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