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