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