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