usb.c revision 1.176 1 /* $NetBSD: usb.c,v 1.176 2019/01/29 09:28:50 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.176 2019/01/29 09:28:50 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 int
660 usbread(dev_t dev, struct uio *uio, int flag)
661 {
662 struct usb_event *ue;
663 struct usb_event_old *ueo = NULL; /* XXXGCC */
664 int useold = 0;
665 int error, n;
666
667 if (minor(dev) != USB_DEV_MINOR)
668 return ENXIO;
669
670 switch (uio->uio_resid) {
671 case sizeof(struct usb_event_old):
672 ueo = kmem_zalloc(sizeof(struct usb_event_old), KM_SLEEP);
673 useold = 1;
674 /* FALLTHRU */
675 case sizeof(struct usb_event):
676 ue = usb_alloc_event();
677 break;
678 default:
679 return EINVAL;
680 }
681
682 error = 0;
683 mutex_enter(&usb_event_lock);
684 for (;;) {
685 n = usb_get_next_event(ue);
686 if (n != 0)
687 break;
688 if (flag & IO_NDELAY) {
689 error = EWOULDBLOCK;
690 break;
691 }
692 error = cv_wait_sig(&usb_event_cv, &usb_event_lock);
693 if (error)
694 break;
695 }
696 mutex_exit(&usb_event_lock);
697 if (!error) {
698 if (useold) { /* copy fields to old struct */
699 MODULE_CALL_HOOK(usb_subr_copy_30_hook,
700 (ue, ueo, uio), enosys(), error);
701 if (error == ENOSYS)
702 error = EINVAL;
703
704 if (!error)
705 error = uiomove((void *)ueo, sizeof(*ueo), uio);
706 } else
707 error = uiomove((void *)ue, sizeof(*ue), uio);
708 }
709 usb_free_event(ue);
710 if (ueo)
711 kmem_free(ueo, sizeof(struct usb_event_old));
712
713 return error;
714 }
715
716 int
717 usbclose(dev_t dev, int flag, int mode,
718 struct lwp *l)
719 {
720 int unit = minor(dev);
721
722 if (unit == USB_DEV_MINOR) {
723 mutex_enter(proc_lock);
724 usb_async_proc = 0;
725 mutex_exit(proc_lock);
726 usb_dev_open = 0;
727 }
728
729 return 0;
730 }
731
732 int
733 usbioctl(dev_t devt, u_long cmd, void *data, int flag, struct lwp *l)
734 {
735 struct usb_softc *sc;
736 int unit = minor(devt);
737
738 USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
739
740 if (unit == USB_DEV_MINOR) {
741 switch (cmd) {
742 case FIONBIO:
743 /* All handled in the upper FS layer. */
744 return 0;
745
746 case FIOASYNC:
747 mutex_enter(proc_lock);
748 if (*(int *)data)
749 usb_async_proc = l->l_proc;
750 else
751 usb_async_proc = 0;
752 mutex_exit(proc_lock);
753 return 0;
754
755 default:
756 return EINVAL;
757 }
758 }
759
760 sc = device_lookup_private(&usb_cd, unit);
761
762 if (sc->sc_dying)
763 return EIO;
764
765 int error = 0;
766 DPRINTF("cmd %#jx", cmd, 0, 0, 0);
767 switch (cmd) {
768 #ifdef USB_DEBUG
769 case USB_SETDEBUG:
770 if (!(flag & FWRITE))
771 return EBADF;
772 usbdebug = ((*(int *)data) & 0x000000ff);
773 break;
774 #endif /* USB_DEBUG */
775 case USB_REQUEST:
776 {
777 struct usb_ctl_request *ur = (void *)data;
778 int len = UGETW(ur->ucr_request.wLength);
779 struct iovec iov;
780 struct uio uio;
781 void *ptr = 0;
782 int addr = ur->ucr_addr;
783 usbd_status err;
784
785 if (!(flag & FWRITE)) {
786 error = EBADF;
787 goto fail;
788 }
789
790 DPRINTF("USB_REQUEST addr=%jd len=%jd", addr, len, 0, 0);
791 if (len < 0 || len > 32768) {
792 error = EINVAL;
793 goto fail;
794 }
795 if (addr < 0 || addr >= USB_MAX_DEVICES) {
796 error = EINVAL;
797 goto fail;
798 }
799 size_t dindex = usb_addr2dindex(addr);
800 if (sc->sc_bus->ub_devices[dindex] == NULL) {
801 error = EINVAL;
802 goto fail;
803 }
804 if (len != 0) {
805 iov.iov_base = (void *)ur->ucr_data;
806 iov.iov_len = len;
807 uio.uio_iov = &iov;
808 uio.uio_iovcnt = 1;
809 uio.uio_resid = len;
810 uio.uio_offset = 0;
811 uio.uio_rw =
812 ur->ucr_request.bmRequestType & UT_READ ?
813 UIO_READ : UIO_WRITE;
814 uio.uio_vmspace = l->l_proc->p_vmspace;
815 ptr = kmem_alloc(len, KM_SLEEP);
816 if (uio.uio_rw == UIO_WRITE) {
817 error = uiomove(ptr, len, &uio);
818 if (error)
819 goto ret;
820 }
821 }
822 err = usbd_do_request_flags(sc->sc_bus->ub_devices[dindex],
823 &ur->ucr_request, ptr, ur->ucr_flags, &ur->ucr_actlen,
824 USBD_DEFAULT_TIMEOUT);
825 if (err) {
826 error = EIO;
827 goto ret;
828 }
829 if (len > ur->ucr_actlen)
830 len = ur->ucr_actlen;
831 if (len != 0) {
832 if (uio.uio_rw == UIO_READ) {
833 error = uiomove(ptr, len, &uio);
834 if (error)
835 goto ret;
836 }
837 }
838 ret:
839 if (ptr) {
840 len = UGETW(ur->ucr_request.wLength);
841 kmem_free(ptr, len);
842 }
843 break;
844 }
845
846 case USB_DEVICEINFO:
847 {
848 struct usbd_device *dev;
849 struct usb_device_info *di = (void *)data;
850 int addr = di->udi_addr;
851
852 if (addr < 0 || addr >= USB_MAX_DEVICES) {
853 error = EINVAL;
854 goto fail;
855 }
856 size_t dindex = usb_addr2dindex(addr);
857 if ((dev = sc->sc_bus->ub_devices[dindex]) == NULL) {
858 error = ENXIO;
859 goto fail;
860 }
861 usbd_fill_deviceinfo(dev, di, 1);
862 break;
863 }
864
865 case USB_DEVICEINFO_OLD:
866 {
867 struct usbd_device *dev;
868 struct usb_device_info_old *di = (void *)data;
869 int addr = di->udi_addr;
870
871 if (addr < 1 || 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 MODULE_CALL_HOOK(usb_subr_fill_30_hook,
881 (dev, di, 1, usbd_devinfo_vp, usbd_printBCD),
882 enosys(), error);
883 if (error == ENOSYS)
884 error = EINVAL;
885 if (error)
886 goto fail;
887 }
888
889 case USB_DEVICESTATS:
890 *(struct usb_device_stats *)data = sc->sc_bus->ub_stats;
891 break;
892
893 default:
894 error = EINVAL;
895 }
896
897 fail:
898
899 DPRINTF("... done (error = %jd)", error, 0, 0, 0);
900
901 return error;
902 }
903
904 int
905 usbpoll(dev_t dev, int events, struct lwp *l)
906 {
907 int revents, mask;
908
909 if (minor(dev) == USB_DEV_MINOR) {
910 revents = 0;
911 mask = POLLIN | POLLRDNORM;
912
913 mutex_enter(&usb_event_lock);
914 if (events & mask && usb_nevents > 0)
915 revents |= events & mask;
916 if (revents == 0 && events & mask)
917 selrecord(l, &usb_selevent);
918 mutex_exit(&usb_event_lock);
919
920 return revents;
921 } else {
922 return 0;
923 }
924 }
925
926 static void
927 filt_usbrdetach(struct knote *kn)
928 {
929
930 mutex_enter(&usb_event_lock);
931 SLIST_REMOVE(&usb_selevent.sel_klist, kn, knote, kn_selnext);
932 mutex_exit(&usb_event_lock);
933 }
934
935 static int
936 filt_usbread(struct knote *kn, long hint)
937 {
938
939 if (usb_nevents == 0)
940 return 0;
941
942 kn->kn_data = sizeof(struct usb_event);
943 return 1;
944 }
945
946 static const struct filterops usbread_filtops = {
947 .f_isfd = 1,
948 .f_attach = NULL,
949 .f_detach = filt_usbrdetach,
950 .f_event = filt_usbread,
951 };
952
953 int
954 usbkqfilter(dev_t dev, struct knote *kn)
955 {
956 struct klist *klist;
957
958 switch (kn->kn_filter) {
959 case EVFILT_READ:
960 if (minor(dev) != USB_DEV_MINOR)
961 return 1;
962 klist = &usb_selevent.sel_klist;
963 kn->kn_fop = &usbread_filtops;
964 break;
965
966 default:
967 return EINVAL;
968 }
969
970 kn->kn_hook = NULL;
971
972 mutex_enter(&usb_event_lock);
973 SLIST_INSERT_HEAD(klist, kn, kn_selnext);
974 mutex_exit(&usb_event_lock);
975
976 return 0;
977 }
978
979 /* Explore device tree from the root. */
980 Static void
981 usb_discover(struct usb_softc *sc)
982 {
983 struct usbd_bus *bus = sc->sc_bus;
984
985 USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
986
987 KASSERT(mutex_owned(bus->ub_lock));
988
989 if (usb_noexplore > 1)
990 return;
991
992 /*
993 * We need mutual exclusion while traversing the device tree,
994 * but this is guaranteed since this function is only called
995 * from the event thread for the controller.
996 *
997 * Also, we now have bus->ub_lock held, and in combination
998 * with ub_exploring, avoids interferring with polling.
999 */
1000 while (bus->ub_needsexplore && !sc->sc_dying) {
1001 bus->ub_needsexplore = 0;
1002 mutex_exit(sc->sc_bus->ub_lock);
1003 bus->ub_roothub->ud_hub->uh_explore(bus->ub_roothub);
1004 mutex_enter(bus->ub_lock);
1005 }
1006 }
1007
1008 void
1009 usb_needs_explore(struct usbd_device *dev)
1010 {
1011
1012 USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
1013
1014 mutex_enter(dev->ud_bus->ub_lock);
1015 dev->ud_bus->ub_needsexplore = 1;
1016 cv_signal(&dev->ud_bus->ub_needsexplore_cv);
1017 mutex_exit(dev->ud_bus->ub_lock);
1018 }
1019
1020 void
1021 usb_needs_reattach(struct usbd_device *dev)
1022 {
1023
1024 USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
1025
1026 mutex_enter(dev->ud_bus->ub_lock);
1027 dev->ud_powersrc->up_reattach = 1;
1028 dev->ud_bus->ub_needsexplore = 1;
1029 cv_signal(&dev->ud_bus->ub_needsexplore_cv);
1030 mutex_exit(dev->ud_bus->ub_lock);
1031 }
1032
1033 /* Called at with usb_event_lock held. */
1034 int
1035 usb_get_next_event(struct usb_event *ue)
1036 {
1037 struct usb_event_q *ueq;
1038
1039 KASSERT(mutex_owned(&usb_event_lock));
1040
1041 if (usb_nevents <= 0)
1042 return 0;
1043 ueq = SIMPLEQ_FIRST(&usb_events);
1044 #ifdef DIAGNOSTIC
1045 if (ueq == NULL) {
1046 printf("usb: usb_nevents got out of sync! %d\n", usb_nevents);
1047 usb_nevents = 0;
1048 return 0;
1049 }
1050 #endif
1051 if (ue)
1052 *ue = ueq->ue;
1053 SIMPLEQ_REMOVE_HEAD(&usb_events, next);
1054 usb_free_event((struct usb_event *)(void *)ueq);
1055 usb_nevents--;
1056 return 1;
1057 }
1058
1059 void
1060 usbd_add_dev_event(int type, struct usbd_device *udev)
1061 {
1062 struct usb_event *ue = usb_alloc_event();
1063
1064 usbd_fill_deviceinfo(udev, &ue->u.ue_device, false);
1065 usb_add_event(type, ue);
1066 }
1067
1068 void
1069 usbd_add_drv_event(int type, struct usbd_device *udev, device_t dev)
1070 {
1071 struct usb_event *ue = usb_alloc_event();
1072
1073 ue->u.ue_driver.ue_cookie = udev->ud_cookie;
1074 strncpy(ue->u.ue_driver.ue_devname, device_xname(dev),
1075 sizeof(ue->u.ue_driver.ue_devname));
1076 usb_add_event(type, ue);
1077 }
1078
1079 Static struct usb_event *
1080 usb_alloc_event(void)
1081 {
1082 /* Yes, this is right; we allocate enough so that we can use it later */
1083 return kmem_zalloc(sizeof(struct usb_event_q), KM_SLEEP);
1084 }
1085
1086 Static void
1087 usb_free_event(struct usb_event *uep)
1088 {
1089 kmem_free(uep, sizeof(struct usb_event_q));
1090 }
1091
1092 Static void
1093 usb_add_event(int type, struct usb_event *uep)
1094 {
1095 struct usb_event_q *ueq;
1096 struct timeval thetime;
1097
1098 USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
1099
1100 microtime(&thetime);
1101 /* Don't want to wait here with usb_event_lock held */
1102 ueq = (struct usb_event_q *)(void *)uep;
1103 ueq->ue = *uep;
1104 ueq->ue.ue_type = type;
1105 TIMEVAL_TO_TIMESPEC(&thetime, &ueq->ue.ue_time);
1106
1107 mutex_enter(&usb_event_lock);
1108 if (++usb_nevents >= USB_MAX_EVENTS) {
1109 /* Too many queued events, drop an old one. */
1110 DPRINTF("event dropped", 0, 0, 0, 0);
1111 (void)usb_get_next_event(0);
1112 }
1113 SIMPLEQ_INSERT_TAIL(&usb_events, ueq, next);
1114 cv_signal(&usb_event_cv);
1115 selnotify(&usb_selevent, 0, 0);
1116 if (usb_async_proc != NULL) {
1117 kpreempt_disable();
1118 softint_schedule(usb_async_sih);
1119 kpreempt_enable();
1120 }
1121 mutex_exit(&usb_event_lock);
1122 }
1123
1124 Static void
1125 usb_async_intr(void *cookie)
1126 {
1127 proc_t *proc;
1128
1129 mutex_enter(proc_lock);
1130 if ((proc = usb_async_proc) != NULL)
1131 psignal(proc, SIGIO);
1132 mutex_exit(proc_lock);
1133 }
1134
1135 Static void
1136 usb_soft_intr(void *arg)
1137 {
1138 struct usbd_bus *bus = arg;
1139
1140 mutex_enter(bus->ub_lock);
1141 bus->ub_methods->ubm_softint(bus);
1142 mutex_exit(bus->ub_lock);
1143 }
1144
1145 void
1146 usb_schedsoftintr(struct usbd_bus *bus)
1147 {
1148
1149 USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
1150
1151 DPRINTFN(10, "polling=%jd", bus->ub_usepolling, 0, 0, 0);
1152
1153 /* In case the bus never finished setting up. */
1154 if (__predict_false(bus->ub_soft == NULL))
1155 return;
1156
1157 if (bus->ub_usepolling) {
1158 bus->ub_methods->ubm_softint(bus);
1159 } else {
1160 kpreempt_disable();
1161 softint_schedule(bus->ub_soft);
1162 kpreempt_enable();
1163 }
1164 }
1165
1166 int
1167 usb_activate(device_t self, enum devact act)
1168 {
1169 struct usb_softc *sc = device_private(self);
1170
1171 switch (act) {
1172 case DVACT_DEACTIVATE:
1173 sc->sc_dying = 1;
1174 return 0;
1175 default:
1176 return EOPNOTSUPP;
1177 }
1178 }
1179
1180 void
1181 usb_childdet(device_t self, device_t child)
1182 {
1183 int i;
1184 struct usb_softc *sc = device_private(self);
1185 struct usbd_device *dev;
1186
1187 if ((dev = sc->sc_port.up_dev) == NULL || dev->ud_subdevlen == 0)
1188 return;
1189
1190 for (i = 0; i < dev->ud_subdevlen; i++)
1191 if (dev->ud_subdevs[i] == child)
1192 dev->ud_subdevs[i] = NULL;
1193 }
1194
1195 int
1196 usb_detach(device_t self, int flags)
1197 {
1198 struct usb_softc *sc = device_private(self);
1199 struct usb_event *ue;
1200 int rc;
1201
1202 USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
1203
1204 /* Make all devices disconnect. */
1205 if (sc->sc_port.up_dev != NULL &&
1206 (rc = usb_disconnect_port(&sc->sc_port, self, flags)) != 0)
1207 return rc;
1208
1209 if (sc->sc_pmf_registered)
1210 pmf_device_deregister(self);
1211 /* Kill off event thread. */
1212 sc->sc_dying = 1;
1213 while (sc->sc_event_thread != NULL) {
1214 mutex_enter(sc->sc_bus->ub_lock);
1215 cv_signal(&sc->sc_bus->ub_needsexplore_cv);
1216 cv_timedwait(&sc->sc_bus->ub_needsexplore_cv,
1217 sc->sc_bus->ub_lock, hz * 60);
1218 mutex_exit(sc->sc_bus->ub_lock);
1219 }
1220 DPRINTF("event thread dead", 0, 0, 0, 0);
1221
1222 if (sc->sc_bus->ub_soft != NULL) {
1223 softint_disestablish(sc->sc_bus->ub_soft);
1224 sc->sc_bus->ub_soft = NULL;
1225 }
1226
1227 ue = usb_alloc_event();
1228 ue->u.ue_ctrlr.ue_bus = device_unit(self);
1229 usb_add_event(USB_EVENT_CTRLR_DETACH, ue);
1230
1231 cv_destroy(&sc->sc_bus->ub_needsexplore_cv);
1232
1233 return 0;
1234 }
1235