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