xref: /netbsd-src/sys/dev/usb/usb_subr.c (revision b757af438b42b93f8c6571f026d8b8ef3eaf5fc9)
1 /*	$NetBSD: usb_subr.c,v 1.180 2011/06/09 19:08:33 matt 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.180 2011/06/09 19:08:33 matt 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 		ifc->endpoints[endpt].datatoggle = 0;
499 		p += ed->bLength;
500 	}
501 #undef ed
502 	LIST_INIT(&ifc->pipes);
503 	return (USBD_NORMAL_COMPLETION);
504 
505  bad:
506 	if (ifc->endpoints != NULL) {
507 		free(ifc->endpoints, M_USB);
508 		ifc->endpoints = NULL;
509 	}
510 	return (USBD_INVAL);
511 }
512 
513 void
514 usbd_free_iface_data(usbd_device_handle dev, int ifcno)
515 {
516 	usbd_interface_handle ifc = &dev->ifaces[ifcno];
517 	if (ifc->endpoints)
518 		free(ifc->endpoints, M_USB);
519 }
520 
521 Static usbd_status
522 usbd_set_config(usbd_device_handle dev, int conf)
523 {
524 	usb_device_request_t req;
525 
526 	req.bmRequestType = UT_WRITE_DEVICE;
527 	req.bRequest = UR_SET_CONFIG;
528 	USETW(req.wValue, conf);
529 	USETW(req.wIndex, 0);
530 	USETW(req.wLength, 0);
531 	return (usbd_do_request(dev, &req, 0));
532 }
533 
534 usbd_status
535 usbd_set_config_no(usbd_device_handle dev, int no, int msg)
536 {
537 	int index;
538 	usb_config_descriptor_t cd;
539 	usbd_status err;
540 
541 	if (no == USB_UNCONFIG_NO)
542 		return (usbd_set_config_index(dev, USB_UNCONFIG_INDEX, msg));
543 
544 	DPRINTFN(5,("usbd_set_config_no: %d\n", no));
545 	/* Figure out what config index to use. */
546 	for (index = 0; index < dev->ddesc.bNumConfigurations; index++) {
547 		err = usbd_get_config_desc(dev, index, &cd);
548 		if (err)
549 			return (err);
550 		if (cd.bConfigurationValue == no)
551 			return (usbd_set_config_index(dev, index, msg));
552 	}
553 	return (USBD_INVAL);
554 }
555 
556 usbd_status
557 usbd_set_config_index(usbd_device_handle dev, int index, int msg)
558 {
559 	usb_config_descriptor_t cd, *cdp;
560 	usbd_status err;
561 	int i, ifcidx, nifc, len, selfpowered, power;
562 
563 	DPRINTFN(5,("usbd_set_config_index: dev=%p index=%d\n", dev, index));
564 
565 	if (index >= dev->ddesc.bNumConfigurations &&
566 	    index != USB_UNCONFIG_INDEX) {
567 		/* panic? */
568 		printf("usbd_set_config_index: illegal index\n");
569 		return (USBD_INVAL);
570 	}
571 
572 	/* XXX check that all interfaces are idle */
573 	if (dev->config != USB_UNCONFIG_NO) {
574 		DPRINTF(("usbd_set_config_index: free old config\n"));
575 		/* Free all configuration data structures. */
576 		nifc = dev->cdesc->bNumInterface;
577 		for (ifcidx = 0; ifcidx < nifc; ifcidx++)
578 			usbd_free_iface_data(dev, ifcidx);
579 		free(dev->ifaces, M_USB);
580 		free(dev->cdesc, M_USB);
581 		dev->ifaces = NULL;
582 		dev->cdesc = NULL;
583 		dev->config = USB_UNCONFIG_NO;
584 	}
585 
586 	if (index == USB_UNCONFIG_INDEX) {
587 		/* We are unconfiguring the device, so leave unallocated. */
588 		DPRINTF(("usbd_set_config_index: set config 0\n"));
589 		err = usbd_set_config(dev, USB_UNCONFIG_NO);
590 		if (err) {
591 			DPRINTF(("usbd_set_config_index: setting config=0 "
592 				 "failed, error=%s\n", usbd_errstr(err)));
593 		}
594 		return (err);
595 	}
596 
597 	/* Get the short descriptor. */
598 	err = usbd_get_config_desc(dev, index, &cd);
599 	if (err) {
600 		DPRINTF(("usbd_set_config_index: get_config_desc=%d\n", err));
601 		return (err);
602 	}
603 	len = UGETW(cd.wTotalLength);
604 	cdp = malloc(len, M_USB, M_NOWAIT);
605 	if (cdp == NULL)
606 		return (USBD_NOMEM);
607 
608 	/* Get the full descriptor.  Try a few times for slow devices. */
609 	for (i = 0; i < 3; i++) {
610 		err = usbd_get_desc(dev, UDESC_CONFIG, index, len, cdp);
611 		if (!err)
612 			break;
613 		usbd_delay_ms(dev, 200);
614 	}
615 	if (err) {
616 		DPRINTF(("usbd_set_config_index: get_desc=%d\n", err));
617 		goto bad;
618 	}
619 	if (cdp->bDescriptorType != UDESC_CONFIG) {
620 		DPRINTFN(-1,("usbd_set_config_index: bad desc %d\n",
621 			     cdp->bDescriptorType));
622 		err = USBD_INVAL;
623 		goto bad;
624 	}
625 
626 	/*
627 	 * Figure out if the device is self or bus powered.
628 	 */
629 #if 0 /* XXX various devices don't report the power state correctly */
630 	selfpowered = 0;
631 	err = usbd_get_device_status(dev, &ds);
632 	if (!err && (UGETW(ds.wStatus) & UDS_SELF_POWERED))
633 		selfpowered = 1;
634 #endif
635 	/*
636 	 * Use the power state in the configuration we are going
637 	 * to set. This doesn't necessarily reflect the actual
638 	 * power state of the device; the driver can control this
639 	 * by choosing the appropriate configuration.
640 	 */
641 	selfpowered = !!(cdp->bmAttributes & UC_SELF_POWERED);
642 
643 	DPRINTF(("usbd_set_config_index: (addr %d) cno=%d attr=0x%02x, "
644 		 "selfpowered=%d, power=%d\n",
645 		 cdp->bConfigurationValue, dev->address, cdp->bmAttributes,
646 		 selfpowered, cdp->bMaxPower * 2));
647 
648 	/* Check if we have enough power. */
649 #if 0 /* this is a no-op, see above */
650 	if ((cdp->bmAttributes & UC_SELF_POWERED) && !selfpowered) {
651 		if (msg)
652 			printf("%s: device addr %d (config %d): "
653 				 "can't set self powered configuration\n",
654 			       device_xname(dev->bus->bdev), dev->address,
655 			       cdp->bConfigurationValue);
656 		err = USBD_NO_POWER;
657 		goto bad;
658 	}
659 #endif
660 #ifdef USB_DEBUG
661 	if (dev->powersrc == NULL) {
662 		DPRINTF(("usbd_set_config_index: No power source?\n"));
663 		err = USBD_IOERROR;
664 		goto bad;
665 	}
666 #endif
667 	power = cdp->bMaxPower * 2;
668 	if (power > dev->powersrc->power) {
669 		DPRINTF(("power exceeded %d %d\n", power,dev->powersrc->power));
670 		/* XXX print nicer message. */
671 		if (msg)
672 			printf("%s: device addr %d (config %d) exceeds power "
673 				 "budget, %d mA > %d mA\n",
674 			       device_xname(dev->bus->usbctl), dev->address,
675 			       cdp->bConfigurationValue,
676 			       power, dev->powersrc->power);
677 		err = USBD_NO_POWER;
678 		goto bad;
679 	}
680 	dev->power = power;
681 	dev->self_powered = selfpowered;
682 
683 	/* Set the actual configuration value. */
684 	DPRINTF(("usbd_set_config_index: set config %d\n",
685 		 cdp->bConfigurationValue));
686 	err = usbd_set_config(dev, cdp->bConfigurationValue);
687 	if (err) {
688 		DPRINTF(("usbd_set_config_index: setting config=%d failed, "
689 			 "error=%s\n",
690 			 cdp->bConfigurationValue, usbd_errstr(err)));
691 		goto bad;
692 	}
693 
694 	/* Allocate and fill interface data. */
695 	nifc = cdp->bNumInterface;
696 	dev->ifaces = malloc(nifc * sizeof(struct usbd_interface),
697 			     M_USB, M_NOWAIT);
698 	if (dev->ifaces == NULL) {
699 		err = USBD_NOMEM;
700 		goto bad;
701 	}
702 	DPRINTFN(5,("usbd_set_config_index: dev=%p cdesc=%p\n", dev, cdp));
703 	dev->cdesc = cdp;
704 	dev->config = cdp->bConfigurationValue;
705 	for (ifcidx = 0; ifcidx < nifc; ifcidx++) {
706 		err = usbd_fill_iface_data(dev, ifcidx, 0);
707 		if (err) {
708 			while (--ifcidx >= 0)
709 				usbd_free_iface_data(dev, ifcidx);
710 			goto bad;
711 		}
712 	}
713 
714 	return (USBD_NORMAL_COMPLETION);
715 
716  bad:
717 	free(cdp, M_USB);
718 	return (err);
719 }
720 
721 /* XXX add function for alternate settings */
722 
723 usbd_status
724 usbd_setup_pipe(usbd_device_handle dev, usbd_interface_handle iface,
725 		struct usbd_endpoint *ep, int ival, usbd_pipe_handle *pipe)
726 {
727 	usbd_pipe_handle p;
728 	usbd_status err;
729 
730 	DPRINTFN(1,("usbd_setup_pipe: dev=%p iface=%p ep=%p pipe=%p\n",
731 		    dev, iface, ep, pipe));
732 	p = malloc(dev->bus->pipe_size, M_USB, M_NOWAIT);
733 	if (p == NULL)
734 		return (USBD_NOMEM);
735 	p->device = dev;
736 	p->iface = iface;
737 	p->endpoint = ep;
738 	ep->refcnt++;
739 	p->refcnt = 1;
740 	p->intrxfer = 0;
741 	p->running = 0;
742 	p->aborting = 0;
743 	p->repeat = 0;
744 	p->interval = ival;
745 	SIMPLEQ_INIT(&p->queue);
746 	err = dev->bus->methods->open_pipe(p);
747 	if (err) {
748 		DPRINTFN(-1,("usbd_setup_pipe: endpoint=0x%x failed, error="
749 			 "%s\n",
750 			 ep->edesc->bEndpointAddress, usbd_errstr(err)));
751 		free(p, M_USB);
752 		return (err);
753 	}
754 	*pipe = p;
755 	return (USBD_NORMAL_COMPLETION);
756 }
757 
758 /* Abort the device control pipe. */
759 void
760 usbd_kill_pipe(usbd_pipe_handle pipe)
761 {
762 	usbd_abort_pipe(pipe);
763 	pipe->methods->close(pipe);
764 	pipe->endpoint->refcnt--;
765 	free(pipe, M_USB);
766 }
767 
768 int
769 usbd_getnewaddr(usbd_bus_handle bus)
770 {
771 	int addr;
772 
773 	for (addr = 1; addr < USB_MAX_DEVICES; addr++)
774 		if (bus->devices[addr] == 0)
775 			return (addr);
776 	return (-1);
777 }
778 
779 usbd_status
780 usbd_attach_roothub(device_t parent, usbd_device_handle dev)
781 {
782 	struct usb_attach_arg uaa;
783 	usb_device_descriptor_t *dd = &dev->ddesc;
784 	device_t dv;
785 
786 	uaa.device = dev;
787 	uaa.usegeneric = 0;
788 	uaa.port = 0;
789 	uaa.vendor = UGETW(dd->idVendor);
790 	uaa.product = UGETW(dd->idProduct);
791 	uaa.release = UGETW(dd->bcdDevice);
792 	uaa.class = dd->bDeviceClass;
793 	uaa.subclass = dd->bDeviceSubClass;
794 	uaa.proto = dd->bDeviceProtocol;
795 
796 	dv = config_found_ia(parent, "usbroothubif", &uaa, 0);
797 	if (dv) {
798 		dev->subdevs = malloc(sizeof dv, M_USB, M_NOWAIT);
799 		if (dev->subdevs == NULL)
800 			return (USBD_NOMEM);
801 		dev->subdevs[0] = dv;
802 		dev->subdevlen = 1;
803 	}
804 	return (USBD_NORMAL_COMPLETION);
805 }
806 
807 static usbd_status
808 usbd_attachwholedevice(device_t parent, usbd_device_handle dev, int port,
809 	int usegeneric)
810 {
811 	struct usb_attach_arg uaa;
812 	usb_device_descriptor_t *dd = &dev->ddesc;
813 	device_t dv;
814 	int dlocs[USBDEVIFCF_NLOCS];
815 
816 	uaa.device = dev;
817 	uaa.usegeneric = usegeneric;
818 	uaa.port = port;
819 	uaa.vendor = UGETW(dd->idVendor);
820 	uaa.product = UGETW(dd->idProduct);
821 	uaa.release = UGETW(dd->bcdDevice);
822 	uaa.class = dd->bDeviceClass;
823 	uaa.subclass = dd->bDeviceSubClass;
824 	uaa.proto = dd->bDeviceProtocol;
825 
826 	dlocs[USBDEVIFCF_PORT] = uaa.port;
827 	dlocs[USBDEVIFCF_VENDOR] = uaa.vendor;
828 	dlocs[USBDEVIFCF_PRODUCT] = uaa.product;
829 	dlocs[USBDEVIFCF_RELEASE] = uaa.release;
830 	/* the rest is historical ballast */
831 	dlocs[USBDEVIFCF_CONFIGURATION] = -1;
832 	dlocs[USBDEVIFCF_INTERFACE] = -1;
833 
834 	dv = config_found_sm_loc(parent, "usbdevif", dlocs, &uaa, usbd_print,
835 				 config_stdsubmatch);
836 	if (dv) {
837 		dev->subdevs = malloc(sizeof dv, M_USB, M_NOWAIT);
838 		if (dev->subdevs == NULL)
839 			return (USBD_NOMEM);
840 		dev->subdevs[0] = dv;
841 		dev->subdevlen = 1;
842 		dev->nifaces_claimed = 1; /* XXX */
843 	}
844 	return (USBD_NORMAL_COMPLETION);
845 }
846 
847 static usbd_status
848 usbd_attachinterfaces(device_t parent, usbd_device_handle dev,
849 		      int port, const int *locators)
850 {
851 	struct usbif_attach_arg uiaa;
852 	int ilocs[USBIFIFCF_NLOCS];
853 	usb_device_descriptor_t *dd = &dev->ddesc;
854 	int nifaces;
855 	usbd_interface_handle *ifaces;
856 	int i, j, loc;
857 	device_t dv;
858 
859 	nifaces = dev->cdesc->bNumInterface;
860 	ifaces = malloc(nifaces * sizeof(*ifaces), M_USB, M_NOWAIT|M_ZERO);
861 	if (!ifaces)
862 		return (USBD_NOMEM);
863 	for (i = 0; i < nifaces; i++)
864 		if (!dev->subdevs[i])
865 			ifaces[i] = &dev->ifaces[i];
866 
867 	uiaa.device = dev;
868 	uiaa.port = port;
869 	uiaa.vendor = UGETW(dd->idVendor);
870 	uiaa.product = UGETW(dd->idProduct);
871 	uiaa.release = UGETW(dd->bcdDevice);
872 	uiaa.configno = dev->cdesc->bConfigurationValue;
873 	uiaa.ifaces = ifaces;
874 	uiaa.nifaces = nifaces;
875 	ilocs[USBIFIFCF_PORT] = uiaa.port;
876 	ilocs[USBIFIFCF_VENDOR] = uiaa.vendor;
877 	ilocs[USBIFIFCF_PRODUCT] = uiaa.product;
878 	ilocs[USBIFIFCF_RELEASE] = uiaa.release;
879 	ilocs[USBIFIFCF_CONFIGURATION] = uiaa.configno;
880 
881 	for (i = 0; i < nifaces; i++) {
882 		if (!ifaces[i])
883 			continue; /* interface already claimed */
884 		uiaa.iface = ifaces[i];
885 		uiaa.class = ifaces[i]->idesc->bInterfaceClass;
886 		uiaa.subclass = ifaces[i]->idesc->bInterfaceSubClass;
887 		uiaa.proto = ifaces[i]->idesc->bInterfaceProtocol;
888 		uiaa.ifaceno = ifaces[i]->idesc->bInterfaceNumber;
889 		ilocs[USBIFIFCF_INTERFACE] = uiaa.ifaceno;
890 		if (locators != NULL) {
891 			loc = locators[USBIFIFCF_CONFIGURATION];
892 			if (loc != USBIFIFCF_CONFIGURATION_DEFAULT &&
893 			    loc != uiaa.configno)
894 				continue;
895 			loc = locators[USBIFIFCF_INTERFACE];
896 			if (loc != USBIFIFCF_INTERFACE && loc != uiaa.ifaceno)
897 				continue;
898 		}
899 		dv = config_found_sm_loc(parent, "usbifif", ilocs, &uiaa,
900 					 usbd_ifprint, config_stdsubmatch);
901 		if (!dv)
902 			continue;
903 		ifaces[i] = 0; /* claim */
904 		/* account for ifaces claimed by the driver behind our back */
905 		for (j = 0; j < nifaces; j++) {
906 			if (!ifaces[j] && !dev->subdevs[j]) {
907 				dev->subdevs[j] = dv;
908 				dev->nifaces_claimed++;
909 			}
910 		}
911 	}
912 
913 	free(ifaces, M_USB);
914 	return (USBD_NORMAL_COMPLETION);
915 }
916 
917 usbd_status
918 usbd_probe_and_attach(device_t parent, usbd_device_handle dev,
919                       int port, int addr)
920 {
921 	usb_device_descriptor_t *dd = &dev->ddesc;
922 	int confi, nifaces;
923 	usbd_status err;
924 
925 	/* First try with device specific drivers. */
926 	DPRINTF(("usbd_probe_and_attach: trying device specific drivers\n"));
927 	err = usbd_attachwholedevice(parent, dev, port, 0);
928 	if (dev->nifaces_claimed || err)
929 		return (err);
930 	DPRINTF(("usbd_probe_and_attach: no device specific driver found\n"));
931 
932 	DPRINTF(("usbd_probe_and_attach: looping over %d configurations\n",
933 		 dd->bNumConfigurations));
934 	for (confi = 0; confi < dd->bNumConfigurations; confi++) {
935 		DPRINTFN(1,("usbd_probe_and_attach: trying config idx=%d\n",
936 			    confi));
937 		err = usbd_set_config_index(dev, confi, 1);
938 		if (err) {
939 #ifdef USB_DEBUG
940 			DPRINTF(("%s: port %d, set config at addr %d failed, "
941 			    "error=%s\n", device_xname(parent), port,
942 			    addr, usbd_errstr(err)));
943 #else
944 			printf("%s: port %d, set config at addr %d failed\n",
945 			    device_xname(parent), port, addr);
946 #endif
947 			return (err);
948 		}
949 		nifaces = dev->cdesc->bNumInterface;
950 		dev->subdevs = malloc(nifaces * sizeof(device_t), M_USB,
951 				      M_NOWAIT|M_ZERO);
952 		if (dev->subdevs == NULL)
953 			return (USBD_NOMEM);
954 		dev->subdevlen = nifaces;
955 
956 		err = usbd_attachinterfaces(parent, dev, port, NULL);
957 
958 		if (!dev->nifaces_claimed) {
959 			free(dev->subdevs, M_USB);
960 			dev->subdevs = 0;
961 			dev->subdevlen = 0;
962 		}
963 		if (dev->nifaces_claimed || err)
964 			return (err);
965 	}
966 	/* No interfaces were attached in any of the configurations. */
967 
968 	if (dd->bNumConfigurations > 1) /* don't change if only 1 config */
969 		usbd_set_config_index(dev, 0, 0);
970 
971 	DPRINTF(("usbd_probe_and_attach: no interface drivers found\n"));
972 
973 	/* Finally try the generic driver. */
974 	err = usbd_attachwholedevice(parent, dev, port, 1);
975 
976 	/*
977 	 * The generic attach failed, but leave the device as it is.
978 	 * We just did not find any drivers, that's all.  The device is
979 	 * fully operational and not harming anyone.
980 	 */
981 	DPRINTF(("usbd_probe_and_attach: generic attach failed\n"));
982 	return (USBD_NORMAL_COMPLETION);
983 }
984 
985 /**
986  * Called from uhub_rescan().  usbd_new_device() for the target dev must be
987  * called before calling this.
988  */
989 usbd_status
990 usbd_reattach_device(device_t parent, usbd_device_handle dev,
991                      int port, const int *locators)
992 {
993 	int i, loc;
994 
995 	if (locators != NULL) {
996 		loc = locators[USBIFIFCF_PORT];
997 		if (loc != USBIFIFCF_PORT_DEFAULT && loc != port)
998 			return USBD_NORMAL_COMPLETION;
999 		loc = locators[USBIFIFCF_VENDOR];
1000 		if (loc != USBIFIFCF_VENDOR_DEFAULT &&
1001 		    loc != UGETW(dev->ddesc.idVendor))
1002 			return USBD_NORMAL_COMPLETION;
1003 		loc = locators[USBIFIFCF_PRODUCT];
1004 		if (loc != USBIFIFCF_PRODUCT_DEFAULT &&
1005 		    loc != UGETW(dev->ddesc.idProduct))
1006 			return USBD_NORMAL_COMPLETION;
1007 		loc = locators[USBIFIFCF_RELEASE];
1008 		if (loc != USBIFIFCF_RELEASE_DEFAULT &&
1009 		    loc != UGETW(dev->ddesc.bcdDevice))
1010 			return USBD_NORMAL_COMPLETION;
1011 	}
1012 	if (dev->subdevlen == 0) {
1013 		/* XXX: check USBIFIFCF_CONFIGURATION and
1014 		 * USBIFIFCF_INTERFACE too */
1015 		return usbd_probe_and_attach(parent, dev, port, dev->address);
1016 	} else if (dev->subdevlen != dev->cdesc->bNumInterface) {
1017 		/* device-specific or generic driver is already attached. */
1018 		return USBD_NORMAL_COMPLETION;
1019 	}
1020 	/* Does the device have unconfigured interfaces? */
1021 	for (i = 0; i < dev->subdevlen; i++) {
1022 		if (dev->subdevs[i] == NULL) {
1023 			break;
1024 		}
1025 	}
1026 	if (i >= dev->subdevlen)
1027 		return USBD_NORMAL_COMPLETION;
1028 	return usbd_attachinterfaces(parent, dev, port, locators);
1029 }
1030 
1031 /*
1032  * Get the first 8 bytes of the device descriptor.
1033  * Do as Windows does: try to read 64 bytes -- there are devices which
1034  * recognize the initial descriptor fetch (before the control endpoint's
1035  * MaxPacketSize is known by the host) by exactly this length.
1036  */
1037 static usbd_status
1038 usbd_get_initial_ddesc(usbd_device_handle dev, usb_device_descriptor_t *desc)
1039 {
1040 	usb_device_request_t req;
1041 	char buf[64];
1042 	int res, actlen;
1043 
1044 	req.bmRequestType = UT_READ_DEVICE;
1045 	req.bRequest = UR_GET_DESCRIPTOR;
1046 	USETW2(req.wValue, UDESC_DEVICE, 0);
1047 	USETW(req.wIndex, 0);
1048 	USETW(req.wLength, 64);
1049 	res = usbd_do_request_flags(dev, &req, buf, USBD_SHORT_XFER_OK,
1050 		&actlen, USBD_DEFAULT_TIMEOUT);
1051 	if (res)
1052 		return res;
1053 	if (actlen < 8)
1054 		return USBD_SHORT_XFER;
1055 	memcpy(desc, buf, 8);
1056 	return USBD_NORMAL_COMPLETION;
1057 }
1058 
1059 /*
1060  * Called when a new device has been put in the powered state,
1061  * but not yet in the addressed state.
1062  * Get initial descriptor, set the address, get full descriptor,
1063  * and attach a driver.
1064  */
1065 usbd_status
1066 usbd_new_device(device_t parent, usbd_bus_handle bus, int depth,
1067                 int speed, int port, struct usbd_port *up)
1068 {
1069 	usbd_device_handle dev, adev;
1070 	struct usbd_device *hub;
1071 	usb_device_descriptor_t *dd;
1072 	usb_port_status_t ps;
1073 	usbd_status err;
1074 	int addr;
1075 	int i;
1076 	int p;
1077 
1078 	DPRINTF(("usbd_new_device bus=%p port=%d depth=%d speed=%d\n",
1079 		 bus, port, depth, speed));
1080 	addr = usbd_getnewaddr(bus);
1081 	if (addr < 0) {
1082 		printf("%s: No free USB addresses, new device ignored.\n",
1083 		       device_xname(bus->usbctl));
1084 		return (USBD_NO_ADDR);
1085 	}
1086 
1087 	dev = malloc(sizeof *dev, M_USB, M_NOWAIT|M_ZERO);
1088 	if (dev == NULL)
1089 		return (USBD_NOMEM);
1090 
1091 	dev->bus = bus;
1092 
1093 	/* Set up default endpoint handle. */
1094 	dev->def_ep.edesc = &dev->def_ep_desc;
1095 
1096 	/* Set up default endpoint descriptor. */
1097 	dev->def_ep_desc.bLength = USB_ENDPOINT_DESCRIPTOR_SIZE;
1098 	dev->def_ep_desc.bDescriptorType = UDESC_ENDPOINT;
1099 	dev->def_ep_desc.bEndpointAddress = USB_CONTROL_ENDPOINT;
1100 	dev->def_ep_desc.bmAttributes = UE_CONTROL;
1101 	/*
1102 	 * temporary, will be fixed after first descriptor fetch
1103 	 * (which uses 64 bytes so it shouldn't be less),
1104 	 * highspeed devices must support 64 byte packets anyway
1105 	 */
1106 	USETW(dev->def_ep_desc.wMaxPacketSize, 64);
1107 	dev->def_ep_desc.bInterval = 0;
1108 
1109 	/* doesn't matter, just don't let it uninitialized */
1110 	dev->def_ep.datatoggle = 0;
1111 
1112 	dev->quirks = &usbd_no_quirk;
1113 	dev->address = USB_START_ADDR;
1114 	dev->ddesc.bMaxPacketSize = 0;
1115 	dev->depth = depth;
1116 	dev->powersrc = up;
1117 	dev->myhub = up->parent;
1118 
1119 	up->device = dev;
1120 
1121 	/* Locate port on upstream high speed hub */
1122 	for (adev = dev, hub = up->parent;
1123 	     hub != NULL && hub->speed != USB_SPEED_HIGH;
1124 	     adev = hub, hub = hub->myhub)
1125 		;
1126 	if (hub) {
1127 		for (p = 0; p < hub->hub->hubdesc.bNbrPorts; p++) {
1128 			if (hub->hub->ports[p].device == adev) {
1129 				dev->myhsport = &hub->hub->ports[p];
1130 				goto found;
1131 			}
1132 		}
1133 		panic("usbd_new_device: cannot find HS port\n");
1134 	found:
1135 		DPRINTFN(1,("usbd_new_device: high speed port %d\n", p));
1136 	} else {
1137 		dev->myhsport = NULL;
1138 	}
1139 	dev->speed = speed;
1140 	dev->langid = USBD_NOLANG;
1141 	dev->cookie.cookie = ++usb_cookie_no;
1142 
1143 	/* Establish the default pipe. */
1144 	err = usbd_setup_pipe(dev, 0, &dev->def_ep, USBD_DEFAULT_INTERVAL,
1145 			      &dev->default_pipe);
1146 	if (err) {
1147 		usbd_remove_device(dev, up);
1148 		return (err);
1149 	}
1150 
1151 	dd = &dev->ddesc;
1152 	/* Try a few times in case the device is slow (i.e. outside specs.) */
1153 	for (i = 0; i < 10; i++) {
1154 		/* Get the first 8 bytes of the device descriptor. */
1155 		err = usbd_get_initial_ddesc(dev, dd);
1156 		if (!err)
1157 			break;
1158 		usbd_delay_ms(dev, 200);
1159 		if ((i & 3) == 3)
1160 			usbd_reset_port(up->parent, port, &ps);
1161 	}
1162 	if (err) {
1163 		DPRINTFN(-1, ("usbd_new_device: addr=%d, getting first desc "
1164 			      "failed: %d\n", addr, err));
1165 		usbd_remove_device(dev, up);
1166 		return (err);
1167 	}
1168 
1169 	/* Windows resets the port here, do likewise */
1170 	if (up->parent)
1171 		usbd_reset_port(up->parent, port, &ps);
1172 
1173 	if (speed == USB_SPEED_HIGH) {
1174 		/* Max packet size must be 64 (sec 5.5.3). */
1175 		if (dd->bMaxPacketSize != USB_2_MAX_CTRL_PACKET) {
1176 #ifdef DIAGNOSTIC
1177 			printf("usbd_new_device: addr=%d bad max packet "
1178 			    "size=%d. adjusting to %d.\n",
1179 			    addr, dd->bMaxPacketSize, USB_2_MAX_CTRL_PACKET);
1180 #endif
1181 			dd->bMaxPacketSize = USB_2_MAX_CTRL_PACKET;
1182 		}
1183 	}
1184 
1185 	DPRINTF(("usbd_new_device: adding unit addr=%d, rev=%02x, class=%d, "
1186 		 "subclass=%d, protocol=%d, maxpacket=%d, len=%d, speed=%d\n",
1187 		 addr,UGETW(dd->bcdUSB), dd->bDeviceClass, dd->bDeviceSubClass,
1188 		 dd->bDeviceProtocol, dd->bMaxPacketSize, dd->bLength,
1189 		 dev->speed));
1190 
1191 	if (dd->bDescriptorType != UDESC_DEVICE) {
1192 		/* Illegal device descriptor */
1193 		DPRINTFN(-1,("usbd_new_device: illegal descriptor %d\n",
1194 			     dd->bDescriptorType));
1195 		usbd_remove_device(dev, up);
1196 		return (USBD_INVAL);
1197 	}
1198 
1199 	if (dd->bLength < USB_DEVICE_DESCRIPTOR_SIZE) {
1200 		DPRINTFN(-1,("usbd_new_device: bad length %d\n", dd->bLength));
1201 		usbd_remove_device(dev, up);
1202 		return (USBD_INVAL);
1203 	}
1204 
1205 	USETW(dev->def_ep_desc.wMaxPacketSize, dd->bMaxPacketSize);
1206 
1207 	/* Set the address */
1208 	DPRINTFN(5, ("usbd_new_device: setting device address=%d\n", addr));
1209 	err = usbd_set_address(dev, addr);
1210 	if (err) {
1211 		DPRINTFN(-1, ("usbd_new_device: set address %d failed\n", addr));
1212 		err = USBD_SET_ADDR_FAILED;
1213 		usbd_remove_device(dev, up);
1214 		return err;
1215 	}
1216 
1217 	/* Allow device time to set new address */
1218 	usbd_delay_ms(dev, USB_SET_ADDRESS_SETTLE);
1219 	dev->address = addr;	/* new device address now */
1220 	bus->devices[addr] = dev;
1221 
1222 	err = usbd_reload_device_desc(dev);
1223 	if (err) {
1224 		DPRINTFN(-1, ("usbd_new_device: addr=%d, getting full desc "
1225 			      "failed\n", addr));
1226 		usbd_remove_device(dev, up);
1227 		return (err);
1228 	}
1229 
1230 	/* Re-establish the default pipe with the new address. */
1231 	usbd_kill_pipe(dev->default_pipe);
1232 	err = usbd_setup_pipe(dev, 0, &dev->def_ep, USBD_DEFAULT_INTERVAL,
1233 	    &dev->default_pipe);
1234 	if (err) {
1235 		DPRINTFN(-1, ("usbd_new_device: setup default pipe failed\n"));
1236 		usbd_remove_device(dev, up);
1237 		return err;
1238 	}
1239 
1240 	/* Assume 100mA bus powered for now. Changed when configured. */
1241 	dev->power = USB_MIN_POWER;
1242 	dev->self_powered = 0;
1243 
1244 	DPRINTF(("usbd_new_device: new dev (addr %d), dev=%p, parent=%p\n",
1245 		 addr, dev, parent));
1246 
1247 	usbd_add_dev_event(USB_EVENT_DEVICE_ATTACH, dev);
1248 
1249 	if (port == 0) { /* root hub */
1250 		KASSERT(addr == 1);
1251 		usbd_attach_roothub(parent, dev);
1252 		return (USBD_NORMAL_COMPLETION);
1253 	}
1254 
1255 	err = usbd_probe_and_attach(parent, dev, port, addr);
1256 	if (err) {
1257 		usbd_remove_device(dev, up);
1258 		return (err);
1259 	}
1260 
1261 	return (USBD_NORMAL_COMPLETION);
1262 }
1263 
1264 usbd_status
1265 usbd_reload_device_desc(usbd_device_handle dev)
1266 {
1267 	usbd_status err;
1268 
1269 	/* Get the full device descriptor. */
1270 	err = usbd_get_device_desc(dev, &dev->ddesc);
1271 	if (err)
1272 		return (err);
1273 
1274 	/* Figure out what's wrong with this device. */
1275 	dev->quirks = usbd_find_quirk(&dev->ddesc);
1276 
1277 	return (USBD_NORMAL_COMPLETION);
1278 }
1279 
1280 void
1281 usbd_remove_device(usbd_device_handle dev, struct usbd_port *up)
1282 {
1283 	DPRINTF(("usbd_remove_device: %p\n", dev));
1284 
1285 	if (dev->default_pipe != NULL)
1286 		usbd_kill_pipe(dev->default_pipe);
1287 	up->device = NULL;
1288 	dev->bus->devices[dev->address] = NULL;
1289 
1290 	free(dev, M_USB);
1291 }
1292 
1293 int
1294 usbd_print(void *aux, const char *pnp)
1295 {
1296 	struct usb_attach_arg *uaa = aux;
1297 
1298 	DPRINTFN(15, ("usbd_print dev=%p\n", uaa->device));
1299 	if (pnp) {
1300 #define USB_DEVINFO 1024
1301 		char *devinfo;
1302 		if (!uaa->usegeneric)
1303 			return (QUIET);
1304 		devinfo = malloc(USB_DEVINFO, M_TEMP, M_WAITOK);
1305 		usbd_devinfo(uaa->device, 1, devinfo, USB_DEVINFO);
1306 		aprint_normal("%s, %s", devinfo, pnp);
1307 		free(devinfo, M_TEMP);
1308 	}
1309 	aprint_normal(" port %d", uaa->port);
1310 #if 0
1311 	/*
1312 	 * It gets very crowded with these locators on the attach line.
1313 	 * They are not really needed since they are printed in the clear
1314 	 * by each driver.
1315 	 */
1316 	if (uaa->vendor != UHUB_UNK_VENDOR)
1317 		aprint_normal(" vendor 0x%04x", uaa->vendor);
1318 	if (uaa->product != UHUB_UNK_PRODUCT)
1319 		aprint_normal(" product 0x%04x", uaa->product);
1320 	if (uaa->release != UHUB_UNK_RELEASE)
1321 		aprint_normal(" release 0x%04x", uaa->release);
1322 #endif
1323 	return (UNCONF);
1324 }
1325 
1326 int
1327 usbd_ifprint(void *aux, const char *pnp)
1328 {
1329 	struct usbif_attach_arg *uaa = aux;
1330 
1331 	DPRINTFN(15, ("usbd_print dev=%p\n", uaa->device));
1332 	if (pnp)
1333 		return (QUIET);
1334 	aprint_normal(" port %d", uaa->port);
1335 	aprint_normal(" configuration %d", uaa->configno);
1336 	aprint_normal(" interface %d", uaa->ifaceno);
1337 #if 0
1338 	/*
1339 	 * It gets very crowded with these locators on the attach line.
1340 	 * They are not really needed since they are printed in the clear
1341 	 * by each driver.
1342 	 */
1343 	if (uaa->vendor != UHUB_UNK_VENDOR)
1344 		aprint_normal(" vendor 0x%04x", uaa->vendor);
1345 	if (uaa->product != UHUB_UNK_PRODUCT)
1346 		aprint_normal(" product 0x%04x", uaa->product);
1347 	if (uaa->release != UHUB_UNK_RELEASE)
1348 		aprint_normal(" release 0x%04x", uaa->release);
1349 #endif
1350 	return (UNCONF);
1351 }
1352 
1353 void
1354 usbd_fill_deviceinfo(usbd_device_handle dev, struct usb_device_info *di,
1355 		     int usedev)
1356 {
1357 	struct usbd_port *p;
1358 	int i, j, err, s;
1359 
1360 	di->udi_bus = device_unit(dev->bus->usbctl);
1361 	di->udi_addr = dev->address;
1362 	di->udi_cookie = dev->cookie;
1363 	usbd_devinfo_vp(dev, di->udi_vendor, sizeof(di->udi_vendor),
1364 	    di->udi_product, sizeof(di->udi_product), usedev, 1);
1365 	usbd_printBCD(di->udi_release, sizeof(di->udi_release),
1366 	    UGETW(dev->ddesc.bcdDevice));
1367 	di->udi_serial[0] = 0;
1368 	if (usedev)
1369 		(void)usbd_get_string(dev, dev->ddesc.iSerialNumber,
1370 				      di->udi_serial);
1371 	di->udi_vendorNo = UGETW(dev->ddesc.idVendor);
1372 	di->udi_productNo = UGETW(dev->ddesc.idProduct);
1373 	di->udi_releaseNo = UGETW(dev->ddesc.bcdDevice);
1374 	di->udi_class = dev->ddesc.bDeviceClass;
1375 	di->udi_subclass = dev->ddesc.bDeviceSubClass;
1376 	di->udi_protocol = dev->ddesc.bDeviceProtocol;
1377 	di->udi_config = dev->config;
1378 	di->udi_power = dev->self_powered ? 0 : dev->power;
1379 	di->udi_speed = dev->speed;
1380 
1381 	if (dev->subdevlen > 0) {
1382 		for (i = 0, j = 0; i < dev->subdevlen &&
1383 			     j < USB_MAX_DEVNAMES; i++) {
1384 			if (!dev->subdevs[i])
1385 				continue;
1386 			strncpy(di->udi_devnames[j],
1387 			    device_xname(dev->subdevs[i]), USB_MAX_DEVNAMELEN);
1388 			di->udi_devnames[j][USB_MAX_DEVNAMELEN-1] = '\0';
1389 			j++;
1390 		}
1391 	} else {
1392 		j = 0;
1393 	}
1394 	for (/* j is set */; j < USB_MAX_DEVNAMES; j++)
1395 		di->udi_devnames[j][0] = 0;                 /* empty */
1396 
1397 	if (dev->hub) {
1398 		for (i = 0;
1399 		     i < sizeof(di->udi_ports) / sizeof(di->udi_ports[0]) &&
1400 			     i < dev->hub->hubdesc.bNbrPorts;
1401 		     i++) {
1402 			p = &dev->hub->ports[i];
1403 			if (p->device)
1404 				err = p->device->address;
1405 			else {
1406 				s = UGETW(p->status.wPortStatus);
1407 				if (s & UPS_PORT_ENABLED)
1408 					err = USB_PORT_ENABLED;
1409 				else if (s & UPS_SUSPEND)
1410 					err = USB_PORT_SUSPENDED;
1411 				else if (s & UPS_PORT_POWER)
1412 					err = USB_PORT_POWERED;
1413 				else
1414 					err = USB_PORT_DISABLED;
1415 			}
1416 			di->udi_ports[i] = err;
1417 		}
1418 		di->udi_nports = dev->hub->hubdesc.bNbrPorts;
1419 	} else
1420 		di->udi_nports = 0;
1421 }
1422 
1423 #ifdef COMPAT_30
1424 void
1425 usbd_fill_deviceinfo_old(usbd_device_handle dev, struct usb_device_info_old *di,
1426                          int usedev)
1427 {
1428 	struct usbd_port *p;
1429 	int i, j, err, s;
1430 
1431 	di->udi_bus = device_unit(dev->bus->usbctl);
1432 	di->udi_addr = dev->address;
1433 	di->udi_cookie = dev->cookie;
1434 	usbd_devinfo_vp(dev, di->udi_vendor, sizeof(di->udi_vendor),
1435 	    di->udi_product, sizeof(di->udi_product), usedev, 0);
1436 	usbd_printBCD(di->udi_release, sizeof(di->udi_release),
1437 	    UGETW(dev->ddesc.bcdDevice));
1438 	di->udi_vendorNo = UGETW(dev->ddesc.idVendor);
1439 	di->udi_productNo = UGETW(dev->ddesc.idProduct);
1440 	di->udi_releaseNo = UGETW(dev->ddesc.bcdDevice);
1441 	di->udi_class = dev->ddesc.bDeviceClass;
1442 	di->udi_subclass = dev->ddesc.bDeviceSubClass;
1443 	di->udi_protocol = dev->ddesc.bDeviceProtocol;
1444 	di->udi_config = dev->config;
1445 	di->udi_power = dev->self_powered ? 0 : dev->power;
1446 	di->udi_speed = dev->speed;
1447 
1448 	if (dev->subdevlen > 0) {
1449 		for (i = 0, j = 0; i < dev->subdevlen &&
1450 			     j < USB_MAX_DEVNAMES; i++) {
1451 			if (!dev->subdevs[i])
1452 				continue;
1453 			strncpy(di->udi_devnames[j],
1454 			    device_xname(dev->subdevs[i]), USB_MAX_DEVNAMELEN);
1455 			di->udi_devnames[j][USB_MAX_DEVNAMELEN-1] = '\0';
1456 			j++;
1457 		}
1458 	} else {
1459 		j = 0;
1460 	}
1461 	for (/* j is set */; j < USB_MAX_DEVNAMES; j++)
1462 		di->udi_devnames[j][0] = 0;		 /* empty */
1463 
1464 	if (dev->hub) {
1465 		for (i = 0;
1466 		     i < sizeof(di->udi_ports) / sizeof(di->udi_ports[0]) &&
1467 			     i < dev->hub->hubdesc.bNbrPorts;
1468 		     i++) {
1469 			p = &dev->hub->ports[i];
1470 			if (p->device)
1471 				err = p->device->address;
1472 			else {
1473 				s = UGETW(p->status.wPortStatus);
1474 				if (s & UPS_PORT_ENABLED)
1475 					err = USB_PORT_ENABLED;
1476 				else if (s & UPS_SUSPEND)
1477 					err = USB_PORT_SUSPENDED;
1478 				else if (s & UPS_PORT_POWER)
1479 					err = USB_PORT_POWERED;
1480 				else
1481 					err = USB_PORT_DISABLED;
1482 			}
1483 			di->udi_ports[i] = err;
1484 		}
1485 		di->udi_nports = dev->hub->hubdesc.bNbrPorts;
1486 	} else
1487 		di->udi_nports = 0;
1488 }
1489 #endif
1490 
1491 
1492 void
1493 usb_free_device(usbd_device_handle dev)
1494 {
1495 	int ifcidx, nifc;
1496 
1497 	if (dev->default_pipe != NULL)
1498 		usbd_kill_pipe(dev->default_pipe);
1499 	if (dev->ifaces != NULL) {
1500 		nifc = dev->cdesc->bNumInterface;
1501 		for (ifcidx = 0; ifcidx < nifc; ifcidx++)
1502 			usbd_free_iface_data(dev, ifcidx);
1503 		free(dev->ifaces, M_USB);
1504 	}
1505 	if (dev->cdesc != NULL)
1506 		free(dev->cdesc, M_USB);
1507 	if (dev->subdevlen > 0) {
1508 		free(dev->subdevs, M_USB);
1509 		dev->subdevlen = 0;
1510 	}
1511 	free(dev, M_USB);
1512 }
1513 
1514 /*
1515  * The general mechanism for detaching drivers works as follows: Each
1516  * driver is responsible for maintaining a reference count on the
1517  * number of outstanding references to its softc (e.g.  from
1518  * processing hanging in a read or write).  The detach method of the
1519  * driver decrements this counter and flags in the softc that the
1520  * driver is dying and then wakes any sleepers.  It then sleeps on the
1521  * softc.  Each place that can sleep must maintain the reference
1522  * count.  When the reference count drops to -1 (0 is the normal value
1523  * of the reference count) the a wakeup on the softc is performed
1524  * signaling to the detach waiter that all references are gone.
1525  */
1526 
1527 /*
1528  * Called from process context when we discover that a port has
1529  * been disconnected.
1530  */
1531 int
1532 usb_disconnect_port(struct usbd_port *up, device_t parent, int flags)
1533 {
1534 	usbd_device_handle dev = up->device;
1535 	device_t subdev;
1536 	char subdevname[16];
1537 	const char *hubname = device_xname(parent);
1538 	int i, rc;
1539 
1540 	DPRINTFN(3,("uhub_disconnect: up=%p dev=%p port=%d\n",
1541 		    up, dev, up->portno));
1542 
1543 	if (dev == NULL) {
1544 #ifdef DIAGNOSTIC
1545 		printf("usb_disconnect_port: no device\n");
1546 #endif
1547 		return 0;
1548 	}
1549 
1550 	if (dev->subdevlen > 0) {
1551 		DPRINTFN(3,("usb_disconnect_port: disconnect subdevs\n"));
1552 		for (i = 0; i < dev->subdevlen; i++) {
1553 			if ((subdev = dev->subdevs[i]) == NULL)
1554 				continue;
1555 			strlcpy(subdevname, device_xname(subdev),
1556 			    sizeof(subdevname));
1557 			if ((rc = config_detach(subdev, flags)) != 0)
1558 				return rc;
1559 			printf("%s: at %s", subdevname, hubname);
1560 			if (up->portno != 0)
1561 				printf(" port %d", up->portno);
1562 			printf(" (addr %d) disconnected\n", dev->address);
1563 		}
1564 		KASSERT(!dev->nifaces_claimed);
1565 	}
1566 
1567 	usbd_add_dev_event(USB_EVENT_DEVICE_DETACH, dev);
1568 	dev->bus->devices[dev->address] = NULL;
1569 	up->device = NULL;
1570 	usb_free_device(dev);
1571 	return 0;
1572 }
1573