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


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




#define ALLOW_FORMATTING
#undef  ALLOW_BDK
#define ALLOW_HW_PROTECTION


/* make TrueFFS ahndle out of socket and disk ## */
#define mk_tffs_handle(socNo,diskNo)  (((unsigned short)(socNo) & 0xf) |          \
                                       (((unsigned int)(diskNo) << 4) & 0xf0))


/*
 * static routines
 */

static int fl_ioctl_get_info (int fd);
static int fl_ioctl_defragment (int fd);
static int fl_ioctl_customer_id (int fd);

#ifdef  ALLOW_BDK
  static int fl_ioctl_bdk_operation (int fd);
#endif

static int hdio_getgeo (int fd);

#ifdef ALLOW_FORMATTING
  static int fl_ioctl_erase_bd (int fd);
  static int fl_ioctl_flash_format (int fd);
  static int fl_ioctl_flash_unformat (int fd);
  static int fl_ioctl_mount_volume (int fd);
#endif

#ifdef ALLOW_HW_PROTECTION
  static int fl_ioctl_hw_protection (int fd, int ioctl_opcode);
#endif




int main ( int argc, char * argv[] )
{
    int ioctl_opcode;
    int flags;
    int fd;
    int rc = -1;

    /* check if devce name and IOCTL opcode are specified, and get IOCTL opcode */
    if ((argc < 3) || (sscanf(argv[2], "%d", &ioctl_opcode) != 1))
    {
        fprintf (stderr, "Usage:   ioctl-example <device-file-name> <ioctl-code>\n");
        fprintf (stderr, "Example: ioctl-example /dev/tffsa 14\n");
        fprintf (stderr, "Accepted values for <ioctl-code>:\n");
        fprintf (stderr, "    %d for FL_IOCTL_CUSTOMER_ID\n",    FL_IOCTL_CUSTOMER_ID);
        fprintf (stderr, "    %d for FL_IOCTL_DEFRAGMENT\n",     FL_IOCTL_DEFRAGMENT);
        fprintf (stderr, "    %d for FL_IOCTL_GET_INFO\n",       FL_IOCTL_GET_INFO);
#ifdef ALLOW_BDK
        fprintf (stderr, "    %d for FL_IOCTL_BDK_OPERATION\n",  FL_IOCTL_BDK_OPERATION);
#endif
#ifdef ALLOW_FORMATTING
        fprintf (stderr, "    %d for FL_IOCTL_MOUNT_VOLUME\n",   FL_IOCTL_MOUNT_VOLUME);
        fprintf (stderr, "    %d for FL_IOCTL_ERASE_BD\n",       FL_IOCTL_ERASE_BD);
        fprintf (stderr, "    %d for FL_IOCTL_FLASH_FORMAT\n",   FL_IOCTL_FLASH_FORMAT);
        fprintf (stderr, "    %d for FL_IOCTL_FLASH_UNFORMAT\n", FL_IOCTL_FLASH_UNFORMAT);
#endif
#ifdef ALLOW_HW_PROTECTION
        fprintf (stderr, "    %d for FL_IOCTL_BDTL_HW_PROTECTION\n", FL_IOCTL_BDTL_HW_PROTECTION);
#endif
        fprintf (stderr, "    %d for HDIO_GETGEO\n", 0x0301 /* HDIO_GETGEO */);
        exit (-1);
    }

    /* open device */
    flags = ((ioctl_opcode == FL_IOCTL_GET_INFO) ? O_RDONLY : O_RDWR);
    if((fd = open(argv[1], flags)) == -1)
    {
        perror ("Can't open device");
        exit (-1);
    }

    /* issue IOCTL to device */
    switch (ioctl_opcode)
    {
        case FL_IOCTL_CUSTOMER_ID:
            rc = fl_ioctl_customer_id (fd);
            break;

        case FL_IOCTL_DEFRAGMENT:
            rc = fl_ioctl_defragment (fd);
            break;

        case FL_IOCTL_MOUNT_VOLUME:
            rc = fl_ioctl_mount_volume (fd);
            break;

        case FL_IOCTL_GET_INFO:
            rc = fl_ioctl_get_info (fd);
            break;

#ifdef ALLOW_BDK
        case FL_IOCTL_BDK_OPERATION:
            rc = fl_ioctl_bdk_operation (fd);
            break;
#endif

#ifdef ALLOW_FORMATTING
        case FL_IOCTL_ERASE_BD:
            rc = fl_ioctl_erase_bd (fd);
            break;

        case FL_IOCTL_FLASH_FORMAT:
            rc = fl_ioctl_flash_format (fd);
            break;

        case FL_IOCTL_FLASH_UNFORMAT:
            rc = fl_ioctl_flash_unformat (fd);
            break;
#endif

#ifdef ALLOW_HW_PROTECTION
        case FL_IOCTL_BDTL_HW_PROTECTION:
            rc = fl_ioctl_hw_protection (fd, ioctl_opcode);
            break;
#endif

        case 0x0301: /* HDIO_GETGEO */
            rc = hdio_getgeo (fd);
            break;

    }

    close (fd);

    exit (rc);
}




static
int fl_ioctl_customer_id (int fd)
{
    flIOctlRecord      ioctl_data;
    flCustomerIdOutput out;
    int                rc;

    ioctl_data.inputRecord  = NULL; /* no input record for this IOCTL */
    ioctl_data.outputRecord = &out;
    rc = ioctl (fd, FL_IOCTL_CUSTOMER_ID, &ioctl_data);
    if ((rc != 0) || (out.status != flOK))
        fprintf (stderr, "FL_IOCTL_CUSTOMER_ID IOCTL failed, error %d\n", out.status);
    else
        fprintf (stdout, "SUCCESS getting customer ID: 0x%x 0x%x 0x%x 0x%x\n",
                        out.id[0], out.id[1], out.id[2], out.id[3]);
    return rc;
}




static
int fl_ioctl_defragment (int fd)
{
    flIOctlRecord  ioctl_data;
    flDefragInput  in;
    flDefragOutput out;
    int            rc;

    in.requiredNoOfSectors = -1;

    ioctl_data.inputRecord  = &in;
    ioctl_data.outputRecord = &out;
    rc = ioctl (fd, FL_IOCTL_DEFRAGMENT, &ioctl_data);
    if ((rc == 0) && (out.status == flOK))
        fprintf (stdout, "free sectors after defragmentation: %ld\n", out.actualNoOfSectors);

    return rc;
}




static
int fl_ioctl_get_info (int fd)
{
    flIOctlRecord    ioctl_data;
    flDiskInfoOutput out;
    int              rc;

    ioctl_data.inputRecord  = NULL;  /* no input record for this IOCTL */
    ioctl_data.outputRecord = &out;
    rc = ioctl (fd, FL_IOCTL_GET_INFO, &ioctl_data);
    if ((rc != 0) || (out.status != flOK))
        fprintf (stderr, "FL_IOCTL_GET_INFO failed %d\n", out.status);
    else
        fprintf (stdout, "FL_IOCTL_GET_INFO reports %ld sectors\n", out.info.logicalSectors);

    return rc;
}




#ifdef ALLOW_FORMATTING

static
int fl_ioctl_mount_volume (int fd)
{
    flIOctlRecord        ioctl_data;
    flMountInput         in;
    flOutputStatusRecord out;
    int                  rc;

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

#if 1  
    in.type = FL_DISMOUNT;    /* unmount disk */
#else  
    in.type = FL_MOUNT;       /* re-mount disk */
#endif

    rc = ioctl (fd, FL_IOCTL_MOUNT_VOLUME, &ioctl_data);
    if ((rc != 0) || (out.status != flOK))
        fprintf (stderr, "FL_IOCTL_MOUNT_VOLUME failed %d\n", out.status);

    return rc;
}

#endif /* ALLOW_FORMATTING */




#ifdef ALLOW_FORMATTING

static
int fl_ioctl_erase_bd (int fd)
{
    flIOctlRecord ioctl_data;
    int           rc;

    /* unmount disk before formatting */
    {   flMountInput         in;
        flOutputStatusRecord out;

        in.type = FL_DISMOUNT;
        ioctl_data.inputRecord  = &in;
        ioctl_data.outputRecord = &out;
        rc = ioctl (fd, FL_IOCTL_MOUNT_VOLUME, &ioctl_data);
        if ((rc != 0) || (out.status != flOK))
            fprintf (stderr, "FL_IOCTL_MOUNT_VOLUME/FL_DISMOUNT failed %d\n", out.status);
    }

    /* re-format disk */
    {   flEraseBDInput       in;
        flOutputStatusRecord out;

        in.dwFlags = 0;
        ioctl_data.inputRecord  = &in;
        ioctl_data.outputRecord = &out;
        rc = ioctl (fd, FL_IOCTL_ERASE_BD, &ioctl_data);
        if ((rc != 0) || (out.status != flOK))
            fprintf (stderr, "FL_IOCTL_ERASE_BD failed %d\n", out.status);
    }

    /* re-mount disk */
    {   flMountInput         in;
        flOutputStatusRecord out;

        in.type = FL_MOUNT;
        ioctl_data.inputRecord  = &in;
        ioctl_data.outputRecord = &out;
        rc = ioctl (fd, FL_IOCTL_MOUNT_VOLUME, &ioctl_data);
        if ((rc != 0) || (out.status != flOK))
            fprintf (stderr, "FL_IOCTL_MOUNT_VOLUME/FL_MOUNT failed %d\n", out.status);
    }

    return rc;
}

#endif /* ALLOW_FORMATTING */




#ifdef ALLOW_FORMATTING

static
int fl_ioctl_flash_format (int fd)
{
    flIOctlRecord        ioctl_data;
    flOutputStatusRecord out;
    int                  rc;

    /* WARNING: You must send FL_IOCTL_MOUNT_VOLUME/FL_DISMOUNT call
     *          to all DiskOnChip disks (except for '/dev/tffsa') prior
     *          to calling this routine. You should not do that for
     *          /dev/tffsa - this routine must do it by itself.
     */

    /* send FL_IOCTL_MOUNT_VOLUME/FL_DISMOUNT call to '/dev/tffsa' */
    {   flMountInput in;

        in.type = FL_DISMOUNT;
        ioctl_data.inputRecord  = &in;
        ioctl_data.outputRecord = &out;
        rc = ioctl (fd, FL_IOCTL_MOUNT_VOLUME, &ioctl_data);
        if ((rc != 0) || (out.status != flOK))
            fprintf (stderr, "FL_IOCTL_MOUNT_VOLUME/FL_DISMOUNT failed %d\n", out.status);
    }

    /* format DiskOnChip */
    {   flFlashFormatInput           in;
        FormatParams3                fp3;
        BDTLPartitionFormatParams3   disks[16];  /* WARNING: Large data structure 1 */
        BinaryPartitionFormatParams3 bins[4];

        memset (&in,   0, sizeof(in));
        memset (&fp3,  0, sizeof(FormatParams3));
        memset (disks, 0, sizeof(disks));
        memset (bins,  0, sizeof(bins));

        in.fpPtr         = &fp3;
#if 1
        in.dwFormatFlags = TL_NORMAL_FORMAT;
#else
        /* If you intent on keeping some of BDTL partitions, uncomment
         * this section, and specify how many partitions you want to keep.
         */
        in.dwFormatFlags = TL_LEAVE_SOME_PARTITIONS;
        in.sdwNoOfKeeps  = 5;  /* keep this many partitions */
#endif

        fp3.progressCallback     = NULL;
        fp3.percentUse           = 95;
        fp3.BDTLPartitionInfo    = &disks[0];
        fp3.binaryPartitionInfo  = &bins[0];
        fp3.noOfBinaryPartitions = 0;
        fp3.noOfBDTLPartitions   = 0;

        /* specify size of 1-st DiskOnChip disk */
        disks[ fp3.noOfBDTLPartitions   ].length         = (40 * 0x100000);  /* disk size in bytes */
        disks[ fp3.noOfBDTLPartitions++ ].noOfSpareUnits = 3;
#if 0
        /* specify sizes of 2-nd .. 13-th DiskOnChip disk (if you need them) */
        disks[ fp3.noOfBDTLPartitions   ].length         = (20 * 0x100000);  /* 2-nd disk size in bytes */
        disks[ fp3.noOfBDTLPartitions++ ].noOfSpareUnits = 3;

        disks[ fp3.noOfBDTLPartitions   ].length         = (30 * 0x100000);  /* 3-rd disk size in bytes */
        disks[ fp3.noOfBDTLPartitions++ ].noOfSpareUnits = 3;

        disks[ fp3.noOfBDTLPartitions   ].length         = (40 * 0x100000);  /* 4-th disk size in bytes */
        disks[ fp3.noOfBDTLPartitions++ ].noOfSpareUnits = 3;

        disks[ fp3.noOfBDTLPartitions   ].length         = (50 * 0x100000);  /* 5-th disk size in bytes */
        disks[ fp3.noOfBDTLPartitions++ ].noOfSpareUnits = 3;

        disks[ fp3.noOfBDTLPartitions   ].length         = (60 * 0x100000);  /* 6-th disk size in bytes */
        disks[ fp3.noOfBDTLPartitions++ ].noOfSpareUnits = 3;

        disks[ fp3.noOfBDTLPartitions   ].length         = (70 * 0x100000);  /* 7-th disk size in bytes */
        disks[ fp3.noOfBDTLPartitions++ ].noOfSpareUnits = 3;

        disks[ fp3.noOfBDTLPartitions   ].length         = (80 * 0x100000);  /* 8-th disk size in bytes */
        disks[ fp3.noOfBDTLPartitions++ ].noOfSpareUnits = 3;

        disks[ fp3.noOfBDTLPartitions   ].length         = (90 * 0x100000);  /* 9-th disk size in bytes */
        disks[ fp3.noOfBDTLPartitions++ ].noOfSpareUnits = 3;

        disks[ fp3.noOfBDTLPartitions   ].length         = (50 * 0x100000);  /* 10-th disk size in bytes */
        disks[ fp3.noOfBDTLPartitions++ ].noOfSpareUnits = 3;

        disks[ fp3.noOfBDTLPartitions   ].length         = (50 * 0x100000);  /* 11-th disk size in bytes */
        disks[ fp3.noOfBDTLPartitions++ ].noOfSpareUnits = 3;

        disks[ fp3.noOfBDTLPartitions   ].length         = (50 * 0x100000);  /* 12-th disk size in bytes */
        disks[ fp3.noOfBDTLPartitions++ ].noOfSpareUnits = 3;

        disks[ fp3.noOfBDTLPartitions   ].length         = (50 * 0x100000);  /* 13-th disk size in bytes */
        disks[ fp3.noOfBDTLPartitions++ ].noOfSpareUnits = 3;
#endif

#if 1   /* specify size of last DiskOnChip disk (if you need it) */
        disks[ fp3.noOfBDTLPartitions   ].length         = 0;  /* take all remaing space on DiskOnChip */
        disks[ fp3.noOfBDTLPartitions++ ].noOfSpareUnits = 3;
#endif

#if 0
        /* specify size of the first binary partition */
        bins[fp3.noOfBinaryPartitions].length = (1 * 0x100000);   /* size in bytes */
        memcpy (bins[fp3.noOfBinaryPartitions].sign, "BIPO", 4);
        fp3.noOfBinaryPartitions++;

        /* specify size of the second binary partition */
        bins[fp3.noOfBinaryPartitions].length = (2 * 0x100000);   /* size in bytes */
        memcpy (bins[fp3.noOfBinaryPartitions].sign, "BIPO", 4);
        fp3.noOfBinaryPartitions++;
#endif

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

        rc = ioctl (fd, FL_IOCTL_FLASH_FORMAT, &ioctl_data);

        if ((rc != 0) || (out.status != flOK))
            fprintf (stderr, "FL_IOCTL_FLASH_FORMAT failed %d\n", out.status);
    }

    /* re-mount disk */
    {   flMountInput in;

        in.type = FL_MOUNT;
        ioctl_data.inputRecord  = &in;
        ioctl_data.outputRecord = &out;
        rc = ioctl (fd, FL_IOCTL_MOUNT_VOLUME, &ioctl_data);
        if ((rc != 0) || (out.status != flOK))
            fprintf (stderr, "FL_IOCTL_MOUNT_VOLUME/FL_MOUNT failed %d\n", out.status);
    }

    /* WARNING: You must kill DiskOnChip driver and reboot your system now ! */
    return rc;
}

#endif /* ALLOW_FORMATTING */




#ifdef ALLOW_FORMATTING

static
int fl_ioctl_flash_unformat (int fd)
{
    flIOctlRecord        ioctl_data;
    flOutputStatusRecord out;
    int                  rc;

    /* unmount disk before formatting */
    {   flMountInput in;

        in.type = FL_DISMOUNT;
        ioctl_data.inputRecord  = &in;
        ioctl_data.outputRecord = &out;
        rc = ioctl (fd, FL_IOCTL_MOUNT_VOLUME, &ioctl_data);
        if ((rc != 0) || (out.status != flOK))
            fprintf (stderr, "FL_IOCTL_MOUNT_VOLUME/FL_DISMOUNT failed %d\n", out.status);
    }

    {   flFlashUnformatInput in;

        in.dwFlags = 0;
        ioctl_data.inputRecord  = &in;
        ioctl_data.outputRecord = &out;
        rc = ioctl (fd, FL_IOCTL_FLASH_UNFORMAT, &ioctl_data);
        if ((rc != 0) || (out.status != flOK))
            fprintf (stderr, "FL_IOCTL_FLASH_UNFORMAT failed %d\n", out.status);
    }

    /* WARNING: You must kill DiskOnChip driver and reboot your system now ! */
    return rc;
}

#endif /* ALLOW_FORMATTING */




static
int hdio_getgeo (int fd)
{
    struct hd_geometry
    {
        unsigned char  heads;
        unsigned char  sectors;
        unsigned short cylinders;
        unsigned long  start;
    }; 

    struct hd_geometry geo;
    int                rc;

    if ((rc = ioctl(fd, 0x0301 /* HDIO_GETGEO */, &geo)) != 0)
        perror ("Error in HDIO_GETGEO");
    else
        printf ("Disk geometry: %d heads, %d cylinders, %d sectors, start sector %ld\n",
                 (int)geo.heads, (int)geo.cylinders, (int)geo.sectors, geo.start);
    return rc;
}



#ifdef ALLOW_BDK

static
int fl_ioctl_bdk_operation (int fd)
{
    flIOctlRecord   ioctl_data;
    int             buf_size = (4 * 1024);
    char          * buf;
    char          * buf2;
    int             rc;
    register int    iBin = 0;

    /* allocate buffers */
    if ((buf = malloc(buf_size)) == NULL)
    {
        fprintf (stderr, "Can't alloc buffer");
        return -1;
    }
    if ((buf2 = malloc(buf_size)) == NULL)
    {
        fprintf (stderr, "Can't alloc buffer");
        free (buf);
        return -1;
    }

#if 0
    for (; iBin <= 1; iBin++)
#endif
    {
        /* set this binary partition as the target of subsequent IOCTLs */

        {   flInputLnxRecord  in;
            flOutputLnxRecord out;

            in.command = 0;
            in.data    = mk_tffs_handle (0, 0);

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

            rc = ioctl (fd, FL_IOCTL_LNX, &ioctl_data);
            if ((rc != 0) || (out.status != flOK))
            {
                fprintf (stderr, "FL_IOCTL_LNX failed %d\n", (int)out.status);
                rc = -1;
                goto quit;
            }
        }

        /* write, the read back and verify 'buf_size' bytes to this binary partition */

        {   flBDKOperationInput  in;
            flOutputStatusRecord out;

            fprintf (stdout, "Writing %d bytes to binary partition %d\n", buf_size, iBin);

            in.type = BDK_GET_INFO;
            in.bdkStruct.flags         = 0;
            in.bdkStruct.length        = 0;
            in.bdkStruct.startingBlock = 0;
            in.bdkStruct.bdkBuffer     = NULL;
            in.bdkStruct.signOffset    = 8;
            if (iBin == 0) 
                memcpy (in.bdkStruct.oldSign, "BIPO", 4);
            else
                memcpy (in.bdkStruct.oldSign, "BIPO", 4);
            ioctl_data.inputRecord  = &in;
            ioctl_data.outputRecord = &out;
            rc = ioctl (fd, FL_IOCTL_BDK_OPERATION, &ioctl_data);
            if ((rc != 0) || (out.status != flOK))
            {
                fprintf (stderr, "FL_IOCTL_BDK_OPERATION/BDK_GET_INFO failed %d\n", out.status);
                rc = -1;
                goto quit;
            }

            in.type = BDK_INIT_WRITE;
            in.bdkStruct.flags         = 0;
            in.bdkStruct.length        = buf_size;
            in.bdkStruct.bdkBuffer     = NULL;
            in.bdkStruct.signOffset    = 8;
            if (iBin == 0) 
            {
                in.bdkStruct.startingBlock = 0;
                memcpy (in.bdkStruct.oldSign, "BIPO", 4);
            }
            else
            {
                in.bdkStruct.startingBlock = 15;
                memcpy (in.bdkStruct.oldSign, "BIPO", 4);
            }
            ioctl_data.inputRecord  = &in;
            ioctl_data.outputRecord = &out;
            rc = ioctl (fd, FL_IOCTL_BDK_OPERATION, &ioctl_data);
            if ((rc != 0) || (out.status != flOK))
            {
                fprintf (stderr, "FL_IOCTL_BDK_OPERATION/BDK_INIT_WRITE failed %d\n", out.status);
                rc = -1;
                goto quit;
            }
        
            in.type = BDK_WRITE;
            in.bdkStruct.flags     = ERASE_BEFORE_WRITE;
            in.bdkStruct.length    = buf_size;
            in.bdkStruct.bdkBuffer = buf;
            memset (buf, '$', buf_size);
            ioctl_data.inputRecord  = &in;
            ioctl_data.outputRecord = &out;
            rc = ioctl (fd, FL_IOCTL_BDK_OPERATION, &ioctl_data);
            if ((rc != 0) || (out.status != flOK))
            {
                fprintf (stderr, "FL_IOCTL_BDK_OPERATION/BDK_WRITE failed %d\n", out.status);
                rc = -1;
                goto quit;
            }

            fprintf (stdout, "SUCCESS writing %d bytes to binary partition %d\n", buf_size, iBin);

            fprintf (stdout, "Reading back and verifying %d bytes from binary partition %d\n", buf_size, iBin);

            in.type = BDK_INIT_READ;
            ioctl_data.inputRecord  = &in;
            ioctl_data.outputRecord = &out;
            rc = ioctl (fd, FL_IOCTL_BDK_OPERATION, &ioctl_data);
            if ((rc != 0) || (out.status != flOK))
            {
                fprintf (stderr, "FL_IOCTL_BDK_OPERATION/BDK_INIT_READ failed %d\n", out.status);
                rc = -1;
                goto quit;
            }

            in.type = BDK_READ;
            in.bdkStruct.bdkBuffer = buf2;
            memset (buf2, 0, buf_size);
            ioctl_data.inputRecord  = &in;
            ioctl_data.outputRecord = &out;
            rc = ioctl (fd, FL_IOCTL_BDK_OPERATION, &ioctl_data);
            if ((rc != 0) || (out.status != flOK))
            {
                fprintf (stderr, "FL_IOCTL_BDK_OPERATION/BDK_READ failed %d\n", out.status);
                rc = -1;
                goto quit;
            }

            if( memcmp(buf, buf2, buf_size) != 0)
            {
                fprintf (stderr, "Error: mismatching data\n");
                rc = -1;
                goto quit;
	    }
            fprintf (stdout, "SUCCESS reading back and verifying data\n");
        }
    } /* for(iBin) */

quit:

    free (buf);
    free (buf2);

    return rc;
}

#endif /* ALLOW_BDK */



#ifdef ALLOW_HW_PROTECTION

/* 
 * This routine sets TrueFFS handle for subsequent IOCTLs
 */
static
int  set_ioctl_handle (int fd, int tffs_handle)
{
    flIOctlRecord      ioctl_data;
    flInputLnxRecord   in;
    flOutputLnxRecord  out;
    int                rc;

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

    in.command = 0;
    in.data    = tffs_handle;

    rc = ioctl (fd, FL_IOCTL_LNX, &ioctl_data);
    if ((rc != 0) || (out.status != flOK))
    {
        fprintf (stderr, "FL_IOCTL_LNX failed %d\n", (int)out.status);
        rc = -1;
    }
    else
        fprintf (stdout, "SUCCESS setting handle 0x%x for future IOCTLs\n", tffs_handle);

    return rc;
}



/* 
 * This routine provides example of using FL_IOCTL_..._HW_PROTECTION
 * IOCTLs to insert key into protected partition.
 */
static
int fl_ioctl_hw_protection (int fd, int ioctl_opcode)
{
    flIOctlRecord  ioctl_data;
    int            socket_no = 0;
    int            partition_no;
    int            rc;

    partition_no = /* specify your own partition here */ 0;

    /* set TrueFFS handle for subsequent IOCTL */

    rc = set_ioctl_handle (fd, mk_tffs_handle(socket_no, partition_no));
    if (rc != 0)
        return rc;

    /* insert key into partition */

    {   flProtectionInput  in;
        flProtectionOutput out;

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

        in.type = PROTECTION_INSERT_KEY;

        /* this is my usual key; replace it with your own */

        in.key[0] = 'p';
        in.key[1] = 'i';
        in.key[2] = 's';
        in.key[3] = 's';
        in.key[4] = 'w';
        in.key[5] = 'o';
        in.key[6] = 'r';
        in.key[7] = 'd';
        
        in.protectionType = 0;  /* not actually used by PROTECTION_INSERT_KEY */

        rc = ioctl (fd, ioctl_opcode, &ioctl_data);
        if ((rc != 0) || (out.status != flOK))
            fprintf (stderr, "%d IOCTL failed %d\n", ioctl_opcode, out.status);
        else
            fprintf (stdout, "SUCCESS inserting protection key\n");
    }

    /* for security, set TrueFFS handle to impossible value (0xffff) */

    set_ioctl_handle (fd, 0xffff);

    return rc;
}

#endif /* ALLOW_HW_PROTECTION */

