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