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