/*
 *               Copyright (C) 2005, 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.
 *
 */

#include <iostypes.h>
#include <iosccert.h>
#include <ioslibc.h>
#include <sc/sc.h>
#include <sc/nvram.h>

static s32 kpChecked = 0;
static s32 kpSize = NV_NC_XPM_SIZE;
static s32 kpInit = 0;

/*
 * Fake XPM, since hardware doesn't work, with an array.
 * device.h is the device NV array, which includes all the ID information and keys
 * from the manufacturing server.
 *
 * We always check the state of the array first. If its not initialized use the device
 * array for reads. For write, unless Fake XPM is set, we always go to the device.
 *
 * device.h includes definition of XPM array, and also "badBits" array for testing the
 * operation of the version writing in case of failures
 */
#include "device.h"


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Function: kpWait(u32 addr)

    Description:
        Wait KP op done. (Port from minimon)
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
static u32
kpWait()
{
    u32 ctrl;

    do {
        ctrl = IO_READ(KP_CTRL_REG);
        if( !(ctrl & KP_CTRL_EXEC)) {
            return(ctrl);
        }
    } while (1);

    return 0;
}

static s32 
kpCheckInit()
{
    /*
     * Read the first 32 bits of the common key to figure out if KP is initialized
     */
    int i;
    u32 w = 0;
    u32 n = 32;
    for (i=0; i<n; i++) {
        IO_WRITE(KP_CTRL_REG, KP_CTRL_EXEC | KP_CTRL_ISSUE_RST | (NV_NC_COMMON_AES_KEY_OFF+i));    
        w |= ((kpWait() & KP_CTRL_R) ? 1 : 0)<<i;
    }
    if (w != 0) {
        return 1;
    } else {
        return 0;
    }

}

static s32
kpReadBit(u32 addr)
{
    if (kpChecked == 0) {
        /*
         * Check for the real kp
         */
        kpChecked = 1;
        kpInit = kpCheckInit();
        if (kpInit == 0) {
            kpSize = sizeof(device) * 8;
        }
    }

    if (addr > kpSize)
        return 0;

    if (kpInit) {
        IO_WRITE(KP_CTRL_REG, KP_CTRL_EXEC | KP_CTRL_ISSUE_RST | addr);    
        return ((kpWait() & KP_CTRL_R) ? 1 : 0);
    } else {
        return (device[addr/8] >> (addr & 7)) & 0x1;
    }
}

/* 
 * New function to deal with forced kpInit = 1 
 */
static void
kpWriteBit(u32 addr)
{
    if (kpChecked == 0) {
        /*
         * Check for the real kp
         */
        kpChecked = 1;
        kpInit = kpCheckInit();
        if (kpInit == 0) {
            kpSize = sizeof(device) * 8;
        }
    }

    if (addr > kpSize)
        return;

    if (kpInit) {
        IO_WRITE(KP_CTRL_REG, KP_CTRL_EXEC | KP_CTRL_ISSUE_RST | KP_CTRL_WR | KP_CTRL_W | addr);
        kpWait();
    } else {
        if (((badBits[addr/8 - NV_NC_WRITEABLE_OFF/8] >> 
              (addr & 7)) & 0x1) == 0) {
            device[addr/8] = device[addr/8] | (1<<(addr & 7));
        }
    }
    return;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Function:  iosNvramForceReal()
  
    Description: 
        Force to use NVRAM real hardware(kp) instead of "fake one"
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void
iosNvramForceReal()
{
    kpInit = 1;
    kpChecked = 1;
    kpSize = NV_NC_XPM_SIZE;
    
    return;
}

static void
kpWriteData(u32 addr, u32 data, u32 n)
{
    int i;

    if (n <= 8*sizeof(u32)) {
        for (i=0; i<n; i++) {
            if ((data>>i)&1) {
                kpWriteBit(addr+i);
            }
        }
    }
}
        
static u32
kpReadData(u32 addr, u32 n)
{
    int i;
    u32 w = 0;
    if (n <= 8*sizeof(u32)) {
        for (i=0; i<n; i++) {
            w |= (kpReadBit(addr + i) << i);
        }
    }
    return w;
}

static void
kpReadArray(u32 addr, u32 size, u8 *data)
{
    int i;
    for (i=0; i<size; i+=8) {
        data[i/8] = kpReadData(addr+i, 8);
    }
}

/*
 * Count the number of ones starting at addr, up to addr+max (not including addr+max).
 * Optionally return the addr of the last bit examined (not the last 1).
 */
static s32
kpCountOnes(u32 addr, u32 max, u32 *lastAddr)
{
    u32 count = 0;
    int i;

    for (i=0; i<max; i++) {
        if (kpReadBit(addr + i) == 0) {
            /* Check next 4 bits */
            if (kpReadData(addr+i, 4) == 0) {
                break;
            }
        } else {
            count++;
        }
    }

    if (lastAddr != 0) {
        *lastAddr = addr + i;
    }

    if (i < max) {
        return count;
    } else {
        return -1;
    }
}

static s32
kpIncVersion(u32 addr)
{
    int retry = 2;
    while (retry-- > 0) {
        kpWriteBit(addr);
        if (kpReadBit(addr++)) {
            return 0;
        }
    }
    return -1;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Function: iosNvramReadData()

    Description:
        Read n bits data from nvram @addr
        If write protect area is written this function is
        disabled
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
u32
iosNvramReadData(u32 addr, u32 n)
{
    u32 wprot;
    u32 w = 0;

    wprot = IO_READ(SYS_CTRL_REG) & SYS_CTRL_KP_WPROT;
    if (!wprot) {
        w = kpReadData(addr, n);
    }
    return w;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Function: iosNvramWriteData()

    Description:
        write n bits data to nvram @addr
        If write protect area is written this function is
        disabled
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
u32
iosNvramWriteData(u32 addr, u32 data, u32 n)
{
    u32 wprot;

    wprot = IO_READ(SYS_CTRL_REG) & SYS_CTRL_KP_WPROT;
    if (!wprot) {
        kpWriteData(addr, data, n);
    }
    return 0;
}

/*
 * These are the specific NC functions for NV data reading, version control. 
 * These should be used
 * by the library layer, so it can remain platform independent
 */
s32 nvGetOsVersion()
{
    return kpCountOnes(NV_NC_OS_VERSION_OFF, NV_NC_OS_VERSION_SIZE-4, 0);
}

s32 nvIncOsVersion()
{
    s32 version;
    u32 addr;

    if ((version = kpCountOnes(NV_NC_OS_VERSION_OFF, NV_NC_OS_VERSION_SIZE-4, &addr)) < 0) {
        return -1;
    }
    if((addr - NV_NC_OS_VERSION_OFF) >= (NV_NC_OS_VERSION_SIZE - 4 - 1)){
        return -1;
    }
    return kpIncVersion(addr);

}

s32 nvGetCaCrlVersion()
{
    return kpCountOnes(NV_NC_CACRL_VERSION_OFF, NV_NC_CACRL_VERSION_SIZE-4, 0);
}

s32 nvIncCaCrlVersion()
{
    s32 version;
    u32 addr;

    if ((version = kpCountOnes(NV_NC_CACRL_VERSION_OFF, NV_NC_CACRL_VERSION_SIZE-4, &addr)) < 0) {
        return -1;
    }
    if((addr - NV_NC_CACRL_VERSION_OFF) >= (NV_NC_CACRL_VERSION_SIZE - 4 - 1)){
        return -1;
    }
    return kpIncVersion(addr);
    
}

s32 nvGetCrlVersion()
{
    return kpCountOnes(NV_NC_CRL_VERSION_OFF, NV_NC_CRL_VERSION_SIZE - 4, 0);
}

s32 nvIncCrlVersion()
{
    s32 version;
    u32 addr;

    if ((version = kpCountOnes(NV_NC_CRL_VERSION_OFF, NV_NC_CRL_VERSION_SIZE-4, &addr)) < 0) {
        return -1;
    }
    if((addr - NV_NC_CRL_VERSION_OFF) >= (NV_NC_CRL_VERSION_SIZE - 4 - 1)){
        return -1;
    }
    return kpIncVersion(addr);
}

s32 nvGetSfsVersion()
{
    return kpCountOnes(NV_NC_SFS_VERSION_OFF, NV_NC_SFS_VERSION_SIZE-4, 0);
}

s32 nvIncSfsVersion()
{
    s32 version;
    u32 addr;

    if ((version = kpCountOnes(NV_NC_SFS_VERSION_OFF, NV_NC_SFS_VERSION_SIZE-4, &addr)) < 0) {
        return -1;
    }
    if((addr - NV_NC_SFS_VERSION_OFF) >= (NV_NC_SFS_VERSION_SIZE - 4 -1)){
        return -1;
    }
    return kpIncVersion(addr);
}

void
nvGetDeviceId(u32 *deviceId)
{
    *deviceId = kpReadData(NV_NC_DEVICE_ID_OFF, NV_NC_DEVICE_ID_SIZE);
}

void
nvGetDeviceKeys(u8 *deviceEcdhKey, u8 *commonAesKey, u8 *sfsHmacKey, u8 *sfsAesKey)
{
    kpReadArray(NV_NC_COMMON_AES_KEY_OFF, NV_NC_COMMON_AES_KEY_SIZE, commonAesKey);
    kpReadArray(NV_NC_DEVICE_ECDH_KEY_OFF, NV_NC_DEVICE_ECDH_KEY_SIZE, deviceEcdhKey);
    kpReadArray(NV_NC_SFS_AES_KEY_OFF, NV_NC_SFS_AES_KEY_SIZE, sfsAesKey);
    kpReadArray(NV_NC_SFS_HMAC_KEY_OFF, NV_NC_SFS_HMAC_KEY_SIZE, sfsHmacKey);
}

void
nvGetDeviceCert(IOSCName mfrName, IOSCName caName, u32 *mfrDate, IOSCName name, u8 *mfrSign)
{
    u32 deviceId;
    u32 mfrId;
    u32 caId;

    mfrId = kpReadData(NV_NC_MFR_ID_OFF, NV_NC_MFR_ID_SIZE);
    snprintf(mfrName, sizeof(IOSCName), "MS%08x", mfrId); 
    caId = kpReadData(NV_NC_CA_ID_OFF, NV_NC_CA_ID_SIZE);
    snprintf(caName, sizeof(IOSCName), "CA%08x", caId);
    *mfrDate = kpReadData(NV_NC_MFR_DATE_OFF, NV_NC_MFR_DATE_SIZE);
    nvGetDeviceId(&deviceId);
    snprintf(name, sizeof(IOSCName), "NC%08x", deviceId);
    kpReadArray(NV_NC_MFR_SIGN_OFF, NV_NC_MFR_SIGN_SIZE, mfrSign);

}
