Home | History | Annotate | Line # | Download | only in usb
usb_subr.c revision 1.143.8.3
      1 /*	$NetBSD: usb_subr.c,v 1.143.8.3 2007/06/21 15:27:58 itohy Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1998, 2004 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Lennart Augustsson (lennart (at) augustsson.net) at
      9  * Carlstedt Research & Technology.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  * 3. All advertising materials mentioning features or use of this software
     20  *    must display the following acknowledgement:
     21  *        This product includes software developed by the NetBSD
     22  *        Foundation, Inc. and its contributors.
     23  * 4. Neither the name of The NetBSD Foundation nor the names of its
     24  *    contributors may be used to endorse or promote products derived
     25  *    from this software without specific prior written permission.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     37  * POSSIBILITY OF SUCH DAMAGE.
     38  */
     39 
     40 #include <sys/cdefs.h>
     41 __KERNEL_RCSID(0, "$NetBSD: usb_subr.c,v 1.143.8.3 2007/06/21 15:27:58 itohy Exp $");
     42 /* __FBSDID("$FreeBSD: src/sys/dev/usb/usb_subr.c,v 1.88 2007/02/03 16:38:32 imp Exp $"); */
     43 
     44 #ifdef __NetBSD__
     45 #include "opt_compat_netbsd.h"
     46 #include "opt_usbverbose.h"
     47 #endif
     48 #ifdef __FreeBSD__
     49 #include "opt_usb.h"
     50 #endif
     51 
     52 #include <sys/param.h>
     53 #include <sys/systm.h>
     54 #include <sys/kernel.h>
     55 #include <sys/malloc.h>
     56 #if defined(__NetBSD__) || defined(__OpenBSD__)
     57 #include <sys/device.h>
     58 #include <sys/select.h>
     59 #elif defined(__FreeBSD__)
     60 #include <sys/module.h>
     61 #include <sys/bus.h>
     62 #endif
     63 #include <sys/proc.h>
     64 
     65 #include <machine/bus.h>
     66 
     67 #include <dev/usb/usb.h>
     68 
     69 #include <dev/usb/usbdi.h>
     70 #include <dev/usb/usbdi_util.h>
     71 #include <dev/usb/usbdivar.h>
     72 #ifdef __FreeBSD__
     73 #include "usbdevs.h"
     74 #else
     75 #include <dev/usb/usbdevs.h>
     76 #endif
     77 #include <dev/usb/usb_quirks.h>
     78 
     79 #ifdef __FreeBSD__
     80 #define delay(d)         DELAY(d)
     81 #endif
     82 
     83 #ifdef USB_DEBUG
     84 #define DPRINTF(x)	if (usbdebug) logprintf x
     85 #define DPRINTFN(n,x)	if (usbdebug>(n)) logprintf x
     86 extern int usbdebug;
     87 #else
     88 #define DPRINTF(x)
     89 #define DPRINTFN(n,x)
     90 #endif
     91 
     92 Static usbd_status usbd_set_config(usbd_device_handle, int);
     93 Static void usbd_devinfo(usbd_device_handle, int, char *, size_t);
     94 Static void usbd_devinfo_vp(usbd_device_handle dev, char *v, char *p,
     95 			    int usedev, int useencoded);
     96 Static int usbd_getnewaddr(usbd_bus_handle bus);
     97 #if defined(__NetBSD__)
     98 Static int usbd_print(void *, const char *);
     99 #ifdef USB_USE_IFATTACH
    100 Static int usbd_ifprint(void *, const char *);
    101 #endif /* USB_USE_IFATTACH */
    102 Static int usbd_submatch(device_ptr_t, struct cfdata *,
    103 			 const int *, void *);
    104 #ifdef USB_USE_IFATTACH
    105 Static int usbd_ifsubmatch(device_ptr_t, struct cfdata *,
    106 			   const int *, void *);
    107 #endif /* USB_USE_IFATTACH */
    108 #elif defined(__OpenBSD__)
    109 Static int usbd_print(void *aux, const char *pnp);
    110 Static int usbd_submatch(device_ptr_t, void *, void *);
    111 #endif
    112 Static void usbd_free_iface_data(usbd_device_handle dev, int ifcno);
    113 Static void usbd_kill_pipe(usbd_pipe_handle);
    114 Static usbd_status usbd_probe_and_attach(device_ptr_t parent,
    115 				 usbd_device_handle dev, int port, int addr);
    116 
    117 Static u_int32_t usb_cookie_no = 0;
    118 
    119 #ifdef USBVERBOSE
    120 typedef u_int16_t usb_vendor_id_t;
    121 typedef u_int16_t usb_product_id_t;
    122 
    123 /*
    124  * Descriptions of of known vendors and devices ("products").
    125  */
    126 struct usb_vendor {
    127 	usb_vendor_id_t		vendor;
    128 	const char		*vendorname;
    129 };
    130 struct usb_product {
    131 	usb_vendor_id_t		vendor;
    132 	usb_product_id_t	product;
    133 	const char		*productname;
    134 };
    135 
    136 #ifdef __FreeBSD__
    137 #include "usbdevs_data.h"
    138 #else
    139 #include <dev/usb/usbdevs_data.h>
    140 #endif
    141 #endif /* USBVERBOSE */
    142 
    143 Static const char * const usbd_error_strs[] = {
    144 	"NORMAL_COMPLETION",
    145 	"IN_PROGRESS",
    146 	"PENDING_REQUESTS",
    147 	"NOT_STARTED",
    148 	"INVAL",
    149 	"NOMEM",
    150 	"CANCELLED",
    151 	"BAD_ADDRESS",
    152 	"IN_USE",
    153 	"NO_ADDR",
    154 	"SET_ADDR_FAILED",
    155 	"NO_POWER",
    156 	"TOO_DEEP",
    157 	"IOERROR",
    158 	"NOT_CONFIGURED",
    159 	"TIMEOUT",
    160 	"SHORT_XFER",
    161 	"STALLED",
    162 	"INTERRUPTED",
    163 	"XXX",
    164 };
    165 
    166 const char *
    167 usbd_errstr(usbd_status err)
    168 {
    169 	static char buffer[5];
    170 
    171 	if (err < USBD_ERROR_MAX) {
    172 		return usbd_error_strs[err];
    173 	} else {
    174 		snprintf(buffer, sizeof buffer, "%d", err);
    175 		return buffer;
    176 	}
    177 }
    178 
    179 usbd_status
    180 usbd_get_string_desc(usbd_device_handle dev, int sindex, int langid,
    181 		     usb_string_descriptor_t *sdesc, int *sizep)
    182 {
    183 	usb_device_request_t req;
    184 	usbd_status err;
    185 	int actlen;
    186 
    187 	req.bmRequestType = UT_READ_DEVICE;
    188 	req.bRequest = UR_GET_DESCRIPTOR;
    189 	USETW2(req.wValue, UDESC_STRING, sindex);
    190 	USETW(req.wIndex, langid);
    191 	USETW(req.wLength, 2);	/* only size byte first */
    192 	err = usbd_do_request_flags(dev, &req, sdesc, USBD_SHORT_XFER_OK,
    193 		&actlen, USBD_DEFAULT_TIMEOUT);
    194 	if (err)
    195 		return (err);
    196 
    197 	if (actlen < 2)
    198 		return (USBD_SHORT_XFER);
    199 
    200 	USETW(req.wLength, sdesc->bLength);	/* the whole string */
    201  	err = usbd_do_request_flags(dev, &req, sdesc, USBD_SHORT_XFER_OK,
    202  		&actlen, USBD_DEFAULT_TIMEOUT);
    203 	if (err)
    204 		return (err);
    205 
    206 	if (actlen != sdesc->bLength) {
    207 		DPRINTFN(-1, ("usbd_get_string_desc: expected %d, got %d\n",
    208 		    sdesc->bLength, actlen));
    209 	}
    210 
    211 	*sizep = actlen;
    212 	return (USBD_NORMAL_COMPLETION);
    213 }
    214 
    215 static void
    216 usbd_trim_spaces(char *p)
    217 {
    218 	char *q, *e;
    219 
    220 	q = e = p;
    221 	while (*q == ' ')		/* skip leading spaces */
    222 		q++;
    223 	while ((*p = *q++))		/* copy string */
    224 		if (*p++ != ' ')	/* remember last non-space */
    225 			e = p;
    226 	*e = '\0';			/* kill trailing spaces */
    227 }
    228 
    229 Static void
    230 usbd_devinfo_vp(usbd_device_handle dev, char *v, char *p, int usedev,
    231 		int useencoded)
    232 {
    233 	usb_device_descriptor_t *udd = &dev->ddesc;
    234 #ifdef USBVERBOSE
    235 	int n;
    236 #endif
    237 
    238 	v[0] = p[0] = '\0';
    239 	if (dev == NULL)
    240 		return;
    241 
    242 	if (usedev) {
    243 		if (usbd_get_string0(dev, udd->iManufacturer, v, useencoded) ==
    244 		    USBD_NORMAL_COMPLETION)
    245 			usbd_trim_spaces(v);
    246 		if (usbd_get_string0(dev, udd->iProduct, p, useencoded) ==
    247 		    USBD_NORMAL_COMPLETION)
    248 			usbd_trim_spaces(p);
    249 	}
    250 	/* There is no need for strlcpy & snprintf below. */
    251 #ifdef USBVERBOSE
    252 	if (v[0] == '\0')
    253 		for (n = 0; n < usb_nvendors; n++)
    254 			if (usb_vendors[n].vendor == UGETW(udd->idVendor)) {
    255 				strcpy(v, usb_vendors[n].vendorname);
    256 				break;
    257 			}
    258 	if (p[0] == '\0')
    259 		for (n = 0; n < usb_nproducts; n++)
    260 			if (usb_products[n].vendor == UGETW(udd->idVendor) &&
    261 			    usb_products[n].product == UGETW(udd->idProduct)) {
    262 				strcpy(p, usb_products[n].productname);
    263 				break;
    264 			}
    265 #endif
    266 	if (v[0] == '\0')
    267 		sprintf(v, "vendor 0x%04x", UGETW(udd->idVendor));
    268 	if (p[0] == '\0')
    269 		sprintf(p, "product 0x%04x", UGETW(udd->idProduct));
    270 }
    271 
    272 int
    273 usbd_printBCD(char *cp, size_t l, int bcd)
    274 {
    275 	return (snprintf(cp, l, "%x.%02x", bcd >> 8, bcd & 0xff));
    276 }
    277 
    278 Static void
    279 usbd_devinfo(usbd_device_handle dev, int showclass, char *cp, size_t l)
    280 {
    281 	usb_device_descriptor_t *udd = &dev->ddesc;
    282 	usbd_interface_handle iface;
    283 	char *vendor, *product;
    284 	int bcdDevice, bcdUSB;
    285 	usb_interface_descriptor_t *id;
    286 	char *ep;
    287 
    288 	vendor = malloc(USB_MAX_ENCODED_STRING_LEN * 2, M_USB, M_NOWAIT);
    289 	if (vendor == NULL) {
    290 		*cp = '\0';
    291 		return;
    292 	}
    293 	product = &vendor[USB_MAX_ENCODED_STRING_LEN];
    294 
    295 	ep = cp + l;
    296 
    297 	usbd_devinfo_vp(dev, vendor, product, 1, 1);
    298 	cp += snprintf(cp, ep - cp, "%s %s", vendor, product);
    299 	if (showclass & USBD_SHOW_DEVICE_CLASS)
    300 		cp += snprintf(cp, ep - cp, ", class %d/%d",
    301 		    udd->bDeviceClass, udd->bDeviceSubClass);
    302 	bcdUSB = UGETW(udd->bcdUSB);
    303 	bcdDevice = UGETW(udd->bcdDevice);
    304 	cp += snprintf(cp, ep - cp, ", rev ");
    305 	cp += usbd_printBCD(cp, ep - cp, bcdUSB);
    306 	*cp++ = '/';
    307 	cp += usbd_printBCD(cp, ep - cp, bcdDevice);
    308 	cp += snprintf(cp, ep - cp, ", addr %d", dev->address);
    309 	if (showclass & USBD_SHOW_INTERFACE_CLASS) {
    310 		/* fetch the interface handle for the first interface */
    311 		(void)usbd_device2interface_handle(dev, 0, &iface);
    312 		id = usbd_get_interface_descriptor(iface);
    313 		cp += snprintf(cp, ep - cp, ", iclass %d/%d",
    314 		    id->bInterfaceClass, id->bInterfaceSubClass);
    315 	}
    316 	*cp = 0;
    317 	free(vendor, M_USB);
    318 }
    319 
    320 char *
    321 usbd_devinfo_alloc(usbd_device_handle dev, int showclass)
    322 {
    323 	char *devinfop;
    324 
    325 	devinfop = malloc(DEVINFOSIZE, M_TEMP, M_WAITOK);
    326 	usbd_devinfo(dev, showclass, devinfop, DEVINFOSIZE);
    327 	return devinfop;
    328 }
    329 
    330 void
    331 usbd_devinfo_free(char *devinfop)
    332 {
    333 	free(devinfop, M_TEMP);
    334 }
    335 
    336 /* Delay for a certain number of ms */
    337 void
    338 usb_delay_ms(usbd_bus_handle bus, u_int ms)
    339 {
    340 	/* Wait at least two clock ticks so we know the time has passed. */
    341 	if (bus->use_polling || cold)
    342 		delay((ms+1) * 1000);
    343 	else
    344 		tsleep(&ms, PRIBIO, "usbdly", (ms*hz+999)/1000 + 1);
    345 }
    346 
    347 /* Delay given a device handle. */
    348 void
    349 usbd_delay_ms(usbd_device_handle dev, u_int ms)
    350 {
    351 	usb_delay_ms(dev->bus, ms);
    352 }
    353 
    354 usbd_status
    355 usbd_reset_port(usbd_device_handle dev, int port, usb_port_status_t *ps)
    356 {
    357 	usb_device_request_t req;
    358 	usbd_status err;
    359 	int n;
    360 
    361 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
    362 	req.bRequest = UR_SET_FEATURE;
    363 	USETW(req.wValue, UHF_PORT_RESET);
    364 	USETW(req.wIndex, port);
    365 	USETW(req.wLength, 0);
    366 	err = usbd_do_request(dev, &req, 0);
    367 	DPRINTFN(1,("usbd_reset_port: port %d reset done, error=%s\n",
    368 		    port, usbd_errstr(err)));
    369 	if (err)
    370 		return (err);
    371 	n = 10;
    372 	do {
    373 		/* Wait for device to recover from reset. */
    374 		usbd_delay_ms(dev, USB_PORT_RESET_DELAY);
    375 		err = usbd_get_port_status(dev, port, ps);
    376 		if (err) {
    377 			DPRINTF(("usbd_reset_port: get status failed %d\n",
    378 				 err));
    379 			return (err);
    380 		}
    381 		/* If the device disappeared, just give up. */
    382 		if (!(UGETW(ps->wPortStatus) & UPS_CURRENT_CONNECT_STATUS))
    383 			return (USBD_NORMAL_COMPLETION);
    384 	} while ((UGETW(ps->wPortChange) & UPS_C_PORT_RESET) == 0 && --n > 0);
    385 	if (n == 0)
    386 		return (USBD_TIMEOUT);
    387 	err = usbd_clear_port_feature(dev, port, UHF_C_PORT_RESET);
    388 #ifdef USB_DEBUG
    389 	if (err)
    390 		DPRINTF(("usbd_reset_port: clear port feature failed %d\n",
    391 			 err));
    392 #endif
    393 
    394 	/* Wait for the device to recover from reset. */
    395 	usbd_delay_ms(dev, USB_PORT_RESET_RECOVERY);
    396 	return (err);
    397 }
    398 
    399 usb_interface_descriptor_t *
    400 usbd_find_idesc(usb_config_descriptor_t *cd, int ifaceidx, int altidx)
    401 {
    402 	char *p = (char *)cd;
    403 	char *end = p + UGETW(cd->wTotalLength);
    404 	usb_interface_descriptor_t *d;
    405 	int curidx, lastidx, curaidx = 0;
    406 
    407 	for (curidx = lastidx = -1; p < end; ) {
    408 		d = (usb_interface_descriptor_t *)p;
    409 		DPRINTFN(4,("usbd_find_idesc: idx=%d(%d) altidx=%d(%d) len=%d "
    410 			    "type=%d\n",
    411 			    ifaceidx, curidx, altidx, curaidx,
    412 			    d->bLength, d->bDescriptorType));
    413 		if (d->bLength == 0) /* bad descriptor */
    414 			break;
    415 		p += d->bLength;
    416 		if (p <= end && d->bDescriptorType == UDESC_INTERFACE) {
    417 			if (d->bInterfaceNumber != lastidx) {
    418 				lastidx = d->bInterfaceNumber;
    419 				curidx++;
    420 				curaidx = 0;
    421 			} else
    422 				curaidx++;
    423 			if (ifaceidx == curidx && altidx == curaidx)
    424 				return (d);
    425 		}
    426 	}
    427 	return (NULL);
    428 }
    429 
    430 usb_endpoint_descriptor_t *
    431 usbd_find_edesc(usb_config_descriptor_t *cd, int ifaceidx, int altidx,
    432 		int endptidx)
    433 {
    434 	char *p = (char *)cd;
    435 	char *end = p + UGETW(cd->wTotalLength);
    436 	usb_interface_descriptor_t *d;
    437 	usb_endpoint_descriptor_t *e;
    438 	int curidx;
    439 
    440 	d = usbd_find_idesc(cd, ifaceidx, altidx);
    441 	if (d == NULL)
    442 		return (NULL);
    443 	if (endptidx >= d->bNumEndpoints) /* quick exit */
    444 		return (NULL);
    445 
    446 	curidx = -1;
    447 	for (p = (char *)d + d->bLength; p < end; ) {
    448 		e = (usb_endpoint_descriptor_t *)p;
    449 		if (e->bLength == 0) /* bad descriptor */
    450 			break;
    451 		p += e->bLength;
    452 		if (p <= end && e->bDescriptorType == UDESC_INTERFACE)
    453 			return (NULL);
    454 		if (p <= end && e->bDescriptorType == UDESC_ENDPOINT) {
    455 			curidx++;
    456 			if (curidx == endptidx)
    457 				return (e);
    458 		}
    459 	}
    460 	return (NULL);
    461 }
    462 
    463 usbd_status
    464 usbd_fill_iface_data(usbd_device_handle dev, int ifaceidx, int altidx)
    465 {
    466 	usbd_interface_handle ifc = &dev->ifaces[ifaceidx];
    467 	usb_interface_descriptor_t *idesc;
    468 	char *p, *end;
    469 	int endpt, nendpt;
    470 
    471 	DPRINTFN(4,("usbd_fill_iface_data: ifaceidx=%d altidx=%d\n",
    472 		    ifaceidx, altidx));
    473 	idesc = usbd_find_idesc(dev->cdesc, ifaceidx, altidx);
    474 	if (idesc == NULL)
    475 		return (USBD_INVAL);
    476 	ifc->device = dev;
    477 	ifc->idesc = idesc;
    478 	ifc->index = ifaceidx;
    479 	ifc->altindex = altidx;
    480 	nendpt = ifc->idesc->bNumEndpoints;
    481 	DPRINTFN(4,("usbd_fill_iface_data: found idesc nendpt=%d\n", nendpt));
    482 	if (nendpt != 0) {
    483 		ifc->endpoints = malloc(nendpt * sizeof(struct usbd_endpoint),
    484 					M_USB, M_NOWAIT);
    485 		if (ifc->endpoints == NULL)
    486 			return (USBD_NOMEM);
    487 	} else
    488 		ifc->endpoints = NULL;
    489 	ifc->priv = NULL;
    490 	p = (char *)ifc->idesc + ifc->idesc->bLength;
    491 	end = (char *)dev->cdesc + UGETW(dev->cdesc->wTotalLength);
    492 #define ed ((usb_endpoint_descriptor_t *)p)
    493 	for (endpt = 0; endpt < nendpt; endpt++) {
    494 		DPRINTFN(10,("usbd_fill_iface_data: endpt=%d\n", endpt));
    495 		for (; p < end; p += ed->bLength) {
    496 			DPRINTFN(10,("usbd_fill_iface_data: p=%p end=%p "
    497 				     "len=%d type=%d\n",
    498 				 p, end, ed->bLength, ed->bDescriptorType));
    499 			if (p + ed->bLength <= end && ed->bLength != 0 &&
    500 			    ed->bDescriptorType == UDESC_ENDPOINT)
    501 				goto found;
    502 			if (ed->bLength == 0 ||
    503 			    ed->bDescriptorType == UDESC_INTERFACE)
    504 				break;
    505 		}
    506 		/* passed end, or bad desc */
    507 		printf("usbd_fill_iface_data: bad descriptor(s): %s\n",
    508 		       ed->bLength == 0 ? "0 length" :
    509 		       ed->bDescriptorType == UDESC_INTERFACE ? "iface desc":
    510 		       "out of data");
    511 		goto bad;
    512 	found:
    513 		ifc->endpoints[endpt].edesc = ed;
    514 		if (dev->speed == USB_SPEED_HIGH) {
    515 			u_int mps;
    516 			/* Control and bulk endpoints have max packet limits. */
    517 			switch (UE_GET_XFERTYPE(ed->bmAttributes)) {
    518 			case UE_CONTROL:
    519 				mps = USB_2_MAX_CTRL_PACKET;
    520 				goto check;
    521 			case UE_BULK:
    522 				mps = USB_2_MAX_BULK_PACKET;
    523 			check:
    524 				if (UGETW(ed->wMaxPacketSize) != mps) {
    525 					USETW(ed->wMaxPacketSize, mps);
    526 #ifdef DIAGNOSTIC
    527 					printf("usbd_fill_iface_data: bad max "
    528 					       "packet size\n");
    529 #endif
    530 				}
    531 				break;
    532 			default:
    533 				break;
    534 			}
    535 		}
    536 		ifc->endpoints[endpt].refcnt = 0;
    537 		ifc->endpoints[endpt].savedtoggle = 0;
    538 		p += ed->bLength;
    539 	}
    540 #undef ed
    541 	LIST_INIT(&ifc->pipes);
    542 	return (USBD_NORMAL_COMPLETION);
    543 
    544  bad:
    545 	if (ifc->endpoints != NULL) {
    546 		free(ifc->endpoints, M_USB);
    547 		ifc->endpoints = NULL;
    548 	}
    549 	return (USBD_INVAL);
    550 }
    551 
    552 void
    553 usbd_free_iface_data(usbd_device_handle dev, int ifcno)
    554 {
    555 	usbd_interface_handle ifc = &dev->ifaces[ifcno];
    556 	if (ifc->endpoints)
    557 		free(ifc->endpoints, M_USB);
    558 }
    559 
    560 Static usbd_status
    561 usbd_set_config(usbd_device_handle dev, int conf)
    562 {
    563 	usb_device_request_t req;
    564 
    565 	req.bmRequestType = UT_WRITE_DEVICE;
    566 	req.bRequest = UR_SET_CONFIG;
    567 	USETW(req.wValue, conf);
    568 	USETW(req.wIndex, 0);
    569 	USETW(req.wLength, 0);
    570 	return (usbd_do_request(dev, &req, 0));
    571 }
    572 
    573 usbd_status
    574 usbd_set_config_no(usbd_device_handle dev, int no, int msg)
    575 {
    576 	int index;
    577 	usb_config_descriptor_t cd;
    578 	usbd_status err;
    579 
    580 	if (no == USB_UNCONFIG_NO)
    581 		return (usbd_set_config_index(dev, USB_UNCONFIG_INDEX, msg));
    582 
    583 	DPRINTFN(5,("usbd_set_config_no: %d\n", no));
    584 	/* Figure out what config index to use. */
    585 	for (index = 0; index < dev->ddesc.bNumConfigurations; index++) {
    586 		err = usbd_get_config_desc(dev, index, &cd);
    587 		if (err)
    588 			return (err);
    589 		if (cd.bConfigurationValue == no)
    590 			return (usbd_set_config_index(dev, index, msg));
    591 	}
    592 	return (USBD_INVAL);
    593 }
    594 
    595 usbd_status
    596 usbd_set_config_index(usbd_device_handle dev, int index, int msg)
    597 {
    598 	usb_config_descriptor_t cd, *cdp;
    599 	usbd_status err;
    600 	int i, ifcidx, nifc, len, selfpowered, power;
    601 
    602 	DPRINTFN(5,("usbd_set_config_index: dev=%p index=%d\n", dev, index));
    603 
    604 	if (index >= dev->ddesc.bNumConfigurations &&
    605 	    index != USB_UNCONFIG_NO) {
    606 		/* panic? */
    607 		printf("usbd_set_config_index: illegal index\n");
    608 		return (USBD_INVAL);
    609 	}
    610 
    611 	if (dev->config != USB_UNCONFIG_NO) {
    612 		nifc = dev->cdesc->bNumInterface;
    613 
    614 		/* Check that all interfaces are idle */
    615 		for (ifcidx = 0; ifcidx < nifc; ifcidx++) {
    616 			if (LIST_EMPTY(&dev->ifaces[ifcidx].pipes))
    617 				continue;
    618 			DPRINTF(("usbd_set_config_index: open pipes exist\n"));
    619 			return (USBD_IN_USE);
    620 		}
    621 
    622 		DPRINTF(("usbd_set_config_index: free old config\n"));
    623 		/* Free all configuration data structures. */
    624 		for (ifcidx = 0; ifcidx < nifc; ifcidx++)
    625 			usbd_free_iface_data(dev, ifcidx);
    626 		free(dev->ifaces, M_USB);
    627 		free(dev->cdesc, M_USB);
    628 		dev->ifaces = NULL;
    629 		dev->cdesc = NULL;
    630 		dev->config = USB_UNCONFIG_NO;
    631 	}
    632 
    633 	if (index == USB_UNCONFIG_INDEX) {
    634 		/* We are unconfiguring the device, so leave unallocated. */
    635 		DPRINTF(("usbd_set_config_index: set config 0\n"));
    636 		err = usbd_set_config(dev, USB_UNCONFIG_NO);
    637 		if (err) {
    638 			DPRINTF(("usbd_set_config_index: setting config=0 "
    639 				 "failed, error=%s\n", usbd_errstr(err)));
    640 		}
    641 		return (err);
    642 	}
    643 
    644 	/* Get the short descriptor. */
    645 	err = usbd_get_config_desc(dev, index, &cd);
    646 	if (err)
    647 		return (err);
    648 	len = UGETW(cd.wTotalLength);
    649 	cdp = malloc(len, M_USB, M_NOWAIT);
    650 	if (cdp == NULL)
    651 		return (USBD_NOMEM);
    652 
    653 	/* Get the full descriptor.  Try a few times for slow devices. */
    654 	for (i = 0; i < 3; i++) {
    655 		err = usbd_get_desc(dev, UDESC_CONFIG, index, len, cdp);
    656 		if (!err)
    657 			break;
    658 		usbd_delay_ms(dev, 200);
    659 	}
    660 	if (err)
    661 		goto bad;
    662 	if (cdp->bDescriptorType != UDESC_CONFIG) {
    663 		DPRINTFN(-1,("usbd_set_config_index: bad desc %d\n",
    664 			     cdp->bDescriptorType));
    665 		err = USBD_INVAL;
    666 		goto bad;
    667 	}
    668 
    669 	/*
    670 	 * Figure out if the device is self or bus powered.
    671 	 */
    672 #if 0 /* XXX various devices don't report the power state correctly */
    673 	selfpowered = 0;
    674 	err = usbd_get_device_status(dev, &ds);
    675 	if (!err && (UGETW(ds.wStatus) & UDS_SELF_POWERED))
    676 		selfpowered = 1;
    677 #endif
    678 	/*
    679 	 * Use the power state in the configuration we are going
    680 	 * to set. This doesn't necessarily reflect the actual
    681 	 * power state of the device; the driver can control this
    682 	 * by choosing the appropriate configuration.
    683 	 */
    684 	selfpowered = !!(cdp->bmAttributes & UC_SELF_POWERED);
    685 
    686 	DPRINTF(("usbd_set_config_index: (addr %d) cno=%d attr=0x%02x, "
    687 		 "selfpowered=%d, power=%d\n",
    688 		 cdp->bConfigurationValue, dev->address, cdp->bmAttributes,
    689 		 selfpowered, cdp->bMaxPower * 2));
    690 
    691 	/* Check if we have enough power. */
    692 #if 0 /* this is a no-op, see above */
    693 	if ((cdp->bmAttributes & UC_SELF_POWERED) && !selfpowered) {
    694 		if (msg)
    695 			printf("%s: device addr %d (config %d): "
    696 				 "can't set self powered configuration\n",
    697 			       USBDEVNAME(dev->bus->bdev), dev->address,
    698 			       cdp->bConfigurationValue);
    699 		err = USBD_NO_POWER;
    700 		goto bad;
    701 	}
    702 #endif
    703 #ifdef USB_DEBUG
    704 	if (dev->powersrc == NULL) {
    705 		DPRINTF(("usbd_set_config_index: No power source?\n"));
    706 		err = USBD_IOERROR;
    707 		goto bad;
    708 	}
    709 #endif
    710 	power = cdp->bMaxPower * 2;
    711 	if (power > dev->powersrc->power) {
    712 		DPRINTF(("power exceeded %d %d\n", power,dev->powersrc->power));
    713 		/* XXX print nicer message. */
    714 		if (msg)
    715 			printf("%s: device addr %d (config %d) exceeds power "
    716 				 "budget, %d mA > %d mA\n",
    717 			       USBDEVNAME(dev->bus->bdev), dev->address,
    718 			       cdp->bConfigurationValue,
    719 			       power, dev->powersrc->power);
    720 		err = USBD_NO_POWER;
    721 		goto bad;
    722 	}
    723 	dev->power = power;
    724 	dev->self_powered = selfpowered;
    725 
    726 	/* Set the actual configuration value. */
    727 	DPRINTF(("usbd_set_config_index: set config %d\n",
    728 		 cdp->bConfigurationValue));
    729 	err = usbd_set_config(dev, cdp->bConfigurationValue);
    730 	if (err) {
    731 		DPRINTF(("usbd_set_config_index: setting config=%d failed, "
    732 			 "error=%s\n",
    733 			 cdp->bConfigurationValue, usbd_errstr(err)));
    734 		goto bad;
    735 	}
    736 
    737 	/* Allocate and fill interface data. */
    738 	nifc = cdp->bNumInterface;
    739 	dev->ifaces = malloc(nifc * sizeof(struct usbd_interface),
    740 			     M_USB, M_NOWAIT);
    741 	if (dev->ifaces == NULL) {
    742 		err = USBD_NOMEM;
    743 		goto bad;
    744 	}
    745 	DPRINTFN(5,("usbd_set_config_index: dev=%p cdesc=%p\n", dev, cdp));
    746 	dev->cdesc = cdp;
    747 	dev->config = cdp->bConfigurationValue;
    748 	for (ifcidx = 0; ifcidx < nifc; ifcidx++) {
    749 		err = usbd_fill_iface_data(dev, ifcidx, 0);
    750 		if (err) {
    751 			while (--ifcidx >= 0)
    752 				usbd_free_iface_data(dev, ifcidx);
    753 			goto bad;
    754 		}
    755 	}
    756 
    757 	return (USBD_NORMAL_COMPLETION);
    758 
    759  bad:
    760 	free(cdp, M_USB);
    761 	return (err);
    762 }
    763 
    764 /* XXX add function for alternate settings */
    765 
    766 usbd_status
    767 usbd_setup_pipe(usbd_device_handle dev, usbd_interface_handle iface,
    768 		struct usbd_endpoint *ep, int ival, usbd_pipe_handle *pipe)
    769 {
    770 	usbd_pipe_handle p;
    771 	usbd_status err;
    772 
    773 	DPRINTFN(1,("usbd_setup_pipe: dev=%p iface=%p ep=%p pipe=%p\n",
    774 		    dev, iface, ep, pipe));
    775 	p = malloc(dev->bus->pipe_size, M_USB, M_NOWAIT);
    776 	if (p == NULL)
    777 		return (USBD_NOMEM);
    778 	p->device = dev;
    779 	p->iface = iface;
    780 	p->endpoint = ep;
    781 	ep->refcnt++;
    782 	p->refcnt = 1;
    783 	p->intrxfer = 0;
    784 	p->running = 0;
    785 	p->aborting = 0;
    786 	p->repeat = 0;
    787 	p->interval = ival;
    788 	SIMPLEQ_INIT(&p->queue);
    789 	err = dev->bus->methods->open_pipe(p);
    790 	if (err) {
    791 		DPRINTFN(-1,("usbd_setup_pipe: endpoint=0x%x failed, error="
    792 			 "%s\n",
    793 			 ep->edesc->bEndpointAddress, usbd_errstr(err)));
    794 		free(p, M_USB);
    795 		return (err);
    796 	}
    797 	*pipe = p;
    798 	return (USBD_NORMAL_COMPLETION);
    799 }
    800 
    801 /* Abort the device control pipe. */
    802 void
    803 usbd_kill_pipe(usbd_pipe_handle pipe)
    804 {
    805 	usbd_abort_pipe(pipe);
    806 	pipe->methods->close(pipe);
    807 	pipe->endpoint->refcnt--;
    808 	free(pipe, M_USB);
    809 }
    810 
    811 int
    812 usbd_getnewaddr(usbd_bus_handle bus)
    813 {
    814 	int addr;
    815 
    816 	for (addr = 1; addr < USB_MAX_DEVICES; addr++)
    817 		if (bus->devices[addr] == 0)
    818 			return (addr);
    819 	return (-1);
    820 }
    821 
    822 
    823 usbd_status
    824 usbd_probe_and_attach(device_ptr_t parent, usbd_device_handle dev,
    825 		      int port, int addr)
    826 {
    827 	struct usb_attach_arg uaa;
    828 #ifdef USB_USE_IFATTACH
    829 	struct usbif_attach_arg uiaa;
    830 #endif /* USB_USE_IFATTACH */
    831 	usb_device_descriptor_t *dd = &dev->ddesc;
    832 	int found, i, confi, nifaces;
    833 	usbd_status err;
    834 	device_ptr_t dv;
    835 	usbd_interface_handle *ifaces;
    836 	device_ptr_t *tmpdv;
    837 #if defined(__FreeBSD__)
    838 	char *devinfo;
    839 	device_t bdev;
    840 	struct usb_attach_arg *uaap;
    841 #ifdef USB_USE_IFATTACH
    842 	struct usbif_attach_arg *uiaap;
    843 #endif /* USB_USE_IFATTACH */
    844 #endif
    845 
    846 #ifdef __FreeBSD__
    847 #define FREEDEVINFO	free(devinfo, M_USB)
    848 #else
    849 #define FREEDEVINFO	/* empty */
    850 #endif
    851 
    852 #if defined(__FreeBSD__)
    853 	/* XXX FreeBSD may leak resources on failure cases -- fixme */
    854 	devinfo = malloc(DEVINFOSIZE, M_USB, M_NOWAIT);
    855 	if (devinfo == NULL) {
    856 		device_printf(parent, "Can't allocate memory for probe string\n");
    857 		return (USBD_NOMEM);
    858 	}
    859 	bdev = device_add_child(parent, NULL, -1);
    860 	if (!bdev) {
    861 		FREEDEVINFO;
    862 		device_printf(parent, "Device creation failed\n");
    863 		return (USBD_INVAL);
    864 	}
    865 	uaap = malloc(sizeof(uaa), M_USB, M_NOWAIT);
    866 	if (uaap == NULL) {
    867 		FREEDEVINFO;
    868 		return (USBD_INVAL);
    869 	}
    870 	device_set_ivars(bdev, uaap);
    871 #endif
    872 
    873 	uaa.device = dev;
    874 #ifndef USB_USE_IFATTACH
    875 	uaa.iface = NULL;
    876 	uaa.ifaces = NULL;
    877 	uaa.nifaces = 0;
    878 #endif /* USB_USE_IFATTACH */
    879 	uaa.usegeneric = 0;
    880 	uaa.port = port;
    881 #ifndef USB_USE_IFATTACH
    882 	uaa.configno = UHUB_UNK_CONFIGURATION;
    883 	uaa.ifaceno = UHUB_UNK_INTERFACE;
    884 #endif /* USB_USE_IFATTACH */
    885 	uaa.vendor = UGETW(dd->idVendor);
    886 	uaa.product = UGETW(dd->idProduct);
    887 	uaa.release = UGETW(dd->bcdDevice);
    888 #ifdef USB_USE_IFATTACH
    889 	uaa.class = dd->bDeviceClass;
    890 	uaa.subclass = dd->bDeviceSubClass;
    891 	uaa.proto = dd->bDeviceProtocol;
    892 #endif /* USB_USE_IFATTACH */
    893 
    894 	/* First try with device specific drivers. */
    895 	DPRINTF(("usbd_probe_and_attach: trying device specific drivers\n"));
    896 
    897 #ifdef __FreeBSD__
    898 	dev->ifacenums = NULL;
    899 	dev->subdevs = malloc(2 * sizeof dv, M_USB, M_NOWAIT);
    900 	if (dev->subdevs == NULL) {
    901 		FREEDEVINFO;
    902 		return (USBD_NOMEM);
    903 	}
    904 	dev->subdevs[0] = bdev;
    905 	dev->subdevs[1] = 0;
    906 	*uaap = uaa;
    907 	usbd_devinfo(dev, 1, devinfo, DEVINFOSIZE);
    908 	device_set_desc_copy(bdev, devinfo);
    909 #endif
    910 	dv = USB_DO_ATTACH(dev, bdev, parent, &uaa, usbd_print, usbd_submatch);
    911 	if (dv) {
    912 #if defined(__NetBSD__) || defined(__OpenBSD__)
    913 		dev->subdevs = malloc(2 * sizeof dv, M_USB, M_NOWAIT);
    914 		if (dev->subdevs == NULL)
    915 			return (USBD_NOMEM);
    916 		dev->subdevs[0] = dv;
    917 		dev->subdevs[1] = 0;
    918 #endif
    919 		FREEDEVINFO;
    920 		return (USBD_NORMAL_COMPLETION);
    921 	}
    922 #ifdef __FreeBSD__
    923 	/*
    924 	 * Free subdevs so we can reallocate it larger for the number of
    925 	 * interfaces
    926 	 */
    927 	tmpdv = dev->subdevs;
    928 	dev->subdevs = NULL;
    929 	free(tmpdv, M_USB);
    930 #ifdef USB_USE_IFATTACH
    931 	free(uaap, M_USB);
    932 	uiaap = malloc(sizeof(uiaa), M_USB, M_NOWAIT);
    933 	if (uiaap == NULL) {
    934 		FREEDEVINFO;
    935 		return (USBD_INVAL);
    936 	}
    937 	device_set_ivars(bdev, uiaap);
    938 #endif /* USB_USE_IFATTACH */
    939 #endif
    940 	DPRINTF(("usbd_probe_and_attach: no device specific driver found\n"));
    941 
    942 #ifdef USB_USE_IFATTACH
    943 	uiaa.device = dev;
    944 	uiaa.port = port;
    945 	uiaa.vendor = UGETW(dd->idVendor);
    946 	uiaa.product = UGETW(dd->idProduct);
    947 	uiaa.release = UGETW(dd->bcdDevice);
    948 #endif /* USB_USE_IFATTACH */
    949 
    950 	DPRINTF(("usbd_probe_and_attach: looping over %d configurations\n",
    951 		 dd->bNumConfigurations));
    952 	/* Next try with interface drivers. */
    953 	for (confi = 0; confi < dd->bNumConfigurations; confi++) {
    954 		DPRINTFN(1,("usbd_probe_and_attach: trying config idx=%d\n",
    955 			    confi));
    956 		err = usbd_set_config_index(dev, confi, 1);
    957 		if (err) {
    958 #ifdef USB_DEBUG
    959 			DPRINTF(("%s: port %d, set config at addr %d failed, "
    960 				 "error=%s\n", USBDEVPTRNAME(parent), port,
    961 				 addr, usbd_errstr(err)));
    962 #else
    963 			printf("%s: port %d, set config at addr %d failed\n",
    964 			       USBDEVPTRNAME(parent), port, addr);
    965 #endif
    966 			FREEDEVINFO;
    967 			return (err);
    968 		}
    969 		nifaces = dev->cdesc->bNumInterface;
    970 #ifndef USB_USE_IFATTACH
    971 		uaa.configno = dev->cdesc->bConfigurationValue;
    972 #else
    973 		uiaa.configno = dev->cdesc->bConfigurationValue;
    974 #endif /* USB_USE_IFATTACH */
    975 		ifaces = malloc(nifaces * sizeof(*ifaces), M_USB, M_NOWAIT);
    976 		if (ifaces == NULL)
    977 			goto nomem;
    978 		for (i = 0; i < nifaces; i++)
    979 			ifaces[i] = &dev->ifaces[i];
    980 #ifndef USB_USE_IFATTACH
    981 		uaa.ifaces = ifaces;
    982 		uaa.nifaces = nifaces;
    983 #else
    984 		uiaa.ifaces = ifaces;
    985 		uiaa.nifaces = nifaces;
    986 #endif /* USB_USE_IFATTACH */
    987 		dev->subdevs = malloc((nifaces+1) * sizeof dv, M_USB,M_NOWAIT);
    988 		if (dev->subdevs == NULL) {
    989 			free(ifaces, M_USB);
    990 nomem:
    991 			FREEDEVINFO;
    992 			return (USBD_NOMEM);
    993 		}
    994 		dev->ifacenums = malloc((nifaces) * sizeof(*dev->ifacenums),
    995 		    M_USB,M_NOWAIT);
    996 		if (dev->ifacenums == NULL) {
    997 			free(ifaces, M_USB);
    998 			FREEDEVINFO;
    999 			return (USBD_NOMEM);
   1000 		}
   1001 
   1002 		found = 0;
   1003 		for (i = 0; i < nifaces; i++) {
   1004 			if (ifaces[i] == NULL)
   1005 				continue; /* interface already claimed */
   1006 #ifndef USB_USE_IFATTACH
   1007 			uaa.iface = ifaces[i];
   1008 			uaa.ifaceno = ifaces[i]->idesc->bInterfaceNumber;
   1009 #else
   1010 			uiaa.iface = ifaces[i];
   1011 			uiaa.class = ifaces[i]->idesc->bInterfaceClass;
   1012 			uiaa.subclass = ifaces[i]->idesc->bInterfaceSubClass;
   1013 			uiaa.proto = ifaces[i]->idesc->bInterfaceProtocol;
   1014 			uiaa.ifaceno = ifaces[i]->idesc->bInterfaceNumber;
   1015 #endif /* USB_USE_IFATTACH */
   1016 			dev->ifacenums[found] = i;
   1017 #ifdef __FreeBSD__
   1018 			dev->subdevs[found] = bdev;
   1019 			dev->subdevs[found + 1] = 0;
   1020 #ifndef USB_USE_IFATTACH
   1021 			*uaap = uaa;
   1022 #else
   1023 			*uiaap = uaa;
   1024 #endif /* USB_USE_IFATTACH */
   1025 			usbd_devinfo(dev, 1, devinfo, DEVINFOSIZE);
   1026 			device_set_desc_copy(bdev, devinfo);
   1027 #endif
   1028 #ifndef USB_USE_IFATTACH
   1029 			dv = USB_DO_ATTACH(dev, bdev, parent, &uaa, usbd_print,
   1030 					   usbd_submatch);
   1031 #else
   1032 			dv = USB_DO_IFATTACH(dev, bdev, parent, &uiaa,
   1033 					     usbd_ifprint, usbd_ifsubmatch);
   1034 #endif /* USB_USE_IFATTACH */
   1035 			if (dv != NULL) {
   1036 #if defined(__NetBSD__) || defined(__OpenBSD__)
   1037 				dev->subdevs[found] = dv;
   1038 				dev->subdevs[found + 1] = 0;
   1039 #endif
   1040 				ifaces[i] = 0; /* consumed */
   1041 				found++;
   1042 #ifdef __FreeBSD__
   1043 				/* create another child for the next iface */
   1044 				bdev = device_add_child(parent, NULL, -1);
   1045 				if (!bdev) {
   1046 					device_printf(parent,
   1047 					    "Device add failed\n");
   1048 					FREEDEVINFO;
   1049 					free(ifaces, M_USB);
   1050 					return (USBD_NORMAL_COMPLETION);
   1051 				}
   1052 #ifndef USB_USE_IFATTACH
   1053 				uaap = malloc(sizeof(uaa), M_USB, M_NOWAIT);
   1054 				if (uaap == NULL) {
   1055 					FREEDEVINFO;
   1056 					free(ifaces, M_USB);
   1057 					return (USBD_NOMEM);
   1058 				}
   1059 				device_set_ivars(bdev, uaap);
   1060 #else
   1061 				uiaap = malloc(sizeof(uiaa), M_USB, M_NOWAIT);
   1062 				if (uiaap == NULL) {
   1063 					FREEDEVINFO;
   1064 					free(ifaces, M_USB);
   1065 					return (USBD_NOMEM);
   1066 				}
   1067 				device_set_ivars(bdev, uiaap);
   1068 #endif /* USB_USE_IFATTACH */
   1069 #endif	/* __FreBSD__ */
   1070 			} else {
   1071 				dev->subdevs[found] = 0;
   1072 			}
   1073 		}
   1074 		free(ifaces, M_USB);
   1075 		if (found != 0) {
   1076 #if defined(__FreeBSD__)
   1077 			/* remove the last created child.  It is unused */
   1078 #ifndef USB_USE_IFATTACH
   1079 			free(uaap, M_USB);
   1080 #else
   1081 			free(uiaap, M_USB);
   1082 #endif /* USB_USE_IFATTACH */
   1083 			FREEDEVINFO;
   1084 			device_delete_child(parent, bdev);
   1085 #endif
   1086 			return (USBD_NORMAL_COMPLETION);
   1087 		}
   1088 		tmpdv = dev->subdevs;
   1089 		dev->subdevs = NULL;
   1090 		free(tmpdv, M_USB);
   1091 		free(dev->ifacenums, M_USB);
   1092 		dev->ifacenums = NULL;
   1093 	}
   1094 	/* No interfaces were attached in any of the configurations. */
   1095 
   1096 	if (dd->bNumConfigurations > 1) /* don't change if only 1 config */
   1097 		usbd_set_config_index(dev, 0, 0);
   1098 
   1099 	DPRINTF(("usbd_probe_and_attach: no interface drivers found\n"));
   1100 
   1101 	/* Finally try the generic driver. */
   1102 #ifndef USB_USE_IFATTACH
   1103 	uaa.iface = NULL;
   1104 #endif /* USB_USE_IFATTACH */
   1105 	uaa.usegeneric = 1;
   1106 #ifndef USB_USE_IFATTACH
   1107 	uaa.configno = UHUB_UNK_CONFIGURATION;
   1108 	uaa.ifaceno = UHUB_UNK_INTERFACE;
   1109 #endif /* USB_USE_IFATTACH */
   1110 #ifdef __FreeBSD__
   1111 #ifdef USB_USE_IFATTACH
   1112 	free(uiaap, M_USB);
   1113 	uaap = malloc(sizeof(uaa), M_USB, M_NOWAIT);
   1114 	if (uaap == NULL) {
   1115 		FREEDEVINFO;
   1116 		return (USBD_INVAL);
   1117 	}
   1118 	device_set_ivars(bdev, uaap);
   1119 #endif /* USB_USE_IFATTACH */
   1120 	dev->subdevs = malloc(2 * sizeof dv, M_USB, M_NOWAIT);
   1121 	if (dev->subdevs == 0) {
   1122 		FREEDEVINFO;
   1123 		return (USBD_NOMEM);
   1124 	}
   1125 	dev->subdevs[0] = bdev;
   1126 	dev->subdevs[1] = 0;
   1127 	*uaap = uaa;
   1128 	usbd_devinfo(dev, 1, devinfo, DEVINFOSIZE);
   1129 	device_set_desc_copy(bdev, devinfo);
   1130 	FREEDEVINFO;
   1131 #endif
   1132 	dv = USB_DO_ATTACH(dev, bdev, parent, &uaa, usbd_print, usbd_submatch);
   1133 	if (dv != NULL) {
   1134 #if defined(__NetBSD__) || defined(__OpenBSD__)
   1135 		dev->subdevs = malloc(2 * sizeof dv, M_USB, M_NOWAIT);
   1136 		if (dev->subdevs == 0)
   1137 			return (USBD_NOMEM);
   1138 		dev->subdevs[0] = dv;
   1139 		dev->subdevs[1] = 0;
   1140 #endif
   1141 		return (USBD_NORMAL_COMPLETION);
   1142 	}
   1143 
   1144 	/*
   1145 	 * The generic attach failed, but leave the device as it is.
   1146 	 * We just did not find any drivers, that's all.  The device is
   1147 	 * fully operational and not harming anyone.
   1148 	 */
   1149 	DPRINTF(("usbd_probe_and_attach: generic attach failed\n"));
   1150 	return (USBD_NORMAL_COMPLETION);
   1151 #undef FREEDEVINFO
   1152 }
   1153 
   1154 
   1155 /*
   1156  * Called when a new device has been put in the powered state,
   1157  * but not yet in the addressed state.
   1158  * Get initial descriptor, set the address, get full descriptor,
   1159  * and attach a driver.
   1160  */
   1161 usbd_status
   1162 usbd_new_device(device_ptr_t parent, usbd_bus_handle bus, int depth,
   1163 		int speed, int port, struct usbd_port *up)
   1164 {
   1165 	usbd_device_handle dev, adev;
   1166 	struct usbd_device *hub;
   1167 	usb_device_descriptor_t *dd;
   1168 	usb_port_status_t ps;
   1169 	usbd_status err;
   1170 	int addr;
   1171 	int i;
   1172 	int p;
   1173 
   1174 	DPRINTF(("usbd_new_device bus=%p port=%d depth=%d speed=%d\n",
   1175 		 bus, port, depth, speed));
   1176 	addr = usbd_getnewaddr(bus);
   1177 	if (addr < 0) {
   1178 		printf("%s: No free USB addresses, new device ignored.\n",
   1179 		       USBDEVNAME(bus->bdev));
   1180 		return (USBD_NO_ADDR);
   1181 	}
   1182 
   1183 	dev = malloc(sizeof *dev, M_USB, M_NOWAIT|M_ZERO);
   1184 	if (dev == NULL)
   1185 		return (USBD_NOMEM);
   1186 
   1187 	dev->bus = bus;
   1188 
   1189 	/* Set up default endpoint handle. */
   1190 	dev->def_ep.edesc = &dev->def_ep_desc;
   1191 
   1192 	/* Set up default endpoint descriptor. */
   1193 	dev->def_ep_desc.bLength = USB_ENDPOINT_DESCRIPTOR_SIZE;
   1194 	dev->def_ep_desc.bDescriptorType = UDESC_ENDPOINT;
   1195 	dev->def_ep_desc.bEndpointAddress = USB_CONTROL_ENDPOINT;
   1196 	dev->def_ep_desc.bmAttributes = UE_CONTROL;
   1197 	USETW(dev->def_ep_desc.wMaxPacketSize, USB_MAX_IPACKET);
   1198 	dev->def_ep_desc.bInterval = 0;
   1199 
   1200 	dev->quirks = &usbd_no_quirk;
   1201 	dev->address = USB_START_ADDR;
   1202 	dev->ddesc.bMaxPacketSize = 0;
   1203 	dev->depth = depth;
   1204 	dev->powersrc = up;
   1205 	dev->myhub = up->parent;
   1206 
   1207 	up->device = dev;
   1208 
   1209 	/* Locate port on upstream high speed hub */
   1210 	for (adev = dev, hub = up->parent;
   1211 	     hub != NULL && hub->speed != USB_SPEED_HIGH;
   1212 	     adev = hub, hub = hub->myhub)
   1213 		;
   1214 	if (hub) {
   1215 		for (p = 0; p < hub->hub->hubdesc.bNbrPorts; p++) {
   1216 			if (hub->hub->ports[p].device == adev) {
   1217 				dev->myhsport = &hub->hub->ports[p];
   1218 				goto found;
   1219 			}
   1220 		}
   1221 		panic("usbd_new_device: cannot find HS port\n");
   1222 	found:
   1223 		DPRINTFN(1,("usbd_new_device: high speed port %d\n", p));
   1224 	} else {
   1225 		dev->myhsport = NULL;
   1226 	}
   1227 	dev->speed = speed;
   1228 	dev->langid = USBD_NOLANG;
   1229 	dev->cookie.cookie = ++usb_cookie_no;
   1230 
   1231 	/* Establish the default pipe. */
   1232 	err = usbd_setup_pipe(dev, 0, &dev->def_ep, USBD_DEFAULT_INTERVAL,
   1233 			      &dev->default_pipe);
   1234 	if (err) {
   1235 		usbd_remove_device(dev, up);
   1236 		return (err);
   1237 	}
   1238 
   1239 	/* Set the address.  Do this early; some devices need that. */
   1240 	/* Try a few times in case the device is slow (i.e. outside specs.) */
   1241 	DPRINTFN(5,("usbd_new_device: setting device address=%d\n", addr));
   1242 	for (i = 0; i < 15; i++) {
   1243 		err = usbd_set_address(dev, addr);
   1244 		if (!err)
   1245 			break;
   1246 		usbd_delay_ms(dev, 200);
   1247 		if ((i & 3) == 3) {
   1248 			DPRINTFN(-1,("usbd_new_device: set address %d "
   1249 			    "failed - trying a port reset\n", addr));
   1250 			usbd_reset_port(up->parent, port, &ps);
   1251 		}
   1252 	}
   1253 	if (err) {
   1254 		DPRINTFN(-1,("usbd_new_device: set address %d failed\n", addr));
   1255 		err = USBD_SET_ADDR_FAILED;
   1256 		usbd_remove_device(dev, up);
   1257 		return (err);
   1258 	}
   1259 	/* Allow device time to set new address */
   1260 	usbd_delay_ms(dev, USB_SET_ADDRESS_SETTLE);
   1261 	dev->address = addr;	/* New device address now */
   1262 	bus->devices[addr] = dev;
   1263 
   1264 	/* Re-establish the default pipe with the new address. */
   1265 	usbd_kill_pipe(dev->default_pipe);
   1266 	err = usbd_setup_pipe(dev, 0, &dev->def_ep, USBD_DEFAULT_INTERVAL,
   1267 	    &dev->default_pipe);
   1268 	if (err) {
   1269 		usbd_remove_device(dev, up);
   1270 		return (err);
   1271 	}
   1272 
   1273 	dd = &dev->ddesc;
   1274 	/* Get the first 8 bytes of the device descriptor. */
   1275 	err = usbd_get_desc(dev, UDESC_DEVICE, 0, USB_MAX_IPACKET, dd);
   1276 	if (err) {
   1277 		DPRINTFN(-1, ("usbd_new_device: addr=%d, getting first desc "
   1278 			      "failed\n", addr));
   1279 		usbd_remove_device(dev, up);
   1280 		return (err);
   1281 	}
   1282 
   1283 	if (speed == USB_SPEED_HIGH) {
   1284 		/* Max packet size must be 64 (sec 5.5.3). */
   1285 		if (dd->bMaxPacketSize != USB_2_MAX_CTRL_PACKET) {
   1286 #ifdef DIAGNOSTIC
   1287 			printf("usbd_new_device: addr=%d bad max packet size\n",
   1288 			       addr);
   1289 #endif
   1290 			dd->bMaxPacketSize = USB_2_MAX_CTRL_PACKET;
   1291 		}
   1292 	}
   1293 
   1294 	DPRINTF(("usbd_new_device: adding unit addr=%d, rev=%02x, class=%d, "
   1295 		 "subclass=%d, protocol=%d, maxpacket=%d, len=%d, speed=%d\n",
   1296 		 addr,UGETW(dd->bcdUSB), dd->bDeviceClass, dd->bDeviceSubClass,
   1297 		 dd->bDeviceProtocol, dd->bMaxPacketSize, dd->bLength,
   1298 		 dev->speed));
   1299 
   1300 	if (dd->bDescriptorType != UDESC_DEVICE) {
   1301 		/* Illegal device descriptor */
   1302 		DPRINTFN(-1,("usbd_new_device: illegal descriptor %d\n",
   1303 			     dd->bDescriptorType));
   1304 		usbd_remove_device(dev, up);
   1305 		return (USBD_INVAL);
   1306 	}
   1307 
   1308 	if (dd->bLength < USB_DEVICE_DESCRIPTOR_SIZE) {
   1309 		DPRINTFN(-1,("usbd_new_device: bad length %d\n", dd->bLength));
   1310 		usbd_remove_device(dev, up);
   1311 		return (USBD_INVAL);
   1312 	}
   1313 
   1314 	USETW(dev->def_ep_desc.wMaxPacketSize, dd->bMaxPacketSize);
   1315 
   1316 	/* Re-establish the default pipe with the new max packet size. */
   1317 	usbd_kill_pipe(dev->default_pipe);
   1318 	err = usbd_setup_pipe(dev, 0, &dev->def_ep, USBD_DEFAULT_INTERVAL,
   1319 	    &dev->default_pipe);
   1320 	if (err) {
   1321 		usbd_remove_device(dev, up);
   1322 		return (err);
   1323 	}
   1324 
   1325 	err = usbd_reload_device_desc(dev);
   1326 	if (err) {
   1327 		DPRINTFN(-1, ("usbd_new_device: addr=%d, getting full desc "
   1328 			      "failed\n", addr));
   1329 		usbd_remove_device(dev, up);
   1330 		return (err);
   1331 	}
   1332 
   1333 	/* Assume 100mA bus powered for now. Changed when configured. */
   1334 	dev->power = USB_MIN_POWER;
   1335 	dev->self_powered = 0;
   1336 
   1337 	DPRINTF(("usbd_new_device: new dev (addr %d), dev=%p, parent=%p\n",
   1338 		 addr, dev, parent));
   1339 
   1340 	err = usbd_probe_and_attach(parent, dev, port, addr);
   1341 	if (err) {
   1342 		usbd_remove_device(dev, up);
   1343 		return (err);
   1344 	}
   1345 
   1346 	usbd_add_dev_event(USB_EVENT_DEVICE_ATTACH, dev);
   1347 
   1348 	return (USBD_NORMAL_COMPLETION);
   1349 }
   1350 
   1351 usbd_status
   1352 usbd_reload_device_desc(usbd_device_handle dev)
   1353 {
   1354 	usbd_status err;
   1355 	int i;
   1356 
   1357 	/* Get the full device descriptor. */
   1358 	for (i = 0; ; ++i) {
   1359 		err = usbd_get_device_desc(dev, &dev->ddesc);
   1360 		if (!err || i >= 3)
   1361 			break;
   1362 		usbd_delay_ms(dev, 200);
   1363 	}
   1364 	if (err)
   1365 		return (err);
   1366 
   1367 	/* Figure out what's wrong with this device. */
   1368 	dev->quirks = usbd_find_quirk(&dev->ddesc);
   1369 
   1370 	return (USBD_NORMAL_COMPLETION);
   1371 }
   1372 
   1373 void
   1374 usbd_remove_device(usbd_device_handle dev, struct usbd_port *up)
   1375 {
   1376 	DPRINTF(("usbd_remove_device: %p\n", dev));
   1377 
   1378 	if (dev->default_pipe != NULL)
   1379 		usbd_kill_pipe(dev->default_pipe);
   1380 	up->device = NULL;
   1381 	dev->bus->devices[dev->address] = NULL;
   1382 
   1383 	free(dev, M_USB);
   1384 }
   1385 
   1386 #if defined(__NetBSD__) || defined(__OpenBSD__)
   1387 int
   1388 usbd_print(void *aux, const char *pnp)
   1389 {
   1390 	struct usb_attach_arg *uaa = aux;
   1391 	char *devinfo;
   1392 
   1393 	DPRINTFN(15, ("usbd_print dev=%p\n", uaa->device));
   1394 	if (pnp) {
   1395 		if (!uaa->usegeneric)
   1396 			return (QUIET);
   1397 		devinfo = usbd_devinfo_alloc(uaa->device, 1);
   1398 		aprint_normal("%s, %s", devinfo, pnp);
   1399 		usbd_devinfo_free(devinfo);
   1400 	}
   1401 	if (uaa->port != 0)
   1402 		aprint_normal(" port %d", uaa->port);
   1403 #ifndef USB_USE_IFATTACH
   1404 	if (uaa->configno != UHUB_UNK_CONFIGURATION)
   1405 		aprint_normal(" configuration %d", uaa->configno);
   1406 	if (uaa->ifaceno != UHUB_UNK_INTERFACE)
   1407 		aprint_normal(" interface %d", uaa->ifaceno);
   1408 #endif /* USB_USE_IFATTACH */
   1409 #if 0
   1410 	/*
   1411 	 * It gets very crowded with these locators on the attach line.
   1412 	 * They are not really needed since they are printed in the clear
   1413 	 * by each driver.
   1414 	 */
   1415 	if (uaa->vendor != UHUB_UNK_VENDOR)
   1416 		aprint_normal(" vendor 0x%04x", uaa->vendor);
   1417 	if (uaa->product != UHUB_UNK_PRODUCT)
   1418 		aprint_normal(" product 0x%04x", uaa->product);
   1419 	if (uaa->release != UHUB_UNK_RELEASE)
   1420 		aprint_normal(" release 0x%04x", uaa->release);
   1421 #endif
   1422 	return (UNCONF);
   1423 }
   1424 
   1425 #ifdef USB_USE_IFATTACH
   1426 int
   1427 usbd_ifprint(void *aux, const char *pnp)
   1428 {
   1429 	struct usbif_attach_arg *uaa = aux;
   1430 
   1431 	DPRINTFN(15, ("usbd_print dev=%p\n", uaa->device));
   1432 	if (pnp)
   1433 		return (QUIET);
   1434 	if (uaa->port != 0)
   1435 		aprint_normal(" port %d", uaa->port);
   1436 	if (uaa->configno != UHUB_UNK_CONFIGURATION)
   1437 		aprint_normal(" configuration %d", uaa->configno);
   1438 	if (uaa->ifaceno != UHUB_UNK_INTERFACE)
   1439 		aprint_normal(" interface %d", uaa->ifaceno);
   1440 #if 0
   1441 	/*
   1442 	 * It gets very crowded with these locators on the attach line.
   1443 	 * They are not really needed since they are printed in the clear
   1444 	 * by each driver.
   1445 	 */
   1446 	if (uaa->vendor != UHUB_UNK_VENDOR)
   1447 		aprint_normal(" vendor 0x%04x", uaa->vendor);
   1448 	if (uaa->product != UHUB_UNK_PRODUCT)
   1449 		aprint_normal(" product 0x%04x", uaa->product);
   1450 	if (uaa->release != UHUB_UNK_RELEASE)
   1451 		aprint_normal(" release 0x%04x", uaa->release);
   1452 #endif
   1453 	return (UNCONF);
   1454 }
   1455 #endif /* USB_USE_IFATTACH */
   1456 
   1457 #if defined(__NetBSD__)
   1458 int
   1459 usbd_submatch(struct device *parent, struct cfdata *cf,
   1460 	      const int *ldesc, void *aux)
   1461 {
   1462 #elif defined(__OpenBSD__)
   1463 int
   1464 usbd_submatch(struct device *parent, void *match, void *aux)
   1465 {
   1466 	struct cfdata *cf = match;
   1467 #endif
   1468 	struct usb_attach_arg *uaa = aux;
   1469 
   1470 #ifdef USB_USE_IFATTACH
   1471 	DPRINTFN(5,("usbd_submatch port=%d,%d "
   1472 	    "vendor=%d,%d product=%d,%d release=%d,%d\n",
   1473 	    uaa->port, cf->uhubcf_port,
   1474 	    uaa->vendor, cf->uhubcf_vendor,
   1475 	    uaa->product, cf->uhubcf_product,
   1476 	    uaa->release, cf->uhubcf_release));
   1477 	if (uaa->port != 0 &&	/* root hub has port 0, it should match */
   1478 	    ((cf->uhubcf_port != UHUB_UNK_PORT &&
   1479 	      cf->uhubcf_port != uaa->port) ||
   1480 	     (uaa->vendor != UHUB_UNK_VENDOR &&
   1481 	      cf->uhubcf_vendor != UHUB_UNK_VENDOR &&
   1482 	      cf->uhubcf_vendor != uaa->vendor) ||
   1483 	     (uaa->product != UHUB_UNK_PRODUCT &&
   1484 	      cf->uhubcf_product != UHUB_UNK_PRODUCT &&
   1485 	      cf->uhubcf_product != uaa->product) ||
   1486 	     (uaa->release != UHUB_UNK_RELEASE &&
   1487 	      cf->uhubcf_release != UHUB_UNK_RELEASE &&
   1488 	      cf->uhubcf_release != uaa->release)
   1489 	     )
   1490 	   )
   1491 		return 0;
   1492 	return (config_match(parent, cf, aux));
   1493 }
   1494 
   1495 int
   1496 usbd_ifsubmatch(struct device *parent, struct cfdata *cf,
   1497 	      const int *ldesc, void *aux)
   1498 {
   1499 	struct usbif_attach_arg *uaa = aux;
   1500 
   1501 #endif /* USB_USE_IFATTACH */
   1502 	DPRINTFN(5,("usbd_submatch port=%d,%d configno=%d,%d "
   1503 	    "ifaceno=%d,%d vendor=%d,%d product=%d,%d release=%d,%d\n",
   1504 	    uaa->port, cf->uhubcf_port,
   1505 	    uaa->configno, cf->uhubcf_configuration,
   1506 	    uaa->ifaceno, cf->uhubcf_interface,
   1507 	    uaa->vendor, cf->uhubcf_vendor,
   1508 	    uaa->product, cf->uhubcf_product,
   1509 	    uaa->release, cf->uhubcf_release));
   1510 	if (uaa->port != 0 &&	/* root hub has port 0, it should match */
   1511 	    ((cf->uhubcf_port != UHUB_UNK_PORT &&
   1512 	      cf->uhubcf_port != uaa->port) ||
   1513 	     (uaa->configno != UHUB_UNK_CONFIGURATION &&
   1514 	      cf->uhubcf_configuration != UHUB_UNK_CONFIGURATION &&
   1515 	      cf->uhubcf_configuration != uaa->configno) ||
   1516 	     (uaa->ifaceno != UHUB_UNK_INTERFACE &&
   1517 	      cf->uhubcf_interface != UHUB_UNK_INTERFACE &&
   1518 	      cf->uhubcf_interface != uaa->ifaceno) ||
   1519 	     (uaa->vendor != UHUB_UNK_VENDOR &&
   1520 	      cf->uhubcf_vendor != UHUB_UNK_VENDOR &&
   1521 	      cf->uhubcf_vendor != uaa->vendor) ||
   1522 	     (uaa->product != UHUB_UNK_PRODUCT &&
   1523 	      cf->uhubcf_product != UHUB_UNK_PRODUCT &&
   1524 	      cf->uhubcf_product != uaa->product) ||
   1525 	     (uaa->release != UHUB_UNK_RELEASE &&
   1526 	      cf->uhubcf_release != UHUB_UNK_RELEASE &&
   1527 	      cf->uhubcf_release != uaa->release)
   1528 	     )
   1529 	   )
   1530 		return 0;
   1531 	return (config_match(parent, cf, aux));
   1532 }
   1533 #endif	/* defined(__NetBSD__) || defined(__OpenBSD__) */
   1534 
   1535 void
   1536 usbd_fill_deviceinfo(usbd_device_handle dev, struct usb_device_info *di,
   1537 		     int usedev)
   1538 {
   1539 	struct usbd_port *p;
   1540 	int i, err, s;
   1541 
   1542 	di->udi_bus = USBDEVUNIT(dev->bus->bdev);
   1543 	di->udi_addr = dev->address;
   1544 	di->udi_cookie = dev->cookie;
   1545 	usbd_devinfo_vp(dev, di->udi_vendor, di->udi_product, usedev, 1);
   1546 	usbd_printBCD(di->udi_release, sizeof(di->udi_release),
   1547 	    UGETW(dev->ddesc.bcdDevice));
   1548 	di->udi_serial[0] = 0;
   1549 	if (usedev)
   1550 		(void)usbd_get_string(dev, dev->ddesc.iSerialNumber,
   1551 				      di->udi_serial);
   1552 	di->udi_vendorNo = UGETW(dev->ddesc.idVendor);
   1553 	di->udi_productNo = UGETW(dev->ddesc.idProduct);
   1554 	di->udi_releaseNo = UGETW(dev->ddesc.bcdDevice);
   1555 	di->udi_class = dev->ddesc.bDeviceClass;
   1556 	di->udi_subclass = dev->ddesc.bDeviceSubClass;
   1557 	di->udi_protocol = dev->ddesc.bDeviceProtocol;
   1558 	di->udi_config = dev->config;
   1559 	di->udi_power = dev->self_powered ? 0 : dev->power;
   1560 	di->udi_speed = dev->speed;
   1561 
   1562 	if (dev->subdevs != NULL) {
   1563 		for (i = 0; dev->subdevs[i] && i < USB_MAX_DEVNAMES; i++) {
   1564 #ifdef __FreeBSD__
   1565 			/* FreeBSD may have device structure without attach. */
   1566 			if (!device_is_attached(dev->subdevs[i]))
   1567 				di->udi_devnames[i][0] = 0;
   1568 			else
   1569 #endif
   1570 			{
   1571 				strlcpy(di->udi_devnames[i],
   1572 				    USBDEVPTRNAME(dev->subdevs[i]),
   1573 				    USB_MAX_DEVNAMELEN);
   1574 			}
   1575 		}
   1576 	} else {
   1577 		i = 0;
   1578 	}
   1579 	for (/*i is set */; i < USB_MAX_DEVNAMES; i++)
   1580 		di->udi_devnames[i][0] = 0;                 /* empty */
   1581 
   1582 	if (dev->hub) {
   1583 		for (i = 0;
   1584 		     i < sizeof(di->udi_ports) / sizeof(di->udi_ports[0]) &&
   1585 			     i < dev->hub->hubdesc.bNbrPorts;
   1586 		     i++) {
   1587 			p = &dev->hub->ports[i];
   1588 			if (p->device)
   1589 				err = p->device->address;
   1590 			else {
   1591 				s = UGETW(p->status.wPortStatus);
   1592 				if (s & UPS_PORT_ENABLED)
   1593 					err = USB_PORT_ENABLED;
   1594 				else if (s & UPS_SUSPEND)
   1595 					err = USB_PORT_SUSPENDED;
   1596 				else if (s & UPS_PORT_POWER)
   1597 					err = USB_PORT_POWERED;
   1598 				else
   1599 					err = USB_PORT_DISABLED;
   1600 			}
   1601 			di->udi_ports[i] = err;
   1602 		}
   1603 		di->udi_nports = dev->hub->hubdesc.bNbrPorts;
   1604 	} else
   1605 		di->udi_nports = 0;
   1606 }
   1607 
   1608 #if defined(__NetBSD__) && defined(COMPAT_30)
   1609 void
   1610 usbd_fill_deviceinfo_old(usbd_device_handle dev, struct usb_device_info_old *di,
   1611 			 int usedev)
   1612 {
   1613 	struct usbd_port *p;
   1614 	int i, err, s;
   1615 
   1616 	di->udi_bus = USBDEVUNIT(dev->bus->bdev);
   1617 	di->udi_addr = dev->address;
   1618 	di->udi_cookie = dev->cookie;
   1619 	usbd_devinfo_vp(dev, di->udi_vendor, di->udi_product, usedev, 0);
   1620 	usbd_printBCD(di->udi_release, sizeof(di->udi_release),
   1621 	    UGETW(dev->ddesc.bcdDevice));
   1622 	di->udi_vendorNo = UGETW(dev->ddesc.idVendor);
   1623 	di->udi_productNo = UGETW(dev->ddesc.idProduct);
   1624 	di->udi_releaseNo = UGETW(dev->ddesc.bcdDevice);
   1625 	di->udi_class = dev->ddesc.bDeviceClass;
   1626 	di->udi_subclass = dev->ddesc.bDeviceSubClass;
   1627 	di->udi_protocol = dev->ddesc.bDeviceProtocol;
   1628 	di->udi_config = dev->config;
   1629 	di->udi_power = dev->self_powered ? 0 : dev->power;
   1630 	di->udi_speed = dev->speed;
   1631 
   1632 	if (dev->subdevs != NULL) {
   1633 		for (i = 0; dev->subdevs[i] &&
   1634 			     i < USB_MAX_DEVNAMES; i++) {
   1635 			strncpy(di->udi_devnames[i], USBDEVPTRNAME(dev->subdevs[i]),
   1636 				USB_MAX_DEVNAMELEN);
   1637 			di->udi_devnames[i][USB_MAX_DEVNAMELEN-1] = '\0';
   1638 		}
   1639 	} else {
   1640 		i = 0;
   1641 	}
   1642 	for (/*i is set */; i < USB_MAX_DEVNAMES; i++)
   1643 		di->udi_devnames[i][0] = 0;		 /* empty */
   1644 
   1645 	if (dev->hub) {
   1646 		for (i = 0;
   1647 		     i < sizeof(di->udi_ports) / sizeof(di->udi_ports[0]) &&
   1648 			     i < dev->hub->hubdesc.bNbrPorts;
   1649 		     i++) {
   1650 			p = &dev->hub->ports[i];
   1651 			if (p->device)
   1652 				err = p->device->address;
   1653 			else {
   1654 				s = UGETW(p->status.wPortStatus);
   1655 				if (s & UPS_PORT_ENABLED)
   1656 					err = USB_PORT_ENABLED;
   1657 				else if (s & UPS_SUSPEND)
   1658 					err = USB_PORT_SUSPENDED;
   1659 				else if (s & UPS_PORT_POWER)
   1660 					err = USB_PORT_POWERED;
   1661 				else
   1662 					err = USB_PORT_DISABLED;
   1663 			}
   1664 			di->udi_ports[i] = err;
   1665 		}
   1666 		di->udi_nports = dev->hub->hubdesc.bNbrPorts;
   1667 	} else
   1668 		di->udi_nports = 0;
   1669 }
   1670 #endif	/* defined(__NetBSD__) && defined(COMPAT_30) */
   1671 
   1672 
   1673 void
   1674 usb_free_device(usbd_device_handle dev)
   1675 {
   1676 	int ifcidx, nifc;
   1677 
   1678 	if (dev->default_pipe != NULL)
   1679 		usbd_kill_pipe(dev->default_pipe);
   1680 	if (dev->ifaces != NULL) {
   1681 		nifc = dev->cdesc->bNumInterface;
   1682 		for (ifcidx = 0; ifcidx < nifc; ifcidx++)
   1683 			usbd_free_iface_data(dev, ifcidx);
   1684 		free(dev->ifaces, M_USB);
   1685 	}
   1686 	if (dev->cdesc != NULL)
   1687 		free(dev->cdesc, M_USB);
   1688 	if (dev->subdevs != NULL)
   1689 		free(dev->subdevs, M_USB);
   1690 	if (dev->ifacenums != NULL)
   1691 		free(dev->ifacenums, M_USB);
   1692 	free(dev, M_USB);
   1693 }
   1694 
   1695 /*
   1696  * The general mechanism for detaching drivers works as follows: Each
   1697  * driver is responsible for maintaining a reference count on the
   1698  * number of outstanding references to its softc (e.g.  from
   1699  * processing hanging in a read or write).  The detach method of the
   1700  * driver decrements this counter and flags in the softc that the
   1701  * driver is dying and then wakes any sleepers.  It then sleeps on the
   1702  * softc.  Each place that can sleep must maintain the reference
   1703  * count.  When the reference count drops to -1 (0 is the normal value
   1704  * of the reference count) the a wakeup on the softc is performed
   1705  * signaling to the detach waiter that all references are gone.
   1706  */
   1707 
   1708 /*
   1709  * Called from process context when we discover that a port has
   1710  * been disconnected.
   1711  */
   1712 void
   1713 usb_disconnect_port(struct usbd_port *up, device_ptr_t parent)
   1714 {
   1715 	usbd_device_handle dev = up->device;
   1716 	const char *hubname = USBDEVPTRNAME(parent);
   1717 	int i;
   1718 
   1719 	DPRINTFN(3,("uhub_disconnect: up=%p dev=%p port=%d\n",
   1720 		    up, dev, up->portno));
   1721 
   1722 #ifdef DIAGNOSTIC
   1723 	if (dev == NULL) {
   1724 		printf("usb_disconnect_port: no device\n");
   1725 		return;
   1726 	}
   1727 #endif
   1728 
   1729 	if (dev->subdevs != NULL) {
   1730 		DPRINTFN(3,("usb_disconnect_port: disconnect subdevs\n"));
   1731 		for (i = 0; dev->subdevs[i]; i++) {
   1732 			printf("%s: at %s", USBDEVPTRNAME(dev->subdevs[i]),
   1733 			       hubname);
   1734 			if (up->portno != 0)
   1735 				printf(" port %d", up->portno);
   1736 			printf(" (addr %d) disconnected\n", dev->address);
   1737 			config_detach(dev->subdevs[i], DETACH_FORCE);
   1738 			dev->subdevs[i] = NULL;
   1739 		}
   1740 	}
   1741 
   1742 	usbd_add_dev_event(USB_EVENT_DEVICE_DETACH, dev);
   1743 	dev->bus->devices[dev->address] = NULL;
   1744 	up->device = NULL;
   1745 	usb_free_device(dev);
   1746 }
   1747