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