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