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