]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/dev/usb/usb_hub.c
MFC r267240:
[FreeBSD/stable/8.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 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         err = 0;
605         timeout = 0;
606         udev = sc->sc_udev;
607         child = usb_bus_port_get_device(udev->bus,
608             udev->hub->ports + portno - 1);
609
610 repeat:
611
612         /* first clear the port connection change bit */
613
614         err = usbd_req_clear_port_feature(udev, NULL,
615             portno, UHF_C_PORT_CONNECTION);
616
617         if (err) {
618                 goto error;
619         }
620         /* check if there is a child */
621
622         if (child != NULL) {
623                 /*
624                  * Free USB device and all subdevices, if any.
625                  */
626                 usb_free_device(child, 0);
627                 child = NULL;
628         }
629         /* get fresh status */
630
631         err = uhub_read_port_status(sc, portno);
632         if (err) {
633                 goto error;
634         }
635         /* check if nothing is connected to the port */
636
637         if (!(sc->sc_st.port_status & UPS_CURRENT_CONNECT_STATUS)) {
638                 goto error;
639         }
640         /* check if there is no power on the port and print a warning */
641
642         switch (udev->speed) {
643         case USB_SPEED_HIGH:
644         case USB_SPEED_FULL:
645         case USB_SPEED_LOW:
646                 power_mask = UPS_PORT_POWER;
647                 break;
648         case USB_SPEED_SUPER:
649                 if (udev->parent_hub == NULL)
650                         power_mask = UPS_PORT_POWER;
651                 else
652                         power_mask = UPS_PORT_POWER_SS;
653                 break;
654         default:
655                 power_mask = 0;
656                 break;
657         }
658         if (!(sc->sc_st.port_status & power_mask)) {
659                 DPRINTF("WARNING: strange, connected port %d "
660                     "has no power\n", portno);
661         }
662
663         /* check if the device is in Host Mode */
664
665         if (!(sc->sc_st.port_status & UPS_PORT_MODE_DEVICE)) {
666
667                 DPRINTF("Port %d is in Host Mode\n", portno);
668
669                 if (sc->sc_st.port_status & UPS_SUSPEND) {
670                         /*
671                          * NOTE: Should not get here in SuperSpeed
672                          * mode, because the HUB should report this
673                          * bit as zero.
674                          */
675                         DPRINTF("Port %d was still "
676                             "suspended, clearing.\n", portno);
677                         err = usbd_req_clear_port_feature(udev,
678                             NULL, portno, UHF_PORT_SUSPEND);
679                 }
680
681                 /* USB Host Mode */
682
683                 /* wait for maximum device power up time */
684
685                 usb_pause_mtx(NULL, 
686                     USB_MS_TO_TICKS(usb_port_powerup_delay));
687
688                 /* reset port, which implies enabling it */
689
690                 err = usbd_req_reset_port(udev, NULL, portno);
691
692                 if (err) {
693                         DPRINTFN(0, "port %d reset "
694                             "failed, error=%s\n",
695                             portno, usbd_errstr(err));
696                         goto error;
697                 }
698                 /* get port status again, it might have changed during reset */
699
700                 err = uhub_read_port_status(sc, portno);
701                 if (err) {
702                         goto error;
703                 }
704                 /* check if something changed during port reset */
705
706                 if ((sc->sc_st.port_change & UPS_C_CONNECT_STATUS) ||
707                     (!(sc->sc_st.port_status & UPS_CURRENT_CONNECT_STATUS))) {
708                         if (timeout) {
709                                 DPRINTFN(0, "giving up port reset "
710                                     "- device vanished\n");
711                                 goto error;
712                         }
713                         timeout = 1;
714                         goto repeat;
715                 }
716         } else {
717                 DPRINTF("Port %d is in Device Mode\n", portno);
718         }
719
720         /*
721          * Figure out the device speed
722          */
723         switch (udev->speed) {
724         case USB_SPEED_HIGH:
725                 if (sc->sc_st.port_status & UPS_HIGH_SPEED)
726                         speed = USB_SPEED_HIGH;
727                 else if (sc->sc_st.port_status & UPS_LOW_SPEED)
728                         speed = USB_SPEED_LOW;
729                 else
730                         speed = USB_SPEED_FULL;
731                 break;
732         case USB_SPEED_FULL:
733                 if (sc->sc_st.port_status & UPS_LOW_SPEED)
734                         speed = USB_SPEED_LOW;
735                 else
736                         speed = USB_SPEED_FULL;
737                 break;
738         case USB_SPEED_LOW:
739                 speed = USB_SPEED_LOW;
740                 break;
741         case USB_SPEED_SUPER:
742                 if (udev->parent_hub == NULL) {
743                         /* Root HUB - special case */
744                         switch (sc->sc_st.port_status & UPS_OTHER_SPEED) {
745                         case 0:
746                                 speed = USB_SPEED_FULL;
747                                 break;
748                         case UPS_LOW_SPEED:
749                                 speed = USB_SPEED_LOW;
750                                 break;
751                         case UPS_HIGH_SPEED:
752                                 speed = USB_SPEED_HIGH;
753                                 break;
754                         default:
755                                 speed = USB_SPEED_SUPER;
756                                 break;
757                         }
758                 } else {
759                         speed = USB_SPEED_SUPER;
760                 }
761                 break;
762         default:
763                 /* same speed like parent */
764                 speed = udev->speed;
765                 break;
766         }
767         if (speed == USB_SPEED_SUPER) {
768                 err = usbd_req_set_hub_u1_timeout(udev, NULL,
769                     portno, 128 - (2 * udev->depth));
770                 if (err) {
771                         DPRINTFN(0, "port %d U1 timeout "
772                             "failed, error=%s\n",
773                             portno, usbd_errstr(err));
774                 }
775                 err = usbd_req_set_hub_u2_timeout(udev, NULL,
776                     portno, 128 - (2 * udev->depth));
777                 if (err) {
778                         DPRINTFN(0, "port %d U2 timeout "
779                             "failed, error=%s\n",
780                             portno, usbd_errstr(err));
781                 }
782         }
783
784         /*
785          * Figure out the device mode
786          *
787          * NOTE: This part is currently FreeBSD specific.
788          */
789         if (sc->sc_st.port_status & UPS_PORT_MODE_DEVICE)
790                 mode = USB_MODE_DEVICE;
791         else
792                 mode = USB_MODE_HOST;
793
794         /* need to create a new child */
795         child = usb_alloc_device(sc->sc_dev, udev->bus, udev,
796             udev->depth + 1, portno - 1, portno, speed, mode);
797         if (child == NULL) {
798                 DPRINTFN(0, "could not allocate new device\n");
799                 goto error;
800         }
801         return (0);                     /* success */
802
803 error:
804         if (child != NULL) {
805                 /*
806                  * Free USB device and all subdevices, if any.
807                  */
808                 usb_free_device(child, 0);
809                 child = NULL;
810         }
811         if (err == 0) {
812                 if (sc->sc_st.port_status & UPS_PORT_ENABLED) {
813                         err = usbd_req_clear_port_feature(
814                             sc->sc_udev, NULL,
815                             portno, UHF_PORT_ENABLE);
816                 }
817         }
818         if (err) {
819                 DPRINTFN(0, "device problem (%s), "
820                     "disabling port %d\n", usbd_errstr(err), portno);
821         }
822         return (err);
823 }
824
825 /*------------------------------------------------------------------------*
826  *      usb_device_20_compatible
827  *
828  * Returns:
829  *    0: HUB does not support suspend and resume
830  * Else: HUB supports suspend and resume
831  *------------------------------------------------------------------------*/
832 static uint8_t
833 usb_device_20_compatible(struct usb_device *udev)
834 {
835         if (udev == NULL)
836                 return (0);
837         switch (udev->speed) {
838         case USB_SPEED_LOW:
839         case USB_SPEED_FULL:
840         case USB_SPEED_HIGH:
841                 return (1);
842         default:
843                 return (0);
844         }
845 }
846
847 /*------------------------------------------------------------------------*
848  *      uhub_suspend_resume_port
849  *
850  * Returns:
851  *    0: Success
852  * Else: A control transaction failed
853  *------------------------------------------------------------------------*/
854 static usb_error_t
855 uhub_suspend_resume_port(struct uhub_softc *sc, uint8_t portno)
856 {
857         struct usb_device *child;
858         struct usb_device *udev;
859         uint8_t is_suspend;
860         usb_error_t err;
861
862         DPRINTF("port %d\n", portno);
863
864         udev = sc->sc_udev;
865         child = usb_bus_port_get_device(udev->bus,
866             udev->hub->ports + portno - 1);
867
868         /* first clear the port suspend change bit */
869
870         if (usb_device_20_compatible(udev)) {
871                 err = usbd_req_clear_port_feature(udev, NULL,
872                     portno, UHF_C_PORT_SUSPEND);
873         } else {
874                 err = usbd_req_clear_port_feature(udev, NULL,
875                     portno, UHF_C_PORT_LINK_STATE);
876         }
877
878         if (err) {
879                 DPRINTF("clearing suspend failed.\n");
880                 goto done;
881         }
882         /* get fresh status */
883
884         err = uhub_read_port_status(sc, portno);
885         if (err) {
886                 DPRINTF("reading port status failed.\n");
887                 goto done;
888         }
889         /* convert current state */
890
891         if (usb_device_20_compatible(udev)) {
892                 if (sc->sc_st.port_status & UPS_SUSPEND) {
893                         is_suspend = 1;
894                 } else {
895                         is_suspend = 0;
896                 }
897         } else {
898                 switch (UPS_PORT_LINK_STATE_GET(sc->sc_st.port_status)) {
899                 case UPS_PORT_LS_U3:
900                         is_suspend = 1;
901                         break;
902                 case UPS_PORT_LS_SS_INA:
903                         usbd_req_warm_reset_port(udev, NULL, portno);
904                         is_suspend = 0;
905                         break;
906                 default:
907                         is_suspend = 0;
908                         break;
909                 }
910         }
911
912         DPRINTF("suspended=%u\n", is_suspend);
913
914         /* do the suspend or resume */
915
916         if (child) {
917                 /*
918                  * This code handle two cases: 1) Host Mode - we can only
919                  * receive resume here 2) Device Mode - we can receive
920                  * suspend and resume here
921                  */
922                 if (is_suspend == 0)
923                         usb_dev_resume_peer(child);
924                 else if (child->flags.usb_mode == USB_MODE_DEVICE)
925                         usb_dev_suspend_peer(child);
926         }
927 done:
928         return (err);
929 }
930
931 /*------------------------------------------------------------------------*
932  *      uhub_root_interrupt
933  *
934  * This function is called when a Root HUB interrupt has
935  * happened. "ptr" and "len" makes up the Root HUB interrupt
936  * packet. This function is called having the "bus_mtx" locked.
937  *------------------------------------------------------------------------*/
938 void
939 uhub_root_intr(struct usb_bus *bus, const uint8_t *ptr, uint8_t len)
940 {
941         USB_BUS_LOCK_ASSERT(bus, MA_OWNED);
942
943         usb_needs_explore(bus, 0);
944 }
945
946 static uint8_t
947 uhub_is_too_deep(struct usb_device *udev)
948 {
949         switch (udev->speed) {
950         case USB_SPEED_FULL:
951         case USB_SPEED_LOW:
952         case USB_SPEED_HIGH:
953                 if (udev->depth > USB_HUB_MAX_DEPTH)
954                         return (1);
955                 break;
956         case USB_SPEED_SUPER:
957                 if (udev->depth > USB_SS_HUB_DEPTH_MAX)
958                         return (1);
959                 break;
960         default:
961                 break;
962         }
963         return (0);
964 }
965
966 /*------------------------------------------------------------------------*
967  *      uhub_explore
968  *
969  * Returns:
970  *     0: Success
971  *  Else: Failure
972  *------------------------------------------------------------------------*/
973 static usb_error_t
974 uhub_explore(struct usb_device *udev)
975 {
976         struct usb_hub *hub;
977         struct uhub_softc *sc;
978         struct usb_port *up;
979         usb_error_t err;
980         uint8_t portno;
981         uint8_t x;
982         uint8_t do_unlock;
983
984         hub = udev->hub;
985         sc = hub->hubsoftc;
986
987         DPRINTFN(11, "udev=%p addr=%d\n", udev, udev->address);
988
989         /* ignore devices that are too deep */
990         if (uhub_is_too_deep(udev))
991                 return (USB_ERR_TOO_DEEP);
992
993         /* check if device is suspended */
994         if (udev->flags.self_suspended) {
995                 /* need to wait until the child signals resume */
996                 DPRINTF("Device is suspended!\n");
997                 return (0);
998         }
999
1000         /*
1001          * Make sure we don't race against user-space applications
1002          * like LibUSB:
1003          */
1004         do_unlock = usbd_enum_lock(udev);
1005
1006         for (x = 0; x != hub->nports; x++) {
1007                 up = hub->ports + x;
1008                 portno = x + 1;
1009
1010                 err = uhub_read_port_status(sc, portno);
1011                 if (err) {
1012                         /* most likely the HUB is gone */
1013                         break;
1014                 }
1015                 if (sc->sc_st.port_change & UPS_C_OVERCURRENT_INDICATOR) {
1016                         DPRINTF("Overcurrent on port %u.\n", portno);
1017                         err = usbd_req_clear_port_feature(
1018                             udev, NULL, portno, UHF_C_PORT_OVER_CURRENT);
1019                         if (err) {
1020                                 /* most likely the HUB is gone */
1021                                 break;
1022                         }
1023                 }
1024                 if (!(sc->sc_flags & UHUB_FLAG_DID_EXPLORE)) {
1025                         /*
1026                          * Fake a connect status change so that the
1027                          * status gets checked initially!
1028                          */
1029                         sc->sc_st.port_change |=
1030                             UPS_C_CONNECT_STATUS;
1031                 }
1032                 if (sc->sc_st.port_change & UPS_C_PORT_ENABLED) {
1033                         err = usbd_req_clear_port_feature(
1034                             udev, NULL, portno, UHF_C_PORT_ENABLE);
1035                         if (err) {
1036                                 /* most likely the HUB is gone */
1037                                 break;
1038                         }
1039                         if (sc->sc_st.port_change & UPS_C_CONNECT_STATUS) {
1040                                 /*
1041                                  * Ignore the port error if the device
1042                                  * has vanished !
1043                                  */
1044                         } else if (sc->sc_st.port_status & UPS_PORT_ENABLED) {
1045                                 DPRINTFN(0, "illegal enable change, "
1046                                     "port %d\n", portno);
1047                         } else {
1048
1049                                 if (up->restartcnt == USB_RESTART_MAX) {
1050                                         /* XXX could try another speed ? */
1051                                         DPRINTFN(0, "port error, giving up "
1052                                             "port %d\n", portno);
1053                                 } else {
1054                                         sc->sc_st.port_change |=
1055                                             UPS_C_CONNECT_STATUS;
1056                                         up->restartcnt++;
1057                                 }
1058                         }
1059                 }
1060                 if (sc->sc_st.port_change & UPS_C_CONNECT_STATUS) {
1061                         err = uhub_reattach_port(sc, portno);
1062                         if (err) {
1063                                 /* most likely the HUB is gone */
1064                                 break;
1065                         }
1066                 }
1067                 if (sc->sc_st.port_change & (UPS_C_SUSPEND |
1068                     UPS_C_PORT_LINK_STATE)) {
1069                         err = uhub_suspend_resume_port(sc, portno);
1070                         if (err) {
1071                                 /* most likely the HUB is gone */
1072                                 break;
1073                         }
1074                 }
1075                 err = uhub_explore_sub(sc, up);
1076                 if (err) {
1077                         /* no device(s) present */
1078                         continue;
1079                 }
1080                 /* explore succeeded - reset restart counter */
1081                 up->restartcnt = 0;
1082         }
1083
1084         if (do_unlock)
1085                 usbd_enum_unlock(udev);
1086
1087         /* initial status checked */
1088         sc->sc_flags |= UHUB_FLAG_DID_EXPLORE;
1089
1090         /* return success */
1091         return (USB_ERR_NORMAL_COMPLETION);
1092 }
1093
1094 static int
1095 uhub_probe(device_t dev)
1096 {
1097         struct usb_attach_arg *uaa = device_get_ivars(dev);
1098
1099         if (uaa->usb_mode != USB_MODE_HOST)
1100                 return (ENXIO);
1101
1102         /*
1103          * The subclass for USB HUBs is currently ignored because it
1104          * is 0 for some and 1 for others.
1105          */
1106         if (uaa->info.bConfigIndex == 0 &&
1107             uaa->info.bDeviceClass == UDCLASS_HUB)
1108                 return (0);
1109
1110         return (ENXIO);
1111 }
1112
1113 /* NOTE: The information returned by this function can be wrong. */
1114 usb_error_t
1115 uhub_query_info(struct usb_device *udev, uint8_t *pnports, uint8_t *ptt)
1116 {
1117         struct usb_hub_descriptor hubdesc20;
1118         struct usb_hub_ss_descriptor hubdesc30;
1119         usb_error_t err;
1120         uint8_t nports;
1121         uint8_t tt;
1122
1123         if (udev->ddesc.bDeviceClass != UDCLASS_HUB)
1124                 return (USB_ERR_INVAL);
1125
1126         nports = 0;
1127         tt = 0;
1128
1129         switch (udev->speed) {
1130         case USB_SPEED_LOW:
1131         case USB_SPEED_FULL:
1132         case USB_SPEED_HIGH:
1133                 /* assuming that there is one port */
1134                 err = usbd_req_get_hub_descriptor(udev, NULL, &hubdesc20, 1);
1135                 if (err) {
1136                         DPRINTFN(0, "getting USB 2.0 HUB descriptor failed,"
1137                             "error=%s\n", usbd_errstr(err));
1138                         break;
1139                 }
1140                 nports = hubdesc20.bNbrPorts;
1141                 if (nports > 127)
1142                         nports = 127;
1143
1144                 if (udev->speed == USB_SPEED_HIGH)
1145                         tt = (UGETW(hubdesc20.wHubCharacteristics) >> 5) & 3;
1146                 break;
1147
1148         case USB_SPEED_SUPER:
1149                 err = usbd_req_get_ss_hub_descriptor(udev, NULL, &hubdesc30, 1);
1150                 if (err) {
1151                         DPRINTFN(0, "Getting USB 3.0 HUB descriptor failed,"
1152                             "error=%s\n", usbd_errstr(err));
1153                         break;
1154                 }
1155                 nports = hubdesc30.bNbrPorts;
1156                 if (nports > 16)
1157                         nports = 16;
1158                 break;
1159
1160         default:
1161                 err = USB_ERR_INVAL;
1162                 break;
1163         }
1164
1165         if (pnports != NULL)
1166                 *pnports = nports;
1167
1168         if (ptt != NULL)
1169                 *ptt = tt;
1170
1171         return (err);
1172 }
1173
1174 static int
1175 uhub_attach(device_t dev)
1176 {
1177         struct uhub_softc *sc = device_get_softc(dev);
1178         struct usb_attach_arg *uaa = device_get_ivars(dev);
1179         struct usb_device *udev = uaa->device;
1180         struct usb_device *parent_hub = udev->parent_hub;
1181         struct usb_hub *hub;
1182         struct usb_hub_descriptor hubdesc20;
1183         struct usb_hub_ss_descriptor hubdesc30;
1184         uint16_t pwrdly;
1185         uint8_t x;
1186         uint8_t nports;
1187         uint8_t portno;
1188         uint8_t removable;
1189         uint8_t iface_index;
1190         usb_error_t err;
1191
1192         sc->sc_udev = udev;
1193         sc->sc_dev = dev;
1194
1195         mtx_init(&sc->sc_mtx, "USB HUB mutex", NULL, MTX_DEF);
1196
1197         snprintf(sc->sc_name, sizeof(sc->sc_name), "%s",
1198             device_get_nameunit(dev));
1199
1200         device_set_usb_desc(dev);
1201
1202         DPRINTFN(2, "depth=%d selfpowered=%d, parent=%p, "
1203             "parent->selfpowered=%d\n",
1204             udev->depth,
1205             udev->flags.self_powered,
1206             parent_hub,
1207             parent_hub ?
1208             parent_hub->flags.self_powered : 0);
1209
1210         if (uhub_is_too_deep(udev)) {
1211                 DPRINTFN(0, "HUB at depth %d, "
1212                     "exceeds maximum. HUB ignored\n", (int)udev->depth);
1213                 goto error;
1214         }
1215
1216         if (!udev->flags.self_powered && parent_hub &&
1217             !parent_hub->flags.self_powered) {
1218                 DPRINTFN(0, "Bus powered HUB connected to "
1219                     "bus powered HUB. HUB ignored\n");
1220                 goto error;
1221         }
1222
1223         if (UHUB_IS_MULTI_TT(sc)) {
1224                 err = usbd_set_alt_interface_index(udev, 0, 1);
1225                 if (err) {
1226                         device_printf(dev, "MTT could not be enabled\n");
1227                         goto error;
1228                 }
1229                 device_printf(dev, "MTT enabled\n");
1230         }
1231
1232         /* get HUB descriptor */
1233
1234         DPRINTFN(2, "Getting HUB descriptor\n");
1235
1236         switch (udev->speed) {
1237         case USB_SPEED_LOW:
1238         case USB_SPEED_FULL:
1239         case USB_SPEED_HIGH:
1240                 /* assuming that there is one port */
1241                 err = usbd_req_get_hub_descriptor(udev, NULL, &hubdesc20, 1);
1242                 if (err) {
1243                         DPRINTFN(0, "getting USB 2.0 HUB descriptor failed,"
1244                             "error=%s\n", usbd_errstr(err));
1245                         goto error;
1246                 }
1247                 /* get number of ports */
1248                 nports = hubdesc20.bNbrPorts;
1249
1250                 /* get power delay */
1251                 pwrdly = ((hubdesc20.bPwrOn2PwrGood * UHD_PWRON_FACTOR) +
1252                     usb_extra_power_up_time);
1253
1254                 /* get complete HUB descriptor */
1255                 if (nports >= 8) {
1256                         /* check number of ports */
1257                         if (nports > 127) {
1258                                 DPRINTFN(0, "Invalid number of USB 2.0 ports,"
1259                                     "error=%s\n", usbd_errstr(err));
1260                                 goto error;
1261                         }
1262                         /* get complete HUB descriptor */
1263                         err = usbd_req_get_hub_descriptor(udev, NULL, &hubdesc20, nports);
1264
1265                         if (err) {
1266                                 DPRINTFN(0, "Getting USB 2.0 HUB descriptor failed,"
1267                                     "error=%s\n", usbd_errstr(err));
1268                                 goto error;
1269                         }
1270                         if (hubdesc20.bNbrPorts != nports) {
1271                                 DPRINTFN(0, "Number of ports changed\n");
1272                                 goto error;
1273                         }
1274                 }
1275                 break;
1276         case USB_SPEED_SUPER:
1277                 if (udev->parent_hub != NULL) {
1278                         err = usbd_req_set_hub_depth(udev, NULL,
1279                             udev->depth - 1);
1280                         if (err) {
1281                                 DPRINTFN(0, "Setting USB 3.0 HUB depth failed,"
1282                                     "error=%s\n", usbd_errstr(err));
1283                                 goto error;
1284                         }
1285                 }
1286                 err = usbd_req_get_ss_hub_descriptor(udev, NULL, &hubdesc30, 1);
1287                 if (err) {
1288                         DPRINTFN(0, "Getting USB 3.0 HUB descriptor failed,"
1289                             "error=%s\n", usbd_errstr(err));
1290                         goto error;
1291                 }
1292                 /* get number of ports */
1293                 nports = hubdesc30.bNbrPorts;
1294
1295                 /* get power delay */
1296                 pwrdly = ((hubdesc30.bPwrOn2PwrGood * UHD_PWRON_FACTOR) +
1297                     usb_extra_power_up_time);
1298
1299                 /* get complete HUB descriptor */
1300                 if (nports >= 8) {
1301                         /* check number of ports */
1302                         if (nports > ((udev->parent_hub != NULL) ? 15 : 127)) {
1303                                 DPRINTFN(0, "Invalid number of USB 3.0 ports,"
1304                                     "error=%s\n", usbd_errstr(err));
1305                                 goto error;
1306                         }
1307                         /* get complete HUB descriptor */
1308                         err = usbd_req_get_ss_hub_descriptor(udev, NULL, &hubdesc30, nports);
1309
1310                         if (err) {
1311                                 DPRINTFN(0, "Getting USB 2.0 HUB descriptor failed,"
1312                                     "error=%s\n", usbd_errstr(err));
1313                                 goto error;
1314                         }
1315                         if (hubdesc30.bNbrPorts != nports) {
1316                                 DPRINTFN(0, "Number of ports changed\n");
1317                                 goto error;
1318                         }
1319                 }
1320                 break;
1321         default:
1322                 DPRINTF("Assuming HUB has only one port\n");
1323                 /* default number of ports */
1324                 nports = 1;
1325                 /* default power delay */
1326                 pwrdly = ((10 * UHD_PWRON_FACTOR) + usb_extra_power_up_time);
1327                 break;
1328         }
1329         if (nports == 0) {
1330                 DPRINTFN(0, "portless HUB\n");
1331                 goto error;
1332         }
1333         hub = malloc(sizeof(hub[0]) + (sizeof(hub->ports[0]) * nports),
1334             M_USBDEV, M_WAITOK | M_ZERO);
1335
1336         if (hub == NULL) {
1337                 goto error;
1338         }
1339         udev->hub = hub;
1340
1341         /* initialize HUB structure */
1342         hub->hubsoftc = sc;
1343         hub->explore = &uhub_explore;
1344         hub->nports = nports;
1345         hub->hubudev = udev;
1346 #if USB_HAVE_TT_SUPPORT
1347         hub->tt_msg[0].hdr.pm_callback = &uhub_reset_tt_proc;
1348         hub->tt_msg[0].udev = udev;
1349         hub->tt_msg[1].hdr.pm_callback = &uhub_reset_tt_proc;
1350         hub->tt_msg[1].udev = udev;
1351 #endif
1352         /* if self powered hub, give ports maximum current */
1353         if (udev->flags.self_powered) {
1354                 hub->portpower = USB_MAX_POWER;
1355         } else {
1356                 hub->portpower = USB_MIN_POWER;
1357         }
1358
1359         /* set up interrupt pipe */
1360         iface_index = 0;
1361         if (udev->parent_hub == NULL) {
1362                 /* root HUB is special */
1363                 err = 0;
1364         } else {
1365                 /* normal HUB */
1366                 err = usbd_transfer_setup(udev, &iface_index, sc->sc_xfer,
1367                     uhub_config, UHUB_N_TRANSFER, sc, &sc->sc_mtx);
1368         }
1369         if (err) {
1370                 DPRINTFN(0, "cannot setup interrupt transfer, "
1371                     "errstr=%s\n", usbd_errstr(err));
1372                 goto error;
1373         }
1374         /* wait with power off for a while */
1375         usb_pause_mtx(NULL, USB_MS_TO_TICKS(USB_POWER_DOWN_TIME));
1376
1377         /*
1378          * To have the best chance of success we do things in the exact same
1379          * order as Windoze98.  This should not be necessary, but some
1380          * devices do not follow the USB specs to the letter.
1381          *
1382          * These are the events on the bus when a hub is attached:
1383          *  Get device and config descriptors (see attach code)
1384          *  Get hub descriptor (see above)
1385          *  For all ports
1386          *     turn on power
1387          *     wait for power to become stable
1388          * (all below happens in explore code)
1389          *  For all ports
1390          *     clear C_PORT_CONNECTION
1391          *  For all ports
1392          *     get port status
1393          *     if device connected
1394          *        wait 100 ms
1395          *        turn on reset
1396          *        wait
1397          *        clear C_PORT_RESET
1398          *        get port status
1399          *        proceed with device attachment
1400          */
1401
1402         /* XXX should check for none, individual, or ganged power? */
1403
1404         removable = 0;
1405
1406         for (x = 0; x != nports; x++) {
1407                 /* set up data structures */
1408                 struct usb_port *up = hub->ports + x;
1409
1410                 up->device_index = 0;
1411                 up->restartcnt = 0;
1412                 portno = x + 1;
1413
1414                 /* check if port is removable */
1415                 switch (udev->speed) {
1416                 case USB_SPEED_LOW:
1417                 case USB_SPEED_FULL:
1418                 case USB_SPEED_HIGH:
1419                         if (!UHD_NOT_REMOV(&hubdesc20, portno))
1420                                 removable++;
1421                         break;
1422                 case USB_SPEED_SUPER:
1423                         if (!UHD_NOT_REMOV(&hubdesc30, portno))
1424                                 removable++;
1425                         break;
1426                 default:
1427                         DPRINTF("Assuming removable port\n");
1428                         removable++;
1429                         break;
1430                 }
1431                 if (!err) {
1432                         /* turn the power on */
1433                         err = usbd_req_set_port_feature(udev, NULL,
1434                             portno, UHF_PORT_POWER);
1435                 }
1436                 if (err) {
1437                         DPRINTFN(0, "port %d power on failed, %s\n",
1438                             portno, usbd_errstr(err));
1439                 }
1440                 DPRINTF("turn on port %d power\n",
1441                     portno);
1442
1443                 /* wait for stable power */
1444                 usb_pause_mtx(NULL, USB_MS_TO_TICKS(pwrdly));
1445         }
1446
1447         device_printf(dev, "%d port%s with %d "
1448             "removable, %s powered\n", nports, (nports != 1) ? "s" : "",
1449             removable, udev->flags.self_powered ? "self" : "bus");
1450
1451         /* Start the interrupt endpoint, if any */
1452
1453         mtx_lock(&sc->sc_mtx);
1454         usbd_transfer_start(sc->sc_xfer[UHUB_INTR_TRANSFER]);
1455         mtx_unlock(&sc->sc_mtx);
1456
1457         /* Enable automatic power save on all USB HUBs */
1458
1459         usbd_set_power_mode(udev, USB_POWER_MODE_SAVE);
1460
1461         return (0);
1462
1463 error:
1464         usbd_transfer_unsetup(sc->sc_xfer, UHUB_N_TRANSFER);
1465
1466         if (udev->hub) {
1467                 free(udev->hub, M_USBDEV);
1468                 udev->hub = NULL;
1469         }
1470
1471         mtx_destroy(&sc->sc_mtx);
1472
1473         return (ENXIO);
1474 }
1475
1476 /*
1477  * Called from process context when the hub is gone.
1478  * Detach all devices on active ports.
1479  */
1480 static int
1481 uhub_detach(device_t dev)
1482 {
1483         struct uhub_softc *sc = device_get_softc(dev);
1484         struct usb_hub *hub = sc->sc_udev->hub;
1485         struct usb_bus *bus = sc->sc_udev->bus;
1486         struct usb_device *child;
1487         uint8_t x;
1488
1489         if (hub == NULL)                /* must be partially working */
1490                 return (0);
1491
1492         /* Make sure interrupt transfer is gone. */
1493         usbd_transfer_unsetup(sc->sc_xfer, UHUB_N_TRANSFER);
1494
1495         /* Detach all ports */
1496         for (x = 0; x != hub->nports; x++) {
1497
1498                 child = usb_bus_port_get_device(bus, hub->ports + x);
1499
1500                 if (child == NULL) {
1501                         continue;
1502                 }
1503
1504                 /*
1505                  * Free USB device and all subdevices, if any.
1506                  */
1507                 usb_free_device(child, 0);
1508         }
1509
1510 #if USB_HAVE_TT_SUPPORT
1511         /* Make sure our TT messages are not queued anywhere */
1512         USB_BUS_LOCK(bus);
1513         usb_proc_mwait(&bus->non_giant_callback_proc,
1514             &hub->tt_msg[0], &hub->tt_msg[1]);
1515         USB_BUS_UNLOCK(bus);
1516 #endif
1517
1518         free(hub, M_USBDEV);
1519         sc->sc_udev->hub = NULL;
1520
1521         mtx_destroy(&sc->sc_mtx);
1522
1523         return (0);
1524 }
1525
1526 static int
1527 uhub_suspend(device_t dev)
1528 {
1529         DPRINTF("\n");
1530         /* Sub-devices are not suspended here! */
1531         return (0);
1532 }
1533
1534 static int
1535 uhub_resume(device_t dev)
1536 {
1537         DPRINTF("\n");
1538         /* Sub-devices are not resumed here! */
1539         return (0);
1540 }
1541
1542 static void
1543 uhub_driver_added(device_t dev, driver_t *driver)
1544 {
1545         usb_needs_explore_all();
1546 }
1547
1548 struct hub_result {
1549         struct usb_device *udev;
1550         uint8_t portno;
1551         uint8_t iface_index;
1552 };
1553
1554 static void
1555 uhub_find_iface_index(struct usb_hub *hub, device_t child,
1556     struct hub_result *res)
1557 {
1558         struct usb_interface *iface;
1559         struct usb_device *udev;
1560         uint8_t nports;
1561         uint8_t x;
1562         uint8_t i;
1563
1564         nports = hub->nports;
1565         for (x = 0; x != nports; x++) {
1566                 udev = usb_bus_port_get_device(hub->hubudev->bus,
1567                     hub->ports + x);
1568                 if (!udev) {
1569                         continue;
1570                 }
1571                 for (i = 0; i != USB_IFACE_MAX; i++) {
1572                         iface = usbd_get_iface(udev, i);
1573                         if (iface &&
1574                             (iface->subdev == child)) {
1575                                 res->iface_index = i;
1576                                 res->udev = udev;
1577                                 res->portno = x + 1;
1578                                 return;
1579                         }
1580                 }
1581         }
1582         res->iface_index = 0;
1583         res->udev = NULL;
1584         res->portno = 0;
1585 }
1586
1587 static int
1588 uhub_child_location_string(device_t parent, device_t child,
1589     char *buf, size_t buflen)
1590 {
1591         struct uhub_softc *sc;
1592         struct usb_hub *hub;
1593         struct hub_result res;
1594
1595         if (!device_is_attached(parent)) {
1596                 if (buflen)
1597                         buf[0] = 0;
1598                 return (0);
1599         }
1600
1601         sc = device_get_softc(parent);
1602         hub = sc->sc_udev->hub;
1603
1604         mtx_lock(&Giant);
1605         uhub_find_iface_index(hub, child, &res);
1606         if (!res.udev) {
1607                 DPRINTF("device not on hub\n");
1608                 if (buflen) {
1609                         buf[0] = '\0';
1610                 }
1611                 goto done;
1612         }
1613         snprintf(buf, buflen, "bus=%u hubaddr=%u port=%u devaddr=%u interface=%u",
1614             (res.udev->parent_hub != NULL) ? res.udev->parent_hub->device_index : 0,
1615             res.portno, device_get_unit(res.udev->bus->bdev),
1616             res.udev->device_index, res.iface_index);
1617 done:
1618         mtx_unlock(&Giant);
1619
1620         return (0);
1621 }
1622
1623 static int
1624 uhub_child_pnpinfo_string(device_t parent, device_t child,
1625     char *buf, size_t buflen)
1626 {
1627         struct uhub_softc *sc;
1628         struct usb_hub *hub;
1629         struct usb_interface *iface;
1630         struct hub_result res;
1631
1632         if (!device_is_attached(parent)) {
1633                 if (buflen)
1634                         buf[0] = 0;
1635                 return (0);
1636         }
1637
1638         sc = device_get_softc(parent);
1639         hub = sc->sc_udev->hub;
1640
1641         mtx_lock(&Giant);
1642         uhub_find_iface_index(hub, child, &res);
1643         if (!res.udev) {
1644                 DPRINTF("device not on hub\n");
1645                 if (buflen) {
1646                         buf[0] = '\0';
1647                 }
1648                 goto done;
1649         }
1650         iface = usbd_get_iface(res.udev, res.iface_index);
1651         if (iface && iface->idesc) {
1652                 snprintf(buf, buflen, "vendor=0x%04x product=0x%04x "
1653                     "devclass=0x%02x devsubclass=0x%02x "
1654                     "sernum=\"%s\" "
1655                     "release=0x%04x "
1656                     "mode=%s "
1657                     "intclass=0x%02x intsubclass=0x%02x "
1658                     "intprotocol=0x%02x " "%s%s",
1659                     UGETW(res.udev->ddesc.idVendor),
1660                     UGETW(res.udev->ddesc.idProduct),
1661                     res.udev->ddesc.bDeviceClass,
1662                     res.udev->ddesc.bDeviceSubClass,
1663                     usb_get_serial(res.udev),
1664                     UGETW(res.udev->ddesc.bcdDevice),
1665                     (res.udev->flags.usb_mode == USB_MODE_HOST) ? "host" : "device",
1666                     iface->idesc->bInterfaceClass,
1667                     iface->idesc->bInterfaceSubClass,
1668                     iface->idesc->bInterfaceProtocol,
1669                     iface->pnpinfo ? " " : "",
1670                     iface->pnpinfo ? iface->pnpinfo : "");
1671         } else {
1672                 if (buflen) {
1673                         buf[0] = '\0';
1674                 }
1675                 goto done;
1676         }
1677 done:
1678         mtx_unlock(&Giant);
1679
1680         return (0);
1681 }
1682
1683 /*
1684  * The USB Transaction Translator:
1685  * ===============================
1686  *
1687  * When doing LOW- and FULL-speed USB transfers accross a HIGH-speed
1688  * USB HUB, bandwidth must be allocated for ISOCHRONOUS and INTERRUPT
1689  * USB transfers. To utilize bandwidth dynamically the "scatter and
1690  * gather" principle must be applied. This means that bandwidth must
1691  * be divided into equal parts of bandwidth. With regard to USB all
1692  * data is transferred in smaller packets with length
1693  * "wMaxPacketSize". The problem however is that "wMaxPacketSize" is
1694  * not a constant!
1695  *
1696  * The bandwidth scheduler which I have implemented will simply pack
1697  * the USB transfers back to back until there is no more space in the
1698  * schedule. Out of the 8 microframes which the USB 2.0 standard
1699  * provides, only 6 are available for non-HIGH-speed devices. I have
1700  * reserved the first 4 microframes for ISOCHRONOUS transfers. The
1701  * last 2 microframes I have reserved for INTERRUPT transfers. Without
1702  * this division, it is very difficult to allocate and free bandwidth
1703  * dynamically.
1704  *
1705  * NOTE about the Transaction Translator in USB HUBs:
1706  *
1707  * USB HUBs have a very simple Transaction Translator, that will
1708  * simply pipeline all the SPLIT transactions. That means that the
1709  * transactions will be executed in the order they are queued!
1710  *
1711  */
1712
1713 /*------------------------------------------------------------------------*
1714  *      usb_intr_find_best_slot
1715  *
1716  * Return value:
1717  *   The best Transaction Translation slot for an interrupt endpoint.
1718  *------------------------------------------------------------------------*/
1719 static uint8_t
1720 usb_intr_find_best_slot(usb_size_t *ptr, uint8_t start,
1721     uint8_t end, uint8_t mask)
1722 {
1723         usb_size_t min = (usb_size_t)-1;
1724         usb_size_t sum;
1725         uint8_t x;
1726         uint8_t y;
1727         uint8_t z;
1728
1729         y = 0;
1730
1731         /* find the last slot with lesser used bandwidth */
1732
1733         for (x = start; x < end; x++) {
1734
1735                 sum = 0;
1736
1737                 /* compute sum of bandwidth */
1738                 for (z = x; z < end; z++) {
1739                         if (mask & (1U << (z - x)))
1740                                 sum += ptr[z];
1741                 }
1742
1743                 /* check if the current multi-slot is more optimal */
1744                 if (min >= sum) {
1745                         min = sum;
1746                         y = x;
1747                 }
1748
1749                 /* check if the mask is about to be shifted out */
1750                 if (mask & (1U << (end - 1 - x)))
1751                         break;
1752         }
1753         return (y);
1754 }
1755
1756 /*------------------------------------------------------------------------*
1757  *      usb_hs_bandwidth_adjust
1758  *
1759  * This function will update the bandwith usage for the microframe
1760  * having index "slot" by "len" bytes. "len" can be negative.  If the
1761  * "slot" argument is greater or equal to "USB_HS_MICRO_FRAMES_MAX"
1762  * the "slot" argument will be replaced by the slot having least used
1763  * bandwidth. The "mask" argument is used for multi-slot allocations.
1764  *
1765  * Returns:
1766  *    The slot in which the bandwidth update was done: 0..7
1767  *------------------------------------------------------------------------*/
1768 static uint8_t
1769 usb_hs_bandwidth_adjust(struct usb_device *udev, int16_t len,
1770     uint8_t slot, uint8_t mask)
1771 {
1772         struct usb_bus *bus = udev->bus;
1773         struct usb_hub *hub;
1774         enum usb_dev_speed speed;
1775         uint8_t x;
1776
1777         USB_BUS_LOCK_ASSERT(bus, MA_OWNED);
1778
1779         speed = usbd_get_speed(udev);
1780
1781         switch (speed) {
1782         case USB_SPEED_LOW:
1783         case USB_SPEED_FULL:
1784                 if (speed == USB_SPEED_LOW) {
1785                         len *= 8;
1786                 }
1787                 /*
1788                  * The Host Controller Driver should have
1789                  * performed checks so that the lookup
1790                  * below does not result in a NULL pointer
1791                  * access.
1792                  */
1793
1794                 hub = udev->parent_hs_hub->hub;
1795                 if (slot >= USB_HS_MICRO_FRAMES_MAX) {
1796                         slot = usb_intr_find_best_slot(hub->uframe_usage,
1797                             USB_FS_ISOC_UFRAME_MAX, 6, mask);
1798                 }
1799                 for (x = slot; x < 8; x++) {
1800                         if (mask & (1U << (x - slot))) {
1801                                 hub->uframe_usage[x] += len;
1802                                 bus->uframe_usage[x] += len;
1803                         }
1804                 }
1805                 break;
1806         default:
1807                 if (slot >= USB_HS_MICRO_FRAMES_MAX) {
1808                         slot = usb_intr_find_best_slot(bus->uframe_usage, 0,
1809                             USB_HS_MICRO_FRAMES_MAX, mask);
1810                 }
1811                 for (x = slot; x < 8; x++) {
1812                         if (mask & (1U << (x - slot))) {
1813                                 bus->uframe_usage[x] += len;
1814                         }
1815                 }
1816                 break;
1817         }
1818         return (slot);
1819 }
1820
1821 /*------------------------------------------------------------------------*
1822  *      usb_hs_bandwidth_alloc
1823  *
1824  * This function is a wrapper function for "usb_hs_bandwidth_adjust()".
1825  *------------------------------------------------------------------------*/
1826 void
1827 usb_hs_bandwidth_alloc(struct usb_xfer *xfer)
1828 {
1829         struct usb_device *udev;
1830         uint8_t slot;
1831         uint8_t mask;
1832         uint8_t speed;
1833
1834         udev = xfer->xroot->udev;
1835
1836         if (udev->flags.usb_mode != USB_MODE_HOST)
1837                 return;         /* not supported */
1838
1839         xfer->endpoint->refcount_bw++;
1840         if (xfer->endpoint->refcount_bw != 1)
1841                 return;         /* already allocated */
1842
1843         speed = usbd_get_speed(udev);
1844
1845         switch (xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE) {
1846         case UE_INTERRUPT:
1847                 /* allocate a microframe slot */
1848
1849                 mask = 0x01;
1850                 slot = usb_hs_bandwidth_adjust(udev,
1851                     xfer->max_frame_size, USB_HS_MICRO_FRAMES_MAX, mask);
1852
1853                 xfer->endpoint->usb_uframe = slot;
1854                 xfer->endpoint->usb_smask = mask << slot;
1855
1856                 if ((speed != USB_SPEED_FULL) &&
1857                     (speed != USB_SPEED_LOW)) {
1858                         xfer->endpoint->usb_cmask = 0x00 ;
1859                 } else {
1860                         xfer->endpoint->usb_cmask = (-(0x04 << slot)) & 0xFE;
1861                 }
1862                 break;
1863
1864         case UE_ISOCHRONOUS:
1865                 switch (usbd_xfer_get_fps_shift(xfer)) {
1866                 case 0:
1867                         mask = 0xFF;
1868                         break;
1869                 case 1:
1870                         mask = 0x55;
1871                         break;
1872                 case 2:
1873                         mask = 0x11;
1874                         break;
1875                 default:
1876                         mask = 0x01;
1877                         break;
1878                 }
1879
1880                 /* allocate a microframe multi-slot */
1881
1882                 slot = usb_hs_bandwidth_adjust(udev,
1883                     xfer->max_frame_size, USB_HS_MICRO_FRAMES_MAX, mask);
1884
1885                 xfer->endpoint->usb_uframe = slot;
1886                 xfer->endpoint->usb_cmask = 0;
1887                 xfer->endpoint->usb_smask = mask << slot;
1888                 break;
1889
1890         default:
1891                 xfer->endpoint->usb_uframe = 0;
1892                 xfer->endpoint->usb_cmask = 0;
1893                 xfer->endpoint->usb_smask = 0;
1894                 break;
1895         }
1896
1897         DPRINTFN(11, "slot=%d, mask=0x%02x\n", 
1898             xfer->endpoint->usb_uframe, 
1899             xfer->endpoint->usb_smask >> xfer->endpoint->usb_uframe);
1900 }
1901
1902 /*------------------------------------------------------------------------*
1903  *      usb_hs_bandwidth_free
1904  *
1905  * This function is a wrapper function for "usb_hs_bandwidth_adjust()".
1906  *------------------------------------------------------------------------*/
1907 void
1908 usb_hs_bandwidth_free(struct usb_xfer *xfer)
1909 {
1910         struct usb_device *udev;
1911         uint8_t slot;
1912         uint8_t mask;
1913
1914         udev = xfer->xroot->udev;
1915
1916         if (udev->flags.usb_mode != USB_MODE_HOST)
1917                 return;         /* not supported */
1918
1919         xfer->endpoint->refcount_bw--;
1920         if (xfer->endpoint->refcount_bw != 0)
1921                 return;         /* still allocated */
1922
1923         switch (xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE) {
1924         case UE_INTERRUPT:
1925         case UE_ISOCHRONOUS:
1926
1927                 slot = xfer->endpoint->usb_uframe;
1928                 mask = xfer->endpoint->usb_smask;
1929
1930                 /* free microframe slot(s): */    
1931                 usb_hs_bandwidth_adjust(udev,
1932                     -xfer->max_frame_size, slot, mask >> slot);
1933
1934                 DPRINTFN(11, "slot=%d, mask=0x%02x\n", 
1935                     slot, mask >> slot);
1936
1937                 xfer->endpoint->usb_uframe = 0;
1938                 xfer->endpoint->usb_cmask = 0;
1939                 xfer->endpoint->usb_smask = 0;
1940                 break;
1941
1942         default:
1943                 break;
1944         }
1945 }
1946
1947 /*------------------------------------------------------------------------*
1948  *      usb_isoc_time_expand
1949  *
1950  * This function will expand the time counter from 7-bit to 16-bit.
1951  *
1952  * Returns:
1953  *   16-bit isochronous time counter.
1954  *------------------------------------------------------------------------*/
1955 uint16_t
1956 usb_isoc_time_expand(struct usb_bus *bus, uint16_t isoc_time_curr)
1957 {
1958         uint16_t rem;
1959
1960         USB_BUS_LOCK_ASSERT(bus, MA_OWNED);
1961
1962         rem = bus->isoc_time_last & (USB_ISOC_TIME_MAX - 1);
1963
1964         isoc_time_curr &= (USB_ISOC_TIME_MAX - 1);
1965
1966         if (isoc_time_curr < rem) {
1967                 /* the time counter wrapped around */
1968                 bus->isoc_time_last += USB_ISOC_TIME_MAX;
1969         }
1970         /* update the remainder */
1971
1972         bus->isoc_time_last &= ~(USB_ISOC_TIME_MAX - 1);
1973         bus->isoc_time_last |= isoc_time_curr;
1974
1975         return (bus->isoc_time_last);
1976 }
1977
1978 /*------------------------------------------------------------------------*
1979  *      usbd_fs_isoc_schedule_alloc_slot
1980  *
1981  * This function will allocate bandwidth for an isochronous FULL speed
1982  * transaction in the FULL speed schedule.
1983  *
1984  * Returns:
1985  *    <8: Success
1986  * Else: Error
1987  *------------------------------------------------------------------------*/
1988 #if USB_HAVE_TT_SUPPORT
1989 uint8_t
1990 usbd_fs_isoc_schedule_alloc_slot(struct usb_xfer *isoc_xfer, uint16_t isoc_time)
1991 {
1992         struct usb_xfer *xfer;
1993         struct usb_xfer *pipe_xfer;
1994         struct usb_bus *bus;
1995         usb_frlength_t len;
1996         usb_frlength_t data_len;
1997         uint16_t delta;
1998         uint16_t slot;
1999         uint8_t retval;
2000
2001         data_len = 0;
2002         slot = 0;
2003
2004         bus = isoc_xfer->xroot->bus;
2005
2006         TAILQ_FOREACH(xfer, &bus->intr_q.head, wait_entry) {
2007
2008                 /* skip self, if any */
2009
2010                 if (xfer == isoc_xfer)
2011                         continue;
2012
2013                 /* check if this USB transfer is going through the same TT */
2014
2015                 if (xfer->xroot->udev->parent_hs_hub !=
2016                     isoc_xfer->xroot->udev->parent_hs_hub) {
2017                         continue;
2018                 }
2019                 if ((isoc_xfer->xroot->udev->parent_hs_hub->
2020                     ddesc.bDeviceProtocol == UDPROTO_HSHUBMTT) &&
2021                     (xfer->xroot->udev->hs_port_no !=
2022                     isoc_xfer->xroot->udev->hs_port_no)) {
2023                         continue;
2024                 }
2025                 if (xfer->endpoint->methods != isoc_xfer->endpoint->methods)
2026                         continue;
2027
2028                 /* check if isoc_time is part of this transfer */
2029
2030                 delta = xfer->isoc_time_complete - isoc_time;
2031                 if (delta > 0 && delta <= xfer->nframes) {
2032                         delta = xfer->nframes - delta;
2033
2034                         len = xfer->frlengths[delta];
2035                         len += 8;
2036                         len *= 7;
2037                         len /= 6;
2038
2039                         data_len += len;
2040                 }
2041
2042                 /* check double buffered transfers */
2043
2044                 TAILQ_FOREACH(pipe_xfer, &xfer->endpoint->endpoint_q.head,
2045                     wait_entry) {
2046
2047                         /* skip self, if any */
2048
2049                         if (pipe_xfer == isoc_xfer)
2050                                 continue;
2051
2052                         /* check if isoc_time is part of this transfer */
2053
2054                         delta = pipe_xfer->isoc_time_complete - isoc_time;
2055                         if (delta > 0 && delta <= pipe_xfer->nframes) {
2056                                 delta = pipe_xfer->nframes - delta;
2057
2058                                 len = pipe_xfer->frlengths[delta];
2059                                 len += 8;
2060                                 len *= 7;
2061                                 len /= 6;
2062
2063                                 data_len += len;
2064                         }
2065                 }
2066         }
2067
2068         while (data_len >= USB_FS_BYTES_PER_HS_UFRAME) {
2069                 data_len -= USB_FS_BYTES_PER_HS_UFRAME;
2070                 slot++;
2071         }
2072
2073         /* check for overflow */
2074
2075         if (slot >= USB_FS_ISOC_UFRAME_MAX)
2076                 return (255);
2077
2078         retval = slot;
2079
2080         delta = isoc_xfer->isoc_time_complete - isoc_time;
2081         if (delta > 0 && delta <= isoc_xfer->nframes) {
2082                 delta = isoc_xfer->nframes - delta;
2083
2084                 len = isoc_xfer->frlengths[delta];
2085                 len += 8;
2086                 len *= 7;
2087                 len /= 6;
2088
2089                 data_len += len;
2090         }
2091
2092         while (data_len >= USB_FS_BYTES_PER_HS_UFRAME) {
2093                 data_len -= USB_FS_BYTES_PER_HS_UFRAME;
2094                 slot++;
2095         }
2096
2097         /* check for overflow */
2098
2099         if (slot >= USB_FS_ISOC_UFRAME_MAX)
2100                 return (255);
2101
2102         return (retval);
2103 }
2104 #endif
2105
2106 /*------------------------------------------------------------------------*
2107  *      usb_bus_port_get_device
2108  *
2109  * This function is NULL safe.
2110  *------------------------------------------------------------------------*/
2111 struct usb_device *
2112 usb_bus_port_get_device(struct usb_bus *bus, struct usb_port *up)
2113 {
2114         if ((bus == NULL) || (up == NULL)) {
2115                 /* be NULL safe */
2116                 return (NULL);
2117         }
2118         if (up->device_index == 0) {
2119                 /* nothing to do */
2120                 return (NULL);
2121         }
2122         return (bus->devices[up->device_index]);
2123 }
2124
2125 /*------------------------------------------------------------------------*
2126  *      usb_bus_port_set_device
2127  *
2128  * This function is NULL safe.
2129  *------------------------------------------------------------------------*/
2130 void
2131 usb_bus_port_set_device(struct usb_bus *bus, struct usb_port *up,
2132     struct usb_device *udev, uint8_t device_index)
2133 {
2134         if (bus == NULL) {
2135                 /* be NULL safe */
2136                 return;
2137         }
2138         /*
2139          * There is only one case where we don't
2140          * have an USB port, and that is the Root Hub!
2141          */
2142         if (up) {
2143                 if (udev) {
2144                         up->device_index = device_index;
2145                 } else {
2146                         device_index = up->device_index;
2147                         up->device_index = 0;
2148                 }
2149         }
2150         /*
2151          * Make relationships to our new device
2152          */
2153         if (device_index != 0) {
2154 #if USB_HAVE_UGEN
2155                 mtx_lock(&usb_ref_lock);
2156 #endif
2157                 bus->devices[device_index] = udev;
2158 #if USB_HAVE_UGEN
2159                 mtx_unlock(&usb_ref_lock);
2160 #endif
2161         }
2162         /*
2163          * Debug print
2164          */
2165         DPRINTFN(2, "bus %p devices[%u] = %p\n", bus, device_index, udev);
2166 }
2167
2168 /*------------------------------------------------------------------------*
2169  *      usb_needs_explore
2170  *
2171  * This functions is called when the USB event thread needs to run.
2172  *------------------------------------------------------------------------*/
2173 void
2174 usb_needs_explore(struct usb_bus *bus, uint8_t do_probe)
2175 {
2176         uint8_t do_unlock;
2177
2178         DPRINTF("\n");
2179
2180         if (bus == NULL) {
2181                 DPRINTF("No bus pointer!\n");
2182                 return;
2183         }
2184         if ((bus->devices == NULL) ||
2185             (bus->devices[USB_ROOT_HUB_ADDR] == NULL)) {
2186                 DPRINTF("No root HUB\n");
2187                 return;
2188         }
2189         if (mtx_owned(&bus->bus_mtx)) {
2190                 do_unlock = 0;
2191         } else {
2192                 USB_BUS_LOCK(bus);
2193                 do_unlock = 1;
2194         }
2195         if (do_probe) {
2196                 bus->do_probe = 1;
2197         }
2198         if (usb_proc_msignal(&bus->explore_proc,
2199             &bus->explore_msg[0], &bus->explore_msg[1])) {
2200                 /* ignore */
2201         }
2202         if (do_unlock) {
2203                 USB_BUS_UNLOCK(bus);
2204         }
2205 }
2206
2207 /*------------------------------------------------------------------------*
2208  *      usb_needs_explore_all
2209  *
2210  * This function is called whenever a new driver is loaded and will
2211  * cause that all USB busses are re-explored.
2212  *------------------------------------------------------------------------*/
2213 void
2214 usb_needs_explore_all(void)
2215 {
2216         struct usb_bus *bus;
2217         devclass_t dc;
2218         device_t dev;
2219         int max;
2220
2221         DPRINTFN(3, "\n");
2222
2223         dc = usb_devclass_ptr;
2224         if (dc == NULL) {
2225                 DPRINTFN(0, "no devclass\n");
2226                 return;
2227         }
2228         /*
2229          * Explore all USB busses in parallell.
2230          */
2231         max = devclass_get_maxunit(dc);
2232         while (max >= 0) {
2233                 dev = devclass_get_device(dc, max);
2234                 if (dev) {
2235                         bus = device_get_softc(dev);
2236                         if (bus) {
2237                                 usb_needs_explore(bus, 1);
2238                         }
2239                 }
2240                 max--;
2241         }
2242 }
2243
2244 /*------------------------------------------------------------------------*
2245  *      usb_bus_power_update
2246  *
2247  * This function will ensure that all USB devices on the given bus are
2248  * properly suspended or resumed according to the device transfer
2249  * state.
2250  *------------------------------------------------------------------------*/
2251 #if USB_HAVE_POWERD
2252 void
2253 usb_bus_power_update(struct usb_bus *bus)
2254 {
2255         usb_needs_explore(bus, 0 /* no probe */ );
2256 }
2257 #endif
2258
2259 /*------------------------------------------------------------------------*
2260  *      usbd_transfer_power_ref
2261  *
2262  * This function will modify the power save reference counts and
2263  * wakeup the USB device associated with the given USB transfer, if
2264  * needed.
2265  *------------------------------------------------------------------------*/
2266 #if USB_HAVE_POWERD
2267 void
2268 usbd_transfer_power_ref(struct usb_xfer *xfer, int val)
2269 {
2270         static const usb_power_mask_t power_mask[4] = {
2271                 [UE_CONTROL] = USB_HW_POWER_CONTROL,
2272                 [UE_BULK] = USB_HW_POWER_BULK,
2273                 [UE_INTERRUPT] = USB_HW_POWER_INTERRUPT,
2274                 [UE_ISOCHRONOUS] = USB_HW_POWER_ISOC,
2275         };
2276         struct usb_device *udev;
2277         uint8_t needs_explore;
2278         uint8_t needs_hw_power;
2279         uint8_t xfer_type;
2280
2281         udev = xfer->xroot->udev;
2282
2283         if (udev->device_index == USB_ROOT_HUB_ADDR) {
2284                 /* no power save for root HUB */
2285                 return;
2286         }
2287         USB_BUS_LOCK(udev->bus);
2288
2289         xfer_type = xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE;
2290
2291         udev->pwr_save.last_xfer_time = ticks;
2292         udev->pwr_save.type_refs[xfer_type] += val;
2293
2294         if (xfer->flags_int.control_xfr) {
2295                 udev->pwr_save.read_refs += val;
2296                 if (xfer->flags_int.usb_mode == USB_MODE_HOST) {
2297                         /*
2298                          * It is not allowed to suspend during a
2299                          * control transfer:
2300                          */
2301                         udev->pwr_save.write_refs += val;
2302                 }
2303         } else if (USB_GET_DATA_ISREAD(xfer)) {
2304                 udev->pwr_save.read_refs += val;
2305         } else {
2306                 udev->pwr_save.write_refs += val;
2307         }
2308
2309         if (val > 0) {
2310                 if (udev->flags.self_suspended)
2311                         needs_explore = usb_peer_should_wakeup(udev);
2312                 else
2313                         needs_explore = 0;
2314
2315                 if (!(udev->bus->hw_power_state & power_mask[xfer_type])) {
2316                         DPRINTF("Adding type %u to power state\n", xfer_type);
2317                         udev->bus->hw_power_state |= power_mask[xfer_type];
2318                         needs_hw_power = 1;
2319                 } else {
2320                         needs_hw_power = 0;
2321                 }
2322         } else {
2323                 needs_explore = 0;
2324                 needs_hw_power = 0;
2325         }
2326
2327         USB_BUS_UNLOCK(udev->bus);
2328
2329         if (needs_explore) {
2330                 DPRINTF("update\n");
2331                 usb_bus_power_update(udev->bus);
2332         } else if (needs_hw_power) {
2333                 DPRINTF("needs power\n");
2334                 if (udev->bus->methods->set_hw_power != NULL) {
2335                         (udev->bus->methods->set_hw_power) (udev->bus);
2336                 }
2337         }
2338 }
2339 #endif
2340
2341 /*------------------------------------------------------------------------*
2342  *      usb_peer_should_wakeup
2343  *
2344  * This function returns non-zero if the current device should wake up.
2345  *------------------------------------------------------------------------*/
2346 static uint8_t
2347 usb_peer_should_wakeup(struct usb_device *udev)
2348 {
2349         return (((udev->power_mode == USB_POWER_MODE_ON) &&
2350             (udev->flags.usb_mode == USB_MODE_HOST)) ||
2351             (udev->driver_added_refcount != udev->bus->driver_added_refcount) ||
2352             (udev->re_enumerate_wait != USB_RE_ENUM_DONE) ||
2353             (udev->pwr_save.type_refs[UE_ISOCHRONOUS] != 0) ||
2354             (udev->pwr_save.write_refs != 0) ||
2355             ((udev->pwr_save.read_refs != 0) &&
2356             (udev->flags.usb_mode == USB_MODE_HOST) &&
2357             (usb_peer_can_wakeup(udev) == 0)));
2358 }
2359
2360 /*------------------------------------------------------------------------*
2361  *      usb_bus_powerd
2362  *
2363  * This function implements the USB power daemon and is called
2364  * regularly from the USB explore thread.
2365  *------------------------------------------------------------------------*/
2366 #if USB_HAVE_POWERD
2367 void
2368 usb_bus_powerd(struct usb_bus *bus)
2369 {
2370         struct usb_device *udev;
2371         usb_ticks_t temp;
2372         usb_ticks_t limit;
2373         usb_ticks_t mintime;
2374         usb_size_t type_refs[5];
2375         uint8_t x;
2376
2377         limit = usb_power_timeout;
2378         if (limit == 0)
2379                 limit = hz;
2380         else if (limit > 255)
2381                 limit = 255 * hz;
2382         else
2383                 limit = limit * hz;
2384
2385         DPRINTF("bus=%p\n", bus);
2386
2387         USB_BUS_LOCK(bus);
2388
2389         /*
2390          * The root HUB device is never suspended
2391          * and we simply skip it.
2392          */
2393         for (x = USB_ROOT_HUB_ADDR + 1;
2394             x != bus->devices_max; x++) {
2395
2396                 udev = bus->devices[x];
2397                 if (udev == NULL)
2398                         continue;
2399
2400                 temp = ticks - udev->pwr_save.last_xfer_time;
2401
2402                 if (usb_peer_should_wakeup(udev)) {
2403                         /* check if we are suspended */
2404                         if (udev->flags.self_suspended != 0) {
2405                                 USB_BUS_UNLOCK(bus);
2406                                 usb_dev_resume_peer(udev);
2407                                 USB_BUS_LOCK(bus);
2408                         }
2409                 } else if ((temp >= limit) &&
2410                     (udev->flags.usb_mode == USB_MODE_HOST) &&
2411                     (udev->flags.self_suspended == 0)) {
2412                         /* try to do suspend */
2413
2414                         USB_BUS_UNLOCK(bus);
2415                         usb_dev_suspend_peer(udev);
2416                         USB_BUS_LOCK(bus);
2417                 }
2418         }
2419
2420         /* reset counters */
2421
2422         mintime = (usb_ticks_t)-1;
2423         type_refs[0] = 0;
2424         type_refs[1] = 0;
2425         type_refs[2] = 0;
2426         type_refs[3] = 0;
2427         type_refs[4] = 0;
2428
2429         /* Re-loop all the devices to get the actual state */
2430
2431         for (x = USB_ROOT_HUB_ADDR + 1;
2432             x != bus->devices_max; x++) {
2433
2434                 udev = bus->devices[x];
2435                 if (udev == NULL)
2436                         continue;
2437
2438                 /* we found a non-Root-Hub USB device */
2439                 type_refs[4] += 1;
2440
2441                 /* "last_xfer_time" can be updated by a resume */
2442                 temp = ticks - udev->pwr_save.last_xfer_time;
2443
2444                 /*
2445                  * Compute minimum time since last transfer for the complete
2446                  * bus:
2447                  */
2448                 if (temp < mintime)
2449                         mintime = temp;
2450
2451                 if (udev->flags.self_suspended == 0) {
2452                         type_refs[0] += udev->pwr_save.type_refs[0];
2453                         type_refs[1] += udev->pwr_save.type_refs[1];
2454                         type_refs[2] += udev->pwr_save.type_refs[2];
2455                         type_refs[3] += udev->pwr_save.type_refs[3];
2456                 }
2457         }
2458
2459         if (mintime >= (usb_ticks_t)(1 * hz)) {
2460                 /* recompute power masks */
2461                 DPRINTF("Recomputing power masks\n");
2462                 bus->hw_power_state = 0;
2463                 if (type_refs[UE_CONTROL] != 0)
2464                         bus->hw_power_state |= USB_HW_POWER_CONTROL;
2465                 if (type_refs[UE_BULK] != 0)
2466                         bus->hw_power_state |= USB_HW_POWER_BULK;
2467                 if (type_refs[UE_INTERRUPT] != 0)
2468                         bus->hw_power_state |= USB_HW_POWER_INTERRUPT;
2469                 if (type_refs[UE_ISOCHRONOUS] != 0)
2470                         bus->hw_power_state |= USB_HW_POWER_ISOC;
2471                 if (type_refs[4] != 0)
2472                         bus->hw_power_state |= USB_HW_POWER_NON_ROOT_HUB;
2473         }
2474         USB_BUS_UNLOCK(bus);
2475
2476         if (bus->methods->set_hw_power != NULL) {
2477                 /* always update hardware power! */
2478                 (bus->methods->set_hw_power) (bus);
2479         }
2480         return;
2481 }
2482 #endif
2483
2484 /*------------------------------------------------------------------------*
2485  *      usb_dev_resume_peer
2486  *
2487  * This function will resume an USB peer and do the required USB
2488  * signalling to get an USB device out of the suspended state.
2489  *------------------------------------------------------------------------*/
2490 static void
2491 usb_dev_resume_peer(struct usb_device *udev)
2492 {
2493         struct usb_bus *bus;
2494         int err;
2495
2496         /* be NULL safe */
2497         if (udev == NULL)
2498                 return;
2499
2500         /* check if already resumed */
2501         if (udev->flags.self_suspended == 0)
2502                 return;
2503
2504         /* we need a parent HUB to do resume */
2505         if (udev->parent_hub == NULL)
2506                 return;
2507
2508         DPRINTF("udev=%p\n", udev);
2509
2510         if ((udev->flags.usb_mode == USB_MODE_DEVICE) &&
2511             (udev->flags.remote_wakeup == 0)) {
2512                 /*
2513                  * If the host did not set the remote wakeup feature, we can
2514                  * not wake it up either!
2515                  */
2516                 DPRINTF("remote wakeup is not set!\n");
2517                 return;
2518         }
2519         /* get bus pointer */
2520         bus = udev->bus;
2521
2522         /* resume parent hub first */
2523         usb_dev_resume_peer(udev->parent_hub);
2524
2525         /* reduce chance of instant resume failure by waiting a little bit */
2526         usb_pause_mtx(NULL, USB_MS_TO_TICKS(20));
2527
2528         if (usb_device_20_compatible(udev)) {
2529                 /* resume current port (Valid in Host and Device Mode) */
2530                 err = usbd_req_clear_port_feature(udev->parent_hub,
2531                     NULL, udev->port_no, UHF_PORT_SUSPEND);
2532                 if (err) {
2533                         DPRINTFN(0, "Resuming port failed\n");
2534                         return;
2535                 }
2536         } else {
2537                 /* resume current port (Valid in Host and Device Mode) */
2538                 err = usbd_req_set_port_link_state(udev->parent_hub,
2539                     NULL, udev->port_no, UPS_PORT_LS_U0);
2540                 if (err) {
2541                         DPRINTFN(0, "Resuming port failed\n");
2542                         return;
2543                 }
2544         }
2545
2546         /* resume settle time */
2547         usb_pause_mtx(NULL, USB_MS_TO_TICKS(usb_port_resume_delay));
2548
2549         if (bus->methods->device_resume != NULL) {
2550                 /* resume USB device on the USB controller */
2551                 (bus->methods->device_resume) (udev);
2552         }
2553         USB_BUS_LOCK(bus);
2554         /* set that this device is now resumed */
2555         udev->flags.self_suspended = 0;
2556 #if USB_HAVE_POWERD
2557         /* make sure that we don't go into suspend right away */
2558         udev->pwr_save.last_xfer_time = ticks;
2559
2560         /* make sure the needed power masks are on */
2561         if (udev->pwr_save.type_refs[UE_CONTROL] != 0)
2562                 bus->hw_power_state |= USB_HW_POWER_CONTROL;
2563         if (udev->pwr_save.type_refs[UE_BULK] != 0)
2564                 bus->hw_power_state |= USB_HW_POWER_BULK;
2565         if (udev->pwr_save.type_refs[UE_INTERRUPT] != 0)
2566                 bus->hw_power_state |= USB_HW_POWER_INTERRUPT;
2567         if (udev->pwr_save.type_refs[UE_ISOCHRONOUS] != 0)
2568                 bus->hw_power_state |= USB_HW_POWER_ISOC;
2569 #endif
2570         USB_BUS_UNLOCK(bus);
2571
2572         if (bus->methods->set_hw_power != NULL) {
2573                 /* always update hardware power! */
2574                 (bus->methods->set_hw_power) (bus);
2575         }
2576
2577         usbd_sr_lock(udev);
2578
2579         /* notify all sub-devices about resume */
2580         err = usb_suspend_resume(udev, 0);
2581
2582         usbd_sr_unlock(udev);
2583
2584         /* check if peer has wakeup capability */
2585         if (usb_peer_can_wakeup(udev)) {
2586                 /* clear remote wakeup */
2587                 err = usbd_req_clear_device_feature(udev,
2588                     NULL, UF_DEVICE_REMOTE_WAKEUP);
2589                 if (err) {
2590                         DPRINTFN(0, "Clearing device "
2591                             "remote wakeup failed: %s\n",
2592                             usbd_errstr(err));
2593                 }
2594         }
2595 }
2596
2597 /*------------------------------------------------------------------------*
2598  *      usb_dev_suspend_peer
2599  *
2600  * This function will suspend an USB peer and do the required USB
2601  * signalling to get an USB device into the suspended state.
2602  *------------------------------------------------------------------------*/
2603 static void
2604 usb_dev_suspend_peer(struct usb_device *udev)
2605 {
2606         struct usb_device *child;
2607         int err;
2608         uint8_t x;
2609         uint8_t nports;
2610
2611 repeat:
2612         /* be NULL safe */
2613         if (udev == NULL)
2614                 return;
2615
2616         /* check if already suspended */
2617         if (udev->flags.self_suspended)
2618                 return;
2619
2620         /* we need a parent HUB to do suspend */
2621         if (udev->parent_hub == NULL)
2622                 return;
2623
2624         DPRINTF("udev=%p\n", udev);
2625
2626         /* check if the current device is a HUB */
2627         if (udev->hub != NULL) {
2628                 nports = udev->hub->nports;
2629
2630                 /* check if all devices on the HUB are suspended */
2631                 for (x = 0; x != nports; x++) {
2632                         child = usb_bus_port_get_device(udev->bus,
2633                             udev->hub->ports + x);
2634
2635                         if (child == NULL)
2636                                 continue;
2637
2638                         if (child->flags.self_suspended)
2639                                 continue;
2640
2641                         DPRINTFN(1, "Port %u is busy on the HUB!\n", x + 1);
2642                         return;
2643                 }
2644         }
2645
2646         if (usb_peer_can_wakeup(udev)) {
2647                 /*
2648                  * This request needs to be done before we set
2649                  * "udev->flags.self_suspended":
2650                  */
2651
2652                 /* allow device to do remote wakeup */
2653                 err = usbd_req_set_device_feature(udev,
2654                     NULL, UF_DEVICE_REMOTE_WAKEUP);
2655                 if (err) {
2656                         DPRINTFN(0, "Setting device "
2657                             "remote wakeup failed\n");
2658                 }
2659         }
2660
2661         USB_BUS_LOCK(udev->bus);
2662         /*
2663          * Checking for suspend condition and setting suspended bit
2664          * must be atomic!
2665          */
2666         err = usb_peer_should_wakeup(udev);
2667         if (err == 0) {
2668                 /*
2669                  * Set that this device is suspended. This variable
2670                  * must be set before calling USB controller suspend
2671                  * callbacks.
2672                  */
2673                 udev->flags.self_suspended = 1;
2674         }
2675         USB_BUS_UNLOCK(udev->bus);
2676
2677         if (err != 0) {
2678                 if (usb_peer_can_wakeup(udev)) {
2679                         /* allow device to do remote wakeup */
2680                         err = usbd_req_clear_device_feature(udev,
2681                             NULL, UF_DEVICE_REMOTE_WAKEUP);
2682                         if (err) {
2683                                 DPRINTFN(0, "Setting device "
2684                                     "remote wakeup failed\n");
2685                         }
2686                 }
2687
2688                 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2689                         /* resume parent HUB first */
2690                         usb_dev_resume_peer(udev->parent_hub);
2691
2692                         /* reduce chance of instant resume failure by waiting a little bit */
2693                         usb_pause_mtx(NULL, USB_MS_TO_TICKS(20));
2694
2695                         /* resume current port (Valid in Host and Device Mode) */
2696                         err = usbd_req_clear_port_feature(udev->parent_hub,
2697                             NULL, udev->port_no, UHF_PORT_SUSPEND);
2698
2699                         /* resume settle time */
2700                         usb_pause_mtx(NULL, USB_MS_TO_TICKS(usb_port_resume_delay));
2701                 }
2702                 DPRINTF("Suspend was cancelled!\n");
2703                 return;
2704         }
2705
2706         usbd_sr_lock(udev);
2707
2708         /* notify all sub-devices about suspend */
2709         err = usb_suspend_resume(udev, 1);
2710
2711         usbd_sr_unlock(udev);
2712
2713         if (udev->bus->methods->device_suspend != NULL) {
2714                 usb_timeout_t temp;
2715
2716                 /* suspend device on the USB controller */
2717                 (udev->bus->methods->device_suspend) (udev);
2718
2719                 /* do DMA delay */
2720                 temp = usbd_get_dma_delay(udev);
2721                 if (temp != 0)
2722                         usb_pause_mtx(NULL, USB_MS_TO_TICKS(temp));
2723
2724         }
2725
2726         if (usb_device_20_compatible(udev)) {
2727                 /* suspend current port */
2728                 err = usbd_req_set_port_feature(udev->parent_hub,
2729                     NULL, udev->port_no, UHF_PORT_SUSPEND);
2730                 if (err) {
2731                         DPRINTFN(0, "Suspending port failed\n");
2732                         return;
2733                 }
2734         } else {
2735                 /* suspend current port */
2736                 err = usbd_req_set_port_link_state(udev->parent_hub,
2737                     NULL, udev->port_no, UPS_PORT_LS_U3);
2738                 if (err) {
2739                         DPRINTFN(0, "Suspending port failed\n");
2740                         return;
2741                 }
2742         }
2743
2744         udev = udev->parent_hub;
2745         goto repeat;
2746 }
2747
2748 /*------------------------------------------------------------------------*
2749  *      usbd_set_power_mode
2750  *
2751  * This function will set the power mode, see USB_POWER_MODE_XXX for a
2752  * USB device.
2753  *------------------------------------------------------------------------*/
2754 void
2755 usbd_set_power_mode(struct usb_device *udev, uint8_t power_mode)
2756 {
2757         /* filter input argument */
2758         if ((power_mode != USB_POWER_MODE_ON) &&
2759             (power_mode != USB_POWER_MODE_OFF))
2760                 power_mode = USB_POWER_MODE_SAVE;
2761
2762         power_mode = usbd_filter_power_mode(udev, power_mode);  
2763
2764         udev->power_mode = power_mode;  /* update copy of power mode */
2765
2766 #if USB_HAVE_POWERD
2767         usb_bus_power_update(udev->bus);
2768 #else
2769         usb_needs_explore(udev->bus, 0 /* no probe */ );
2770 #endif
2771 }
2772
2773 /*------------------------------------------------------------------------*
2774  *      usbd_filter_power_mode
2775  *
2776  * This function filters the power mode based on hardware requirements.
2777  *------------------------------------------------------------------------*/
2778 uint8_t
2779 usbd_filter_power_mode(struct usb_device *udev, uint8_t power_mode)
2780 {
2781         struct usb_bus_methods *mtod;
2782         int8_t temp;
2783
2784         mtod = udev->bus->methods;
2785         temp = -1;
2786
2787         if (mtod->get_power_mode != NULL)
2788                 (mtod->get_power_mode) (udev, &temp);
2789
2790         /* check if we should not filter */
2791         if (temp < 0)
2792                 return (power_mode);
2793
2794         /* use fixed power mode given by hardware driver */
2795         return (temp);
2796 }
2797
2798 /*------------------------------------------------------------------------*
2799  *      usbd_start_re_enumerate
2800  *
2801  * This function starts re-enumeration of the given USB device. This
2802  * function does not need to be called BUS-locked. This function does
2803  * not wait until the re-enumeration is completed.
2804  *------------------------------------------------------------------------*/
2805 void
2806 usbd_start_re_enumerate(struct usb_device *udev)
2807 {
2808         if (udev->re_enumerate_wait == USB_RE_ENUM_DONE) {
2809                 udev->re_enumerate_wait = USB_RE_ENUM_START;
2810                 usb_needs_explore(udev->bus, 0);
2811         }
2812 }
2813
2814 /*-----------------------------------------------------------------------*
2815  *      usbd_start_set_config
2816  *
2817  * This function starts setting a USB configuration. This function
2818  * does not need to be called BUS-locked. This function does not wait
2819  * until the set USB configuratino is completed.
2820  *------------------------------------------------------------------------*/
2821 usb_error_t
2822 usbd_start_set_config(struct usb_device *udev, uint8_t index)
2823 {
2824         if (udev->re_enumerate_wait == USB_RE_ENUM_DONE) {
2825                 if (udev->curr_config_index == index) {
2826                         /* no change needed */
2827                         return (0);
2828                 }
2829                 udev->next_config_index = index;
2830                 udev->re_enumerate_wait = USB_RE_ENUM_SET_CONFIG;
2831                 usb_needs_explore(udev->bus, 0);
2832                 return (0);
2833         } else if (udev->re_enumerate_wait == USB_RE_ENUM_SET_CONFIG) {
2834                 if (udev->next_config_index == index) {
2835                         /* no change needed */
2836                         return (0);
2837                 }
2838         }
2839         return (USB_ERR_PENDING_REQUESTS);
2840 }