Home | History | Annotate | Line # | Download | only in usb
usb_subr.c revision 1.81
      1 /*	$NetBSD: usb_subr.c,v 1.81 2000/10/24 15:01:26 augustss 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 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  * 3. All advertising materials mentioning features or use of this software
     21  *    must display the following acknowledgement:
     22  *        This product includes software developed by the NetBSD
     23  *        Foundation, Inc. and its contributors.
     24  * 4. Neither the name of The NetBSD Foundation nor the names of its
     25  *    contributors may be used to endorse or promote products derived
     26  *    from this software without specific prior written permission.
     27  *
     28  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     29  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     30  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     31  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     32  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     33  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     34  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     35  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     36  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     37  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     38  * POSSIBILITY OF SUCH DAMAGE.
     39  */
     40 
     41 #include <sys/param.h>
     42 #include <sys/systm.h>
     43 #include <sys/kernel.h>
     44 #include <sys/malloc.h>
     45 #if defined(__NetBSD__) || defined(__OpenBSD__)
     46 #include <sys/device.h>
     47 #include <sys/select.h>
     48 #elif defined(__FreeBSD__)
     49 #include <sys/module.h>
     50 #include <sys/bus.h>
     51 #endif
     52 #include <sys/proc.h>
     53 
     54 #include <machine/bus.h>
     55 
     56 #include <dev/usb/usb.h>
     57 
     58 #include <dev/usb/usbdi.h>
     59 #include <dev/usb/usbdi_util.h>
     60 #include <dev/usb/usbdivar.h>
     61 #include <dev/usb/usbdevs.h>
     62 #include <dev/usb/usb_quirks.h>
     63 
     64 #if defined(__FreeBSD__)
     65 #include <machine/clock.h>
     66 #define delay(d)         DELAY(d)
     67 #endif
     68 
     69 #ifdef USB_DEBUG
     70 #define DPRINTF(x)	if (usbdebug) logprintf x
     71 #define DPRINTFN(n,x)	if (usbdebug>(n)) logprintf x
     72 extern int usbdebug;
     73 #else
     74 #define DPRINTF(x)
     75 #define DPRINTFN(n,x)
     76 #endif
     77 
     78 Static usbd_status	usbd_set_config(usbd_device_handle, int);
     79 Static char *usbd_get_string(usbd_device_handle, int, char *);
     80 Static int usbd_getnewaddr(usbd_bus_handle bus);
     81 #if defined(__NetBSD__)
     82 Static int usbd_print(void *aux, const char *pnp);
     83 Static int usbd_submatch(device_ptr_t, struct cfdata *cf, void *);
     84 #elif defined(__OpenBSD__)
     85 Static int usbd_print(void *aux, const char *pnp);
     86 Static int usbd_submatch(device_ptr_t, void *, void *);
     87 #endif
     88 Static void usbd_free_iface_data(usbd_device_handle dev, int ifcno);
     89 Static void usbd_kill_pipe(usbd_pipe_handle);
     90 Static usbd_status usbd_probe_and_attach(device_ptr_t parent,
     91 				 usbd_device_handle dev, int port, int addr);
     92 
     93 Static u_int32_t usb_cookie_no = 0;
     94 
     95 #ifdef USBVERBOSE
     96 typedef u_int16_t usb_vendor_id_t;
     97 typedef u_int16_t usb_product_id_t;
     98 
     99 /*
    100  * Descriptions of of known vendors and devices ("products").
    101  */
    102 struct usb_knowndev {
    103 	usb_vendor_id_t		vendor;
    104 	usb_product_id_t	product;
    105 	int			flags;
    106 	char			*vendorname, *productname;
    107 };
    108 #define	USB_KNOWNDEV_NOPROD	0x01		/* match on vendor only */
    109 
    110 #include <dev/usb/usbdevs_data.h>
    111 #endif /* USBVERBOSE */
    112 
    113 Static const char *usbd_error_strs[] = {
    114 	"NORMAL_COMPLETION",
    115 	"IN_PROGRESS",
    116 	"PENDING_REQUESTS",
    117 	"NOT_STARTED",
    118 	"INVAL",
    119 	"NOMEM",
    120 	"CANCELLED",
    121 	"BAD_ADDRESS",
    122 	"IN_USE",
    123 	"NO_ADDR",
    124 	"SET_ADDR_FAILED",
    125 	"NO_POWER",
    126 	"TOO_DEEP",
    127 	"IOERROR",
    128 	"NOT_CONFIGURED",
    129 	"TIMEOUT",
    130 	"SHORT_XFER",
    131 	"STALLED",
    132 	"INTERRUPTED",
    133 	"XXX",
    134 };
    135 
    136 const char *
    137 usbd_errstr(usbd_status err)
    138 {
    139 	static char buffer[5];
    140 
    141 	if (err < USBD_ERROR_MAX) {
    142 		return usbd_error_strs[err];
    143 	} else {
    144 		snprintf(buffer, sizeof buffer, "%d", err);
    145 		return buffer;
    146 	}
    147 }
    148 
    149 usbd_status
    150 usbd_get_string_desc(usbd_device_handle dev, int sindex, int langid,
    151 		     usb_string_descriptor_t *sdesc)
    152 {
    153 	usb_device_request_t req;
    154 	usbd_status err;
    155 
    156 	req.bmRequestType = UT_READ_DEVICE;
    157 	req.bRequest = UR_GET_DESCRIPTOR;
    158 	USETW2(req.wValue, UDESC_STRING, sindex);
    159 	USETW(req.wIndex, langid);
    160 	USETW(req.wLength, 1);	/* only size byte first */
    161 	err = usbd_do_request(dev, &req, sdesc);
    162 	if (err)
    163 		return (err);
    164 	USETW(req.wLength, sdesc->bLength);	/* the whole string */
    165 	return (usbd_do_request(dev, &req, sdesc));
    166 }
    167 
    168 char *
    169 usbd_get_string(usbd_device_handle dev, int si, char *buf)
    170 {
    171 	int swap = dev->quirks->uq_flags & UQ_SWAP_UNICODE;
    172 	usb_string_descriptor_t us;
    173 	char *s;
    174 	int i, n;
    175 	u_int16_t c;
    176 	usbd_status err;
    177 
    178 	if (si == 0)
    179 		return (0);
    180 	if (dev->quirks->uq_flags & UQ_NO_STRINGS)
    181 		return (0);
    182 	if (dev->langid == USBD_NOLANG) {
    183 		/* Set up default language */
    184 		err = usbd_get_string_desc(dev, USB_LANGUAGE_TABLE, 0, &us);
    185 		if (err || us.bLength < 4) {
    186 			dev->langid = 0; /* Well, just pick English then */
    187 		} else {
    188 			/* Pick the first language as the default. */
    189 			dev->langid = UGETW(us.bString[0]);
    190 		}
    191 	}
    192 	err = usbd_get_string_desc(dev, si, dev->langid, &us);
    193 	if (err)
    194 		return (0);
    195 	s = buf;
    196 	n = us.bLength / 2 - 1;
    197 	for (i = 0; i < n; i++) {
    198 		c = UGETW(us.bString[i]);
    199 		/* Convert from Unicode, handle buggy strings. */
    200 		if ((c & 0xff00) == 0)
    201 			*s++ = c;
    202 		else if ((c & 0x00ff) == 0 && swap)
    203 			*s++ = c >> 8;
    204 		else
    205 			*s++ = '?';
    206 	}
    207 	*s++ = 0;
    208 	return (buf);
    209 }
    210 
    211 void
    212 usbd_devinfo_vp(usbd_device_handle dev, char *v, char *p)
    213 {
    214 	usb_device_descriptor_t *udd = &dev->ddesc;
    215 	char *vendor = 0, *product = 0;
    216 #ifdef USBVERBOSE
    217 	struct usb_knowndev *kdp;
    218 #endif
    219 
    220 	if (dev == NULL) {
    221 		v[0] = p[0] = '\0';
    222 		return;
    223 	}
    224 
    225 	vendor = usbd_get_string(dev, udd->iManufacturer, v);
    226 	product = usbd_get_string(dev, udd->iProduct, p);
    227 #ifdef USBVERBOSE
    228 	if (vendor == NULL || product == NULL) {
    229 		for(kdp = usb_knowndevs;
    230 		    kdp->vendorname != NULL;
    231 		    kdp++) {
    232 			if (kdp->vendor == UGETW(udd->idVendor) &&
    233 			    (kdp->product == UGETW(udd->idProduct) ||
    234 			     (kdp->flags & USB_KNOWNDEV_NOPROD) != 0))
    235 				break;
    236 		}
    237 		if (kdp->vendorname != NULL) {
    238 			if (!vendor)
    239 			    vendor = kdp->vendorname;
    240 			if (!product)
    241 			    product = (kdp->flags & USB_KNOWNDEV_NOPROD) == 0 ?
    242 				kdp->productname : NULL;
    243 		}
    244 	}
    245 #endif
    246 	if (vendor != NULL && *vendor)
    247 		strcpy(v, vendor);
    248 	else
    249 		sprintf(v, "vendor 0x%04x", UGETW(udd->idVendor));
    250 	if (product != NULL && *product)
    251 		strcpy(p, product);
    252 	else
    253 		sprintf(p, "product 0x%04x", UGETW(udd->idProduct));
    254 }
    255 
    256 int
    257 usbd_printBCD(char *cp, int bcd)
    258 {
    259 	return (sprintf(cp, "%x.%02x", bcd >> 8, bcd & 0xff));
    260 }
    261 
    262 void
    263 usbd_devinfo(usbd_device_handle dev, int showclass, char *cp)
    264 {
    265 	usb_device_descriptor_t *udd = &dev->ddesc;
    266 	char vendor[USB_MAX_STRING_LEN];
    267 	char product[USB_MAX_STRING_LEN];
    268 	int bcdDevice, bcdUSB;
    269 
    270 	usbd_devinfo_vp(dev, vendor, product);
    271 	cp += sprintf(cp, "%s %s", vendor, product);
    272 	if (showclass)
    273 		cp += sprintf(cp, ", class %d/%d",
    274 			      udd->bDeviceClass, udd->bDeviceSubClass);
    275 	bcdUSB = UGETW(udd->bcdUSB);
    276 	bcdDevice = UGETW(udd->bcdDevice);
    277 	cp += sprintf(cp, ", rev ");
    278 	cp += usbd_printBCD(cp, bcdUSB);
    279 	*cp++ = '/';
    280 	cp += usbd_printBCD(cp, bcdDevice);
    281 	cp += sprintf(cp, ", addr %d", dev->address);
    282 	*cp = 0;
    283 }
    284 
    285 /* Delay for a certain number of ms */
    286 void
    287 usb_delay_ms(usbd_bus_handle bus, u_int ms)
    288 {
    289 	/* Wait at least two clock ticks so we know the time has passed. */
    290 	if (bus->use_polling || cold)
    291 		delay((ms+1) * 1000);
    292 	else
    293 		tsleep(&ms, PRIBIO, "usbdly", (ms*hz+999)/1000 + 1);
    294 }
    295 
    296 /* Delay given a device handle. */
    297 void
    298 usbd_delay_ms(usbd_device_handle dev, u_int ms)
    299 {
    300 	usb_delay_ms(dev->bus, ms);
    301 }
    302 
    303 usbd_status
    304 usbd_reset_port(usbd_device_handle dev, int port, usb_port_status_t *ps)
    305 {
    306 	usb_device_request_t req;
    307 	usbd_status err;
    308 	int n;
    309 
    310 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
    311 	req.bRequest = UR_SET_FEATURE;
    312 	USETW(req.wValue, UHF_PORT_RESET);
    313 	USETW(req.wIndex, port);
    314 	USETW(req.wLength, 0);
    315 	err = usbd_do_request(dev, &req, 0);
    316 	DPRINTFN(1,("usbd_reset_port: port %d reset done, error=%s\n",
    317 		    port, usbd_errstr(err)));
    318 	if (err)
    319 		return (err);
    320 	n = 10;
    321 	do {
    322 		/* Wait for device to recover from reset. */
    323 		usbd_delay_ms(dev, USB_PORT_RESET_DELAY);
    324 		err = usbd_get_port_status(dev, port, ps);
    325 		if (err) {
    326 			DPRINTF(("usbd_reset_port: get status failed %d\n",
    327 				 err));
    328 			return (err);
    329 		}
    330 	} while ((UGETW(ps->wPortChange) & UPS_C_PORT_RESET) == 0 && --n > 0);
    331 	if (n == 0)
    332 		return (USBD_TIMEOUT);
    333 	err = usbd_clear_port_feature(dev, port, UHF_C_PORT_RESET);
    334 #ifdef USB_DEBUG
    335 	if (err)
    336 		DPRINTF(("usbd_reset_port: clear port feature failed %d\n",
    337 			 err));
    338 #endif
    339 
    340 	/* Wait for the device to recover from reset. */
    341 	usbd_delay_ms(dev, USB_PORT_RESET_RECOVERY);
    342 	return (err);
    343 }
    344 
    345 usb_interface_descriptor_t *
    346 usbd_find_idesc(usb_config_descriptor_t *cd, int ifaceidx, int altidx)
    347 {
    348 	char *p = (char *)cd;
    349 	char *end = p + UGETW(cd->wTotalLength);
    350 	usb_interface_descriptor_t *d;
    351 	int curidx, lastidx, curaidx = 0;
    352 
    353 	for (curidx = lastidx = -1; p < end; ) {
    354 		d = (usb_interface_descriptor_t *)p;
    355 		DPRINTFN(4,("usbd_find_idesc: idx=%d(%d) altidx=%d(%d) len=%d "
    356 			    "type=%d\n",
    357 			    ifaceidx, curidx, altidx, curaidx,
    358 			    d->bLength, d->bDescriptorType));
    359 		if (d->bLength == 0) /* bad descriptor */
    360 			break;
    361 		p += d->bLength;
    362 		if (p <= end && d->bDescriptorType == UDESC_INTERFACE) {
    363 			if (d->bInterfaceNumber != lastidx) {
    364 				lastidx = d->bInterfaceNumber;
    365 				curidx++;
    366 				curaidx = 0;
    367 			} else
    368 				curaidx++;
    369 			if (ifaceidx == curidx && altidx == curaidx)
    370 				return (d);
    371 		}
    372 	}
    373 	return (NULL);
    374 }
    375 
    376 usb_endpoint_descriptor_t *
    377 usbd_find_edesc(usb_config_descriptor_t *cd, int ifaceidx, int altidx,
    378 		int endptidx)
    379 {
    380 	char *p = (char *)cd;
    381 	char *end = p + UGETW(cd->wTotalLength);
    382 	usb_interface_descriptor_t *d;
    383 	usb_endpoint_descriptor_t *e;
    384 	int curidx;
    385 
    386 	d = usbd_find_idesc(cd, ifaceidx, altidx);
    387 	if (d == NULL)
    388 		return (NULL);
    389 	if (endptidx >= d->bNumEndpoints) /* quick exit */
    390 		return (NULL);
    391 
    392 	curidx = -1;
    393 	for (p = (char *)d + d->bLength; p < end; ) {
    394 		e = (usb_endpoint_descriptor_t *)p;
    395 		if (e->bLength == 0) /* bad descriptor */
    396 			break;
    397 		p += e->bLength;
    398 		if (p <= end && e->bDescriptorType == UDESC_INTERFACE)
    399 			return (NULL);
    400 		if (p <= end && e->bDescriptorType == UDESC_ENDPOINT) {
    401 			curidx++;
    402 			if (curidx == endptidx)
    403 				return (e);
    404 		}
    405 	}
    406 	return (NULL);
    407 }
    408 
    409 usbd_status
    410 usbd_fill_iface_data(usbd_device_handle dev, int ifaceidx, int altidx)
    411 {
    412 	usbd_interface_handle ifc = &dev->ifaces[ifaceidx];
    413 	usb_interface_descriptor_t *idesc;
    414 	char *p, *end;
    415 	int endpt, nendpt;
    416 
    417 	DPRINTFN(4,("usbd_fill_iface_data: ifaceidx=%d altidx=%d\n",
    418 		    ifaceidx, altidx));
    419 	idesc = usbd_find_idesc(dev->cdesc, ifaceidx, altidx);
    420 	if (idesc == NULL)
    421 		return (USBD_INVAL);
    422 	ifc->device = dev;
    423 	ifc->idesc = idesc;
    424 	ifc->index = ifaceidx;
    425 	ifc->altindex = altidx;
    426 	nendpt = ifc->idesc->bNumEndpoints;
    427 	DPRINTFN(4,("usbd_fill_iface_data: found idesc nendpt=%d\n", nendpt));
    428 	if (nendpt != 0) {
    429 		ifc->endpoints = malloc(nendpt * sizeof(struct usbd_endpoint),
    430 					M_USB, M_NOWAIT);
    431 		if (ifc->endpoints == NULL)
    432 			return (USBD_NOMEM);
    433 	} else
    434 		ifc->endpoints = NULL;
    435 	ifc->priv = NULL;
    436 	p = (char *)ifc->idesc + ifc->idesc->bLength;
    437 	end = (char *)dev->cdesc + UGETW(dev->cdesc->wTotalLength);
    438 #define ed ((usb_endpoint_descriptor_t *)p)
    439 	for (endpt = 0; endpt < nendpt; endpt++) {
    440 		DPRINTFN(10,("usbd_fill_iface_data: endpt=%d\n", endpt));
    441 		for (; p < end; p += ed->bLength) {
    442 			ed = (usb_endpoint_descriptor_t *)p;
    443 			DPRINTFN(10,("usbd_fill_iface_data: p=%p end=%p "
    444 				     "len=%d type=%d\n",
    445 				 p, end, ed->bLength, ed->bDescriptorType));
    446 			if (p + ed->bLength <= end && ed->bLength != 0 &&
    447 			    ed->bDescriptorType == UDESC_ENDPOINT)
    448 				goto found;
    449 			if (ed->bLength == 0 ||
    450 			    ed->bDescriptorType == UDESC_INTERFACE)
    451 				break;
    452 		}
    453 		/* passed end, or bad desc */
    454 		DPRINTF(("usbd_fill_iface_data: bad descriptor(s): %s\n",
    455 			 ed->bLength == 0 ? "0 length" :
    456 			 ed->bDescriptorType == UDESC_INTERFACE ? "iface desc":
    457 			 "out of data"));
    458 		goto bad;
    459 	found:
    460 		ifc->endpoints[endpt].edesc = ed;
    461 		ifc->endpoints[endpt].refcnt = 0;
    462 		p += ed->bLength;
    463 	}
    464 #undef ed
    465 	LIST_INIT(&ifc->pipes);
    466 	return (USBD_NORMAL_COMPLETION);
    467 
    468  bad:
    469 	if (ifc->endpoints != NULL) {
    470 		free(ifc->endpoints, M_USB);
    471 		ifc->endpoints = NULL;
    472 	}
    473 	return (USBD_INVAL);
    474 }
    475 
    476 void
    477 usbd_free_iface_data(usbd_device_handle dev, int ifcno)
    478 {
    479 	usbd_interface_handle ifc = &dev->ifaces[ifcno];
    480 	if (ifc->endpoints)
    481 		free(ifc->endpoints, M_USB);
    482 }
    483 
    484 Static usbd_status
    485 usbd_set_config(usbd_device_handle dev, int conf)
    486 {
    487 	usb_device_request_t req;
    488 
    489 	req.bmRequestType = UT_WRITE_DEVICE;
    490 	req.bRequest = UR_SET_CONFIG;
    491 	USETW(req.wValue, conf);
    492 	USETW(req.wIndex, 0);
    493 	USETW(req.wLength, 0);
    494 	return (usbd_do_request(dev, &req, 0));
    495 }
    496 
    497 usbd_status
    498 usbd_set_config_no(usbd_device_handle dev, int no, int msg)
    499 {
    500 	int index;
    501 	usb_config_descriptor_t cd;
    502 	usbd_status err;
    503 
    504 	if (no == USB_UNCONFIG_NO)
    505 		return (usbd_set_config_index(dev, USB_UNCONFIG_INDEX, msg));
    506 
    507 	DPRINTFN(5,("usbd_set_config_no: %d\n", no));
    508 	/* Figure out what config index to use. */
    509 	for (index = 0; index < dev->ddesc.bNumConfigurations; index++) {
    510 		err = usbd_get_config_desc(dev, index, &cd);
    511 		if (err)
    512 			return (err);
    513 		if (cd.bConfigurationValue == no)
    514 			return (usbd_set_config_index(dev, index, msg));
    515 	}
    516 	return (USBD_INVAL);
    517 }
    518 
    519 usbd_status
    520 usbd_set_config_index(usbd_device_handle dev, int index, int msg)
    521 {
    522 	usb_status_t ds;
    523 	usb_config_descriptor_t cd, *cdp;
    524 	usbd_status err;
    525 	int ifcidx, nifc, len, selfpowered, power;
    526 
    527 	DPRINTFN(5,("usbd_set_config_index: dev=%p index=%d\n", dev, index));
    528 
    529 	/* XXX check that all interfaces are idle */
    530 	if (dev->config != USB_UNCONFIG_NO) {
    531 		DPRINTF(("usbd_set_config_index: free old config\n"));
    532 		/* Free all configuration data structures. */
    533 		nifc = dev->cdesc->bNumInterface;
    534 		for (ifcidx = 0; ifcidx < nifc; ifcidx++)
    535 			usbd_free_iface_data(dev, ifcidx);
    536 		free(dev->ifaces, M_USB);
    537 		free(dev->cdesc, M_USB);
    538 		dev->ifaces = NULL;
    539 		dev->cdesc = NULL;
    540 		dev->config = USB_UNCONFIG_NO;
    541 	}
    542 
    543 	if (index == USB_UNCONFIG_INDEX) {
    544 		/* We are unconfiguring the device, so leave unallocated. */
    545 		DPRINTF(("usbd_set_config_index: set config 0\n"));
    546 		err = usbd_set_config(dev, USB_UNCONFIG_NO);
    547 		if (err)
    548 			DPRINTF(("usbd_set_config_index: setting config=0 "
    549 				 "failed, error=%s\n", usbd_errstr(err)));
    550 		return (err);
    551 	}
    552 
    553 	/* Get the short descriptor. */
    554 	err = usbd_get_config_desc(dev, index, &cd);
    555 	if (err)
    556 		return (err);
    557 	len = UGETW(cd.wTotalLength);
    558 	cdp = malloc(len, M_USB, M_NOWAIT);
    559 	if (cdp == NULL)
    560 		return (USBD_NOMEM);
    561 	/* Get the full descriptor. */
    562 	err = usbd_get_desc(dev, UDESC_CONFIG, index, len, cdp);
    563 	if (err)
    564 		goto bad;
    565 	if (cdp->bDescriptorType != UDESC_CONFIG) {
    566 		DPRINTFN(-1,("usbd_set_config_index: bad desc %d\n",
    567 			     cdp->bDescriptorType));
    568 		err = USBD_INVAL;
    569 		goto bad;
    570 	}
    571 
    572 	/* Figure out if the device is self or bus powered. */
    573 	selfpowered = 0;
    574 	if (!(dev->quirks->uq_flags & UQ_BUS_POWERED) &&
    575 	    (cdp->bmAttributes & UC_SELF_POWERED)) {
    576 		/* May be self powered. */
    577 		if (cdp->bmAttributes & UC_BUS_POWERED) {
    578 			/* Must ask device. */
    579 			if (dev->quirks->uq_flags & UQ_POWER_CLAIM) {
    580 				/*
    581 				 * Hub claims to be self powered, but isn't.
    582 				 * It seems that the power status can be
    583 				 * determined by the hub characteristics.
    584 				 */
    585 				usb_hub_descriptor_t hd;
    586 				usb_device_request_t req;
    587 				req.bmRequestType = UT_READ_CLASS_DEVICE;
    588 				req.bRequest = UR_GET_DESCRIPTOR;
    589 				USETW(req.wValue, 0);
    590 				USETW(req.wIndex, 0);
    591 				USETW(req.wLength, USB_HUB_DESCRIPTOR_SIZE);
    592 				err = usbd_do_request(dev, &req, &hd);
    593 				if (!err &&
    594 				    (UGETW(hd.wHubCharacteristics) &
    595 				     UHD_PWR_INDIVIDUAL))
    596 					selfpowered = 1;
    597 				DPRINTF(("usbd_set_config_index: charac=0x%04x"
    598 				    ", error=%s\n",
    599 				    UGETW(hd.wHubCharacteristics),
    600 				    usbd_errstr(err)));
    601 			} else {
    602 				err = usbd_get_device_status(dev, &ds);
    603 				if (!err &&
    604 				    (UGETW(ds.wStatus) & UDS_SELF_POWERED))
    605 					selfpowered = 1;
    606 				DPRINTF(("usbd_set_config_index: status=0x%04x"
    607 				    ", error=%s\n",
    608 				    UGETW(ds.wStatus), usbd_errstr(err)));
    609 			}
    610 		} else
    611 			selfpowered = 1;
    612 	}
    613 	DPRINTF(("usbd_set_config_index: (addr %d) cno=%d attr=0x%02x, "
    614 		 "selfpowered=%d, power=%d\n",
    615 		 cdp->bConfigurationValue, dev->address, cdp->bmAttributes,
    616 		 selfpowered, cdp->bMaxPower * 2));
    617 
    618 	/* Check if we have enough power. */
    619 #ifdef USB_DEBUG
    620 	if (dev->powersrc == NULL) {
    621 		DPRINTF(("usbd_set_config_index: No power source?\n"));
    622 		return (USBD_IOERROR);
    623 	}
    624 #endif
    625 	power = cdp->bMaxPower * 2;
    626 	if (power > dev->powersrc->power) {
    627 		DPRINTF(("power exceeded %d %d\n", power,dev->powersrc->power));
    628 		/* XXX print nicer message. */
    629 		if (msg)
    630 			printf("%s: device addr %d (config %d) exceeds power "
    631 				 "budget, %d mA > %d mA\n",
    632 			       USBDEVNAME(dev->bus->bdev), dev->address,
    633 			       cdp->bConfigurationValue,
    634 			       power, dev->powersrc->power);
    635 		err = USBD_NO_POWER;
    636 		goto bad;
    637 	}
    638 	dev->power = power;
    639 	dev->self_powered = selfpowered;
    640 
    641 	/* Set the actual configuration value. */
    642 	DPRINTF(("usbd_set_config_index: set config %d\n",
    643 		 cdp->bConfigurationValue));
    644 	err = usbd_set_config(dev, cdp->bConfigurationValue);
    645 	if (err) {
    646 		DPRINTF(("usbd_set_config_index: setting config=%d failed, "
    647 			 "error=%s\n",
    648 			 cdp->bConfigurationValue, usbd_errstr(err)));
    649 		goto bad;
    650 	}
    651 
    652 	/* Allocate and fill interface data. */
    653 	nifc = cdp->bNumInterface;
    654 	dev->ifaces = malloc(nifc * sizeof(struct usbd_interface),
    655 			     M_USB, M_NOWAIT);
    656 	if (dev->ifaces == NULL) {
    657 		err = USBD_NOMEM;
    658 		goto bad;
    659 	}
    660 	DPRINTFN(5,("usbd_set_config_index: dev=%p cdesc=%p\n", dev, cdp));
    661 	dev->cdesc = cdp;
    662 	dev->config = cdp->bConfigurationValue;
    663 	for (ifcidx = 0; ifcidx < nifc; ifcidx++) {
    664 		err = usbd_fill_iface_data(dev, ifcidx, 0);
    665 		if (err) {
    666 			while (--ifcidx >= 0)
    667 				usbd_free_iface_data(dev, ifcidx);
    668 			goto bad;
    669 		}
    670 	}
    671 
    672 	return (USBD_NORMAL_COMPLETION);
    673 
    674  bad:
    675 	free(cdp, M_USB);
    676 	return (err);
    677 }
    678 
    679 /* XXX add function for alternate settings */
    680 
    681 usbd_status
    682 usbd_setup_pipe(usbd_device_handle dev, usbd_interface_handle iface,
    683 		struct usbd_endpoint *ep, int ival, usbd_pipe_handle *pipe)
    684 {
    685 	usbd_pipe_handle p;
    686 	usbd_status err;
    687 
    688 	DPRINTFN(1,("usbd_setup_pipe: dev=%p iface=%p ep=%p pipe=%p\n",
    689 		    dev, iface, ep, pipe));
    690 	p = malloc(dev->bus->pipe_size, M_USB, M_NOWAIT);
    691 	if (p == NULL)
    692 		return (USBD_NOMEM);
    693 	p->device = dev;
    694 	p->iface = iface;
    695 	p->endpoint = ep;
    696 	ep->refcnt++;
    697 	p->refcnt = 1;
    698 	p->intrxfer = 0;
    699 	p->running = 0;
    700 	p->aborting = 0;
    701 	p->repeat = 0;
    702 	p->interval = ival;
    703 	SIMPLEQ_INIT(&p->queue);
    704 	usb_callout_init(p->abort_handle);
    705 	err = dev->bus->methods->open_pipe(p);
    706 	if (err) {
    707 		DPRINTFN(-1,("usbd_setup_pipe: endpoint=0x%x failed, error="
    708 			 "%s\n",
    709 			 ep->edesc->bEndpointAddress, usbd_errstr(err)));
    710 		free(p, M_USB);
    711 		return (err);
    712 	}
    713 	/* Clear any stall and make sure DATA0 toggle will be used next. */
    714 	if (UE_GET_ADDR(ep->edesc->bEndpointAddress) != USB_CONTROL_ENDPOINT)
    715 		usbd_clear_endpoint_stall(p);
    716 	*pipe = p;
    717 	return (USBD_NORMAL_COMPLETION);
    718 }
    719 
    720 /* Abort the device control pipe. */
    721 void
    722 usbd_kill_pipe(usbd_pipe_handle pipe)
    723 {
    724 	pipe->methods->close(pipe);
    725 	pipe->endpoint->refcnt--;
    726 	free(pipe, M_USB);
    727 }
    728 
    729 int
    730 usbd_getnewaddr(usbd_bus_handle bus)
    731 {
    732 	int addr;
    733 
    734 	for (addr = 1; addr < USB_MAX_DEVICES; addr++)
    735 		if (bus->devices[addr] == 0)
    736 			return (addr);
    737 	return (-1);
    738 }
    739 
    740 
    741 usbd_status
    742 usbd_probe_and_attach(device_ptr_t parent, usbd_device_handle dev,
    743 		      int port, int addr)
    744 {
    745 	struct usb_attach_arg uaa;
    746 	usb_device_descriptor_t *dd = &dev->ddesc;
    747 	int found, i, confi, nifaces;
    748 	usbd_status err;
    749 	device_ptr_t dv;
    750 	usbd_interface_handle ifaces[256]; /* 256 is the absolute max */
    751 
    752 #if defined(__FreeBSD__)
    753 	/*
    754 	 * XXX uaa is a static var. Not a problem as it _should_ be used only
    755 	 * during probe and attach. Should be changed however.
    756 	 */
    757 	device_t bdev;
    758 	bdev = device_add_child(parent, NULL, -1, &uaa);
    759 	if (!bdev) {
    760 	    printf("%s: Device creation failed\n", USBDEVNAME(dev->bus->bdev));
    761 	    return (USBD_INVAL);
    762 	}
    763 	device_quiet(bdev);
    764 #endif
    765 
    766 	uaa.device = dev;
    767 	uaa.iface = NULL;
    768 	uaa.ifaces = NULL;
    769 	uaa.nifaces = 0;
    770 	uaa.usegeneric = 0;
    771 	uaa.port = port;
    772 	uaa.configno = UHUB_UNK_CONFIGURATION;
    773 	uaa.ifaceno = UHUB_UNK_INTERFACE;
    774 	uaa.vendor = UGETW(dd->idVendor);
    775 	uaa.product = UGETW(dd->idProduct);
    776 	uaa.release = UGETW(dd->bcdDevice);
    777 
    778 	/* First try with device specific drivers. */
    779 	DPRINTF(("usbd_probe_and_attach: trying device specific drivers\n"));
    780 	dv = USB_DO_ATTACH(dev, bdev, parent, &uaa, usbd_print, usbd_submatch);
    781 	if (dv) {
    782 		dev->subdevs = malloc(2 * sizeof dv, M_USB, M_NOWAIT);
    783 		if (dev->subdevs == NULL)
    784 			return (USBD_NOMEM);
    785 		dev->subdevs[0] = dv;
    786 		dev->subdevs[1] = 0;
    787 		return (USBD_NORMAL_COMPLETION);
    788 	}
    789 
    790 	DPRINTF(("usbd_probe_and_attach: no device specific driver found\n"));
    791 
    792 	DPRINTF(("usbd_probe_and_attach: looping over %d configurations\n",
    793 		 dd->bNumConfigurations));
    794 	/* Next try with interface drivers. */
    795 	for (confi = 0; confi < dd->bNumConfigurations; confi++) {
    796 		DPRINTFN(1,("usbd_probe_and_attach: trying config idx=%d\n",
    797 			    confi));
    798 		err = usbd_set_config_index(dev, confi, 1);
    799 		if (err) {
    800 #ifdef USB_DEBUG
    801 			DPRINTF(("%s: port %d, set config at addr %d failed, "
    802 				 "error=%s\n", USBDEVPTRNAME(parent), port,
    803 				 addr, usbd_errstr(err)));
    804 #else
    805 			printf("%s: port %d, set config at addr %d failed\n",
    806 			       USBDEVPTRNAME(parent), port, addr);
    807 #endif
    808 #if defined(__FreeBSD__)
    809 			device_delete_child(parent, bdev);
    810 #endif
    811 
    812  			return (err);
    813 		}
    814 		nifaces = dev->cdesc->bNumInterface;
    815 		uaa.configno = dev->cdesc->bConfigurationValue;
    816 		for (i = 0; i < nifaces; i++)
    817 			ifaces[i] = &dev->ifaces[i];
    818 		uaa.ifaces = ifaces;
    819 		uaa.nifaces = nifaces;
    820 		dev->subdevs = malloc((nifaces+1) * sizeof dv, M_USB,M_NOWAIT);
    821 		if (dev->subdevs == NULL) {
    822 #if defined(__FreeBSD__)
    823 			device_delete_child(parent, bdev);
    824 #endif
    825 			return (USBD_NOMEM);
    826 		}
    827 
    828 		found = 0;
    829 		for (i = 0; i < nifaces; i++) {
    830 			if (ifaces[i] == NULL)
    831 				continue; /* interface already claimed */
    832 			uaa.iface = ifaces[i];
    833 			uaa.ifaceno = ifaces[i]->idesc->bInterfaceNumber;
    834 			dv = USB_DO_ATTACH(dev, bdev, parent, &uaa, usbd_print,
    835 					   usbd_submatch);
    836 			if (dv != NULL) {
    837 				dev->subdevs[found++] = dv;
    838 				dev->subdevs[found] = 0;
    839 				ifaces[i] = 0; /* consumed */
    840 
    841 #if defined(__FreeBSD__)
    842 				/* create another child for the next iface */
    843 				bdev = device_add_child(parent, NULL, -1,&uaa);
    844 				if (!bdev) {
    845 					printf("%s: Device creation failed\n",
    846 					USBDEVNAME(dev->bus->bdev));
    847 					return (USBD_NORMAL_COMPLETION);
    848 				}
    849 				device_quiet(bdev);
    850 #endif
    851 			}
    852 		}
    853 		if (found != 0) {
    854 #if defined(__FreeBSD__)
    855 			/* remove the last created child again; it is unused */
    856 			device_delete_child(parent, bdev);
    857 #endif
    858 			return (USBD_NORMAL_COMPLETION);
    859 		}
    860 		free(dev->subdevs, M_USB);
    861 		dev->subdevs = 0;
    862 	}
    863 	/* No interfaces were attached in any of the configurations. */
    864 
    865 	if (dd->bNumConfigurations > 1) /* don't change if only 1 config */
    866 		usbd_set_config_index(dev, 0, 0);
    867 
    868 	DPRINTF(("usbd_probe_and_attach: no interface drivers found\n"));
    869 
    870 	/* Finally try the generic driver. */
    871 	uaa.iface = NULL;
    872 	uaa.usegeneric = 1;
    873 	uaa.configno = UHUB_UNK_CONFIGURATION;
    874 	uaa.ifaceno = UHUB_UNK_INTERFACE;
    875 	dv = USB_DO_ATTACH(dev, bdev, parent, &uaa, usbd_print, usbd_submatch);
    876 	if (dv != NULL) {
    877 		dev->subdevs = malloc(2 * sizeof dv, M_USB, M_NOWAIT);
    878 		if (dev->subdevs == 0)
    879 			return (USBD_NOMEM);
    880 		dev->subdevs[0] = dv;
    881 		dev->subdevs[1] = 0;
    882 		return (USBD_NORMAL_COMPLETION);
    883 	}
    884 
    885 	/*
    886 	 * The generic attach failed, but leave the device as it is.
    887 	 * We just did not find any drivers, that's all.  The device is
    888 	 * fully operational and not harming anyone.
    889 	 */
    890 	DPRINTF(("usbd_probe_and_attach: generic attach failed\n"));
    891 #if defined(__FreeBSD__)
    892 	device_delete_child(parent, bdev);
    893 #endif
    894  	return (USBD_NORMAL_COMPLETION);
    895 }
    896 
    897 
    898 /*
    899  * Called when a new device has been put in the powered state,
    900  * but not yet in the addressed state.
    901  * Get initial descriptor, set the address, get full descriptor,
    902  * and attach a driver.
    903  */
    904 usbd_status
    905 usbd_new_device(device_ptr_t parent, usbd_bus_handle bus, int depth,
    906 		int lowspeed, int port, struct usbd_port *up)
    907 {
    908 	usbd_device_handle dev;
    909 	usb_device_descriptor_t *dd;
    910 	usbd_status err;
    911 	int addr;
    912 	int i;
    913 
    914 	DPRINTF(("usbd_new_device bus=%p port=%d depth=%d lowspeed=%d\n",
    915 		 bus, port, depth, lowspeed));
    916 	addr = usbd_getnewaddr(bus);
    917 	if (addr < 0) {
    918 		printf("%s: No free USB addresses, new device ignored.\n",
    919 		       USBDEVNAME(bus->bdev));
    920 		return (USBD_NO_ADDR);
    921 	}
    922 
    923 	dev = malloc(sizeof *dev, M_USB, M_NOWAIT);
    924 	if (dev == NULL)
    925 		return (USBD_NOMEM);
    926 	memset(dev, 0, sizeof(*dev));
    927 
    928 	dev->bus = bus;
    929 
    930 	/* Set up default endpoint handle. */
    931 	dev->def_ep.edesc = &dev->def_ep_desc;
    932 
    933 	/* Set up default endpoint descriptor. */
    934 	dev->def_ep_desc.bLength = USB_ENDPOINT_DESCRIPTOR_SIZE;
    935 	dev->def_ep_desc.bDescriptorType = UDESC_ENDPOINT;
    936 	dev->def_ep_desc.bEndpointAddress = USB_CONTROL_ENDPOINT;
    937 	dev->def_ep_desc.bmAttributes = UE_CONTROL;
    938 	USETW(dev->def_ep_desc.wMaxPacketSize, USB_MAX_IPACKET);
    939 	dev->def_ep_desc.bInterval = 0;
    940 
    941 	dev->quirks = &usbd_no_quirk;
    942 	dev->address = USB_START_ADDR;
    943 	dev->ddesc.bMaxPacketSize = 0;
    944 	dev->lowspeed = lowspeed != 0;
    945 	dev->depth = depth;
    946 	dev->powersrc = up;
    947 	dev->langid = USBD_NOLANG;
    948 	dev->cookie.cookie = ++usb_cookie_no;
    949 
    950 	/* Establish the default pipe. */
    951 	err = usbd_setup_pipe(dev, 0, &dev->def_ep, USBD_DEFAULT_INTERVAL,
    952 			      &dev->default_pipe);
    953 	if (err) {
    954 		usbd_remove_device(dev, up);
    955 		return (err);
    956 	}
    957 
    958 	up->device = dev;
    959 	dd = &dev->ddesc;
    960 	/* Try a few times in case the device is slow (i.e. outside specs.) */
    961 	for (i = 0; i < 3; i++) {
    962 		/* Get the first 8 bytes of the device descriptor. */
    963 		err = usbd_get_desc(dev, UDESC_DEVICE, 0, USB_MAX_IPACKET, dd);
    964 		if (!err)
    965 			break;
    966 		usbd_delay_ms(dev, 200);
    967 	}
    968 	if (err) {
    969 		DPRINTFN(-1, ("usbd_new_device: addr=%d, getting first desc "
    970 			      "failed\n", addr));
    971 		usbd_remove_device(dev, up);
    972 		return (err);
    973 	}
    974 
    975 	DPRINTF(("usbd_new_device: adding unit addr=%d, rev=%02x, class=%d, "
    976 		 "subclass=%d, protocol=%d, maxpacket=%d, len=%d, ls=%d\n",
    977 		 addr,UGETW(dd->bcdUSB), dd->bDeviceClass, dd->bDeviceSubClass,
    978 		 dd->bDeviceProtocol, dd->bMaxPacketSize, dd->bLength,
    979 		 dev->lowspeed));
    980 
    981 	if (dd->bDescriptorType != UDESC_DEVICE) {
    982 		/* Illegal device descriptor */
    983 		DPRINTFN(-1,("usbd_new_device: illegal descriptor %d\n",
    984 			     dd->bDescriptorType));
    985 		usbd_remove_device(dev, up);
    986 		return (USBD_INVAL);
    987 	}
    988 
    989 	if (dd->bLength < USB_DEVICE_DESCRIPTOR_SIZE) {
    990 		DPRINTFN(-1,("usbd_new_device: bad length %d\n", dd->bLength));
    991 		usbd_remove_device(dev, up);
    992 		return (USBD_INVAL);
    993 	}
    994 
    995 	USETW(dev->def_ep_desc.wMaxPacketSize, dd->bMaxPacketSize);
    996 
    997 	err = usbd_reload_device_desc(dev);
    998 	if (err) {
    999 		DPRINTFN(-1, ("usbd_new_device: addr=%d, getting full desc "
   1000 			      "failed\n", addr));
   1001 		usbd_remove_device(dev, up);
   1002 		return (err);
   1003 	}
   1004 
   1005 	/* Set the address */
   1006 	err = usbd_set_address(dev, addr);
   1007 	DPRINTFN(5,("usbd_new_device: setting device address=%d\n", addr));
   1008 	if (err) {
   1009 		DPRINTFN(-1,("usb_new_device: set address %d failed\n", addr));
   1010 		err = USBD_SET_ADDR_FAILED;
   1011 		usbd_remove_device(dev, up);
   1012 		return (err);
   1013 	}
   1014 	/* Allow device time to set new address */
   1015 	usbd_delay_ms(dev, USB_SET_ADDRESS_SETTLE);
   1016 
   1017 	dev->address = addr;	/* New device address now */
   1018 	bus->devices[addr] = dev;
   1019 
   1020 	/* Assume 100mA bus powered for now. Changed when configured. */
   1021 	dev->power = USB_MIN_POWER;
   1022 	dev->self_powered = 0;
   1023 
   1024 	DPRINTF(("usbd_new_device: new dev (addr %d), dev=%p, parent=%p\n",
   1025 		 addr, dev, parent));
   1026 
   1027 	usbd_add_dev_event(USB_EVENT_DEVICE_ATTACH, dev);
   1028 
   1029 	err = usbd_probe_and_attach(parent, dev, port, addr);
   1030 	if (err) {
   1031 		usbd_remove_device(dev, up);
   1032 		return (err);
   1033   	}
   1034 
   1035   	return (USBD_NORMAL_COMPLETION);
   1036 }
   1037 
   1038 usbd_status
   1039 usbd_reload_device_desc(usbd_device_handle dev)
   1040 {
   1041 	usbd_status err;
   1042 
   1043 	/* Get the full device descriptor. */
   1044 	err = usbd_get_device_desc(dev, &dev->ddesc);
   1045 	if (err)
   1046 		return (err);
   1047 
   1048 	/* Figure out what's wrong with this device. */
   1049 	dev->quirks = usbd_find_quirk(&dev->ddesc);
   1050 
   1051 	return (USBD_NORMAL_COMPLETION);
   1052 }
   1053 
   1054 void
   1055 usbd_remove_device(usbd_device_handle dev, struct usbd_port *up)
   1056 {
   1057 	DPRINTF(("usbd_remove_device: %p\n", dev));
   1058 
   1059 	if (dev->default_pipe != NULL)
   1060 		usbd_kill_pipe(dev->default_pipe);
   1061 	up->device = 0;
   1062 	dev->bus->devices[dev->address] = 0;
   1063 
   1064 	free(dev, M_USB);
   1065 }
   1066 
   1067 #if defined(__NetBSD__) || defined(__OpenBSD__)
   1068 int
   1069 usbd_print(void *aux, const char *pnp)
   1070 {
   1071 	struct usb_attach_arg *uaa = aux;
   1072 	char devinfo[1024];
   1073 
   1074 	DPRINTFN(15, ("usbd_print dev=%p\n", uaa->device));
   1075 	if (pnp) {
   1076 		if (!uaa->usegeneric)
   1077 			return (QUIET);
   1078 		usbd_devinfo(uaa->device, 1, devinfo);
   1079 		printf("%s, %s", devinfo, pnp);
   1080 	}
   1081 	if (uaa->port != 0)
   1082 		printf(" port %d", uaa->port);
   1083 	if (uaa->configno != UHUB_UNK_CONFIGURATION)
   1084 		printf(" configuration %d", uaa->configno);
   1085 	if (uaa->ifaceno != UHUB_UNK_INTERFACE)
   1086 		printf(" interface %d", uaa->ifaceno);
   1087 #if 0
   1088 	/*
   1089 	 * It gets very crowded with these locators on the attach line.
   1090 	 * They are not really needed since they are printed in the clear
   1091 	 * by each driver.
   1092 	 */
   1093 	if (uaa->vendor != UHUB_UNK_VENDOR)
   1094 		printf(" vendor 0x%04x", uaa->vendor);
   1095 	if (uaa->product != UHUB_UNK_PRODUCT)
   1096 		printf(" product 0x%04x", uaa->product);
   1097 	if (uaa->release != UHUB_UNK_RELEASE)
   1098 		printf(" release 0x%04x", uaa->release);
   1099 #endif
   1100 	return (UNCONF);
   1101 }
   1102 
   1103 #if defined(__NetBSD__)
   1104 int
   1105 usbd_submatch(struct device *parent, struct cfdata *cf, void *aux)
   1106 {
   1107 #elif defined(__OpenBSD__)
   1108 int
   1109 usbd_submatch(struct device *parent, void *match, void *aux)
   1110 {
   1111 	struct cfdata *cf = match;
   1112 #endif
   1113 	struct usb_attach_arg *uaa = aux;
   1114 
   1115 	DPRINTFN(5,("usbd_submatch port=%d,%d configno=%d,%d "
   1116 	    "ifaceno=%d,%d vendor=%d,%d product=%d,%d release=%d,%d\n",
   1117 	    uaa->port, cf->uhubcf_port,
   1118 	    uaa->configno, cf->uhubcf_configuration,
   1119 	    uaa->ifaceno, cf->uhubcf_interface,
   1120 	    uaa->vendor, cf->uhubcf_vendor,
   1121 	    uaa->product, cf->uhubcf_product,
   1122 	    uaa->release, cf->uhubcf_release));
   1123 	if (uaa->port != 0 &&	/* root hub has port 0, it should match */
   1124 	    ((uaa->port != 0 &&
   1125 	      cf->uhubcf_port != UHUB_UNK_PORT &&
   1126 	      cf->uhubcf_port != uaa->port) ||
   1127 	     (uaa->configno != UHUB_UNK_CONFIGURATION &&
   1128 	      cf->uhubcf_configuration != UHUB_UNK_CONFIGURATION &&
   1129 	      cf->uhubcf_configuration != uaa->configno) ||
   1130 	     (uaa->ifaceno != UHUB_UNK_INTERFACE &&
   1131 	      cf->uhubcf_interface != UHUB_UNK_INTERFACE &&
   1132 	      cf->uhubcf_interface != uaa->ifaceno) ||
   1133 	     (uaa->vendor != UHUB_UNK_VENDOR &&
   1134 	      cf->uhubcf_vendor != UHUB_UNK_VENDOR &&
   1135 	      cf->uhubcf_vendor != uaa->vendor) ||
   1136 	     (uaa->product != UHUB_UNK_PRODUCT &&
   1137 	      cf->uhubcf_product != UHUB_UNK_PRODUCT &&
   1138 	      cf->uhubcf_product != uaa->product) ||
   1139 	     (uaa->release != UHUB_UNK_RELEASE &&
   1140 	      cf->uhubcf_release != UHUB_UNK_RELEASE &&
   1141 	      cf->uhubcf_release != uaa->release)
   1142 	     )
   1143 	   )
   1144 		return 0;
   1145 	return ((*cf->cf_attach->ca_match)(parent, cf, aux));
   1146 }
   1147 
   1148 #endif
   1149 
   1150 void
   1151 usbd_fill_deviceinfo(usbd_device_handle dev, struct usb_device_info *di)
   1152 {
   1153 	struct usbd_port *p;
   1154 	int i, err, s;
   1155 
   1156 	di->bus = USBDEVUNIT(dev->bus->bdev);
   1157 	di->addr = dev->address;
   1158 	di->cookie = dev->cookie;
   1159 	usbd_devinfo_vp(dev, di->vendor, di->product);
   1160 	usbd_printBCD(di->release, UGETW(dev->ddesc.bcdDevice));
   1161 	di->vendorNo = UGETW(dev->ddesc.idVendor);
   1162 	di->productNo = UGETW(dev->ddesc.idProduct);
   1163 	di->releaseNo = UGETW(dev->ddesc.bcdDevice);
   1164 	di->class = dev->ddesc.bDeviceClass;
   1165 	di->subclass = dev->ddesc.bDeviceSubClass;
   1166 	di->protocol = dev->ddesc.bDeviceProtocol;
   1167 	di->config = dev->config;
   1168 	di->power = dev->self_powered ? 0 : dev->power;
   1169 	di->lowspeed = dev->lowspeed;
   1170 
   1171 	if (dev->subdevs != NULL) {
   1172 		for (i = 0; dev->subdevs[i] &&
   1173 			     i < USB_MAX_DEVNAMES; i++) {
   1174 			strncpy(di->devnames[i], USBDEVPTRNAME(dev->subdevs[i]),
   1175 				USB_MAX_DEVNAMELEN);
   1176 			di->devnames[i][USB_MAX_DEVNAMELEN-1] = '\0';
   1177                 }
   1178         } else {
   1179                 i = 0;
   1180         }
   1181         for (/*i is set */; i < USB_MAX_DEVNAMES; i++)
   1182                 di->devnames[i][0] = 0;                 /* empty */
   1183 
   1184 	if (dev->hub) {
   1185 		for (i = 0;
   1186 		     i < sizeof(di->ports) / sizeof(di->ports[0]) &&
   1187 			     i < dev->hub->hubdesc.bNbrPorts;
   1188 		     i++) {
   1189 			p = &dev->hub->ports[i];
   1190 			if (p->device)
   1191 				err = p->device->address;
   1192 			else {
   1193 				s = UGETW(p->status.wPortStatus);
   1194 				if (s & UPS_PORT_ENABLED)
   1195 					err = USB_PORT_ENABLED;
   1196 				else if (s & UPS_SUSPEND)
   1197 					err = USB_PORT_SUSPENDED;
   1198 				else if (s & UPS_PORT_POWER)
   1199 					err = USB_PORT_POWERED;
   1200 				else
   1201 					err = USB_PORT_DISABLED;
   1202 			}
   1203 			di->ports[i] = err;
   1204 		}
   1205 		di->nports = dev->hub->hubdesc.bNbrPorts;
   1206 	} else
   1207 		di->nports = 0;
   1208 }
   1209 
   1210 void
   1211 usb_free_device(usbd_device_handle dev)
   1212 {
   1213 	int ifcidx, nifc;
   1214 
   1215 	if (dev->default_pipe != NULL)
   1216 		usbd_kill_pipe(dev->default_pipe);
   1217 	if (dev->ifaces != NULL) {
   1218 		nifc = dev->cdesc->bNumInterface;
   1219 		for (ifcidx = 0; ifcidx < nifc; ifcidx++)
   1220 			usbd_free_iface_data(dev, ifcidx);
   1221 		free(dev->ifaces, M_USB);
   1222 	}
   1223 	if (dev->cdesc != NULL)
   1224 		free(dev->cdesc, M_USB);
   1225 	if (dev->subdevs != NULL)
   1226 		free(dev->subdevs, M_USB);
   1227 	free(dev, M_USB);
   1228 }
   1229 
   1230 /*
   1231  * The general mechanism for detaching drivers works as follows: Each
   1232  * driver is responsible for maintaining a reference count on the
   1233  * number of outstanding references to its softc (e.g.  from
   1234  * processing hanging in a read or write).  The detach method of the
   1235  * driver decrements this counter and flags in the softc that the
   1236  * driver is dying and then wakes any sleepers.  It then sleeps on the
   1237  * softc.  Each place that can sleep must maintain the reference
   1238  * count.  When the reference count drops to -1 (0 is the normal value
   1239  * of the reference count) the a wakeup on the softc is performed
   1240  * signaling to the detach waiter that all references are gone.
   1241  */
   1242 
   1243 /*
   1244  * Called from process context when we discover that a port has
   1245  * been disconnected.
   1246  */
   1247 void
   1248 usb_disconnect_port(struct usbd_port *up, device_ptr_t parent)
   1249 {
   1250 	usbd_device_handle dev = up->device;
   1251 	char *hubname = USBDEVPTRNAME(parent);
   1252 	int i;
   1253 
   1254 	DPRINTFN(3,("uhub_disconnect: up=%p dev=%p port=%d\n",
   1255 		    up, dev, up->portno));
   1256 
   1257 #ifdef DIAGNOSTIC
   1258 	if (dev == NULL) {
   1259 		printf("usb_disconnect_port: no device\n");
   1260 		return;
   1261 	}
   1262 #endif
   1263 
   1264 	if (dev->subdevs != NULL) {
   1265 		DPRINTFN(3,("usb_disconnect_port: disconnect subdevs\n"));
   1266 		for (i = 0; dev->subdevs[i]; i++) {
   1267 			printf("%s: at %s", USBDEVPTRNAME(dev->subdevs[i]),
   1268 			       hubname);
   1269 			if (up->portno != 0)
   1270 				printf(" port %d", up->portno);
   1271 			printf(" (addr %d) disconnected\n", dev->address);
   1272 #if defined(__NetBSD__) || defined(__OpenBSD__)
   1273 			config_detach(dev->subdevs[i], DETACH_FORCE);
   1274 #elif defined(__FreeBSD__)
   1275                         device_delete_child(device_get_parent(dev->subdevs[i]),
   1276 					    dev->subdevs[i]);
   1277 #endif
   1278 
   1279 		}
   1280 	}
   1281 
   1282 	usbd_add_dev_event(USB_EVENT_DEVICE_DETACH, dev);
   1283 	dev->bus->devices[dev->address] = NULL;
   1284 	up->device = NULL;
   1285 	usb_free_device(dev);
   1286 }
   1287 
   1288 #ifdef __OpenBSD__
   1289 void *usb_realloc(void *p, u_int size, int pool, int flags)
   1290 {
   1291 	void *q;
   1292 
   1293 	q = malloc(size, pool, flags);
   1294 	if (q == NULL)
   1295 		return (NULL);
   1296 	bcopy(p, q, size);
   1297 	free(p, pool);
   1298 	return (q);
   1299 }
   1300 #endif
   1301