boot.c 20.7 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 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
#include <PR/bcp.h>
#include <PR/bbboot.h>
#include <PR/bbnand.h>
#include <PR/bbticket.h>
#include <PR/bbvirage.h>
#include <PR/bbfs.h>
#include <PR/bbcert.h>
#include <aes.h>
#include "util.h"
#include "cert.h"
#include "rl.h"
#include "nvram.h"

#if defined(SK_LOG_RDB)
#include <PR/bbdebug.h>
#endif

/*
 * defines used only locally
 */


#define SK_BLOCKS (LOAD_SK_PAGES/PI_FLASH_PAGES_PER_BLOCK)


/*
 * 8 bytes into rom is load address (as kseg0/1, not physical)
 */
#define N64_ROM_LOADADDR_OFFSET 8


/* patch BbCrlBundle pointers from ticket bundle (packaged as
 * offsets from wherever 16KB ticket bundle is loaded).
 */
#define BOOT_PATCH_RL(_name,_off)                                      \
    if(rlBundle->##_name.head != NULL) rlBundle->##_name.head  =       \
                (BbCrlHead *)(((u32)(rlBundle->##_name.head))          \
                + (u32)_off);                                          \
    rlBundle->##_name.list =                                           \
                (BbServerSuffix *)(((u32)(rlBundle->##_name.list))     \
                + (u32)_off);                                          \
    rlBundle->##_name.certChain[0] =                                   \
                (BbCertBase *)(((u32)(rlBundle->##_name.certChain[0])) \
                + (u32)_off);                                          \
    rlBundle->##_name.certChain[1] =                                   \
                (BbCertBase *)(((u32)(rlBundle->##_name.certChain[1])) \
                + (u32)_off);


/* NOTE: best 2of3 for 1B value in spare area bytes 512, 513 and 514.
 *       Making assumption that a 2of3 match exists because:
 *          i) it's simpler code
 *         ii) someone could attack by setting up flash anyhow, so 
 *             we don't have a true protection mechanism
 *        iii) the result of loading the wrong block is just that
 *             bytes pass through the decryption engine (someone
 *             could be attempting to crack the key), but the code
 *             is never run since the hash will fail.
 */
u32 getBlockLink(u32 encoded)
{
    if( ((encoded>>8)&0xff) == ((encoded>>16)&0xff))
        return (encoded>>8)&0xff;
    return (encoded>>24)&0xff;
}

#define SK_LOCKDOWN
#ifdef SK_LOCKDOWN
static int lockSk(void);
#endif

/* Return is error if < 0 (as per def'ns in boot.h), and block
 * index when >=0.
 *
 * NOTE: first page of good block will be in pi buf 0. 
 */
int getGoodBlock(int startSearch)
{
    int i, badbits, bitshift;
    u32 blockStatus;
    u32 ret;

    do{
        ret = readFlashPage(startSearch<<PI_FLASH_PAGE_PER_BLOCK_POW2,0);
       if(ret == SK_ERROR_FLASH_MODULE_REMOVED){
            return ret;
        }
        blockStatus = IO_READ(PI_BUFFER_0_OOB_START +
                              (PI_FLASH_OOB_BLOCK_STATUS_OFFSET&(~3)));

        /* Given the current definitions in bbnand.h, blockStatus
         * holds bytes 516, 517, 518 and 519 from the flash page.
         * If more than one bit of byte 517 is 0, the block is bad.
         * The bitshift computation will insure byte 517 is checked
         * (or whatever the defines in bbnand.h dictate).
         */
        bitshift = (3 - (PI_FLASH_OOB_BLOCK_STATUS_OFFSET&3))*8;
        for(badbits=0,i=0;i<8;i++){
            if( !((blockStatus>>(bitshift+i))&1) ){
#ifdef DEBUG
                message("Found 0 bit in block status byte.\n");
#endif
                badbits++;
            }
        }
        startSearch++;
    }while(badbits>1);

    if(ret == SK_ERROR_FLASH_CTRL_DOUBLE_BIT){
#ifdef DEBUG
        /* block status was good, but had double-bit ECC error */
        message("Double bit error in getGoodBlock.\n");
#endif
        return ret;
    }

    return startSearch-1;
}

/* skip over "skip" good blocks, starting at block startBlock,
 * and return the number of the first good block past the skip.
 *
 * Return is error if < 0 (as per def'ns in boot.h), and block
 * index when >=0.
 *
 * NOTE: the first page of block with the returned index will
 *       be in PI buffer 0.
 */
int findGoodBlock(int startBlock,int skip)
{
    int i;

    for(i=0;i<=skip;i++){
        startBlock = getGoodBlock(startBlock);
        if(startBlock<0) /* error */
            break;
        startBlock++;
    }

    return startBlock-1;
}


/* TODO: too many hard-coded constants in this function! */
void initDdr(void) 
{
    unsigned int sysclk_period, memclk;
    int refcnt = 0x1e0;
    int trdel, twdel, tras, trp, trcdr, trfc, tcl, tcl_b;
    int bd_id;

    bd_id = IO_READ(PI_GPIO_REG);

    switch( (bd_id&PI_ID_SYS_CLOCK_MASK)>>PI_ID_SYS_CLOCK_SHIFT ){
    case PI_ID_SYS_CLOCK_62_5:
        sysclk_period = 1000000/62.5;
        break;
    case PI_ID_SYS_CLOCK_80:
        sysclk_period = 1000000/83.3;
        break;
    default:
        sysclk_period = 1000000/96.0;
    };

    memclk = 2000000 / sysclk_period;

    trdel = 3;
    twdel = 1;
    tras = 1;
    trp = 1;
    trcdr = 1;
    trfc = 0xE;
    tcl = 3;
    tcl_b = 4;    

    IO_WRITE(RI_NMODE_REG, RI_NMODE_CMD_PRECHARGE_ALL);
    IO_READ(RI_NMODE_REG);

    IO_WRITE(RI_NMODE_REG, RI_NMODE_EX|RI_NMODE_EX_DRIVE_STR_HALF);
    IO_READ(RI_NMODE_REG);

    IO_WRITE(RI_NMODE_REG, RI_NMODE_MX_RESET_DLL);
    IO_READ(RI_NMODE_REG);
    
    IO_WRITE(RI_NMODE_REG, RI_NMODE_CMD_PRECHARGE_ALL);
    IO_READ(RI_NMODE_REG);
    
    IO_WRITE(RI_NMODE_REG, RI_NMODE_CMD_AUTO_REFRESH);
    IO_READ(RI_NMODE_REG);
    IO_WRITE(RI_NMODE_REG, RI_NMODE_CMD_AUTO_REFRESH);
    IO_READ(RI_NMODE_REG);
    
    IO_WRITE(RI_NMODE_REG, RI_NMODE_MX_BURST_ILV|
                           RI_NMODE_MX_BURST_LEN_4|
                           RI_NMODE_MX_CL(tcl));
    IO_READ(RI_NMODE_REG);

    IO_WRITE(RI_DDR_CONFIG_REG, (trdel<<RI_DDR_CONFIG_TRDEL_SHIFT)|
                                (twdel<<RI_DDR_CONFIG_TWDEL_SHIFT)|
                                (tras<<RI_DDR_CONFIG_TRAS_SHIFT)|
                                (trp<<RI_DDR_CONFIG_TRP_SHIFT)|
                                (trcdr<<RI_DDR_CONFIG_TRCD_SHIFT)|
                                (trfc<<RI_DDR_CONFIG_TRFC_SHIFT)|
                                (tcl_b<<RI_DDR_CONFIG_TCL_SHIFT));

    IO_READ(RI_NREFRESH_REG);
    IO_READ(RI_NREFRESH_REG);

    IO_WRITE(RI_STROBE_REV_REG, 1);
    IO_READ(RI_NREFRESH_REG);
    IO_WRITE(RI_AUTO_PRE_CHG_REG, 1);
    IO_READ(RI_NREFRESH_REG);
    
    for (tcl=0; tcl<100; tcl++)  
	    IO_READ(RI_NREFRESH_REG);
    
    IO_WRITE(RI_NREFRESH_REG, RI_NREFRESH_ENABLE | refcnt);
    IO_READ(RI_NREFRESH_REG);
}


/* loadSysappTicket:
 *   read and verify ticket. 
 *
 * startNandBlock:
 *   out - nand block holding first content block.
 *
 * return:
 *   success, or error codes for invalid ticket and problems 
 *   reading from flash.
 */
int loadSysappTicket(u32 *startNandBlock)
{
    int i,j,ret;
    BbContentMetaDataHead *cmd =
        (BbContentMetaDataHead *)CMDBUNDLE_STORAGE_START;
    u32 *p32 = (u32 *)cmd;
    u8 decryptChunk[BB_CMD_ENCRYPTED_CHUNK_BYTES];
    BbCertBase *certs[3];
    SkDataChain dataChain[1];
    u32 ticketStartBlock;
    BbAppLaunchCrls *rlBundle;

    /* skip SK blocks on nand */
    if( (ret = findGoodBlock(*startNandBlock,SK_BLOCKS))<0)
        return ret;
    ticketStartBlock = (u32)ret;

    /* verify chain (sysapp case assumes proper certs in place) */

    /* copy entire block into iram */
    for(i=0;i<PI_FLASH_PAGES_PER_BLOCK;i++){
        /* read page into pi buffer 0. */
        ret = readFlashPage(ticketStartBlock*PI_FLASH_PAGES_PER_BLOCK+i,0);
        if(ret<0)
            return ret;
        if(i==0){
            *startNandBlock = getBlockLink(IO_READ(PI_BUFFER_0_OOB_START+
                                                   BB_FL_BLOCK_LINK_OFF));
        }
        /* copy to iram */
        for(j=0;j<PI_FLASH_PAGE_DATA_SIZE;j+=4){
                *(p32++) = IO_READ(PI_BUFFER_BASE_REG+j);
        }
    }

    /* 
     * crl/cert authentication 
     */
    certs[0] = (BbCertBase *)(CMDBUNDLE_STORAGE_START + 
                           sizeof(BbContentMetaDataHead));
    certs[1] = (BbCertBase *)((u8 *)certs[0] + sizeof(BbRsaCert));
    /* hardcoded two certs here */
    certs[2] = NULL;

    /* verify rl and insure sysapp bundle is OK */
    rlBundle = (BbAppLaunchCrls *)(((u8 *)certs[1]) + sizeof(BbRsaCert));
    BOOT_PATCH_RL(carl,CMDBUNDLE_STORAGE_START);
    BOOT_PATCH_RL(cprl,CMDBUNDLE_STORAGE_START);
    if(sysappBundleRevoked(cmd, certs, rlBundle) < 0)
        return SK_FAIL;

    if(verifyCertChain(certs,CHAIN_TYPE_CONTENT_PUB) < 0)
        return SK_FAIL;

    message("sysapp verify cert chain passed\n");

    /* for cmdh, only one data chunk is needed */
    dataChain[0].data = (u8 *)cmd;    
    dataChain[0].size = BB_CMD_HEAD_SIGNED_BYTES ;
    /* hard-coding cert type here: reset certs */

    if( verifyRsaSigDataChain(dataChain, 1,
                         ((BbRsaCert *)certs[0])->publicKey,
                         ((BbRsaCert *)certs[0])->exponent,
                         BB_SIG_TYPE_RSA2048,
                         (BbGenericSig *)cmd->contentMetaDataSign)
        <0 )
        return SK_FAIL;

    message("sysapp verify cmd sign passed\n");

    /* decrypt encrypted portions of cmd */
    ret = aes_SwDecrypt((u8 *)v2->bootAppKey,
                        (u8 *)cmd->commonCmdIv,
                        (u8 *)&(cmd->key),
                        BB_CMD_ENCRYPTED_CHUNK_BYTES,
                        decryptChunk);
    if(ret<0){
        message("failed internal to decryption\n");
        return SK_FAIL;
    }
    message("sysapp decryption finished\n");
    memcpy((u8 *)&(cmd->key),decryptChunk,BB_CMD_ENCRYPTED_CHUNK_BYTES);

    /* bbid check */
    if(cmd->bbid && (cmd->bbid != v2->bbId)){
        return SK_FAIL;
    }

#ifdef DEBUG
    message("key value = \n");
    output_int32_hex(*((u32 *)(&(cmd->key[0]))));
    message("\n");
    output_int32_hex(*((u32 *)(&(cmd->key[1]))));
    message("\n");
    output_int32_hex(*((u32 *)(&(cmd->key[2]))));
    message("\n");
    output_int32_hex(*((u32 *)(&(cmd->key[3]))));
    message("\n");
#endif
    
    return SK_SUCCESS;
}

int processSysappPage(u32 pageNum, u32 piBuf, u32 useHwChaining,
                      u32 *dramTarget, u32 bytes, SHA1Context *sha, u32 first)
{
    int ret;
    
    if( (ret=readFlashPage(pageNum,piBuf))<0)
        return ret;
    
    /* decrypt, using hardware iv chaining */
    aesStart(piBuf,useHwChaining);
    POLL_AES_BUSY;
    
    if(first){
        u32 *tmp;
        tmp = (u32 *)PHYS_TO_K1(((piBuf ? PI_BUFFER_1_START : 
                               PI_BUFFER_0_START) + N64_ROM_LOADADDR_OFFSET));
        if (!ptrValid((void *)*tmp, 0, 4)) {
            return SK_FAIL;
        }
        *dramTarget = *tmp;
        *dramTarget = KSEG_TO_PHYS((*dramTarget));
    }

    skInvalDCache((void *)PHYS_TO_K0(*dramTarget), 512);
    if ((ret=piBufDma(piBuf,*dramTarget,bytes,SK_DMA_BUF_TO_DRAM))<0){
        message("BUF DMA FAIL\n");
        return ret;
    }
    
    SHA1Input(sha,(u8 *)PHYS_TO_K0(*dramTarget),bytes);

    return SK_SUCCESS;
}

int loadSysapp(u32 *loadAddr)
{
    int ret;
    u32 i, baPages, togo, pageCnt, flashBlock=0;
    BbContentMetaDataHead *cmd=
        (BbContentMetaDataHead *)CMDBUNDLE_STORAGE_START;
    SHA1Context sha;
    BbShaHash appHash;
    u32 pageNum, piBuf, useHwChaining, dramTarget, bytes;

    /* load ticket block */
    if( (ret = loadSysappTicket(&flashBlock))<0)
        return ret;

    baPages = (cmd->size + (PI_FLASH_PAGE_DATA_SIZE))
              >> PI_FLASH_PAGE_ADDR_SHIFT;

#ifdef DEBUG
    message("content size = ");
    output_int32_hex(cmd->size);
    message("\n");

    message("first flash block = ");
    output_int32_hex(flashBlock);
    message("\n");
#endif
  
    /* setup hw aes for decryption */
    aesHwInit(cmd->key,cmd->iv);

    /* initialize SHA */
    SHA1Reset(&sha);

    /* load sysapp binary */
    piBuf=0;
    useHwChaining=0;
    bytes = PI_FLASH_PAGE_DATA_SIZE;

    /* first 4KB hash only */
    for(pageCnt=0; pageCnt<8; pageCnt++){
        /* use same dramTarget each call ok, since real code
         * loaded in place during next loop
         */
        pageNum = flashBlock*PI_FLASH_PAGES_PER_BLOCK+pageCnt;
        if((ret = processSysappPage(pageNum, piBuf, useHwChaining,
                             &dramTarget, bytes, &sha, pageCnt==0)) < 0)
            return ret;
        useHwChaining=1;        

        if(pageCnt == 0){
            /* NOTE: this address is a KSEGX address, so must be
             *       converted to physical to use for DMA purposes.
             *       When used to jump to app code no conversion is
             *       necessary (this is the same as n64 rom and Boot.s)
             */
            *loadAddr = *(u32 *)PHYS_TO_K0((dramTarget+
                                            N64_ROM_LOADADDR_OFFSET));
#ifdef DEBUG
            message("load address = ");
            output_int32_hex((*loadAddr));
            message("\n");
#endif
        }
    }

    for(i=pageCnt, togo=(cmd->size-(4*1024)); i<baPages; 
        i++, dramTarget+=PI_FLASH_PAGE_DATA_SIZE){

        /* input and process page */
        pageNum = flashBlock*PI_FLASH_PAGES_PER_BLOCK+pageCnt;
        if(togo>PI_FLASH_PAGE_DATA_SIZE){
            bytes=PI_FLASH_PAGE_DATA_SIZE;
            togo -= PI_FLASH_PAGE_DATA_SIZE;
        }
        else{
            bytes=togo;
            togo = 0;
        }

        if((ret = processSysappPage(pageNum, piBuf, useHwChaining,
                             &dramTarget, bytes, &sha, 0)) < 0)
            return ret;

        /* next flash block */
        if(pageCnt++ == (PI_FLASH_PAGES_PER_BLOCK-1)){
            flashBlock = getBlockLink(IO_READ(PI_BUFFER_0_OOB_START+
                                              BB_FL_BLOCK_LINK_OFF));
#ifdef DEBUG
            message("new flash block = ");
            output_int32_hex(flashBlock);
            message("\n");
#endif
            pageCnt = 0;
        }
    }

    /* verify hash */
    SHA1Result(&sha,(u8 *)appHash);
#ifdef DEBUG
    message("app hash value = \n");
    output_int32_hex(appHash[0]);
    message("\n");
    output_int32_hex(appHash[1]);
    message("\n");
    output_int32_hex(appHash[2]);
    message("\n");
    output_int32_hex(appHash[3]);
    message("\n");
    output_int32_hex(appHash[4]);
    message("\n");
#endif
    if (memcmp(appHash, cmd->hash, sizeof appHash)) {
	message("hash mismatch\n");
	return SK_FAIL;
    }

    setAccessRights(cmd);

    return ret;
}


/* Errors are handled within this function before returning
 * to asm. Currently, all errors result in jump to exception
 * handler that spins forever. 
 *
 * On successfull loading of sysapp, the load address
 * is returned exactly as it appeared in the eTicket. It must
 * be an appropriate KSEG0 or KSEG1 address in the eTicket!
 */
u32 skEntryBoot(void)
{
    u32 loadAddr;
    int ret;

    /* keep power on */
    IO_WRITE(PI_GPIO_REG, ((PI_GPIO_POWER_BIT|PI_GPIO_ERROR_BIT)<<
             PI_GPIO_ENABLE_SHIFT)|(PI_GPIO_POWER_BIT));
    IO_WRITE(MI_INTR_EMASK_REG, MI_INTR_MASK_CLR_BUT);
    IO_WRITE(MI_SEC_MODE_REG, IO_READ(MI_SEC_MODE_REG) & ~MI_SEC_MODE_BUT_TRAP_EN);
    /* disable timer from limited play */
    IO_WRITE(MI_SEC_TIMER_REG, 0);
    /* just to be on the safe side, disable everything */
#ifdef WHACK_SPDP
    if (IO_READ(SP_PC_REG)) {
	IO_WRITE(SP_STATUS_REG, SP_SET_SSTEP|SP_CLR_HALT);
	IO_WRITE(SP_PC_REG, 0);
    }
    IO_WRITE(SP_STATUS_REG, SP_SET_HALT|SP_CLR_BROKE|SP_CLR_INTR|SP_CLR_SSTEP|SP_CLR_SIG0|SP_CLR_SIG1|SP_CLR_SIG2|SP_CLR_SIG3|SP_CLR_SIG4|SP_CLR_SIG5|SP_CLR_SIG6|SP_CLR_SIG7|SP_CLR_INTR_BREAK);
    /*IO_WRITE(SP_STATUS_REG, SP_SET_HALT);*/
    IO_WRITE(DPC_STATUS_REG, DPC_CLR_XBUS_DMEM_DMA|DPC_CLR_FREEZE|DPC_CLR_FLUSH|DPC_CLR_TMEM_CTR|DPC_CLR_PIPE_CTR|DPC_CLR_CMD_CTR|DPC_CLR_CLOCK_CTR);
#endif
    IO_WRITE(PI_STATUS_REG, PI_STATUS_DMA_BUSY|PI_STATUS_IO_BUSY|PI_CLR_INTR);
    IO_WRITE(PI_FLASH_CTRL_REG, 0);
    IO_WRITE(PI_AES_CTRL_REG, 0);
    IO_WRITE(VI_CURRENT_REG, 0);
    IO_WRITE(SP_STATUS_REG, SP_CLR_INTR|SP_CLR_RSPSIGNAL);
    IO_WRITE(AI_STATUS_REG, 1);
    IO_WRITE(SI_STATUS_REG, 0);
    IO_WRITE(MI_MODE_REG, MI_CLR_DP_INTR);
    IO_WRITE(MI_INTR_MASK_REG, MI_INTR_MASK_CLR_SP|
	                        MI_INTR_MASK_CLR_SI|
	                        MI_INTR_MASK_CLR_AI|
	                        MI_INTR_MASK_CLR_VI|
	                        MI_INTR_MASK_CLR_PI|
	                        MI_INTR_MASK_CLR_DP);
    IO_WRITE(MI_INTR_EMASK_REG, MI_INTR_MASK_CLR_FLASH|
	                        MI_INTR_MASK_CLR_AES|
	                        MI_INTR_MASK_CLR_IDE|
	                        MI_INTR_MASK_CLR_PI_ERR|
	                        MI_INTR_MASK_CLR_USB0|
	                        MI_INTR_MASK_CLR_USB1|
	                        MI_INTR_MASK_CLR_BUT|
	                        MI_INTR_MASK_CLR_MD);

#if defined(SK_LOG_RDB)
    /* init IDE for 96MHz */
    /* bottom of 2 below is slower */
    /* IO_WRITE(PI_IDE_CONFIG_REG, 2 << 0 | 0xa << 5 | 0xc << 10); */
    IO_WRITE(PI_IDE_CONFIG_REG, 2 << 0 | 16 << 5 | 20 << 10);
    IDE_WRITE(IDE_RDB_CTRL_REG, IDE_RDB_CTRL_RESET);
#endif

    v01Load(&v01);
    if ((IO_READ(MI_SEC_MODE_REG) & (MI_SEC_MODE_APP | MI_SEC_MODE_MD_TRAP |
	    MI_SEC_MODE_TIMER | MI_SEC_MODE_BUT_TRAP | MI_SEC_MODE_TRAP |
	    MI_SEC_MODE_FATAL)) ||
	 gSavedCode == BB_LIMIT_CODE_TIME2) {
	/* if we got here through a trap and we were running a
	 * time-limited application, update the remaining time in the
	 * stashed away consumption counter
	 */
	if (gSavedTid != BB_TICKET_ID_INVAL) {
	    u16* cc = getCcSlot(gSavedTid);
	    if (cc) {
		*cc = gSavedCc;
		v01Update(&v01);
	    }
	    gSavedCode = BB_LIMIT_CODE_INVAL;
	    gSavedTid = BB_TICKET_ID_INVAL;
	}
#ifdef DO_RESET
#define SAVED_SM	PI_ATB_BUFFER_LO_REG
	IO_WRITE(SAVED_SM, IO_READ(MI_SEC_MODE_REG));
	IO_WRITE(MI_CTRL_REG, MI_CTRL_SOFT_RESET);
#endif
    } else {
#ifdef DO_RESET
	/* detect that we did a soft reset and recover the saved SEC_MODE reg */
#endif
	/* init dram, if it is the first time through */
	initDdr();
#ifdef DEBUG
	message("ddr init complete...\n");
#endif
    }
#ifdef DEBUG
    if (IO_READ(PI_ERROR_REG) & PI_ERROR_CORRECTABLE_ECC) {
	message("correctable ecc @ virtual ");
	output_int32_hex(IO_READ(PI_ERROR_REG)&PI_ERROR_ADDR_MASK);
	message("\n");
    }
#endif

#ifdef SK_LOCKDOWN
    if (lockSk() != SK_SUCCESS) {
        message("error locking sk\n");
        JUMP_EXCEPTION;
    }
#endif

    if( (ret = loadSysapp(&loadAddr)) != SK_SUCCESS ){

        message("fatal error loading sysapp!\n");

        JUMP_EXCEPTION;
    }

    /* XXX: decide on below! */
    //IO_WRITE(PI_ERROR_REG, PI_ERROR_KERNEL_INTR);
    /* XXX: don't clear the soft/double error info */
    //IO_WRITE(PI_ERROR_REG, 0);

#ifdef DEBUG
    message("error reg: ");
    output_int32_hex(IO_READ(PI_ERROR_REG));
    message("\n");
#endif

    /* now turn off error LED */
    IO_WRITE(PI_GPIO_REG, ((PI_GPIO_POWER_BIT|PI_GPIO_ERROR_BIT)<<
             PI_GPIO_ENABLE_SHIFT)|(PI_GPIO_ERROR_BIT | PI_GPIO_POWER_BIT));

    message("app copy completed...\n");

    gSavedCode = BB_LIMIT_CODE_INVAL;
    return loadAddr;
}

#ifdef SK_LOCKDOWN
static int
computeSkHash(BbShaHash skHash) {
    int page,currentBlock,togo,ret;
    SHA1Context sha;
    int blockCount=0;

    /* assume key and iv are already initialized */

    SHA1Reset(&sha);
    currentBlock = 0;
    togo = LOAD_SK_PAGES;
    do {
        currentBlock = getGoodBlock(currentBlock);
        blockCount++;
        if (currentBlock < 0) return currentBlock;
        for (page = 0; page < PI_FLASH_PAGES_PER_BLOCK; page++) {
            if (page == 0) {
                if (blockCount == 1)
                    aesStart(0, 0);
                else
                    aesStart(0, 1);
            } else {
                ret = readFlashPage(
                    (currentBlock<<PI_FLASH_PAGE_PER_BLOCK_POW2) + page, 0);
                if(ret < 0) return ret;
                aesStart(0, 1);
            }
            POLL_AES_BUSY;
	    SHA1Input(&sha, (u8 *)PHYS_TO_K1(PI_BUFFER_0_START), PI_FLASH_PAGE_DATA_SIZE);
            if(--togo == 0)
                break;
        }
        currentBlock++;
    } while (togo > 0);
    SHA1Result(&sha,(u8*)skHash);
#ifdef DEBUG
    message("sk hash = \n");
    output_int32_hex(skHash[0]);
    output_int32_hex(skHash[1]);
    output_int32_hex(skHash[2]);
    output_int32_hex(skHash[3]);
    output_int32_hex(skHash[4]);
#endif
    return SK_SUCCESS;
}

#define MIPS_JR_T0 0x01000008
static int
lockSk(void) {
    int rv, i;
    u32 sum, *p;
    BbShaHash skHash;
    if (v2->romPatch[0] == MIPS_JR_T0) return 0;
    if ((rv = computeSkHash(skHash)) != SK_SUCCESS) return rv;
    wmemcpy(v2->skHash, skHash, sizeof skHash/4);
    v2->romPatch[0] = MIPS_JR_T0;
    v2->csumAdjust = 0;
    /* recompute checksum */
    p = (u32*)v2;
    for(sum = i = 0; i < sizeof *v2/4; i++)
	sum += *p++;
    v2->csumAdjust = VIRAGE2_CHECKSUM - sum;
    if ((rv = nms_store_and_verify(VIRAGE2_CTRL_REG, v2, sizeof *v2/4)) < 0) {
	message("nms_store failed\n");
	return rv;
    }
    return SK_SUCCESS;
}
#endif