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