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