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