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