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