all repos — mgba @ ac8d1e2bf6169b4adbe1f9e28f36c381f1b6097d

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);
535	if (gb->cpu->cycles + 8 < gb->cpu->nextEvent) {
536		gb->cpu->nextEvent = gb->cpu->cycles + 8;
537	}
538	gb->memory.dmaSource = base;
539	gb->memory.dmaDest = 0;
540	gb->memory.dmaRemaining = 0xA0;
541}
542
543uint8_t GBMemoryWriteHDMA5(struct GB* gb, uint8_t value) {
544	gb->memory.hdmaSource = gb->memory.io[GB_REG_HDMA1] << 8;
545	gb->memory.hdmaSource |= gb->memory.io[GB_REG_HDMA2];
546	gb->memory.hdmaDest = gb->memory.io[GB_REG_HDMA3] << 8;
547	gb->memory.hdmaDest |= gb->memory.io[GB_REG_HDMA4];
548	gb->memory.hdmaSource &= 0xFFF0;
549	if (gb->memory.hdmaSource >= 0x8000 && gb->memory.hdmaSource < 0xA000) {
550		mLOG(GB_MEM, GAME_ERROR, "Invalid HDMA source: %04X", gb->memory.hdmaSource);
551		return value | 0x80;
552	}
553	gb->memory.hdmaDest &= 0x1FF0;
554	gb->memory.hdmaDest |= 0x8000;
555	bool wasHdma = gb->memory.isHdma;
556	gb->memory.isHdma = value & 0x80;
557	if ((!wasHdma && !gb->memory.isHdma) || (GBRegisterLCDCIsEnable(gb->memory.io[GB_REG_LCDC]) && gb->video.mode == 0)) {
558		if (gb->memory.isHdma) {
559			gb->memory.hdmaRemaining = 0x10;
560		} else {
561			gb->memory.hdmaRemaining = ((value & 0x7F) + 1) * 0x10;
562		}
563		gb->cpuBlocked = true;
564		mTimingSchedule(&gb->timing, &gb->memory.hdmaEvent, 0);
565	} else if (gb->memory.isHdma && !GBRegisterLCDCIsEnable(gb->memory.io[GB_REG_LCDC])) {
566		return 0x80 | ((value + 1) & 0x7F);
567	}
568	return value & 0x7F;
569}
570
571void _GBMemoryDMAService(struct mTiming* timing, void* context, uint32_t cyclesLate) {
572	struct GB* gb = context;
573	int dmaRemaining = gb->memory.dmaRemaining;
574	gb->memory.dmaRemaining = 0;
575	uint8_t b = GBLoad8(gb->cpu, gb->memory.dmaSource);
576	// TODO: Can DMA write OAM during modes 2-3?
577	gb->video.oam.raw[gb->memory.dmaDest] = b;
578	gb->video.renderer->writeOAM(gb->video.renderer, gb->memory.dmaDest);
579	++gb->memory.dmaSource;
580	++gb->memory.dmaDest;
581	gb->memory.dmaRemaining = dmaRemaining - 1;
582	if (gb->memory.dmaRemaining) {
583		mTimingSchedule(timing, &gb->memory.dmaEvent, 4 - cyclesLate);
584	}
585}
586
587void _GBMemoryHDMAService(struct mTiming* timing, void* context, uint32_t cyclesLate) {
588	struct GB* gb = context;
589	gb->cpuBlocked = true;
590	uint8_t b = gb->cpu->memory.load8(gb->cpu, gb->memory.hdmaSource);
591	gb->cpu->memory.store8(gb->cpu, gb->memory.hdmaDest, b);
592	++gb->memory.hdmaSource;
593	++gb->memory.hdmaDest;
594	--gb->memory.hdmaRemaining;
595	if (gb->memory.hdmaRemaining) {
596		mTimingDeschedule(timing, &gb->memory.hdmaEvent);
597		mTimingSchedule(timing, &gb->memory.hdmaEvent, 2 - cyclesLate);
598	} else {
599		gb->cpuBlocked = false;
600		gb->memory.io[GB_REG_HDMA1] = gb->memory.hdmaSource >> 8;
601		gb->memory.io[GB_REG_HDMA2] = gb->memory.hdmaSource;
602		gb->memory.io[GB_REG_HDMA3] = gb->memory.hdmaDest >> 8;
603		gb->memory.io[GB_REG_HDMA4] = gb->memory.hdmaDest;
604		if (gb->memory.isHdma) {
605			--gb->memory.io[GB_REG_HDMA5];
606			if (gb->memory.io[GB_REG_HDMA5] == 0xFF) {
607				gb->memory.isHdma = false;
608			}
609		} else {
610			gb->memory.io[GB_REG_HDMA5] = 0xFF;
611		}
612	}
613}
614
615void GBPatch8(struct SM83Core* cpu, uint16_t address, int8_t value, int8_t* old, int segment) {
616	struct GB* gb = (struct GB*) cpu->master;
617	struct GBMemory* memory = &gb->memory;
618	int8_t oldValue = -1;
619
620	switch (address >> 12) {
621	case GB_REGION_CART_BANK0:
622	case GB_REGION_CART_BANK0 + 1:
623	case GB_REGION_CART_BANK0 + 2:
624	case GB_REGION_CART_BANK0 + 3:
625		_pristineCow(gb);
626		oldValue = memory->romBase[address & (GB_SIZE_CART_BANK0 - 1)];
627		memory->romBase[address & (GB_SIZE_CART_BANK0 - 1)] =  value;
628		break;
629	case GB_REGION_CART_BANK1:
630	case GB_REGION_CART_BANK1 + 1:
631	case GB_REGION_CART_BANK1 + 2:
632	case GB_REGION_CART_BANK1 + 3:
633		_pristineCow(gb);
634		if (segment < 0) {
635			oldValue = memory->romBank[address & (GB_SIZE_CART_BANK0 - 1)];
636			memory->romBank[address & (GB_SIZE_CART_BANK0 - 1)] = value;
637		} else if ((size_t) segment * GB_SIZE_CART_BANK0 < memory->romSize) {
638			oldValue = memory->rom[(address & (GB_SIZE_CART_BANK0 - 1)) + segment * GB_SIZE_CART_BANK0];
639			memory->rom[(address & (GB_SIZE_CART_BANK0 - 1)) + segment * GB_SIZE_CART_BANK0] = value;
640		} else {
641			return;
642		}
643		break;
644	case GB_REGION_VRAM:
645	case GB_REGION_VRAM + 1:
646		if (segment < 0) {
647			oldValue = gb->video.vramBank[address & (GB_SIZE_VRAM_BANK0 - 1)];
648			gb->video.vramBank[address & (GB_SIZE_VRAM_BANK0 - 1)] = value;
649			gb->video.renderer->writeVRAM(gb->video.renderer, (address & (GB_SIZE_VRAM_BANK0 - 1)) + GB_SIZE_VRAM_BANK0 * gb->video.vramCurrentBank);
650		} else if (segment < 2) {
651			oldValue = gb->video.vram[(address & (GB_SIZE_VRAM_BANK0 - 1)) + segment * GB_SIZE_VRAM_BANK0];
652			gb->video.vramBank[(address & (GB_SIZE_VRAM_BANK0 - 1)) + segment * GB_SIZE_VRAM_BANK0] = value;
653			gb->video.renderer->writeVRAM(gb->video.renderer, (address & (GB_SIZE_VRAM_BANK0 - 1)) + segment * GB_SIZE_VRAM_BANK0);
654		} else {
655			return;
656		}
657		break;
658	case GB_REGION_EXTERNAL_RAM:
659	case GB_REGION_EXTERNAL_RAM + 1:
660		if (memory->rtcAccess) {
661			memory->rtcRegs[memory->activeRtcReg] = value;
662		} else if (memory->sramAccess && memory->sram && memory->mbcType != GB_MBC2) {
663			// TODO: Remove sramAccess check?
664			memory->sramBank[address & (GB_SIZE_EXTERNAL_RAM - 1)] = value;
665		} else {
666			memory->mbcWrite(gb, address, value);
667		}
668		gb->sramDirty |= GB_SRAM_DIRT_NEW;
669		return;
670	case GB_REGION_WORKING_RAM_BANK0:
671	case GB_REGION_WORKING_RAM_BANK0 + 2:
672		oldValue = memory->wram[address & (GB_SIZE_WORKING_RAM_BANK0 - 1)];
673		memory->wram[address & (GB_SIZE_WORKING_RAM_BANK0 - 1)] = value;
674		break;
675	case GB_REGION_WORKING_RAM_BANK1:
676		if (segment < 0) {
677			oldValue = memory->wramBank[address & (GB_SIZE_WORKING_RAM_BANK0 - 1)];
678			memory->wramBank[address & (GB_SIZE_WORKING_RAM_BANK0 - 1)] = value;
679		} else if (segment < 8) {
680			oldValue = memory->wram[(address & (GB_SIZE_WORKING_RAM_BANK0 - 1)) + segment * GB_SIZE_WORKING_RAM_BANK0];
681			memory->wram[(address & (GB_SIZE_WORKING_RAM_BANK0 - 1)) + segment * GB_SIZE_WORKING_RAM_BANK0] = value;
682		} else {
683			return;
684		}
685		break;
686	default:
687		if (address < GB_BASE_OAM) {
688			oldValue = memory->wramBank[address & (GB_SIZE_WORKING_RAM_BANK0 - 1)];
689			memory->wramBank[address & (GB_SIZE_WORKING_RAM_BANK0 - 1)] = value;
690		} else if (address < GB_BASE_UNUSABLE) {
691			oldValue = gb->video.oam.raw[address & 0xFF];
692			gb->video.oam.raw[address & 0xFF] = value;
693			gb->video.renderer->writeOAM(gb->video.renderer, address & 0xFF);
694		} else if (address < GB_BASE_HRAM) {
695			mLOG(GB_MEM, STUB, "Unimplemented memory Patch8: 0x%08X", address);
696			return;
697		} else if (address < GB_BASE_IE) {
698			oldValue = memory->hram[address & GB_SIZE_HRAM];
699			memory->hram[address & GB_SIZE_HRAM] = value;
700		} else {
701			mLOG(GB_MEM, STUB, "Unimplemented memory Patch8: 0x%08X", address);
702			return;
703		}
704	}
705	if (old) {
706		*old = oldValue;
707	}
708}
709
710void GBMemorySerialize(const struct GB* gb, struct GBSerializedState* state) {
711	const struct GBMemory* memory = &gb->memory;
712	memcpy(state->wram, memory->wram, GB_SIZE_WORKING_RAM);
713	memcpy(state->hram, memory->hram, GB_SIZE_HRAM);
714	STORE_16LE(memory->currentBank, 0, &state->memory.currentBank);
715	state->memory.wramCurrentBank = memory->wramCurrentBank;
716	state->memory.sramCurrentBank = memory->sramCurrentBank;
717
718	STORE_16LE(memory->dmaSource, 0, &state->memory.dmaSource);
719	STORE_16LE(memory->dmaDest, 0, &state->memory.dmaDest);
720
721	STORE_16LE(memory->hdmaSource, 0, &state->memory.hdmaSource);
722	STORE_16LE(memory->hdmaDest, 0, &state->memory.hdmaDest);
723
724	STORE_16LE(memory->hdmaRemaining, 0, &state->memory.hdmaRemaining);
725	state->memory.dmaRemaining = memory->dmaRemaining;
726	memcpy(state->memory.rtcRegs, memory->rtcRegs, sizeof(state->memory.rtcRegs));
727
728	STORE_32LE(memory->dmaEvent.when - mTimingCurrentTime(&gb->timing), 0, &state->memory.dmaNext);
729	STORE_32LE(memory->hdmaEvent.when - mTimingCurrentTime(&gb->timing), 0, &state->memory.hdmaNext);
730
731	GBSerializedMemoryFlags flags = 0;
732	flags = GBSerializedMemoryFlagsSetSramAccess(flags, memory->sramAccess);
733	flags = GBSerializedMemoryFlagsSetRtcAccess(flags, memory->rtcAccess);
734	flags = GBSerializedMemoryFlagsSetRtcLatched(flags, memory->rtcLatched);
735	flags = GBSerializedMemoryFlagsSetIme(flags, memory->ime);
736	flags = GBSerializedMemoryFlagsSetIsHdma(flags, memory->isHdma);
737	flags = GBSerializedMemoryFlagsSetActiveRtcReg(flags, memory->activeRtcReg);
738	STORE_16LE(flags, 0, &state->memory.flags);
739
740	switch (memory->mbcType) {
741	case GB_MBC1:
742		state->memory.mbc1.mode = memory->mbcState.mbc1.mode;
743		state->memory.mbc1.multicartStride = memory->mbcState.mbc1.multicartStride;
744		state->memory.mbc1.bankLo = memory->mbcState.mbc1.bankLo;
745		state->memory.mbc1.bankHi = memory->mbcState.mbc1.bankHi;
746		break;
747	case GB_MBC3_RTC:
748		STORE_64LE(gb->memory.rtcLastLatch, 0, &state->memory.rtc.lastLatch);
749		break;
750	case GB_MBC7:
751		state->memory.mbc7.state = memory->mbcState.mbc7.state;
752		state->memory.mbc7.eeprom = memory->mbcState.mbc7.eeprom;
753		state->memory.mbc7.address = memory->mbcState.mbc7.address;
754		state->memory.mbc7.access = memory->mbcState.mbc7.access;
755		state->memory.mbc7.latch = memory->mbcState.mbc7.latch;
756		state->memory.mbc7.srBits = memory->mbcState.mbc7.srBits;
757		STORE_16LE(memory->mbcState.mbc7.sr, 0, &state->memory.mbc7.sr);
758		STORE_32LE(memory->mbcState.mbc7.writable, 0, &state->memory.mbc7.writable);
759		break;
760	case GB_MMM01:
761		state->memory.mmm01.locked = memory->mbcState.mmm01.locked;
762		state->memory.mmm01.bank0 = memory->mbcState.mmm01.currentBank0;
763		break;
764	case GB_UNL_BBD:
765	case GB_UNL_HITEK:
766		state->memory.bbd.dataSwapMode = memory->mbcState.bbd.dataSwapMode;
767		state->memory.bbd.bankSwapMode = memory->mbcState.bbd.bankSwapMode;
768		break;
769	default:
770		break;
771	}
772}
773
774void GBMemoryDeserialize(struct GB* gb, const struct GBSerializedState* state) {
775	struct GBMemory* memory = &gb->memory;
776	memcpy(memory->wram, state->wram, GB_SIZE_WORKING_RAM);
777	memcpy(memory->hram, state->hram, GB_SIZE_HRAM);
778	LOAD_16LE(memory->currentBank, 0, &state->memory.currentBank);
779	memory->wramCurrentBank = state->memory.wramCurrentBank;
780	memory->sramCurrentBank = state->memory.sramCurrentBank;
781
782	GBMBCSwitchBank(gb, memory->currentBank);
783	GBMemorySwitchWramBank(memory, memory->wramCurrentBank);
784	GBMBCSwitchSramBank(gb, memory->sramCurrentBank);
785
786	LOAD_16LE(memory->dmaSource, 0, &state->memory.dmaSource);
787	LOAD_16LE(memory->dmaDest, 0, &state->memory.dmaDest);
788
789	LOAD_16LE(memory->hdmaSource, 0, &state->memory.hdmaSource);
790	LOAD_16LE(memory->hdmaDest, 0, &state->memory.hdmaDest);
791
792	LOAD_16LE(memory->hdmaRemaining, 0, &state->memory.hdmaRemaining);
793	memory->dmaRemaining = state->memory.dmaRemaining;
794	memcpy(memory->rtcRegs, state->memory.rtcRegs, sizeof(state->memory.rtcRegs));
795
796	uint32_t when;
797	LOAD_32LE(when, 0, &state->memory.dmaNext);
798	if (memory->dmaRemaining) {
799		mTimingSchedule(&gb->timing, &memory->dmaEvent, when);
800	} else {
801		memory->dmaEvent.when = when + mTimingCurrentTime(&gb->timing);
802	}
803	LOAD_32LE(when, 0, &state->memory.hdmaNext);
804	if (memory->hdmaRemaining) {
805		mTimingSchedule(&gb->timing, &memory->hdmaEvent, when);
806	} else {
807		memory->hdmaEvent.when = when + mTimingCurrentTime(&gb->timing);
808	}
809
810	GBSerializedMemoryFlags flags;
811	LOAD_16LE(flags, 0, &state->memory.flags);
812	memory->sramAccess = GBSerializedMemoryFlagsGetSramAccess(flags);
813	memory->rtcAccess = GBSerializedMemoryFlagsGetRtcAccess(flags);
814	memory->rtcLatched = GBSerializedMemoryFlagsGetRtcLatched(flags);
815	memory->ime = GBSerializedMemoryFlagsGetIme(flags);
816	memory->isHdma = GBSerializedMemoryFlagsGetIsHdma(flags);
817	memory->activeRtcReg = GBSerializedMemoryFlagsGetActiveRtcReg(flags);
818
819	switch (memory->mbcType) {
820	case GB_MBC1:
821		memory->mbcState.mbc1.mode = state->memory.mbc1.mode;
822		memory->mbcState.mbc1.multicartStride = state->memory.mbc1.multicartStride;
823		memory->mbcState.mbc1.bankLo = state->memory.mbc1.bankLo;
824		memory->mbcState.mbc1.bankHi = state->memory.mbc1.bankHi;
825		if (!(memory->mbcState.mbc1.bankLo || memory->mbcState.mbc1.bankHi)) {
826			// Backwards compat
827			memory->mbcState.mbc1.bankLo = memory->currentBank & ((1 << memory->mbcState.mbc1.multicartStride) - 1);
828			memory->mbcState.mbc1.bankHi = memory->currentBank >> memory->mbcState.mbc1.multicartStride;
829		}
830		if (memory->mbcState.mbc1.mode) {
831			GBMBCSwitchBank0(gb, memory->mbcState.mbc1.bankHi);
832		}
833		break;
834	case GB_MBC3_RTC:
835		LOAD_64LE(gb->memory.rtcLastLatch, 0, &state->memory.rtc.lastLatch);
836		break;
837	case GB_MBC7:
838		memory->mbcState.mbc7.state = state->memory.mbc7.state;
839		memory->mbcState.mbc7.eeprom = state->memory.mbc7.eeprom;
840		memory->mbcState.mbc7.address = state->memory.mbc7.address & 0x7F;
841		memory->mbcState.mbc7.access = state->memory.mbc7.access;
842		memory->mbcState.mbc7.latch = state->memory.mbc7.latch;
843		memory->mbcState.mbc7.srBits = state->memory.mbc7.srBits;
844		LOAD_16LE(memory->mbcState.mbc7.sr, 0, &state->memory.mbc7.sr);
845		LOAD_32LE(memory->mbcState.mbc7.writable, 0, &state->memory.mbc7.writable);
846		break;
847	case GB_MMM01:
848		memory->mbcState.mmm01.locked = state->memory.mmm01.locked;
849		memory->mbcState.mmm01.currentBank0 = state->memory.mmm01.bank0;
850		if (memory->mbcState.mmm01.locked) {
851			GBMBCSwitchBank0(gb, memory->mbcState.mmm01.currentBank0);
852		} else {
853			GBMBCSwitchBank0(gb, gb->memory.romSize / GB_SIZE_CART_BANK0 - 2);
854		}
855		break;
856	case GB_UNL_BBD:
857	case GB_UNL_HITEK:
858		memory->mbcState.bbd.dataSwapMode = state->memory.bbd.dataSwapMode & 0x7;
859		memory->mbcState.bbd.bankSwapMode = state->memory.bbd.bankSwapMode & 0x7;
860		break;
861	default:
862		break;
863	}
864}
865
866void _pristineCow(struct GB* gb) {
867	if (!gb->isPristine) {
868		return;
869	}
870	void* newRom = anonymousMemoryMap(GB_SIZE_CART_MAX);
871	memcpy(newRom, gb->memory.rom, gb->memory.romSize);
872	memset(((uint8_t*) newRom) + gb->memory.romSize, 0xFF, GB_SIZE_CART_MAX - gb->memory.romSize);
873	if (gb->memory.rom == gb->memory.romBase) {
874		gb->memory.romBase = newRom;
875	}
876	gb->memory.rom = newRom;
877	GBMBCSwitchBank(gb, gb->memory.currentBank);
878	gb->isPristine = false;
879}