xref: /netbsd-src/sys/dev/usb/usb_subr.c (revision cac8e449158efc7261bebc8657cbb0125a2cfdde)
1 /*	$NetBSD: usb_subr.c,v 1.160 2008/07/28 15:22:01 drochner Exp $	*/
2 /*	$FreeBSD: src/sys/dev/usb/usb_subr.c,v 1.18 1999/11/17 22:33:47 n_hibma Exp $	*/
3 
4 /*
5  * Copyright (c) 1998, 2004 The NetBSD Foundation, Inc.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by Lennart Augustsson (lennart@augustsson.net) at
10  * Carlstedt Research & Technology.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
23  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
25  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #include <sys/cdefs.h>
35 __KERNEL_RCSID(0, "$NetBSD: usb_subr.c,v 1.160 2008/07/28 15:22:01 drochner Exp $");
36 
37 #include "opt_compat_netbsd.h"
38 #include "opt_usbverbose.h"
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/kernel.h>
43 #include <sys/malloc.h>
44 #include <sys/device.h>
45 #include <sys/select.h>
46 #include <sys/proc.h>
47 
48 #include <sys/bus.h>
49 
50 #include <dev/usb/usb.h>
51 
52 #include <dev/usb/usbdi.h>
53 #include <dev/usb/usbdi_util.h>
54 #include <dev/usb/usbdivar.h>
55 #include <dev/usb/usbdevs.h>
56 #include <dev/usb/usb_quirks.h>
57 
58 #include "locators.h"
59 
60 #ifdef USB_DEBUG
61 #define DPRINTF(x)	if (usbdebug) logprintf x
62 #define DPRINTFN(n,x)	if (usbdebug>(n)) logprintf x
63 extern int usbdebug;
64 #else
65 #define DPRINTF(x)
66 #define DPRINTFN(n,x)
67 #endif
68 
69 Static usbd_status usbd_set_config(usbd_device_handle, int);
70 Static void usbd_devinfo(usbd_device_handle, int, char *, size_t);
71 Static void usbd_devinfo_vp(usbd_device_handle dev,
72 			    char *v,
73 			    char *p, int usedev,
74 			    int useencoded );
75 Static int usbd_getnewaddr(usbd_bus_handle bus);
76 Static int usbd_print(void *, const char *);
77 Static int usbd_ifprint(void *, const char *);
78 Static void usbd_free_iface_data(usbd_device_handle dev, int ifcno);
79 Static void usbd_kill_pipe(usbd_pipe_handle);
80 usbd_status usbd_attach_roothub(device_t, usbd_device_handle);
81 Static usbd_status usbd_probe_and_attach(device_ptr_t parent,
82 				 usbd_device_handle dev, int port, int addr);
83 
84 Static u_int32_t usb_cookie_no = 0;
85 
86 #ifdef USBVERBOSE
87 typedef u_int16_t usb_vendor_id_t;
88 typedef u_int16_t usb_product_id_t;
89 
90 /*
91  * Descriptions of of known vendors and devices ("products").
92  */
93 struct usb_vendor {
94 	usb_vendor_id_t		vendor;
95 	const char		*vendorname;
96 };
97 struct usb_product {
98 	usb_vendor_id_t		vendor;
99 	usb_product_id_t	product;
100 	const char		*productname;
101 };
102 
103 #include <dev/usb/usbdevs_data.h>
104 #endif /* USBVERBOSE */
105 
106 Static const char * const usbd_error_strs[] = {
107 	"NORMAL_COMPLETION",
108 	"IN_PROGRESS",
109 	"PENDING_REQUESTS",
110 	"NOT_STARTED",
111 	"INVAL",
112 	"NOMEM",
113 	"CANCELLED",
114 	"BAD_ADDRESS",
115 	"IN_USE",
116 	"NO_ADDR",
117 	"SET_ADDR_FAILED",
118 	"NO_POWER",
119 	"TOO_DEEP",
120 	"IOERROR",
121 	"NOT_CONFIGURED",
122 	"TIMEOUT",
123 	"SHORT_XFER",
124 	"STALLED",
125 	"INTERRUPTED",
126 	"XXX",
127 };
128 
129 const char *
130 usbd_errstr(usbd_status err)
131 {
132 	static char buffer[5];
133 
134 	if (err < USBD_ERROR_MAX) {
135 		return usbd_error_strs[err];
136 	} else {
137 		snprintf(buffer, sizeof buffer, "%d", err);
138 		return buffer;
139 	}
140 }
141 
142 usbd_status
143 usbd_get_string_desc(usbd_device_handle dev, int sindex, int langid,
144 		     usb_string_descriptor_t *sdesc, int *sizep)
145 {
146 	usb_device_request_t req;
147 	usbd_status err;
148 	int actlen;
149 
150 	req.bmRequestType = UT_READ_DEVICE;
151 	req.bRequest = UR_GET_DESCRIPTOR;
152 	USETW2(req.wValue, UDESC_STRING, sindex);
153 	USETW(req.wIndex, langid);
154 	USETW(req.wLength, 2);	/* only size byte first */
155 	err = usbd_do_request_flags(dev, &req, sdesc, USBD_SHORT_XFER_OK,
156 		&actlen, USBD_DEFAULT_TIMEOUT);
157 	if (err)
158 		return (err);
159 
160 	if (actlen < 2)
161 		return (USBD_SHORT_XFER);
162 
163 	USETW(req.wLength, sdesc->bLength);	/* the whole string */
164  	err = usbd_do_request_flags(dev, &req, sdesc, USBD_SHORT_XFER_OK,
165  		&actlen, USBD_DEFAULT_TIMEOUT);
166 	if (err)
167 		return (err);
168 
169 	if (actlen != sdesc->bLength) {
170 		DPRINTFN(-1, ("usbd_get_string_desc: expected %d, got %d\n",
171 		    sdesc->bLength, actlen));
172 	}
173 
174 	*sizep = actlen;
175 	return (USBD_NORMAL_COMPLETION);
176 }
177 
178 static void
179 usbd_trim_spaces(char *p)
180 {
181 	char *q, *e;
182 
183 	q = e = p;
184 	while (*q == ' ')		/* skip leading spaces */
185 		q++;
186 	while ((*p = *q++))		/* copy string */
187 		if (*p++ != ' ')	/* remember last non-space */
188 			e = p;
189 	*e = '\0';			/* kill trailing spaces */
190 }
191 
192 Static void
193 usbd_devinfo_vp(usbd_device_handle dev, char *v,
194 		char *p, int usedev, int useencoded)
195 {
196 	usb_device_descriptor_t *udd = &dev->ddesc;
197 #ifdef USBVERBOSE
198 	int n;
199 #endif
200 
201 	v[0] = p[0] = '\0';
202 	if (dev == NULL)
203 		return;
204 
205 	if (usedev) {
206 		if (usbd_get_string0(dev, udd->iManufacturer, v, useencoded) ==
207 		    USBD_NORMAL_COMPLETION)
208 			usbd_trim_spaces(v);
209 		if (usbd_get_string0(dev, udd->iProduct, p, useencoded) ==
210 		    USBD_NORMAL_COMPLETION)
211 			usbd_trim_spaces(p);
212 	}
213 	/* There is no need for strlcpy & snprintf below. */
214 #ifdef USBVERBOSE
215 	if (v[0] == '\0')
216 		for (n = 0; n < usb_nvendors; n++)
217 			if (usb_vendors[n].vendor == UGETW(udd->idVendor)) {
218 				strcpy(v, usb_vendors[n].vendorname);
219 				break;
220 			}
221 	if (p[0] == '\0')
222 		for (n = 0; n < usb_nproducts; n++)
223 			if (usb_products[n].vendor == UGETW(udd->idVendor) &&
224 			    usb_products[n].product == UGETW(udd->idProduct)) {
225 				strcpy(p, usb_products[n].productname);
226 				break;
227 			}
228 #endif
229 	if (v[0] == '\0')
230 		sprintf(v, "vendor 0x%04x", UGETW(udd->idVendor));
231 	if (p[0] == '\0')
232 		sprintf(p, "product 0x%04x", UGETW(udd->idProduct));
233 }
234 
235 int
236 usbd_printBCD(char *cp, size_t l, int bcd)
237 {
238 	return (snprintf(cp, l, "%x.%02x", bcd >> 8, bcd & 0xff));
239 }
240 
241 Static void
242 usbd_devinfo(usbd_device_handle dev, int showclass, char *cp, size_t l)
243 {
244 	usb_device_descriptor_t *udd = &dev->ddesc;
245 	char *vendor, *product;
246 	int bcdDevice, bcdUSB;
247 	char *ep;
248 
249 	vendor = malloc(USB_MAX_ENCODED_STRING_LEN * 2, M_USB, M_NOWAIT);
250 	if (vendor == NULL) {
251 		*cp = '\0';
252 		return;
253 	}
254 	product = &vendor[USB_MAX_ENCODED_STRING_LEN];
255 
256 	ep = cp + l;
257 
258 	usbd_devinfo_vp(dev, vendor, product, 1, 1);
259 	cp += snprintf(cp, ep - cp, "%s %s", vendor, product);
260 	if (showclass)
261 		cp += snprintf(cp, ep - cp, ", class %d/%d",
262 		    udd->bDeviceClass, udd->bDeviceSubClass);
263 	bcdUSB = UGETW(udd->bcdUSB);
264 	bcdDevice = UGETW(udd->bcdDevice);
265 	cp += snprintf(cp, ep - cp, ", rev ");
266 	cp += usbd_printBCD(cp, ep - cp, bcdUSB);
267 	*cp++ = '/';
268 	cp += usbd_printBCD(cp, ep - cp, bcdDevice);
269 	cp += snprintf(cp, ep - cp, ", addr %d", dev->address);
270 	*cp = 0;
271 	free(vendor, M_USB);
272 }
273 
274 char *
275 usbd_devinfo_alloc(usbd_device_handle dev, int showclass)
276 {
277 	char *devinfop;
278 
279 	devinfop = malloc(DEVINFOSIZE, M_TEMP, M_WAITOK);
280 	usbd_devinfo(dev, showclass, devinfop, DEVINFOSIZE);
281 	return devinfop;
282 }
283 
284 void
285 usbd_devinfo_free(char *devinfop)
286 {
287 	free(devinfop, M_TEMP);
288 }
289 
290 /* Delay for a certain number of ms */
291 void
292 usb_delay_ms(usbd_bus_handle bus, u_int ms)
293 {
294 	/* Wait at least two clock ticks so we know the time has passed. */
295 	if (bus->use_polling || cold)
296 		delay((ms+1) * 1000);
297 	else
298 		tsleep(&ms, PRIBIO, "usbdly", (ms*hz+999)/1000 + 1);
299 }
300 
301 /* Delay given a device handle. */
302 void
303 usbd_delay_ms(usbd_device_handle dev, u_int ms)
304 {
305 	usb_delay_ms(dev->bus, ms);
306 }
307 
308 usbd_status
309 usbd_reset_port(usbd_device_handle dev, int port, usb_port_status_t *ps)
310 {
311 	usb_device_request_t req;
312 	usbd_status err;
313 	int n;
314 
315 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
316 	req.bRequest = UR_SET_FEATURE;
317 	USETW(req.wValue, UHF_PORT_RESET);
318 	USETW(req.wIndex, port);
319 	USETW(req.wLength, 0);
320 	err = usbd_do_request(dev, &req, 0);
321 	DPRINTFN(1,("usbd_reset_port: port %d reset done, error=%s\n",
322 		    port, usbd_errstr(err)));
323 	if (err)
324 		return (err);
325 	n = 10;
326 	do {
327 		/* Wait for device to recover from reset. */
328 		usbd_delay_ms(dev, USB_PORT_RESET_DELAY);
329 		err = usbd_get_port_status(dev, port, ps);
330 		if (err) {
331 			DPRINTF(("usbd_reset_port: get status failed %d\n",
332 				 err));
333 			return (err);
334 		}
335 		/* If the device disappeared, just give up. */
336 		if (!(UGETW(ps->wPortStatus) & UPS_CURRENT_CONNECT_STATUS))
337 			return (USBD_NORMAL_COMPLETION);
338 	} while ((UGETW(ps->wPortChange) & UPS_C_PORT_RESET) == 0 && --n > 0);
339 	if (n == 0)
340 		return (USBD_TIMEOUT);
341 	err = usbd_clear_port_feature(dev, port, UHF_C_PORT_RESET);
342 #ifdef USB_DEBUG
343 	if (err)
344 		DPRINTF(("usbd_reset_port: clear port feature failed %d\n",
345 			 err));
346 #endif
347 
348 	/* Wait for the device to recover from reset. */
349 	usbd_delay_ms(dev, USB_PORT_RESET_RECOVERY);
350 	return (err);
351 }
352 
353 usb_interface_descriptor_t *
354 usbd_find_idesc(usb_config_descriptor_t *cd, int ifaceidx, int altidx)
355 {
356 	char *p = (char *)cd;
357 	char *end = p + UGETW(cd->wTotalLength);
358 	usb_interface_descriptor_t *d;
359 	int curidx, lastidx, curaidx = 0;
360 
361 	for (curidx = lastidx = -1; p < end; ) {
362 		d = (usb_interface_descriptor_t *)p;
363 		DPRINTFN(4,("usbd_find_idesc: idx=%d(%d) altidx=%d(%d) len=%d "
364 			    "type=%d\n",
365 			    ifaceidx, curidx, altidx, curaidx,
366 			    d->bLength, d->bDescriptorType));
367 		if (d->bLength == 0) /* bad descriptor */
368 			break;
369 		p += d->bLength;
370 		if (p <= end && d->bDescriptorType == UDESC_INTERFACE) {
371 			if (d->bInterfaceNumber != lastidx) {
372 				lastidx = d->bInterfaceNumber;
373 				curidx++;
374 				curaidx = 0;
375 			} else
376 				curaidx++;
377 			if (ifaceidx == curidx && altidx == curaidx)
378 				return (d);
379 		}
380 	}
381 	return (NULL);
382 }
383 
384 usb_endpoint_descriptor_t *
385 usbd_find_edesc(usb_config_descriptor_t *cd, int ifaceidx, int altidx,
386 		int endptidx)
387 {
388 	char *p = (char *)cd;
389 	char *end = p + UGETW(cd->wTotalLength);
390 	usb_interface_descriptor_t *d;
391 	usb_endpoint_descriptor_t *e;
392 	int curidx;
393 
394 	d = usbd_find_idesc(cd, ifaceidx, altidx);
395 	if (d == NULL)
396 		return (NULL);
397 	if (endptidx >= d->bNumEndpoints) /* quick exit */
398 		return (NULL);
399 
400 	curidx = -1;
401 	for (p = (char *)d + d->bLength; p < end; ) {
402 		e = (usb_endpoint_descriptor_t *)p;
403 		if (e->bLength == 0) /* bad descriptor */
404 			break;
405 		p += e->bLength;
406 		if (p <= end && e->bDescriptorType == UDESC_INTERFACE)
407 			return (NULL);
408 		if (p <= end && e->bDescriptorType == UDESC_ENDPOINT) {
409 			curidx++;
410 			if (curidx == endptidx)
411 				return (e);
412 		}
413 	}
414 	return (NULL);
415 }
416 
417 usbd_status
418 usbd_fill_iface_data(usbd_device_handle dev, int ifaceidx, int altidx)
419 {
420 	usbd_interface_handle ifc = &dev->ifaces[ifaceidx];
421 	usb_interface_descriptor_t *idesc;
422 	char *p, *end;
423 	int endpt, nendpt;
424 
425 	DPRINTFN(4,("usbd_fill_iface_data: ifaceidx=%d altidx=%d\n",
426 		    ifaceidx, altidx));
427 	idesc = usbd_find_idesc(dev->cdesc, ifaceidx, altidx);
428 	if (idesc == NULL)
429 		return (USBD_INVAL);
430 	ifc->device = dev;
431 	ifc->idesc = idesc;
432 	ifc->index = ifaceidx;
433 	ifc->altindex = altidx;
434 	nendpt = ifc->idesc->bNumEndpoints;
435 	DPRINTFN(4,("usbd_fill_iface_data: found idesc nendpt=%d\n", nendpt));
436 	if (nendpt != 0) {
437 		ifc->endpoints = malloc(nendpt * sizeof(struct usbd_endpoint),
438 					M_USB, M_NOWAIT);
439 		if (ifc->endpoints == NULL)
440 			return (USBD_NOMEM);
441 	} else
442 		ifc->endpoints = NULL;
443 	ifc->priv = NULL;
444 	p = (char *)ifc->idesc + ifc->idesc->bLength;
445 	end = (char *)dev->cdesc + UGETW(dev->cdesc->wTotalLength);
446 #define ed ((usb_endpoint_descriptor_t *)p)
447 	for (endpt = 0; endpt < nendpt; endpt++) {
448 		DPRINTFN(10,("usbd_fill_iface_data: endpt=%d\n", endpt));
449 		for (; p < end; p += ed->bLength) {
450 			DPRINTFN(10,("usbd_fill_iface_data: p=%p end=%p "
451 				     "len=%d type=%d\n",
452 				 p, end, ed->bLength, ed->bDescriptorType));
453 			if (p + ed->bLength <= end && ed->bLength != 0 &&
454 			    ed->bDescriptorType == UDESC_ENDPOINT)
455 				goto found;
456 			if (ed->bLength == 0 ||
457 			    ed->bDescriptorType == UDESC_INTERFACE)
458 				break;
459 		}
460 		/* passed end, or bad desc */
461 		printf("usbd_fill_iface_data: bad descriptor(s): %s\n",
462 		       ed->bLength == 0 ? "0 length" :
463 		       ed->bDescriptorType == UDESC_INTERFACE ? "iface desc":
464 		       "out of data");
465 		goto bad;
466 	found:
467 		ifc->endpoints[endpt].edesc = ed;
468 		if (dev->speed == USB_SPEED_HIGH) {
469 			u_int mps;
470 			/* Control and bulk endpoints have max packet limits. */
471 			switch (UE_GET_XFERTYPE(ed->bmAttributes)) {
472 			case UE_CONTROL:
473 				mps = USB_2_MAX_CTRL_PACKET;
474 				goto check;
475 			case UE_BULK:
476 				mps = USB_2_MAX_BULK_PACKET;
477 			check:
478 				if (UGETW(ed->wMaxPacketSize) != mps) {
479 					USETW(ed->wMaxPacketSize, mps);
480 #ifdef DIAGNOSTIC
481 					printf("usbd_fill_iface_data: bad max "
482 					       "packet size\n");
483 #endif
484 				}
485 				break;
486 			default:
487 				break;
488 			}
489 		}
490 		ifc->endpoints[endpt].refcnt = 0;
491 		p += ed->bLength;
492 	}
493 #undef ed
494 	LIST_INIT(&ifc->pipes);
495 	return (USBD_NORMAL_COMPLETION);
496 
497  bad:
498 	if (ifc->endpoints != NULL) {
499 		free(ifc->endpoints, M_USB);
500 		ifc->endpoints = NULL;
501 	}
502 	return (USBD_INVAL);
503 }
504 
505 void
506 usbd_free_iface_data(usbd_device_handle dev, int ifcno)
507 {
508 	usbd_interface_handle ifc = &dev->ifaces[ifcno];
509 	if (ifc->endpoints)
510 		free(ifc->endpoints, M_USB);
511 }
512 
513 Static usbd_status
514 usbd_set_config(usbd_device_handle dev, int conf)
515 {
516 	usb_device_request_t req;
517 
518 	req.bmRequestType = UT_WRITE_DEVICE;
519 	req.bRequest = UR_SET_CONFIG;
520 	USETW(req.wValue, conf);
521 	USETW(req.wIndex, 0);
522 	USETW(req.wLength, 0);
523 	return (usbd_do_request(dev, &req, 0));
524 }
525 
526 usbd_status
527 usbd_set_config_no(usbd_device_handle dev, int no, int msg)
528 {
529 	int index;
530 	usb_config_descriptor_t cd;
531 	usbd_status err;
532 
533 	if (no == USB_UNCONFIG_NO)
534 		return (usbd_set_config_index(dev, USB_UNCONFIG_INDEX, msg));
535 
536 	DPRINTFN(5,("usbd_set_config_no: %d\n", no));
537 	/* Figure out what config index to use. */
538 	for (index = 0; index < dev->ddesc.bNumConfigurations; index++) {
539 		err = usbd_get_config_desc(dev, index, &cd);
540 		if (err)
541 			return (err);
542 		if (cd.bConfigurationValue == no)
543 			return (usbd_set_config_index(dev, index, msg));
544 	}
545 	return (USBD_INVAL);
546 }
547 
548 usbd_status
549 usbd_set_config_index(usbd_device_handle dev, int index, int msg)
550 {
551 	usb_config_descriptor_t cd, *cdp;
552 	usbd_status err;
553 	int i, ifcidx, nifc, len, selfpowered, power;
554 
555 	DPRINTFN(5,("usbd_set_config_index: dev=%p index=%d\n", dev, index));
556 
557 	if (index >= dev->ddesc.bNumConfigurations &&
558 	    index != USB_UNCONFIG_NO) {
559 		/* panic? */
560 		printf("usbd_set_config_index: illegal index\n");
561 		return (USBD_INVAL);
562 	}
563 
564 	/* XXX check that all interfaces are idle */
565 	if (dev->config != USB_UNCONFIG_NO) {
566 		DPRINTF(("usbd_set_config_index: free old config\n"));
567 		/* Free all configuration data structures. */
568 		nifc = dev->cdesc->bNumInterface;
569 		for (ifcidx = 0; ifcidx < nifc; ifcidx++)
570 			usbd_free_iface_data(dev, ifcidx);
571 		free(dev->ifaces, M_USB);
572 		free(dev->cdesc, M_USB);
573 		dev->ifaces = NULL;
574 		dev->cdesc = NULL;
575 		dev->config = USB_UNCONFIG_NO;
576 	}
577 
578 	if (index == USB_UNCONFIG_INDEX) {
579 		/* We are unconfiguring the device, so leave unallocated. */
580 		DPRINTF(("usbd_set_config_index: set config 0\n"));
581 		err = usbd_set_config(dev, USB_UNCONFIG_NO);
582 		if (err) {
583 			DPRINTF(("usbd_set_config_index: setting config=0 "
584 				 "failed, error=%s\n", usbd_errstr(err)));
585 		}
586 		return (err);
587 	}
588 
589 	/* Get the short descriptor. */
590 	err = usbd_get_config_desc(dev, index, &cd);
591 	if (err)
592 		return (err);
593 	len = UGETW(cd.wTotalLength);
594 	cdp = malloc(len, M_USB, M_NOWAIT);
595 	if (cdp == NULL)
596 		return (USBD_NOMEM);
597 
598 	/* Get the full descriptor.  Try a few times for slow devices. */
599 	for (i = 0; i < 3; i++) {
600 		err = usbd_get_desc(dev, UDESC_CONFIG, index, len, cdp);
601 		if (!err)
602 			break;
603 		usbd_delay_ms(dev, 200);
604 	}
605 	if (err)
606 		goto bad;
607 
608 	if (cdp->bDescriptorType != UDESC_CONFIG) {
609 		DPRINTFN(-1,("usbd_set_config_index: bad desc %d\n",
610 			     cdp->bDescriptorType));
611 		err = USBD_INVAL;
612 		goto bad;
613 	}
614 
615 	/*
616 	 * Figure out if the device is self or bus powered.
617 	 */
618 #if 0 /* XXX various devices don't report the power state correctly */
619 	selfpowered = 0;
620 	err = usbd_get_device_status(dev, &ds);
621 	if (!err && (UGETW(ds.wStatus) & UDS_SELF_POWERED))
622 		selfpowered = 1;
623 #endif
624 	/*
625 	 * Use the power state in the configuration we are going
626 	 * to set. This doesn't necessarily reflect the actual
627 	 * power state of the device; the driver can control this
628 	 * by choosing the appropriate configuration.
629 	 */
630 	selfpowered = !!(cdp->bmAttributes & UC_SELF_POWERED);
631 
632 	DPRINTF(("usbd_set_config_index: (addr %d) cno=%d attr=0x%02x, "
633 		 "selfpowered=%d, power=%d\n",
634 		 cdp->bConfigurationValue, dev->address, cdp->bmAttributes,
635 		 selfpowered, cdp->bMaxPower * 2));
636 
637 	/* Check if we have enough power. */
638 #if 0 /* this is a no-op, see above */
639 	if ((cdp->bmAttributes & UC_SELF_POWERED) && !selfpowered) {
640 		if (msg)
641 			printf("%s: device addr %d (config %d): "
642 				 "can't set self powered configuration\n",
643 			       USBDEVNAME(dev->bus->bdev), dev->address,
644 			       cdp->bConfigurationValue);
645 		err = USBD_NO_POWER;
646 		goto bad;
647 	}
648 #endif
649 #ifdef USB_DEBUG
650 	if (dev->powersrc == NULL) {
651 		DPRINTF(("usbd_set_config_index: No power source?\n"));
652 		err = USBD_IOERROR;
653 		goto bad;
654 	}
655 #endif
656 	power = cdp->bMaxPower * 2;
657 	if (power > dev->powersrc->power) {
658 		DPRINTF(("power exceeded %d %d\n", power,dev->powersrc->power));
659 		/* XXX print nicer message. */
660 		if (msg)
661 			printf("%s: device addr %d (config %d) exceeds power "
662 				 "budget, %d mA > %d mA\n",
663 			       device_xname(dev->bus->usbctl), dev->address,
664 			       cdp->bConfigurationValue,
665 			       power, dev->powersrc->power);
666 		err = USBD_NO_POWER;
667 		goto bad;
668 	}
669 	dev->power = power;
670 	dev->self_powered = selfpowered;
671 
672 	/* Set the actual configuration value. */
673 	DPRINTF(("usbd_set_config_index: set config %d\n",
674 		 cdp->bConfigurationValue));
675 	err = usbd_set_config(dev, cdp->bConfigurationValue);
676 	if (err) {
677 		DPRINTF(("usbd_set_config_index: setting config=%d failed, "
678 			 "error=%s\n",
679 			 cdp->bConfigurationValue, usbd_errstr(err)));
680 		goto bad;
681 	}
682 
683 	/* Allocate and fill interface data. */
684 	nifc = cdp->bNumInterface;
685 	dev->ifaces = malloc(nifc * sizeof(struct usbd_interface),
686 			     M_USB, M_NOWAIT);
687 	if (dev->ifaces == NULL) {
688 		err = USBD_NOMEM;
689 		goto bad;
690 	}
691 	DPRINTFN(5,("usbd_set_config_index: dev=%p cdesc=%p\n", dev, cdp));
692 	dev->cdesc = cdp;
693 	dev->config = cdp->bConfigurationValue;
694 	for (ifcidx = 0; ifcidx < nifc; ifcidx++) {
695 		err = usbd_fill_iface_data(dev, ifcidx, 0);
696 		if (err) {
697 			while (--ifcidx >= 0)
698 				usbd_free_iface_data(dev, ifcidx);
699 			goto bad;
700 		}
701 	}
702 
703 	return (USBD_NORMAL_COMPLETION);
704 
705  bad:
706 	free(cdp, M_USB);
707 	return (err);
708 }
709 
710 /* XXX add function for alternate settings */
711 
712 usbd_status
713 usbd_setup_pipe(usbd_device_handle dev, usbd_interface_handle iface,
714 		struct usbd_endpoint *ep, int ival, usbd_pipe_handle *pipe)
715 {
716 	usbd_pipe_handle p;
717 	usbd_status err;
718 
719 	DPRINTFN(1,("usbd_setup_pipe: dev=%p iface=%p ep=%p pipe=%p\n",
720 		    dev, iface, ep, pipe));
721 	p = malloc(dev->bus->pipe_size, M_USB, M_NOWAIT);
722 	if (p == NULL)
723 		return (USBD_NOMEM);
724 	p->device = dev;
725 	p->iface = iface;
726 	p->endpoint = ep;
727 	ep->refcnt++;
728 	p->refcnt = 1;
729 	p->intrxfer = 0;
730 	p->running = 0;
731 	p->aborting = 0;
732 	p->repeat = 0;
733 	p->interval = ival;
734 	SIMPLEQ_INIT(&p->queue);
735 	err = dev->bus->methods->open_pipe(p);
736 	if (err) {
737 		DPRINTFN(-1,("usbd_setup_pipe: endpoint=0x%x failed, error="
738 			 "%s\n",
739 			 ep->edesc->bEndpointAddress, usbd_errstr(err)));
740 		free(p, M_USB);
741 		return (err);
742 	}
743 	*pipe = p;
744 	return (USBD_NORMAL_COMPLETION);
745 }
746 
747 /* Abort the device control pipe. */
748 void
749 usbd_kill_pipe(usbd_pipe_handle pipe)
750 {
751 	usbd_abort_pipe(pipe);
752 	pipe->methods->close(pipe);
753 	pipe->endpoint->refcnt--;
754 	free(pipe, M_USB);
755 }
756 
757 int
758 usbd_getnewaddr(usbd_bus_handle bus)
759 {
760 	int addr;
761 
762 	for (addr = 1; addr < USB_MAX_DEVICES; addr++)
763 		if (bus->devices[addr] == 0)
764 			return (addr);
765 	return (-1);
766 }
767 
768 usbd_status
769 usbd_attach_roothub(device_t parent, usbd_device_handle dev)
770 {
771 	struct usb_attach_arg uaa;
772 	usb_device_descriptor_t *dd = &dev->ddesc;
773 	device_t dv;
774 
775 	uaa.device = dev;
776 	uaa.usegeneric = 0;
777 	uaa.port = 0;
778 	uaa.vendor = UGETW(dd->idVendor);
779 	uaa.product = UGETW(dd->idProduct);
780 	uaa.release = UGETW(dd->bcdDevice);
781 	uaa.class = dd->bDeviceClass;
782 	uaa.subclass = dd->bDeviceSubClass;
783 	uaa.proto = dd->bDeviceProtocol;
784 
785 	dv = config_found_ia(parent, "usbroothubif", &uaa, 0);
786 	if (dv) {
787 		dev->subdevs = malloc(sizeof dv, M_USB, M_NOWAIT);
788 		if (dev->subdevs == NULL)
789 			return (USBD_NOMEM);
790 		dev->subdevs[0] = dv;
791 		dev->subdevlen = 1;
792 	}
793 	return (USBD_NORMAL_COMPLETION);
794 }
795 
796 static usbd_status
797 usbd_attachwholedevice(device_t parent, usbd_device_handle dev, int port,
798 	int usegeneric)
799 {
800 	struct usb_attach_arg uaa;
801 	usb_device_descriptor_t *dd = &dev->ddesc;
802 	device_t dv;
803 	int dlocs[USBDEVIFCF_NLOCS];
804 
805 	uaa.device = dev;
806 	uaa.usegeneric = usegeneric;
807 	uaa.port = port;
808 	uaa.vendor = UGETW(dd->idVendor);
809 	uaa.product = UGETW(dd->idProduct);
810 	uaa.release = UGETW(dd->bcdDevice);
811 	uaa.class = dd->bDeviceClass;
812 	uaa.subclass = dd->bDeviceSubClass;
813 	uaa.proto = dd->bDeviceProtocol;
814 
815 	dlocs[USBDEVIFCF_PORT] = uaa.port;
816 	dlocs[USBDEVIFCF_VENDOR] = uaa.vendor;
817 	dlocs[USBDEVIFCF_PRODUCT] = uaa.product;
818 	dlocs[USBDEVIFCF_RELEASE] = uaa.release;
819 	/* the rest is historical ballast */
820 	dlocs[USBDEVIFCF_CONFIGURATION] = -1;
821 	dlocs[USBDEVIFCF_INTERFACE] = -1;
822 
823 	dv = config_found_sm_loc(parent, "usbdevif", dlocs, &uaa, usbd_print,
824 				 config_stdsubmatch);
825 	if (dv) {
826 		dev->subdevs = malloc(sizeof dv, M_USB, M_NOWAIT);
827 		if (dev->subdevs == NULL)
828 			return (USBD_NOMEM);
829 		dev->subdevs[0] = dv;
830 		dev->subdevlen = 1;
831 		dev->nifaces_claimed = 1; /* XXX */
832 	}
833 	return (USBD_NORMAL_COMPLETION);
834 }
835 
836 static usbd_status
837 usbd_attachinterfaces(device_t parent, usbd_device_handle dev, int port)
838 {
839 	struct usbif_attach_arg uiaa;
840 	usb_device_descriptor_t *dd = &dev->ddesc;
841 	int nifaces;
842 	usbd_interface_handle *ifaces;
843 	int i, j;
844 	device_t dv;
845 	int ilocs[USBIFIFCF_NLOCS];
846 
847 	nifaces = dev->cdesc->bNumInterface;
848 	ifaces = malloc(nifaces * sizeof(*ifaces), M_USB, M_NOWAIT|M_ZERO);
849 	if (!ifaces)
850 		return (USBD_NOMEM);
851 	for (i = 0; i < nifaces; i++)
852 		if (!dev->subdevs[i])
853 			ifaces[i] = &dev->ifaces[i];
854 
855 	uiaa.device = dev;
856 	uiaa.port = port;
857 	uiaa.vendor = UGETW(dd->idVendor);
858 	uiaa.product = UGETW(dd->idProduct);
859 	uiaa.release = UGETW(dd->bcdDevice);
860 	uiaa.configno = dev->cdesc->bConfigurationValue;
861 	uiaa.ifaces = ifaces;
862 	uiaa.nifaces = nifaces;
863 	ilocs[USBIFIFCF_PORT] = uiaa.port;
864 	ilocs[USBIFIFCF_VENDOR] = uiaa.vendor;
865 	ilocs[USBIFIFCF_PRODUCT] = uiaa.product;
866 	ilocs[USBIFIFCF_RELEASE] = uiaa.release;
867 	ilocs[USBIFIFCF_CONFIGURATION] = uiaa.configno;
868 
869 	for (i = 0; i < nifaces; i++) {
870 		if (!ifaces[i])
871 			continue; /* interface already claimed */
872 		uiaa.iface = ifaces[i];
873 		uiaa.class = ifaces[i]->idesc->bInterfaceClass;
874 		uiaa.subclass = ifaces[i]->idesc->bInterfaceSubClass;
875 		uiaa.proto = ifaces[i]->idesc->bInterfaceProtocol;
876 		uiaa.ifaceno = ifaces[i]->idesc->bInterfaceNumber;
877 		ilocs[USBIFIFCF_INTERFACE] = uiaa.ifaceno;
878 		dv = config_found_sm_loc(parent, "usbifif", ilocs, &uiaa,
879 					 usbd_ifprint, config_stdsubmatch);
880 		if (!dv)
881 			continue;
882 		ifaces[i] = 0; /* claim */
883 		/* account for ifaces claimed by the driver behind our back */
884 		for (j = 0; j < nifaces; j++) {
885 			if (!ifaces[j] && !dev->subdevs[j]) {
886 				dev->subdevs[j] = dv;
887 				dev->nifaces_claimed++;
888 			}
889 		}
890 	}
891 
892 	free(ifaces, M_USB);
893 	return (USBD_NORMAL_COMPLETION);
894 }
895 
896 usbd_status
897 usbd_probe_and_attach(device_ptr_t parent, usbd_device_handle dev,
898 		      int port, int addr)
899 {
900 	usb_device_descriptor_t *dd = &dev->ddesc;
901 	int confi, nifaces;
902 	usbd_status err;
903 
904 	/* First try with device specific drivers. */
905 	DPRINTF(("usbd_probe_and_attach: trying device specific drivers\n"));
906 	err = usbd_attachwholedevice(parent, dev, port, 0);
907 	if (dev->nifaces_claimed || err)
908 		return (err);
909 	DPRINTF(("usbd_probe_and_attach: no device specific driver found\n"));
910 
911 	DPRINTF(("usbd_probe_and_attach: looping over %d configurations\n",
912 		 dd->bNumConfigurations));
913 	for (confi = 0; confi < dd->bNumConfigurations; confi++) {
914 		DPRINTFN(1,("usbd_probe_and_attach: trying config idx=%d\n",
915 			    confi));
916 		err = usbd_set_config_index(dev, confi, 1);
917 		if (err) {
918 #ifdef USB_DEBUG
919 			DPRINTF(("%s: port %d, set config at addr %d failed, "
920 				 "error=%s\n", USBDEVPTRNAME(parent), port,
921 				 addr, usbd_errstr(err)));
922 #else
923 			printf("%s: port %d, set config at addr %d failed\n",
924 			       USBDEVPTRNAME(parent), port, addr);
925 #endif
926  			return (err);
927 		}
928 		nifaces = dev->cdesc->bNumInterface;
929 		dev->subdevs = malloc(nifaces * sizeof(device_t), M_USB,
930 				      M_NOWAIT|M_ZERO);
931 		if (dev->subdevs == NULL)
932 			return (USBD_NOMEM);
933 		dev->subdevlen = nifaces;
934 
935 		err = usbd_attachinterfaces(parent, dev, port);
936 
937 		if (!dev->nifaces_claimed) {
938 			free(dev->subdevs, M_USB);
939 			dev->subdevs = 0;
940 			dev->subdevlen = 0;
941 		}
942 		if (dev->nifaces_claimed || err)
943 			return (err);
944 	}
945 	/* No interfaces were attached in any of the configurations. */
946 
947 	if (dd->bNumConfigurations > 1) /* don't change if only 1 config */
948 		usbd_set_config_index(dev, 0, 0);
949 
950 	DPRINTF(("usbd_probe_and_attach: no interface drivers found\n"));
951 
952 	/* Finally try the generic driver. */
953 	err = usbd_attachwholedevice(parent, dev, port, 1);
954 
955 	/*
956 	 * The generic attach failed, but leave the device as it is.
957 	 * We just did not find any drivers, that's all.  The device is
958 	 * fully operational and not harming anyone.
959 	 */
960 	DPRINTF(("usbd_probe_and_attach: generic attach failed\n"));
961  	return (USBD_NORMAL_COMPLETION);
962 }
963 
964 
965 /*
966  * Called when a new device has been put in the powered state,
967  * but not yet in the addressed state.
968  * Get initial descriptor, set the address, get full descriptor,
969  * and attach a driver.
970  */
971 usbd_status
972 usbd_new_device(device_ptr_t parent, usbd_bus_handle bus, int depth,
973 		int speed, int port, struct usbd_port *up)
974 {
975 	usbd_device_handle dev, adev;
976 	struct usbd_device *hub;
977 	usb_device_descriptor_t *dd;
978 	usb_port_status_t ps;
979 	usbd_status err;
980 	int addr;
981 	int i;
982 	int p;
983 
984 	DPRINTF(("usbd_new_device bus=%p port=%d depth=%d speed=%d\n",
985 		 bus, port, depth, speed));
986 	addr = usbd_getnewaddr(bus);
987 	if (addr < 0) {
988 		printf("%s: No free USB addresses, new device ignored.\n",
989 		       device_xname(bus->usbctl));
990 		return (USBD_NO_ADDR);
991 	}
992 
993 	dev = malloc(sizeof *dev, M_USB, M_NOWAIT|M_ZERO);
994 	if (dev == NULL)
995 		return (USBD_NOMEM);
996 
997 	dev->bus = bus;
998 
999 	/* Set up default endpoint handle. */
1000 	dev->def_ep.edesc = &dev->def_ep_desc;
1001 
1002 	/* Set up default endpoint descriptor. */
1003 	dev->def_ep_desc.bLength = USB_ENDPOINT_DESCRIPTOR_SIZE;
1004 	dev->def_ep_desc.bDescriptorType = UDESC_ENDPOINT;
1005 	dev->def_ep_desc.bEndpointAddress = USB_CONTROL_ENDPOINT;
1006 	dev->def_ep_desc.bmAttributes = UE_CONTROL;
1007 	USETW(dev->def_ep_desc.wMaxPacketSize, USB_MAX_IPACKET);
1008 	dev->def_ep_desc.bInterval = 0;
1009 
1010 	dev->quirks = &usbd_no_quirk;
1011 	dev->address = USB_START_ADDR;
1012 	dev->ddesc.bMaxPacketSize = 0;
1013 	dev->depth = depth;
1014 	dev->powersrc = up;
1015 	dev->myhub = up->parent;
1016 
1017 	up->device = dev;
1018 
1019 	/* Locate port on upstream high speed hub */
1020 	for (adev = dev, hub = up->parent;
1021 	     hub != NULL && hub->speed != USB_SPEED_HIGH;
1022 	     adev = hub, hub = hub->myhub)
1023 		;
1024 	if (hub) {
1025 		for (p = 0; p < hub->hub->hubdesc.bNbrPorts; p++) {
1026 			if (hub->hub->ports[p].device == adev) {
1027 				dev->myhsport = &hub->hub->ports[p];
1028 				goto found;
1029 			}
1030 		}
1031 		panic("usbd_new_device: cannot find HS port\n");
1032 	found:
1033 		DPRINTFN(1,("usbd_new_device: high speed port %d\n", p));
1034 	} else {
1035 		dev->myhsport = NULL;
1036 	}
1037 	dev->speed = speed;
1038 	dev->langid = USBD_NOLANG;
1039 	dev->cookie.cookie = ++usb_cookie_no;
1040 
1041 	/* Establish the default pipe. */
1042 	err = usbd_setup_pipe(dev, 0, &dev->def_ep, USBD_DEFAULT_INTERVAL,
1043 			      &dev->default_pipe);
1044 	if (err) {
1045 		usbd_remove_device(dev, up);
1046 		return (err);
1047 	}
1048 
1049 	dd = &dev->ddesc;
1050 	/* Try a few times in case the device is slow (i.e. outside specs.) */
1051 	for (i = 0; i < 10; i++) {
1052 		/* Get the first 8 bytes of the device descriptor. */
1053 		err = usbd_get_desc(dev, UDESC_DEVICE, 0, USB_MAX_IPACKET, dd);
1054 		if (!err)
1055 			break;
1056 		usbd_delay_ms(dev, 200);
1057 		if ((i & 3) == 3)
1058 			usbd_reset_port(up->parent, port, &ps);
1059 	}
1060 	if (err) {
1061 		DPRINTFN(-1, ("usbd_new_device: addr=%d, getting first desc "
1062 			      "failed\n", addr));
1063 		usbd_remove_device(dev, up);
1064 		return (err);
1065 	}
1066 
1067 	if (speed == USB_SPEED_HIGH) {
1068 		/* Max packet size must be 64 (sec 5.5.3). */
1069 		if (dd->bMaxPacketSize != USB_2_MAX_CTRL_PACKET) {
1070 #ifdef DIAGNOSTIC
1071 			printf("usbd_new_device: addr=%d bad max packet size\n",
1072 			       addr);
1073 #endif
1074 			dd->bMaxPacketSize = USB_2_MAX_CTRL_PACKET;
1075 		}
1076 	}
1077 
1078 	DPRINTF(("usbd_new_device: adding unit addr=%d, rev=%02x, class=%d, "
1079 		 "subclass=%d, protocol=%d, maxpacket=%d, len=%d, speed=%d\n",
1080 		 addr,UGETW(dd->bcdUSB), dd->bDeviceClass, dd->bDeviceSubClass,
1081 		 dd->bDeviceProtocol, dd->bMaxPacketSize, dd->bLength,
1082 		 dev->speed));
1083 
1084 	if (dd->bDescriptorType != UDESC_DEVICE) {
1085 		/* Illegal device descriptor */
1086 		DPRINTFN(-1,("usbd_new_device: illegal descriptor %d\n",
1087 			     dd->bDescriptorType));
1088 		usbd_remove_device(dev, up);
1089 		return (USBD_INVAL);
1090 	}
1091 
1092 	if (dd->bLength < USB_DEVICE_DESCRIPTOR_SIZE) {
1093 		DPRINTFN(-1,("usbd_new_device: bad length %d\n", dd->bLength));
1094 		usbd_remove_device(dev, up);
1095 		return (USBD_INVAL);
1096 	}
1097 
1098 	USETW(dev->def_ep_desc.wMaxPacketSize, dd->bMaxPacketSize);
1099 
1100 	err = usbd_reload_device_desc(dev);
1101 	if (err) {
1102 		DPRINTFN(-1, ("usbd_new_device: addr=%d, getting full desc "
1103 			      "failed\n", addr));
1104 		usbd_remove_device(dev, up);
1105 		return (err);
1106 	}
1107 
1108 	/* Set the address */
1109 	DPRINTFN(5, ("usbd_new_device: setting device address=%d\n", addr));
1110 	err = usbd_set_address(dev, addr);
1111 	if (err) {
1112 		DPRINTFN(-1, ("usbd_new_device: set address %d failed\n", addr));
1113 		err = USBD_SET_ADDR_FAILED;
1114 		usbd_remove_device(dev, up);
1115 		return err;
1116 	}
1117 
1118 	/* Allow device time to set new address */
1119 	usbd_delay_ms(dev, USB_SET_ADDRESS_SETTLE);
1120 	dev->address = addr;	/* new device address now */
1121 	bus->devices[addr] = dev;
1122 
1123 	/* Re-establish the default pipe with the new address. */
1124 	usbd_kill_pipe(dev->default_pipe);
1125 	err = usbd_setup_pipe(dev, 0, &dev->def_ep, USBD_DEFAULT_INTERVAL,
1126 	    &dev->default_pipe);
1127 	if (err) {
1128 		DPRINTFN(-1, ("usbd_new_device: setup default pipe failed\n"));
1129 		usbd_remove_device(dev, up);
1130 		return err;
1131 	}
1132 
1133 	/* Assume 100mA bus powered for now. Changed when configured. */
1134 	dev->power = USB_MIN_POWER;
1135 	dev->self_powered = 0;
1136 
1137 	DPRINTF(("usbd_new_device: new dev (addr %d), dev=%p, parent=%p\n",
1138 		 addr, dev, parent));
1139 
1140 	usbd_add_dev_event(USB_EVENT_DEVICE_ATTACH, dev);
1141 
1142 	if (port == 0) { /* root hub */
1143 		KASSERT(addr == 1);
1144 		usbd_attach_roothub(parent, dev);
1145 		return (USBD_NORMAL_COMPLETION);
1146 	}
1147 
1148 	err = usbd_probe_and_attach(parent, dev, port, addr);
1149 	if (err) {
1150 		usbd_remove_device(dev, up);
1151 		return (err);
1152   	}
1153 
1154   	return (USBD_NORMAL_COMPLETION);
1155 }
1156 
1157 usbd_status
1158 usbd_reload_device_desc(usbd_device_handle dev)
1159 {
1160 	usbd_status err;
1161 
1162 	/* Get the full device descriptor. */
1163 	err = usbd_get_device_desc(dev, &dev->ddesc);
1164 	if (err)
1165 		return (err);
1166 
1167 	/* Figure out what's wrong with this device. */
1168 	dev->quirks = usbd_find_quirk(&dev->ddesc);
1169 
1170 	return (USBD_NORMAL_COMPLETION);
1171 }
1172 
1173 void
1174 usbd_remove_device(usbd_device_handle dev, struct usbd_port *up)
1175 {
1176 	DPRINTF(("usbd_remove_device: %p\n", dev));
1177 
1178 	if (dev->default_pipe != NULL)
1179 		usbd_kill_pipe(dev->default_pipe);
1180 	up->device = NULL;
1181 	dev->bus->devices[dev->address] = NULL;
1182 
1183 	free(dev, M_USB);
1184 }
1185 
1186 int
1187 usbd_print(void *aux, const char *pnp)
1188 {
1189 	struct usb_attach_arg *uaa = aux;
1190 
1191 	DPRINTFN(15, ("usbd_print dev=%p\n", uaa->device));
1192 	if (pnp) {
1193 #define USB_DEVINFO 1024
1194 		char *devinfo;
1195 		if (!uaa->usegeneric)
1196 			return (QUIET);
1197 		devinfo = malloc(USB_DEVINFO, M_TEMP, M_WAITOK);
1198 		usbd_devinfo(uaa->device, 1, devinfo, USB_DEVINFO);
1199 		aprint_normal("%s, %s", devinfo, pnp);
1200 		free(devinfo, M_TEMP);
1201 	}
1202 	aprint_normal(" port %d", uaa->port);
1203 #if 0
1204 	/*
1205 	 * It gets very crowded with these locators on the attach line.
1206 	 * They are not really needed since they are printed in the clear
1207 	 * by each driver.
1208 	 */
1209 	if (uaa->vendor != UHUB_UNK_VENDOR)
1210 		aprint_normal(" vendor 0x%04x", uaa->vendor);
1211 	if (uaa->product != UHUB_UNK_PRODUCT)
1212 		aprint_normal(" product 0x%04x", uaa->product);
1213 	if (uaa->release != UHUB_UNK_RELEASE)
1214 		aprint_normal(" release 0x%04x", uaa->release);
1215 #endif
1216 	return (UNCONF);
1217 }
1218 
1219 int
1220 usbd_ifprint(void *aux, const char *pnp)
1221 {
1222 	struct usbif_attach_arg *uaa = aux;
1223 
1224 	DPRINTFN(15, ("usbd_print dev=%p\n", uaa->device));
1225 	if (pnp)
1226 		return (QUIET);
1227 	aprint_normal(" port %d", uaa->port);
1228 	aprint_normal(" configuration %d", uaa->configno);
1229 	aprint_normal(" interface %d", uaa->ifaceno);
1230 #if 0
1231 	/*
1232 	 * It gets very crowded with these locators on the attach line.
1233 	 * They are not really needed since they are printed in the clear
1234 	 * by each driver.
1235 	 */
1236 	if (uaa->vendor != UHUB_UNK_VENDOR)
1237 		aprint_normal(" vendor 0x%04x", uaa->vendor);
1238 	if (uaa->product != UHUB_UNK_PRODUCT)
1239 		aprint_normal(" product 0x%04x", uaa->product);
1240 	if (uaa->release != UHUB_UNK_RELEASE)
1241 		aprint_normal(" release 0x%04x", uaa->release);
1242 #endif
1243 	return (UNCONF);
1244 }
1245 
1246 void
1247 usbd_fill_deviceinfo(usbd_device_handle dev, struct usb_device_info *di,
1248 		     int usedev)
1249 {
1250 	struct usbd_port *p;
1251 	int i, j, err, s;
1252 
1253 	di->udi_bus = device_unit(dev->bus->usbctl);
1254 	di->udi_addr = dev->address;
1255 	di->udi_cookie = dev->cookie;
1256 	usbd_devinfo_vp(dev, di->udi_vendor, di->udi_product, usedev, 1);
1257 	usbd_printBCD(di->udi_release, sizeof(di->udi_release),
1258 	    UGETW(dev->ddesc.bcdDevice));
1259 	di->udi_serial[0] = 0;
1260 	if (usedev)
1261 		(void)usbd_get_string(dev, dev->ddesc.iSerialNumber,
1262 				      di->udi_serial);
1263 	di->udi_vendorNo = UGETW(dev->ddesc.idVendor);
1264 	di->udi_productNo = UGETW(dev->ddesc.idProduct);
1265 	di->udi_releaseNo = UGETW(dev->ddesc.bcdDevice);
1266 	di->udi_class = dev->ddesc.bDeviceClass;
1267 	di->udi_subclass = dev->ddesc.bDeviceSubClass;
1268 	di->udi_protocol = dev->ddesc.bDeviceProtocol;
1269 	di->udi_config = dev->config;
1270 	di->udi_power = dev->self_powered ? 0 : dev->power;
1271 	di->udi_speed = dev->speed;
1272 
1273 	if (dev->subdevlen > 0) {
1274 		for (i = 0, j = 0; i < dev->subdevlen &&
1275 			     j < USB_MAX_DEVNAMES; i++) {
1276 			if (!dev->subdevs[i])
1277 				continue;
1278 			strncpy(di->udi_devnames[j], USBDEVPTRNAME(dev->subdevs[i]),
1279 				USB_MAX_DEVNAMELEN);
1280 			di->udi_devnames[j][USB_MAX_DEVNAMELEN-1] = '\0';
1281 			j++;
1282                 }
1283         } else {
1284                 j = 0;
1285         }
1286         for (/* j is set */; j < USB_MAX_DEVNAMES; j++)
1287                 di->udi_devnames[j][0] = 0;                 /* empty */
1288 
1289 	if (dev->hub) {
1290 		for (i = 0;
1291 		     i < sizeof(di->udi_ports) / sizeof(di->udi_ports[0]) &&
1292 			     i < dev->hub->hubdesc.bNbrPorts;
1293 		     i++) {
1294 			p = &dev->hub->ports[i];
1295 			if (p->device)
1296 				err = p->device->address;
1297 			else {
1298 				s = UGETW(p->status.wPortStatus);
1299 				if (s & UPS_PORT_ENABLED)
1300 					err = USB_PORT_ENABLED;
1301 				else if (s & UPS_SUSPEND)
1302 					err = USB_PORT_SUSPENDED;
1303 				else if (s & UPS_PORT_POWER)
1304 					err = USB_PORT_POWERED;
1305 				else
1306 					err = USB_PORT_DISABLED;
1307 			}
1308 			di->udi_ports[i] = err;
1309 		}
1310 		di->udi_nports = dev->hub->hubdesc.bNbrPorts;
1311 	} else
1312 		di->udi_nports = 0;
1313 }
1314 
1315 #ifdef COMPAT_30
1316 void
1317 usbd_fill_deviceinfo_old(usbd_device_handle dev, struct usb_device_info_old *di,
1318                          int usedev)
1319 {
1320 	struct usbd_port *p;
1321 	int i, j, err, s;
1322 
1323 	di->udi_bus = device_unit(dev->bus->usbctl);
1324 	di->udi_addr = dev->address;
1325 	di->udi_cookie = dev->cookie;
1326 	usbd_devinfo_vp(dev, di->udi_vendor, di->udi_product, usedev, 0);
1327 	usbd_printBCD(di->udi_release, sizeof(di->udi_release),
1328 	    UGETW(dev->ddesc.bcdDevice));
1329 	di->udi_vendorNo = UGETW(dev->ddesc.idVendor);
1330 	di->udi_productNo = UGETW(dev->ddesc.idProduct);
1331 	di->udi_releaseNo = UGETW(dev->ddesc.bcdDevice);
1332 	di->udi_class = dev->ddesc.bDeviceClass;
1333 	di->udi_subclass = dev->ddesc.bDeviceSubClass;
1334 	di->udi_protocol = dev->ddesc.bDeviceProtocol;
1335 	di->udi_config = dev->config;
1336 	di->udi_power = dev->self_powered ? 0 : dev->power;
1337 	di->udi_speed = dev->speed;
1338 
1339 	if (dev->subdevlen > 0) {
1340 		for (i = 0, j = 0; i < dev->subdevlen &&
1341 			     j < USB_MAX_DEVNAMES; i++) {
1342 			if (!dev->subdevs[i])
1343 				continue;
1344 			strncpy(di->udi_devnames[j], USBDEVPTRNAME(dev->subdevs[i]),
1345 				USB_MAX_DEVNAMELEN);
1346 			di->udi_devnames[j][USB_MAX_DEVNAMELEN-1] = '\0';
1347 			j++;
1348 		}
1349 	} else {
1350 		j = 0;
1351 	}
1352 	for (/* j is set */; j < USB_MAX_DEVNAMES; j++)
1353 		di->udi_devnames[j][0] = 0;		 /* empty */
1354 
1355 	if (dev->hub) {
1356 		for (i = 0;
1357 		     i < sizeof(di->udi_ports) / sizeof(di->udi_ports[0]) &&
1358 			     i < dev->hub->hubdesc.bNbrPorts;
1359 		     i++) {
1360 			p = &dev->hub->ports[i];
1361 			if (p->device)
1362 				err = p->device->address;
1363 			else {
1364 				s = UGETW(p->status.wPortStatus);
1365 				if (s & UPS_PORT_ENABLED)
1366 					err = USB_PORT_ENABLED;
1367 				else if (s & UPS_SUSPEND)
1368 					err = USB_PORT_SUSPENDED;
1369 				else if (s & UPS_PORT_POWER)
1370 					err = USB_PORT_POWERED;
1371 				else
1372 					err = USB_PORT_DISABLED;
1373 			}
1374 			di->udi_ports[i] = err;
1375 		}
1376 		di->udi_nports = dev->hub->hubdesc.bNbrPorts;
1377 	} else
1378 		di->udi_nports = 0;
1379 }
1380 #endif
1381 
1382 
1383 void
1384 usb_free_device(usbd_device_handle dev)
1385 {
1386 	int ifcidx, nifc;
1387 
1388 	if (dev->default_pipe != NULL)
1389 		usbd_kill_pipe(dev->default_pipe);
1390 	if (dev->ifaces != NULL) {
1391 		nifc = dev->cdesc->bNumInterface;
1392 		for (ifcidx = 0; ifcidx < nifc; ifcidx++)
1393 			usbd_free_iface_data(dev, ifcidx);
1394 		free(dev->ifaces, M_USB);
1395 	}
1396 	if (dev->cdesc != NULL)
1397 		free(dev->cdesc, M_USB);
1398 	if (dev->subdevlen > 0) {
1399 		free(dev->subdevs, M_USB);
1400 		dev->subdevlen = 0;
1401 	}
1402 	free(dev, M_USB);
1403 }
1404 
1405 /*
1406  * The general mechanism for detaching drivers works as follows: Each
1407  * driver is responsible for maintaining a reference count on the
1408  * number of outstanding references to its softc (e.g.  from
1409  * processing hanging in a read or write).  The detach method of the
1410  * driver decrements this counter and flags in the softc that the
1411  * driver is dying and then wakes any sleepers.  It then sleeps on the
1412  * softc.  Each place that can sleep must maintain the reference
1413  * count.  When the reference count drops to -1 (0 is the normal value
1414  * of the reference count) the a wakeup on the softc is performed
1415  * signaling to the detach waiter that all references are gone.
1416  */
1417 
1418 /*
1419  * Called from process context when we discover that a port has
1420  * been disconnected.
1421  */
1422 void
1423 usb_disconnect_port(struct usbd_port *up, device_ptr_t parent)
1424 {
1425 	usbd_device_handle dev = up->device;
1426 	const char *hubname = USBDEVPTRNAME(parent);
1427 	int i;
1428 
1429 	DPRINTFN(3,("uhub_disconnect: up=%p dev=%p port=%d\n",
1430 		    up, dev, up->portno));
1431 
1432 #ifdef DIAGNOSTIC
1433 	if (dev == NULL) {
1434 		printf("usb_disconnect_port: no device\n");
1435 		return;
1436 	}
1437 #endif
1438 
1439 	if (dev->subdevlen > 0) {
1440 		DPRINTFN(3,("usb_disconnect_port: disconnect subdevs\n"));
1441 		for (i = 0; i < dev->subdevlen; i++) {
1442 			if (!dev->subdevs[i])
1443 				continue;
1444 			printf("%s: at %s", USBDEVPTRNAME(dev->subdevs[i]),
1445 			       hubname);
1446 			if (up->portno != 0)
1447 				printf(" port %d", up->portno);
1448 			printf(" (addr %d) disconnected\n", dev->address);
1449 			config_detach(dev->subdevs[i], DETACH_FORCE);
1450 		}
1451 		KASSERT(!dev->nifaces_claimed);
1452 	}
1453 
1454 	usbd_add_dev_event(USB_EVENT_DEVICE_DETACH, dev);
1455 	dev->bus->devices[dev->address] = NULL;
1456 	up->device = NULL;
1457 	usb_free_device(dev);
1458 }
1459