/*
 *               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 <iostypes.h>
#include <ios.h>
#include <iop.h>
#include <ioslibc.h>

#ifndef ENABLE_TEST
#define STACK_SIZE 2048
const u8        _initStack[STACK_SIZE];
const u32       _initStackSize = sizeof(_initStack);
const u32       _initPriority = 20;
#endif /* ENABLE_TEST */

#include "iosusbtypes.h"
#include "iosusb.h"

/* ---- start bms.h -------------------------*/
#define BMS_ERR(...) /*  */
#define BMS_LOG(...)  /*  */

#define BMS_DMA_IN  0
#define BMS_DMA_OUT 1

#define READ_CAP10_SIZE 10
#define BMS_ERROR_TAG     -7500
#define BMS_ERROR_STAT    -7501
#define BMS_ERROR_SIG     -7502
#define BMS_ERROR_DATA    -7503

#define CSW_ERROR_PASS  0x00
#define CSW_ERROR_FAIL  0x01
#define CSW_ERROR_PHASE 0x02

typedef struct CBW {
    u32 sig;
    u32 tag;
    u32 dataLen;
    u8 flags;
    u8 lun;
    u8 cbLen;
    u8 cb[16];
} CBW __attribute__((aligned(32)));
#define CBW_XFER_SIZE 31
#define CBW_SIGNATURE SWAP32(0x43425355)

typedef struct CSW {
    u32 sig;
    u32 tag;
    u32 residue;
    u8 status;
} CSW __attribute__((aligned(32)));
#define CSW_XFER_SIZE 13
#define CSW_SIGNATURE SWAP32(0x53425355)

/* SCSI direct-access block commands */
/* Read capacity */
#define RDCAP10_OPCODE 0x25
#define RDCAP10_SIZE 9
#define READ_CAP10_RCV_SIZE 8
typedef struct RDCAP10 {
    u8 opcode;
    u8 pad1;
    u16 lba;
    u8  pad2;
    u8  pmi;
    u16 pad3;
    u8 ctrl;
} RDCAP10  __attribute__((aligned(32)));


#define WR10_OPCODE 0x2a
#define WR10_SIZE  10
#define RD10_OPCODE 0x28
#define RD10_SIZE  10

/* ---- end bms.h -------------------------*/

/* Bulk-only mass storage class support */

static u32 __numBlocks = 0; /* max lba + 1 */
static u32 __blockSize = 0; /* bytes */
static u32 __capacity  = 0; /* bytes */
static u32 __maxLUN = 0; 
static u32 __iter = 10;
static u8 __inEp = 0x81;
static u8 __outEp = 0x01;
s32
bmsReset(IOSFd fd, u16 wIntf)
{
  return IUSB_WriteCtrlMsg(fd, 0x21, 0xff, 0, wIntf, 0, NULL);
}

s32
bmsGetMaxLUN(IOSFd fd, u16 wIntf, u8 *lun)
{
    s32 rv;
    rv = IUSB_ReadCtrlMsg(fd, 0xa1, 0xfe, 0, wIntf, 1, lun);
    if (rv >= 0) {
        __maxLUN = *lun;
    }
    return rv;
}

static s32 
__bmsCBW(IOSFd fd, u32 ep, u32 tag, u32 dataLen, u32 dir, u8 lun, 
        u32 cbLen, u8 *cb)
{
    s32 rv;
    CBW cbw;

    if (cbLen > sizeof(cbw.cb)) {
        BMS_ERR("invalid CBW block length: %u (expect <= 16))\n", cbLen);
        rv = (s32) IOS_ERROR_INVALID;
        goto done;
    }    
    cbw.sig = CBW_SIGNATURE;
    cbw.tag = SWAP32(tag);
    cbw.dataLen = SWAP32(dataLen);
    cbw.lun = lun;
    cbw.cbLen = cbLen;
    if (BMS_DMA_IN == dir) {
        cbw.flags = 0x80; 
    } else {
        cbw.flags = 0; 
    }
    memset(cbw.cb, 0, sizeof(cbw.cb));
    memcpy(cbw.cb, cb, cbLen);
    rv = IUSB_WriteBlkMsg(fd, ep, CBW_XFER_SIZE, (char *)&cbw); 
done:
    return rv;
}

static s32 
__bmsCSW(IOSFd fd, u32 epIn, u32 tag)
{
    s32 rv;
    CSW csw;
    memset(&csw, 0, sizeof(csw));
    rv = IUSB_ReadBlkMsg(fd, epIn, CSW_XFER_SIZE, (char *)&csw); 
    if (rv < 0) {
        BMS_ERR("%s: blk transfer error %d\n", __FUNCTION__, rv);
        if (IUSB_ERROR_STALL == rv) {
            goto reset_recover;
        }
        goto done;
    }
    if (csw.status) {
        BMS_ERR("status error: %x\n", csw.status);
        rv = BMS_ERROR_STAT;
        if (CSW_ERROR_PHASE == csw.status) {
            goto reset_recover;
        }
        goto done;
    }
    if (csw.residue) {
        BMS_ERR("Data transfer failed. Residue = %x\n", SWAP32(csw.residue));
        rv = BMS_ERROR_DATA;
        goto done;
    }
    if (SWAP32(tag) != csw.tag) {
        BMS_ERR("tag mismatch: tag = %x csw tag = %x\n", tag, csw.tag);
        rv = BMS_ERROR_TAG;
        goto done;
    }
    goto done;

reset_recover:
    bmsReset(fd, 0);
    goto done;
done:
    return rv;
}

s32
bmsReadCapacity(IOSFd fd, u32 epOut, u32 epIn, u32 buflen, char *buf)
{
  s32 rv;
  u32 tag = 0xcafebabe;
  RDCAP10 rdcap10;

  if (buflen < READ_CAP10_RCV_SIZE) {
      printf("read capacity: %u < %u\n", buflen < READ_CAP10_RCV_SIZE);
      rv = IOS_ERROR_INVALID;
      goto done;
  }
  memset(&rdcap10, 0, sizeof(rdcap10));
  rdcap10.opcode = RDCAP10_OPCODE;
  rdcap10.lba = 0;
  rdcap10.pmi = 0;
  rdcap10.ctrl = 0 ;
  rv = __bmsCBW(fd, epOut, tag, READ_CAP10_RCV_SIZE, BMS_DMA_IN, 0, READ_CAP10_SIZE, (u8 *) &rdcap10);
  if (rv < 0) {
      BMS_ERR("CBW get capacity command failed: %d\n", rv);
      goto done;
  }
  rv = IUSB_ReadBlkMsg(fd, epIn, 8, buf);
  if (rv < 0) {
      BMS_ERR("get capacity data failed: %d\n", rv);
      goto done;
  } else {
      u32 size;
      u32 blocks;
      memcpy((char *)&size, buf + 4, 4);
      memcpy((char *)&blocks, buf, 4);
      blocks++; 
      BMS_LOG("block size = %u bytes\n", size);
      BMS_LOG("blocks = %u\n", blocks);
      BMS_LOG("capacity = %u MB\n", blocks*size/1024/1024);
      __numBlocks = blocks;
      __blockSize = size;
      __capacity = blocks * size;
  }
  rv = __bmsCSW(fd, epIn, tag);
  
done:
  return rv;
}

static int
__isalnum(u8 c) 
{
    if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
          (c >= '0' && c <= '9')) {
        return 1;
    }
    return 0;
}

s32
bmsInquiry(IOSFd fd, u32 epOut, u32 epIn, u32 buflen, char *buf)
{
    s32 rv;
    u8 cmd[6];
    u32 tag = 0xbabecafe;
    u8 len;
    printf("Entered %s\n", __FUNCTION__);    
    memset(cmd, 0, sizeof(cmd));
    cmd[0] = 0x12;
    cmd[4] = 0x24;
    rv = __bmsCBW(fd, epOut, tag, 0x24, BMS_DMA_IN, 0, 6, cmd);
    if (rv < 0) {
        BMS_ERR("CBW for read command failed: %d\n", rv);
        goto done;
    }
    rv = IUSB_ReadBlkMsg(fd, epIn, 36, buf);
    if (rv < 0) {
        BMS_ERR("reading data failed: %d\n", rv);
        goto done;
    }
    rv = __bmsCSW(fd, epIn, tag);
    if (rv < 0) {
        goto done;
    }

    /* Get actual length */
    len = (u8)buf[4]; 
    if (len > 31) { /* Fetch all data */
        printf("additional inquiry data len = %u\n", len - 31);
#if 0
        rv = __bmsCBW(fd, epOut, tag, len, BMS_DMA_IN, 0, 6, cmd);
        if (rv < 0) {
            BMS_ERR("CBW for read command failed: %d\n", rv);
            goto done;
        }
        rv = IUSB_ReadBlkMsg(fd, epIn, len, buf);
        if (rv < 0) {
            BMS_ERR("reading data failed: %d\n", rv);
            goto done;
        }
        rv = __bmsCSW(fd, epIn, tag);
        if (rv < 0) {
            goto done;
        }
#endif
    }

    {
        u32 i;
        if (0 == buf[0]) {
            printf("Direct access device attached\n");
        }
        printf("Vendor/product/version:");
        for (i = 0; i < 16; ++i) {
            if (__isalnum(buf[i])) {
                printf("%c", buf[i]);
            }
        }
        for (i = 15; i < 32; ++i) {
            printf("%c", buf[i]);
        }
       for (i = 32; i < 36; ++i) {
           printf("%c", buf[i]);
       }
       printf("\n");
    }
    
done:
    printf("Leaving %s\n", __FUNCTION__);
    return rv;
}

s32
bmsWriteBlock(IOSFd fd, u32 epOut, u32 epIn, u32 lba, u16 nblocks, char *buf)
{
    s32 rv;
    char *c;
    char wr10[WR10_SIZE];
    u32 tag = 0xcafebabe;

    if (lba + nblocks > __numBlocks) {
        printf("requested transfer exceeds medium size\n");
        rv = IOS_ERROR_MAX;
        goto done;
    }
    memset(&wr10, 0, sizeof(wr10));
    wr10[0] = WR10_OPCODE; 
    wr10[1] = 0; /* u8 flags */

    /* u32 LBA */
    c = (char *) &lba;
    wr10[2] = c[0];
    wr10[3] = c[1];
    wr10[4] = c[2];
    wr10[5] = c[3];   

    wr10[6] = 0; /* u8 group */

    /* u16 nblocks */
    c = (char *) &nblocks;
    wr10[7] = c[0];
    wr10[8] = c[1];

    wr10[9] = 0; /* u8 ctrl */

    rv = __bmsCBW(fd, epOut, tag, nblocks*__blockSize, BMS_DMA_OUT, 0, WR10_SIZE, (u8 *) &wr10);
    if (rv < 0) {
        BMS_ERR("CBW for write command failed: %d\n", rv);
        goto done;
    }
    rv = IUSB_WriteBlkMsg(fd, epOut, nblocks*__blockSize, buf);
    if (rv < 0) {
        BMS_ERR("writing data failed: %d\n", rv);
        goto done;
    }
    rv = __bmsCSW(fd, epIn, tag);
done:
    return rv;
}

s32
bmsReadBlock(IOSFd fd, u32 epOut, u32 epIn, u32 lba, u16 nblocks, char *buf)
{
    s32 rv;
    char *c;
    char rd10[RD10_SIZE];
    u32 tag = 0xcafebabe;

    if (lba + nblocks > __numBlocks) {
        printf("requested transfer exceeds medium size\n");
        rv = IOS_ERROR_MAX;
        goto done;
    }
//    printf("reading %u blocks starting at buf 0x%x.\n", nblocks, buf);
    memset(&rd10, 0, sizeof(rd10));
    rd10[0] = RD10_OPCODE; 
    rd10[1] = 0; /* u8 flags */

    /* u32 LBA */
    c = (char *) &lba;
    rd10[2] = c[0];
    rd10[3] = c[1];
    rd10[4] = c[2];
    rd10[5] = c[3];   

    rd10[6] = 0; /* u8 group */

    /* u16 nblocks */
    c = (char *) &nblocks;
    rd10[7] = c[0];
    rd10[8] = c[1];

    rd10[9] = 0; /* u8 ctrl */

//    printf("%s: nblocks = %u blockSize = %u\n", __FUNCTION__, nblocks, __blockSize);
    rv = __bmsCBW(fd, epOut, tag, nblocks*__blockSize, BMS_DMA_IN, 0, RD10_SIZE, (u8 *) &rd10);
    if (rv < 0) {
        BMS_ERR("CBW for read command failed: %d\n", rv);
        goto done;
    }
//    printf("CBW for read command succeeded: %d\n", rv);
//    printf("calling read blk msg: len = %lu buf = %p\n", 
//            nblocks*__blockSize, buf);
    rv = IUSB_ReadBlkMsg(fd, epIn, nblocks*__blockSize, buf);
    if (rv < 0) {
        BMS_ERR("reading data failed: %d\n", rv);
        printf("reading data failed: readBlkMsg returned %d\n", rv);
        goto done;
    }
    rv = __bmsCSW(fd, epIn, tag);
done:
    return rv;
}

s32
initBMS(IOSFd fd)
{
    s32 rv;
    char buf[64];
    u8 lun = 0;
    if ((rv = bmsGetMaxLUN(fd, 0, &lun)) < 0) {
        printf("GetMaxLUN failed: %d\n", rv);
        goto done;
    } else {
        printf("max LUN = %x\n", lun);
    }

    rv =  bmsInquiry(fd, __outEp, __inEp, 64, buf);
    rv = bmsReadCapacity(fd, __outEp, __inEp, 64, buf);
    if (rv < 0) {
        printf("read capacity failed: %d\n", rv);
        goto done;
    } else {
        printf("block size = %lu bytes numBlocks = %lu capacity = %lu KB\n",
                __blockSize, __numBlocks,  __blockSize*(__numBlocks/1024));
    }
done:
    return rv;
}

/* ---------------- end BMS functions -------------- */
static void
__ctrlTransferTests(IOSFd fd)
{
    u8 buf[IOS_USB_STR_MAX];
    struct USB_DevDescr d;
    memset(buf, 0, sizeof(buf));
    memset(&d, 0, sizeof(d));
    IUSB_GetDevDescr(fd, &d); 

    printf("Entered %s\n", __FUNCTION__);    
    printf("--- Ctrl transfer tests \n");
    if ( (d.iManufacturer != 0 )
            && (0 < IUSB_GetAsciiStr(fd, 0, d.iManufacturer, 
                    USB_LANG_EN_US, buf, sizeof(buf))))
        printf("Manufacturer: %s\n", buf);
    if ( (d.iProduct != 0)
            && (0 < IUSB_GetAsciiStr(fd, 0, d.iProduct, 
                    USB_LANG_EN_US, buf, sizeof(buf))) ) 
        printf("Product: %s\n", buf);

    if ( (d.iSerialNumber != 0)
            && (0 < IUSB_GetAsciiStr(fd, 0, d.iSerialNumber, 
                    USB_LANG_EN_US, buf, sizeof(buf))) ) 
        printf("Serial number: %s\n", buf);
    printf("Leaving %s\n", __FUNCTION__);
}

#define PATTERN 0xbc
#define BLOCKS 4096
static char *read_buf = (char *)0x10000000;
#define READ_BUF_SIZE (BLOCKS*512)

void
readTest(IOSFd fd0)
{
    u32 start, end;
    s32 rv;
    int i;
    u32 total_time = 0;

    /* spin up */
    rv = bmsReadBlock(fd0, __outEp, __inEp, 0, READ_BUF_SIZE/__blockSize, read_buf);
   
    memset(read_buf, 0, READ_BUF_SIZE);
    for (i = 0; i < __iter; ++i) {
        start = busRd32(SYS_TIMER_REG);
        rv = bmsReadBlock(fd0, __outEp, __inEp, 0, READ_BUF_SIZE/__blockSize, read_buf);
        rv = bmsReadBlock(fd0, __outEp, __inEp, 0, READ_BUF_SIZE/__blockSize, read_buf);
        rv = bmsReadBlock(fd0, __outEp, __inEp, 0, READ_BUF_SIZE/__blockSize, read_buf);
        rv = bmsReadBlock(fd0, __outEp, __inEp, 0, READ_BUF_SIZE/__blockSize, read_buf);
        rv = bmsReadBlock(fd0, __outEp, __inEp, 0, READ_BUF_SIZE/__blockSize, read_buf);
        rv = bmsReadBlock(fd0, __outEp, __inEp, 0, READ_BUF_SIZE/__blockSize, read_buf);
        rv = bmsReadBlock(fd0, __outEp, __inEp, 0, READ_BUF_SIZE/__blockSize, read_buf);
        rv = bmsReadBlock(fd0, __outEp, __inEp, 0, READ_BUF_SIZE/__blockSize, read_buf);
        rv = bmsReadBlock(fd0, __outEp, __inEp, 0, READ_BUF_SIZE/__blockSize, read_buf);
        rv = bmsReadBlock(fd0, __outEp, __inEp, 0, READ_BUF_SIZE/__blockSize, read_buf);
        end = busRd32(SYS_TIMER_REG);

        /* Run test with debug separately and verify reads succeed */
        {
            printf("Iteration %d time = %lu ticks\n", i, end - start);
            total_time += (end - start);
        }
    }
    printf("Buffer size: %lu bytes time = %lu ticks\n", 
            READ_BUF_SIZE, total_time/(10*__iter));
    return;
}

#ifdef ENABLE_TEST
void
ehci_test(u32 arg)
#else
void
main(u32 arg)
#endif
{
    IOSFd fd0;
    fd0 = IOS_Open("/dev/usb/ehc/0781/5151", 0);
    if (fd0 < 0) {
        fd0 = IOS_Open("/dev/usb/ehc/059b/0275", 0);
        __inEp = 0x82;
        __outEp = 0x01;
        __iter = 50;
    }
    if (fd0 < 0) {
        fd0 = IOS_Open("/dev/usb/ehc/0411/00db", 0);
        __inEp = 0x81;
        __outEp = 0x02;
        __iter = 50;
    }
    if (fd0 < 0) {
        printf("Test needs device: Sandisk cruzer (0781,5151) or Iomega HD(059b, 0275) or Buffalo/Samsung USB drive(0411, 00db)\n");
        goto done;
    }

    __ctrlTransferTests(fd0);
    if (initBMS(fd0) < 0) {
        printf("initializing mass storage driver failed\n");
    }
    readTest(fd0);
    __ctrlTransferTests(fd0);
done:
    IOS_DestroyThread(0, NULL);
    return;
}
