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