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