all repos — mgba @ 4fd170ac38a9c312f3dd1d0dd912d2c761f60fdb

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