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