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