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