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