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