cdrom: change pause timing again
[pcsx_rearmed.git] / libpcsxcore / psxbios.c
index 0f8beb0..1f2e37a 100644 (file)
@@ -1,6 +1,6 @@
 /***************************************************************************
  *   Copyright (C) 2019 Ryan Schultz, PCSX-df Team, PCSX team, gameblabla, *
- *      dmitrysmagin, senquack                                                                                            *
+ *   dmitrysmagin, senquack                                                *
  *                                                                         *
  *   This program is free software; you can redistribute it and/or modify  *
  *   it under the terms of the GNU General Public License as published by  *
 #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(...)
 #endif
+#ifndef PSXBIOS_EV_LOG
+//#define PSXBIOS_EV_LOG printf
+#define PSXBIOS_EV_LOG(...)
+#endif
+
+#define PTR_1 (void *)(size_t)1
 
 char *biosA0n[256] = {
 // 0x00
@@ -84,7 +89,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",
@@ -95,7 +100,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
@@ -113,10 +118,10 @@ char *biosB0n[256] = {
        "SysMalloc",            "sys_b0_01",    "sys_b0_02",    "sys_b0_03",
        "sys_b0_04",            "sys_b0_05",    "sys_b0_06",    "DeliverEvent",
        "OpenEvent",            "CloseEvent",   "WaitEvent",    "TestEvent",
-       "EnableEvent",          "DisableEvent", "OpenTh",               "CloseTh",
+       "EnableEvent",          "DisableEvent", "OpenTh",       "CloseTh",
 // 0x10
-       "ChangeTh",                     "sys_b0_11",    "InitPAD",              "StartPAD",
-       "StopPAD",                      "PAD_init",             "PAD_dr",               "ReturnFromExecption",
+       "ChangeTh",             "sys_b0_11",    "InitPAD",      "StartPAD",
+       "StopPAD",              "PAD_init",     "PAD_dr",       "ReturnFromException",
        "ResetEntryInt",        "HookEntryInt", "sys_b0_1a",    "sys_b0_1b",
        "sys_b0_1c",            "sys_b0_1d",    "sys_b0_1e",    "sys_b0_1f",
 // 0x20
@@ -256,8 +261,11 @@ typedef struct {
 // todo: FileDesc layout is wrong
 // todo: get rid of these globals
 static FileDesc FDesc[32];
-static char ffile[64], *pfile;
+static char ffile[64];
 static int nfile;
+static char cdir[8*8+8];
+static u32 floodchk;
+static int card_io_delay;
 
 // fixed RAM offsets, SCPH1001 compatible
 #define A_TT_ExCB       0x0100
@@ -271,6 +279,7 @@ static int nfile;
 #define A_EXCEPTION     0x0c80
 #define A_EXC_SP        0x6cf0
 #define A_EEXIT_DEF     0x6cf4
+#define A_CARD_ISLOT    0x7264  // 0 or 1, toggled by card vint handler
 #define A_KMALLOC_PTR   0x7460
 #define A_KMALLOC_SIZE  0x7464
 #define A_KMALLOC_END   0x7468
@@ -282,7 +291,10 @@ static int nfile;
 #define A_PAD_IN_LEN    0x74d8
 #define A_PAD_OUT_LEN   0x74e0
 #define A_PAD_DR_DST    0x74c4
-#define A_CARD_CHAN1    0x7500
+#define A_CARD_ACHAN    0x7500  // currently active port in 0xPortSlot format
+#define A_CARD_HANDLER  0x7528  // ptr to irq handler
+#define A_CARD_STATUS1  0x7568
+#define A_CARD_STATUS2  0x7569
 #define A_PAD_DR_BUF1   0x7570
 #define A_PAD_DR_BUF2   0x7598
 #define A_EEXIT_PTR     0x75d0
@@ -292,12 +304,35 @@ static int nfile;
 #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 CARD_HARDLER_WRITE  0x51F4
+#define CARD_HARDLER_WRITEM 0x51F5 // fake, for psxBios_write()
+#define CARD_HARDLER_READ   0x5688
+#define CARD_HARDLER_READM  0x5689 // fake, for psxBios_read()
+#define CARD_HARDLER_INFO   0x5B64
+
 #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));
@@ -380,10 +415,17 @@ static inline void softCall(u32 pc) {
        ra = 0x80001000;
        psxRegs.CP0.n.SR &= ~0x404; // disable interrupts
 
-       while (pc0 != 0x80001000 && ++lim < 1000000)
+       assert(psxRegs.cpuInRecursion <= 1);
+       psxRegs.cpuInRecursion++;
+       psxCpu->Notify(R3000ACPU_NOTIFY_AFTER_LOAD, PTR_1);
+
+       while (pc0 != 0x80001000 && ++lim < 0x100000)
                psxCpu->ExecuteBlock(EXEC_CALLER_HLE);
 
-       if (lim == 1000000)
+       psxCpu->Notify(R3000ACPU_NOTIFY_BEFORE_SAVE, PTR_1);
+       psxRegs.cpuInRecursion--;
+
+       if (lim == 0x100000)
                PSXBIOS_LOG("softCall @%x hit lim\n", pc);
        ra = sra;
        psxRegs.CP0.n.SR |= ssr & 0x404;
@@ -393,116 +435,130 @@ static inline void softCallInException(u32 pc) {
        u32 sra = ra;
        u32 lim = 0;
        pc0 = pc;
+
+       assert(ra != 0x80001000);
+       if (ra == 0x80001000)
+               return;
        ra = 0x80001000;
 
-       while (!returned_from_exception() && pc0 != 0x80001000 && ++lim < 1000000)
+       psxRegs.cpuInRecursion++;
+       psxCpu->Notify(R3000ACPU_NOTIFY_AFTER_LOAD, PTR_1);
+
+       while (!returned_from_exception() && pc0 != 0x80001000 && ++lim < 0x100000)
                psxCpu->ExecuteBlock(EXEC_CALLER_HLE);
 
-       if (lim == 1000000)
+       psxCpu->Notify(R3000ACPU_NOTIFY_BEFORE_SAVE, PTR_1);
+       psxRegs.cpuInRecursion--;
+
+       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);
 
+static int card_buf_io(int is_write, int port, void *buf, u32 size)
+{
+       char *mcdptr = port ? Mcd2Data : Mcd1Data;
+       FileDesc *desc = &FDesc[2 + port];
+       u32 offset = 8192 * desc->mcfile + desc->offset;
+
+       PSXBIOS_LOG("card_%s_buf %d,%d: ofs=%x(%x) sz=%x (%s)\n",
+               is_write ? "write" : "read", port, desc->mcfile,
+               desc->offset, offset, size, mcdptr + 128 * desc->mcfile + 0xa);
+       if (!(loadRam8(A_CARD_STATUS1 + port) & 1)) {
+               PSXBIOS_LOG(" ...busy %x\n", loadRam8(A_CARD_STATUS1 + port));
+               return -1;
+       }
+       UnDeliverEvent(0xf4000001, 0x0004);
+       UnDeliverEvent(0xf4000001, 0x8000);
+       UnDeliverEvent(0xf4000001, 0x2000);
+       UnDeliverEvent(0xf4000001, 0x0100);
+
+       if (offset >= 128*1024u) {
+               log_unhandled("card offs %x(%x)\n", desc->offset, offset);
+               DeliverEvent(0xf4000001, 0x8000); // ?
+               return -1;
+       }
+       if (offset + size >= 128*1024u) {
+               log_unhandled("card offs+size %x+%x\n", offset, size);
+               size = 128*1024 - offset;
+       }
+       if (is_write) {
+               memcpy(mcdptr + offset, buf, size);
+               if (port == 0)
+                       SaveMcd(Config.Mcd1, Mcd1Data, offset, size);
+               else
+                       SaveMcd(Config.Mcd2, Mcd2Data, offset, size);
+       }
+       else {
+               size_t ram_offset = (s8 *)buf - psxM;
+               memcpy(buf, mcdptr + offset, size);
+               if (ram_offset < 0x200000)
+                       psxCpu->Clear(ram_offset, (size + 3) / 4);
+       }
+       desc->offset += size;
+       if (desc->mode & 0x8000) { // async
+               storeRam8(A_CARD_STATUS1 + port, is_write ? 4 : 2); // busy
+               storeRam32(A_CARD_HANDLER,
+                       is_write ? CARD_HARDLER_WRITEM : CARD_HARDLER_READM);
+               card_io_delay = 2 + size / 1024; // hack
+               return 0;
+       }
+       return size;
+}
+
 /*                                           *
 //                                           *
 //                                           *
 //               System calls A0             */
 
-
-#define buread(Ra1, mcd, length) { \
-       PSXBIOS_LOG("read %d: %x,%x (%s)\n", FDesc[1 + mcd].mcfile, FDesc[1 + mcd].offset, a2, Mcd##mcd##Data + 128 * FDesc[1 + mcd].mcfile + 0xa); \
-       ptr = Mcd##mcd##Data + 8192 * FDesc[1 + mcd].mcfile + FDesc[1 + mcd].offset; \
-       memcpy(Ra1, ptr, length); \
-       psxCpu->Clear(a1, (length + 3) / 4); \
-       if (FDesc[1 + mcd].mode & 0x8000) { \
-       DeliverEvent(0xf0000011, 0x0004); \
-       DeliverEvent(0xf4000001, 0x0004); \
-       v0 = 0; } \
-       else v0 = length; \
-       FDesc[1 + mcd].offset += v0; \
-}
-
-#define buwrite(Ra1, mcd, length) { \
-       u32 offset =  + 8192 * FDesc[1 + mcd].mcfile + FDesc[1 + mcd].offset; \
-       PSXBIOS_LOG("write %d: %x,%x\n", FDesc[1 + mcd].mcfile, FDesc[1 + mcd].offset, a2); \
-       ptr = Mcd##mcd##Data + offset; \
-       memcpy(ptr, Ra1, length); \
-       FDesc[1 + mcd].offset += length; \
-       SaveMcd(Config.Mcd##mcd, Mcd##mcd##Data, offset, length); \
-       if (FDesc[1 + mcd].mode & 0x8000) { \
-       DeliverEvent(0xf0000011, 0x0004); \
-       DeliverEvent(0xf4000001, 0x0004); \
-       v0 = 0; } \
-       else v0 = length; \
-}
-
 /* Internally redirects to "FileRead(fd,tempbuf,1)".*/
 /* For some strange reason, the returned character is sign-expanded; */
 /* So if a return value of FFFFFFFFh could mean either character FFh, or error. */
-/* TODO FIX ME : Properly implement this behaviour */
-void psxBios_getc(void) // 0x03, 0x35
+static void psxBios_getc(void) // 0x03, 0x35
 {
-       char *ptr;
-       void *pa1 = Ra1;
-#ifdef PSXBIOS_LOG
-       PSXBIOS_LOG("psxBios_%s\n", biosA0n[0x03]);
-#endif
-       v0 = -1;
+       s8 buf[1] = { -1 };
+       int ret = -1;
 
-       if (pa1 != INVALID_PTR) {
-               switch (a0) {
-                       case 2: buread(pa1, 1, 1); break;
-                       case 3: buread(pa1, 2, 1); break;
-               }
+       PSXBIOS_LOG("psxBios_%s %d\n", biosA0n[0x03], a0);
+
+       if (a0 == 1)
+               ret = -1;
+       else if (a0 == 2 || a0 == 3) {
+               card_buf_io(0, a0 - 2, buf, 1);
+               ret = buf[0];
        }
 
-       pc0 = ra;
+       mips_return_c(ret, 100);
 }
 
 /* Copy of psxBios_write, except size is 1. */
-void psxBios_putc(void) // 0x09, 0x3B
+static void psxBios_putc(void) // 0x09, 0x3B
 {
-       char *ptr;
-       void *pa1 = Ra1;
-#ifdef PSXBIOS_LOG
-       PSXBIOS_LOG("psxBios_%s\n", biosA0n[0x09]);
-#endif
-       v0 = -1;
-       if (pa1 == INVALID_PTR) {
-               pc0 = ra;
-               return;
-       }
+       u8 buf[1] = { (u8)a0 };
+       int ret = -1;
 
-       if (a0 == 1) { // stdout
-               char *ptr = (char *)pa1;
+       if (a1 != 1) // not stdout
+               PSXBIOS_LOG("psxBios_%s '%c' %d\n", biosA0n[0x09], (char)a0, a1);
 
-               v0 = a2;
-               while (a2 > 0) {
-                       printf("%c", *ptr++); a2--;
-               }
-               pc0 = ra; return;
+       if (a1 == 1) { // stdout
+               if (Config.PsxOut) printf("%c", (char)a0);
        }
-
-       switch (a0) {
-               case 2: buwrite(pa1, 1, 1); break;
-               case 3: buwrite(pa1, 2, 1); break;
+       else if (a1 == 2 || a1 == 3) {
+               ret = card_buf_io(1, a1 - 2, buf, 1);
        }
 
-       pc0 = ra;
+       mips_return_c(ret, 100);
 }
 
-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;
@@ -514,14 +570,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
@@ -538,6 +653,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;
@@ -553,6 +673,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
@@ -602,22 +723,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
@@ -736,6 +859,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;
@@ -877,6 +1001,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;
@@ -889,10 +1014,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;
@@ -1080,16 +1207,16 @@ void psxBios_memchr() { // 0x2e
        v0 = 0; pc0 = ra;
 }
 
-void psxBios_rand() { // 0x2f
-       u32 s = psxMu32(0x9010) * 1103515245 + 12345;
-       v0 = (s >> 16) & 0x7fff;
-       psxMu32ref(0x9010) = SWAPu32(s);
-       pc0 = ra;
+static void psxBios_rand() { // 0x2f
+       u32 s = loadRam32(A_RND_SEED) * 1103515245 + 12345;
+       storeRam32(A_RND_SEED, s);
+       v1 = s;
+       mips_return_c((s >> 16) & 0x7fff, 12+37);
 }
 
-void psxBios_srand() { // 0x30
-       psxMu32ref(0x9010) = SWAPu32(a0);
-       pc0 = ra;
+static void psxBios_srand() { // 0x30
+       storeRam32(A_RND_SEED, a0);
+       mips_return_void_c(3);
 }
 
 static u32 qscmpfunc, qswidth;
@@ -1198,114 +1325,109 @@ 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 + size + 4;
+       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) {
+                               // rm useless last free block
+                               storeRam32(A_HEAP_BASE, chunk + 4);
+                               storeRam32(chunk, ~1);
+                               continue;
+                       }
+                       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;
+       if (i == limit) {
+               PSXBIOS_LOG("malloc: limit OOM\n");
+               ret = 0;
        }
-
-       // 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;
+       else if (tries == 0 && malloc_heap_grow(size)) {
+               PSXBIOS_LOG("malloc: grow OOM s=%d end=%08x/%08x\n",
+                       size, loadRam32(A_HEAP_BASE), loadRam32(A_HEAP_END));
+               ret = 0;
        }
-
-       // 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);
+       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);
 }
@@ -1327,9 +1449,8 @@ static void psxBios_calloc() { // 0x37
 void psxBios_realloc() { // 0x38
        u32 block = a0;
        u32 size = a1;
-#ifdef PSXBIOS_LOG
-       PSXBIOS_LOG("psxBios_%s\n", biosA0n[0x38]);
-#endif
+
+       PSXBIOS_LOG("psxBios_%s %08x %d\n", biosA0n[0x38], a0, a1);
 
        a0 = block;
        /* If "old_buf" is zero, executes malloc(new_size), and returns r2=new_buf (or 0=failed). */
@@ -1360,7 +1481,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);
@@ -1373,7 +1494,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;
@@ -1447,7 +1568,21 @@ void psxBios_printf() { // 0x3f
        pc0 = ra;
 }
 
-void psxBios_format() { // 0x41
+static void psxBios_cd() { // 0x40
+       const char *p, *dir = Ra0;
+       PSXBIOS_LOG("psxBios_%s %x(%s)\n", biosB0n[0x40], a0, 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);
+}
+
+static void psxBios_format() { // 0x41
+       PSXBIOS_LOG("psxBios_%s %x(%s)\n", biosB0n[0x41], a0, Ra0);
        if (strcmp(Ra0, "bu00:") == 0 && Config.Mcd1[0] != '\0')
        {
                CreateMcd(Config.Mcd1);
@@ -1468,9 +1603,9 @@ void psxBios_format() { // 0x41
 }
 
 static void psxBios_SystemErrorUnresolvedException() {
-       if (loadRam32(0xfffc) != 0x12345678) { // prevent log flood
+       if (floodchk != 0x12340a40) { // prevent log flood
                SysPrintf("psxBios_%s called from %08x\n", biosA0n[0x40], ra);
-               storeRam32(0xfffc, 0x12345678);
+               floodchk = 0x12340a40;
        }
        mips_return_void_c(1000);
 }
@@ -1483,24 +1618,94 @@ 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;
        void *pa1;
 
+       pa0 = Ra0;
        pa1 = Ra1;
-       if (pa1 != INVALID_PTR && LoadCdromFile(Ra0, &eheader) == 0) {
+       PSXBIOS_LOG("psxBios_%s %x(%s), %x\n", biosA0n[0x42], a0, pa0, a1);
+       if (pa0 == INVALID_PTR || pa1 == INVALID_PTR) {
+               mips_return(0);
+               return;
+       }
+       if ((p = strchr(pa0, ':')))
+               pa0 = ++p;
+       if (*pa0 == '\\')
+               pa0++;
+       if (cdir[0])
+               snprintf(path, sizeof(path), "%s\\%s", cdir, (char *)pa0);
+       else
+               snprintf(path, sizeof(path), "%s", (char *)pa0);
+
+       if (LoadCdromFile(path, &eheader, time) == 0) {
                memcpy(pa1, ((char*)&eheader)+16, sizeof(EXEC));
                psxCpu->Clear(a1, sizeof(EXEC) / 4);
                FlushCache();
                v0 = 1;
        } else v0 = 0;
-       PSXBIOS_LOG("psxBios_%s: %s, %d -> %d\n", biosA0n[0x42], Ra0, a1, v0);
+       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);
 }
 
 /*
@@ -1569,9 +1774,17 @@ 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();
+       gpuSyncPluginSR(); // flush
        GPU_writeData(0xa0000000);
        GPU_writeData((a1<<0x10)|(a0&0xffff));
        GPU_writeData((a3<<0x10)|(a2&0xffff));
@@ -1593,10 +1806,10 @@ void psxBios_SendGPU() { // 0x48
 }
 
 void psxBios_GPU_cw() { // 0x49
-       gpuSyncPluginSR();
        GPU_writeData(a0);
-       v0 = HW_GPU_STATUS;
-       pc0 = ra;
+       gpuSyncPluginSR();
+       use_cycles(13);
+       gpu_sync();
 }
 
 void psxBios_GPU_cwb() { // 0x4a
@@ -1657,10 +1870,8 @@ void psxBios_LoadExec() { // 51
        psxBios_Exec();
 }
 
-void psxBios__bu_init() { // 70
-#ifdef PSXBIOS_LOG
+static void psxBios__bu_init() { // 70
        PSXBIOS_LOG("psxBios_%s\n", biosA0n[0x70]);
-#endif
 
        DeliverEvent(0xf0000011, 0x0004);
        DeliverEvent(0xf4000001, 0x0004);
@@ -1668,24 +1879,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_();
@@ -1708,6 +1981,23 @@ static void psxBios_CdRemove() { // 56, 72
        use_cycles(30);
 }
 
+static void setup_tt(u32 tcb_cnt, u32 evcb_cnt, u32 stack);
+
+static void psxBios_SetConf() { // 9c
+       PSXBIOS_LOG("psxBios_%s %x %x %x\n", biosA0n[0x9c], a0, a1, a2);
+       setup_tt(a1, a0, a2);
+       psxRegs.CP0.n.SR |= 0x401;
+       mips_return_void_c(500);
+}
+
+static void psxBios_GetConf() { // 9d
+       PSXBIOS_LOG("psxBios_%s %x %x %x\n", biosA0n[0x9d], a0, a1, a2);
+       storeRam32(a0, loadRam32(A_CONF_EvCB));
+       storeRam32(a1, loadRam32(A_CONF_TCB));
+       storeRam32(a2, loadRam32(A_CONF_SP));
+       mips_return_void_c(10);
+}
+
 void psxBios_SetMem() { // 9f
        u32 new = psxHu32(0x1060);
 
@@ -1743,47 +2033,6 @@ static void psxBios_get_cd_status() // a6
        pc0 = ra;
 }
 
-static void psxBios__card_info() { // ab
-       PSXBIOS_LOG("psxBios_%s: %x\n", biosA0n[0xab], a0);
-       u32 ret, port;
-       storeRam32(A_CARD_CHAN1, a0);
-       port = a0 >> 4;
-
-       switch (port) {
-       case 0x0:
-       case 0x1:
-               ret = 0x0004;
-               if (McdDisable[port & 1])
-                       ret = 0x0100;
-               break;
-       default:
-               PSXBIOS_LOG("psxBios_%s: UNKNOWN PORT 0x%x\n", biosA0n[0xab], a0);
-               ret = 0x0302;
-               break;
-       }
-
-       if (McdDisable[0] && McdDisable[1])
-               ret = 0x0100;
-
-       DeliverEvent(0xf0000011, 0x0004);
-//     DeliverEvent(0xf4000001, 0x0004);
-       DeliverEvent(0xf4000001, ret);
-       v0 = 1; pc0 = ra;
-}
-
-void psxBios__card_load() { // ac
-#ifdef PSXBIOS_LOG
-       PSXBIOS_LOG("psxBios_%s: %x\n", biosA0n[0xac], a0);
-#endif
-
-       storeRam32(A_CARD_CHAN1, a0);
-
-//     DeliverEvent(0xf0000011, 0x0004);
-       DeliverEvent(0xf4000001, 0x0004);
-
-       v0 = 1; pc0 = ra;
-}
-
 static void psxBios_GetSystemInfo() { // b4
        u32 ret = 0;
        //PSXBIOS_LOG("psxBios_%s %x\n", biosA0n[0xb4], a0);
@@ -1834,9 +2083,13 @@ void psxBios_GetRCnt() { // 03
        PSXBIOS_LOG("psxBios_%s\n", biosB0n[0x03]);
 #endif
 
-       a0&= 0x3;
-       if (a0 != 3) v0 = psxRcntRcount(a0);
-       else v0 = 0;
+       switch (a0 & 0x3)
+       {
+       case 0: v0 = psxRcntRcount0(); break;
+       case 1: v0 = psxRcntRcount1(); break;
+       case 2: v0 = psxRcntRcount2(); break;
+       case 3: v0 = 0; break;
+       }
        pc0 = ra;
 }
 
@@ -1877,12 +2130,13 @@ void psxBios_ResetRCnt() { // 06
 }
 
 static u32 DeliverEvent(u32 class, u32 spec) {
-       EvCB *ev = (EvCB *)loadRam32ptr(A_TT_EvCB);
+       EvCB *ev, *ev_first = (EvCB *)loadRam32ptr(A_TT_EvCB);
        u32 evcb_len = loadRam32(A_TT_EvCB + 4);
        u32 ret = loadRam32(A_TT_EvCB) + evcb_len;
        u32 i, lim = evcb_len / 0x1c;
 
-       for (i = 0; i < lim; i++, ev++) {
+       //printf("%s %08x %x\n", __func__, class, spec);
+       for (i = 0, ev = ev_first; i < lim; i++, ev++) {
                use_cycles(8);
                if (SWAP32(ev->status) != EvStACTIVE)
                        continue;
@@ -1895,12 +2149,17 @@ static u32 DeliverEvent(u32 class, u32 spec) {
                use_cycles(6);
                ret = SWAP32(ev->mode);
                if (ret == EvMdMARK) {
+                       if (ev->status != SWAP32(EvStALREADY))
+                               PSXBIOS_EV_LOG("DeliverEvent %08x %x (%08zx) set\n",
+                                       class, spec, (ev - ev_first) | 0xf1000000u);
                        ev->status = SWAP32(EvStALREADY);
                        continue;
                }
                use_cycles(8);
                if (ret == EvMdCALL) {
                        ret = SWAP32(ev->fhandler);
+                       PSXBIOS_EV_LOG("DeliverEvent %08x %x (%08zx) cb %x\n",
+                               class, spec, (ev - ev_first) | 0xf1000000u, ret);
                        if (ret) {
                                v0 = ret;
                                softCall(ret);
@@ -1908,6 +2167,7 @@ static u32 DeliverEvent(u32 class, u32 spec) {
                        }
                }
        }
+       floodchk = 0;
        use_cycles(29);
        return ret;
 }
@@ -2019,7 +2279,11 @@ static void psxBios_TestEvent() { // 0b
        u32 base = loadRam32(A_TT_EvCB);
        u32 status = loadRam32(base + (a0 & 0xffff) * sizeof(EvCB) + 4);
        u32 ret = 0;
-       PSXBIOS_LOG("psxBios_%s    %x %x\n", biosB0n[0x0b], a0, status);
+
+       if (psxRegs.cycle - floodchk > 16*1024u) { // prevent log flood
+               PSXBIOS_LOG("psxBios_%s    %x %x\n", biosB0n[0x0b], a0, status);
+               floodchk = psxRegs.cycle;
+       }
        if (status == EvStALREADY) {
                storeRam32(base + (a0 & 0xffff) * sizeof(EvCB) + 4, EvStACTIVE);
                ret = 1;
@@ -2028,13 +2292,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);
 }
 
@@ -2071,7 +2339,7 @@ void psxBios_OpenTh() { // 0e
                mips_return_c(0xffffffff, 20);
                return;
        }
-       PSXBIOS_LOG("psxBios_%s: %x\n", biosB0n[0x0e], th);
+       PSXBIOS_LOG("psxBios_%s -> %x\n", biosB0n[0x0e], 0xff000000 + th);
 
        tcb[th].status  = SWAP32(0x4000);
        tcb[th].mode    = SWAP32(0x1000);
@@ -2087,21 +2355,15 @@ void psxBios_OpenTh() { // 0e
  *     int CloseTh(long thread);
  */
 
-void psxBios_CloseTh() { // 0f
-       TCB *tcb = loadRam32ptr(A_TT_TCB);
-       u32 limit = loadRam32(A_TT_TCB + 4) / 0xc0u;
-       u32 th = a0 & 0xff;
+static void psxBios_CloseTh() { // 0f
+       u32 tcb = loadRam32(A_TT_TCB);
+       u32 th = a0 & 0xffff;
 
-#ifdef PSXBIOS_LOG
-       PSXBIOS_LOG("psxBios_%s: %x\n", biosB0n[0x0f], th);
-#endif
-       /* The return value is always 1 (even if the handle was already closed). */
-       v0 = 1;
-       if (th < limit && tcb[th].status == SWAP32(0x4000)) {
-               tcb[th].status = SWAP32(0x1000);
-       }
+       PSXBIOS_LOG("psxBios_%s %x\n", biosB0n[0x0f], a0);
+       // in the usual bios fashion no checks, just write and return 1
+       storeRam32(tcb + th * sizeof(TCB), 0x1000);
 
-       pc0 = ra;
+       mips_return_c(1, 11);
 }
 
 /*
@@ -2283,8 +2545,8 @@ static void buopen(int mcd, char *ptr, char *cfg)
                if ((*fptr & 0xF0) != 0x50) continue;
                if (strcmp(FDesc[1 + mcd].name, fptr+0xa)) continue;
                FDesc[1 + mcd].mcfile = i;
-               PSXBIOS_LOG("open %s\n", fptr+0xa);
                v0 = 1 + mcd;
+               PSXBIOS_LOG("open %s -> %d\n", fptr+0xa, v0);
                break;
        }
        if (a1 & 0x200 && v0 == -1) { /* FCREAT */
@@ -2339,9 +2601,7 @@ static void buopen(int mcd, char *ptr, char *cfg)
 void psxBios_open() { // 0x32
        void *pa0 = Ra0;
 
-#ifdef PSXBIOS_LOG
-       PSXBIOS_LOG("psxBios_%s: %s,%x\n", biosB0n[0x32], Ra0, a1);
-#endif
+       PSXBIOS_LOG("psxBios_%s %s(%x) %x\n", biosB0n[0x32], Ra0, a0, a1);
 
        v0 = -1;
 
@@ -2389,44 +2649,34 @@ void psxBios_lseek() { // 0x33
  *     int read(int fd , void *buf , int nbytes);
  */
 
-void psxBios_read() { // 0x34
-       char *ptr;
+static void psxBios_read() { // 0x34
        void *pa1 = Ra1;
+       int ret = -1;
 
-#ifdef PSXBIOS_LOG
        PSXBIOS_LOG("psxBios_%s: %x, %x, %x\n", biosB0n[0x34], a0, a1, a2);
-#endif
 
-       v0 = -1;
-
-       if (pa1 != INVALID_PTR) {
-               switch (a0) {
-                       case 2: buread(pa1, 1, a2); break;
-                       case 3: buread(pa1, 2, a2); break;
-               }
-       }
+       if (pa1 == INVALID_PTR)
+               ;
+       else if (a0 == 2 || a0 == 3)
+               ret = card_buf_io(0, a0 - 2, pa1, a2);
 
-       pc0 = ra;
+       mips_return_c(ret, 100);
 }
 
 /*
  *     int write(int fd , void *buf , int nbytes);
  */
 
-void psxBios_write() { // 0x35/0x03
-       char *ptr;
+static void psxBios_write() { // 0x35/0x03
        void *pa1 = Ra1;
+       int ret = -1;
 
-       if (a0 != 1) // stdout
+       if (a0 != 1) // not stdout
                PSXBIOS_LOG("psxBios_%s: %x,%x,%x\n", biosB0n[0x35], a0, a1, a2);
 
-       v0 = -1;
-       if (pa1 == INVALID_PTR) {
-               pc0 = ra;
-               return;
-       }
-
-       if (a0 == 1) { // stdout
+       if (pa1 == INVALID_PTR)
+               ;
+       else if (a0 == 1) { // stdout
                char *ptr = pa1;
 
                v0 = a2;
@@ -2435,13 +2685,10 @@ void psxBios_write() { // 0x35/0x03
                }
                pc0 = ra; return;
        }
+       else if (a0 == 2 || a0 == 3)
+               ret = card_buf_io(1, a0 - 2, pa1, a2);
 
-       switch (a0) {
-               case 2: buwrite(pa1, 1, a2); break;
-               case 3: buwrite(pa1, 2, a2); break;
-       }
-
-       pc0 = ra;
+       mips_return_c(ret, 100);
 }
 
 static void psxBios_write_psxout() {
@@ -2486,76 +2733,90 @@ void psxBios_puts() { // 3e/3f
        pc0 = ra;
 }
 
+static void bufile(const u8 *mcd_data, u32 dir_) {
+       struct DIRENTRY *dir = (struct DIRENTRY *)PSXM(dir_);
+       const char *pfile = ffile + 5;
+       const u8 *data = mcd_data;
+       int i = 0, match = 0;
+       int blocks = 1;
+       u32 head = 0;
 
-/* To avoid any issues with different behaviour when using the libc's own strlen instead.
- * We want to mimic the PSX's behaviour in this case for bufile. */
-static size_t strlen_internal(char* p)
-{
-       size_t size_of_array = 0;
-       while (*p++) size_of_array++;
-       return size_of_array;
-}
-
-#define bufile(mcd) { \
-       size_t size_of_name = strlen_internal(dir->name); \
-       while (nfile < 16) { \
-               int match=1; \
- \
-               ptr = Mcd##mcd##Data + 128 * (nfile + 1); \
-               nfile++; \
-               if ((*ptr & 0xF0) != 0x50) continue; \
-               /* Bug link files show up as free block. */ \
-               if (!ptr[0xa]) continue; \
-               ptr+= 0xa; \
-               if (pfile[0] == 0) { \
-                       strncpy(dir->name, ptr, sizeof(dir->name) - 1); \
-                       if (size_of_name < sizeof(dir->name)) dir->name[size_of_name] = '\0'; \
-               } else for (i=0; i<20; i++) { \
-                       if (pfile[i] == ptr[i]) { \
-                                                               dir->name[i] = ptr[i]; continue; } \
-                       if (pfile[i] == '?') { \
-                               dir->name[i] = ptr[i]; continue; } \
-                       if (pfile[i] == '*') { \
-                               strcpy(dir->name+i, ptr+i); break; } \
-                       match = 0; break; \
-               } \
-               PSXBIOS_LOG("%d : %s = %s + %s (match=%d)\n", nfile, dir->name, pfile, ptr, match); \
-               if (match == 0) { continue; } \
-               dir->size = 8192; \
-               v0 = _dir; \
-               break; \
-       } \
+       v0 = 0;
+       if (dir == INVALID_PTR)
+               return;
+
+       for (; nfile <= 15 && !match; nfile++) {
+               const char *name;
+
+               head = nfile * 0x40;
+               data = mcd_data + 128 * nfile;
+               name = (const char *)data + 0x0a;
+               if ((data[0] & 0xF0) != 0x50) continue;
+               /* Bug link files show up as free block. */
+               if (!name[0]) continue;
+               match = 1;
+               for (i = 0; i < 20; i++) {
+                       if (pfile[i] == name[i] || pfile[i] == '?')
+                               dir->name[i] = name[i];
+                       else if (pfile[i] == '*') {
+                               int len = strlen(name + i);
+                               if (i + len > 20)
+                                       len = 20 - i;
+                               memcpy(dir->name + i, name + i, len + 1);
+                               i += len;
+                               break;
+                       }
+                       else {
+                               match = 0;
+                               break;
+                       }
+                       if (!name[i])
+                               break;
+               }
+               PSXBIOS_LOG("%d : %s = %s + %s (match=%d)\n",
+                       nfile, dir->name, pfile, name, match);
+       }
+       for (; nfile <= 15; nfile++, blocks++) {
+               const u8 *data2 = mcd_data + 128 * nfile;
+               const char *name = (const char *)data2 + 0x0a;
+               if ((data2[0] & 0xF0) != 0x50 || name[0])
+                       break;
+       }
+       if (match) {
+               // nul char of full lenth name seems to overwrite .attr
+               dir->attr = SWAP32(i < 20 ? data[0] & 0xf0 : 0); // ?
+               dir->size = 8192 * blocks;
+               dir->head = head;
+               v0 = dir_;
+       }
+       PSXBIOS_LOG("  -> %x '%s' %x %x %x %x\n", v0, v0 ? dir->name : "",
+                   dir->attr, dir->size, dir->next, dir->head);
 }
 
 /*
  *     struct DIRENTRY* firstfile(char *name,struct DIRENTRY *dir);
  */
 
-void psxBios_firstfile() { // 42
-       struct DIRENTRY *dir = (struct DIRENTRY *)Ra1;
-       void *pa0 = Ra0;
-       u32 _dir = a1;
-       char *ptr;
-       int i;
-
-#ifdef PSXBIOS_LOG
-       PSXBIOS_LOG("psxBios_%s: %s\n", biosB0n[0x42], Ra0);
-#endif
+static void psxBios_firstfile() { // 42
+       char *pa0 = Ra0;
 
+       PSXBIOS_LOG("psxBios_%s %s %x\n", biosB0n[0x42], pa0, a1);
        v0 = 0;
 
-       if (pa0 != INVALID_PTR) {
-               strcpy(ffile, pa0);
-               pfile = ffile+5;
-               nfile = 0;
+       if (pa0 != INVALID_PTR)
+       {
+               snprintf(ffile, sizeof(ffile), "%s", pa0);
+               if (ffile[5] == 0)
+                       strcpy(ffile + 5, "*"); // maybe?
+               nfile = 1;
                if (!strncmp(pa0, "bu00", 4)) {
                        // firstfile() calls _card_read() internally, so deliver it's event
                        DeliverEvent(0xf0000011, 0x0004);
-                       bufile(1);
+                       bufile((u8 *)Mcd1Data, a1);
                } else if (!strncmp(pa0, "bu10", 4)) {
                        // firstfile() calls _card_read() internally, so deliver it's event
                        DeliverEvent(0xf0000011, 0x0004);
-                       bufile(2);
+                       bufile((u8 *)Mcd2Data, a1);
                }
        }
 
@@ -2567,24 +2828,13 @@ void psxBios_firstfile() { // 42
  */
 
 void psxBios_nextfile() { // 43
-       struct DIRENTRY *dir = (struct DIRENTRY *)Ra0;
-       u32 _dir = a0;
-       char *ptr;
-       int i;
-
-#ifdef PSXBIOS_LOG
-       PSXBIOS_LOG("psxBios_%s: %s\n", biosB0n[0x43], dir->name);
-#endif
+       PSXBIOS_LOG("psxBios_%s %x\n", biosB0n[0x43], a0);
 
        v0 = 0;
-
-       if (!strncmp(ffile, "bu00", 4)) {
-               bufile(1);
-       }
-
-       if (!strncmp(ffile, "bu10", 4)) {
-               bufile(2);
-       }
+       if (!strncmp(ffile, "bu00", 4))
+               bufile((u8 *)Mcd1Data, a0);
+       else if (!strncmp(ffile, "bu10", 4))
+               bufile((u8 *)Mcd2Data, a0);
 
        pc0 = ra;
 }
@@ -2678,9 +2928,14 @@ void psxBios_delete() { // 45
 }
 
 void psxBios_InitCARD() { // 4a
+       u8 *ram8 = (u8 *)psxM;
        u32 *ram32 = (u32 *)psxM;
        PSXBIOS_LOG("psxBios_%s: %x\n", biosB0n[0x4a], a0);
        write_chain(ram32 + A_PADCRD_CHN_E/4, 0, 0x49bc, 0x4a4c);
+       //card_error = 0;
+       ram8[A_CARD_ISLOT] = 0;
+       ram8[A_CARD_STATUS1] = 1;
+       ram8[A_CARD_STATUS2] = 1;
        // (maybe) todo: early_card_irq, etc
 
        ram32[A_PAD_IRQR_ENA/4] = SWAP32(a0);
@@ -2716,23 +2971,19 @@ void psxBios__card_write() { // 0x4e
        void *pa2 = Ra2;
        int port;
 
-#ifdef PSXBIOS_LOG
-       PSXBIOS_LOG("psxBios_%s: %x,%x,%x\n", biosB0n[0x4e], a0, a1, a2);
-#endif
-       /*
-       Function also accepts sector 400h (a bug).
-       But notaz said we shouldn't allow sector 400h because it can corrupt the emulator.
-       */
-       if (!(a1 <= 0x3FF))
+       PSXBIOS_LOG("psxBios_%s %02x,%x,%x\n", biosB0n[0x4e], a0, a1, a2);
+       // function also accepts sector 400h (a bug),
+       // but what actually happens then?
+       if (a1 > 0x400)
        {
                /* Invalid sectors */
                v0 = 0; pc0 = ra;
                return;
        }
-       storeRam32(A_CARD_CHAN1, a0);
+       storeRam32(A_CARD_ACHAN, a0);
        port = a0 >> 4;
 
-       if (pa2 != INVALID_PTR) {
+       if (pa2 != INVALID_PTR && a1 < 0x400) {
                if (port == 0) {
                        memcpy(Mcd1Data + a1 * 128, pa2, 128);
                        SaveMcd(Config.Mcd1, Mcd1Data, a1 * 128, 128);
@@ -2742,33 +2993,27 @@ void psxBios__card_write() { // 0x4e
                }
        }
 
-       DeliverEvent(0xf0000011, 0x0004);
-//     DeliverEvent(0xf4000001, 0x0004);
+       storeRam8(A_CARD_STATUS1 + port, 4); // busy/write
+       storeRam32(A_CARD_HANDLER, CARD_HARDLER_WRITE);
 
        v0 = 1; pc0 = ra;
 }
 
-void psxBios__card_read() { // 0x4f
+static void psxBios__card_read() { // 0x4f
        void *pa2 = Ra2;
        int port;
 
-#ifdef PSXBIOS_LOG
-       PSXBIOS_LOG("psxBios_%s\n", biosB0n[0x4f]);
-#endif
-       /*
-       Function also accepts sector 400h (a bug).
-       But notaz said we shouldn't allow sector 400h because it can corrupt the emulator.
-       */
-       if (!(a1 <= 0x3FF))
+       PSXBIOS_LOG("psxBios_%s %x,%x,%x\n", biosB0n[0x4f], a0, a1, a2);
+       if (a1 > 0x400)
        {
                /* Invalid sectors */
                v0 = 0; pc0 = ra;
                return;
        }
-       storeRam32(A_CARD_CHAN1, a0);
+       storeRam32(A_CARD_ACHAN, a0);
        port = a0 >> 4;
 
-       if (pa2 != INVALID_PTR) {
+       if (pa2 != INVALID_PTR && a1 < 0x400) {
                if (port == 0) {
                        memcpy(pa2, Mcd1Data + a1 * 128, 128);
                } else {
@@ -2776,8 +3021,8 @@ void psxBios__card_read() { // 0x4f
                }
        }
 
-       DeliverEvent(0xf0000011, 0x0004);
-//     DeliverEvent(0xf4000001, 0x0004);
+       storeRam8(A_CARD_STATUS1 + port, 2); // busy/read
+       storeRam32(A_CARD_HANDLER, CARD_HARDLER_READ);
 
        v0 = 1; pc0 = ra;
 }
@@ -2857,12 +3102,11 @@ void psxBios_GetB0Table() { // 57
 }
 
 static void psxBios__card_chan() { // 0x58
-       u32 ret;
-       PSXBIOS_LOG("psxBios_%s\n", biosB0n[0x58]);
-
-       // todo: should return active slot chan
+       // todo: should return active slot channel
        // (active - which was last processed by irq code)
-       ret = loadRam32(A_CARD_CHAN1);
+       u32 ret = loadRam32(A_CARD_ACHAN);
+       PSXBIOS_LOG("psxBios_%s -> %02x\n", biosB0n[0x58], ret);
+
        mips_return_c(ret, 8);
 }
 
@@ -2876,17 +3120,123 @@ static void psxBios_ChangeClearPad() { // 5b
 }
 
 static void psxBios__card_status() { // 5c
-       PSXBIOS_LOG("psxBios_%s %x\n", biosB0n[0x5c], a0);
+       u8 s = loadRam8(A_CARD_STATUS1 + a0);
+       PSXBIOS_LOG("psxBios_%s %x -> %x\n", biosB0n[0x5c], a0, s);
 
-       v0 = 1; // ready
-       pc0 = ra;
+       mips_return_c(s, 5);
 }
 
 static void psxBios__card_wait() { // 5d
-       PSXBIOS_LOG("psxBios_%s %x\n", biosB0n[0x5d], a0);
+       u8 s = loadRam8(A_CARD_STATUS1 + a0);
+       PSXBIOS_LOG("psxBios_%s %x -> %x\n", biosB0n[0x5d], a0, s);
 
-       v0 = 1; // ready
-       pc0 = ra;
+       // todo
+       if (!(s & 1))
+               log_unhandled("%s %x\n", __func__, s);
+
+       mips_return_c(s, 11);
+}
+
+static void psxBios__card_info() { // A ab
+       PSXBIOS_LOG("psxBios_%s %02x\n", biosA0n[0xab], a0);
+       u32 ret, port;
+       storeRam32(A_CARD_ACHAN, a0);
+       port = a0 >> 4;
+
+       switch (port) {
+       case 0x0:
+       case 0x1:
+               ret = 0x0004;
+               if (McdDisable[port & 1])
+                       ret = 0x0100;
+               break;
+       default:
+               PSXBIOS_LOG("psxBios_%s: UNKNOWN PORT 0x%x\n", biosA0n[0xab], a0);
+               ret = 0x0302;
+               break;
+       }
+
+       if (McdDisable[0] && McdDisable[1])
+               ret = 0x0100;
+
+       if (ret == 4) {
+               // deliver from card_vint_handler()
+               storeRam8(A_CARD_STATUS1 + port, 8); // busy/info
+               storeRam32(A_CARD_HANDLER, CARD_HARDLER_INFO);
+       } else {
+               DeliverEvent(0xf4000001, ret);
+               DeliverEvent(0xf0000011, 0x0004); // ?
+       }
+       mips_return(1);
+}
+
+static void psxBios__card_load() { // A ac
+       PSXBIOS_LOG("psxBios_%s %02x\n", biosA0n[0xac], a0);
+
+       storeRam32(A_CARD_ACHAN, a0);
+
+//     DeliverEvent(0xf0000011, 0x0004);
+       DeliverEvent(0xf4000001, 0x0004);
+
+       mips_return(1);
+}
+
+static void card_vint_handler(void) {
+       u8 select, status;
+       u32 handler;
+
+       if (card_io_delay) {
+               card_io_delay--;
+               return;
+       }
+       UnDeliverEvent(0xf0000011, 0x0004);
+       UnDeliverEvent(0xf0000011, 0x8000);
+       UnDeliverEvent(0xf0000011, 0x0100);
+       UnDeliverEvent(0xf0000011, 0x0200);
+       UnDeliverEvent(0xf0000011, 0x2000);
+
+#if 0
+       select = loadRam8(A_CARD_ISLOT);
+       select = (select ^ 1) & 1;
+       storeRam8(A_CARD_ISLOT, select);
+#else
+       select = loadRam8(A_CARD_ACHAN) >> 4;
+       storeRam8(A_CARD_ISLOT, select);
+#endif
+       status = loadRam8(A_CARD_STATUS1 + select);
+       if (status & 1)
+               return; // done
+
+       //psxBios_SysDeqIntRP_(0, 0x7540);
+       //psxBios_SysDeqIntRP_(0, 0x7540);
+       //card_state_machine = 0;
+       //card_error_flag = 0;
+       handler = loadRam32(A_CARD_HANDLER);
+       switch (handler) {
+       case CARD_HARDLER_INFO:
+               DeliverEvent(0xf4000001, 4);
+               DeliverEvent(0xf0000011, 4);
+               storeRam8(A_CARD_STATUS1 + select, 1);
+               storeRam32(A_CARD_HANDLER, 0);
+               break;
+       case CARD_HARDLER_WRITEM:
+       case CARD_HARDLER_READM:
+               DeliverEvent(0xf4000001, 4);
+               // fallthrough
+       case CARD_HARDLER_WRITE:
+       case CARD_HARDLER_READ:
+               DeliverEvent(0xf0000011, 4);
+               storeRam8(A_CARD_STATUS1 + select, 1);
+               storeRam32(A_CARD_HANDLER, 0);
+               break;
+       case 0:
+               break;
+       default:
+               log_unhandled("%s: unhandled handler %x\n", __func__, handler);
+               DeliverEvent(0xf0000011, 0x8000);
+               storeRam8(A_CARD_STATUS1 + select, 1);
+               storeRam32(A_CARD_HANDLER, 0);
+       }
 }
 
 /* System calls C0 */
@@ -2900,7 +3250,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);
 }
 
@@ -3077,7 +3428,7 @@ static const struct {
        {     0x1920, hleop_exc1_3_1 },
        {     0x1794, hleop_exc1_3_2 },
        {     0x2458, hleop_exc3_0_2 },
-       {     0x49bc, hleop_exc_padcard1 },
+       {     0x49bc, hleop_exc_padcard1 }, // hleExcPadCard1
        {     0x4a4c, hleop_exc_padcard2 },
 };
 
@@ -3102,12 +3453,21 @@ static void write_chain(u32 *d, u32 next, u32 handler1, u32 handler2)
        if (handler2) PSXMu32ref(handler2) = HLEOP(chain_hle_op(handler2));
 }
 
-static void setup_tt(u32 tcb_cnt, u32 evcb_cnt)
+static void setup_tt(u32 tcb_cnt, u32 evcb_cnt, u32 stack)
 {
        u32 *ram32 = (u32 *)psxM;
-       u32 s_excb = 0x20, s_evcb = 0x1c * evcb_cnt;
-       u32 s_pcb = 4, s_tcb = 0xc0 * tcb_cnt;
+       u32 s_excb = 0x20, s_evcb, s_pcb = 4, s_tcb;
        u32 p_excb, p_evcb, p_pcb, p_tcb;
+       u32 i;
+
+       PSXBIOS_LOG("setup: tcb %u, evcb %u\n", tcb_cnt, evcb_cnt);
+
+       // the real bios doesn't care, but we just don't
+       // want to crash in case of garbage parameters
+       if (tcb_cnt > 1024) tcb_cnt = 1024;
+       if (evcb_cnt > 1024) evcb_cnt = 1024;
+       s_evcb = 0x1c * evcb_cnt;
+       s_tcb = 0xc0 * tcb_cnt;
 
        memset(ram32 + 0xe000/4, 0, s_excb + s_evcb + s_pcb + s_tcb + 5*4);
        psxBios_SysInitMemory_(0xa000e000, 0x2000);
@@ -3131,21 +3491,22 @@ static void setup_tt(u32 tcb_cnt, u32 evcb_cnt)
        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
 
        storeRam32(p_pcb, p_tcb);
        storeRam32(p_tcb, 0x4000);          // first TCB
+       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));
-       DeliverEvent(0xf0000003, 0x0010);
+       psxBios_SysEnqIntRP_(0, 0x6da8);
+       setup_cd_irq_and_events();
+
+       storeRam32(A_CONF_EvCB, evcb_cnt);
+       storeRam32(A_CONF_TCB, tcb_cnt);
+       storeRam32(A_CONF_SP, stack);
 }
 
 static const u32 gpu_ctl_def[] = {
@@ -3224,20 +3585,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;
@@ -3249,7 +3617,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;
@@ -3269,8 +3645,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;
@@ -3341,8 +3717,8 @@ void psxBiosInit() {
        biosA0[0x51] = psxBios_LoadExec;
        //biosA0[0x52] = psxBios_GetSysSp;
        //biosA0[0x53] = psxBios_sys_a0_53;
-       //biosA0[0x54] = psxBios__96_init_a54;
-       //biosA0[0x55] = psxBios__bu_init_a55;
+       biosA0[0x54] = psxBios_CdInit;
+       biosA0[0x55] = psxBios__bu_init;
        biosA0[0x56] = psxBios_CdRemove;
        //biosA0[0x57] = psxBios_sys_a0_57;
        //biosA0[0x58] = psxBios_sys_a0_58;
@@ -3370,7 +3746,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;
@@ -3406,20 +3782,20 @@ 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;
        //biosA0[0x99] = psxBios_EnableKernelIORedirection;
        //biosA0[0x9a] = psxBios_sys_a0_9a;
        //biosA0[0x9b] = psxBios_sys_a0_9b;
-       //biosA0[0x9c] = psxBios_SetConf;
-       //biosA0[0x9d] = psxBios_GetConf;
+       biosA0[0x9c] = psxBios_SetConf;
+       biosA0[0x9d] = psxBios_GetConf;
        //biosA0[0x9e] = psxBios_sys_a0_9e;
        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;
@@ -3497,13 +3873,13 @@ void psxBiosInit() {
        //biosB0[0x37] = psxBios_ioctl;
        //biosB0[0x38] = psxBios_exit;
        //biosB0[0x39] = psxBios_sys_b0_39;
-       //biosB0[0x3a] = psxBios_getc;
-       //biosB0[0x3b] = psxBios_putc;
+       biosB0[0x3a] = psxBios_getc;
+       biosB0[0x3b] = psxBios_putc;
        biosB0[0x3c] = psxBios_getchar;
        biosB0[0x3d] = psxBios_putchar;
        //biosB0[0x3e] = psxBios_gets;
        biosB0[0x3f] = psxBios_puts;
-       //biosB0[0x40] = psxBios_cd;
+       biosB0[0x40] = psxBios_cd;
        biosB0[0x41] = psxBios_format;
        biosB0[0x42] = psxBios_firstfile;
        biosB0[0x43] = psxBios_nextfile;
@@ -3567,19 +3943,19 @@ void psxBiosInit() {
 /**/
 
        memset(FDesc, 0, sizeof(FDesc));
-
-       // initial RNG seed
-       psxMu32ref(0x9010) = SWAPu32(0xac20cc00);
+       memset(cdir, 0, sizeof(cdir));
+       floodchk = 0;
 
        // somewhat pretend to be a SCPH1001 BIOS
        // some games look for these and take an exception if they're missing
        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;
@@ -3619,12 +3995,14 @@ void psxBiosInit() {
        ram32[0x00b0/4] = HLEOP(hleop_b0);
        ram32[0x00c0/4] = HLEOP(hleop_c0);
 
-       setup_tt(4, 16);
+       setup_tt(4, 16, 0x801fff00);
+       DeliverEvent(0xf0000003, 0x0010);
 
        ram32[0x6ee0/4] = SWAPu32(0x0000eff0); // DCB
        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
@@ -3638,18 +4016,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
@@ -3660,15 +4045,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[0x4c54/4] = HLEOP(hleop_dummy);   // for B12_InitPad?
+       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);
@@ -3677,29 +4064,31 @@ void psxBiosInit() {
        ram32[A_RCNT_VBL_ACK/4 + 1] = SWAP32(1);
        ram32[A_RCNT_VBL_ACK/4 + 2] = SWAP32(1);
        ram32[A_RCNT_VBL_ACK/4 + 3] = SWAP32(1);
+       ram32[A_RND_SEED/4] = SWAPu32(0x24040001); // was 0xac20cc00
 }
 
 void psxBiosShutdown() {
 }
 
-void psxBiosCnfLoaded(u32 tcb_cnt, u32 evcb_cnt) {
-       if (tcb_cnt != 4 || evcb_cnt != 16)
-               setup_tt(tcb_cnt, evcb_cnt);
+void psxBiosCnfLoaded(u32 tcb_cnt, u32 evcb_cnt, u32 stack) {
+       if (stack == 0)
+               stack = 0x801FFF00;
+       if (tcb_cnt != 4 || evcb_cnt != 16) {
+               setup_tt(tcb_cnt, evcb_cnt, stack);
+               DeliverEvent(0xf0000003, 0x0010);
+       }
+       storeRam32(A_CONF_SP, stack);
 }
 
 #define psxBios_PADpoll(pad) { \
+       int i, more_data = 0; \
        PAD##pad##_startPoll(pad); \
-       pad_buf##pad[0] = 0; \
-       pad_buf##pad[1] = PAD##pad##_poll(0x42); \
-       if (!(pad_buf##pad[1] & 0x0f)) { \
-               bufcount = 32; \
-       } else { \
-               bufcount = (pad_buf##pad[1] & 0x0f) * 2; \
-       } \
-       PAD##pad##_poll(0); \
+       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 (bufcount--) { \
-               pad_buf##pad[i++] = PAD##pad##_poll(0); \
+       while (more_data) { \
+               pad_buf##pad[i++] = PAD##pad##_poll(0, &more_data); \
        } \
 }
 
@@ -3716,13 +4105,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__);
@@ -3737,13 +4126,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
@@ -3753,11 +4142,11 @@ 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 code = (psxRegs.CP0.n.Cause & 0x3c) >> 2;
        u32 tcbPtr = loadRam32(A_TT_PCB);
        TCB *tcb = loadRam32ptr(tcbPtr);
+       u32 code = (SWAP32(tcb->cause) & 0x3c) >> 2;
 
        if (code != R3000E_Syscall) {
                if (code != 0) {
@@ -3768,9 +4157,9 @@ void hleExc0_2_2_syscall() // not in any A/B/C table
                return;
        }
 
-       //printf("%s c=%d a0=%d\n", __func__, code, a0);
+       //printf("%s c=%d a0=%d\n", __func__, code, SWAP32(tcb->reg[4]));
        tcb->epc += SWAP32(4);
-       switch (a0) {
+       switch (SWAP32(tcb->reg[4])) { // a0
                case 0: // noop
                        break;
 
@@ -3786,7 +4175,7 @@ void hleExc0_2_2_syscall() // not in any A/B/C table
 
                case 3: { // ChangeThreadSubFunction
                        u32 tcbPtr = loadRam32(A_TT_PCB);
-                       storeRam32(tcbPtr, a1);
+                       storeRam32(tcbPtr, SWAP32(tcb->reg[5])); // a1
                        break;
                }
                default:
@@ -3797,7 +4186,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
@@ -3813,45 +4202,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;
@@ -3879,12 +4268,11 @@ 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);
                u8 *pad_buf2 = loadRam8ptr(A_PAD_INBUF + 4);
-               int i, bufcount;
 
                psxBios_PADpoll(1);
                psxBios_PADpoll(2);
@@ -3894,14 +4282,13 @@ void hleExcPadCard1(void)
        }
        if (loadRam32(A_PAD_ACK_VBL))
                psxHwWrite16(0x1f801070, ~1);
-       if (loadRam32(A_CARD_IRQR_ENA)) {
-               // todo, maybe
-       }
+       if (loadRam32(A_CARD_IRQR_ENA))
+               card_vint_handler();
 
        mips_return_c(0, 18);
 }
 
-void hleExcPadCard2(void)
+static void hleExcPadCard2(void)
 {
        u32 ret = psxHu32(0x1074) & psxHu32(0x1070) & 1;
        mips_return_c(ret, 15);
@@ -3916,8 +4303,8 @@ void psxBiosException() {
        int i;
 
        // save the regs
-       // $at, $v0, $v1 already saved by the mips code at A_EXCEPTION
-       for (i = 4; i < 32; i++) {
+       // $at, $v0, $v1, $ra already saved by the mips code at A_EXCEPTION
+       for (i = 4; i < 31; i++) {
                if (i == 26) // $k0
                        continue;
                tcb->reg[i] = SWAP32(psxRegs.GPR.r[i]);
@@ -3930,6 +4317,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++) {
@@ -3968,6 +4356,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); \
@@ -3975,21 +4580,14 @@ void psxBiosException() {
 }
 
 #define bfreezes(ptr) bfreeze(ptr, sizeof(ptr))
-#define bfreezel(ptr) bfreeze(ptr, sizeof(*ptr))
-
-#define bfreezepsxMptr(ptr, type) { \
-       if (Mode == 1) { \
-               if (ptr) psxRu32ref(base) = SWAPu32((s8 *)(ptr) - psxM); \
-               else psxRu32ref(base) = 0; \
-       } else { \
-               if (psxRu32(base) != 0) ptr = (type *)(psxM + psxRu32(base)); \
-               else (ptr) = NULL; \
-       } \
-       base += sizeof(u32); \
-}
+#define bfreezel(ptr) bfreeze(ptr, sizeof(*(ptr)))
 
 void psxBiosFreeze(int Mode) {
        u32 base = 0x40000;
 
        bfreezes(FDesc);
+       bfreezes(ffile);
+       bfreezel(&nfile);
+       bfreezes(cdir);
+       bfreezel(&card_io_delay);
 }