all repos — mgba @ b8b7ec0b12cdfa3aab1da32e06e8868e76ed9dbb

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