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