all repos — mgba @ b6c0d5307f4690b796dd11e13900dcebfacdfcc9

mGBA Game Boy Advance Emulator

src/gba/memory.c (view raw)

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