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 cpu->nextEvent = INT_MAX;
422 nextEvent = 0;
423 do {
424 int32_t cycles = cpu->cycles;
425 cpu->cycles = 0;
426#ifdef USE_DEBUGGERS
427 dscore->timing.globalCycles += cycles;
428#endif
429#ifndef NDEBUG
430 if (cycles < 0) {
431 mLOG(DS, FATAL, "Negative cycles passed: %i", cycles);
432 }
433#endif
434 nextEvent = mTimingTick(&dscore->timing, cycles < nextEvent ? nextEvent : cycles);
435 } while (ds->cpuBlocked && !ds->earlyExit);
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 if (ds->earlyExit) {
447 break;
448 }
449 }
450 ds->earlyExit = false;
451 if (ds->cpuBlocked) {
452 cpu->cycles = cpu->nextEvent;
453 }
454}
455
456void DSRunLoop(struct DS* ds) {
457 if (ds->activeCpu == ds->ds9.cpu) {
458 ARMv5RunLoop(ds->ds9.cpu);
459 } else {
460 ARMv4RunLoop(ds->ds7.cpu);
461 }
462}
463
464void DS7Step(struct DS* ds) {
465 int32_t pc = ds->ds7.cpu->gprs[ARM_PC];
466 do {
467 while (ds->activeCpu == ds->ds9.cpu) {
468 ARMv5RunLoop(ds->ds9.cpu);
469 }
470 ARMv4Run(ds->ds7.cpu);
471 } while (ds->ds7.cpu->halted || ds->ds7.cpu->gprs[ARM_PC] == pc);
472}
473
474void DS9Step(struct DS* ds) {
475 int32_t pc = ds->ds9.cpu->gprs[ARM_PC];
476 do {
477 while (ds->activeCpu == ds->ds7.cpu) {
478 ARMv4RunLoop(ds->ds7.cpu);
479 }
480 ARMv5Run(ds->ds9.cpu);
481 } while (ds->ds9.cpu->halted || ds->ds9.cpu->gprs[ARM_PC] == pc);
482}
483
484void DSAttachDebugger(struct DS* ds, struct mDebugger* debugger) {
485 ds->debugger = (struct ARMDebugger*) debugger->platform;
486 ds->ds7.cpu->components[CPU_COMPONENT_DEBUGGER] = &debugger->d;
487 ds->ds9.cpu->components[CPU_COMPONENT_DEBUGGER] = &debugger->d;
488 ARMHotplugAttach(ds->ds7.cpu, CPU_COMPONENT_DEBUGGER);
489 ARMHotplugAttach(ds->ds9.cpu, CPU_COMPONENT_DEBUGGER);
490}
491
492void DSDetachDebugger(struct DS* ds) {
493 if (ds->debugger) {
494 ARMHotplugDetach(ds->ds7.cpu, CPU_COMPONENT_DEBUGGER);
495 ARMHotplugDetach(ds->ds9.cpu, CPU_COMPONENT_DEBUGGER);
496 }
497 ds->ds7.cpu->components[CPU_COMPONENT_DEBUGGER] = NULL;
498 ds->ds9.cpu->components[CPU_COMPONENT_DEBUGGER] = NULL;
499 ds->debugger = NULL;
500}
501
502bool DSLoadROM(struct DS* ds, struct VFile* vf) {
503 DSUnloadROM(ds);
504 ds->romVf = vf;
505 // TODO: error check
506 return true;
507}
508
509bool DSLoadSave(struct DS* ds, struct VFile* sav) {
510 DSSlot1SPIInit(ds, sav);
511 return sav;
512}
513
514bool DSIsROM(struct VFile* vf) {
515 if (vf->seek(vf, DS_ROM_MAGIC_OFFSET, SEEK_SET) < 0) {
516 return false;
517 }
518 uint8_t signature[sizeof(DS_ROM_MAGIC)];
519 if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
520 return false;
521 }
522 return memcmp(signature, DS_ROM_MAGIC, sizeof(signature)) == 0 || memcmp(signature, DS_ROM_MAGIC_2, sizeof(signature)) == 0;
523}
524
525bool DSIsBIOS7(struct VFile* vf) {
526 size_t size = vf->size(vf);
527 void* data = NULL;
528 uint32_t crc;
529 if (size == DS7_SIZE_BIOS) {
530 data = vf->map(vf, size, MAP_READ);
531 }
532 if (!data) {
533 return false;
534 }
535 crc = doCrc32(data, size);
536 vf->unmap(vf, data, size);
537 return crc == DS7_BIOS_CHECKSUM;
538}
539
540bool DSIsBIOS9(struct VFile* vf) {
541 size_t size = vf->size(vf);
542 void* data = NULL;
543 uint32_t crc;
544 if (size == DS9_SIZE_BIOS) {
545 data = vf->map(vf, 0x1000, MAP_READ);
546 } else if (size == 0x1000) {
547 data = vf->map(vf, 0x1000, MAP_READ);
548 }
549 if (!data) {
550 return false;
551 }
552 crc = doCrc32(data, 0x1000);
553 vf->unmap(vf, data, 0x1000);
554 return crc == DS9_BIOS_CHECKSUM;
555}
556
557bool DSIsFirmware(struct VFile* vf) {
558 if (vf->seek(vf, DS_FIRMWARE_MAGIC_OFFSET, SEEK_SET) < 0) {
559 return false;
560 }
561 uint8_t signature[sizeof(DS_FIRMWARE_MAGIC)];
562 if (vf->read(vf, &signature, sizeof(signature)) != sizeof(signature)) {
563 return false;
564 }
565 return memcmp(signature, DS_FIRMWARE_MAGIC, sizeof(signature)) == 0;
566}
567
568bool DSLoadBIOS(struct DS* ds, struct VFile* vf) {
569 size_t size = vf->size(vf);
570 void* data = NULL;
571 uint32_t crc;
572 if (size == DS7_SIZE_BIOS) {
573 data = vf->map(vf, size, MAP_READ);
574 } else if (size == 0x1000) {
575 data = calloc(DS9_SIZE_BIOS, 1);
576 vf->read(vf, data, size);
577 } else if (size == DS9_SIZE_BIOS) {
578 data = vf->map(vf, size, MAP_READ);
579 } else if (size == DS_SIZE_FIRMWARE) {
580 return DSLoadFirmware(ds, vf);
581 }
582 if (!data) {
583 return false;
584 }
585 crc = doCrc32(data, size);
586 if (crc == DS7_BIOS_CHECKSUM) {
587 if (ds->bios7Vf) {
588 ds->bios7Vf->unmap(ds->bios7Vf, ds->memory.bios7, DS7_SIZE_BIOS);
589 ds->bios7Vf->close(ds->bios7Vf);
590 }
591 ds->bios7Vf = vf;
592 ds->memory.bios7 = data;
593 mLOG(DS, INFO, "Official DS ARM7 BIOS detected");
594 } else if (crc == DS9_BIOS_CHECKSUM) {
595 if (ds->bios9Vf) {
596 if (ds->bios9Vf->size(ds->bios9Vf) == 0x1000) {
597 free(ds->memory.bios9);
598 } else {
599 ds->bios9Vf->unmap(ds->bios9Vf, ds->memory.bios9, DS9_SIZE_BIOS);
600 }
601 ds->bios9Vf->close(ds->bios9Vf);
602 }
603 ds->bios9Vf = vf;
604 ds->memory.bios9 = data;
605 mLOG(DS, INFO, "Official DS ARM9 BIOS detected");
606 } else {
607 mLOG(DS, WARN, "BIOS checksum incorrect");
608 if (size == 0x1000) {
609 free(data);
610 } else {
611 vf->unmap(vf, data, size);
612 }
613 return false;
614 }
615 return true;
616}
617
618bool DSLoadFirmware(struct DS* ds, struct VFile* vf) {
619 size_t size = vf->size(vf);
620 if (!DSIsFirmware(vf)) {
621 return false;
622 }
623 if (size != DS_SIZE_FIRMWARE) {
624 return false;
625 }
626 mLOG(DS, INFO, "Found DS firmware");
627 if (ds->firmwareVf) {
628 ds->firmwareVf->close(ds->firmwareVf);
629 }
630 ds->firmwareVf = vf;
631 return true;
632}
633
634void DSGetGameCode(struct DS* ds, char* out) {
635 memset(out, 0, 8);
636 if (!ds->romVf) {
637 return;
638 }
639
640 struct DSCartridge* cart = ds->romVf->map(ds->romVf, sizeof(*cart), MAP_READ);
641 // TODO: TWL-?
642 memcpy(out, "NTR-", 4);
643 memcpy(&out[4], &cart->id, 4);
644 ds->romVf->unmap(ds->romVf, cart, sizeof(*cart));
645}
646
647void DSGetGameTitle(struct DS* ds, char* out) {
648 memset(out, 0, 12);
649 if (!ds->romVf) {
650 return;
651 }
652
653 struct DSCartridge* cart = ds->romVf->map(ds->romVf, sizeof(*cart), MAP_READ);
654 memcpy(out, &cart->title, 12);
655 ds->romVf->unmap(ds->romVf, cart, sizeof(*cart));
656}
657
658void DSHitStub(struct ARMCore* cpu, uint32_t opcode) {
659 struct DS* ds = (struct DS*) cpu->master;
660#ifdef USE_DEBUGGERS
661 if (ds->debugger) {
662 struct mDebuggerEntryInfo info = {
663 .address = _ARMPCAddress(cpu),
664 .type.bp.opcode = opcode
665 };
666 mDebuggerEnter(ds->debugger->d.p, DEBUGGER_ENTER_ILLEGAL_OP, &info);
667 }
668#endif
669 // TODO: More sensible category?
670 mLOG(DS, ERROR, "Stub opcode: %08x", opcode);
671}
672
673void DSIllegal(struct ARMCore* cpu, uint32_t opcode) {
674 struct DS* ds = (struct DS*) cpu->master;
675 if ((opcode & 0xFFFF) == (redzoneInstruction & 0xFFFF)) {
676 int currentCycles = 0;
677 if (cpu->executionMode == MODE_THUMB) {
678 cpu->gprs[ARM_PC] -= WORD_SIZE_THUMB * 2;
679 ThumbWritePC(cpu);
680 } else {
681 cpu->gprs[ARM_PC] -= WORD_SIZE_ARM * 2;
682 ARMWritePC(cpu);
683 }
684#ifdef USE_DEBUGGERS
685 } else if (ds->debugger) {
686 struct mDebuggerEntryInfo info = {
687 .address = _ARMPCAddress(cpu),
688 .type.bp.opcode = opcode
689 };
690 mDebuggerEnter(ds->debugger->d.p, DEBUGGER_ENTER_ILLEGAL_OP, &info);
691#endif
692 } else {
693 ARMRaiseUndefined(cpu);
694 }
695}
696
697void DSBreakpoint(struct ARMCore* cpu, int immediate) {
698 struct DS* ds = (struct DS*) cpu->master;
699 if (immediate >= CPU_COMPONENT_MAX) {
700 return;
701 }
702 switch (immediate) {
703#ifdef USE_DEBUGGERS
704 case CPU_COMPONENT_DEBUGGER:
705 if (ds->debugger) {
706 struct mDebuggerEntryInfo info = {
707 .address = _ARMPCAddress(cpu)
708 };
709 mDebuggerEnter(ds->debugger->d.p, DEBUGGER_ENTER_BREAKPOINT, &info);
710 }
711 break;
712#endif
713 default:
714 break;
715 }
716}
717
718void DS7TestIRQ(struct ARMCore* cpu) {
719 struct DS* ds = (struct DS*) cpu->master;
720 if (!ds->memory.io7[DS_REG_IME >> 1]) {
721 return;
722 }
723 uint32_t test = (ds->memory.io7[DS_REG_IE_LO >> 1] & ds->memory.io7[DS_REG_IF_LO >> 1]);
724 test |= (ds->memory.io7[DS_REG_IE_HI >> 1] & ds->memory.io7[DS_REG_IF_HI >> 1]) << 16;
725 if (test) {
726 ds->ds7.springIRQ = test;
727 cpu->nextEvent = cpu->cycles;
728 }
729}
730
731void DS9TestIRQ(struct ARMCore* cpu) {
732 struct DS* ds = (struct DS*) cpu->master;
733 if (!ds->memory.io9[DS_REG_IME >> 1]) {
734 return;
735 }
736 uint32_t test = (ds->memory.io9[DS_REG_IE_LO >> 1] & ds->memory.io9[DS_REG_IF_LO >> 1]);
737 test |= (ds->memory.io9[DS_REG_IE_HI >> 1] & ds->memory.io9[DS_REG_IF_HI >> 1]) << 16;
738 if (test) {
739 ds->ds9.springIRQ = test;
740 cpu->nextEvent = cpu->cycles;
741 }
742}
743
744static void _writeSysControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
745 mLOG(DS, STUB, "CP15 system control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
746}
747
748static void _writeCacheControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
749 mLOG(DS, STUB, "CP15 cache control control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
750 switch (opcode2) {
751 case 0:
752 cpu->cp15.r2.d = value;
753 break;
754 case 1:
755 cpu->cp15.r2.i = 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 _writeWriteBufferControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
764 mLOG(DS, STUB, "CP15 write buffer control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
765 switch (opcode2) {
766 case 0:
767 cpu->cp15.r3.d = value;
768 break;
769 default:
770 mLOG(DS, GAME_ERROR, "CP15 cache control control bad op2: %i", opcode2);
771 break;
772 }
773}
774
775static void _writeAccessControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
776 mLOG(DS, STUB, "CP15 access control write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
777}
778
779static void _writeRegionConfiguration(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
780 cpu->cp15.r6.region[crm] = value;
781 uint32_t base = ARMProtectionGetBase(value) << 12;
782 uint32_t size = 2 << ARMProtectionGetSize(value);
783 mLOG(DS, STUB, "CP15 region configuration write: Region: %i, Insn: %i, Base: %08X, Size: %08X", crm, opcode2, base, size);
784}
785
786static void _writeCache(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
787 switch (crm) {
788 case 0:
789 if (opcode2 == 4) {
790 ARMHalt(cpu);
791 return;
792 }
793 break;
794 }
795 mLOG(DS, STUB, "CP15 cache write: CRm: %i, Op2: %i, Value: 0x%08X", crm, opcode2, value);
796}
797
798static void _writeTCMControl(struct ARMCore* cpu, int crm, int opcode2, uint32_t value) {
799 uint32_t base = ARMTCMControlGetBase(value) << 12;
800 uint32_t size = 512 << ARMTCMControlGetVirtualSize(value);
801 struct DS* ds = (struct DS*) cpu->master;
802 mLOG(DS, DEBUG, "CP15 TCM control write: CRm: %i, Op2: %i, Base: %08X, Size: %08X", crm, opcode2, base, size);
803 switch (opcode2) {
804 case 0:
805 cpu->cp15.r9.d = value;
806 ds->memory.dtcmBase = base;
807 ds->memory.dtcmSize = size;
808 break;
809 case 1:
810 cpu->cp15.r9.i = value;
811 ds->memory.itcmSize = size;
812 break;
813 default:
814 mLOG(DS, GAME_ERROR, "CP15 TCM control bad op2: %i", opcode2);
815 break;
816 }
817}
818
819void DS9WriteCP15(struct ARMCore* cpu, int crn, int crm, int opcode1, int opcode2, uint32_t value) {
820 switch (crn) {
821 default:
822 mLOG(DS, STUB, "CP15 unknown write: CRn: %i, CRm: %i, Op1: %i, Op2: %i, Value: 0x%08X", crn, crm, opcode1, opcode2, value);
823 break;
824 case 0:
825 mLOG(DS, GAME_ERROR, "Attempted to write to read-only cp15 register");
826 ARMRaiseUndefined(cpu);
827 break;
828 case 1:
829 _writeSysControl(cpu, crm, opcode2, value);
830 break;
831 case 2:
832 _writeCacheControl(cpu, crm, opcode2, value);
833 break;
834 case 3:
835 _writeWriteBufferControl(cpu, crm, opcode2, value);
836 break;
837 case 5:
838 _writeAccessControl(cpu, crm, opcode2, value);
839 break;
840 case 6:
841 _writeRegionConfiguration(cpu, crm, opcode2, value);
842 break;
843 case 7:
844 _writeCache(cpu, crm, opcode2, value);
845 break;
846 case 9:
847 _writeTCMControl(cpu, crm, opcode2, value);
848 break;
849 }
850}
851
852static uint32_t _readTCMControl(struct ARMCore* cpu, int crm, int opcode2) {
853 switch (opcode2) {
854 case 0:
855 return cpu->cp15.r9.d;
856 case 1:
857 return cpu->cp15.r9.i;
858 default:
859 mLOG(DS, GAME_ERROR, "CP15 TCM control bad op2: %i", opcode2);
860 return 0;
861 }
862}
863
864uint32_t DS9ReadCP15(struct ARMCore* cpu, int crn, int crm, int opcode1, int opcode2) {
865 switch (crn) {
866 default:
867 mLOG(DS, STUB, "CP15 unknown read: CRn: %i, CRm: %i, Op1: %i, Op2: %i", crn, crm, opcode1, opcode2);
868 return 0;
869 case 9:
870 return _readTCMControl(cpu, crm, opcode2);
871 }
872}
873
874void DSWriteIE(struct ARMCore* cpu, uint16_t* io, uint32_t value) {
875 if (io[DS_REG_IME >> 1] && (value & io[DS_REG_IF_LO >> 1] || (value >> 16) & io[DS_REG_IF_HI >> 1])) {
876 ARMRaiseIRQ(cpu);
877 }
878}
879void DSWriteIME(struct ARMCore* cpu, uint16_t* io, uint16_t value) {
880 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])) {
881 ARMRaiseIRQ(cpu);
882 }
883}
884
885void DSRaiseIRQ(struct ARMCore* cpu, uint16_t* io, enum DSIRQ irq) {
886 if (irq < 16) {
887 io[DS_REG_IF_LO >> 1] |= 1 << irq;
888 } else {
889 io[DS_REG_IF_HI >> 1] |= 1 << (irq - 16);
890 }
891
892 if ((irq < 16 && (io[DS_REG_IE_LO >> 1] & 1 << irq)) || (io[DS_REG_IE_HI >> 1] & (1 << (irq - 16)))) {
893 cpu->halted = 0;
894 if (io[DS_REG_IME >> 1]) {
895 ARMRaiseIRQ(cpu);
896 }
897 }
898}
899
900void DSFrameStarted(struct DS* ds) {
901 size_t c;
902 for (c = 0; c < mCoreCallbacksListSize(&ds->coreCallbacks); ++c) {
903 struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&ds->coreCallbacks, c);
904 if (callbacks->videoFrameStarted) {
905 callbacks->videoFrameStarted(callbacks->context);
906 }
907 }
908}
909
910void DSFrameEnded(struct DS* ds) {
911 size_t c;
912 for (c = 0; c < mCoreCallbacksListSize(&ds->coreCallbacks); ++c) {
913 struct mCoreCallbacks* callbacks = mCoreCallbacksListGetPointer(&ds->coreCallbacks, c);
914 if (callbacks->videoFrameEnded) {
915 callbacks->videoFrameEnded(callbacks->context);
916 }
917 }
918
919 if (ds->stream && ds->stream->postVideoFrame) {
920 const color_t* pixels;
921 size_t stride;
922 ds->video.renderer->getPixels(ds->video.renderer, &stride, (const void**) &pixels);
923 ds->stream->postVideoFrame(ds->stream, pixels, stride);
924 }
925}
926
927uint16_t DSWriteRTC(struct DS* ds, DSRegisterRTC value) {
928 switch (ds->rtc.transferStep) {
929 case 0:
930 if ((value & 6) == 2) {
931 ds->rtc.transferStep = 1;
932 }
933 break;
934 case 1:
935 if ((value & 6) == 6) {
936 ds->rtc.transferStep = 2;
937 }
938 break;
939 case 2:
940 if (!DSRegisterRTCIsClock(value)) {
941 if (DSRegisterRTCIsDataDirection(value)) {
942 ds->rtc.bits &= ~(1 << ds->rtc.bitsRead);
943 ds->rtc.bits |= DSRegisterRTCGetData(value) << ds->rtc.bitsRead;
944 } else {
945 value = DSRegisterRTCSetData(value, GBARTCOutput(&ds->rtc));
946 }
947 } else {
948 if (DSRegisterRTCIsSelect(value)) {
949 // GPIO direction should always != reading
950 if (DSRegisterRTCIsDataDirection(value)) {
951 if (RTCCommandDataIsReading(ds->rtc.command)) {
952 mLOG(DS, GAME_ERROR, "Attempting to write to RTC while in read mode");
953 }
954 ++ds->rtc.bitsRead;
955 if (ds->rtc.bitsRead == 8) {
956 GBARTCProcessByte(&ds->rtc, ds->rtcSource);
957 }
958 } else {
959 value = DSRegisterRTCSetData(value, GBARTCOutput(&ds->rtc));
960 ++ds->rtc.bitsRead;
961 if (ds->rtc.bitsRead == 8) {
962 --ds->rtc.bytesRemaining;
963 if (ds->rtc.bytesRemaining <= 0) {
964 ds->rtc.commandActive = 0;
965 ds->rtc.command = RTCCommandDataClearReading(ds->rtc.command);
966 }
967 ds->rtc.bitsRead = 0;
968 }
969 }
970 } else {
971 ds->rtc.bitsRead = 0;
972 ds->rtc.bytesRemaining = 0;
973 ds->rtc.commandActive = 0;
974 ds->rtc.command = RTCCommandDataClearReading(ds->rtc.command);
975 ds->rtc.transferStep = 0;
976 }
977 }
978 break;
979 }
980 return value;
981}