Home | History | Annotate | Line # | Download | only in usb
usb.c revision 1.168.2.7
      1 /*	$NetBSD: usb.c,v 1.168.2.7 2018/09/30 01:45:51 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.7 2018/09/30 01:45:51 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 /* Call hook for usbd30_fill_device_info_old() */
    660 MODULE_CALL_HOOK_DECL(usb_subr_30_hook, f2,
    661     (struct usb_event *ue, struct usb_event_old *ueo, struct uio *uio));
    662 MODULE_CALL_HOOK(usb_subr_30_hook, f2,
    663     (struct usb_event *ue, struct usb_event_old *ueo, struct uio *uio),
    664     (ue, ueo, uio), enosys());
    665 
    666 int
    667 usbread(dev_t dev, struct uio *uio, int flag)
    668 {
    669 	struct usb_event *ue;
    670 	struct usb_event_old *ueo = NULL;	/* XXXGCC */
    671 	int useold = 0;
    672 	int error, n;
    673 
    674 	if (minor(dev) != USB_DEV_MINOR)
    675 		return ENXIO;
    676 
    677 	switch (uio->uio_resid) {
    678 	case sizeof(struct usb_event_old):
    679 		ueo = kmem_zalloc(sizeof(struct usb_event_old), KM_SLEEP);
    680 		useold = 1;
    681 		/* FALLTHRU */
    682 	case sizeof(struct usb_event):
    683 		ue = usb_alloc_event();
    684 		break;
    685 	default:
    686 		return EINVAL;
    687 	}
    688 
    689 	error = 0;
    690 	mutex_enter(&usb_event_lock);
    691 	for (;;) {
    692 		n = usb_get_next_event(ue);
    693 		if (n != 0)
    694 			break;
    695 		if (flag & IO_NDELAY) {
    696 			error = EWOULDBLOCK;
    697 			break;
    698 		}
    699 		error = cv_wait_sig(&usb_event_cv, &usb_event_lock);
    700 		if (error)
    701 			break;
    702 	}
    703 	mutex_exit(&usb_event_lock);
    704 	if (!error) {
    705 		if (useold) { /* copy fields to old struct */
    706 			error = usb_subr_30_hook_f2_call(ue, ueo, uio);
    707 			if (error == ENOSYS)
    708 				error = EINVAL;
    709 
    710 			if (!error)
    711 				error = uiomove((void *)ueo, sizeof(*ueo), uio);
    712 		} else
    713 			error = uiomove((void *)ue, sizeof(*ue), uio);
    714 	}
    715 	usb_free_event(ue);
    716 	if (ueo)
    717 		kmem_free(ueo, sizeof(struct usb_event_old));
    718 
    719 	return error;
    720 }
    721 
    722 int
    723 usbclose(dev_t dev, int flag, int mode,
    724     struct lwp *l)
    725 {
    726 	int unit = minor(dev);
    727 
    728 	if (unit == USB_DEV_MINOR) {
    729 		mutex_enter(proc_lock);
    730 		usb_async_proc = 0;
    731 		mutex_exit(proc_lock);
    732 		usb_dev_open = 0;
    733 	}
    734 
    735 	return 0;
    736 }
    737 
    738 /* Call the hook for usb30_copy_to_old() */
    739 MODULE_CALL_HOOK_DECL(usb_subr_30_hook, f1,
    740     (struct usbd_device *udev, struct usb_device_info_old * addr, int usedev,
    741       void (*fill_devinfo_vp)(struct usbd_device *, char *, size_t, char *,
    742 	size_t, int, int), int (*printBCD)(char *, size_t, int)));
    743 MODULE_CALL_HOOK(usb_subr_30_hook, f1,
    744     (struct usbd_device *udev, struct usb_device_info_old * addr, int usedev,
    745       void (*fill_devinfo_vp)(struct usbd_device *, char *, size_t, char *,
    746 	size_t, int, int), int (*printBCD)(char *, size_t, int)),
    747     (udev, addr, usedev, fill_devinfo_vp, printBCD),
    748     enosys());
    749 
    750 int
    751 usbioctl(dev_t devt, u_long cmd, void *data, int flag, struct lwp *l)
    752 {
    753 	struct usb_softc *sc;
    754 	int unit = minor(devt);
    755 
    756 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
    757 
    758 	if (unit == USB_DEV_MINOR) {
    759 		switch (cmd) {
    760 		case FIONBIO:
    761 			/* All handled in the upper FS layer. */
    762 			return 0;
    763 
    764 		case FIOASYNC:
    765 			mutex_enter(proc_lock);
    766 			if (*(int *)data)
    767 				usb_async_proc = l->l_proc;
    768 			else
    769 				usb_async_proc = 0;
    770 			mutex_exit(proc_lock);
    771 			return 0;
    772 
    773 		default:
    774 			return EINVAL;
    775 		}
    776 	}
    777 
    778 	sc = device_lookup_private(&usb_cd, unit);
    779 
    780 	if (sc->sc_dying)
    781 		return EIO;
    782 
    783 	int error = 0;
    784 	DPRINTF("cmd %#jx", cmd, 0, 0, 0);
    785 	switch (cmd) {
    786 #ifdef USB_DEBUG
    787 	case USB_SETDEBUG:
    788 		if (!(flag & FWRITE))
    789 			return EBADF;
    790 		usbdebug  = ((*(int *)data) & 0x000000ff);
    791 		break;
    792 #endif /* USB_DEBUG */
    793 	case USB_REQUEST:
    794 	{
    795 		struct usb_ctl_request *ur = (void *)data;
    796 		int len = UGETW(ur->ucr_request.wLength);
    797 		struct iovec iov;
    798 		struct uio uio;
    799 		void *ptr = 0;
    800 		int addr = ur->ucr_addr;
    801 		usbd_status err;
    802 
    803 		if (!(flag & FWRITE)) {
    804 			error = EBADF;
    805 			goto fail;
    806 		}
    807 
    808 		DPRINTF("USB_REQUEST addr=%jd len=%jd", addr, len, 0, 0);
    809 		if (len < 0 || len > 32768) {
    810 			error = EINVAL;
    811 			goto fail;
    812 		}
    813 		if (addr < 0 || addr >= USB_MAX_DEVICES) {
    814 			error = EINVAL;
    815 			goto fail;
    816 		}
    817 		size_t dindex = usb_addr2dindex(addr);
    818 		if (sc->sc_bus->ub_devices[dindex] == NULL) {
    819 			error = EINVAL;
    820 			goto fail;
    821 		}
    822 		if (len != 0) {
    823 			iov.iov_base = (void *)ur->ucr_data;
    824 			iov.iov_len = len;
    825 			uio.uio_iov = &iov;
    826 			uio.uio_iovcnt = 1;
    827 			uio.uio_resid = len;
    828 			uio.uio_offset = 0;
    829 			uio.uio_rw =
    830 				ur->ucr_request.bmRequestType & UT_READ ?
    831 				UIO_READ : UIO_WRITE;
    832 			uio.uio_vmspace = l->l_proc->p_vmspace;
    833 			ptr = kmem_alloc(len, KM_SLEEP);
    834 			if (uio.uio_rw == UIO_WRITE) {
    835 				error = uiomove(ptr, len, &uio);
    836 				if (error)
    837 					goto ret;
    838 			}
    839 		}
    840 		err = usbd_do_request_flags(sc->sc_bus->ub_devices[dindex],
    841 			  &ur->ucr_request, ptr, ur->ucr_flags, &ur->ucr_actlen,
    842 			  USBD_DEFAULT_TIMEOUT);
    843 		if (err) {
    844 			error = EIO;
    845 			goto ret;
    846 		}
    847 		if (len > ur->ucr_actlen)
    848 			len = ur->ucr_actlen;
    849 		if (len != 0) {
    850 			if (uio.uio_rw == UIO_READ) {
    851 				error = uiomove(ptr, len, &uio);
    852 				if (error)
    853 					goto ret;
    854 			}
    855 		}
    856 	ret:
    857 		if (ptr) {
    858 			len = UGETW(ur->ucr_request.wLength);
    859 			kmem_free(ptr, len);
    860 		}
    861 		break;
    862 	}
    863 
    864 	case USB_DEVICEINFO:
    865 	{
    866 		struct usbd_device *dev;
    867 		struct usb_device_info *di = (void *)data;
    868 		int addr = di->udi_addr;
    869 
    870 		if (addr < 0 || addr >= USB_MAX_DEVICES) {
    871 			error = EINVAL;
    872 			goto fail;
    873 		}
    874 		size_t dindex = usb_addr2dindex(addr);
    875 		if ((dev = sc->sc_bus->ub_devices[dindex]) == NULL) {
    876 			error = ENXIO;
    877 			goto fail;
    878 		}
    879 		usbd_fill_deviceinfo(dev, di, 1);
    880 		break;
    881 	}
    882 
    883 	case USB_DEVICEINFO_OLD:
    884 	{
    885 		struct usbd_device *dev;
    886 		struct usb_device_info_old *di = (void *)data;
    887 		int addr = di->udi_addr;
    888 
    889 		if (addr < 1 || addr >= USB_MAX_DEVICES) {
    890 			error = EINVAL;
    891 			goto fail;
    892 		}
    893 		size_t dindex = usb_addr2dindex(addr);
    894 		if ((dev = sc->sc_bus->ub_devices[dindex]) == NULL) {
    895 			error = ENXIO;
    896 			goto fail;
    897 		}
    898 		error = usb_subr_30_hook_f1_call(dev, di, 1,
    899 				usbd_devinfo_vp, usbd_printBCD);
    900 		if (error == ENOSYS)
    901 			error = EINVAL;
    902 		if (error)
    903 			goto fail;
    904 	}
    905 
    906 	case USB_DEVICESTATS:
    907 		*(struct usb_device_stats *)data = sc->sc_bus->ub_stats;
    908 		break;
    909 
    910 	default:
    911 		error = EINVAL;
    912 	}
    913 
    914 fail:
    915 
    916 	DPRINTF("... done (error = %jd)", error, 0, 0, 0);
    917 
    918 	return error;
    919 }
    920 
    921 int
    922 usbpoll(dev_t dev, int events, struct lwp *l)
    923 {
    924 	int revents, mask;
    925 
    926 	if (minor(dev) == USB_DEV_MINOR) {
    927 		revents = 0;
    928 		mask = POLLIN | POLLRDNORM;
    929 
    930 		mutex_enter(&usb_event_lock);
    931 		if (events & mask && usb_nevents > 0)
    932 			revents |= events & mask;
    933 		if (revents == 0 && events & mask)
    934 			selrecord(l, &usb_selevent);
    935 		mutex_exit(&usb_event_lock);
    936 
    937 		return revents;
    938 	} else {
    939 		return 0;
    940 	}
    941 }
    942 
    943 static void
    944 filt_usbrdetach(struct knote *kn)
    945 {
    946 
    947 	mutex_enter(&usb_event_lock);
    948 	SLIST_REMOVE(&usb_selevent.sel_klist, kn, knote, kn_selnext);
    949 	mutex_exit(&usb_event_lock);
    950 }
    951 
    952 static int
    953 filt_usbread(struct knote *kn, long hint)
    954 {
    955 
    956 	if (usb_nevents == 0)
    957 		return 0;
    958 
    959 	kn->kn_data = sizeof(struct usb_event);
    960 	return 1;
    961 }
    962 
    963 static const struct filterops usbread_filtops = {
    964 	.f_isfd = 1,
    965 	.f_attach = NULL,
    966 	.f_detach = filt_usbrdetach,
    967 	.f_event = filt_usbread,
    968 };
    969 
    970 int
    971 usbkqfilter(dev_t dev, struct knote *kn)
    972 {
    973 	struct klist *klist;
    974 
    975 	switch (kn->kn_filter) {
    976 	case EVFILT_READ:
    977 		if (minor(dev) != USB_DEV_MINOR)
    978 			return 1;
    979 		klist = &usb_selevent.sel_klist;
    980 		kn->kn_fop = &usbread_filtops;
    981 		break;
    982 
    983 	default:
    984 		return EINVAL;
    985 	}
    986 
    987 	kn->kn_hook = NULL;
    988 
    989 	mutex_enter(&usb_event_lock);
    990 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
    991 	mutex_exit(&usb_event_lock);
    992 
    993 	return 0;
    994 }
    995 
    996 /* Explore device tree from the root. */
    997 Static void
    998 usb_discover(struct usb_softc *sc)
    999 {
   1000 	struct usbd_bus *bus = sc->sc_bus;
   1001 
   1002 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
   1003 
   1004 	KASSERT(mutex_owned(bus->ub_lock));
   1005 
   1006 	if (usb_noexplore > 1)
   1007 		return;
   1008 
   1009 	/*
   1010 	 * We need mutual exclusion while traversing the device tree,
   1011 	 * but this is guaranteed since this function is only called
   1012 	 * from the event thread for the controller.
   1013 	 *
   1014 	 * Also, we now have bus->ub_lock held, and in combination
   1015 	 * with ub_exploring, avoids interferring with polling.
   1016 	 */
   1017 	while (bus->ub_needsexplore && !sc->sc_dying) {
   1018 		bus->ub_needsexplore = 0;
   1019 		mutex_exit(sc->sc_bus->ub_lock);
   1020 		bus->ub_roothub->ud_hub->uh_explore(bus->ub_roothub);
   1021 		mutex_enter(bus->ub_lock);
   1022 	}
   1023 }
   1024 
   1025 void
   1026 usb_needs_explore(struct usbd_device *dev)
   1027 {
   1028 
   1029 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
   1030 
   1031 	mutex_enter(dev->ud_bus->ub_lock);
   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 void
   1038 usb_needs_reattach(struct usbd_device *dev)
   1039 {
   1040 
   1041 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
   1042 
   1043 	mutex_enter(dev->ud_bus->ub_lock);
   1044 	dev->ud_powersrc->up_reattach = 1;
   1045 	dev->ud_bus->ub_needsexplore = 1;
   1046 	cv_signal(&dev->ud_bus->ub_needsexplore_cv);
   1047 	mutex_exit(dev->ud_bus->ub_lock);
   1048 }
   1049 
   1050 /* Called at with usb_event_lock held. */
   1051 int
   1052 usb_get_next_event(struct usb_event *ue)
   1053 {
   1054 	struct usb_event_q *ueq;
   1055 
   1056 	KASSERT(mutex_owned(&usb_event_lock));
   1057 
   1058 	if (usb_nevents <= 0)
   1059 		return 0;
   1060 	ueq = SIMPLEQ_FIRST(&usb_events);
   1061 #ifdef DIAGNOSTIC
   1062 	if (ueq == NULL) {
   1063 		printf("usb: usb_nevents got out of sync! %d\n", usb_nevents);
   1064 		usb_nevents = 0;
   1065 		return 0;
   1066 	}
   1067 #endif
   1068 	if (ue)
   1069 		*ue = ueq->ue;
   1070 	SIMPLEQ_REMOVE_HEAD(&usb_events, next);
   1071 	usb_free_event((struct usb_event *)(void *)ueq);
   1072 	usb_nevents--;
   1073 	return 1;
   1074 }
   1075 
   1076 void
   1077 usbd_add_dev_event(int type, struct usbd_device *udev)
   1078 {
   1079 	struct usb_event *ue = usb_alloc_event();
   1080 
   1081 	usbd_fill_deviceinfo(udev, &ue->u.ue_device, false);
   1082 	usb_add_event(type, ue);
   1083 }
   1084 
   1085 void
   1086 usbd_add_drv_event(int type, struct usbd_device *udev, device_t dev)
   1087 {
   1088 	struct usb_event *ue = usb_alloc_event();
   1089 
   1090 	ue->u.ue_driver.ue_cookie = udev->ud_cookie;
   1091 	strncpy(ue->u.ue_driver.ue_devname, device_xname(dev),
   1092 	    sizeof(ue->u.ue_driver.ue_devname));
   1093 	usb_add_event(type, ue);
   1094 }
   1095 
   1096 Static struct usb_event *
   1097 usb_alloc_event(void)
   1098 {
   1099 	/* Yes, this is right; we allocate enough so that we can use it later */
   1100 	return kmem_zalloc(sizeof(struct usb_event_q), KM_SLEEP);
   1101 }
   1102 
   1103 Static void
   1104 usb_free_event(struct usb_event *uep)
   1105 {
   1106 	kmem_free(uep, sizeof(struct usb_event_q));
   1107 }
   1108 
   1109 Static void
   1110 usb_add_event(int type, struct usb_event *uep)
   1111 {
   1112 	struct usb_event_q *ueq;
   1113 	struct timeval thetime;
   1114 
   1115 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
   1116 
   1117 	microtime(&thetime);
   1118 	/* Don't want to wait here with usb_event_lock held */
   1119 	ueq = (struct usb_event_q *)(void *)uep;
   1120 	ueq->ue = *uep;
   1121 	ueq->ue.ue_type = type;
   1122 	TIMEVAL_TO_TIMESPEC(&thetime, &ueq->ue.ue_time);
   1123 
   1124 	mutex_enter(&usb_event_lock);
   1125 	if (++usb_nevents >= USB_MAX_EVENTS) {
   1126 		/* Too many queued events, drop an old one. */
   1127 		DPRINTF("event dropped", 0, 0, 0, 0);
   1128 		(void)usb_get_next_event(0);
   1129 	}
   1130 	SIMPLEQ_INSERT_TAIL(&usb_events, ueq, next);
   1131 	cv_signal(&usb_event_cv);
   1132 	selnotify(&usb_selevent, 0, 0);
   1133 	if (usb_async_proc != NULL) {
   1134 		kpreempt_disable();
   1135 		softint_schedule(usb_async_sih);
   1136 		kpreempt_enable();
   1137 	}
   1138 	mutex_exit(&usb_event_lock);
   1139 }
   1140 
   1141 Static void
   1142 usb_async_intr(void *cookie)
   1143 {
   1144 	proc_t *proc;
   1145 
   1146 	mutex_enter(proc_lock);
   1147 	if ((proc = usb_async_proc) != NULL)
   1148 		psignal(proc, SIGIO);
   1149 	mutex_exit(proc_lock);
   1150 }
   1151 
   1152 Static void
   1153 usb_soft_intr(void *arg)
   1154 {
   1155 	struct usbd_bus *bus = arg;
   1156 
   1157 	mutex_enter(bus->ub_lock);
   1158 	bus->ub_methods->ubm_softint(bus);
   1159 	mutex_exit(bus->ub_lock);
   1160 }
   1161 
   1162 void
   1163 usb_schedsoftintr(struct usbd_bus *bus)
   1164 {
   1165 
   1166 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
   1167 
   1168 	DPRINTFN(10, "polling=%jd", bus->ub_usepolling, 0, 0, 0);
   1169 
   1170 	/* In case the bus never finished setting up. */
   1171 	if (__predict_false(bus->ub_soft == NULL))
   1172 		return;
   1173 
   1174 	if (bus->ub_usepolling) {
   1175 		bus->ub_methods->ubm_softint(bus);
   1176 	} else {
   1177 		kpreempt_disable();
   1178 		softint_schedule(bus->ub_soft);
   1179 		kpreempt_enable();
   1180 	}
   1181 }
   1182 
   1183 int
   1184 usb_activate(device_t self, enum devact act)
   1185 {
   1186 	struct usb_softc *sc = device_private(self);
   1187 
   1188 	switch (act) {
   1189 	case DVACT_DEACTIVATE:
   1190 		sc->sc_dying = 1;
   1191 		return 0;
   1192 	default:
   1193 		return EOPNOTSUPP;
   1194 	}
   1195 }
   1196 
   1197 void
   1198 usb_childdet(device_t self, device_t child)
   1199 {
   1200 	int i;
   1201 	struct usb_softc *sc = device_private(self);
   1202 	struct usbd_device *dev;
   1203 
   1204 	if ((dev = sc->sc_port.up_dev) == NULL || dev->ud_subdevlen == 0)
   1205 		return;
   1206 
   1207 	for (i = 0; i < dev->ud_subdevlen; i++)
   1208 		if (dev->ud_subdevs[i] == child)
   1209 			dev->ud_subdevs[i] = NULL;
   1210 }
   1211 
   1212 int
   1213 usb_detach(device_t self, int flags)
   1214 {
   1215 	struct usb_softc *sc = device_private(self);
   1216 	struct usb_event *ue;
   1217 	int rc;
   1218 
   1219 	USBHIST_FUNC(); USBHIST_CALLED(usbdebug);
   1220 
   1221 	/* Make all devices disconnect. */
   1222 	if (sc->sc_port.up_dev != NULL &&
   1223 	    (rc = usb_disconnect_port(&sc->sc_port, self, flags)) != 0)
   1224 		return rc;
   1225 
   1226 	if (sc->sc_pmf_registered)
   1227 		pmf_device_deregister(self);
   1228 	/* Kill off event thread. */
   1229 	sc->sc_dying = 1;
   1230 	while (sc->sc_event_thread != NULL) {
   1231 		mutex_enter(sc->sc_bus->ub_lock);
   1232 		cv_signal(&sc->sc_bus->ub_needsexplore_cv);
   1233 		cv_timedwait(&sc->sc_bus->ub_needsexplore_cv,
   1234 		    sc->sc_bus->ub_lock, hz * 60);
   1235 		mutex_exit(sc->sc_bus->ub_lock);
   1236 	}
   1237 	DPRINTF("event thread dead", 0, 0, 0, 0);
   1238 
   1239 	if (sc->sc_bus->ub_soft != NULL) {
   1240 		softint_disestablish(sc->sc_bus->ub_soft);
   1241 		sc->sc_bus->ub_soft = NULL;
   1242 	}
   1243 
   1244 	ue = usb_alloc_event();
   1245 	ue->u.ue_ctrlr.ue_bus = device_unit(self);
   1246 	usb_add_event(USB_EVENT_CTRLR_DETACH, ue);
   1247 
   1248 	cv_destroy(&sc->sc_bus->ub_needsexplore_cv);
   1249 
   1250 	return 0;
   1251 }
   1252