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