Merge from vendor branch SENDMAIL:
[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.17 2006/06/13 08:11:56 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                 tsleep(&sc->sc_bus->needs_explore, 0, "usbevt",
419                        usb_noexplore ? 0 : hz * 60);
420 #else
421                 tsleep(&sc->sc_bus->needs_explore, 0, "usbevt", hz * 60);
422 #endif
423                 DPRINTFN(2,("usb_event_thread: woke up\n"));
424         }
425         sc->sc_event_thread = NULL;
426
427         /* In case parent is waiting for us to exit. */
428         wakeup(sc);
429
430         DPRINTF(("usb_event_thread: exit\n"));
431         kthread_exit();
432 }
433
434 void
435 usb_task_thread(void *arg)
436 {
437         struct usb_task *task;
438
439 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
440         mtx_lock(&Giant);
441 #endif
442
443         DPRINTF(("usb_task_thread: start\n"));
444
445         crit_enter();
446         for (;;) {
447                 task = TAILQ_FIRST(&usb_all_tasks);
448                 if (task == NULL) {
449                         tsleep(&usb_all_tasks, 0, "usbtsk", 0);
450                         task = TAILQ_FIRST(&usb_all_tasks);
451                 }
452                 DPRINTFN(2,("usb_task_thread: woke up task=%p\n", task));
453                 if (task != NULL) {
454                         TAILQ_REMOVE(&usb_all_tasks, task, next);
455                         task->onqueue = 0;
456                         crit_exit();
457                         task->fun(task->arg);
458                         crit_enter();
459                 }
460         }
461 }
462
463 #if defined(__NetBSD__) || defined(__OpenBSD__)
464 int
465 usbctlprint(void *aux, const char *pnp)
466 {
467         /* only "usb"es can attach to host controllers */
468         if (pnp)
469                 printf("usb at %s", pnp);
470
471         return (UNCONF);
472 }
473 #endif /* defined(__NetBSD__) || defined(__OpenBSD__) */
474
475 int
476 usbopen(dev_t dev, int flag, int mode, usb_proc_ptr p)
477 {
478         int unit = USBUNIT(dev);
479         struct usb_softc *sc;
480
481         if (unit == USB_DEV_MINOR) {
482                 if (usb_dev_open)
483                         return (EBUSY);
484                 usb_dev_open = 1;
485                 usb_async_proc = NULL;
486                 return (0);
487         }
488
489         USB_GET_SC_OPEN(usb, unit, sc);
490
491         if (sc->sc_dying)
492                 return (EIO);
493
494         return (0);
495 }
496
497 int
498 usbread(dev_t dev, struct uio *uio, int flag)
499 {
500         struct usb_event ue;
501         int unit = USBUNIT(dev);
502         int error, n;
503
504         if (unit != USB_DEV_MINOR)
505                 return (ENODEV);
506
507         if (uio->uio_resid != sizeof(struct usb_event))
508                 return (EINVAL);
509
510         error = 0;
511         crit_enter();
512         for (;;) {
513                 n = usb_get_next_event(&ue);
514                 if (n != 0)
515                         break;
516                 if (flag & IO_NDELAY) {
517                         error = EWOULDBLOCK;
518                         break;
519                 }
520                 error = tsleep(&usb_events, PCATCH, "usbrea", 0);
521                 if (error)
522                         break;
523         }
524         crit_exit();
525         if (!error)
526                 error = uiomove((void *)&ue, uio->uio_resid, uio);
527
528         return (error);
529 }
530
531 int
532 usbclose(dev_t dev, int flag, int mode, usb_proc_ptr p)
533 {
534         int unit = USBUNIT(dev);
535
536         if (unit == USB_DEV_MINOR) {
537                 usb_async_proc = NULL;
538                 usb_dev_open = 0;
539         }
540
541         return (0);
542 }
543
544 int
545 usbioctl(dev_t devt, u_long cmd, caddr_t data, int flag, usb_proc_ptr p)
546 {
547         struct usb_softc *sc;
548         int unit = USBUNIT(devt);
549
550         if (unit == USB_DEV_MINOR) {
551                 switch (cmd) {
552                 case FIOASYNC:
553                         if (*(int *)data)
554 #if defined(__DragonFly__)
555                                 usb_async_proc = p->td_proc;
556 #elif __FreeBSD_version >= 500000
557                                 usb_async_proc = p->td_proc;
558 #else
559                                 usb_async_proc = p;
560 #endif
561                         else
562                                 usb_async_proc = NULL;
563                         return (0);
564
565                 default:
566                         return (EINVAL);
567                 }
568         }
569
570         USB_GET_SC(usb, unit, sc);
571
572         if (sc->sc_dying)
573                 return (EIO);
574
575         switch (cmd) {
576 #if defined(__FreeBSD__) || defined(__DragonFly__)
577         /* This part should be deleted */
578         case USB_DISCOVER:
579                 break;
580 #endif
581         case USB_REQUEST:
582         {
583                 struct usb_ctl_request *ur = (void *)data;
584                 int len = UGETW(ur->ucr_request.wLength);
585                 struct iovec iov;
586                 struct uio uio;
587                 void *ptr = 0;
588                 int addr = ur->ucr_addr;
589                 usbd_status err;
590                 int error = 0;
591
592                 DPRINTF(("usbioctl: USB_REQUEST addr=%d len=%d\n", addr, len));
593                 if (len < 0 || len > 32768)
594                         return (EINVAL);
595                 if (addr < 0 || addr >= USB_MAX_DEVICES ||
596                     sc->sc_bus->devices[addr] == 0)
597                         return (EINVAL);
598                 if (len != 0) {
599                         iov.iov_base = (caddr_t)ur->ucr_data;
600                         iov.iov_len = len;
601                         uio.uio_iov = &iov;
602                         uio.uio_iovcnt = 1;
603                         uio.uio_resid = len;
604                         uio.uio_offset = 0;
605                         uio.uio_segflg = UIO_USERSPACE;
606                         uio.uio_rw =
607                                 ur->ucr_request.bmRequestType & UT_READ ?
608                                 UIO_READ : UIO_WRITE;
609                         uio.uio_td = p;
610                         ptr = malloc(len, M_TEMP, M_WAITOK);
611                         if (uio.uio_rw == UIO_WRITE) {
612                                 error = uiomove(ptr, len, &uio);
613                                 if (error)
614                                         goto ret;
615                         }
616                 }
617                 err = usbd_do_request_flags(sc->sc_bus->devices[addr],
618                           &ur->ucr_request, ptr, ur->ucr_flags, &ur->ucr_actlen,
619                           USBD_DEFAULT_TIMEOUT);
620                 if (err) {
621                         error = EIO;
622                         goto ret;
623                 }
624                 if (len != 0) {
625                         if (uio.uio_rw == UIO_READ) {
626                                 error = uiomove(ptr, len, &uio);
627                                 if (error)
628                                         goto ret;
629                         }
630                 }
631         ret:
632                 if (ptr)
633                         free(ptr, M_TEMP);
634                 return (error);
635         }
636
637         case USB_DEVICEINFO:
638         {
639                 struct usb_device_info *di = (void *)data;
640                 int addr = di->udi_addr;
641                 usbd_device_handle dev;
642
643                 if (addr < 1 || addr >= USB_MAX_DEVICES)
644                         return (EINVAL);
645                 dev = sc->sc_bus->devices[addr];
646                 if (dev == NULL)
647                         return (ENXIO);
648                 usbd_fill_deviceinfo(dev, di, 1);
649                 break;
650         }
651
652         case USB_DEVICESTATS:
653                 *(struct usb_device_stats *)data = sc->sc_bus->stats;
654                 break;
655
656         default:
657                 return (EINVAL);
658         }
659         return (0);
660 }
661
662 int
663 usbpoll(dev_t dev, int events, usb_proc_ptr p)
664 {
665         int revents, mask;
666         int unit = USBUNIT(dev);
667
668         if (unit == USB_DEV_MINOR) {
669                 revents = 0;
670                 mask = POLLIN | POLLRDNORM;
671
672                 crit_enter();
673                 if (events & mask && usb_nevents > 0)
674                         revents |= events & mask;
675                 if (revents == 0 && events & mask)
676                         selrecord(p, &usb_selevent);
677                 crit_exit();
678
679                 return (revents);
680         } else {
681 #if defined(__FreeBSD__) || defined(__DragonFly__)
682                 return (0);     /* select/poll never wakes up - back compat */
683 #else
684                 return (ENXIO);
685 #endif
686         }
687 }
688
689 /* Explore device tree from the root. */
690 Static void
691 usb_discover(void *v)
692 {
693         struct usb_softc *sc = v;
694
695         DPRINTFN(2,("usb_discover\n"));
696 #ifdef USB_DEBUG
697         if (usb_noexplore > 1)
698                 return;
699 #endif
700
701         /*
702          * We need mutual exclusion while traversing the device tree,
703          * but this is guaranteed since this function is only called
704          * from the event thread for the controller.
705          */
706 #if defined(__FreeBSD__) || defined(__DragonFly__)
707         crit_enter();
708 #endif
709         while (sc->sc_bus->needs_explore && !sc->sc_dying) {
710                 sc->sc_bus->needs_explore = 0;
711 #if defined(__FreeBSD__) || defined(__DragonFly__)
712                 crit_exit();
713 #endif
714                 sc->sc_bus->root_hub->hub->explore(sc->sc_bus->root_hub);
715 #if defined(__FreeBSD__) || defined(__DragonFly__)
716                 crit_enter();
717 #endif
718         }
719 #if defined(__FreeBSD__) || defined(__DragonFly__)
720         crit_exit();
721 #endif
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                 printf("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         free(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_ptr_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, USBDEVPTRNAME(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 = malloc(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                                 free(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                 PROC_LOCK(usb_async_proc);
814                 psignal(usb_async_proc, SIGIO);
815                 PROC_UNLOCK(usb_async_proc);
816         }
817         crit_exit();
818 }
819
820 void
821 usb_schedsoftintr(usbd_bus_handle bus)
822 {
823         DPRINTFN(10,("usb_schedsoftintr: polling=%d\n", bus->use_polling));
824 #ifdef USB_USE_SOFTINTR
825         if (bus->use_polling) {
826                 bus->methods->soft_intr(bus);
827         } else {
828 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
829                 softintr_schedule(bus->soft);
830 #else
831                 if (!callout_pending(&bus->softi))
832                         callout_reset(&bus->softi, 0, bus->methods->soft_intr,
833                             bus);
834 #endif /* __HAVE_GENERIC_SOFT_INTERRUPTS */
835         }
836 #else
837         bus->methods->soft_intr(bus);
838 #endif /* USB_USE_SOFTINTR */
839 }
840
841
842 #if defined(__NetBSD__) || defined(__OpenBSD__)
843 int
844 usb_activate(device_ptr_t self, enum devact act)
845 {
846         struct usb_softc *sc = (struct usb_softc *)self;
847         usbd_device_handle dev = sc->sc_port.device;
848         int i, rv = 0;
849
850         switch (act) {
851         case DVACT_ACTIVATE:
852                 return (EOPNOTSUPP);
853
854         case DVACT_DEACTIVATE:
855                 sc->sc_dying = 1;
856                 if (dev != NULL && dev->cdesc != NULL && dev->subdevs != NULL) {
857                         for (i = 0; dev->subdevs[i]; i++)
858                                 rv |= config_deactivate(dev->subdevs[i]);
859                 }
860                 break;
861         }
862         return (rv);
863 }
864
865 int
866 usb_detach(device_ptr_t self, int flags)
867 {
868         struct usb_softc *sc = (struct usb_softc *)self;
869         struct usb_event ue;
870
871         DPRINTF(("usb_detach: start\n"));
872
873         sc->sc_dying = 1;
874
875         /* Make all devices disconnect. */
876         if (sc->sc_port.device != NULL)
877                 usb_disconnect_port(&sc->sc_port, self);
878
879         /* Kill off event thread. */
880         if (sc->sc_event_thread != NULL) {
881                 wakeup(&sc->sc_bus->needs_explore);
882                 if (tsleep(sc, 0, "usbdet", hz * 60))
883                         printf("%s: event thread didn't die\n",
884                                USBDEVNAME(sc->sc_dev));
885                 DPRINTF(("usb_detach: event thread dead\n"));
886         }
887
888         usbd_finish();
889
890 #ifdef USB_USE_SOFTINTR
891 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
892         if (sc->sc_bus->soft != NULL) {
893                 softintr_disestablish(sc->sc_bus->soft);
894                 sc->sc_bus->soft = NULL;
895         }
896 #else
897         callout_stop(&sc->sc_bus->softi);
898 #endif
899 #endif
900
901         ue.u.ue_ctrlr.ue_bus = USBDEVUNIT(sc->sc_dev);
902         usb_add_event(USB_EVENT_CTRLR_DETACH, &ue);
903
904         return (0);
905 }
906 #elif defined(__FreeBSD__) || defined(__DragonFly__)
907 int
908 usb_detach(device_t self)
909 {
910         DPRINTF(("%s: unload, prevented\n", USBDEVNAME(self)));
911
912         return (EINVAL);
913 }
914 #endif
915
916
917 #if defined(__FreeBSD__) || defined(__DragonFly__)
918 DRIVER_MODULE(usb, ohci, usb_driver, usb_devclass, 0, 0);
919 DRIVER_MODULE(usb, uhci, usb_driver, usb_devclass, 0, 0);
920 DRIVER_MODULE(usb, ehci, usb_driver, usb_devclass, 0, 0);
921 #endif