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