all repos — mgba @ 1a0e44c014ad34bea30d237d27015d82d02cda4b

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 = 0x3FEC3FC;
 24const uint32_t DS_ARM7TDMI_FREQUENCY = 0x1FF61FE;
 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	ds->isHomebrew = false;
298
299	struct DSCartridge* header = ds->romVf->map(ds->romVf, sizeof(*header), MAP_READ);
300	if (header) {
301		memcpy(&ds->memory.ram[0x3FF800 >> 2], DS_CHIP_ID, 4);
302		memcpy(&ds->memory.ram[0x3FF804 >> 2], DS_CHIP_ID, 4);
303		memcpy(&ds->memory.ram[0x3FFC00 >> 2], DS_CHIP_ID, 4);
304		memcpy(&ds->memory.ram[0x3FFC04 >> 2], DS_CHIP_ID, 4);
305		ds->memory.ram[0x3FFC40 >> 2] = 1;
306		memcpy(&ds->memory.ram[0x3FFE00 >> 2], header, 0x170);
307		DS7IOWrite32(ds, DS_REG_ROMCNT_LO, header->busTiming | 0x2700000);
308
309		ds->isHomebrew = memcmp(&header->logoCrc16, DS_ROM_MAGIC, sizeof(header->logoCrc16));
310
311		// TODO: Error check
312		ds->romVf->seek(ds->romVf, header->arm7Offset, SEEK_SET);
313		uint32_t base = header->arm7Base;
314		if (base >> DS_BASE_OFFSET == DS_REGION_RAM) {
315			base -= DS_BASE_RAM;
316			uint32_t* basePointer = &ds->memory.ram[base >> 2];
317			if (base < DS_SIZE_RAM && base + header->arm7Size <= DS_SIZE_RAM) {
318				ds->romVf->read(ds->romVf, basePointer, header->arm7Size);
319			}
320		} else {
321			uint32_t size;
322			for (size = header->arm7Size; size; --size) {
323				uint8_t b = 0;
324				ds->romVf->read(ds->romVf, &b, 1);
325				cpu->memory.store8(cpu, base, b, NULL);
326				++base;
327			}
328		}
329		cpu->gprs[12] = header->arm7Entry;
330		cpu->gprs[ARM_LR] = header->arm7Entry;
331		cpu->gprs[ARM_PC] = header->arm7Entry;
332		int currentCycles = 0;
333		ARM_WRITE_PC;
334
335		ds->romVf->unmap(ds->romVf, header, sizeof(*header));
336	}
337}
338
339void DS9Reset(struct ARMCore* cpu) {
340	ARMSetPrivilegeMode(cpu, MODE_IRQ);
341	cpu->gprs[ARM_SP] = DS9_SP_BASE_IRQ;
342	ARMSetPrivilegeMode(cpu, MODE_SUPERVISOR);
343	cpu->gprs[ARM_SP] = DS9_SP_BASE_SVC;
344	ARMSetPrivilegeMode(cpu, MODE_SYSTEM);
345	cpu->gprs[ARM_SP] = DS9_SP_BASE;
346
347	struct DS* ds = (struct DS*) cpu->master;
348	mTimingClear(&ds->ds9.timing);
349	CircleBufferInit(&ds->ds9.fifo, 64);
350	DSVideoReset(&ds->video);
351	DSGXReset(&ds->gx);
352	DSDMAReset(&ds->ds9);
353	DS9IOInit(ds);
354
355	ds->activeCpu = cpu;
356	mTimingSchedule(&ds->ds9.timing, &ds->slice, SLICE_CYCLES);
357	ds->cycleDrift = 0;
358	ds->sliceStart = mTimingCurrentTime(&ds->ds9.timing);
359
360	struct DSCartridge* header = ds->romVf->map(ds->romVf, sizeof(*header), MAP_READ);
361	if (header) {
362		// TODO: Error check
363		ds->romVf->seek(ds->romVf, header->arm9Offset, SEEK_SET);
364		uint32_t base = header->arm9Base - DS_BASE_RAM;
365		uint32_t* basePointer = &ds->memory.ram[base >> 2];
366		if (base < DS_SIZE_RAM && base + header->arm9Size <= DS_SIZE_RAM) {
367			ds->romVf->read(ds->romVf, basePointer, header->arm9Size);
368		}
369		cpu->gprs[12] = header->arm9Entry;
370		cpu->gprs[ARM_LR] = header->arm9Entry;
371		cpu->gprs[ARM_PC] = header->arm9Entry;
372		int currentCycles = 0;
373		ARM_WRITE_PC;
374
375		ds->romVf->unmap(ds->romVf, header, sizeof(*header));
376	}
377}
378
379static void DS7ProcessEvents(struct ARMCore* cpu) {
380	struct DS* ds = (struct DS*) cpu->master;
381	DSProcessEvents(&ds->ds7);
382}
383
384static void DS9ProcessEvents(struct ARMCore* cpu) {
385	struct DS* ds = (struct DS*) cpu->master;
386	DSProcessEvents(&ds->ds9);
387}
388
389static void DSProcessEvents(struct DSCommon* dscore) {
390	struct ARMCore* cpu = dscore->cpu;
391	struct DS* ds = dscore->p;
392	if (dscore->springIRQ && !cpu->cpsr.i) {
393		ARMRaiseIRQ(cpu);
394		dscore->springIRQ = 0;
395	}
396
397	int32_t nextEvent = cpu->nextEvent;
398	while (cpu->cycles >= nextEvent) {
399		int32_t cycles = cpu->cycles;
400
401		cpu->cycles = 0;
402		cpu->nextEvent = 0;
403
404#ifndef NDEBUG
405		if (cycles < 0) {
406			mLOG(DS, FATAL, "Negative cycles passed: %i", cycles);
407		}
408#endif
409		nextEvent = cycles;
410		do {
411			nextEvent = mTimingTick(&dscore->timing, nextEvent);
412		} while (ds->cpuBlocked && !ds->earlyExit);
413
414		if (ds->earlyExit) {
415			ds->earlyExit = false;
416			break;
417		}
418
419		cpu->nextEvent = nextEvent;
420		if (cpu->halted) {
421			cpu->cycles = nextEvent;
422		}
423#ifndef NDEBUG
424		else if (nextEvent < 0) {
425			mLOG(DS, FATAL, "Negative cycles will pass: %i", nextEvent);
426		}
427#endif
428	}
429}
430
431void DSRunLoop(struct DS* ds) {
432	if (ds->activeCpu == ds->ds9.cpu) {
433		ARMv5RunLoop(ds->ds9.cpu);
434	} else {
435		ARMv4RunLoop(ds->ds7.cpu);
436	}
437}
438
439void DS7Step(struct DS* ds) {
440	int32_t pc = ds->ds7.cpu->gprs[ARM_PC];
441	do {
442		while (ds->activeCpu == ds->ds9.cpu) {
443			ARMv5RunLoop(ds->ds9.cpu);
444		}
445		ARMv4Run(ds->ds7.cpu);
446	} while (ds->ds7.cpu->halted || ds->ds7.cpu->gprs[ARM_PC] == pc);
447}
448
449void DS9Step(struct DS* ds) {
450	int32_t pc = ds->ds9.cpu->gprs[ARM_PC];
451	do {
452		while (ds->activeCpu == ds->ds7.cpu) {
453			ARMv4RunLoop(ds->ds7.cpu);
454		}
455		ARMv5Run(ds->ds9.cpu);
456	} while (ds->ds9.cpu->halted || ds->ds9.cpu->gprs[ARM_PC] == pc);
457}
458
459void DSAttachDebugger(struct DS* ds, struct mDebugger* debugger) {
460	ds->debugger = (struct ARMDebugger*) debugger->platform;
461	ds->ds7.cpu->components[CPU_COMPONENT_DEBUGGER] = &debugger->d;
462	ds->ds9.cpu->components[CPU_COMPONENT_DEBUGGER] = &debugger->d;
463	ARMHotplugAttach(ds->ds7.cpu, CPU_COMPONENT_DEBUGGER);
464	ARMHotplugAttach(ds->ds9.cpu, CPU_COMPONENT_DEBUGGER);
465}
466
467void DSDetachDebugger(struct DS* ds) {
468	if (ds->debugger) {
469		ARMHotplugDetach(ds->ds7.cpu, CPU_COMPONENT_DEBUGGER);
470		ARMHotplugDetach(ds->ds9.cpu, CPU_COMPONENT_DEBUGGER);
471	}
472	ds->ds7.cpu->components[CPU_COMPONENT_DEBUGGER] = NULL;
473	ds->ds9.cpu->components[CPU_COMPONENT_DEBUGGER] = NULL;
474	ds->debugger = NULL;
475}
476
477bool DSLoadROM(struct DS* ds, struct VFile* vf) {
478	DSUnloadROM(ds);
479	ds->romVf = vf;
480	// TODO: error check
481	return true;
482}
483
484bool DSLoadSave(struct DS* ds, struct VFile* sav) {
485	DSSlot1SPIInit(ds, sav);
486	return true;
487}
488
489bool DSIsROM(struct VFile* vf) {
490	if (vf->seek(vf, DS_ROM_MAGIC_OFFSET, SEEK_SET) < 0) {
491		return false;
492	}
493	uint8_t signature[sizeof(DS_ROM_MAGIC)];
494	if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
495		return false;
496	}
497	return memcmp(signature, DS_ROM_MAGIC, sizeof(signature)) == 0 || memcmp(signature, DS_ROM_MAGIC_2, sizeof(signature)) == 0;
498}
499
500bool DSIsBIOS7(struct VFile* vf) {
501	size_t size = vf->size(vf);
502	void* data = NULL;
503	uint32_t crc;
504	if (size == DS7_SIZE_BIOS) {
505		data = vf->map(vf, size, MAP_READ);
506	}
507	if (!data) {
508		return false;
509	}
510	crc = doCrc32(data, size);
511	vf->unmap(vf, data, size);
512	return crc == DS7_BIOS_CHECKSUM;
513}
514
515bool DSIsBIOS9(struct VFile* vf) {
516	size_t size = vf->size(vf);
517	void* data = NULL;
518	uint32_t crc;
519	if (size == DS9_SIZE_BIOS) {
520		data = vf->map(vf, 0x1000, MAP_READ);
521	} else if (size == 0x1000) {
522		data = vf->map(vf, 0x1000, MAP_READ);
523	}
524	if (!data) {
525		return false;
526	}
527	crc = doCrc32(data, 0x1000);
528	vf->unmap(vf, data, 0x1000);
529	return crc == DS9_BIOS_CHECKSUM;
530}
531
532bool DSIsFirmware(struct VFile* vf) {
533	if (vf->seek(vf, DS_FIRMWARE_MAGIC_OFFSET, SEEK_SET) < 0) {
534		return false;
535	}
536	uint8_t signature[sizeof(DS_FIRMWARE_MAGIC)];
537	if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
538		return false;
539	}
540	return memcmp(signature, DS_FIRMWARE_MAGIC, sizeof(signature)) == 0;
541}
542
543bool DSLoadBIOS(struct DS* ds, struct VFile* vf) {
544	size_t size = vf->size(vf);
545	void* data = NULL;
546	uint32_t crc;
547	if (size == DS7_SIZE_BIOS) {
548		data = vf->map(vf, size, MAP_READ);
549	} else if (size == 0x1000) {
550		data = calloc(DS9_SIZE_BIOS, 1);
551		vf->read(vf, data, size);
552	} else if (size == DS9_SIZE_BIOS) {
553		data = vf->map(vf, size, MAP_READ);
554	} else if (size == DS_SIZE_FIRMWARE) {
555		return DSLoadFirmware(ds, vf);
556	}
557	if (!data) {
558		return false;
559	}
560	crc = doCrc32(data, size);
561	if (crc == DS7_BIOS_CHECKSUM) {
562		ds->bios7Vf = vf;
563		ds->memory.bios7 = data;
564		mLOG(DS, INFO, "Official DS ARM7 BIOS detected");
565	} else if (crc == DS9_BIOS_CHECKSUM) {
566		ds->bios9Vf = vf;
567		ds->memory.bios9 = data;
568		mLOG(DS, INFO, "Official DS ARM9 BIOS detected");
569	} else {
570		mLOG(DS, WARN, "BIOS checksum incorrect");
571		vf->unmap(vf, data, size);
572		return false;
573	}
574	return true;
575}
576
577bool DSLoadFirmware(struct DS* ds, struct VFile* vf) {
578	size_t size = vf->size(vf);
579	if (!DSIsFirmware(vf)) {
580		return false;
581	}
582	if (size != DS_SIZE_FIRMWARE) {
583		return false;
584	}
585	mLOG(DS, INFO, "Found DS firmware");
586	ds->firmwareVf = vf;
587	return true;
588}
589
590void DSGetGameCode(struct DS* ds, char* out) {
591	memset(out, 0, 8);
592	if (!ds->romVf) {
593		return;
594	}
595
596	struct DSCartridge* cart = ds->romVf->map(ds->romVf, sizeof(*cart), MAP_READ);
597	// TODO: TWL-?
598	memcpy(out, "NTR-", 4);
599	memcpy(&out[4], &cart->id, 4);
600	ds->romVf->unmap(ds->romVf, cart, sizeof(*cart));
601}
602
603void DSGetGameTitle(struct DS* ds, char* out) {
604	memset(out, 0, 12);
605	if (!ds->romVf) {
606		return;
607	}
608
609	struct DSCartridge* cart = ds->romVf->map(ds->romVf, sizeof(*cart), MAP_READ);
610	memcpy(out, &cart->title, 12);
611	ds->romVf->unmap(ds->romVf, cart, sizeof(*cart));
612}
613
614void DSHitStub(struct ARMCore* cpu, uint32_t opcode) {
615	struct DS* ds = (struct DS*) cpu->master;
616#ifdef USE_DEBUGGERS
617	if (ds->debugger) {
618		struct mDebuggerEntryInfo info = {
619			.address = _ARMPCAddress(cpu),
620			.type.bp.opcode = opcode
621		};
622		mDebuggerEnter(ds->debugger->d.p, DEBUGGER_ENTER_ILLEGAL_OP, &info);
623	}
624#endif
625	// TODO: More sensible category?
626	mLOG(DS, ERROR, "Stub opcode: %08x", opcode);
627}
628
629void DSIllegal(struct ARMCore* cpu, uint32_t opcode) {
630	struct DS* ds = (struct DS*) cpu->master;
631	if ((opcode & 0xFFFF) == (redzoneInstruction & 0xFFFF)) {
632		int currentCycles = 0;
633		if (cpu->executionMode == MODE_THUMB) {
634			cpu->gprs[ARM_PC] -= WORD_SIZE_THUMB * 2;
635			THUMB_WRITE_PC;
636		} else {
637			cpu->gprs[ARM_PC] -= WORD_SIZE_ARM * 2;
638			ARM_WRITE_PC;
639		}
640#ifdef USE_DEBUGGERS
641	} else if (ds->debugger) {
642		struct mDebuggerEntryInfo info = {
643			.address = _ARMPCAddress(cpu),
644			.type.bp.opcode = opcode
645		};
646		mDebuggerEnter(ds->debugger->d.p, DEBUGGER_ENTER_ILLEGAL_OP, &info);
647#endif
648	} else {
649		ARMRaiseUndefined(cpu);
650	}
651}
652
653void DSBreakpoint(struct ARMCore* cpu, int immediate) {
654	struct DS* ds = (struct DS*) cpu->master;
655	if (immediate >= CPU_COMPONENT_MAX) {
656		return;
657	}
658	switch (immediate) {
659#ifdef USE_DEBUGGERS
660	case CPU_COMPONENT_DEBUGGER:
661		if (ds->debugger) {
662			struct mDebuggerEntryInfo info = {
663				.address = _ARMPCAddress(cpu)
664			};
665			mDebuggerEnter(ds->debugger->d.p, DEBUGGER_ENTER_BREAKPOINT, &info);
666		}
667		break;
668#endif
669	default:
670		break;
671	}
672}
673
674void DS7TestIRQ(struct ARMCore* cpu) {
675	struct DS* ds = (struct DS*) cpu->master;
676	if (!ds->memory.io7[DS_REG_IME >> 1]) {
677		return;
678	}
679	uint32_t test = (ds->memory.io7[DS_REG_IE_LO >> 1] & ds->memory.io7[DS_REG_IF_LO >> 1]);
680	test |= (ds->memory.io7[DS_REG_IE_HI >> 1] & ds->memory.io7[DS_REG_IF_HI >> 1]) << 16;
681	if (test) {
682		ds->ds7.springIRQ = test;
683		cpu->nextEvent = cpu->cycles;
684	}
685}
686
687void DS9TestIRQ(struct ARMCore* cpu) {
688	struct DS* ds = (struct DS*) cpu->master;
689	if (!ds->memory.io9[DS_REG_IME >> 1]) {
690		return;
691	}
692	uint32_t test = (ds->memory.io9[DS_REG_IE_LO >> 1] & ds->memory.io9[DS_REG_IF_LO >> 1]);
693	test |= (ds->memory.io9[DS_REG_IE_HI >> 1] & ds->memory.io9[DS_REG_IF_HI >> 1]) << 16;
694	if (test) {
695		ds->ds9.springIRQ = test;
696		cpu->nextEvent = cpu->cycles;
697	}
698}
699
700static void _writeSysControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
701	mLOG(DS, STUB, "CP15 system control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
702}
703
704static void _writeCacheControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
705	mLOG(DS, STUB, "CP15 cache control control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
706	switch (opcode2) {
707	case 0:
708		cpu->cp15.r2.d = value;
709		break;
710	case 1:
711		cpu->cp15.r2.i = value;
712		break;
713	default:
714		mLOG(DS, GAME_ERROR, "CP15 cache control control bad op2: %i", opcode2);
715		break;
716	}
717}
718
719static void _writeWriteBufferControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
720	mLOG(DS, STUB, "CP15 write buffer control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
721	switch (opcode2) {
722	case 0:
723		cpu->cp15.r3.d = value;
724		break;
725	default:
726		mLOG(DS, GAME_ERROR, "CP15 cache control control bad op2: %i", opcode2);
727		break;
728	}
729}
730
731static void _writeAccessControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
732	mLOG(DS, STUB, "CP15 access control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
733}
734
735static void _writeRegionConfiguration(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
736	cpu->cp15.r6.region[crm] = value;
737	uint32_t base = ARMProtectionGetBase(value) << 12;
738	uint32_t size = 2 << ARMProtectionGetSize(value);
739	mLOG(DS, STUB, "CP15 region configuration write: Region: %i, Insn: %i, Base: %08X, Size: %08X", crm, opcode2, base, size);
740}
741
742static void _writeCache(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
743	switch (crm) {
744	case 0:
745		if (opcode2 == 4) {
746			ARMHalt(cpu);
747			return;
748		}
749		break;
750	}
751	mLOG(DS, STUB, "CP15 cache write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
752}
753
754static void _writeTCMControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
755	uint32_t base = ARMTCMControlGetBase(value) << 12;
756	uint32_t size = 512 << ARMTCMControlGetVirtualSize(value);
757	struct DS* ds = (struct DS*) cpu->master;
758	mLOG(DS, DEBUG, "CP15 TCM control write: CRm: %i, Op2: %i, Base: %08X, Size: %08X", crm, opcode2, base, size);
759	switch (opcode2) {
760	case 0:
761		cpu->cp15.r9.d = value;
762		ds->memory.dtcmBase = base;
763		ds->memory.dtcmSize = size;
764		break;
765	case 1:
766		cpu->cp15.r9.i = value;
767		ds->memory.itcmSize = size;
768		break;
769	default:
770		mLOG(DS, GAME_ERROR, "CP15 TCM control bad op2: %i", opcode2);
771		break;
772	}
773}
774
775void DS9WriteCP15(struct ARMCore* cpu, int crn, int crm, int opcode1, int opcode2, uint32_t value) {
776	switch (crn) {
777	default:
778		mLOG(DS, STUB, "CP15 unknown write: CRn: %i, CRm: %i, Op1: %i, Op2: %i, Value: 0x%08X", crn, crm, opcode1, opcode2, value);
779		break;
780	case 0:
781		mLOG(DS, GAME_ERROR, "Attempted to write to read-only cp15 register");
782		ARMRaiseUndefined(cpu);
783		break;
784	case 1:
785		_writeSysControl(cpu, crm, opcode2, value);
786		break;
787	case 2:
788		_writeCacheControl(cpu, crm, opcode2, value);
789		break;
790	case 3:
791		_writeWriteBufferControl(cpu, crm, opcode2, value);
792		break;
793	case 5:
794		_writeAccessControl(cpu, crm, opcode2, value);
795		break;
796	case 6:
797		_writeRegionConfiguration(cpu, crm, opcode2, value);
798		break;
799	case 7:
800		_writeCache(cpu, crm, opcode2, value);
801		break;
802	case 9:
803		_writeTCMControl(cpu, crm, opcode2, value);
804		break;
805	}
806}
807
808static uint32_t _readTCMControl(struct ARMCore* cpu, int crm, int opcode2) {
809	switch (opcode2) {
810	case 0:
811		return cpu->cp15.r9.d;
812	case 1:
813		return cpu->cp15.r9.i;
814	default:
815		mLOG(DS, GAME_ERROR, "CP15 TCM control bad op2: %i", opcode2);
816		return 0;
817	}
818}
819
820uint32_t DS9ReadCP15(struct ARMCore* cpu, int crn, int crm, int opcode1, int opcode2) {
821	switch (crn) {
822	default:
823		mLOG(DS, STUB, "CP15 unknown read: CRn: %i, CRm: %i, Op1: %i, Op2: %i", crn, crm, opcode1, opcode2);
824		return 0;
825	case 9:
826		return _readTCMControl(cpu, crm, opcode2);
827	}
828}
829
830void DSWriteIE(struct ARMCore* cpu, uint16_t* io, uint32_t value) {
831	if (io[DS_REG_IME >> 1] && (value & io[DS_REG_IF_LO >> 1] || (value >> 16) & io[DS_REG_IF_HI >> 1])) {
832		ARMRaiseIRQ(cpu);
833	}
834}
835void DSWriteIME(struct ARMCore* cpu, uint16_t* io, uint16_t value) {
836	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])) {
837		ARMRaiseIRQ(cpu);
838	}
839}
840
841void DSRaiseIRQ(struct ARMCore* cpu, uint16_t* io, enum DSIRQ irq) {
842	if (irq < 16) {
843		io[DS_REG_IF_LO >> 1] |= 1 << irq;
844	} else {
845		io[DS_REG_IF_HI >> 1] |= 1 << (irq - 16);
846	}
847
848	if ((irq < 16 && (io[DS_REG_IE_LO >> 1] & 1 << irq)) || (io[DS_REG_IE_HI >> 1] & (1 << (irq - 16)))) {
849		cpu->halted = 0;
850		if (io[DS_REG_IME >> 1]) {
851			ARMRaiseIRQ(cpu);
852		}
853	}
854}
855
856void DSFrameStarted(struct DS* ds) {
857	size_t c;
858	for (c = 0; c < mCoreCallbacksListSize(&ds->coreCallbacks); ++c) {
859		struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&ds->coreCallbacks, c);
860		if (callbacks->videoFrameStarted) {
861			callbacks->videoFrameStarted(callbacks->context);
862		}
863	}
864}
865
866void DSFrameEnded(struct DS* ds) {
867	size_t c;
868	for (c = 0; c < mCoreCallbacksListSize(&ds->coreCallbacks); ++c) {
869		struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&ds->coreCallbacks, c);
870		if (callbacks->videoFrameEnded) {
871			callbacks->videoFrameEnded(callbacks->context);
872		}
873	}
874
875	if (ds->stream && ds->stream->postVideoFrame) {
876		const color_t* pixels;
877		size_t stride;
878		ds->video.renderer->getPixels(ds->video.renderer, &stride, (const void**) &pixels);
879		ds->stream->postVideoFrame(ds->stream, pixels, stride);
880	}
881}
882
883uint16_t DSWriteRTC(struct DS* ds, DSRegisterRTC value) {
884	switch (ds->rtc.transferStep) {
885	case 0:
886		if ((value & 6) == 2) {
887			ds->rtc.transferStep = 1;
888		}
889		break;
890	case 1:
891		if ((value & 6) == 6) {
892			ds->rtc.transferStep = 2;
893		}
894		break;
895	case 2:
896		if (!DSRegisterRTCIsClock(value)) {
897			if (DSRegisterRTCIsDataDirection(value)) {
898				ds->rtc.bits &= ~(1 << ds->rtc.bitsRead);
899				ds->rtc.bits |= DSRegisterRTCGetData(value) << ds->rtc.bitsRead;
900			} else {
901				value = DSRegisterRTCSetData(value, GBARTCOutput(&ds->rtc));
902			}
903		} else {
904			if (DSRegisterRTCIsSelect(value)) {
905				// GPIO direction should always != reading
906				if (DSRegisterRTCIsDataDirection(value)) {
907					if (RTCCommandDataIsReading(ds->rtc.command)) {
908						mLOG(DS, GAME_ERROR, "Attempting to write to RTC while in read mode");
909					}
910					++ds->rtc.bitsRead;
911					if (ds->rtc.bitsRead == 8) {
912						GBARTCProcessByte(&ds->rtc, ds->rtcSource);
913					}
914				} else {
915					value = DSRegisterRTCSetData(value, GBARTCOutput(&ds->rtc));
916					++ds->rtc.bitsRead;
917					if (ds->rtc.bitsRead == 8) {
918						--ds->rtc.bytesRemaining;
919						if (ds->rtc.bytesRemaining <= 0) {
920							ds->rtc.commandActive = 0;
921							ds->rtc.command = RTCCommandDataClearReading(ds->rtc.command);
922						}
923						ds->rtc.bitsRead = 0;
924					}
925				}
926			} else {
927				ds->rtc.bitsRead = 0;
928				ds->rtc.bytesRemaining = 0;
929				ds->rtc.commandActive = 0;
930				ds->rtc.command = RTCCommandDataClearReading(ds->rtc.command);
931				ds->rtc.transferStep = 0;
932			}
933		}
934		break;
935	}
936	return value;
937}