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