all repos — mgba @ 0cf9bf75e28e632ca071bb59a15e4f1afa4b4b9c

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		return false;
578	}
579	mLOG(DS, INFO, "Found DS firmware");
580	ds->firmwareVf = vf;
581	return true;
582}
583
584void DSGetGameCode(struct DS* ds, char* out) {
585	memset(out, 0, 8);
586	if (!ds->romVf) {
587		return;
588	}
589
590	struct DSCartridge* cart = ds->romVf->map(ds->romVf, sizeof(*cart), MAP_READ);
591	// TODO: TWL-?
592	memcpy(out, "NTR-", 4);
593	memcpy(&out[4], &cart->id, 4);
594	ds->romVf->unmap(ds->romVf, cart, sizeof(*cart));
595}
596
597void DSGetGameTitle(struct DS* ds, char* out) {
598	memset(out, 0, 12);
599	if (!ds->romVf) {
600		return;
601	}
602
603	struct DSCartridge* cart = ds->romVf->map(ds->romVf, sizeof(*cart), MAP_READ);
604	memcpy(out, &cart->title, 12);
605	ds->romVf->unmap(ds->romVf, cart, sizeof(*cart));
606}
607
608void DSHitStub(struct ARMCore* cpu, uint32_t opcode) {
609	struct DS* ds = (struct DS*) cpu->master;
610	if (ds->debugger) {
611		struct mDebuggerEntryInfo info = {
612			.address = _ARMPCAddress(cpu),
613			.opcode = opcode
614		};
615		mDebuggerEnter(ds->debugger->d.p, DEBUGGER_ENTER_ILLEGAL_OP, &info);
616	}
617	// TODO: More sensible category?
618	mLOG(DS, ERROR, "Stub opcode: %08x", opcode);
619}
620
621void DSIllegal(struct ARMCore* cpu, uint32_t opcode) {
622	struct DS* ds = (struct DS*) cpu->master;
623	if ((opcode & 0xFFFF) == (redzoneInstruction & 0xFFFF)) {
624		int currentCycles = 0;
625		if (cpu->executionMode == MODE_THUMB) {
626			cpu->gprs[ARM_PC] -= WORD_SIZE_THUMB * 2;
627			THUMB_WRITE_PC;
628		} else {
629			cpu->gprs[ARM_PC] -= WORD_SIZE_ARM * 2;
630			ARM_WRITE_PC;
631		}
632	} else if (ds->debugger) {
633		struct mDebuggerEntryInfo info = {
634			.address = _ARMPCAddress(cpu),
635			.opcode = opcode
636		};
637		mDebuggerEnter(ds->debugger->d.p, DEBUGGER_ENTER_ILLEGAL_OP, &info);
638	} else {
639		ARMRaiseUndefined(cpu);
640	}
641}
642
643void DSBreakpoint(struct ARMCore* cpu, int immediate) {
644	struct DS* ds = (struct DS*) cpu->master;
645	if (immediate >= CPU_COMPONENT_MAX) {
646		return;
647	}
648	switch (immediate) {
649	case CPU_COMPONENT_DEBUGGER:
650		if (ds->debugger) {
651			struct mDebuggerEntryInfo info = {
652				.address = _ARMPCAddress(cpu)
653			};
654			mDebuggerEnter(ds->debugger->d.p, DEBUGGER_ENTER_BREAKPOINT, &info);
655		}
656		break;
657	default:
658		break;
659	}
660}
661
662void DS7TestIRQ(struct ARMCore* cpu) {
663	struct DS* ds = (struct DS*) cpu->master;
664	if (!ds->memory.io7[DS_REG_IME >> 1]) {
665		return;
666	}
667	uint32_t test = (ds->memory.io7[DS_REG_IE_LO >> 1] & ds->memory.io7[DS_REG_IF_LO >> 1]);
668	test |= (ds->memory.io7[DS_REG_IE_HI >> 1] & ds->memory.io7[DS_REG_IF_HI >> 1]) << 16;
669	if (test) {
670		ds->ds7.springIRQ = test;
671		cpu->nextEvent = cpu->cycles;
672	}
673}
674
675void DS9TestIRQ(struct ARMCore* cpu) {
676	struct DS* ds = (struct DS*) cpu->master;
677	if (!ds->memory.io9[DS_REG_IME >> 1]) {
678		return;
679	}
680	uint32_t test = (ds->memory.io9[DS_REG_IE_LO >> 1] & ds->memory.io9[DS_REG_IF_LO >> 1]);
681	test |= (ds->memory.io9[DS_REG_IE_HI >> 1] & ds->memory.io9[DS_REG_IF_HI >> 1]) << 16;
682	if (test) {
683		ds->ds9.springIRQ = test;
684		cpu->nextEvent = cpu->cycles;
685	}
686}
687
688static void _writeSysControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
689	mLOG(DS, STUB, "CP15 system control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
690}
691
692static void _writeCacheControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
693	mLOG(DS, STUB, "CP15 cache control control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
694	switch (opcode2) {
695	case 0:
696		cpu->cp15.r2.d = value;
697		break;
698	case 1:
699		cpu->cp15.r2.i = value;
700		break;
701	default:
702		mLOG(DS, GAME_ERROR, "CP15 cache control control bad op2: %i", opcode2);
703		break;
704	}
705}
706
707static void _writeWriteBufferControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
708	mLOG(DS, STUB, "CP15 write buffer control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
709	switch (opcode2) {
710	case 0:
711		cpu->cp15.r3.d = 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 _writeAccessControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
720	mLOG(DS, STUB, "CP15 access control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
721}
722
723static void _writeRegionConfiguration(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
724	cpu->cp15.r6.region[crm] = value;
725	uint32_t base = ARMProtectionGetBase(value) << 12;
726	uint32_t size = 2 << ARMProtectionGetSize(value);
727	mLOG(DS, STUB, "CP15 region configuration write: Region: %i, Insn: %i, Base: %08X, Size: %08X", crm, opcode2, base, size);
728}
729
730static void _writeCache(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
731	switch (crm) {
732	case 0:
733		if (opcode2 == 4) {
734			ARMHalt(cpu);
735			return;
736		}
737		break;
738	}
739	mLOG(DS, STUB, "CP15 cache write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
740}
741
742static void _writeTCMControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
743	uint32_t base = ARMTCMControlGetBase(value) << 12;
744	uint32_t size = 512 << ARMTCMControlGetVirtualSize(value);
745	struct DS* ds = (struct DS*) cpu->master;
746	mLOG(DS, DEBUG, "CP15 TCM control write: CRm: %i, Op2: %i, Base: %08X, Size: %08X", crm, opcode2, base, size);
747	switch (opcode2) {
748	case 0:
749		cpu->cp15.r9.d = value;
750		ds->memory.dtcmBase = base;
751		ds->memory.dtcmSize = size;
752		break;
753	case 1:
754		cpu->cp15.r9.i = value;
755		ds->memory.itcmSize = size;
756		break;
757	default:
758		mLOG(DS, GAME_ERROR, "CP15 TCM control bad op2: %i", opcode2);
759		break;
760	}
761}
762
763void DS9WriteCP15(struct ARMCore* cpu, int crn, int crm, int opcode1, int opcode2, uint32_t value) {
764	switch (crn) {
765	default:
766		mLOG(DS, STUB, "CP15 unknown write: CRn: %i, CRm: %i, Op1: %i, Op2: %i, Value: 0x%08X", crn, crm, opcode1, opcode2, value);
767		break;
768	case 0:
769		mLOG(DS, GAME_ERROR, "Attempted to write to read-only cp15 register");
770		ARMRaiseUndefined(cpu);
771		break;
772	case 1:
773		_writeSysControl(cpu, crm, opcode2, value);
774		break;
775	case 2:
776		_writeCacheControl(cpu, crm, opcode2, value);
777		break;
778	case 3:
779		_writeWriteBufferControl(cpu, crm, opcode2, value);
780		break;
781	case 5:
782		_writeAccessControl(cpu, crm, opcode2, value);
783		break;
784	case 6:
785		_writeRegionConfiguration(cpu, crm, opcode2, value);
786		break;
787	case 7:
788		_writeCache(cpu, crm, opcode2, value);
789		break;
790	case 9:
791		_writeTCMControl(cpu, crm, opcode2, value);
792		break;
793	}
794}
795
796static uint32_t _readTCMControl(struct ARMCore* cpu, int crm, int opcode2) {
797	switch (opcode2) {
798	case 0:
799		return cpu->cp15.r9.d;
800	case 1:
801		return cpu->cp15.r9.i;
802	default:
803		mLOG(DS, GAME_ERROR, "CP15 TCM control bad op2: %i", opcode2);
804		return 0;
805	}
806}
807
808uint32_t DS9ReadCP15(struct ARMCore* cpu, int crn, int crm, int opcode1, int opcode2) {
809	switch (crn) {
810	default:
811		mLOG(DS, STUB, "CP15 unknown read: CRn: %i, CRm: %i, Op1: %i, Op2: %i", crn, crm, opcode1, opcode2);
812		return 0;
813	case 9:
814		return _readTCMControl(cpu, crm, opcode2);
815	}
816}
817
818void DSWriteIE(struct ARMCore* cpu, uint16_t* io, uint32_t value) {
819	if (io[DS_REG_IME >> 1] && (value & io[DS_REG_IF_LO >> 1] || (value >> 16) & io[DS_REG_IF_HI >> 1])) {
820		ARMRaiseIRQ(cpu);
821	}
822}
823void DSWriteIME(struct ARMCore* cpu, uint16_t* io, uint16_t value) {
824	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])) {
825		ARMRaiseIRQ(cpu);
826	}
827}
828
829void DSRaiseIRQ(struct ARMCore* cpu, uint16_t* io, enum DSIRQ irq) {
830	if (irq < 16) {
831		io[DS_REG_IF_LO >> 1] |= 1 << irq;
832	} else {
833		io[DS_REG_IF_HI >> 1] |= 1 << (irq - 16);
834	}
835
836	if ((irq < 16 && (io[DS_REG_IE_LO >> 1] & 1 << irq)) || (io[DS_REG_IE_HI >> 1] & (1 << (irq - 16)))) {
837		cpu->halted = 0;
838		if (io[DS_REG_IME >> 1]) {
839			ARMRaiseIRQ(cpu);
840		}
841	}
842}
843
844void DSFrameStarted(struct DS* ds) {
845	size_t c;
846	for (c = 0; c < mCoreCallbacksListSize(&ds->coreCallbacks); ++c) {
847		struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&ds->coreCallbacks, c);
848		if (callbacks->videoFrameStarted) {
849			callbacks->videoFrameStarted(callbacks->context);
850		}
851	}
852}
853
854void DSFrameEnded(struct DS* ds) {
855	size_t c;
856	for (c = 0; c < mCoreCallbacksListSize(&ds->coreCallbacks); ++c) {
857		struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&ds->coreCallbacks, c);
858		if (callbacks->videoFrameEnded) {
859			callbacks->videoFrameEnded(callbacks->context);
860		}
861	}
862
863	if (ds->stream && ds->stream->postVideoFrame) {
864		const color_t* pixels;
865		size_t stride;
866		ds->video.renderer->getPixels(ds->video.renderer, &stride, (const void**) &pixels);
867		ds->stream->postVideoFrame(ds->stream, pixels, stride);
868	}
869}
870
871uint16_t DSWriteRTC(struct DS* ds, DSRegisterRTC value) {
872	switch (ds->rtc.transferStep) {
873	case 0:
874		if ((value & 6) == 2) {
875			ds->rtc.transferStep = 1;
876		}
877		break;
878	case 1:
879		if ((value & 6) == 6) {
880			ds->rtc.transferStep = 2;
881		}
882		break;
883	case 2:
884		if (!DSRegisterRTCIsClock(value)) {
885			if (DSRegisterRTCIsDataDirection(value)) {
886				ds->rtc.bits &= ~(1 << ds->rtc.bitsRead);
887				ds->rtc.bits |= DSRegisterRTCGetData(value) << ds->rtc.bitsRead;
888			} else {
889				value = DSRegisterRTCSetData(value, GBARTCOutput(&ds->rtc));
890			}
891		} else {
892			if (DSRegisterRTCIsSelect(value)) {
893				// GPIO direction should always != reading
894				if (DSRegisterRTCIsDataDirection(value)) {
895					if (RTCCommandDataIsReading(ds->rtc.command)) {
896						mLOG(DS, GAME_ERROR, "Attempting to write to RTC while in read mode");
897					}
898					++ds->rtc.bitsRead;
899					if (ds->rtc.bitsRead == 8) {
900						GBARTCProcessByte(&ds->rtc, ds->rtcSource);
901					}
902				} else {
903					value = DSRegisterRTCSetData(value, GBARTCOutput(&ds->rtc));
904					++ds->rtc.bitsRead;
905					if (ds->rtc.bitsRead == 8) {
906						--ds->rtc.bytesRemaining;
907						if (ds->rtc.bytesRemaining <= 0) {
908							ds->rtc.commandActive = 0;
909							ds->rtc.command = RTCCommandDataClearReading(ds->rtc.command);
910						}
911						ds->rtc.bitsRead = 0;
912					}
913				}
914			} else {
915				ds->rtc.bitsRead = 0;
916				ds->rtc.bytesRemaining = 0;
917				ds->rtc.commandActive = 0;
918				ds->rtc.command = RTCCommandDataClearReading(ds->rtc.command);
919				ds->rtc.transferStep = 0;
920			}
921		}
922		break;
923	}
924	return value;
925}