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