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