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