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