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