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