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