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