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