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