Home | History | Annotate | Line # | Download | only in usb
usb_subr.c revision 1.107
      1 /*	$NetBSD: usb_subr.c,v 1.107 2004/01/05 13:32:23 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 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.107 2004/01/05 13:32:23 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 Static usbd_status usbd_set_config(usbd_device_handle, int);
     84 Static void usbd_devinfo_vp(usbd_device_handle, char *, char *, int);
     85 Static char *usbd_get_string(usbd_device_handle, int, char *);
     86 Static int usbd_getnewaddr(usbd_bus_handle bus);
     87 #if defined(__NetBSD__)
     88 Static int usbd_print(void *aux, const char *pnp);
     89 Static int usbd_submatch(device_ptr_t, struct cfdata *cf, void *);
     90 #elif defined(__OpenBSD__)
     91 Static int usbd_print(void *aux, const char *pnp);
     92 Static int usbd_submatch(device_ptr_t, void *, void *);
     93 #endif
     94 Static void usbd_free_iface_data(usbd_device_handle dev, int ifcno);
     95 Static void usbd_kill_pipe(usbd_pipe_handle);
     96 Static usbd_status usbd_probe_and_attach(device_ptr_t parent,
     97 				 usbd_device_handle dev, int port, int addr);
     98 
     99 Static u_int32_t usb_cookie_no = 0;
    100 
    101 #ifdef USBVERBOSE
    102 typedef u_int16_t usb_vendor_id_t;
    103 typedef u_int16_t usb_product_id_t;
    104 
    105 /*
    106  * Descriptions of of known vendors and devices ("products").
    107  */
    108 struct usb_knowndev {
    109 	usb_vendor_id_t		vendor;
    110 	usb_product_id_t	product;
    111 	int			flags;
    112 	char			*vendorname, *productname;
    113 };
    114 #define	USB_KNOWNDEV_NOPROD	0x01		/* match on vendor only */
    115 
    116 #include <dev/usb/usbdevs_data.h>
    117 #endif /* USBVERBOSE */
    118 
    119 Static const char * const usbd_error_strs[] = {
    120 	"NORMAL_COMPLETION",
    121 	"IN_PROGRESS",
    122 	"PENDING_REQUESTS",
    123 	"NOT_STARTED",
    124 	"INVAL",
    125 	"NOMEM",
    126 	"CANCELLED",
    127 	"BAD_ADDRESS",
    128 	"IN_USE",
    129 	"NO_ADDR",
    130 	"SET_ADDR_FAILED",
    131 	"NO_POWER",
    132 	"TOO_DEEP",
    133 	"IOERROR",
    134 	"NOT_CONFIGURED",
    135 	"TIMEOUT",
    136 	"SHORT_XFER",
    137 	"STALLED",
    138 	"INTERRUPTED",
    139 	"XXX",
    140 };
    141 
    142 const char *
    143 usbd_errstr(usbd_status err)
    144 {
    145 	static char buffer[5];
    146 
    147 	if (err < USBD_ERROR_MAX) {
    148 		return usbd_error_strs[err];
    149 	} else {
    150 		snprintf(buffer, sizeof buffer, "%d", err);
    151 		return buffer;
    152 	}
    153 }
    154 
    155 usbd_status
    156 usbd_get_string_desc(usbd_device_handle dev, int sindex, int langid,
    157 		     usb_string_descriptor_t *sdesc)
    158 {
    159 	usb_device_request_t req;
    160 	usbd_status err;
    161 	int actlen;
    162 
    163 	req.bmRequestType = UT_READ_DEVICE;
    164 	req.bRequest = UR_GET_DESCRIPTOR;
    165 	USETW2(req.wValue, UDESC_STRING, sindex);
    166 	USETW(req.wIndex, langid);
    167 	USETW(req.wLength, 2);	/* only size byte first */
    168 	err = usbd_do_request_flags(dev, &req, sdesc, USBD_SHORT_XFER_OK,
    169 		&actlen, USBD_DEFAULT_TIMEOUT);
    170 	if (err)
    171 		return (err);
    172 
    173 	if (actlen < 1)
    174 		return (USBD_SHORT_XFER);
    175 
    176 	USETW(req.wLength, sdesc->bLength);	/* the whole string */
    177 	return (usbd_do_request(dev, &req, sdesc));
    178 }
    179 
    180 char *
    181 usbd_get_string(usbd_device_handle dev, int si, char *buf)
    182 {
    183 	int swap = dev->quirks->uq_flags & UQ_SWAP_UNICODE;
    184 	usb_string_descriptor_t us;
    185 	char *s;
    186 	int i, n;
    187 	u_int16_t c;
    188 	usbd_status err;
    189 
    190 	if (si == 0)
    191 		return (0);
    192 	if (dev->quirks->uq_flags & UQ_NO_STRINGS)
    193 		return (0);
    194 	if (dev->langid == USBD_NOLANG) {
    195 		/* Set up default language */
    196 		err = usbd_get_string_desc(dev, USB_LANGUAGE_TABLE, 0, &us);
    197 		if (err || us.bLength < 4) {
    198 			dev->langid = 0; /* Well, just pick something then */
    199 		} else {
    200 			/* Pick the first language as the default. */
    201 			dev->langid = UGETW(us.bString[0]);
    202 		}
    203 	}
    204 	err = usbd_get_string_desc(dev, si, dev->langid, &us);
    205 	if (err)
    206 		return (0);
    207 	s = buf;
    208 	n = us.bLength / 2 - 1;
    209 	for (i = 0; i < n; i++) {
    210 		c = UGETW(us.bString[i]);
    211 		/* Convert from Unicode, handle buggy strings. */
    212 		if ((c & 0xff00) == 0)
    213 			*s++ = c;
    214 		else if ((c & 0x00ff) == 0 && swap)
    215 			*s++ = c >> 8;
    216 		else
    217 			*s++ = '?';
    218 	}
    219 	*s++ = 0;
    220 	return (buf);
    221 }
    222 
    223 static void
    224 usbd_trim_spaces(char *p)
    225 {
    226 	char *q, *e;
    227 
    228 	if (p == NULL)
    229 		return;
    230 	q = e = p;
    231 	while (*q == ' ')	/* skip leading spaces */
    232 		q++;
    233 	while ((*p = *q++))	/* copy string */
    234 		if (*p++ != ' ') /* remember last non-space */
    235 			e = p;
    236 	*e = 0;			/* kill trailing spaces */
    237 }
    238 
    239 void
    240 usbd_devinfo_vp(usbd_device_handle dev, char *v, char *p, int usedev)
    241 {
    242 	usb_device_descriptor_t *udd = &dev->ddesc;
    243 	char *vendor = 0, *product = 0;
    244 #ifdef USBVERBOSE
    245 	const struct usb_knowndev *kdp;
    246 #endif
    247 
    248 	if (dev == NULL) {
    249 		v[0] = p[0] = '\0';
    250 		return;
    251 	}
    252 
    253 	if (usedev) {
    254 		vendor = usbd_get_string(dev, udd->iManufacturer, v);
    255 		usbd_trim_spaces(vendor);
    256 		product = usbd_get_string(dev, udd->iProduct, p);
    257 		usbd_trim_spaces(product);
    258 	} else {
    259 		vendor = NULL;
    260 		product = NULL;
    261 	}
    262 #ifdef USBVERBOSE
    263 	if (vendor == NULL || product == NULL) {
    264 		for(kdp = usb_knowndevs;
    265 		    kdp->vendorname != NULL;
    266 		    kdp++) {
    267 			if (kdp->vendor == UGETW(udd->idVendor) &&
    268 			    (kdp->product == UGETW(udd->idProduct) ||
    269 			     (kdp->flags & USB_KNOWNDEV_NOPROD) != 0))
    270 				break;
    271 		}
    272 		if (kdp->vendorname != NULL) {
    273 			if (vendor == NULL)
    274 			    vendor = kdp->vendorname;
    275 			if (product == NULL)
    276 			    product = (kdp->flags & USB_KNOWNDEV_NOPROD) == 0 ?
    277 				kdp->productname : NULL;
    278 		}
    279 	}
    280 #endif
    281 	if (vendor != NULL && *vendor)
    282 		strcpy(v, vendor);
    283 	else
    284 		sprintf(v, "vendor 0x%04x", UGETW(udd->idVendor));
    285 	if (product != NULL && *product)
    286 		strcpy(p, product);
    287 	else
    288 		sprintf(p, "product 0x%04x", UGETW(udd->idProduct));
    289 }
    290 
    291 int
    292 usbd_printBCD(char *cp, int bcd)
    293 {
    294 	return (sprintf(cp, "%x.%02x", bcd >> 8, bcd & 0xff));
    295 }
    296 
    297 void
    298 usbd_devinfo(usbd_device_handle dev, int showclass, char *cp)
    299 {
    300 	usb_device_descriptor_t *udd = &dev->ddesc;
    301 	char vendor[USB_MAX_STRING_LEN];
    302 	char product[USB_MAX_STRING_LEN];
    303 	int bcdDevice, bcdUSB;
    304 
    305 	usbd_devinfo_vp(dev, vendor, product, 1);
    306 	cp += sprintf(cp, "%s %s", vendor, product);
    307 	if (showclass)
    308 		cp += sprintf(cp, ", class %d/%d",
    309 			      udd->bDeviceClass, udd->bDeviceSubClass);
    310 	bcdUSB = UGETW(udd->bcdUSB);
    311 	bcdDevice = UGETW(udd->bcdDevice);
    312 	cp += sprintf(cp, ", rev ");
    313 	cp += usbd_printBCD(cp, bcdUSB);
    314 	*cp++ = '/';
    315 	cp += usbd_printBCD(cp, bcdDevice);
    316 	cp += sprintf(cp, ", addr %d", dev->address);
    317 	*cp = 0;
    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;
    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 
    988 	DPRINTF(("usbd_new_device bus=%p port=%d depth=%d speed=%d\n",
    989 		 bus, port, depth, speed));
    990 	addr = usbd_getnewaddr(bus);
    991 	if (addr < 0) {
    992 		printf("%s: No free USB addresses, new device ignored.\n",
    993 		       USBDEVNAME(bus->bdev));
    994 		return (USBD_NO_ADDR);
    995 	}
    996 
    997 	dev = malloc(sizeof *dev, M_USB, M_NOWAIT|M_ZERO);
    998 	if (dev == NULL)
    999 		return (USBD_NOMEM);
   1000 
   1001 	dev->bus = bus;
   1002 
   1003 	/* Set up default endpoint handle. */
   1004 	dev->def_ep.edesc = &dev->def_ep_desc;
   1005 
   1006 	/* Set up default endpoint descriptor. */
   1007 	dev->def_ep_desc.bLength = USB_ENDPOINT_DESCRIPTOR_SIZE;
   1008 	dev->def_ep_desc.bDescriptorType = UDESC_ENDPOINT;
   1009 	dev->def_ep_desc.bEndpointAddress = USB_CONTROL_ENDPOINT;
   1010 	dev->def_ep_desc.bmAttributes = UE_CONTROL;
   1011 	USETW(dev->def_ep_desc.wMaxPacketSize, USB_MAX_IPACKET);
   1012 	dev->def_ep_desc.bInterval = 0;
   1013 
   1014 	dev->quirks = &usbd_no_quirk;
   1015 	dev->address = USB_START_ADDR;
   1016 	dev->ddesc.bMaxPacketSize = 0;
   1017 	dev->depth = depth;
   1018 	dev->powersrc = up;
   1019 	dev->myhub = up->parent;
   1020 	for (hub = up->parent;
   1021 	     hub != NULL && hub->speed != USB_SPEED_HIGH;
   1022 	     hub = hub->myhub)
   1023 		;
   1024 	dev->myhighhub = hub;
   1025 	dev->speed = speed;
   1026 	dev->langid = USBD_NOLANG;
   1027 	dev->cookie.cookie = ++usb_cookie_no;
   1028 
   1029 	/* Establish the default pipe. */
   1030 	err = usbd_setup_pipe(dev, 0, &dev->def_ep, USBD_DEFAULT_INTERVAL,
   1031 			      &dev->default_pipe);
   1032 	if (err) {
   1033 		usbd_remove_device(dev, up);
   1034 		return (err);
   1035 	}
   1036 
   1037 	up->device = dev;
   1038 	dd = &dev->ddesc;
   1039 	/* Try a few times in case the device is slow (i.e. outside specs.) */
   1040 	for (i = 0; i < 10; i++) {
   1041 		/* Get the first 8 bytes of the device descriptor. */
   1042 		err = usbd_get_desc(dev, UDESC_DEVICE, 0, USB_MAX_IPACKET, dd);
   1043 		if (!err)
   1044 			break;
   1045 		usbd_delay_ms(dev, 200);
   1046 		if ((i & 3) == 3)
   1047 			usbd_reset_port(up->parent, port, &ps);
   1048 	}
   1049 	if (err) {
   1050 		DPRINTFN(-1, ("usbd_new_device: addr=%d, getting first desc "
   1051 			      "failed\n", addr));
   1052 		usbd_remove_device(dev, up);
   1053 		return (err);
   1054 	}
   1055 
   1056 	if (speed == USB_SPEED_HIGH) {
   1057 		/* Max packet size must be 64 (sec 5.5.3). */
   1058 		if (dd->bMaxPacketSize != USB_2_MAX_CTRL_PACKET) {
   1059 #ifdef DIAGNOSTIC
   1060 			printf("usbd_new_device: addr=%d bad max packet size\n",
   1061 			       addr);
   1062 #endif
   1063 			dd->bMaxPacketSize = USB_2_MAX_CTRL_PACKET;
   1064 		}
   1065 	}
   1066 
   1067 	DPRINTF(("usbd_new_device: adding unit addr=%d, rev=%02x, class=%d, "
   1068 		 "subclass=%d, protocol=%d, maxpacket=%d, len=%d, speed=%d\n",
   1069 		 addr,UGETW(dd->bcdUSB), dd->bDeviceClass, dd->bDeviceSubClass,
   1070 		 dd->bDeviceProtocol, dd->bMaxPacketSize, dd->bLength,
   1071 		 dev->speed));
   1072 
   1073 	if (dd->bDescriptorType != UDESC_DEVICE) {
   1074 		/* Illegal device descriptor */
   1075 		DPRINTFN(-1,("usbd_new_device: illegal descriptor %d\n",
   1076 			     dd->bDescriptorType));
   1077 		usbd_remove_device(dev, up);
   1078 		return (USBD_INVAL);
   1079 	}
   1080 
   1081 	if (dd->bLength < USB_DEVICE_DESCRIPTOR_SIZE) {
   1082 		DPRINTFN(-1,("usbd_new_device: bad length %d\n", dd->bLength));
   1083 		usbd_remove_device(dev, up);
   1084 		return (USBD_INVAL);
   1085 	}
   1086 
   1087 	USETW(dev->def_ep_desc.wMaxPacketSize, dd->bMaxPacketSize);
   1088 
   1089 	err = usbd_reload_device_desc(dev);
   1090 	if (err) {
   1091 		DPRINTFN(-1, ("usbd_new_device: addr=%d, getting full desc "
   1092 			      "failed\n", addr));
   1093 		usbd_remove_device(dev, up);
   1094 		return (err);
   1095 	}
   1096 
   1097 	/* Set the address */
   1098 	err = usbd_set_address(dev, addr);
   1099 	DPRINTFN(5,("usbd_new_device: setting device address=%d\n", addr));
   1100 	if (err) {
   1101 		DPRINTFN(-1,("usb_new_device: set address %d failed\n", addr));
   1102 		err = USBD_SET_ADDR_FAILED;
   1103 		usbd_remove_device(dev, up);
   1104 		return (err);
   1105 	}
   1106 	/* Allow device time to set new address */
   1107 	usbd_delay_ms(dev, USB_SET_ADDRESS_SETTLE);
   1108 
   1109 	dev->address = addr;	/* New device address now */
   1110 	bus->devices[addr] = dev;
   1111 
   1112 	/* Assume 100mA bus powered for now. Changed when configured. */
   1113 	dev->power = USB_MIN_POWER;
   1114 	dev->self_powered = 0;
   1115 
   1116 	DPRINTF(("usbd_new_device: new dev (addr %d), dev=%p, parent=%p\n",
   1117 		 addr, dev, parent));
   1118 
   1119 	usbd_add_dev_event(USB_EVENT_DEVICE_ATTACH, dev);
   1120 
   1121 	err = usbd_probe_and_attach(parent, dev, port, addr);
   1122 	if (err) {
   1123 		usbd_remove_device(dev, up);
   1124 		return (err);
   1125   	}
   1126 
   1127   	return (USBD_NORMAL_COMPLETION);
   1128 }
   1129 
   1130 usbd_status
   1131 usbd_reload_device_desc(usbd_device_handle dev)
   1132 {
   1133 	usbd_status err;
   1134 
   1135 	/* Get the full device descriptor. */
   1136 	err = usbd_get_device_desc(dev, &dev->ddesc);
   1137 	if (err)
   1138 		return (err);
   1139 
   1140 	/* Figure out what's wrong with this device. */
   1141 	dev->quirks = usbd_find_quirk(&dev->ddesc);
   1142 
   1143 	return (USBD_NORMAL_COMPLETION);
   1144 }
   1145 
   1146 void
   1147 usbd_remove_device(usbd_device_handle dev, struct usbd_port *up)
   1148 {
   1149 	DPRINTF(("usbd_remove_device: %p\n", dev));
   1150 
   1151 	if (dev->default_pipe != NULL)
   1152 		usbd_kill_pipe(dev->default_pipe);
   1153 	up->device = 0;
   1154 	dev->bus->devices[dev->address] = 0;
   1155 
   1156 	free(dev, M_USB);
   1157 }
   1158 
   1159 #if defined(__NetBSD__) || defined(__OpenBSD__)
   1160 int
   1161 usbd_print(void *aux, const char *pnp)
   1162 {
   1163 	struct usb_attach_arg *uaa = aux;
   1164 	char devinfo[1024];
   1165 
   1166 	DPRINTFN(15, ("usbd_print dev=%p\n", uaa->device));
   1167 	if (pnp) {
   1168 		if (!uaa->usegeneric)
   1169 			return (QUIET);
   1170 		usbd_devinfo(uaa->device, 1, devinfo);
   1171 		aprint_normal("%s, %s", devinfo, pnp);
   1172 	}
   1173 	if (uaa->port != 0)
   1174 		aprint_normal(" port %d", uaa->port);
   1175 	if (uaa->configno != UHUB_UNK_CONFIGURATION)
   1176 		aprint_normal(" configuration %d", uaa->configno);
   1177 	if (uaa->ifaceno != UHUB_UNK_INTERFACE)
   1178 		aprint_normal(" interface %d", uaa->ifaceno);
   1179 #if 0
   1180 	/*
   1181 	 * It gets very crowded with these locators on the attach line.
   1182 	 * They are not really needed since they are printed in the clear
   1183 	 * by each driver.
   1184 	 */
   1185 	if (uaa->vendor != UHUB_UNK_VENDOR)
   1186 		aprint_normal(" vendor 0x%04x", uaa->vendor);
   1187 	if (uaa->product != UHUB_UNK_PRODUCT)
   1188 		aprint_normal(" product 0x%04x", uaa->product);
   1189 	if (uaa->release != UHUB_UNK_RELEASE)
   1190 		aprint_normal(" release 0x%04x", uaa->release);
   1191 #endif
   1192 	return (UNCONF);
   1193 }
   1194 
   1195 #if defined(__NetBSD__)
   1196 int
   1197 usbd_submatch(struct device *parent, struct cfdata *cf, void *aux)
   1198 {
   1199 #elif defined(__OpenBSD__)
   1200 int
   1201 usbd_submatch(struct device *parent, void *match, void *aux)
   1202 {
   1203 	struct cfdata *cf = match;
   1204 #endif
   1205 	struct usb_attach_arg *uaa = aux;
   1206 
   1207 	DPRINTFN(5,("usbd_submatch port=%d,%d configno=%d,%d "
   1208 	    "ifaceno=%d,%d vendor=%d,%d product=%d,%d release=%d,%d\n",
   1209 	    uaa->port, cf->uhubcf_port,
   1210 	    uaa->configno, cf->uhubcf_configuration,
   1211 	    uaa->ifaceno, cf->uhubcf_interface,
   1212 	    uaa->vendor, cf->uhubcf_vendor,
   1213 	    uaa->product, cf->uhubcf_product,
   1214 	    uaa->release, cf->uhubcf_release));
   1215 	if (uaa->port != 0 &&	/* root hub has port 0, it should match */
   1216 	    ((uaa->port != 0 &&
   1217 	      cf->uhubcf_port != UHUB_UNK_PORT &&
   1218 	      cf->uhubcf_port != uaa->port) ||
   1219 	     (uaa->configno != UHUB_UNK_CONFIGURATION &&
   1220 	      cf->uhubcf_configuration != UHUB_UNK_CONFIGURATION &&
   1221 	      cf->uhubcf_configuration != uaa->configno) ||
   1222 	     (uaa->ifaceno != UHUB_UNK_INTERFACE &&
   1223 	      cf->uhubcf_interface != UHUB_UNK_INTERFACE &&
   1224 	      cf->uhubcf_interface != uaa->ifaceno) ||
   1225 	     (uaa->vendor != UHUB_UNK_VENDOR &&
   1226 	      cf->uhubcf_vendor != UHUB_UNK_VENDOR &&
   1227 	      cf->uhubcf_vendor != uaa->vendor) ||
   1228 	     (uaa->product != UHUB_UNK_PRODUCT &&
   1229 	      cf->uhubcf_product != UHUB_UNK_PRODUCT &&
   1230 	      cf->uhubcf_product != uaa->product) ||
   1231 	     (uaa->release != UHUB_UNK_RELEASE &&
   1232 	      cf->uhubcf_release != UHUB_UNK_RELEASE &&
   1233 	      cf->uhubcf_release != uaa->release)
   1234 	     )
   1235 	   )
   1236 		return 0;
   1237 	if (cf->uhubcf_vendor != UHUB_UNK_VENDOR &&
   1238 	    cf->uhubcf_vendor == uaa->vendor &&
   1239 	    cf->uhubcf_product != UHUB_UNK_PRODUCT &&
   1240 	    cf->uhubcf_product == uaa->product) {
   1241 		/* We have a vendor&product locator match */
   1242 		if (cf->uhubcf_release != UHUB_UNK_RELEASE &&
   1243 		    cf->uhubcf_release == uaa->release)
   1244 			uaa->matchlvl = UMATCH_VENDOR_PRODUCT_REV;
   1245 		else
   1246 			uaa->matchlvl = UMATCH_VENDOR_PRODUCT;
   1247 	} else
   1248 		uaa->matchlvl = 0;
   1249 	return (config_match(parent, cf, aux));
   1250 }
   1251 
   1252 #endif
   1253 
   1254 void
   1255 usbd_fill_deviceinfo(usbd_device_handle dev, struct usb_device_info *di,
   1256 		     int usedev)
   1257 {
   1258 	struct usbd_port *p;
   1259 	int i, err, s;
   1260 
   1261 	di->udi_bus = USBDEVUNIT(dev->bus->bdev);
   1262 	di->udi_addr = dev->address;
   1263 	di->udi_cookie = dev->cookie;
   1264 	usbd_devinfo_vp(dev, di->udi_vendor, di->udi_product, usedev);
   1265 	usbd_printBCD(di->udi_release, UGETW(dev->ddesc.bcdDevice));
   1266 	di->udi_vendorNo = UGETW(dev->ddesc.idVendor);
   1267 	di->udi_productNo = UGETW(dev->ddesc.idProduct);
   1268 	di->udi_releaseNo = UGETW(dev->ddesc.bcdDevice);
   1269 	di->udi_class = dev->ddesc.bDeviceClass;
   1270 	di->udi_subclass = dev->ddesc.bDeviceSubClass;
   1271 	di->udi_protocol = dev->ddesc.bDeviceProtocol;
   1272 	di->udi_config = dev->config;
   1273 	di->udi_power = dev->self_powered ? 0 : dev->power;
   1274 	di->udi_speed = dev->speed;
   1275 
   1276 	if (dev->subdevs != NULL) {
   1277 		for (i = 0; dev->subdevs[i] &&
   1278 			     i < USB_MAX_DEVNAMES; i++) {
   1279 			strncpy(di->udi_devnames[i], USBDEVPTRNAME(dev->subdevs[i]),
   1280 				USB_MAX_DEVNAMELEN);
   1281 			di->udi_devnames[i][USB_MAX_DEVNAMELEN-1] = '\0';
   1282                 }
   1283         } else {
   1284                 i = 0;
   1285         }
   1286         for (/*i is set */; i < USB_MAX_DEVNAMES; i++)
   1287                 di->udi_devnames[i][0] = 0;                 /* empty */
   1288 
   1289 	if (dev->hub) {
   1290 		for (i = 0;
   1291 		     i < sizeof(di->udi_ports) / sizeof(di->udi_ports[0]) &&
   1292 			     i < dev->hub->hubdesc.bNbrPorts;
   1293 		     i++) {
   1294 			p = &dev->hub->ports[i];
   1295 			if (p->device)
   1296 				err = p->device->address;
   1297 			else {
   1298 				s = UGETW(p->status.wPortStatus);
   1299 				if (s & UPS_PORT_ENABLED)
   1300 					err = USB_PORT_ENABLED;
   1301 				else if (s & UPS_SUSPEND)
   1302 					err = USB_PORT_SUSPENDED;
   1303 				else if (s & UPS_PORT_POWER)
   1304 					err = USB_PORT_POWERED;
   1305 				else
   1306 					err = USB_PORT_DISABLED;
   1307 			}
   1308 			di->udi_ports[i] = err;
   1309 		}
   1310 		di->udi_nports = dev->hub->hubdesc.bNbrPorts;
   1311 	} else
   1312 		di->udi_nports = 0;
   1313 }
   1314 
   1315 void
   1316 usb_free_device(usbd_device_handle dev)
   1317 {
   1318 	int ifcidx, nifc;
   1319 
   1320 	if (dev->default_pipe != NULL)
   1321 		usbd_kill_pipe(dev->default_pipe);
   1322 	if (dev->ifaces != NULL) {
   1323 		nifc = dev->cdesc->bNumInterface;
   1324 		for (ifcidx = 0; ifcidx < nifc; ifcidx++)
   1325 			usbd_free_iface_data(dev, ifcidx);
   1326 		free(dev->ifaces, M_USB);
   1327 	}
   1328 	if (dev->cdesc != NULL)
   1329 		free(dev->cdesc, M_USB);
   1330 	if (dev->subdevs != NULL)
   1331 		free(dev->subdevs, M_USB);
   1332 	free(dev, M_USB);
   1333 }
   1334 
   1335 /*
   1336  * The general mechanism for detaching drivers works as follows: Each
   1337  * driver is responsible for maintaining a reference count on the
   1338  * number of outstanding references to its softc (e.g.  from
   1339  * processing hanging in a read or write).  The detach method of the
   1340  * driver decrements this counter and flags in the softc that the
   1341  * driver is dying and then wakes any sleepers.  It then sleeps on the
   1342  * softc.  Each place that can sleep must maintain the reference
   1343  * count.  When the reference count drops to -1 (0 is the normal value
   1344  * of the reference count) the a wakeup on the softc is performed
   1345  * signaling to the detach waiter that all references are gone.
   1346  */
   1347 
   1348 /*
   1349  * Called from process context when we discover that a port has
   1350  * been disconnected.
   1351  */
   1352 void
   1353 usb_disconnect_port(struct usbd_port *up, device_ptr_t parent)
   1354 {
   1355 	usbd_device_handle dev = up->device;
   1356 	char *hubname = USBDEVPTRNAME(parent);
   1357 	int i;
   1358 
   1359 	DPRINTFN(3,("uhub_disconnect: up=%p dev=%p port=%d\n",
   1360 		    up, dev, up->portno));
   1361 
   1362 #ifdef DIAGNOSTIC
   1363 	if (dev == NULL) {
   1364 		printf("usb_disconnect_port: no device\n");
   1365 		return;
   1366 	}
   1367 #endif
   1368 
   1369 	if (dev->subdevs != NULL) {
   1370 		DPRINTFN(3,("usb_disconnect_port: disconnect subdevs\n"));
   1371 		for (i = 0; dev->subdevs[i]; i++) {
   1372 			printf("%s: at %s", USBDEVPTRNAME(dev->subdevs[i]),
   1373 			       hubname);
   1374 			if (up->portno != 0)
   1375 				printf(" port %d", up->portno);
   1376 			printf(" (addr %d) disconnected\n", dev->address);
   1377 			config_detach(dev->subdevs[i], DETACH_FORCE);
   1378 		}
   1379 	}
   1380 
   1381 	usbd_add_dev_event(USB_EVENT_DEVICE_DETACH, dev);
   1382 	dev->bus->devices[dev->address] = NULL;
   1383 	up->device = NULL;
   1384 	usb_free_device(dev);
   1385 }
   1386 
   1387 #ifdef __OpenBSD__
   1388 void *usb_realloc(void *p, u_int size, int pool, int flags)
   1389 {
   1390 	void *q;
   1391 
   1392 	q = malloc(size, pool, flags);
   1393 	if (q == NULL)
   1394 		return (NULL);
   1395 	bcopy(p, q, size);
   1396 	free(p, pool);
   1397 	return (q);
   1398 }
   1399 #endif
   1400