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