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