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