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