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