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