all repos — mgba @ 9756f79f044767052280bcc7d7d1225b1f326698

mGBA Game Boy Advance Emulator

src/gba/memory.c (view raw)

   1/* Copyright (c) 2013-2015 Jeffrey Pfau
   2 *
   3 * This Source Code Form is subject to the terms of the Mozilla Public
   4 * License, v. 2.0. If a copy of the MPL was not distributed with this
   5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
   6#include "memory.h"
   7
   8#include "arm/decoder.h"
   9#include "gba/hardware.h"
  10#include "gba/io.h"
  11#include "gba/serialize.h"
  12#include "gba/hle-bios.h"
  13#include "util/math.h"
  14#include "util/memory.h"
  15#include "util/vfs.h"
  16
  17#define IDLE_LOOP_THRESHOLD 10000
  18
  19mLOG_DEFINE_CATEGORY(GBA_MEM, "GBA Memory");
  20
  21static void _pristineCow(struct GBA* gba);
  22static uint32_t _deadbeef[1] = { 0xE710B710 }; // Illegal instruction on both ARM and Thumb
  23
  24static void GBASetActiveRegion(struct ARMCore* cpu, uint32_t region);
  25static void GBAMemoryServiceDMA(struct GBA* gba, int number, struct GBADMA* info);
  26static int32_t GBAMemoryStall(struct ARMCore* cpu, int32_t wait);
  27
  28static const char GBA_BASE_WAITSTATES[16] = { 0, 0, 2, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4 };
  29static const char GBA_BASE_WAITSTATES_32[16] = { 0, 0, 5, 0, 0, 1, 1, 0, 7, 7, 9, 9, 13, 13, 9 };
  30static const char GBA_BASE_WAITSTATES_SEQ[16] = { 0, 0, 2, 0, 0, 0, 0, 0, 2, 2, 4, 4, 8, 8, 4 };
  31static const char GBA_BASE_WAITSTATES_SEQ_32[16] = { 0, 0, 5, 0, 0, 1, 1, 0, 5, 5, 9, 9, 17, 17, 9 };
  32static const char GBA_ROM_WAITSTATES[] = { 4, 3, 2, 8 };
  33static const char GBA_ROM_WAITSTATES_SEQ[] = { 2, 1, 4, 1, 8, 1 };
  34static const int DMA_OFFSET[] = { 1, -1, 0, 1 };
  35
  36void GBAMemoryInit(struct GBA* gba) {
  37	struct ARMCore* cpu = gba->cpu;
  38	cpu->memory.load32 = GBALoad32;
  39	cpu->memory.load16 = GBALoad16;
  40	cpu->memory.load8 = GBALoad8;
  41	cpu->memory.loadMultiple = GBALoadMultiple;
  42	cpu->memory.store32 = GBAStore32;
  43	cpu->memory.store16 = GBAStore16;
  44	cpu->memory.store8 = GBAStore8;
  45	cpu->memory.storeMultiple = GBAStoreMultiple;
  46	cpu->memory.stall = GBAMemoryStall;
  47
  48	gba->memory.bios = (uint32_t*) hleBios;
  49	gba->memory.fullBios = 0;
  50	gba->memory.wram = 0;
  51	gba->memory.iwram = 0;
  52	gba->memory.rom = 0;
  53	gba->memory.romSize = 0;
  54	gba->memory.romMask = 0;
  55	gba->memory.hw.p = gba;
  56
  57	int i;
  58	for (i = 0; i < 16; ++i) {
  59		gba->memory.waitstatesNonseq16[i] = GBA_BASE_WAITSTATES[i];
  60		gba->memory.waitstatesSeq16[i] = GBA_BASE_WAITSTATES_SEQ[i];
  61		gba->memory.waitstatesPrefetchNonseq16[i] = GBA_BASE_WAITSTATES[i];
  62		gba->memory.waitstatesPrefetchSeq16[i] = GBA_BASE_WAITSTATES_SEQ[i];
  63		gba->memory.waitstatesNonseq32[i] = GBA_BASE_WAITSTATES_32[i];
  64		gba->memory.waitstatesSeq32[i] = GBA_BASE_WAITSTATES_SEQ_32[i];
  65		gba->memory.waitstatesPrefetchNonseq32[i] = GBA_BASE_WAITSTATES_32[i];
  66		gba->memory.waitstatesPrefetchSeq32[i] = GBA_BASE_WAITSTATES_SEQ_32[i];
  67	}
  68	for (; i < 256; ++i) {
  69		gba->memory.waitstatesNonseq16[i] = 0;
  70		gba->memory.waitstatesSeq16[i] = 0;
  71		gba->memory.waitstatesNonseq32[i] = 0;
  72		gba->memory.waitstatesSeq32[i] = 0;
  73	}
  74
  75	gba->memory.activeRegion = -1;
  76	cpu->memory.activeRegion = 0;
  77	cpu->memory.activeMask = 0;
  78	cpu->memory.setActiveRegion = GBASetActiveRegion;
  79	cpu->memory.activeSeqCycles32 = 0;
  80	cpu->memory.activeSeqCycles16 = 0;
  81	cpu->memory.activeNonseqCycles32 = 0;
  82	cpu->memory.activeNonseqCycles16 = 0;
  83	gba->memory.biosPrefetch = 0;
  84	gba->memory.mirroring = false;
  85
  86	GBAVFameInit(&gba->memory.vfame);
  87}
  88
  89void GBAMemoryDeinit(struct GBA* gba) {
  90	mappedMemoryFree(gba->memory.wram, SIZE_WORKING_RAM);
  91	mappedMemoryFree(gba->memory.iwram, SIZE_WORKING_IRAM);
  92	if (gba->memory.rom) {
  93		mappedMemoryFree(gba->memory.rom, gba->memory.romSize);
  94	}
  95	GBASavedataUnmask(&gba->memory.savedata);
  96	GBASavedataDeinit(&gba->memory.savedata);
  97	if (gba->memory.savedata.realVf) {
  98		gba->memory.savedata.realVf->close(gba->memory.savedata.realVf);
  99	}
 100}
 101
 102void GBAMemoryReset(struct GBA* gba) {
 103	if (gba->memory.wram) {
 104		mappedMemoryFree(gba->memory.wram, SIZE_WORKING_RAM);
 105	}
 106	gba->memory.wram = anonymousMemoryMap(SIZE_WORKING_RAM);
 107	if (gba->pristineRom && !gba->memory.rom) {
 108		// Multiboot
 109		memcpy(gba->memory.wram, gba->pristineRom, gba->pristineRomSize);
 110	}
 111
 112	if (gba->memory.iwram) {
 113		mappedMemoryFree(gba->memory.iwram, SIZE_WORKING_IRAM);
 114	}
 115	gba->memory.iwram = anonymousMemoryMap(SIZE_WORKING_IRAM);
 116
 117	memset(gba->memory.io, 0, sizeof(gba->memory.io));
 118	memset(gba->memory.dma, 0, sizeof(gba->memory.dma));
 119	int i;
 120	for (i = 0; i < 4; ++i) {
 121		gba->memory.dma[i].count = 0x4000;
 122		gba->memory.dma[i].nextEvent = INT_MAX;
 123	}
 124	gba->memory.dma[3].count = 0x10000;
 125	gba->memory.activeDMA = -1;
 126	gba->memory.nextDMA = INT_MAX;
 127	gba->memory.eventDiff = 0;
 128
 129	gba->memory.prefetch = false;
 130	gba->memory.lastPrefetchedPc = 0;
 131
 132	if (!gba->memory.wram || !gba->memory.iwram) {
 133		GBAMemoryDeinit(gba);
 134		mLOG(GBA_MEM, FATAL, "Could not map memory");
 135	}
 136}
 137
 138static void _analyzeForIdleLoop(struct GBA* gba, struct ARMCore* cpu, uint32_t address) {
 139	struct ARMInstructionInfo info;
 140	uint32_t nextAddress = address;
 141	memset(gba->taintedRegisters, 0, sizeof(gba->taintedRegisters));
 142	if (cpu->executionMode == MODE_THUMB) {
 143		while (true) {
 144			uint16_t opcode;
 145			LOAD_16(opcode, nextAddress & cpu->memory.activeMask, cpu->memory.activeRegion);
 146			ARMDecodeThumb(opcode, &info);
 147			switch (info.branchType) {
 148			case ARM_BRANCH_NONE:
 149				if (info.operandFormat & ARM_OPERAND_MEMORY_2) {
 150					if (info.mnemonic == ARM_MN_STR || gba->taintedRegisters[info.memory.baseReg]) {
 151						gba->idleDetectionStep = -1;
 152						return;
 153					}
 154					uint32_t loadAddress = gba->cachedRegisters[info.memory.baseReg];
 155					uint32_t offset = 0;
 156					if (info.memory.format & ARM_MEMORY_IMMEDIATE_OFFSET) {
 157						offset = info.memory.offset.immediate;
 158					} else if (info.memory.format & ARM_MEMORY_REGISTER_OFFSET) {
 159						int reg = info.memory.offset.reg;
 160						if (gba->cachedRegisters[reg]) {
 161							gba->idleDetectionStep = -1;
 162							return;
 163						}
 164						offset = gba->cachedRegisters[reg];
 165					}
 166					if (info.memory.format & ARM_MEMORY_OFFSET_SUBTRACT) {
 167						loadAddress -= offset;
 168					} else {
 169						loadAddress += offset;
 170					}
 171					if ((loadAddress >> BASE_OFFSET) == REGION_IO && !GBAIOIsReadConstant(loadAddress)) {
 172						gba->idleDetectionStep = -1;
 173						return;
 174					}
 175					if ((loadAddress >> BASE_OFFSET) < REGION_CART0 || (loadAddress >> BASE_OFFSET) > REGION_CART2_EX) {
 176						gba->taintedRegisters[info.op1.reg] = true;
 177					} else {
 178						switch (info.memory.width) {
 179						case 1:
 180							gba->cachedRegisters[info.op1.reg] = GBALoad8(cpu, loadAddress, 0);
 181							break;
 182						case 2:
 183							gba->cachedRegisters[info.op1.reg] = GBALoad16(cpu, loadAddress, 0);
 184							break;
 185						case 4:
 186							gba->cachedRegisters[info.op1.reg] = GBALoad32(cpu, loadAddress, 0);
 187							break;
 188						}
 189					}
 190				} else if (info.operandFormat & ARM_OPERAND_AFFECTED_1) {
 191					gba->taintedRegisters[info.op1.reg] = true;
 192				}
 193				nextAddress += WORD_SIZE_THUMB;
 194				break;
 195			case ARM_BRANCH:
 196				if ((uint32_t) info.op1.immediate + nextAddress + WORD_SIZE_THUMB * 2 == address) {
 197					gba->idleLoop = address;
 198					gba->idleOptimization = IDLE_LOOP_REMOVE;
 199				}
 200				gba->idleDetectionStep = -1;
 201				return;
 202			default:
 203				gba->idleDetectionStep = -1;
 204				return;
 205			}
 206		}
 207	} else {
 208		gba->idleDetectionStep = -1;
 209	}
 210}
 211
 212static void GBASetActiveRegion(struct ARMCore* cpu, uint32_t address) {
 213	struct GBA* gba = (struct GBA*) cpu->master;
 214	struct GBAMemory* memory = &gba->memory;
 215
 216	int newRegion = address >> BASE_OFFSET;
 217	if (gba->idleOptimization >= IDLE_LOOP_REMOVE && memory->activeRegion != REGION_BIOS) {
 218		if (address == gba->idleLoop) {
 219			if (gba->haltPending) {
 220				gba->haltPending = false;
 221				GBAHalt(gba);
 222			} else {
 223				gba->haltPending = true;
 224			}
 225		} else if (gba->idleOptimization >= IDLE_LOOP_DETECT && newRegion == memory->activeRegion) {
 226			if (address == gba->lastJump) {
 227				switch (gba->idleDetectionStep) {
 228				case 0:
 229					memcpy(gba->cachedRegisters, cpu->gprs, sizeof(gba->cachedRegisters));
 230					++gba->idleDetectionStep;
 231					break;
 232				case 1:
 233					if (memcmp(gba->cachedRegisters, cpu->gprs, sizeof(gba->cachedRegisters))) {
 234						gba->idleDetectionStep = -1;
 235						++gba->idleDetectionFailures;
 236						if (gba->idleDetectionFailures > IDLE_LOOP_THRESHOLD) {
 237							gba->idleOptimization = IDLE_LOOP_IGNORE;
 238						}
 239						break;
 240					}
 241					_analyzeForIdleLoop(gba, cpu, address);
 242					break;
 243				}
 244			} else {
 245				gba->idleDetectionStep = 0;
 246			}
 247		}
 248	}
 249
 250	gba->lastJump = address;
 251	memory->lastPrefetchedPc = 0;
 252	if (newRegion == memory->activeRegion) {
 253		if (newRegion < REGION_CART0 || (address & (SIZE_CART0 - 1)) < memory->romSize) {
 254			return;
 255		}
 256		if (memory->mirroring && (address & memory->romMask) < memory->romSize) {
 257			return;
 258		}
 259	}
 260
 261	if (memory->activeRegion == REGION_BIOS) {
 262		memory->biosPrefetch = cpu->prefetch[1];
 263	}
 264	memory->activeRegion = newRegion;
 265	switch (newRegion) {
 266	case REGION_BIOS:
 267		cpu->memory.activeRegion = memory->bios;
 268		cpu->memory.activeMask = SIZE_BIOS - 1;
 269		break;
 270	case REGION_WORKING_RAM:
 271		cpu->memory.activeRegion = memory->wram;
 272		cpu->memory.activeMask = SIZE_WORKING_RAM - 1;
 273		break;
 274	case REGION_WORKING_IRAM:
 275		cpu->memory.activeRegion = memory->iwram;
 276		cpu->memory.activeMask = SIZE_WORKING_IRAM - 1;
 277		break;
 278	case REGION_PALETTE_RAM:
 279		cpu->memory.activeRegion = (uint32_t*) gba->video.palette;
 280		cpu->memory.activeMask = SIZE_PALETTE_RAM - 1;
 281		break;
 282	case REGION_VRAM:
 283		if (address & 0x10000) {
 284			cpu->memory.activeRegion = (uint32_t*) &gba->video.renderer->vram[0x8000];
 285			cpu->memory.activeMask = 0x00007FFF;
 286		} else {
 287			cpu->memory.activeRegion = (uint32_t*) gba->video.renderer->vram;
 288			cpu->memory.activeMask = 0x0000FFFF;
 289		}
 290		break;
 291	case REGION_OAM:
 292		cpu->memory.activeRegion = (uint32_t*) gba->video.oam.raw;
 293		cpu->memory.activeMask = SIZE_OAM - 1;
 294		break;
 295	case REGION_CART0:
 296	case REGION_CART0_EX:
 297	case REGION_CART1:
 298	case REGION_CART1_EX:
 299	case REGION_CART2:
 300	case REGION_CART2_EX:
 301		cpu->memory.activeRegion = memory->rom;
 302		cpu->memory.activeMask = memory->romMask;
 303		if ((address & (SIZE_CART0 - 1)) < memory->romSize) {
 304			break;
 305		}
 306	// Fall through
 307	default:
 308		memory->activeRegion = -1;
 309		cpu->memory.activeRegion = _deadbeef;
 310		cpu->memory.activeMask = 0;
 311		if (gba->yankedRomSize || !gba->hardCrash) {
 312			mLOG(GBA_MEM, GAME_ERROR, "Jumped to invalid address: %08X", address);
 313		} else {
 314			mLOG(GBA_MEM, FATAL, "Jumped to invalid address: %08X", address);
 315		}
 316		return;
 317	}
 318	cpu->memory.activeSeqCycles32 = memory->waitstatesSeq32[memory->activeRegion];
 319	cpu->memory.activeSeqCycles16 = memory->waitstatesSeq16[memory->activeRegion];
 320	cpu->memory.activeNonseqCycles32 = memory->waitstatesNonseq32[memory->activeRegion];
 321	cpu->memory.activeNonseqCycles16 = memory->waitstatesNonseq16[memory->activeRegion];
 322}
 323
 324#define LOAD_BAD \
 325	if (gba->performingDMA) { \
 326		value = gba->bus; \
 327	} else { \
 328		value = cpu->prefetch[1]; \
 329		if (cpu->executionMode == MODE_THUMB) { \
 330			/* http://ngemu.com/threads/gba-open-bus.170809/ */ \
 331			switch (cpu->gprs[ARM_PC] >> BASE_OFFSET) { \
 332			case REGION_BIOS: \
 333			case REGION_OAM: \
 334				/* This isn't right half the time, but we don't have $+6 handy */ \
 335				value <<= 16; \
 336				value |= cpu->prefetch[0]; \
 337				break; \
 338			case REGION_WORKING_IRAM: \
 339				/* This doesn't handle prefetch clobbering */ \
 340				if (cpu->gprs[ARM_PC] & 2) { \
 341					value |= cpu->prefetch[0] << 16; \
 342				} else { \
 343					value <<= 16; \
 344					value |= cpu->prefetch[0]; \
 345				} \
 346			default: \
 347				value |= value << 16; \
 348			} \
 349		} \
 350	}
 351
 352#define LOAD_BIOS \
 353	if (address < SIZE_BIOS) { \
 354		if (memory->activeRegion == REGION_BIOS) { \
 355			LOAD_32(value, address & -4, memory->bios); \
 356		} else { \
 357			mLOG(GBA_MEM, GAME_ERROR, "Bad BIOS Load32: 0x%08X", address); \
 358			value = memory->biosPrefetch; \
 359		} \
 360	} else { \
 361		mLOG(GBA_MEM, GAME_ERROR, "Bad memory Load32: 0x%08X", address); \
 362		LOAD_BAD; \
 363	}
 364
 365#define LOAD_WORKING_RAM \
 366	LOAD_32(value, address & (SIZE_WORKING_RAM - 4), memory->wram); \
 367	wait += waitstatesRegion[REGION_WORKING_RAM];
 368
 369#define LOAD_WORKING_IRAM LOAD_32(value, address & (SIZE_WORKING_IRAM - 4), memory->iwram);
 370#define LOAD_IO value = GBAIORead(gba, address & OFFSET_MASK & ~2) | (GBAIORead(gba, (address & OFFSET_MASK) | 2) << 16);
 371
 372#define LOAD_PALETTE_RAM \
 373	LOAD_32(value, address & (SIZE_PALETTE_RAM - 4), gba->video.palette); \
 374	wait += waitstatesRegion[REGION_PALETTE_RAM];
 375
 376#define LOAD_VRAM \
 377	if ((address & 0x0001FFFF) < SIZE_VRAM) { \
 378		LOAD_32(value, address & 0x0001FFFC, gba->video.renderer->vram); \
 379	} else { \
 380		LOAD_32(value, address & 0x00017FFC, gba->video.renderer->vram); \
 381	} \
 382	wait += waitstatesRegion[REGION_VRAM];
 383
 384#define LOAD_OAM LOAD_32(value, address & (SIZE_OAM - 4), gba->video.oam.raw);
 385
 386#define LOAD_CART \
 387	wait += waitstatesRegion[address >> BASE_OFFSET]; \
 388	if ((address & (SIZE_CART0 - 1)) < memory->romSize) { \
 389		LOAD_32(value, address & (SIZE_CART0 - 4), memory->rom); \
 390	} else if (memory->mirroring && (address & memory->romMask) < memory->romSize) { \
 391		LOAD_32(value, address & memory->romMask & -4, memory->rom); \
 392	} else if (memory->vfame.cartType) { \
 393		value = GBAVFameGetPatternValue(address, 32); \
 394	} else { \
 395		mLOG(GBA_MEM, GAME_ERROR, "Out of bounds ROM Load32: 0x%08X", address); \
 396		value = ((address & ~3) >> 1) & 0xFFFF; \
 397		value |= (((address & ~3) + 2) >> 1) << 16; \
 398	}
 399
 400#define LOAD_SRAM \
 401	wait = memory->waitstatesNonseq16[address >> BASE_OFFSET]; \
 402	value = GBALoad8(cpu, address, 0); \
 403	value |= value << 8; \
 404	value |= value << 16;
 405
 406uint32_t GBALoadBad(struct ARMCore* cpu) {
 407	struct GBA* gba = (struct GBA*) cpu->master;
 408	uint32_t value = 0;
 409	LOAD_BAD;
 410	return value;
 411}
 412
 413uint32_t GBALoad32(struct ARMCore* cpu, uint32_t address, int* cycleCounter) {
 414	struct GBA* gba = (struct GBA*) cpu->master;
 415	struct GBAMemory* memory = &gba->memory;
 416	uint32_t value = 0;
 417	int wait = 0;
 418	char* waitstatesRegion = memory->waitstatesNonseq32;
 419
 420	switch (address >> BASE_OFFSET) {
 421	case REGION_BIOS:
 422		LOAD_BIOS;
 423		break;
 424	case REGION_WORKING_RAM:
 425		LOAD_WORKING_RAM;
 426		break;
 427	case REGION_WORKING_IRAM:
 428		LOAD_WORKING_IRAM;
 429		break;
 430	case REGION_IO:
 431		LOAD_IO;
 432		break;
 433	case REGION_PALETTE_RAM:
 434		LOAD_PALETTE_RAM;
 435		break;
 436	case REGION_VRAM:
 437		LOAD_VRAM;
 438		break;
 439	case REGION_OAM:
 440		LOAD_OAM;
 441		break;
 442	case REGION_CART0:
 443	case REGION_CART0_EX:
 444	case REGION_CART1:
 445	case REGION_CART1_EX:
 446	case REGION_CART2:
 447	case REGION_CART2_EX:
 448		LOAD_CART;
 449		break;
 450	case REGION_CART_SRAM:
 451	case REGION_CART_SRAM_MIRROR:
 452		LOAD_SRAM;
 453		break;
 454	default:
 455		mLOG(GBA_MEM, GAME_ERROR, "Bad memory Load32: 0x%08X", address);
 456		LOAD_BAD;
 457		break;
 458	}
 459
 460	if (cycleCounter) {
 461		wait += 2;
 462		if (address >> BASE_OFFSET < REGION_CART0) {
 463			wait = GBAMemoryStall(cpu, wait);
 464		}
 465		*cycleCounter += wait;
 466	}
 467	// Unaligned 32-bit loads are "rotated" so they make some semblance of sense
 468	int rotate = (address & 3) << 3;
 469	return ROR(value, rotate);
 470}
 471
 472uint32_t GBALoad16(struct ARMCore* cpu, uint32_t address, int* cycleCounter) {
 473	struct GBA* gba = (struct GBA*) cpu->master;
 474	struct GBAMemory* memory = &gba->memory;
 475	uint32_t value = 0;
 476	int wait = 0;
 477
 478	switch (address >> BASE_OFFSET) {
 479	case REGION_BIOS:
 480		if (address < SIZE_BIOS) {
 481			if (memory->activeRegion == REGION_BIOS) {
 482				LOAD_16(value, address & -2, memory->bios);
 483			} else {
 484				mLOG(GBA_MEM, GAME_ERROR, "Bad BIOS Load16: 0x%08X", address);
 485				value = (memory->biosPrefetch >> ((address & 2) * 8)) & 0xFFFF;
 486			}
 487		} else {
 488			mLOG(GBA_MEM, GAME_ERROR, "Bad memory Load16: 0x%08X", address);
 489			LOAD_BAD;
 490			value = (value >> ((address & 2) * 8)) & 0xFFFF;
 491		}
 492		break;
 493	case REGION_WORKING_RAM:
 494		LOAD_16(value, address & (SIZE_WORKING_RAM - 2), memory->wram);
 495		wait = memory->waitstatesNonseq16[REGION_WORKING_RAM];
 496		break;
 497	case REGION_WORKING_IRAM:
 498		LOAD_16(value, address & (SIZE_WORKING_IRAM - 2), memory->iwram);
 499		break;
 500	case REGION_IO:
 501		value = GBAIORead(gba, address & (OFFSET_MASK - 1));
 502		break;
 503	case REGION_PALETTE_RAM:
 504		LOAD_16(value, address & (SIZE_PALETTE_RAM - 2), gba->video.palette);
 505		break;
 506	case REGION_VRAM:
 507		if ((address & 0x0001FFFF) < SIZE_VRAM) {
 508			LOAD_16(value, address & 0x0001FFFE, gba->video.renderer->vram);
 509		} else {
 510			LOAD_16(value, address & 0x00017FFE, gba->video.renderer->vram);
 511		}
 512		break;
 513	case REGION_OAM:
 514		LOAD_16(value, address & (SIZE_OAM - 2), gba->video.oam.raw);
 515		break;
 516	case REGION_CART0:
 517	case REGION_CART0_EX:
 518	case REGION_CART1:
 519	case REGION_CART1_EX:
 520	case REGION_CART2:
 521		wait = memory->waitstatesNonseq16[address >> BASE_OFFSET];
 522		if ((address & (SIZE_CART0 - 1)) < memory->romSize) {
 523			LOAD_16(value, address & (SIZE_CART0 - 2), memory->rom);
 524		} else if (memory->mirroring && (address & memory->romMask) < memory->romSize) {
 525			LOAD_16(value, address & memory->romMask, memory->rom);
 526		} else if (memory->vfame.cartType) {
 527			value = GBAVFameGetPatternValue(address, 16);
 528		} else {
 529			mLOG(GBA_MEM, GAME_ERROR, "Out of bounds ROM Load16: 0x%08X", address);
 530			value = (address >> 1) & 0xFFFF;
 531		}
 532		break;
 533	case REGION_CART2_EX:
 534		wait = memory->waitstatesNonseq16[address >> BASE_OFFSET];
 535		if (memory->savedata.type == SAVEDATA_EEPROM) {
 536			value = GBASavedataReadEEPROM(&memory->savedata);
 537		} else if ((address & (SIZE_CART0 - 1)) < memory->romSize) {
 538			LOAD_16(value, address & (SIZE_CART0 - 2), memory->rom);
 539		} else if (memory->mirroring && (address & memory->romMask) < memory->romSize) {
 540			LOAD_16(value, address & memory->romMask, memory->rom);
 541		} else if (memory->vfame.cartType) {
 542			value = GBAVFameGetPatternValue(address, 16);
 543		} else {
 544			mLOG(GBA_MEM, GAME_ERROR, "Out of bounds ROM Load16: 0x%08X", address);
 545			value = (address >> 1) & 0xFFFF;
 546		}
 547		break;
 548	case REGION_CART_SRAM:
 549	case REGION_CART_SRAM_MIRROR:
 550		wait = memory->waitstatesNonseq16[address >> BASE_OFFSET];
 551		value = GBALoad8(cpu, address, 0);
 552		value |= value << 8;
 553		break;
 554	default:
 555		mLOG(GBA_MEM, GAME_ERROR, "Bad memory Load16: 0x%08X", address);
 556		LOAD_BAD;
 557		value = (value >> ((address & 2) * 8)) & 0xFFFF;
 558		break;
 559	}
 560
 561	if (cycleCounter) {
 562		wait += 2;
 563		if (address >> BASE_OFFSET < REGION_CART0) {
 564			wait = GBAMemoryStall(cpu, wait);
 565		}
 566		*cycleCounter += wait;
 567	}
 568	// Unaligned 16-bit loads are "unpredictable", but the GBA rotates them, so we have to, too.
 569	int rotate = (address & 1) << 3;
 570	return ROR(value, rotate);
 571}
 572
 573uint32_t GBALoad8(struct ARMCore* cpu, uint32_t address, int* cycleCounter) {
 574	struct GBA* gba = (struct GBA*) cpu->master;
 575	struct GBAMemory* memory = &gba->memory;
 576	uint32_t value = 0;
 577	int wait = 0;
 578
 579	switch (address >> BASE_OFFSET) {
 580	case REGION_BIOS:
 581		if (address < SIZE_BIOS) {
 582			if (memory->activeRegion == REGION_BIOS) {
 583				value = ((uint8_t*) memory->bios)[address];
 584			} else {
 585				mLOG(GBA_MEM, GAME_ERROR, "Bad BIOS Load8: 0x%08X", address);
 586				value = (memory->biosPrefetch >> ((address & 3) * 8)) & 0xFF;
 587			}
 588		} else {
 589			mLOG(GBA_MEM, GAME_ERROR, "Bad memory Load8: 0x%08x", address);
 590			LOAD_BAD;
 591			value = (value >> ((address & 3) * 8)) & 0xFF;
 592		}
 593		break;
 594	case REGION_WORKING_RAM:
 595		value = ((uint8_t*) memory->wram)[address & (SIZE_WORKING_RAM - 1)];
 596		wait = memory->waitstatesNonseq16[REGION_WORKING_RAM];
 597		break;
 598	case REGION_WORKING_IRAM:
 599		value = ((uint8_t*) memory->iwram)[address & (SIZE_WORKING_IRAM - 1)];
 600		break;
 601	case REGION_IO:
 602		value = (GBAIORead(gba, address & 0xFFFE) >> ((address & 0x0001) << 3)) & 0xFF;
 603		break;
 604	case REGION_PALETTE_RAM:
 605		value = ((uint8_t*) gba->video.palette)[address & (SIZE_PALETTE_RAM - 1)];
 606		break;
 607	case REGION_VRAM:
 608		if ((address & 0x0001FFFF) < SIZE_VRAM) {
 609			value = ((uint8_t*) gba->video.renderer->vram)[address & 0x0001FFFF];
 610		} else {
 611			value = ((uint8_t*) gba->video.renderer->vram)[address & 0x00017FFF];
 612		}
 613		break;
 614	case REGION_OAM:
 615		value = ((uint8_t*) gba->video.oam.raw)[address & (SIZE_OAM - 1)];
 616		break;
 617	case REGION_CART0:
 618	case REGION_CART0_EX:
 619	case REGION_CART1:
 620	case REGION_CART1_EX:
 621	case REGION_CART2:
 622	case REGION_CART2_EX:
 623		wait = memory->waitstatesNonseq16[address >> BASE_OFFSET];
 624		if ((address & (SIZE_CART0 - 1)) < memory->romSize) {
 625			value = ((uint8_t*) memory->rom)[address & (SIZE_CART0 - 1)];
 626		} else if (memory->mirroring && (address & memory->romMask) < memory->romSize) {
 627			value = ((uint8_t*) memory->rom)[address & memory->romMask];
 628		} else if (memory->vfame.cartType) {
 629			value = GBAVFameGetPatternValue(address, 8);
 630		} else {
 631			mLOG(GBA_MEM, GAME_ERROR, "Out of bounds ROM Load8: 0x%08X", address);
 632			value = (address >> 1) & 0xFF;
 633		}
 634		break;
 635	case REGION_CART_SRAM:
 636	case REGION_CART_SRAM_MIRROR:
 637		wait = memory->waitstatesNonseq16[address >> BASE_OFFSET];
 638		if (memory->savedata.type == SAVEDATA_AUTODETECT) {
 639			mLOG(GBA_MEM, INFO, "Detected SRAM savegame");
 640			GBASavedataInitSRAM(&memory->savedata);
 641		}
 642		if (gba->performingDMA == 1) {
 643			break;
 644		}
 645		if (memory->savedata.type == SAVEDATA_SRAM) {
 646			value = memory->savedata.data[address & (SIZE_CART_SRAM - 1)];
 647		} else if (memory->savedata.type == SAVEDATA_FLASH512 || memory->savedata.type == SAVEDATA_FLASH1M) {
 648			value = GBASavedataReadFlash(&memory->savedata, address);
 649		} else if (memory->hw.devices & HW_TILT) {
 650			value = GBAHardwareTiltRead(&memory->hw, address & OFFSET_MASK);
 651		} else {
 652			mLOG(GBA_MEM, GAME_ERROR, "Reading from non-existent SRAM: 0x%08X", address);
 653			value = 0xFF;
 654		}
 655		value &= 0xFF;
 656		break;
 657	default:
 658		mLOG(GBA_MEM, GAME_ERROR, "Bad memory Load8: 0x%08x", address);
 659		LOAD_BAD;
 660		value = (value >> ((address & 3) * 8)) & 0xFF;
 661		break;
 662	}
 663
 664	if (cycleCounter) {
 665		wait += 2;
 666		if (address >> BASE_OFFSET < REGION_CART0) {
 667			wait = GBAMemoryStall(cpu, wait);
 668		}
 669		*cycleCounter += wait;
 670	}
 671	return value;
 672}
 673
 674#define STORE_WORKING_RAM \
 675	STORE_32(value, address & (SIZE_WORKING_RAM - 4), memory->wram); \
 676	wait += waitstatesRegion[REGION_WORKING_RAM];
 677
 678#define STORE_WORKING_IRAM \
 679	STORE_32(value, address & (SIZE_WORKING_IRAM - 4), memory->iwram);
 680
 681#define STORE_IO \
 682	GBAIOWrite32(gba, address & (OFFSET_MASK - 3), value);
 683
 684#define STORE_PALETTE_RAM \
 685	STORE_32(value, address & (SIZE_PALETTE_RAM - 4), gba->video.palette); \
 686	gba->video.renderer->writePalette(gba->video.renderer, (address & (SIZE_PALETTE_RAM - 4)) + 2, value >> 16); \
 687	wait += waitstatesRegion[REGION_PALETTE_RAM]; \
 688	gba->video.renderer->writePalette(gba->video.renderer, address & (SIZE_PALETTE_RAM - 4), value);
 689
 690#define STORE_VRAM \
 691	if ((address & 0x0001FFFF) < SIZE_VRAM) { \
 692		STORE_32(value, address & 0x0001FFFC, gba->video.renderer->vram); \
 693		gba->video.renderer->writeVRAM(gba->video.renderer, (address & 0x0001FFFC) + 2); \
 694		gba->video.renderer->writeVRAM(gba->video.renderer, (address & 0x0001FFFC)); \
 695	} else { \
 696		STORE_32(value, address & 0x00017FFC, gba->video.renderer->vram); \
 697		gba->video.renderer->writeVRAM(gba->video.renderer, (address & 0x00017FFC) + 2); \
 698		gba->video.renderer->writeVRAM(gba->video.renderer, (address & 0x00017FFC)); \
 699	} \
 700	wait += waitstatesRegion[REGION_VRAM];
 701
 702#define STORE_OAM \
 703	STORE_32(value, address & (SIZE_OAM - 4), gba->video.oam.raw); \
 704	gba->video.renderer->writeOAM(gba->video.renderer, (address & (SIZE_OAM - 4)) >> 1); \
 705	gba->video.renderer->writeOAM(gba->video.renderer, ((address & (SIZE_OAM - 4)) >> 1) + 1);
 706
 707#define STORE_CART \
 708	wait += waitstatesRegion[address >> BASE_OFFSET]; \
 709	mLOG(GBA_MEM, STUB, "Unimplemented memory Store32: 0x%08X", address);
 710
 711#define STORE_SRAM \
 712	if (address & 0x3) { \
 713		mLOG(GBA_MEM, GAME_ERROR, "Unaligned SRAM Store32: 0x%08X", address); \
 714		value = 0; \
 715	} \
 716	GBAStore8(cpu, address & ~0x3, value, cycleCounter); \
 717	GBAStore8(cpu, (address & ~0x3) | 1, value, cycleCounter); \
 718	GBAStore8(cpu, (address & ~0x3) | 2, value, cycleCounter); \
 719	GBAStore8(cpu, (address & ~0x3) | 3, value, cycleCounter);
 720
 721#define STORE_BAD \
 722	mLOG(GBA_MEM, GAME_ERROR, "Bad memory Store32: 0x%08X", address);
 723
 724void GBAStore32(struct ARMCore* cpu, uint32_t address, int32_t value, int* cycleCounter) {
 725	struct GBA* gba = (struct GBA*) cpu->master;
 726	struct GBAMemory* memory = &gba->memory;
 727	int wait = 0;
 728	char* waitstatesRegion = memory->waitstatesNonseq32;
 729
 730	switch (address >> BASE_OFFSET) {
 731	case REGION_WORKING_RAM:
 732		STORE_WORKING_RAM;
 733		break;
 734	case REGION_WORKING_IRAM:
 735		STORE_WORKING_IRAM
 736		break;
 737	case REGION_IO:
 738		STORE_IO;
 739		break;
 740	case REGION_PALETTE_RAM:
 741		STORE_PALETTE_RAM;
 742		break;
 743	case REGION_VRAM:
 744		STORE_VRAM;
 745		break;
 746	case REGION_OAM:
 747		STORE_OAM;
 748		break;
 749	case REGION_CART0:
 750	case REGION_CART0_EX:
 751	case REGION_CART1:
 752	case REGION_CART1_EX:
 753	case REGION_CART2:
 754	case REGION_CART2_EX:
 755		STORE_CART;
 756		break;
 757	case REGION_CART_SRAM:
 758	case REGION_CART_SRAM_MIRROR:
 759		STORE_SRAM;
 760		break;
 761	default:
 762		STORE_BAD;
 763		break;
 764	}
 765
 766	if (cycleCounter) {
 767		++wait;
 768		if (address >> BASE_OFFSET < REGION_CART0) {
 769			wait = GBAMemoryStall(cpu, wait);
 770		}
 771		*cycleCounter += wait;
 772	}
 773}
 774
 775void GBAStore16(struct ARMCore* cpu, uint32_t address, int16_t value, int* cycleCounter) {
 776	struct GBA* gba = (struct GBA*) cpu->master;
 777	struct GBAMemory* memory = &gba->memory;
 778	int wait = 0;
 779
 780	switch (address >> BASE_OFFSET) {
 781	case REGION_WORKING_RAM:
 782		STORE_16(value, address & (SIZE_WORKING_RAM - 2), memory->wram);
 783		wait = memory->waitstatesNonseq16[REGION_WORKING_RAM];
 784		break;
 785	case REGION_WORKING_IRAM:
 786		STORE_16(value, address & (SIZE_WORKING_IRAM - 2), memory->iwram);
 787		break;
 788	case REGION_IO:
 789		GBAIOWrite(gba, address & (OFFSET_MASK - 1), value);
 790		break;
 791	case REGION_PALETTE_RAM:
 792		STORE_16(value, address & (SIZE_PALETTE_RAM - 2), gba->video.palette);
 793		gba->video.renderer->writePalette(gba->video.renderer, address & (SIZE_PALETTE_RAM - 2), value);
 794		break;
 795	case REGION_VRAM:
 796		if ((address & 0x0001FFFF) < SIZE_VRAM) {
 797			STORE_16(value, address & 0x0001FFFE, gba->video.renderer->vram);
 798			gba->video.renderer->writeVRAM(gba->video.renderer, address & 0x0001FFFE);
 799		} else {
 800			STORE_16(value, address & 0x00017FFE, gba->video.renderer->vram);
 801			gba->video.renderer->writeVRAM(gba->video.renderer, address & 0x00017FFE);
 802		}
 803		break;
 804	case REGION_OAM:
 805		STORE_16(value, address & (SIZE_OAM - 2), gba->video.oam.raw);
 806		gba->video.renderer->writeOAM(gba->video.renderer, (address & (SIZE_OAM - 2)) >> 1);
 807		break;
 808	case REGION_CART0:
 809		if (memory->hw.devices != HW_NONE && IS_GPIO_REGISTER(address & 0xFFFFFE)) {
 810			uint32_t reg = address & 0xFFFFFE;
 811			GBAHardwareGPIOWrite(&memory->hw, reg, value);
 812		} else {
 813			mLOG(GBA_MEM, GAME_ERROR, "Bad cartridge Store16: 0x%08X", address);
 814		}
 815		break;
 816	case REGION_CART2_EX:
 817		if (memory->savedata.type == SAVEDATA_AUTODETECT) {
 818			mLOG(GBA_MEM, INFO, "Detected EEPROM savegame");
 819			GBASavedataInitEEPROM(&memory->savedata, gba->realisticTiming);
 820		}
 821		GBASavedataWriteEEPROM(&memory->savedata, value, 1);
 822		break;
 823	case REGION_CART_SRAM:
 824	case REGION_CART_SRAM_MIRROR:
 825		GBAStore8(cpu, (address & ~0x1), value, cycleCounter);
 826		GBAStore8(cpu, (address & ~0x1) | 1, value, cycleCounter);
 827		break;
 828	default:
 829		mLOG(GBA_MEM, GAME_ERROR, "Bad memory Store16: 0x%08X", address);
 830		break;
 831	}
 832
 833	if (cycleCounter) {
 834		++wait;
 835		if (address >> BASE_OFFSET < REGION_CART0) {
 836			wait = GBAMemoryStall(cpu, wait);
 837		}
 838		*cycleCounter += wait;
 839	}
 840}
 841
 842void GBAStore8(struct ARMCore* cpu, uint32_t address, int8_t value, int* cycleCounter) {
 843	struct GBA* gba = (struct GBA*) cpu->master;
 844	struct GBAMemory* memory = &gba->memory;
 845	int wait = 0;
 846
 847	switch (address >> BASE_OFFSET) {
 848	case REGION_WORKING_RAM:
 849		((int8_t*) memory->wram)[address & (SIZE_WORKING_RAM - 1)] = value;
 850		wait = memory->waitstatesNonseq16[REGION_WORKING_RAM];
 851		break;
 852	case REGION_WORKING_IRAM:
 853		((int8_t*) memory->iwram)[address & (SIZE_WORKING_IRAM - 1)] = value;
 854		break;
 855	case REGION_IO:
 856		GBAIOWrite8(gba, address & OFFSET_MASK, value);
 857		break;
 858	case REGION_PALETTE_RAM:
 859		GBAStore16(cpu, address & ~1, ((uint8_t) value) | ((uint8_t) value << 8), cycleCounter);
 860		break;
 861	case REGION_VRAM:
 862		if ((address & 0x0001FFFF) >= ((GBARegisterDISPCNTGetMode(gba->memory.io[REG_DISPCNT >> 1]) == 4) ? 0x00014000 : 0x00010000)) {
 863			// TODO: check BG mode
 864			mLOG(GBA_MEM, GAME_ERROR, "Cannot Store8 to OBJ: 0x%08X", address);
 865			break;
 866		}
 867		gba->video.renderer->vram[(address & 0x1FFFE) >> 1] = ((uint8_t) value) | (value << 8);
 868		gba->video.renderer->writeVRAM(gba->video.renderer, address & 0x0001FFFE);
 869		break;
 870	case REGION_OAM:
 871		mLOG(GBA_MEM, GAME_ERROR, "Cannot Store8 to OAM: 0x%08X", address);
 872		break;
 873	case REGION_CART0:
 874		mLOG(GBA_MEM, STUB, "Unimplemented memory Store8: 0x%08X", address);
 875		break;
 876	case REGION_CART_SRAM:
 877	case REGION_CART_SRAM_MIRROR:
 878		if (memory->savedata.type == SAVEDATA_AUTODETECT) {
 879			if (address == SAVEDATA_FLASH_BASE) {
 880				mLOG(GBA_MEM, INFO, "Detected Flash savegame");
 881				GBASavedataInitFlash(&memory->savedata, gba->realisticTiming);
 882			} else {
 883				mLOG(GBA_MEM, INFO, "Detected SRAM savegame");
 884				GBASavedataInitSRAM(&memory->savedata);
 885			}
 886		}
 887		if (memory->savedata.type == SAVEDATA_FLASH512 || memory->savedata.type == SAVEDATA_FLASH1M) {
 888			GBASavedataWriteFlash(&memory->savedata, address, value);
 889		} else if (memory->savedata.type == SAVEDATA_SRAM) {
 890			if (memory->vfame.cartType) {
 891				GBAVFameSramWrite(&memory->vfame, address, value, memory->savedata.data);
 892			} else {
 893				memory->savedata.data[address & (SIZE_CART_SRAM - 1)] = value;
 894			}
 895			memory->savedata.dirty |= SAVEDATA_DIRT_NEW;
 896		} else if (memory->hw.devices & HW_TILT) {
 897			GBAHardwareTiltWrite(&memory->hw, address & OFFSET_MASK, value);
 898		} else {
 899			mLOG(GBA_MEM, GAME_ERROR, "Writing to non-existent SRAM: 0x%08X", address);
 900		}
 901		wait = memory->waitstatesNonseq16[REGION_CART_SRAM];
 902		break;
 903	default:
 904		mLOG(GBA_MEM, GAME_ERROR, "Bad memory Store8: 0x%08X", address);
 905		break;
 906	}
 907
 908	if (cycleCounter) {
 909		++wait;
 910		if (address >> BASE_OFFSET < REGION_CART0) {
 911			wait = GBAMemoryStall(cpu, wait);
 912		}
 913		*cycleCounter += wait;
 914	}
 915}
 916
 917uint32_t GBAView32(struct ARMCore* cpu, uint32_t address) {
 918	struct GBA* gba = (struct GBA*) cpu->master;
 919	uint32_t value = 0;
 920	address &= ~3;
 921	switch (address >> BASE_OFFSET) {
 922	case REGION_BIOS:
 923		if (address < SIZE_BIOS) {
 924			LOAD_32(value, address, gba->memory.bios);
 925		}
 926		break;
 927	case REGION_WORKING_RAM:
 928	case REGION_WORKING_IRAM:
 929	case REGION_PALETTE_RAM:
 930	case REGION_VRAM:
 931	case REGION_OAM:
 932	case REGION_CART0:
 933	case REGION_CART0_EX:
 934	case REGION_CART1:
 935	case REGION_CART1_EX:
 936	case REGION_CART2:
 937	case REGION_CART2_EX:
 938		value = GBALoad32(cpu, address, 0);
 939		break;
 940	case REGION_IO:
 941		if ((address & OFFSET_MASK) < REG_MAX) {
 942			value = gba->memory.io[(address & OFFSET_MASK) >> 1];
 943			value |= gba->memory.io[((address & OFFSET_MASK) >> 1) + 1] << 16;
 944		}
 945		break;
 946	case REGION_CART_SRAM:
 947		value = GBALoad8(cpu, address, 0);
 948		value |= GBALoad8(cpu, address + 1, 0) << 8;
 949		value |= GBALoad8(cpu, address + 2, 0) << 16;
 950		value |= GBALoad8(cpu, address + 3, 0) << 24;
 951		break;
 952	default:
 953		break;
 954	}
 955	return value;
 956}
 957
 958uint16_t GBAView16(struct ARMCore* cpu, uint32_t address) {
 959	struct GBA* gba = (struct GBA*) cpu->master;
 960	uint16_t value = 0;
 961	address &= ~1;
 962	switch (address >> BASE_OFFSET) {
 963	case REGION_BIOS:
 964		if (address < SIZE_BIOS) {
 965			LOAD_16(value, address, gba->memory.bios);
 966		}
 967		break;
 968	case REGION_WORKING_RAM:
 969	case REGION_WORKING_IRAM:
 970	case REGION_PALETTE_RAM:
 971	case REGION_VRAM:
 972	case REGION_OAM:
 973	case REGION_CART0:
 974	case REGION_CART0_EX:
 975	case REGION_CART1:
 976	case REGION_CART1_EX:
 977	case REGION_CART2:
 978	case REGION_CART2_EX:
 979		value = GBALoad16(cpu, address, 0);
 980		break;
 981	case REGION_IO:
 982		if ((address & OFFSET_MASK) < REG_MAX) {
 983			value = gba->memory.io[(address & OFFSET_MASK) >> 1];
 984		}
 985		break;
 986	case REGION_CART_SRAM:
 987		value = GBALoad8(cpu, address, 0);
 988		value |= GBALoad8(cpu, address + 1, 0) << 8;
 989		break;
 990	default:
 991		break;
 992	}
 993	return value;
 994}
 995
 996uint8_t GBAView8(struct ARMCore* cpu, uint32_t address) {
 997	struct GBA* gba = (struct GBA*) cpu->master;
 998	uint8_t value = 0;
 999	switch (address >> BASE_OFFSET) {
1000	case REGION_BIOS:
1001		if (address < SIZE_BIOS) {
1002			value = ((uint8_t*) gba->memory.bios)[address];
1003		}
1004		break;
1005	case REGION_WORKING_RAM:
1006	case REGION_WORKING_IRAM:
1007	case REGION_CART0:
1008	case REGION_CART0_EX:
1009	case REGION_CART1:
1010	case REGION_CART1_EX:
1011	case REGION_CART2:
1012	case REGION_CART2_EX:
1013	case REGION_CART_SRAM:
1014		value = GBALoad8(cpu, address, 0);
1015		break;
1016	case REGION_IO:
1017	case REGION_PALETTE_RAM:
1018	case REGION_VRAM:
1019	case REGION_OAM:
1020		value = GBAView16(cpu, address) >> ((address & 1) * 8);
1021		break;
1022	default:
1023		break;
1024	}
1025	return value;
1026}
1027
1028void GBAPatch32(struct ARMCore* cpu, uint32_t address, int32_t value, int32_t* old) {
1029	struct GBA* gba = (struct GBA*) cpu->master;
1030	struct GBAMemory* memory = &gba->memory;
1031	int32_t oldValue = -1;
1032
1033	switch (address >> BASE_OFFSET) {
1034	case REGION_WORKING_RAM:
1035		LOAD_32(oldValue, address & (SIZE_WORKING_RAM - 4), memory->wram);
1036		STORE_32(value, address & (SIZE_WORKING_RAM - 4), memory->wram);
1037		break;
1038	case REGION_WORKING_IRAM:
1039		LOAD_32(oldValue, address & (SIZE_WORKING_IRAM - 4), memory->iwram);
1040		STORE_32(value, address & (SIZE_WORKING_IRAM - 4), memory->iwram);
1041		break;
1042	case REGION_IO:
1043		mLOG(GBA_MEM, STUB, "Unimplemented memory Patch32: 0x%08X", address);
1044		break;
1045	case REGION_PALETTE_RAM:
1046		LOAD_32(oldValue, address & (SIZE_PALETTE_RAM - 1), gba->video.palette);
1047		STORE_32(value, address & (SIZE_PALETTE_RAM - 4), gba->video.palette);
1048		gba->video.renderer->writePalette(gba->video.renderer, address & (SIZE_PALETTE_RAM - 4), value);
1049		gba->video.renderer->writePalette(gba->video.renderer, (address & (SIZE_PALETTE_RAM - 4)) + 2, value >> 16);
1050		break;
1051	case REGION_VRAM:
1052		if ((address & 0x0001FFFF) < SIZE_VRAM) {
1053			LOAD_32(oldValue, address & 0x0001FFFC, gba->video.renderer->vram);
1054			STORE_32(value, address & 0x0001FFFC, gba->video.renderer->vram);
1055		} else {
1056			LOAD_32(oldValue, address & 0x00017FFC, gba->video.renderer->vram);
1057			STORE_32(value, address & 0x00017FFC, gba->video.renderer->vram);
1058		}
1059		break;
1060	case REGION_OAM:
1061		LOAD_32(oldValue, address & (SIZE_OAM - 4), gba->video.oam.raw);
1062		STORE_32(value, address & (SIZE_OAM - 4), gba->video.oam.raw);
1063		gba->video.renderer->writeOAM(gba->video.renderer, (address & (SIZE_OAM - 4)) >> 1);
1064		gba->video.renderer->writeOAM(gba->video.renderer, ((address & (SIZE_OAM - 4)) + 2) >> 1);
1065		break;
1066	case REGION_CART0:
1067	case REGION_CART0_EX:
1068	case REGION_CART1:
1069	case REGION_CART1_EX:
1070	case REGION_CART2:
1071	case REGION_CART2_EX:
1072		_pristineCow(gba);
1073		if ((address & (SIZE_CART0 - 4)) >= gba->memory.romSize) {
1074			gba->memory.romSize = (address & (SIZE_CART0 - 4)) + 4;
1075			gba->memory.romMask = toPow2(gba->memory.romSize) - 1;
1076		}
1077		LOAD_32(oldValue, address & (SIZE_CART0 - 4), gba->memory.rom);
1078		STORE_32(value, address & (SIZE_CART0 - 4), gba->memory.rom);
1079		break;
1080	case REGION_CART_SRAM:
1081	case REGION_CART_SRAM_MIRROR:
1082		if (memory->savedata.type == SAVEDATA_SRAM) {
1083			LOAD_32(oldValue, address & (SIZE_CART_SRAM - 4), memory->savedata.data);
1084			STORE_32(value, address & (SIZE_CART_SRAM - 4), memory->savedata.data);
1085		} else {
1086			mLOG(GBA_MEM, GAME_ERROR, "Writing to non-existent SRAM: 0x%08X", address);
1087		}
1088		break;
1089	default:
1090		mLOG(GBA_MEM, WARN, "Bad memory Patch16: 0x%08X", address);
1091		break;
1092	}
1093	if (old) {
1094		*old = oldValue;
1095	}
1096}
1097
1098void GBAPatch16(struct ARMCore* cpu, uint32_t address, int16_t value, int16_t* old) {
1099	struct GBA* gba = (struct GBA*) cpu->master;
1100	struct GBAMemory* memory = &gba->memory;
1101	int16_t oldValue = -1;
1102
1103	switch (address >> BASE_OFFSET) {
1104	case REGION_WORKING_RAM:
1105		LOAD_16(oldValue, address & (SIZE_WORKING_RAM - 2), memory->wram);
1106		STORE_16(value, address & (SIZE_WORKING_RAM - 2), memory->wram);
1107		break;
1108	case REGION_WORKING_IRAM:
1109		LOAD_16(oldValue, address & (SIZE_WORKING_IRAM - 2), memory->iwram);
1110		STORE_16(value, address & (SIZE_WORKING_IRAM - 2), memory->iwram);
1111		break;
1112	case REGION_IO:
1113		mLOG(GBA_MEM, STUB, "Unimplemented memory Patch16: 0x%08X", address);
1114		break;
1115	case REGION_PALETTE_RAM:
1116		LOAD_16(oldValue, address & (SIZE_PALETTE_RAM - 2), gba->video.palette);
1117		STORE_16(value, address & (SIZE_PALETTE_RAM - 2), gba->video.palette);
1118		gba->video.renderer->writePalette(gba->video.renderer, address & (SIZE_PALETTE_RAM - 2), value);
1119		break;
1120	case REGION_VRAM:
1121		if ((address & 0x0001FFFF) < SIZE_VRAM) {
1122			LOAD_16(oldValue, address & 0x0001FFFE, gba->video.renderer->vram);
1123			STORE_16(value, address & 0x0001FFFE, gba->video.renderer->vram);
1124		} else {
1125			LOAD_16(oldValue, address & 0x00017FFE, gba->video.renderer->vram);
1126			STORE_16(value, address & 0x00017FFE, gba->video.renderer->vram);
1127		}
1128		break;
1129	case REGION_OAM:
1130		LOAD_16(oldValue, address & (SIZE_OAM - 2), gba->video.oam.raw);
1131		STORE_16(value, address & (SIZE_OAM - 2), gba->video.oam.raw);
1132		gba->video.renderer->writeOAM(gba->video.renderer, (address & (SIZE_OAM - 2)) >> 1);
1133		break;
1134	case REGION_CART0:
1135	case REGION_CART0_EX:
1136	case REGION_CART1:
1137	case REGION_CART1_EX:
1138	case REGION_CART2:
1139	case REGION_CART2_EX:
1140		_pristineCow(gba);
1141		if ((address & (SIZE_CART0 - 1)) >= gba->memory.romSize) {
1142			gba->memory.romSize = (address & (SIZE_CART0 - 2)) + 2;
1143			gba->memory.romMask = toPow2(gba->memory.romSize) - 1;
1144		}
1145		LOAD_16(oldValue, address & (SIZE_CART0 - 2), gba->memory.rom);
1146		STORE_16(value, address & (SIZE_CART0 - 2), gba->memory.rom);
1147		break;
1148	case REGION_CART_SRAM:
1149	case REGION_CART_SRAM_MIRROR:
1150		if (memory->savedata.type == SAVEDATA_SRAM) {
1151			LOAD_16(oldValue, address & (SIZE_CART_SRAM - 2), memory->savedata.data);
1152			STORE_16(value, address & (SIZE_CART_SRAM - 2), memory->savedata.data);
1153		} else {
1154			mLOG(GBA_MEM, GAME_ERROR, "Writing to non-existent SRAM: 0x%08X", address);
1155		}
1156		break;
1157	default:
1158		mLOG(GBA_MEM, WARN, "Bad memory Patch16: 0x%08X", address);
1159		break;
1160	}
1161	if (old) {
1162		*old = oldValue;
1163	}
1164}
1165
1166void GBAPatch8(struct ARMCore* cpu, uint32_t address, int8_t value, int8_t* old) {
1167	struct GBA* gba = (struct GBA*) cpu->master;
1168	struct GBAMemory* memory = &gba->memory;
1169	int8_t oldValue = -1;
1170
1171	switch (address >> BASE_OFFSET) {
1172	case REGION_WORKING_RAM:
1173		oldValue = ((int8_t*) memory->wram)[address & (SIZE_WORKING_RAM - 1)];
1174		((int8_t*) memory->wram)[address & (SIZE_WORKING_RAM - 1)] = value;
1175		break;
1176	case REGION_WORKING_IRAM:
1177		oldValue = ((int8_t*) memory->iwram)[address & (SIZE_WORKING_IRAM - 1)];
1178		((int8_t*) memory->iwram)[address & (SIZE_WORKING_IRAM - 1)] = value;
1179		break;
1180	case REGION_IO:
1181		mLOG(GBA_MEM, STUB, "Unimplemented memory Patch8: 0x%08X", address);
1182		break;
1183	case REGION_PALETTE_RAM:
1184		mLOG(GBA_MEM, STUB, "Unimplemented memory Patch8: 0x%08X", address);
1185		break;
1186	case REGION_VRAM:
1187		mLOG(GBA_MEM, STUB, "Unimplemented memory Patch8: 0x%08X", address);
1188		break;
1189	case REGION_OAM:
1190		mLOG(GBA_MEM, STUB, "Unimplemented memory Patch8: 0x%08X", address);
1191		break;
1192	case REGION_CART0:
1193	case REGION_CART0_EX:
1194	case REGION_CART1:
1195	case REGION_CART1_EX:
1196	case REGION_CART2:
1197	case REGION_CART2_EX:
1198		_pristineCow(gba);
1199		if ((address & (SIZE_CART0 - 1)) >= gba->memory.romSize) {
1200			gba->memory.romSize = (address & (SIZE_CART0 - 2)) + 2;
1201			gba->memory.romMask = toPow2(gba->memory.romSize) - 1;
1202		}
1203		oldValue = ((int8_t*) memory->rom)[address & (SIZE_CART0 - 1)];
1204		((int8_t*) memory->rom)[address & (SIZE_CART0 - 1)] = value;
1205		break;
1206	case REGION_CART_SRAM:
1207	case REGION_CART_SRAM_MIRROR:
1208		if (memory->savedata.type == SAVEDATA_SRAM) {
1209			oldValue = ((int8_t*) memory->savedata.data)[address & (SIZE_CART_SRAM - 1)];
1210			((int8_t*) memory->savedata.data)[address & (SIZE_CART_SRAM - 1)] = value;
1211		} else {
1212			mLOG(GBA_MEM, GAME_ERROR, "Writing to non-existent SRAM: 0x%08X", address);
1213		}
1214		break;
1215	default:
1216		mLOG(GBA_MEM, WARN, "Bad memory Patch8: 0x%08X", address);
1217		break;
1218	}
1219	if (old) {
1220		*old = oldValue;
1221	}
1222}
1223
1224#define LDM_LOOP(LDM) \
1225	for (i = 0; i < 16; i += 4) { \
1226		if (UNLIKELY(mask & (1 << i))) { \
1227			LDM; \
1228			cpu->gprs[i] = value; \
1229			++wait; \
1230			address += 4; \
1231		} \
1232		if (UNLIKELY(mask & (2 << i))) { \
1233			LDM; \
1234			cpu->gprs[i + 1] = value; \
1235			++wait; \
1236			address += 4; \
1237		} \
1238		if (UNLIKELY(mask & (4 << i))) { \
1239			LDM; \
1240			cpu->gprs[i + 2] = value; \
1241			++wait; \
1242			address += 4; \
1243		} \
1244		if (UNLIKELY(mask & (8 << i))) { \
1245			LDM; \
1246			cpu->gprs[i + 3] = value; \
1247			++wait; \
1248			address += 4; \
1249		} \
1250	}
1251
1252uint32_t GBALoadMultiple(struct ARMCore* cpu, uint32_t address, int mask, enum LSMDirection direction, int* cycleCounter) {
1253	struct GBA* gba = (struct GBA*) cpu->master;
1254	struct GBAMemory* memory = &gba->memory;
1255	uint32_t value;
1256	char* waitstatesRegion = memory->waitstatesSeq32;
1257
1258	int i;
1259	int offset = 4;
1260	int popcount = 0;
1261	if (direction & LSM_D) {
1262		offset = -4;
1263		popcount = popcount32(mask);
1264		address -= (popcount << 2) - 4;
1265	}
1266
1267	if (direction & LSM_B) {
1268		address += offset;
1269	}
1270
1271	uint32_t addressMisalign = address & 0x3;
1272	int region = address >> BASE_OFFSET;
1273	if (region < REGION_CART_SRAM) {
1274		address &= 0xFFFFFFFC;
1275	}
1276	int wait = memory->waitstatesSeq32[region] - memory->waitstatesNonseq32[region];
1277
1278	switch (region) {
1279	case REGION_BIOS:
1280		LDM_LOOP(LOAD_BIOS);
1281		break;
1282	case REGION_WORKING_RAM:
1283		LDM_LOOP(LOAD_WORKING_RAM);
1284		break;
1285	case REGION_WORKING_IRAM:
1286		LDM_LOOP(LOAD_WORKING_IRAM);
1287		break;
1288	case REGION_IO:
1289		LDM_LOOP(LOAD_IO);
1290		break;
1291	case REGION_PALETTE_RAM:
1292		LDM_LOOP(LOAD_PALETTE_RAM);
1293		break;
1294	case REGION_VRAM:
1295		LDM_LOOP(LOAD_VRAM);
1296		break;
1297	case REGION_OAM:
1298		LDM_LOOP(LOAD_OAM);
1299		break;
1300	case REGION_CART0:
1301	case REGION_CART0_EX:
1302	case REGION_CART1:
1303	case REGION_CART1_EX:
1304	case REGION_CART2:
1305	case REGION_CART2_EX:
1306		LDM_LOOP(LOAD_CART);
1307		break;
1308	case REGION_CART_SRAM:
1309	case REGION_CART_SRAM_MIRROR:
1310		LDM_LOOP(LOAD_SRAM);
1311		break;
1312	default:
1313		LDM_LOOP(LOAD_BAD);
1314		break;
1315	}
1316
1317	if (cycleCounter) {
1318		++wait;
1319		if (address >> BASE_OFFSET < REGION_CART0) {
1320			wait = GBAMemoryStall(cpu, wait);
1321		}
1322		*cycleCounter += wait;
1323	}
1324
1325	if (direction & LSM_B) {
1326		address -= offset;
1327	}
1328
1329	if (direction & LSM_D) {
1330		address -= (popcount << 2) + 4;
1331	}
1332
1333	return address | addressMisalign;
1334}
1335
1336#define STM_LOOP(STM) \
1337	for (i = 0; i < 16; i += 4) { \
1338		if (UNLIKELY(mask & (1 << i))) { \
1339			value = cpu->gprs[i]; \
1340			STM; \
1341			++wait; \
1342			address += 4; \
1343		} \
1344		if (UNLIKELY(mask & (2 << i))) { \
1345			value = cpu->gprs[i + 1]; \
1346			STM; \
1347			++wait; \
1348			address += 4; \
1349		} \
1350		if (UNLIKELY(mask & (4 << i))) { \
1351			value = cpu->gprs[i + 2]; \
1352			STM; \
1353			++wait; \
1354			address += 4; \
1355		} \
1356		if (UNLIKELY(mask & (8 << i))) { \
1357			value = cpu->gprs[i + 3]; \
1358			if (i + 3 == ARM_PC) { \
1359				value += WORD_SIZE_ARM; \
1360			} \
1361			STM; \
1362			++wait; \
1363			address += 4; \
1364		} \
1365	}
1366
1367uint32_t GBAStoreMultiple(struct ARMCore* cpu, uint32_t address, int mask, enum LSMDirection direction, int* cycleCounter) {
1368	struct GBA* gba = (struct GBA*) cpu->master;
1369	struct GBAMemory* memory = &gba->memory;
1370	uint32_t value;
1371	char* waitstatesRegion = memory->waitstatesSeq32;
1372
1373	int i;
1374	int offset = 4;
1375	int popcount = 0;
1376	if (direction & LSM_D) {
1377		offset = -4;
1378		popcount = popcount32(mask);
1379		address -= (popcount << 2) - 4;
1380	}
1381
1382	if (direction & LSM_B) {
1383		address += offset;
1384	}
1385
1386	uint32_t addressMisalign = address & 0x3;
1387	int region = address >> BASE_OFFSET;
1388	if (region < REGION_CART_SRAM) {
1389		address &= 0xFFFFFFFC;
1390	}
1391	int wait = memory->waitstatesSeq32[region] - memory->waitstatesNonseq32[region];
1392
1393	switch (region) {
1394	case REGION_WORKING_RAM:
1395		STM_LOOP(STORE_WORKING_RAM);
1396		break;
1397	case REGION_WORKING_IRAM:
1398		STM_LOOP(STORE_WORKING_IRAM);
1399		break;
1400	case REGION_IO:
1401		STM_LOOP(STORE_IO);
1402		break;
1403	case REGION_PALETTE_RAM:
1404		STM_LOOP(STORE_PALETTE_RAM);
1405		break;
1406	case REGION_VRAM:
1407		STM_LOOP(STORE_VRAM);
1408		break;
1409	case REGION_OAM:
1410		STM_LOOP(STORE_OAM);
1411		break;
1412	case REGION_CART0:
1413	case REGION_CART0_EX:
1414	case REGION_CART1:
1415	case REGION_CART1_EX:
1416	case REGION_CART2:
1417	case REGION_CART2_EX:
1418		STM_LOOP(STORE_CART);
1419		break;
1420	case REGION_CART_SRAM:
1421	case REGION_CART_SRAM_MIRROR:
1422		STM_LOOP(STORE_SRAM);
1423		break;
1424	default:
1425		STM_LOOP(STORE_BAD);
1426		break;
1427	}
1428
1429	if (cycleCounter) {
1430		if (address >> BASE_OFFSET < REGION_CART0) {
1431			wait = GBAMemoryStall(cpu, wait);
1432		}
1433		*cycleCounter += wait;
1434	}
1435
1436	if (direction & LSM_B) {
1437		address -= offset;
1438	}
1439
1440	if (direction & LSM_D) {
1441		address -= (popcount << 2) + 4;
1442	}
1443
1444	return address | addressMisalign;
1445}
1446
1447void GBAAdjustWaitstates(struct GBA* gba, uint16_t parameters) {
1448	struct GBAMemory* memory = &gba->memory;
1449	struct ARMCore* cpu = gba->cpu;
1450	int sram = parameters & 0x0003;
1451	int ws0 = (parameters & 0x000C) >> 2;
1452	int ws0seq = (parameters & 0x0010) >> 4;
1453	int ws1 = (parameters & 0x0060) >> 5;
1454	int ws1seq = (parameters & 0x0080) >> 7;
1455	int ws2 = (parameters & 0x0300) >> 8;
1456	int ws2seq = (parameters & 0x0400) >> 10;
1457	int prefetch = parameters & 0x4000;
1458
1459	memory->waitstatesNonseq16[REGION_CART_SRAM] = memory->waitstatesNonseq16[REGION_CART_SRAM_MIRROR] = GBA_ROM_WAITSTATES[sram];
1460	memory->waitstatesSeq16[REGION_CART_SRAM] = memory->waitstatesSeq16[REGION_CART_SRAM_MIRROR] = GBA_ROM_WAITSTATES[sram];
1461	memory->waitstatesNonseq32[REGION_CART_SRAM] = memory->waitstatesNonseq32[REGION_CART_SRAM_MIRROR] = 2 * GBA_ROM_WAITSTATES[sram] + 1;
1462	memory->waitstatesSeq32[REGION_CART_SRAM] = memory->waitstatesSeq32[REGION_CART_SRAM_MIRROR] = 2 * GBA_ROM_WAITSTATES[sram] + 1;
1463
1464	memory->waitstatesNonseq16[REGION_CART0] = memory->waitstatesNonseq16[REGION_CART0_EX] = GBA_ROM_WAITSTATES[ws0];
1465	memory->waitstatesNonseq16[REGION_CART1] = memory->waitstatesNonseq16[REGION_CART1_EX] = GBA_ROM_WAITSTATES[ws1];
1466	memory->waitstatesNonseq16[REGION_CART2] = memory->waitstatesNonseq16[REGION_CART2_EX] = GBA_ROM_WAITSTATES[ws2];
1467
1468	memory->waitstatesSeq16[REGION_CART0] = memory->waitstatesSeq16[REGION_CART0_EX] = GBA_ROM_WAITSTATES_SEQ[ws0seq];
1469	memory->waitstatesSeq16[REGION_CART1] = memory->waitstatesSeq16[REGION_CART1_EX] = GBA_ROM_WAITSTATES_SEQ[ws1seq + 2];
1470	memory->waitstatesSeq16[REGION_CART2] = memory->waitstatesSeq16[REGION_CART2_EX] = GBA_ROM_WAITSTATES_SEQ[ws2seq + 4];
1471
1472	memory->waitstatesNonseq32[REGION_CART0] = memory->waitstatesNonseq32[REGION_CART0_EX] = memory->waitstatesNonseq16[REGION_CART0] + 1 + memory->waitstatesSeq16[REGION_CART0];
1473	memory->waitstatesNonseq32[REGION_CART1] = memory->waitstatesNonseq32[REGION_CART1_EX] = memory->waitstatesNonseq16[REGION_CART1] + 1 + memory->waitstatesSeq16[REGION_CART1];
1474	memory->waitstatesNonseq32[REGION_CART2] = memory->waitstatesNonseq32[REGION_CART2_EX] = memory->waitstatesNonseq16[REGION_CART2] + 1 + memory->waitstatesSeq16[REGION_CART2];
1475
1476	memory->waitstatesSeq32[REGION_CART0] = memory->waitstatesSeq32[REGION_CART0_EX] = 2 * memory->waitstatesSeq16[REGION_CART0] + 1;
1477	memory->waitstatesSeq32[REGION_CART1] = memory->waitstatesSeq32[REGION_CART1_EX] = 2 * memory->waitstatesSeq16[REGION_CART1] + 1;
1478	memory->waitstatesSeq32[REGION_CART2] = memory->waitstatesSeq32[REGION_CART2_EX] = 2 * memory->waitstatesSeq16[REGION_CART2] + 1;
1479
1480	memory->prefetch = prefetch;
1481
1482	cpu->memory.activeSeqCycles32 = memory->waitstatesSeq32[memory->activeRegion];
1483	cpu->memory.activeSeqCycles16 = memory->waitstatesSeq16[memory->activeRegion];
1484
1485	cpu->memory.activeNonseqCycles32 = memory->waitstatesNonseq32[memory->activeRegion];
1486	cpu->memory.activeNonseqCycles16 = memory->waitstatesNonseq16[memory->activeRegion];
1487}
1488
1489static bool _isValidDMASAD(int dma, uint32_t address) {
1490	if (dma == 0 && address >= BASE_CART0 && address < BASE_CART_SRAM) {
1491		return false;
1492	}
1493	return address >= BASE_WORKING_RAM;
1494}
1495
1496static bool _isValidDMADAD(int dma, uint32_t address) {
1497	return dma == 3 || address < BASE_CART0;
1498}
1499
1500uint32_t GBAMemoryWriteDMASAD(struct GBA* gba, int dma, uint32_t address) {
1501	struct GBAMemory* memory = &gba->memory;
1502	address &= 0x0FFFFFFE;
1503	if (_isValidDMASAD(dma, address)) {
1504		memory->dma[dma].source = address;
1505	}
1506	return memory->dma[dma].source;
1507}
1508
1509uint32_t GBAMemoryWriteDMADAD(struct GBA* gba, int dma, uint32_t address) {
1510	struct GBAMemory* memory = &gba->memory;
1511	address &= 0x0FFFFFFE;
1512	if (_isValidDMADAD(dma, address)) {
1513		memory->dma[dma].dest = address;
1514	}
1515	return memory->dma[dma].dest;
1516}
1517
1518void GBAMemoryWriteDMACNT_LO(struct GBA* gba, int dma, uint16_t count) {
1519	struct GBAMemory* memory = &gba->memory;
1520	memory->dma[dma].count = count ? count : (dma == 3 ? 0x10000 : 0x4000);
1521}
1522
1523uint16_t GBAMemoryWriteDMACNT_HI(struct GBA* gba, int dma, uint16_t control) {
1524	struct GBAMemory* memory = &gba->memory;
1525	struct GBADMA* currentDma = &memory->dma[dma];
1526	int wasEnabled = GBADMARegisterIsEnable(currentDma->reg);
1527	if (dma < 3) {
1528		control &= 0xF7E0;
1529	} else {
1530		control &= 0xFFE0;
1531	}
1532	currentDma->reg = control;
1533
1534	if (GBADMARegisterIsDRQ(currentDma->reg)) {
1535		mLOG(GBA_MEM, STUB, "DRQ not implemented");
1536	}
1537
1538	if (!wasEnabled && GBADMARegisterIsEnable(currentDma->reg)) {
1539		currentDma->nextSource = currentDma->source;
1540		currentDma->nextDest = currentDma->dest;
1541		currentDma->nextCount = currentDma->count;
1542		GBAMemoryScheduleDMA(gba, dma, currentDma);
1543	}
1544	// If the DMA has already occurred, this value might have changed since the function started
1545	return currentDma->reg;
1546};
1547
1548void GBAMemoryScheduleDMA(struct GBA* gba, int number, struct GBADMA* info) {
1549	struct ARMCore* cpu = gba->cpu;
1550	switch (GBADMARegisterGetTiming(info->reg)) {
1551	case DMA_TIMING_NOW:
1552		info->nextEvent = cpu->cycles + 2;
1553		GBAMemoryUpdateDMAs(gba, -1);
1554		break;
1555	case DMA_TIMING_HBLANK:
1556		// Handled implicitly
1557		info->nextEvent = INT_MAX;
1558		break;
1559	case DMA_TIMING_VBLANK:
1560		// Handled implicitly
1561		info->nextEvent = INT_MAX;
1562		break;
1563	case DMA_TIMING_CUSTOM:
1564		info->nextEvent = INT_MAX;
1565		switch (number) {
1566		case 0:
1567			mLOG(GBA_MEM, WARN, "Discarding invalid DMA0 scheduling");
1568			break;
1569		case 1:
1570		case 2:
1571			GBAAudioScheduleFifoDma(&gba->audio, number, info);
1572			break;
1573		case 3:
1574			// GBAVideoScheduleVCaptureDma(dma, info);
1575			break;
1576		}
1577	}
1578}
1579
1580void GBAMemoryRunHblankDMAs(struct GBA* gba, int32_t cycles) {
1581	struct GBAMemory* memory = &gba->memory;
1582	struct GBADMA* dma;
1583	int i;
1584	for (i = 0; i < 4; ++i) {
1585		dma = &memory->dma[i];
1586		if (GBADMARegisterIsEnable(dma->reg) && GBADMARegisterGetTiming(dma->reg) == DMA_TIMING_HBLANK) {
1587			dma->nextEvent = cycles;
1588		}
1589	}
1590	GBAMemoryUpdateDMAs(gba, 0);
1591}
1592
1593void GBAMemoryRunVblankDMAs(struct GBA* gba, int32_t cycles) {
1594	struct GBAMemory* memory = &gba->memory;
1595	struct GBADMA* dma;
1596	int i;
1597	for (i = 0; i < 4; ++i) {
1598		dma = &memory->dma[i];
1599		if (GBADMARegisterIsEnable(dma->reg) && GBADMARegisterGetTiming(dma->reg) == DMA_TIMING_VBLANK) {
1600			dma->nextEvent = cycles;
1601		}
1602	}
1603	GBAMemoryUpdateDMAs(gba, 0);
1604}
1605
1606int32_t GBAMemoryRunDMAs(struct GBA* gba, int32_t cycles) {
1607	struct GBAMemory* memory = &gba->memory;
1608	if (memory->nextDMA == INT_MAX) {
1609		return INT_MAX;
1610	}
1611	memory->nextDMA -= cycles;
1612	memory->eventDiff += cycles;
1613	while (memory->nextDMA <= 0) {
1614		struct GBADMA* dma = &memory->dma[memory->activeDMA];
1615		GBAMemoryServiceDMA(gba, memory->activeDMA, dma);
1616		GBAMemoryUpdateDMAs(gba, memory->eventDiff);
1617		memory->eventDiff = 0;
1618	}
1619	return memory->nextDMA;
1620}
1621
1622void GBAMemoryUpdateDMAs(struct GBA* gba, int32_t cycles) {
1623	int i;
1624	struct GBAMemory* memory = &gba->memory;
1625	struct ARMCore* cpu = gba->cpu;
1626	memory->activeDMA = -1;
1627	memory->nextDMA = INT_MAX;
1628	for (i = 3; i >= 0; --i) {
1629		struct GBADMA* dma = &memory->dma[i];
1630		if (dma->nextEvent != INT_MAX) {
1631			dma->nextEvent -= cycles;
1632			if (GBADMARegisterIsEnable(dma->reg)) {
1633				memory->activeDMA = i;
1634				memory->nextDMA = dma->nextEvent;
1635			}
1636		}
1637	}
1638	if (memory->nextDMA < cpu->nextEvent) {
1639		cpu->nextEvent = memory->nextDMA;
1640	}
1641}
1642
1643void GBAMemoryServiceDMA(struct GBA* gba, int number, struct GBADMA* info) {
1644	struct GBAMemory* memory = &gba->memory;
1645	struct ARMCore* cpu = gba->cpu;
1646	uint32_t width = GBADMARegisterGetWidth(info->reg) ? 4 : 2;
1647	int sourceOffset = DMA_OFFSET[GBADMARegisterGetSrcControl(info->reg)] * width;
1648	int destOffset = DMA_OFFSET[GBADMARegisterGetDestControl(info->reg)] * width;
1649	int32_t wordsRemaining = info->nextCount;
1650	uint32_t source = info->nextSource;
1651	uint32_t dest = info->nextDest;
1652	uint32_t sourceRegion = source >> BASE_OFFSET;
1653	uint32_t destRegion = dest >> BASE_OFFSET;
1654	int32_t cycles = 2;
1655
1656	if (source == info->source && dest == info->dest && wordsRemaining == info->count) {
1657		if (sourceRegion < REGION_CART0 || destRegion < REGION_CART0) {
1658			cycles += 2;
1659		}
1660		if (width == 4) {
1661			cycles += memory->waitstatesNonseq32[sourceRegion] + memory->waitstatesNonseq32[destRegion];
1662			source &= 0xFFFFFFFC;
1663			dest &= 0xFFFFFFFC;
1664		} else {
1665			cycles += memory->waitstatesNonseq16[sourceRegion] + memory->waitstatesNonseq16[destRegion];
1666		}
1667	} else {
1668		if (width == 4) {
1669			cycles += memory->waitstatesSeq32[sourceRegion] + memory->waitstatesSeq32[destRegion];
1670		} else {
1671			cycles += memory->waitstatesSeq16[sourceRegion] + memory->waitstatesSeq16[destRegion];
1672		}
1673	}
1674
1675	gba->performingDMA = 1 | (number << 1);
1676	int32_t word;
1677	if (width == 4) {
1678		word = cpu->memory.load32(cpu, source, 0);
1679		gba->bus = word;
1680		cpu->memory.store32(cpu, dest, word, 0);
1681		source += sourceOffset;
1682		dest += destOffset;
1683		--wordsRemaining;
1684	} else {
1685		if (sourceRegion == REGION_CART2_EX && memory->savedata.type == SAVEDATA_EEPROM) {
1686			word = GBASavedataReadEEPROM(&memory->savedata);
1687			gba->bus = word | (word << 16);
1688			cpu->memory.store16(cpu, dest, word, 0);
1689			source += sourceOffset;
1690			dest += destOffset;
1691			--wordsRemaining;
1692		} else if (destRegion == REGION_CART2_EX) {
1693			if (memory->savedata.type == SAVEDATA_AUTODETECT) {
1694				mLOG(GBA_MEM, INFO, "Detected EEPROM savegame");
1695				GBASavedataInitEEPROM(&memory->savedata, gba->realisticTiming);
1696			}
1697			word = cpu->memory.load16(cpu, source, 0);
1698			gba->bus = word | (word << 16);
1699			GBASavedataWriteEEPROM(&memory->savedata, word, wordsRemaining);
1700			source += sourceOffset;
1701			dest += destOffset;
1702			--wordsRemaining;
1703		} else {
1704			word = cpu->memory.load16(cpu, source, 0);
1705			gba->bus = word | (word << 16);
1706			cpu->memory.store16(cpu, dest, word, 0);
1707			source += sourceOffset;
1708			dest += destOffset;
1709			--wordsRemaining;
1710		}
1711	}
1712	gba->performingDMA = 0;
1713
1714	if (!wordsRemaining) {
1715		if (!GBADMARegisterIsRepeat(info->reg) || GBADMARegisterGetTiming(info->reg) == DMA_TIMING_NOW) {
1716			info->reg = GBADMARegisterClearEnable(info->reg);
1717			info->nextEvent = INT_MAX;
1718
1719			// Clear the enable bit in memory
1720			memory->io[(REG_DMA0CNT_HI + number * (REG_DMA1CNT_HI - REG_DMA0CNT_HI)) >> 1] &= 0x7FE0;
1721		} else {
1722			info->nextCount = info->count;
1723			if (GBADMARegisterGetDestControl(info->reg) == DMA_INCREMENT_RELOAD) {
1724				info->nextDest = info->dest;
1725			}
1726			GBAMemoryScheduleDMA(gba, number, info);
1727		}
1728		if (GBADMARegisterIsDoIRQ(info->reg)) {
1729			GBARaiseIRQ(gba, IRQ_DMA0 + number);
1730		}
1731	} else {
1732		info->nextDest = dest;
1733		info->nextCount = wordsRemaining;
1734	}
1735	info->nextSource = source;
1736
1737	if (info->nextEvent != INT_MAX) {
1738		info->nextEvent += cycles;
1739	}
1740	cpu->cycles += cycles;
1741}
1742
1743int32_t GBAMemoryStall(struct ARMCore* cpu, int32_t wait) {
1744	struct GBA* gba = (struct GBA*) cpu->master;
1745	struct GBAMemory* memory = &gba->memory;
1746
1747	if (memory->activeRegion < REGION_CART0 || !memory->prefetch) {
1748		// The wait is the stall
1749		return wait;
1750	}
1751
1752	int32_t previousLoads = 0;
1753
1754	// Don't prefetch too much if we're overlapping with a previous prefetch
1755	uint32_t dist = (memory->lastPrefetchedPc - cpu->gprs[ARM_PC]) >> 1;
1756	if (dist < 8) {
1757		previousLoads = dist;
1758	}
1759
1760	int32_t s = cpu->memory.activeSeqCycles16 + 1;
1761	int32_t n2s = cpu->memory.activeNonseqCycles16 - cpu->memory.activeSeqCycles16 + 1;
1762
1763	// Figure out how many sequential loads we can jam in
1764	int32_t stall = s;
1765	int32_t loads = 1;
1766
1767	if (stall > wait && !previousLoads) {
1768		// We might need to stall a bit extra if we haven't finished the first S cycle
1769		wait = stall;
1770	} else {
1771		while (stall < wait) {
1772			stall += s;
1773			++loads;
1774		}
1775		if (loads + previousLoads > 8) {
1776			loads = 8 - previousLoads;
1777		}
1778	}
1779	// This instruction used to have an N, convert it to an S.
1780	wait -= n2s;
1781
1782	// TODO: Invalidate prefetch on branch
1783	memory->lastPrefetchedPc = cpu->gprs[ARM_PC] + WORD_SIZE_THUMB * loads;
1784
1785	// The next |loads|S waitstates disappear entirely, so long as they're all in a row
1786	cpu->cycles -= (s - 1) * loads;
1787	return wait;
1788}
1789
1790void GBAMemorySerialize(const struct GBAMemory* memory, struct GBASerializedState* state) {
1791	memcpy(state->wram, memory->wram, SIZE_WORKING_RAM);
1792	memcpy(state->iwram, memory->iwram, SIZE_WORKING_IRAM);
1793}
1794
1795void GBAMemoryDeserialize(struct GBAMemory* memory, const struct GBASerializedState* state) {
1796	memcpy(memory->wram, state->wram, SIZE_WORKING_RAM);
1797	memcpy(memory->iwram, state->iwram, SIZE_WORKING_IRAM);
1798}
1799
1800void _pristineCow(struct GBA* gba) {
1801	if (gba->memory.rom != gba->pristineRom) {
1802		return;
1803	}
1804	gba->memory.rom = anonymousMemoryMap(SIZE_CART0);
1805	memcpy(gba->memory.rom, gba->pristineRom, gba->memory.romSize);
1806	memset(((uint8_t*) gba->memory.rom) + gba->memory.romSize, 0xFF, SIZE_CART0 - gba->memory.romSize);
1807}