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