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