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