all repos — mgba @ 2a35f0689aaf74b03a0e02de19643275c9822e6d

mGBA Game Boy Advance Emulator

src/gb/memory.c (view raw)

  1/* Copyright (c) 2013-2016 Jeffrey Pfau
  2 *
  3 * This Source Code Form is subject to the terms of the Mozilla Public
  4 * License, v. 2.0. If a copy of the MPL was not distributed with this
  5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  6#include <mgba/internal/gb/memory.h>
  7
  8#include <mgba/core/interface.h>
  9#include <mgba/internal/gb/gb.h>
 10#include <mgba/internal/gb/io.h>
 11#include <mgba/internal/gb/mbc.h>
 12#include <mgba/internal/gb/serialize.h>
 13#include <mgba/internal/sm83/sm83.h>
 14
 15#include <mgba-util/memory.h>
 16
 17mLOG_DEFINE_CATEGORY(GB_MEM, "GB Memory", "gb.memory");
 18
 19static const uint8_t _yankBuffer[] = { 0xFF };
 20
 21enum GBBus {
 22	GB_BUS_CPU,
 23	GB_BUS_MAIN,
 24	GB_BUS_VRAM,
 25	GB_BUS_RAM
 26};
 27
 28static const enum GBBus _oamBlockDMG[] = {
 29	GB_BUS_MAIN, // 0x0000
 30	GB_BUS_MAIN, // 0x2000
 31	GB_BUS_MAIN, // 0x4000
 32	GB_BUS_MAIN, // 0x6000
 33	GB_BUS_VRAM, // 0x8000
 34	GB_BUS_MAIN, // 0xA000
 35	GB_BUS_MAIN, // 0xC000
 36	GB_BUS_CPU, // 0xE000
 37};
 38
 39static const enum GBBus _oamBlockCGB[] = {
 40	GB_BUS_MAIN, // 0x0000
 41	GB_BUS_MAIN, // 0x2000
 42	GB_BUS_MAIN, // 0x4000
 43	GB_BUS_MAIN, // 0x6000
 44	GB_BUS_VRAM, // 0x8000
 45	GB_BUS_MAIN, // 0xA000
 46	GB_BUS_RAM, // 0xC000
 47	GB_BUS_CPU // 0xE000
 48};
 49
 50static const uint8_t _blockedRegion[1] = { 0xFF };
 51
 52static void _pristineCow(struct GB* gba);
 53
 54static uint8_t GBFastLoad8(struct SM83Core* cpu, uint16_t address) {
 55	if (UNLIKELY(address >= cpu->memory.activeRegionEnd)) {
 56		cpu->memory.setActiveRegion(cpu, address);
 57		return cpu->memory.cpuLoad8(cpu, address);
 58	}
 59	return cpu->memory.activeRegion[address & cpu->memory.activeMask];
 60}
 61
 62static void GBSetActiveRegion(struct SM83Core* cpu, uint16_t address) {
 63	struct GB* gb = (struct GB*) cpu->master;
 64	struct GBMemory* memory = &gb->memory;
 65	switch (address >> 12) {
 66	case GB_REGION_CART_BANK0:
 67	case GB_REGION_CART_BANK0 + 1:
 68	case GB_REGION_CART_BANK0 + 2:
 69	case GB_REGION_CART_BANK0 + 3:
 70		cpu->memory.cpuLoad8 = GBFastLoad8;
 71		cpu->memory.activeRegion = memory->romBase;
 72		cpu->memory.activeRegionEnd = GB_BASE_CART_BANK1;
 73		cpu->memory.activeMask = GB_SIZE_CART_BANK0 - 1;
 74		if (gb->memory.romSize < GB_SIZE_CART_BANK0) {
 75			if (address >= gb->memory.romSize) {
 76				cpu->memory.activeRegion = _yankBuffer;
 77				cpu->memory.activeMask = 0;
 78			} else {
 79				cpu->memory.activeRegionEnd = gb->memory.romSize;
 80			}
 81		}
 82		break;
 83	case GB_REGION_CART_BANK1:
 84	case GB_REGION_CART_BANK1 + 1:
 85	case GB_REGION_CART_BANK1 + 2:
 86	case GB_REGION_CART_BANK1 + 3:
 87		if ((gb->memory.mbcType & GB_UNL_BBD) == GB_UNL_BBD) {
 88			cpu->memory.cpuLoad8 = GBLoad8;
 89			break;
 90		}
 91		cpu->memory.cpuLoad8 = GBFastLoad8;
 92		if (gb->memory.mbcType != GB_MBC6) {
 93			cpu->memory.activeRegion = memory->romBank;
 94			cpu->memory.activeRegionEnd = GB_BASE_VRAM;
 95			cpu->memory.activeMask = GB_SIZE_CART_BANK0 - 1;
 96		} else {
 97			cpu->memory.activeMask = GB_SIZE_CART_HALFBANK - 1;
 98			if (address & 0x2000) {
 99				cpu->memory.activeRegion = memory->mbcState.mbc6.romBank1;
100				cpu->memory.activeRegionEnd = GB_BASE_VRAM;
101			} else {
102				cpu->memory.activeRegion = memory->romBank;
103				cpu->memory.activeRegionEnd = GB_BASE_CART_BANK1 + 0x2000;
104			}
105		}
106		if (gb->memory.romSize < GB_SIZE_CART_BANK0 * 2) {
107			if (address >= gb->memory.romSize) {
108				cpu->memory.activeRegion = _yankBuffer;
109				cpu->memory.activeMask = 0;
110			} else {
111				cpu->memory.activeRegionEnd = gb->memory.romSize;
112			}
113		}
114		break;
115	default:
116		cpu->memory.cpuLoad8 = GBLoad8;
117		break;
118	}
119	if (gb->memory.dmaRemaining) {
120		const enum GBBus* block = gb->model < GB_MODEL_CGB ? _oamBlockDMG : _oamBlockCGB;
121		enum GBBus dmaBus = block[memory->dmaSource >> 13];
122		enum GBBus accessBus = block[address >> 13];
123		if ((dmaBus != GB_BUS_CPU && dmaBus == accessBus) || (address >= GB_BASE_OAM && address < GB_BASE_UNUSABLE)) {
124			cpu->memory.activeRegion = _blockedRegion;
125			cpu->memory.activeMask = 0;
126		}
127	}
128}
129
130static void _GBMemoryDMAService(struct mTiming* timing, void* context, uint32_t cyclesLate);
131static void _GBMemoryHDMAService(struct mTiming* timing, void* context, uint32_t cyclesLate);
132
133void GBMemoryInit(struct GB* gb) {
134	struct SM83Core* cpu = gb->cpu;
135	cpu->memory.cpuLoad8 = GBLoad8;
136	cpu->memory.load8 = GBLoad8;
137	cpu->memory.store8 = GBStore8;
138	cpu->memory.currentSegment = GBCurrentSegment;
139	cpu->memory.setActiveRegion = GBSetActiveRegion;
140
141	gb->memory.wram = 0;
142	gb->memory.wramBank = 0;
143	gb->memory.rom = 0;
144	gb->memory.romBank = 0;
145	gb->memory.romSize = 0;
146	gb->memory.sram = 0;
147	gb->memory.mbcType = GB_MBC_AUTODETECT;
148	gb->memory.mbcRead = NULL;
149	gb->memory.mbcWrite = NULL;
150
151	gb->memory.rtc = NULL;
152	gb->memory.rotation = NULL;
153	gb->memory.rumble = NULL;
154	gb->memory.cam = NULL;
155
156	GBIOInit(gb);
157}
158
159void GBMemoryDeinit(struct GB* gb) {
160	mappedMemoryFree(gb->memory.wram, GB_SIZE_WORKING_RAM);
161	if (gb->memory.rom) {
162		mappedMemoryFree(gb->memory.rom, gb->memory.romSize);
163	}
164}
165
166void GBMemoryReset(struct GB* gb) {
167	if (gb->memory.wram) {
168		mappedMemoryFree(gb->memory.wram, GB_SIZE_WORKING_RAM);
169	}
170	gb->memory.wram = anonymousMemoryMap(GB_SIZE_WORKING_RAM);
171	if (gb->model >= GB_MODEL_CGB) {
172		uint32_t* base = (uint32_t*) gb->memory.wram;
173		size_t i;
174		uint32_t pattern = 0;
175		for (i = 0; i < GB_SIZE_WORKING_RAM / 4; i += 4) {
176			if ((i & 0x1FF) == 0) {
177				pattern = ~pattern;
178			}
179			base[i + 0] = pattern;
180			base[i + 1] = pattern;
181			base[i + 2] = ~pattern;
182			base[i + 3] = ~pattern;
183		}
184	}
185	GBMemorySwitchWramBank(&gb->memory, 1);
186	gb->memory.romBank = &gb->memory.rom[GB_SIZE_CART_BANK0];
187	gb->memory.currentBank = 1;
188	gb->memory.sramCurrentBank = 0;
189
190	gb->memory.ime = false;
191	gb->memory.ie = 0;
192
193	gb->memory.dmaRemaining = 0;
194	gb->memory.dmaSource = 0;
195	gb->memory.dmaDest = 0;
196	gb->memory.hdmaRemaining = 0;
197	gb->memory.hdmaSource = 0;
198	gb->memory.hdmaDest = 0;
199	gb->memory.isHdma = false;
200
201
202	gb->memory.dmaEvent.context = gb;
203	gb->memory.dmaEvent.name = "GB DMA";
204	gb->memory.dmaEvent.callback = _GBMemoryDMAService;
205	gb->memory.dmaEvent.priority = 0x40;
206	gb->memory.hdmaEvent.context = gb;
207	gb->memory.hdmaEvent.name = "GB HDMA";
208	gb->memory.hdmaEvent.callback = _GBMemoryHDMAService;
209	gb->memory.hdmaEvent.priority = 0x41;
210
211	memset(&gb->memory.hram, 0, sizeof(gb->memory.hram));
212
213	memset(&gb->memory.mbcState, 0, sizeof(gb->memory.mbcState));
214	GBMBCInit(gb);
215	switch (gb->memory.mbcType) {
216	case GB_MBC1:
217		gb->memory.mbcState.mbc1.mode = 0;
218		gb->memory.mbcState.mbc1.bankLo = 1;
219		break;
220	case GB_MBC6:
221		GBMBCSwitchHalfBank(gb, 0, 2);
222		GBMBCSwitchHalfBank(gb, 1, 3);
223		gb->memory.mbcState.mbc6.sramAccess = false;
224		GBMBCSwitchSramHalfBank(gb, 0, 0);
225		GBMBCSwitchSramHalfBank(gb, 0, 1);
226		break;
227	case GB_MMM01:
228		GBMBCSwitchBank0(gb, gb->memory.romSize / GB_SIZE_CART_BANK0 - 2);
229		GBMBCSwitchBank(gb, gb->memory.romSize / GB_SIZE_CART_BANK0 - 1);
230		break;
231	default:
232		break;
233	}
234	gb->memory.sramBank = gb->memory.sram;
235
236	if (!gb->memory.wram) {
237		GBMemoryDeinit(gb);
238	}
239}
240
241void GBMemorySwitchWramBank(struct GBMemory* memory, int bank) {
242	bank &= 7;
243	if (!bank) {
244		bank = 1;
245	}
246	memory->wramBank = &memory->wram[GB_SIZE_WORKING_RAM_BANK0 * bank];
247	memory->wramCurrentBank = bank;
248}
249
250uint8_t GBLoad8(struct SM83Core* cpu, uint16_t address) {
251	struct GB* gb = (struct GB*) cpu->master;
252	struct GBMemory* memory = &gb->memory;
253	if (gb->memory.dmaRemaining) {
254		const enum GBBus* block = gb->model < GB_MODEL_CGB ? _oamBlockDMG : _oamBlockCGB;
255		enum GBBus dmaBus = block[memory->dmaSource >> 13];
256		enum GBBus accessBus = block[address >> 13];
257		if (dmaBus != GB_BUS_CPU && dmaBus == accessBus) {
258			return 0xFF;
259		}
260		if (address >= GB_BASE_OAM && address < GB_BASE_IO) {
261			return 0xFF;
262		}
263	}
264	switch (address >> 12) {
265	case GB_REGION_CART_BANK0:
266	case GB_REGION_CART_BANK0 + 1:
267	case GB_REGION_CART_BANK0 + 2:
268	case GB_REGION_CART_BANK0 + 3:
269		if (address >= memory->romSize) {
270			return 0xFF;
271		}
272		return memory->romBase[address & (GB_SIZE_CART_BANK0 - 1)];
273	case GB_REGION_CART_BANK1 + 2:
274	case GB_REGION_CART_BANK1 + 3:
275		if (memory->mbcType == GB_MBC6) {
276			return memory->mbcState.mbc6.romBank1[address & (GB_SIZE_CART_HALFBANK - 1)];
277		}
278		// Fall through
279	case GB_REGION_CART_BANK1:
280	case GB_REGION_CART_BANK1 + 1:
281		if (address >= memory->romSize) {
282			return 0xFF;
283		}
284		if ((memory->mbcType & GB_UNL_BBD) == GB_UNL_BBD) {
285			return memory->mbcRead(memory, address);
286		}
287		return memory->romBank[address & (GB_SIZE_CART_BANK0 - 1)];
288	case GB_REGION_VRAM:
289	case GB_REGION_VRAM + 1:
290		if (gb->video.mode != 3) {
291			return gb->video.vramBank[address & (GB_SIZE_VRAM_BANK0 - 1)];
292		}
293		return 0xFF;
294	case GB_REGION_EXTERNAL_RAM:
295	case GB_REGION_EXTERNAL_RAM + 1:
296		if (memory->rtcAccess) {
297			return memory->rtcRegs[memory->activeRtcReg];
298		} else if (memory->mbcRead) {
299			return memory->mbcRead(memory, address);
300		} else if (memory->sramAccess && memory->sram) {
301			return memory->sramBank[address & (GB_SIZE_EXTERNAL_RAM - 1)];
302		} else if (memory->mbcType == GB_HuC3) {
303			return 0x01; // TODO: Is this supposed to be the current SRAM bank?
304		}
305		return 0xFF;
306	case GB_REGION_WORKING_RAM_BANK0:
307	case GB_REGION_WORKING_RAM_BANK0 + 2:
308		return memory->wram[address & (GB_SIZE_WORKING_RAM_BANK0 - 1)];
309	case GB_REGION_WORKING_RAM_BANK1:
310		return memory->wramBank[address & (GB_SIZE_WORKING_RAM_BANK0 - 1)];
311	default:
312		if (address < GB_BASE_OAM) {
313			return memory->wramBank[address & (GB_SIZE_WORKING_RAM_BANK0 - 1)];
314		}
315		if (address < GB_BASE_UNUSABLE) {
316			if (gb->video.mode < 2) {
317				return gb->video.oam.raw[address & 0xFF];
318			}
319			return 0xFF;
320		}
321		if (address < GB_BASE_IO) {
322			mLOG(GB_MEM, GAME_ERROR, "Attempt to read from unusable memory: %04X", address);
323			return 0xFF;
324		}
325		if (address < GB_BASE_HRAM) {
326			return GBIORead(gb, address & (GB_SIZE_IO - 1));
327		}
328		if (address < GB_BASE_IE) {
329			return memory->hram[address & GB_SIZE_HRAM];
330		}
331		return GBIORead(gb, GB_REG_IE);
332	}
333}
334
335void GBStore8(struct SM83Core* cpu, uint16_t address, int8_t value) {
336	struct GB* gb = (struct GB*) cpu->master;
337	struct GBMemory* memory = &gb->memory;
338	if (gb->memory.dmaRemaining) {
339		const enum GBBus* block = gb->model < GB_MODEL_CGB ? _oamBlockDMG : _oamBlockCGB;
340		enum GBBus dmaBus = block[memory->dmaSource >> 13];
341		enum GBBus accessBus = block[address >> 13];
342		if (dmaBus != GB_BUS_CPU && dmaBus == accessBus) {
343			return;
344		}
345		if (address >= GB_BASE_OAM && address < GB_BASE_UNUSABLE) {
346			return;
347		}
348	}
349	switch (address >> 12) {
350	case GB_REGION_CART_BANK0:
351	case GB_REGION_CART_BANK0 + 1:
352	case GB_REGION_CART_BANK0 + 2:
353	case GB_REGION_CART_BANK0 + 3:
354	case GB_REGION_CART_BANK1:
355	case GB_REGION_CART_BANK1 + 1:
356	case GB_REGION_CART_BANK1 + 2:
357	case GB_REGION_CART_BANK1 + 3:
358		memory->mbcWrite(gb, address, value);
359		cpu->memory.setActiveRegion(cpu, cpu->pc);
360		return;
361	case GB_REGION_VRAM:
362	case GB_REGION_VRAM + 1:
363		if (gb->video.mode != 3) {
364			gb->video.renderer->writeVRAM(gb->video.renderer, (address & (GB_SIZE_VRAM_BANK0 - 1)) | (GB_SIZE_VRAM_BANK0 * gb->video.vramCurrentBank));
365			gb->video.vramBank[address & (GB_SIZE_VRAM_BANK0 - 1)] = value;
366		}
367		return;
368	case GB_REGION_EXTERNAL_RAM:
369	case GB_REGION_EXTERNAL_RAM + 1:
370		if (memory->rtcAccess) {
371			memory->rtcRegs[memory->activeRtcReg] = value;
372		} else if (memory->sramAccess && memory->sram && memory->directSramAccess) {
373			memory->sramBank[address & (GB_SIZE_EXTERNAL_RAM - 1)] = value;
374		} else {
375			memory->mbcWrite(gb, address, value);
376		}
377		gb->sramDirty |= GB_SRAM_DIRT_NEW;
378		return;
379	case GB_REGION_WORKING_RAM_BANK0:
380	case GB_REGION_WORKING_RAM_BANK0 + 2:
381		memory->wram[address & (GB_SIZE_WORKING_RAM_BANK0 - 1)] = value;
382		return;
383	case GB_REGION_WORKING_RAM_BANK1:
384		memory->wramBank[address & (GB_SIZE_WORKING_RAM_BANK0 - 1)] = value;
385		return;
386	default:
387		if (address < GB_BASE_OAM) {
388			memory->wramBank[address & (GB_SIZE_WORKING_RAM_BANK0 - 1)] = value;
389		} else if (address < GB_BASE_UNUSABLE) {
390			if (gb->video.mode < 2) {
391				gb->video.oam.raw[address & 0xFF] = value;
392				gb->video.renderer->writeOAM(gb->video.renderer, address & 0xFF);
393			}
394		} else if (address < GB_BASE_IO) {
395			mLOG(GB_MEM, GAME_ERROR, "Attempt to write to unusable memory: %04X:%02X", address, value);
396		} else if (address < GB_BASE_HRAM) {
397			GBIOWrite(gb, address & (GB_SIZE_IO - 1), value);
398		} else if (address < GB_BASE_IE) {
399			memory->hram[address & GB_SIZE_HRAM] = value;
400		} else {
401			GBIOWrite(gb, GB_REG_IE, value);
402		}
403	}
404}
405
406int GBCurrentSegment(struct SM83Core* cpu, uint16_t address) {
407	struct GB* gb = (struct GB*) cpu->master;
408	struct GBMemory* memory = &gb->memory;
409	switch (address >> 12) {
410	case GB_REGION_CART_BANK0:
411	case GB_REGION_CART_BANK0 + 1:
412	case GB_REGION_CART_BANK0 + 2:
413	case GB_REGION_CART_BANK0 + 3:
414		return 0;
415	case GB_REGION_CART_BANK1:
416	case GB_REGION_CART_BANK1 + 1:
417	case GB_REGION_CART_BANK1 + 2:
418	case GB_REGION_CART_BANK1 + 3:
419		return memory->currentBank;
420	case GB_REGION_VRAM:
421	case GB_REGION_VRAM + 1:
422		return gb->video.vramCurrentBank;
423	case GB_REGION_EXTERNAL_RAM:
424	case GB_REGION_EXTERNAL_RAM + 1:
425		return memory->sramCurrentBank;
426	case GB_REGION_WORKING_RAM_BANK0:
427	case GB_REGION_WORKING_RAM_BANK0 + 2:
428		return 0;
429	case GB_REGION_WORKING_RAM_BANK1:
430		return memory->wramCurrentBank;
431	default:
432		return 0;
433	}
434}
435
436uint8_t GBView8(struct SM83Core* cpu, uint16_t address, int segment) {
437	struct GB* gb = (struct GB*) cpu->master;
438	struct GBMemory* memory = &gb->memory;
439	switch (address >> 12) {
440	case GB_REGION_CART_BANK0:
441	case GB_REGION_CART_BANK0 + 1:
442	case GB_REGION_CART_BANK0 + 2:
443	case GB_REGION_CART_BANK0 + 3:
444		return memory->romBase[address & (GB_SIZE_CART_BANK0 - 1)];
445	case GB_REGION_CART_BANK1:
446	case GB_REGION_CART_BANK1 + 1:
447	case GB_REGION_CART_BANK1 + 2:
448	case GB_REGION_CART_BANK1 + 3:
449		if (segment < 0) {
450			return memory->romBank[address & (GB_SIZE_CART_BANK0 - 1)];
451		} else if ((size_t) segment * GB_SIZE_CART_BANK0 < memory->romSize) {
452			return memory->rom[(address & (GB_SIZE_CART_BANK0 - 1)) + segment * GB_SIZE_CART_BANK0];
453		} else {
454			return 0xFF;
455		}
456	case GB_REGION_VRAM:
457	case GB_REGION_VRAM + 1:
458		if (segment < 0) {
459			return gb->video.vramBank[address & (GB_SIZE_VRAM_BANK0 - 1)];
460		} else if (segment < 2) {
461			return gb->video.vram[(address & (GB_SIZE_VRAM_BANK0 - 1)) + segment *GB_SIZE_VRAM_BANK0];
462		} else {
463			return 0xFF;
464		}
465	case GB_REGION_EXTERNAL_RAM:
466	case GB_REGION_EXTERNAL_RAM + 1:
467		if (memory->rtcAccess) {
468			return memory->rtcRegs[memory->activeRtcReg];
469		} else if (memory->sramAccess) {
470			if (segment < 0 && memory->sram) {
471				return memory->sramBank[address & (GB_SIZE_EXTERNAL_RAM - 1)];
472			} else if ((size_t) segment * GB_SIZE_EXTERNAL_RAM < gb->sramSize) {
473				return memory->sram[(address & (GB_SIZE_EXTERNAL_RAM - 1)) + segment *GB_SIZE_EXTERNAL_RAM];
474			} else {
475				return 0xFF;
476			}
477		} else if (memory->mbcRead) {
478			return memory->mbcRead(memory, address);
479		} else if (memory->mbcType == GB_HuC3) {
480			return 0x01; // TODO: Is this supposed to be the current SRAM bank?
481		}
482		return 0xFF;
483	case GB_REGION_WORKING_RAM_BANK0:
484	case GB_REGION_WORKING_RAM_BANK0 + 2:
485		return memory->wram[address & (GB_SIZE_WORKING_RAM_BANK0 - 1)];
486	case GB_REGION_WORKING_RAM_BANK1:
487		if (segment < 0) {
488			return memory->wramBank[address & (GB_SIZE_WORKING_RAM_BANK0 - 1)];
489		} else if (segment < 8) {
490			return memory->wram[(address & (GB_SIZE_WORKING_RAM_BANK0 - 1)) + segment *GB_SIZE_WORKING_RAM_BANK0];
491		} else {
492			return 0xFF;
493		}
494	default:
495		if (address < GB_BASE_OAM) {
496			return memory->wramBank[address & (GB_SIZE_WORKING_RAM_BANK0 - 1)];
497		}
498		if (address < GB_BASE_UNUSABLE) {
499			if (gb->video.mode < 2) {
500				return gb->video.oam.raw[address & 0xFF];
501			}
502			return 0xFF;
503		}
504		if (address < GB_BASE_IO) {
505			mLOG(GB_MEM, GAME_ERROR, "Attempt to read from unusable memory: %04X", address);
506			if (gb->video.mode < 2) {
507				switch (gb->model) {
508				case GB_MODEL_AGB:
509					return (address & 0xF0) | ((address >> 4) & 0xF);
510				case GB_MODEL_CGB:
511					// TODO: R/W behavior
512					return 0x00;
513				default:
514					return 0x00;
515				}
516			}
517			return 0xFF;
518		}
519		if (address < GB_BASE_HRAM) {
520			return GBIORead(gb, address & (GB_SIZE_IO - 1));
521		}
522		if (address < GB_BASE_IE) {
523			return memory->hram[address & GB_SIZE_HRAM];
524		}
525		return GBIORead(gb, GB_REG_IE);
526	}
527}
528
529void GBMemoryDMA(struct GB* gb, uint16_t base) {
530	if (base >= 0xE000) {
531		base &= 0xDFFF;
532	}
533	mTimingDeschedule(&gb->timing, &gb->memory.dmaEvent);
534	mTimingSchedule(&gb->timing, &gb->memory.dmaEvent, 8 * (2 - gb->doubleSpeed));
535	gb->memory.dmaSource = base;
536	gb->memory.dmaDest = 0;
537	gb->memory.dmaRemaining = 0xA0;
538}
539
540uint8_t GBMemoryWriteHDMA5(struct GB* gb, uint8_t value) {
541	gb->memory.hdmaSource = gb->memory.io[GB_REG_HDMA1] << 8;
542	gb->memory.hdmaSource |= gb->memory.io[GB_REG_HDMA2];
543	gb->memory.hdmaDest = gb->memory.io[GB_REG_HDMA3] << 8;
544	gb->memory.hdmaDest |= gb->memory.io[GB_REG_HDMA4];
545	gb->memory.hdmaSource &= 0xFFF0;
546	if (gb->memory.hdmaSource >= 0x8000 && gb->memory.hdmaSource < 0xA000) {
547		mLOG(GB_MEM, GAME_ERROR, "Invalid HDMA source: %04X", gb->memory.hdmaSource);
548		return value | 0x80;
549	}
550	gb->memory.hdmaDest &= 0x1FF0;
551	gb->memory.hdmaDest |= 0x8000;
552	bool wasHdma = gb->memory.isHdma;
553	gb->memory.isHdma = value & 0x80;
554	if ((!wasHdma && !gb->memory.isHdma) || (GBRegisterLCDCIsEnable(gb->memory.io[GB_REG_LCDC]) && gb->video.mode == 0)) {
555		if (gb->memory.isHdma) {
556			gb->memory.hdmaRemaining = 0x10;
557		} else {
558			gb->memory.hdmaRemaining = ((value & 0x7F) + 1) * 0x10;
559		}
560		gb->cpuBlocked = true;
561		mTimingSchedule(&gb->timing, &gb->memory.hdmaEvent, 0);
562	} else if (gb->memory.isHdma && !GBRegisterLCDCIsEnable(gb->memory.io[GB_REG_LCDC])) {
563		return 0x80 | ((value + 1) & 0x7F);
564	}
565	return value & 0x7F;
566}
567
568void _GBMemoryDMAService(struct mTiming* timing, void* context, uint32_t cyclesLate) {
569	struct GB* gb = context;
570	int dmaRemaining = gb->memory.dmaRemaining;
571	gb->memory.dmaRemaining = 0;
572	uint8_t b = GBLoad8(gb->cpu, gb->memory.dmaSource);
573	// TODO: Can DMA write OAM during modes 2-3?
574	gb->video.oam.raw[gb->memory.dmaDest] = b;
575	gb->video.renderer->writeOAM(gb->video.renderer, gb->memory.dmaDest);
576	++gb->memory.dmaSource;
577	++gb->memory.dmaDest;
578	gb->memory.dmaRemaining = dmaRemaining - 1;
579	if (gb->memory.dmaRemaining) {
580		mTimingSchedule(timing, &gb->memory.dmaEvent, 4 * (2 - gb->doubleSpeed) - cyclesLate);
581	}
582}
583
584void _GBMemoryHDMAService(struct mTiming* timing, void* context, uint32_t cyclesLate) {
585	struct GB* gb = context;
586	gb->cpuBlocked = true;
587	uint8_t b = gb->cpu->memory.load8(gb->cpu, gb->memory.hdmaSource);
588	gb->cpu->memory.store8(gb->cpu, gb->memory.hdmaDest, b);
589	++gb->memory.hdmaSource;
590	++gb->memory.hdmaDest;
591	--gb->memory.hdmaRemaining;
592	if (gb->memory.hdmaRemaining) {
593		mTimingDeschedule(timing, &gb->memory.hdmaEvent);
594		mTimingSchedule(timing, &gb->memory.hdmaEvent, 4 - cyclesLate);
595	} else {
596		gb->cpuBlocked = false;
597		gb->memory.io[GB_REG_HDMA1] = gb->memory.hdmaSource >> 8;
598		gb->memory.io[GB_REG_HDMA2] = gb->memory.hdmaSource;
599		gb->memory.io[GB_REG_HDMA3] = gb->memory.hdmaDest >> 8;
600		gb->memory.io[GB_REG_HDMA4] = gb->memory.hdmaDest;
601		if (gb->memory.isHdma) {
602			--gb->memory.io[GB_REG_HDMA5];
603			if (gb->memory.io[GB_REG_HDMA5] == 0xFF) {
604				gb->memory.isHdma = false;
605			}
606		} else {
607			gb->memory.io[GB_REG_HDMA5] = 0xFF;
608		}
609	}
610}
611
612void GBPatch8(struct SM83Core* cpu, uint16_t address, int8_t value, int8_t* old, int segment) {
613	struct GB* gb = (struct GB*) cpu->master;
614	struct GBMemory* memory = &gb->memory;
615	int8_t oldValue = -1;
616
617	switch (address >> 12) {
618	case GB_REGION_CART_BANK0:
619	case GB_REGION_CART_BANK0 + 1:
620	case GB_REGION_CART_BANK0 + 2:
621	case GB_REGION_CART_BANK0 + 3:
622		_pristineCow(gb);
623		oldValue = memory->romBase[address & (GB_SIZE_CART_BANK0 - 1)];
624		memory->romBase[address & (GB_SIZE_CART_BANK0 - 1)] =  value;
625		break;
626	case GB_REGION_CART_BANK1:
627	case GB_REGION_CART_BANK1 + 1:
628	case GB_REGION_CART_BANK1 + 2:
629	case GB_REGION_CART_BANK1 + 3:
630		_pristineCow(gb);
631		if (segment < 0) {
632			oldValue = memory->romBank[address & (GB_SIZE_CART_BANK0 - 1)];
633			memory->romBank[address & (GB_SIZE_CART_BANK0 - 1)] = value;
634		} else if ((size_t) segment * GB_SIZE_CART_BANK0 < memory->romSize) {
635			oldValue = memory->rom[(address & (GB_SIZE_CART_BANK0 - 1)) + segment * GB_SIZE_CART_BANK0];
636			memory->rom[(address & (GB_SIZE_CART_BANK0 - 1)) + segment * GB_SIZE_CART_BANK0] = value;
637		} else {
638			return;
639		}
640		break;
641	case GB_REGION_VRAM:
642	case GB_REGION_VRAM + 1:
643		if (segment < 0) {
644			oldValue = gb->video.vramBank[address & (GB_SIZE_VRAM_BANK0 - 1)];
645			gb->video.vramBank[address & (GB_SIZE_VRAM_BANK0 - 1)] = value;
646			gb->video.renderer->writeVRAM(gb->video.renderer, (address & (GB_SIZE_VRAM_BANK0 - 1)) + GB_SIZE_VRAM_BANK0 * gb->video.vramCurrentBank);
647		} else if (segment < 2) {
648			oldValue = gb->video.vram[(address & (GB_SIZE_VRAM_BANK0 - 1)) + segment * GB_SIZE_VRAM_BANK0];
649			gb->video.vramBank[(address & (GB_SIZE_VRAM_BANK0 - 1)) + segment * GB_SIZE_VRAM_BANK0] = value;
650			gb->video.renderer->writeVRAM(gb->video.renderer, (address & (GB_SIZE_VRAM_BANK0 - 1)) + segment * GB_SIZE_VRAM_BANK0);
651		} else {
652			return;
653		}
654		break;
655	case GB_REGION_EXTERNAL_RAM:
656	case GB_REGION_EXTERNAL_RAM + 1:
657		if (memory->rtcAccess) {
658			memory->rtcRegs[memory->activeRtcReg] = value;
659		} else if (memory->sramAccess && memory->sram && memory->mbcType != GB_MBC2) {
660			// TODO: Remove sramAccess check?
661			memory->sramBank[address & (GB_SIZE_EXTERNAL_RAM - 1)] = value;
662		} else {
663			memory->mbcWrite(gb, address, value);
664		}
665		gb->sramDirty |= GB_SRAM_DIRT_NEW;
666		return;
667	case GB_REGION_WORKING_RAM_BANK0:
668	case GB_REGION_WORKING_RAM_BANK0 + 2:
669		oldValue = memory->wram[address & (GB_SIZE_WORKING_RAM_BANK0 - 1)];
670		memory->wram[address & (GB_SIZE_WORKING_RAM_BANK0 - 1)] = value;
671		break;
672	case GB_REGION_WORKING_RAM_BANK1:
673		if (segment < 0) {
674			oldValue = memory->wramBank[address & (GB_SIZE_WORKING_RAM_BANK0 - 1)];
675			memory->wramBank[address & (GB_SIZE_WORKING_RAM_BANK0 - 1)] = value;
676		} else if (segment < 8) {
677			oldValue = memory->wram[(address & (GB_SIZE_WORKING_RAM_BANK0 - 1)) + segment * GB_SIZE_WORKING_RAM_BANK0];
678			memory->wram[(address & (GB_SIZE_WORKING_RAM_BANK0 - 1)) + segment * GB_SIZE_WORKING_RAM_BANK0] = value;
679		} else {
680			return;
681		}
682		break;
683	default:
684		if (address < GB_BASE_OAM) {
685			oldValue = memory->wramBank[address & (GB_SIZE_WORKING_RAM_BANK0 - 1)];
686			memory->wramBank[address & (GB_SIZE_WORKING_RAM_BANK0 - 1)] = value;
687		} else if (address < GB_BASE_UNUSABLE) {
688			oldValue = gb->video.oam.raw[address & 0xFF];
689			gb->video.oam.raw[address & 0xFF] = value;
690			gb->video.renderer->writeOAM(gb->video.renderer, address & 0xFF);
691		} else if (address < GB_BASE_HRAM) {
692			mLOG(GB_MEM, STUB, "Unimplemented memory Patch8: 0x%08X", address);
693			return;
694		} else if (address < GB_BASE_IE) {
695			oldValue = memory->hram[address & GB_SIZE_HRAM];
696			memory->hram[address & GB_SIZE_HRAM] = value;
697		} else {
698			mLOG(GB_MEM, STUB, "Unimplemented memory Patch8: 0x%08X", address);
699			return;
700		}
701	}
702	if (old) {
703		*old = oldValue;
704	}
705}
706
707void GBMemorySerialize(const struct GB* gb, struct GBSerializedState* state) {
708	const struct GBMemory* memory = &gb->memory;
709	memcpy(state->wram, memory->wram, GB_SIZE_WORKING_RAM);
710	memcpy(state->hram, memory->hram, GB_SIZE_HRAM);
711	STORE_16LE(memory->currentBank, 0, &state->memory.currentBank);
712	state->memory.wramCurrentBank = memory->wramCurrentBank;
713	state->memory.sramCurrentBank = memory->sramCurrentBank;
714
715	STORE_16LE(memory->dmaSource, 0, &state->memory.dmaSource);
716	STORE_16LE(memory->dmaDest, 0, &state->memory.dmaDest);
717
718	STORE_16LE(memory->hdmaSource, 0, &state->memory.hdmaSource);
719	STORE_16LE(memory->hdmaDest, 0, &state->memory.hdmaDest);
720
721	STORE_16LE(memory->hdmaRemaining, 0, &state->memory.hdmaRemaining);
722	state->memory.dmaRemaining = memory->dmaRemaining;
723	memcpy(state->memory.rtcRegs, memory->rtcRegs, sizeof(state->memory.rtcRegs));
724
725	STORE_32LE(memory->dmaEvent.when - mTimingCurrentTime(&gb->timing), 0, &state->memory.dmaNext);
726	STORE_32LE(memory->hdmaEvent.when - mTimingCurrentTime(&gb->timing), 0, &state->memory.hdmaNext);
727
728	GBSerializedMemoryFlags flags = 0;
729	flags = GBSerializedMemoryFlagsSetSramAccess(flags, memory->sramAccess);
730	flags = GBSerializedMemoryFlagsSetRtcAccess(flags, memory->rtcAccess);
731	flags = GBSerializedMemoryFlagsSetRtcLatched(flags, memory->rtcLatched);
732	flags = GBSerializedMemoryFlagsSetIme(flags, memory->ime);
733	flags = GBSerializedMemoryFlagsSetIsHdma(flags, memory->isHdma);
734	flags = GBSerializedMemoryFlagsSetActiveRtcReg(flags, memory->activeRtcReg);
735	STORE_16LE(flags, 0, &state->memory.flags);
736
737	switch (memory->mbcType) {
738	case GB_MBC1:
739		state->memory.mbc1.mode = memory->mbcState.mbc1.mode;
740		state->memory.mbc1.multicartStride = memory->mbcState.mbc1.multicartStride;
741		state->memory.mbc1.bankLo = memory->mbcState.mbc1.bankLo;
742		state->memory.mbc1.bankHi = memory->mbcState.mbc1.bankHi;
743		break;
744	case GB_MBC3_RTC:
745		STORE_64LE(gb->memory.rtcLastLatch, 0, &state->memory.rtc.lastLatch);
746		break;
747	case GB_MBC7:
748		state->memory.mbc7.state = memory->mbcState.mbc7.state;
749		state->memory.mbc7.eeprom = memory->mbcState.mbc7.eeprom;
750		state->memory.mbc7.address = memory->mbcState.mbc7.address;
751		state->memory.mbc7.access = memory->mbcState.mbc7.access;
752		state->memory.mbc7.latch = memory->mbcState.mbc7.latch;
753		state->memory.mbc7.srBits = memory->mbcState.mbc7.srBits;
754		STORE_16LE(memory->mbcState.mbc7.sr, 0, &state->memory.mbc7.sr);
755		STORE_32LE(memory->mbcState.mbc7.writable, 0, &state->memory.mbc7.writable);
756		break;
757	case GB_MMM01:
758		state->memory.mmm01.locked = memory->mbcState.mmm01.locked;
759		state->memory.mmm01.bank0 = memory->mbcState.mmm01.currentBank0;
760		break;
761	case GB_UNL_BBD:
762	case GB_UNL_HITEK:
763		state->memory.bbd.dataSwapMode = memory->mbcState.bbd.dataSwapMode;
764		state->memory.bbd.bankSwapMode = memory->mbcState.bbd.bankSwapMode;
765		break;
766	default:
767		break;
768	}
769}
770
771void GBMemoryDeserialize(struct GB* gb, const struct GBSerializedState* state) {
772	struct GBMemory* memory = &gb->memory;
773	memcpy(memory->wram, state->wram, GB_SIZE_WORKING_RAM);
774	memcpy(memory->hram, state->hram, GB_SIZE_HRAM);
775	LOAD_16LE(memory->currentBank, 0, &state->memory.currentBank);
776	memory->wramCurrentBank = state->memory.wramCurrentBank;
777	memory->sramCurrentBank = state->memory.sramCurrentBank;
778
779	GBMBCSwitchBank(gb, memory->currentBank);
780	GBMemorySwitchWramBank(memory, memory->wramCurrentBank);
781	GBMBCSwitchSramBank(gb, memory->sramCurrentBank);
782
783	LOAD_16LE(memory->dmaSource, 0, &state->memory.dmaSource);
784	LOAD_16LE(memory->dmaDest, 0, &state->memory.dmaDest);
785
786	LOAD_16LE(memory->hdmaSource, 0, &state->memory.hdmaSource);
787	LOAD_16LE(memory->hdmaDest, 0, &state->memory.hdmaDest);
788
789	LOAD_16LE(memory->hdmaRemaining, 0, &state->memory.hdmaRemaining);
790	memory->dmaRemaining = state->memory.dmaRemaining;
791	memcpy(memory->rtcRegs, state->memory.rtcRegs, sizeof(state->memory.rtcRegs));
792
793	uint32_t when;
794	LOAD_32LE(when, 0, &state->memory.dmaNext);
795	if (memory->dmaRemaining) {
796		mTimingSchedule(&gb->timing, &memory->dmaEvent, when);
797	} else {
798		memory->dmaEvent.when = when + mTimingCurrentTime(&gb->timing);
799	}
800	LOAD_32LE(when, 0, &state->memory.hdmaNext);
801	if (memory->hdmaRemaining) {
802		mTimingSchedule(&gb->timing, &memory->hdmaEvent, when);
803	} else {
804		memory->hdmaEvent.when = when + mTimingCurrentTime(&gb->timing);
805	}
806
807	GBSerializedMemoryFlags flags;
808	LOAD_16LE(flags, 0, &state->memory.flags);
809	memory->sramAccess = GBSerializedMemoryFlagsGetSramAccess(flags);
810	memory->rtcAccess = GBSerializedMemoryFlagsGetRtcAccess(flags);
811	memory->rtcLatched = GBSerializedMemoryFlagsGetRtcLatched(flags);
812	memory->ime = GBSerializedMemoryFlagsGetIme(flags);
813	memory->isHdma = GBSerializedMemoryFlagsGetIsHdma(flags);
814	memory->activeRtcReg = GBSerializedMemoryFlagsGetActiveRtcReg(flags);
815
816	switch (memory->mbcType) {
817	case GB_MBC1:
818		memory->mbcState.mbc1.mode = state->memory.mbc1.mode;
819		memory->mbcState.mbc1.multicartStride = state->memory.mbc1.multicartStride;
820		memory->mbcState.mbc1.bankLo = state->memory.mbc1.bankLo;
821		memory->mbcState.mbc1.bankHi = state->memory.mbc1.bankHi;
822		if (!(memory->mbcState.mbc1.bankLo || memory->mbcState.mbc1.bankHi)) {
823			// Backwards compat
824			memory->mbcState.mbc1.bankLo = memory->currentBank & ((1 << memory->mbcState.mbc1.multicartStride) - 1);
825			memory->mbcState.mbc1.bankHi = memory->currentBank >> memory->mbcState.mbc1.multicartStride;
826		}
827		if (memory->mbcState.mbc1.mode) {
828			GBMBCSwitchBank0(gb, memory->mbcState.mbc1.bankHi);
829		}
830		break;
831	case GB_MBC3_RTC:
832		LOAD_64LE(gb->memory.rtcLastLatch, 0, &state->memory.rtc.lastLatch);
833		break;
834	case GB_MBC7:
835		memory->mbcState.mbc7.state = state->memory.mbc7.state;
836		memory->mbcState.mbc7.eeprom = state->memory.mbc7.eeprom;
837		memory->mbcState.mbc7.address = state->memory.mbc7.address & 0x7F;
838		memory->mbcState.mbc7.access = state->memory.mbc7.access;
839		memory->mbcState.mbc7.latch = state->memory.mbc7.latch;
840		memory->mbcState.mbc7.srBits = state->memory.mbc7.srBits;
841		LOAD_16LE(memory->mbcState.mbc7.sr, 0, &state->memory.mbc7.sr);
842		LOAD_32LE(memory->mbcState.mbc7.writable, 0, &state->memory.mbc7.writable);
843		break;
844	case GB_MMM01:
845		memory->mbcState.mmm01.locked = state->memory.mmm01.locked;
846		memory->mbcState.mmm01.currentBank0 = state->memory.mmm01.bank0;
847		if (memory->mbcState.mmm01.locked) {
848			GBMBCSwitchBank0(gb, memory->mbcState.mmm01.currentBank0);
849		} else {
850			GBMBCSwitchBank0(gb, gb->memory.romSize / GB_SIZE_CART_BANK0 - 2);
851		}
852		break;
853	case GB_UNL_BBD:
854	case GB_UNL_HITEK:
855		memory->mbcState.bbd.dataSwapMode = state->memory.bbd.dataSwapMode & 0x7;
856		memory->mbcState.bbd.bankSwapMode = state->memory.bbd.bankSwapMode & 0x7;
857		break;
858	default:
859		break;
860	}
861}
862
863void _pristineCow(struct GB* gb) {
864	if (!gb->isPristine) {
865		return;
866	}
867	void* newRom = anonymousMemoryMap(GB_SIZE_CART_MAX);
868	memcpy(newRom, gb->memory.rom, gb->memory.romSize);
869	memset(((uint8_t*) newRom) + gb->memory.romSize, 0xFF, GB_SIZE_CART_MAX - gb->memory.romSize);
870	if (gb->memory.rom == gb->memory.romBase) {
871		gb->memory.romBase = newRom;
872	}
873	gb->memory.rom = newRom;
874	GBMBCSwitchBank(gb, gb->memory.currentBank);
875	gb->isPristine = false;
876}