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