/*
 * $Id: toflash2.c,v 1.6 2006/06/07 18:14:35 wheeler Exp $
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>


#define ECC_UNIT       512
#define PAGE_SIZE      2048
#define SPARE_SIZE     64
#define MAX_PAGES      64
#define MAX_BAD_BLOCKS 16
#define INVAL_BLOCKNO  -1

#define bit(c, n) ((c & (1 << n)) >> n)

/*
 * computeECC
 *
 * Compute the ECC for a 512 byte block of data.
 */
unsigned int
computeECC(unsigned char *indata)
{
    unsigned char data[512];
    unsigned int ecc = 0, bits[8], allBits, parity[12], parity_p[12];
    int count, bitcount, parityCount;

    /*
     * This swizzling of the input data is necessary because the NNGC
     * system is big-endian.
     */
    {
        int i;

        for (i = 0; i < ECC_UNIT; i += 4) {
            data[i] = indata[i+3];
            data[i+1] = indata[i+2];
            data[i+2] = indata[i+1];
            data[i+3] = indata[i];
        }
    }

    memset (&bits[0], 0, sizeof (bits));
    memset (&parity[0], 0, sizeof (parity));
    memset (&parity_p[0], 0, sizeof (parity_p));

    for (count = 0; count < ECC_UNIT; count++) {
        for (bitcount = 0; bitcount < 8; bitcount++) {
            bits[bitcount] = bit(data[count], bitcount);
        }
        allBits = bits[0] ^ bits[1] ^ bits[2] ^ bits[3] ^ bits[4] ^ bits[5] ^ bits[6] ^ bits[7];

        parity[0] = parity[0] ^ bits[1] ^ bits[3] ^ bits[5] ^ bits[7];
        parity_p[0] = parity_p[0] ^ bits[0] ^ bits[2] ^ bits[4] ^ bits[6];
        parity[1] = parity[1] ^ bits[2] ^ bits[3] ^ bits[6] ^ bits[7];
        parity_p[1] = parity_p[1] ^ bits[0] ^ bits[1] ^ bits[4] ^ bits[5];
        parity[2] = parity[2] ^ bits[4] ^ bits[5] ^ bits[6] ^ bits[7];
        parity_p[2] = parity_p[2] ^ bits[0] ^ bits[1] ^ bits[2] ^ bits[3];

        for (parityCount = 3; parityCount < 12; parityCount++) {
            if ((count >> (parityCount - 3)) & 1) {
                parity[parityCount] = parity[parityCount] ^ allBits;
            } else {
                parity_p[parityCount] = parity_p[parityCount] ^ allBits;
            }
        }
    }

    ecc = 0;
    for (count = 0; count < 12; count++) {
        ecc = ecc | ((parity[count] & 0x1) << (16 + count)) 
            | ((parity_p[count] & 0x1) << count);
    }

    /*
     * This swizzling of the output ECC is necessary because the NNGC
     * system is big-endian.
     */
    ecc = ((ecc & 0xff000000) >> 24) 
        | ((ecc & 0x00ff0000) >> 8) 
        | ((ecc & 0x0000ff00) << 8) 
        | ((ecc & 0x000000ff) << 24);

    return ecc;
}

/*
 * write_bad_block
 *
 * Write out a bad block, which consists of MAX_PAGES pages with zeroed
 * data and spare areas.
 */
void
write_bad_block (FILE *outfile, int block)
{
    int page;
    unsigned char data[PAGE_SIZE];
    unsigned int spare[SPARE_SIZE/sizeof(unsigned int)];
    int status;

    memset (&data[0], 0, sizeof (data));
    memset (&spare[0], 0, sizeof (spare));

    for (page = 0; page < MAX_PAGES; page++) {
        status = fwrite (&data[0], sizeof (data), 1, outfile);
        if (status != 1) {
            perror ("fwrite");
            exit (1);
        }
        spare[1] = block << 16 | page;
        status = fwrite (&spare[0], sizeof (spare), 1, outfile);
        if (status != 1) {
            perror ("fwrite");
            exit (1);
        }
        printf ("%s: block %d page %d\n",
               __FUNCTION__, block, page);
    }

    return;
}

/*
 * is_bad
 *
 * Is a block number in the bad block list?
 */
int
is_bad (int *bad_block_list, int block)
{
    int i;

    if (bad_block_list) {
        for (i = 0; 
             (i < MAX_BAD_BLOCKS) && (bad_block_list[i] != INVAL_BLOCKNO); i++) {
            if (bad_block_list[i] == block) {
                fprintf (stderr, "%s: bad_block[%d] = %d\n",
                         __FUNCTION__, i, bad_block_list[i]);
                return 1;
            }
        }
    }

    return 0;
}

/*
 * write_header
 *
 * If we are asked to, write a preliminary page containing the boot2
 * header.
 */
void
write_header (FILE *outfile, int filesize)
{
    unsigned char data[PAGE_SIZE];
    unsigned int spare[SPARE_SIZE/sizeof(unsigned int)];
    unsigned int status;
    int i, j, page = -1;

    memset (&data[0], 0, sizeof(data));
    *(int *)(&data[0]) = filesize;

    i = 12;
    memset (&spare[0], 0, sizeof (spare));
    for (j = 0; j < PAGE_SIZE; j += ECC_UNIT) {
        spare[i] = computeECC (&data[j]);
        printf ("%s: page %d spare[%d] = 0x%08x\n",
                __FUNCTION__, page, i, spare[i]);
        i++;
    }
    i = 0;
    spare[i] = 0xffffffff;
    status = fwrite (&data[0], sizeof (data), 1, outfile);
    if (status != 1) {
        perror ("fwrite");
        exit (1);
    }
    status = fwrite (&spare[0], sizeof (spare), 1, outfile);
    if (status != 1) {
        perror ("fwrite");
        exit (1);
    }

    return;
}

/*
 * read_data
 *
 * Read the input data for one 2048 byte page, compute the ECC values
 * for each of four sub-pages per page, and write the ECC values to
 * the spare area.  Then write out the data, followed by the spare
 * area, for the page.  Repeat for each page.
 */
void
read_data (FILE *infile, FILE *outfile, int errors, 
           int fill_block, int bad_block, int *bad_block_list, 
           int header, int filesize)
{
    unsigned char data[PAGE_SIZE];
    unsigned int spare[SPARE_SIZE/sizeof(unsigned int)];
    unsigned int status;
    int i, j, k, l, page = 0, block = 0, eof = 0;

    while (1) {
        memset (&data[0], 0, sizeof (data));
        status = fread (&data[0], sizeof (char), sizeof (data), infile);
        if (status != sizeof(data)) {
            if (status == 0) {
                /*
                 * zero read.
                 */
                goto fill;
            }
            if (feof(infile)) {
                /*
                 * short read.
                 */
                eof = 1;
            }
        }
        /*
         * At the first page of each block, check if that block has
         * been marked bad, and if so, output a bad block of MAX_PAGES zeroed
         * pages, and update the block number.
         */
        if (page == 0) {
            while (is_bad(bad_block_list, block)) {
                fprintf (stderr, "%s: block %d is bad\n",
                         __FUNCTION__, block);
                write_bad_block (outfile, block);
                block++;
            }
        }
        if (page == 0) {
            if (header) {
                write_header (outfile, filesize);
                page++;
            }
        }
        i = 12;
        memset (&spare[0], 0, sizeof (spare));
        for (j = 0; j < PAGE_SIZE; j += ECC_UNIT) {
            spare[i] = computeECC (&data[j]);
            printf ("%s: block %d page %d spare[%d] = 0x%08x\n",
                    __FUNCTION__, block, page, i, spare[i]);
            i++;
        }

        /*
         * If we were asked to, construct a bad block table, which
         * consists of placing a pattern in the first location of
         * the spare area of the first two pages of a good block.
         * The absence of this pattern indicates that the entire
         * block is bad, and should be skipped.
         */
        if (bad_block) {
            if ((page == 0) || (page == 1)) {
                i = 0;
                spare[i] = 0xffffffff;
                printf ("%s: block %d page %d spare[%d] = 0x%08x\n",
                        __FUNCTION__, block, page, i, spare[i]);
            }
        }
        spare[1] = block << 16 | page;
        if (errors != 0) {
            for (k = 0; k < errors; k++) {
                l = random() & (PAGE_SIZE - 1);
                data[l] = data[l] ^ (1 << (random() & 0x7));
            }
        }
        fwrite (&data[0], sizeof (data), 1, outfile);
        fwrite (&spare[0], sizeof (spare), 1, outfile);
        page++;
        if (page == MAX_PAGES) {
            if (eof) {
                /*
                 * The input file was exactly one block long,
                 * so no need to fill to end.
                 */
                return;
            }
            block++;
            page = 0;
        }
        if (eof) {
            fprintf (stderr, "Found eof on input %d read\n",
                     status);
            goto fill;
        }
    }

 fill:
    if (fill_block) {
        while (page < MAX_PAGES) {
            memset (&data[0], 0, sizeof (data));
            i = 12;
            memset (&spare[0], 0, sizeof (spare));
            for (j = 0; j < PAGE_SIZE; j += ECC_UNIT) {
                spare[i] = computeECC (&data[j]);
                printf ("%s: block %d page %d spare[%d] = 0x%08x\n",
                        __FUNCTION__, block, page, i, spare[i]);
                i++;
            }
            if (errors != 0) {
                for (k = 0; k < errors; k++) {
                    l = random() & (PAGE_SIZE - 1);
                    data[l] = data[l] ^ (1 << (random() & 0x7));
                }
            }
            fwrite (&data[0], sizeof (data), 1, outfile);
            fwrite (&spare[0], sizeof (spare), 1, outfile);
            page++;
        }
    }
}

/*
 * fsize
 *
 * Find the size of a file.
 */
int
fsize (char *file_name)
{
    struct stat buf;
    int status;

    memset (&buf, 0, sizeof (struct stat));
    status = stat(file_name, &buf);
    if (status != 0) {
        perror ("stat");
        exit (1);
    }

    return buf.st_size;
}

/*
 * usage
 */
void
usage (char **argv)
{
    fprintf (stderr, "usage: %s [-s|-d|-f|-b|-h] file1 file2\n", 
             argv[0]);
    fprintf (stderr, "\t-s    - introduce a single bit error per page\n");
    fprintf (stderr, "\t-d    - introduce a double bit error per page\n");
    fprintf (stderr, "\t-f    - fill out to the end of block (64 pages)\n");
    fprintf (stderr, "\t-b    - introduce a bad block table\n");
    fprintf (stderr, "\t-B    - add a list of bad blocks\n");
    fprintf (stderr, "\t-h    - prepend a header page to the executable\n");
    fprintf (stderr, "\t-i    - write output in Intel hex format\n");
    fprintf (stderr, "\t-F nn - force a header size which is not the input file size\n");
    exit (1);
}

/*
 * This version of 'to_flash2' is a modification of the original
 * 'to_flash' and could eventually be folded back into it.  
 *
 * The 'to_flash' command takes an executable, and for each page of
 * 2048 bytes it creates a spare area of 64 bytes in which it stores
 * four ECC values, each ECC value computed from a sub-page of 512
 * bytes.
 *
 * The 'to_flash2' command
 *
 * The algorithm is:
 *
 *  + Use fseek(3)/ftell(3) to find out the size of the executable to
 *    be loaded.
 *
 *  + Write the program size in the fist bad block area.
 *
 *  + If the command line arguments tell us to mark a page/block as
 *    bad, store that information.
 *
 *  + For the first two pages of a good block, write a valid bad block
 *    table.   Fill remainder of these two pages with data, followed
 *    by a 64-byte spare area.
 *
 *  + For any bad blocks write an invalid bad block table.
 *
 *  + For pages after the first two, in a good block, write 2048 bytes
 *    of data, followed by a 64-byte spare area.
 *
 * Command line arguments.
 *
 *  first:  input file one
 *  second: input file two.
 *
 *  -s: introduce a single bit error per page.
 *  -d: introduce a double bit error per page.
 *  -f: extend the data to the end of the block.
 *  -b: construct a bad block table for each block.
 *  -B: add a list of bad blocks
 *  -h: prepend a header page to the executable
 *  -i: write output in Intel hex format.
 */
int
main (int argc, char **argv)
{
    char *infilename = "", *outfilename = "";
    FILE *infile, *outfile;
    int errors = 0, i, j, valid, fill_block = 0, bad_block = 0, header = 0;
    int filesize = 0, forced_filesize = 0;
    int bad_blocks = 0, bad_block_no, *bad_block_list = NULL;

    if (argc > 2) {
        infilename = argv[1];
        printf ("%s\n", infilename);
        if ((infile = fopen (infilename, "r")) == NULL) {
            perror ("open");
            exit (1);
        }
        outfilename = argv[2];
        printf ("%s\n", outfilename);
        if ((outfile = fopen (outfilename, "w")) == NULL) {
            perror ("open");
            exit (1);
        }
        if (argc > 3) {
            for (i = 3; i < argc; i++) {
                valid = 0;
                /*
                 * If we are constructing a bad block list, assume
                 * that and option that does not begin with '-' is a
                 * block number and one that does begin with '-' ends
                 * the list.  In the latter case we do not set valid
                 * to 1 and we drop through to the rest of option
                 * processing.
                 */
                if (bad_blocks == 1) {
                    if (argv[i][0] != '-') {
                        bad_block_no = strtol (argv[i], NULL, 10);
                        for (j = 0; j < MAX_BAD_BLOCKS; j++) {
                            if (bad_block_list[j] == INVAL_BLOCKNO) {
                                bad_block_list[j] = bad_block_no;
                                valid = 1;
                                break;
                            }
                        }
                        if (valid == 0) {
                            fprintf (stderr, "Too many bad blocks\n");
                        }
                    } else {
                        bad_blocks = 0;
                    }
                }
                /*
                 * Insert single-bit errors per page.
                 */
                if (!strcmp(argv[i], "-s")) {
                    errors = 1;
                    valid=1;
                }
                /*
                 * Insert double-bit errors per page.
                 */
                if (!strcmp(argv[i], "-d")) {
                    errors = 2;
                    valid=1;
                }
                /*
                 * Fill the current block to the end (MAX_PAGES pages)
                 */
                if (!strcmp(argv[i], "-f")) {
                    fill_block = 1;
                    valid=1;
                }
                /*
                 * Construct a bad-block table in the spare area of
                 * the first two pages of each block.  If the '-B'
                 * option is not used, all blocks are assumed to be
                 * good.
                 */
                if (!strcmp(argv[i], "-b")) {
                    bad_block = 1;
                    valid=1;
                }
                /*
                 * Construct a list of bad blocks.  These blocks will
                 * be skipped when constructing the flash image.  This
                 * also implicitly sets the '-b' flag.
                 */
                if (!strcmp(argv[i], "-B")) {
                    bad_block = 1;
                    valid=1;
                    if (bad_block_list == NULL) {
                        bad_block_list = 
                            (int *) malloc (MAX_BAD_BLOCKS * sizeof (int));
                        for (j = 0; j < MAX_BAD_BLOCKS; j++) {
                            bad_block_list[j] = INVAL_BLOCKNO;
                        }
                    }
                    /*
                     * Indicate that we are constructing a bad block
                     * list.
                     */
                    bad_blocks = 1;
                }
                /*
                 * Prepend the executable pages with a header page
                 * that contains the size of the executable image.
                 */
                if (!strcmp(argv[i], "-h")) {
                    header = 1;
                    valid=1;
                }
                /*
                 * Allow the user to force a header size which is not 
                 * size of the input file.
                 */
                if (!strcmp(argv[i], "-F")) {
                    i++;
                    forced_filesize=strtol(argv[i], NULL, 10);
                    valid=1;
               }
                /*
                 * Just print out the usage message.
                 */
                if (!strcmp(argv[i], "-?")) {
                    usage (argv);
                }
                /*
                 * If we got this far, we saw no valid options.
                 */
                if (valid == 0) {
                    fprintf (stderr, "Bad argument '%s'\n", argv[i]);
                    usage (argv);
                }
            }
        }
    } else {
        usage (argv);
        exit (1);
    }

    if (header) {
        if (forced_filesize == 0) {
            filesize = fsize (infilename);
        } else {
            filesize = forced_filesize;
        }
    }

    read_data (infile, outfile, errors, fill_block, bad_block, bad_block_list, header, filesize);
    
    exit (0);
}
