xref: /openbsd-src/sys/dev/usb/usb.c (revision b2ea75c1b17e1a9a339660e7ed45cd24946b230e)
1 /*	$OpenBSD: usb.c,v 1.15 2001/05/03 02:20:34 aaron Exp $	*/
2 /*	$NetBSD: usb.c,v 1.53 2001/01/23 17:04:30 augustss Exp $	*/
3 /*	$FreeBSD: src/sys/dev/usb/usb.c,v 1.20 1999/11/17 22:33:46 n_hibma Exp $	*/
4 
5 /*
6  * Copyright (c) 1998 The NetBSD Foundation, Inc.
7  * All rights reserved.
8  *
9  * This code is derived from software contributed to The NetBSD Foundation
10  * by Lennart Augustsson (lennart@augustsson.net) at
11  * Carlstedt Research & Technology.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. All advertising materials mentioning features or use of this software
22  *    must display the following acknowledgement:
23  *        This product includes software developed by the NetBSD
24  *        Foundation, Inc. and its contributors.
25  * 4. Neither the name of The NetBSD Foundation nor the names of its
26  *    contributors may be used to endorse or promote products derived
27  *    from this software without specific prior written permission.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
30  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
31  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
32  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
33  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
34  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
35  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
36  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
37  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
39  * POSSIBILITY OF SUCH DAMAGE.
40  */
41 
42 /*
43  * USB specifications and other documentation can be found at
44  * http://www.usb.org/developers/data/ and
45  * http://www.usb.org/developers/index.html .
46  */
47 
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/kernel.h>
51 #include <sys/malloc.h>
52 #include <sys/device.h>
53 #include <sys/kthread.h>
54 #include <sys/proc.h>
55 #include <sys/conf.h>
56 #include <sys/poll.h>
57 #include <sys/select.h>
58 #include <sys/vnode.h>
59 #include <sys/signalvar.h>
60 
61 #include <dev/usb/usb.h>
62 #include <dev/usb/usbdi.h>
63 #include <dev/usb/usbdi_util.h>
64 
65 #define USB_DEV_MINOR 255
66 
67 #include <machine/bus.h>
68 
69 #include <dev/usb/usbdivar.h>
70 #include <dev/usb/usb_quirks.h>
71 
72 #ifdef USB_DEBUG
73 #define DPRINTF(x)	if (usbdebug) logprintf x
74 #define DPRINTFN(n,x)	if (usbdebug>(n)) logprintf x
75 int	usbdebug = 0;
76 #ifdef UHCI_DEBUG
77 int	uhcidebug;
78 #endif
79 #ifdef OHCI_DEBUG
80 int	ohcidebug;
81 #endif
82 /*
83  * 0  - do usual exploration
84  * 1  - do not use timeout exploration
85  * >1 - do no exploration
86  */
87 int	usb_noexplore = 0;
88 #else
89 #define DPRINTF(x)
90 #define DPRINTFN(n,x)
91 #endif
92 
93 struct usb_softc {
94 	USBBASEDEVICE	sc_dev;		/* base device */
95 	usbd_bus_handle sc_bus;		/* USB controller */
96 	struct usbd_port sc_port;	/* dummy port for root hub */
97 
98 	TAILQ_HEAD(, usb_task) sc_tasks;
99 	struct proc    *sc_event_thread;
100 
101 	struct usb_task sc_exp_task;
102 
103 	char		sc_dying;
104 };
105 
106 cdev_decl(usb);
107 
108 Static void	usb_discover(void *);
109 Static void	usb_create_event_thread(void *);
110 Static void	usb_event_thread(void *);
111 
112 #define USB_MAX_EVENTS 100
113 struct usb_event_q {
114 	struct usb_event ue;
115 	SIMPLEQ_ENTRY(usb_event_q) next;
116 };
117 Static SIMPLEQ_HEAD(, usb_event_q) usb_events =
118 	SIMPLEQ_HEAD_INITIALIZER(usb_events);
119 Static int usb_nevents = 0;
120 Static struct selinfo usb_selevent;
121 Static struct proc *usb_async_proc;  /* process that wants USB SIGIO */
122 Static int usb_dev_open = 0;
123 Static void usb_add_event(int, struct usb_event *);
124 
125 Static int usb_get_next_event(struct usb_event *);
126 
127 Static const char *usbrev_str[] = USBREV_STR;
128 
129 USB_DECLARE_DRIVER(usb);
130 
131 USB_MATCH(usb)
132 {
133 	DPRINTF(("usbd_match\n"));
134 	return (UMATCH_GENERIC);
135 }
136 
137 USB_ATTACH(usb)
138 {
139 	struct usb_softc *sc = (struct usb_softc *)self;
140 	usbd_device_handle dev;
141 	usbd_status err;
142 	int usbrev;
143 	struct usb_event ue;
144 
145 	DPRINTF(("usbd_attach\n"));
146 
147 	usbd_init();
148 	sc->sc_bus = aux;
149 	sc->sc_bus->usbctl = sc;
150 	sc->sc_port.power = USB_MAX_POWER;
151 	TAILQ_INIT(&sc->sc_tasks);
152 
153 	usb_init_task(&sc->sc_exp_task, usb_discover, sc);
154 
155 	usbrev = sc->sc_bus->usbrev;
156 	printf(": USB revision %s", usbrev_str[usbrev]);
157 	if (usbrev != USBREV_1_0 && usbrev != USBREV_1_1) {
158 		printf(", not supported\n");
159 		USB_ATTACH_ERROR_RETURN;
160 	}
161 	printf("\n");
162 
163 	/* Make sure not to use tsleep() if we are cold booting. */
164 	if (cold)
165 		sc->sc_bus->use_polling++;
166 
167 	ue.u.ue_ctrlr.ue_bus = USBDEVUNIT(sc->sc_dev);
168 	usb_add_event(USB_EVENT_CTRLR_ATTACH, &ue);
169 
170 	err = usbd_new_device(USBDEV(sc->sc_dev), sc->sc_bus, 0, 0, 0,
171 		  &sc->sc_port);
172 	if (!err) {
173 		dev = sc->sc_port.device;
174 		if (dev->hub == NULL) {
175 			sc->sc_dying = 1;
176 			printf("%s: root device is not a hub\n",
177 			       USBDEVNAME(sc->sc_dev));
178 			USB_ATTACH_ERROR_RETURN;
179 		}
180 		sc->sc_bus->root_hub = dev;
181 #if 1
182 		/*
183 		 * Turning this code off will delay attachment of USB devices
184 		 * until the USB event thread is running, which means that
185 		 * the keyboard will not work until after cold boot.
186 		 */
187 		if (cold && (sc->sc_dev.dv_cfdata->cf_flags & 1))
188 			dev->hub->explore(sc->sc_bus->root_hub);
189 #endif
190 	} else {
191 		printf("%s: root hub problem, error=%d\n",
192 		       USBDEVNAME(sc->sc_dev), err);
193 		sc->sc_dying = 1;
194 	}
195 	if (cold)
196 		sc->sc_bus->use_polling--;
197 
198 	config_pending_incr();
199 	usb_kthread_create(usb_create_event_thread, sc);
200 
201 	USB_ATTACH_SUCCESS_RETURN;
202 }
203 
204 #if defined(__NetBSD__) || defined(__OpenBSD__)
205 void
206 usb_create_event_thread(void *arg)
207 {
208 	struct usb_softc *sc = arg;
209 
210 	if (usb_kthread_create1(usb_event_thread, sc, &sc->sc_event_thread,
211 			   "%s", sc->sc_dev.dv_xname)) {
212 		printf("%s: unable to create event thread for\n",
213 		       sc->sc_dev.dv_xname);
214 		panic("usb_create_event_thread");
215 	}
216 }
217 
218 /*
219  * Add a task to be performed by the event thread.  This function can be
220  * called from any context and the task will be executed in a process
221  * context ASAP.
222  */
223 void
224 usb_add_task(usbd_device_handle dev, struct usb_task *task)
225 {
226 	struct usb_softc *sc = dev->bus->usbctl;
227 	int s;
228 
229 	s = splusb();
230 	if (!task->onqueue) {
231 		DPRINTFN(2,("usb_add_task: sc=%p task=%p\n", sc, task));
232 		TAILQ_INSERT_TAIL(&sc->sc_tasks, task, next);
233 		task->onqueue = 1;
234 	} else
235 	DPRINTFN(3,("usb_add_task: sc=%p task=%p on q\n", sc, task));
236 	wakeup(&sc->sc_tasks);
237 	splx(s);
238 }
239 
240 void
241 usb_rem_task(usbd_device_handle dev, struct usb_task *task)
242 {
243 	struct usb_softc *sc = dev->bus->usbctl;
244 	int s;
245 
246 	s = splusb();
247 	if (task->onqueue) {
248 		TAILQ_REMOVE(&sc->sc_tasks, task, next);
249 		task->onqueue = 0;
250 	}
251 	splx(s);
252 }
253 
254 void
255 usb_event_thread(void *arg)
256 {
257 	struct usb_softc *sc = arg;
258 	struct usb_task *task;
259 	int s;
260 
261 	DPRINTF(("usb_event_thread: start\n"));
262 
263 	/* Make sure first discover does something. */
264 	sc->sc_bus->needs_explore = 1;
265 	usb_discover(sc);
266 	config_pending_decr();
267 
268 	while (!sc->sc_dying) {
269 		s = splusb();
270 		task = TAILQ_FIRST(&sc->sc_tasks);
271 		if (task == NULL) {
272 			tsleep(&sc->sc_tasks, PWAIT, "usbevt", 0);
273 			task = TAILQ_FIRST(&sc->sc_tasks);
274 		}
275 		DPRINTFN(2,("usb_event_thread: woke up task=%p\n", task));
276 		if (task != NULL && !sc->sc_dying) {
277 			TAILQ_REMOVE(&sc->sc_tasks, task, next);
278 			task->onqueue = 0;
279 			splx(s);
280 			task->fun(task->arg);
281 		} else
282 			splx(s);
283 	}
284 	sc->sc_event_thread = NULL;
285 
286 	/* In case parent is waiting for us to exit. */
287 	wakeup(sc);
288 
289 	DPRINTF(("usb_event_thread: exit\n"));
290 	kthread_exit(0);
291 }
292 
293 int
294 usbctlprint(void *aux, const char *pnp)
295 {
296 	/* only "usb"es can attach to host controllers */
297 	if (pnp)
298 		printf("usb at %s", pnp);
299 
300 	return (UNCONF);
301 }
302 #endif /* defined(__NetBSD__) || defined(__OpenBSD__) */
303 
304 int
305 usbopen(dev_t dev, int flag, int mode, struct proc *p)
306 {
307 	int unit = minor(dev);
308 	struct usb_softc *sc;
309 
310 	if (unit == USB_DEV_MINOR) {
311 		if (usb_dev_open)
312 			return (EBUSY);
313 		usb_dev_open = 1;
314 		usb_async_proc = 0;
315 		return (0);
316 	}
317 
318 	USB_GET_SC_OPEN(usb, unit, sc);
319 
320 	if (sc->sc_dying)
321 		return (EIO);
322 
323 	return (0);
324 }
325 
326 int
327 usbread(dev_t dev, struct uio *uio, int flag)
328 {
329 	struct usb_event ue;
330 	int s, error, n;
331 
332 	if (minor(dev) != USB_DEV_MINOR)
333 		return (ENXIO);
334 
335 	if (uio->uio_resid != sizeof(struct usb_event))
336 		return (EINVAL);
337 
338 	error = 0;
339 	s = splusb();
340 	for (;;) {
341 		n = usb_get_next_event(&ue);
342 		if (n != 0)
343 			break;
344 		if (flag & IO_NDELAY) {
345 			error = EWOULDBLOCK;
346 			break;
347 		}
348 		error = tsleep(&usb_events, PZERO | PCATCH, "usbrea", 0);
349 		if (error)
350 			break;
351 	}
352 	splx(s);
353 	if (!error)
354 		error = uiomove((void *)&ue, uio->uio_resid, uio);
355 
356 	return (error);
357 }
358 
359 int
360 usbclose(dev_t dev, int flag, int mode, struct proc *p)
361 {
362 	int unit = minor(dev);
363 
364 	if (unit == USB_DEV_MINOR) {
365 		usb_async_proc = 0;
366 		usb_dev_open = 0;
367 	}
368 
369 	return (0);
370 }
371 
372 int
373 usbioctl(dev_t devt, u_long cmd, caddr_t data, int flag, struct proc *p)
374 {
375 	struct usb_softc *sc;
376 	int unit = minor(devt);
377 
378 	if (unit == USB_DEV_MINOR) {
379 		switch (cmd) {
380 		case FIONBIO:
381 			/* All handled in the upper FS layer. */
382 			return (0);
383 
384 		case FIOASYNC:
385 			if (*(int *)data)
386 				usb_async_proc = p;
387 			else
388 				usb_async_proc = 0;
389 			return (0);
390 
391 		default:
392 			return (EINVAL);
393 		}
394 	}
395 
396 	USB_GET_SC(usb, unit, sc);
397 
398 	if (sc->sc_dying)
399 		return (EIO);
400 
401 	switch (cmd) {
402 #ifdef USB_DEBUG
403 	case USB_SETDEBUG:
404 		usbdebug  = ((*(int *)data) & 0x000000ff);
405 #ifdef UHCI_DEBUG
406 		uhcidebug = ((*(int *)data) & 0x0000ff00) >> 8;
407 #endif
408 #ifdef OHCI_DEBUG
409 		ohcidebug = ((*(int *)data) & 0x00ff0000) >> 16;
410 #endif
411 		break;
412 #endif
413 	case USB_REQUEST:
414 	{
415 		struct usb_ctl_request *ur = (void *)data;
416 		int len = UGETW(ur->request.wLength);
417 		struct iovec iov;
418 		struct uio uio;
419 		void *ptr = 0;
420 		int addr = ur->addr;
421 		usbd_status err;
422 		int error = 0;
423 
424 		DPRINTF(("usbioctl: USB_REQUEST addr=%d len=%d\n", addr, len));
425 		if (len < 0 || len > 32768)
426 			return (EINVAL);
427 		if (addr < 0 || addr >= USB_MAX_DEVICES ||
428 		    sc->sc_bus->devices[addr] == 0)
429 			return (EINVAL);
430 		if (len != 0) {
431 			iov.iov_base = (caddr_t)ur->data;
432 			iov.iov_len = len;
433 			uio.uio_iov = &iov;
434 			uio.uio_iovcnt = 1;
435 			uio.uio_resid = len;
436 			uio.uio_offset = 0;
437 			uio.uio_segflg = UIO_USERSPACE;
438 			uio.uio_rw =
439 				ur->request.bmRequestType & UT_READ ?
440 				UIO_READ : UIO_WRITE;
441 			uio.uio_procp = p;
442 			ptr = malloc(len, M_TEMP, M_WAITOK);
443 			if (uio.uio_rw == UIO_WRITE) {
444 				error = uiomove(ptr, len, &uio);
445 				if (error)
446 					goto ret;
447 			}
448 		}
449 		err = usbd_do_request_flags(sc->sc_bus->devices[addr],
450 			  &ur->request, ptr, ur->flags, &ur->actlen);
451 		if (err) {
452 			error = EIO;
453 			goto ret;
454 		}
455 		if (len != 0) {
456 			if (uio.uio_rw == UIO_READ) {
457 				error = uiomove(ptr, len, &uio);
458 				if (error)
459 					goto ret;
460 			}
461 		}
462 	ret:
463 		if (ptr)
464 			free(ptr, M_TEMP);
465 		return (error);
466 	}
467 
468 	case USB_DEVICEINFO:
469 	{
470 		struct usb_device_info *di = (void *)data;
471 		int addr = di->addr;
472 		usbd_device_handle dev;
473 
474 		if (addr < 1 || addr >= USB_MAX_DEVICES)
475 			return (EINVAL);
476 		dev = sc->sc_bus->devices[addr];
477 		if (dev == NULL)
478 			return (ENXIO);
479 		usbd_fill_deviceinfo(dev, di, 1);
480 		break;
481 	}
482 
483 	case USB_DEVICESTATS:
484 		*(struct usb_device_stats *)data = sc->sc_bus->stats;
485 		break;
486 
487 	default:
488 		return (EINVAL);
489 	}
490 	return (0);
491 }
492 
493 int
494 usbpoll(dev_t dev, int events, struct proc *p)
495 {
496 	int revents, mask, s;
497 
498 	if (minor(dev) == USB_DEV_MINOR) {
499 		revents = 0;
500 		mask = POLLIN | POLLRDNORM;
501 
502 		s = splusb();
503 		if (events & mask && usb_nevents > 0)
504 			revents |= events & mask;
505 		if (revents == 0 && events & mask)
506 			selrecord(p, &usb_selevent);
507 		splx(s);
508 
509 		return (revents);
510 	} else {
511 		return (ENXIO);
512 	}
513 }
514 
515 /* Explore device tree from the root. */
516 Static void
517 usb_discover(void *v)
518 {
519 	struct usb_softc *sc = v;
520 
521 	DPRINTFN(2,("usb_discover\n"));
522 #ifdef USB_DEBUG
523 	if (usb_noexplore > 1)
524 		return;
525 #endif
526 	/*
527 	 * We need mutual exclusion while traversing the device tree,
528 	 * but this is guaranteed since this function is only called
529 	 * from the event thread for the controller.
530 	 */
531 	while (sc->sc_bus->needs_explore && !sc->sc_dying) {
532 		sc->sc_bus->needs_explore = 0;
533 		sc->sc_bus->root_hub->hub->explore(sc->sc_bus->root_hub);
534 	}
535 }
536 
537 void
538 usb_needs_explore(usbd_device_handle dev)
539 {
540 	DPRINTFN(2,("usb_needs_explore\n"));
541 	dev->bus->needs_explore = 1;
542 	usb_add_task(dev, &dev->bus->usbctl->sc_exp_task);
543 }
544 
545 /* Called at splusb() */
546 int
547 usb_get_next_event(struct usb_event *ue)
548 {
549 	struct usb_event_q *ueq;
550 
551 	if (usb_nevents <= 0)
552 		return (0);
553 	ueq = SIMPLEQ_FIRST(&usb_events);
554 	*ue = ueq->ue;
555 	SIMPLEQ_REMOVE_HEAD(&usb_events, ueq, next);
556 	free(ueq, M_USBDEV);
557 	usb_nevents--;
558 	return (1);
559 }
560 
561 void
562 usbd_add_dev_event(int type, usbd_device_handle udev)
563 {
564 	struct usb_event ue;
565 
566 	usbd_fill_deviceinfo(udev, &ue.u.ue_device, USB_EVENT_IS_ATTACH(type));
567 	usb_add_event(type, &ue);
568 }
569 
570 void
571 usbd_add_drv_event(int type, usbd_device_handle udev, device_ptr_t dev)
572 {
573 	struct usb_event ue;
574 
575 	ue.u.ue_driver.ue_cookie = udev->cookie;
576 	strncpy(ue.u.ue_driver.ue_devname, USBDEVPTRNAME(dev),
577 	    sizeof ue.u.ue_driver.ue_devname);
578 	usb_add_event(type, &ue);
579 }
580 
581 Static void
582 usb_add_event(int type, struct usb_event *uep)
583 {
584 	struct usb_event_q *ueq;
585 	struct usb_event ue;
586 	struct timeval thetime;
587 	int s;
588 
589 	microtime(&thetime);
590 	/* Don't want to wait here inside splusb() */
591 	ueq = malloc(sizeof *ueq, M_USBDEV, M_WAITOK);
592 	ueq->ue = *uep;
593 	ueq->ue.ue_type = type;
594 	TIMEVAL_TO_TIMESPEC(&thetime, &ueq->ue.ue_time);
595 
596 	s = splusb();
597 	if (++usb_nevents >= USB_MAX_EVENTS) {
598 		/* Too many queued events, drop an old one. */
599 		DPRINTFN(-1,("usb: event dropped\n"));
600 		(void)usb_get_next_event(&ue);
601 	}
602 	SIMPLEQ_INSERT_TAIL(&usb_events, ueq, next);
603 	wakeup(&usb_events);
604 	selwakeup(&usb_selevent);
605 	if (usb_async_proc != NULL)
606 		psignal(usb_async_proc, SIGIO);
607 	splx(s);
608 }
609 void
610 usb_schedsoftintr(struct usbd_bus *bus)
611 {
612 	bus->methods->soft_intr(bus);
613 }
614 
615 int
616 usb_activate(device_ptr_t self, enum devact act)
617 {
618 	struct usb_softc *sc = (struct usb_softc *)self;
619 	usbd_device_handle dev = sc->sc_port.device;
620 	int i, rv = 0;
621 
622 	switch (act) {
623 	case DVACT_ACTIVATE:
624 		return (EOPNOTSUPP);
625 		break;
626 
627 	case DVACT_DEACTIVATE:
628 		sc->sc_dying = 1;
629 		if (dev && dev->cdesc && dev->subdevs) {
630 			for (i = 0; dev->subdevs[i]; i++)
631 				rv |= config_deactivate(dev->subdevs[i]);
632 		}
633 		break;
634 	}
635 	return (rv);
636 }
637 
638 int
639 usb_detach(device_ptr_t self, int flags)
640 {
641 	struct usb_softc *sc = (struct usb_softc *)self;
642 	struct usb_event ue;
643 
644 	DPRINTF(("usb_detach: start\n"));
645 
646 	sc->sc_dying = 1;
647 
648 	/* Make all devices disconnect. */
649 	if (sc->sc_port.device)
650 		usb_disconnect_port(&sc->sc_port, self);
651 
652 	/* Kill off event thread. */
653 	if (sc->sc_event_thread) {
654 		wakeup(&sc->sc_tasks);
655 		if (tsleep(sc, PWAIT, "usbdet", hz * 60))
656 			printf("%s: event thread didn't die\n",
657 			       USBDEVNAME(sc->sc_dev));
658 		DPRINTF(("usb_detach: event thread dead\n"));
659 	}
660 
661 	usbd_finish();
662 
663 	ue.u.ue_ctrlr.ue_bus = USBDEVUNIT(sc->sc_dev);
664 	usb_add_event(USB_EVENT_CTRLR_DETACH, &ue);
665 
666 	return (0);
667 }
668