xref: /freebsd/sys/dev/usb/usb_hub.c (revision 7dce26eded4e4c8a511ecc7e8522b9a0332386ea)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 1998 The NetBSD Foundation, Inc. All rights reserved.
5  * Copyright (c) 1998 Lennart Augustsson. All rights reserved.
6  * Copyright (c) 2008-2022 Hans Petter Selasky
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 /*
31  * USB spec: http://www.usb.org/developers/docs/usbspec.zip
32  */
33 
34 #ifdef USB_GLOBAL_INCLUDE_FILE
35 #include USB_GLOBAL_INCLUDE_FILE
36 #else
37 #include <sys/stdint.h>
38 #include <sys/stddef.h>
39 #include <sys/param.h>
40 #include <sys/queue.h>
41 #include <sys/types.h>
42 #include <sys/systm.h>
43 #include <sys/kernel.h>
44 #include <sys/bus.h>
45 #include <sys/module.h>
46 #include <sys/lock.h>
47 #include <sys/mutex.h>
48 #include <sys/condvar.h>
49 #include <sys/sbuf.h>
50 #include <sys/sysctl.h>
51 #include <sys/sx.h>
52 #include <sys/unistd.h>
53 #include <sys/callout.h>
54 #include <sys/malloc.h>
55 #include <sys/priv.h>
56 
57 #include <dev/usb/usb.h>
58 #include <dev/usb/usbdi.h>
59 #include <dev/usb/usbdi_util.h>
60 
61 #define	USB_DEBUG_VAR uhub_debug
62 
63 #include <dev/usb/usb_core.h>
64 #include <dev/usb/usb_process.h>
65 #include <dev/usb/usb_device.h>
66 #include <dev/usb/usb_request.h>
67 #include <dev/usb/usb_debug.h>
68 #include <dev/usb/usb_hub.h>
69 #include <dev/usb/usb_util.h>
70 #include <dev/usb/usb_busdma.h>
71 #include <dev/usb/usb_transfer.h>
72 #include <dev/usb/usb_dynamic.h>
73 
74 #include <dev/usb/usb_controller.h>
75 #include <dev/usb/usb_bus.h>
76 #endif			/* USB_GLOBAL_INCLUDE_FILE */
77 
78 #include <dev/usb/usb_hub_private.h>
79 
80 #ifdef USB_DEBUG
81 static int uhub_debug = 0;
82 
83 static SYSCTL_NODE(_hw_usb, OID_AUTO, uhub, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
84     "USB HUB");
85 SYSCTL_INT(_hw_usb_uhub, OID_AUTO, debug, CTLFLAG_RWTUN, &uhub_debug, 0,
86     "Debug level");
87 #endif
88 
89 #if USB_HAVE_POWERD
90 static int usb_power_timeout = 30;	/* seconds */
91 
92 SYSCTL_INT(_hw_usb, OID_AUTO, power_timeout, CTLFLAG_RWTUN,
93     &usb_power_timeout, 0, "USB power timeout");
94 #endif
95 
96 #if USB_HAVE_DISABLE_ENUM
97 static int usb_disable_enumeration = 0;
98 SYSCTL_INT(_hw_usb, OID_AUTO, disable_enumeration, CTLFLAG_RWTUN,
99     &usb_disable_enumeration, 0, "Set to disable all USB device enumeration. "
100 	"This can secure against USB devices turning evil, "
101 	"for example a USB memory stick becoming a USB keyboard.");
102 
103 static int usb_disable_port_power = 0;
104 SYSCTL_INT(_hw_usb, OID_AUTO, disable_port_power, CTLFLAG_RWTUN,
105     &usb_disable_port_power, 0, "Set to disable all USB port power.");
106 #endif
107 
108 #define	UHUB_PROTO(sc) ((sc)->sc_udev->ddesc.bDeviceProtocol)
109 #define	UHUB_IS_HIGH_SPEED(sc) (UHUB_PROTO(sc) != UDPROTO_FSHUB)
110 #define	UHUB_IS_SINGLE_TT(sc) (UHUB_PROTO(sc) == UDPROTO_HSHUBSTT)
111 #define	UHUB_IS_MULTI_TT(sc) (UHUB_PROTO(sc) == UDPROTO_HSHUBMTT)
112 #define	UHUB_IS_SUPER_SPEED(sc) (UHUB_PROTO(sc) == UDPROTO_SSHUB)
113 
114 /* prototypes for type checking: */
115 
116 static device_suspend_t uhub_suspend;
117 static device_resume_t uhub_resume;
118 
119 static bus_driver_added_t uhub_driver_added;
120 static bus_child_pnpinfo_t uhub_child_pnpinfo;
121 
122 static usb_callback_t uhub_intr_callback;
123 #if USB_HAVE_TT_SUPPORT
124 static usb_callback_t uhub_reset_tt_callback;
125 #endif
126 
127 static void usb_dev_resume_peer(struct usb_device *udev);
128 static void usb_dev_suspend_peer(struct usb_device *udev);
129 static uint8_t usb_peer_should_wakeup(struct usb_device *udev);
130 
131 static const struct usb_config uhub_config[UHUB_N_TRANSFER] = {
132 	[UHUB_INTR_TRANSFER] = {
133 		.type = UE_INTERRUPT,
134 		.endpoint = UE_ADDR_ANY,
135 		.direction = UE_DIR_ANY,
136 		.timeout = 0,
137 		.flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
138 		.bufsize = 0,	/* use wMaxPacketSize */
139 		.callback = &uhub_intr_callback,
140 		.interval = UHUB_INTR_INTERVAL,
141 	},
142 #if USB_HAVE_TT_SUPPORT
143 	[UHUB_RESET_TT_TRANSFER] = {
144 		.type = UE_CONTROL,
145 		.endpoint = 0x00,	/* Control pipe */
146 		.direction = UE_DIR_ANY,
147 		.bufsize = sizeof(struct usb_device_request),
148 		.callback = &uhub_reset_tt_callback,
149 		.timeout = 1000,	/* 1 second */
150 		.usb_mode = USB_MODE_HOST,
151 	},
152 #endif
153 };
154 
155 /*
156  * driver instance for "hub" connected to "usb"
157  * and "hub" connected to "hub"
158  */
159 static device_method_t uhub_methods[] = {
160 	DEVMETHOD(device_probe, uhub_probe),
161 	DEVMETHOD(device_attach, uhub_attach),
162 	DEVMETHOD(device_detach, uhub_detach),
163 
164 	DEVMETHOD(device_suspend, uhub_suspend),
165 	DEVMETHOD(device_resume, uhub_resume),
166 
167 	DEVMETHOD(bus_child_location, uhub_child_location),
168 	DEVMETHOD(bus_child_pnpinfo, uhub_child_pnpinfo),
169 	DEVMETHOD(bus_get_device_path, uhub_get_device_path),
170 	DEVMETHOD(bus_driver_added, uhub_driver_added),
171 	DEVMETHOD_END
172 };
173 
174 driver_t uhub_driver = {
175 	.name = "uhub",
176 	.methods = uhub_methods,
177 	.size = sizeof(struct uhub_softc)
178 };
179 
180 DRIVER_MODULE(uhub, usbus, uhub_driver, 0, 0);
181 DRIVER_MODULE(uhub, uhub, uhub_driver, 0, 0);
182 MODULE_VERSION(uhub, 1);
183 
184 static void
uhub_intr_callback(struct usb_xfer * xfer,usb_error_t error)185 uhub_intr_callback(struct usb_xfer *xfer, usb_error_t error)
186 {
187 	struct uhub_softc *sc = usbd_xfer_softc(xfer);
188 
189 	switch (USB_GET_STATE(xfer)) {
190 	case USB_ST_TRANSFERRED:
191 		DPRINTFN(2, "\n");
192 		/*
193 		 * This is an indication that some port
194 		 * has changed status. Notify the bus
195 		 * event handler thread that we need
196 		 * to be explored again:
197 		 */
198 		usb_needs_explore(sc->sc_udev->bus, 0);
199 
200 	case USB_ST_SETUP:
201 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
202 		usbd_transfer_submit(xfer);
203 		break;
204 
205 	default:			/* Error */
206 		if (xfer->error != USB_ERR_CANCELLED) {
207 			/*
208 			 * Do a clear-stall. The "stall_pipe" flag
209 			 * will get cleared before next callback by
210 			 * the USB stack.
211 			 */
212 			usbd_xfer_set_stall(xfer);
213 			usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
214 			usbd_transfer_submit(xfer);
215 		}
216 		break;
217 	}
218 }
219 
220 /*------------------------------------------------------------------------*
221  *      uhub_reset_tt_proc
222  *
223  * This function starts the TT reset USB request
224  *------------------------------------------------------------------------*/
225 #if USB_HAVE_TT_SUPPORT
226 static void
uhub_reset_tt_proc(struct usb_proc_msg * _pm)227 uhub_reset_tt_proc(struct usb_proc_msg *_pm)
228 {
229 	struct usb_udev_msg *pm = (void *)_pm;
230 	struct usb_device *udev = pm->udev;
231 	struct usb_hub *hub;
232 	struct uhub_softc *sc;
233 
234 	hub = udev->hub;
235 	if (hub == NULL)
236 		return;
237 	sc = hub->hubsoftc;
238 	if (sc == NULL)
239 		return;
240 
241 	/* Change lock */
242 	USB_BUS_UNLOCK(udev->bus);
243 	USB_MTX_LOCK(&sc->sc_mtx);
244 	/* Start transfer */
245 	usbd_transfer_start(sc->sc_xfer[UHUB_RESET_TT_TRANSFER]);
246 	/* Change lock */
247 	USB_MTX_UNLOCK(&sc->sc_mtx);
248 	USB_BUS_LOCK(udev->bus);
249 }
250 #endif
251 
252 /*------------------------------------------------------------------------*
253  *      uhub_tt_buffer_reset_async_locked
254  *
255  * This function queues a TT reset for the given USB device and endpoint.
256  *------------------------------------------------------------------------*/
257 #if USB_HAVE_TT_SUPPORT
258 void
uhub_tt_buffer_reset_async_locked(struct usb_device * child,struct usb_endpoint * ep)259 uhub_tt_buffer_reset_async_locked(struct usb_device *child, struct usb_endpoint *ep)
260 {
261 	struct usb_device_request req;
262 	struct usb_device *udev;
263 	struct usb_hub *hub;
264 	struct usb_port *up;
265 	uint16_t wValue;
266 	uint8_t port;
267 
268 	if (child == NULL || ep == NULL)
269 		return;
270 
271 	udev = child->parent_hs_hub;
272 	port = child->hs_port_no;
273 
274 	if (udev == NULL)
275 		return;
276 
277 	hub = udev->hub;
278 	if ((hub == NULL) ||
279 	    (udev->speed != USB_SPEED_HIGH) ||
280 	    (child->speed != USB_SPEED_LOW &&
281 	     child->speed != USB_SPEED_FULL) ||
282 	    (child->flags.usb_mode != USB_MODE_HOST) ||
283 	    (port == 0) || (ep->edesc == NULL)) {
284 		/* not applicable */
285 		return;
286 	}
287 
288 	USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED);
289 
290 	up = hub->ports + port - 1;
291 
292 	if (udev->ddesc.bDeviceClass == UDCLASS_HUB &&
293 	    udev->ddesc.bDeviceProtocol == UDPROTO_HSHUBSTT)
294 		port = 1;
295 
296 	/* if we already received a clear buffer request, reset the whole TT */
297 	if (up->req_reset_tt.bRequest != 0) {
298 		req.bmRequestType = UT_WRITE_CLASS_OTHER;
299 		req.bRequest = UR_RESET_TT;
300 		USETW(req.wValue, 0);
301 		req.wIndex[0] = port;
302 		req.wIndex[1] = 0;
303 		USETW(req.wLength, 0);
304 	} else {
305 		wValue = (ep->edesc->bEndpointAddress & 0xF) |
306 		      ((child->address & 0x7F) << 4) |
307 		      ((ep->edesc->bEndpointAddress & 0x80) << 8) |
308 		      ((ep->edesc->bmAttributes & 3) << 12);
309 
310 		req.bmRequestType = UT_WRITE_CLASS_OTHER;
311 		req.bRequest = UR_CLEAR_TT_BUFFER;
312 		USETW(req.wValue, wValue);
313 		req.wIndex[0] = port;
314 		req.wIndex[1] = 0;
315 		USETW(req.wLength, 0);
316 	}
317 	up->req_reset_tt = req;
318 	/* get reset transfer started */
319 	usb_proc_msignal(USB_BUS_TT_PROC(udev->bus),
320 	    &hub->tt_msg[0], &hub->tt_msg[1]);
321 }
322 #endif
323 
324 #if USB_HAVE_TT_SUPPORT
325 static void
uhub_reset_tt_callback(struct usb_xfer * xfer,usb_error_t error)326 uhub_reset_tt_callback(struct usb_xfer *xfer, usb_error_t error)
327 {
328 	struct uhub_softc *sc;
329 	struct usb_device *udev;
330 	struct usb_port *up;
331 	uint8_t x;
332 
333 	DPRINTF("TT buffer reset\n");
334 
335 	sc = usbd_xfer_softc(xfer);
336 	udev = sc->sc_udev;
337 
338 	switch (USB_GET_STATE(xfer)) {
339 	case USB_ST_TRANSFERRED:
340 	case USB_ST_SETUP:
341 tr_setup:
342 		USB_BUS_LOCK(udev->bus);
343 		/* find first port which needs a TT reset */
344 		for (x = 0; x != udev->hub->nports; x++) {
345 			up = udev->hub->ports + x;
346 
347 			if (up->req_reset_tt.bRequest == 0)
348 				continue;
349 
350 			/* copy in the transfer */
351 			usbd_copy_in(xfer->frbuffers, 0, &up->req_reset_tt,
352 			    sizeof(up->req_reset_tt));
353 			/* reset buffer */
354 			memset(&up->req_reset_tt, 0, sizeof(up->req_reset_tt));
355 
356 			/* set length */
357 			usbd_xfer_set_frame_len(xfer, 0, sizeof(up->req_reset_tt));
358 			xfer->nframes = 1;
359 			USB_BUS_UNLOCK(udev->bus);
360 
361 			usbd_transfer_submit(xfer);
362 			return;
363 		}
364 		USB_BUS_UNLOCK(udev->bus);
365 		break;
366 
367 	default:
368 		if (error == USB_ERR_CANCELLED)
369 			break;
370 
371 		DPRINTF("TT buffer reset failed (%s)\n", usbd_errstr(error));
372 		goto tr_setup;
373 	}
374 }
375 #endif
376 
377 /*------------------------------------------------------------------------*
378  *      uhub_count_active_host_ports
379  *
380  * This function counts the number of active ports at the given speed.
381  *------------------------------------------------------------------------*/
382 uint8_t
uhub_count_active_host_ports(struct usb_device * udev,enum usb_dev_speed speed)383 uhub_count_active_host_ports(struct usb_device *udev, enum usb_dev_speed speed)
384 {
385 	struct uhub_softc *sc;
386 	struct usb_device *child;
387 	struct usb_hub *hub;
388 	struct usb_port *up;
389 	uint8_t retval = 0;
390 	uint8_t x;
391 
392 	if (udev == NULL)
393 		goto done;
394 	hub = udev->hub;
395 	if (hub == NULL)
396 		goto done;
397 	sc = hub->hubsoftc;
398 	if (sc == NULL)
399 		goto done;
400 
401 	for (x = 0; x != hub->nports; x++) {
402 		up = hub->ports + x;
403 		child = usb_bus_port_get_device(udev->bus, up);
404 		if (child != NULL &&
405 		    child->flags.usb_mode == USB_MODE_HOST &&
406 		    child->speed == speed)
407 			retval++;
408 	}
409 done:
410 	return (retval);
411 }
412 
413 void
uhub_explore_handle_re_enumerate(struct usb_device * child)414 uhub_explore_handle_re_enumerate(struct usb_device *child)
415 {
416 	uint8_t do_unlock;
417 	usb_error_t err;
418 
419 	/* check if device should be re-enumerated */
420 	if (child->flags.usb_mode != USB_MODE_HOST)
421 		return;
422 
423 	do_unlock = usbd_enum_lock(child);
424 	switch (child->re_enumerate_wait) {
425 	case USB_RE_ENUM_START:
426 		err = usbd_set_config_index(child,
427 		    USB_UNCONFIG_INDEX);
428 		if (err != 0) {
429 			DPRINTF("Unconfigure failed: %s: Ignored.\n",
430 			    usbd_errstr(err));
431 		}
432 		if (child->parent_hub == NULL) {
433 			/* the root HUB cannot be re-enumerated */
434 			DPRINTFN(6, "cannot reset root HUB\n");
435 			err = 0;
436 		} else {
437 			err = usbd_req_re_enumerate(child, NULL);
438 		}
439 		if (err == 0) {
440 			/* refresh device strings */
441 			usb_get_langid(child);
442 			usb_set_device_strings(child);
443 
444 			/* set default configuration */
445 			err = usbd_set_config_index(child, 0);
446 		}
447 		if (err == 0) {
448 			err = usb_probe_and_attach(child,
449 			    USB_IFACE_INDEX_ANY);
450 		}
451 		child->re_enumerate_wait = USB_RE_ENUM_DONE;
452 		break;
453 
454 	case USB_RE_ENUM_PWR_OFF:
455 		/* get the device unconfigured */
456 		err = usbd_set_config_index(child,
457 		    USB_UNCONFIG_INDEX);
458 		if (err) {
459 			DPRINTFN(0, "Could not unconfigure "
460 			    "device (ignored)\n");
461 		}
462 		if (child->parent_hub == NULL) {
463 			/* the root HUB cannot be re-enumerated */
464 			DPRINTFN(6, "cannot set port feature\n");
465 			err = 0;
466 		} else {
467 			/* clear port enable */
468 			err = usbd_req_clear_port_feature(child->parent_hub,
469 			    NULL, child->port_no, UHF_PORT_ENABLE);
470 			if (err) {
471 				DPRINTFN(0, "Could not disable port "
472 				    "(ignored)\n");
473 			}
474 		}
475 		child->re_enumerate_wait = USB_RE_ENUM_DONE;
476 		break;
477 
478 	case USB_RE_ENUM_SET_CONFIG:
479 		err = usbd_set_config_index(child,
480 		    child->next_config_index);
481 		if (err != 0) {
482 			DPRINTF("Configure failed: %s: Ignored.\n",
483 			    usbd_errstr(err));
484 		} else {
485 			err = usb_probe_and_attach(child,
486 			    USB_IFACE_INDEX_ANY);
487 		}
488 		child->re_enumerate_wait = USB_RE_ENUM_DONE;
489 		break;
490 
491 	default:
492 		child->re_enumerate_wait = USB_RE_ENUM_DONE;
493 		break;
494 	}
495 	if (do_unlock)
496 		usbd_enum_unlock(child);
497 }
498 
499 /*------------------------------------------------------------------------*
500  *	uhub_explore_sub - subroutine
501  *
502  * Return values:
503  *    0: Success
504  * Else: A control transaction failed
505  *------------------------------------------------------------------------*/
506 static usb_error_t
uhub_explore_sub(struct uhub_softc * sc,struct usb_port * up)507 uhub_explore_sub(struct uhub_softc *sc, struct usb_port *up)
508 {
509 	struct usb_bus *bus;
510 	struct usb_device *child;
511 	uint8_t refcount;
512 	usb_error_t err;
513 
514 	bus = sc->sc_udev->bus;
515 	err = USB_ERR_NORMAL_COMPLETION;
516 
517 	/* get driver added refcount from USB bus */
518 	refcount = bus->driver_added_refcount;
519 
520 	/* get device assosiated with the given port */
521 	child = usb_bus_port_get_device(bus, up);
522 	if (child == NULL) {
523 		/* nothing to do */
524 		goto done;
525 	}
526 
527 	uhub_explore_handle_re_enumerate(child);
528 
529 	/* check if probe and attach should be done */
530 
531 	if (child->driver_added_refcount != refcount) {
532 		child->driver_added_refcount = refcount;
533 		err = usb_probe_and_attach(child,
534 		    USB_IFACE_INDEX_ANY);
535 		if (err) {
536 			goto done;
537 		}
538 	}
539 	/* start control transfer, if device mode */
540 
541 	if (child->flags.usb_mode == USB_MODE_DEVICE)
542 		usbd_ctrl_transfer_setup(child);
543 
544 	/* if a HUB becomes present, do a recursive HUB explore */
545 
546 	if (child->hub)
547 		err = (child->hub->explore) (child);
548 
549 done:
550 	return (err);
551 }
552 
553 /*------------------------------------------------------------------------*
554  *	uhub_read_port_status - factored out code
555  *------------------------------------------------------------------------*/
556 static usb_error_t
uhub_read_port_status(struct uhub_softc * sc,uint8_t portno)557 uhub_read_port_status(struct uhub_softc *sc, uint8_t portno)
558 {
559 	struct usb_port_status ps;
560 	usb_error_t err;
561 
562 	if (sc->sc_usb_port_errors >= UHUB_USB_PORT_ERRORS_MAX) {
563 		DPRINTFN(4, "port %d, HUB looks dead, too many errors\n", portno);
564 		sc->sc_st.port_status = 0;
565 		sc->sc_st.port_change = 0;
566 		return (USB_ERR_TIMEOUT);
567 	}
568 
569 	err = usbd_req_get_port_status(
570 	    sc->sc_udev, NULL, &ps, portno);
571 
572 	if (err == 0) {
573 		sc->sc_st.port_status = UGETW(ps.wPortStatus);
574 		sc->sc_st.port_change = UGETW(ps.wPortChange);
575 		sc->sc_usb_port_errors = 0;
576 	} else {
577 		sc->sc_st.port_status = 0;
578 		sc->sc_st.port_change = 0;
579 		sc->sc_usb_port_errors++;
580 	}
581 
582 	/* debugging print */
583 
584 	DPRINTFN(4, "port %d, wPortStatus=0x%04x, "
585 	    "wPortChange=0x%04x, err=%s\n",
586 	    portno, sc->sc_st.port_status,
587 	    sc->sc_st.port_change, usbd_errstr(err));
588 	return (err);
589 }
590 
591 /*------------------------------------------------------------------------*
592  *	uhub_reattach_port
593  *
594  * Returns:
595  *    0: Success
596  * Else: A control transaction failed
597  *------------------------------------------------------------------------*/
598 static usb_error_t
uhub_reattach_port(struct uhub_softc * sc,uint8_t portno)599 uhub_reattach_port(struct uhub_softc *sc, uint8_t portno)
600 {
601 	struct usb_device *child;
602 	struct usb_device *udev;
603 	enum usb_dev_speed speed;
604 	enum usb_hc_mode mode;
605 	usb_error_t err;
606 	uint16_t power_mask;
607 	uint8_t timeout;
608 
609 	DPRINTF("reattaching port %d\n", portno);
610 
611 	timeout = 0;
612 	udev = sc->sc_udev;
613 	child = usb_bus_port_get_device(udev->bus,
614 	    udev->hub->ports + portno - 1);
615 
616 repeat:
617 
618 	/* first clear the port connection change bit */
619 
620 	err = usbd_req_clear_port_feature(udev, NULL,
621 	    portno, UHF_C_PORT_CONNECTION);
622 
623 	if (err)
624 		goto error;
625 
626 	/* check if there is a child */
627 
628 	if (child != NULL) {
629 		/*
630 		 * Free USB device and all subdevices, if any.
631 		 */
632 		usb_free_device(child, 0);
633 		child = NULL;
634 	}
635 	/* get fresh status */
636 
637 	err = uhub_read_port_status(sc, portno);
638 	if (err)
639 		goto error;
640 
641 #if USB_HAVE_DISABLE_ENUM
642 	/* check if we should skip enumeration from this USB HUB */
643 	if (usb_disable_enumeration != 0 ||
644 	    sc->sc_disable_enumeration != 0) {
645 		DPRINTF("Enumeration is disabled!\n");
646 		goto error;
647 	}
648 #endif
649 	/* check if nothing is connected to the port */
650 
651 	if (!(sc->sc_st.port_status & UPS_CURRENT_CONNECT_STATUS))
652 		goto error;
653 
654 	/* check if there is no power on the port and print a warning */
655 
656 	switch (udev->speed) {
657 	case USB_SPEED_HIGH:
658 	case USB_SPEED_FULL:
659 	case USB_SPEED_LOW:
660 		power_mask = UPS_PORT_POWER;
661 		break;
662 	case USB_SPEED_SUPER:
663 		if (udev->parent_hub == NULL)
664 			power_mask = 0;	/* XXX undefined */
665 		else
666 			power_mask = UPS_PORT_POWER_SS;
667 		break;
668 	default:
669 		power_mask = 0;
670 		break;
671 	}
672 	if ((sc->sc_st.port_status & power_mask) != power_mask) {
673 		DPRINTF("WARNING: strange, connected port %d "
674 		    "has no power\n", portno);
675 	}
676 
677 	/* check if the device is in Host Mode */
678 
679 	if (!(sc->sc_st.port_status & UPS_PORT_MODE_DEVICE)) {
680 		DPRINTF("Port %d is in Host Mode\n", portno);
681 
682 		if (sc->sc_st.port_status & UPS_SUSPEND) {
683 			/*
684 			 * NOTE: Should not get here in SuperSpeed
685 			 * mode, because the HUB should report this
686 			 * bit as zero.
687 			 */
688 			DPRINTF("Port %d was still "
689 			    "suspended, clearing.\n", portno);
690 			err = usbd_req_clear_port_feature(udev,
691 			    NULL, portno, UHF_PORT_SUSPEND);
692 		}
693 
694 		/* USB Host Mode */
695 
696 		/* wait for maximum device power up time */
697 
698 		usb_pause_mtx(NULL,
699 		    USB_MS_TO_TICKS(usb_port_powerup_delay));
700 
701 		/* reset port, which implies enabling it */
702 
703 		err = usbd_req_reset_port(udev, NULL, portno);
704 
705 		if (err) {
706 			DPRINTFN(0, "port %d reset "
707 			    "failed, error=%s\n",
708 			    portno, usbd_errstr(err));
709 			goto error;
710 		}
711 		/* get port status again, it might have changed during reset */
712 
713 		err = uhub_read_port_status(sc, portno);
714 		if (err) {
715 			goto error;
716 		}
717 		/* check if something changed during port reset */
718 
719 		if ((sc->sc_st.port_change & UPS_C_CONNECT_STATUS) ||
720 		    (!(sc->sc_st.port_status & UPS_CURRENT_CONNECT_STATUS))) {
721 			if (timeout) {
722 				DPRINTFN(1, "giving up port %d reset - "
723 				   "device vanished: change %#x status %#x\n",
724 				   portno, sc->sc_st.port_change,
725 				   sc->sc_st.port_status);
726 				goto error;
727 			}
728 			timeout = 1;
729 			goto repeat;
730 		}
731 	} else {
732 		DPRINTF("Port %d is in Device Mode\n", portno);
733 	}
734 
735 	/*
736 	 * Figure out the device speed
737 	 */
738 	switch (udev->speed) {
739 	case USB_SPEED_HIGH:
740 		if (sc->sc_st.port_status & UPS_HIGH_SPEED)
741 			speed = USB_SPEED_HIGH;
742 		else if (sc->sc_st.port_status & UPS_LOW_SPEED)
743 			speed = USB_SPEED_LOW;
744 		else
745 			speed = USB_SPEED_FULL;
746 		break;
747 	case USB_SPEED_FULL:
748 		if (sc->sc_st.port_status & UPS_LOW_SPEED)
749 			speed = USB_SPEED_LOW;
750 		else
751 			speed = USB_SPEED_FULL;
752 		break;
753 	case USB_SPEED_LOW:
754 		speed = USB_SPEED_LOW;
755 		break;
756 	case USB_SPEED_SUPER:
757 		if (udev->parent_hub == NULL) {
758 			/* Root HUB - special case */
759 			switch (sc->sc_st.port_status & UPS_OTHER_SPEED) {
760 			case 0:
761 				speed = USB_SPEED_FULL;
762 				break;
763 			case UPS_LOW_SPEED:
764 				speed = USB_SPEED_LOW;
765 				break;
766 			case UPS_HIGH_SPEED:
767 				speed = USB_SPEED_HIGH;
768 				break;
769 			default:
770 				speed = USB_SPEED_SUPER;
771 				break;
772 			}
773 		} else {
774 			speed = USB_SPEED_SUPER;
775 		}
776 		break;
777 	default:
778 		/* same speed like parent */
779 		speed = udev->speed;
780 		break;
781 	}
782 	if (speed == USB_SPEED_SUPER) {
783 		err = usbd_req_set_hub_u1_timeout(udev, NULL,
784 		    portno, 128 - (2 * udev->depth));
785 		if (err) {
786 			DPRINTFN(0, "port %d U1 timeout "
787 			    "failed, error=%s\n",
788 			    portno, usbd_errstr(err));
789 		}
790 		err = usbd_req_set_hub_u2_timeout(udev, NULL,
791 		    portno, 128 - (2 * udev->depth));
792 		if (err) {
793 			DPRINTFN(0, "port %d U2 timeout "
794 			    "failed, error=%s\n",
795 			    portno, usbd_errstr(err));
796 		}
797 	}
798 
799 	/*
800 	 * Figure out the device mode
801 	 *
802 	 * NOTE: This part is currently FreeBSD specific.
803 	 */
804 	if (udev->parent_hub != NULL) {
805 		/* inherit mode from the parent HUB */
806 		mode = udev->parent_hub->flags.usb_mode;
807 	} else if (sc->sc_st.port_status & UPS_PORT_MODE_DEVICE)
808 		mode = USB_MODE_DEVICE;
809 	else
810 		mode = USB_MODE_HOST;
811 
812 	/* need to create a new child */
813 	child = usb_alloc_device(sc->sc_dev, udev->bus, udev,
814 	    udev->depth + 1, portno - 1, portno, speed, mode);
815 	if (child == NULL) {
816 		DPRINTFN(0, "could not allocate new device\n");
817 		goto error;
818 	}
819 	return (0);			/* success */
820 
821 error:
822 	if (child != NULL) {
823 		/*
824 		 * Free USB device and all subdevices, if any.
825 		 */
826 		usb_free_device(child, 0);
827 		child = NULL;
828 	}
829 	if (err == 0) {
830 		if (sc->sc_st.port_status & UPS_PORT_ENABLED) {
831 			err = usbd_req_clear_port_feature(
832 			    sc->sc_udev, NULL,
833 			    portno, UHF_PORT_ENABLE);
834 		}
835 	}
836 	if (err) {
837 		DPRINTFN(0, "device problem (%s), "
838 		    "disabling port %d\n", usbd_errstr(err), portno);
839 	}
840 	return (err);
841 }
842 
843 /*------------------------------------------------------------------------*
844  *	usb_device_20_compatible
845  *
846  * Returns:
847  *    0: HUB does not support suspend and resume
848  * Else: HUB supports suspend and resume
849  *------------------------------------------------------------------------*/
850 static uint8_t
usb_device_20_compatible(struct usb_device * udev)851 usb_device_20_compatible(struct usb_device *udev)
852 {
853 	if (udev == NULL)
854 		return (0);
855 	switch (udev->speed) {
856 	case USB_SPEED_LOW:
857 	case USB_SPEED_FULL:
858 	case USB_SPEED_HIGH:
859 		return (1);
860 	default:
861 		return (0);
862 	}
863 }
864 
865 /*------------------------------------------------------------------------*
866  *	uhub_suspend_resume_port
867  *
868  * Returns:
869  *    0: Success
870  * Else: A control transaction failed
871  *------------------------------------------------------------------------*/
872 static usb_error_t
uhub_suspend_resume_port(struct uhub_softc * sc,uint8_t portno)873 uhub_suspend_resume_port(struct uhub_softc *sc, uint8_t portno)
874 {
875 	struct usb_device *child;
876 	struct usb_device *udev;
877 	uint8_t is_suspend;
878 	usb_error_t err;
879 
880 	DPRINTF("port %d\n", portno);
881 
882 	udev = sc->sc_udev;
883 	child = usb_bus_port_get_device(udev->bus,
884 	    udev->hub->ports + portno - 1);
885 
886 	/* first clear the port suspend change bit */
887 
888 	if (usb_device_20_compatible(udev)) {
889 		err = usbd_req_clear_port_feature(udev, NULL,
890 		    portno, UHF_C_PORT_SUSPEND);
891 	} else {
892 		err = usbd_req_clear_port_feature(udev, NULL,
893 		    portno, UHF_C_PORT_LINK_STATE);
894 	}
895 
896 	if (err) {
897 		DPRINTF("clearing suspend failed.\n");
898 		goto done;
899 	}
900 	/* get fresh status */
901 
902 	err = uhub_read_port_status(sc, portno);
903 	if (err) {
904 		DPRINTF("reading port status failed.\n");
905 		goto done;
906 	}
907 	/* convert current state */
908 
909 	if (usb_device_20_compatible(udev)) {
910 		if (sc->sc_st.port_status & UPS_SUSPEND) {
911 			is_suspend = 1;
912 		} else {
913 			is_suspend = 0;
914 		}
915 	} else {
916 		switch (UPS_PORT_LINK_STATE_GET(sc->sc_st.port_status)) {
917 		case UPS_PORT_LS_U3:
918 			is_suspend = 1;
919 			break;
920 		case UPS_PORT_LS_SS_INA:
921 			usbd_req_warm_reset_port(udev, NULL, portno);
922 			is_suspend = 0;
923 			break;
924 		default:
925 			is_suspend = 0;
926 			break;
927 		}
928 	}
929 
930 	DPRINTF("suspended=%u\n", is_suspend);
931 
932 	/* do the suspend or resume */
933 
934 	if (child) {
935 		/*
936 		 * This code handle two cases: 1) Host Mode - we can only
937 		 * receive resume here 2) Device Mode - we can receive
938 		 * suspend and resume here
939 		 */
940 		if (is_suspend == 0)
941 			usb_dev_resume_peer(child);
942 		else if (child->flags.usb_mode == USB_MODE_DEVICE)
943 			usb_dev_suspend_peer(child);
944 	}
945 done:
946 	return (err);
947 }
948 
949 /*------------------------------------------------------------------------*
950  *	uhub_root_interrupt
951  *
952  * This function is called when a Root HUB interrupt has
953  * happened. "ptr" and "len" makes up the Root HUB interrupt
954  * packet. This function is called having the "bus_mtx" locked.
955  *------------------------------------------------------------------------*/
956 void
uhub_root_intr(struct usb_bus * bus,const uint8_t * ptr __unused,uint8_t len __unused)957 uhub_root_intr(struct usb_bus *bus,
958     const uint8_t *ptr __unused, uint8_t len __unused)
959 {
960 	USB_BUS_LOCK_ASSERT(bus, MA_OWNED);
961 
962 	usb_needs_explore(bus, 0);
963 }
964 
965 static uint8_t
uhub_is_too_deep(struct usb_device * udev)966 uhub_is_too_deep(struct usb_device *udev)
967 {
968 	switch (udev->speed) {
969 	case USB_SPEED_FULL:
970 	case USB_SPEED_LOW:
971 	case USB_SPEED_HIGH:
972 		if (udev->depth > USB_HUB_MAX_DEPTH)
973 			return (1);
974 		break;
975 	case USB_SPEED_SUPER:
976 		if (udev->depth > USB_SS_HUB_DEPTH_MAX)
977 			return (1);
978 		break;
979 	default:
980 		break;
981 	}
982 	return (0);
983 }
984 
985 /*------------------------------------------------------------------------*
986  *	uhub_explore
987  *
988  * Returns:
989  *     0: Success
990  *  Else: Failure
991  *------------------------------------------------------------------------*/
992 static usb_error_t
uhub_explore(struct usb_device * udev)993 uhub_explore(struct usb_device *udev)
994 {
995 	struct usb_hub *hub;
996 	struct uhub_softc *sc;
997 	struct usb_port *up;
998 	usb_error_t retval;
999 	usb_error_t err;
1000 	uint8_t portno;
1001 	uint8_t x;
1002 	uint8_t do_unlock;
1003 
1004 	hub = udev->hub;
1005 	sc = hub->hubsoftc;
1006 
1007 	DPRINTFN(11, "udev=%p addr=%d\n", udev, udev->address);
1008 
1009 	/* ignore devices that are too deep */
1010 	if (uhub_is_too_deep(udev))
1011 		return (USB_ERR_TOO_DEEP);
1012 
1013 	/* check if device is suspended */
1014 	if (udev->flags.self_suspended) {
1015 		/* need to wait until the child signals resume */
1016 		DPRINTF("Device is suspended!\n");
1017 		return (USB_ERR_NORMAL_COMPLETION);
1018 	}
1019 
1020 	/*
1021 	 * Make sure we don't race against user-space applications
1022 	 * like LibUSB:
1023 	 */
1024 	do_unlock = usbd_enum_lock(udev);
1025 
1026 	/*
1027 	 * Set default error code to avoid compiler warnings.
1028 	 * Note that hub->nports cannot be zero.
1029 	 */
1030 	retval = USB_ERR_NORMAL_COMPLETION;
1031 
1032 	for (x = 0; x != hub->nports; x++) {
1033 		up = hub->ports + x;
1034 		portno = x + 1;
1035 
1036 		err = uhub_read_port_status(sc, portno);
1037 		if (err != USB_ERR_NORMAL_COMPLETION)
1038 			retval = err;
1039 
1040 		if (sc->sc_st.port_change & UPS_C_OVERCURRENT_INDICATOR) {
1041 			DPRINTF("Overcurrent on port %u.\n", portno);
1042 			err = usbd_req_clear_port_feature(
1043 			    udev, NULL, portno, UHF_C_PORT_OVER_CURRENT);
1044 			if (err != USB_ERR_NORMAL_COMPLETION)
1045 				retval = err;
1046 		}
1047 		if (!(sc->sc_flags & UHUB_FLAG_DID_EXPLORE)) {
1048 			/*
1049 			 * Fake a connect status change so that the
1050 			 * status gets checked initially!
1051 			 */
1052 			sc->sc_st.port_change |=
1053 			    UPS_C_CONNECT_STATUS;
1054 		}
1055 		if (sc->sc_st.port_change & UPS_C_PORT_ENABLED) {
1056 			err = usbd_req_clear_port_feature(
1057 			    udev, NULL, portno, UHF_C_PORT_ENABLE);
1058 			if (err != USB_ERR_NORMAL_COMPLETION)
1059 				retval = err;
1060 			if (sc->sc_st.port_change & UPS_C_CONNECT_STATUS) {
1061 				/*
1062 				 * Ignore the port error if the device
1063 				 * has vanished !
1064 				 */
1065 			} else if (sc->sc_st.port_status & UPS_PORT_ENABLED) {
1066 				DPRINTFN(0, "illegal enable change, "
1067 				    "port %d\n", portno);
1068 			} else {
1069 				if (up->restartcnt == USB_RESTART_MAX) {
1070 					/* XXX could try another speed ? */
1071 					DPRINTFN(0, "port error, giving up "
1072 					    "port %d\n", portno);
1073 				} else {
1074 					sc->sc_st.port_change |=
1075 					    UPS_C_CONNECT_STATUS;
1076 					up->restartcnt++;
1077 				}
1078 			}
1079 		}
1080 		if (sc->sc_st.port_change & UPS_C_CONNECT_STATUS) {
1081 			err = uhub_reattach_port(sc, portno);
1082 			if (err != USB_ERR_NORMAL_COMPLETION)
1083 				retval = err;
1084 		}
1085 		if (sc->sc_st.port_change & (UPS_C_SUSPEND |
1086 		    UPS_C_PORT_LINK_STATE)) {
1087 			err = uhub_suspend_resume_port(sc, portno);
1088 			if (err != USB_ERR_NORMAL_COMPLETION)
1089 				retval = err;
1090 		}
1091 		if (udev->speed == USB_SPEED_SUPER &&
1092 		    (sc->sc_st.port_change & UPS_C_BH_PORT_RESET) != 0) {
1093 			DPRINTF("Warm reset finished on port %u.\n", portno);
1094 			err = usbd_req_clear_port_feature(
1095 			    udev, NULL, portno, UHF_C_BH_PORT_RESET);
1096 			if (err != USB_ERR_NORMAL_COMPLETION)
1097 				retval = err;
1098 		}
1099 		if (sc->sc_st.port_change & UPS_C_PORT_RESET) {
1100 			DPRINTF("Port reset finished on port %u.\n", portno);
1101 			err = usbd_req_clear_port_feature(
1102 			    udev, NULL, portno, UHF_C_PORT_RESET);
1103 			if (err != USB_ERR_NORMAL_COMPLETION)
1104 				retval = err;
1105 		}
1106 
1107 		if (uhub_explore_sub(sc, up) == USB_ERR_NORMAL_COMPLETION) {
1108 			/* explore succeeded - reset restart counter */
1109 			up->restartcnt = 0;
1110 		}
1111 	}
1112 
1113 	if (do_unlock)
1114 		usbd_enum_unlock(udev);
1115 
1116 	/* initial status checked */
1117 	sc->sc_flags |= UHUB_FLAG_DID_EXPLORE;
1118 
1119 	return (retval);
1120 }
1121 
1122 int
uhub_probe(device_t dev)1123 uhub_probe(device_t dev)
1124 {
1125 	struct usb_attach_arg *uaa = device_get_ivars(dev);
1126 
1127 	if (uaa->usb_mode != USB_MODE_HOST)
1128 		return (ENXIO);
1129 
1130 	/*
1131 	 * The subclass for USB HUBs is currently ignored because it
1132 	 * is 0 for some and 1 for others.
1133 	 */
1134 	if (uaa->info.bConfigIndex == 0 &&
1135 	    uaa->info.bDeviceClass == UDCLASS_HUB)
1136 		return (BUS_PROBE_DEFAULT);
1137 
1138 	return (ENXIO);
1139 }
1140 
1141 /* NOTE: The information returned by this function can be wrong. */
1142 usb_error_t
uhub_query_info(struct usb_device * udev,uint8_t * pnports,uint8_t * ptt)1143 uhub_query_info(struct usb_device *udev, uint8_t *pnports, uint8_t *ptt)
1144 {
1145 	struct usb_hub_descriptor hubdesc20;
1146 	struct usb_hub_ss_descriptor hubdesc30;
1147 	usb_error_t err;
1148 	uint8_t nports;
1149 	uint8_t tt;
1150 
1151 	if (udev->ddesc.bDeviceClass != UDCLASS_HUB)
1152 		return (USB_ERR_INVAL);
1153 
1154 	nports = 0;
1155 	tt = 0;
1156 
1157 	switch (udev->speed) {
1158 	case USB_SPEED_LOW:
1159 	case USB_SPEED_FULL:
1160 	case USB_SPEED_HIGH:
1161 		/* assuming that there is one port */
1162 		err = usbd_req_get_hub_descriptor(udev, NULL, &hubdesc20, 1);
1163 		if (err) {
1164 			DPRINTFN(0, "getting USB 2.0 HUB descriptor failed,"
1165 			    "error=%s\n", usbd_errstr(err));
1166 			break;
1167 		}
1168 		nports = hubdesc20.bNbrPorts;
1169 		if (nports > 127)
1170 			nports = 127;
1171 
1172 		if (udev->speed == USB_SPEED_HIGH)
1173 			tt = (UGETW(hubdesc20.wHubCharacteristics) >> 5) & 3;
1174 		break;
1175 
1176 	case USB_SPEED_SUPER:
1177 		err = usbd_req_get_ss_hub_descriptor(udev, NULL, &hubdesc30, 1);
1178 		if (err) {
1179 			DPRINTFN(0, "Getting USB 3.0 HUB descriptor failed,"
1180 			    "error=%s\n", usbd_errstr(err));
1181 			break;
1182 		}
1183 		nports = hubdesc30.bNbrPorts;
1184 		if (nports > 16)
1185 			nports = 16;
1186 		break;
1187 
1188 	default:
1189 		err = USB_ERR_INVAL;
1190 		break;
1191 	}
1192 
1193 	if (pnports != NULL)
1194 		*pnports = nports;
1195 
1196 	if (ptt != NULL)
1197 		*ptt = tt;
1198 
1199 	return (err);
1200 }
1201 
1202 int
uhub_attach(device_t dev)1203 uhub_attach(device_t dev)
1204 {
1205 	struct uhub_softc *sc = device_get_softc(dev);
1206 	struct usb_attach_arg *uaa = device_get_ivars(dev);
1207 	struct usb_device *udev = uaa->device;
1208 	struct usb_device *parent_hub = udev->parent_hub;
1209 	struct usb_hub *hub;
1210 	struct usb_hub_descriptor hubdesc20;
1211 	struct usb_hub_ss_descriptor hubdesc30;
1212 #if USB_HAVE_DISABLE_ENUM
1213 	struct sysctl_ctx_list *sysctl_ctx;
1214 	struct sysctl_oid *sysctl_tree;
1215 #endif
1216 	uint16_t pwrdly;
1217 	uint16_t nports;
1218 	uint8_t x;
1219 	uint8_t portno;
1220 	uint8_t removable;
1221 	uint8_t iface_index;
1222 	usb_error_t err;
1223 
1224 	sc->sc_udev = udev;
1225 	sc->sc_dev = dev;
1226 
1227 	mtx_init(&sc->sc_mtx, "USB HUB mutex", NULL, MTX_DEF);
1228 
1229 	device_set_usb_desc(dev);
1230 
1231 	DPRINTFN(2, "depth=%d selfpowered=%d, parent=%p, "
1232 	    "parent->selfpowered=%d\n",
1233 	    udev->depth,
1234 	    udev->flags.self_powered,
1235 	    parent_hub,
1236 	    parent_hub ?
1237 	    parent_hub->flags.self_powered : 0);
1238 
1239 	if (uhub_is_too_deep(udev)) {
1240 		DPRINTFN(0, "HUB at depth %d, "
1241 		    "exceeds maximum. HUB ignored\n", (int)udev->depth);
1242 		goto error;
1243 	}
1244 
1245 	if (!udev->flags.self_powered && parent_hub &&
1246 	    !parent_hub->flags.self_powered) {
1247 		DPRINTFN(0, "Bus powered HUB connected to "
1248 		    "bus powered HUB. HUB ignored\n");
1249 		goto error;
1250 	}
1251 
1252 	if (UHUB_IS_MULTI_TT(sc)) {
1253 		err = usbd_set_alt_interface_index(udev, 0, 1);
1254 		if (err) {
1255 			device_printf(dev, "MTT could not be enabled\n");
1256 			goto error;
1257 		}
1258 		device_printf(dev, "MTT enabled\n");
1259 	}
1260 
1261 	/* get HUB descriptor */
1262 
1263 	DPRINTFN(2, "Getting HUB descriptor\n");
1264 
1265 	switch (udev->speed) {
1266 	case USB_SPEED_LOW:
1267 	case USB_SPEED_FULL:
1268 	case USB_SPEED_HIGH:
1269 		/* assuming that there is one port */
1270 		err = usbd_req_get_hub_descriptor(udev, NULL, &hubdesc20, 1);
1271 		if (err) {
1272 			DPRINTFN(0, "getting USB 2.0 HUB descriptor failed,"
1273 			    "error=%s\n", usbd_errstr(err));
1274 			goto error;
1275 		}
1276 		/* get number of ports */
1277 		nports = hubdesc20.bNbrPorts;
1278 
1279 		/* get power delay */
1280 		pwrdly = ((hubdesc20.bPwrOn2PwrGood * UHD_PWRON_FACTOR) +
1281 		    usb_extra_power_up_time);
1282 
1283 		/* get complete HUB descriptor */
1284 		if (nports >= 8) {
1285 			/* check number of ports */
1286 			if (nports > 127) {
1287 				DPRINTFN(0, "Invalid number of USB 2.0 ports,"
1288 				    "error=%s\n", usbd_errstr(err));
1289 				goto error;
1290 			}
1291 			/* get complete HUB descriptor */
1292 			err = usbd_req_get_hub_descriptor(udev, NULL, &hubdesc20, nports);
1293 
1294 			if (err) {
1295 				DPRINTFN(0, "Getting USB 2.0 HUB descriptor failed,"
1296 				    "error=%s\n", usbd_errstr(err));
1297 				goto error;
1298 			}
1299 			if (hubdesc20.bNbrPorts != nports) {
1300 				DPRINTFN(0, "Number of ports changed\n");
1301 				goto error;
1302 			}
1303 		}
1304 		break;
1305 	case USB_SPEED_SUPER:
1306 		if (udev->parent_hub != NULL) {
1307 			err = usbd_req_set_hub_depth(udev, NULL,
1308 			    udev->depth - 1);
1309 			if (err) {
1310 				DPRINTFN(0, "Setting USB 3.0 HUB depth failed,"
1311 				    "error=%s\n", usbd_errstr(err));
1312 				goto error;
1313 			}
1314 		}
1315 		err = usbd_req_get_ss_hub_descriptor(udev, NULL, &hubdesc30, 1);
1316 		if (err) {
1317 			DPRINTFN(0, "Getting USB 3.0 HUB descriptor failed,"
1318 			    "error=%s\n", usbd_errstr(err));
1319 			goto error;
1320 		}
1321 		/* get number of ports */
1322 		nports = hubdesc30.bNbrPorts;
1323 
1324 		/* get power delay */
1325 		pwrdly = ((hubdesc30.bPwrOn2PwrGood * UHD_PWRON_FACTOR) +
1326 		    usb_extra_power_up_time);
1327 
1328 		/* get complete HUB descriptor */
1329 		if (nports >= 8) {
1330 			/* check number of ports */
1331 			if (nports > ((udev->parent_hub != NULL) ? 15 : 127)) {
1332 				DPRINTFN(0, "Invalid number of USB 3.0 ports,"
1333 				    "error=%s\n", usbd_errstr(err));
1334 				goto error;
1335 			}
1336 			/* get complete HUB descriptor */
1337 			err = usbd_req_get_ss_hub_descriptor(udev, NULL, &hubdesc30, nports);
1338 
1339 			if (err) {
1340 				DPRINTFN(0, "Getting USB 2.0 HUB descriptor failed,"
1341 				    "error=%s\n", usbd_errstr(err));
1342 				goto error;
1343 			}
1344 			if (hubdesc30.bNbrPorts != nports) {
1345 				DPRINTFN(0, "Number of ports changed\n");
1346 				goto error;
1347 			}
1348 		}
1349 		break;
1350 	default:
1351 		DPRINTF("Assuming HUB has only one port\n");
1352 		/* default number of ports */
1353 		nports = 1;
1354 		/* default power delay */
1355 		pwrdly = ((10 * UHD_PWRON_FACTOR) + usb_extra_power_up_time);
1356 		break;
1357 	}
1358 	if (nports == 0) {
1359 		DPRINTFN(0, "portless HUB\n");
1360 		goto error;
1361 	}
1362 	if (nports > USB_MAX_PORTS) {
1363 		DPRINTF("Port limit exceeded\n");
1364 		goto error;
1365 	}
1366 #if (USB_HAVE_FIXED_PORT == 0)
1367 	hub = malloc(sizeof(hub[0]) + (sizeof(hub->ports[0]) * nports),
1368 	    M_USBDEV, M_WAITOK | M_ZERO);
1369 
1370 	if (hub == NULL)
1371 		goto error;
1372 #else
1373 	hub = &sc->sc_hub;
1374 #endif
1375 	udev->hub = hub;
1376 
1377 	/* initialize HUB structure */
1378 	hub->hubsoftc = sc;
1379 	hub->explore = &uhub_explore;
1380 	hub->nports = nports;
1381 	hub->hubudev = udev;
1382 #if USB_HAVE_TT_SUPPORT
1383 	hub->tt_msg[0].hdr.pm_callback = &uhub_reset_tt_proc;
1384 	hub->tt_msg[0].udev = udev;
1385 	hub->tt_msg[1].hdr.pm_callback = &uhub_reset_tt_proc;
1386 	hub->tt_msg[1].udev = udev;
1387 #endif
1388 	/* if self powered hub, give ports maximum current */
1389 	if (udev->flags.self_powered) {
1390 		hub->portpower = USB_MAX_POWER;
1391 	} else {
1392 		hub->portpower = USB_MIN_POWER;
1393 	}
1394 
1395 	/* set up interrupt pipe */
1396 	iface_index = 0;
1397 	if (udev->parent_hub == NULL) {
1398 		/* root HUB is special */
1399 		err = 0;
1400 	} else {
1401 		/* normal HUB */
1402 		err = usbd_transfer_setup(udev, &iface_index, sc->sc_xfer,
1403 		    uhub_config, UHUB_N_TRANSFER, sc, &sc->sc_mtx);
1404 	}
1405 	if (err) {
1406 		DPRINTFN(0, "cannot setup interrupt transfer, "
1407 		    "errstr=%s\n", usbd_errstr(err));
1408 		goto error;
1409 	}
1410 	/* wait with power off for a while */
1411 	usb_pause_mtx(NULL, USB_MS_TO_TICKS(USB_POWER_DOWN_TIME));
1412 
1413 #if USB_HAVE_DISABLE_ENUM
1414 	/* Add device sysctls */
1415 
1416 	sysctl_ctx = device_get_sysctl_ctx(dev);
1417 	sysctl_tree = device_get_sysctl_tree(dev);
1418 
1419 	if (sysctl_ctx != NULL && sysctl_tree != NULL) {
1420 		(void) SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1421 		    OID_AUTO, "disable_enumeration", CTLFLAG_RWTUN,
1422 		    &sc->sc_disable_enumeration, 0,
1423 		    "Set to disable enumeration on this USB HUB.");
1424 
1425 		(void) SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1426 		    OID_AUTO, "disable_port_power", CTLFLAG_RWTUN,
1427 		    &sc->sc_disable_port_power, 0,
1428 		    "Set to disable USB port power on this USB HUB.");
1429 	}
1430 #endif
1431 	/*
1432 	 * To have the best chance of success we do things in the exact same
1433 	 * order as Windoze98.  This should not be necessary, but some
1434 	 * devices do not follow the USB specs to the letter.
1435 	 *
1436 	 * These are the events on the bus when a hub is attached:
1437 	 *  Get device and config descriptors (see attach code)
1438 	 *  Get hub descriptor (see above)
1439 	 *  For all ports
1440 	 *     turn on power
1441 	 *     wait for power to become stable
1442 	 * (all below happens in explore code)
1443 	 *  For all ports
1444 	 *     clear C_PORT_CONNECTION
1445 	 *  For all ports
1446 	 *     get port status
1447 	 *     if device connected
1448 	 *        wait 100 ms
1449 	 *        turn on reset
1450 	 *        wait
1451 	 *        clear C_PORT_RESET
1452 	 *        get port status
1453 	 *        proceed with device attachment
1454 	 */
1455 
1456 	/* XXX should check for none, individual, or ganged power? */
1457 
1458 	removable = 0;
1459 
1460 	for (x = 0; x != nports; x++) {
1461 		/* set up data structures */
1462 		struct usb_port *up = hub->ports + x;
1463 
1464 		up->device_index = 0;
1465 		up->restartcnt = 0;
1466 		portno = x + 1;
1467 
1468 		/* check if port is removable */
1469 		switch (udev->speed) {
1470 		case USB_SPEED_LOW:
1471 		case USB_SPEED_FULL:
1472 		case USB_SPEED_HIGH:
1473 			if (!UHD_NOT_REMOV(&hubdesc20, portno))
1474 				removable++;
1475 			break;
1476 		case USB_SPEED_SUPER:
1477 			if (!UHD_NOT_REMOV(&hubdesc30, portno))
1478 				removable++;
1479 			break;
1480 		default:
1481 			DPRINTF("Assuming removable port\n");
1482 			removable++;
1483 			break;
1484 		}
1485 		if (err == 0) {
1486 #if USB_HAVE_DISABLE_ENUM
1487 			/* check if we should disable USB port power or not */
1488 			if (usb_disable_port_power != 0 ||
1489 			    sc->sc_disable_port_power != 0) {
1490 				/* turn the power off */
1491 				DPRINTFN(2, "Turning port %d power off\n", portno);
1492 				err = usbd_req_clear_port_feature(udev, NULL,
1493 				    portno, UHF_PORT_POWER);
1494 			} else {
1495 #endif
1496 				/* turn the power on */
1497 				DPRINTFN(2, "Turning port %d power on\n", portno);
1498 				err = usbd_req_set_port_feature(udev, NULL,
1499 				    portno, UHF_PORT_POWER);
1500 #if USB_HAVE_DISABLE_ENUM
1501 			}
1502 #endif
1503 		}
1504 		if (err != 0) {
1505 			DPRINTFN(0, "port %d power on or off failed, %s\n",
1506 			    portno, usbd_errstr(err));
1507 		}
1508 		DPRINTF("turn on port %d power\n",
1509 		    portno);
1510 
1511 		/* wait for stable power */
1512 		usb_pause_mtx(NULL, USB_MS_TO_TICKS(pwrdly));
1513 	}
1514 
1515 	device_printf(dev, "%d port%s with %d "
1516 	    "removable, %s powered\n", nports, (nports != 1) ? "s" : "",
1517 	    removable, udev->flags.self_powered ? "self" : "bus");
1518 
1519 	/* Start the interrupt endpoint, if any */
1520 
1521 	USB_MTX_LOCK(&sc->sc_mtx);
1522 	usbd_transfer_start(sc->sc_xfer[UHUB_INTR_TRANSFER]);
1523 	USB_MTX_UNLOCK(&sc->sc_mtx);
1524 
1525 	/* Enable automatic power save on all USB HUBs */
1526 
1527 	usbd_set_power_mode(udev, USB_POWER_MODE_SAVE);
1528 
1529 	return (0);
1530 
1531 error:
1532 	usbd_transfer_unsetup(sc->sc_xfer, UHUB_N_TRANSFER);
1533 
1534 #if (USB_HAVE_FIXED_PORT == 0)
1535 	free(udev->hub, M_USBDEV);
1536 #endif
1537 	udev->hub = NULL;
1538 
1539 	mtx_destroy(&sc->sc_mtx);
1540 
1541 	return (ENXIO);
1542 }
1543 
1544 /*
1545  * Called from process context when the hub is gone.
1546  * Detach all devices on active ports.
1547  */
1548 int
uhub_detach(device_t dev)1549 uhub_detach(device_t dev)
1550 {
1551 	struct uhub_softc *sc = device_get_softc(dev);
1552 	struct usb_hub *hub = sc->sc_udev->hub;
1553 	struct usb_bus *bus = sc->sc_udev->bus;
1554 	struct usb_device *child;
1555 	uint8_t x;
1556 
1557 	if (hub == NULL)		/* must be partially working */
1558 		return (0);
1559 
1560 	/* Make sure interrupt transfer is gone. */
1561 	usbd_transfer_unsetup(sc->sc_xfer, UHUB_N_TRANSFER);
1562 
1563 	/* Detach all ports */
1564 	for (x = 0; x != hub->nports; x++) {
1565 		child = usb_bus_port_get_device(bus, hub->ports + x);
1566 
1567 		if (child == NULL) {
1568 			continue;
1569 		}
1570 
1571 		/*
1572 		 * Free USB device and all subdevices, if any.
1573 		 */
1574 		usb_free_device(child, 0);
1575 	}
1576 
1577 #if USB_HAVE_TT_SUPPORT
1578 	/* Make sure our TT messages are not queued anywhere */
1579 	USB_BUS_LOCK(bus);
1580 	usb_proc_mwait(USB_BUS_TT_PROC(bus),
1581 	    &hub->tt_msg[0], &hub->tt_msg[1]);
1582 	USB_BUS_UNLOCK(bus);
1583 #endif
1584 
1585 #if (USB_HAVE_FIXED_PORT == 0)
1586 	free(hub, M_USBDEV);
1587 #endif
1588 	sc->sc_udev->hub = NULL;
1589 
1590 	mtx_destroy(&sc->sc_mtx);
1591 
1592 	return (0);
1593 }
1594 
1595 static int
uhub_suspend(device_t dev)1596 uhub_suspend(device_t dev)
1597 {
1598 	DPRINTF("\n");
1599 	/* Sub-devices are not suspended here! */
1600 	return (0);
1601 }
1602 
1603 static int
uhub_resume(device_t dev)1604 uhub_resume(device_t dev)
1605 {
1606 	DPRINTF("\n");
1607 	/* Sub-devices are not resumed here! */
1608 	return (0);
1609 }
1610 
1611 static void
uhub_driver_added(device_t dev,driver_t * driver)1612 uhub_driver_added(device_t dev, driver_t *driver)
1613 {
1614 	usb_needs_explore_all();
1615 }
1616 
1617 void
uhub_find_iface_index(struct usb_hub * hub,device_t child,struct hub_result * res)1618 uhub_find_iface_index(struct usb_hub *hub, device_t child,
1619     struct hub_result *res)
1620 {
1621 	struct usb_interface *iface;
1622 	struct usb_device *udev;
1623 	uint8_t nports;
1624 	uint8_t x;
1625 	uint8_t i;
1626 
1627 	nports = hub->nports;
1628 	for (x = 0; x != nports; x++) {
1629 		udev = usb_bus_port_get_device(hub->hubudev->bus,
1630 		    hub->ports + x);
1631 		if (!udev) {
1632 			continue;
1633 		}
1634 		for (i = 0; i != USB_IFACE_MAX; i++) {
1635 			iface = usbd_get_iface(udev, i);
1636 			if (iface &&
1637 			    (iface->subdev == child)) {
1638 				res->iface_index = i;
1639 				res->udev = udev;
1640 				res->portno = x + 1;
1641 				return;
1642 			}
1643 		}
1644 	}
1645 	res->iface_index = 0;
1646 	res->udev = NULL;
1647 	res->portno = 0;
1648 }
1649 
1650 int
uhub_child_location(device_t parent,device_t child,struct sbuf * sb)1651 uhub_child_location(device_t parent, device_t child, struct sbuf *sb)
1652 {
1653 	struct uhub_softc *sc;
1654 	struct usb_hub *hub;
1655 	struct hub_result res;
1656 
1657 	if (!device_is_attached(parent))
1658 		return (0);
1659 
1660 	sc = device_get_softc(parent);
1661 	hub = sc->sc_udev->hub;
1662 
1663 	bus_topo_lock();
1664 	uhub_find_iface_index(hub, child, &res);
1665 	if (!res.udev) {
1666 		DPRINTF("device not on hub\n");
1667 		goto done;
1668 	}
1669 	sbuf_printf(sb, "bus=%u hubaddr=%u port=%u devaddr=%u"
1670 	    " interface=%u"
1671 #if USB_HAVE_UGEN
1672 	    " ugen=%s"
1673 #endif
1674 	    , device_get_unit(res.udev->bus->bdev)
1675 	    , (res.udev->parent_hub != NULL) ?
1676 	    res.udev->parent_hub->device_index : 0
1677 	    , res.portno, res.udev->device_index, res.iface_index
1678 #if USB_HAVE_UGEN
1679 	    , res.udev->ugen_name
1680 #endif
1681 	    );
1682 done:
1683 	bus_topo_unlock();
1684 
1685 	return (0);
1686 }
1687 
1688 int
uhub_get_device_path(device_t bus,device_t child,const char * locator,struct sbuf * sb)1689 uhub_get_device_path(device_t bus, device_t child, const char *locator,
1690     struct sbuf *sb)
1691 {
1692 	struct uhub_softc *sc;
1693 	struct usb_hub *hub;
1694 	struct hub_result res;
1695 	int rv;
1696 
1697 	if (strcmp(locator, BUS_LOCATOR_UEFI) == 0) {
1698 		rv = bus_generic_get_device_path(device_get_parent(bus), bus, locator, sb);
1699 		if (rv != 0)
1700 			return (rv);
1701 
1702 		sc = device_get_softc(bus);
1703 		hub = sc->sc_udev->hub;
1704 
1705 		bus_topo_lock();
1706 		uhub_find_iface_index(hub, child, &res);
1707 		if (!res.udev) {
1708 			printf("device not on hub\n");
1709 			goto done;
1710 		}
1711 		sbuf_printf(sb, "/USB(0x%x,0x%x)", res.portno - 1, res.iface_index);
1712 	done:
1713 		bus_topo_unlock();
1714 		return (0);
1715 	}
1716 
1717 	/* For the rest, punt to the default handler */
1718 	return (bus_generic_get_device_path(bus, child, locator, sb));
1719 }
1720 
1721 static int
uhub_child_pnpinfo(device_t parent,device_t child,struct sbuf * sb)1722 uhub_child_pnpinfo(device_t parent, device_t child, struct sbuf*sb)
1723 {
1724 	struct uhub_softc *sc;
1725 	struct usb_hub *hub;
1726 	struct usb_interface *iface;
1727 	struct hub_result res;
1728 	uint8_t do_unlock;
1729 
1730 	if (!device_is_attached(parent))
1731 		return (0);
1732 
1733 	sc = device_get_softc(parent);
1734 	hub = sc->sc_udev->hub;
1735 
1736 	bus_topo_lock();
1737 	uhub_find_iface_index(hub, child, &res);
1738 	if (!res.udev) {
1739 		DPRINTF("device not on hub\n");
1740 		goto done;
1741 	}
1742 	iface = usbd_get_iface(res.udev, res.iface_index);
1743 	if (iface && iface->idesc) {
1744 		/* Make sure device information is not changed during the print. */
1745 		do_unlock = usbd_ctrl_lock(res.udev);
1746 
1747 		sbuf_printf(sb, "vendor=0x%04x product=0x%04x "
1748 		    "devclass=0x%02x devsubclass=0x%02x "
1749 		    "devproto=0x%02x "
1750 		    "sernum=\"%s\" "
1751 		    "release=0x%04x "
1752 		    "mode=%s "
1753 		    "intclass=0x%02x intsubclass=0x%02x "
1754 		    "intprotocol=0x%02x" "%s%s",
1755 		    UGETW(res.udev->ddesc.idVendor),
1756 		    UGETW(res.udev->ddesc.idProduct),
1757 		    res.udev->ddesc.bDeviceClass,
1758 		    res.udev->ddesc.bDeviceSubClass,
1759 		    res.udev->ddesc.bDeviceProtocol,
1760 		    usb_get_serial(res.udev),
1761 		    UGETW(res.udev->ddesc.bcdDevice),
1762 		    (res.udev->flags.usb_mode == USB_MODE_HOST) ? "host" : "device",
1763 		    iface->idesc->bInterfaceClass,
1764 		    iface->idesc->bInterfaceSubClass,
1765 		    iface->idesc->bInterfaceProtocol,
1766 		    iface->pnpinfo ? " " : "",
1767 		    iface->pnpinfo ? iface->pnpinfo : "");
1768 
1769 		if (do_unlock)
1770 			usbd_ctrl_unlock(res.udev);
1771 	}
1772 done:
1773 	bus_topo_unlock();
1774 
1775 	return (0);
1776 }
1777 
1778 /*
1779  * The USB Transaction Translator:
1780  * ===============================
1781  *
1782  * When doing LOW- and FULL-speed USB transfers across a HIGH-speed
1783  * USB HUB, bandwidth must be allocated for ISOCHRONOUS and INTERRUPT
1784  * USB transfers. To utilize bandwidth dynamically the "scatter and
1785  * gather" principle must be applied. This means that bandwidth must
1786  * be divided into equal parts of bandwidth. With regard to USB all
1787  * data is transferred in smaller packets with length
1788  * "wMaxPacketSize". The problem however is that "wMaxPacketSize" is
1789  * not a constant!
1790  *
1791  * The bandwidth scheduler which I have implemented will simply pack
1792  * the USB transfers back to back until there is no more space in the
1793  * schedule. Out of the 8 microframes which the USB 2.0 standard
1794  * provides, only 6 are available for non-HIGH-speed devices. I have
1795  * reserved the first 4 microframes for ISOCHRONOUS transfers. The
1796  * last 2 microframes I have reserved for INTERRUPT transfers. Without
1797  * this division, it is very difficult to allocate and free bandwidth
1798  * dynamically.
1799  *
1800  * NOTE about the Transaction Translator in USB HUBs:
1801  *
1802  * USB HUBs have a very simple Transaction Translator, that will
1803  * simply pipeline all the SPLIT transactions. That means that the
1804  * transactions will be executed in the order they are queued!
1805  *
1806  */
1807 
1808 /*------------------------------------------------------------------------*
1809  *	usb_intr_find_best_slot
1810  *
1811  * Return value:
1812  *   The best Transaction Translation slot for an interrupt endpoint.
1813  *------------------------------------------------------------------------*/
1814 static uint8_t
usb_intr_find_best_slot(usb_size_t * ptr,uint8_t start,uint8_t end,uint8_t mask)1815 usb_intr_find_best_slot(usb_size_t *ptr, uint8_t start,
1816     uint8_t end, uint8_t mask)
1817 {
1818 	usb_size_t min = (usb_size_t)-1;
1819 	usb_size_t sum;
1820 	uint8_t x;
1821 	uint8_t y;
1822 	uint8_t z;
1823 
1824 	y = 0;
1825 
1826 	/* find the last slot with lesser used bandwidth */
1827 
1828 	for (x = start; x < end; x++) {
1829 		sum = 0;
1830 
1831 		/* compute sum of bandwidth */
1832 		for (z = x; z < end; z++) {
1833 			if (mask & (1U << (z - x)))
1834 				sum += ptr[z];
1835 		}
1836 
1837 		/* check if the current multi-slot is more optimal */
1838 		if (min >= sum) {
1839 			min = sum;
1840 			y = x;
1841 		}
1842 
1843 		/* check if the mask is about to be shifted out */
1844 		if (mask & (1U << (end - 1 - x)))
1845 			break;
1846 	}
1847 	return (y);
1848 }
1849 
1850 /*------------------------------------------------------------------------*
1851  *	usb_hs_bandwidth_adjust
1852  *
1853  * This function will update the bandwidth usage for the microframe
1854  * having index "slot" by "len" bytes. "len" can be negative.  If the
1855  * "slot" argument is greater or equal to "USB_HS_MICRO_FRAMES_MAX"
1856  * the "slot" argument will be replaced by the slot having least used
1857  * bandwidth. The "mask" argument is used for multi-slot allocations.
1858  *
1859  * Returns:
1860  *    The slot in which the bandwidth update was done: 0..7
1861  *------------------------------------------------------------------------*/
1862 static uint8_t
usb_hs_bandwidth_adjust(struct usb_device * udev,int16_t len,uint8_t slot,uint8_t mask)1863 usb_hs_bandwidth_adjust(struct usb_device *udev, int16_t len,
1864     uint8_t slot, uint8_t mask)
1865 {
1866 	struct usb_bus *bus = udev->bus;
1867 	struct usb_hub *hub;
1868 	enum usb_dev_speed speed;
1869 	uint8_t x;
1870 
1871 	USB_BUS_LOCK_ASSERT(bus, MA_OWNED);
1872 
1873 	speed = usbd_get_speed(udev);
1874 
1875 	switch (speed) {
1876 	case USB_SPEED_LOW:
1877 	case USB_SPEED_FULL:
1878 		if (speed == USB_SPEED_LOW) {
1879 			len *= 8;
1880 		}
1881 		/*
1882 	         * The Host Controller Driver should have
1883 	         * performed checks so that the lookup
1884 	         * below does not result in a NULL pointer
1885 	         * access.
1886 	         */
1887 
1888 		hub = udev->parent_hs_hub->hub;
1889 		if (slot >= USB_HS_MICRO_FRAMES_MAX) {
1890 			slot = usb_intr_find_best_slot(hub->uframe_usage,
1891 			    USB_FS_ISOC_UFRAME_MAX, 6, mask);
1892 		}
1893 		for (x = slot; x < 8; x++) {
1894 			if (mask & (1U << (x - slot))) {
1895 				hub->uframe_usage[x] += len;
1896 				bus->uframe_usage[x] += len;
1897 			}
1898 		}
1899 		break;
1900 	default:
1901 		if (slot >= USB_HS_MICRO_FRAMES_MAX) {
1902 			slot = usb_intr_find_best_slot(bus->uframe_usage, 0,
1903 			    USB_HS_MICRO_FRAMES_MAX, mask);
1904 		}
1905 		for (x = slot; x < 8; x++) {
1906 			if (mask & (1U << (x - slot))) {
1907 				bus->uframe_usage[x] += len;
1908 			}
1909 		}
1910 		break;
1911 	}
1912 	return (slot);
1913 }
1914 
1915 /*------------------------------------------------------------------------*
1916  *	usb_hs_bandwidth_alloc
1917  *
1918  * This function is a wrapper function for "usb_hs_bandwidth_adjust()".
1919  *------------------------------------------------------------------------*/
1920 void
usb_hs_bandwidth_alloc(struct usb_xfer * xfer)1921 usb_hs_bandwidth_alloc(struct usb_xfer *xfer)
1922 {
1923 	struct usb_device *udev;
1924 	uint8_t slot;
1925 	uint8_t mask;
1926 	uint8_t speed;
1927 
1928 	udev = xfer->xroot->udev;
1929 
1930 	if (udev->flags.usb_mode != USB_MODE_HOST)
1931 		return;		/* not supported */
1932 
1933 	xfer->endpoint->refcount_bw++;
1934 	if (xfer->endpoint->refcount_bw != 1)
1935 		return;		/* already allocated */
1936 
1937 	speed = usbd_get_speed(udev);
1938 
1939 	switch (xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE) {
1940 	case UE_INTERRUPT:
1941 		/* allocate a microframe slot */
1942 
1943 		mask = 0x01;
1944 		slot = usb_hs_bandwidth_adjust(udev,
1945 		    xfer->max_frame_size, USB_HS_MICRO_FRAMES_MAX, mask);
1946 
1947 		xfer->endpoint->usb_uframe = slot;
1948 		xfer->endpoint->usb_smask = mask << slot;
1949 
1950 		if ((speed != USB_SPEED_FULL) &&
1951 		    (speed != USB_SPEED_LOW)) {
1952 			xfer->endpoint->usb_cmask = 0x00 ;
1953 		} else {
1954 			xfer->endpoint->usb_cmask = (-(0x04 << slot)) & 0xFE;
1955 		}
1956 		break;
1957 
1958 	case UE_ISOCHRONOUS:
1959 		switch (usbd_xfer_get_fps_shift(xfer)) {
1960 		case 0:
1961 			mask = 0xFF;
1962 			break;
1963 		case 1:
1964 			mask = 0x55;
1965 			break;
1966 		case 2:
1967 			mask = 0x11;
1968 			break;
1969 		default:
1970 			mask = 0x01;
1971 			break;
1972 		}
1973 
1974 		/* allocate a microframe multi-slot */
1975 
1976 		slot = usb_hs_bandwidth_adjust(udev,
1977 		    xfer->max_frame_size, USB_HS_MICRO_FRAMES_MAX, mask);
1978 
1979 		xfer->endpoint->usb_uframe = slot;
1980 		xfer->endpoint->usb_cmask = 0;
1981 		xfer->endpoint->usb_smask = mask << slot;
1982 		break;
1983 
1984 	default:
1985 		xfer->endpoint->usb_uframe = 0;
1986 		xfer->endpoint->usb_cmask = 0;
1987 		xfer->endpoint->usb_smask = 0;
1988 		break;
1989 	}
1990 
1991 	DPRINTFN(11, "slot=%d, mask=0x%02x\n",
1992 	    xfer->endpoint->usb_uframe,
1993 	    xfer->endpoint->usb_smask >> xfer->endpoint->usb_uframe);
1994 }
1995 
1996 /*------------------------------------------------------------------------*
1997  *	usb_hs_bandwidth_free
1998  *
1999  * This function is a wrapper function for "usb_hs_bandwidth_adjust()".
2000  *------------------------------------------------------------------------*/
2001 void
usb_hs_bandwidth_free(struct usb_xfer * xfer)2002 usb_hs_bandwidth_free(struct usb_xfer *xfer)
2003 {
2004 	struct usb_device *udev;
2005 	uint8_t slot;
2006 	uint8_t mask;
2007 
2008 	udev = xfer->xroot->udev;
2009 
2010 	if (udev->flags.usb_mode != USB_MODE_HOST)
2011 		return;		/* not supported */
2012 
2013 	xfer->endpoint->refcount_bw--;
2014 	if (xfer->endpoint->refcount_bw != 0)
2015 		return;		/* still allocated */
2016 
2017 	switch (xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE) {
2018 	case UE_INTERRUPT:
2019 	case UE_ISOCHRONOUS:
2020 
2021 		slot = xfer->endpoint->usb_uframe;
2022 		mask = xfer->endpoint->usb_smask;
2023 
2024 		/* free microframe slot(s): */
2025 		usb_hs_bandwidth_adjust(udev,
2026 		    -xfer->max_frame_size, slot, mask >> slot);
2027 
2028 		DPRINTFN(11, "slot=%d, mask=0x%02x\n",
2029 		    slot, mask >> slot);
2030 
2031 		xfer->endpoint->usb_uframe = 0;
2032 		xfer->endpoint->usb_cmask = 0;
2033 		xfer->endpoint->usb_smask = 0;
2034 		break;
2035 
2036 	default:
2037 		break;
2038 	}
2039 }
2040 
2041 /*------------------------------------------------------------------------*
2042  *	usb_isoc_time_expand
2043  *
2044  * This function will expand the time counter from 7-bit to 16-bit.
2045  *
2046  * Returns:
2047  *   16-bit isochronous time counter.
2048  *------------------------------------------------------------------------*/
2049 uint16_t
usb_isoc_time_expand(struct usb_bus * bus,uint16_t isoc_time_curr)2050 usb_isoc_time_expand(struct usb_bus *bus, uint16_t isoc_time_curr)
2051 {
2052 	uint16_t rem;
2053 
2054 	USB_BUS_LOCK_ASSERT(bus, MA_OWNED);
2055 
2056 	rem = bus->isoc_time_last & (USB_ISOC_TIME_MAX - 1);
2057 
2058 	isoc_time_curr &= (USB_ISOC_TIME_MAX - 1);
2059 
2060 	if (isoc_time_curr < rem) {
2061 		/* the time counter wrapped around */
2062 		bus->isoc_time_last += USB_ISOC_TIME_MAX;
2063 	}
2064 	/* update the remainder */
2065 
2066 	bus->isoc_time_last &= ~(USB_ISOC_TIME_MAX - 1);
2067 	bus->isoc_time_last |= isoc_time_curr;
2068 
2069 	return (bus->isoc_time_last);
2070 }
2071 
2072 /*------------------------------------------------------------------------*
2073  *	usbd_fs_isoc_schedule_alloc_slot
2074  *
2075  * This function will allocate bandwidth for an isochronous FULL speed
2076  * transaction in the FULL speed schedule.
2077  *
2078  * Returns:
2079  *    <8: Success
2080  * Else: Error
2081  *------------------------------------------------------------------------*/
2082 #if USB_HAVE_TT_SUPPORT
2083 uint8_t
usbd_fs_isoc_schedule_alloc_slot(struct usb_xfer * isoc_xfer,uint16_t isoc_time)2084 usbd_fs_isoc_schedule_alloc_slot(struct usb_xfer *isoc_xfer, uint16_t isoc_time)
2085 {
2086 	struct usb_xfer *xfer;
2087 	struct usb_xfer *pipe_xfer;
2088 	struct usb_bus *bus;
2089 	usb_frlength_t len;
2090 	usb_frlength_t data_len;
2091 	uint16_t delta;
2092 	uint16_t slot;
2093 	uint8_t retval;
2094 
2095 	data_len = 0;
2096 	slot = 0;
2097 
2098 	bus = isoc_xfer->xroot->bus;
2099 
2100 	TAILQ_FOREACH(xfer, &bus->intr_q.head, wait_entry) {
2101 		/* skip self, if any */
2102 
2103 		if (xfer == isoc_xfer)
2104 			continue;
2105 
2106 		/* check if this USB transfer is going through the same TT */
2107 
2108 		if (xfer->xroot->udev->parent_hs_hub !=
2109 		    isoc_xfer->xroot->udev->parent_hs_hub) {
2110 			continue;
2111 		}
2112 		if ((isoc_xfer->xroot->udev->parent_hs_hub->
2113 		    ddesc.bDeviceProtocol == UDPROTO_HSHUBMTT) &&
2114 		    (xfer->xroot->udev->hs_port_no !=
2115 		    isoc_xfer->xroot->udev->hs_port_no)) {
2116 			continue;
2117 		}
2118 		if (xfer->endpoint->methods != isoc_xfer->endpoint->methods)
2119 			continue;
2120 
2121 		/* check if isoc_time is part of this transfer */
2122 
2123 		delta = xfer->isoc_time_complete - isoc_time;
2124 		if (delta > 0 && delta <= xfer->nframes) {
2125 			delta = xfer->nframes - delta;
2126 
2127 			len = xfer->frlengths[delta];
2128 			len += 8;
2129 			len *= 7;
2130 			len /= 6;
2131 
2132 			data_len += len;
2133 		}
2134 
2135 		/*
2136 		 * Check double buffered transfers. Only stream ID
2137 		 * equal to zero is valid here!
2138 		 */
2139 		TAILQ_FOREACH(pipe_xfer, &xfer->endpoint->endpoint_q[0].head,
2140 		    wait_entry) {
2141 			/* skip self, if any */
2142 
2143 			if (pipe_xfer == isoc_xfer)
2144 				continue;
2145 
2146 			/* check if isoc_time is part of this transfer */
2147 
2148 			delta = pipe_xfer->isoc_time_complete - isoc_time;
2149 			if (delta > 0 && delta <= pipe_xfer->nframes) {
2150 				delta = pipe_xfer->nframes - delta;
2151 
2152 				len = pipe_xfer->frlengths[delta];
2153 				len += 8;
2154 				len *= 7;
2155 				len /= 6;
2156 
2157 				data_len += len;
2158 			}
2159 		}
2160 	}
2161 
2162 	while (data_len >= USB_FS_BYTES_PER_HS_UFRAME) {
2163 		data_len -= USB_FS_BYTES_PER_HS_UFRAME;
2164 		slot++;
2165 	}
2166 
2167 	/* check for overflow */
2168 
2169 	if (slot >= USB_FS_ISOC_UFRAME_MAX)
2170 		return (255);
2171 
2172 	retval = slot;
2173 
2174 	delta = isoc_xfer->isoc_time_complete - isoc_time;
2175 	if (delta > 0 && delta <= isoc_xfer->nframes) {
2176 		delta = isoc_xfer->nframes - delta;
2177 
2178 		len = isoc_xfer->frlengths[delta];
2179 		len += 8;
2180 		len *= 7;
2181 		len /= 6;
2182 
2183 		data_len += len;
2184 	}
2185 
2186 	while (data_len >= USB_FS_BYTES_PER_HS_UFRAME) {
2187 		data_len -= USB_FS_BYTES_PER_HS_UFRAME;
2188 		slot++;
2189 	}
2190 
2191 	/* check for overflow */
2192 
2193 	if (slot >= USB_FS_ISOC_UFRAME_MAX)
2194 		return (255);
2195 
2196 	return (retval);
2197 }
2198 #endif
2199 
2200 /*------------------------------------------------------------------------*
2201  *	usb_bus_port_get_device
2202  *
2203  * This function is NULL safe.
2204  *------------------------------------------------------------------------*/
2205 struct usb_device *
usb_bus_port_get_device(struct usb_bus * bus,struct usb_port * up)2206 usb_bus_port_get_device(struct usb_bus *bus, struct usb_port *up)
2207 {
2208 	if ((bus == NULL) || (up == NULL)) {
2209 		/* be NULL safe */
2210 		return (NULL);
2211 	}
2212 	if (up->device_index == 0) {
2213 		/* nothing to do */
2214 		return (NULL);
2215 	}
2216 	return (bus->devices[up->device_index]);
2217 }
2218 
2219 /*------------------------------------------------------------------------*
2220  *	usb_bus_port_set_device
2221  *
2222  * This function is NULL safe.
2223  *------------------------------------------------------------------------*/
2224 void
usb_bus_port_set_device(struct usb_bus * bus,struct usb_port * up,struct usb_device * udev,uint8_t device_index)2225 usb_bus_port_set_device(struct usb_bus *bus, struct usb_port *up,
2226     struct usb_device *udev, uint8_t device_index)
2227 {
2228 	if (bus == NULL) {
2229 		/* be NULL safe */
2230 		return;
2231 	}
2232 	/*
2233 	 * There is only one case where we don't
2234 	 * have an USB port, and that is the Root Hub!
2235          */
2236 	if (up) {
2237 		if (udev) {
2238 			up->device_index = device_index;
2239 		} else {
2240 			device_index = up->device_index;
2241 			up->device_index = 0;
2242 		}
2243 	}
2244 	/*
2245 	 * Make relationships to our new device
2246 	 */
2247 	if (device_index != 0) {
2248 #if USB_HAVE_UGEN
2249 		mtx_lock(&usb_ref_lock);
2250 #endif
2251 		bus->devices[device_index] = udev;
2252 #if USB_HAVE_UGEN
2253 		mtx_unlock(&usb_ref_lock);
2254 #endif
2255 	}
2256 	/*
2257 	 * Debug print
2258 	 */
2259 	DPRINTFN(2, "bus %p devices[%u] = %p\n", bus, device_index, udev);
2260 }
2261 
2262 /*------------------------------------------------------------------------*
2263  *	usb_needs_explore
2264  *
2265  * This functions is called when the USB event thread needs to run.
2266  *------------------------------------------------------------------------*/
2267 void
usb_needs_explore(struct usb_bus * bus,uint8_t do_probe)2268 usb_needs_explore(struct usb_bus *bus, uint8_t do_probe)
2269 {
2270 	uint8_t do_unlock;
2271 
2272 	DPRINTF("\n");
2273 
2274 	if (cold != 0) {
2275 		DPRINTF("Cold\n");
2276 		return;
2277 	}
2278 
2279 	if (bus == NULL) {
2280 		DPRINTF("No bus pointer!\n");
2281 		return;
2282 	}
2283 	if ((bus->devices == NULL) ||
2284 	    (bus->devices[USB_ROOT_HUB_ADDR] == NULL)) {
2285 		DPRINTF("No root HUB\n");
2286 		return;
2287 	}
2288 	if (mtx_owned(&bus->bus_mtx)) {
2289 		do_unlock = 0;
2290 	} else {
2291 		USB_BUS_LOCK(bus);
2292 		do_unlock = 1;
2293 	}
2294 	if (do_probe) {
2295 		bus->do_probe = 1;
2296 	}
2297 	if (usb_proc_msignal(USB_BUS_EXPLORE_PROC(bus),
2298 	    &bus->explore_msg[0], &bus->explore_msg[1])) {
2299 		/* ignore */
2300 	}
2301 	if (do_unlock) {
2302 		USB_BUS_UNLOCK(bus);
2303 	}
2304 }
2305 
2306 /*------------------------------------------------------------------------*
2307  *	usb_needs_explore_all
2308  *
2309  * This function is called whenever a new driver is loaded and will
2310  * cause that all USB buses are re-explored.
2311  *------------------------------------------------------------------------*/
2312 void
usb_needs_explore_all(void)2313 usb_needs_explore_all(void)
2314 {
2315 	struct usb_bus *bus;
2316 	devclass_t dc;
2317 	device_t dev;
2318 	int max;
2319 
2320 	DPRINTFN(3, "\n");
2321 
2322 	dc = usb_devclass_ptr;
2323 	if (dc == NULL) {
2324 		DPRINTFN(0, "no devclass\n");
2325 		return;
2326 	}
2327 	/*
2328 	 * Explore all USB buses in parallel.
2329 	 */
2330 	max = devclass_get_maxunit(dc);
2331 	while (max >= 0) {
2332 		dev = devclass_get_device(dc, max);
2333 		if (dev) {
2334 			bus = device_get_softc(dev);
2335 			if (bus) {
2336 				usb_needs_explore(bus, 1);
2337 			}
2338 		}
2339 		max--;
2340 	}
2341 }
2342 
2343 /*------------------------------------------------------------------------*
2344  *	usb_needs_explore_init
2345  *
2346  * This function will ensure that the USB controllers are not enumerated
2347  * until the "cold" variable is cleared.
2348  *------------------------------------------------------------------------*/
2349 static void
usb_needs_explore_init(void * arg)2350 usb_needs_explore_init(void *arg)
2351 {
2352 	/*
2353 	 * The cold variable should be cleared prior to this function
2354 	 * being called:
2355 	 */
2356 	if (cold == 0)
2357 		usb_needs_explore_all();
2358 	else
2359 		DPRINTFN(-1, "Cold variable is still set!\n");
2360 }
2361 SYSINIT(usb_needs_explore_init, SI_SUB_KICK_SCHEDULER, SI_ORDER_SECOND, usb_needs_explore_init, NULL);
2362 
2363 /*------------------------------------------------------------------------*
2364  *	usb_bus_power_update
2365  *
2366  * This function will ensure that all USB devices on the given bus are
2367  * properly suspended or resumed according to the device transfer
2368  * state.
2369  *------------------------------------------------------------------------*/
2370 #if USB_HAVE_POWERD
2371 void
usb_bus_power_update(struct usb_bus * bus)2372 usb_bus_power_update(struct usb_bus *bus)
2373 {
2374 	usb_needs_explore(bus, 0 /* no probe */ );
2375 }
2376 #endif
2377 
2378 /*------------------------------------------------------------------------*
2379  *	usbd_transfer_power_ref
2380  *
2381  * This function will modify the power save reference counts and
2382  * wakeup the USB device associated with the given USB transfer, if
2383  * needed.
2384  *------------------------------------------------------------------------*/
2385 #if USB_HAVE_POWERD
2386 void
usbd_transfer_power_ref(struct usb_xfer * xfer,int val)2387 usbd_transfer_power_ref(struct usb_xfer *xfer, int val)
2388 {
2389 	static const usb_power_mask_t power_mask[4] = {
2390 		[UE_CONTROL] = USB_HW_POWER_CONTROL,
2391 		[UE_BULK] = USB_HW_POWER_BULK,
2392 		[UE_INTERRUPT] = USB_HW_POWER_INTERRUPT,
2393 		[UE_ISOCHRONOUS] = USB_HW_POWER_ISOC,
2394 	};
2395 	struct usb_device *udev;
2396 	uint8_t needs_explore;
2397 	uint8_t needs_hw_power;
2398 	uint8_t xfer_type;
2399 
2400 	udev = xfer->xroot->udev;
2401 
2402 	if (udev->device_index == USB_ROOT_HUB_ADDR) {
2403 		/* no power save for root HUB */
2404 		return;
2405 	}
2406 	USB_BUS_LOCK(udev->bus);
2407 
2408 	xfer_type = xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE;
2409 
2410 	udev->pwr_save.last_xfer_time = ticks;
2411 	udev->pwr_save.type_refs[xfer_type] += val;
2412 
2413 	if (xfer->flags_int.control_xfr) {
2414 		udev->pwr_save.read_refs += val;
2415 		if (xfer->flags_int.usb_mode == USB_MODE_HOST) {
2416 			/*
2417 			 * It is not allowed to suspend during a
2418 			 * control transfer:
2419 			 */
2420 			udev->pwr_save.write_refs += val;
2421 		}
2422 	} else if (USB_GET_DATA_ISREAD(xfer)) {
2423 		udev->pwr_save.read_refs += val;
2424 	} else {
2425 		udev->pwr_save.write_refs += val;
2426 	}
2427 
2428 	if (val > 0) {
2429 		if (udev->flags.self_suspended)
2430 			needs_explore = usb_peer_should_wakeup(udev);
2431 		else
2432 			needs_explore = 0;
2433 
2434 		if (!(udev->bus->hw_power_state & power_mask[xfer_type])) {
2435 			DPRINTF("Adding type %u to power state\n", xfer_type);
2436 			udev->bus->hw_power_state |= power_mask[xfer_type];
2437 			needs_hw_power = 1;
2438 		} else {
2439 			needs_hw_power = 0;
2440 		}
2441 	} else {
2442 		needs_explore = 0;
2443 		needs_hw_power = 0;
2444 	}
2445 
2446 	USB_BUS_UNLOCK(udev->bus);
2447 
2448 	if (needs_explore) {
2449 		DPRINTF("update\n");
2450 		usb_bus_power_update(udev->bus);
2451 	} else if (needs_hw_power) {
2452 		DPRINTF("needs power\n");
2453 		if (udev->bus->methods->set_hw_power != NULL) {
2454 			(udev->bus->methods->set_hw_power) (udev->bus);
2455 		}
2456 	}
2457 }
2458 #endif
2459 
2460 /*------------------------------------------------------------------------*
2461  *	usb_peer_should_wakeup
2462  *
2463  * This function returns non-zero if the current device should wake up.
2464  *------------------------------------------------------------------------*/
2465 static uint8_t
usb_peer_should_wakeup(struct usb_device * udev)2466 usb_peer_should_wakeup(struct usb_device *udev)
2467 {
2468 	return (((udev->power_mode == USB_POWER_MODE_ON) &&
2469 	    (udev->flags.usb_mode == USB_MODE_HOST)) ||
2470 	    (udev->driver_added_refcount != udev->bus->driver_added_refcount) ||
2471 	    (udev->re_enumerate_wait != USB_RE_ENUM_DONE) ||
2472 	    (udev->pwr_save.type_refs[UE_ISOCHRONOUS] != 0) ||
2473 	    (udev->pwr_save.write_refs != 0) ||
2474 	    ((udev->pwr_save.read_refs != 0) &&
2475 	    (udev->flags.usb_mode == USB_MODE_HOST) &&
2476 	    (usb_peer_can_wakeup(udev) == 0)));
2477 }
2478 
2479 /*------------------------------------------------------------------------*
2480  *	usb_bus_powerd
2481  *
2482  * This function implements the USB power daemon and is called
2483  * regularly from the USB explore thread.
2484  *------------------------------------------------------------------------*/
2485 #if USB_HAVE_POWERD
2486 void
usb_bus_powerd(struct usb_bus * bus)2487 usb_bus_powerd(struct usb_bus *bus)
2488 {
2489 	struct usb_device *udev;
2490 	usb_ticks_t temp;
2491 	usb_ticks_t limit;
2492 	usb_ticks_t mintime;
2493 	usb_size_t type_refs[5];
2494 	uint8_t x;
2495 
2496 	limit = usb_power_timeout;
2497 	if (limit == 0)
2498 		limit = hz;
2499 	else if (limit > 255)
2500 		limit = 255 * hz;
2501 	else
2502 		limit = limit * hz;
2503 
2504 	DPRINTF("bus=%p\n", bus);
2505 
2506 	USB_BUS_LOCK(bus);
2507 
2508 	/*
2509 	 * The root HUB device is never suspended
2510 	 * and we simply skip it.
2511 	 */
2512 	for (x = USB_ROOT_HUB_ADDR + 1;
2513 	    x != bus->devices_max; x++) {
2514 		udev = bus->devices[x];
2515 		if (udev == NULL)
2516 			continue;
2517 
2518 		temp = ticks - udev->pwr_save.last_xfer_time;
2519 
2520 		if (usb_peer_should_wakeup(udev)) {
2521 			/* check if we are suspended */
2522 			if (udev->flags.self_suspended != 0) {
2523 				USB_BUS_UNLOCK(bus);
2524 				usb_dev_resume_peer(udev);
2525 				USB_BUS_LOCK(bus);
2526 			}
2527 		} else if ((temp >= limit) &&
2528 		    (udev->flags.usb_mode == USB_MODE_HOST) &&
2529 		    (udev->flags.self_suspended == 0)) {
2530 			/* try to do suspend */
2531 
2532 			USB_BUS_UNLOCK(bus);
2533 			usb_dev_suspend_peer(udev);
2534 			USB_BUS_LOCK(bus);
2535 		}
2536 	}
2537 
2538 	/* reset counters */
2539 
2540 	mintime = (usb_ticks_t)-1;
2541 	type_refs[0] = 0;
2542 	type_refs[1] = 0;
2543 	type_refs[2] = 0;
2544 	type_refs[3] = 0;
2545 	type_refs[4] = 0;
2546 
2547 	/* Re-loop all the devices to get the actual state */
2548 
2549 	for (x = USB_ROOT_HUB_ADDR + 1;
2550 	    x != bus->devices_max; x++) {
2551 		udev = bus->devices[x];
2552 		if (udev == NULL)
2553 			continue;
2554 
2555 		/* we found a non-Root-Hub USB device */
2556 		type_refs[4] += 1;
2557 
2558 		/* "last_xfer_time" can be updated by a resume */
2559 		temp = ticks - udev->pwr_save.last_xfer_time;
2560 
2561 		/*
2562 		 * Compute minimum time since last transfer for the complete
2563 		 * bus:
2564 		 */
2565 		if (temp < mintime)
2566 			mintime = temp;
2567 
2568 		if (udev->flags.self_suspended == 0) {
2569 			type_refs[0] += udev->pwr_save.type_refs[0];
2570 			type_refs[1] += udev->pwr_save.type_refs[1];
2571 			type_refs[2] += udev->pwr_save.type_refs[2];
2572 			type_refs[3] += udev->pwr_save.type_refs[3];
2573 		}
2574 	}
2575 
2576 	if (mintime >= (usb_ticks_t)(1 * hz)) {
2577 		/* recompute power masks */
2578 		DPRINTF("Recomputing power masks\n");
2579 		bus->hw_power_state = 0;
2580 		if (type_refs[UE_CONTROL] != 0)
2581 			bus->hw_power_state |= USB_HW_POWER_CONTROL;
2582 		if (type_refs[UE_BULK] != 0)
2583 			bus->hw_power_state |= USB_HW_POWER_BULK;
2584 		if (type_refs[UE_INTERRUPT] != 0)
2585 			bus->hw_power_state |= USB_HW_POWER_INTERRUPT;
2586 		if (type_refs[UE_ISOCHRONOUS] != 0)
2587 			bus->hw_power_state |= USB_HW_POWER_ISOC;
2588 		if (type_refs[4] != 0)
2589 			bus->hw_power_state |= USB_HW_POWER_NON_ROOT_HUB;
2590 	}
2591 	USB_BUS_UNLOCK(bus);
2592 
2593 	if (bus->methods->set_hw_power != NULL) {
2594 		/* always update hardware power! */
2595 		(bus->methods->set_hw_power) (bus);
2596 	}
2597 	return;
2598 }
2599 #endif
2600 
2601 static usb_error_t
usbd_device_30_remote_wakeup(struct usb_device * udev,uint8_t bRequest)2602 usbd_device_30_remote_wakeup(struct usb_device *udev, uint8_t bRequest)
2603 {
2604 	struct usb_device_request req = {};
2605 
2606 	req.bmRequestType = UT_WRITE_INTERFACE;
2607 	req.bRequest = bRequest;
2608 	USETW(req.wValue, USB_INTERFACE_FUNC_SUSPEND);
2609 	USETW(req.wIndex, USB_INTERFACE_FUNC_SUSPEND_LP |
2610 	    USB_INTERFACE_FUNC_SUSPEND_RW);
2611 
2612 	return (usbd_do_request(udev, NULL, &req, 0));
2613 }
2614 
2615 static usb_error_t
usbd_clear_dev_wakeup(struct usb_device * udev)2616 usbd_clear_dev_wakeup(struct usb_device *udev)
2617 {
2618 	usb_error_t err;
2619 
2620 	if (usb_device_20_compatible(udev)) {
2621 		err = usbd_req_clear_device_feature(udev,
2622 		    NULL, UF_DEVICE_REMOTE_WAKEUP);
2623 	} else {
2624 		err = usbd_device_30_remote_wakeup(udev,
2625 		    UR_CLEAR_FEATURE);
2626 	}
2627 	return (err);
2628 }
2629 
2630 static usb_error_t
usbd_set_dev_wakeup(struct usb_device * udev)2631 usbd_set_dev_wakeup(struct usb_device *udev)
2632 {
2633 	usb_error_t err;
2634 
2635 	if (usb_device_20_compatible(udev)) {
2636 		err = usbd_req_set_device_feature(udev,
2637 		    NULL, UF_DEVICE_REMOTE_WAKEUP);
2638 	} else {
2639 		err = usbd_device_30_remote_wakeup(udev,
2640 		    UR_SET_FEATURE);
2641 	}
2642 	return (err);
2643 }
2644 
2645 /*------------------------------------------------------------------------*
2646  *	usb_dev_resume_peer
2647  *
2648  * This function will resume an USB peer and do the required USB
2649  * signalling to get an USB device out of the suspended state.
2650  *------------------------------------------------------------------------*/
2651 static void
usb_dev_resume_peer(struct usb_device * udev)2652 usb_dev_resume_peer(struct usb_device *udev)
2653 {
2654 	struct usb_bus *bus;
2655 	int err;
2656 
2657 	/* be NULL safe */
2658 	if (udev == NULL)
2659 		return;
2660 
2661 	/* check if already resumed */
2662 	if (udev->flags.self_suspended == 0)
2663 		return;
2664 
2665 	/* we need a parent HUB to do resume */
2666 	if (udev->parent_hub == NULL)
2667 		return;
2668 
2669 	DPRINTF("udev=%p\n", udev);
2670 
2671 	if ((udev->flags.usb_mode == USB_MODE_DEVICE) &&
2672 	    (udev->flags.remote_wakeup == 0)) {
2673 		/*
2674 		 * If the host did not set the remote wakeup feature, we can
2675 		 * not wake it up either!
2676 		 */
2677 		DPRINTF("remote wakeup is not set!\n");
2678 		return;
2679 	}
2680 	/* get bus pointer */
2681 	bus = udev->bus;
2682 
2683 	/* resume parent hub first */
2684 	usb_dev_resume_peer(udev->parent_hub);
2685 
2686 	/* reduce chance of instant resume failure by waiting a little bit */
2687 	usb_pause_mtx(NULL, USB_MS_TO_TICKS(20));
2688 
2689 	if (usb_device_20_compatible(udev)) {
2690 		/* resume current port (Valid in Host and Device Mode) */
2691 		err = usbd_req_clear_port_feature(udev->parent_hub,
2692 		    NULL, udev->port_no, UHF_PORT_SUSPEND);
2693 	} else {
2694 		/* resume current port (Valid in Host and Device Mode) */
2695 		err = usbd_req_set_port_link_state(udev->parent_hub,
2696 		    NULL, udev->port_no, UPS_PORT_LS_U0);
2697 	}
2698 
2699 	if (err != 0) {
2700 		DPRINTFN(0, "Resuming port failed: %s (ignored)\n",
2701 		    usbd_errstr(err));
2702 	}
2703 
2704 	/* resume settle time */
2705 	usb_pause_mtx(NULL, USB_MS_TO_TICKS(usb_port_resume_delay));
2706 
2707 	if (bus->methods->device_resume != NULL) {
2708 		/* resume USB device on the USB controller */
2709 		(bus->methods->device_resume) (udev);
2710 	}
2711 	USB_BUS_LOCK(bus);
2712 	/* set that this device is now resumed */
2713 	udev->flags.self_suspended = 0;
2714 #if USB_HAVE_POWERD
2715 	/* make sure that we don't go into suspend right away */
2716 	udev->pwr_save.last_xfer_time = ticks;
2717 
2718 	/* make sure the needed power masks are on */
2719 	if (udev->pwr_save.type_refs[UE_CONTROL] != 0)
2720 		bus->hw_power_state |= USB_HW_POWER_CONTROL;
2721 	if (udev->pwr_save.type_refs[UE_BULK] != 0)
2722 		bus->hw_power_state |= USB_HW_POWER_BULK;
2723 	if (udev->pwr_save.type_refs[UE_INTERRUPT] != 0)
2724 		bus->hw_power_state |= USB_HW_POWER_INTERRUPT;
2725 	if (udev->pwr_save.type_refs[UE_ISOCHRONOUS] != 0)
2726 		bus->hw_power_state |= USB_HW_POWER_ISOC;
2727 #endif
2728 	USB_BUS_UNLOCK(bus);
2729 
2730 	if (bus->methods->set_hw_power != NULL) {
2731 		/* always update hardware power! */
2732 		(bus->methods->set_hw_power) (bus);
2733 	}
2734 
2735 	usbd_sr_lock(udev);
2736 
2737 	/* notify all sub-devices about resume */
2738 	err = usb_suspend_resume(udev, 0);
2739 
2740 	usbd_sr_unlock(udev);
2741 
2742 	/* check if peer has wakeup capability */
2743 	if (usb_peer_can_wakeup(udev)) {
2744 		/* clear remote wakeup */
2745 		err = usbd_clear_dev_wakeup(udev);
2746 		if (err) {
2747 			DPRINTFN(0, "Clearing device "
2748 			    "remote wakeup failed: %s\n",
2749 			    usbd_errstr(err));
2750 		}
2751 	}
2752 }
2753 
2754 /*------------------------------------------------------------------------*
2755  *	usb_dev_suspend_peer
2756  *
2757  * This function will suspend an USB peer and do the required USB
2758  * signalling to get an USB device into the suspended state.
2759  *------------------------------------------------------------------------*/
2760 static void
usb_dev_suspend_peer(struct usb_device * udev)2761 usb_dev_suspend_peer(struct usb_device *udev)
2762 {
2763 	struct usb_device *child;
2764 	int err;
2765 	uint8_t x;
2766 	uint8_t nports;
2767 
2768 repeat:
2769 	/* be NULL safe */
2770 	if (udev == NULL)
2771 		return;
2772 
2773 	/* check if already suspended */
2774 	if (udev->flags.self_suspended)
2775 		return;
2776 
2777 	/* we need a parent HUB to do suspend */
2778 	if (udev->parent_hub == NULL)
2779 		return;
2780 
2781 	DPRINTF("udev=%p\n", udev);
2782 
2783 	/* check if the current device is a HUB */
2784 	if (udev->hub != NULL) {
2785 		nports = udev->hub->nports;
2786 
2787 		/* check if all devices on the HUB are suspended */
2788 		for (x = 0; x != nports; x++) {
2789 			child = usb_bus_port_get_device(udev->bus,
2790 			    udev->hub->ports + x);
2791 
2792 			if (child == NULL)
2793 				continue;
2794 
2795 			if (child->flags.self_suspended)
2796 				continue;
2797 
2798 			DPRINTFN(1, "Port %u is busy on the HUB!\n", x + 1);
2799 			return;
2800 		}
2801 	}
2802 
2803 	if (usb_peer_can_wakeup(udev)) {
2804 		/*
2805 		 * This request needs to be done before we set
2806 		 * "udev->flags.self_suspended":
2807 		 */
2808 
2809 		/* allow device to do remote wakeup */
2810 		err = usbd_set_dev_wakeup(udev);
2811 		if (err) {
2812 			DPRINTFN(0, "Setting device "
2813 			    "remote wakeup failed\n");
2814 		}
2815 	}
2816 
2817 	USB_BUS_LOCK(udev->bus);
2818 	/*
2819 	 * Checking for suspend condition and setting suspended bit
2820 	 * must be atomic!
2821 	 */
2822 	err = usb_peer_should_wakeup(udev);
2823 	if (err == 0) {
2824 		/*
2825 		 * Set that this device is suspended. This variable
2826 		 * must be set before calling USB controller suspend
2827 		 * callbacks.
2828 		 */
2829 		udev->flags.self_suspended = 1;
2830 	}
2831 	USB_BUS_UNLOCK(udev->bus);
2832 
2833 	if (err != 0) {
2834 		if (usb_peer_can_wakeup(udev)) {
2835 			/* allow device to do remote wakeup */
2836 			err = usbd_clear_dev_wakeup(udev);
2837 			if (err) {
2838 				DPRINTFN(0, "Setting device "
2839 				    "remote wakeup failed\n");
2840 			}
2841 		}
2842 
2843 		if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2844 			/* resume parent HUB first */
2845 			usb_dev_resume_peer(udev->parent_hub);
2846 
2847 			/* reduce chance of instant resume failure by waiting a little bit */
2848 			usb_pause_mtx(NULL, USB_MS_TO_TICKS(20));
2849 
2850 			/* resume current port (Valid in Host and Device Mode) */
2851 			err = usbd_req_clear_port_feature(udev->parent_hub,
2852 			    NULL, udev->port_no, UHF_PORT_SUSPEND);
2853 
2854 			/* resume settle time */
2855 			usb_pause_mtx(NULL, USB_MS_TO_TICKS(usb_port_resume_delay));
2856 		}
2857 		DPRINTF("Suspend was cancelled!\n");
2858 		return;
2859 	}
2860 
2861 	usbd_sr_lock(udev);
2862 
2863 	/* notify all sub-devices about suspend */
2864 	err = usb_suspend_resume(udev, 1);
2865 
2866 	usbd_sr_unlock(udev);
2867 
2868 	if (udev->bus->methods->device_suspend != NULL) {
2869 		usb_timeout_t temp;
2870 
2871 		/* suspend device on the USB controller */
2872 		(udev->bus->methods->device_suspend) (udev);
2873 
2874 		/* do DMA delay */
2875 		temp = usbd_get_dma_delay(udev);
2876 		if (temp != 0)
2877 			usb_pause_mtx(NULL, USB_MS_TO_TICKS(temp));
2878 	}
2879 
2880 	if (usb_device_20_compatible(udev)) {
2881 		/* suspend current port */
2882 		err = usbd_req_set_port_feature(udev->parent_hub,
2883 		    NULL, udev->port_no, UHF_PORT_SUSPEND);
2884 		if (err) {
2885 			DPRINTFN(0, "Suspending port failed\n");
2886 			return;
2887 		}
2888 	} else {
2889 		/* suspend current port */
2890 		err = usbd_req_set_port_link_state(udev->parent_hub,
2891 		    NULL, udev->port_no, UPS_PORT_LS_U3);
2892 		if (err) {
2893 			DPRINTFN(0, "Suspending port failed\n");
2894 			return;
2895 		}
2896 	}
2897 
2898 	udev = udev->parent_hub;
2899 	goto repeat;
2900 }
2901 
2902 /*------------------------------------------------------------------------*
2903  *	usbd_set_power_mode
2904  *
2905  * This function will set the power mode, see USB_POWER_MODE_XXX for a
2906  * USB device.
2907  *------------------------------------------------------------------------*/
2908 void
usbd_set_power_mode(struct usb_device * udev,uint8_t power_mode)2909 usbd_set_power_mode(struct usb_device *udev, uint8_t power_mode)
2910 {
2911 	/* filter input argument */
2912 	if ((power_mode != USB_POWER_MODE_ON) &&
2913 	    (power_mode != USB_POWER_MODE_OFF))
2914 		power_mode = USB_POWER_MODE_SAVE;
2915 
2916 	power_mode = usbd_filter_power_mode(udev, power_mode);
2917 
2918 	udev->power_mode = power_mode;	/* update copy of power mode */
2919 
2920 #if USB_HAVE_POWERD
2921 	usb_bus_power_update(udev->bus);
2922 #else
2923 	usb_needs_explore(udev->bus, 0 /* no probe */ );
2924 #endif
2925 }
2926 
2927 /*------------------------------------------------------------------------*
2928  *	usbd_filter_power_mode
2929  *
2930  * This function filters the power mode based on hardware requirements.
2931  *------------------------------------------------------------------------*/
2932 uint8_t
usbd_filter_power_mode(struct usb_device * udev,uint8_t power_mode)2933 usbd_filter_power_mode(struct usb_device *udev, uint8_t power_mode)
2934 {
2935 	const struct usb_bus_methods *mtod;
2936 	int8_t temp;
2937 
2938 	mtod = udev->bus->methods;
2939 	temp = -1;
2940 
2941 	if (mtod->get_power_mode != NULL)
2942 		(mtod->get_power_mode) (udev, &temp);
2943 
2944 	/* check if we should not filter */
2945 	if (temp < 0)
2946 		return (power_mode);
2947 
2948 	/* use fixed power mode given by hardware driver */
2949 	return (temp);
2950 }
2951 
2952 /*------------------------------------------------------------------------*
2953  *	usbd_start_re_enumerate
2954  *
2955  * This function starts re-enumeration of the given USB device. This
2956  * function does not need to be called BUS-locked. This function does
2957  * not wait until the re-enumeration is completed.
2958  *------------------------------------------------------------------------*/
2959 void
usbd_start_re_enumerate(struct usb_device * udev)2960 usbd_start_re_enumerate(struct usb_device *udev)
2961 {
2962 	if (udev->re_enumerate_wait == USB_RE_ENUM_DONE) {
2963 		udev->re_enumerate_wait = USB_RE_ENUM_START;
2964 		usb_needs_explore(udev->bus, 0);
2965 	}
2966 }
2967 
2968 /*-----------------------------------------------------------------------*
2969  *	usbd_start_set_config
2970  *
2971  * This function starts setting a USB configuration. This function
2972  * does not need to be called BUS-locked. This function does not wait
2973  * until the set USB configuratino is completed.
2974  *------------------------------------------------------------------------*/
2975 usb_error_t
usbd_start_set_config(struct usb_device * udev,uint8_t index)2976 usbd_start_set_config(struct usb_device *udev, uint8_t index)
2977 {
2978 	if (udev->re_enumerate_wait == USB_RE_ENUM_DONE) {
2979 		if (udev->curr_config_index == index) {
2980 			/* no change needed */
2981 			return (0);
2982 		}
2983 		udev->next_config_index = index;
2984 		udev->re_enumerate_wait = USB_RE_ENUM_SET_CONFIG;
2985 		usb_needs_explore(udev->bus, 0);
2986 		return (0);
2987 	} else if (udev->re_enumerate_wait == USB_RE_ENUM_SET_CONFIG) {
2988 		if (udev->next_config_index == index) {
2989 			/* no change needed */
2990 			return (0);
2991 		}
2992 	}
2993 	return (USB_ERR_PENDING_REQUESTS);
2994 }
2995