Simple USBHost MSD(USB flash drive) for EA LPC4088 QSB test program

Dependencies:   LPC4088-USBHost mbed

EA LPC4088をUSBホストにしてUSBフラッシュメモリ(USB flash drive)を読み書きするテストプログラムです。
/media/uploads/va009039/lpc4088-msd-1.jpg
/media/uploads/va009039/lpc4088-msd-2.png

https://bitbucket.org/va009039/lpc4088_usbhost

Revision:
0:11152e69fc05
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/LPC4088-USBHost/USBHost/USBHALHost.cpp	Tue Apr 22 10:54:52 2014 +0000
@@ -0,0 +1,388 @@
+/* mbed USBHost Library
+ * Copyright (c) 2006-2013 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+ 
+#include "USBHALHost.h"
+//#define _USB_DBG
+#include "BaseUsbHostDebug.h"
+#include "BaseUsbHostTest.h"
+
+#ifndef CTASSERT
+template <bool>struct CtAssert;
+template <>struct CtAssert<true> {};
+#define CTASSERT(A) CtAssert<A>();
+#endif
+
+#ifdef _USB_DBG
+#define USB_DBG(...) do{fprintf(stderr,"[%s@%d] ",__PRETTY_FUNCTION__,__LINE__);fprintf(stderr,__VA_ARGS__);fprintf(stderr,"\n");} while(0);
+#define USB_DBG_HEX(A,B) debug_hex(A,B)
+void debug_hex(uint8_t* buf, int size);
+#else
+#define USB_DBG(...) while(0)
+#define USB_DBG_HEX(A,B) while(0)
+#endif
+
+#ifdef _USB_TEST
+#define USB_TEST_ASSERT(A) while(!(A)){fprintf(stderr,"\n\n%s@%d %s ASSERT!\n\n",__PRETTY_FUNCTION__,__LINE__,#A);exit(1);};
+#define USB_TEST_ASSERT_FALSE(A) USB_TEST_ASSERT(!(A))
+#else
+#define USB_TEST_ASSERT(A) while(0)
+#define USB_TEST_ASSERT_FALSE(A) while(0)
+#endif
+
+#define USB_INFO(...) do{fprintf(stderr,__VA_ARGS__);fprintf(stderr,"\n");}while(0);
+
+// bits of the USB/OTG clock control register
+#define HOST_CLK_EN     (1<<0)
+#define DEV_CLK_EN      (1<<1)
+#define PORTSEL_CLK_EN  (1<<3)
+#define AHB_CLK_EN      (1<<4)
+
+// bits of the USB/OTG clock status register
+#define HOST_CLK_ON     (1<<0)
+#define DEV_CLK_ON      (1<<1)
+#define PORTSEL_CLK_ON  (1<<3)
+#define AHB_CLK_ON      (1<<4)
+
+// we need host clock, OTG/portsel clock and AHB clock
+#define CLOCK_MASK (HOST_CLK_EN | PORTSEL_CLK_EN | AHB_CLK_EN)
+#define  FI                     0x2EDF           /* 12000 bits per frame (-1) */
+#define  DEFAULT_FMINTERVAL     ((((6 * (FI - 210)) / 7) << 16) | FI)
+
+USBHALHost* USBHALHost::instHost;
+
+USBHALHost::USBHALHost() {
+    instHost = this;
+}
+
+void USBHALHost::init() {
+    NVIC_DisableIRQ(USB_IRQn);
+    m_pHcca = new HCCA();
+    init_hw_ohci(m_pHcca);
+    ResetRootHub();
+    NVIC_SetVector(USB_IRQn, (uint32_t)_usbisr);
+    NVIC_SetPriority(USB_IRQn, 0);
+    NVIC_EnableIRQ(USB_IRQn);
+    
+#ifndef BASE_USBHOST
+    USB_INFO("Simple USBHost Library for EA LPC4088 QSB");
+    bool lowSpeed = false;
+    addDevice(NULL, 0, lowSpeed);
+#endif // BASE_USBHOST
+}
+
+void USBHALHost::init_hw_ohci(HCCA* pHcca) {
+    LPC_SC->PCONP &= ~(1UL<<31);    //Cut power
+    wait(1);
+    LPC_SC->PCONP |= (1UL<<31);     // turn on power for USB
+    LPC_USB->USBClkCtrl |= CLOCK_MASK; // Enable USB host clock, port selection and AHB clock
+    // Wait for clocks to become available
+    while ((LPC_USB->USBClkSt & CLOCK_MASK) != CLOCK_MASK)
+        ;
+    LPC_USB->OTGStCtrl |= 1;
+    LPC_USB->USBClkCtrl &= ~PORTSEL_CLK_EN;
+    
+#if defined(TARGET_LPC1768)
+    LPC_PINCON->PINSEL1 &= ~((3<<26) | (3<<28));  
+    LPC_PINCON->PINSEL1 |=  ((1<<26)|(1<<28));     // 0x14000000
+#elif defined(TARGET_LPC4088)
+    LPC_IOCON->P0_29 = 0x01; // USB_D+1
+    LPC_IOCON->P0_30 = 0x01; // USB_D-1
+    // DO NOT CHANGE P1_19.
+#else
+#error "target error"
+#endif
+    DBG("initialize OHCI\n");
+    wait_ms(100);                                   /* Wait 50 ms before apply reset              */
+    TEST_ASSERT((LPC_USB->HcRevision&0xff) == 0x10); // check revision
+    LPC_USB->HcControl       = 0;                       /* HARDWARE RESET                             */
+    LPC_USB->HcControlHeadED = 0;                       /* Initialize Control list head to Zero       */
+    LPC_USB->HcBulkHeadED    = 0;                       /* Initialize Bulk list head to Zero          */
+                                                        /* SOFTWARE RESET                             */
+    LPC_USB->HcCommandStatus = OR_CMD_STATUS_HCR;
+    LPC_USB->HcFmInterval    = DEFAULT_FMINTERVAL;      /* Write Fm Interval and Largest Data Packet Counter */
+    LPC_USB->HcPeriodicStart = FI*90/100;
+                                                      /* Put HC in operational state                */
+    LPC_USB->HcControl  = (LPC_USB->HcControl & (~OR_CONTROL_HCFS)) | OR_CONTROL_HC_OPER;
+    LPC_USB->HcRhStatus = OR_RH_STATUS_LPSC;            /* Set Global Power */
+    TEST_ASSERT(pHcca);
+    for (int i = 0; i < 32; i++) {
+        pHcca->InterruptTable[i] = NULL;
+    }
+    LPC_USB->HcHCCA = reinterpret_cast<uint32_t>(pHcca);
+    LPC_USB->HcInterruptStatus |= LPC_USB->HcInterruptStatus; /* Clear Interrrupt Status */
+    LPC_USB->HcInterruptEnable  = OR_INTR_ENABLE_MIE|OR_INTR_ENABLE_WDH|OR_INTR_ENABLE_FNO;
+
+    LPC_USB->HcRhPortStatus1 = OR_RH_PORT_CSC;
+    LPC_USB->HcRhPortStatus1 = OR_RH_PORT_PRSC;
+}
+
+void USBHALHost::ResetRootHub() {
+    wait_ms(100); /* USB 2.0 spec says at least 50ms delay before port reset */
+    LPC_USB->HcRhPortStatus1 = OR_RH_PORT_PRS; // Initiate port reset
+    DBG("Before loop\n");
+    while (LPC_USB->HcRhPortStatus1 & OR_RH_PORT_PRS)
+      ;
+    LPC_USB->HcRhPortStatus1 = OR_RH_PORT_PRSC; // ...and clear port reset signal
+    DBG("After loop\n");
+    wait_ms(200); /* Wait for 100 MS after port reset  */
+}
+
+void USBHALHost::enable(ENDPOINT_TYPE type) {
+    switch(type) {
+        case CONTROL_ENDPOINT:
+            LPC_USB->HcCommandStatus |= OR_CMD_STATUS_CLF;
+            LPC_USB->HcControl |= OR_CONTROL_CLE;
+            break;
+        case ISOCHRONOUS_ENDPOINT:
+            LPC_USB->HcControl |= OR_CONTROL_PLE;
+            break;
+        case BULK_ENDPOINT:
+            LPC_USB->HcCommandStatus |= OR_CMD_STATUS_BLF;
+            LPC_USB->HcControl |= OR_CONTROL_BLE;
+            break;
+        case INTERRUPT_ENDPOINT:
+            LPC_USB->HcControl |= OR_CONTROL_PLE;
+            break;
+    }
+}
+
+void USBHALHost::token_init(USBEndpoint* ep) {
+    if (ep->m_pED == NULL) {
+        ep->m_pED = new HCED(ep);
+        USB_DBG_ED(ep->m_pED);
+    }
+    HCED* ed = ep->m_pED;
+    USBDeviceConnected* dev = ep->getDevice();
+    USB_TEST_ASSERT(dev);
+    if (dev) {
+        uint8_t devAddr = dev->getAddress();
+        USB_DBG("devAddr=%02x", devAddr);
+        ed->setFunctionAddress(devAddr);
+    }
+    uint16_t size = ep->getSize();
+    USB_DBG("MaxPacketSize=%d", size);
+    ed->setMaxPacketSize(size);
+    if (ed->HeadTd == NULL) {
+        HCTD* td = new HCTD(ep);
+        ed->TailTd = td;
+        ed->HeadTd = td;
+        switch(ep->getType()) {
+            case CONTROL_ENDPOINT:
+                ed->Next = reinterpret_cast<HCED*>(LPC_USB->HcControlHeadED);
+                LPC_USB->HcControlHeadED = reinterpret_cast<uint32_t>(ed);
+                break;
+            case BULK_ENDPOINT:
+                ed->Next = reinterpret_cast<HCED*>(LPC_USB->HcBulkHeadED);
+                LPC_USB->HcBulkHeadED = reinterpret_cast<uint32_t>(ed);
+                break;
+            case INTERRUPT_ENDPOINT:
+                HCCA* pHcca = reinterpret_cast<HCCA*>(LPC_USB->HcHCCA);
+                ed->Next = pHcca->InterruptTable[0];
+                pHcca->InterruptTable[0] = ed;
+                break;
+        }
+        USB_DBG_ED(ed);
+    }
+}
+
+int USBHALHost::token_setup(USBEndpoint* ep, SETUP_PACKET* setup, uint16_t wLength) {
+    token_init(ep);
+    HCED* ed = ep->m_pED;
+    HCTD* td = ed->TailTd;
+    setup->wLength = wLength;
+    TBUF* tbuf = new(sizeof(SETUP_PACKET))TBUF(setup, sizeof(SETUP_PACKET));
+    td->transfer(tbuf, sizeof(SETUP_PACKET));
+    td->Control |= TD_TOGGLE_0|TD_SETUP; 
+    HCTD* blank = new HCTD(ep);
+    td->Next = blank;
+    ed->TailTd = blank;
+    //DBG_ED(ed);
+    enable(ep->getType());
+
+    td = ep->get_queue_HCTD();
+    TEST_ASSERT(td);
+    int result = td->getLengthTransferred();
+    DBG_TD(td);
+    delete tbuf;
+    delete td;
+    return result;
+}
+
+int USBHALHost::token_in(USBEndpoint* ep, uint8_t* data, int size, int retryLimit) {
+    token_init(ep);
+    HCED* ed = ep->m_pED;
+    HCTD* td = ed->TailTd;
+    TBUF* tbuf = NULL;
+    if (data != NULL) {
+        tbuf = new(size)TBUF();
+        td->transfer(tbuf, size);
+    }
+    td->Control |= TD_IN;
+    HCTD* blank = new HCTD(ep);
+    td->Next = blank;
+    ed->TailTd = blank;
+    USB_DBG_ED_IF(ed->EndpointNumber()==0, ed); // control transfer
+    enable(ep->getType());
+
+    td = ep->get_queue_HCTD();
+    TEST_ASSERT(td);
+    if (data != NULL) {
+        memcpy(data, tbuf->buf, size);
+        delete tbuf;
+    }
+    int result = td->getLengthTransferred();
+    delete td;
+    return result;
+}
+
+int USBHALHost::token_out(USBEndpoint* ep, const uint8_t* data, int size, int retryLimit) {
+    token_init(ep);
+    HCED* ed = ep->m_pED;
+    HCTD* td = ed->TailTd;
+    TBUF* tbuf = NULL;
+    if (data != NULL) {
+        tbuf = new(size)TBUF(data, size);
+        td->transfer(tbuf, size);
+    }
+    td->Control |= TD_OUT;
+    HCTD* blank = new HCTD(ep);
+    td->Next = blank;
+    ed->TailTd = blank;
+    DBG_ED(ed);
+    enable(ep->getType());
+
+    td = ep->get_queue_HCTD();
+    TEST_ASSERT(td);
+    if (data != NULL) {
+        delete tbuf;
+    }
+    int result = td->getLengthTransferred();
+    delete td;
+    return result;
+}
+
+void USBHALHost::token_inNB(USBEndpoint* ep, uint8_t* data, int size) {
+    token_init(ep);
+    HCED* ed = ep->m_pED;
+    HCTD* td = ed->TailTd;
+    TBUF* tbuf = new(size)TBUF();
+    td->transfer(tbuf, size);
+    td->Control |= TD_IN;
+    HCTD* blank = new HCTD(ep);
+    td->Next = blank;
+    ed->TailTd = blank;
+    enable(ep->getType());
+}
+
+USB_TYPE USBHALHost::token_inNB_result(USBEndpoint* ep) {
+    HCTD* td = ep->get_queue_HCTD(0);
+    if (td) {
+        int len = td->getLengthTransferred();
+        TBUF* tbuf = (TBUF*)td->buf_top;
+        memcpy(ep->getBufStart(), tbuf->buf, len);
+        ep->setLengthTransferred(len);
+        delete td;
+        delete tbuf;
+        return USB_TYPE_OK;
+    }
+    return USB_TYPE_PROCESSING;
+}
+
+void USBHALHost::_usbisr(void) {
+    if (instHost) {
+        instHost->UsbIrqhandler();
+    }
+}
+
+HCTD* td_reverse(HCTD* td)
+{
+    HCTD* result = NULL;
+    HCTD* next;
+    while(td) {
+        next = const_cast<HCTD*>(td->Next);
+        td->Next = result;
+        result = td;
+        td = next;
+    }
+    return result;
+}
+
+void USBHALHost::UsbIrqhandler() {
+    if (!(LPC_USB->HcInterruptStatus & LPC_USB->HcInterruptEnable)) {
+        return;
+    }
+    m_report_irq++;
+    uint32_t status = LPC_USB->HcInterruptStatus;
+    if (status & OR_INTR_STATUS_FNO) {
+        m_report_FNO++;
+    }
+    if (status & OR_INTR_STATUS_WDH) {
+        union {
+            HCTD* done_td;
+            uint32_t lsb;
+        };
+        done_td = const_cast<HCTD*>(m_pHcca->DoneHead);
+        TEST_ASSERT(done_td);
+        m_pHcca->DoneHead = NULL; // reset
+        if (lsb & 1) { // error ?
+            lsb &= ~1;
+        }
+        HCTD* td = td_reverse(done_td);
+        while(td) {
+            USBEndpoint* ep = td->ep;
+            TEST_ASSERT(ep);
+            if (ep) {
+                ep->irqWdhHandler(td);
+            }
+            td = td->Next;
+        }
+        m_report_WDH++;
+    }
+    LPC_USB->HcInterruptStatus = status; // Clear Interrrupt Status
+}
+
+HCTD::HCTD(USBEndpoint* obj) {
+    CTASSERT(sizeof(HCTD) == 36);
+    TEST_ASSERT(obj);
+    Control = TD_CC|TD_ROUNDING;
+    CurrBufPtr = NULL;
+    Next = NULL;
+    BufEnd = NULL;
+    buf_top = NULL;
+    buf_size = 0;
+    ep = obj;
+}
+
+HCED::HCED(USBEndpoint* ep) {
+    USBDeviceConnected* dev = ep->getDevice();
+    int devAddr = 0;
+    bool lowSpeed = false;
+    if (dev) {
+        devAddr = dev->getAddress();
+        lowSpeed = dev->getSpeed();
+    }
+    int ep_number = ep->getAddress();
+    int MaxPacketSize = ep->getSize();
+        Control =  devAddr        | /* USB address */
+        ((ep_number & 0x7F) << 7) | /* Endpoint address */
+        (ep_number!=0?(((ep_number&0x80)?2:1) << 11):0)| /* direction : Out = 1, 2 = In */
+        ((lowSpeed?1:0) << 13)    | /* speed full=0 low=1 */
+        (MaxPacketSize << 16);      /* MaxPkt Size */
+        TailTd = NULL;
+        HeadTd = NULL;
+        Next = NULL;
+}
+