usb.c revision 1.168.2.9 1 /* $NetBSD: usb.c,v 1.168.2.9 2019/01/14 13:34:27 pgoyette Exp $ */
2
3 /*
4 * Copyright (c) 1998, 2002, 2008, 2012 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Lennart Augustsson (lennart (at) augustsson.net) at
9 * Carlstedt Research & Technology and Matthew R. Green (mrg (at) eterna.com.au).
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
31 */
32
33 /*
34 * USB specifications and other documentation can be found at
35 * http://www.usb.org/developers/docs/ and
36 * http://www.usb.org/developers/devclass_docs/
37 */
38
39 #include <sys/cdefs.h>
40 __KERNEL_RCSID(0, "$NetBSD: usb.c,v 1.168.2.9 2019/01/14 13:34:27 pgoyette Exp $");
41
42 #ifdef _KERNEL_OPT
43 #include "opt_usb.h"
44 #include "opt_compat_netbsd.h"
45 #endif
46
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/kernel.h>
50 #include <sys/kmem.h>
51 #include <sys/device.h>
52 #include <sys/kthread.h>
53 #include <sys/proc.h>
54 #include <sys/conf.h>
55 #include <sys/fcntl.h>
56 #include <sys/poll.h>
57 #include <sys/select.h>
58 #include <sys/vnode.h>
59 #include <sys/signalvar.h>
60 #include <sys/intr.h>
61 #include <sys/module.h>
62 #include <sys/mutex.h>
63 #include <sys/bus.h>
64 #include <sys/once.h>
65 #include <sys/atomic.h>
66 #include <sys/sysctl.h>
67 #include <sys/compat_stub.h>
68
69 #include <dev/usb/usb.h>
70 #include <dev/usb/usbdi.h>
71 #include <dev/usb/usbdi_util.h>
72 #include <dev/usb/usbdivar.h>
73 #include <dev/usb/usb_verbose.h>
74 #include <dev/usb/usb_quirks.h>
75 #include <dev/usb/usbhist.h>
76
77 #if defined(USB_DEBUG)
78
79 #ifndef USBHIST_SIZE
80 #define USBHIST_SIZE 50000
81 #endif
82
83 static struct kern_history_ent usbhistbuf[USBHIST_SIZE];
84 USBHIST_DEFINE(usbhist) = KERNHIST_INITIALIZER(usbhist, usbhistbuf);
85
86 #endif
87
88 #define USB_DEV_MINOR 255
89
90 #ifdef USB_DEBUG
91 /*
92 * 0 - do usual exploration
93 * 1 - do not use timeout exploration
94 * >1 - do no exploration
95 */
96 int usb_noexplore = 0;
97
98 int usbdebug = 0;
99 SYSCTL_SETUP(sysctl_hw_usb_setup, "sysctl hw.usb setup")
100 {
101 int err;
102 const struct sysctlnode *rnode;
103 const struct sysctlnode *cnode;
104
105 err = sysctl_createv(clog, 0, NULL, &rnode,
106 CTLFLAG_PERMANENT, CTLTYPE_NODE, "usb",
107 SYSCTL_DESCR("usb global controls"),
108 NULL, 0, NULL, 0, CTL_HW, CTL_CREATE, CTL_EOL);
109
110 if (err)
111 goto fail;
112
113 /* control debugging printfs */
114 err = sysctl_createv(clog, 0, &rnode, &cnode,
115 CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
116 "debug", SYSCTL_DESCR("Enable debugging output"),
117 NULL, 0, &usbdebug, sizeof(usbdebug), CTL_CREATE, CTL_EOL);
118 if (err)
119 goto fail;
120
121 return;
122 fail:
123 aprint_error("%s: sysctl_createv failed (err = %d)\n", __func__, err);
124 }
125 #else
126 #define usb_noexplore 0
127 #endif
128
129 #define DPRINTF(FMT,A,B,C,D) USBHIST_LOG(usbdebug,FMT,A,B,C,D)
130 #define DPRINTFN(N,FMT,A,B,C,D) USBHIST_LOGN(usbdebug,N,FMT,A,B,C,D)
131
132 struct usb_softc {
133 #if 0
134 device_t sc_dev; /* base device */
135 #endif
136 struct usbd_bus *sc_bus; /* USB controller */
137 struct usbd_port sc_port; /* dummy port for root hub */
138
139 struct lwp *sc_event_thread;
140
141 char sc_dying;
142 bool sc_pmf_registered;
143 };
144
145 struct usb_taskq {
146 TAILQ_HEAD(, usb_task) tasks;
147 kmutex_t lock;
148 kcondvar_t cv;
149 struct lwp *task_thread_lwp;
150 const char *name;
151 struct usb_task *current_task;
152 };
153
154 static struct usb_taskq usb_taskq[USB_NUM_TASKQS];
155
156 dev_type_open(usbopen);
157 dev_type_close(usbclose);
158 dev_type_read(usbread);
159 dev_type_ioctl(usbioctl);
160 dev_type_poll(usbpoll);
161 dev_type_kqfilter(usbkqfilter);
162
163 const struct cdevsw usb_cdevsw = {
164 .d_open = usbopen,
165 .d_close = usbclose,
166 .d_read = usbread,
167 .d_write = nowrite,
168 .d_ioctl = usbioctl,
169 .d_stop = nostop,
170 .d_tty = notty,
171 .d_poll = usbpoll,
172 .d_mmap = nommap,
173 .d_kqfilter = usbkqfilter,
174 .d_discard = nodiscard,
175 .d_flag = D_OTHER
176 };
177
178 Static void usb_discover(struct usb_softc *);
179 Static void usb_create_event_thread(device_t);
180 Static void usb_event_thread(void *);
181 Static void usb_task_thread(void *);
182
183 #define USB_MAX_EVENTS 100
184 struct usb_event_q {
185 struct usb_event ue;
186 SIMPLEQ_ENTRY(usb_event_q) next;
187 };
188 Static SIMPLEQ_HEAD(, usb_event_q) usb_events =
189 SIMPLEQ_HEAD_INITIALIZER(usb_events);
190 Static int usb_nevents = 0;
191 Static struct selinfo usb_selevent;
192 Static kmutex_t usb_event_lock;
193 Static kcondvar_t usb_event_cv;
194 /* XXX this is gross and broken */
195 Static proc_t *usb_async_proc; /* process that wants USB SIGIO */
196 Static void *usb_async_sih;
197 Static int usb_dev_open = 0;
198 Static struct usb_event *usb_alloc_event(void);
199 Static void usb_free_event(struct usb_event *);
200 Static void usb_add_event(int, struct usb_event *);
201 Static int usb_get_next_event(struct usb_event *);
202 Static void usb_async_intr(void *);
203 Static void usb_soft_intr(void *);
204
205 Static const char *usbrev_str[] = USBREV_STR;
206
207 static int usb_match(device_t, cfdata_t, void *);
208 static void usb_attach(device_t, device_t, void *);
209 static int usb_detach(device_t, int);
210 static int usb_activate(device_t, enum devact);
211 static void usb_childdet(device_t, device_t);
212 static int usb_once_init(void);
213 static void usb_doattach(device_t);
214
215 extern struct cfdriver usb_cd;
216
217 CFATTACH_DECL3_NEW(usb, sizeof(struct usb_softc),
218 usb_match, usb_attach, usb_detach, usb_activate, NULL, usb_childdet,
219 DVF_DETACH_SHUTDOWN);
220
221 static const char *taskq_names[] = USB_TASKQ_NAMES;
222
223 int
224 usb_match(device_t parent, cfdata_t match, void *aux)
225 {
226 USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
227
228 return UMATCH_GENERIC;
229 }
230
231 void
232 usb_attach(device_t parent, device_t self, void *aux)
233 {
234 static ONCE_DECL(init_control);
235 struct usb_softc *sc = device_private(self);
236 int usbrev;
237
238 sc->sc_bus = aux;
239 usbrev = sc->sc_bus->ub_revision;
240
241 cv_init(&sc->sc_bus->ub_needsexplore_cv, "usbevt");
242 sc->sc_pmf_registered = false;
243
244 aprint_naive("\n");
245 aprint_normal(": USB revision %s", usbrev_str[usbrev]);
246 switch (usbrev) {
247 case USBREV_1_0:
248 case USBREV_1_1:
249 case USBREV_2_0:
250 case USBREV_3_0:
251 case USBREV_3_1:
252 break;
253 default:
254 aprint_error(", not supported\n");
255 sc->sc_dying = 1;
256 return;
257 }
258 aprint_normal("\n");
259
260 /* XXX we should have our own level */
261 sc->sc_bus->ub_soft = softint_establish(SOFTINT_USB | SOFTINT_MPSAFE,
262 usb_soft_intr, sc->sc_bus);
263 if (sc->sc_bus->ub_soft == NULL) {
264 aprint_error("%s: can't register softintr\n",
265 device_xname(self));
266 sc->sc_dying = 1;
267 return;
268 }
269
270 sc->sc_bus->ub_methods->ubm_getlock(sc->sc_bus, &sc->sc_bus->ub_lock);
271 KASSERT(sc->sc_bus->ub_lock != NULL);
272
273 RUN_ONCE(&init_control, usb_once_init);
274 config_interrupts(self, usb_doattach);
275 }
276
277 static int
278 usb_once_init(void)
279 {
280 struct usb_taskq *taskq;
281 int i;
282
283 USBHIST_LINK_STATIC(usbhist);
284
285 selinit(&usb_selevent);
286 mutex_init(&usb_event_lock, MUTEX_DEFAULT, IPL_NONE);
287 cv_init(&usb_event_cv, "usbrea");
288
289 for (i = 0; i < USB_NUM_TASKQS; i++) {
290 taskq = &usb_taskq[i];
291
292 TAILQ_INIT(&taskq->tasks);
293 /*
294 * Since USB task methods usb_{add,rem}_task are callable
295 * from any context, we have to make this lock a spinlock.
296 */
297 mutex_init(&taskq->lock, MUTEX_DEFAULT, IPL_USB);
298 cv_init(&taskq->cv, "usbtsk");
299 taskq->name = taskq_names[i];
300 taskq->current_task = NULL;
301 if (kthread_create(PRI_NONE, KTHREAD_MPSAFE, NULL,
302 usb_task_thread, taskq, &taskq->task_thread_lwp,
303 "%s", taskq->name)) {
304 printf("unable to create task thread: %s\n", taskq->name);
305 panic("usb_create_event_thread task");
306 }
307 /*
308 * XXX we should make sure these threads are alive before
309 * end up using them in usb_doattach().
310 */
311 }
312
313 KASSERT(usb_async_sih == NULL);
314 usb_async_sih = softint_establish(SOFTINT_CLOCK | SOFTINT_MPSAFE,
315 usb_async_intr, NULL);
316
317 return 0;
318 }
319
320 static void
321 usb_doattach(device_t self)
322 {
323 struct usb_softc *sc = device_private(self);
324 struct usbd_device *dev;
325 usbd_status err;
326 int speed;
327 struct usb_event *ue;
328
329 USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
330
331 sc->sc_bus->ub_usbctl = self;
332 sc->sc_port.up_power = USB_MAX_POWER;
333
334 switch (sc->sc_bus->ub_revision) {
335 case USBREV_1_0:
336 case USBREV_1_1:
337 speed = USB_SPEED_FULL;
338 break;
339 case USBREV_2_0:
340 speed = USB_SPEED_HIGH;
341 break;
342 case USBREV_3_0:
343 speed = USB_SPEED_SUPER;
344 break;
345 case USBREV_3_1:
346 speed = USB_SPEED_SUPER_PLUS;
347 break;
348 default:
349 panic("usb_doattach");
350 }
351
352 ue = usb_alloc_event();
353 ue->u.ue_ctrlr.ue_bus = device_unit(self);
354 usb_add_event(USB_EVENT_CTRLR_ATTACH, ue);
355
356 err = usbd_new_device(self, sc->sc_bus, 0, speed, 0,
357 &sc->sc_port);
358 if (!err) {
359 dev = sc->sc_port.up_dev;
360 if (dev->ud_hub == NULL) {
361 sc->sc_dying = 1;
362 aprint_error("%s: root device is not a hub\n",
363 device_xname(self));
364 return;
365 }
366 sc->sc_bus->ub_roothub = dev;
367 usb_create_event_thread(self);
368 } else {
369 aprint_error("%s: root hub problem, error=%s\n",
370 device_xname(self), usbd_errstr(err));
371 sc->sc_dying = 1;
372 }
373
374 /*
375 * Drop this reference after the first set of attachments in the
376 * event thread.
377 */
378 config_pending_incr(self);
379
380 if (!pmf_device_register(self, NULL, NULL))
381 aprint_error_dev(self, "couldn't establish power handler\n");
382 else
383 sc->sc_pmf_registered = true;
384
385 return;
386 }
387
388 void
389 usb_create_event_thread(device_t self)
390 {
391 struct usb_softc *sc = device_private(self);
392
393 if (kthread_create(PRI_NONE, KTHREAD_MPSAFE, NULL,
394 usb_event_thread, sc, &sc->sc_event_thread,
395 "%s", device_xname(self))) {
396 printf("%s: unable to create event thread for\n",
397 device_xname(self));
398 panic("usb_create_event_thread");
399 }
400 }
401
402 /*
403 * Add a task to be performed by the task thread. This function can be
404 * called from any context and the task will be executed in a process
405 * context ASAP.
406 */
407 void
408 usb_add_task(struct usbd_device *dev, struct usb_task *task, int queue)
409 {
410 struct usb_taskq *taskq;
411
412 USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
413
414 KASSERT(0 <= queue);
415 KASSERT(queue < USB_NUM_TASKQS);
416 taskq = &usb_taskq[queue];
417 mutex_enter(&taskq->lock);
418 if (atomic_cas_uint(&task->queue, USB_NUM_TASKQS, queue) ==
419 USB_NUM_TASKQS) {
420 DPRINTFN(2, "task=%#jx", (uintptr_t)task, 0, 0, 0);
421 TAILQ_INSERT_TAIL(&taskq->tasks, task, next);
422 cv_signal(&taskq->cv);
423 } else {
424 DPRINTFN(2, "task=%#jx on q", (uintptr_t)task, 0, 0, 0);
425 }
426 mutex_exit(&taskq->lock);
427 }
428
429 /*
430 * usb_rem_task(dev, task)
431 *
432 * If task is queued to run, remove it from the queue.
433 *
434 * Caller is _not_ guaranteed that the task is not running when
435 * this is done.
436 *
437 * Never sleeps.
438 */
439 void
440 usb_rem_task(struct usbd_device *dev, struct usb_task *task)
441 {
442 unsigned queue;
443
444 USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
445
446 while ((queue = task->queue) != USB_NUM_TASKQS) {
447 struct usb_taskq *taskq = &usb_taskq[queue];
448 mutex_enter(&taskq->lock);
449 if (__predict_true(task->queue == queue)) {
450 TAILQ_REMOVE(&taskq->tasks, task, next);
451 task->queue = USB_NUM_TASKQS;
452 mutex_exit(&taskq->lock);
453 break;
454 }
455 mutex_exit(&taskq->lock);
456 }
457 }
458
459 /*
460 * usb_rem_task_wait(dev, task, queue, interlock)
461 *
462 * If task is scheduled to run, remove it from the queue. If it
463 * may have already begun to run, drop interlock if not null, wait
464 * for it to complete, and reacquire interlock if not null.
465 * Return true if it successfully removed the task from the queue,
466 * false if not.
467 *
468 * Caller MUST guarantee that task will not be scheduled on a
469 * _different_ queue, at least until after this returns.
470 *
471 * If caller guarantees that task will not be scheduled on the
472 * same queue before this returns, then caller is guaranteed that
473 * the task is not running at all when this returns.
474 *
475 * May sleep.
476 */
477 bool
478 usb_rem_task_wait(struct usbd_device *dev, struct usb_task *task, int queue,
479 kmutex_t *interlock)
480 {
481 struct usb_taskq *taskq;
482 int queue1;
483 bool removed;
484
485 USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
486 ASSERT_SLEEPABLE();
487 KASSERT(0 <= queue);
488 KASSERT(queue < USB_NUM_TASKQS);
489
490 taskq = &usb_taskq[queue];
491 mutex_enter(&taskq->lock);
492 queue1 = task->queue;
493 if (queue1 == USB_NUM_TASKQS) {
494 /*
495 * It is not on the queue. It may be about to run, or
496 * it may have already finished running -- there is no
497 * stopping it now. Wait for it if it is running.
498 */
499 if (interlock)
500 mutex_exit(interlock);
501 while (taskq->current_task == task)
502 cv_wait(&taskq->cv, &taskq->lock);
503 removed = false;
504 } else {
505 /*
506 * It is still on the queue. We can stop it before the
507 * task thread will run it.
508 */
509 KASSERTMSG(queue1 == queue, "task %p on q%d expected on q%d",
510 task, queue1, queue);
511 TAILQ_REMOVE(&taskq->tasks, task, next);
512 task->queue = USB_NUM_TASKQS;
513 removed = true;
514 }
515 mutex_exit(&taskq->lock);
516
517 /*
518 * If there's an interlock, and we dropped it to wait,
519 * reacquire it.
520 */
521 if (interlock && !removed)
522 mutex_enter(interlock);
523
524 return removed;
525 }
526
527 void
528 usb_event_thread(void *arg)
529 {
530 struct usb_softc *sc = arg;
531 struct usbd_bus *bus = sc->sc_bus;
532
533 USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
534
535 /*
536 * In case this controller is a companion controller to an
537 * EHCI controller we need to wait until the EHCI controller
538 * has grabbed the port.
539 * XXX It would be nicer to do this with a tsleep(), but I don't
540 * know how to synchronize the creation of the threads so it
541 * will work.
542 */
543 usb_delay_ms(bus, 500);
544
545 /* Make sure first discover does something. */
546 mutex_enter(bus->ub_lock);
547 sc->sc_bus->ub_needsexplore = 1;
548 usb_discover(sc);
549 mutex_exit(bus->ub_lock);
550
551 /* Drop the config_pending reference from attach. */
552 config_pending_decr(bus->ub_usbctl);
553
554 mutex_enter(bus->ub_lock);
555 while (!sc->sc_dying) {
556 #if 0 /* not yet */
557 while (sc->sc_bus->ub_usepolling)
558 kpause("usbpoll", true, hz, bus->ub_lock);
559 #endif
560
561 if (usb_noexplore < 2)
562 usb_discover(sc);
563
564 cv_timedwait(&bus->ub_needsexplore_cv,
565 bus->ub_lock, usb_noexplore ? 0 : hz * 60);
566
567 DPRINTFN(2, "sc %#jx woke up", (uintptr_t)sc, 0, 0, 0);
568 }
569 sc->sc_event_thread = NULL;
570
571 /* In case parent is waiting for us to exit. */
572 cv_signal(&bus->ub_needsexplore_cv);
573 mutex_exit(bus->ub_lock);
574
575 DPRINTF("sc %#jx exit", (uintptr_t)sc, 0, 0, 0);
576 kthread_exit(0);
577 }
578
579 void
580 usb_task_thread(void *arg)
581 {
582 struct usb_task *task;
583 struct usb_taskq *taskq;
584 bool mpsafe;
585
586 USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
587
588 taskq = arg;
589 DPRINTF("start taskq %#jx", (uintptr_t)taskq, 0, 0, 0);
590
591 mutex_enter(&taskq->lock);
592 for (;;) {
593 task = TAILQ_FIRST(&taskq->tasks);
594 if (task == NULL) {
595 cv_wait(&taskq->cv, &taskq->lock);
596 task = TAILQ_FIRST(&taskq->tasks);
597 }
598 DPRINTFN(2, "woke up task=%#jx", (uintptr_t)task, 0, 0, 0);
599 if (task != NULL) {
600 mpsafe = ISSET(task->flags, USB_TASKQ_MPSAFE);
601 TAILQ_REMOVE(&taskq->tasks, task, next);
602 task->queue = USB_NUM_TASKQS;
603 taskq->current_task = task;
604 mutex_exit(&taskq->lock);
605
606 if (!mpsafe)
607 KERNEL_LOCK(1, curlwp);
608 task->fun(task->arg);
609 /* Can't dereference task after this point. */
610 if (!mpsafe)
611 KERNEL_UNLOCK_ONE(curlwp);
612
613 mutex_enter(&taskq->lock);
614 KASSERTMSG(taskq->current_task == task,
615 "somebody scribbled on usb taskq %p", taskq);
616 taskq->current_task = NULL;
617 cv_broadcast(&taskq->cv);
618 }
619 }
620 mutex_exit(&taskq->lock);
621 }
622
623 int
624 usbctlprint(void *aux, const char *pnp)
625 {
626 /* only "usb"es can attach to host controllers */
627 if (pnp)
628 aprint_normal("usb at %s", pnp);
629
630 return UNCONF;
631 }
632
633 int
634 usbopen(dev_t dev, int flag, int mode, struct lwp *l)
635 {
636 int unit = minor(dev);
637 struct usb_softc *sc;
638
639 if (unit == USB_DEV_MINOR) {
640 if (usb_dev_open)
641 return EBUSY;
642 usb_dev_open = 1;
643 mutex_enter(proc_lock);
644 usb_async_proc = 0;
645 mutex_exit(proc_lock);
646 return 0;
647 }
648
649 sc = device_lookup_private(&usb_cd, unit);
650 if (!sc)
651 return ENXIO;
652
653 if (sc->sc_dying)
654 return EIO;
655
656 return 0;
657 }
658
659 /* Call the hook for usb30_copy_to_old() */
660 MODULE_CALL_INT_HOOK_DECL(usb_subr_30_copy_hook,
661 (struct usb_event *ue, struct usb_event_old *ueo, struct uio *uio));
662 MODULE_CALL_INT_HOOK(usb_subr_30_copy_hook,
663 (struct usb_event *ue, struct usb_event_old *ueo, struct uio *uio),
664 (ue, ueo, uio), enosys());
665
666 int
667 usbread(dev_t dev, struct uio *uio, int flag)
668 {
669 struct usb_event *ue;
670 struct usb_event_old *ueo = NULL; /* XXXGCC */
671 int useold = 0;
672 int error, n;
673
674 if (minor(dev) != USB_DEV_MINOR)
675 return ENXIO;
676
677 switch (uio->uio_resid) {
678 case sizeof(struct usb_event_old):
679 ueo = kmem_zalloc(sizeof(struct usb_event_old), KM_SLEEP);
680 useold = 1;
681 /* FALLTHRU */
682 case sizeof(struct usb_event):
683 ue = usb_alloc_event();
684 break;
685 default:
686 return EINVAL;
687 }
688
689 error = 0;
690 mutex_enter(&usb_event_lock);
691 for (;;) {
692 n = usb_get_next_event(ue);
693 if (n != 0)
694 break;
695 if (flag & IO_NDELAY) {
696 error = EWOULDBLOCK;
697 break;
698 }
699 error = cv_wait_sig(&usb_event_cv, &usb_event_lock);
700 if (error)
701 break;
702 }
703 mutex_exit(&usb_event_lock);
704 if (!error) {
705 if (useold) { /* copy fields to old struct */
706 error = usb_subr_30_copy_hook_call(ue, ueo, uio);
707 if (error == ENOSYS)
708 error = EINVAL;
709
710 if (!error)
711 error = uiomove((void *)ueo, sizeof(*ueo), uio);
712 } else
713 error = uiomove((void *)ue, sizeof(*ue), uio);
714 }
715 usb_free_event(ue);
716 if (ueo)
717 kmem_free(ueo, sizeof(struct usb_event_old));
718
719 return error;
720 }
721
722 int
723 usbclose(dev_t dev, int flag, int mode,
724 struct lwp *l)
725 {
726 int unit = minor(dev);
727
728 if (unit == USB_DEV_MINOR) {
729 mutex_enter(proc_lock);
730 usb_async_proc = 0;
731 mutex_exit(proc_lock);
732 usb_dev_open = 0;
733 }
734
735 return 0;
736 }
737
738 /* Call hook for usbd30_fill_device_info_old() */
739 MODULE_CALL_INT_HOOK_DECL(usb_subr_30_fill_hook,
740 (struct usbd_device *, struct usb_device_info_old *, int,
741 void (*)(struct usbd_device *, char *, size_t, char *, size_t, int, int),
742 int (*)(char *, size_t, int)));
743 MODULE_CALL_INT_HOOK(usb_subr_30_fill_hook,
744 (struct usbd_device *udev, struct usb_device_info_old * addr, int usedev,
745 void (*fill_devinfo_vp)(struct usbd_device *, char *, size_t, char *,
746 size_t, int, int),
747 int (*printBCD)(char *, size_t, int)),
748 (udev, addr, usedev, fill_devinfo_vp, printBCD),
749 enosys());
750
751 int
752 usbioctl(dev_t devt, u_long cmd, void *data, int flag, struct lwp *l)
753 {
754 struct usb_softc *sc;
755 int unit = minor(devt);
756
757 USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
758
759 if (unit == USB_DEV_MINOR) {
760 switch (cmd) {
761 case FIONBIO:
762 /* All handled in the upper FS layer. */
763 return 0;
764
765 case FIOASYNC:
766 mutex_enter(proc_lock);
767 if (*(int *)data)
768 usb_async_proc = l->l_proc;
769 else
770 usb_async_proc = 0;
771 mutex_exit(proc_lock);
772 return 0;
773
774 default:
775 return EINVAL;
776 }
777 }
778
779 sc = device_lookup_private(&usb_cd, unit);
780
781 if (sc->sc_dying)
782 return EIO;
783
784 int error = 0;
785 DPRINTF("cmd %#jx", cmd, 0, 0, 0);
786 switch (cmd) {
787 #ifdef USB_DEBUG
788 case USB_SETDEBUG:
789 if (!(flag & FWRITE))
790 return EBADF;
791 usbdebug = ((*(int *)data) & 0x000000ff);
792 break;
793 #endif /* USB_DEBUG */
794 case USB_REQUEST:
795 {
796 struct usb_ctl_request *ur = (void *)data;
797 int len = UGETW(ur->ucr_request.wLength);
798 struct iovec iov;
799 struct uio uio;
800 void *ptr = 0;
801 int addr = ur->ucr_addr;
802 usbd_status err;
803
804 if (!(flag & FWRITE)) {
805 error = EBADF;
806 goto fail;
807 }
808
809 DPRINTF("USB_REQUEST addr=%jd len=%jd", addr, len, 0, 0);
810 if (len < 0 || len > 32768) {
811 error = EINVAL;
812 goto fail;
813 }
814 if (addr < 0 || addr >= USB_MAX_DEVICES) {
815 error = EINVAL;
816 goto fail;
817 }
818 size_t dindex = usb_addr2dindex(addr);
819 if (sc->sc_bus->ub_devices[dindex] == NULL) {
820 error = EINVAL;
821 goto fail;
822 }
823 if (len != 0) {
824 iov.iov_base = (void *)ur->ucr_data;
825 iov.iov_len = len;
826 uio.uio_iov = &iov;
827 uio.uio_iovcnt = 1;
828 uio.uio_resid = len;
829 uio.uio_offset = 0;
830 uio.uio_rw =
831 ur->ucr_request.bmRequestType & UT_READ ?
832 UIO_READ : UIO_WRITE;
833 uio.uio_vmspace = l->l_proc->p_vmspace;
834 ptr = kmem_alloc(len, KM_SLEEP);
835 if (uio.uio_rw == UIO_WRITE) {
836 error = uiomove(ptr, len, &uio);
837 if (error)
838 goto ret;
839 }
840 }
841 err = usbd_do_request_flags(sc->sc_bus->ub_devices[dindex],
842 &ur->ucr_request, ptr, ur->ucr_flags, &ur->ucr_actlen,
843 USBD_DEFAULT_TIMEOUT);
844 if (err) {
845 error = EIO;
846 goto ret;
847 }
848 if (len > ur->ucr_actlen)
849 len = ur->ucr_actlen;
850 if (len != 0) {
851 if (uio.uio_rw == UIO_READ) {
852 error = uiomove(ptr, len, &uio);
853 if (error)
854 goto ret;
855 }
856 }
857 ret:
858 if (ptr) {
859 len = UGETW(ur->ucr_request.wLength);
860 kmem_free(ptr, len);
861 }
862 break;
863 }
864
865 case USB_DEVICEINFO:
866 {
867 struct usbd_device *dev;
868 struct usb_device_info *di = (void *)data;
869 int addr = di->udi_addr;
870
871 if (addr < 0 || addr >= USB_MAX_DEVICES) {
872 error = EINVAL;
873 goto fail;
874 }
875 size_t dindex = usb_addr2dindex(addr);
876 if ((dev = sc->sc_bus->ub_devices[dindex]) == NULL) {
877 error = ENXIO;
878 goto fail;
879 }
880 usbd_fill_deviceinfo(dev, di, 1);
881 break;
882 }
883
884 case USB_DEVICEINFO_OLD:
885 {
886 struct usbd_device *dev;
887 struct usb_device_info_old *di = (void *)data;
888 int addr = di->udi_addr;
889
890 if (addr < 1 || addr >= USB_MAX_DEVICES) {
891 error = EINVAL;
892 goto fail;
893 }
894 size_t dindex = usb_addr2dindex(addr);
895 if ((dev = sc->sc_bus->ub_devices[dindex]) == NULL) {
896 error = ENXIO;
897 goto fail;
898 }
899 error = usb_subr_30_fill_hook_call(dev, di, 1,
900 usbd_devinfo_vp, usbd_printBCD);
901 if (error == ENOSYS)
902 error = EINVAL;
903 if (error)
904 goto fail;
905 }
906
907 case USB_DEVICESTATS:
908 *(struct usb_device_stats *)data = sc->sc_bus->ub_stats;
909 break;
910
911 default:
912 error = EINVAL;
913 }
914
915 fail:
916
917 DPRINTF("... done (error = %jd)", error, 0, 0, 0);
918
919 return error;
920 }
921
922 int
923 usbpoll(dev_t dev, int events, struct lwp *l)
924 {
925 int revents, mask;
926
927 if (minor(dev) == USB_DEV_MINOR) {
928 revents = 0;
929 mask = POLLIN | POLLRDNORM;
930
931 mutex_enter(&usb_event_lock);
932 if (events & mask && usb_nevents > 0)
933 revents |= events & mask;
934 if (revents == 0 && events & mask)
935 selrecord(l, &usb_selevent);
936 mutex_exit(&usb_event_lock);
937
938 return revents;
939 } else {
940 return 0;
941 }
942 }
943
944 static void
945 filt_usbrdetach(struct knote *kn)
946 {
947
948 mutex_enter(&usb_event_lock);
949 SLIST_REMOVE(&usb_selevent.sel_klist, kn, knote, kn_selnext);
950 mutex_exit(&usb_event_lock);
951 }
952
953 static int
954 filt_usbread(struct knote *kn, long hint)
955 {
956
957 if (usb_nevents == 0)
958 return 0;
959
960 kn->kn_data = sizeof(struct usb_event);
961 return 1;
962 }
963
964 static const struct filterops usbread_filtops = {
965 .f_isfd = 1,
966 .f_attach = NULL,
967 .f_detach = filt_usbrdetach,
968 .f_event = filt_usbread,
969 };
970
971 int
972 usbkqfilter(dev_t dev, struct knote *kn)
973 {
974 struct klist *klist;
975
976 switch (kn->kn_filter) {
977 case EVFILT_READ:
978 if (minor(dev) != USB_DEV_MINOR)
979 return 1;
980 klist = &usb_selevent.sel_klist;
981 kn->kn_fop = &usbread_filtops;
982 break;
983
984 default:
985 return EINVAL;
986 }
987
988 kn->kn_hook = NULL;
989
990 mutex_enter(&usb_event_lock);
991 SLIST_INSERT_HEAD(klist, kn, kn_selnext);
992 mutex_exit(&usb_event_lock);
993
994 return 0;
995 }
996
997 /* Explore device tree from the root. */
998 Static void
999 usb_discover(struct usb_softc *sc)
1000 {
1001 struct usbd_bus *bus = sc->sc_bus;
1002
1003 USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
1004
1005 KASSERT(mutex_owned(bus->ub_lock));
1006
1007 if (usb_noexplore > 1)
1008 return;
1009
1010 /*
1011 * We need mutual exclusion while traversing the device tree,
1012 * but this is guaranteed since this function is only called
1013 * from the event thread for the controller.
1014 *
1015 * Also, we now have bus->ub_lock held, and in combination
1016 * with ub_exploring, avoids interferring with polling.
1017 */
1018 while (bus->ub_needsexplore && !sc->sc_dying) {
1019 bus->ub_needsexplore = 0;
1020 mutex_exit(sc->sc_bus->ub_lock);
1021 bus->ub_roothub->ud_hub->uh_explore(bus->ub_roothub);
1022 mutex_enter(bus->ub_lock);
1023 }
1024 }
1025
1026 void
1027 usb_needs_explore(struct usbd_device *dev)
1028 {
1029
1030 USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
1031
1032 mutex_enter(dev->ud_bus->ub_lock);
1033 dev->ud_bus->ub_needsexplore = 1;
1034 cv_signal(&dev->ud_bus->ub_needsexplore_cv);
1035 mutex_exit(dev->ud_bus->ub_lock);
1036 }
1037
1038 void
1039 usb_needs_reattach(struct usbd_device *dev)
1040 {
1041
1042 USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
1043
1044 mutex_enter(dev->ud_bus->ub_lock);
1045 dev->ud_powersrc->up_reattach = 1;
1046 dev->ud_bus->ub_needsexplore = 1;
1047 cv_signal(&dev->ud_bus->ub_needsexplore_cv);
1048 mutex_exit(dev->ud_bus->ub_lock);
1049 }
1050
1051 /* Called at with usb_event_lock held. */
1052 int
1053 usb_get_next_event(struct usb_event *ue)
1054 {
1055 struct usb_event_q *ueq;
1056
1057 KASSERT(mutex_owned(&usb_event_lock));
1058
1059 if (usb_nevents <= 0)
1060 return 0;
1061 ueq = SIMPLEQ_FIRST(&usb_events);
1062 #ifdef DIAGNOSTIC
1063 if (ueq == NULL) {
1064 printf("usb: usb_nevents got out of sync! %d\n", usb_nevents);
1065 usb_nevents = 0;
1066 return 0;
1067 }
1068 #endif
1069 if (ue)
1070 *ue = ueq->ue;
1071 SIMPLEQ_REMOVE_HEAD(&usb_events, next);
1072 usb_free_event((struct usb_event *)(void *)ueq);
1073 usb_nevents--;
1074 return 1;
1075 }
1076
1077 void
1078 usbd_add_dev_event(int type, struct usbd_device *udev)
1079 {
1080 struct usb_event *ue = usb_alloc_event();
1081
1082 usbd_fill_deviceinfo(udev, &ue->u.ue_device, false);
1083 usb_add_event(type, ue);
1084 }
1085
1086 void
1087 usbd_add_drv_event(int type, struct usbd_device *udev, device_t dev)
1088 {
1089 struct usb_event *ue = usb_alloc_event();
1090
1091 ue->u.ue_driver.ue_cookie = udev->ud_cookie;
1092 strncpy(ue->u.ue_driver.ue_devname, device_xname(dev),
1093 sizeof(ue->u.ue_driver.ue_devname));
1094 usb_add_event(type, ue);
1095 }
1096
1097 Static struct usb_event *
1098 usb_alloc_event(void)
1099 {
1100 /* Yes, this is right; we allocate enough so that we can use it later */
1101 return kmem_zalloc(sizeof(struct usb_event_q), KM_SLEEP);
1102 }
1103
1104 Static void
1105 usb_free_event(struct usb_event *uep)
1106 {
1107 kmem_free(uep, sizeof(struct usb_event_q));
1108 }
1109
1110 Static void
1111 usb_add_event(int type, struct usb_event *uep)
1112 {
1113 struct usb_event_q *ueq;
1114 struct timeval thetime;
1115
1116 USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
1117
1118 microtime(&thetime);
1119 /* Don't want to wait here with usb_event_lock held */
1120 ueq = (struct usb_event_q *)(void *)uep;
1121 ueq->ue = *uep;
1122 ueq->ue.ue_type = type;
1123 TIMEVAL_TO_TIMESPEC(&thetime, &ueq->ue.ue_time);
1124
1125 mutex_enter(&usb_event_lock);
1126 if (++usb_nevents >= USB_MAX_EVENTS) {
1127 /* Too many queued events, drop an old one. */
1128 DPRINTF("event dropped", 0, 0, 0, 0);
1129 (void)usb_get_next_event(0);
1130 }
1131 SIMPLEQ_INSERT_TAIL(&usb_events, ueq, next);
1132 cv_signal(&usb_event_cv);
1133 selnotify(&usb_selevent, 0, 0);
1134 if (usb_async_proc != NULL) {
1135 kpreempt_disable();
1136 softint_schedule(usb_async_sih);
1137 kpreempt_enable();
1138 }
1139 mutex_exit(&usb_event_lock);
1140 }
1141
1142 Static void
1143 usb_async_intr(void *cookie)
1144 {
1145 proc_t *proc;
1146
1147 mutex_enter(proc_lock);
1148 if ((proc = usb_async_proc) != NULL)
1149 psignal(proc, SIGIO);
1150 mutex_exit(proc_lock);
1151 }
1152
1153 Static void
1154 usb_soft_intr(void *arg)
1155 {
1156 struct usbd_bus *bus = arg;
1157
1158 mutex_enter(bus->ub_lock);
1159 bus->ub_methods->ubm_softint(bus);
1160 mutex_exit(bus->ub_lock);
1161 }
1162
1163 void
1164 usb_schedsoftintr(struct usbd_bus *bus)
1165 {
1166
1167 USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
1168
1169 DPRINTFN(10, "polling=%jd", bus->ub_usepolling, 0, 0, 0);
1170
1171 /* In case the bus never finished setting up. */
1172 if (__predict_false(bus->ub_soft == NULL))
1173 return;
1174
1175 if (bus->ub_usepolling) {
1176 bus->ub_methods->ubm_softint(bus);
1177 } else {
1178 kpreempt_disable();
1179 softint_schedule(bus->ub_soft);
1180 kpreempt_enable();
1181 }
1182 }
1183
1184 int
1185 usb_activate(device_t self, enum devact act)
1186 {
1187 struct usb_softc *sc = device_private(self);
1188
1189 switch (act) {
1190 case DVACT_DEACTIVATE:
1191 sc->sc_dying = 1;
1192 return 0;
1193 default:
1194 return EOPNOTSUPP;
1195 }
1196 }
1197
1198 void
1199 usb_childdet(device_t self, device_t child)
1200 {
1201 int i;
1202 struct usb_softc *sc = device_private(self);
1203 struct usbd_device *dev;
1204
1205 if ((dev = sc->sc_port.up_dev) == NULL || dev->ud_subdevlen == 0)
1206 return;
1207
1208 for (i = 0; i < dev->ud_subdevlen; i++)
1209 if (dev->ud_subdevs[i] == child)
1210 dev->ud_subdevs[i] = NULL;
1211 }
1212
1213 int
1214 usb_detach(device_t self, int flags)
1215 {
1216 struct usb_softc *sc = device_private(self);
1217 struct usb_event *ue;
1218 int rc;
1219
1220 USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
1221
1222 /* Make all devices disconnect. */
1223 if (sc->sc_port.up_dev != NULL &&
1224 (rc = usb_disconnect_port(&sc->sc_port, self, flags)) != 0)
1225 return rc;
1226
1227 if (sc->sc_pmf_registered)
1228 pmf_device_deregister(self);
1229 /* Kill off event thread. */
1230 sc->sc_dying = 1;
1231 while (sc->sc_event_thread != NULL) {
1232 mutex_enter(sc->sc_bus->ub_lock);
1233 cv_signal(&sc->sc_bus->ub_needsexplore_cv);
1234 cv_timedwait(&sc->sc_bus->ub_needsexplore_cv,
1235 sc->sc_bus->ub_lock, hz * 60);
1236 mutex_exit(sc->sc_bus->ub_lock);
1237 }
1238 DPRINTF("event thread dead", 0, 0, 0, 0);
1239
1240 if (sc->sc_bus->ub_soft != NULL) {
1241 softint_disestablish(sc->sc_bus->ub_soft);
1242 sc->sc_bus->ub_soft = NULL;
1243 }
1244
1245 ue = usb_alloc_event();
1246 ue->u.ue_ctrlr.ue_bus = device_unit(self);
1247 usb_add_event(USB_EVENT_CTRLR_DETACH, ue);
1248
1249 cv_destroy(&sc->sc_bus->ub_needsexplore_cv);
1250
1251 return 0;
1252 }
1253