/*
 *               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 <ios.h>
#include <iostypes.h>
#include <ioslibc.h>
#include <iop.h>
#include <diag/diag.h>
#include <diag/aes_hal.h>
#include <diag/aes_sw.h>
#include <ahb_fdl_defs.h>
#include <mem_reg.h>
#include <sys.h>



#define DEBUG_PRINT  1

#ifdef DEBUG_PRINT
#define debugPrint(s, args...)     { printf(s, ## args); }
#else
#define debugPrint(s, ...)  (void)(0)
#endif

#define TO_SRAM_BASE(addr)	\
		((((u32)addr & 0xFFFF0000) == SRN_SRAM_BASE) ? \
		 (u8 *)((u32)addr | sramFlipMask) : (u8 *)addr)
            

#if defined(USE_SRAM)
#define SRAM_SOURCE_ADDRESS	(SRN_SRAM_BASE+0x8000) /* 32KB boundary */
#else
#define SRAM_SOURCE_ADDRESS	(SRN_SRAM_BASE+0x0400)
#endif

#define NAPA_SOURCE_ADDRESS	(SPLASH_BASE+0x00000)
#define DDR_SOURCE_ADDRESS	(DDR_BASE+0x100000)   /* 1MB boundary */

/* Scratch pad area for software AES encrytion and decryption results */
#define DDR_SW_ENCDATA_ADDRESS  (DDR_BASE+0x200000)   /* 2MB boundary */
#define DDR_SW_DECDATA_ADDRESS  (DDR_BASE+0x240000)   /* 2MB + 256KB */

#define AES_BLOCK_SZ_SHIFT	4

/* LED trace codes */
#define REASON_AES_PASS		0x27
#define REASON_AES_FAIL		0x28

#define SRAM_LOG_ADDR           (SRN_SRAM_BASE+0xFF80)


#ifdef STDALONE
#define STACK_SIZE              2048
const u8   _initStack[STACK_SIZE];
const u32  _initStackSize = sizeof(_initStack);
#endif


/* Test using different combinations of memory for src and dst addresses 
 *   0) SRAM,
 *   1) Napa,
 *   2) DDR,
 *
 *   0 -> 0, 0 -> 1, 0 -> 2
 *   1 -> 1, 1 -> 0, 1 -> 2
 *   2 -> 2, 2 -> 0, 2 -> 1
*/
#define SRAM_ID         0
#define NAPA_ID         1
#define DDR_ID          2

#define NUM_OF_TESTS	3
static u32 testSeq[NUM_OF_TESTS][2] = { /* {src, dst} */
            {DDR_ID , DDR_ID}, 
            {DDR_ID , SRAM_ID}, 
            {DDR_ID , NAPA_ID}
};


/* Each block contains 16 bytes - Test 64, 512, 1024, and 4096 blocks */
static u32 blockSize[3] = {512, 1024, 4096};

/* This mask contains 0xFFFF0000 when the IOUEN bit is set in ACRSRNPROT reg */
static u32 sramFlipMask = 0;

static u32 swKey[4], swIv[4];


/* Assuming we're using ES 2.11 chips only */
void 
enableSramAccess()
{

#if 0
    u32 reg;

    /* Enable access for SRON */
    reg = *(u32 *)((u32)(ACR_REGS_BASE+ACRSRNPROT_OFFSET+AHB_TRUSTED_OFFSET)); 
    reg = reg | (ACRSRNPROT_AESEN_MASK | ACRSRNPROT_SHAEN_MASK |
          ACRSRNPROT_FLAEN_MASK);
    *(u32 *)((u32)(ACR_REGS_BASE+ACRSRNPROT_OFFSET+AHB_TRUSTED_OFFSET)) = reg;
#endif

}


void 
fillBufFromRandom(u8 *data, u32 size)
{

    u32 count;

    debugPrint("InitMem: data=0x%08x size=%d\n", data, size);

    for (count = 0; count < size; count++) {
        data[count] = (count * 1928) - 879;
    }

    /* Flush memory */
    ahbMemFlush(IOS_WB_IOP);

    /* Invalidate AHM AES RDB */
    ahbMemRBInvalidate(IOS_RB_AES);
}


void 
setupAes(u32 *swKey, u32 *swIv)
{

    /* Program key */
    *(u32 *)(AES_KEY_REG) = swKey[0];
    *(u32 *)(AES_KEY_REG) = swKey[1];
    *(u32 *)(AES_KEY_REG) = swKey[2];
    *(u32 *)(AES_KEY_REG) = swKey[3];

    /* Program IV */
    *(u32 *)(AES_IVPTR_REG) = swIv[0];
    *(u32 *)(AES_IVPTR_REG) = swIv[1];
    *(u32 *)(AES_IVPTR_REG) = swIv[2];
    *(u32 *)(AES_IVPTR_REG) = swIv[3];
}


int 
doEncrypt(u8 *input, u8 *output, u32 size, u32 *swKey, u32 *swIv)
{

    int rc;
    u8 *src, *dst;


    rc = AES_ERROR_OK;

    setupAes(swKey, swIv);
    AES_Encrypt((u32)input, (u32)output, size >> AES_BLOCK_SZ_SHIFT, 0, 0);

    debugPrint("SW Encrypt: src=0x%08x dst=0x%08x bits=%d\n", 
        input, DDR_SW_ENCDATA_ADDRESS, size * 8);

    aes_sw_encrypt((u8 *)swKey, (u8 *)swIv, (u8 *)input,
        size * 8, (u8 *)DDR_SW_ENCDATA_ADDRESS);

    src = TO_SRAM_BASE(output);
    dst = (u8 *)DDR_SW_ENCDATA_ADDRESS;

    debugPrint("memcmp: src=0x%08x dst=0x%08x size=%d\n", src, dst, size);

    if (memcmp((u8 *)src, (u8 *)dst, size) != 0) {
        rc = AES_ERROR_UNKNOWN;
    }

    return rc;

}


int 
doDecrypt(u8 *input, u8 *output, u32 size, u32 *swKey, u32 *swIv)
{

    int rc;
    u8 *src, *dst;


    rc = AES_ERROR_OK;

    setupAes(swKey, swIv);
    AES_Decrypt((u32)input, (u32)output, size >> AES_BLOCK_SZ_SHIFT, 0, 0);

    debugPrint("SW Decrypt: src=0x%08x dst=0x%08x bits=%d\n", 
        DDR_SW_ENCDATA_ADDRESS, DDR_SW_DECDATA_ADDRESS, size * 8);

    aes_sw_decrypt((u8 *)swKey, (u8 *)swIv, (u8 *)DDR_SW_ENCDATA_ADDRESS,
        size * 8, (u8 *)DDR_SW_DECDATA_ADDRESS);

    src = TO_SRAM_BASE(output);
    dst = (u8 *)DDR_SW_DECDATA_ADDRESS;

    debugPrint("memcmp: src=0x%08x dst=0x%08x size=%d\n", src, dst, size);

    if (memcmp((u8 *)src, (u8 *)dst, size) != 0) {
        rc = AES_ERROR_UNKNOWN;
    }

    return rc;

}


int 
encryptDecryptTest(u8 *input, u8 *output, u32 size, u32 *swKey, u32 *swIv)
{
    int rc = AES_ERROR_OK;
    u8 *src, *dst, *dst2;
    u8 *output2;


    /* We need to convert the SRAM address to 0xFFFF000 range since we
     * flip the IOUEN bit in the ACRSRNPROT register
     */
    src = TO_SRAM_BASE(input);
    dst = TO_SRAM_BASE(output);
    output2 = (u8 *)((u32)output + 256 + size);
    dst2 = TO_SRAM_BASE(output2);

     /* Fill source buffer with pseudo-random data */
    fillBufFromRandom(src, size);

    debugPrint("AES encrypt: src=0x%08x dst=0x%08x size=%d\n",
        input, output, size);

    rc = doEncrypt(input, output, size, (u32 *)swKey, (u32 *)swIv);
    if (rc != AES_ERROR_OK) {
        goto encryptDecryptTest_out;
    }

    debugPrint("AES decrypt: src=0x%08x dst=0x%08x size=%d\n",
        dst, dst2, size);

    rc = doDecrypt(output, output2, size, (u32 *)swKey, (u32 *)swIv);
    if (rc != AES_ERROR_OK) {
        goto encryptDecryptTest_out;
    }

#if 0
    debugPrint("HW memcmp: src=0x%08x dst=0x%08x size=%d\n", src, dst2, size);

    if (memcmp((u8 *)src, (u8 *)dst2, size) != 0) {
        rc = AES_ERROR_UNKNOWN;
    }
#endif

encryptDecryptTest_out:

    return(rc);

}  /* encryptDecryptTest */



#ifdef STDALONE
int main(int argc, char *argv[])
#else
int doAesTest()
#endif
{
    int i, j, rc = AES_ERROR_OK;
    u32 size, srcAddr, dstAddr;
    u32 srcIndx, dstIndx, dstBaseAddr;
    u32 t1, t2, baseAddr[3];


    debugPrint("\nStarting AES Block tests...\n");
    t1 = *(u32 *)(SYS_TIMER_REG);

    /* Init defaults */
    srcIndx = SRAM_ID;
    baseAddr[SRAM_ID] = SRAM_SOURCE_ADDRESS;
    baseAddr[NAPA_ID] = NAPA_SOURCE_ADDRESS;
    baseAddr[DDR_ID] = DDR_SOURCE_ADDRESS;

    /* Need to enabble the SRAM split fix bit in ES 2.11 */
    u32 val = *(u32 *)(PHYS_TO_PROTECTED(ACR_REGS_BASE + ACRSPARE1_OFFSET));
    val |= ACRSPARE1_SRAM_SPLIT_FIX_ENABLE_MASK;
    *(u32 *)(PHYS_TO_PROTECTED(ACR_REGS_BASE + ACRSPARE1_OFFSET)) = val;
 
    /* Allow AES, SHA, and Flash to access SRAM */
    enableSramAccess();
  
    /* Init Keys and Ivs */
    swKey[0] = 0x2b7e1516;
    swKey[1] = 0x28aed2a6;
    swKey[2] = 0xabf71588;
    swKey[3] = 0x09cf4f3c;
    memset(swIv,  0, sizeof(swIv));

    /* Determine if the SRAM IOUEN bit is set */
    swKey[0] = 0x2b7e1516;
    val = *(u32 *)(PHYS_TO_PROTECTED(ACR_REGS_BASE + ACRSRNPROT_OFFSET));
    sramFlipMask = 0;
    if (val & ACRSRNPROT_IOUEN_MASK)
        sramFlipMask = 0xFFFF0000;

    /* Loop through the predefined test sequence */
    for (j = 0; j < (u32)(sizeof(testSeq)/sizeof(testSeq[0])); j++) {
        /* Test size from 1-9 blocks first */
        srcIndx = testSeq[j][0];
        dstIndx = testSeq[j][1];

        srcAddr = baseAddr[srcIndx];
        dstBaseAddr = baseAddr[dstIndx];

        debugPrint("***** AES: %d: Idx=(src=%d dst=%d), srcAddr=0x%08x, "
               "dstBase=0x%08x\n", j, srcIndx, dstIndx, srcAddr, dstBaseAddr);

        /* Loop through the (predefined) different block sizes */
        for (i = 0; i < (u32)(sizeof(blockSize)/sizeof(blockSize[0])); i++) {
            size = blockSize[i] * 16;

            if ((srcIndx != SRAM_ID) && (dstIndx == SRAM_ID))
                dstAddr = dstBaseAddr;
            else
                dstAddr = dstBaseAddr + size;

            /* Skip testing SRAM if numBlocks is greater than 1024 */
            if (((srcIndx == SRAM_ID) || (dstIndx == SRAM_ID)) && 
                (size > (1024*16)))
                continue;

            debugPrint("AES: src=0x%08x dst=0x%08x size=%d\n", 
                      srcAddr, dstAddr, size);

            rc = encryptDecryptTest((u8 *)srcAddr, (u8 *)dstAddr, size, 
                     (u32 *)swKey, (u32 *)swIv);
    
            if (rc != AES_ERROR_OK) {
                debugPrint("**** [%2d] Test -> FAIL (size=%d)\n", 
                    i, size);
                outputLed(REASON_AES_FAIL);
                *(u32 *)(SRAM_LOG_ADDR|sramFlipMask) = 0xDEADBEEF;
                *(u32 *)((SRAM_LOG_ADDR|sramFlipMask)+4) = REASON_AES_FAIL;
                *(u32 *)((SRAM_LOG_ADDR|sramFlipMask)+8) = i;
                *(u32 *)((SRAM_LOG_ADDR|sramFlipMask)+12)= size;
                *(u32 *)((SRAM_LOG_ADDR|sramFlipMask)+14)= 0xDEADBEEF;
                while (1) {};
            }
            else {
                debugPrint("[%2d] Test -> PASS (size=%d)\n",i,size);
            }
        }  /* for */

    }  /* for */

    t2 = *(u32 *)(SYS_TIMER_REG);

    outputLed(REASON_AES_PASS);
    *(u32 *)(SRAM_LOG_ADDR|sramFlipMask) = 0xDEADBEEF;
    *(u32 *)((SRAM_LOG_ADDR|sramFlipMask)+4) = REASON_AES_PASS;
    *(u32 *)((SRAM_LOG_ADDR|sramFlipMask)+8) = t2-t1;
    *(u32 *)((SRAM_LOG_ADDR|sramFlipMask)+12) = 0xDEADBEEF;

    debugPrint("\nTotal ticks=%d for %d tests (start=%d end=%d)\n\n", 
        t2-t1, i*j, t1, t2);

    return rc;

}

