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