Home | History | Annotate | Line # | Download | only in usb
usb_subr.c revision 1.198.2.3
      1 /*	$NetBSD: usb_subr.c,v 1.198.2.3 2014/12/03 13:30:51 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.3 2014/12/03 13:30:51 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/malloc.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 MALLOC_DEFINE(M_USB, "USB", "USB misc. memory");
     75 MALLOC_DEFINE(M_USBDEV, "USB device", "USB device driver");
     76 
     77 Static usbd_status usbd_set_config(usbd_device_handle, int);
     78 Static void usbd_devinfo(usbd_device_handle, int, char *, size_t);
     79 Static void usbd_devinfo_vp(usbd_device_handle, char *, size_t, char *, size_t,
     80     int, int);
     81 Static int usbd_getnewaddr(usbd_bus_handle);
     82 Static int usbd_print(void *, const char *);
     83 Static int usbd_ifprint(void *, const char *);
     84 Static void usbd_free_iface_data(usbd_device_handle, int);
     85 
     86 uint32_t usb_cookie_no = 0;
     87 
     88 Static const char * const usbd_error_strs[] = {
     89 	"NORMAL_COMPLETION",
     90 	"IN_PROGRESS",
     91 	"PENDING_REQUESTS",
     92 	"NOT_STARTED",
     93 	"INVAL",
     94 	"NOMEM",
     95 	"CANCELLED",
     96 	"BAD_ADDRESS",
     97 	"IN_USE",
     98 	"NO_ADDR",
     99 	"SET_ADDR_FAILED",
    100 	"NO_POWER",
    101 	"TOO_DEEP",
    102 	"IOERROR",
    103 	"NOT_CONFIGURED",
    104 	"TIMEOUT",
    105 	"SHORT_XFER",
    106 	"STALLED",
    107 	"INTERRUPTED",
    108 	"XXX",
    109 };
    110 
    111 DEV_VERBOSE_DEFINE(usb);
    112 
    113 const char *
    114 usbd_errstr(usbd_status err)
    115 {
    116 	static char buffer[5];
    117 
    118 	if (err < USBD_ERROR_MAX) {
    119 		return usbd_error_strs[err];
    120 	} else {
    121 		snprintf(buffer, sizeof buffer, "%d", err);
    122 		return buffer;
    123 	}
    124 }
    125 
    126 usbd_status
    127 usbd_get_string_desc(usbd_device_handle dev, int sindex, int langid,
    128 		     usb_string_descriptor_t *sdesc, int *sizep)
    129 {
    130 	usb_device_request_t req;
    131 	usbd_status err;
    132 	int actlen;
    133 
    134 	req.bmRequestType = UT_READ_DEVICE;
    135 	req.bRequest = UR_GET_DESCRIPTOR;
    136 	USETW2(req.wValue, UDESC_STRING, sindex);
    137 	USETW(req.wIndex, langid);
    138 	USETW(req.wLength, 2);	/* only size byte first */
    139 	err = usbd_do_request_flags(dev, &req, sdesc, USBD_SHORT_XFER_OK,
    140 		&actlen, USBD_DEFAULT_TIMEOUT);
    141 	if (err)
    142 		return (err);
    143 
    144 	if (actlen < 2)
    145 		return (USBD_SHORT_XFER);
    146 
    147 	USETW(req.wLength, sdesc->bLength);	/* the whole string */
    148  	err = usbd_do_request_flags(dev, &req, sdesc, USBD_SHORT_XFER_OK,
    149  		&actlen, USBD_DEFAULT_TIMEOUT);
    150 	if (err)
    151 		return (err);
    152 
    153 	if (actlen != sdesc->bLength) {
    154 		DPRINTFN(-1, ("usbd_get_string_desc: expected %d, got %d\n",
    155 		    sdesc->bLength, actlen));
    156 	}
    157 
    158 	*sizep = actlen;
    159 	return (USBD_NORMAL_COMPLETION);
    160 }
    161 
    162 static void
    163 usbd_trim_spaces(char *p)
    164 {
    165 	char *q, *e;
    166 
    167 	q = e = p;
    168 	while (*q == ' ')		/* skip leading spaces */
    169 		q++;
    170 	while ((*p = *q++))		/* copy string */
    171 		if (*p++ != ' ')	/* remember last non-space */
    172 			e = p;
    173 	*e = '\0';			/* kill trailing spaces */
    174 }
    175 
    176 Static void
    177 usbd_devinfo_vp(usbd_device_handle dev, char *v, size_t vl, char *p,
    178     size_t pl, int usedev, int useencoded)
    179 {
    180 	usb_device_descriptor_t *udd = &dev->ud_ddesc;
    181 	if (dev == NULL)
    182 		return;
    183 
    184 	v[0] = p[0] = '\0';
    185 
    186 	if (usedev) {
    187 		if (usbd_get_string0(dev, udd->iManufacturer, v, useencoded) ==
    188 		    USBD_NORMAL_COMPLETION)
    189 			usbd_trim_spaces(v);
    190 		if (usbd_get_string0(dev, udd->iProduct, p, useencoded) ==
    191 		    USBD_NORMAL_COMPLETION)
    192 			usbd_trim_spaces(p);
    193 	}
    194 	if (v[0] == '\0')
    195 		usb_findvendor(v, vl, UGETW(udd->idVendor));
    196 	if (p[0] == '\0')
    197 		usb_findproduct(p, pl, UGETW(udd->idVendor),
    198 		    UGETW(udd->idProduct));
    199 }
    200 
    201 int
    202 usbd_printBCD(char *cp, size_t l, int bcd)
    203 {
    204 	return snprintf(cp, l, "%x.%02x", bcd >> 8, bcd & 0xff);
    205 }
    206 
    207 Static void
    208 usbd_devinfo(usbd_device_handle dev, int showclass, char *cp, size_t l)
    209 {
    210 	usb_device_descriptor_t *udd = &dev->ud_ddesc;
    211 	char *vendor, *product;
    212 	int bcdDevice, bcdUSB;
    213 	char *ep;
    214 
    215 	vendor = malloc(USB_MAX_ENCODED_STRING_LEN * 2, M_USB, M_NOWAIT);
    216 	if (vendor == NULL) {
    217 		*cp = '\0';
    218 		return;
    219 	}
    220 	product = &vendor[USB_MAX_ENCODED_STRING_LEN];
    221 
    222 	ep = cp + l;
    223 
    224 	usbd_devinfo_vp(dev, vendor, USB_MAX_ENCODED_STRING_LEN,
    225 	    product, USB_MAX_ENCODED_STRING_LEN, 1, 1);
    226 	cp += snprintf(cp, ep - cp, "%s %s", vendor, product);
    227 	if (showclass)
    228 		cp += snprintf(cp, ep - cp, ", class %d/%d",
    229 		    udd->bDeviceClass, udd->bDeviceSubClass);
    230 	bcdUSB = UGETW(udd->bcdUSB);
    231 	bcdDevice = UGETW(udd->bcdDevice);
    232 	cp += snprintf(cp, ep - cp, ", rev ");
    233 	cp += usbd_printBCD(cp, ep - cp, bcdUSB);
    234 	*cp++ = '/';
    235 	cp += usbd_printBCD(cp, ep - cp, bcdDevice);
    236 	cp += snprintf(cp, ep - cp, ", addr %d", dev->ud_addr);
    237 	*cp = 0;
    238 	free(vendor, M_USB);
    239 }
    240 
    241 char *
    242 usbd_devinfo_alloc(usbd_device_handle dev, int showclass)
    243 {
    244 	char *devinfop;
    245 
    246 	devinfop = malloc(DEVINFOSIZE, M_TEMP, M_WAITOK);
    247 	usbd_devinfo(dev, showclass, devinfop, DEVINFOSIZE);
    248 	return devinfop;
    249 }
    250 
    251 void
    252 usbd_devinfo_free(char *devinfop)
    253 {
    254 	free(devinfop, M_TEMP);
    255 }
    256 
    257 /* Delay for a certain number of ms */
    258 void
    259 usb_delay_ms_locked(usbd_bus_handle bus, u_int ms, kmutex_t *lock)
    260 {
    261 	/* Wait at least two clock ticks so we know the time has passed. */
    262 	if (bus->ub_usepolling || cold)
    263 		delay((ms+1) * 1000);
    264 	else
    265 		kpause("usbdly", false, (ms*hz+999)/1000 + 1, lock);
    266 }
    267 
    268 void
    269 usb_delay_ms(usbd_bus_handle bus, u_int ms)
    270 {
    271 	usb_delay_ms_locked(bus, ms, NULL);
    272 }
    273 
    274 /* Delay given a device handle. */
    275 void
    276 usbd_delay_ms_locked(usbd_device_handle dev, u_int ms, kmutex_t *lock)
    277 {
    278 	usb_delay_ms_locked(dev->ud_bus, ms, lock);
    279 }
    280 
    281 /* Delay given a device handle. */
    282 void
    283 usbd_delay_ms(usbd_device_handle dev, u_int ms)
    284 {
    285 	usb_delay_ms_locked(dev->ud_bus, ms, NULL);
    286 }
    287 
    288 usbd_status
    289 usbd_reset_port(usbd_device_handle dev, int port, usb_port_status_t *ps)
    290 {
    291 	usb_device_request_t req;
    292 	usbd_status err;
    293 	int n;
    294 
    295 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
    296 	req.bRequest = UR_SET_FEATURE;
    297 	USETW(req.wValue, UHF_PORT_RESET);
    298 	USETW(req.wIndex, port);
    299 	USETW(req.wLength, 0);
    300 	err = usbd_do_request(dev, &req, 0);
    301 	DPRINTFN(1,("usbd_reset_port: port %d reset done, error=%s\n",
    302 		    port, usbd_errstr(err)));
    303 	if (err)
    304 		return (err);
    305 	n = 10;
    306 	do {
    307 		/* Wait for device to recover from reset. */
    308 		usbd_delay_ms(dev, USB_PORT_RESET_DELAY);
    309 		err = usbd_get_port_status(dev, port, ps);
    310 		if (err) {
    311 			DPRINTF(("usbd_reset_port: get status failed %d\n",
    312 				 err));
    313 			return (err);
    314 		}
    315 		/* If the device disappeared, just give up. */
    316 		if (!(UGETW(ps->wPortStatus) & UPS_CURRENT_CONNECT_STATUS))
    317 			return (USBD_NORMAL_COMPLETION);
    318 	} while ((UGETW(ps->wPortChange) & UPS_C_PORT_RESET) == 0 && --n > 0);
    319 	if (n == 0)
    320 		return (USBD_TIMEOUT);
    321 	err = usbd_clear_port_feature(dev, port, UHF_C_PORT_RESET);
    322 #ifdef USB_DEBUG
    323 	if (err)
    324 		DPRINTF(("usbd_reset_port: clear port feature failed %d\n",
    325 			 err));
    326 #endif
    327 
    328 	/* Wait for the device to recover from reset. */
    329 	usbd_delay_ms(dev, USB_PORT_RESET_RECOVERY);
    330 	return (err);
    331 }
    332 
    333 usb_interface_descriptor_t *
    334 usbd_find_idesc(usb_config_descriptor_t *cd, int ifaceidx, int altidx)
    335 {
    336 	char *p = (char *)cd;
    337 	char *end = p + UGETW(cd->wTotalLength);
    338 	usb_interface_descriptor_t *d;
    339 	int curidx, lastidx, curaidx = 0;
    340 
    341 	for (curidx = lastidx = -1; p < end; ) {
    342 		d = (usb_interface_descriptor_t *)p;
    343 		DPRINTFN(4,("usbd_find_idesc: idx=%d(%d) altidx=%d(%d) len=%d "
    344 			    "type=%d\n",
    345 			    ifaceidx, curidx, altidx, curaidx,
    346 			    d->bLength, d->bDescriptorType));
    347 		if (d->bLength == 0) /* bad descriptor */
    348 			break;
    349 		p += d->bLength;
    350 		if (p <= end && d->bDescriptorType == UDESC_INTERFACE) {
    351 			if (d->bInterfaceNumber != lastidx) {
    352 				lastidx = d->bInterfaceNumber;
    353 				curidx++;
    354 				curaidx = 0;
    355 			} else
    356 				curaidx++;
    357 			if (ifaceidx == curidx && altidx == curaidx)
    358 				return (d);
    359 		}
    360 	}
    361 	return (NULL);
    362 }
    363 
    364 usb_endpoint_descriptor_t *
    365 usbd_find_edesc(usb_config_descriptor_t *cd, int ifaceidx, int altidx,
    366 		int endptidx)
    367 {
    368 	char *p = (char *)cd;
    369 	char *end = p + UGETW(cd->wTotalLength);
    370 	usb_interface_descriptor_t *d;
    371 	usb_endpoint_descriptor_t *e;
    372 	int curidx;
    373 
    374 	d = usbd_find_idesc(cd, ifaceidx, altidx);
    375 	if (d == NULL)
    376 		return (NULL);
    377 	if (endptidx >= d->bNumEndpoints) /* quick exit */
    378 		return (NULL);
    379 
    380 	curidx = -1;
    381 	for (p = (char *)d + d->bLength; p < end; ) {
    382 		e = (usb_endpoint_descriptor_t *)p;
    383 		if (e->bLength == 0) /* bad descriptor */
    384 			break;
    385 		p += e->bLength;
    386 		if (p <= end && e->bDescriptorType == UDESC_INTERFACE)
    387 			return (NULL);
    388 		if (p <= end && e->bDescriptorType == UDESC_ENDPOINT) {
    389 			curidx++;
    390 			if (curidx == endptidx)
    391 				return (e);
    392 		}
    393 	}
    394 	return (NULL);
    395 }
    396 
    397 usbd_status
    398 usbd_fill_iface_data(usbd_device_handle dev, int ifaceidx, int altidx)
    399 {
    400 	usbd_interface_handle ifc = &dev->ud_ifaces[ifaceidx];
    401 	usb_interface_descriptor_t *idesc;
    402 	char *p, *end;
    403 	int endpt, nendpt;
    404 
    405 	DPRINTFN(4,("usbd_fill_iface_data: ifaceidx=%d altidx=%d\n",
    406 		    ifaceidx, altidx));
    407 	idesc = usbd_find_idesc(dev->ud_cdesc, ifaceidx, altidx);
    408 	if (idesc == NULL)
    409 		return (USBD_INVAL);
    410 	ifc->ui_dev = dev;
    411 	ifc->ui_idesc = idesc;
    412 	ifc->ui_index = ifaceidx;
    413 	ifc->ui_altindex = altidx;
    414 	nendpt = ifc->ui_idesc->bNumEndpoints;
    415 	DPRINTFN(4,("usbd_fill_iface_data: found idesc nendpt=%d\n", nendpt));
    416 	if (nendpt != 0) {
    417 		ifc->ui_endpoints = malloc(nendpt * sizeof(struct usbd_endpoint),
    418 					M_USB, M_NOWAIT);
    419 		if (ifc->ui_endpoints == NULL)
    420 			return (USBD_NOMEM);
    421 	} else
    422 		ifc->ui_endpoints = NULL;
    423 	ifc->ui_priv = NULL;
    424 	p = (char *)ifc->ui_idesc + ifc->ui_idesc->bLength;
    425 	end = (char *)dev->ud_cdesc + UGETW(dev->ud_cdesc->wTotalLength);
    426 #define ed ((usb_endpoint_descriptor_t *)p)
    427 	for (endpt = 0; endpt < nendpt; endpt++) {
    428 		DPRINTFN(10,("usbd_fill_iface_data: endpt=%d\n", endpt));
    429 		for (; p < end; p += ed->bLength) {
    430 			DPRINTFN(10,("usbd_fill_iface_data: p=%p end=%p "
    431 				     "len=%d type=%d\n",
    432 				 p, end, ed->bLength, ed->bDescriptorType));
    433 			if (p + ed->bLength <= end && ed->bLength != 0 &&
    434 			    ed->bDescriptorType == UDESC_ENDPOINT)
    435 				goto found;
    436 			if (ed->bLength == 0 ||
    437 			    ed->bDescriptorType == UDESC_INTERFACE)
    438 				break;
    439 		}
    440 		/* passed end, or bad desc */
    441 		printf("usbd_fill_iface_data: bad descriptor(s): %s\n",
    442 		       ed->bLength == 0 ? "0 length" :
    443 		       ed->bDescriptorType == UDESC_INTERFACE ? "iface desc":
    444 		       "out of data");
    445 		goto bad;
    446 	found:
    447 		ifc->ui_endpoints[endpt].ue_edesc = ed;
    448 		if (dev->ud_speed == USB_SPEED_HIGH) {
    449 			u_int mps;
    450 			/* Control and bulk endpoints have max packet limits. */
    451 			switch (UE_GET_XFERTYPE(ed->bmAttributes)) {
    452 			case UE_CONTROL:
    453 				mps = USB_2_MAX_CTRL_PACKET;
    454 				goto check;
    455 			case UE_BULK:
    456 				mps = USB_2_MAX_BULK_PACKET;
    457 			check:
    458 				if (UGETW(ed->wMaxPacketSize) != mps) {
    459 					USETW(ed->wMaxPacketSize, mps);
    460 #ifdef DIAGNOSTIC
    461 					printf("usbd_fill_iface_data: bad max "
    462 					       "packet size\n");
    463 #endif
    464 				}
    465 				break;
    466 			default:
    467 				break;
    468 			}
    469 		}
    470 		ifc->ui_endpoints[endpt].ue_refcnt = 0;
    471 		ifc->ui_endpoints[endpt].ue_toggle = 0;
    472 		p += ed->bLength;
    473 	}
    474 #undef ed
    475 	LIST_INIT(&ifc->ui_pipes);
    476 	return (USBD_NORMAL_COMPLETION);
    477 
    478  bad:
    479 	if (ifc->ui_endpoints != NULL) {
    480 		free(ifc->ui_endpoints, M_USB);
    481 		ifc->ui_endpoints = NULL;
    482 	}
    483 	return (USBD_INVAL);
    484 }
    485 
    486 void
    487 usbd_free_iface_data(usbd_device_handle dev, int ifcno)
    488 {
    489 	usbd_interface_handle ifc = &dev->ud_ifaces[ifcno];
    490 	if (ifc->ui_endpoints)
    491 		free(ifc->ui_endpoints, M_USB);
    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 		free(dev->ud_ifaces, M_USB);
    553 		free(dev->ud_cdesc, M_USB);
    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 = malloc(len, M_USB, M_NOWAIT);
    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 = malloc(nifc * sizeof(struct usbd_interface),
    670 			     M_USB, M_NOWAIT);
    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 	free(cdp, M_USB);
    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 = malloc(dev->ud_bus->ub_pipesize, M_USB, M_NOWAIT);
    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 		free(p, M_USB);
    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 	free(pipe, M_USB);
    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 = malloc(sizeof dv, M_USB, M_NOWAIT);
    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 = malloc(sizeof dv, M_USB, M_NOWAIT);
    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 = malloc(nifaces * sizeof(*ifaces), M_USB, M_NOWAIT|M_ZERO);
    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 	free(ifaces, M_USB);
    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 = malloc(nifaces * sizeof(device_t), M_USB,
    937 				      M_NOWAIT|M_ZERO);
    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 			free(dev->ud_subdevs, M_USB);
    946 			dev->ud_subdevs = 0;
    947 			dev->ud_subdevlen = 0;
    948 		}
    949 		if (dev->ud_nifaces_claimed || err)
    950 			return (err);
    951 	}
    952 	/* No interfaces were attached in any of the configurations. */
    953 
    954 	if (dd->bNumConfigurations > 1) /* don't change if only 1 config */
    955 		usbd_set_config_index(dev, 0, 0);
    956 
    957 	DPRINTF(("usbd_probe_and_attach: no interface drivers found\n"));
    958 
    959 	/* Finally try the generic driver. */
    960 	err = usbd_attachwholedevice(parent, dev, port, 1);
    961 
    962 	/*
    963 	 * The generic attach failed, but leave the device as it is.
    964 	 * We just did not find any drivers, that's all.  The device is
    965 	 * fully operational and not harming anyone.
    966 	 */
    967 	DPRINTF(("usbd_probe_and_attach: generic attach failed\n"));
    968 	return (USBD_NORMAL_COMPLETION);
    969 }
    970 
    971 /**
    972  * Called from uhub_rescan().  usbd_new_device() for the target dev must be
    973  * called before calling this.
    974  */
    975 usbd_status
    976 usbd_reattach_device(device_t parent, usbd_device_handle dev,
    977                      int port, const int *locators)
    978 {
    979 	int i, loc;
    980 
    981 	if (locators != NULL) {
    982 		loc = locators[USBIFIFCF_PORT];
    983 		if (loc != USBIFIFCF_PORT_DEFAULT && loc != port)
    984 			return USBD_NORMAL_COMPLETION;
    985 		loc = locators[USBIFIFCF_VENDOR];
    986 		if (loc != USBIFIFCF_VENDOR_DEFAULT &&
    987 		    loc != UGETW(dev->ud_ddesc.idVendor))
    988 			return USBD_NORMAL_COMPLETION;
    989 		loc = locators[USBIFIFCF_PRODUCT];
    990 		if (loc != USBIFIFCF_PRODUCT_DEFAULT &&
    991 		    loc != UGETW(dev->ud_ddesc.idProduct))
    992 			return USBD_NORMAL_COMPLETION;
    993 		loc = locators[USBIFIFCF_RELEASE];
    994 		if (loc != USBIFIFCF_RELEASE_DEFAULT &&
    995 		    loc != UGETW(dev->ud_ddesc.bcdDevice))
    996 			return USBD_NORMAL_COMPLETION;
    997 	}
    998 	if (dev->ud_subdevlen == 0) {
    999 		/* XXX: check USBIFIFCF_CONFIGURATION and
   1000 		 * USBIFIFCF_INTERFACE too */
   1001 		return usbd_probe_and_attach(parent, dev, port, dev->ud_addr);
   1002 	} else if (dev->ud_subdevlen != dev->ud_cdesc->bNumInterface) {
   1003 		/* device-specific or generic driver is already attached. */
   1004 		return USBD_NORMAL_COMPLETION;
   1005 	}
   1006 	/* Does the device have unconfigured interfaces? */
   1007 	for (i = 0; i < dev->ud_subdevlen; i++) {
   1008 		if (dev->ud_subdevs[i] == NULL) {
   1009 			break;
   1010 		}
   1011 	}
   1012 	if (i >= dev->ud_subdevlen)
   1013 		return USBD_NORMAL_COMPLETION;
   1014 	return usbd_attachinterfaces(parent, dev, port, locators);
   1015 }
   1016 
   1017 /*
   1018  * Get the first 8 bytes of the device descriptor.
   1019  * Do as Windows does: try to read 64 bytes -- there are devices which
   1020  * recognize the initial descriptor fetch (before the control endpoint's
   1021  * MaxPacketSize is known by the host) by exactly this length.
   1022  */
   1023 usbd_status
   1024 usbd_get_initial_ddesc(usbd_device_handle dev, usb_device_descriptor_t *desc)
   1025 {
   1026 	usb_device_request_t req;
   1027 	char buf[64];
   1028 	int res, actlen;
   1029 
   1030 	req.bmRequestType = UT_READ_DEVICE;
   1031 	req.bRequest = UR_GET_DESCRIPTOR;
   1032 	USETW2(req.wValue, UDESC_DEVICE, 0);
   1033 	USETW(req.wIndex, 0);
   1034 	USETW(req.wLength, 64);
   1035 	res = usbd_do_request_flags(dev, &req, buf, USBD_SHORT_XFER_OK,
   1036 		&actlen, USBD_DEFAULT_TIMEOUT);
   1037 	if (res)
   1038 		return res;
   1039 	if (actlen < 8)
   1040 		return USBD_SHORT_XFER;
   1041 	memcpy(desc, buf, 8);
   1042 	return USBD_NORMAL_COMPLETION;
   1043 }
   1044 
   1045 /*
   1046  * Called when a new device has been put in the powered state,
   1047  * but not yet in the addressed state.
   1048  * Get initial descriptor, set the address, get full descriptor,
   1049  * and attach a driver.
   1050  */
   1051 usbd_status
   1052 usbd_new_device(device_t parent, usbd_bus_handle bus, int depth,
   1053                 int speed, int port, struct usbd_port *up)
   1054 {
   1055 	usbd_device_handle dev, adev;
   1056 	struct usbd_device *hub;
   1057 	usb_device_descriptor_t *dd;
   1058 	usb_port_status_t ps;
   1059 	usbd_status err;
   1060 	int addr;
   1061 	int i;
   1062 	int p;
   1063 
   1064 	DPRINTF(("usbd_new_device bus=%p port=%d depth=%d speed=%d\n",
   1065 		 bus, port, depth, speed));
   1066 
   1067 	if (bus->ub_methods->ubm_newdev != NULL)
   1068 		return (bus->ub_methods->ubm_newdev)(parent, bus, depth, speed,
   1069 		    port, up);
   1070 
   1071 	addr = usbd_getnewaddr(bus);
   1072 	if (addr < 0) {
   1073 		printf("%s: No free USB addresses, new device ignored.\n",
   1074 		       device_xname(bus->ub_usbctl));
   1075 		return (USBD_NO_ADDR);
   1076 	}
   1077 
   1078 	dev = malloc(sizeof *dev, M_USB, M_NOWAIT|M_ZERO);
   1079 	if (dev == NULL)
   1080 		return (USBD_NOMEM);
   1081 
   1082 	dev->ud_bus = bus;
   1083 
   1084 	/* Set up default endpoint handle. */
   1085 	dev->ud_ep0.ue_edesc = &dev->ud_ep0desc;
   1086 
   1087 	/* Set up default endpoint descriptor. */
   1088 	dev->ud_ep0desc.bLength = USB_ENDPOINT_DESCRIPTOR_SIZE;
   1089 	dev->ud_ep0desc.bDescriptorType = UDESC_ENDPOINT;
   1090 	dev->ud_ep0desc.bEndpointAddress = USB_CONTROL_ENDPOINT;
   1091 	dev->ud_ep0desc.bmAttributes = UE_CONTROL;
   1092 	/*
   1093 	 * temporary, will be fixed after first descriptor fetch
   1094 	 * (which uses 64 bytes so it shouldn't be less),
   1095 	 * highspeed devices must support 64 byte packets anyway
   1096 	 */
   1097 	if (speed == USB_SPEED_HIGH || speed == USB_SPEED_FULL)
   1098 		USETW(dev->ud_ep0desc.wMaxPacketSize, 64);
   1099 	else
   1100 		USETW(dev->ud_ep0desc.wMaxPacketSize, USB_MAX_IPACKET);
   1101 
   1102 	dev->ud_ep0desc.bInterval = 0;
   1103 
   1104 	/* doesn't matter, just don't let it uninitialized */
   1105 	dev->ud_ep0.ue_toggle = 0;
   1106 
   1107 	dev->ud_quirks = &usbd_no_quirk;
   1108 	dev->ud_addr = USB_START_ADDR;
   1109 	dev->ud_ddesc.bMaxPacketSize = 0;
   1110 	dev->ud_depth = depth;
   1111 	dev->ud_powersrc = up;
   1112 	dev->ud_myhub = up->up_parent;
   1113 
   1114 	up->up_dev = dev;
   1115 
   1116 	/* Locate port on upstream high speed hub */
   1117 	for (adev = dev, hub = up->up_parent;
   1118 	     hub != NULL && hub->ud_speed != USB_SPEED_HIGH;
   1119 	     adev = hub, hub = hub->ud_myhub)
   1120 		;
   1121 	if (hub) {
   1122 		for (p = 0; p < hub->ud_hub->uh_hubdesc.bNbrPorts; p++) {
   1123 			if (hub->ud_hub->uh_ports[p].up_dev == adev) {
   1124 				dev->ud_myhsport = &hub->ud_hub->uh_ports[p];
   1125 				goto found;
   1126 			}
   1127 		}
   1128 		panic("usbd_new_device: cannot find HS port\n");
   1129 	found:
   1130 		DPRINTFN(1,("usbd_new_device: high speed port %d\n", p));
   1131 	} else {
   1132 		dev->ud_myhsport = NULL;
   1133 	}
   1134 	dev->ud_speed = speed;
   1135 	dev->ud_langid = USBD_NOLANG;
   1136 	dev->ud_cookie.cookie = ++usb_cookie_no;
   1137 
   1138 	/* Establish the default pipe. */
   1139 	err = usbd_setup_pipe_flags(dev, 0, &dev->ud_ep0, USBD_DEFAULT_INTERVAL,
   1140 			      &dev->ud_pipe0, USBD_MPSAFE);
   1141 	if (err) {
   1142 		usbd_remove_device(dev, up);
   1143 		return (err);
   1144 	}
   1145 
   1146 	dd = &dev->ud_ddesc;
   1147 	/* Try a few times in case the device is slow (i.e. outside specs.) */
   1148 	for (i = 0; i < 10; i++) {
   1149 		/* Get the first 8 bytes of the device descriptor. */
   1150 		err = usbd_get_initial_ddesc(dev, dd);
   1151 		if (!err)
   1152 			break;
   1153 		usbd_delay_ms(dev, 200);
   1154 		if ((i & 3) == 3)
   1155 			usbd_reset_port(up->up_parent, port, &ps);
   1156 	}
   1157 	if (err) {
   1158 		DPRINTFN(-1, ("usbd_new_device: addr=%d, getting first desc "
   1159 			      "failed: %d\n", addr, err));
   1160 		usbd_remove_device(dev, up);
   1161 		return (err);
   1162 	}
   1163 
   1164 	/* Windows resets the port here, do likewise */
   1165 	if (up->up_parent)
   1166 		usbd_reset_port(up->up_parent, port, &ps);
   1167 
   1168 	if (speed == USB_SPEED_HIGH) {
   1169 		/* Max packet size must be 64 (sec 5.5.3). */
   1170 		if (dd->bMaxPacketSize != USB_2_MAX_CTRL_PACKET) {
   1171 #ifdef DIAGNOSTIC
   1172 			printf("usbd_new_device: addr=%d bad max packet "
   1173 			    "size=%d. adjusting to %d.\n",
   1174 			    addr, dd->bMaxPacketSize, USB_2_MAX_CTRL_PACKET);
   1175 #endif
   1176 			dd->bMaxPacketSize = USB_2_MAX_CTRL_PACKET;
   1177 		}
   1178 	}
   1179 
   1180 	DPRINTF(("usbd_new_device: adding unit addr=%d, rev=%02x, class=%d, "
   1181 		 "subclass=%d, protocol=%d, maxpacket=%d, len=%d, speed=%d\n",
   1182 		 addr,UGETW(dd->bcdUSB), dd->bDeviceClass, dd->bDeviceSubClass,
   1183 		 dd->bDeviceProtocol, dd->bMaxPacketSize, dd->bLength,
   1184 		 dev->ud_speed));
   1185 
   1186 	if (dd->bDescriptorType != UDESC_DEVICE) {
   1187 		/* Illegal device descriptor */
   1188 		DPRINTFN(-1,("usbd_new_device: illegal descriptor %d\n",
   1189 			     dd->bDescriptorType));
   1190 		usbd_remove_device(dev, up);
   1191 		return (USBD_INVAL);
   1192 	}
   1193 
   1194 	if (dd->bLength < USB_DEVICE_DESCRIPTOR_SIZE) {
   1195 		DPRINTFN(-1,("usbd_new_device: bad length %d\n", dd->bLength));
   1196 		usbd_remove_device(dev, up);
   1197 		return (USBD_INVAL);
   1198 	}
   1199 
   1200 	USETW(dev->ud_ep0desc.wMaxPacketSize, dd->bMaxPacketSize);
   1201 
   1202 	/* Re-establish the default pipe with the new MPS. */
   1203 	usbd_kill_pipe(dev->ud_pipe0);
   1204 	err = usbd_setup_pipe_flags(dev, 0, &dev->ud_ep0, USBD_DEFAULT_INTERVAL,
   1205 	    &dev->ud_pipe0, USBD_MPSAFE);
   1206 	if (err) {
   1207 		DPRINTFN(-1, ("usbd_new_device: setup default pipe failed\n"));
   1208 		usbd_remove_device(dev, up);
   1209 		return err;
   1210 	}
   1211 
   1212 	/* Set the address */
   1213 	DPRINTFN(5, ("usbd_new_device: setting device address=%d\n", addr));
   1214 	err = usbd_set_address(dev, addr);
   1215 	if (err) {
   1216 		DPRINTFN(-1, ("usbd_new_device: set address %d failed\n", addr));
   1217 		err = USBD_SET_ADDR_FAILED;
   1218 		usbd_remove_device(dev, up);
   1219 		return err;
   1220 	}
   1221 
   1222 	/* Allow device time to set new address */
   1223 	usbd_delay_ms(dev, USB_SET_ADDRESS_SETTLE);
   1224 	dev->ud_addr = addr;	/* new device address now */
   1225 	bus->ub_devices[addr] = dev;
   1226 
   1227 	/* Re-establish the default pipe with the new address. */
   1228 	usbd_kill_pipe(dev->ud_pipe0);
   1229 	err = usbd_setup_pipe_flags(dev, 0, &dev->ud_ep0, USBD_DEFAULT_INTERVAL,
   1230 	    &dev->ud_pipe0, USBD_MPSAFE);
   1231 	if (err) {
   1232 		DPRINTFN(-1, ("usbd_new_device: setup default pipe failed\n"));
   1233 		usbd_remove_device(dev, up);
   1234 		return err;
   1235 	}
   1236 
   1237 	err = usbd_reload_device_desc(dev);
   1238 	if (err) {
   1239 		DPRINTFN(-1, ("usbd_new_device: addr=%d, getting full desc "
   1240 			      "failed\n", addr));
   1241 		usbd_remove_device(dev, up);
   1242 		return (err);
   1243 	}
   1244 
   1245 	/* Assume 100mA bus powered for now. Changed when configured. */
   1246 	dev->ud_power = USB_MIN_POWER;
   1247 	dev->ud_selfpowered = 0;
   1248 
   1249 	DPRINTF(("usbd_new_device: new dev (addr %d), dev=%p, parent=%p\n",
   1250 		 addr, dev, parent));
   1251 
   1252 	usbd_add_dev_event(USB_EVENT_DEVICE_ATTACH, dev);
   1253 
   1254 	if (port == 0) { /* root hub */
   1255 		KASSERT(addr == 1);
   1256 		usbd_attach_roothub(parent, dev);
   1257 		return (USBD_NORMAL_COMPLETION);
   1258 	}
   1259 
   1260 	err = usbd_probe_and_attach(parent, dev, port, addr);
   1261 	if (err) {
   1262 		usbd_remove_device(dev, up);
   1263 		return (err);
   1264 	}
   1265 
   1266 	return (USBD_NORMAL_COMPLETION);
   1267 }
   1268 
   1269 usbd_status
   1270 usbd_reload_device_desc(usbd_device_handle dev)
   1271 {
   1272 	usbd_status err;
   1273 
   1274 	/* Get the full device descriptor. */
   1275 	err = usbd_get_device_desc(dev, &dev->ud_ddesc);
   1276 	if (err)
   1277 		return (err);
   1278 
   1279 	/* Figure out what's wrong with this device. */
   1280 	dev->ud_quirks = usbd_find_quirk(&dev->ud_ddesc);
   1281 
   1282 	return (USBD_NORMAL_COMPLETION);
   1283 }
   1284 
   1285 void
   1286 usbd_remove_device(usbd_device_handle dev, struct usbd_port *up)
   1287 {
   1288 
   1289 	DPRINTF(("usbd_remove_device: %p\n", dev));
   1290 
   1291 	if (dev->ud_pipe0 != NULL)
   1292 		usbd_kill_pipe(dev->ud_pipe0);
   1293 	up->up_dev = NULL;
   1294 	dev->ud_bus->ub_devices[dev->ud_addr] = NULL;
   1295 
   1296 	free(dev, M_USB);
   1297 }
   1298 
   1299 int
   1300 usbd_print(void *aux, const char *pnp)
   1301 {
   1302 	struct usb_attach_arg *uaa = aux;
   1303 
   1304 	DPRINTFN(15, ("usbd_print dev=%p\n", uaa->device));
   1305 	if (pnp) {
   1306 #define USB_DEVINFO 1024
   1307 		char *devinfo;
   1308 		if (!uaa->usegeneric)
   1309 			return (QUIET);
   1310 		devinfo = malloc(USB_DEVINFO, M_TEMP, M_WAITOK);
   1311 		usbd_devinfo(uaa->device, 1, devinfo, USB_DEVINFO);
   1312 		aprint_normal("%s, %s", devinfo, pnp);
   1313 		free(devinfo, M_TEMP);
   1314 	}
   1315 	aprint_normal(" port %d", uaa->port);
   1316 #if 0
   1317 	/*
   1318 	 * It gets very crowded with these locators on the attach line.
   1319 	 * They are not really needed since they are printed in the clear
   1320 	 * by each driver.
   1321 	 */
   1322 	if (uaa->vendor != UHUB_UNK_VENDOR)
   1323 		aprint_normal(" vendor 0x%04x", uaa->vendor);
   1324 	if (uaa->product != UHUB_UNK_PRODUCT)
   1325 		aprint_normal(" product 0x%04x", uaa->product);
   1326 	if (uaa->release != UHUB_UNK_RELEASE)
   1327 		aprint_normal(" release 0x%04x", uaa->release);
   1328 #endif
   1329 	return (UNCONF);
   1330 }
   1331 
   1332 int
   1333 usbd_ifprint(void *aux, const char *pnp)
   1334 {
   1335 	struct usbif_attach_arg *uaa = aux;
   1336 
   1337 	DPRINTFN(15, ("usbd_print dev=%p\n", uaa->device));
   1338 	if (pnp)
   1339 		return (QUIET);
   1340 	aprint_normal(" port %d", uaa->port);
   1341 	aprint_normal(" configuration %d", uaa->configno);
   1342 	aprint_normal(" interface %d", uaa->ifaceno);
   1343 #if 0
   1344 	/*
   1345 	 * It gets very crowded with these locators on the attach line.
   1346 	 * They are not really needed since they are printed in the clear
   1347 	 * by each driver.
   1348 	 */
   1349 	if (uaa->vendor != UHUB_UNK_VENDOR)
   1350 		aprint_normal(" vendor 0x%04x", uaa->vendor);
   1351 	if (uaa->product != UHUB_UNK_PRODUCT)
   1352 		aprint_normal(" product 0x%04x", uaa->product);
   1353 	if (uaa->release != UHUB_UNK_RELEASE)
   1354 		aprint_normal(" release 0x%04x", uaa->release);
   1355 #endif
   1356 	return (UNCONF);
   1357 }
   1358 
   1359 void
   1360 usbd_fill_deviceinfo(usbd_device_handle dev, struct usb_device_info *di,
   1361 		     int usedev)
   1362 {
   1363 	struct usbd_port *p;
   1364 	int i, j, err, s;
   1365 
   1366 	di->udi_bus = device_unit(dev->ud_bus->ub_usbctl);
   1367 	di->udi_addr = dev->ud_addr;
   1368 	di->udi_cookie = dev->ud_cookie;
   1369 	usbd_devinfo_vp(dev, di->udi_vendor, sizeof(di->udi_vendor),
   1370 	    di->udi_product, sizeof(di->udi_product), usedev, 1);
   1371 	usbd_printBCD(di->udi_release, sizeof(di->udi_release),
   1372 	    UGETW(dev->ud_ddesc.bcdDevice));
   1373 	di->udi_serial[0] = 0;
   1374 	if (usedev)
   1375 		(void)usbd_get_string(dev, dev->ud_ddesc.iSerialNumber,
   1376 				      di->udi_serial);
   1377 	di->udi_vendorNo = UGETW(dev->ud_ddesc.idVendor);
   1378 	di->udi_productNo = UGETW(dev->ud_ddesc.idProduct);
   1379 	di->udi_releaseNo = UGETW(dev->ud_ddesc.bcdDevice);
   1380 	di->udi_class = dev->ud_ddesc.bDeviceClass;
   1381 	di->udi_subclass = dev->ud_ddesc.bDeviceSubClass;
   1382 	di->udi_protocol = dev->ud_ddesc.bDeviceProtocol;
   1383 	di->udi_config = dev->ud_config;
   1384 	di->udi_power = dev->ud_selfpowered ? 0 : dev->ud_power;
   1385 	di->udi_speed = dev->ud_speed;
   1386 
   1387 	if (dev->ud_subdevlen > 0) {
   1388 		for (i = 0, j = 0; i < dev->ud_subdevlen &&
   1389 			     j < USB_MAX_DEVNAMES; i++) {
   1390 			if (!dev->ud_subdevs[i])
   1391 				continue;
   1392 			strncpy(di->udi_devnames[j],
   1393 			    device_xname(dev->ud_subdevs[i]), USB_MAX_DEVNAMELEN);
   1394 			di->udi_devnames[j][USB_MAX_DEVNAMELEN-1] = '\0';
   1395 			j++;
   1396 		}
   1397 	} else {
   1398 		j = 0;
   1399 	}
   1400 	for (/* j is set */; j < USB_MAX_DEVNAMES; j++)
   1401 		di->udi_devnames[j][0] = 0;                 /* empty */
   1402 
   1403 	if (dev->ud_hub) {
   1404 		for (i = 0;
   1405 		     i < sizeof(di->udi_ports) / sizeof(di->udi_ports[0]) &&
   1406 			     i < dev->ud_hub->uh_hubdesc.bNbrPorts;
   1407 		     i++) {
   1408 			p = &dev->ud_hub->uh_ports[i];
   1409 			if (p->up_dev)
   1410 				err = p->up_dev->ud_addr;
   1411 			else {
   1412 				s = UGETW(p->up_status.wPortStatus);
   1413 				if (s & UPS_PORT_ENABLED)
   1414 					err = USB_PORT_ENABLED;
   1415 				else if (s & UPS_SUSPEND)
   1416 					err = USB_PORT_SUSPENDED;
   1417 				else if (s & UPS_PORT_POWER)
   1418 					err = USB_PORT_POWERED;
   1419 				else
   1420 					err = USB_PORT_DISABLED;
   1421 			}
   1422 			di->udi_ports[i] = err;
   1423 		}
   1424 		di->udi_nports = dev->ud_hub->uh_hubdesc.bNbrPorts;
   1425 	} else
   1426 		di->udi_nports = 0;
   1427 }
   1428 
   1429 #ifdef COMPAT_30
   1430 void
   1431 usbd_fill_deviceinfo_old(usbd_device_handle dev, struct usb_device_info_old *di,
   1432                          int usedev)
   1433 {
   1434 	struct usbd_port *p;
   1435 	int i, j, err, s;
   1436 
   1437 	di->udi_bus = device_unit(dev->ud_bus->ub_usbctl);
   1438 	di->udi_addr = dev->ud_addr;
   1439 	di->udi_cookie = dev->ud_cookie;
   1440 	usbd_devinfo_vp(dev, di->udi_vendor, sizeof(di->udi_vendor),
   1441 	    di->udi_product, sizeof(di->udi_product), usedev, 0);
   1442 	usbd_printBCD(di->udi_release, sizeof(di->udi_release),
   1443 	    UGETW(dev->ud_ddesc.bcdDevice));
   1444 	di->udi_vendorNo = UGETW(dev->ud_ddesc.idVendor);
   1445 	di->udi_productNo = UGETW(dev->ud_ddesc.idProduct);
   1446 	di->udi_releaseNo = UGETW(dev->ud_ddesc.bcdDevice);
   1447 	di->udi_class = dev->ud_ddesc.bDeviceClass;
   1448 	di->udi_subclass = dev->ud_ddesc.bDeviceSubClass;
   1449 	di->udi_protocol = dev->ud_ddesc.bDeviceProtocol;
   1450 	di->udi_config = dev->ud_config;
   1451 	di->udi_power = dev->ud_selfpowered ? 0 : dev->ud_power;
   1452 	di->udi_speed = dev->ud_speed;
   1453 
   1454 	if (dev->ud_subdevlen > 0) {
   1455 		for (i = 0, j = 0; i < dev->ud_subdevlen &&
   1456 			     j < USB_MAX_DEVNAMES; i++) {
   1457 			if (!dev->ud_subdevs[i])
   1458 				continue;
   1459 			strncpy(di->udi_devnames[j],
   1460 			    device_xname(dev->ud_subdevs[i]), USB_MAX_DEVNAMELEN);
   1461 			di->udi_devnames[j][USB_MAX_DEVNAMELEN-1] = '\0';
   1462 			j++;
   1463 		}
   1464 	} else {
   1465 		j = 0;
   1466 	}
   1467 	for (/* j is set */; j < USB_MAX_DEVNAMES; j++)
   1468 		di->udi_devnames[j][0] = 0;		 /* empty */
   1469 
   1470 	if (dev->ud_hub) {
   1471 		for (i = 0;
   1472 		     i < sizeof(di->udi_ports) / sizeof(di->udi_ports[0]) &&
   1473 			     i < dev->ud_hub->uh_hubdesc.bNbrPorts;
   1474 		     i++) {
   1475 			p = &dev->ud_hub->uh_ports[i];
   1476 			if (p->up_dev)
   1477 				err = p->up_dev->ud_addr;
   1478 			else {
   1479 				s = UGETW(p->up_status.wPortStatus);
   1480 				if (s & UPS_PORT_ENABLED)
   1481 					err = USB_PORT_ENABLED;
   1482 				else if (s & UPS_SUSPEND)
   1483 					err = USB_PORT_SUSPENDED;
   1484 				else if (s & UPS_PORT_POWER)
   1485 					err = USB_PORT_POWERED;
   1486 				else
   1487 					err = USB_PORT_DISABLED;
   1488 			}
   1489 			di->udi_ports[i] = err;
   1490 		}
   1491 		di->udi_nports = dev->ud_hub->uh_hubdesc.bNbrPorts;
   1492 	} else
   1493 		di->udi_nports = 0;
   1494 }
   1495 #endif
   1496 
   1497 
   1498 void
   1499 usb_free_device(usbd_device_handle dev)
   1500 {
   1501 	int ifcidx, nifc;
   1502 
   1503 	if (dev->ud_pipe0 != NULL)
   1504 		usbd_kill_pipe(dev->ud_pipe0);
   1505 	if (dev->ud_ifaces != NULL) {
   1506 		nifc = dev->ud_cdesc->bNumInterface;
   1507 		for (ifcidx = 0; ifcidx < nifc; ifcidx++)
   1508 			usbd_free_iface_data(dev, ifcidx);
   1509 		free(dev->ud_ifaces, M_USB);
   1510 	}
   1511 	if (dev->ud_cdesc != NULL)
   1512 		free(dev->ud_cdesc, M_USB);
   1513 	if (dev->ud_subdevlen > 0) {
   1514 		free(dev->ud_subdevs, M_USB);
   1515 		dev->ud_subdevlen = 0;
   1516 	}
   1517 	free(dev, M_USB);
   1518 }
   1519 
   1520 /*
   1521  * The general mechanism for detaching drivers works as follows: Each
   1522  * driver is responsible for maintaining a reference count on the
   1523  * number of outstanding references to its softc (e.g.  from
   1524  * processing hanging in a read or write).  The detach method of the
   1525  * driver decrements this counter and flags in the softc that the
   1526  * driver is dying and then wakes any sleepers.  It then sleeps on the
   1527  * softc.  Each place that can sleep must maintain the reference
   1528  * count.  When the reference count drops to -1 (0 is the normal value
   1529  * of the reference count) the a wakeup on the softc is performed
   1530  * signaling to the detach waiter that all references are gone.
   1531  */
   1532 
   1533 /*
   1534  * Called from process context when we discover that a port has
   1535  * been disconnected.
   1536  */
   1537 int
   1538 usb_disconnect_port(struct usbd_port *up, device_t parent, int flags)
   1539 {
   1540 	usbd_device_handle dev = up->up_dev;
   1541 	device_t subdev;
   1542 	char subdevname[16];
   1543 	const char *hubname = device_xname(parent);
   1544 	int i, rc;
   1545 
   1546 	DPRINTFN(3,("uhub_disconnect: up=%p dev=%p port=%d\n",
   1547 		    up, dev, up->up_portno));
   1548 
   1549 	if (dev == NULL) {
   1550 #ifdef DIAGNOSTIC
   1551 		printf("usb_disconnect_port: no device\n");
   1552 #endif
   1553 		return 0;
   1554 	}
   1555 
   1556 	if (dev->ud_subdevlen > 0) {
   1557 		DPRINTFN(3,("usb_disconnect_port: disconnect subdevs\n"));
   1558 		for (i = 0; i < dev->ud_subdevlen; i++) {
   1559 			if ((subdev = dev->ud_subdevs[i]) == NULL)
   1560 				continue;
   1561 			strlcpy(subdevname, device_xname(subdev),
   1562 			    sizeof(subdevname));
   1563 			if ((rc = config_detach(subdev, flags)) != 0)
   1564 				return rc;
   1565 			printf("%s: at %s", subdevname, hubname);
   1566 			if (up->up_portno != 0)
   1567 				printf(" port %d", up->up_portno);
   1568 			printf(" (addr %d) disconnected\n", dev->ud_addr);
   1569 		}
   1570 		KASSERT(!dev->ud_nifaces_claimed);
   1571 	}
   1572 
   1573 	usbd_add_dev_event(USB_EVENT_DEVICE_DETACH, dev);
   1574 	dev->ud_bus->ub_devices[dev->ud_addr] = NULL;
   1575 	up->up_dev = NULL;
   1576 	usb_free_device(dev);
   1577 	return 0;
   1578 }
   1579