Home | History | Annotate | Line # | Download | only in kern
tty.c revision 1.275.2.3
      1 /*	$NetBSD: tty.c,v 1.275.2.3 2018/09/04 02:21:58 pgoyette Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2008 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     17  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     18  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     19  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     26  * POSSIBILITY OF SUCH DAMAGE.
     27  */
     28 
     29 /*-
     30  * Copyright (c) 1982, 1986, 1990, 1991, 1993
     31  *	The Regents of the University of California.  All rights reserved.
     32  * (c) UNIX System Laboratories, Inc.
     33  * All or some portions of this file are derived from material licensed
     34  * to the University of California by American Telephone and Telegraph
     35  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     36  * the permission of UNIX System Laboratories, Inc.
     37  *
     38  * Redistribution and use in source and binary forms, with or without
     39  * modification, are permitted provided that the following conditions
     40  * are met:
     41  * 1. Redistributions of source code must retain the above copyright
     42  *    notice, this list of conditions and the following disclaimer.
     43  * 2. Redistributions in binary form must reproduce the above copyright
     44  *    notice, this list of conditions and the following disclaimer in the
     45  *    documentation and/or other materials provided with the distribution.
     46  * 3. Neither the name of the University nor the names of its contributors
     47  *    may be used to endorse or promote products derived from this software
     48  *    without specific prior written permission.
     49  *
     50  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     53  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     60  * SUCH DAMAGE.
     61  *
     62  *	@(#)tty.c	8.13 (Berkeley) 1/9/95
     63  */
     64 
     65 #include <sys/cdefs.h>
     66 __KERNEL_RCSID(0, "$NetBSD: tty.c,v 1.275.2.3 2018/09/04 02:21:58 pgoyette Exp $");
     67 
     68 #ifdef _KERNEL_OPT
     69 #include "opt_compat_netbsd.h"
     70 #endif
     71 
     72 #define TTY_ALLOW_PRIVATE
     73 
     74 #include <sys/param.h>
     75 #include <sys/systm.h>
     76 #include <sys/ioctl.h>
     77 #include <sys/proc.h>
     78 #define	TTYDEFCHARS
     79 #include <sys/tty.h>
     80 #undef	TTYDEFCHARS
     81 #include <sys/file.h>
     82 #include <sys/conf.h>
     83 #include <sys/cpu.h>
     84 #include <sys/dkstat.h>
     85 #include <sys/uio.h>
     86 #include <sys/kernel.h>
     87 #include <sys/vnode.h>
     88 #include <sys/syslog.h>
     89 #include <sys/kmem.h>
     90 #include <sys/signalvar.h>
     91 #include <sys/resourcevar.h>
     92 #include <sys/poll.h>
     93 #include <sys/kprintf.h>
     94 #include <sys/namei.h>
     95 #include <sys/sysctl.h>
     96 #include <sys/kauth.h>
     97 #include <sys/intr.h>
     98 #include <sys/ioctl_compat.h>
     99 #include <sys/module.h>
    100 #include <sys/bitops.h>
    101 
    102 #ifdef COMPAT_60
    103 #include <compat/sys/ttycom.h>
    104 #endif /* COMPAT_60 */
    105 
    106 static int	ttnread(struct tty *);
    107 static void	ttyblock(struct tty *);
    108 static void	ttyecho(int, struct tty *);
    109 static void	ttyrubo(struct tty *, int);
    110 static void	ttyprintf_nolock(struct tty *, const char *fmt, ...)
    111     __printflike(2, 3);
    112 static int	proc_compare_wrapper(struct proc *, struct proc *);
    113 static void	ttysigintr(void *);
    114 
    115 /* Symbolic sleep message strings. */
    116 const char	ttclos[] = "ttycls";
    117 const char	ttopen[] = "ttyopn";
    118 const char	ttybg[] = "ttybg";
    119 const char	ttyin[] = "ttyin";
    120 const char	ttyout[] = "ttyout";
    121 
    122 /*
    123  * Used to determine whether we still have a connection.  This is true in
    124  * one of 3 cases:
    125  * 1) We have carrier.
    126  * 2) It's a locally attached terminal, and we are therefore ignoring carrier.
    127  * 3) We're using a flow control mechanism that overloads the carrier signal.
    128  */
    129 #define	CONNECTED(tp)	(ISSET(tp->t_state, TS_CARR_ON) ||	\
    130 			 ISSET(tp->t_cflag, CLOCAL | MDMBUF))
    131 
    132 /*
    133  * Table with character classes and parity. The 8th bit indicates parity,
    134  * the 7th bit indicates the character is an alphameric or underscore (for
    135  * ALTWERASE), and the low 6 bits indicate delay type.  If the low 6 bits
    136  * are 0 then the character needs no special processing on output; classes
    137  * other than 0 might be translated or (not currently) require delays.
    138  */
    139 #define	E	0x00	/* Even parity. */
    140 #define	O	0x80	/* Odd parity. */
    141 #define	PARITY(c)	(char_type[c] & O)
    142 
    143 #define	ALPHA	0x40	/* Alpha or underscore. */
    144 #define	ISALPHA(c)	(char_type[(c) & TTY_CHARMASK] & ALPHA)
    145 
    146 #define	CCLASSMASK	0x3f
    147 #define	CCLASS(c)	(char_type[c] & CCLASSMASK)
    148 
    149 #define	BS	BACKSPACE
    150 #define	CC	CONTROL
    151 #define	CR	RETURN
    152 #define	NA	ORDINARY | ALPHA
    153 #define	NL	NEWLINE
    154 #define	NO	ORDINARY
    155 #define	TB	TAB
    156 #define	VT	VTAB
    157 
    158 unsigned char const char_type[] = {
    159 	E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC,	/* nul - bel */
    160 	O|BS, E|TB, E|NL, O|CC, E|VT, O|CR, O|CC, E|CC,	/* bs - si */
    161 	O|CC, E|CC, E|CC, O|CC, E|CC, O|CC, O|CC, E|CC,	/* dle - etb */
    162 	E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC,	/* can - us */
    163 	O|NO, E|NO, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO,	/* sp - ' */
    164 	E|NO, O|NO, O|NO, E|NO, O|NO, E|NO, E|NO, O|NO,	/* ( - / */
    165 	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA,	/* 0 - 7 */
    166 	O|NA, E|NA, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO,	/* 8 - ? */
    167 	O|NO, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA,	/* @ - G */
    168 	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA,	/* H - O */
    169 	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA,	/* P - W */
    170 	O|NA, E|NA, E|NA, O|NO, E|NO, O|NO, O|NO, O|NA,	/* X - _ */
    171 	E|NO, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA,	/* ` - g */
    172 	O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA,	/* h - o */
    173 	O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA,	/* p - w */
    174 	E|NA, O|NA, O|NA, E|NO, O|NO, E|NO, E|NO, O|CC,	/* x - del */
    175 	/*
    176 	 * Meta chars; should be settable per character set;
    177 	 * for now, treat them all as normal characters.
    178 	 */
    179 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    180 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    181 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    182 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    183 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    184 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    185 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    186 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    187 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    188 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    189 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    190 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    191 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    192 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    193 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    194 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    195 };
    196 #undef	BS
    197 #undef	CC
    198 #undef	CR
    199 #undef	NA
    200 #undef	NL
    201 #undef	NO
    202 #undef	TB
    203 #undef	VT
    204 
    205 static struct ttylist_head tty_sigqueue = TAILQ_HEAD_INITIALIZER(tty_sigqueue);
    206 static void *tty_sigsih;
    207 
    208 struct ttylist_head ttylist = TAILQ_HEAD_INITIALIZER(ttylist);
    209 int tty_count;
    210 kmutex_t tty_lock;
    211 krwlock_t ttcompat_lock;
    212 int (*vec_compat_ttioctl_60)(dev_t, u_long, void *, int, struct lwp *) = NULL;
    213 int (*vec_compat_ptmioctl_60)(dev_t, u_long, void *, int, struct lwp *) =
    214     stub_compat_ptmioctl_60;
    215 
    216 struct ptm_pty *ptm = NULL;
    217 
    218 uint64_t tk_cancc;
    219 uint64_t tk_nin;
    220 uint64_t tk_nout;
    221 uint64_t tk_rawcc;
    222 
    223 static kauth_listener_t tty_listener;
    224 
    225 #define	TTY_MINQSIZE	0x00400
    226 #define	TTY_MAXQSIZE	0x10000
    227 int tty_qsize = TTY_MINQSIZE;
    228 
    229 static int
    230 tty_get_qsize(int *qsize, int newsize)
    231 {
    232 	newsize = 1 << ilog2(newsize);	/* Make it a power of two */
    233 
    234 	if (newsize < TTY_MINQSIZE || newsize > TTY_MAXQSIZE)
    235 		return EINVAL;
    236 
    237 	*qsize = newsize;
    238 	return 0;
    239 }
    240 
    241 static int
    242 tty_set_qsize(struct tty *tp, int newsize)
    243 {
    244 	struct clist rawq, canq, outq;
    245 	struct clist orawq, ocanq, ooutq;
    246 
    247 	clalloc(&rawq, newsize, 1);
    248 	clalloc(&canq, newsize, 1);
    249 	clalloc(&outq, newsize, 0);
    250 
    251 	mutex_spin_enter(&tty_lock);
    252 
    253 	if (tp->t_outq.c_cc != 0) {
    254 		mutex_spin_exit(&tty_lock);
    255 		clfree(&rawq);
    256 		clfree(&canq);
    257 		clfree(&outq);
    258 		return EBUSY;
    259 	}
    260 
    261 	orawq = tp->t_rawq;
    262 	ocanq = tp->t_canq;
    263 	ooutq = tp->t_outq;
    264 
    265 	tp->t_qsize = newsize;
    266 	tp->t_rawq = rawq;
    267 	tp->t_canq = canq;
    268 	tp->t_outq = outq;
    269 
    270 	ttsetwater(tp);
    271 
    272 	mutex_spin_exit(&tty_lock);
    273 
    274 	clfree(&orawq);
    275 	clfree(&ocanq);
    276 	clfree(&ooutq);
    277 
    278 	return 0;
    279 }
    280 
    281 static int
    282 sysctl_kern_tty_qsize(SYSCTLFN_ARGS)
    283 {
    284 	int newsize;
    285 	int error;
    286 	struct sysctlnode node;
    287 	node = *rnode;
    288 	node.sysctl_data = &newsize;
    289 
    290 	newsize = tty_qsize;
    291 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    292 	if (error || newp == NULL)
    293 		return error;
    294 
    295 
    296 	return tty_get_qsize(&tty_qsize, newsize);
    297 }
    298 
    299 static void
    300 sysctl_kern_tty_setup(void)
    301 {
    302 	const struct sysctlnode *rnode, *cnode;
    303 	struct sysctllog *kern_tkstat_sysctllog, *kern_tty_sysctllog;
    304 
    305 	kern_tkstat_sysctllog = NULL;
    306 	sysctl_createv(&kern_tkstat_sysctllog, 0, NULL, NULL,
    307 		       CTLFLAG_PERMANENT,
    308 		       CTLTYPE_NODE, "tkstat",
    309 		       SYSCTL_DESCR("Number of characters sent and received "
    310 				    "on ttys"),
    311 		       NULL, 0, NULL, 0,
    312 		       CTL_KERN, KERN_TKSTAT, CTL_EOL);
    313 
    314 	sysctl_createv(&kern_tkstat_sysctllog, 0, NULL, NULL,
    315 		       CTLFLAG_PERMANENT,
    316 		       CTLTYPE_QUAD, "nin",
    317 		       SYSCTL_DESCR("Total number of tty input characters"),
    318 		       NULL, 0, &tk_nin, 0,
    319 		       CTL_KERN, KERN_TKSTAT, KERN_TKSTAT_NIN, CTL_EOL);
    320 	sysctl_createv(&kern_tkstat_sysctllog, 0, NULL, NULL,
    321 		       CTLFLAG_PERMANENT,
    322 		       CTLTYPE_QUAD, "nout",
    323 		       SYSCTL_DESCR("Total number of tty output characters"),
    324 		       NULL, 0, &tk_nout, 0,
    325 		       CTL_KERN, KERN_TKSTAT, KERN_TKSTAT_NOUT, CTL_EOL);
    326 	sysctl_createv(&kern_tkstat_sysctllog, 0, NULL, NULL,
    327 		       CTLFLAG_PERMANENT,
    328 		       CTLTYPE_QUAD, "cancc",
    329 		       SYSCTL_DESCR("Number of canonical tty input characters"),
    330 		       NULL, 0, &tk_cancc, 0,
    331 		       CTL_KERN, KERN_TKSTAT, KERN_TKSTAT_CANCC, CTL_EOL);
    332 	sysctl_createv(&kern_tkstat_sysctllog, 0, NULL, NULL,
    333 		       CTLFLAG_PERMANENT,
    334 		       CTLTYPE_QUAD, "rawcc",
    335 		       SYSCTL_DESCR("Number of raw tty input characters"),
    336 		       NULL, 0, &tk_rawcc, 0,
    337 		       CTL_KERN, KERN_TKSTAT, KERN_TKSTAT_RAWCC, CTL_EOL);
    338 
    339 	kern_tty_sysctllog = NULL;
    340 	sysctl_createv(&kern_tty_sysctllog, 0, NULL, &rnode,
    341 		       CTLFLAG_PERMANENT,
    342 		       CTLTYPE_NODE, "tty", NULL,
    343 		       NULL, 0, NULL, 0,
    344 		       CTL_KERN, CTL_CREATE, CTL_EOL);
    345 	sysctl_createv(&kern_tty_sysctllog, 0, &rnode, &cnode,
    346 		       CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
    347 		       CTLTYPE_INT, "qsize",
    348 		       SYSCTL_DESCR("TTY input and output queue size"),
    349 		       sysctl_kern_tty_qsize, 0, &tty_qsize, 0,
    350 		       CTL_CREATE, CTL_EOL);
    351 }
    352 
    353 int
    354 ttyopen(struct tty *tp, int dialout, int nonblock)
    355 {
    356 	int	error;
    357 
    358 	error = 0;
    359 
    360 	mutex_spin_enter(&tty_lock);
    361 
    362 	if (dialout) {
    363 		/*
    364 		 * If the device is already open for non-dialout, fail.
    365 		 * Otherwise, set TS_DIALOUT to block any pending non-dialout
    366 		 * opens.
    367 		 */
    368 		if (ISSET(tp->t_state, TS_ISOPEN) &&
    369 		    !ISSET(tp->t_state, TS_DIALOUT)) {
    370 			error = EBUSY;
    371 			goto out;
    372 		}
    373 		SET(tp->t_state, TS_DIALOUT);
    374 	} else {
    375 		if (!nonblock) {
    376 			/*
    377 			 * Wait for carrier.  Also wait for any dialout
    378 			 * processes to close the tty first.
    379 			 */
    380 			while (ISSET(tp->t_state, TS_DIALOUT) ||
    381 			       !CONNECTED(tp)) {
    382 				tp->t_wopen++;
    383 				error = ttysleep(tp, &tp->t_rawcv, true, 0);
    384 				tp->t_wopen--;
    385 				if (error)
    386 					goto out;
    387 			}
    388 		} else {
    389 			/*
    390 			 * Don't allow a non-blocking non-dialout open if the
    391 			 * device is already open for dialout.
    392 			 */
    393 			if (ISSET(tp->t_state, TS_DIALOUT)) {
    394 				error = EBUSY;
    395 				goto out;
    396 			}
    397 		}
    398 	}
    399 
    400 out:
    401 	mutex_spin_exit(&tty_lock);
    402 	return (error);
    403 }
    404 
    405 /*
    406  * Initial open of tty, or (re)entry to standard tty line discipline.
    407  */
    408 int
    409 ttylopen(dev_t device, struct tty *tp)
    410 {
    411 
    412 	mutex_spin_enter(&tty_lock);
    413 	tp->t_dev = device;
    414 	if (!ISSET(tp->t_state, TS_ISOPEN)) {
    415 		SET(tp->t_state, TS_ISOPEN);
    416 		memset(&tp->t_winsize, 0, sizeof(tp->t_winsize));
    417 		tp->t_flags = 0;
    418 	}
    419 	mutex_spin_exit(&tty_lock);
    420 	if (tp->t_qsize != tty_qsize)
    421 		tty_set_qsize(tp, tty_qsize);
    422 	return (0);
    423 }
    424 
    425 /*
    426  * Handle close() on a tty line: flush and set to initial state,
    427  * bumping generation number so that pending read/write calls
    428  * can detect recycling of the tty.
    429  */
    430 int
    431 ttyclose(struct tty *tp)
    432 {
    433 	extern struct tty *constty;	/* Temporary virtual console. */
    434 	struct session *sess;
    435 
    436 	mutex_spin_enter(&tty_lock);
    437 
    438 	if (constty == tp)
    439 		constty = NULL;
    440 
    441 	ttyflush(tp, FREAD | FWRITE);
    442 
    443 	tp->t_gen++;
    444 	tp->t_pgrp = NULL;
    445 	tp->t_state = 0;
    446 	sess = tp->t_session;
    447 	tp->t_session = NULL;
    448 
    449 	mutex_spin_exit(&tty_lock);
    450 
    451 	if (sess != NULL) {
    452 		mutex_enter(proc_lock);
    453 		/* Releases proc_lock. */
    454 		proc_sessrele(sess);
    455 	}
    456 	return (0);
    457 }
    458 
    459 #define	FLUSHQ(q) {							\
    460 	if ((q)->c_cc)							\
    461 		ndflush(q, (q)->c_cc);					\
    462 }
    463 
    464 /*
    465  * This macro is used in canonical mode input processing, where a read
    466  * request shall not return unless a 'line delimiter' ('\n') or 'break'
    467  * (EOF, EOL, EOL2) character (or a signal) has been received. As EOL2
    468  * is an extension to the POSIX.1 defined set of special characters,
    469  * recognize it only if IEXTEN is set in the set of local flags.
    470  */
    471 #define	TTBREAKC(c, lflg)						\
    472 	((c) == '\n' || (((c) == cc[VEOF] || (c) == cc[VEOL] ||		\
    473 	((c) == cc[VEOL2] && ISSET(lflg, IEXTEN))) && (c) != _POSIX_VDISABLE))
    474 
    475 
    476 
    477 /*
    478  * ttyinput() helper.
    479  * Call with the tty lock held.
    480  */
    481 /* XXX static */ int
    482 ttyinput_wlock(int c, struct tty *tp)
    483 {
    484 	int	iflag, lflag, i, error;
    485 	u_char	*cc;
    486 
    487 	KASSERT(mutex_owned(&tty_lock));
    488 
    489 	/*
    490 	 * If input is pending take it first.
    491 	 */
    492 	lflag = tp->t_lflag;
    493 	if (ISSET(lflag, PENDIN))
    494 		ttypend(tp);
    495 	/*
    496 	 * Gather stats.
    497 	 */
    498 	if (ISSET(lflag, ICANON)) {
    499 		++tk_cancc;
    500 		++tp->t_cancc;
    501 	} else {
    502 		++tk_rawcc;
    503 		++tp->t_rawcc;
    504 	}
    505 	++tk_nin;
    506 
    507 	cc = tp->t_cc;
    508 
    509 	/*
    510 	 * Handle exceptional conditions (break, parity, framing).
    511 	 */
    512 	iflag = tp->t_iflag;
    513 	if ((error = (ISSET(c, TTY_ERRORMASK))) != 0) {
    514 		CLR(c, TTY_ERRORMASK);
    515 		if (ISSET(error, TTY_FE) && c == 0) {		/* Break. */
    516 			if (ISSET(iflag, IGNBRK))
    517 				return (0);
    518 			else if (ISSET(iflag, BRKINT)) {
    519 				ttyflush(tp, FREAD | FWRITE);
    520 				ttysig(tp, TTYSIG_PG1, SIGINT);
    521 				return (0);
    522 			} else if (ISSET(iflag, PARMRK))
    523 				goto parmrk;
    524 		} else if ((ISSET(error, TTY_PE) && ISSET(iflag, INPCK)) ||
    525 		    ISSET(error, TTY_FE)) {
    526 			if (ISSET(iflag, IGNPAR))
    527 				return (0);
    528 			else if (ISSET(iflag, PARMRK)) {
    529  parmrk:			(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
    530 				(void)putc(0    | TTY_QUOTE, &tp->t_rawq);
    531 				(void)putc(c    | TTY_QUOTE, &tp->t_rawq);
    532 				return (0);
    533 			} else
    534 				c = 0;
    535 		}
    536 	} else if (c == 0377 &&
    537 	    ISSET(iflag, ISTRIP|IGNPAR|INPCK|PARMRK) == (INPCK|PARMRK)) {
    538 		/* "Escape" a valid character of '\377'. */
    539 		(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
    540 		(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
    541 		goto endcase;
    542 	}
    543 
    544 	/*
    545 	 * In tandem mode, check high water mark.
    546 	 */
    547 	if (ISSET(iflag, IXOFF) || ISSET(tp->t_cflag, CHWFLOW))
    548 		ttyblock(tp);
    549 	if (!ISSET(tp->t_state, TS_TYPEN) && ISSET(iflag, ISTRIP))
    550 		CLR(c, 0x80);
    551 	if (!ISSET(lflag, EXTPROC)) {
    552 		/*
    553 		 * Check for literal nexting very first
    554 		 */
    555 		if (ISSET(tp->t_state, TS_LNCH)) {
    556 			SET(c, TTY_QUOTE);
    557 			CLR(tp->t_state, TS_LNCH);
    558 		}
    559 		/*
    560 		 * Scan for special characters.  This code
    561 		 * is really just a big case statement with
    562 		 * non-constant cases.  The bottom of the
    563 		 * case statement is labeled ``endcase'', so goto
    564 		 * it after a case match, or similar.
    565 		 */
    566 
    567 		/*
    568 		 * Control chars which aren't controlled
    569 		 * by ICANON, ISIG, or IXON.
    570 		 */
    571 		if (ISSET(lflag, IEXTEN)) {
    572 			if (CCEQ(cc[VLNEXT], c)) {
    573 				if (ISSET(lflag, ECHO)) {
    574 					if (ISSET(lflag, ECHOE)) {
    575 						(void)ttyoutput('^', tp);
    576 						(void)ttyoutput('\b', tp);
    577 					} else
    578 						ttyecho(c, tp);
    579 				}
    580 				SET(tp->t_state, TS_LNCH);
    581 				goto endcase;
    582 			}
    583 			if (CCEQ(cc[VDISCARD], c)) {
    584 				if (ISSET(lflag, FLUSHO))
    585 					CLR(tp->t_lflag, FLUSHO);
    586 				else {
    587 					ttyflush(tp, FWRITE);
    588 					ttyecho(c, tp);
    589 					if (tp->t_rawq.c_cc + tp->t_canq.c_cc)
    590 						ttyretype(tp);
    591 					SET(tp->t_lflag, FLUSHO);
    592 				}
    593 				goto startoutput;
    594 			}
    595 		}
    596 		/*
    597 		 * Signals.
    598 		 */
    599 		if (ISSET(lflag, ISIG)) {
    600 			if (CCEQ(cc[VINTR], c) || CCEQ(cc[VQUIT], c)) {
    601 				if (!ISSET(lflag, NOFLSH))
    602 					ttyflush(tp, FREAD | FWRITE);
    603 				ttyecho(c, tp);
    604 				ttysig(tp, TTYSIG_PG1, CCEQ(cc[VINTR], c) ?
    605 				    SIGINT : SIGQUIT);
    606 				goto endcase;
    607 			}
    608 			if (CCEQ(cc[VSUSP], c)) {
    609 				if (!ISSET(lflag, NOFLSH))
    610 					ttyflush(tp, FREAD);
    611 				ttyecho(c, tp);
    612 				ttysig(tp, TTYSIG_PG1, SIGTSTP);
    613 				goto endcase;
    614 			}
    615 		}
    616 		/*
    617 		 * Handle start/stop characters.
    618 		 */
    619 		if (ISSET(iflag, IXON)) {
    620 			if (CCEQ(cc[VSTOP], c)) {
    621 				if (!ISSET(tp->t_state, TS_TTSTOP)) {
    622 					SET(tp->t_state, TS_TTSTOP);
    623 					cdev_stop(tp, 0);
    624 					return (0);
    625 				}
    626 				if (!CCEQ(cc[VSTART], c))
    627 					return (0);
    628 				/*
    629 				 * if VSTART == VSTOP then toggle
    630 				 */
    631 				goto endcase;
    632 			}
    633 			if (CCEQ(cc[VSTART], c))
    634 				goto restartoutput;
    635 		}
    636 		/*
    637 		 * IGNCR, ICRNL, & INLCR
    638 		 */
    639 		if (c == '\r') {
    640 			if (ISSET(iflag, IGNCR))
    641 				goto endcase;
    642 			else if (ISSET(iflag, ICRNL))
    643 				c = '\n';
    644 		} else if (c == '\n' && ISSET(iflag, INLCR))
    645 			c = '\r';
    646 	}
    647 	if (!ISSET(lflag, EXTPROC) && ISSET(lflag, ICANON)) {
    648 		/*
    649 		 * From here on down canonical mode character
    650 		 * processing takes place.
    651 		 */
    652 		/*
    653 		 * erase (^H / ^?)
    654 		 */
    655 		if (CCEQ(cc[VERASE], c)) {
    656 			if (tp->t_rawq.c_cc)
    657 				ttyrub(unputc(&tp->t_rawq), tp);
    658 			goto endcase;
    659 		}
    660 		/*
    661 		 * kill (^U)
    662 		 */
    663 		if (CCEQ(cc[VKILL], c)) {
    664 			if (ISSET(lflag, ECHOKE) &&
    665 			    tp->t_rawq.c_cc == tp->t_rocount &&
    666 			    !ISSET(lflag, ECHOPRT))
    667 				while (tp->t_rawq.c_cc)
    668 					ttyrub(unputc(&tp->t_rawq), tp);
    669 			else {
    670 				ttyecho(c, tp);
    671 				if (ISSET(lflag, ECHOK) ||
    672 				    ISSET(lflag, ECHOKE))
    673 					ttyecho('\n', tp);
    674 				FLUSHQ(&tp->t_rawq);
    675 				tp->t_rocount = 0;
    676 			}
    677 			CLR(tp->t_state, TS_LOCAL);
    678 			goto endcase;
    679 		}
    680 		/*
    681 		 * Extensions to the POSIX.1 GTI set of functions.
    682 		 */
    683 		if (ISSET(lflag, IEXTEN)) {
    684 			/*
    685 			 * word erase (^W)
    686 			 */
    687 			if (CCEQ(cc[VWERASE], c)) {
    688 				int alt = ISSET(lflag, ALTWERASE);
    689 				int ctype;
    690 
    691 				/*
    692 				 * erase whitespace
    693 				 */
    694 				while ((c = unputc(&tp->t_rawq)) == ' ' ||
    695 				    c == '\t')
    696 					ttyrub(c, tp);
    697 				if (c == -1)
    698 					goto endcase;
    699 				/*
    700 				 * erase last char of word and remember the
    701 				 * next chars type (for ALTWERASE)
    702 				 */
    703 				ttyrub(c, tp);
    704 				c = unputc(&tp->t_rawq);
    705 				if (c == -1)
    706 					goto endcase;
    707 				if (c == ' ' || c == '\t') {
    708 					(void)putc(c, &tp->t_rawq);
    709 					goto endcase;
    710 				}
    711 				ctype = ISALPHA(c);
    712 				/*
    713 				 * erase rest of word
    714 				 */
    715 				do {
    716 					ttyrub(c, tp);
    717 					c = unputc(&tp->t_rawq);
    718 					if (c == -1)
    719 						goto endcase;
    720 				} while (c != ' ' && c != '\t' &&
    721 				    (alt == 0 || ISALPHA(c) == ctype));
    722 				(void)putc(c, &tp->t_rawq);
    723 				goto endcase;
    724 			}
    725 			/*
    726 			 * reprint line (^R)
    727 			 */
    728 			if (CCEQ(cc[VREPRINT], c)) {
    729 				ttyretype(tp);
    730 				goto endcase;
    731 			}
    732 			/*
    733 			 * ^T - kernel info and generate SIGINFO
    734 			 */
    735 			if (CCEQ(cc[VSTATUS], c)) {
    736 				ttysig(tp, TTYSIG_PG1, SIGINFO);
    737 				goto endcase;
    738 			}
    739 		}
    740 	}
    741 	/*
    742 	 * Check for input buffer overflow
    743 	 */
    744 	if (tp->t_rawq.c_cc + tp->t_canq.c_cc >= TTYHOG) {
    745 		if (ISSET(iflag, IMAXBEL)) {
    746 			if (tp->t_outq.c_cc < tp->t_hiwat)
    747 				(void)ttyoutput(CTRL('g'), tp);
    748 		} else
    749 			ttyflush(tp, FREAD | FWRITE);
    750 		goto endcase;
    751 	}
    752 	/*
    753 	 * Put data char in q for user and
    754 	 * wakeup on seeing a line delimiter.
    755 	 */
    756 	if (putc(c, &tp->t_rawq) >= 0) {
    757 		if (!ISSET(lflag, ICANON)) {
    758 			ttwakeup(tp);
    759 			ttyecho(c, tp);
    760 			goto endcase;
    761 		}
    762 		if (TTBREAKC(c, lflag)) {
    763 			tp->t_rocount = 0;
    764 			catq(&tp->t_rawq, &tp->t_canq);
    765 			ttwakeup(tp);
    766 		} else if (tp->t_rocount++ == 0)
    767 			tp->t_rocol = tp->t_column;
    768 		if (ISSET(tp->t_state, TS_ERASE)) {
    769 			/*
    770 			 * end of prterase \.../
    771 			 */
    772 			CLR(tp->t_state, TS_ERASE);
    773 			(void)ttyoutput('/', tp);
    774 		}
    775 		i = tp->t_column;
    776 		ttyecho(c, tp);
    777 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ECHO)) {
    778 			/*
    779 			 * Place the cursor over the '^' of the ^D.
    780 			 */
    781 			i = min(2, tp->t_column - i);
    782 			while (i > 0) {
    783 				(void)ttyoutput('\b', tp);
    784 				i--;
    785 			}
    786 		}
    787 	}
    788  endcase:
    789 	/*
    790 	 * IXANY means allow any character to restart output.
    791 	 */
    792 	if (ISSET(tp->t_state, TS_TTSTOP) &&
    793 	    !ISSET(iflag, IXANY) && cc[VSTART] != cc[VSTOP]) {
    794 		return (0);
    795 	}
    796  restartoutput:
    797 	CLR(tp->t_lflag, FLUSHO);
    798 	CLR(tp->t_state, TS_TTSTOP);
    799  startoutput:
    800 	return (ttstart(tp));
    801 }
    802 
    803 /*
    804  * Process input of a single character received on a tty.
    805  *
    806  * XXX - this is a hack, all drivers must changed to acquire the
    807  *	 lock before calling linesw->l_rint()
    808  */
    809 int
    810 ttyinput(int c, struct tty *tp)
    811 {
    812 	int error;
    813 
    814 	/*
    815 	 * Unless the receiver is enabled, drop incoming data.
    816 	 */
    817 	if (!ISSET(tp->t_cflag, CREAD))
    818 		return (0);
    819 
    820 	mutex_spin_enter(&tty_lock);
    821 	error = ttyinput_wlock(c, tp);
    822 	mutex_spin_exit(&tty_lock);
    823 
    824 	return (error);
    825 }
    826 
    827 /*
    828  * Output a single character on a tty, doing output processing
    829  * as needed (expanding tabs, newline processing, etc.).
    830  * Returns < 0 if succeeds, otherwise returns char to resend.
    831  * Must be recursive.
    832  *
    833  * Call with tty lock held.
    834  */
    835 int
    836 ttyoutput(int c, struct tty *tp)
    837 {
    838 	long	oflag;
    839 	int	col, notout;
    840 
    841 	KASSERT(mutex_owned(&tty_lock));
    842 
    843 	oflag = tp->t_oflag;
    844 	if (!ISSET(oflag, OPOST)) {
    845 		tk_nout++;
    846 		tp->t_outcc++;
    847 		if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
    848 			return (c);
    849 		return (-1);
    850 	}
    851 	/*
    852 	 * Do tab expansion if OXTABS is set.  Special case if we do external
    853 	 * processing, we don't do the tab expansion because we'll probably
    854 	 * get it wrong.  If tab expansion needs to be done, let it happen
    855 	 * externally.
    856 	 */
    857 	CLR(c, ~TTY_CHARMASK);
    858 	if (c == '\t' &&
    859 	    ISSET(oflag, OXTABS) && !ISSET(tp->t_lflag, EXTPROC)) {
    860 		c = 8 - (tp->t_column & 7);
    861 		if (ISSET(tp->t_lflag, FLUSHO)) {
    862 			notout = 0;
    863 		} else {
    864 			notout = b_to_q("        ", c, &tp->t_outq);
    865 			c -= notout;
    866 			tk_nout += c;
    867 			tp->t_outcc += c;
    868 		}
    869 		tp->t_column += c;
    870 		return (notout ? '\t' : -1);
    871 	}
    872 	if (c == CEOT && ISSET(oflag, ONOEOT))
    873 		return (-1);
    874 
    875 	/*
    876 	 * Newline translation: if ONLCR is set,
    877 	 * translate newline into "\r\n".
    878 	 */
    879 	if (c == '\n' && ISSET(tp->t_oflag, ONLCR)) {
    880 		tk_nout++;
    881 		tp->t_outcc++;
    882 		if (!ISSET(tp->t_lflag, FLUSHO) && putc('\r', &tp->t_outq))
    883 			return (c);
    884 	}
    885 	/* If OCRNL is set, translate "\r" into "\n". */
    886 	else if (c == '\r' && ISSET(tp->t_oflag, OCRNL))
    887 		c = '\n';
    888 	/* If ONOCR is set, don't transmit CRs when on column 0. */
    889 	else if (c == '\r' && ISSET(tp->t_oflag, ONOCR) && tp->t_column == 0)
    890 		return (-1);
    891 
    892 	tk_nout++;
    893 	tp->t_outcc++;
    894 	if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
    895 		return (c);
    896 
    897 	col = tp->t_column;
    898 	switch (CCLASS(c)) {
    899 	case BACKSPACE:
    900 		if (col > 0)
    901 			--col;
    902 		break;
    903 	case CONTROL:
    904 		break;
    905 	case NEWLINE:
    906 		if (ISSET(tp->t_oflag, ONLCR | ONLRET))
    907 			col = 0;
    908 		break;
    909 	case RETURN:
    910 		col = 0;
    911 		break;
    912 	case ORDINARY:
    913 		++col;
    914 		break;
    915 	case TAB:
    916 		col = (col + 8) & ~7;
    917 		break;
    918 	}
    919 	tp->t_column = col;
    920 	return (-1);
    921 }
    922 
    923 /*
    924  * Ioctls for all tty devices.  Called after line-discipline specific ioctl
    925  * has been called to do discipline-specific functions and/or reject any
    926  * of these ioctl commands.
    927  */
    928 /* ARGSUSED */
    929 int
    930 ttioctl(struct tty *tp, u_long cmd, void *data, int flag, struct lwp *l)
    931 {
    932 	extern struct tty *constty;	/* Temporary virtual console. */
    933 	struct proc *p;
    934 	struct linesw	*lp;
    935 	int		s, error;
    936 	struct pathbuf *pb;
    937 	struct nameidata nd;
    938 	char		infobuf[200];
    939 
    940 	KASSERT(l != NULL);
    941 	p = l->l_proc;
    942 
    943 	/* If the ioctl involves modification, hang if in the background. */
    944 	switch (cmd) {
    945 	case  TIOCFLUSH:
    946 	case  TIOCDRAIN:
    947 	case  TIOCSBRK:
    948 	case  TIOCCBRK:
    949 	case  TIOCSTART:
    950 	case  TIOCSETA:
    951 	case  TIOCSETD:
    952 	case  TIOCSLINED:
    953 	case  TIOCSETAF:
    954 	case  TIOCSETAW:
    955 #ifdef notdef
    956 	case  TIOCSPGRP:
    957 	case  FIOSETOWN:
    958 #endif
    959 	case  TIOCSTAT:
    960 	case  TIOCSTI:
    961 	case  TIOCSWINSZ:
    962 	case  TIOCSQSIZE:
    963 	case  TIOCLBIC:
    964 	case  TIOCLBIS:
    965 	case  TIOCLSET:
    966 	case  TIOCSETC:
    967 	case OTIOCSETD:
    968 	case  TIOCSETN:
    969 	case  TIOCSETP:
    970 	case  TIOCSLTC:
    971 		mutex_spin_enter(&tty_lock);
    972 		while (isbackground(curproc, tp) &&
    973 		    p->p_pgrp->pg_jobc && (p->p_lflag & PL_PPWAIT) == 0 &&
    974 		    !sigismasked(l, SIGTTOU)) {
    975 			mutex_spin_exit(&tty_lock);
    976 
    977 			mutex_enter(proc_lock);
    978 			pgsignal(p->p_pgrp, SIGTTOU, 1);
    979 			mutex_exit(proc_lock);
    980 
    981 			mutex_spin_enter(&tty_lock);
    982 			error = ttypause(tp, hz);
    983 			if (error) {
    984 				mutex_spin_exit(&tty_lock);
    985 				return (error);
    986 			}
    987 		}
    988 		mutex_spin_exit(&tty_lock);
    989 		break;
    990 	}
    991 
    992 	switch (cmd) {			/* Process the ioctl. */
    993 	case FIOASYNC:			/* set/clear async i/o */
    994 		mutex_spin_enter(&tty_lock);
    995 		if (*(int *)data)
    996 			SET(tp->t_state, TS_ASYNC);
    997 		else
    998 			CLR(tp->t_state, TS_ASYNC);
    999 		mutex_spin_exit(&tty_lock);
   1000 		break;
   1001 	case FIONBIO:			/* set/clear non-blocking i/o */
   1002 		break;			/* XXX: delete. */
   1003 	case FIONREAD:			/* get # bytes to read */
   1004 		mutex_spin_enter(&tty_lock);
   1005 		*(int *)data = ttnread(tp);
   1006 		mutex_spin_exit(&tty_lock);
   1007 		break;
   1008 	case FIONWRITE:			/* get # bytes to written & unsent */
   1009 		mutex_spin_enter(&tty_lock);
   1010 		*(int *)data = tp->t_outq.c_cc;
   1011 		mutex_spin_exit(&tty_lock);
   1012 		break;
   1013 	case FIONSPACE:			/* get # bytes to written & unsent */
   1014 		mutex_spin_enter(&tty_lock);
   1015 		*(int *)data = tp->t_outq.c_cn - tp->t_outq.c_cc;
   1016 		mutex_spin_exit(&tty_lock);
   1017 		break;
   1018 	case TIOCEXCL:			/* set exclusive use of tty */
   1019 		mutex_spin_enter(&tty_lock);
   1020 		SET(tp->t_state, TS_XCLUDE);
   1021 		mutex_spin_exit(&tty_lock);
   1022 		break;
   1023 	case TIOCFLUSH: {		/* flush buffers */
   1024 		int flags = *(int *)data;
   1025 
   1026 		if (flags == 0)
   1027 			flags = FREAD | FWRITE;
   1028 		else
   1029 			flags &= FREAD | FWRITE;
   1030 		mutex_spin_enter(&tty_lock);
   1031 		ttyflush(tp, flags);
   1032 		mutex_spin_exit(&tty_lock);
   1033 		break;
   1034 	}
   1035 	case TIOCCONS:			/* become virtual console */
   1036 		if (*(int *)data) {
   1037 			if (constty && constty != tp &&
   1038 			    ISSET(constty->t_state, TS_CARR_ON | TS_ISOPEN) ==
   1039 			    (TS_CARR_ON | TS_ISOPEN))
   1040 				return EBUSY;
   1041 
   1042 			pb = pathbuf_create("/dev/console");
   1043 			if (pb == NULL) {
   1044 				return ENOMEM;
   1045 			}
   1046 			NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, pb);
   1047 			if ((error = namei(&nd)) != 0) {
   1048 				pathbuf_destroy(pb);
   1049 				return error;
   1050 			}
   1051 			error = VOP_ACCESS(nd.ni_vp, VREAD, l->l_cred);
   1052 			vput(nd.ni_vp);
   1053 			pathbuf_destroy(pb);
   1054 			if (error)
   1055 				return error;
   1056 
   1057 			constty = tp;
   1058 		} else if (tp == constty)
   1059 			constty = NULL;
   1060 		break;
   1061 	case TIOCDRAIN:			/* wait till output drained */
   1062 		if ((error = ttywait(tp)) != 0)
   1063 			return (error);
   1064 		break;
   1065 	case TIOCGETA: {		/* get termios struct */
   1066 		struct termios *t = (struct termios *)data;
   1067 
   1068 		memcpy(t, &tp->t_termios, sizeof(struct termios));
   1069 		break;
   1070 	}
   1071 	case TIOCGETD:			/* get line discipline (old) */
   1072 		*(int *)data = tp->t_linesw->l_no;
   1073 		break;
   1074 	case TIOCGLINED:		/* get line discipline (new) */
   1075 		(void)strncpy((char *)data, tp->t_linesw->l_name,
   1076 		    TTLINEDNAMELEN - 1);
   1077 		break;
   1078 	case TIOCGWINSZ:		/* get window size */
   1079 		*(struct winsize *)data = tp->t_winsize;
   1080 		break;
   1081 	case TIOCGQSIZE:
   1082 		*(int *)data = tp->t_qsize;
   1083 		break;
   1084 	case FIOGETOWN:
   1085 		mutex_enter(proc_lock);
   1086 		if (tp->t_session != NULL && !isctty(p, tp)) {
   1087 			mutex_exit(proc_lock);
   1088 			return (ENOTTY);
   1089 		}
   1090 		*(int *)data = tp->t_pgrp ? -tp->t_pgrp->pg_id : 0;
   1091 		mutex_exit(proc_lock);
   1092 		break;
   1093 	case TIOCGPGRP:			/* get pgrp of tty */
   1094 		mutex_enter(proc_lock);
   1095 		if (!isctty(p, tp)) {
   1096 			mutex_exit(proc_lock);
   1097 			return (ENOTTY);
   1098 		}
   1099 		*(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PGID;
   1100 		mutex_exit(proc_lock);
   1101 		break;
   1102 	case TIOCGSID:			/* get sid of tty */
   1103 		mutex_enter(proc_lock);
   1104 		if (!isctty(p, tp)) {
   1105 			mutex_exit(proc_lock);
   1106 			return (ENOTTY);
   1107 		}
   1108 		*(int *)data = tp->t_session->s_sid;
   1109 		mutex_exit(proc_lock);
   1110 		break;
   1111 #ifdef TIOCHPCL
   1112 	case TIOCHPCL:			/* hang up on last close */
   1113 		mutex_spin_enter(&tty_lock);
   1114 		SET(tp->t_cflag, HUPCL);
   1115 		mutex_spin_exit(&tty_lock);
   1116 		break;
   1117 #endif
   1118 	case TIOCNXCL:			/* reset exclusive use of tty */
   1119 		mutex_spin_enter(&tty_lock);
   1120 		CLR(tp->t_state, TS_XCLUDE);
   1121 		mutex_spin_exit(&tty_lock);
   1122 		break;
   1123 	case TIOCOUTQ:			/* output queue size */
   1124 		*(int *)data = tp->t_outq.c_cc;
   1125 		break;
   1126 	case TIOCSETA:			/* set termios struct */
   1127 	case TIOCSETAW:			/* drain output, set */
   1128 	case TIOCSETAF: {		/* drn out, fls in, set */
   1129 		struct termios *t = (struct termios *)data;
   1130 
   1131 		if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
   1132 			if ((error = ttywait(tp)) != 0)
   1133 				return (error);
   1134 
   1135 			if (cmd == TIOCSETAF) {
   1136 				mutex_spin_enter(&tty_lock);
   1137 				ttyflush(tp, FREAD);
   1138 				mutex_spin_exit(&tty_lock);
   1139 			}
   1140 		}
   1141 
   1142 		s = spltty();
   1143 		/*
   1144 		 * XXXSMP - some drivers call back on us from t_param(), so
   1145 		 *	    don't take the tty spin lock here.
   1146 		 *	    require t_param() to unlock upon callback?
   1147 		 */
   1148 		/* wanted here: mutex_spin_enter(&tty_lock); */
   1149 		if (!ISSET(t->c_cflag, CIGNORE)) {
   1150 			/*
   1151 			 * Set device hardware.
   1152 			 */
   1153 			if (tp->t_param && (error = (*tp->t_param)(tp, t))) {
   1154 				/* wanted here: mutex_spin_exit(&tty_lock); */
   1155 				splx(s);
   1156 				return (error);
   1157 			} else {
   1158 				tp->t_cflag = t->c_cflag;
   1159 				tp->t_ispeed = t->c_ispeed;
   1160 				tp->t_ospeed = t->c_ospeed;
   1161 				if (t->c_ospeed == 0)
   1162 					ttysig(tp, TTYSIG_LEADER, SIGHUP);
   1163 			}
   1164 			ttsetwater(tp);
   1165 		}
   1166 
   1167 		/* delayed lock acquiring */
   1168 		mutex_spin_enter(&tty_lock);
   1169 		if (cmd != TIOCSETAF) {
   1170 			if (ISSET(t->c_lflag, ICANON) !=
   1171 			    ISSET(tp->t_lflag, ICANON)) {
   1172 				if (ISSET(t->c_lflag, ICANON)) {
   1173 					SET(tp->t_lflag, PENDIN);
   1174 					ttwakeup(tp);
   1175 				} else {
   1176 					struct clist tq;
   1177 
   1178 					catq(&tp->t_rawq, &tp->t_canq);
   1179 					tq = tp->t_rawq;
   1180 					tp->t_rawq = tp->t_canq;
   1181 					tp->t_canq = tq;
   1182 					CLR(tp->t_lflag, PENDIN);
   1183 				}
   1184 			}
   1185 		}
   1186 		tp->t_iflag = t->c_iflag;
   1187 		tp->t_oflag = t->c_oflag;
   1188 		/*
   1189 		 * Make the EXTPROC bit read only.
   1190 		 */
   1191 		if (ISSET(tp->t_lflag, EXTPROC))
   1192 			SET(t->c_lflag, EXTPROC);
   1193 		else
   1194 			CLR(t->c_lflag, EXTPROC);
   1195 		tp->t_lflag = t->c_lflag | ISSET(tp->t_lflag, PENDIN);
   1196 		memcpy(tp->t_cc, t->c_cc, sizeof(t->c_cc));
   1197 		mutex_spin_exit(&tty_lock);
   1198 		splx(s);
   1199 		break;
   1200 	}
   1201 	case TIOCSETD:			/* set line discipline (old) */
   1202 		lp = ttyldisc_lookup_bynum(*(int *)data);
   1203 		goto setldisc;
   1204 
   1205 	case TIOCSLINED: {		/* set line discipline (new) */
   1206 		char *name = (char *)data;
   1207 		dev_t device;
   1208 
   1209 		/* Null terminate to prevent buffer overflow */
   1210 		name[TTLINEDNAMELEN - 1] = '\0';
   1211 		lp = ttyldisc_lookup(name);
   1212  setldisc:
   1213 		if (lp == NULL)
   1214 			return (ENXIO);
   1215 
   1216 		if (lp != tp->t_linesw) {
   1217 			device = tp->t_dev;
   1218 			s = spltty();
   1219 			(*tp->t_linesw->l_close)(tp, flag);
   1220 			error = (*lp->l_open)(device, tp);
   1221 			if (error) {
   1222 				(void)(*tp->t_linesw->l_open)(device, tp);
   1223 				splx(s);
   1224 				ttyldisc_release(lp);
   1225 				return (error);
   1226 			}
   1227 			ttyldisc_release(tp->t_linesw);
   1228 			tp->t_linesw = lp;
   1229 			splx(s);
   1230 		} else {
   1231 			/* Drop extra reference. */
   1232 			ttyldisc_release(lp);
   1233 		}
   1234 		break;
   1235 	}
   1236 	case TIOCSTART:			/* start output, like ^Q */
   1237 		mutex_spin_enter(&tty_lock);
   1238 		if (ISSET(tp->t_state, TS_TTSTOP) ||
   1239 		    ISSET(tp->t_lflag, FLUSHO)) {
   1240 			CLR(tp->t_lflag, FLUSHO);
   1241 			CLR(tp->t_state, TS_TTSTOP);
   1242 			ttstart(tp);
   1243 		}
   1244 		mutex_spin_exit(&tty_lock);
   1245 		break;
   1246 	case TIOCSTI:			/* simulate terminal input */
   1247 		if ((error = kauth_authorize_device_tty(l->l_cred,
   1248 		    KAUTH_DEVICE_TTY_STI, tp)) != 0) {
   1249 			if (!ISSET(flag, FREAD))
   1250 				return EPERM;
   1251 			if (!isctty(p, tp))
   1252 				return EACCES;
   1253 			if (tp->t_session->s_leader->p_cred != p->p_cred)
   1254 				return error;
   1255 		}
   1256 		(*tp->t_linesw->l_rint)(*(u_char *)data, tp);
   1257 		break;
   1258 	case TIOCSTOP:			/* stop output, like ^S */
   1259 	{
   1260 		mutex_spin_enter(&tty_lock);
   1261 		if (!ISSET(tp->t_state, TS_TTSTOP)) {
   1262 			SET(tp->t_state, TS_TTSTOP);
   1263 			cdev_stop(tp, 0);
   1264 		}
   1265 		mutex_spin_exit(&tty_lock);
   1266 		break;
   1267 	}
   1268 	case TIOCSCTTY:			/* become controlling tty */
   1269 		mutex_enter(proc_lock);
   1270 		mutex_spin_enter(&tty_lock);
   1271 
   1272 		/* Session ctty vnode pointer set in vnode layer. */
   1273 		if (!SESS_LEADER(p) ||
   1274 		    ((p->p_session->s_ttyvp || tp->t_session) &&
   1275 		    (tp->t_session != p->p_session))) {
   1276 			mutex_spin_exit(&tty_lock);
   1277 			mutex_exit(proc_lock);
   1278 			return (EPERM);
   1279 		}
   1280 
   1281 		/*
   1282 		 * `p_session' acquires a reference.
   1283 		 * But note that if `t_session' is set at this point,
   1284 		 * it must equal `p_session', in which case the session
   1285 		 * already has the correct reference count.
   1286 		 */
   1287 		if (tp->t_session == NULL) {
   1288 			proc_sesshold(p->p_session);
   1289 		}
   1290 		tp->t_session = p->p_session;
   1291 		tp->t_pgrp = p->p_pgrp;
   1292 		p->p_session->s_ttyp = tp;
   1293 		p->p_lflag |= PL_CONTROLT;
   1294 		mutex_spin_exit(&tty_lock);
   1295 		mutex_exit(proc_lock);
   1296 		break;
   1297 	case FIOSETOWN: {		/* set pgrp of tty */
   1298 		pid_t pgid = *(pid_t *)data;
   1299 		struct pgrp *pgrp;
   1300 
   1301 		mutex_enter(proc_lock);
   1302 		if (tp->t_session != NULL && !isctty(p, tp)) {
   1303 			mutex_exit(proc_lock);
   1304 			return (ENOTTY);
   1305 		}
   1306 
   1307 		if (pgid < 0) {
   1308 			pgrp = pgrp_find(-pgid);
   1309 			if (pgrp == NULL) {
   1310 				mutex_exit(proc_lock);
   1311 				return (EINVAL);
   1312 			}
   1313 		} else {
   1314 			struct proc *p1;
   1315 			p1 = proc_find(pgid);
   1316 			if (!p1) {
   1317 				mutex_exit(proc_lock);
   1318 				return (ESRCH);
   1319 			}
   1320 			pgrp = p1->p_pgrp;
   1321 		}
   1322 
   1323 		if (pgrp->pg_session != p->p_session) {
   1324 			mutex_exit(proc_lock);
   1325 			return (EPERM);
   1326 		}
   1327 		mutex_spin_enter(&tty_lock);
   1328 		tp->t_pgrp = pgrp;
   1329 		mutex_spin_exit(&tty_lock);
   1330 		mutex_exit(proc_lock);
   1331 		break;
   1332 	}
   1333 	case TIOCSPGRP: {		/* set pgrp of tty */
   1334 		struct pgrp *pgrp;
   1335 		pid_t pgid = *(pid_t *)data;
   1336 
   1337 		if (pgid == NO_PGID)
   1338 			return EINVAL;
   1339 
   1340 		mutex_enter(proc_lock);
   1341 		if (!isctty(p, tp)) {
   1342 			mutex_exit(proc_lock);
   1343 			return (ENOTTY);
   1344 		}
   1345 		pgrp = pgrp_find(pgid);
   1346 		if (pgrp == NULL || pgrp->pg_session != p->p_session) {
   1347 			mutex_exit(proc_lock);
   1348 			return (EPERM);
   1349 		}
   1350 		mutex_spin_enter(&tty_lock);
   1351 		tp->t_pgrp = pgrp;
   1352 		mutex_spin_exit(&tty_lock);
   1353 		mutex_exit(proc_lock);
   1354 		break;
   1355 	}
   1356 	case TIOCSTAT:			/* get load avg stats */
   1357 		mutex_enter(proc_lock);
   1358 		ttygetinfo(tp, 0, infobuf, sizeof(infobuf));
   1359 		mutex_exit(proc_lock);
   1360 
   1361 		mutex_spin_enter(&tty_lock);
   1362 		ttyputinfo(tp, infobuf);
   1363 		mutex_spin_exit(&tty_lock);
   1364 		break;
   1365 	case TIOCSWINSZ:		/* set window size */
   1366 		mutex_spin_enter(&tty_lock);
   1367 		if (memcmp((void *)&tp->t_winsize, data,
   1368 		    sizeof(struct winsize))) {
   1369 			tp->t_winsize = *(struct winsize *)data;
   1370 			ttysig(tp, TTYSIG_PG1, SIGWINCH);
   1371 		}
   1372 		mutex_spin_exit(&tty_lock);
   1373 		break;
   1374 	case TIOCSQSIZE:
   1375 		if ((error = tty_get_qsize(&s, *(int *)data)) == 0 &&
   1376 		    s != tp->t_qsize)
   1377 			error = tty_set_qsize(tp, s);
   1378 		return error;
   1379 
   1380 	case TIOCSBRK:
   1381 	case TIOCCBRK:
   1382 	case TIOCSDTR:
   1383 	case TIOCCDTR:
   1384 	case TIOCSFLAGS:
   1385 	case TIOCGFLAGS:
   1386 	case TIOCMSET:
   1387 	case TIOCMGET:
   1388 	case TIOCMBIS:
   1389 	case TIOCMBIC:
   1390 		/* Handled by the driver layer */
   1391 		return EPASSTHROUGH;
   1392 
   1393 	case TIOCEXT:
   1394 	case TIOCPTSNAME:
   1395 	case TIOCGRANTPT:
   1396 	case TIOCPKT:
   1397 	case TIOCUCNTL:
   1398 	case TIOCREMOTE:
   1399 	case TIOCSIG:
   1400 		/* for ptys */
   1401 		return EPASSTHROUGH;
   1402 
   1403 	default:
   1404 		/* Pass through various console ioctls */
   1405 		switch (IOCGROUP(cmd)) {
   1406 		case 'c':	/* syscons console */
   1407 		case 'v':	/* usl console, video - where one letter */
   1408 		case 'K':	/* usl console, keyboard - aint enough */
   1409 		case 'V':	/* pcvt compat */
   1410 		case 'W':	/* wscons console */
   1411 			return EPASSTHROUGH;
   1412 		default:
   1413 			break;
   1414 		}
   1415 		/* We may have to load the compat module for this. */
   1416 		for (;;) {
   1417 			rw_enter(&ttcompat_lock, RW_READER);
   1418 			if (vec_compat_ttioctl_60 != NULL) {
   1419 				break;
   1420 			}
   1421 			rw_exit(&ttcompat_lock);
   1422 			(void)module_autoload("compat", MODULE_CLASS_EXEC);
   1423 			if (vec_compat_ttioctl_60 == NULL) {
   1424 				return EPASSTHROUGH;
   1425 			}
   1426 		}
   1427 		error = (*vec_compat_ttioctl_60)(tp->t_dev, cmd, data, flag, l);
   1428 		rw_exit(&ttcompat_lock);
   1429 		return error;
   1430 	}
   1431 	return (0);
   1432 }
   1433 
   1434 int
   1435 ttpoll(struct tty *tp, int events, struct lwp *l)
   1436 {
   1437 	int	revents;
   1438 
   1439 	revents = 0;
   1440 	mutex_spin_enter(&tty_lock);
   1441 	if (events & (POLLIN | POLLRDNORM))
   1442 		if (ttnread(tp) > 0)
   1443 			revents |= events & (POLLIN | POLLRDNORM);
   1444 
   1445 	if (events & (POLLOUT | POLLWRNORM))
   1446 		if (tp->t_outq.c_cc <= tp->t_lowat)
   1447 			revents |= events & (POLLOUT | POLLWRNORM);
   1448 
   1449 	if (events & POLLHUP)
   1450 		if (!CONNECTED(tp))
   1451 			revents |= POLLHUP;
   1452 
   1453 	if (revents == 0) {
   1454 		if (events & (POLLIN | POLLHUP | POLLRDNORM))
   1455 			selrecord(l, &tp->t_rsel);
   1456 
   1457 		if (events & (POLLOUT | POLLWRNORM))
   1458 			selrecord(l, &tp->t_wsel);
   1459 	}
   1460 
   1461 	mutex_spin_exit(&tty_lock);
   1462 
   1463 	return (revents);
   1464 }
   1465 
   1466 static void
   1467 filt_ttyrdetach(struct knote *kn)
   1468 {
   1469 	struct tty	*tp;
   1470 
   1471 	tp = kn->kn_hook;
   1472 	mutex_spin_enter(&tty_lock);
   1473 	SLIST_REMOVE(&tp->t_rsel.sel_klist, kn, knote, kn_selnext);
   1474 	mutex_spin_exit(&tty_lock);
   1475 }
   1476 
   1477 static int
   1478 filt_ttyread(struct knote *kn, long hint)
   1479 {
   1480 	struct tty	*tp;
   1481 
   1482 	tp = kn->kn_hook;
   1483 	if ((hint & NOTE_SUBMIT) == 0)
   1484 		mutex_spin_enter(&tty_lock);
   1485 	kn->kn_data = ttnread(tp);
   1486 	if ((hint & NOTE_SUBMIT) == 0)
   1487 		mutex_spin_exit(&tty_lock);
   1488 	return (kn->kn_data > 0);
   1489 }
   1490 
   1491 static void
   1492 filt_ttywdetach(struct knote *kn)
   1493 {
   1494 	struct tty	*tp;
   1495 
   1496 	tp = kn->kn_hook;
   1497 	mutex_spin_enter(&tty_lock);
   1498 	SLIST_REMOVE(&tp->t_wsel.sel_klist, kn, knote, kn_selnext);
   1499 	mutex_spin_exit(&tty_lock);
   1500 }
   1501 
   1502 static int
   1503 filt_ttywrite(struct knote *kn, long hint)
   1504 {
   1505 	struct tty	*tp;
   1506 	int		canwrite;
   1507 
   1508 	tp = kn->kn_hook;
   1509 	if ((hint & NOTE_SUBMIT) == 0)
   1510 		mutex_spin_enter(&tty_lock);
   1511 	kn->kn_data = tp->t_outq.c_cn - tp->t_outq.c_cc;
   1512 	canwrite = (tp->t_outq.c_cc <= tp->t_lowat) && CONNECTED(tp);
   1513 	if ((hint & NOTE_SUBMIT) == 0)
   1514 		mutex_spin_exit(&tty_lock);
   1515 	return (canwrite);
   1516 }
   1517 
   1518 static const struct filterops ttyread_filtops = {
   1519 	.f_isfd = 1,
   1520 	.f_attach = NULL,
   1521 	.f_detach = filt_ttyrdetach,
   1522 	.f_event = filt_ttyread,
   1523 };
   1524 
   1525 static const struct filterops ttywrite_filtops = {
   1526 	.f_isfd = 1,
   1527 	.f_attach = NULL,
   1528 	.f_detach = filt_ttywdetach,
   1529 	.f_event = filt_ttywrite,
   1530 };
   1531 
   1532 int
   1533 ttykqfilter(dev_t dev, struct knote *kn)
   1534 {
   1535 	struct tty	*tp;
   1536 	struct klist	*klist;
   1537 
   1538 	if ((tp = cdev_tty(dev)) == NULL)
   1539 		return (ENXIO);
   1540 
   1541 	switch (kn->kn_filter) {
   1542 	case EVFILT_READ:
   1543 		klist = &tp->t_rsel.sel_klist;
   1544 		kn->kn_fop = &ttyread_filtops;
   1545 		break;
   1546 	case EVFILT_WRITE:
   1547 		klist = &tp->t_wsel.sel_klist;
   1548 		kn->kn_fop = &ttywrite_filtops;
   1549 		break;
   1550 	default:
   1551 		return EINVAL;
   1552 	}
   1553 
   1554 	kn->kn_hook = tp;
   1555 
   1556 	mutex_spin_enter(&tty_lock);
   1557 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
   1558 	mutex_spin_exit(&tty_lock);
   1559 
   1560 	return (0);
   1561 }
   1562 
   1563 /*
   1564  * Find the number of chars ready to be read from this tty.
   1565  * Call with the tty lock held.
   1566  */
   1567 static int
   1568 ttnread(struct tty *tp)
   1569 {
   1570 	int	nread;
   1571 
   1572 	KASSERT(mutex_owned(&tty_lock));
   1573 
   1574 	if (ISSET(tp->t_lflag, PENDIN))
   1575 		ttypend(tp);
   1576 	nread = tp->t_canq.c_cc;
   1577 	if (!ISSET(tp->t_lflag, ICANON)) {
   1578 		nread += tp->t_rawq.c_cc;
   1579 		if (nread < tp->t_cc[VMIN] && !tp->t_cc[VTIME])
   1580 			nread = 0;
   1581 	}
   1582 	return (nread);
   1583 }
   1584 
   1585 /*
   1586  * Wait for output to drain, or if this times out, flush it.
   1587  */
   1588 static int
   1589 ttywait_timo(struct tty *tp, int timo)
   1590 {
   1591 	int	error;
   1592 
   1593 	error = 0;
   1594 
   1595 	mutex_spin_enter(&tty_lock);
   1596 	while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
   1597 	    CONNECTED(tp) && tp->t_oproc) {
   1598 		(*tp->t_oproc)(tp);
   1599 		error = ttysleep(tp, &tp->t_outcv, true, timo);
   1600 		if (error == EWOULDBLOCK)
   1601 			ttyflush(tp, FWRITE);
   1602 		if (error)
   1603 			break;
   1604 	}
   1605 	mutex_spin_exit(&tty_lock);
   1606 
   1607 	return (error);
   1608 }
   1609 
   1610 /*
   1611  * Wait for output to drain.
   1612  */
   1613 int
   1614 ttywait(struct tty *tp)
   1615 {
   1616 	return ttywait_timo(tp, 0);
   1617 }
   1618 
   1619 /*
   1620  * Flush if successfully wait.
   1621  */
   1622 int
   1623 ttywflush(struct tty *tp)
   1624 {
   1625 	int	error;
   1626 
   1627 	error = ttywait_timo(tp, 5 * hz);
   1628 	if (error == 0 || error == EWOULDBLOCK) {
   1629 		mutex_spin_enter(&tty_lock);
   1630 		ttyflush(tp, FREAD);
   1631 		mutex_spin_exit(&tty_lock);
   1632 	}
   1633 	return (error);
   1634 }
   1635 
   1636 /*
   1637  * Flush tty read and/or write queues, notifying anyone waiting.
   1638  * Call with the tty lock held.
   1639  */
   1640 void
   1641 ttyflush(struct tty *tp, int rw)
   1642 {
   1643 
   1644 	KASSERT(mutex_owned(&tty_lock));
   1645 
   1646 	if (rw & FREAD) {
   1647 		FLUSHQ(&tp->t_canq);
   1648 		FLUSHQ(&tp->t_rawq);
   1649 		tp->t_rocount = 0;
   1650 		tp->t_rocol = 0;
   1651 		CLR(tp->t_state, TS_LOCAL);
   1652 		ttwakeup(tp);
   1653 	}
   1654 	if (rw & FWRITE) {
   1655 		CLR(tp->t_state, TS_TTSTOP);
   1656 		cdev_stop(tp, rw);
   1657 		FLUSHQ(&tp->t_outq);
   1658 		cv_broadcast(&tp->t_outcv);
   1659 		selnotify(&tp->t_wsel, 0, NOTE_SUBMIT);
   1660 	}
   1661 }
   1662 
   1663 /*
   1664  * Copy in the default termios characters.
   1665  */
   1666 void
   1667 ttychars(struct tty *tp)
   1668 {
   1669 
   1670 	memcpy(tp->t_cc, ttydefchars, sizeof(ttydefchars));
   1671 }
   1672 
   1673 /*
   1674  * Send stop character on input overflow.
   1675  * Call with the tty lock held.
   1676  */
   1677 static void
   1678 ttyblock(struct tty *tp)
   1679 {
   1680 	int	total;
   1681 
   1682 	KASSERT(mutex_owned(&tty_lock));
   1683 
   1684 	total = tp->t_rawq.c_cc + tp->t_canq.c_cc;
   1685 	if (tp->t_rawq.c_cc > TTYHOG) {
   1686 		ttyflush(tp, FREAD | FWRITE);
   1687 		CLR(tp->t_state, TS_TBLOCK);
   1688 	}
   1689 	/*
   1690 	 * Block further input iff: current input > threshold
   1691 	 * AND input is available to user program.
   1692 	 */
   1693 	if (total >= TTYHOG / 2 &&
   1694 	    !ISSET(tp->t_state, TS_TBLOCK) &&
   1695 	    (!ISSET(tp->t_lflag, ICANON) || tp->t_canq.c_cc > 0)) {
   1696 		if (ISSET(tp->t_iflag, IXOFF) &&
   1697 		    tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
   1698 		    putc(tp->t_cc[VSTOP], &tp->t_outq) == 0) {
   1699 			SET(tp->t_state, TS_TBLOCK);
   1700 			ttstart(tp);
   1701 		}
   1702 		/* Try to block remote output via hardware flow control. */
   1703 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
   1704 		    (*tp->t_hwiflow)(tp, 1) != 0)
   1705 			SET(tp->t_state, TS_TBLOCK);
   1706 	}
   1707 }
   1708 
   1709 /*
   1710  * Delayed line discipline output
   1711  */
   1712 void
   1713 ttrstrt(void *tp_arg)
   1714 {
   1715 	struct tty	*tp;
   1716 
   1717 #ifdef DIAGNOSTIC
   1718 	if (tp_arg == NULL)
   1719 		panic("ttrstrt");
   1720 #endif
   1721 	tp = tp_arg;
   1722 	mutex_spin_enter(&tty_lock);
   1723 
   1724 	CLR(tp->t_state, TS_TIMEOUT);
   1725 	ttstart(tp); /* XXX - Shouldn't this be tp->l_start(tp)? */
   1726 
   1727 	mutex_spin_exit(&tty_lock);
   1728 }
   1729 
   1730 /*
   1731  * start a line discipline
   1732  * Always call with tty lock held?
   1733  */
   1734 int
   1735 ttstart(struct tty *tp)
   1736 {
   1737 
   1738 	if (tp->t_oproc != NULL)	/* XXX: Kludge for pty. */
   1739 		(*tp->t_oproc)(tp);
   1740 	return (0);
   1741 }
   1742 
   1743 /*
   1744  * "close" a line discipline
   1745  */
   1746 int
   1747 ttylclose(struct tty *tp, int flag)
   1748 {
   1749 
   1750 	if (flag & FNONBLOCK) {
   1751 		mutex_spin_enter(&tty_lock);
   1752 		ttyflush(tp, FREAD | FWRITE);
   1753 		mutex_spin_exit(&tty_lock);
   1754 	} else
   1755 		ttywflush(tp);
   1756 	return (0);
   1757 }
   1758 
   1759 /*
   1760  * Handle modem control transition on a tty.
   1761  * Flag indicates new state of carrier.
   1762  * Returns 0 if the line should be turned off, otherwise 1.
   1763  */
   1764 int
   1765 ttymodem(struct tty *tp, int flag)
   1766 {
   1767 
   1768 	mutex_spin_enter(&tty_lock);
   1769 	if (flag == 0) {
   1770 		if (ISSET(tp->t_state, TS_CARR_ON)) {
   1771 			/*
   1772 			 * Lost carrier.
   1773 			 */
   1774 			CLR(tp->t_state, TS_CARR_ON);
   1775 			if (ISSET(tp->t_state, TS_ISOPEN) && !CONNECTED(tp)) {
   1776 				ttysig(tp, TTYSIG_LEADER, SIGHUP);
   1777 				ttyflush(tp, FREAD | FWRITE);
   1778 				mutex_spin_exit(&tty_lock);
   1779 				return (0);
   1780 			}
   1781 		}
   1782 	} else {
   1783 		if (!ISSET(tp->t_state, TS_CARR_ON)) {
   1784 			/*
   1785 			 * Carrier now on.
   1786 			 */
   1787 			SET(tp->t_state, TS_CARR_ON);
   1788 			ttwakeup(tp);
   1789 		}
   1790 	}
   1791 	mutex_spin_exit(&tty_lock);
   1792 
   1793 	return (1);
   1794 }
   1795 
   1796 /*
   1797  * Default modem control routine (for other line disciplines).
   1798  * Return argument flag, to turn off device on carrier drop.
   1799  */
   1800 int
   1801 nullmodem(struct tty *tp, int flag)
   1802 {
   1803 
   1804 	mutex_spin_enter(&tty_lock);
   1805 	if (flag)
   1806 		SET(tp->t_state, TS_CARR_ON);
   1807 	else {
   1808 		CLR(tp->t_state, TS_CARR_ON);
   1809 		if (!CONNECTED(tp)) {
   1810 			ttysig(tp, TTYSIG_LEADER, SIGHUP);
   1811 			mutex_spin_exit(&tty_lock);
   1812 			return (0);
   1813 		}
   1814 	}
   1815 	mutex_spin_exit(&tty_lock);
   1816 
   1817 	return (1);
   1818 }
   1819 
   1820 /*
   1821  * Reinput pending characters after state switch.
   1822  */
   1823 void
   1824 ttypend(struct tty *tp)
   1825 {
   1826 	struct clist	tq;
   1827 	int		c;
   1828 
   1829 	KASSERT(mutex_owned(&tty_lock));
   1830 
   1831 	CLR(tp->t_lflag, PENDIN);
   1832 	SET(tp->t_state, TS_TYPEN);
   1833 	tq = tp->t_rawq;
   1834 	tp->t_rawq.c_cc = 0;
   1835 	tp->t_rawq.c_cf = tp->t_rawq.c_cl = 0;
   1836 	while ((c = getc(&tq)) >= 0)
   1837 		ttyinput_wlock(c, tp);
   1838 	CLR(tp->t_state, TS_TYPEN);
   1839 }
   1840 
   1841 /*
   1842  * Process a read call on a tty device.
   1843  */
   1844 int
   1845 ttread(struct tty *tp, struct uio *uio, int flag)
   1846 {
   1847 	struct clist	*qp;
   1848 	u_char		*cc;
   1849 	struct proc	*p;
   1850 	int		c, first, error, has_stime, last_cc;
   1851 	long		lflag, slp;
   1852 	struct timeval	now, stime;
   1853 
   1854 	if (uio->uio_resid == 0)
   1855 		return 0;
   1856 
   1857 	stime.tv_usec = 0;	/* XXX gcc */
   1858 	stime.tv_sec = 0;	/* XXX gcc */
   1859 
   1860 	cc = tp->t_cc;
   1861 	p = curproc;
   1862 	error = 0;
   1863 	has_stime = 0;
   1864 	last_cc = 0;
   1865 	slp = 0;
   1866 
   1867  loop:
   1868 	mutex_spin_enter(&tty_lock);
   1869 	lflag = tp->t_lflag;
   1870 	/*
   1871 	 * take pending input first
   1872 	 */
   1873 	if (ISSET(lflag, PENDIN))
   1874 		ttypend(tp);
   1875 
   1876 	/*
   1877 	 * Hang process if it's in the background.
   1878 	 */
   1879 	if (isbackground(p, tp)) {
   1880 		if (sigismasked(curlwp, SIGTTIN) ||
   1881 		    p->p_lflag & PL_PPWAIT || p->p_pgrp->pg_jobc == 0) {
   1882 			mutex_spin_exit(&tty_lock);
   1883 			return (EIO);
   1884 		}
   1885 		mutex_spin_exit(&tty_lock);
   1886 
   1887 		mutex_enter(proc_lock);
   1888 		pgsignal(p->p_pgrp, SIGTTIN, 1);
   1889 		mutex_exit(proc_lock);
   1890 
   1891 		mutex_spin_enter(&tty_lock);
   1892 		error = ttypause(tp, hz);
   1893 		mutex_spin_exit(&tty_lock);
   1894 		if (error)
   1895 			return (error);
   1896 		goto loop;
   1897 	}
   1898 
   1899 	if (!ISSET(lflag, ICANON)) {
   1900 		int m = cc[VMIN];
   1901 		long t = cc[VTIME];
   1902 
   1903 		qp = &tp->t_rawq;
   1904 		/*
   1905 		 * Check each of the four combinations.
   1906 		 * (m > 0 && t == 0) is the normal read case.
   1907 		 * It should be fairly efficient, so we check that and its
   1908 		 * companion case (m == 0 && t == 0) first.
   1909 		 * For the other two cases, we compute the target sleep time
   1910 		 * into slp.
   1911 		 */
   1912 		if (t == 0) {
   1913 			if (qp->c_cc < m)
   1914 				goto sleep;
   1915 			goto read;
   1916 		}
   1917 		t *= hz;		/* time in deca-ticks */
   1918 /*
   1919  * Time difference in deca-ticks, split division to avoid numeric overflow.
   1920  * Ok for hz < ~200kHz
   1921  */
   1922 #define	diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 10 * hz + \
   1923 			 ((t1).tv_usec - (t2).tv_usec) / 100 * hz / 1000)
   1924 		if (m > 0) {
   1925 			if (qp->c_cc <= 0)
   1926 				goto sleep;
   1927 			if (qp->c_cc >= m)
   1928 				goto read;
   1929 			if (!has_stime) {
   1930 				/* first character, start timer */
   1931 				has_stime = 1;
   1932 				getmicrotime(&stime);
   1933 				slp = t;
   1934 			} else if (qp->c_cc > last_cc) {
   1935 				/* got a character, restart timer */
   1936 				getmicrotime(&stime);
   1937 				slp = t;
   1938 			} else {
   1939 				/* nothing, check expiration */
   1940 				getmicrotime(&now);
   1941 				slp = t - diff(now, stime);
   1942 			}
   1943 		} else {	/* m == 0 */
   1944 			if (qp->c_cc > 0)
   1945 				goto read;
   1946 			if (!has_stime) {
   1947 				has_stime = 1;
   1948 				getmicrotime(&stime);
   1949 				slp = t;
   1950 			} else {
   1951 				getmicrotime(&now);
   1952 				slp = t - diff(now, stime);
   1953 			}
   1954 		}
   1955 		last_cc = qp->c_cc;
   1956 #undef diff
   1957 		if (slp > 0) {
   1958 			/*
   1959 			 * Convert deca-ticks back to ticks.
   1960 			 * Rounding down may make us wake up just short
   1961 			 * of the target, so we round up.
   1962 			 * Maybe we should do 'slp/10 + 1' because the
   1963 			 * first tick maybe almost immediate.
   1964 			 * However it is more useful for a program that sets
   1965 			 * VTIME=10 to wakeup every second not every 1.01
   1966 			 * seconds (if hz=100).
   1967 			 */
   1968 			slp = (slp + 9)/ 10;
   1969 			goto sleep;
   1970 		}
   1971 	} else if ((qp = &tp->t_canq)->c_cc <= 0) {
   1972 		int	carrier;
   1973 
   1974  sleep:
   1975 		/*
   1976 		 * If there is no input, sleep on rawq
   1977 		 * awaiting hardware receipt and notification.
   1978 		 * If we have data, we don't need to check for carrier.
   1979 		 */
   1980 		carrier = CONNECTED(tp);
   1981 		if (!carrier && ISSET(tp->t_state, TS_ISOPEN)) {
   1982 			mutex_spin_exit(&tty_lock);
   1983 			return (0);	/* EOF */
   1984 		}
   1985 		if (!has_stime || slp <= 0) {
   1986 			if (flag & IO_NDELAY) {
   1987 				mutex_spin_exit(&tty_lock);
   1988 				return (EWOULDBLOCK);
   1989 			}
   1990 		}
   1991 		error = ttysleep(tp, &tp->t_rawcv, true, slp);
   1992 		mutex_spin_exit(&tty_lock);
   1993 		/* VMIN == 0: any quantity read satisfies */
   1994 		if (cc[VMIN] == 0 && error == EWOULDBLOCK)
   1995 			return (0);
   1996 		if (error && error != EWOULDBLOCK)
   1997 			return (error);
   1998 		goto loop;
   1999 	}
   2000  read:
   2001 
   2002 	/*
   2003 	 * Input present, check for input mapping and processing.
   2004 	 */
   2005 	first = 1;
   2006 	while ((c = getc(qp)) >= 0) {
   2007 		/*
   2008 		 * delayed suspend (^Y)
   2009 		 */
   2010 		if (CCEQ(cc[VDSUSP], c) &&
   2011 		    ISSET(lflag, IEXTEN|ISIG) == (IEXTEN|ISIG)) {
   2012 			ttysig(tp, TTYSIG_PG1, SIGTSTP);
   2013 			if (first) {
   2014 				error = ttypause(tp, hz);
   2015 				if (error)
   2016 					break;
   2017 				mutex_spin_exit(&tty_lock);
   2018 				goto loop;
   2019 			}
   2020 			break;
   2021 		}
   2022 		/*
   2023 		 * Interpret EOF only in canonical mode.
   2024 		 */
   2025 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
   2026 			break;
   2027 		/*
   2028 		 * Give user character.
   2029 		 */
   2030 		mutex_spin_exit(&tty_lock);
   2031  		error = ureadc(c, uio);
   2032 		mutex_spin_enter(&tty_lock);
   2033 		if (error)
   2034 			break;
   2035  		if (uio->uio_resid == 0)
   2036 			break;
   2037 		/*
   2038 		 * In canonical mode check for a "break character"
   2039 		 * marking the end of a "line of input".
   2040 		 */
   2041 		if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
   2042 			break;
   2043 		first = 0;
   2044 	}
   2045 
   2046 	/*
   2047 	 * Look to unblock output now that (presumably)
   2048 	 * the input queue has gone down.
   2049 	 */
   2050 	if (ISSET(tp->t_state, TS_TBLOCK) && tp->t_rawq.c_cc < TTYHOG / 5) {
   2051 		if (ISSET(tp->t_iflag, IXOFF) &&
   2052 		    cc[VSTART] != _POSIX_VDISABLE &&
   2053 		    putc(cc[VSTART], &tp->t_outq) == 0) {
   2054 			CLR(tp->t_state, TS_TBLOCK);
   2055 			ttstart(tp);
   2056 		}
   2057 		/* Try to unblock remote output via hardware flow control. */
   2058 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
   2059 		    (*tp->t_hwiflow)(tp, 0) != 0)
   2060 			CLR(tp->t_state, TS_TBLOCK);
   2061 	}
   2062 	mutex_spin_exit(&tty_lock);
   2063 
   2064 	return (error);
   2065 }
   2066 
   2067 /*
   2068  * Check the output queue on tp for space for a kernel message (from uprintf
   2069  * or tprintf).  Allow some space over the normal hiwater mark so we don't
   2070  * lose messages due to normal flow control, but don't let the tty run amok.
   2071  * Sleeps here are not interruptible, but we return prematurely if new signals
   2072  * arrive.
   2073  * Call with tty lock held.
   2074  */
   2075 static int
   2076 ttycheckoutq_wlock(struct tty *tp, int wait)
   2077 {
   2078 	int	hiwat, error;
   2079 
   2080 	KASSERT(mutex_owned(&tty_lock));
   2081 
   2082 	hiwat = tp->t_hiwat;
   2083 	if (tp->t_outq.c_cc > hiwat + 200)
   2084 		while (tp->t_outq.c_cc > hiwat) {
   2085 			ttstart(tp);
   2086 			if (wait == 0)
   2087 				return (0);
   2088 			error = ttysleep(tp, &tp->t_outcv, true, hz);
   2089 			if (error == EINTR)
   2090 				wait = 0;
   2091 		}
   2092 
   2093 	return (1);
   2094 }
   2095 
   2096 int
   2097 ttycheckoutq(struct tty *tp, int wait)
   2098 {
   2099 	int	r;
   2100 
   2101 	mutex_spin_enter(&tty_lock);
   2102 	r = ttycheckoutq_wlock(tp, wait);
   2103 	mutex_spin_exit(&tty_lock);
   2104 
   2105 	return (r);
   2106 }
   2107 
   2108 /*
   2109  * Process a write call on a tty device.
   2110  */
   2111 int
   2112 ttwrite(struct tty *tp, struct uio *uio, int flag)
   2113 {
   2114 	u_char		*cp;
   2115 	struct proc	*p;
   2116 	int		cc, ce, i, hiwat, error;
   2117 	u_char		obuf[OBUFSIZ];
   2118 
   2119 	cp = NULL;
   2120 	hiwat = tp->t_hiwat;
   2121 	error = 0;
   2122 	cc = 0;
   2123  loop:
   2124 	mutex_spin_enter(&tty_lock);
   2125 	if (!CONNECTED(tp)) {
   2126 		if (ISSET(tp->t_state, TS_ISOPEN)) {
   2127 			mutex_spin_exit(&tty_lock);
   2128 			return (EIO);
   2129 		} else if (flag & IO_NDELAY) {
   2130 			mutex_spin_exit(&tty_lock);
   2131 			error = EWOULDBLOCK;
   2132 			goto out;
   2133 		} else {
   2134 			/* Sleep awaiting carrier. */
   2135 			error = ttysleep(tp, &tp->t_rawcv, true, 0);
   2136 			mutex_spin_exit(&tty_lock);
   2137 			if (error)
   2138 				goto out;
   2139 			goto loop;
   2140 		}
   2141 	}
   2142 
   2143 	/*
   2144 	 * Hang the process if it's in the background.
   2145 	 */
   2146 	p = curproc;
   2147 	if (isbackground(p, tp) &&
   2148 	    ISSET(tp->t_lflag, TOSTOP) && (p->p_lflag & PL_PPWAIT) == 0 &&
   2149 	    !sigismasked(curlwp, SIGTTOU)) {
   2150 		if (p->p_pgrp->pg_jobc == 0) {
   2151 			error = EIO;
   2152 			mutex_spin_exit(&tty_lock);
   2153 			goto out;
   2154 		}
   2155 		mutex_spin_exit(&tty_lock);
   2156 
   2157 		mutex_enter(proc_lock);
   2158 		pgsignal(p->p_pgrp, SIGTTOU, 1);
   2159 		mutex_exit(proc_lock);
   2160 
   2161 		mutex_spin_enter(&tty_lock);
   2162 		error = ttypause(tp, hz);
   2163 		mutex_spin_exit(&tty_lock);
   2164 		if (error)
   2165 			goto out;
   2166 		goto loop;
   2167 	}
   2168 	mutex_spin_exit(&tty_lock);
   2169 
   2170 	/*
   2171 	 * Process the user's data in at most OBUFSIZ chunks.  Perform any
   2172 	 * output translation.  Keep track of high water mark, sleep on
   2173 	 * overflow awaiting device aid in acquiring new space.
   2174 	 */
   2175 	while (uio->uio_resid > 0 || cc > 0) {
   2176 		if (ISSET(tp->t_lflag, FLUSHO)) {
   2177 			uio->uio_resid = 0;
   2178 			return (0);
   2179 		}
   2180 		if (tp->t_outq.c_cc > hiwat)
   2181 			goto ovhiwat;
   2182 		/*
   2183 		 * Grab a hunk of data from the user, unless we have some
   2184 		 * leftover from last time.
   2185 		 */
   2186 		if (cc == 0) {
   2187 			cc = min(uio->uio_resid, OBUFSIZ);
   2188 			cp = obuf;
   2189 			error = uiomove(cp, cc, uio);
   2190 			if (error) {
   2191 				cc = 0;
   2192 				goto out;
   2193 			}
   2194 		}
   2195 		/*
   2196 		 * If nothing fancy need be done, grab those characters we
   2197 		 * can handle without any of ttyoutput's processing and
   2198 		 * just transfer them to the output q.  For those chars
   2199 		 * which require special processing (as indicated by the
   2200 		 * bits in char_type), call ttyoutput.  After processing
   2201 		 * a hunk of data, look for FLUSHO so ^O's will take effect
   2202 		 * immediately.
   2203 		 */
   2204 		mutex_spin_enter(&tty_lock);
   2205 		while (cc > 0) {
   2206 			if (!ISSET(tp->t_oflag, OPOST))
   2207 				ce = cc;
   2208 			else {
   2209 				ce = cc - scanc((u_int)cc, cp, char_type,
   2210 				    CCLASSMASK);
   2211 				/*
   2212 				 * If ce is zero, then we're processing
   2213 				 * a special character through ttyoutput.
   2214 				 */
   2215 				if (ce == 0) {
   2216 					tp->t_rocount = 0;
   2217 					if (ttyoutput(*cp, tp) >= 0) {
   2218 						/* out of space */
   2219 						mutex_spin_exit(&tty_lock);
   2220 						goto overfull;
   2221 					}
   2222 					cp++;
   2223 					cc--;
   2224 					if (ISSET(tp->t_lflag, FLUSHO) ||
   2225 					    tp->t_outq.c_cc > hiwat) {
   2226 						mutex_spin_exit(&tty_lock);
   2227 						goto ovhiwat;
   2228 					}
   2229 					continue;
   2230 				}
   2231 			}
   2232 			/*
   2233 			 * A bunch of normal characters have been found.
   2234 			 * Transfer them en masse to the output queue and
   2235 			 * continue processing at the top of the loop.
   2236 			 * If there are any further characters in this
   2237 			 * <= OBUFSIZ chunk, the first should be a character
   2238 			 * requiring special handling by ttyoutput.
   2239 			 */
   2240 			tp->t_rocount = 0;
   2241 			i = b_to_q(cp, ce, &tp->t_outq);
   2242 			ce -= i;
   2243 			tp->t_column += ce;
   2244 			cp += ce, cc -= ce, tk_nout += ce;
   2245 			tp->t_outcc += ce;
   2246 			if (i > 0) {
   2247 				/* out of space */
   2248 				mutex_spin_exit(&tty_lock);
   2249 				goto overfull;
   2250 			}
   2251 			if (ISSET(tp->t_lflag, FLUSHO) ||
   2252 			    tp->t_outq.c_cc > hiwat)
   2253 				break;
   2254 		}
   2255 		ttstart(tp);
   2256 		mutex_spin_exit(&tty_lock);
   2257 	}
   2258 
   2259  out:
   2260 	/*
   2261 	 * If cc is nonzero, we leave the uio structure inconsistent, as the
   2262 	 * offset and iov pointers have moved forward, but it doesn't matter
   2263 	 * (the call will either return short or restart with a new uio).
   2264 	 */
   2265 	uio->uio_resid += cc;
   2266 	return (error);
   2267 
   2268  overfull:
   2269 	/*
   2270 	 * Since we are using ring buffers, if we can't insert any more into
   2271 	 * the output queue, we can assume the ring is full and that someone
   2272 	 * forgot to set the high water mark correctly.  We set it and then
   2273 	 * proceed as normal.
   2274 	 */
   2275 	hiwat = tp->t_outq.c_cc - 1;
   2276 
   2277  ovhiwat:
   2278 	mutex_spin_enter(&tty_lock);
   2279 	ttstart(tp);
   2280 	/*
   2281 	 * This can only occur if FLUSHO is set in t_lflag,
   2282 	 * or if ttstart/oproc is synchronous (or very fast).
   2283 	 */
   2284 	if (tp->t_outq.c_cc <= hiwat) {
   2285 		mutex_spin_exit(&tty_lock);
   2286 		goto loop;
   2287 	}
   2288 	if (flag & IO_NDELAY) {
   2289 		mutex_spin_exit(&tty_lock);
   2290 		error = EWOULDBLOCK;
   2291 		goto out;
   2292 	}
   2293 	error = ttysleep(tp, &tp->t_outcv, true, 0);
   2294 	mutex_spin_exit(&tty_lock);
   2295 	if (error)
   2296 		goto out;
   2297 	goto loop;
   2298 }
   2299 
   2300 /*
   2301  * Try to pull more output from the producer.  Return non-zero if
   2302  * there is output ready to be sent.
   2303  */
   2304 bool
   2305 ttypull(struct tty *tp)
   2306 {
   2307 
   2308 	/* XXXSMP not yet KASSERT(mutex_owned(&tty_lock)); */
   2309 
   2310 	if (tp->t_outq.c_cc <= tp->t_lowat) {
   2311 		cv_broadcast(&tp->t_outcv);
   2312 		selnotify(&tp->t_wsel, 0, NOTE_SUBMIT);
   2313 	}
   2314 	return tp->t_outq.c_cc != 0;
   2315 }
   2316 
   2317 /*
   2318  * Rubout one character from the rawq of tp
   2319  * as cleanly as possible.
   2320  * Called with tty lock held.
   2321  */
   2322 void
   2323 ttyrub(int c, struct tty *tp)
   2324 {
   2325 	u_char	*cp;
   2326 	int	savecol, tabc;
   2327 
   2328 	KASSERT(mutex_owned(&tty_lock));
   2329 
   2330 	if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
   2331 		return;
   2332 	CLR(tp->t_lflag, FLUSHO);
   2333 	if (ISSET(tp->t_lflag, ECHOE)) {
   2334 		if (tp->t_rocount == 0) {
   2335 			/*
   2336 			 * Screwed by ttwrite; retype
   2337 			 */
   2338 			ttyretype(tp);
   2339 			return;
   2340 		}
   2341 		if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
   2342 			ttyrubo(tp, 2);
   2343 		else {
   2344 			CLR(c, ~TTY_CHARMASK);
   2345 			switch (CCLASS(c)) {
   2346 			case ORDINARY:
   2347 				ttyrubo(tp, 1);
   2348 				break;
   2349 			case BACKSPACE:
   2350 			case CONTROL:
   2351 			case NEWLINE:
   2352 			case RETURN:
   2353 			case VTAB:
   2354 				if (ISSET(tp->t_lflag, ECHOCTL))
   2355 					ttyrubo(tp, 2);
   2356 				break;
   2357 			case TAB:
   2358 				if (tp->t_rocount < tp->t_rawq.c_cc) {
   2359 					ttyretype(tp);
   2360 					return;
   2361 				}
   2362 				savecol = tp->t_column;
   2363 				SET(tp->t_state, TS_CNTTB);
   2364 				SET(tp->t_lflag, FLUSHO);
   2365 				tp->t_column = tp->t_rocol;
   2366 				for (cp = firstc(&tp->t_rawq, &tabc); cp;
   2367 				    cp = nextc(&tp->t_rawq, cp, &tabc))
   2368 					ttyecho(tabc, tp);
   2369 				CLR(tp->t_lflag, FLUSHO);
   2370 				CLR(tp->t_state, TS_CNTTB);
   2371 
   2372 				/* savecol will now be length of the tab. */
   2373 				savecol -= tp->t_column;
   2374 				tp->t_column += savecol;
   2375 				if (savecol > 8)
   2376 					savecol = 8;	/* overflow screw */
   2377 				while (--savecol >= 0)
   2378 					(void)ttyoutput('\b', tp);
   2379 				break;
   2380 			default:			/* XXX */
   2381 				(void)printf("ttyrub: would panic c = %d, "
   2382 				    "val = %d\n", c, CCLASS(c));
   2383 			}
   2384 		}
   2385 	} else if (ISSET(tp->t_lflag, ECHOPRT)) {
   2386 		if (!ISSET(tp->t_state, TS_ERASE)) {
   2387 			SET(tp->t_state, TS_ERASE);
   2388 			(void)ttyoutput('\\', tp);
   2389 		}
   2390 		ttyecho(c, tp);
   2391 	} else
   2392 		ttyecho(tp->t_cc[VERASE], tp);
   2393 	--tp->t_rocount;
   2394 }
   2395 
   2396 /*
   2397  * Back over cnt characters, erasing them.
   2398  * Called with tty lock held.
   2399  */
   2400 static void
   2401 ttyrubo(struct tty *tp, int cnt)
   2402 {
   2403 
   2404 	KASSERT(mutex_owned(&tty_lock));
   2405 
   2406 	while (cnt-- > 0) {
   2407 		(void)ttyoutput('\b', tp);
   2408 		(void)ttyoutput(' ', tp);
   2409 		(void)ttyoutput('\b', tp);
   2410 	}
   2411 }
   2412 
   2413 /*
   2414  * ttyretype --
   2415  *	Reprint the rawq line.  Note, it is assumed that c_cc has already
   2416  *	been checked.
   2417  *
   2418  * Called with tty lock held.
   2419  */
   2420 void
   2421 ttyretype(struct tty *tp)
   2422 {
   2423 	u_char	*cp;
   2424 	int	c;
   2425 
   2426 	KASSERT(mutex_owned(&tty_lock));
   2427 
   2428 	/* Echo the reprint character. */
   2429 	if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
   2430 		ttyecho(tp->t_cc[VREPRINT], tp);
   2431 
   2432 	(void)ttyoutput('\n', tp);
   2433 
   2434 	for (cp = firstc(&tp->t_canq, &c); cp; cp = nextc(&tp->t_canq, cp, &c))
   2435 		ttyecho(c, tp);
   2436 	for (cp = firstc(&tp->t_rawq, &c); cp; cp = nextc(&tp->t_rawq, cp, &c))
   2437 		ttyecho(c, tp);
   2438 	CLR(tp->t_state, TS_ERASE);
   2439 
   2440 	tp->t_rocount = tp->t_rawq.c_cc;
   2441 	tp->t_rocol = 0;
   2442 }
   2443 
   2444 /*
   2445  * Echo a typed character to the terminal.
   2446  * Called with tty lock held.
   2447  */
   2448 static void
   2449 ttyecho(int c, struct tty *tp)
   2450 {
   2451 
   2452 	KASSERT(mutex_owned(&tty_lock));
   2453 
   2454 	if (!ISSET(tp->t_state, TS_CNTTB))
   2455 		CLR(tp->t_lflag, FLUSHO);
   2456 	if ((!ISSET(tp->t_lflag, ECHO) &&
   2457 	    (!ISSET(tp->t_lflag, ECHONL) || c != '\n')) ||
   2458 	    ISSET(tp->t_lflag, EXTPROC))
   2459 		return;
   2460 	if (((ISSET(tp->t_lflag, ECHOCTL) &&
   2461 	    (ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n')) ||
   2462 	    ISSET(c, TTY_CHARMASK) == 0177)) {
   2463 		(void)ttyoutput('^', tp);
   2464 		CLR(c, ~TTY_CHARMASK);
   2465 		if (c == 0177)
   2466 			c = '?';
   2467 		else
   2468 			c += 'A' - 1;
   2469 	}
   2470 	(void)ttyoutput(c, tp);
   2471 }
   2472 
   2473 /*
   2474  * Wake up any readers on a tty.
   2475  * Called with tty lock held.
   2476  */
   2477 void
   2478 ttwakeup(struct tty *tp)
   2479 {
   2480 
   2481 	KASSERT(mutex_owned(&tty_lock));
   2482 
   2483 	selnotify(&tp->t_rsel, 0, NOTE_SUBMIT);
   2484 	if (ISSET(tp->t_state, TS_ASYNC))
   2485 		ttysig(tp, TTYSIG_PG2, SIGIO);
   2486 	cv_broadcast(&tp->t_rawcv);
   2487 }
   2488 
   2489 /*
   2490  * Look up a code for a specified speed in a conversion table;
   2491  * used by drivers to map software speed values to hardware parameters.
   2492  */
   2493 int
   2494 ttspeedtab(int speed, const struct speedtab *table)
   2495 {
   2496 
   2497 	for (; table->sp_speed != -1; table++)
   2498 		if (table->sp_speed == speed)
   2499 			return (table->sp_code);
   2500 	return (-1);
   2501 }
   2502 
   2503 /*
   2504  * Set tty hi and low water marks.
   2505  *
   2506  * Try to arrange the dynamics so there's about one second
   2507  * from hi to low water.
   2508  */
   2509 void
   2510 ttsetwater(struct tty *tp)
   2511 {
   2512 	int	cps, x;
   2513 
   2514 	/* XXX not yet KASSERT(mutex_owned(&tty_lock)); */
   2515 
   2516 #define	CLAMP(x, h, l)	((x) > h ? h : ((x) < l) ? l : (x))
   2517 
   2518 	cps = tp->t_ospeed / 10;
   2519 	tp->t_lowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
   2520 	x += cps;
   2521 	x = CLAMP(x, TTMAXHIWAT, TTMINHIWAT);
   2522 	tp->t_hiwat = roundup(x, TTROUND);
   2523 #undef	CLAMP
   2524 }
   2525 
   2526 /*
   2527  * Prepare report on state of foreground process group.
   2528  * Call with proc_lock held.
   2529  */
   2530 void
   2531 ttygetinfo(struct tty *tp, int fromsig, char *buf, size_t bufsz)
   2532 {
   2533 	struct lwp	*l;
   2534 	struct proc	*p, *pick = NULL;
   2535 	struct timeval	utime, stime;
   2536 	int		tmp;
   2537 	fixpt_t		pctcpu = 0;
   2538 	const char	*msg;
   2539 	char		lmsg[100];
   2540 	long		rss;
   2541 
   2542 	KASSERT(mutex_owned(proc_lock));
   2543 
   2544 	*buf = '\0';
   2545 
   2546 	if (tp->t_session == NULL)
   2547 		msg = "not a controlling terminal\n";
   2548 	else if (tp->t_pgrp == NULL)
   2549 		msg = "no foreground process group\n";
   2550 	else if ((p = LIST_FIRST(&tp->t_pgrp->pg_members)) == NULL)
   2551 		msg = "empty foreground process group\n";
   2552 	else {
   2553 		/* Pick interesting process. */
   2554 		for (; p != NULL; p = LIST_NEXT(p, p_pglist)) {
   2555 			struct proc *oldpick;
   2556 
   2557 			if (pick == NULL) {
   2558 				pick = p;
   2559 				continue;
   2560 			}
   2561 			if (pick->p_lock < p->p_lock) {
   2562 				mutex_enter(pick->p_lock);
   2563 				mutex_enter(p->p_lock);
   2564 			} else if (pick->p_lock > p->p_lock) {
   2565 				mutex_enter(p->p_lock);
   2566 				mutex_enter(pick->p_lock);
   2567 			} else
   2568 				mutex_enter(p->p_lock);
   2569 			oldpick = pick;
   2570 			if (proc_compare_wrapper(pick, p))
   2571 				pick = p;
   2572 			mutex_exit(p->p_lock);
   2573 			if (p->p_lock != oldpick->p_lock)
   2574 				mutex_exit(oldpick->p_lock);
   2575 		}
   2576 		if (fromsig &&
   2577 		    (SIGACTION_PS(pick->p_sigacts, SIGINFO).sa_flags &
   2578 		    SA_NOKERNINFO))
   2579 			return;
   2580 		msg = NULL;
   2581 	}
   2582 
   2583 	/* Print load average. */
   2584 	tmp = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
   2585 	snprintf(lmsg, sizeof(lmsg), "load: %d.%02d ", tmp / 100, tmp % 100);
   2586 	strlcat(buf, lmsg, bufsz);
   2587 
   2588 	if (pick == NULL) {
   2589 		strlcat(buf, msg, bufsz);
   2590 		return;
   2591 	}
   2592 
   2593 	snprintf(lmsg, sizeof(lmsg), " cmd: %s %d [", pick->p_comm,
   2594 	    pick->p_pid);
   2595 	strlcat(buf, lmsg, bufsz);
   2596 
   2597 	mutex_enter(pick->p_lock);
   2598 	LIST_FOREACH(l, &pick->p_lwps, l_sibling) {
   2599 		const char *lp;
   2600 		lwp_lock(l);
   2601 #ifdef LWP_PC
   2602 #define FMT_RUN "%#"PRIxVADDR
   2603 #define VAL_RUNNING (vaddr_t)LWP_PC(l)
   2604 #define VAL_RUNABLE (vaddr_t)LWP_PC(l)
   2605 #else
   2606 #define FMT_RUN "%s"
   2607 #define VAL_RUNNING "running"
   2608 #define VAL_RUNABLE "runnable"
   2609 #endif
   2610 		switch (l->l_stat) {
   2611 		case LSONPROC:
   2612 			snprintf(lmsg, sizeof(lmsg), FMT_RUN"/%d", VAL_RUNNING,
   2613 			    cpu_index(l->l_cpu));
   2614 			lp = lmsg;
   2615 			break;
   2616 		case LSRUN:
   2617 			snprintf(lmsg, sizeof(lmsg), FMT_RUN, VAL_RUNABLE);
   2618 			lp = lmsg;
   2619 			break;
   2620 		default:
   2621 			lp = l->l_wchan ? l->l_wmesg : "iowait";
   2622 			break;
   2623 		}
   2624 		strlcat(buf, lp, bufsz);
   2625 		strlcat(buf, LIST_NEXT(l, l_sibling) != NULL ? " " : "] ",
   2626 		    bufsz);
   2627 		pctcpu += l->l_pctcpu;
   2628 		lwp_unlock(l);
   2629 	}
   2630 	pctcpu += pick->p_pctcpu;
   2631 	calcru(pick, &utime, &stime, NULL, NULL);
   2632 	mutex_exit(pick->p_lock);
   2633 
   2634 	/* Round up and print user+system time, %CPU and RSS. */
   2635 	utime.tv_usec += 5000;
   2636 	if (utime.tv_usec >= 1000000) {
   2637 		utime.tv_sec += 1;
   2638 		utime.tv_usec -= 1000000;
   2639 	}
   2640 	stime.tv_usec += 5000;
   2641 	if (stime.tv_usec >= 1000000) {
   2642 		stime.tv_sec += 1;
   2643 		stime.tv_usec -= 1000000;
   2644 	}
   2645 #define	pgtok(a)	(((u_long) ((a) * PAGE_SIZE) / 1024))
   2646 	tmp = (pctcpu * 10000 + FSCALE / 2) >> FSHIFT;
   2647 	if (pick->p_stat == SIDL || P_ZOMBIE(pick))
   2648 		rss = 0;
   2649 	else
   2650 		rss = pgtok(vm_resident_count(pick->p_vmspace));
   2651 
   2652 	snprintf(lmsg, sizeof(lmsg), "%ld.%02ldu %ld.%02lds %d%% %ldk",
   2653 	    (long)utime.tv_sec, (long)utime.tv_usec / 10000,
   2654 	    (long)stime.tv_sec, (long)stime.tv_usec / 10000,
   2655 	    tmp / 100, rss);
   2656 	strlcat(buf, lmsg, bufsz);
   2657 }
   2658 
   2659 /*
   2660  * Print report on state of foreground process group.
   2661  * Call with tty_lock held.
   2662  */
   2663 void
   2664 ttyputinfo(struct tty *tp, char *buf)
   2665 {
   2666 
   2667 	KASSERT(mutex_owned(&tty_lock));
   2668 
   2669 	if (ttycheckoutq_wlock(tp, 0) == 0)
   2670 		return;
   2671 	ttyprintf_nolock(tp, "%s\n", buf);
   2672 	tp->t_rocount = 0;	/* so pending input will be retyped if BS */
   2673 }
   2674 
   2675 /*
   2676  * Returns 1 if p2 has a better chance being the active foreground process
   2677  * in a terminal instead of p1.
   2678  */
   2679 static int
   2680 proc_compare_wrapper(struct proc *p1, struct proc *p2)
   2681 {
   2682 	lwp_t *l1, *l2;
   2683 
   2684 	KASSERT(mutex_owned(p1->p_lock));
   2685 	KASSERT(mutex_owned(p2->p_lock));
   2686 
   2687 	if ((l1 = LIST_FIRST(&p1->p_lwps)) == NULL)
   2688 		return 1;
   2689 
   2690 	if ((l2 = LIST_FIRST(&p2->p_lwps)) == NULL)
   2691 		return 0;
   2692 
   2693 	return proc_compare(p1, l1, p2, l2);
   2694 }
   2695 
   2696 /*
   2697  * Output char to tty; console putchar style.
   2698  * Can be called with tty lock held through kprintf() machinery..
   2699  */
   2700 int
   2701 tputchar(int c, int flags, struct tty *tp)
   2702 {
   2703 	int r = 0;
   2704 
   2705 	if ((flags & NOLOCK) == 0)
   2706 		mutex_spin_enter(&tty_lock);
   2707 	if (!CONNECTED(tp)) {
   2708 		r = -1;
   2709 		goto out;
   2710 	}
   2711 	if (c == '\n')
   2712 		(void)ttyoutput('\r', tp);
   2713 	(void)ttyoutput(c, tp);
   2714 	ttstart(tp);
   2715 out:
   2716 	if ((flags & NOLOCK) == 0)
   2717 		mutex_spin_exit(&tty_lock);
   2718 	return (r);
   2719 }
   2720 
   2721 /*
   2722  * Sleep on chan, returning ERESTART if tty changed while we napped and
   2723  * returning any errors (e.g. EINTR/EWOULDBLOCK) reported by
   2724  * cv_timedwait(_sig).
   2725  * If the tty is revoked, restarting a pending call will redo validation done
   2726  * at the start of the call.
   2727  *
   2728  * Must be called with the tty lock held.
   2729  */
   2730 int
   2731 ttysleep(struct tty *tp, kcondvar_t *cv, bool catch_p, int timo)
   2732 {
   2733 	int	error;
   2734 	short	gen;
   2735 
   2736 	KASSERT(mutex_owned(&tty_lock));
   2737 
   2738 	gen = tp->t_gen;
   2739 	if (cv == NULL)
   2740 		error = kpause("ttypause", catch_p, timo, &tty_lock);
   2741 	else if (catch_p)
   2742 		error = cv_timedwait_sig(cv, &tty_lock, timo);
   2743 	else
   2744 		error = cv_timedwait(cv, &tty_lock, timo);
   2745 	if (error != 0)
   2746 		return (error);
   2747 	return (tp->t_gen == gen ? 0 : ERESTART);
   2748 }
   2749 
   2750 int
   2751 ttypause(struct tty *tp, int timo)
   2752 {
   2753 	int error;
   2754 
   2755 	error = ttysleep(tp, NULL, true, timo);
   2756 	if (error == EWOULDBLOCK)
   2757 		error = 0;
   2758 	return error;
   2759 }
   2760 
   2761 /*
   2762  * Attach a tty to the tty list.
   2763  *
   2764  * This should be called ONLY once per real tty (including pty's).
   2765  * eg, on the sparc, the keyboard and mouse have struct tty's that are
   2766  * distinctly NOT usable as tty's, and thus should not be attached to
   2767  * the ttylist.  This is why this call is not done from tty_alloc().
   2768  *
   2769  * Device drivers should attach tty's at a similar time that they are
   2770  * allocated, or, for the case of statically allocated struct tty's
   2771  * either in the attach or (first) open routine.
   2772  */
   2773 void
   2774 tty_attach(struct tty *tp)
   2775 {
   2776 
   2777 	mutex_spin_enter(&tty_lock);
   2778 	TAILQ_INSERT_TAIL(&ttylist, tp, tty_link);
   2779 	++tty_count;
   2780 	mutex_spin_exit(&tty_lock);
   2781 }
   2782 
   2783 /*
   2784  * Remove a tty from the tty list.
   2785  */
   2786 void
   2787 tty_detach(struct tty *tp)
   2788 {
   2789 
   2790 	mutex_spin_enter(&tty_lock);
   2791 	--tty_count;
   2792 #ifdef DIAGNOSTIC
   2793 	if (tty_count < 0)
   2794 		panic("tty_detach: tty_count < 0");
   2795 #endif
   2796 	TAILQ_REMOVE(&ttylist, tp, tty_link);
   2797 	mutex_spin_exit(&tty_lock);
   2798 }
   2799 
   2800 /*
   2801  * Allocate a tty structure and its associated buffers.
   2802  */
   2803 struct tty *
   2804 tty_alloc(void)
   2805 {
   2806 	struct tty *tp;
   2807 	int i;
   2808 
   2809 	tp = kmem_zalloc(sizeof(*tp), KM_SLEEP);
   2810 	callout_init(&tp->t_rstrt_ch, 0);
   2811 	callout_setfunc(&tp->t_rstrt_ch, ttrstrt, tp);
   2812 	tp->t_qsize = tty_qsize;
   2813 	clalloc(&tp->t_rawq, tp->t_qsize, 1);
   2814 	cv_init(&tp->t_rawcv, "ttyraw");
   2815 	cv_init(&tp->t_rawcvf, "ttyrawf");
   2816 	clalloc(&tp->t_canq, tp->t_qsize, 1);
   2817 	cv_init(&tp->t_cancv, "ttycan");
   2818 	cv_init(&tp->t_cancvf, "ttycanf");
   2819 	/* output queue doesn't need quoting */
   2820 	clalloc(&tp->t_outq, tp->t_qsize, 0);
   2821 	cv_init(&tp->t_outcv, "ttyout");
   2822 	cv_init(&tp->t_outcvf, "ttyoutf");
   2823 	/* Set default line discipline. */
   2824 	tp->t_linesw = ttyldisc_default();
   2825 	tp->t_dev = NODEV;
   2826 	selinit(&tp->t_rsel);
   2827 	selinit(&tp->t_wsel);
   2828 	for (i = 0; i < TTYSIG_COUNT; i++)  {
   2829 		sigemptyset(&tp->t_sigs[i]);
   2830 	}
   2831 
   2832 	return tp;
   2833 }
   2834 
   2835 /*
   2836  * Free a tty structure and its buffers.
   2837  *
   2838  * Be sure to call tty_detach() for any tty that has been
   2839  * tty_attach()ed.
   2840  */
   2841 void
   2842 tty_free(struct tty *tp)
   2843 {
   2844 	int i;
   2845 
   2846 	mutex_enter(proc_lock);
   2847 	mutex_enter(&tty_lock);
   2848 	for (i = 0; i < TTYSIG_COUNT; i++)
   2849 		sigemptyset(&tp->t_sigs[i]);
   2850 	if (tp->t_sigcount != 0)
   2851 		TAILQ_REMOVE(&tty_sigqueue, tp, t_sigqueue);
   2852 	mutex_exit(&tty_lock);
   2853 	mutex_exit(proc_lock);
   2854 
   2855 	callout_halt(&tp->t_rstrt_ch, NULL);
   2856 	callout_destroy(&tp->t_rstrt_ch);
   2857 	ttyldisc_release(tp->t_linesw);
   2858 	clfree(&tp->t_rawq);
   2859 	clfree(&tp->t_canq);
   2860 	clfree(&tp->t_outq);
   2861 	cv_destroy(&tp->t_rawcv);
   2862 	cv_destroy(&tp->t_rawcvf);
   2863 	cv_destroy(&tp->t_cancv);
   2864 	cv_destroy(&tp->t_cancvf);
   2865 	cv_destroy(&tp->t_outcv);
   2866 	cv_destroy(&tp->t_outcvf);
   2867 	seldestroy(&tp->t_rsel);
   2868 	seldestroy(&tp->t_wsel);
   2869 	kmem_free(tp, sizeof(*tp));
   2870 }
   2871 
   2872 /*
   2873  * ttyprintf_nolock: send a message to a specific tty, without locking.
   2874  *
   2875  * => should be used only by tty driver or anything that knows the
   2876  *    underlying tty will not be revoked(2)'d away.  [otherwise,
   2877  *    use tprintf]
   2878  */
   2879 static void
   2880 ttyprintf_nolock(struct tty *tp, const char *fmt, ...)
   2881 {
   2882 	va_list ap;
   2883 
   2884 	/* No mutex needed; going to process TTY. */
   2885 	va_start(ap, fmt);
   2886 	kprintf(fmt, TOTTY|NOLOCK, tp, NULL, ap);
   2887 	va_end(ap);
   2888 }
   2889 
   2890 static int
   2891 tty_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
   2892     void *arg0, void *arg1, void *arg2, void *arg3)
   2893 {
   2894 	struct tty *tty;
   2895 	int result;
   2896 
   2897 	result = KAUTH_RESULT_DEFER;
   2898 
   2899 	if (action != KAUTH_DEVICE_TTY_OPEN)
   2900 		return result;
   2901 
   2902 	tty = arg0;
   2903 
   2904 	/* If it's not opened, we allow. */
   2905 	if ((tty->t_state & TS_ISOPEN) == 0)
   2906 		result = KAUTH_RESULT_ALLOW;
   2907 	else {
   2908 		/*
   2909 		 * If it's opened, we can only allow if it's not exclusively
   2910 		 * opened; otherwise, that's a privileged operation and we
   2911 		 * let the secmodel handle it.
   2912 		 */
   2913 		if ((tty->t_state & TS_XCLUDE) == 0)
   2914 			result = KAUTH_RESULT_ALLOW;
   2915 	}
   2916 
   2917 	return result;
   2918 }
   2919 
   2920 /*
   2921  * Initialize the tty subsystem.
   2922  */
   2923 void
   2924 tty_init(void)
   2925 {
   2926 
   2927 	mutex_init(&tty_lock, MUTEX_DEFAULT, IPL_VM);
   2928 	rw_init(&ttcompat_lock);
   2929 	tty_sigsih = softint_establish(SOFTINT_CLOCK, ttysigintr, NULL);
   2930 	KASSERT(tty_sigsih != NULL);
   2931 
   2932 	tty_listener = kauth_listen_scope(KAUTH_SCOPE_DEVICE,
   2933 	    tty_listener_cb, NULL);
   2934 
   2935 	sysctl_kern_tty_setup();
   2936 }
   2937 
   2938 /*
   2939  * Send a signal from a tty to its process group or session leader.
   2940  * Handoff to the target is deferred to a soft interrupt.
   2941  */
   2942 void
   2943 ttysig(struct tty *tp, enum ttysigtype st, int sig)
   2944 {
   2945 	sigset_t *sp;
   2946 
   2947 	/* XXXSMP not yet KASSERT(mutex_owned(&tty_lock)); */
   2948 
   2949 	sp = &tp->t_sigs[st];
   2950 	if (sigismember(sp, sig))
   2951 		return;
   2952 	sigaddset(sp, sig);
   2953 	if (tp->t_sigcount++ == 0)
   2954 		TAILQ_INSERT_TAIL(&tty_sigqueue, tp, t_sigqueue);
   2955 	softint_schedule(tty_sigsih);
   2956 }
   2957 
   2958 /*
   2959  * Deliver deferred signals from ttys.  Note that the process groups
   2960  * and sessions associated with the ttys may have changed from when
   2961  * the signal was originally sent, but in practice it should not matter.
   2962  * For signals produced as a result of a syscall, the soft interrupt
   2963  * will fire before the syscall returns to the user.
   2964  */
   2965 static void
   2966 ttysigintr(void *cookie)
   2967 {
   2968 	struct tty *tp;
   2969 	enum ttysigtype st;
   2970 	struct pgrp *pgrp;
   2971 	struct session *sess;
   2972 	int sig, lflag;
   2973 	char infobuf[200];
   2974 
   2975 	mutex_enter(proc_lock);
   2976 	mutex_spin_enter(&tty_lock);
   2977 	while ((tp = TAILQ_FIRST(&tty_sigqueue)) != NULL) {
   2978 		KASSERT(tp->t_sigcount > 0);
   2979 		for (st = TTYSIG_PG1; st < TTYSIG_COUNT; st++) {
   2980 			if ((sig = firstsig(&tp->t_sigs[st])) != 0)
   2981 				break;
   2982 		}
   2983 		KASSERT(st < TTYSIG_COUNT);
   2984 		sigdelset(&tp->t_sigs[st], sig);
   2985 		if (--tp->t_sigcount == 0)
   2986 			TAILQ_REMOVE(&tty_sigqueue, tp, t_sigqueue);
   2987 		pgrp = tp->t_pgrp;
   2988 		sess = tp->t_session;
   2989 		lflag = tp->t_lflag;
   2990 		if  (sig == SIGINFO) {
   2991 			if (ISSET(tp->t_state, TS_SIGINFO)) {
   2992 				/* Via ioctl: ignore tty option. */
   2993 				tp->t_state &= ~TS_SIGINFO;
   2994 				lflag |= ISIG;
   2995 			}
   2996 			if (!ISSET(lflag, NOKERNINFO)) {
   2997 				mutex_spin_exit(&tty_lock);
   2998 				ttygetinfo(tp, 1, infobuf, sizeof(infobuf));
   2999 				mutex_spin_enter(&tty_lock);
   3000 				ttyputinfo(tp, infobuf);
   3001 			}
   3002 			if (!ISSET(lflag, ISIG))
   3003 				continue;
   3004 		}
   3005 		mutex_spin_exit(&tty_lock);
   3006 		KASSERT(sig != 0);
   3007 		switch (st) {
   3008 		case TTYSIG_PG1:
   3009 			if (pgrp != NULL)
   3010 				pgsignal(pgrp, sig, 1);
   3011 			break;
   3012 		case TTYSIG_PG2:
   3013 			if (pgrp != NULL)
   3014 				pgsignal(pgrp, sig, sess != NULL);
   3015 			break;
   3016 		case TTYSIG_LEADER:
   3017 			if (sess != NULL && sess->s_leader != NULL)
   3018 				psignal(sess->s_leader, sig);
   3019 			break;
   3020 		default:
   3021 			/* NOTREACHED */
   3022 			break;
   3023 		}
   3024 		mutex_spin_enter(&tty_lock);
   3025 	}
   3026 	mutex_spin_exit(&tty_lock);
   3027 	mutex_exit(proc_lock);
   3028 }
   3029 
   3030 unsigned char
   3031 tty_getctrlchar(struct tty *tp, unsigned which)
   3032 {
   3033 	KASSERT(which < NCCS);
   3034 	return tp->t_cc[which];
   3035 }
   3036 
   3037 void
   3038 tty_setctrlchar(struct tty *tp, unsigned which, unsigned char val)
   3039 {
   3040 	KASSERT(which < NCCS);
   3041 	tp->t_cc[which] = val;
   3042 }
   3043 
   3044 int
   3045 tty_try_xonxoff(struct tty *tp, unsigned char c)
   3046 {
   3047     const struct cdevsw *cdev;
   3048 
   3049     if (tp->t_iflag & IXON) {
   3050 	if (c == tp->t_cc[VSTOP] && tp->t_cc[VSTOP] != _POSIX_VDISABLE) {
   3051 	    if ((tp->t_state & TS_TTSTOP) == 0) {
   3052 		tp->t_state |= TS_TTSTOP;
   3053 		cdev = cdevsw_lookup(tp->t_dev);
   3054 		if (cdev != NULL)
   3055 			(*cdev->d_stop)(tp, 0);
   3056 	    }
   3057 	    return 0;
   3058 	}
   3059 	if (c == tp->t_cc[VSTART] && tp->t_cc[VSTART] != _POSIX_VDISABLE) {
   3060 	    tp->t_state &= ~TS_TTSTOP;
   3061 	    if (tp->t_oproc != NULL) {
   3062 	        mutex_spin_enter(&tty_lock);	/* XXX */
   3063 		(*tp->t_oproc)(tp);
   3064 	        mutex_spin_exit(&tty_lock);	/* XXX */
   3065 	    }
   3066 	    return 0;
   3067 	}
   3068     }
   3069     return EAGAIN;
   3070 }
   3071 
   3072 int
   3073 stub_compat_ptmioctl_60(dev_t dev, u_long cmd, void *data, int flag,
   3074     struct lwp *l)
   3075 {
   3076 
   3077 	return EPASSTHROUGH;
   3078 }
   3079