all repos — mgba @ 5966f46355d18ba472404a7f7ed3cbeebf846635

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