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