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