doku newon / DokuUSBHostWithIso

Dependencies:   FATFileSystem mbed-rtos

Dependents:   Peach_AudioChannelDividerAndCompensator

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