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