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