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