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