Nuke USB_DECLARE_DRIVER and USB_DECLARE_DRIVER_INIT macros.
[dragonfly.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.38 2007/07/02 23:52:04 hasso 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         usbd_bus_handle sc_bus;         /* USB controller */
121         struct usbd_port sc_port;       /* dummy port for root hub */
122
123         struct thread   *sc_event_thread;
124
125         char            sc_dying;
126 };
127
128 struct usb_taskq {
129         TAILQ_HEAD(, usb_task)  tasks;
130         usb_proc_ptr            task_thread_proc;
131         const char              *name;
132         int                     taskcreated;    /* task thread exists. */
133 };
134 static struct usb_taskq usb_taskq[USB_NUM_TASKQS];
135
136 d_open_t  usbopen;
137 d_close_t usbclose;
138 d_read_t usbread;
139 d_ioctl_t usbioctl;
140 d_poll_t usbpoll;
141
142 struct dev_ops usb_ops = {
143         { "usb", USB_CDEV_MAJOR, 0 },
144         .d_open =       usbopen,
145         .d_close =      usbclose,
146         .d_read =       usbread,
147         .d_ioctl =      usbioctl,
148         .d_poll =       usbpoll,
149 };
150
151 static void     usb_discover(void *);
152 static bus_child_detached_t usb_child_detached;
153 static void     usb_create_event_thread(void *);
154 static void     usb_event_thread(void *);
155 static void     usb_task_thread(void *);
156
157 static cdev_t usb_dev;          /* The /dev/usb device. */
158 static int usb_ndevs;                   /* Number of /dev/usbN devices. */
159
160 #define USB_MAX_EVENTS 100
161 struct usb_event_q {
162         struct usb_event ue;
163         TAILQ_ENTRY(usb_event_q) next;
164 };
165 static TAILQ_HEAD(, usb_event_q) usb_events =
166         TAILQ_HEAD_INITIALIZER(usb_events);
167 static int usb_nevents = 0;
168 static struct selinfo usb_selevent;
169 static struct proc *usb_async_proc;  /* process that wants USB SIGIO */
170 static int usb_dev_open = 0;
171 static void usb_add_event(int, struct usb_event *);
172
173 static int usb_get_next_event(struct usb_event *);
174
175 static const char *usbrev_str[] = USBREV_STR;
176
177 static device_probe_t usb_match;
178 static device_attach_t usb_attach;
179 static device_detach_t usb_detach;
180
181 static devclass_t usb_devclass;
182
183 static kobj_method_t usb_methods[] = {
184         DEVMETHOD(device_probe, usb_match),
185         DEVMETHOD(device_attach, usb_attach),
186         DEVMETHOD(device_detach, usb_detach),
187         DEVMETHOD(bus_child_detached, usb_child_detached),
188         DEVMETHOD(device_suspend, bus_generic_suspend),
189         DEVMETHOD(device_resume, bus_generic_resume),
190         DEVMETHOD(device_shutdown, bus_generic_shutdown),
191         {0,0}
192 };
193
194 static driver_t usb_driver = {
195         "usb",
196         usb_methods,
197         sizeof(struct usb_softc)
198 };
199
200 MODULE_DEPEND(usb, usb, 1, 1, 1);
201 MODULE_VERSION(usb, 1);
202
203 static int
204 usb_match(device_t self)
205 {
206         DPRINTF(("usbd_match\n"));
207         return (UMATCH_GENERIC);
208 }
209
210 static int
211 usb_attach(device_t self)
212 {
213         struct usb_softc *sc = device_get_softc(self);
214         void *aux = device_get_ivars(self);
215         cdev_t tmp_dev;
216         usbd_device_handle dev;
217         usbd_status err;
218         int usbrev;
219         int speed;
220         struct usb_event ue;
221
222         sc->sc_dev = self;
223
224         DPRINTF(("usbd_attach\n"));
225
226         usbd_init();
227         sc->sc_bus = aux;
228         sc->sc_bus->usbctl = sc;
229         sc->sc_port.power = USB_MAX_POWER;
230
231         kprintf("%s", device_get_nameunit(sc->sc_dev));
232         usbrev = sc->sc_bus->usbrev;
233         kprintf(": USB revision %s", usbrev_str[usbrev]);
234         switch (usbrev) {
235         case USBREV_1_0:
236         case USBREV_1_1:
237                 speed = USB_SPEED_FULL;
238                 break;
239         case USBREV_2_0:
240                 speed = USB_SPEED_HIGH;
241                 break;
242         default:
243                 kprintf(", not supported\n");
244                 sc->sc_dying = 1;
245                 return ENXIO;
246         }
247         kprintf("\n");
248
249 #if 0
250         /* Make sure not to use tsleep() if we are cold booting. */
251         if (cold)
252                 sc->sc_bus->use_polling++;
253 #endif
254
255         ue.u.ue_ctrlr.ue_bus = device_get_unit(sc->sc_dev);
256         usb_add_event(USB_EVENT_CTRLR_ATTACH, &ue);
257
258 #ifdef USB_USE_SOFTINTR
259 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
260         /* XXX we should have our own level */
261         sc->sc_bus->soft = softintr_establish(IPL_SOFTNET,
262             sc->sc_bus->methods->soft_intr, sc->sc_bus);
263         if (sc->sc_bus->soft == NULL) {
264                 kprintf("%s: can't register softintr\n", device_get_nameunit(sc->sc_dev));
265                 sc->sc_dying = 1;
266                 return ENXIO;
267         }
268 #else
269         callout_init(&sc->sc_bus->softi);
270 #endif
271 #endif
272
273         err = usbd_new_device(sc->sc_dev, sc->sc_bus, 0, speed, 0,
274                   &sc->sc_port);
275         if (!err) {
276                 dev = sc->sc_port.device;
277                 if (dev->hub == NULL) {
278                         sc->sc_dying = 1;
279                         kprintf("%s: root device is not a hub\n",
280                                device_get_nameunit(sc->sc_dev));
281                         return ENXIO;
282                 }
283                 sc->sc_bus->root_hub = dev;
284 #if 1
285                 /*
286                  * Turning this code off will delay attachment of USB devices
287                  * until the USB event thread is running, which means that
288                  * the keyboard will not work until after cold boot.
289                  */
290                 if (cold) {
291                         /*
292                          * XXX Exploring high speed device here will
293                          * hang the system.
294                          */
295                         if (speed != USB_SPEED_HIGH)
296                                 dev->hub->explore(sc->sc_bus->root_hub);
297                 }
298 #endif
299         } else {
300                 kprintf("%s: root hub problem, error=%d\n",
301                        device_get_nameunit(sc->sc_dev), err);
302                 sc->sc_dying = 1;
303         }
304 #if 0
305         if (cold)
306                 sc->sc_bus->use_polling--;
307 #endif
308
309         config_pending_incr();
310
311         usb_create_event_thread(sc);
312         /* The per controller devices (used for usb_discover) */
313         /* XXX This is redundant now, but old usbd's will want it */
314         dev_ops_add(&usb_ops, -1, device_get_unit(self));
315         tmp_dev = make_dev(&usb_ops, device_get_unit(self),
316                            UID_ROOT, GID_OPERATOR, 0660,
317                            "usb%d", device_get_unit(self));
318         sc->sc_usbdev = reference_dev(tmp_dev);
319         if (usb_ndevs++ == 0) {
320                 /* The device spitting out events */
321                 dev_ops_add(&usb_ops, -1, USB_DEV_MINOR);
322                 tmp_dev = make_dev(&usb_ops, USB_DEV_MINOR,
323                                    UID_ROOT, GID_OPERATOR, 0660, "usb");
324                 usb_dev = reference_dev(tmp_dev);
325         }
326
327         return 0;
328 }
329
330 static const char *taskq_names[] = USB_TASKQ_NAMES;
331
332 void
333 usb_create_event_thread(void *arg)
334 {
335         struct usb_softc *sc = arg;
336         int i;
337
338         if (kthread_create(usb_event_thread, sc, &sc->sc_event_thread,
339                            "%s", device_get_nameunit(sc->sc_dev))) {
340                 kprintf("%s: unable to create event thread for\n",
341                        device_get_nameunit(sc->sc_dev));
342                 panic("usb_create_event_thread");
343         }
344
345         for (i = 0; i < USB_NUM_TASKQS; i++) {
346                 struct usb_taskq *taskq = &usb_taskq[i];
347
348                 if (taskq->taskcreated == 0) {
349                         taskq->taskcreated = 1;
350                         taskq->name = taskq_names[i];
351                         TAILQ_INIT(&taskq->tasks);
352                         if (kthread_create(usb_task_thread, taskq,
353                             &taskq->task_thread_proc, taskq->name)) {
354                                 kprintf("unable to create task thread\n");
355                                 panic("usb_create_event_thread task");
356                         }
357                 }
358         }
359 }
360
361 /*
362  * Add a task to be performed by the task thread.  This function can be
363  * called from any context and the task will be executed in a process
364  * context ASAP.
365  */
366 void
367 usb_add_task(usbd_device_handle dev, struct usb_task *task, int queue)
368 {
369         struct usb_taskq *taskq;
370
371         crit_enter();
372
373         taskq = &usb_taskq[queue];
374         if (task->queue == -1) {
375                 DPRINTFN(2,("usb_add_task: task=%p\n", task));
376                 TAILQ_INSERT_TAIL(&taskq->tasks, task, next);
377                 task->queue = queue;
378         } else {
379                 DPRINTFN(3,("usb_add_task: task=%p on q\n", task));
380         }
381         wakeup(&taskq->tasks);
382
383         crit_exit();
384 }
385
386 void
387 usb_do_task(usbd_device_handle dev, struct usb_task *task, int queue,
388             int time_out)
389 {
390         struct usb_taskq *taskq;
391
392         crit_enter();
393
394         taskq = &usb_taskq[queue];
395         if (task->queue == -1) {
396                 DPRINTFN(2,("usb_add_task: task=%p\n", task));
397                 TAILQ_INSERT_TAIL(&taskq->tasks, task, next);
398                 task->queue = queue;
399         } else {
400                 DPRINTFN(3,("usb_add_task: task=%p on q\n", task));
401         }
402         wakeup(&taskq->tasks);
403
404         /* Wait until task is finished */
405         tsleep((&taskq->tasks + 1), 0, "usbdotsk", time_out);
406
407         crit_exit();
408 }
409
410 void
411 usb_rem_task(usbd_device_handle dev, struct usb_task *task)
412 {
413         crit_enter();
414         if (task->queue != -1) {
415                 TAILQ_REMOVE(&usb_taskq[task->queue].tasks, task, next);
416                 task->queue = -1;
417         }
418         crit_exit();
419 }
420
421 void
422 usb_event_thread(void *arg)
423 {
424         struct usb_softc *sc = arg;
425
426         DPRINTF(("usb_event_thread: start\n"));
427
428         /*
429          * In case this controller is a companion controller to an
430          * EHCI controller we need to wait until the EHCI controller
431          * has grabbed the port.
432          * XXX It would be nicer to do this with a tsleep(), but I don't
433          * know how to synchronize the creation of the threads so it
434          * will work.
435          */
436         usb_delay_ms(sc->sc_bus, 500);
437
438         crit_enter();
439
440         /* Make sure first discover does something. */
441         sc->sc_bus->needs_explore = 1;
442         usb_discover(sc);
443         config_pending_decr();
444
445         while (!sc->sc_dying) {
446 #ifdef USB_DEBUG
447                 if (usb_noexplore < 2)
448 #endif
449                 usb_discover(sc);
450 #ifdef USB_DEBUG
451                 tsleep(&sc->sc_bus->needs_explore, 0, "usbevt",
452                        usb_noexplore ? 0 : hz * 60);
453 #else
454                 tsleep(&sc->sc_bus->needs_explore, 0, "usbevt", hz * 60);
455 #endif
456                 DPRINTFN(2,("usb_event_thread: woke up\n"));
457         }
458         sc->sc_event_thread = NULL;
459
460         crit_exit();
461
462         /* In case parent is waiting for us to exit. */
463         wakeup(sc);
464
465         DPRINTF(("usb_event_thread: exit\n"));
466         kthread_exit();
467 }
468
469 void
470 usb_task_thread(void *arg)
471 {
472         struct usb_task *task;
473         struct usb_taskq *taskq;
474
475         crit_enter();
476
477         taskq = arg;
478         DPRINTF(("usb_task_thread: start taskq %s\n", taskq->name));
479
480         while (usb_ndevs > 0) {
481                 task = TAILQ_FIRST(&taskq->tasks);
482                 if (task == NULL) {
483                         tsleep(&taskq->tasks, 0, "usbtsk", 0);
484                         task = TAILQ_FIRST(&taskq->tasks);
485                 }
486                 DPRINTFN(2,("usb_task_thread: woke up task=%p\n", task));
487                 if (task != NULL) {
488                         TAILQ_REMOVE(&taskq->tasks, task, next);
489                         task->queue = -1;
490                         crit_exit();
491                         task->fun(task->arg);
492                         crit_enter();
493                         wakeup((&taskq->tasks + 1));
494                 }
495         }
496
497         crit_exit();
498
499         taskq->taskcreated = 0;
500         wakeup(&taskq->taskcreated);
501
502         DPRINTF(("usb_event_thread: exit\n"));
503 }
504
505 int
506 usbopen(struct dev_open_args *ap)
507 {
508         cdev_t dev = ap->a_head.a_dev;
509         int unit = USBUNIT(dev);
510         struct usb_softc *sc;
511
512         if (unit == USB_DEV_MINOR) {
513                 if (usb_dev_open)
514                         return (EBUSY);
515                 usb_dev_open = 1;
516                 usb_async_proc = NULL;
517                 return (0);
518         }
519
520         sc = devclass_get_softc(usb_devclass, unit);
521         if (sc == NULL)
522                 return (ENXIO);
523
524         if (sc->sc_dying)
525                 return (EIO);
526
527         return (0);
528 }
529
530 int
531 usbread(struct dev_read_args *ap)
532 {
533         cdev_t dev = ap->a_head.a_dev;
534         struct uio *uio = ap->a_uio;
535         struct usb_event ue;
536         int unit = USBUNIT(dev);
537         int error, n;
538
539         if (unit != USB_DEV_MINOR)
540                 return (ENODEV);
541
542         if (uio->uio_resid != sizeof(struct usb_event))
543                 return (EINVAL);
544
545         error = 0;
546         crit_enter();
547         for (;;) {
548                 n = usb_get_next_event(&ue);
549                 if (n != 0)
550                         break;
551                 if (ap->a_ioflag & IO_NDELAY) {
552                         error = EWOULDBLOCK;
553                         break;
554                 }
555                 error = tsleep(&usb_events, PCATCH, "usbrea", 0);
556                 if (error)
557                         break;
558         }
559         crit_exit();
560         if (!error)
561                 error = uiomove((void *)&ue, uio->uio_resid, uio);
562
563         return (error);
564 }
565
566 int
567 usbclose(struct dev_close_args *ap)
568 {
569         cdev_t dev = ap->a_head.a_dev;
570         int unit = USBUNIT(dev);
571
572         if (unit == USB_DEV_MINOR) {
573                 usb_async_proc = NULL;
574                 usb_dev_open = 0;
575         }
576
577         return (0);
578 }
579
580 int
581 usbioctl(struct dev_ioctl_args *ap)
582 {
583         cdev_t devt = ap->a_head.a_dev;
584         struct usb_softc *sc;
585         int unit = USBUNIT(devt);
586
587         if (unit == USB_DEV_MINOR) {
588                 switch (ap->a_cmd) {
589                 case FIOASYNC:
590                         if (*(int *)ap->a_data)
591                                 usb_async_proc = curproc;
592                         else
593                                 usb_async_proc = NULL;
594                         return (0);
595
596                 default:
597                         return (EINVAL);
598                 }
599         }
600
601         sc = devclass_get_softc(usb_devclass, unit);
602
603         if (sc->sc_dying)
604                 return (EIO);
605
606         switch (ap->a_cmd) {
607         /* This part should be deleted */
608         case USB_DISCOVER:
609                 break;
610         case USB_REQUEST:
611         {
612                 struct usb_ctl_request *ur = (void *)ap->a_data;
613                 int len = UGETW(ur->ucr_request.wLength);
614                 struct iovec iov;
615                 struct uio uio;
616                 void *ptr = 0;
617                 int addr = ur->ucr_addr;
618                 usbd_status err;
619                 int error = 0;
620
621                 DPRINTF(("usbioctl: USB_REQUEST addr=%d len=%d\n", addr, len));
622                 if (len < 0 || len > 32768)
623                         return (EINVAL);
624                 if (addr < 0 || addr >= USB_MAX_DEVICES ||
625                     sc->sc_bus->devices[addr] == 0)
626                         return (EINVAL);
627                 if (len != 0) {
628                         iov.iov_base = (caddr_t)ur->ucr_data;
629                         iov.iov_len = len;
630                         uio.uio_iov = &iov;
631                         uio.uio_iovcnt = 1;
632                         uio.uio_resid = len;
633                         uio.uio_offset = 0;
634                         uio.uio_segflg = UIO_USERSPACE;
635                         uio.uio_rw =
636                                 ur->ucr_request.bmRequestType & UT_READ ?
637                                 UIO_READ : UIO_WRITE;
638                         uio.uio_td = curthread;
639                         ptr = kmalloc(len, M_TEMP, M_WAITOK);
640                         if (uio.uio_rw == UIO_WRITE) {
641                                 error = uiomove(ptr, len, &uio);
642                                 if (error)
643                                         goto ret;
644                         }
645                 }
646                 err = usbd_do_request_flags(sc->sc_bus->devices[addr],
647                           &ur->ucr_request, ptr, ur->ucr_flags, &ur->ucr_actlen,
648                           USBD_DEFAULT_TIMEOUT);
649                 if (err) {
650                         error = EIO;
651                         goto ret;
652                 }
653                 if (len != 0) {
654                         if (uio.uio_rw == UIO_READ) {
655                                 error = uiomove(ptr, len, &uio);
656                                 if (error)
657                                         goto ret;
658                         }
659                 }
660         ret:
661                 if (ptr)
662                         kfree(ptr, M_TEMP);
663                 return (error);
664         }
665
666         case USB_DEVICEINFO:
667         {
668                 struct usb_device_info *di = (void *)ap->a_data;
669                 int addr = di->udi_addr;
670                 usbd_device_handle dev;
671
672                 if (addr < 1 || addr >= USB_MAX_DEVICES)
673                         return (EINVAL);
674                 dev = sc->sc_bus->devices[addr];
675                 if (dev == NULL)
676                         return (ENXIO);
677                 usbd_fill_deviceinfo(dev, di, 1);
678                 break;
679         }
680
681         case USB_DEVICESTATS:
682                 *(struct usb_device_stats *)ap->a_data = sc->sc_bus->stats;
683                 break;
684
685         default:
686                 return (EINVAL);
687         }
688         return (0);
689 }
690
691 int
692 usbpoll(struct dev_poll_args *ap)
693 {
694         cdev_t dev = ap->a_head.a_dev;
695         int revents, mask;
696         int unit = USBUNIT(dev);
697
698         if (unit == USB_DEV_MINOR) {
699                 revents = 0;
700                 mask = POLLIN | POLLRDNORM;
701
702                 crit_enter();
703                 if (ap->a_events & mask && usb_nevents > 0)
704                         revents |= ap->a_events & mask;
705                 if (revents == 0 && ap->a_events & mask)
706                         selrecord(curthread, &usb_selevent);
707                 crit_exit();
708                 ap->a_events = revents;
709                 return (0);
710         } else {
711                 ap->a_events = 0;
712                 return (0);     /* select/poll never wakes up - back compat */
713         }
714 }
715
716 /* Explore device tree from the root. */
717 static void
718 usb_discover(void *v)
719 {
720         struct usb_softc *sc = v;
721
722         DPRINTFN(2,("usb_discover\n"));
723 #ifdef USB_DEBUG
724         if (usb_noexplore > 1)
725                 return;
726 #endif
727
728         /*
729          * We need mutual exclusion while traversing the device tree,
730          * but this is guaranteed since this function is only called
731          * from the event thread for the controller.
732          */
733         crit_enter();
734         while (sc->sc_bus->needs_explore && !sc->sc_dying) {
735                 sc->sc_bus->needs_explore = 0;
736
737                 crit_exit();
738                 sc->sc_bus->root_hub->hub->explore(sc->sc_bus->root_hub);
739                 crit_enter();
740
741         }
742         crit_exit();
743 }
744
745 void
746 usb_needs_explore(usbd_device_handle dev)
747 {
748         DPRINTFN(2,("usb_needs_explore\n"));
749         dev->bus->needs_explore = 1;
750         wakeup(&dev->bus->needs_explore);
751 }
752
753 /* Called from a critical section */
754 int
755 usb_get_next_event(struct usb_event *ue)
756 {
757         struct usb_event_q *ueq;
758
759         if (usb_nevents <= 0)
760                 return (0);
761         ueq = TAILQ_FIRST(&usb_events);
762 #ifdef DIAGNOSTIC
763         if (ueq == NULL) {
764                 kprintf("usb: usb_nevents got out of sync! %d\n", usb_nevents);
765                 usb_nevents = 0;
766                 return (0);
767         }
768 #endif
769         *ue = ueq->ue;
770         TAILQ_REMOVE(&usb_events, ueq, next);
771         kfree(ueq, M_USBDEV);
772         usb_nevents--;
773         return (1);
774 }
775
776 void
777 usbd_add_dev_event(int type, usbd_device_handle udev)
778 {
779         struct usb_event ue;
780
781         usbd_fill_deviceinfo(udev, &ue.u.ue_device, USB_EVENT_IS_ATTACH(type));
782         usb_add_event(type, &ue);
783 }
784
785 void
786 usbd_add_drv_event(int type, usbd_device_handle udev, device_t dev)
787 {
788         struct usb_event ue;
789
790         ue.u.ue_driver.ue_cookie = udev->cookie;
791         strncpy(ue.u.ue_driver.ue_devname, device_get_nameunit(dev),
792                 sizeof ue.u.ue_driver.ue_devname);
793         usb_add_event(type, &ue);
794 }
795
796 void
797 usb_add_event(int type, struct usb_event *uep)
798 {
799         struct usb_event_q *ueq;
800         struct usb_event ue;
801         struct timeval thetime;
802
803         ueq = kmalloc(sizeof *ueq, M_USBDEV, M_INTWAIT);
804         ueq->ue = *uep;
805         ueq->ue.ue_type = type;
806         microtime(&thetime);
807         TIMEVAL_TO_TIMESPEC(&thetime, &ueq->ue.ue_time);
808
809         crit_enter();
810         if (USB_EVENT_IS_DETACH(type)) {
811                 struct usb_event_q *ueqi, *ueqi_next;
812
813                 for (ueqi = TAILQ_FIRST(&usb_events); ueqi; ueqi = ueqi_next) {
814                         ueqi_next = TAILQ_NEXT(ueqi, next);
815                         if (ueqi->ue.u.ue_driver.ue_cookie.cookie ==
816                             uep->u.ue_device.udi_cookie.cookie) {
817                                 TAILQ_REMOVE(&usb_events, ueqi, next);
818                                 kfree(ueqi, M_USBDEV);
819                                 usb_nevents--;
820                                 ueqi_next = TAILQ_FIRST(&usb_events);
821                         }
822                 }
823         }
824         if (usb_nevents >= USB_MAX_EVENTS) {
825                 /* Too many queued events, drop an old one. */
826                 DPRINTF(("usb: event dropped\n"));
827                 usb_get_next_event(&ue);
828         }
829         TAILQ_INSERT_TAIL(&usb_events, ueq, next);
830         usb_nevents++;
831         wakeup(&usb_events);
832         selwakeuppri(&usb_selevent, 0);
833         if (usb_async_proc != NULL) {
834                 ksignal(usb_async_proc, SIGIO);
835         }
836         crit_exit();
837 }
838
839 void
840 usb_schedsoftintr(usbd_bus_handle bus)
841 {
842         DPRINTFN(10,("usb_schedsoftintr: polling=%d\n", bus->use_polling));
843 #ifdef USB_USE_SOFTINTR
844         if (bus->use_polling) {
845                 bus->methods->soft_intr(bus);
846         } else {
847 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
848                 softintr_schedule(bus->soft);
849 #else
850                 if (!callout_pending(&bus->softi))
851                         callout_reset(&bus->softi, 0, bus->methods->soft_intr,
852                             bus);
853 #endif /* __HAVE_GENERIC_SOFT_INTERRUPTS */
854         }
855 #else
856        bus->methods->soft_intr(bus);
857 #endif /* USB_USE_SOFTINTR */
858 }
859
860 static int
861 usb_detach(device_t self)
862 {
863         struct usb_softc *sc = device_get_softc(self);
864         struct usb_event ue;
865
866         DPRINTF(("usb_detach: start\n"));
867
868         sc->sc_dying = 1;
869
870         /* Make all devices disconnect. */
871         if (sc->sc_port.device != NULL)
872                 usb_disconnect_port(&sc->sc_port, self);
873
874         /* Kill off event thread. */
875         if (sc->sc_event_thread != NULL) {
876                 wakeup(&sc->sc_bus->needs_explore);
877                 if (tsleep(sc, 0, "usbdet", hz * 60))
878                         kprintf("%s: event thread didn't die\n",
879                                device_get_nameunit(sc->sc_dev));
880                 DPRINTF(("usb_detach: event thread dead\n"));
881         }
882
883         destroy_dev(sc->sc_usbdev);
884         if (--usb_ndevs == 0) {
885                 int i;
886
887                 destroy_dev(usb_dev);
888                 usb_dev = NULL;
889
890                 for (i = 0; i < USB_NUM_TASKQS; i++) {
891                         struct usb_taskq *taskq = &usb_taskq[i];
892                         wakeup(&taskq->tasks);
893                         if (tsleep(&taskq->taskcreated, 0, "usbtdt",
894                             hz * 60)) {
895                                 kprintf("usb task thread %s didn't die\n",
896                                     taskq->name);
897                         }
898                 }
899         }
900
901         usbd_finish();
902
903 #ifdef USB_USE_SOFTINTR
904 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
905         if (sc->sc_bus->soft != NULL) {
906                 softintr_disestablish(sc->sc_bus->soft);
907                 sc->sc_bus->soft = NULL;
908         }
909 #else
910         callout_stop(&sc->sc_bus->softi);
911 #endif
912 #endif
913
914         ue.u.ue_ctrlr.ue_bus = device_get_unit(sc->sc_dev);
915         usb_add_event(USB_EVENT_CTRLR_DETACH, &ue);
916
917         return (0);
918 }
919
920 static void
921 usb_child_detached(device_t self, device_t child)
922 {
923         struct usb_softc *sc = device_get_softc(self);
924
925         /* XXX, should check it is the right device. */
926         sc->sc_port.device = NULL;
927 }
928
929 DRIVER_MODULE(usb, ohci, usb_driver, usb_devclass, 0, 0);
930 DRIVER_MODULE(usb, uhci, usb_driver, usb_devclass, 0, 0);
931 DRIVER_MODULE(usb, ehci, usb_driver, usb_devclass, 0, 0);
932