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