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