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