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