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