all repos — mgba @ 06a3770daa90023e2a4fb85ed17559e99ce248f9

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		mLOG(GBA_BIOS, FATAL, "Attempting to divide %i by zero!", num);
281		// If abs(num) > 1, this should hang, but that would be painful to
282		// emulate in HLE, and no game will get into a state under normal
283		// operation where it hangs...
284		cpu->gprs[0] = (num < 0) ? -1 : 1;
285		cpu->gprs[1] = num;
286		cpu->gprs[3] = 1;
287	} else if (denom == -1 && num == INT32_MIN) {
288		mLOG(GBA_BIOS, GAME_ERROR, "Attempting to divide INT_MIN by -1!");
289		cpu->gprs[0] = INT32_MIN;
290		cpu->gprs[1] = 0;
291		cpu->gprs[3] = INT32_MIN;
292	} else {
293		div_t result = div(num, denom);
294		cpu->gprs[0] = result.quot;
295		cpu->gprs[1] = result.rem;
296		cpu->gprs[3] = abs(result.quot);
297	}
298	int loops = clz32(denom) - clz32(num);
299	if (loops < 1) {
300		loops = 1;
301	}
302	gba->biosStall = 4 /* prologue */ + 13 * loops + 7 /* epilogue */;
303}
304
305static int16_t _ArcTan(int32_t i, int32_t* r1, int32_t* r3, uint32_t* cycles) {
306	int currentCycles = 37;
307	currentCycles += _mulWait(i * i);
308	int32_t a = -((i * i) >> 14);
309	currentCycles += _mulWait(0xA9 * a);
310	int32_t b = ((0xA9 * a) >> 14) + 0x390;
311	currentCycles += _mulWait(b * a);
312	b = ((b * a) >> 14) + 0x91C;
313	currentCycles += _mulWait(b * a);
314	b = ((b * a) >> 14) + 0xFB6;
315	currentCycles += _mulWait(b * a);
316	b = ((b * a) >> 14) + 0x16AA;
317	currentCycles += _mulWait(b * a);
318	b = ((b * a) >> 14) + 0x2081;
319	currentCycles += _mulWait(b * a);
320	b = ((b * a) >> 14) + 0x3651;
321	currentCycles += _mulWait(b * a);
322	b = ((b * a) >> 14) + 0xA2F9;
323	if (r1) {
324		*r1 = a;
325	}
326	if (r3) {
327		*r3 = b;
328	}
329	*cycles = currentCycles;
330	return (i * b) >> 16;
331}
332
333static int16_t _ArcTan2(int32_t x, int32_t y, int32_t* r1, uint32_t* cycles) {
334	if (!y) {
335		if (x >= 0) {
336			return 0;
337		}
338		return 0x8000;
339	}
340	if (!x) {
341		if (y >= 0) {
342			return 0x4000;
343		}
344		return 0xC000;
345	}
346	if (y >= 0) {
347		if (x >= 0) {
348			if (x >= y) {
349				return _ArcTan((y << 14) / x, r1, NULL, cycles);
350			}
351		} else if (-x >= y) {
352			return _ArcTan((y << 14) / x, r1, NULL, cycles) + 0x8000;
353		}
354		return 0x4000 - _ArcTan((x << 14) / y, r1, NULL, cycles);
355	} else {
356		if (x <= 0) {
357			if (-x > -y) {
358				return _ArcTan((y << 14) / x, r1, NULL, cycles) + 0x8000;
359			}
360		} else if (x >= -y) {
361			return _ArcTan((y << 14) / x, r1, NULL, cycles) + 0x10000;
362		}
363		return 0xC000 - _ArcTan((x << 14) / y, r1, NULL, cycles);
364	}
365}
366
367static int32_t _Sqrt(uint32_t x, uint32_t* cycles) {
368	if (!x) {
369		*cycles = 53;
370		return 0;
371	}
372	int32_t currentCycles = 15;
373	uint32_t lower;
374	uint32_t upper = x;
375	uint32_t bound = 1;
376	while (bound < upper) {
377		upper >>= 1;
378		bound <<= 1;
379		currentCycles += 6;
380	}
381	while (true) {
382		currentCycles += 6;
383		upper = x;
384		uint32_t accum = 0;
385		lower = bound;
386		while (true) {
387			currentCycles += 5;
388			uint32_t oldLower = lower;
389			if (lower <= upper >> 1) {
390				lower <<= 1;
391			}
392			if (oldLower >= upper >> 1) {
393				break;
394			}
395		}
396		while (true) {
397			currentCycles += 8;
398			accum <<= 1;
399			if (upper >= lower) {
400				++accum;
401				upper -= lower;
402			}
403			if (lower == bound) {
404				break;
405			}
406			lower >>= 1;
407		}
408		uint32_t oldBound = bound;
409		bound += accum;
410		bound >>= 1;
411		if (bound >= oldBound) {
412			bound = oldBound;
413			break;
414		}
415	}
416	*cycles = currentCycles;
417	return bound;
418}
419
420void GBASwi16(struct ARMCore* cpu, int immediate) {
421	struct GBA* gba = (struct GBA*) cpu->master;
422	mLOG(GBA_BIOS, DEBUG, "SWI: %02X r0: %08X r1: %08X r2: %08X r3: %08X",
423	    immediate, cpu->gprs[0], cpu->gprs[1], cpu->gprs[2], cpu->gprs[3]);
424
425	switch (immediate) {
426	case 0xF0: // Used for internal stall counting
427		cpu->gprs[12] = gba->biosStall;
428		return;
429	case 0xFA:
430		GBAPrintFlush(gba);
431		return;
432	}
433
434	if (gba->memory.fullBios) {
435		ARMRaiseSWI(cpu);
436		return;
437	}
438
439	bool useStall = false;
440	switch (immediate) {
441	case GBA_SWI_SOFT_RESET:
442		_SoftReset(gba);
443		break;
444	case GBA_SWI_REGISTER_RAM_RESET:
445		_RegisterRamReset(gba);
446		break;
447	case GBA_SWI_HALT:
448		ARMRaiseSWI(cpu);
449		return;
450	case GBA_SWI_STOP:
451		GBAStop(gba);
452		break;
453	case GBA_SWI_VBLANK_INTR_WAIT:
454	// VBlankIntrWait
455	// Fall through:
456	case GBA_SWI_INTR_WAIT:
457		// IntrWait
458		ARMRaiseSWI(cpu);
459		return;
460	case GBA_SWI_DIV:
461		useStall = true;
462		_Div(gba, cpu->gprs[0], cpu->gprs[1]);
463		break;
464	case GBA_SWI_DIV_ARM:
465		useStall = true;
466		_Div(gba, cpu->gprs[1], cpu->gprs[0]);
467		break;
468	case GBA_SWI_SQRT:
469		useStall = true;
470		cpu->gprs[0] = _Sqrt(cpu->gprs[0], &gba->biosStall);
471		break;
472	case GBA_SWI_ARCTAN:
473		useStall = true;
474		cpu->gprs[0] = _ArcTan(cpu->gprs[0], &cpu->gprs[1], &cpu->gprs[3], &gba->biosStall);
475		break;
476	case GBA_SWI_ARCTAN2:
477		useStall = true;
478		cpu->gprs[0] = (uint16_t) _ArcTan2(cpu->gprs[0], cpu->gprs[1], &cpu->gprs[1], &gba->biosStall);
479		cpu->gprs[3] = 0x170;
480		break;
481	case GBA_SWI_CPU_SET:
482	case GBA_SWI_CPU_FAST_SET:
483		if (cpu->gprs[0] >> BASE_OFFSET < REGION_WORKING_RAM) {
484			mLOG(GBA_BIOS, GAME_ERROR, "Cannot CpuSet from BIOS");
485			break;
486		}
487		if (cpu->gprs[0] & (cpu->gprs[2] & (1 << 26) ? 3 : 1)) {
488			mLOG(GBA_BIOS, GAME_ERROR, "Misaligned CpuSet source");
489		}
490		if (cpu->gprs[1] & (cpu->gprs[2] & (1 << 26) ? 3 : 1)) {
491			mLOG(GBA_BIOS, GAME_ERROR, "Misaligned CpuSet destination");
492		}
493		ARMRaiseSWI(cpu);
494		return;
495	case GBA_SWI_GET_BIOS_CHECKSUM:
496		cpu->gprs[0] = GBA_BIOS_CHECKSUM;
497		cpu->gprs[1] = 1;
498		cpu->gprs[3] = SIZE_BIOS;
499		break;
500	case GBA_SWI_BG_AFFINE_SET:
501		_BgAffineSet(gba);
502		break;
503	case GBA_SWI_OBJ_AFFINE_SET:
504		_ObjAffineSet(gba);
505		break;
506	case GBA_SWI_BIT_UNPACK:
507		if (cpu->gprs[0] < BASE_WORKING_RAM) {
508			mLOG(GBA_BIOS, GAME_ERROR, "Bad BitUnPack source");
509			break;
510		}
511		switch (cpu->gprs[1] >> BASE_OFFSET) {
512		default:
513			mLOG(GBA_BIOS, GAME_ERROR, "Bad BitUnPack destination");
514		// Fall through
515		case REGION_WORKING_RAM:
516		case REGION_WORKING_IRAM:
517		case REGION_VRAM:
518			_unBitPack(gba);
519			break;
520		}
521		break;
522	case GBA_SWI_LZ77_UNCOMP_WRAM:
523	case GBA_SWI_LZ77_UNCOMP_VRAM:
524		if (cpu->gprs[0] < BASE_WORKING_RAM) {
525			mLOG(GBA_BIOS, GAME_ERROR, "Bad LZ77 source");
526			break;
527		}
528		switch (cpu->gprs[1] >> BASE_OFFSET) {
529		default:
530			mLOG(GBA_BIOS, GAME_ERROR, "Bad LZ77 destination");
531		// Fall through
532		case REGION_WORKING_RAM:
533		case REGION_WORKING_IRAM:
534		case REGION_VRAM:
535			_unLz77(gba, immediate == GBA_SWI_LZ77_UNCOMP_WRAM ? 1 : 2);
536			break;
537		}
538		break;
539	case GBA_SWI_HUFFMAN_UNCOMP:
540		if (cpu->gprs[0] < BASE_WORKING_RAM) {
541			mLOG(GBA_BIOS, GAME_ERROR, "Bad Huffman source");
542			break;
543		}
544		switch (cpu->gprs[1] >> BASE_OFFSET) {
545		default:
546			mLOG(GBA_BIOS, GAME_ERROR, "Bad Huffman destination");
547		// Fall through
548		case REGION_WORKING_RAM:
549		case REGION_WORKING_IRAM:
550		case REGION_VRAM:
551			_unHuffman(gba);
552			break;
553		}
554		break;
555	case GBA_SWI_RL_UNCOMP_WRAM:
556	case GBA_SWI_RL_UNCOMP_VRAM:
557		if (cpu->gprs[0] < BASE_WORKING_RAM) {
558			mLOG(GBA_BIOS, GAME_ERROR, "Bad RL source");
559			break;
560		}
561		switch (cpu->gprs[1] >> BASE_OFFSET) {
562		default:
563			mLOG(GBA_BIOS, GAME_ERROR, "Bad RL destination");
564		// Fall through
565		case REGION_WORKING_RAM:
566		case REGION_WORKING_IRAM:
567		case REGION_VRAM:
568			_unRl(gba, immediate == GBA_SWI_RL_UNCOMP_WRAM ? 1 : 2);
569			break;
570		}
571		break;
572	case GBA_SWI_DIFF_8BIT_UNFILTER_WRAM:
573	case GBA_SWI_DIFF_8BIT_UNFILTER_VRAM:
574	case GBA_SWI_DIFF_16BIT_UNFILTER:
575		if (cpu->gprs[0] < BASE_WORKING_RAM) {
576			mLOG(GBA_BIOS, GAME_ERROR, "Bad UnFilter source");
577			break;
578		}
579		switch (cpu->gprs[1] >> BASE_OFFSET) {
580		default:
581			mLOG(GBA_BIOS, GAME_ERROR, "Bad UnFilter destination");
582		// Fall through
583		case REGION_WORKING_RAM:
584		case REGION_WORKING_IRAM:
585		case REGION_VRAM:
586			_unFilter(gba, immediate == GBA_SWI_DIFF_16BIT_UNFILTER ? 2 : 1, immediate == GBA_SWI_DIFF_8BIT_UNFILTER_WRAM ? 1 : 2);
587			break;
588		}
589		break;
590	case GBA_SWI_SOUND_BIAS:
591		// SoundBias is mostly meaningless here
592		mLOG(GBA_BIOS, STUB, "Stub software interrupt: SoundBias (19)");
593		break;
594	case GBA_SWI_MIDI_KEY_2_FREQ:
595		_MidiKey2Freq(gba);
596		break;
597	case GBA_SWI_SOUND_DRIVER_GET_JUMP_LIST:
598		ARMRaiseSWI(cpu);
599		return;
600	default:
601		mLOG(GBA_BIOS, STUB, "Stub software interrupt: %02X", immediate);
602	}
603	if (useStall) {
604		if (gba->biosStall >= 18) {
605			gba->biosStall -= 18;
606			gba->cpu->cycles += gba->biosStall & 3;
607			gba->biosStall &= ~3;
608			ARMRaiseSWI(cpu);
609		} else {
610			gba->cpu->cycles += gba->biosStall;
611			useStall = false;
612		}
613	}
614	if (!useStall) {
615		gba->cpu->cycles += 45 + cpu->memory.activeNonseqCycles16 /* 8 bit load for SWI # */;
616		// Return cycles
617		if (gba->cpu->executionMode == MODE_ARM) {
618			gba->cpu->cycles += cpu->memory.activeNonseqCycles32 + cpu->memory.activeSeqCycles32;
619		} else {
620			gba->cpu->cycles += cpu->memory.activeNonseqCycles16 + cpu->memory.activeSeqCycles16;
621		}
622	}
623	gba->memory.biosPrefetch = 0xE3A02004;
624}
625
626void GBASwi32(struct ARMCore* cpu, int immediate) {
627	GBASwi16(cpu, immediate >> 16);
628}
629
630uint32_t GBAChecksum(uint32_t* memory, size_t size) {
631	size_t i;
632	uint32_t sum = 0;
633	for (i = 0; i < size; i += 4) {
634		sum += memory[i >> 2];
635	}
636	return sum;
637}
638
639static void _unLz77(struct GBA* gba, int width) {
640	struct ARMCore* cpu = gba->cpu;
641	uint32_t source = cpu->gprs[0];
642	uint32_t dest = cpu->gprs[1];
643	int remaining = (cpu->memory.load32(cpu, source, 0) & 0xFFFFFF00) >> 8;
644	// We assume the signature byte (0x10) is correct
645	int blockheader = 0; // Some compilers warn if this isn't set, even though it's trivially provably always set
646	source += 4;
647	int blocksRemaining = 0;
648	uint32_t disp;
649	int bytes;
650	int byte;
651	int halfword = 0;
652	while (remaining > 0) {
653		if (blocksRemaining) {
654			if (blockheader & 0x80) {
655				// Compressed
656				int block = cpu->memory.load8(cpu, source + 1, 0) | (cpu->memory.load8(cpu, source, 0) << 8);
657				source += 2;
658				disp = dest - (block & 0x0FFF) - 1;
659				bytes = (block >> 12) + 3;
660				while (bytes--) {
661					if (remaining) {
662						--remaining;
663					}
664					if (width == 2) {
665						byte = (int16_t) cpu->memory.load16(cpu, disp & ~1, 0);
666						if (dest & 1) {
667							byte >>= (disp & 1) * 8;
668							halfword |= byte << 8;
669							cpu->memory.store16(cpu, dest ^ 1, halfword, 0);
670						} else {
671							byte >>= (disp & 1) * 8;
672							halfword = byte & 0xFF;
673						}
674					} else {
675						byte = cpu->memory.load8(cpu, disp, 0);
676						cpu->memory.store8(cpu, dest, byte, 0);
677					}
678					++disp;
679					++dest;
680				}
681			} else {
682				// Uncompressed
683				byte = cpu->memory.load8(cpu, source, 0);
684				++source;
685				if (width == 2) {
686					if (dest & 1) {
687						halfword |= byte << 8;
688						cpu->memory.store16(cpu, dest ^ 1, halfword, 0);
689					} else {
690						halfword = byte;
691					}
692				} else {
693					cpu->memory.store8(cpu, dest, byte, 0);
694				}
695				++dest;
696				--remaining;
697			}
698			blockheader <<= 1;
699			--blocksRemaining;
700		} else {
701			blockheader = cpu->memory.load8(cpu, source, 0);
702			++source;
703			blocksRemaining = 8;
704		}
705	}
706	cpu->gprs[0] = source;
707	cpu->gprs[1] = dest;
708	cpu->gprs[3] = 0;
709}
710
711DECL_BITFIELD(HuffmanNode, uint8_t);
712DECL_BITS(HuffmanNode, Offset, 0, 6);
713DECL_BIT(HuffmanNode, RTerm, 6);
714DECL_BIT(HuffmanNode, LTerm, 7);
715
716static void _unHuffman(struct GBA* gba) {
717	struct ARMCore* cpu = gba->cpu;
718	uint32_t source = cpu->gprs[0] & 0xFFFFFFFC;
719	uint32_t dest = cpu->gprs[1];
720	uint32_t header = cpu->memory.load32(cpu, source, 0);
721	int remaining = header >> 8;
722	unsigned bits = header & 0xF;
723	if (bits == 0) {
724		mLOG(GBA_BIOS, GAME_ERROR, "Invalid Huffman bits");
725		bits = 8;
726	}
727	if (32 % bits || bits == 1) {
728		mLOG(GBA_BIOS, STUB, "Unimplemented unaligned Huffman");
729		return;
730	}
731	// We assume the signature byte (0x20) is correct
732	int treesize = (cpu->memory.load8(cpu, source + 4, 0) << 1) + 1;
733	int block = 0;
734	uint32_t treeBase = source + 5;
735	source += 5 + treesize;
736	uint32_t nPointer = treeBase;
737	HuffmanNode node;
738	int bitsRemaining;
739	int readBits;
740	int bitsSeen = 0;
741	node = cpu->memory.load8(cpu, nPointer, 0);
742	while (remaining > 0) {
743		uint32_t bitstream = cpu->memory.load32(cpu, source, 0);
744		source += 4;
745		for (bitsRemaining = 32; bitsRemaining > 0 && remaining > 0; --bitsRemaining, bitstream <<= 1) {
746			uint32_t next = (nPointer & ~1) + HuffmanNodeGetOffset(node) * 2 + 2;
747			if (bitstream & 0x80000000) {
748				// Go right
749				if (HuffmanNodeIsRTerm(node)) {
750					readBits = cpu->memory.load8(cpu, next + 1, 0);
751				} else {
752					nPointer = next + 1;
753					node = cpu->memory.load8(cpu, nPointer, 0);
754					continue;
755				}
756			} else {
757				// Go left
758				if (HuffmanNodeIsLTerm(node)) {
759					readBits = cpu->memory.load8(cpu, next, 0);
760				} else {
761					nPointer = next;
762					node = cpu->memory.load8(cpu, nPointer, 0);
763					continue;
764				}
765			}
766
767			block |= (readBits & ((1 << bits) - 1)) << bitsSeen;
768			bitsSeen += bits;
769			nPointer = treeBase;
770			node = cpu->memory.load8(cpu, nPointer, 0);
771			if (bitsSeen == 32) {
772				bitsSeen = 0;
773				cpu->memory.store32(cpu, dest, block, 0);
774				dest += 4;
775				remaining -= 4;
776				block = 0;
777			}
778		}
779	}
780	cpu->gprs[0] = source;
781	cpu->gprs[1] = dest;
782}
783
784static void _unRl(struct GBA* gba, int width) {
785	struct ARMCore* cpu = gba->cpu;
786	uint32_t source = cpu->gprs[0];
787	int remaining = (cpu->memory.load32(cpu, source & 0xFFFFFFFC, 0) & 0xFFFFFF00) >> 8;
788	int padding = (4 - remaining) & 0x3;
789	// We assume the signature byte (0x30) is correct
790	int blockheader;
791	int block;
792	source += 4;
793	uint32_t dest = cpu->gprs[1];
794	int halfword = 0;
795	while (remaining > 0) {
796		blockheader = cpu->memory.load8(cpu, source, 0);
797		++source;
798		if (blockheader & 0x80) {
799			// Compressed
800			blockheader &= 0x7F;
801			blockheader += 3;
802			block = cpu->memory.load8(cpu, source, 0);
803			++source;
804			while (blockheader-- && remaining) {
805				--remaining;
806				if (width == 2) {
807					if (dest & 1) {
808						halfword |= block << 8;
809						cpu->memory.store16(cpu, dest ^ 1, halfword, 0);
810					} else {
811						halfword = block;
812					}
813				} else {
814					cpu->memory.store8(cpu, dest, block, 0);
815				}
816				++dest;
817			}
818		} else {
819			// Uncompressed
820			blockheader++;
821			while (blockheader-- && remaining) {
822				--remaining;
823				int byte = cpu->memory.load8(cpu, source, 0);
824				++source;
825				if (width == 2) {
826					if (dest & 1) {
827						halfword |= byte << 8;
828						cpu->memory.store16(cpu, dest ^ 1, halfword, 0);
829					} else {
830						halfword = byte;
831					}
832				} else {
833					cpu->memory.store8(cpu, dest, byte, 0);
834				}
835				++dest;
836			}
837		}
838	}
839	if (width == 2) {
840		if (dest & 1) {
841			--padding;
842			++dest;
843		}
844		for (; padding > 0; padding -= 2, dest += 2) {
845			cpu->memory.store16(cpu, dest, 0, 0);
846		}
847	} else {
848		while (padding--) {
849			cpu->memory.store8(cpu, dest, 0, 0);
850			++dest;
851		}
852	}
853	cpu->gprs[0] = source;
854	cpu->gprs[1] = dest;
855}
856
857static void _unFilter(struct GBA* gba, int inwidth, int outwidth) {
858	struct ARMCore* cpu = gba->cpu;
859	uint32_t source = cpu->gprs[0] & 0xFFFFFFFC;
860	uint32_t dest = cpu->gprs[1];
861	uint32_t header = cpu->memory.load32(cpu, source, 0);
862	int remaining = header >> 8;
863	// We assume the signature nybble (0x8) is correct
864	uint16_t halfword = 0;
865	uint16_t old = 0;
866	source += 4;
867	while (remaining > 0) {
868		uint16_t new;
869		if (inwidth == 1) {
870			new = cpu->memory.load8(cpu, source, 0);
871		} else {
872			new = cpu->memory.load16(cpu, source, 0);
873		}
874		new += old;
875		if (outwidth > inwidth) {
876			halfword >>= 8;
877			halfword |= (new << 8);
878			if (source & 1) {
879				cpu->memory.store16(cpu, dest, halfword, 0);
880				dest += outwidth;
881				remaining -= outwidth;
882			}
883		} else if (outwidth == 1) {
884			cpu->memory.store8(cpu, dest, new, 0);
885			dest += outwidth;
886			remaining -= outwidth;
887		} else {
888			cpu->memory.store16(cpu, dest, new, 0);
889			dest += outwidth;
890			remaining -= outwidth;
891		}
892		old = new;
893		source += inwidth;
894	}
895	cpu->gprs[0] = source;
896	cpu->gprs[1] = dest;
897}
898
899static void _unBitPack(struct GBA* gba) {
900	struct ARMCore* cpu = gba->cpu;
901	uint32_t source = cpu->gprs[0];
902	uint32_t dest = cpu->gprs[1];
903	uint32_t info = cpu->gprs[2];
904	unsigned sourceLen = cpu->memory.load16(cpu, info, 0);
905	unsigned sourceWidth = cpu->memory.load8(cpu, info + 2, 0);
906	unsigned destWidth = cpu->memory.load8(cpu, info + 3, 0);
907	switch (sourceWidth) {
908	case 1:
909	case 2:
910	case 4:
911	case 8:
912		break;
913	default:
914		mLOG(GBA_BIOS, GAME_ERROR, "Bad BitUnPack source width: %u", sourceWidth);
915		return;
916	}
917	switch (destWidth) {
918	case 1:
919	case 2:
920	case 4:
921	case 8:
922	case 16:
923	case 32:
924		break;
925	default:
926		mLOG(GBA_BIOS, GAME_ERROR, "Bad BitUnPack destination width: %u", destWidth);
927		return;
928	}
929	uint32_t bias = cpu->memory.load32(cpu, info + 4, 0);
930	uint8_t in = 0;
931	uint32_t out = 0;
932	int bitsRemaining = 0;
933	int bitsEaten = 0;
934	while (sourceLen > 0 || bitsRemaining) {
935		if (!bitsRemaining) {
936			in = cpu->memory.load8(cpu, source, 0);
937			bitsRemaining = 8;
938			++source;
939			--sourceLen;
940		}
941		unsigned scaled = in & ((1 << sourceWidth) - 1);
942		in >>= sourceWidth;
943		if (scaled || bias & 0x80000000) {
944			scaled += bias & 0x7FFFFFFF;
945		}
946		bitsRemaining -= sourceWidth;
947		out |= scaled << bitsEaten;
948		bitsEaten += destWidth;
949		if (bitsEaten == 32) {
950			cpu->memory.store32(cpu, dest, out, 0);
951			bitsEaten = 0;
952			out = 0;
953			dest += 4;
954		}
955	}
956	cpu->gprs[0] = source;
957	cpu->gprs[1] = dest;
958}