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