devmon.c 16.2 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 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
#include "ultra64.h"
#include "os_bb.h"
#include "bcp.h"
#include "bbvirage.h"

#include "devmon.h"
#include "libfb.h"

char version[] = VERSION;

extern u32 __osBbHackFlags;
s32 binding[] = {0, 1, 2, 3};
static    u8 pattern;
static u16 lastbutton[MAXCONTROLLERS];
static char msg[256];
static u16 cfb[320*240] __attribute__((aligned(64)));
OSContStatus statusData[MAXCONTROLLERS];
OSContPad controllerData[MAXCONTROLLERS];

#define DMA_QUEUE_SIZE	200

/*
 * Thread and stack structures
 */
char   bootStack[STACKSIZE] __attribute__ ((aligned (8)));

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

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

static OSThread monThread;
static char     monThreadStack[STACKSIZE] __attribute__ ((aligned (8)));

/*
 * Message queues and message buffers used by this app 
 */
static OSMesg           PiMessages[DMA_QUEUE_SIZE];
static OSMesgQueue      PiMessageQ;

static OSMesg           SiMessages[DMA_QUEUE_SIZE];
static OSMesgQueue      SiMessageQ, contMessageQ;

static OSMesg           nmiMessages[1];
static OSMesgQueue      nmiMessageQ;

OSPiHandle              *handler;

#define NUM_ACCESS_MESG 1
static OSMesgQueue accessQueue;
static OSMesg accessBuf[NUM_ACCESS_MESG];
static int queueCreated = 0;

static void
createQueue(void)
{
    osCreateMesgQueue(&accessQueue, accessBuf, NUM_ACCESS_MESG);
    (void) osSendMesg(&accessQueue, (OSMesg)0, OS_MESG_NOBLOCK);
    queueCreated = 1;
}

static void
getAccess(void)
{
    OSMesg dummyMesg;

    /* Create access message queue if haven't done so */
    if (!queueCreated) {
        createQueue();
    }

    (void)osRecvMesg(&accessQueue, &dummyMesg, OS_MESG_BLOCK);
}

static void
relAccess(void)
{
    (void) osSendMesg(&accessQueue, (OSMesg)0, OS_MESG_NOBLOCK);
}

/*
 * Local variables and routines
 */

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

static u32 entryCode;
void
boot(u32 reg)
{
    entryCode = reg;

    /*
     * 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 ((entryCode & (MI_SEC_MODE_BUT_TRAP | MI_SEC_MODE_TIMER | MI_SEC_MODE_APP)) == 0) {
        extern void __osBbVideoPllInit(s32);
        __osBbVideoPllInit(OS_TV_NTSC);
    } else {
        /*
         * Make the video output black
         */
        IO_WRITE(VI_H_START_REG, 0x0);
    }

    osInitialize();
    osCreateThread(&idleThread, 1, (void(*)(void *))idleproc, (void *)0,
                   idleThreadStack+STACKSIZE, 8);
    osStartThread(&idleThread);
}


static void
idleproc(char *argv)		/* priority 8 */
{
    osCreateViManager(OS_PRIORITY_VIMGR);
    /*
     * 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);

    osCreateMesgQueue(&nmiMessageQ, nmiMessages, 1);
    osSetEventMesg(OS_EVENT_PRENMI, &nmiMessageQ, (OSMesg)1);

    /*
     * 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, 3, (void(*)(void *))mainproc, argv,
           mainThreadStack+STACKSIZE, (OSPri)7);
    osStartThread(&mainThread);

    osSetThreadPri(0, OS_PRIORITY_IDLE);
    for(;;);                                    /* idle thread */
}

static OSMesgQueue	retraceMessageQ;
static OSMesg		dummyMessage, retraceMessageBuf;

static u8 block[BB_FL_BLOCK_SIZE] __attribute__((aligned(16)));
static u16 blockList[8*1024];
static OSBbFs fs;
static OSBbDirEnt dir[410];
static int num_files = 0;
static int current = 0;

static int top = 0;

s32 sberrCorrect(char stateName[] /* 8.3 <cid>.sta */)
{
    s32 fd;
    u32 addr;
    int i;

    addr = IO_READ(PI_ERROR_REG);
    if(! ((addr & PI_ERROR_CORRECTABLE_ECC) &&
         !(addr & PI_ERROR_UNCORRECTABLE_ECC))) return 0;

    addr &= PI_ERROR_ADDR_MASK;
    addr -= osBbAtbGetVAddr();

    for(i=0; i<8 && stateName[i]!='.'; i++);
    stateName[i+1]='a';
    stateName[i+2]='e';
    stateName[i+3]='s';
    stateName[i+4]='\0';
    if( (fd = osBbFOpen(stateName,"r")) < 0){
        return -1;
    }
    return osBbFRepairBlock(fd,addr&(~(BB_FL_BLOCK_SIZE-1)),block,
                            BB_FL_BLOCK_SIZE);
}

static void
drawFile(int i) {
    int x, y;
    u16 color;
    if ((i < top || i > (top+7)) && (i < ((num_files+1)/2+top) || i > ((num_files+1)/2+7+top))) {
        return;
    }
    color = i == current ? GPACK_RGBA5551(255,0,255,1): fbWhite;
    x = (i >= (num_files+1)/2) ? 20 : 5;
    y = 4-top+(i % ((num_files+1)/2));
    fbPrintStr(color, x, y, dir[i].name);
}

static void redraw(void) {
    int i;
    char *title =  "Dev Kit";

    fbClear();
    fbPrintStr(fbMarkColor, 2+16-strlen(title)/2, 2, title);
    if (num_files == 0) {
        current = -1;
        fbPrintStr(fbRed, 6, 4, "No files found!");
    }
    for (i = 0; i < num_files; ++i) {
        drawFile(i);
    }
    if (top) {
        fbPrintStr(fbYellow, 17, 4, "^^^");
    }
    if (top < num_files/2-8) {
        fbPrintStr(fbYellow, 17, 12, "vvv");
    }

    if (*msg) {
        fbPrintStr(fbRed, 4, 13, msg);
        *msg = 0;
    }

    osWritebackDCacheAll();
}

static void
readFiles(void) {
    int i;
    current = 0;
    num_files = osBbFReadDir(dir, sizeof dir/sizeof dir[0]);
    for (i = 0; i < num_files-1; ++i) {
        int j, k;
        for (j = i+1; j < num_files; ++j) {
            int l1 = strlen(dir[i].name);
            int l2 = strlen(dir[j].name);
            for (k = 0; k < l1 < l2 ? l1 : l2; ++k) {
                if (dir[i].name[k] > dir[j].name[k]) {
                    OSBbDirEnt tmp = dir[i];
                    dir[i] = dir[j];
                    dir[j] = tmp;
                    break;
                } else if (dir[i].name[k] < dir[j].name[k]) {
                    break;
                }
            }
        }
    }
    for (i = 0; i < num_files; ++i) {
        int j = strlen(dir[i].name);
        if ((j < 4 || dir[i].name[j-4] != '.' || dir[i].name[j-3] != 'a' || 
                      dir[i].name[j-2] != 'e' || dir[i].name[j-1] != 's')) {
            --num_files;
            for (j = i; j < num_files;++j) {
                dir[j] = dir[j+1];
            }
            --i;
        }
    }
}


static void
initController(void)
{
    __osBbHackFlags = 0;

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

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

static void
executeApp(char *name)
{
    int i, fd;
    u32 const ekey[] = {
        0x13448f2f, 0x5e91bda9, 0xb0f3b531, 0xd80ec5eb,
        0x174f0987, 0xd600f10b, 0xa48f7a4d, 0xe5bc83e5,
        0x06b1dca9, 0xc14ff88c, 0x728f8b46, 0x4133f9a8,
        0x88d96d13, 0xc7fe2425, 0xb3c073ca, 0x33bc72ee,
        0x210b14c1, 0x4f274936, 0x743e57ef, 0x807c0124,
        0xe6ee3bec, 0x6e2c5df7, 0x3b191ed9, 0xf44256cb,
        0xe790a78d, 0x88c2661b, 0x5535432e, 0xcf5b4812,
        0xa1d03bd0, 0x6f52c196, 0xddf72535, 0x9a6e0b3c,
        0x2125d871, 0xce82fa46, 0xb2a5e4a3, 0x47992e09,
        0xeab26c42, 0xefa72237, 0x7c271ee5, 0xf53ccaaa,
        0xa5ef7877, 0x0e8813be, 0x481e06ad, 0xbf97f0d1
    };

    u32 const iv[] = {
        0x55284d8c, 0xad8f83a0, 0xa9736a29, 0xf5e39359
    };

    sprintf(msg, "Launching: %s...", name);
    redraw();
    __osBbHackFlags = 0;

    for(i = 0; i < 44; i++) {
        IO_WRITE(PI_AES_EKEY_REG+i*4,ekey[i]);
    }

    /* copy iv to pi buf */
    IO_WRITE(PI_AES_INIT_REG,iv[0]);
    IO_WRITE(PI_AES_INIT_REG+4,iv[1]);
    IO_WRITE(PI_AES_INIT_REG+8,iv[2]);
    IO_WRITE(PI_AES_INIT_REG+12,iv[3]);

    fd = osBbFOpen(name, "r");
    if (fd >= 0) {
        OSBbStatBuf sb;
        if (osBbFStat(fd, &sb, blockList, sizeof(blockList)/sizeof(blockList[0])) >= 0) {
            OSBbLaunchMetaData md;
            u32 addr;
            s32 listSize = sb.size / BB_FL_BLOCK_SIZE;
            if (osBbGetLaunchMetaData(&md, blockList, listSize) >= 0) {
                osBbLoadState(name, 0, &md.state, binding);
            }
            else osBbInitState(name);
            if ((addr = osBbLoadApp(&md, blockList, listSize, 0)) != NULL) {
                osBbExecApp(addr);
            }
        }
    }
}
    
static void
processButton(u16 button, int lastbutton)
{
    int old = current;

    if (current == -1) {
	redraw();
	return;
    }
    if (button & D_JPAD && !(lastbutton & D_JPAD)) {
        current = (current + 1) % num_files;
    }

    if (button & U_JPAD && !(lastbutton & U_JPAD)) {
        current = (current - 1) < 0? num_files - 1: current-1;
    }

    if (button & R_JPAD && !(lastbutton & R_JPAD)) {
        if (current + (num_files+1)/2 < num_files) {
            current += (num_files+1)/2;
        }
    }

    if (button & L_JPAD && !(lastbutton & L_JPAD)) {
        if (current >= (num_files+1)/2) {
            current -= (num_files+1)/2;
        }
    }

    if ((button & A_BUTTON && !(lastbutton & A_BUTTON)) ||
        (button & START_BUTTON && !(lastbutton & START_BUTTON))) {
        executeApp(dir[current].name);
    }



    if (old != current) {
        if (current < (num_files+1)/2) {
            if (current < top) {
                top = current;
            } else if (current > top+7) {
                top = current - 7;
            }
        } else {
            if (current-(num_files+1)/2 < top) {
                top = current-(num_files+1)/2;
            } else if (current-(num_files+1)/2 > top+7) {
                top = current-(num_files+1)/2 - 7;
            }
        }
    }
    redraw();
}

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

    getAccess();
    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;
        }
    }
    relAccess();
}

static u8 name[256], name2[256];
static void
monproc(char *argv)
{
    s32 rv = 0, i, n, len, fd, off;

    for(;;) {
        unsigned int hbuf[2], rbuf[2], size;
        osReadHost(hbuf, sizeof hbuf);
        getAccess();
        rbuf[0] = 255-hbuf[0];
        rbuf[1] = 0;
        switch(hbuf[0]) {
        case REQ_WRITE_FILE:
            osReadHost(&size, sizeof size);
            size = (size+3)&~3;
            if (size > sizeof(name))
                size = sizeof(name);
            osReadHost(name, size);
            size = (hbuf[1]+BB_FL_BLOCK_SIZE-1)&~(BB_FL_BLOCK_SIZE-1);
            len = (hbuf[1]+3)&~3;
            fd = osBbFCreate(name, 1, size);
            rbuf[1] = fd < 0 ? fd : 0;
            osWriteHost(rbuf, sizeof rbuf); /* first response */
            if (fd >= 0) {
                off = 0;
                while(len > 0) {
                    n = len > sizeof block ? sizeof block : len;
                    if (n != sizeof block) bzero(block, sizeof block);
                    osReadHost(block, n);
                    if ((rv = osBbFWrite(fd, off, block, sizeof block)) < 0) {
                        break;
                    }
                    len -= n;
                    off += sizeof block;
                    if (off % (16 * sizeof block) == 0) {
                        sprintf(msg, "Write: %s %d%%", name, (int)(100.0f*off/size));
                        redraw();
                    }
                }
                osBbFClose(fd);
                rbuf[1] = fd < 0 ? fd : rv < 0 ? rv : 0;
                osWriteHost(rbuf, sizeof rbuf); /* second response */
            }
            sprintf(msg, "Wrote: %s %s", name, rbuf[1] < 0 ? "(failed)": "");
            readFiles();
            break;
        case REQ_DELETE_FILE:
            size = (hbuf[1]+3)&~3;
            if (size > sizeof(name))
                size = sizeof(name);
            osReadHost(name, size);
            rv = osBbFDelete(name);
            rbuf[1] = rv;
            osWriteHost(rbuf, sizeof rbuf);
            sprintf(msg, "Delete: %s %s", name, rv < 0 ? "(failed)": "");
            readFiles();
            break;
        case REQ_READ_DIR:
            rv = osBbFReadDir(dir, sizeof dir/sizeof dir[0]);
            rbuf[1] = rv;
            osWriteHost(rbuf, sizeof rbuf);
            for(i = 0; i < rv; ++i) {
                osWriteHost(dir[i].name, 16);
                osWriteHost(&dir[i].size, 4);
            }
            readFiles();
            break;
        case REQ_READ_FILE:
            size = (hbuf[1]+3)&~3;
            if (size > sizeof(name))
                size = sizeof(name);
            osReadHost(name, size);
            fd = osBbFOpen(name, "r");
            if (fd < 0) {
                rbuf[1] = fd;
                len = 0;
            } else {
                OSBbStatBuf sb;
                if ((rv = osBbFStat(fd, &sb, 0, 0)) < 0) {
                    len = 0;
                } else
                    len = rbuf[1] = sb.size;
            }
            osWriteHost(rbuf, sizeof rbuf);
            off = 0;
            size = len;
            while(fd >= 0 && len > 0) {
                n = len > sizeof block ? sizeof block : len;
                if ((rv = osBbFRead(fd, off, block, sizeof block)) < 0) {
                    break;
                }
                osWriteHost(block, n);
                len -= n;
                off += sizeof block;
                sprintf(msg, "Read: %s %d%%", name, (int)(100.0f*off/size));
                redraw();
            }
            osBbFClose(fd);
            sprintf(msg, "Read: %s %s", name, rbuf[1] < 0 ? "(failed)": "");
            break;
        case REQ_EXEC_FILE:
            size = (hbuf[1]+3)&~3;
            if (size > sizeof(name))
                size = sizeof(name);
            osReadHost(name, size);
            fd = osBbFOpen(name, "r");
            if (fd < 0) {
                rbuf[1] = fd;
            }
            osWriteHost(rbuf, sizeof rbuf);
            if (fd >= 0)
                executeApp(name);
            break;
	case REQ_RENAME_FILE:
	    size = (hbuf[1]+3)&~3;
	    if (size > sizeof(name))
		size = sizeof(name);
	    osReadHost(name, size);
	    osReadHost(&len, 4);
	    len = (len+3)&~3;
	    if (len > sizeof(name2))
		len = sizeof(name2);
	    osReadHost(name2, len);
	    rbuf[1] = osBbFRename(name, name2);
	    osWriteHost(rbuf, sizeof rbuf);
            sprintf(msg, "Rename: %s->%s", name, name2);
            readFiles();
	    break;
        case REQ_PING:
            osWriteHost(rbuf, sizeof rbuf);
            sprintf(msg, "Ping...");
            break;
        }
        redraw();
        relAccess();
    }
}

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

static void 
mainproc(char *argv) {
    s32 rv;
    int ready = 0;
    void __osBbDelay(u32);

    if ((rv = osBbUsbInit()) < 0) {
        return;
    }

    __osBbDelay(800000);
    osSyncPrintf("devmon (%s)...\n", version);

    osCreateThread(&monThread, 3, (void(*)(void *))monproc, argv,
           monThreadStack+STACKSIZE, (OSPri)6);
    osStartThread(&monThread);

    osCreateMesgQueue(&retraceMessageQ, &retraceMessageBuf, 1);
    osViSetEvent(&retraceMessageQ, dummyMessage, 1);
    osViBlack(1);
    osViSwapBuffer(cfb);
    initController();

    osBbFInit(&fs);
    
    if (entryCode & (MI_SEC_MODE_APP|MI_SEC_MODE_BUT_TRAP)) {
        char stateName[16];
        BbTicketId tid;
        if (osBbSaveState(stateName, &tid) == 0) {
            sberrCorrect(stateName);
        }
    }

    fbInit(FB_LOW_RES);

    readFiles();
    redraw();

    osViBlack(0);
    osViSwapBuffer(cfb);

    for(;;) {
        osRecvMesg(&retraceMessageQ, NULL, OS_MESG_BLOCK);
        if (ready) {
            osContStartReadData(&contMessageQ);
            if (osRecvMesg(&nmiMessageQ, NULL, OS_MESG_NOBLOCK) == 0)
                osBbPowerOff();
            readControllers();
        } else {
            if (BUT_RELEASED) {
                IO_WRITE(MI_INTR_EMASK_REG, MI_INTR_MASK_SET_BUT);
                ready = 1;
            }
        }
    }
}