all repos — mgba @ 013948f129f5449d7ba718fca940c0ad5c6cf8e9

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