MFC rev 1.11 and 1.12:
[dragonfly.git] / sys / bus / usb / usb_subr.c
blobd4a4d3b22a6f43f98d6ccff81647e33b73b227b3
1 /* $NetBSD: usb_subr.c,v 1.99 2002/07/11 21:14:34 augustss Exp $ */
2 /* $FreeBSD: src/sys/dev/usb/usb_subr.c,v 1.76.2.3 2006/03/01 01:59:05 iedowse Exp $ */
3 /* $DragonFly: src/sys/bus/usb/usb_subr.c,v 1.28 2008/05/25 16:38:36 mneumann Exp $ */
5 /* Also already have from NetBSD:
6 * $NetBSD: usb_subr.c,v 1.102 2003/01/01 16:21:50 augustss Exp $
7 * $NetBSD: usb_subr.c,v 1.103 2003/01/10 11:19:13 augustss Exp $
8 * $NetBSD: usb_subr.c,v 1.111 2004/03/15 10:35:04 augustss Exp $
9 * $NetBSD: usb_subr.c,v 1.114 2004/06/23 02:30:52 mycroft Exp $
10 * $NetBSD: usb_subr.c,v 1.115 2004/06/23 05:23:19 mycroft Exp $
11 * $NetBSD: usb_subr.c,v 1.116 2004/06/23 06:27:54 mycroft Exp $
12 * $NetBSD: usb_subr.c,v 1.119 2004/10/23 13:26:33 augustss Exp $
16 * Copyright (c) 1998 The NetBSD Foundation, Inc.
17 * All rights reserved.
19 * This code is derived from software contributed to The NetBSD Foundation
20 * by Lennart Augustsson (lennart@augustsson.net) at
21 * Carlstedt Research & Technology.
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the above copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 * must display the following acknowledgement:
33 * This product includes software developed by the NetBSD
34 * Foundation, Inc. and its contributors.
35 * 4. Neither the name of The NetBSD Foundation nor the names of its
36 * contributors may be used to endorse or promote products derived
37 * from this software without specific prior written permission.
39 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
40 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
41 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
43 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
44 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
45 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
46 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
47 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
48 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
49 * POSSIBILITY OF SUCH DAMAGE.
52 #include "opt_usb.h"
54 #include <sys/param.h>
55 #include <sys/systm.h>
56 #include <sys/kernel.h>
57 #include <sys/malloc.h>
58 #include <sys/module.h>
59 #include <sys/bus.h>
60 #include <sys/proc.h>
62 #include <bus/usb/usb.h>
64 #include <bus/usb/usbdi.h>
65 #include <bus/usb/usbdi_util.h>
66 #include <bus/usb/usbdivar.h>
67 #include <bus/usb/usb_quirks.h>
69 #define delay(d) DELAY(d)
71 #ifdef USB_DEBUG
72 #define DPRINTF(x) if (usbdebug) kprintf x
73 #define DPRINTFN(n,x) if (usbdebug>(n)) kprintf x
74 extern int usbdebug;
75 #else
76 #define DPRINTF(x)
77 #define DPRINTFN(n,x)
78 #endif
80 static usbd_status usbd_set_config(usbd_device_handle, int);
81 static void usbd_devinfo_vp(usbd_device_handle, char *, char *, int);
82 static int usbd_getnewaddr(usbd_bus_handle bus);
83 static void usbd_free_iface_data(usbd_device_handle dev, int ifcno);
84 static void usbd_kill_pipe(usbd_pipe_handle);
85 static usbd_status usbd_probe_and_attach(device_t parent,
86 usbd_device_handle dev, int port, int addr);
88 static u_int32_t usb_cookie_no = 0;
90 static const char * const usbd_error_strs[] = {
91 "NORMAL_COMPLETION",
92 "IN_PROGRESS",
93 "PENDING_REQUESTS",
94 "NOT_STARTED",
95 "INVAL",
96 "NOMEM",
97 "CANCELLED",
98 "BAD_ADDRESS",
99 "IN_USE",
100 "NO_ADDR",
101 "SET_ADDR_FAILED",
102 "NO_POWER",
103 "TOO_DEEP",
104 "IOERROR",
105 "NOT_CONFIGURED",
106 "TIMEOUT",
107 "SHORT_XFER",
108 "STALLED",
109 "INTERRUPTED",
110 "XXX",
113 const char *
114 usbd_errstr(usbd_status err)
116 static char buffer[5];
118 if (err < USBD_ERROR_MAX) {
119 return usbd_error_strs[err];
120 } else {
121 ksnprintf(buffer, sizeof buffer, "%d", err);
122 return buffer;
126 usbd_status
127 usbd_get_string_desc(usbd_device_handle dev, int sindex, int langid,
128 usb_string_descriptor_t *sdesc, int *sizep)
130 usb_device_request_t req;
131 usbd_status err;
132 int actlen;
134 req.bmRequestType = UT_READ_DEVICE;
135 req.bRequest = UR_GET_DESCRIPTOR;
136 USETW2(req.wValue, UDESC_STRING, sindex);
137 USETW(req.wIndex, langid);
138 USETW(req.wLength, 2); /* only size byte first */
139 err = usbd_do_request_flags(dev, &req, sdesc, USBD_SHORT_XFER_OK,
140 &actlen, USBD_DEFAULT_TIMEOUT);
141 if (err)
142 return (err);
144 if (actlen < 2)
145 return (USBD_SHORT_XFER);
147 USETW(req.wLength, sdesc->bLength); /* the whole string */
148 err = usbd_do_request_flags(dev, &req, sdesc, USBD_SHORT_XFER_OK,
149 &actlen, USBD_DEFAULT_TIMEOUT);
150 if (err)
151 return (err);
153 if (actlen != sdesc->bLength) {
154 DPRINTFN(-1, ("usbd_get_string_desc: expected %d, got %d\n",
155 sdesc->bLength, actlen));
158 *sizep = actlen;
159 return (USBD_NORMAL_COMPLETION);
162 static void
163 usbd_trim_spaces(char *p)
165 char *q, *e;
167 if (p == NULL)
168 return;
169 q = e = p;
170 while (*q == ' ') /* skip leading spaces */
171 q++;
172 while ((*p = *q++)) /* copy string */
173 if (*p++ != ' ') /* remember last non-space */
174 e = p;
175 *e = 0; /* kill trailing spaces */
178 static void
179 usbd_devinfo_vp(usbd_device_handle dev, char *v, char *p, int usedev)
181 usb_device_descriptor_t *udd = &dev->ddesc;
182 char *vendor = 0, *product = 0;
184 if (dev == NULL) {
185 v[0] = p[0] = '\0';
186 return;
189 if (usedev) {
190 if (usbd_get_string(dev, udd->iManufacturer, v))
191 vendor = NULL;
192 else
193 vendor = v;
194 usbd_trim_spaces(vendor);
195 if (usbd_get_string(dev, udd->iProduct, p))
196 product = NULL;
197 else
198 product = p;
199 usbd_trim_spaces(product);
200 if (vendor && !*vendor)
201 vendor = NULL;
202 if (product && !*product)
203 product = NULL;
204 } else {
205 vendor = NULL;
206 product = NULL;
209 if (vendor != NULL && *vendor)
210 strcpy(v, vendor);
211 else
212 ksprintf(v, "vendor 0x%04x", UGETW(udd->idVendor));
213 if (product != NULL && *product)
214 strcpy(p, product);
215 else
216 ksprintf(p, "product 0x%04x", UGETW(udd->idProduct));
220 usbd_printBCD(char *cp, int bcd)
222 return (ksprintf(cp, "%x.%02x", bcd >> 8, bcd & 0xff));
225 void
226 usbd_devinfo(usbd_device_handle dev, int showclass, char *cp)
228 usb_device_descriptor_t *udd = &dev->ddesc;
229 usbd_interface_handle iface;
230 char vendor[USB_MAX_STRING_LEN];
231 char product[USB_MAX_STRING_LEN];
232 int bcdDevice, bcdUSB;
233 usb_interface_descriptor_t *id;
235 usbd_devinfo_vp(dev, vendor, product, 1);
236 cp += ksprintf(cp, "%s %s", vendor, product);
237 if (showclass & USBD_SHOW_DEVICE_CLASS)
238 cp += ksprintf(cp, ", class %d/%d",
239 udd->bDeviceClass, udd->bDeviceSubClass);
240 bcdUSB = UGETW(udd->bcdUSB);
241 bcdDevice = UGETW(udd->bcdDevice);
242 cp += ksprintf(cp, ", rev ");
243 cp += usbd_printBCD(cp, bcdUSB);
244 *cp++ = '/';
245 cp += usbd_printBCD(cp, bcdDevice);
246 cp += ksprintf(cp, ", addr %d", dev->address);
247 if (showclass & USBD_SHOW_INTERFACE_CLASS)
249 /* fetch the interface handle for the first interface */
250 (void)usbd_device2interface_handle(dev, 0, &iface);
251 id = usbd_get_interface_descriptor(iface);
252 cp += ksprintf(cp, ", iclass %d/%d",
253 id->bInterfaceClass, id->bInterfaceSubClass);
255 *cp = 0;
258 /* Delay for a certain number of ms */
259 void
260 usb_delay_ms(usbd_bus_handle bus, u_int ms)
262 /* Wait at least two clock ticks so we know the time has passed. */
263 if (bus->use_polling || cold)
264 delay((ms+1) * 1000);
265 else
266 tsleep(&ms, 0, "usbdly", (ms*hz+999)/1000 + 1);
269 /* Delay given a device handle. */
270 void
271 usbd_delay_ms(usbd_device_handle dev, u_int ms)
273 usb_delay_ms(dev->bus, ms);
276 usbd_status
277 usbd_reset_port(usbd_device_handle dev, int port, usb_port_status_t *ps)
279 usb_device_request_t req;
280 usbd_status err;
281 int n;
283 req.bmRequestType = UT_WRITE_CLASS_OTHER;
284 req.bRequest = UR_SET_FEATURE;
285 USETW(req.wValue, UHF_PORT_RESET);
286 USETW(req.wIndex, port);
287 USETW(req.wLength, 0);
288 err = usbd_do_request(dev, &req, 0);
289 DPRINTFN(1,("usbd_reset_port: port %d reset done, error=%s\n",
290 port, usbd_errstr(err)));
291 if (err)
292 return (err);
293 n = 10;
294 do {
295 /* Wait for device to recover from reset. */
296 usbd_delay_ms(dev, USB_PORT_RESET_DELAY);
297 err = usbd_get_port_status(dev, port, ps);
298 if (err) {
299 DPRINTF(("usbd_reset_port: get status failed %d\n",
300 err));
301 return (err);
303 /* If the device disappeared, just give up. */
304 if (!(UGETW(ps->wPortStatus) & UPS_CURRENT_CONNECT_STATUS))
305 return (USBD_NORMAL_COMPLETION);
306 } while ((UGETW(ps->wPortChange) & UPS_C_PORT_RESET) == 0 && --n > 0);
307 if (n == 0)
308 return (USBD_TIMEOUT);
309 err = usbd_clear_port_feature(dev, port, UHF_C_PORT_RESET);
310 #ifdef USB_DEBUG
311 if (err)
312 DPRINTF(("usbd_reset_port: clear port feature failed %d\n",
313 err));
314 #endif
316 /* Wait for the device to recover from reset. */
317 usbd_delay_ms(dev, USB_PORT_RESET_RECOVERY);
318 return (err);
321 usb_interface_descriptor_t *
322 usbd_find_idesc(usb_config_descriptor_t *cd, int ifaceidx, int altidx)
324 char *p = (char *)cd;
325 char *end = p + UGETW(cd->wTotalLength);
326 usb_interface_descriptor_t *d;
327 int curidx, lastidx, curaidx = 0;
329 for (curidx = lastidx = -1; p < end; ) {
330 d = (usb_interface_descriptor_t *)p;
331 DPRINTFN(4,("usbd_find_idesc: idx=%d(%d) altidx=%d(%d) len=%d "
332 "type=%d\n",
333 ifaceidx, curidx, altidx, curaidx,
334 d->bLength, d->bDescriptorType));
335 if (d->bLength == 0) /* bad descriptor */
336 break;
337 p += d->bLength;
338 if (p <= end && d->bDescriptorType == UDESC_INTERFACE) {
339 if (d->bInterfaceNumber != lastidx) {
340 lastidx = d->bInterfaceNumber;
341 curidx++;
342 curaidx = 0;
343 } else
344 curaidx++;
345 if (ifaceidx == curidx && altidx == curaidx)
346 return (d);
349 return (NULL);
352 usb_endpoint_descriptor_t *
353 usbd_find_edesc(usb_config_descriptor_t *cd, int ifaceidx, int altidx,
354 int endptidx)
356 char *p = (char *)cd;
357 char *end = p + UGETW(cd->wTotalLength);
358 usb_interface_descriptor_t *d;
359 usb_endpoint_descriptor_t *e;
360 int curidx;
362 d = usbd_find_idesc(cd, ifaceidx, altidx);
363 if (d == NULL)
364 return (NULL);
365 if (endptidx >= d->bNumEndpoints) /* quick exit */
366 return (NULL);
368 curidx = -1;
369 for (p = (char *)d + d->bLength; p < end; ) {
370 e = (usb_endpoint_descriptor_t *)p;
371 if (e->bLength == 0) /* bad descriptor */
372 break;
373 p += e->bLength;
374 if (p <= end && e->bDescriptorType == UDESC_INTERFACE)
375 return (NULL);
376 if (p <= end && e->bDescriptorType == UDESC_ENDPOINT) {
377 curidx++;
378 if (curidx == endptidx)
379 return (e);
382 return (NULL);
385 usbd_status
386 usbd_fill_iface_data(usbd_device_handle dev, int ifaceidx, int altidx)
388 usbd_interface_handle ifc = &dev->ifaces[ifaceidx];
389 usb_interface_descriptor_t *idesc;
390 char *p, *end;
391 int endpt, nendpt;
393 DPRINTFN(4,("usbd_fill_iface_data: ifaceidx=%d altidx=%d\n",
394 ifaceidx, altidx));
395 idesc = usbd_find_idesc(dev->cdesc, ifaceidx, altidx);
396 if (idesc == NULL)
397 return (USBD_INVAL);
398 ifc->device = dev;
399 ifc->idesc = idesc;
400 ifc->index = ifaceidx;
401 ifc->altindex = altidx;
402 nendpt = ifc->idesc->bNumEndpoints;
403 DPRINTFN(4,("usbd_fill_iface_data: found idesc nendpt=%d\n", nendpt));
404 if (nendpt != 0) {
405 ifc->endpoints = kmalloc(nendpt * sizeof(struct usbd_endpoint),
406 M_USB, M_INTWAIT);
407 } else {
408 ifc->endpoints = NULL;
410 ifc->priv = NULL;
411 p = (char *)ifc->idesc + ifc->idesc->bLength;
412 end = (char *)dev->cdesc + UGETW(dev->cdesc->wTotalLength);
413 #define ed ((usb_endpoint_descriptor_t *)p)
414 for (endpt = 0; endpt < nendpt; endpt++) {
415 DPRINTFN(10,("usbd_fill_iface_data: endpt=%d\n", endpt));
416 for (; p < end; p += ed->bLength) {
417 DPRINTFN(10,("usbd_fill_iface_data: p=%p end=%p "
418 "len=%d type=%d\n",
419 p, end, ed->bLength, ed->bDescriptorType));
420 if (p + ed->bLength <= end && ed->bLength != 0 &&
421 ed->bDescriptorType == UDESC_ENDPOINT)
422 goto found;
423 if (ed->bLength == 0 ||
424 ed->bDescriptorType == UDESC_INTERFACE)
425 break;
427 /* passed end, or bad desc */
428 kprintf("usbd_fill_iface_data: bad descriptor(s): %s\n",
429 ed->bLength == 0 ? "0 length" :
430 ed->bDescriptorType == UDESC_INTERFACE ? "iface desc":
431 "out of data");
432 goto bad;
433 found:
434 ifc->endpoints[endpt].edesc = ed;
435 if (dev->speed == USB_SPEED_HIGH) {
436 u_int mps;
437 /* Control and bulk endpoints have max packet limits. */
438 switch (UE_GET_XFERTYPE(ed->bmAttributes)) {
439 case UE_CONTROL:
440 mps = USB_2_MAX_CTRL_PACKET;
441 goto check;
442 case UE_BULK:
443 mps = USB_2_MAX_BULK_PACKET;
444 check:
445 if (UGETW(ed->wMaxPacketSize) != mps) {
446 USETW(ed->wMaxPacketSize, mps);
447 #ifdef DIAGNOSTIC
448 kprintf("usbd_fill_iface_data: bad max "
449 "packet size\n");
450 #endif
452 break;
453 default:
454 break;
457 ifc->endpoints[endpt].refcnt = 0;
458 ifc->endpoints[endpt].savedtoggle = 0;
459 p += ed->bLength;
461 #undef ed
462 LIST_INIT(&ifc->pipes);
463 return (USBD_NORMAL_COMPLETION);
465 bad:
466 if (ifc->endpoints != NULL) {
467 kfree(ifc->endpoints, M_USB);
468 ifc->endpoints = NULL;
470 return (USBD_INVAL);
473 void
474 usbd_free_iface_data(usbd_device_handle dev, int ifcno)
476 usbd_interface_handle ifc = &dev->ifaces[ifcno];
477 if (ifc->endpoints)
478 kfree(ifc->endpoints, M_USB);
481 static usbd_status
482 usbd_set_config(usbd_device_handle dev, int conf)
484 usb_device_request_t req;
486 req.bmRequestType = UT_WRITE_DEVICE;
487 req.bRequest = UR_SET_CONFIG;
488 USETW(req.wValue, conf);
489 USETW(req.wIndex, 0);
490 USETW(req.wLength, 0);
491 return (usbd_do_request(dev, &req, 0));
494 usbd_status
495 usbd_set_config_no(usbd_device_handle dev, int no, int msg)
497 int index;
498 usb_config_descriptor_t cd;
499 usbd_status err;
501 if (no == USB_UNCONFIG_NO)
502 return (usbd_set_config_index(dev, USB_UNCONFIG_INDEX, msg));
504 DPRINTFN(5,("usbd_set_config_no: %d\n", no));
505 /* Figure out what config index to use. */
506 for (index = 0; index < dev->ddesc.bNumConfigurations; index++) {
507 err = usbd_get_config_desc(dev, index, &cd);
508 if (err)
509 return (err);
510 if (cd.bConfigurationValue == no)
511 return (usbd_set_config_index(dev, index, msg));
513 return (USBD_INVAL);
516 usbd_status
517 usbd_set_config_index(usbd_device_handle dev, int index, int msg)
519 usb_status_t ds;
520 usb_config_descriptor_t cd, *cdp;
521 usbd_status err;
522 int i, ifcidx, nifc, len, selfpowered, power;
524 DPRINTFN(5,("usbd_set_config_index: dev=%p index=%d\n", dev, index));
526 if (dev->config != USB_UNCONFIG_NO) {
527 nifc = dev->cdesc->bNumInterface;
529 /* Check that all interfaces are idle */
530 for (ifcidx = 0; ifcidx < nifc; ifcidx++) {
531 if (LIST_EMPTY(&dev->ifaces[ifcidx].pipes))
532 continue;
533 DPRINTF(("usbd_set_config_index: open pipes exist\n"));
534 return (USBD_IN_USE);
537 DPRINTF(("usbd_set_config_index: free old config\n"));
538 /* Free all configuration data structures. */
539 for (ifcidx = 0; ifcidx < nifc; ifcidx++)
540 usbd_free_iface_data(dev, ifcidx);
541 kfree(dev->ifaces, M_USB);
542 kfree(dev->cdesc, M_USB);
543 dev->ifaces = NULL;
544 dev->cdesc = NULL;
545 dev->config = USB_UNCONFIG_NO;
548 if (index == USB_UNCONFIG_INDEX) {
549 /* We are unconfiguring the device, so leave unallocated. */
550 DPRINTF(("usbd_set_config_index: set config 0\n"));
551 err = usbd_set_config(dev, USB_UNCONFIG_NO);
552 if (err)
553 DPRINTF(("usbd_set_config_index: setting config=0 "
554 "failed, error=%s\n", usbd_errstr(err)));
555 return (err);
558 /* Get the short descriptor. */
559 err = usbd_get_config_desc(dev, index, &cd);
560 if (err)
561 return (err);
562 len = UGETW(cd.wTotalLength);
563 cdp = kmalloc(len, M_USB, M_INTWAIT);
564 /* Get the full descriptor. Try a few times for slow devices. */
565 for (i = 0; i < 3; i++) {
566 err = usbd_get_desc(dev, UDESC_CONFIG, index, len, cdp);
567 if (!err)
568 break;
569 usbd_delay_ms(dev, 200);
571 if (err)
572 goto bad;
573 if (cdp->bDescriptorType != UDESC_CONFIG) {
574 DPRINTFN(-1,("usbd_set_config_index: bad desc %d\n",
575 cdp->bDescriptorType));
576 err = USBD_INVAL;
577 goto bad;
580 /* Figure out if the device is self or bus powered. */
581 selfpowered = 0;
582 if (!(dev->quirks->uq_flags & UQ_BUS_POWERED) &&
583 (cdp->bmAttributes & UC_SELF_POWERED)) {
584 /* May be self powered. */
585 if (cdp->bmAttributes & UC_BUS_POWERED) {
586 /* Must ask device. */
587 if (dev->quirks->uq_flags & UQ_POWER_CLAIM) {
589 * Hub claims to be self powered, but isn't.
590 * It seems that the power status can be
591 * determined by the hub characteristics.
593 usb_hub_descriptor_t hd;
594 usb_device_request_t req;
595 req.bmRequestType = UT_READ_CLASS_DEVICE;
596 req.bRequest = UR_GET_DESCRIPTOR;
597 USETW(req.wValue, 0);
598 USETW(req.wIndex, 0);
599 USETW(req.wLength, USB_HUB_DESCRIPTOR_SIZE);
600 err = usbd_do_request(dev, &req, &hd);
601 if (!err &&
602 (UGETW(hd.wHubCharacteristics) &
603 UHD_PWR_INDIVIDUAL))
604 selfpowered = 1;
605 DPRINTF(("usbd_set_config_index: charac=0x%04x"
606 ", error=%s\n",
607 UGETW(hd.wHubCharacteristics),
608 usbd_errstr(err)));
609 } else {
610 err = usbd_get_device_status(dev, &ds);
611 if (!err &&
612 (UGETW(ds.wStatus) & UDS_SELF_POWERED))
613 selfpowered = 1;
614 DPRINTF(("usbd_set_config_index: status=0x%04x"
615 ", error=%s\n",
616 UGETW(ds.wStatus), usbd_errstr(err)));
618 } else
619 selfpowered = 1;
621 DPRINTF(("usbd_set_config_index: (addr %d) cno=%d attr=0x%02x, "
622 "selfpowered=%d, power=%d\n",
623 cdp->bConfigurationValue, dev->address, cdp->bmAttributes,
624 selfpowered, cdp->bMaxPower * 2));
626 /* Check if we have enough power. */
627 #ifdef USB_DEBUG
628 if (dev->powersrc == NULL) {
629 DPRINTF(("usbd_set_config_index: No power source?\n"));
630 return (USBD_IOERROR);
632 #endif
633 power = cdp->bMaxPower * 2;
634 if (power > dev->powersrc->power) {
635 DPRINTF(("power exceeded %d %d\n", power,dev->powersrc->power));
636 /* XXX print nicer message. */
637 if (msg)
638 kprintf("%s: device addr %d (config %d) exceeds power "
639 "budget, %d mA > %d mA\n",
640 device_get_nameunit(dev->bus->bdev), dev->address,
641 cdp->bConfigurationValue,
642 power, dev->powersrc->power);
643 err = USBD_NO_POWER;
644 goto bad;
646 dev->power = power;
647 dev->self_powered = selfpowered;
649 /* Set the actual configuration value. */
650 DPRINTF(("usbd_set_config_index: set config %d\n",
651 cdp->bConfigurationValue));
652 err = usbd_set_config(dev, cdp->bConfigurationValue);
653 if (err) {
654 DPRINTF(("usbd_set_config_index: setting config=%d failed, "
655 "error=%s\n",
656 cdp->bConfigurationValue, usbd_errstr(err)));
657 goto bad;
660 /* Allocate and fill interface data. */
661 nifc = cdp->bNumInterface;
662 dev->ifaces = kmalloc(nifc * sizeof(struct usbd_interface),
663 M_USB, M_INTWAIT);
664 DPRINTFN(5,("usbd_set_config_index: dev=%p cdesc=%p\n", dev, cdp));
665 dev->cdesc = cdp;
666 dev->config = cdp->bConfigurationValue;
667 for (ifcidx = 0; ifcidx < nifc; ifcidx++) {
668 err = usbd_fill_iface_data(dev, ifcidx, 0);
669 if (err) {
670 while (--ifcidx >= 0)
671 usbd_free_iface_data(dev, ifcidx);
672 goto bad;
676 return (USBD_NORMAL_COMPLETION);
678 bad:
679 kfree(cdp, M_USB);
680 return (err);
683 /* XXX add function for alternate settings */
685 usbd_status
686 usbd_setup_pipe(usbd_device_handle dev, usbd_interface_handle iface,
687 struct usbd_endpoint *ep, int ival, usbd_pipe_handle *pipe)
689 usbd_pipe_handle p;
690 usbd_status err;
692 DPRINTFN(1,("usbd_setup_pipe: dev=%p iface=%p ep=%p pipe=%p\n",
693 dev, iface, ep, pipe));
694 p = kmalloc(dev->bus->pipe_size, M_USB, M_INTWAIT);
695 p->device = dev;
696 p->iface = iface;
697 p->endpoint = ep;
698 ep->refcnt++;
699 p->refcnt = 1;
700 p->intrxfer = 0;
701 p->running = 0;
702 p->aborting = 0;
703 p->repeat = 0;
704 p->interval = ival;
705 STAILQ_INIT(&p->queue);
706 err = dev->bus->methods->open_pipe(p);
707 if (err) {
708 DPRINTFN(-1,("usbd_setup_pipe: endpoint=0x%x failed, error="
709 "%s\n",
710 ep->edesc->bEndpointAddress, usbd_errstr(err)));
711 kfree(p, M_USB);
712 return (err);
715 *pipe = p;
716 return (USBD_NORMAL_COMPLETION);
719 /* Abort the device control pipe. */
720 void
721 usbd_kill_pipe(usbd_pipe_handle pipe)
723 usbd_abort_pipe(pipe);
724 pipe->methods->close(pipe);
725 pipe->endpoint->refcnt--;
726 kfree(pipe, M_USB);
730 usbd_getnewaddr(usbd_bus_handle bus)
732 int addr;
734 for (addr = 1; addr < USB_MAX_DEVICES; addr++)
735 if (bus->devices[addr] == 0)
736 return (addr);
737 return (-1);
741 usbd_status
742 usbd_probe_and_attach(device_t parent, usbd_device_handle dev,
743 int port, int addr)
745 struct usb_attach_arg uaa;
746 usb_device_descriptor_t *dd = &dev->ddesc;
747 int found, i, confi, nifaces;
748 usbd_status err;
749 device_t *tmpdv;
750 usbd_interface_handle ifaces[256]; /* 256 is the absolute max */
751 char *devinfo;
753 /* XXX FreeBSD may leak resources on failure cases -- fixme */
754 device_t bdev;
755 struct usb_attach_arg *uaap;
757 devinfo = kmalloc(1024, M_USB, M_NOWAIT);
758 if (devinfo == NULL) {
759 device_printf(parent,
760 "Can't allocate memory for probe string\n");
761 return (USBD_NOMEM);
763 bdev = device_add_child(parent, NULL, -1);
764 if (!bdev) {
765 kfree(devinfo, M_USB);
766 device_printf(parent, "Device creation failed\n");
767 return (USBD_INVAL);
769 uaap = kmalloc(sizeof(uaa), M_USB, M_WAITOK);
770 device_set_ivars(bdev, uaap);
771 uaa.device = dev;
772 uaa.iface = NULL;
773 uaa.ifaces = NULL;
774 uaa.nifaces = 0;
775 uaa.usegeneric = 0;
776 uaa.port = port;
777 uaa.configno = UHUB_UNK_CONFIGURATION;
778 uaa.ifaceno = UHUB_UNK_INTERFACE;
779 uaa.vendor = UGETW(dd->idVendor);
780 uaa.product = UGETW(dd->idProduct);
781 uaa.release = UGETW(dd->bcdDevice);
783 /* First try with device specific drivers. */
784 DPRINTF(("usbd_probe_and_attach: trying device specific drivers\n"));
786 dev->ifacenums = NULL;
787 dev->subdevs = kmalloc(2 * sizeof(device_t), M_USB, M_WAITOK);
788 dev->subdevs[0] = bdev;
789 dev->subdevs[1] = 0;
790 *uaap = uaa;
791 usbd_devinfo(dev, 1, devinfo);
792 device_set_desc_copy(bdev, devinfo);
793 if (device_probe_and_attach(bdev) == 0) {
794 kfree(devinfo, M_USB);
795 return (USBD_NORMAL_COMPLETION);
799 * Free subdevs so we can reallocate it larger for the number of
800 * interfaces
802 tmpdv = dev->subdevs;
803 dev->subdevs = NULL;
804 kfree(tmpdv, M_USB);
805 DPRINTF(("usbd_probe_and_attach: no device specific driver found\n"));
807 DPRINTF(("usbd_probe_and_attach: looping over %d configurations\n",
808 dd->bNumConfigurations));
809 /* Next try with interface drivers. */
810 for (confi = 0; confi < dd->bNumConfigurations; confi++) {
811 DPRINTFN(1,("usbd_probe_and_attach: trying config idx=%d\n",
812 confi));
813 err = usbd_set_config_index(dev, confi, 1);
814 if (err) {
815 #ifdef USB_DEBUG
816 DPRINTF(("%s: port %d, set config at addr %d failed, "
817 "error=%s\n", device_get_nameunit(parent), port,
818 addr, usbd_errstr(err)));
819 #else
820 kprintf("%s: port %d, set config at addr %d failed\n",
821 device_get_nameunit(parent), port, addr);
822 #endif
823 kfree(devinfo, M_USB);
824 return (err);
826 nifaces = dev->cdesc->bNumInterface;
827 uaa.configno = dev->cdesc->bConfigurationValue;
828 for (i = 0; i < nifaces; i++)
829 ifaces[i] = &dev->ifaces[i];
830 uaa.ifaces = ifaces;
831 uaa.nifaces = nifaces;
832 dev->subdevs = kmalloc((nifaces+1) * sizeof(device_t), M_USB,
833 M_WAITOK);
834 dev->ifacenums = kmalloc((nifaces) * sizeof(*dev->ifacenums),
835 M_USB, M_WAITOK);
837 found = 0;
838 for (i = 0; i < nifaces; i++) {
839 if (ifaces[i] == NULL)
840 continue; /* interface already claimed */
841 uaa.iface = ifaces[i];
842 uaa.ifaceno = ifaces[i]->idesc->bInterfaceNumber;
843 dev->subdevs[found] = bdev;
844 dev->subdevs[found + 1] = 0;
845 dev->ifacenums[found] = i;
846 *uaap = uaa;
847 usbd_devinfo(dev, 1, devinfo);
848 device_set_desc_copy(bdev, devinfo);
849 if (device_probe_and_attach(bdev) == 0) {
850 ifaces[i] = 0; /* consumed */
851 found++;
853 /* create another child for the next iface */
854 bdev = device_add_child(parent, NULL, -1);
855 if (!bdev) {
856 device_printf(parent,
857 "Device add failed\n");
858 kfree(devinfo, M_USB);
859 return (USBD_NORMAL_COMPLETION);
861 uaap = kmalloc(sizeof(uaa), M_USB, M_WAITOK);
862 device_set_ivars(bdev, uaap);
863 } else {
864 dev->subdevs[found] = 0;
867 if (found != 0) {
868 /* remove the last created child. It is unused */
869 kfree(uaap, M_USB);
870 kfree(devinfo, M_USB);
871 device_delete_child(parent, bdev);
872 /* kfree(uaap, M_USB); */ /* May be needed? xxx */
873 return (USBD_NORMAL_COMPLETION);
875 tmpdv = dev->subdevs;
876 dev->subdevs = NULL;
877 kfree(tmpdv, M_USB);
878 kfree(dev->ifacenums, M_USB);
879 dev->ifacenums = NULL;
881 /* No interfaces were attached in any of the configurations. */
883 if (dd->bNumConfigurations > 1) /* don't change if only 1 config */
884 usbd_set_config_index(dev, 0, 0);
886 DPRINTF(("usbd_probe_and_attach: no interface drivers found\n"));
888 /* Finally try the generic driver. */
889 uaa.iface = NULL;
890 uaa.usegeneric = 1;
891 uaa.configno = UHUB_UNK_CONFIGURATION;
892 uaa.ifaceno = UHUB_UNK_INTERFACE;
893 dev->subdevs = kmalloc(2 * sizeof(device_t), M_USB, M_WAITOK);
894 dev->subdevs[0] = bdev;
895 dev->subdevs[1] = 0;
896 *uaap = uaa;
897 usbd_devinfo(dev, 1, devinfo);
898 device_set_desc_copy(bdev, devinfo);
899 kfree(devinfo, M_USB);
900 if (device_probe_and_attach(bdev) == 0)
901 return (USBD_NORMAL_COMPLETION);
904 * The generic attach failed, but leave the device as it is.
905 * We just did not find any drivers, that's all. The device is
906 * fully operational and not harming anyone.
908 DPRINTF(("usbd_probe_and_attach: generic attach failed\n"));
909 return (USBD_NORMAL_COMPLETION);
914 * Called when a new device has been put in the powered state,
915 * but not yet in the addressed state.
916 * Get initial descriptor, set the address, get full descriptor,
917 * and attach a driver.
919 usbd_status
920 usbd_new_device(device_t parent, usbd_bus_handle bus, int depth,
921 int speed, int port, struct usbd_port *up)
923 usbd_device_handle dev, adev;
924 struct usbd_device *hub;
925 usb_device_descriptor_t *dd;
926 usb_port_status_t ps;
927 usbd_status err;
928 int addr;
929 int i;
930 int p;
932 DPRINTF(("usbd_new_device bus=%p port=%d depth=%d speed=%d\n",
933 bus, port, depth, speed));
934 addr = usbd_getnewaddr(bus);
935 if (addr < 0) {
936 kprintf("%s: No free USB addresses, new device ignored.\n",
937 device_get_nameunit(bus->bdev));
938 return (USBD_NO_ADDR);
941 dev = kmalloc(sizeof *dev, M_USB, M_INTWAIT | M_ZERO);
942 dev->bus = bus;
944 /* Set up default endpoint handle. */
945 dev->def_ep.edesc = &dev->def_ep_desc;
947 /* Set up default endpoint descriptor. */
948 dev->def_ep_desc.bLength = USB_ENDPOINT_DESCRIPTOR_SIZE;
949 dev->def_ep_desc.bDescriptorType = UDESC_ENDPOINT;
950 dev->def_ep_desc.bEndpointAddress = USB_CONTROL_ENDPOINT;
951 dev->def_ep_desc.bmAttributes = UE_CONTROL;
952 USETW(dev->def_ep_desc.wMaxPacketSize, USB_MAX_IPACKET);
953 dev->def_ep_desc.bInterval = 0;
955 dev->quirks = &usbd_no_quirk;
956 dev->address = USB_START_ADDR;
957 dev->ddesc.bMaxPacketSize = 0;
958 dev->depth = depth;
959 dev->powersrc = up;
960 dev->myhub = up->parent;
962 up->device = dev;
964 /* Locate port on upstream high speed hub */
965 for (adev = dev, hub = up->parent;
966 hub != NULL && hub->speed != USB_SPEED_HIGH;
967 adev = hub, hub = hub->myhub)
969 if (hub) {
970 for (p = 0; p < hub->hub->hubdesc.bNbrPorts; p++) {
971 if (hub->hub->ports[p].device == adev) {
972 dev->myhsport = &hub->hub->ports[p];
973 goto found;
976 panic("usbd_new_device: cannot find HS port\n");
977 found:
978 DPRINTFN(1,("usbd_new_device: high speed port %d\n", p));
979 } else {
980 dev->myhsport = NULL;
982 dev->speed = speed;
983 dev->langid = USBD_NOLANG;
984 dev->cookie.cookie = ++usb_cookie_no;
986 /* Establish the default pipe. */
987 err = usbd_setup_pipe(dev, 0, &dev->def_ep, USBD_DEFAULT_INTERVAL,
988 &dev->default_pipe);
989 if (err) {
990 usbd_remove_device(dev, up);
991 return (err);
994 /* Set the address. Do this early; some devices need that. */
995 /* Try a few times in case the device is slow (i.e. outside specs.) */
996 DPRINTFN(5,("usbd_new_device: setting device address=%d\n", addr));
997 for (i = 0; i < 15; i++) {
998 err = usbd_set_address(dev, addr);
999 if (!err)
1000 break;
1001 usbd_delay_ms(dev, 200);
1002 if ((i & 3) == 3) {
1003 DPRINTFN(-1,("usb_new_device: set address %d "
1004 "failed - trying a port reset\n", addr));
1005 usbd_reset_port(up->parent, port, &ps);
1008 if (err) {
1009 DPRINTFN(-1,("usb_new_device: set address %d failed\n", addr));
1010 err = USBD_SET_ADDR_FAILED;
1011 usbd_remove_device(dev, up);
1012 return (err);
1014 /* Allow device time to set new address */
1015 usbd_delay_ms(dev, USB_SET_ADDRESS_SETTLE);
1016 dev->address = addr; /* New device address now */
1017 bus->devices[addr] = dev;
1019 dd = &dev->ddesc;
1020 /* Get the first 8 bytes of the device descriptor. */
1021 err = usbd_get_desc(dev, UDESC_DEVICE, 0, USB_MAX_IPACKET, dd);
1022 if (err) {
1023 DPRINTFN(-1, ("usbd_new_device: addr=%d, getting first desc "
1024 "failed\n", addr));
1025 usbd_remove_device(dev, up);
1026 return (err);
1029 if (speed == USB_SPEED_HIGH) {
1030 /* Max packet size must be 64 (sec 5.5.3). */
1031 if (dd->bMaxPacketSize != USB_2_MAX_CTRL_PACKET) {
1032 #ifdef DIAGNOSTIC
1033 kprintf("usbd_new_device: addr=%d bad max packet size\n",
1034 addr);
1035 #endif
1036 dd->bMaxPacketSize = USB_2_MAX_CTRL_PACKET;
1040 DPRINTF(("usbd_new_device: adding unit addr=%d, rev=%02x, class=%d, "
1041 "subclass=%d, protocol=%d, maxpacket=%d, len=%d, speed=%d\n",
1042 addr,UGETW(dd->bcdUSB), dd->bDeviceClass, dd->bDeviceSubClass,
1043 dd->bDeviceProtocol, dd->bMaxPacketSize, dd->bLength,
1044 dev->speed));
1046 if (dd->bDescriptorType != UDESC_DEVICE) {
1047 /* Illegal device descriptor */
1048 DPRINTFN(-1,("usbd_new_device: illegal descriptor %d\n",
1049 dd->bDescriptorType));
1050 usbd_remove_device(dev, up);
1051 return (USBD_INVAL);
1054 if (dd->bLength < USB_DEVICE_DESCRIPTOR_SIZE) {
1055 DPRINTFN(-1,("usbd_new_device: bad length %d\n", dd->bLength));
1056 usbd_remove_device(dev, up);
1057 return (USBD_INVAL);
1060 USETW(dev->def_ep_desc.wMaxPacketSize, dd->bMaxPacketSize);
1062 err = usbd_reload_device_desc(dev);
1063 if (err) {
1064 DPRINTFN(-1, ("usbd_new_device: addr=%d, getting full desc "
1065 "failed\n", addr));
1066 usbd_remove_device(dev, up);
1067 return (err);
1070 /* Assume 100mA bus powered for now. Changed when configured. */
1071 dev->power = USB_MIN_POWER;
1072 dev->self_powered = 0;
1074 DPRINTF(("usbd_new_device: new dev (addr %d), dev=%p, parent=%p\n",
1075 addr, dev, parent));
1077 err = usbd_probe_and_attach(parent, dev, port, addr);
1078 if (err) {
1079 usbd_remove_device(dev, up);
1080 return (err);
1083 usbd_add_dev_event(USB_EVENT_DEVICE_ATTACH, dev);
1085 return (USBD_NORMAL_COMPLETION);
1088 usbd_status
1089 usbd_reload_device_desc(usbd_device_handle dev)
1091 usbd_status err;
1092 int i;
1094 /* Get the full device descriptor. */
1095 for (i = 0; i < 3; ++i) {
1096 err = usbd_get_device_desc(dev, &dev->ddesc);
1097 if (!err)
1098 break;
1099 usbd_delay_ms(dev, 200);
1101 if (err)
1102 return (err);
1104 /* Figure out what's wrong with this device. */
1105 dev->quirks = usbd_find_quirk(&dev->ddesc);
1107 return (USBD_NORMAL_COMPLETION);
1110 void
1111 usbd_remove_device(usbd_device_handle dev, struct usbd_port *up)
1113 DPRINTF(("usbd_remove_device: %p\n", dev));
1115 if (dev->default_pipe != NULL)
1116 usbd_kill_pipe(dev->default_pipe);
1117 up->device = NULL;
1118 dev->bus->devices[dev->address] = NULL;
1120 kfree(dev, M_USB);
1123 void
1124 usbd_fill_deviceinfo(usbd_device_handle dev, struct usb_device_info *di,
1125 int usedev)
1127 struct usbd_port *p;
1128 int i, err, s;
1130 di->udi_bus = device_get_unit(dev->bus->bdev);
1131 di->udi_addr = dev->address;
1132 di->udi_cookie = dev->cookie;
1133 usbd_devinfo_vp(dev, di->udi_vendor, di->udi_product, usedev);
1134 usbd_printBCD(di->udi_release, UGETW(dev->ddesc.bcdDevice));
1135 di->udi_vendorNo = UGETW(dev->ddesc.idVendor);
1136 di->udi_productNo = UGETW(dev->ddesc.idProduct);
1137 di->udi_releaseNo = UGETW(dev->ddesc.bcdDevice);
1138 di->udi_class = dev->ddesc.bDeviceClass;
1139 di->udi_subclass = dev->ddesc.bDeviceSubClass;
1140 di->udi_protocol = dev->ddesc.bDeviceProtocol;
1141 di->udi_config = dev->config;
1142 di->udi_power = dev->self_powered ? 0 : dev->power;
1143 di->udi_speed = dev->speed;
1145 if (dev->subdevs != NULL) {
1146 for (i = 0; dev->subdevs[i] && i < USB_MAX_DEVNAMES; i++) {
1147 if (device_is_attached(dev->subdevs[i]))
1148 strlcpy(di->udi_devnames[i],
1149 device_get_nameunit(dev->subdevs[i]),
1150 USB_MAX_DEVNAMELEN);
1151 else
1152 di->udi_devnames[i][0] = 0;
1154 } else {
1155 i = 0;
1157 for (/*i is set */; i < USB_MAX_DEVNAMES; i++)
1158 di->udi_devnames[i][0] = 0; /* empty */
1160 if (dev->hub) {
1161 for (i = 0;
1162 i < sizeof(di->udi_ports) / sizeof(di->udi_ports[0]) &&
1163 i < dev->hub->hubdesc.bNbrPorts;
1164 i++) {
1165 p = &dev->hub->ports[i];
1166 if (p->device)
1167 err = p->device->address;
1168 else {
1169 s = UGETW(p->status.wPortStatus);
1170 if (s & UPS_PORT_ENABLED)
1171 err = USB_PORT_ENABLED;
1172 else if (s & UPS_SUSPEND)
1173 err = USB_PORT_SUSPENDED;
1174 else if (s & UPS_PORT_POWER)
1175 err = USB_PORT_POWERED;
1176 else
1177 err = USB_PORT_DISABLED;
1179 di->udi_ports[i] = err;
1181 di->udi_nports = dev->hub->hubdesc.bNbrPorts;
1182 } else
1183 di->udi_nports = 0;
1186 void
1187 usb_free_device(usbd_device_handle dev)
1189 int ifcidx, nifc;
1191 if (dev->default_pipe != NULL)
1192 usbd_kill_pipe(dev->default_pipe);
1193 if (dev->ifaces != NULL) {
1194 nifc = dev->cdesc->bNumInterface;
1195 for (ifcidx = 0; ifcidx < nifc; ifcidx++)
1196 usbd_free_iface_data(dev, ifcidx);
1197 kfree(dev->ifaces, M_USB);
1199 if (dev->cdesc != NULL)
1200 kfree(dev->cdesc, M_USB);
1201 if (dev->subdevs != NULL)
1202 kfree(dev->subdevs, M_USB);
1203 if (dev->ifacenums != NULL)
1204 kfree(dev->ifacenums, M_USB);
1205 kfree(dev, M_USB);
1209 * The general mechanism for detaching drivers works as follows: Each
1210 * driver is responsible for maintaining a reference count on the
1211 * number of outstanding references to its softc (e.g. from
1212 * processing hanging in a read or write). The detach method of the
1213 * driver decrements this counter and flags in the softc that the
1214 * driver is dying and then wakes any sleepers. It then sleeps on the
1215 * softc. Each place that can sleep must maintain the reference
1216 * count. When the reference count drops to -1 (0 is the normal value
1217 * of the reference count) the a wakeup on the softc is performed
1218 * signaling to the detach waiter that all references are gone.
1222 * Called from process context when we discover that a port has
1223 * been disconnected.
1225 void
1226 usb_disconnect_port(struct usbd_port *up, device_t parent)
1228 usbd_device_handle dev = up->device;
1229 const char *hubname = device_get_nameunit(parent);
1230 int i;
1232 DPRINTFN(3,("uhub_disconnect: up=%p dev=%p port=%d\n",
1233 up, dev, up->portno));
1235 #ifdef DIAGNOSTIC
1236 if (dev == NULL) {
1237 kprintf("usb_disconnect_port: no device\n");
1238 return;
1240 #endif
1242 if (dev->subdevs != NULL) {
1243 DPRINTFN(3,("usb_disconnect_port: disconnect subdevs\n"));
1244 for (i = 0; dev->subdevs[i]; i++) {
1245 kprintf("%s: at %s", device_get_nameunit(dev->subdevs[i]),
1246 hubname);
1247 if (up->portno != 0)
1248 kprintf(" port %d", up->portno);
1249 kprintf(" (addr %d) disconnected\n", dev->address);
1250 device_delete_child(device_get_parent(dev->subdevs[i]), dev->subdevs[i]);
1251 dev->subdevs[i] = NULL;
1255 usbd_add_dev_event(USB_EVENT_DEVICE_DETACH, dev);
1256 dev->bus->devices[dev->address] = NULL;
1257 up->device = NULL;
1258 usb_free_device(dev);