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