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