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