xref: /netbsd-src/sys/dev/usb/usb_subr.c (revision 796c32c94f6e154afc9de0f63da35c91bb739b45)
1 /*	$NetBSD: usb_subr.c,v 1.221 2017/10/28 00:37:12 pgoyette Exp $	*/
2 /*	$FreeBSD: src/sys/dev/usb/usb_subr.c,v 1.18 1999/11/17 22:33:47 n_hibma Exp $	*/
3 
4 /*
5  * Copyright (c) 1998, 2004 The NetBSD Foundation, Inc.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by Lennart Augustsson (lennart@augustsson.net) at
10  * Carlstedt Research & Technology.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
23  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
25  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #include <sys/cdefs.h>
35 __KERNEL_RCSID(0, "$NetBSD: usb_subr.c,v 1.221 2017/10/28 00:37:12 pgoyette Exp $");
36 
37 #ifdef _KERNEL_OPT
38 #include "opt_compat_netbsd.h"
39 #include "opt_usb.h"
40 #include "opt_usbverbose.h"
41 #endif
42 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/kernel.h>
46 #include <sys/kmem.h>
47 #include <sys/device.h>
48 #include <sys/select.h>
49 #include <sys/proc.h>
50 
51 #include <sys/bus.h>
52 #include <sys/module.h>
53 
54 #include <dev/usb/usb.h>
55 
56 #include <dev/usb/usbdi.h>
57 #include <dev/usb/usbdi_util.h>
58 #include <dev/usb/usbdivar.h>
59 #include <dev/usb/usbdevs.h>
60 #include <dev/usb/usb_quirks.h>
61 #include <dev/usb/usb_verbose.h>
62 #include <dev/usb/usbhist.h>
63 
64 #include "locators.h"
65 
66 #define	DPRINTF(FMT,A,B,C,D)	USBHIST_LOG(usbdebug,FMT,A,B,C,D)
67 #define	DPRINTFN(N,FMT,A,B,C,D)	USBHIST_LOGN(usbdebug,N,FMT,A,B,C,D)
68 
69 Static usbd_status usbd_set_config(struct usbd_device *, int);
70 Static void usbd_devinfo(struct usbd_device *, int, char *, size_t);
71 Static void usbd_devinfo_vp(struct usbd_device *, char *, size_t, char *, size_t,
72     int, int);
73 Static int usbd_getnewaddr(struct usbd_bus *);
74 Static int usbd_print(void *, const char *);
75 Static int usbd_ifprint(void *, const char *);
76 Static void usbd_free_iface_data(struct usbd_device *, int);
77 
78 uint32_t usb_cookie_no = 0;
79 
80 Static const char * const usbd_error_strs[] = {
81 	"NORMAL_COMPLETION",
82 	"IN_PROGRESS",
83 	"PENDING_REQUESTS",
84 	"NOT_STARTED",
85 	"INVAL",
86 	"NOMEM",
87 	"CANCELLED",
88 	"BAD_ADDRESS",
89 	"IN_USE",
90 	"NO_ADDR",
91 	"SET_ADDR_FAILED",
92 	"NO_POWER",
93 	"TOO_DEEP",
94 	"IOERROR",
95 	"NOT_CONFIGURED",
96 	"TIMEOUT",
97 	"SHORT_XFER",
98 	"STALLED",
99 	"INTERRUPTED",
100 	"XXX",
101 };
102 
103 DEV_VERBOSE_DEFINE(usb);
104 
105 const char *
106 usbd_errstr(usbd_status err)
107 {
108 	static char buffer[5];
109 
110 	if (err < USBD_ERROR_MAX) {
111 		return usbd_error_strs[err];
112 	} else {
113 		snprintf(buffer, sizeof(buffer), "%d", err);
114 		return buffer;
115 	}
116 }
117 
118 usbd_status
119 usbd_get_string_desc(struct usbd_device *dev, int sindex, int langid,
120 		     usb_string_descriptor_t *sdesc, int *sizep)
121 {
122 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
123 	usb_device_request_t req;
124 	usbd_status err;
125 	int actlen;
126 
127 	req.bmRequestType = UT_READ_DEVICE;
128 	req.bRequest = UR_GET_DESCRIPTOR;
129 	USETW2(req.wValue, UDESC_STRING, sindex);
130 	USETW(req.wIndex, langid);
131 	USETW(req.wLength, 2);	/* only size byte first */
132 	err = usbd_do_request_flags(dev, &req, sdesc, USBD_SHORT_XFER_OK,
133 		&actlen, USBD_DEFAULT_TIMEOUT);
134 	if (err)
135 		return err;
136 
137 	if (actlen < 2)
138 		return USBD_SHORT_XFER;
139 
140 	USETW(req.wLength, sdesc->bLength);	/* the whole string */
141 	err = usbd_do_request_flags(dev, &req, sdesc, USBD_SHORT_XFER_OK,
142 		&actlen, USBD_DEFAULT_TIMEOUT);
143 	if (err)
144 		return err;
145 
146 	if (actlen != sdesc->bLength) {
147 		DPRINTF("expected %jd, got %jd", sdesc->bLength, actlen, 0, 0);
148 	}
149 
150 	*sizep = actlen;
151 	return USBD_NORMAL_COMPLETION;
152 }
153 
154 static void
155 usbd_trim_spaces(char *p)
156 {
157 	char *q, *e;
158 
159 	q = e = p;
160 	while (*q == ' ')		/* skip leading spaces */
161 		q++;
162 	while ((*p = *q++))		/* copy string */
163 		if (*p++ != ' ')	/* remember last non-space */
164 			e = p;
165 	*e = '\0';			/* kill trailing spaces */
166 }
167 
168 static void
169 usbd_get_device_string(struct usbd_device *ud, uByte index, char **buf)
170 {
171 	char *b;
172 	usbd_status err;
173 
174 	b = kmem_alloc(USB_MAX_ENCODED_STRING_LEN, KM_SLEEP);
175 	err = usbd_get_string0(ud, index, b, true);
176 	if (err != USBD_NORMAL_COMPLETION) {
177 		kmem_free(b, USB_MAX_ENCODED_STRING_LEN);
178 		b = NULL;
179 	} else {
180 		usbd_trim_spaces(b);
181 	}
182 
183 	*buf = b;
184 }
185 
186 void
187 usbd_get_device_strings(struct usbd_device *ud)
188 {
189 	usb_device_descriptor_t *udd = &ud->ud_ddesc;
190 
191 	usbd_get_device_string(ud, udd->iManufacturer, &ud->ud_vendor);
192 	usbd_get_device_string(ud, udd->iProduct, &ud->ud_product);
193 	usbd_get_device_string(ud, udd->iSerialNumber, &ud->ud_serial);
194 }
195 
196 
197 Static void
198 usbd_devinfo_vp(struct usbd_device *dev, char *v, size_t vl, char *p,
199     size_t pl, int usedev, int useencoded)
200 {
201 	usb_device_descriptor_t *udd = &dev->ud_ddesc;
202 	if (dev == NULL)
203 		return;
204 
205 	v[0] = p[0] = '\0';
206 
207 	if (usedev) {
208 		if (usbd_get_string0(dev, udd->iManufacturer, v, useencoded) ==
209 		    USBD_NORMAL_COMPLETION)
210 			usbd_trim_spaces(v);
211 		if (usbd_get_string0(dev, udd->iProduct, p, useencoded) ==
212 		    USBD_NORMAL_COMPLETION)
213 			usbd_trim_spaces(p);
214 	} else {
215 		if (dev->ud_vendor) {
216 			strlcpy(v, dev->ud_vendor, vl);
217 		}
218 		if (dev->ud_product) {
219 			strlcpy(p, dev->ud_product, pl);
220 		}
221 	}
222 	if (v[0] == '\0')
223 		usb_findvendor(v, vl, UGETW(udd->idVendor));
224 	if (p[0] == '\0')
225 		usb_findproduct(p, pl, UGETW(udd->idVendor),
226 		    UGETW(udd->idProduct));
227 }
228 
229 int
230 usbd_printBCD(char *cp, size_t l, int bcd)
231 {
232 	return snprintf(cp, l, "%x.%02x", bcd >> 8, bcd & 0xff);
233 }
234 
235 Static void
236 usbd_devinfo(struct usbd_device *dev, int showclass, char *cp, size_t l)
237 {
238 	usb_device_descriptor_t *udd = &dev->ud_ddesc;
239 	char *vendor, *product;
240 	int bcdDevice, bcdUSB;
241 	char *ep;
242 
243 	vendor = kmem_alloc(USB_MAX_ENCODED_STRING_LEN * 2, KM_SLEEP);
244 	product = &vendor[USB_MAX_ENCODED_STRING_LEN];
245 
246 	ep = cp + l;
247 
248 	usbd_devinfo_vp(dev, vendor, USB_MAX_ENCODED_STRING_LEN,
249 	    product, USB_MAX_ENCODED_STRING_LEN, 0, 1);
250 	cp += snprintf(cp, ep - cp, "%s (%#04x) %s (%#04x)", vendor,
251 	    UGETW(udd->idVendor), product, UGETW(udd->idProduct));
252 	if (showclass)
253 		cp += snprintf(cp, ep - cp, ", class %d/%d",
254 		    udd->bDeviceClass, udd->bDeviceSubClass);
255 	bcdUSB = UGETW(udd->bcdUSB);
256 	bcdDevice = UGETW(udd->bcdDevice);
257 	cp += snprintf(cp, ep - cp, ", rev ");
258 	cp += usbd_printBCD(cp, ep - cp, bcdUSB);
259 	*cp++ = '/';
260 	cp += usbd_printBCD(cp, ep - cp, bcdDevice);
261 	cp += snprintf(cp, ep - cp, ", addr %d", dev->ud_addr);
262 	*cp = 0;
263 	kmem_free(vendor, USB_MAX_ENCODED_STRING_LEN * 2);
264 }
265 
266 char *
267 usbd_devinfo_alloc(struct usbd_device *dev, int showclass)
268 {
269 	char *devinfop;
270 
271 	devinfop = kmem_alloc(DEVINFOSIZE, KM_SLEEP);
272 	usbd_devinfo(dev, showclass, devinfop, DEVINFOSIZE);
273 	return devinfop;
274 }
275 
276 void
277 usbd_devinfo_free(char *devinfop)
278 {
279 	kmem_free(devinfop, DEVINFOSIZE);
280 }
281 
282 /* Delay for a certain number of ms */
283 void
284 usb_delay_ms_locked(struct usbd_bus *bus, u_int ms, kmutex_t *lock)
285 {
286 	/* Wait at least two clock ticks so we know the time has passed. */
287 	if (bus->ub_usepolling || cold)
288 		delay((ms+1) * 1000);
289 	else
290 		kpause("usbdly", false, (ms*hz+999)/1000 + 1, lock);
291 }
292 
293 void
294 usb_delay_ms(struct usbd_bus *bus, u_int ms)
295 {
296 	usb_delay_ms_locked(bus, ms, NULL);
297 }
298 
299 /* Delay given a device handle. */
300 void
301 usbd_delay_ms_locked(struct usbd_device *dev, u_int ms, kmutex_t *lock)
302 {
303 	usb_delay_ms_locked(dev->ud_bus, ms, lock);
304 }
305 
306 /* Delay given a device handle. */
307 void
308 usbd_delay_ms(struct usbd_device *dev, u_int ms)
309 {
310 	usb_delay_ms_locked(dev->ud_bus, ms, NULL);
311 }
312 
313 usbd_status
314 usbd_reset_port(struct usbd_device *dev, int port, usb_port_status_t *ps)
315 {
316 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
317 	usb_device_request_t req;
318 	usbd_status err;
319 	int n;
320 
321 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
322 	req.bRequest = UR_SET_FEATURE;
323 	USETW(req.wValue, UHF_PORT_RESET);
324 	USETW(req.wIndex, port);
325 	USETW(req.wLength, 0);
326 	err = usbd_do_request(dev, &req, 0);
327 	DPRINTFN(1, "port %jd reset done, error=%jd", port, err, 0, 0);
328 	if (err)
329 		return err;
330 	n = 10;
331 	do {
332 		/* Wait for device to recover from reset. */
333 		usbd_delay_ms(dev, USB_PORT_RESET_DELAY);
334 		err = usbd_get_port_status(dev, port, ps);
335 		if (err) {
336 			DPRINTF("get status failed %jd", err, 0, 0, 0);
337 			return err;
338 		}
339 		/* If the device disappeared, just give up. */
340 		if (!(UGETW(ps->wPortStatus) & UPS_CURRENT_CONNECT_STATUS))
341 			return USBD_NORMAL_COMPLETION;
342 	} while ((UGETW(ps->wPortChange) & UPS_C_PORT_RESET) == 0 && --n > 0);
343 	if (n == 0)
344 		return USBD_TIMEOUT;
345 	err = usbd_clear_port_feature(dev, port, UHF_C_PORT_RESET);
346 #ifdef USB_DEBUG
347 	if (err)
348 		DPRINTF("clear port feature failed %jd", err, 0, 0, 0);
349 #endif
350 
351 	/* Wait for the device to recover from reset. */
352 	usbd_delay_ms(dev, USB_PORT_RESET_RECOVERY);
353 	return err;
354 }
355 
356 usb_interface_descriptor_t *
357 usbd_find_idesc(usb_config_descriptor_t *cd, int ifaceidx, int altidx)
358 {
359 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
360 	char *p = (char *)cd;
361 	char *end = p + UGETW(cd->wTotalLength);
362 	usb_interface_descriptor_t *d;
363 	int curidx, lastidx, curaidx = 0;
364 
365 	for (curidx = lastidx = -1; p < end; ) {
366 		d = (usb_interface_descriptor_t *)p;
367 		DPRINTFN(4, "idx=%jd(%jd) altidx=%jd(%jd)", ifaceidx, curidx,
368 		    altidx, curaidx);
369 		DPRINTFN(4, "len=%jd type=%jd", d->bLength, d->bDescriptorType,
370 		    0, 0);
371 		if (d->bLength == 0) /* bad descriptor */
372 			break;
373 		p += d->bLength;
374 		if (p <= end && d->bDescriptorType == UDESC_INTERFACE) {
375 			if (d->bInterfaceNumber != lastidx) {
376 				lastidx = d->bInterfaceNumber;
377 				curidx++;
378 				curaidx = 0;
379 			} else
380 				curaidx++;
381 			if (ifaceidx == curidx && altidx == curaidx)
382 				return d;
383 		}
384 	}
385 	return NULL;
386 }
387 
388 usb_endpoint_descriptor_t *
389 usbd_find_edesc(usb_config_descriptor_t *cd, int ifaceidx, int altidx,
390 		int endptidx)
391 {
392 	char *p = (char *)cd;
393 	char *end = p + UGETW(cd->wTotalLength);
394 	usb_interface_descriptor_t *d;
395 	usb_endpoint_descriptor_t *e;
396 	int curidx;
397 
398 	d = usbd_find_idesc(cd, ifaceidx, altidx);
399 	if (d == NULL)
400 		return NULL;
401 	if (endptidx >= d->bNumEndpoints) /* quick exit */
402 		return NULL;
403 
404 	curidx = -1;
405 	for (p = (char *)d + d->bLength; p < end; ) {
406 		e = (usb_endpoint_descriptor_t *)p;
407 		if (e->bLength == 0) /* bad descriptor */
408 			break;
409 		p += e->bLength;
410 		if (p <= end && e->bDescriptorType == UDESC_INTERFACE)
411 			return NULL;
412 		if (p <= end && e->bDescriptorType == UDESC_ENDPOINT) {
413 			curidx++;
414 			if (curidx == endptidx)
415 				return e;
416 		}
417 	}
418 	return NULL;
419 }
420 
421 usbd_status
422 usbd_fill_iface_data(struct usbd_device *dev, int ifaceidx, int altidx)
423 {
424 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
425 	struct usbd_interface *ifc = &dev->ud_ifaces[ifaceidx];
426 	usb_interface_descriptor_t *idesc;
427 	char *p, *end;
428 	int endpt, nendpt;
429 
430 	DPRINTFN(4, "ifaceidx=%jd altidx=%jd", ifaceidx, altidx, 0, 0);
431 	idesc = usbd_find_idesc(dev->ud_cdesc, ifaceidx, altidx);
432 	if (idesc == NULL)
433 		return USBD_INVAL;
434 	ifc->ui_dev = dev;
435 	ifc->ui_idesc = idesc;
436 	ifc->ui_index = ifaceidx;
437 	ifc->ui_altindex = altidx;
438 	nendpt = ifc->ui_idesc->bNumEndpoints;
439 	DPRINTFN(4, "found idesc nendpt=%jd", nendpt, 0, 0, 0);
440 	if (nendpt != 0) {
441 		ifc->ui_endpoints = kmem_alloc(nendpt * sizeof(struct usbd_endpoint),
442 				KM_SLEEP);
443 	} else
444 		ifc->ui_endpoints = NULL;
445 	ifc->ui_priv = NULL;
446 	p = (char *)ifc->ui_idesc + ifc->ui_idesc->bLength;
447 	end = (char *)dev->ud_cdesc + UGETW(dev->ud_cdesc->wTotalLength);
448 #define ed ((usb_endpoint_descriptor_t *)p)
449 	for (endpt = 0; endpt < nendpt; endpt++) {
450 		DPRINTFN(10, "endpt=%jd", endpt, 0, 0, 0);
451 		for (; p < end; p += ed->bLength) {
452 			DPRINTFN(10, "p=%#jx end=%#jx len=%jd type=%jd",
453 			    (uintptr_t)p, (uintptr_t)end, ed->bLength,
454 			    ed->bDescriptorType);
455 			if (p + ed->bLength <= end && ed->bLength != 0 &&
456 			    ed->bDescriptorType == UDESC_ENDPOINT)
457 				goto found;
458 			if (ed->bLength == 0 ||
459 			    ed->bDescriptorType == UDESC_INTERFACE)
460 				break;
461 		}
462 		/* passed end, or bad desc */
463 		printf("usbd_fill_iface_data: bad descriptor(s): %s\n",
464 		       ed->bLength == 0 ? "0 length" :
465 		       ed->bDescriptorType == UDESC_INTERFACE ? "iface desc":
466 		       "out of data");
467 		goto bad;
468 	found:
469 		ifc->ui_endpoints[endpt].ue_edesc = ed;
470 		if (dev->ud_speed == USB_SPEED_HIGH) {
471 			u_int mps;
472 			/* Control and bulk endpoints have max packet limits. */
473 			switch (UE_GET_XFERTYPE(ed->bmAttributes)) {
474 			case UE_CONTROL:
475 				mps = USB_2_MAX_CTRL_PACKET;
476 				goto check;
477 			case UE_BULK:
478 				mps = USB_2_MAX_BULK_PACKET;
479 			check:
480 				if (UGETW(ed->wMaxPacketSize) != mps) {
481 					USETW(ed->wMaxPacketSize, mps);
482 #ifdef DIAGNOSTIC
483 					printf("usbd_fill_iface_data: bad max "
484 					       "packet size\n");
485 #endif
486 				}
487 				break;
488 			default:
489 				break;
490 			}
491 		}
492 		ifc->ui_endpoints[endpt].ue_refcnt = 0;
493 		ifc->ui_endpoints[endpt].ue_toggle = 0;
494 		p += ed->bLength;
495 	}
496 #undef ed
497 	LIST_INIT(&ifc->ui_pipes);
498 	return USBD_NORMAL_COMPLETION;
499 
500  bad:
501 	if (ifc->ui_endpoints != NULL) {
502 		kmem_free(ifc->ui_endpoints, nendpt * sizeof(struct usbd_endpoint));
503 		ifc->ui_endpoints = NULL;
504 	}
505 	return USBD_INVAL;
506 }
507 
508 void
509 usbd_free_iface_data(struct usbd_device *dev, int ifcno)
510 {
511 	struct usbd_interface *ifc = &dev->ud_ifaces[ifcno];
512 	if (ifc->ui_endpoints) {
513 		int nendpt = ifc->ui_idesc->bNumEndpoints;
514 		size_t sz = nendpt * sizeof(struct usbd_endpoint);
515 		kmem_free(ifc->ui_endpoints, sz);
516 	}
517 }
518 
519 Static usbd_status
520 usbd_set_config(struct usbd_device *dev, int conf)
521 {
522 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
523 	usb_device_request_t req;
524 
525 	DPRINTFN(5, "dev %#jx conf %jd", (uintptr_t)dev, conf, 0, 0);
526 
527 	req.bmRequestType = UT_WRITE_DEVICE;
528 	req.bRequest = UR_SET_CONFIG;
529 	USETW(req.wValue, conf);
530 	USETW(req.wIndex, 0);
531 	USETW(req.wLength, 0);
532 	return usbd_do_request(dev, &req, 0);
533 }
534 
535 usbd_status
536 usbd_set_config_no(struct usbd_device *dev, int no, int msg)
537 {
538 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
539 	usb_config_descriptor_t cd;
540 	usbd_status err;
541 	int index;
542 
543 	if (no == USB_UNCONFIG_NO)
544 		return usbd_set_config_index(dev, USB_UNCONFIG_INDEX, msg);
545 
546 	DPRINTFN(5, "%jd", no, 0, 0, 0);
547 	/* Figure out what config index to use. */
548 	for (index = 0; index < dev->ud_ddesc.bNumConfigurations; index++) {
549 		err = usbd_get_config_desc(dev, index, &cd);
550 		if (err)
551 			return err;
552 		if (cd.bConfigurationValue == no)
553 			return usbd_set_config_index(dev, index, msg);
554 	}
555 	return USBD_INVAL;
556 }
557 
558 usbd_status
559 usbd_set_config_index(struct usbd_device *dev, int index, int msg)
560 {
561 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
562 	usb_config_descriptor_t cd, *cdp;
563 	usb_bos_descriptor_t *bdp = NULL;
564 	usbd_status err;
565 	int i, ifcidx, nifc, len, selfpowered, power;
566 
567 	DPRINTFN(5, "dev=%#jx index=%jd", (uintptr_t)dev, index, 0, 0);
568 
569 	if (index >= dev->ud_ddesc.bNumConfigurations &&
570 	    index != USB_UNCONFIG_INDEX) {
571 		/* panic? */
572 		printf("usbd_set_config_index: illegal index\n");
573 		return USBD_INVAL;
574 	}
575 
576 	/* XXX check that all interfaces are idle */
577 	if (dev->ud_config != USB_UNCONFIG_NO) {
578 		DPRINTF("free old config", 0, 0, 0, 0);
579 		/* Free all configuration data structures. */
580 		nifc = dev->ud_cdesc->bNumInterface;
581 		for (ifcidx = 0; ifcidx < nifc; ifcidx++)
582 			usbd_free_iface_data(dev, ifcidx);
583 		kmem_free(dev->ud_ifaces, nifc * sizeof(struct usbd_interface));
584 		kmem_free(dev->ud_cdesc, UGETW(dev->ud_cdesc->wTotalLength));
585 		if (dev->ud_bdesc != NULL)
586 			kmem_free(dev->ud_bdesc,
587 			    UGETW(dev->ud_bdesc->wTotalLength));
588 		dev->ud_ifaces = NULL;
589 		dev->ud_cdesc = NULL;
590 		dev->ud_bdesc = NULL;
591 		dev->ud_config = USB_UNCONFIG_NO;
592 	}
593 
594 	if (index == USB_UNCONFIG_INDEX) {
595 		/* We are unconfiguring the device, so leave unallocated. */
596 		DPRINTF("set config 0", 0, 0, 0, 0);
597 		err = usbd_set_config(dev, USB_UNCONFIG_NO);
598 		if (err) {
599 			DPRINTF("setting config=0 failed, err = %jd", err,
600 			    0, 0, 0);
601 		}
602 		return err;
603 	}
604 
605 	/* Get the short descriptor. */
606 	err = usbd_get_config_desc(dev, index, &cd);
607 	if (err) {
608 		DPRINTF("get_config_desc=%jd", err, 0, 0, 0);
609 		return err;
610 	}
611 	len = UGETW(cd.wTotalLength);
612 	cdp = kmem_alloc(len, KM_SLEEP);
613 
614 	/* Get the full descriptor.  Try a few times for slow devices. */
615 	for (i = 0; i < 3; i++) {
616 		err = usbd_get_desc(dev, UDESC_CONFIG, index, len, cdp);
617 		if (!err)
618 			break;
619 		usbd_delay_ms(dev, 200);
620 	}
621 	if (err) {
622 		DPRINTF("get_desc=%jd", err, 0, 0, 0);
623 		goto bad;
624 	}
625 	if (cdp->bDescriptorType != UDESC_CONFIG) {
626 		DPRINTF("bad desc %jd", cdp->bDescriptorType, 0, 0, 0);
627 		err = USBD_INVAL;
628 		goto bad;
629 	}
630 
631 	if (USB_IS_SS(dev->ud_speed)) {
632 		usb_bos_descriptor_t bd;
633 
634 		/* get short bos desc */
635 		err = usbd_get_bos_desc(dev, index, &bd);
636 		if (!err) {
637 			int blen = UGETW(bd.wTotalLength);
638 			bdp = kmem_alloc(blen, KM_SLEEP);
639 
640 			/* Get the full desc */
641 			for (i = 0; i < 3; i++) {
642 				err = usbd_get_desc(dev, UDESC_BOS, index, blen,
643 				    bdp);
644 				if (!err)
645 					break;
646 				usbd_delay_ms(dev, 200);
647 			}
648 			if (err || bdp->bDescriptorType != UDESC_BOS) {
649 				DPRINTF("error %jd or bad desc %jd", err,
650 				    bdp->bDescriptorType, 0, 0);
651 				kmem_free(bdp, blen);
652 				bdp = NULL;
653 			}
654 		}
655 	}
656 	dev->ud_bdesc = bdp;
657 
658 	/*
659 	 * Figure out if the device is self or bus powered.
660 	 */
661 #if 0 /* XXX various devices don't report the power state correctly */
662 	selfpowered = 0;
663 	err = usbd_get_device_status(dev, &ds);
664 	if (!err && (UGETW(ds.wStatus) & UDS_SELF_POWERED))
665 		selfpowered = 1;
666 #endif
667 	/*
668 	 * Use the power state in the configuration we are going
669 	 * to set. This doesn't necessarily reflect the actual
670 	 * power state of the device; the driver can control this
671 	 * by choosing the appropriate configuration.
672 	 */
673 	selfpowered = !!(cdp->bmAttributes & UC_SELF_POWERED);
674 
675 	DPRINTF("addr %jd cno=%jd attr=%#02jx, selfpowered=%jd",
676 	    dev->ud_addr, cdp->bConfigurationValue, cdp->bmAttributes,
677 	    selfpowered);
678 	DPRINTF("max power=%jd", cdp->bMaxPower * 2, 0, 0, 0);
679 
680 	/* Check if we have enough power. */
681 #if 0 /* this is a no-op, see above */
682 	if ((cdp->bmAttributes & UC_SELF_POWERED) && !selfpowered) {
683 		if (msg)
684 			printf("%s: device addr %d (config %d): "
685 				 "can't set self powered configuration\n",
686 			       device_xname(dev->ud_bus->bdev), dev->ud_addr,
687 			       cdp->bConfigurationValue);
688 		err = USBD_NO_POWER;
689 		goto bad;
690 	}
691 #endif
692 #ifdef USB_DEBUG
693 	if (dev->ud_powersrc == NULL) {
694 		DPRINTF("No power source?", 0, 0, 0, 0);
695 		err = USBD_IOERROR;
696 		goto bad;
697 	}
698 #endif
699 	power = cdp->bMaxPower * 2;
700 	if (power > dev->ud_powersrc->up_power) {
701 		DPRINTF("power exceeded %jd %jd", power,
702 		    dev->ud_powersrc->up_power, 0, 0);
703 		/* XXX print nicer message. */
704 		if (msg)
705 			printf("%s: device addr %d (config %d) exceeds power "
706 				 "budget, %d mA > %d mA\n",
707 			       device_xname(dev->ud_bus->ub_usbctl), dev->ud_addr,
708 			       cdp->bConfigurationValue,
709 			       power, dev->ud_powersrc->up_power);
710 		err = USBD_NO_POWER;
711 		goto bad;
712 	}
713 	dev->ud_power = power;
714 	dev->ud_selfpowered = selfpowered;
715 
716 	/* Set the actual configuration value. */
717 	DPRINTF("set config %jd", cdp->bConfigurationValue, 0, 0, 0);
718 	err = usbd_set_config(dev, cdp->bConfigurationValue);
719 	if (err) {
720 		DPRINTF("setting config=%jd failed, error=%jd",
721 		    cdp->bConfigurationValue, err, 0, 0);
722 		goto bad;
723 	}
724 
725 	/* Allocate and fill interface data. */
726 	nifc = cdp->bNumInterface;
727 	dev->ud_ifaces = kmem_alloc(nifc * sizeof(struct usbd_interface),
728 	    KM_SLEEP);
729 	DPRINTFN(5, "dev=%#jx cdesc=%#jx", (uintptr_t)dev, (uintptr_t)cdp,
730 	    0, 0);
731 	dev->ud_cdesc = cdp;
732 	dev->ud_config = cdp->bConfigurationValue;
733 	for (ifcidx = 0; ifcidx < nifc; ifcidx++) {
734 		err = usbd_fill_iface_data(dev, ifcidx, 0);
735 		if (err) {
736 			while (--ifcidx >= 0)
737 				usbd_free_iface_data(dev, ifcidx);
738 			goto bad;
739 		}
740 	}
741 
742 	return USBD_NORMAL_COMPLETION;
743 
744  bad:
745 	kmem_free(cdp, len);
746 	if (bdp != NULL) {
747 		kmem_free(bdp, UGETW(bdp->wTotalLength));
748 		dev->ud_bdesc = NULL;
749 	}
750 	return err;
751 }
752 
753 /* XXX add function for alternate settings */
754 
755 usbd_status
756 usbd_setup_pipe(struct usbd_device *dev, struct usbd_interface *iface,
757 		struct usbd_endpoint *ep, int ival, struct usbd_pipe **pipe)
758 {
759 	return usbd_setup_pipe_flags(dev, iface, ep, ival, pipe, 0);
760 }
761 
762 usbd_status
763 usbd_setup_pipe_flags(struct usbd_device *dev, struct usbd_interface *iface,
764     struct usbd_endpoint *ep, int ival, struct usbd_pipe **pipe, uint8_t flags)
765 {
766 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
767 	struct usbd_pipe *p;
768 	usbd_status err;
769 
770 	p = kmem_alloc(dev->ud_bus->ub_pipesize, KM_SLEEP);
771 	DPRINTFN(1, "dev=%#jx addr=%jd iface=%#jx ep=%#jx",
772 	    (uintptr_t)dev, dev->ud_addr, (uintptr_t)iface, (uintptr_t)ep);
773 	DPRINTFN(1, "pipe=%#jx", (uintptr_t)p, 0, 0, 0);
774 	p->up_dev = dev;
775 	p->up_iface = iface;
776 	p->up_endpoint = ep;
777 	ep->ue_refcnt++;
778 	p->up_intrxfer = NULL;
779 	p->up_running = 0;
780 	p->up_aborting = 0;
781 	p->up_serialise = true;
782 	p->up_repeat = 0;
783 	p->up_interval = ival;
784 	p->up_flags = flags;
785 	p->up_serialise = true;
786 	SIMPLEQ_INIT(&p->up_queue);
787 	err = dev->ud_bus->ub_methods->ubm_open(p);
788 	if (err) {
789 		DPRINTF("endpoint=%#jx failed, error=%jd",
790 		    (uintptr_t)ep->ue_edesc->bEndpointAddress, err, 0, 0);
791 		kmem_free(p, dev->ud_bus->ub_pipesize);
792 		return err;
793 	}
794 
795 	KASSERT(p->up_methods->upm_start || p->up_serialise == false);
796 
797 	usb_init_task(&p->up_async_task, usbd_clear_endpoint_stall_task, p,
798 	    USB_TASKQ_MPSAFE);
799 	DPRINTFN(1, "pipe=%#jx", (uintptr_t)p, 0, 0, 0);
800 	*pipe = p;
801 	return USBD_NORMAL_COMPLETION;
802 }
803 
804 /* Abort the device control pipe. */
805 void
806 usbd_kill_pipe(struct usbd_pipe *pipe)
807 {
808 	usbd_abort_pipe(pipe);
809 	usbd_lock_pipe(pipe);
810 	pipe->up_methods->upm_close(pipe);
811 	usbd_unlock_pipe(pipe);
812 	usb_rem_task(pipe->up_dev, &pipe->up_async_task);
813 	pipe->up_endpoint->ue_refcnt--;
814 	kmem_free(pipe, pipe->up_dev->ud_bus->ub_pipesize);
815 }
816 
817 int
818 usbd_getnewaddr(struct usbd_bus *bus)
819 {
820 	int addr;
821 
822 	for (addr = 1; addr < USB_MAX_DEVICES; addr++) {
823 		size_t dindex = usb_addr2dindex(addr);
824 		if (bus->ub_devices[dindex] == NULL)
825 			return addr;
826 	}
827 	return -1;
828 }
829 
830 usbd_status
831 usbd_attach_roothub(device_t parent, struct usbd_device *dev)
832 {
833 	struct usb_attach_arg uaa;
834 	usb_device_descriptor_t *dd = &dev->ud_ddesc;
835 	device_t dv;
836 
837 	uaa.uaa_device = dev;
838 	uaa.uaa_usegeneric = 0;
839 	uaa.uaa_port = 0;
840 	uaa.uaa_vendor = UGETW(dd->idVendor);
841 	uaa.uaa_product = UGETW(dd->idProduct);
842 	uaa.uaa_release = UGETW(dd->bcdDevice);
843 	uaa.uaa_class = dd->bDeviceClass;
844 	uaa.uaa_subclass = dd->bDeviceSubClass;
845 	uaa.uaa_proto = dd->bDeviceProtocol;
846 
847 	dv = config_found_ia(parent, "usbroothubif", &uaa, 0);
848 	if (dv) {
849 		dev->ud_subdevs = kmem_alloc(sizeof(dv), KM_SLEEP);
850 		dev->ud_subdevs[0] = dv;
851 		dev->ud_subdevlen = 1;
852 	}
853 	return USBD_NORMAL_COMPLETION;
854 }
855 
856 static void
857 usbd_serialnumber(device_t dv, struct usbd_device *dev)
858 {
859 	if (dev->ud_serial) {
860 		prop_dictionary_set_cstring(device_properties(dv),
861 		    "serialnumber", dev->ud_serial);
862 	}
863 }
864 
865 static usbd_status
866 usbd_attachwholedevice(device_t parent, struct usbd_device *dev, int port,
867 	int usegeneric)
868 {
869 	struct usb_attach_arg uaa;
870 	usb_device_descriptor_t *dd = &dev->ud_ddesc;
871 	device_t dv;
872 	int dlocs[USBDEVIFCF_NLOCS];
873 
874 	uaa.uaa_device = dev;
875 	uaa.uaa_usegeneric = usegeneric;
876 	uaa.uaa_port = port;
877 	uaa.uaa_vendor = UGETW(dd->idVendor);
878 	uaa.uaa_product = UGETW(dd->idProduct);
879 	uaa.uaa_release = UGETW(dd->bcdDevice);
880 	uaa.uaa_class = dd->bDeviceClass;
881 	uaa.uaa_subclass = dd->bDeviceSubClass;
882 	uaa.uaa_proto = dd->bDeviceProtocol;
883 
884 	dlocs[USBDEVIFCF_PORT] = uaa.uaa_port;
885 	dlocs[USBDEVIFCF_VENDOR] = uaa.uaa_vendor;
886 	dlocs[USBDEVIFCF_PRODUCT] = uaa.uaa_product;
887 	dlocs[USBDEVIFCF_RELEASE] = uaa.uaa_release;
888 	/* the rest is historical ballast */
889 	dlocs[USBDEVIFCF_CONFIGURATION] = -1;
890 	dlocs[USBDEVIFCF_INTERFACE] = -1;
891 
892 	KERNEL_LOCK(1, NULL);
893 	dv = config_found_sm_loc(parent, "usbdevif", dlocs, &uaa, usbd_print,
894 				 config_stdsubmatch);
895 	KERNEL_UNLOCK_ONE(NULL);
896 	if (dv) {
897 		dev->ud_subdevs = kmem_alloc(sizeof(dv), KM_SLEEP);
898 		dev->ud_subdevs[0] = dv;
899 		dev->ud_subdevlen = 1;
900 		dev->ud_nifaces_claimed = 1; /* XXX */
901 		usbd_serialnumber(dv, dev);
902 	}
903 	return USBD_NORMAL_COMPLETION;
904 }
905 
906 static usbd_status
907 usbd_attachinterfaces(device_t parent, struct usbd_device *dev,
908 		      int port, const int *locators)
909 {
910 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
911 	struct usbif_attach_arg uiaa;
912 	int ilocs[USBIFIFCF_NLOCS];
913 	usb_device_descriptor_t *dd = &dev->ud_ddesc;
914 	int nifaces;
915 	struct usbd_interface **ifaces;
916 	int i, j, loc;
917 	device_t dv;
918 
919 	nifaces = dev->ud_cdesc->bNumInterface;
920 	ifaces = kmem_zalloc(nifaces * sizeof(*ifaces), KM_SLEEP);
921 	for (i = 0; i < nifaces; i++) {
922 		if (!dev->ud_subdevs[i]) {
923 			ifaces[i] = &dev->ud_ifaces[i];
924 		}
925 		DPRINTF("interface %jd %#jx", i, (uintptr_t)ifaces[i], 0, 0);
926 	}
927 
928 
929 	uiaa.uiaa_device = dev;
930 	uiaa.uiaa_port = port;
931 	uiaa.uiaa_vendor = UGETW(dd->idVendor);
932 	uiaa.uiaa_product = UGETW(dd->idProduct);
933 	uiaa.uiaa_release = UGETW(dd->bcdDevice);
934 	uiaa.uiaa_configno = dev->ud_cdesc->bConfigurationValue;
935 	uiaa.uiaa_ifaces = ifaces;
936 	uiaa.uiaa_nifaces = nifaces;
937 	ilocs[USBIFIFCF_PORT] = uiaa.uiaa_port;
938 	ilocs[USBIFIFCF_VENDOR] = uiaa.uiaa_vendor;
939 	ilocs[USBIFIFCF_PRODUCT] = uiaa.uiaa_product;
940 	ilocs[USBIFIFCF_RELEASE] = uiaa.uiaa_release;
941 	ilocs[USBIFIFCF_CONFIGURATION] = uiaa.uiaa_configno;
942 
943 	for (i = 0; i < nifaces; i++) {
944 		if (!ifaces[i]) {
945 			DPRINTF("interface %jd claimed", i, 0, 0, 0);
946 			continue; /* interface already claimed */
947 		}
948 		uiaa.uiaa_iface = ifaces[i];
949 		uiaa.uiaa_class = ifaces[i]->ui_idesc->bInterfaceClass;
950 		uiaa.uiaa_subclass = ifaces[i]->ui_idesc->bInterfaceSubClass;
951 		uiaa.uiaa_proto = ifaces[i]->ui_idesc->bInterfaceProtocol;
952 		uiaa.uiaa_ifaceno = ifaces[i]->ui_idesc->bInterfaceNumber;
953 
954 		DPRINTF("searching for interface %jd...", i, 0, 0, 0);
955 		DPRINTF("class %jx subclass %jx proto %jx ifaceno %jd",
956 		    uiaa.uiaa_class, uiaa.uiaa_subclass, uiaa.uiaa_proto,
957 		    uiaa.uiaa_ifaceno);
958 		ilocs[USBIFIFCF_INTERFACE] = uiaa.uiaa_ifaceno;
959 		if (locators != NULL) {
960 			loc = locators[USBIFIFCF_CONFIGURATION];
961 			if (loc != USBIFIFCF_CONFIGURATION_DEFAULT &&
962 			    loc != uiaa.uiaa_configno)
963 				continue;
964 			loc = locators[USBIFIFCF_INTERFACE];
965 			if (loc != USBIFIFCF_INTERFACE_DEFAULT &&
966 			    loc != uiaa.uiaa_ifaceno)
967 				continue;
968 		}
969 		KERNEL_LOCK(1, NULL);
970 		dv = config_found_sm_loc(parent, "usbifif", ilocs, &uiaa,
971 					 usbd_ifprint, config_stdsubmatch);
972 		KERNEL_UNLOCK_ONE(NULL);
973 		if (!dv)
974 			continue;
975 
976 		usbd_serialnumber(dv, dev);
977 
978 		/* claim */
979 		ifaces[i] = NULL;
980 		/* account for ifaces claimed by the driver behind our back */
981 		for (j = 0; j < nifaces; j++) {
982 
983 			if (!ifaces[j] && !dev->ud_subdevs[j]) {
984 				DPRINTF("interface %jd claimed behind our back",
985 				    j, 0, 0, 0);
986 				dev->ud_subdevs[j] = dv;
987 				dev->ud_nifaces_claimed++;
988 			}
989 		}
990 	}
991 
992 	kmem_free(ifaces, nifaces * sizeof(*ifaces));
993 	return USBD_NORMAL_COMPLETION;
994 }
995 
996 usbd_status
997 usbd_probe_and_attach(device_t parent, struct usbd_device *dev,
998                       int port, int addr)
999 {
1000 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
1001 	usb_device_descriptor_t *dd = &dev->ud_ddesc;
1002 	int confi, nifaces;
1003 	usbd_status err;
1004 
1005 	/* First try with device specific drivers. */
1006 	DPRINTF("trying device specific drivers", 0, 0, 0, 0);
1007 	err = usbd_attachwholedevice(parent, dev, port, 0);
1008 	if (dev->ud_nifaces_claimed || err)
1009 		return err;
1010 	DPRINTF("no device specific driver found", 0, 0, 0, 0);
1011 
1012 	DPRINTF("looping over %jd configurations", dd->bNumConfigurations,
1013 	    0, 0, 0);
1014 	for (confi = 0; confi < dd->bNumConfigurations; confi++) {
1015 		DPRINTFN(1, "trying config idx=%jd", confi, 0, 0, 0);
1016 		err = usbd_set_config_index(dev, confi, 1);
1017 		if (err) {
1018 			DPRINTF("port %jd, set config at addr %jd failed, "
1019 			    "error=%d", port, addr, err, 0);
1020 			printf("%s: port %d, set config at addr %d failed\n",
1021 			    device_xname(parent), port, addr);
1022 			return err;
1023 		}
1024 		nifaces = dev->ud_cdesc->bNumInterface;
1025 		dev->ud_subdevs = kmem_zalloc(nifaces * sizeof(device_t),
1026 		    KM_SLEEP);
1027 		if (dev->ud_subdevs == NULL)
1028 			return USBD_NOMEM;
1029 		dev->ud_subdevlen = nifaces;
1030 
1031 		err = usbd_attachinterfaces(parent, dev, port, NULL);
1032 
1033 		if (!dev->ud_nifaces_claimed) {
1034 			kmem_free(dev->ud_subdevs,
1035 			    dev->ud_subdevlen * sizeof(device_t));
1036 			dev->ud_subdevs = 0;
1037 			dev->ud_subdevlen = 0;
1038 		}
1039 		if (dev->ud_nifaces_claimed || err)
1040 			return err;
1041 	}
1042 	/* No interfaces were attached in any of the configurations. */
1043 
1044 	if (dd->bNumConfigurations > 1) /* don't change if only 1 config */
1045 		usbd_set_config_index(dev, 0, 0);
1046 
1047 	DPRINTF("no interface drivers found", 0, 0, 0, 0);
1048 
1049 	/* Finally try the generic driver. */
1050 	err = usbd_attachwholedevice(parent, dev, port, 1);
1051 
1052 	/*
1053 	 * The generic attach failed, but leave the device as it is.
1054 	 * We just did not find any drivers, that's all.  The device is
1055 	 * fully operational and not harming anyone.
1056 	 */
1057 	DPRINTF("generic attach failed", 0, 0, 0, 0);
1058 
1059 	return USBD_NORMAL_COMPLETION;
1060 }
1061 
1062 /**
1063  * Called from uhub_rescan().  usbd_new_device() for the target dev must be
1064  * called before calling this.
1065  */
1066 usbd_status
1067 usbd_reattach_device(device_t parent, struct usbd_device *dev,
1068                      int port, const int *locators)
1069 {
1070 	int i, loc;
1071 
1072 	if (locators != NULL) {
1073 		loc = locators[USBIFIFCF_PORT];
1074 		if (loc != USBIFIFCF_PORT_DEFAULT && loc != port)
1075 			return USBD_NORMAL_COMPLETION;
1076 		loc = locators[USBIFIFCF_VENDOR];
1077 		if (loc != USBIFIFCF_VENDOR_DEFAULT &&
1078 		    loc != UGETW(dev->ud_ddesc.idVendor))
1079 			return USBD_NORMAL_COMPLETION;
1080 		loc = locators[USBIFIFCF_PRODUCT];
1081 		if (loc != USBIFIFCF_PRODUCT_DEFAULT &&
1082 		    loc != UGETW(dev->ud_ddesc.idProduct))
1083 			return USBD_NORMAL_COMPLETION;
1084 		loc = locators[USBIFIFCF_RELEASE];
1085 		if (loc != USBIFIFCF_RELEASE_DEFAULT &&
1086 		    loc != UGETW(dev->ud_ddesc.bcdDevice))
1087 			return USBD_NORMAL_COMPLETION;
1088 	}
1089 	if (dev->ud_subdevlen == 0) {
1090 		/* XXX: check USBIFIFCF_CONFIGURATION and
1091 		 * USBIFIFCF_INTERFACE too */
1092 		return usbd_probe_and_attach(parent, dev, port, dev->ud_addr);
1093 	} else if (dev->ud_subdevlen != dev->ud_cdesc->bNumInterface) {
1094 		/* device-specific or generic driver is already attached. */
1095 		return USBD_NORMAL_COMPLETION;
1096 	}
1097 	/* Does the device have unconfigured interfaces? */
1098 	for (i = 0; i < dev->ud_subdevlen; i++) {
1099 		if (dev->ud_subdevs[i] == NULL) {
1100 			break;
1101 		}
1102 	}
1103 	if (i >= dev->ud_subdevlen)
1104 		return USBD_NORMAL_COMPLETION;
1105 	return usbd_attachinterfaces(parent, dev, port, locators);
1106 }
1107 
1108 /*
1109  * Get the first 8 bytes of the device descriptor.
1110  * Do as Windows does: try to read 64 bytes -- there are devices which
1111  * recognize the initial descriptor fetch (before the control endpoint's
1112  * MaxPacketSize is known by the host) by exactly this length.
1113  */
1114 usbd_status
1115 usbd_get_initial_ddesc(struct usbd_device *dev, usb_device_descriptor_t *desc)
1116 {
1117 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
1118 	usb_device_request_t req;
1119 	char buf[64];
1120 	int res, actlen;
1121 
1122 	DPRINTFN(5, "dev %#jx", (uintptr_t)dev, 0, 0, 0);
1123 
1124 	req.bmRequestType = UT_READ_DEVICE;
1125 	req.bRequest = UR_GET_DESCRIPTOR;
1126 	USETW2(req.wValue, UDESC_DEVICE, 0);
1127 	USETW(req.wIndex, 0);
1128 	USETW(req.wLength, 64);
1129 	res = usbd_do_request_flags(dev, &req, buf, USBD_SHORT_XFER_OK,
1130 		&actlen, USBD_DEFAULT_TIMEOUT);
1131 	if (res)
1132 		return res;
1133 	if (actlen < 8)
1134 		return USBD_SHORT_XFER;
1135 	memcpy(desc, buf, 8);
1136 	return USBD_NORMAL_COMPLETION;
1137 }
1138 
1139 /*
1140  * Called when a new device has been put in the powered state,
1141  * but not yet in the addressed state.
1142  * Get initial descriptor, set the address, get full descriptor,
1143  * and attach a driver.
1144  */
1145 usbd_status
1146 usbd_new_device(device_t parent, struct usbd_bus *bus, int depth, int speed,
1147     int port, struct usbd_port *up)
1148 {
1149 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
1150 	struct usbd_device *dev, *adev;
1151 	struct usbd_device *hub;
1152 	usb_device_descriptor_t *dd;
1153 	usb_port_status_t ps;
1154 	usbd_status err;
1155 	int addr;
1156 	int i;
1157 	int p;
1158 
1159 	DPRINTF("bus=%#jx port=%jd depth=%jd speed=%jd",
1160 	    (uintptr_t)bus, port, depth, speed);
1161 
1162 	if (bus->ub_methods->ubm_newdev != NULL)
1163 		return (bus->ub_methods->ubm_newdev)(parent, bus, depth, speed,
1164 		    port, up);
1165 
1166 	addr = usbd_getnewaddr(bus);
1167 	if (addr < 0) {
1168 		printf("%s: No free USB addresses, new device ignored.\n",
1169 		       device_xname(bus->ub_usbctl));
1170 		return USBD_NO_ADDR;
1171 	}
1172 
1173 	dev = kmem_zalloc(sizeof(*dev), KM_SLEEP);
1174 	dev->ud_bus = bus;
1175 
1176 	/* Set up default endpoint handle. */
1177 	dev->ud_ep0.ue_edesc = &dev->ud_ep0desc;
1178 
1179 	/* Set up default endpoint descriptor. */
1180 	dev->ud_ep0desc.bLength = USB_ENDPOINT_DESCRIPTOR_SIZE;
1181 	dev->ud_ep0desc.bDescriptorType = UDESC_ENDPOINT;
1182 	dev->ud_ep0desc.bEndpointAddress = USB_CONTROL_ENDPOINT;
1183 	dev->ud_ep0desc.bmAttributes = UE_CONTROL;
1184 	/*
1185 	 * temporary, will be fixed after first descriptor fetch
1186 	 * (which uses 64 bytes so it shouldn't be less),
1187 	 * highspeed devices must support 64 byte packets anyway
1188 	 */
1189 	if (speed == USB_SPEED_HIGH || speed == USB_SPEED_FULL)
1190 		USETW(dev->ud_ep0desc.wMaxPacketSize, 64);
1191 	else
1192 		USETW(dev->ud_ep0desc.wMaxPacketSize, USB_MAX_IPACKET);
1193 
1194 	dev->ud_ep0desc.bInterval = 0;
1195 
1196 	/* doesn't matter, just don't leave it uninitialized */
1197 	dev->ud_ep0.ue_toggle = 0;
1198 
1199 	dev->ud_quirks = &usbd_no_quirk;
1200 	dev->ud_addr = USB_START_ADDR;
1201 	dev->ud_ddesc.bMaxPacketSize = 0;
1202 	dev->ud_depth = depth;
1203 	dev->ud_powersrc = up;
1204 	dev->ud_myhub = up->up_parent;
1205 
1206 	up->up_dev = dev;
1207 
1208 	/* Locate port on upstream high speed hub */
1209 	for (adev = dev, hub = up->up_parent;
1210 	     hub != NULL && hub->ud_speed != USB_SPEED_HIGH;
1211 	     adev = hub, hub = hub->ud_myhub)
1212 		;
1213 	if (hub) {
1214 		for (p = 0; p < hub->ud_hub->uh_hubdesc.bNbrPorts; p++) {
1215 			if (hub->ud_hub->uh_ports[p].up_dev == adev) {
1216 				dev->ud_myhsport = &hub->ud_hub->uh_ports[p];
1217 				goto found;
1218 			}
1219 		}
1220 		panic("usbd_new_device: cannot find HS port");
1221 	found:
1222 		DPRINTFN(1, "high speed port %jd", p, 0, 0, 0);
1223 	} else {
1224 		dev->ud_myhsport = NULL;
1225 	}
1226 	dev->ud_speed = speed;
1227 	dev->ud_langid = USBD_NOLANG;
1228 	dev->ud_cookie.cookie = ++usb_cookie_no;
1229 
1230 	/* Establish the default pipe. */
1231 	err = usbd_setup_pipe_flags(dev, 0, &dev->ud_ep0, USBD_DEFAULT_INTERVAL,
1232 	    &dev->ud_pipe0, USBD_MPSAFE);
1233 	if (err) {
1234 		usbd_remove_device(dev, up);
1235 		return err;
1236 	}
1237 
1238 	dd = &dev->ud_ddesc;
1239 	/* Try a few times in case the device is slow (i.e. outside specs.) */
1240 	for (i = 0; i < 10; i++) {
1241 		/* Get the first 8 bytes of the device descriptor. */
1242 		err = usbd_get_initial_ddesc(dev, dd);
1243 		if (!err)
1244 			break;
1245 		/*
1246 		 * The root hub can never fail to give the initial descriptor,
1247 		 * but assert it just in case.
1248 		 */
1249 		KASSERT(up->up_parent);
1250 		usbd_delay_ms(dev, 200);
1251 		if ((i & 3) == 3)
1252 			usbd_reset_port(up->up_parent, port, &ps);
1253 	}
1254 	if (err) {
1255 		DPRINTF("addr=%jd, getting first desc failed: %jd", addr, err,
1256 		    0, 0);
1257 		usbd_remove_device(dev, up);
1258 		return err;
1259 	}
1260 
1261 	/* Windows resets the port here, do likewise */
1262 	if (up->up_parent)
1263 		usbd_reset_port(up->up_parent, port, &ps);
1264 
1265 	if (speed == USB_SPEED_HIGH) {
1266 		/* Max packet size must be 64 (sec 5.5.3). */
1267 		if (dd->bMaxPacketSize != USB_2_MAX_CTRL_PACKET) {
1268 #ifdef DIAGNOSTIC
1269 			printf("usbd_new_device: addr=%d bad max packet "
1270 			    "size=%d. adjusting to %d.\n",
1271 			    addr, dd->bMaxPacketSize, USB_2_MAX_CTRL_PACKET);
1272 #endif
1273 			dd->bMaxPacketSize = USB_2_MAX_CTRL_PACKET;
1274 		}
1275 	}
1276 
1277 	DPRINTF("adding unit addr=%jd, rev=%02jx, class=%jd, subclass=%jd",
1278 	    addr, UGETW(dd->bcdUSB), dd->bDeviceClass, dd->bDeviceSubClass);
1279 	DPRINTF("protocol=%jd, maxpacket=%jd, len=%jd, speed=%jd",
1280 	    dd->bDeviceProtocol, dd->bMaxPacketSize, dd->bLength, dev->ud_speed);
1281 
1282 	if (dd->bDescriptorType != UDESC_DEVICE) {
1283 		/* Illegal device descriptor */
1284 		DPRINTF("illegal descriptor %jd", dd->bDescriptorType, 0, 0, 0);
1285 		usbd_remove_device(dev, up);
1286 		return USBD_INVAL;
1287 	}
1288 
1289 	if (dd->bLength < USB_DEVICE_DESCRIPTOR_SIZE) {
1290 		DPRINTF("bad length %jd", dd->bLength, 0, 0, 0);
1291 		usbd_remove_device(dev, up);
1292 		return USBD_INVAL;
1293 	}
1294 
1295 	USETW(dev->ud_ep0desc.wMaxPacketSize, dd->bMaxPacketSize);
1296 
1297 	/* Re-establish the default pipe with the new MPS. */
1298 	usbd_kill_pipe(dev->ud_pipe0);
1299 	err = usbd_setup_pipe_flags(dev, 0, &dev->ud_ep0, USBD_DEFAULT_INTERVAL,
1300 	    &dev->ud_pipe0, USBD_MPSAFE);
1301 	if (err) {
1302 		DPRINTF("setup default pipe failed err %jd", err, 0, 0, 0);
1303 		usbd_remove_device(dev, up);
1304 		return err;
1305 	}
1306 
1307 	/* Set the address */
1308 	DPRINTFN(5, "setting device address=%jd", addr, 0, 0, 0);
1309 	err = usbd_set_address(dev, addr);
1310 	if (err) {
1311 		DPRINTF("set address %jd failed, err = %jd", addr, err, 0, 0);
1312 		err = USBD_SET_ADDR_FAILED;
1313 		usbd_remove_device(dev, up);
1314 		return err;
1315 	}
1316 
1317 	/* Allow device time to set new address */
1318 	usbd_delay_ms(dev, USB_SET_ADDRESS_SETTLE);
1319 	dev->ud_addr = addr;	/* new device address now */
1320 	bus->ub_devices[usb_addr2dindex(addr)] = dev;
1321 
1322 	/* Re-establish the default pipe with the new address. */
1323 	usbd_kill_pipe(dev->ud_pipe0);
1324 	err = usbd_setup_pipe_flags(dev, 0, &dev->ud_ep0, USBD_DEFAULT_INTERVAL,
1325 	    &dev->ud_pipe0, USBD_MPSAFE);
1326 	if (err) {
1327 		DPRINTF("setup default pipe failed, err = %jd", err, 0, 0, 0);
1328 		usbd_remove_device(dev, up);
1329 		return err;
1330 	}
1331 
1332 	err = usbd_reload_device_desc(dev);
1333 	if (err) {
1334 		DPRINTF("addr=%jd, getting full desc failed, err = %jd", addr,
1335 		    err, 0, 0);
1336 		usbd_remove_device(dev, up);
1337 		return err;
1338 	}
1339 
1340 	/* Assume 100mA bus powered for now. Changed when configured. */
1341 	dev->ud_power = USB_MIN_POWER;
1342 	dev->ud_selfpowered = 0;
1343 
1344 	DPRINTF("new dev (addr %jd), dev=%#jx, parent=%#jx",
1345 	    addr, (uintptr_t)dev, (uintptr_t)parent, 0);
1346 
1347 	usbd_get_device_strings(dev);
1348 
1349 	usbd_add_dev_event(USB_EVENT_DEVICE_ATTACH, dev);
1350 
1351 	if (port == 0) { /* root hub */
1352 		KASSERT(addr == 1);
1353 		usbd_attach_roothub(parent, dev);
1354 		return USBD_NORMAL_COMPLETION;
1355 	}
1356 
1357 	err = usbd_probe_and_attach(parent, dev, port, addr);
1358 	if (err) {
1359 		usbd_remove_device(dev, up);
1360 		return err;
1361 	}
1362 
1363 	return USBD_NORMAL_COMPLETION;
1364 }
1365 
1366 usbd_status
1367 usbd_reload_device_desc(struct usbd_device *dev)
1368 {
1369 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
1370 	usb_device_descriptor_t *udd = &dev->ud_ddesc;
1371 	usbd_status err;
1372 
1373 	/* Get the full device descriptor. */
1374 	err = usbd_get_device_desc(dev, udd);
1375 	if (err)
1376 		return err;
1377 
1378 	DPRINTFN(15, "bLength             %5ju", udd->bLength, 0, 0, 0);
1379 	DPRINTFN(15, "bDescriptorType     %5ju", udd->bDescriptorType, 0, 0, 0);
1380 	DPRINTFN(15, "bcdUSB              %2jx.%02jx", udd->bcdUSB[1],
1381 	    udd->bcdUSB[0], 0, 0);
1382 	DPRINTFN(15, "bDeviceClass        %5ju", udd->bDeviceClass, 0, 0, 0);
1383 	DPRINTFN(15, "bDeviceSubClass     %5ju", udd->bDeviceSubClass, 0, 0, 0);
1384 	DPRINTFN(15, "bDeviceProtocol     %5ju", udd->bDeviceProtocol, 0, 0, 0);
1385 	DPRINTFN(15, "bMaxPacketSize0     %5ju", udd->bMaxPacketSize, 0, 0, 0);
1386 	DPRINTFN(15, "idVendor            %#02jx %#02jx",
1387 						    udd->idVendor[0],
1388 						    udd->idVendor[1], 0, 0);
1389 	DPRINTFN(15, "idProduct           %#02jx %#02jx",
1390 						    udd->idProduct[0],
1391 						    udd->idProduct[1], 0, 0);
1392 	DPRINTFN(15, "bcdDevice           %2jx.%02jx", udd->bcdDevice[1],
1393 	    udd->bcdDevice[0], 0, 0);
1394 	DPRINTFN(15, "iManufacturer       %5ju", udd->iManufacturer, 0, 0, 0);
1395 	DPRINTFN(15, "iProduct            %5ju", udd->iProduct, 0, 0, 0);
1396 	DPRINTFN(15, "iSerial             %5ju", udd->iSerialNumber, 0, 0, 0);
1397 	DPRINTFN(15, "bNumConfigurations  %5ju", udd->bNumConfigurations, 0, 0,
1398 	    0);
1399 
1400 	/* Figure out what's wrong with this device. */
1401 	dev->ud_quirks = usbd_find_quirk(udd);
1402 
1403 	return USBD_NORMAL_COMPLETION;
1404 }
1405 
1406 void
1407 usbd_remove_device(struct usbd_device *dev, struct usbd_port *up)
1408 {
1409 
1410 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
1411 
1412 	DPRINTF("dev %#jx up %#jx", (uintptr_t)dev, (uintptr_t)up, 0, 0);
1413 
1414 	if (dev->ud_pipe0 != NULL)
1415 		usbd_kill_pipe(dev->ud_pipe0);
1416 	up->up_dev = NULL;
1417 	dev->ud_bus->ub_devices[usb_addr2dindex(dev->ud_addr)] = NULL;
1418 
1419 	kmem_free(dev, sizeof(*dev));
1420 }
1421 
1422 int
1423 usbd_print(void *aux, const char *pnp)
1424 {
1425 	struct usb_attach_arg *uaa = aux;
1426 
1427 	if (pnp) {
1428 #define USB_DEVINFO 1024
1429 		char *devinfo;
1430 		if (!uaa->uaa_usegeneric)
1431 			return QUIET;
1432 		devinfo = kmem_alloc(USB_DEVINFO, KM_SLEEP);
1433 		usbd_devinfo(uaa->uaa_device, 1, devinfo, USB_DEVINFO);
1434 		aprint_normal("%s, %s", devinfo, pnp);
1435 		kmem_free(devinfo, USB_DEVINFO);
1436 	}
1437 	aprint_normal(" port %d", uaa->uaa_port);
1438 #if 0
1439 	/*
1440 	 * It gets very crowded with these locators on the attach line.
1441 	 * They are not really needed since they are printed in the clear
1442 	 * by each driver.
1443 	 */
1444 	if (uaa->uaa_vendor != UHUB_UNK_VENDOR)
1445 		aprint_normal(" vendor %#04x", uaa->uaa_vendor);
1446 	if (uaa->uaa_product != UHUB_UNK_PRODUCT)
1447 		aprint_normal(" product %#04x", uaa->uaa_product);
1448 	if (uaa->uaa_release != UHUB_UNK_RELEASE)
1449 		aprint_normal(" release %#04x", uaa->uaa_release);
1450 #endif
1451 	return UNCONF;
1452 }
1453 
1454 int
1455 usbd_ifprint(void *aux, const char *pnp)
1456 {
1457 	struct usbif_attach_arg *uiaa = aux;
1458 
1459 	if (pnp)
1460 		return QUIET;
1461 	aprint_normal(" port %d", uiaa->uiaa_port);
1462 	aprint_normal(" configuration %d", uiaa->uiaa_configno);
1463 	aprint_normal(" interface %d", uiaa->uiaa_ifaceno);
1464 #if 0
1465 	/*
1466 	 * It gets very crowded with these locators on the attach line.
1467 	 * They are not really needed since they are printed in the clear
1468 	 * by each driver.
1469 	 */
1470 	if (uaa->uaa_vendor != UHUB_UNK_VENDOR)
1471 		aprint_normal(" vendor %#04x", uaa->uaa_vendor);
1472 	if (uaa->uaa_product != UHUB_UNK_PRODUCT)
1473 		aprint_normal(" product %#04x", uaa->uaa_product);
1474 	if (uaa->uaa_release != UHUB_UNK_RELEASE)
1475 		aprint_normal(" release %#04x", uaa->uaa_release);
1476 #endif
1477 	return UNCONF;
1478 }
1479 
1480 void
1481 usbd_fill_deviceinfo(struct usbd_device *dev, struct usb_device_info *di,
1482 		     int usedev)
1483 {
1484 	struct usbd_port *p;
1485 	int i, j, err;
1486 
1487 	di->udi_bus = device_unit(dev->ud_bus->ub_usbctl);
1488 	di->udi_addr = dev->ud_addr;
1489 	di->udi_cookie = dev->ud_cookie;
1490 	usbd_devinfo_vp(dev, di->udi_vendor, sizeof(di->udi_vendor),
1491 	    di->udi_product, sizeof(di->udi_product), usedev, 1);
1492 	usbd_printBCD(di->udi_release, sizeof(di->udi_release),
1493 	    UGETW(dev->ud_ddesc.bcdDevice));
1494 	if (usedev) {
1495 		usbd_status uerr = usbd_get_string(dev,
1496 		    dev->ud_ddesc.iSerialNumber, di->udi_serial);
1497 		if (uerr != USBD_NORMAL_COMPLETION) {
1498 			di->udi_serial[0] = '\0';
1499 		} else {
1500 			usbd_trim_spaces(di->udi_serial);
1501 		}
1502 	} else {
1503 		di->udi_serial[0] = '\0';
1504 		if (dev->ud_serial) {
1505 			strlcpy(di->udi_serial, dev->ud_serial,
1506 			    sizeof(di->udi_serial));
1507 		}
1508 	}
1509 
1510 	di->udi_vendorNo = UGETW(dev->ud_ddesc.idVendor);
1511 	di->udi_productNo = UGETW(dev->ud_ddesc.idProduct);
1512 	di->udi_releaseNo = UGETW(dev->ud_ddesc.bcdDevice);
1513 	di->udi_class = dev->ud_ddesc.bDeviceClass;
1514 	di->udi_subclass = dev->ud_ddesc.bDeviceSubClass;
1515 	di->udi_protocol = dev->ud_ddesc.bDeviceProtocol;
1516 	di->udi_config = dev->ud_config;
1517 	di->udi_power = dev->ud_selfpowered ? 0 : dev->ud_power;
1518 	di->udi_speed = dev->ud_speed;
1519 
1520 	if (dev->ud_subdevlen > 0) {
1521 		for (i = 0, j = 0; i < dev->ud_subdevlen &&
1522 			     j < USB_MAX_DEVNAMES; i++) {
1523 			if (!dev->ud_subdevs[i])
1524 				continue;
1525 			strncpy(di->udi_devnames[j],
1526 			    device_xname(dev->ud_subdevs[i]), USB_MAX_DEVNAMELEN);
1527 			di->udi_devnames[j][USB_MAX_DEVNAMELEN-1] = '\0';
1528 			j++;
1529 		}
1530 	} else {
1531 		j = 0;
1532 	}
1533 	for (/* j is set */; j < USB_MAX_DEVNAMES; j++)
1534 		di->udi_devnames[j][0] = 0;                 /* empty */
1535 
1536 	if (!dev->ud_hub) {
1537 		di->udi_nports = 0;
1538 		return;
1539 	}
1540 
1541 	const int nports = dev->ud_hub->uh_hubdesc.bNbrPorts;
1542 	for (i = 0; i < __arraycount(di->udi_ports) && i < nports; i++) {
1543 		p = &dev->ud_hub->uh_ports[i];
1544 		if (p->up_dev)
1545 			err = p->up_dev->ud_addr;
1546 		else {
1547 			const int s = UGETW(p->up_status.wPortStatus);
1548 			const bool sshub_p = USB_IS_SS(dev->ud_speed);
1549 			if (s & UPS_PORT_ENABLED)
1550 				err = USB_PORT_ENABLED;
1551 			else if (s & UPS_SUSPEND)
1552 				err = USB_PORT_SUSPENDED;
1553 			/*
1554 			 * Note: UPS_PORT_POWER_SS is available only
1555 			 * on 3.x, and UPS_PORT_POWER is available
1556 			 * only on 2.0 or 1.1.
1557 			 */
1558 			else if (sshub_p && (s & UPS_PORT_POWER_SS))
1559 				err = USB_PORT_POWERED;
1560 			else if (!sshub_p && (s & UPS_PORT_POWER))
1561 				err = USB_PORT_POWERED;
1562 			else
1563 				err = USB_PORT_DISABLED;
1564 		}
1565 		di->udi_ports[i] = err;
1566 	}
1567 	di->udi_nports = nports;
1568 }
1569 
1570 #ifdef COMPAT_30
1571 void
1572 usbd_fill_deviceinfo_old(struct usbd_device *dev, struct usb_device_info_old *di,
1573                          int usedev)
1574 {
1575 	struct usbd_port *p;
1576 	int i, j, err;
1577 
1578 	di->udi_bus = device_unit(dev->ud_bus->ub_usbctl);
1579 	di->udi_addr = dev->ud_addr;
1580 	di->udi_cookie = dev->ud_cookie;
1581 	usbd_devinfo_vp(dev, di->udi_vendor, sizeof(di->udi_vendor),
1582 	    di->udi_product, sizeof(di->udi_product), usedev, 0);
1583 	usbd_printBCD(di->udi_release, sizeof(di->udi_release),
1584 	    UGETW(dev->ud_ddesc.bcdDevice));
1585 	di->udi_vendorNo = UGETW(dev->ud_ddesc.idVendor);
1586 	di->udi_productNo = UGETW(dev->ud_ddesc.idProduct);
1587 	di->udi_releaseNo = UGETW(dev->ud_ddesc.bcdDevice);
1588 	di->udi_class = dev->ud_ddesc.bDeviceClass;
1589 	di->udi_subclass = dev->ud_ddesc.bDeviceSubClass;
1590 	di->udi_protocol = dev->ud_ddesc.bDeviceProtocol;
1591 	di->udi_config = dev->ud_config;
1592 	di->udi_power = dev->ud_selfpowered ? 0 : dev->ud_power;
1593 	di->udi_speed = dev->ud_speed;
1594 
1595 	if (dev->ud_subdevlen > 0) {
1596 		for (i = 0, j = 0; i < dev->ud_subdevlen &&
1597 			     j < USB_MAX_DEVNAMES; i++) {
1598 			if (!dev->ud_subdevs[i])
1599 				continue;
1600 			strncpy(di->udi_devnames[j],
1601 			    device_xname(dev->ud_subdevs[i]), USB_MAX_DEVNAMELEN);
1602 			di->udi_devnames[j][USB_MAX_DEVNAMELEN-1] = '\0';
1603 			j++;
1604 		}
1605 	} else {
1606 		j = 0;
1607 	}
1608 	for (/* j is set */; j < USB_MAX_DEVNAMES; j++)
1609 		di->udi_devnames[j][0] = 0;		 /* empty */
1610 
1611 	if (!dev->ud_hub) {
1612 		di->udi_nports = 0;
1613 		return;
1614 	}
1615 
1616 	const int nports = dev->ud_hub->uh_hubdesc.bNbrPorts;
1617 	for (i = 0; i < __arraycount(di->udi_ports) && i < nports;
1618 	     i++) {
1619 		p = &dev->ud_hub->uh_ports[i];
1620 		if (p->up_dev)
1621 			err = p->up_dev->ud_addr;
1622 		else {
1623 			const int s = UGETW(p->up_status.wPortStatus);
1624 			if (s & UPS_PORT_ENABLED)
1625 				err = USB_PORT_ENABLED;
1626 			else if (s & UPS_SUSPEND)
1627 				err = USB_PORT_SUSPENDED;
1628 			else if (s & UPS_PORT_POWER)
1629 				err = USB_PORT_POWERED;
1630 			else
1631 				err = USB_PORT_DISABLED;
1632 		}
1633 		di->udi_ports[i] = err;
1634 	}
1635 	di->udi_nports = nports;
1636 }
1637 #endif
1638 
1639 
1640 void
1641 usb_free_device(struct usbd_device *dev)
1642 {
1643 	int ifcidx, nifc;
1644 
1645 	if (dev->ud_pipe0 != NULL)
1646 		usbd_kill_pipe(dev->ud_pipe0);
1647 	if (dev->ud_ifaces != NULL) {
1648 		nifc = dev->ud_cdesc->bNumInterface;
1649 		for (ifcidx = 0; ifcidx < nifc; ifcidx++)
1650 			usbd_free_iface_data(dev, ifcidx);
1651 		kmem_free(dev->ud_ifaces,
1652 		    nifc * sizeof(struct usbd_interface));
1653 	}
1654 	if (dev->ud_cdesc != NULL)
1655 		kmem_free(dev->ud_cdesc, UGETW(dev->ud_cdesc->wTotalLength));
1656 	if (dev->ud_bdesc != NULL)
1657 		kmem_free(dev->ud_bdesc, UGETW(dev->ud_bdesc->wTotalLength));
1658 	if (dev->ud_subdevlen > 0) {
1659 		kmem_free(dev->ud_subdevs,
1660 		    dev->ud_subdevlen * sizeof(device_t));
1661 		dev->ud_subdevlen = 0;
1662 	}
1663 	if (dev->ud_vendor) {
1664 		kmem_free(dev->ud_vendor, USB_MAX_ENCODED_STRING_LEN);
1665 	}
1666 	if (dev->ud_product) {
1667 		kmem_free(dev->ud_product, USB_MAX_ENCODED_STRING_LEN);
1668 	}
1669 	if (dev->ud_serial) {
1670 		kmem_free(dev->ud_serial, USB_MAX_ENCODED_STRING_LEN);
1671 	}
1672 	kmem_free(dev, sizeof(*dev));
1673 }
1674 
1675 /*
1676  * The general mechanism for detaching drivers works as follows: Each
1677  * driver is responsible for maintaining a reference count on the
1678  * number of outstanding references to its softc (e.g.  from
1679  * processing hanging in a read or write).  The detach method of the
1680  * driver decrements this counter and flags in the softc that the
1681  * driver is dying and then wakes any sleepers.  It then sleeps on the
1682  * softc.  Each place that can sleep must maintain the reference
1683  * count.  When the reference count drops to -1 (0 is the normal value
1684  * of the reference count) the a wakeup on the softc is performed
1685  * signaling to the detach waiter that all references are gone.
1686  */
1687 
1688 /*
1689  * Called from process context when we discover that a port has
1690  * been disconnected.
1691  */
1692 int
1693 usb_disconnect_port(struct usbd_port *up, device_t parent, int flags)
1694 {
1695 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
1696 	struct usbd_device *dev = up->up_dev;
1697 	device_t subdev;
1698 	char subdevname[16];
1699 	const char *hubname = device_xname(parent);
1700 	int i, rc;
1701 
1702 	DPRINTFN(3, "up=%#jx dev=%#jx port=%jd", (uintptr_t)up, (uintptr_t)dev,
1703 	    up->up_portno, 0);
1704 
1705 	if (dev == NULL) {
1706 		return 0;
1707 	}
1708 
1709 	if (dev->ud_subdevlen > 0) {
1710 		DPRINTFN(3, "disconnect subdevs", 0, 0, 0, 0);
1711 		for (i = 0; i < dev->ud_subdevlen; i++) {
1712 			if ((subdev = dev->ud_subdevs[i]) == NULL)
1713 				continue;
1714 			strlcpy(subdevname, device_xname(subdev),
1715 			    sizeof(subdevname));
1716 			if ((rc = config_detach(subdev, flags)) != 0)
1717 				return rc;
1718 			printf("%s: at %s", subdevname, hubname);
1719 			if (up->up_portno != 0)
1720 				printf(" port %d", up->up_portno);
1721 			printf(" (addr %d) disconnected\n", dev->ud_addr);
1722 		}
1723 		KASSERT(!dev->ud_nifaces_claimed);
1724 	}
1725 
1726 	mutex_enter(dev->ud_bus->ub_lock);
1727 	dev->ud_bus->ub_devices[usb_addr2dindex(dev->ud_addr)] = NULL;
1728 	up->up_dev = NULL;
1729 	mutex_exit(dev->ud_bus->ub_lock);
1730 
1731 	usbd_add_dev_event(USB_EVENT_DEVICE_DETACH, dev);
1732 
1733 	usb_free_device(dev);
1734 
1735 	return 0;
1736 }
1737