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