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