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