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