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