These changes are the raw update to qemu-2.6.
[kvmfornfv.git] / qemu / roms / ipxe / src / drivers / bus / usb.c
1 /*
2  * Copyright (C) 2014 Michael Brown <mbrown@fensystems.co.uk>.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License as
6  * published by the Free Software Foundation; either version 2 of the
7  * License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17  * 02110-1301, USA.
18  *
19  * You can also choose to distribute this program under the terms of
20  * the Unmodified Binary Distribution Licence (as given in the file
21  * COPYING.UBDL), provided that you have satisfied its requirements.
22  */
23
24 FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL );
25
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <strings.h>
30 #include <unistd.h>
31 #include <errno.h>
32 #include <assert.h>
33 #include <byteswap.h>
34 #include <ipxe/usb.h>
35 #include <ipxe/cdc.h>
36
37 /** @file
38  *
39  * Universal Serial Bus (USB)
40  *
41  */
42
43 /** List of USB buses */
44 struct list_head usb_buses = LIST_HEAD_INIT ( usb_buses );
45
46 /** List of changed ports */
47 static struct list_head usb_changed = LIST_HEAD_INIT ( usb_changed );
48
49 /** List of halted endpoints */
50 static struct list_head usb_halted = LIST_HEAD_INIT ( usb_halted );
51
52 /******************************************************************************
53  *
54  * Utility functions
55  *
56  ******************************************************************************
57  */
58
59 /**
60  * Get USB speed name (for debugging)
61  *
62  * @v speed             Speed
63  * @ret name            Speed name
64  */
65 static inline const char * usb_speed_name ( unsigned int speed ) {
66         static const char *exponents[4] = { "", "k", "M", "G" };
67         static char buf[ 10 /* "xxxxxXbps" + NUL */ ];
68         unsigned int mantissa;
69         unsigned int exponent;
70
71         /* Extract mantissa and exponent */
72         mantissa = USB_SPEED_MANTISSA ( speed );
73         exponent = USB_SPEED_EXPONENT ( speed );
74
75         /* Name speed */
76         switch ( speed ) {
77         case USB_SPEED_NONE:            return "DETACHED";
78         case USB_SPEED_LOW:             return "low";
79         case USB_SPEED_FULL:            return "full";
80         case USB_SPEED_HIGH:            return "high";
81         case USB_SPEED_SUPER:           return "super";
82         default:
83                 snprintf ( buf, sizeof ( buf ), "%d%sbps",
84                            mantissa, exponents[exponent] );
85                 return buf;
86         }
87 }
88
89 /**
90  * Transcribe USB BCD-coded value (for debugging)
91  *
92  * @v bcd               BCD-coded value
93  * @ret string          Transcribed value
94  */
95 static inline const char * usb_bcd ( uint16_t bcd ) {
96         static char buf[ 6 /* "xx.xx" + NUL */ ];
97         uint8_t high = ( bcd >> 8 );
98         uint8_t low = ( bcd >> 0 );
99
100         snprintf ( buf, sizeof ( buf ), "%x.%02x", high, low );
101         return buf;
102 }
103
104 /******************************************************************************
105  *
106  * USB descriptors
107  *
108  ******************************************************************************
109  */
110
111 /**
112  * Locate USB interface association descriptor
113  *
114  * @v config            Configuraton descriptor
115  * @v first             First interface number
116  * @ret desc            Interface association descriptor, or NULL if not found
117  */
118 static struct usb_interface_association_descriptor *
119 usb_interface_association_descriptor ( struct usb_configuration_descriptor
120                                                                        *config,
121                                        unsigned int first ) {
122         struct usb_interface_association_descriptor *desc;
123
124         /* Find a matching interface association descriptor */
125         for_each_config_descriptor ( desc, config ) {
126                 if ( ( desc->header.type ==
127                        USB_INTERFACE_ASSOCIATION_DESCRIPTOR ) &&
128                      ( desc->first == first ) )
129                         return desc;
130         }
131         return NULL;
132 }
133
134 /**
135  * Locate USB interface descriptor
136  *
137  * @v config            Configuraton descriptor
138  * @v interface         Interface number
139  * @v alternate         Alternate setting
140  * @ret desc            Interface descriptor, or NULL if not found
141  */
142 struct usb_interface_descriptor *
143 usb_interface_descriptor ( struct usb_configuration_descriptor *config,
144                            unsigned int interface, unsigned int alternate ) {
145         struct usb_interface_descriptor *desc;
146
147         /* Find a matching interface descriptor */
148         for_each_config_descriptor ( desc, config ) {
149                 if ( ( desc->header.type == USB_INTERFACE_DESCRIPTOR ) &&
150                      ( desc->interface == interface ) &&
151                      ( desc->alternate == alternate ) )
152                         return desc;
153         }
154         return NULL;
155 }
156
157 /**
158  * Locate USB endpoint descriptor
159  *
160  * @v config            Configuration descriptor
161  * @v interface         Interface descriptor
162  * @v type              Endpoint (internal) type
163  * @v index             Endpoint index
164  * @ret desc            Descriptor, or NULL if not found
165  */
166 struct usb_endpoint_descriptor *
167 usb_endpoint_descriptor ( struct usb_configuration_descriptor *config,
168                           struct usb_interface_descriptor *interface,
169                           unsigned int type, unsigned int index ) {
170         struct usb_endpoint_descriptor *desc;
171         unsigned int attributes = ( type & USB_ENDPOINT_ATTR_TYPE_MASK );
172         unsigned int direction = ( type & USB_DIR_IN );
173
174         /* Find a matching endpoint descriptor */
175         for_each_interface_descriptor ( desc, config, interface ) {
176                 if ( ( desc->header.type == USB_ENDPOINT_DESCRIPTOR ) &&
177                      ( ( desc->attributes &
178                          USB_ENDPOINT_ATTR_TYPE_MASK ) == attributes ) &&
179                      ( ( desc->endpoint & USB_DIR_IN ) == direction ) &&
180                      ( index-- == 0 ) )
181                         return desc;
182         }
183         return NULL;
184 }
185
186 /**
187  * Locate USB endpoint companion descriptor
188  *
189  * @v config            Configuration descriptor
190  * @v desc              Endpoint descriptor
191  * @ret descx           Companion descriptor, or NULL if not found
192  */
193 struct usb_endpoint_companion_descriptor *
194 usb_endpoint_companion_descriptor ( struct usb_configuration_descriptor *config,
195                                     struct usb_endpoint_descriptor *desc ) {
196         struct usb_endpoint_companion_descriptor *descx;
197
198         /* Get companion descriptor, if present */
199         descx = container_of ( usb_next_descriptor ( &desc->header ),
200                                struct usb_endpoint_companion_descriptor,
201                                header );
202         return ( ( usb_is_within_config ( config, &descx->header ) &&
203                    descx->header.type == USB_ENDPOINT_COMPANION_DESCRIPTOR )
204                  ? descx : NULL );
205 }
206
207 /******************************************************************************
208  *
209  * USB endpoint
210  *
211  ******************************************************************************
212  */
213
214 /**
215  * Get USB endpoint name (for debugging)
216  *
217  * @v ep                USB endpoint
218  * @ret name            Endpoint name
219  */
220 const char * usb_endpoint_name ( struct usb_endpoint *ep ) {
221         static char buf[ 9 /* "EPxx OUT" + NUL */ ];
222         unsigned int address = ep->address;
223
224         snprintf ( buf, sizeof ( buf ), "EP%d%s",
225                    ( address & USB_ENDPOINT_MAX ),
226                    ( address ?
227                      ( ( address & USB_ENDPOINT_IN ) ? " IN" : " OUT" ) : "" ));
228         return buf;
229 }
230
231 /**
232  * Describe USB endpoint from device configuration
233  *
234  * @v ep                USB endpoint
235  * @v config            Configuration descriptor
236  * @v interface         Interface descriptor
237  * @v type              Endpoint (internal) type
238  * @v index             Endpoint index
239  * @ret rc              Return status code
240  */
241 int usb_endpoint_described ( struct usb_endpoint *ep,
242                              struct usb_configuration_descriptor *config,
243                              struct usb_interface_descriptor *interface,
244                              unsigned int type, unsigned int index ) {
245         struct usb_device *usb = ep->usb;
246         struct usb_port *port = usb->port;
247         struct usb_endpoint_descriptor *desc;
248         struct usb_endpoint_companion_descriptor *descx;
249         unsigned int sizes;
250         unsigned int burst;
251         unsigned int interval;
252         size_t mtu;
253
254         /* Locate endpoint descriptor */
255         desc = usb_endpoint_descriptor ( config, interface, type, index );
256         if ( ! desc )
257                 return -ENOENT;
258
259         /* Locate companion descriptor, if any */
260         descx = usb_endpoint_companion_descriptor ( config, desc );
261
262         /* Calculate MTU and burst size */
263         sizes = le16_to_cpu ( desc->sizes );
264         mtu = USB_ENDPOINT_MTU ( sizes );
265         burst = ( descx ? descx->burst : USB_ENDPOINT_BURST ( sizes ) );
266
267         /* Calculate interval */
268         if ( ( type & USB_ENDPOINT_ATTR_TYPE_MASK ) ==
269              USB_ENDPOINT_ATTR_INTERRUPT ) {
270                 if ( port->speed >= USB_SPEED_HIGH ) {
271                         /* 2^(desc->interval-1) is a microframe count */
272                         interval = ( 1 << ( desc->interval - 1 ) );
273                 } else {
274                         /* desc->interval is a (whole) frame count */
275                         interval = ( desc->interval << 3 );
276                 }
277         } else {
278                 /* desc->interval is a microframe count */
279                 interval = desc->interval;
280         }
281
282         /* Describe endpoint */
283         usb_endpoint_describe ( ep, desc->endpoint, desc->attributes,
284                                 mtu, burst, interval );
285         return 0;
286 }
287
288 /**
289  * Open USB endpoint
290  *
291  * @v ep                USB endpoint
292  * @ret rc              Return status code
293  */
294 int usb_endpoint_open ( struct usb_endpoint *ep ) {
295         struct usb_device *usb = ep->usb;
296         unsigned int idx = USB_ENDPOINT_IDX ( ep->address );
297         int rc;
298
299         /* Populate host controller operations */
300         ep->host = &usb->port->hub->bus->op->endpoint;
301
302         /* Add to endpoint list */
303         if ( usb->ep[idx] != NULL ) {
304                 DBGC ( usb, "USB %s %s is already open\n",
305                        usb->name, usb_endpoint_name ( ep ) );
306                 rc = -EALREADY;
307                 goto err_already;
308         }
309         usb->ep[idx] = ep;
310         INIT_LIST_HEAD ( &ep->halted );
311
312         /* Open endpoint */
313         if ( ( rc = ep->host->open ( ep ) ) != 0 ) {
314                 DBGC ( usb, "USB %s %s could not open: %s\n", usb->name,
315                        usb_endpoint_name ( ep ), strerror ( rc ) );
316                 goto err_open;
317         }
318         ep->open = 1;
319
320         DBGC2 ( usb, "USB %s %s opened with MTU %zd, burst %d, interval %d\n",
321                 usb->name, usb_endpoint_name ( ep ), ep->mtu, ep->burst,
322                 ep->interval );
323         return 0;
324
325         ep->open = 0;
326         ep->host->close ( ep );
327  err_open:
328         usb->ep[idx] = NULL;
329  err_already:
330         if ( ep->max )
331                 usb_flush ( ep );
332         return rc;
333 }
334
335 /**
336  * Clear transaction translator (if applicable)
337  *
338  * @v ep                USB endpoint
339  * @ret rc              Return status code
340  */
341 static int usb_endpoint_clear_tt ( struct usb_endpoint *ep ) {
342         struct usb_device *usb = ep->usb;
343         struct usb_port *tt;
344         int rc;
345
346         /* Do nothing if this is a periodic endpoint */
347         if ( ep->attributes & USB_ENDPOINT_ATTR_PERIODIC )
348                 return 0;
349
350         /* Do nothing if this endpoint is not behind a transaction translator */
351         tt = usb_transaction_translator ( usb );
352         if ( ! tt )
353                 return 0;
354
355         /* Clear transaction translator buffer */
356         if ( ( rc = tt->hub->driver->clear_tt ( tt->hub, tt, ep ) ) != 0 ) {
357                 DBGC ( usb, "USB %s %s could not clear transaction translator: "
358                        "%s\n", usb->name, usb_endpoint_name ( ep ),
359                        strerror ( rc ) );
360                 return rc;
361         }
362
363         return 0;
364 }
365
366 /**
367  * Close USB endpoint
368  *
369  * @v ep                USB endpoint
370  */
371 void usb_endpoint_close ( struct usb_endpoint *ep ) {
372         struct usb_device *usb = ep->usb;
373         unsigned int idx = USB_ENDPOINT_IDX ( ep->address );
374
375         /* Sanity checks */
376         assert ( usb->ep[idx] == ep );
377
378         /* Close endpoint */
379         ep->open = 0;
380         ep->host->close ( ep );
381         assert ( ep->fill == 0 );
382
383         /* Remove from endpoint list */
384         usb->ep[idx] = NULL;
385         list_del ( &ep->halted );
386
387         /* Discard any recycled buffers, if applicable */
388         if ( ep->max )
389                 usb_flush ( ep );
390
391         /* Clear transaction translator, if applicable */
392         usb_endpoint_clear_tt ( ep );
393 }
394
395 /**
396  * Reset USB endpoint
397  *
398  * @v ep                USB endpoint
399  * @ret rc              Return status code
400  */
401 static int usb_endpoint_reset ( struct usb_endpoint *ep ) {
402         struct usb_device *usb = ep->usb;
403         unsigned int type;
404         int rc;
405
406         /* Sanity check */
407         assert ( ! list_empty ( &ep->halted ) );
408
409         /* Reset endpoint */
410         if ( ( rc = ep->host->reset ( ep ) ) != 0 ) {
411                 DBGC ( usb, "USB %s %s could not reset: %s\n",
412                        usb->name, usb_endpoint_name ( ep ), strerror ( rc ) );
413                 return rc;
414         }
415
416         /* Clear transaction translator, if applicable */
417         if ( ( rc = usb_endpoint_clear_tt ( ep ) ) != 0 )
418                 return rc;
419
420         /* Clear endpoint halt, if applicable */
421         type = ( ep->attributes & USB_ENDPOINT_ATTR_TYPE_MASK );
422         if ( ( type != USB_ENDPOINT_ATTR_CONTROL ) &&
423              ( ( rc = usb_clear_feature ( usb, USB_RECIP_ENDPOINT,
424                                           USB_ENDPOINT_HALT,
425                                           ep->address ) ) != 0 ) ) {
426                 DBGC ( usb, "USB %s %s could not clear endpoint halt: %s\n",
427                        usb->name, usb_endpoint_name ( ep ), strerror ( rc ) );
428                 return rc;
429         }
430
431         /* Remove from list of halted endpoints */
432         list_del ( &ep->halted );
433         INIT_LIST_HEAD ( &ep->halted );
434
435         DBGC ( usb, "USB %s %s reset\n",
436                usb->name, usb_endpoint_name ( ep ) );
437         return 0;
438 }
439
440 /**
441  * Update endpoint MTU
442  *
443  * @v ep                USB endpoint
444  * @v mtu               New MTU
445  * @ret rc              Return status code
446  */
447 static int usb_endpoint_mtu ( struct usb_endpoint *ep, size_t mtu ) {
448         struct usb_device *usb = ep->usb;
449         int rc;
450
451         /* Update MTU */
452         ep->mtu = mtu;
453         if ( ( rc = ep->host->mtu ( ep ) ) != 0 ) {
454                 DBGC ( usb, "USB %s %s could not update MTU: %s\n",
455                        usb->name, usb_endpoint_name ( ep ), strerror ( rc ) );
456                 return rc;
457         }
458
459         return 0;
460 }
461
462 /**
463  * Enqueue USB message transfer
464  *
465  * @v ep                USB endpoint
466  * @v request           Request
467  * @v value             Value parameter
468  * @v index             Index parameter
469  * @v iobuf             I/O buffer
470  * @ret rc              Return status code
471  *
472  * The I/O buffer must have sufficient headroom to contain a setup
473  * packet.
474  */
475 int usb_message ( struct usb_endpoint *ep, unsigned int request,
476                   unsigned int value, unsigned int index,
477                   struct io_buffer *iobuf ) {
478         struct usb_device *usb = ep->usb;
479         struct usb_port *port = usb->port;
480         struct usb_setup_packet *packet;
481         size_t len = iob_len ( iobuf );
482         int rc;
483
484         /* Sanity check */
485         assert ( iob_headroom ( iobuf ) >= sizeof ( *packet ) );
486
487         /* Fail immediately if device has been unplugged */
488         if ( port->speed == USB_SPEED_NONE )
489                 return -ENODEV;
490
491         /* Reset endpoint if required */
492         if ( ( ! list_empty ( &ep->halted ) ) &&
493              ( ( rc = usb_endpoint_reset ( ep ) ) != 0 ) )
494                 return rc;
495
496         /* Zero input data buffer (if applicable) */
497         if ( request & USB_DIR_IN )
498                 memset ( iobuf->data, 0, len );
499
500         /* Construct setup packet */
501         packet = iob_push ( iobuf, sizeof ( *packet ) );
502         packet->request = cpu_to_le16 ( request );
503         packet->value = cpu_to_le16 ( value );
504         packet->index = cpu_to_le16 ( index );
505         packet->len = cpu_to_le16 ( len );
506
507         /* Enqueue message transfer */
508         if ( ( rc = ep->host->message ( ep, iobuf ) ) != 0 ) {
509                 DBGC ( usb, "USB %s %s could not enqueue message transfer: "
510                        "%s\n", usb->name, usb_endpoint_name ( ep ),
511                        strerror ( rc ) );
512                 return rc;
513         }
514
515         /* Increment fill level */
516         ep->fill++;
517
518         return 0;
519 }
520
521 /**
522  * Enqueue USB stream transfer
523  *
524  * @v ep                USB endpoint
525  * @v iobuf             I/O buffer
526  * @v terminate         Terminate using a short packet
527  * @ret rc              Return status code
528  */
529 int usb_stream ( struct usb_endpoint *ep, struct io_buffer *iobuf,
530                  int terminate ) {
531         struct usb_device *usb = ep->usb;
532         struct usb_port *port = usb->port;
533         int rc;
534
535         /* Fail immediately if device has been unplugged */
536         if ( port->speed == USB_SPEED_NONE )
537                 return -ENODEV;
538
539         /* Reset endpoint if required */
540         if ( ( ! list_empty ( &ep->halted ) ) &&
541              ( ( rc = usb_endpoint_reset ( ep ) ) != 0 ) )
542                 return rc;
543
544         /* Enqueue stream transfer */
545         if ( ( rc = ep->host->stream ( ep, iobuf, terminate ) ) != 0 ) {
546                 DBGC ( usb, "USB %s %s could not enqueue stream transfer: %s\n",
547                        usb->name, usb_endpoint_name ( ep ), strerror ( rc ) );
548                 return rc;
549         }
550
551         /* Increment fill level */
552         ep->fill++;
553
554         return 0;
555 }
556
557 /**
558  * Complete transfer (possibly with error)
559  *
560  * @v ep                USB endpoint
561  * @v iobuf             I/O buffer
562  * @v rc                Completion status code
563  */
564 void usb_complete_err ( struct usb_endpoint *ep, struct io_buffer *iobuf,
565                         int rc ) {
566         struct usb_device *usb = ep->usb;
567
568         /* Decrement fill level */
569         assert ( ep->fill > 0 );
570         ep->fill--;
571
572         /* Schedule reset, if applicable */
573         if ( ( rc != 0 ) && ep->open ) {
574                 DBGC ( usb, "USB %s %s completion failed: %s\n",
575                        usb->name, usb_endpoint_name ( ep ), strerror ( rc ) );
576                 list_del ( &ep->halted );
577                 list_add_tail ( &ep->halted, &usb_halted );
578         }
579
580         /* Report completion */
581         ep->driver->complete ( ep, iobuf, rc );
582 }
583
584 /******************************************************************************
585  *
586  * Endpoint refilling
587  *
588  ******************************************************************************
589  */
590
591 /**
592  * Prefill endpoint recycled buffer list
593  *
594  * @v ep                USB endpoint
595  * @ret rc              Return status code
596  */
597 int usb_prefill ( struct usb_endpoint *ep ) {
598         struct io_buffer *iobuf;
599         size_t len = ( ep->len ? ep->len : ep->mtu );
600         unsigned int fill;
601         int rc;
602
603         /* Sanity checks */
604         assert ( ep->fill == 0 );
605         assert ( ep->max > 0 );
606         assert ( list_empty ( &ep->recycled ) );
607
608         /* Fill recycled buffer list */
609         for ( fill = 0 ; fill < ep->max ; fill++ ) {
610
611                 /* Allocate I/O buffer */
612                 iobuf = alloc_iob ( len );
613                 if ( ! iobuf ) {
614                         rc = -ENOMEM;
615                         goto err_alloc;
616                 }
617
618                 /* Add to recycled buffer list */
619                 list_add_tail ( &iobuf->list, &ep->recycled );
620         }
621
622         return 0;
623
624  err_alloc:
625         usb_flush ( ep );
626         return rc;
627 }
628
629 /**
630  * Refill endpoint
631  *
632  * @v ep                USB endpoint
633  * @ret rc              Return status code
634  */
635 int usb_refill ( struct usb_endpoint *ep ) {
636         struct io_buffer *iobuf;
637         size_t len = ( ep->len ? ep->len : ep->mtu );
638         int rc;
639
640         /* Sanity checks */
641         assert ( ep->open );
642         assert ( ep->max > 0 );
643
644         /* Refill endpoint */
645         while ( ep->fill < ep->max ) {
646
647                 /* Get or allocate buffer */
648                 if ( list_empty ( &ep->recycled ) ) {
649                         /* Recycled buffer list is empty; allocate new buffer */
650                         iobuf = alloc_iob ( len );
651                         if ( ! iobuf )
652                                 return -ENOMEM;
653                 } else {
654                         /* Get buffer from recycled buffer list */
655                         iobuf = list_first_entry ( &ep->recycled,
656                                                    struct io_buffer, list );
657                         assert ( iobuf != NULL );
658                         list_del ( &iobuf->list );
659                 }
660
661                 /* Reset buffer to maximum size */
662                 assert ( iob_len ( iobuf ) <= len );
663                 iob_put ( iobuf, ( len - iob_len ( iobuf ) ) );
664
665                 /* Enqueue buffer */
666                 if ( ( rc = usb_stream ( ep, iobuf, 0 ) ) != 0 ) {
667                         list_add ( &iobuf->list, &ep->recycled );
668                         return rc;
669                 }
670         }
671
672         return 0;
673 }
674
675 /**
676  * Discard endpoint recycled buffer list
677  *
678  * @v ep                USB endpoint
679  */
680 void usb_flush ( struct usb_endpoint *ep ) {
681         struct io_buffer *iobuf;
682         struct io_buffer *tmp;
683
684         /* Sanity checks */
685         assert ( ! ep->open );
686         assert ( ep->max > 0 );
687
688         /* Free all I/O buffers */
689         list_for_each_entry_safe ( iobuf, tmp, &ep->recycled, list ) {
690                 list_del ( &iobuf->list );
691                 free_iob ( iobuf );
692         }
693 }
694
695 /******************************************************************************
696  *
697  * Control endpoint
698  *
699  ******************************************************************************
700  */
701
702 /** USB control transfer pseudo-header */
703 struct usb_control_pseudo_header {
704         /** Completion status */
705         int rc;
706 };
707
708 /**
709  * Complete USB control transfer
710  *
711  * @v ep                USB endpoint
712  * @v iobuf             I/O buffer
713  * @v rc                Completion status code
714  */
715 static void usb_control_complete ( struct usb_endpoint *ep,
716                                    struct io_buffer *iobuf, int rc ) {
717         struct usb_device *usb = ep->usb;
718         struct usb_control_pseudo_header *pshdr;
719
720         /* Record completion status in buffer */
721         pshdr = iob_push ( iobuf, sizeof ( *pshdr ) );
722         pshdr->rc = rc;
723
724         /* Add to list of completed I/O buffers */
725         list_add_tail ( &iobuf->list, &usb->complete );
726 }
727
728 /** USB control endpoint driver operations */
729 static struct usb_endpoint_driver_operations usb_control_operations = {
730         .complete = usb_control_complete,
731 };
732
733 /**
734  * Issue USB control transaction
735  *
736  * @v usb               USB device
737  * @v request           Request
738  * @v value             Value parameter
739  * @v index             Index parameter
740  * @v data              Data buffer (if any)
741  * @v len               Length of data
742  * @ret rc              Return status code
743  */
744 int usb_control ( struct usb_device *usb, unsigned int request,
745                   unsigned int value, unsigned int index, void *data,
746                   size_t len ) {
747         struct usb_bus *bus = usb->port->hub->bus;
748         struct usb_endpoint *ep = &usb->control;
749         struct io_buffer *iobuf;
750         struct io_buffer *cmplt;
751         union {
752                 struct usb_setup_packet setup;
753                 struct usb_control_pseudo_header pshdr;
754         } *headroom;
755         struct usb_control_pseudo_header *pshdr;
756         unsigned int i;
757         int rc;
758
759         /* Allocate I/O buffer */
760         iobuf = alloc_iob ( sizeof ( *headroom ) + len );
761         if ( ! iobuf ) {
762                 rc = -ENOMEM;
763                 goto err_alloc;
764         }
765         iob_reserve ( iobuf, sizeof ( *headroom ) );
766         iob_put ( iobuf, len );
767         if ( request & USB_DIR_IN ) {
768                 memset ( data, 0, len );
769         } else {
770                 memcpy ( iobuf->data, data, len );
771         }
772
773         /* Enqueue message */
774         if ( ( rc = usb_message ( ep, request, value, index, iobuf ) ) != 0 )
775                 goto err_message;
776
777         /* Wait for completion */
778         for ( i = 0 ; i < USB_CONTROL_MAX_WAIT_MS ; i++ ) {
779
780                 /* Poll bus */
781                 usb_poll ( bus );
782
783                 /* Check for completion */
784                 while ( ( cmplt = list_first_entry ( &usb->complete,
785                                                      struct io_buffer,
786                                                      list ) ) ) {
787
788                         /* Remove from completion list */
789                         list_del ( &cmplt->list );
790
791                         /* Extract and strip completion status */
792                         pshdr = cmplt->data;
793                         iob_pull ( cmplt, sizeof ( *pshdr ) );
794                         rc = pshdr->rc;
795
796                         /* Discard stale completions */
797                         if ( cmplt != iobuf ) {
798                                 DBGC ( usb, "USB %s stale control completion: "
799                                        "%s\n", usb->name, strerror ( rc ) );
800                                 DBGC_HDA ( usb, 0, cmplt->data,
801                                            iob_len ( cmplt ) );
802                                 free_iob ( cmplt );
803                                 continue;
804                         }
805
806                         /* Fail immediately if completion was in error */
807                         if ( rc != 0 ) {
808                                 DBGC ( usb, "USB %s control %04x:%04x:%04x "
809                                        "failed: %s\n", usb->name, request,
810                                        value, index, strerror ( rc ) );
811                                 free_iob ( cmplt );
812                                 return rc;
813                         }
814
815                         /* Copy completion to data buffer, if applicable */
816                         assert ( iob_len ( cmplt ) <= len );
817                         if ( request & USB_DIR_IN )
818                                 memcpy ( data, cmplt->data, iob_len ( cmplt ) );
819                         free_iob ( cmplt );
820                         return 0;
821                 }
822
823                 /* Delay */
824                 mdelay ( 1 );
825         }
826
827         DBGC ( usb, "USB %s timed out waiting for control %04x:%04x:%04x\n",
828                usb->name, request, value, index );
829         return -ETIMEDOUT;
830
831  err_message:
832         free_iob ( iobuf );
833  err_alloc:
834         return rc;
835 }
836
837 /**
838  * Get USB string descriptor
839  *
840  * @v usb               USB device
841  * @v index             String index
842  * @v language          Language ID
843  * @v buf               Data buffer
844  * @v len               Length of buffer
845  * @ret len             String length (excluding NUL), or negative error
846  */
847 int usb_get_string_descriptor ( struct usb_device *usb, unsigned int index,
848                                 unsigned int language, char *buf, size_t len ) {
849         size_t max = ( len ? ( len - 1 /* NUL */ ) : 0 );
850         struct {
851                 struct usb_descriptor_header header;
852                 uint16_t character[max];
853         } __attribute__ (( packed )) *desc;
854         unsigned int actual;
855         unsigned int i;
856         int rc;
857
858         /* Allocate buffer for string */
859         desc = malloc ( sizeof ( *desc ) );
860         if ( ! desc ) {
861                 rc = -ENOMEM;
862                 goto err_alloc;
863         }
864
865         /* Get descriptor */
866         if ( ( rc = usb_get_descriptor ( usb, 0, USB_STRING_DESCRIPTOR, index,
867                                          language, &desc->header,
868                                          sizeof ( *desc ) ) ) != 0 )
869                 goto err_get_descriptor;
870
871         /* Copy to buffer */
872         actual = ( ( desc->header.len - sizeof ( desc->header ) ) /
873                    sizeof ( desc->character[0] ) );
874         for ( i = 0 ; ( ( i < actual ) && ( i < max ) ) ; i++ )
875                 buf[i] = le16_to_cpu ( desc->character[i] );
876         if ( len )
877                 buf[i] = '\0';
878
879         /* Free buffer */
880         free ( desc );
881
882         return actual;
883
884  err_get_descriptor:
885         free ( desc );
886  err_alloc:
887         return rc;
888 }
889
890 /******************************************************************************
891  *
892  * USB device driver
893  *
894  ******************************************************************************
895  */
896
897 /**
898  * Describe USB function
899  *
900  * @v func              USB function
901  * @v config            Configuration descriptor
902  * @v first             First interface number
903  * @ret rc              Return status code
904  */
905 static int usb_function ( struct usb_function *func,
906                           struct usb_configuration_descriptor *config,
907                           unsigned int first ) {
908         struct usb_device *usb = func->usb;
909         struct usb_interface_association_descriptor *association;
910         struct usb_interface_descriptor *interface;
911         struct cdc_union_descriptor *cdc_union;
912         unsigned int i;
913
914         /* First, look for an interface association descriptor */
915         association = usb_interface_association_descriptor ( config, first );
916         if ( association ) {
917
918                 /* Sanity check */
919                 if ( association->count > config->interfaces ) {
920                         DBGC ( usb, "USB %s has invalid association [%d-%d)\n",
921                                func->name, association->first,
922                                ( association->first + association->count ) );
923                         return -ERANGE;
924                 }
925
926                 /* Describe function */
927                 memcpy ( &func->class, &association->class,
928                          sizeof ( func->class ) );
929                 func->count = association->count;
930                 for ( i = 0 ; i < association->count ; i++ )
931                         func->interface[i] = ( association->first + i );
932                 return 0;
933         }
934
935         /* Next, look for an interface descriptor */
936         interface = usb_interface_descriptor ( config, first, 0 );
937         if ( ! interface ) {
938                 DBGC ( usb, "USB %s has no interface descriptor\n",
939                        func->name );
940                 return -ENOENT;
941         }
942
943         /* Describe function */
944         memcpy ( &func->class, &interface->class, sizeof ( func->class ) );
945         func->count = 1;
946         func->interface[0] = first;
947
948         /* Look for a CDC union descriptor, if applicable */
949         if ( ( func->class.class == USB_CLASS_CDC ) &&
950              ( cdc_union = cdc_union_descriptor ( config, interface ) ) ) {
951
952                 /* Determine interface count */
953                 func->count = ( ( cdc_union->header.len -
954                                   offsetof ( typeof ( *cdc_union ),
955                                              interface[0] ) ) /
956                                 sizeof ( cdc_union->interface[0] ) );
957                 if ( func->count > config->interfaces ) {
958                         DBGC ( usb, "USB %s has invalid union functional "
959                                "descriptor with %d interfaces\n",
960                                func->name, func->count );
961                         return -ERANGE;
962                 }
963
964                 /* Describe function */
965                 for ( i = 0 ; i < func->count ; i++ )
966                         func->interface[i] = cdc_union->interface[i];
967
968                 return 0;
969         }
970
971         return 0;
972 }
973
974 /**
975  * Check for a USB device ID match
976  *
977  * @v func              USB function
978  * @v id                Device ID
979  * @ret matches         Device ID matches
980  */
981 static int
982 usb_device_id_matches ( struct usb_function *func, struct usb_device_id *id ) {
983
984         return ( ( ( id->vendor == func->dev.desc.vendor ) ||
985                    ( id->vendor == USB_ANY_ID ) ) &&
986                  ( ( id->product == func->dev.desc.device ) ||
987                    ( id->product == USB_ANY_ID ) ) &&
988                  ( id->class.class == func->class.class ) &&
989                  ( id->class.subclass == func->class.subclass ) &&
990                  ( id->class.protocol == func->class.protocol ) );
991 }
992
993 /**
994  * Probe USB device driver
995  *
996  * @v func              USB function
997  * @v config            Configuration descriptor
998  * @ret rc              Return status code
999  */
1000 static int usb_probe ( struct usb_function *func,
1001                        struct usb_configuration_descriptor *config ) {
1002         struct usb_device *usb = func->usb;
1003         struct usb_driver *driver;
1004         struct usb_device_id *id;
1005         unsigned int i;
1006         int rc;
1007
1008         /* Look for a matching driver */
1009         for_each_table_entry ( driver, USB_DRIVERS ) {
1010                 for ( i = 0 ; i < driver->id_count ; i++ ) {
1011
1012                         /* Check for a matching ID */
1013                         id = &driver->ids[i];
1014                         if ( ! usb_device_id_matches ( func, id ) )
1015                                 continue;
1016
1017                         /* Probe driver */
1018                         if ( ( rc = driver->probe ( func, config ) ) != 0 ) {
1019                                 DBGC ( usb, "USB %s failed to probe driver %s: "
1020                                        "%s\n", func->name, id->name,
1021                                        strerror ( rc ) );
1022                                 /* Continue trying other drivers */
1023                                 continue;
1024                         }
1025
1026                         /* Record driver */
1027                         func->driver = driver;
1028                         func->dev.driver_name = id->name;
1029                         return 0;
1030                 }
1031         }
1032
1033         /* No driver found */
1034         DBGC ( usb, "USB %s %04x:%04x class %d:%d:%d has no driver\n",
1035                func->name, func->dev.desc.vendor, func->dev.desc.device,
1036                func->class.class, func->class.subclass, func->class.protocol );
1037         return -ENOENT;
1038 }
1039
1040 /**
1041  * Remove USB device driver
1042  *
1043  * @v func              USB function
1044  */
1045 static void usb_remove ( struct usb_function *func ) {
1046
1047         /* Remove driver */
1048         func->driver->remove ( func );
1049 }
1050
1051 /**
1052  * Probe all USB device drivers
1053  *
1054  * @v usb               USB device
1055  * @v config            Configuration descriptor
1056  */
1057 static void
1058 usb_probe_all ( struct usb_device *usb,
1059                 struct usb_configuration_descriptor *config ) {
1060         struct usb_bus *bus = usb->port->hub->bus;
1061         struct usb_function *func;
1062         uint8_t used[config->interfaces];
1063         unsigned int first;
1064         unsigned int i;
1065         int rc;
1066
1067         /* Identify each function in turn */
1068         memset ( used, 0, sizeof ( used ) );
1069         for ( first = 0 ; first < config->interfaces ; first++ ) {
1070
1071                 /* Skip interfaces already used */
1072                 if ( used[first] )
1073                         continue;
1074
1075                 /* Allocate and initialise structure */
1076                 func = zalloc ( sizeof ( *func ) +
1077                                 ( config->interfaces *
1078                                   sizeof ( func->interface[0] ) ) );
1079                 if ( ! func )
1080                         goto err_alloc;
1081                 func->name = func->dev.name;
1082                 func->usb = usb;
1083                 func->dev.desc.bus_type = BUS_TYPE_USB;
1084                 func->dev.desc.location = usb->address;
1085                 func->dev.desc.vendor = le16_to_cpu ( usb->device.vendor );
1086                 func->dev.desc.device = le16_to_cpu ( usb->device.product );
1087                 snprintf ( func->dev.name, sizeof ( func->dev.name ),
1088                            "%s-%d.%d", usb->name, config->config, first );
1089                 INIT_LIST_HEAD ( &func->dev.children );
1090                 func->dev.parent = bus->dev;
1091
1092                 /* Identify function */
1093                 if ( ( rc = usb_function ( func, config, first ) ) != 0 )
1094                         goto err_function;
1095                 assert ( func->count <= config->interfaces );
1096
1097                 /* Mark interfaces as used */
1098                 for ( i = 0 ; i < func->count ; i++ ) {
1099                         if ( func->interface[i] >= config->interfaces ) {
1100                                 DBGC ( usb, "USB %s has invalid interface %d\n",
1101                                        func->name, func->interface[i] );
1102                                 goto err_interface;
1103                         }
1104                         used[ func->interface[i] ] = 1;
1105                 }
1106
1107                 /* Probe device driver */
1108                 if ( ( rc = usb_probe ( func, config ) ) != 0 )
1109                         goto err_probe;
1110                 DBGC ( usb, "USB %s %04x:%04x class %d:%d:%d interfaces ",
1111                        func->name, func->dev.desc.vendor, func->dev.desc.device,
1112                        func->class.class, func->class.subclass,
1113                        func->class.protocol );
1114                 for ( i = 0 ; i < func->count ; i++ )
1115                         DBGC ( usb, "%s%d", ( i ? "," : "" ),
1116                                func->interface[i] );
1117                 DBGC ( usb, " using driver %s\n", func->dev.driver_name );
1118
1119                 /* Add to list of functions */
1120                 list_add ( &func->list, &usb->functions );
1121
1122                 /* Add to device hierarchy */
1123                 list_add_tail ( &func->dev.siblings, &bus->dev->children );
1124
1125                 continue;
1126
1127                 list_del ( &func->dev.siblings );
1128                 list_del ( &func->list );
1129                 usb_remove ( func );
1130         err_probe:
1131                 free ( func );
1132         err_alloc:
1133         err_interface:
1134         err_function:
1135                 /* Continue registering other functions */
1136                 continue;
1137         }
1138 }
1139
1140 /**
1141  * Remove all device drivers
1142  *
1143  * @v usb               USB device
1144  */
1145 static void usb_remove_all ( struct usb_device *usb ) {
1146         struct usb_function *func;
1147         struct usb_function *tmp;
1148
1149         /* Remove all functions */
1150         list_for_each_entry_safe ( func, tmp, &usb->functions, list ) {
1151
1152                 /* Remove device driver */
1153                 usb_remove ( func );
1154
1155                 /* Remove from device hierarchy */
1156                 assert ( list_empty ( &func->dev.children ) );
1157                 list_del ( &func->dev.siblings );
1158
1159                 /* Remove from list of functions */
1160                 list_del ( &func->list );
1161
1162                 /* Free function */
1163                 free ( func );
1164         }
1165 }
1166
1167 /**
1168  * Select USB device configuration
1169  *
1170  * @v usb               USB device
1171  * @v index             Configuration index
1172  * @ret rc              Return status code
1173  */
1174 static int usb_configure ( struct usb_device *usb, unsigned int index ) {
1175         struct usb_configuration_descriptor partial;
1176         struct usb_configuration_descriptor *config;
1177         size_t len;
1178         int rc;
1179
1180         /* Read first part of configuration descriptor to get size */
1181         if ( ( rc = usb_get_config_descriptor ( usb, index, &partial,
1182                                                 sizeof ( partial ) ) ) != 0 ) {
1183                 DBGC ( usb, "USB %s could not get configuration descriptor %d: "
1184                        "%s\n", usb->name, index, strerror ( rc ) );
1185                 goto err_get_partial;
1186         }
1187         len = le16_to_cpu ( partial.len );
1188         if ( len < sizeof ( partial ) ) {
1189                 DBGC ( usb, "USB %s underlength configuraton descriptor %d\n",
1190                        usb->name, index );
1191                 rc = -EINVAL;
1192                 goto err_partial_len;
1193         }
1194
1195         /* Allocate buffer for whole configuration descriptor */
1196         config = malloc ( len );
1197         if ( ! config ) {
1198                 rc = -ENOMEM;
1199                 goto err_alloc_config;
1200         }
1201
1202         /* Read whole configuration descriptor */
1203         if ( ( rc = usb_get_config_descriptor ( usb, index, config,
1204                                                 len ) ) != 0 ) {
1205                 DBGC ( usb, "USB %s could not get configuration descriptor %d: "
1206                        "%s\n", usb->name, index, strerror ( rc ) );
1207                 goto err_get_config_descriptor;
1208         }
1209         if ( config->len != partial.len ) {
1210                 DBGC ( usb, "USB %s bad configuration descriptor %d length\n",
1211                        usb->name, index );
1212                 rc = -EINVAL;
1213                 goto err_config_len;
1214         }
1215
1216         /* Set configuration */
1217         if ( ( rc = usb_set_configuration ( usb, config->config ) ) != 0){
1218                 DBGC ( usb, "USB %s could not set configuration %d: %s\n",
1219                        usb->name, config->config, strerror ( rc ) );
1220                 goto err_set_configuration;
1221         }
1222
1223         /* Probe USB device drivers */
1224         usb_probe_all ( usb, config );
1225
1226         /* Free configuration descriptor */
1227         free ( config );
1228
1229         return 0;
1230
1231         usb_remove_all ( usb );
1232         usb_set_configuration ( usb, 0 );
1233  err_set_configuration:
1234  err_config_len:
1235  err_get_config_descriptor:
1236         free ( config );
1237  err_alloc_config:
1238  err_partial_len:
1239  err_get_partial:
1240         return rc;
1241 }
1242
1243 /**
1244  * Clear USB device configuration
1245  *
1246  * @v usb               USB device
1247  */
1248 static void usb_deconfigure ( struct usb_device *usb ) {
1249         unsigned int i;
1250
1251         /* Remove device drivers */
1252         usb_remove_all ( usb );
1253
1254         /* Sanity checks */
1255         for ( i = 0 ; i < ( sizeof ( usb->ep ) / sizeof ( usb->ep[0] ) ) ; i++){
1256                 if ( i != USB_ENDPOINT_IDX ( USB_EP0_ADDRESS ) )
1257                         assert ( usb->ep[i] == NULL );
1258         }
1259
1260         /* Clear device configuration */
1261         usb_set_configuration ( usb, 0 );
1262 }
1263
1264 /**
1265  * Find and select a supported USB device configuration
1266  *
1267  * @v usb               USB device
1268  * @ret rc              Return status code
1269  */
1270 static int usb_configure_any ( struct usb_device *usb ) {
1271         unsigned int index;
1272         int rc = -ENOENT;
1273
1274         /* Attempt all configuration indexes */
1275         for ( index = 0 ; index < usb->device.configurations ; index++ ) {
1276
1277                 /* Attempt this configuration index */
1278                 if ( ( rc = usb_configure ( usb, index ) ) != 0 )
1279                         continue;
1280
1281                 /* If we have no drivers, then try the next configuration */
1282                 if ( list_empty ( &usb->functions ) ) {
1283                         rc = -ENOTSUP;
1284                         usb_deconfigure ( usb );
1285                         continue;
1286                 }
1287
1288                 return 0;
1289         }
1290
1291         return rc;
1292 }
1293
1294 /******************************************************************************
1295  *
1296  * USB device
1297  *
1298  ******************************************************************************
1299  */
1300
1301 /**
1302  * Allocate USB device
1303  *
1304  * @v port              USB port
1305  * @ret usb             USB device, or NULL on allocation failure
1306  */
1307 static struct usb_device * alloc_usb ( struct usb_port *port ) {
1308         struct usb_hub *hub = port->hub;
1309         struct usb_bus *bus = hub->bus;
1310         struct usb_device *usb;
1311
1312         /* Allocate and initialise structure */
1313         usb = zalloc ( sizeof ( *usb ) );
1314         if ( ! usb )
1315                 return NULL;
1316         snprintf ( usb->name, sizeof ( usb->name ), "%s%c%d", hub->name,
1317                    ( hub->usb ? '.' : '-' ), port->address );
1318         usb->port = port;
1319         INIT_LIST_HEAD ( &usb->functions );
1320         usb->host = &bus->op->device;
1321         usb_endpoint_init ( &usb->control, usb, &usb_control_operations );
1322         INIT_LIST_HEAD ( &usb->complete );
1323
1324         return usb;
1325 }
1326
1327 /**
1328  * Register USB device
1329  *
1330  * @v usb               USB device
1331  * @ret rc              Return status code
1332  */
1333 static int register_usb ( struct usb_device *usb ) {
1334         struct usb_port *port = usb->port;
1335         struct usb_hub *hub = port->hub;
1336         struct usb_bus *bus = hub->bus;
1337         unsigned int protocol;
1338         size_t mtu;
1339         int rc;
1340
1341         /* Add to port */
1342         if ( port->usb != NULL ) {
1343                 DBGC ( hub, "USB hub %s port %d is already registered to %s\n",
1344                        hub->name, port->address, port->usb->name );
1345                 rc = -EALREADY;
1346                 goto err_already;
1347         }
1348         port->usb = usb;
1349
1350         /* Add to bus device list */
1351         list_add_tail ( &usb->list, &bus->devices );
1352
1353         /* Enable device */
1354         if ( ( rc = hub->driver->enable ( hub, port ) ) != 0 ) {
1355                 DBGC ( hub, "USB hub %s port %d could not enable: %s\n",
1356                        hub->name, port->address, strerror ( rc ) );
1357                 goto err_enable;
1358         }
1359
1360         /* Allow recovery interval since port may have been reset */
1361         mdelay ( USB_RESET_RECOVER_DELAY_MS );
1362
1363         /* Get device speed */
1364         if ( ( rc = hub->driver->speed ( hub, port ) ) != 0 ) {
1365                 DBGC ( hub, "USB hub %s port %d could not get speed: %s\n",
1366                        hub->name, port->address, strerror ( rc ) );
1367                 goto err_speed;
1368         }
1369         DBGC2 ( usb, "USB %s attached as %s-speed device\n",
1370                 usb->name, usb_speed_name ( port->speed ) );
1371
1372         /* Open device */
1373         if ( ( rc = usb->host->open ( usb ) ) != 0 ) {
1374                 DBGC ( usb, "USB %s could not open: %s\n",
1375                        usb->name, strerror ( rc ) );
1376                 goto err_open;
1377         }
1378
1379         /* Describe control endpoint */
1380         mtu = USB_EP0_DEFAULT_MTU ( port->speed );
1381         usb_endpoint_describe ( &usb->control, USB_EP0_ADDRESS,
1382                                 USB_EP0_ATTRIBUTES, mtu, USB_EP0_BURST,
1383                                 USB_EP0_INTERVAL );
1384
1385         /* Open control endpoint */
1386         if ( ( rc = usb_endpoint_open ( &usb->control ) ) != 0 )
1387                 goto err_open_control;
1388         assert ( usb_endpoint ( usb, USB_EP0_ADDRESS ) == &usb->control );
1389
1390         /* Assign device address */
1391         if ( ( rc = usb->host->address ( usb ) ) != 0 ) {
1392                 DBGC ( usb, "USB %s could not set address: %s\n",
1393                        usb->name, strerror ( rc ) );
1394                 goto err_address;
1395         }
1396         DBGC2 ( usb, "USB %s assigned address %d\n", usb->name, usb->address );
1397
1398         /* Allow recovery interval after Set Address command */
1399         mdelay ( USB_SET_ADDRESS_RECOVER_DELAY_MS );
1400
1401         /* Read first part of device descriptor to get EP0 MTU */
1402         if ( ( rc = usb_get_mtu ( usb, &usb->device ) ) != 0 ) {
1403                 DBGC ( usb, "USB %s could not get MTU: %s\n",
1404                        usb->name, strerror ( rc ) );
1405                 goto err_get_mtu;
1406         }
1407
1408         /* Calculate EP0 MTU */
1409         protocol = le16_to_cpu ( usb->device.protocol );
1410         mtu = ( ( protocol < USB_PROTO_3_0 ) ?
1411                 usb->device.mtu : ( 1 << usb->device.mtu ) );
1412         DBGC2 ( usb, "USB %s has control MTU %zd (guessed %zd)\n",
1413                 usb->name, mtu, usb->control.mtu );
1414
1415         /* Update MTU */
1416         if ( ( rc = usb_endpoint_mtu ( &usb->control, mtu ) ) != 0 )
1417                 goto err_mtu;
1418
1419         /* Read whole device descriptor */
1420         if ( ( rc = usb_get_device_descriptor ( usb, &usb->device ) ) != 0 ) {
1421                 DBGC ( usb, "USB %s could not get device descriptor: %s\n",
1422                        usb->name, strerror ( rc ) );
1423                 goto err_get_device_descriptor;
1424         }
1425         DBGC ( usb, "USB %s addr %d %04x:%04x class %d:%d:%d (v%s, %s-speed, "
1426                "MTU %zd)\n", usb->name, usb->address,
1427                le16_to_cpu ( usb->device.vendor ),
1428                le16_to_cpu ( usb->device.product ), usb->device.class.class,
1429                usb->device.class.subclass, usb->device.class.protocol,
1430                usb_bcd ( le16_to_cpu ( usb->device.protocol ) ),
1431                usb_speed_name ( port->speed ), usb->control.mtu );
1432
1433         /* Configure device */
1434         if ( ( rc = usb_configure_any ( usb ) ) != 0 )
1435                 goto err_configure_any;
1436
1437         return 0;
1438
1439         usb_deconfigure ( usb );
1440  err_configure_any:
1441  err_get_device_descriptor:
1442  err_mtu:
1443  err_get_mtu:
1444  err_address:
1445         usb_endpoint_close ( &usb->control );
1446  err_open_control:
1447         usb->host->close ( usb );
1448  err_open:
1449  err_speed:
1450         hub->driver->disable ( hub, port );
1451  err_enable:
1452         list_del ( &usb->list );
1453         port->usb = NULL;
1454  err_already:
1455         return rc;
1456 }
1457
1458 /**
1459  * Unregister USB device
1460  *
1461  * @v usb               USB device
1462  */
1463 static void unregister_usb ( struct usb_device *usb ) {
1464         struct usb_port *port = usb->port;
1465         struct usb_hub *hub = port->hub;
1466         struct io_buffer *iobuf;
1467         struct io_buffer *tmp;
1468
1469         /* Sanity checks */
1470         assert ( port->usb == usb );
1471
1472         /* Clear device configuration */
1473         usb_deconfigure ( usb );
1474
1475         /* Close control endpoint */
1476         usb_endpoint_close ( &usb->control );
1477
1478         /* Discard any stale control completions */
1479         list_for_each_entry_safe ( iobuf, tmp, &usb->complete, list ) {
1480                 list_del ( &iobuf->list );
1481                 free_iob ( iobuf );
1482         }
1483
1484         /* Close device */
1485         usb->host->close ( usb );
1486
1487         /* Disable port */
1488         hub->driver->disable ( hub, port );
1489
1490         /* Remove from bus device list */
1491         list_del ( &usb->list );
1492
1493         /* Remove from port */
1494         port->usb = NULL;
1495 }
1496
1497 /**
1498  * Free USB device
1499  *
1500  * @v usb               USB device
1501  */
1502 static void free_usb ( struct usb_device *usb ) {
1503         unsigned int i;
1504
1505         /* Sanity checks */
1506         for ( i = 0 ; i < ( sizeof ( usb->ep ) / sizeof ( usb->ep[0] ) ) ; i++ )
1507                 assert ( usb->ep[i] == NULL );
1508         assert ( list_empty ( &usb->functions ) );
1509         assert ( list_empty ( &usb->complete ) );
1510
1511         /* Free device */
1512         free ( usb );
1513 }
1514
1515 /******************************************************************************
1516  *
1517  * USB device hotplug event handling
1518  *
1519  ******************************************************************************
1520  */
1521
1522 /**
1523  * Handle newly attached USB device
1524  *
1525  * @v port              USB port
1526  * @ret rc              Return status code
1527  */
1528 static int usb_attached ( struct usb_port *port ) {
1529         struct usb_device *usb;
1530         int rc;
1531
1532         /* Mark port as attached */
1533         port->attached = 1;
1534
1535         /* Sanity checks */
1536         assert ( port->usb == NULL );
1537
1538         /* Allocate USB device */
1539         usb = alloc_usb ( port );
1540         if ( ! usb ) {
1541                 rc = -ENOMEM;
1542                 goto err_alloc;
1543         }
1544
1545         /* Register USB device */
1546         if ( ( rc = register_usb ( usb ) ) != 0 )
1547                 goto err_register;
1548
1549         return 0;
1550
1551         unregister_usb ( usb );
1552  err_register:
1553         free_usb ( usb );
1554  err_alloc:
1555         return rc;
1556 }
1557
1558 /**
1559  * Handle newly detached USB device
1560  *
1561  * @v port              USB port
1562  */
1563 static void usb_detached ( struct usb_port *port ) {
1564         struct usb_device *usb = port->usb;
1565
1566         /* Mark port as detached */
1567         port->attached = 0;
1568
1569         /* Do nothing if we have no USB device */
1570         if ( ! usb )
1571                 return;
1572
1573         /* Unregister USB device */
1574         unregister_usb ( usb );
1575
1576         /* Free USB device */
1577         free_usb ( usb );
1578 }
1579
1580 /**
1581  * Handle newly attached or detached USB device
1582  *
1583  * @v port              USB port
1584  * @ret rc              Return status code
1585  */
1586 static int usb_hotplugged ( struct usb_port *port ) {
1587         struct usb_hub *hub = port->hub;
1588         int rc;
1589
1590         /* Get current port speed */
1591         if ( ( rc = hub->driver->speed ( hub, port ) ) != 0 ) {
1592                 DBGC ( hub, "USB hub %s port %d could not get speed: %s\n",
1593                        hub->name, port->address, strerror ( rc ) );
1594                 goto err_speed;
1595         }
1596
1597         /* Detach device, if applicable */
1598         if ( port->attached && ( port->disconnected || ! port->speed ) )
1599                 usb_detached ( port );
1600
1601         /* Attach device, if applicable */
1602         if ( port->speed && ( ! port->attached ) &&
1603              ( ( rc = usb_attached ( port ) ) != 0 ) )
1604                 goto err_attached;
1605
1606  err_attached:
1607  err_speed:
1608         /* Clear any recorded disconnections */
1609         port->disconnected = 0;
1610         return rc;
1611 }
1612
1613 /******************************************************************************
1614  *
1615  * USB process
1616  *
1617  ******************************************************************************
1618  */
1619
1620 /**
1621  * Report port status change
1622  *
1623  * @v port              USB port
1624  */
1625 void usb_port_changed ( struct usb_port *port ) {
1626
1627         /* Record hub port status change */
1628         list_del ( &port->changed );
1629         list_add_tail ( &port->changed, &usb_changed );
1630 }
1631
1632 /**
1633  * Handle newly attached or detached USB device
1634  *
1635  */
1636 static void usb_hotplug ( void ) {
1637         struct usb_port *port;
1638
1639         /* Handle any changed ports, allowing for the fact that the
1640          * port list may change as we perform hotplug actions.
1641          */
1642         while ( ! list_empty ( &usb_changed ) ) {
1643
1644                 /* Get first changed port */
1645                 port = list_first_entry ( &usb_changed, struct usb_port,
1646                                           changed );
1647                 assert ( port != NULL );
1648
1649                 /* Remove from list of changed ports */
1650                 list_del ( &port->changed );
1651                 INIT_LIST_HEAD ( &port->changed );
1652
1653                 /* Perform appropriate hotplug action */
1654                 usb_hotplugged ( port );
1655         }
1656 }
1657
1658 /**
1659  * USB process
1660  *
1661  * @v process           USB process
1662  */
1663 static void usb_step ( struct process *process __unused ) {
1664         struct usb_bus *bus;
1665         struct usb_endpoint *ep;
1666
1667         /* Poll all buses */
1668         for_each_usb_bus ( bus )
1669                 usb_poll ( bus );
1670
1671         /* Attempt to reset first halted endpoint in list, if any.  We
1672          * do not attempt to process the complete list, since this
1673          * would require extra code to allow for the facts that the
1674          * halted endpoint list may change as we do so, and that
1675          * resetting an endpoint may fail.
1676          */
1677         if ( ( ep = list_first_entry ( &usb_halted, struct usb_endpoint,
1678                                        halted ) ) != NULL )
1679                 usb_endpoint_reset ( ep );
1680
1681         /* Handle any changed ports */
1682         usb_hotplug();
1683 }
1684
1685 /** USB process */
1686 PERMANENT_PROCESS ( usb_process, usb_step );
1687
1688 /******************************************************************************
1689  *
1690  * USB hub
1691  *
1692  ******************************************************************************
1693  */
1694
1695 /**
1696  * Allocate USB hub
1697  *
1698  * @v bus               USB bus
1699  * @v usb               Underlying USB device, if any
1700  * @v ports             Number of ports
1701  * @v driver            Hub driver operations
1702  * @ret hub             USB hub, or NULL on allocation failure
1703  */
1704 struct usb_hub * alloc_usb_hub ( struct usb_bus *bus, struct usb_device *usb,
1705                                  unsigned int ports,
1706                                  struct usb_hub_driver_operations *driver ) {
1707         struct usb_hub *hub;
1708         struct usb_port *port;
1709         unsigned int i;
1710
1711         /* Allocate and initialise structure */
1712         hub = zalloc ( sizeof ( *hub ) + ( ports * sizeof ( hub->port[0] ) ) );
1713         if ( ! hub )
1714                 return NULL;
1715         hub->name = ( usb ? usb->name : bus->name );
1716         hub->bus = bus;
1717         hub->usb = usb;
1718         if ( usb )
1719                 hub->protocol = usb->port->protocol;
1720         hub->ports = ports;
1721         hub->driver = driver;
1722         hub->host = &bus->op->hub;
1723
1724         /* Initialise port list */
1725         for ( i = 1 ; i <= hub->ports ; i++ ) {
1726                 port = usb_port ( hub, i );
1727                 port->hub = hub;
1728                 port->address = i;
1729                 if ( usb )
1730                         port->protocol = usb->port->protocol;
1731                 INIT_LIST_HEAD ( &port->changed );
1732         }
1733
1734         return hub;
1735 }
1736
1737 /**
1738  * Register USB hub
1739  *
1740  * @v hub               USB hub
1741  * @ret rc              Return status code
1742  */
1743 int register_usb_hub ( struct usb_hub *hub ) {
1744         struct usb_bus *bus = hub->bus;
1745         struct usb_port *port;
1746         unsigned int i;
1747         int rc;
1748
1749         /* Add to hub list */
1750         list_add_tail ( &hub->list, &bus->hubs );
1751
1752         /* Open hub (host controller) */
1753         if ( ( rc = hub->host->open ( hub ) ) != 0 ) {
1754                 DBGC ( hub, "USB hub %s could not open: %s\n",
1755                        hub->name, strerror ( rc ) );
1756                 goto err_host_open;
1757         }
1758
1759         /* Open hub (driver) */
1760         if ( ( rc = hub->driver->open ( hub ) ) != 0 ) {
1761                 DBGC ( hub, "USB hub %s could not open: %s\n",
1762                        hub->name, strerror ( rc ) );
1763                 goto err_driver_open;
1764         }
1765
1766         /* Delay to allow ports to stabilise */
1767         mdelay ( USB_PORT_DELAY_MS );
1768
1769         /* Mark all ports as changed */
1770         for ( i = 1 ; i <= hub->ports ; i++ ) {
1771                 port = usb_port ( hub, i );
1772                 usb_port_changed ( port );
1773         }
1774
1775         /* Some hubs seem to defer reporting device connections until
1776          * their interrupt endpoint is polled for the first time.
1777          * Poll the bus once now in order to pick up any such
1778          * connections.
1779          */
1780         usb_poll ( bus );
1781
1782         return 0;
1783
1784         hub->driver->close ( hub );
1785  err_driver_open:
1786         hub->host->close ( hub );
1787  err_host_open:
1788         list_del ( &hub->list );
1789         return rc;
1790 }
1791
1792 /**
1793  * Unregister USB hub
1794  *
1795  * @v hub               USB hub
1796  */
1797 void unregister_usb_hub ( struct usb_hub *hub ) {
1798         struct usb_port *port;
1799         unsigned int i;
1800
1801         /* Detach all devices */
1802         for ( i = 1 ; i <= hub->ports ; i++ ) {
1803                 port = usb_port ( hub, i );
1804                 if ( port->attached )
1805                         usb_detached ( port );
1806         }
1807
1808         /* Close hub (driver) */
1809         hub->driver->close ( hub );
1810
1811         /* Close hub (host controller) */
1812         hub->host->close ( hub );
1813
1814         /* Cancel any pending port status changes */
1815         for ( i = 1 ; i <= hub->ports ; i++ ) {
1816                 port = usb_port ( hub, i );
1817                 list_del ( &port->changed );
1818                 INIT_LIST_HEAD ( &port->changed );
1819         }
1820
1821         /* Remove from hub list */
1822         list_del ( &hub->list );
1823 }
1824
1825 /**
1826  * Free USB hub
1827  *
1828  * @v hub               USB hub
1829  */
1830 void free_usb_hub ( struct usb_hub *hub ) {
1831         struct usb_port *port;
1832         unsigned int i;
1833
1834         /* Sanity checks */
1835         for ( i = 1 ; i <= hub->ports ; i++ ) {
1836                 port = usb_port ( hub, i );
1837                 assert ( ! port->attached );
1838                 assert ( port->usb == NULL );
1839                 assert ( list_empty ( &port->changed ) );
1840         }
1841
1842         /* Free hub */
1843         free ( hub );
1844 }
1845
1846 /******************************************************************************
1847  *
1848  * USB bus
1849  *
1850  ******************************************************************************
1851  */
1852
1853 /**
1854  * Allocate USB bus
1855  *
1856  * @v dev               Underlying hardware device
1857  * @v ports             Number of root hub ports
1858  * @v mtu               Largest transfer allowed on the bus
1859  * @v op                Host controller operations
1860  * @ret bus             USB bus, or NULL on allocation failure
1861  */
1862 struct usb_bus * alloc_usb_bus ( struct device *dev, unsigned int ports,
1863                                  size_t mtu, struct usb_host_operations *op ) {
1864         struct usb_bus *bus;
1865
1866         /* Allocate and initialise structure */
1867         bus = zalloc ( sizeof ( *bus ) );
1868         if ( ! bus )
1869                 goto err_alloc_bus;
1870         bus->name = dev->name;
1871         bus->dev = dev;
1872         bus->mtu = mtu;
1873         bus->op = op;
1874         INIT_LIST_HEAD ( &bus->devices );
1875         INIT_LIST_HEAD ( &bus->hubs );
1876         bus->host = &bus->op->bus;
1877
1878         /* Allocate root hub */
1879         bus->hub = alloc_usb_hub ( bus, NULL, ports, &op->root );
1880         if ( ! bus->hub )
1881                 goto err_alloc_hub;
1882
1883         return bus;
1884
1885         free_usb_hub ( bus->hub );
1886  err_alloc_hub:
1887         free ( bus );
1888  err_alloc_bus:
1889         return NULL;
1890 }
1891
1892 /**
1893  * Register USB bus
1894  *
1895  * @v bus               USB bus
1896  * @ret rc              Return status code
1897  */
1898 int register_usb_bus ( struct usb_bus *bus ) {
1899         int rc;
1900
1901         /* Sanity checks */
1902         assert ( bus->hub != NULL );
1903
1904         /* Open bus */
1905         if ( ( rc = bus->host->open ( bus ) ) != 0 )
1906                 goto err_open;
1907
1908         /* Add to list of USB buses */
1909         list_add_tail ( &bus->list, &usb_buses );
1910
1911         /* Register root hub */
1912         if ( ( rc = register_usb_hub ( bus->hub ) ) != 0 )
1913                 goto err_register_hub;
1914
1915         /* Attach any devices already present */
1916         usb_hotplug();
1917
1918         return 0;
1919
1920         unregister_usb_hub ( bus->hub );
1921  err_register_hub:
1922         list_del ( &bus->list );
1923         bus->host->close ( bus );
1924  err_open:
1925         return rc;
1926 }
1927
1928 /**
1929  * Unregister USB bus
1930  *
1931  * @v bus               USB bus
1932  */
1933 void unregister_usb_bus ( struct usb_bus *bus ) {
1934
1935         /* Sanity checks */
1936         assert ( bus->hub != NULL );
1937
1938         /* Unregister root hub */
1939         unregister_usb_hub ( bus->hub );
1940
1941         /* Remove from list of USB buses */
1942         list_del ( &bus->list );
1943
1944         /* Close bus */
1945         bus->host->close ( bus );
1946
1947         /* Sanity checks */
1948         assert ( list_empty ( &bus->devices ) );
1949         assert ( list_empty ( &bus->hubs ) );
1950 }
1951
1952 /**
1953  * Free USB bus
1954  *
1955  * @v bus               USB bus
1956  */
1957 void free_usb_bus ( struct usb_bus *bus ) {
1958         struct usb_endpoint *ep;
1959         struct usb_port *port;
1960
1961         /* Sanity checks */
1962         assert ( list_empty ( &bus->devices ) );
1963         assert ( list_empty ( &bus->hubs ) );
1964         list_for_each_entry ( ep, &usb_halted, halted )
1965                 assert ( ep->usb->port->hub->bus != bus );
1966         list_for_each_entry ( port, &usb_changed, changed )
1967                 assert ( port->hub->bus != bus );
1968
1969         /* Free root hub */
1970         free_usb_hub ( bus->hub );
1971
1972         /* Free bus */
1973         free ( bus );
1974 }
1975
1976 /**
1977  * Find USB bus by device location
1978  *
1979  * @v bus_type          Bus type
1980  * @v location          Bus location
1981  * @ret bus             USB bus, or NULL
1982  */
1983 struct usb_bus * find_usb_bus_by_location ( unsigned int bus_type,
1984                                             unsigned int location ) {
1985         struct usb_bus *bus;
1986
1987         for_each_usb_bus ( bus ) {
1988                 if ( ( bus->dev->desc.bus_type == bus_type ) &&
1989                      ( bus->dev->desc.location == location ) )
1990                         return bus;
1991         }
1992
1993         return NULL;
1994 }
1995
1996 /******************************************************************************
1997  *
1998  * USB address assignment
1999  *
2000  ******************************************************************************
2001  */
2002
2003 /**
2004  * Allocate device address
2005  *
2006  * @v bus               USB bus
2007  * @ret address         Device address, or negative error
2008  */
2009 int usb_alloc_address ( struct usb_bus *bus ) {
2010         unsigned int address;
2011
2012         /* Find first free device address */
2013         address = ffsll ( ~bus->addresses );
2014         if ( ! address )
2015                 return -ENOENT;
2016
2017         /* Mark address as used */
2018         bus->addresses |= ( 1ULL << ( address - 1 ) );
2019
2020         return address;
2021 }
2022
2023 /**
2024  * Free device address
2025  *
2026  * @v bus               USB bus
2027  * @v address           Device address
2028  */
2029 void usb_free_address ( struct usb_bus *bus, unsigned int address ) {
2030
2031         /* Sanity check */
2032         assert ( address > 0 );
2033         assert ( bus->addresses & ( 1ULL << ( address - 1 ) ) );
2034
2035         /* Mark address as free */
2036         bus->addresses &= ~( 1ULL << ( address - 1 ) );
2037 }
2038
2039 /******************************************************************************
2040  *
2041  * USB bus topology
2042  *
2043  ******************************************************************************
2044  */
2045
2046 /**
2047  * Get USB route string
2048  *
2049  * @v usb               USB device
2050  * @ret route           USB route string
2051  */
2052 unsigned int usb_route_string ( struct usb_device *usb ) {
2053         struct usb_device *parent;
2054         unsigned int route;
2055
2056         /* Navigate up to root hub, constructing route string as we go */
2057         for ( route = 0 ; ( parent = usb->port->hub->usb ) ; usb = parent ) {
2058                 route <<= 4;
2059                 route |= ( ( usb->port->address > 0xf ) ?
2060                            0xf : usb->port->address );
2061         }
2062
2063         return route;
2064 }
2065
2066 /**
2067  * Get USB depth
2068  *
2069  * @v usb               USB device
2070  * @ret depth           Hub depth
2071  */
2072 unsigned int usb_depth ( struct usb_device *usb ) {
2073         struct usb_device *parent;
2074         unsigned int depth;
2075
2076         /* Navigate up to root hub, constructing depth as we go */
2077         for ( depth = 0 ; ( parent = usb->port->hub->usb ) ; usb = parent )
2078                 depth++;
2079
2080         return depth;
2081 }
2082
2083 /**
2084  * Get USB root hub port
2085  *
2086  * @v usb               USB device
2087  * @ret port            Root hub port
2088  */
2089 struct usb_port * usb_root_hub_port ( struct usb_device *usb ) {
2090         struct usb_device *parent;
2091
2092         /* Navigate up to root hub */
2093         while ( ( parent = usb->port->hub->usb ) )
2094                 usb = parent;
2095
2096         return usb->port;
2097 }
2098
2099 /**
2100  * Get USB transaction translator
2101  *
2102  * @v usb               USB device
2103  * @ret port            Transaction translator port, or NULL
2104  */
2105 struct usb_port * usb_transaction_translator ( struct usb_device *usb ) {
2106         struct usb_device *parent;
2107
2108         /* Navigate up to root hub.  If we find a low-speed or
2109          * full-speed port with a higher-speed parent device, then
2110          * that port is the transaction translator.
2111          */
2112         for ( ; ( parent = usb->port->hub->usb ) ; usb = parent ) {
2113                 if ( ( usb->port->speed <= USB_SPEED_FULL ) &&
2114                      ( parent->port->speed > USB_SPEED_FULL ) )
2115                         return usb->port;
2116         }
2117
2118         return NULL;
2119 }
2120
2121 /* Drag in objects via register_usb_bus() */
2122 REQUIRING_SYMBOL ( register_usb_bus );
2123
2124 /* Drag in USB configuration */
2125 REQUIRE_OBJECT ( config_usb );
2126
2127 /* Drag in hub driver */
2128 REQUIRE_OBJECT ( usbhub );