/*
 *               Copyright (C) 2006, BroadOn Communications Corp.
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished  proprietary information of BroadOn Communications Corp.,
 *  and are protected by Federal copyright law. They may not be disclosed
 *  to third  parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 * $Id: eeprom.c,v 1.4 2006/11/03 21:53:06 cnguyen Exp $
 */


#include <types.h>
#include <ioslibc.h>
#include <iop.h>
#include <sys.h>
#include <mmu.h>
#include <diag/proto.h>
#include <diag/aes_sw.h>
#include <diag/sha1.h>
#include <diag/sha_sw.h>
#include <addr_map.h>
#include <bsl.h>
#include <csl.h>
#include <iosctypes.h>
#include <iosccert.h>
#include <nvram.h>

extern void readEfuse();


#ifdef EE_DEBUG_LOG
#define DbgPrint(s, args...) printf(s, ## args)
#else
#define DbgPrint(s, ...)    (void)(0) 
#endif


#define DATA_START          IOP_GDDR3_START
#define DATA_SIZE           (64 * 1024)

#define SHA_BLOCK_SZ_SHIFT  6
#define HASH_RESULT_SIZE    20

/* Device control */
#define WAIT(dev)           while (IO_READ(dev##_CTRL_REG) & dev##_CTRL_EXEC)
#define FLUSH(dev)          ahbMemFlush(IOS_WB_##dev)
#define INVAL(dev)          ahbMemRBInvalidate(IOS_RB_##dev)


#define STACK_SIZE          (8 * 1024)
const u8    _initStack[STACK_SIZE];
const u32   _initStackSize = sizeof(_initStack);
const u32   _initPriority = 10;

void
busDelay (unsigned int cycles)
{
    int i;

    for (i = 0; i < cycles; i++)
        ;

    return;
}


#define PROD_DEF_ID (0x4a39) 
#define DEV_DEF_ID  (0x1f5)

#define ALIGN_SIZE 64

//static IOSCRsa2048EccCert msCert __attribute__((aligned(ALIGN_SIZE)));
static IOSCEccSignedCert returnedCert __attribute__((aligned(ALIGN_SIZE)));
static IOSCEccSignedCert appCert __attribute__((aligned(ALIGN_SIZE)));

#ifdef RVL_DEVEL_PKI
#define msCert ms_dpki
#else
#define msCert ms_ppki
#endif

extern u8 msCert[];

s32
main(void)
{
    BSL_KeyStoreInit();
    IOSCError err;
    u32 id;
    IOSCPublicKeyHandle msPublickeyh;
    IOSCPublicKeyHandle devPublickeyh;
    IOSCPublicKeyHandle appPublickeyh;
    IOSCSecretKeyHandle inputPrivkeyh;
    CSLOSEccPrivateKey inputPrivate;
    IOSCCertName appName;
    CSLOSAesKey commonKey;
    CSLOSSha1Hash boot1Hash;
    CSLOSSha1Hash zeros;

    outputLed(0x10);

    err = BSL_GetData(IOSC_DEV_ID_HANDLE, &id);
    if (err != IOSC_ERROR_OK) {
        DbgPrint("Failed to read device ID, err=%d\n", err);
        outputLed(0x20);
        goto main_out;
    }

    if (id == PROD_DEF_ID || id == DEV_DEF_ID) {
        DbgPrint("Default ID found 0x%x\n", id);
        outputLed(0x21);
        goto main_out;
    }
    DbgPrint("Dev ID = 0x%x\n", id);
    
    /* Check common key directly from eeprom */
    memset(zeros, 0, sizeof(CSLOSSha1Hash));
    readEfuse(NV_RVL_COMMON_AES_KEY_OFF / sizeof (u32), (u8 *) &commonKey[0],
              NV_RVL_COMMON_AES_KEY_SIZE);
    if(memcmp(zeros, commonKey, sizeof(CSLOSAesKey)) == 0){
        DbgPrint("Common Key is Zero!\n");
        outputLed(0x22);
        goto main_out;
    }
    else{
        DbgPrint("Common Key is not Zero\n");
    }
    
    /* Check hash directly from eeprom */
    readEfuse(NV_RVL_BOOT1_HASH_OFF / sizeof (u32), (u8 *) &boot1Hash[0],
              NV_RVL_BOOT1_HASH_SIZE);
    if(memcmp(zeros, boot1Hash, sizeof(CSLOSSha1Hash)) == 0){
        DbgPrint("Hash is Zero!\n");
        outputLed(0x23);
        goto main_out;
    }
    else{
        DbgPrint("Hash is not Zero\n");
    }
    
    /*
     * Check EEPROM contents: device cert signature and private key
     */
     
    err = BSL_CreateObject(&msPublickeyh, IOSC_PUBLICKEY_TYPE, 
                           IOSC_ECC233_SUBTYPE);
    if (err != IOSC_ERROR_OK) {
        DbgPrint("Failed to create object for MS public key=%d\n", err);
        outputLed(0x24);
        goto main_out;
    }

    /* Import MS public key */
    err = BSL_ImportPublicKey((((IOSCRsa2048EccCert *)msCert)->pubKey), 0, 
                              msPublickeyh);
    if (err != IOSC_ERROR_OK) {
        DbgPrint("Failed to import MS public key=%d\n", err);
        outputLed(0x25);
        goto main_out;
    }

    /* Get device certificate */
    err = BSL_GetDeviceCertificate((IOSCEccSignedCert *)&returnedCert);
    if (err != IOSC_ERROR_OK) {
        DbgPrint("Failed to get Device Cert=%d\n", err);
        outputLed(0x26);
        goto main_out;
    }

    /* Import it to check if it was a good cert */
    err = BSL_CreateObject(&devPublickeyh, IOSC_PUBLICKEY_TYPE, 
                           IOSC_ECC233_SUBTYPE);
    if (err != IOSC_ERROR_OK) {
        DbgPrint("Failed to create object for Dev public key=%d\n", err);
        outputLed(0x27);
        goto main_out;
    }
    err = BSL_ImportCertificate((u8 *)returnedCert, msPublickeyh, 
                                devPublickeyh);
    if(err == IOS_ERROR_OK) {
        DbgPrint("Device Certificate import Pass\n");
    } else {
        DbgPrint("Device Certificate import Fail, err = %d\n", err);
        outputLed(0x28);
        goto main_out;
    }

    /* Use the device private key to sign an application cert */
    memset(inputPrivate, 0x5, sizeof(CSLOSEccPrivateKey));
    err = BSL_CreateObject(&inputPrivkeyh, IOSC_SECRETKEY_TYPE, 
                           IOSC_ECC233_SUBTYPE);
    if (err != IOSC_ERROR_OK) {
        DbgPrint("Failed to create object for input private key=%d\n", err);
        outputLed(0x29);
        goto main_out;
    }

    err = BSL_ImportSecretKey(inputPrivkeyh, 0, 0, IOSC_NOSIGN_NOENC, 0, 0, 
                              inputPrivate);
    if (err != IOSC_ERROR_OK) {
        DbgPrint("Failed to import input private key=%d\n", err);
        outputLed(0x2A);
        goto main_out;
    }

    memset(appName, 0x0, sizeof(IOSCCertName));
    memcpy(appName, "APP00000001", sizeof("APP00000001"));
    err = BSL_GenerateCertificate(inputPrivkeyh, appName, &appCert);
    if (err != IOSC_ERROR_OK) {
        DbgPrint("Failed to generate application cert err = %d\n", err);
        outputLed(0x2B);
        goto main_out;
    }
    DbgPrint("Generated Cert for app key\n");
    DbgPrint("Name = %s\n", ((IOSCEccEccCert *)appCert)->head.name.deviceId);
   
    err = BSL_CreateObject(&appPublickeyh, IOSC_PUBLICKEY_TYPE, 
                           IOSC_ECC233_SUBTYPE);
    if (err != IOSC_ERROR_OK) {
        DbgPrint("Failed to create public key=%d\n", err);
        outputLed(0x2C);
        goto main_out;
    }

    DbgPrint("Issuer = %s\n", ((IOSCEccEccCert *)appCert)->sig.issuer);
    err = BSL_ImportCertificate(appCert, devPublickeyh, appPublickeyh);
    if (err == IOSC_ERROR_OK) {
        DbgPrint("App Cert Import Pass\n");
    } else {
        DbgPrint("Failed to import App cert err = %d\n", err);
        outputLed(0x2D);
        goto main_out;
    }

    /* Delete all the objects */
    BSL_DeleteObject(devPublickeyh);
    BSL_DeleteObject(msPublickeyh);
    BSL_DeleteObject(inputPrivkeyh);
    BSL_DeleteObject(appPublickeyh);

    DbgPrint("Test Successful!\n");
    outputLed(0x11);

main_out:
    return (err);

}


