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