all repos — mgba @ c5092559ef04c700a233e8fcf3263e818766075f

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