xref: /netbsd-src/sys/dev/usb/usb_subr.c (revision 3cec974c61d7fac0a37c0377723a33214a458c8b)
1 /*	$NetBSD: usb_subr.c,v 1.85 2001/01/21 02:34:34 augustss 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@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/param.h>
42 #include <sys/systm.h>
43 #include <sys/kernel.h>
44 #include <sys/malloc.h>
45 #if defined(__NetBSD__) || defined(__OpenBSD__)
46 #include <sys/device.h>
47 #include <sys/select.h>
48 #elif defined(__FreeBSD__)
49 #include <sys/module.h>
50 #include <sys/bus.h>
51 #endif
52 #include <sys/proc.h>
53 
54 #include <machine/bus.h>
55 
56 #include <dev/usb/usb.h>
57 
58 #include <dev/usb/usbdi.h>
59 #include <dev/usb/usbdi_util.h>
60 #include <dev/usb/usbdivar.h>
61 #include <dev/usb/usbdevs.h>
62 #include <dev/usb/usb_quirks.h>
63 
64 #if defined(__FreeBSD__)
65 #include <machine/clock.h>
66 #define delay(d)         DELAY(d)
67 #endif
68 
69 #ifdef USB_DEBUG
70 #define DPRINTF(x)	if (usbdebug) logprintf x
71 #define DPRINTFN(n,x)	if (usbdebug>(n)) logprintf x
72 extern int usbdebug;
73 #else
74 #define DPRINTF(x)
75 #define DPRINTFN(n,x)
76 #endif
77 
78 Static usbd_status usbd_set_config(usbd_device_handle, int);
79 Static void usbd_devinfo_vp(usbd_device_handle, char *, char *, int);
80 Static char *usbd_get_string(usbd_device_handle, int, char *);
81 Static int usbd_getnewaddr(usbd_bus_handle bus);
82 #if defined(__NetBSD__)
83 Static int usbd_print(void *aux, const char *pnp);
84 Static int usbd_submatch(device_ptr_t, struct cfdata *cf, void *);
85 #elif defined(__OpenBSD__)
86 Static int usbd_print(void *aux, const char *pnp);
87 Static int usbd_submatch(device_ptr_t, void *, void *);
88 #endif
89 Static void usbd_free_iface_data(usbd_device_handle dev, int ifcno);
90 Static void usbd_kill_pipe(usbd_pipe_handle);
91 Static usbd_status usbd_probe_and_attach(device_ptr_t parent,
92 				 usbd_device_handle dev, int port, int addr);
93 
94 Static u_int32_t usb_cookie_no = 0;
95 
96 #ifdef USBVERBOSE
97 typedef u_int16_t usb_vendor_id_t;
98 typedef u_int16_t usb_product_id_t;
99 
100 /*
101  * Descriptions of of known vendors and devices ("products").
102  */
103 struct usb_knowndev {
104 	usb_vendor_id_t		vendor;
105 	usb_product_id_t	product;
106 	int			flags;
107 	char			*vendorname, *productname;
108 };
109 #define	USB_KNOWNDEV_NOPROD	0x01		/* match on vendor only */
110 
111 #include <dev/usb/usbdevs_data.h>
112 #endif /* USBVERBOSE */
113 
114 Static const char * const usbd_error_strs[] = {
115 	"NORMAL_COMPLETION",
116 	"IN_PROGRESS",
117 	"PENDING_REQUESTS",
118 	"NOT_STARTED",
119 	"INVAL",
120 	"NOMEM",
121 	"CANCELLED",
122 	"BAD_ADDRESS",
123 	"IN_USE",
124 	"NO_ADDR",
125 	"SET_ADDR_FAILED",
126 	"NO_POWER",
127 	"TOO_DEEP",
128 	"IOERROR",
129 	"NOT_CONFIGURED",
130 	"TIMEOUT",
131 	"SHORT_XFER",
132 	"STALLED",
133 	"INTERRUPTED",
134 	"XXX",
135 };
136 
137 const char *
138 usbd_errstr(usbd_status err)
139 {
140 	static char buffer[5];
141 
142 	if (err < USBD_ERROR_MAX) {
143 		return usbd_error_strs[err];
144 	} else {
145 		snprintf(buffer, sizeof buffer, "%d", err);
146 		return buffer;
147 	}
148 }
149 
150 usbd_status
151 usbd_get_string_desc(usbd_device_handle dev, int sindex, int langid,
152 		     usb_string_descriptor_t *sdesc)
153 {
154 	usb_device_request_t req;
155 	usbd_status err;
156 
157 	req.bmRequestType = UT_READ_DEVICE;
158 	req.bRequest = UR_GET_DESCRIPTOR;
159 	USETW2(req.wValue, UDESC_STRING, sindex);
160 	USETW(req.wIndex, langid);
161 	USETW(req.wLength, 1);	/* only size byte first */
162 	err = usbd_do_request(dev, &req, sdesc);
163 	if (err)
164 		return (err);
165 	USETW(req.wLength, sdesc->bLength);	/* the whole string */
166 	return (usbd_do_request(dev, &req, sdesc));
167 }
168 
169 char *
170 usbd_get_string(usbd_device_handle dev, int si, char *buf)
171 {
172 	int swap = dev->quirks->uq_flags & UQ_SWAP_UNICODE;
173 	usb_string_descriptor_t us;
174 	char *s;
175 	int i, n;
176 	u_int16_t c;
177 	usbd_status err;
178 
179 	if (si == 0)
180 		return (0);
181 	if (dev->quirks->uq_flags & UQ_NO_STRINGS)
182 		return (0);
183 	if (dev->langid == USBD_NOLANG) {
184 		/* Set up default language */
185 		err = usbd_get_string_desc(dev, USB_LANGUAGE_TABLE, 0, &us);
186 		if (err || us.bLength < 4) {
187 			dev->langid = 0; /* Well, just pick English then */
188 		} else {
189 			/* Pick the first language as the default. */
190 			dev->langid = UGETW(us.bString[0]);
191 		}
192 	}
193 	err = usbd_get_string_desc(dev, si, dev->langid, &us);
194 	if (err)
195 		return (0);
196 	s = buf;
197 	n = us.bLength / 2 - 1;
198 	for (i = 0; i < n; i++) {
199 		c = UGETW(us.bString[i]);
200 		/* Convert from Unicode, handle buggy strings. */
201 		if ((c & 0xff00) == 0)
202 			*s++ = c;
203 		else if ((c & 0x00ff) == 0 && swap)
204 			*s++ = c >> 8;
205 		else
206 			*s++ = '?';
207 	}
208 	*s++ = 0;
209 	return (buf);
210 }
211 
212 static void
213 usbd_trim_spaces(char *p)
214 {
215 	char *q, *e;
216 
217 	if (p == NULL)
218 		return;
219 	q = e = p;
220 	while (*q == ' ')	/* skip leading spaces */
221 		q++;
222 	while ((*p = *q++))	/* copy string */
223 		if (*p++ != ' ') /* remember last non-space */
224 			e = p;
225 	*e = 0;			/* kill trailing spaces */
226 }
227 
228 void
229 usbd_devinfo_vp(usbd_device_handle dev, char *v, char *p, int usedev)
230 {
231 	usb_device_descriptor_t *udd = &dev->ddesc;
232 	char *vendor = 0, *product = 0;
233 #ifdef USBVERBOSE
234 	const struct usb_knowndev *kdp;
235 #endif
236 
237 	if (dev == NULL) {
238 		v[0] = p[0] = '\0';
239 		return;
240 	}
241 
242 	if (usedev) {
243 		vendor = usbd_get_string(dev, udd->iManufacturer, v);
244 		usbd_trim_spaces(vendor);
245 		product = usbd_get_string(dev, udd->iProduct, p);
246 		usbd_trim_spaces(product);
247 	} else {
248 		vendor = NULL;
249 		product = NULL;
250 	}
251 #ifdef USBVERBOSE
252 	if (vendor == NULL || product == NULL) {
253 		for(kdp = usb_knowndevs;
254 		    kdp->vendorname != NULL;
255 		    kdp++) {
256 			if (kdp->vendor == UGETW(udd->idVendor) &&
257 			    (kdp->product == UGETW(udd->idProduct) ||
258 			     (kdp->flags & USB_KNOWNDEV_NOPROD) != 0))
259 				break;
260 		}
261 		if (kdp->vendorname != NULL) {
262 			if (vendor == NULL)
263 			    vendor = kdp->vendorname;
264 			if (product == NULL)
265 			    product = (kdp->flags & USB_KNOWNDEV_NOPROD) == 0 ?
266 				kdp->productname : NULL;
267 		}
268 	}
269 #endif
270 	if (vendor != NULL && *vendor)
271 		strcpy(v, vendor);
272 	else
273 		sprintf(v, "vendor 0x%04x", UGETW(udd->idVendor));
274 	if (product != NULL && *product)
275 		strcpy(p, product);
276 	else
277 		sprintf(p, "product 0x%04x", UGETW(udd->idProduct));
278 }
279 
280 int
281 usbd_printBCD(char *cp, int bcd)
282 {
283 	return (sprintf(cp, "%x.%02x", bcd >> 8, bcd & 0xff));
284 }
285 
286 void
287 usbd_devinfo(usbd_device_handle dev, int showclass, char *cp)
288 {
289 	usb_device_descriptor_t *udd = &dev->ddesc;
290 	char vendor[USB_MAX_STRING_LEN];
291 	char product[USB_MAX_STRING_LEN];
292 	int bcdDevice, bcdUSB;
293 
294 	usbd_devinfo_vp(dev, vendor, product, 1);
295 	cp += sprintf(cp, "%s %s", vendor, product);
296 	if (showclass)
297 		cp += sprintf(cp, ", class %d/%d",
298 			      udd->bDeviceClass, udd->bDeviceSubClass);
299 	bcdUSB = UGETW(udd->bcdUSB);
300 	bcdDevice = UGETW(udd->bcdDevice);
301 	cp += sprintf(cp, ", rev ");
302 	cp += usbd_printBCD(cp, bcdUSB);
303 	*cp++ = '/';
304 	cp += usbd_printBCD(cp, bcdDevice);
305 	cp += sprintf(cp, ", addr %d", dev->address);
306 	*cp = 0;
307 }
308 
309 /* Delay for a certain number of ms */
310 void
311 usb_delay_ms(usbd_bus_handle bus, u_int ms)
312 {
313 	/* Wait at least two clock ticks so we know the time has passed. */
314 	if (bus->use_polling || cold)
315 		delay((ms+1) * 1000);
316 	else
317 		tsleep(&ms, PRIBIO, "usbdly", (ms*hz+999)/1000 + 1);
318 }
319 
320 /* Delay given a device handle. */
321 void
322 usbd_delay_ms(usbd_device_handle dev, u_int ms)
323 {
324 	usb_delay_ms(dev->bus, ms);
325 }
326 
327 usbd_status
328 usbd_reset_port(usbd_device_handle dev, int port, usb_port_status_t *ps)
329 {
330 	usb_device_request_t req;
331 	usbd_status err;
332 	int n;
333 
334 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
335 	req.bRequest = UR_SET_FEATURE;
336 	USETW(req.wValue, UHF_PORT_RESET);
337 	USETW(req.wIndex, port);
338 	USETW(req.wLength, 0);
339 	err = usbd_do_request(dev, &req, 0);
340 	DPRINTFN(1,("usbd_reset_port: port %d reset done, error=%s\n",
341 		    port, usbd_errstr(err)));
342 	if (err)
343 		return (err);
344 	n = 10;
345 	do {
346 		/* Wait for device to recover from reset. */
347 		usbd_delay_ms(dev, USB_PORT_RESET_DELAY);
348 		err = usbd_get_port_status(dev, port, ps);
349 		if (err) {
350 			DPRINTF(("usbd_reset_port: get status failed %d\n",
351 				 err));
352 			return (err);
353 		}
354 	} while ((UGETW(ps->wPortChange) & UPS_C_PORT_RESET) == 0 && --n > 0);
355 	if (n == 0)
356 		return (USBD_TIMEOUT);
357 	err = usbd_clear_port_feature(dev, port, UHF_C_PORT_RESET);
358 #ifdef USB_DEBUG
359 	if (err)
360 		DPRINTF(("usbd_reset_port: clear port feature failed %d\n",
361 			 err));
362 #endif
363 
364 	/* Wait for the device to recover from reset. */
365 	usbd_delay_ms(dev, USB_PORT_RESET_RECOVERY);
366 	return (err);
367 }
368 
369 usb_interface_descriptor_t *
370 usbd_find_idesc(usb_config_descriptor_t *cd, int ifaceidx, int altidx)
371 {
372 	char *p = (char *)cd;
373 	char *end = p + UGETW(cd->wTotalLength);
374 	usb_interface_descriptor_t *d;
375 	int curidx, lastidx, curaidx = 0;
376 
377 	for (curidx = lastidx = -1; p < end; ) {
378 		d = (usb_interface_descriptor_t *)p;
379 		DPRINTFN(4,("usbd_find_idesc: idx=%d(%d) altidx=%d(%d) len=%d "
380 			    "type=%d\n",
381 			    ifaceidx, curidx, altidx, curaidx,
382 			    d->bLength, d->bDescriptorType));
383 		if (d->bLength == 0) /* bad descriptor */
384 			break;
385 		p += d->bLength;
386 		if (p <= end && d->bDescriptorType == UDESC_INTERFACE) {
387 			if (d->bInterfaceNumber != lastidx) {
388 				lastidx = d->bInterfaceNumber;
389 				curidx++;
390 				curaidx = 0;
391 			} else
392 				curaidx++;
393 			if (ifaceidx == curidx && altidx == curaidx)
394 				return (d);
395 		}
396 	}
397 	return (NULL);
398 }
399 
400 usb_endpoint_descriptor_t *
401 usbd_find_edesc(usb_config_descriptor_t *cd, int ifaceidx, int altidx,
402 		int endptidx)
403 {
404 	char *p = (char *)cd;
405 	char *end = p + UGETW(cd->wTotalLength);
406 	usb_interface_descriptor_t *d;
407 	usb_endpoint_descriptor_t *e;
408 	int curidx;
409 
410 	d = usbd_find_idesc(cd, ifaceidx, altidx);
411 	if (d == NULL)
412 		return (NULL);
413 	if (endptidx >= d->bNumEndpoints) /* quick exit */
414 		return (NULL);
415 
416 	curidx = -1;
417 	for (p = (char *)d + d->bLength; p < end; ) {
418 		e = (usb_endpoint_descriptor_t *)p;
419 		if (e->bLength == 0) /* bad descriptor */
420 			break;
421 		p += e->bLength;
422 		if (p <= end && e->bDescriptorType == UDESC_INTERFACE)
423 			return (NULL);
424 		if (p <= end && e->bDescriptorType == UDESC_ENDPOINT) {
425 			curidx++;
426 			if (curidx == endptidx)
427 				return (e);
428 		}
429 	}
430 	return (NULL);
431 }
432 
433 usbd_status
434 usbd_fill_iface_data(usbd_device_handle dev, int ifaceidx, int altidx)
435 {
436 	usbd_interface_handle ifc = &dev->ifaces[ifaceidx];
437 	usb_interface_descriptor_t *idesc;
438 	char *p, *end;
439 	int endpt, nendpt;
440 
441 	DPRINTFN(4,("usbd_fill_iface_data: ifaceidx=%d altidx=%d\n",
442 		    ifaceidx, altidx));
443 	idesc = usbd_find_idesc(dev->cdesc, ifaceidx, altidx);
444 	if (idesc == NULL)
445 		return (USBD_INVAL);
446 	ifc->device = dev;
447 	ifc->idesc = idesc;
448 	ifc->index = ifaceidx;
449 	ifc->altindex = altidx;
450 	nendpt = ifc->idesc->bNumEndpoints;
451 	DPRINTFN(4,("usbd_fill_iface_data: found idesc nendpt=%d\n", nendpt));
452 	if (nendpt != 0) {
453 		ifc->endpoints = malloc(nendpt * sizeof(struct usbd_endpoint),
454 					M_USB, M_NOWAIT);
455 		if (ifc->endpoints == NULL)
456 			return (USBD_NOMEM);
457 	} else
458 		ifc->endpoints = NULL;
459 	ifc->priv = NULL;
460 	p = (char *)ifc->idesc + ifc->idesc->bLength;
461 	end = (char *)dev->cdesc + UGETW(dev->cdesc->wTotalLength);
462 #define ed ((usb_endpoint_descriptor_t *)p)
463 	for (endpt = 0; endpt < nendpt; endpt++) {
464 		DPRINTFN(10,("usbd_fill_iface_data: endpt=%d\n", endpt));
465 		for (; p < end; p += ed->bLength) {
466 			ed = (usb_endpoint_descriptor_t *)p;
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 	return ((*cf->cf_attach->ca_match)(parent, cf, aux));
1170 }
1171 
1172 #endif
1173 
1174 void
1175 usbd_fill_deviceinfo(usbd_device_handle dev, struct usb_device_info *di,
1176 		     int usedev)
1177 {
1178 	struct usbd_port *p;
1179 	int i, err, s;
1180 
1181 	di->bus = USBDEVUNIT(dev->bus->bdev);
1182 	di->addr = dev->address;
1183 	di->cookie = dev->cookie;
1184 	usbd_devinfo_vp(dev, di->vendor, di->product, usedev);
1185 	usbd_printBCD(di->release, UGETW(dev->ddesc.bcdDevice));
1186 	di->vendorNo = UGETW(dev->ddesc.idVendor);
1187 	di->productNo = UGETW(dev->ddesc.idProduct);
1188 	di->releaseNo = UGETW(dev->ddesc.bcdDevice);
1189 	di->class = dev->ddesc.bDeviceClass;
1190 	di->subclass = dev->ddesc.bDeviceSubClass;
1191 	di->protocol = dev->ddesc.bDeviceProtocol;
1192 	di->config = dev->config;
1193 	di->power = dev->self_powered ? 0 : dev->power;
1194 	di->lowspeed = dev->lowspeed;
1195 
1196 	if (dev->subdevs != NULL) {
1197 		for (i = 0; dev->subdevs[i] &&
1198 			     i < USB_MAX_DEVNAMES; i++) {
1199 			strncpy(di->devnames[i], USBDEVPTRNAME(dev->subdevs[i]),
1200 				USB_MAX_DEVNAMELEN);
1201 			di->devnames[i][USB_MAX_DEVNAMELEN-1] = '\0';
1202                 }
1203         } else {
1204                 i = 0;
1205         }
1206         for (/*i is set */; i < USB_MAX_DEVNAMES; i++)
1207                 di->devnames[i][0] = 0;                 /* empty */
1208 
1209 	if (dev->hub) {
1210 		for (i = 0;
1211 		     i < sizeof(di->ports) / sizeof(di->ports[0]) &&
1212 			     i < dev->hub->hubdesc.bNbrPorts;
1213 		     i++) {
1214 			p = &dev->hub->ports[i];
1215 			if (p->device)
1216 				err = p->device->address;
1217 			else {
1218 				s = UGETW(p->status.wPortStatus);
1219 				if (s & UPS_PORT_ENABLED)
1220 					err = USB_PORT_ENABLED;
1221 				else if (s & UPS_SUSPEND)
1222 					err = USB_PORT_SUSPENDED;
1223 				else if (s & UPS_PORT_POWER)
1224 					err = USB_PORT_POWERED;
1225 				else
1226 					err = USB_PORT_DISABLED;
1227 			}
1228 			di->ports[i] = err;
1229 		}
1230 		di->nports = dev->hub->hubdesc.bNbrPorts;
1231 	} else
1232 		di->nports = 0;
1233 }
1234 
1235 void
1236 usb_free_device(usbd_device_handle dev)
1237 {
1238 	int ifcidx, nifc;
1239 
1240 	if (dev->default_pipe != NULL)
1241 		usbd_kill_pipe(dev->default_pipe);
1242 	if (dev->ifaces != NULL) {
1243 		nifc = dev->cdesc->bNumInterface;
1244 		for (ifcidx = 0; ifcidx < nifc; ifcidx++)
1245 			usbd_free_iface_data(dev, ifcidx);
1246 		free(dev->ifaces, M_USB);
1247 	}
1248 	if (dev->cdesc != NULL)
1249 		free(dev->cdesc, M_USB);
1250 	if (dev->subdevs != NULL)
1251 		free(dev->subdevs, M_USB);
1252 	free(dev, M_USB);
1253 }
1254 
1255 /*
1256  * The general mechanism for detaching drivers works as follows: Each
1257  * driver is responsible for maintaining a reference count on the
1258  * number of outstanding references to its softc (e.g.  from
1259  * processing hanging in a read or write).  The detach method of the
1260  * driver decrements this counter and flags in the softc that the
1261  * driver is dying and then wakes any sleepers.  It then sleeps on the
1262  * softc.  Each place that can sleep must maintain the reference
1263  * count.  When the reference count drops to -1 (0 is the normal value
1264  * of the reference count) the a wakeup on the softc is performed
1265  * signaling to the detach waiter that all references are gone.
1266  */
1267 
1268 /*
1269  * Called from process context when we discover that a port has
1270  * been disconnected.
1271  */
1272 void
1273 usb_disconnect_port(struct usbd_port *up, device_ptr_t parent)
1274 {
1275 	usbd_device_handle dev = up->device;
1276 	char *hubname = USBDEVPTRNAME(parent);
1277 	int i;
1278 
1279 	DPRINTFN(3,("uhub_disconnect: up=%p dev=%p port=%d\n",
1280 		    up, dev, up->portno));
1281 
1282 #ifdef DIAGNOSTIC
1283 	if (dev == NULL) {
1284 		printf("usb_disconnect_port: no device\n");
1285 		return;
1286 	}
1287 #endif
1288 
1289 	if (dev->subdevs != NULL) {
1290 		DPRINTFN(3,("usb_disconnect_port: disconnect subdevs\n"));
1291 		for (i = 0; dev->subdevs[i]; i++) {
1292 			printf("%s: at %s", USBDEVPTRNAME(dev->subdevs[i]),
1293 			       hubname);
1294 			if (up->portno != 0)
1295 				printf(" port %d", up->portno);
1296 			printf(" (addr %d) disconnected\n", dev->address);
1297 #if defined(__NetBSD__) || defined(__OpenBSD__)
1298 			config_detach(dev->subdevs[i], DETACH_FORCE);
1299 #elif defined(__FreeBSD__)
1300                         device_delete_child(device_get_parent(dev->subdevs[i]),
1301 					    dev->subdevs[i]);
1302 #endif
1303 
1304 		}
1305 	}
1306 
1307 	usbd_add_dev_event(USB_EVENT_DEVICE_DETACH, dev);
1308 	dev->bus->devices[dev->address] = NULL;
1309 	up->device = NULL;
1310 	usb_free_device(dev);
1311 }
1312 
1313 #ifdef __OpenBSD__
1314 void *usb_realloc(void *p, u_int size, int pool, int flags)
1315 {
1316 	void *q;
1317 
1318 	q = malloc(size, pool, flags);
1319 	if (q == NULL)
1320 		return (NULL);
1321 	bcopy(p, q, size);
1322 	free(p, pool);
1323 	return (q);
1324 }
1325 #endif
1326