xref: /freebsd/sys/dev/usb/usb_hub.c (revision 9e5787d2284e187abb5b654d924394a65772e004)
1 /* $FreeBSD$ */
2 /*-
3  * SPDX-License-Identifier: BSD-2-Clause-NetBSD
4  *
5  * Copyright (c) 1998 The NetBSD Foundation, Inc. All rights reserved.
6  * Copyright (c) 1998 Lennart Augustsson. All rights reserved.
7  * Copyright (c) 2008-2010 Hans Petter Selasky. All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 
31 /*
32  * USB spec: http://www.usb.org/developers/docs/usbspec.zip
33  */
34 
35 #ifdef USB_GLOBAL_INCLUDE_FILE
36 #include USB_GLOBAL_INCLUDE_FILE
37 #else
38 #include <sys/stdint.h>
39 #include <sys/stddef.h>
40 #include <sys/param.h>
41 #include <sys/queue.h>
42 #include <sys/types.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
45 #include <sys/bus.h>
46 #include <sys/module.h>
47 #include <sys/lock.h>
48 #include <sys/mutex.h>
49 #include <sys/condvar.h>
50 #include <sys/sysctl.h>
51 #include <sys/sx.h>
52 #include <sys/unistd.h>
53 #include <sys/callout.h>
54 #include <sys/malloc.h>
55 #include <sys/priv.h>
56 
57 #include <dev/usb/usb.h>
58 #include <dev/usb/usbdi.h>
59 #include <dev/usb/usbdi_util.h>
60 
61 #define	USB_DEBUG_VAR uhub_debug
62 
63 #include <dev/usb/usb_core.h>
64 #include <dev/usb/usb_process.h>
65 #include <dev/usb/usb_device.h>
66 #include <dev/usb/usb_request.h>
67 #include <dev/usb/usb_debug.h>
68 #include <dev/usb/usb_hub.h>
69 #include <dev/usb/usb_util.h>
70 #include <dev/usb/usb_busdma.h>
71 #include <dev/usb/usb_transfer.h>
72 #include <dev/usb/usb_dynamic.h>
73 
74 #include <dev/usb/usb_controller.h>
75 #include <dev/usb/usb_bus.h>
76 #endif			/* USB_GLOBAL_INCLUDE_FILE */
77 
78 
79 #include <dev/usb/usb_hub_private.h>
80 
81 
82 #ifdef USB_DEBUG
83 static int uhub_debug = 0;
84 
85 static SYSCTL_NODE(_hw_usb, OID_AUTO, uhub, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
86     "USB HUB");
87 SYSCTL_INT(_hw_usb_uhub, OID_AUTO, debug, CTLFLAG_RWTUN, &uhub_debug, 0,
88     "Debug level");
89 #endif
90 
91 #if USB_HAVE_POWERD
92 static int usb_power_timeout = 30;	/* seconds */
93 
94 SYSCTL_INT(_hw_usb, OID_AUTO, power_timeout, CTLFLAG_RWTUN,
95     &usb_power_timeout, 0, "USB power timeout");
96 #endif
97 
98 #if USB_HAVE_DISABLE_ENUM
99 static int usb_disable_enumeration = 0;
100 SYSCTL_INT(_hw_usb, OID_AUTO, disable_enumeration, CTLFLAG_RWTUN,
101     &usb_disable_enumeration, 0, "Set to disable all USB device enumeration. "
102 	"This can secure against USB devices turning evil, "
103 	"for example a USB memory stick becoming a USB keyboard.");
104 
105 static int usb_disable_port_power = 0;
106 SYSCTL_INT(_hw_usb, OID_AUTO, disable_port_power, CTLFLAG_RWTUN,
107     &usb_disable_port_power, 0, "Set to disable all USB port power.");
108 #endif
109 
110 
111 #define	UHUB_PROTO(sc) ((sc)->sc_udev->ddesc.bDeviceProtocol)
112 #define	UHUB_IS_HIGH_SPEED(sc) (UHUB_PROTO(sc) != UDPROTO_FSHUB)
113 #define	UHUB_IS_SINGLE_TT(sc) (UHUB_PROTO(sc) == UDPROTO_HSHUBSTT)
114 #define	UHUB_IS_MULTI_TT(sc) (UHUB_PROTO(sc) == UDPROTO_HSHUBMTT)
115 #define	UHUB_IS_SUPER_SPEED(sc) (UHUB_PROTO(sc) == UDPROTO_SSHUB)
116 
117 /* prototypes for type checking: */
118 
119 static device_suspend_t uhub_suspend;
120 static device_resume_t uhub_resume;
121 
122 static bus_driver_added_t uhub_driver_added;
123 static bus_child_pnpinfo_str_t uhub_child_pnpinfo_string;
124 
125 static usb_callback_t uhub_intr_callback;
126 #if USB_HAVE_TT_SUPPORT
127 static usb_callback_t uhub_reset_tt_callback;
128 #endif
129 
130 static void usb_dev_resume_peer(struct usb_device *udev);
131 static void usb_dev_suspend_peer(struct usb_device *udev);
132 static uint8_t usb_peer_should_wakeup(struct usb_device *udev);
133 
134 static const struct usb_config uhub_config[UHUB_N_TRANSFER] = {
135 
136 	[UHUB_INTR_TRANSFER] = {
137 		.type = UE_INTERRUPT,
138 		.endpoint = UE_ADDR_ANY,
139 		.direction = UE_DIR_ANY,
140 		.timeout = 0,
141 		.flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
142 		.bufsize = 0,	/* use wMaxPacketSize */
143 		.callback = &uhub_intr_callback,
144 		.interval = UHUB_INTR_INTERVAL,
145 	},
146 #if USB_HAVE_TT_SUPPORT
147 	[UHUB_RESET_TT_TRANSFER] = {
148 		.type = UE_CONTROL,
149 		.endpoint = 0x00,	/* Control pipe */
150 		.direction = UE_DIR_ANY,
151 		.bufsize = sizeof(struct usb_device_request),
152 		.callback = &uhub_reset_tt_callback,
153 		.timeout = 1000,	/* 1 second */
154 		.usb_mode = USB_MODE_HOST,
155 	},
156 #endif
157 };
158 
159 /*
160  * driver instance for "hub" connected to "usb"
161  * and "hub" connected to "hub"
162  */
163 static devclass_t uhub_devclass;
164 
165 static device_method_t uhub_methods[] = {
166 	DEVMETHOD(device_probe, uhub_probe),
167 	DEVMETHOD(device_attach, uhub_attach),
168 	DEVMETHOD(device_detach, uhub_detach),
169 
170 	DEVMETHOD(device_suspend, uhub_suspend),
171 	DEVMETHOD(device_resume, uhub_resume),
172 
173 	DEVMETHOD(bus_child_location_str, uhub_child_location_string),
174 	DEVMETHOD(bus_child_pnpinfo_str, uhub_child_pnpinfo_string),
175 	DEVMETHOD(bus_driver_added, uhub_driver_added),
176 	DEVMETHOD_END
177 };
178 
179 driver_t uhub_driver = {
180 	.name = "uhub",
181 	.methods = uhub_methods,
182 	.size = sizeof(struct uhub_softc)
183 };
184 
185 DRIVER_MODULE(uhub, usbus, uhub_driver, uhub_devclass, 0, 0);
186 DRIVER_MODULE(uhub, uhub, uhub_driver, uhub_devclass, NULL, 0);
187 MODULE_VERSION(uhub, 1);
188 
189 static void
190 uhub_intr_callback(struct usb_xfer *xfer, usb_error_t error)
191 {
192 	struct uhub_softc *sc = usbd_xfer_softc(xfer);
193 
194 	switch (USB_GET_STATE(xfer)) {
195 	case USB_ST_TRANSFERRED:
196 		DPRINTFN(2, "\n");
197 		/*
198 		 * This is an indication that some port
199 		 * has changed status. Notify the bus
200 		 * event handler thread that we need
201 		 * to be explored again:
202 		 */
203 		usb_needs_explore(sc->sc_udev->bus, 0);
204 
205 	case USB_ST_SETUP:
206 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
207 		usbd_transfer_submit(xfer);
208 		break;
209 
210 	default:			/* Error */
211 		if (xfer->error != USB_ERR_CANCELLED) {
212 			/*
213 			 * Do a clear-stall. The "stall_pipe" flag
214 			 * will get cleared before next callback by
215 			 * the USB stack.
216 			 */
217 			usbd_xfer_set_stall(xfer);
218 			usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
219 			usbd_transfer_submit(xfer);
220 		}
221 		break;
222 	}
223 }
224 
225 /*------------------------------------------------------------------------*
226  *      uhub_reset_tt_proc
227  *
228  * This function starts the TT reset USB request
229  *------------------------------------------------------------------------*/
230 #if USB_HAVE_TT_SUPPORT
231 static void
232 uhub_reset_tt_proc(struct usb_proc_msg *_pm)
233 {
234 	struct usb_udev_msg *pm = (void *)_pm;
235 	struct usb_device *udev = pm->udev;
236 	struct usb_hub *hub;
237 	struct uhub_softc *sc;
238 
239 	hub = udev->hub;
240 	if (hub == NULL)
241 		return;
242 	sc = hub->hubsoftc;
243 	if (sc == NULL)
244 		return;
245 
246 	/* Change lock */
247 	USB_BUS_UNLOCK(udev->bus);
248 	USB_MTX_LOCK(&sc->sc_mtx);
249 	/* Start transfer */
250 	usbd_transfer_start(sc->sc_xfer[UHUB_RESET_TT_TRANSFER]);
251 	/* Change lock */
252 	USB_MTX_UNLOCK(&sc->sc_mtx);
253 	USB_BUS_LOCK(udev->bus);
254 }
255 #endif
256 
257 /*------------------------------------------------------------------------*
258  *      uhub_tt_buffer_reset_async_locked
259  *
260  * This function queues a TT reset for the given USB device and endpoint.
261  *------------------------------------------------------------------------*/
262 #if USB_HAVE_TT_SUPPORT
263 void
264 uhub_tt_buffer_reset_async_locked(struct usb_device *child, struct usb_endpoint *ep)
265 {
266 	struct usb_device_request req;
267 	struct usb_device *udev;
268 	struct usb_hub *hub;
269 	struct usb_port *up;
270 	uint16_t wValue;
271 	uint8_t port;
272 
273 	if (child == NULL || ep == NULL)
274 		return;
275 
276 	udev = child->parent_hs_hub;
277 	port = child->hs_port_no;
278 
279 	if (udev == NULL)
280 		return;
281 
282 	hub = udev->hub;
283 	if ((hub == NULL) ||
284 	    (udev->speed != USB_SPEED_HIGH) ||
285 	    (child->speed != USB_SPEED_LOW &&
286 	     child->speed != USB_SPEED_FULL) ||
287 	    (child->flags.usb_mode != USB_MODE_HOST) ||
288 	    (port == 0) || (ep->edesc == NULL)) {
289 		/* not applicable */
290 		return;
291 	}
292 
293 	USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED);
294 
295 	up = hub->ports + port - 1;
296 
297 	if (udev->ddesc.bDeviceClass == UDCLASS_HUB &&
298 	    udev->ddesc.bDeviceProtocol == UDPROTO_HSHUBSTT)
299 		port = 1;
300 
301 	/* if we already received a clear buffer request, reset the whole TT */
302 	if (up->req_reset_tt.bRequest != 0) {
303 		req.bmRequestType = UT_WRITE_CLASS_OTHER;
304 		req.bRequest = UR_RESET_TT;
305 		USETW(req.wValue, 0);
306 		req.wIndex[0] = port;
307 		req.wIndex[1] = 0;
308 		USETW(req.wLength, 0);
309 	} else {
310 		wValue = (ep->edesc->bEndpointAddress & 0xF) |
311 		      ((child->address & 0x7F) << 4) |
312 		      ((ep->edesc->bEndpointAddress & 0x80) << 8) |
313 		      ((ep->edesc->bmAttributes & 3) << 12);
314 
315 		req.bmRequestType = UT_WRITE_CLASS_OTHER;
316 		req.bRequest = UR_CLEAR_TT_BUFFER;
317 		USETW(req.wValue, wValue);
318 		req.wIndex[0] = port;
319 		req.wIndex[1] = 0;
320 		USETW(req.wLength, 0);
321 	}
322 	up->req_reset_tt = req;
323 	/* get reset transfer started */
324 	usb_proc_msignal(USB_BUS_TT_PROC(udev->bus),
325 	    &hub->tt_msg[0], &hub->tt_msg[1]);
326 }
327 #endif
328 
329 #if USB_HAVE_TT_SUPPORT
330 static void
331 uhub_reset_tt_callback(struct usb_xfer *xfer, usb_error_t error)
332 {
333 	struct uhub_softc *sc;
334 	struct usb_device *udev;
335 	struct usb_port *up;
336 	uint8_t x;
337 
338 	DPRINTF("TT buffer reset\n");
339 
340 	sc = usbd_xfer_softc(xfer);
341 	udev = sc->sc_udev;
342 
343 	switch (USB_GET_STATE(xfer)) {
344 	case USB_ST_TRANSFERRED:
345 	case USB_ST_SETUP:
346 tr_setup:
347 		USB_BUS_LOCK(udev->bus);
348 		/* find first port which needs a TT reset */
349 		for (x = 0; x != udev->hub->nports; x++) {
350 			up = udev->hub->ports + x;
351 
352 			if (up->req_reset_tt.bRequest == 0)
353 				continue;
354 
355 			/* copy in the transfer */
356 			usbd_copy_in(xfer->frbuffers, 0, &up->req_reset_tt,
357 			    sizeof(up->req_reset_tt));
358 			/* reset buffer */
359 			memset(&up->req_reset_tt, 0, sizeof(up->req_reset_tt));
360 
361 			/* set length */
362 			usbd_xfer_set_frame_len(xfer, 0, sizeof(up->req_reset_tt));
363 			xfer->nframes = 1;
364 			USB_BUS_UNLOCK(udev->bus);
365 
366 			usbd_transfer_submit(xfer);
367 			return;
368 		}
369 		USB_BUS_UNLOCK(udev->bus);
370 		break;
371 
372 	default:
373 		if (error == USB_ERR_CANCELLED)
374 			break;
375 
376 		DPRINTF("TT buffer reset failed (%s)\n", usbd_errstr(error));
377 		goto tr_setup;
378 	}
379 }
380 #endif
381 
382 /*------------------------------------------------------------------------*
383  *      uhub_count_active_host_ports
384  *
385  * This function counts the number of active ports at the given speed.
386  *------------------------------------------------------------------------*/
387 uint8_t
388 uhub_count_active_host_ports(struct usb_device *udev, enum usb_dev_speed speed)
389 {
390 	struct uhub_softc *sc;
391 	struct usb_device *child;
392 	struct usb_hub *hub;
393 	struct usb_port *up;
394 	uint8_t retval = 0;
395 	uint8_t x;
396 
397 	if (udev == NULL)
398 		goto done;
399 	hub = udev->hub;
400 	if (hub == NULL)
401 		goto done;
402 	sc = hub->hubsoftc;
403 	if (sc == NULL)
404 		goto done;
405 
406 	for (x = 0; x != hub->nports; x++) {
407 		up = hub->ports + x;
408 		child = usb_bus_port_get_device(udev->bus, up);
409 		if (child != NULL &&
410 		    child->flags.usb_mode == USB_MODE_HOST &&
411 		    child->speed == speed)
412 			retval++;
413 	}
414 done:
415 	return (retval);
416 }
417 
418 void
419 uhub_explore_handle_re_enumerate(struct usb_device *child)
420 {
421 	uint8_t do_unlock;
422 	usb_error_t err;
423 
424 	/* check if device should be re-enumerated */
425 	if (child->flags.usb_mode != USB_MODE_HOST)
426 		return;
427 
428 	do_unlock = usbd_enum_lock(child);
429 	switch (child->re_enumerate_wait) {
430 	case USB_RE_ENUM_START:
431 		err = usbd_set_config_index(child,
432 		    USB_UNCONFIG_INDEX);
433 		if (err != 0) {
434 			DPRINTF("Unconfigure failed: %s: Ignored.\n",
435 			    usbd_errstr(err));
436 		}
437 		if (child->parent_hub == NULL) {
438 			/* the root HUB cannot be re-enumerated */
439 			DPRINTFN(6, "cannot reset root HUB\n");
440 			err = 0;
441 		} else {
442 			err = usbd_req_re_enumerate(child, NULL);
443 		}
444 		if (err == 0) {
445 			/* refresh device strings */
446 			usb_get_langid(child);
447 			usb_set_device_strings(child);
448 
449 			/* set default configuration */
450 			err = usbd_set_config_index(child, 0);
451 		}
452 		if (err == 0) {
453 			err = usb_probe_and_attach(child,
454 			    USB_IFACE_INDEX_ANY);
455 		}
456 		child->re_enumerate_wait = USB_RE_ENUM_DONE;
457 		break;
458 
459 	case USB_RE_ENUM_PWR_OFF:
460 		/* get the device unconfigured */
461 		err = usbd_set_config_index(child,
462 		    USB_UNCONFIG_INDEX);
463 		if (err) {
464 			DPRINTFN(0, "Could not unconfigure "
465 			    "device (ignored)\n");
466 		}
467 		if (child->parent_hub == NULL) {
468 			/* the root HUB cannot be re-enumerated */
469 			DPRINTFN(6, "cannot set port feature\n");
470 			err = 0;
471 		} else {
472 			/* clear port enable */
473 			err = usbd_req_clear_port_feature(child->parent_hub,
474 			    NULL, child->port_no, UHF_PORT_ENABLE);
475 			if (err) {
476 				DPRINTFN(0, "Could not disable port "
477 				    "(ignored)\n");
478 			}
479 		}
480 		child->re_enumerate_wait = USB_RE_ENUM_DONE;
481 		break;
482 
483 	case USB_RE_ENUM_SET_CONFIG:
484 		err = usbd_set_config_index(child,
485 		    child->next_config_index);
486 		if (err != 0) {
487 			DPRINTF("Configure failed: %s: Ignored.\n",
488 			    usbd_errstr(err));
489 		} else {
490 			err = usb_probe_and_attach(child,
491 			    USB_IFACE_INDEX_ANY);
492 		}
493 		child->re_enumerate_wait = USB_RE_ENUM_DONE;
494 		break;
495 
496 	default:
497 		child->re_enumerate_wait = USB_RE_ENUM_DONE;
498 		break;
499 	}
500 	if (do_unlock)
501 		usbd_enum_unlock(child);
502 }
503 
504 /*------------------------------------------------------------------------*
505  *	uhub_explore_sub - subroutine
506  *
507  * Return values:
508  *    0: Success
509  * Else: A control transaction failed
510  *------------------------------------------------------------------------*/
511 static usb_error_t
512 uhub_explore_sub(struct uhub_softc *sc, struct usb_port *up)
513 {
514 	struct usb_bus *bus;
515 	struct usb_device *child;
516 	uint8_t refcount;
517 	usb_error_t err;
518 
519 	bus = sc->sc_udev->bus;
520 	err = 0;
521 
522 	/* get driver added refcount from USB bus */
523 	refcount = bus->driver_added_refcount;
524 
525 	/* get device assosiated with the given port */
526 	child = usb_bus_port_get_device(bus, up);
527 	if (child == NULL) {
528 		/* nothing to do */
529 		goto done;
530 	}
531 
532 	uhub_explore_handle_re_enumerate(child);
533 
534 	/* check if probe and attach should be done */
535 
536 	if (child->driver_added_refcount != refcount) {
537 		child->driver_added_refcount = refcount;
538 		err = usb_probe_and_attach(child,
539 		    USB_IFACE_INDEX_ANY);
540 		if (err) {
541 			goto done;
542 		}
543 	}
544 	/* start control transfer, if device mode */
545 
546 	if (child->flags.usb_mode == USB_MODE_DEVICE)
547 		usbd_ctrl_transfer_setup(child);
548 
549 	/* if a HUB becomes present, do a recursive HUB explore */
550 
551 	if (child->hub)
552 		err = (child->hub->explore) (child);
553 
554 done:
555 	return (err);
556 }
557 
558 /*------------------------------------------------------------------------*
559  *	uhub_read_port_status - factored out code
560  *------------------------------------------------------------------------*/
561 static usb_error_t
562 uhub_read_port_status(struct uhub_softc *sc, uint8_t portno)
563 {
564 	struct usb_port_status ps;
565 	usb_error_t err;
566 
567 	if (sc->sc_usb_port_errors >= UHUB_USB_PORT_ERRORS_MAX) {
568 		DPRINTFN(4, "port %d, HUB looks dead, too many errors\n", portno);
569 		sc->sc_st.port_status = 0;
570 		sc->sc_st.port_change = 0;
571 		return (USB_ERR_TIMEOUT);
572 	}
573 
574 	err = usbd_req_get_port_status(
575 	    sc->sc_udev, NULL, &ps, portno);
576 
577 	if (err == 0) {
578 		sc->sc_st.port_status = UGETW(ps.wPortStatus);
579 		sc->sc_st.port_change = UGETW(ps.wPortChange);
580 		sc->sc_usb_port_errors = 0;
581 	} else {
582 		sc->sc_st.port_status = 0;
583 		sc->sc_st.port_change = 0;
584 		sc->sc_usb_port_errors++;
585 	}
586 
587 	/* debugging print */
588 
589 	DPRINTFN(4, "port %d, wPortStatus=0x%04x, "
590 	    "wPortChange=0x%04x, err=%s\n",
591 	    portno, sc->sc_st.port_status,
592 	    sc->sc_st.port_change, usbd_errstr(err));
593 	return (err);
594 }
595 
596 /*------------------------------------------------------------------------*
597  *	uhub_reattach_port
598  *
599  * Returns:
600  *    0: Success
601  * Else: A control transaction failed
602  *------------------------------------------------------------------------*/
603 static usb_error_t
604 uhub_reattach_port(struct uhub_softc *sc, uint8_t portno)
605 {
606 	struct usb_device *child;
607 	struct usb_device *udev;
608 	enum usb_dev_speed speed;
609 	enum usb_hc_mode mode;
610 	usb_error_t err;
611 	uint16_t power_mask;
612 	uint8_t timeout;
613 
614 	DPRINTF("reattaching port %d\n", portno);
615 
616 	timeout = 0;
617 	udev = sc->sc_udev;
618 	child = usb_bus_port_get_device(udev->bus,
619 	    udev->hub->ports + portno - 1);
620 
621 repeat:
622 
623 	/* first clear the port connection change bit */
624 
625 	err = usbd_req_clear_port_feature(udev, NULL,
626 	    portno, UHF_C_PORT_CONNECTION);
627 
628 	if (err)
629 		goto error;
630 
631 	/* check if there is a child */
632 
633 	if (child != NULL) {
634 		/*
635 		 * Free USB device and all subdevices, if any.
636 		 */
637 		usb_free_device(child, 0);
638 		child = NULL;
639 	}
640 	/* get fresh status */
641 
642 	err = uhub_read_port_status(sc, portno);
643 	if (err)
644 		goto error;
645 
646 #if USB_HAVE_DISABLE_ENUM
647 	/* check if we should skip enumeration from this USB HUB */
648 	if (usb_disable_enumeration != 0 ||
649 	    sc->sc_disable_enumeration != 0) {
650 		DPRINTF("Enumeration is disabled!\n");
651 		goto error;
652 	}
653 #endif
654 	/* check if nothing is connected to the port */
655 
656 	if (!(sc->sc_st.port_status & UPS_CURRENT_CONNECT_STATUS))
657 		goto error;
658 
659 	/* check if there is no power on the port and print a warning */
660 
661 	switch (udev->speed) {
662 	case USB_SPEED_HIGH:
663 	case USB_SPEED_FULL:
664 	case USB_SPEED_LOW:
665 		power_mask = UPS_PORT_POWER;
666 		break;
667 	case USB_SPEED_SUPER:
668 		if (udev->parent_hub == NULL)
669 			power_mask = 0;	/* XXX undefined */
670 		else
671 			power_mask = UPS_PORT_POWER_SS;
672 		break;
673 	default:
674 		power_mask = 0;
675 		break;
676 	}
677 	if ((sc->sc_st.port_status & power_mask) != power_mask) {
678 		DPRINTF("WARNING: strange, connected port %d "
679 		    "has no power\n", portno);
680 	}
681 
682 	/* check if the device is in Host Mode */
683 
684 	if (!(sc->sc_st.port_status & UPS_PORT_MODE_DEVICE)) {
685 
686 		DPRINTF("Port %d is in Host Mode\n", portno);
687 
688 		if (sc->sc_st.port_status & UPS_SUSPEND) {
689 			/*
690 			 * NOTE: Should not get here in SuperSpeed
691 			 * mode, because the HUB should report this
692 			 * bit as zero.
693 			 */
694 			DPRINTF("Port %d was still "
695 			    "suspended, clearing.\n", portno);
696 			err = usbd_req_clear_port_feature(udev,
697 			    NULL, portno, UHF_PORT_SUSPEND);
698 		}
699 
700 		/* USB Host Mode */
701 
702 		/* wait for maximum device power up time */
703 
704 		usb_pause_mtx(NULL,
705 		    USB_MS_TO_TICKS(usb_port_powerup_delay));
706 
707 		/* reset port, which implies enabling it */
708 
709 		err = usbd_req_reset_port(udev, NULL, portno);
710 
711 		if (err) {
712 			DPRINTFN(0, "port %d reset "
713 			    "failed, error=%s\n",
714 			    portno, usbd_errstr(err));
715 			goto error;
716 		}
717 		/* get port status again, it might have changed during reset */
718 
719 		err = uhub_read_port_status(sc, portno);
720 		if (err) {
721 			goto error;
722 		}
723 		/* check if something changed during port reset */
724 
725 		if ((sc->sc_st.port_change & UPS_C_CONNECT_STATUS) ||
726 		    (!(sc->sc_st.port_status & UPS_CURRENT_CONNECT_STATUS))) {
727 			if (timeout) {
728 				DPRINTFN(0, "giving up port reset "
729 				    "- device vanished\n");
730 				goto error;
731 			}
732 			timeout = 1;
733 			goto repeat;
734 		}
735 	} else {
736 		DPRINTF("Port %d is in Device Mode\n", portno);
737 	}
738 
739 	/*
740 	 * Figure out the device speed
741 	 */
742 	switch (udev->speed) {
743 	case USB_SPEED_HIGH:
744 		if (sc->sc_st.port_status & UPS_HIGH_SPEED)
745 			speed = USB_SPEED_HIGH;
746 		else if (sc->sc_st.port_status & UPS_LOW_SPEED)
747 			speed = USB_SPEED_LOW;
748 		else
749 			speed = USB_SPEED_FULL;
750 		break;
751 	case USB_SPEED_FULL:
752 		if (sc->sc_st.port_status & UPS_LOW_SPEED)
753 			speed = USB_SPEED_LOW;
754 		else
755 			speed = USB_SPEED_FULL;
756 		break;
757 	case USB_SPEED_LOW:
758 		speed = USB_SPEED_LOW;
759 		break;
760 	case USB_SPEED_SUPER:
761 		if (udev->parent_hub == NULL) {
762 			/* Root HUB - special case */
763 			switch (sc->sc_st.port_status & UPS_OTHER_SPEED) {
764 			case 0:
765 				speed = USB_SPEED_FULL;
766 				break;
767 			case UPS_LOW_SPEED:
768 				speed = USB_SPEED_LOW;
769 				break;
770 			case UPS_HIGH_SPEED:
771 				speed = USB_SPEED_HIGH;
772 				break;
773 			default:
774 				speed = USB_SPEED_SUPER;
775 				break;
776 			}
777 		} else {
778 			speed = USB_SPEED_SUPER;
779 		}
780 		break;
781 	default:
782 		/* same speed like parent */
783 		speed = udev->speed;
784 		break;
785 	}
786 	if (speed == USB_SPEED_SUPER) {
787 		err = usbd_req_set_hub_u1_timeout(udev, NULL,
788 		    portno, 128 - (2 * udev->depth));
789 		if (err) {
790 			DPRINTFN(0, "port %d U1 timeout "
791 			    "failed, error=%s\n",
792 			    portno, usbd_errstr(err));
793 		}
794 		err = usbd_req_set_hub_u2_timeout(udev, NULL,
795 		    portno, 128 - (2 * udev->depth));
796 		if (err) {
797 			DPRINTFN(0, "port %d U2 timeout "
798 			    "failed, error=%s\n",
799 			    portno, usbd_errstr(err));
800 		}
801 	}
802 
803 	/*
804 	 * Figure out the device mode
805 	 *
806 	 * NOTE: This part is currently FreeBSD specific.
807 	 */
808 	if (udev->parent_hub != NULL) {
809 		/* inherit mode from the parent HUB */
810 		mode = udev->parent_hub->flags.usb_mode;
811 	} else if (sc->sc_st.port_status & UPS_PORT_MODE_DEVICE)
812 		mode = USB_MODE_DEVICE;
813 	else
814 		mode = USB_MODE_HOST;
815 
816 	/* need to create a new child */
817 	child = usb_alloc_device(sc->sc_dev, udev->bus, udev,
818 	    udev->depth + 1, portno - 1, portno, speed, mode);
819 	if (child == NULL) {
820 		DPRINTFN(0, "could not allocate new device\n");
821 		goto error;
822 	}
823 	return (0);			/* success */
824 
825 error:
826 	if (child != NULL) {
827 		/*
828 		 * Free USB device and all subdevices, if any.
829 		 */
830 		usb_free_device(child, 0);
831 		child = NULL;
832 	}
833 	if (err == 0) {
834 		if (sc->sc_st.port_status & UPS_PORT_ENABLED) {
835 			err = usbd_req_clear_port_feature(
836 			    sc->sc_udev, NULL,
837 			    portno, UHF_PORT_ENABLE);
838 		}
839 	}
840 	if (err) {
841 		DPRINTFN(0, "device problem (%s), "
842 		    "disabling port %d\n", usbd_errstr(err), portno);
843 	}
844 	return (err);
845 }
846 
847 /*------------------------------------------------------------------------*
848  *	usb_device_20_compatible
849  *
850  * Returns:
851  *    0: HUB does not support suspend and resume
852  * Else: HUB supports suspend and resume
853  *------------------------------------------------------------------------*/
854 static uint8_t
855 usb_device_20_compatible(struct usb_device *udev)
856 {
857 	if (udev == NULL)
858 		return (0);
859 	switch (udev->speed) {
860 	case USB_SPEED_LOW:
861 	case USB_SPEED_FULL:
862 	case USB_SPEED_HIGH:
863 		return (1);
864 	default:
865 		return (0);
866 	}
867 }
868 
869 /*------------------------------------------------------------------------*
870  *	uhub_suspend_resume_port
871  *
872  * Returns:
873  *    0: Success
874  * Else: A control transaction failed
875  *------------------------------------------------------------------------*/
876 static usb_error_t
877 uhub_suspend_resume_port(struct uhub_softc *sc, uint8_t portno)
878 {
879 	struct usb_device *child;
880 	struct usb_device *udev;
881 	uint8_t is_suspend;
882 	usb_error_t err;
883 
884 	DPRINTF("port %d\n", portno);
885 
886 	udev = sc->sc_udev;
887 	child = usb_bus_port_get_device(udev->bus,
888 	    udev->hub->ports + portno - 1);
889 
890 	/* first clear the port suspend change bit */
891 
892 	if (usb_device_20_compatible(udev)) {
893 		err = usbd_req_clear_port_feature(udev, NULL,
894 		    portno, UHF_C_PORT_SUSPEND);
895 	} else {
896 		err = usbd_req_clear_port_feature(udev, NULL,
897 		    portno, UHF_C_PORT_LINK_STATE);
898 	}
899 
900 	if (err) {
901 		DPRINTF("clearing suspend failed.\n");
902 		goto done;
903 	}
904 	/* get fresh status */
905 
906 	err = uhub_read_port_status(sc, portno);
907 	if (err) {
908 		DPRINTF("reading port status failed.\n");
909 		goto done;
910 	}
911 	/* convert current state */
912 
913 	if (usb_device_20_compatible(udev)) {
914 		if (sc->sc_st.port_status & UPS_SUSPEND) {
915 			is_suspend = 1;
916 		} else {
917 			is_suspend = 0;
918 		}
919 	} else {
920 		switch (UPS_PORT_LINK_STATE_GET(sc->sc_st.port_status)) {
921 		case UPS_PORT_LS_U3:
922 			is_suspend = 1;
923 			break;
924 		case UPS_PORT_LS_SS_INA:
925 			usbd_req_warm_reset_port(udev, NULL, portno);
926 			is_suspend = 0;
927 			break;
928 		default:
929 			is_suspend = 0;
930 			break;
931 		}
932 	}
933 
934 	DPRINTF("suspended=%u\n", is_suspend);
935 
936 	/* do the suspend or resume */
937 
938 	if (child) {
939 		/*
940 		 * This code handle two cases: 1) Host Mode - we can only
941 		 * receive resume here 2) Device Mode - we can receive
942 		 * suspend and resume here
943 		 */
944 		if (is_suspend == 0)
945 			usb_dev_resume_peer(child);
946 		else if (child->flags.usb_mode == USB_MODE_DEVICE)
947 			usb_dev_suspend_peer(child);
948 	}
949 done:
950 	return (err);
951 }
952 
953 /*------------------------------------------------------------------------*
954  *	uhub_root_interrupt
955  *
956  * This function is called when a Root HUB interrupt has
957  * happened. "ptr" and "len" makes up the Root HUB interrupt
958  * packet. This function is called having the "bus_mtx" locked.
959  *------------------------------------------------------------------------*/
960 void
961 uhub_root_intr(struct usb_bus *bus, const uint8_t *ptr, uint8_t len)
962 {
963 	USB_BUS_LOCK_ASSERT(bus, MA_OWNED);
964 
965 	usb_needs_explore(bus, 0);
966 }
967 
968 static uint8_t
969 uhub_is_too_deep(struct usb_device *udev)
970 {
971 	switch (udev->speed) {
972 	case USB_SPEED_FULL:
973 	case USB_SPEED_LOW:
974 	case USB_SPEED_HIGH:
975 		if (udev->depth > USB_HUB_MAX_DEPTH)
976 			return (1);
977 		break;
978 	case USB_SPEED_SUPER:
979 		if (udev->depth > USB_SS_HUB_DEPTH_MAX)
980 			return (1);
981 		break;
982 	default:
983 		break;
984 	}
985 	return (0);
986 }
987 
988 /*------------------------------------------------------------------------*
989  *	uhub_explore
990  *
991  * Returns:
992  *     0: Success
993  *  Else: Failure
994  *------------------------------------------------------------------------*/
995 static usb_error_t
996 uhub_explore(struct usb_device *udev)
997 {
998 	struct usb_hub *hub;
999 	struct uhub_softc *sc;
1000 	struct usb_port *up;
1001 	usb_error_t err;
1002 	uint8_t portno;
1003 	uint8_t x;
1004 	uint8_t do_unlock;
1005 
1006 	hub = udev->hub;
1007 	sc = hub->hubsoftc;
1008 
1009 	DPRINTFN(11, "udev=%p addr=%d\n", udev, udev->address);
1010 
1011 	/* ignore devices that are too deep */
1012 	if (uhub_is_too_deep(udev))
1013 		return (USB_ERR_TOO_DEEP);
1014 
1015 	/* check if device is suspended */
1016 	if (udev->flags.self_suspended) {
1017 		/* need to wait until the child signals resume */
1018 		DPRINTF("Device is suspended!\n");
1019 		return (0);
1020 	}
1021 
1022 	/*
1023 	 * Make sure we don't race against user-space applications
1024 	 * like LibUSB:
1025 	 */
1026 	do_unlock = usbd_enum_lock(udev);
1027 
1028 	for (x = 0; x != hub->nports; x++) {
1029 		up = hub->ports + x;
1030 		portno = x + 1;
1031 
1032 		err = uhub_read_port_status(sc, portno);
1033 		if (err) {
1034 			/* most likely the HUB is gone */
1035 			break;
1036 		}
1037 		if (sc->sc_st.port_change & UPS_C_OVERCURRENT_INDICATOR) {
1038 			DPRINTF("Overcurrent on port %u.\n", portno);
1039 			err = usbd_req_clear_port_feature(
1040 			    udev, NULL, portno, UHF_C_PORT_OVER_CURRENT);
1041 			if (err) {
1042 				/* most likely the HUB is gone */
1043 				break;
1044 			}
1045 		}
1046 		if (!(sc->sc_flags & UHUB_FLAG_DID_EXPLORE)) {
1047 			/*
1048 			 * Fake a connect status change so that the
1049 			 * status gets checked initially!
1050 			 */
1051 			sc->sc_st.port_change |=
1052 			    UPS_C_CONNECT_STATUS;
1053 		}
1054 		if (sc->sc_st.port_change & UPS_C_PORT_ENABLED) {
1055 			err = usbd_req_clear_port_feature(
1056 			    udev, NULL, portno, UHF_C_PORT_ENABLE);
1057 			if (err) {
1058 				/* most likely the HUB is gone */
1059 				break;
1060 			}
1061 			if (sc->sc_st.port_change & UPS_C_CONNECT_STATUS) {
1062 				/*
1063 				 * Ignore the port error if the device
1064 				 * has vanished !
1065 				 */
1066 			} else if (sc->sc_st.port_status & UPS_PORT_ENABLED) {
1067 				DPRINTFN(0, "illegal enable change, "
1068 				    "port %d\n", portno);
1069 			} else {
1070 
1071 				if (up->restartcnt == USB_RESTART_MAX) {
1072 					/* XXX could try another speed ? */
1073 					DPRINTFN(0, "port error, giving up "
1074 					    "port %d\n", portno);
1075 				} else {
1076 					sc->sc_st.port_change |=
1077 					    UPS_C_CONNECT_STATUS;
1078 					up->restartcnt++;
1079 				}
1080 			}
1081 		}
1082 		if (sc->sc_st.port_change & UPS_C_CONNECT_STATUS) {
1083 			err = uhub_reattach_port(sc, portno);
1084 			if (err) {
1085 				/* most likely the HUB is gone */
1086 				break;
1087 			}
1088 		}
1089 		if (sc->sc_st.port_change & (UPS_C_SUSPEND |
1090 		    UPS_C_PORT_LINK_STATE)) {
1091 			err = uhub_suspend_resume_port(sc, portno);
1092 			if (err) {
1093 				/* most likely the HUB is gone */
1094 				break;
1095 			}
1096 		}
1097 		err = uhub_explore_sub(sc, up);
1098 		if (err) {
1099 			/* no device(s) present */
1100 			continue;
1101 		}
1102 		/* explore succeeded - reset restart counter */
1103 		up->restartcnt = 0;
1104 	}
1105 
1106 	if (do_unlock)
1107 		usbd_enum_unlock(udev);
1108 
1109 	/* initial status checked */
1110 	sc->sc_flags |= UHUB_FLAG_DID_EXPLORE;
1111 
1112 	/* return success */
1113 	return (USB_ERR_NORMAL_COMPLETION);
1114 }
1115 
1116 int
1117 uhub_probe(device_t dev)
1118 {
1119 	struct usb_attach_arg *uaa = device_get_ivars(dev);
1120 
1121 	if (uaa->usb_mode != USB_MODE_HOST)
1122 		return (ENXIO);
1123 
1124 	/*
1125 	 * The subclass for USB HUBs is currently ignored because it
1126 	 * is 0 for some and 1 for others.
1127 	 */
1128 	if (uaa->info.bConfigIndex == 0 &&
1129 	    uaa->info.bDeviceClass == UDCLASS_HUB)
1130 		return (BUS_PROBE_DEFAULT);
1131 
1132 	return (ENXIO);
1133 }
1134 
1135 /* NOTE: The information returned by this function can be wrong. */
1136 usb_error_t
1137 uhub_query_info(struct usb_device *udev, uint8_t *pnports, uint8_t *ptt)
1138 {
1139 	struct usb_hub_descriptor hubdesc20;
1140 	struct usb_hub_ss_descriptor hubdesc30;
1141 	usb_error_t err;
1142 	uint8_t nports;
1143 	uint8_t tt;
1144 
1145 	if (udev->ddesc.bDeviceClass != UDCLASS_HUB)
1146 		return (USB_ERR_INVAL);
1147 
1148 	nports = 0;
1149 	tt = 0;
1150 
1151 	switch (udev->speed) {
1152 	case USB_SPEED_LOW:
1153 	case USB_SPEED_FULL:
1154 	case USB_SPEED_HIGH:
1155 		/* assuming that there is one port */
1156 		err = usbd_req_get_hub_descriptor(udev, NULL, &hubdesc20, 1);
1157 		if (err) {
1158 			DPRINTFN(0, "getting USB 2.0 HUB descriptor failed,"
1159 			    "error=%s\n", usbd_errstr(err));
1160 			break;
1161 		}
1162 		nports = hubdesc20.bNbrPorts;
1163 		if (nports > 127)
1164 			nports = 127;
1165 
1166 		if (udev->speed == USB_SPEED_HIGH)
1167 			tt = (UGETW(hubdesc20.wHubCharacteristics) >> 5) & 3;
1168 		break;
1169 
1170 	case USB_SPEED_SUPER:
1171 		err = usbd_req_get_ss_hub_descriptor(udev, NULL, &hubdesc30, 1);
1172 		if (err) {
1173 			DPRINTFN(0, "Getting USB 3.0 HUB descriptor failed,"
1174 			    "error=%s\n", usbd_errstr(err));
1175 			break;
1176 		}
1177 		nports = hubdesc30.bNbrPorts;
1178 		if (nports > 16)
1179 			nports = 16;
1180 		break;
1181 
1182 	default:
1183 		err = USB_ERR_INVAL;
1184 		break;
1185 	}
1186 
1187 	if (pnports != NULL)
1188 		*pnports = nports;
1189 
1190 	if (ptt != NULL)
1191 		*ptt = tt;
1192 
1193 	return (err);
1194 }
1195 
1196 int
1197 uhub_attach(device_t dev)
1198 {
1199 	struct uhub_softc *sc = device_get_softc(dev);
1200 	struct usb_attach_arg *uaa = device_get_ivars(dev);
1201 	struct usb_device *udev = uaa->device;
1202 	struct usb_device *parent_hub = udev->parent_hub;
1203 	struct usb_hub *hub;
1204 	struct usb_hub_descriptor hubdesc20;
1205 	struct usb_hub_ss_descriptor hubdesc30;
1206 #if USB_HAVE_DISABLE_ENUM
1207 	struct sysctl_ctx_list *sysctl_ctx;
1208 	struct sysctl_oid *sysctl_tree;
1209 #endif
1210 	uint16_t pwrdly;
1211 	uint16_t nports;
1212 	uint8_t x;
1213 	uint8_t portno;
1214 	uint8_t removable;
1215 	uint8_t iface_index;
1216 	usb_error_t err;
1217 
1218 	sc->sc_udev = udev;
1219 	sc->sc_dev = dev;
1220 
1221 	mtx_init(&sc->sc_mtx, "USB HUB mutex", NULL, MTX_DEF);
1222 
1223 	device_set_usb_desc(dev);
1224 
1225 	DPRINTFN(2, "depth=%d selfpowered=%d, parent=%p, "
1226 	    "parent->selfpowered=%d\n",
1227 	    udev->depth,
1228 	    udev->flags.self_powered,
1229 	    parent_hub,
1230 	    parent_hub ?
1231 	    parent_hub->flags.self_powered : 0);
1232 
1233 	if (uhub_is_too_deep(udev)) {
1234 		DPRINTFN(0, "HUB at depth %d, "
1235 		    "exceeds maximum. HUB ignored\n", (int)udev->depth);
1236 		goto error;
1237 	}
1238 
1239 	if (!udev->flags.self_powered && parent_hub &&
1240 	    !parent_hub->flags.self_powered) {
1241 		DPRINTFN(0, "Bus powered HUB connected to "
1242 		    "bus powered HUB. HUB ignored\n");
1243 		goto error;
1244 	}
1245 
1246 	if (UHUB_IS_MULTI_TT(sc)) {
1247 		err = usbd_set_alt_interface_index(udev, 0, 1);
1248 		if (err) {
1249 			device_printf(dev, "MTT could not be enabled\n");
1250 			goto error;
1251 		}
1252 		device_printf(dev, "MTT enabled\n");
1253 	}
1254 
1255 	/* get HUB descriptor */
1256 
1257 	DPRINTFN(2, "Getting HUB descriptor\n");
1258 
1259 	switch (udev->speed) {
1260 	case USB_SPEED_LOW:
1261 	case USB_SPEED_FULL:
1262 	case USB_SPEED_HIGH:
1263 		/* assuming that there is one port */
1264 		err = usbd_req_get_hub_descriptor(udev, NULL, &hubdesc20, 1);
1265 		if (err) {
1266 			DPRINTFN(0, "getting USB 2.0 HUB descriptor failed,"
1267 			    "error=%s\n", usbd_errstr(err));
1268 			goto error;
1269 		}
1270 		/* get number of ports */
1271 		nports = hubdesc20.bNbrPorts;
1272 
1273 		/* get power delay */
1274 		pwrdly = ((hubdesc20.bPwrOn2PwrGood * UHD_PWRON_FACTOR) +
1275 		    usb_extra_power_up_time);
1276 
1277 		/* get complete HUB descriptor */
1278 		if (nports >= 8) {
1279 			/* check number of ports */
1280 			if (nports > 127) {
1281 				DPRINTFN(0, "Invalid number of USB 2.0 ports,"
1282 				    "error=%s\n", usbd_errstr(err));
1283 				goto error;
1284 			}
1285 			/* get complete HUB descriptor */
1286 			err = usbd_req_get_hub_descriptor(udev, NULL, &hubdesc20, nports);
1287 
1288 			if (err) {
1289 				DPRINTFN(0, "Getting USB 2.0 HUB descriptor failed,"
1290 				    "error=%s\n", usbd_errstr(err));
1291 				goto error;
1292 			}
1293 			if (hubdesc20.bNbrPorts != nports) {
1294 				DPRINTFN(0, "Number of ports changed\n");
1295 				goto error;
1296 			}
1297 		}
1298 		break;
1299 	case USB_SPEED_SUPER:
1300 		if (udev->parent_hub != NULL) {
1301 			err = usbd_req_set_hub_depth(udev, NULL,
1302 			    udev->depth - 1);
1303 			if (err) {
1304 				DPRINTFN(0, "Setting USB 3.0 HUB depth failed,"
1305 				    "error=%s\n", usbd_errstr(err));
1306 				goto error;
1307 			}
1308 		}
1309 		err = usbd_req_get_ss_hub_descriptor(udev, NULL, &hubdesc30, 1);
1310 		if (err) {
1311 			DPRINTFN(0, "Getting USB 3.0 HUB descriptor failed,"
1312 			    "error=%s\n", usbd_errstr(err));
1313 			goto error;
1314 		}
1315 		/* get number of ports */
1316 		nports = hubdesc30.bNbrPorts;
1317 
1318 		/* get power delay */
1319 		pwrdly = ((hubdesc30.bPwrOn2PwrGood * UHD_PWRON_FACTOR) +
1320 		    usb_extra_power_up_time);
1321 
1322 		/* get complete HUB descriptor */
1323 		if (nports >= 8) {
1324 			/* check number of ports */
1325 			if (nports > ((udev->parent_hub != NULL) ? 15 : 127)) {
1326 				DPRINTFN(0, "Invalid number of USB 3.0 ports,"
1327 				    "error=%s\n", usbd_errstr(err));
1328 				goto error;
1329 			}
1330 			/* get complete HUB descriptor */
1331 			err = usbd_req_get_ss_hub_descriptor(udev, NULL, &hubdesc30, nports);
1332 
1333 			if (err) {
1334 				DPRINTFN(0, "Getting USB 2.0 HUB descriptor failed,"
1335 				    "error=%s\n", usbd_errstr(err));
1336 				goto error;
1337 			}
1338 			if (hubdesc30.bNbrPorts != nports) {
1339 				DPRINTFN(0, "Number of ports changed\n");
1340 				goto error;
1341 			}
1342 		}
1343 		break;
1344 	default:
1345 		DPRINTF("Assuming HUB has only one port\n");
1346 		/* default number of ports */
1347 		nports = 1;
1348 		/* default power delay */
1349 		pwrdly = ((10 * UHD_PWRON_FACTOR) + usb_extra_power_up_time);
1350 		break;
1351 	}
1352 	if (nports == 0) {
1353 		DPRINTFN(0, "portless HUB\n");
1354 		goto error;
1355 	}
1356 	if (nports > USB_MAX_PORTS) {
1357 		DPRINTF("Port limit exceeded\n");
1358 		goto error;
1359 	}
1360 #if (USB_HAVE_FIXED_PORT == 0)
1361 	hub = malloc(sizeof(hub[0]) + (sizeof(hub->ports[0]) * nports),
1362 	    M_USBDEV, M_WAITOK | M_ZERO);
1363 
1364 	if (hub == NULL)
1365 		goto error;
1366 #else
1367 	hub = &sc->sc_hub;
1368 #endif
1369 	udev->hub = hub;
1370 
1371 	/* initialize HUB structure */
1372 	hub->hubsoftc = sc;
1373 	hub->explore = &uhub_explore;
1374 	hub->nports = nports;
1375 	hub->hubudev = udev;
1376 #if USB_HAVE_TT_SUPPORT
1377 	hub->tt_msg[0].hdr.pm_callback = &uhub_reset_tt_proc;
1378 	hub->tt_msg[0].udev = udev;
1379 	hub->tt_msg[1].hdr.pm_callback = &uhub_reset_tt_proc;
1380 	hub->tt_msg[1].udev = udev;
1381 #endif
1382 	/* if self powered hub, give ports maximum current */
1383 	if (udev->flags.self_powered) {
1384 		hub->portpower = USB_MAX_POWER;
1385 	} else {
1386 		hub->portpower = USB_MIN_POWER;
1387 	}
1388 
1389 	/* set up interrupt pipe */
1390 	iface_index = 0;
1391 	if (udev->parent_hub == NULL) {
1392 		/* root HUB is special */
1393 		err = 0;
1394 	} else {
1395 		/* normal HUB */
1396 		err = usbd_transfer_setup(udev, &iface_index, sc->sc_xfer,
1397 		    uhub_config, UHUB_N_TRANSFER, sc, &sc->sc_mtx);
1398 	}
1399 	if (err) {
1400 		DPRINTFN(0, "cannot setup interrupt transfer, "
1401 		    "errstr=%s\n", usbd_errstr(err));
1402 		goto error;
1403 	}
1404 	/* wait with power off for a while */
1405 	usb_pause_mtx(NULL, USB_MS_TO_TICKS(USB_POWER_DOWN_TIME));
1406 
1407 #if USB_HAVE_DISABLE_ENUM
1408 	/* Add device sysctls */
1409 
1410 	sysctl_ctx = device_get_sysctl_ctx(dev);
1411 	sysctl_tree = device_get_sysctl_tree(dev);
1412 
1413 	if (sysctl_ctx != NULL && sysctl_tree != NULL) {
1414 		(void) SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1415 		    OID_AUTO, "disable_enumeration", CTLFLAG_RWTUN,
1416 		    &sc->sc_disable_enumeration, 0,
1417 		    "Set to disable enumeration on this USB HUB.");
1418 
1419 		(void) SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1420 		    OID_AUTO, "disable_port_power", CTLFLAG_RWTUN,
1421 		    &sc->sc_disable_port_power, 0,
1422 		    "Set to disable USB port power on this USB HUB.");
1423 	}
1424 #endif
1425 	/*
1426 	 * To have the best chance of success we do things in the exact same
1427 	 * order as Windoze98.  This should not be necessary, but some
1428 	 * devices do not follow the USB specs to the letter.
1429 	 *
1430 	 * These are the events on the bus when a hub is attached:
1431 	 *  Get device and config descriptors (see attach code)
1432 	 *  Get hub descriptor (see above)
1433 	 *  For all ports
1434 	 *     turn on power
1435 	 *     wait for power to become stable
1436 	 * (all below happens in explore code)
1437 	 *  For all ports
1438 	 *     clear C_PORT_CONNECTION
1439 	 *  For all ports
1440 	 *     get port status
1441 	 *     if device connected
1442 	 *        wait 100 ms
1443 	 *        turn on reset
1444 	 *        wait
1445 	 *        clear C_PORT_RESET
1446 	 *        get port status
1447 	 *        proceed with device attachment
1448 	 */
1449 
1450 	/* XXX should check for none, individual, or ganged power? */
1451 
1452 	removable = 0;
1453 
1454 	for (x = 0; x != nports; x++) {
1455 		/* set up data structures */
1456 		struct usb_port *up = hub->ports + x;
1457 
1458 		up->device_index = 0;
1459 		up->restartcnt = 0;
1460 		portno = x + 1;
1461 
1462 		/* check if port is removable */
1463 		switch (udev->speed) {
1464 		case USB_SPEED_LOW:
1465 		case USB_SPEED_FULL:
1466 		case USB_SPEED_HIGH:
1467 			if (!UHD_NOT_REMOV(&hubdesc20, portno))
1468 				removable++;
1469 			break;
1470 		case USB_SPEED_SUPER:
1471 			if (!UHD_NOT_REMOV(&hubdesc30, portno))
1472 				removable++;
1473 			break;
1474 		default:
1475 			DPRINTF("Assuming removable port\n");
1476 			removable++;
1477 			break;
1478 		}
1479 		if (err == 0) {
1480 #if USB_HAVE_DISABLE_ENUM
1481 			/* check if we should disable USB port power or not */
1482 			if (usb_disable_port_power != 0 ||
1483 			    sc->sc_disable_port_power != 0) {
1484 				/* turn the power off */
1485 				DPRINTFN(2, "Turning port %d power off\n", portno);
1486 				err = usbd_req_clear_port_feature(udev, NULL,
1487 				    portno, UHF_PORT_POWER);
1488 			} else {
1489 #endif
1490 				/* turn the power on */
1491 				DPRINTFN(2, "Turning port %d power on\n", portno);
1492 				err = usbd_req_set_port_feature(udev, NULL,
1493 				    portno, UHF_PORT_POWER);
1494 #if USB_HAVE_DISABLE_ENUM
1495 			}
1496 #endif
1497 		}
1498 		if (err != 0) {
1499 			DPRINTFN(0, "port %d power on or off failed, %s\n",
1500 			    portno, usbd_errstr(err));
1501 		}
1502 		DPRINTF("turn on port %d power\n",
1503 		    portno);
1504 
1505 		/* wait for stable power */
1506 		usb_pause_mtx(NULL, USB_MS_TO_TICKS(pwrdly));
1507 	}
1508 
1509 	device_printf(dev, "%d port%s with %d "
1510 	    "removable, %s powered\n", nports, (nports != 1) ? "s" : "",
1511 	    removable, udev->flags.self_powered ? "self" : "bus");
1512 
1513 	/* Start the interrupt endpoint, if any */
1514 
1515 	USB_MTX_LOCK(&sc->sc_mtx);
1516 	usbd_transfer_start(sc->sc_xfer[UHUB_INTR_TRANSFER]);
1517 	USB_MTX_UNLOCK(&sc->sc_mtx);
1518 
1519 	/* Enable automatic power save on all USB HUBs */
1520 
1521 	usbd_set_power_mode(udev, USB_POWER_MODE_SAVE);
1522 
1523 	return (0);
1524 
1525 error:
1526 	usbd_transfer_unsetup(sc->sc_xfer, UHUB_N_TRANSFER);
1527 
1528 #if (USB_HAVE_FIXED_PORT == 0)
1529 	free(udev->hub, M_USBDEV);
1530 #endif
1531 	udev->hub = NULL;
1532 
1533 	mtx_destroy(&sc->sc_mtx);
1534 
1535 	return (ENXIO);
1536 }
1537 
1538 /*
1539  * Called from process context when the hub is gone.
1540  * Detach all devices on active ports.
1541  */
1542 int
1543 uhub_detach(device_t dev)
1544 {
1545 	struct uhub_softc *sc = device_get_softc(dev);
1546 	struct usb_hub *hub = sc->sc_udev->hub;
1547 	struct usb_bus *bus = sc->sc_udev->bus;
1548 	struct usb_device *child;
1549 	uint8_t x;
1550 
1551 	if (hub == NULL)		/* must be partially working */
1552 		return (0);
1553 
1554 	/* Make sure interrupt transfer is gone. */
1555 	usbd_transfer_unsetup(sc->sc_xfer, UHUB_N_TRANSFER);
1556 
1557 	/* Detach all ports */
1558 	for (x = 0; x != hub->nports; x++) {
1559 
1560 		child = usb_bus_port_get_device(bus, hub->ports + x);
1561 
1562 		if (child == NULL) {
1563 			continue;
1564 		}
1565 
1566 		/*
1567 		 * Free USB device and all subdevices, if any.
1568 		 */
1569 		usb_free_device(child, 0);
1570 	}
1571 
1572 #if USB_HAVE_TT_SUPPORT
1573 	/* Make sure our TT messages are not queued anywhere */
1574 	USB_BUS_LOCK(bus);
1575 	usb_proc_mwait(USB_BUS_TT_PROC(bus),
1576 	    &hub->tt_msg[0], &hub->tt_msg[1]);
1577 	USB_BUS_UNLOCK(bus);
1578 #endif
1579 
1580 #if (USB_HAVE_FIXED_PORT == 0)
1581 	free(hub, M_USBDEV);
1582 #endif
1583 	sc->sc_udev->hub = NULL;
1584 
1585 	mtx_destroy(&sc->sc_mtx);
1586 
1587 	return (0);
1588 }
1589 
1590 static int
1591 uhub_suspend(device_t dev)
1592 {
1593 	DPRINTF("\n");
1594 	/* Sub-devices are not suspended here! */
1595 	return (0);
1596 }
1597 
1598 static int
1599 uhub_resume(device_t dev)
1600 {
1601 	DPRINTF("\n");
1602 	/* Sub-devices are not resumed here! */
1603 	return (0);
1604 }
1605 
1606 static void
1607 uhub_driver_added(device_t dev, driver_t *driver)
1608 {
1609 	usb_needs_explore_all();
1610 }
1611 
1612 void
1613 uhub_find_iface_index(struct usb_hub *hub, device_t child,
1614     struct hub_result *res)
1615 {
1616 	struct usb_interface *iface;
1617 	struct usb_device *udev;
1618 	uint8_t nports;
1619 	uint8_t x;
1620 	uint8_t i;
1621 
1622 	nports = hub->nports;
1623 	for (x = 0; x != nports; x++) {
1624 		udev = usb_bus_port_get_device(hub->hubudev->bus,
1625 		    hub->ports + x);
1626 		if (!udev) {
1627 			continue;
1628 		}
1629 		for (i = 0; i != USB_IFACE_MAX; i++) {
1630 			iface = usbd_get_iface(udev, i);
1631 			if (iface &&
1632 			    (iface->subdev == child)) {
1633 				res->iface_index = i;
1634 				res->udev = udev;
1635 				res->portno = x + 1;
1636 				return;
1637 			}
1638 		}
1639 	}
1640 	res->iface_index = 0;
1641 	res->udev = NULL;
1642 	res->portno = 0;
1643 }
1644 
1645 int
1646 uhub_child_location_string(device_t parent, device_t child,
1647     char *buf, size_t buflen)
1648 {
1649 	struct uhub_softc *sc;
1650 	struct usb_hub *hub;
1651 	struct hub_result res;
1652 
1653 	if (!device_is_attached(parent)) {
1654 		if (buflen)
1655 			buf[0] = 0;
1656 		return (0);
1657 	}
1658 
1659 	sc = device_get_softc(parent);
1660 	hub = sc->sc_udev->hub;
1661 
1662 	mtx_lock(&Giant);
1663 	uhub_find_iface_index(hub, child, &res);
1664 	if (!res.udev) {
1665 		DPRINTF("device not on hub\n");
1666 		if (buflen) {
1667 			buf[0] = '\0';
1668 		}
1669 		goto done;
1670 	}
1671 	snprintf(buf, buflen, "bus=%u hubaddr=%u port=%u devaddr=%u"
1672 	    " interface=%u"
1673 #if USB_HAVE_UGEN
1674 	    " ugen=%s"
1675 #endif
1676 	    , device_get_unit(res.udev->bus->bdev)
1677 	    , (res.udev->parent_hub != NULL) ?
1678 	    res.udev->parent_hub->device_index : 0
1679 	    , res.portno, res.udev->device_index, res.iface_index
1680 #if USB_HAVE_UGEN
1681 	    , res.udev->ugen_name
1682 #endif
1683 	    );
1684 done:
1685 	mtx_unlock(&Giant);
1686 
1687 	return (0);
1688 }
1689 
1690 static int
1691 uhub_child_pnpinfo_string(device_t parent, device_t child,
1692     char *buf, size_t buflen)
1693 {
1694 	struct uhub_softc *sc;
1695 	struct usb_hub *hub;
1696 	struct usb_interface *iface;
1697 	struct hub_result res;
1698 	uint8_t do_unlock;
1699 
1700 	if (!device_is_attached(parent)) {
1701 		if (buflen)
1702 			buf[0] = 0;
1703 		return (0);
1704 	}
1705 
1706 	sc = device_get_softc(parent);
1707 	hub = sc->sc_udev->hub;
1708 
1709 	mtx_lock(&Giant);
1710 	uhub_find_iface_index(hub, child, &res);
1711 	if (!res.udev) {
1712 		DPRINTF("device not on hub\n");
1713 		if (buflen) {
1714 			buf[0] = '\0';
1715 		}
1716 		goto done;
1717 	}
1718 	iface = usbd_get_iface(res.udev, res.iface_index);
1719 	if (iface && iface->idesc) {
1720 		/* Make sure device information is not changed during the print. */
1721 		do_unlock = usbd_ctrl_lock(res.udev);
1722 
1723 		snprintf(buf, buflen, "vendor=0x%04x product=0x%04x "
1724 		    "devclass=0x%02x devsubclass=0x%02x "
1725 		    "devproto=0x%02x "
1726 		    "sernum=\"%s\" "
1727 		    "release=0x%04x "
1728 		    "mode=%s "
1729 		    "intclass=0x%02x intsubclass=0x%02x "
1730 		    "intprotocol=0x%02x" "%s%s",
1731 		    UGETW(res.udev->ddesc.idVendor),
1732 		    UGETW(res.udev->ddesc.idProduct),
1733 		    res.udev->ddesc.bDeviceClass,
1734 		    res.udev->ddesc.bDeviceSubClass,
1735 		    res.udev->ddesc.bDeviceProtocol,
1736 		    usb_get_serial(res.udev),
1737 		    UGETW(res.udev->ddesc.bcdDevice),
1738 		    (res.udev->flags.usb_mode == USB_MODE_HOST) ? "host" : "device",
1739 		    iface->idesc->bInterfaceClass,
1740 		    iface->idesc->bInterfaceSubClass,
1741 		    iface->idesc->bInterfaceProtocol,
1742 		    iface->pnpinfo ? " " : "",
1743 		    iface->pnpinfo ? iface->pnpinfo : "");
1744 
1745 		if (do_unlock)
1746 			usbd_ctrl_unlock(res.udev);
1747 	} else {
1748 		if (buflen) {
1749 			buf[0] = '\0';
1750 		}
1751 		goto done;
1752 	}
1753 done:
1754 	mtx_unlock(&Giant);
1755 
1756 	return (0);
1757 }
1758 
1759 /*
1760  * The USB Transaction Translator:
1761  * ===============================
1762  *
1763  * When doing LOW- and FULL-speed USB transfers across a HIGH-speed
1764  * USB HUB, bandwidth must be allocated for ISOCHRONOUS and INTERRUPT
1765  * USB transfers. To utilize bandwidth dynamically the "scatter and
1766  * gather" principle must be applied. This means that bandwidth must
1767  * be divided into equal parts of bandwidth. With regard to USB all
1768  * data is transferred in smaller packets with length
1769  * "wMaxPacketSize". The problem however is that "wMaxPacketSize" is
1770  * not a constant!
1771  *
1772  * The bandwidth scheduler which I have implemented will simply pack
1773  * the USB transfers back to back until there is no more space in the
1774  * schedule. Out of the 8 microframes which the USB 2.0 standard
1775  * provides, only 6 are available for non-HIGH-speed devices. I have
1776  * reserved the first 4 microframes for ISOCHRONOUS transfers. The
1777  * last 2 microframes I have reserved for INTERRUPT transfers. Without
1778  * this division, it is very difficult to allocate and free bandwidth
1779  * dynamically.
1780  *
1781  * NOTE about the Transaction Translator in USB HUBs:
1782  *
1783  * USB HUBs have a very simple Transaction Translator, that will
1784  * simply pipeline all the SPLIT transactions. That means that the
1785  * transactions will be executed in the order they are queued!
1786  *
1787  */
1788 
1789 /*------------------------------------------------------------------------*
1790  *	usb_intr_find_best_slot
1791  *
1792  * Return value:
1793  *   The best Transaction Translation slot for an interrupt endpoint.
1794  *------------------------------------------------------------------------*/
1795 static uint8_t
1796 usb_intr_find_best_slot(usb_size_t *ptr, uint8_t start,
1797     uint8_t end, uint8_t mask)
1798 {
1799 	usb_size_t min = (usb_size_t)-1;
1800 	usb_size_t sum;
1801 	uint8_t x;
1802 	uint8_t y;
1803 	uint8_t z;
1804 
1805 	y = 0;
1806 
1807 	/* find the last slot with lesser used bandwidth */
1808 
1809 	for (x = start; x < end; x++) {
1810 
1811 		sum = 0;
1812 
1813 		/* compute sum of bandwidth */
1814 		for (z = x; z < end; z++) {
1815 			if (mask & (1U << (z - x)))
1816 				sum += ptr[z];
1817 		}
1818 
1819 		/* check if the current multi-slot is more optimal */
1820 		if (min >= sum) {
1821 			min = sum;
1822 			y = x;
1823 		}
1824 
1825 		/* check if the mask is about to be shifted out */
1826 		if (mask & (1U << (end - 1 - x)))
1827 			break;
1828 	}
1829 	return (y);
1830 }
1831 
1832 /*------------------------------------------------------------------------*
1833  *	usb_hs_bandwidth_adjust
1834  *
1835  * This function will update the bandwidth usage for the microframe
1836  * having index "slot" by "len" bytes. "len" can be negative.  If the
1837  * "slot" argument is greater or equal to "USB_HS_MICRO_FRAMES_MAX"
1838  * the "slot" argument will be replaced by the slot having least used
1839  * bandwidth. The "mask" argument is used for multi-slot allocations.
1840  *
1841  * Returns:
1842  *    The slot in which the bandwidth update was done: 0..7
1843  *------------------------------------------------------------------------*/
1844 static uint8_t
1845 usb_hs_bandwidth_adjust(struct usb_device *udev, int16_t len,
1846     uint8_t slot, uint8_t mask)
1847 {
1848 	struct usb_bus *bus = udev->bus;
1849 	struct usb_hub *hub;
1850 	enum usb_dev_speed speed;
1851 	uint8_t x;
1852 
1853 	USB_BUS_LOCK_ASSERT(bus, MA_OWNED);
1854 
1855 	speed = usbd_get_speed(udev);
1856 
1857 	switch (speed) {
1858 	case USB_SPEED_LOW:
1859 	case USB_SPEED_FULL:
1860 		if (speed == USB_SPEED_LOW) {
1861 			len *= 8;
1862 		}
1863 		/*
1864 	         * The Host Controller Driver should have
1865 	         * performed checks so that the lookup
1866 	         * below does not result in a NULL pointer
1867 	         * access.
1868 	         */
1869 
1870 		hub = udev->parent_hs_hub->hub;
1871 		if (slot >= USB_HS_MICRO_FRAMES_MAX) {
1872 			slot = usb_intr_find_best_slot(hub->uframe_usage,
1873 			    USB_FS_ISOC_UFRAME_MAX, 6, mask);
1874 		}
1875 		for (x = slot; x < 8; x++) {
1876 			if (mask & (1U << (x - slot))) {
1877 				hub->uframe_usage[x] += len;
1878 				bus->uframe_usage[x] += len;
1879 			}
1880 		}
1881 		break;
1882 	default:
1883 		if (slot >= USB_HS_MICRO_FRAMES_MAX) {
1884 			slot = usb_intr_find_best_slot(bus->uframe_usage, 0,
1885 			    USB_HS_MICRO_FRAMES_MAX, mask);
1886 		}
1887 		for (x = slot; x < 8; x++) {
1888 			if (mask & (1U << (x - slot))) {
1889 				bus->uframe_usage[x] += len;
1890 			}
1891 		}
1892 		break;
1893 	}
1894 	return (slot);
1895 }
1896 
1897 /*------------------------------------------------------------------------*
1898  *	usb_hs_bandwidth_alloc
1899  *
1900  * This function is a wrapper function for "usb_hs_bandwidth_adjust()".
1901  *------------------------------------------------------------------------*/
1902 void
1903 usb_hs_bandwidth_alloc(struct usb_xfer *xfer)
1904 {
1905 	struct usb_device *udev;
1906 	uint8_t slot;
1907 	uint8_t mask;
1908 	uint8_t speed;
1909 
1910 	udev = xfer->xroot->udev;
1911 
1912 	if (udev->flags.usb_mode != USB_MODE_HOST)
1913 		return;		/* not supported */
1914 
1915 	xfer->endpoint->refcount_bw++;
1916 	if (xfer->endpoint->refcount_bw != 1)
1917 		return;		/* already allocated */
1918 
1919 	speed = usbd_get_speed(udev);
1920 
1921 	switch (xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE) {
1922 	case UE_INTERRUPT:
1923 		/* allocate a microframe slot */
1924 
1925 		mask = 0x01;
1926 		slot = usb_hs_bandwidth_adjust(udev,
1927 		    xfer->max_frame_size, USB_HS_MICRO_FRAMES_MAX, mask);
1928 
1929 		xfer->endpoint->usb_uframe = slot;
1930 		xfer->endpoint->usb_smask = mask << slot;
1931 
1932 		if ((speed != USB_SPEED_FULL) &&
1933 		    (speed != USB_SPEED_LOW)) {
1934 			xfer->endpoint->usb_cmask = 0x00 ;
1935 		} else {
1936 			xfer->endpoint->usb_cmask = (-(0x04 << slot)) & 0xFE;
1937 		}
1938 		break;
1939 
1940 	case UE_ISOCHRONOUS:
1941 		switch (usbd_xfer_get_fps_shift(xfer)) {
1942 		case 0:
1943 			mask = 0xFF;
1944 			break;
1945 		case 1:
1946 			mask = 0x55;
1947 			break;
1948 		case 2:
1949 			mask = 0x11;
1950 			break;
1951 		default:
1952 			mask = 0x01;
1953 			break;
1954 		}
1955 
1956 		/* allocate a microframe multi-slot */
1957 
1958 		slot = usb_hs_bandwidth_adjust(udev,
1959 		    xfer->max_frame_size, USB_HS_MICRO_FRAMES_MAX, mask);
1960 
1961 		xfer->endpoint->usb_uframe = slot;
1962 		xfer->endpoint->usb_cmask = 0;
1963 		xfer->endpoint->usb_smask = mask << slot;
1964 		break;
1965 
1966 	default:
1967 		xfer->endpoint->usb_uframe = 0;
1968 		xfer->endpoint->usb_cmask = 0;
1969 		xfer->endpoint->usb_smask = 0;
1970 		break;
1971 	}
1972 
1973 	DPRINTFN(11, "slot=%d, mask=0x%02x\n",
1974 	    xfer->endpoint->usb_uframe,
1975 	    xfer->endpoint->usb_smask >> xfer->endpoint->usb_uframe);
1976 }
1977 
1978 /*------------------------------------------------------------------------*
1979  *	usb_hs_bandwidth_free
1980  *
1981  * This function is a wrapper function for "usb_hs_bandwidth_adjust()".
1982  *------------------------------------------------------------------------*/
1983 void
1984 usb_hs_bandwidth_free(struct usb_xfer *xfer)
1985 {
1986 	struct usb_device *udev;
1987 	uint8_t slot;
1988 	uint8_t mask;
1989 
1990 	udev = xfer->xroot->udev;
1991 
1992 	if (udev->flags.usb_mode != USB_MODE_HOST)
1993 		return;		/* not supported */
1994 
1995 	xfer->endpoint->refcount_bw--;
1996 	if (xfer->endpoint->refcount_bw != 0)
1997 		return;		/* still allocated */
1998 
1999 	switch (xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE) {
2000 	case UE_INTERRUPT:
2001 	case UE_ISOCHRONOUS:
2002 
2003 		slot = xfer->endpoint->usb_uframe;
2004 		mask = xfer->endpoint->usb_smask;
2005 
2006 		/* free microframe slot(s): */
2007 		usb_hs_bandwidth_adjust(udev,
2008 		    -xfer->max_frame_size, slot, mask >> slot);
2009 
2010 		DPRINTFN(11, "slot=%d, mask=0x%02x\n",
2011 		    slot, mask >> slot);
2012 
2013 		xfer->endpoint->usb_uframe = 0;
2014 		xfer->endpoint->usb_cmask = 0;
2015 		xfer->endpoint->usb_smask = 0;
2016 		break;
2017 
2018 	default:
2019 		break;
2020 	}
2021 }
2022 
2023 /*------------------------------------------------------------------------*
2024  *	usb_isoc_time_expand
2025  *
2026  * This function will expand the time counter from 7-bit to 16-bit.
2027  *
2028  * Returns:
2029  *   16-bit isochronous time counter.
2030  *------------------------------------------------------------------------*/
2031 uint16_t
2032 usb_isoc_time_expand(struct usb_bus *bus, uint16_t isoc_time_curr)
2033 {
2034 	uint16_t rem;
2035 
2036 	USB_BUS_LOCK_ASSERT(bus, MA_OWNED);
2037 
2038 	rem = bus->isoc_time_last & (USB_ISOC_TIME_MAX - 1);
2039 
2040 	isoc_time_curr &= (USB_ISOC_TIME_MAX - 1);
2041 
2042 	if (isoc_time_curr < rem) {
2043 		/* the time counter wrapped around */
2044 		bus->isoc_time_last += USB_ISOC_TIME_MAX;
2045 	}
2046 	/* update the remainder */
2047 
2048 	bus->isoc_time_last &= ~(USB_ISOC_TIME_MAX - 1);
2049 	bus->isoc_time_last |= isoc_time_curr;
2050 
2051 	return (bus->isoc_time_last);
2052 }
2053 
2054 /*------------------------------------------------------------------------*
2055  *	usbd_fs_isoc_schedule_alloc_slot
2056  *
2057  * This function will allocate bandwidth for an isochronous FULL speed
2058  * transaction in the FULL speed schedule.
2059  *
2060  * Returns:
2061  *    <8: Success
2062  * Else: Error
2063  *------------------------------------------------------------------------*/
2064 #if USB_HAVE_TT_SUPPORT
2065 uint8_t
2066 usbd_fs_isoc_schedule_alloc_slot(struct usb_xfer *isoc_xfer, uint16_t isoc_time)
2067 {
2068 	struct usb_xfer *xfer;
2069 	struct usb_xfer *pipe_xfer;
2070 	struct usb_bus *bus;
2071 	usb_frlength_t len;
2072 	usb_frlength_t data_len;
2073 	uint16_t delta;
2074 	uint16_t slot;
2075 	uint8_t retval;
2076 
2077 	data_len = 0;
2078 	slot = 0;
2079 
2080 	bus = isoc_xfer->xroot->bus;
2081 
2082 	TAILQ_FOREACH(xfer, &bus->intr_q.head, wait_entry) {
2083 
2084 		/* skip self, if any */
2085 
2086 		if (xfer == isoc_xfer)
2087 			continue;
2088 
2089 		/* check if this USB transfer is going through the same TT */
2090 
2091 		if (xfer->xroot->udev->parent_hs_hub !=
2092 		    isoc_xfer->xroot->udev->parent_hs_hub) {
2093 			continue;
2094 		}
2095 		if ((isoc_xfer->xroot->udev->parent_hs_hub->
2096 		    ddesc.bDeviceProtocol == UDPROTO_HSHUBMTT) &&
2097 		    (xfer->xroot->udev->hs_port_no !=
2098 		    isoc_xfer->xroot->udev->hs_port_no)) {
2099 			continue;
2100 		}
2101 		if (xfer->endpoint->methods != isoc_xfer->endpoint->methods)
2102 			continue;
2103 
2104 		/* check if isoc_time is part of this transfer */
2105 
2106 		delta = xfer->isoc_time_complete - isoc_time;
2107 		if (delta > 0 && delta <= xfer->nframes) {
2108 			delta = xfer->nframes - delta;
2109 
2110 			len = xfer->frlengths[delta];
2111 			len += 8;
2112 			len *= 7;
2113 			len /= 6;
2114 
2115 			data_len += len;
2116 		}
2117 
2118 		/*
2119 		 * Check double buffered transfers. Only stream ID
2120 		 * equal to zero is valid here!
2121 		 */
2122 		TAILQ_FOREACH(pipe_xfer, &xfer->endpoint->endpoint_q[0].head,
2123 		    wait_entry) {
2124 
2125 			/* skip self, if any */
2126 
2127 			if (pipe_xfer == isoc_xfer)
2128 				continue;
2129 
2130 			/* check if isoc_time is part of this transfer */
2131 
2132 			delta = pipe_xfer->isoc_time_complete - isoc_time;
2133 			if (delta > 0 && delta <= pipe_xfer->nframes) {
2134 				delta = pipe_xfer->nframes - delta;
2135 
2136 				len = pipe_xfer->frlengths[delta];
2137 				len += 8;
2138 				len *= 7;
2139 				len /= 6;
2140 
2141 				data_len += len;
2142 			}
2143 		}
2144 	}
2145 
2146 	while (data_len >= USB_FS_BYTES_PER_HS_UFRAME) {
2147 		data_len -= USB_FS_BYTES_PER_HS_UFRAME;
2148 		slot++;
2149 	}
2150 
2151 	/* check for overflow */
2152 
2153 	if (slot >= USB_FS_ISOC_UFRAME_MAX)
2154 		return (255);
2155 
2156 	retval = slot;
2157 
2158 	delta = isoc_xfer->isoc_time_complete - isoc_time;
2159 	if (delta > 0 && delta <= isoc_xfer->nframes) {
2160 		delta = isoc_xfer->nframes - delta;
2161 
2162 		len = isoc_xfer->frlengths[delta];
2163 		len += 8;
2164 		len *= 7;
2165 		len /= 6;
2166 
2167 		data_len += len;
2168 	}
2169 
2170 	while (data_len >= USB_FS_BYTES_PER_HS_UFRAME) {
2171 		data_len -= USB_FS_BYTES_PER_HS_UFRAME;
2172 		slot++;
2173 	}
2174 
2175 	/* check for overflow */
2176 
2177 	if (slot >= USB_FS_ISOC_UFRAME_MAX)
2178 		return (255);
2179 
2180 	return (retval);
2181 }
2182 #endif
2183 
2184 /*------------------------------------------------------------------------*
2185  *	usb_bus_port_get_device
2186  *
2187  * This function is NULL safe.
2188  *------------------------------------------------------------------------*/
2189 struct usb_device *
2190 usb_bus_port_get_device(struct usb_bus *bus, struct usb_port *up)
2191 {
2192 	if ((bus == NULL) || (up == NULL)) {
2193 		/* be NULL safe */
2194 		return (NULL);
2195 	}
2196 	if (up->device_index == 0) {
2197 		/* nothing to do */
2198 		return (NULL);
2199 	}
2200 	return (bus->devices[up->device_index]);
2201 }
2202 
2203 /*------------------------------------------------------------------------*
2204  *	usb_bus_port_set_device
2205  *
2206  * This function is NULL safe.
2207  *------------------------------------------------------------------------*/
2208 void
2209 usb_bus_port_set_device(struct usb_bus *bus, struct usb_port *up,
2210     struct usb_device *udev, uint8_t device_index)
2211 {
2212 	if (bus == NULL) {
2213 		/* be NULL safe */
2214 		return;
2215 	}
2216 	/*
2217 	 * There is only one case where we don't
2218 	 * have an USB port, and that is the Root Hub!
2219          */
2220 	if (up) {
2221 		if (udev) {
2222 			up->device_index = device_index;
2223 		} else {
2224 			device_index = up->device_index;
2225 			up->device_index = 0;
2226 		}
2227 	}
2228 	/*
2229 	 * Make relationships to our new device
2230 	 */
2231 	if (device_index != 0) {
2232 #if USB_HAVE_UGEN
2233 		mtx_lock(&usb_ref_lock);
2234 #endif
2235 		bus->devices[device_index] = udev;
2236 #if USB_HAVE_UGEN
2237 		mtx_unlock(&usb_ref_lock);
2238 #endif
2239 	}
2240 	/*
2241 	 * Debug print
2242 	 */
2243 	DPRINTFN(2, "bus %p devices[%u] = %p\n", bus, device_index, udev);
2244 }
2245 
2246 /*------------------------------------------------------------------------*
2247  *	usb_needs_explore
2248  *
2249  * This functions is called when the USB event thread needs to run.
2250  *------------------------------------------------------------------------*/
2251 void
2252 usb_needs_explore(struct usb_bus *bus, uint8_t do_probe)
2253 {
2254 	uint8_t do_unlock;
2255 
2256 	DPRINTF("\n");
2257 
2258 	if (cold != 0) {
2259 		DPRINTF("Cold\n");
2260 		return;
2261 	}
2262 
2263 	if (bus == NULL) {
2264 		DPRINTF("No bus pointer!\n");
2265 		return;
2266 	}
2267 	if ((bus->devices == NULL) ||
2268 	    (bus->devices[USB_ROOT_HUB_ADDR] == NULL)) {
2269 		DPRINTF("No root HUB\n");
2270 		return;
2271 	}
2272 	if (mtx_owned(&bus->bus_mtx)) {
2273 		do_unlock = 0;
2274 	} else {
2275 		USB_BUS_LOCK(bus);
2276 		do_unlock = 1;
2277 	}
2278 	if (do_probe) {
2279 		bus->do_probe = 1;
2280 	}
2281 	if (usb_proc_msignal(USB_BUS_EXPLORE_PROC(bus),
2282 	    &bus->explore_msg[0], &bus->explore_msg[1])) {
2283 		/* ignore */
2284 	}
2285 	if (do_unlock) {
2286 		USB_BUS_UNLOCK(bus);
2287 	}
2288 }
2289 
2290 /*------------------------------------------------------------------------*
2291  *	usb_needs_explore_all
2292  *
2293  * This function is called whenever a new driver is loaded and will
2294  * cause that all USB buses are re-explored.
2295  *------------------------------------------------------------------------*/
2296 void
2297 usb_needs_explore_all(void)
2298 {
2299 	struct usb_bus *bus;
2300 	devclass_t dc;
2301 	device_t dev;
2302 	int max;
2303 
2304 	DPRINTFN(3, "\n");
2305 
2306 	dc = usb_devclass_ptr;
2307 	if (dc == NULL) {
2308 		DPRINTFN(0, "no devclass\n");
2309 		return;
2310 	}
2311 	/*
2312 	 * Explore all USB buses in parallel.
2313 	 */
2314 	max = devclass_get_maxunit(dc);
2315 	while (max >= 0) {
2316 		dev = devclass_get_device(dc, max);
2317 		if (dev) {
2318 			bus = device_get_softc(dev);
2319 			if (bus) {
2320 				usb_needs_explore(bus, 1);
2321 			}
2322 		}
2323 		max--;
2324 	}
2325 }
2326 
2327 /*------------------------------------------------------------------------*
2328  *	usb_needs_explore_init
2329  *
2330  * This function will ensure that the USB controllers are not enumerated
2331  * until the "cold" variable is cleared.
2332  *------------------------------------------------------------------------*/
2333 static void
2334 usb_needs_explore_init(void *arg)
2335 {
2336 	/*
2337 	 * The cold variable should be cleared prior to this function
2338 	 * being called:
2339 	 */
2340 	if (cold == 0)
2341 		usb_needs_explore_all();
2342 	else
2343 		DPRINTFN(-1, "Cold variable is still set!\n");
2344 }
2345 SYSINIT(usb_needs_explore_init, SI_SUB_KICK_SCHEDULER, SI_ORDER_SECOND, usb_needs_explore_init, NULL);
2346 
2347 /*------------------------------------------------------------------------*
2348  *	usb_bus_power_update
2349  *
2350  * This function will ensure that all USB devices on the given bus are
2351  * properly suspended or resumed according to the device transfer
2352  * state.
2353  *------------------------------------------------------------------------*/
2354 #if USB_HAVE_POWERD
2355 void
2356 usb_bus_power_update(struct usb_bus *bus)
2357 {
2358 	usb_needs_explore(bus, 0 /* no probe */ );
2359 }
2360 #endif
2361 
2362 /*------------------------------------------------------------------------*
2363  *	usbd_transfer_power_ref
2364  *
2365  * This function will modify the power save reference counts and
2366  * wakeup the USB device associated with the given USB transfer, if
2367  * needed.
2368  *------------------------------------------------------------------------*/
2369 #if USB_HAVE_POWERD
2370 void
2371 usbd_transfer_power_ref(struct usb_xfer *xfer, int val)
2372 {
2373 	static const usb_power_mask_t power_mask[4] = {
2374 		[UE_CONTROL] = USB_HW_POWER_CONTROL,
2375 		[UE_BULK] = USB_HW_POWER_BULK,
2376 		[UE_INTERRUPT] = USB_HW_POWER_INTERRUPT,
2377 		[UE_ISOCHRONOUS] = USB_HW_POWER_ISOC,
2378 	};
2379 	struct usb_device *udev;
2380 	uint8_t needs_explore;
2381 	uint8_t needs_hw_power;
2382 	uint8_t xfer_type;
2383 
2384 	udev = xfer->xroot->udev;
2385 
2386 	if (udev->device_index == USB_ROOT_HUB_ADDR) {
2387 		/* no power save for root HUB */
2388 		return;
2389 	}
2390 	USB_BUS_LOCK(udev->bus);
2391 
2392 	xfer_type = xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE;
2393 
2394 	udev->pwr_save.last_xfer_time = ticks;
2395 	udev->pwr_save.type_refs[xfer_type] += val;
2396 
2397 	if (xfer->flags_int.control_xfr) {
2398 		udev->pwr_save.read_refs += val;
2399 		if (xfer->flags_int.usb_mode == USB_MODE_HOST) {
2400 			/*
2401 			 * It is not allowed to suspend during a
2402 			 * control transfer:
2403 			 */
2404 			udev->pwr_save.write_refs += val;
2405 		}
2406 	} else if (USB_GET_DATA_ISREAD(xfer)) {
2407 		udev->pwr_save.read_refs += val;
2408 	} else {
2409 		udev->pwr_save.write_refs += val;
2410 	}
2411 
2412 	if (val > 0) {
2413 		if (udev->flags.self_suspended)
2414 			needs_explore = usb_peer_should_wakeup(udev);
2415 		else
2416 			needs_explore = 0;
2417 
2418 		if (!(udev->bus->hw_power_state & power_mask[xfer_type])) {
2419 			DPRINTF("Adding type %u to power state\n", xfer_type);
2420 			udev->bus->hw_power_state |= power_mask[xfer_type];
2421 			needs_hw_power = 1;
2422 		} else {
2423 			needs_hw_power = 0;
2424 		}
2425 	} else {
2426 		needs_explore = 0;
2427 		needs_hw_power = 0;
2428 	}
2429 
2430 	USB_BUS_UNLOCK(udev->bus);
2431 
2432 	if (needs_explore) {
2433 		DPRINTF("update\n");
2434 		usb_bus_power_update(udev->bus);
2435 	} else if (needs_hw_power) {
2436 		DPRINTF("needs power\n");
2437 		if (udev->bus->methods->set_hw_power != NULL) {
2438 			(udev->bus->methods->set_hw_power) (udev->bus);
2439 		}
2440 	}
2441 }
2442 #endif
2443 
2444 /*------------------------------------------------------------------------*
2445  *	usb_peer_should_wakeup
2446  *
2447  * This function returns non-zero if the current device should wake up.
2448  *------------------------------------------------------------------------*/
2449 static uint8_t
2450 usb_peer_should_wakeup(struct usb_device *udev)
2451 {
2452 	return (((udev->power_mode == USB_POWER_MODE_ON) &&
2453 	    (udev->flags.usb_mode == USB_MODE_HOST)) ||
2454 	    (udev->driver_added_refcount != udev->bus->driver_added_refcount) ||
2455 	    (udev->re_enumerate_wait != USB_RE_ENUM_DONE) ||
2456 	    (udev->pwr_save.type_refs[UE_ISOCHRONOUS] != 0) ||
2457 	    (udev->pwr_save.write_refs != 0) ||
2458 	    ((udev->pwr_save.read_refs != 0) &&
2459 	    (udev->flags.usb_mode == USB_MODE_HOST) &&
2460 	    (usb_peer_can_wakeup(udev) == 0)));
2461 }
2462 
2463 /*------------------------------------------------------------------------*
2464  *	usb_bus_powerd
2465  *
2466  * This function implements the USB power daemon and is called
2467  * regularly from the USB explore thread.
2468  *------------------------------------------------------------------------*/
2469 #if USB_HAVE_POWERD
2470 void
2471 usb_bus_powerd(struct usb_bus *bus)
2472 {
2473 	struct usb_device *udev;
2474 	usb_ticks_t temp;
2475 	usb_ticks_t limit;
2476 	usb_ticks_t mintime;
2477 	usb_size_t type_refs[5];
2478 	uint8_t x;
2479 
2480 	limit = usb_power_timeout;
2481 	if (limit == 0)
2482 		limit = hz;
2483 	else if (limit > 255)
2484 		limit = 255 * hz;
2485 	else
2486 		limit = limit * hz;
2487 
2488 	DPRINTF("bus=%p\n", bus);
2489 
2490 	USB_BUS_LOCK(bus);
2491 
2492 	/*
2493 	 * The root HUB device is never suspended
2494 	 * and we simply skip it.
2495 	 */
2496 	for (x = USB_ROOT_HUB_ADDR + 1;
2497 	    x != bus->devices_max; x++) {
2498 
2499 		udev = bus->devices[x];
2500 		if (udev == NULL)
2501 			continue;
2502 
2503 		temp = ticks - udev->pwr_save.last_xfer_time;
2504 
2505 		if (usb_peer_should_wakeup(udev)) {
2506 			/* check if we are suspended */
2507 			if (udev->flags.self_suspended != 0) {
2508 				USB_BUS_UNLOCK(bus);
2509 				usb_dev_resume_peer(udev);
2510 				USB_BUS_LOCK(bus);
2511 			}
2512 		} else if ((temp >= limit) &&
2513 		    (udev->flags.usb_mode == USB_MODE_HOST) &&
2514 		    (udev->flags.self_suspended == 0)) {
2515 			/* try to do suspend */
2516 
2517 			USB_BUS_UNLOCK(bus);
2518 			usb_dev_suspend_peer(udev);
2519 			USB_BUS_LOCK(bus);
2520 		}
2521 	}
2522 
2523 	/* reset counters */
2524 
2525 	mintime = (usb_ticks_t)-1;
2526 	type_refs[0] = 0;
2527 	type_refs[1] = 0;
2528 	type_refs[2] = 0;
2529 	type_refs[3] = 0;
2530 	type_refs[4] = 0;
2531 
2532 	/* Re-loop all the devices to get the actual state */
2533 
2534 	for (x = USB_ROOT_HUB_ADDR + 1;
2535 	    x != bus->devices_max; x++) {
2536 
2537 		udev = bus->devices[x];
2538 		if (udev == NULL)
2539 			continue;
2540 
2541 		/* we found a non-Root-Hub USB device */
2542 		type_refs[4] += 1;
2543 
2544 		/* "last_xfer_time" can be updated by a resume */
2545 		temp = ticks - udev->pwr_save.last_xfer_time;
2546 
2547 		/*
2548 		 * Compute minimum time since last transfer for the complete
2549 		 * bus:
2550 		 */
2551 		if (temp < mintime)
2552 			mintime = temp;
2553 
2554 		if (udev->flags.self_suspended == 0) {
2555 			type_refs[0] += udev->pwr_save.type_refs[0];
2556 			type_refs[1] += udev->pwr_save.type_refs[1];
2557 			type_refs[2] += udev->pwr_save.type_refs[2];
2558 			type_refs[3] += udev->pwr_save.type_refs[3];
2559 		}
2560 	}
2561 
2562 	if (mintime >= (usb_ticks_t)(1 * hz)) {
2563 		/* recompute power masks */
2564 		DPRINTF("Recomputing power masks\n");
2565 		bus->hw_power_state = 0;
2566 		if (type_refs[UE_CONTROL] != 0)
2567 			bus->hw_power_state |= USB_HW_POWER_CONTROL;
2568 		if (type_refs[UE_BULK] != 0)
2569 			bus->hw_power_state |= USB_HW_POWER_BULK;
2570 		if (type_refs[UE_INTERRUPT] != 0)
2571 			bus->hw_power_state |= USB_HW_POWER_INTERRUPT;
2572 		if (type_refs[UE_ISOCHRONOUS] != 0)
2573 			bus->hw_power_state |= USB_HW_POWER_ISOC;
2574 		if (type_refs[4] != 0)
2575 			bus->hw_power_state |= USB_HW_POWER_NON_ROOT_HUB;
2576 	}
2577 	USB_BUS_UNLOCK(bus);
2578 
2579 	if (bus->methods->set_hw_power != NULL) {
2580 		/* always update hardware power! */
2581 		(bus->methods->set_hw_power) (bus);
2582 	}
2583 	return;
2584 }
2585 #endif
2586 
2587 static usb_error_t
2588 usbd_device_30_remote_wakeup(struct usb_device *udev, uint8_t bRequest)
2589 {
2590 	struct usb_device_request req = {};
2591 
2592 	req.bmRequestType = UT_WRITE_INTERFACE;
2593 	req.bRequest = bRequest;
2594 	USETW(req.wValue, USB_INTERFACE_FUNC_SUSPEND);
2595 	USETW(req.wIndex, USB_INTERFACE_FUNC_SUSPEND_LP |
2596 	    USB_INTERFACE_FUNC_SUSPEND_RW);
2597 
2598 	return (usbd_do_request(udev, NULL, &req, 0));
2599 }
2600 
2601 static usb_error_t
2602 usbd_clear_dev_wakeup(struct usb_device *udev)
2603 {
2604 	usb_error_t err;
2605 
2606 	if (usb_device_20_compatible(udev)) {
2607 		err = usbd_req_clear_device_feature(udev,
2608 		    NULL, UF_DEVICE_REMOTE_WAKEUP);
2609 	} else {
2610 		err = usbd_device_30_remote_wakeup(udev,
2611 		    UR_CLEAR_FEATURE);
2612 	}
2613 	return (err);
2614 }
2615 
2616 static usb_error_t
2617 usbd_set_dev_wakeup(struct usb_device *udev)
2618 {
2619 	usb_error_t err;
2620 
2621 	if (usb_device_20_compatible(udev)) {
2622 		err = usbd_req_set_device_feature(udev,
2623 		    NULL, UF_DEVICE_REMOTE_WAKEUP);
2624 	} else {
2625 		err = usbd_device_30_remote_wakeup(udev,
2626 		    UR_SET_FEATURE);
2627 	}
2628 	return (err);
2629 }
2630 
2631 /*------------------------------------------------------------------------*
2632  *	usb_dev_resume_peer
2633  *
2634  * This function will resume an USB peer and do the required USB
2635  * signalling to get an USB device out of the suspended state.
2636  *------------------------------------------------------------------------*/
2637 static void
2638 usb_dev_resume_peer(struct usb_device *udev)
2639 {
2640 	struct usb_bus *bus;
2641 	int err;
2642 
2643 	/* be NULL safe */
2644 	if (udev == NULL)
2645 		return;
2646 
2647 	/* check if already resumed */
2648 	if (udev->flags.self_suspended == 0)
2649 		return;
2650 
2651 	/* we need a parent HUB to do resume */
2652 	if (udev->parent_hub == NULL)
2653 		return;
2654 
2655 	DPRINTF("udev=%p\n", udev);
2656 
2657 	if ((udev->flags.usb_mode == USB_MODE_DEVICE) &&
2658 	    (udev->flags.remote_wakeup == 0)) {
2659 		/*
2660 		 * If the host did not set the remote wakeup feature, we can
2661 		 * not wake it up either!
2662 		 */
2663 		DPRINTF("remote wakeup is not set!\n");
2664 		return;
2665 	}
2666 	/* get bus pointer */
2667 	bus = udev->bus;
2668 
2669 	/* resume parent hub first */
2670 	usb_dev_resume_peer(udev->parent_hub);
2671 
2672 	/* reduce chance of instant resume failure by waiting a little bit */
2673 	usb_pause_mtx(NULL, USB_MS_TO_TICKS(20));
2674 
2675 	if (usb_device_20_compatible(udev)) {
2676 		/* resume current port (Valid in Host and Device Mode) */
2677 		err = usbd_req_clear_port_feature(udev->parent_hub,
2678 		    NULL, udev->port_no, UHF_PORT_SUSPEND);
2679 		if (err) {
2680 			DPRINTFN(0, "Resuming port failed\n");
2681 			return;
2682 		}
2683 	} else {
2684 		/* resume current port (Valid in Host and Device Mode) */
2685 		err = usbd_req_set_port_link_state(udev->parent_hub,
2686 		    NULL, udev->port_no, UPS_PORT_LS_U0);
2687 		if (err) {
2688 			DPRINTFN(0, "Resuming port failed\n");
2689 			return;
2690 		}
2691 	}
2692 
2693 	/* resume settle time */
2694 	usb_pause_mtx(NULL, USB_MS_TO_TICKS(usb_port_resume_delay));
2695 
2696 	if (bus->methods->device_resume != NULL) {
2697 		/* resume USB device on the USB controller */
2698 		(bus->methods->device_resume) (udev);
2699 	}
2700 	USB_BUS_LOCK(bus);
2701 	/* set that this device is now resumed */
2702 	udev->flags.self_suspended = 0;
2703 #if USB_HAVE_POWERD
2704 	/* make sure that we don't go into suspend right away */
2705 	udev->pwr_save.last_xfer_time = ticks;
2706 
2707 	/* make sure the needed power masks are on */
2708 	if (udev->pwr_save.type_refs[UE_CONTROL] != 0)
2709 		bus->hw_power_state |= USB_HW_POWER_CONTROL;
2710 	if (udev->pwr_save.type_refs[UE_BULK] != 0)
2711 		bus->hw_power_state |= USB_HW_POWER_BULK;
2712 	if (udev->pwr_save.type_refs[UE_INTERRUPT] != 0)
2713 		bus->hw_power_state |= USB_HW_POWER_INTERRUPT;
2714 	if (udev->pwr_save.type_refs[UE_ISOCHRONOUS] != 0)
2715 		bus->hw_power_state |= USB_HW_POWER_ISOC;
2716 #endif
2717 	USB_BUS_UNLOCK(bus);
2718 
2719 	if (bus->methods->set_hw_power != NULL) {
2720 		/* always update hardware power! */
2721 		(bus->methods->set_hw_power) (bus);
2722 	}
2723 
2724 	usbd_sr_lock(udev);
2725 
2726 	/* notify all sub-devices about resume */
2727 	err = usb_suspend_resume(udev, 0);
2728 
2729 	usbd_sr_unlock(udev);
2730 
2731 	/* check if peer has wakeup capability */
2732 	if (usb_peer_can_wakeup(udev)) {
2733 		/* clear remote wakeup */
2734 		err = usbd_clear_dev_wakeup(udev);
2735 		if (err) {
2736 			DPRINTFN(0, "Clearing device "
2737 			    "remote wakeup failed: %s\n",
2738 			    usbd_errstr(err));
2739 		}
2740 	}
2741 }
2742 
2743 /*------------------------------------------------------------------------*
2744  *	usb_dev_suspend_peer
2745  *
2746  * This function will suspend an USB peer and do the required USB
2747  * signalling to get an USB device into the suspended state.
2748  *------------------------------------------------------------------------*/
2749 static void
2750 usb_dev_suspend_peer(struct usb_device *udev)
2751 {
2752 	struct usb_device *child;
2753 	int err;
2754 	uint8_t x;
2755 	uint8_t nports;
2756 
2757 repeat:
2758 	/* be NULL safe */
2759 	if (udev == NULL)
2760 		return;
2761 
2762 	/* check if already suspended */
2763 	if (udev->flags.self_suspended)
2764 		return;
2765 
2766 	/* we need a parent HUB to do suspend */
2767 	if (udev->parent_hub == NULL)
2768 		return;
2769 
2770 	DPRINTF("udev=%p\n", udev);
2771 
2772 	/* check if the current device is a HUB */
2773 	if (udev->hub != NULL) {
2774 		nports = udev->hub->nports;
2775 
2776 		/* check if all devices on the HUB are suspended */
2777 		for (x = 0; x != nports; x++) {
2778 			child = usb_bus_port_get_device(udev->bus,
2779 			    udev->hub->ports + x);
2780 
2781 			if (child == NULL)
2782 				continue;
2783 
2784 			if (child->flags.self_suspended)
2785 				continue;
2786 
2787 			DPRINTFN(1, "Port %u is busy on the HUB!\n", x + 1);
2788 			return;
2789 		}
2790 	}
2791 
2792 	if (usb_peer_can_wakeup(udev)) {
2793 		/*
2794 		 * This request needs to be done before we set
2795 		 * "udev->flags.self_suspended":
2796 		 */
2797 
2798 		/* allow device to do remote wakeup */
2799 		err = usbd_set_dev_wakeup(udev);
2800 		if (err) {
2801 			DPRINTFN(0, "Setting device "
2802 			    "remote wakeup failed\n");
2803 		}
2804 	}
2805 
2806 	USB_BUS_LOCK(udev->bus);
2807 	/*
2808 	 * Checking for suspend condition and setting suspended bit
2809 	 * must be atomic!
2810 	 */
2811 	err = usb_peer_should_wakeup(udev);
2812 	if (err == 0) {
2813 		/*
2814 		 * Set that this device is suspended. This variable
2815 		 * must be set before calling USB controller suspend
2816 		 * callbacks.
2817 		 */
2818 		udev->flags.self_suspended = 1;
2819 	}
2820 	USB_BUS_UNLOCK(udev->bus);
2821 
2822 	if (err != 0) {
2823 		if (usb_peer_can_wakeup(udev)) {
2824 			/* allow device to do remote wakeup */
2825 			err = usbd_clear_dev_wakeup(udev);
2826 			if (err) {
2827 				DPRINTFN(0, "Setting device "
2828 				    "remote wakeup failed\n");
2829 			}
2830 		}
2831 
2832 		if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2833 			/* resume parent HUB first */
2834 			usb_dev_resume_peer(udev->parent_hub);
2835 
2836 			/* reduce chance of instant resume failure by waiting a little bit */
2837 			usb_pause_mtx(NULL, USB_MS_TO_TICKS(20));
2838 
2839 			/* resume current port (Valid in Host and Device Mode) */
2840 			err = usbd_req_clear_port_feature(udev->parent_hub,
2841 			    NULL, udev->port_no, UHF_PORT_SUSPEND);
2842 
2843 			/* resume settle time */
2844 			usb_pause_mtx(NULL, USB_MS_TO_TICKS(usb_port_resume_delay));
2845 		}
2846 		DPRINTF("Suspend was cancelled!\n");
2847 		return;
2848 	}
2849 
2850 	usbd_sr_lock(udev);
2851 
2852 	/* notify all sub-devices about suspend */
2853 	err = usb_suspend_resume(udev, 1);
2854 
2855 	usbd_sr_unlock(udev);
2856 
2857 	if (udev->bus->methods->device_suspend != NULL) {
2858 		usb_timeout_t temp;
2859 
2860 		/* suspend device on the USB controller */
2861 		(udev->bus->methods->device_suspend) (udev);
2862 
2863 		/* do DMA delay */
2864 		temp = usbd_get_dma_delay(udev);
2865 		if (temp != 0)
2866 			usb_pause_mtx(NULL, USB_MS_TO_TICKS(temp));
2867 
2868 	}
2869 
2870 	if (usb_device_20_compatible(udev)) {
2871 		/* suspend current port */
2872 		err = usbd_req_set_port_feature(udev->parent_hub,
2873 		    NULL, udev->port_no, UHF_PORT_SUSPEND);
2874 		if (err) {
2875 			DPRINTFN(0, "Suspending port failed\n");
2876 			return;
2877 		}
2878 	} else {
2879 		/* suspend current port */
2880 		err = usbd_req_set_port_link_state(udev->parent_hub,
2881 		    NULL, udev->port_no, UPS_PORT_LS_U3);
2882 		if (err) {
2883 			DPRINTFN(0, "Suspending port failed\n");
2884 			return;
2885 		}
2886 	}
2887 
2888 	udev = udev->parent_hub;
2889 	goto repeat;
2890 }
2891 
2892 /*------------------------------------------------------------------------*
2893  *	usbd_set_power_mode
2894  *
2895  * This function will set the power mode, see USB_POWER_MODE_XXX for a
2896  * USB device.
2897  *------------------------------------------------------------------------*/
2898 void
2899 usbd_set_power_mode(struct usb_device *udev, uint8_t power_mode)
2900 {
2901 	/* filter input argument */
2902 	if ((power_mode != USB_POWER_MODE_ON) &&
2903 	    (power_mode != USB_POWER_MODE_OFF))
2904 		power_mode = USB_POWER_MODE_SAVE;
2905 
2906 	power_mode = usbd_filter_power_mode(udev, power_mode);
2907 
2908 	udev->power_mode = power_mode;	/* update copy of power mode */
2909 
2910 #if USB_HAVE_POWERD
2911 	usb_bus_power_update(udev->bus);
2912 #else
2913 	usb_needs_explore(udev->bus, 0 /* no probe */ );
2914 #endif
2915 }
2916 
2917 /*------------------------------------------------------------------------*
2918  *	usbd_filter_power_mode
2919  *
2920  * This function filters the power mode based on hardware requirements.
2921  *------------------------------------------------------------------------*/
2922 uint8_t
2923 usbd_filter_power_mode(struct usb_device *udev, uint8_t power_mode)
2924 {
2925 	const struct usb_bus_methods *mtod;
2926 	int8_t temp;
2927 
2928 	mtod = udev->bus->methods;
2929 	temp = -1;
2930 
2931 	if (mtod->get_power_mode != NULL)
2932 		(mtod->get_power_mode) (udev, &temp);
2933 
2934 	/* check if we should not filter */
2935 	if (temp < 0)
2936 		return (power_mode);
2937 
2938 	/* use fixed power mode given by hardware driver */
2939 	return (temp);
2940 }
2941 
2942 /*------------------------------------------------------------------------*
2943  *	usbd_start_re_enumerate
2944  *
2945  * This function starts re-enumeration of the given USB device. This
2946  * function does not need to be called BUS-locked. This function does
2947  * not wait until the re-enumeration is completed.
2948  *------------------------------------------------------------------------*/
2949 void
2950 usbd_start_re_enumerate(struct usb_device *udev)
2951 {
2952 	if (udev->re_enumerate_wait == USB_RE_ENUM_DONE) {
2953 		udev->re_enumerate_wait = USB_RE_ENUM_START;
2954 		usb_needs_explore(udev->bus, 0);
2955 	}
2956 }
2957 
2958 /*-----------------------------------------------------------------------*
2959  *	usbd_start_set_config
2960  *
2961  * This function starts setting a USB configuration. This function
2962  * does not need to be called BUS-locked. This function does not wait
2963  * until the set USB configuratino is completed.
2964  *------------------------------------------------------------------------*/
2965 usb_error_t
2966 usbd_start_set_config(struct usb_device *udev, uint8_t index)
2967 {
2968 	if (udev->re_enumerate_wait == USB_RE_ENUM_DONE) {
2969 		if (udev->curr_config_index == index) {
2970 			/* no change needed */
2971 			return (0);
2972 		}
2973 		udev->next_config_index = index;
2974 		udev->re_enumerate_wait = USB_RE_ENUM_SET_CONFIG;
2975 		usb_needs_explore(udev->bus, 0);
2976 		return (0);
2977 	} else if (udev->re_enumerate_wait == USB_RE_ENUM_SET_CONFIG) {
2978 		if (udev->next_config_index == index) {
2979 			/* no change needed */
2980 			return (0);
2981 		}
2982 	}
2983 	return (USB_ERR_PENDING_REQUESTS);
2984 }
2985