/*
 *               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.
 *
 * $Id: flash.c,v 1.22 2008/05/17 03:29:44 cnguyen Exp $
 */

#include <iostypes.h>
#include <ios.h>
#include <ioslibc.h>
#include <apputils.h>
#include <elf.h>
#include <iostypes.h>
#include <iop.h>

#include "flash.h"
#include "fl_ops.h"
#include <fs.h>

// #define UTIL_DEBUG          1

#define FL_DEBUG_LEVEL      0x1f

#define BYTES_PER_PAGE      2048
#define BYTES_PER_SPARE     64
#define DEFAULT_PAGE_COUNT  1
#define PAGES_PER_BLOCK     64
#define BOOT1_START_PAGE    0
#define BOOT2_START_PAGE    64

#define MAX_NUM_BLOCKS      4096

/* 
 * Semi-hosting read size 
 */
#define SEMIHOST_READ_SIZE  (16 * 1024)    /* XXX */

/* 
 * 16KB buffer.
 */
static u8       buf[ISFS_BLOCK_SIZE + 16];

u8              page_buf[BYTES_PER_PAGE];
u8              spare_buf[BYTES_PER_SPARE];
u8              page2_buf[BYTES_PER_PAGE];
u8              spare2_buf[BYTES_PER_SPARE];


/* Array of 4096 bits to represent 4096 blocks 
 * If the specific bit is set, then that block has been erased by the erase
 * command.
 */
static u32      erasedBlks[129];
static u32      rdErrEnabled = 1;    /* Flag to enable ECC error when read */

int cmdInitRun = 0;
int verbose = 0;

static void setupSron (void);


/*
 * Map error code to string for display
 */
static char *
ioserr (int err) {
    switch (err) {
        case IOS_ERROR_ACCESS:
            return "no access";
        case IOS_ERROR_INVALID:
            return "invalid parameters";
        case IOS_ERROR_NOTREADY:
            return "device not ready";
        case IOS_ERROR_ECC:
            return "single-bit error";
        case IOS_ERROR_ECC_CRIT:
            return "multi-bit error";
        case IOS_ERROR_BADBLOCK:
            return "bad block detected";
    }
    return "unknown";
}

s32
isfscmdInit(void)
{
    s32         rc = IOS_ERROR_OK;

    setupSron();

    rc = flOpen();
    if (rc != IOS_ERROR_OK) {
        printf ("%s: flOpen failed, rc=%d\n", __FUNCTION__, rc);
    }

    return (rc);
}

/*
 * cap
 *
 * Read the flash capabilities and print them.
 */
int
cap(char *args, char *d)
{
    s32             rc = 0;
    FLDevCap        cap;
    FLIdentifier    id;

    printf ("%s: %s\n", __FUNCTION__, args);

    if (cmdInitRun == 0) {
        rc = isfscmdInit();
        if (rc != IOS_ERROR_OK) {
            printf ("%s: isfscmdInit failed\n", __FUNCTION__);
            goto cap_out;
        }
        cmdInitRun=1;
    }

    rc = flGetId(&id);
    if (rc != IOS_ERROR_OK) {
        printf("%s: Failed to get flash id, rc=%d\n", 
               __FUNCTION__, rc);
        goto cap_out;
    }
    printf("Device: MID=0x%x DID=0x%x\n", id.makerID, id.deviceID);

    rc = flGetCap(&cap);
    if (rc != IOS_ERROR_OK) {
        printf("%s: Failed to get flash cap, rc=%d\n", 
               __FUNCTION__, rc);
        goto cap_out;
    }

    printf("Total flash size %d\n", (1 << cap.totalSzShift));
    printf("Erasable block size %d\n", (1 << cap.erasableBlockSzShift));
    printf("Page size %d\n", (1 << cap.pageSzShift));
    printf("Spare size %d\n", (1 << cap.pageSpareSzShift));
    printf("User spare size %d\n", (1 << cap.userSpareSzShift));
    printf("Planes %d\n", cap.numPlanes);
    printf("Copy %d\n", cap.supportCopy);
    printf("Status byte offset %d\n", cap.statusByteOffset);

 cap_out:

    return (rc);
}

int
silentCap(char *args, char *d)
{
    s32         rc = 0;
    FLDevCap    cap;

    rc = isfscmdInit();
    if (rc != IOS_ERROR_OK) {
        goto scap_out;
    }
    rc = flGetCap(&cap);
    if (rc != IOS_ERROR_OK) {
        goto scap_out;
    }

scap_out:
    return (rc);
}

/*
 * erase
 *
 * Erase a selected area of flash, in blocks.  Takes two arguments,
 * start and end block.
 */
int
erase(char *args, char *d)
{
    s32         rc = 0;
    FLDevCap    cap;
    char        *ptr;
    u32         start, end, numLogiBlks, blkNum, useLogiBlk;
    u32         logiBlkNum, phyBlkNum, wordIndex, bitIndex;

    if (getNextToken(&ptr, &args) == 0) {
        printf ("Usage: erase start_block [end_block] [use_logical_block]\n");
        rc = -1;
        goto erase_out;
    }
    start = asciiToInt(ptr);

    if (getNextToken(&ptr, &args) == 0) {
        end = start;
    }
    else
        end = asciiToInt(ptr);

    useLogiBlk = 0;
    if (getNextToken(&ptr, &args) != 0) {
        useLogiBlk = asciiToInt(ptr);
        if (useLogiBlk != 1)
            useLogiBlk = 0;
    }

    if (verbose)
        printf("%s: erasing %s block %d to %d\n", 
           __FUNCTION__, useLogiBlk ? "logical" : "physical", start, end);

    rc = flGetCap(&cap);
    if (rc != IOS_ERROR_OK) {
        printf("%s: Failed to get flash cap, rc=%d\n", 
               __FUNCTION__, rc);
        goto erase_out;
    }
    numLogiBlks = 1 << (cap.erasableBlockSzShift - FL_LOGI_BLOCK_SIZE_SHIFT);

    for (blkNum = start; blkNum <= end; blkNum++) {
        if (useLogiBlk) {
            logiBlkNum = blkNum & ~0x7;
        }
        else {
            logiBlkNum = blkNum * numLogiBlks;
        }
        rc = flErase(logiBlkNum);
        if (rc != IOS_ERROR_OK) {
            printf("%s: Failed to erase flash block %d\n", 
                   __FUNCTION__, blkNum);
            goto erase_out;
        }
        if (verbose) {
            printf("%s: erased block %d\n", 
                __FUNCTION__, useLogiBlk ? (blkNum & ~0x7) : blkNum);
        }

        /* Record which physical block has been erased */
        phyBlkNum = logiBlkNum >> (FL_LOGI_BLOCK_SIZE_SHIFT - cap.pageSzShift);
        wordIndex = phyBlkNum >> 5;
        bitIndex = phyBlkNum - (wordIndex << 5);
#ifdef UTIL_DEBUG
        printf("%s: logiBlkNum=%d phyBlkNum=%d wordIndex=%d bitIndex=%d\n",
           __FUNCTION__, logiBlkNum, phyBlkNum, wordIndex, bitIndex);
#endif
        if (wordIndex > 127) {
            printf("%s: Error - array index (%d) is out of range!\n",
                __FUNCTION__, wordIndex);
            goto erase_out;
        }
        erasedBlks[wordIndex] = erasedBlks[wordIndex] | (1 << bitIndex);
#ifdef UTIL_DEBUG
        printf("%s: erasedBlks[%d]=0x%x\n", 
           __FUNCTION__, wordIndex, erasedBlks[wordIndex]);
#endif

    }

erase_out:

    return (rc);
}

void
mem_dump(u8* buf, int len)
{
    int i;

    printf ("%08x:\n", (u32)buf);
    for (i = 0; i < len; i++) {
        printf("%02x ", buf[i]);
        if (((i+1) % 16) == 0) {
            printf ("\n");
        }
    }
    printf ("\n");
}

int
__writeboot1(char *fname)
{
    s32         rc = 0;
    FILE        *fp = NULL;
    u32         addr = (u32)buf, size, bytes, i;
    u32         eBlkSz;
    FLDevCap    cap;

    if (addr & 0xf) {
        addr = (addr + 16) & ~0xf;
    }

    /* Get flash attributes */
    rc = flGetCap(&cap);
    if (rc != IOS_ERROR_OK) {
        printf("Failed to get flash cap, rc=%d\n", rc);
        goto __writeboot1_out;
    }
    eBlkSz = (1 << cap.erasableBlockSzShift);

    /* Open source file */
    fp = fopen(fname, "rb");
    if (fp == NULL) {
        printf("Failed to open file %s\n", fname);
        rc = -1;
        goto __writeboot1_out;
    }

    size = flen(fp);
    if (size > eBlkSz) {
        printf("File size can not exceed %d\n", eBlkSz);
        rc = -2;
        goto __writeboot1_out;
    }

    printf("Loading %#x bytes from '%s' @ %#08x\n", size, fname, addr);

    i = 0;
    while (size) {
        bytes = (size > SEMIHOST_READ_SIZE) ? SEMIHOST_READ_SIZE : size;

        /* Read the data from the source file */
        fread((void *) addr+i,  bytes, 1, fp);
        size -= bytes;
        i += bytes;

        if ((size == 0) /* || (i == FL_LOGI_BLOCK_SIZE) */ ) {
            /* Boot1 can occupy at most one logical block */
            rc = flErase(0);
            if (rc != IOS_ERROR_OK) {
                printf("Failed to erase block 0\n");
                goto __writeboot1_out;
            }

            // blockIndex, numBlocks, iv, customData, customDataSize, buf, spare
            rc = flWrite(0, 1, NULL, NULL, 0, (u8 *) addr, (u8 *) addr);
            if (rc != IOS_ERROR_OK) {
                printf("Failed to write boot1, rc=%d\n", rc);
                goto __writeboot1_out;
            }

            i = 0;
        }
    }

__writeboot1_out:

    if (fp) {
        fclose(fp);
    }

    return rc;
}

/*
 * wb1
 *
 * Write the boot1 image to the sys area of flash.  The sys area is
 * not part of the flash file system.  Boot1 occupies part of block
 * zero of the flash, which is guaranteed to be a good block, so there
 * is no bad block handling.
 */
int
wb1(char *args, char *d)
{
    s32         rc = 0;
    char        *boot1;

    if (getNextToken(&boot1, &args) == 0) {
        printf ("Usage: wb1 boot1_file\n");
        rc = -1;
        return rc;
    }

    rc = __writeboot1(boot1);

    return (rc);
}

int
__writeboot2(char *fname)
{
    s32         rc = 0;
    FILE        *fp = NULL;
    u32         addr = (u32) buf, size, bytes, i, j, totalBytes;
    u32         blkNum, eBlkSz, numLogiBlks, remainBlks;
    u8          *ptr;
    FLDevCap    cap;

    printf ("%s: %s\n", __FUNCTION__, fname);

    /* Get flash attributes */
    rc = flGetCap(&cap);
    if (rc != IOS_ERROR_OK) {
        printf("Failed to get flash cap, rc=%d\n", rc);
        goto __writeboot2_out;
    }
    eBlkSz = (1 << cap.erasableBlockSzShift);
    numLogiBlks = eBlkSz >> FL_LOGI_BLOCK_SIZE_SHIFT;

    /* Open source file */
    fp = fopen(fname, "rb");
    if (fp == NULL) {
        printf("Failed to open file %s\n", fname);
        rc = -1;
        goto __writeboot2_out;
    }

    /* Set the boot2 header */
    size = flen(fp);
    ptr = (u8 *) &size;
    memcpy ((u8 *) addr, ptr, 4);
    printf("Loading %#x bytes from '%s' @ %#08x\n", size, fname, addr);

    /* Start from flash block #1 */
    blkNum = numLogiBlks;

    /* Skip the boot2 header */
    totalBytes = 64;
    i = 64;

    while (size) {
        bytes = (size > SEMIHOST_READ_SIZE) ? SEMIHOST_READ_SIZE : size;

        /* Take the header into account when reading the first block */
        if ((totalBytes < FL_LOGI_BLOCK_SIZE) &&
                ((i + bytes) >= FL_LOGI_BLOCK_SIZE)) {
            bytes = SEMIHOST_READ_SIZE - 4;
        }

        fread((void *) addr+i,  bytes, 1, fp);
        size -= bytes;
        totalBytes += bytes;
        i += bytes;

        if ((size == 0) || (i == FL_LOGI_BLOCK_SIZE)) {
            if ((blkNum & (numLogiBlks - 1)) == 0) {
                while ((rc = flStatus(blkNum)) != IOS_ERROR_OK) {
                    printf("Detected bad block %d, rc=%d\n", blkNum, rc);
                    blkNum += numLogiBlks;
                }
            }

            if ((blkNum & (numLogiBlks - 1)) == 0) {
                rc = flErase(blkNum);
                if (rc != IOS_ERROR_OK) {
                    printf("Failed to erase block %d\n", blkNum);
                    goto __writeboot2_out;
                }   
            }

            // blockIndex, numBlocks, iv, customData, customDataSize, buf, spare
            rc = flWrite(blkNum, 1, NULL, NULL, 0, (u8 *) addr, (u8 *) addr);
            if (rc != IOS_ERROR_OK) {
                printf("Failed to write boot2, rc=%d\n", rc);
                goto __writeboot2_out;
            }

            i = 0;
            blkNum++;
        }
    }

    /* Pad to the size of a full flash block */
    remainBlks = numLogiBlks - (blkNum & (numLogiBlks - 1));
    if (remainBlks == numLogiBlks) {
        remainBlks = 0;
    }

    if (remainBlks != 0) {
        memset((u8 *) addr, 0, FL_LOGI_BLOCK_SIZE);

        for (j = blkNum; j < (blkNum + remainBlks); j++) {
            // blockIndex, numBlocks, iv, customData, customDataSize, buf, spare
            rc = flWrite(j, 1, NULL, NULL, 0, (u8 *) addr, (u8 *) addr);
            if (rc != IOS_ERROR_OK) {
                printf("Failed to write boot2, rc=%d\n", rc);
                goto __writeboot2_out;
            }
        }
    }

__writeboot2_out:

    if (fp) {
        fclose(fp);
    }

    return (rc);
}

/*
 * wb2
 *
 * Write the boot2 image to the sys area of flash.  The sys area is
 * not part of the flash file system.  Boot2 occupies blocks 2 onwards
 * in the flash.  These are not guaranteed good blocks so we have to
 * handle bad blocks, if they exist.  A block is regarded as bad if
 * there are any bad pages in it.  There are 64 pages per block.
 */
int
wb2(char *args, char *d)
{
    s32         rc = 0;
    char        *boot2;


    if (getNextToken(&boot2, &args) == 0) {
        printf ("Usage: wb2 boot2_file\n");
        rc = -1;
        return rc;
    }

    rc = __writeboot2(boot2);

    return rc;
}

/*
 * wb
 *
 * Write both boot1 and boot2 to flash.   See the comments above for
 * the differences in the handling of these two images.
 */
int
wb(char *args, char *d)
{
    s32         rc = 0;
    char        *boot1, *boot2;


    if ((getNextToken(&boot1, &args) == 0) ||
            (getNextToken(&boot2, &args) == 0)) {
        printf("Usage: wb boot1 boot2\n");
        printf ("%s: bad arguments %s\n",
                __FUNCTION__, args);
        rc = -1;
        goto writeboot_out;
    }

    if ((rc = __writeboot1(boot1)) != IOS_ERROR_OK) {
        printf("%s: Failed to write boot1 %s, rc=%d\n", 
               __FUNCTION__, boot1, rc);
        goto writeboot_out;
    }

    if ((rc = __writeboot2(boot2)) != IOS_ERROR_OK) {
        printf("%s: Failed to write boot2 %s, rc=%d\n", 
               __FUNCTION__, boot2, rc);
        goto writeboot_out;
    }

writeboot_out:

    return (rc);
}

/*
 * Read a flash page and display the result to screen or dump to file
 */
int
fr(char *args, char *d)
{
    s32           rc = 0, dump = 0, 
    count1 = BYTES_PER_SPARE, count2 = BYTES_PER_SPARE;
    char          *ptr, *filename = NULL;
    u32           pageNum, phyBlkNum, wordIndex, bitIndex, blkErased;
    FLDevCap      cap;
    IOSError      status;
    FILE          *fp = 0;

    if (getNextToken(&ptr, &args) == 0) {
        printf ("Usage: fr page_num [data_bytes to dump] [filename]\n");
        rc = -1;
        goto fr_out;
    }
    pageNum = asciiToInt(ptr);

    if (getNextToken(&ptr, &args) == 0) {
        printf ("fr: no count, will dump %d of data and %d of spare\n", 
	        count1, count2);
    } else {
        count1 = asciiToInt(ptr);
        if (count1 > BYTES_PER_PAGE) count1 = BYTES_PER_PAGE;
    }

    if (pageNum < 0) {
        printf ("fr: bad page number %d\n", pageNum);
        rc = -1;
        goto fr_out;
    }

    if (getNextToken(&filename, &args) == 0) {
#ifdef APP_VERBOSE
        printf ("fr: no filename.   Will dump to screen\n");
#endif
        dump = 1;
        filename = NULL;
        if (verbose)
            printf ("fr: will dump %d bytes of data and %d of spare\n",
	            count1, count2);
    }
    else {
        dump = 0;
        printf ("fr: writing %d bytes of data and %d of spare to file '%s'\n", 
            BYTES_PER_PAGE, BYTES_PER_SPARE, filename);
    }

    rc = flGetCap(&cap);
    if (rc != IOS_ERROR_OK) {
        printf("%s: Failed to get flash cap, rc=%d\n", __FUNCTION__, rc);
        goto fr_out;
    }

    memset (&page_buf[0], 'e', BYTES_PER_PAGE);
    memset (&spare_buf[0], 'e', BYTES_PER_SPARE);

    status = flReadPage(pageNum, &page_buf[0], &spare_buf[0], 1);
    if (status != IOS_ERROR_OK) {

        /* Find the physical block that this page belongs to */
        phyBlkNum = pageNum >> (cap.erasableBlockSzShift - cap.pageSzShift);
        wordIndex = phyBlkNum >> 5;
        bitIndex = phyBlkNum - (wordIndex << 5);
        blkErased = (erasedBlks[wordIndex] >> bitIndex) & 0x1;
#ifdef UTIL_DEBUG
        printf("%s: phyBlkNum=%d wordIndex=%d bitIndex=%d\n",
            __FUNCTION__, phyBlkNum, wordIndex, bitIndex);
        printf("%s: erasedBlks[%d]=0x%x, blkErased=%d\n", 
            __FUNCTION__, wordIndex, erasedBlks[wordIndex], blkErased);
#endif

        if (rdErrEnabled || (status != IOS_ERROR_ECC_CRIT) ||
            ((status == IOS_ERROR_ECC_CRIT) && !blkErased)) {
            printf ("fr: read page %d, err=%d (%s)\n", pageNum, status, 
                ioserr(status));
            rc = -1;
        }
    }

    if ((dump != 0) && (verbose)) {
        printf ("fr: #%d page data\n", pageNum);
        mem_dump (&page_buf[0], count1);
        printf ("fr: spare data\n");
        mem_dump (&spare_buf[0], count2);
    }
    else if (filename != NULL) {
        if ((fp = fopen(filename, "wb")) == 0) {
            printf("fr: unable to open file '%s'\n", filename);
            rc = -1;
            goto fr_out;
        }
        fwrite(&page_buf[0], sizeof(page_buf), 1, fp);
        fwrite(&spare_buf[0], sizeof(spare_buf), 1, fp);
        fclose(fp);
    }

fr_out:

    return (rc);

}

/*
 * Write a flash page with the specified data pattern
 */
int 
fw (char *args, char *d)
{
    s32         rc = 0;
    u32         page_no, i, start_data = 0;
    char        *ptr;
    u32         ecc = 0;

    if (getNextToken(&ptr, &args) == 0) {
        printf ("Usage: fw page_num [ecc_flag] [data_pattern]\n");
        rc = -1;
        goto fw_out;
    }
    page_no = asciiToInt(ptr);

    if (getNextToken(&ptr, &args) == 0) {
        printf ("fw: no ecc or start pattern, will use ecc=off and start pattern=%02x\n", start_data & 0xff);
    } else {
        ecc = asciiToInt(ptr);
        if (ecc > 0) ecc = 1;
        printf ("fw: will use ecc=%d\n", ecc);
    }

    if (getNextToken(&ptr, &args) == 0) {
        printf ("fw: no start pattern, will use %02x\n", start_data & 0xff);
    } else {
        start_data = asciiToInt(ptr);
        printf ("fw: will start data pattern at %02x\n", start_data & 0xff);
    }

    for (i = 0; i < BYTES_PER_PAGE; i++) {
        page_buf[i] = (start_data + i) % 0xff;
    }
    for (i = 0; i < BYTES_PER_SPARE; i++) {
        spare_buf[i] = (BYTES_PER_SPARE - (start_data + i)) & 0xff;
    }

    rc = flWritePage(page_no, &page_buf[0], &spare_buf[0], 0, ecc);
    if (rc != IOS_ERROR_OK) {
        printf ("fw: write page %d, err=%d (%s)\n", page_no, rc, ioserr(rc));
        goto fw_out;
    }
    printf ("fw: page %d written\n", page_no);

fw_out:

    return rc;
}

/*
 * Verify a flash page by reading it with ECC enabled
 */
int
fv(char *args, char *d)
{
    s32         rc = 0, 
                count1 = BYTES_PER_SPARE, count2 = BYTES_PER_SPARE;
    char        *ptr;
    u32         block_no, page_no1, page_no2, i;
    IOSError    status;

    if (getNextToken(&ptr, &args) == 0) {
        printf ("Usage: fv block_no page_no1 [page_no2]\n");
        rc = -1;
        goto fv_out;
    }
    block_no = asciiToInt(ptr);

    if (getNextToken(&ptr, &args) == 0) {
        printf ("Usage: fv block_no page_no1 [page_no2]\n");
        rc = -1;
        goto fv_out;
    }
    page_no1 = asciiToInt(ptr) + (block_no * PAGES_PER_BLOCK);

    if (getNextToken(&ptr, &args) == 0) {
        printf ("fv: no second page, will verify one page\n", 
	        count1, count2);
        page_no2 = page_no1;
    } else {
        page_no2 = asciiToInt(ptr) + (block_no * PAGES_PER_BLOCK);
        printf ("fv: will verify from page %d to page %d\n",
	        page_no1, page_no2);
    }

    if (page_no2 < page_no1) {
        printf ("%s: mis-ordered pages %d %d\n",
	        __FUNCTION__, page_no1, page_no2);
    }

    for (i = page_no1; i < page_no2; i++) {
        memset (&page_buf[0], 'e', BYTES_PER_PAGE);
        memset (&spare_buf[0], 'e', BYTES_PER_SPARE);

        status = flReadPage(i, &page_buf[0], &spare_buf[0], 1);
        if (status != IOS_ERROR_OK) {
            printf ("fv: read page %d, err=%d (%s)\n", 
	            i, status, ioserr(status));
            rc = -1;
        } else {
            printf ("%s: page %2d is good\n",
	            __FUNCTION__, i);
        }
    }

fv_out:

  return (rc);
}

/*
 * Read one or more flash blocks and save the result to file 
 */
int
br(char *args, char *d)
{
    s32           rc = 0;
    char          *ptr, *filename = NULL;
    u32           startBlock, numBlocks, numLogiBlks, block;
    u32           startPage, numPagesInBlock, pageSz, page;
    FLDevCap      cap;
    FILE          *fp = 0;

    if (getNextToken(&ptr, &args) == 0) {
        printf ("Usage: br start_block num_blocks filename\n");
        rc = -1;
        goto br_out;
    }
    startBlock = asciiToInt(ptr);

    if ((startBlock < 0) || (startBlock >= MAX_NUM_BLOCKS)) {
        printf ("%s: bad block number %d\n", __FUNCTION__, startBlock);
        rc = -1;
        goto br_out;
    }

    if (getNextToken(&ptr, &args) == 0) {
        printf ("Usage: br start_block num_blocks filename\n");
        rc = -1;
        goto br_out;
    }
    numBlocks = asciiToInt(ptr);

    if ((numBlocks < 0) || (numBlocks > MAX_NUM_BLOCKS) || 
        ((startBlock+numBlocks) > MAX_NUM_BLOCKS)) {
        printf ("%s: bad number of blocks %d\n", __FUNCTION__, numBlocks);
        rc = -1;
        goto br_out;
    }

    if (getNextToken(&filename, &args) == 0) {
        printf ("Usage: br start_block num_blocks filename\n");
        rc = -1;
        goto br_out;
    }
    printf ("%s: writing to file '%s'\n", __FUNCTION__, filename);
    if ((fp = fopen(filename, "wb")) == 0) {
        printf("%s: unable to open file '%s'\n", __FUNCTION__, filename);
        rc = -1;
        goto br_out;
    }

    rc = flGetCap(&cap);
    if (rc != IOS_ERROR_OK) {
        printf("%s: Failed to get flash cap, rc=%d\n", __FUNCTION__, rc);
        goto br_out;
    }

    /* 
     * For 512MB NAND with pageSz=2KB, blockSz=128KB
     *   - There are 64 pages per block
     *   - There are 8 pages per logical FS block (16KB / 2KB = 8) 
     */
    numLogiBlks = 1 << (cap.erasableBlockSzShift - FL_LOGI_BLOCK_SIZE_SHIFT);
    numPagesInBlock = 1 << (cap.erasableBlockSzShift - cap.pageSzShift);
    pageSz = 1 << cap.pageSzShift;
    startPage = startBlock * numPagesInBlock;

    if (verbose) {
        printf("%s: startBlock=%d startPage=%d numBlocks=%d numPagesInBlock=%d\n",
            __FUNCTION__, startBlock, startPage, numBlocks, numPagesInBlock);
    }

    for (block = 0; block < numBlocks; block++) {
        startPage = (startBlock+block) * numPagesInBlock;

        if (verbose) {
            printf("%s: reading block %d (startPage=%d)\n", __FUNCTION__,
                (startBlock+block), startPage);
        }

        for (page = 0; page < numPagesInBlock; page++) {

            /* Init page buffer */
            memset (&page_buf[0], 'e', BYTES_PER_PAGE);
            memset (&spare_buf[0], 'e', BYTES_PER_SPARE);

            /*
            if (verbose)
                printf("%s: reading page %d\n", __FUNCTION__, startPage+page);
            */
            printf(".");

            /* Read each page */ 
            rc = flReadPage(startPage+page, &page_buf[0], &spare_buf[0], 1);
            if (rc != IOS_ERROR_OK) {
                printf ("%s: read page %d, err=%d (%s)\n", __FUNCTION__,
                        startPage+page, rc, ioserr(rc));
                /* If ECC error, we'll continue */
                if ((rc != IOS_ERROR_ECC) && (rc != IOS_ERROR_ECC_CRIT)) {
                    goto br_out;
                }
            }

            fwrite(&page_buf[0], sizeof(page_buf), 1, fp);
            fwrite(&spare_buf[0], sizeof(spare_buf), 1, fp);

        }  /* for reading one block */

        printf("\n");

     }  /* for reading numBlocks */

br_out:
    if (fp)
        fclose(fp);

    return (rc);

}  /* br */

/* 
 * Write/read/verify a flash block (one page at a time) using the specified
 * data pattern.
 */
int 
bwrv (char *args, char *d)
{
    s32         rc = 0;
    u32         pageNum, totalPages, i, j, startData = 0;
    u32         loopCnt = 1;
    u32         blkNum, numLogiBlks;
    char        *ptr;
    FLDevCap    cap;

    if (getNextToken(&ptr, &args) == 0) {
        printf ("Usage: bwrv block_num [loop_count] [data_pattern]\n");
        rc = -1;
        goto bwrv_out;
    }
    blkNum = asciiToInt(ptr);
    if ((blkNum < (8*8)) || (blkNum > (4095*8))) {
        printf ("bwrv: invalid block_num %d\n", blkNum);
        rc = -1;
        goto bwrv_out;
    }

    loopCnt = 1;
    if (getNextToken(&ptr, &args) == 0) {
        printf ("bwrv: no loop_count, will use %d\n", loopCnt);
    } else {
        loopCnt = asciiToInt(ptr);
        if (loopCnt >= 10000) loopCnt = 10000; 
        printf ("bwrv: will loop %d iterations\n", loopCnt);
    }

    startData = 0;
    if (getNextToken(&ptr, &args) == 0) {
        printf ("bwrv: no start pattern, will use 0x%02x\n", startData & 0xff);
    } else {
        startData = asciiToInt(ptr);
        printf ("bwrv: will start data pattern at %02x\n", startData & 0xff);
    }

    /* Get flash attributes */
    rc = flGetCap(&cap);
    if (rc != IOS_ERROR_OK) {
        printf("bwrv: failed to get flash cap, rc=%d\n", rc);
        goto bwrv_out; 
    }

    /* There are 8 pages in a logical FS block (16KB / 2KB = 8) */
    blkNum = blkNum & ~0x7;    /* Align block number */
    numLogiBlks = 1 << (cap.erasableBlockSzShift - FL_LOGI_BLOCK_SIZE_SHIFT);
    pageNum = blkNum << 3;
   
    totalPages = 1 << (cap.erasableBlockSzShift - cap.pageSzShift);

    if (verbose)
        printf("bwrv: blkNum=%d totalPages=%d pageNum=%d numLogiBlks=%d\n", 
            blkNum, totalPages, pageNum, numLogiBlks);

    for (i = 0; i < BYTES_PER_PAGE; i++) {
        page_buf[i] = (startData + i) % 0xff;
    }
    memset (&spare_buf[0], 0, BYTES_PER_SPARE);

    for (i = 0; i < loopCnt; i++) {
        if (verbose)
            printf("bwrv: Iteration %d\n", i);

        /* Erase the block */
        rc = flErase(blkNum);
        if (rc != IOS_ERROR_OK) {
            printf("bwrv: erase block %d, count=%d err=%d (%s)\n", 
	          blkNum, i, rc, ioserr(rc));
            goto bwrv_out;
        }

        for (j = 0; j < totalPages; j++) {
            /* Write the designated page with ECC enabled */
            rc = flWritePage(pageNum+j, &page_buf[0], &spare_buf[0], 0, 1);
            if (rc != IOS_ERROR_OK) {
                printf ("bwrv: write page %d, count=%d err=%d (%s)\n",
	                pageNum+j, i, rc, ioserr(rc));
                goto bwrv_out;
            }

            /* Init page buffer */
            memset (&page2_buf[0], 'e', BYTES_PER_PAGE);
            memset (&spare2_buf[0], 'e', BYTES_PER_SPARE);

            /* Read back the page */
            rc = flReadPage(pageNum+j, &page2_buf[0], &spare2_buf[0], 1);
            if (rc != IOS_ERROR_OK) {
                printf ("bwrv: read page %d, count=%d err=%d (%s)\n",
	                pageNum+j, i, rc, ioserr(rc));
                goto bwrv_out;
            }

            if (memcmp(page_buf, page2_buf, BYTES_PER_PAGE) != 0) {
                printf ("bwrv: failed to compare page %d\n", pageNum+j);
                goto bwrv_out;
            }
            if (verbose) 
                printf ("bwrv: page %d verified\n", pageNum+j);
        }  /* for writing block */

    }  /* for */

 bwrv_out:

    return rc;
}

/* 
 * This test will perform the followings:
 *    - Erase a specified blockA (128KB)
 *    - Write all the pages in blockA with pattern data
 *    - Read back all pages and verify that they are OK
 *    - Erase the second blockB (128KB)
 *    - Read back all pages in blockA and verify data integrity
 */
int 
testBlk1 (char *args, char *d)
{
    s32         rc = 0;
    u32         pageNum, totalPages, i, j, startData = 0;
    u32         loopCnt = 1, delayCount = 0;
    u32         numLogiBlks, blkA, blkB;
    char        *ptr;
    FLDevCap    cap;


    blkA = 3694; // 3688;
    blkB = 3720;

    if (getNextToken(&ptr, &args) == 0) {
        printf ("Usage: testBlk1 blockA blockB [start_pattern] [delay_count]\n");
        rc = -1;
        goto testBlk1_out;
    }
    blkA = asciiToInt(ptr);
    if ((blkA < 64) || (blkA > (4095*8)))  {
        printf ("testBlk1: invalid blockA %d\n", blkB);
        rc = 1;
        goto testBlk1_out;
    }

    if (getNextToken(&ptr, &args) == 0) {
        printf ("Usage: testBlk1 blockA blockB [start_pattern] [delay_count]\n");
        rc = -1;
        goto testBlk1_out;
    } else {
        blkB = asciiToInt(ptr);
        if ((blkB < 64) || (blkB > (4095*8)))  {
            printf ("testBlk1: invalid blockB %d\n", blkB);
            rc = 1;
            goto testBlk1_out;
        }
    }


    loopCnt = 1;

    startData = 0;
    if (getNextToken(&ptr, &args) == 0) {
        printf ("testBlk1: no start pattern, will use 0x%02x\n", startData & 0xff);
    } else {
        startData = asciiToInt(ptr);
        printf ("testBlk1: will start data pattern at %02x\n", startData & 0xff);
    }

    delayCount = 0;
    if (getNextToken(&ptr, &args) == 0) {
        printf ("testBlk1: no delay_count, will use %d\n", delayCount);
    } else {
        delayCount = asciiToInt(ptr);
        if (delayCount >= 9999) delayCount = 9999; 
        delayCount *= 100000;
        printf ("testBlk1: will use delay of %d\n", delayCount);
    }

    /* Align block numbers */
    blkA = blkA & ~0x7; 
    blkB = blkB & ~0x7;

    /* Starting page number (block << 3) */
    pageNum = blkA << 3;

    /* Get flash attributes */
    rc = flGetCap(&cap);
    if (rc != IOS_ERROR_OK) {
        printf("testBlk1: failed to get flash cap, rc=%d\n", rc);
        goto testBlk1_out; 
    }

    /* There are 8 pages in a logical FS block (16KB / 2KB = 8) */
    numLogiBlks = 1 << (cap.erasableBlockSzShift - FL_LOGI_BLOCK_SIZE_SHIFT);

    totalPages = 1 << (cap.erasableBlockSzShift - cap.pageSzShift);

    for (i = 0; i < BYTES_PER_PAGE; i++) {
        page_buf[i] = (startData + i) % 0xff;
    }
    memset (&spare_buf[0], 0, BYTES_PER_SPARE);

    for (i = 0; i < loopCnt; i++) {
        if (verbose)
            printf("testBlk1: Iteration %d\n", i);

        /* Erase block A */
        rc = flErase(blkA);
        if (rc != IOS_ERROR_OK) {
            printf("testBlk1: erase blockA %d, err=%d (%s)\n",
	            blkA, rc, ioserr(rc));
            goto testBlk1_out;
        }
        if (verbose)
            printf("testBlk1: erased block A %d\n", blkA);

        /* Write the entire block 128KB */
        for (j = 0; j < totalPages; j++) {
            /* Write the all the pages with ECC enabled */
            rc = flWritePage(pageNum+j, &page_buf[0], &spare_buf[0], 0, 1);
            if (rc != IOS_ERROR_OK) {
                printf("testBlk1: write page %d, err=%d (%s)\n",
	                pageNum+j, rc, ioserr(rc));
                goto testBlk1_out;
            }

            /* Init page buffer */
            memset (&page2_buf[0], 'e', BYTES_PER_PAGE);
            memset (&spare2_buf[0], 'e', BYTES_PER_SPARE);

            /* Read back the page */
            rc = flReadPage(pageNum+j, &page2_buf[0], &spare2_buf[0], 1);
            if (rc != IOS_ERROR_OK) {
                printf("testBlk1: read page %d, err=%d (%s)\n",
	                pageNum+j, rc, ioserr(rc));
                goto testBlk1_out;
            }

            if (memcmp(page_buf, page2_buf, BYTES_PER_PAGE) != 0) {
                printf ("testBlk1: failed to compare page %d\n", pageNum+j);
                goto testBlk1_out;
            }
            if (verbose) 
                printf ("testBlk1: page %d verified\n", pageNum+j);

        }  /* for writing one logical block */

        /* Delay */
        for (j = 0; j < delayCount; j++) { ; }

        /* Erase block B */
        rc = flErase(blkB & ~0x7);
        if (rc != IOS_ERROR_OK) {
            printf("testBlk1: erase blockB %d, err=%d (%s)\n", 
	            blkB & ~0x7, rc, ioserr(rc));
            goto testBlk1_out;
        }
        if (verbose) 
            printf ("testBlk1: erased blockB %d\n", blkB & ~0x7);

        /* Read back the last block in block A and verify */
        for (j = 0; j < totalPages; j++) {
            /* Read back the page */
            rc = flReadPage(pageNum+j, &page2_buf[0], &spare2_buf[0], 1);
            if (rc != IOS_ERROR_OK) {
                printf ("testBlk1: read page %d, err=%d (%s)\n",
	              pageNum+j, rc, ioserr(rc));
                goto testBlk1_out;
            }

            if (memcmp(page_buf, page2_buf, BYTES_PER_PAGE) != 0) {
                printf ("testBlk1: failed to compare page %d\n", pageNum+j);
                rc = -1;
                goto testBlk1_out;
            }
            if (verbose) 
                printf ("testBlk1: page %d verified\n", pageNum+j);

        }  /* for reading one block */

    }  /* for */

 testBlk1_out:

    return rc;
}

/*
 * wrb1
 *
 * Open a given filename and write the minimum of the file
 * length or the page count to the first block (page 0) of
 * flash.
 *
 * Examples:
 *
 * wrb1 file 1   - writes just one page, from 'file'
 * wrb1 file 64  - writes 64 pages, or the length of 'file' 
 *                 if 'file' less than 64 pages long.
 *
 * Todo: enhance the code to fill out the block in the case
 * where 'file' is less than 64 pages long.
 */
int 
wrb1 (char *args, char *d)
{
    s32              rc = 0;
    FLDevCap         cap;
    char             *fname, *ptr;
    FILE             *fp = NULL;
    u32              page_no, eBlkSz, size, page_count = DEFAULT_PAGE_COUNT;

    if (getNextToken(&fname, &args) == 0) {
        printf ("Usage: wrb1 filename [pages]\n");
        goto wrb1_out;
    }

    if (getNextToken(&ptr, &args) == 0) {
        printf("%s: no page count specified, will use %d\n", 
	         __FUNCTION__, page_count);
    } else {
        page_count = asciiToInt(ptr);
        printf ("%s: will load %d pages\n", 
	        __FUNCTION__, page_count);
    }

    rc = flGetCap(&cap);
    if (rc != IOS_ERROR_OK) {
        printf ("%s: failed o get flash cap, rc=%d\n",
	        __FUNCTION__, rc);
        goto wrb1_out;
    }
    eBlkSz = (1 << cap.erasableBlockSzShift);

    fp = fopen(fname, "rb");
    if (fp == NULL) {
        printf ("%s: cannot open file %s\n",
	        __FUNCTION__, fname);
        rc = -1;
        goto wrb1_out;
    }

    size = flen(fp);
    if (size > (eBlkSz + (PAGES_PER_BLOCK * BYTES_PER_SPARE))) {
        printf ("%s: file size %d too large, will write only %d\n",
	        __FUNCTION__, size, eBlkSz);
        size = eBlkSz;
    }

    page_no = BOOT1_START_PAGE;
    do {
        memset (&page_buf[0], 0, BYTES_PER_PAGE);
        fread (&page_buf[0], BYTES_PER_PAGE, 1, fp);
        size -= BYTES_PER_PAGE;

        memset (&spare_buf[0], 0, BYTES_PER_SPARE);
        fread (&spare_buf[0], BYTES_PER_SPARE, 1, fp);
        size -= BYTES_PER_SPARE;

#ifdef APP_VERBOSE
        if (verbose)
            mem_dump (&spare_buf[0], BYTES_PER_SPARE);
#endif

        rc = flWritePage(page_no, &page_buf[0], &spare_buf[0], 0, 0);
        if (rc != IOS_ERROR_OK) {
            printf ("%s: write page %d, err=%d (%s)\n",
	            __FUNCTION__, page_no, rc, ioserr(rc));
            goto wrb1_out;
        }

        page_count--;

        printf ("%s: wrote page %d\n", __FUNCTION__, page_no);
        page_no++;

    } while ((size > 0) && (page_count > 0));

 wrb1_out:

    if (fp) fclose(fp);

  return rc;
}

/*
 * wrb2
 *
 * Open a given filename and write the minimum of the file
 * length or the page count to the second block (page 64) 
 * of flash.
 *
 * Examples:
 *
 * wrb2 file 1   - writes just one page, from 'file'
 * wrb2 file 64  - writes 64 pages, or the length of 'file' 
 *                 if 'file' less than 64 pages long.
 *
 * Todo: enhance the code to fill out the block in the case
 * where 'file' is less than 64 pages long.
 */
int 
wrb2 (char *args, char *d)
{
    s32              rc = 0;
    FLDevCap         cap;
    char             *fname, *ptr;
    FILE             *fp = NULL;
    u32              page_no, eBlkSz, size, page_count = DEFAULT_PAGE_COUNT;

    if (getNextToken(&fname, &args) == 0) {
        printf ("Usage: wrb2 filename [pages]\n");
        goto wrb2_out;
    }

    if (getNextToken(&ptr, &args) == 0) {
        printf("%s: no page count specified, will use %d\n", 
	         __FUNCTION__, page_count);
    } else {
        page_count = asciiToInt(ptr);
        printf ("%s: will load %d pages\n", 
	        __FUNCTION__, page_count);
    }

    rc = flGetCap(&cap);
    if (rc != IOS_ERROR_OK) {
        printf ("%s: failed o get flash cap, rc=%d\n",
	        __FUNCTION__, rc);
        goto wrb2_out;
    }
    eBlkSz = (1 << cap.erasableBlockSzShift);

    fp = fopen(fname, "rb");
    if (fp == NULL) {
        printf ("%s: cannot open file %s\n",
	        __FUNCTION__, fname);
        rc = -1;
        goto wrb2_out;
    }

    size = flen(fp);
    if (size > (eBlkSz + (PAGES_PER_BLOCK * BYTES_PER_SPARE))) {
        printf ("%s: file size %d too large, will write only %d\n",
	        __FUNCTION__, size, eBlkSz);
        size = eBlkSz;
    }

    page_no = BOOT2_START_PAGE;
    do {
        memset (&page_buf[0], 0, BYTES_PER_PAGE);
        fread (&page_buf[0], BYTES_PER_PAGE, 1, fp);
        size -= BYTES_PER_PAGE;

        memset (&spare_buf[0], 0, BYTES_PER_SPARE);
        fread (&spare_buf[0], BYTES_PER_SPARE, 1, fp);
        size -= BYTES_PER_SPARE;

#ifdef APP_VERBOSE
        if (verbose)
            mem_dump (&spare_buf[0], BYTES_PER_SPARE);
#endif

        rc = flWritePage(page_no, &page_buf[0], &spare_buf[0], 0, 0);
        if (rc != IOS_ERROR_OK) {
            printf ("%s: write page %d, err=%d (%s)\n",
	            __FUNCTION__, page_no, rc, ioserr(rc));
            goto wrb2_out;
        }

        page_count--;
        printf ("%s: wrote page %d\n", __FUNCTION__, page_no);
        page_no++;

    } while ((size > 0) && (page_count > 0));

 wrb2_out:

    if (fp) fclose(fp);

  return rc;
}

int
wrbN (char *args, char *d)
{
    s32         rc = 0;
    FLDevCap    cap;
    char        *fname, *ptr;
    FILE        *fp = NULL;
    u32         page_no, size, page_count = DEFAULT_PAGE_COUNT;
    u32         blockSz, blockCount, numPagesInBlock, pageSz, spareSz;
    u32         block = 1;

    if (getNextToken(&fname, &args) == 0) {
        printf ("Usage: wrbN filename <number of pages to write> <block [counting from 0]>\n");
        goto wrbN_out;
    }

    if (getNextToken(&ptr, &args) == 0) {
        printf("%s: no page count specified, will use %d\n",
            __FUNCTION__, page_count);
    } else {
        page_count = asciiToInt(ptr);
    }
  
    if (getNextToken(&ptr, &args) == 0) {
        printf("%s: Need to specify block number\n", __FUNCTION__);
        goto wrbN_out;
    } else {
        block = asciiToInt(ptr);
    }

    rc = flGetCap(&cap);
    if (rc != IOS_ERROR_OK) {
        printf ("%s: failed o get flash cap, rc=%d\n",
	        __FUNCTION__, rc);
        goto wrbN_out;
    }

    fp = fopen(fname, "rb");
    if (fp == NULL) {
        printf ("%s: cannot open file %s\n", __FUNCTION__, fname);
        rc = -1;
        goto wrbN_out;
    }

    size = flen(fp);
    /* 
     * For 512MB NAND with pageSz=2KB, blockSz=128KB
     *   - There are 64 pages per block
     *   - There are 8 pages per logical FS block (16KB / 2KB = 8) 
     */
    blockSz = (1 << cap.erasableBlockSzShift);
    numPagesInBlock = 1 << (cap.erasableBlockSzShift - cap.pageSzShift);
    pageSz = 1 << cap.pageSzShift;
    spareSz = 1 << cap.pageSpareSzShift;
    blockCount = page_count / numPagesInBlock;

    if (blockCount) {
      if (size < (blockCount * (blockSz+ (numPagesInBlock * spareSz)))) {
          printf ("%s: file size %d too small\n", __FUNCTION__, size);
          rc = -1;
          goto wrbN_out;
      }
    }

    if (verbose) {
        printf("%s: will load %d pages, from block %d "
               "(blocks=%d blockSz=%d pageSz=%d spareSz=%d)\n",
            __FUNCTION__, page_count, block, blockCount, blockSz, 
            pageSz, spareSz);
    }

    page_no = numPagesInBlock*(block);
    do {
        memset (&page_buf[0], 0, pageSz);
        fread (&page_buf[0], pageSz, 1, fp);
        size -= pageSz;

        memset (&spare_buf[0], 0, spareSz);
        fread (&spare_buf[0], spareSz, 1, fp);
        size -= spareSz;

#ifdef APP_VERBOSE
        if (verbose)
            mem_dump (&spare_buf[0], spareSz);
#endif

        rc = flWritePage(page_no, &page_buf[0], &spare_buf[0], 0, 0);
        if (rc != IOS_ERROR_OK) {
            printf ("%s: write page %d, err=%d (%s)\n",
	            __FUNCTION__, page_no, rc, ioserr(rc));
            goto wrbN_out;
        }

        page_count--;
        if (verbose) printf ("%s: wrote page %d\n", __FUNCTION__, page_no);
        page_no++;

    } while ((size > 0) && (page_count > 0));

 wrbN_out:

    if (fp) fclose(fp);

    return rc;
}

static void
setupSron(void)
{
    u32 *ptr = (u32 *)ACR_SRN_PROT, reg;

    reg = *ptr;
    *ptr = reg | (ACRSRNPROT_AESEN_MASK
	           |  ACRSRNPROT_SHAEN_MASK
	           |  ACRSRNPROT_FLAEN_MASK);
  
    return;
}

int
dbg (char *args, char *d)
{
    /*
     * Takes no arguments and just toggles verbose
     */
    verbose = 1 - verbose;
    printf("verbose is %s\n", verbose ? "on" : "off");

    return 0;
}

int
rderr (char *args, char *d)
{
    s32   rc = 0;
    u32   reset = 0;
    char  *ptr;


    if (getNextToken(&ptr, &args) == 0) {
        printf ("Usage: rderr on/off [reset]\n");
        printf("Read-error is %s\n", rdErrEnabled ? "on" : "off");
        goto end;
    }
    else {
        if (strncmp(ptr, "off", 3) == 0)
            rdErrEnabled = 0;
        else if (strncmp(ptr, "on", 2) == 0)
            rdErrEnabled = 1;
        else {
            printf ("Usage: rderr on/off [reset]\n");
            goto end;
        }
    }
    if (getNextToken(&ptr, &args) != 0) {
        if (strncmp(ptr, "reset", 5) == 0)
            reset = 1;
        else
            reset = 0;
    }

    if (reset) {
        memset(erasedBlks, 0, sizeof(erasedBlks));
    }

    printf("Read-error is %s\n", rdErrEnabled ? "on" : "off");
  
end:
    return rc;

}

int
fdSelect (char *args, char *d)
{
    extern IOSError flSelDev(u32 id);

    u32 rc = IOS_ERROR_OK;
    u32 devId = 0;
    char  *ptr;


    if (getNextToken(&ptr, &args) == 0) {
        printf ("Usage: dev id\n");
        rc = -1;
        goto fdSelect_out;
    }
    devId = asciiToInt(ptr);

    rc = flSelDev(devId);
    if (rc != IOS_ERROR_OK) {
        printf("Failed to select device id %d, rc=%d\n", devId, rc);
        goto fdSelect_out;
    }

    printf("Select flash device id = %d\n", devId); 

fdSelect_out:

    return rc;
}

/* eof */
