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