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