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