4fb89e5a339bb1e9b68748f08613d87660348f15
[games.git] / sys / bus / usb / usb.c
1 /*
2  * $NetBSD: usb.c,v 1.68 2002/02/20 20:30:12 christos Exp $
3  * $FreeBSD: src/sys/dev/usb/usb.c,v 1.106 2005/03/27 15:31:23 iedowse Exp $
4  * $DragonFly: src/sys/bus/usb/usb.c,v 1.44 2008/05/25 16:53:41 mneumann Exp $
5  */
6
7 /* Also already merged from NetBSD:
8  *      $NetBSD: usb.c,v 1.70 2002/05/09 21:54:32 augustss Exp $
9  *      $NetBSD: usb.c,v 1.71 2002/06/01 23:51:04 lukem Exp $
10  *      $NetBSD: usb.c,v 1.73 2002/09/23 05:51:19 simonb Exp $
11  *      $NetBSD: usb.c,v 1.80 2003/11/07 17:03:25 wiz Exp $
12  */
13
14 /*
15  * Copyright (c) 1998 The NetBSD Foundation, Inc.
16  * All rights reserved.
17  *
18  * This code is derived from software contributed to The NetBSD Foundation
19  * by Lennart Augustsson (lennart@augustsson.net) at
20  * Carlstedt Research & Technology.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the above copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *        This product includes software developed by the NetBSD
33  *        Foundation, Inc. and its contributors.
34  * 4. Neither the name of The NetBSD Foundation nor the names of its
35  *    contributors may be used to endorse or promote products derived
36  *    from this software without specific prior written permission.
37  *
38  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
39  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
40  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
41  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
42  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
43  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
44  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
45  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
46  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
47  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
48  * POSSIBILITY OF SUCH DAMAGE.
49  */
50
51 /*
52  * USB specifications and other documentation can be found at
53  * http://www.usb.org/developers/docs/ and
54  * http://www.usb.org/developers/devclass_docs/
55  */
56
57 #include <sys/param.h>
58 #include <sys/systm.h>
59 #include <sys/kernel.h>
60 #include <sys/lock.h>
61 #include <sys/malloc.h>
62 #include <sys/unistd.h>
63 #include <sys/module.h>
64 #include <sys/bus.h>
65 #include <sys/fcntl.h>
66 #include <sys/filio.h>
67 #include <sys/uio.h>
68 #include <sys/kthread.h>
69 #include <sys/proc.h>
70 #include <sys/conf.h>
71 #include <sys/device.h>
72 #include <sys/poll.h>
73 #include <sys/select.h>
74 #include <sys/vnode.h>
75 #include <sys/signalvar.h>
76 #include <sys/sysctl.h>
77 #include <sys/thread2.h>
78
79 #include <bus/usb/usb.h>
80 #include <bus/usb/usbdi.h>
81 #include <bus/usb/usbdi_util.h>
82
83 #define USBUNIT(d)      (minor(d))      /* usb_discover device nodes, kthread */
84 #define USB_DEV_MINOR   255             /* event queue device */
85
86 MALLOC_DEFINE(M_USB, "USB", "USB");
87 MALLOC_DEFINE(M_USBDEV, "USBdev", "USB device");
88 MALLOC_DEFINE(M_USBHC, "USBHC", "USB host controller");
89
90 #include "usb_if.h"
91
92 #include <bus/usb/usbdivar.h>
93 #include <bus/usb/usb_quirks.h>
94
95 /* Define this unconditionally in case a kernel module is loaded that
96  * has been compiled with debugging options.
97  */
98 SYSCTL_NODE(_hw, OID_AUTO, usb, CTLFLAG_RW, 0, "USB debugging");
99
100 #ifdef USB_DEBUG
101 #define DPRINTF(x)      if (usbdebug) kprintf x
102 #define DPRINTFN(n,x)   if (usbdebug>(n)) kprintf x
103 int     usbdebug = 0;
104 SYSCTL_INT(_hw_usb, OID_AUTO, debug, CTLFLAG_RW,
105            &usbdebug, 0, "usb debug level");
106 /*
107  * 0  - do usual exploration
108  * 1  - do not use timeout exploration
109  * >1 - do no exploration
110  */
111 int     usb_noexplore = 0;
112 #else
113 #define DPRINTF(x)
114 #define DPRINTFN(n,x)
115 #endif
116
117 struct usb_softc {
118         device_t        sc_dev;         /* base device */
119         cdev_t          sc_usbdev;
120         TAILQ_ENTRY(usb_softc) sc_coldexplist; /* cold needs-explore list */
121         usbd_bus_handle sc_bus;         /* USB controller */
122         struct usbd_port sc_port;       /* dummy port for root hub */
123
124         struct thread   *sc_event_thread;
125
126         char            sc_dying;
127 };
128
129 struct usb_taskq {
130         TAILQ_HEAD(, usb_task)  tasks;
131         struct thread           *task_thread_proc;
132         const char              *name;
133         int                     taskcreated;    /* task thread exists. */
134 };
135 static struct usb_taskq usb_taskq[USB_NUM_TASKQS];
136
137 d_open_t  usbopen;
138 d_close_t usbclose;
139 d_read_t usbread;
140 d_ioctl_t usbioctl;
141 d_poll_t usbpoll;
142
143 struct dev_ops usb_ops = {
144         { "usb", USB_CDEV_MAJOR, 0 },
145         .d_open =       usbopen,
146         .d_close =      usbclose,
147         .d_read =       usbread,
148         .d_ioctl =      usbioctl,
149         .d_poll =       usbpoll,
150 };
151
152 static void     usb_discover(void *);
153 static bus_child_detached_t usb_child_detached;
154 static void     usb_create_event_thread(void *);
155 static void     usb_event_thread(void *);
156 static void     usb_task_thread(void *);
157
158 static cdev_t usb_dev;          /* The /dev/usb device. */
159 static int usb_ndevs;                   /* Number of /dev/usbN devices. */
160 /* Busses to explore at the end of boot-time device configuration */
161 static TAILQ_HEAD(, usb_softc) usb_coldexplist =
162     TAILQ_HEAD_INITIALIZER(usb_coldexplist);
163  
164 #define USB_MAX_EVENTS 100
165 struct usb_event_q {
166         struct usb_event ue;
167         TAILQ_ENTRY(usb_event_q) next;
168 };
169 static TAILQ_HEAD(, usb_event_q) usb_events =
170         TAILQ_HEAD_INITIALIZER(usb_events);
171 static int usb_nevents = 0;
172 static struct selinfo usb_selevent;
173 static struct proc *usb_async_proc;  /* process that wants USB SIGIO */
174 static int usb_dev_open = 0;
175 static void usb_add_event(int, struct usb_event *);
176
177 static int usb_get_next_event(struct usb_event *);
178
179 static const char *usbrev_str[] = USBREV_STR;
180
181 static device_probe_t usb_match;
182 static device_attach_t usb_attach;
183 static device_detach_t usb_detach;
184
185 static devclass_t usb_devclass;
186
187 static kobj_method_t usb_methods[] = {
188         DEVMETHOD(device_probe, usb_match),
189         DEVMETHOD(device_attach, usb_attach),
190         DEVMETHOD(device_detach, usb_detach),
191         DEVMETHOD(bus_child_detached, usb_child_detached),
192         DEVMETHOD(device_suspend, bus_generic_suspend),
193         DEVMETHOD(device_resume, bus_generic_resume),
194         DEVMETHOD(device_shutdown, bus_generic_shutdown),
195         {0,0}
196 };
197
198 static driver_t usb_driver = {
199         "usb",
200         usb_methods,
201         sizeof(struct usb_softc)
202 };
203
204 MODULE_DEPEND(usb, usb, 1, 1, 1);
205 MODULE_VERSION(usb, 1);
206
207 static int
208 usb_match(device_t self)
209 {
210         DPRINTF(("usbd_match\n"));
211         return (UMATCH_GENERIC);
212 }
213
214 static int
215 usb_attach(device_t self)
216 {
217         struct usb_softc *sc = device_get_softc(self);
218         void *aux = device_get_ivars(self);
219         cdev_t tmp_dev;
220         usbd_device_handle dev;
221         usbd_status err;
222         int usbrev;
223         int speed;
224         struct usb_event ue;
225
226         sc->sc_dev = self;
227
228         DPRINTF(("usbd_attach\n"));
229
230         usbd_init();
231         sc->sc_bus = aux;
232         sc->sc_bus->usbctl = sc;
233         sc->sc_port.power = USB_MAX_POWER;
234
235         usbrev = sc->sc_bus->usbrev;
236         device_printf(sc->sc_dev, "USB revision %s", usbrev_str[usbrev]);
237         switch (usbrev) {
238         case USBREV_1_0:
239         case USBREV_1_1:
240                 speed = USB_SPEED_FULL;
241                 break;
242         case USBREV_2_0:
243                 speed = USB_SPEED_HIGH;
244                 break;
245         default:
246                 kprintf(", not supported\n");
247                 sc->sc_dying = 1;
248                 return ENXIO;
249         }
250         kprintf("\n");
251
252         /* Make sure not to use tsleep() if we are cold booting. */
253         if (cold)
254                 sc->sc_bus->use_polling++;
255
256         ue.u.ue_ctrlr.ue_bus = device_get_unit(sc->sc_dev);
257         usb_add_event(USB_EVENT_CTRLR_ATTACH, &ue);
258
259 #ifdef USB_USE_SOFTINTR
260 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
261         /* XXX we should have our own level */
262         sc->sc_bus->soft = softintr_establish(IPL_SOFTNET,
263             sc->sc_bus->methods->soft_intr, sc->sc_bus);
264         if (sc->sc_bus->soft == NULL) {
265                 device_printf(sc->sc_dev, "can't register softintr\n");
266                 sc->sc_dying = 1;
267                 return ENXIO;
268         }
269 #else
270         callout_init(&sc->sc_bus->softi);
271 #endif
272 #endif
273
274         err = usbd_new_device(sc->sc_dev, sc->sc_bus, 0, speed, 0,
275                   &sc->sc_port);
276         if (!err) {
277                 dev = sc->sc_port.device;
278                 if (dev->hub == NULL) {
279                         sc->sc_dying = 1;
280                         device_printf(sc->sc_dev,
281                             "root device is not a hub\n");
282                         return ENXIO;
283                 }
284                 sc->sc_bus->root_hub = dev;
285 #if 1
286                 /*
287                  * Turning this code off will delay attachment of USB devices
288                  * until the USB event thread is running, which means that
289                  * the keyboard will not work until after cold boot.
290                  */
291                 if (cold) {
292                         /* Explore high-speed busses before others. */
293                         if (speed == USB_SPEED_HIGH)
294                                 dev->hub->explore(sc->sc_bus->root_hub);
295                         else
296                                 TAILQ_INSERT_TAIL(&usb_coldexplist, sc,
297                                     sc_coldexplist);
298                 }
299 #endif
300         } else {
301                 device_printf(sc->sc_dev,
302                     "root hub problem, error=%d\n", err);
303                 sc->sc_dying = 1;
304         }
305         if (cold)
306                 sc->sc_bus->use_polling--;
307
308         usb_create_event_thread(sc);
309         /* The per controller devices (used for usb_discover) */
310         /* XXX This is redundant now, but old usbd's will want it */
311         dev_ops_add(&usb_ops, -1, device_get_unit(self));
312         tmp_dev = make_dev(&usb_ops, device_get_unit(self),
313                            UID_ROOT, GID_OPERATOR, 0660,
314                            "usb%d", device_get_unit(self));
315         sc->sc_usbdev = reference_dev(tmp_dev);
316         if (usb_ndevs++ == 0) {
317                 /* The device spitting out events */
318                 dev_ops_add(&usb_ops, -1, USB_DEV_MINOR);
319                 tmp_dev = make_dev(&usb_ops, USB_DEV_MINOR,
320                                    UID_ROOT, GID_OPERATOR, 0660, "usb");
321                 usb_dev = reference_dev(tmp_dev);
322         }
323
324         return 0;
325 }
326
327 static const char *taskq_names[] = USB_TASKQ_NAMES;
328
329 void
330 usb_create_event_thread(void *arg)
331 {
332         struct usb_softc *sc = arg;
333         int i;
334
335         if (kthread_create(usb_event_thread, sc, &sc->sc_event_thread,
336                            "%s", device_get_nameunit(sc->sc_dev))) {
337                 device_printf(sc->sc_dev,
338                     "unable to create event thread for\n");
339                 panic("usb_create_event_thread");
340         }
341
342         for (i = 0; i < USB_NUM_TASKQS; i++) {
343                 struct usb_taskq *taskq = &usb_taskq[i];
344
345                 if (taskq->taskcreated == 0) {
346                         taskq->taskcreated = 1;
347                         taskq->name = taskq_names[i];
348                         TAILQ_INIT(&taskq->tasks);
349                         if (kthread_create(usb_task_thread, taskq,
350                             &taskq->task_thread_proc, taskq->name)) {
351                                 kprintf("unable to create task thread\n");
352                                 panic("usb_create_event_thread task");
353                         }
354                 }
355         }
356 }
357
358 /*
359  * Add a task to be performed by the task thread.  This function can be
360  * called from any context and the task will be executed in a process
361  * context ASAP.
362  */
363 void
364 usb_add_task(usbd_device_handle dev, struct usb_task *task, int queue)
365 {
366         struct usb_taskq *taskq;
367
368         crit_enter();
369
370         taskq = &usb_taskq[queue];
371         if (task->queue == -1) {
372                 DPRINTFN(2,("usb_add_task: task=%p\n", task));
373                 TAILQ_INSERT_TAIL(&taskq->tasks, task, next);
374                 task->queue = queue;
375         } else {
376                 DPRINTFN(3,("usb_add_task: task=%p on q\n", task));
377         }
378         wakeup(&taskq->tasks);
379
380         crit_exit();
381 }
382
383 void
384 usb_do_task(usbd_device_handle dev, struct usb_task *task, int queue,
385             int time_out)
386 {
387         struct usb_taskq *taskq;
388
389         crit_enter();
390
391         taskq = &usb_taskq[queue];
392         if (task->queue == -1) {
393                 DPRINTFN(2,("usb_add_task: task=%p\n", task));
394                 TAILQ_INSERT_TAIL(&taskq->tasks, task, next);
395                 task->queue = queue;
396         } else {
397                 DPRINTFN(3,("usb_add_task: task=%p on q\n", task));
398         }
399         wakeup(&taskq->tasks);
400
401         /* Wait until task is finished */
402         tsleep((&taskq->tasks + 1), 0, "usbdotsk", time_out);
403
404         crit_exit();
405 }
406
407 void
408 usb_rem_task(usbd_device_handle dev, struct usb_task *task)
409 {
410         crit_enter();
411         if (task->queue != -1) {
412                 TAILQ_REMOVE(&usb_taskq[task->queue].tasks, task, next);
413                 task->queue = -1;
414         }
415         crit_exit();
416 }
417
418 void
419 usb_event_thread(void *arg)
420 {
421         struct usb_softc *sc = arg;
422
423         DPRINTF(("usb_event_thread: start\n"));
424
425         /*
426          * In case this controller is a companion controller to an
427          * EHCI controller we need to wait until the EHCI controller
428          * has grabbed the port.
429          * XXX It would be nicer to do this with a tsleep(), but I don't
430          * know how to synchronize the creation of the threads so it
431          * will work.
432          */
433         usb_delay_ms(sc->sc_bus, 500);
434
435         crit_enter();
436
437         /* Make sure first discover does something. */
438         sc->sc_bus->needs_explore = 1;
439         usb_discover(sc);
440
441         while (!sc->sc_dying) {
442 #ifdef USB_DEBUG
443                 if (usb_noexplore < 2)
444 #endif
445                 usb_discover(sc);
446 #ifdef USB_DEBUG
447                 tsleep(&sc->sc_bus->needs_explore, 0, "usbevt",
448                        usb_noexplore ? 0 : hz * 60);
449 #else
450                 tsleep(&sc->sc_bus->needs_explore, 0, "usbevt", hz * 60);
451 #endif
452                 DPRINTFN(2,("usb_event_thread: woke up\n"));
453         }
454         sc->sc_event_thread = NULL;
455
456         crit_exit();
457
458         /* In case parent is waiting for us to exit. */
459         wakeup(sc);
460
461         DPRINTF(("usb_event_thread: exit\n"));
462         kthread_exit();
463 }
464
465 void
466 usb_task_thread(void *arg)
467 {
468         struct usb_task *task;
469         struct usb_taskq *taskq;
470
471         crit_enter();
472
473         taskq = arg;
474         DPRINTF(("usb_task_thread: start taskq %s\n", taskq->name));
475
476         while (usb_ndevs > 0) {
477                 task = TAILQ_FIRST(&taskq->tasks);
478                 if (task == NULL) {
479                         tsleep(&taskq->tasks, 0, "usbtsk", 0);
480                         task = TAILQ_FIRST(&taskq->tasks);
481                 }
482                 DPRINTFN(2,("usb_task_thread: woke up task=%p\n", task));
483                 if (task != NULL) {
484                         TAILQ_REMOVE(&taskq->tasks, task, next);
485                         task->queue = -1;
486                         crit_exit();
487                         task->fun(task->arg);
488                         crit_enter();
489                         wakeup((&taskq->tasks + 1));
490                 }
491         }
492
493         crit_exit();
494
495         taskq->taskcreated = 0;
496         wakeup(&taskq->taskcreated);
497
498         DPRINTF(("usb_event_thread: exit\n"));
499 }
500
501 int
502 usbopen(struct dev_open_args *ap)
503 {
504         cdev_t dev = ap->a_head.a_dev;
505         int unit = USBUNIT(dev);
506         struct usb_softc *sc;
507
508         if (unit == USB_DEV_MINOR) {
509                 if (usb_dev_open)
510                         return (EBUSY);
511                 usb_dev_open = 1;
512                 usb_async_proc = NULL;
513                 return (0);
514         }
515
516         sc = devclass_get_softc(usb_devclass, unit);
517         if (sc == NULL)
518                 return (ENXIO);
519
520         if (sc->sc_dying)
521                 return (EIO);
522
523         return (0);
524 }
525
526 int
527 usbread(struct dev_read_args *ap)
528 {
529         cdev_t dev = ap->a_head.a_dev;
530         struct uio *uio = ap->a_uio;
531         struct usb_event ue;
532         int unit = USBUNIT(dev);
533         int error, n;
534
535         if (unit != USB_DEV_MINOR)
536                 return (ENODEV);
537
538         if (uio->uio_resid != sizeof(struct usb_event))
539                 return (EINVAL);
540
541         error = 0;
542         crit_enter();
543         for (;;) {
544                 n = usb_get_next_event(&ue);
545                 if (n != 0)
546                         break;
547                 if (ap->a_ioflag & IO_NDELAY) {
548                         error = EWOULDBLOCK;
549                         break;
550                 }
551                 error = tsleep(&usb_events, PCATCH, "usbrea", 0);
552                 if (error)
553                         break;
554         }
555         crit_exit();
556         if (!error)
557                 error = uiomove((void *)&ue, uio->uio_resid, uio);
558
559         return (error);
560 }
561
562 int
563 usbclose(struct dev_close_args *ap)
564 {
565         cdev_t dev = ap->a_head.a_dev;
566         int unit = USBUNIT(dev);
567
568         if (unit == USB_DEV_MINOR) {
569                 usb_async_proc = NULL;
570                 usb_dev_open = 0;
571         }
572
573         return (0);
574 }
575
576 int
577 usbioctl(struct dev_ioctl_args *ap)
578 {
579         cdev_t devt = ap->a_head.a_dev;
580         struct usb_softc *sc;
581         int unit = USBUNIT(devt);
582
583         if (unit == USB_DEV_MINOR) {
584                 switch (ap->a_cmd) {
585                 case FIOASYNC:
586                         if (*(int *)ap->a_data)
587                                 usb_async_proc = curproc;
588                         else
589                                 usb_async_proc = NULL;
590                         return (0);
591
592                 default:
593                         return (EINVAL);
594                 }
595         }
596
597         sc = devclass_get_softc(usb_devclass, unit);
598
599         if (sc->sc_dying)
600                 return (EIO);
601
602         switch (ap->a_cmd) {
603         /* This part should be deleted */
604         case USB_DISCOVER:
605                 break;
606         case USB_REQUEST:
607         {
608                 struct usb_ctl_request *ur = (void *)ap->a_data;
609                 int len = UGETW(ur->ucr_request.wLength);
610                 struct iovec iov;
611                 struct uio uio;
612                 void *ptr = 0;
613                 int addr = ur->ucr_addr;
614                 usbd_status err;
615                 int error = 0;
616
617                 DPRINTF(("usbioctl: USB_REQUEST addr=%d len=%d\n", addr, len));
618                 if (len < 0 || len > 32768)
619                         return (EINVAL);
620                 if (addr < 0 || addr >= USB_MAX_DEVICES ||
621                     sc->sc_bus->devices[addr] == 0)
622                         return (EINVAL);
623                 if (len != 0) {
624                         iov.iov_base = (caddr_t)ur->ucr_data;
625                         iov.iov_len = len;
626                         uio.uio_iov = &iov;
627                         uio.uio_iovcnt = 1;
628                         uio.uio_resid = len;
629                         uio.uio_offset = 0;
630                         uio.uio_segflg = UIO_USERSPACE;
631                         uio.uio_rw =
632                                 ur->ucr_request.bmRequestType & UT_READ ?
633                                 UIO_READ : UIO_WRITE;
634                         uio.uio_td = curthread;
635                         ptr = kmalloc(len, M_TEMP, M_WAITOK);
636                         if (uio.uio_rw == UIO_WRITE) {
637                                 error = uiomove(ptr, len, &uio);
638                                 if (error)
639                                         goto ret;
640                         }
641                 }
642                 err = usbd_do_request_flags(sc->sc_bus->devices[addr],
643                           &ur->ucr_request, ptr, ur->ucr_flags, &ur->ucr_actlen,
644                           USBD_DEFAULT_TIMEOUT);
645                 if (err) {
646                         error = EIO;
647                         goto ret;
648                 }
649                 if (len != 0) {
650                         if (uio.uio_rw == UIO_READ) {
651                                 error = uiomove(ptr, len, &uio);
652                                 if (error)
653                                         goto ret;
654                         }
655                 }
656         ret:
657                 if (ptr)
658                         kfree(ptr, M_TEMP);
659                 return (error);
660         }
661
662         case USB_DEVICEINFO:
663         {
664                 struct usb_device_info *di = (void *)ap->a_data;
665                 int addr = di->udi_addr;
666                 usbd_device_handle dev;
667
668                 if (addr < 1 || addr >= USB_MAX_DEVICES)
669                         return (EINVAL);
670                 dev = sc->sc_bus->devices[addr];
671                 if (dev == NULL)
672                         return (ENXIO);
673                 usbd_fill_deviceinfo(dev, di, 1);
674                 break;
675         }
676
677         case USB_DEVICESTATS:
678                 *(struct usb_device_stats *)ap->a_data = sc->sc_bus->stats;
679                 break;
680
681         default:
682                 return (EINVAL);
683         }
684         return (0);
685 }
686
687 int
688 usbpoll(struct dev_poll_args *ap)
689 {
690         cdev_t dev = ap->a_head.a_dev;
691         int revents, mask;
692         int unit = USBUNIT(dev);
693
694         if (unit == USB_DEV_MINOR) {
695                 revents = 0;
696                 mask = POLLIN | POLLRDNORM;
697
698                 crit_enter();
699                 if (ap->a_events & mask && usb_nevents > 0)
700                         revents |= ap->a_events & mask;
701                 if (revents == 0 && ap->a_events & mask)
702                         selrecord(curthread, &usb_selevent);
703                 crit_exit();
704                 ap->a_events = revents;
705                 return (0);
706         } else {
707                 ap->a_events = 0;
708                 return (0);     /* select/poll never wakes up - back compat */
709         }
710 }
711
712 /* Explore device tree from the root. */
713 static void
714 usb_discover(void *v)
715 {
716         struct usb_softc *sc = v;
717
718         DPRINTFN(2,("usb_discover\n"));
719 #ifdef USB_DEBUG
720         if (usb_noexplore > 1)
721                 return;
722 #endif
723
724         /*
725          * We need mutual exclusion while traversing the device tree,
726          * but this is guaranteed since this function is only called
727          * from the event thread for the controller.
728          */
729         crit_enter();
730         while (sc->sc_bus->needs_explore && !sc->sc_dying) {
731                 sc->sc_bus->needs_explore = 0;
732
733                 crit_exit();
734                 sc->sc_bus->root_hub->hub->explore(sc->sc_bus->root_hub);
735                 crit_enter();
736
737         }
738         crit_exit();
739 }
740
741 void
742 usb_needs_explore(usbd_device_handle dev)
743 {
744         DPRINTFN(2,("usb_needs_explore\n"));
745         dev->bus->needs_explore = 1;
746         wakeup(&dev->bus->needs_explore);
747 }
748
749 /* Called from a critical section */
750 int
751 usb_get_next_event(struct usb_event *ue)
752 {
753         struct usb_event_q *ueq;
754
755         if (usb_nevents <= 0)
756                 return (0);
757         ueq = TAILQ_FIRST(&usb_events);
758 #ifdef DIAGNOSTIC
759         if (ueq == NULL) {
760                 kprintf("usb: usb_nevents got out of sync! %d\n", usb_nevents);
761                 usb_nevents = 0;
762                 return (0);
763         }
764 #endif
765         *ue = ueq->ue;
766         TAILQ_REMOVE(&usb_events, ueq, next);
767         kfree(ueq, M_USBDEV);
768         usb_nevents--;
769         return (1);
770 }
771
772 void
773 usbd_add_dev_event(int type, usbd_device_handle udev)
774 {
775         struct usb_event ue;
776
777         usbd_fill_deviceinfo(udev, &ue.u.ue_device, USB_EVENT_IS_ATTACH(type));
778         usb_add_event(type, &ue);
779 }
780
781 void
782 usbd_add_drv_event(int type, usbd_device_handle udev, device_t dev)
783 {
784         struct usb_event ue;
785
786         ue.u.ue_driver.ue_cookie = udev->cookie;
787         strncpy(ue.u.ue_driver.ue_devname, device_get_nameunit(dev),
788                 sizeof ue.u.ue_driver.ue_devname);
789         usb_add_event(type, &ue);
790 }
791
792 void
793 usb_add_event(int type, struct usb_event *uep)
794 {
795         struct usb_event_q *ueq;
796         struct usb_event ue;
797         struct timeval thetime;
798
799         ueq = kmalloc(sizeof *ueq, M_USBDEV, M_INTWAIT);
800         ueq->ue = *uep;
801         ueq->ue.ue_type = type;
802         microtime(&thetime);
803         TIMEVAL_TO_TIMESPEC(&thetime, &ueq->ue.ue_time);
804
805         crit_enter();
806         if (USB_EVENT_IS_DETACH(type)) {
807                 struct usb_event_q *ueqi, *ueqi_next;
808
809                 for (ueqi = TAILQ_FIRST(&usb_events); ueqi; ueqi = ueqi_next) {
810                         ueqi_next = TAILQ_NEXT(ueqi, next);
811                         if (ueqi->ue.u.ue_driver.ue_cookie.cookie ==
812                             uep->u.ue_device.udi_cookie.cookie) {
813                                 TAILQ_REMOVE(&usb_events, ueqi, next);
814                                 kfree(ueqi, M_USBDEV);
815                                 usb_nevents--;
816                                 ueqi_next = TAILQ_FIRST(&usb_events);
817                         }
818                 }
819         }
820         if (usb_nevents >= USB_MAX_EVENTS) {
821                 /* Too many queued events, drop an old one. */
822                 DPRINTF(("usb: event dropped\n"));
823                 usb_get_next_event(&ue);
824         }
825         TAILQ_INSERT_TAIL(&usb_events, ueq, next);
826         usb_nevents++;
827         wakeup(&usb_events);
828         selwakeup(&usb_selevent);
829         if (usb_async_proc != NULL) {
830                 ksignal(usb_async_proc, SIGIO);
831         }
832         crit_exit();
833 }
834
835 void
836 usb_schedsoftintr(usbd_bus_handle bus)
837 {
838         DPRINTFN(10,("usb_schedsoftintr: polling=%d\n", bus->use_polling));
839 #ifdef USB_USE_SOFTINTR
840         if (bus->use_polling) {
841                 bus->methods->soft_intr(bus);
842         } else {
843 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
844                 softintr_schedule(bus->soft);
845 #else
846                 if (!callout_pending(&bus->softi))
847                         callout_reset(&bus->softi, 0, bus->methods->soft_intr,
848                             bus);
849 #endif /* __HAVE_GENERIC_SOFT_INTERRUPTS */
850         }
851 #else
852        bus->methods->soft_intr(bus);
853 #endif /* USB_USE_SOFTINTR */
854 }
855
856 static int
857 usb_detach(device_t self)
858 {
859         struct usb_softc *sc = device_get_softc(self);
860         struct usb_event ue;
861
862         DPRINTF(("usb_detach: start\n"));
863
864         sc->sc_dying = 1;
865
866         /* Make all devices disconnect. */
867         if (sc->sc_port.device != NULL)
868                 usb_disconnect_port(&sc->sc_port, self);
869
870         /* Kill off event thread. */
871         if (sc->sc_event_thread != NULL) {
872                 wakeup(&sc->sc_bus->needs_explore);
873                 if (tsleep(sc, 0, "usbdet", hz * 60))
874                         device_printf(sc->sc_dev,
875                             "event thread didn't die\n");
876                 DPRINTF(("usb_detach: event thread dead\n"));
877         }
878
879         destroy_dev(sc->sc_usbdev);
880         if (--usb_ndevs == 0) {
881                 int i;
882
883                 destroy_dev(usb_dev);
884                 usb_dev = NULL;
885
886                 for (i = 0; i < USB_NUM_TASKQS; i++) {
887                         struct usb_taskq *taskq = &usb_taskq[i];
888                         wakeup(&taskq->tasks);
889                         if (tsleep(&taskq->taskcreated, 0, "usbtdt",
890                             hz * 60)) {
891                                 kprintf("usb task thread %s didn't die\n",
892                                     taskq->name);
893                         }
894                 }
895         }
896
897         usbd_finish();
898
899 #ifdef USB_USE_SOFTINTR
900 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
901         if (sc->sc_bus->soft != NULL) {
902                 softintr_disestablish(sc->sc_bus->soft);
903                 sc->sc_bus->soft = NULL;
904         }
905 #else
906         callout_stop(&sc->sc_bus->softi);
907 #endif
908 #endif
909
910         ue.u.ue_ctrlr.ue_bus = device_get_unit(sc->sc_dev);
911         usb_add_event(USB_EVENT_CTRLR_DETACH, &ue);
912
913         return (0);
914 }
915
916 static void
917 usb_child_detached(device_t self, device_t child)
918 {
919         struct usb_softc *sc = device_get_softc(self);
920
921         /* XXX, should check it is the right device. */
922         sc->sc_port.device = NULL;
923 }
924
925 /* Explore USB busses at the end of device configuration */
926 static void
927 usb_cold_explore(void *arg)
928 {
929         struct usb_softc *sc;
930
931         KASSERT(cold || TAILQ_EMPTY(&usb_coldexplist),
932             ("usb_cold_explore: busses to explore when !cold"));
933         while (!TAILQ_EMPTY(&usb_coldexplist)) {
934                 sc = TAILQ_FIRST(&usb_coldexplist);
935                 TAILQ_REMOVE(&usb_coldexplist, sc, sc_coldexplist);
936
937                 sc->sc_bus->use_polling++;
938                 sc->sc_port.device->hub->explore(sc->sc_bus->root_hub);
939                 sc->sc_bus->use_polling--;
940         }
941 }
942
943 SYSINIT(usb_cold_explore, SI_SUB_CONFIGURE, SI_ORDER_MIDDLE,
944     usb_cold_explore, NULL);
945
946 DRIVER_MODULE(usb, ohci, usb_driver, usb_devclass, 0, 0);
947 DRIVER_MODULE(usb, uhci, usb_driver, usb_devclass, 0, 0);
948 DRIVER_MODULE(usb, ehci, usb_driver, usb_devclass, 0, 0);
949