all repos — mgba @ 40731754098ba9f7aa4dc80b0cc76b3612e75529

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");
 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	ds->ds7.springIRQ = 0;
203	ds->ds9.springIRQ = 0;
204	DSTimerInit(ds);
205	ds->keySource = NULL;
206	ds->rtcSource = NULL;
207	ds->rumble = NULL;
208
209	ds->romVf = NULL;
210	DSSlot1SPIInit(ds, NULL);
211
212	ds->keyCallback = NULL;
213
214	ds->divEvent.name = "DS Hardware Divide";
215	ds->divEvent.callback = _divide;
216	ds->divEvent.context = ds;
217	ds->divEvent.priority = 0x50;
218
219	ds->sqrtEvent.name = "DS Hardware Sqrt";
220	ds->sqrtEvent.callback = _sqrt;
221	ds->sqrtEvent.context = ds;
222	ds->sqrtEvent.priority = 0x51;
223
224	mTimingInit(&ds->ds7.timing, &ds->ds7.cpu->cycles, &ds->ds7.cpu->nextEvent);
225	mTimingInit(&ds->ds9.timing, &ds->ds9.cpu->cycles, &ds->ds9.cpu->nextEvent);
226}
227
228void DSUnloadROM(struct DS* ds) {
229	if (ds->romVf) {
230		ds->romVf->close(ds->romVf);
231		ds->romVf = NULL;
232	}
233}
234
235void DSDestroy(struct DS* ds) {
236	CircleBufferDeinit(&ds->ds7.fifo);
237	CircleBufferDeinit(&ds->ds9.fifo);
238	DSUnloadROM(ds);
239	DSMemoryDeinit(ds);
240	DSGXDeinit(&ds->gx);
241	mTimingDeinit(&ds->ds7.timing);
242	mTimingDeinit(&ds->ds9.timing);
243}
244
245void DS7InterruptHandlerInit(struct ARMInterruptHandler* irqh) {
246	irqh->reset = DS7Reset;
247	irqh->processEvents = DS7ProcessEvents;
248	irqh->swi16 = DS7Swi16;
249	irqh->swi32 = DS7Swi32;
250	irqh->hitIllegal = DSIllegal;
251	irqh->readCPSR = DS7TestIRQ;
252	irqh->writeCP15 = NULL;
253	irqh->readCP15 = NULL;
254	irqh->hitStub = DSHitStub;
255	irqh->bkpt16 = DSBreakpoint;
256	irqh->bkpt32 = DSBreakpoint;
257}
258
259void DS9InterruptHandlerInit(struct ARMInterruptHandler* irqh) {
260	irqh->reset = DS9Reset;
261	irqh->processEvents = DS9ProcessEvents;
262	irqh->swi16 = DS9Swi16;
263	irqh->swi32 = DS9Swi32;
264	irqh->hitIllegal = DSIllegal;
265	irqh->readCPSR = DS9TestIRQ;
266	irqh->writeCP15 = DS9WriteCP15;
267	irqh->readCP15 = DS9ReadCP15;
268	irqh->hitStub = DSHitStub;
269	irqh->bkpt16 = DSBreakpoint;
270	irqh->bkpt32 = DSBreakpoint;
271}
272
273void DS7Reset(struct ARMCore* cpu) {
274	ARMSetPrivilegeMode(cpu, MODE_IRQ);
275	cpu->gprs[ARM_SP] = DS7_SP_BASE_IRQ;
276	ARMSetPrivilegeMode(cpu, MODE_SUPERVISOR);
277	cpu->gprs[ARM_SP] = DS7_SP_BASE_SVC;
278	ARMSetPrivilegeMode(cpu, MODE_SYSTEM);
279	cpu->gprs[ARM_SP] = DS7_SP_BASE;
280
281	struct DS* ds = (struct DS*) cpu->master;
282	mTimingClear(&ds->ds7.timing);
283	CircleBufferInit(&ds->ds7.fifo, 64);
284	DSMemoryReset(ds);
285	DSDMAReset(&ds->ds7);
286	DS7IOInit(ds);
287
288	struct DSCartridge* header = ds->romVf->map(ds->romVf, sizeof(*header), MAP_READ);
289	if (header) {
290		memcpy(&ds->memory.ram[0x3FF800 >> 2], DS_CHIP_ID, 4);
291		memcpy(&ds->memory.ram[0x3FF804 >> 2], DS_CHIP_ID, 4);
292		memcpy(&ds->memory.ram[0x3FFC00 >> 2], DS_CHIP_ID, 4);
293		memcpy(&ds->memory.ram[0x3FFC04 >> 2], DS_CHIP_ID, 4);
294		memcpy(&ds->memory.ram[0x3FFE00 >> 2], header, 0x170);
295		DS7IOWrite32(ds, DS_REG_ROMCNT_LO, header->busTiming | 0x2700000);
296		// TODO: Error check
297		ds->romVf->seek(ds->romVf, header->arm7Offset, SEEK_SET);
298		uint32_t base = header->arm7Base - DS_BASE_RAM;
299		uint32_t* basePointer = &ds->memory.ram[base >> 2];
300		if (base < DS_SIZE_RAM && base + header->arm7Size <= DS_SIZE_RAM) {
301			ds->romVf->read(ds->romVf, basePointer, header->arm7Size);
302		}
303		cpu->gprs[12] = header->arm7Entry;
304		cpu->gprs[ARM_LR] = header->arm7Entry;
305		cpu->gprs[ARM_PC] = header->arm7Entry;
306		int currentCycles = 0;
307		ARM_WRITE_PC;
308
309		ds->romVf->unmap(ds->romVf, header, sizeof(*header));
310	}
311}
312
313void DS9Reset(struct ARMCore* cpu) {
314	ARMSetPrivilegeMode(cpu, MODE_IRQ);
315	cpu->gprs[ARM_SP] = DS9_SP_BASE_IRQ;
316	ARMSetPrivilegeMode(cpu, MODE_SUPERVISOR);
317	cpu->gprs[ARM_SP] = DS9_SP_BASE_SVC;
318	ARMSetPrivilegeMode(cpu, MODE_SYSTEM);
319	cpu->gprs[ARM_SP] = DS9_SP_BASE;
320
321	struct DS* ds = (struct DS*) cpu->master;
322	mTimingClear(&ds->ds9.timing);
323	CircleBufferInit(&ds->ds9.fifo, 64);
324	DSVideoReset(&ds->video);
325	DSGXReset(&ds->gx);
326	DSDMAReset(&ds->ds9);
327	DS9IOInit(ds);
328
329	ds->activeCpu = cpu;
330	mTimingSchedule(&ds->ds9.timing, &ds->slice, SLICE_CYCLES);
331	ds->cycleDrift = 0;
332	ds->sliceStart = mTimingCurrentTime(&ds->ds9.timing);
333
334	struct DSCartridge* header = ds->romVf->map(ds->romVf, sizeof(*header), MAP_READ);
335	if (header) {
336		// TODO: Error check
337		ds->romVf->seek(ds->romVf, header->arm9Offset, SEEK_SET);
338		uint32_t base = header->arm9Base - DS_BASE_RAM;
339		uint32_t* basePointer = &ds->memory.ram[base >> 2];
340		if (base < DS_SIZE_RAM && base + header->arm9Size <= DS_SIZE_RAM) {
341			ds->romVf->read(ds->romVf, basePointer, header->arm9Size);
342		}
343		cpu->gprs[12] = header->arm9Entry;
344		cpu->gprs[ARM_LR] = header->arm9Entry;
345		cpu->gprs[ARM_PC] = header->arm9Entry;
346		int currentCycles = 0;
347		ARM_WRITE_PC;
348
349		ds->romVf->unmap(ds->romVf, header, sizeof(*header));
350	}
351}
352
353static void DS7ProcessEvents(struct ARMCore* cpu) {
354	struct DS* ds = (struct DS*) cpu->master;
355	DSProcessEvents(&ds->ds7);
356}
357
358static void DS9ProcessEvents(struct ARMCore* cpu) {
359	struct DS* ds = (struct DS*) cpu->master;
360	DSProcessEvents(&ds->ds9);
361}
362
363static void DSProcessEvents(struct DSCommon* dscore) {
364	struct ARMCore* cpu = dscore->cpu;
365	struct DS* ds = dscore->p;
366	if (dscore->springIRQ && !cpu->cpsr.i) {
367		ARMRaiseIRQ(cpu);
368		dscore->springIRQ = 0;
369	}
370
371	int32_t nextEvent = cpu->nextEvent;
372	while (cpu->cycles >= nextEvent) {
373		int32_t cycles = cpu->cycles;
374
375		cpu->cycles = 0;
376		cpu->nextEvent = 0;
377
378#ifndef NDEBUG
379		if (cycles < 0) {
380			mLOG(DS, FATAL, "Negative cycles passed: %i", cycles);
381		}
382#endif
383		nextEvent = cycles;
384		do {
385			nextEvent = mTimingTick(&dscore->timing, nextEvent);
386		} while (ds->cpuBlocked);
387
388		if (ds->earlyExit) {
389			ds->earlyExit = false;
390			break;
391		}
392
393		cpu->nextEvent = nextEvent;
394		if (cpu->halted) {
395			cpu->cycles = nextEvent;
396		}
397#ifndef NDEBUG
398		else if (nextEvent < 0) {
399			mLOG(DS, FATAL, "Negative cycles will pass: %i", nextEvent);
400		}
401#endif
402	}
403}
404
405void DSRunLoop(struct DS* ds) {
406	if (ds->activeCpu == ds->ds9.cpu) {
407		ARMv5RunLoop(ds->ds9.cpu);
408	} else {
409		ARMv4RunLoop(ds->ds7.cpu);
410	}
411}
412
413void DS7Step(struct DS* ds) {
414	int32_t pc = ds->ds7.cpu->gprs[ARM_PC];
415	do {
416		while (ds->activeCpu == ds->ds9.cpu) {
417			ARMv5RunLoop(ds->ds9.cpu);
418		}
419		ARMv4Run(ds->ds7.cpu);
420	} while (ds->ds7.cpu->halted || ds->ds7.cpu->gprs[ARM_PC] == pc);
421}
422
423void DS9Step(struct DS* ds) {
424	int32_t pc = ds->ds9.cpu->gprs[ARM_PC];
425	do {
426		while (ds->activeCpu == ds->ds7.cpu) {
427			ARMv4RunLoop(ds->ds7.cpu);
428		}
429		ARMv5Run(ds->ds9.cpu);
430	} while (ds->ds9.cpu->halted || ds->ds9.cpu->gprs[ARM_PC] == pc);
431}
432
433void DSAttachDebugger(struct DS* ds, struct mDebugger* debugger) {
434	ds->debugger = (struct ARMDebugger*) debugger->platform;
435	ds->ds7.cpu->components[CPU_COMPONENT_DEBUGGER] = &debugger->d;
436	ds->ds9.cpu->components[CPU_COMPONENT_DEBUGGER] = &debugger->d;
437	ARMHotplugAttach(ds->ds7.cpu, CPU_COMPONENT_DEBUGGER);
438	ARMHotplugAttach(ds->ds9.cpu, CPU_COMPONENT_DEBUGGER);
439}
440
441void DSDetachDebugger(struct DS* ds) {
442	ds->debugger = NULL;
443	ARMHotplugDetach(ds->ds7.cpu, CPU_COMPONENT_DEBUGGER);
444	ARMHotplugDetach(ds->ds9.cpu, CPU_COMPONENT_DEBUGGER);
445	ds->ds7.cpu->components[CPU_COMPONENT_DEBUGGER] = NULL;
446	ds->ds9.cpu->components[CPU_COMPONENT_DEBUGGER] = NULL;
447}
448
449bool DSLoadROM(struct DS* ds, struct VFile* vf) {
450	DSUnloadROM(ds);
451	ds->romVf = vf;
452	// TODO: error check
453	return true;
454}
455
456bool DSLoadSave(struct DS* ds, struct VFile* sav) {
457	DSSlot1SPIInit(ds, sav);
458	return true;
459}
460
461bool DSIsROM(struct VFile* vf) {
462	if (vf->seek(vf, DS_ROM_MAGIC_OFFSET, SEEK_SET) < 0) {
463		return false;
464	}
465	uint8_t signature[sizeof(DS_ROM_MAGIC)];
466	if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
467		return false;
468	}
469	return memcmp(signature, DS_ROM_MAGIC, sizeof(signature)) == 0 || memcmp(signature, DS_ROM_MAGIC_2, sizeof(signature)) == 0;
470}
471
472bool DSIsBIOS7(struct VFile* vf) {
473	size_t size = vf->size(vf);
474	void* data = NULL;
475	uint32_t crc;
476	if (size == DS7_SIZE_BIOS) {
477		data = vf->map(vf, size, MAP_READ);
478	}
479	if (!data) {
480		return false;
481	}
482	crc = doCrc32(data, size);
483	vf->unmap(vf, data, size);
484	return crc == DS7_BIOS_CHECKSUM;
485}
486
487bool DSIsBIOS9(struct VFile* vf) {
488	size_t size = vf->size(vf);
489	void* data = NULL;
490	uint32_t crc;
491	if (size == DS9_SIZE_BIOS) {
492		data = vf->map(vf, 0x1000, MAP_READ);
493	} else if (size == 0x1000) {
494		data = vf->map(vf, 0x1000, MAP_READ);
495	}
496	if (!data) {
497		return false;
498	}
499	crc = doCrc32(data, 0x1000);
500	vf->unmap(vf, data, 0x1000);
501	return crc == DS9_BIOS_CHECKSUM;
502}
503
504bool DSIsFirmware(struct VFile* vf) {
505	if (vf->seek(vf, DS_FIRMWARE_MAGIC_OFFSET, SEEK_SET) < 0) {
506		return false;
507	}
508	uint8_t signature[sizeof(DS_FIRMWARE_MAGIC)];
509	if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
510		return false;
511	}
512	return memcmp(signature, DS_FIRMWARE_MAGIC, sizeof(signature)) == 0;
513}
514
515bool DSLoadBIOS(struct DS* ds, struct VFile* vf) {
516	size_t size = vf->size(vf);
517	void* data = NULL;
518	uint32_t crc;
519	if (size == DS7_SIZE_BIOS) {
520		data = vf->map(vf, size, MAP_READ);
521	} else if (size == 0x1000) {
522		data = calloc(DS9_SIZE_BIOS, 1);
523		vf->read(vf, data, size);
524	} else if (size == DS9_SIZE_BIOS) {
525		data = vf->map(vf, size, MAP_READ);
526	} else if (size == DS_SIZE_FIRMWARE) {
527		return DSLoadFirmware(ds, vf);
528	}
529	if (!data) {
530		return false;
531	}
532	crc = doCrc32(data, size);
533	if (crc == DS7_BIOS_CHECKSUM) {
534		ds->bios7Vf = vf;
535		ds->memory.bios7 = data;
536		mLOG(DS, INFO, "Official DS ARM7 BIOS detected");
537	} else if (crc == DS9_BIOS_CHECKSUM) {
538		ds->bios9Vf = vf;
539		ds->memory.bios9 = data;
540		mLOG(DS, INFO, "Official DS ARM9 BIOS detected");
541	} else {
542		mLOG(DS, WARN, "BIOS checksum incorrect");
543		vf->unmap(vf, data, size);
544		return false;
545	}
546	return true;
547}
548
549bool DSLoadFirmware(struct DS* ds, struct VFile* vf) {
550	size_t size = vf->size(vf);
551	void* data = NULL;
552	if (!DSIsFirmware(vf)) {
553		return false;
554	}
555	if (size == DS_SIZE_FIRMWARE) {
556		data = vf->map(vf, size, MAP_WRITE);
557	}
558	if (!data) {
559		return false;
560	}
561	mLOG(DS, INFO, "Found DS firmware");
562	ds->firmwareVf = vf;
563	return true;
564}
565
566void DSGetGameCode(struct DS* ds, char* out) {
567	memset(out, 0, 8);
568	if (!ds->romVf) {
569		return;
570	}
571
572	struct DSCartridge* cart = ds->romVf->map(ds->romVf, sizeof(*cart), MAP_READ);
573	// TODO: TWL-?
574	memcpy(out, "NTR-", 4);
575	memcpy(&out[4], &cart->id, 4);
576	ds->romVf->unmap(ds->romVf, cart, sizeof(*cart));
577}
578
579void DSGetGameTitle(struct DS* ds, char* out) {
580	memset(out, 0, 12);
581	if (!ds->romVf) {
582		return;
583	}
584
585	struct DSCartridge* cart = ds->romVf->map(ds->romVf, sizeof(*cart), MAP_READ);
586	memcpy(out, &cart->title, 12);
587	ds->romVf->unmap(ds->romVf, cart, sizeof(*cart));
588}
589
590void DSHitStub(struct ARMCore* cpu, uint32_t opcode) {
591	struct DS* ds = (struct DS*) cpu->master;
592	if (ds->debugger) {
593		struct mDebuggerEntryInfo info = {
594			.address = _ARMPCAddress(cpu),
595			.opcode = opcode
596		};
597		mDebuggerEnter(ds->debugger->d.p, DEBUGGER_ENTER_ILLEGAL_OP, &info);
598	}
599	// TODO: More sensible category?
600	mLOG(DS, ERROR, "Stub opcode: %08x", opcode);
601}
602
603void DSIllegal(struct ARMCore* cpu, uint32_t opcode) {
604	struct DS* ds = (struct DS*) cpu->master;
605	if ((opcode & 0xFFFF) == (redzoneInstruction & 0xFFFF)) {
606		int currentCycles = 0;
607		if (cpu->executionMode == MODE_THUMB) {
608			cpu->gprs[ARM_PC] -= WORD_SIZE_THUMB * 2;
609			THUMB_WRITE_PC;
610		} else {
611			cpu->gprs[ARM_PC] -= WORD_SIZE_ARM * 2;
612			ARM_WRITE_PC;
613		}
614	} else if (ds->debugger) {
615		struct mDebuggerEntryInfo info = {
616			.address = _ARMPCAddress(cpu),
617			.opcode = opcode
618		};
619		mDebuggerEnter(ds->debugger->d.p, DEBUGGER_ENTER_ILLEGAL_OP, &info);
620	} else {
621		ARMRaiseUndefined(cpu);
622	}
623}
624
625void DSBreakpoint(struct ARMCore* cpu, int immediate) {
626	struct DS* ds = (struct DS*) cpu->master;
627	if (immediate >= CPU_COMPONENT_MAX) {
628		return;
629	}
630	switch (immediate) {
631	case CPU_COMPONENT_DEBUGGER:
632		if (ds->debugger) {
633			struct mDebuggerEntryInfo info = {
634				.address = _ARMPCAddress(cpu)
635			};
636			mDebuggerEnter(ds->debugger->d.p, DEBUGGER_ENTER_BREAKPOINT, &info);
637		}
638		break;
639	default:
640		break;
641	}
642}
643
644void DS7TestIRQ(struct ARMCore* cpu) {
645	struct DS* ds = (struct DS*) cpu->master;
646	if (!ds->memory.io7[DS_REG_IME >> 1]) {
647		return;
648	}
649	uint32_t test = (ds->memory.io7[DS_REG_IE_LO >> 1] & ds->memory.io7[DS_REG_IF_LO >> 1]);
650	test |= (ds->memory.io7[DS_REG_IE_HI >> 1] & ds->memory.io7[DS_REG_IF_HI >> 1]) << 16;
651	if (test) {
652		ds->ds7.springIRQ = test;
653		cpu->nextEvent = cpu->cycles;
654	}
655}
656
657void DS9TestIRQ(struct ARMCore* cpu) {
658	struct DS* ds = (struct DS*) cpu->master;
659	if (!ds->memory.io9[DS_REG_IME >> 1]) {
660		return;
661	}
662	uint32_t test = (ds->memory.io9[DS_REG_IE_LO >> 1] & ds->memory.io9[DS_REG_IF_LO >> 1]);
663	test |= (ds->memory.io9[DS_REG_IE_HI >> 1] & ds->memory.io9[DS_REG_IF_HI >> 1]) << 16;
664	if (test) {
665		ds->ds9.springIRQ = test;
666		cpu->nextEvent = cpu->cycles;
667	}
668}
669
670static void _writeSysControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
671	mLOG(DS, STUB, "CP15 system control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
672}
673
674static void _writeCacheControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
675	mLOG(DS, STUB, "CP15 cache control control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
676	switch (opcode2) {
677	case 0:
678		cpu->cp15.r2.d = value;
679		break;
680	case 1:
681		cpu->cp15.r2.i = value;
682		break;
683	default:
684		mLOG(DS, GAME_ERROR, "CP15 cache control control bad op2: %i", opcode2);
685		break;
686	}
687}
688
689static void _writeWriteBufferControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
690	mLOG(DS, STUB, "CP15 write buffer control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
691	switch (opcode2) {
692	case 0:
693		cpu->cp15.r3.d = value;
694		break;
695	default:
696		mLOG(DS, GAME_ERROR, "CP15 cache control control bad op2: %i", opcode2);
697		break;
698	}
699}
700
701static void _writeAccessControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
702	mLOG(DS, STUB, "CP15 access control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
703}
704
705static void _writeRegionConfiguration(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
706	cpu->cp15.r6.region[crm] = value;
707	uint32_t base = ARMProtectionGetBase(value) << 12;
708	uint32_t size = 2 << ARMProtectionGetSize(value);
709	mLOG(DS, STUB, "CP15 region configuration write: Region: %i, Insn: %i, Base: %08X, Size: %08X", crm, opcode2, base, size);
710}
711
712static void _writeCache(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
713	switch (crm) {
714	case 0:
715		if (opcode2 == 4) {
716			ARMHalt(cpu);
717			return;
718		}
719		break;
720	}
721	mLOG(DS, STUB, "CP15 cache write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
722}
723
724static void _writeTCMControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
725	uint32_t base = ARMTCMControlGetBase(value) << 12;
726	uint32_t size = 512 << ARMTCMControlGetVirtualSize(value);
727	struct DS* ds = (struct DS*) cpu->master;
728	mLOG(DS, DEBUG, "CP15 TCM control write: CRm: %i, Op2: %i, Base: %08X, Size: %08X", crm, opcode2, base, size);
729	switch (opcode2) {
730	case 0:
731		cpu->cp15.r9.d = value;
732		ds->memory.dtcmBase = base;
733		ds->memory.dtcmSize = size;
734		break;
735	case 1:
736		cpu->cp15.r9.i = value;
737		ds->memory.itcmSize = size;
738		break;
739	default:
740		mLOG(DS, GAME_ERROR, "CP15 TCM control bad op2: %i", opcode2);
741		break;
742	}
743}
744
745void DS9WriteCP15(struct ARMCore* cpu, int crn, int crm, int opcode1, int opcode2, uint32_t value) {
746	switch (crn) {
747	default:
748		mLOG(DS, STUB, "CP15 unknown write: CRn: %i, CRm: %i, Op1: %i, Op2: %i, Value: 0x%08X", crn, crm, opcode1, opcode2, value);
749		break;
750	case 0:
751		mLOG(DS, GAME_ERROR, "Attempted to write to read-only cp15 register");
752		ARMRaiseUndefined(cpu);
753		break;
754	case 1:
755		_writeSysControl(cpu, crm, opcode2, value);
756		break;
757	case 2:
758		_writeCacheControl(cpu, crm, opcode2, value);
759		break;
760	case 3:
761		_writeWriteBufferControl(cpu, crm, opcode2, value);
762		break;
763	case 5:
764		_writeAccessControl(cpu, crm, opcode2, value);
765		break;
766	case 6:
767		_writeRegionConfiguration(cpu, crm, opcode2, value);
768		break;
769	case 7:
770		_writeCache(cpu, crm, opcode2, value);
771		break;
772	case 9:
773		_writeTCMControl(cpu, crm, opcode2, value);
774		break;
775	}
776}
777
778static uint32_t _readTCMControl(struct ARMCore* cpu, int crm, int opcode2) {
779	switch (opcode2) {
780	case 0:
781		return cpu->cp15.r9.d;
782	case 1:
783		return cpu->cp15.r9.i;
784	default:
785		mLOG(DS, GAME_ERROR, "CP15 TCM control bad op2: %i", opcode2);
786		return 0;
787	}
788}
789
790uint32_t DS9ReadCP15(struct ARMCore* cpu, int crn, int crm, int opcode1, int opcode2) {
791	switch (crn) {
792	default:
793		mLOG(DS, STUB, "CP15 unknown read: CRn: %i, CRm: %i, Op1: %i, Op2: %i", crn, crm, opcode1, opcode2);
794		return 0;
795	case 9:
796		return _readTCMControl(cpu, crm, opcode2);
797	}
798}
799
800void DSWriteIE(struct ARMCore* cpu, uint16_t* io, uint32_t value) {
801	if (io[DS_REG_IME >> 1] && (value & io[DS_REG_IF_LO >> 1] || (value >> 16) & io[DS_REG_IF_HI >> 1])) {
802		ARMRaiseIRQ(cpu);
803	}
804}
805void DSWriteIME(struct ARMCore* cpu, uint16_t* io, uint16_t value) {
806	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])) {
807		ARMRaiseIRQ(cpu);
808	}
809}
810
811void DSRaiseIRQ(struct ARMCore* cpu, uint16_t* io, enum DSIRQ irq) {
812	if (irq < 16) {
813		io[DS_REG_IF_LO >> 1] |= 1 << irq;
814	} else {
815		io[DS_REG_IF_HI >> 1] |= 1 << (irq - 16);
816	}
817
818	if ((irq < 16 && (io[DS_REG_IE_LO >> 1] & 1 << irq)) || (io[DS_REG_IE_HI >> 1] & (1 << (irq - 16)))) {
819		cpu->halted = 0;
820		if (io[DS_REG_IME >> 1]) {
821			ARMRaiseIRQ(cpu);
822		}
823	}
824}
825
826void DSFrameStarted(struct DS* ds) {
827	struct mCoreCallbacks* callbacks = ds->coreCallbacks;
828	if (callbacks && callbacks->videoFrameStarted) {
829		callbacks->videoFrameStarted(callbacks->context);
830	}
831}
832
833void DSFrameEnded(struct DS* ds) {
834	struct mCoreCallbacks* callbacks = ds->coreCallbacks;
835	if (callbacks && callbacks->videoFrameEnded) {
836		callbacks->videoFrameEnded(callbacks->context);
837	}
838}