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