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