all repos — mgba @ 1882b155677ce11c4fd6e02bb5285fe78a2cc3f4

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	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	ds->debugger = NULL;
469	ARMHotplugDetach(ds->ds7.cpu, CPU_COMPONENT_DEBUGGER);
470	ARMHotplugDetach(ds->ds9.cpu, CPU_COMPONENT_DEBUGGER);
471	ds->ds7.cpu->components[CPU_COMPONENT_DEBUGGER] = NULL;
472	ds->ds9.cpu->components[CPU_COMPONENT_DEBUGGER] = NULL;
473}
474
475bool DSLoadROM(struct DS* ds, struct VFile* vf) {
476	DSUnloadROM(ds);
477	ds->romVf = vf;
478	// TODO: error check
479	return true;
480}
481
482bool DSLoadSave(struct DS* ds, struct VFile* sav) {
483	DSSlot1SPIInit(ds, sav);
484	return true;
485}
486
487bool DSIsROM(struct VFile* vf) {
488	if (vf->seek(vf, DS_ROM_MAGIC_OFFSET, SEEK_SET) < 0) {
489		return false;
490	}
491	uint8_t signature[sizeof(DS_ROM_MAGIC)];
492	if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
493		return false;
494	}
495	return memcmp(signature, DS_ROM_MAGIC, sizeof(signature)) == 0 || memcmp(signature, DS_ROM_MAGIC_2, sizeof(signature)) == 0;
496}
497
498bool DSIsBIOS7(struct VFile* vf) {
499	size_t size = vf->size(vf);
500	void* data = NULL;
501	uint32_t crc;
502	if (size == DS7_SIZE_BIOS) {
503		data = vf->map(vf, size, MAP_READ);
504	}
505	if (!data) {
506		return false;
507	}
508	crc = doCrc32(data, size);
509	vf->unmap(vf, data, size);
510	return crc == DS7_BIOS_CHECKSUM;
511}
512
513bool DSIsBIOS9(struct VFile* vf) {
514	size_t size = vf->size(vf);
515	void* data = NULL;
516	uint32_t crc;
517	if (size == DS9_SIZE_BIOS) {
518		data = vf->map(vf, 0x1000, MAP_READ);
519	} else if (size == 0x1000) {
520		data = vf->map(vf, 0x1000, MAP_READ);
521	}
522	if (!data) {
523		return false;
524	}
525	crc = doCrc32(data, 0x1000);
526	vf->unmap(vf, data, 0x1000);
527	return crc == DS9_BIOS_CHECKSUM;
528}
529
530bool DSIsFirmware(struct VFile* vf) {
531	if (vf->seek(vf, DS_FIRMWARE_MAGIC_OFFSET, SEEK_SET) < 0) {
532		return false;
533	}
534	uint8_t signature[sizeof(DS_FIRMWARE_MAGIC)];
535	if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
536		return false;
537	}
538	return memcmp(signature, DS_FIRMWARE_MAGIC, sizeof(signature)) == 0;
539}
540
541bool DSLoadBIOS(struct DS* ds, struct VFile* vf) {
542	size_t size = vf->size(vf);
543	void* data = NULL;
544	uint32_t crc;
545	if (size == DS7_SIZE_BIOS) {
546		data = vf->map(vf, size, MAP_READ);
547	} else if (size == 0x1000) {
548		data = calloc(DS9_SIZE_BIOS, 1);
549		vf->read(vf, data, size);
550	} else if (size == DS9_SIZE_BIOS) {
551		data = vf->map(vf, size, MAP_READ);
552	} else if (size == DS_SIZE_FIRMWARE) {
553		return DSLoadFirmware(ds, vf);
554	}
555	if (!data) {
556		return false;
557	}
558	crc = doCrc32(data, size);
559	if (crc == DS7_BIOS_CHECKSUM) {
560		ds->bios7Vf = vf;
561		ds->memory.bios7 = data;
562		mLOG(DS, INFO, "Official DS ARM7 BIOS detected");
563	} else if (crc == DS9_BIOS_CHECKSUM) {
564		ds->bios9Vf = vf;
565		ds->memory.bios9 = data;
566		mLOG(DS, INFO, "Official DS ARM9 BIOS detected");
567	} else {
568		mLOG(DS, WARN, "BIOS checksum incorrect");
569		vf->unmap(vf, data, size);
570		return false;
571	}
572	return true;
573}
574
575bool DSLoadFirmware(struct DS* ds, struct VFile* vf) {
576	size_t size = vf->size(vf);
577	if (!DSIsFirmware(vf)) {
578		return false;
579	}
580	if (size != DS_SIZE_FIRMWARE) {
581		return false;
582	}
583	mLOG(DS, INFO, "Found DS firmware");
584	ds->firmwareVf = vf;
585	return true;
586}
587
588void DSGetGameCode(struct DS* ds, char* out) {
589	memset(out, 0, 8);
590	if (!ds->romVf) {
591		return;
592	}
593
594	struct DSCartridge* cart = ds->romVf->map(ds->romVf, sizeof(*cart), MAP_READ);
595	// TODO: TWL-?
596	memcpy(out, "NTR-", 4);
597	memcpy(&out[4], &cart->id, 4);
598	ds->romVf->unmap(ds->romVf, cart, sizeof(*cart));
599}
600
601void DSGetGameTitle(struct DS* ds, char* out) {
602	memset(out, 0, 12);
603	if (!ds->romVf) {
604		return;
605	}
606
607	struct DSCartridge* cart = ds->romVf->map(ds->romVf, sizeof(*cart), MAP_READ);
608	memcpy(out, &cart->title, 12);
609	ds->romVf->unmap(ds->romVf, cart, sizeof(*cart));
610}
611
612void DSHitStub(struct ARMCore* cpu, uint32_t opcode) {
613	struct DS* ds = (struct DS*) cpu->master;
614#ifdef USE_DEBUGGERS
615	if (ds->debugger) {
616		struct mDebuggerEntryInfo info = {
617			.address = _ARMPCAddress(cpu),
618			.opcode = opcode
619		};
620		mDebuggerEnter(ds->debugger->d.p, DEBUGGER_ENTER_ILLEGAL_OP, &info);
621	}
622#endif
623	// TODO: More sensible category?
624	mLOG(DS, ERROR, "Stub opcode: %08x", opcode);
625}
626
627void DSIllegal(struct ARMCore* cpu, uint32_t opcode) {
628	struct DS* ds = (struct DS*) cpu->master;
629	if ((opcode & 0xFFFF) == (redzoneInstruction & 0xFFFF)) {
630		int currentCycles = 0;
631		if (cpu->executionMode == MODE_THUMB) {
632			cpu->gprs[ARM_PC] -= WORD_SIZE_THUMB * 2;
633			THUMB_WRITE_PC;
634		} else {
635			cpu->gprs[ARM_PC] -= WORD_SIZE_ARM * 2;
636			ARM_WRITE_PC;
637		}
638#ifdef USE_DEBUGGERS
639	} else if (ds->debugger) {
640		struct mDebuggerEntryInfo info = {
641			.address = _ARMPCAddress(cpu),
642			.opcode = opcode
643		};
644		mDebuggerEnter(ds->debugger->d.p, DEBUGGER_ENTER_ILLEGAL_OP, &info);
645#endif
646	} else {
647		ARMRaiseUndefined(cpu);
648	}
649}
650
651void DSBreakpoint(struct ARMCore* cpu, int immediate) {
652	struct DS* ds = (struct DS*) cpu->master;
653	if (immediate >= CPU_COMPONENT_MAX) {
654		return;
655	}
656	switch (immediate) {
657#ifdef USE_DEBUGGERS
658	case CPU_COMPONENT_DEBUGGER:
659		if (ds->debugger) {
660			struct mDebuggerEntryInfo info = {
661				.address = _ARMPCAddress(cpu)
662			};
663			mDebuggerEnter(ds->debugger->d.p, DEBUGGER_ENTER_BREAKPOINT, &info);
664		}
665		break;
666#endif
667	default:
668		break;
669	}
670}
671
672void DS7TestIRQ(struct ARMCore* cpu) {
673	struct DS* ds = (struct DS*) cpu->master;
674	if (!ds->memory.io7[DS_REG_IME >> 1]) {
675		return;
676	}
677	uint32_t test = (ds->memory.io7[DS_REG_IE_LO >> 1] & ds->memory.io7[DS_REG_IF_LO >> 1]);
678	test |= (ds->memory.io7[DS_REG_IE_HI >> 1] & ds->memory.io7[DS_REG_IF_HI >> 1]) << 16;
679	if (test) {
680		ds->ds7.springIRQ = test;
681		cpu->nextEvent = cpu->cycles;
682	}
683}
684
685void DS9TestIRQ(struct ARMCore* cpu) {
686	struct DS* ds = (struct DS*) cpu->master;
687	if (!ds->memory.io9[DS_REG_IME >> 1]) {
688		return;
689	}
690	uint32_t test = (ds->memory.io9[DS_REG_IE_LO >> 1] & ds->memory.io9[DS_REG_IF_LO >> 1]);
691	test |= (ds->memory.io9[DS_REG_IE_HI >> 1] & ds->memory.io9[DS_REG_IF_HI >> 1]) << 16;
692	if (test) {
693		ds->ds9.springIRQ = test;
694		cpu->nextEvent = cpu->cycles;
695	}
696}
697
698static void _writeSysControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
699	mLOG(DS, STUB, "CP15 system control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
700}
701
702static void _writeCacheControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
703	mLOG(DS, STUB, "CP15 cache control control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
704	switch (opcode2) {
705	case 0:
706		cpu->cp15.r2.d = value;
707		break;
708	case 1:
709		cpu->cp15.r2.i = value;
710		break;
711	default:
712		mLOG(DS, GAME_ERROR, "CP15 cache control control bad op2: %i", opcode2);
713		break;
714	}
715}
716
717static void _writeWriteBufferControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
718	mLOG(DS, STUB, "CP15 write buffer control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
719	switch (opcode2) {
720	case 0:
721		cpu->cp15.r3.d = value;
722		break;
723	default:
724		mLOG(DS, GAME_ERROR, "CP15 cache control control bad op2: %i", opcode2);
725		break;
726	}
727}
728
729static void _writeAccessControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
730	mLOG(DS, STUB, "CP15 access control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
731}
732
733static void _writeRegionConfiguration(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
734	cpu->cp15.r6.region[crm] = value;
735	uint32_t base = ARMProtectionGetBase(value) << 12;
736	uint32_t size = 2 << ARMProtectionGetSize(value);
737	mLOG(DS, STUB, "CP15 region configuration write: Region: %i, Insn: %i, Base: %08X, Size: %08X", crm, opcode2, base, size);
738}
739
740static void _writeCache(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
741	switch (crm) {
742	case 0:
743		if (opcode2 == 4) {
744			ARMHalt(cpu);
745			return;
746		}
747		break;
748	}
749	mLOG(DS, STUB, "CP15 cache write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
750}
751
752static void _writeTCMControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
753	uint32_t base = ARMTCMControlGetBase(value) << 12;
754	uint32_t size = 512 << ARMTCMControlGetVirtualSize(value);
755	struct DS* ds = (struct DS*) cpu->master;
756	mLOG(DS, DEBUG, "CP15 TCM control write: CRm: %i, Op2: %i, Base: %08X, Size: %08X", crm, opcode2, base, size);
757	switch (opcode2) {
758	case 0:
759		cpu->cp15.r9.d = value;
760		ds->memory.dtcmBase = base;
761		ds->memory.dtcmSize = size;
762		break;
763	case 1:
764		cpu->cp15.r9.i = value;
765		ds->memory.itcmSize = size;
766		break;
767	default:
768		mLOG(DS, GAME_ERROR, "CP15 TCM control bad op2: %i", opcode2);
769		break;
770	}
771}
772
773void DS9WriteCP15(struct ARMCore* cpu, int crn, int crm, int opcode1, int opcode2, uint32_t value) {
774	switch (crn) {
775	default:
776		mLOG(DS, STUB, "CP15 unknown write: CRn: %i, CRm: %i, Op1: %i, Op2: %i, Value: 0x%08X", crn, crm, opcode1, opcode2, value);
777		break;
778	case 0:
779		mLOG(DS, GAME_ERROR, "Attempted to write to read-only cp15 register");
780		ARMRaiseUndefined(cpu);
781		break;
782	case 1:
783		_writeSysControl(cpu, crm, opcode2, value);
784		break;
785	case 2:
786		_writeCacheControl(cpu, crm, opcode2, value);
787		break;
788	case 3:
789		_writeWriteBufferControl(cpu, crm, opcode2, value);
790		break;
791	case 5:
792		_writeAccessControl(cpu, crm, opcode2, value);
793		break;
794	case 6:
795		_writeRegionConfiguration(cpu, crm, opcode2, value);
796		break;
797	case 7:
798		_writeCache(cpu, crm, opcode2, value);
799		break;
800	case 9:
801		_writeTCMControl(cpu, crm, opcode2, value);
802		break;
803	}
804}
805
806static uint32_t _readTCMControl(struct ARMCore* cpu, int crm, int opcode2) {
807	switch (opcode2) {
808	case 0:
809		return cpu->cp15.r9.d;
810	case 1:
811		return cpu->cp15.r9.i;
812	default:
813		mLOG(DS, GAME_ERROR, "CP15 TCM control bad op2: %i", opcode2);
814		return 0;
815	}
816}
817
818uint32_t DS9ReadCP15(struct ARMCore* cpu, int crn, int crm, int opcode1, int opcode2) {
819	switch (crn) {
820	default:
821		mLOG(DS, STUB, "CP15 unknown read: CRn: %i, CRm: %i, Op1: %i, Op2: %i", crn, crm, opcode1, opcode2);
822		return 0;
823	case 9:
824		return _readTCMControl(cpu, crm, opcode2);
825	}
826}
827
828void DSWriteIE(struct ARMCore* cpu, uint16_t* io, uint32_t value) {
829	if (io[DS_REG_IME >> 1] && (value & io[DS_REG_IF_LO >> 1] || (value >> 16) & io[DS_REG_IF_HI >> 1])) {
830		ARMRaiseIRQ(cpu);
831	}
832}
833void DSWriteIME(struct ARMCore* cpu, uint16_t* io, uint16_t value) {
834	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])) {
835		ARMRaiseIRQ(cpu);
836	}
837}
838
839void DSRaiseIRQ(struct ARMCore* cpu, uint16_t* io, enum DSIRQ irq) {
840	if (irq < 16) {
841		io[DS_REG_IF_LO >> 1] |= 1 << irq;
842	} else {
843		io[DS_REG_IF_HI >> 1] |= 1 << (irq - 16);
844	}
845
846	if ((irq < 16 && (io[DS_REG_IE_LO >> 1] & 1 << irq)) || (io[DS_REG_IE_HI >> 1] & (1 << (irq - 16)))) {
847		cpu->halted = 0;
848		if (io[DS_REG_IME >> 1]) {
849			ARMRaiseIRQ(cpu);
850		}
851	}
852}
853
854void DSFrameStarted(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->videoFrameStarted) {
859			callbacks->videoFrameStarted(callbacks->context);
860		}
861	}
862}
863
864void DSFrameEnded(struct DS* ds) {
865	size_t c;
866	for (c = 0; c < mCoreCallbacksListSize(&ds->coreCallbacks); ++c) {
867		struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&ds->coreCallbacks, c);
868		if (callbacks->videoFrameEnded) {
869			callbacks->videoFrameEnded(callbacks->context);
870		}
871	}
872
873	if (ds->stream && ds->stream->postVideoFrame) {
874		const color_t* pixels;
875		size_t stride;
876		ds->video.renderer->getPixels(ds->video.renderer, &stride, (const void**) &pixels);
877		ds->stream->postVideoFrame(ds->stream, pixels, stride);
878	}
879}
880
881uint16_t DSWriteRTC(struct DS* ds, DSRegisterRTC value) {
882	switch (ds->rtc.transferStep) {
883	case 0:
884		if ((value & 6) == 2) {
885			ds->rtc.transferStep = 1;
886		}
887		break;
888	case 1:
889		if ((value & 6) == 6) {
890			ds->rtc.transferStep = 2;
891		}
892		break;
893	case 2:
894		if (!DSRegisterRTCIsClock(value)) {
895			if (DSRegisterRTCIsDataDirection(value)) {
896				ds->rtc.bits &= ~(1 << ds->rtc.bitsRead);
897				ds->rtc.bits |= DSRegisterRTCGetData(value) << ds->rtc.bitsRead;
898			} else {
899				value = DSRegisterRTCSetData(value, GBARTCOutput(&ds->rtc));
900			}
901		} else {
902			if (DSRegisterRTCIsSelect(value)) {
903				// GPIO direction should always != reading
904				if (DSRegisterRTCIsDataDirection(value)) {
905					if (RTCCommandDataIsReading(ds->rtc.command)) {
906						mLOG(DS, GAME_ERROR, "Attempting to write to RTC while in read mode");
907					}
908					++ds->rtc.bitsRead;
909					if (ds->rtc.bitsRead == 8) {
910						GBARTCProcessByte(&ds->rtc, ds->rtcSource);
911					}
912				} else {
913					value = DSRegisterRTCSetData(value, GBARTCOutput(&ds->rtc));
914					++ds->rtc.bitsRead;
915					if (ds->rtc.bitsRead == 8) {
916						--ds->rtc.bytesRemaining;
917						if (ds->rtc.bytesRemaining <= 0) {
918							ds->rtc.commandActive = 0;
919							ds->rtc.command = RTCCommandDataClearReading(ds->rtc.command);
920						}
921						ds->rtc.bitsRead = 0;
922					}
923				}
924			} else {
925				ds->rtc.bitsRead = 0;
926				ds->rtc.bytesRemaining = 0;
927				ds->rtc.commandActive = 0;
928				ds->rtc.command = RTCCommandDataClearReading(ds->rtc.command);
929				ds->rtc.transferStep = 0;
930			}
931		}
932		break;
933	}
934	return value;
935}