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