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