all repos — mgba @ e9a2b2a57c4f478fb3600fe9d87e1b97804d73de

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-hardware.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 10000
  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.hw.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 (gba->performingDMA) { \
 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 (gba->performingDMA) {
 408				LOAD_16(value, address & 2, &gba->bus);
 409			} else {
 410				uint32_t prefetch = cpu->prefetch[1];
 411				if (cpu->executionMode == MODE_THUMB) {
 412					prefetch |= prefetch << 16;
 413				}
 414				LOAD_16(value, address & 2, &prefetch);
 415			}
 416		}
 417		break;
 418	case REGION_WORKING_RAM:
 419		LOAD_16(value, address & (SIZE_WORKING_RAM - 1), memory->wram);
 420		wait = memory->waitstatesNonseq16[REGION_WORKING_RAM];
 421		break;
 422	case REGION_WORKING_IRAM:
 423		LOAD_16(value, address & (SIZE_WORKING_IRAM - 1), memory->iwram);
 424		break;
 425	case REGION_IO:
 426		value = GBAIORead(gba, address & (SIZE_IO - 1));
 427		break;
 428	case REGION_PALETTE_RAM:
 429		LOAD_16(value, address & (SIZE_PALETTE_RAM - 1), gba->video.palette);
 430		break;
 431	case REGION_VRAM:
 432		if ((address & 0x0001FFFF) < SIZE_VRAM) {
 433			LOAD_16(value, address & 0x0001FFFF, gba->video.renderer->vram);
 434		} else {
 435			LOAD_16(value, address & 0x00017FFF, gba->video.renderer->vram);
 436		}
 437		break;
 438	case REGION_OAM:
 439		LOAD_16(value, address & (SIZE_OAM - 1), gba->video.oam.raw);
 440		break;
 441	case REGION_CART0:
 442	case REGION_CART0_EX:
 443	case REGION_CART1:
 444	case REGION_CART1_EX:
 445	case REGION_CART2:
 446		wait = memory->waitstatesNonseq16[address >> BASE_OFFSET];
 447		if ((address & (SIZE_CART0 - 1)) < memory->romSize) {
 448			LOAD_16(value, address & (SIZE_CART0 - 1), memory->rom);
 449		} else {
 450			GBALog(gba, GBA_LOG_GAME_ERROR, "Out of bounds ROM Load16: 0x%08X", address);
 451			value = (address >> 1) & 0xFFFF; \
 452		}
 453		break;
 454	case REGION_CART2_EX:
 455		wait = memory->waitstatesNonseq16[address >> BASE_OFFSET];
 456		if (memory->savedata.type == SAVEDATA_EEPROM) {
 457			value = GBASavedataReadEEPROM(&memory->savedata);
 458		} else if ((address & (SIZE_CART0 - 1)) < memory->romSize) {
 459			LOAD_16(value, address & (SIZE_CART0 - 1), memory->rom);
 460		} else {
 461			GBALog(gba, GBA_LOG_GAME_ERROR, "Out of bounds ROM Load16: 0x%08X", address);
 462			value = (address >> 1) & 0xFFFF; \
 463		}
 464		break;
 465	case REGION_CART_SRAM:
 466	case REGION_CART_SRAM_MIRROR:
 467		wait = memory->waitstatesNonseq16[address >> BASE_OFFSET];
 468		value = GBALoad8(cpu, address, 0);
 469		value |= value << 8;
 470		break;
 471	default:
 472		GBALog(gba, GBA_LOG_GAME_ERROR, "Bad memory Load16: 0x%08X", address);
 473		if (gba->performingDMA) {
 474			LOAD_16(value, address & 2, &gba->bus);
 475		} else {
 476			uint32_t prefetch = cpu->prefetch[1];
 477			if (cpu->executionMode == MODE_THUMB) {
 478				prefetch |= prefetch << 16;
 479			}
 480			LOAD_16(value, address & 2, &prefetch);
 481		}
 482		break;
 483	}
 484
 485	if (cycleCounter) {
 486		*cycleCounter += 2 + wait;
 487	}
 488	// Unaligned 16-bit loads are "unpredictable", but the GBA rotates them, so we have to, too.
 489	int rotate = (address & 1) << 3;
 490	return ROR(value, rotate);
 491}
 492
 493uint32_t GBALoad8(struct ARMCore* cpu, uint32_t address, int* cycleCounter) {
 494	struct GBA* gba = (struct GBA*) cpu->master;
 495	struct GBAMemory* memory = &gba->memory;
 496	uint8_t value = 0;
 497	int wait = 0;
 498
 499	switch (address >> BASE_OFFSET) {
 500	case REGION_BIOS:
 501		if (address < SIZE_BIOS) {
 502			if (memory->activeRegion == REGION_BIOS) {
 503				value = ((int8_t*) memory->bios)[address];
 504			} else {
 505				GBALog(gba, GBA_LOG_GAME_ERROR, "Bad BIOS Load8: 0x%08X", address);
 506				value = ((uint8_t*) &memory->biosPrefetch)[address & 3];
 507			}
 508		} else {
 509			GBALog(gba, GBA_LOG_GAME_ERROR, "Bad memory Load8: 0x%08x", address);
 510			if (gba->performingDMA) {
 511				value = ((uint8_t*) &gba->bus)[address & 3];
 512			} else {
 513				uint32_t prefetch = cpu->prefetch[1];
 514				if (cpu->executionMode == MODE_THUMB) {
 515					prefetch |= prefetch << 16;
 516				}
 517				value = ((uint8_t*) &prefetch)[address & 3];
 518			}
 519		}
 520		break;
 521	case REGION_WORKING_RAM:
 522		value = ((int8_t*) memory->wram)[address & (SIZE_WORKING_RAM - 1)];
 523		wait = memory->waitstatesNonseq16[REGION_WORKING_RAM];
 524		break;
 525	case REGION_WORKING_IRAM:
 526		value = ((int8_t*) memory->iwram)[address & (SIZE_WORKING_IRAM - 1)];
 527		break;
 528	case REGION_IO:
 529		value = (GBAIORead(gba, address & 0xFFFE) >> ((address & 0x0001) << 3)) & 0xFF;
 530		break;
 531	case REGION_PALETTE_RAM:
 532		value = ((int8_t*) gba->video.palette)[address & (SIZE_PALETTE_RAM - 1)];
 533		break;
 534	case REGION_VRAM:
 535		if ((address & 0x0001FFFF) < SIZE_VRAM) {
 536			value = ((int8_t*) gba->video.renderer->vram)[address & 0x0001FFFF];
 537		} else {
 538			value = ((int8_t*) gba->video.renderer->vram)[address & 0x00017FFF];
 539		}
 540		break;
 541	case REGION_OAM:
 542		GBALog(gba, GBA_LOG_STUB, "Unimplemented memory Load8: 0x%08X", address);
 543		break;
 544	case REGION_CART0:
 545	case REGION_CART0_EX:
 546	case REGION_CART1:
 547	case REGION_CART1_EX:
 548	case REGION_CART2:
 549	case REGION_CART2_EX:
 550		wait = memory->waitstatesNonseq16[address >> BASE_OFFSET];
 551		if ((address & (SIZE_CART0 - 1)) < memory->romSize) {
 552			value = ((int8_t*) memory->rom)[address & (SIZE_CART0 - 1)];
 553		} else {
 554			GBALog(gba, GBA_LOG_GAME_ERROR, "Out of bounds ROM Load8: 0x%08X", address);
 555			value = (address >> 1) & 0xFF; \
 556		}
 557		break;
 558	case REGION_CART_SRAM:
 559	case REGION_CART_SRAM_MIRROR:
 560		wait = memory->waitstatesNonseq16[address >> BASE_OFFSET];
 561		if (memory->savedata.type == SAVEDATA_AUTODETECT) {
 562			GBALog(gba, GBA_LOG_INFO, "Detected SRAM savegame");
 563			GBASavedataInitSRAM(&memory->savedata);
 564		}
 565		if (memory->savedata.type == SAVEDATA_SRAM) {
 566			value = memory->savedata.data[address & (SIZE_CART_SRAM - 1)];
 567		} else if (memory->savedata.type == SAVEDATA_FLASH512 || memory->savedata.type == SAVEDATA_FLASH1M) {
 568			value = GBASavedataReadFlash(&memory->savedata, address);
 569		} else if (memory->hw.devices & HW_TILT) {
 570			value = GBAHardwareTiltRead(&memory->hw, address & OFFSET_MASK);
 571		} else {
 572			GBALog(gba, GBA_LOG_GAME_ERROR, "Reading from non-existent SRAM: 0x%08X", address);
 573			value = 0xFF;
 574		}
 575		break;
 576	default:
 577		GBALog(gba, GBA_LOG_GAME_ERROR, "Bad memory Load8: 0x%08x", address);
 578		if (gba->performingDMA) {
 579			value = ((uint8_t*) &gba->bus)[address & 3];
 580		} else {
 581			uint32_t prefetch = cpu->prefetch[1];
 582			if (cpu->executionMode == MODE_THUMB) {
 583				prefetch |= prefetch << 16;
 584			}
 585			value = ((uint8_t*) &prefetch)[address & 3];
 586		}
 587		break;
 588	}
 589
 590	if (cycleCounter) {
 591		*cycleCounter += 2 + wait;
 592	}
 593	return value;
 594}
 595
 596#define STORE_WORKING_RAM \
 597	STORE_32(value, address & (SIZE_WORKING_RAM - 1), memory->wram); \
 598	wait += waitstatesRegion[REGION_WORKING_RAM];
 599
 600#define STORE_WORKING_IRAM \
 601	STORE_32(value, address & (SIZE_WORKING_IRAM - 1), memory->iwram);
 602
 603#define STORE_IO \
 604	GBAIOWrite32(gba, address & (SIZE_IO - 1), value);
 605
 606#define STORE_PALETTE_RAM \
 607	STORE_32(value, address & (SIZE_PALETTE_RAM - 1), gba->video.palette); \
 608	gba->video.renderer->writePalette(gba->video.renderer, (address & (SIZE_PALETTE_RAM - 1)) + 2, value >> 16); \
 609	++wait; \
 610	gba->video.renderer->writePalette(gba->video.renderer, address & (SIZE_PALETTE_RAM - 1), value);
 611
 612#define STORE_VRAM \
 613	if ((address & 0x0001FFFF) < SIZE_VRAM) { \
 614		STORE_32(value, address & 0x0001FFFF, gba->video.renderer->vram); \
 615	} else { \
 616		STORE_32(value, address & 0x00017FFF, gba->video.renderer->vram); \
 617	} \
 618	++wait;
 619
 620#define STORE_OAM \
 621	STORE_32(value, address & (SIZE_OAM - 1), gba->video.oam.raw); \
 622	gba->video.renderer->writeOAM(gba->video.renderer, (address & (SIZE_OAM - 4)) >> 1); \
 623	gba->video.renderer->writeOAM(gba->video.renderer, ((address & (SIZE_OAM - 4)) >> 1) + 1);
 624
 625#define STORE_CART \
 626	GBALog(gba, GBA_LOG_STUB, "Unimplemented memory Store32: 0x%08X", address);
 627
 628#define STORE_SRAM \
 629	GBALog(gba, GBA_LOG_STUB, "Unimplemented memory Store32: 0x%08X", address);
 630
 631#define STORE_BAD \
 632	GBALog(gba, GBA_LOG_GAME_ERROR, "Bad memory Store32: 0x%08X", address);
 633
 634void GBAStore32(struct ARMCore* cpu, uint32_t address, int32_t value, int* cycleCounter) {
 635	struct GBA* gba = (struct GBA*) cpu->master;
 636	struct GBAMemory* memory = &gba->memory;
 637	int wait = 0;
 638	char* waitstatesRegion = memory->waitstatesNonseq32;
 639
 640	switch (address >> BASE_OFFSET) {
 641	case REGION_WORKING_RAM:
 642		STORE_WORKING_RAM;
 643		break;
 644	case REGION_WORKING_IRAM:
 645		STORE_WORKING_IRAM
 646		break;
 647	case REGION_IO:
 648		STORE_IO;
 649		break;
 650	case REGION_PALETTE_RAM:
 651		STORE_PALETTE_RAM;
 652		break;
 653	case REGION_VRAM:
 654		STORE_VRAM;
 655		break;
 656	case REGION_OAM:
 657		STORE_OAM;
 658		break;
 659	case REGION_CART0:
 660	case REGION_CART0_EX:
 661	case REGION_CART1:
 662	case REGION_CART1_EX:
 663	case REGION_CART2:
 664	case REGION_CART2_EX:
 665		STORE_CART;
 666		break;
 667	case REGION_CART_SRAM:
 668	case REGION_CART_SRAM_MIRROR:
 669		STORE_SRAM;
 670		break;
 671	default:
 672		STORE_BAD;
 673		break;
 674	}
 675
 676	if (cycleCounter) {
 677		*cycleCounter += 1 + wait;
 678	}
 679}
 680
 681void GBAStore16(struct ARMCore* cpu, uint32_t address, int16_t value, int* cycleCounter) {
 682	struct GBA* gba = (struct GBA*) cpu->master;
 683	struct GBAMemory* memory = &gba->memory;
 684	int wait = 0;
 685
 686	switch (address >> BASE_OFFSET) {
 687	case REGION_WORKING_RAM:
 688		STORE_16(value, address & (SIZE_WORKING_RAM - 1), memory->wram);
 689		wait = memory->waitstatesNonseq16[REGION_WORKING_RAM];
 690		break;
 691	case REGION_WORKING_IRAM:
 692		STORE_16(value, address & (SIZE_WORKING_IRAM - 1), memory->iwram);
 693		break;
 694	case REGION_IO:
 695		GBAIOWrite(gba, address & (SIZE_IO - 1), value);
 696		break;
 697	case REGION_PALETTE_RAM:
 698		STORE_16(value, address & (SIZE_PALETTE_RAM - 1), gba->video.palette);
 699		gba->video.renderer->writePalette(gba->video.renderer, address & (SIZE_PALETTE_RAM - 1), value);
 700		break;
 701	case REGION_VRAM:
 702		if ((address & 0x0001FFFF) < SIZE_VRAM) {
 703			STORE_16(value, address & 0x0001FFFF, gba->video.renderer->vram);
 704		} else {
 705			STORE_16(value, address & 0x00017FFF, gba->video.renderer->vram);
 706		}
 707		break;
 708	case REGION_OAM:
 709		STORE_16(value, address & (SIZE_OAM - 1), gba->video.oam.raw);
 710		gba->video.renderer->writeOAM(gba->video.renderer, (address & (SIZE_OAM - 1)) >> 1);
 711		break;
 712	case REGION_CART0:
 713		if (memory->hw.devices != HW_NONE && IS_GPIO_REGISTER(address & 0xFFFFFF)) {
 714			uint32_t reg = address & 0xFFFFFF;
 715			GBAHardwareGPIOWrite(&memory->hw, reg, value);
 716		} else {
 717			GBALog(gba, GBA_LOG_GAME_ERROR, "Bad cartridge Store16: 0x%08X", address);
 718		}
 719		break;
 720	case REGION_CART2_EX:
 721		if (memory->savedata.type == SAVEDATA_AUTODETECT) {
 722			GBALog(gba, GBA_LOG_INFO, "Detected EEPROM savegame");
 723			GBASavedataInitEEPROM(&memory->savedata);
 724		}
 725		GBASavedataWriteEEPROM(&memory->savedata, value, 1);
 726		break;
 727	case REGION_CART_SRAM:
 728	case REGION_CART_SRAM_MIRROR:
 729		GBALog(gba, GBA_LOG_STUB, "Unimplemented memory Store16: 0x%08X", address);
 730		break;
 731	default:
 732		GBALog(gba, GBA_LOG_GAME_ERROR, "Bad memory Store16: 0x%08X", address);
 733		break;
 734	}
 735
 736	if (cycleCounter) {
 737		*cycleCounter += 1 + wait;
 738	}
 739}
 740
 741void GBAStore8(struct ARMCore* cpu, uint32_t address, int8_t value, int* cycleCounter) {
 742	struct GBA* gba = (struct GBA*) cpu->master;
 743	struct GBAMemory* memory = &gba->memory;
 744	int wait = 0;
 745
 746	switch (address >> BASE_OFFSET) {
 747	case REGION_WORKING_RAM:
 748		((int8_t*) memory->wram)[address & (SIZE_WORKING_RAM - 1)] = value;
 749		wait = memory->waitstatesNonseq16[REGION_WORKING_RAM];
 750		break;
 751	case REGION_WORKING_IRAM:
 752		((int8_t*) memory->iwram)[address & (SIZE_WORKING_IRAM - 1)] = value;
 753		break;
 754	case REGION_IO:
 755		GBAIOWrite8(gba, address & (SIZE_IO - 1), value);
 756		break;
 757	case REGION_PALETTE_RAM:
 758		GBALog(gba, GBA_LOG_STUB, "Unimplemented memory Store8: 0x%08X", address);
 759		break;
 760	case REGION_VRAM:
 761		if (address >= 0x06018000) {
 762			// TODO: check BG mode
 763			GBALog(gba, GBA_LOG_GAME_ERROR, "Cannot Store8 to OBJ: 0x%08X", address);
 764			break;
 765		}
 766		((int8_t*) gba->video.renderer->vram)[address & 0x1FFFE] = value;
 767		((int8_t*) gba->video.renderer->vram)[(address & 0x1FFFE) | 1] = value;
 768		break;
 769	case REGION_OAM:
 770		GBALog(gba, GBA_LOG_GAME_ERROR, "Cannot Store8 to OAM: 0x%08X", address);
 771		break;
 772	case REGION_CART0:
 773		GBALog(gba, GBA_LOG_STUB, "Unimplemented memory Store8: 0x%08X", address);
 774		break;
 775	case REGION_CART_SRAM:
 776	case REGION_CART_SRAM_MIRROR:
 777		if (memory->savedata.type == SAVEDATA_AUTODETECT) {
 778			if (address == SAVEDATA_FLASH_BASE) {
 779				GBALog(gba, GBA_LOG_INFO, "Detected Flash savegame");
 780				GBASavedataInitFlash(&memory->savedata);
 781			} else {
 782				GBALog(gba, GBA_LOG_INFO, "Detected SRAM savegame");
 783				GBASavedataInitSRAM(&memory->savedata);
 784			}
 785		}
 786		if (memory->savedata.type == SAVEDATA_FLASH512 || memory->savedata.type == SAVEDATA_FLASH1M) {
 787			GBASavedataWriteFlash(&memory->savedata, address, value);
 788		} else if (memory->savedata.type == SAVEDATA_SRAM) {
 789			memory->savedata.data[address & (SIZE_CART_SRAM - 1)] = value;
 790		} else if (memory->hw.devices & HW_TILT) {
 791			GBAHardwareTiltWrite(&memory->hw, address & OFFSET_MASK, value);
 792		} else {
 793			GBALog(gba, GBA_LOG_GAME_ERROR, "Writing to non-existent SRAM: 0x%08X", address);
 794		}
 795		wait = memory->waitstatesNonseq16[REGION_CART_SRAM];
 796		break;
 797	default:
 798		GBALog(gba, GBA_LOG_GAME_ERROR, "Bad memory Store8: 0x%08X", address);
 799		break;
 800	}
 801
 802	if (cycleCounter) {
 803		*cycleCounter += 1 + wait;
 804	}
 805}
 806
 807#define LDM_LOOP(LDM) \
 808	for (i = 0; i < 16; i += 4) { \
 809		if (UNLIKELY(mask & (1 << i))) { \
 810			LDM; \
 811			waitstatesRegion = memory->waitstatesSeq32; \
 812			cpu->gprs[i] = value; \
 813			++wait; \
 814			address += 4; \
 815		} \
 816		if (UNLIKELY(mask & (2 << i))) { \
 817			LDM; \
 818			waitstatesRegion = memory->waitstatesSeq32; \
 819			cpu->gprs[i + 1] = value; \
 820			++wait; \
 821			address += 4; \
 822		} \
 823		if (UNLIKELY(mask & (4 << i))) { \
 824			LDM; \
 825			waitstatesRegion = memory->waitstatesSeq32; \
 826			cpu->gprs[i + 2] = value; \
 827			++wait; \
 828			address += 4; \
 829		} \
 830		if (UNLIKELY(mask & (8 << i))) { \
 831			LDM; \
 832			waitstatesRegion = memory->waitstatesSeq32; \
 833			cpu->gprs[i + 3] = value; \
 834			++wait; \
 835			address += 4; \
 836		} \
 837	}
 838
 839uint32_t GBALoadMultiple(struct ARMCore* cpu, uint32_t address, int mask, enum LSMDirection direction, int* cycleCounter) {
 840	struct GBA* gba = (struct GBA*) cpu->master;
 841	struct GBAMemory* memory = &gba->memory;
 842	uint32_t value;
 843	int wait = 0;
 844	char* waitstatesRegion = memory->waitstatesNonseq32;
 845
 846	int i;
 847	int offset = 4;
 848	int popcount = 0;
 849	if (direction & LSM_D) {
 850		offset = -4;
 851		popcount = _popcount32(mask);
 852		address -= (popcount << 2) - 4;
 853	}
 854
 855	if (direction & LSM_B) {
 856		address += offset;
 857	}
 858
 859	uint32_t addressMisalign = address & 0x3;
 860	address &= 0xFFFFFFFC;
 861
 862	switch (address >> BASE_OFFSET) {
 863	case REGION_BIOS:
 864		LDM_LOOP(LOAD_BIOS);
 865		break;
 866	case REGION_WORKING_RAM:
 867		LDM_LOOP(LOAD_WORKING_RAM);
 868		break;
 869	case REGION_WORKING_IRAM:
 870		LDM_LOOP(LOAD_WORKING_IRAM);
 871		break;
 872	case REGION_IO:
 873		LDM_LOOP(LOAD_IO);
 874		break;
 875	case REGION_PALETTE_RAM:
 876		LDM_LOOP(LOAD_PALETTE_RAM);
 877		break;
 878	case REGION_VRAM:
 879		LDM_LOOP(LOAD_VRAM);
 880		break;
 881	case REGION_OAM:
 882		LDM_LOOP(LOAD_OAM);
 883		break;
 884	case REGION_CART0:
 885	case REGION_CART0_EX:
 886	case REGION_CART1:
 887	case REGION_CART1_EX:
 888	case REGION_CART2:
 889	case REGION_CART2_EX:
 890		LDM_LOOP(LOAD_CART);
 891		break;
 892	case REGION_CART_SRAM:
 893	case REGION_CART_SRAM_MIRROR:
 894		LDM_LOOP(LOAD_SRAM);
 895		break;
 896	default:
 897		LDM_LOOP(LOAD_BAD);
 898		break;
 899	}
 900
 901	if (cycleCounter) {
 902		*cycleCounter += wait;
 903	}
 904
 905	if (direction & LSM_B) {
 906		address -= offset;
 907	}
 908
 909	if (direction & LSM_D) {
 910		address -= (popcount << 2) + 4;
 911	}
 912
 913	return address | addressMisalign;
 914}
 915
 916#define STM_LOOP(STM) \
 917	for (i = 0; i < 16; i += 4) { \
 918		if (UNLIKELY(mask & (1 << i))) { \
 919			value = cpu->gprs[i]; \
 920			STM; \
 921			waitstatesRegion = memory->waitstatesSeq32; \
 922			++wait; \
 923			address += 4; \
 924		} \
 925		if (UNLIKELY(mask & (2 << i))) { \
 926			value = cpu->gprs[i + 1]; \
 927			STM; \
 928			waitstatesRegion = memory->waitstatesSeq32; \
 929			++wait; \
 930			address += 4; \
 931		} \
 932		if (UNLIKELY(mask & (4 << i))) { \
 933			value = cpu->gprs[i + 2]; \
 934			STM; \
 935			waitstatesRegion = memory->waitstatesSeq32; \
 936			++wait; \
 937			address += 4; \
 938		} \
 939		if (UNLIKELY(mask & (8 << i))) { \
 940			value = cpu->gprs[i + 3]; \
 941			STM; \
 942			waitstatesRegion = memory->waitstatesSeq32; \
 943			++wait; \
 944			address += 4; \
 945		} \
 946	}
 947
 948uint32_t GBAStoreMultiple(struct ARMCore* cpu, uint32_t address, int mask, enum LSMDirection direction, int* cycleCounter) {
 949	struct GBA* gba = (struct GBA*) cpu->master;
 950	struct GBAMemory* memory = &gba->memory;
 951	uint32_t value;
 952	int wait = 0;
 953	char* waitstatesRegion = memory->waitstatesNonseq32;
 954
 955	int i;
 956	int offset = 4;
 957	int popcount = 0;
 958	if (direction & LSM_D) {
 959		offset = -4;
 960		popcount = _popcount32(mask);
 961		address -= (popcount << 2) - 4;
 962	}
 963
 964	if (direction & LSM_B) {
 965		address += offset;
 966	}
 967
 968	uint32_t addressMisalign = address & 0x3;
 969	address &= 0xFFFFFFFC;
 970
 971	switch (address >> BASE_OFFSET) {
 972	case REGION_WORKING_RAM:
 973		STM_LOOP(STORE_WORKING_RAM);
 974		break;
 975	case REGION_WORKING_IRAM:
 976		STM_LOOP(STORE_WORKING_IRAM);
 977		break;
 978	case REGION_IO:
 979		STM_LOOP(STORE_IO);
 980		break;
 981	case REGION_PALETTE_RAM:
 982		STM_LOOP(STORE_PALETTE_RAM);
 983		break;
 984	case REGION_VRAM:
 985		STM_LOOP(STORE_VRAM);
 986		break;
 987	case REGION_OAM:
 988		STM_LOOP(STORE_OAM);
 989		break;
 990	case REGION_CART0:
 991	case REGION_CART0_EX:
 992	case REGION_CART1:
 993	case REGION_CART1_EX:
 994	case REGION_CART2:
 995	case REGION_CART2_EX:
 996		STM_LOOP(STORE_CART);
 997		break;
 998	case REGION_CART_SRAM:
 999	case REGION_CART_SRAM_MIRROR:
1000		STM_LOOP(STORE_SRAM);
1001		break;
1002	default:
1003		STM_LOOP(STORE_BAD);
1004		break;
1005	}
1006
1007	if (cycleCounter) {
1008		*cycleCounter += wait;
1009	}
1010
1011	if (direction & LSM_B) {
1012		address -= offset;
1013	}
1014
1015	if (direction & LSM_D) {
1016		address -= (popcount << 2) + 4;
1017	}
1018
1019	return address | addressMisalign;
1020}
1021
1022void GBAAdjustWaitstates(struct GBA* gba, uint16_t parameters) {
1023	struct GBAMemory* memory = &gba->memory;
1024	struct ARMCore* cpu = gba->cpu;
1025	int sram = parameters & 0x0003;
1026	int ws0 = (parameters & 0x000C) >> 2;
1027	int ws0seq = (parameters & 0x0010) >> 4;
1028	int ws1 = (parameters & 0x0060) >> 5;
1029	int ws1seq = (parameters & 0x0080) >> 7;
1030	int ws2 = (parameters & 0x0300) >> 8;
1031	int ws2seq = (parameters & 0x0400) >> 10;
1032	int prefetch = parameters & 0x4000;
1033
1034	memory->waitstatesNonseq16[REGION_CART_SRAM] = memory->waitstatesNonseq16[REGION_CART_SRAM_MIRROR] =  GBA_ROM_WAITSTATES[sram];
1035	memory->waitstatesSeq16[REGION_CART_SRAM] = memory->waitstatesSeq16[REGION_CART_SRAM_MIRROR] = GBA_ROM_WAITSTATES[sram];
1036	memory->waitstatesNonseq32[REGION_CART_SRAM] = memory->waitstatesNonseq32[REGION_CART_SRAM_MIRROR] = 2 * GBA_ROM_WAITSTATES[sram] + 1;
1037	memory->waitstatesSeq32[REGION_CART_SRAM] = memory->waitstatesSeq32[REGION_CART_SRAM_MIRROR] = 2 * GBA_ROM_WAITSTATES[sram] + 1;
1038
1039	memory->waitstatesNonseq16[REGION_CART0] = memory->waitstatesNonseq16[REGION_CART0_EX] = GBA_ROM_WAITSTATES[ws0];
1040	memory->waitstatesNonseq16[REGION_CART1] = memory->waitstatesNonseq16[REGION_CART1_EX] = GBA_ROM_WAITSTATES[ws1];
1041	memory->waitstatesNonseq16[REGION_CART2] = memory->waitstatesNonseq16[REGION_CART2_EX] = GBA_ROM_WAITSTATES[ws2];
1042
1043	memory->waitstatesSeq16[REGION_CART0] = memory->waitstatesSeq16[REGION_CART0_EX] = GBA_ROM_WAITSTATES_SEQ[ws0seq];
1044	memory->waitstatesSeq16[REGION_CART1] = memory->waitstatesSeq16[REGION_CART1_EX] = GBA_ROM_WAITSTATES_SEQ[ws1seq + 2];
1045	memory->waitstatesSeq16[REGION_CART2] = memory->waitstatesSeq16[REGION_CART2_EX] = GBA_ROM_WAITSTATES_SEQ[ws2seq + 4];
1046
1047	memory->waitstatesNonseq32[REGION_CART0] = memory->waitstatesNonseq32[REGION_CART0_EX] = memory->waitstatesSeq16[REGION_CART0] + 1 + memory->waitstatesSeq16[REGION_CART0];
1048	memory->waitstatesNonseq32[REGION_CART1] = memory->waitstatesNonseq32[REGION_CART1_EX] = memory->waitstatesSeq16[REGION_CART1] + 1 + memory->waitstatesSeq16[REGION_CART1];
1049	memory->waitstatesNonseq32[REGION_CART2] = memory->waitstatesNonseq32[REGION_CART2_EX] = memory->waitstatesSeq16[REGION_CART2] + 1 + memory->waitstatesSeq16[REGION_CART2];
1050
1051	memory->waitstatesSeq32[REGION_CART0] = memory->waitstatesSeq32[REGION_CART0_EX] = 2 * memory->waitstatesSeq16[REGION_CART0] + 1;
1052	memory->waitstatesSeq32[REGION_CART1] = memory->waitstatesSeq32[REGION_CART1_EX] = 2 * memory->waitstatesSeq16[REGION_CART1] + 1;
1053	memory->waitstatesSeq32[REGION_CART2] = memory->waitstatesSeq32[REGION_CART2_EX] = 2 * memory->waitstatesSeq16[REGION_CART2] + 1;
1054
1055	if (!prefetch) {
1056		memory->waitstatesPrefetchSeq16[REGION_CART0] = memory->waitstatesPrefetchSeq16[REGION_CART0_EX] = memory->waitstatesSeq16[REGION_CART0];
1057		memory->waitstatesPrefetchSeq16[REGION_CART1] = memory->waitstatesPrefetchSeq16[REGION_CART1_EX] = memory->waitstatesSeq16[REGION_CART1];
1058		memory->waitstatesPrefetchSeq16[REGION_CART2] = memory->waitstatesPrefetchSeq16[REGION_CART2_EX] = memory->waitstatesSeq16[REGION_CART2];
1059
1060		memory->waitstatesPrefetchSeq32[REGION_CART0] = memory->waitstatesPrefetchSeq32[REGION_CART0_EX] = memory->waitstatesSeq32[REGION_CART0];
1061		memory->waitstatesPrefetchSeq32[REGION_CART1] = memory->waitstatesPrefetchSeq32[REGION_CART1_EX] = memory->waitstatesSeq32[REGION_CART1];
1062		memory->waitstatesPrefetchSeq32[REGION_CART2] = memory->waitstatesPrefetchSeq32[REGION_CART2_EX] = memory->waitstatesSeq32[REGION_CART2];
1063
1064		memory->waitstatesPrefetchNonseq16[REGION_CART0] = memory->waitstatesPrefetchNonseq16[REGION_CART0_EX] = memory->waitstatesNonseq16[REGION_CART0];
1065		memory->waitstatesPrefetchNonseq16[REGION_CART1] = memory->waitstatesPrefetchNonseq16[REGION_CART1_EX] = memory->waitstatesNonseq16[REGION_CART1];
1066		memory->waitstatesPrefetchNonseq16[REGION_CART2] = memory->waitstatesPrefetchNonseq16[REGION_CART2_EX] = memory->waitstatesNonseq16[REGION_CART2];
1067
1068		memory->waitstatesPrefetchNonseq32[REGION_CART0] = memory->waitstatesPrefetchNonseq32[REGION_CART0_EX] = memory->waitstatesNonseq32[REGION_CART0];
1069		memory->waitstatesPrefetchNonseq32[REGION_CART1] = memory->waitstatesPrefetchNonseq32[REGION_CART1_EX] = memory->waitstatesNonseq32[REGION_CART1];
1070		memory->waitstatesPrefetchNonseq32[REGION_CART2] = memory->waitstatesPrefetchNonseq32[REGION_CART2_EX] = memory->waitstatesNonseq32[REGION_CART2];
1071	} else {
1072		memory->waitstatesPrefetchSeq16[REGION_CART0] = memory->waitstatesPrefetchSeq16[REGION_CART0_EX] = 0;
1073		memory->waitstatesPrefetchSeq16[REGION_CART1] = memory->waitstatesPrefetchSeq16[REGION_CART1_EX] = 0;
1074		memory->waitstatesPrefetchSeq16[REGION_CART2] = memory->waitstatesPrefetchSeq16[REGION_CART2_EX] = 0;
1075
1076		memory->waitstatesPrefetchSeq32[REGION_CART0] = memory->waitstatesPrefetchSeq32[REGION_CART0_EX] = 0;
1077		memory->waitstatesPrefetchSeq32[REGION_CART1] = memory->waitstatesPrefetchSeq32[REGION_CART1_EX] = 0;
1078		memory->waitstatesPrefetchSeq32[REGION_CART2] = memory->waitstatesPrefetchSeq32[REGION_CART2_EX] = 0;
1079
1080		memory->waitstatesPrefetchNonseq16[REGION_CART0] = memory->waitstatesPrefetchNonseq16[REGION_CART0_EX] = 0;
1081		memory->waitstatesPrefetchNonseq16[REGION_CART1] = memory->waitstatesPrefetchNonseq16[REGION_CART1_EX] = 0;
1082		memory->waitstatesPrefetchNonseq16[REGION_CART2] = memory->waitstatesPrefetchNonseq16[REGION_CART2_EX] = 0;
1083
1084		memory->waitstatesPrefetchNonseq32[REGION_CART0] = memory->waitstatesPrefetchNonseq32[REGION_CART0_EX] = 0;
1085		memory->waitstatesPrefetchNonseq32[REGION_CART1] = memory->waitstatesPrefetchNonseq32[REGION_CART1_EX] = 0;
1086		memory->waitstatesPrefetchNonseq32[REGION_CART2] = memory->waitstatesPrefetchNonseq32[REGION_CART2_EX] = 0;
1087	}
1088
1089	cpu->memory.activeSeqCycles32 = memory->waitstatesPrefetchSeq32[memory->activeRegion];
1090	cpu->memory.activeSeqCycles16 = memory->waitstatesPrefetchSeq16[memory->activeRegion];
1091
1092	cpu->memory.activeNonseqCycles32 = memory->waitstatesPrefetchNonseq32[memory->activeRegion];
1093	cpu->memory.activeNonseqCycles16 = memory->waitstatesPrefetchNonseq16[memory->activeRegion];
1094
1095	cpu->memory.activeUncachedCycles32 = memory->waitstatesNonseq32[memory->activeRegion];
1096	cpu->memory.activeUncachedCycles16 = memory->waitstatesNonseq16[memory->activeRegion];
1097}
1098
1099void GBAMemoryWriteDMASAD(struct GBA* gba, int dma, uint32_t address) {
1100	struct GBAMemory* memory = &gba->memory;
1101	memory->dma[dma].source = address & 0x0FFFFFFE;
1102}
1103
1104void GBAMemoryWriteDMADAD(struct GBA* gba, int dma, uint32_t address) {
1105	struct GBAMemory* memory = &gba->memory;
1106	memory->dma[dma].dest = address & 0x0FFFFFFE;
1107}
1108
1109void GBAMemoryWriteDMACNT_LO(struct GBA* gba, int dma, uint16_t count) {
1110	struct GBAMemory* memory = &gba->memory;
1111	memory->dma[dma].count = count ? count : (dma == 3 ? 0x10000 : 0x4000);
1112}
1113
1114uint16_t GBAMemoryWriteDMACNT_HI(struct GBA* gba, int dma, uint16_t control) {
1115	struct GBAMemory* memory = &gba->memory;
1116	struct GBADMA* currentDma = &memory->dma[dma];
1117	int wasEnabled = GBADMARegisterIsEnable(currentDma->reg);
1118	currentDma->reg = control;
1119
1120	if (GBADMARegisterIsDRQ(currentDma->reg)) {
1121		GBALog(gba, GBA_LOG_STUB, "DRQ not implemented");
1122	}
1123
1124	if (!wasEnabled && GBADMARegisterIsEnable(currentDma->reg)) {
1125		currentDma->nextSource = currentDma->source;
1126		currentDma->nextDest = currentDma->dest;
1127		currentDma->nextCount = currentDma->count;
1128		GBAMemoryScheduleDMA(gba, dma, currentDma);
1129	}
1130	// If the DMA has already occurred, this value might have changed since the function started
1131	return currentDma->reg;
1132};
1133
1134void GBAMemoryScheduleDMA(struct GBA* gba, int number, struct GBADMA* info) {
1135	struct ARMCore* cpu = gba->cpu;
1136	switch (GBADMARegisterGetTiming(info->reg)) {
1137	case DMA_TIMING_NOW:
1138		info->nextEvent = cpu->cycles;
1139		GBAMemoryUpdateDMAs(gba, 0);
1140		break;
1141	case DMA_TIMING_HBLANK:
1142		// Handled implicitly
1143		info->nextEvent = INT_MAX;
1144		break;
1145	case DMA_TIMING_VBLANK:
1146		// Handled implicitly
1147		info->nextEvent = INT_MAX;
1148		break;
1149	case DMA_TIMING_CUSTOM:
1150		info->nextEvent = INT_MAX;
1151		switch (number) {
1152		case 0:
1153			GBALog(gba, GBA_LOG_WARN, "Discarding invalid DMA0 scheduling");
1154			break;
1155		case 1:
1156		case 2:
1157			GBAAudioScheduleFifoDma(&gba->audio, number, info);
1158			break;
1159		case 3:
1160			// GBAVideoScheduleVCaptureDma(dma, info);
1161			break;
1162		}
1163	}
1164}
1165
1166void GBAMemoryRunHblankDMAs(struct GBA* gba, int32_t cycles) {
1167	struct GBAMemory* memory = &gba->memory;
1168	struct GBADMA* dma;
1169	int i;
1170	for (i = 0; i < 4; ++i) {
1171		dma = &memory->dma[i];
1172		if (GBADMARegisterIsEnable(dma->reg) && GBADMARegisterGetTiming(dma->reg) == DMA_TIMING_HBLANK) {
1173			dma->nextEvent = cycles;
1174		}
1175	}
1176	GBAMemoryUpdateDMAs(gba, 0);
1177}
1178
1179void GBAMemoryRunVblankDMAs(struct GBA* gba, int32_t cycles) {
1180	struct GBAMemory* memory = &gba->memory;
1181	struct GBADMA* dma;
1182	int i;
1183	for (i = 0; i < 4; ++i) {
1184		dma = &memory->dma[i];
1185		if (GBADMARegisterIsEnable(dma->reg) && GBADMARegisterGetTiming(dma->reg) == DMA_TIMING_VBLANK) {
1186			dma->nextEvent = cycles;
1187		}
1188	}
1189	GBAMemoryUpdateDMAs(gba, 0);
1190}
1191
1192int32_t GBAMemoryRunDMAs(struct GBA* gba, int32_t cycles) {
1193	struct GBAMemory* memory = &gba->memory;
1194	if (memory->nextDMA == INT_MAX) {
1195		return INT_MAX;
1196	}
1197	memory->nextDMA -= cycles;
1198	memory->eventDiff += cycles;
1199	if (memory->nextDMA <= 0) {
1200		struct GBADMA* dma = &memory->dma[memory->activeDMA];
1201		GBAMemoryServiceDMA(gba, memory->activeDMA, dma);
1202		GBAMemoryUpdateDMAs(gba, memory->eventDiff);
1203		memory->eventDiff = 0;
1204	}
1205	return memory->nextDMA;
1206}
1207
1208void GBAMemoryUpdateDMAs(struct GBA* gba, int32_t cycles) {
1209	int i;
1210	struct GBAMemory* memory = &gba->memory;
1211	struct ARMCore* cpu = gba->cpu;
1212	memory->activeDMA = -1;
1213	memory->nextDMA = INT_MAX;
1214	for (i = 3; i >= 0; --i) {
1215		struct GBADMA* dma = &memory->dma[i];
1216		if (dma->nextEvent != INT_MAX) {
1217			dma->nextEvent -= cycles;
1218			if (GBADMARegisterIsEnable(dma->reg)) {
1219				memory->activeDMA = i;
1220				memory->nextDMA = dma->nextEvent;
1221			}
1222		}
1223	}
1224	if (memory->nextDMA < cpu->nextEvent) {
1225		cpu->nextEvent = memory->nextDMA;
1226	}
1227}
1228
1229void GBAMemoryServiceDMA(struct GBA* gba, int number, struct GBADMA* info) {
1230	struct GBAMemory* memory = &gba->memory;
1231	struct ARMCore* cpu = gba->cpu;
1232	uint32_t width = GBADMARegisterGetWidth(info->reg) ? 4 : 2;
1233	int sourceOffset = DMA_OFFSET[GBADMARegisterGetSrcControl(info->reg)] * width;
1234	int destOffset = DMA_OFFSET[GBADMARegisterGetDestControl(info->reg)] * width;
1235	int32_t wordsRemaining = info->nextCount;
1236	uint32_t source = info->nextSource;
1237	uint32_t dest = info->nextDest;
1238	uint32_t sourceRegion = source >> BASE_OFFSET;
1239	uint32_t destRegion = dest >> BASE_OFFSET;
1240	int32_t cycles = 2;
1241
1242	if (source == info->source) {
1243		// TODO: support 4 cycles for ROM access
1244		cycles += 2;
1245		if (width == 4) {
1246			cycles += memory->waitstatesNonseq32[sourceRegion] + memory->waitstatesNonseq32[destRegion];
1247			source &= 0xFFFFFFFC;
1248			dest &= 0xFFFFFFFC;
1249		} else {
1250			cycles += memory->waitstatesNonseq16[sourceRegion] + memory->waitstatesNonseq16[destRegion];
1251		}
1252	} else {
1253		if (width == 4) {
1254			cycles += memory->waitstatesSeq32[sourceRegion] + memory->waitstatesSeq32[destRegion];
1255		} else {
1256			cycles += memory->waitstatesSeq16[sourceRegion] + memory->waitstatesSeq16[destRegion];
1257		}
1258	}
1259
1260	gba->performingDMA = true;
1261	int32_t word;
1262	if (width == 4) {
1263		word = cpu->memory.load32(cpu, source, 0);
1264		gba->bus = word;
1265		cpu->memory.store32(cpu, dest, word, 0);
1266		source += sourceOffset;
1267		dest += destOffset;
1268		--wordsRemaining;
1269	} else {
1270		if (sourceRegion == REGION_CART2_EX && memory->savedata.type == SAVEDATA_EEPROM) {
1271			word = GBASavedataReadEEPROM(&memory->savedata);
1272			gba->bus = word | (word << 16);
1273			cpu->memory.store16(cpu, dest, word, 0);
1274			source += sourceOffset;
1275			dest += destOffset;
1276			--wordsRemaining;
1277		} else if (destRegion == REGION_CART2_EX) {
1278			if (memory->savedata.type == SAVEDATA_AUTODETECT) {
1279				GBALog(gba, GBA_LOG_INFO, "Detected EEPROM savegame");
1280				GBASavedataInitEEPROM(&memory->savedata);
1281			}
1282			word = cpu->memory.load16(cpu, source, 0);
1283			gba->bus = word | (word << 16);
1284			GBASavedataWriteEEPROM(&memory->savedata, word, wordsRemaining);
1285			source += sourceOffset;
1286			dest += destOffset;
1287			--wordsRemaining;
1288		} else {
1289			word = cpu->memory.load16(cpu, source, 0);
1290			gba->bus = word | (word << 16);
1291			cpu->memory.store16(cpu, dest, word, 0);
1292			source += sourceOffset;
1293			dest += destOffset;
1294			--wordsRemaining;
1295		}
1296	}
1297	gba->performingDMA = false;
1298
1299	if (!wordsRemaining) {
1300		if (!GBADMARegisterIsRepeat(info->reg) || GBADMARegisterGetTiming(info->reg) == DMA_TIMING_NOW) {
1301			info->reg = GBADMARegisterClearEnable(info->reg);
1302			info->nextEvent = INT_MAX;
1303
1304			// Clear the enable bit in memory
1305			memory->io[(REG_DMA0CNT_HI + number * (REG_DMA1CNT_HI - REG_DMA0CNT_HI)) >> 1] &= 0x7FE0;
1306		} else {
1307			info->nextCount = info->count;
1308			if (GBADMARegisterGetDestControl(info->reg) == DMA_INCREMENT_RELOAD) {
1309				info->nextDest = info->dest;
1310			}
1311			GBAMemoryScheduleDMA(gba, number, info);
1312		}
1313		if (GBADMARegisterIsDoIRQ(info->reg)) {
1314			GBARaiseIRQ(gba, IRQ_DMA0 + number);
1315		}
1316	} else {
1317		info->nextDest = dest;
1318		info->nextCount = wordsRemaining;
1319	}
1320	info->nextSource = source;
1321
1322	if (info->nextEvent != INT_MAX) {
1323		info->nextEvent += cycles;
1324	}
1325	cpu->cycles += cycles;
1326}
1327
1328void GBAMemorySerialize(struct GBAMemory* memory, struct GBASerializedState* state) {
1329	memcpy(state->wram, memory->wram, SIZE_WORKING_RAM);
1330	memcpy(state->iwram, memory->iwram, SIZE_WORKING_IRAM);
1331}
1332
1333void GBAMemoryDeserialize(struct GBAMemory* memory, struct GBASerializedState* state) {
1334	memcpy(memory->wram, state->wram, SIZE_WORKING_RAM);
1335	memcpy(memory->iwram, state->iwram, SIZE_WORKING_IRAM);
1336}
1337
1338uint32_t _popcount32(unsigned bits) {
1339	bits = bits - ((bits >> 1) & 0x55555555);
1340	bits = (bits & 0x33333333) + ((bits >> 2) & 0x33333333);
1341	return (((bits + (bits >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24;
1342}