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