all repos — mgba @ 14e8b1230794f9b0018e990e2802954502a928e1

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