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