Lcd companion boards support (VKLCD50RTA & VKLCD70RT)

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