all repos — mgba @ c1147c9616c846d10673ce5fd37aa7e3ad7b068e

mGBA Game Boy Advance Emulator

src/gba/bios.c (view raw)

  1/* Copyright (c) 2013-2015 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/gba/bios.h>
  7
  8#include <mgba/internal/arm/isa-inlines.h>
  9#include <mgba/internal/arm/macros.h>
 10#include <mgba/internal/gba/gba.h>
 11#include <mgba/internal/gba/io.h>
 12#include <mgba/internal/gba/memory.h>
 13#include <mgba-util/math.h>
 14
 15const uint32_t GBA_BIOS_CHECKSUM = 0xBAAE187F;
 16const uint32_t GBA_DS_BIOS_CHECKSUM = 0xBAAE1880;
 17
 18mLOG_DEFINE_CATEGORY(GBA_BIOS, "GBA BIOS", "gba.bios");
 19
 20static void _unLz77(struct GBA* gba, int width);
 21static void _unHuffman(struct GBA* gba);
 22static void _unRl(struct GBA* gba, int width);
 23static void _unFilter(struct GBA* gba, int inwidth, int outwidth);
 24static void _unBitPack(struct GBA* gba);
 25
 26static int _mulWait(int32_t r) {
 27	if ((r & 0xFFFFFF00) == 0xFFFFFF00 || !(r & 0xFFFFFF00)) {
 28		return 1;
 29	} else if ((r & 0xFFFF0000) == 0xFFFF0000 || !(r & 0xFFFF0000)) {
 30		return 2;
 31	} else if ((r & 0xFF000000) == 0xFF000000 || !(r & 0xFF000000)) {
 32		return 3;
 33	} else {
 34		return 4;
 35	}
 36}
 37
 38static void _SoftReset(struct GBA* gba) {
 39	struct ARMCore* cpu = gba->cpu;
 40	ARMSetPrivilegeMode(cpu, MODE_IRQ);
 41	cpu->spsr.packed = 0;
 42	cpu->gprs[ARM_LR] = 0;
 43	cpu->gprs[ARM_SP] = SP_BASE_IRQ;
 44	ARMSetPrivilegeMode(cpu, MODE_SUPERVISOR);
 45	cpu->spsr.packed = 0;
 46	cpu->gprs[ARM_LR] = 0;
 47	cpu->gprs[ARM_SP] = SP_BASE_SUPERVISOR;
 48	ARMSetPrivilegeMode(cpu, MODE_SYSTEM);
 49	cpu->gprs[ARM_LR] = 0;
 50	cpu->gprs[ARM_SP] = SP_BASE_SYSTEM;
 51	int8_t flag = ((int8_t*) gba->memory.iwram)[0x7FFA];
 52	memset(((int8_t*) gba->memory.iwram) + SIZE_WORKING_IRAM - 0x200, 0, 0x200);
 53	if (flag) {
 54		cpu->gprs[ARM_PC] = BASE_WORKING_RAM;
 55	} else {
 56		cpu->gprs[ARM_PC] = BASE_CART0;
 57	}
 58	_ARMSetMode(cpu, MODE_ARM);
 59	ARMWritePC(cpu);
 60}
 61
 62static void _RegisterRamReset(struct GBA* gba) {
 63	uint32_t registers = gba->cpu->gprs[0];
 64	struct ARMCore* cpu = gba->cpu;
 65	cpu->memory.store16(cpu, BASE_IO | REG_DISPCNT, 0x0080, 0);
 66	if (registers & 0x01) {
 67		memset(gba->memory.wram, 0, SIZE_WORKING_RAM);
 68	}
 69	if (registers & 0x02) {
 70		memset(gba->memory.iwram, 0, SIZE_WORKING_IRAM - 0x200);
 71	}
 72	if (registers & 0x04) {
 73		memset(gba->video.palette, 0, SIZE_PALETTE_RAM);
 74	}
 75	if (registers & 0x08) {
 76		memset(gba->video.vram, 0, SIZE_VRAM);
 77	}
 78	if (registers & 0x10) {
 79		memset(gba->video.oam.raw, 0, SIZE_OAM);
 80	}
 81	if (registers & 0x20) {
 82		cpu->memory.store16(cpu, BASE_IO | REG_SIOCNT, 0x0000, 0);
 83		cpu->memory.store16(cpu, BASE_IO | REG_RCNT, RCNT_INITIAL, 0);
 84		cpu->memory.store16(cpu, BASE_IO | REG_SIOMLT_SEND, 0, 0);
 85		cpu->memory.store16(cpu, BASE_IO | REG_JOYCNT, 0, 0);
 86		cpu->memory.store32(cpu, BASE_IO | REG_JOY_RECV_LO, 0, 0);
 87		cpu->memory.store32(cpu, BASE_IO | REG_JOY_TRANS_LO, 0, 0);
 88	}
 89	if (registers & 0x40) {
 90		cpu->memory.store16(cpu, BASE_IO | REG_SOUND1CNT_LO, 0, 0);
 91		cpu->memory.store16(cpu, BASE_IO | REG_SOUND1CNT_HI, 0, 0);
 92		cpu->memory.store16(cpu, BASE_IO | REG_SOUND1CNT_X, 0, 0);
 93		cpu->memory.store16(cpu, BASE_IO | REG_SOUND2CNT_LO, 0, 0);
 94		cpu->memory.store16(cpu, BASE_IO | REG_SOUND2CNT_HI, 0, 0);
 95		cpu->memory.store16(cpu, BASE_IO | REG_SOUND3CNT_LO, 0, 0);
 96		cpu->memory.store16(cpu, BASE_IO | REG_SOUND3CNT_HI, 0, 0);
 97		cpu->memory.store16(cpu, BASE_IO | REG_SOUND3CNT_X, 0, 0);
 98		cpu->memory.store16(cpu, BASE_IO | REG_SOUND4CNT_LO, 0, 0);
 99		cpu->memory.store16(cpu, BASE_IO | REG_SOUND4CNT_HI, 0, 0);
100		cpu->memory.store16(cpu, BASE_IO | REG_SOUNDCNT_LO, 0, 0);
101		cpu->memory.store16(cpu, BASE_IO | REG_SOUNDCNT_HI, 0, 0);
102		cpu->memory.store16(cpu, BASE_IO | REG_SOUNDCNT_X, 0, 0);
103		cpu->memory.store16(cpu, BASE_IO | REG_SOUNDBIAS, 0x200, 0);
104		memset(gba->audio.psg.ch3.wavedata32, 0, sizeof(gba->audio.psg.ch3.wavedata32));
105	}
106	if (registers & 0x80) {
107		cpu->memory.store16(cpu, BASE_IO | REG_DISPSTAT, 0, 0);
108		cpu->memory.store16(cpu, BASE_IO | REG_VCOUNT, 0, 0);
109		cpu->memory.store16(cpu, BASE_IO | REG_BG0CNT, 0, 0);
110		cpu->memory.store16(cpu, BASE_IO | REG_BG1CNT, 0, 0);
111		cpu->memory.store16(cpu, BASE_IO | REG_BG2CNT, 0, 0);
112		cpu->memory.store16(cpu, BASE_IO | REG_BG3CNT, 0, 0);
113		cpu->memory.store16(cpu, BASE_IO | REG_BG0HOFS, 0, 0);
114		cpu->memory.store16(cpu, BASE_IO | REG_BG0VOFS, 0, 0);
115		cpu->memory.store16(cpu, BASE_IO | REG_BG1HOFS, 0, 0);
116		cpu->memory.store16(cpu, BASE_IO | REG_BG1VOFS, 0, 0);
117		cpu->memory.store16(cpu, BASE_IO | REG_BG2HOFS, 0, 0);
118		cpu->memory.store16(cpu, BASE_IO | REG_BG2VOFS, 0, 0);
119		cpu->memory.store16(cpu, BASE_IO | REG_BG3HOFS, 0, 0);
120		cpu->memory.store16(cpu, BASE_IO | REG_BG3VOFS, 0, 0);
121		cpu->memory.store16(cpu, BASE_IO | REG_BG2PA, 0x100, 0);
122		cpu->memory.store16(cpu, BASE_IO | REG_BG2PB, 0, 0);
123		cpu->memory.store16(cpu, BASE_IO | REG_BG2PC, 0, 0);
124		cpu->memory.store16(cpu, BASE_IO | REG_BG2PD, 0x100, 0);
125		cpu->memory.store32(cpu, BASE_IO | REG_BG2X_LO, 0, 0);
126		cpu->memory.store32(cpu, BASE_IO | REG_BG2Y_LO, 0, 0);
127		cpu->memory.store16(cpu, BASE_IO | REG_BG3PA, 0x100, 0);
128		cpu->memory.store16(cpu, BASE_IO | REG_BG3PB, 0, 0);
129		cpu->memory.store16(cpu, BASE_IO | REG_BG3PC, 0, 0);
130		cpu->memory.store16(cpu, BASE_IO | REG_BG3PD, 0x100, 0);
131		cpu->memory.store32(cpu, BASE_IO | REG_BG3X_LO, 0, 0);
132		cpu->memory.store32(cpu, BASE_IO | REG_BG3Y_LO, 0, 0);
133		cpu->memory.store16(cpu, BASE_IO | REG_WIN0H, 0, 0);
134		cpu->memory.store16(cpu, BASE_IO | REG_WIN1H, 0, 0);
135		cpu->memory.store16(cpu, BASE_IO | REG_WIN0V, 0, 0);
136		cpu->memory.store16(cpu, BASE_IO | REG_WIN1V, 0, 0);
137		cpu->memory.store16(cpu, BASE_IO | REG_WININ, 0, 0);
138		cpu->memory.store16(cpu, BASE_IO | REG_WINOUT, 0, 0);
139		cpu->memory.store16(cpu, BASE_IO | REG_MOSAIC, 0, 0);
140		cpu->memory.store16(cpu, BASE_IO | REG_BLDCNT, 0, 0);
141		cpu->memory.store16(cpu, BASE_IO | REG_BLDALPHA, 0, 0);
142		cpu->memory.store16(cpu, BASE_IO | REG_BLDY, 0, 0);
143		cpu->memory.store16(cpu, BASE_IO | REG_DMA0SAD_LO, 0, 0);
144		cpu->memory.store16(cpu, BASE_IO | REG_DMA0SAD_HI, 0, 0);
145		cpu->memory.store16(cpu, BASE_IO | REG_DMA0DAD_LO, 0, 0);
146		cpu->memory.store16(cpu, BASE_IO | REG_DMA0DAD_HI, 0, 0);
147		cpu->memory.store16(cpu, BASE_IO | REG_DMA0CNT_LO, 0, 0);
148		cpu->memory.store16(cpu, BASE_IO | REG_DMA0CNT_HI, 0, 0);
149		cpu->memory.store16(cpu, BASE_IO | REG_DMA1SAD_LO, 0, 0);
150		cpu->memory.store16(cpu, BASE_IO | REG_DMA1SAD_HI, 0, 0);
151		cpu->memory.store16(cpu, BASE_IO | REG_DMA1DAD_LO, 0, 0);
152		cpu->memory.store16(cpu, BASE_IO | REG_DMA1DAD_HI, 0, 0);
153		cpu->memory.store16(cpu, BASE_IO | REG_DMA1CNT_LO, 0, 0);
154		cpu->memory.store16(cpu, BASE_IO | REG_DMA1CNT_HI, 0, 0);
155		cpu->memory.store16(cpu, BASE_IO | REG_DMA2SAD_LO, 0, 0);
156		cpu->memory.store16(cpu, BASE_IO | REG_DMA2SAD_HI, 0, 0);
157		cpu->memory.store16(cpu, BASE_IO | REG_DMA2DAD_LO, 0, 0);
158		cpu->memory.store16(cpu, BASE_IO | REG_DMA2DAD_HI, 0, 0);
159		cpu->memory.store16(cpu, BASE_IO | REG_DMA2CNT_LO, 0, 0);
160		cpu->memory.store16(cpu, BASE_IO | REG_DMA2CNT_HI, 0, 0);
161		cpu->memory.store16(cpu, BASE_IO | REG_DMA3SAD_LO, 0, 0);
162		cpu->memory.store16(cpu, BASE_IO | REG_DMA3SAD_HI, 0, 0);
163		cpu->memory.store16(cpu, BASE_IO | REG_DMA3DAD_LO, 0, 0);
164		cpu->memory.store16(cpu, BASE_IO | REG_DMA3DAD_HI, 0, 0);
165		cpu->memory.store16(cpu, BASE_IO | REG_DMA3CNT_LO, 0, 0);
166		cpu->memory.store16(cpu, BASE_IO | REG_DMA3CNT_HI, 0, 0);
167		cpu->memory.store16(cpu, BASE_IO | REG_TM0CNT_LO, 0, 0);
168		cpu->memory.store16(cpu, BASE_IO | REG_TM0CNT_HI, 0, 0);
169		cpu->memory.store16(cpu, BASE_IO | REG_TM1CNT_LO, 0, 0);
170		cpu->memory.store16(cpu, BASE_IO | REG_TM1CNT_HI, 0, 0);
171		cpu->memory.store16(cpu, BASE_IO | REG_TM2CNT_LO, 0, 0);
172		cpu->memory.store16(cpu, BASE_IO | REG_TM2CNT_HI, 0, 0);
173		cpu->memory.store16(cpu, BASE_IO | REG_TM3CNT_LO, 0, 0);
174		cpu->memory.store16(cpu, BASE_IO | REG_TM3CNT_HI, 0, 0);
175		cpu->memory.store16(cpu, BASE_IO | REG_IE, 0, 0);
176		cpu->memory.store16(cpu, BASE_IO | REG_IF, 0xFFFF, 0);
177		cpu->memory.store16(cpu, BASE_IO | REG_WAITCNT, 0, 0);
178		cpu->memory.store16(cpu, BASE_IO | REG_IME, 0, 0);
179	}
180	if (registers & 0x9C) {
181		gba->video.renderer->reset(gba->video.renderer);
182		gba->video.renderer->writeVideoRegister(gba->video.renderer, REG_DISPCNT, gba->memory.io[REG_DISPCNT >> 1]);
183		int i;
184		for (i = REG_BG0CNT; i < REG_SOUND1CNT_LO; i += 2) {
185			gba->video.renderer->writeVideoRegister(gba->video.renderer, i, gba->memory.io[i >> 1]);
186		}
187	}
188}
189
190static void _BgAffineSet(struct GBA* gba) {
191	struct ARMCore* cpu = gba->cpu;
192	int i = cpu->gprs[2];
193	float ox, oy;
194	float cx, cy;
195	float sx, sy;
196	float theta;
197	int offset = cpu->gprs[0];
198	int destination = cpu->gprs[1];
199	float a, b, c, d;
200	float rx, ry;
201	while (i--) {
202		// [ sx   0  0 ]   [ cos(theta)  -sin(theta)  0 ]   [ 1  0  cx - ox ]   [ A B rx ]
203		// [  0  sy  0 ] * [ sin(theta)   cos(theta)  0 ] * [ 0  1  cy - oy ] = [ C D ry ]
204		// [  0   0  1 ]   [     0            0       1 ]   [ 0  0     1    ]   [ 0 0  1 ]
205		ox = (int32_t) cpu->memory.load32(cpu, offset, 0) / 256.f;
206		oy = (int32_t) cpu->memory.load32(cpu, offset + 4, 0) / 256.f;
207		cx = (int16_t) cpu->memory.load16(cpu, offset + 8, 0);
208		cy = (int16_t) cpu->memory.load16(cpu, offset + 10, 0);
209		sx = (int16_t) cpu->memory.load16(cpu, offset + 12, 0) / 256.f;
210		sy = (int16_t) cpu->memory.load16(cpu, offset + 14, 0) / 256.f;
211		theta = (cpu->memory.load16(cpu, offset + 16, 0) >> 8) / 128.f * M_PI;
212		offset += 20;
213		// Rotation
214		a = d = cosf(theta);
215		b = c = sinf(theta);
216		// Scale
217		a *= sx;
218		b *= -sx;
219		c *= sy;
220		d *= sy;
221		// Translate
222		rx = ox - (a * cx + b * cy);
223		ry = oy - (c * cx + d * cy);
224		cpu->memory.store16(cpu, destination, a * 256, 0);
225		cpu->memory.store16(cpu, destination + 2, b * 256, 0);
226		cpu->memory.store16(cpu, destination + 4, c * 256, 0);
227		cpu->memory.store16(cpu, destination + 6, d * 256, 0);
228		cpu->memory.store32(cpu, destination + 8, rx * 256, 0);
229		cpu->memory.store32(cpu, destination + 12, ry * 256, 0);
230		destination += 16;
231	}
232}
233
234static void _ObjAffineSet(struct GBA* gba) {
235	struct ARMCore* cpu = gba->cpu;
236	int i = cpu->gprs[2];
237	float sx, sy;
238	float theta;
239	int offset = cpu->gprs[0];
240	int destination = cpu->gprs[1];
241	int diff = cpu->gprs[3];
242	float a, b, c, d;
243	while (i--) {
244		// [ sx   0 ]   [ cos(theta)  -sin(theta) ]   [ A B ]
245		// [  0  sy ] * [ sin(theta)   cos(theta) ] = [ C D ]
246		sx = (int16_t) cpu->memory.load16(cpu, offset, 0) / 256.f;
247		sy = (int16_t) cpu->memory.load16(cpu, offset + 2, 0) / 256.f;
248		theta = (cpu->memory.load16(cpu, offset + 4, 0) >> 8) / 128.f * M_PI;
249		offset += 8;
250		// Rotation
251		a = d = cosf(theta);
252		b = c = sinf(theta);
253		// Scale
254		a *= sx;
255		b *= -sx;
256		c *= sy;
257		d *= sy;
258		cpu->memory.store16(cpu, destination, a * 256, 0);
259		cpu->memory.store16(cpu, destination + diff, b * 256, 0);
260		cpu->memory.store16(cpu, destination + diff * 2, c * 256, 0);
261		cpu->memory.store16(cpu, destination + diff * 3, d * 256, 0);
262		destination += diff * 4;
263	}
264}
265
266static void _MidiKey2Freq(struct GBA* gba) {
267	struct ARMCore* cpu = gba->cpu;
268
269	int oldRegion = gba->memory.activeRegion;
270	gba->memory.activeRegion = REGION_BIOS;
271	uint32_t key = cpu->memory.load32(cpu, cpu->gprs[0] + 4, 0);
272	gba->memory.activeRegion = oldRegion;
273
274	cpu->gprs[0] = key / exp2f((180.f - cpu->gprs[1] - cpu->gprs[2] / 256.f) / 12.f);
275}
276
277static void _Div(struct GBA* gba, int32_t num, int32_t denom) {
278	struct ARMCore* cpu = gba->cpu;
279	if (denom == 0) {
280		if (num == 0 || num == -1 || num == 1) {
281			mLOG(GBA_BIOS, GAME_ERROR, "Attempting to divide %i by zero!", num);
282		} else {
283			mLOG(GBA_BIOS, FATAL, "Attempting to divide %i by zero!", num);
284		}
285		// If abs(num) > 1, this should hang, but that would be painful to
286		// emulate in HLE, and no game will get into a state under normal
287		// operation where it hangs...
288		cpu->gprs[0] = (num < 0) ? -1 : 1;
289		cpu->gprs[1] = num;
290		cpu->gprs[3] = 1;
291	} else if (denom == -1 && num == INT32_MIN) {
292		mLOG(GBA_BIOS, GAME_ERROR, "Attempting to divide INT_MIN by -1!");
293		cpu->gprs[0] = INT32_MIN;
294		cpu->gprs[1] = 0;
295		cpu->gprs[3] = INT32_MIN;
296	} else {
297		div_t result = div(num, denom);
298		cpu->gprs[0] = result.quot;
299		cpu->gprs[1] = result.rem;
300		cpu->gprs[3] = abs(result.quot);
301	}
302	int loops = clz32(denom) - clz32(num);
303	if (loops < 1) {
304		loops = 1;
305	}
306	gba->biosStall = 4 /* prologue */ + 13 * loops + 7 /* epilogue */;
307}
308
309static int16_t _ArcTan(int32_t i, int32_t* r1, int32_t* r3, uint32_t* cycles) {
310	int currentCycles = 37;
311	currentCycles += _mulWait(i * i);
312	int32_t a = -((i * i) >> 14);
313	currentCycles += _mulWait(0xA9 * a);
314	int32_t b = ((0xA9 * a) >> 14) + 0x390;
315	currentCycles += _mulWait(b * a);
316	b = ((b * a) >> 14) + 0x91C;
317	currentCycles += _mulWait(b * a);
318	b = ((b * a) >> 14) + 0xFB6;
319	currentCycles += _mulWait(b * a);
320	b = ((b * a) >> 14) + 0x16AA;
321	currentCycles += _mulWait(b * a);
322	b = ((b * a) >> 14) + 0x2081;
323	currentCycles += _mulWait(b * a);
324	b = ((b * a) >> 14) + 0x3651;
325	currentCycles += _mulWait(b * a);
326	b = ((b * a) >> 14) + 0xA2F9;
327	if (r1) {
328		*r1 = a;
329	}
330	if (r3) {
331		*r3 = b;
332	}
333	*cycles = currentCycles;
334	return (i * b) >> 16;
335}
336
337static int16_t _ArcTan2(int32_t x, int32_t y, int32_t* r1, uint32_t* cycles) {
338	if (!y) {
339		if (x >= 0) {
340			return 0;
341		}
342		return 0x8000;
343	}
344	if (!x) {
345		if (y >= 0) {
346			return 0x4000;
347		}
348		return 0xC000;
349	}
350	if (y >= 0) {
351		if (x >= 0) {
352			if (x >= y) {
353				return _ArcTan((y << 14) / x, r1, NULL, cycles);
354			}
355		} else if (-x >= y) {
356			return _ArcTan((y << 14) / x, r1, NULL, cycles) + 0x8000;
357		}
358		return 0x4000 - _ArcTan((x << 14) / y, r1, NULL, cycles);
359	} else {
360		if (x <= 0) {
361			if (-x > -y) {
362				return _ArcTan((y << 14) / x, r1, NULL, cycles) + 0x8000;
363			}
364		} else if (x >= -y) {
365			return _ArcTan((y << 14) / x, r1, NULL, cycles) + 0x10000;
366		}
367		return 0xC000 - _ArcTan((x << 14) / y, r1, NULL, cycles);
368	}
369}
370
371static int32_t _Sqrt(uint32_t x, uint32_t* cycles) {
372	if (!x) {
373		*cycles = 53;
374		return 0;
375	}
376	int32_t currentCycles = 15;
377	uint32_t lower;
378	uint32_t upper = x;
379	uint32_t bound = 1;
380	while (bound < upper) {
381		upper >>= 1;
382		bound <<= 1;
383		currentCycles += 6;
384	}
385	while (true) {
386		currentCycles += 6;
387		upper = x;
388		uint32_t accum = 0;
389		lower = bound;
390		while (true) {
391			currentCycles += 5;
392			uint32_t oldLower = lower;
393			if (lower <= upper >> 1) {
394				lower <<= 1;
395			}
396			if (oldLower >= upper >> 1) {
397				break;
398			}
399		}
400		while (true) {
401			currentCycles += 8;
402			accum <<= 1;
403			if (upper >= lower) {
404				++accum;
405				upper -= lower;
406			}
407			if (lower == bound) {
408				break;
409			}
410			lower >>= 1;
411		}
412		uint32_t oldBound = bound;
413		bound += accum;
414		bound >>= 1;
415		if (bound >= oldBound) {
416			bound = oldBound;
417			break;
418		}
419	}
420	*cycles = currentCycles;
421	return bound;
422}
423
424void GBASwi16(struct ARMCore* cpu, int immediate) {
425	struct GBA* gba = (struct GBA*) cpu->master;
426	mLOG(GBA_BIOS, DEBUG, "SWI: %02X r0: %08X r1: %08X r2: %08X r3: %08X",
427	    immediate, cpu->gprs[0], cpu->gprs[1], cpu->gprs[2], cpu->gprs[3]);
428
429	switch (immediate) {
430	case 0xF0: // Used for internal stall counting
431		cpu->gprs[12] = gba->biosStall;
432		return;
433	case 0xFA:
434		GBAPrintFlush(gba);
435		return;
436	}
437
438	if (gba->memory.fullBios) {
439		ARMRaiseSWI(cpu);
440		return;
441	}
442
443	bool useStall = false;
444	switch (immediate) {
445	case GBA_SWI_SOFT_RESET:
446		_SoftReset(gba);
447		break;
448	case GBA_SWI_REGISTER_RAM_RESET:
449		_RegisterRamReset(gba);
450		break;
451	case GBA_SWI_HALT:
452		ARMRaiseSWI(cpu);
453		return;
454	case GBA_SWI_STOP:
455		GBAStop(gba);
456		break;
457	case GBA_SWI_VBLANK_INTR_WAIT:
458	// VBlankIntrWait
459	// Fall through:
460	case GBA_SWI_INTR_WAIT:
461		// IntrWait
462		ARMRaiseSWI(cpu);
463		return;
464	case GBA_SWI_DIV:
465		useStall = true;
466		_Div(gba, cpu->gprs[0], cpu->gprs[1]);
467		break;
468	case GBA_SWI_DIV_ARM:
469		useStall = true;
470		_Div(gba, cpu->gprs[1], cpu->gprs[0]);
471		break;
472	case GBA_SWI_SQRT:
473		useStall = true;
474		cpu->gprs[0] = _Sqrt(cpu->gprs[0], &gba->biosStall);
475		break;
476	case GBA_SWI_ARCTAN:
477		useStall = true;
478		cpu->gprs[0] = _ArcTan(cpu->gprs[0], &cpu->gprs[1], &cpu->gprs[3], &gba->biosStall);
479		break;
480	case GBA_SWI_ARCTAN2:
481		useStall = true;
482		cpu->gprs[0] = (uint16_t) _ArcTan2(cpu->gprs[0], cpu->gprs[1], &cpu->gprs[1], &gba->biosStall);
483		cpu->gprs[3] = 0x170;
484		break;
485	case GBA_SWI_CPU_SET:
486	case GBA_SWI_CPU_FAST_SET:
487		if (cpu->gprs[0] >> BASE_OFFSET < REGION_WORKING_RAM) {
488			mLOG(GBA_BIOS, GAME_ERROR, "Cannot CpuSet from BIOS");
489			break;
490		}
491		if (cpu->gprs[0] & (cpu->gprs[2] & (1 << 26) ? 3 : 1)) {
492			mLOG(GBA_BIOS, GAME_ERROR, "Misaligned CpuSet source");
493		}
494		if (cpu->gprs[1] & (cpu->gprs[2] & (1 << 26) ? 3 : 1)) {
495			mLOG(GBA_BIOS, GAME_ERROR, "Misaligned CpuSet destination");
496		}
497		ARMRaiseSWI(cpu);
498		return;
499	case GBA_SWI_GET_BIOS_CHECKSUM:
500		cpu->gprs[0] = GBA_BIOS_CHECKSUM;
501		cpu->gprs[1] = 1;
502		cpu->gprs[3] = SIZE_BIOS;
503		break;
504	case GBA_SWI_BG_AFFINE_SET:
505		_BgAffineSet(gba);
506		break;
507	case GBA_SWI_OBJ_AFFINE_SET:
508		_ObjAffineSet(gba);
509		break;
510	case GBA_SWI_BIT_UNPACK:
511		if (cpu->gprs[0] < BASE_WORKING_RAM) {
512			mLOG(GBA_BIOS, GAME_ERROR, "Bad BitUnPack source");
513			break;
514		}
515		switch (cpu->gprs[1] >> BASE_OFFSET) {
516		default:
517			mLOG(GBA_BIOS, GAME_ERROR, "Bad BitUnPack destination");
518		// Fall through
519		case REGION_WORKING_RAM:
520		case REGION_WORKING_IRAM:
521		case REGION_VRAM:
522			_unBitPack(gba);
523			break;
524		}
525		break;
526	case GBA_SWI_LZ77_UNCOMP_WRAM:
527	case GBA_SWI_LZ77_UNCOMP_VRAM:
528		if (cpu->gprs[0] < BASE_WORKING_RAM) {
529			mLOG(GBA_BIOS, GAME_ERROR, "Bad LZ77 source");
530			break;
531		}
532		switch (cpu->gprs[1] >> BASE_OFFSET) {
533		default:
534			mLOG(GBA_BIOS, GAME_ERROR, "Bad LZ77 destination");
535		// Fall through
536		case REGION_WORKING_RAM:
537		case REGION_WORKING_IRAM:
538		case REGION_VRAM:
539			_unLz77(gba, immediate == GBA_SWI_LZ77_UNCOMP_WRAM ? 1 : 2);
540			break;
541		}
542		break;
543	case GBA_SWI_HUFFMAN_UNCOMP:
544		if (cpu->gprs[0] < BASE_WORKING_RAM) {
545			mLOG(GBA_BIOS, GAME_ERROR, "Bad Huffman source");
546			break;
547		}
548		switch (cpu->gprs[1] >> BASE_OFFSET) {
549		default:
550			mLOG(GBA_BIOS, GAME_ERROR, "Bad Huffman destination");
551		// Fall through
552		case REGION_WORKING_RAM:
553		case REGION_WORKING_IRAM:
554		case REGION_VRAM:
555			_unHuffman(gba);
556			break;
557		}
558		break;
559	case GBA_SWI_RL_UNCOMP_WRAM:
560	case GBA_SWI_RL_UNCOMP_VRAM:
561		if (cpu->gprs[0] < BASE_WORKING_RAM) {
562			mLOG(GBA_BIOS, GAME_ERROR, "Bad RL source");
563			break;
564		}
565		switch (cpu->gprs[1] >> BASE_OFFSET) {
566		default:
567			mLOG(GBA_BIOS, GAME_ERROR, "Bad RL destination");
568		// Fall through
569		case REGION_WORKING_RAM:
570		case REGION_WORKING_IRAM:
571		case REGION_VRAM:
572			_unRl(gba, immediate == GBA_SWI_RL_UNCOMP_WRAM ? 1 : 2);
573			break;
574		}
575		break;
576	case GBA_SWI_DIFF_8BIT_UNFILTER_WRAM:
577	case GBA_SWI_DIFF_8BIT_UNFILTER_VRAM:
578	case GBA_SWI_DIFF_16BIT_UNFILTER:
579		if (cpu->gprs[0] < BASE_WORKING_RAM) {
580			mLOG(GBA_BIOS, GAME_ERROR, "Bad UnFilter source");
581			break;
582		}
583		switch (cpu->gprs[1] >> BASE_OFFSET) {
584		default:
585			mLOG(GBA_BIOS, GAME_ERROR, "Bad UnFilter destination");
586		// Fall through
587		case REGION_WORKING_RAM:
588		case REGION_WORKING_IRAM:
589		case REGION_VRAM:
590			_unFilter(gba, immediate == GBA_SWI_DIFF_16BIT_UNFILTER ? 2 : 1, immediate == GBA_SWI_DIFF_8BIT_UNFILTER_WRAM ? 1 : 2);
591			break;
592		}
593		break;
594	case GBA_SWI_SOUND_BIAS:
595		// SoundBias is mostly meaningless here
596		mLOG(GBA_BIOS, STUB, "Stub software interrupt: SoundBias (19)");
597		break;
598	case GBA_SWI_MIDI_KEY_2_FREQ:
599		_MidiKey2Freq(gba);
600		break;
601	case GBA_SWI_SOUND_DRIVER_GET_JUMP_LIST:
602		ARMRaiseSWI(cpu);
603		return;
604	default:
605		mLOG(GBA_BIOS, STUB, "Stub software interrupt: %02X", immediate);
606	}
607	if (useStall) {
608		if (gba->biosStall >= 18) {
609			gba->biosStall -= 18;
610			gba->cpu->cycles += gba->biosStall & 3;
611			gba->biosStall &= ~3;
612			ARMRaiseSWI(cpu);
613		} else {
614			gba->cpu->cycles += gba->biosStall;
615			useStall = false;
616		}
617	}
618	if (!useStall) {
619		gba->cpu->cycles += 45 + cpu->memory.activeNonseqCycles16 /* 8 bit load for SWI # */;
620		// Return cycles
621		if (gba->cpu->executionMode == MODE_ARM) {
622			gba->cpu->cycles += cpu->memory.activeNonseqCycles32 + cpu->memory.activeSeqCycles32;
623		} else {
624			gba->cpu->cycles += cpu->memory.activeNonseqCycles16 + cpu->memory.activeSeqCycles16;
625		}
626	}
627	gba->memory.biosPrefetch = 0xE3A02004;
628}
629
630void GBASwi32(struct ARMCore* cpu, int immediate) {
631	GBASwi16(cpu, immediate >> 16);
632}
633
634uint32_t GBAChecksum(uint32_t* memory, size_t size) {
635	size_t i;
636	uint32_t sum = 0;
637	for (i = 0; i < size; i += 4) {
638		sum += memory[i >> 2];
639	}
640	return sum;
641}
642
643static void _unLz77(struct GBA* gba, int width) {
644	struct ARMCore* cpu = gba->cpu;
645	uint32_t source = cpu->gprs[0];
646	uint32_t dest = cpu->gprs[1];
647	int remaining = (cpu->memory.load32(cpu, source, 0) & 0xFFFFFF00) >> 8;
648	// We assume the signature byte (0x10) is correct
649	int blockheader = 0; // Some compilers warn if this isn't set, even though it's trivially provably always set
650	source += 4;
651	int blocksRemaining = 0;
652	uint32_t disp;
653	int bytes;
654	int byte;
655	int halfword = 0;
656	while (remaining > 0) {
657		if (blocksRemaining) {
658			if (blockheader & 0x80) {
659				// Compressed
660				int block = cpu->memory.load8(cpu, source + 1, 0) | (cpu->memory.load8(cpu, source, 0) << 8);
661				source += 2;
662				disp = dest - (block & 0x0FFF) - 1;
663				bytes = (block >> 12) + 3;
664				while (bytes--) {
665					if (remaining) {
666						--remaining;
667					} else {
668						mLOG(GBA_BIOS, GAME_ERROR, "Improperly compressed LZ77 data at %08X. "
669						     "This will lead to a buffer overrun at %08X and may crash on hardware.",
670						     cpu->gprs[0], cpu->gprs[1]);
671						if (gba->vbaBugCompat) {
672							break;
673						}
674					}
675					if (width == 2) {
676						byte = (int16_t) cpu->memory.load16(cpu, disp & ~1, 0);
677						if (dest & 1) {
678							byte >>= (disp & 1) * 8;
679							halfword |= byte << 8;
680							cpu->memory.store16(cpu, dest ^ 1, halfword, 0);
681						} else {
682							byte >>= (disp & 1) * 8;
683							halfword = byte & 0xFF;
684						}
685					} else {
686						byte = cpu->memory.load8(cpu, disp, 0);
687						cpu->memory.store8(cpu, dest, byte, 0);
688					}
689					++disp;
690					++dest;
691				}
692			} else {
693				// Uncompressed
694				byte = cpu->memory.load8(cpu, source, 0);
695				++source;
696				if (width == 2) {
697					if (dest & 1) {
698						halfword |= byte << 8;
699						cpu->memory.store16(cpu, dest ^ 1, halfword, 0);
700					} else {
701						halfword = byte;
702					}
703				} else {
704					cpu->memory.store8(cpu, dest, byte, 0);
705				}
706				++dest;
707				--remaining;
708			}
709			blockheader <<= 1;
710			--blocksRemaining;
711		} else {
712			blockheader = cpu->memory.load8(cpu, source, 0);
713			++source;
714			blocksRemaining = 8;
715		}
716	}
717	cpu->gprs[0] = source;
718	cpu->gprs[1] = dest;
719	cpu->gprs[3] = 0;
720}
721
722DECL_BITFIELD(HuffmanNode, uint8_t);
723DECL_BITS(HuffmanNode, Offset, 0, 6);
724DECL_BIT(HuffmanNode, RTerm, 6);
725DECL_BIT(HuffmanNode, LTerm, 7);
726
727static void _unHuffman(struct GBA* gba) {
728	struct ARMCore* cpu = gba->cpu;
729	uint32_t source = cpu->gprs[0] & 0xFFFFFFFC;
730	uint32_t dest = cpu->gprs[1];
731	uint32_t header = cpu->memory.load32(cpu, source, 0);
732	int remaining = header >> 8;
733	unsigned bits = header & 0xF;
734	if (bits == 0) {
735		mLOG(GBA_BIOS, GAME_ERROR, "Invalid Huffman bits");
736		bits = 8;
737	}
738	if (32 % bits || bits == 1) {
739		mLOG(GBA_BIOS, STUB, "Unimplemented unaligned Huffman");
740		return;
741	}
742	// We assume the signature byte (0x20) is correct
743	int treesize = (cpu->memory.load8(cpu, source + 4, 0) << 1) + 1;
744	int block = 0;
745	uint32_t treeBase = source + 5;
746	source += 5 + treesize;
747	uint32_t nPointer = treeBase;
748	HuffmanNode node;
749	int bitsRemaining;
750	int readBits;
751	int bitsSeen = 0;
752	node = cpu->memory.load8(cpu, nPointer, 0);
753	while (remaining > 0) {
754		uint32_t bitstream = cpu->memory.load32(cpu, source, 0);
755		source += 4;
756		for (bitsRemaining = 32; bitsRemaining > 0 && remaining > 0; --bitsRemaining, bitstream <<= 1) {
757			uint32_t next = (nPointer & ~1) + HuffmanNodeGetOffset(node) * 2 + 2;
758			if (bitstream & 0x80000000) {
759				// Go right
760				if (HuffmanNodeIsRTerm(node)) {
761					readBits = cpu->memory.load8(cpu, next + 1, 0);
762				} else {
763					nPointer = next + 1;
764					node = cpu->memory.load8(cpu, nPointer, 0);
765					continue;
766				}
767			} else {
768				// Go left
769				if (HuffmanNodeIsLTerm(node)) {
770					readBits = cpu->memory.load8(cpu, next, 0);
771				} else {
772					nPointer = next;
773					node = cpu->memory.load8(cpu, nPointer, 0);
774					continue;
775				}
776			}
777
778			block |= (readBits & ((1 << bits) - 1)) << bitsSeen;
779			bitsSeen += bits;
780			nPointer = treeBase;
781			node = cpu->memory.load8(cpu, nPointer, 0);
782			if (bitsSeen == 32) {
783				bitsSeen = 0;
784				cpu->memory.store32(cpu, dest, block, 0);
785				dest += 4;
786				remaining -= 4;
787				block = 0;
788			}
789		}
790	}
791	cpu->gprs[0] = source;
792	cpu->gprs[1] = dest;
793}
794
795static void _unRl(struct GBA* gba, int width) {
796	struct ARMCore* cpu = gba->cpu;
797	uint32_t source = cpu->gprs[0];
798	int remaining = (cpu->memory.load32(cpu, source & 0xFFFFFFFC, 0) & 0xFFFFFF00) >> 8;
799	int padding = (4 - remaining) & 0x3;
800	// We assume the signature byte (0x30) is correct
801	int blockheader;
802	int block;
803	source += 4;
804	uint32_t dest = cpu->gprs[1];
805	int halfword = 0;
806	while (remaining > 0) {
807		blockheader = cpu->memory.load8(cpu, source, 0);
808		++source;
809		if (blockheader & 0x80) {
810			// Compressed
811			blockheader &= 0x7F;
812			blockheader += 3;
813			block = cpu->memory.load8(cpu, source, 0);
814			++source;
815			while (blockheader-- && remaining) {
816				--remaining;
817				if (width == 2) {
818					if (dest & 1) {
819						halfword |= block << 8;
820						cpu->memory.store16(cpu, dest ^ 1, halfword, 0);
821					} else {
822						halfword = block;
823					}
824				} else {
825					cpu->memory.store8(cpu, dest, block, 0);
826				}
827				++dest;
828			}
829		} else {
830			// Uncompressed
831			blockheader++;
832			while (blockheader-- && remaining) {
833				--remaining;
834				int byte = cpu->memory.load8(cpu, source, 0);
835				++source;
836				if (width == 2) {
837					if (dest & 1) {
838						halfword |= byte << 8;
839						cpu->memory.store16(cpu, dest ^ 1, halfword, 0);
840					} else {
841						halfword = byte;
842					}
843				} else {
844					cpu->memory.store8(cpu, dest, byte, 0);
845				}
846				++dest;
847			}
848		}
849	}
850	if (width == 2) {
851		if (dest & 1) {
852			--padding;
853			++dest;
854		}
855		for (; padding > 0; padding -= 2, dest += 2) {
856			cpu->memory.store16(cpu, dest, 0, 0);
857		}
858	} else {
859		while (padding--) {
860			cpu->memory.store8(cpu, dest, 0, 0);
861			++dest;
862		}
863	}
864	cpu->gprs[0] = source;
865	cpu->gprs[1] = dest;
866}
867
868static void _unFilter(struct GBA* gba, int inwidth, int outwidth) {
869	struct ARMCore* cpu = gba->cpu;
870	uint32_t source = cpu->gprs[0] & 0xFFFFFFFC;
871	uint32_t dest = cpu->gprs[1];
872	uint32_t header = cpu->memory.load32(cpu, source, 0);
873	int remaining = header >> 8;
874	// We assume the signature nybble (0x8) is correct
875	uint16_t halfword = 0;
876	uint16_t old = 0;
877	source += 4;
878	while (remaining > 0) {
879		uint16_t new;
880		if (inwidth == 1) {
881			new = cpu->memory.load8(cpu, source, 0);
882		} else {
883			new = cpu->memory.load16(cpu, source, 0);
884		}
885		new += old;
886		if (outwidth > inwidth) {
887			halfword >>= 8;
888			halfword |= (new << 8);
889			if (source & 1) {
890				cpu->memory.store16(cpu, dest, halfword, 0);
891				dest += outwidth;
892				remaining -= outwidth;
893			}
894		} else if (outwidth == 1) {
895			cpu->memory.store8(cpu, dest, new, 0);
896			dest += outwidth;
897			remaining -= outwidth;
898		} else {
899			cpu->memory.store16(cpu, dest, new, 0);
900			dest += outwidth;
901			remaining -= outwidth;
902		}
903		old = new;
904		source += inwidth;
905	}
906	cpu->gprs[0] = source;
907	cpu->gprs[1] = dest;
908}
909
910static void _unBitPack(struct GBA* gba) {
911	struct ARMCore* cpu = gba->cpu;
912	uint32_t source = cpu->gprs[0];
913	uint32_t dest = cpu->gprs[1];
914	uint32_t info = cpu->gprs[2];
915	unsigned sourceLen = cpu->memory.load16(cpu, info, 0);
916	unsigned sourceWidth = cpu->memory.load8(cpu, info + 2, 0);
917	unsigned destWidth = cpu->memory.load8(cpu, info + 3, 0);
918	switch (sourceWidth) {
919	case 1:
920	case 2:
921	case 4:
922	case 8:
923		break;
924	default:
925		mLOG(GBA_BIOS, GAME_ERROR, "Bad BitUnPack source width: %u", sourceWidth);
926		return;
927	}
928	switch (destWidth) {
929	case 1:
930	case 2:
931	case 4:
932	case 8:
933	case 16:
934	case 32:
935		break;
936	default:
937		mLOG(GBA_BIOS, GAME_ERROR, "Bad BitUnPack destination width: %u", destWidth);
938		return;
939	}
940	uint32_t bias = cpu->memory.load32(cpu, info + 4, 0);
941	uint8_t in = 0;
942	uint32_t out = 0;
943	int bitsRemaining = 0;
944	int bitsEaten = 0;
945	while (sourceLen > 0 || bitsRemaining) {
946		if (!bitsRemaining) {
947			in = cpu->memory.load8(cpu, source, 0);
948			bitsRemaining = 8;
949			++source;
950			--sourceLen;
951		}
952		unsigned scaled = in & ((1 << sourceWidth) - 1);
953		in >>= sourceWidth;
954		if (scaled || bias & 0x80000000) {
955			scaled += bias & 0x7FFFFFFF;
956		}
957		bitsRemaining -= sourceWidth;
958		out |= scaled << bitsEaten;
959		bitsEaten += destWidth;
960		if (bitsEaten == 32) {
961			cpu->memory.store32(cpu, dest, out, 0);
962			bitsEaten = 0;
963			out = 0;
964			dest += 4;
965		}
966	}
967	cpu->gprs[0] = source;
968	cpu->gprs[1] = dest;
969}