all repos — mgba @ f96a8f78ebcc7d730b9977bf5658063bc9d66e9b

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