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