xref: /openbsd-src/sys/dev/usb/usb.c (revision aa997e528a848ca5596493c2a801bdd6fb26ae61)
1 /*	$OpenBSD: usb.c,v 1.118 2018/02/26 13:06:49 mpi Exp $	*/
2 /*	$NetBSD: usb.c,v 1.77 2003/01/01 00:10:26 thorpej Exp $	*/
3 
4 /*
5  * Copyright (c) 1998, 2002 The NetBSD Foundation, Inc.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by Lennart Augustsson (lennart@augustsson.net) at
10  * Carlstedt Research & Technology.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
23  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
25  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 /*
35  * USB specifications and other documentation can be found at
36  * http://www.usb.org/developers/docs/ and
37  * http://www.usb.org/developers/devclass_docs/
38  */
39 
40 #include "ohci.h"
41 #include "uhci.h"
42 #include "ehci.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/kernel.h>
47 #include <sys/malloc.h>
48 #include <sys/device.h>
49 #include <sys/timeout.h>
50 #include <sys/kthread.h>
51 #include <sys/conf.h>
52 #include <sys/fcntl.h>
53 #include <sys/poll.h>
54 #include <sys/selinfo.h>
55 #include <sys/signalvar.h>
56 #include <sys/time.h>
57 #include <sys/rwlock.h>
58 
59 #include <dev/usb/usb.h>
60 #include <dev/usb/usbdi.h>
61 #include <dev/usb/usbdi_util.h>
62 
63 #include <machine/bus.h>
64 
65 #include <dev/usb/usbdivar.h>
66 #include <dev/usb/usb_mem.h>
67 #include <dev/usb/usbpcap.h>
68 
69 #ifdef USB_DEBUG
70 #define DPRINTF(x)	do { if (usbdebug) printf x; } while (0)
71 #define DPRINTFN(n,x)	do { if (usbdebug>(n)) printf x; } while (0)
72 int	usbdebug = 0;
73 #if defined(UHCI_DEBUG) && NUHCI > 0
74 extern int	uhcidebug;
75 #endif
76 #if defined(OHCI_DEBUG) && NOHCI > 0
77 extern int	ohcidebug;
78 #endif
79 #if defined(EHCI_DEBUG) && NEHCI > 0
80 extern int	ehcidebug;
81 #endif
82 /*
83  * 0  - do usual exploration
84  * !0 - do no exploration
85  */
86 int	usb_noexplore = 0;
87 #else
88 #define DPRINTF(x)
89 #define DPRINTFN(n,x)
90 #endif
91 
92 struct usb_softc {
93 	struct device	 sc_dev;	/* base device */
94 	struct usbd_bus  *sc_bus;	/* USB controller */
95 	struct usbd_port sc_port;	/* dummy port for root hub */
96 	int		 sc_speed;
97 
98 	struct usb_task	 sc_explore_task;
99 
100 	struct timeval	 sc_ptime;
101 };
102 
103 struct rwlock usbpalock;
104 
105 TAILQ_HEAD(, usb_task) usb_abort_tasks;
106 TAILQ_HEAD(, usb_task) usb_explore_tasks;
107 TAILQ_HEAD(, usb_task) usb_generic_tasks;
108 
109 static int usb_nbuses = 0;
110 static int usb_run_tasks, usb_run_abort_tasks;
111 int explore_pending;
112 const char *usbrev_str[] = USBREV_STR;
113 
114 void		 usb_explore(void *);
115 void		 usb_create_task_threads(void *);
116 void		 usb_task_thread(void *);
117 struct proc	*usb_task_thread_proc = NULL;
118 void		 usb_abort_task_thread(void *);
119 struct proc	*usb_abort_task_thread_proc = NULL;
120 
121 void		 usb_fill_di_task(void *);
122 void		 usb_fill_udc_task(void *);
123 void		 usb_fill_udf_task(void *);
124 
125 int		 usb_match(struct device *, void *, void *);
126 void		 usb_attach(struct device *, struct device *, void *);
127 int		 usb_detach(struct device *, int);
128 int		 usb_activate(struct device *, int);
129 
130 int		 usb_attach_roothub(struct usb_softc *);
131 void		 usb_detach_roothub(struct usb_softc *);
132 
133 struct cfdriver usb_cd = {
134 	NULL, "usb", DV_DULL
135 };
136 
137 const struct cfattach usb_ca = {
138 	sizeof(struct usb_softc), usb_match, usb_attach, usb_detach,
139 	usb_activate,
140 };
141 
142 int
143 usb_match(struct device *parent, void *match, void *aux)
144 {
145 	return (1);
146 }
147 
148 void
149 usb_attach(struct device *parent, struct device *self, void *aux)
150 {
151 	struct usb_softc *sc = (struct usb_softc *)self;
152 	int usbrev;
153 
154 	if (usb_nbuses == 0) {
155 		rw_init(&usbpalock, "usbpalock");
156 		TAILQ_INIT(&usb_abort_tasks);
157 		TAILQ_INIT(&usb_explore_tasks);
158 		TAILQ_INIT(&usb_generic_tasks);
159 		usb_run_tasks = usb_run_abort_tasks = 1;
160 		kthread_create_deferred(usb_create_task_threads, NULL);
161 	}
162 	usb_nbuses++;
163 
164 	sc->sc_bus = aux;
165 	sc->sc_bus->usbctl = self;
166 	sc->sc_port.power = USB_MAX_POWER;
167 
168 	usbrev = sc->sc_bus->usbrev;
169 	printf(": USB revision %s", usbrev_str[usbrev]);
170 	switch (usbrev) {
171 	case USBREV_1_0:
172 	case USBREV_1_1:
173 		sc->sc_speed = USB_SPEED_FULL;
174 		break;
175 	case USBREV_2_0:
176 		sc->sc_speed = USB_SPEED_HIGH;
177 		break;
178 	case USBREV_3_0:
179 		sc->sc_speed = USB_SPEED_SUPER;
180 		break;
181 	default:
182 		printf(", not supported\n");
183 		sc->sc_bus->dying = 1;
184 		return;
185 	}
186 	printf("\n");
187 
188 #if NBPFILTER > 0
189 	sc->sc_bus->bpfif = bpfsattach(&sc->sc_bus->bpf, sc->sc_dev.dv_xname,
190 	    DLT_USBPCAP, sizeof(struct usbpcap_pkt_hdr));
191 #endif
192 
193 	/* Make sure not to use tsleep() if we are cold booting. */
194 	if (cold)
195 		sc->sc_bus->use_polling++;
196 
197 	/* Don't let hub interrupts cause explore until ready. */
198 	sc->sc_bus->flags |= USB_BUS_CONFIG_PENDING;
199 
200 	/* explore task */
201 	usb_init_task(&sc->sc_explore_task, usb_explore, sc,
202 	    USB_TASK_TYPE_EXPLORE);
203 
204 	sc->sc_bus->soft = softintr_establish(IPL_SOFTUSB,
205 	    sc->sc_bus->methods->soft_intr, sc->sc_bus);
206 	if (sc->sc_bus->soft == NULL) {
207 		printf("%s: can't register softintr\n", sc->sc_dev.dv_xname);
208 		sc->sc_bus->dying = 1;
209 		return;
210 	}
211 
212 	if (!usb_attach_roothub(sc)) {
213 		struct usbd_device *dev = sc->sc_bus->root_hub;
214 #if 1
215 		/*
216 		 * Turning this code off will delay attachment of USB devices
217 		 * until the USB task thread is running, which means that
218 		 * the keyboard will not work until after cold boot.
219 		 */
220 		if (cold && (sc->sc_dev.dv_cfdata->cf_flags & 1))
221 			dev->hub->explore(sc->sc_bus->root_hub);
222 #endif
223 	}
224 
225 	if (cold)
226 		sc->sc_bus->use_polling--;
227 
228 	if (!sc->sc_bus->dying) {
229 		getmicrouptime(&sc->sc_ptime);
230 		if (sc->sc_bus->usbrev == USBREV_2_0)
231 			explore_pending++;
232 		config_pending_incr();
233 		usb_needs_explore(sc->sc_bus->root_hub, 1);
234 	}
235 }
236 
237 int
238 usb_attach_roothub(struct usb_softc *sc)
239 {
240 	struct usbd_device *dev;
241 
242 	if (usbd_new_device(&sc->sc_dev, sc->sc_bus, 0, sc->sc_speed, 0,
243 	    &sc->sc_port)) {
244 		printf("%s: root hub problem\n", sc->sc_dev.dv_xname);
245 		sc->sc_bus->dying = 1;
246 		return (1);
247 	}
248 
249 	dev = sc->sc_port.device;
250 	if (dev->hub == NULL) {
251 		printf("%s: root device is not a hub\n", sc->sc_dev.dv_xname);
252 		sc->sc_bus->dying = 1;
253 		return (1);
254 	}
255 	sc->sc_bus->root_hub = dev;
256 
257 	return (0);
258 }
259 
260 void
261 usb_detach_roothub(struct usb_softc *sc)
262 {
263 	/*
264 	 * To avoid races with the usb task thread, mark the root hub
265 	 * as disconnecting and schedule an exploration task to detach
266 	 * it.
267 	 */
268 	sc->sc_bus->flags |= USB_BUS_DISCONNECTING;
269 	/*
270 	 * Reset the dying flag in case it has been set by the interrupt
271 	 * handler when unplugging an HC card otherwise the task wont be
272 	 * scheduled.  This is safe since a dead HC should not trigger
273 	 * new interrupt.
274 	 */
275 	sc->sc_bus->dying = 0;
276 	usb_needs_explore(sc->sc_bus->root_hub, 0);
277 
278 	usb_wait_task(sc->sc_bus->root_hub, &sc->sc_explore_task);
279 
280 	sc->sc_bus->root_hub = NULL;
281 }
282 
283 void
284 usb_create_task_threads(void *arg)
285 {
286 	if (kthread_create(usb_abort_task_thread, NULL,
287 	    &usb_abort_task_thread_proc, "usbatsk"))
288 		panic("unable to create usb abort task thread");
289 
290 	if (kthread_create(usb_task_thread, NULL,
291 	    &usb_task_thread_proc, "usbtask"))
292 		panic("unable to create usb task thread");
293 }
294 
295 /*
296  * Add a task to be performed by the task thread.  This function can be
297  * called from any context and the task will be executed in a process
298  * context ASAP.
299  */
300 void
301 usb_add_task(struct usbd_device *dev, struct usb_task *task)
302 {
303 	int s;
304 
305 	/*
306 	 * If the thread detaching ``dev'' is sleeping, waiting
307 	 * for all submitted transfers to finish, we must be able
308 	 * to enqueue abort tasks.  Otherwise timeouts can't give
309 	 * back submitted transfers to the stack.
310 	 */
311 	if (usbd_is_dying(dev) && (task->type != USB_TASK_TYPE_ABORT))
312 		return;
313 
314 	DPRINTFN(2,("%s: task=%p state=%d type=%d\n", __func__, task,
315 	    task->state, task->type));
316 
317 	s = splusb();
318 	if (!(task->state & USB_TASK_STATE_ONQ)) {
319 		switch (task->type) {
320 		case USB_TASK_TYPE_ABORT:
321 			TAILQ_INSERT_TAIL(&usb_abort_tasks, task, next);
322 			break;
323 		case USB_TASK_TYPE_EXPLORE:
324 			TAILQ_INSERT_TAIL(&usb_explore_tasks, task, next);
325 			break;
326 		case USB_TASK_TYPE_GENERIC:
327 			TAILQ_INSERT_TAIL(&usb_generic_tasks, task, next);
328 			break;
329 		}
330 		task->state |= USB_TASK_STATE_ONQ;
331 		task->dev = dev;
332 	}
333 	if (task->type == USB_TASK_TYPE_ABORT)
334 		wakeup(&usb_run_abort_tasks);
335 	else
336 		wakeup(&usb_run_tasks);
337 	splx(s);
338 }
339 
340 void
341 usb_rem_task(struct usbd_device *dev, struct usb_task *task)
342 {
343 	int s;
344 
345 	if (!(task->state & USB_TASK_STATE_ONQ))
346 		return;
347 
348 	DPRINTFN(2,("%s: task=%p state=%d type=%d\n", __func__, task,
349 	    task->state, task->type));
350 
351 	s = splusb();
352 
353 	switch (task->type) {
354 	case USB_TASK_TYPE_ABORT:
355 		TAILQ_REMOVE(&usb_abort_tasks, task, next);
356 		break;
357 	case USB_TASK_TYPE_EXPLORE:
358 		TAILQ_REMOVE(&usb_explore_tasks, task, next);
359 		break;
360 	case USB_TASK_TYPE_GENERIC:
361 		TAILQ_REMOVE(&usb_generic_tasks, task, next);
362 		break;
363 	}
364 	task->state &= ~USB_TASK_STATE_ONQ;
365 	if (task->state == USB_TASK_STATE_NONE)
366 		wakeup(task);
367 
368 	splx(s);
369 }
370 
371 void
372 usb_wait_task(struct usbd_device *dev, struct usb_task *task)
373 {
374 	int s;
375 
376 	DPRINTFN(2,("%s: task=%p state=%d type=%d\n", __func__, task,
377 	    task->state, task->type));
378 
379 	if (task->state == USB_TASK_STATE_NONE)
380 		return;
381 
382 	s = splusb();
383 	while (task->state != USB_TASK_STATE_NONE) {
384 		DPRINTF(("%s: waiting for task to complete\n", __func__));
385 		tsleep(task, PWAIT, "endtask", 0);
386 	}
387 	splx(s);
388 }
389 
390 void
391 usb_rem_wait_task(struct usbd_device *dev, struct usb_task *task)
392 {
393 	usb_rem_task(dev, task);
394 	usb_wait_task(dev, task);
395 }
396 
397 void
398 usb_task_thread(void *arg)
399 {
400 	struct usb_task *task;
401 	int s;
402 
403 	DPRINTF(("usb_task_thread: start\n"));
404 
405 	s = splusb();
406 	while (usb_run_tasks) {
407 		if ((task = TAILQ_FIRST(&usb_explore_tasks)) != NULL)
408 			TAILQ_REMOVE(&usb_explore_tasks, task, next);
409 		else if ((task = TAILQ_FIRST(&usb_generic_tasks)) != NULL)
410 			TAILQ_REMOVE(&usb_generic_tasks, task, next);
411 		else {
412 			tsleep(&usb_run_tasks, PWAIT, "usbtsk", 0);
413 			continue;
414 		}
415 		/*
416 		 * Set the state run bit before clearing the onq bit.
417 		 * This avoids state == none between dequeue and
418 		 * execution, which could cause usb_wait_task() to do
419 		 * the wrong thing.
420 		 */
421 		task->state |= USB_TASK_STATE_RUN;
422 		task->state &= ~USB_TASK_STATE_ONQ;
423 		/* Don't actually execute the task if dying. */
424 		if (!usbd_is_dying(task->dev)) {
425 			splx(s);
426 			task->fun(task->arg);
427 			s = splusb();
428 		}
429 		task->state &= ~USB_TASK_STATE_RUN;
430 		if (task->state == USB_TASK_STATE_NONE)
431 			wakeup(task);
432 	}
433 	splx(s);
434 
435 	kthread_exit(0);
436 }
437 
438 /*
439  * This thread is ONLY for the HCI drivers to be able to abort xfers.
440  * Synchronous xfers sleep the task thread, so the aborts need to happen
441  * in a different thread.
442  */
443 void
444 usb_abort_task_thread(void *arg)
445 {
446 	struct usb_task *task;
447 	int s;
448 
449 	DPRINTF(("usb_xfer_abort_thread: start\n"));
450 
451 	s = splusb();
452 	while (usb_run_abort_tasks) {
453 		if ((task = TAILQ_FIRST(&usb_abort_tasks)) != NULL)
454 			TAILQ_REMOVE(&usb_abort_tasks, task, next);
455 		else {
456 			tsleep(&usb_run_abort_tasks, PWAIT, "usbatsk", 0);
457 			continue;
458 		}
459 		/*
460 		 * Set the state run bit before clearing the onq bit.
461 		 * This avoids state == none between dequeue and
462 		 * execution, which could cause usb_wait_task() to do
463 		 * the wrong thing.
464 		 */
465 		task->state |= USB_TASK_STATE_RUN;
466 		task->state &= ~USB_TASK_STATE_ONQ;
467 		splx(s);
468 		task->fun(task->arg);
469 		s = splusb();
470 		task->state &= ~USB_TASK_STATE_RUN;
471 		if (task->state == USB_TASK_STATE_NONE)
472 			wakeup(task);
473 	}
474 	splx(s);
475 
476 	kthread_exit(0);
477 }
478 
479 int
480 usbctlprint(void *aux, const char *pnp)
481 {
482 	/* only "usb"es can attach to host controllers */
483 	if (pnp)
484 		printf("usb at %s", pnp);
485 
486 	return (UNCONF);
487 }
488 
489 int
490 usbopen(dev_t dev, int flag, int mode, struct proc *p)
491 {
492 	int unit = minor(dev);
493 	struct usb_softc *sc;
494 
495 	if (unit >= usb_cd.cd_ndevs)
496 		return (ENXIO);
497 	sc = usb_cd.cd_devs[unit];
498 	if (sc == NULL)
499 		return (ENXIO);
500 
501 	if (sc->sc_bus->dying)
502 		return (EIO);
503 
504 	return (0);
505 }
506 
507 int
508 usbclose(dev_t dev, int flag, int mode, struct proc *p)
509 {
510 	return (0);
511 }
512 
513 void
514 usb_fill_di_task(void *arg)
515 {
516 	struct usb_device_info *di = (struct usb_device_info *)arg;
517 	struct usb_softc *sc;
518 	struct usbd_device *dev;
519 
520 	/* check that the bus and device are still present */
521 	if (di->udi_bus >= usb_cd.cd_ndevs)
522 		return;
523 	sc = usb_cd.cd_devs[di->udi_bus];
524 	if (sc == NULL)
525 		return;
526 	dev = sc->sc_bus->devices[di->udi_addr];
527 	if (dev == NULL)
528 		return;
529 
530 	usbd_fill_deviceinfo(dev, di, 0);
531 }
532 
533 void
534 usb_fill_udc_task(void *arg)
535 {
536 	struct usb_device_cdesc *udc = (struct usb_device_cdesc *)arg;
537 	struct usb_softc *sc;
538 	struct usbd_device *dev;
539 	int addr = udc->udc_addr;
540 	usb_config_descriptor_t *cdesc;
541 
542 	/* check that the bus and device are still present */
543 	if (udc->udc_bus >= usb_cd.cd_ndevs)
544 		return;
545 	sc = usb_cd.cd_devs[udc->udc_bus];
546 	if (sc == NULL)
547 		return;
548 	dev = sc->sc_bus->devices[udc->udc_addr];
549 	if (dev == NULL)
550 		return;
551 
552 	cdesc = usbd_get_cdesc(sc->sc_bus->devices[addr],
553 	    udc->udc_config_index, 0);
554 	if (cdesc == NULL)
555 		return;
556 	udc->udc_desc = *cdesc;
557 	free(cdesc, M_TEMP, 0);
558 }
559 
560 void
561 usb_fill_udf_task(void *arg)
562 {
563 	struct usb_device_fdesc *udf = (struct usb_device_fdesc *)arg;
564 	struct usb_softc *sc;
565 	struct usbd_device *dev;
566 	int addr = udf->udf_addr;
567 	usb_config_descriptor_t *cdesc;
568 
569 	/* check that the bus and device are still present */
570 	if (udf->udf_bus >= usb_cd.cd_ndevs)
571 		return;
572 	sc = usb_cd.cd_devs[udf->udf_bus];
573 	if (sc == NULL)
574 		return;
575 	dev = sc->sc_bus->devices[udf->udf_addr];
576 	if (dev == NULL)
577 		return;
578 
579 	cdesc = usbd_get_cdesc(sc->sc_bus->devices[addr],
580 	    udf->udf_config_index, &udf->udf_size);
581 	udf->udf_data = (char *)cdesc;
582 }
583 
584 int
585 usbioctl(dev_t devt, u_long cmd, caddr_t data, int flag, struct proc *p)
586 {
587 	struct usb_softc *sc;
588 	int unit = minor(devt);
589 	int error;
590 
591 	sc = usb_cd.cd_devs[unit];
592 
593 	if (sc->sc_bus->dying)
594 		return (EIO);
595 
596 	error = 0;
597 	switch (cmd) {
598 #ifdef USB_DEBUG
599 	case USB_SETDEBUG:
600 		/* only root can access to these debug flags */
601 		if ((error = suser(curproc)) != 0)
602 			return (error);
603 		if (!(flag & FWRITE))
604 			return (EBADF);
605 		usbdebug  = ((*(unsigned int *)data) & 0x000000ff);
606 #if defined(UHCI_DEBUG) && NUHCI > 0
607 		uhcidebug = ((*(unsigned int *)data) & 0x0000ff00) >> 8;
608 #endif
609 #if defined(OHCI_DEBUG) && NOHCI > 0
610 		ohcidebug = ((*(unsigned int *)data) & 0x00ff0000) >> 16;
611 #endif
612 #if defined(EHCI_DEBUG) && NEHCI > 0
613 		ehcidebug = ((*(unsigned int *)data) & 0xff000000) >> 24;
614 #endif
615 		break;
616 #endif /* USB_DEBUG */
617 	case USB_REQUEST:
618 	{
619 		struct usb_ctl_request *ur = (void *)data;
620 		size_t len = UGETW(ur->ucr_request.wLength), mlen;
621 		struct iovec iov;
622 		struct uio uio;
623 		void *ptr = NULL;
624 		int addr = ur->ucr_addr;
625 		usbd_status err;
626 		int error = 0;
627 
628 		if (!(flag & FWRITE))
629 			return (EBADF);
630 
631 		DPRINTF(("usbioctl: USB_REQUEST addr=%d len=%zu\n", addr, len));
632 		/* Avoid requests that would damage the bus integrity. */
633 		if ((ur->ucr_request.bmRequestType == UT_WRITE_DEVICE &&
634 		     ur->ucr_request.bRequest == UR_SET_ADDRESS) ||
635 		    (ur->ucr_request.bmRequestType == UT_WRITE_DEVICE &&
636 		     ur->ucr_request.bRequest == UR_SET_CONFIG) ||
637 		    (ur->ucr_request.bmRequestType == UT_WRITE_INTERFACE &&
638 		     ur->ucr_request.bRequest == UR_SET_INTERFACE))
639 			return (EINVAL);
640 
641 		if (len > 32767)
642 			return (EINVAL);
643 		if (addr < 0 || addr >= USB_MAX_DEVICES)
644 			return (EINVAL);
645 		if (sc->sc_bus->devices[addr] == NULL)
646 			return (ENXIO);
647 		if (len != 0) {
648 			iov.iov_base = (caddr_t)ur->ucr_data;
649 			iov.iov_len = len;
650 			uio.uio_iov = &iov;
651 			uio.uio_iovcnt = 1;
652 			uio.uio_resid = len;
653 			uio.uio_offset = 0;
654 			uio.uio_segflg = UIO_USERSPACE;
655 			uio.uio_rw =
656 				ur->ucr_request.bmRequestType & UT_READ ?
657 				UIO_READ : UIO_WRITE;
658 			uio.uio_procp = p;
659 			if ((ptr = malloc(len, M_TEMP, M_NOWAIT)) == NULL) {
660 				error = ENOMEM;
661 				goto ret;
662 			}
663 			if (uio.uio_rw == UIO_WRITE) {
664 				error = uiomove(ptr, len, &uio);
665 				if (error)
666 					goto ret;
667 			}
668 		}
669 		err = usbd_do_request_flags(sc->sc_bus->devices[addr],
670 			  &ur->ucr_request, ptr, ur->ucr_flags,
671 			  &ur->ucr_actlen, USBD_DEFAULT_TIMEOUT);
672 		if (err) {
673 			error = EIO;
674 			goto ret;
675 		}
676 		/* Only if USBD_SHORT_XFER_OK is set. */
677 		mlen = len;
678 		if (mlen > ur->ucr_actlen)
679 			mlen = ur->ucr_actlen;
680 		if (mlen != 0) {
681 			if (uio.uio_rw == UIO_READ) {
682 				error = uiomove(ptr, mlen, &uio);
683 				if (error)
684 					goto ret;
685 			}
686 		}
687 	ret:
688 		free(ptr, M_TEMP, len);
689 		return (error);
690 	}
691 
692 	case USB_DEVICEINFO:
693 	{
694 		struct usb_device_info *di = (void *)data;
695 		int addr = di->udi_addr;
696 		struct usb_task di_task;
697 		struct usbd_device *dev;
698 
699 		if (addr < 1 || addr >= USB_MAX_DEVICES)
700 			return (EINVAL);
701 
702 		dev = sc->sc_bus->devices[addr];
703 		if (dev == NULL)
704 			return (ENXIO);
705 
706 		di->udi_bus = unit;
707 
708 		/* All devices get a driver, thanks to ugen(4).  If the
709 		 * task ends without adding a driver name, there was an error.
710 		 */
711 		di->udi_devnames[0][0] = '\0';
712 
713 		usb_init_task(&di_task, usb_fill_di_task, di,
714 		    USB_TASK_TYPE_GENERIC);
715 		usb_add_task(sc->sc_bus->root_hub, &di_task);
716 		usb_wait_task(sc->sc_bus->root_hub, &di_task);
717 
718 		if (di->udi_devnames[0][0] == '\0')
719 			return (ENXIO);
720 
721 		break;
722 	}
723 
724 	case USB_DEVICESTATS:
725 		*(struct usb_device_stats *)data = sc->sc_bus->stats;
726 		break;
727 
728 	case USB_DEVICE_GET_DDESC:
729 	{
730 		struct usb_device_ddesc *udd = (struct usb_device_ddesc *)data;
731 		int addr = udd->udd_addr;
732 		struct usbd_device *dev;
733 
734 		if (addr < 1 || addr >= USB_MAX_DEVICES)
735 			return (EINVAL);
736 
737 		dev = sc->sc_bus->devices[addr];
738 		if (dev == NULL)
739 			return (ENXIO);
740 
741 		udd->udd_bus = unit;
742 
743 		udd->udd_desc = *usbd_get_device_descriptor(dev);
744 		break;
745 	}
746 
747 	case USB_DEVICE_GET_CDESC:
748 	{
749 		struct usb_device_cdesc *udc = (struct usb_device_cdesc *)data;
750 		int addr = udc->udc_addr;
751 		struct usb_task udc_task;
752 
753 		if (addr < 1 || addr >= USB_MAX_DEVICES)
754 			return (EINVAL);
755 		if (sc->sc_bus->devices[addr] == NULL)
756 			return (ENXIO);
757 
758 		udc->udc_bus = unit;
759 
760 		udc->udc_desc.bLength = 0;
761 		usb_init_task(&udc_task, usb_fill_udc_task, udc,
762 		    USB_TASK_TYPE_GENERIC);
763 		usb_add_task(sc->sc_bus->root_hub, &udc_task);
764 		usb_wait_task(sc->sc_bus->root_hub, &udc_task);
765 		if (udc->udc_desc.bLength == 0)
766 			return (EINVAL);
767 		break;
768 	}
769 
770 	case USB_DEVICE_GET_FDESC:
771 	{
772 		struct usb_device_fdesc *udf = (struct usb_device_fdesc *)data;
773 		int addr = udf->udf_addr;
774 		struct usb_task udf_task;
775 		struct usb_device_fdesc save_udf;
776 		usb_config_descriptor_t *cdesc;
777 		struct iovec iov;
778 		struct uio uio;
779 		size_t len;
780 		int error;
781 
782 		if (addr < 1 || addr >= USB_MAX_DEVICES)
783 			return (EINVAL);
784 		if (sc->sc_bus->devices[addr] == NULL)
785 			return (ENXIO);
786 
787 		udf->udf_bus = unit;
788 
789 		save_udf = *udf;
790 		udf->udf_data = NULL;
791 		usb_init_task(&udf_task, usb_fill_udf_task, udf,
792 		    USB_TASK_TYPE_GENERIC);
793 		usb_add_task(sc->sc_bus->root_hub, &udf_task);
794 		usb_wait_task(sc->sc_bus->root_hub, &udf_task);
795 		len = udf->udf_size;
796 		cdesc = (usb_config_descriptor_t *)udf->udf_data;
797 		*udf = save_udf;
798 		if (cdesc == NULL)
799 			return (EINVAL);
800 		if (len > udf->udf_size)
801 			len = udf->udf_size;
802 		iov.iov_base = (caddr_t)udf->udf_data;
803 		iov.iov_len = len;
804 		uio.uio_iov = &iov;
805 		uio.uio_iovcnt = 1;
806 		uio.uio_resid = len;
807 		uio.uio_offset = 0;
808 		uio.uio_segflg = UIO_USERSPACE;
809 		uio.uio_rw = UIO_READ;
810 		uio.uio_procp = p;
811 		error = uiomove((void *)cdesc, len, &uio);
812 		free(cdesc, M_TEMP, 0);
813 		return (error);
814 	}
815 
816 	default:
817 		return (EINVAL);
818 	}
819 	return (0);
820 }
821 
822 /*
823  * Explore device tree from the root.  We need mutual exclusion to this
824  * hub while traversing the device tree, but this is guaranteed since this
825  * function is only called from the task thread, with one exception:
826  * usb_attach() calls this function, but there shouldn't be anything else
827  * trying to explore this hub at that time.
828  */
829 void
830 usb_explore(void *v)
831 {
832 	struct usb_softc *sc = v;
833 	struct timeval now, waited;
834 	int pwrdly, waited_ms;
835 
836 	DPRINTFN(2,("%s: %s\n", __func__, sc->sc_dev.dv_xname));
837 #ifdef USB_DEBUG
838 	if (usb_noexplore)
839 		return;
840 #endif
841 
842 	if (sc->sc_bus->dying)
843 		return;
844 
845 	if (sc->sc_bus->flags & USB_BUS_CONFIG_PENDING) {
846 		/*
847 		 * If this is a low/full speed hub and there is a high
848 		 * speed hub that hasn't explored yet, reshedule this
849 		 * task, allowing the high speed explore task to run.
850 		 */
851 		if (sc->sc_bus->usbrev < USBREV_2_0 && explore_pending > 0) {
852 			usb_add_task(sc->sc_bus->root_hub,
853 			    &sc->sc_explore_task);
854 			return;
855 		}
856 
857 		/*
858 		 * Wait for power to stabilize.
859 		 */
860 		getmicrouptime(&now);
861 		timersub(&now, &sc->sc_ptime, &waited);
862 		waited_ms = waited.tv_sec * 1000 + waited.tv_usec / 1000;
863 
864 		pwrdly = sc->sc_bus->root_hub->hub->powerdelay +
865 		    USB_EXTRA_POWER_UP_TIME;
866 		if (pwrdly > waited_ms)
867 			usb_delay_ms(sc->sc_bus, pwrdly - waited_ms);
868 	}
869 
870 	if (sc->sc_bus->flags & USB_BUS_DISCONNECTING) {
871 		/* Prevent new tasks from being scheduled. */
872 		sc->sc_bus->dying = 1;
873 
874 		/* Make all devices disconnect. */
875 		if (sc->sc_port.device != NULL) {
876 			usbd_detach(sc->sc_port.device, (struct device *)sc);
877 			sc->sc_port.device = NULL;
878 		}
879 
880 		sc->sc_bus->flags &= ~USB_BUS_DISCONNECTING;
881 	} else {
882 		sc->sc_bus->root_hub->hub->explore(sc->sc_bus->root_hub);
883 	}
884 
885 	if (sc->sc_bus->flags & USB_BUS_CONFIG_PENDING) {
886 		DPRINTF(("%s: %s: first explore done\n", __func__,
887 		    sc->sc_dev.dv_xname));
888 		if (sc->sc_bus->usbrev == USBREV_2_0 && explore_pending)
889 			explore_pending--;
890 		config_pending_decr();
891 		sc->sc_bus->flags &= ~(USB_BUS_CONFIG_PENDING);
892 	}
893 }
894 
895 void
896 usb_needs_explore(struct usbd_device *dev, int first_explore)
897 {
898 	struct usb_softc *usbctl = (struct usb_softc *)dev->bus->usbctl;
899 
900 	DPRINTFN(3,("%s: %s\n", usbctl->sc_dev.dv_xname, __func__));
901 
902 	if (!first_explore && (dev->bus->flags & USB_BUS_CONFIG_PENDING)) {
903 		DPRINTF(("%s: %s: not exploring before first explore\n",
904 		    __func__, usbctl->sc_dev.dv_xname));
905 		return;
906 	}
907 
908 	usb_add_task(dev, &usbctl->sc_explore_task);
909 }
910 
911 void
912 usb_needs_reattach(struct usbd_device *dev)
913 {
914 	DPRINTFN(2,("usb_needs_reattach\n"));
915 	dev->powersrc->reattach = 1;
916 	usb_needs_explore(dev, 0);
917 }
918 
919 void
920 usb_schedsoftintr(struct usbd_bus *bus)
921 {
922 	DPRINTFN(10,("usb_schedsoftintr: polling=%d\n", bus->use_polling));
923 
924 	if (bus->use_polling) {
925 		bus->methods->soft_intr(bus);
926 	} else {
927 		softintr_schedule(bus->soft);
928 	}
929 }
930 
931 int
932 usb_activate(struct device *self, int act)
933 {
934 	struct usb_softc *sc = (struct usb_softc *)self;
935 	int rv = 0;
936 
937 	switch (act) {
938 	case DVACT_QUIESCE:
939 		if (sc->sc_bus->root_hub != NULL)
940 			usb_detach_roothub(sc);
941 		break;
942 	case DVACT_RESUME:
943 		sc->sc_bus->dying = 0;
944 
945 		/*
946 		 * Make sure the root hub is present before interrupts
947 		 * get enabled.   As long as the bus is in polling mode
948 		 * it is safe to call usbd_new_device() now since root
949 		 * hub transfers do not need to sleep.
950 		 */
951 		sc->sc_bus->use_polling++;
952 		if (!usb_attach_roothub(sc))
953 			usb_needs_explore(sc->sc_bus->root_hub, 0);
954 		sc->sc_bus->use_polling--;
955 		break;
956 	default:
957 		rv = config_activate_children(self, act);
958 		break;
959 	}
960 	return (rv);
961 }
962 
963 int
964 usb_detach(struct device *self, int flags)
965 {
966 	struct usb_softc *sc = (struct usb_softc *)self;
967 
968 	if (sc->sc_bus->root_hub != NULL) {
969 		usb_detach_roothub(sc);
970 
971 		if (--usb_nbuses == 0) {
972 			usb_run_tasks = usb_run_abort_tasks = 0;
973 			wakeup(&usb_run_abort_tasks);
974 			wakeup(&usb_run_tasks);
975 		}
976 	}
977 
978 	if (sc->sc_bus->soft != NULL) {
979 		softintr_disestablish(sc->sc_bus->soft);
980 		sc->sc_bus->soft = NULL;
981 	}
982 
983 #if NBPFILTER > 0
984 	bpfsdetach(sc->sc_bus->bpfif);
985 #endif
986 	return (0);
987 }
988 
989 void
990 usb_tap(struct usbd_bus *bus, struct usbd_xfer *xfer, uint8_t dir)
991 {
992 #if NBPFILTER > 0
993 	struct usb_softc *sc = (struct usb_softc *)bus->usbctl;
994 	usb_endpoint_descriptor_t *ed = xfer->pipe->endpoint->edesc;
995 	union {
996 		struct usbpcap_ctl_hdr		uch;
997 		struct usbpcap_iso_hdr_full	uih;
998 	} h;
999 	struct usbpcap_pkt_hdr *uph = &h.uch.uch_hdr;
1000 	uint32_t nframes, offset;
1001 	unsigned int bpfdir;
1002 	void *data = NULL;
1003 	size_t flen;
1004 	caddr_t bpf;
1005 	int i;
1006 
1007 	bpf = bus->bpf;
1008 	if (bpf == NULL)
1009 		return;
1010 
1011 	switch (UE_GET_XFERTYPE(ed->bmAttributes)) {
1012 	case UE_CONTROL:
1013 		/* Control transfer headers include an extra byte */
1014 		uph->uph_hlen = htole16(sizeof(struct usbpcap_ctl_hdr));
1015 		uph->uph_xfertype = USBPCAP_TRANSFER_CONTROL;
1016 		break;
1017 	case UE_ISOCHRONOUS:
1018 		offset = 0;
1019 		nframes = xfer->nframes;
1020 #ifdef DIAGNOSTIC
1021 		if (nframes > _USBPCAP_MAX_ISOFRAMES) {
1022 			printf("%s: too many frames: %d > %d\n", __func__,
1023 			    xfer->nframes, _USBPCAP_MAX_ISOFRAMES);
1024 			nframes = _USBPCAP_MAX_ISOFRAMES;
1025 		}
1026 #endif
1027 		/* Isochronous transfer headers include space for one frame */
1028 		flen = (nframes - 1) * sizeof(struct usbpcap_iso_pkt);
1029 		uph->uph_hlen = htole16(sizeof(struct usbpcap_iso_hdr) + flen);
1030 		uph->uph_xfertype = USBPCAP_TRANSFER_ISOCHRONOUS;
1031 		h.uih.uih_startframe = 0; /* not yet used */
1032 		h.uih.uih_nframes = nframes;
1033 		h.uih.uih_errors = 0; /* we don't have per-frame error */
1034 		for (i = 0; i < nframes; i++) {
1035 			h.uih.uih_frames[i].uip_offset = offset;
1036 			h.uih.uih_frames[i].uip_length = xfer->frlengths[i];
1037 			/* See above, we don't have per-frame error */
1038 			h.uih.uih_frames[i].uip_status = 0;
1039 			offset += xfer->frlengths[i];
1040 		}
1041 		break;
1042 	case UE_BULK:
1043 		uph->uph_hlen = htole16(sizeof(*uph));
1044 		uph->uph_xfertype = USBPCAP_TRANSFER_BULK;
1045 		break;
1046 	case UE_INTERRUPT:
1047 		uph->uph_hlen = htole16(sizeof(*uph));
1048 		uph->uph_xfertype = USBPCAP_TRANSFER_INTERRUPT;
1049 		break;
1050 	default:
1051 		return;
1052 	}
1053 
1054 	uph->uph_id = 0; /* not yet used */
1055 	uph->uph_status = htole32(xfer->status);
1056 	uph->uph_function = 0; /* not yet used */
1057 	uph->uph_bus = htole32(sc->sc_dev.dv_unit);
1058 	uph->uph_devaddr = htole16(xfer->device->address);
1059 	uph->uph_epaddr = ed->bEndpointAddress;
1060 	uph->uph_info = 0;
1061 
1062 	/* Outgoing control requests start with a STAGE dump. */
1063 	if ((xfer->rqflags & URQ_REQUEST) && (dir == USBTAP_DIR_OUT)) {
1064 		h.uch.uch_stage = USBPCAP_CONTROL_STAGE_SETUP;
1065 		uph->uph_dlen = sizeof(usb_device_request_t);
1066 		bpf_tap_hdr(bpf, uph, uph->uph_hlen, &xfer->request,
1067 		    uph->uph_dlen, BPF_DIRECTION_OUT);
1068 	}
1069 
1070 	if (dir == USBTAP_DIR_OUT) {
1071 		bpfdir = BPF_DIRECTION_OUT;
1072 		if (!usbd_xfer_isread(xfer)) {
1073 			data = KERNADDR(&xfer->dmabuf, 0);
1074 			uph->uph_dlen = xfer->length;
1075 			if (xfer->rqflags & URQ_REQUEST)
1076 				h.uch.uch_stage = USBPCAP_CONTROL_STAGE_DATA;
1077 		} else {
1078 			data = NULL;
1079 			uph->uph_dlen = 0;
1080 			if (xfer->rqflags & URQ_REQUEST)
1081 				h.uch.uch_stage = USBPCAP_CONTROL_STAGE_STATUS;
1082 		}
1083 	} else { /* USBTAP_DIR_IN */
1084 		bpfdir = BPF_DIRECTION_IN;
1085 		uph->uph_info = USBPCAP_INFO_DIRECTION_IN;
1086 		if (usbd_xfer_isread(xfer)) {
1087 			data = KERNADDR(&xfer->dmabuf, 0);
1088 			uph->uph_dlen = xfer->actlen;
1089 			if (xfer->rqflags & URQ_REQUEST)
1090 				h.uch.uch_stage = USBPCAP_CONTROL_STAGE_DATA;
1091 		} else {
1092 			data = NULL;
1093 			uph->uph_dlen = 0;
1094 			if (xfer->rqflags & URQ_REQUEST)
1095 				h.uch.uch_stage = USBPCAP_CONTROL_STAGE_STATUS;
1096 		}
1097 	}
1098 
1099 	/* Dump bulk/intr/iso data, ctrl DATA or STATUS stage. */
1100 	bpf_tap_hdr(bpf, uph, uph->uph_hlen, data, uph->uph_dlen, bpfdir);
1101 
1102 	/* Incoming control requests with DATA need a STATUS stage. */
1103 	if ((xfer->rqflags & URQ_REQUEST) && (dir == USBTAP_DIR_IN) &&
1104 	    (h.uch.uch_stage == USBPCAP_CONTROL_STAGE_DATA)) {
1105 		h.uch.uch_stage = USBPCAP_CONTROL_STAGE_STATUS;
1106 		uph->uph_dlen = 0;
1107 		bpf_tap_hdr(bpf, uph, uph->uph_hlen, NULL, 0, BPF_DIRECTION_IN);
1108 	}
1109 #endif
1110 }
1111