Home | History | Annotate | Line # | Download | only in kern
tty.c revision 1.128.2.8
      1 /*	$NetBSD: tty.c,v 1.128.2.8 2002/03/16 16:01:51 jdolecek 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. All advertising materials mentioning features or use of this software
     21  *    must display the following acknowledgement:
     22  *	This product includes software developed by the University of
     23  *	California, Berkeley and its contributors.
     24  * 4. Neither the name of the University nor the names of its contributors
     25  *    may be used to endorse or promote products derived from this software
     26  *    without specific prior written permission.
     27  *
     28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     38  * SUCH DAMAGE.
     39  *
     40  *	@(#)tty.c	8.13 (Berkeley) 1/9/95
     41  */
     42 
     43 #include <sys/cdefs.h>
     44 __KERNEL_RCSID(0, "$NetBSD: tty.c,v 1.128.2.8 2002/03/16 16:01:51 jdolecek Exp $");
     45 
     46 #include "opt_uconsole.h"
     47 
     48 #include <sys/param.h>
     49 #include <sys/systm.h>
     50 #include <sys/ioctl.h>
     51 #include <sys/proc.h>
     52 #define	TTYDEFCHARS
     53 #include <sys/tty.h>
     54 #undef	TTYDEFCHARS
     55 #include <sys/file.h>
     56 #include <sys/conf.h>
     57 #include <sys/dkstat.h>
     58 #include <sys/uio.h>
     59 #include <sys/kernel.h>
     60 #include <sys/vnode.h>
     61 #include <sys/syslog.h>
     62 #include <sys/malloc.h>
     63 #include <sys/pool.h>
     64 #include <sys/signalvar.h>
     65 #include <sys/resourcevar.h>
     66 #include <sys/poll.h>
     67 
     68 static int	filt_ttyread(struct knote *kn, long hint);
     69 static void 	filt_ttyrdetach(struct knote *kn);
     70 static int	filt_ttywrite(struct knote *kn, long hint);
     71 static void 	filt_ttywdetach(struct knote *kn);
     72 static int	ttnread(struct tty *);
     73 static void	ttyblock(struct tty *);
     74 static void	ttyecho(int, struct tty *);
     75 static void	ttyrubo(struct tty *, int);
     76 static int	proc_compare(struct proc *, struct proc *);
     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 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 /* Macros to clear/set/test flags. */
    169 #define	SET(t, f)	(t) |= (f)
    170 #define	CLR(t, f)	(t) &= ~((unsigned)(f))
    171 #define	ISSET(t, f)	((t) & (f))
    172 
    173 struct ttylist_head ttylist;	/* TAILQ_HEAD */
    174 int tty_count;
    175 
    176 struct pool tty_pool;
    177 
    178 u_int64_t tk_cancc;
    179 u_int64_t tk_nin;
    180 u_int64_t tk_nout;
    181 u_int64_t tk_rawcc;
    182 
    183 int
    184 ttyopen(struct tty *tp, int dialout, int nonblock)
    185 {
    186 	int	s, error;
    187 
    188 	s = spltty();
    189 
    190 	if (dialout) {
    191 		/*
    192 		 * If the device is already open for non-dialout, fail.
    193 		 * Otherwise, set TS_DIALOUT to block any pending non-dialout
    194 		 * opens.
    195 		 */
    196 		if (ISSET(tp->t_state, TS_ISOPEN) &&
    197 		    !ISSET(tp->t_state, TS_DIALOUT)) {
    198 			splx(s);
    199 			return (EBUSY);
    200 		}
    201 		SET(tp->t_state, TS_DIALOUT);
    202 	} else {
    203 		if (!nonblock) {
    204 			/*
    205 			 * Wait for carrier.  Also wait for any dialout
    206 			 * processes to close the tty first.
    207 			 */
    208 			while (ISSET(tp->t_state, TS_DIALOUT) ||
    209 			       (!ISSET(tp->t_state, TS_CARR_ON) &&
    210 				!ISSET(tp->t_cflag, CLOCAL | MDMBUF))) {
    211 				tp->t_wopen++;
    212 				error = ttysleep(tp, &tp->t_rawq,
    213 				    TTIPRI | PCATCH, ttopen, 0);
    214 				tp->t_wopen--;
    215 				if (error) {
    216 					splx(s);
    217 					return (error);
    218 				}
    219 			}
    220 		} else {
    221 			/*
    222 			 * Don't allow a non-blocking non-dialout open if the
    223 			 * device is already open for dialout.
    224 			 */
    225 		        if (ISSET(tp->t_state, TS_DIALOUT)) {
    226 				splx(s);
    227 				return (EBUSY);
    228 			}
    229 		}
    230 	}
    231 
    232 	splx(s);
    233 	return (0);
    234 }
    235 
    236 /*
    237  * Initial open of tty, or (re)entry to standard tty line discipline.
    238  */
    239 int
    240 ttylopen(dev_t device, struct tty *tp)
    241 {
    242 	int	s;
    243 
    244 	s = spltty();
    245 	tp->t_dev = device;
    246 	if (!ISSET(tp->t_state, TS_ISOPEN)) {
    247 		SET(tp->t_state, TS_ISOPEN);
    248 		memset(&tp->t_winsize, 0, sizeof(tp->t_winsize));
    249 #ifdef COMPAT_OLDTTY
    250 		tp->t_flags = 0;
    251 #endif
    252 	}
    253 	splx(s);
    254 	return (0);
    255 }
    256 
    257 /*
    258  * Handle close() on a tty line: flush and set to initial state,
    259  * bumping generation number so that pending read/write calls
    260  * can detect recycling of the tty.
    261  */
    262 int
    263 ttyclose(struct tty *tp)
    264 {
    265 	extern struct tty *constty;	/* Temporary virtual console. */
    266 
    267 	if (constty == tp)
    268 		constty = NULL;
    269 
    270 	ttyflush(tp, FREAD | FWRITE);
    271 
    272 	tp->t_gen++;
    273 	tp->t_pgrp = NULL;
    274 	tp->t_session = NULL;
    275 	tp->t_state = 0;
    276 	return (0);
    277 }
    278 
    279 #define	FLUSHQ(q) {							\
    280 	if ((q)->c_cc)							\
    281 		ndflush(q, (q)->c_cc);					\
    282 }
    283 
    284 /*
    285  * This macro is used in canonical mode input processing, where a read
    286  * request shall not return unless a 'line delimiter' ('\n') or 'break'
    287  * (EOF, EOL, EOL2) character (or a signal) has been received. As EOL2
    288  * is an extension to the POSIX.1 defined set of special characters,
    289  * recognize it only if IEXTEN is set in the set of local flags.
    290  */
    291 #define	TTBREAKC(c, lflg)						\
    292 	((c) == '\n' || (((c) == cc[VEOF] || (c) == cc[VEOL] ||		\
    293 	((c) == cc[VEOL2] && ISSET(lflg, IEXTEN))) && (c) != _POSIX_VDISABLE))
    294 
    295 
    296 /*
    297  * Process input of a single character received on a tty.
    298  */
    299 int
    300 ttyinput(int c, struct tty *tp)
    301 {
    302 	int	iflag, lflag, i, error;
    303 	u_char	*cc;
    304 
    305 	/*
    306 	 * Unless the receiver is enabled, drop incoming data.
    307 	 */
    308 	if (!ISSET(tp->t_cflag, CREAD))
    309 		return (0);
    310 
    311 	/*
    312 	 * If input is pending take it first.
    313 	 */
    314 	lflag = tp->t_lflag;
    315 	if (ISSET(lflag, PENDIN))
    316 		ttypend(tp);
    317 	/*
    318 	 * Gather stats.
    319 	 */
    320 	if (ISSET(lflag, ICANON)) {
    321 		++tk_cancc;
    322 		++tp->t_cancc;
    323 	} else {
    324 		++tk_rawcc;
    325 		++tp->t_rawcc;
    326 	}
    327 	++tk_nin;
    328 
    329 	cc = tp->t_cc;
    330 
    331 	/*
    332 	 * Handle exceptional conditions (break, parity, framing).
    333 	 */
    334 	iflag = tp->t_iflag;
    335 	if ((error = (ISSET(c, TTY_ERRORMASK))) != 0) {
    336 		CLR(c, TTY_ERRORMASK);
    337 		if (ISSET(error, TTY_FE) && c == 0) {		/* Break. */
    338 			if (ISSET(iflag, IGNBRK))
    339 				return (0);
    340 			else if (ISSET(iflag, BRKINT)) {
    341 				ttyflush(tp, FREAD | FWRITE);
    342 				pgsignal(tp->t_pgrp, SIGINT, 1);
    343 				return (0);
    344 			}
    345 			else if (ISSET(iflag, PARMRK))
    346 				goto parmrk;
    347 		}
    348 		else if ((ISSET(error, TTY_PE) && ISSET(iflag, INPCK)) ||
    349 		    ISSET(error, TTY_FE)) {
    350 			if (ISSET(iflag, IGNPAR))
    351 				return (0);
    352 			else if (ISSET(iflag, PARMRK)) {
    353  parmrk:			(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
    354 				(void)putc(0    | TTY_QUOTE, &tp->t_rawq);
    355 				(void)putc(c    | TTY_QUOTE, &tp->t_rawq);
    356 				return (0);
    357 			}
    358 			else
    359 				c = 0;
    360 		}
    361 	}
    362 	else if (c == 0377 &&
    363 	    ISSET(iflag, ISTRIP|IGNPAR|INPCK|PARMRK) == (INPCK|PARMRK)) {
    364 		/* "Escape" a valid character of '\377'. */
    365 		(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
    366 		(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
    367 		goto endcase;
    368 	}
    369 
    370 	/*
    371 	 * In tandem mode, check high water mark.
    372 	 */
    373 	if (ISSET(iflag, IXOFF) || ISSET(tp->t_cflag, CHWFLOW))
    374 		ttyblock(tp);
    375 	if (!ISSET(tp->t_state, TS_TYPEN) && ISSET(iflag, ISTRIP))
    376 		CLR(c, 0x80);
    377 	if (!ISSET(lflag, EXTPROC)) {
    378 		/*
    379 		 * Check for literal nexting very first
    380 		 */
    381 		if (ISSET(tp->t_state, TS_LNCH)) {
    382 			SET(c, TTY_QUOTE);
    383 			CLR(tp->t_state, TS_LNCH);
    384 		}
    385 		/*
    386 		 * Scan for special characters.  This code
    387 		 * is really just a big case statement with
    388 		 * non-constant cases.  The bottom of the
    389 		 * case statement is labeled ``endcase'', so goto
    390 		 * it after a case match, or similar.
    391 		 */
    392 
    393 		/*
    394 		 * Control chars which aren't controlled
    395 		 * by ICANON, ISIG, or IXON.
    396 		 */
    397 		if (ISSET(lflag, IEXTEN)) {
    398 			if (CCEQ(cc[VLNEXT], c)) {
    399 				if (ISSET(lflag, ECHO)) {
    400 					if (ISSET(lflag, ECHOE)) {
    401 						(void)ttyoutput('^', tp);
    402 						(void)ttyoutput('\b', tp);
    403 					} else
    404 						ttyecho(c, tp);
    405 				}
    406 				SET(tp->t_state, TS_LNCH);
    407 				goto endcase;
    408 			}
    409 			if (CCEQ(cc[VDISCARD], c)) {
    410 				if (ISSET(lflag, FLUSHO))
    411 					CLR(tp->t_lflag, FLUSHO);
    412 				else {
    413 					ttyflush(tp, FWRITE);
    414 					ttyecho(c, tp);
    415 					if (tp->t_rawq.c_cc + tp->t_canq.c_cc)
    416 						ttyretype(tp);
    417 					SET(tp->t_lflag, FLUSHO);
    418 				}
    419 				goto startoutput;
    420 			}
    421 		}
    422 		/*
    423 		 * Signals.
    424 		 */
    425 		if (ISSET(lflag, ISIG)) {
    426 			if (CCEQ(cc[VINTR], c) || CCEQ(cc[VQUIT], c)) {
    427 				if (!ISSET(lflag, NOFLSH))
    428 					ttyflush(tp, FREAD | FWRITE);
    429 				ttyecho(c, tp);
    430 				pgsignal(tp->t_pgrp,
    431 				    CCEQ(cc[VINTR], c) ? SIGINT : SIGQUIT, 1);
    432 				goto endcase;
    433 			}
    434 			if (CCEQ(cc[VSUSP], c)) {
    435 				if (!ISSET(lflag, NOFLSH))
    436 					ttyflush(tp, FREAD);
    437 				ttyecho(c, tp);
    438 				pgsignal(tp->t_pgrp, SIGTSTP, 1);
    439 				goto endcase;
    440 			}
    441 		}
    442 		/*
    443 		 * Handle start/stop characters.
    444 		 */
    445 		if (ISSET(iflag, IXON)) {
    446 			if (CCEQ(cc[VSTOP], c)) {
    447 				if (!ISSET(tp->t_state, TS_TTSTOP)) {
    448 					SET(tp->t_state, TS_TTSTOP);
    449 					(*cdevsw[major(tp->t_dev)].d_stop)(tp,
    450 					   0);
    451 					return (0);
    452 				}
    453 				if (!CCEQ(cc[VSTART], c))
    454 					return (0);
    455 				/*
    456 				 * if VSTART == VSTOP then toggle
    457 				 */
    458 				goto endcase;
    459 			}
    460 			if (CCEQ(cc[VSTART], c))
    461 				goto restartoutput;
    462 		}
    463 		/*
    464 		 * IGNCR, ICRNL, & INLCR
    465 		 */
    466 		if (c == '\r') {
    467 			if (ISSET(iflag, IGNCR))
    468 				goto endcase;
    469 			else if (ISSET(iflag, ICRNL))
    470 				c = '\n';
    471 		} else if (c == '\n' && ISSET(iflag, INLCR))
    472 			c = '\r';
    473 	}
    474 	if (!ISSET(tp->t_lflag, EXTPROC) && ISSET(lflag, ICANON)) {
    475 		/*
    476 		 * From here on down canonical mode character
    477 		 * processing takes place.
    478 		 */
    479 		/*
    480 		 * erase (^H / ^?)
    481 		 */
    482 		if (CCEQ(cc[VERASE], c)) {
    483 			if (tp->t_rawq.c_cc)
    484 				ttyrub(unputc(&tp->t_rawq), tp);
    485 			goto endcase;
    486 		}
    487 		/*
    488 		 * kill (^U)
    489 		 */
    490 		if (CCEQ(cc[VKILL], c)) {
    491 			if (ISSET(lflag, ECHOKE) &&
    492 			    tp->t_rawq.c_cc == tp->t_rocount &&
    493 			    !ISSET(lflag, ECHOPRT))
    494 				while (tp->t_rawq.c_cc)
    495 					ttyrub(unputc(&tp->t_rawq), tp);
    496 			else {
    497 				ttyecho(c, tp);
    498 				if (ISSET(lflag, ECHOK) ||
    499 				    ISSET(lflag, ECHOKE))
    500 					ttyecho('\n', tp);
    501 				FLUSHQ(&tp->t_rawq);
    502 				tp->t_rocount = 0;
    503 			}
    504 			CLR(tp->t_state, TS_LOCAL);
    505 			goto endcase;
    506 		}
    507 		/*
    508 		 * Extensions to the POSIX.1 GTI set of functions.
    509 		 */
    510 		if (ISSET(lflag, IEXTEN)) {
    511 			/*
    512 			 * word erase (^W)
    513 			 */
    514 			if (CCEQ(cc[VWERASE], c)) {
    515 				int alt = ISSET(lflag, ALTWERASE);
    516 				int ctype;
    517 
    518 				/*
    519 				 * erase whitespace
    520 				 */
    521 				while ((c = unputc(&tp->t_rawq)) == ' ' ||
    522 				       c == '\t')
    523 					ttyrub(c, tp);
    524 				if (c == -1)
    525 					goto endcase;
    526 				/*
    527 				 * erase last char of word and remember the
    528 				 * next chars type (for ALTWERASE)
    529 				 */
    530 				ttyrub(c, tp);
    531 				c = unputc(&tp->t_rawq);
    532 				if (c == -1)
    533 					goto endcase;
    534 				if (c == ' ' || c == '\t') {
    535 					(void)putc(c, &tp->t_rawq);
    536 					goto endcase;
    537 				}
    538 				ctype = ISALPHA(c);
    539 				/*
    540 				 * erase rest of word
    541 				 */
    542 				do {
    543 					ttyrub(c, tp);
    544 					c = unputc(&tp->t_rawq);
    545 					if (c == -1)
    546 						goto endcase;
    547 				} while (c != ' ' && c != '\t' &&
    548 				         (alt == 0 || ISALPHA(c) == ctype));
    549 				(void)putc(c, &tp->t_rawq);
    550 				goto endcase;
    551 			}
    552 			/*
    553 			 * reprint line (^R)
    554 			 */
    555 			if (CCEQ(cc[VREPRINT], c)) {
    556 				ttyretype(tp);
    557 				goto endcase;
    558 			}
    559 			/*
    560 			 * ^T - kernel info and generate SIGINFO
    561 			 */
    562 			if (CCEQ(cc[VSTATUS], c)) {
    563 				if (ISSET(lflag, ISIG))
    564 					pgsignal(tp->t_pgrp, SIGINFO, 1);
    565 				if (!ISSET(lflag, NOKERNINFO))
    566 					ttyinfo(tp);
    567 				goto endcase;
    568 			}
    569 		}
    570 	}
    571 	/*
    572 	 * Check for input buffer overflow
    573 	 */
    574 	if (tp->t_rawq.c_cc + tp->t_canq.c_cc >= TTYHOG) {
    575 		if (ISSET(iflag, IMAXBEL)) {
    576 			if (tp->t_outq.c_cc < tp->t_hiwat)
    577 				(void)ttyoutput(CTRL('g'), tp);
    578 		} else
    579 			ttyflush(tp, FREAD | FWRITE);
    580 		goto endcase;
    581 	}
    582 	/*
    583 	 * Put data char in q for user and
    584 	 * wakeup on seeing a line delimiter.
    585 	 */
    586 	if (putc(c, &tp->t_rawq) >= 0) {
    587 		if (!ISSET(lflag, ICANON)) {
    588 			ttwakeup(tp);
    589 			ttyecho(c, tp);
    590 			goto endcase;
    591 		}
    592 		if (TTBREAKC(c, lflag)) {
    593 			tp->t_rocount = 0;
    594 			catq(&tp->t_rawq, &tp->t_canq);
    595 			ttwakeup(tp);
    596 		} else if (tp->t_rocount++ == 0)
    597 			tp->t_rocol = tp->t_column;
    598 		if (ISSET(tp->t_state, TS_ERASE)) {
    599 			/*
    600 			 * end of prterase \.../
    601 			 */
    602 			CLR(tp->t_state, TS_ERASE);
    603 			(void)ttyoutput('/', tp);
    604 		}
    605 		i = tp->t_column;
    606 		ttyecho(c, tp);
    607 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ECHO)) {
    608 			/*
    609 			 * Place the cursor over the '^' of the ^D.
    610 			 */
    611 			i = min(2, tp->t_column - i);
    612 			while (i > 0) {
    613 				(void)ttyoutput('\b', tp);
    614 				i--;
    615 			}
    616 		}
    617 	}
    618  endcase:
    619 	/*
    620 	 * IXANY means allow any character to restart output.
    621 	 */
    622 	if (ISSET(tp->t_state, TS_TTSTOP) &&
    623 	    !ISSET(iflag, IXANY) && cc[VSTART] != cc[VSTOP])
    624 		return (0);
    625  restartoutput:
    626 	CLR(tp->t_lflag, FLUSHO);
    627 	CLR(tp->t_state, TS_TTSTOP);
    628  startoutput:
    629 	return (ttstart(tp));
    630 }
    631 
    632 /*
    633  * Output a single character on a tty, doing output processing
    634  * as needed (expanding tabs, newline processing, etc.).
    635  * Returns < 0 if succeeds, otherwise returns char to resend.
    636  * Must be recursive.
    637  */
    638 int
    639 ttyoutput(int c, struct tty *tp)
    640 {
    641 	long	oflag;
    642 	int	col, notout, s;
    643 
    644 	oflag = tp->t_oflag;
    645 	if (!ISSET(oflag, OPOST)) {
    646 		tk_nout++;
    647 		tp->t_outcc++;
    648 		if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
    649 			return (c);
    650 		return (-1);
    651 	}
    652 	/*
    653 	 * Do tab expansion if OXTABS is set.  Special case if we do external
    654 	 * processing, we don't do the tab expansion because we'll probably
    655 	 * get it wrong.  If tab expansion needs to be done, let it happen
    656 	 * externally.
    657 	 */
    658 	CLR(c, ~TTY_CHARMASK);
    659 	if (c == '\t' &&
    660 	    ISSET(oflag, OXTABS) && !ISSET(tp->t_lflag, EXTPROC)) {
    661 		c = 8 - (tp->t_column & 7);
    662 		if (ISSET(tp->t_lflag, FLUSHO)) {
    663 			notout = 0;
    664 		} else {
    665 			s = spltty();		/* Don't interrupt tabs. */
    666 			notout = b_to_q("        ", c, &tp->t_outq);
    667 			c -= notout;
    668 			tk_nout += c;
    669 			tp->t_outcc += c;
    670 			splx(s);
    671 		}
    672 		tp->t_column += c;
    673 		return (notout ? '\t' : -1);
    674 	}
    675 	if (c == CEOT && ISSET(oflag, ONOEOT))
    676 		return (-1);
    677 
    678 	/*
    679 	 * Newline translation: if ONLCR is set,
    680 	 * translate newline into "\r\n".
    681 	 */
    682 	if (c == '\n' && ISSET(tp->t_oflag, ONLCR)) {
    683 		tk_nout++;
    684 		tp->t_outcc++;
    685 		if (!ISSET(tp->t_lflag, FLUSHO) && putc('\r', &tp->t_outq))
    686 			return (c);
    687 	}
    688 	/* If OCRNL is set, translate "\r" into "\n". */
    689 	else if (c == '\r' && ISSET(tp->t_oflag, OCRNL))
    690 		c = '\n';
    691 	/* If ONOCR is set, don't transmit CRs when on column 0. */
    692 	else if (c == '\r' && ISSET(tp->t_oflag, ONOCR) && tp->t_column == 0)
    693 		return (-1);
    694 
    695 	tk_nout++;
    696 	tp->t_outcc++;
    697 	if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
    698 		return (c);
    699 
    700 	col = tp->t_column;
    701 	switch (CCLASS(c)) {
    702 	case BACKSPACE:
    703 		if (col > 0)
    704 			--col;
    705 		break;
    706 	case CONTROL:
    707 		break;
    708 	case NEWLINE:
    709 		if (ISSET(tp->t_oflag, ONLCR | ONLRET))
    710 			col = 0;
    711 		break;
    712 	case RETURN:
    713 		col = 0;
    714 		break;
    715 	case ORDINARY:
    716 		++col;
    717 		break;
    718 	case TAB:
    719 		col = (col + 8) & ~7;
    720 		break;
    721 	}
    722 	tp->t_column = col;
    723 	return (-1);
    724 }
    725 
    726 /*
    727  * Ioctls for all tty devices.  Called after line-discipline specific ioctl
    728  * has been called to do discipline-specific functions and/or reject any
    729  * of these ioctl commands.
    730  */
    731 /* ARGSUSED */
    732 int
    733 ttioctl(struct tty *tp, u_long cmd, caddr_t data, int flag, struct proc *p)
    734 {
    735 	extern struct tty *constty;	/* Temporary virtual console. */
    736 	struct linesw	*lp;
    737 	int		s, error;
    738 
    739 	/* If the ioctl involves modification, hang if in the background. */
    740 	switch (cmd) {
    741 	case  TIOCFLUSH:
    742 	case  TIOCDRAIN:
    743 	case  TIOCSBRK:
    744 	case  TIOCCBRK:
    745 	case  TIOCSTART:
    746 	case  TIOCSETA:
    747 	case  TIOCSETD:
    748 	case  TIOCSLINED:
    749 	case  TIOCSETAF:
    750 	case  TIOCSETAW:
    751 #ifdef notdef
    752 	case  TIOCSPGRP:
    753 #endif
    754 	case  TIOCSTAT:
    755 	case  TIOCSTI:
    756 	case  TIOCSWINSZ:
    757 #ifdef COMPAT_OLDTTY
    758 	case  TIOCLBIC:
    759 	case  TIOCLBIS:
    760 	case  TIOCLSET:
    761 	case  TIOCSETC:
    762 	case OTIOCSETD:
    763 	case  TIOCSETN:
    764 	case  TIOCSETP:
    765 	case  TIOCSLTC:
    766 #endif
    767 		while (isbackground(curproc, tp) &&
    768 		    p->p_pgrp->pg_jobc && (p->p_flag & P_PPWAIT) == 0 &&
    769 		    !sigismasked(p, SIGTTOU)) {
    770 			pgsignal(p->p_pgrp, SIGTTOU, 1);
    771 			error = ttysleep(tp, &lbolt, TTOPRI | PCATCH, ttybg, 0);
    772 			if (error)
    773 				return (error);
    774 		}
    775 		break;
    776 	}
    777 
    778 	switch (cmd) {			/* Process the ioctl. */
    779 	case FIOASYNC:			/* set/clear async i/o */
    780 		s = spltty();
    781 		if (*(int *)data)
    782 			SET(tp->t_state, TS_ASYNC);
    783 		else
    784 			CLR(tp->t_state, TS_ASYNC);
    785 		splx(s);
    786 		break;
    787 	case FIONBIO:			/* set/clear non-blocking i/o */
    788 		break;			/* XXX: delete. */
    789 	case FIONREAD:			/* get # bytes to read */
    790 		*(int *)data = ttnread(tp);
    791 		break;
    792 	case TIOCEXCL:			/* set exclusive use of tty */
    793 		s = spltty();
    794 		SET(tp->t_state, TS_XCLUDE);
    795 		splx(s);
    796 		break;
    797 	case TIOCFLUSH: {		/* flush buffers */
    798 		int flags = *(int *)data;
    799 
    800 		if (flags == 0)
    801 			flags = FREAD | FWRITE;
    802 		else
    803 			flags &= FREAD | FWRITE;
    804 		ttyflush(tp, flags);
    805 		break;
    806 	}
    807 	case TIOCCONS:			/* become virtual console */
    808 		if (*(int *)data) {
    809 			if (constty && constty != tp &&
    810 			    ISSET(constty->t_state, TS_CARR_ON | TS_ISOPEN) ==
    811 			    (TS_CARR_ON | TS_ISOPEN))
    812 				return (EBUSY);
    813 #ifndef	UCONSOLE
    814 			if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
    815 				return (error);
    816 #endif
    817 			constty = tp;
    818 		} else if (tp == constty)
    819 			constty = NULL;
    820 		break;
    821 	case TIOCDRAIN:			/* wait till output drained */
    822 		if ((error = ttywait(tp)) != 0)
    823 			return (error);
    824 		break;
    825 	case TIOCGETA: {		/* get termios struct */
    826 		struct termios *t = (struct termios *)data;
    827 
    828 		memcpy(t, &tp->t_termios, sizeof(struct termios));
    829 		break;
    830 	}
    831 	case TIOCGETD:			/* get line discipline */
    832 		*(int *)data = tp->t_linesw->l_no;
    833 		break;
    834 	case TIOCGLINED:
    835 		(void)strncpy((char *)data, tp->t_linesw->l_name,
    836 		    TTLINEDNAMELEN - 1);
    837 		break;
    838 	case TIOCGWINSZ:		/* get window size */
    839 		*(struct winsize *)data = tp->t_winsize;
    840 		break;
    841 	case TIOCGPGRP:			/* get pgrp of tty */
    842 		if (!isctty(p, tp))
    843 			return (ENOTTY);
    844 		*(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
    845 		break;
    846 	case TIOCGSID:			/* get sid of tty */
    847 		if (!isctty(p, tp))
    848 			return (ENOTTY);
    849 		*(int *)data = tp->t_session->s_sid;
    850 		break;
    851 #ifdef TIOCHPCL
    852 	case TIOCHPCL:			/* hang up on last close */
    853 		s = spltty();
    854 		SET(tp->t_cflag, HUPCL);
    855 		splx(s);
    856 		break;
    857 #endif
    858 	case TIOCNXCL:			/* reset exclusive use of tty */
    859 		s = spltty();
    860 		CLR(tp->t_state, TS_XCLUDE);
    861 		splx(s);
    862 		break;
    863 	case TIOCOUTQ:			/* output queue size */
    864 		*(int *)data = tp->t_outq.c_cc;
    865 		break;
    866 	case TIOCSETA:			/* set termios struct */
    867 	case TIOCSETAW:			/* drain output, set */
    868 	case TIOCSETAF: {		/* drn out, fls in, set */
    869 		struct termios *t = (struct termios *)data;
    870 
    871 		s = spltty();
    872 		if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
    873 			if ((error = ttywait(tp)) != 0) {
    874 				splx(s);
    875 				return (error);
    876 			}
    877 			if (cmd == TIOCSETAF)
    878 				ttyflush(tp, FREAD);
    879 		}
    880 		if (!ISSET(t->c_cflag, CIGNORE)) {
    881 			/*
    882 			 * Set device hardware.
    883 			 */
    884 			if (tp->t_param && (error = (*tp->t_param)(tp, t))) {
    885 				splx(s);
    886 				return (error);
    887 			} else {
    888 				tp->t_cflag = t->c_cflag;
    889 				tp->t_ispeed = t->c_ispeed;
    890 				tp->t_ospeed = t->c_ospeed;
    891 				if (t->c_ospeed == 0 && tp->t_session &&
    892 				    tp->t_session->s_leader)
    893 					psignal(tp->t_session->s_leader,
    894 					    SIGHUP);
    895 			}
    896 			ttsetwater(tp);
    897 		}
    898 		if (cmd != TIOCSETAF) {
    899 			if (ISSET(t->c_lflag, ICANON) !=
    900 			    ISSET(tp->t_lflag, ICANON)) {
    901 				if (ISSET(t->c_lflag, ICANON)) {
    902 					SET(tp->t_lflag, PENDIN);
    903 					ttwakeup(tp);
    904 				} else {
    905 					struct clist tq;
    906 
    907 					catq(&tp->t_rawq, &tp->t_canq);
    908 					tq = tp->t_rawq;
    909 					tp->t_rawq = tp->t_canq;
    910 					tp->t_canq = tq;
    911 					CLR(tp->t_lflag, PENDIN);
    912 				}
    913 			}
    914 		}
    915 		tp->t_iflag = t->c_iflag;
    916 		tp->t_oflag = t->c_oflag;
    917 		/*
    918 		 * Make the EXTPROC bit read only.
    919 		 */
    920 		if (ISSET(tp->t_lflag, EXTPROC))
    921 			SET(t->c_lflag, EXTPROC);
    922 		else
    923 			CLR(t->c_lflag, EXTPROC);
    924 		tp->t_lflag = t->c_lflag | ISSET(tp->t_lflag, PENDIN);
    925 		memcpy(tp->t_cc, t->c_cc, sizeof(t->c_cc));
    926 		splx(s);
    927 		break;
    928 	}
    929 	case TIOCSETD: {		/* set line discipline */
    930 		int t = *(int *)data;
    931 
    932 		if ((u_int)t >= nlinesw)
    933 			return (ENXIO);
    934 		lp = linesw[t];
    935 		goto setldisc;
    936 	}
    937 	case TIOCSLINED: {		/* set line discipline */
    938 		char *name = (char *)data;
    939 		dev_t device;
    940 
    941 		/* Null terminate to prevent buffer overflow */
    942 		name[TTLINEDNAMELEN - 1] = '\0';
    943 		lp = ttyldisc_lookup(name);
    944 
    945  setldisc:
    946 		if (lp == NULL)
    947 			return (ENXIO);
    948 
    949 		if (lp != tp->t_linesw) {
    950 			device = tp->t_dev;
    951 			s = spltty();
    952 			(*tp->t_linesw->l_close)(tp, flag);
    953 			error = (*lp->l_open)(device, tp);
    954 			if (error) {
    955 				(void)(*tp->t_linesw->l_open)(device, tp);
    956 				splx(s);
    957 				return (error);
    958 			}
    959 			tp->t_linesw = lp;
    960 			splx(s);
    961 		}
    962 		break;
    963 	}
    964 	case TIOCSTART:			/* start output, like ^Q */
    965 		s = spltty();
    966 		if (ISSET(tp->t_state, TS_TTSTOP) ||
    967 		    ISSET(tp->t_lflag, FLUSHO)) {
    968 			CLR(tp->t_lflag, FLUSHO);
    969 			CLR(tp->t_state, TS_TTSTOP);
    970 			ttstart(tp);
    971 		}
    972 		splx(s);
    973 		break;
    974 	case TIOCSTI:			/* simulate terminal input */
    975 		if (p->p_ucred->cr_uid && (flag & FREAD) == 0)
    976 			return (EPERM);
    977 		if (p->p_ucred->cr_uid && !isctty(p, tp))
    978 			return (EACCES);
    979 		(*tp->t_linesw->l_rint)(*(u_char *)data, tp);
    980 		break;
    981 	case TIOCSTOP:			/* stop output, like ^S */
    982 		s = spltty();
    983 		if (!ISSET(tp->t_state, TS_TTSTOP)) {
    984 			SET(tp->t_state, TS_TTSTOP);
    985 			(*cdevsw[major(tp->t_dev)].d_stop)(tp, 0);
    986 		}
    987 		splx(s);
    988 		break;
    989 	case TIOCSCTTY:			/* become controlling tty */
    990 		/* Session ctty vnode pointer set in vnode layer. */
    991 		if (!SESS_LEADER(p) ||
    992 		    ((p->p_session->s_ttyvp || tp->t_session) &&
    993 		     (tp->t_session != p->p_session)))
    994 			return (EPERM);
    995 		tp->t_session = p->p_session;
    996 		tp->t_pgrp = p->p_pgrp;
    997 		p->p_session->s_ttyp = tp;
    998 		p->p_flag |= P_CONTROLT;
    999 		break;
   1000 	case TIOCSPGRP: {		/* set pgrp of tty */
   1001 		struct pgrp *pgrp = pgfind(*(int *)data);
   1002 
   1003 		if (!isctty(p, tp))
   1004 			return (ENOTTY);
   1005 		else if (pgrp == NULL)
   1006 			return (EINVAL);
   1007 		else if (pgrp->pg_session != p->p_session)
   1008 			return (EPERM);
   1009 		tp->t_pgrp = pgrp;
   1010 		break;
   1011 	}
   1012 	case TIOCSTAT:			/* get load avg stats */
   1013 		ttyinfo(tp);
   1014 		break;
   1015 	case TIOCSWINSZ:		/* set window size */
   1016 		if (memcmp((caddr_t)&tp->t_winsize, data,
   1017 		    sizeof(struct winsize))) {
   1018 			tp->t_winsize = *(struct winsize *)data;
   1019 			pgsignal(tp->t_pgrp, SIGWINCH, 1);
   1020 		}
   1021 		break;
   1022 	default:
   1023 #ifdef COMPAT_OLDTTY
   1024 		return (ttcompat(tp, cmd, data, flag, p));
   1025 #else
   1026 		return (-1);
   1027 #endif
   1028 	}
   1029 	return (0);
   1030 }
   1031 
   1032 int
   1033 ttpoll(struct tty *tp, int events, struct proc *p)
   1034 {
   1035 	int	revents, s;
   1036 
   1037 	revents = 0;
   1038 	s = spltty();
   1039 	if (events & (POLLIN | POLLRDNORM))
   1040 		if (ttnread(tp) > 0)
   1041 			revents |= events & (POLLIN | POLLRDNORM);
   1042 
   1043 	if (events & (POLLOUT | POLLWRNORM))
   1044 		if (tp->t_outq.c_cc <= tp->t_lowat)
   1045 			revents |= events & (POLLOUT | POLLWRNORM);
   1046 
   1047 	if (events & POLLHUP)
   1048 		if (!CONNECTED(tp))
   1049 			revents |= POLLHUP;
   1050 
   1051 	if (revents == 0) {
   1052 		if (events & (POLLIN | POLLHUP | POLLRDNORM))
   1053 			selrecord(p, &tp->t_rsel);
   1054 
   1055 		if (events & (POLLOUT | POLLWRNORM))
   1056 			selrecord(p, &tp->t_wsel);
   1057 	}
   1058 
   1059 	splx(s);
   1060 	return (revents);
   1061 }
   1062 
   1063 static const struct filterops ttyread_filtops =
   1064 	{ 1, NULL, filt_ttyrdetach, filt_ttyread };
   1065 static const struct filterops ttywrite_filtops =
   1066 	{ 1, NULL, filt_ttywdetach, filt_ttywrite };
   1067 
   1068 int
   1069 ttykqfilter(dev_t dev, struct knote *kn)
   1070 {
   1071 	struct tty	*tp;
   1072 	struct klist	*klist;
   1073 	int		s;
   1074 
   1075 	tp = (*cdevsw[major(dev)].d_tty)(dev);
   1076 	switch (kn->kn_filter) {
   1077 	case EVFILT_READ:
   1078 		klist = &tp->t_rsel.si_klist;
   1079 		kn->kn_fop = &ttyread_filtops;
   1080 		break;
   1081 	case EVFILT_WRITE:
   1082 		klist = &tp->t_wsel.si_klist;
   1083 		kn->kn_fop = &ttywrite_filtops;
   1084 		break;
   1085 	default:
   1086 		return (1);
   1087 	}
   1088 
   1089 	kn->kn_hook = (void *) tp;
   1090 
   1091 	s = spltty();
   1092 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
   1093 	splx(s);
   1094 
   1095 	return (0);
   1096 }
   1097 
   1098 static void
   1099 filt_ttyrdetach(struct knote *kn)
   1100 {
   1101 	struct tty	*tp;
   1102 	int		s;
   1103 
   1104 	tp = (void *) kn->kn_hook;
   1105 	s = spltty();
   1106 	SLIST_REMOVE(&tp->t_rsel.si_klist, kn, knote, kn_selnext);
   1107 	splx(s);
   1108 }
   1109 
   1110 static int
   1111 filt_ttyread(struct knote *kn, long hint)
   1112 {
   1113 	struct tty	*tp;
   1114 
   1115 	tp = (void *) kn->kn_hook;
   1116 	kn->kn_data = ttnread(tp);
   1117 	return (kn->kn_data > 0);
   1118 }
   1119 
   1120 static void
   1121 filt_ttywdetach(struct knote *kn)
   1122 {
   1123 	struct tty	*tp;
   1124 	int		s;
   1125 
   1126 	tp = (void *) kn->kn_hook;
   1127 	s = spltty();
   1128 	SLIST_REMOVE(&tp->t_wsel.si_klist, kn, knote, kn_selnext);
   1129 	splx(s);
   1130 }
   1131 
   1132 static int
   1133 filt_ttywrite(kn, hint)
   1134 	struct knote *kn;
   1135 	long hint;
   1136 {
   1137 	struct tty	*tp;
   1138 
   1139 	tp = (void *) kn->kn_hook;
   1140 	kn->kn_data = tp->t_outq.c_cc;
   1141 	return (kn->kn_data <= tp->t_lowat && CONNECTED(tp));
   1142 }
   1143 
   1144 
   1145 static int
   1146 ttnread(struct tty *tp)
   1147 {
   1148 	int	nread;
   1149 
   1150 	if (ISSET(tp->t_lflag, PENDIN))
   1151 		ttypend(tp);
   1152 	nread = tp->t_canq.c_cc;
   1153 	if (!ISSET(tp->t_lflag, ICANON)) {
   1154 		nread += tp->t_rawq.c_cc;
   1155 		if (nread < tp->t_cc[VMIN] && !tp->t_cc[VTIME])
   1156 			nread = 0;
   1157 	}
   1158 	return (nread);
   1159 }
   1160 
   1161 /*
   1162  * Wait for output to drain.
   1163  */
   1164 int
   1165 ttywait(tp)
   1166 	struct tty *tp;
   1167 {
   1168 	int	error, s;
   1169 
   1170 	error = 0;
   1171 	s = spltty();
   1172 	while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
   1173 	    CONNECTED(tp) && tp->t_oproc) {
   1174 		(*tp->t_oproc)(tp);
   1175 		SET(tp->t_state, TS_ASLEEP);
   1176 		error = ttysleep(tp, &tp->t_outq, TTOPRI | PCATCH, ttyout, 0);
   1177 		if (error)
   1178 			break;
   1179 	}
   1180 	splx(s);
   1181 	return (error);
   1182 }
   1183 
   1184 /*
   1185  * Flush if successfully wait.
   1186  */
   1187 int
   1188 ttywflush(struct tty *tp)
   1189 {
   1190 	int	error;
   1191 
   1192 	if ((error = ttywait(tp)) == 0)
   1193 		ttyflush(tp, FREAD);
   1194 	return (error);
   1195 }
   1196 
   1197 /*
   1198  * Flush tty read and/or write queues, notifying anyone waiting.
   1199  */
   1200 void
   1201 ttyflush(struct tty *tp, int rw)
   1202 {
   1203 	int	s;
   1204 
   1205 	s = spltty();
   1206 	if (rw & FREAD) {
   1207 		FLUSHQ(&tp->t_canq);
   1208 		FLUSHQ(&tp->t_rawq);
   1209 		tp->t_rocount = 0;
   1210 		tp->t_rocol = 0;
   1211 		CLR(tp->t_state, TS_LOCAL);
   1212 		ttwakeup(tp);
   1213 	}
   1214 	if (rw & FWRITE) {
   1215 		CLR(tp->t_state, TS_TTSTOP);
   1216 		(*cdevsw[major(tp->t_dev)].d_stop)(tp, rw);
   1217 		FLUSHQ(&tp->t_outq);
   1218 		wakeup((caddr_t)&tp->t_outq);
   1219 		selnotify(&tp->t_wsel, 0);
   1220 	}
   1221 	splx(s);
   1222 }
   1223 
   1224 /*
   1225  * Copy in the default termios characters.
   1226  */
   1227 void
   1228 ttychars(struct tty *tp)
   1229 {
   1230 
   1231 	memcpy(tp->t_cc, ttydefchars, sizeof(ttydefchars));
   1232 }
   1233 
   1234 /*
   1235  * Send stop character on input overflow.
   1236  */
   1237 static void
   1238 ttyblock(struct tty *tp)
   1239 {
   1240 	int	total;
   1241 
   1242 	total = tp->t_rawq.c_cc + tp->t_canq.c_cc;
   1243 	if (tp->t_rawq.c_cc > TTYHOG) {
   1244 		ttyflush(tp, FREAD | FWRITE);
   1245 		CLR(tp->t_state, TS_TBLOCK);
   1246 	}
   1247 	/*
   1248 	 * Block further input iff: current input > threshold
   1249 	 * AND input is available to user program.
   1250 	 */
   1251 	if (total >= TTYHOG / 2 &&
   1252 	    !ISSET(tp->t_state, TS_TBLOCK) &&
   1253 	    (!ISSET(tp->t_lflag, ICANON) || tp->t_canq.c_cc > 0)) {
   1254 		if (ISSET(tp->t_iflag, IXOFF) &&
   1255 		    tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
   1256 		    putc(tp->t_cc[VSTOP], &tp->t_outq) == 0) {
   1257 			SET(tp->t_state, TS_TBLOCK);
   1258 			ttstart(tp);
   1259 		}
   1260 		/* Try to block remote output via hardware flow control. */
   1261 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
   1262 		    (*tp->t_hwiflow)(tp, 1) != 0)
   1263 			SET(tp->t_state, TS_TBLOCK);
   1264 	}
   1265 }
   1266 
   1267 void
   1268 ttrstrt(void *tp_arg)
   1269 {
   1270 	struct tty	*tp;
   1271 	int		s;
   1272 
   1273 #ifdef DIAGNOSTIC
   1274 	if (tp_arg == NULL)
   1275 		panic("ttrstrt");
   1276 #endif
   1277 	tp = tp_arg;
   1278 	s = spltty();
   1279 
   1280 	CLR(tp->t_state, TS_TIMEOUT);
   1281 	ttstart(tp);
   1282 
   1283 	splx(s);
   1284 }
   1285 
   1286 int
   1287 ttstart(struct tty *tp)
   1288 {
   1289 
   1290 	if (tp->t_oproc != NULL)	/* XXX: Kludge for pty. */
   1291 		(*tp->t_oproc)(tp);
   1292 	return (0);
   1293 }
   1294 
   1295 /*
   1296  * "close" a line discipline
   1297  */
   1298 int
   1299 ttylclose(struct tty *tp, int flag)
   1300 {
   1301 
   1302 	if (flag & FNONBLOCK)
   1303 		ttyflush(tp, FREAD | FWRITE);
   1304 	else
   1305 		ttywflush(tp);
   1306 	return (0);
   1307 }
   1308 
   1309 /*
   1310  * Handle modem control transition on a tty.
   1311  * Flag indicates new state of carrier.
   1312  * Returns 0 if the line should be turned off, otherwise 1.
   1313  */
   1314 int
   1315 ttymodem(struct tty *tp, int flag)
   1316 {
   1317 
   1318 	if (flag == 0) {
   1319 		if (ISSET(tp->t_state, TS_CARR_ON)) {
   1320 			/*
   1321 			 * Lost carrier.
   1322 			 */
   1323 			CLR(tp->t_state, TS_CARR_ON);
   1324 			if (ISSET(tp->t_state, TS_ISOPEN) && !CONNECTED(tp)) {
   1325 				if (tp->t_session && tp->t_session->s_leader)
   1326 					psignal(tp->t_session->s_leader, SIGHUP);
   1327 				ttyflush(tp, FREAD | FWRITE);
   1328 				return (0);
   1329 			}
   1330 		}
   1331 	} else {
   1332 		if (!ISSET(tp->t_state, TS_CARR_ON)) {
   1333 			/*
   1334 			 * Carrier now on.
   1335 			 */
   1336 			SET(tp->t_state, TS_CARR_ON);
   1337 			ttwakeup(tp);
   1338 		}
   1339 	}
   1340 	return (1);
   1341 }
   1342 
   1343 /*
   1344  * Default modem control routine (for other line disciplines).
   1345  * Return argument flag, to turn off device on carrier drop.
   1346  */
   1347 int
   1348 nullmodem(struct tty *tp, int flag)
   1349 {
   1350 
   1351 	if (flag)
   1352 		SET(tp->t_state, TS_CARR_ON);
   1353 	else {
   1354 		CLR(tp->t_state, TS_CARR_ON);
   1355 		if (!CONNECTED(tp)) {
   1356 			if (tp->t_session && tp->t_session->s_leader)
   1357 				psignal(tp->t_session->s_leader, SIGHUP);
   1358 			return (0);
   1359 		}
   1360 	}
   1361 	return (1);
   1362 }
   1363 
   1364 /*
   1365  * Reinput pending characters after state switch
   1366  * call at spltty().
   1367  */
   1368 void
   1369 ttypend(struct tty *tp)
   1370 {
   1371 	struct clist	tq;
   1372 	int		c;
   1373 
   1374 	CLR(tp->t_lflag, PENDIN);
   1375 	SET(tp->t_state, TS_TYPEN);
   1376 	tq = tp->t_rawq;
   1377 	tp->t_rawq.c_cc = 0;
   1378 	tp->t_rawq.c_cf = tp->t_rawq.c_cl = 0;
   1379 	while ((c = getc(&tq)) >= 0)
   1380 		ttyinput(c, tp);
   1381 	CLR(tp->t_state, TS_TYPEN);
   1382 }
   1383 
   1384 /*
   1385  * Process a read call on a tty device.
   1386  */
   1387 int
   1388 ttread(struct tty *tp, struct uio *uio, int flag)
   1389 {
   1390 	struct clist	*qp;
   1391 	u_char		*cc;
   1392 	struct proc	*p;
   1393 	int		c, s, first, error, has_stime, last_cc;
   1394 	long		lflag, slp;
   1395 	struct timeval	stime;
   1396 
   1397 	cc = tp->t_cc;
   1398 	p = curproc;
   1399 	error = 0;
   1400 	has_stime = 0;
   1401 	last_cc = 0;
   1402 	slp = 0;
   1403 
   1404  loop:
   1405 	lflag = tp->t_lflag;
   1406 	s = spltty();
   1407 	/*
   1408 	 * take pending input first
   1409 	 */
   1410 	if (ISSET(lflag, PENDIN))
   1411 		ttypend(tp);
   1412 	splx(s);
   1413 
   1414 	/*
   1415 	 * Hang process if it's in the background.
   1416 	 */
   1417 	if (isbackground(p, tp)) {
   1418 		if (sigismember(&p->p_sigctx.ps_sigignore, SIGTTIN) ||
   1419 		    sigismember(&p->p_sigctx.ps_sigmask, SIGTTIN) ||
   1420 		    p->p_flag & P_PPWAIT || p->p_pgrp->pg_jobc == 0)
   1421 			return (EIO);
   1422 		pgsignal(p->p_pgrp, SIGTTIN, 1);
   1423 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, ttybg, 0);
   1424 		if (error)
   1425 			return (error);
   1426 		goto loop;
   1427 	}
   1428 
   1429 	s = spltty();
   1430 	if (!ISSET(lflag, ICANON)) {
   1431 		int m = cc[VMIN];
   1432 		long t = cc[VTIME];
   1433 
   1434 		qp = &tp->t_rawq;
   1435 		/*
   1436 		 * Check each of the four combinations.
   1437 		 * (m > 0 && t == 0) is the normal read case.
   1438 		 * It should be fairly efficient, so we check that and its
   1439 		 * companion case (m == 0 && t == 0) first.
   1440 		 * For the other two cases, we compute the target sleep time
   1441 		 * into slp.
   1442 		 */
   1443 		if (t == 0) {
   1444 			if (qp->c_cc < m)
   1445 				goto sleep;
   1446 			goto read;
   1447 		}
   1448 		t *= 100000;		/* time in us */
   1449 #define	diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 1000000 + \
   1450 			 ((t1).tv_usec - (t2).tv_usec))
   1451 		if (m > 0) {
   1452 			if (qp->c_cc <= 0)
   1453 				goto sleep;
   1454 			if (qp->c_cc >= m)
   1455 				goto read;
   1456 			if (!has_stime) {
   1457 				/* first character, start timer */
   1458 				has_stime = 1;
   1459 				stime = time;
   1460 				slp = t;
   1461 			} else if (qp->c_cc > last_cc) {
   1462 				/* got a character, restart timer */
   1463 				stime = time;
   1464 				slp = t;
   1465 			} else {
   1466 				/* nothing, check expiration */
   1467 				slp = t - diff(time, stime);
   1468 			}
   1469 		} else {	/* m == 0 */
   1470 			if (qp->c_cc > 0)
   1471 				goto read;
   1472 			if (!has_stime) {
   1473 				has_stime = 1;
   1474 				stime = time;
   1475 				slp = t;
   1476 			} else
   1477 				slp = t - diff(time, stime);
   1478 		}
   1479 		last_cc = qp->c_cc;
   1480 #undef diff
   1481 		if (slp > 0) {
   1482 			/*
   1483 			 * Rounding down may make us wake up just short
   1484 			 * of the target, so we round up.
   1485 			 * The formula is ceiling(slp * hz/1000000).
   1486 			 * 32-bit arithmetic is enough for hz < 169.
   1487 			 *
   1488 			 * Also, use plain wakeup() not ttwakeup().
   1489 			 */
   1490 			slp = (long) (((u_long)slp * hz) + 999999) / 1000000;
   1491 			goto sleep;
   1492 		}
   1493 	} else if ((qp = &tp->t_canq)->c_cc <= 0) {
   1494 		int	carrier;
   1495 
   1496  sleep:
   1497 		/*
   1498 		 * If there is no input, sleep on rawq
   1499 		 * awaiting hardware receipt and notification.
   1500 		 * If we have data, we don't need to check for carrier.
   1501 		 */
   1502 		carrier = CONNECTED(tp);
   1503 		if (!carrier && ISSET(tp->t_state, TS_ISOPEN)) {
   1504 			splx(s);
   1505 			return (0);	/* EOF */
   1506 		}
   1507 		if (flag & IO_NDELAY) {
   1508 			splx(s);
   1509 			return (EWOULDBLOCK);
   1510 		}
   1511 		error = ttysleep(tp, &tp->t_rawq, TTIPRI | PCATCH,
   1512 		    carrier ? ttyin : ttopen, slp);
   1513 		splx(s);
   1514 		/* VMIN == 0: any quantity read satisfies */
   1515 		if (cc[VMIN] == 0 && error == EWOULDBLOCK)
   1516 			return (0);
   1517 		if (error && error != EWOULDBLOCK)
   1518 			return (error);
   1519 		goto loop;
   1520 	}
   1521  read:
   1522 	splx(s);
   1523 
   1524 	/*
   1525 	 * Input present, check for input mapping and processing.
   1526 	 */
   1527 	first = 1;
   1528 	while ((c = getc(qp)) >= 0) {
   1529 		/*
   1530 		 * delayed suspend (^Y)
   1531 		 */
   1532 		if (CCEQ(cc[VDSUSP], c) &&
   1533 		    ISSET(lflag, IEXTEN|ISIG) == (IEXTEN|ISIG)) {
   1534 			pgsignal(tp->t_pgrp, SIGTSTP, 1);
   1535 			if (first) {
   1536 				error = ttysleep(tp, &lbolt,
   1537 						 TTIPRI | PCATCH, ttybg, 0);
   1538 				if (error)
   1539 					break;
   1540 				goto loop;
   1541 			}
   1542 			break;
   1543 		}
   1544 		/*
   1545 		 * Interpret EOF only in canonical mode.
   1546 		 */
   1547 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
   1548 			break;
   1549 		/*
   1550 		 * Give user character.
   1551 		 */
   1552  		error = ureadc(c, uio);
   1553 		if (error)
   1554 			break;
   1555  		if (uio->uio_resid == 0)
   1556 			break;
   1557 		/*
   1558 		 * In canonical mode check for a "break character"
   1559 		 * marking the end of a "line of input".
   1560 		 */
   1561 		if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
   1562 			break;
   1563 		first = 0;
   1564 	}
   1565 	/*
   1566 	 * Look to unblock output now that (presumably)
   1567 	 * the input queue has gone down.
   1568 	 */
   1569 	s = spltty();
   1570 	if (ISSET(tp->t_state, TS_TBLOCK) && tp->t_rawq.c_cc < TTYHOG/5) {
   1571 		if (ISSET(tp->t_iflag, IXOFF) &&
   1572 		    cc[VSTART] != _POSIX_VDISABLE &&
   1573 		    putc(cc[VSTART], &tp->t_outq) == 0) {
   1574 			CLR(tp->t_state, TS_TBLOCK);
   1575 			ttstart(tp);
   1576 		}
   1577 		/* Try to unblock remote output via hardware flow control. */
   1578 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
   1579 		    (*tp->t_hwiflow)(tp, 0) != 0)
   1580 			CLR(tp->t_state, TS_TBLOCK);
   1581 	}
   1582 	splx(s);
   1583 	return (error);
   1584 }
   1585 
   1586 /*
   1587  * Check the output queue on tp for space for a kernel message (from uprintf
   1588  * or tprintf).  Allow some space over the normal hiwater mark so we don't
   1589  * lose messages due to normal flow control, but don't let the tty run amok.
   1590  * Sleeps here are not interruptible, but we return prematurely if new signals
   1591  * arrive.
   1592  */
   1593 int
   1594 ttycheckoutq(struct tty *tp, int wait)
   1595 {
   1596 	int	hiwat, s, error;
   1597 
   1598 	hiwat = tp->t_hiwat;
   1599 	s = spltty();
   1600 	if (tp->t_outq.c_cc > hiwat + 200)
   1601 		while (tp->t_outq.c_cc > hiwat) {
   1602 			ttstart(tp);
   1603 			if (wait == 0) {
   1604 				splx(s);
   1605 				return (0);
   1606 			}
   1607 			callout_reset(&tp->t_outq_ch, hz,
   1608 			    (void (*)__P((void *)))wakeup, &tp->t_outq);
   1609 			SET(tp->t_state, TS_ASLEEP);
   1610 			error = tsleep(&tp->t_outq, (PZERO - 1) | PCATCH,
   1611 			    "ttckoutq", 0);
   1612 			if (error == EINTR)
   1613 				wait = 0;
   1614 		}
   1615 	splx(s);
   1616 	return (1);
   1617 }
   1618 
   1619 /*
   1620  * Process a write call on a tty device.
   1621  */
   1622 int
   1623 ttwrite(struct tty *tp, struct uio *uio, int flag)
   1624 {
   1625 	u_char		*cp;
   1626 	struct proc	*p;
   1627 	int		cc, ce, i, hiwat, cnt, error, s;
   1628 	u_char		obuf[OBUFSIZ];
   1629 
   1630 	cp = NULL;
   1631 	hiwat = tp->t_hiwat;
   1632 	cnt = uio->uio_resid;
   1633 	error = 0;
   1634 	cc = 0;
   1635  loop:
   1636 	s = spltty();
   1637 	if (!CONNECTED(tp)) {
   1638 		if (ISSET(tp->t_state, TS_ISOPEN)) {
   1639 			splx(s);
   1640 			return (EIO);
   1641 		} else if (flag & IO_NDELAY) {
   1642 			splx(s);
   1643 			error = EWOULDBLOCK;
   1644 			goto out;
   1645 		} else {
   1646 			/* Sleep awaiting carrier. */
   1647 			error = ttysleep(tp,
   1648 			    &tp->t_rawq, TTIPRI | PCATCH, ttopen, 0);
   1649 			splx(s);
   1650 			if (error)
   1651 				goto out;
   1652 			goto loop;
   1653 		}
   1654 	}
   1655 	splx(s);
   1656 	/*
   1657 	 * Hang the process if it's in the background.
   1658 	 */
   1659 	p = curproc;
   1660 	if (isbackground(p, tp) &&
   1661 	    ISSET(tp->t_lflag, TOSTOP) && (p->p_flag & P_PPWAIT) == 0 &&
   1662 	    !sigismember(&p->p_sigctx.ps_sigignore, SIGTTOU) &&
   1663 	    !sigismember(&p->p_sigctx.ps_sigmask, SIGTTOU)) {
   1664 		if (p->p_pgrp->pg_jobc == 0) {
   1665 			error = EIO;
   1666 			goto out;
   1667 		}
   1668 		pgsignal(p->p_pgrp, SIGTTOU, 1);
   1669 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, ttybg, 0);
   1670 		if (error)
   1671 			goto out;
   1672 		goto loop;
   1673 	}
   1674 	/*
   1675 	 * Process the user's data in at most OBUFSIZ chunks.  Perform any
   1676 	 * output translation.  Keep track of high water mark, sleep on
   1677 	 * overflow awaiting device aid in acquiring new space.
   1678 	 */
   1679 	while (uio->uio_resid > 0 || cc > 0) {
   1680 		if (ISSET(tp->t_lflag, FLUSHO)) {
   1681 			uio->uio_resid = 0;
   1682 			return (0);
   1683 		}
   1684 		if (tp->t_outq.c_cc > hiwat)
   1685 			goto ovhiwat;
   1686 		/*
   1687 		 * Grab a hunk of data from the user, unless we have some
   1688 		 * leftover from last time.
   1689 		 */
   1690 		if (cc == 0) {
   1691 			cc = min(uio->uio_resid, OBUFSIZ);
   1692 			cp = obuf;
   1693 			error = uiomove(cp, cc, uio);
   1694 			if (error) {
   1695 				cc = 0;
   1696 				break;
   1697 			}
   1698 		}
   1699 		/*
   1700 		 * If nothing fancy need be done, grab those characters we
   1701 		 * can handle without any of ttyoutput's processing and
   1702 		 * just transfer them to the output q.  For those chars
   1703 		 * which require special processing (as indicated by the
   1704 		 * bits in char_type), call ttyoutput.  After processing
   1705 		 * a hunk of data, look for FLUSHO so ^O's will take effect
   1706 		 * immediately.
   1707 		 */
   1708 		while (cc > 0) {
   1709 			if (!ISSET(tp->t_oflag, OPOST))
   1710 				ce = cc;
   1711 			else {
   1712 				ce = cc - scanc((u_int)cc, cp, char_type,
   1713 				    CCLASSMASK);
   1714 				/*
   1715 				 * If ce is zero, then we're processing
   1716 				 * a special character through ttyoutput.
   1717 				 */
   1718 				if (ce == 0) {
   1719 					tp->t_rocount = 0;
   1720 					if (ttyoutput(*cp, tp) >= 0) {
   1721 						/* out of space */
   1722 						goto overfull;
   1723 					}
   1724 					cp++;
   1725 					cc--;
   1726 					if (ISSET(tp->t_lflag, FLUSHO) ||
   1727 					    tp->t_outq.c_cc > hiwat)
   1728 						goto ovhiwat;
   1729 					continue;
   1730 				}
   1731 			}
   1732 			/*
   1733 			 * A bunch of normal characters have been found.
   1734 			 * Transfer them en masse to the output queue and
   1735 			 * continue processing at the top of the loop.
   1736 			 * If there are any further characters in this
   1737 			 * <= OBUFSIZ chunk, the first should be a character
   1738 			 * requiring special handling by ttyoutput.
   1739 			 */
   1740 			tp->t_rocount = 0;
   1741 			i = b_to_q(cp, ce, &tp->t_outq);
   1742 			ce -= i;
   1743 			tp->t_column += ce;
   1744 			cp += ce, cc -= ce, tk_nout += ce;
   1745 			tp->t_outcc += ce;
   1746 			if (i > 0) {
   1747 				/* out of space */
   1748 				goto overfull;
   1749 			}
   1750 			if (ISSET(tp->t_lflag, FLUSHO) ||
   1751 			    tp->t_outq.c_cc > hiwat)
   1752 				break;
   1753 		}
   1754 		ttstart(tp);
   1755 	}
   1756  out:
   1757 	/*
   1758 	 * If cc is nonzero, we leave the uio structure inconsistent, as the
   1759 	 * offset and iov pointers have moved forward, but it doesn't matter
   1760 	 * (the call will either return short or restart with a new uio).
   1761 	 */
   1762 	uio->uio_resid += cc;
   1763 	return (error);
   1764 
   1765  overfull:
   1766 	/*
   1767 	 * Since we are using ring buffers, if we can't insert any more into
   1768 	 * the output queue, we can assume the ring is full and that someone
   1769 	 * forgot to set the high water mark correctly.  We set it and then
   1770 	 * proceed as normal.
   1771 	 */
   1772 	hiwat = tp->t_outq.c_cc - 1;
   1773 
   1774  ovhiwat:
   1775 	ttstart(tp);
   1776 	s = spltty();
   1777 	/*
   1778 	 * This can only occur if FLUSHO is set in t_lflag,
   1779 	 * or if ttstart/oproc is synchronous (or very fast).
   1780 	 */
   1781 	if (tp->t_outq.c_cc <= hiwat) {
   1782 		splx(s);
   1783 		goto loop;
   1784 	}
   1785 	if (flag & IO_NDELAY) {
   1786 		splx(s);
   1787 		uio->uio_resid += cc;
   1788 		return (uio->uio_resid == cnt ? EWOULDBLOCK : 0);
   1789 	}
   1790 	SET(tp->t_state, TS_ASLEEP);
   1791 	error = ttysleep(tp, &tp->t_outq, TTOPRI | PCATCH, ttyout, 0);
   1792 	splx(s);
   1793 	if (error)
   1794 		goto out;
   1795 	goto loop;
   1796 }
   1797 
   1798 /*
   1799  * Rubout one character from the rawq of tp
   1800  * as cleanly as possible.
   1801  */
   1802 void
   1803 ttyrub(int c, struct tty *tp)
   1804 {
   1805 	u_char	*cp;
   1806 	int	savecol, tabc, s;
   1807 
   1808 	if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
   1809 		return;
   1810 	CLR(tp->t_lflag, FLUSHO);
   1811 	if (ISSET(tp->t_lflag, ECHOE)) {
   1812 		if (tp->t_rocount == 0) {
   1813 			/*
   1814 			 * Screwed by ttwrite; retype
   1815 			 */
   1816 			ttyretype(tp);
   1817 			return;
   1818 		}
   1819 		if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
   1820 			ttyrubo(tp, 2);
   1821 		else {
   1822 			CLR(c, ~TTY_CHARMASK);
   1823 			switch (CCLASS(c)) {
   1824 			case ORDINARY:
   1825 				ttyrubo(tp, 1);
   1826 				break;
   1827 			case BACKSPACE:
   1828 			case CONTROL:
   1829 			case NEWLINE:
   1830 			case RETURN:
   1831 			case VTAB:
   1832 				if (ISSET(tp->t_lflag, ECHOCTL))
   1833 					ttyrubo(tp, 2);
   1834 				break;
   1835 			case TAB:
   1836 				if (tp->t_rocount < tp->t_rawq.c_cc) {
   1837 					ttyretype(tp);
   1838 					return;
   1839 				}
   1840 				s = spltty();
   1841 				savecol = tp->t_column;
   1842 				SET(tp->t_state, TS_CNTTB);
   1843 				SET(tp->t_lflag, FLUSHO);
   1844 				tp->t_column = tp->t_rocol;
   1845 				for (cp = firstc(&tp->t_rawq, &tabc); cp;
   1846 				    cp = nextc(&tp->t_rawq, cp, &tabc))
   1847 					ttyecho(tabc, tp);
   1848 				CLR(tp->t_lflag, FLUSHO);
   1849 				CLR(tp->t_state, TS_CNTTB);
   1850 				splx(s);
   1851 
   1852 				/* savecol will now be length of the tab. */
   1853 				savecol -= tp->t_column;
   1854 				tp->t_column += savecol;
   1855 				if (savecol > 8)
   1856 					savecol = 8;	/* overflow screw */
   1857 				while (--savecol >= 0)
   1858 					(void)ttyoutput('\b', tp);
   1859 				break;
   1860 			default:			/* XXX */
   1861 #define	PANICSTR	"ttyrub: would panic c = %d, val = %d\n"
   1862 				(void)printf(PANICSTR, c, CCLASS(c));
   1863 #ifdef notdef
   1864 				panic(PANICSTR, c, CCLASS(c));
   1865 #endif
   1866 			}
   1867 		}
   1868 	} else if (ISSET(tp->t_lflag, ECHOPRT)) {
   1869 		if (!ISSET(tp->t_state, TS_ERASE)) {
   1870 			SET(tp->t_state, TS_ERASE);
   1871 			(void)ttyoutput('\\', tp);
   1872 		}
   1873 		ttyecho(c, tp);
   1874 	} else
   1875 		ttyecho(tp->t_cc[VERASE], tp);
   1876 	--tp->t_rocount;
   1877 }
   1878 
   1879 /*
   1880  * Back over cnt characters, erasing them.
   1881  */
   1882 static void
   1883 ttyrubo(struct tty *tp, int cnt)
   1884 {
   1885 
   1886 	while (cnt-- > 0) {
   1887 		(void)ttyoutput('\b', tp);
   1888 		(void)ttyoutput(' ', tp);
   1889 		(void)ttyoutput('\b', tp);
   1890 	}
   1891 }
   1892 
   1893 /*
   1894  * ttyretype --
   1895  *	Reprint the rawq line.  Note, it is assumed that c_cc has already
   1896  *	been checked.
   1897  */
   1898 void
   1899 ttyretype(struct tty *tp)
   1900 {
   1901 	u_char	*cp;
   1902 	int	s, c;
   1903 
   1904 	/* Echo the reprint character. */
   1905 	if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
   1906 		ttyecho(tp->t_cc[VREPRINT], tp);
   1907 
   1908 	(void)ttyoutput('\n', tp);
   1909 
   1910 	s = spltty();
   1911 	for (cp = firstc(&tp->t_canq, &c); cp; cp = nextc(&tp->t_canq, cp, &c))
   1912 		ttyecho(c, tp);
   1913 	for (cp = firstc(&tp->t_rawq, &c); cp; cp = nextc(&tp->t_rawq, cp, &c))
   1914 		ttyecho(c, tp);
   1915 	CLR(tp->t_state, TS_ERASE);
   1916 	splx(s);
   1917 
   1918 	tp->t_rocount = tp->t_rawq.c_cc;
   1919 	tp->t_rocol = 0;
   1920 }
   1921 
   1922 /*
   1923  * Echo a typed character to the terminal.
   1924  */
   1925 static void
   1926 ttyecho(int c, struct tty *tp)
   1927 {
   1928 
   1929 	if (!ISSET(tp->t_state, TS_CNTTB))
   1930 		CLR(tp->t_lflag, FLUSHO);
   1931 	if ((!ISSET(tp->t_lflag, ECHO) &&
   1932 	    (!ISSET(tp->t_lflag, ECHONL) || c != '\n')) ||
   1933 	    ISSET(tp->t_lflag, EXTPROC))
   1934 		return;
   1935 	if (((ISSET(tp->t_lflag, ECHOCTL) &&
   1936 	     (ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n')) ||
   1937 	    ISSET(c, TTY_CHARMASK) == 0177)) {
   1938 		(void)ttyoutput('^', tp);
   1939 		CLR(c, ~TTY_CHARMASK);
   1940 		if (c == 0177)
   1941 			c = '?';
   1942 		else
   1943 			c += 'A' - 1;
   1944 	}
   1945 	(void)ttyoutput(c, tp);
   1946 }
   1947 
   1948 /*
   1949  * Wake up any readers on a tty.
   1950  */
   1951 void
   1952 ttwakeup(struct tty *tp)
   1953 {
   1954 
   1955 	selnotify(&tp->t_rsel, 0);
   1956 	if (ISSET(tp->t_state, TS_ASYNC))
   1957 		pgsignal(tp->t_pgrp, SIGIO, 1);
   1958 	wakeup((caddr_t)&tp->t_rawq);
   1959 }
   1960 
   1961 /*
   1962  * Look up a code for a specified speed in a conversion table;
   1963  * used by drivers to map software speed values to hardware parameters.
   1964  */
   1965 int
   1966 ttspeedtab(int speed, struct speedtab *table)
   1967 {
   1968 
   1969 	for ( ; table->sp_speed != -1; table++)
   1970 		if (table->sp_speed == speed)
   1971 			return (table->sp_code);
   1972 	return (-1);
   1973 }
   1974 
   1975 /*
   1976  * Set tty hi and low water marks.
   1977  *
   1978  * Try to arrange the dynamics so there's about one second
   1979  * from hi to low water.
   1980  */
   1981 void
   1982 ttsetwater(struct tty *tp)
   1983 {
   1984 	int	cps, x;
   1985 
   1986 #define	CLAMP(x, h, l)	((x) > h ? h : ((x) < l) ? l : (x))
   1987 
   1988 	cps = tp->t_ospeed / 10;
   1989 	tp->t_lowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
   1990 	x += cps;
   1991 	x = CLAMP(x, TTMAXHIWAT, TTMINHIWAT);
   1992 	tp->t_hiwat = roundup(x, CBSIZE);
   1993 #undef	CLAMP
   1994 }
   1995 
   1996 /*
   1997  * Report on state of foreground process group.
   1998  */
   1999 void
   2000 ttyinfo(struct tty *tp)
   2001 {
   2002 	struct proc	*p, *pick;
   2003 	struct timeval	utime, stime;
   2004 	int		tmp;
   2005 
   2006 	if (ttycheckoutq(tp,0) == 0)
   2007 		return;
   2008 
   2009 	/* Print load average. */
   2010 	tmp = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
   2011 	ttyprintf(tp, "load: %d.%02d ", tmp / 100, tmp % 100);
   2012 
   2013 	if (tp->t_session == NULL)
   2014 		ttyprintf(tp, "not a controlling terminal\n");
   2015 	else if (tp->t_pgrp == NULL)
   2016 		ttyprintf(tp, "no foreground process group\n");
   2017 	else if ((p = tp->t_pgrp->pg_members.lh_first) == 0)
   2018 		ttyprintf(tp, "empty foreground process group\n");
   2019 	else {
   2020 		/* Pick interesting process. */
   2021 		for (pick = NULL; p != NULL; p = p->p_pglist.le_next)
   2022 			if (proc_compare(pick, p))
   2023 				pick = p;
   2024 
   2025 		ttyprintf(tp, " cmd: %s %d [%s] ", pick->p_comm, pick->p_pid,
   2026 		    pick->p_stat == SONPROC ? "running" :
   2027 		    pick->p_stat == SRUN ? "runnable" :
   2028 		    pick->p_wmesg ? pick->p_wmesg : "iowait");
   2029 
   2030 		calcru(pick, &utime, &stime, NULL);
   2031 
   2032 		/* Round up and print user time. */
   2033 		utime.tv_usec += 5000;
   2034 		if (utime.tv_usec >= 1000000) {
   2035 			utime.tv_sec += 1;
   2036 			utime.tv_usec -= 1000000;
   2037 		}
   2038 		ttyprintf(tp, "%ld.%02ldu ", (long int)utime.tv_sec,
   2039 		    (long int)utime.tv_usec / 10000);
   2040 
   2041 		/* Round up and print system time. */
   2042 		stime.tv_usec += 5000;
   2043 		if (stime.tv_usec >= 1000000) {
   2044 			stime.tv_sec += 1;
   2045 			stime.tv_usec -= 1000000;
   2046 		}
   2047 		ttyprintf(tp, "%ld.%02lds ", (long int)stime.tv_sec,
   2048 		    (long int)stime.tv_usec / 10000);
   2049 
   2050 #define	pgtok(a)	(((u_long) ((a) * PAGE_SIZE) / 1024))
   2051 		/* Print percentage cpu. */
   2052 		tmp = (pick->p_pctcpu * 10000 + FSCALE / 2) >> FSHIFT;
   2053 		ttyprintf(tp, "%d%% ", tmp / 100);
   2054 
   2055 		/* Print resident set size. */
   2056 		if (pick->p_stat == SIDL || P_ZOMBIE(pick))
   2057 			tmp = 0;
   2058 		else {
   2059 			struct vmspace *vm = pick->p_vmspace;
   2060 			tmp = pgtok(vm_resident_count(vm));
   2061 		}
   2062 		ttyprintf(tp, "%dk\n", tmp);
   2063 	}
   2064 	tp->t_rocount = 0;	/* so pending input will be retyped if BS */
   2065 }
   2066 
   2067 /*
   2068  * Returns 1 if p2 is "better" than p1
   2069  *
   2070  * The algorithm for picking the "interesting" process is thus:
   2071  *
   2072  *	1) Only foreground processes are eligible - implied.
   2073  *	2) Runnable processes are favored over anything else.  The runner
   2074  *	   with the highest cpu utilization is picked (p_estcpu).  Ties are
   2075  *	   broken by picking the highest pid.
   2076  *	3) The sleeper with the shortest sleep time is next.  With ties,
   2077  *	   we pick out just "short-term" sleepers (P_SINTR == 0).
   2078  *	4) Further ties are broken by picking the highest pid.
   2079  */
   2080 #define	ISRUN(p)	(((p)->p_stat == SRUN) || ((p)->p_stat == SIDL) || \
   2081 			 ((p)->p_stat == SONPROC))
   2082 #define	TESTAB(a, b)    ((a)<<1 | (b))
   2083 #define	ONLYA   2
   2084 #define	ONLYB   1
   2085 #define	BOTH    3
   2086 
   2087 static int
   2088 proc_compare(struct proc *p1, struct proc *p2)
   2089 {
   2090 
   2091 	if (p1 == NULL)
   2092 		return (1);
   2093 	/*
   2094 	 * see if at least one of them is runnable
   2095 	 */
   2096 	switch (TESTAB(ISRUN(p1), ISRUN(p2))) {
   2097 	case ONLYA:
   2098 		return (0);
   2099 	case ONLYB:
   2100 		return (1);
   2101 	case BOTH:
   2102 		/*
   2103 		 * tie - favor one with highest recent cpu utilization
   2104 		 */
   2105 		if (p2->p_estcpu > p1->p_estcpu)
   2106 			return (1);
   2107 		if (p1->p_estcpu > p2->p_estcpu)
   2108 			return (0);
   2109 		return (p2->p_pid > p1->p_pid);	/* tie - return highest pid */
   2110 	}
   2111 	/*
   2112  	 * weed out zombies
   2113 	 */
   2114 	switch (TESTAB(P_ZOMBIE(p1), P_ZOMBIE(p2))) {
   2115 	case ONLYA:
   2116 		return (1);
   2117 	case ONLYB:
   2118 		return (0);
   2119 	case BOTH:
   2120 		return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
   2121 	}
   2122 	/*
   2123 	 * pick the one with the smallest sleep time
   2124 	 */
   2125 	if (p2->p_slptime > p1->p_slptime)
   2126 		return (0);
   2127 	if (p1->p_slptime > p2->p_slptime)
   2128 		return (1);
   2129 	/*
   2130 	 * favor one sleeping in a non-interruptible sleep
   2131 	 */
   2132 	if (p1->p_flag & P_SINTR && (p2->p_flag & P_SINTR) == 0)
   2133 		return (1);
   2134 	if (p2->p_flag & P_SINTR && (p1->p_flag & P_SINTR) == 0)
   2135 		return (0);
   2136 	return (p2->p_pid > p1->p_pid);		/* tie - return highest pid */
   2137 }
   2138 
   2139 /*
   2140  * Output char to tty; console putchar style.
   2141  */
   2142 int
   2143 tputchar(int c, struct tty *tp)
   2144 {
   2145 	int	s;
   2146 
   2147 	s = spltty();
   2148 	if (ISSET(tp->t_state,
   2149 	    TS_CARR_ON | TS_ISOPEN) != (TS_CARR_ON | TS_ISOPEN)) {
   2150 		splx(s);
   2151 		return (-1);
   2152 	}
   2153 	if (c == '\n')
   2154 		(void)ttyoutput('\r', tp);
   2155 	(void)ttyoutput(c, tp);
   2156 	ttstart(tp);
   2157 	splx(s);
   2158 	return (0);
   2159 }
   2160 
   2161 /*
   2162  * Sleep on chan, returning ERESTART if tty changed while we napped and
   2163  * returning any errors (e.g. EINTR/ETIMEDOUT) reported by tsleep.  If
   2164  * the tty is revoked, restarting a pending call will redo validation done
   2165  * at the start of the call.
   2166  */
   2167 int
   2168 ttysleep(struct tty *tp, void *chan, int pri, const char *wmesg, int timo)
   2169 {
   2170 	int	error;
   2171 	short	gen;
   2172 
   2173 	gen = tp->t_gen;
   2174 	if ((error = tsleep(chan, pri, wmesg, timo)) != 0)
   2175 		return (error);
   2176 	return (tp->t_gen == gen ? 0 : ERESTART);
   2177 }
   2178 
   2179 /*
   2180  * Initialise the global tty list.
   2181  */
   2182 void
   2183 tty_init(void)
   2184 {
   2185 	ttyldisc_init();
   2186 
   2187 	TAILQ_INIT(&ttylist);
   2188 	tty_count = 0;
   2189 
   2190 	pool_init(&tty_pool, sizeof(struct tty), 0, 0, 0, "ttypl",
   2191 	    &pool_allocator_nointr);
   2192 }
   2193 
   2194 /*
   2195  * Attach a tty to the tty list.
   2196  *
   2197  * This should be called ONLY once per real tty (including pty's).
   2198  * eg, on the sparc, the keyboard and mouse have struct tty's that are
   2199  * distinctly NOT usable as tty's, and thus should not be attached to
   2200  * the ttylist.  This is why this call is not done from ttymalloc().
   2201  *
   2202  * Device drivers should attach tty's at a similar time that they are
   2203  * ttymalloc()'ed, or, for the case of statically allocated struct tty's
   2204  * either in the attach or (first) open routine.
   2205  */
   2206 void
   2207 tty_attach(struct tty *tp)
   2208 {
   2209 
   2210 	TAILQ_INSERT_TAIL(&ttylist, tp, tty_link);
   2211 	++tty_count;
   2212 }
   2213 
   2214 /*
   2215  * Remove a tty from the tty list.
   2216  */
   2217 void
   2218 tty_detach(struct tty *tp)
   2219 {
   2220 
   2221 	--tty_count;
   2222 #ifdef DIAGNOSTIC
   2223 	if (tty_count < 0)
   2224 		panic("tty_detach: tty_count < 0");
   2225 #endif
   2226 	TAILQ_REMOVE(&ttylist, tp, tty_link);
   2227 }
   2228 
   2229 /*
   2230  * Allocate a tty structure and its associated buffers.
   2231  */
   2232 struct tty *
   2233 ttymalloc(void)
   2234 {
   2235 	struct tty	*tp;
   2236 
   2237 	tp = pool_get(&tty_pool, PR_WAITOK);
   2238 	memset(tp, 0, sizeof(*tp));
   2239 	callout_init(&tp->t_outq_ch);
   2240 	callout_init(&tp->t_rstrt_ch);
   2241 	/* XXX: default to 1024 chars for now */
   2242 	clalloc(&tp->t_rawq, 1024, 1);
   2243 	clalloc(&tp->t_canq, 1024, 1);
   2244 	/* output queue doesn't need quoting */
   2245 	clalloc(&tp->t_outq, 1024, 0);
   2246 	/* Set default line discipline. */
   2247 	tp->t_linesw = linesw[0];
   2248 	return(tp);
   2249 }
   2250 
   2251 /*
   2252  * Free a tty structure and its buffers.
   2253  *
   2254  * Be sure to call tty_detach() for any tty that has been
   2255  * tty_attach()ed.
   2256  */
   2257 void
   2258 ttyfree(struct tty *tp)
   2259 {
   2260 
   2261 	callout_stop(&tp->t_outq_ch);
   2262 	callout_stop(&tp->t_rstrt_ch);
   2263 	clfree(&tp->t_rawq);
   2264 	clfree(&tp->t_canq);
   2265 	clfree(&tp->t_outq);
   2266 	pool_put(&tty_pool, tp);
   2267 }
   2268