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