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