all repos — mgba @ 3d25a10f3d9e5baaa6a42ffa9d06ac9851b94242

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