Home | History | Annotate | Line # | Download | only in usb
usb_subr.c revision 1.257
      1 /*	$NetBSD: usb_subr.c,v 1.257 2021/06/12 15:39:46 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.257 2021/06/12 15:39:46 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 the device control pipe. */
    904 void
    905 usbd_kill_pipe(struct usbd_pipe *pipe)
    906 {
    907 	usbd_abort_pipe(pipe);
    908 	usbd_lock_pipe(pipe);
    909 	pipe->up_methods->upm_close(pipe);
    910 	usbd_unlock_pipe(pipe);
    911 	usb_rem_task_wait(pipe->up_dev, &pipe->up_async_task, USB_TASKQ_DRIVER,
    912 	    NULL);
    913 	KASSERT(pipe->up_iface == NULL);
    914 	usbd_endpoint_release(pipe->up_dev, pipe->up_endpoint);
    915 	kmem_free(pipe, pipe->up_dev->ud_bus->ub_pipesize);
    916 }
    917 
    918 int
    919 usbd_getnewaddr(struct usbd_bus *bus)
    920 {
    921 	int addr;
    922 
    923 	for (addr = 1; addr < USB_MAX_DEVICES; addr++) {
    924 		size_t dindex = usb_addr2dindex(addr);
    925 		if (bus->ub_devices[dindex] == NULL)
    926 			return addr;
    927 	}
    928 	return -1;
    929 }
    930 
    931 usbd_status
    932 usbd_attach_roothub(device_t parent, struct usbd_device *dev)
    933 {
    934 	struct usb_attach_arg uaa;
    935 	usb_device_descriptor_t *dd = &dev->ud_ddesc;
    936 	device_t dv;
    937 
    938 	uaa.uaa_device = dev;
    939 	uaa.uaa_usegeneric = 0;
    940 	uaa.uaa_port = 0;
    941 	uaa.uaa_vendor = UGETW(dd->idVendor);
    942 	uaa.uaa_product = UGETW(dd->idProduct);
    943 	uaa.uaa_release = UGETW(dd->bcdDevice);
    944 	uaa.uaa_class = dd->bDeviceClass;
    945 	uaa.uaa_subclass = dd->bDeviceSubClass;
    946 	uaa.uaa_proto = dd->bDeviceProtocol;
    947 
    948 	KERNEL_LOCK(1, curlwp);
    949 	dv = config_found(parent, &uaa, NULL,
    950 	    CFARG_IATTR, "usbroothubif",
    951 	    CFARG_EOL);
    952 	KERNEL_UNLOCK_ONE(curlwp);
    953 	if (dv) {
    954 		dev->ud_subdevs = kmem_alloc(sizeof(dv), KM_SLEEP);
    955 		dev->ud_subdevs[0] = dv;
    956 		dev->ud_subdevlen = 1;
    957 	}
    958 	return USBD_NORMAL_COMPLETION;
    959 }
    960 
    961 static void
    962 usbd_properties(device_t dv, struct usbd_device *dev)
    963 {
    964 	usb_device_descriptor_t *dd = &dev->ud_ddesc;
    965 	prop_dictionary_t dict = device_properties(dv);
    966 	int class, subclass, release, proto, vendor, product;
    967 
    968 	class = dd->bDeviceClass;
    969 	subclass = dd->bDeviceSubClass;
    970 	release = UGETW(dd->bcdDevice);
    971 	proto = dd->bDeviceProtocol;
    972 	vendor = UGETW(dd->idVendor);
    973 	product = UGETW(dd->idProduct);
    974 
    975 	prop_dictionary_set_uint16(dict, "class", class);
    976 	prop_dictionary_set_uint16(dict, "subclass", subclass);
    977 	prop_dictionary_set_uint16(dict, "release", release);
    978 	prop_dictionary_set_uint16(dict, "proto", proto);
    979 	prop_dictionary_set_uint16(dict, "vendor", vendor);
    980 	prop_dictionary_set_uint16(dict, "product", product);
    981 
    982 	if (dev->ud_vendor) {
    983 		prop_dictionary_set_string(dict,
    984 		    "vendor-string", dev->ud_vendor);
    985 	}
    986 	if (dev->ud_product) {
    987 		prop_dictionary_set_string(dict,
    988 		    "product-string", dev->ud_product);
    989 	}
    990 	if (dev->ud_serial) {
    991 		prop_dictionary_set_string(dict,
    992 		    "serialnumber", dev->ud_serial);
    993 	}
    994 }
    995 
    996 static usbd_status
    997 usbd_attachwholedevice(device_t parent, struct usbd_device *dev, int port,
    998 	int usegeneric)
    999 {
   1000 	struct usb_attach_arg uaa;
   1001 	usb_device_descriptor_t *dd = &dev->ud_ddesc;
   1002 	device_t dv;
   1003 	int dlocs[USBDEVIFCF_NLOCS];
   1004 
   1005 	uaa.uaa_device = dev;
   1006 	uaa.uaa_usegeneric = usegeneric;
   1007 	uaa.uaa_port = port;
   1008 	uaa.uaa_vendor = UGETW(dd->idVendor);
   1009 	uaa.uaa_product = UGETW(dd->idProduct);
   1010 	uaa.uaa_release = UGETW(dd->bcdDevice);
   1011 	uaa.uaa_class = dd->bDeviceClass;
   1012 	uaa.uaa_subclass = dd->bDeviceSubClass;
   1013 	uaa.uaa_proto = dd->bDeviceProtocol;
   1014 
   1015 	dlocs[USBDEVIFCF_PORT] = uaa.uaa_port;
   1016 	dlocs[USBDEVIFCF_VENDOR] = uaa.uaa_vendor;
   1017 	dlocs[USBDEVIFCF_PRODUCT] = uaa.uaa_product;
   1018 	dlocs[USBDEVIFCF_RELEASE] = uaa.uaa_release;
   1019 	/* the rest is historical ballast */
   1020 	dlocs[USBDEVIFCF_CONFIGURATION] = -1;
   1021 	dlocs[USBDEVIFCF_INTERFACE] = -1;
   1022 
   1023 	KERNEL_LOCK(1, curlwp);
   1024 	config_pending_incr(parent);
   1025 	dv = config_found(parent, &uaa, usbd_print,
   1026 			  CFARG_SUBMATCH, config_stdsubmatch,
   1027 			  CFARG_IATTR, "usbdevif",
   1028 			  CFARG_LOCATORS, dlocs,
   1029 			  CFARG_EOL);
   1030 	KERNEL_UNLOCK_ONE(curlwp);
   1031 	if (dv) {
   1032 		dev->ud_subdevs = kmem_alloc(sizeof(dv), KM_SLEEP);
   1033 		dev->ud_subdevs[0] = dv;
   1034 		dev->ud_subdevlen = 1;
   1035 		dev->ud_nifaces_claimed = 1; /* XXX */
   1036 		usbd_properties(dv, dev);
   1037 	}
   1038 	config_pending_decr(parent);
   1039 	return USBD_NORMAL_COMPLETION;
   1040 }
   1041 
   1042 static usbd_status
   1043 usbd_attachinterfaces(device_t parent, struct usbd_device *dev,
   1044 		      int port, const int *locators)
   1045 {
   1046 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
   1047 	struct usbif_attach_arg uiaa;
   1048 	int ilocs[USBIFIFCF_NLOCS];
   1049 	usb_device_descriptor_t *dd = &dev->ud_ddesc;
   1050 	int nifaces;
   1051 	struct usbd_interface **ifaces;
   1052 	int i, j, loc;
   1053 	device_t dv;
   1054 
   1055 	/* Needed for access to dev->ud_subdevs.  */
   1056 	KASSERT(KERNEL_LOCKED_P());
   1057 
   1058 	nifaces = dev->ud_cdesc->bNumInterface;
   1059 	ifaces = kmem_zalloc(nifaces * sizeof(*ifaces), KM_SLEEP);
   1060 	for (i = 0; i < nifaces; i++) {
   1061 		if (!dev->ud_subdevs[i]) {
   1062 			ifaces[i] = &dev->ud_ifaces[i];
   1063 		}
   1064 		DPRINTF("interface %jd %#jx", i, (uintptr_t)ifaces[i], 0, 0);
   1065 	}
   1066 
   1067 
   1068 	uiaa.uiaa_device = dev;
   1069 	uiaa.uiaa_port = port;
   1070 	uiaa.uiaa_vendor = UGETW(dd->idVendor);
   1071 	uiaa.uiaa_product = UGETW(dd->idProduct);
   1072 	uiaa.uiaa_release = UGETW(dd->bcdDevice);
   1073 	uiaa.uiaa_configno = dev->ud_cdesc->bConfigurationValue;
   1074 	uiaa.uiaa_ifaces = ifaces;
   1075 	uiaa.uiaa_nifaces = nifaces;
   1076 	ilocs[USBIFIFCF_PORT] = uiaa.uiaa_port;
   1077 	ilocs[USBIFIFCF_VENDOR] = uiaa.uiaa_vendor;
   1078 	ilocs[USBIFIFCF_PRODUCT] = uiaa.uiaa_product;
   1079 	ilocs[USBIFIFCF_RELEASE] = uiaa.uiaa_release;
   1080 	ilocs[USBIFIFCF_CONFIGURATION] = uiaa.uiaa_configno;
   1081 
   1082 	for (i = 0; i < nifaces; i++) {
   1083 		if (!ifaces[i]) {
   1084 			DPRINTF("interface %jd claimed", i, 0, 0, 0);
   1085 			continue; /* interface already claimed */
   1086 		}
   1087 		uiaa.uiaa_iface = ifaces[i];
   1088 		uiaa.uiaa_class = ifaces[i]->ui_idesc->bInterfaceClass;
   1089 		uiaa.uiaa_subclass = ifaces[i]->ui_idesc->bInterfaceSubClass;
   1090 		uiaa.uiaa_proto = ifaces[i]->ui_idesc->bInterfaceProtocol;
   1091 		uiaa.uiaa_ifaceno = ifaces[i]->ui_idesc->bInterfaceNumber;
   1092 
   1093 		DPRINTF("searching for interface %jd...", i, 0, 0, 0);
   1094 		DPRINTF("class %jx subclass %jx proto %jx ifaceno %jd",
   1095 		    uiaa.uiaa_class, uiaa.uiaa_subclass, uiaa.uiaa_proto,
   1096 		    uiaa.uiaa_ifaceno);
   1097 		ilocs[USBIFIFCF_INTERFACE] = uiaa.uiaa_ifaceno;
   1098 		if (locators != NULL) {
   1099 			loc = locators[USBIFIFCF_CONFIGURATION];
   1100 			if (loc != USBIFIFCF_CONFIGURATION_DEFAULT &&
   1101 			    loc != uiaa.uiaa_configno)
   1102 				continue;
   1103 			loc = locators[USBIFIFCF_INTERFACE];
   1104 			if (loc != USBIFIFCF_INTERFACE_DEFAULT &&
   1105 			    loc != uiaa.uiaa_ifaceno)
   1106 				continue;
   1107 		}
   1108 		KERNEL_LOCK(1, curlwp);
   1109 		dv = config_found(parent, &uiaa, usbd_ifprint,
   1110 				  CFARG_SUBMATCH, config_stdsubmatch,
   1111 				  CFARG_IATTR, "usbifif",
   1112 				  CFARG_LOCATORS, ilocs,
   1113 				  CFARG_EOL);
   1114 		KERNEL_UNLOCK_ONE(curlwp);
   1115 		if (!dv)
   1116 			continue;
   1117 
   1118 		usbd_properties(dv, dev);
   1119 
   1120 		/* claim */
   1121 		ifaces[i] = NULL;
   1122 		/* account for ifaces claimed by the driver behind our back */
   1123 		for (j = 0; j < nifaces; j++) {
   1124 
   1125 			if (!ifaces[j] && !dev->ud_subdevs[j]) {
   1126 				DPRINTF("interface %jd claimed behind our back",
   1127 				    j, 0, 0, 0);
   1128 				dev->ud_subdevs[j] = dv;
   1129 				dev->ud_nifaces_claimed++;
   1130 			}
   1131 		}
   1132 	}
   1133 
   1134 	kmem_free(ifaces, nifaces * sizeof(*ifaces));
   1135 	return USBD_NORMAL_COMPLETION;
   1136 }
   1137 
   1138 usbd_status
   1139 usbd_probe_and_attach(device_t parent, struct usbd_device *dev,
   1140                       int port, int addr)
   1141 {
   1142 	USBHIST_FUNC();
   1143 	USBHIST_CALLARGS(usbdebug, "trying device specific drivers", 0, 0, 0, 0);
   1144 	usb_device_descriptor_t *dd = &dev->ud_ddesc;
   1145 	int confi, nifaces;
   1146 	usbd_status err;
   1147 
   1148 	KASSERT(KERNEL_LOCKED_P());
   1149 
   1150 	/* First try with device specific drivers. */
   1151 	err = usbd_attachwholedevice(parent, dev, port, 0);
   1152 	if (dev->ud_nifaces_claimed || err)
   1153 		return err;
   1154 	DPRINTF("no device specific driver found", 0, 0, 0, 0);
   1155 
   1156 	DPRINTF("looping over %jd configurations", dd->bNumConfigurations,
   1157 	    0, 0, 0);
   1158 	for (confi = 0; confi < dd->bNumConfigurations; confi++) {
   1159 		DPRINTFN(1, "trying config idx=%jd", confi, 0, 0, 0);
   1160 		err = usbd_set_config_index(dev, confi, 1);
   1161 		if (err) {
   1162 			DPRINTF("port %jd, set config at addr %jd failed, "
   1163 			    "error=%jd", port, addr, err, 0);
   1164 			printf("%s: port %d, set config at addr %d failed\n",
   1165 			    device_xname(parent), port, addr);
   1166 			return err;
   1167 		}
   1168 		nifaces = dev->ud_cdesc->bNumInterface;
   1169 		dev->ud_subdevs = kmem_zalloc(nifaces * sizeof(device_t),
   1170 		    KM_SLEEP);
   1171 		dev->ud_subdevlen = nifaces;
   1172 
   1173 		err = usbd_attachinterfaces(parent, dev, port, NULL);
   1174 
   1175 		if (dev->ud_subdevs && dev->ud_nifaces_claimed == 0) {
   1176 			kmem_free(dev->ud_subdevs,
   1177 			    dev->ud_subdevlen * sizeof(device_t));
   1178 			dev->ud_subdevs = 0;
   1179 			dev->ud_subdevlen = 0;
   1180 		}
   1181 		if (dev->ud_nifaces_claimed || err)
   1182 			return err;
   1183 	}
   1184 	/* No interfaces were attached in any of the configurations. */
   1185 
   1186 	if (dd->bNumConfigurations > 1) /* don't change if only 1 config */
   1187 		usbd_set_config_index(dev, 0, 0);
   1188 
   1189 	DPRINTF("no interface drivers found", 0, 0, 0, 0);
   1190 
   1191 	/* Finally try the generic driver. */
   1192 	err = usbd_attachwholedevice(parent, dev, port, 1);
   1193 
   1194 	/*
   1195 	 * The generic attach failed, but leave the device as it is.
   1196 	 * We just did not find any drivers, that's all.  The device is
   1197 	 * fully operational and not harming anyone.
   1198 	 */
   1199 	DPRINTF("generic attach failed", 0, 0, 0, 0);
   1200 
   1201 	return USBD_NORMAL_COMPLETION;
   1202 }
   1203 
   1204 /**
   1205  * Called from uhub_rescan().  usbd_new_device() for the target dev must be
   1206  * called before calling this.
   1207  */
   1208 usbd_status
   1209 usbd_reattach_device(device_t parent, struct usbd_device *dev,
   1210                      int port, const int *locators)
   1211 {
   1212 	int i, loc;
   1213 
   1214 	USBHIST_FUNC();
   1215 	USBHIST_CALLARGS(usbdebug, "uhub%jd port=%jd",
   1216 	    device_unit(parent), port, 0, 0);
   1217 
   1218 	KASSERT(KERNEL_LOCKED_P());
   1219 
   1220 	if (locators != NULL) {
   1221 		loc = locators[USBIFIFCF_PORT];
   1222 		if (loc != USBIFIFCF_PORT_DEFAULT && loc != port)
   1223 			return USBD_NORMAL_COMPLETION;
   1224 		loc = locators[USBIFIFCF_VENDOR];
   1225 		if (loc != USBIFIFCF_VENDOR_DEFAULT &&
   1226 		    loc != UGETW(dev->ud_ddesc.idVendor))
   1227 			return USBD_NORMAL_COMPLETION;
   1228 		loc = locators[USBIFIFCF_PRODUCT];
   1229 		if (loc != USBIFIFCF_PRODUCT_DEFAULT &&
   1230 		    loc != UGETW(dev->ud_ddesc.idProduct))
   1231 			return USBD_NORMAL_COMPLETION;
   1232 		loc = locators[USBIFIFCF_RELEASE];
   1233 		if (loc != USBIFIFCF_RELEASE_DEFAULT &&
   1234 		    loc != UGETW(dev->ud_ddesc.bcdDevice))
   1235 			return USBD_NORMAL_COMPLETION;
   1236 	}
   1237 	if (dev->ud_subdevlen == 0) {
   1238 		/* XXX: check USBIFIFCF_CONFIGURATION and
   1239 		 * USBIFIFCF_INTERFACE too */
   1240 		return usbd_probe_and_attach(parent, dev, port, dev->ud_addr);
   1241 	} else if (dev->ud_subdevlen != dev->ud_cdesc->bNumInterface) {
   1242 		/* device-specific or generic driver is already attached. */
   1243 		return USBD_NORMAL_COMPLETION;
   1244 	}
   1245 	/* Does the device have unconfigured interfaces? */
   1246 	for (i = 0; i < dev->ud_subdevlen; i++) {
   1247 		if (dev->ud_subdevs[i] == NULL) {
   1248 			break;
   1249 		}
   1250 	}
   1251 	if (i >= dev->ud_subdevlen)
   1252 		return USBD_NORMAL_COMPLETION;
   1253 	return usbd_attachinterfaces(parent, dev, port, locators);
   1254 }
   1255 
   1256 /*
   1257  * Called when a new device has been put in the powered state,
   1258  * but not yet in the addressed state.
   1259  * Get initial descriptor, set the address, get full descriptor,
   1260  * and attach a driver.
   1261  */
   1262 usbd_status
   1263 usbd_new_device(device_t parent, struct usbd_bus *bus, int depth, int speed,
   1264     int port, struct usbd_port *up)
   1265 {
   1266 	USBHIST_FUNC();
   1267 	USBHIST_CALLARGS(usbdebug, "bus=%#jx port=%jd depth=%jd speed=%jd",
   1268 	    (uintptr_t)bus, port, depth, speed);
   1269 	struct usbd_device *dev, *adev;
   1270 	struct usbd_device *hub;
   1271 	usb_device_descriptor_t *dd;
   1272 	usb_port_status_t ps;
   1273 	usbd_status err;
   1274 	int addr;
   1275 	int i;
   1276 	int p;
   1277 
   1278 	KASSERT(KERNEL_LOCKED_P());
   1279 
   1280 	if (bus->ub_methods->ubm_newdev != NULL)
   1281 		return (bus->ub_methods->ubm_newdev)(parent, bus, depth, speed,
   1282 		    port, up);
   1283 
   1284 	addr = usbd_getnewaddr(bus);
   1285 	if (addr < 0) {
   1286 		printf("%s: No free USB addresses, new device ignored.\n",
   1287 		       device_xname(bus->ub_usbctl));
   1288 		return USBD_NO_ADDR;
   1289 	}
   1290 
   1291 	dev = kmem_zalloc(sizeof(*dev), KM_SLEEP);
   1292 	dev->ud_bus = bus;
   1293 
   1294 	/* Set up default endpoint handle. */
   1295 	dev->ud_ep0.ue_edesc = &dev->ud_ep0desc;
   1296 
   1297 	/* Set up default endpoint descriptor. */
   1298 	dev->ud_ep0desc.bLength = USB_ENDPOINT_DESCRIPTOR_SIZE;
   1299 	dev->ud_ep0desc.bDescriptorType = UDESC_ENDPOINT;
   1300 	dev->ud_ep0desc.bEndpointAddress = USB_CONTROL_ENDPOINT;
   1301 	dev->ud_ep0desc.bmAttributes = UE_CONTROL;
   1302 	/*
   1303 	 * temporary, will be fixed after first descriptor fetch
   1304 	 * (which uses 64 bytes so it shouldn't be less),
   1305 	 * highspeed devices must support 64 byte packets anyway
   1306 	 */
   1307 	if (speed == USB_SPEED_HIGH || speed == USB_SPEED_FULL)
   1308 		USETW(dev->ud_ep0desc.wMaxPacketSize, 64);
   1309 	else
   1310 		USETW(dev->ud_ep0desc.wMaxPacketSize, USB_MAX_IPACKET);
   1311 
   1312 	dev->ud_ep0desc.bInterval = 0;
   1313 
   1314 	/* doesn't matter, just don't leave it uninitialized */
   1315 	dev->ud_ep0.ue_toggle = 0;
   1316 
   1317 	dev->ud_quirks = &usbd_no_quirk;
   1318 	dev->ud_addr = USB_START_ADDR;
   1319 	dev->ud_ddesc.bMaxPacketSize = 0;
   1320 	dev->ud_depth = depth;
   1321 	dev->ud_powersrc = up;
   1322 	dev->ud_myhub = up->up_parent;
   1323 
   1324 	up->up_dev = dev;
   1325 
   1326 	/* Locate port on upstream high speed hub */
   1327 	for (adev = dev, hub = up->up_parent;
   1328 	     hub != NULL && hub->ud_speed != USB_SPEED_HIGH;
   1329 	     adev = hub, hub = hub->ud_myhub)
   1330 		;
   1331 	if (hub) {
   1332 		for (p = 1; p <= hub->ud_hub->uh_hubdesc.bNbrPorts; p++) {
   1333 			if (hub->ud_hub->uh_ports[p - 1].up_dev == adev) {
   1334 				dev->ud_myhsport =
   1335 				    &hub->ud_hub->uh_ports[p - 1];
   1336 				goto found;
   1337 			}
   1338 		}
   1339 		panic("usbd_new_device: cannot find HS port");
   1340 	found:
   1341 		DPRINTFN(1, "high speed port %jd", p, 0, 0, 0);
   1342 	} else {
   1343 		dev->ud_myhsport = NULL;
   1344 	}
   1345 	dev->ud_speed = speed;
   1346 	dev->ud_langid = USBD_NOLANG;
   1347 	dev->ud_cookie.cookie = ++usb_cookie_no;
   1348 
   1349 	/* Establish the default pipe. */
   1350 	err = usbd_setup_pipe_flags(dev, 0, &dev->ud_ep0, USBD_DEFAULT_INTERVAL,
   1351 	    &dev->ud_pipe0, USBD_MPSAFE);
   1352 	if (err) {
   1353 		usbd_remove_device(dev, up);
   1354 		return err;
   1355 	}
   1356 
   1357 	dd = &dev->ud_ddesc;
   1358 	/* Try a few times in case the device is slow (i.e. outside specs.) */
   1359 	for (i = 0; i < 10; i++) {
   1360 		/* Get the first 8 bytes of the device descriptor. */
   1361 		err = usbd_get_initial_ddesc(dev, dd);
   1362 		if (!err)
   1363 			break;
   1364 		/*
   1365 		 * The root hub can never fail to give the initial descriptor,
   1366 		 * but assert it just in case.
   1367 		 */
   1368 		KASSERT(up->up_parent);
   1369 		usbd_delay_ms(dev, 200);
   1370 		if ((i & 3) == 3)
   1371 			usbd_reset_port(up->up_parent, port, &ps);
   1372 	}
   1373 	if (err) {
   1374 		DPRINTF("addr=%jd, getting first desc failed: %jd", addr, err,
   1375 		    0, 0);
   1376 		usbd_remove_device(dev, up);
   1377 		return err;
   1378 	}
   1379 
   1380 	/* Windows resets the port here, do likewise */
   1381 	if (up->up_parent)
   1382 		usbd_reset_port(up->up_parent, port, &ps);
   1383 
   1384 	if (speed == USB_SPEED_HIGH) {
   1385 		/* Max packet size must be 64 (sec 5.5.3). */
   1386 		if (dd->bMaxPacketSize != USB_2_MAX_CTRL_PACKET) {
   1387 #ifdef DIAGNOSTIC
   1388 			printf("usbd_new_device: addr=%d bad max packet "
   1389 			    "size=%d. adjusting to %d.\n",
   1390 			    addr, dd->bMaxPacketSize, USB_2_MAX_CTRL_PACKET);
   1391 #endif
   1392 			dd->bMaxPacketSize = USB_2_MAX_CTRL_PACKET;
   1393 		}
   1394 	}
   1395 
   1396 	DPRINTF("adding unit addr=%jd, rev=%02jx, class=%jd, subclass=%jd",
   1397 	    addr, UGETW(dd->bcdUSB), dd->bDeviceClass, dd->bDeviceSubClass);
   1398 	DPRINTF("protocol=%jd, maxpacket=%jd, len=%jd, speed=%jd",
   1399 	    dd->bDeviceProtocol, dd->bMaxPacketSize, dd->bLength, dev->ud_speed);
   1400 
   1401 	if (dd->bDescriptorType != UDESC_DEVICE) {
   1402 		/* Illegal device descriptor */
   1403 		DPRINTF("illegal descriptor %jd", dd->bDescriptorType, 0, 0, 0);
   1404 		usbd_remove_device(dev, up);
   1405 		return USBD_INVAL;
   1406 	}
   1407 
   1408 	if (dd->bLength < USB_DEVICE_DESCRIPTOR_SIZE) {
   1409 		DPRINTF("bad length %jd", dd->bLength, 0, 0, 0);
   1410 		usbd_remove_device(dev, up);
   1411 		return USBD_INVAL;
   1412 	}
   1413 
   1414 	USETW(dev->ud_ep0desc.wMaxPacketSize, dd->bMaxPacketSize);
   1415 
   1416 	/* Re-establish the default pipe with the new MPS. */
   1417 	usbd_kill_pipe(dev->ud_pipe0);
   1418 	dev->ud_pipe0 = NULL;
   1419 	err = usbd_setup_pipe_flags(dev, 0, &dev->ud_ep0, USBD_DEFAULT_INTERVAL,
   1420 	    &dev->ud_pipe0, USBD_MPSAFE);
   1421 	if (err) {
   1422 		DPRINTF("setup default pipe failed err %jd", err, 0, 0, 0);
   1423 		usbd_remove_device(dev, up);
   1424 		return err;
   1425 	}
   1426 
   1427 	/* Set the address */
   1428 	DPRINTFN(5, "setting device address=%jd", addr, 0, 0, 0);
   1429 	err = usbd_set_address(dev, addr);
   1430 	if (err) {
   1431 		DPRINTF("set address %jd failed, err = %jd", addr, err, 0, 0);
   1432 		err = USBD_SET_ADDR_FAILED;
   1433 		usbd_remove_device(dev, up);
   1434 		return err;
   1435 	}
   1436 
   1437 	/* Allow device time to set new address */
   1438 	usbd_delay_ms(dev, USB_SET_ADDRESS_SETTLE);
   1439 	dev->ud_addr = addr;	/* new device address now */
   1440 	bus->ub_devices[usb_addr2dindex(addr)] = dev;
   1441 
   1442 	/* Re-establish the default pipe with the new address. */
   1443 	usbd_kill_pipe(dev->ud_pipe0);
   1444 	dev->ud_pipe0 = NULL;
   1445 	err = usbd_setup_pipe_flags(dev, 0, &dev->ud_ep0, USBD_DEFAULT_INTERVAL,
   1446 	    &dev->ud_pipe0, USBD_MPSAFE);
   1447 	if (err) {
   1448 		DPRINTF("setup default pipe failed, err = %jd", err, 0, 0, 0);
   1449 		usbd_remove_device(dev, up);
   1450 		return err;
   1451 	}
   1452 
   1453 	err = usbd_reload_device_desc(dev);
   1454 	if (err) {
   1455 		DPRINTF("addr=%jd, getting full desc failed, err = %jd", addr,
   1456 		    err, 0, 0);
   1457 		usbd_remove_device(dev, up);
   1458 		return err;
   1459 	}
   1460 
   1461 	/* Assume 100mA bus powered for now. Changed when configured. */
   1462 	dev->ud_power = USB_MIN_POWER;
   1463 	dev->ud_selfpowered = 0;
   1464 
   1465 	DPRINTF("new dev (addr %jd), dev=%#jx, parent=%#jx",
   1466 	    addr, (uintptr_t)dev, (uintptr_t)parent, 0);
   1467 
   1468 	usbd_get_device_strings(dev);
   1469 
   1470 	usbd_add_dev_event(USB_EVENT_DEVICE_ATTACH, dev);
   1471 
   1472 	if (port == 0) { /* root hub */
   1473 		KASSERT(addr == 1);
   1474 		usbd_attach_roothub(parent, dev);
   1475 		return USBD_NORMAL_COMPLETION;
   1476 	}
   1477 
   1478 	err = usbd_probe_and_attach(parent, dev, port, addr);
   1479 	if (err) {
   1480 		usbd_remove_device(dev, up);
   1481 		return err;
   1482 	}
   1483 
   1484 	return USBD_NORMAL_COMPLETION;
   1485 }
   1486 
   1487 usbd_status
   1488 usbd_reload_device_desc(struct usbd_device *dev)
   1489 {
   1490 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
   1491 	usb_device_descriptor_t *udd = &dev->ud_ddesc;
   1492 	usbd_status err;
   1493 
   1494 	/* Get the full device descriptor. */
   1495 	err = usbd_get_device_desc(dev, udd);
   1496 	if (err)
   1497 		return err;
   1498 	if (udd->bDescriptorType != UDESC_DEVICE)
   1499 		return USBD_INVAL;
   1500 	if (udd->bLength < USB_DEVICE_DESCRIPTOR_SIZE)
   1501 		return USBD_INVAL;
   1502 
   1503 	DPRINTFN(15, "bLength             %5ju", udd->bLength, 0, 0, 0);
   1504 	DPRINTFN(15, "bDescriptorType     %5ju", udd->bDescriptorType, 0, 0, 0);
   1505 	DPRINTFN(15, "bcdUSB              %2jx.%02jx", udd->bcdUSB[1],
   1506 	    udd->bcdUSB[0], 0, 0);
   1507 	DPRINTFN(15, "bDeviceClass        %5ju", udd->bDeviceClass, 0, 0, 0);
   1508 	DPRINTFN(15, "bDeviceSubClass     %5ju", udd->bDeviceSubClass, 0, 0, 0);
   1509 	DPRINTFN(15, "bDeviceProtocol     %5ju", udd->bDeviceProtocol, 0, 0, 0);
   1510 	DPRINTFN(15, "bMaxPacketSize0     %5ju", udd->bMaxPacketSize, 0, 0, 0);
   1511 	DPRINTFN(15, "idVendor            0x%02jx 0x%02jx",
   1512 						    udd->idVendor[0],
   1513 						    udd->idVendor[1], 0, 0);
   1514 	DPRINTFN(15, "idProduct           0x%02jx 0x%02jx",
   1515 						    udd->idProduct[0],
   1516 						    udd->idProduct[1], 0, 0);
   1517 	DPRINTFN(15, "bcdDevice           %2jx.%02jx", udd->bcdDevice[1],
   1518 	    udd->bcdDevice[0], 0, 0);
   1519 	DPRINTFN(15, "iManufacturer       %5ju", udd->iManufacturer, 0, 0, 0);
   1520 	DPRINTFN(15, "iProduct            %5ju", udd->iProduct, 0, 0, 0);
   1521 	DPRINTFN(15, "iSerial             %5ju", udd->iSerialNumber, 0, 0, 0);
   1522 	DPRINTFN(15, "bNumConfigurations  %5ju", udd->bNumConfigurations, 0, 0,
   1523 	    0);
   1524 
   1525 	/* Figure out what's wrong with this device. */
   1526 	dev->ud_quirks = usbd_find_quirk(udd);
   1527 
   1528 	return USBD_NORMAL_COMPLETION;
   1529 }
   1530 
   1531 void
   1532 usbd_remove_device(struct usbd_device *dev, struct usbd_port *up)
   1533 {
   1534 
   1535 	USBHIST_FUNC();
   1536 	USBHIST_CALLARGS(usbdebug, "dev %#jx up %#jx",
   1537 	    (uintptr_t)dev, (uintptr_t)up, 0, 0);
   1538 
   1539 	if (dev->ud_pipe0 != NULL)
   1540 		usbd_kill_pipe(dev->ud_pipe0);
   1541 	up->up_dev = NULL;
   1542 	dev->ud_bus->ub_devices[usb_addr2dindex(dev->ud_addr)] = NULL;
   1543 
   1544 	if (dev->ud_vendor != NULL) {
   1545 		kmem_free(dev->ud_vendor, USB_MAX_ENCODED_STRING_LEN);
   1546 	}
   1547 	if (dev->ud_product != NULL) {
   1548 		kmem_free(dev->ud_product, USB_MAX_ENCODED_STRING_LEN);
   1549 	}
   1550 	if (dev->ud_serial != NULL) {
   1551 		kmem_free(dev->ud_serial, USB_MAX_ENCODED_STRING_LEN);
   1552 	}
   1553 	kmem_free(dev, sizeof(*dev));
   1554 }
   1555 
   1556 int
   1557 usbd_print(void *aux, const char *pnp)
   1558 {
   1559 	struct usb_attach_arg *uaa = aux;
   1560 
   1561 	if (pnp) {
   1562 #define USB_DEVINFO 1024
   1563 		char *devinfo;
   1564 		if (!uaa->uaa_usegeneric)
   1565 			return QUIET;
   1566 		devinfo = kmem_alloc(USB_DEVINFO, KM_SLEEP);
   1567 		usbd_devinfo(uaa->uaa_device, 1, devinfo, USB_DEVINFO);
   1568 		aprint_normal("%s, %s", devinfo, pnp);
   1569 		kmem_free(devinfo, USB_DEVINFO);
   1570 	}
   1571 	aprint_normal(" port %d", uaa->uaa_port);
   1572 #if 0
   1573 	/*
   1574 	 * It gets very crowded with these locators on the attach line.
   1575 	 * They are not really needed since they are printed in the clear
   1576 	 * by each driver.
   1577 	 */
   1578 	if (uaa->uaa_vendor != UHUB_UNK_VENDOR)
   1579 		aprint_normal(" vendor 0x%04x", uaa->uaa_vendor);
   1580 	if (uaa->uaa_product != UHUB_UNK_PRODUCT)
   1581 		aprint_normal(" product 0x%04x", uaa->uaa_product);
   1582 	if (uaa->uaa_release != UHUB_UNK_RELEASE)
   1583 		aprint_normal(" release 0x%04x", uaa->uaa_release);
   1584 #endif
   1585 	return UNCONF;
   1586 }
   1587 
   1588 int
   1589 usbd_ifprint(void *aux, const char *pnp)
   1590 {
   1591 	struct usbif_attach_arg *uiaa = aux;
   1592 
   1593 	if (pnp)
   1594 		return QUIET;
   1595 	aprint_normal(" port %d", uiaa->uiaa_port);
   1596 	aprint_normal(" configuration %d", uiaa->uiaa_configno);
   1597 	aprint_normal(" interface %d", uiaa->uiaa_ifaceno);
   1598 #if 0
   1599 	/*
   1600 	 * It gets very crowded with these locators on the attach line.
   1601 	 * They are not really needed since they are printed in the clear
   1602 	 * by each driver.
   1603 	 */
   1604 	if (uaa->uaa_vendor != UHUB_UNK_VENDOR)
   1605 		aprint_normal(" vendor 0x%04x", uaa->uaa_vendor);
   1606 	if (uaa->uaa_product != UHUB_UNK_PRODUCT)
   1607 		aprint_normal(" product 0x%04x", uaa->uaa_product);
   1608 	if (uaa->uaa_release != UHUB_UNK_RELEASE)
   1609 		aprint_normal(" release 0x%04x", uaa->uaa_release);
   1610 #endif
   1611 	return UNCONF;
   1612 }
   1613 
   1614 void
   1615 usbd_fill_deviceinfo(struct usbd_device *dev, struct usb_device_info *di,
   1616 		     int usedev)
   1617 {
   1618 	struct usbd_port *p;
   1619 	int i, j, err;
   1620 
   1621 	di->udi_bus = device_unit(dev->ud_bus->ub_usbctl);
   1622 	di->udi_addr = dev->ud_addr;
   1623 	di->udi_cookie = dev->ud_cookie;
   1624 	usbd_devinfo_vp(dev, di->udi_vendor, sizeof(di->udi_vendor),
   1625 	    di->udi_product, sizeof(di->udi_product), usedev, 1);
   1626 	usbd_printBCD(di->udi_release, sizeof(di->udi_release),
   1627 	    UGETW(dev->ud_ddesc.bcdDevice));
   1628 	if (usedev) {
   1629 		usbd_status uerr = usbd_get_string(dev,
   1630 		    dev->ud_ddesc.iSerialNumber, di->udi_serial);
   1631 		if (uerr != USBD_NORMAL_COMPLETION) {
   1632 			di->udi_serial[0] = '\0';
   1633 		} else {
   1634 			usbd_trim_spaces(di->udi_serial);
   1635 		}
   1636 	} else {
   1637 		di->udi_serial[0] = '\0';
   1638 		if (dev->ud_serial) {
   1639 			strlcpy(di->udi_serial, dev->ud_serial,
   1640 			    sizeof(di->udi_serial));
   1641 		}
   1642 	}
   1643 
   1644 	di->udi_vendorNo = UGETW(dev->ud_ddesc.idVendor);
   1645 	di->udi_productNo = UGETW(dev->ud_ddesc.idProduct);
   1646 	di->udi_releaseNo = UGETW(dev->ud_ddesc.bcdDevice);
   1647 	di->udi_class = dev->ud_ddesc.bDeviceClass;
   1648 	di->udi_subclass = dev->ud_ddesc.bDeviceSubClass;
   1649 	di->udi_protocol = dev->ud_ddesc.bDeviceProtocol;
   1650 	di->udi_config = dev->ud_config;
   1651 	di->udi_power = dev->ud_selfpowered ? 0 : dev->ud_power;
   1652 	di->udi_speed = dev->ud_speed;
   1653 
   1654 	if (dev->ud_subdevlen > 0) {
   1655 		for (i = 0, j = 0; i < dev->ud_subdevlen &&
   1656 			     j < USB_MAX_DEVNAMES; i++) {
   1657 			if (!dev->ud_subdevs[i])
   1658 				continue;
   1659 			strncpy(di->udi_devnames[j],
   1660 			    device_xname(dev->ud_subdevs[i]), USB_MAX_DEVNAMELEN);
   1661 			di->udi_devnames[j][USB_MAX_DEVNAMELEN-1] = '\0';
   1662 			j++;
   1663 		}
   1664 	} else {
   1665 		j = 0;
   1666 	}
   1667 	for (/* j is set */; j < USB_MAX_DEVNAMES; j++)
   1668 		di->udi_devnames[j][0] = 0;                 /* empty */
   1669 
   1670 	if (!dev->ud_hub) {
   1671 		di->udi_nports = 0;
   1672 		return;
   1673 	}
   1674 
   1675 	const int nports = dev->ud_hub->uh_hubdesc.bNbrPorts;
   1676 	for (i = 1; i <= __arraycount(di->udi_ports) && i <= nports; i++) {
   1677 		p = &dev->ud_hub->uh_ports[i - 1];
   1678 		if (p->up_dev)
   1679 			err = p->up_dev->ud_addr;
   1680 		else {
   1681 			const int s = UGETW(p->up_status.wPortStatus);
   1682 			const bool sshub_p = USB_IS_SS(dev->ud_speed);
   1683 			if (s & UPS_PORT_ENABLED)
   1684 				err = USB_PORT_ENABLED;
   1685 			else if (s & UPS_SUSPEND)
   1686 				err = USB_PORT_SUSPENDED;
   1687 			/*
   1688 			 * Note: UPS_PORT_POWER_SS is available only
   1689 			 * on 3.x, and UPS_PORT_POWER is available
   1690 			 * only on 2.0 or 1.1.
   1691 			 */
   1692 			else if (sshub_p && (s & UPS_PORT_POWER_SS))
   1693 				err = USB_PORT_POWERED;
   1694 			else if (!sshub_p && (s & UPS_PORT_POWER))
   1695 				err = USB_PORT_POWERED;
   1696 			else
   1697 				err = USB_PORT_DISABLED;
   1698 		}
   1699 		di->udi_ports[i - 1] = err;
   1700 	}
   1701 	di->udi_nports = nports;
   1702 }
   1703 
   1704 void
   1705 usb_free_device(struct usbd_device *dev)
   1706 {
   1707 	int ifcidx, nifc;
   1708 
   1709 	if (dev->ud_pipe0 != NULL)
   1710 		usbd_kill_pipe(dev->ud_pipe0);
   1711 	if (dev->ud_ifaces != NULL) {
   1712 		nifc = dev->ud_cdesc->bNumInterface;
   1713 		for (ifcidx = 0; ifcidx < nifc; ifcidx++) {
   1714 			usbd_free_iface_data(dev, ifcidx);
   1715 			usbd_iface_fini(dev, ifcidx);
   1716 		}
   1717 		kmem_free(dev->ud_ifaces,
   1718 		    nifc * sizeof(struct usbd_interface));
   1719 	}
   1720 	if (dev->ud_cdesc != NULL)
   1721 		kmem_free(dev->ud_cdesc, UGETW(dev->ud_cdesc->wTotalLength));
   1722 	if (dev->ud_bdesc != NULL)
   1723 		kmem_free(dev->ud_bdesc, UGETW(dev->ud_bdesc->wTotalLength));
   1724 	if (dev->ud_subdevlen > 0) {
   1725 		kmem_free(dev->ud_subdevs,
   1726 		    dev->ud_subdevlen * sizeof(device_t));
   1727 		dev->ud_subdevlen = 0;
   1728 	}
   1729 	if (dev->ud_vendor) {
   1730 		kmem_free(dev->ud_vendor, USB_MAX_ENCODED_STRING_LEN);
   1731 	}
   1732 	if (dev->ud_product) {
   1733 		kmem_free(dev->ud_product, USB_MAX_ENCODED_STRING_LEN);
   1734 	}
   1735 	if (dev->ud_serial) {
   1736 		kmem_free(dev->ud_serial, USB_MAX_ENCODED_STRING_LEN);
   1737 	}
   1738 	kmem_free(dev, sizeof(*dev));
   1739 }
   1740 
   1741 /*
   1742  * The general mechanism for detaching drivers works as follows: Each
   1743  * driver is responsible for maintaining a reference count on the
   1744  * number of outstanding references to its softc (e.g.  from
   1745  * processing hanging in a read or write).  The detach method of the
   1746  * driver decrements this counter and flags in the softc that the
   1747  * driver is dying and then wakes any sleepers.  It then sleeps on the
   1748  * softc.  Each place that can sleep must maintain the reference
   1749  * count.  When the reference count drops to -1 (0 is the normal value
   1750  * of the reference count) then a wakeup on the softc is performed
   1751  * signaling to the detach waiter that all references are gone.
   1752  */
   1753 
   1754 /*
   1755  * Called from process context when we discover that a port has
   1756  * been disconnected.
   1757  */
   1758 int
   1759 usb_disconnect_port(struct usbd_port *up, device_t parent, int flags)
   1760 {
   1761 	struct usbd_device *dev = up->up_dev;
   1762 	device_t subdev;
   1763 	char subdevname[16];
   1764 	const char *hubname = device_xname(parent);
   1765 	int i, rc;
   1766 
   1767 	USBHIST_FUNC();
   1768 	USBHIST_CALLARGS(usbdebug, "up=%#jx dev=%#jx port=%jd",
   1769 	    (uintptr_t)up, (uintptr_t)dev, up->up_portno, 0);
   1770 
   1771 	if (dev == NULL) {
   1772 		return 0;
   1773 	}
   1774 
   1775 	if (dev->ud_subdevlen > 0) {
   1776 		DPRINTFN(3, "disconnect subdevs", 0, 0, 0, 0);
   1777 		for (i = 0; i < dev->ud_subdevlen; i++) {
   1778 			if ((subdev = dev->ud_subdevs[i]) == NULL)
   1779 				continue;
   1780 			strlcpy(subdevname, device_xname(subdev),
   1781 			    sizeof(subdevname));
   1782 			KERNEL_LOCK(1, curlwp);
   1783 			rc = config_detach(subdev, flags);
   1784 			KERNEL_UNLOCK_ONE(curlwp);
   1785 			if (rc != 0)
   1786 				return rc;
   1787 			printf("%s: at %s", subdevname, hubname);
   1788 			if (up->up_portno != 0)
   1789 				printf(" port %d", up->up_portno);
   1790 			printf(" (addr %d) disconnected\n", dev->ud_addr);
   1791 		}
   1792 		KASSERT(!dev->ud_nifaces_claimed);
   1793 	}
   1794 
   1795 	mutex_enter(dev->ud_bus->ub_lock);
   1796 	dev->ud_bus->ub_devices[usb_addr2dindex(dev->ud_addr)] = NULL;
   1797 	up->up_dev = NULL;
   1798 	mutex_exit(dev->ud_bus->ub_lock);
   1799 
   1800 	usbd_add_dev_event(USB_EVENT_DEVICE_DETACH, dev);
   1801 
   1802 	usb_free_device(dev);
   1803 
   1804 	return 0;
   1805 }
   1806