all repos — mgba @ 60fb32b71f7716a1be7ac88f58db82bb06f1c927

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