xref: /openbsd/sys/dev/usb/usb_subr.c (revision 81508fe3)
1 /*	$OpenBSD: usb_subr.c,v 1.163 2024/05/23 03:21:09 jsg Exp $ */
2 /*	$NetBSD: usb_subr.c,v 1.103 2003/01/10 11:19:13 augustss Exp $	*/
3 /*	$FreeBSD: src/sys/dev/usb/usb_subr.c,v 1.18 1999/11/17 22:33:47 n_hibma Exp $	*/
4 
5 /*
6  * Copyright (c) 1998 The NetBSD Foundation, Inc.
7  * All rights reserved.
8  *
9  * This code is derived from software contributed to The NetBSD Foundation
10  * by Lennart Augustsson (lennart@augustsson.net) at
11  * Carlstedt Research & Technology.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
24  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
26  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/malloc.h>
38 #include <sys/device.h>
39 #include <sys/rwlock.h>
40 
41 #include <machine/bus.h>
42 
43 #include <dev/usb/usb.h>
44 
45 #include <dev/usb/usbdi.h>
46 #include <dev/usb/usbdi_util.h>
47 #include <dev/usb/usbdivar.h>
48 #include <dev/usb/usbdevs.h>
49 #include <dev/usb/usb_quirks.h>
50 
51 #ifdef USB_DEBUG
52 #define DPRINTF(x)	do { if (usbdebug) printf x; } while (0)
53 #define DPRINTFN(n,x)	do { if (usbdebug>(n)) printf x; } while (0)
54 extern int usbdebug;
55 #else
56 #define DPRINTF(x)
57 #define DPRINTFN(n,x)
58 #endif
59 
60 usbd_status	usbd_set_config(struct usbd_device *, int);
61 void		usbd_devinfo(struct usbd_device *, int, char *, size_t);
62 char		*usbd_get_string(struct usbd_device *, int, char *, size_t);
63 int		usbd_getnewaddr(struct usbd_bus *);
64 int		usbd_print(void *, const char *);
65 void		usbd_free_iface_data(struct usbd_device *, int);
66 int		usbd_cache_devinfo(struct usbd_device *);
67 usbd_status	usbd_probe_and_attach(struct device *,
68 		    struct usbd_device *, int, int);
69 
70 int		usbd_printBCD(char *cp, size_t len, int bcd);
71 void		usb_free_device(struct usbd_device *);
72 int		usbd_parse_idesc(struct usbd_device *, struct usbd_interface *);
73 
74 #ifdef USBVERBOSE
75 #include <dev/usb/usbdevs_data.h>
76 #endif /* USBVERBOSE */
77 
78 const char * const usbd_error_strs[] = {
79 	"NORMAL_COMPLETION",
80 	"IN_PROGRESS",
81 	"PENDING_REQUESTS",
82 	"NOT_STARTED",
83 	"INVAL",
84 	"NOMEM",
85 	"CANCELLED",
86 	"BAD_ADDRESS",
87 	"IN_USE",
88 	"NO_ADDR",
89 	"SET_ADDR_FAILED",
90 	"NO_POWER",
91 	"TOO_DEEP",
92 	"IOERROR",
93 	"NOT_CONFIGURED",
94 	"TIMEOUT",
95 	"SHORT_XFER",
96 	"STALLED",
97 	"INTERRUPTED",
98 	"XXX",
99 };
100 
101 const char *
usbd_errstr(usbd_status err)102 usbd_errstr(usbd_status err)
103 {
104 	static char buffer[5];
105 
106 	if (err < USBD_ERROR_MAX)
107 		return (usbd_error_strs[err]);
108 	else {
109 		snprintf(buffer, sizeof(buffer), "%d", err);
110 		return (buffer);
111 	}
112 }
113 
114 usbd_status
usbd_get_string_desc(struct usbd_device * dev,int sindex,int langid,usb_string_descriptor_t * sdesc,int * sizep)115 usbd_get_string_desc(struct usbd_device *dev, int sindex, int langid,
116     usb_string_descriptor_t *sdesc, int *sizep)
117 {
118 	usb_device_request_t req;
119 	usbd_status err;
120 	int actlen;
121 
122 	req.bmRequestType = UT_READ_DEVICE;
123 	req.bRequest = UR_GET_DESCRIPTOR;
124 	USETW2(req.wValue, UDESC_STRING, sindex);
125 	USETW(req.wIndex, langid);
126 	USETW(req.wLength, 2);	/* size and descriptor type first */
127 	err = usbd_do_request_flags(dev, &req, sdesc, USBD_SHORT_XFER_OK,
128 	    &actlen, USBD_DEFAULT_TIMEOUT);
129 	if (err)
130 		return (err);
131 
132 	if (actlen < 2)
133 		return (USBD_SHORT_XFER);
134 
135 	USETW(req.wLength, sdesc->bLength);	/* the whole string */
136 	err = usbd_do_request_flags(dev, &req, sdesc, USBD_SHORT_XFER_OK,
137 	    &actlen, USBD_DEFAULT_TIMEOUT);
138 	if (err)
139 		return (err);
140 
141 	if (actlen != sdesc->bLength) {
142 		DPRINTFN(-1, ("%s: expected %d, got %d\n", __func__,
143 		    sdesc->bLength, actlen));
144 	}
145 
146 	*sizep = actlen;
147 	return (USBD_NORMAL_COMPLETION);
148 }
149 
150 char *
usbd_get_string(struct usbd_device * dev,int si,char * buf,size_t buflen)151 usbd_get_string(struct usbd_device *dev, int si, char *buf, size_t buflen)
152 {
153 	int swap = dev->quirks->uq_flags & UQ_SWAP_UNICODE;
154 	usb_string_descriptor_t us;
155 	char *s;
156 	int i, n;
157 	u_int16_t c;
158 	usbd_status err;
159 	int size;
160 
161 	if (si == 0)
162 		return (0);
163 	if (dev->quirks->uq_flags & UQ_NO_STRINGS)
164 		return (0);
165 	if (dev->langid == USBD_NOLANG) {
166 		/* Set up default language */
167 		err = usbd_get_string_desc(dev, USB_LANGUAGE_TABLE, 0, &us,
168 		    &size);
169 		if (err || size < 4)
170 			dev->langid = 0; /* Well, just pick English then */
171 		else {
172 			/* Pick the first language as the default. */
173 			dev->langid = UGETW(us.bString[0]);
174 		}
175 	}
176 	err = usbd_get_string_desc(dev, si, dev->langid, &us, &size);
177 	if (err)
178 		return (0);
179 	s = buf;
180 	n = size / 2 - 1;
181 	for (i = 0; i < n && i < buflen ; i++) {
182 		c = UGETW(us.bString[i]);
183 		/* Convert from Unicode, handle buggy strings. */
184 		if ((c & 0xff00) == 0)
185 			*s++ = c;
186 		else if ((c & 0x00ff) == 0 && swap)
187 			*s++ = c >> 8;
188 		else
189 			*s++ = '?';
190 	}
191 	if (buflen > 0)
192 		*s++ = 0;
193 	return (buf);
194 }
195 
196 static void
usbd_trim_spaces(char * p)197 usbd_trim_spaces(char *p)
198 {
199 	char *q, *e;
200 
201 	if (p == NULL)
202 		return;
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 int
usbd_cache_devinfo(struct usbd_device * dev)213 usbd_cache_devinfo(struct usbd_device *dev)
214 {
215 	usb_device_descriptor_t *udd = &dev->ddesc;
216 
217 	dev->serial = malloc(USB_MAX_STRING_LEN, M_USB, M_NOWAIT);
218 	if (dev->serial == NULL)
219 		return (ENOMEM);
220 
221 	if (usbd_get_string(dev, udd->iSerialNumber, dev->serial, USB_MAX_STRING_LEN) != NULL) {
222 		usbd_trim_spaces(dev->serial);
223 	} else {
224 		free(dev->serial, M_USB, USB_MAX_STRING_LEN);
225 		dev->serial = NULL;
226 	}
227 
228 	dev->vendor = malloc(USB_MAX_STRING_LEN, M_USB, M_NOWAIT);
229 	if (dev->vendor == NULL)
230 		return (ENOMEM);
231 
232 	if (usbd_get_string(dev, udd->iManufacturer, dev->vendor, USB_MAX_STRING_LEN) != NULL) {
233 		usbd_trim_spaces(dev->vendor);
234 	} else {
235 #ifdef USBVERBOSE
236 		const struct usb_known_vendor *ukv;
237 
238 		for (ukv = usb_known_vendors; ukv->vendorname != NULL; ukv++) {
239 			if (ukv->vendor == UGETW(udd->idVendor)) {
240 				strlcpy(dev->vendor, ukv->vendorname,
241 				    USB_MAX_STRING_LEN);
242 				break;
243 			}
244 		}
245 		if (ukv->vendorname == NULL)
246 #endif
247 			snprintf(dev->vendor, USB_MAX_STRING_LEN, "vendor 0x%04x",
248 			    UGETW(udd->idVendor));
249 	}
250 
251 	dev->product = malloc(USB_MAX_STRING_LEN, M_USB, M_NOWAIT);
252 	if (dev->product == NULL)
253 		return (ENOMEM);
254 
255 	if (usbd_get_string(dev, udd->iProduct, dev->product, USB_MAX_STRING_LEN) != NULL) {
256 		usbd_trim_spaces(dev->product);
257 	} else {
258 #ifdef USBVERBOSE
259 		const struct usb_known_product *ukp;
260 
261 		for (ukp = usb_known_products; ukp->productname != NULL; ukp++) {
262 			if (ukp->vendor == UGETW(udd->idVendor) &&
263 			    (ukp->product == UGETW(udd->idProduct))) {
264 				strlcpy(dev->product, ukp->productname,
265 				    USB_MAX_STRING_LEN);
266 				break;
267 			}
268 		}
269 		if (ukp->productname == NULL)
270 #endif
271 			snprintf(dev->product, USB_MAX_STRING_LEN, "product 0x%04x",
272 			    UGETW(udd->idProduct));
273 	}
274 
275 	return (0);
276 }
277 
278 int
usbd_printBCD(char * cp,size_t len,int bcd)279 usbd_printBCD(char *cp, size_t len, int bcd)
280 {
281 	int l;
282 
283 	l = snprintf(cp, len, "%x.%02x", bcd >> 8, bcd & 0xff);
284 	if (l == -1 || len == 0)
285 		return (0);
286 	if (l >= len)
287 		return len - 1;
288 	return (l);
289 }
290 
291 void
usbd_devinfo(struct usbd_device * dev,int showclass,char * base,size_t len)292 usbd_devinfo(struct usbd_device *dev, int showclass, char *base, size_t len)
293 {
294 	usb_device_descriptor_t *udd = &dev->ddesc;
295 	char *cp = base;
296 	int bcdDevice, bcdUSB;
297 
298 	snprintf(cp, len, "\"%s %s\"", dev->vendor, dev->product);
299 	cp += strlen(cp);
300 	if (showclass) {
301 		snprintf(cp, base + len - cp, ", class %d/%d",
302 		    udd->bDeviceClass, udd->bDeviceSubClass);
303 		cp += strlen(cp);
304 	}
305 	bcdUSB = UGETW(udd->bcdUSB);
306 	bcdDevice = UGETW(udd->bcdDevice);
307 	snprintf(cp, base + len - cp, " rev ");
308 	cp += strlen(cp);
309 	usbd_printBCD(cp, base + len - cp, bcdUSB);
310 	cp += strlen(cp);
311 	snprintf(cp, base + len - cp, "/");
312 	cp += strlen(cp);
313 	usbd_printBCD(cp, base + len - cp, bcdDevice);
314 	cp += strlen(cp);
315 	snprintf(cp, base + len - cp, " addr %d", dev->address);
316 }
317 
318 /* Delay for a certain number of ms */
319 void
usb_delay_ms(struct usbd_bus * bus,u_int ms)320 usb_delay_ms(struct usbd_bus *bus, u_int ms)
321 {
322 	static int usb_delay_wchan;
323 
324 	if (bus->use_polling || cold)
325 		delay((ms+1) * 1000);
326 	else
327 		tsleep_nsec(&usb_delay_wchan, PRIBIO, "usbdly",
328 		    MSEC_TO_NSEC(ms));
329 }
330 
331 /* Delay given a device handle. */
332 void
usbd_delay_ms(struct usbd_device * dev,u_int ms)333 usbd_delay_ms(struct usbd_device *dev, u_int ms)
334 {
335 	if (usbd_is_dying(dev))
336 		return;
337 
338 	usb_delay_ms(dev->bus, ms);
339 }
340 
341 usbd_status
usbd_port_disown_to_1_1(struct usbd_device * dev,int port)342 usbd_port_disown_to_1_1(struct usbd_device *dev, int port)
343 {
344 	usb_port_status_t ps;
345 	usbd_status err;
346 	int n;
347 
348 	err = usbd_set_port_feature(dev, port, UHF_PORT_DISOWN_TO_1_1);
349 	DPRINTF(("%s: port %d disown request done, error=%s\n", __func__,
350 	    port, usbd_errstr(err)));
351 	if (err)
352 		return (err);
353 	n = 10;
354 	do {
355 		/* Wait for device to recover from reset. */
356 		usbd_delay_ms(dev, USB_PORT_RESET_DELAY);
357 		err = usbd_get_port_status(dev, port, &ps);
358 		if (err) {
359 			DPRINTF(("%s: get status failed %d\n", __func__, err));
360 			return (err);
361 		}
362 		/* If the device disappeared, just give up. */
363 		if (!(UGETW(ps.wPortStatus) & UPS_CURRENT_CONNECT_STATUS))
364 			return (USBD_NORMAL_COMPLETION);
365 	} while ((UGETW(ps.wPortChange) & UPS_C_PORT_RESET) == 0 && --n > 0);
366 	if (n == 0)
367 		return (USBD_TIMEOUT);
368 
369 	return (err);
370 }
371 
372 int
usbd_reset_port(struct usbd_device * dev,int port)373 usbd_reset_port(struct usbd_device *dev, int port)
374 {
375 	usb_port_status_t ps;
376 	int n;
377 
378 	if (usbd_set_port_feature(dev, port, UHF_PORT_RESET))
379 		return (EIO);
380 	DPRINTF(("%s: port %d reset done\n", __func__, port));
381 	n = 10;
382 	do {
383 		/* Wait for device to recover from reset. */
384 		usbd_delay_ms(dev, USB_PORT_RESET_DELAY);
385 		if (usbd_get_port_status(dev, port, &ps)) {
386 			DPRINTF(("%s: get status failed\n", __func__));
387 			return (EIO);
388 		}
389 		/* If the device disappeared, just give up. */
390 		if (!(UGETW(ps.wPortStatus) & UPS_CURRENT_CONNECT_STATUS))
391 			return (0);
392 	} while ((UGETW(ps.wPortChange) & UPS_C_PORT_RESET) == 0 && --n > 0);
393 
394 	/* Clear port reset even if a timeout occurred. */
395 	if (usbd_clear_port_feature(dev, port, UHF_C_PORT_RESET)) {
396 		DPRINTF(("%s: clear port feature failed\n", __func__));
397 		return (EIO);
398 	}
399 
400 	if (n == 0)
401 		return (ETIMEDOUT);
402 
403 	/* Wait for the device to recover from reset. */
404 	usbd_delay_ms(dev, USB_PORT_RESET_RECOVERY);
405 	return (0);
406 }
407 
408 usb_interface_descriptor_t *
usbd_find_idesc(usb_config_descriptor_t * cd,int ifaceno,int altno)409 usbd_find_idesc(usb_config_descriptor_t *cd, int ifaceno, int altno)
410 {
411 	char *p = (char *)cd;
412 	char *end = p + UGETW(cd->wTotalLength);
413 	usb_interface_descriptor_t *d;
414 	int curidx, lastidx, curaidx = 0;
415 
416 	for (curidx = lastidx = -1; p < end; ) {
417 		d = (usb_interface_descriptor_t *)p;
418 		DPRINTFN(4,("usbd_find_idesc: ifaceno=%d(%d) altno=%d(%d) "
419 			    "len=%d type=%d\n",
420 			    ifaceno, curidx, altno, curaidx,
421 			    d->bLength, d->bDescriptorType));
422 		if (d->bLength == 0) /* bad descriptor */
423 			break;
424 		p += d->bLength;
425 		if (p <= end && d->bDescriptorType == UDESC_INTERFACE) {
426 			if (d->bInterfaceNumber != lastidx) {
427 				lastidx = d->bInterfaceNumber;
428 				curidx++;
429 				curaidx = 0;
430 			} else
431 				curaidx++;
432 			if (ifaceno == curidx && altno == curaidx)
433 				return (d);
434 		}
435 	}
436 	return (NULL);
437 }
438 
439 usb_endpoint_descriptor_t *
usbd_find_edesc(usb_config_descriptor_t * cd,int ifaceno,int altno,int endptidx)440 usbd_find_edesc(usb_config_descriptor_t *cd, int ifaceno, int altno,
441 		int endptidx)
442 {
443 	char *p = (char *)cd;
444 	char *end = p + UGETW(cd->wTotalLength);
445 	usb_interface_descriptor_t *d;
446 	usb_endpoint_descriptor_t *e;
447 	int curidx;
448 
449 	d = usbd_find_idesc(cd, ifaceno, altno);
450 	if (d == NULL)
451 		return (NULL);
452 	if (endptidx >= d->bNumEndpoints) /* quick exit */
453 		return (NULL);
454 
455 	curidx = -1;
456 	for (p = (char *)d + d->bLength; p < end; ) {
457 		e = (usb_endpoint_descriptor_t *)p;
458 		if (e->bLength == 0) /* bad descriptor */
459 			break;
460 		p += e->bLength;
461 		if (p <= end && e->bDescriptorType == UDESC_INTERFACE)
462 			return (NULL);
463 		if (p <= end && e->bDescriptorType == UDESC_ENDPOINT) {
464 			curidx++;
465 			if (curidx == endptidx)
466 				return (e);
467 		}
468 	}
469 	return (NULL);
470 }
471 
472 usbd_status
usbd_fill_iface_data(struct usbd_device * dev,int ifaceno,int altno)473 usbd_fill_iface_data(struct usbd_device *dev, int ifaceno, int altno)
474 {
475 	struct usbd_interface *ifc = &dev->ifaces[ifaceno];
476 	usb_interface_descriptor_t *idesc;
477 	int nendpt;
478 
479 	DPRINTFN(4,("%s: ifaceno=%d altno=%d\n", __func__, ifaceno, altno));
480 
481 	idesc = usbd_find_idesc(dev->cdesc, ifaceno, altno);
482 	if (idesc == NULL)
483 		return (USBD_INVAL);
484 
485 	nendpt = idesc->bNumEndpoints;
486 	DPRINTFN(4,("%s: found idesc nendpt=%d\n", __func__, nendpt));
487 
488 	ifc->device = dev;
489 	ifc->idesc = idesc;
490 	ifc->index = ifaceno;
491 	ifc->altindex = altno;
492 	ifc->endpoints = NULL;
493 	ifc->priv = NULL;
494 	LIST_INIT(&ifc->pipes);
495 	ifc->nendpt = nendpt;
496 
497 	if (nendpt != 0) {
498 		ifc->endpoints = mallocarray(nendpt, sizeof(*ifc->endpoints),
499 		    M_USB, M_NOWAIT | M_ZERO);
500 		if (ifc->endpoints == NULL)
501 			return (USBD_NOMEM);
502 	}
503 
504 	if (usbd_parse_idesc(dev, ifc)) {
505 		free(ifc->endpoints, M_USB, nendpt * sizeof(*ifc->endpoints));
506 		ifc->endpoints = NULL;
507 		return (USBD_INVAL);
508 	}
509 
510 	return (USBD_NORMAL_COMPLETION);
511 }
512 
513 int
usbd_parse_idesc(struct usbd_device * dev,struct usbd_interface * ifc)514 usbd_parse_idesc(struct usbd_device *dev, struct usbd_interface *ifc)
515 {
516 #define ed ((usb_endpoint_descriptor_t *)p)
517 	char *p, *end;
518 	int i;
519 
520 	p = (char *)ifc->idesc + ifc->idesc->bLength;
521 	end = (char *)dev->cdesc + UGETW(dev->cdesc->wTotalLength);
522 
523 	for (i = 0; i < ifc->idesc->bNumEndpoints; i++) {
524 		for (; p < end; p += ed->bLength) {
525 			if (p + ed->bLength <= end && ed->bLength != 0 &&
526 			    ed->bDescriptorType == UDESC_ENDPOINT)
527 				break;
528 
529 			if (ed->bLength == 0 ||
530 			    ed->bDescriptorType == UDESC_INTERFACE)
531 			    	return (-1);
532 		}
533 
534 		if (p >= end)
535 			return (-1);
536 
537 		if (dev->speed == USB_SPEED_HIGH) {
538 			unsigned int mps;
539 
540 			/* Control and bulk endpoints have max packet limits. */
541 			switch (UE_GET_XFERTYPE(ed->bmAttributes)) {
542 			case UE_CONTROL:
543 				mps = USB_2_MAX_CTRL_PACKET;
544 				goto check;
545 			case UE_BULK:
546 				mps = USB_2_MAX_BULK_PACKET;
547 			check:
548 				if (UGETW(ed->wMaxPacketSize) != mps) {
549 					USETW(ed->wMaxPacketSize, mps);
550 					DPRINTF(("%s: bad max packet size\n",
551 					    __func__));
552 				}
553 				break;
554 			default:
555 				break;
556 			}
557 		}
558 
559 		ifc->endpoints[i].edesc = ed;
560 		ifc->endpoints[i].refcnt = 0;
561 		ifc->endpoints[i].savedtoggle = 0;
562 		p += ed->bLength;
563 	}
564 
565 	return (0);
566 #undef ed
567 }
568 
569 void
usbd_free_iface_data(struct usbd_device * dev,int ifcno)570 usbd_free_iface_data(struct usbd_device *dev, int ifcno)
571 {
572 	struct usbd_interface *ifc = &dev->ifaces[ifcno];
573 
574 	free(ifc->endpoints, M_USB, ifc->nendpt * sizeof(*ifc->endpoints));
575 	ifc->endpoints = NULL;
576 }
577 
578 usbd_status
usbd_set_config(struct usbd_device * dev,int conf)579 usbd_set_config(struct usbd_device *dev, int conf)
580 {
581 	usb_device_request_t req;
582 
583 	req.bmRequestType = UT_WRITE_DEVICE;
584 	req.bRequest = UR_SET_CONFIG;
585 	USETW(req.wValue, conf);
586 	USETW(req.wIndex, 0);
587 	USETW(req.wLength, 0);
588 	return (usbd_do_request(dev, &req, 0));
589 }
590 
591 usbd_status
usbd_set_config_no(struct usbd_device * dev,int no,int msg)592 usbd_set_config_no(struct usbd_device *dev, int no, int msg)
593 {
594 	int index;
595 	usb_config_descriptor_t cd;
596 	usbd_status err;
597 
598 	DPRINTFN(5,("%s: %d\n", __func__, no));
599 	/* Figure out what config index to use. */
600 	for (index = 0; index < dev->ddesc.bNumConfigurations; index++) {
601 		err = usbd_get_desc(dev, UDESC_CONFIG, index,
602 		    USB_CONFIG_DESCRIPTOR_SIZE, &cd);
603 		if (err || cd.bDescriptorType != UDESC_CONFIG)
604 			return (err);
605 		if (cd.bConfigurationValue == no)
606 			return (usbd_set_config_index(dev, index, msg));
607 	}
608 	return (USBD_INVAL);
609 }
610 
611 usbd_status
usbd_set_config_index(struct usbd_device * dev,int index,int msg)612 usbd_set_config_index(struct usbd_device *dev, int index, int msg)
613 {
614 	usb_status_t ds;
615 	usb_config_descriptor_t cd, *cdp;
616 	usbd_status err;
617 	int i, ifcidx, nifc, cdplen, selfpowered, power;
618 
619 	DPRINTFN(5,("%s: dev=%p index=%d\n", __func__, dev, index));
620 
621 	/* XXX check that all interfaces are idle */
622 	if (dev->config != USB_UNCONFIG_NO) {
623 		DPRINTF(("%s: free old config\n", __func__));
624 		/* Free all configuration data structures. */
625 		nifc = dev->cdesc->bNumInterfaces;
626 		for (ifcidx = 0; ifcidx < nifc; ifcidx++)
627 			usbd_free_iface_data(dev, ifcidx);
628 		free(dev->ifaces, M_USB, nifc * sizeof(*dev->ifaces));
629 		free(dev->cdesc, M_USB, UGETW(dev->cdesc->wTotalLength));
630 		dev->ifaces = NULL;
631 		dev->cdesc = NULL;
632 		dev->config = USB_UNCONFIG_NO;
633 	}
634 
635 	if (index == USB_UNCONFIG_INDEX) {
636 		/* We are unconfiguring the device, so leave unallocated. */
637 		DPRINTF(("%s: set config 0\n", __func__));
638 		err = usbd_set_config(dev, USB_UNCONFIG_NO);
639 		if (err)
640 			DPRINTF(("%s: setting config=0 failed, error=%s\n",
641 			    __func__, usbd_errstr(err)));
642 		return (err);
643 	}
644 
645 	/* Get the short descriptor. */
646 	err = usbd_get_desc(dev, UDESC_CONFIG, index,
647 	    USB_CONFIG_DESCRIPTOR_SIZE, &cd);
648 	if (err)
649 		return (err);
650 	if (cd.bDescriptorType != UDESC_CONFIG)
651 		return (USBD_INVAL);
652 	cdplen = UGETW(cd.wTotalLength);
653 	cdp = malloc(cdplen, M_USB, M_NOWAIT);
654 	if (cdp == NULL)
655 		return (USBD_NOMEM);
656 	/* Get the full descriptor. */
657 	for (i = 0; i < 3; i++) {
658 		err = usbd_get_desc(dev, UDESC_CONFIG, index, cdplen, cdp);
659 		if (!err)
660 			break;
661 		usbd_delay_ms(dev, 200);
662 	}
663 	if (err)
664 		goto bad;
665 
666 	if (cdp->bDescriptorType != UDESC_CONFIG) {
667 		DPRINTFN(-1,("%s: bad desc %d\n", __func__,
668 		    cdp->bDescriptorType));
669 		err = USBD_INVAL;
670 		goto bad;
671 	}
672 
673 	/* Figure out if the device is self or bus powered. */
674 	selfpowered = 0;
675 	if (!(dev->quirks->uq_flags & UQ_BUS_POWERED) &&
676 	    (cdp->bmAttributes & UC_SELF_POWERED)) {
677 		/* May be self powered. */
678 		if (cdp->bmAttributes & UC_BUS_POWERED) {
679 			/* Must ask device. */
680 			if (dev->quirks->uq_flags & UQ_POWER_CLAIM) {
681 				/*
682 				 * Hub claims to be self powered, but isn't.
683 				 * It seems that the power status can be
684 				 * determined by the hub characteristics.
685 				 */
686 				usb_hub_descriptor_t hd;
687 				usb_device_request_t req;
688 				req.bmRequestType = UT_READ_CLASS_DEVICE;
689 				req.bRequest = UR_GET_DESCRIPTOR;
690 				USETW(req.wValue, 0);
691 				USETW(req.wIndex, 0);
692 				USETW(req.wLength, USB_HUB_DESCRIPTOR_SIZE);
693 				err = usbd_do_request(dev, &req, &hd);
694 				if (!err &&
695 				    (UGETW(hd.wHubCharacteristics) &
696 				     UHD_PWR_INDIVIDUAL))
697 					selfpowered = 1;
698 				DPRINTF(("%s: charac=0x%04x, error=%s\n",
699 				    __func__, UGETW(hd.wHubCharacteristics),
700 				    usbd_errstr(err)));
701 			} else {
702 				err = usbd_get_device_status(dev, &ds);
703 				if (!err &&
704 				    (UGETW(ds.wStatus) & UDS_SELF_POWERED))
705 					selfpowered = 1;
706 				DPRINTF(("%s: status=0x%04x, error=%s\n",
707 				    __func__, UGETW(ds.wStatus),
708 				    usbd_errstr(err)));
709 			}
710 		} else
711 			selfpowered = 1;
712 	}
713 	DPRINTF(("%s: (addr %d) cno=%d attr=0x%02x, selfpowered=%d, power=%d\n",
714 	    __func__, dev->address, cdp->bConfigurationValue, cdp->bmAttributes,
715 	    selfpowered, cdp->bMaxPower * 2));
716 
717 	/* Check if we have enough power. */
718 #ifdef USB_DEBUG
719 	if (dev->powersrc == NULL) {
720 		DPRINTF(("%s: No power source?\n", __func__));
721 		err = USBD_IOERROR;
722 		goto bad;
723 	}
724 #endif
725 	power = cdp->bMaxPower * 2;
726 	if (power > dev->powersrc->power) {
727 		DPRINTF(("power exceeded %d %d\n", power,dev->powersrc->power));
728 		/* XXX print nicer message. */
729 		if (msg)
730 			printf("%s: device addr %d (config %d) exceeds power "
731 			    "budget, %d mA > %d mA\n",
732 			    dev->bus->bdev.dv_xname, dev->address,
733 			    cdp->bConfigurationValue,
734 			    power, dev->powersrc->power);
735 		err = USBD_NO_POWER;
736 		goto bad;
737 	}
738 	dev->power = power;
739 	dev->self_powered = selfpowered;
740 
741 	/* Set the actual configuration value. */
742 	DPRINTF(("%s: set config %d\n", __func__, cdp->bConfigurationValue));
743 	err = usbd_set_config(dev, cdp->bConfigurationValue);
744 	if (err) {
745 		DPRINTF(("%s: setting config=%d failed, error=%s\n", __func__,
746 		    cdp->bConfigurationValue, usbd_errstr(err)));
747 		goto bad;
748 	}
749 
750 	/* Allocate and fill interface data. */
751 	nifc = cdp->bNumInterfaces;
752 	dev->ifaces = mallocarray(nifc, sizeof(*dev->ifaces), M_USB,
753 	    M_NOWAIT | M_ZERO);
754 	if (dev->ifaces == NULL) {
755 		err = USBD_NOMEM;
756 		goto bad;
757 	}
758 	DPRINTFN(5,("%s: dev=%p cdesc=%p\n", __func__, dev, cdp));
759 	dev->cdesc = cdp;
760 	dev->config = cdp->bConfigurationValue;
761 	for (ifcidx = 0; ifcidx < nifc; ifcidx++) {
762 		err = usbd_fill_iface_data(dev, ifcidx, 0);
763 		if (err)
764 			return (err);
765 	}
766 
767 	return (USBD_NORMAL_COMPLETION);
768 
769  bad:
770 	free(cdp, M_USB, cdplen);
771 	return (err);
772 }
773 
774 /* XXX add function for alternate settings */
775 
776 usbd_status
usbd_setup_pipe(struct usbd_device * dev,struct usbd_interface * iface,struct usbd_endpoint * ep,int ival,struct usbd_pipe ** pipe)777 usbd_setup_pipe(struct usbd_device *dev, struct usbd_interface *iface,
778     struct usbd_endpoint *ep, int ival, struct usbd_pipe **pipe)
779 {
780 	struct usbd_pipe *p;
781 	usbd_status err;
782 
783 	DPRINTF(("%s: dev=%p iface=%p ep=%p pipe=%p\n", __func__,
784 		    dev, iface, ep, pipe));
785 	p = malloc(dev->bus->pipe_size, M_USB, M_NOWAIT|M_ZERO);
786 	if (p == NULL)
787 		return (USBD_NOMEM);
788 	p->pipe_size = dev->bus->pipe_size;
789 	p->device = dev;
790 	p->iface = iface;
791 	p->endpoint = ep;
792 	ep->refcnt++;
793 	p->interval = ival;
794 	SIMPLEQ_INIT(&p->queue);
795 	err = dev->bus->methods->open_pipe(p);
796 	if (err) {
797 		DPRINTF(("%s: endpoint=0x%x failed, error=%s\n", __func__,
798 			 ep->edesc->bEndpointAddress, usbd_errstr(err)));
799 		free(p, M_USB, dev->bus->pipe_size);
800 		return (err);
801 	}
802 	*pipe = p;
803 	return (USBD_NORMAL_COMPLETION);
804 }
805 
806 int
usbd_set_address(struct usbd_device * dev,int addr)807 usbd_set_address(struct usbd_device *dev, int addr)
808 {
809 	usb_device_request_t req;
810 
811 	req.bmRequestType = UT_WRITE_DEVICE;
812 	req.bRequest = UR_SET_ADDRESS;
813 	USETW(req.wValue, addr);
814 	USETW(req.wIndex, 0);
815 	USETW(req.wLength, 0);
816 	if (usbd_do_request(dev, &req, 0))
817 		return (1);
818 
819 	/* Allow device time to set new address */
820 	usbd_delay_ms(dev, USB_SET_ADDRESS_SETTLE);
821 
822 	return (0);
823 }
824 
825 int
usbd_getnewaddr(struct usbd_bus * bus)826 usbd_getnewaddr(struct usbd_bus *bus)
827 {
828 	int addr;
829 
830 	for (addr = 1; addr < USB_MAX_DEVICES; addr++)
831 		if (bus->devices[addr] == NULL)
832 			return (addr);
833 	return (-1);
834 }
835 
836 usbd_status
usbd_probe_and_attach(struct device * parent,struct usbd_device * dev,int port,int addr)837 usbd_probe_and_attach(struct device *parent, struct usbd_device *dev, int port,
838     int addr)
839 {
840 	/*
841 	 * Used to correlate audio and wskbd devices as this is the common point
842 	 * of attachment between the two.
843 	 */
844 	static char *cookie = 0;
845 	struct usb_attach_arg uaa;
846 	usb_device_descriptor_t *dd = &dev->ddesc;
847 	int i, confi, nifaces;
848 	usbd_status err;
849 	struct device *dv;
850 	struct usbd_interface **ifaces;
851 	extern struct rwlock usbpalock;
852 
853 	rw_enter_write(&usbpalock);
854 
855 	uaa.device = dev;
856 	uaa.iface = NULL;
857 	uaa.ifaces = NULL;
858 	uaa.nifaces = 0;
859 	uaa.usegeneric = 0;
860 	uaa.port = port;
861 	uaa.configno = UHUB_UNK_CONFIGURATION;
862 	uaa.ifaceno = UHUB_UNK_INTERFACE;
863 	uaa.vendor = UGETW(dd->idVendor);
864 	uaa.product = UGETW(dd->idProduct);
865 	uaa.release = UGETW(dd->bcdDevice);
866 	uaa.cookie = ++cookie;
867 
868 	/* First try with device specific drivers. */
869 	DPRINTF(("usbd_probe_and_attach trying device specific drivers\n"));
870 	dv = config_found(parent, &uaa, usbd_print);
871 	if (dv) {
872 		dev->subdevs = mallocarray(2, sizeof dv, M_USB, M_NOWAIT);
873 		if (dev->subdevs == NULL) {
874 			err = USBD_NOMEM;
875 			goto fail;
876 		}
877 		dev->nsubdev = 2;
878 		dev->subdevs[dev->ndevs++] = dv;
879 		dev->subdevs[dev->ndevs] = 0;
880 		err = USBD_NORMAL_COMPLETION;
881 		goto fail;
882 	}
883 
884 	DPRINTF(("%s: no device specific driver found\n", __func__));
885 
886 	DPRINTF(("%s: looping over %d configurations\n", __func__,
887 		 dd->bNumConfigurations));
888 	/* Next try with interface drivers. */
889 	for (confi = 0; confi < dd->bNumConfigurations; confi++) {
890 		DPRINTFN(1,("%s: trying config idx=%d\n", __func__,
891 			    confi));
892 		err = usbd_set_config_index(dev, confi, 1);
893 		if (err) {
894 #ifdef USB_DEBUG
895 			DPRINTF(("%s: port %d, set config at addr %d failed, "
896 				 "error=%s\n", parent->dv_xname, port,
897 				 addr, usbd_errstr(err)));
898 #else
899 			printf("%s: port %d, set config %d at addr %d failed\n",
900 			    parent->dv_xname, port, confi, addr);
901 #endif
902 
903  			goto fail;
904 		}
905 		nifaces = dev->cdesc->bNumInterfaces;
906 		uaa.configno = dev->cdesc->bConfigurationValue;
907 		ifaces = mallocarray(nifaces, sizeof(*ifaces), M_USB, M_NOWAIT);
908 		if (ifaces == NULL) {
909 			err = USBD_NOMEM;
910 			goto fail;
911 		}
912 		for (i = 0; i < nifaces; i++)
913 			ifaces[i] = &dev->ifaces[i];
914 		uaa.ifaces = ifaces;
915 		uaa.nifaces = nifaces;
916 
917 		/* add 1 for possible ugen and 1 for NULL terminator */
918 		dev->subdevs = mallocarray(nifaces + 2, sizeof(dv), M_USB,
919 		    M_NOWAIT | M_ZERO);
920 		if (dev->subdevs == NULL) {
921 			free(ifaces, M_USB, nifaces * sizeof(*ifaces));
922 			err = USBD_NOMEM;
923 			goto fail;
924 		}
925 		dev->nsubdev = nifaces + 2;
926 
927 		for (i = 0; i < nifaces; i++) {
928 			if (usbd_iface_claimed(dev, i))
929 				continue;
930 			uaa.iface = ifaces[i];
931 			uaa.ifaceno = ifaces[i]->idesc->bInterfaceNumber;
932 			dv = config_found(parent, &uaa, usbd_print);
933 			if (dv != NULL) {
934 				dev->subdevs[dev->ndevs++] = dv;
935 				usbd_claim_iface(dev, i);
936 			}
937 		}
938 		free(ifaces, M_USB, nifaces * sizeof(*ifaces));
939 
940 		if (dev->ndevs > 0) {
941 			for (i = 0; i < nifaces; i++) {
942 				if (!usbd_iface_claimed(dev, i))
943 					break;
944 			}
945 			if (i < nifaces)
946 				goto generic;
947 			 else
948 				goto fail;
949 		}
950 
951 		free(dev->subdevs, M_USB, dev->nsubdev * sizeof(*dev->subdevs));
952 		dev->subdevs = NULL;
953 		dev->nsubdev = 0;
954 	}
955 	/* No interfaces were attached in any of the configurations. */
956 
957 	if (dd->bNumConfigurations > 1) /* don't change if only 1 config */
958 		usbd_set_config_index(dev, 0, 0);
959 
960 	DPRINTF(("%s: no interface drivers found\n", __func__));
961 
962 generic:
963 	/* Finally try the generic driver. */
964 	uaa.iface = NULL;
965 	uaa.usegeneric = 1;
966 	uaa.configno = dev->ndevs == 0 ? UHUB_UNK_CONFIGURATION :
967 	    dev->cdesc->bConfigurationValue;
968 	uaa.ifaceno = UHUB_UNK_INTERFACE;
969 	dv = config_found(parent, &uaa, usbd_print);
970 	if (dv != NULL) {
971 		if (dev->ndevs == 0) {
972 			dev->subdevs = mallocarray(2, sizeof dv, M_USB, M_NOWAIT);
973 			if (dev->subdevs == NULL) {
974 				err = USBD_NOMEM;
975 				goto fail;
976 			}
977 			dev->nsubdev = 2;
978 		}
979 		dev->subdevs[dev->ndevs++] = dv;
980 		dev->subdevs[dev->ndevs] = 0;
981 		err = USBD_NORMAL_COMPLETION;
982 		goto fail;
983 	}
984 
985 	/*
986 	 * The generic attach failed, but leave the device as it is.
987 	 * We just did not find any drivers, that's all.  The device is
988 	 * fully operational and not harming anyone.
989 	 */
990 	DPRINTF(("%s: generic attach failed\n", __func__));
991  	err = USBD_NORMAL_COMPLETION;
992 fail:
993 	rw_exit_write(&usbpalock);
994 	return (err);
995 }
996 
997 
998 /*
999  * Called when a new device has been put in the powered state,
1000  * but not yet in the addressed state.
1001  * Get initial descriptor, set the address, get full descriptor,
1002  * and attach a driver.
1003  */
1004 usbd_status
usbd_new_device(struct device * parent,struct usbd_bus * bus,int depth,int speed,int port,struct usbd_port * up)1005 usbd_new_device(struct device *parent, struct usbd_bus *bus, int depth,
1006 		int speed, int port, struct usbd_port *up)
1007 {
1008 	struct usbd_device *dev, *adev, *hub;
1009 	usb_device_descriptor_t *dd;
1010 	usbd_status err;
1011 	uint32_t mps, mps0;
1012 	int addr, i, p;
1013 
1014 	DPRINTF(("%s: bus=%p port=%d depth=%d speed=%d\n", __func__,
1015 		 bus, port, depth, speed));
1016 
1017 	/*
1018 	 * Fixed size for ep0 max packet, FULL device variable size is
1019 	 * handled below.
1020 	 */
1021 	switch (speed) {
1022 	case USB_SPEED_LOW:
1023 		mps0 = 8;
1024 		break;
1025 	case USB_SPEED_HIGH:
1026 	case USB_SPEED_FULL:
1027 		mps0 = 64;
1028 		break;
1029 	case USB_SPEED_SUPER:
1030 		mps0 = 512;
1031 		break;
1032 	default:
1033 		return (USBD_INVAL);
1034 	}
1035 
1036 	addr = usbd_getnewaddr(bus);
1037 	if (addr < 0) {
1038 		printf("%s: No free USB addresses, new device ignored.\n",
1039 		    bus->bdev.dv_xname);
1040 		return (USBD_NO_ADDR);
1041 	}
1042 
1043 	dev = malloc(sizeof *dev, M_USB, M_NOWAIT | M_ZERO);
1044 	if (dev == NULL)
1045 		return (USBD_NOMEM);
1046 
1047 	dev->bus = bus;
1048 
1049 	/* Set up default endpoint handle. */
1050 	dev->def_ep.edesc = &dev->def_ep_desc;
1051 
1052 	/* Set up default endpoint descriptor. */
1053 	dev->def_ep_desc.bLength = USB_ENDPOINT_DESCRIPTOR_SIZE;
1054 	dev->def_ep_desc.bDescriptorType = UDESC_ENDPOINT;
1055 	dev->def_ep_desc.bEndpointAddress = USB_CONTROL_ENDPOINT;
1056 	dev->def_ep_desc.bmAttributes = UE_CONTROL;
1057 	dev->def_ep_desc.bInterval = 0;
1058 	USETW(dev->def_ep_desc.wMaxPacketSize, mps0);
1059 
1060 	dev->quirks = &usbd_no_quirk;
1061 	dev->address = USB_START_ADDR;
1062 	dev->ddesc.bMaxPacketSize = 0;
1063 	dev->depth = depth;
1064 	dev->powersrc = up;
1065 	dev->myhub = up->parent;
1066 	dev->speed = speed;
1067 	dev->langid = USBD_NOLANG;
1068 
1069 	up->device = dev;
1070 
1071 	/* Locate port on upstream high speed hub */
1072 	for (adev = dev, hub = up->parent;
1073 	    hub != NULL && hub->speed != USB_SPEED_HIGH;
1074 	    adev = hub, hub = hub->myhub)
1075 		;
1076 	if (hub) {
1077 		for (p = 0; p < hub->hub->nports; p++) {
1078 			if (hub->hub->ports[p].device == adev) {
1079 				dev->myhsport = &hub->hub->ports[p];
1080 				goto found;
1081 			}
1082 		}
1083 		panic("usbd_new_device: cannot find HS port");
1084 	found:
1085 		DPRINTFN(1,("%s: high speed port %d\n", __func__, p));
1086 	} else {
1087 		dev->myhsport = NULL;
1088 	}
1089 
1090 	/* Establish the default pipe. */
1091 	err = usbd_setup_pipe(dev, 0, &dev->def_ep, USBD_DEFAULT_INTERVAL,
1092 	    &dev->default_pipe);
1093 	if (err)
1094 		goto fail;
1095 
1096 	dd = &dev->ddesc;
1097 
1098 	/* Try to get device descriptor */
1099 	/*
1100 	 * some device will need small size query at first (XXX: out of spec)
1101 	 * we will get full size descriptor later, just determine the maximum
1102 	 * packet size of the control pipe at this moment.
1103 	 */
1104 	for (i = 0; i < 3; i++) {
1105 		/* Get the first 8 bytes of the device descriptor. */
1106 		/* 8 byte is magic size, some device only return 8 byte for 1st
1107 		 * query (XXX: out of spec) */
1108 		err = usbd_get_desc(dev, UDESC_DEVICE, 0, USB_MAX_IPACKET, dd);
1109 		if (!err)
1110 			break;
1111 		if (err == USBD_TIMEOUT)
1112 			goto fail;
1113 		usbd_delay_ms(dev, 100+50*i);
1114 	}
1115 
1116 	/* some device need actual size request for the query. try again */
1117 	if (err) {
1118 		USETW(dev->def_ep_desc.wMaxPacketSize,
1119 			USB_DEVICE_DESCRIPTOR_SIZE);
1120 		usbd_reset_port(up->parent, port);
1121 		for (i = 0; i < 3; i++) {
1122 			err = usbd_get_desc(dev, UDESC_DEVICE, 0,
1123 				USB_DEVICE_DESCRIPTOR_SIZE, dd);
1124 			if (!err)
1125 				break;
1126 			if (err == USBD_TIMEOUT)
1127 				goto fail;
1128 			usbd_delay_ms(dev, 100+50*i);
1129 		}
1130 	}
1131 
1132 	/* XXX some devices need more time to wake up */
1133 	if (err) {
1134 		USETW(dev->def_ep_desc.wMaxPacketSize, USB_MAX_IPACKET);
1135 		usbd_reset_port(up->parent, port);
1136 		usbd_delay_ms(dev, 500);
1137 		err = usbd_get_desc(dev, UDESC_DEVICE, 0,
1138 			USB_MAX_IPACKET, dd);
1139 	}
1140 
1141 	if (err)
1142 		goto fail;
1143 
1144 	DPRINTF(("%s: adding unit addr=%d, rev=%02x, class=%d, subclass=%d, "
1145 		 "protocol=%d, maxpacket=%d, len=%d, speed=%d\n", __func__,
1146 		 addr,UGETW(dd->bcdUSB), dd->bDeviceClass, dd->bDeviceSubClass,
1147 		 dd->bDeviceProtocol, dd->bMaxPacketSize, dd->bLength,
1148 		 dev->speed));
1149 
1150 	if ((dd->bDescriptorType != UDESC_DEVICE) ||
1151 	    (dd->bLength < USB_DEVICE_DESCRIPTOR_SIZE)) {
1152 		err = USBD_INVAL;
1153 		goto fail;
1154 	}
1155 
1156 	mps = dd->bMaxPacketSize;
1157 	if (speed == USB_SPEED_SUPER) {
1158 		if (mps == 0xff)
1159 			mps = 9;
1160 		/* xHCI Section 4.8.2.1 */
1161 		mps = (1 << mps);
1162 	}
1163 
1164 	if (mps != mps0) {
1165 		if ((speed == USB_SPEED_LOW) ||
1166 		    (mps != 8 && mps != 16 && mps != 32 && mps != 64)) {
1167 			err = USBD_INVAL;
1168 			goto fail;
1169 		}
1170 		USETW(dev->def_ep_desc.wMaxPacketSize, mps);
1171 	}
1172 
1173 
1174 	/* Set the address if the HC didn't do it already. */
1175 	if (bus->methods->dev_setaddr != NULL &&
1176 	    bus->methods->dev_setaddr(dev, addr)) {
1177 		err = USBD_SET_ADDR_FAILED;
1178 		goto fail;
1179  	}
1180 
1181 	/* Wait for device to settle before reloading the descriptor. */
1182 	usbd_delay_ms(dev, 10);
1183 
1184 	/*
1185 	 * If this device is attached to an xHCI controller, this
1186 	 * address does not correspond to the hardware one.
1187 	 */
1188 	dev->address = addr;
1189 
1190 	err = usbd_reload_device_desc(dev);
1191 	if (err)
1192 		goto fail;
1193 
1194 	/* send disown request to handover 2.0 to 1.1. */
1195 	if (dev->quirks->uq_flags & UQ_EHCI_NEEDTO_DISOWN) {
1196 		/* only effective when the target device is on ehci */
1197 		if (dev->bus->usbrev == USBREV_2_0) {
1198 			DPRINTF(("%s: disown request issues to dev:%p on usb2.0 bus\n",
1199 				__func__, dev));
1200 			usbd_port_disown_to_1_1(dev->myhub, port);
1201 			/* reset_port required to finish disown request */
1202 			usbd_reset_port(dev->myhub, port);
1203   			return (USBD_NORMAL_COMPLETION);
1204 		}
1205 	}
1206 
1207 	/* Assume 100mA bus powered for now. Changed when configured. */
1208 	dev->power = USB_MIN_POWER;
1209 	dev->self_powered = 0;
1210 
1211 	DPRINTF(("%s: new dev (addr %d), dev=%p, parent=%p\n", __func__,
1212 		 addr, dev, parent));
1213 
1214 	/* Get device info and cache it */
1215 	err = usbd_cache_devinfo(dev);
1216 	if (err)
1217 		goto fail;
1218 
1219 	bus->devices[addr] = dev;
1220 
1221 	err = usbd_probe_and_attach(parent, dev, port, addr);
1222 	if (err)
1223 		goto fail;
1224 
1225   	return (USBD_NORMAL_COMPLETION);
1226 
1227 fail:
1228 	usb_free_device(dev);
1229 	up->device = NULL;
1230 	return (err);
1231 }
1232 
1233 usbd_status
usbd_reload_device_desc(struct usbd_device * dev)1234 usbd_reload_device_desc(struct usbd_device *dev)
1235 {
1236 	usbd_status err;
1237 
1238 	/* Get the full device descriptor. */
1239 	err = usbd_get_desc(dev, UDESC_DEVICE, 0,
1240 		USB_DEVICE_DESCRIPTOR_SIZE, &dev->ddesc);
1241 	if (err)
1242 		return (err);
1243 
1244 	/* Figure out what's wrong with this device. */
1245 	dev->quirks = usbd_find_quirk(&dev->ddesc);
1246 
1247 	return (USBD_NORMAL_COMPLETION);
1248 }
1249 
1250 int
usbd_print(void * aux,const char * pnp)1251 usbd_print(void *aux, const char *pnp)
1252 {
1253 	struct usb_attach_arg *uaa = aux;
1254 	char *devinfop;
1255 
1256 	devinfop = malloc(DEVINFOSIZE, M_TEMP, M_WAITOK);
1257 	usbd_devinfo(uaa->device, 0, devinfop, DEVINFOSIZE);
1258 
1259 	DPRINTFN(15, ("usbd_print dev=%p\n", uaa->device));
1260 	if (pnp) {
1261 		if (!uaa->usegeneric) {
1262 			free(devinfop, M_TEMP, DEVINFOSIZE);
1263 			return (QUIET);
1264 		}
1265 		printf("%s at %s", devinfop, pnp);
1266 	}
1267 	if (uaa->port != 0)
1268 		printf(" port %d", uaa->port);
1269 	if (uaa->configno != UHUB_UNK_CONFIGURATION)
1270 		printf(" configuration %d", uaa->configno);
1271 	if (uaa->ifaceno != UHUB_UNK_INTERFACE)
1272 		printf(" interface %d", uaa->ifaceno);
1273 
1274 	if (!pnp)
1275 		printf(" %s\n", devinfop);
1276 	free(devinfop, M_TEMP, DEVINFOSIZE);
1277 	return (UNCONF);
1278 }
1279 
1280 void
usbd_fill_deviceinfo(struct usbd_device * dev,struct usb_device_info * di)1281 usbd_fill_deviceinfo(struct usbd_device *dev, struct usb_device_info *di)
1282 {
1283 	struct usbd_port *p;
1284 	int i;
1285 
1286 	di->udi_bus = dev->bus->usbctl->dv_unit;
1287 	di->udi_addr = dev->address;
1288 	strlcpy(di->udi_vendor, dev->vendor, sizeof(di->udi_vendor));
1289 	strlcpy(di->udi_product, dev->product, sizeof(di->udi_product));
1290 	usbd_printBCD(di->udi_release, sizeof di->udi_release,
1291 	    UGETW(dev->ddesc.bcdDevice));
1292 	di->udi_vendorNo = UGETW(dev->ddesc.idVendor);
1293 	di->udi_productNo = UGETW(dev->ddesc.idProduct);
1294 	di->udi_releaseNo = UGETW(dev->ddesc.bcdDevice);
1295 	di->udi_class = dev->ddesc.bDeviceClass;
1296 	di->udi_subclass = dev->ddesc.bDeviceSubClass;
1297 	di->udi_protocol = dev->ddesc.bDeviceProtocol;
1298 	di->udi_config = dev->config;
1299 	di->udi_power = dev->self_powered ? 0 : dev->power;
1300 	di->udi_speed = dev->speed;
1301 	di->udi_port = dev->powersrc ? dev->powersrc->portno : 0;
1302 
1303 	if (dev->subdevs != NULL) {
1304 		for (i = 0; dev->subdevs[i] && i < USB_MAX_DEVNAMES; i++) {
1305 			strncpy(di->udi_devnames[i],
1306 			    dev->subdevs[i]->dv_xname, USB_MAX_DEVNAMELEN);
1307 			di->udi_devnames[i][USB_MAX_DEVNAMELEN-1] = '\0';
1308 		}
1309 	} else
1310 		i = 0;
1311 
1312 	for (/*i is set */; i < USB_MAX_DEVNAMES; i++)
1313 		di->udi_devnames[i][0] = 0; /* empty */
1314 
1315 	if (dev->hub) {
1316 		for (i = 0;
1317 		    i < nitems(di->udi_ports) && i < dev->hub->nports; i++) {
1318 			p = &dev->hub->ports[i];
1319 			di->udi_ports[i] = UGETW(p->status.wPortChange) << 16 |
1320 			    UGETW(p->status.wPortStatus);
1321 		}
1322 		di->udi_nports = dev->hub->nports;
1323 	} else
1324 		di->udi_nports = 0;
1325 
1326 	bzero(di->udi_serial, sizeof(di->udi_serial));
1327 	if (dev->serial != NULL)
1328 		strlcpy(di->udi_serial, dev->serial,
1329 		    sizeof(di->udi_serial));
1330 }
1331 
1332 int
usbd_get_routestring(struct usbd_device * dev,uint32_t * route)1333 usbd_get_routestring(struct usbd_device *dev, uint32_t *route)
1334 {
1335 	struct usbd_device *hub;
1336 	uint32_t r;
1337 	uint8_t port;
1338 
1339 	/*
1340 	 * Calculate the Route String.  Assume that there is no hub with
1341 	 * more than 15 ports and that they all have a depth < 6.  See
1342 	 * section 8.9 of USB 3.1 Specification for more details.
1343 	 */
1344 	r = dev->powersrc ? dev->powersrc->portno : 0;
1345 	for (hub = dev->myhub; hub && hub->depth > 1; hub = hub->myhub) {
1346 		port = hub->powersrc ? hub->powersrc->portno : 0;
1347 		if (port > 15)
1348 			return -1;
1349 		r <<= 4;
1350 		r |= port;
1351 	}
1352 
1353 	/* Add in the host root port, of which there may be 255. */
1354 	port = (hub && hub->powersrc) ? hub->powersrc->portno : 0;
1355 	r <<= 8;
1356 	r |= port;
1357 
1358 	*route = r;
1359 	return 0;
1360 }
1361 
1362 int
usbd_get_location(struct usbd_device * dev,struct usbd_interface * iface,uint8_t * bus,uint32_t * route,uint8_t * ifaceno)1363 usbd_get_location(struct usbd_device *dev, struct usbd_interface *iface,
1364     uint8_t *bus, uint32_t *route, uint8_t *ifaceno)
1365 {
1366 	int i;
1367 	uint32_t r;
1368 
1369 	if (dev == NULL || usbd_is_dying(dev) ||
1370 	    dev->cdesc == NULL ||
1371 	    dev->cdesc->bNumInterfaces == 0 ||
1372 	    dev->bus == NULL ||
1373 	    dev->bus->usbctl == NULL ||
1374 	    dev->myhub == NULL ||
1375 	    dev->powersrc == NULL)
1376 		return -1;
1377 
1378 	for(i = 0; i < dev->cdesc->bNumInterfaces; i++) {
1379 		if (iface == &dev->ifaces[i]) {
1380 			*bus = dev->bus->usbctl->dv_unit;
1381 			*route = (usbd_get_routestring(dev, &r)) ? 0 : r;
1382 			*ifaceno = i;
1383 			return 0;
1384 		}
1385 	}
1386 
1387 	return -1;
1388 }
1389 
1390 /* Retrieve a complete descriptor for a certain device and index. */
1391 usb_config_descriptor_t *
usbd_get_cdesc(struct usbd_device * dev,int index,u_int * lenp)1392 usbd_get_cdesc(struct usbd_device *dev, int index, u_int *lenp)
1393 {
1394 	usb_config_descriptor_t *cdesc, *tdesc, cdescr;
1395 	u_int len;
1396 	usbd_status err;
1397 
1398 	if (index == USB_CURRENT_CONFIG_INDEX) {
1399 		tdesc = usbd_get_config_descriptor(dev);
1400 		if (tdesc == NULL)
1401 			return (NULL);
1402 		len = UGETW(tdesc->wTotalLength);
1403 		if (lenp)
1404 			*lenp = len;
1405 		cdesc = malloc(len, M_TEMP, M_WAITOK);
1406 		memcpy(cdesc, tdesc, len);
1407 		DPRINTFN(5,("%s: current, len=%u\n", __func__, len));
1408 	} else {
1409 		err = usbd_get_desc(dev, UDESC_CONFIG, index,
1410 		    USB_CONFIG_DESCRIPTOR_SIZE, &cdescr);
1411 		if (err || cdescr.bDescriptorType != UDESC_CONFIG)
1412 			return (NULL);
1413 		len = UGETW(cdescr.wTotalLength);
1414 		DPRINTFN(5,("%s: index=%d, len=%u\n", __func__, index, len));
1415 		if (lenp)
1416 			*lenp = len;
1417 		cdesc = malloc(len, M_TEMP, M_WAITOK);
1418 		err = usbd_get_desc(dev, UDESC_CONFIG, index, len, cdesc);
1419 		if (err) {
1420 			free(cdesc, M_TEMP, len);
1421 			return (NULL);
1422 		}
1423 	}
1424 	return (cdesc);
1425 }
1426 
1427 void
usb_free_device(struct usbd_device * dev)1428 usb_free_device(struct usbd_device *dev)
1429 {
1430 	int ifcidx, nifc;
1431 
1432 	DPRINTF(("%s: %p\n", __func__, dev));
1433 
1434 	if (dev->default_pipe != NULL)
1435 		usbd_close_pipe(dev->default_pipe);
1436 	if (dev->ifaces != NULL) {
1437 		nifc = dev->cdesc->bNumInterfaces;
1438 		for (ifcidx = 0; ifcidx < nifc; ifcidx++)
1439 			usbd_free_iface_data(dev, ifcidx);
1440 		free(dev->ifaces, M_USB, nifc * sizeof(*dev->ifaces));
1441 	}
1442 	if (dev->cdesc != NULL)
1443 		free(dev->cdesc, M_USB, UGETW(dev->cdesc->wTotalLength));
1444 	free(dev->subdevs, M_USB, dev->nsubdev * sizeof(*dev->subdevs));
1445 	dev->bus->devices[dev->address] = NULL;
1446 
1447 	if (dev->vendor != NULL)
1448 		free(dev->vendor, M_USB, USB_MAX_STRING_LEN);
1449 	if (dev->product != NULL)
1450 		free(dev->product, M_USB, USB_MAX_STRING_LEN);
1451 	if (dev->serial != NULL)
1452 		free(dev->serial, M_USB, USB_MAX_STRING_LEN);
1453 
1454 	free(dev, M_USB, sizeof *dev);
1455 }
1456 
1457 /*
1458  * Should only be called by the USB thread doing bus exploration to
1459  * avoid connect/disconnect races.
1460  */
1461 int
usbd_detach(struct usbd_device * dev,struct device * parent)1462 usbd_detach(struct usbd_device *dev, struct device *parent)
1463 {
1464 	int i, rv = 0;
1465 
1466 	usbd_deactivate(dev);
1467 
1468 	if (dev->ndevs > 0) {
1469 		for (i = 0; dev->subdevs[i] != NULL; i++)
1470 			rv |= config_detach(dev->subdevs[i], DETACH_FORCE);
1471 	}
1472 
1473 	if (rv == 0)
1474 		usb_free_device(dev);
1475 
1476 	return (rv);
1477 }
1478