/*
 *               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.10 2006/03/10 23:25:25 horti 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 FL_DEBUG_LEVEL		0x1f

#define HAVE_OS_ROUTINES   0
#define HAVE_FLASH_FS      0
#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

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

/* 
 * 16KB buffer.
 */
#if HAVE_OS_ROUTINES
static u8       *buf;
#else
static u8       buf[ISFS_BLOCK_SIZE + 16];
#endif

int cmdInitRun = 0;
int verbose = 0;

void setupSron (void);

s32
isfscmdInit(void)
{
    s32         rc = IOS_ERROR_OK;
    IOSError    result;
#if HAVE_OS_ROUTINES
    ISFSError   ret;
#endif

#if HAVE_OS_ROUTINES
    buf = IOS_Alloc(0, ISFS_BLOCK_SIZE);
    if (buf == NULL) {
        printf("%s: Failed to allocate buffer of size %d\n", 
               __FUNCTION__, ISFS_BLOCK_SIZE);
        rc = -1;
        goto isfscmdInit_out;
    }
#endif
    setupSron ();

    result = flOpen();
    if (result != IOS_ERROR_OK) {
        printf ("%s: Failed to mount, please reformat the flash\n",
                __FUNCTION__);
        rc = -2;
        return rc;
    }

#if HAVE_FLASH_FS
    ret = isfsMount(1);
    if (ret != ISFS_ERROR_OK) {
        printf("%s: Failed to mount, please reformat the flash\n",
               __FUNCTION__);
        goto isfscmdInit_out;
    }

    /* Set the current directory to the root directory */
    strncpy(cur, "/", ISFS_PATH_MAXLEN);

    cmdInitRun = 1;

isfscmdInit_out:
#endif

    if (rc < 0) {
        printf("%s: Failed to initialize FS commands\n",
               __FUNCTION__);
#if HAVE_OS_ROUTINES
        if (buf) {
            IOS_Free(0, buf);
        }
#endif
    }

    return rc;
}

void
isfscmdQuit(void)
{
    IOSError    result;
#if HAVE_FLASH_FS
    ISFSError   ret;

    ret = isfsMount(0);
    if (ret != ISFS_ERROR_OK) {
        printf("%s: Failed to unmount\n", 
               __FUNCTION__);
    }
#endif

    result = flClose();
    if (result != IOS_ERROR_OK) {
        printf("%s: Failed to close device driver\n", 
               __FUNCTION__);
    }

#if HAVE_OS_ROUTINES
    result = IOS_Free(0, buf);
    if (buf == NULL) {
        printf("%s: Failed to de-allocate buffer\n", 
               __FUNCTION__);
    }
#endif

    cmdInitRun = 0;

    return;
}


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

    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;
        }
    }

    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", (1 << cap.numPlanes));
    printf("Copy %d\n", (1 << cap.supportCopy));
    printf("Status byte offset %d\n", (1 << 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);
}

/*
 * format
 *
 * Format the flash file system.  This won't do anything until we have
 * a flash file system.
 */
int
format(char *args, char *d)
{
    printf ("%s: %s\n", __FUNCTION__, args);

    return 0;
}

/*
 * 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;

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

    if (getNextToken(&ptr, &args) == 0) {
        rc = -1;
        goto erase_out;
    }
    start = asciiToInt(ptr);

    if (getNextToken(&ptr, &args) == 0) {
        rc = -2;
        goto erase_out;
    }
    end = asciiToInt(ptr);

    printf("%s: Erasing flash block %d to %d\n", 
           __FUNCTION__, 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++) {
        rc = flErase(blkNum * numLogiBlks);
        if (rc != IOS_ERROR_OK) {
            printf("%s: Failed to erase flash block %d\n", 
                   __FUNCTION__, blkNum);
            goto erase_out;
        }
    }

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;
            }

            rc = flWrite(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;

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

    if (getNextToken(&boot1, &args) == 0) {
        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;
                }   
            }

            rc = flWrite(blkNum, (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++) {
            rc = flWrite(j, (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;

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


    if (getNextToken(&boot2, &args) == 0) {
        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;

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

    if ((getNextToken(&boot1, &args) == 0) ||
            (getNextToken(&boot2, &args) == 0)) {
        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);
}

char *
ioserr (int err) {
  switch (err) {
  case IOS_ERROR_ECC:
    return "single-bit error";
  case IOS_ERROR_ECC_CRIT:
    return "multi-bit error";
  }
  return "unknown";
}

char page_buf[BYTES_PER_PAGE];
char spare_buf[BYTES_PER_SPARE];

int
fr(char *args, char *d)
{
  s32           rc = 0, dump = 0, 
    count1 = BYTES_PER_SPARE, count2 = BYTES_PER_SPARE;
  char          *ptr, *filename = NULL;
  u32           page_no;
  IOSError      status;

  if (getNextToken(&ptr, &args) == 0) {
    printf ("fr page_num [data_bytes to dump] [filename]\n");
    rc = -1;
    goto fr_out;
  }
  page_no = 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);
    printf ("fr: will dump %d bytes of data and %d of spare\n",
	    count1, count2);
  }

  if ((page_no < 0) || (page_no > 1024)) {
    printf ("rf: bad page number %d\n", page_no);
    rc = -1;
    goto fr_out;
  }

  if (getNextToken(&filename, &args) == 0) {
    printf ("fr: no filename.   Will dump to screen\n");
    dump = 1;
  }

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

  status = flReadPage(page_no, &page_buf[0], &spare_buf[0]);
  if (status != IOS_ERROR_OK) {
    printf ("fr: bad frReadPage %d %s\n", status, ioserr(status));
    rc = -1;
  }

  if (dump != 0) {
    printf ("fr: page data\n");
    mem_dump (&page_buf[0], count1);
    printf ("fr: spare data\n");
    mem_dump (&spare_buf[0], count2);
  }

 fr_out:

  return (rc);
}

int 
fw (char *args, char *d)
{
  s32            rc = 0;
  u32            page_no, i, start_data = 0;
  char           *ptr;

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

  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, 0);
  if (rc != IOS_ERROR_OK) {
    printf ("fw: page page write %d %s\n",
	    rc, ioserr(rc));
    goto fw_out;
  }
  printf ("fw: page %d written\n", page_no);

 fw_out:

  return rc;
}

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 ("fv block_no page_no1 [page_no2]\n");
    rc = -1;
    goto fv_out;
  }
  block_no = asciiToInt(ptr);

  if (getNextToken(&ptr, &args) == 0) {
    printf ("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]);
    if (status != IOS_ERROR_OK) {
      printf ("fv: page %d bad frReadPage %d %s\n", 
	      i, status, ioserr(status));
      rc = -1;
    } else {
      printf ("%s: page %2d is good\n",
	      __FUNCTION__, i);
    }
  }

 fv_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 ("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;

    if (verbose)
      mem_dump (&spare_buf[0], BYTES_PER_SPARE);

    rc = flWritePage(page_no, &page_buf[0], &spare_buf[0], 0, 0);
    if (rc != IOS_ERROR_OK) {
      printf ("%s: bad page %d write %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 ("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;

    if (verbose)
      mem_dump (&spare_buf[0], BYTES_PER_SPARE);

    rc = flWritePage(page_no, &page_buf[0], &spare_buf[0], 0, 0);
    if (rc != IOS_ERROR_OK) {
      printf ("%s: bad page %d write %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, eBlkSz, size, page_count = DEFAULT_PAGE_COUNT;
  u32 block = 1;

  if (getNextToken(&fname, &args) == 0) {
    printf ("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);
    printf ("%s: will load %d pages\n", __FUNCTION__, page_count);
  }
  
  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;
  }
  eBlkSz = (1 << cap.erasableBlockSzShift);

  fp = fopen(fname, "rb");
  if (fp == NULL) {
    printf ("%s: cannot open file %s\n", __FUNCTION__, fname);
    rc = -1;
    goto wrbN_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 = 64*(block);
  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;

    if (verbose)
      mem_dump (&spare_buf[0], BYTES_PER_SPARE);

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

    page_count--;
    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;
}

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)
{
  s32             rc = 0;

  /*
   * Takes no arguments and just toggles verbose
   */

  verbose = 1 - verbose;

  if (verbose) {
    printf("verbose is on\n");
  } else {
    printf("verbose is off\n");
  }

  return rc;
}

/* eof */
