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