all repos — mgba @ 0cdc9ff32887e57767fac74ea12c8616025583bd

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