all repos — mgba @ b69e5392a1653abfd32346c03d44970273b0ad22

mGBA Game Boy Advance Emulator

src/gba/memory.c (view raw)

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