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