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