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