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