all repos — mgba @ 063605a2167e700278659ae83e1b006517700487

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