Initial import from FreeBSD RELENG_4:
[dragonfly.git] / sys / bus / usb / uhub.c
1 /*      $NetBSD: uhub.c,v 1.47 2000/09/24 02:08:38 augustss Exp $       */
2 /*      $FreeBSD: src/sys/dev/usb/uhub.c,v 1.21.2.7 2002/11/06 20:23:50 joe Exp $       */
3
4 /*
5  * Copyright (c) 1998 The NetBSD Foundation, Inc.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by Lennart Augustsson (lennart@augustsson.net) at
10  * Carlstedt Research & Technology.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *        This product includes software developed by the NetBSD
23  *        Foundation, Inc. and its contributors.
24  * 4. Neither the name of The NetBSD Foundation nor the names of its
25  *    contributors may be used to endorse or promote products derived
26  *    from this software without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
29  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
30  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
31  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
32  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
34  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
35  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
36  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38  * POSSIBILITY OF SUCH DAMAGE.
39  */
40
41 /*
42  * USB spec: http://www.usb.org/developers/docs.htm
43  */
44
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/kernel.h>
48 #include <sys/malloc.h>
49 #if defined(__NetBSD__) || defined(__OpenBSD__)
50 #include <sys/device.h>
51 #include <sys/proc.h>
52 #elif defined(__FreeBSD__)
53 #include <sys/module.h>
54 #include <sys/bus.h>
55 #include "bus_if.h"
56 #include <sys/sysctl.h>
57 #endif
58
59 #include <machine/bus.h>
60
61 #include <dev/usb/usb.h>
62 #include <dev/usb/usbdi.h>
63 #include <dev/usb/usbdi_util.h>
64 #include <dev/usb/usbdivar.h>
65
66 #define UHUB_INTR_INTERVAL 255  /* ms */
67
68 #ifdef USB_DEBUG
69 #define DPRINTF(x)      if (uhubdebug) logprintf x
70 #define DPRINTFN(n,x)   if (uhubdebug>(n)) logprintf x
71 static int      uhubdebug = 0;
72 SYSCTL_NODE(_hw_usb, OID_AUTO, uhub, CTLFLAG_RW, 0, "USB uhub");
73 SYSCTL_INT(_hw_usb_uhub, OID_AUTO, debug, CTLFLAG_RW,
74         &uhubdebug, 0, "uhub debug level");
75 #else
76 #define DPRINTF(x)
77 #define DPRINTFN(n,x)
78 #endif
79
80 struct uhub_softc {
81         USBBASEDEVICE           sc_dev;         /* base device */
82         usbd_device_handle      sc_hub;         /* USB device */
83         usbd_pipe_handle        sc_ipipe;       /* interrupt pipe */
84         u_int8_t                sc_status[1];   /* XXX more ports */
85         u_char                  sc_running;
86 };
87
88 Static usbd_status uhub_explore(usbd_device_handle hub);
89 Static void uhub_intr(usbd_xfer_handle, usbd_private_handle,usbd_status);
90
91 #if defined(__FreeBSD__)
92 Static bus_child_detached_t uhub_child_detached;
93 #endif
94
95
96 /* 
97  * We need two attachment points:
98  * hub to usb and hub to hub
99  * Every other driver only connects to hubs
100  */
101
102 #if defined(__NetBSD__) || defined(__OpenBSD__)
103 USB_DECLARE_DRIVER(uhub);
104
105 /* Create the driver instance for the hub connected to hub case */
106 struct cfattach uhub_uhub_ca = {
107         sizeof(struct uhub_softc), uhub_match, uhub_attach,
108         uhub_detach, uhub_activate
109 };
110 #elif defined(__FreeBSD__)
111 USB_DECLARE_DRIVER_INIT(uhub,
112                         DEVMETHOD(bus_child_detached, uhub_child_detached),
113                         DEVMETHOD(device_suspend, bus_generic_suspend),
114                         DEVMETHOD(device_resume, bus_generic_resume),
115                         DEVMETHOD(device_shutdown, bus_generic_shutdown)
116                         );
117                         
118 /* Create the driver instance for the hub connected to usb case. */
119 devclass_t uhubroot_devclass;
120
121 Static device_method_t uhubroot_methods[] = {
122         DEVMETHOD(device_probe, uhub_match),
123         DEVMETHOD(device_attach, uhub_attach),
124         /* detach is not allowed for a root hub */
125         DEVMETHOD(device_suspend, bus_generic_suspend),
126         DEVMETHOD(device_resume, bus_generic_resume),
127         DEVMETHOD(device_shutdown, bus_generic_shutdown),
128         {0,0}
129 };
130
131 Static  driver_t uhubroot_driver = {
132         "uhub",
133         uhubroot_methods,
134         sizeof(struct uhub_softc)
135 };
136 #endif
137
138 USB_MATCH(uhub)
139 {
140         USB_MATCH_START(uhub, uaa);
141         usb_device_descriptor_t *dd = usbd_get_device_descriptor(uaa->device);
142         
143         DPRINTFN(5,("uhub_match, dd=%p\n", dd));
144         /* 
145          * The subclass for hubs seems to be 0 for some and 1 for others,
146          * so we just ignore the subclass.
147          */
148         if (uaa->iface == NULL && dd->bDeviceClass == UDCLASS_HUB)
149                 return (UMATCH_DEVCLASS_DEVSUBCLASS);
150         return (UMATCH_NONE);
151 }
152
153 USB_ATTACH(uhub)
154 {
155         USB_ATTACH_START(uhub, sc, uaa);
156         usbd_device_handle dev = uaa->device;
157         char devinfo[1024];
158         usbd_status err;
159         struct usbd_hub *hub;
160         usb_device_request_t req;
161         usb_hub_descriptor_t hubdesc;
162         int p, port, nports, nremov, pwrdly;
163         usbd_interface_handle iface;
164         usb_endpoint_descriptor_t *ed;
165         
166         DPRINTFN(1,("uhub_attach\n"));
167         sc->sc_hub = dev;
168         usbd_devinfo(dev, 1, devinfo);
169         USB_ATTACH_SETUP;
170         printf("%s: %s\n", USBDEVNAME(sc->sc_dev), devinfo);
171
172         err = usbd_set_config_index(dev, 0, 1);
173         if (err) {
174                 DPRINTF(("%s: configuration failed, error=%s\n",
175                          USBDEVNAME(sc->sc_dev), usbd_errstr(err)));
176                 USB_ATTACH_ERROR_RETURN;
177         }
178
179         if (dev->depth > USB_HUB_MAX_DEPTH) {
180                 printf("%s: hub depth (%d) exceeded, hub ignored\n",
181                        USBDEVNAME(sc->sc_dev), USB_HUB_MAX_DEPTH);
182                 USB_ATTACH_ERROR_RETURN;
183         }
184
185         /* Get hub descriptor. */
186         req.bmRequestType = UT_READ_CLASS_DEVICE;
187         req.bRequest = UR_GET_DESCRIPTOR;
188         USETW(req.wValue, 0);
189         USETW(req.wIndex, 0);
190         USETW(req.wLength, USB_HUB_DESCRIPTOR_SIZE);
191         DPRINTFN(1,("usb_init_hub: getting hub descriptor\n"));
192         err = usbd_do_request(dev, &req, &hubdesc);
193         nports = hubdesc.bNbrPorts;
194         if (!err && nports > 7) {
195                 USETW(req.wLength, USB_HUB_DESCRIPTOR_SIZE + (nports+1) / 8);
196                 err = usbd_do_request(dev, &req, &hubdesc);
197         }
198         if (err) {
199                 DPRINTF(("%s: getting hub descriptor failed, error=%s\n",
200                          USBDEVNAME(sc->sc_dev), usbd_errstr(err)));
201                 USB_ATTACH_ERROR_RETURN;
202         }
203
204         for (nremov = 0, port = 1; port <= nports; port++)
205                 if (!UHD_NOT_REMOV(&hubdesc, port))
206                         nremov++;
207         printf("%s: %d port%s with %d removable, %s powered\n",
208                USBDEVNAME(sc->sc_dev), nports, nports != 1 ? "s" : "",
209                nremov, dev->self_powered ? "self" : "bus");
210
211         hub = malloc(sizeof(*hub) + (nports-1) * sizeof(struct usbd_port),
212                      M_USBDEV, M_NOWAIT);
213         if (hub == NULL)
214                 USB_ATTACH_ERROR_RETURN;
215         dev->hub = hub;
216         dev->hub->hubsoftc = sc;
217         hub->explore = uhub_explore;
218         hub->hubdesc = hubdesc;
219         
220         DPRINTFN(1,("usbhub_init_hub: selfpowered=%d, parent=%p, "
221                     "parent->selfpowered=%d\n",
222                  dev->self_powered, dev->powersrc->parent,
223                  dev->powersrc->parent ? 
224                  dev->powersrc->parent->self_powered : 0));
225
226         if (!dev->self_powered && dev->powersrc->parent != NULL &&
227             !dev->powersrc->parent->self_powered) {
228                 printf("%s: bus powered hub connected to bus powered hub, "
229                        "ignored\n", USBDEVNAME(sc->sc_dev));
230                 goto bad;
231         }
232
233         /* Set up interrupt pipe. */
234         err = usbd_device2interface_handle(dev, 0, &iface);
235         if (err) {
236                 printf("%s: no interface handle\n", USBDEVNAME(sc->sc_dev));
237                 goto bad;
238         }
239         ed = usbd_interface2endpoint_descriptor(iface, 0);
240         if (ed == NULL) {
241                 printf("%s: no endpoint descriptor\n", USBDEVNAME(sc->sc_dev));
242                 goto bad;
243         }
244         if ((ed->bmAttributes & UE_XFERTYPE) != UE_INTERRUPT) {
245                 printf("%s: bad interrupt endpoint\n", USBDEVNAME(sc->sc_dev));
246                 goto bad;
247         }
248
249         err = usbd_open_pipe_intr(iface, ed->bEndpointAddress,
250                   USBD_SHORT_XFER_OK, &sc->sc_ipipe, sc, sc->sc_status, 
251                   sizeof(sc->sc_status), uhub_intr, UHUB_INTR_INTERVAL);
252         if (err) {
253                 printf("%s: cannot open interrupt pipe\n", 
254                        USBDEVNAME(sc->sc_dev));
255                 goto bad;
256         }
257
258         /* Wait with power off for a while. */
259         usbd_delay_ms(dev, USB_POWER_DOWN_TIME);
260
261         /*
262          * To have the best chance of success we do things in the exact same
263          * order as Windoze98.  This should not be necessary, but some
264          * devices do not follow the USB specs to the letter.
265          *
266          * These are the events on the bus when a hub is attached:
267          *  Get device and config descriptors (see attach code)
268          *  Get hub descriptor (see above)
269          *  For all ports
270          *     turn on power
271          *     wait for power to become stable
272          * (all below happens in explore code)
273          *  For all ports
274          *     clear C_PORT_CONNECTION
275          *  For all ports
276          *     get port status
277          *     if device connected
278          *        turn on reset
279          *        wait
280          *        clear C_PORT_RESET
281          *        get port status
282          *        proceed with device attachment
283          */
284
285         /* Set up data structures */
286         for (p = 0; p < nports; p++) {
287                 struct usbd_port *up = &hub->ports[p];
288                 up->device = 0;
289                 up->parent = dev;
290                 up->portno = p+1;
291                 if (dev->self_powered)
292                         /* Self powered hub, give ports maximum current. */
293                         up->power = USB_MAX_POWER;
294                 else
295                         up->power = USB_MIN_POWER;
296         }
297
298         /* XXX should check for none, individual, or ganged power? */
299
300         pwrdly = dev->hub->hubdesc.bPwrOn2PwrGood * UHD_PWRON_FACTOR
301             + USB_EXTRA_POWER_UP_TIME;
302         for (port = 1; port <= nports; port++) {
303                 /* Turn the power on. */
304                 err = usbd_set_port_feature(dev, port, UHF_PORT_POWER);
305                 if (err)
306                         printf("%s: port %d power on failed, %s\n", 
307                                USBDEVNAME(sc->sc_dev), port,
308                                usbd_errstr(err));
309                 DPRINTF(("usb_init_port: turn on port %d power\n", port));
310                 /* Wait for stable power. */
311                 usbd_delay_ms(dev, pwrdly);
312         }
313
314         /* The usual exploration will finish the setup. */
315
316         sc->sc_running = 1;
317
318         USB_ATTACH_SUCCESS_RETURN;
319
320  bad:
321         free(hub, M_USBDEV);
322         dev->hub = 0;
323         USB_ATTACH_ERROR_RETURN;
324 }
325
326 usbd_status
327 uhub_explore(usbd_device_handle dev)
328 {
329         usb_hub_descriptor_t *hd = &dev->hub->hubdesc;
330         struct uhub_softc *sc = dev->hub->hubsoftc;
331         struct usbd_port *up;
332         usbd_status err;
333         int port;
334         int change, status;
335
336         DPRINTFN(10, ("uhub_explore dev=%p addr=%d\n", dev, dev->address));
337
338         if (!sc->sc_running)
339                 return (USBD_NOT_STARTED);
340
341         /* Ignore hubs that are too deep. */
342         if (dev->depth > USB_HUB_MAX_DEPTH)
343                 return (USBD_TOO_DEEP);
344
345         for(port = 1; port <= hd->bNbrPorts; port++) {
346                 up = &dev->hub->ports[port-1];
347                 err = usbd_get_port_status(dev, port, &up->status);
348                 if (err) {
349                         DPRINTF(("uhub_explore: get port status failed, "
350                                  "error=%s\n", usbd_errstr(err)));
351                         continue;
352                 }
353                 status = UGETW(up->status.wPortStatus);
354                 change = UGETW(up->status.wPortChange);
355                 DPRINTFN(3,("uhub_explore: port %d status 0x%04x 0x%04x\n",
356                             port, status, change));
357                 if (change & UPS_C_PORT_ENABLED) {
358                         DPRINTF(("uhub_explore: C_PORT_ENABLED\n"));
359                         usbd_clear_port_feature(dev, port, UHF_C_PORT_ENABLE);
360                         if (status & UPS_PORT_ENABLED) {
361                                 printf("%s: illegal enable change, port %d\n",
362                                        USBDEVNAME(sc->sc_dev), port);
363                         } else {
364                                 /* Port error condition. */
365                                 if (up->restartcnt) /* no message first time */
366                                         printf("%s: port error, restarting "
367                                                "port %d\n",
368                                                USBDEVNAME(sc->sc_dev), port);
369
370                                 if (up->restartcnt++ < USBD_RESTART_MAX)
371                                         goto disco;
372                                 else
373                                         printf("%s: port error, giving up "
374                                                "port %d\n",
375                                                USBDEVNAME(sc->sc_dev), port);
376                         }
377                 }
378                 if (!(change & UPS_C_CONNECT_STATUS)) {
379                         DPRINTFN(3,("uhub_explore: port=%d !C_CONNECT_"
380                                     "STATUS\n", port));
381                         /* No status change, just do recursive explore. */
382                         if (up->device && up->device->hub)
383                                 up->device->hub->explore(up->device);
384                         continue;
385                 }
386
387                 /* We have a connect status change, handle it. */
388
389                 DPRINTF(("uhub_explore: status change hub=%d port=%d\n",
390                          dev->address, port));
391                 usbd_clear_port_feature(dev, port, UHF_C_PORT_CONNECTION);
392                 /*usbd_clear_port_feature(dev, port, UHF_C_PORT_ENABLE);*/
393                 /*
394                  * If there is already a device on the port the change status
395                  * must mean that is has disconnected.  Looking at the
396                  * current connect status is not enough to figure this out
397                  * since a new unit may have been connected before we handle
398                  * the disconnect.
399                  */
400         disco:
401                 if (up->device != NULL) {
402                         /* Disconnected */
403                         DPRINTF(("uhub_explore: device addr=%d disappeared "
404                                  "on port %d\n", up->device->address, port));
405                         usb_disconnect_port(up, USBDEV(sc->sc_dev));
406                         usbd_clear_port_feature(dev, port, 
407                                                 UHF_C_PORT_CONNECTION);
408                 }
409                 if (!(status & UPS_CURRENT_CONNECT_STATUS)) {
410                         /* Nothing connected, just ignore it. */
411                         DPRINTFN(3,("uhub_explore: port=%d !CURRENT_CONNECT"
412                                     "_STATUS\n", port));
413                         continue;
414                 }
415
416                 /* Connected */
417
418                 if (!(status & UPS_PORT_POWER))
419                         printf("%s: strange, connected port %d has no power\n",
420                                USBDEVNAME(sc->sc_dev), port);
421
422                 /* Wait for maximum device power up time. */
423                 usbd_delay_ms(dev, USB_PORT_POWERUP_DELAY);
424
425                 /* Reset port, which implies enabling it. */
426                 if (usbd_reset_port(dev, port, &up->status)) {
427                         printf("uhub_explore: port=%d reset failed\n",
428                                  port);
429                         continue;
430                 }
431
432                 /* Get device info and set its address. */
433                 err = usbd_new_device(USBDEV(sc->sc_dev), dev->bus, 
434                           dev->depth + 1, status & UPS_LOW_SPEED, 
435                           port, up);
436                 /* XXX retry a few times? */
437                 if (err) {
438                         DPRINTFN(-1,("uhub_explore: usb_new_device failed, "
439                                      "error=%s\n", usbd_errstr(err)));
440                         /* Avoid addressing problems by disabling. */
441                         /* usbd_reset_port(dev, port, &up->status); */
442
443                         /* 
444                          * The unit refused to accept a new address, or had
445                          * some other serious problem.  Since we cannot leave
446                          * at 0 we have to disable the port instead.
447                          */
448                         printf("%s: device problem, disabling port %d\n",
449                                USBDEVNAME(sc->sc_dev), port);
450                         usbd_clear_port_feature(dev, port, UHF_PORT_ENABLE);
451                 } else {
452                         /* The port set up succeeded, reset error count. */
453                         up->restartcnt = 0;
454
455                         if (up->device->hub)
456                                 up->device->hub->explore(up->device);
457                 }
458         }
459         return (USBD_NORMAL_COMPLETION);
460 }
461
462 #if defined(__NetBSD__) || defined(__OpenBSD__)
463 int
464 uhub_activate(device_ptr_t self, enum devact act)
465 {
466         struct uhub_softc *sc = (struct uhub_softc *)self;
467         struct usbd_hub *hub = sc->sc_hub->hub;
468         usbd_device_handle dev;
469         int nports, port, i;
470
471         switch (act) {
472         case DVACT_ACTIVATE:
473                 return (EOPNOTSUPP);
474                 break;
475
476         case DVACT_DEACTIVATE:
477                 if (hub == NULL) /* malfunctioning hub */
478                         break;
479                 nports = hub->hubdesc.bNbrPorts;
480                 for(port = 0; port < nports; port++) {
481                         dev = hub->ports[port].device;
482                         if (dev != NULL && dev->subdevs != NULL) {
483                                 for (i = 0; dev->subdevs[i] != NULL; i++)
484                                         config_deactivate(dev->subdevs[i]);
485                         }
486                 }
487                 break;
488         }
489         return (0);
490 }
491 #endif
492
493 /*
494  * Called from process context when the hub is gone.
495  * Detach all devices on active ports.
496  */
497 USB_DETACH(uhub)
498 {
499         USB_DETACH_START(uhub, sc);
500         struct usbd_hub *hub = sc->sc_hub->hub;
501         struct usbd_port *rup;
502         int port, nports;
503
504 #if defined(__NetBSD__) || defined(__OpenBSD__)
505         DPRINTF(("uhub_detach: sc=%p flags=%d\n", sc, flags));
506 #elif defined(__FreeBSD__)
507         DPRINTF(("uhub_detach: sc=%port\n", sc));
508 #endif
509
510         if (hub == NULL)                /* Must be partially working */
511                 return (0);
512
513         usbd_abort_pipe(sc->sc_ipipe);
514         usbd_close_pipe(sc->sc_ipipe);
515
516         nports = hub->hubdesc.bNbrPorts;
517         for(port = 0; port < nports; port++) {
518                 rup = &hub->ports[port];
519                 if (rup->device)
520                         usb_disconnect_port(rup, self);
521         }
522         
523
524         free(hub, M_USBDEV);
525         sc->sc_hub->hub = NULL;
526
527         return (0);
528 }
529
530 #if defined(__FreeBSD__)
531 /* Called when a device has been detached from it */
532 Static void
533 uhub_child_detached(device_t self, device_t child)
534 {
535        struct uhub_softc *sc = device_get_softc(self);
536        usbd_device_handle devhub = sc->sc_hub;
537        usbd_device_handle dev;
538        int nports;
539        int port;
540        int i;
541
542        if (!devhub->hub)  
543                /* should never happen; children are only created after init */
544                panic("hub not fully initialised, but child deleted?");
545
546        nports = devhub->hub->hubdesc.bNbrPorts;
547        for (port = 0; port < nports; port++) {
548                dev = devhub->hub->ports[port].device;
549                if (dev && dev->subdevs) {
550                        for (i = 0; dev->subdevs[i]; i++) {
551                                if (dev->subdevs[i] == child) {
552                                        dev->subdevs[i] = NULL;
553                                        return;
554                                }
555                        }
556                }
557        }
558 }
559 #endif
560
561
562 /*
563  * Hub interrupt.
564  * This an indication that some port has changed status.
565  * Notify the bus event handler thread that we need
566  * to be explored again.
567  */
568 void
569 uhub_intr(usbd_xfer_handle xfer, usbd_private_handle addr, usbd_status status)
570 {
571         struct uhub_softc *sc = addr;
572
573         DPRINTFN(5,("uhub_intr: sc=%p\n", sc));
574         if (status != USBD_NORMAL_COMPLETION)
575                 usbd_clear_endpoint_stall_async(sc->sc_ipipe);
576
577         usb_needs_explore(sc->sc_hub->bus);
578 }
579
580 #if defined(__FreeBSD__)
581 DRIVER_MODULE(uhub, usb, uhubroot_driver, uhubroot_devclass, 0, 0);
582 DRIVER_MODULE(uhub, uhub, uhub_driver, uhub_devclass, usbd_driver_load, 0);
583 #endif