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