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