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