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