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