iPXE
usb.c
Go to the documentation of this file.
00001 /*
00002  * Copyright (C) 2014 Michael Brown <mbrown@fensystems.co.uk>.
00003  *
00004  * This program is free software; you can redistribute it and/or
00005  * modify it under the terms of the GNU General Public License as
00006  * published by the Free Software Foundation; either version 2 of the
00007  * License, or (at your option) any later version.
00008  *
00009  * This program is distributed in the hope that it will be useful, but
00010  * WITHOUT ANY WARRANTY; without even the implied warranty of
00011  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012  * General Public License for more details.
00013  *
00014  * You should have received a copy of the GNU General Public License
00015  * along with this program; if not, write to the Free Software
00016  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
00017  * 02110-1301, USA.
00018  *
00019  * You can also choose to distribute this program under the terms of
00020  * the Unmodified Binary Distribution Licence (as given in the file
00021  * COPYING.UBDL), provided that you have satisfied its requirements.
00022  */
00023 
00024 FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );
00025 
00026 #include <stdlib.h>
00027 #include <stdio.h>
00028 #include <string.h>
00029 #include <strings.h>
00030 #include <unistd.h>
00031 #include <errno.h>
00032 #include <assert.h>
00033 #include <byteswap.h>
00034 #include <ipxe/usb.h>
00035 #include <ipxe/cdc.h>
00036 
00037 /** @file
00038  *
00039  * Universal Serial Bus (USB)
00040  *
00041  */
00042 
00043 /** List of USB buses */
00044 struct list_head usb_buses = LIST_HEAD_INIT ( usb_buses );
00045 
00046 /** List of changed ports */
00047 static struct list_head usb_changed = LIST_HEAD_INIT ( usb_changed );
00048 
00049 /** List of halted endpoints */
00050 static struct list_head usb_halted = LIST_HEAD_INIT ( usb_halted );
00051 
00052 /******************************************************************************
00053  *
00054  * Utility functions
00055  *
00056  ******************************************************************************
00057  */
00058 
00059 /**
00060  * Get USB speed name (for debugging)
00061  *
00062  * @v speed             Speed
00063  * @ret name            Speed name
00064  */
00065 static inline const char * usb_speed_name ( unsigned int speed ) {
00066         static const char *exponents[4] = { "", "k", "M", "G" };
00067         static char buf[ 10 /* "xxxxxXbps" + NUL */ ];
00068         unsigned int mantissa;
00069         unsigned int exponent;
00070 
00071         /* Extract mantissa and exponent */
00072         mantissa = USB_SPEED_MANTISSA ( speed );
00073         exponent = USB_SPEED_EXPONENT ( speed );
00074 
00075         /* Name speed */
00076         switch ( speed ) {
00077         case USB_SPEED_NONE:            return "DETACHED";
00078         case USB_SPEED_LOW:             return "low";
00079         case USB_SPEED_FULL:            return "full";
00080         case USB_SPEED_HIGH:            return "high";
00081         case USB_SPEED_SUPER:           return "super";
00082         default:
00083                 snprintf ( buf, sizeof ( buf ), "%d%sbps",
00084                            mantissa, exponents[exponent] );
00085                 return buf;
00086         }
00087 }
00088 
00089 /**
00090  * Transcribe USB BCD-coded value (for debugging)
00091  *
00092  * @v bcd               BCD-coded value
00093  * @ret string          Transcribed value
00094  */
00095 static inline const char * usb_bcd ( uint16_t bcd ) {
00096         static char buf[ 6 /* "xx.xx" + NUL */ ];
00097         uint8_t high = ( bcd >> 8 );
00098         uint8_t low = ( bcd >> 0 );
00099 
00100         snprintf ( buf, sizeof ( buf ), "%x.%02x", high, low );
00101         return buf;
00102 }
00103 
00104 /******************************************************************************
00105  *
00106  * USB descriptors
00107  *
00108  ******************************************************************************
00109  */
00110 
00111 /**
00112  * Locate USB interface association descriptor
00113  *
00114  * @v config            Configuraton descriptor
00115  * @v first             First interface number
00116  * @ret desc            Interface association descriptor, or NULL if not found
00117  */
00118 static struct usb_interface_association_descriptor *
00119 usb_interface_association_descriptor ( struct usb_configuration_descriptor
00120                                                                        *config,
00121                                        unsigned int first ) {
00122         struct usb_interface_association_descriptor *desc;
00123 
00124         /* Find a matching interface association descriptor */
00125         for_each_config_descriptor ( desc, config ) {
00126                 if ( ( desc->header.type ==
00127                        USB_INTERFACE_ASSOCIATION_DESCRIPTOR ) &&
00128                      ( desc->first == first ) )
00129                         return desc;
00130         }
00131         return NULL;
00132 }
00133 
00134 /**
00135  * Locate USB interface descriptor
00136  *
00137  * @v config            Configuraton descriptor
00138  * @v interface         Interface number
00139  * @v alternate         Alternate setting
00140  * @ret desc            Interface descriptor, or NULL if not found
00141  */
00142 struct usb_interface_descriptor *
00143 usb_interface_descriptor ( struct usb_configuration_descriptor *config,
00144                            unsigned int interface, unsigned int alternate ) {
00145         struct usb_interface_descriptor *desc;
00146 
00147         /* Find a matching interface descriptor */
00148         for_each_config_descriptor ( desc, config ) {
00149                 if ( ( desc->header.type == USB_INTERFACE_DESCRIPTOR ) &&
00150                      ( desc->interface == interface ) &&
00151                      ( desc->alternate == alternate ) )
00152                         return desc;
00153         }
00154         return NULL;
00155 }
00156 
00157 /**
00158  * Locate USB endpoint descriptor
00159  *
00160  * @v config            Configuration descriptor
00161  * @v interface         Interface descriptor
00162  * @v type              Endpoint (internal) type
00163  * @v index             Endpoint index
00164  * @ret desc            Descriptor, or NULL if not found
00165  */
00166 struct usb_endpoint_descriptor *
00167 usb_endpoint_descriptor ( struct usb_configuration_descriptor *config,
00168                           struct usb_interface_descriptor *interface,
00169                           unsigned int type, unsigned int index ) {
00170         struct usb_endpoint_descriptor *desc;
00171         unsigned int attributes = ( type & USB_ENDPOINT_ATTR_TYPE_MASK );
00172         unsigned int direction = ( type & USB_DIR_IN );
00173 
00174         /* Find a matching endpoint descriptor */
00175         for_each_interface_descriptor ( desc, config, interface ) {
00176                 if ( ( desc->header.type == USB_ENDPOINT_DESCRIPTOR ) &&
00177                      ( ( desc->attributes &
00178                          USB_ENDPOINT_ATTR_TYPE_MASK ) == attributes ) &&
00179                      ( ( desc->endpoint & USB_DIR_IN ) == direction ) &&
00180                      ( index-- == 0 ) )
00181                         return desc;
00182         }
00183         return NULL;
00184 }
00185 
00186 /**
00187  * Locate USB endpoint companion descriptor
00188  *
00189  * @v config            Configuration descriptor
00190  * @v desc              Endpoint descriptor
00191  * @ret descx           Companion descriptor, or NULL if not found
00192  */
00193 struct usb_endpoint_companion_descriptor *
00194 usb_endpoint_companion_descriptor ( struct usb_configuration_descriptor *config,
00195                                     struct usb_endpoint_descriptor *desc ) {
00196         struct usb_endpoint_companion_descriptor *descx;
00197 
00198         /* Get companion descriptor, if present */
00199         descx = container_of ( usb_next_descriptor ( &desc->header ),
00200                                struct usb_endpoint_companion_descriptor,
00201                                header );
00202         return ( ( usb_is_within_config ( config, &descx->header ) &&
00203                    descx->header.type == USB_ENDPOINT_COMPANION_DESCRIPTOR )
00204                  ? descx : NULL );
00205 }
00206 
00207 /******************************************************************************
00208  *
00209  * USB endpoint
00210  *
00211  ******************************************************************************
00212  */
00213 
00214 /**
00215  * Get USB endpoint name (for debugging)
00216  *
00217  * @v ep                USB endpoint
00218  * @ret name            Endpoint name
00219  */
00220 const char * usb_endpoint_name ( struct usb_endpoint *ep ) {
00221         static char buf[ 9 /* "EPxx OUT" + NUL */ ];
00222         unsigned int address = ep->address;
00223 
00224         snprintf ( buf, sizeof ( buf ), "EP%d%s",
00225                    ( address & USB_ENDPOINT_MAX ),
00226                    ( address ?
00227                      ( ( address & USB_ENDPOINT_IN ) ? " IN" : " OUT" ) : "" ));
00228         return buf;
00229 }
00230 
00231 /**
00232  * Describe USB endpoint from device configuration
00233  *
00234  * @v ep                USB endpoint
00235  * @v config            Configuration descriptor
00236  * @v interface         Interface descriptor
00237  * @v type              Endpoint (internal) type
00238  * @v index             Endpoint index
00239  * @ret rc              Return status code
00240  */
00241 int usb_endpoint_described ( struct usb_endpoint *ep,
00242                              struct usb_configuration_descriptor *config,
00243                              struct usb_interface_descriptor *interface,
00244                              unsigned int type, unsigned int index ) {
00245         struct usb_device *usb = ep->usb;
00246         struct usb_endpoint_descriptor *desc;
00247         struct usb_endpoint_companion_descriptor *descx;
00248         unsigned int sizes;
00249         unsigned int burst;
00250         unsigned int interval;
00251         size_t mtu;
00252 
00253         /* Locate endpoint descriptor */
00254         desc = usb_endpoint_descriptor ( config, interface, type, index );
00255         if ( ! desc )
00256                 return -ENOENT;
00257 
00258         /* Locate companion descriptor, if any */
00259         descx = usb_endpoint_companion_descriptor ( config, desc );
00260 
00261         /* Calculate MTU and burst size */
00262         sizes = le16_to_cpu ( desc->sizes );
00263         mtu = USB_ENDPOINT_MTU ( sizes );
00264         burst = ( descx ? descx->burst : USB_ENDPOINT_BURST ( sizes ) );
00265 
00266         /* Calculate interval */
00267         if ( ( type & USB_ENDPOINT_ATTR_TYPE_MASK ) ==
00268              USB_ENDPOINT_ATTR_INTERRUPT ) {
00269                 if ( usb->speed >= USB_SPEED_HIGH ) {
00270                         /* 2^(desc->interval-1) is a microframe count */
00271                         interval = ( 1 << ( desc->interval - 1 ) );
00272                 } else {
00273                         /* desc->interval is a (whole) frame count */
00274                         interval = ( desc->interval << 3 );
00275                 }
00276         } else {
00277                 /* desc->interval is a microframe count */
00278                 interval = desc->interval;
00279         }
00280 
00281         /* Describe endpoint */
00282         usb_endpoint_describe ( ep, desc->endpoint, desc->attributes,
00283                                 mtu, burst, interval );
00284         return 0;
00285 }
00286 
00287 /**
00288  * Open USB endpoint
00289  *
00290  * @v ep                USB endpoint
00291  * @ret rc              Return status code
00292  */
00293 int usb_endpoint_open ( struct usb_endpoint *ep ) {
00294         struct usb_device *usb = ep->usb;
00295         unsigned int idx = USB_ENDPOINT_IDX ( ep->address );
00296         int rc;
00297 
00298         /* Populate host controller operations */
00299         ep->host = &usb->port->hub->bus->op->endpoint;
00300 
00301         /* Add to endpoint list */
00302         if ( usb->ep[idx] != NULL ) {
00303                 DBGC ( usb, "USB %s %s is already open\n",
00304                        usb->name, usb_endpoint_name ( ep ) );
00305                 rc = -EALREADY;
00306                 goto err_already;
00307         }
00308         usb->ep[idx] = ep;
00309         INIT_LIST_HEAD ( &ep->halted );
00310 
00311         /* Open endpoint */
00312         if ( ( rc = ep->host->open ( ep ) ) != 0 ) {
00313                 DBGC ( usb, "USB %s %s could not open: %s\n", usb->name,
00314                        usb_endpoint_name ( ep ), strerror ( rc ) );
00315                 goto err_open;
00316         }
00317         ep->open = 1;
00318 
00319         DBGC2 ( usb, "USB %s %s opened with MTU %zd, burst %d, interval %d\n",
00320                 usb->name, usb_endpoint_name ( ep ), ep->mtu, ep->burst,
00321                 ep->interval );
00322         return 0;
00323 
00324         ep->open = 0;
00325         ep->host->close ( ep );
00326  err_open:
00327         usb->ep[idx] = NULL;
00328  err_already:
00329         if ( ep->max )
00330                 usb_flush ( ep );
00331         return rc;
00332 }
00333 
00334 /**
00335  * Clear transaction translator (if applicable)
00336  *
00337  * @v ep                USB endpoint
00338  * @ret rc              Return status code
00339  */
00340 static int usb_endpoint_clear_tt ( struct usb_endpoint *ep ) {
00341         struct usb_device *usb = ep->usb;
00342         struct usb_port *tt;
00343         int rc;
00344 
00345         /* Do nothing if this is a periodic endpoint */
00346         if ( ep->attributes & USB_ENDPOINT_ATTR_PERIODIC )
00347                 return 0;
00348 
00349         /* Do nothing if this endpoint is not behind a transaction translator */
00350         tt = usb_transaction_translator ( usb );
00351         if ( ! tt )
00352                 return 0;
00353 
00354         /* Clear transaction translator buffer */
00355         if ( ( rc = tt->hub->driver->clear_tt ( tt->hub, tt, ep ) ) != 0 ) {
00356                 DBGC ( usb, "USB %s %s could not clear transaction translator: "
00357                        "%s\n", usb->name, usb_endpoint_name ( ep ),
00358                        strerror ( rc ) );
00359                 return rc;
00360         }
00361 
00362         return 0;
00363 }
00364 
00365 /**
00366  * Close USB endpoint
00367  *
00368  * @v ep                USB endpoint
00369  */
00370 void usb_endpoint_close ( struct usb_endpoint *ep ) {
00371         struct usb_device *usb = ep->usb;
00372         unsigned int idx = USB_ENDPOINT_IDX ( ep->address );
00373 
00374         /* Sanity checks */
00375         assert ( usb->ep[idx] == ep );
00376 
00377         /* Close endpoint */
00378         ep->open = 0;
00379         ep->host->close ( ep );
00380         assert ( ep->fill == 0 );
00381 
00382         /* Remove from endpoint list */
00383         usb->ep[idx] = NULL;
00384         list_del ( &ep->halted );
00385 
00386         /* Discard any recycled buffers, if applicable */
00387         if ( ep->max )
00388                 usb_flush ( ep );
00389 
00390         /* Clear transaction translator, if applicable */
00391         usb_endpoint_clear_tt ( ep );
00392 }
00393 
00394 /**
00395  * Reset USB endpoint
00396  *
00397  * @v ep                USB endpoint
00398  * @ret rc              Return status code
00399  */
00400 static int usb_endpoint_reset ( struct usb_endpoint *ep ) {
00401         struct usb_device *usb = ep->usb;
00402         unsigned int type;
00403         int rc;
00404 
00405         /* Sanity check */
00406         assert ( ! list_empty ( &ep->halted ) );
00407 
00408         /* Reset endpoint */
00409         if ( ( rc = ep->host->reset ( ep ) ) != 0 ) {
00410                 DBGC ( usb, "USB %s %s could not reset: %s\n",
00411                        usb->name, usb_endpoint_name ( ep ), strerror ( rc ) );
00412                 return rc;
00413         }
00414 
00415         /* Clear transaction translator, if applicable */
00416         if ( ( rc = usb_endpoint_clear_tt ( ep ) ) != 0 )
00417                 return rc;
00418 
00419         /* Clear endpoint halt, if applicable */
00420         type = ( ep->attributes & USB_ENDPOINT_ATTR_TYPE_MASK );
00421         if ( ( type != USB_ENDPOINT_ATTR_CONTROL ) &&
00422              ( ( rc = usb_clear_feature ( usb, USB_RECIP_ENDPOINT,
00423                                           USB_ENDPOINT_HALT,
00424                                           ep->address ) ) != 0 ) ) {
00425                 DBGC ( usb, "USB %s %s could not clear endpoint halt: %s\n",
00426                        usb->name, usb_endpoint_name ( ep ), strerror ( rc ) );
00427                 return rc;
00428         }
00429 
00430         /* Remove from list of halted endpoints */
00431         list_del ( &ep->halted );
00432         INIT_LIST_HEAD ( &ep->halted );
00433 
00434         DBGC ( usb, "USB %s %s reset\n",
00435                usb->name, usb_endpoint_name ( ep ) );
00436         return 0;
00437 }
00438 
00439 /**
00440  * Update endpoint MTU
00441  *
00442  * @v ep                USB endpoint
00443  * @v mtu               New MTU
00444  * @ret rc              Return status code
00445  */
00446 static int usb_endpoint_mtu ( struct usb_endpoint *ep, size_t mtu ) {
00447         struct usb_device *usb = ep->usb;
00448         int rc;
00449 
00450         /* Update MTU */
00451         ep->mtu = mtu;
00452         if ( ( rc = ep->host->mtu ( ep ) ) != 0 ) {
00453                 DBGC ( usb, "USB %s %s could not update MTU: %s\n",
00454                        usb->name, usb_endpoint_name ( ep ), strerror ( rc ) );
00455                 return rc;
00456         }
00457 
00458         return 0;
00459 }
00460 
00461 /**
00462  * Enqueue USB message transfer
00463  *
00464  * @v ep                USB endpoint
00465  * @v request           Request
00466  * @v value             Value parameter
00467  * @v index             Index parameter
00468  * @v iobuf             I/O buffer
00469  * @ret rc              Return status code
00470  *
00471  * The I/O buffer must have sufficient headroom to contain a setup
00472  * packet.
00473  */
00474 int usb_message ( struct usb_endpoint *ep, unsigned int request,
00475                   unsigned int value, unsigned int index,
00476                   struct io_buffer *iobuf ) {
00477         struct usb_device *usb = ep->usb;
00478         struct usb_port *port = usb->port;
00479         struct usb_setup_packet *packet;
00480         size_t len = iob_len ( iobuf );
00481         int rc;
00482 
00483         /* Sanity check */
00484         assert ( iob_headroom ( iobuf ) >= sizeof ( *packet ) );
00485 
00486         /* Fail immediately if device has been unplugged */
00487         if ( port->disconnected )
00488                 return -ENODEV;
00489 
00490         /* Reset endpoint if required */
00491         if ( ( ! list_empty ( &ep->halted ) ) &&
00492              ( ( rc = usb_endpoint_reset ( ep ) ) != 0 ) )
00493                 return rc;
00494 
00495         /* Zero input data buffer (if applicable) */
00496         if ( request & USB_DIR_IN )
00497                 memset ( iobuf->data, 0, len );
00498 
00499         /* Construct setup packet */
00500         packet = iob_push ( iobuf, sizeof ( *packet ) );
00501         packet->request = cpu_to_le16 ( request );
00502         packet->value = cpu_to_le16 ( value );
00503         packet->index = cpu_to_le16 ( index );
00504         packet->len = cpu_to_le16 ( len );
00505 
00506         /* Enqueue message transfer */
00507         if ( ( rc = ep->host->message ( ep, iobuf ) ) != 0 ) {
00508                 DBGC ( usb, "USB %s %s could not enqueue message transfer: "
00509                        "%s\n", usb->name, usb_endpoint_name ( ep ),
00510                        strerror ( rc ) );
00511                 return rc;
00512         }
00513 
00514         /* Increment fill level */
00515         ep->fill++;
00516 
00517         return 0;
00518 }
00519 
00520 /**
00521  * Enqueue USB stream transfer
00522  *
00523  * @v ep                USB endpoint
00524  * @v iobuf             I/O buffer
00525  * @v terminate         Terminate using a short packet
00526  * @ret rc              Return status code
00527  */
00528 int usb_stream ( struct usb_endpoint *ep, struct io_buffer *iobuf,
00529                  int terminate ) {
00530         struct usb_device *usb = ep->usb;
00531         struct usb_port *port = usb->port;
00532         int zlp;
00533         int rc;
00534 
00535         /* Fail immediately if device has been unplugged */
00536         if ( port->disconnected )
00537                 return -ENODEV;
00538 
00539         /* Reset endpoint if required */
00540         if ( ( ! list_empty ( &ep->halted ) ) &&
00541              ( ( rc = usb_endpoint_reset ( ep ) ) != 0 ) )
00542                 return rc;
00543 
00544         /* Append a zero-length packet if necessary */
00545         zlp = terminate;
00546         if ( iob_len ( iobuf ) & ( ep->mtu - 1 ) )
00547                 zlp = 0;
00548 
00549         /* Enqueue stream transfer */
00550         if ( ( rc = ep->host->stream ( ep, iobuf, zlp ) ) != 0 ) {
00551                 DBGC ( usb, "USB %s %s could not enqueue stream transfer: %s\n",
00552                        usb->name, usb_endpoint_name ( ep ), strerror ( rc ) );
00553                 return rc;
00554         }
00555 
00556         /* Increment fill level */
00557         ep->fill++;
00558 
00559         return 0;
00560 }
00561 
00562 /**
00563  * Complete transfer (possibly with error)
00564  *
00565  * @v ep                USB endpoint
00566  * @v iobuf             I/O buffer
00567  * @v rc                Completion status code
00568  */
00569 void usb_complete_err ( struct usb_endpoint *ep, struct io_buffer *iobuf,
00570                         int rc ) {
00571         struct usb_device *usb = ep->usb;
00572 
00573         /* Decrement fill level */
00574         assert ( ep->fill > 0 );
00575         ep->fill--;
00576 
00577         /* Schedule reset, if applicable */
00578         if ( ( rc != 0 ) && ep->open ) {
00579                 DBGC ( usb, "USB %s %s completion failed: %s\n",
00580                        usb->name, usb_endpoint_name ( ep ), strerror ( rc ) );
00581                 list_del ( &ep->halted );
00582                 list_add_tail ( &ep->halted, &usb_halted );
00583         }
00584 
00585         /* Report completion */
00586         ep->driver->complete ( ep, iobuf, rc );
00587 }
00588 
00589 /******************************************************************************
00590  *
00591  * Endpoint refilling
00592  *
00593  ******************************************************************************
00594  */
00595 
00596 /**
00597  * Prefill endpoint recycled buffer list
00598  *
00599  * @v ep                USB endpoint
00600  * @ret rc              Return status code
00601  */
00602 int usb_prefill ( struct usb_endpoint *ep ) {
00603         struct io_buffer *iobuf;
00604         size_t reserve = ep->reserve;
00605         size_t len = ( ep->len ? ep->len : ep->mtu );
00606         unsigned int fill;
00607         int rc;
00608 
00609         /* Sanity checks */
00610         assert ( ep->fill == 0 );
00611         assert ( ep->max > 0 );
00612         assert ( list_empty ( &ep->recycled ) );
00613 
00614         /* Fill recycled buffer list */
00615         for ( fill = 0 ; fill < ep->max ; fill++ ) {
00616 
00617                 /* Allocate I/O buffer */
00618                 iobuf = alloc_iob ( reserve + len );
00619                 if ( ! iobuf ) {
00620                         rc = -ENOMEM;
00621                         goto err_alloc;
00622                 }
00623                 iob_reserve ( iobuf, reserve );
00624 
00625                 /* Add to recycled buffer list */
00626                 list_add_tail ( &iobuf->list, &ep->recycled );
00627         }
00628 
00629         return 0;
00630 
00631  err_alloc:
00632         usb_flush ( ep );
00633         return rc;
00634 }
00635 
00636 /**
00637  * Refill endpoint
00638  *
00639  * @v ep                USB endpoint
00640  * @ret rc              Return status code
00641  */
00642 int usb_refill ( struct usb_endpoint *ep ) {
00643         struct io_buffer *iobuf;
00644         size_t reserve = ep->reserve;
00645         size_t len = ( ep->len ? ep->len : ep->mtu );
00646         int rc;
00647 
00648         /* Sanity checks */
00649         assert ( ep->open );
00650         assert ( ep->max > 0 );
00651 
00652         /* Refill endpoint */
00653         while ( ep->fill < ep->max ) {
00654 
00655                 /* Get or allocate buffer */
00656                 if ( list_empty ( &ep->recycled ) ) {
00657                         /* Recycled buffer list is empty; allocate new buffer */
00658                         iobuf = alloc_iob ( reserve + len );
00659                         if ( ! iobuf )
00660                                 return -ENOMEM;
00661                         iob_reserve ( iobuf, reserve );
00662                 } else {
00663                         /* Get buffer from recycled buffer list */
00664                         iobuf = list_first_entry ( &ep->recycled,
00665                                                    struct io_buffer, list );
00666                         assert ( iobuf != NULL );
00667                         list_del ( &iobuf->list );
00668                 }
00669 
00670                 /* Reset buffer to maximum size */
00671                 assert ( iob_len ( iobuf ) <= len );
00672                 iob_put ( iobuf, ( len - iob_len ( iobuf ) ) );
00673 
00674                 /* Enqueue buffer */
00675                 if ( ( rc = usb_stream ( ep, iobuf, 0 ) ) != 0 ) {
00676                         list_add ( &iobuf->list, &ep->recycled );
00677                         return rc;
00678                 }
00679         }
00680 
00681         return 0;
00682 }
00683 
00684 /**
00685  * Discard endpoint recycled buffer list
00686  *
00687  * @v ep                USB endpoint
00688  */
00689 void usb_flush ( struct usb_endpoint *ep ) {
00690         struct io_buffer *iobuf;
00691         struct io_buffer *tmp;
00692 
00693         /* Sanity checks */
00694         assert ( ! ep->open );
00695         assert ( ep->max > 0 );
00696 
00697         /* Free all I/O buffers */
00698         list_for_each_entry_safe ( iobuf, tmp, &ep->recycled, list ) {
00699                 list_del ( &iobuf->list );
00700                 free_iob ( iobuf );
00701         }
00702 }
00703 
00704 /******************************************************************************
00705  *
00706  * Control endpoint
00707  *
00708  ******************************************************************************
00709  */
00710 
00711 /** USB control transfer pseudo-header */
00712 struct usb_control_pseudo_header {
00713         /** Completion status */
00714         int rc;
00715 };
00716 
00717 /**
00718  * Complete USB control transfer
00719  *
00720  * @v ep                USB endpoint
00721  * @v iobuf             I/O buffer
00722  * @v rc                Completion status code
00723  */
00724 static void usb_control_complete ( struct usb_endpoint *ep,
00725                                    struct io_buffer *iobuf, int rc ) {
00726         struct usb_device *usb = ep->usb;
00727         struct usb_control_pseudo_header *pshdr;
00728 
00729         /* Record completion status in buffer */
00730         pshdr = iob_push ( iobuf, sizeof ( *pshdr ) );
00731         pshdr->rc = rc;
00732 
00733         /* Add to list of completed I/O buffers */
00734         list_add_tail ( &iobuf->list, &usb->complete );
00735 }
00736 
00737 /** USB control endpoint driver operations */
00738 static struct usb_endpoint_driver_operations usb_control_operations = {
00739         .complete = usb_control_complete,
00740 };
00741 
00742 /**
00743  * Issue USB control transaction
00744  *
00745  * @v usb               USB device
00746  * @v request           Request
00747  * @v value             Value parameter
00748  * @v index             Index parameter
00749  * @v data              Data buffer (if any)
00750  * @v len               Length of data
00751  * @ret rc              Return status code
00752  */
00753 int usb_control ( struct usb_device *usb, unsigned int request,
00754                   unsigned int value, unsigned int index, void *data,
00755                   size_t len ) {
00756         struct usb_bus *bus = usb->port->hub->bus;
00757         struct usb_endpoint *ep = &usb->control;
00758         struct io_buffer *iobuf;
00759         struct io_buffer *cmplt;
00760         union {
00761                 struct usb_setup_packet setup;
00762                 struct usb_control_pseudo_header pshdr;
00763         } *headroom;
00764         struct usb_control_pseudo_header *pshdr;
00765         unsigned int i;
00766         int rc;
00767 
00768         /* Allocate I/O buffer */
00769         iobuf = alloc_iob ( sizeof ( *headroom ) + len );
00770         if ( ! iobuf ) {
00771                 rc = -ENOMEM;
00772                 goto err_alloc;
00773         }
00774         iob_reserve ( iobuf, sizeof ( *headroom ) );
00775         iob_put ( iobuf, len );
00776         if ( request & USB_DIR_IN ) {
00777                 memset ( data, 0, len );
00778         } else {
00779                 memcpy ( iobuf->data, data, len );
00780         }
00781 
00782         /* Enqueue message */
00783         if ( ( rc = usb_message ( ep, request, value, index, iobuf ) ) != 0 )
00784                 goto err_message;
00785 
00786         /* Wait for completion */
00787         for ( i = 0 ; i < USB_CONTROL_MAX_WAIT_MS ; i++ ) {
00788 
00789                 /* Poll bus */
00790                 usb_poll ( bus );
00791 
00792                 /* Check for completion */
00793                 while ( ( cmplt = list_first_entry ( &usb->complete,
00794                                                      struct io_buffer,
00795                                                      list ) ) ) {
00796 
00797                         /* Remove from completion list */
00798                         list_del ( &cmplt->list );
00799 
00800                         /* Extract and strip completion status */
00801                         pshdr = cmplt->data;
00802                         iob_pull ( cmplt, sizeof ( *pshdr ) );
00803                         rc = pshdr->rc;
00804 
00805                         /* Discard stale completions */
00806                         if ( cmplt != iobuf ) {
00807                                 DBGC ( usb, "USB %s stale control completion: "
00808                                        "%s\n", usb->name, strerror ( rc ) );
00809                                 DBGC_HDA ( usb, 0, cmplt->data,
00810                                            iob_len ( cmplt ) );
00811                                 free_iob ( cmplt );
00812                                 continue;
00813                         }
00814 
00815                         /* Fail immediately if completion was in error */
00816                         if ( rc != 0 ) {
00817                                 DBGC ( usb, "USB %s control %04x:%04x:%04x "
00818                                        "failed: %s\n", usb->name, request,
00819                                        value, index, strerror ( rc ) );
00820                                 free_iob ( cmplt );
00821                                 return rc;
00822                         }
00823 
00824                         /* Copy completion to data buffer, if applicable */
00825                         assert ( iob_len ( cmplt ) <= len );
00826                         if ( request & USB_DIR_IN )
00827                                 memcpy ( data, cmplt->data, iob_len ( cmplt ) );
00828                         free_iob ( cmplt );
00829                         return 0;
00830                 }
00831 
00832                 /* Delay */
00833                 mdelay ( 1 );
00834         }
00835 
00836         DBGC ( usb, "USB %s timed out waiting for control %04x:%04x:%04x\n",
00837                usb->name, request, value, index );
00838         return -ETIMEDOUT;
00839 
00840  err_message:
00841         free_iob ( iobuf );
00842  err_alloc:
00843         return rc;
00844 }
00845 
00846 /**
00847  * Get default language ID
00848  *
00849  * @v usb               USB device
00850  * @ret language        Language ID
00851  */
00852 static unsigned int usb_get_default_language ( struct usb_device *usb ) {
00853         struct {
00854                 struct usb_descriptor_header header;
00855                 uint16_t language[1];
00856         } __attribute__ (( packed )) desc;
00857         unsigned int language;
00858         int rc;
00859 
00860         /* Get descriptor */
00861         if ( ( rc = usb_get_descriptor ( usb, 0, USB_STRING_DESCRIPTOR, 0, 0,
00862                                          &desc.header, sizeof ( desc ) ) ) !=0){
00863                 DBGC ( usb, "USB %s has no default language: %s\n",
00864                        usb->name, strerror ( rc ) );
00865                 return USB_LANG_ENGLISH;
00866         }
00867 
00868         /* Use first language ID */
00869         language = le16_to_cpu ( desc.language[0] );
00870         DBGC2 ( usb, "USB %s default language %#04x\n", usb->name, language );
00871         return language;
00872 }
00873 
00874 /**
00875  * Get USB string descriptor
00876  *
00877  * @v usb               USB device
00878  * @v index             String index
00879  * @v language          Language ID, or 0 to use default
00880  * @v buf               Data buffer
00881  * @v len               Length of buffer
00882  * @ret len             String length (excluding NUL), or negative error
00883  */
00884 int usb_get_string_descriptor ( struct usb_device *usb, unsigned int index,
00885                                 unsigned int language, char *buf, size_t len ) {
00886         size_t max = ( len ? ( len - 1 /* NUL */ ) : 0 );
00887         struct {
00888                 struct usb_descriptor_header header;
00889                 uint16_t character[max];
00890         } __attribute__ (( packed )) *desc;
00891         unsigned int actual;
00892         unsigned int i;
00893         int rc;
00894 
00895         /* Use default language ID, if applicable */
00896         if ( ( language == 0 ) && ( index != 0 ) ) {
00897                 if ( ! usb->language )
00898                         usb->language = usb_get_default_language ( usb );
00899                 language = usb->language;
00900         }
00901 
00902         /* Allocate buffer for string */
00903         desc = malloc ( sizeof ( *desc ) );
00904         if ( ! desc ) {
00905                 rc = -ENOMEM;
00906                 goto err_alloc;
00907         }
00908 
00909         /* Get descriptor */
00910         if ( ( rc = usb_get_descriptor ( usb, 0, USB_STRING_DESCRIPTOR, index,
00911                                          language, &desc->header,
00912                                          sizeof ( *desc ) ) ) != 0 )
00913                 goto err_get_descriptor;
00914 
00915         /* Copy to buffer */
00916         actual = ( ( desc->header.len - sizeof ( desc->header ) ) /
00917                    sizeof ( desc->character[0] ) );
00918         for ( i = 0 ; ( ( i < actual ) && ( i < max ) ) ; i++ )
00919                 buf[i] = le16_to_cpu ( desc->character[i] );
00920         if ( len )
00921                 buf[i] = '\0';
00922 
00923         /* Free buffer */
00924         free ( desc );
00925 
00926         return actual;
00927 
00928  err_get_descriptor:
00929         free ( desc );
00930  err_alloc:
00931         return rc;
00932 }
00933 
00934 /******************************************************************************
00935  *
00936  * USB device driver
00937  *
00938  ******************************************************************************
00939  */
00940 
00941 /**
00942  * Get USB configuration descriptor
00943  *
00944  * @v usb               USB device
00945  * @v index             Configuration index
00946  * @ret config          Configuration descriptor
00947  * @ret rc              Return status code
00948  *
00949  * The configuration descriptor is dynamically allocated and must
00950  * eventually be freed by the caller.
00951  */
00952 static int
00953 usb_config_descriptor ( struct usb_device *usb, unsigned int index,
00954                         struct usb_configuration_descriptor **config ) {
00955         struct usb_configuration_descriptor partial;
00956         size_t len;
00957         int rc;
00958 
00959         /* Read first part of configuration descriptor to get size */
00960         if ( ( rc = usb_get_config_descriptor ( usb, index, &partial,
00961                                                 sizeof ( partial ) ) ) != 0 ) {
00962                 DBGC ( usb, "USB %s could not get configuration descriptor %d: "
00963                        "%s\n", usb->name, index, strerror ( rc ) );
00964                 goto err_get_partial;
00965         }
00966         len = le16_to_cpu ( partial.len );
00967         if ( len < sizeof ( partial ) ) {
00968                 DBGC ( usb, "USB %s underlength configuraton descriptor %d\n",
00969                        usb->name, index );
00970                 rc = -EINVAL;
00971                 goto err_partial_len;
00972         }
00973 
00974         /* Allocate buffer for whole configuration descriptor */
00975         *config = malloc ( len );
00976         if ( ! *config ) {
00977                 rc = -ENOMEM;
00978                 goto err_alloc_config;
00979         }
00980 
00981         /* Read whole configuration descriptor */
00982         if ( ( rc = usb_get_config_descriptor ( usb, index, *config,
00983                                                 len ) ) != 0 ) {
00984                 DBGC ( usb, "USB %s could not get configuration descriptor %d: "
00985                        "%s\n", usb->name, index, strerror ( rc ) );
00986                 goto err_get_config_descriptor;
00987         }
00988         if ( (*config)->len != partial.len ) {
00989                 DBGC ( usb, "USB %s bad configuration descriptor %d length\n",
00990                        usb->name, index );
00991                 rc = -EINVAL;
00992                 goto err_config_len;
00993         }
00994 
00995         return 0;
00996 
00997  err_config_len:
00998  err_get_config_descriptor:
00999         free ( *config );
01000  err_alloc_config:
01001  err_partial_len:
01002  err_get_partial:
01003         return rc;
01004 }
01005 
01006 /**
01007  * Describe USB function
01008  *
01009  * @v usb               USB device
01010  * @v config            Configuration descriptor
01011  * @v first             First interface number
01012  * @v interfaces        Interface list to fill in
01013  * @v desc              Function descriptor to fill in
01014  * @ret rc              Return status code
01015  */
01016 static int usb_describe ( struct usb_device *usb,
01017                           struct usb_configuration_descriptor *config,
01018                           unsigned int first, uint8_t *interfaces,
01019                           struct usb_function_descriptor *desc ) {
01020         struct usb_interface_association_descriptor *association;
01021         struct usb_interface_descriptor *interface;
01022         struct cdc_union_descriptor *cdc_union;
01023         unsigned int i;
01024 
01025         /* Fill in vendor and product ID */
01026         memset ( desc, 0, sizeof ( *desc ) );
01027         desc->vendor = le16_to_cpu ( usb->device.vendor );
01028         desc->product = le16_to_cpu ( usb->device.product );
01029 
01030         /* First, look for an interface association descriptor */
01031         association = usb_interface_association_descriptor ( config, first );
01032         if ( association ) {
01033 
01034                 /* Sanity check */
01035                 assert ( association->first == first );
01036                 if ( ( first + association->count ) > config->interfaces ) {
01037                         DBGC ( usb, "USB %s has invalid association [%d-%d)\n",
01038                                usb->name, first, ( first + association->count));
01039                         return -ERANGE;
01040                 }
01041 
01042                 /* Describe function */
01043                 memcpy ( &desc->class.class, &association->class,
01044                          sizeof ( desc->class.class ) );
01045                 desc->count = association->count;
01046                 for ( i = 0 ; i < association->count ; i++ )
01047                         interfaces[i] = ( first + i );
01048                 return 0;
01049         }
01050 
01051         /* Next, look for an interface descriptor */
01052         interface = usb_interface_descriptor ( config, first, 0 );
01053         if ( ! interface ) {
01054                 DBGC ( usb, "USB %s has no descriptor for interface %d\n",
01055                        usb->name, first );
01056                 return -ENOENT;
01057         }
01058 
01059         /* Describe function */
01060         memcpy ( &desc->class.class, &interface->class,
01061                  sizeof ( desc->class.class ) );
01062         desc->count = 1;
01063         interfaces[0] = first;
01064 
01065         /* Look for a CDC union descriptor, if applicable */
01066         if ( ( desc->class.class.class == USB_CLASS_CDC ) &&
01067              ( cdc_union = cdc_union_descriptor ( config, interface ) ) ) {
01068 
01069                 /* Determine interface count */
01070                 desc->count = ( ( cdc_union->header.len -
01071                                   offsetof ( typeof ( *cdc_union ),
01072                                              interface[0] ) ) /
01073                                 sizeof ( cdc_union->interface[0] ) );
01074                 if ( desc->count > config->interfaces ) {
01075                         DBGC ( usb, "USB %s has invalid union functional "
01076                                "descriptor with %d interfaces\n",
01077                                usb->name, desc->count );
01078                         return -ERANGE;
01079                 }
01080 
01081                 /* Describe function */
01082                 for ( i = 0 ; i < desc->count ; i++ ) {
01083                         if ( cdc_union->interface[i] >= config->interfaces ) {
01084                                 DBGC ( usb, "USB %s has invalid union "
01085                                        "functional descriptor covering "
01086                                        "interface %d\n", usb->name,
01087                                        cdc_union->interface[i] );
01088                                 return -ERANGE;
01089                         }
01090                         interfaces[i] = cdc_union->interface[i];
01091                 }
01092 
01093                 return 0;
01094         }
01095 
01096         return 0;
01097 }
01098 
01099 /**
01100  * Update list of used interface
01101  *
01102  * @v usb               USB device
01103  * @v count             Number of interfaces
01104  * @v interface         List of interfaces
01105  * @v used              List of already-used interfaces
01106  * @ret rc              Return status code
01107  */
01108 static int usb_used ( struct usb_device *usb, unsigned int count,
01109                       uint8_t *interface, uint8_t *used ) {
01110         unsigned int i;
01111 
01112         for ( i = 0 ; i < count ; i++ ) {
01113                 if ( used[interface[i]] ) {
01114                         DBGC ( usb, "USB %s interface %d already in use\n",
01115                                usb->name, interface[i] );
01116                         return -EINVAL;
01117                 }
01118                 used[interface[i]] = 1;
01119         }
01120         return 0;
01121 }
01122 
01123 /**
01124  * Find USB device driver
01125  *
01126  * @v desc              Function descriptor
01127  * @ret id              USB device ID, or NULL
01128  * @ret driver          USB device driver, or NULL
01129  */
01130 struct usb_driver * usb_find_driver ( struct usb_function_descriptor *desc,
01131                                       struct usb_device_id **id ) {
01132         struct usb_driver *driver;
01133         unsigned int i;
01134 
01135         /* Look for a matching driver */
01136         for_each_table_entry ( driver, USB_DRIVERS ) {
01137                 for ( i = 0 ; i < driver->id_count ; i++ ) {
01138 
01139                         /* Ignore non-matching driver class */
01140                         if ( ( driver->class.class.scalar ^ desc->class.scalar )
01141                              & driver->class.mask.scalar )
01142                                 continue;
01143 
01144                         /* Look for a matching ID */
01145                         *id = &driver->ids[i];
01146                         if ( ( ( (*id)->vendor == desc->vendor ) ||
01147                                ( (*id)->vendor == USB_ANY_ID ) ) &&
01148                              ( ( (*id)->product == desc->product ) ||
01149                                ( (*id)->product == USB_ANY_ID ) ) )
01150                                 return driver;
01151                 }
01152         }
01153 
01154         /* Not found */
01155         *id = NULL;
01156         return NULL;
01157 }
01158 
01159 /**
01160  * Get USB device configuration score
01161  *
01162  * @v usb               USB device
01163  * @v config            Configuration descriptor
01164  * @ret score           Device configuration score, or negative error
01165  */
01166 static int usb_score ( struct usb_device *usb,
01167                        struct usb_configuration_descriptor *config ) {
01168         uint8_t used[config->interfaces];
01169         uint8_t interface[config->interfaces];
01170         struct usb_function_descriptor desc;
01171         struct usb_driver *driver;
01172         struct usb_device_id *id;
01173         unsigned int first;
01174         unsigned int score = 0;
01175         int rc;
01176 
01177         /* Identify each function in turn */
01178         memset ( used, 0, sizeof ( used ) );
01179         for ( first = 0 ; first < config->interfaces ; first++ ) {
01180 
01181                 /* Skip interfaces already used */
01182                 if ( used[first] )
01183                         continue;
01184 
01185                 /* Describe function */
01186                 if ( ( rc = usb_describe ( usb, config, first, interface,
01187                                            &desc ) ) != 0 )
01188                         return rc;
01189 
01190                 /* Update used interfaces */
01191                 if ( ( rc = usb_used ( usb, desc.count, interface,
01192                                        used ) ) != 0 )
01193                         return rc;
01194 
01195                 /* Look for a driver for this function */
01196                 driver = usb_find_driver ( &desc, &id );
01197                 if ( driver )
01198                         score += driver->score;
01199         }
01200 
01201         return score;
01202 }
01203 
01204 /**
01205  * Probe USB device driver
01206  *
01207  * @v func              USB function
01208  * @v config            Configuration descriptor
01209  * @ret rc              Return status code
01210  */
01211 static int usb_probe ( struct usb_function *func,
01212                        struct usb_configuration_descriptor *config ) {
01213         struct usb_device *usb = func->usb;
01214         struct usb_driver *driver;
01215         struct usb_device_id *id;
01216         int rc;
01217 
01218         /* Identify driver */
01219         driver = usb_find_driver ( &func->desc, &id );
01220         if ( ! driver ) {
01221                 DBGC ( usb, "USB %s %04x:%04x class %d:%d:%d has no driver\n",
01222                        func->name, func->desc.vendor, func->desc.product,
01223                        func->desc.class.class.class,
01224                        func->desc.class.class.subclass,
01225                        func->desc.class.class.protocol );
01226                 return -ENOENT;
01227         }
01228 
01229         /* Record driver */
01230         func->driver = driver;
01231         func->id = id;
01232         func->dev.driver_name = id->name;
01233 
01234         /* Probe driver */
01235         if ( ( rc = driver->probe ( func, config ) ) != 0 ) {
01236                 DBGC ( usb, "USB %s failed to probe driver %s: %s\n",
01237                        func->name, id->name, strerror ( rc ) );
01238                 return rc;
01239         }
01240 
01241         return 0;
01242 }
01243 
01244 /**
01245  * Remove USB device driver
01246  *
01247  * @v func              USB function
01248  */
01249 static void usb_remove ( struct usb_function *func ) {
01250 
01251         /* Remove driver */
01252         func->driver->remove ( func );
01253 }
01254 
01255 /**
01256  * Probe all USB device drivers
01257  *
01258  * @v usb               USB device
01259  * @v config            Configuration descriptor
01260  */
01261 static void
01262 usb_probe_all ( struct usb_device *usb,
01263                 struct usb_configuration_descriptor *config ) {
01264         struct usb_bus *bus = usb->port->hub->bus;
01265         struct usb_function *func;
01266         uint8_t used[config->interfaces];
01267         unsigned int first;
01268         unsigned int i;
01269         int rc;
01270 
01271         /* Identify each function in turn */
01272         memset ( used, 0, sizeof ( used ) );
01273         for ( first = 0 ; first < config->interfaces ; first++ ) {
01274 
01275                 /* Skip interfaces already used */
01276                 if ( used[first] )
01277                         continue;
01278 
01279                 /* Allocate and initialise structure */
01280                 func = zalloc ( sizeof ( *func ) +
01281                                 ( config->interfaces *
01282                                   sizeof ( func->interface[0] ) ) );
01283                 if ( ! func )
01284                         goto err_alloc;
01285                 func->name = func->dev.name;
01286                 func->usb = usb;
01287                 func->dev.desc.bus_type = BUS_TYPE_USB;
01288                 func->dev.desc.location = usb->address;
01289                 func->dev.desc.vendor = le16_to_cpu ( usb->device.vendor );
01290                 func->dev.desc.device = le16_to_cpu ( usb->device.product );
01291                 snprintf ( func->dev.name, sizeof ( func->dev.name ),
01292                            "%s-%d.%d", usb->name, config->config, first );
01293                 INIT_LIST_HEAD ( &func->dev.children );
01294                 func->dev.parent = bus->dev;
01295                 list_add_tail ( &func->list, &usb->functions );
01296 
01297                 /* Identify function */
01298                 if ( ( rc = usb_describe ( usb, config, first, func->interface,
01299                                            &func->desc ) ) != 0 )
01300                         goto err_describe;
01301                 assert ( func->desc.count <= config->interfaces );
01302 
01303                 /* Mark interfaces as used */
01304                 if ( ( rc = usb_used ( usb, func->desc.count, func->interface,
01305                                        used ) ) != 0 )
01306                         goto err_used;
01307 
01308                 /* Probe device driver */
01309                 if ( ( rc = usb_probe ( func, config ) ) != 0 )
01310                         goto err_probe;
01311                 DBGC ( usb, "USB %s %04x:%04x class %d:%d:%d interfaces ",
01312                        func->name, func->desc.vendor, func->desc.product,
01313                        func->desc.class.class.class,
01314                        func->desc.class.class.subclass,
01315                        func->desc.class.class.protocol );
01316                 for ( i = 0 ; i < func->desc.count ; i++ )
01317                         DBGC ( usb, "%s%d", ( i ? "," : "" ),
01318                                func->interface[i] );
01319                 DBGC ( usb, " using driver %s\n", func->dev.driver_name );
01320 
01321                 /* Add to device hierarchy */
01322                 list_add_tail ( &func->dev.siblings, &bus->dev->children );
01323 
01324                 continue;
01325 
01326                 list_del ( &func->dev.siblings );
01327                 usb_remove ( func );
01328         err_probe:
01329         err_used:
01330         err_describe:
01331                 list_del ( &func->list );
01332                 free ( func );
01333         err_alloc:
01334                 /* Continue registering other functions */
01335                 continue;
01336         }
01337 }
01338 
01339 /**
01340  * Remove all device drivers
01341  *
01342  * @v usb               USB device
01343  */
01344 static void usb_remove_all ( struct usb_device *usb ) {
01345         struct usb_function *func;
01346         struct usb_function *tmp;
01347 
01348         /* Remove all functions */
01349         list_for_each_entry_safe ( func, tmp, &usb->functions, list ) {
01350 
01351                 /* Remove device driver */
01352                 usb_remove ( func );
01353 
01354                 /* Remove from device hierarchy */
01355                 assert ( list_empty ( &func->dev.children ) );
01356                 list_del ( &func->dev.siblings );
01357 
01358                 /* Remove from list of functions */
01359                 list_del ( &func->list );
01360 
01361                 /* Free function */
01362                 free ( func );
01363         }
01364 }
01365 
01366 /**
01367  * Clear USB device configuration
01368  *
01369  * @v usb               USB device
01370  */
01371 static void usb_deconfigure ( struct usb_device *usb ) {
01372         unsigned int i;
01373 
01374         /* Remove device drivers */
01375         usb_remove_all ( usb );
01376 
01377         /* Sanity checks */
01378         for ( i = 0 ; i < ( sizeof ( usb->ep ) / sizeof ( usb->ep[0] ) ) ; i++){
01379                 if ( i != USB_ENDPOINT_IDX ( USB_EP0_ADDRESS ) )
01380                         assert ( usb->ep[i] == NULL );
01381         }
01382 
01383         /* Clear device configuration */
01384         usb_set_configuration ( usb, 0 );
01385 }
01386 
01387 /**
01388  * Choose our preferred USB device configuration
01389  *
01390  * @v usb               USB device
01391  * @ret rc              Return status code
01392  */
01393 static int usb_autoconfigure ( struct usb_device *usb ) {
01394         struct usb_configuration_descriptor *config;
01395         unsigned int preferred = 0;
01396         unsigned int index;
01397         int score;
01398         int best = 0;
01399         int rc;
01400 
01401         /* Calculate driver score for each configuration index */
01402         for ( index = 0 ; index < usb->device.configurations ; index++ ) {
01403 
01404                 /* Read configuration descriptor */
01405                 if ( ( rc = usb_config_descriptor ( usb, index,
01406                                                     &config ) ) != 0 )
01407                         goto err_config;
01408 
01409                 /* Get score for this configuration */
01410                 score = usb_score ( usb, config );
01411                 if ( score < 0 ) {
01412                         rc = score;
01413                         goto err_score;
01414                 }
01415                 DBGC2 ( usb, "USB %s configuration %d score %d\n",
01416                         usb->name, config->config, score );
01417 
01418                 /* Record as preferred configuration, if applicable */
01419                 if ( score > best ) {
01420                         best = score;
01421                         preferred = index;
01422                 }
01423 
01424                 /* Free configuration descriptor */
01425                 free ( config );
01426                 config = NULL;
01427         }
01428 
01429         /* Read preferred configuration descriptor */
01430         if ( ( rc = usb_config_descriptor ( usb, preferred, &config ) ) != 0 )
01431                 goto err_preferred;
01432 
01433         /* Set configuration */
01434         if ( ( rc = usb_set_configuration ( usb, config->config ) ) != 0){
01435                 DBGC ( usb, "USB %s could not set configuration %d: %s\n",
01436                        usb->name, config->config, strerror ( rc ) );
01437                 goto err_set_configuration;
01438         }
01439 
01440         /* Probe USB device drivers */
01441         usb_probe_all ( usb, config );
01442 
01443         /* Free configuration descriptor */
01444         free ( config );
01445 
01446         return 0;
01447 
01448         usb_remove_all ( usb );
01449         usb_set_configuration ( usb, 0 );
01450  err_set_configuration:
01451         free ( config );
01452  err_preferred:
01453         return rc;
01454 
01455  err_score:
01456         free ( config );
01457  err_config:
01458         return rc;
01459 }
01460 
01461 /******************************************************************************
01462  *
01463  * USB device
01464  *
01465  ******************************************************************************
01466  */
01467 
01468 /**
01469  * Allocate USB device
01470  *
01471  * @v port              USB port
01472  * @ret usb             USB device, or NULL on allocation failure
01473  */
01474 static struct usb_device * alloc_usb ( struct usb_port *port ) {
01475         struct usb_hub *hub = port->hub;
01476         struct usb_bus *bus = hub->bus;
01477         struct usb_device *usb;
01478 
01479         /* Allocate and initialise structure */
01480         usb = zalloc ( sizeof ( *usb ) );
01481         if ( ! usb )
01482                 return NULL;
01483         snprintf ( usb->name, sizeof ( usb->name ), "%s%c%d", hub->name,
01484                    ( hub->usb ? '.' : '-' ), port->address );
01485         usb->port = port;
01486         INIT_LIST_HEAD ( &usb->functions );
01487         usb->host = &bus->op->device;
01488         usb_endpoint_init ( &usb->control, usb, &usb_control_operations );
01489         INIT_LIST_HEAD ( &usb->complete );
01490 
01491         return usb;
01492 }
01493 
01494 /**
01495  * Register USB device
01496  *
01497  * @v usb               USB device
01498  * @ret rc              Return status code
01499  */
01500 static int register_usb ( struct usb_device *usb ) {
01501         struct usb_port *port = usb->port;
01502         struct usb_hub *hub = port->hub;
01503         struct usb_bus *bus = hub->bus;
01504         unsigned int protocol;
01505         size_t mtu;
01506         int rc;
01507 
01508         /* Add to port */
01509         if ( port->usb != NULL ) {
01510                 DBGC ( hub, "USB hub %s port %d is already registered to %s\n",
01511                        hub->name, port->address, port->usb->name );
01512                 rc = -EALREADY;
01513                 goto err_already;
01514         }
01515         port->usb = usb;
01516 
01517         /* Add to bus device list */
01518         list_add_tail ( &usb->list, &bus->devices );
01519 
01520         /* Enable device */
01521         if ( ( rc = hub->driver->enable ( hub, port ) ) != 0 ) {
01522                 DBGC ( hub, "USB hub %s port %d could not enable: %s\n",
01523                        hub->name, port->address, strerror ( rc ) );
01524                 goto err_enable;
01525         }
01526 
01527         /* Allow recovery interval since port may have been reset */
01528         mdelay ( USB_RESET_RECOVER_DELAY_MS );
01529 
01530         /* Get device speed */
01531         if ( ( rc = hub->driver->speed ( hub, port ) ) != 0 ) {
01532                 DBGC ( hub, "USB hub %s port %d could not get speed: %s\n",
01533                        hub->name, port->address, strerror ( rc ) );
01534                 goto err_speed;
01535         }
01536         usb->speed = port->speed;
01537         DBGC2 ( usb, "USB %s attached as %s-speed device\n",
01538                 usb->name, usb_speed_name ( usb->speed ) );
01539 
01540         /* Open device */
01541         if ( ( rc = usb->host->open ( usb ) ) != 0 ) {
01542                 DBGC ( usb, "USB %s could not open: %s\n",
01543                        usb->name, strerror ( rc ) );
01544                 goto err_open;
01545         }
01546 
01547         /* Describe control endpoint */
01548         mtu = USB_EP0_DEFAULT_MTU ( usb->speed );
01549         usb_endpoint_describe ( &usb->control, USB_EP0_ADDRESS,
01550                                 USB_EP0_ATTRIBUTES, mtu, USB_EP0_BURST,
01551                                 USB_EP0_INTERVAL );
01552 
01553         /* Open control endpoint */
01554         if ( ( rc = usb_endpoint_open ( &usb->control ) ) != 0 )
01555                 goto err_open_control;
01556         assert ( usb_endpoint ( usb, USB_EP0_ADDRESS ) == &usb->control );
01557 
01558         /* Assign device address */
01559         if ( ( rc = usb->host->address ( usb ) ) != 0 ) {
01560                 DBGC ( usb, "USB %s could not set address: %s\n",
01561                        usb->name, strerror ( rc ) );
01562                 goto err_address;
01563         }
01564         DBGC2 ( usb, "USB %s assigned address %d\n", usb->name, usb->address );
01565 
01566         /* Allow recovery interval after Set Address command */
01567         mdelay ( USB_SET_ADDRESS_RECOVER_DELAY_MS );
01568 
01569         /* Read first part of device descriptor to get EP0 MTU */
01570         if ( ( rc = usb_get_mtu ( usb, &usb->device ) ) != 0 ) {
01571                 DBGC ( usb, "USB %s could not get MTU: %s\n",
01572                        usb->name, strerror ( rc ) );
01573                 goto err_get_mtu;
01574         }
01575 
01576         /* Calculate EP0 MTU */
01577         protocol = le16_to_cpu ( usb->device.protocol );
01578         mtu = ( ( protocol < USB_PROTO_3_0 ) ?
01579                 usb->device.mtu : ( 1 << usb->device.mtu ) );
01580         DBGC2 ( usb, "USB %s has control MTU %zd (guessed %zd)\n",
01581                 usb->name, mtu, usb->control.mtu );
01582 
01583         /* Update MTU */
01584         if ( ( rc = usb_endpoint_mtu ( &usb->control, mtu ) ) != 0 )
01585                 goto err_mtu;
01586 
01587         /* Read whole device descriptor */
01588         if ( ( rc = usb_get_device_descriptor ( usb, &usb->device ) ) != 0 ) {
01589                 DBGC ( usb, "USB %s could not get device descriptor: %s\n",
01590                        usb->name, strerror ( rc ) );
01591                 goto err_get_device_descriptor;
01592         }
01593         DBGC ( usb, "USB %s addr %d %04x:%04x class %d:%d:%d (v%s, %s-speed, "
01594                "MTU %zd)\n", usb->name, usb->address,
01595                le16_to_cpu ( usb->device.vendor ),
01596                le16_to_cpu ( usb->device.product ), usb->device.class.class,
01597                usb->device.class.subclass, usb->device.class.protocol,
01598                usb_bcd ( le16_to_cpu ( usb->device.protocol ) ),
01599                usb_speed_name ( usb->speed ), usb->control.mtu );
01600 
01601         /* Configure device */
01602         if ( ( rc = usb_autoconfigure ( usb ) ) != 0 )
01603                 goto err_autoconfigure;
01604 
01605         return 0;
01606 
01607         usb_deconfigure ( usb );
01608  err_autoconfigure:
01609  err_get_device_descriptor:
01610  err_mtu:
01611  err_get_mtu:
01612  err_address:
01613         usb_endpoint_close ( &usb->control );
01614  err_open_control:
01615         usb->host->close ( usb );
01616  err_open:
01617  err_speed:
01618         hub->driver->disable ( hub, port );
01619  err_enable:
01620         list_del ( &usb->list );
01621         port->usb = NULL;
01622  err_already:
01623         return rc;
01624 }
01625 
01626 /**
01627  * Unregister USB device
01628  *
01629  * @v usb               USB device
01630  */
01631 static void unregister_usb ( struct usb_device *usb ) {
01632         struct usb_port *port = usb->port;
01633         struct usb_hub *hub = port->hub;
01634         struct io_buffer *iobuf;
01635         struct io_buffer *tmp;
01636 
01637         /* Sanity checks */
01638         assert ( port->usb == usb );
01639 
01640         /* Clear device configuration */
01641         usb_deconfigure ( usb );
01642 
01643         /* Close control endpoint */
01644         usb_endpoint_close ( &usb->control );
01645 
01646         /* Discard any stale control completions */
01647         list_for_each_entry_safe ( iobuf, tmp, &usb->complete, list ) {
01648                 list_del ( &iobuf->list );
01649                 free_iob ( iobuf );
01650         }
01651 
01652         /* Close device */
01653         usb->host->close ( usb );
01654 
01655         /* Disable port */
01656         hub->driver->disable ( hub, port );
01657 
01658         /* Remove from bus device list */
01659         list_del ( &usb->list );
01660 
01661         /* Remove from port */
01662         port->usb = NULL;
01663 }
01664 
01665 /**
01666  * Free USB device
01667  *
01668  * @v usb               USB device
01669  */
01670 static void free_usb ( struct usb_device *usb ) {
01671         unsigned int i;
01672 
01673         /* Sanity checks */
01674         for ( i = 0 ; i < ( sizeof ( usb->ep ) / sizeof ( usb->ep[0] ) ) ; i++ )
01675                 assert ( usb->ep[i] == NULL );
01676         assert ( list_empty ( &usb->functions ) );
01677         assert ( list_empty ( &usb->complete ) );
01678 
01679         /* Free device */
01680         free ( usb );
01681 }
01682 
01683 /******************************************************************************
01684  *
01685  * USB device hotplug event handling
01686  *
01687  ******************************************************************************
01688  */
01689 
01690 /**
01691  * Handle newly attached USB device
01692  *
01693  * @v port              USB port
01694  * @ret rc              Return status code
01695  */
01696 static int usb_attached ( struct usb_port *port ) {
01697         struct usb_device *usb;
01698         int rc;
01699 
01700         /* Mark port as attached */
01701         port->attached = 1;
01702 
01703         /* Sanity checks */
01704         assert ( port->usb == NULL );
01705 
01706         /* Allocate USB device */
01707         usb = alloc_usb ( port );
01708         if ( ! usb ) {
01709                 rc = -ENOMEM;
01710                 goto err_alloc;
01711         }
01712 
01713         /* Register USB device */
01714         if ( ( rc = register_usb ( usb ) ) != 0 )
01715                 goto err_register;
01716 
01717         return 0;
01718 
01719         unregister_usb ( usb );
01720  err_register:
01721         free_usb ( usb );
01722  err_alloc:
01723         return rc;
01724 }
01725 
01726 /**
01727  * Handle newly detached USB device
01728  *
01729  * @v port              USB port
01730  */
01731 static void usb_detached ( struct usb_port *port ) {
01732         struct usb_device *usb = port->usb;
01733 
01734         /* Mark port as detached */
01735         port->attached = 0;
01736 
01737         /* Do nothing if we have no USB device */
01738         if ( ! usb )
01739                 return;
01740 
01741         /* Unregister USB device */
01742         unregister_usb ( usb );
01743 
01744         /* Free USB device */
01745         free_usb ( usb );
01746 }
01747 
01748 /**
01749  * Handle newly attached or detached USB device
01750  *
01751  * @v port              USB port
01752  * @ret rc              Return status code
01753  */
01754 static int usb_hotplugged ( struct usb_port *port ) {
01755         struct usb_hub *hub = port->hub;
01756         int rc;
01757 
01758         /* Get current port speed */
01759         if ( ( rc = hub->driver->speed ( hub, port ) ) != 0 ) {
01760                 DBGC ( hub, "USB hub %s port %d could not get speed: %s\n",
01761                        hub->name, port->address, strerror ( rc ) );
01762                 /* Treat as a disconnection */
01763                 port->disconnected = 1;
01764                 port->speed = USB_SPEED_NONE;
01765         }
01766 
01767         /* Detach device, if applicable */
01768         if ( port->attached && ( port->disconnected || ! port->speed ) )
01769                 usb_detached ( port );
01770 
01771         /* Clear any recorded disconnections */
01772         port->disconnected = 0;
01773 
01774         /* Attach device, if applicable */
01775         if ( port->speed && ( ! port->attached ) &&
01776              ( ( rc = usb_attached ( port ) ) != 0 ) )
01777                 return rc;
01778 
01779         return 0;
01780 }
01781 
01782 /******************************************************************************
01783  *
01784  * USB process
01785  *
01786  ******************************************************************************
01787  */
01788 
01789 /**
01790  * Report port status change
01791  *
01792  * @v port              USB port
01793  */
01794 void usb_port_changed ( struct usb_port *port ) {
01795 
01796         /* Record hub port status change */
01797         list_del ( &port->changed );
01798         list_add_tail ( &port->changed, &usb_changed );
01799 }
01800 
01801 /**
01802  * Handle newly attached or detached USB device
01803  *
01804  */
01805 static void usb_hotplug ( void ) {
01806         struct usb_port *port;
01807 
01808         /* Handle any changed ports, allowing for the fact that the
01809          * port list may change as we perform hotplug actions.
01810          */
01811         while ( ! list_empty ( &usb_changed ) ) {
01812 
01813                 /* Get first changed port */
01814                 port = list_first_entry ( &usb_changed, struct usb_port,
01815                                           changed );
01816                 assert ( port != NULL );
01817 
01818                 /* Remove from list of changed ports */
01819                 list_del ( &port->changed );
01820                 INIT_LIST_HEAD ( &port->changed );
01821 
01822                 /* Perform appropriate hotplug action */
01823                 usb_hotplugged ( port );
01824         }
01825 }
01826 
01827 /**
01828  * USB process
01829  *
01830  * @v process           USB process
01831  */
01832 static void usb_step ( struct process *process __unused ) {
01833         struct usb_bus *bus;
01834         struct usb_endpoint *ep;
01835 
01836         /* Poll all buses */
01837         for_each_usb_bus ( bus )
01838                 usb_poll ( bus );
01839 
01840         /* Attempt to reset first halted endpoint in list, if any.  We
01841          * do not attempt to process the complete list, since this
01842          * would require extra code to allow for the facts that the
01843          * halted endpoint list may change as we do so, and that
01844          * resetting an endpoint may fail.
01845          */
01846         if ( ( ep = list_first_entry ( &usb_halted, struct usb_endpoint,
01847                                        halted ) ) != NULL )
01848                 usb_endpoint_reset ( ep );
01849 
01850         /* Handle any changed ports */
01851         usb_hotplug();
01852 }
01853 
01854 /** USB process */
01855 PERMANENT_PROCESS ( usb_process, usb_step );
01856 
01857 /******************************************************************************
01858  *
01859  * USB hub
01860  *
01861  ******************************************************************************
01862  */
01863 
01864 /**
01865  * Allocate USB hub
01866  *
01867  * @v bus               USB bus
01868  * @v usb               Underlying USB device, if any
01869  * @v ports             Number of ports
01870  * @v driver            Hub driver operations
01871  * @ret hub             USB hub, or NULL on allocation failure
01872  */
01873 struct usb_hub * alloc_usb_hub ( struct usb_bus *bus, struct usb_device *usb,
01874                                  unsigned int ports,
01875                                  struct usb_hub_driver_operations *driver ) {
01876         struct usb_hub *hub;
01877         struct usb_port *port;
01878         unsigned int i;
01879 
01880         /* Allocate and initialise structure */
01881         hub = zalloc ( sizeof ( *hub ) + ( ports * sizeof ( hub->port[0] ) ) );
01882         if ( ! hub )
01883                 return NULL;
01884         hub->name = ( usb ? usb->name : bus->name );
01885         hub->bus = bus;
01886         hub->usb = usb;
01887         if ( usb )
01888                 hub->protocol = usb->port->protocol;
01889         hub->ports = ports;
01890         hub->driver = driver;
01891         hub->host = &bus->op->hub;
01892 
01893         /* Initialise port list */
01894         for ( i = 1 ; i <= hub->ports ; i++ ) {
01895                 port = usb_port ( hub, i );
01896                 port->hub = hub;
01897                 port->address = i;
01898                 if ( usb )
01899                         port->protocol = usb->port->protocol;
01900                 INIT_LIST_HEAD ( &port->changed );
01901         }
01902 
01903         return hub;
01904 }
01905 
01906 /**
01907  * Register USB hub
01908  *
01909  * @v hub               USB hub
01910  * @ret rc              Return status code
01911  */
01912 int register_usb_hub ( struct usb_hub *hub ) {
01913         struct usb_bus *bus = hub->bus;
01914         struct usb_port *port;
01915         unsigned int i;
01916         int rc;
01917 
01918         /* Add to hub list */
01919         list_add_tail ( &hub->list, &bus->hubs );
01920 
01921         /* Open hub (host controller) */
01922         if ( ( rc = hub->host->open ( hub ) ) != 0 ) {
01923                 DBGC ( hub, "USB hub %s could not open: %s\n",
01924                        hub->name, strerror ( rc ) );
01925                 goto err_host_open;
01926         }
01927 
01928         /* Open hub (driver) */
01929         if ( ( rc = hub->driver->open ( hub ) ) != 0 ) {
01930                 DBGC ( hub, "USB hub %s could not open: %s\n",
01931                        hub->name, strerror ( rc ) );
01932                 goto err_driver_open;
01933         }
01934 
01935         /* Delay to allow ports to stabilise */
01936         mdelay ( USB_PORT_DELAY_MS );
01937 
01938         /* Mark all ports as changed */
01939         for ( i = 1 ; i <= hub->ports ; i++ ) {
01940                 port = usb_port ( hub, i );
01941                 usb_port_changed ( port );
01942         }
01943 
01944         /* Some hubs seem to defer reporting device connections until
01945          * their interrupt endpoint is polled for the first time.
01946          * Poll the bus once now in order to pick up any such
01947          * connections.
01948          */
01949         usb_poll ( bus );
01950 
01951         return 0;
01952 
01953         hub->driver->close ( hub );
01954  err_driver_open:
01955         hub->host->close ( hub );
01956  err_host_open:
01957         list_del ( &hub->list );
01958         return rc;
01959 }
01960 
01961 /**
01962  * Unregister USB hub
01963  *
01964  * @v hub               USB hub
01965  */
01966 void unregister_usb_hub ( struct usb_hub *hub ) {
01967         struct usb_port *port;
01968         unsigned int i;
01969 
01970         /* Detach all devices */
01971         for ( i = 1 ; i <= hub->ports ; i++ ) {
01972                 port = usb_port ( hub, i );
01973                 if ( port->attached )
01974                         usb_detached ( port );
01975         }
01976 
01977         /* Close hub (driver) */
01978         hub->driver->close ( hub );
01979 
01980         /* Close hub (host controller) */
01981         hub->host->close ( hub );
01982 
01983         /* Cancel any pending port status changes */
01984         for ( i = 1 ; i <= hub->ports ; i++ ) {
01985                 port = usb_port ( hub, i );
01986                 list_del ( &port->changed );
01987                 INIT_LIST_HEAD ( &port->changed );
01988         }
01989 
01990         /* Remove from hub list */
01991         list_del ( &hub->list );
01992 }
01993 
01994 /**
01995  * Free USB hub
01996  *
01997  * @v hub               USB hub
01998  */
01999 void free_usb_hub ( struct usb_hub *hub ) {
02000         struct usb_port *port;
02001         unsigned int i;
02002 
02003         /* Sanity checks */
02004         for ( i = 1 ; i <= hub->ports ; i++ ) {
02005                 port = usb_port ( hub, i );
02006                 assert ( ! port->attached );
02007                 assert ( port->usb == NULL );
02008                 assert ( list_empty ( &port->changed ) );
02009         }
02010 
02011         /* Free hub */
02012         free ( hub );
02013 }
02014 
02015 /******************************************************************************
02016  *
02017  * USB bus
02018  *
02019  ******************************************************************************
02020  */
02021 
02022 /**
02023  * Allocate USB bus
02024  *
02025  * @v dev               Underlying hardware device
02026  * @v ports             Number of root hub ports
02027  * @v mtu               Largest transfer allowed on the bus
02028  * @v op                Host controller operations
02029  * @ret bus             USB bus, or NULL on allocation failure
02030  */
02031 struct usb_bus * alloc_usb_bus ( struct device *dev, unsigned int ports,
02032                                  size_t mtu, struct usb_host_operations *op ) {
02033         struct usb_bus *bus;
02034 
02035         /* Allocate and initialise structure */
02036         bus = zalloc ( sizeof ( *bus ) );
02037         if ( ! bus )
02038                 goto err_alloc_bus;
02039         bus->name = dev->name;
02040         bus->dev = dev;
02041         bus->mtu = mtu;
02042         bus->op = op;
02043         INIT_LIST_HEAD ( &bus->devices );
02044         INIT_LIST_HEAD ( &bus->hubs );
02045         bus->host = &bus->op->bus;
02046 
02047         /* Allocate root hub */
02048         bus->hub = alloc_usb_hub ( bus, NULL, ports, &op->root );
02049         if ( ! bus->hub )
02050                 goto err_alloc_hub;
02051 
02052         return bus;
02053 
02054         free_usb_hub ( bus->hub );
02055  err_alloc_hub:
02056         free ( bus );
02057  err_alloc_bus:
02058         return NULL;
02059 }
02060 
02061 /**
02062  * Register USB bus
02063  *
02064  * @v bus               USB bus
02065  * @ret rc              Return status code
02066  */
02067 int register_usb_bus ( struct usb_bus *bus ) {
02068         int rc;
02069 
02070         /* Sanity checks */
02071         assert ( bus->hub != NULL );
02072 
02073         /* Open bus */
02074         if ( ( rc = bus->host->open ( bus ) ) != 0 )
02075                 goto err_open;
02076 
02077         /* Add to list of USB buses */
02078         list_add_tail ( &bus->list, &usb_buses );
02079 
02080         /* Register root hub */
02081         if ( ( rc = register_usb_hub ( bus->hub ) ) != 0 )
02082                 goto err_register_hub;
02083 
02084         /* Attach any devices already present */
02085         usb_hotplug();
02086 
02087         return 0;
02088 
02089         unregister_usb_hub ( bus->hub );
02090  err_register_hub:
02091         list_del ( &bus->list );
02092         bus->host->close ( bus );
02093  err_open:
02094         return rc;
02095 }
02096 
02097 /**
02098  * Unregister USB bus
02099  *
02100  * @v bus               USB bus
02101  */
02102 void unregister_usb_bus ( struct usb_bus *bus ) {
02103 
02104         /* Sanity checks */
02105         assert ( bus->hub != NULL );
02106 
02107         /* Unregister root hub */
02108         unregister_usb_hub ( bus->hub );
02109 
02110         /* Remove from list of USB buses */
02111         list_del ( &bus->list );
02112 
02113         /* Close bus */
02114         bus->host->close ( bus );
02115 
02116         /* Sanity checks */
02117         assert ( list_empty ( &bus->devices ) );
02118         assert ( list_empty ( &bus->hubs ) );
02119 }
02120 
02121 /**
02122  * Free USB bus
02123  *
02124  * @v bus               USB bus
02125  */
02126 void free_usb_bus ( struct usb_bus *bus ) {
02127         struct usb_endpoint *ep;
02128         struct usb_port *port;
02129 
02130         /* Sanity checks */
02131         assert ( list_empty ( &bus->devices ) );
02132         assert ( list_empty ( &bus->hubs ) );
02133         list_for_each_entry ( ep, &usb_halted, halted )
02134                 assert ( ep->usb->port->hub->bus != bus );
02135         list_for_each_entry ( port, &usb_changed, changed )
02136                 assert ( port->hub->bus != bus );
02137 
02138         /* Free root hub */
02139         free_usb_hub ( bus->hub );
02140 
02141         /* Free bus */
02142         free ( bus );
02143 }
02144 
02145 /**
02146  * Find USB bus by device location
02147  *
02148  * @v bus_type          Bus type
02149  * @v location          Bus location
02150  * @ret bus             USB bus, or NULL
02151  */
02152 struct usb_bus * find_usb_bus_by_location ( unsigned int bus_type,
02153                                             unsigned int location ) {
02154         struct usb_bus *bus;
02155 
02156         for_each_usb_bus ( bus ) {
02157                 if ( ( bus->dev->desc.bus_type == bus_type ) &&
02158                      ( bus->dev->desc.location == location ) )
02159                         return bus;
02160         }
02161 
02162         return NULL;
02163 }
02164 
02165 /******************************************************************************
02166  *
02167  * USB address assignment
02168  *
02169  ******************************************************************************
02170  */
02171 
02172 /**
02173  * Allocate device address
02174  *
02175  * @v bus               USB bus
02176  * @ret address         Device address, or negative error
02177  */
02178 int usb_alloc_address ( struct usb_bus *bus ) {
02179         unsigned int address;
02180 
02181         /* Find first free device address */
02182         address = ffsll ( ~bus->addresses );
02183         if ( ! address )
02184                 return -ENOENT;
02185 
02186         /* Mark address as used */
02187         bus->addresses |= ( 1ULL << ( address - 1 ) );
02188 
02189         return address;
02190 }
02191 
02192 /**
02193  * Free device address
02194  *
02195  * @v bus               USB bus
02196  * @v address           Device address
02197  */
02198 void usb_free_address ( struct usb_bus *bus, unsigned int address ) {
02199 
02200         /* Sanity check */
02201         assert ( address > 0 );
02202         assert ( bus->addresses & ( 1ULL << ( address - 1 ) ) );
02203 
02204         /* Mark address as free */
02205         bus->addresses &= ~( 1ULL << ( address - 1 ) );
02206 }
02207 
02208 /******************************************************************************
02209  *
02210  * USB bus topology
02211  *
02212  ******************************************************************************
02213  */
02214 
02215 /**
02216  * Get USB route string
02217  *
02218  * @v usb               USB device
02219  * @ret route           USB route string
02220  */
02221 unsigned int usb_route_string ( struct usb_device *usb ) {
02222         struct usb_device *parent;
02223         unsigned int route;
02224 
02225         /* Navigate up to root hub, constructing route string as we go */
02226         for ( route = 0 ; ( parent = usb->port->hub->usb ) ; usb = parent ) {
02227                 route <<= 4;
02228                 route |= ( ( usb->port->address > 0xf ) ?
02229                            0xf : usb->port->address );
02230         }
02231 
02232         return route;
02233 }
02234 
02235 /**
02236  * Get USB depth
02237  *
02238  * @v usb               USB device
02239  * @ret depth           Hub depth
02240  */
02241 unsigned int usb_depth ( struct usb_device *usb ) {
02242         struct usb_device *parent;
02243         unsigned int depth;
02244 
02245         /* Navigate up to root hub, constructing depth as we go */
02246         for ( depth = 0 ; ( parent = usb->port->hub->usb ) ; usb = parent )
02247                 depth++;
02248 
02249         return depth;
02250 }
02251 
02252 /**
02253  * Get USB root hub port
02254  *
02255  * @v usb               USB device
02256  * @ret port            Root hub port
02257  */
02258 struct usb_port * usb_root_hub_port ( struct usb_device *usb ) {
02259         struct usb_device *parent;
02260 
02261         /* Navigate up to root hub */
02262         while ( ( parent = usb->port->hub->usb ) )
02263                 usb = parent;
02264 
02265         return usb->port;
02266 }
02267 
02268 /**
02269  * Get USB transaction translator
02270  *
02271  * @v usb               USB device
02272  * @ret port            Transaction translator port, or NULL
02273  */
02274 struct usb_port * usb_transaction_translator ( struct usb_device *usb ) {
02275         struct usb_device *parent;
02276 
02277         /* Navigate up to root hub.  If we find a low-speed or
02278          * full-speed device with a higher-speed parent hub, then that
02279          * device's port is the transaction translator.
02280          */
02281         for ( ; ( parent = usb->port->hub->usb ) ; usb = parent ) {
02282                 if ( ( usb->speed <= USB_SPEED_FULL ) &&
02283                      ( parent->speed > USB_SPEED_FULL ) )
02284                         return usb->port;
02285         }
02286 
02287         return NULL;
02288 }
02289 
02290 /* Drag in objects via register_usb_bus() */
02291 REQUIRING_SYMBOL ( register_usb_bus );
02292 
02293 /* Drag in USB configuration */
02294 REQUIRE_OBJECT ( config_usb );
02295 
02296 /* Drag in hub driver */
02297 REQUIRE_OBJECT ( usbhub );