Nuke device_ptr_t, USBBASEDEVICE, USBDEVNAME(), USBDEVUNIT(), USBGETSOFTC(),
[dragonfly.git] / sys / bus / usb / usb_subr.c
blob43f549eba920dca95d167e5966287e79acde5f83
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.20 2007/06/28 06:32:31 hasso 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 "usbdevs.h"
68 #include <bus/usb/usb_quirks.h>
70 #define delay(d) DELAY(d)
72 #ifdef USB_DEBUG
73 #define DPRINTF(x) if (usbdebug) logprintf x
74 #define DPRINTFN(n,x) if (usbdebug>(n)) logprintf x
75 extern int usbdebug;
76 #else
77 #define DPRINTF(x)
78 #define DPRINTFN(n,x)
79 #endif
81 static usbd_status usbd_set_config(usbd_device_handle, int);
82 static void usbd_devinfo_vp(usbd_device_handle, char *, char *, int);
83 static int usbd_getnewaddr(usbd_bus_handle bus);
84 static void usbd_free_iface_data(usbd_device_handle dev, int ifcno);
85 static void usbd_kill_pipe(usbd_pipe_handle);
86 static usbd_status usbd_probe_and_attach(device_t parent,
87 usbd_device_handle dev, int port, int addr);
89 static u_int32_t usb_cookie_no = 0;
91 #ifdef USBVERBOSE
92 typedef u_int16_t usb_vendor_id_t;
93 typedef u_int16_t usb_product_id_t;
96 * Descriptions of of known vendors and devices ("products").
98 struct usb_knowndev {
99 usb_vendor_id_t vendor;
100 usb_product_id_t product;
101 int flags;
102 char *vendorname, *productname;
104 #define USB_KNOWNDEV_NOPROD 0x01 /* match on vendor only */
106 #include "usbdevs_data.h"
107 #endif /* USBVERBOSE */
109 static const char * const usbd_error_strs[] = {
110 "NORMAL_COMPLETION",
111 "IN_PROGRESS",
112 "PENDING_REQUESTS",
113 "NOT_STARTED",
114 "INVAL",
115 "NOMEM",
116 "CANCELLED",
117 "BAD_ADDRESS",
118 "IN_USE",
119 "NO_ADDR",
120 "SET_ADDR_FAILED",
121 "NO_POWER",
122 "TOO_DEEP",
123 "IOERROR",
124 "NOT_CONFIGURED",
125 "TIMEOUT",
126 "SHORT_XFER",
127 "STALLED",
128 "INTERRUPTED",
129 "XXX",
132 const char *
133 usbd_errstr(usbd_status err)
135 static char buffer[5];
137 if (err < USBD_ERROR_MAX) {
138 return usbd_error_strs[err];
139 } else {
140 ksnprintf(buffer, sizeof buffer, "%d", err);
141 return buffer;
145 usbd_status
146 usbd_get_string_desc(usbd_device_handle dev, int sindex, int langid,
147 usb_string_descriptor_t *sdesc, int *sizep)
149 usb_device_request_t req;
150 usbd_status err;
151 int actlen;
153 req.bmRequestType = UT_READ_DEVICE;
154 req.bRequest = UR_GET_DESCRIPTOR;
155 USETW2(req.wValue, UDESC_STRING, sindex);
156 USETW(req.wIndex, langid);
157 USETW(req.wLength, 2); /* only size byte first */
158 err = usbd_do_request_flags(dev, &req, sdesc, USBD_SHORT_XFER_OK,
159 &actlen, USBD_DEFAULT_TIMEOUT);
160 if (err)
161 return (err);
163 if (actlen < 2)
164 return (USBD_SHORT_XFER);
166 USETW(req.wLength, sdesc->bLength); /* the whole string */
167 err = usbd_do_request_flags(dev, &req, sdesc, USBD_SHORT_XFER_OK,
168 &actlen, USBD_DEFAULT_TIMEOUT);
169 if (err)
170 return (err);
172 if (actlen != sdesc->bLength) {
173 DPRINTFN(-1, ("usbd_get_string_desc: expected %d, got %d\n",
174 sdesc->bLength, actlen));
177 *sizep = actlen;
178 return (USBD_NORMAL_COMPLETION);
181 static void
182 usbd_trim_spaces(char *p)
184 char *q, *e;
186 if (p == NULL)
187 return;
188 q = e = p;
189 while (*q == ' ') /* skip leading spaces */
190 q++;
191 while ((*p = *q++)) /* copy string */
192 if (*p++ != ' ') /* remember last non-space */
193 e = p;
194 *e = 0; /* kill trailing spaces */
197 static void
198 usbd_devinfo_vp(usbd_device_handle dev, char *v, char *p, int usedev)
200 usb_device_descriptor_t *udd = &dev->ddesc;
201 char *vendor = 0, *product = 0;
202 #ifdef USBVERBOSE
203 const struct usb_knowndev *kdp;
204 #endif
206 if (dev == NULL) {
207 v[0] = p[0] = '\0';
208 return;
211 if (usedev) {
212 if (usbd_get_string(dev, udd->iManufacturer, v))
213 vendor = NULL;
214 else
215 vendor = v;
216 usbd_trim_spaces(vendor);
217 if (usbd_get_string(dev, udd->iProduct, p))
218 product = NULL;
219 else
220 product = p;
221 usbd_trim_spaces(product);
222 if (vendor && !*vendor)
223 vendor = NULL;
224 if (product && !*product)
225 product = NULL;
226 } else {
227 vendor = NULL;
228 product = NULL;
230 #ifdef USBVERBOSE
231 if (vendor == NULL || product == NULL) {
232 for(kdp = usb_knowndevs;
233 kdp->vendorname != NULL;
234 kdp++) {
235 if (kdp->vendor == UGETW(udd->idVendor) &&
236 (kdp->product == UGETW(udd->idProduct) ||
237 (kdp->flags & USB_KNOWNDEV_NOPROD) != 0))
238 break;
240 if (kdp->vendorname != NULL) {
241 if (vendor == NULL)
242 vendor = kdp->vendorname;
243 if (product == NULL)
244 product = (kdp->flags & USB_KNOWNDEV_NOPROD) == 0 ?
245 kdp->productname : NULL;
248 #endif
249 if (vendor != NULL && *vendor)
250 strcpy(v, vendor);
251 else
252 ksprintf(v, "vendor 0x%04x", UGETW(udd->idVendor));
253 if (product != NULL && *product)
254 strcpy(p, product);
255 else
256 ksprintf(p, "product 0x%04x", UGETW(udd->idProduct));
260 usbd_printBCD(char *cp, int bcd)
262 return (ksprintf(cp, "%x.%02x", bcd >> 8, bcd & 0xff));
265 void
266 usbd_devinfo(usbd_device_handle dev, int showclass, char *cp)
268 usb_device_descriptor_t *udd = &dev->ddesc;
269 usbd_interface_handle iface;
270 char vendor[USB_MAX_STRING_LEN];
271 char product[USB_MAX_STRING_LEN];
272 int bcdDevice, bcdUSB;
273 usb_interface_descriptor_t *id;
275 usbd_devinfo_vp(dev, vendor, product, 1);
276 cp += ksprintf(cp, "%s %s", vendor, product);
277 if (showclass & USBD_SHOW_DEVICE_CLASS)
278 cp += ksprintf(cp, ", class %d/%d",
279 udd->bDeviceClass, udd->bDeviceSubClass);
280 bcdUSB = UGETW(udd->bcdUSB);
281 bcdDevice = UGETW(udd->bcdDevice);
282 cp += ksprintf(cp, ", rev ");
283 cp += usbd_printBCD(cp, bcdUSB);
284 *cp++ = '/';
285 cp += usbd_printBCD(cp, bcdDevice);
286 cp += ksprintf(cp, ", addr %d", dev->address);
287 if (showclass & USBD_SHOW_INTERFACE_CLASS)
289 /* fetch the interface handle for the first interface */
290 (void)usbd_device2interface_handle(dev, 0, &iface);
291 id = usbd_get_interface_descriptor(iface);
292 cp += ksprintf(cp, ", iclass %d/%d",
293 id->bInterfaceClass, id->bInterfaceSubClass);
295 *cp = 0;
298 /* Delay for a certain number of ms */
299 void
300 usb_delay_ms(usbd_bus_handle bus, u_int ms)
302 /* Wait at least two clock ticks so we know the time has passed. */
303 if (bus->use_polling)
304 delay((ms+1) * 1000);
305 else
306 tsleep(&ms, 0, "usbdly", (ms*hz+999)/1000 + 1);
309 /* Delay given a device handle. */
310 void
311 usbd_delay_ms(usbd_device_handle dev, u_int ms)
313 usb_delay_ms(dev->bus, ms);
316 usbd_status
317 usbd_reset_port(usbd_device_handle dev, int port, usb_port_status_t *ps)
319 usb_device_request_t req;
320 usbd_status err;
321 int n;
323 req.bmRequestType = UT_WRITE_CLASS_OTHER;
324 req.bRequest = UR_SET_FEATURE;
325 USETW(req.wValue, UHF_PORT_RESET);
326 USETW(req.wIndex, port);
327 USETW(req.wLength, 0);
328 err = usbd_do_request(dev, &req, 0);
329 DPRINTFN(1,("usbd_reset_port: port %d reset done, error=%s\n",
330 port, usbd_errstr(err)));
331 if (err)
332 return (err);
333 n = 10;
334 do {
335 /* Wait for device to recover from reset. */
336 usbd_delay_ms(dev, USB_PORT_RESET_DELAY);
337 err = usbd_get_port_status(dev, port, ps);
338 if (err) {
339 DPRINTF(("usbd_reset_port: get status failed %d\n",
340 err));
341 return (err);
343 /* If the device disappeared, just give up. */
344 if (!(UGETW(ps->wPortStatus) & UPS_CURRENT_CONNECT_STATUS))
345 return (USBD_NORMAL_COMPLETION);
346 } while ((UGETW(ps->wPortChange) & UPS_C_PORT_RESET) == 0 && --n > 0);
347 if (n == 0)
348 return (USBD_TIMEOUT);
349 err = usbd_clear_port_feature(dev, port, UHF_C_PORT_RESET);
350 #ifdef USB_DEBUG
351 if (err)
352 DPRINTF(("usbd_reset_port: clear port feature failed %d\n",
353 err));
354 #endif
356 /* Wait for the device to recover from reset. */
357 usbd_delay_ms(dev, USB_PORT_RESET_RECOVERY);
358 return (err);
361 usb_interface_descriptor_t *
362 usbd_find_idesc(usb_config_descriptor_t *cd, int ifaceidx, int altidx)
364 char *p = (char *)cd;
365 char *end = p + UGETW(cd->wTotalLength);
366 usb_interface_descriptor_t *d;
367 int curidx, lastidx, curaidx = 0;
369 for (curidx = lastidx = -1; p < end; ) {
370 d = (usb_interface_descriptor_t *)p;
371 DPRINTFN(4,("usbd_find_idesc: idx=%d(%d) altidx=%d(%d) len=%d "
372 "type=%d\n",
373 ifaceidx, curidx, altidx, curaidx,
374 d->bLength, d->bDescriptorType));
375 if (d->bLength == 0) /* bad descriptor */
376 break;
377 p += d->bLength;
378 if (p <= end && d->bDescriptorType == UDESC_INTERFACE) {
379 if (d->bInterfaceNumber != lastidx) {
380 lastidx = d->bInterfaceNumber;
381 curidx++;
382 curaidx = 0;
383 } else
384 curaidx++;
385 if (ifaceidx == curidx && altidx == curaidx)
386 return (d);
389 return (NULL);
392 usb_endpoint_descriptor_t *
393 usbd_find_edesc(usb_config_descriptor_t *cd, int ifaceidx, int altidx,
394 int endptidx)
396 char *p = (char *)cd;
397 char *end = p + UGETW(cd->wTotalLength);
398 usb_interface_descriptor_t *d;
399 usb_endpoint_descriptor_t *e;
400 int curidx;
402 d = usbd_find_idesc(cd, ifaceidx, altidx);
403 if (d == NULL)
404 return (NULL);
405 if (endptidx >= d->bNumEndpoints) /* quick exit */
406 return (NULL);
408 curidx = -1;
409 for (p = (char *)d + d->bLength; p < end; ) {
410 e = (usb_endpoint_descriptor_t *)p;
411 if (e->bLength == 0) /* bad descriptor */
412 break;
413 p += e->bLength;
414 if (p <= end && e->bDescriptorType == UDESC_INTERFACE)
415 return (NULL);
416 if (p <= end && e->bDescriptorType == UDESC_ENDPOINT) {
417 curidx++;
418 if (curidx == endptidx)
419 return (e);
422 return (NULL);
425 usbd_status
426 usbd_fill_iface_data(usbd_device_handle dev, int ifaceidx, int altidx)
428 usbd_interface_handle ifc = &dev->ifaces[ifaceidx];
429 usb_interface_descriptor_t *idesc;
430 char *p, *end;
431 int endpt, nendpt;
433 DPRINTFN(4,("usbd_fill_iface_data: ifaceidx=%d altidx=%d\n",
434 ifaceidx, altidx));
435 idesc = usbd_find_idesc(dev->cdesc, ifaceidx, altidx);
436 if (idesc == NULL)
437 return (USBD_INVAL);
438 ifc->device = dev;
439 ifc->idesc = idesc;
440 ifc->index = ifaceidx;
441 ifc->altindex = altidx;
442 nendpt = ifc->idesc->bNumEndpoints;
443 DPRINTFN(4,("usbd_fill_iface_data: found idesc nendpt=%d\n", nendpt));
444 if (nendpt != 0) {
445 ifc->endpoints = kmalloc(nendpt * sizeof(struct usbd_endpoint),
446 M_USB, M_INTWAIT);
447 } else {
448 ifc->endpoints = NULL;
450 ifc->priv = NULL;
451 p = (char *)ifc->idesc + ifc->idesc->bLength;
452 end = (char *)dev->cdesc + UGETW(dev->cdesc->wTotalLength);
453 #define ed ((usb_endpoint_descriptor_t *)p)
454 for (endpt = 0; endpt < nendpt; endpt++) {
455 DPRINTFN(10,("usbd_fill_iface_data: endpt=%d\n", endpt));
456 for (; p < end; p += ed->bLength) {
457 DPRINTFN(10,("usbd_fill_iface_data: p=%p end=%p "
458 "len=%d type=%d\n",
459 p, end, ed->bLength, ed->bDescriptorType));
460 if (p + ed->bLength <= end && ed->bLength != 0 &&
461 ed->bDescriptorType == UDESC_ENDPOINT)
462 goto found;
463 if (ed->bLength == 0 ||
464 ed->bDescriptorType == UDESC_INTERFACE)
465 break;
467 /* passed end, or bad desc */
468 kprintf("usbd_fill_iface_data: bad descriptor(s): %s\n",
469 ed->bLength == 0 ? "0 length" :
470 ed->bDescriptorType == UDESC_INTERFACE ? "iface desc":
471 "out of data");
472 goto bad;
473 found:
474 ifc->endpoints[endpt].edesc = ed;
475 if (dev->speed == USB_SPEED_HIGH) {
476 u_int mps;
477 /* Control and bulk endpoints have max packet limits. */
478 switch (UE_GET_XFERTYPE(ed->bmAttributes)) {
479 case UE_CONTROL:
480 mps = USB_2_MAX_CTRL_PACKET;
481 goto check;
482 case UE_BULK:
483 mps = USB_2_MAX_BULK_PACKET;
484 check:
485 if (UGETW(ed->wMaxPacketSize) != mps) {
486 USETW(ed->wMaxPacketSize, mps);
487 #ifdef DIAGNOSTIC
488 kprintf("usbd_fill_iface_data: bad max "
489 "packet size\n");
490 #endif
492 break;
493 default:
494 break;
497 ifc->endpoints[endpt].refcnt = 0;
498 ifc->endpoints[endpt].savedtoggle = 0;
499 p += ed->bLength;
501 #undef ed
502 LIST_INIT(&ifc->pipes);
503 return (USBD_NORMAL_COMPLETION);
505 bad:
506 if (ifc->endpoints != NULL) {
507 kfree(ifc->endpoints, M_USB);
508 ifc->endpoints = NULL;
510 return (USBD_INVAL);
513 void
514 usbd_free_iface_data(usbd_device_handle dev, int ifcno)
516 usbd_interface_handle ifc = &dev->ifaces[ifcno];
517 if (ifc->endpoints)
518 kfree(ifc->endpoints, M_USB);
521 static usbd_status
522 usbd_set_config(usbd_device_handle dev, int conf)
524 usb_device_request_t req;
526 req.bmRequestType = UT_WRITE_DEVICE;
527 req.bRequest = UR_SET_CONFIG;
528 USETW(req.wValue, conf);
529 USETW(req.wIndex, 0);
530 USETW(req.wLength, 0);
531 return (usbd_do_request(dev, &req, 0));
534 usbd_status
535 usbd_set_config_no(usbd_device_handle dev, int no, int msg)
537 int index;
538 usb_config_descriptor_t cd;
539 usbd_status err;
541 if (no == USB_UNCONFIG_NO)
542 return (usbd_set_config_index(dev, USB_UNCONFIG_INDEX, msg));
544 DPRINTFN(5,("usbd_set_config_no: %d\n", no));
545 /* Figure out what config index to use. */
546 for (index = 0; index < dev->ddesc.bNumConfigurations; index++) {
547 err = usbd_get_config_desc(dev, index, &cd);
548 if (err)
549 return (err);
550 if (cd.bConfigurationValue == no)
551 return (usbd_set_config_index(dev, index, msg));
553 return (USBD_INVAL);
556 usbd_status
557 usbd_set_config_index(usbd_device_handle dev, int index, int msg)
559 usb_status_t ds;
560 usb_config_descriptor_t cd, *cdp;
561 usbd_status err;
562 int i, ifcidx, nifc, len, selfpowered, power;
564 DPRINTFN(5,("usbd_set_config_index: dev=%p index=%d\n", dev, index));
566 if (dev->config != USB_UNCONFIG_NO) {
567 nifc = dev->cdesc->bNumInterface;
569 /* Check that all interfaces are idle */
570 for (ifcidx = 0; ifcidx < nifc; ifcidx++) {
571 if (LIST_EMPTY(&dev->ifaces[ifcidx].pipes))
572 continue;
573 DPRINTF(("usbd_set_config_index: open pipes exist\n"));
574 return (USBD_IN_USE);
577 DPRINTF(("usbd_set_config_index: free old config\n"));
578 /* Free all configuration data structures. */
579 for (ifcidx = 0; ifcidx < nifc; ifcidx++)
580 usbd_free_iface_data(dev, ifcidx);
581 kfree(dev->ifaces, M_USB);
582 kfree(dev->cdesc, M_USB);
583 dev->ifaces = NULL;
584 dev->cdesc = NULL;
585 dev->config = USB_UNCONFIG_NO;
588 if (index == USB_UNCONFIG_INDEX) {
589 /* We are unconfiguring the device, so leave unallocated. */
590 DPRINTF(("usbd_set_config_index: set config 0\n"));
591 err = usbd_set_config(dev, USB_UNCONFIG_NO);
592 if (err)
593 DPRINTF(("usbd_set_config_index: setting config=0 "
594 "failed, error=%s\n", usbd_errstr(err)));
595 return (err);
598 /* Get the short descriptor. */
599 err = usbd_get_config_desc(dev, index, &cd);
600 if (err)
601 return (err);
602 len = UGETW(cd.wTotalLength);
603 cdp = kmalloc(len, M_USB, M_INTWAIT);
604 /* Get the full descriptor. Try a few times for slow devices. */
605 for (i = 0; i < 3; i++) {
606 err = usbd_get_desc(dev, UDESC_CONFIG, index, len, cdp);
607 if (!err)
608 break;
609 usbd_delay_ms(dev, 200);
611 if (err)
612 goto bad;
613 if (cdp->bDescriptorType != UDESC_CONFIG) {
614 DPRINTFN(-1,("usbd_set_config_index: bad desc %d\n",
615 cdp->bDescriptorType));
616 err = USBD_INVAL;
617 goto bad;
620 /* Figure out if the device is self or bus powered. */
621 selfpowered = 0;
622 if (!(dev->quirks->uq_flags & UQ_BUS_POWERED) &&
623 (cdp->bmAttributes & UC_SELF_POWERED)) {
624 /* May be self powered. */
625 if (cdp->bmAttributes & UC_BUS_POWERED) {
626 /* Must ask device. */
627 if (dev->quirks->uq_flags & UQ_POWER_CLAIM) {
629 * Hub claims to be self powered, but isn't.
630 * It seems that the power status can be
631 * determined by the hub characteristics.
633 usb_hub_descriptor_t hd;
634 usb_device_request_t req;
635 req.bmRequestType = UT_READ_CLASS_DEVICE;
636 req.bRequest = UR_GET_DESCRIPTOR;
637 USETW(req.wValue, 0);
638 USETW(req.wIndex, 0);
639 USETW(req.wLength, USB_HUB_DESCRIPTOR_SIZE);
640 err = usbd_do_request(dev, &req, &hd);
641 if (!err &&
642 (UGETW(hd.wHubCharacteristics) &
643 UHD_PWR_INDIVIDUAL))
644 selfpowered = 1;
645 DPRINTF(("usbd_set_config_index: charac=0x%04x"
646 ", error=%s\n",
647 UGETW(hd.wHubCharacteristics),
648 usbd_errstr(err)));
649 } else {
650 err = usbd_get_device_status(dev, &ds);
651 if (!err &&
652 (UGETW(ds.wStatus) & UDS_SELF_POWERED))
653 selfpowered = 1;
654 DPRINTF(("usbd_set_config_index: status=0x%04x"
655 ", error=%s\n",
656 UGETW(ds.wStatus), usbd_errstr(err)));
658 } else
659 selfpowered = 1;
661 DPRINTF(("usbd_set_config_index: (addr %d) cno=%d attr=0x%02x, "
662 "selfpowered=%d, power=%d\n",
663 cdp->bConfigurationValue, dev->address, cdp->bmAttributes,
664 selfpowered, cdp->bMaxPower * 2));
666 /* Check if we have enough power. */
667 #ifdef USB_DEBUG
668 if (dev->powersrc == NULL) {
669 DPRINTF(("usbd_set_config_index: No power source?\n"));
670 return (USBD_IOERROR);
672 #endif
673 power = cdp->bMaxPower * 2;
674 if (power > dev->powersrc->power) {
675 DPRINTF(("power exceeded %d %d\n", power,dev->powersrc->power));
676 /* XXX print nicer message. */
677 if (msg)
678 kprintf("%s: device addr %d (config %d) exceeds power "
679 "budget, %d mA > %d mA\n",
680 device_get_nameunit(dev->bus->bdev), dev->address,
681 cdp->bConfigurationValue,
682 power, dev->powersrc->power);
683 err = USBD_NO_POWER;
684 goto bad;
686 dev->power = power;
687 dev->self_powered = selfpowered;
689 /* Set the actual configuration value. */
690 DPRINTF(("usbd_set_config_index: set config %d\n",
691 cdp->bConfigurationValue));
692 err = usbd_set_config(dev, cdp->bConfigurationValue);
693 if (err) {
694 DPRINTF(("usbd_set_config_index: setting config=%d failed, "
695 "error=%s\n",
696 cdp->bConfigurationValue, usbd_errstr(err)));
697 goto bad;
700 /* Allocate and fill interface data. */
701 nifc = cdp->bNumInterface;
702 dev->ifaces = kmalloc(nifc * sizeof(struct usbd_interface),
703 M_USB, M_INTWAIT);
704 DPRINTFN(5,("usbd_set_config_index: dev=%p cdesc=%p\n", dev, cdp));
705 dev->cdesc = cdp;
706 dev->config = cdp->bConfigurationValue;
707 for (ifcidx = 0; ifcidx < nifc; ifcidx++) {
708 err = usbd_fill_iface_data(dev, ifcidx, 0);
709 if (err) {
710 while (--ifcidx >= 0)
711 usbd_free_iface_data(dev, ifcidx);
712 goto bad;
716 return (USBD_NORMAL_COMPLETION);
718 bad:
719 kfree(cdp, M_USB);
720 return (err);
723 /* XXX add function for alternate settings */
725 usbd_status
726 usbd_setup_pipe(usbd_device_handle dev, usbd_interface_handle iface,
727 struct usbd_endpoint *ep, int ival, usbd_pipe_handle *pipe)
729 usbd_pipe_handle p;
730 usbd_status err;
732 DPRINTFN(1,("usbd_setup_pipe: dev=%p iface=%p ep=%p pipe=%p\n",
733 dev, iface, ep, pipe));
734 p = kmalloc(dev->bus->pipe_size, M_USB, M_INTWAIT);
735 p->device = dev;
736 p->iface = iface;
737 p->endpoint = ep;
738 ep->refcnt++;
739 p->refcnt = 1;
740 p->intrxfer = 0;
741 p->running = 0;
742 p->aborting = 0;
743 p->repeat = 0;
744 p->interval = ival;
745 SIMPLEQ_INIT(&p->queue);
746 err = dev->bus->methods->open_pipe(p);
747 if (err) {
748 DPRINTFN(-1,("usbd_setup_pipe: endpoint=0x%x failed, error="
749 "%s\n",
750 ep->edesc->bEndpointAddress, usbd_errstr(err)));
751 kfree(p, M_USB);
752 return (err);
755 *pipe = p;
756 return (USBD_NORMAL_COMPLETION);
759 /* Abort the device control pipe. */
760 void
761 usbd_kill_pipe(usbd_pipe_handle pipe)
763 usbd_abort_pipe(pipe);
764 pipe->methods->close(pipe);
765 pipe->endpoint->refcnt--;
766 kfree(pipe, M_USB);
770 usbd_getnewaddr(usbd_bus_handle bus)
772 int addr;
774 for (addr = 1; addr < USB_MAX_DEVICES; addr++)
775 if (bus->devices[addr] == 0)
776 return (addr);
777 return (-1);
781 usbd_status
782 usbd_probe_and_attach(device_t parent, usbd_device_handle dev,
783 int port, int addr)
785 struct usb_attach_arg uaa;
786 usb_device_descriptor_t *dd = &dev->ddesc;
787 int found, i, confi, nifaces;
788 usbd_status err;
789 device_t dv;
790 device_t *tmpdv;
791 usbd_interface_handle ifaces[256]; /* 256 is the absolute max */
793 /* XXX FreeBSD may leak resources on failure cases -- fixme */
794 device_t bdev;
795 struct usb_attach_arg *uaap;
797 bdev = device_add_child(parent, NULL, -1);
798 if (!bdev) {
799 device_printf(parent, "Device creation failed\n");
800 return (USBD_INVAL);
802 device_quiet(bdev);
803 uaap = kmalloc(sizeof(uaa), M_USB, M_WAITOK);
804 device_set_ivars(bdev, uaap);
805 uaa.device = dev;
806 uaa.iface = NULL;
807 uaa.ifaces = NULL;
808 uaa.nifaces = 0;
809 uaa.usegeneric = 0;
810 uaa.port = port;
811 uaa.configno = UHUB_UNK_CONFIGURATION;
812 uaa.ifaceno = UHUB_UNK_INTERFACE;
813 uaa.vendor = UGETW(dd->idVendor);
814 uaa.product = UGETW(dd->idProduct);
815 uaa.release = UGETW(dd->bcdDevice);
817 /* First try with device specific drivers. */
818 DPRINTF(("usbd_probe_and_attach: trying device specific drivers\n"));
820 dev->ifacenums = NULL;
821 dev->subdevs = kmalloc(2 * sizeof dv, M_USB, M_WAITOK);
822 dev->subdevs[0] = bdev;
823 dev->subdevs[1] = 0;
824 *uaap = uaa;
825 dv = USB_DO_ATTACH(dev, bdev, parent, &uaa, usbd_print, usbd_submatch);
826 if (dv) {
827 return (USBD_NORMAL_COMPLETION);
830 * Free subdevs so we can reallocate it larger for the number of
831 * interfaces
833 tmpdv = dev->subdevs;
834 dev->subdevs = NULL;
835 kfree(tmpdv, M_USB);
836 DPRINTF(("usbd_probe_and_attach: no device specific driver found\n"));
838 DPRINTF(("usbd_probe_and_attach: looping over %d configurations\n",
839 dd->bNumConfigurations));
840 /* Next try with interface drivers. */
841 for (confi = 0; confi < dd->bNumConfigurations; confi++) {
842 DPRINTFN(1,("usbd_probe_and_attach: trying config idx=%d\n",
843 confi));
844 err = usbd_set_config_index(dev, confi, 1);
845 if (err) {
846 #ifdef USB_DEBUG
847 DPRINTF(("%s: port %d, set config at addr %d failed, "
848 "error=%s\n", device_get_nameunit(parent), port,
849 addr, usbd_errstr(err)));
850 #else
851 kprintf("%s: port %d, set config at addr %d failed\n",
852 device_get_nameunit(parent), port, addr);
853 #endif
854 return (err);
856 nifaces = dev->cdesc->bNumInterface;
857 uaa.configno = dev->cdesc->bConfigurationValue;
858 for (i = 0; i < nifaces; i++)
859 ifaces[i] = &dev->ifaces[i];
860 uaa.ifaces = ifaces;
861 uaa.nifaces = nifaces;
862 dev->subdevs = kmalloc((nifaces+1) * sizeof dv, M_USB,
863 M_WAITOK);
864 dev->ifacenums = kmalloc((nifaces) * sizeof(*dev->ifacenums),
865 M_USB, M_WAITOK);
867 found = 0;
868 for (i = 0; i < nifaces; i++) {
869 if (ifaces[i] == NULL)
870 continue; /* interface already claimed */
871 uaa.iface = ifaces[i];
872 uaa.ifaceno = ifaces[i]->idesc->bInterfaceNumber;
873 dev->subdevs[found] = bdev;
874 dev->subdevs[found + 1] = 0;
875 dev->ifacenums[found] = i;
876 *uaap = uaa;
877 dv = USB_DO_ATTACH(dev, bdev, parent, &uaa, usbd_print,
878 usbd_submatch);
879 if (dv != NULL) {
880 ifaces[i] = 0; /* consumed */
881 found++;
883 /* create another child for the next iface */
884 bdev = device_add_child(parent, NULL, -1);
885 if (!bdev) {
886 device_printf(parent,
887 "Device add failed\n");
888 return (USBD_NORMAL_COMPLETION);
890 uaap = kmalloc(sizeof(uaa), M_USB, M_WAITOK);
891 device_set_ivars(bdev, uaap);
892 device_quiet(bdev);
893 } else {
894 dev->subdevs[found] = 0;
897 if (found != 0) {
898 /* remove the last created child. It is unused */
899 device_delete_child(parent, bdev);
900 /* kfree(uaap, M_USB); */ /* May be needed? xxx */
901 return (USBD_NORMAL_COMPLETION);
903 tmpdv = dev->subdevs;
904 dev->subdevs = NULL;
905 kfree(tmpdv, M_USB);
906 kfree(dev->ifacenums, M_USB);
907 dev->ifacenums = NULL;
909 /* No interfaces were attached in any of the configurations. */
911 if (dd->bNumConfigurations > 1) /* don't change if only 1 config */
912 usbd_set_config_index(dev, 0, 0);
914 DPRINTF(("usbd_probe_and_attach: no interface drivers found\n"));
916 /* Finally try the generic driver. */
917 uaa.iface = NULL;
918 uaa.usegeneric = 1;
919 uaa.configno = UHUB_UNK_CONFIGURATION;
920 uaa.ifaceno = UHUB_UNK_INTERFACE;
921 dev->subdevs = kmalloc(2 * sizeof dv, M_USB, M_WAITOK);
922 dev->subdevs[0] = bdev;
923 dev->subdevs[1] = 0;
924 *uaap = uaa;
925 dv = USB_DO_ATTACH(dev, bdev, parent, &uaa, usbd_print, usbd_submatch);
926 if (dv != NULL) {
927 return (USBD_NORMAL_COMPLETION);
931 * The generic attach failed, but leave the device as it is.
932 * We just did not find any drivers, that's all. The device is
933 * fully operational and not harming anyone.
935 DPRINTF(("usbd_probe_and_attach: generic attach failed\n"));
936 return (USBD_NORMAL_COMPLETION);
941 * Called when a new device has been put in the powered state,
942 * but not yet in the addressed state.
943 * Get initial descriptor, set the address, get full descriptor,
944 * and attach a driver.
946 usbd_status
947 usbd_new_device(device_t parent, usbd_bus_handle bus, int depth,
948 int speed, int port, struct usbd_port *up)
950 usbd_device_handle dev, adev;
951 struct usbd_device *hub;
952 usb_device_descriptor_t *dd;
953 usb_port_status_t ps;
954 usbd_status err;
955 int addr;
956 int i;
957 int p;
959 DPRINTF(("usbd_new_device bus=%p port=%d depth=%d speed=%d\n",
960 bus, port, depth, speed));
961 addr = usbd_getnewaddr(bus);
962 if (addr < 0) {
963 kprintf("%s: No free USB addresses, new device ignored.\n",
964 device_get_nameunit(bus->bdev));
965 return (USBD_NO_ADDR);
968 dev = kmalloc(sizeof *dev, M_USB, M_INTWAIT | M_ZERO);
969 dev->bus = bus;
971 /* Set up default endpoint handle. */
972 dev->def_ep.edesc = &dev->def_ep_desc;
974 /* Set up default endpoint descriptor. */
975 dev->def_ep_desc.bLength = USB_ENDPOINT_DESCRIPTOR_SIZE;
976 dev->def_ep_desc.bDescriptorType = UDESC_ENDPOINT;
977 dev->def_ep_desc.bEndpointAddress = USB_CONTROL_ENDPOINT;
978 dev->def_ep_desc.bmAttributes = UE_CONTROL;
979 USETW(dev->def_ep_desc.wMaxPacketSize, USB_MAX_IPACKET);
980 dev->def_ep_desc.bInterval = 0;
982 dev->quirks = &usbd_no_quirk;
983 dev->address = USB_START_ADDR;
984 dev->ddesc.bMaxPacketSize = 0;
985 dev->depth = depth;
986 dev->powersrc = up;
987 dev->myhub = up->parent;
989 up->device = dev;
991 /* Locate port on upstream high speed hub */
992 for (adev = dev, hub = up->parent;
993 hub != NULL && hub->speed != USB_SPEED_HIGH;
994 adev = hub, hub = hub->myhub)
996 if (hub) {
997 for (p = 0; p < hub->hub->hubdesc.bNbrPorts; p++) {
998 if (hub->hub->ports[p].device == adev) {
999 dev->myhsport = &hub->hub->ports[p];
1000 goto found;
1003 panic("usbd_new_device: cannot find HS port\n");
1004 found:
1005 DPRINTFN(1,("usbd_new_device: high speed port %d\n", p));
1006 } else {
1007 dev->myhsport = NULL;
1009 dev->speed = speed;
1010 dev->langid = USBD_NOLANG;
1011 dev->cookie.cookie = ++usb_cookie_no;
1013 /* Establish the default pipe. */
1014 err = usbd_setup_pipe(dev, 0, &dev->def_ep, USBD_DEFAULT_INTERVAL,
1015 &dev->default_pipe);
1016 if (err) {
1017 usbd_remove_device(dev, up);
1018 return (err);
1021 /* Set the address. Do this early; some devices need that. */
1022 /* Try a few times in case the device is slow (i.e. outside specs.) */
1023 DPRINTFN(5,("usbd_new_device: setting device address=%d\n", addr));
1024 for (i = 0; i < 15; i++) {
1025 err = usbd_set_address(dev, addr);
1026 if (!err)
1027 break;
1028 usbd_delay_ms(dev, 200);
1029 if ((i & 3) == 3) {
1030 DPRINTFN(-1,("usb_new_device: set address %d "
1031 "failed - trying a port reset\n", addr));
1032 usbd_reset_port(up->parent, port, &ps);
1035 if (err) {
1036 DPRINTFN(-1,("usb_new_device: set address %d failed\n", addr));
1037 err = USBD_SET_ADDR_FAILED;
1038 usbd_remove_device(dev, up);
1039 return (err);
1041 /* Allow device time to set new address */
1042 usbd_delay_ms(dev, USB_SET_ADDRESS_SETTLE);
1043 dev->address = addr; /* New device address now */
1044 bus->devices[addr] = dev;
1046 dd = &dev->ddesc;
1047 /* Get the first 8 bytes of the device descriptor. */
1048 err = usbd_get_desc(dev, UDESC_DEVICE, 0, USB_MAX_IPACKET, dd);
1049 if (err) {
1050 DPRINTFN(-1, ("usbd_new_device: addr=%d, getting first desc "
1051 "failed\n", addr));
1052 usbd_remove_device(dev, up);
1053 return (err);
1056 if (speed == USB_SPEED_HIGH) {
1057 /* Max packet size must be 64 (sec 5.5.3). */
1058 if (dd->bMaxPacketSize != USB_2_MAX_CTRL_PACKET) {
1059 #ifdef DIAGNOSTIC
1060 kprintf("usbd_new_device: addr=%d bad max packet size\n",
1061 addr);
1062 #endif
1063 dd->bMaxPacketSize = USB_2_MAX_CTRL_PACKET;
1067 DPRINTF(("usbd_new_device: adding unit addr=%d, rev=%02x, class=%d, "
1068 "subclass=%d, protocol=%d, maxpacket=%d, len=%d, speed=%d\n",
1069 addr,UGETW(dd->bcdUSB), dd->bDeviceClass, dd->bDeviceSubClass,
1070 dd->bDeviceProtocol, dd->bMaxPacketSize, dd->bLength,
1071 dev->speed));
1073 if (dd->bDescriptorType != UDESC_DEVICE) {
1074 /* Illegal device descriptor */
1075 DPRINTFN(-1,("usbd_new_device: illegal descriptor %d\n",
1076 dd->bDescriptorType));
1077 usbd_remove_device(dev, up);
1078 return (USBD_INVAL);
1081 if (dd->bLength < USB_DEVICE_DESCRIPTOR_SIZE) {
1082 DPRINTFN(-1,("usbd_new_device: bad length %d\n", dd->bLength));
1083 usbd_remove_device(dev, up);
1084 return (USBD_INVAL);
1087 USETW(dev->def_ep_desc.wMaxPacketSize, dd->bMaxPacketSize);
1089 err = usbd_reload_device_desc(dev);
1090 if (err) {
1091 DPRINTFN(-1, ("usbd_new_device: addr=%d, getting full desc "
1092 "failed\n", addr));
1093 usbd_remove_device(dev, up);
1094 return (err);
1097 /* Assume 100mA bus powered for now. Changed when configured. */
1098 dev->power = USB_MIN_POWER;
1099 dev->self_powered = 0;
1101 DPRINTF(("usbd_new_device: new dev (addr %d), dev=%p, parent=%p\n",
1102 addr, dev, parent));
1104 err = usbd_probe_and_attach(parent, dev, port, addr);
1105 if (err) {
1106 usbd_remove_device(dev, up);
1107 return (err);
1110 usbd_add_dev_event(USB_EVENT_DEVICE_ATTACH, dev);
1112 return (USBD_NORMAL_COMPLETION);
1115 usbd_status
1116 usbd_reload_device_desc(usbd_device_handle dev)
1118 usbd_status err;
1119 int i;
1121 /* Get the full device descriptor. */
1122 for (i = 0; i < 3; ++i) {
1123 err = usbd_get_device_desc(dev, &dev->ddesc);
1124 if (!err)
1125 break;
1126 usbd_delay_ms(dev, 200);
1128 if (err)
1129 return (err);
1131 /* Figure out what's wrong with this device. */
1132 dev->quirks = usbd_find_quirk(&dev->ddesc);
1134 return (USBD_NORMAL_COMPLETION);
1137 void
1138 usbd_remove_device(usbd_device_handle dev, struct usbd_port *up)
1140 DPRINTF(("usbd_remove_device: %p\n", dev));
1142 if (dev->default_pipe != NULL)
1143 usbd_kill_pipe(dev->default_pipe);
1144 up->device = NULL;
1145 dev->bus->devices[dev->address] = NULL;
1147 kfree(dev, M_USB);
1150 void
1151 usbd_fill_deviceinfo(usbd_device_handle dev, struct usb_device_info *di,
1152 int usedev)
1154 struct usbd_port *p;
1155 int i, err, s;
1157 di->udi_bus = device_get_unit(dev->bus->bdev);
1158 di->udi_addr = dev->address;
1159 di->udi_cookie = dev->cookie;
1160 usbd_devinfo_vp(dev, di->udi_vendor, di->udi_product, usedev);
1161 usbd_printBCD(di->udi_release, UGETW(dev->ddesc.bcdDevice));
1162 di->udi_vendorNo = UGETW(dev->ddesc.idVendor);
1163 di->udi_productNo = UGETW(dev->ddesc.idProduct);
1164 di->udi_releaseNo = UGETW(dev->ddesc.bcdDevice);
1165 di->udi_class = dev->ddesc.bDeviceClass;
1166 di->udi_subclass = dev->ddesc.bDeviceSubClass;
1167 di->udi_protocol = dev->ddesc.bDeviceProtocol;
1168 di->udi_config = dev->config;
1169 di->udi_power = dev->self_powered ? 0 : dev->power;
1170 di->udi_speed = dev->speed;
1172 if (dev->subdevs != NULL) {
1173 for (i = 0; dev->subdevs[i] && i < USB_MAX_DEVNAMES; i++) {
1174 if (device_is_attached(dev->subdevs[i]))
1175 strlcpy(di->udi_devnames[i],
1176 device_get_nameunit(dev->subdevs[i]),
1177 USB_MAX_DEVNAMELEN);
1178 else
1179 di->udi_devnames[i][0] = 0;
1181 } else {
1182 i = 0;
1184 for (/*i is set */; i < USB_MAX_DEVNAMES; i++)
1185 di->udi_devnames[i][0] = 0; /* empty */
1187 if (dev->hub) {
1188 for (i = 0;
1189 i < sizeof(di->udi_ports) / sizeof(di->udi_ports[0]) &&
1190 i < dev->hub->hubdesc.bNbrPorts;
1191 i++) {
1192 p = &dev->hub->ports[i];
1193 if (p->device)
1194 err = p->device->address;
1195 else {
1196 s = UGETW(p->status.wPortStatus);
1197 if (s & UPS_PORT_ENABLED)
1198 err = USB_PORT_ENABLED;
1199 else if (s & UPS_SUSPEND)
1200 err = USB_PORT_SUSPENDED;
1201 else if (s & UPS_PORT_POWER)
1202 err = USB_PORT_POWERED;
1203 else
1204 err = USB_PORT_DISABLED;
1206 di->udi_ports[i] = err;
1208 di->udi_nports = dev->hub->hubdesc.bNbrPorts;
1209 } else
1210 di->udi_nports = 0;
1213 void
1214 usb_free_device(usbd_device_handle dev)
1216 int ifcidx, nifc;
1218 if (dev->default_pipe != NULL)
1219 usbd_kill_pipe(dev->default_pipe);
1220 if (dev->ifaces != NULL) {
1221 nifc = dev->cdesc->bNumInterface;
1222 for (ifcidx = 0; ifcidx < nifc; ifcidx++)
1223 usbd_free_iface_data(dev, ifcidx);
1224 kfree(dev->ifaces, M_USB);
1226 if (dev->cdesc != NULL)
1227 kfree(dev->cdesc, M_USB);
1228 if (dev->subdevs != NULL)
1229 kfree(dev->subdevs, M_USB);
1230 if (dev->ifacenums != NULL)
1231 kfree(dev->ifacenums, M_USB);
1232 kfree(dev, M_USB);
1236 * The general mechanism for detaching drivers works as follows: Each
1237 * driver is responsible for maintaining a reference count on the
1238 * number of outstanding references to its softc (e.g. from
1239 * processing hanging in a read or write). The detach method of the
1240 * driver decrements this counter and flags in the softc that the
1241 * driver is dying and then wakes any sleepers. It then sleeps on the
1242 * softc. Each place that can sleep must maintain the reference
1243 * count. When the reference count drops to -1 (0 is the normal value
1244 * of the reference count) the a wakeup on the softc is performed
1245 * signaling to the detach waiter that all references are gone.
1249 * Called from process context when we discover that a port has
1250 * been disconnected.
1252 void
1253 usb_disconnect_port(struct usbd_port *up, device_t parent)
1255 usbd_device_handle dev = up->device;
1256 const char *hubname = device_get_nameunit(parent);
1257 int i;
1259 DPRINTFN(3,("uhub_disconnect: up=%p dev=%p port=%d\n",
1260 up, dev, up->portno));
1262 #ifdef DIAGNOSTIC
1263 if (dev == NULL) {
1264 kprintf("usb_disconnect_port: no device\n");
1265 return;
1267 #endif
1269 if (dev->subdevs != NULL) {
1270 DPRINTFN(3,("usb_disconnect_port: disconnect subdevs\n"));
1271 for (i = 0; dev->subdevs[i]; i++) {
1272 kprintf("%s: at %s", device_get_nameunit(dev->subdevs[i]),
1273 hubname);
1274 if (up->portno != 0)
1275 kprintf(" port %d", up->portno);
1276 kprintf(" (addr %d) disconnected\n", dev->address);
1277 config_detach(dev->subdevs[i], DETACH_FORCE);
1278 dev->subdevs[i] = NULL;
1282 usbd_add_dev_event(USB_EVENT_DEVICE_DETACH, dev);
1283 dev->bus->devices[dev->address] = NULL;
1284 up->device = NULL;
1285 usb_free_device(dev);