Norimasa Okamoto / USBHost

Dependencies:   FATFileSystem mbed-rtos

Dependents:   USBHostC210_example USBHostC270_example GSwifi_ap_webcam n-bed-USBHostC270_example

Fork of USBHost by mbed official

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers USBHost.cpp Source File

USBHost.cpp

00001 /* mbed USBHost Library
00002  * Copyright (c) 2006-2013 ARM Limited
00003  *
00004  * Licensed under the Apache License, Version 2.0 (the "License");
00005  * you may not use this file except in compliance with the License.
00006  * You may obtain a copy of the License at
00007  *
00008  *     http://www.apache.org/licenses/LICENSE-2.0
00009  *
00010  * Unless required by applicable law or agreed to in writing, software
00011  * distributed under the License is distributed on an "AS IS" BASIS,
00012  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00013  * See the License for the specific language governing permissions and
00014  * limitations under the License.
00015  */
00016 
00017 
00018 #include "USBHost.h"
00019 #include "USBHostHub.h"
00020 #include "USBIsochronous.h"
00021 
00022 USBHost * USBHost::instHost = NULL;
00023 
00024 #define DEVICE_CONNECTED_EVENT      (1 << 0)
00025 #define DEVICE_DISCONNECTED_EVENT   (1 << 1)
00026 #define TD_PROCESSED_EVENT          (1 << 2)
00027 
00028 #define MAX_TRY_ENUMERATE_HUB       3
00029 
00030 #define MIN(a, b) ((a > b) ? b : a)
00031 
00032 DigitalOut l4(LED4);
00033 
00034 /**
00035 * How interrupts are processed:
00036 *    - new device connected:
00037 *       - a message is queued in queue_usb_event with the id DEVICE_CONNECTED_EVENT
00038 *       - when the usb_thread receives the event, it:
00039 *           - resets the device
00040 *           - reads the device descriptor
00041 *           - sets the address of the device
00042 *           - if it is a hub, enumerates it
00043 *   - device disconnected:
00044 *       - a message is queued in queue_usb_event with the id DEVICE_DISCONNECTED_EVENT
00045 *       - when the usb_thread receives the event, it:
00046 *           - free the device and all its children (hub)
00047 *   - td processed
00048 *       - a message is queued in queue_usb_event with the id TD_PROCESSED_EVENT
00049 *       - when the usb_thread receives the event, it:
00050 *           - call the callback attached to the endpoint where the td is attached
00051 */
00052 void USBHost::usb_process() {
00053     
00054     bool controlListState;
00055     bool bulkListState;
00056     bool interruptListState;
00057     USBEndpoint * ep;
00058     uint8_t i, j, res, timeout_set_addr = 10;
00059     uint8_t buf[8];
00060     bool too_many_hub;
00061     int idx;
00062 
00063 #if DEBUG_TRANSFER
00064     uint8_t * buf_transfer;
00065 #endif
00066         
00067 #if MAX_HUB_NB
00068     uint8_t k;
00069 #endif
00070     
00071     while(1) {
00072         osEvent evt = mail_usb_event.get();
00073         
00074         if (evt.status == osEventMail) {
00075             
00076             l4 = !l4;
00077             message_t * usb_msg = (message_t*)evt.value.p;
00078             
00079             switch (usb_msg->event_id) {
00080                 
00081                 // a new device has been connected
00082                 case DEVICE_CONNECTED_EVENT:
00083                     too_many_hub = false;
00084                     buf[4] = 0;
00085                 
00086                     usb_mutex.lock();
00087                     
00088                     for (i = 0; i < MAX_DEVICE_CONNECTED; i++) {
00089                         if (!deviceInUse[i]) {
00090                             USB_DBG_EVENT("new device connected: %p\r\n", &devices[i]);
00091                             devices[i].init(usb_msg->hub, usb_msg->port, usb_msg->lowSpeed);
00092                             deviceReset[i] = false;
00093                             deviceInited[i] = true;
00094                             break;
00095                         }
00096                     }
00097                     
00098                     if (i == MAX_DEVICE_CONNECTED) {
00099                         USB_ERR("Too many device connected!!\r\n");
00100                         deviceInited[i] = false;
00101                         usb_mutex.unlock();
00102                         continue;
00103                     }
00104                     
00105                     if (!controlEndpointAllocated) {
00106                         control = newEndpoint(CONTROL_ENDPOINT, OUT, 0x08, 0x00);
00107                         addEndpoint(NULL, 0, (USBEndpoint*)control);
00108                         controlEndpointAllocated = true;
00109                     }
00110                     
00111 #if MAX_HUB_NB
00112                     if (usb_msg->hub_parent)
00113                         devices[i].setHubParent((USBHostHub *)(usb_msg->hub_parent));
00114 #endif
00115                     
00116                     for (j = 0; j < timeout_set_addr; j++) {
00117                         
00118                         resetDevice(&devices[i]);
00119                         
00120                         // set size of control endpoint
00121                         devices[i].setSizeControlEndpoint(8);
00122                         
00123                         devices[i].activeAddress(false);
00124                         
00125                         // get first 8 bit of device descriptor
00126                         // and check if we deal with a hub
00127                         USB_DBG("usb_thread read device descriptor on dev: %p\r\n", &devices[i]);
00128                         res = getDeviceDescriptor(&devices[i], buf, 8);
00129                     
00130                         if (res != USB_TYPE_OK) {
00131                             USB_ERR("usb_thread could not read dev descr");
00132                             continue;
00133                         }
00134                     
00135                         // set size of control endpoint
00136                         devices[i].setSizeControlEndpoint(buf[7]);
00137                         
00138                         // second step: set an address to the device
00139                         res = setAddress(&devices[i], devices[i].getAddress());
00140                     
00141                         if (res != USB_TYPE_OK) {
00142                             USB_ERR("SET ADDR FAILED");
00143                             continue;
00144                         }
00145                         devices[i].activeAddress(true);
00146                         USB_DBG("Address of %p: %d", &devices[i], devices[i].getAddress());
00147                         
00148                         // try to read again the device descriptor to check if the device
00149                         // answers to its new address
00150                         res = getDeviceDescriptor(&devices[i], buf, 8);
00151                     
00152                         if (res == USB_TYPE_OK) {
00153                             break;
00154                         }
00155                         
00156                         Thread::wait(100);
00157                     }
00158                     
00159                     USB_INFO("New device connected: %p [hub: %d - port: %d]", &devices[i], usb_msg->hub, usb_msg->port);
00160                     
00161 #if MAX_HUB_NB
00162                     if (buf[4] == HUB_CLASS) {
00163                         for (k = 0; k < MAX_HUB_NB; k++) {
00164                             if (hub_in_use[k] == false) {
00165                                 for (uint8_t j = 0; j < MAX_TRY_ENUMERATE_HUB; j++) {
00166                                     if (hubs[k].connect(&devices[i])) {
00167                                         devices[i].hub = &hubs[k];
00168                                         hub_in_use[k] = true;
00169                                         break;
00170                                     }
00171                                 }
00172                                 if (hub_in_use[k] == true)
00173                                     break;
00174                             }
00175                         }
00176                         
00177                         if (k == MAX_HUB_NB) {
00178                             USB_ERR("Too many hubs connected!!\r\n");
00179                             too_many_hub = true;
00180                         }
00181                     }
00182                     
00183                     if (usb_msg->hub_parent)
00184                         ((USBHostHub *)(usb_msg->hub_parent))->deviceConnected(&devices[i]);
00185 #endif
00186                     
00187                     if ((i < MAX_DEVICE_CONNECTED) && !too_many_hub) {
00188                         deviceInUse[i] = true;
00189                     }
00190                     
00191                     usb_mutex.unlock();
00192                     
00193                     break;
00194                     
00195                 // a device has been disconnected
00196                 case DEVICE_DISCONNECTED_EVENT:
00197                     
00198                     usb_mutex.lock();
00199                 
00200                     controlListState = disableList(CONTROL_ENDPOINT);
00201                     bulkListState = disableList(BULK_ENDPOINT);
00202                     interruptListState = disableList(INTERRUPT_ENDPOINT);
00203                 
00204                     idx = findDevice(usb_msg->hub, usb_msg->port, (USBHostHub *)(usb_msg->hub_parent));
00205                     if (idx != -1) {
00206                         freeDevice((USBDeviceConnected*)&devices[idx]);
00207                     }
00208                     
00209                     if (controlListState) enableList(CONTROL_ENDPOINT);
00210                     if (bulkListState) enableList(BULK_ENDPOINT);
00211                     if (interruptListState) enableList(INTERRUPT_ENDPOINT);
00212                     
00213                     usb_mutex.unlock();
00214                     
00215                     break;
00216                     
00217                 // a td has been processed
00218                 // call callback on the ed associated to the td
00219                 // we are not in ISR -> users can use printf in their callback method
00220                 case TD_PROCESSED_EVENT:
00221                     ep = (USBEndpoint *) ((HCTD *)usb_msg->td_addr)->ep;
00222                     if (usb_msg->td_state == USB_TYPE_IDLE) {
00223                         USB_DBG_EVENT("call callback on td %p [ep: %p state: %s - dev: %p - %s]", usb_msg->td_addr, ep, ep->getStateString(), ep->dev, ep->dev->getName(ep->getIntfNb()));
00224 
00225 #if DEBUG_TRANSFER
00226                         if (ep->getDir() == IN) {
00227                             buf_transfer = ep->getBufStart();
00228                             printf("READ SUCCESS [%d bytes transferred - td: 0x%08X] on ep: [%p - addr: %02X]: ",  ep->getLengthTransferred(), usb_msg->td_addr, ep, ep->getAddress());
00229                             for (int i = 0; i < ep->getLengthTransferred(); i++)
00230                                 printf("%02X ", buf_transfer[i]);
00231                             printf("\r\n\r\n");
00232                         }
00233 #endif
00234                         ep->call();
00235                     } else {
00236                         idx = findDevice(ep->dev);
00237                         if (idx != -1) {
00238                             if (deviceInUse[idx]) {
00239                                 USB_WARN("td %p processed but not in idle state: %s [ep: %p - dev: %p - %s]", usb_msg->td_addr, ep->getStateString(), ep, ep->dev, ep->dev->getName(ep->getIntfNb()));
00240                                 ep->setState(USB_TYPE_IDLE);
00241                             }
00242                         }
00243                     }
00244                     break;
00245             }
00246             
00247             mail_usb_event.free(usb_msg);
00248         }
00249     }
00250 }
00251 
00252 /* static */void USBHost::usb_process_static(void const * arg) {
00253     ((USBHost *)arg)->usb_process();
00254 }
00255 
00256 USBHost::USBHost() : usbThread(USBHost::usb_process_static, (void *)this, osPriorityNormal, USB_THREAD_STACK)
00257 {
00258     headControlEndpoint = NULL;
00259     headBulkEndpoint = NULL;
00260     headInterruptEndpoint = NULL;
00261     tailControlEndpoint = NULL;
00262     tailBulkEndpoint = NULL;
00263     tailInterruptEndpoint = NULL;
00264 
00265     lenReportDescr = 0;
00266 
00267     controlEndpointAllocated = false;
00268 
00269     for (uint8_t i = 0; i < MAX_DEVICE_CONNECTED; i++) {
00270         deviceInUse[i] = false;
00271         devices[i].setAddress(i + 1);
00272         deviceReset[i] = false;
00273         deviceInited[i] = false;
00274         for (uint8_t j = 0; j < MAX_INTF; j++)
00275             deviceAttachedDriver[i][j] = false;
00276     }
00277     
00278 #if MAX_HUB_NB
00279     for (uint8_t i = 0; i < MAX_HUB_NB; i++) {
00280         hubs[i].setHost(this);
00281         hub_in_use[i] = false;
00282     }
00283 #endif
00284 }
00285 
00286 
00287 void USBHost::transferCompleted(volatile uint32_t addr)
00288 {
00289     uint8_t state;
00290 
00291     if(addr == NULL)
00292         return;
00293 
00294     volatile HCTD* tdList = NULL;
00295 
00296     //First we must reverse the list order and dequeue each TD
00297     do {
00298         volatile HCTD* td = (volatile HCTD*)addr;
00299         addr = (uint32_t)td->nextTD; //Dequeue from physical list
00300         td->nextTD = tdList; //Enqueue into reversed list
00301         tdList = td;
00302     } while(addr);
00303 
00304     while(tdList != NULL) {
00305         volatile HCTD* td = tdList;
00306         tdList = (volatile HCTD*)td->nextTD; //Dequeue element now as it could be modified below
00307         if (!isTD((uint8_t*)td)) { // ITD?
00308             HCITD* itd = (HCITD*)td;
00309             IsochronousEp* ep = itd->ep;
00310             if (ep) {
00311                 ep->irqWdhHandler(itd);
00312             }
00313             continue;
00314         }
00315         if (td->ep != NULL) {
00316             USBEndpoint * ep = (USBEndpoint *)(td->ep);
00317             
00318             if (((HCTD *)td)->control >> 28) {
00319                 state = ((HCTD *)td)->control >> 28;
00320             } else {
00321                 if (td->currBufPtr)
00322                     ep->setLengthTransferred((uint32_t)td->currBufPtr - (uint32_t)ep->getBufStart());
00323                 state = 16 /*USB_TYPE_IDLE*/;
00324             }
00325             
00326             ep->unqueueTransfer(td);
00327             
00328             if (ep->getType() != CONTROL_ENDPOINT) {
00329                 // callback on the processed td will be called from the usb_thread (not in ISR)
00330                 message_t * usb_msg = mail_usb_event.alloc();
00331                 usb_msg->event_id = TD_PROCESSED_EVENT;
00332                 usb_msg->td_addr = (void *)td;
00333                 usb_msg->td_state = state;
00334                 mail_usb_event.put(usb_msg);
00335             }
00336             ep->setState(state);
00337             ep->ep_queue.put((uint8_t*)1);
00338         }
00339     }
00340 }
00341 
00342 USBHost * USBHost::getHostInst()
00343 {
00344     if (instHost == NULL) {
00345         instHost = new USBHost();
00346         instHost->init();
00347     }
00348     return instHost;
00349 }
00350 
00351 
00352 /*
00353  * Called when a device has been connected
00354  * Called in ISR!!!! (no printf)
00355  */
00356 /* virtual */ void USBHost::deviceConnected(int hub, int port, bool lowSpeed, USBHostHub * hub_parent)
00357 {
00358     // be sure that the new device connected is not already connected...
00359     int idx = findDevice(hub, port, hub_parent);
00360     if (idx != -1) {
00361         if (deviceInited[idx])
00362             return;
00363     }
00364     
00365     message_t * usb_msg = mail_usb_event.alloc();
00366     usb_msg->event_id = DEVICE_CONNECTED_EVENT;
00367     usb_msg->hub = hub;
00368     usb_msg->port = port;
00369     usb_msg->lowSpeed = lowSpeed;
00370     usb_msg->hub_parent = hub_parent;
00371     mail_usb_event.put(usb_msg);
00372 }
00373 
00374 /*
00375  * Called when a device has been disconnected
00376  * Called in ISR!!!! (no printf)
00377  */
00378 /* virtual */ void USBHost::deviceDisconnected(int hub, int port, USBHostHub * hub_parent, volatile uint32_t addr)
00379 {
00380     // be sure that the device disconnected is connected...
00381     int idx = findDevice(hub, port, hub_parent);
00382     if (idx != -1) {
00383         if (!deviceInUse[idx])
00384             return;
00385     } else {
00386         return;
00387     }
00388     
00389     message_t * usb_msg = mail_usb_event.alloc();
00390     usb_msg->event_id = DEVICE_DISCONNECTED_EVENT;
00391     usb_msg->hub = hub;
00392     usb_msg->port = port;
00393     usb_msg->hub_parent = hub_parent;
00394     mail_usb_event.put(usb_msg);
00395 }
00396 
00397 void USBHost::freeDevice(USBDeviceConnected * dev)
00398 {
00399     USBEndpoint * ep = NULL;
00400     HCED * ed = NULL;
00401     
00402 #if MAX_HUB_NB
00403     if (dev->getClass() == HUB_CLASS) {
00404         if (dev->hub == NULL) {
00405             USB_ERR("HUB NULL!!!!!\r\n");
00406         } else {
00407             dev->hub->hubDisconnected();
00408             for (uint8_t i = 0; i < MAX_HUB_NB; i++) {
00409                 if (dev->hub == &hubs[i]) {
00410                     hub_in_use[i] = false;
00411                     break;
00412                 }
00413             }
00414         }
00415     }
00416     
00417     // notify hub parent that this device has been disconnected
00418     if (dev->getHubParent())
00419         dev->getHubParent()->deviceDisconnected(dev);
00420     
00421 #endif
00422     
00423     int idx = findDevice(dev);
00424     if (idx != -1) {
00425         deviceInUse[idx] = false;
00426         deviceReset[idx] = false;
00427 
00428         for (uint8_t j = 0; j < MAX_INTF; j++) {
00429             deviceAttachedDriver[idx][j] = false;
00430             if (dev->getInterface(j) != NULL) {
00431                 USB_DBG("FREE INTF %d on dev: %p, %p, nb_endpot: %d, %s", j, (void *)dev->getInterface(j), dev, dev->getInterface(j)->nb_endpoint, dev->getName(j));
00432                 for (int i = 0; i < dev->getInterface(j)->nb_endpoint; i++) {
00433                     if ((ep = dev->getEndpoint(j, i)) != NULL) {
00434                         ed = (HCED *)ep->getHCED();
00435                         ed->control |= (1 << 14); //sKip bit
00436                         unqueueEndpoint(ep);
00437 
00438                         freeTD((volatile uint8_t*)ep->getTDList()[0]);
00439                         freeTD((volatile uint8_t*)ep->getTDList()[1]);
00440 
00441                         freeED((uint8_t *)ep->getHCED());
00442                     }
00443                     printList(BULK_ENDPOINT);
00444                     printList(INTERRUPT_ENDPOINT);
00445                 }
00446                 USB_INFO("Device disconnected [%p - %s - hub: %d - port: %d]", dev, dev->getName(j), dev->getHub(), dev->getPort());
00447             }
00448         }
00449         dev->disconnect();
00450     }
00451 }
00452 
00453 
00454 void USBHost::unqueueEndpoint(USBEndpoint * ep)
00455 {
00456     USBEndpoint * prec = NULL;
00457     USBEndpoint * current = NULL;
00458 
00459     for (int i = 0; i < 2; i++) {
00460         current = (i == 0) ? (USBEndpoint*)headBulkEndpoint : (USBEndpoint*)headInterruptEndpoint;
00461         prec = current;
00462         while (current != NULL) {
00463             if (current == ep) {
00464                 if (current->nextEndpoint() != NULL) {
00465                     prec->queueEndpoint(current->nextEndpoint());
00466                     if (current == headBulkEndpoint) {
00467                         updateBulkHeadED((uint32_t)current->nextEndpoint()->getHCED());
00468                         headBulkEndpoint = current->nextEndpoint();
00469                     } else if (current == headInterruptEndpoint) {
00470                         updateInterruptHeadED((uint32_t)current->nextEndpoint()->getHCED());
00471                         headInterruptEndpoint = current->nextEndpoint();
00472                     }
00473                 }
00474                 // here we are dequeuing the queue of ed
00475                 // we need to update the tail pointer
00476                 else {
00477                     prec->queueEndpoint(NULL);
00478                     if (current == headBulkEndpoint) {
00479                         updateBulkHeadED(0);
00480                         headBulkEndpoint = current->nextEndpoint();
00481                     } else if (current == headInterruptEndpoint) {
00482                         updateInterruptHeadED(0);
00483                         headInterruptEndpoint = current->nextEndpoint();
00484                     }
00485                     
00486                     // modify tail
00487                     switch (current->getType()) {
00488                         case BULK_ENDPOINT:
00489                             tailBulkEndpoint = prec;
00490                             break;
00491                         case INTERRUPT_ENDPOINT:
00492                             tailInterruptEndpoint = prec;
00493                             break;
00494                     }
00495                 }
00496                 current->setState(USB_TYPE_FREE);
00497                 return;
00498             }
00499             prec = current;
00500             current = current->nextEndpoint();
00501         }
00502     }
00503 }
00504 
00505 
00506 USBDeviceConnected * USBHost::getDevice(uint8_t index)
00507 {
00508     if ((index >= MAX_DEVICE_CONNECTED) || (!deviceInUse[index])) {
00509         return NULL;
00510     }
00511     return (USBDeviceConnected*)&devices[index];
00512 }
00513 
00514 // create an USBEndpoint descriptor. the USBEndpoint is not linked
00515 USBEndpoint * USBHost::newEndpoint(ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir, uint32_t size, uint8_t addr)
00516 {
00517     int i = 0;
00518     HCED * ed = (HCED *)getED();
00519     HCTD* td_list[2] = { (HCTD*)getTD(), (HCTD*)getTD() };
00520 
00521     memset((void *)td_list[0], 0x00, sizeof(HCTD));
00522     memset((void *)td_list[1], 0x00, sizeof(HCTD));
00523 
00524     // search a free USBEndpoint
00525     for (i = 0; i < MAX_ENDPOINT; i++) {
00526         if (endpoints[i].getState() == USB_TYPE_FREE) {
00527             endpoints[i].init(ed, type, dir, size, addr, td_list);
00528             USB_DBG("USBEndpoint created (%p): type: %d, dir: %d, size: %d, addr: %d, state: %s", &endpoints[i], type, dir, size, addr, endpoints[i].getStateString());
00529             return &endpoints[i];
00530         }
00531     }
00532     USB_ERR("could not allocate more endpoints!!!!");
00533     return NULL;
00534 }
00535 
00536 
00537 USB_TYPE USBHost::resetDevice(USBDeviceConnected * dev)
00538 {
00539     int index = findDevice(dev);
00540     if (index != -1) {
00541         USB_DBG("Resetting hub %d, port %d\n", dev->getHub(), dev->getPort());
00542         Thread::wait(100);
00543         if (dev->getHub() == 0) {
00544             resetRootHub();
00545         }
00546 #if MAX_HUB_NB
00547         else {
00548             dev->getHubParent()->portReset(dev->getPort());
00549         }
00550 #endif
00551         Thread::wait(100);
00552         deviceReset[index] = true;
00553         return USB_TYPE_OK;
00554     }
00555     
00556     return USB_TYPE_ERROR;
00557 }
00558 
00559 // link the USBEndpoint to the linked list and attach an USBEndpoint to a device
00560 bool USBHost::addEndpoint(USBDeviceConnected * dev, uint8_t intf_nb, USBEndpoint * ep)
00561 {
00562 
00563     if (ep == NULL) {
00564         return false;
00565     }
00566 
00567     HCED * prevEd;
00568 
00569     // set device address in the USBEndpoint descriptor
00570     if (dev == NULL) {
00571         ep->setDeviceAddress(0);
00572     } else {
00573         ep->setDeviceAddress(dev->getAddress());
00574     }
00575 
00576     if ((dev != NULL) && dev->getSpeed()) {
00577         ep->setSpeed(dev->getSpeed());
00578     }
00579     
00580     ep->setIntfNb(intf_nb);
00581 
00582     // queue the new USBEndpoint on the ED list
00583     switch (ep->getType()) {
00584 
00585         case CONTROL_ENDPOINT:
00586             prevEd = ( HCED*) controlHeadED();
00587             if (!prevEd) {
00588                 updateControlHeadED((uint32_t) ep->getHCED());
00589                 USB_DBG_TRANSFER("First control USBEndpoint: %08X", (uint32_t) ep->getHCED());
00590                 headControlEndpoint = ep;
00591                 tailControlEndpoint = ep;
00592                 return true;
00593             }
00594             tailControlEndpoint->queueEndpoint(ep);
00595             tailControlEndpoint = ep;
00596             return true;
00597 
00598         case BULK_ENDPOINT:
00599             prevEd = ( HCED*) bulkHeadED();
00600             if (!prevEd) {
00601                 updateBulkHeadED((uint32_t) ep->getHCED());
00602                 USB_DBG_TRANSFER("First bulk USBEndpoint: %08X\r\n", (uint32_t) ep->getHCED());
00603                 headBulkEndpoint = ep;
00604                 tailBulkEndpoint = ep;
00605                 break;
00606             }
00607             USB_DBG_TRANSFER("Queue BULK Ed %p after %p\r\n",ep->getHCED(), prevEd);
00608             tailBulkEndpoint->queueEndpoint(ep);
00609             tailBulkEndpoint = ep;
00610             break;
00611 
00612         case INTERRUPT_ENDPOINT:
00613             prevEd = ( HCED*) interruptHeadED();
00614             if (!prevEd) {
00615                 updateInterruptHeadED((uint32_t) ep->getHCED());
00616                 USB_DBG_TRANSFER("First interrupt USBEndpoint: %08X\r\n", (uint32_t) ep->getHCED());
00617                 headInterruptEndpoint = ep;
00618                 tailInterruptEndpoint = ep;
00619                 break;
00620             }
00621             USB_DBG_TRANSFER("Queue INTERRUPT Ed %p after %p\r\n",ep->getHCED(), prevEd);
00622             tailInterruptEndpoint->queueEndpoint(ep);
00623             tailInterruptEndpoint = ep;
00624             break;
00625         default:
00626             return false;
00627     }
00628     
00629     ep->dev = dev;
00630     dev->addEndpoint(intf_nb, ep);
00631 
00632     return true;
00633 }
00634 
00635 
00636 int USBHost::findDevice(USBDeviceConnected * dev)
00637 {
00638     for (int i = 0; i < MAX_DEVICE_CONNECTED; i++) {
00639         if (dev == &devices[i]) {
00640             return i;
00641         }
00642     }
00643     return -1;
00644 }
00645 
00646 int USBHost::findDevice(uint8_t hub, uint8_t port, USBHostHub * hub_parent)
00647 {
00648     for (int i = 0; i < MAX_DEVICE_CONNECTED; i++) {
00649         if (devices[i].getHub() == hub && devices[i].getPort() == port) {
00650             if (hub_parent != NULL) {
00651                 if (hub_parent == devices[i].getHubParent())
00652                     return i;
00653             } else {
00654                 return i;
00655             }
00656         }
00657     }
00658     return -1;
00659 }
00660 
00661 void USBHost::printList(ENDPOINT_TYPE type)
00662 {
00663 #if DEBUG_EP_STATE
00664     volatile HCED * hced;
00665     switch(type) {
00666         case CONTROL_ENDPOINT:
00667             hced = (HCED *)controlHeadED();
00668             break;
00669         case BULK_ENDPOINT:
00670             hced = (HCED *)bulkHeadED();
00671             break;
00672         case INTERRUPT_ENDPOINT:
00673             hced = (HCED *)interruptHeadED();
00674             break;
00675     }
00676     volatile HCTD * hctd = NULL;
00677     const char * type_str = (type == BULK_ENDPOINT) ? "BULK" :
00678                             ((type == INTERRUPT_ENDPOINT) ? "INTERRUPT" :
00679                             ((type == CONTROL_ENDPOINT) ? "CONTROL" : "ISOCHRONOUS"));
00680     printf("State of %s:\r\n", type_str);
00681     while (hced != NULL) {
00682         uint8_t dir = ((hced->control & (3 << 11)) >> 11);
00683         printf("hced: %p [ADDR: %d, DIR: %s, EP_NB: 0x%X]\r\n", hced,
00684                                                    hced->control & 0x7f,
00685                                                    (dir == 1) ? "OUT" : ((dir == 0) ? "FROM_TD":"IN"),
00686                                                     (hced->control & (0xf << 7)) >> 7);
00687         hctd = (HCTD *)((uint32_t)(hced->headTD) & ~(0xf));
00688         while (hctd != hced->tailTD) {
00689             printf("\thctd: %p [DIR: %s]\r\n", hctd, ((hctd->control & (3 << 19)) >> 19) == 1 ? "OUT" : "IN");
00690             hctd = hctd->nextTD;
00691         }
00692         printf("\thctd: %p\r\n", hctd);
00693         hced = hced->nextED;
00694     }
00695     printf("\r\n\r\n");
00696 #endif
00697 }
00698 
00699 
00700 // add a transfer on the TD linked list
00701 USB_TYPE USBHost::addTransfer(USBEndpoint * ed, uint8_t * buf, uint32_t len)
00702 {
00703     td_mutex.lock();
00704 
00705     // allocate a TD which will be freed in TDcompletion
00706     volatile HCTD * td = ed->getNextTD();
00707     if (td == NULL) {
00708         return USB_TYPE_ERROR;
00709     }
00710 
00711     uint32_t token = (ed->isSetup() ? TD_SETUP : ( (ed->getDir() == IN) ? TD_IN : TD_OUT ));
00712 
00713     uint32_t td_toggle;
00714 
00715     if (ed->getType() == CONTROL_ENDPOINT) {
00716         if (ed->isSetup()) {
00717             td_toggle = TD_TOGGLE_0;
00718         } else {
00719             td_toggle = TD_TOGGLE_1;
00720         }
00721     } else {
00722         td_toggle = 0;
00723     }
00724 
00725     td->control      = (TD_ROUNDING | token | TD_DELAY_INT(0) | td_toggle | TD_CC);
00726     td->currBufPtr   = buf;
00727     td->bufEnd       = (buf + (len - 1));
00728 
00729     ENDPOINT_TYPE type = ed->getType();
00730 
00731     disableList(type);
00732     ed->queueTransfer();
00733     printList(type);
00734     enableList(type);
00735     
00736     td_mutex.unlock();
00737 
00738     return USB_TYPE_PROCESSING;
00739 }
00740 
00741 
00742 
00743 USB_TYPE USBHost::getDeviceDescriptor(USBDeviceConnected * dev, uint8_t * buf, uint16_t max_len_buf, uint16_t * len_dev_descr)
00744 {
00745     USB_TYPE t = controlRead(  dev,
00746                          USB_DEVICE_TO_HOST | USB_RECIPIENT_DEVICE,
00747                          GET_DESCRIPTOR,
00748                          (DEVICE_DESCRIPTOR << 8) | (0),
00749                          0, buf, MIN(DEVICE_DESCRIPTOR_LENGTH, max_len_buf));
00750     if (len_dev_descr)
00751         *len_dev_descr = MIN(DEVICE_DESCRIPTOR_LENGTH, max_len_buf);
00752     
00753     return t;
00754 }
00755 
00756 USB_TYPE USBHost::getConfigurationDescriptor(USBDeviceConnected * dev, uint8_t * buf, uint16_t max_len_buf, uint16_t * len_conf_descr)
00757 {
00758     USB_TYPE res;
00759     uint16_t total_conf_descr_length = 0;
00760 
00761     // fourth step: get the beginning of the configuration descriptor to have the total length of the conf descr
00762     res = controlRead(  dev,
00763                         USB_DEVICE_TO_HOST | USB_RECIPIENT_DEVICE,
00764                         GET_DESCRIPTOR,
00765                         (CONFIGURATION_DESCRIPTOR << 8) | (0),
00766                         0, buf, CONFIGURATION_DESCRIPTOR_LENGTH);
00767 
00768     if (res != USB_TYPE_OK) {
00769         USB_ERR("GET CONF 1 DESCR FAILED");
00770         return res;
00771     }
00772     total_conf_descr_length = buf[2] | (buf[3] << 8);
00773     total_conf_descr_length = MIN(max_len_buf, total_conf_descr_length);
00774     
00775     if (len_conf_descr)
00776         *len_conf_descr = total_conf_descr_length;
00777     
00778     USB_DBG("TOTAL_LENGTH: %d \t NUM_INTERF: %d", total_conf_descr_length, buf[4]);
00779 
00780     return controlRead(  dev,
00781                          USB_DEVICE_TO_HOST | USB_RECIPIENT_DEVICE,
00782                          GET_DESCRIPTOR,
00783                          (CONFIGURATION_DESCRIPTOR << 8) | (0),
00784                          0, buf, total_conf_descr_length);
00785 }
00786 
00787 
00788 USB_TYPE USBHost::setAddress(USBDeviceConnected * dev, uint8_t address) {
00789     return controlWrite(    dev,
00790                             USB_HOST_TO_DEVICE | USB_RECIPIENT_DEVICE,
00791                             SET_ADDRESS,
00792                             address,
00793                             0, NULL, 0);
00794     
00795 }
00796 
00797 USB_TYPE USBHost::setConfiguration(USBDeviceConnected * dev, uint8_t conf)
00798 {
00799     return controlWrite( dev,
00800                          USB_HOST_TO_DEVICE | USB_RECIPIENT_DEVICE,
00801                          SET_CONFIGURATION,
00802                          conf,
00803                          0, NULL, 0);
00804 }
00805 
00806 uint8_t USBHost::numberDriverAttached(USBDeviceConnected * dev) {
00807     int index = findDevice(dev);
00808     uint8_t cnt = 0;
00809     if (index == -1)
00810         return 0;
00811     for (uint8_t i = 0; i < MAX_INTF; i++) {
00812         if (deviceAttachedDriver[index][i])
00813             cnt++;
00814     }
00815     return cnt;
00816 }
00817 
00818 // enumerate a device with the control USBEndpoint
00819 USB_TYPE USBHost::enumerate(USBDeviceConnected * dev, IUSBEnumerator* pEnumerator)
00820 {
00821     uint16_t total_conf_descr_length = 0;
00822     USB_TYPE res;
00823     
00824     usb_mutex.lock();
00825     
00826     // don't enumerate a device which all interfaces are registered to a specific driver
00827     int index = findDevice(dev);
00828     
00829     if (index == -1) {
00830         usb_mutex.unlock();
00831         return USB_TYPE_ERROR;
00832     }
00833     
00834     uint8_t nb_intf_attached = numberDriverAttached(dev);
00835     USB_DBG("dev: %p nb_intf: %d", dev, dev->getNbIntf());
00836     USB_DBG("dev: %p nb_intf_attached: %d", dev, nb_intf_attached);
00837     if ((nb_intf_attached != 0) && (dev->getNbIntf() == nb_intf_attached)) {
00838         USB_DBG("Don't enumerate dev: %p because all intf are registered with a driver", dev);
00839         usb_mutex.unlock();
00840         return USB_TYPE_OK;
00841     }
00842     
00843     USB_DBG("Enumerate dev: %p", dev);
00844     
00845     // third step: get the whole device descriptor to see vid, pid
00846     res = getDeviceDescriptor(dev, data, DEVICE_DESCRIPTOR_LENGTH);
00847 
00848     if (res != USB_TYPE_OK) {
00849         USB_DBG("GET DEV DESCR FAILED");
00850         usb_mutex.unlock();
00851         return res;
00852     }
00853     
00854     dev->setClass(data[4]);
00855     dev->setSubClass(data[5]);
00856     dev->setProtocol(data[6]);
00857     dev->setVid(data[8] | (data[9] << 8));
00858     dev->setPid(data[10] | (data[11] << 8));
00859     USB_DBG("CLASS: %02X \t VID: %04X \t PID: %04X", data[4], data[8] | (data[9] << 8), data[10] | (data[11] << 8));
00860 
00861     pEnumerator->setVidPid( data[8] | (data[9] << 8), data[10] | (data[11] << 8) );
00862 
00863     res = getConfigurationDescriptor(dev, data, sizeof(data), &total_conf_descr_length);
00864     if (res != USB_TYPE_OK) {
00865         usb_mutex.unlock();
00866         return res;
00867     }
00868 
00869 #if DEBUG
00870     USB_DBG("CONFIGURATION DESCRIPTOR:\r\n");
00871     for (int i = 0; i < total_conf_descr_length; i++)
00872         printf("%02X ", data[i]);
00873     printf("\r\n\r\n");
00874 #endif
00875 
00876     // Parse the configuration descriptor
00877     parseConfDescr(dev, data, total_conf_descr_length, pEnumerator);
00878 
00879     // only set configuration if not enumerated before
00880     if (!dev->isEnumerated()) {
00881         
00882         USB_DBG("Set configuration 1 on dev: %p", dev);
00883         // sixth step: set configuration (only 1 supported)
00884         res = setConfiguration(dev, 1);
00885 
00886         if (res != USB_TYPE_OK) {
00887             USB_DBG("SET CONF FAILED");
00888             usb_mutex.unlock();
00889             return res;
00890         }
00891     }
00892     
00893     dev->setEnumerated();
00894 
00895     // Now the device is enumerated!
00896     USB_DBG("dev %p is enumerated\r\n", dev);
00897     usb_mutex.unlock();
00898 
00899     // Some devices may require this delay
00900     wait_ms(100);
00901 
00902     return USB_TYPE_OK;
00903 }
00904 // this method fills the USBDeviceConnected object: class,.... . It also add endpoints found in the descriptor.
00905 void USBHost::parseConfDescr(USBDeviceConnected * dev, uint8_t * conf_descr, uint32_t len, IUSBEnumerator* pEnumerator)
00906 {
00907     uint32_t index = 0;
00908     uint32_t len_desc = 0;
00909     uint8_t id = 0;
00910     int nb_endpoints_used = 0;
00911     USBEndpoint * ep = NULL;
00912     uint8_t intf_nb = 0;
00913     bool parsing_intf = false;
00914     uint8_t current_intf = 0;
00915 
00916     while (index < len) {
00917         len_desc = conf_descr[index];
00918         id = conf_descr[index+1];
00919         switch (id) {
00920             case CONFIGURATION_DESCRIPTOR:
00921                 USB_DBG("dev: %p has %d intf", dev, conf_descr[4]);
00922                 dev->setNbIntf(conf_descr[4]);
00923                 break;
00924             case INTERFACE_DESCRIPTOR:
00925                 if(pEnumerator->parseInterface(conf_descr[index + 2], conf_descr[index + 5], conf_descr[index + 6], conf_descr[index + 7])) {
00926                     if (intf_nb++ <= MAX_INTF) {
00927                         current_intf = conf_descr[index + 2];
00928                         dev->addInterface(current_intf, conf_descr[index + 5], conf_descr[index + 6], conf_descr[index + 7]);
00929                         nb_endpoints_used = 0;
00930                         USB_DBG("ADD INTF %d on device %p: class: %d, subclass: %d, proto: %d", current_intf, dev, conf_descr[index + 5],conf_descr[index + 6],conf_descr[index + 7]);
00931                     } else {
00932                         USB_DBG("Drop intf...");
00933                     }
00934                     parsing_intf = true;
00935                 } else {
00936                     parsing_intf = false;
00937                 }
00938                 break;
00939             case ENDPOINT_DESCRIPTOR:
00940                 if (parsing_intf && (intf_nb <= MAX_INTF) ) {
00941                     if (nb_endpoints_used < MAX_ENDPOINT_PER_INTERFACE) {
00942                         if( pEnumerator->useEndpoint(current_intf, (ENDPOINT_TYPE)(conf_descr[index + 3] & 0x03), (ENDPOINT_DIRECTION)((conf_descr[index + 2] >> 7) + 1)) ) {
00943                             // if the USBEndpoint is isochronous -> skip it (TODO: fix this)
00944                             if ((conf_descr[index + 3] & 0x03) != ISOCHRONOUS_ENDPOINT) {
00945                                 ep = newEndpoint((ENDPOINT_TYPE)(conf_descr[index+3] & 0x03),
00946                                                  (ENDPOINT_DIRECTION)((conf_descr[index + 2] >> 7) + 1),
00947                                                  conf_descr[index + 4] | (conf_descr[index + 5] << 8),
00948                                                  conf_descr[index + 2] & 0x0f);
00949                                 USB_DBG("ADD USBEndpoint %p, on interf %d on device %p", ep, current_intf, dev);
00950                                 if (ep != NULL && dev != NULL) {
00951                                     addEndpoint(dev, current_intf, ep);
00952                                 } else {
00953                                     USB_DBG("EP NULL");
00954                                 }
00955                                 nb_endpoints_used++;
00956                             } else {
00957                                 USB_DBG("ISO USBEndpoint NOT SUPPORTED");
00958                             }
00959                         }
00960                     }
00961                 }
00962                 break;
00963             case HID_DESCRIPTOR:
00964                 lenReportDescr = conf_descr[index + 7] | (conf_descr[index + 8] << 8);
00965                 break;
00966             default:
00967                 break;
00968         }
00969         index += len_desc;
00970     }
00971 }
00972 
00973 
00974 USB_TYPE USBHost::bulkWrite(USBDeviceConnected * dev, USBEndpoint * ep, uint8_t * buf, uint32_t len, bool blocking)
00975 {
00976     return generalTransfer(dev, ep, buf, len, blocking, BULK_ENDPOINT, true);
00977 }
00978 
00979 USB_TYPE USBHost::bulkRead(USBDeviceConnected * dev, USBEndpoint * ep, uint8_t * buf, uint32_t len, bool blocking)
00980 {
00981     return generalTransfer(dev, ep, buf, len, blocking, BULK_ENDPOINT, false);
00982 }
00983 
00984 USB_TYPE USBHost::interruptWrite(USBDeviceConnected * dev, USBEndpoint * ep, uint8_t * buf, uint32_t len, bool blocking)
00985 {
00986     return generalTransfer(dev, ep, buf, len, blocking, INTERRUPT_ENDPOINT, true);
00987 }
00988 
00989 USB_TYPE USBHost::interruptRead(USBDeviceConnected * dev, USBEndpoint * ep, uint8_t * buf, uint32_t len, bool blocking)
00990 {
00991     return generalTransfer(dev, ep, buf, len, blocking, INTERRUPT_ENDPOINT, false);
00992 }
00993 
00994 USB_TYPE USBHost::generalTransfer(USBDeviceConnected * dev, USBEndpoint * ep, uint8_t * buf, uint32_t len, bool blocking, ENDPOINT_TYPE type, bool write) {
00995     
00996 #if DEBUG_TRANSFER
00997     const char * type_str = (type == BULK_ENDPOINT) ? "BULK" : ((type == INTERRUPT_ENDPOINT) ? "INTERRUPT" : "ISOCHRONOUS");
00998     USB_DBG_TRANSFER("----- %s %s [dev: %p - %s - hub: %d - port: %d - addr: %d - ep: %02X]------", type_str, (write) ? "WRITE" : "READ", dev, dev->getName(ep->getIntfNb()), dev->getHub(), dev->getPort(), dev->getAddress(), ep->getAddress());
00999 #endif
01000     
01001     usb_mutex.lock();
01002     
01003     USB_TYPE res;
01004     ENDPOINT_DIRECTION dir = (write) ? OUT : IN;
01005     
01006     if (dev == NULL) {
01007         USB_ERR("dev NULL");
01008         usb_mutex.unlock();
01009         return USB_TYPE_ERROR;
01010     }
01011 
01012     if (ep == NULL) {
01013         USB_ERR("ep NULL");
01014         usb_mutex.unlock();
01015         return USB_TYPE_ERROR;
01016     }
01017 
01018     if (ep->getState() != USB_TYPE_IDLE) {
01019         USB_WARN("[ep: %p - dev: %p - %s] NOT IDLE: %s", ep, ep->dev, ep->dev->getName(ep->getIntfNb()), ep->getStateString());
01020         usb_mutex.unlock();
01021         return ep->getState();
01022     }
01023 
01024     if ((ep->getDir() != dir) || (ep->getType() != type)) {
01025         USB_ERR("[ep: %p - dev: %p] wrong dir or bad USBEndpoint type", ep, ep->dev);
01026         usb_mutex.unlock();
01027         return USB_TYPE_ERROR;
01028     }
01029 
01030     if (dev->getAddress() != ep->getDeviceAddress()) {
01031         USB_ERR("[ep: %p - dev: %p] USBEndpoint addr and device addr don't match", ep, ep->dev);
01032         usb_mutex.unlock();
01033         return USB_TYPE_ERROR;
01034     }
01035     
01036 #if DEBUG_TRANSFER
01037     if (write) {
01038         USB_DBG_TRANSFER("%s WRITE buffer", type_str);
01039         for (int i = 0; i < ep->getLengthTransferred(); i++)
01040             printf("%02X ", buf[i]);
01041         printf("\r\n\r\n");
01042     }
01043 #endif
01044     addTransfer(ep, buf, len);
01045 
01046     if (blocking) {
01047         
01048         ep->ep_queue.get();
01049         res = ep->getState();
01050         
01051         USB_DBG_TRANSFER("%s TRANSFER res: %s on ep: %p\r\n", type_str, ep->getStateString(), ep);
01052         
01053         if (res != USB_TYPE_IDLE) {
01054             usb_mutex.unlock();
01055             return res;
01056         }
01057         
01058         usb_mutex.unlock();
01059         return USB_TYPE_OK;
01060     }
01061     
01062     usb_mutex.unlock();
01063     return USB_TYPE_PROCESSING;
01064 
01065 }
01066 
01067 
01068 USB_TYPE USBHost::controlRead(USBDeviceConnected * dev, uint8_t requestType, uint8_t request, uint32_t value, uint32_t index, uint8_t * buf, uint32_t len) {
01069     return controlTransfer(dev, requestType, request, value, index, buf, len, false);
01070 }
01071 
01072 USB_TYPE USBHost::controlWrite(USBDeviceConnected * dev, uint8_t requestType, uint8_t request, uint32_t value, uint32_t index, uint8_t * buf, uint32_t len) {
01073     return controlTransfer(dev, requestType, request, value, index, buf, len, true);
01074 }
01075 
01076 USB_TYPE USBHost::controlTransfer(USBDeviceConnected * dev, uint8_t requestType, uint8_t request, uint32_t value, uint32_t index, uint8_t * buf, uint32_t len, bool write)
01077 {
01078     usb_mutex.lock();
01079     USB_DBG_TRANSFER("----- CONTROL %s [dev: %p - hub: %d - port: %d] ------", (write) ? "WRITE" : "READ", dev, dev->getHub(), dev->getPort());
01080 
01081     int length_transfer = len;
01082     USB_TYPE res;
01083     uint32_t token;
01084 
01085     control->setSpeed(dev->getSpeed());
01086     control->setSize(dev->getSizeControlEndpoint());
01087     if (dev->isActiveAddress()) {
01088         control->setDeviceAddress(dev->getAddress());
01089     } else {
01090         control->setDeviceAddress(0);
01091     }
01092 
01093     USB_DBG_TRANSFER("Control transfer on device: %d\r\n", control->getDeviceAddress());
01094     fillControlBuf(requestType, request, value, index, len);
01095 
01096 #if DEBUG_TRANSFER
01097     USB_DBG_TRANSFER("SETUP PACKET: ");
01098     for (int i = 0; i < 8; i++)
01099         printf("%01X ", setupPacket[i]);
01100     printf("\r\n");
01101 #endif
01102 
01103     control->setNextToken(TD_SETUP);
01104     addTransfer(control, (uint8_t*)setupPacket, 8);
01105 
01106     control->ep_queue.get();
01107     res = control->getState();
01108 
01109     USB_DBG_TRANSFER("CONTROL setup stage %s", control->getStateString());
01110 
01111     if (res != USB_TYPE_IDLE) {
01112         usb_mutex.unlock();
01113         return res;
01114     }
01115 
01116     if (length_transfer) {
01117         token = (write) ? TD_OUT : TD_IN;
01118         control->setNextToken(token);
01119         addTransfer(control, (uint8_t *)buf, length_transfer);
01120 
01121         control->ep_queue.get();
01122         res = control->getState();
01123 
01124 #if DEBUG_TRANSFER
01125         USB_DBG_TRANSFER("CONTROL %s stage %s", (write) ? "WRITE" : "READ", control->getStateString());
01126         if (write) {
01127             USB_DBG_TRANSFER("CONTROL WRITE buffer");
01128             for (int i = 0; i < control->getLengthTransferred(); i++)
01129                 printf("%02X ", buf[i]);
01130             printf("\r\n\r\n");
01131         } else {
01132             USB_DBG_TRANSFER("CONTROL READ SUCCESS [%d bytes transferred]", control->getLengthTransferred());
01133             for (int i = 0; i < control->getLengthTransferred(); i++)
01134                 printf("%02X ", buf[i]);
01135             printf("\r\n\r\n");
01136         }
01137 #endif
01138 
01139         if (res != USB_TYPE_IDLE) {
01140             usb_mutex.unlock();
01141             return res;
01142         }
01143     }
01144 
01145     token = (write) ? TD_IN : TD_OUT;
01146     control->setNextToken(token);
01147     addTransfer(control, NULL, 0);
01148 
01149     control->ep_queue.get();
01150     res = control->getState();
01151 
01152     USB_DBG_TRANSFER("CONTROL ack stage %s", control->getStateString());
01153     usb_mutex.unlock();
01154 
01155     if (res != USB_TYPE_IDLE)
01156         return res;
01157 
01158     return USB_TYPE_OK;
01159 }
01160 
01161 
01162 void USBHost::fillControlBuf(uint8_t requestType, uint8_t request, uint16_t value, uint16_t index, int len)
01163 {
01164 #ifdef __BIG_ENDIAN
01165 #error "Must implement BE to LE conv here"
01166 #endif
01167     setupPacket[0] = requestType;
01168     setupPacket[1] = request;
01169     //We are in LE so it's fine
01170     *((uint16_t*)&setupPacket[2]) = value;
01171     *((uint16_t*)&setupPacket[4]) = index;
01172     *((uint16_t*)&setupPacket[6]) = (uint32_t) len;
01173 }