all repos — mgba @ 8d8f3148641b63df92719745fc193e34c5dd46c9

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