Angel David Yaguana Hernandez / USBHost

Dependencies:   FATFileSystem mbed-rtos

Dependents:   Proyect_Patric_electronic_door_MSC_Ok_ESP

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