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