xref: /freebsd/usr.sbin/bhyve/uart_emul.c (revision 13464e4a44fc58490a03bb8bfc7e3c972e9c30b2)
1 /*-
2  * Copyright (c) 2012 NetApp, Inc.
3  * Copyright (c) 2013 Neel Natu <neel@freebsd.org>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  * $FreeBSD$
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include <sys/types.h>
34 #include <dev/ic/ns16550.h>
35 #ifndef WITHOUT_CAPSICUM
36 #include <sys/capsicum.h>
37 #include <capsicum_helpers.h>
38 #endif
39 
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <assert.h>
43 #include <err.h>
44 #include <errno.h>
45 #include <fcntl.h>
46 #include <termios.h>
47 #include <unistd.h>
48 #include <stdbool.h>
49 #include <string.h>
50 #include <pthread.h>
51 #include <sysexits.h>
52 
53 #include "mevent.h"
54 #include "uart_emul.h"
55 
56 #define	COM1_BASE      	0x3F8
57 #define COM1_IRQ	4
58 #define	COM2_BASE      	0x2F8
59 #define COM2_IRQ	3
60 
61 #define	DEFAULT_RCLK	1843200
62 #define	DEFAULT_BAUD	9600
63 
64 #define	FCR_RX_MASK	0xC0
65 
66 #define	MCR_OUT1	0x04
67 #define	MCR_OUT2	0x08
68 
69 #define	MSR_DELTA_MASK	0x0f
70 
71 #ifndef REG_SCR
72 #define REG_SCR		com_scr
73 #endif
74 
75 #define	FIFOSZ	16
76 
77 static bool uart_stdio;		/* stdio in use for i/o */
78 static struct termios tio_stdio_orig;
79 
80 static struct {
81 	int	baseaddr;
82 	int	irq;
83 	bool	inuse;
84 } uart_lres[] = {
85 	{ COM1_BASE, COM1_IRQ, false},
86 	{ COM2_BASE, COM2_IRQ, false},
87 };
88 
89 #define	UART_NLDEVS	(sizeof(uart_lres) / sizeof(uart_lres[0]))
90 
91 struct fifo {
92 	uint8_t	buf[FIFOSZ];
93 	int	rindex;		/* index to read from */
94 	int	windex;		/* index to write to */
95 	int	num;		/* number of characters in the fifo */
96 	int	size;		/* size of the fifo */
97 };
98 
99 struct ttyfd {
100 	bool	opened;
101 	int	fd;		/* tty device file descriptor */
102 	struct termios tio_orig, tio_new;    /* I/O Terminals */
103 };
104 
105 struct uart_softc {
106 	pthread_mutex_t mtx;	/* protects all softc elements */
107 	uint8_t	data;		/* Data register (R/W) */
108 	uint8_t ier;		/* Interrupt enable register (R/W) */
109 	uint8_t lcr;		/* Line control register (R/W) */
110 	uint8_t mcr;		/* Modem control register (R/W) */
111 	uint8_t lsr;		/* Line status register (R/W) */
112 	uint8_t msr;		/* Modem status register (R/W) */
113 	uint8_t fcr;		/* FIFO control register (W) */
114 	uint8_t scr;		/* Scratch register (R/W) */
115 
116 	uint8_t dll;		/* Baudrate divisor latch LSB */
117 	uint8_t dlh;		/* Baudrate divisor latch MSB */
118 
119 	struct fifo rxfifo;
120 	struct mevent *mev;
121 
122 	struct ttyfd tty;
123 	bool	thre_int_pending;	/* THRE interrupt pending */
124 
125 	void	*arg;
126 	uart_intr_func_t intr_assert;
127 	uart_intr_func_t intr_deassert;
128 };
129 
130 static void uart_drain(int fd, enum ev_type ev, void *arg);
131 
132 static void
133 ttyclose(void)
134 {
135 
136 	tcsetattr(STDIN_FILENO, TCSANOW, &tio_stdio_orig);
137 }
138 
139 static void
140 ttyopen(struct ttyfd *tf)
141 {
142 
143 	tcgetattr(tf->fd, &tf->tio_orig);
144 
145 	tf->tio_new = tf->tio_orig;
146 	cfmakeraw(&tf->tio_new);
147 	tf->tio_new.c_cflag |= CLOCAL;
148 	tcsetattr(tf->fd, TCSANOW, &tf->tio_new);
149 
150 	if (tf->fd == STDIN_FILENO) {
151 		tio_stdio_orig = tf->tio_orig;
152 		atexit(ttyclose);
153 	}
154 }
155 
156 static int
157 ttyread(struct ttyfd *tf)
158 {
159 	unsigned char rb;
160 
161 	if (read(tf->fd, &rb, 1) == 1)
162 		return (rb);
163 	else
164 		return (-1);
165 }
166 
167 static void
168 ttywrite(struct ttyfd *tf, unsigned char wb)
169 {
170 
171 	(void)write(tf->fd, &wb, 1);
172 }
173 
174 static void
175 rxfifo_reset(struct uart_softc *sc, int size)
176 {
177 	char flushbuf[32];
178 	struct fifo *fifo;
179 	ssize_t nread;
180 	int error;
181 
182 	fifo = &sc->rxfifo;
183 	bzero(fifo, sizeof(struct fifo));
184 	fifo->size = size;
185 
186 	if (sc->tty.opened) {
187 		/*
188 		 * Flush any unread input from the tty buffer.
189 		 */
190 		while (1) {
191 			nread = read(sc->tty.fd, flushbuf, sizeof(flushbuf));
192 			if (nread != sizeof(flushbuf))
193 				break;
194 		}
195 
196 		/*
197 		 * Enable mevent to trigger when new characters are available
198 		 * on the tty fd.
199 		 */
200 		error = mevent_enable(sc->mev);
201 		assert(error == 0);
202 	}
203 }
204 
205 static int
206 rxfifo_available(struct uart_softc *sc)
207 {
208 	struct fifo *fifo;
209 
210 	fifo = &sc->rxfifo;
211 	return (fifo->num < fifo->size);
212 }
213 
214 static int
215 rxfifo_putchar(struct uart_softc *sc, uint8_t ch)
216 {
217 	struct fifo *fifo;
218 	int error;
219 
220 	fifo = &sc->rxfifo;
221 
222 	if (fifo->num < fifo->size) {
223 		fifo->buf[fifo->windex] = ch;
224 		fifo->windex = (fifo->windex + 1) % fifo->size;
225 		fifo->num++;
226 		if (!rxfifo_available(sc)) {
227 			if (sc->tty.opened) {
228 				/*
229 				 * Disable mevent callback if the FIFO is full.
230 				 */
231 				error = mevent_disable(sc->mev);
232 				assert(error == 0);
233 			}
234 		}
235 		return (0);
236 	} else
237 		return (-1);
238 }
239 
240 static int
241 rxfifo_getchar(struct uart_softc *sc)
242 {
243 	struct fifo *fifo;
244 	int c, error, wasfull;
245 
246 	wasfull = 0;
247 	fifo = &sc->rxfifo;
248 	if (fifo->num > 0) {
249 		if (!rxfifo_available(sc))
250 			wasfull = 1;
251 		c = fifo->buf[fifo->rindex];
252 		fifo->rindex = (fifo->rindex + 1) % fifo->size;
253 		fifo->num--;
254 		if (wasfull) {
255 			if (sc->tty.opened) {
256 				error = mevent_enable(sc->mev);
257 				assert(error == 0);
258 			}
259 		}
260 		return (c);
261 	} else
262 		return (-1);
263 }
264 
265 static int
266 rxfifo_numchars(struct uart_softc *sc)
267 {
268 	struct fifo *fifo = &sc->rxfifo;
269 
270 	return (fifo->num);
271 }
272 
273 static void
274 uart_opentty(struct uart_softc *sc)
275 {
276 
277 	ttyopen(&sc->tty);
278 	sc->mev = mevent_add(sc->tty.fd, EVF_READ, uart_drain, sc);
279 	assert(sc->mev != NULL);
280 }
281 
282 static uint8_t
283 modem_status(uint8_t mcr)
284 {
285 	uint8_t msr;
286 
287 	if (mcr & MCR_LOOPBACK) {
288 		/*
289 		 * In the loopback mode certain bits from the MCR are
290 		 * reflected back into MSR.
291 		 */
292 		msr = 0;
293 		if (mcr & MCR_RTS)
294 			msr |= MSR_CTS;
295 		if (mcr & MCR_DTR)
296 			msr |= MSR_DSR;
297 		if (mcr & MCR_OUT1)
298 			msr |= MSR_RI;
299 		if (mcr & MCR_OUT2)
300 			msr |= MSR_DCD;
301 	} else {
302 		/*
303 		 * Always assert DCD and DSR so tty open doesn't block
304 		 * even if CLOCAL is turned off.
305 		 */
306 		msr = MSR_DCD | MSR_DSR;
307 	}
308 	assert((msr & MSR_DELTA_MASK) == 0);
309 
310 	return (msr);
311 }
312 
313 /*
314  * The IIR returns a prioritized interrupt reason:
315  * - receive data available
316  * - transmit holding register empty
317  * - modem status change
318  *
319  * Return an interrupt reason if one is available.
320  */
321 static int
322 uart_intr_reason(struct uart_softc *sc)
323 {
324 
325 	if ((sc->lsr & LSR_OE) != 0 && (sc->ier & IER_ERLS) != 0)
326 		return (IIR_RLS);
327 	else if (rxfifo_numchars(sc) > 0 && (sc->ier & IER_ERXRDY) != 0)
328 		return (IIR_RXTOUT);
329 	else if (sc->thre_int_pending && (sc->ier & IER_ETXRDY) != 0)
330 		return (IIR_TXRDY);
331 	else if ((sc->msr & MSR_DELTA_MASK) != 0 && (sc->ier & IER_EMSC) != 0)
332 		return (IIR_MLSC);
333 	else
334 		return (IIR_NOPEND);
335 }
336 
337 static void
338 uart_reset(struct uart_softc *sc)
339 {
340 	uint16_t divisor;
341 
342 	divisor = DEFAULT_RCLK / DEFAULT_BAUD / 16;
343 	sc->dll = divisor;
344 	sc->dlh = divisor >> 16;
345 	sc->msr = modem_status(sc->mcr);
346 
347 	rxfifo_reset(sc, 1);	/* no fifo until enabled by software */
348 }
349 
350 /*
351  * Toggle the COM port's intr pin depending on whether or not we have an
352  * interrupt condition to report to the processor.
353  */
354 static void
355 uart_toggle_intr(struct uart_softc *sc)
356 {
357 	uint8_t intr_reason;
358 
359 	intr_reason = uart_intr_reason(sc);
360 
361 	if (intr_reason == IIR_NOPEND)
362 		(*sc->intr_deassert)(sc->arg);
363 	else
364 		(*sc->intr_assert)(sc->arg);
365 }
366 
367 static void
368 uart_drain(int fd, enum ev_type ev, void *arg)
369 {
370 	struct uart_softc *sc;
371 	int ch;
372 
373 	sc = arg;
374 
375 	assert(fd == sc->tty.fd);
376 	assert(ev == EVF_READ);
377 
378 	/*
379 	 * This routine is called in the context of the mevent thread
380 	 * to take out the softc lock to protect against concurrent
381 	 * access from a vCPU i/o exit
382 	 */
383 	pthread_mutex_lock(&sc->mtx);
384 
385 	if ((sc->mcr & MCR_LOOPBACK) != 0) {
386 		(void) ttyread(&sc->tty);
387 	} else {
388 		while (rxfifo_available(sc) &&
389 		       ((ch = ttyread(&sc->tty)) != -1)) {
390 			rxfifo_putchar(sc, ch);
391 		}
392 		uart_toggle_intr(sc);
393 	}
394 
395 	pthread_mutex_unlock(&sc->mtx);
396 }
397 
398 void
399 uart_write(struct uart_softc *sc, int offset, uint8_t value)
400 {
401 	int fifosz;
402 	uint8_t msr;
403 
404 	pthread_mutex_lock(&sc->mtx);
405 
406 	/*
407 	 * Take care of the special case DLAB accesses first
408 	 */
409 	if ((sc->lcr & LCR_DLAB) != 0) {
410 		if (offset == REG_DLL) {
411 			sc->dll = value;
412 			goto done;
413 		}
414 
415 		if (offset == REG_DLH) {
416 			sc->dlh = value;
417 			goto done;
418 		}
419 	}
420 
421         switch (offset) {
422 	case REG_DATA:
423 		if (sc->mcr & MCR_LOOPBACK) {
424 			if (rxfifo_putchar(sc, value) != 0)
425 				sc->lsr |= LSR_OE;
426 		} else if (sc->tty.opened) {
427 			ttywrite(&sc->tty, value);
428 		} /* else drop on floor */
429 		sc->thre_int_pending = true;
430 		break;
431 	case REG_IER:
432 		/*
433 		 * Apply mask so that bits 4-7 are 0
434 		 * Also enables bits 0-3 only if they're 1
435 		 */
436 		sc->ier = value & 0x0F;
437 		break;
438 		case REG_FCR:
439 			/*
440 			 * When moving from FIFO and 16450 mode and vice versa,
441 			 * the FIFO contents are reset.
442 			 */
443 			if ((sc->fcr & FCR_ENABLE) ^ (value & FCR_ENABLE)) {
444 				fifosz = (value & FCR_ENABLE) ? FIFOSZ : 1;
445 				rxfifo_reset(sc, fifosz);
446 			}
447 
448 			/*
449 			 * The FCR_ENABLE bit must be '1' for the programming
450 			 * of other FCR bits to be effective.
451 			 */
452 			if ((value & FCR_ENABLE) == 0) {
453 				sc->fcr = 0;
454 			} else {
455 				if ((value & FCR_RCV_RST) != 0)
456 					rxfifo_reset(sc, FIFOSZ);
457 
458 				sc->fcr = value &
459 					 (FCR_ENABLE | FCR_DMA | FCR_RX_MASK);
460 			}
461 			break;
462 		case REG_LCR:
463 			sc->lcr = value;
464 			break;
465 		case REG_MCR:
466 			/* Apply mask so that bits 5-7 are 0 */
467 			sc->mcr = value & 0x1F;
468 			msr = modem_status(sc->mcr);
469 
470 			/*
471 			 * Detect if there has been any change between the
472 			 * previous and the new value of MSR. If there is
473 			 * then assert the appropriate MSR delta bit.
474 			 */
475 			if ((msr & MSR_CTS) ^ (sc->msr & MSR_CTS))
476 				sc->msr |= MSR_DCTS;
477 			if ((msr & MSR_DSR) ^ (sc->msr & MSR_DSR))
478 				sc->msr |= MSR_DDSR;
479 			if ((msr & MSR_DCD) ^ (sc->msr & MSR_DCD))
480 				sc->msr |= MSR_DDCD;
481 			if ((sc->msr & MSR_RI) != 0 && (msr & MSR_RI) == 0)
482 				sc->msr |= MSR_TERI;
483 
484 			/*
485 			 * Update the value of MSR while retaining the delta
486 			 * bits.
487 			 */
488 			sc->msr &= MSR_DELTA_MASK;
489 			sc->msr |= msr;
490 			break;
491 		case REG_LSR:
492 			/*
493 			 * Line status register is not meant to be written to
494 			 * during normal operation.
495 			 */
496 			break;
497 		case REG_MSR:
498 			/*
499 			 * As far as I can tell MSR is a read-only register.
500 			 */
501 			break;
502 		case REG_SCR:
503 			sc->scr = value;
504 			break;
505 		default:
506 			break;
507 	}
508 
509 done:
510 	uart_toggle_intr(sc);
511 	pthread_mutex_unlock(&sc->mtx);
512 }
513 
514 uint8_t
515 uart_read(struct uart_softc *sc, int offset)
516 {
517 	uint8_t iir, intr_reason, reg;
518 
519 	pthread_mutex_lock(&sc->mtx);
520 
521 	/*
522 	 * Take care of the special case DLAB accesses first
523 	 */
524 	if ((sc->lcr & LCR_DLAB) != 0) {
525 		if (offset == REG_DLL) {
526 			reg = sc->dll;
527 			goto done;
528 		}
529 
530 		if (offset == REG_DLH) {
531 			reg = sc->dlh;
532 			goto done;
533 		}
534 	}
535 
536 	switch (offset) {
537 	case REG_DATA:
538 		reg = rxfifo_getchar(sc);
539 		break;
540 	case REG_IER:
541 		reg = sc->ier;
542 		break;
543 	case REG_IIR:
544 		iir = (sc->fcr & FCR_ENABLE) ? IIR_FIFO_MASK : 0;
545 
546 		intr_reason = uart_intr_reason(sc);
547 
548 		/*
549 		 * Deal with side effects of reading the IIR register
550 		 */
551 		if (intr_reason == IIR_TXRDY)
552 			sc->thre_int_pending = false;
553 
554 		iir |= intr_reason;
555 
556 		reg = iir;
557 		break;
558 	case REG_LCR:
559 		reg = sc->lcr;
560 		break;
561 	case REG_MCR:
562 		reg = sc->mcr;
563 		break;
564 	case REG_LSR:
565 		/* Transmitter is always ready for more data */
566 		sc->lsr |= LSR_TEMT | LSR_THRE;
567 
568 		/* Check for new receive data */
569 		if (rxfifo_numchars(sc) > 0)
570 			sc->lsr |= LSR_RXRDY;
571 		else
572 			sc->lsr &= ~LSR_RXRDY;
573 
574 		reg = sc->lsr;
575 
576 		/* The LSR_OE bit is cleared on LSR read */
577 		sc->lsr &= ~LSR_OE;
578 		break;
579 	case REG_MSR:
580 		/*
581 		 * MSR delta bits are cleared on read
582 		 */
583 		reg = sc->msr;
584 		sc->msr &= ~MSR_DELTA_MASK;
585 		break;
586 	case REG_SCR:
587 		reg = sc->scr;
588 		break;
589 	default:
590 		reg = 0xFF;
591 		break;
592 	}
593 
594 done:
595 	uart_toggle_intr(sc);
596 	pthread_mutex_unlock(&sc->mtx);
597 
598 	return (reg);
599 }
600 
601 int
602 uart_legacy_alloc(int which, int *baseaddr, int *irq)
603 {
604 
605 	if (which < 0 || which >= UART_NLDEVS || uart_lres[which].inuse)
606 		return (-1);
607 
608 	uart_lres[which].inuse = true;
609 	*baseaddr = uart_lres[which].baseaddr;
610 	*irq = uart_lres[which].irq;
611 
612 	return (0);
613 }
614 
615 struct uart_softc *
616 uart_init(uart_intr_func_t intr_assert, uart_intr_func_t intr_deassert,
617     void *arg)
618 {
619 	struct uart_softc *sc;
620 
621 	sc = calloc(1, sizeof(struct uart_softc));
622 
623 	sc->arg = arg;
624 	sc->intr_assert = intr_assert;
625 	sc->intr_deassert = intr_deassert;
626 
627 	pthread_mutex_init(&sc->mtx, NULL);
628 
629 	uart_reset(sc);
630 
631 	return (sc);
632 }
633 
634 static int
635 uart_tty_backend(struct uart_softc *sc, const char *opts)
636 {
637 	int fd;
638 	int retval;
639 
640 	retval = -1;
641 
642 	fd = open(opts, O_RDWR | O_NONBLOCK);
643 	if (fd > 0 && isatty(fd)) {
644 		sc->tty.fd = fd;
645 		sc->tty.opened = true;
646 		retval = 0;
647 	}
648 
649 	return (retval);
650 }
651 
652 int
653 uart_set_backend(struct uart_softc *sc, const char *opts)
654 {
655 	int retval;
656 #ifndef WITHOUT_CAPSICUM
657 	cap_rights_t rights;
658 	cap_ioctl_t cmds[] = { TIOCGETA, TIOCSETA, TIOCGWINSZ };
659 #endif
660 
661 	retval = -1;
662 
663 	if (opts == NULL)
664 		return (0);
665 
666 	if (strcmp("stdio", opts) == 0) {
667 		if (!uart_stdio) {
668 			sc->tty.fd = STDIN_FILENO;
669 			sc->tty.opened = true;
670 			uart_stdio = true;
671 			retval = 0;
672 		}
673 	} else if (uart_tty_backend(sc, opts) == 0) {
674 		retval = 0;
675 	}
676 
677 	/* Make the backend file descriptor non-blocking */
678 	if (retval == 0)
679 		retval = fcntl(sc->tty.fd, F_SETFL, O_NONBLOCK);
680 
681 #ifndef WITHOUT_CAPSICUM
682 	cap_rights_init(&rights, CAP_EVENT, CAP_IOCTL, CAP_READ, CAP_WRITE);
683 	if (cap_rights_limit(sc->tty.fd, &rights) == -1 && errno != ENOSYS)
684 		errx(EX_OSERR, "Unable to apply rights for sandbox");
685 	if (cap_ioctls_limit(sc->tty.fd, cmds, nitems(cmds)) == -1 && errno != ENOSYS)
686 		errx(EX_OSERR, "Unable to apply rights for sandbox");
687 	if (!uart_stdio) {
688 		if (caph_limit_stdin() == -1 && errno != ENOSYS)
689 			errx(EX_OSERR, "Unable to apply rights for sandbox");
690 	}
691 #endif
692 
693 	if (retval == 0)
694 		uart_opentty(sc);
695 
696 	return (retval);
697 }
698