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