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