xref: /freebsd/sys/dev/usb/usb_hub.c (revision 39beb93c3f8bdbf72a61fda42300b5ebed7390c8)
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 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 <dev/usb/usb_defs.h>
34 #include <dev/usb/usb_mfunc.h>
35 #include <dev/usb/usb_error.h>
36 #include <dev/usb/usb.h>
37 #include <dev/usb/usb_ioctl.h>
38 
39 #define	USB_DEBUG_VAR uhub_debug
40 
41 #include <dev/usb/usb_core.h>
42 #include <dev/usb/usb_process.h>
43 #include <dev/usb/usb_device.h>
44 #include <dev/usb/usb_request.h>
45 #include <dev/usb/usb_debug.h>
46 #include <dev/usb/usb_hub.h>
47 #include <dev/usb/usb_util.h>
48 #include <dev/usb/usb_busdma.h>
49 #include <dev/usb/usb_transfer.h>
50 #include <dev/usb/usb_dynamic.h>
51 
52 #include <dev/usb/usb_controller.h>
53 #include <dev/usb/usb_bus.h>
54 
55 #define	UHUB_INTR_INTERVAL 250		/* ms */
56 #define	UHUB_N_TRANSFER 1
57 
58 #if USB_DEBUG
59 static int uhub_debug = 0;
60 
61 SYSCTL_NODE(_hw_usb2, OID_AUTO, uhub, CTLFLAG_RW, 0, "USB HUB");
62 SYSCTL_INT(_hw_usb2_uhub, OID_AUTO, debug, CTLFLAG_RW, &uhub_debug, 0,
63     "Debug level");
64 #endif
65 
66 static int usb2_power_timeout = 30;	/* seconds */
67 
68 SYSCTL_INT(_hw_usb2, OID_AUTO, power_timeout, CTLFLAG_RW,
69     &usb2_power_timeout, 0, "USB power timeout");
70 
71 struct uhub_current_state {
72 	uint16_t port_change;
73 	uint16_t port_status;
74 };
75 
76 struct uhub_softc {
77 	struct uhub_current_state sc_st;/* current state */
78 	device_t sc_dev;		/* base device */
79 	struct usb2_device *sc_udev;	/* USB device */
80 	struct usb2_xfer *sc_xfer[UHUB_N_TRANSFER];	/* interrupt xfer */
81 	uint8_t	sc_flags;
82 #define	UHUB_FLAG_DID_EXPLORE 0x01
83 	char	sc_name[32];
84 };
85 
86 #define	UHUB_PROTO(sc) ((sc)->sc_udev->ddesc.bDeviceProtocol)
87 #define	UHUB_IS_HIGH_SPEED(sc) (UHUB_PROTO(sc) != UDPROTO_FSHUB)
88 #define	UHUB_IS_SINGLE_TT(sc) (UHUB_PROTO(sc) == UDPROTO_HSHUBSTT)
89 
90 /* prototypes for type checking: */
91 
92 static device_probe_t uhub_probe;
93 static device_attach_t uhub_attach;
94 static device_detach_t uhub_detach;
95 static device_suspend_t uhub_suspend;
96 static device_resume_t uhub_resume;
97 
98 static bus_driver_added_t uhub_driver_added;
99 static bus_child_location_str_t uhub_child_location_string;
100 static bus_child_pnpinfo_str_t uhub_child_pnpinfo_string;
101 
102 static usb2_callback_t uhub_intr_callback;
103 
104 static void usb2_dev_resume_peer(struct usb2_device *udev);
105 static void usb2_dev_suspend_peer(struct usb2_device *udev);
106 
107 static const struct usb2_config uhub_config[UHUB_N_TRANSFER] = {
108 
109 	[0] = {
110 		.type = UE_INTERRUPT,
111 		.endpoint = UE_ADDR_ANY,
112 		.direction = UE_DIR_ANY,
113 		.mh.timeout = 0,
114 		.mh.flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
115 		.mh.bufsize = 0,	/* use wMaxPacketSize */
116 		.mh.callback = &uhub_intr_callback,
117 		.mh.interval = UHUB_INTR_INTERVAL,
118 	},
119 };
120 
121 /*
122  * driver instance for "hub" connected to "usb"
123  * and "hub" connected to "hub"
124  */
125 static devclass_t uhub_devclass;
126 
127 static driver_t uhub_driver =
128 {
129 	.name = "ushub",
130 	.methods = (device_method_t[]){
131 		DEVMETHOD(device_probe, uhub_probe),
132 		DEVMETHOD(device_attach, uhub_attach),
133 		DEVMETHOD(device_detach, uhub_detach),
134 
135 		DEVMETHOD(device_suspend, uhub_suspend),
136 		DEVMETHOD(device_resume, uhub_resume),
137 		DEVMETHOD(device_shutdown, bus_generic_shutdown),
138 
139 		DEVMETHOD(bus_child_location_str, uhub_child_location_string),
140 		DEVMETHOD(bus_child_pnpinfo_str, uhub_child_pnpinfo_string),
141 		DEVMETHOD(bus_driver_added, uhub_driver_added),
142 		{0, 0}
143 	},
144 	.size = sizeof(struct uhub_softc)
145 };
146 
147 DRIVER_MODULE(ushub, usbus, uhub_driver, uhub_devclass, 0, 0);
148 DRIVER_MODULE(ushub, ushub, uhub_driver, uhub_devclass, NULL, 0);
149 
150 static void
151 uhub_intr_callback(struct usb2_xfer *xfer)
152 {
153 	struct uhub_softc *sc = xfer->priv_sc;
154 
155 	switch (USB_GET_STATE(xfer)) {
156 	case USB_ST_TRANSFERRED:
157 		DPRINTFN(2, "\n");
158 		/*
159 		 * This is an indication that some port
160 		 * has changed status. Notify the bus
161 		 * event handler thread that we need
162 		 * to be explored again:
163 		 */
164 		usb2_needs_explore(sc->sc_udev->bus, 0);
165 
166 	case USB_ST_SETUP:
167 		xfer->frlengths[0] = xfer->max_data_length;
168 		usb2_start_hardware(xfer);
169 		break;
170 
171 	default:			/* Error */
172 		if (xfer->error != USB_ERR_CANCELLED) {
173 			/*
174 			 * Do a clear-stall. The "stall_pipe" flag
175 			 * will get cleared before next callback by
176 			 * the USB stack.
177 			 */
178 			xfer->flags.stall_pipe = 1;
179 			xfer->frlengths[0] = xfer->max_data_length;
180 			usb2_start_hardware(xfer);
181 		}
182 		break;
183 	}
184 }
185 
186 /*------------------------------------------------------------------------*
187  *	uhub_explore_sub - subroutine
188  *
189  * Return values:
190  *    0: Success
191  * Else: A control transaction failed
192  *------------------------------------------------------------------------*/
193 static usb2_error_t
194 uhub_explore_sub(struct uhub_softc *sc, struct usb2_port *up)
195 {
196 	struct usb2_bus *bus;
197 	struct usb2_device *child;
198 	uint8_t refcount;
199 	usb2_error_t err;
200 
201 	bus = sc->sc_udev->bus;
202 	err = 0;
203 
204 	/* get driver added refcount from USB bus */
205 	refcount = bus->driver_added_refcount;
206 
207 	/* get device assosiated with the given port */
208 	child = usb2_bus_port_get_device(bus, up);
209 	if (child == NULL) {
210 		/* nothing to do */
211 		goto done;
212 	}
213 	/* check if probe and attach should be done */
214 
215 	if (child->driver_added_refcount != refcount) {
216 		child->driver_added_refcount = refcount;
217 		err = usb2_probe_and_attach(child,
218 		    USB_IFACE_INDEX_ANY);
219 		if (err) {
220 			goto done;
221 		}
222 	}
223 	/* start control transfer, if device mode */
224 
225 	if (child->flags.usb2_mode == USB_MODE_DEVICE) {
226 		usb2_default_transfer_setup(child);
227 	}
228 	/* if a HUB becomes present, do a recursive HUB explore */
229 
230 	if (child->hub) {
231 		err = (child->hub->explore) (child);
232 	}
233 done:
234 	return (err);
235 }
236 
237 /*------------------------------------------------------------------------*
238  *	uhub_read_port_status - factored out code
239  *------------------------------------------------------------------------*/
240 static usb2_error_t
241 uhub_read_port_status(struct uhub_softc *sc, uint8_t portno)
242 {
243 	struct usb2_port_status ps;
244 	usb2_error_t err;
245 
246 	err = usb2_req_get_port_status(
247 	    sc->sc_udev, NULL, &ps, portno);
248 
249 	/* update status regardless of error */
250 
251 	sc->sc_st.port_status = UGETW(ps.wPortStatus);
252 	sc->sc_st.port_change = UGETW(ps.wPortChange);
253 
254 	/* debugging print */
255 
256 	DPRINTFN(4, "port %d, wPortStatus=0x%04x, "
257 	    "wPortChange=0x%04x, err=%s\n",
258 	    portno, sc->sc_st.port_status,
259 	    sc->sc_st.port_change, usb2_errstr(err));
260 	return (err);
261 }
262 
263 /*------------------------------------------------------------------------*
264  *	uhub_reattach_port
265  *
266  * Returns:
267  *    0: Success
268  * Else: A control transaction failed
269  *------------------------------------------------------------------------*/
270 static usb2_error_t
271 uhub_reattach_port(struct uhub_softc *sc, uint8_t portno)
272 {
273 	struct usb2_device *child;
274 	struct usb2_device *udev;
275 	usb2_error_t err;
276 	uint8_t timeout;
277 	uint8_t speed;
278 	uint8_t usb2_mode;
279 
280 	DPRINTF("reattaching port %d\n", portno);
281 
282 	err = 0;
283 	timeout = 0;
284 	udev = sc->sc_udev;
285 	child = usb2_bus_port_get_device(udev->bus,
286 	    udev->hub->ports + portno - 1);
287 
288 repeat:
289 
290 	/* first clear the port connection change bit */
291 
292 	err = usb2_req_clear_port_feature(udev, NULL,
293 	    portno, UHF_C_PORT_CONNECTION);
294 
295 	if (err) {
296 		goto error;
297 	}
298 	/* detach any existing devices */
299 
300 	if (child) {
301 		usb2_detach_device(child, USB_IFACE_INDEX_ANY, 1);
302 		usb2_free_device(child);
303 		child = NULL;
304 	}
305 	/* get fresh status */
306 
307 	err = uhub_read_port_status(sc, portno);
308 	if (err) {
309 		goto error;
310 	}
311 	/* check if nothing is connected to the port */
312 
313 	if (!(sc->sc_st.port_status & UPS_CURRENT_CONNECT_STATUS)) {
314 		goto error;
315 	}
316 	/* check if there is no power on the port and print a warning */
317 
318 	if (!(sc->sc_st.port_status & UPS_PORT_POWER)) {
319 		DPRINTF("WARNING: strange, connected port %d "
320 		    "has no power\n", portno);
321 	}
322 	/* check if the device is in Host Mode */
323 
324 	if (!(sc->sc_st.port_status & UPS_PORT_MODE_DEVICE)) {
325 
326 		DPRINTF("Port %d is in Host Mode\n", portno);
327 
328 		if (sc->sc_st.port_status & UPS_SUSPEND) {
329 			DPRINTF("Port %d was still "
330 			    "suspended, clearing.\n", portno);
331 			err = usb2_req_clear_port_feature(sc->sc_udev,
332 			    NULL, portno, UHF_PORT_SUSPEND);
333 		}
334 		/* USB Host Mode */
335 
336 		/* wait for maximum device power up time */
337 
338 		usb2_pause_mtx(NULL,
339 		    USB_MS_TO_TICKS(USB_PORT_POWERUP_DELAY));
340 
341 		/* reset port, which implies enabling it */
342 
343 		err = usb2_req_reset_port(udev, NULL, portno);
344 
345 		if (err) {
346 			DPRINTFN(0, "port %d reset "
347 			    "failed, error=%s\n",
348 			    portno, usb2_errstr(err));
349 			goto error;
350 		}
351 		/* get port status again, it might have changed during reset */
352 
353 		err = uhub_read_port_status(sc, portno);
354 		if (err) {
355 			goto error;
356 		}
357 		/* check if something changed during port reset */
358 
359 		if ((sc->sc_st.port_change & UPS_C_CONNECT_STATUS) ||
360 		    (!(sc->sc_st.port_status & UPS_CURRENT_CONNECT_STATUS))) {
361 			if (timeout) {
362 				DPRINTFN(0, "giving up port reset "
363 				    "- device vanished!\n");
364 				goto error;
365 			}
366 			timeout = 1;
367 			goto repeat;
368 		}
369 	} else {
370 		DPRINTF("Port %d is in Device Mode\n", portno);
371 	}
372 
373 	/*
374 	 * Figure out the device speed
375 	 */
376 	switch (udev->speed) {
377 	case USB_SPEED_HIGH:
378 		if (sc->sc_st.port_status & UPS_HIGH_SPEED)
379 			speed = USB_SPEED_HIGH;
380 		else if (sc->sc_st.port_status & UPS_LOW_SPEED)
381 			speed = USB_SPEED_LOW;
382 		else
383 			speed = USB_SPEED_FULL;
384 		break;
385 	case USB_SPEED_FULL:
386 		if (sc->sc_st.port_status & UPS_LOW_SPEED)
387 			speed = USB_SPEED_LOW;
388 		else
389 			speed = USB_SPEED_FULL;
390 		break;
391 	case USB_SPEED_LOW:
392 		speed = USB_SPEED_LOW;
393 		break;
394 	default:
395 		/* same speed like parent */
396 		speed = udev->speed;
397 		break;
398 	}
399 	/*
400 	 * Figure out the device mode
401 	 *
402 	 * NOTE: This part is currently FreeBSD specific.
403 	 */
404 	if (sc->sc_st.port_status & UPS_PORT_MODE_DEVICE)
405 		usb2_mode = USB_MODE_DEVICE;
406 	else
407 		usb2_mode = USB_MODE_HOST;
408 
409 	/* need to create a new child */
410 
411 	child = usb2_alloc_device(sc->sc_dev, udev->bus, udev,
412 	    udev->depth + 1, portno - 1, portno, speed, usb2_mode);
413 	if (child == NULL) {
414 		DPRINTFN(0, "could not allocate new device!\n");
415 		goto error;
416 	}
417 	return (0);			/* success */
418 
419 error:
420 	if (child) {
421 		usb2_detach_device(child, USB_IFACE_INDEX_ANY, 1);
422 		usb2_free_device(child);
423 		child = NULL;
424 	}
425 	if (err == 0) {
426 		if (sc->sc_st.port_status & UPS_PORT_ENABLED) {
427 			err = usb2_req_clear_port_feature(
428 			    sc->sc_udev, NULL,
429 			    portno, UHF_PORT_ENABLE);
430 		}
431 	}
432 	if (err) {
433 		DPRINTFN(0, "device problem (%s), "
434 		    "disabling port %d\n", usb2_errstr(err), portno);
435 	}
436 	return (err);
437 }
438 
439 /*------------------------------------------------------------------------*
440  *	uhub_suspend_resume_port
441  *
442  * Returns:
443  *    0: Success
444  * Else: A control transaction failed
445  *------------------------------------------------------------------------*/
446 static usb2_error_t
447 uhub_suspend_resume_port(struct uhub_softc *sc, uint8_t portno)
448 {
449 	struct usb2_device *child;
450 	struct usb2_device *udev;
451 	uint8_t is_suspend;
452 	usb2_error_t err;
453 
454 	DPRINTF("port %d\n", portno);
455 
456 	udev = sc->sc_udev;
457 	child = usb2_bus_port_get_device(udev->bus,
458 	    udev->hub->ports + portno - 1);
459 
460 	/* first clear the port suspend change bit */
461 
462 	err = usb2_req_clear_port_feature(udev, NULL,
463 	    portno, UHF_C_PORT_SUSPEND);
464 	if (err) {
465 		DPRINTF("clearing suspend failed.\n");
466 		goto done;
467 	}
468 	/* get fresh status */
469 
470 	err = uhub_read_port_status(sc, portno);
471 	if (err) {
472 		DPRINTF("reading port status failed.\n");
473 		goto done;
474 	}
475 	/* get current state */
476 
477 	if (sc->sc_st.port_status & UPS_SUSPEND) {
478 		is_suspend = 1;
479 	} else {
480 		is_suspend = 0;
481 	}
482 
483 	DPRINTF("suspended=%u\n", is_suspend);
484 
485 	/* do the suspend or resume */
486 
487 	if (child) {
488 		/*
489 		 * This code handle two cases: 1) Host Mode - we can only
490 		 * receive resume here 2) Device Mode - we can receive
491 		 * suspend and resume here
492 		 */
493 		if (is_suspend == 0)
494 			usb2_dev_resume_peer(child);
495 		else if (child->flags.usb2_mode == USB_MODE_DEVICE)
496 			usb2_dev_suspend_peer(child);
497 	}
498 done:
499 	return (err);
500 }
501 
502 /*------------------------------------------------------------------------*
503  *	uhub_explore
504  *
505  * Returns:
506  *     0: Success
507  *  Else: Failure
508  *------------------------------------------------------------------------*/
509 static usb2_error_t
510 uhub_explore(struct usb2_device *udev)
511 {
512 	struct usb2_hub *hub;
513 	struct uhub_softc *sc;
514 	struct usb2_port *up;
515 	usb2_error_t err;
516 	uint8_t portno;
517 	uint8_t x;
518 
519 	hub = udev->hub;
520 	sc = hub->hubsoftc;
521 
522 	DPRINTFN(11, "udev=%p addr=%d\n", udev, udev->address);
523 
524 	/* ignore hubs that are too deep */
525 	if (udev->depth > USB_HUB_MAX_DEPTH) {
526 		return (USB_ERR_TOO_DEEP);
527 	}
528 	if (udev->pwr_save.suspended) {
529 		/* need to wait until the child signals resume */
530 		DPRINTF("Device is suspended!\n");
531 		return (0);
532 	}
533 	for (x = 0; x != hub->nports; x++) {
534 		up = hub->ports + x;
535 		portno = x + 1;
536 
537 		err = uhub_read_port_status(sc, portno);
538 		if (err) {
539 			/* most likely the HUB is gone */
540 			break;
541 		}
542 		if (sc->sc_st.port_change & UPS_C_OVERCURRENT_INDICATOR) {
543 			DPRINTF("Overcurrent on port %u.\n", portno);
544 			err = usb2_req_clear_port_feature(
545 			    udev, NULL, portno, UHF_C_PORT_OVER_CURRENT);
546 			if (err) {
547 				/* most likely the HUB is gone */
548 				break;
549 			}
550 		}
551 		if (!(sc->sc_flags & UHUB_FLAG_DID_EXPLORE)) {
552 			/*
553 			 * Fake a connect status change so that the
554 			 * status gets checked initially!
555 			 */
556 			sc->sc_st.port_change |=
557 			    UPS_C_CONNECT_STATUS;
558 		}
559 		if (sc->sc_st.port_change & UPS_C_PORT_ENABLED) {
560 			err = usb2_req_clear_port_feature(
561 			    udev, NULL, portno, UHF_C_PORT_ENABLE);
562 			if (err) {
563 				/* most likely the HUB is gone */
564 				break;
565 			}
566 			if (sc->sc_st.port_change & UPS_C_CONNECT_STATUS) {
567 				/*
568 				 * Ignore the port error if the device
569 				 * has vanished !
570 				 */
571 			} else if (sc->sc_st.port_status & UPS_PORT_ENABLED) {
572 				DPRINTFN(0, "illegal enable change, "
573 				    "port %d\n", portno);
574 			} else {
575 
576 				if (up->restartcnt == USB_RESTART_MAX) {
577 					/* XXX could try another speed ? */
578 					DPRINTFN(0, "port error, giving up "
579 					    "port %d\n", portno);
580 				} else {
581 					sc->sc_st.port_change |=
582 					    UPS_C_CONNECT_STATUS;
583 					up->restartcnt++;
584 				}
585 			}
586 		}
587 		if (sc->sc_st.port_change & UPS_C_CONNECT_STATUS) {
588 			err = uhub_reattach_port(sc, portno);
589 			if (err) {
590 				/* most likely the HUB is gone */
591 				break;
592 			}
593 		}
594 		if (sc->sc_st.port_change & UPS_C_SUSPEND) {
595 			err = uhub_suspend_resume_port(sc, portno);
596 			if (err) {
597 				/* most likely the HUB is gone */
598 				break;
599 			}
600 		}
601 		err = uhub_explore_sub(sc, up);
602 		if (err) {
603 			/* no device(s) present */
604 			continue;
605 		}
606 		/* explore succeeded - reset restart counter */
607 		up->restartcnt = 0;
608 	}
609 
610 	/* initial status checked */
611 	sc->sc_flags |= UHUB_FLAG_DID_EXPLORE;
612 
613 	/* return success */
614 	return (USB_ERR_NORMAL_COMPLETION);
615 }
616 
617 static int
618 uhub_probe(device_t dev)
619 {
620 	struct usb2_attach_arg *uaa = device_get_ivars(dev);
621 
622 	if (uaa->usb2_mode != USB_MODE_HOST) {
623 		return (ENXIO);
624 	}
625 	/*
626 	 * The subclass for USB HUBs is ignored because it is 0 for
627 	 * some and 1 for others.
628 	 */
629 	if ((uaa->info.bConfigIndex == 0) &&
630 	    (uaa->info.bDeviceClass == UDCLASS_HUB)) {
631 		return (0);
632 	}
633 	return (ENXIO);
634 }
635 
636 static int
637 uhub_attach(device_t dev)
638 {
639 	struct uhub_softc *sc = device_get_softc(dev);
640 	struct usb2_attach_arg *uaa = device_get_ivars(dev);
641 	struct usb2_device *udev = uaa->device;
642 	struct usb2_device *parent_hub = udev->parent_hub;
643 	struct usb2_hub *hub;
644 	struct usb2_hub_descriptor hubdesc;
645 	uint16_t pwrdly;
646 	uint8_t x;
647 	uint8_t nports;
648 	uint8_t portno;
649 	uint8_t removable;
650 	uint8_t iface_index;
651 	usb2_error_t err;
652 
653 	sc->sc_udev = udev;
654 	sc->sc_dev = dev;
655 
656 	snprintf(sc->sc_name, sizeof(sc->sc_name), "%s",
657 	    device_get_nameunit(dev));
658 
659 	device_set_usb2_desc(dev);
660 
661 	DPRINTFN(2, "depth=%d selfpowered=%d, parent=%p, "
662 	    "parent->selfpowered=%d\n",
663 	    udev->depth,
664 	    udev->flags.self_powered,
665 	    parent_hub,
666 	    parent_hub ?
667 	    parent_hub->flags.self_powered : 0);
668 
669 	if (udev->depth > USB_HUB_MAX_DEPTH) {
670 		DPRINTFN(0, "hub depth, %d, exceeded. HUB ignored!\n",
671 		    USB_HUB_MAX_DEPTH);
672 		goto error;
673 	}
674 	if (!udev->flags.self_powered && parent_hub &&
675 	    (!parent_hub->flags.self_powered)) {
676 		DPRINTFN(0, "bus powered HUB connected to "
677 		    "bus powered HUB. HUB ignored!\n");
678 		goto error;
679 	}
680 	/* get HUB descriptor */
681 
682 	DPRINTFN(2, "getting HUB descriptor\n");
683 
684 	/* assuming that there is one port */
685 	err = usb2_req_get_hub_descriptor(udev, NULL, &hubdesc, 1);
686 
687 	nports = hubdesc.bNbrPorts;
688 
689 	if (!err && (nports >= 8)) {
690 		/* get complete HUB descriptor */
691 		err = usb2_req_get_hub_descriptor(udev, NULL, &hubdesc, nports);
692 	}
693 	if (err) {
694 		DPRINTFN(0, "getting hub descriptor failed,"
695 		    "error=%s\n", usb2_errstr(err));
696 		goto error;
697 	}
698 	if (hubdesc.bNbrPorts != nports) {
699 		DPRINTFN(0, "number of ports changed!\n");
700 		goto error;
701 	}
702 	if (nports == 0) {
703 		DPRINTFN(0, "portless HUB!\n");
704 		goto error;
705 	}
706 	hub = malloc(sizeof(hub[0]) + (sizeof(hub->ports[0]) * nports),
707 	    M_USBDEV, M_WAITOK | M_ZERO);
708 
709 	if (hub == NULL) {
710 		goto error;
711 	}
712 	udev->hub = hub;
713 
714 	/* init FULL-speed ISOCHRONOUS schedule */
715 	usb2_fs_isoc_schedule_init_all(hub->fs_isoc_schedule);
716 
717 	/* initialize HUB structure */
718 	hub->hubsoftc = sc;
719 	hub->explore = &uhub_explore;
720 	hub->nports = hubdesc.bNbrPorts;
721 	hub->hubudev = udev;
722 
723 	/* if self powered hub, give ports maximum current */
724 	if (udev->flags.self_powered) {
725 		hub->portpower = USB_MAX_POWER;
726 	} else {
727 		hub->portpower = USB_MIN_POWER;
728 	}
729 
730 	/* set up interrupt pipe */
731 	iface_index = 0;
732 	err = usb2_transfer_setup(udev, &iface_index, sc->sc_xfer,
733 	    uhub_config, UHUB_N_TRANSFER, sc, &Giant);
734 	if (err) {
735 		DPRINTFN(0, "cannot setup interrupt transfer, "
736 		    "errstr=%s!\n", usb2_errstr(err));
737 		goto error;
738 	}
739 	/* wait with power off for a while */
740 	usb2_pause_mtx(NULL, USB_MS_TO_TICKS(USB_POWER_DOWN_TIME));
741 
742 	/*
743 	 * To have the best chance of success we do things in the exact same
744 	 * order as Windoze98.  This should not be necessary, but some
745 	 * devices do not follow the USB specs to the letter.
746 	 *
747 	 * These are the events on the bus when a hub is attached:
748 	 *  Get device and config descriptors (see attach code)
749 	 *  Get hub descriptor (see above)
750 	 *  For all ports
751 	 *     turn on power
752 	 *     wait for power to become stable
753 	 * (all below happens in explore code)
754 	 *  For all ports
755 	 *     clear C_PORT_CONNECTION
756 	 *  For all ports
757 	 *     get port status
758 	 *     if device connected
759 	 *        wait 100 ms
760 	 *        turn on reset
761 	 *        wait
762 	 *        clear C_PORT_RESET
763 	 *        get port status
764 	 *        proceed with device attachment
765 	 */
766 
767 	/* XXX should check for none, individual, or ganged power? */
768 
769 	removable = 0;
770 	pwrdly = ((hubdesc.bPwrOn2PwrGood * UHD_PWRON_FACTOR) +
771 	    USB_EXTRA_POWER_UP_TIME);
772 
773 	for (x = 0; x != nports; x++) {
774 		/* set up data structures */
775 		struct usb2_port *up = hub->ports + x;
776 
777 		up->device_index = 0;
778 		up->restartcnt = 0;
779 		portno = x + 1;
780 
781 		/* check if port is removable */
782 		if (!UHD_NOT_REMOV(&hubdesc, portno)) {
783 			removable++;
784 		}
785 		if (!err) {
786 			/* turn the power on */
787 			err = usb2_req_set_port_feature(udev, NULL,
788 			    portno, UHF_PORT_POWER);
789 		}
790 		if (err) {
791 			DPRINTFN(0, "port %d power on failed, %s\n",
792 			    portno, usb2_errstr(err));
793 		}
794 		DPRINTF("turn on port %d power\n",
795 		    portno);
796 
797 		/* wait for stable power */
798 		usb2_pause_mtx(NULL, USB_MS_TO_TICKS(pwrdly));
799 	}
800 
801 	device_printf(dev, "%d port%s with %d "
802 	    "removable, %s powered\n", nports, (nports != 1) ? "s" : "",
803 	    removable, udev->flags.self_powered ? "self" : "bus");
804 
805 	/* start the interrupt endpoint */
806 
807 	USB_XFER_LOCK(sc->sc_xfer[0]);
808 	usb2_transfer_start(sc->sc_xfer[0]);
809 	USB_XFER_UNLOCK(sc->sc_xfer[0]);
810 
811 	/* Enable automatic power save on all USB HUBs */
812 
813 	usb2_set_power_mode(udev, USB_POWER_MODE_SAVE);
814 
815 	return (0);
816 
817 error:
818 	usb2_transfer_unsetup(sc->sc_xfer, UHUB_N_TRANSFER);
819 
820 	if (udev->hub) {
821 		free(udev->hub, M_USBDEV);
822 		udev->hub = NULL;
823 	}
824 	return (ENXIO);
825 }
826 
827 /*
828  * Called from process context when the hub is gone.
829  * Detach all devices on active ports.
830  */
831 static int
832 uhub_detach(device_t dev)
833 {
834 	struct uhub_softc *sc = device_get_softc(dev);
835 	struct usb2_hub *hub = sc->sc_udev->hub;
836 	struct usb2_device *child;
837 	uint8_t x;
838 
839 	/* detach all children first */
840 	bus_generic_detach(dev);
841 
842 	if (hub == NULL) {		/* must be partially working */
843 		return (0);
844 	}
845 	for (x = 0; x != hub->nports; x++) {
846 
847 		child = usb2_bus_port_get_device(sc->sc_udev->bus, hub->ports + x);
848 
849 		if (child == NULL) {
850 			continue;
851 		}
852 		/*
853 		 * Subdevices are not freed, because the caller of
854 		 * uhub_detach() will do that.
855 		 */
856 		usb2_detach_device(child, USB_IFACE_INDEX_ANY, 0);
857 		usb2_free_device(child);
858 		child = NULL;
859 	}
860 
861 	usb2_transfer_unsetup(sc->sc_xfer, UHUB_N_TRANSFER);
862 
863 	free(hub, M_USBDEV);
864 	sc->sc_udev->hub = NULL;
865 	return (0);
866 }
867 
868 static int
869 uhub_suspend(device_t dev)
870 {
871 	DPRINTF("\n");
872 	/* Sub-devices are not suspended here! */
873 	return (0);
874 }
875 
876 static int
877 uhub_resume(device_t dev)
878 {
879 	DPRINTF("\n");
880 	/* Sub-devices are not resumed here! */
881 	return (0);
882 }
883 
884 static void
885 uhub_driver_added(device_t dev, driver_t *driver)
886 {
887 	usb2_needs_explore_all();
888 }
889 
890 struct hub_result {
891 	struct usb2_device *udev;
892 	uint8_t	portno;
893 	uint8_t	iface_index;
894 };
895 
896 static void
897 uhub_find_iface_index(struct usb2_hub *hub, device_t child,
898     struct hub_result *res)
899 {
900 	struct usb2_interface *iface;
901 	struct usb2_device *udev;
902 	uint8_t nports;
903 	uint8_t x;
904 	uint8_t i;
905 
906 	nports = hub->nports;
907 	for (x = 0; x != nports; x++) {
908 		udev = usb2_bus_port_get_device(hub->hubudev->bus,
909 		    hub->ports + x);
910 		if (!udev) {
911 			continue;
912 		}
913 		for (i = 0; i != USB_IFACE_MAX; i++) {
914 			iface = usb2_get_iface(udev, i);
915 			if (iface &&
916 			    (iface->subdev == child)) {
917 				res->iface_index = i;
918 				res->udev = udev;
919 				res->portno = x + 1;
920 				return;
921 			}
922 		}
923 	}
924 	res->iface_index = 0;
925 	res->udev = NULL;
926 	res->portno = 0;
927 }
928 
929 static int
930 uhub_child_location_string(device_t parent, device_t child,
931     char *buf, size_t buflen)
932 {
933 	struct uhub_softc *sc = device_get_softc(parent);
934 	struct usb2_hub *hub = sc->sc_udev->hub;
935 	struct hub_result res;
936 
937 	mtx_lock(&Giant);
938 	uhub_find_iface_index(hub, child, &res);
939 	if (!res.udev) {
940 		DPRINTF("device not on hub\n");
941 		if (buflen) {
942 			buf[0] = '\0';
943 		}
944 		goto done;
945 	}
946 	snprintf(buf, buflen, "port=%u interface=%u",
947 	    res.portno, res.iface_index);
948 done:
949 	mtx_unlock(&Giant);
950 
951 	return (0);
952 }
953 
954 static int
955 uhub_child_pnpinfo_string(device_t parent, device_t child,
956     char *buf, size_t buflen)
957 {
958 	struct uhub_softc *sc = device_get_softc(parent);
959 	struct usb2_hub *hub = sc->sc_udev->hub;
960 	struct usb2_interface *iface;
961 	struct hub_result res;
962 
963 	mtx_lock(&Giant);
964 	uhub_find_iface_index(hub, child, &res);
965 	if (!res.udev) {
966 		DPRINTF("device not on hub\n");
967 		if (buflen) {
968 			buf[0] = '\0';
969 		}
970 		goto done;
971 	}
972 	iface = usb2_get_iface(res.udev, res.iface_index);
973 	if (iface && iface->idesc) {
974 		snprintf(buf, buflen, "vendor=0x%04x product=0x%04x "
975 		    "devclass=0x%02x devsubclass=0x%02x "
976 		    "sernum=\"%s\" "
977 		    "intclass=0x%02x intsubclass=0x%02x",
978 		    UGETW(res.udev->ddesc.idVendor),
979 		    UGETW(res.udev->ddesc.idProduct),
980 		    res.udev->ddesc.bDeviceClass,
981 		    res.udev->ddesc.bDeviceSubClass,
982 		    res.udev->serial,
983 		    iface->idesc->bInterfaceClass,
984 		    iface->idesc->bInterfaceSubClass);
985 	} else {
986 		if (buflen) {
987 			buf[0] = '\0';
988 		}
989 		goto done;
990 	}
991 done:
992 	mtx_unlock(&Giant);
993 
994 	return (0);
995 }
996 
997 /*
998  * The USB Transaction Translator:
999  * ===============================
1000  *
1001  * When doing LOW- and FULL-speed USB transfers accross a HIGH-speed
1002  * USB HUB, bandwidth must be allocated for ISOCHRONOUS and INTERRUPT
1003  * USB transfers. To utilize bandwidth dynamically the "scatter and
1004  * gather" principle must be applied. This means that bandwidth must
1005  * be divided into equal parts of bandwidth. With regard to USB all
1006  * data is transferred in smaller packets with length
1007  * "wMaxPacketSize". The problem however is that "wMaxPacketSize" is
1008  * not a constant!
1009  *
1010  * The bandwidth scheduler which I have implemented will simply pack
1011  * the USB transfers back to back until there is no more space in the
1012  * schedule. Out of the 8 microframes which the USB 2.0 standard
1013  * provides, only 6 are available for non-HIGH-speed devices. I have
1014  * reserved the first 4 microframes for ISOCHRONOUS transfers. The
1015  * last 2 microframes I have reserved for INTERRUPT transfers. Without
1016  * this division, it is very difficult to allocate and free bandwidth
1017  * dynamically.
1018  *
1019  * NOTE about the Transaction Translator in USB HUBs:
1020  *
1021  * USB HUBs have a very simple Transaction Translator, that will
1022  * simply pipeline all the SPLIT transactions. That means that the
1023  * transactions will be executed in the order they are queued!
1024  *
1025  */
1026 
1027 /*------------------------------------------------------------------------*
1028  *	usb2_intr_find_best_slot
1029  *
1030  * Return value:
1031  *   The best Transaction Translation slot for an interrupt endpoint.
1032  *------------------------------------------------------------------------*/
1033 static uint8_t
1034 usb2_intr_find_best_slot(uint32_t *ptr, uint8_t start, uint8_t end)
1035 {
1036 	uint32_t max = 0xffffffff;
1037 	uint8_t x;
1038 	uint8_t y;
1039 
1040 	y = 0;
1041 
1042 	/* find the last slot with lesser used bandwidth */
1043 
1044 	for (x = start; x < end; x++) {
1045 		if (max >= ptr[x]) {
1046 			max = ptr[x];
1047 			y = x;
1048 		}
1049 	}
1050 	return (y);
1051 }
1052 
1053 /*------------------------------------------------------------------------*
1054  *	usb2_intr_schedule_adjust
1055  *
1056  * This function will update the bandwith usage for the microframe
1057  * having index "slot" by "len" bytes. "len" can be negative.  If the
1058  * "slot" argument is greater or equal to "USB_HS_MICRO_FRAMES_MAX"
1059  * the "slot" argument will be replaced by the slot having least used
1060  * bandwidth.
1061  *
1062  * Returns:
1063  *   The slot on which the bandwidth update was done.
1064  *------------------------------------------------------------------------*/
1065 uint8_t
1066 usb2_intr_schedule_adjust(struct usb2_device *udev, int16_t len, uint8_t slot)
1067 {
1068 	struct usb2_bus *bus = udev->bus;
1069 	struct usb2_hub *hub;
1070 	uint8_t speed;
1071 
1072 	USB_BUS_LOCK_ASSERT(bus, MA_OWNED);
1073 
1074 	speed = usb2_get_speed(udev);
1075 
1076 	switch (speed) {
1077 	case USB_SPEED_LOW:
1078 	case USB_SPEED_FULL:
1079 		if (speed == USB_SPEED_LOW) {
1080 			len *= 8;
1081 		}
1082 		/*
1083 	         * The Host Controller Driver should have
1084 	         * performed checks so that the lookup
1085 	         * below does not result in a NULL pointer
1086 	         * access.
1087 	         */
1088 
1089 		hub = bus->devices[udev->hs_hub_addr]->hub;
1090 		if (slot >= USB_HS_MICRO_FRAMES_MAX) {
1091 			slot = usb2_intr_find_best_slot(hub->uframe_usage,
1092 			    USB_FS_ISOC_UFRAME_MAX, 6);
1093 		}
1094 		hub->uframe_usage[slot] += len;
1095 		bus->uframe_usage[slot] += len;
1096 		break;
1097 	default:
1098 		if (slot >= USB_HS_MICRO_FRAMES_MAX) {
1099 			slot = usb2_intr_find_best_slot(bus->uframe_usage, 0,
1100 			    USB_HS_MICRO_FRAMES_MAX);
1101 		}
1102 		bus->uframe_usage[slot] += len;
1103 		break;
1104 	}
1105 	return (slot);
1106 }
1107 
1108 /*------------------------------------------------------------------------*
1109  *	usb2_fs_isoc_schedule_init_sub
1110  *
1111  * This function initialises an USB FULL speed isochronous schedule
1112  * entry.
1113  *------------------------------------------------------------------------*/
1114 static void
1115 usb2_fs_isoc_schedule_init_sub(struct usb2_fs_isoc_schedule *fss)
1116 {
1117 	fss->total_bytes = (USB_FS_ISOC_UFRAME_MAX *
1118 	    USB_FS_BYTES_PER_HS_UFRAME);
1119 	fss->frame_bytes = (USB_FS_BYTES_PER_HS_UFRAME);
1120 	fss->frame_slot = 0;
1121 }
1122 
1123 /*------------------------------------------------------------------------*
1124  *	usb2_fs_isoc_schedule_init_all
1125  *
1126  * This function will reset the complete USB FULL speed isochronous
1127  * bandwidth schedule.
1128  *------------------------------------------------------------------------*/
1129 void
1130 usb2_fs_isoc_schedule_init_all(struct usb2_fs_isoc_schedule *fss)
1131 {
1132 	struct usb2_fs_isoc_schedule *fss_end = fss + USB_ISOC_TIME_MAX;
1133 
1134 	while (fss != fss_end) {
1135 		usb2_fs_isoc_schedule_init_sub(fss);
1136 		fss++;
1137 	}
1138 }
1139 
1140 /*------------------------------------------------------------------------*
1141  *	usb2_isoc_time_expand
1142  *
1143  * This function will expand the time counter from 7-bit to 16-bit.
1144  *
1145  * Returns:
1146  *   16-bit isochronous time counter.
1147  *------------------------------------------------------------------------*/
1148 uint16_t
1149 usb2_isoc_time_expand(struct usb2_bus *bus, uint16_t isoc_time_curr)
1150 {
1151 	uint16_t rem;
1152 
1153 	USB_BUS_LOCK_ASSERT(bus, MA_OWNED);
1154 
1155 	rem = bus->isoc_time_last & (USB_ISOC_TIME_MAX - 1);
1156 
1157 	isoc_time_curr &= (USB_ISOC_TIME_MAX - 1);
1158 
1159 	if (isoc_time_curr < rem) {
1160 		/* the time counter wrapped around */
1161 		bus->isoc_time_last += USB_ISOC_TIME_MAX;
1162 	}
1163 	/* update the remainder */
1164 
1165 	bus->isoc_time_last &= ~(USB_ISOC_TIME_MAX - 1);
1166 	bus->isoc_time_last |= isoc_time_curr;
1167 
1168 	return (bus->isoc_time_last);
1169 }
1170 
1171 /*------------------------------------------------------------------------*
1172  *	usb2_fs_isoc_schedule_isoc_time_expand
1173  *
1174  * This function does multiple things. First of all it will expand the
1175  * passed isochronous time, which is the return value. Then it will
1176  * store where the current FULL speed isochronous schedule is
1177  * positioned in time and where the end is. See "pp_start" and
1178  * "pp_end" arguments.
1179  *
1180  * Returns:
1181  *   Expanded version of "isoc_time".
1182  *
1183  * NOTE: This function depends on being called regularly with
1184  * intervals less than "USB_ISOC_TIME_MAX".
1185  *------------------------------------------------------------------------*/
1186 uint16_t
1187 usb2_fs_isoc_schedule_isoc_time_expand(struct usb2_device *udev,
1188     struct usb2_fs_isoc_schedule **pp_start,
1189     struct usb2_fs_isoc_schedule **pp_end,
1190     uint16_t isoc_time)
1191 {
1192 	struct usb2_fs_isoc_schedule *fss_end;
1193 	struct usb2_fs_isoc_schedule *fss_a;
1194 	struct usb2_fs_isoc_schedule *fss_b;
1195 	struct usb2_hub *hs_hub;
1196 
1197 	isoc_time = usb2_isoc_time_expand(udev->bus, isoc_time);
1198 
1199 	hs_hub = udev->bus->devices[udev->hs_hub_addr]->hub;
1200 
1201 	if (hs_hub != NULL) {
1202 
1203 		fss_a = hs_hub->fs_isoc_schedule +
1204 		    (hs_hub->isoc_last_time % USB_ISOC_TIME_MAX);
1205 
1206 		hs_hub->isoc_last_time = isoc_time;
1207 
1208 		fss_b = hs_hub->fs_isoc_schedule +
1209 		    (isoc_time % USB_ISOC_TIME_MAX);
1210 
1211 		fss_end = hs_hub->fs_isoc_schedule + USB_ISOC_TIME_MAX;
1212 
1213 		*pp_start = hs_hub->fs_isoc_schedule;
1214 		*pp_end = fss_end;
1215 
1216 		while (fss_a != fss_b) {
1217 			if (fss_a == fss_end) {
1218 				fss_a = hs_hub->fs_isoc_schedule;
1219 				continue;
1220 			}
1221 			usb2_fs_isoc_schedule_init_sub(fss_a);
1222 			fss_a++;
1223 		}
1224 
1225 	} else {
1226 
1227 		*pp_start = NULL;
1228 		*pp_end = NULL;
1229 	}
1230 	return (isoc_time);
1231 }
1232 
1233 /*------------------------------------------------------------------------*
1234  *	usb2_fs_isoc_schedule_alloc
1235  *
1236  * This function will allocate bandwidth for an isochronous FULL speed
1237  * transaction in the FULL speed schedule. The microframe slot where
1238  * the transaction should be started is stored in the byte pointed to
1239  * by "pstart". The "len" argument specifies the length of the
1240  * transaction in bytes.
1241  *
1242  * Returns:
1243  *    0: Success
1244  * Else: Error
1245  *------------------------------------------------------------------------*/
1246 uint8_t
1247 usb2_fs_isoc_schedule_alloc(struct usb2_fs_isoc_schedule *fss,
1248     uint8_t *pstart, uint16_t len)
1249 {
1250 	uint8_t slot = fss->frame_slot;
1251 
1252 	/* Compute overhead and bit-stuffing */
1253 
1254 	len += 8;
1255 
1256 	len *= 7;
1257 	len /= 6;
1258 
1259 	if (len > fss->total_bytes) {
1260 		*pstart = 0;		/* set some dummy value */
1261 		return (1);		/* error */
1262 	}
1263 	if (len > 0) {
1264 
1265 		fss->total_bytes -= len;
1266 
1267 		while (len >= fss->frame_bytes) {
1268 			len -= fss->frame_bytes;
1269 			fss->frame_bytes = USB_FS_BYTES_PER_HS_UFRAME;
1270 			fss->frame_slot++;
1271 		}
1272 
1273 		fss->frame_bytes -= len;
1274 	}
1275 	*pstart = slot;
1276 	return (0);			/* success */
1277 }
1278 
1279 /*------------------------------------------------------------------------*
1280  *	usb2_bus_port_get_device
1281  *
1282  * This function is NULL safe.
1283  *------------------------------------------------------------------------*/
1284 struct usb2_device *
1285 usb2_bus_port_get_device(struct usb2_bus *bus, struct usb2_port *up)
1286 {
1287 	if ((bus == NULL) || (up == NULL)) {
1288 		/* be NULL safe */
1289 		return (NULL);
1290 	}
1291 	if (up->device_index == 0) {
1292 		/* nothing to do */
1293 		return (NULL);
1294 	}
1295 	return (bus->devices[up->device_index]);
1296 }
1297 
1298 /*------------------------------------------------------------------------*
1299  *	usb2_bus_port_set_device
1300  *
1301  * This function is NULL safe.
1302  *------------------------------------------------------------------------*/
1303 void
1304 usb2_bus_port_set_device(struct usb2_bus *bus, struct usb2_port *up,
1305     struct usb2_device *udev, uint8_t device_index)
1306 {
1307 	if (bus == NULL) {
1308 		/* be NULL safe */
1309 		return;
1310 	}
1311 	/*
1312 	 * There is only one case where we don't
1313 	 * have an USB port, and that is the Root Hub!
1314          */
1315 	if (up) {
1316 		if (udev) {
1317 			up->device_index = device_index;
1318 		} else {
1319 			device_index = up->device_index;
1320 			up->device_index = 0;
1321 		}
1322 	}
1323 	/*
1324 	 * Make relationships to our new device
1325 	 */
1326 	if (device_index != 0) {
1327 		mtx_lock(&usb2_ref_lock);
1328 		bus->devices[device_index] = udev;
1329 		mtx_unlock(&usb2_ref_lock);
1330 	}
1331 	/*
1332 	 * Debug print
1333 	 */
1334 	DPRINTFN(2, "bus %p devices[%u] = %p\n", bus, device_index, udev);
1335 }
1336 
1337 /*------------------------------------------------------------------------*
1338  *	usb2_needs_explore
1339  *
1340  * This functions is called when the USB event thread needs to run.
1341  *------------------------------------------------------------------------*/
1342 void
1343 usb2_needs_explore(struct usb2_bus *bus, uint8_t do_probe)
1344 {
1345 	DPRINTF("\n");
1346 
1347 	if (bus == NULL) {
1348 		DPRINTF("No bus pointer!\n");
1349 		return;
1350 	}
1351 	USB_BUS_LOCK(bus);
1352 	if (do_probe) {
1353 		bus->do_probe = 1;
1354 	}
1355 	if (usb2_proc_msignal(&bus->explore_proc,
1356 	    &bus->explore_msg[0], &bus->explore_msg[1])) {
1357 		/* ignore */
1358 	}
1359 	USB_BUS_UNLOCK(bus);
1360 }
1361 
1362 /*------------------------------------------------------------------------*
1363  *	usb2_needs_explore_all
1364  *
1365  * This function is called whenever a new driver is loaded and will
1366  * cause that all USB busses are re-explored.
1367  *------------------------------------------------------------------------*/
1368 void
1369 usb2_needs_explore_all(void)
1370 {
1371 	struct usb2_bus *bus;
1372 	devclass_t dc;
1373 	device_t dev;
1374 	int max;
1375 
1376 	DPRINTFN(3, "\n");
1377 
1378 	dc = usb2_devclass_ptr;
1379 	if (dc == NULL) {
1380 		DPRINTFN(0, "no devclass\n");
1381 		return;
1382 	}
1383 	/*
1384 	 * Explore all USB busses in parallell.
1385 	 */
1386 	max = devclass_get_maxunit(dc);
1387 	while (max >= 0) {
1388 		dev = devclass_get_device(dc, max);
1389 		if (dev) {
1390 			bus = device_get_softc(dev);
1391 			if (bus) {
1392 				usb2_needs_explore(bus, 1);
1393 			}
1394 		}
1395 		max--;
1396 	}
1397 }
1398 
1399 /*------------------------------------------------------------------------*
1400  *	usb2_bus_power_update
1401  *
1402  * This function will ensure that all USB devices on the given bus are
1403  * properly suspended or resumed according to the device transfer
1404  * state.
1405  *------------------------------------------------------------------------*/
1406 void
1407 usb2_bus_power_update(struct usb2_bus *bus)
1408 {
1409 	usb2_needs_explore(bus, 0 /* no probe */ );
1410 }
1411 
1412 /*------------------------------------------------------------------------*
1413  *	usb2_transfer_power_ref
1414  *
1415  * This function will modify the power save reference counts and
1416  * wakeup the USB device associated with the given USB transfer, if
1417  * needed.
1418  *------------------------------------------------------------------------*/
1419 void
1420 usb2_transfer_power_ref(struct usb2_xfer *xfer, int val)
1421 {
1422 	static const uint32_t power_mask[4] = {
1423 		[UE_CONTROL] = USB_HW_POWER_CONTROL,
1424 		[UE_BULK] = USB_HW_POWER_BULK,
1425 		[UE_INTERRUPT] = USB_HW_POWER_INTERRUPT,
1426 		[UE_ISOCHRONOUS] = USB_HW_POWER_ISOC,
1427 	};
1428 	struct usb2_device *udev;
1429 	uint8_t needs_explore;
1430 	uint8_t needs_hw_power;
1431 	uint8_t xfer_type;
1432 
1433 	udev = xfer->xroot->udev;
1434 
1435 	if (udev->device_index == USB_ROOT_HUB_ADDR) {
1436 		/* no power save for root HUB */
1437 		return;
1438 	}
1439 	USB_BUS_LOCK(udev->bus);
1440 
1441 	xfer_type = xfer->pipe->edesc->bmAttributes & UE_XFERTYPE;
1442 
1443 	udev->pwr_save.last_xfer_time = ticks;
1444 	udev->pwr_save.type_refs[xfer_type] += val;
1445 
1446 	if (xfer->flags_int.control_xfr) {
1447 		udev->pwr_save.read_refs += val;
1448 		if (xfer->flags_int.usb2_mode == USB_MODE_HOST) {
1449 			/*
1450 			 * it is not allowed to suspend during a control
1451 			 * transfer
1452 			 */
1453 			udev->pwr_save.write_refs += val;
1454 		}
1455 	} else if (USB_GET_DATA_ISREAD(xfer)) {
1456 		udev->pwr_save.read_refs += val;
1457 	} else {
1458 		udev->pwr_save.write_refs += val;
1459 	}
1460 
1461 	if (udev->pwr_save.suspended)
1462 		needs_explore =
1463 		    (udev->pwr_save.write_refs != 0) ||
1464 		    ((udev->pwr_save.read_refs != 0) &&
1465 		    (usb2_peer_can_wakeup(udev) == 0));
1466 	else
1467 		needs_explore = 0;
1468 
1469 	if (!(udev->bus->hw_power_state & power_mask[xfer_type])) {
1470 		DPRINTF("Adding type %u to power state\n", xfer_type);
1471 		udev->bus->hw_power_state |= power_mask[xfer_type];
1472 		needs_hw_power = 1;
1473 	} else {
1474 		needs_hw_power = 0;
1475 	}
1476 
1477 	USB_BUS_UNLOCK(udev->bus);
1478 
1479 	if (needs_explore) {
1480 		DPRINTF("update\n");
1481 		usb2_bus_power_update(udev->bus);
1482 	} else if (needs_hw_power) {
1483 		DPRINTF("needs power\n");
1484 		if (udev->bus->methods->set_hw_power != NULL) {
1485 			(udev->bus->methods->set_hw_power) (udev->bus);
1486 		}
1487 	}
1488 	return;
1489 }
1490 
1491 /*------------------------------------------------------------------------*
1492  *	usb2_bus_powerd
1493  *
1494  * This function implements the USB power daemon and is called
1495  * regularly from the USB explore thread.
1496  *------------------------------------------------------------------------*/
1497 void
1498 usb2_bus_powerd(struct usb2_bus *bus)
1499 {
1500 	struct usb2_device *udev;
1501 	unsigned int temp;
1502 	unsigned int limit;
1503 	unsigned int mintime;
1504 	uint32_t type_refs[5];
1505 	uint8_t x;
1506 	uint8_t rem_wakeup;
1507 
1508 	limit = usb2_power_timeout;
1509 	if (limit == 0)
1510 		limit = hz;
1511 	else if (limit > 255)
1512 		limit = 255 * hz;
1513 	else
1514 		limit = limit * hz;
1515 
1516 	DPRINTF("bus=%p\n", bus);
1517 
1518 	USB_BUS_LOCK(bus);
1519 
1520 	/*
1521 	 * The root HUB device is never suspended
1522 	 * and we simply skip it.
1523 	 */
1524 	for (x = USB_ROOT_HUB_ADDR + 1;
1525 	    x != bus->devices_max; x++) {
1526 
1527 		udev = bus->devices[x];
1528 		if (udev == NULL)
1529 			continue;
1530 
1531 		rem_wakeup = usb2_peer_can_wakeup(udev);
1532 
1533 		temp = ticks - udev->pwr_save.last_xfer_time;
1534 
1535 		if ((udev->power_mode == USB_POWER_MODE_ON) ||
1536 		    (udev->pwr_save.type_refs[UE_ISOCHRONOUS] != 0) ||
1537 		    (udev->pwr_save.write_refs != 0) ||
1538 		    ((udev->pwr_save.read_refs != 0) &&
1539 		    (rem_wakeup == 0))) {
1540 
1541 			/* check if we are suspended */
1542 			if (udev->pwr_save.suspended != 0) {
1543 				USB_BUS_UNLOCK(bus);
1544 				usb2_dev_resume_peer(udev);
1545 				USB_BUS_LOCK(bus);
1546 			}
1547 		} else if (temp >= limit) {
1548 
1549 			/* check if we are not suspended */
1550 			if (udev->pwr_save.suspended == 0) {
1551 				USB_BUS_UNLOCK(bus);
1552 				usb2_dev_suspend_peer(udev);
1553 				USB_BUS_LOCK(bus);
1554 			}
1555 		}
1556 	}
1557 
1558 	/* reset counters */
1559 
1560 	mintime = 0 - 1;
1561 	type_refs[0] = 0;
1562 	type_refs[1] = 0;
1563 	type_refs[2] = 0;
1564 	type_refs[3] = 0;
1565 	type_refs[4] = 0;
1566 
1567 	/* Re-loop all the devices to get the actual state */
1568 
1569 	for (x = USB_ROOT_HUB_ADDR + 1;
1570 	    x != bus->devices_max; x++) {
1571 
1572 		udev = bus->devices[x];
1573 		if (udev == NULL)
1574 			continue;
1575 
1576 		/* we found a non-Root-Hub USB device */
1577 		type_refs[4] += 1;
1578 
1579 		/* "last_xfer_time" can be updated by a resume */
1580 		temp = ticks - udev->pwr_save.last_xfer_time;
1581 
1582 		/*
1583 		 * Compute minimum time since last transfer for the complete
1584 		 * bus:
1585 		 */
1586 		if (temp < mintime)
1587 			mintime = temp;
1588 
1589 		if (udev->pwr_save.suspended == 0) {
1590 			type_refs[0] += udev->pwr_save.type_refs[0];
1591 			type_refs[1] += udev->pwr_save.type_refs[1];
1592 			type_refs[2] += udev->pwr_save.type_refs[2];
1593 			type_refs[3] += udev->pwr_save.type_refs[3];
1594 		}
1595 	}
1596 
1597 	if (mintime >= (1 * hz)) {
1598 		/* recompute power masks */
1599 		DPRINTF("Recomputing power masks\n");
1600 		bus->hw_power_state = 0;
1601 		if (type_refs[UE_CONTROL] != 0)
1602 			bus->hw_power_state |= USB_HW_POWER_CONTROL;
1603 		if (type_refs[UE_BULK] != 0)
1604 			bus->hw_power_state |= USB_HW_POWER_BULK;
1605 		if (type_refs[UE_INTERRUPT] != 0)
1606 			bus->hw_power_state |= USB_HW_POWER_INTERRUPT;
1607 		if (type_refs[UE_ISOCHRONOUS] != 0)
1608 			bus->hw_power_state |= USB_HW_POWER_ISOC;
1609 		if (type_refs[4] != 0)
1610 			bus->hw_power_state |= USB_HW_POWER_NON_ROOT_HUB;
1611 	}
1612 	USB_BUS_UNLOCK(bus);
1613 
1614 	if (bus->methods->set_hw_power != NULL) {
1615 		/* always update hardware power! */
1616 		(bus->methods->set_hw_power) (bus);
1617 	}
1618 	return;
1619 }
1620 
1621 /*------------------------------------------------------------------------*
1622  *	usb2_dev_resume_peer
1623  *
1624  * This function will resume an USB peer and do the required USB
1625  * signalling to get an USB device out of the suspended state.
1626  *------------------------------------------------------------------------*/
1627 static void
1628 usb2_dev_resume_peer(struct usb2_device *udev)
1629 {
1630 	struct usb2_bus *bus;
1631 	int err;
1632 
1633 	/* be NULL safe */
1634 	if (udev == NULL)
1635 		return;
1636 
1637 	/* check if already resumed */
1638 	if (udev->pwr_save.suspended == 0)
1639 		return;
1640 
1641 	/* we need a parent HUB to do resume */
1642 	if (udev->parent_hub == NULL)
1643 		return;
1644 
1645 	DPRINTF("udev=%p\n", udev);
1646 
1647 	if ((udev->flags.usb2_mode == USB_MODE_DEVICE) &&
1648 	    (udev->flags.remote_wakeup == 0)) {
1649 		/*
1650 		 * If the host did not set the remote wakeup feature, we can
1651 		 * not wake it up either!
1652 		 */
1653 		DPRINTF("remote wakeup is not set!\n");
1654 		return;
1655 	}
1656 	/* get bus pointer */
1657 	bus = udev->bus;
1658 
1659 	/* resume parent hub first */
1660 	usb2_dev_resume_peer(udev->parent_hub);
1661 
1662 	/* resume current port (Valid in Host and Device Mode) */
1663 	err = usb2_req_clear_port_feature(udev->parent_hub,
1664 	    NULL, udev->port_no, UHF_PORT_SUSPEND);
1665 	if (err) {
1666 		DPRINTFN(0, "Resuming port failed!\n");
1667 		return;
1668 	}
1669 	/* resume settle time */
1670 	usb2_pause_mtx(NULL, USB_MS_TO_TICKS(USB_PORT_RESUME_DELAY));
1671 
1672 	if (bus->methods->device_resume != NULL) {
1673 		/* resume USB device on the USB controller */
1674 		(bus->methods->device_resume) (udev);
1675 	}
1676 	USB_BUS_LOCK(bus);
1677 	/* set that this device is now resumed */
1678 	udev->pwr_save.suspended = 0;
1679 	/* make sure that we don't go into suspend right away */
1680 	udev->pwr_save.last_xfer_time = ticks;
1681 
1682 	/* make sure the needed power masks are on */
1683 	if (udev->pwr_save.type_refs[UE_CONTROL] != 0)
1684 		bus->hw_power_state |= USB_HW_POWER_CONTROL;
1685 	if (udev->pwr_save.type_refs[UE_BULK] != 0)
1686 		bus->hw_power_state |= USB_HW_POWER_BULK;
1687 	if (udev->pwr_save.type_refs[UE_INTERRUPT] != 0)
1688 		bus->hw_power_state |= USB_HW_POWER_INTERRUPT;
1689 	if (udev->pwr_save.type_refs[UE_ISOCHRONOUS] != 0)
1690 		bus->hw_power_state |= USB_HW_POWER_ISOC;
1691 	USB_BUS_UNLOCK(bus);
1692 
1693 	if (bus->methods->set_hw_power != NULL) {
1694 		/* always update hardware power! */
1695 		(bus->methods->set_hw_power) (bus);
1696 	}
1697 	sx_xlock(udev->default_sx + 1);
1698 	/* notify all sub-devices about resume */
1699 	err = usb2_suspend_resume(udev, 0);
1700 	sx_unlock(udev->default_sx + 1);
1701 
1702 	/* check if peer has wakeup capability */
1703 	if (usb2_peer_can_wakeup(udev)) {
1704 		/* clear remote wakeup */
1705 		err = usb2_req_clear_device_feature(udev,
1706 		    NULL, UF_DEVICE_REMOTE_WAKEUP);
1707 		if (err) {
1708 			DPRINTFN(0, "Clearing device "
1709 			    "remote wakeup failed: %s!\n",
1710 			    usb2_errstr(err));
1711 		}
1712 	}
1713 	return;
1714 }
1715 
1716 /*------------------------------------------------------------------------*
1717  *	usb2_dev_suspend_peer
1718  *
1719  * This function will suspend an USB peer and do the required USB
1720  * signalling to get an USB device into the suspended state.
1721  *------------------------------------------------------------------------*/
1722 static void
1723 usb2_dev_suspend_peer(struct usb2_device *udev)
1724 {
1725 	struct usb2_device *hub;
1726 	struct usb2_device *child;
1727 	uint32_t temp;
1728 	int err;
1729 	uint8_t x;
1730 	uint8_t nports;
1731 	uint8_t suspend_parent;
1732 
1733 repeat:
1734 	/* be NULL safe */
1735 	if (udev == NULL)
1736 		return;
1737 
1738 	/* check if already suspended */
1739 	if (udev->pwr_save.suspended)
1740 		return;
1741 
1742 	/* we need a parent HUB to do suspend */
1743 	if (udev->parent_hub == NULL)
1744 		return;
1745 
1746 	DPRINTF("udev=%p\n", udev);
1747 
1748 	/* check if all devices on the parent hub are suspended */
1749 	hub = udev->parent_hub;
1750 	if (hub != NULL) {
1751 		nports = hub->hub->nports;
1752 		suspend_parent = 1;
1753 
1754 		for (x = 0; x != nports; x++) {
1755 
1756 			child = usb2_bus_port_get_device(hub->bus,
1757 			    hub->hub->ports + x);
1758 
1759 			if (child == NULL)
1760 				continue;
1761 
1762 			if (child->pwr_save.suspended)
1763 				continue;
1764 
1765 			if (child == udev)
1766 				continue;
1767 
1768 			/* another device on the HUB is not suspended */
1769 			suspend_parent = 0;
1770 
1771 			break;
1772 		}
1773 	} else {
1774 		suspend_parent = 0;
1775 	}
1776 
1777 	sx_xlock(udev->default_sx + 1);
1778 	/* notify all sub-devices about suspend */
1779 	err = usb2_suspend_resume(udev, 1);
1780 	sx_unlock(udev->default_sx + 1);
1781 
1782 	if (usb2_peer_can_wakeup(udev)) {
1783 		/* allow device to do remote wakeup */
1784 		err = usb2_req_set_device_feature(udev,
1785 		    NULL, UF_DEVICE_REMOTE_WAKEUP);
1786 		if (err) {
1787 			DPRINTFN(0, "Setting device "
1788 			    "remote wakeup failed!\n");
1789 		}
1790 	}
1791 	USB_BUS_LOCK(udev->bus);
1792 	/*
1793 	 * Set that this device is suspended. This variable must be set
1794 	 * before calling USB controller suspend callbacks.
1795 	 */
1796 	udev->pwr_save.suspended = 1;
1797 	USB_BUS_UNLOCK(udev->bus);
1798 
1799 	if (udev->bus->methods->device_suspend != NULL) {
1800 
1801 		/* suspend device on the USB controller */
1802 		(udev->bus->methods->device_suspend) (udev);
1803 
1804 		/* do DMA delay */
1805 		temp = usb2_get_dma_delay(udev->bus);
1806 		usb2_pause_mtx(NULL, USB_MS_TO_TICKS(temp));
1807 
1808 	}
1809 	/* suspend current port */
1810 	err = usb2_req_set_port_feature(udev->parent_hub,
1811 	    NULL, udev->port_no, UHF_PORT_SUSPEND);
1812 	if (err) {
1813 		DPRINTFN(0, "Suspending port failed\n");
1814 		return;
1815 	}
1816 	if (suspend_parent) {
1817 		udev = udev->parent_hub;
1818 		goto repeat;
1819 	}
1820 	return;
1821 }
1822 
1823 /*------------------------------------------------------------------------*
1824  *	usb2_set_power_mode
1825  *
1826  * This function will set the power mode, see USB_POWER_MODE_XXX for a
1827  * USB device.
1828  *------------------------------------------------------------------------*/
1829 void
1830 usb2_set_power_mode(struct usb2_device *udev, uint8_t power_mode)
1831 {
1832 	/* filter input argument */
1833 	if ((power_mode != USB_POWER_MODE_ON) &&
1834 	    (power_mode != USB_POWER_MODE_OFF)) {
1835 		power_mode = USB_POWER_MODE_SAVE;
1836 	}
1837 	udev->power_mode = power_mode;	/* update copy of power mode */
1838 
1839 	usb2_bus_power_update(udev->bus);
1840 
1841 	return;
1842 }
1843