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