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