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