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