all repos — mgba @ 2b70e1714a1354d50013a532ba4e494815905c6e

mGBA Game Boy Advance Emulator

src/ds/ds.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/ds/ds.h>
  7
  8#include <mgba/core/interface.h>
  9#include <mgba/internal/arm/decoder.h>
 10#include <mgba/internal/arm/debugger/debugger.h>
 11#include <mgba/internal/arm/isa-inlines.h>
 12#include <mgba/internal/ds/bios.h>
 13
 14#include <mgba-util/crc32.h>
 15#include <mgba-util/memory.h>
 16#include <mgba-util/math.h>
 17#include <mgba-util/vfs.h>
 18
 19#define SLICE_CYCLES 2048
 20
 21mLOG_DEFINE_CATEGORY(DS, "DS", "ds");
 22
 23const uint32_t DS_ARM946ES_FREQUENCY = 0x1FF61FE;
 24const uint32_t DS_ARM7TDMI_FREQUENCY = 0xFFB0FF;
 25const uint32_t DS_COMPONENT_MAGIC = 0x1FF61FE;
 26const uint8_t DS_CHIP_ID[4] = { 0xC2, 0x0F, 0x00, 0x00 };
 27
 28static const size_t DS_ROM_MAGIC_OFFSET = 0x15C;
 29static const uint8_t DS_ROM_MAGIC[] = { 0x56, 0xCF };
 30static const uint8_t DS_ROM_MAGIC_2[] = { 0x1A, 0x9E };
 31
 32static const size_t DS_FIRMWARE_MAGIC_OFFSET = 0x8;
 33static const uint8_t DS_FIRMWARE_MAGIC[] = { 0x4D, 0x41, 0x43 };
 34
 35enum {
 36	DS7_SP_BASE = 0x380FD80,
 37	DS7_SP_BASE_IRQ = 0x380FF80,
 38	DS7_SP_BASE_SVC = 0x380FFC0,
 39
 40	DS9_SP_BASE = 0x3002F7C,
 41	DS9_SP_BASE_IRQ = 0x3003F80,
 42	DS9_SP_BASE_SVC = 0x3003FC0,
 43};
 44
 45static void DSInit(void* cpu, struct mCPUComponent* component);
 46
 47static void DS7Reset(struct ARMCore* cpu);
 48static void DS7TestIRQ(struct ARMCore* cpu);
 49static void DS7InterruptHandlerInit(struct ARMInterruptHandler* irqh);
 50static void DS7ProcessEvents(struct ARMCore* cpu);
 51
 52static void DS9Reset(struct ARMCore* cpu);
 53static void DS9TestIRQ(struct ARMCore* cpu);
 54static void DS9WriteCP15(struct ARMCore* cpu, int crn, int crm, int opcode1, int opcode2, uint32_t value);
 55static uint32_t DS9ReadCP15(struct ARMCore* cpu, int crn, int crm, int opcode1, int opcode2);
 56static void DS9InterruptHandlerInit(struct ARMInterruptHandler* irqh);
 57static void DS9ProcessEvents(struct ARMCore* cpu);
 58
 59static void DSProcessEvents(struct DSCommon* dscore);
 60static void DSHitStub(struct ARMCore* cpu, uint32_t opcode);
 61static void DSIllegal(struct ARMCore* cpu, uint32_t opcode);
 62static void DSBreakpoint(struct ARMCore* cpu, int immediate);
 63
 64static void _slice(struct mTiming* timing, void* context, uint32_t cyclesLate) {
 65	UNUSED(cyclesLate);
 66	struct DS* ds = context;
 67	uint32_t cycles = mTimingCurrentTime(timing) - ds->sliceStart;
 68	if (ds->activeCpu == ds->ds9.cpu) {
 69		ds->activeCpu = ds->ds7.cpu;
 70		ds->cycleDrift += cycles;
 71		cycles = ds->cycleDrift >> 1;
 72		timing = &ds->ds7.timing;
 73	} else {
 74		ds->activeCpu = ds->ds9.cpu;
 75		ds->cycleDrift -= cycles << 1;
 76		cycles = ds->cycleDrift + SLICE_CYCLES;
 77		timing = &ds->ds9.timing;
 78	}
 79	mTimingSchedule(timing, &ds->slice, cycles);
 80	ds->sliceStart = mTimingCurrentTime(timing);
 81	ds->earlyExit = true;
 82}
 83
 84static void _divide(struct mTiming* timing, void* context, uint32_t cyclesLate) {
 85	UNUSED(timing);
 86	UNUSED(cyclesLate);
 87	struct DS* ds = context;
 88	ds->memory.io9[DS9_REG_DIVCNT >> 1] &= ~0x8000;
 89	int64_t numerator;
 90	int64_t denominator;
 91	LOAD_64LE(numerator, DS9_REG_DIV_NUMER_0, ds->memory.io9);
 92	LOAD_64LE(denominator, DS9_REG_DIV_DENOM_0, ds->memory.io9);
 93	bool max = false;
 94	switch (ds->memory.io9[DS9_REG_DIVCNT >> 1] & 0x3) {
 95	case 0:
 96		numerator = (int64_t)(int32_t) numerator;
 97	case 1:
 98	case 3:
 99		denominator = (int64_t)(int32_t) denominator;
100		break;
101	}
102	if (numerator == INT64_MIN) {
103		max = true;
104	}
105	if (!denominator) {
106		ds->memory.io9[DS9_REG_DIVCNT >> 1] |= 0x4000;
107		STORE_64LE(numerator, DS9_REG_DIVREM_RESULT_0, ds->memory.io9);
108		numerator >>= 63LL;
109		numerator = -numerator;
110		STORE_64LE(numerator, DS9_REG_DIV_RESULT_0, ds->memory.io9);
111		return;
112	}
113	if (denominator == -1LL && max) {
114		ds->memory.io9[DS9_REG_DIVCNT >> 1] |= 0x4000;
115		STORE_64LE(numerator, DS9_REG_DIV_RESULT_0, ds->memory.io9);
116		return;
117	}
118	ds->memory.io9[DS9_REG_DIVCNT >> 1] &= ~0x4000;
119	int64_t result = numerator / denominator;
120	int64_t remainder = numerator % denominator; // TODO: defined behavior for negative denominator?
121	STORE_64LE(result, DS9_REG_DIV_RESULT_0, ds->memory.io9);
122	STORE_64LE(remainder, DS9_REG_DIVREM_RESULT_0, ds->memory.io9);
123}
124
125static void _sqrt(struct mTiming* timing, void* context, uint32_t cyclesLate) {
126	UNUSED(timing);
127	UNUSED(cyclesLate);
128	struct DS* ds = context;
129	ds->memory.io9[DS9_REG_SQRTCNT >> 1] &= ~0x8000;
130	uint64_t param;
131	LOAD_64LE(param, DS9_REG_SQRT_PARAM_0, ds->memory.io9);
132	if (!(ds->memory.io9[DS9_REG_SQRTCNT >> 1] & 1)) {
133		param &= 0xFFFFFFFFULL;
134	}
135
136	uint64_t result = 0;
137	uint64_t bit = 0x4000000000000000ULL; // The second-to-top bit is set: 1 << 30 for 32 bits
138
139	// "bit" starts at the highest power of four <= the argument.
140	while (bit > param) {
141		bit >>= 2;
142	}
143
144	while (bit != 0) {
145		if (param >= result + bit) {
146			param -= result + bit;
147			result = (result >> 1) + bit;
148		} else {
149			result >>= 1;
150		}
151		bit >>= 2;
152	}
153	STORE_32LE(result, DS9_REG_SQRT_RESULT_LO, ds->memory.io9);
154}
155
156void DSCreate(struct DS* ds) {
157	ds->d.id = DS_COMPONENT_MAGIC;
158	ds->d.init = DSInit;
159	ds->d.deinit = NULL;
160	ds->ds7.p = ds;
161	ds->ds9.p = ds;
162	ds->ds7.cpu = NULL;
163	ds->ds9.cpu = NULL;
164	ds->ds7.ipc = &ds->ds9;
165	ds->ds9.ipc = &ds->ds7;
166}
167
168static void DSInit(void* cpu, struct mCPUComponent* component) {
169	struct DS* ds = (struct DS*) component;
170	struct ARMCore* core = cpu;
171	if (!ds->ds7.cpu) {
172		// The ARM7 must get initialized first
173		ds->ds7.cpu = core;
174		ds->debugger = 0;
175		ds->sync = 0;
176		return;
177	}
178	ds->ds9.cpu = cpu;
179	ds->activeCpu = NULL;
180
181	ds->ds9.cpu->cp15.r1.c0 = ARMControlRegFillVE(0);
182
183	ds->slice.name = "DS CPU Time Slicing";
184	ds->slice.callback = _slice;
185	ds->slice.context = ds;
186	ds->slice.priority = UINT_MAX;
187
188	CircleBufferInit(&ds->ds7.fifo, 64);
189	CircleBufferInit(&ds->ds9.fifo, 64);
190
191	DS7InterruptHandlerInit(&ds->ds7.cpu->irqh);
192	DS9InterruptHandlerInit(&ds->ds9.cpu->irqh);
193	DSMemoryInit(ds);
194	DSDMAInit(ds);
195
196	DSVideoInit(&ds->video);
197	ds->video.p = ds;
198
199	DSGXInit(&ds->gx);
200	ds->gx.p = ds;
201
202	DSAudioInit(&ds->audio, 2048);
203	ds->audio.p = ds;
204
205	ds->ds7.springIRQ = 0;
206	ds->ds9.springIRQ = 0;
207	DSTimerInit(ds);
208	ds->keySource = NULL;
209	ds->rtcSource = NULL;
210	ds->rumble = NULL;
211
212	ds->romVf = NULL;
213	DSSlot1SPIInit(ds, NULL);
214
215	ds->stream = NULL;
216	ds->keyCallback = NULL;
217	mCoreCallbacksListInit(&ds->coreCallbacks, 0);
218
219	ds->divEvent.name = "DS Hardware Divide";
220	ds->divEvent.callback = _divide;
221	ds->divEvent.context = ds;
222	ds->divEvent.priority = 0x50;
223
224	ds->sqrtEvent.name = "DS Hardware Sqrt";
225	ds->sqrtEvent.callback = _sqrt;
226	ds->sqrtEvent.context = ds;
227	ds->sqrtEvent.priority = 0x51;
228
229	mTimingInit(&ds->ds7.timing, &ds->ds7.cpu->cycles, &ds->ds7.cpu->nextEvent);
230	mTimingInit(&ds->ds9.timing, &ds->ds9.cpu->cycles, &ds->ds9.cpu->nextEvent);
231}
232
233void DSUnloadROM(struct DS* ds) {
234	if (ds->romVf) {
235		ds->romVf->close(ds->romVf);
236		ds->romVf = NULL;
237	}
238}
239
240void DSDestroy(struct DS* ds) {
241	CircleBufferDeinit(&ds->ds7.fifo);
242	CircleBufferDeinit(&ds->ds9.fifo);
243	DSUnloadROM(ds);
244	DSMemoryDeinit(ds);
245	DSGXDeinit(&ds->gx);
246	DSAudioDeinit(&ds->audio);
247	mTimingDeinit(&ds->ds7.timing);
248	mTimingDeinit(&ds->ds9.timing);
249	mCoreCallbacksListDeinit(&ds->coreCallbacks);
250}
251
252void DS7InterruptHandlerInit(struct ARMInterruptHandler* irqh) {
253	irqh->reset = DS7Reset;
254	irqh->processEvents = DS7ProcessEvents;
255	irqh->swi16 = DS7Swi16;
256	irqh->swi32 = DS7Swi32;
257	irqh->hitIllegal = DSIllegal;
258	irqh->readCPSR = DS7TestIRQ;
259	irqh->writeCP15 = NULL;
260	irqh->readCP15 = NULL;
261	irqh->hitStub = DSHitStub;
262	irqh->bkpt16 = DSBreakpoint;
263	irqh->bkpt32 = DSBreakpoint;
264}
265
266void DS9InterruptHandlerInit(struct ARMInterruptHandler* irqh) {
267	irqh->reset = DS9Reset;
268	irqh->processEvents = DS9ProcessEvents;
269	irqh->swi16 = DS9Swi16;
270	irqh->swi32 = DS9Swi32;
271	irqh->hitIllegal = DSIllegal;
272	irqh->readCPSR = DS9TestIRQ;
273	irqh->writeCP15 = DS9WriteCP15;
274	irqh->readCP15 = DS9ReadCP15;
275	irqh->hitStub = DSHitStub;
276	irqh->bkpt16 = DSBreakpoint;
277	irqh->bkpt32 = DSBreakpoint;
278}
279
280void DS7Reset(struct ARMCore* cpu) {
281	ARMSetPrivilegeMode(cpu, MODE_IRQ);
282	cpu->gprs[ARM_SP] = DS7_SP_BASE_IRQ;
283	ARMSetPrivilegeMode(cpu, MODE_SUPERVISOR);
284	cpu->gprs[ARM_SP] = DS7_SP_BASE_SVC;
285	ARMSetPrivilegeMode(cpu, MODE_SYSTEM);
286	cpu->gprs[ARM_SP] = DS7_SP_BASE;
287
288	struct DS* ds = (struct DS*) cpu->master;
289	mTimingClear(&ds->ds7.timing);
290	CircleBufferInit(&ds->ds7.fifo, 64);
291	DSMemoryReset(ds);
292	DSDMAReset(&ds->ds7);
293	DSAudioReset(&ds->audio);
294	DS7IOInit(ds);
295
296	DSConfigureWRAM(&ds->memory, 3);
297
298	struct DSCartridge* header = ds->romVf->map(ds->romVf, sizeof(*header), MAP_READ);
299	if (header) {
300		memcpy(&ds->memory.ram[0x3FF800 >> 2], DS_CHIP_ID, 4);
301		memcpy(&ds->memory.ram[0x3FF804 >> 2], DS_CHIP_ID, 4);
302		memcpy(&ds->memory.ram[0x3FFC00 >> 2], DS_CHIP_ID, 4);
303		memcpy(&ds->memory.ram[0x3FFC04 >> 2], DS_CHIP_ID, 4);
304		memcpy(&ds->memory.ram[0x3FFE00 >> 2], header, 0x170);
305		DS7IOWrite32(ds, DS_REG_ROMCNT_LO, header->busTiming | 0x2700000);
306		// TODO: Error check
307		ds->romVf->seek(ds->romVf, header->arm7Offset, SEEK_SET);
308		uint32_t base = header->arm7Base;
309		if (base >> DS_BASE_OFFSET == DS_REGION_RAM) {
310			base -= DS_BASE_RAM;
311			uint32_t* basePointer = &ds->memory.ram[base >> 2];
312			if (base < DS_SIZE_RAM && base + header->arm7Size <= DS_SIZE_RAM) {
313				ds->romVf->read(ds->romVf, basePointer, header->arm7Size);
314			}
315		} else {
316			uint32_t size;
317			for (size = header->arm7Size; size; --size) {
318				uint8_t b = 0;
319				ds->romVf->read(ds->romVf, &b, 1);
320				cpu->memory.store8(cpu, base, b, NULL);
321				++base;
322			}
323		}
324		cpu->gprs[12] = header->arm7Entry;
325		cpu->gprs[ARM_LR] = header->arm7Entry;
326		cpu->gprs[ARM_PC] = header->arm7Entry;
327		int currentCycles = 0;
328		ARM_WRITE_PC;
329
330		ds->romVf->unmap(ds->romVf, header, sizeof(*header));
331	}
332}
333
334void DS9Reset(struct ARMCore* cpu) {
335	ARMSetPrivilegeMode(cpu, MODE_IRQ);
336	cpu->gprs[ARM_SP] = DS9_SP_BASE_IRQ;
337	ARMSetPrivilegeMode(cpu, MODE_SUPERVISOR);
338	cpu->gprs[ARM_SP] = DS9_SP_BASE_SVC;
339	ARMSetPrivilegeMode(cpu, MODE_SYSTEM);
340	cpu->gprs[ARM_SP] = DS9_SP_BASE;
341
342	struct DS* ds = (struct DS*) cpu->master;
343	mTimingClear(&ds->ds9.timing);
344	CircleBufferInit(&ds->ds9.fifo, 64);
345	DSVideoReset(&ds->video);
346	DSGXReset(&ds->gx);
347	DSDMAReset(&ds->ds9);
348	DS9IOInit(ds);
349
350	ds->activeCpu = cpu;
351	mTimingSchedule(&ds->ds9.timing, &ds->slice, SLICE_CYCLES);
352	ds->cycleDrift = 0;
353	ds->sliceStart = mTimingCurrentTime(&ds->ds9.timing);
354
355	struct DSCartridge* header = ds->romVf->map(ds->romVf, sizeof(*header), MAP_READ);
356	if (header) {
357		// TODO: Error check
358		ds->romVf->seek(ds->romVf, header->arm9Offset, SEEK_SET);
359		uint32_t base = header->arm9Base - DS_BASE_RAM;
360		uint32_t* basePointer = &ds->memory.ram[base >> 2];
361		if (base < DS_SIZE_RAM && base + header->arm9Size <= DS_SIZE_RAM) {
362			ds->romVf->read(ds->romVf, basePointer, header->arm9Size);
363		}
364		cpu->gprs[12] = header->arm9Entry;
365		cpu->gprs[ARM_LR] = header->arm9Entry;
366		cpu->gprs[ARM_PC] = header->arm9Entry;
367		int currentCycles = 0;
368		ARM_WRITE_PC;
369
370		ds->romVf->unmap(ds->romVf, header, sizeof(*header));
371	}
372}
373
374static void DS7ProcessEvents(struct ARMCore* cpu) {
375	struct DS* ds = (struct DS*) cpu->master;
376	DSProcessEvents(&ds->ds7);
377}
378
379static void DS9ProcessEvents(struct ARMCore* cpu) {
380	struct DS* ds = (struct DS*) cpu->master;
381	DSProcessEvents(&ds->ds9);
382}
383
384static void DSProcessEvents(struct DSCommon* dscore) {
385	struct ARMCore* cpu = dscore->cpu;
386	struct DS* ds = dscore->p;
387	if (dscore->springIRQ && !cpu->cpsr.i) {
388		ARMRaiseIRQ(cpu);
389		dscore->springIRQ = 0;
390	}
391
392	int32_t nextEvent = cpu->nextEvent;
393	while (cpu->cycles >= nextEvent) {
394		int32_t cycles = cpu->cycles;
395
396		cpu->cycles = 0;
397		cpu->nextEvent = 0;
398
399#ifndef NDEBUG
400		if (cycles < 0) {
401			mLOG(DS, FATAL, "Negative cycles passed: %i", cycles);
402		}
403#endif
404		nextEvent = cycles;
405		do {
406			nextEvent = mTimingTick(&dscore->timing, nextEvent);
407		} while (ds->cpuBlocked && !ds->earlyExit);
408
409		if (ds->earlyExit) {
410			ds->earlyExit = false;
411			break;
412		}
413
414		cpu->nextEvent = nextEvent;
415		if (cpu->halted) {
416			cpu->cycles = nextEvent;
417		}
418#ifndef NDEBUG
419		else if (nextEvent < 0) {
420			mLOG(DS, FATAL, "Negative cycles will pass: %i", nextEvent);
421		}
422#endif
423	}
424}
425
426void DSRunLoop(struct DS* ds) {
427	if (ds->activeCpu == ds->ds9.cpu) {
428		ARMv5RunLoop(ds->ds9.cpu);
429	} else {
430		ARMv4RunLoop(ds->ds7.cpu);
431	}
432}
433
434void DS7Step(struct DS* ds) {
435	int32_t pc = ds->ds7.cpu->gprs[ARM_PC];
436	do {
437		while (ds->activeCpu == ds->ds9.cpu) {
438			ARMv5RunLoop(ds->ds9.cpu);
439		}
440		ARMv4Run(ds->ds7.cpu);
441	} while (ds->ds7.cpu->halted || ds->ds7.cpu->gprs[ARM_PC] == pc);
442}
443
444void DS9Step(struct DS* ds) {
445	int32_t pc = ds->ds9.cpu->gprs[ARM_PC];
446	do {
447		while (ds->activeCpu == ds->ds7.cpu) {
448			ARMv4RunLoop(ds->ds7.cpu);
449		}
450		ARMv5Run(ds->ds9.cpu);
451	} while (ds->ds9.cpu->halted || ds->ds9.cpu->gprs[ARM_PC] == pc);
452}
453
454void DSAttachDebugger(struct DS* ds, struct mDebugger* debugger) {
455	ds->debugger = (struct ARMDebugger*) debugger->platform;
456	ds->ds7.cpu->components[CPU_COMPONENT_DEBUGGER] = &debugger->d;
457	ds->ds9.cpu->components[CPU_COMPONENT_DEBUGGER] = &debugger->d;
458	ARMHotplugAttach(ds->ds7.cpu, CPU_COMPONENT_DEBUGGER);
459	ARMHotplugAttach(ds->ds9.cpu, CPU_COMPONENT_DEBUGGER);
460}
461
462void DSDetachDebugger(struct DS* ds) {
463	ds->debugger = NULL;
464	ARMHotplugDetach(ds->ds7.cpu, CPU_COMPONENT_DEBUGGER);
465	ARMHotplugDetach(ds->ds9.cpu, CPU_COMPONENT_DEBUGGER);
466	ds->ds7.cpu->components[CPU_COMPONENT_DEBUGGER] = NULL;
467	ds->ds9.cpu->components[CPU_COMPONENT_DEBUGGER] = NULL;
468}
469
470bool DSLoadROM(struct DS* ds, struct VFile* vf) {
471	DSUnloadROM(ds);
472	ds->romVf = vf;
473	// TODO: error check
474	return true;
475}
476
477bool DSLoadSave(struct DS* ds, struct VFile* sav) {
478	DSSlot1SPIInit(ds, sav);
479	return true;
480}
481
482bool DSIsROM(struct VFile* vf) {
483	if (vf->seek(vf, DS_ROM_MAGIC_OFFSET, SEEK_SET) < 0) {
484		return false;
485	}
486	uint8_t signature[sizeof(DS_ROM_MAGIC)];
487	if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
488		return false;
489	}
490	return memcmp(signature, DS_ROM_MAGIC, sizeof(signature)) == 0 || memcmp(signature, DS_ROM_MAGIC_2, sizeof(signature)) == 0;
491}
492
493bool DSIsBIOS7(struct VFile* vf) {
494	size_t size = vf->size(vf);
495	void* data = NULL;
496	uint32_t crc;
497	if (size == DS7_SIZE_BIOS) {
498		data = vf->map(vf, size, MAP_READ);
499	}
500	if (!data) {
501		return false;
502	}
503	crc = doCrc32(data, size);
504	vf->unmap(vf, data, size);
505	return crc == DS7_BIOS_CHECKSUM;
506}
507
508bool DSIsBIOS9(struct VFile* vf) {
509	size_t size = vf->size(vf);
510	void* data = NULL;
511	uint32_t crc;
512	if (size == DS9_SIZE_BIOS) {
513		data = vf->map(vf, 0x1000, MAP_READ);
514	} else if (size == 0x1000) {
515		data = vf->map(vf, 0x1000, MAP_READ);
516	}
517	if (!data) {
518		return false;
519	}
520	crc = doCrc32(data, 0x1000);
521	vf->unmap(vf, data, 0x1000);
522	return crc == DS9_BIOS_CHECKSUM;
523}
524
525bool DSIsFirmware(struct VFile* vf) {
526	if (vf->seek(vf, DS_FIRMWARE_MAGIC_OFFSET, SEEK_SET) < 0) {
527		return false;
528	}
529	uint8_t signature[sizeof(DS_FIRMWARE_MAGIC)];
530	if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
531		return false;
532	}
533	return memcmp(signature, DS_FIRMWARE_MAGIC, sizeof(signature)) == 0;
534}
535
536bool DSLoadBIOS(struct DS* ds, struct VFile* vf) {
537	size_t size = vf->size(vf);
538	void* data = NULL;
539	uint32_t crc;
540	if (size == DS7_SIZE_BIOS) {
541		data = vf->map(vf, size, MAP_READ);
542	} else if (size == 0x1000) {
543		data = calloc(DS9_SIZE_BIOS, 1);
544		vf->read(vf, data, size);
545	} else if (size == DS9_SIZE_BIOS) {
546		data = vf->map(vf, size, MAP_READ);
547	} else if (size == DS_SIZE_FIRMWARE) {
548		return DSLoadFirmware(ds, vf);
549	}
550	if (!data) {
551		return false;
552	}
553	crc = doCrc32(data, size);
554	if (crc == DS7_BIOS_CHECKSUM) {
555		ds->bios7Vf = vf;
556		ds->memory.bios7 = data;
557		mLOG(DS, INFO, "Official DS ARM7 BIOS detected");
558	} else if (crc == DS9_BIOS_CHECKSUM) {
559		ds->bios9Vf = vf;
560		ds->memory.bios9 = data;
561		mLOG(DS, INFO, "Official DS ARM9 BIOS detected");
562	} else {
563		mLOG(DS, WARN, "BIOS checksum incorrect");
564		vf->unmap(vf, data, size);
565		return false;
566	}
567	return true;
568}
569
570bool DSLoadFirmware(struct DS* ds, struct VFile* vf) {
571	size_t size = vf->size(vf);
572	void* data = NULL;
573	if (!DSIsFirmware(vf)) {
574		return false;
575	}
576	if (size == DS_SIZE_FIRMWARE) {
577		data = vf->map(vf, size, MAP_WRITE);
578	}
579	if (!data) {
580		return false;
581	}
582	mLOG(DS, INFO, "Found DS firmware");
583	ds->firmwareVf = vf;
584	return true;
585}
586
587void DSGetGameCode(struct DS* ds, char* out) {
588	memset(out, 0, 8);
589	if (!ds->romVf) {
590		return;
591	}
592
593	struct DSCartridge* cart = ds->romVf->map(ds->romVf, sizeof(*cart), MAP_READ);
594	// TODO: TWL-?
595	memcpy(out, "NTR-", 4);
596	memcpy(&out[4], &cart->id, 4);
597	ds->romVf->unmap(ds->romVf, cart, sizeof(*cart));
598}
599
600void DSGetGameTitle(struct DS* ds, char* out) {
601	memset(out, 0, 12);
602	if (!ds->romVf) {
603		return;
604	}
605
606	struct DSCartridge* cart = ds->romVf->map(ds->romVf, sizeof(*cart), MAP_READ);
607	memcpy(out, &cart->title, 12);
608	ds->romVf->unmap(ds->romVf, cart, sizeof(*cart));
609}
610
611void DSHitStub(struct ARMCore* cpu, uint32_t opcode) {
612	struct DS* ds = (struct DS*) cpu->master;
613	if (ds->debugger) {
614		struct mDebuggerEntryInfo info = {
615			.address = _ARMPCAddress(cpu),
616			.opcode = opcode
617		};
618		mDebuggerEnter(ds->debugger->d.p, DEBUGGER_ENTER_ILLEGAL_OP, &info);
619	}
620	// TODO: More sensible category?
621	mLOG(DS, ERROR, "Stub opcode: %08x", opcode);
622}
623
624void DSIllegal(struct ARMCore* cpu, uint32_t opcode) {
625	struct DS* ds = (struct DS*) cpu->master;
626	if ((opcode & 0xFFFF) == (redzoneInstruction & 0xFFFF)) {
627		int currentCycles = 0;
628		if (cpu->executionMode == MODE_THUMB) {
629			cpu->gprs[ARM_PC] -= WORD_SIZE_THUMB * 2;
630			THUMB_WRITE_PC;
631		} else {
632			cpu->gprs[ARM_PC] -= WORD_SIZE_ARM * 2;
633			ARM_WRITE_PC;
634		}
635	} else if (ds->debugger) {
636		struct mDebuggerEntryInfo info = {
637			.address = _ARMPCAddress(cpu),
638			.opcode = opcode
639		};
640		mDebuggerEnter(ds->debugger->d.p, DEBUGGER_ENTER_ILLEGAL_OP, &info);
641	} else {
642		ARMRaiseUndefined(cpu);
643	}
644}
645
646void DSBreakpoint(struct ARMCore* cpu, int immediate) {
647	struct DS* ds = (struct DS*) cpu->master;
648	if (immediate >= CPU_COMPONENT_MAX) {
649		return;
650	}
651	switch (immediate) {
652	case CPU_COMPONENT_DEBUGGER:
653		if (ds->debugger) {
654			struct mDebuggerEntryInfo info = {
655				.address = _ARMPCAddress(cpu)
656			};
657			mDebuggerEnter(ds->debugger->d.p, DEBUGGER_ENTER_BREAKPOINT, &info);
658		}
659		break;
660	default:
661		break;
662	}
663}
664
665void DS7TestIRQ(struct ARMCore* cpu) {
666	struct DS* ds = (struct DS*) cpu->master;
667	if (!ds->memory.io7[DS_REG_IME >> 1]) {
668		return;
669	}
670	uint32_t test = (ds->memory.io7[DS_REG_IE_LO >> 1] & ds->memory.io7[DS_REG_IF_LO >> 1]);
671	test |= (ds->memory.io7[DS_REG_IE_HI >> 1] & ds->memory.io7[DS_REG_IF_HI >> 1]) << 16;
672	if (test) {
673		ds->ds7.springIRQ = test;
674		cpu->nextEvent = cpu->cycles;
675	}
676}
677
678void DS9TestIRQ(struct ARMCore* cpu) {
679	struct DS* ds = (struct DS*) cpu->master;
680	if (!ds->memory.io9[DS_REG_IME >> 1]) {
681		return;
682	}
683	uint32_t test = (ds->memory.io9[DS_REG_IE_LO >> 1] & ds->memory.io9[DS_REG_IF_LO >> 1]);
684	test |= (ds->memory.io9[DS_REG_IE_HI >> 1] & ds->memory.io9[DS_REG_IF_HI >> 1]) << 16;
685	if (test) {
686		ds->ds9.springIRQ = test;
687		cpu->nextEvent = cpu->cycles;
688	}
689}
690
691static void _writeSysControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
692	mLOG(DS, STUB, "CP15 system control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
693}
694
695static void _writeCacheControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
696	mLOG(DS, STUB, "CP15 cache control control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
697	switch (opcode2) {
698	case 0:
699		cpu->cp15.r2.d = value;
700		break;
701	case 1:
702		cpu->cp15.r2.i = value;
703		break;
704	default:
705		mLOG(DS, GAME_ERROR, "CP15 cache control control bad op2: %i", opcode2);
706		break;
707	}
708}
709
710static void _writeWriteBufferControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
711	mLOG(DS, STUB, "CP15 write buffer control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
712	switch (opcode2) {
713	case 0:
714		cpu->cp15.r3.d = value;
715		break;
716	default:
717		mLOG(DS, GAME_ERROR, "CP15 cache control control bad op2: %i", opcode2);
718		break;
719	}
720}
721
722static void _writeAccessControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
723	mLOG(DS, STUB, "CP15 access control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
724}
725
726static void _writeRegionConfiguration(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
727	cpu->cp15.r6.region[crm] = value;
728	uint32_t base = ARMProtectionGetBase(value) << 12;
729	uint32_t size = 2 << ARMProtectionGetSize(value);
730	mLOG(DS, STUB, "CP15 region configuration write: Region: %i, Insn: %i, Base: %08X, Size: %08X", crm, opcode2, base, size);
731}
732
733static void _writeCache(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
734	switch (crm) {
735	case 0:
736		if (opcode2 == 4) {
737			ARMHalt(cpu);
738			return;
739		}
740		break;
741	}
742	mLOG(DS, STUB, "CP15 cache write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
743}
744
745static void _writeTCMControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
746	uint32_t base = ARMTCMControlGetBase(value) << 12;
747	uint32_t size = 512 << ARMTCMControlGetVirtualSize(value);
748	struct DS* ds = (struct DS*) cpu->master;
749	mLOG(DS, DEBUG, "CP15 TCM control write: CRm: %i, Op2: %i, Base: %08X, Size: %08X", crm, opcode2, base, size);
750	switch (opcode2) {
751	case 0:
752		cpu->cp15.r9.d = value;
753		ds->memory.dtcmBase = base;
754		ds->memory.dtcmSize = size;
755		break;
756	case 1:
757		cpu->cp15.r9.i = value;
758		ds->memory.itcmSize = size;
759		break;
760	default:
761		mLOG(DS, GAME_ERROR, "CP15 TCM control bad op2: %i", opcode2);
762		break;
763	}
764}
765
766void DS9WriteCP15(struct ARMCore* cpu, int crn, int crm, int opcode1, int opcode2, uint32_t value) {
767	switch (crn) {
768	default:
769		mLOG(DS, STUB, "CP15 unknown write: CRn: %i, CRm: %i, Op1: %i, Op2: %i, Value: 0x%08X", crn, crm, opcode1, opcode2, value);
770		break;
771	case 0:
772		mLOG(DS, GAME_ERROR, "Attempted to write to read-only cp15 register");
773		ARMRaiseUndefined(cpu);
774		break;
775	case 1:
776		_writeSysControl(cpu, crm, opcode2, value);
777		break;
778	case 2:
779		_writeCacheControl(cpu, crm, opcode2, value);
780		break;
781	case 3:
782		_writeWriteBufferControl(cpu, crm, opcode2, value);
783		break;
784	case 5:
785		_writeAccessControl(cpu, crm, opcode2, value);
786		break;
787	case 6:
788		_writeRegionConfiguration(cpu, crm, opcode2, value);
789		break;
790	case 7:
791		_writeCache(cpu, crm, opcode2, value);
792		break;
793	case 9:
794		_writeTCMControl(cpu, crm, opcode2, value);
795		break;
796	}
797}
798
799static uint32_t _readTCMControl(struct ARMCore* cpu, int crm, int opcode2) {
800	switch (opcode2) {
801	case 0:
802		return cpu->cp15.r9.d;
803	case 1:
804		return cpu->cp15.r9.i;
805	default:
806		mLOG(DS, GAME_ERROR, "CP15 TCM control bad op2: %i", opcode2);
807		return 0;
808	}
809}
810
811uint32_t DS9ReadCP15(struct ARMCore* cpu, int crn, int crm, int opcode1, int opcode2) {
812	switch (crn) {
813	default:
814		mLOG(DS, STUB, "CP15 unknown read: CRn: %i, CRm: %i, Op1: %i, Op2: %i", crn, crm, opcode1, opcode2);
815		return 0;
816	case 9:
817		return _readTCMControl(cpu, crm, opcode2);
818	}
819}
820
821void DSWriteIE(struct ARMCore* cpu, uint16_t* io, uint32_t value) {
822	if (io[DS_REG_IME >> 1] && (value & io[DS_REG_IF_LO >> 1] || (value >> 16) & io[DS_REG_IF_HI >> 1])) {
823		ARMRaiseIRQ(cpu);
824	}
825}
826void DSWriteIME(struct ARMCore* cpu, uint16_t* io, uint16_t value) {
827	if (value && (io[DS_REG_IE_LO >> 1] & io[DS_REG_IF_LO >> 1] || io[DS_REG_IE_HI >> 1] & io[DS_REG_IF_HI >> 1])) {
828		ARMRaiseIRQ(cpu);
829	}
830}
831
832void DSRaiseIRQ(struct ARMCore* cpu, uint16_t* io, enum DSIRQ irq) {
833	if (irq < 16) {
834		io[DS_REG_IF_LO >> 1] |= 1 << irq;
835	} else {
836		io[DS_REG_IF_HI >> 1] |= 1 << (irq - 16);
837	}
838
839	if ((irq < 16 && (io[DS_REG_IE_LO >> 1] & 1 << irq)) || (io[DS_REG_IE_HI >> 1] & (1 << (irq - 16)))) {
840		cpu->halted = 0;
841		if (io[DS_REG_IME >> 1]) {
842			ARMRaiseIRQ(cpu);
843		}
844	}
845}
846
847void DSFrameStarted(struct DS* ds) {
848	size_t c;
849	for (c = 0; c < mCoreCallbacksListSize(&ds->coreCallbacks); ++c) {
850		struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&ds->coreCallbacks, c);
851		if (callbacks->videoFrameStarted) {
852			callbacks->videoFrameStarted(callbacks->context);
853		}
854	}
855}
856
857void DSFrameEnded(struct DS* ds) {
858	size_t c;
859	for (c = 0; c < mCoreCallbacksListSize(&ds->coreCallbacks); ++c) {
860		struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&ds->coreCallbacks, c);
861		if (callbacks->videoFrameEnded) {
862			callbacks->videoFrameEnded(callbacks->context);
863		}
864	}
865
866	if (ds->stream && ds->stream->postVideoFrame) {
867		const color_t* pixels;
868		size_t stride;
869		ds->video.renderer->getPixels(ds->video.renderer, &stride, (const void**) &pixels);
870		ds->stream->postVideoFrame(ds->stream, pixels, stride);
871	}
872}
873
874uint16_t DSWriteRTC(struct DS* ds, DSRegisterRTC value) {
875	switch (ds->rtc.transferStep) {
876	case 0:
877		if ((value & 6) == 2) {
878			ds->rtc.transferStep = 1;
879		}
880		break;
881	case 1:
882		if ((value & 6) == 6) {
883			ds->rtc.transferStep = 2;
884		}
885		break;
886	case 2:
887		if (!DSRegisterRTCIsClock(value)) {
888			ds->rtc.bits &= ~(1 << ds->rtc.bitsRead);
889			ds->rtc.bits |= DSRegisterRTCGetData(value) << ds->rtc.bitsRead;
890		} else {
891			if (DSRegisterRTCIsSelect(value)) {
892				// GPIO direction should always != reading
893				if (DSRegisterRTCIsDataDirection(value)) {
894					if (RTCCommandDataIsReading(ds->rtc.command)) {
895						mLOG(DS, GAME_ERROR, "Attempting to write to RTC while in read mode");
896					}
897					++ds->rtc.bitsRead;
898					if (ds->rtc.bitsRead == 8) {
899						GBARTCProcessByte(&ds->rtc, ds->rtcSource);
900					}
901				} else {
902					value = DSRegisterRTCSetData(value, GBARTCOutput(&ds->rtc));
903					++ds->rtc.bitsRead;
904					if (ds->rtc.bitsRead == 8) {
905						--ds->rtc.bytesRemaining;
906						if (ds->rtc.bytesRemaining <= 0) {
907							ds->rtc.commandActive = 0;
908							ds->rtc.command = RTCCommandDataClearReading(ds->rtc.command);
909						}
910						ds->rtc.bitsRead = 0;
911					}
912				}
913			} else {
914				ds->rtc.bitsRead = 0;
915				ds->rtc.bytesRemaining = 0;
916				ds->rtc.commandActive = 0;
917				ds->rtc.command = RTCCommandDataClearReading(ds->rtc.command);
918				ds->rtc.transferStep = 0;
919			}
920		}
921		break;
922	}
923	return value;
924}