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