/******************************************************************************/
/*                                                                            */
/*  Copyright (C), 1995-2006, msystems Ltd. All rights reserved.              */
/*                                                                            */
/*  Redistribution and use in source and binary forms, with or without        */
/*  modification, are permitted provided that the following conditions are    */
/*  met:                                                                      */
/*  1. Redistributions of source code must retain the above copyright notice, */
/*     this list of conditions and the following disclaimer.                  */
/*  2. Redistributions in binary form must reproduce the above copyright      */
/*     notice, this list of conditions and the following disclaimer in the    */
/*     documentation and/or other materials provided with the distribution.   */
/*  3. Neither the name of msystems nor the names of its contributors may be  */
/*     used to endorse or promote products derived from this software without */
/*     specific prior written permission.                                     */
/*                                                                            */
/*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       */
/*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED */
/*  TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR             */
/*  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT      */
/*  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,     */
/*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED  */
/*  TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR    */
/*  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    */
/*  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      */
/*  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        */
/*  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.              */
/*                                                                            */
/******************************************************************************/

/*********************************************************************************** 
 *                                                                                 * 
 *   This utility program updates firmware in mDOC H3 devices. It takes two        * 
 *   parameters: name of mDOC's device file (for example /dev/tffsa), and name     * 
 *   of mDOC firmware file (for example, "image.enc-0050"). Here is an example:    * 
 *                                                                                 * 
 *      doch-firmware /dev/tffsa image.enc-0050                                    * 
 *                                                                                 * 
 ***********************************************************************************/


/*
 * $Log$
 */


#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/mount.h>
#include <errno.h>
#include <assert.h>
#include "tffsioct.h"




#ifndef FL_SECTOR_SIZE
# define FL_SECTOR_SIZE 512
#endif



/*
 * Calculate simple checksum on buffer 'buf' containing 'buf_size' bytes.
 * We expect 'buf_size' to be multiple of 4.
 */
static 
unsigned long  chksum (unsigned long * buf, int buf_size)
{
    register unsigned long s = 0;
    register int           n;

    assert ((buf != NULL) && ((buf_size % sizeof(long)) == 0));

    for (n = ((buf_size / sizeof(long)) - 1); n >= 0; n--)
        s ^= buf[n];

    return s;
}




/*
 * Write firmware to DiskOnChip via IOCTL call to DiskOnChip driver.
 * We expect 'buf_size' to be multiple of sector size.
 */
static
int write_firmware (int fd, void * buf, int buf_size)
{
    flIOctlRecord     ioctl_record;
    flInputLnxRecord  in;
    flOutputLnxRecord out;
    flAtaPassthrough  ata_passthrough;
    int               rc;

    assert (buf != NULL);
    assert ((buf_size % FL_SECTOR_SIZE) == 0);   /* must be multiple of sector size */
    assert ((buf_size / FL_SECTOR_SIZE) <= 256); /* max 256 sectors at once */

    ioctl_record.inputRecord  = &in;
    ioctl_record.outputRecord = &out;

    in.command = 5;  /* ATA pass through command */
    in.data    = (unsigned long) &ata_passthrough;

    out.data   = (unsigned long) NULL;

    memset (&ata_passthrough, 0, sizeof(ata_passthrough));
    ata_passthrough.socketNum              = 0;
    ata_passthrough.userBuff               = buf;
    ata_passthrough.userBuffSize           = buf_size;
    ata_passthrough.secNum                 = (buf_size / FL_SECTOR_SIZE);
    ata_passthrough.passThruOP             = DOCH_PASSTHRU_DATA_OUT;
    ata_passthrough.in_regs.bCommandStatus = DOCH_DOWNLOAD_MICROCODE;
    ata_passthrough.in_regs.bFeaturesError = DOCH_DLMCODE_DOWNLOAD_AND_SAVE;
    ata_passthrough.in_regs.bSectorCount   = (unsigned char) (buf_size / FL_SECTOR_SIZE);
    ata_passthrough.in_regs.bSectorNumber  = (unsigned char)((buf_size / FL_SECTOR_SIZE) >> 8);

    rc = ioctl (fd, FL_IOCTL_LNX, &ioctl_record);
    if ((rc != 0) || (ata_passthrough.status != 0))
    {
        fprintf (stderr, "Error %d writing DiskOnChip firmware\n", (int)out.status);
        rc = -1;
    }
    else
        fprintf (stdout, "Success writing DiskOnChip firmware\n");

    return rc;
}




/*
 * Main
 */
int main ( int argc, char * argv[] )
{
    int    fd;
    void * buf;
    int    buf_size;
    int    rc = -1;

    /* arg check */
    if ((argc != 3) || (argv[1] == NULL) || (strlen(argv[1]) == 0) ||
                       (argv[2] == NULL) || (strlen(argv[2]) == 0))
    {
        fprintf (stderr, "Usage:   doch-firmware <device-file-name> <firmware_file>\n");
        fprintf (stderr, "Example: doch-firmware /dev/tffsa image.enc-0050\n");
        exit (-1);
    }

    /* open firmware file */
    if((fd = open(argv[2], O_RDONLY)) == -1)
        { perror ("Can't open firmware file"); exit (-1); }

    /* find out size of firmware file */
    if ((buf_size = lseek(fd, 0, SEEK_END)) == -1)
        { perror ("Can't determine size of firmware file"); exit (-1); }

    /* set file pointer back to start of firmware file */
    if( lseek(fd, 0, SEEK_SET) != 0)
        { perror ("Can't rewind firmware file"); exit (-1); }

    /* allocate buffer to hold firmware file's contents, and clear it */
    if ((buf = calloc(buf_size + FL_SECTOR_SIZE, sizeof(char))) == NULL)
        { perror ("Can't allocate memory"); exit (-1); }

    /* read firmware file into the buffer */
    if( read(fd, buf, buf_size) != buf_size )
        { perror ("Can't read firmware file"); exit (-1); }

    /* close firmware file */
    close (fd);

    /* round up 'buf_size' to multiple of FL_SECTOR_SIZE */
    buf_size = (((buf_size - 1) / FL_SECTOR_SIZE) + 1) * FL_SECTOR_SIZE;

    if ((buf_size / FL_SECTOR_SIZE) > 256)
        { perror ("Firmware file too large");  free (buf);  exit (-1); }

    /* calculate checksum on the buffer */					     
    fprintf (stdout, "Firmware file checksum 0x%lx\n", chksum(buf, buf_size));

    /* open device file */
    if((fd = open(argv[1], O_RDWR)) == -1)
        { perror ("Can't open device");  free (buf);  exit (-1); }

    /* issue IOCTL to device */
    rc = write_firmware (fd, buf, buf_size);

    /* close device file */
    close (fd);

    /* clear and free allocated buffer */
    memset (buf, 0, buf_size);
    free (buf);

    fprintf (stdout, "Reset DiskOnChip to activate new firmware\n");

    exit (rc);
}
