libpayload: usb: Retry get_descriptor() on failure
[coreboot.git] / payloads / libpayload / drivers / usb / usb.c
blobe87e397061e8c0b839dc3d90d6dd8d355f6991e9
1 /*
2 * This file is part of the libpayload project.
4 * Copyright (C) 2008-2010 coresystems GmbH
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
30 //#define USB_DEBUG
32 #include <libpayload-config.h>
33 #include <usb/usb.h>
35 #define DR_DESC gen_bmRequestType(device_to_host, standard_type, dev_recp)
37 hci_t *usb_hcs = 0;
39 hci_t *
40 new_controller (void)
42 hci_t *controller = xzalloc(sizeof (hci_t));
43 controller->next = usb_hcs;
44 usb_hcs = controller;
45 return controller;
48 void
49 detach_controller (hci_t *controller)
51 if (controller == NULL)
52 return;
54 usb_detach_device(controller, 0); /* tear down root hub tree */
56 if (usb_hcs == controller) {
57 usb_hcs = controller->next;
58 } else {
59 hci_t *it = usb_hcs;
60 while (it != NULL) {
61 if (it->next == controller) {
62 it->next = controller->next;
63 return;
65 it = it->next;
70 /**
71 * Shut down all controllers
73 int
74 usb_exit (void)
76 while (usb_hcs != NULL) {
77 usb_hcs->shutdown(usb_hcs);
79 return 0;
82 /**
83 * Polls all hubs on all USB controllers, to find out about device changes
85 void
86 usb_poll (void)
88 if (usb_hcs == 0)
89 return;
90 hci_t *controller = usb_hcs;
91 while (controller != NULL) {
92 int i;
93 for (i = 0; i < 128; i++) {
94 if (controller->devices[i] != 0) {
95 controller->devices[i]->poll (controller->devices[i]);
98 controller = controller->next;
102 usbdev_t *
103 init_device_entry (hci_t *controller, int i)
105 usbdev_t *dev = calloc(1, sizeof(usbdev_t));
106 if (!dev) {
107 usb_debug("no memory to allocate device structure\n");
108 return NULL;
110 if (controller->devices[i] != 0)
111 usb_debug("warning: device %d reassigned?\n", i);
112 controller->devices[i] = dev;
113 dev->controller = controller;
114 dev->address = -1;
115 dev->hub = -1;
116 dev->port = -1;
117 dev->init = usb_nop_init;
118 dev->init (controller->devices[i]);
119 return dev;
123 set_feature (usbdev_t *dev, int endp, int feature, int rtype)
125 dev_req_t dr;
127 dr.bmRequestType = rtype;
128 dr.data_dir = host_to_device;
129 dr.bRequest = SET_FEATURE;
130 dr.wValue = feature;
131 dr.wIndex = endp;
132 dr.wLength = 0;
134 return dev->controller->control (dev, OUT, sizeof (dr), &dr, 0, 0);
138 get_status (usbdev_t *dev, int intf, int rtype, int len, void *data)
140 dev_req_t dr;
142 dr.bmRequestType = rtype;
143 dr.data_dir = device_to_host;
144 dr.bRequest = GET_STATUS;
145 dr.wValue = 0;
146 dr.wIndex = intf;
147 dr.wLength = len;
149 return dev->controller->control (dev, IN, sizeof (dr), &dr, len, data);
153 * Certain Lexar / Micron USB 2.0 disks will fail the get_descriptor(DT_CFG)
154 * call due to timing issues. Work around this by making extra attempts on
155 * failure.
157 #define GET_DESCRIPTOR_TRIES 3
160 get_descriptor(usbdev_t *dev, int rtype, int desc_type, int desc_idx,
161 void *data, size_t len)
163 dev_req_t dr;
164 int fail_tries = 0;
165 int ret = 0;
167 while (fail_tries++ < GET_DESCRIPTOR_TRIES) {
168 dr.bmRequestType = rtype;
169 dr.bRequest = GET_DESCRIPTOR;
170 dr.wValue = desc_type << 8 | desc_idx;
171 dr.wIndex = 0;
172 dr.wLength = len;
174 ret = dev->controller->control(dev, IN,
175 sizeof(dr), &dr, len, data);
176 if (ret)
177 udelay(10);
178 else
179 return 0;
181 return ret;
185 set_configuration (usbdev_t *dev)
187 dev_req_t dr;
189 dr.bmRequestType = 0;
190 dr.bRequest = SET_CONFIGURATION;
191 dr.wValue = dev->configuration->bConfigurationValue;
192 dr.wIndex = 0;
193 dr.wLength = 0;
195 return dev->controller->control (dev, OUT, sizeof (dr), &dr, 0, 0);
199 clear_feature (usbdev_t *dev, int endp, int feature, int rtype)
201 dev_req_t dr;
203 dr.bmRequestType = rtype;
204 dr.data_dir = host_to_device;
205 dr.bRequest = CLEAR_FEATURE;
206 dr.wValue = feature;
207 dr.wIndex = endp;
208 dr.wLength = 0;
210 return dev->controller->control (dev, OUT, sizeof (dr), &dr, 0, 0) < 0;
214 clear_stall (endpoint_t *ep)
216 int ret = clear_feature (ep->dev, ep->endpoint, ENDPOINT_HALT,
217 gen_bmRequestType (host_to_device, standard_type, endp_recp));
218 ep->toggle = 0;
219 return ret;
222 /* returns free address or -1 */
223 static int
224 get_free_address (hci_t *controller)
226 int i = controller->latest_address + 1;
227 for (; i != controller->latest_address; i++) {
228 if (i >= ARRAY_SIZE(controller->devices) || i < 1) {
229 usb_debug("WARNING: Device addresses for controller %#x"
230 " wrapped around!\n", controller->reg_base);
231 i = 0;
232 continue;
234 if (controller->devices[i] == 0) {
235 controller->latest_address = i;
236 return i;
239 usb_debug ("no free address found\n");
240 return -1; // no free address
244 usb_decode_mps0(usb_speed speed, u8 bMaxPacketSize0)
246 switch (speed) {
247 case LOW_SPEED:
248 if (bMaxPacketSize0 != 8) {
249 usb_debug("Invalid MPS0: 0x%02x\n", bMaxPacketSize0);
250 bMaxPacketSize0 = 8;
252 return bMaxPacketSize0;
253 case FULL_SPEED:
254 switch (bMaxPacketSize0) {
255 case 8: case 16: case 32: case 64:
256 return bMaxPacketSize0;
257 default:
258 usb_debug("Invalid MPS0: 0x%02x\n", bMaxPacketSize0);
259 return 8;
261 case HIGH_SPEED:
262 if (bMaxPacketSize0 != 64) {
263 usb_debug("Invalid MPS0: 0x%02x\n", bMaxPacketSize0);
264 bMaxPacketSize0 = 64;
266 return bMaxPacketSize0;
267 case SUPER_SPEED:
268 if (bMaxPacketSize0 != 9) {
269 usb_debug("Invalid MPS0: 0x%02x\n", bMaxPacketSize0);
270 bMaxPacketSize0 = 9;
272 return 1 << bMaxPacketSize0;
273 default: /* GCC is stupid and cannot deal with enums correctly */
274 return 8;
278 /* Normalize bInterval to log2 of microframes */
279 static int
280 usb_decode_interval(usb_speed speed, const endpoint_type type, const unsigned char bInterval)
282 #define LOG2(a) ((sizeof(unsigned) << 3) - __builtin_clz(a) - 1)
283 switch (speed) {
284 case LOW_SPEED:
285 switch (type) {
286 case ISOCHRONOUS: case INTERRUPT:
287 return LOG2(bInterval) + 3;
288 default:
289 return 0;
291 case FULL_SPEED:
292 switch (type) {
293 case ISOCHRONOUS:
294 return (bInterval - 1) + 3;
295 case INTERRUPT:
296 return LOG2(bInterval) + 3;
297 default:
298 return 0;
300 case HIGH_SPEED:
301 switch (type) {
302 case ISOCHRONOUS: case INTERRUPT:
303 return bInterval - 1;
304 default:
305 return LOG2(bInterval);
307 case SUPER_SPEED:
308 switch (type) {
309 case ISOCHRONOUS: case INTERRUPT:
310 return bInterval - 1;
311 default:
312 return 0;
314 default:
315 return 0;
317 #undef LOG2
320 usbdev_t *
321 generic_set_address (hci_t *controller, usb_speed speed,
322 int hubport, int hubaddr)
324 int adr = get_free_address (controller); // address to set
325 dev_req_t dr;
327 memset (&dr, 0, sizeof (dr));
328 dr.data_dir = host_to_device;
329 dr.req_type = standard_type;
330 dr.req_recp = dev_recp;
331 dr.bRequest = SET_ADDRESS;
332 dr.wValue = adr;
333 dr.wIndex = 0;
334 dr.wLength = 0;
336 usbdev_t *dev = init_device_entry(controller, adr);
337 if (!dev)
338 return NULL;
340 // dummy values for registering the address
341 dev->address = 0;
342 dev->hub = hubaddr;
343 dev->port = hubport;
344 dev->speed = speed;
345 dev->endpoints[0].dev = dev;
346 dev->endpoints[0].endpoint = 0;
347 dev->endpoints[0].maxpacketsize = 8;
348 dev->endpoints[0].toggle = 0;
349 dev->endpoints[0].direction = SETUP;
350 dev->endpoints[0].type = CONTROL;
351 if (dev->controller->control (dev, OUT, sizeof (dr), &dr, 0, 0) < 0) {
352 usb_debug ("set_address failed\n");
353 usb_detach_device (controller, adr);
354 return NULL;
356 mdelay (SET_ADDRESS_MDELAY);
358 u8 buf[8];
359 dev->address = adr;
360 if (get_descriptor (dev, DR_DESC, DT_DEV, 0, buf, sizeof(buf))
361 != sizeof(buf)) {
362 usb_debug("first get_descriptor(DT_DEV) failed\n");
363 usb_detach_device (controller, adr);
364 return NULL;
366 dev->endpoints[0].maxpacketsize = usb_decode_mps0(speed, buf[7]);
368 return dev;
371 static int
372 set_address (hci_t *controller, usb_speed speed, int hubport, int hubaddr)
374 usbdev_t *dev = controller->set_address(controller, speed,
375 hubport, hubaddr);
376 if (!dev) {
377 usb_debug ("set_address failed\n");
378 return -1;
381 dev->descriptor = malloc(sizeof(*dev->descriptor));
382 if (!dev->descriptor || get_descriptor (dev, DR_DESC, DT_DEV, 0,
383 dev->descriptor, sizeof(*dev->descriptor))
384 != sizeof(*dev->descriptor)) {
385 usb_debug ("get_descriptor(DT_DEV) failed\n");
386 usb_detach_device (controller, dev->address);
387 return -1;
390 usb_debug ("* found device (0x%04x:0x%04x, USB %x.%x, MPS0: %d)\n",
391 dev->descriptor->idVendor, dev->descriptor->idProduct,
392 dev->descriptor->bcdUSB >> 8, dev->descriptor->bcdUSB & 0xff,
393 dev->endpoints[0].maxpacketsize);
394 dev->quirks = usb_quirk_check(dev->descriptor->idVendor,
395 dev->descriptor->idProduct);
397 usb_debug ("device has %d configurations\n",
398 dev->descriptor->bNumConfigurations);
399 if (dev->descriptor->bNumConfigurations == 0) {
400 /* device isn't usable */
401 usb_debug ("... no usable configuration!\n");
402 usb_detach_device (controller, dev->address);
403 return -1;
406 u16 buf[2];
407 if (get_descriptor (dev, DR_DESC, DT_CFG, 0, buf, sizeof(buf))
408 != sizeof(buf)) {
409 usb_debug ("first get_descriptor(DT_CFG) failed\n");
410 usb_detach_device (controller, dev->address);
411 return -1;
413 /* workaround for some USB devices: wait until they're ready, or
414 * they send a NAK when they're not allowed to do. 1ms is enough */
415 mdelay(1);
416 dev->configuration = malloc(buf[1]);
417 if (!dev->configuration) {
418 usb_debug ("could not allocate %d bytes for DT_CFG\n", buf[1]);
419 usb_detach_device (controller, dev->address);
420 return -1;
422 if (get_descriptor (dev, DR_DESC, DT_CFG, 0, dev->configuration,
423 buf[1]) != buf[1]) {
424 usb_debug ("get_descriptor(DT_CFG) failed\n");
425 usb_detach_device (controller, dev->address);
426 return -1;
428 configuration_descriptor_t *cd = dev->configuration;
429 if (cd->wTotalLength != buf[1]) {
430 usb_debug ("configuration descriptor size changed, aborting\n");
431 usb_detach_device (controller, dev->address);
432 return -1;
436 * If the device is not well known (ifnum == -1), we use the first
437 * interface we encounter, as there was no need to implement something
438 * else for the time being. If you need it, see the SetInterface and
439 * GetInterface functions in the USB specification and set it yourself.
441 usb_debug ("device has %x interfaces\n", cd->bNumInterfaces);
442 int ifnum = usb_interface_check(dev->descriptor->idVendor,
443 dev->descriptor->idProduct);
444 if (cd->bNumInterfaces > 1 && ifnum < 0)
445 usb_debug ("NOTICE: Your device has multiple interfaces and\n"
446 "this driver will only use the first one. That may\n"
447 "be the wrong choice and cause the device to not\n"
448 "work correctly. Please report this case\n"
449 "(including the above debugging output) to\n"
450 "coreboot@coreboot.org to have the device added to\n"
451 "the list of well-known quirks.\n");
453 u8 *end = (void *)dev->configuration + cd->wTotalLength;
454 interface_descriptor_t *intf;
455 u8 *ptr;
457 /* Find our interface (or the first good one if we don't know) */
458 for (ptr = (void *)dev->configuration + sizeof(*cd); ; ptr += ptr[0]) {
459 if (ptr + 2 > end || !ptr[0] || ptr + ptr[0] > end) {
460 usb_debug ("Couldn't find usable DT_INTF\n");
461 usb_detach_device (controller, dev->address);
462 return -1;
464 if (ptr[1] != DT_INTF)
465 continue;
466 intf = (void *)ptr;
467 if (intf->bLength != sizeof(*intf)) {
468 usb_debug ("Skipping broken DT_INTF\n");
469 continue;
471 if (ifnum >= 0 && intf->bInterfaceNumber != ifnum)
472 continue;
473 usb_debug ("Interface %d: class 0x%x, sub 0x%x. proto 0x%x\n",
474 intf->bInterfaceNumber, intf->bInterfaceClass,
475 intf->bInterfaceSubClass, intf->bInterfaceProtocol);
476 ptr += sizeof(*intf);
477 break;
480 /* Gather up all endpoints belonging to this inteface */
481 dev->num_endp = 1;
482 for (; ptr + 2 <= end && ptr[0] && ptr + ptr[0] <= end; ptr += ptr[0]) {
483 if (ptr[1] == DT_INTF || ptr[1] == DT_CFG ||
484 dev->num_endp >= ARRAY_SIZE(dev->endpoints))
485 break;
486 if (ptr[1] != DT_ENDP)
487 continue;
489 endpoint_descriptor_t *desc = (void *)ptr;
490 static const char *transfertypes[4] = {
491 "control", "isochronous", "bulk", "interrupt"
493 usb_debug (" #Endpoint %d (%s), max packet size %x, type %s\n",
494 desc->bEndpointAddress & 0x7f,
495 (desc->bEndpointAddress & 0x80) ? "in" : "out",
496 desc->wMaxPacketSize,
497 transfertypes[desc->bmAttributes & 0x3]);
499 endpoint_t *ep = &dev->endpoints[dev->num_endp++];
500 ep->dev = dev;
501 ep->endpoint = desc->bEndpointAddress;
502 ep->toggle = 0;
503 ep->maxpacketsize = desc->wMaxPacketSize;
504 ep->direction = (desc->bEndpointAddress & 0x80) ? IN : OUT;
505 ep->type = desc->bmAttributes & 0x3;
506 ep->interval = usb_decode_interval (dev->speed, ep->type,
507 desc->bInterval);
510 if ((controller->finish_device_config &&
511 controller->finish_device_config(dev)) ||
512 set_configuration(dev) < 0) {
513 usb_debug ("Could not finalize device configuration\n");
514 usb_detach_device (controller, dev->address);
515 return -1;
518 int class = dev->descriptor->bDeviceClass;
519 if (class == 0)
520 class = intf->bInterfaceClass;
522 enum {
523 audio_device = 0x01,
524 comm_device = 0x02,
525 hid_device = 0x03,
526 physical_device = 0x05,
527 imaging_device = 0x06,
528 printer_device = 0x07,
529 msc_device = 0x08,
530 hub_device = 0x09,
531 cdc_device = 0x0a,
532 ccid_device = 0x0b,
533 security_device = 0x0d,
534 video_device = 0x0e,
535 healthcare_device = 0x0f,
536 diagnostic_device = 0xdc,
537 wireless_device = 0xe0,
538 misc_device = 0xef,
540 usb_debug("Class: ");
541 switch (class) {
542 case audio_device:
543 usb_debug("audio\n");
544 break;
545 case comm_device:
546 usb_debug("communication\n");
547 break;
548 case hid_device:
549 usb_debug ("HID\n");
550 #if IS_ENABLED(CONFIG_LP_USB_HID)
551 dev->init = usb_hid_init;
552 return dev->address;
553 #else
554 usb_debug ("NOTICE: USB HID support not compiled in\n");
555 #endif
556 break;
557 case physical_device:
558 usb_debug("physical\n");
559 break;
560 case imaging_device:
561 usb_debug("camera\n");
562 break;
563 case printer_device:
564 usb_debug("printer\n");
565 break;
566 case msc_device:
567 usb_debug ("MSC\n");
568 #if IS_ENABLED(CONFIG_LP_USB_MSC)
569 dev->init = usb_msc_init;
570 return dev->address;
571 #else
572 usb_debug ("NOTICE: USB MSC support not compiled in\n");
573 #endif
574 break;
575 case hub_device:
576 usb_debug ("hub\n");
577 #if IS_ENABLED(CONFIG_LP_USB_HUB)
578 dev->init = usb_hub_init;
579 return dev->address;
580 #else
581 usb_debug ("NOTICE: USB hub support not compiled in\n");
582 #endif
583 break;
584 case cdc_device:
585 usb_debug("CDC\n");
586 break;
587 case ccid_device:
588 usb_debug("smartcard / CCID\n");
589 break;
590 case security_device:
591 usb_debug("content security\n");
592 break;
593 case video_device:
594 usb_debug("video\n");
595 break;
596 case healthcare_device:
597 usb_debug("healthcare\n");
598 break;
599 case diagnostic_device:
600 usb_debug("diagnostic\n");
601 break;
602 case wireless_device:
603 usb_debug("wireless\n");
604 break;
605 default:
606 usb_debug("unsupported class %x\n", class);
607 break;
609 dev->init = usb_generic_init;
610 return dev->address;
614 * Should be called by the hub drivers whenever a physical detach occurs
615 * and can be called by usb class drivers if they are unsatisfied with a
616 * malfunctioning device.
618 void
619 usb_detach_device(hci_t *controller, int devno)
621 /* check if device exists, as we may have
622 been called yet by the usb class driver */
623 if (controller->devices[devno]) {
624 controller->devices[devno]->destroy (controller->devices[devno]);
625 if (controller->destroy_device)
626 controller->destroy_device(controller, devno);
627 /* Tear down the device itself *after* destroy_device()
628 * has had a chance to interoogate it. */
629 free(controller->devices[devno]);
630 controller->devices[devno] = NULL;
635 usb_attach_device(hci_t *controller, int hubaddress, int port, usb_speed speed)
637 static const char* speeds[] = { "full", "low", "high", "super" };
638 usb_debug ("%sspeed device\n", (speed < sizeof(speeds) / sizeof(char*))
639 ? speeds[speed] : "invalid value - no");
640 int newdev = set_address (controller, speed, port, hubaddress);
641 if (newdev == -1)
642 return -1;
643 usbdev_t *newdev_t = controller->devices[newdev];
644 // determine responsible driver - current done in set_address
645 newdev_t->init (newdev_t);
646 /* init() may have called usb_detach_device() yet, so check */
647 return controller->devices[newdev] ? newdev : -1;
650 static void
651 usb_generic_destroy (usbdev_t *dev)
653 if (usb_generic_remove)
654 usb_generic_remove(dev);
657 void
658 usb_generic_init (usbdev_t *dev)
660 dev->data = NULL;
661 dev->destroy = usb_generic_destroy;
663 if (usb_generic_create)
664 usb_generic_create(dev);
666 if (dev->data == NULL) {
667 usb_debug("Detaching device not used by payload\n");
668 usb_detach_device(dev->controller, dev->address);
673 * returns the address of the closest USB2.0 hub, which is responsible for
674 * split transactions, along with the number of the used downstream port
676 int closest_usb2_hub(const usbdev_t *dev, int *const addr, int *const port)
678 const usbdev_t *usb1dev;
680 do {
681 usb1dev = dev;
682 if ((dev->hub >= 0) && (dev->hub < 128))
683 dev = dev->controller->devices[dev->hub];
684 else
685 dev = NULL;
686 } while (dev && (dev->speed < 2));
688 if (dev) {
689 *addr = usb1dev->hub;
690 *port = usb1dev->port;
691 return 0;
694 usb_debug("Couldn't find closest USB2.0 hub.\n");
695 return 1;