sysapp.c 14.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
#include <PR/os_bbsa.h>
#include <libfb.h>
#include "sysapp.h"
#include "skerror.h"
#include "vidreset.h"
#include "gfx.h"

/* USB definition from libultra/include/arcusb.h */
#define  VUSB_CTRL_SINGLE_ENDED_0         (0x40)
#define  OTG_STAT_ID_VLD                  (0x80)
#define  OTG_STAT_LINE_STATE_CHANGE       (0x20)  /* 1=stable, 0=unstable */

/* Macros for determine if USB attached and acting as device */
#define  USB0_HOST()     ((IO_READ(USB0_OTG_STATUS_REG) & OTG_STAT_ID_VLD) == 0)
/* USB1 always a device, never a host */
#define  USB1_HOST()     (0) 

#if 0
/* No longer use SE0 to detect USB connected or not.  Does not seem to give a stable value
 * for USB0 (changes if there is activity), and does not work for USB1.
 */
#define  USB0_ATTACHED() ((IO_READ(USB0_CTL_REG) & VUSB_CTRL_SINGLE_ENDED_0) == 0)
#endif

/* Determine if USB0 or USB1 attached, try Line State Change bit - May have race condition
   with host since value may depend on RESET from host, but we don't care except upon
   startup, and USB1 cannot be disconnected from host without disconnecting power */
/* USB0: Seems to be okay without delay, no false positives */
#define  USB0_ATTACHED() ((IO_READ(USB0_OTG_STATUS_REG) & OTG_STAT_LINE_STATE_CHANGE) == 0)
/* USB1: Race condition seen, if checked too early, will give false positive */
#define  USB1_ATTACHED() ((IO_READ(USB1_OTG_STATUS_REG) & OTG_STAT_LINE_STATE_CHANGE) == 0)

#define USB_ATTACHED(which)   ((which)? USB1_ATTACHED(): USB0_ATTACHED())
#define USB_HOST(which)       ((which)? USB1_HOST(): USB0_HOST())

extern u32 osBbLoadSA2();
extern s32 osBbExecSA(u32 loadAddr, u32 entryCode);
extern void monproc();
extern int  check_sysid_file();

#define _USE_CONTROLS 0
#define _USE_POWERBUTTON 1

#define printstr fbPrintf

static u32 gMiSecModeRegEntryVal;
extern u32  __osBbHackFlags;

#if USE_TEXTURE
extern unsigned char gzTexMsg1[];
extern int gzTexMsg1Size;
extern unsigned char gzTexMsg2[];
extern int gzTexMsg2Size;
#endif

#ifdef FBDEBUG
char tmpstr[256];
#endif

/*
 * Thread and stack structures
 */

char   bootStack[STACKSIZE] __attribute__ ((aligned (8)));

/* Thread priorities */
#define IDLE_START_PRIORITY 20
#define MAIN_PRIORITY 18
#define HELPER_PRIORITY 15

/* Thread IDs */
#define IDLE_ID        1
#define MAIN_ID        3
#define HELPER_ID      5

static OSThread idleThread;
static char     idleThreadStack[STACKSIZE] __attribute__ ((aligned (8)));

static OSThread mainThread;
static char     mainThreadStack[STACKSIZE] __attribute__ ((aligned (8)));

static OSThread helperThread;
static char     helperThreadStack[STACKSIZE] __attribute__ ((aligned (8)));

static void	idleproc(char *);
static void	mainproc(char *);
static void	helperproc(char *);

#define MAGIC_STASH_ADDR     ((void*)PHYS_TO_K1(USB1_BDT_SRAM+256))
static char magic_stash[256];

#define DMA_QUEUE_SIZE	200

static OSMesg           PiMessages[DMA_QUEUE_SIZE];
static OSMesgQueue      PiMessageQ;

static OSMesg           SiMessages[DMA_QUEUE_SIZE];
static OSMesgQueue      SiMessageQ; 

/* USB status */
static int usbHost = 0;
static int usbAttached = 0;
static int which_usb = 0;

/*
 * simple graphics
 */

static OSMesgQueue      retraceMessageQ;
static OSMesg           dummyMessage, retraceMessageBuf;

static int gLaunchSA2  = 0;

#if _USE_CONTROLS
static int gLaunchTime = 0;

/*
 * controller
 */
static OSMesgQueue      contMessageQ;
OSContStatus statusData[MAXCONTROLLERS];
OSContPad controllerData[MAXCONTROLLERS];
static u16 lastbutton[MAXCONTROLLERS];
static int no_controller = 1;

static void
initController(void)
{
    int i, c = 0;
    u8 pattern;

    if (__osBbIsBb<2)
        __osBbHackFlags = 1;
    else
        __osBbHackFlags = 0;

    osCreateMesgQueue(&contMessageQ, &dummyMessage, 1);
    osSetEventMesg(OS_EVENT_SI, &contMessageQ, (OSMesg) 0);

    osContInit(&contMessageQ, &pattern, &statusData[0]);

    for (i = 0; i < MAXCONTROLLERS; i++) {
        if ((pattern & (1 << i)) &&
            !(statusData[i].errno & CONT_NO_RESPONSE_ERROR)) {
            ++c;
            no_controller = 0;
        }
    }
}

static void
processButton(u16 button, int lastbutton)
{
    if (button & A_BUTTON && !(lastbutton & A_BUTTON)) {
        gLaunchTime = 1;
        gLaunchSA2  = 1;
        return;
    }

    if (button & B_BUTTON && !(lastbutton & B_BUTTON)) {
        gLaunchTime = 1;
        gLaunchSA2  = 0;
        return;
    }
}

static void
readControllers(void)
{
    int i;
    OSContPad *pad;

    osRecvMesg(&contMessageQ, &dummyMessage, OS_MESG_BLOCK);
    osContGetReadData(controllerData);

    for (i = 0; i < MAXCONTROLLERS; ++i) {
        pad = &controllerData[i];
        if (!pad->errno && pad->button != lastbutton[i]) {
            processButton(pad->button, lastbutton[i]);
            lastbutton[i] = pad->button;
        }
    }
}
#endif

static void
startup(u32 entryCode)
{
    /* Save BDT state */
    memcpy(magic_stash, MAGIC_STASH_ADDR, sizeof(magic_stash));

    /* Check BBID - create id.sys file if not present */
    uiBbidCheck();
}

void  __osBbVideoPllInit(u32);
void boot(u32 miSecModeRegVal)
{
    gMiSecModeRegEntryVal = miSecModeRegVal;

    /* Copied from viewer.c */
    /*
     * Turn off the button interrupt
     */
    IO_WRITE(MI_INTR_EMASK_REG, MI_INTR_MASK_CLR_BUT);

    /*
     * Init Pll. No need to do all this if it already happened
     */
    if ((gMiSecModeRegEntryVal & 
         (MI_SEC_MODE_BUT_TRAP | MI_SEC_MODE_TIMER | MI_SEC_MODE_APP)) == 0) {
        __osBbVideoPllInit(OS_TV_NTSC);
        vidReset(&cfb[0]);
    } else {
        /*
         * Make the video output black
         */
        IO_WRITE(VI_H_START_REG, 0x0);
    }

    osInitialize();

    osCreateThread(&idleThread, IDLE_ID, (void(*)(void *))idleproc, (void *)0,
                   idleThreadStack+STACKSIZE, IDLE_START_PRIORITY);
    osStartThread(&idleThread);
}

#if _USE_POWERBUTTON
/* For handling power button */
static OSMesg           nmiMessages[1];
static OSMesgQueue      nmiMessageQ;

#define BUT_RELEASED (!((IO_READ(MI_EINTR_REG)&MI_EINTR_BUTTON_PRESSED)))

static void
check_powerbutton()
{
    static int pwrbtn_ready = 0;

    /* Check if power button pressed */
    if (pwrbtn_ready) {
        if (osRecvMesg(&nmiMessageQ, NULL, OS_MESG_NOBLOCK) == 0) {
            osBbPowerOff();
        }
    } else {
        if (BUT_RELEASED) {
            IO_WRITE(MI_INTR_EMASK_REG, MI_INTR_MASK_SET_BUT);
            pwrbtn_ready = 1;
        }
    }
}
#endif /* _USE_POWERBUTTON */

static void
idleproc(char *argv)		/* priority 20 */
{ 
    /*
     * Start PI Mgr for access to cartridge - start before the debugger
     */
    osCreatePiManager((OSPri) OS_PRIORITY_PIMGR, &PiMessageQ, PiMessages,
            DMA_QUEUE_SIZE);

    osCreateMesgQueue(&SiMessageQ, SiMessages, DMA_QUEUE_SIZE);
    osSetEventMesg(OS_EVENT_SI, &SiMessageQ, (OSMesg)DMA_QUEUE_SIZE);

    /*
     * The main thread's priority must be the same or lower than the original
     * idle's thread priority. This allows the idle thread to change its
     * priority to 0 before the main thread starts execution.
     */
    osCreateThread(&mainThread, MAIN_ID, (void(*)(void *))mainproc, argv,
                   mainThreadStack+STACKSIZE, (OSPri) MAIN_PRIORITY);
    osStartThread(&mainThread);

    /* Create message queues for power button */
    osCreateMesgQueue(&nmiMessageQ, nmiMessages, 1);
    osSetEventMesg(OS_EVENT_PRENMI, &nmiMessageQ, (OSMesg) 1);

    osSetThreadPri(0, OS_PRIORITY_IDLE);

    for (;;) {}
}

static void
helperproc(char *argv)		/* priority 15 */
{
    /* Helper thread for checking power button and debugging */
    for (;;) {
        osRecvMesg(&retraceMessageQ, NULL, OS_MESG_BLOCK);
#if _USE_POWERBUTTON
        /* NOTE: There is no synchronization with mon so it is 
           for someone who are writing their card to press the
           power button and cause the BBplayer to turn off at
           and inopportune time */   
        check_powerbutton();
#endif

#ifdef FBDEBUG
        /* Don't print any more debugging stuff if launching SA2 */
        if (gLaunchSA2) continue;

        sprintf(tmpstr, "USB CTL REG: 0x%02x, 0x%02x", 
                IO_READ(USB0_CTL_REG), IO_READ(USB1_CTL_REG));
        printstr(fbWhite, 3, 3, tmpstr);
        sprintf(tmpstr, "USB OTG STAT REG: 0x%02x, 0x%02x",
                IO_READ(USB0_OTG_STATUS_REG), IO_READ(USB1_OTG_STATUS_REG));
        printstr(fbWhite, 3, 4, tmpstr);
        osWritebackDCacheAll();
        if (usbAttached) {
            sprintf(tmpstr, "USB %d Attached\n", which_usb);
            printstr(fbWhite, 3,2,  tmpstr);
            osWritebackDCacheAll();

            osBbSetErrorLed(1);
            /* Check to see if usb state still agrees */
            if (!USB_ATTACHED(which_usb)) {
                /* Flash */
                __osBbDelay(200000);
                osBbSetErrorLed(0);
                __osBbDelay(200000);
                if (which_usb) {
                    osBbSetErrorLed(1);
                    __osBbDelay(10000);
                    osBbSetErrorLed(0);
                    osBbSetErrorLed(1);
                    __osBbDelay(10000);
                    osBbSetErrorLed(0);
                    __osBbDelay(200000);                
                }
            }
            osBbSetErrorLed(1);
         }
        else {
            sprintf(tmpstr, "USB %d Disconnected\n", which_usb);
            printstr(fbWhite, 3,2,  tmpstr);
            osBbSetErrorLed(0);
        }
#endif
    }
}

void mainproc(char *argv)
{
    u32 loadAddr;

    /* Start VI manager and clear screen */
    osCreateViManager(OS_PRIORITY_VIMGR);
    fbInit(FB_LOW_RES);

    /* setup text output to screen */
    osCreateMesgQueue(&retraceMessageQ, &retraceMessageBuf, 1);
    osViSetEvent(&retraceMessageQ, dummyMessage, 1);
    osViBlack(1);
    osViSwapBuffer(cfb);
    fbSetBg(fbBlack);
    fbClear();
    osViBlack(0);
    osWritebackDCacheAll();
    osViSwapBuffer(cfb);
    fbClear();

#if USE_TEXTURE
    initGFX(); 
#endif

#ifdef FBDEBUG
    printstr(fbWhite, 3, 2, "iQue Loader");
    printstr(fbWhite, 3, 12, "Saving game state");
    osWritebackDCacheAll();
#endif

    /* Call startup code */
    /* Be sure to do this before initializing USB1.
       Otherwise, the game state will be lost!!! */
    startup(gMiSecModeRegEntryVal);
   
    /* Start helper thread (for checking power button and all) */
    osCreateThread(&helperThread, HELPER_ID, (void(*)(void *))helperproc, argv,
                   helperThreadStack+STACKSIZE, (OSPri) HELPER_PRIORITY);
    osStartThread(&helperThread);

#ifdef FBDEBUG
    printstr(fbWhite, 3, 12, "Detecting USB       ");
    osWritebackDCacheAll();
#endif

    /* Try to get USB initialized and figure out if 
       USB0 or USB1 is attached as soon as possible */

    /* Try to initialize USB1 as device, USB0 disabled */
    which_usb = 1;
    osBbUsbSetCtlrModes(~which_usb & 1, OS_USB_TYPE_DISABLED);
    osBbUsbSetCtlrModes(which_usb, OS_USB_TYPE_DEVICE);
    (void) osBbUsbInit();

#ifdef USB_PRINTF
    /* Wait for a while to before we are ready to do debug printfs */
    __osBbDelay(1400000);

    /* osGetTime need to be started after the VI manager */
    PRINTF("Start: %llu\n", OS_CYCLES_TO_NSEC(osGetTime()));
    PRINTF("gMiSecModeRegEntryVal=0x%08x\n", gMiSecModeRegEntryVal);
#endif

    /* Load viewer regardless */
#ifdef FBDEBUG
    PRINTF("Load: %llu\n", OS_CYCLES_TO_NSEC(osGetTime()));
    printstr(fbWhite, 3, 12, "Loading viewer...");
    osWritebackDCacheAll();
#endif
    
    loadAddr = osBbLoadSA2();
    
    /* Check USB attached and if it is device or host */
    usbHost = USB_HOST(which_usb);
    usbAttached = USB_ATTACHED(which_usb);

    if (!usbAttached) {
	u64 tlim;
	int rc;

        /* Try to initialize USB0 as device, USB1 disabled */
        which_usb = ~which_usb & 1;
        osBbUsbSetCtlrModes(~which_usb & 1, OS_USB_TYPE_DISABLED);
        osBbUsbSetCtlrModes(which_usb, OS_USB_TYPE_DEVICE);
        (void) osBbUsbInit();

	/*
	 * Consider USB0 attached if any additional resets
	 * are received after the completion of UsbInit.
	 * Note that the initialization sequence causes
	 * one spurious reset on some players.
	 *
	 * Wait 2 seconds for the real reset from Windows.
	 * XXX can probably reduce this time limit
	 */
        usbHost = USB_HOST(which_usb);
	usbAttached = 0;
        rc = osBbUsbGetResetCount(which_usb);
        tlim = OS_CYCLES_TO_USEC(osGetCount()) + 2000000LL;

        while (OS_CYCLES_TO_USEC(osGetCount()) < tlim) {
            if (osBbUsbGetResetCount(which_usb) > rc) {
                usbAttached = 1;
                break;
            }
        }
    }

    /* Determine if we should start viewer or mon */
#if _USE_CONTROLS
    PRINTF("init controls\n");
    initController();

    do {
        osRecvMesg(&retraceMessageQ, NULL, OS_MESG_BLOCK);
        osContStartReadData(&contMessageQ);
        readControllers();
    } while(!gLaunchTime);
#else /* Not using controls */
    /* Launch viewer if the BB Player is acting as host or is not connected */
    gLaunchSA2 = (usbHost || !usbAttached);
    // Make sure led off for launch
    osBbSetErrorLed(0);
#endif

    /* Launch SA2 or start mon */
    if (gLaunchSA2) {
        if (loadAddr) {
#ifdef FBDEBUG
            PRINTF("Launch: %llu\n", OS_CYCLES_TO_NSEC(osGetTime()));
            printstr(fbWhite, 3, 12, "Launching viewer...");
            osWritebackDCacheAll();
#endif

            /* Put magic stash back */
            __osDisableInt();
            memcpy(MAGIC_STASH_ADDR, magic_stash, sizeof(magic_stash));
            osBbExecSA(loadAddr, gMiSecModeRegEntryVal);
        }
        else {
            /* Problem launching viewer - print error message
               and enter mon mode */
#if USE_TEXTURE
            PRINTF("Displaying gzTexMsg2\n");
            displayGzippedTexture(gzTexMsg2, gzTexMsg2Size);
#else
            /* print english message */
            printstr(fbWhite, 3, 6, "Error launching viewer.");
            printstr(fbWhite, 3, 7, "Please connect the iQue player to");
            printstr(fbWhite, 3, 8, "iQue@Home to update the viewer.");
            osWritebackDCacheAll();
#endif
            PRINTF("Starting mon\n");
            monproc();
        }
    }
    else {
#if USE_TEXTURE
        PRINTF("Displaying gzTexMsg1\n");
        displayGzippedTexture(gzTexMsg1, gzTexMsg1Size);
#else
        printstr(fbWhite, 3, 6, "Please use iQue@Home to manage");
        printstr(fbWhite, 3, 7, "and update the iQue player.");
        osWritebackDCacheAll();
#endif

        PRINTF("Starting mon\n");
        monproc();
    }

     PRINTF("\nAPP FINISHED\n");
    osBbPowerOff();
    return;
}