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