kernel: Remove <sys/mutex.h> from all files that don't need it (2/2).
[dragonfly.git] / sys / bus / u4b / usb_hub.c
blob804b3b1d84435eaa3e257c28614ecf7407cbc247
1 /* $FreeBSD: head/sys/dev/usb/usb_hub.c 276701 2015-01-05 15:04:17Z hselasky $ */
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.
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.
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.
30 * USB spec: http://www.usb.org/developers/docs/usbspec.zip
33 #include <sys/stdint.h>
34 #include <sys/param.h>
35 #include <sys/queue.h>
36 #include <sys/types.h>
37 #include <sys/systm.h>
38 #include <sys/kernel.h>
39 #include <sys/bus.h>
40 #include <sys/module.h>
41 #include <sys/lock.h>
42 #include <sys/condvar.h>
43 #include <sys/sysctl.h>
44 #include <sys/unistd.h>
45 #include <sys/callout.h>
46 #include <sys/malloc.h>
47 #include <sys/priv.h>
49 #include <bus/u4b/usb.h>
50 #include <bus/u4b/usb_ioctl.h>
51 #include <bus/u4b/usbdi.h>
52 #include <bus/u4b/usbdi_util.h>
54 #define USB_DEBUG_VAR uhub_debug
56 #include <bus/u4b/usb_core.h>
57 #include <bus/u4b/usb_process.h>
58 #include <bus/u4b/usb_device.h>
59 #include <bus/u4b/usb_request.h>
60 #include <bus/u4b/usb_debug.h>
61 #include <bus/u4b/usb_hub.h>
62 #include <bus/u4b/usb_util.h>
63 #include <bus/u4b/usb_busdma.h>
64 #include <bus/u4b/usb_transfer.h>
65 #include <bus/u4b/usb_dynamic.h>
67 #include <bus/u4b/usb_controller.h>
68 #include <bus/u4b/usb_bus.h>
70 #define UHUB_INTR_INTERVAL 250 /* ms */
71 enum {
72 UHUB_INTR_TRANSFER,
73 #if USB_HAVE_TT_SUPPORT
74 UHUB_RESET_TT_TRANSFER,
75 #endif
76 UHUB_N_TRANSFER,
79 #ifdef USB_DEBUG
80 static int uhub_debug = 0;
82 static SYSCTL_NODE(_hw_usb, OID_AUTO, uhub, CTLFLAG_RW, 0, "USB HUB");
83 SYSCTL_INT(_hw_usb_uhub, OID_AUTO, debug, CTLFLAG_RW, &uhub_debug, 0,
84 "Debug level");
86 TUNABLE_INT("hw.usb.uhub.debug", &uhub_debug);
87 #endif
89 #if USB_HAVE_POWERD
90 static int usb_power_timeout = 30; /* seconds */
92 SYSCTL_INT(_hw_usb, OID_AUTO, power_timeout, CTLFLAG_RW,
93 &usb_power_timeout, 0, "USB power timeout");
94 TUNABLE_INT("hw.usb.power_timeout", &usb_power_timeout);
95 #endif
97 #if USB_HAVE_DISABLE_ENUM
98 static int usb_disable_enumeration = 0;
99 SYSCTL_INT(_hw_usb, OID_AUTO, disable_enumeration, CTLFLAG_RW,
100 &usb_disable_enumeration, 0, "Set to disable all USB device enumeration.");
101 TUNABLE_INT("hw.usb.disable_enumeration", &usb_disable_enumeration);
103 static int usb_disable_port_power = 0;
104 SYSCTL_INT(_hw_usb, OID_AUTO, disable_port_power, CTLFLAG_RW,
105 &usb_disable_port_power, 0, "Set to disable all USB port power.");
106 TUNABLE_INT("hw.usb.disable_port_power", &usb_disable_port_power);
107 #endif
109 struct uhub_current_state {
110 uint16_t port_change;
111 uint16_t port_status;
114 struct uhub_softc {
115 struct uhub_current_state sc_st;/* current state */
116 #if (USB_HAVE_FIXED_PORT != 0)
117 struct usb_hub sc_hub;
118 #endif
119 device_t sc_dev; /* base device */
120 struct lock sc_lock; /* our mutex */
121 struct usb_device *sc_udev; /* USB device */
122 struct usb_xfer *sc_xfer[UHUB_N_TRANSFER]; /* interrupt xfer */
123 #if USB_HAVE_DISABLE_ENUM
124 int sc_disable_enumeration;
125 int sc_disable_port_power;
126 #endif
127 uint8_t sc_flags;
128 #define UHUB_FLAG_DID_EXPLORE 0x01
131 #define UHUB_PROTO(sc) ((sc)->sc_udev->ddesc.bDeviceProtocol)
132 #define UHUB_IS_HIGH_SPEED(sc) (UHUB_PROTO(sc) != UDPROTO_FSHUB)
133 #define UHUB_IS_SINGLE_TT(sc) (UHUB_PROTO(sc) == UDPROTO_HSHUBSTT)
134 #define UHUB_IS_MULTI_TT(sc) (UHUB_PROTO(sc) == UDPROTO_HSHUBMTT)
135 #define UHUB_IS_SUPER_SPEED(sc) (UHUB_PROTO(sc) == UDPROTO_SSHUB)
137 /* prototypes for type checking: */
139 static device_probe_t uhub_probe;
140 static device_attach_t uhub_attach;
141 static device_detach_t uhub_detach;
142 static device_suspend_t uhub_suspend;
143 static device_resume_t uhub_resume;
145 static bus_driver_added_t uhub_driver_added;
146 static bus_child_location_str_t uhub_child_location_string;
147 static bus_child_pnpinfo_str_t uhub_child_pnpinfo_string;
149 static usb_callback_t uhub_intr_callback;
150 #if USB_HAVE_TT_SUPPORT
151 static usb_callback_t uhub_reset_tt_callback;
152 #endif
154 static void usb_dev_resume_peer(struct usb_device *udev);
155 static void usb_dev_suspend_peer(struct usb_device *udev);
156 static uint8_t usb_peer_should_wakeup(struct usb_device *udev);
158 static const struct usb_config uhub_config[UHUB_N_TRANSFER] = {
160 [UHUB_INTR_TRANSFER] = {
161 .type = UE_INTERRUPT,
162 .endpoint = UE_ADDR_ANY,
163 .direction = UE_DIR_ANY,
164 .timeout = 0,
165 .flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
166 .bufsize = 0, /* use wMaxPacketSize */
167 .callback = &uhub_intr_callback,
168 .interval = UHUB_INTR_INTERVAL,
170 #if USB_HAVE_TT_SUPPORT
171 [UHUB_RESET_TT_TRANSFER] = {
172 .type = UE_CONTROL,
173 .endpoint = 0x00, /* Control pipe */
174 .direction = UE_DIR_ANY,
175 .bufsize = sizeof(struct usb_device_request),
176 .callback = &uhub_reset_tt_callback,
177 .timeout = 1000, /* 1 second */
178 .usb_mode = USB_MODE_HOST,
180 #endif
184 * driver instance for "hub" connected to "usb"
185 * and "hub" connected to "hub"
187 static devclass_t uhub_devclass;
189 static device_method_t uhub_methods[] = {
190 DEVMETHOD(device_probe, uhub_probe),
191 DEVMETHOD(device_attach, uhub_attach),
192 DEVMETHOD(device_detach, uhub_detach),
194 DEVMETHOD(device_suspend, uhub_suspend),
195 DEVMETHOD(device_resume, uhub_resume),
197 DEVMETHOD(bus_child_location_str, uhub_child_location_string),
198 DEVMETHOD(bus_child_pnpinfo_str, uhub_child_pnpinfo_string),
199 DEVMETHOD(bus_driver_added, uhub_driver_added),
200 DEVMETHOD_END
203 static driver_t uhub_driver = {
204 .name = "uhub",
205 .methods = uhub_methods,
206 .size = sizeof(struct uhub_softc)
209 DRIVER_MODULE(uhub, usbus, uhub_driver, uhub_devclass, NULL, NULL);
210 DRIVER_MODULE(uhub, uhub, uhub_driver, uhub_devclass, NULL, NULL);
211 MODULE_VERSION(uhub, 1);
213 static void
214 uhub_intr_callback(struct usb_xfer *xfer, usb_error_t error)
216 struct uhub_softc *sc = usbd_xfer_softc(xfer);
218 switch (USB_GET_STATE(xfer)) {
219 case USB_ST_TRANSFERRED:
220 DPRINTFN(2, "\n");
222 * This is an indication that some port
223 * has changed status. Notify the bus
224 * event handler thread that we need
225 * to be explored again:
227 usb_needs_explore(sc->sc_udev->bus, 0);
229 case USB_ST_SETUP:
230 usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
231 usbd_transfer_submit(xfer);
232 break;
234 default: /* Error */
235 if (xfer->error != USB_ERR_CANCELLED) {
237 * Do a clear-stall. The "stall_pipe" flag
238 * will get cleared before next callback by
239 * the USB stack.
241 usbd_xfer_set_stall(xfer);
242 usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
243 usbd_transfer_submit(xfer);
245 break;
249 /*------------------------------------------------------------------------*
250 * uhub_reset_tt_proc
252 * This function starts the TT reset USB request
253 *------------------------------------------------------------------------*/
254 #if USB_HAVE_TT_SUPPORT
255 static void
256 uhub_reset_tt_proc(struct usb_proc_msg *_pm)
258 struct usb_udev_msg *pm = (void *)_pm;
259 struct usb_device *udev = pm->udev;
260 struct usb_hub *hub;
261 struct uhub_softc *sc;
263 hub = udev->hub;
264 if (hub == NULL)
265 return;
266 sc = hub->hubsoftc;
267 if (sc == NULL)
268 return;
270 /* Change lock */
271 USB_BUS_UNLOCK(udev->bus);
272 lockmgr(&sc->sc_lock, LK_EXCLUSIVE);
273 /* Start transfer */
274 usbd_transfer_start(sc->sc_xfer[UHUB_RESET_TT_TRANSFER]);
275 /* Change lock */
276 lockmgr(&sc->sc_lock, LK_RELEASE);
277 USB_BUS_LOCK(udev->bus);
279 #endif
281 /*------------------------------------------------------------------------*
282 * uhub_tt_buffer_reset_async_locked
284 * This function queues a TT reset for the given USB device and endpoint.
285 *------------------------------------------------------------------------*/
286 #if USB_HAVE_TT_SUPPORT
287 void
288 uhub_tt_buffer_reset_async_locked(struct usb_device *child, struct usb_endpoint *ep)
290 struct usb_device_request req;
291 struct usb_device *udev;
292 struct usb_hub *hub;
293 struct usb_port *up;
294 uint16_t wValue;
295 uint8_t port;
297 if (child == NULL || ep == NULL)
298 return;
300 udev = child->parent_hs_hub;
301 port = child->hs_port_no;
303 if (udev == NULL)
304 return;
306 hub = udev->hub;
307 if ((hub == NULL) ||
308 (udev->speed != USB_SPEED_HIGH) ||
309 (child->speed != USB_SPEED_LOW &&
310 child->speed != USB_SPEED_FULL) ||
311 (child->flags.usb_mode != USB_MODE_HOST) ||
312 (port == 0) || (ep->edesc == NULL)) {
313 /* not applicable */
314 return;
317 USB_BUS_LOCK_ASSERT(udev->bus);
319 up = hub->ports + port - 1;
321 if (udev->ddesc.bDeviceClass == UDCLASS_HUB &&
322 udev->ddesc.bDeviceProtocol == UDPROTO_HSHUBSTT)
323 port = 1;
325 /* if we already received a clear buffer request, reset the whole TT */
326 if (up->req_reset_tt.bRequest != 0) {
327 req.bmRequestType = UT_WRITE_CLASS_OTHER;
328 req.bRequest = UR_RESET_TT;
329 USETW(req.wValue, 0);
330 req.wIndex[0] = port;
331 req.wIndex[1] = 0;
332 USETW(req.wLength, 0);
333 } else {
334 wValue = (ep->edesc->bEndpointAddress & 0xF) |
335 ((child->address & 0x7F) << 4) |
336 ((ep->edesc->bEndpointAddress & 0x80) << 8) |
337 ((ep->edesc->bmAttributes & 3) << 12);
339 req.bmRequestType = UT_WRITE_CLASS_OTHER;
340 req.bRequest = UR_CLEAR_TT_BUFFER;
341 USETW(req.wValue, wValue);
342 req.wIndex[0] = port;
343 req.wIndex[1] = 0;
344 USETW(req.wLength, 0);
346 up->req_reset_tt = req;
347 /* get reset transfer started */
348 usb_proc_msignal(USB_BUS_NON_GIANT_PROC(udev->bus),
349 &hub->tt_msg[0], &hub->tt_msg[1]);
351 #endif
353 #if USB_HAVE_TT_SUPPORT
354 static void
355 uhub_reset_tt_callback(struct usb_xfer *xfer, usb_error_t error)
357 struct uhub_softc *sc;
358 struct usb_device *udev;
359 struct usb_port *up;
360 uint8_t x;
362 DPRINTF("TT buffer reset\n");
364 sc = usbd_xfer_softc(xfer);
365 udev = sc->sc_udev;
367 switch (USB_GET_STATE(xfer)) {
368 case USB_ST_TRANSFERRED:
369 case USB_ST_SETUP:
370 tr_setup:
371 USB_BUS_LOCK(udev->bus);
372 /* find first port which needs a TT reset */
373 for (x = 0; x != udev->hub->nports; x++) {
374 up = udev->hub->ports + x;
376 if (up->req_reset_tt.bRequest == 0)
377 continue;
379 /* copy in the transfer */
380 usbd_copy_in(xfer->frbuffers, 0, &up->req_reset_tt,
381 sizeof(up->req_reset_tt));
382 /* reset buffer */
383 memset(&up->req_reset_tt, 0, sizeof(up->req_reset_tt));
385 /* set length */
386 usbd_xfer_set_frame_len(xfer, 0, sizeof(up->req_reset_tt));
387 xfer->nframes = 1;
388 USB_BUS_UNLOCK(udev->bus);
390 usbd_transfer_submit(xfer);
391 return;
393 USB_BUS_UNLOCK(udev->bus);
394 break;
396 default:
397 if (error == USB_ERR_CANCELLED)
398 break;
400 DPRINTF("TT buffer reset failed (%s)\n", usbd_errstr(error));
401 goto tr_setup;
404 #endif
406 /*------------------------------------------------------------------------*
407 * uhub_count_active_host_ports
409 * This function counts the number of active ports at the given speed.
410 *------------------------------------------------------------------------*/
411 uint8_t
412 uhub_count_active_host_ports(struct usb_device *udev, enum usb_dev_speed speed)
414 struct uhub_softc *sc;
415 struct usb_device *child;
416 struct usb_hub *hub;
417 struct usb_port *up;
418 uint8_t retval = 0;
419 uint8_t x;
421 if (udev == NULL)
422 goto done;
423 hub = udev->hub;
424 if (hub == NULL)
425 goto done;
426 sc = hub->hubsoftc;
427 if (sc == NULL)
428 goto done;
430 for (x = 0; x != hub->nports; x++) {
431 up = hub->ports + x;
432 child = usb_bus_port_get_device(udev->bus, up);
433 if (child != NULL &&
434 child->flags.usb_mode == USB_MODE_HOST &&
435 child->speed == speed)
436 retval++;
438 done:
439 return (retval);
442 void
443 uhub_explore_handle_re_enumerate(struct usb_device *child)
445 uint8_t do_unlock;
446 usb_error_t err;
448 /* check if device should be re-enumerated */
449 if (child->flags.usb_mode != USB_MODE_HOST)
450 return;
452 do_unlock = usbd_enum_lock(child);
453 switch (child->re_enumerate_wait) {
454 case USB_RE_ENUM_START:
455 err = usbd_set_config_index(child,
456 USB_UNCONFIG_INDEX);
457 if (err != 0) {
458 DPRINTF("Unconfigure failed: %s: Ignored.\n",
459 usbd_errstr(err));
461 if (child->parent_hub == NULL) {
462 /* the root HUB cannot be re-enumerated */
463 DPRINTFN(6, "cannot reset root HUB\n");
464 err = 0;
465 } else {
466 err = usbd_req_re_enumerate(child, NULL);
468 if (err == 0)
469 err = usbd_set_config_index(child, 0);
470 if (err == 0) {
471 err = usb_probe_and_attach(child,
472 USB_IFACE_INDEX_ANY);
474 child->re_enumerate_wait = USB_RE_ENUM_DONE;
475 break;
477 case USB_RE_ENUM_PWR_OFF:
478 /* get the device unconfigured */
479 err = usbd_set_config_index(child,
480 USB_UNCONFIG_INDEX);
481 if (err) {
482 DPRINTFN(0, "Could not unconfigure "
483 "device (ignored)\n");
485 if (child->parent_hub == NULL) {
486 /* the root HUB cannot be re-enumerated */
487 DPRINTFN(6, "cannot set port feature\n");
488 err = 0;
489 } else {
490 /* clear port enable */
491 err = usbd_req_clear_port_feature(child->parent_hub,
492 NULL, child->port_no, UHF_PORT_ENABLE);
493 if (err) {
494 DPRINTFN(0, "Could not disable port "
495 "(ignored)\n");
498 child->re_enumerate_wait = USB_RE_ENUM_DONE;
499 break;
501 case USB_RE_ENUM_SET_CONFIG:
502 err = usbd_set_config_index(child,
503 child->next_config_index);
504 if (err != 0) {
505 DPRINTF("Configure failed: %s: Ignored.\n",
506 usbd_errstr(err));
507 } else {
508 err = usb_probe_and_attach(child,
509 USB_IFACE_INDEX_ANY);
511 child->re_enumerate_wait = USB_RE_ENUM_DONE;
512 break;
514 default:
515 child->re_enumerate_wait = USB_RE_ENUM_DONE;
516 break;
518 if (do_unlock)
519 usbd_enum_unlock(child);
522 /*------------------------------------------------------------------------*
523 * uhub_explore_sub - subroutine
525 * Return values:
526 * 0: Success
527 * Else: A control transaction failed
528 *------------------------------------------------------------------------*/
529 static usb_error_t
530 uhub_explore_sub(struct uhub_softc *sc, struct usb_port *up)
532 struct usb_bus *bus;
533 struct usb_device *child;
534 uint8_t refcount;
535 usb_error_t err;
537 bus = sc->sc_udev->bus;
538 err = 0;
540 /* get driver added refcount from USB bus */
541 refcount = bus->driver_added_refcount;
543 /* get device assosiated with the given port */
544 child = usb_bus_port_get_device(bus, up);
545 if (child == NULL) {
546 /* nothing to do */
547 goto done;
550 uhub_explore_handle_re_enumerate(child);
552 /* check if probe and attach should be done */
554 if (child->driver_added_refcount != refcount) {
555 child->driver_added_refcount = refcount;
556 err = usb_probe_and_attach(child,
557 USB_IFACE_INDEX_ANY);
558 if (err) {
559 goto done;
562 /* start control transfer, if device mode */
564 if (child->flags.usb_mode == USB_MODE_DEVICE)
565 usbd_ctrl_transfer_setup(child);
567 /* if a HUB becomes present, do a recursive HUB explore */
569 if (child->hub)
570 err = (child->hub->explore) (child);
572 done:
573 return (err);
576 /*------------------------------------------------------------------------*
577 * uhub_read_port_status - factored out code
578 *------------------------------------------------------------------------*/
579 static usb_error_t
580 uhub_read_port_status(struct uhub_softc *sc, uint8_t portno)
582 struct usb_port_status ps;
583 usb_error_t err;
585 err = usbd_req_get_port_status(
586 sc->sc_udev, NULL, &ps, portno);
588 /* update status regardless of error */
590 sc->sc_st.port_status = UGETW(ps.wPortStatus);
591 sc->sc_st.port_change = UGETW(ps.wPortChange);
593 /* debugging print */
595 DPRINTFN(4, "port %d, wPortStatus=0x%04x, "
596 "wPortChange=0x%04x, err=%s\n",
597 portno, sc->sc_st.port_status,
598 sc->sc_st.port_change, usbd_errstr(err));
599 return (err);
602 /*------------------------------------------------------------------------*
603 * uhub_reattach_port
605 * Returns:
606 * 0: Success
607 * Else: A control transaction failed
608 *------------------------------------------------------------------------*/
609 static usb_error_t
610 uhub_reattach_port(struct uhub_softc *sc, uint8_t portno)
612 struct usb_device *child;
613 struct usb_device *udev;
614 enum usb_dev_speed speed;
615 enum usb_hc_mode mode;
616 usb_error_t err;
617 uint16_t power_mask;
618 uint8_t timeout;
620 DPRINTF("reattaching port %d\n", portno);
622 timeout = 0;
623 udev = sc->sc_udev;
624 child = usb_bus_port_get_device(udev->bus,
625 udev->hub->ports + portno - 1);
627 repeat:
629 /* first clear the port connection change bit */
631 err = usbd_req_clear_port_feature(udev, NULL,
632 portno, UHF_C_PORT_CONNECTION);
634 if (err) {
635 goto error;
637 /* check if there is a child */
639 if (child != NULL) {
641 * Free USB device and all subdevices, if any.
643 usb_free_device(child, 0);
644 child = NULL;
646 /* get fresh status */
648 err = uhub_read_port_status(sc, portno);
649 if (err)
650 goto error;
652 #if USB_HAVE_DISABLE_ENUM
653 /* check if we should skip enumeration from this USB HUB */
654 if (usb_disable_enumeration != 0 ||
655 sc->sc_disable_enumeration != 0) {
656 DPRINTF("Enumeration is disabled!\n");
657 goto error;
659 #endif
660 /* check if nothing is connected to the port */
662 if (!(sc->sc_st.port_status & UPS_CURRENT_CONNECT_STATUS)) {
663 goto error;
665 /* check if there is no power on the port and print a warning */
667 switch (udev->speed) {
668 case USB_SPEED_HIGH:
669 case USB_SPEED_FULL:
670 case USB_SPEED_LOW:
671 power_mask = UPS_PORT_POWER;
672 break;
673 case USB_SPEED_SUPER:
674 if (udev->parent_hub == NULL)
675 power_mask = UPS_PORT_POWER;
676 else
677 power_mask = UPS_PORT_POWER_SS;
678 break;
679 default:
680 power_mask = 0;
681 break;
683 if (!(sc->sc_st.port_status & power_mask)) {
684 DPRINTF("WARNING: strange, connected port %d "
685 "has no power\n", portno);
688 /* check if the device is in Host Mode */
690 if (!(sc->sc_st.port_status & UPS_PORT_MODE_DEVICE)) {
692 DPRINTF("Port %d is in Host Mode\n", portno);
694 if (sc->sc_st.port_status & UPS_SUSPEND) {
696 * NOTE: Should not get here in SuperSpeed
697 * mode, because the HUB should report this
698 * bit as zero.
700 DPRINTF("Port %d was still "
701 "suspended, clearing.\n", portno);
702 err = usbd_req_clear_port_feature(udev,
703 NULL, portno, UHF_PORT_SUSPEND);
706 /* USB Host Mode */
708 /* wait for maximum device power up time */
710 usb_pause_mtx(NULL,
711 USB_MS_TO_TICKS(usb_port_powerup_delay));
713 /* reset port, which implies enabling it */
715 err = usbd_req_reset_port(udev, NULL, portno);
717 if (err) {
718 DPRINTFN(0, "port %d reset "
719 "failed, error=%s\n",
720 portno, usbd_errstr(err));
721 goto error;
723 /* get port status again, it might have changed during reset */
725 err = uhub_read_port_status(sc, portno);
726 if (err) {
727 goto error;
729 /* check if something changed during port reset */
731 if ((sc->sc_st.port_change & UPS_C_CONNECT_STATUS) ||
732 (!(sc->sc_st.port_status & UPS_CURRENT_CONNECT_STATUS))) {
733 if (timeout) {
734 DPRINTFN(0, "giving up port reset "
735 "- device vanished\n");
736 goto error;
738 timeout = 1;
739 goto repeat;
741 } else {
742 DPRINTF("Port %d is in Device Mode\n", portno);
746 * Figure out the device speed
748 switch (udev->speed) {
749 case USB_SPEED_HIGH:
750 if (sc->sc_st.port_status & UPS_HIGH_SPEED)
751 speed = USB_SPEED_HIGH;
752 else if (sc->sc_st.port_status & UPS_LOW_SPEED)
753 speed = USB_SPEED_LOW;
754 else
755 speed = USB_SPEED_FULL;
756 break;
757 case USB_SPEED_FULL:
758 if (sc->sc_st.port_status & UPS_LOW_SPEED)
759 speed = USB_SPEED_LOW;
760 else
761 speed = USB_SPEED_FULL;
762 break;
763 case USB_SPEED_LOW:
764 speed = USB_SPEED_LOW;
765 break;
766 case USB_SPEED_SUPER:
767 if (udev->parent_hub == NULL) {
768 /* Root HUB - special case */
769 switch (sc->sc_st.port_status & UPS_OTHER_SPEED) {
770 case 0:
771 speed = USB_SPEED_FULL;
772 break;
773 case UPS_LOW_SPEED:
774 speed = USB_SPEED_LOW;
775 break;
776 case UPS_HIGH_SPEED:
777 speed = USB_SPEED_HIGH;
778 break;
779 default:
780 speed = USB_SPEED_SUPER;
781 break;
783 } else {
784 speed = USB_SPEED_SUPER;
786 break;
787 default:
788 /* same speed like parent */
789 speed = udev->speed;
790 break;
792 if (speed == USB_SPEED_SUPER) {
793 err = usbd_req_set_hub_u1_timeout(udev, NULL,
794 portno, 128 - (2 * udev->depth));
795 if (err) {
796 DPRINTFN(0, "port %d U1 timeout "
797 "failed, error=%s\n",
798 portno, usbd_errstr(err));
800 err = usbd_req_set_hub_u2_timeout(udev, NULL,
801 portno, 128 - (2 * udev->depth));
802 if (err) {
803 DPRINTFN(0, "port %d U2 timeout "
804 "failed, error=%s\n",
805 portno, usbd_errstr(err));
810 * Figure out the device mode
812 * NOTE: This part is currently FreeBSD specific.
814 if (udev->parent_hub != NULL) {
815 /* inherit mode from the parent HUB */
816 mode = udev->parent_hub->flags.usb_mode;
817 } else if (sc->sc_st.port_status & UPS_PORT_MODE_DEVICE)
818 mode = USB_MODE_DEVICE;
819 else
820 mode = USB_MODE_HOST;
822 /* need to create a new child */
823 child = usb_alloc_device(sc->sc_dev, udev->bus, udev,
824 udev->depth + 1, portno - 1, portno, speed, mode);
825 if (child == NULL) {
826 DPRINTFN(0, "could not allocate new device\n");
827 goto error;
829 return (0); /* success */
831 error:
832 if (child != NULL) {
834 * Free USB device and all subdevices, if any.
836 usb_free_device(child, 0);
837 child = NULL;
839 if (err == 0) {
840 if (sc->sc_st.port_status & UPS_PORT_ENABLED) {
841 err = usbd_req_clear_port_feature(
842 sc->sc_udev, NULL,
843 portno, UHF_PORT_ENABLE);
846 if (err) {
847 DPRINTFN(0, "device problem (%s), "
848 "disabling port %d\n", usbd_errstr(err), portno);
850 return (err);
853 /*------------------------------------------------------------------------*
854 * usb_device_20_compatible
856 * Returns:
857 * 0: HUB does not support suspend and resume
858 * Else: HUB supports suspend and resume
859 *------------------------------------------------------------------------*/
860 static uint8_t
861 usb_device_20_compatible(struct usb_device *udev)
863 if (udev == NULL)
864 return (0);
865 switch (udev->speed) {
866 case USB_SPEED_LOW:
867 case USB_SPEED_FULL:
868 case USB_SPEED_HIGH:
869 return (1);
870 default:
871 return (0);
875 /*------------------------------------------------------------------------*
876 * uhub_suspend_resume_port
878 * Returns:
879 * 0: Success
880 * Else: A control transaction failed
881 *------------------------------------------------------------------------*/
882 static usb_error_t
883 uhub_suspend_resume_port(struct uhub_softc *sc, uint8_t portno)
885 struct usb_device *child;
886 struct usb_device *udev;
887 uint8_t is_suspend;
888 usb_error_t err;
890 DPRINTF("port %d\n", portno);
892 udev = sc->sc_udev;
893 child = usb_bus_port_get_device(udev->bus,
894 udev->hub->ports + portno - 1);
896 /* first clear the port suspend change bit */
898 if (usb_device_20_compatible(udev)) {
899 err = usbd_req_clear_port_feature(udev, NULL,
900 portno, UHF_C_PORT_SUSPEND);
901 } else {
902 err = usbd_req_clear_port_feature(udev, NULL,
903 portno, UHF_C_PORT_LINK_STATE);
906 if (err) {
907 DPRINTF("clearing suspend failed.\n");
908 goto done;
910 /* get fresh status */
912 err = uhub_read_port_status(sc, portno);
913 if (err) {
914 DPRINTF("reading port status failed.\n");
915 goto done;
917 /* convert current state */
919 if (usb_device_20_compatible(udev)) {
920 if (sc->sc_st.port_status & UPS_SUSPEND) {
921 is_suspend = 1;
922 } else {
923 is_suspend = 0;
925 } else {
926 switch (UPS_PORT_LINK_STATE_GET(sc->sc_st.port_status)) {
927 case UPS_PORT_LS_U3:
928 is_suspend = 1;
929 break;
930 case UPS_PORT_LS_SS_INA:
931 usbd_req_warm_reset_port(udev, NULL, portno);
932 is_suspend = 0;
933 break;
934 default:
935 is_suspend = 0;
936 break;
940 DPRINTF("suspended=%u\n", is_suspend);
942 /* do the suspend or resume */
944 if (child) {
946 * This code handle two cases: 1) Host Mode - we can only
947 * receive resume here 2) Device Mode - we can receive
948 * suspend and resume here
950 if (is_suspend == 0)
951 usb_dev_resume_peer(child);
952 else if (child->flags.usb_mode == USB_MODE_DEVICE)
953 usb_dev_suspend_peer(child);
955 done:
956 return (err);
959 /*------------------------------------------------------------------------*
960 * uhub_root_interrupt
962 * This function is called when a Root HUB interrupt has
963 * happened. "ptr" and "len" makes up the Root HUB interrupt
964 * packet. This function is called having the "bus_mtx" locked.
965 *------------------------------------------------------------------------*/
966 void
967 uhub_root_intr(struct usb_bus *bus, const uint8_t *ptr, uint8_t len)
969 USB_BUS_LOCK_ASSERT(bus);
971 usb_needs_explore(bus, 0);
974 static uint8_t
975 uhub_is_too_deep(struct usb_device *udev)
977 switch (udev->speed) {
978 case USB_SPEED_FULL:
979 case USB_SPEED_LOW:
980 case USB_SPEED_HIGH:
981 if (udev->depth > USB_HUB_MAX_DEPTH)
982 return (1);
983 break;
984 case USB_SPEED_SUPER:
985 if (udev->depth > USB_SS_HUB_DEPTH_MAX)
986 return (1);
987 break;
988 default:
989 break;
991 return (0);
994 /*------------------------------------------------------------------------*
995 * uhub_explore
997 * Returns:
998 * 0: Success
999 * Else: Failure
1000 *------------------------------------------------------------------------*/
1001 static usb_error_t
1002 uhub_explore(struct usb_device *udev)
1004 struct usb_hub *hub;
1005 struct uhub_softc *sc;
1006 struct usb_port *up;
1007 usb_error_t err;
1008 uint8_t portno;
1009 uint8_t x;
1010 uint8_t do_unlock;
1012 hub = udev->hub;
1013 sc = hub->hubsoftc;
1015 DPRINTFN(11, "udev=%p addr=%d\n", udev, udev->address);
1017 /* ignore devices that are too deep */
1018 if (uhub_is_too_deep(udev))
1019 return (USB_ERR_TOO_DEEP);
1021 /* check if device is suspended */
1022 if (udev->flags.self_suspended) {
1023 /* need to wait until the child signals resume */
1024 DPRINTF("Device is suspended!\n");
1025 return (0);
1029 * Make sure we don't race against user-space applications
1030 * like LibUSB:
1032 do_unlock = usbd_enum_lock(udev);
1034 for (x = 0; x != hub->nports; x++) {
1035 up = hub->ports + x;
1036 portno = x + 1;
1038 err = uhub_read_port_status(sc, portno);
1039 if (err) {
1040 /* most likely the HUB is gone */
1041 break;
1043 if (sc->sc_st.port_change & UPS_C_OVERCURRENT_INDICATOR) {
1044 DPRINTF("Overcurrent on port %u.\n", portno);
1045 err = usbd_req_clear_port_feature(
1046 udev, NULL, portno, UHF_C_PORT_OVER_CURRENT);
1047 if (err) {
1048 /* most likely the HUB is gone */
1049 break;
1052 if (!(sc->sc_flags & UHUB_FLAG_DID_EXPLORE)) {
1054 * Fake a connect status change so that the
1055 * status gets checked initially!
1057 sc->sc_st.port_change |=
1058 UPS_C_CONNECT_STATUS;
1060 if (sc->sc_st.port_change & UPS_C_PORT_ENABLED) {
1061 err = usbd_req_clear_port_feature(
1062 udev, NULL, portno, UHF_C_PORT_ENABLE);
1063 if (err) {
1064 /* most likely the HUB is gone */
1065 break;
1067 if (sc->sc_st.port_change & UPS_C_CONNECT_STATUS) {
1069 * Ignore the port error if the device
1070 * has vanished !
1072 } else if (sc->sc_st.port_status & UPS_PORT_ENABLED) {
1073 DPRINTFN(0, "illegal enable change, "
1074 "port %d\n", portno);
1075 } else {
1077 if (up->restartcnt == USB_RESTART_MAX) {
1078 /* XXX could try another speed ? */
1079 DPRINTFN(0, "port error, giving up "
1080 "port %d\n", portno);
1081 } else {
1082 sc->sc_st.port_change |=
1083 UPS_C_CONNECT_STATUS;
1084 up->restartcnt++;
1088 if (sc->sc_st.port_change & UPS_C_CONNECT_STATUS) {
1089 err = uhub_reattach_port(sc, portno);
1090 if (err) {
1091 /* most likely the HUB is gone */
1092 break;
1095 if (sc->sc_st.port_change & (UPS_C_SUSPEND |
1096 UPS_C_PORT_LINK_STATE)) {
1097 err = uhub_suspend_resume_port(sc, portno);
1098 if (err) {
1099 /* most likely the HUB is gone */
1100 break;
1103 err = uhub_explore_sub(sc, up);
1104 if (err) {
1105 /* no device(s) present */
1106 continue;
1108 /* explore succeeded - reset restart counter */
1109 up->restartcnt = 0;
1112 if (do_unlock)
1113 usbd_enum_unlock(udev);
1115 /* initial status checked */
1116 sc->sc_flags |= UHUB_FLAG_DID_EXPLORE;
1118 /* return success */
1119 return (USB_ERR_NORMAL_COMPLETION);
1122 static int
1123 uhub_probe(device_t dev)
1125 struct usb_attach_arg *uaa = device_get_ivars(dev);
1127 if (uaa->usb_mode != USB_MODE_HOST)
1128 return (ENXIO);
1131 * The subclass for USB HUBs is currently ignored because it
1132 * is 0 for some and 1 for others.
1134 if (uaa->info.bConfigIndex == 0 &&
1135 uaa->info.bDeviceClass == UDCLASS_HUB)
1136 return (0);
1138 return (ENXIO);
1141 /* NOTE: The information returned by this function can be wrong. */
1142 usb_error_t
1143 uhub_query_info(struct usb_device *udev, uint8_t *pnports, uint8_t *ptt)
1145 struct usb_hub_descriptor hubdesc20;
1146 struct usb_hub_ss_descriptor hubdesc30;
1147 usb_error_t err;
1148 uint8_t nports;
1149 uint8_t tt;
1151 if (udev->ddesc.bDeviceClass != UDCLASS_HUB)
1152 return (USB_ERR_INVAL);
1154 nports = 0;
1155 tt = 0;
1157 switch (udev->speed) {
1158 case USB_SPEED_LOW:
1159 case USB_SPEED_FULL:
1160 case USB_SPEED_HIGH:
1161 /* assuming that there is one port */
1162 err = usbd_req_get_hub_descriptor(udev, NULL, &hubdesc20, 1);
1163 if (err) {
1164 DPRINTFN(0, "getting USB 2.0 HUB descriptor failed,"
1165 "error=%s\n", usbd_errstr(err));
1166 break;
1168 nports = hubdesc20.bNbrPorts;
1169 if (nports > 127)
1170 nports = 127;
1172 if (udev->speed == USB_SPEED_HIGH)
1173 tt = (UGETW(hubdesc20.wHubCharacteristics) >> 5) & 3;
1174 break;
1176 case USB_SPEED_SUPER:
1177 err = usbd_req_get_ss_hub_descriptor(udev, NULL, &hubdesc30, 1);
1178 if (err) {
1179 DPRINTFN(0, "Getting USB 3.0 HUB descriptor failed,"
1180 "error=%s\n", usbd_errstr(err));
1181 break;
1183 nports = hubdesc30.bNbrPorts;
1184 if (nports > 16)
1185 nports = 16;
1186 break;
1188 default:
1189 err = USB_ERR_INVAL;
1190 break;
1193 if (pnports != NULL)
1194 *pnports = nports;
1196 if (ptt != NULL)
1197 *ptt = tt;
1199 return (err);
1202 static int
1203 uhub_attach(device_t dev)
1205 struct uhub_softc *sc = device_get_softc(dev);
1206 struct usb_attach_arg *uaa = device_get_ivars(dev);
1207 struct usb_device *udev = uaa->device;
1208 struct usb_device *parent_hub = udev->parent_hub;
1209 struct usb_hub *hub;
1210 struct usb_hub_descriptor hubdesc20;
1211 struct usb_hub_ss_descriptor hubdesc30;
1212 #if USB_HAVE_DISABLE_ENUM
1213 struct sysctl_ctx_list *sysctl_ctx;
1214 struct sysctl_oid *sysctl_tree;
1215 #endif
1216 uint16_t pwrdly;
1217 uint16_t nports;
1218 uint8_t x;
1219 uint8_t portno;
1220 uint8_t removable;
1221 uint8_t iface_index;
1222 usb_error_t err;
1224 sc->sc_udev = udev;
1225 sc->sc_dev = dev;
1227 lockinit(&sc->sc_lock, "USB HUB mutex", 0, 0);
1229 device_set_usb_desc(dev);
1231 DPRINTFN(2, "depth=%d selfpowered=%d, parent=%p, "
1232 "parent->selfpowered=%d\n",
1233 udev->depth,
1234 udev->flags.self_powered,
1235 parent_hub,
1236 parent_hub ?
1237 parent_hub->flags.self_powered : 0);
1239 if (uhub_is_too_deep(udev)) {
1240 DPRINTFN(0, "HUB at depth %d, "
1241 "exceeds maximum. HUB ignored\n", (int)udev->depth);
1242 goto error;
1245 if (!udev->flags.self_powered && parent_hub &&
1246 !parent_hub->flags.self_powered) {
1247 DPRINTFN(0, "Bus powered HUB connected to "
1248 "bus powered HUB. HUB ignored\n");
1249 goto error;
1252 if (UHUB_IS_MULTI_TT(sc)) {
1253 err = usbd_set_alt_interface_index(udev, 0, 1);
1254 if (err) {
1255 device_printf(dev, "MTT could not be enabled\n");
1256 goto error;
1258 device_printf(dev, "MTT enabled\n");
1261 /* get HUB descriptor */
1263 DPRINTFN(2, "Getting HUB descriptor\n");
1265 switch (udev->speed) {
1266 case USB_SPEED_LOW:
1267 case USB_SPEED_FULL:
1268 case USB_SPEED_HIGH:
1269 /* assuming that there is one port */
1270 err = usbd_req_get_hub_descriptor(udev, NULL, &hubdesc20, 1);
1271 if (err) {
1272 DPRINTFN(0, "getting USB 2.0 HUB descriptor failed,"
1273 "error=%s\n", usbd_errstr(err));
1274 goto error;
1276 /* get number of ports */
1277 nports = hubdesc20.bNbrPorts;
1279 /* get power delay */
1280 pwrdly = ((hubdesc20.bPwrOn2PwrGood * UHD_PWRON_FACTOR) +
1281 usb_extra_power_up_time);
1283 /* get complete HUB descriptor */
1284 if (nports >= 8) {
1285 /* check number of ports */
1286 if (nports > 127) {
1287 DPRINTFN(0, "Invalid number of USB 2.0 ports,"
1288 "error=%s\n", usbd_errstr(err));
1289 goto error;
1291 /* get complete HUB descriptor */
1292 err = usbd_req_get_hub_descriptor(udev, NULL, &hubdesc20, nports);
1294 if (err) {
1295 DPRINTFN(0, "Getting USB 2.0 HUB descriptor failed,"
1296 "error=%s\n", usbd_errstr(err));
1297 goto error;
1299 if (hubdesc20.bNbrPorts != nports) {
1300 DPRINTFN(0, "Number of ports changed\n");
1301 goto error;
1304 break;
1305 case USB_SPEED_SUPER:
1306 if (udev->parent_hub != NULL) {
1307 err = usbd_req_set_hub_depth(udev, NULL,
1308 udev->depth - 1);
1309 if (err) {
1310 DPRINTFN(0, "Setting USB 3.0 HUB depth failed,"
1311 "error=%s\n", usbd_errstr(err));
1312 goto error;
1315 err = usbd_req_get_ss_hub_descriptor(udev, NULL, &hubdesc30, 1);
1316 if (err) {
1317 DPRINTFN(0, "Getting USB 3.0 HUB descriptor failed,"
1318 "error=%s\n", usbd_errstr(err));
1319 goto error;
1321 /* get number of ports */
1322 nports = hubdesc30.bNbrPorts;
1324 /* get power delay */
1325 pwrdly = ((hubdesc30.bPwrOn2PwrGood * UHD_PWRON_FACTOR) +
1326 usb_extra_power_up_time);
1328 /* get complete HUB descriptor */
1329 if (nports >= 8) {
1330 /* check number of ports */
1331 if (nports > ((udev->parent_hub != NULL) ? 15 : 127)) {
1332 DPRINTFN(0, "Invalid number of USB 3.0 ports,"
1333 "error=%s\n", usbd_errstr(err));
1334 goto error;
1336 /* get complete HUB descriptor */
1337 err = usbd_req_get_ss_hub_descriptor(udev, NULL, &hubdesc30, nports);
1339 if (err) {
1340 DPRINTFN(0, "Getting USB 2.0 HUB descriptor failed,"
1341 "error=%s\n", usbd_errstr(err));
1342 goto error;
1344 if (hubdesc30.bNbrPorts != nports) {
1345 DPRINTFN(0, "Number of ports changed\n");
1346 goto error;
1349 break;
1350 default:
1351 DPRINTF("Assuming HUB has only one port\n");
1352 /* default number of ports */
1353 nports = 1;
1354 /* default power delay */
1355 pwrdly = ((10 * UHD_PWRON_FACTOR) + usb_extra_power_up_time);
1356 break;
1358 if (nports == 0) {
1359 DPRINTFN(0, "portless HUB\n");
1360 goto error;
1362 if (nports > USB_MAX_PORTS) {
1363 DPRINTF("Port limit exceeded\n");
1364 goto error;
1366 #if (USB_HAVE_FIXED_PORT == 0)
1367 hub = kmalloc(sizeof(hub[0]) + (sizeof(hub->ports[0]) * nports),
1368 M_USBDEV, M_WAITOK | M_ZERO);
1370 if (hub == NULL)
1371 goto error;
1372 #else
1373 hub = &sc->sc_hub;
1374 #endif
1375 udev->hub = hub;
1377 /* initialize HUB structure */
1378 hub->hubsoftc = sc;
1379 hub->explore = &uhub_explore;
1380 hub->nports = nports;
1381 hub->hubudev = udev;
1382 #if USB_HAVE_TT_SUPPORT
1383 hub->tt_msg[0].hdr.pm_callback = &uhub_reset_tt_proc;
1384 hub->tt_msg[0].udev = udev;
1385 hub->tt_msg[1].hdr.pm_callback = &uhub_reset_tt_proc;
1386 hub->tt_msg[1].udev = udev;
1387 #endif
1388 /* if self powered hub, give ports maximum current */
1389 if (udev->flags.self_powered) {
1390 hub->portpower = USB_MAX_POWER;
1391 } else {
1392 hub->portpower = USB_MIN_POWER;
1395 /* set up interrupt pipe */
1396 iface_index = 0;
1397 if (udev->parent_hub == NULL) {
1398 /* root HUB is special */
1399 err = 0;
1400 } else {
1401 /* normal HUB */
1402 err = usbd_transfer_setup(udev, &iface_index, sc->sc_xfer,
1403 uhub_config, UHUB_N_TRANSFER, sc, &sc->sc_lock);
1405 if (err) {
1406 DPRINTFN(0, "cannot setup interrupt transfer, "
1407 "errstr=%s\n", usbd_errstr(err));
1408 goto error;
1410 /* wait with power off for a while */
1411 usb_pause_mtx(NULL, USB_MS_TO_TICKS(USB_POWER_DOWN_TIME));
1413 #if USB_HAVE_DISABLE_ENUM
1414 /* Add device sysctls */
1416 sysctl_ctx = device_get_sysctl_ctx(dev);
1417 sysctl_tree = device_get_sysctl_tree(dev);
1419 if (sysctl_ctx != NULL && sysctl_tree != NULL) {
1420 (void) SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1421 OID_AUTO, "disable_enumeration", CTLFLAG_RW,
1422 &sc->sc_disable_enumeration, 0,
1423 "Set to disable enumeration on this USB HUB.");
1425 (void) SYSCTL_ADD_INT(sysctl_ctx, SYSCTL_CHILDREN(sysctl_tree),
1426 OID_AUTO, "disable_port_power", CTLFLAG_RW,
1427 &sc->sc_disable_port_power, 0,
1428 "Set to disable USB port power on this USB HUB.");
1430 #endif
1432 * To have the best chance of success we do things in the exact same
1433 * order as Windoze98. This should not be necessary, but some
1434 * devices do not follow the USB specs to the letter.
1436 * These are the events on the bus when a hub is attached:
1437 * Get device and config descriptors (see attach code)
1438 * Get hub descriptor (see above)
1439 * For all ports
1440 * turn on power
1441 * wait for power to become stable
1442 * (all below happens in explore code)
1443 * For all ports
1444 * clear C_PORT_CONNECTION
1445 * For all ports
1446 * get port status
1447 * if device connected
1448 * wait 100 ms
1449 * turn on reset
1450 * wait
1451 * clear C_PORT_RESET
1452 * get port status
1453 * proceed with device attachment
1456 /* XXX should check for none, individual, or ganged power? */
1458 removable = 0;
1460 for (x = 0; x != nports; x++) {
1461 /* set up data structures */
1462 struct usb_port *up = hub->ports + x;
1464 up->device_index = 0;
1465 up->restartcnt = 0;
1466 portno = x + 1;
1468 /* check if port is removable */
1469 switch (udev->speed) {
1470 case USB_SPEED_LOW:
1471 case USB_SPEED_FULL:
1472 case USB_SPEED_HIGH:
1473 if (!UHD_NOT_REMOV(&hubdesc20, portno))
1474 removable++;
1475 break;
1476 case USB_SPEED_SUPER:
1477 if (!UHD_NOT_REMOV(&hubdesc30, portno))
1478 removable++;
1479 break;
1480 default:
1481 DPRINTF("Assuming removable port\n");
1482 removable++;
1483 break;
1485 if (err == 0) {
1486 #if USB_HAVE_DISABLE_ENUM
1487 /* check if we should disable USB port power or not */
1488 if (usb_disable_port_power != 0 ||
1489 sc->sc_disable_port_power != 0) {
1490 /* turn the power off */
1491 DPRINTFN(2, "Turning port %d power off\n", portno);
1492 err = usbd_req_clear_port_feature(udev, NULL,
1493 portno, UHF_PORT_POWER);
1494 } else {
1495 #endif
1496 /* turn the power on */
1497 DPRINTFN(2, "Turning port %d power on\n", portno);
1498 err = usbd_req_set_port_feature(udev, NULL,
1499 portno, UHF_PORT_POWER);
1500 #if USB_HAVE_DISABLE_ENUM
1502 #endif
1504 if (err != 0) {
1505 DPRINTFN(0, "port %d power on or off failed, %s\n",
1506 portno, usbd_errstr(err));
1508 DPRINTF("turn on port %d power\n",
1509 portno);
1511 /* wait for stable power */
1512 usb_pause_mtx(NULL, USB_MS_TO_TICKS(pwrdly));
1515 device_printf(dev, "%d port%s with %d "
1516 "removable, %s powered\n", nports, (nports != 1) ? "s" : "",
1517 removable, udev->flags.self_powered ? "self" : "bus");
1519 /* Start the interrupt endpoint, if any */
1521 if (sc->sc_xfer[0] != NULL) {
1522 lockmgr(&sc->sc_lock, LK_EXCLUSIVE);
1523 usbd_transfer_start(sc->sc_xfer[0]);
1524 lockmgr(&sc->sc_lock, LK_RELEASE);
1527 /* Enable automatic power save on all USB HUBs */
1529 usbd_set_power_mode(udev, USB_POWER_MODE_SAVE);
1531 return (0);
1533 error:
1534 usbd_transfer_unsetup(sc->sc_xfer, UHUB_N_TRANSFER);
1536 if (udev->hub) {
1537 #if (USB_HAVE_FIXED_PORT == 0)
1538 kfree(udev->hub, M_USBDEV);
1539 #endif
1540 udev->hub = NULL;
1542 lockuninit(&sc->sc_lock);
1544 return (ENXIO);
1548 * Called from process context when the hub is gone.
1549 * Detach all devices on active ports.
1551 static int
1552 uhub_detach(device_t dev)
1554 struct uhub_softc *sc = device_get_softc(dev);
1555 struct usb_hub *hub = sc->sc_udev->hub;
1556 struct usb_bus *bus = sc->sc_udev->bus;
1557 struct usb_device *child;
1558 uint8_t x;
1560 if (hub == NULL) /* must be partially working */
1561 return (0);
1563 /* Make sure interrupt transfer is gone. */
1564 usbd_transfer_unsetup(sc->sc_xfer, UHUB_N_TRANSFER);
1566 /* Detach all ports */
1567 for (x = 0; x != hub->nports; x++) {
1569 child = usb_bus_port_get_device(bus, hub->ports + x);
1571 if (child == NULL) {
1572 continue;
1576 * Free USB device and all subdevices, if any.
1578 usb_free_device(child, 0);
1581 #if USB_HAVE_TT_SUPPORT
1582 /* Make sure our TT messages are not queued anywhere */
1583 USB_BUS_LOCK(bus);
1584 usb_proc_mwait(USB_BUS_NON_GIANT_PROC(bus),
1585 &hub->tt_msg[0], &hub->tt_msg[1]);
1586 USB_BUS_UNLOCK(bus);
1587 #endif
1589 #if (USB_HAVE_FIXED_PORT == 0)
1590 kfree(hub, M_USBDEV);
1591 #endif
1592 sc->sc_udev->hub = NULL;
1594 lockuninit(&sc->sc_lock);
1596 return (0);
1599 static int
1600 uhub_suspend(device_t dev)
1602 DPRINTF("\n");
1603 /* Sub-devices are not suspended here! */
1604 return (0);
1607 static int
1608 uhub_resume(device_t dev)
1610 DPRINTF("\n");
1611 /* Sub-devices are not resumed here! */
1612 return (0);
1615 static void
1616 uhub_driver_added(device_t dev, driver_t *driver)
1618 usb_needs_explore_all();
1621 struct hub_result {
1622 struct usb_device *udev;
1623 uint8_t portno;
1624 uint8_t iface_index;
1627 static void
1628 uhub_find_iface_index(struct usb_hub *hub, device_t child,
1629 struct hub_result *res)
1631 struct usb_interface *iface;
1632 struct usb_device *udev;
1633 uint8_t nports;
1634 uint8_t x;
1635 uint8_t i;
1637 nports = hub->nports;
1638 for (x = 0; x != nports; x++) {
1639 udev = usb_bus_port_get_device(hub->hubudev->bus,
1640 hub->ports + x);
1641 if (!udev) {
1642 continue;
1644 for (i = 0; i != USB_IFACE_MAX; i++) {
1645 iface = usbd_get_iface(udev, i);
1646 if (iface &&
1647 (iface->subdev == child)) {
1648 res->iface_index = i;
1649 res->udev = udev;
1650 res->portno = x + 1;
1651 return;
1655 res->iface_index = 0;
1656 res->udev = NULL;
1657 res->portno = 0;
1660 static int
1661 uhub_child_location_string(device_t parent, device_t child,
1662 char *buf, size_t buflen)
1664 struct uhub_softc *sc;
1665 struct usb_hub *hub;
1666 struct hub_result res;
1668 if (!device_is_attached(parent)) {
1669 if (buflen)
1670 buf[0] = 0;
1671 return (0);
1674 sc = device_get_softc(parent);
1675 hub = sc->sc_udev->hub;
1677 uhub_find_iface_index(hub, child, &res);
1678 if (!res.udev) {
1679 DPRINTF("device not on hub\n");
1680 if (buflen) {
1681 buf[0] = '\0';
1683 goto done;
1685 ksnprintf(buf, buflen, "bus=%u hubaddr=%u port=%u devaddr=%u"
1686 " interface=%u"
1687 #if USB_HAVE_UGEN
1688 " ugen=%s"
1689 #endif
1690 , device_get_unit(res.udev->bus->bdev)
1691 , (res.udev->parent_hub != NULL) ?
1692 res.udev->parent_hub->device_index : 0
1693 , res.portno, res.udev->device_index, res.iface_index
1694 #if USB_HAVE_UGEN
1695 , res.udev->ugen_name
1696 #endif
1698 done:
1699 return (0);
1702 static int
1703 uhub_child_pnpinfo_string(device_t parent, device_t child,
1704 char *buf, size_t buflen)
1706 struct uhub_softc *sc;
1707 struct usb_hub *hub;
1708 struct usb_interface *iface;
1709 struct hub_result res;
1711 if (!device_is_attached(parent)) {
1712 if (buflen)
1713 buf[0] = 0;
1714 return (0);
1717 sc = device_get_softc(parent);
1718 hub = sc->sc_udev->hub;
1720 uhub_find_iface_index(hub, child, &res);
1721 if (!res.udev) {
1722 DPRINTF("device not on hub\n");
1723 if (buflen) {
1724 buf[0] = '\0';
1726 goto done;
1728 iface = usbd_get_iface(res.udev, res.iface_index);
1729 if (iface && iface->idesc) {
1730 ksnprintf(buf, buflen, "vendor=0x%04x product=0x%04x "
1731 "devclass=0x%02x devsubclass=0x%02x "
1732 "sernum=\"%s\" "
1733 "release=0x%04x "
1734 "mode=%s "
1735 "intclass=0x%02x intsubclass=0x%02x "
1736 "intprotocol=0x%02x" "%s%s",
1737 UGETW(res.udev->ddesc.idVendor),
1738 UGETW(res.udev->ddesc.idProduct),
1739 res.udev->ddesc.bDeviceClass,
1740 res.udev->ddesc.bDeviceSubClass,
1741 usb_get_serial(res.udev),
1742 UGETW(res.udev->ddesc.bcdDevice),
1743 (res.udev->flags.usb_mode == USB_MODE_HOST) ? "host" : "device",
1744 iface->idesc->bInterfaceClass,
1745 iface->idesc->bInterfaceSubClass,
1746 iface->idesc->bInterfaceProtocol,
1747 iface->pnpinfo ? " " : "",
1748 iface->pnpinfo ? iface->pnpinfo : "");
1749 } else {
1750 if (buflen) {
1751 buf[0] = '\0';
1753 goto done;
1755 done:
1756 return (0);
1760 * The USB Transaction Translator:
1761 * ===============================
1763 * When doing LOW- and FULL-speed USB transfers accross a HIGH-speed
1764 * USB HUB, bandwidth must be allocated for ISOCHRONOUS and INTERRUPT
1765 * USB transfers. To utilize bandwidth dynamically the "scatter and
1766 * gather" principle must be applied. This means that bandwidth must
1767 * be divided into equal parts of bandwidth. With regard to USB all
1768 * data is transferred in smaller packets with length
1769 * "wMaxPacketSize". The problem however is that "wMaxPacketSize" is
1770 * not a constant!
1772 * The bandwidth scheduler which I have implemented will simply pack
1773 * the USB transfers back to back until there is no more space in the
1774 * schedule. Out of the 8 microframes which the USB 2.0 standard
1775 * provides, only 6 are available for non-HIGH-speed devices. I have
1776 * reserved the first 4 microframes for ISOCHRONOUS transfers. The
1777 * last 2 microframes I have reserved for INTERRUPT transfers. Without
1778 * this division, it is very difficult to allocate and free bandwidth
1779 * dynamically.
1781 * NOTE about the Transaction Translator in USB HUBs:
1783 * USB HUBs have a very simple Transaction Translator, that will
1784 * simply pipeline all the SPLIT transactions. That means that the
1785 * transactions will be executed in the order they are queued!
1789 /*------------------------------------------------------------------------*
1790 * usb_intr_find_best_slot
1792 * Return value:
1793 * The best Transaction Translation slot for an interrupt endpoint.
1794 *------------------------------------------------------------------------*/
1795 static uint8_t
1796 usb_intr_find_best_slot(usb_size_t *ptr, uint8_t start,
1797 uint8_t end, uint8_t mask)
1799 usb_size_t min = (usb_size_t)-1;
1800 usb_size_t sum;
1801 uint8_t x;
1802 uint8_t y;
1803 uint8_t z;
1805 y = 0;
1807 /* find the last slot with lesser used bandwidth */
1809 for (x = start; x < end; x++) {
1811 sum = 0;
1813 /* compute sum of bandwidth */
1814 for (z = x; z < end; z++) {
1815 if (mask & (1U << (z - x)))
1816 sum += ptr[z];
1819 /* check if the current multi-slot is more optimal */
1820 if (min >= sum) {
1821 min = sum;
1822 y = x;
1825 /* check if the mask is about to be shifted out */
1826 if (mask & (1U << (end - 1 - x)))
1827 break;
1829 return (y);
1832 /*------------------------------------------------------------------------*
1833 * usb_hs_bandwidth_adjust
1835 * This function will update the bandwith usage for the microframe
1836 * having index "slot" by "len" bytes. "len" can be negative. If the
1837 * "slot" argument is greater or equal to "USB_HS_MICRO_FRAMES_MAX"
1838 * the "slot" argument will be replaced by the slot having least used
1839 * bandwidth. The "mask" argument is used for multi-slot allocations.
1841 * Returns:
1842 * The slot in which the bandwidth update was done: 0..7
1843 *------------------------------------------------------------------------*/
1844 static uint8_t
1845 usb_hs_bandwidth_adjust(struct usb_device *udev, int16_t len,
1846 uint8_t slot, uint8_t mask)
1848 struct usb_bus *bus = udev->bus;
1849 struct usb_hub *hub;
1850 enum usb_dev_speed speed;
1851 uint8_t x;
1853 USB_BUS_LOCK_ASSERT(bus);
1855 speed = usbd_get_speed(udev);
1857 switch (speed) {
1858 case USB_SPEED_LOW:
1859 case USB_SPEED_FULL:
1860 if (speed == USB_SPEED_LOW) {
1861 len *= 8;
1864 * The Host Controller Driver should have
1865 * performed checks so that the lookup
1866 * below does not result in a NULL pointer
1867 * access.
1870 hub = udev->parent_hs_hub->hub;
1871 if (slot >= USB_HS_MICRO_FRAMES_MAX) {
1872 slot = usb_intr_find_best_slot(hub->uframe_usage,
1873 USB_FS_ISOC_UFRAME_MAX, 6, mask);
1875 for (x = slot; x < 8; x++) {
1876 if (mask & (1U << (x - slot))) {
1877 hub->uframe_usage[x] += len;
1878 bus->uframe_usage[x] += len;
1881 break;
1882 default:
1883 if (slot >= USB_HS_MICRO_FRAMES_MAX) {
1884 slot = usb_intr_find_best_slot(bus->uframe_usage, 0,
1885 USB_HS_MICRO_FRAMES_MAX, mask);
1887 for (x = slot; x < 8; x++) {
1888 if (mask & (1U << (x - slot))) {
1889 bus->uframe_usage[x] += len;
1892 break;
1894 return (slot);
1897 /*------------------------------------------------------------------------*
1898 * usb_hs_bandwidth_alloc
1900 * This function is a wrapper function for "usb_hs_bandwidth_adjust()".
1901 *------------------------------------------------------------------------*/
1902 void
1903 usb_hs_bandwidth_alloc(struct usb_xfer *xfer)
1905 struct usb_device *udev;
1906 uint8_t slot;
1907 uint8_t mask;
1908 uint8_t speed;
1910 udev = xfer->xroot->udev;
1912 if (udev->flags.usb_mode != USB_MODE_HOST)
1913 return; /* not supported */
1915 xfer->endpoint->refcount_bw++;
1916 if (xfer->endpoint->refcount_bw != 1)
1917 return; /* already allocated */
1919 speed = usbd_get_speed(udev);
1921 switch (xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE) {
1922 case UE_INTERRUPT:
1923 /* allocate a microframe slot */
1925 mask = 0x01;
1926 slot = usb_hs_bandwidth_adjust(udev,
1927 xfer->max_frame_size, USB_HS_MICRO_FRAMES_MAX, mask);
1929 xfer->endpoint->usb_uframe = slot;
1930 xfer->endpoint->usb_smask = mask << slot;
1932 if ((speed != USB_SPEED_FULL) &&
1933 (speed != USB_SPEED_LOW)) {
1934 xfer->endpoint->usb_cmask = 0x00 ;
1935 } else {
1936 xfer->endpoint->usb_cmask = (-(0x04 << slot)) & 0xFE;
1938 break;
1940 case UE_ISOCHRONOUS:
1941 switch (usbd_xfer_get_fps_shift(xfer)) {
1942 case 0:
1943 mask = 0xFF;
1944 break;
1945 case 1:
1946 mask = 0x55;
1947 break;
1948 case 2:
1949 mask = 0x11;
1950 break;
1951 default:
1952 mask = 0x01;
1953 break;
1956 /* allocate a microframe multi-slot */
1958 slot = usb_hs_bandwidth_adjust(udev,
1959 xfer->max_frame_size, USB_HS_MICRO_FRAMES_MAX, mask);
1961 xfer->endpoint->usb_uframe = slot;
1962 xfer->endpoint->usb_cmask = 0;
1963 xfer->endpoint->usb_smask = mask << slot;
1964 break;
1966 default:
1967 xfer->endpoint->usb_uframe = 0;
1968 xfer->endpoint->usb_cmask = 0;
1969 xfer->endpoint->usb_smask = 0;
1970 break;
1973 DPRINTFN(11, "slot=%d, mask=0x%02x\n",
1974 xfer->endpoint->usb_uframe,
1975 xfer->endpoint->usb_smask >> xfer->endpoint->usb_uframe);
1978 /*------------------------------------------------------------------------*
1979 * usb_hs_bandwidth_free
1981 * This function is a wrapper function for "usb_hs_bandwidth_adjust()".
1982 *------------------------------------------------------------------------*/
1983 void
1984 usb_hs_bandwidth_free(struct usb_xfer *xfer)
1986 struct usb_device *udev;
1987 uint8_t slot;
1988 uint8_t mask;
1990 udev = xfer->xroot->udev;
1992 if (udev->flags.usb_mode != USB_MODE_HOST)
1993 return; /* not supported */
1995 xfer->endpoint->refcount_bw--;
1996 if (xfer->endpoint->refcount_bw != 0)
1997 return; /* still allocated */
1999 switch (xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE) {
2000 case UE_INTERRUPT:
2001 case UE_ISOCHRONOUS:
2003 slot = xfer->endpoint->usb_uframe;
2004 mask = xfer->endpoint->usb_smask;
2006 /* free microframe slot(s): */
2007 usb_hs_bandwidth_adjust(udev,
2008 -xfer->max_frame_size, slot, mask >> slot);
2010 DPRINTFN(11, "slot=%d, mask=0x%02x\n",
2011 slot, mask >> slot);
2013 xfer->endpoint->usb_uframe = 0;
2014 xfer->endpoint->usb_cmask = 0;
2015 xfer->endpoint->usb_smask = 0;
2016 break;
2018 default:
2019 break;
2023 /*------------------------------------------------------------------------*
2024 * usb_isoc_time_expand
2026 * This function will expand the time counter from 7-bit to 16-bit.
2028 * Returns:
2029 * 16-bit isochronous time counter.
2030 *------------------------------------------------------------------------*/
2031 uint16_t
2032 usb_isoc_time_expand(struct usb_bus *bus, uint16_t isoc_time_curr)
2034 uint16_t rem;
2036 USB_BUS_LOCK_ASSERT(bus);
2038 rem = bus->isoc_time_last & (USB_ISOC_TIME_MAX - 1);
2040 isoc_time_curr &= (USB_ISOC_TIME_MAX - 1);
2042 if (isoc_time_curr < rem) {
2043 /* the time counter wrapped around */
2044 bus->isoc_time_last += USB_ISOC_TIME_MAX;
2046 /* update the remainder */
2048 bus->isoc_time_last &= ~(USB_ISOC_TIME_MAX - 1);
2049 bus->isoc_time_last |= isoc_time_curr;
2051 return (bus->isoc_time_last);
2054 /*------------------------------------------------------------------------*
2055 * usbd_fs_isoc_schedule_alloc_slot
2057 * This function will allocate bandwidth for an isochronous FULL speed
2058 * transaction in the FULL speed schedule.
2060 * Returns:
2061 * <8: Success
2062 * Else: Error
2063 *------------------------------------------------------------------------*/
2064 #if USB_HAVE_TT_SUPPORT
2065 uint8_t
2066 usbd_fs_isoc_schedule_alloc_slot(struct usb_xfer *isoc_xfer, uint16_t isoc_time)
2068 struct usb_xfer *xfer;
2069 struct usb_xfer *pipe_xfer;
2070 struct usb_bus *bus;
2071 usb_frlength_t len;
2072 usb_frlength_t data_len;
2073 uint16_t delta;
2074 uint16_t slot;
2075 uint8_t retval;
2077 data_len = 0;
2078 slot = 0;
2080 bus = isoc_xfer->xroot->bus;
2082 TAILQ_FOREACH(xfer, &bus->intr_q.head, wait_entry) {
2084 /* skip self, if any */
2086 if (xfer == isoc_xfer)
2087 continue;
2089 /* check if this USB transfer is going through the same TT */
2091 if (xfer->xroot->udev->parent_hs_hub !=
2092 isoc_xfer->xroot->udev->parent_hs_hub) {
2093 continue;
2095 if ((isoc_xfer->xroot->udev->parent_hs_hub->
2096 ddesc.bDeviceProtocol == UDPROTO_HSHUBMTT) &&
2097 (xfer->xroot->udev->hs_port_no !=
2098 isoc_xfer->xroot->udev->hs_port_no)) {
2099 continue;
2101 if (xfer->endpoint->methods != isoc_xfer->endpoint->methods)
2102 continue;
2104 /* check if isoc_time is part of this transfer */
2106 delta = xfer->isoc_time_complete - isoc_time;
2107 if (delta > 0 && delta <= xfer->nframes) {
2108 delta = xfer->nframes - delta;
2110 len = xfer->frlengths[delta];
2111 len += 8;
2112 len *= 7;
2113 len /= 6;
2115 data_len += len;
2119 * Check double buffered transfers. Only stream ID
2120 * equal to zero is valid here!
2122 TAILQ_FOREACH(pipe_xfer, &xfer->endpoint->endpoint_q[0].head,
2123 wait_entry) {
2125 /* skip self, if any */
2127 if (pipe_xfer == isoc_xfer)
2128 continue;
2130 /* check if isoc_time is part of this transfer */
2132 delta = pipe_xfer->isoc_time_complete - isoc_time;
2133 if (delta > 0 && delta <= pipe_xfer->nframes) {
2134 delta = pipe_xfer->nframes - delta;
2136 len = pipe_xfer->frlengths[delta];
2137 len += 8;
2138 len *= 7;
2139 len /= 6;
2141 data_len += len;
2146 while (data_len >= USB_FS_BYTES_PER_HS_UFRAME) {
2147 data_len -= USB_FS_BYTES_PER_HS_UFRAME;
2148 slot++;
2151 /* check for overflow */
2153 if (slot >= USB_FS_ISOC_UFRAME_MAX)
2154 return (255);
2156 retval = slot;
2158 delta = isoc_xfer->isoc_time_complete - isoc_time;
2159 if (delta > 0 && delta <= isoc_xfer->nframes) {
2160 delta = isoc_xfer->nframes - delta;
2162 len = isoc_xfer->frlengths[delta];
2163 len += 8;
2164 len *= 7;
2165 len /= 6;
2167 data_len += len;
2170 while (data_len >= USB_FS_BYTES_PER_HS_UFRAME) {
2171 data_len -= USB_FS_BYTES_PER_HS_UFRAME;
2172 slot++;
2175 /* check for overflow */
2177 if (slot >= USB_FS_ISOC_UFRAME_MAX)
2178 return (255);
2180 return (retval);
2182 #endif
2184 /*------------------------------------------------------------------------*
2185 * usb_bus_port_get_device
2187 * This function is NULL safe.
2188 *------------------------------------------------------------------------*/
2189 struct usb_device *
2190 usb_bus_port_get_device(struct usb_bus *bus, struct usb_port *up)
2192 if ((bus == NULL) || (up == NULL)) {
2193 /* be NULL safe */
2194 return (NULL);
2196 if (up->device_index == 0) {
2197 /* nothing to do */
2198 return (NULL);
2200 return (bus->devices[up->device_index]);
2203 /*------------------------------------------------------------------------*
2204 * usb_bus_port_set_device
2206 * This function is NULL safe.
2207 *------------------------------------------------------------------------*/
2208 void
2209 usb_bus_port_set_device(struct usb_bus *bus, struct usb_port *up,
2210 struct usb_device *udev, uint8_t device_index)
2212 if (bus == NULL) {
2213 /* be NULL safe */
2214 return;
2217 * There is only one case where we don't
2218 * have an USB port, and that is the Root Hub!
2220 if (up) {
2221 if (udev) {
2222 up->device_index = device_index;
2223 } else {
2224 device_index = up->device_index;
2225 up->device_index = 0;
2229 * Make relationships to our new device
2231 if (device_index != 0) {
2232 #if USB_HAVE_UGEN
2233 lockmgr(&usb_ref_lock, LK_EXCLUSIVE);
2234 #endif
2235 bus->devices[device_index] = udev;
2236 #if USB_HAVE_UGEN
2237 lockmgr(&usb_ref_lock, LK_RELEASE);
2238 #endif
2241 * Debug print
2243 DPRINTFN(2, "bus %p devices[%u] = %p\n", bus, device_index, udev);
2246 /*------------------------------------------------------------------------*
2247 * usb_needs_explore
2249 * This functions is called when the USB event thread needs to run.
2250 *------------------------------------------------------------------------*/
2251 void
2252 usb_needs_explore(struct usb_bus *bus, uint8_t do_probe)
2254 uint8_t do_unlock;
2256 DPRINTF("\n");
2258 if (bus == NULL) {
2259 DPRINTF("No bus pointer!\n");
2260 return;
2262 if ((bus->devices == NULL) ||
2263 (bus->devices[USB_ROOT_HUB_ADDR] == NULL)) {
2264 DPRINTF("No root HUB\n");
2265 return;
2267 if (lockowned(&bus->bus_lock) != 0) {
2268 do_unlock = 0;
2269 } else {
2270 USB_BUS_LOCK(bus);
2271 do_unlock = 1;
2273 if (do_probe) {
2274 bus->do_probe = 1;
2276 if (usb_proc_msignal(USB_BUS_EXPLORE_PROC(bus),
2277 &bus->explore_msg[0], &bus->explore_msg[1])) {
2278 /* ignore */
2280 if (do_unlock) {
2281 USB_BUS_UNLOCK(bus);
2285 /*------------------------------------------------------------------------*
2286 * usb_needs_explore_all
2288 * This function is called whenever a new driver is loaded and will
2289 * cause that all USB busses are re-explored.
2290 *------------------------------------------------------------------------*/
2291 void
2292 usb_needs_explore_all(void)
2294 struct usb_bus *bus;
2295 devclass_t dc;
2296 device_t dev;
2297 int max;
2299 DPRINTFN(3, "\n");
2301 dc = usb_devclass_ptr;
2302 if (dc == NULL) {
2303 DPRINTFN(0, "no devclass\n");
2304 return;
2307 * Explore all USB busses in parallell.
2309 max = devclass_get_maxunit(dc);
2310 while (max >= 0) {
2311 dev = devclass_get_device(dc, max);
2312 if (dev) {
2313 bus = device_get_softc(dev);
2314 if (bus) {
2315 usb_needs_explore(bus, 1);
2318 max--;
2322 /*------------------------------------------------------------------------*
2323 * usb_bus_power_update
2325 * This function will ensure that all USB devices on the given bus are
2326 * properly suspended or resumed according to the device transfer
2327 * state.
2328 *------------------------------------------------------------------------*/
2329 #if USB_HAVE_POWERD
2330 void
2331 usb_bus_power_update(struct usb_bus *bus)
2333 usb_needs_explore(bus, 0 /* no probe */ );
2335 #endif
2337 /*------------------------------------------------------------------------*
2338 * usbd_transfer_power_ref
2340 * This function will modify the power save reference counts and
2341 * wakeup the USB device associated with the given USB transfer, if
2342 * needed.
2343 *------------------------------------------------------------------------*/
2344 #if USB_HAVE_POWERD
2345 void
2346 usbd_transfer_power_ref(struct usb_xfer *xfer, int val)
2348 static const usb_power_mask_t power_mask[4] = {
2349 [UE_CONTROL] = USB_HW_POWER_CONTROL,
2350 [UE_BULK] = USB_HW_POWER_BULK,
2351 [UE_INTERRUPT] = USB_HW_POWER_INTERRUPT,
2352 [UE_ISOCHRONOUS] = USB_HW_POWER_ISOC,
2354 struct usb_device *udev;
2355 uint8_t needs_explore;
2356 uint8_t needs_hw_power;
2357 uint8_t xfer_type;
2359 udev = xfer->xroot->udev;
2361 if (udev->device_index == USB_ROOT_HUB_ADDR) {
2362 /* no power save for root HUB */
2363 return;
2365 USB_BUS_LOCK(udev->bus);
2367 xfer_type = xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE;
2369 udev->pwr_save.last_xfer_time = ticks;
2370 udev->pwr_save.type_refs[xfer_type] += val;
2372 if (xfer->flags_int.control_xfr) {
2373 udev->pwr_save.read_refs += val;
2374 if (xfer->flags_int.usb_mode == USB_MODE_HOST) {
2376 * It is not allowed to suspend during a
2377 * control transfer:
2379 udev->pwr_save.write_refs += val;
2381 } else if (USB_GET_DATA_ISREAD(xfer)) {
2382 udev->pwr_save.read_refs += val;
2383 } else {
2384 udev->pwr_save.write_refs += val;
2387 if (val > 0) {
2388 if (udev->flags.self_suspended)
2389 needs_explore = usb_peer_should_wakeup(udev);
2390 else
2391 needs_explore = 0;
2393 if (!(udev->bus->hw_power_state & power_mask[xfer_type])) {
2394 DPRINTF("Adding type %u to power state\n", xfer_type);
2395 udev->bus->hw_power_state |= power_mask[xfer_type];
2396 needs_hw_power = 1;
2397 } else {
2398 needs_hw_power = 0;
2400 } else {
2401 needs_explore = 0;
2402 needs_hw_power = 0;
2405 USB_BUS_UNLOCK(udev->bus);
2407 if (needs_explore) {
2408 DPRINTF("update\n");
2409 usb_bus_power_update(udev->bus);
2410 } else if (needs_hw_power) {
2411 DPRINTF("needs power\n");
2412 if (udev->bus->methods->set_hw_power != NULL) {
2413 (udev->bus->methods->set_hw_power) (udev->bus);
2417 #endif
2419 /*------------------------------------------------------------------------*
2420 * usb_peer_should_wakeup
2422 * This function returns non-zero if the current device should wake up.
2423 *------------------------------------------------------------------------*/
2424 static uint8_t
2425 usb_peer_should_wakeup(struct usb_device *udev)
2427 return (((udev->power_mode == USB_POWER_MODE_ON) &&
2428 (udev->flags.usb_mode == USB_MODE_HOST)) ||
2429 (udev->driver_added_refcount != udev->bus->driver_added_refcount) ||
2430 (udev->re_enumerate_wait != USB_RE_ENUM_DONE) ||
2431 (udev->pwr_save.type_refs[UE_ISOCHRONOUS] != 0) ||
2432 (udev->pwr_save.write_refs != 0) ||
2433 ((udev->pwr_save.read_refs != 0) &&
2434 (udev->flags.usb_mode == USB_MODE_HOST) &&
2435 (usb_peer_can_wakeup(udev) == 0)));
2438 /*------------------------------------------------------------------------*
2439 * usb_bus_powerd
2441 * This function implements the USB power daemon and is called
2442 * regularly from the USB explore thread.
2443 *------------------------------------------------------------------------*/
2444 #if USB_HAVE_POWERD
2445 void
2446 usb_bus_powerd(struct usb_bus *bus)
2448 struct usb_device *udev;
2449 usb_ticks_t temp;
2450 usb_ticks_t limit;
2451 usb_ticks_t mintime;
2452 usb_size_t type_refs[5];
2453 uint8_t x;
2455 limit = usb_power_timeout;
2456 if (limit == 0)
2457 limit = hz;
2458 else if (limit > 255)
2459 limit = 255 * hz;
2460 else
2461 limit = limit * hz;
2463 DPRINTF("bus=%p\n", bus);
2465 USB_BUS_LOCK(bus);
2468 * The root HUB device is never suspended
2469 * and we simply skip it.
2471 for (x = USB_ROOT_HUB_ADDR + 1;
2472 x != bus->devices_max; x++) {
2474 udev = bus->devices[x];
2475 if (udev == NULL)
2476 continue;
2478 temp = ticks - udev->pwr_save.last_xfer_time;
2480 if (usb_peer_should_wakeup(udev)) {
2481 /* check if we are suspended */
2482 if (udev->flags.self_suspended != 0) {
2483 USB_BUS_UNLOCK(bus);
2484 usb_dev_resume_peer(udev);
2485 USB_BUS_LOCK(bus);
2487 } else if ((temp >= limit) &&
2488 (udev->flags.usb_mode == USB_MODE_HOST) &&
2489 (udev->flags.self_suspended == 0)) {
2490 /* try to do suspend */
2492 USB_BUS_UNLOCK(bus);
2493 usb_dev_suspend_peer(udev);
2494 USB_BUS_LOCK(bus);
2498 /* reset counters */
2500 mintime = (usb_ticks_t)-1;
2501 type_refs[0] = 0;
2502 type_refs[1] = 0;
2503 type_refs[2] = 0;
2504 type_refs[3] = 0;
2505 type_refs[4] = 0;
2507 /* Re-loop all the devices to get the actual state */
2509 for (x = USB_ROOT_HUB_ADDR + 1;
2510 x != bus->devices_max; x++) {
2512 udev = bus->devices[x];
2513 if (udev == NULL)
2514 continue;
2516 /* we found a non-Root-Hub USB device */
2517 type_refs[4] += 1;
2519 /* "last_xfer_time" can be updated by a resume */
2520 temp = ticks - udev->pwr_save.last_xfer_time;
2523 * Compute minimum time since last transfer for the complete
2524 * bus:
2526 if (temp < mintime)
2527 mintime = temp;
2529 if (udev->flags.self_suspended == 0) {
2530 type_refs[0] += udev->pwr_save.type_refs[0];
2531 type_refs[1] += udev->pwr_save.type_refs[1];
2532 type_refs[2] += udev->pwr_save.type_refs[2];
2533 type_refs[3] += udev->pwr_save.type_refs[3];
2537 if (mintime >= (usb_ticks_t)(1 * hz)) {
2538 /* recompute power masks */
2539 DPRINTF("Recomputing power masks\n");
2540 bus->hw_power_state = 0;
2541 if (type_refs[UE_CONTROL] != 0)
2542 bus->hw_power_state |= USB_HW_POWER_CONTROL;
2543 if (type_refs[UE_BULK] != 0)
2544 bus->hw_power_state |= USB_HW_POWER_BULK;
2545 if (type_refs[UE_INTERRUPT] != 0)
2546 bus->hw_power_state |= USB_HW_POWER_INTERRUPT;
2547 if (type_refs[UE_ISOCHRONOUS] != 0)
2548 bus->hw_power_state |= USB_HW_POWER_ISOC;
2549 if (type_refs[4] != 0)
2550 bus->hw_power_state |= USB_HW_POWER_NON_ROOT_HUB;
2552 USB_BUS_UNLOCK(bus);
2554 if (bus->methods->set_hw_power != NULL) {
2555 /* always update hardware power! */
2556 (bus->methods->set_hw_power) (bus);
2558 return;
2560 #endif
2562 /*------------------------------------------------------------------------*
2563 * usb_dev_resume_peer
2565 * This function will resume an USB peer and do the required USB
2566 * signalling to get an USB device out of the suspended state.
2567 *------------------------------------------------------------------------*/
2568 static void
2569 usb_dev_resume_peer(struct usb_device *udev)
2571 struct usb_bus *bus;
2572 int err;
2574 /* be NULL safe */
2575 if (udev == NULL)
2576 return;
2578 /* check if already resumed */
2579 if (udev->flags.self_suspended == 0)
2580 return;
2582 /* we need a parent HUB to do resume */
2583 if (udev->parent_hub == NULL)
2584 return;
2586 DPRINTF("udev=%p\n", udev);
2588 if ((udev->flags.usb_mode == USB_MODE_DEVICE) &&
2589 (udev->flags.remote_wakeup == 0)) {
2591 * If the host did not set the remote wakeup feature, we can
2592 * not wake it up either!
2594 DPRINTF("remote wakeup is not set!\n");
2595 return;
2597 /* get bus pointer */
2598 bus = udev->bus;
2600 /* resume parent hub first */
2601 usb_dev_resume_peer(udev->parent_hub);
2603 /* reduce chance of instant resume failure by waiting a little bit */
2604 usb_pause_mtx(NULL, USB_MS_TO_TICKS(20));
2606 if (usb_device_20_compatible(udev)) {
2607 /* resume current port (Valid in Host and Device Mode) */
2608 err = usbd_req_clear_port_feature(udev->parent_hub,
2609 NULL, udev->port_no, UHF_PORT_SUSPEND);
2610 if (err) {
2611 DPRINTFN(0, "Resuming port failed\n");
2612 return;
2614 } else {
2615 /* resume current port (Valid in Host and Device Mode) */
2616 err = usbd_req_set_port_link_state(udev->parent_hub,
2617 NULL, udev->port_no, UPS_PORT_LS_U0);
2618 if (err) {
2619 DPRINTFN(0, "Resuming port failed\n");
2620 return;
2624 /* resume settle time */
2625 usb_pause_mtx(NULL, USB_MS_TO_TICKS(usb_port_resume_delay));
2627 if (bus->methods->device_resume != NULL) {
2628 /* resume USB device on the USB controller */
2629 (bus->methods->device_resume) (udev);
2631 USB_BUS_LOCK(bus);
2632 /* set that this device is now resumed */
2633 udev->flags.self_suspended = 0;
2634 #if USB_HAVE_POWERD
2635 /* make sure that we don't go into suspend right away */
2636 udev->pwr_save.last_xfer_time = ticks;
2638 /* make sure the needed power masks are on */
2639 if (udev->pwr_save.type_refs[UE_CONTROL] != 0)
2640 bus->hw_power_state |= USB_HW_POWER_CONTROL;
2641 if (udev->pwr_save.type_refs[UE_BULK] != 0)
2642 bus->hw_power_state |= USB_HW_POWER_BULK;
2643 if (udev->pwr_save.type_refs[UE_INTERRUPT] != 0)
2644 bus->hw_power_state |= USB_HW_POWER_INTERRUPT;
2645 if (udev->pwr_save.type_refs[UE_ISOCHRONOUS] != 0)
2646 bus->hw_power_state |= USB_HW_POWER_ISOC;
2647 #endif
2648 USB_BUS_UNLOCK(bus);
2650 if (bus->methods->set_hw_power != NULL) {
2651 /* always update hardware power! */
2652 (bus->methods->set_hw_power) (bus);
2655 usbd_sr_lock(udev);
2657 /* notify all sub-devices about resume */
2658 err = usb_suspend_resume(udev, 0);
2660 usbd_sr_unlock(udev);
2662 /* check if peer has wakeup capability */
2663 if (usb_peer_can_wakeup(udev)) {
2664 /* clear remote wakeup */
2665 err = usbd_req_clear_device_feature(udev,
2666 NULL, UF_DEVICE_REMOTE_WAKEUP);
2667 if (err) {
2668 DPRINTFN(0, "Clearing device "
2669 "remote wakeup failed: %s\n",
2670 usbd_errstr(err));
2675 /*------------------------------------------------------------------------*
2676 * usb_dev_suspend_peer
2678 * This function will suspend an USB peer and do the required USB
2679 * signalling to get an USB device into the suspended state.
2680 *------------------------------------------------------------------------*/
2681 static void
2682 usb_dev_suspend_peer(struct usb_device *udev)
2684 struct usb_device *child;
2685 int err;
2686 uint8_t x;
2687 uint8_t nports;
2689 repeat:
2690 /* be NULL safe */
2691 if (udev == NULL)
2692 return;
2694 /* check if already suspended */
2695 if (udev->flags.self_suspended)
2696 return;
2698 /* we need a parent HUB to do suspend */
2699 if (udev->parent_hub == NULL)
2700 return;
2702 DPRINTF("udev=%p\n", udev);
2704 /* check if the current device is a HUB */
2705 if (udev->hub != NULL) {
2706 nports = udev->hub->nports;
2708 /* check if all devices on the HUB are suspended */
2709 for (x = 0; x != nports; x++) {
2710 child = usb_bus_port_get_device(udev->bus,
2711 udev->hub->ports + x);
2713 if (child == NULL)
2714 continue;
2716 if (child->flags.self_suspended)
2717 continue;
2719 DPRINTFN(1, "Port %u is busy on the HUB!\n", x + 1);
2720 return;
2724 if (usb_peer_can_wakeup(udev)) {
2726 * This request needs to be done before we set
2727 * "udev->flags.self_suspended":
2730 /* allow device to do remote wakeup */
2731 err = usbd_req_set_device_feature(udev,
2732 NULL, UF_DEVICE_REMOTE_WAKEUP);
2733 if (err) {
2734 DPRINTFN(0, "Setting device "
2735 "remote wakeup failed\n");
2739 USB_BUS_LOCK(udev->bus);
2741 * Checking for suspend condition and setting suspended bit
2742 * must be atomic!
2744 err = usb_peer_should_wakeup(udev);
2745 if (err == 0) {
2747 * Set that this device is suspended. This variable
2748 * must be set before calling USB controller suspend
2749 * callbacks.
2751 udev->flags.self_suspended = 1;
2753 USB_BUS_UNLOCK(udev->bus);
2755 if (err != 0) {
2756 if (usb_peer_can_wakeup(udev)) {
2757 /* allow device to do remote wakeup */
2758 err = usbd_req_clear_device_feature(udev,
2759 NULL, UF_DEVICE_REMOTE_WAKEUP);
2760 if (err) {
2761 DPRINTFN(0, "Setting device "
2762 "remote wakeup failed\n");
2766 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2767 /* resume parent HUB first */
2768 usb_dev_resume_peer(udev->parent_hub);
2770 /* reduce chance of instant resume failure by waiting a little bit */
2771 usb_pause_mtx(NULL, USB_MS_TO_TICKS(20));
2773 /* resume current port (Valid in Host and Device Mode) */
2774 err = usbd_req_clear_port_feature(udev->parent_hub,
2775 NULL, udev->port_no, UHF_PORT_SUSPEND);
2777 /* resume settle time */
2778 usb_pause_mtx(NULL, USB_MS_TO_TICKS(usb_port_resume_delay));
2780 DPRINTF("Suspend was cancelled!\n");
2781 return;
2784 usbd_sr_lock(udev);
2786 /* notify all sub-devices about suspend */
2787 err = usb_suspend_resume(udev, 1);
2789 usbd_sr_unlock(udev);
2791 if (udev->bus->methods->device_suspend != NULL) {
2792 usb_timeout_t temp;
2794 /* suspend device on the USB controller */
2795 (udev->bus->methods->device_suspend) (udev);
2797 /* do DMA delay */
2798 temp = usbd_get_dma_delay(udev);
2799 if (temp != 0)
2800 usb_pause_mtx(NULL, USB_MS_TO_TICKS(temp));
2804 if (usb_device_20_compatible(udev)) {
2805 /* suspend current port */
2806 err = usbd_req_set_port_feature(udev->parent_hub,
2807 NULL, udev->port_no, UHF_PORT_SUSPEND);
2808 if (err) {
2809 DPRINTFN(0, "Suspending port failed\n");
2810 return;
2812 } else {
2813 /* suspend current port */
2814 err = usbd_req_set_port_link_state(udev->parent_hub,
2815 NULL, udev->port_no, UPS_PORT_LS_U3);
2816 if (err) {
2817 DPRINTFN(0, "Suspending port failed\n");
2818 return;
2822 udev = udev->parent_hub;
2823 goto repeat;
2826 /*------------------------------------------------------------------------*
2827 * usbd_set_power_mode
2829 * This function will set the power mode, see USB_POWER_MODE_XXX for a
2830 * USB device.
2831 *------------------------------------------------------------------------*/
2832 void
2833 usbd_set_power_mode(struct usb_device *udev, uint8_t power_mode)
2835 /* filter input argument */
2836 if ((power_mode != USB_POWER_MODE_ON) &&
2837 (power_mode != USB_POWER_MODE_OFF))
2838 power_mode = USB_POWER_MODE_SAVE;
2840 power_mode = usbd_filter_power_mode(udev, power_mode);
2842 udev->power_mode = power_mode; /* update copy of power mode */
2844 #if USB_HAVE_POWERD
2845 usb_bus_power_update(udev->bus);
2846 #else
2847 usb_needs_explore(udev->bus, 0 /* no probe */ );
2848 #endif
2851 /*------------------------------------------------------------------------*
2852 * usbd_filter_power_mode
2854 * This function filters the power mode based on hardware requirements.
2855 *------------------------------------------------------------------------*/
2856 uint8_t
2857 usbd_filter_power_mode(struct usb_device *udev, uint8_t power_mode)
2859 const struct usb_bus_methods *mtod;
2860 int8_t temp;
2862 mtod = udev->bus->methods;
2863 temp = -1;
2865 if (mtod->get_power_mode != NULL)
2866 (mtod->get_power_mode) (udev, &temp);
2868 /* check if we should not filter */
2869 if (temp < 0)
2870 return (power_mode);
2872 /* use fixed power mode given by hardware driver */
2873 return (temp);
2876 /*------------------------------------------------------------------------*
2877 * usbd_start_re_enumerate
2879 * This function starts re-enumeration of the given USB device. This
2880 * function does not need to be called BUS-locked. This function does
2881 * not wait until the re-enumeration is completed.
2882 *------------------------------------------------------------------------*/
2883 void
2884 usbd_start_re_enumerate(struct usb_device *udev)
2886 if (udev->re_enumerate_wait == USB_RE_ENUM_DONE) {
2887 udev->re_enumerate_wait = USB_RE_ENUM_START;
2888 usb_needs_explore(udev->bus, 0);
2892 /*-----------------------------------------------------------------------*
2893 * usbd_start_set_config
2895 * This function starts setting a USB configuration. This function
2896 * does not need to be called BUS-locked. This function does not wait
2897 * until the set USB configuratino is completed.
2898 *------------------------------------------------------------------------*/
2899 usb_error_t
2900 usbd_start_set_config(struct usb_device *udev, uint8_t index)
2902 if (udev->re_enumerate_wait == USB_RE_ENUM_DONE) {
2903 if (udev->curr_config_index == index) {
2904 /* no change needed */
2905 return (0);
2907 udev->next_config_index = index;
2908 udev->re_enumerate_wait = USB_RE_ENUM_SET_CONFIG;
2909 usb_needs_explore(udev->bus, 0);
2910 return (0);
2911 } else if (udev->re_enumerate_wait == USB_RE_ENUM_SET_CONFIG) {
2912 if (udev->next_config_index == index) {
2913 /* no change needed */
2914 return (0);
2917 return (USB_ERR_PENDING_REQUESTS);