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