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