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