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