all repos — mgba @ fc172147eea8a5c8a7fba3b74d21caab845e6705

mGBA Game Boy Advance Emulator

src/gba/gba-memory.c (view raw)

   1/* Copyright (c) 2013-2014 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 "gba-memory.h"
   7
   8#include "macros.h"
   9
  10#include "decoder.h"
  11#include "gba-gpio.h"
  12#include "gba-io.h"
  13#include "gba-serialize.h"
  14#include "hle-bios.h"
  15#include "util/memory.h"
  16
  17#define IDLE_LOOP_THRESHOLD 200
  18
  19static uint32_t _popcount32(unsigned bits);
  20static uint32_t _deadbeef[2] = { 0xDEADBEEF, 0xFEEDFACE };
  21
  22static void GBASetActiveRegion(struct ARMCore* cpu, uint32_t region);
  23static void GBAMemoryServiceDMA(struct GBA* gba, int number, struct GBADMA* info);
  24
  25static const char GBA_BASE_WAITSTATES[16] = { 0, 0, 2, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4 };
  26static const char GBA_BASE_WAITSTATES_32[16] = { 0, 0, 5, 0, 0, 0, 0, 0, 7, 7, 9, 9, 13, 13, 9 };
  27static const char GBA_BASE_WAITSTATES_SEQ[16] = { 0, 0, 2, 0, 0, 0, 0, 0, 2, 2, 4, 4, 8, 8, 4 };
  28static const char GBA_BASE_WAITSTATES_SEQ_32[16] = { 0, 0, 5, 0, 0, 0, 0, 0, 5, 5, 9, 9, 17, 17, 9 };
  29static const char GBA_ROM_WAITSTATES[] = { 4, 3, 2, 8 };
  30static const char GBA_ROM_WAITSTATES_SEQ[] = { 2, 1, 4, 1, 8, 1 };
  31static const int DMA_OFFSET[] = { 1, -1, 0, 1 };
  32
  33void GBAMemoryInit(struct GBA* gba) {
  34	struct ARMCore* cpu = gba->cpu;
  35	cpu->memory.load32 = GBALoad32;
  36	cpu->memory.load16 = GBALoad16;
  37	cpu->memory.load8 = GBALoad8;
  38	cpu->memory.loadMultiple = GBALoadMultiple;
  39	cpu->memory.store32 = GBAStore32;
  40	cpu->memory.store16 = GBAStore16;
  41	cpu->memory.store8 = GBAStore8;
  42	cpu->memory.storeMultiple = GBAStoreMultiple;
  43
  44	gba->memory.bios = (uint32_t*) hleBios;
  45	gba->memory.fullBios = 0;
  46	gba->memory.wram = 0;
  47	gba->memory.iwram = 0;
  48	gba->memory.rom = 0;
  49	gba->memory.gpio.p = gba;
  50
  51	int i;
  52	for (i = 0; i < 16; ++i) {
  53		gba->memory.waitstatesNonseq16[i] = GBA_BASE_WAITSTATES[i];
  54		gba->memory.waitstatesSeq16[i] = GBA_BASE_WAITSTATES_SEQ[i];
  55		gba->memory.waitstatesPrefetchNonseq16[i] = GBA_BASE_WAITSTATES[i];
  56		gba->memory.waitstatesPrefetchSeq16[i] = GBA_BASE_WAITSTATES_SEQ[i];
  57		gba->memory.waitstatesNonseq32[i] = GBA_BASE_WAITSTATES_32[i];
  58		gba->memory.waitstatesSeq32[i] = GBA_BASE_WAITSTATES_SEQ_32[i];
  59		gba->memory.waitstatesPrefetchNonseq32[i] = GBA_BASE_WAITSTATES_32[i];
  60		gba->memory.waitstatesPrefetchSeq32[i] = GBA_BASE_WAITSTATES_SEQ_32[i];
  61	}
  62	for (; i < 256; ++i) {
  63		gba->memory.waitstatesNonseq16[i] = 0;
  64		gba->memory.waitstatesSeq16[i] = 0;
  65		gba->memory.waitstatesNonseq32[i] = 0;
  66		gba->memory.waitstatesSeq32[i] = 0;
  67	}
  68
  69	gba->memory.activeRegion = -1;
  70	cpu->memory.activeRegion = 0;
  71	cpu->memory.activeMask = 0;
  72	cpu->memory.setActiveRegion = GBASetActiveRegion;
  73	cpu->memory.activeSeqCycles32 = 0;
  74	cpu->memory.activeSeqCycles16 = 0;
  75	cpu->memory.activeNonseqCycles32 = 0;
  76	cpu->memory.activeNonseqCycles16 = 0;
  77	cpu->memory.activeUncachedCycles32 = 0;
  78	cpu->memory.activeUncachedCycles16 = 0;
  79	gba->memory.biosPrefetch = 0;
  80}
  81
  82void GBAMemoryDeinit(struct GBA* gba) {
  83	mappedMemoryFree(gba->memory.wram, SIZE_WORKING_RAM);
  84	mappedMemoryFree(gba->memory.iwram, SIZE_WORKING_IRAM);
  85	if (gba->memory.rom) {
  86		mappedMemoryFree(gba->memory.rom, gba->memory.romSize);
  87	}
  88	GBASavedataDeinit(&gba->memory.savedata);
  89}
  90
  91void GBAMemoryReset(struct GBA* gba) {
  92	if (gba->memory.wram) {
  93		mappedMemoryFree(gba->memory.wram, SIZE_WORKING_RAM);
  94	}
  95	gba->memory.wram = anonymousMemoryMap(SIZE_WORKING_RAM);
  96
  97	if (gba->memory.iwram) {
  98		mappedMemoryFree(gba->memory.iwram, SIZE_WORKING_IRAM);
  99	}
 100	gba->memory.iwram = anonymousMemoryMap(SIZE_WORKING_IRAM);
 101
 102	memset(gba->memory.io, 0, sizeof(gba->memory.io));
 103	memset(gba->memory.dma, 0, sizeof(gba->memory.dma));
 104	int i;
 105	for (i = 0; i < 4; ++i) {
 106		gba->memory.dma[i].count = 0x4000;
 107		gba->memory.dma[i].nextEvent = INT_MAX;
 108	}
 109	gba->memory.dma[3].count = 0x10000;
 110	gba->memory.activeDMA = -1;
 111	gba->memory.nextDMA = INT_MAX;
 112	gba->memory.eventDiff = 0;
 113
 114	if (!gba->memory.wram || !gba->memory.iwram) {
 115		GBAMemoryDeinit(gba);
 116		GBALog(gba, GBA_LOG_FATAL, "Could not map memory");
 117	}
 118}
 119
 120static void _analyzeForIdleLoop(struct GBA* gba, struct ARMCore* cpu, uint32_t address) {
 121	struct ARMInstructionInfo info;
 122	uint32_t nextAddress = address;
 123	memset(gba->taintedRegisters, 0, sizeof(gba->taintedRegisters));
 124	if (cpu->executionMode == MODE_THUMB) {
 125		while (true) {
 126			uint16_t opcode;
 127			LOAD_16(opcode, nextAddress & cpu->memory.activeMask, cpu->memory.activeRegion);
 128			ARMDecodeThumb(opcode, &info);
 129			switch (info.branchType) {
 130			case ARM_BRANCH_NONE:
 131				if (info.operandFormat & ARM_OPERAND_MEMORY_2) {
 132					if (info.mnemonic == ARM_MN_STR || gba->taintedRegisters[info.memory.baseReg]) {
 133						gba->idleDetectionStep = -1;
 134						return;
 135					}
 136					uint32_t loadAddress = gba->cachedRegisters[info.memory.baseReg];
 137					uint32_t offset = 0;
 138					if (info.memory.format & ARM_MEMORY_IMMEDIATE_OFFSET) {
 139						offset = info.memory.offset.immediate;
 140					} else if (info.memory.format & ARM_MEMORY_REGISTER_OFFSET) {
 141						int reg = info.memory.offset.reg;
 142						if (gba->cachedRegisters[reg]) {
 143							gba->idleDetectionStep = -1;
 144							return;
 145						}
 146						offset = gba->cachedRegisters[reg];
 147					}
 148					if (info.memory.format & ARM_MEMORY_OFFSET_SUBTRACT) {
 149						loadAddress -= offset;
 150					} else {
 151						loadAddress += offset;
 152					}
 153					if ((loadAddress >> BASE_OFFSET) == REGION_IO) {
 154						gba->idleDetectionStep = -1;
 155						return;
 156					}
 157					if ((loadAddress >> BASE_OFFSET) < REGION_CART0 || (loadAddress >> BASE_OFFSET) > REGION_CART2_EX) {
 158						gba->taintedRegisters[info.op1.reg] = true;
 159					} else {
 160						switch (info.memory.width) {
 161						case 1:
 162							gba->cachedRegisters[info.op1.reg] = GBALoad8(cpu, loadAddress, 0);
 163							break;
 164						case 2:
 165							gba->cachedRegisters[info.op1.reg] = GBALoad16(cpu, loadAddress, 0);
 166							break;
 167						case 4:
 168							gba->cachedRegisters[info.op1.reg] = GBALoad32(cpu, loadAddress, 0);
 169							break;
 170						}
 171					}
 172				} else if (info.operandFormat & ARM_OPERAND_AFFECTED_1) {
 173					gba->taintedRegisters[info.op1.reg] = true;
 174				}
 175				nextAddress += WORD_SIZE_THUMB;
 176				break;
 177			case ARM_BRANCH:
 178				if ((uint32_t) info.op1.immediate + nextAddress + WORD_SIZE_THUMB * 2 == address) {
 179					gba->idleLoop = address;
 180					gba->idleOptimization = IDLE_LOOP_REMOVE;
 181				}
 182				gba->idleDetectionStep = -1;
 183				return;
 184			default:
 185				gba->idleDetectionStep = -1;
 186				return;
 187			}
 188		}
 189	} else {
 190		gba->idleDetectionStep = -1;
 191	}
 192}
 193
 194static void GBASetActiveRegion(struct ARMCore* cpu, uint32_t address) {
 195	struct GBA* gba = (struct GBA*) cpu->master;
 196	struct GBAMemory* memory = &gba->memory;
 197
 198	int newRegion = address >> BASE_OFFSET;
 199	if (gba->idleOptimization >= IDLE_LOOP_REMOVE && memory->activeRegion != REGION_BIOS) {
 200		if (address == gba->lastJump && address == gba->idleLoop) {
 201			GBAHalt(gba);
 202		} else if (gba->idleOptimization >= IDLE_LOOP_DETECT && newRegion == memory->activeRegion) {
 203			if (address == gba->lastJump) {
 204				switch (gba->idleDetectionStep) {
 205				case 0:
 206					memcpy(gba->cachedRegisters, cpu->gprs, sizeof(gba->cachedRegisters));
 207					++gba->idleDetectionStep;
 208					break;
 209				case 1:
 210					if (memcmp(gba->cachedRegisters, cpu->gprs, sizeof(gba->cachedRegisters))) {
 211						gba->idleDetectionStep = -1;
 212						++gba->idleDetectionFailures;
 213						if (gba->idleDetectionFailures > IDLE_LOOP_THRESHOLD) {
 214							gba->idleOptimization = IDLE_LOOP_IGNORE;
 215						}
 216						break;
 217					}
 218					_analyzeForIdleLoop(gba, cpu, address);
 219					break;
 220				}
 221			} else {
 222				gba->idleDetectionStep = 0;
 223			}
 224		}
 225	}
 226
 227	gba->lastJump = address;
 228	if (newRegion == memory->activeRegion) {
 229		return;
 230	}
 231
 232	if (memory->activeRegion == REGION_BIOS) {
 233		memory->biosPrefetch = cpu->prefetch[1];
 234	}
 235	memory->activeRegion = newRegion;
 236	switch (address & ~OFFSET_MASK) {
 237	case BASE_BIOS:
 238		cpu->memory.activeRegion = memory->bios;
 239		cpu->memory.activeMask = SIZE_BIOS - 1;
 240		break;
 241	case BASE_WORKING_RAM:
 242		cpu->memory.activeRegion = memory->wram;
 243		cpu->memory.activeMask = SIZE_WORKING_RAM - 1;
 244		break;
 245	case BASE_WORKING_IRAM:
 246		cpu->memory.activeRegion = memory->iwram;
 247		cpu->memory.activeMask = SIZE_WORKING_IRAM - 1;
 248		break;
 249	case BASE_VRAM:
 250		cpu->memory.activeRegion = (uint32_t*) gba->video.renderer->vram;
 251		cpu->memory.activeMask = 0x0000FFFF;
 252		break;
 253	case BASE_CART0:
 254	case BASE_CART0_EX:
 255	case BASE_CART1:
 256	case BASE_CART1_EX:
 257	case BASE_CART2:
 258	case BASE_CART2_EX:
 259		cpu->memory.activeRegion = memory->rom;
 260		cpu->memory.activeMask = SIZE_CART0 - 1;
 261		break;
 262	default:
 263		cpu->memory.activeRegion = _deadbeef;
 264		cpu->memory.activeMask = 0;
 265		GBALog(gba, GBA_LOG_FATAL, "Jumped to invalid address");
 266		break;
 267	}
 268	cpu->memory.activeSeqCycles32 = memory->waitstatesPrefetchSeq32[memory->activeRegion];
 269	cpu->memory.activeSeqCycles16 = memory->waitstatesPrefetchSeq16[memory->activeRegion];
 270	cpu->memory.activeNonseqCycles32 = memory->waitstatesPrefetchNonseq32[memory->activeRegion];
 271	cpu->memory.activeNonseqCycles16 = memory->waitstatesPrefetchNonseq16[memory->activeRegion];
 272	cpu->memory.activeUncachedCycles32 = memory->waitstatesNonseq32[memory->activeRegion];
 273	cpu->memory.activeUncachedCycles16 = memory->waitstatesNonseq16[memory->activeRegion];
 274}
 275
 276#define LOAD_BAD \
 277	GBALog(gba, GBA_LOG_GAME_ERROR, "Bad memory Load32: 0x%08X", address); \
 278	if (cpu->cycles >= cpu->nextEvent) { \
 279		value = gba->bus; \
 280	} else { \
 281		value = cpu->prefetch[1]; \
 282		if (cpu->executionMode == MODE_THUMB) { \
 283			value |= value << 16; \
 284		} \
 285	}
 286
 287#define LOAD_BIOS \
 288	if (address < SIZE_BIOS) { \
 289		if (memory->activeRegion == REGION_BIOS) { \
 290			LOAD_32(value, address, memory->bios); \
 291		} else { \
 292			GBALog(gba, GBA_LOG_GAME_ERROR, "Bad BIOS Load32: 0x%08X", address); \
 293			value = memory->biosPrefetch; \
 294		} \
 295	} else { \
 296		LOAD_BAD; \
 297	}
 298
 299#define LOAD_WORKING_RAM \
 300	LOAD_32(value, address & (SIZE_WORKING_RAM - 1), memory->wram); \
 301	wait += waitstatesRegion[REGION_WORKING_RAM];
 302
 303#define LOAD_WORKING_IRAM LOAD_32(value, address & (SIZE_WORKING_IRAM - 1), memory->iwram);
 304#define LOAD_IO value = GBAIORead(gba, (address & (SIZE_IO - 1)) & ~2) | (GBAIORead(gba, (address & (SIZE_IO - 1)) | 2) << 16);
 305
 306#define LOAD_PALETTE_RAM \
 307	LOAD_32(value, address & (SIZE_PALETTE_RAM - 1), gba->video.palette); \
 308	++wait;
 309
 310#define LOAD_VRAM \
 311	if ((address & 0x0001FFFF) < SIZE_VRAM) { \
 312		LOAD_32(value, address & 0x0001FFFF, gba->video.renderer->vram); \
 313	} else { \
 314		LOAD_32(value, address & 0x00017FFF, gba->video.renderer->vram); \
 315	} \
 316	++wait;
 317
 318#define LOAD_OAM LOAD_32(value, address & (SIZE_OAM - 1), gba->video.oam.raw);
 319
 320#define LOAD_CART \
 321	wait += waitstatesRegion[address >> BASE_OFFSET]; \
 322	if ((address & (SIZE_CART0 - 1)) < memory->romSize) { \
 323		LOAD_32(value, address & (SIZE_CART0 - 1), memory->rom); \
 324	} else { \
 325		GBALog(gba, GBA_LOG_GAME_ERROR, "Out of bounds ROM Load32: 0x%08X", address); \
 326		value = (address >> 1) & 0xFFFF; \
 327		value |= value << 16; \
 328	}
 329
 330#define LOAD_SRAM \
 331	wait = memory->waitstatesNonseq16[address >> BASE_OFFSET]; \
 332	value = GBALoad8(cpu, address, 0); \
 333	value |= value << 8; \
 334	value |= value << 16;
 335
 336uint32_t GBALoad32(struct ARMCore* cpu, uint32_t address, int* cycleCounter) {
 337	struct GBA* gba = (struct GBA*) cpu->master;
 338	struct GBAMemory* memory = &gba->memory;
 339	uint32_t value = 0;
 340	int wait = 0;
 341	char* waitstatesRegion = memory->waitstatesNonseq32;
 342
 343	switch (address >> BASE_OFFSET) {
 344	case REGION_BIOS:
 345		LOAD_BIOS;
 346		break;
 347	case REGION_WORKING_RAM:
 348		LOAD_WORKING_RAM;
 349		break;
 350	case REGION_WORKING_IRAM:
 351		LOAD_WORKING_IRAM;
 352		break;
 353	case REGION_IO:
 354		LOAD_IO;
 355		break;
 356	case REGION_PALETTE_RAM:
 357		LOAD_PALETTE_RAM;
 358		break;
 359	case REGION_VRAM:
 360		LOAD_VRAM;
 361		break;
 362	case REGION_OAM:
 363		LOAD_OAM;
 364		break;
 365	case REGION_CART0:
 366	case REGION_CART0_EX:
 367	case REGION_CART1:
 368	case REGION_CART1_EX:
 369	case REGION_CART2:
 370	case REGION_CART2_EX:
 371		LOAD_CART;
 372		break;
 373	case REGION_CART_SRAM:
 374	case REGION_CART_SRAM_MIRROR:
 375		LOAD_SRAM;
 376		break;
 377	default:
 378		LOAD_BAD;
 379		break;
 380	}
 381
 382	if (cycleCounter) {
 383		*cycleCounter += 2 + wait;
 384	}
 385	// Unaligned 32-bit loads are "rotated" so they make some semblance of sense
 386	int rotate = (address & 3) << 3;
 387	return ROR(value, rotate);
 388}
 389
 390uint32_t GBALoad16(struct ARMCore* cpu, uint32_t address, int* cycleCounter) {
 391	struct GBA* gba = (struct GBA*) cpu->master;
 392	struct GBAMemory* memory = &gba->memory;
 393	uint32_t value = 0;
 394	int wait = 0;
 395
 396	switch (address >> BASE_OFFSET) {
 397	case REGION_BIOS:
 398		if (address < SIZE_BIOS) {
 399			if (memory->activeRegion == REGION_BIOS) {
 400				LOAD_16(value, address, memory->bios);
 401			} else {
 402				GBALog(gba, GBA_LOG_GAME_ERROR, "Bad BIOS Load16: 0x%08X", address);
 403				LOAD_16(value, address & 2, &memory->biosPrefetch);
 404			}
 405		} else {
 406			GBALog(gba, GBA_LOG_GAME_ERROR, "Bad memory Load16: 0x%08X", address);
 407			if (cpu->cycles >= cpu->nextEvent) {
 408				LOAD_16(value, address & 2, &gba->bus);
 409			} else {
 410				LOAD_16(value, address & 2, &cpu->prefetch[1]);
 411			}
 412		}
 413		break;
 414	case REGION_WORKING_RAM:
 415		LOAD_16(value, address & (SIZE_WORKING_RAM - 1), memory->wram);
 416		wait = memory->waitstatesNonseq16[REGION_WORKING_RAM];
 417		break;
 418	case REGION_WORKING_IRAM:
 419		LOAD_16(value, address & (SIZE_WORKING_IRAM - 1), memory->iwram);
 420		break;
 421	case REGION_IO:
 422		value = GBAIORead(gba, address & (SIZE_IO - 1));
 423		break;
 424	case REGION_PALETTE_RAM:
 425		LOAD_16(value, address & (SIZE_PALETTE_RAM - 1), gba->video.palette);
 426		break;
 427	case REGION_VRAM:
 428		if ((address & 0x0001FFFF) < SIZE_VRAM) {
 429			LOAD_16(value, address & 0x0001FFFF, gba->video.renderer->vram);
 430		} else {
 431			LOAD_16(value, address & 0x00017FFF, gba->video.renderer->vram);
 432		}
 433		break;
 434	case REGION_OAM:
 435		LOAD_16(value, address & (SIZE_OAM - 1), gba->video.oam.raw);
 436		break;
 437	case REGION_CART0:
 438	case REGION_CART0_EX:
 439	case REGION_CART1:
 440	case REGION_CART1_EX:
 441	case REGION_CART2:
 442		wait = memory->waitstatesNonseq16[address >> BASE_OFFSET];
 443		if ((address & (SIZE_CART0 - 1)) < memory->romSize) {
 444			LOAD_16(value, address & (SIZE_CART0 - 1), memory->rom);
 445		} else {
 446			GBALog(gba, GBA_LOG_GAME_ERROR, "Out of bounds ROM Load16: 0x%08X", address);
 447			value = (address >> 1) & 0xFFFF; \
 448		}
 449		break;
 450	case REGION_CART2_EX:
 451		wait = memory->waitstatesNonseq16[address >> BASE_OFFSET];
 452		if (memory->savedata.type == SAVEDATA_EEPROM) {
 453			value = GBASavedataReadEEPROM(&memory->savedata);
 454		} else if ((address & (SIZE_CART0 - 1)) < memory->romSize) {
 455			LOAD_16(value, address & (SIZE_CART0 - 1), memory->rom);
 456		} else {
 457			GBALog(gba, GBA_LOG_GAME_ERROR, "Out of bounds ROM Load16: 0x%08X", address);
 458			value = (address >> 1) & 0xFFFF; \
 459		}
 460		break;
 461	case REGION_CART_SRAM:
 462	case REGION_CART_SRAM_MIRROR:
 463		wait = memory->waitstatesNonseq16[address >> BASE_OFFSET];
 464		value = GBALoad8(cpu, address, 0);
 465		value |= value << 8;
 466		break;
 467	default:
 468		GBALog(gba, GBA_LOG_GAME_ERROR, "Bad memory Load16: 0x%08X", address);
 469		if (cpu->cycles >= cpu->nextEvent) {
 470			LOAD_16(value, address & 2, &gba->bus);
 471		} else {
 472			LOAD_16(value, address & 2, &cpu->prefetch[1]);
 473		}
 474		break;
 475	}
 476
 477	if (cycleCounter) {
 478		*cycleCounter += 2 + wait;
 479	}
 480	// Unaligned 16-bit loads are "unpredictable", but the GBA rotates them, so we have to, too.
 481	int rotate = (address & 1) << 3;
 482	return ROR(value, rotate);
 483}
 484
 485uint32_t GBALoad8(struct ARMCore* cpu, uint32_t address, int* cycleCounter) {
 486	struct GBA* gba = (struct GBA*) cpu->master;
 487	struct GBAMemory* memory = &gba->memory;
 488	uint8_t value = 0;
 489	int wait = 0;
 490
 491	switch (address >> BASE_OFFSET) {
 492	case REGION_BIOS:
 493		if (address < SIZE_BIOS) {
 494			if (memory->activeRegion == REGION_BIOS) {
 495				value = ((int8_t*) memory->bios)[address];
 496			} else {
 497				GBALog(gba, GBA_LOG_GAME_ERROR, "Bad BIOS Load8: 0x%08X", address);
 498				value = ((uint8_t*) &memory->biosPrefetch)[address & 3];
 499			}
 500		} else {
 501			GBALog(gba, GBA_LOG_GAME_ERROR, "Bad memory Load8: 0x%08x", address);
 502			if (cpu->cycles >= cpu->nextEvent) {
 503				value = ((uint8_t*) &gba->bus)[address & 3];
 504			} else {
 505				value = ((uint8_t*) &cpu->prefetch[1])[address & 3];
 506			}
 507		}
 508		break;
 509	case REGION_WORKING_RAM:
 510		value = ((int8_t*) memory->wram)[address & (SIZE_WORKING_RAM - 1)];
 511		wait = memory->waitstatesNonseq16[REGION_WORKING_RAM];
 512		break;
 513	case REGION_WORKING_IRAM:
 514		value = ((int8_t*) memory->iwram)[address & (SIZE_WORKING_IRAM - 1)];
 515		break;
 516	case REGION_IO:
 517		value = (GBAIORead(gba, address & 0xFFFE) >> ((address & 0x0001) << 3)) & 0xFF;
 518		break;
 519	case REGION_PALETTE_RAM:
 520		value = ((int8_t*) gba->video.palette)[address & (SIZE_PALETTE_RAM - 1)];
 521		break;
 522	case REGION_VRAM:
 523		if ((address & 0x0001FFFF) < SIZE_VRAM) {
 524			value = ((int8_t*) gba->video.renderer->vram)[address & 0x0001FFFF];
 525		} else {
 526			value = ((int8_t*) gba->video.renderer->vram)[address & 0x00017FFF];
 527		}
 528		break;
 529	case REGION_OAM:
 530		GBALog(gba, GBA_LOG_STUB, "Unimplemented memory Load8: 0x%08X", address);
 531		break;
 532	case REGION_CART0:
 533	case REGION_CART0_EX:
 534	case REGION_CART1:
 535	case REGION_CART1_EX:
 536	case REGION_CART2:
 537	case REGION_CART2_EX:
 538		wait = memory->waitstatesNonseq16[address >> BASE_OFFSET];
 539		if ((address & (SIZE_CART0 - 1)) < memory->romSize) {
 540			value = ((int8_t*) memory->rom)[address & (SIZE_CART0 - 1)];
 541		} else {
 542			GBALog(gba, GBA_LOG_GAME_ERROR, "Out of bounds ROM Load8: 0x%08X", address);
 543			value = (address >> 1) & 0xFF; \
 544		}
 545		break;
 546	case REGION_CART_SRAM:
 547	case REGION_CART_SRAM_MIRROR:
 548		wait = memory->waitstatesNonseq16[address >> BASE_OFFSET];
 549		if (memory->savedata.type == SAVEDATA_AUTODETECT) {
 550			GBALog(gba, GBA_LOG_INFO, "Detected SRAM savegame");
 551			GBASavedataInitSRAM(&memory->savedata);
 552		}
 553		if (memory->savedata.type == SAVEDATA_SRAM) {
 554			value = memory->savedata.data[address & (SIZE_CART_SRAM - 1)];
 555		} else if (memory->savedata.type == SAVEDATA_FLASH512 || memory->savedata.type == SAVEDATA_FLASH1M) {
 556			value = GBASavedataReadFlash(&memory->savedata, address);
 557		} else if (memory->gpio.gpioDevices & GPIO_TILT) {
 558			value = GBAGPIOTiltRead(&memory->gpio, address & OFFSET_MASK);
 559		} else {
 560			GBALog(gba, GBA_LOG_GAME_ERROR, "Reading from non-existent SRAM: 0x%08X", address);
 561			value = 0xFF;
 562		}
 563		break;
 564	default:
 565		GBALog(gba, GBA_LOG_GAME_ERROR, "Bad memory Load8: 0x%08x", address);
 566		if (cpu->cycles >= cpu->nextEvent) {
 567			value = ((uint8_t*) &gba->bus)[address & 3];
 568		} else {
 569			value = ((uint8_t*) &cpu->prefetch[1])[address & 3];
 570		}
 571		break;
 572	}
 573
 574	if (cycleCounter) {
 575		*cycleCounter += 2 + wait;
 576	}
 577	return value;
 578}
 579
 580#define STORE_WORKING_RAM \
 581	STORE_32(value, address & (SIZE_WORKING_RAM - 1), memory->wram); \
 582	wait += waitstatesRegion[REGION_WORKING_RAM];
 583
 584#define STORE_WORKING_IRAM \
 585	STORE_32(value, address & (SIZE_WORKING_IRAM - 1), memory->iwram);
 586
 587#define STORE_IO \
 588	GBAIOWrite32(gba, address & (SIZE_IO - 1), value);
 589
 590#define STORE_PALETTE_RAM \
 591	STORE_32(value, address & (SIZE_PALETTE_RAM - 1), gba->video.palette); \
 592	gba->video.renderer->writePalette(gba->video.renderer, (address & (SIZE_PALETTE_RAM - 1)) + 2, value >> 16); \
 593	++wait; \
 594	gba->video.renderer->writePalette(gba->video.renderer, address & (SIZE_PALETTE_RAM - 1), value);
 595
 596#define STORE_VRAM \
 597	if ((address & 0x0001FFFF) < SIZE_VRAM) { \
 598		STORE_32(value, address & 0x0001FFFF, gba->video.renderer->vram); \
 599	} else { \
 600		STORE_32(value, address & 0x00017FFF, gba->video.renderer->vram); \
 601	} \
 602	++wait;
 603
 604#define STORE_OAM \
 605	STORE_32(value, address & (SIZE_OAM - 1), gba->video.oam.raw); \
 606	gba->video.renderer->writeOAM(gba->video.renderer, (address & (SIZE_OAM - 4)) >> 1); \
 607	gba->video.renderer->writeOAM(gba->video.renderer, ((address & (SIZE_OAM - 4)) >> 1) + 1);
 608
 609#define STORE_CART \
 610	GBALog(gba, GBA_LOG_STUB, "Unimplemented memory Store32: 0x%08X", address);
 611
 612#define STORE_SRAM \
 613	GBALog(gba, GBA_LOG_STUB, "Unimplemented memory Store32: 0x%08X", address);
 614
 615#define STORE_BAD \
 616	GBALog(gba, GBA_LOG_GAME_ERROR, "Bad memory Store32: 0x%08X", address);
 617
 618void GBAStore32(struct ARMCore* cpu, uint32_t address, int32_t value, int* cycleCounter) {
 619	struct GBA* gba = (struct GBA*) cpu->master;
 620	struct GBAMemory* memory = &gba->memory;
 621	int wait = 0;
 622	char* waitstatesRegion = memory->waitstatesNonseq32;
 623
 624	switch (address >> BASE_OFFSET) {
 625	case REGION_WORKING_RAM:
 626		STORE_WORKING_RAM;
 627		break;
 628	case REGION_WORKING_IRAM:
 629		STORE_WORKING_IRAM
 630		break;
 631	case REGION_IO:
 632		STORE_IO;
 633		break;
 634	case REGION_PALETTE_RAM:
 635		STORE_PALETTE_RAM;
 636		break;
 637	case REGION_VRAM:
 638		STORE_VRAM;
 639		break;
 640	case REGION_OAM:
 641		STORE_OAM;
 642		break;
 643	case REGION_CART0:
 644	case REGION_CART0_EX:
 645	case REGION_CART1:
 646	case REGION_CART1_EX:
 647	case REGION_CART2:
 648	case REGION_CART2_EX:
 649		STORE_CART;
 650		break;
 651	case REGION_CART_SRAM:
 652	case REGION_CART_SRAM_MIRROR:
 653		STORE_SRAM;
 654		break;
 655	default:
 656		STORE_BAD;
 657		break;
 658	}
 659
 660	if (cycleCounter) {
 661		*cycleCounter += 1 + wait;
 662	}
 663}
 664
 665void GBAStore16(struct ARMCore* cpu, uint32_t address, int16_t value, int* cycleCounter) {
 666	struct GBA* gba = (struct GBA*) cpu->master;
 667	struct GBAMemory* memory = &gba->memory;
 668	int wait = 0;
 669
 670	switch (address >> BASE_OFFSET) {
 671	case REGION_WORKING_RAM:
 672		STORE_16(value, address & (SIZE_WORKING_RAM - 1), memory->wram);
 673		wait = memory->waitstatesNonseq16[REGION_WORKING_RAM];
 674		break;
 675	case REGION_WORKING_IRAM:
 676		STORE_16(value, address & (SIZE_WORKING_IRAM - 1), memory->iwram);
 677		break;
 678	case REGION_IO:
 679		GBAIOWrite(gba, address & (SIZE_IO - 1), value);
 680		break;
 681	case REGION_PALETTE_RAM:
 682		STORE_16(value, address & (SIZE_PALETTE_RAM - 1), gba->video.palette);
 683		gba->video.renderer->writePalette(gba->video.renderer, address & (SIZE_PALETTE_RAM - 1), value);
 684		break;
 685	case REGION_VRAM:
 686		if ((address & 0x0001FFFF) < SIZE_VRAM) {
 687			STORE_16(value, address & 0x0001FFFF, gba->video.renderer->vram);
 688		} else {
 689			STORE_16(value, address & 0x00017FFF, gba->video.renderer->vram);
 690		}
 691		break;
 692	case REGION_OAM:
 693		STORE_16(value, address & (SIZE_OAM - 1), gba->video.oam.raw);
 694		gba->video.renderer->writeOAM(gba->video.renderer, (address & (SIZE_OAM - 1)) >> 1);
 695		break;
 696	case REGION_CART0:
 697		if (memory->gpio.gpioDevices != GPIO_NONE && IS_GPIO_REGISTER(address & 0xFFFFFF)) {
 698			uint32_t reg = address & 0xFFFFFF;
 699			GBAGPIOWrite(&memory->gpio, reg, value);
 700		} else {
 701			GBALog(gba, GBA_LOG_GAME_ERROR, "Bad cartridge Store16: 0x%08X", address);
 702		}
 703		break;
 704	case REGION_CART2_EX:
 705		if (memory->savedata.type == SAVEDATA_AUTODETECT) {
 706			GBALog(gba, GBA_LOG_INFO, "Detected EEPROM savegame");
 707			GBASavedataInitEEPROM(&memory->savedata);
 708		}
 709		GBASavedataWriteEEPROM(&memory->savedata, value, 1);
 710		break;
 711	case REGION_CART_SRAM:
 712	case REGION_CART_SRAM_MIRROR:
 713		GBALog(gba, GBA_LOG_STUB, "Unimplemented memory Store16: 0x%08X", address);
 714		break;
 715	default:
 716		GBALog(gba, GBA_LOG_GAME_ERROR, "Bad memory Store16: 0x%08X", address);
 717		break;
 718	}
 719
 720	if (cycleCounter) {
 721		*cycleCounter += 1 + wait;
 722	}
 723}
 724
 725void GBAStore8(struct ARMCore* cpu, uint32_t address, int8_t value, int* cycleCounter) {
 726	struct GBA* gba = (struct GBA*) cpu->master;
 727	struct GBAMemory* memory = &gba->memory;
 728	int wait = 0;
 729
 730	switch (address >> BASE_OFFSET) {
 731	case REGION_WORKING_RAM:
 732		((int8_t*) memory->wram)[address & (SIZE_WORKING_RAM - 1)] = value;
 733		wait = memory->waitstatesNonseq16[REGION_WORKING_RAM];
 734		break;
 735	case REGION_WORKING_IRAM:
 736		((int8_t*) memory->iwram)[address & (SIZE_WORKING_IRAM - 1)] = value;
 737		break;
 738	case REGION_IO:
 739		GBAIOWrite8(gba, address & (SIZE_IO - 1), value);
 740		break;
 741	case REGION_PALETTE_RAM:
 742		GBALog(gba, GBA_LOG_STUB, "Unimplemented memory Store8: 0x%08X", address);
 743		break;
 744	case REGION_VRAM:
 745		if (address >= 0x06018000) {
 746			// TODO: check BG mode
 747			GBALog(gba, GBA_LOG_GAME_ERROR, "Cannot Store8 to OBJ: 0x%08X", address);
 748			break;
 749		}
 750		((int8_t*) gba->video.renderer->vram)[address & 0x1FFFE] = value;
 751		((int8_t*) gba->video.renderer->vram)[(address & 0x1FFFE) | 1] = value;
 752		break;
 753	case REGION_OAM:
 754		GBALog(gba, GBA_LOG_GAME_ERROR, "Cannot Store8 to OAM: 0x%08X", address);
 755		break;
 756	case REGION_CART0:
 757		GBALog(gba, GBA_LOG_STUB, "Unimplemented memory Store8: 0x%08X", address);
 758		break;
 759	case REGION_CART_SRAM:
 760	case REGION_CART_SRAM_MIRROR:
 761		if (memory->savedata.type == SAVEDATA_AUTODETECT) {
 762			if (address == SAVEDATA_FLASH_BASE) {
 763				GBALog(gba, GBA_LOG_INFO, "Detected Flash savegame");
 764				GBASavedataInitFlash(&memory->savedata);
 765			} else {
 766				GBALog(gba, GBA_LOG_INFO, "Detected SRAM savegame");
 767				GBASavedataInitSRAM(&memory->savedata);
 768			}
 769		}
 770		if (memory->savedata.type == SAVEDATA_FLASH512 || memory->savedata.type == SAVEDATA_FLASH1M) {
 771			GBASavedataWriteFlash(&memory->savedata, address, value);
 772		} else if (memory->savedata.type == SAVEDATA_SRAM) {
 773			memory->savedata.data[address & (SIZE_CART_SRAM - 1)] = value;
 774		} else if (memory->gpio.gpioDevices & GPIO_TILT) {
 775			GBAGPIOTiltWrite(&memory->gpio, address & OFFSET_MASK, value);
 776		} else {
 777			GBALog(gba, GBA_LOG_GAME_ERROR, "Writing to non-existent SRAM: 0x%08X", address);
 778		}
 779		wait = memory->waitstatesNonseq16[REGION_CART_SRAM];
 780		break;
 781	default:
 782		GBALog(gba, GBA_LOG_GAME_ERROR, "Bad memory Store8: 0x%08X", address);
 783		break;
 784	}
 785
 786	if (cycleCounter) {
 787		*cycleCounter += 1 + wait;
 788	}
 789}
 790
 791#define LDM_LOOP(LDM) \
 792	for (i = 0; i < 16; i += 4) { \
 793		if (UNLIKELY(mask & (1 << i))) { \
 794			LDM; \
 795			waitstatesRegion = memory->waitstatesSeq32; \
 796			cpu->gprs[i] = value; \
 797			++wait; \
 798			address += 4; \
 799		} \
 800		if (UNLIKELY(mask & (2 << i))) { \
 801			LDM; \
 802			waitstatesRegion = memory->waitstatesSeq32; \
 803			cpu->gprs[i + 1] = value; \
 804			++wait; \
 805			address += 4; \
 806		} \
 807		if (UNLIKELY(mask & (4 << i))) { \
 808			LDM; \
 809			waitstatesRegion = memory->waitstatesSeq32; \
 810			cpu->gprs[i + 2] = value; \
 811			++wait; \
 812			address += 4; \
 813		} \
 814		if (UNLIKELY(mask & (8 << i))) { \
 815			LDM; \
 816			waitstatesRegion = memory->waitstatesSeq32; \
 817			cpu->gprs[i + 3] = value; \
 818			++wait; \
 819			address += 4; \
 820		} \
 821	}
 822
 823uint32_t GBALoadMultiple(struct ARMCore* cpu, uint32_t address, int mask, enum LSMDirection direction, int* cycleCounter) {
 824	struct GBA* gba = (struct GBA*) cpu->master;
 825	struct GBAMemory* memory = &gba->memory;
 826	uint32_t value;
 827	int wait = 0;
 828	char* waitstatesRegion = memory->waitstatesNonseq32;
 829
 830	int i;
 831	int offset = 4;
 832	int popcount = 0;
 833	if (direction & LSM_D) {
 834		offset = -4;
 835		popcount = _popcount32(mask);
 836		address -= (popcount << 2) - 4;
 837	}
 838
 839	if (direction & LSM_B) {
 840		address += offset;
 841	}
 842
 843	uint32_t addressMisalign = address & 0x3;
 844	address &= 0xFFFFFFFC;
 845
 846	switch (address >> BASE_OFFSET) {
 847	case REGION_BIOS:
 848		LDM_LOOP(LOAD_BIOS);
 849		break;
 850	case REGION_WORKING_RAM:
 851		LDM_LOOP(LOAD_WORKING_RAM);
 852		break;
 853	case REGION_WORKING_IRAM:
 854		LDM_LOOP(LOAD_WORKING_IRAM);
 855		break;
 856	case REGION_IO:
 857		LDM_LOOP(LOAD_IO);
 858		break;
 859	case REGION_PALETTE_RAM:
 860		LDM_LOOP(LOAD_PALETTE_RAM);
 861		break;
 862	case REGION_VRAM:
 863		LDM_LOOP(LOAD_VRAM);
 864		break;
 865	case REGION_OAM:
 866		LDM_LOOP(LOAD_OAM);
 867		break;
 868	case REGION_CART0:
 869	case REGION_CART0_EX:
 870	case REGION_CART1:
 871	case REGION_CART1_EX:
 872	case REGION_CART2:
 873	case REGION_CART2_EX:
 874		LDM_LOOP(LOAD_CART);
 875		break;
 876	case REGION_CART_SRAM:
 877	case REGION_CART_SRAM_MIRROR:
 878		LDM_LOOP(LOAD_SRAM);
 879		break;
 880	default:
 881		LDM_LOOP(LOAD_BAD);
 882		break;
 883	}
 884
 885	if (cycleCounter) {
 886		*cycleCounter += wait;
 887	}
 888
 889	if (direction & LSM_B) {
 890		address -= offset;
 891	}
 892
 893	if (direction & LSM_D) {
 894		address -= (popcount << 2) + 4;
 895	}
 896
 897	return address | addressMisalign;
 898}
 899
 900#define STM_LOOP(STM) \
 901	for (i = 0; i < 16; i += 4) { \
 902		if (UNLIKELY(mask & (1 << i))) { \
 903			value = cpu->gprs[i]; \
 904			STM; \
 905			waitstatesRegion = memory->waitstatesSeq32; \
 906			++wait; \
 907			address += 4; \
 908		} \
 909		if (UNLIKELY(mask & (2 << i))) { \
 910			value = cpu->gprs[i + 1]; \
 911			STM; \
 912			waitstatesRegion = memory->waitstatesSeq32; \
 913			++wait; \
 914			address += 4; \
 915		} \
 916		if (UNLIKELY(mask & (4 << i))) { \
 917			value = cpu->gprs[i + 2]; \
 918			STM; \
 919			waitstatesRegion = memory->waitstatesSeq32; \
 920			++wait; \
 921			address += 4; \
 922		} \
 923		if (UNLIKELY(mask & (8 << i))) { \
 924			value = cpu->gprs[i + 3]; \
 925			STM; \
 926			waitstatesRegion = memory->waitstatesSeq32; \
 927			++wait; \
 928			address += 4; \
 929		} \
 930	}
 931
 932uint32_t GBAStoreMultiple(struct ARMCore* cpu, uint32_t address, int mask, enum LSMDirection direction, int* cycleCounter) {
 933	struct GBA* gba = (struct GBA*) cpu->master;
 934	struct GBAMemory* memory = &gba->memory;
 935	uint32_t value;
 936	int wait = 0;
 937	char* waitstatesRegion = memory->waitstatesNonseq32;
 938
 939	int i;
 940	int offset = 4;
 941	int popcount = 0;
 942	if (direction & LSM_D) {
 943		offset = -4;
 944		popcount = _popcount32(mask);
 945		address -= (popcount << 2) - 4;
 946	}
 947
 948	if (direction & LSM_B) {
 949		address += offset;
 950	}
 951
 952	uint32_t addressMisalign = address & 0x3;
 953	address &= 0xFFFFFFFC;
 954
 955	switch (address >> BASE_OFFSET) {
 956	case REGION_WORKING_RAM:
 957		STM_LOOP(STORE_WORKING_RAM);
 958		break;
 959	case REGION_WORKING_IRAM:
 960		STM_LOOP(STORE_WORKING_IRAM);
 961		break;
 962	case REGION_IO:
 963		STM_LOOP(STORE_IO);
 964		break;
 965	case REGION_PALETTE_RAM:
 966		STM_LOOP(STORE_PALETTE_RAM);
 967		break;
 968	case REGION_VRAM:
 969		STM_LOOP(STORE_VRAM);
 970		break;
 971	case REGION_OAM:
 972		STM_LOOP(STORE_OAM);
 973		break;
 974	case REGION_CART0:
 975	case REGION_CART0_EX:
 976	case REGION_CART1:
 977	case REGION_CART1_EX:
 978	case REGION_CART2:
 979	case REGION_CART2_EX:
 980		STM_LOOP(STORE_CART);
 981		break;
 982	case REGION_CART_SRAM:
 983	case REGION_CART_SRAM_MIRROR:
 984		STM_LOOP(STORE_SRAM);
 985		break;
 986	default:
 987		STM_LOOP(STORE_BAD);
 988		break;
 989	}
 990
 991	if (cycleCounter) {
 992		*cycleCounter += wait;
 993	}
 994
 995	if (direction & LSM_B) {
 996		address -= offset;
 997	}
 998
 999	if (direction & LSM_D) {
1000		address -= (popcount << 2) + 4;
1001	}
1002
1003	return address | addressMisalign;
1004}
1005
1006void GBAAdjustWaitstates(struct GBA* gba, uint16_t parameters) {
1007	struct GBAMemory* memory = &gba->memory;
1008	struct ARMCore* cpu = gba->cpu;
1009	int sram = parameters & 0x0003;
1010	int ws0 = (parameters & 0x000C) >> 2;
1011	int ws0seq = (parameters & 0x0010) >> 4;
1012	int ws1 = (parameters & 0x0060) >> 5;
1013	int ws1seq = (parameters & 0x0080) >> 7;
1014	int ws2 = (parameters & 0x0300) >> 8;
1015	int ws2seq = (parameters & 0x0400) >> 10;
1016	int prefetch = parameters & 0x4000;
1017
1018	memory->waitstatesNonseq16[REGION_CART_SRAM] = memory->waitstatesNonseq16[REGION_CART_SRAM_MIRROR] =  GBA_ROM_WAITSTATES[sram];
1019	memory->waitstatesSeq16[REGION_CART_SRAM] = memory->waitstatesSeq16[REGION_CART_SRAM_MIRROR] = GBA_ROM_WAITSTATES[sram];
1020	memory->waitstatesNonseq32[REGION_CART_SRAM] = memory->waitstatesNonseq32[REGION_CART_SRAM_MIRROR] = 2 * GBA_ROM_WAITSTATES[sram] + 1;
1021	memory->waitstatesSeq32[REGION_CART_SRAM] = memory->waitstatesSeq32[REGION_CART_SRAM_MIRROR] = 2 * GBA_ROM_WAITSTATES[sram] + 1;
1022
1023	memory->waitstatesNonseq16[REGION_CART0] = memory->waitstatesNonseq16[REGION_CART0_EX] = GBA_ROM_WAITSTATES[ws0];
1024	memory->waitstatesNonseq16[REGION_CART1] = memory->waitstatesNonseq16[REGION_CART1_EX] = GBA_ROM_WAITSTATES[ws1];
1025	memory->waitstatesNonseq16[REGION_CART2] = memory->waitstatesNonseq16[REGION_CART2_EX] = GBA_ROM_WAITSTATES[ws2];
1026
1027	memory->waitstatesSeq16[REGION_CART0] = memory->waitstatesSeq16[REGION_CART0_EX] = GBA_ROM_WAITSTATES_SEQ[ws0seq];
1028	memory->waitstatesSeq16[REGION_CART1] = memory->waitstatesSeq16[REGION_CART1_EX] = GBA_ROM_WAITSTATES_SEQ[ws1seq + 2];
1029	memory->waitstatesSeq16[REGION_CART2] = memory->waitstatesSeq16[REGION_CART2_EX] = GBA_ROM_WAITSTATES_SEQ[ws2seq + 4];
1030
1031	memory->waitstatesNonseq32[REGION_CART0] = memory->waitstatesNonseq32[REGION_CART0_EX] = memory->waitstatesSeq16[REGION_CART0] + 1 + memory->waitstatesSeq16[REGION_CART0];
1032	memory->waitstatesNonseq32[REGION_CART1] = memory->waitstatesNonseq32[REGION_CART1_EX] = memory->waitstatesSeq16[REGION_CART1] + 1 + memory->waitstatesSeq16[REGION_CART1];
1033	memory->waitstatesNonseq32[REGION_CART2] = memory->waitstatesNonseq32[REGION_CART2_EX] = memory->waitstatesSeq16[REGION_CART2] + 1 + memory->waitstatesSeq16[REGION_CART2];
1034
1035	memory->waitstatesSeq32[REGION_CART0] = memory->waitstatesSeq32[REGION_CART0_EX] = 2 * memory->waitstatesSeq16[REGION_CART0] + 1;
1036	memory->waitstatesSeq32[REGION_CART1] = memory->waitstatesSeq32[REGION_CART1_EX] = 2 * memory->waitstatesSeq16[REGION_CART1] + 1;
1037	memory->waitstatesSeq32[REGION_CART2] = memory->waitstatesSeq32[REGION_CART2_EX] = 2 * memory->waitstatesSeq16[REGION_CART2] + 1;
1038
1039	if (!prefetch) {
1040		memory->waitstatesPrefetchSeq16[REGION_CART0] = memory->waitstatesPrefetchSeq16[REGION_CART0_EX] = memory->waitstatesSeq16[REGION_CART0];
1041		memory->waitstatesPrefetchSeq16[REGION_CART1] = memory->waitstatesPrefetchSeq16[REGION_CART1_EX] = memory->waitstatesSeq16[REGION_CART1];
1042		memory->waitstatesPrefetchSeq16[REGION_CART2] = memory->waitstatesPrefetchSeq16[REGION_CART2_EX] = memory->waitstatesSeq16[REGION_CART2];
1043
1044		memory->waitstatesPrefetchSeq32[REGION_CART0] = memory->waitstatesPrefetchSeq32[REGION_CART0_EX] = memory->waitstatesSeq32[REGION_CART0];
1045		memory->waitstatesPrefetchSeq32[REGION_CART1] = memory->waitstatesPrefetchSeq32[REGION_CART1_EX] = memory->waitstatesSeq32[REGION_CART1];
1046		memory->waitstatesPrefetchSeq32[REGION_CART2] = memory->waitstatesPrefetchSeq32[REGION_CART2_EX] = memory->waitstatesSeq32[REGION_CART2];
1047
1048		memory->waitstatesPrefetchNonseq16[REGION_CART0] = memory->waitstatesPrefetchNonseq16[REGION_CART0_EX] = memory->waitstatesNonseq16[REGION_CART0];
1049		memory->waitstatesPrefetchNonseq16[REGION_CART1] = memory->waitstatesPrefetchNonseq16[REGION_CART1_EX] = memory->waitstatesNonseq16[REGION_CART1];
1050		memory->waitstatesPrefetchNonseq16[REGION_CART2] = memory->waitstatesPrefetchNonseq16[REGION_CART2_EX] = memory->waitstatesNonseq16[REGION_CART2];
1051
1052		memory->waitstatesPrefetchNonseq32[REGION_CART0] = memory->waitstatesPrefetchNonseq32[REGION_CART0_EX] = memory->waitstatesNonseq32[REGION_CART0];
1053		memory->waitstatesPrefetchNonseq32[REGION_CART1] = memory->waitstatesPrefetchNonseq32[REGION_CART1_EX] = memory->waitstatesNonseq32[REGION_CART1];
1054		memory->waitstatesPrefetchNonseq32[REGION_CART2] = memory->waitstatesPrefetchNonseq32[REGION_CART2_EX] = memory->waitstatesNonseq32[REGION_CART2];
1055	} else {
1056		memory->waitstatesPrefetchSeq16[REGION_CART0] = memory->waitstatesPrefetchSeq16[REGION_CART0_EX] = 0;
1057		memory->waitstatesPrefetchSeq16[REGION_CART1] = memory->waitstatesPrefetchSeq16[REGION_CART1_EX] = 0;
1058		memory->waitstatesPrefetchSeq16[REGION_CART2] = memory->waitstatesPrefetchSeq16[REGION_CART2_EX] = 0;
1059
1060		memory->waitstatesPrefetchSeq32[REGION_CART0] = memory->waitstatesPrefetchSeq32[REGION_CART0_EX] = 0;
1061		memory->waitstatesPrefetchSeq32[REGION_CART1] = memory->waitstatesPrefetchSeq32[REGION_CART1_EX] = 0;
1062		memory->waitstatesPrefetchSeq32[REGION_CART2] = memory->waitstatesPrefetchSeq32[REGION_CART2_EX] = 0;
1063
1064		memory->waitstatesPrefetchNonseq16[REGION_CART0] = memory->waitstatesPrefetchNonseq16[REGION_CART0_EX] = 0;
1065		memory->waitstatesPrefetchNonseq16[REGION_CART1] = memory->waitstatesPrefetchNonseq16[REGION_CART1_EX] = 0;
1066		memory->waitstatesPrefetchNonseq16[REGION_CART2] = memory->waitstatesPrefetchNonseq16[REGION_CART2_EX] = 0;
1067
1068		memory->waitstatesPrefetchNonseq32[REGION_CART0] = memory->waitstatesPrefetchNonseq32[REGION_CART0_EX] = 0;
1069		memory->waitstatesPrefetchNonseq32[REGION_CART1] = memory->waitstatesPrefetchNonseq32[REGION_CART1_EX] = 0;
1070		memory->waitstatesPrefetchNonseq32[REGION_CART2] = memory->waitstatesPrefetchNonseq32[REGION_CART2_EX] = 0;
1071	}
1072
1073	cpu->memory.activeSeqCycles32 = memory->waitstatesPrefetchSeq32[memory->activeRegion];
1074	cpu->memory.activeSeqCycles16 = memory->waitstatesPrefetchSeq16[memory->activeRegion];
1075
1076	cpu->memory.activeNonseqCycles32 = memory->waitstatesPrefetchNonseq32[memory->activeRegion];
1077	cpu->memory.activeNonseqCycles16 = memory->waitstatesPrefetchNonseq16[memory->activeRegion];
1078
1079	cpu->memory.activeUncachedCycles32 = memory->waitstatesNonseq32[memory->activeRegion];
1080	cpu->memory.activeUncachedCycles16 = memory->waitstatesNonseq16[memory->activeRegion];
1081}
1082
1083void GBAMemoryWriteDMASAD(struct GBA* gba, int dma, uint32_t address) {
1084	struct GBAMemory* memory = &gba->memory;
1085	memory->dma[dma].source = address & 0x0FFFFFFE;
1086}
1087
1088void GBAMemoryWriteDMADAD(struct GBA* gba, int dma, uint32_t address) {
1089	struct GBAMemory* memory = &gba->memory;
1090	memory->dma[dma].dest = address & 0x0FFFFFFE;
1091}
1092
1093void GBAMemoryWriteDMACNT_LO(struct GBA* gba, int dma, uint16_t count) {
1094	struct GBAMemory* memory = &gba->memory;
1095	memory->dma[dma].count = count ? count : (dma == 3 ? 0x10000 : 0x4000);
1096}
1097
1098uint16_t GBAMemoryWriteDMACNT_HI(struct GBA* gba, int dma, uint16_t control) {
1099	struct GBAMemory* memory = &gba->memory;
1100	struct GBADMA* currentDma = &memory->dma[dma];
1101	int wasEnabled = GBADMARegisterIsEnable(currentDma->reg);
1102	currentDma->reg = control;
1103
1104	if (GBADMARegisterIsDRQ(currentDma->reg)) {
1105		GBALog(gba, GBA_LOG_STUB, "DRQ not implemented");
1106	}
1107
1108	if (!wasEnabled && GBADMARegisterIsEnable(currentDma->reg)) {
1109		currentDma->nextSource = currentDma->source;
1110		currentDma->nextDest = currentDma->dest;
1111		currentDma->nextCount = currentDma->count;
1112		GBAMemoryScheduleDMA(gba, dma, currentDma);
1113	}
1114	// If the DMA has already occurred, this value might have changed since the function started
1115	return currentDma->reg;
1116};
1117
1118void GBAMemoryScheduleDMA(struct GBA* gba, int number, struct GBADMA* info) {
1119	struct ARMCore* cpu = gba->cpu;
1120	switch (GBADMARegisterGetTiming(info->reg)) {
1121	case DMA_TIMING_NOW:
1122		info->nextEvent = cpu->cycles;
1123		GBAMemoryUpdateDMAs(gba, 0);
1124		break;
1125	case DMA_TIMING_HBLANK:
1126		// Handled implicitly
1127		info->nextEvent = INT_MAX;
1128		break;
1129	case DMA_TIMING_VBLANK:
1130		// Handled implicitly
1131		info->nextEvent = INT_MAX;
1132		break;
1133	case DMA_TIMING_CUSTOM:
1134		info->nextEvent = INT_MAX;
1135		switch (number) {
1136		case 0:
1137			GBALog(gba, GBA_LOG_WARN, "Discarding invalid DMA0 scheduling");
1138			break;
1139		case 1:
1140		case 2:
1141			GBAAudioScheduleFifoDma(&gba->audio, number, info);
1142			break;
1143		case 3:
1144			// GBAVideoScheduleVCaptureDma(dma, info);
1145			break;
1146		}
1147	}
1148}
1149
1150void GBAMemoryRunHblankDMAs(struct GBA* gba, int32_t cycles) {
1151	struct GBAMemory* memory = &gba->memory;
1152	struct GBADMA* dma;
1153	int i;
1154	for (i = 0; i < 4; ++i) {
1155		dma = &memory->dma[i];
1156		if (GBADMARegisterIsEnable(dma->reg) && GBADMARegisterGetTiming(dma->reg) == DMA_TIMING_HBLANK) {
1157			dma->nextEvent = cycles;
1158		}
1159	}
1160	GBAMemoryUpdateDMAs(gba, 0);
1161}
1162
1163void GBAMemoryRunVblankDMAs(struct GBA* gba, int32_t cycles) {
1164	struct GBAMemory* memory = &gba->memory;
1165	struct GBADMA* dma;
1166	int i;
1167	for (i = 0; i < 4; ++i) {
1168		dma = &memory->dma[i];
1169		if (GBADMARegisterIsEnable(dma->reg) && GBADMARegisterGetTiming(dma->reg) == DMA_TIMING_VBLANK) {
1170			dma->nextEvent = cycles;
1171		}
1172	}
1173	GBAMemoryUpdateDMAs(gba, 0);
1174}
1175
1176int32_t GBAMemoryRunDMAs(struct GBA* gba, int32_t cycles) {
1177	struct GBAMemory* memory = &gba->memory;
1178	if (memory->nextDMA == INT_MAX) {
1179		return INT_MAX;
1180	}
1181	memory->nextDMA -= cycles;
1182	memory->eventDiff += cycles;
1183	if (memory->nextDMA <= 0) {
1184		struct GBADMA* dma = &memory->dma[memory->activeDMA];
1185		GBAMemoryServiceDMA(gba, memory->activeDMA, dma);
1186		GBAMemoryUpdateDMAs(gba, memory->eventDiff);
1187		memory->eventDiff = 0;
1188	}
1189	return memory->nextDMA;
1190}
1191
1192void GBAMemoryUpdateDMAs(struct GBA* gba, int32_t cycles) {
1193	int i;
1194	struct GBAMemory* memory = &gba->memory;
1195	struct ARMCore* cpu = gba->cpu;
1196	memory->activeDMA = -1;
1197	memory->nextDMA = INT_MAX;
1198	for (i = 3; i >= 0; --i) {
1199		struct GBADMA* dma = &memory->dma[i];
1200		if (dma->nextEvent != INT_MAX) {
1201			dma->nextEvent -= cycles;
1202			if (GBADMARegisterIsEnable(dma->reg)) {
1203				memory->activeDMA = i;
1204				memory->nextDMA = dma->nextEvent;
1205			}
1206		}
1207	}
1208	if (memory->nextDMA < cpu->nextEvent) {
1209		cpu->nextEvent = memory->nextDMA;
1210	}
1211}
1212
1213void GBAMemoryServiceDMA(struct GBA* gba, int number, struct GBADMA* info) {
1214	struct GBAMemory* memory = &gba->memory;
1215	struct ARMCore* cpu = gba->cpu;
1216	uint32_t width = GBADMARegisterGetWidth(info->reg) ? 4 : 2;
1217	int sourceOffset = DMA_OFFSET[GBADMARegisterGetSrcControl(info->reg)] * width;
1218	int destOffset = DMA_OFFSET[GBADMARegisterGetDestControl(info->reg)] * width;
1219	int32_t wordsRemaining = info->nextCount;
1220	uint32_t source = info->nextSource;
1221	uint32_t dest = info->nextDest;
1222	uint32_t sourceRegion = source >> BASE_OFFSET;
1223	uint32_t destRegion = dest >> BASE_OFFSET;
1224	int32_t cycles = 2;
1225
1226	if (source == info->source) {
1227		// TODO: support 4 cycles for ROM access
1228		cycles += 2;
1229		if (width == 4) {
1230			cycles += memory->waitstatesNonseq32[sourceRegion] + memory->waitstatesNonseq32[destRegion];
1231			source &= 0xFFFFFFFC;
1232			dest &= 0xFFFFFFFC;
1233		} else {
1234			cycles += memory->waitstatesNonseq16[sourceRegion] + memory->waitstatesNonseq16[destRegion];
1235		}
1236	} else {
1237		if (width == 4) {
1238			cycles += memory->waitstatesSeq32[sourceRegion] + memory->waitstatesSeq32[destRegion];
1239		} else {
1240			cycles += memory->waitstatesSeq16[sourceRegion] + memory->waitstatesSeq16[destRegion];
1241		}
1242	}
1243
1244	int32_t word;
1245	if (width == 4) {
1246		word = cpu->memory.load32(cpu, source, 0);
1247		gba->bus = word;
1248		cpu->memory.store32(cpu, dest, word, 0);
1249		source += sourceOffset;
1250		dest += destOffset;
1251		--wordsRemaining;
1252	} else {
1253		if (sourceRegion == REGION_CART2_EX && memory->savedata.type == SAVEDATA_EEPROM) {
1254			word = GBASavedataReadEEPROM(&memory->savedata);
1255			gba->bus = word | (word << 16);
1256			cpu->memory.store16(cpu, dest, word, 0);
1257			source += sourceOffset;
1258			dest += destOffset;
1259			--wordsRemaining;
1260		} else if (destRegion == REGION_CART2_EX) {
1261			if (memory->savedata.type == SAVEDATA_AUTODETECT) {
1262				GBALog(gba, GBA_LOG_INFO, "Detected EEPROM savegame");
1263				GBASavedataInitEEPROM(&memory->savedata);
1264			}
1265			word = cpu->memory.load16(cpu, source, 0);
1266			gba->bus = word | (word << 16);
1267			GBASavedataWriteEEPROM(&memory->savedata, word, wordsRemaining);
1268			source += sourceOffset;
1269			dest += destOffset;
1270			--wordsRemaining;
1271		} else {
1272			word = cpu->memory.load16(cpu, source, 0);
1273			gba->bus = word | (word << 16);
1274			cpu->memory.store16(cpu, dest, word, 0);
1275			source += sourceOffset;
1276			dest += destOffset;
1277			--wordsRemaining;
1278		}
1279	}
1280
1281	if (!wordsRemaining) {
1282		if (!GBADMARegisterIsRepeat(info->reg) || GBADMARegisterGetTiming(info->reg) == DMA_TIMING_NOW) {
1283			info->reg = GBADMARegisterClearEnable(info->reg);
1284			info->nextEvent = INT_MAX;
1285
1286			// Clear the enable bit in memory
1287			memory->io[(REG_DMA0CNT_HI + number * (REG_DMA1CNT_HI - REG_DMA0CNT_HI)) >> 1] &= 0x7FE0;
1288		} else {
1289			info->nextCount = info->count;
1290			if (GBADMARegisterGetDestControl(info->reg) == DMA_INCREMENT_RELOAD) {
1291				info->nextDest = info->dest;
1292			}
1293			GBAMemoryScheduleDMA(gba, number, info);
1294		}
1295		if (GBADMARegisterIsDoIRQ(info->reg)) {
1296			GBARaiseIRQ(gba, IRQ_DMA0 + number);
1297		}
1298	} else {
1299		info->nextDest = dest;
1300		info->nextCount = wordsRemaining;
1301	}
1302	info->nextSource = source;
1303
1304	if (info->nextEvent != INT_MAX) {
1305		info->nextEvent += cycles;
1306	}
1307	cpu->cycles += cycles;
1308}
1309
1310void GBAMemorySerialize(struct GBAMemory* memory, struct GBASerializedState* state) {
1311	memcpy(state->wram, memory->wram, SIZE_WORKING_RAM);
1312	memcpy(state->iwram, memory->iwram, SIZE_WORKING_IRAM);
1313}
1314
1315void GBAMemoryDeserialize(struct GBAMemory* memory, struct GBASerializedState* state) {
1316	memcpy(memory->wram, state->wram, SIZE_WORKING_RAM);
1317	memcpy(memory->iwram, state->iwram, SIZE_WORKING_IRAM);
1318}
1319
1320uint32_t _popcount32(unsigned bits) {
1321	bits = bits - ((bits >> 1) & 0x55555555);
1322	bits = (bits & 0x33333333) + ((bits >> 2) & 0x33333333);
1323	return (((bits + (bits >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24;
1324}