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