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