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