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