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