all repos — mgba @ f1816279a57555d2b8ca4ad1b4c28c0a21576c37

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