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