psxbios: implement some cdrom related stuff
[pcsx_rearmed.git] / libpcsxcore / psxbios.c
index 88f994f..936f076 100644 (file)
 #include "sio.h"
 #include "psxhle.h"
 #include "psxinterpreter.h"
+#include "psxevents.h"
+#include "cdrom.h"
+#include <stdarg.h>
 #include <zlib.h>
 
-#if (defined(__GNUC__) && __GNUC__ >= 5) || defined(__clang__)
-#pragma GCC diagnostic ignored "-Wpointer-sign"
-#endif
-
 #ifndef PSXBIOS_LOG
 //#define PSXBIOS_LOG printf
 #define PSXBIOS_LOG(...)
@@ -86,7 +85,7 @@ char *biosA0n[256] = {
        "dev_card_close",       "dev_card_firstfile",   "dev_card_nextfile","dev_card_erase",
        "dev_card_undelete","dev_card_format",          "dev_card_rename",      "dev_card_6f",
 // 0x70
-       "_bu_init",                     "_96_init",             "CdRemove",             "sys_a0_73",
+       "_bu_init",             "CdInit",       "CdRemove",             "sys_a0_73",
        "sys_a0_74",            "sys_a0_75",    "sys_a0_76",            "sys_a0_77",
        "_96_CdSeekL",          "sys_a0_79",    "sys_a0_7a",            "sys_a0_7b",
        "_96_CdGetStatus",      "sys_a0_7d",    "_96_CdRead",           "sys_a0_7f",
@@ -97,7 +96,7 @@ char *biosA0n[256] = {
        "sys_a0_8c",            "sys_a0_8d",    "sys_a0_8e",            "sys_a0_8f",
 // 0x90
        "sys_a0_90",            "sys_a0_91",    "sys_a0_92",            "sys_a0_93",
-       "sys_a0_94",            "sys_a0_95",    "AddCDROMDevice",       "AddMemCardDevide",
+       "sys_a0_94",            "CdReset",      "AddCDROMDevice",       "AddMemCardDevide",
        "DisableKernelIORedirection",           "EnableKernelIORedirection", "sys_a0_9a", "sys_a0_9b",
        "SetConf",                      "GetConf",              "sys_a0_9e",            "SetMem",
 // 0xa0
@@ -296,16 +295,29 @@ static u32 floodchk;
 #define A_HEAP_BASE     0x9000
 #define A_HEAP_SIZE     0x9004
 #define A_HEAP_END      0x9008
-#define A_HEAP_FLAG     0x900c
+#define A_HEAP_INIT_FLG 0x900c
 #define A_RND_SEED      0x9010
+#define A_HEAP_FRSTCHNK 0xb060
+#define A_HEAP_CURCHNK  0xb064
 #define A_CONF_TCB      0xb940
 #define A_CONF_EvCB     0xb944
 #define A_CONF_SP       0xb948
 #define A_CD_EVENTS     0xb9b8
 #define A_EXC_GP        0xf450
 
+#define A_A0_TRAPS      0x1010
+#define A_B0_TRAPS      0x2010
+#define A_C0_TRAPS      0x3010
+#define A_B0_5B_TRAP    0x43d0
+
 #define HLEOP(n) SWAPu32((0x3b << 26) | (n));
 
+static u8 loadRam8(u32 addr)
+{
+       assert(!(addr & 0x5f800000));
+       return psxM[addr & 0x1fffff];
+}
+
 static u32 loadRam32(u32 addr)
 {
        assert(!(addr & 0x5f800000));
@@ -388,14 +400,17 @@ static inline void softCall(u32 pc) {
        ra = 0x80001000;
        psxRegs.CP0.n.SR &= ~0x404; // disable interrupts
 
+       assert(psxRegs.cpuInRecursion <= 1);
+       psxRegs.cpuInRecursion++;
        psxCpu->Notify(R3000ACPU_NOTIFY_AFTER_LOAD, PTR_1);
 
-       while (pc0 != 0x80001000 && ++lim < 1000000)
+       while (pc0 != 0x80001000 && ++lim < 0x100000)
                psxCpu->ExecuteBlock(EXEC_CALLER_HLE);
 
        psxCpu->Notify(R3000ACPU_NOTIFY_BEFORE_SAVE, PTR_1);
+       psxRegs.cpuInRecursion--;
 
-       if (lim == 1000000)
+       if (lim == 0x100000)
                PSXBIOS_LOG("softCall @%x hit lim\n", pc);
        ra = sra;
        psxRegs.CP0.n.SR |= ssr & 0x404;
@@ -411,22 +426,25 @@ static inline void softCallInException(u32 pc) {
                return;
        ra = 0x80001000;
 
+       psxRegs.cpuInRecursion++;
        psxCpu->Notify(R3000ACPU_NOTIFY_AFTER_LOAD, PTR_1);
 
-       while (!returned_from_exception() && pc0 != 0x80001000 && ++lim < 1000000)
+       while (!returned_from_exception() && pc0 != 0x80001000 && ++lim < 0x100000)
                psxCpu->ExecuteBlock(EXEC_CALLER_HLE);
 
        psxCpu->Notify(R3000ACPU_NOTIFY_BEFORE_SAVE, PTR_1);
+       psxRegs.cpuInRecursion--;
 
-       if (lim == 1000000)
+       if (lim == 0x100000)
                PSXBIOS_LOG("softCallInException @%x hit lim\n", pc);
        if (pc0 == 0x80001000)
                ra = sra;
 }
 
-static u32 OpenEvent(u32 class, u32 spec, u32 mode, u32 func);
-static u32 DeliverEvent(u32 class, u32 spec);
-static u32 UnDeliverEvent(u32 class, u32 spec);
+static u32  OpenEvent(u32 class, u32 spec, u32 mode, u32 func);
+static void EnableEvent(u32 ev, int do_log);
+static u32  DeliverEvent(u32 class, u32 spec);
+static u32  UnDeliverEvent(u32 class, u32 spec);
 static void CloseEvent(u32 ev);
 
 /*                                           *
@@ -517,12 +535,8 @@ void psxBios_putc(void) // 0x09, 0x3B
        pc0 = ra;
 }
 
-void psxBios_todigit(void) // 0x0a
+static u32 do_todigit(u32 c)
 {
-       int c = a0;
-#ifdef PSXBIOS_LOG
-       PSXBIOS_LOG("psxBios_%s\n", biosA0n[0x0a]);
-#endif
        c &= 0xFF;
        if (c >= 0x30 && c < 0x3A) {
                c -= 0x30;
@@ -534,14 +548,73 @@ void psxBios_todigit(void) // 0x0a
                c = c - 0x41 + 10;
        }
        else if (c >= 0x80) {
+               log_unhandled("todigit %02x\n", c);
                c = -1;
        }
        else
        {
                c = 0x0098967F;
        }
-       v0 = c;
-       pc0 = ra;
+       use_cycles(40);
+       return c;
+}
+
+static void psxBios_todigit(void) // 0x0a
+{
+       mips_return(do_todigit(a0));
+       PSXBIOS_LOG("psxBios_%s '%c' -> %u\n", biosA0n[0x0a], a0, v0);
+}
+
+static void do_strtol(char *p, void *end_, u32 base, int can_neg) {
+       s32 n = 0, f = 0, t;
+       u32 *end = end_;
+
+       use_cycles(12);
+       if (p == INVALID_PTR) {
+               mips_return(0);
+               return;
+       }
+
+       for (; (0x09 <= *p && *p <= '\r') || *p == ' '; p++)
+               use_cycles(9);
+       if (can_neg) {
+               for (; *p == '-'; f = 1, p++)
+                       use_cycles(4);
+       }
+       if (base == 0 || base > 36)
+               base = 10;
+       if (*p == '0') {
+               switch (*p++) {
+               case 'b': case 'B': base = 2; break;
+               case 'x': case 'X': base = 16; break;
+               }
+       }
+       else if (*p == 'o' || *p == 'O') {
+               base = 8;
+               p++;
+       }
+
+       for (; (t = do_todigit(*p)) < base; p++) {
+               n = n * base + t;
+               use_cycles(12);
+       }
+
+       n = (f ? -n : n);
+       if (end != INVALID_PTR)
+               *end = SWAP32(a0 + (p - Ra0));
+       mips_return_c(n, 100);
+}
+
+static void psxBios_strtoul() { // 0x0c
+       do_strtol(a0 ? Ra0 : INVALID_PTR, a1 ? Ra1 : INVALID_PTR, a2, 0);
+       PSXBIOS_LOG("psxBios_%s %s (%x), %x, %x -> 0x%x\n",
+               biosA0n[0x0c], a0 ? Ra0 : NULL, a0, a1, a2, v0);
+}
+
+static void psxBios_strtol() { // 0x0d
+       do_strtol(a0 ? Ra0 : INVALID_PTR, a1 ? Ra1 : INVALID_PTR, a2, 1);
+       PSXBIOS_LOG("psxBios_%s %s (%x), %x, %x -> 0x%x\n",
+               biosA0n[0x0d], a0 ? Ra0 : NULL, a0, a1, a2, v0);
 }
 
 void psxBios_abs() { // 0x0e
@@ -558,6 +631,11 @@ void psxBios_atoi() { // 0x10
        s32 n = 0, f = 0;
        char *p = (char *)Ra0;
 
+       if (p == INVALID_PTR) {
+               mips_return(0);
+               return;
+       }
+
        for (;;p++) {
                switch (*p) {
                        case ' ': case '\t': continue;
@@ -573,6 +651,7 @@ void psxBios_atoi() { // 0x10
 
        v0 = (f ? -n : n);
        pc0 = ra;
+       PSXBIOS_LOG("psxBios_%s %s (%x) -> 0x%x\n", biosA0n[0x10], Ra0, a0, v0);
 }
 
 void psxBios_atol() { // 0x11
@@ -622,22 +701,24 @@ void psxBios_longjmp() { // 0x14
 }
 
 void psxBios_strcat() { // 0x15
-       char *p1 = (char *)Ra0, *p2 = (char *)Ra1;
+       u8 *p2 = (u8 *)Ra1;
+       u32 p1 = a0;
 
-#ifdef PSXBIOS_LOG
-       PSXBIOS_LOG("psxBios_%s: %s, %s\n", biosA0n[0x15], Ra0, Ra1);
-#endif
-       if (a0 == 0 || a1 == 0)
+       PSXBIOS_LOG("psxBios_%s %s (%x), %s (%x)\n", biosA0n[0x15], Ra0, a0, Ra1, a1);
+       if (a0 == 0 || a1 == 0 || p2 == INVALID_PTR)
        {
-               v0 = 0;
-               pc0 = ra;
+               mips_return_c(0, 6);
                return;
        }
-       while (*p1++);
-       --p1;
-       while ((*p1++ = *p2++) != '\0');
+       while (loadRam8(p1)) {
+               use_cycles(4);
+               p1++;
+       }
+       for (; *p2; p1++, p2++)
+               storeRam8(p1, *p2);
+       storeRam8(p1, 0);
 
-       v0 = a0; pc0 = ra;
+       mips_return_c(a0, 22);
 }
 
 void psxBios_strncat() { // 0x16
@@ -756,6 +837,7 @@ void psxBios_strncmp() { // 0x18
 
 void psxBios_strcpy() { // 0x19
        char *p1 = (char *)Ra0, *p2 = (char *)Ra1;
+       PSXBIOS_LOG("psxBios_%s %x, %s (%x)\n", biosA0n[0x19], a0, p2, a1);
        if (a0 == 0 || a1 == 0)
        {
                v0 = 0;
@@ -897,6 +979,7 @@ void psxBios_strtok() { // 0x23
 
 void psxBios_strstr() { // 0x24
        char *p = (char *)Ra0, *p1, *p2;
+       PSXBIOS_LOG("psxBios_%s %s (%x), %s (%x)\n", biosA0n[0x24], p, a0, Ra1, a1);
 
        while (*p != '\0') {
                p1 = p;
@@ -909,10 +992,12 @@ void psxBios_strstr() { // 0x24
                if (*p2 == '\0') {
                        v0 = a0 + (p - (char *)Ra0);
                        pc0 = ra;
+                       PSXBIOS_LOG(" -> %x\n", v0);
                        return;
                }
 
-               p++;
+               // bug: skips the whole matched substring + 1
+               p = p1 + 1;
        }
 
        v0 = 0; pc0 = ra;
@@ -1218,114 +1303,98 @@ void psxBios_qsort() { // 0x31
        pc0 = ra;
 }
 
-// this isn't how the real bios works, but maybe good enough
+static int malloc_heap_grow(u32 size) {
+       u32 heap_addr, heap_end, heap_addr_new;
+
+       heap_addr = loadRam32(A_HEAP_BASE);
+       heap_end = loadRam32(A_HEAP_END);
+       heap_addr_new = heap_addr + 4 + size;
+       if (heap_addr_new >= heap_end)
+               return -1;
+       storeRam32(A_HEAP_BASE, heap_addr_new);
+       storeRam32(heap_addr - 4, size | 1);
+       storeRam32(heap_addr + size, ~1); // terminator
+       return 0;
+}
+
 static void psxBios_malloc() { // 0x33
-       u32 *heap_addr, *heap_end;
-       u32 *chunk, *newchunk = NULL;
-       unsigned int dsize = 0, csize, cstat;
-       int colflag;
-       PSXBIOS_LOG("psxBios_%s %x\n", biosA0n[0x33], a0);
-       heap_addr = loadRam32ptr(A_HEAP_BASE);
-       heap_end = loadRam32ptr(A_HEAP_END);
-       if (heap_addr >= heap_end) {
-               v0 = 0;
-               pc0 = ra;
-               return;
-       }
+       u32 size = (a0 + 3) & ~3;
+       u32 limit = 32*1024;
+       u32 tries = 2, i;
+       u32 ret;
 
-       // scan through heap and combine free chunks of space
-       chunk = heap_addr;
-       colflag = 0;
-       while(chunk < heap_end) {
-               // get size and status of actual chunk
-               csize = ((u32)*chunk) & 0xfffffffc;
-               cstat = ((u32)*chunk) & 1;
-
-               // most probably broken heap descriptor
-               // this fixes Burning Road
-               if (*chunk == 0) {
-                       newchunk = chunk;
-                       dsize = ((uptr)heap_end - (uptr)chunk) - 4;
-                       colflag = 1;
-                       break;
+       PSXBIOS_LOG("psxBios_%s %d\n", biosA0n[0x33], a0);
+
+       if (!loadRam32(A_HEAP_INIT_FLG)) {
+               u32 heap_addr = loadRam32(A_HEAP_BASE);
+               storeRam32(heap_addr, ~1);
+               storeRam32(A_HEAP_FRSTCHNK, heap_addr);
+               storeRam32(A_HEAP_CURCHNK, heap_addr);
+               storeRam32(A_HEAP_BASE, heap_addr + 4);
+               if (malloc_heap_grow(size)) {
+                       PSXBIOS_LOG("malloc: init OOM\n");
+                       mips_return_c(0, 20);
+                       return;
                }
+               storeRam32(A_HEAP_INIT_FLG, 1);
+       }
 
-               // it's a free chunk
-               if(cstat == 1) {
-                       if(colflag == 0) {
-                               newchunk = chunk;
-                               dsize = csize;
-                               colflag = 1;                    // let's begin a new collection of free memory
+       for (i = 0; tries > 0 && i < limit; i++)
+       {
+               u32 chunk = loadRam32(A_HEAP_CURCHNK);
+               u32 chunk_hdr = loadRam32(chunk);
+               u32 next_chunk = chunk + 4 + (chunk_hdr & ~3);
+               u32 next_chunk_hdr = loadRam32(next_chunk);
+               use_cycles(20);
+               //printf(" c %08x %08x\n", chunk, chunk_hdr);
+               if (chunk_hdr & 1) {
+                       // free chunk
+                       if (chunk_hdr > (size | 1)) {
+                               // split
+                               u32 p2size = (chunk_hdr & ~3) - size - 4;
+                               storeRam32(chunk + 4 + size, p2size | 1);
+                               chunk_hdr = size | 1;
+                       }
+                       if (chunk_hdr == (size | 1)) {
+                               storeRam32(chunk, size);
+                               break;
+                       }
+                       // chunk too small
+                       if (next_chunk_hdr & 1) {
+                               // merge
+                               u32 msize = (chunk_hdr & ~3) + 4 + (next_chunk_hdr & ~3);
+                               storeRam32(chunk, msize | 1);
+                               continue;
                        }
-                       else dsize += (csize+4);        // add the new size including header
                }
-               // not a free chunk: did we start a collection ?
+               if (chunk_hdr == ~1) {
+                       // last chunk
+                       if (tries == 2)
+                               storeRam32(A_HEAP_CURCHNK, loadRam32(A_HEAP_FRSTCHNK));
+                       tries--;
+               }
                else {
-                       if(colflag == 1) {                      // collection is over
-                               colflag = 0;
-                               *newchunk = SWAP32(dsize | 1);
-                       }
+                       // go to the next chunk
+                       storeRam32(A_HEAP_CURCHNK, next_chunk);
                }
-
-               // next chunk
-               chunk = (u32*)((uptr)chunk + csize + 4);
-       }
-       // if neccessary free memory on end of heap
-       if (colflag == 1)
-               *newchunk = SWAP32(dsize | 1);
-
-       chunk = heap_addr;
-       csize = ((u32)*chunk) & 0xfffffffc;
-       cstat = ((u32)*chunk) & 1;
-       dsize = (a0 + 3) & 0xfffffffc;
-
-       // exit on uninitialized heap
-       if (chunk == NULL) {
-               printf("malloc %x,%x: Uninitialized Heap!\n", v0, a0);
-               v0 = 0;
-               pc0 = ra;
-               return;
-       }
-
-       // search an unused chunk that is big enough until the end of the heap
-       while ((dsize > csize || cstat==0) && chunk < heap_end ) {
-               chunk = (u32*)((uptr)chunk + csize + 4);
-
-                       // catch out of memory
-                       if(chunk >= heap_end) {
-                               printf("malloc %x,%x: Out of memory error!\n",
-                                       v0, a0);
-                               v0 = 0; pc0 = ra;
-                               return;
-                       }
-
-               csize = ((u32)*chunk) & 0xfffffffc;
-               cstat = ((u32)*chunk) & 1;
        }
 
-       // allocate memory
-       if(dsize == csize) {
-               // chunk has same size
-               *chunk &= 0xfffffffc;
-       } else if (dsize > csize) {
-               v0 = 0; pc0 = ra;
-               return;
-       } else {
-               // split free chunk
-               *chunk = SWAP32(dsize);
-               newchunk = (u32*)((uptr)chunk + dsize + 4);
-               *newchunk = SWAP32(((csize - dsize - 4) & 0xfffffffc) | 1);
+       if (i == limit)
+               ret = 0;
+       else if (tries == 0 && malloc_heap_grow(size))
+               ret = 0;
+       else {
+               u32 chunk = loadRam32(A_HEAP_CURCHNK);
+               storeRam32(chunk, loadRam32(chunk) & ~3);
+               ret = chunk + 4;
        }
 
-       // return pointer to allocated memory
-       v0 = ((uptr)chunk - (uptr)psxM) + 4;
-       v0|= 0x80000000;
-       //printf ("malloc %x,%x\n", v0, a0);
-       pc0 = ra;
+       PSXBIOS_LOG(" -> %08x\n", ret);
+       mips_return_c(ret, 40);
 }
 
 static void psxBios_free() { // 0x34
-       PSXBIOS_LOG("psxBios_%s %x (%x bytes)\n", biosA0n[0x34], a0, loadRam32(a0 - 4));
+       PSXBIOS_LOG("psxBios_%s %x (%d bytes)\n", biosA0n[0x34], a0, loadRam32(a0 - 4));
        storeRam32(a0 - 4, loadRam32(a0 - 4) | 1); // set chunk to free
        mips_return_void_c(5);
 }
@@ -1380,7 +1449,7 @@ static void psxBios_InitHeap() { // 0x39
        storeRam32(A_HEAP_BASE, a0);
        storeRam32(A_HEAP_SIZE, a1);
        storeRam32(A_HEAP_END, a0 + (a1 & ~3) + 4);
-       storeRam32(A_HEAP_FLAG, 0);
+       storeRam32(A_HEAP_INIT_FLG, 0);
        storeRam32(a0, 0);
 
        mips_return_void_c(14);
@@ -1393,7 +1462,7 @@ void psxBios_getchar() { //0x3b
 static void psxBios_printf_psxout() { // 0x3f
        char tmp[1024];
        char tmp2[1024];
-       u32 save[4];
+       u32 save[4] = { 0, };
        char *ptmp = tmp;
        int n=1, i=0, j;
        void *psp;
@@ -1468,13 +1537,15 @@ void psxBios_printf() { // 0x3f
 }
 
 static void psxBios_cd() { // 0x40
-       const char *p, *dir = castRam8ptr(a0);
+       const char *p, *dir = Ra0;
        PSXBIOS_LOG("psxBios_%s %x(%s)\n", biosB0n[0x40], a0, dir);
-       if ((p = strchr(dir, ':')))
-               dir = ++p;
-       if (*dir == '\\')
-               dir++;
-       snprintf(cdir, sizeof(cdir), "%s", dir);
+       if (dir != INVALID_PTR) {
+               if ((p = strchr(dir, ':')))
+                       dir = ++p;
+               if (*dir == '\\')
+                       dir++;
+               snprintf(cdir, sizeof(cdir), "%s", dir);
+       }
        mips_return_c(1, 100);
 }
 
@@ -1515,11 +1586,53 @@ static void FlushCache() {
        use_cycles(500);
 }
 
+// you likely want to mask irqs before calling these
+static u8 cdrom_sync(int do_ack)
+{
+       u8 r = 0;
+       if (psxRegs.interrupt & (1u << PSXINT_CDR)) {
+               if ((s32)(psxRegs.cycle - event_cycles[PSXINT_CDR]) < 0)
+                       psxRegs.cycle = event_cycles[PSXINT_CDR] + 1;
+               irq_test(&psxRegs.CP0);
+       }
+       if (do_ack) {
+               cdrWrite0(1);
+               r = cdrRead3() & 0x1f;
+               cdrWrite3(0x5f); // ack; clear params
+       }
+       return r;
+}
+
+static void cdrom_cmd_and_wait(u8 cmd, int arg_cnt, int resp_cnt, ...)
+{
+       va_list ap;
+
+       cdrom_sync(0);
+       cdrWrite0(0);
+       va_start(ap, resp_cnt);
+       while (arg_cnt-- > 0)
+               cdrWrite2(va_arg(ap, u32));
+       va_end(ap);
+       cdrWrite1(cmd);
+
+       if (resp_cnt > 0) {
+               u8 r = cdrom_sync(1);
+               assert(r == 3); (void)r;
+               cdrRead1();
+       }
+       if (resp_cnt > 1) {
+               u8 r = cdrom_sync(1);
+               assert(r == 2); (void)r;
+               cdrRead1();
+       }
+}
+
 /*
  *     long Load(char *name, struct EXEC *header);
  */
 
 void psxBios_Load() { // 0x42
+       u8 time[3] = { 2, 0, 0x16 };
        EXE_HEADER eheader;
        char path[256];
        char *pa0, *p;
@@ -1541,7 +1654,7 @@ void psxBios_Load() { // 0x42
        else
                snprintf(path, sizeof(path), "%s", (char *)pa0);
 
-       if (LoadCdromFile(path, &eheader) == 0) {
+       if (LoadCdromFile(path, &eheader, time) == 0) {
                memcpy(pa1, ((char*)&eheader)+16, sizeof(EXEC));
                psxCpu->Clear(a1, sizeof(EXEC) / 4);
                FlushCache();
@@ -1550,6 +1663,17 @@ void psxBios_Load() { // 0x42
        PSXBIOS_LOG(" -> %d\n", v0);
 
        pc0 = ra;
+
+       // set the cdrom to a state of just after exe read
+       psxRegs.CP0.n.SR &= ~0x404;
+       cdrom_sync(1);
+       cdrWrite0(1);
+       cdrWrite2(0x1f); // unmask
+       cdrom_cmd_and_wait(0x0e, 1, 1, 0x80u); // CdlSetmode
+       cdrom_cmd_and_wait(0x02, 3, 1, time[0], time[1], time[2]); // CdlSetloc
+       cdrom_cmd_and_wait(0x15, 0, 2); // CdlSeekL
+       psxHwWrite16(0x1f801070, ~4);
+       MTC0(&psxRegs, 12, psxRegs.CP0.n.SR | 0x404);
 }
 
 /*
@@ -1618,6 +1742,14 @@ void psxBios_GPU_dw() { // 0x46
        pc0 = ra;
 }
 
+static void gpu_sync() {
+       // not implemented...
+       // might be problematic to do because of Config.GpuListWalking
+       if (psxRegs.interrupt & (1u << PSXINT_GPUDMA))
+               log_unhandled("gpu_sync with active dma\n");
+       mips_return_c(0, 21);
+}
+
 void psxBios_mem2vram() { // 0x47
        int size;
        gpuSyncPluginSR(); // flush
@@ -1644,8 +1776,8 @@ void psxBios_SendGPU() { // 0x48
 void psxBios_GPU_cw() { // 0x49
        GPU_writeData(a0);
        gpuSyncPluginSR();
-       v0 = HW_GPU_STATUS;
-       pc0 = ra;
+       use_cycles(13);
+       gpu_sync();
 }
 
 void psxBios_GPU_cwb() { // 0x4a
@@ -1717,24 +1849,86 @@ void psxBios__bu_init() { // 70
        pc0 = ra;
 }
 
-void psxBios__96_init() { // 71
-#ifdef PSXBIOS_LOG
-       PSXBIOS_LOG("psxBios_%s\n", biosA0n[0x71]);
-#endif
-
-       pc0 = ra;
-}
-
 static void write_chain(u32 *d, u32 next, u32 handler1, u32 handler2);
 static void psxBios_SysEnqIntRP_(u32 priority, u32 chain_eptr);
 static void psxBios_SysDeqIntRP_(u32 priority, u32 chain_rm_eptr);
 
+static void psxBios_EnqueueCdIntr_(void)
+{
+       u32 *ram32 = (u32 *)psxM;
+
+       // traps should already be installed by write_chain()
+       ram32[0x91d0/4] = 0;
+       ram32[0x91d4/4] = SWAP32(0xbfc0506c);
+       ram32[0x91d8/4] = SWAP32(0xbfc04dec);
+       psxBios_SysEnqIntRP_(0, 0x91d0);
+       ram32[0x91e0/4] = 0;
+       ram32[0x91e4/4] = SWAP32(0xbfc050a4);
+       ram32[0x91e8/4] = SWAP32(0xbfc04fbc);
+       psxBios_SysEnqIntRP_(0, 0x91e0);
+       use_cycles(31);
+}
+
+static void setup_cd_irq_and_events(void)
+{
+       u16 specs[] = { 0x10, 0x20, 0x40, 0x80, 0x8000 };
+       size_t i;
+
+       psxBios_EnqueueCdIntr_();
+
+       for (i = 0; i < sizeof(specs) / sizeof(specs[0]); i++) {
+               u32 h = OpenEvent(0xf0000003, specs[i], EvMdMARK, 0);
+               // no error checks
+               storeRam32(A_CD_EVENTS + i * 4, h);
+               EnableEvent(h, 0);
+       }
+}
+
+static void psxBios_CdReset_() {
+       psxRegs.CP0.n.SR &= ~0x404; // disable interrupts
+
+       cdrom_sync(1);
+       cdrWrite0(1);
+       cdrWrite2(0x1f); // unmask
+       cdrom_cmd_and_wait(0x0a, 0, 2); // CdlReset
+       cdrom_cmd_and_wait(0x0e, 1, 1, 0x80u); // CdlSetmode
+
+       // todo(?): should read something (iso root directory?)
+       // from { 0, 2, 16 } to somewhere and pause
+
+       mips_return(1);
+       psxHwWrite16(0x1f801070, ~4);
+       MTC0(&psxRegs, 12, psxRegs.CP0.n.SR | 0x404);
+       DeliverEvent(0xf0000003, 0x0020);
+}
+
+static void psxBios_CdInit() { // 54, 71
+       PSXBIOS_LOG("psxBios_%s\n", biosA0n[0x71]);
+       setup_cd_irq_and_events();
+
+       psxBios_CdReset_();
+
+       // this function takes pretty much forever
+       mips_return_c(0, 50000*11);
+}
+
 static void psxBios_DequeueCdIntr_() {
        psxBios_SysDeqIntRP_(0, 0x91d0);
        psxBios_SysDeqIntRP_(0, 0x91e0);
        use_cycles(16);
 }
 
+static void psxBios_CdReset() { // 95
+       PSXBIOS_LOG("psxBios_%s\n", biosA0n[0x95]);
+       psxBios_CdReset_();
+}
+
+static void psxBios_EnqueueCdIntr() { // a2
+       PSXBIOS_LOG("psxBios_%s\n", biosA0n[0xa2]);
+       psxBios_EnqueueCdIntr_();
+       // return value comes from SysEnqIntRP() insternal call
+}
+
 static void psxBios_DequeueCdIntr() { // a3
        PSXBIOS_LOG("psxBios_%s\n", biosA0n[0xa3]);
        psxBios_DequeueCdIntr_();
@@ -2104,13 +2298,17 @@ static void psxBios_TestEvent() { // 0b
        mips_return_c(ret, 15);
 }
 
-static void psxBios_EnableEvent() { // 0c
+static void EnableEvent(u32 ev, int do_log) {
        u32 base = loadRam32(A_TT_EvCB);
-       u32 status = loadRam32(base + (a0 & 0xffff) * sizeof(EvCB) + 4);
-       PSXBIOS_LOG("psxBios_%s %x (%x)\n", biosB0n[0x0c], a0, status);
+       u32 status = loadRam32(base + (ev & 0xffff) * sizeof(EvCB) + 4);
+       if (do_log)
+               PSXBIOS_LOG("psxBios_%s %x (%x)\n", biosB0n[0x0c], ev, status);
        if (status != EvStUNUSED)
-               storeRam32(base + (a0 & 0xffff) * sizeof(EvCB) + 4, EvStACTIVE);
+               storeRam32(base + (ev & 0xffff) * sizeof(EvCB) + 4, EvStACTIVE);
+}
 
+static void psxBios_EnableEvent() { // 0c
+       EnableEvent(a0, 1);
        mips_return_c(1, 15);
 }
 
@@ -2555,7 +2753,7 @@ void psxBios_puts() { // 3e/3f
 }
 
 static void bufile(const u8 *mcd_data, u32 dir_) {
-       struct DIRENTRY *dir = (struct DIRENTRY *)castRam8ptr(dir_);
+       struct DIRENTRY *dir = (struct DIRENTRY *)PSXM(dir_);
        const char *pfile = ffile + 5;
        const u8 *data = mcd_data;
        int i = 0, match = 0;
@@ -2563,6 +2761,9 @@ static void bufile(const u8 *mcd_data, u32 dir_) {
        u32 head = 0;
 
        v0 = 0;
+       if (dir == INVALID_PTR)
+               return;
+
        for (; nfile <= 15 && !match; nfile++) {
                const char *name;
 
@@ -2596,7 +2797,7 @@ static void bufile(const u8 *mcd_data, u32 dir_) {
        }
        for (; nfile <= 15; nfile++, blocks++) {
                const u8 *data2 = mcd_data + 128 * nfile;
-               const char *name = data2 + 0x0a;
+               const char *name = (const char *)data2 + 0x0a;
                if ((data2[0] & 0xF0) != 0x50 || name[0])
                        break;
        }
@@ -2616,11 +2817,12 @@ static void bufile(const u8 *mcd_data, u32 dir_) {
  */
 
 static void psxBios_firstfile() { // 42
-       char *pa0 = castRam8ptr(a0);
+       char *pa0 = Ra0;
 
        PSXBIOS_LOG("psxBios_%s %s %x\n", biosB0n[0x42], pa0, a1);
        v0 = 0;
 
+       if (pa0 != INVALID_PTR)
        {
                snprintf(ffile, sizeof(ffile), "%s", pa0);
                if (ffile[5] == 0)
@@ -2629,11 +2831,11 @@ static void psxBios_firstfile() { // 42
                if (!strncmp(pa0, "bu00", 4)) {
                        // firstfile() calls _card_read() internally, so deliver it's event
                        DeliverEvent(0xf0000011, 0x0004);
-                       bufile(Mcd1Data, a1);
+                       bufile((u8 *)Mcd1Data, a1);
                } else if (!strncmp(pa0, "bu10", 4)) {
                        // firstfile() calls _card_read() internally, so deliver it's event
                        DeliverEvent(0xf0000011, 0x0004);
-                       bufile(Mcd2Data, a1);
+                       bufile((u8 *)Mcd2Data, a1);
                }
        }
 
@@ -2649,9 +2851,9 @@ void psxBios_nextfile() { // 43
 
        v0 = 0;
        if (!strncmp(ffile, "bu00", 4))
-               bufile(Mcd1Data, a0);
+               bufile((u8 *)Mcd1Data, a0);
        else if (!strncmp(ffile, "bu10", 4))
-               bufile(Mcd2Data, a0);
+               bufile((u8 *)Mcd2Data, a0);
 
        pc0 = ra;
 }
@@ -2967,7 +3169,8 @@ static void psxBios_InitRCnt() { // 00
                psxHwWrite16(0x1f801100 + i*0x10 + 8, 0);
                psxHwWrite16(0x1f801100 + i*0x10 + 0, 0);
        }
-       psxBios_SysEnqIntRP_(a0, 0x6d88);
+       for (i = 0; i < 4; i++)
+               psxBios_SysEnqIntRP_(a0, 0x6d58 + i * 0x10);
        mips_return_c(0, 9);
 }
 
@@ -3207,7 +3410,7 @@ static void setup_tt(u32 tcb_cnt, u32 evcb_cnt, u32 stack)
        ram32[0x0150/4] = SWAPu32(0x6ee0);  // DCB - device control
        ram32[0x0154/4] = SWAPu32(0x0320);  // DCB size
 
-       storeRam32(p_excb + 0*4, 0x91e0);   // chain0
+       storeRam32(p_excb + 0*4, 0x0000);   // chain0
        storeRam32(p_excb + 2*4, 0x6d88);   // chain1
        storeRam32(p_excb + 4*4, 0x0000);   // chain2
        storeRam32(p_excb + 6*4, 0x6d98);   // chain3
@@ -3217,12 +3420,8 @@ static void setup_tt(u32 tcb_cnt, u32 evcb_cnt, u32 stack)
        for (i = 1; i < tcb_cnt; i++)
                storeRam32(p_tcb + sizeof(TCB) * i, 0x1000);
 
-       // default events
-       storeRam32(A_CD_EVENTS + 0x00, OpenEvent(0xf0000003, 0x0010, EvMdMARK, 0));
-       storeRam32(A_CD_EVENTS + 0x04, OpenEvent(0xf0000003, 0x0020, EvMdMARK, 0));
-       storeRam32(A_CD_EVENTS + 0x08, OpenEvent(0xf0000003, 0x0040, EvMdMARK, 0));
-       storeRam32(A_CD_EVENTS + 0x0c, OpenEvent(0xf0000003, 0x0080, EvMdMARK, 0));
-       storeRam32(A_CD_EVENTS + 0x10, OpenEvent(0xf0000003, 0x8000, EvMdMARK, 0));
+       psxBios_SysEnqIntRP_(0, 0x6da8);
+       setup_cd_irq_and_events();
 
        storeRam32(A_CONF_EvCB, evcb_cnt);
        storeRam32(A_CONF_TCB, tcb_cnt);
@@ -3305,20 +3504,27 @@ void psxBiosSetupBootState(void)
                GPU_writeStatus(gpu_ctl_def[i]);
        for (i = 0; i < sizeof(gpu_data_def) / sizeof(gpu_data_def[0]); i++)
                GPU_writeData(gpu_data_def[i]);
-       HW_GPU_STATUS |= SWAP32(PSXGPU_nBUSY);
 
        // spu
        for (i = 0x1f801d80; i < sizeof(spu_config) / sizeof(spu_config[0]); i++)
                SPU_writeRegister(0x1f801d80 + i*2, spu_config[i], psxRegs.cycle);
 }
 
+static void hleExc0_0_1();
+static void hleExc0_0_2();
+static void hleExc0_1_1();
+static void hleExc0_1_2();
+
 #include "sjisfont.h"
 
 void psxBiosInit() {
        u32 *ptr, *ram32, *rom32;
+       char *romc;
        int i;
        uLongf len;
 
+       psxRegs.biosBranchCheck = ~0;
+
        memset(psxM, 0, 0x10000);
        for(i = 0; i < 256; i++) {
                biosA0[i] = NULL;
@@ -3330,7 +3536,15 @@ void psxBiosInit() {
        biosA0[0x3e] = biosB0[0x3f] = psxBios_puts_psxout;
        biosA0[0x3f] = psxBios_printf_psxout;
 
-       if (!Config.HLE) return;
+       if (!Config.HLE) {
+               char verstr[0x24+1];
+               rom32 = (u32 *)psxR;
+               memcpy(verstr, psxR + 0x12c, 0x24);
+               verstr[0x24] = 0;
+               SysPrintf("BIOS: %08x, '%s', '%c'\n", SWAP32(rom32[0x100/4]),
+                       verstr, psxR[0x7ff52]);
+               return;
+       }
 
        for(i = 0; i < 256; i++) {
                if (biosA0[i] == NULL) biosA0[i] = psxBios_dummy;
@@ -3350,8 +3564,8 @@ void psxBiosInit() {
        biosA0[0x09] = psxBios_putc;
        biosA0[0x0a] = psxBios_todigit;
        //biosA0[0x0b] = psxBios_atof;
-       //biosA0[0x0c] = psxBios_strtoul;
-       //biosA0[0x0d] = psxBios_strtol;
+       biosA0[0x0c] = psxBios_strtoul;
+       biosA0[0x0d] = psxBios_strtol;
        biosA0[0x0e] = psxBios_abs;
        biosA0[0x0f] = psxBios_labs;
        biosA0[0x10] = psxBios_atoi;
@@ -3422,7 +3636,7 @@ void psxBiosInit() {
        biosA0[0x51] = psxBios_LoadExec;
        //biosA0[0x52] = psxBios_GetSysSp;
        //biosA0[0x53] = psxBios_sys_a0_53;
-       //biosA0[0x54] = psxBios__96_init_a54;
+       biosA0[0x54] = psxBios_CdInit;
        //biosA0[0x55] = psxBios__bu_init_a55;
        biosA0[0x56] = psxBios_CdRemove;
        //biosA0[0x57] = psxBios_sys_a0_57;
@@ -3451,7 +3665,7 @@ void psxBiosInit() {
        //biosA0[0x6e] = psxBios_dev_card_rename;
        //biosA0[0x6f] = psxBios_dev_card_6f;
        biosA0[0x70] = psxBios__bu_init;
-       biosA0[0x71] = psxBios__96_init;
+       biosA0[0x71] = psxBios_CdInit;
        biosA0[0x72] = psxBios_CdRemove;
        //biosA0[0x73] = psxBios_sys_a0_73;
        //biosA0[0x74] = psxBios_sys_a0_74;
@@ -3487,7 +3701,7 @@ void psxBiosInit() {
        biosA0[0x92] = hleExc0_1_1;
        biosA0[0x93] = hleExc0_0_1;
        //biosA0[0x94] = psxBios_sys_a0_94;
-       //biosA0[0x95] = psxBios_sys_a0_95;
+       biosA0[0x95] = psxBios_CdReset;
        //biosA0[0x96] = psxBios_AddCDROMDevice;
        //biosA0[0x97] = psxBios_AddMemCardDevide;
        //biosA0[0x98] = psxBios_DisableKernelIORedirection;
@@ -3500,7 +3714,7 @@ void psxBiosInit() {
        biosA0[0x9f] = psxBios_SetMem;
        //biosA0[0xa0] = psxBios__boot;
        //biosA0[0xa1] = psxBios_SystemError;
-       //biosA0[0xa2] = psxBios_EnqueueCdIntr;
+       biosA0[0xa2] = psxBios_EnqueueCdIntr;
        biosA0[0xa3] = psxBios_DequeueCdIntr;
        //biosA0[0xa4] = psxBios_sys_a0_a4;
        //biosA0[0xa5] = psxBios_ReadSector;
@@ -3656,10 +3870,11 @@ void psxBiosInit() {
        rom32 = (u32 *)psxR;
        rom32[0x100/4] = SWAP32(0x19951204);
        rom32[0x104/4] = SWAP32(3);
-       strcpy(psxR + 0x108, "PCSX authors");
-       strcpy(psxR + 0x12c, "CEX-3000 PCSX HLE"); // see psxBios_GetSystemInfo
-       strcpy(psxR + 0x7ff32, "System ROM Version 2.2 12/04/95 A");
-       strcpy(psxR + 0x7ff54, "GPL-2.0-or-later");
+       romc = (char *)psxR;
+       strcpy(romc + 0x108, "PCSX authors");
+       strcpy(romc + 0x12c, "CEX-3000 PCSX HLE"); // see psxBios_GetSystemInfo
+       strcpy(romc + 0x7ff32, "System ROM Version 2.2 12/04/95 A");
+       strcpy(romc + 0x7ff54, "GPL-2.0-or-later");
 
        // fonts
        len = 0x80000 - 0x66000;
@@ -3706,6 +3921,7 @@ void psxBiosInit() {
        strcpy((char *)&ram32[0xeff0/4], "bu");
 
        // default exception handler chains
+       // see also setup_cd_irq_and_events()
        write_chain(&ram32[0x91e0/4], 0x91d0, 0xbfc050a4, 0xbfc04fbc); // chain0.e0
        write_chain(&ram32[0x91d0/4], 0x6da8, 0xbfc0506c, 0xbfc04dec); // chain0.e1
        write_chain(&ram32[0x6da8/4],      0,          0,     0x1a00); // chain0.e2
@@ -3719,18 +3935,25 @@ void psxBiosInit() {
 
        // fill the api jumptables with fake entries as some games patch them
        // (or rather the funcs listed there)
+       // also trap the destination as some "Cheats Edition" thing overrides the
+       // dispatcher with a wrapper and then jumps to the table entries directly
        ptr = (u32 *)&psxM[A_A0_TABLE];
-       for (i = 0; i < 256; i++)
-               ptr[i] = SWAP32(0x1000);
-
+       for (i = 0; i < 256; i++) {
+               ptr[i] = SWAP32(A_A0_TRAPS + i*4);
+               ram32[A_A0_TRAPS/4 + i] = HLEOP(hleop_a0t);
+       }
        ptr = (u32 *)&psxM[A_B0_TABLE];
-       for (i = 0; i < 256; i++)
-               ptr[i] = SWAP32(0x2000);
+       for (i = 0; i < 256; i++) {
+               ptr[i] = SWAP32(A_B0_TRAPS + i*4);
+               ram32[A_B0_TRAPS/4 + i] = HLEOP(hleop_b0t);
+       }
        // B(5b) is special because games patch (sometimes even jump to)
        // code at fixed offsets from it, nocash lists offsets:
        //  patch: +3d8, +4dc, +594, +62c, +9c8, +1988
        //  call:  +7a0=4b70, +884=4c54, +894=4c64
-       ptr[0x5b] = SWAP32(0x43d0);
+       ptr[0x5b] = SWAP32(A_B0_5B_TRAP);     // 0x43d0
+       ram32[A_B0_5B_TRAP/4] = HLEOP(hleop_b0t);
+
        ram32[0x4b70/4] = SWAP32(0x03e00008); // jr $ra // setPadOutputBuf
 
        ram32[0x4c54/4] = SWAP32(0x240e0001); // mov $t6, 1
@@ -3741,14 +3964,17 @@ void psxBiosInit() {
        ram32[0x4c68/4] = SWAP32(0xac000000 + A_PAD_IRQR_ENA); // sw $0, ...
 
        ptr = (u32 *)&psxM[A_C0_TABLE];
-       for (i = 0; i < 256/2; i++)
-               ptr[i] = SWAP32(0x3000);
+       for (i = 0; i < 256/2; i++) {
+               ptr[i] = SWAP32(A_C0_TRAPS + i*4);
+               ram32[A_C0_TRAPS/4 + i] = HLEOP(hleop_c0t);
+       }
        ptr[6] = SWAP32(A_EXCEPTION);
 
        // more HLE traps
-       ram32[0x1000/4] = HLEOP(hleop_dummy);
-       ram32[0x2000/4] = HLEOP(hleop_dummy);
-       ram32[0x3000/4] = HLEOP(hleop_dummy);
+       ram32[A_A0_TRAPS/4 - 1] = HLEOP(hleop_dummy);
+       ram32[A_B0_TRAPS/4 - 1] = HLEOP(hleop_dummy);
+       ram32[A_C0_TRAPS/4 - 1] = HLEOP(hleop_dummy);
+       ram32[0x7ffc/4] = HLEOP(hleop_dummy);
        ram32[0x8000/4] = HLEOP(hleop_execret);
 
        ram32[A_EEXIT_PTR/4] = SWAP32(A_EEXIT_DEF);
@@ -3775,8 +4001,10 @@ void psxBiosCnfLoaded(u32 tcb_cnt, u32 evcb_cnt, u32 stack) {
 
 #define psxBios_PADpoll(pad) { \
        int i, more_data = 0; \
-       pad_buf##pad[0] = PAD##pad##_startPoll(pad); \
+       PAD##pad##_startPoll(pad); \
        pad_buf##pad[1] = PAD##pad##_poll(0x42, &more_data); \
+       pad_buf##pad[0] = more_data ? 0 : 0xff; \
+       PAD##pad##_poll(0, &more_data); \
        i = 2; \
        while (more_data) { \
                pad_buf##pad[i++] = PAD##pad##_poll(0, &more_data); \
@@ -3796,13 +4024,13 @@ static void handle_chain_x_x_1(u32 enable, u32 irqbit)
 
 // hleExc0_{0,1}* are usually removed by A(56)/A(72) on the game's startup,
 // so this is only partially implemented
-void hleExc0_0_1() // A(93h) - CdromDmaIrqFunc2
+static void hleExc0_0_1() // A(93h) - CdromDmaIrqFunc2
 {
        u32 cdrom_dma_ack_enable = 1; // a000b93c
        handle_chain_x_x_1(cdrom_dma_ack_enable, 3); // IRQ3 DMA
 }
 
-void hleExc0_0_2() // A(91h) - CdromDmaIrqFunc1
+static void hleExc0_0_2() // A(91h) - CdromDmaIrqFunc1
 {
        u32 ret = 0;
        //PSXBIOS_LOG("%s\n", __func__);
@@ -3817,13 +4045,13 @@ void hleExc0_0_2() // A(91h) - CdromDmaIrqFunc1
        mips_return_c(ret, 20);
 }
 
-void hleExc0_1_1() // A(92h) - CdromIoIrqFunc2
+static void hleExc0_1_1() // A(92h) - CdromIoIrqFunc2
 {
        u32 cdrom_irq_ack_enable = 1; // a000b938
        handle_chain_x_x_1(cdrom_irq_ack_enable, 2); // IRQ2 cdrom
 }
 
-void hleExc0_1_2() // A(90h) - CdromIoIrqFunc1
+static void hleExc0_1_2() // A(90h) - CdromIoIrqFunc1
 {
        u32 ret = 0;
        if (psxHu32(0x1074) & psxHu32(0x1070) & 4) { // IRQ2 cdrom
@@ -3833,7 +4061,7 @@ void hleExc0_1_2() // A(90h) - CdromIoIrqFunc1
        mips_return_c(ret, 20);
 }
 
-void hleExc0_2_2_syscall() // not in any A/B/C table
+static void hleExc0_2_2_syscall() // not in any A/B/C table
 {
        u32 tcbPtr = loadRam32(A_TT_PCB);
        TCB *tcb = loadRam32ptr(tcbPtr);
@@ -3877,7 +4105,7 @@ void hleExc0_2_2_syscall() // not in any A/B/C table
        psxBios_ReturnFromException();
 }
 
-void hleExc1_0_1(void)
+static void hleExc1_0_1(void)
 {
        u32 vbl_irq_ack_enable = loadRam32(A_RCNT_VBL_ACK + 0x0c); // 860c
        handle_chain_x_x_1(vbl_irq_ack_enable, 0); // IRQ0 vblank
@@ -3893,45 +4121,45 @@ static void handle_chain_1_x_2(u32 ev_index, u32 irqbit)
        mips_return_c(ret, 22);
 }
 
-void hleExc1_0_2(void)
+static void hleExc1_0_2(void)
 {
        handle_chain_1_x_2(3, 0); // IRQ0 vblank
 }
 
-void hleExc1_1_1(void)
+static void hleExc1_1_1(void)
 {
        u32 rcnt_irq_ack_enable = loadRam32(A_RCNT_VBL_ACK + 0x08); // 8608
        handle_chain_x_x_1(rcnt_irq_ack_enable, 6); // IRQ6 rcnt2
 }
 
-void hleExc1_1_2(void)
+static void hleExc1_1_2(void)
 {
        handle_chain_1_x_2(2, 6); // IRQ6 rcnt2
 }
 
-void hleExc1_2_1(void)
+static void hleExc1_2_1(void)
 {
        u32 rcnt_irq_ack_enable = loadRam32(A_RCNT_VBL_ACK + 0x04); // 8604
        handle_chain_x_x_1(rcnt_irq_ack_enable, 5); // IRQ5 rcnt1
 }
 
-void hleExc1_2_2(void)
+static void hleExc1_2_2(void)
 {
        handle_chain_1_x_2(1, 5); // IRQ5 rcnt1
 }
 
-void hleExc1_3_1(void)
+static void hleExc1_3_1(void)
 {
        u32 rcnt_irq_ack_enable = loadRam32(A_RCNT_VBL_ACK + 0x00); // 8600
        handle_chain_x_x_1(rcnt_irq_ack_enable, 4); // IRQ4 rcnt0
 }
 
-void hleExc1_3_2(void)
+static void hleExc1_3_2(void)
 {
        handle_chain_1_x_2(0, 4); // IRQ4 rcnt0
 }
 
-void hleExc3_0_2_defint(void)
+static void hleExc3_0_2_defint(void)
 {
        static const struct {
                u8 ev, irqbit;
@@ -3959,7 +4187,7 @@ void hleExc3_0_2_defint(void)
        mips_return_c(0, 11 + 7*11 + 7*11 + 12);
 }
 
-void hleExcPadCard1(void)
+static void hleExcPadCard1(void)
 {
        if (loadRam32(A_PAD_IRQR_ENA)) {
                u8 *pad_buf1 = loadRam8ptr(A_PAD_INBUF + 0);
@@ -3980,7 +4208,7 @@ void hleExcPadCard1(void)
        mips_return_c(0, 18);
 }
 
-void hleExcPadCard2(void)
+static void hleExcPadCard2(void)
 {
        u32 ret = psxHu32(0x1074) & psxHu32(0x1070) & 1;
        mips_return_c(ret, 15);
@@ -4009,6 +4237,7 @@ void psxBiosException() {
        sp = fp = loadRam32(A_EXC_SP);
        gp = A_EXC_GP;
        use_cycles(46);
+       assert(!psxRegs.cpuInRecursion);
 
        // do the chains (always 4)
        for (c = lim = 0; c < 4; c++) {
@@ -4047,6 +4276,223 @@ void psxBiosException() {
        psxBios_ReturnFromException();
 }
 
+/* HLE */
+static void hleDummy() {
+       log_unhandled("hleDummy called @%08x ra=%08x\n", psxRegs.pc - 4, ra);
+       psxRegs.pc = ra;
+       psxRegs.cycle += 1000;
+
+       psxBranchTest();
+}
+
+static void hleA0() {
+       u32 call = t1 & 0xff;
+       u32 entry = loadRam32(A_A0_TABLE + call * 4);
+
+       use_cycles(4+7);
+       if (call < 192 && entry != A_A0_TRAPS + call * 4) {
+               PSXBIOS_LOG("custom A%02x %s(0x%x, )  addr=%08x ra=%08x\n",
+                       call, biosA0n[call], a0, entry, ra);
+               softCall(entry);
+               pc0 = ra;
+               PSXBIOS_LOG(" -> %08x\n", v0);
+       }
+       else if (biosA0[call])
+               biosA0[call]();
+
+       //printf("A(%02x) -> %x\n", call, v0);
+       psxBranchTest();
+}
+
+static void hleB0() {
+       u32 call = t1 & 0xff;
+       u32 entry = loadRam32(A_B0_TABLE + call * 4);
+       int is_custom = 0;
+
+       use_cycles(4+7);
+       if (call == 0x5b)
+               is_custom = entry != A_B0_5B_TRAP;
+       else
+               is_custom = entry != A_B0_TRAPS + call * 4;
+       if (is_custom) {
+               PSXBIOS_LOG("custom B%02x %s(0x%x, )  addr=%08x ra=%08x\n",
+                       call, biosB0n[call], a0, entry, ra);
+               softCall(entry);
+               pc0 = ra;
+               PSXBIOS_LOG(" -> %08x\n", v0);
+       }
+       else if (biosB0[call])
+               biosB0[call]();
+
+       //printf("B(%02x) -> %x\n", call, v0);
+       psxBranchTest();
+}
+
+static void hleC0() {
+       u32 call = t1 & 0xff;
+       u32 entry = loadRam32(A_C0_TABLE + call * 4);
+
+       use_cycles(4+7);
+       if (call < 128 && entry != A_C0_TRAPS + call * 4) {
+               PSXBIOS_LOG("custom C%02x %s(0x%x, )  addr=%08x ra=%08x\n",
+                       call, biosC0n[call], a0, entry, ra);
+               softCall(entry);
+               pc0 = ra;
+               PSXBIOS_LOG(" -> %08x\n", v0);
+       }
+       else if (biosC0[call])
+               biosC0[call]();
+
+       //printf("C(%02x) -> %x\n", call, v0);
+       psxBranchTest();
+}
+
+static void hleA0t() {
+       u32 call = (pc0 - A_A0_TRAPS) / 4 - 1;
+       if (call >= 256u || !biosA0[call]) {
+               log_unhandled("unexpected A trap @%08x ra=%08x\n", pc0 - 4, ra);
+               mips_return_void_c(1000);
+       }
+       else
+               biosA0[call]();
+
+       //printf("A(%02x) -> %x\n", call, v0);
+       psxBranchTest();
+}
+
+static void hleB0t() {
+       u32 call = (pc0 - A_B0_TRAPS) / 4 - 1;
+       if (pc0 - 4 == A_B0_5B_TRAP)
+               call = 0x5b;
+       if (call >= 256u || !biosB0[call]) {
+               log_unhandled("unexpected B trap @%08x ra=%08x\n", pc0 - 4, ra);
+               mips_return_void_c(1000);
+       }
+       else
+               biosB0[call]();
+
+       //printf("B(%02x) -> %x\n", call, v0);
+       psxBranchTest();
+}
+
+static void hleC0t() {
+       u32 call = (pc0 - A_C0_TRAPS) / 4 - 1;
+       if (call >= 128u || !biosC0[call]) {
+               log_unhandled("unexpected C trap @%08x ra=%08x\n", pc0 - 4, ra);
+               mips_return_void_c(1000);
+       }
+       else
+               biosC0[call]();
+
+       //printf("C(%02x) -> %x\n", call, v0);
+       psxBranchTest();
+}
+
+// currently not used
+static void hleBootstrap() {
+       CheckCdrom();
+       LoadCdrom();
+}
+
+static void hleExecRet() {
+       const EXEC *header = (EXEC *)PSXM(s0);
+
+       PSXBIOS_LOG("ExecRet %x: %x\n", s0, header->ret);
+
+       ra = SWAP32(header->ret);
+       sp = SWAP32(header->_sp);
+       fp = SWAP32(header->_fp);
+       gp = SWAP32(header->_gp);
+       s0 = SWAP32(header->base);
+
+       v0 = 1;
+       psxRegs.pc = ra;
+}
+
+void (* const psxHLEt[hleop_count_])() = {
+       hleDummy, hleA0, hleB0, hleC0,
+       hleBootstrap, hleExecRet, psxBiosException, hleDummy,
+       hleExc0_0_1, hleExc0_0_2,
+       hleExc0_1_1, hleExc0_1_2, hleExc0_2_2_syscall,
+       hleExc1_0_1, hleExc1_0_2,
+       hleExc1_1_1, hleExc1_1_2,
+       hleExc1_2_1, hleExc1_2_2,
+       hleExc1_3_1, hleExc1_3_2,
+       hleExc3_0_2_defint,
+       hleExcPadCard1, hleExcPadCard2,
+       hleA0t, hleB0t, hleC0t,
+};
+
+void psxBiosCheckExe(u32 t_addr, u32 t_size, int loading_state)
+{
+       // lw      $v0, 0x10($sp)
+       // nop
+       // addiu   $v0, -1
+       // sw      $v0, 0x10($sp)
+       // lw      $v0, 0x10($sp)
+       // nop
+       // bne     $v0, $v1, not_timeout
+       // nop
+       // lui     $a0, ...
+       static const u8 pattern[] = {
+               0x10, 0x00, 0xA2, 0x8F, 0x00, 0x00, 0x00, 0x00,
+               0xFF, 0xFF, 0x42, 0x24, 0x10, 0x00, 0xA2, 0xAF,
+               0x10, 0x00, 0xA2, 0x8F, 0x00, 0x00, 0x00, 0x00,
+               0x0C, 0x00, 0x43, 0x14, 0x00, 0x00, 0x00, 0x00,
+       };
+       u32 start = t_addr & 0x1ffffc;
+       u32 end = (start + t_size) & 0x1ffffc;
+       u32 buf[sizeof(pattern) / sizeof(u32)];
+       const u32 *r32 = (u32 *)(psxM + start);
+       u32 i, j;
+
+       if (end <= start)
+               return;
+       if (!Config.HLE)
+               return;
+
+       memcpy(buf, pattern, sizeof(buf));
+       for (i = 0; i < t_size / 4; i += j + 1) {
+               for (j = 0; j < sizeof(buf) / sizeof(buf[0]); j++)
+                       if (r32[i + j] != buf[j])
+                               break;
+               if (j != sizeof(buf) / sizeof(buf[0]))
+                       continue;
+
+               if ((SWAP32(r32[i + j]) >> 16) != 0x3c04) // lui
+                       continue;
+               if (!loading_state)
+                       SysPrintf("HLE vsync @%08x\n", start + i * 4);
+               psxRegs.biosBranchCheck = (t_addr & 0xa01ffffc) + i * 4;
+       }
+}
+
+void psxBiosCheckBranch(void)
+{
+#if 1
+       // vsync HLE hack
+       static u32 cycles_prev, v0_prev;
+       u32 cycles_passed, waste_cycles;
+       u32 loops, v0_expect = v0_prev - 1;
+       if (v0 != 1)
+               return;
+       execI(&psxRegs);
+       cycles_passed = psxRegs.cycle - cycles_prev;
+       cycles_prev = psxRegs.cycle;
+       v0_prev = v0;
+       if (cycles_passed < 10 || cycles_passed > 50 || v0 != v0_expect)
+               return;
+
+       waste_cycles = schedule_timeslice() - psxRegs.cycle;
+       loops = waste_cycles / cycles_passed;
+       if (loops > v0)
+               loops = v0;
+       v0 -= loops;
+       psxRegs.cycle += loops * cycles_passed;
+       //printf("c %4u %d\n", loops, cycles_passed);
+#endif
+}
+
 #define bfreeze(ptr, size) { \
        if (Mode == 1) memcpy(&psxR[base], ptr, size); \
        if (Mode == 0) memcpy(ptr, &psxR[base], size); \