xref: /illumos-gate/usr/src/cmd/bhyve/uart_emul.c (revision 154972aff898a787b38af3bab5b8d754b5a42447)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2012 NetApp, Inc.
5  * Copyright (c) 2013 Neel Natu <neel@freebsd.org>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $FreeBSD$
30  *
31  */
32 /*
33  * This file and its contents are supplied under the terms of the
34  * Common Development and Distribution License ("CDDL"), version 1.0.
35  * You may only use this file in accordance with the terms of version
36  * 1.0 of the CDDL.
37  *
38  * A full copy of the text of the CDDL should have accompanied this
39  * source.  A copy of the CDDL is also available via the Internet at
40  * http://www.illumos.org/license/CDDL.
41  *
42  * Copyright 2015 Pluribus Networks Inc.
43  * Copyright 2018 Joyent, Inc.
44  */
45 
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
48 
49 #include <sys/types.h>
50 #include <dev/ic/ns16550.h>
51 #ifndef WITHOUT_CAPSICUM
52 #include <sys/capsicum.h>
53 #include <capsicum_helpers.h>
54 #endif
55 
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <assert.h>
59 #include <err.h>
60 #include <errno.h>
61 #include <fcntl.h>
62 #include <termios.h>
63 #include <unistd.h>
64 #include <stdbool.h>
65 #include <string.h>
66 #include <pthread.h>
67 #include <sysexits.h>
68 #ifndef	__FreeBSD__
69 #include <sys/socket.h>
70 #endif
71 
72 #include "mevent.h"
73 #include "uart_emul.h"
74 #include "debug.h"
75 
76 #define	COM1_BASE	0x3F8
77 #define	COM1_IRQ	4
78 #define	COM2_BASE	0x2F8
79 #define	COM2_IRQ	3
80 
81 #define	DEFAULT_RCLK	1843200
82 #define	DEFAULT_BAUD	9600
83 
84 #define	FCR_RX_MASK	0xC0
85 
86 #define	MCR_OUT1	0x04
87 #define	MCR_OUT2	0x08
88 
89 #define	MSR_DELTA_MASK	0x0f
90 
91 #ifndef REG_SCR
92 #define	REG_SCR		com_scr
93 #endif
94 
95 #define	FIFOSZ	16
96 
97 static bool uart_stdio;		/* stdio in use for i/o */
98 static struct termios tio_stdio_orig;
99 
100 static struct {
101 	int	baseaddr;
102 	int	irq;
103 	bool	inuse;
104 } uart_lres[] = {
105 	{ COM1_BASE, COM1_IRQ, false},
106 	{ COM2_BASE, COM2_IRQ, false},
107 };
108 
109 #define	UART_NLDEVS	(sizeof(uart_lres) / sizeof(uart_lres[0]))
110 
111 struct fifo {
112 	uint8_t	buf[FIFOSZ];
113 	int	rindex;		/* index to read from */
114 	int	windex;		/* index to write to */
115 	int	num;		/* number of characters in the fifo */
116 	int	size;		/* size of the fifo */
117 };
118 
119 struct ttyfd {
120 	bool	opened;
121 	int	rfd;		/* fd for reading */
122 	int	wfd;		/* fd for writing, may be == rfd */
123 };
124 
125 struct uart_softc {
126 	pthread_mutex_t mtx;	/* protects all softc elements */
127 	uint8_t	data;		/* Data register (R/W) */
128 	uint8_t ier;		/* Interrupt enable register (R/W) */
129 	uint8_t lcr;		/* Line control register (R/W) */
130 	uint8_t mcr;		/* Modem control register (R/W) */
131 	uint8_t lsr;		/* Line status register (R/W) */
132 	uint8_t msr;		/* Modem status register (R/W) */
133 	uint8_t fcr;		/* FIFO control register (W) */
134 	uint8_t scr;		/* Scratch register (R/W) */
135 
136 	uint8_t dll;		/* Baudrate divisor latch LSB */
137 	uint8_t dlh;		/* Baudrate divisor latch MSB */
138 
139 	struct fifo rxfifo;
140 	struct mevent *mev;
141 
142 	struct ttyfd tty;
143 #ifndef	__FreeBSD__
144 	bool	sock;
145 	struct {
146 		int	clifd;		/* console client unix domain socket */
147 		int	servfd;		/* console server unix domain socket */
148 		struct mevent *servmev;	/* mevent for server socket */
149 	} usc_sock;
150 #endif
151 
152 	bool	thre_int_pending;	/* THRE interrupt pending */
153 
154 	void	*arg;
155 	uart_intr_func_t intr_assert;
156 	uart_intr_func_t intr_deassert;
157 };
158 
159 static void uart_drain(int fd, enum ev_type ev, void *arg);
160 
161 static void
162 ttyclose(void)
163 {
164 
165 	tcsetattr(STDIN_FILENO, TCSANOW, &tio_stdio_orig);
166 }
167 
168 static void
169 ttyopen(struct ttyfd *tf)
170 {
171 	struct termios orig, new;
172 
173 	tcgetattr(tf->rfd, &orig);
174 	new = orig;
175 	cfmakeraw(&new);
176 	new.c_cflag |= CLOCAL;
177 	tcsetattr(tf->rfd, TCSANOW, &new);
178 	if (uart_stdio) {
179 		tio_stdio_orig = orig;
180 		atexit(ttyclose);
181 	}
182 	raw_stdio = 1;
183 }
184 
185 static int
186 ttyread(struct ttyfd *tf)
187 {
188 	unsigned char rb;
189 
190 	if (read(tf->rfd, &rb, 1) == 1)
191 		return (rb);
192 	else
193 		return (-1);
194 }
195 
196 static void
197 ttywrite(struct ttyfd *tf, unsigned char wb)
198 {
199 
200 	(void)write(tf->wfd, &wb, 1);
201 }
202 
203 #ifndef	__FreeBSD__
204 static void
205 sockwrite(struct uart_softc *sc, unsigned char wb)
206 {
207 	(void) write(sc->usc_sock.clifd, &wb, 1);
208 }
209 #endif
210 
211 static void
212 rxfifo_reset(struct uart_softc *sc, int size)
213 {
214 	char flushbuf[32];
215 	struct fifo *fifo;
216 	ssize_t nread;
217 	int error;
218 
219 	fifo = &sc->rxfifo;
220 	bzero(fifo, sizeof(struct fifo));
221 	fifo->size = size;
222 
223 	if (sc->tty.opened) {
224 		/*
225 		 * Flush any unread input from the tty buffer.
226 		 */
227 		while (1) {
228 			nread = read(sc->tty.rfd, flushbuf, sizeof(flushbuf));
229 			if (nread != sizeof(flushbuf))
230 				break;
231 		}
232 
233 		/*
234 		 * Enable mevent to trigger when new characters are available
235 		 * on the tty fd.
236 		 */
237 		error = mevent_enable(sc->mev);
238 		assert(error == 0);
239 	}
240 #ifndef	__FreeBSD__
241 	if (sc->sock && sc->usc_sock.clifd != -1) {
242 		/* Flush any unread input from the socket buffer. */
243 		do {
244 			nread = read(sc->usc_sock.clifd, flushbuf,
245 			    sizeof (flushbuf));
246 		} while (nread == sizeof (flushbuf));
247 
248 		/* Enable mevent to trigger when new data available on sock */
249 		error = mevent_enable(sc->mev);
250 		assert(error == 0);
251 	}
252 #endif /* __FreeBSD__ */
253 }
254 
255 static int
256 rxfifo_available(struct uart_softc *sc)
257 {
258 	struct fifo *fifo;
259 
260 	fifo = &sc->rxfifo;
261 	return (fifo->num < fifo->size);
262 }
263 
264 static int
265 rxfifo_putchar(struct uart_softc *sc, uint8_t ch)
266 {
267 	struct fifo *fifo;
268 	int error;
269 
270 	fifo = &sc->rxfifo;
271 
272 	if (fifo->num < fifo->size) {
273 		fifo->buf[fifo->windex] = ch;
274 		fifo->windex = (fifo->windex + 1) % fifo->size;
275 		fifo->num++;
276 		if (!rxfifo_available(sc)) {
277 			if (sc->tty.opened) {
278 				/*
279 				 * Disable mevent callback if the FIFO is full.
280 				 */
281 				error = mevent_disable(sc->mev);
282 				assert(error == 0);
283 			}
284 #ifndef	__FreeBSD__
285 			if (sc->sock && sc->usc_sock.clifd != -1) {
286 				/*
287 				 * Disable mevent callback if the FIFO is full.
288 				 */
289 				error = mevent_disable(sc->mev);
290 				assert(error == 0);
291 			}
292 #endif /* __FreeBSD__ */
293 		}
294 		return (0);
295 	} else
296 		return (-1);
297 }
298 
299 static int
300 rxfifo_getchar(struct uart_softc *sc)
301 {
302 	struct fifo *fifo;
303 	int c, error, wasfull;
304 
305 	wasfull = 0;
306 	fifo = &sc->rxfifo;
307 	if (fifo->num > 0) {
308 		if (!rxfifo_available(sc))
309 			wasfull = 1;
310 		c = fifo->buf[fifo->rindex];
311 		fifo->rindex = (fifo->rindex + 1) % fifo->size;
312 		fifo->num--;
313 		if (wasfull) {
314 			if (sc->tty.opened) {
315 				error = mevent_enable(sc->mev);
316 				assert(error == 0);
317 			}
318 #ifndef	__FreeBSD__
319 			if (sc->sock && sc->usc_sock.clifd != -1) {
320 				error = mevent_enable(sc->mev);
321 				assert(error == 0);
322 			}
323 #endif /* __FreeBSD__ */
324 		}
325 		return (c);
326 	} else
327 		return (-1);
328 }
329 
330 static int
331 rxfifo_numchars(struct uart_softc *sc)
332 {
333 	struct fifo *fifo = &sc->rxfifo;
334 
335 	return (fifo->num);
336 }
337 
338 static void
339 uart_opentty(struct uart_softc *sc)
340 {
341 
342 	ttyopen(&sc->tty);
343 	sc->mev = mevent_add(sc->tty.rfd, EVF_READ, uart_drain, sc);
344 	assert(sc->mev != NULL);
345 }
346 
347 static uint8_t
348 modem_status(uint8_t mcr)
349 {
350 	uint8_t msr;
351 
352 	if (mcr & MCR_LOOPBACK) {
353 		/*
354 		 * In the loopback mode certain bits from the MCR are
355 		 * reflected back into MSR.
356 		 */
357 		msr = 0;
358 		if (mcr & MCR_RTS)
359 			msr |= MSR_CTS;
360 		if (mcr & MCR_DTR)
361 			msr |= MSR_DSR;
362 		if (mcr & MCR_OUT1)
363 			msr |= MSR_RI;
364 		if (mcr & MCR_OUT2)
365 			msr |= MSR_DCD;
366 	} else {
367 		/*
368 		 * Always assert DCD and DSR so tty open doesn't block
369 		 * even if CLOCAL is turned off.
370 		 */
371 		msr = MSR_DCD | MSR_DSR;
372 	}
373 	assert((msr & MSR_DELTA_MASK) == 0);
374 
375 	return (msr);
376 }
377 
378 /*
379  * The IIR returns a prioritized interrupt reason:
380  * - receive data available
381  * - transmit holding register empty
382  * - modem status change
383  *
384  * Return an interrupt reason if one is available.
385  */
386 static int
387 uart_intr_reason(struct uart_softc *sc)
388 {
389 
390 	if ((sc->lsr & LSR_OE) != 0 && (sc->ier & IER_ERLS) != 0)
391 		return (IIR_RLS);
392 	else if (rxfifo_numchars(sc) > 0 && (sc->ier & IER_ERXRDY) != 0)
393 		return (IIR_RXTOUT);
394 	else if (sc->thre_int_pending && (sc->ier & IER_ETXRDY) != 0)
395 		return (IIR_TXRDY);
396 	else if ((sc->msr & MSR_DELTA_MASK) != 0 && (sc->ier & IER_EMSC) != 0)
397 		return (IIR_MLSC);
398 	else
399 		return (IIR_NOPEND);
400 }
401 
402 static void
403 uart_reset(struct uart_softc *sc)
404 {
405 	uint16_t divisor;
406 
407 	divisor = DEFAULT_RCLK / DEFAULT_BAUD / 16;
408 	sc->dll = divisor;
409 #ifndef __FreeBSD__
410 	sc->dlh = 0;
411 #else
412 	sc->dlh = divisor >> 16;
413 #endif
414 	sc->msr = modem_status(sc->mcr);
415 
416 	rxfifo_reset(sc, 1);	/* no fifo until enabled by software */
417 }
418 
419 /*
420  * Toggle the COM port's intr pin depending on whether or not we have an
421  * interrupt condition to report to the processor.
422  */
423 static void
424 uart_toggle_intr(struct uart_softc *sc)
425 {
426 	uint8_t intr_reason;
427 
428 	intr_reason = uart_intr_reason(sc);
429 
430 	if (intr_reason == IIR_NOPEND)
431 		(*sc->intr_deassert)(sc->arg);
432 	else
433 		(*sc->intr_assert)(sc->arg);
434 }
435 
436 static void
437 uart_drain(int fd, enum ev_type ev, void *arg)
438 {
439 	struct uart_softc *sc;
440 	int ch;
441 
442 	sc = arg;
443 
444 	assert(fd == sc->tty.rfd);
445 	assert(ev == EVF_READ);
446 
447 	/*
448 	 * This routine is called in the context of the mevent thread
449 	 * to take out the softc lock to protect against concurrent
450 	 * access from a vCPU i/o exit
451 	 */
452 	pthread_mutex_lock(&sc->mtx);
453 
454 	if ((sc->mcr & MCR_LOOPBACK) != 0) {
455 		(void) ttyread(&sc->tty);
456 	} else {
457 		while (rxfifo_available(sc) &&
458 		       ((ch = ttyread(&sc->tty)) != -1)) {
459 			rxfifo_putchar(sc, ch);
460 		}
461 		uart_toggle_intr(sc);
462 	}
463 
464 	pthread_mutex_unlock(&sc->mtx);
465 }
466 
467 void
468 uart_write(struct uart_softc *sc, int offset, uint8_t value)
469 {
470 	int fifosz;
471 	uint8_t msr;
472 
473 	pthread_mutex_lock(&sc->mtx);
474 
475 	/*
476 	 * Take care of the special case DLAB accesses first
477 	 */
478 	if ((sc->lcr & LCR_DLAB) != 0) {
479 		if (offset == REG_DLL) {
480 			sc->dll = value;
481 			goto done;
482 		}
483 
484 		if (offset == REG_DLH) {
485 			sc->dlh = value;
486 			goto done;
487 		}
488 	}
489 
490         switch (offset) {
491 	case REG_DATA:
492 		if (sc->mcr & MCR_LOOPBACK) {
493 			if (rxfifo_putchar(sc, value) != 0)
494 				sc->lsr |= LSR_OE;
495 		} else if (sc->tty.opened) {
496 			ttywrite(&sc->tty, value);
497 #ifndef	__FreeBSD__
498 		} else if (sc->sock) {
499 			sockwrite(sc, value);
500 #endif
501 		} /* else drop on floor */
502 		sc->thre_int_pending = true;
503 		break;
504 	case REG_IER:
505 		/* Set pending when IER_ETXRDY is raised (edge-triggered). */
506 		if ((sc->ier & IER_ETXRDY) == 0 && (value & IER_ETXRDY) != 0)
507 			sc->thre_int_pending = true;
508 		/*
509 		 * Apply mask so that bits 4-7 are 0
510 		 * Also enables bits 0-3 only if they're 1
511 		 */
512 		sc->ier = value & 0x0F;
513 		break;
514 	case REG_FCR:
515 		/*
516 		 * When moving from FIFO and 16450 mode and vice versa,
517 		 * the FIFO contents are reset.
518 		 */
519 		if ((sc->fcr & FCR_ENABLE) ^ (value & FCR_ENABLE)) {
520 			fifosz = (value & FCR_ENABLE) ? FIFOSZ : 1;
521 			rxfifo_reset(sc, fifosz);
522 		}
523 
524 		/*
525 		 * The FCR_ENABLE bit must be '1' for the programming
526 		 * of other FCR bits to be effective.
527 		 */
528 		if ((value & FCR_ENABLE) == 0) {
529 			sc->fcr = 0;
530 		} else {
531 			if ((value & FCR_RCV_RST) != 0)
532 				rxfifo_reset(sc, FIFOSZ);
533 
534 			sc->fcr = value &
535 				 (FCR_ENABLE | FCR_DMA | FCR_RX_MASK);
536 		}
537 		break;
538 	case REG_LCR:
539 		sc->lcr = value;
540 		break;
541 	case REG_MCR:
542 		/* Apply mask so that bits 5-7 are 0 */
543 		sc->mcr = value & 0x1F;
544 		msr = modem_status(sc->mcr);
545 
546 		/*
547 		 * Detect if there has been any change between the
548 		 * previous and the new value of MSR. If there is
549 		 * then assert the appropriate MSR delta bit.
550 		 */
551 		if ((msr & MSR_CTS) ^ (sc->msr & MSR_CTS))
552 			sc->msr |= MSR_DCTS;
553 		if ((msr & MSR_DSR) ^ (sc->msr & MSR_DSR))
554 			sc->msr |= MSR_DDSR;
555 		if ((msr & MSR_DCD) ^ (sc->msr & MSR_DCD))
556 			sc->msr |= MSR_DDCD;
557 		if ((sc->msr & MSR_RI) != 0 && (msr & MSR_RI) == 0)
558 			sc->msr |= MSR_TERI;
559 
560 		/*
561 		 * Update the value of MSR while retaining the delta
562 		 * bits.
563 		 */
564 		sc->msr &= MSR_DELTA_MASK;
565 		sc->msr |= msr;
566 		break;
567 	case REG_LSR:
568 		/*
569 		 * Line status register is not meant to be written to
570 		 * during normal operation.
571 		 */
572 		break;
573 	case REG_MSR:
574 		/*
575 		 * As far as I can tell MSR is a read-only register.
576 		 */
577 		break;
578 	case REG_SCR:
579 		sc->scr = value;
580 		break;
581 	default:
582 		break;
583 	}
584 
585 done:
586 	uart_toggle_intr(sc);
587 	pthread_mutex_unlock(&sc->mtx);
588 }
589 
590 uint8_t
591 uart_read(struct uart_softc *sc, int offset)
592 {
593 	uint8_t iir, intr_reason, reg;
594 
595 	pthread_mutex_lock(&sc->mtx);
596 
597 	/*
598 	 * Take care of the special case DLAB accesses first
599 	 */
600 	if ((sc->lcr & LCR_DLAB) != 0) {
601 		if (offset == REG_DLL) {
602 			reg = sc->dll;
603 			goto done;
604 		}
605 
606 		if (offset == REG_DLH) {
607 			reg = sc->dlh;
608 			goto done;
609 		}
610 	}
611 
612 	switch (offset) {
613 	case REG_DATA:
614 		reg = rxfifo_getchar(sc);
615 		break;
616 	case REG_IER:
617 		reg = sc->ier;
618 		break;
619 	case REG_IIR:
620 		iir = (sc->fcr & FCR_ENABLE) ? IIR_FIFO_MASK : 0;
621 
622 		intr_reason = uart_intr_reason(sc);
623 
624 		/*
625 		 * Deal with side effects of reading the IIR register
626 		 */
627 		if (intr_reason == IIR_TXRDY)
628 			sc->thre_int_pending = false;
629 
630 		iir |= intr_reason;
631 
632 		reg = iir;
633 		break;
634 	case REG_LCR:
635 		reg = sc->lcr;
636 		break;
637 	case REG_MCR:
638 		reg = sc->mcr;
639 		break;
640 	case REG_LSR:
641 		/* Transmitter is always ready for more data */
642 		sc->lsr |= LSR_TEMT | LSR_THRE;
643 
644 		/* Check for new receive data */
645 		if (rxfifo_numchars(sc) > 0)
646 			sc->lsr |= LSR_RXRDY;
647 		else
648 			sc->lsr &= ~LSR_RXRDY;
649 
650 		reg = sc->lsr;
651 
652 		/* The LSR_OE bit is cleared on LSR read */
653 		sc->lsr &= ~LSR_OE;
654 		break;
655 	case REG_MSR:
656 		/*
657 		 * MSR delta bits are cleared on read
658 		 */
659 		reg = sc->msr;
660 		sc->msr &= ~MSR_DELTA_MASK;
661 		break;
662 	case REG_SCR:
663 		reg = sc->scr;
664 		break;
665 	default:
666 		reg = 0xFF;
667 		break;
668 	}
669 
670 done:
671 	uart_toggle_intr(sc);
672 	pthread_mutex_unlock(&sc->mtx);
673 
674 	return (reg);
675 }
676 
677 #ifndef	__FreeBSD__
678 static void
679 uart_sock_drain(int fd, enum ev_type ev, void *arg)
680 {
681 	struct uart_softc *sc = arg;
682 	char ch;
683 
684 	/*
685 	 * Take the softc lock to protect against concurrent
686 	 * access from a vCPU i/o exit
687 	 */
688 	pthread_mutex_lock(&sc->mtx);
689 
690 	if ((sc->mcr & MCR_LOOPBACK) != 0) {
691 		(void) read(sc->usc_sock.clifd, &ch, 1);
692 	} else {
693 		bool err_close = false;
694 
695 		while (rxfifo_available(sc)) {
696 			int res;
697 
698 			res = read(sc->usc_sock.clifd, &ch, 1);
699 			if (res == 0) {
700 				err_close = true;
701 				break;
702 			} else if (res == -1) {
703 				if (errno != EAGAIN && errno != EINTR) {
704 					err_close = true;
705 				}
706 				break;
707 			}
708 
709 			rxfifo_putchar(sc, ch);
710 		}
711 		uart_toggle_intr(sc);
712 
713 		if (err_close) {
714 			(void) fprintf(stderr, "uart: closing client conn\n");
715 			(void) shutdown(sc->usc_sock.clifd, SHUT_RDWR);
716 			mevent_delete_close(sc->mev);
717 			sc->mev = NULL;
718 			sc->usc_sock.clifd = -1;
719 		}
720 	}
721 
722 	pthread_mutex_unlock(&sc->mtx);
723 }
724 
725 static void
726 uart_sock_accept(int fd, enum ev_type ev, void *arg)
727 {
728 	struct uart_softc *sc = arg;
729 	int connfd;
730 
731 	connfd = accept(sc->usc_sock.servfd, NULL, NULL);
732 	if (connfd == -1) {
733 		return;
734 	}
735 
736 	/*
737 	 * Do client connection management under protection of the softc lock
738 	 * to avoid racing with concurrent UART events.
739 	 */
740 	pthread_mutex_lock(&sc->mtx);
741 
742 	if (sc->usc_sock.clifd != -1) {
743 		/* we're already handling a client */
744 		(void) fprintf(stderr, "uart: unexpected client conn\n");
745 		(void) shutdown(connfd, SHUT_RDWR);
746 		(void) close(connfd);
747 	} else {
748 		if (fcntl(connfd, F_SETFL, O_NONBLOCK) < 0) {
749 			perror("uart: fcntl(O_NONBLOCK)");
750 			(void) shutdown(connfd, SHUT_RDWR);
751 			(void) close(connfd);
752 		} else {
753 			sc->usc_sock.clifd = connfd;
754 			sc->mev = mevent_add(sc->usc_sock.clifd, EVF_READ,
755 			    uart_sock_drain, sc);
756 		}
757 	}
758 
759 	pthread_mutex_unlock(&sc->mtx);
760 }
761 
762 static int
763 init_sock(const char *path)
764 {
765 	int servfd;
766 	struct sockaddr_un servaddr;
767 
768 	bzero(&servaddr, sizeof (servaddr));
769 	servaddr.sun_family = AF_UNIX;
770 
771 	if (strlcpy(servaddr.sun_path, path, sizeof (servaddr.sun_path)) >=
772 	    sizeof (servaddr.sun_path)) {
773 		(void) fprintf(stderr, "uart: path '%s' too long\n",
774 		    path);
775 		return (-1);
776 	}
777 
778 	if ((servfd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
779 		(void) fprintf(stderr, "uart: socket() error - %s\n",
780 		    strerror(errno));
781 		return (-1);
782 	}
783 	(void) unlink(servaddr.sun_path);
784 
785 	if (bind(servfd, (struct sockaddr *)&servaddr,
786 	    sizeof (servaddr)) == -1) {
787 		(void) fprintf(stderr, "uart: bind() error - %s\n",
788 		    strerror(errno));
789 		goto out;
790         }
791 
792         if (listen(servfd, 1) == -1) {
793 		(void) fprintf(stderr, "uart: listen() error - %s\n",
794 		    strerror(errno));
795 		goto out;
796         }
797         return (servfd);
798 
799 out:
800 	(void) unlink(servaddr.sun_path);
801         (void) close(servfd);
802         return (-1);
803 }
804 #endif /* not __FreeBSD__ */
805 
806 int
807 uart_legacy_alloc(int which, int *baseaddr, int *irq)
808 {
809 
810 	if (which < 0 || which >= UART_NLDEVS || uart_lres[which].inuse)
811 		return (-1);
812 
813 	uart_lres[which].inuse = true;
814 	*baseaddr = uart_lres[which].baseaddr;
815 	*irq = uart_lres[which].irq;
816 
817 	return (0);
818 }
819 
820 struct uart_softc *
821 uart_init(uart_intr_func_t intr_assert, uart_intr_func_t intr_deassert,
822     void *arg)
823 {
824 	struct uart_softc *sc;
825 
826 	sc = calloc(1, sizeof(struct uart_softc));
827 
828 	sc->arg = arg;
829 	sc->intr_assert = intr_assert;
830 	sc->intr_deassert = intr_deassert;
831 
832 	pthread_mutex_init(&sc->mtx, NULL);
833 
834 	uart_reset(sc);
835 
836 	return (sc);
837 }
838 
839 #ifndef __FreeBSD__
840 static int
841 uart_sock_backend(struct uart_softc *sc, const char *inopts)
842 {
843 	char *opts;
844 	char *opt;
845 	char *nextopt;
846 	char *path = NULL;
847 
848 	if (strncmp(inopts, "socket,", 7) != 0) {
849 		return (-1);
850 	}
851 	if ((opts = strdup(inopts + 7)) == NULL) {
852 		return (-1);
853 	}
854 
855 	nextopt = opts;
856 	for (opt = strsep(&nextopt, ","); opt != NULL;
857 	    opt = strsep(&nextopt, ",")) {
858 		if (path == NULL && *opt == '/') {
859 			path = opt;
860 			continue;
861 		}
862 		/*
863 		 * XXX check for server and client options here.  For now,
864 		 * everything is a server
865 		 */
866 		free(opts);
867 		return (-1);
868 	}
869 
870 	sc->usc_sock.clifd = -1;
871 	if ((sc->usc_sock.servfd = init_sock(path)) == -1) {
872 		free(opts);
873 		return (-1);
874 	}
875 	sc->sock = true;
876 	sc->tty.rfd = sc->tty.wfd = -1;
877 	sc->usc_sock.servmev = mevent_add(sc->usc_sock.servfd, EVF_READ,
878 	    uart_sock_accept, sc);
879 	assert(sc->usc_sock.servmev != NULL);
880 
881 	return (0);
882 }
883 #endif /* not __FreeBSD__ */
884 
885 static int
886 uart_stdio_backend(struct uart_softc *sc)
887 {
888 #ifndef WITHOUT_CAPSICUM
889 	cap_rights_t rights;
890 	cap_ioctl_t cmds[] = { TIOCGETA, TIOCSETA, TIOCGWINSZ };
891 #endif
892 
893 	if (uart_stdio)
894 		return (-1);
895 
896 	sc->tty.rfd = STDIN_FILENO;
897 	sc->tty.wfd = STDOUT_FILENO;
898 	sc->tty.opened = true;
899 
900 	if (fcntl(sc->tty.rfd, F_SETFL, O_NONBLOCK) != 0)
901 		return (-1);
902 	if (fcntl(sc->tty.wfd, F_SETFL, O_NONBLOCK) != 0)
903 		return (-1);
904 
905 #ifndef WITHOUT_CAPSICUM
906 	cap_rights_init(&rights, CAP_EVENT, CAP_IOCTL, CAP_READ);
907 	if (caph_rights_limit(sc->tty.rfd, &rights) == -1)
908 		errx(EX_OSERR, "Unable to apply rights for sandbox");
909 	if (caph_ioctls_limit(sc->tty.rfd, cmds, nitems(cmds)) == -1)
910 		errx(EX_OSERR, "Unable to apply rights for sandbox");
911 #endif
912 
913 	uart_stdio = true;
914 
915 	return (0);
916 }
917 
918 static int
919 uart_tty_backend(struct uart_softc *sc, const char *opts)
920 {
921 #ifndef WITHOUT_CAPSICUM
922 	cap_rights_t rights;
923 	cap_ioctl_t cmds[] = { TIOCGETA, TIOCSETA, TIOCGWINSZ };
924 #endif
925 	int fd;
926 
927 	fd = open(opts, O_RDWR | O_NONBLOCK);
928 	if (fd < 0)
929 		return (-1);
930 
931 	if (!isatty(fd)) {
932 		close(fd);
933 		return (-1);
934 	}
935 
936 	sc->tty.rfd = sc->tty.wfd = fd;
937 	sc->tty.opened = true;
938 
939 #ifndef WITHOUT_CAPSICUM
940 	cap_rights_init(&rights, CAP_EVENT, CAP_IOCTL, CAP_READ, CAP_WRITE);
941 	if (caph_rights_limit(fd, &rights) == -1)
942 		errx(EX_OSERR, "Unable to apply rights for sandbox");
943 	if (caph_ioctls_limit(fd, cmds, nitems(cmds)) == -1)
944 		errx(EX_OSERR, "Unable to apply rights for sandbox");
945 #endif
946 
947 	return (0);
948 }
949 
950 int
951 uart_set_backend(struct uart_softc *sc, const char *opts)
952 {
953 	int retval;
954 
955 	if (opts == NULL)
956 		return (0);
957 
958 #ifndef __FreeBSD__
959 	if (strncmp("socket,", opts, 7) == 0)
960 		return (uart_sock_backend(sc, opts));
961 #endif
962 	if (strcmp("stdio", opts) == 0)
963 		retval = uart_stdio_backend(sc);
964 	else
965 		retval = uart_tty_backend(sc, opts);
966 	if (retval == 0)
967 		uart_opentty(sc);
968 
969 	return (retval);
970 }
971