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