/*
 *               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.
 *
 *  Description:
 *      This file implements file system related monitor functions
 *
 */


#include <ioslibc.h>
#include <fs.h>
#include <fl_ops.h>
#include <fs_block.h>
#include <fs_fat.h>
#include <fs_ops.h>
#include <boot.h>
#include <boot2_ops.h>
#include <apputils.h>

#ifdef NET_CARD
#include <sc/sc.h>
#include <sc/ios.h>
#endif

#ifdef NEXT_GEN
#include <rvl/iop.h>
#include <rvl/ios.h>
#ifdef CPU_TO_BUS_ADDR
#undef CPU_TO_BUS_ADDR
#define CPU_TO_BUS_ADDR(a)  (a)
#endif
#endif


/* Dump size */
#define DUMP_SIZE               1024

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


/* 16KB buffer */
static u8       *buf;

/* Current directory */
static char     cur[ISFS_PATH_MAXLEN];


s32
isfscmdInit(void)
{
    s32         rc = 0;
    IOSError    result;
    ISFSError   ret;

    buf = IOS_AllocAligned(0, ISFS_BLOCK_SIZE, 64);
    if (buf == NULL) {
        printf("Failed to allocate buffer of size %d\n", ISFS_BLOCK_SIZE);
        rc = -1;
        goto isfscmdInit_out;
    }

    result = flOpen();
    if (result != IOS_ERROR_OK) {
        rc = -2;
        goto isfscmdInit_out;
    }

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

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

isfscmdInit_out:

    if (rc < 0) {
        printf("Failed to initialize FS commands\n");
        if (buf) {
            IOS_Free(0, buf);
        }
    }

    return (rc);
}


void
isfscmdQuit(void)
{
    IOSError    result;
    ISFSError   ret;

    ret = isfsMount(0);
    if (ret != ISFS_ERROR_OK) {
        printf("Failed to unmount\n");
    }

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

    result = IOS_Free(0, buf);
    if (buf == NULL) {
        printf("Failed to de-allocate buffer\n");
    }
}


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

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

    printf("Total flash size %d\n", (1 << cap.totalSzShift));
    printf("Erasable block size %d\n", (1 << cap.erasableBlockSzShift));

cap_out:

    return (rc);
}

s32
id(char *args, char *d)
{
    s32         rc = 0;
    FLIdentifier id;
    char *maker = "unknown";
    char *device = "unknown";

    rc = flGetId(&id);
    if (rc != IOS_ERROR_OK) {
        printf("Failed to get flash id, rc=%d\n", rc);
        goto id_out;
    }

    switch (id.makerID) {
    case FL_HYNIX_ID:
        maker = "Hynix";
        break;
    case FL_SAMSUNG_ID:
        maker = "Samsung";
        break;
    case FL_TOSHIBA_ID:
        maker = "Toshiba";
        break;
    }
    
    switch (id.deviceID) {
    case FL_SAMSUNG_64MB_ID:
        device = "64MB";
        break;
    case FL_SAMSUNG_256MB_ID:
        device = "256MB";
        break;
    }
    printf("Manufacturer: %02X (%s)\n", id.makerID, maker);
    printf("Device:       %02X (%s)\n", id.deviceID, device);

id_out:

    return (rc);
}


u32
statfs(char *args, char *d)
{
    s32         rc = IOS_ERROR_OK;
    ISFSStats   stat;

    rc = isfsGetStats(&stat);
    if (rc != IOS_ERROR_OK) {
        printf("Failed to get FS stats, rc=%d\n", rc);
        goto statfs_out;
    }

    printf("File system statistics:\n");
    printf("Block size:         %d\n", stat.blockSize);
    printf("Free blocks:        %d\n", stat.freeBlocks);
    printf("Occupied blocks:    %d\n", stat.occupiedBlocks);
    printf("Bad blocks:         %d\n", stat.badBlocks);
    printf("Reserved blocks:    %d\n", stat.reservedBlocks);
    printf("Free inodes:        %d\n", stat.freeInodes);
    printf("Occupied inodes:    %d\n", stat.occupiedInodes);

statfs_out:

    return (rc);
}


s32
erase(char *args, char *d)
{
    s32         rc = 0;
    FLDevCap    cap;
    char        *ptr;
    u32         start, end, numLogiBlks, blkNum, force = 0;

    if (getNextToken(&ptr, &args) == 0) {
        rc = -1;
        goto erase_out;
    }
    if (strncmp(ptr, "-f", 2) == 0) {
        force = 1;

        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("Erasing flash block %d to %d\n", start, end);

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

    for (blkNum = start; blkNum <= end; blkNum++) {
        if (!force) {
            rc = flStatus(blkNum * numLogiBlks);
            if (rc == IOS_ERROR_BADBLOCK) {
                printf("Detected bad block %d, rc=%d\n", blkNum, rc);
                continue;
            }
        }

        rc = flErase(blkNum * numLogiBlks);
        if (rc != IOS_ERROR_OK) {
            printf("Failed to erase flash block %d\n", blkNum);
            goto erase_out;
        }
    }

erase_out:

    return (rc);
}


s32
cd(char *args, char *d)
{
    s32         rc = 0;
    u32         len, num;
    ISFSError   result = ISFS_ERROR_OK;
    char        *name, temp[ISFS_PATH_MAXLEN];

    if (getNextToken(&name, &args) == 0) {
        rc = -1;
        goto cd_out;
    }

    len = strnlen(name, ISFS_PATH_MAXLEN);

    if (name[0] == '/') {
        /* Absolute path */
        if (len < ISFS_PATH_MAXLEN) {
            strncpy(temp, name, ISFS_PATH_MAXLEN);
        }
    } else {
        int     cur_len = strnlen(cur, ISFS_PATH_MAXLEN);

        /* Relative path */
        if ((len + cur_len) < ISFS_PATH_MAXLEN) {
            strncpy(temp, cur, ISFS_PATH_MAXLEN);

            if (cur_len != 1) {     /* Not root */
                temp[cur_len] = '/';
                cur_len++;
            }
            memcpy((temp + cur_len), name, (len + 1));
        }
    }

    /* Make sure the directory exists by doing a read */
    result = isfsReadDir(IOS_ROOT_ID, IOS_ROOT_GROUP, temp, NULL, &num);
    if (result != ISFS_ERROR_OK) {
        rc = -2;
        goto cd_out;
    }

    /* cd is successful, change the current directory */
    strncpy(cur, temp, ISFS_PATH_MAXLEN);

cd_out:

    if (rc == 0) {
        printf("Current directory is %s\n", cur);
    } else {
        printf("Failed to cd, rc=%d\n", rc);
    }

    return (rc);
}


s32
ls(char *args, char *d)
{
    s32         rc = 0;
    u32         num, count;
    ISFSError   result;
    u8          *list = buf;

    result = isfsReadDir(IOS_ROOT_ID, IOS_ROOT_GROUP, cur, NULL, &num);
    if (result != ISFS_ERROR_OK) {
        printf("Failed to get the number of elements, rc=%d\n", result);
        rc = -1;
        goto ls_out;
    }

    result = isfsReadDir(IOS_ROOT_ID, IOS_ROOT_GROUP, cur, list, &num);
    if (result != ISFS_ERROR_OK) {
        printf("Failed to read the directory, rc=%d\n", result);
        rc = -2;
        goto ls_out;
    }

    printf("List of files/directories under %s:\n", cur);
    for (count = 0; count < num; count++) {
        printf("%s\n", list);
        list += strnlen(list, ISFS_INODE_NAMELEN) + 1;
    }

ls_out:

    if (rc != 0) {
        printf("Failed to ls, rc=%d\n", rc);
    }

    return (rc);
}


void
getAbsolutePath(char *rel, char *ab)
{
    u32     len;

    len = strnlen(rel, ISFS_PATH_MAXLEN);

    if (rel[0] == '/') {
        /* Absolute path */
        if (len < ISFS_PATH_MAXLEN) {
            strncpy(ab, rel, ISFS_PATH_MAXLEN);
        }
    } else {
        int     cur_len = strnlen(cur, ISFS_PATH_MAXLEN);

        /* Relative path */
        if ((len + cur_len) < ISFS_PATH_MAXLEN) {
            strncpy(ab, cur, ISFS_PATH_MAXLEN);

            if (cur_len != 1) {     /* Not root */
                ab[cur_len] = '/';
                cur_len++;
            }
            memcpy((ab + cur_len), rel, (len + 1));
        }
    }
}


s32
cp(char *args, char *d)
{
    s32             rc = 0, fd = -1, fdSrc = -1;
    u32             size;
    ISFSError       result;
    char            *opt, *src, *dst;
    char            tempSrc[ISFS_PATH_MAXLEN], tempDst[ISFS_PATH_MAXLEN];
    u32             addr = (u32) buf, force = 0;
    u32             startw, endw, totalw = 0, startr, endr, totalr = 0;
    ISFSFileStats   stats;

    if (getNextToken(&opt, &args) == 0) {
        rc = -1;
        goto cp_out;
    }
    if (strncmp(opt, "-f", 2) == 0) {
        force = 1;
        if (getNextToken(&src, &args) == 0) {
            rc = -1;
            goto cp_out;
        }
    } else {
        src = opt;
    }
    if ((getNextToken(&dst, &args) == 0)) {
        rc = -1;
        goto cp_out;
    }

    getAbsolutePath(src, tempSrc);
    getAbsolutePath(dst, tempDst);

    fdSrc = isfsOpen(IOS_ROOT_ID, IOS_ROOT_GROUP, tempSrc, ISFS_READ_ACCESS);
    if (fdSrc < 0) {
        printf("Failed to open source file %d\n", fdSrc);
        printf("Please use the put command to transfer from a remote host"
            " to the target flash\n");
        rc = -2;
        goto cp_out;
    }

    /* Open the destination file */
    result = isfsCreateFile(IOS_ROOT_ID, IOS_ROOT_GROUP, tempDst,
                        0, ISFS_RW_ACCESS, ISFS_RW_ACCESS, ISFS_RW_ACCESS);
    if (result != ISFS_ERROR_OK) {
        if (result == ISFS_ERROR_EXISTS) {
            if (!force) {
                printf("File already exists, please delete first\n");
                rc = -3;
                goto cp_out;
            } else {
                result = isfsDelete(IOS_ROOT_ID, IOS_ROOT_GROUP, tempDst);
                if (result != ISFS_ERROR_OK) {
                    printf("Failed to delete %d\n", result);
                    rc = -3;
                    goto cp_out;
                }

                result = isfsCreateFile(IOS_ROOT_ID, IOS_ROOT_GROUP, tempDst,
                            0, ISFS_RW_ACCESS, ISFS_RW_ACCESS, ISFS_RW_ACCESS);
                if (result != ISFS_ERROR_OK) {
                    printf("Failed to create file %d\n", result);
                    rc = -3;
                    goto cp_out;
                }
            }
        } else {
            printf("Failed to create file %d\n", result);
            rc = -3;
            goto cp_out;
        }
    }

    fd = isfsOpen(IOS_ROOT_ID, IOS_ROOT_GROUP, tempDst, ISFS_WRITE_ACCESS);
    if (fd < 0) {
        printf("Failed to open destination file %d\n", fd);
        rc = -4;
        goto cp_out;
    }

    memset((void *)addr, 0, DUMP_SIZE);

    result = isfsGetFileStats(fdSrc, &stats);
    if (result != ISFS_ERROR_OK) {
        printf("Failed to get file stats %d\n, result");
        rc = -5;
        goto cp_out;
    }
    size = stats.size;

    /* Read data from source to destination */
    printf("Loading %#x bytes from '%s' @ %#08x\n", size, src, addr);
    while (size) {
        int     bytes;

        startr = IO_READ(SYS_TIMER_REG);
        result = isfsRead(fdSrc, (void *)addr, ISFS_BLOCK_SIZE);
        endr = IO_READ(SYS_TIMER_REG);
        if (result != ISFS_ERROR_OK) {
            printf("Failed to read %d\n", result);
            rc = -6;
            goto cp_out;
         }
        totalr += (endr - startr);

        bytes = (size > ISFS_BLOCK_SIZE) ? ISFS_BLOCK_SIZE : size;
        size -= bytes;

        startw = IO_READ(SYS_TIMER_REG);
        result = isfsWrite(fd, (u8 *)addr, bytes);
        endw = IO_READ(SYS_TIMER_REG);
        if (result != ISFS_ERROR_OK) {
            printf("Failed to write %d\n", result);
            rc = -7;
            goto cp_out;
        }
        totalw += (endw - startw);
    }

    if (totalr > 0) {
        printf("Total read time is %d ticks\n", totalr);
    }
    if (totalw > 0) {
        printf("Total write time is %d ticks\n", totalw);
    }

cp_out:

    if (fdSrc >= 0) {
        isfsClose(fdSrc);
    }

    if (fd >= 0) {
        isfsClose(fd);
    }

    if (rc == 0) {
        printf("Copied file to %s\n", tempDst);
    } else {
        printf("Failed to cp, rc=%d\n", rc);
    }

    return (rc);
}


s32
mv(char *args, char *d)
{
    s32         rc = 0;
    char        *src, *dst;
    char        srcTemp[ISFS_PATH_MAXLEN], dstTemp[ISFS_PATH_MAXLEN];
    ISFSError   result;

    if (getNextToken(&src, &args) == 0) {
        rc = -1;
        goto mv_out;
    }

    if (getNextToken(&dst, &args) == 0) {
        rc = -2;
        goto mv_out;
    }

    getAbsolutePath(src, srcTemp);
    getAbsolutePath(dst, dstTemp);

    result = isfsRename(IOS_ROOT_ID, IOS_ROOT_GROUP, srcTemp, dstTemp);
    if (result != ISFS_ERROR_OK) {
        printf("Failed to rename %s to %s, rc = %d\n", srcTemp, dstTemp, rc);
        rc = -3;
        goto mv_out;
    }

mv_out:

    return (rc);
}


s32
put(char *args, char *d)
{
    s32         rc = 0, fd = -1;
    u32         i, size;
    ISFSError   result;
    FILE        *fp = NULL;
    char        *opt, *src, *dst, temp[ISFS_PATH_MAXLEN];
    u32         addr = (u32) buf, force = 0;
    u32         startw, endw, totalw = 0;

    if (getNextToken(&opt, &args) == 0) {
        rc = -1;
        goto put_out;
    }
    if (strncmp(opt, "-f", 2) == 0) {
        force = 1;
        if (getNextToken(&src, &args) == 0) {
            rc = -1;
            goto put_out;
        }
    } else {
        src = opt;
    }
    if ((getNextToken(&dst, &args) == 0)) {
        rc = -1;
        goto put_out;
    }

    getAbsolutePath(dst, temp);

    /* Open the source file */
    fp = fopen(src, "rb");
    if (fp == NULL) {
        printf("Failed to open source file\n");
        rc = -2;
        goto put_out;
    }

    /* Open the destination file */
    result = isfsCreateFile(IOS_ROOT_ID, IOS_ROOT_GROUP, temp,
                        0, ISFS_RW_ACCESS, ISFS_RW_ACCESS, ISFS_RW_ACCESS);
    if (result != ISFS_ERROR_OK) {
        if (result == ISFS_ERROR_EXISTS) {
            if (!force) {
                printf("File already exists, please delete first\n");
                rc = -3;
                goto put_out;
            } else {
                result = isfsDelete(IOS_ROOT_ID, IOS_ROOT_GROUP, temp);
                if (result != ISFS_ERROR_OK) {
                    printf("Failed to delete %d\n", result);
                    rc = -3;
                    goto put_out;
                }

                result = isfsCreateFile(IOS_ROOT_ID, IOS_ROOT_GROUP, temp,
                            0, ISFS_RW_ACCESS, ISFS_RW_ACCESS, ISFS_RW_ACCESS);
                if (result != ISFS_ERROR_OK) {
                    printf("Failed to create file %d\n", result);
                    rc = -3;
                    goto put_out;
                }
            }
        } else {
            printf("Failed to create file %d\n", result);
            rc = -3;
            goto put_out;
        }
    }

    fd = isfsOpen(IOS_ROOT_ID, IOS_ROOT_GROUP, temp, ISFS_WRITE_ACCESS);
    if (fd < 0) {
        printf("Failed to open destination file %d\n", fd);
        rc = -4;
        goto put_out;
    }

    memset((void *)addr, 0, DUMP_SIZE);

    /* Read data from source to destination */
    size = flen(fp);
    i = 0;
    printf("Loading %#x bytes from '%s' @ %#08x\n", size, src, addr);
    while (size) {
        int     bytes;

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

        fread((void *)addr+i, bytes, 1, fp);

        size -= bytes;
        i += bytes;
        if ((size == 0) || (i == (ISFS_BLOCK_SIZE))) {
            startw = IO_READ(SYS_TIMER_REG);
            result = isfsWrite(fd, (u8 *)addr, i);
            endw = IO_READ(SYS_TIMER_REG);
            if (result != ISFS_ERROR_OK) {
                printf("Failed to write to file, rc=%d\n", result);
                rc = -5;
                goto put_out;
            }
            totalw += (endw - startw);

            i = 0;
        }
    }

    if (totalw > 0) {
        printf("Total write time is %d ticks\n", totalw);
    }

put_out:

    if (fd >= 0) {
        isfsClose(fd);
    }

    if (fp) {
        fclose(fp);
    }

    if (rc == 0) {
        printf("Copied file to %s\n", temp);
    } else {
        printf("Failed to cp, rc=%d\n", rc);
    }

    return (rc);
}

s32
get(char *args, char *d)
{
    s32         rc = 0, fd = -1;
    u32         i, size;
    ISFSError   result;
    FILE        *fp = NULL;
    char        *src, *dst, temp[ISFS_PATH_MAXLEN];
    u32         addr = (u32) buf;

    if (getNextToken(&src, &args) == 0) {
        rc = -1;
        goto get_out;
    }
    if ((getNextToken(&dst, &args) == 0)) {
        rc = -1;
        goto get_out;
    }

    getAbsolutePath(src, temp);

    /* Open the source file */
    fd = isfsOpen(IOS_ROOT_ID, IOS_ROOT_GROUP, temp, ISFS_READ_ACCESS);
    if (fd < 0) {
        printf("Failed to open source file %d\n", fd);
        rc = -2;
        goto get_out;
    }

    /* Open the destination file */
    fp = fopen(dst, "wb");
    if (fp == NULL) {
        printf("Failed to open destination file\n");
        rc = -3;
        goto get_out;
    }

    memset((void *)addr, 0, DUMP_SIZE);

    /* Read data from source to destination */
    ISFSFileStats   stats;
    result = isfsGetFileStats(fd, &stats);
    if (result != ISFS_ERROR_OK) {
        printf("Failed to get file stats %d\n, result");
        rc = -5;
        goto get_out;
    }
    size = stats.size;
    i = 0;
    printf("Loading %#x bytes from '%s' @ %#08x\n", size, src, addr);
    while (size) {
        int     bytes;

        bytes = (size > ISFS_BLOCK_SIZE) ? ISFS_BLOCK_SIZE : size; 

        /* Read rounding up to 16KB */
        result = isfsRead(fd, (void *)addr,
                    (bytes + ISFS_BLOCK_SIZE - 1) & ~(ISFS_BLOCK_SIZE - 1));
        if (result != ISFS_ERROR_OK) {
            printf("Failed to read %d\n", result);
            rc = -6;
            goto get_out;
         }
        fwrite((void *)addr, bytes, 1, fp);

        size -= bytes;
        i += bytes;
    }

get_out:

    if (fd >= 0) {
        isfsClose(fd);
    }

    if (fp) {
        fclose(fp);
    }

    if (rc == 0) {
        printf("Copied file to %s\n", dst);
    } else {
        printf("Failed to cp, rc=%d\n", rc);
    }

    return (rc);
}


s32
dump(char *args, char *d)
{
    s32         rc = 0, fd = -1;
    ISFSError   result;
    char        *fname, temp[ISFS_PATH_MAXLEN], *data_p;
    u32         len, addr = (u32) buf;

    if (getNextToken(&fname, &args) == 0) {
        rc = -1;
        goto dump_out;
    }

    /* Figure out the path name */
    len = strnlen(fname, ISFS_PATH_MAXLEN);

    if (fname[0] == '/') {
        /* Absolute path */
        if (len < ISFS_PATH_MAXLEN) {
            strncpy(temp, fname, ISFS_PATH_MAXLEN);
        }
    } else {
        int     cur_len = strnlen(cur, ISFS_PATH_MAXLEN);

        /* Relative path */
        if ((len + cur_len) < ISFS_PATH_MAXLEN) {
            strncpy(temp, cur, ISFS_PATH_MAXLEN);

            if (cur_len != 1) {     /* Not root */
                temp[cur_len] = '/';
                cur_len++;
            }
            memcpy((temp + cur_len), fname, (len + 1));
        }
    }

    /* Open the file */
    fd = isfsOpen(IOS_ROOT_ID, IOS_ROOT_GROUP, temp, ISFS_READ_ACCESS);
    if (fd < 0) {
        rc = -2;
        goto dump_out;
    }

    data_p = (u8 *) addr;
    memset(data_p, 0, DUMP_SIZE);

    /* Read the first FS block of file */
    result = isfsRead(fd, data_p, ISFS_BLOCK_SIZE);
    if (result != ISFS_ERROR_OK) {
        if (result == ISFS_ERROR_INVALID) {
            printf("File is empty\n");
            goto dump_out;
        } else {
            printf("Failed to read %d\n", result);
            rc = -3;
            goto dump_out;
        }
    }

    /* Dump at most the first 1KB */
    data_p[DUMP_SIZE] = '\0';
    printf("%s\n", data_p);

dump_out:

    if (fd >= 0) {
        isfsClose(fd);
    }

    if (rc != 0) {
        printf("Failed to dump, rc=%d\n", rc);
    }

    return (rc);
}

s32
stat(char *args, char *d)
{
    s32         rc = 0, fd = -1;
    ISFSError   result;
    char        *fname, temp[ISFS_PATH_MAXLEN];
    ISFSFileStats stats;

    if (getNextToken(&fname, &args) == 0) {
        rc = -1;
        goto stat_out;
    }

    getAbsolutePath(fname, temp);

    /* Open the file */
    fd = isfsOpen(IOS_ROOT_ID, IOS_ROOT_GROUP, temp, ISFS_READ_ACCESS);
    if (fd < 0) {
        rc = -2;
        goto stat_out;
    }

    result = isfsGetFileStats(fd, &stats);
    if (result != ISFS_ERROR_OK) {
        printf("Failed to get file stats %d\n", result);
        rc = -3;
        goto stat_out;
    }

    printf("'%s' stats:\n", fname);
    printf("  bytes:  %d\n", stats.size);
    printf("  offset: %d\n", stats.offset);

stat_out:
    if (fd >= 0) {
        isfsClose(fd);
    }

    return (rc);
}

static char *
access(char *s, u32 len, u32 access)
{
    switch (access) {
    case 0:
        snprintf(s, len, "NONE");
        break;
    case ISFS_READ_ACCESS:
        snprintf(s, len, "R");
        break;
    case ISFS_WRITE_ACCESS:
        snprintf(s, len, "W");
        break;
    case ISFS_RW_ACCESS:
        snprintf(s, len, "RW");
        break;
    default:
        snprintf(s, len, "ILLEGAL");
        break;
    }
    return s;
}

s32
attr(char *args, char *d)
{
    s32         rc = 0;
    ISFSError   result;
    char        *fname, temp[ISFS_PATH_MAXLEN];
    char accString[16];
    IOSUid owner;
    IOSGid group;
    u32 attributes;
    u32 ownerAcc;
    u32 groupAcc;
    u32 othersAcc;

    if (getNextToken(&fname, &args) == 0) {
        rc = -1;
        goto attr_out;
    }

    getAbsolutePath(fname, temp);

    result = isfsGetAttr(IOS_ROOT_ID, IOS_ROOT_GROUP, temp, &owner, &group, &attributes, &ownerAcc, &groupAcc, &othersAcc);
    if (result != ISFS_ERROR_OK) {
        printf("Failed to get file attributes %d\n", result);
        rc = -3;
        goto attr_out;
    }

    printf("'%s' attributes:\n", fname);
    printf("  owner: 0x%x\n", owner);
    printf("  group: 0x%x\n", group);
    printf("  attributes: 0x%x\n", attributes);
    printf("  owner access: %s\n", access(accString, sizeof(accString), ownerAcc));
    printf("  group access: %s\n", access(accString, sizeof(accString), groupAcc));
    printf("  others access: %s\n", access(accString, sizeof(accString), othersAcc));

attr_out:
    return (rc);
}


s32
mkdir(char *args, char *d)
{
    s32         rc = 0;
    u32         len;
    ISFSError   result;
    char        *name, temp[ISFS_PATH_MAXLEN];

    if (getNextToken(&name, &args) == 0) {
        rc = -1;
        goto mkdir_out;
    }

    len = strnlen(name, ISFS_PATH_MAXLEN);

    if (name[0] == '/') {
        /* Absolute path */
        if (len < ISFS_PATH_MAXLEN) {
            strncpy(temp, name, ISFS_PATH_MAXLEN);
        }
    } else {
        int     cur_len = strnlen(cur, ISFS_PATH_MAXLEN);

        /* Relative path */
        if ((len + cur_len) < ISFS_PATH_MAXLEN) {
            strncpy(temp, cur, ISFS_PATH_MAXLEN);

            if (cur_len != 1) {     /* Not root */
                temp[cur_len] = '/';
                cur_len++;
            }
            memcpy((temp + cur_len), name, (len + 1));
        }
    }

    /* Create the new directory */
    result = isfsCreateDir(IOS_ROOT_ID, IOS_ROOT_GROUP, temp,
          0, ISFS_RW_ACCESS, ISFS_RW_ACCESS, ISFS_RW_ACCESS);
    if (result != ISFS_ERROR_OK) {
        rc = -2;
        goto mkdir_out;
    }

mkdir_out:

    if (rc == 0) {
        printf("Created directory %s\n", temp);
    } else {
        printf("Failed to create the directory, rc=%d\n", rc);
    }

    return (rc);
}


s32
rm(char *args, char *d)
{
    s32         rc = 0;
    u32         len;
    ISFSError   result;
    char        *name, temp[ISFS_PATH_MAXLEN];

    if (getNextToken(&name, &args) == 0) {
        rc = -1;
        goto rm_out;
    }

    len = strnlen(name, ISFS_PATH_MAXLEN);

    if (name[0] == '/') {
        /* Absolute path */
        if (len < ISFS_PATH_MAXLEN) {
            strncpy(temp, name, ISFS_PATH_MAXLEN);
        }
    } else {
        int     cur_len = strnlen(cur, ISFS_PATH_MAXLEN);

        /* Relative path */
        if ((len + cur_len) < ISFS_PATH_MAXLEN) {
            strncpy(temp, cur, ISFS_PATH_MAXLEN);

            if (cur_len != 1) {     /* Not root */
                temp[cur_len] = '/';
                cur_len++;
            }
            memcpy((temp + cur_len), name, (len + 1));
        }
    }

    /* Try to delete as a file */
    result = isfsDelete(IOS_ROOT_ID, IOS_ROOT_GROUP, temp);
    if (result != ISFS_ERROR_OK) {
        printf("Delete returns error %d\n", result);
        rc = -2;
        goto rm_out;
    }

rm_out:

    if (rc == 0) {
        printf("Removed %s\n", temp);
    } else {
        printf("Failed to remove the file or directory, rc=%d\n", rc);
    }

    return (rc);
}


s32
format(char *args, char *d)
{
    s32         rc = 0;

    rc = isfsFormat(IOS_ROOT_ID);
    if (rc != ISFS_ERROR_OK) {
        printf("Failed to format file system, rc=%d\n", rc);
        goto format_out;
    }

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

format_out:
    
    if (rc == 0) {
        printf("Formatted the file system\n");
    } else {
        printf("Failed to format, rc=%d\n", rc);
    }

    return (rc);
}


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

    /* 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;
    blkNum = 0;
    numLogiBlks = (eBlkSz >> FL_LOGI_BLOCK_SIZE_SHIFT);
    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 flash block */
            if ((blkNum & (numLogiBlks - 1)) == 0) {
                rc = flErase(blkNum);
                if (rc != IOS_ERROR_OK) {
                    printf("Failed to erase block %d\n", blkNum);
                    goto __writeboot1_out;
                }
            }

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

            blkNum++;
            i = 0;
        }
    }

    /* Pad to the size of a full flash block */
    memset((u8 *) addr, 0, FL_LOGI_BLOCK_SIZE);
    for (; blkNum < numLogiBlks; blkNum++) {
        rc = flWrite(blkNum, 1, NULL, NULL, 0, (u8 *) addr, (u8 *) addr);
        if (rc != IOS_ERROR_OK) {
            printf("Failed to pad the rest of flash block, rc=%d\n", rc);
            goto __writeboot1_out;
        }
    }

__writeboot1_out:

    if (fp) {
        fclose(fp);
    }

    return (rc);
}


s32
writeboot1(char *args, char *d)
{
    s32         rc = 0;
    char        *boot1;

    if (getNextToken(&boot1, &args) == 0) {
        rc = -1;
        goto writeboot1_out;
    }

    rc = __writeboot1(boot1);

writeboot1_out:

    if (rc == ISFS_ERROR_OK) {
        printf("Write boot1 succeeded\n");
    }

    return (rc);
}


/* Write boot2 without a block map, no mirroring */
static s32
__writeboot2M(char *fname)
{
    s32         rc = 0;
    FILE        *fp = NULL;
    u32         addr = (u32) buf, size, bytes, i, totalBytes;
    u32         block, blkNum, eBlkSz, numLogiBlks;
    FLDevCap    cap;
    int         first = 0;

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

    /* Erase non-bad blocks */
    for (block = 1;
            block < (ISFS_SYSAREA_SIZE >> cap.erasableBlockSzShift);
            block++) {
        blkNum = block <<
                (cap.erasableBlockSzShift - FL_LOGI_BLOCK_SIZE_SHIFT);

        rc = flStatus(blkNum);
        if (rc != IOS_ERROR_OK) {
            continue;
        }

        rc = flErase(blkNum);
        if (rc != IOS_ERROR_OK) {
            printf("Failed to erase blk %d\n", block);
            goto __writeboot2M_out;
        }
    }

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

    /* Start at flash block 1 */
    blkNum = numLogiBlks;
    size = flen(fp);
    printf("Loading %#x bytes from '%s' @ %#08x\n", size, fname, addr);

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

        fread((void *) addr+i,  bytes, 1, fp);
        size -= bytes;
        totalBytes += bytes;
        i += bytes;
        if (first==0) {
            if (*((char*)addr+4)=='i' && *((char*)addr+5)=='b') {
                printf("incorrect WAD format, use publish.py instead\n");
                rc = -2;
                goto __writeboot2M_out;
            }
            first=1;
        }

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

            rc = flWrite(blkNum, 1, NULL, NULL, 0, (u8 *) addr, (u8 *) addr);
            if (rc != IOS_ERROR_OK) {
                printf("Failed to write boot3, rc=%d\n", rc);
                goto __writeboot2M_out;
            }

            i = 0;
            blkNum++;
        }
    }

__writeboot2M_out:

    if (fp) {
        fclose(fp);
    }

    return (rc);
}


static s32
__writeboot2(char *fname, u32 force)
{
    s32         rc = 0;
    FILE        *fp = NULL;
    u32         addr = (u32) buf, size, bytes, block, logiBlk, totalSize;
    FLDevCap    cap;
    int         first = 0;

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

    /* Erase if forcing a new write */
    if (force) {
        for (block = 1;
                block < (ISFS_SYSAREA_SIZE >> cap.erasableBlockSzShift);
                block++) {
            logiBlk = block <<
                    (cap.erasableBlockSzShift - FL_LOGI_BLOCK_SIZE_SHIFT);

            rc = flStatus(logiBlk);
            if (rc != IOS_ERROR_OK) {
                continue;
            }

            rc = flErase(logiBlk);
            if (rc != IOS_ERROR_OK) {
                printf("Failed to erase blk %d\n", block);
                goto __writeboot2_out;
            }
        }
    }

    rc = boot2Open();
    if (rc < 0) {
        printf("Failed to open boot2, rc=%d\n", rc);
        goto __writeboot2_out;
    }

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

    /* Get the size */
    totalSize = size = flen(fp);
    printf("Loading %#x bytes from '%s' @ %#08x\n", size, fname, addr);

    while (size) {
        bytes = (size > SEMIHOST_READ_SIZE) ? SEMIHOST_READ_SIZE : size;
        fread((void *) addr,  bytes, 1, fp);
        size -= bytes;
        if (first==0) {
            if (*((char*)addr+4)=='i' && *((char*)addr+5)=='b') {
                printf("incorrect WAD format, use publish.py instead\n");
                rc = -2;
                goto __writeboot2_close_out;
            }
            first=1;
        }

        rc = boot2Write((u8 *) addr, bytes);
        if (rc < 0) {
            printf("Failed to write boot2, rc=%d\n", rc);
            goto __writeboot2_close_out;
        }
    }

    rc = boot2CommitFirstCopy();
    if (rc != IOS_ERROR_OK) {
        printf("Failed to commit first copy of boot2, rc=%d\n", rc);
        goto __writeboot2_close_out;
    }

    rc = boot2SyncSecondCopy(totalSize);
    if (rc != IOS_ERROR_OK) {
        printf("Failed to sync second copy of boot2, rc=%d\n", rc);
        goto __writeboot2_close_out;
    }

__writeboot2_close_out:

    (void) boot2Close();

__writeboot2_out:

    if (fp) {
        fclose(fp);
    }

    return (rc);
}


s32
writeboot2(char *args, char *d)
{
    s32         rc = 0, force = 0, manufacture = 0;
    char        *opt, *boot2;

    if (getNextToken(&opt, &args) == 0) {
        rc = -1;
        goto writeboot2_out;
    }

    if (strncmp(opt, "-f", 2) == 0) {
        force = 1;
        if (getNextToken(&boot2, &args) == 0) {
            rc = -2;
            goto writeboot2_out;
        }
    } else if (strncmp(opt, "-m", 2) == 0) {
        manufacture = 1;
        if (getNextToken(&boot2, &args) == 0) {
            rc = -2;
            goto writeboot2_out;
        }
    } else {
        boot2 = opt;
    }

    if (manufacture) {
        rc = __writeboot2M(boot2);
    } else {
        rc = __writeboot2(boot2, force);
    }

writeboot2_out:

    if (rc == ISFS_ERROR_OK) {
        printf("Write boot2 succeeded\n");
    }

    return (rc);
}


s32
writeboot(char *args, char *d)
{
    s32         rc = 0;
    char        *boot1, *boot2;

    if ((getNextToken(&boot1, &args) == 0) ||
            (getNextToken(&boot2, &args) == 0)) {
        rc = -1;
        goto writeboot_out;
    }

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

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

writeboot_out:

    if (rc == ISFS_ERROR_OK) {
        printf("Write boot succeeded\n");
    }

    return (rc);
}


s32
showBad(char *args, char *d)
{
    s32         rc = 0, count, numBlocks;
    FLDevCap    cap;

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

    printf("The following flash blocks are marked as bad: ");

    numBlocks = 1 << (cap.totalSzShift - cap.erasableBlockSzShift);
    for (count = 0; count < numBlocks; count++) {
        u32 logiBlockNum = count <<
                        (cap.erasableBlockSzShift - FL_LOGI_BLOCK_SIZE_SHIFT);

        rc = flStatus(logiBlockNum);
        if (rc != IOS_ERROR_OK) {
            printf("%d ", count);
        }
    }
    printf("\n");

    rc = 0;

showBad_out:

    return (rc);
}


static void
__flashWritePage(int from, int to, int pageSize)
{
    int adp = (pageSize > 528) ? 0x1f: 0x1d;

    IO_WRITE(FL_AD0_REG, 0);
    IO_WRITE(FL_AD1_REG, to);
    IO_WRITE(FL_MA0_REG, CPU_TO_BUS_ADDR(from));
    IO_WRITE(FL_MA1_REG, 0);

    /* Disable the WP bit */
    IO_WRITE(FL_CONF_REG, IO_READ(FL_CONF_REG) & ~FL_CONF_WP);

    IO_WRITE(FL_CTRL_REG, FL_CTRL_EXEC |
                          FL_CTRL_WDP |
                         (adp << FL_CTRL_ADP_SHIFT) |
                         (0x80 << FL_CTRL_CMD_SHIFT)|
                         pageSize);
    while (IO_READ(FL_CTRL_REG) & FL_CTRL_EXEC);

    IO_WRITE(FL_CTRL_REG, FL_CTRL_EXEC |
                          FL_CTRL_RDY |
                          //FL_CTRL_ECC |
                          (0x10 << FL_CTRL_CMD_SHIFT));
    while (IO_READ(FL_CTRL_REG) & FL_CTRL_EXEC);

    /* Enable the WP bit */
    IO_WRITE(FL_CONF_REG, IO_READ(FL_CONF_REG) | FL_CONF_WP);
}

s32
markBad(char *args, char *d)
{
    s32         rc = 0, flBlock, logiBlock, page, alternate = 0;
    FLDevCap    cap;
    char        *ptr;

    if (getNextToken(&ptr, &args) == 0) {
        rc = -1;
        goto markBad_out;
    }
    if (strncmp(ptr, "-a", 2) == 0) {
        alternate = 1;
        if (getNextToken(&ptr, &args) == 0) {
            rc = -2;
            goto markBad_out;
        }
    }
    flBlock = asciiToInt(ptr);

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

    logiBlock = flBlock <<
                    (cap.erasableBlockSzShift - FL_LOGI_BLOCK_SIZE_SHIFT);
    rc = flStatus(logiBlock);
    if (rc == IOS_ERROR_BADBLOCK) {
        /* Already marked as bad, no need to do anything */
        printf("Block %d is already marked as bad\n", flBlock);
        goto markBad_out;
    }

    /* Erase the flash block */
    rc = flErase(logiBlock);
    if (rc != IOS_ERROR_OK) {
        printf("Failed to erase block %d\n", flBlock);
        goto markBad_out;
    }

    page = flBlock << (cap.erasableBlockSzShift - cap.pageSzShift);
    if (alternate) {
        /* Mark the second page */
        page++;
    }

    /* Set the status byte to something other than 0xff */
    buf[(1 << cap.pageSzShift) + cap.statusByteOffset] = 0xab;
    __flashWritePage((u32) buf, page,
                (1 << cap.pageSzShift) + (1 << cap.pageSpareSzShift));
    printf("Marked block %d as bad\n", flBlock);

markBad_out:

    return (rc);
}


s32
showBadAll(char *args, char *d)
{
    s32         rc = 0, count;
    ISFSFat     *fatp;

    /* Load the FAT */
    fatp = isfsLoadFat();
    if (fatp == NULL) {
        printf("Failed to load FAT\n");
        rc = ISFS_ERROR_NOTREADY;
        goto showBadAll_out;
    }

    printf("The following flash blocks are marked as bad in the FAT:\n");
    for (count = 0; count < ISFS_BLOCK_ENTRIES;
            count += ISFS_BLOCKS_IN_FL_BLOCK) {
        if (ISFS_FAT_BLOCK_ARRAY(fatp)[count] == ISFS_BLOCK_BAD) {
            printf("block %d\n", count / ISFS_BLOCKS_IN_FL_BLOCK);
        }
    }

showBadAll_out:

    if (rc < 0) {
        printf("showBadAll failed with rc=%d\n", rc);
    }

    return (rc);
}


s32
checkPage(char *args, char *d)
{
    s32         rc = 0;
    u32         i, start, pages;
    char        *ptr;

    /* Get the start page */
    if (getNextToken(&ptr, &args) == 0) {
        rc = -1;
        goto checkPage_out;
    }
    start = asciiToInt(ptr);

    /* Get the number of pages to verify */
    if (getNextToken(&ptr, &args) == 0) {
        rc = -2;
        goto checkPage_out;
    }
    pages = asciiToInt(ptr);

    /* Check all the pages indicated */
    for (i = 0; i < pages; i++) {
        rc = flReadPage(start + i, buf, NULL, 1);
        if (rc != IOS_ERROR_OK) {
            printf("Page %d failed check, rc=%d\n", start + i, rc);
            printf("%x:%x:%x:%x:%x:%x:%x:%x\n", buf[0], buf[1], buf[2], buf[3],
                                            buf[4], buf[5], buf[6], buf[7]);
        }
    }
    rc = IOS_ERROR_OK;

checkPage_out:

    if (rc < 0) {
        printf("checkPage failed with rc=%d\n", rc);
    }

    return (rc);
}


s32
blockTest(char *args, char *d)
{
    s32         rc = 0;
    u32         i, j, block, cycles, numPagesInBlock, page, pageSz;
    char        *ptr;
    FLDevCap    cap;

    /* Get the block to test */
    if (getNextToken(&ptr, &args) == 0) {
        rc = -1;
        goto blockTest_out;
    }
    block = asciiToInt(ptr);

    /* Get the number of cycles to run */
    if (getNextToken(&ptr, &args) == 0) {
        rc = -2;
        goto blockTest_out;
    }
    cycles = asciiToInt(ptr);

    /* Number of pages in a block */
    rc = flGetCap(&cap);
    if (rc != IOS_ERROR_OK) {
        printf("Failed to get flash cap, rc=%d\n", rc);
        goto blockTest_out;
    }
    numPagesInBlock = 1 << (cap.erasableBlockSzShift - cap.pageSzShift);
    pageSz = 1 << cap.pageSzShift;

    printf("Test block %d for %d cycles\n", block, cycles);

    /* Repeatedly do the erase-write cycle to the flash block */
    for (i = 0; i < cycles; i++) {
        if ((i % 1024) == 0) {
            printf("Tested %d cycles\n", i);
        }

        /* Erase the block before writing */
        rc = flErase(block <<
                (cap.erasableBlockSzShift - FL_LOGI_BLOCK_SIZE_SHIFT));
        if (rc != IOS_ERROR_OK) {
            printf("Failed to erase in cycle %d, rc=%d\n", i, rc);
            goto blockTest_out;
        }

        /* Write a known pattern to the buffer */
        for (page = 0; page < numPagesInBlock; page++) {
            for (j = 0; j < pageSz; j++) {
                buf[j] = (u8) (((j + 276) * page * i) - 778);
            }

            rc = flWritePage(((block * numPagesInBlock) + page), buf, NULL,
                            (page != (numPagesInBlock - 1)), 1);
            if (rc != IOS_ERROR_OK) {
                printf("Failed to write to page %d in cycle %d, rc=%d\n",
                    page, i, rc);
                goto blockTest_out;
            }
        }

        /* Read back to check data integrity */
        for (page = 0; page < numPagesInBlock; page++) {
            memset(buf, 0, pageSz);
            rc = flReadPage(((block * numPagesInBlock) + page), buf, NULL, 1);
            if ((rc != IOS_ERROR_OK) && (rc != IOS_ERROR_ECC)) {
                printf("Failed to read back page %d in cycle %d, rc=%d\n",
                    page, i, rc);
                goto blockTest_out;
            }
            if (rc == IOS_ERROR_ECC) {
                printf("Found single-bit ECC error while reading page %d"
                    " in cycle %d\n", page, i);
            }

            /* Data integrity check */
            for (j = 0; j < pageSz; j++) {
                if (buf[j] != (u8) (((j + 276) * page * i) - 778)) {
                    printf("Failed read-back check for page %d in cycle %d"
                        " at byte %d:%x, rc=%d\n", page, i, j, buf[j], rc);
                    goto blockTest_out;
                }
            }
        }
    }
 
blockTest_out:

    if (rc < 0) {
        printf("blockTest failed with rc=%d\n", rc);
    }

    return (rc);
}


static IOSError
__copyPageToBlock(u32 srcPage, u32 dstBlock)
{
    IOSError    rc = IOS_ERROR_OK;
    u32         page, pageSz, dstPage, numPagesInBlock;
    FLDevCap    cap;

    /* Number of pages in a block */
    rc = flGetCap(&cap);
    if (rc != IOS_ERROR_OK) {
        printf("Failed to get flash cap, rc=%d\n", rc);
        goto __copyPageToBlock_out;
    }
    numPagesInBlock = 1 << (cap.erasableBlockSzShift - cap.pageSzShift);
    pageSz = 1 << cap.pageSzShift;

    /* Erase the destination block */
    rc = flErase(dstBlock <<
            (cap.erasableBlockSzShift - FL_LOGI_BLOCK_SIZE_SHIFT));
    if (rc != IOS_ERROR_OK) {
        printf("Failed to erase destination block %d, rc=%d\n", dstBlock, rc);
        goto __copyPageToBlock_out;
    }

    /* Read the source page for comparison */
    rc = flReadPage(srcPage, buf, NULL, 1);
    if ((rc != IOS_ERROR_OK) && (rc != IOS_ERROR_ECC)) {
        printf("Failed to read source page %d\n", srcPage);
        goto __copyPageToBlock_out;
    }
    rc = IOS_ERROR_OK;

    /* Copy the source page to every page in the destination block */
    for (page = 0; page < numPagesInBlock; page++) {
        dstPage = (dstBlock * numPagesInBlock) + page;

        rc = flCopyPage(srcPage, dstPage);
        if (rc != IOS_ERROR_OK) {
            printf("Failed to copy from page %d to page %d, rc=%d\n",
                        srcPage, dstPage, rc);
            goto __copyPageToBlock_out;
        }

        /* Check the content of the destination page */
        rc = flReadPage(dstPage, buf + (2 * pageSz), NULL, 1);
        if ((rc != IOS_ERROR_OK) && (rc != IOS_ERROR_ECC)) {
            printf("Failed to read destination page %d, rc=%d\n", dstPage, rc);
            goto __copyPageToBlock_out;
        }
        rc = IOS_ERROR_OK;

        /* Check the content of the destination page */
        if (memcmp(buf, buf + (2 * pageSz), pageSz) != 0) {
            printf("Copy data check failed between page %d and %d\n");
            rc = IOS_ERROR_BADBLOCK;
            goto __copyPageToBlock_out;
        }
    }

__copyPageToBlock_out:

    return (rc);
}


s32
copyTest(char *args, char *d)
{
    s32         rc = 0;
    u32         srcBlock, dstBlock, numPagesInBlock;
    u32         j, page, pageSz, cycle = 0;
    FLDevCap    cap;

    /* Randomly pick the source and destination flash blocks */
    srcBlock = 569;
    dstBlock = 3300;

    /* Number of pages in a block */
    rc = flGetCap(&cap);
    if (rc != IOS_ERROR_OK) {
        printf("Failed to get flash cap, rc=%d\n", rc);
        goto copyTest_out;
    }
    numPagesInBlock = 1 << (cap.erasableBlockSzShift - cap.pageSzShift);
    pageSz = 1 << cap.pageSzShift;

    printf("Start copy test\n");

    while (1) {
        /* Erase the source block before writing */
        rc = flErase(srcBlock <<
                (cap.erasableBlockSzShift - FL_LOGI_BLOCK_SIZE_SHIFT));
        if (rc != IOS_ERROR_OK) {
            printf("Failed to erase source block in cycle %d, rc=%d\n",
                        cycle, rc);
            goto copyTest_out;
        }

        /* Fill the source block with random data */
        for (page = 0; page < numPagesInBlock; page++) {
            for (j = 0; j < pageSz; j++) {
                buf[j] = (u8) (((j + 276) * page * cycle) - 778);
            }

            rc = flWritePage(((srcBlock * numPagesInBlock) + page), buf, NULL,
                            (page != (numPagesInBlock - 1)), 1);
            if (rc != IOS_ERROR_OK) {
                printf("Failed to write to page %d in cycle %d, rc=%d\n",
                            page, cycle, rc);
                goto copyTest_out;
            }
        }

        /* Copy and check */
        for (page = 0; page < numPagesInBlock; page++) {
            rc = __copyPageToBlock((srcBlock * numPagesInBlock) + page,
                                dstBlock + page);
            if (rc != IOS_ERROR_OK) {
                printf("Failed to copy page %d to block %d in cycle %d,"
                    " rc = %d\n",  (srcBlock * numPagesInBlock) + page,
                    dstBlock + page, cycle, rc);
                goto copyTest_out;
            }
        }

        cycle++;
        if ((cycle % 10) == 0) {
            printf("Copy test completed %d cycles\n", cycle);
        }
    }
    
copyTest_out:

    if (rc < 0) {
        printf("copyTest failed with rc=%d\n", rc);
    }

    return (rc);
}


s32
eccTest(char *args, char *d)
{
    s32         rc = 0;
    u32         page, i, pageSz, byte, bit;
    char        *ptr;
    FLDevCap    cap;

    /* Get the page to test */
    if (getNextToken(&ptr, &args) == 0) {
        rc = -1;
        goto eccTest_out;
    }
    page = asciiToInt(ptr);

    /* Get the page size */
    rc = flGetCap(&cap);
    if (rc != IOS_ERROR_OK) {
        printf("Failed to get flash cap, rc=%d\n", rc);
        goto eccTest_out;
    }
    pageSz = 1 << cap.pageSzShift;

    printf("Test page %d\n", page);

    /* Read out the page without ECC */
    rc = flReadPage(page, buf, NULL, 0);
    if (rc != IOS_ERROR_OK) {
        printf("Page read failed, rc=%d\n", rc);
        goto eccTest_out;
    }

    /* Change a 1-bit to 0 */
    i = 100;
    while (i-- > 0) {
        /* Randomly pick a bit location to change */
        byte = (IO_READ(SYS_TIMER_REG) * i) % pageSz;
        bit = (IO_READ(SYS_TIMER_REG) * i) % 8;

        if ((buf[byte] & (1 << bit)) != 0) {
            buf[byte] &= ~(1 << bit);
            printf("Modified byte %d, bit %d\n", byte, bit);
            break;
        }
    }

    if (i == 0) {
        printf("Failed to find a 1-bit in 100 tries\n");
        rc = IOS_ERROR_INVALID;
        goto eccTest_out;
    }

    /* Write the page back */
    rc = flWritePage(page, buf, NULL, 0, 0);
    if (rc != IOS_ERROR_OK) {
        printf("Failed to write back page %d, rc=%d\n", page, rc);
        goto eccTest_out;
    }

    /* Read the page back to verify single-bit ECC error */
    rc = flReadPage(page, buf, NULL, 1);
    if (rc != IOS_ERROR_ECC) {
        printf("Failed to detect ECC error, rc=%d\n", rc);
        if (rc == IOS_ERROR_OK) {
            rc = IOS_ERROR_UNKNOWN;
        }
        goto eccTest_out;
    }
    rc = IOS_ERROR_OK;

eccTest_out:

    if (rc < 0) {
        printf("eccTest failed with rc=%d\n", rc);
    }

    return (rc);
}
