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

#include <sc/sc.h>
#include <sc/ios.h>
#include <ioslibc.h>
#include <iosc.h>
#include <fs.h>
#include "usb.h"
#include "usbdev.h"
#include "ch9.h"
#include "bulk.h"
#include "msd.h"
#include "usbhw.h"

/* * * * * *  MSD device ctrl data * * * * * * */
extern  USBMsdCtrl msdCtrl;
extern  u8 daBuf[128];

/* * * * * * SPC2 sense data(18 bytes) * * * * */
u8 msdSenseRepond[MSD_SENSE_DATA_SIZE];

/* * * MSD descriptors for USB chapter9 enum * */
unsigned char msdDevDesc[18] DCACHE_ALIGN =
{
    sizeof(msdDevDesc),      /* Length */
    1,                       /* Type of descriptor = device */
    U16_LOW_BYTE(USB_VER), 
    U16_HIGH_BYTE(USB_VER),  /* Usb version */
    0x00,                    /* Device Class */
    0x00,                    /* Subclass */
    0x00,                    /* No class specific protocols */
    8,                       /* Maximum packet size */
    U16_LOW_BYTE(MSD_VENDOR_ID), 
    U16_HIGH_BYTE(MSD_VENDOR_ID),
    U16_LOW_BYTE(MSD_PRODUCT_ID), 
    U16_HIGH_BYTE(MSD_PRODUCT_ID),
    U16_LOW_BYTE(MSD_VERSION_ID), 
    U16_HIGH_BYTE(MSD_VERSION_ID),
    1,                       /* Manufacturer string index */
    2,                       /* Product string index */
    3,                       /* Serial number string index */
    1                        /* Number of configurations */
};

unsigned char msdCfgDesc[MSD_CFG_DESC_SIZE] DCACHE_ALIGN = 
{
    /* * Configuration descriptor * */    
    9,                       /* Configuration Descriptor - always 9 bytes */
    2,                       /* "Configuration" type of descriptor */
    U16_LOW_BYTE(MSD_CFG_DESC_SIZE), 
    U16_HIGH_BYTE(MSD_CFG_DESC_SIZE),
    1,                       /* # of Interfaces  */
    1,                       /* Configuration Value */
    0,                       /* Configuration Description String Index */
    0x40,                    /* Attributes:  Self-powered */
    0,                     /* Current draw from bus (units of 2mA) */

    /* Interface */
    9,                       /* Interface 0 Descriptor - always 9 bytes */
    4,                       /* "Interface" type of descriptor */
    0,                       /* Number of this interface */
    0,                       /* Alternate Setting */
    2,                       /* Number of endpoints on this interface */
    0x08,                    /* Mass storage class */
    0x06,                    /* SPC-2 command set    */
    0x50,                    /* Bulk only Transport */
    0,                       /* Interface Description */
   
    /* Ep 2 (config as bulk in) */  
    7,                       /* Interface 0 Descriptor - always 7 bytes */
    5,                       /* ep type of descriptor */
    0x82,                    /* ep2, bit 7 -- Rx(IN) */
    0x2,                     /* 0=Control 1=Isochronous 2=Bulk 3=Interrupt */
    U16_LOW_BYTE(MSD_MAX_PKT_SIZE),    /* BOT, so size is same as bulk */
    U16_HIGH_BYTE(MSD_MAX_PKT_SIZE),
    0,                       /* Pulling interval */

    /* Ep 3 (config as bulk out) */  
    7,                       /* Interface 0 Descriptor - always 7 bytes */
    5,                       /* ep type of descriptor */
    0x3,                     /* ep3, bit 7 -- Tx(Out) */
    0x2,                     /* 0=Control 1=Isochronous 2=Bulk 3=Interrupt */
    U16_LOW_BYTE(MSD_MAX_PKT_SIZE),
    U16_HIGH_BYTE(MSD_MAX_PKT_SIZE),
    0                        /* Pulling interval */
};

   /* Languages supported = American English (0x0409) */
unsigned char MSD_STR_0[4] DCACHE_ALIGN = 
       {sizeof(MSD_STR_0), 0x03, 0x09, 0x04};         

unsigned char MSD_STR_1[20] DCACHE_ALIGN =
{
    sizeof(MSD_STR_1), 0x03,
    'i', 0, 'Q', 0, 'u', 0, 'e', 0, ' ', 0, 'L', 0, 't', 0, 'd', 0,
    '.', 0
};
        
static unsigned char MSD_STR_2[28] = {sizeof(MSD_STR_2), 0x03,
     'i', 0, 'Q', 0, 'u', 0, 'e', 0, ' ', 0, 'N', 0, 'e', 0, 't', 0,
     ' ', 0, 'C', 0, 'a', 0, 'r', 0, 'd', 0};

/* Serial number = Vendor ID + product ID + NC ID*/
static unsigned char MSD_STR_3[34] = {sizeof(MSD_STR_3), 0x03,
     '1', 0, '5', 0, '2', 0, '7', 0, 'B', 0, 'C', 0, 'D', 0, 'D', 0,
     '0', 0, '0', 0, '0', 0, '0', 0, '0', 0, '0', 0, '1', 0, '3', 0};
#define MSD_STR_ID_OFFS      18          /* NC ID offset */

static unsigned char  MSD_STR_n[34] DCACHE_ALIGN =
{
    sizeof(MSD_STR_n), 0x03,
    'B',0,'A',0,'D',0,' ',0,'S',0,'T',0,'R',0,'I',0,
    'N',0,'G',0,' ',0,'I',0,'n',0,'d',0,'e',0,'x',0
};

/* * * * * SPC2 Inquire response data * * * */
static SPC2InquiryResponse sp2Inqury = {
    0x00,           /* Disk */
    0x00,           /* removable disk to preform autorun */
    0x00,           /* SPC 2 command set */
    0x02,           /* response is in format specified by SPC-2 */
    0x5B,           /* additional length */
    0x00,           /* sccs, acc, etc*/
    0x00,           /* bque, etc */
    0x00,           /* obsolete */ 
    "iQue    ",
    "NC Install Disk ",
    "0001"
};
    
unsigned char * MSD_USB_STRING_DESC[MSD_STR_NUM+2] = 
{   
    (unsigned char *) MSD_STR_0, 
    (unsigned char *) MSD_STR_1, 
    (unsigned char *) MSD_STR_2, 
    (unsigned char *) MSD_STR_3, 
    (unsigned char *) MSD_STR_n, 
};

IOSError
msdSetDeviceType(u8 newType)
{
    if (newType == sp2Inqury.rmb) 
        return IOS_ERROR_EXISTS; 
   
    if (newType != USB_SET_MSD_REMOVABLE && newType != USB_SET_MSD_FIXED) 
        return IOS_ERROR_NOEXISTS;

    sp2Inqury.rmb = newType;
    usbHwRestart(usbHwUnplug());
    
    return IOS_ERROR_OK; 
}

u8
msdGetDeviceType()
{
    return sp2Inqury.rmb;
}

u8*
msdGetDevDesc(int *len)
{
    *len = sizeof(msdDevDesc);

    return msdDevDesc;
}

u8*
msdGetConfDesc(int *len)
{
    *len = sizeof(msdCfgDesc);

    return msdCfgDesc;
}

u8*
msdGetDescString(int n, int *len)
{
    int i, id;
    u8  buf[16];

    /* Read NC id from SK */
    IOSC_GetData(IOSC_DEV_ID_HANDLE, &id); 
    if (n == 3) {   
        snprintf(buf, 16, "%08x", id);
        for (i=0; i<8; i++) {
            MSD_STR_3[MSD_STR_ID_OFFS + i*2] = buf[i];
        }
    }

    if (n > MSD_STR_NUM) n = 0;
    *len =  MSD_USB_STRING_DESC[n][0];

    return MSD_USB_STRING_DESC[n];
}

void 
msdEnumDone()
{
    /* make buffer ready to accept SPC2 command */
    usbHwRead(MSD_READ_EP, daBuf, MSD_MAX_PKT_SIZE);
 
    return;
}

Ch9CallBack msdCh9Callback = {
    msdGetDevDesc,
    msdGetConfDesc,
    msdGetDescString,
    msdEnumDone
};

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Function: isValidCbw()
    
    Description:
        Check cbw is valid (see USB Nass Storage class
    -- bulk only transport spec 6.2.1

    Return:
        non-zero if cbw is valid 
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int 
isValidCbw(USBMsdCBW *cbw, int len)
{
    if ((cbw->signature == MSD_CBW_SIGNATURE) && (len == 31)) 
        return 1; 

    return 0;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Function: isMeaningfulCbw()
    
    Description:
        Check cbw is meaningful (see USB Nass Storage class
    -- bulk only transport spec 6.2.2

    Return:
        non-zero if cbw is meaningful
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int 
isMeaningfulCbw(USBMsdCBW *cbw)
{
    if ((cbw->lun == 0)  && (cbw->cbLen<=16))
        return 1; 

    return 0;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Function: prepareFormatCapacityData()
    
    Description:
        Prepare formated capacity data 
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
int
prepareFormatCapacityData(u8 *out)
{
    /* capacity List header */
    out[0] = out[1] = out[2] = 0;
    out[3] = 8;

    /* current capacity List */
    out[4] = (msdCtrl.blkNum >> 24) & 0xff;
    out[5] = (msdCtrl.blkNum >> 16) & 0xff;
    out[6] = (msdCtrl.blkNum >> 8) & 0xff;
    out[7] =  msdCtrl.blkNum  & 0xff;

    out[8] = SPC2_FORMAT_CAP_DESC_FRMT; 
    out[9] =  (msdCtrl.blkSize >> 16) & 0xff;
    out[10] = (msdCtrl.blkSize >> 8) & 0xff;
    out[11] = msdCtrl.blkSize  & 0xff;

    return 12;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Function: prepareCapacityData()
    
    Description:
        Prepare 8 byte capacity data 
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void 
prepareCapacityData(u8 *out)
{
    out[0] = (msdCtrl.blkNum >> 24) & 0xff;
    out[1] = (msdCtrl.blkNum >> 16) & 0xff;
    out[2] = (msdCtrl.blkNum >> 8) & 0xff;
    out[3] =  msdCtrl.blkNum  & 0xff;

    out[4] = (msdCtrl.blkSize >> 24) & 0xff;
    out[5] = (msdCtrl.blkSize >> 16) & 0xff;
    out[6] = (msdCtrl.blkSize >> 8) & 0xff;
    out[7] =  msdCtrl.blkSize  & 0xff;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Function: prepareSenseRespond()
    
    Description:
        Prepare 18 byte capacity data 
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void 
prepareSenseRespond(u8 *out)
{
    out[0] = SPC2_SENSE_CURRENT;    /* valid=0 : not information */
    out[1] = 0;

    /* set filemark, eom and ili to 0 */
    out[2] = SPC2_NO_SENSE;   
    out[2] = 5;     // XXXXX

    /* information set to 0 */
    out[3] = out[4] = out[5] = out[6] = 0;

    out[7] = 17 - 7;
    
    /* command specific information */
    out[8] = out[9] =  out[10] = out[11] = 0;

    /*  asc and ascq both set to 0 */
    out[12] = out[13] = 0;

    /* Field replace unit code set to 0 */
    out[14] = 0;

    /* sense key specify also set to 0 */
    out[15] = out[16] = out[17] = 0;
    
    return;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Function: setSenseRespondCode
    
    Description:
        Set additional sense code(ASC) and additional sense code
    Qualifier.
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void 
setSenseRespondCode(u8 *out, u8 asc, u8 ascq)
{
    out[12] = asc;
    out[13] = ascq;
    
    return;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Function: msdReadWriteData()
    
    Description:
        Handle MSD CBW read10 and write10 command 

    Return:
        IOS_ERROR_OK if suceed.
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
IOSError
msdReadWriteData(u8 *cmd, USBMsdCSW *csw)
{
    u32 lba, len;
    IOSError rv = IOS_ERROR_OK;
    ISFSFileStats *fstats; 

    lba = (cmd[2] << 24) | (cmd[3] << 16) | (cmd[4] << 8) | cmd[5];
    len = (cmd[7] << 8) | cmd[8];

    lba *= msdCtrl.blkSize;
    len *= msdCtrl.blkSize;
    fstats = (ISFSFileStats *) msdCtrl.data;
    rv = ISFS_GetFileStats(msdCtrl.fd, fstats);
    
    if ((rv >= 0) && (fstats->size >= (lba+len))) 
        rv = ISFS_Seek(msdCtrl.fd, lba, SEEK_SET);
    msdCtrl.lba = lba;

    if (rv >= 0) {
        msdCtrl.pos = 0;
        msdCtrl.len = len;
        csw->status = MSD_CSW_STATUS_GOOD;
        csw->dataResidue = len;
    } else {
        prepareSenseRespond(msdSenseRepond);
        setSenseRespondCode(msdSenseRepond, SPC2_ASC_OUT_OF_RANGE, SPC2_ASCQ_OUT_OF_RANGE);
        csw->status = MSD_CSW_STATUS_FAIL;
        csw->dataResidue = 0;
    }

    return rv;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    Function: msdHandleCommand()
    
    Description:
        Handle MSD CBW command 

    Return:
        IOS_ERROR_OK if suceed.
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
IOSError
msdHandleCommand(USBMsdCBW *cbw, USBMsdCSW *csw)
{
    int i;
    IOSError rv = IOS_ERROR_OK;

    if (cbw == NULL || csw == NULL)
        return IOS_ERROR_INVALID;
   
    csw->status = MSD_CSW_STATUS_GOOD;
    switch (cbw->cb[0]) {
    case SPC2_INQUIRY:
        memcpy(&msdCtrl.send, &sp2Inqury, sizeof(SPC2InquiryResponse));
        csw->dataResidue = sizeof(SPC2InquiryResponse);
        break;
    case SPC2_FORMAT_CAP:
        csw->dataResidue = prepareFormatCapacityData(msdCtrl.send);
        break;
    case SPC2_CAPACITY10:
        prepareCapacityData(msdCtrl.send);
        csw->dataResidue = 8;
        break;
    case SPC2_MODESENSE6:
        for (i=1; i<MSD_SENSE_DATA_SIZE; i++) msdCtrl.send[i]=0;
        msdCtrl.send[0] = SPC2_SENSE_CURRENT;
        msdCtrl.send[7] = 0xA;
        csw->dataResidue = MSD_SENSE_DATA_SIZE;
        break;
    case SPC2_READ10:
        if ((msdCtrl.data != NULL) && (msdCtrl.fd >= 0)) {
            msdReadWriteData(cbw->cb, csw);
            if (csw->status != MSD_CSW_STATUS_GOOD)
                csw->dataResidue = 0;
        } else { /* MSD cannot alloc shared mem */
            csw->status = MSD_CSW_STATUS_FAIL;
            csw->dataResidue = 0;
        }
        break;
    case SPC2_REQUEST_SENSE:
        memcpy(&msdCtrl.send, msdSenseRepond, MSD_SENSE_DATA_SIZE);
        csw->dataResidue = MSD_SENSE_DATA_SIZE;
        break;
    case SPC2_TEST_UNIT_READY:
        prepareSenseRespond(msdSenseRepond);
        csw->dataResidue = 0;
        break;
    case SPC2_WRITE10:
        if (msdCtrl.fd >= 0) msdReadWriteData(cbw->cb, csw);
        else csw->status = MSD_CSW_STATUS_FAIL;
        csw->dataResidue = cbw->dataTransferLen;
        break;
    default:
        prepareSenseRespond(msdSenseRepond);
        setSenseRespondCode(msdSenseRepond, SPC2_ASC_INVALID_COMMAND, SPC2_ASCQ_INVALID_COMMAND);
        csw->status = MSD_CSW_STATUS_FAIL;
        csw->dataResidue = cbw->dataTransferLen;
        break;
    }

    csw->signature = MSD_CSW_SIGNATURE;
    csw->tag = cbw->tag;

    return rv;
}

