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