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