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