all repos — mgba @ aa0ee743b3779e056b74b15dba9415c541a6533f

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