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