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