
/*
 * Simple Usb test
 *     Polling USB ctrl register
 *     Try to set up all chapter 9 enumeration to fool PC 
 */

#include <types.h>
#include <sc/sc.h>
#include <ioslibc.h>
#include <sc/dv_boot.h>

#define DCACHE_ALIGN  __attribute__ ((aligned (16)))
#define U16_LOW_BYTE(x)            ((x) & 0xff)
#define U16_HIGH_BYTE(x)           (((x) >> 8) & 0xff) 
#define MAX_PKT_SIZE               64

#define USB_VER                    0x0110
#define SC_VENDOR_ID               0xBB3D
#define SC_PRODUCT_ID              0xBBDB
#define SC_VERSION_ID              0x0001

  /* USB Request Type*/
#define USB_REQ_TYPE_MASK          0x60
#define USB_REQ_TYPE_SHIFT         5
#define USB_REQ_TYPE(v)            (((v) & USB_REQ_TYPE_MASK) >> \
                                    USB_REQ_TYPE_SHIFT)

#define USB_REQ_HOST_TO_DEV        0x0
#define USB_REQ_DEV_TO_HOST        0x80

#define USB_REQ_REP_DEVICE         0
#define USB_REQ_REP_INTERFACE      1
#define USB_REQ_REP_EP             2
#define USB_REQ_REP_OTHER          3

#define USB_REQ_STANDARD           0x0
#define USB_REQ_CLASS              0x1
#define USB_REQ_VENDOR             0x2
#define USB_REQ_OTHER              0x3

  /* Standard USB Request Type */
#define USB_REQ_GET_STATUS         0
#define USB_REQ_CLEAR_FEATURE      1
#define USB_REQ_SET_FEATURE        3
#define USB_REQ_SET_ADDRESS        5
#define USB_REQ_GET_DESCRIPTOR     6
#define USB_REQ_SET_DESCRIPTOR     7
#define USB_REQ_GET_CONFIGURATION  8
#define USB_REQ_SET_CONFIGURATION  9

char in[MAX_PKT_SIZE] DCACHE_ALIGN;        /* Usb IN buffer */
char out[MAX_PKT_SIZE] DCACHE_ALIGN;       /* Usb OUT buffer */
char xbuf[MAX_PKT_SIZE*16] DCACHE_ALIGN;
char min[2348] DCACHE_ALIGN;        /* Usb IN buffer */
int  rlen, wlen;

static unsigned char devDesc[18] DCACHE_ALIGN =
{
    sizeof(devDesc),         /* 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,                       /* XXX Maximum packet size */
    U16_LOW_BYTE(SC_VENDOR_ID), 
    U16_HIGH_BYTE(SC_VENDOR_ID),
    U16_LOW_BYTE(SC_PRODUCT_ID), 
    U16_HIGH_BYTE(SC_PRODUCT_ID),
    U16_LOW_BYTE(SC_VERSION_ID), 
    U16_HIGH_BYTE(SC_VERSION_ID),
    1,                       /* Manufacturer string index */
    2,                       /* Product string index */
    0,                       /* Serial number string index */
    1                        /* Number of configurations */
};

/* 9(1 configuration) + 9(1 interface) + 2*7 (2 ep) = 32 */
#define SC_CFG_DESC_SIZE             32

static unsigned char cfgDesc[SC_CFG_DESC_SIZE] DCACHE_ALIGN = 
{
    /* * Configuration descriptor * */    
    9,                       /* Configuration Descriptor - always 9 bytes */
    2,                       /* "Configuration" type of descriptor */
    U16_LOW_BYTE(SC_CFG_DESC_SIZE), 
    U16_HIGH_BYTE(SC_CFG_DESC_SIZE),
    1,                       /* # of Interfaces  */
    1,                       /* Configuration Value */
    0,                       /* Configuration Description String Index */
    0x80,                    /* Attributes:  Self-powered */
    250,                     /* 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 */
    0xff,                    /* Interface Class: Vendor specific */
    0xff,                    /* Interface Subclass: Vendor specific */
    0x0,                     /* Interface Protocol */
    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(MAX_PKT_SIZE),
    U16_HIGH_BYTE(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(MAX_PKT_SIZE),
    U16_HIGH_BYTE(MAX_PKT_SIZE),
    0                        /* Pulling interval */
};

#define SC_USB_STR_NUM       2 

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

static unsigned char USB_STR_1[20] DCACHE_ALIGN =
{
    sizeof(USB_STR_1), 0x03,
    'i', 0, 'Q', 0, 'u', 0, 'e', 0, ' ', 0, 'L', 0, 't', 0, 'd', 0,
    '.', 0
};
        
static unsigned char USB_STR_2[24] = {sizeof(USB_STR_2), 0x03,
      'i',0,'Q',0,'u',0,'e',0,' ',0,'P',0,'l',0,'a',0,
      'y',0,'e',0, 'r', 0};

static unsigned char  USB_STR_n[34] DCACHE_ALIGN =
{
    sizeof(USB_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
};

static const unsigned char * USB_STRING_DESC[SC_USB_STR_NUM+2] = 
{   
    (unsigned char *) USB_STR_0, 
    (unsigned char *) USB_STR_1, 
    (unsigned char *) USB_STR_2, 
    (unsigned char *) USB_STR_n, 
};

#define USB_GET_DESC_DEV        1
#define USB_GET_DESC_CONF       2
#define USB_GET_DESC_STRING     3

typedef struct {
    unsigned char  reqType;
    unsigned char  req;
    unsigned short wValue;
    unsigned short wIndex;
    unsigned short wLength;
} USB_SETUP_PKT;

#define SETUP_PTR(r, a) IO_WRITE(r##_REG, \
        r##_WE | r##_VALID | r##_VIOL | r##_ZERO | r##_SETUP | \
        CPU_TO_BUS_ADDR((a)))

#define SETUP_EP0_OUT(a, len) { \
            IO_WRITE(USB_OUT0_LEN_REG, len); \
            SETUP_PTR(USB_OUT0_PTR, a); \
        }

#define SETUP_EP0_IN(a, len) { \
            IO_WRITE(USB_IN0_LEN_REG, len); \
            SETUP_PTR(USB_IN0_PTR, a); \
        }

#define SETUP_EP3_OUT(a, len) { \
            IO_WRITE(USB_OUT3_LEN_REG, len); \
            SETUP_PTR(USB_OUT3_PTR, a); \
        }

#define SETUP_EP2_IN(a, len) { \
            IO_WRITE(USB_IN2_LEN_REG, len); \
            SETUP_PTR(USB_IN2_PTR, a); \
        }

int 
cpu0main(void)
{
    volatile unsigned int ctrl=0, curReq=-1;
    int v, n;
    int xLen=-1, xCur=0, len;
    USB_SETUP_PKT *setup;
    int hostAskSize=-1;
    unsigned short curConfig = 0;

    /* No interrupt handler at this moment */
    for (n=0; n<600; n++) IO_READ(PWR_CTRL_REG);
    printf("IN addr = 0x%x OUT = 0x%x \n", (int) in, (int) out);
    IO_WRITE(PWR_CTRL_REG, PWR_CTRL_CLOCK_ON << PWR_CTRL_USB_SHIFT);
    IO_WRITE(PWR_CTRL_REG, PWR_CTRL_RESET_MASK << PWR_CTRL_USB_SHIFT);
    IO_WRITE(USB_CTRL_REG, USB_CTRL_WE);
    printf("Start here pwr control = 0x%x\n", IO_READ(PWR_CTRL_REG));
    printf("hello world\n");
    IO_WRITE(USB_CTRL_REG, USB_CTRL_ENA | USB_CTRL_PULLUP | USB_CTRL_WE);
    SETUP_EP0_OUT(((int) out), 8);
    printf("OUT0 = 0x%x ctrl=0x%x \n", 
	    IO_READ(USB_OUT0_PTR_REG), IO_READ(USB_CTRL_REG));

    for (; ;) {
        ctrl = IO_READ(USB_CTRL_REG);
        ctrl = IO_READ(USB_CTRL_REG);
        if (ctrl != IO_READ(USB_CTRL_REG)) 
            continue;
        
        if (ctrl & USB_CTRL_RST_INT) {
            /* Usb bus reset event */
                
              /* (1) clear all pointer (valid, intr, stall) */
            v = USB_IN0_PTR_WE | USB_IN0_PTR_ST_CLR | USB_IN0_PTR_INT;
            IO_WRITE(USB_IN0_PTR_REG,  v);
            IO_WRITE(USB_IN1_PTR_REG,  v);
            IO_WRITE(USB_IN2_PTR_REG,  v);
            IO_WRITE(USB_OUT0_PTR_REG, v);
            IO_WRITE(USB_OUT1_PTR_REG, v);
            IO_WRITE(USB_OUT3_PTR_REG, v);

              /* (2) Re-enable USB core to bring usb-clk back  */
            IO_WRITE(USB_CTRL_REG, USB_CTRL_ENA | USB_CTRL_MASK |
                     USB_CTRL_PULLUP | USB_CTRL_WE);

              /* (3) Clear Reset intr */
            IO_WRITE(USB_CTRL_REG, USB_CTRL_RST_INT);
                
              /* (4) setup ep0 ready to accept setup packet */ 
            SETUP_EP0_OUT(((int) out), 8);
            xLen = xCur = 0;
            continue;
        } 

        if (ctrl & USB_CTRL_SUSP_INT) {
            /* Suspend event, clear intr and wake up host */  
            IO_WRITE(USB_CTRL_REG, USB_CTRL_SUSP_INT);
            IO_WRITE(USB_CTRL_REG, USB_CTRL_WAKEUP);
        }

        if (USB_CTRL_INT(ctrl) & 1) {
            v = IO_READ(USB_OUT0_PTR_REG);
            if (v & USB_OUT0_PTR_INT) {
                /* DATA from Host ==> SC */
                if (v & USB_OUT0_PTR_REWIND) {
                    /* Got Packet xfer error */
                    printf("ERROR: USB packet rewind\n");
                    IO_WRITE(USB_OUT0_PTR_REG, 
                             USB_OUT0_PTR_INT | USB_OUT0_PTR_VIOL); 
                    SETUP_EP0_OUT(((int) out), 8);
                    continue;
                }

                if (v & USB_OUT0_PTR_OF) {
                    printf("ERROR: USB overflow\n");
                    IO_WRITE(USB_OUT0_PTR_REG,
                            USB_OUT0_PTR_OF | USB_OUT0_PTR_INT);
                    SETUP_EP0_OUT(((int) out), 8);
                    continue;
                }

                if (v & USB_OUT0_PTR_SETUP) {
                    /* Recv Setup packet */
                    IO_WRITE(USB_OUT0_PTR_REG, USB_OUT0_PTR_INT | USB_OUT0_PTR_SETUP); 

                    /* deal with chapter 9 enumeration */ 
                    setup = (USB_SETUP_PKT *) out;            
                    if (USB_REQ_TYPE(setup->reqType) != USB_REQ_STANDARD) {
                        printf("ERROR: ch9 reqType 0x%x not supported\n",
                            USB_REQ_TYPE(setup->reqType));
                        SETUP_EP0_OUT(((int) out), 8);
                        continue;   
                    }

                    /* Exit for simulator */
                    if (out[0] == 0xba && out[1] == 0xbe && out[2] == 0xca && out[3]==0xfe) 
                        break;

                    curReq = setup->req;
                    hostAskSize = -1;
                    switch (setup->req) {
                    case USB_REQ_GET_STATUS:
                        out[0] = out[1] = 0;
                        SETUP_EP0_OUT(((int) out), 8);
                        break;
                    case USB_REQ_CLEAR_FEATURE:
                        /* XXXX add stall wakeup here */
                        SETUP_EP0_OUT(((int) out), 8);
                        break;
                    case USB_REQ_SET_FEATURE:
                        /* XXXX add stall wakeup here */
                        SETUP_EP0_OUT(((int) out), 8);
                        SETUP_EP0_IN(((int) in), 0);
                        break;
                    case USB_REQ_SET_ADDRESS:
#if 0
                        printf("Set addr = %d\n", setup->wValue);
#endif
                        IO_WRITE(USB_CTRL_REG, USB_CTRL_A_WE |
                                 ((setup->wValue) << USB_CTRL_USB_ADDR_SHIFT));
                        xCur = xLen = 0;
                        SETUP_EP0_IN(((int) in), 0);
                        SETUP_EP0_OUT(((int) out), 8);
                        break;
                    case USB_REQ_GET_DESCRIPTOR:
                        switch (U16_HIGH_BYTE(setup->wValue)) {
                        case USB_GET_DESC_DEV:
                            memcpy(xbuf, devDesc, sizeof(devDesc));
                            xCur = 0;
                            xLen = setup->wLength;        
                            hostAskSize = setup->wLength;
                            memcpy(in, devDesc, sizeof(devDesc));
                            SETUP_EP0_IN(((int) in), 8);
                            break;
                        case USB_GET_DESC_CONF:
                            memcpy(xbuf, cfgDesc, sizeof(cfgDesc));
                            xCur = 0;
                            xLen = hostAskSize = setup->wLength;        
                            memcpy(in, cfgDesc, sizeof(cfgDesc));
                            if (xLen > sizeof(cfgDesc)) xLen = sizeof(cfgDesc);
                            SETUP_EP0_IN(((int) in), 8);
                            break;
                        case USB_GET_DESC_STRING:
                            n = U16_LOW_BYTE(setup->wValue);
                            hostAskSize = setup->wLength;
                            if (n > SC_USB_STR_NUM) n = 0; 
                            memcpy(xbuf, USB_STRING_DESC[n], 
                                USB_STRING_DESC[n][0]);
                            xCur = 0;
                            xLen = USB_STRING_DESC[n][0];
                            if (xLen > setup->wLength) xLen = setup->wLength;
                            n = (xLen > 8) ? 8 : xLen;
                            memcpy(in, xbuf, n);
                            SETUP_EP0_IN(((int) in), n);
                            break;
                        default:
                            printf("Wrong Get Desc req\n");
                            break;
                        }
   
                        SETUP_EP0_OUT(((int) out), 8);
                        break;
                    case USB_REQ_SET_DESCRIPTOR:
                        /*  XXX not support at this moment */
                        SETUP_EP0_OUT(((int) out), 8);
                        SETUP_EP0_IN(((int) in), 0); 
                        break;
                    case USB_REQ_GET_CONFIGURATION:
                        memcpy(in, &curConfig, sizeof(short));
                        SETUP_EP0_IN(((int) in), 0);   
                        break;
                    case USB_REQ_SET_CONFIGURATION:
                        curConfig = setup->wValue & 0xff;
                        SETUP_EP0_OUT(((int) out), 8);
                        SETUP_EP0_IN(((int) in), 0); 
                        IO_WRITE(USB_CTRL_REG, IO_READ(USB_CTRL_REG) | 
                                 USB_CTRL_CFG_DONE | USB_CTRL_WE);
                        SETUP_EP3_OUT(((int) out), MAX_PKT_SIZE);
                        wlen = rlen = 0;
                        break;
                    }
                } else {
                    /* USB OUT packet */
                    SETUP_EP0_OUT(((int) out), 8);
                    IO_WRITE(USB_OUT0_PTR_REG, USB_OUT0_PTR_INT | USB_OUT0_PTR_SETUP); 
                }

                continue;
            }

            v = IO_READ(USB_IN0_PTR_REG);
            if (v & USB_IN0_PTR_INT) {
                if (v & USB_IN0_PTR_REWIND) 
                    printf("rewind occurred !!\n");

                /* IN transaction (Device to Host) */
                xCur += 8;       
                IO_WRITE(USB_IN0_PTR_REG, USB_IN0_PTR_INT);
                if ((xCur <= xLen) && (xLen > 0)) { /* More data to send out */
                    len = ((xLen - xCur) > 8) ? 8 : xLen - xCur;
                    if (len == 0) {
                        if (hostAskSize > xLen) {
                            SETUP_EP0_IN(((int) in), 0);
                        }
                    } else {
                        memcpy(in, xbuf+xCur, len); 
                        SETUP_EP0_IN(((int) in), len);
                    }
                } else {
                    xLen = -1;
                }
                continue;
            }  
        }

        if (USB_CTRL_INT(ctrl) & 2) {
            printf("EP1 got transactions !!");
            IO_WRITE(USB_OUT1_PTR_REG, USB_OUT1_PTR_INT | USB_OUT1_PTR_VIOL);
            IO_WRITE(USB_IN1_PTR_REG, USB_IN1_PTR_INT | USB_IN1_PTR_VIOL);
            continue;
        }
        
        if (USB_CTRL_INT(ctrl) & 4) {
            IO_WRITE(USB_IN2_PTR_REG, USB_IN2_PTR_INT | USB_IN2_PTR_VIOL);
            rlen += IO_READ(USB_IN2_LEN_REG) >> USB_IN2_LEN_RUN_LEN_SHIFT;
            if (rlen < wlen) { 
                len = wlen-rlen > MAX_PKT_SIZE ? MAX_PKT_SIZE : wlen-rlen;
                memcpy(in, min+rlen, len);
                SETUP_EP2_IN(((int) in), len);
            } else rlen = wlen = 0;
            continue;
        }
        
        if (USB_CTRL_INT(ctrl) & 8) {
            IO_WRITE(USB_OUT3_PTR_REG, USB_OUT3_PTR_INT | USB_OUT3_PTR_VIOL); 
            len = IO_READ(USB_OUT3_LEN_REG) >> USB_OUT3_LEN_RUN_LEN_SHIFT;
            if (wlen == 0) {
                memcpy(in, out, len);
                SETUP_EP2_IN(((int) in), len);
            }
            memcpy(min+wlen, out, len);
            wlen += len;
            SETUP_EP3_OUT(((int) out), MAX_PKT_SIZE);
            continue;
        }
    }

    return 0;
}

int 
cpu1main(void)
{
    return 0;
}
