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