Home | History | Annotate | Line # | Download | only in kern
tty.c revision 1.83
      1 /*	$NetBSD: tty.c,v 1.83 1997/04/04 21:02:28 mycroft 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)							\
    225 	((c) == '\n' || ((c) == cc[VEOF] ||				\
    226 	(c) == cc[VEOL] || (((c) == cc[VEOL2]) && (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)) {
    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))
   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 	     p->p_pgrp->pg_jobc) {
   1505 		pgsignal(p->p_pgrp, SIGTTOU, 1);
   1506 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, ttybg, 0);
   1507 		if (error)
   1508 			goto out;
   1509 		goto loop;
   1510 	}
   1511 	/*
   1512 	 * Process the user's data in at most OBUFSIZ chunks.  Perform any
   1513 	 * output translation.  Keep track of high water mark, sleep on
   1514 	 * overflow awaiting device aid in acquiring new space.
   1515 	 */
   1516 	while (uio->uio_resid > 0 || cc > 0) {
   1517 		if (ISSET(tp->t_lflag, FLUSHO)) {
   1518 			uio->uio_resid = 0;
   1519 			return (0);
   1520 		}
   1521 		if (tp->t_outq.c_cc > hiwat)
   1522 			goto ovhiwat;
   1523 		/*
   1524 		 * Grab a hunk of data from the user, unless we have some
   1525 		 * leftover from last time.
   1526 		 */
   1527 		if (cc == 0) {
   1528 			cc = min(uio->uio_resid, OBUFSIZ);
   1529 			cp = obuf;
   1530 			error = uiomove(cp, cc, uio);
   1531 			if (error) {
   1532 				cc = 0;
   1533 				break;
   1534 			}
   1535 		}
   1536 		/*
   1537 		 * If nothing fancy need be done, grab those characters we
   1538 		 * can handle without any of ttyoutput's processing and
   1539 		 * just transfer them to the output q.  For those chars
   1540 		 * which require special processing (as indicated by the
   1541 		 * bits in char_type), call ttyoutput.  After processing
   1542 		 * a hunk of data, look for FLUSHO so ^O's will take effect
   1543 		 * immediately.
   1544 		 */
   1545 		while (cc > 0) {
   1546 			if (!ISSET(tp->t_oflag, OPOST))
   1547 				ce = cc;
   1548 			else {
   1549 				ce = cc - scanc((u_int)cc, cp, char_type,
   1550 				    CCLASSMASK);
   1551 				/*
   1552 				 * If ce is zero, then we're processing
   1553 				 * a special character through ttyoutput.
   1554 				 */
   1555 				if (ce == 0) {
   1556 					tp->t_rocount = 0;
   1557 					if (ttyoutput(*cp, tp) >= 0) {
   1558 #ifdef REAL_CLISTS
   1559 						/* No Clists, wait a bit. */
   1560 						ttstart(tp);
   1561 						if (error = ttysleep(tp, &lbolt,
   1562 						    TTOPRI | PCATCH, ttybuf, 0))
   1563 							break;
   1564 						goto loop;
   1565 #else
   1566 						/* out of space */
   1567 						goto overfull;
   1568 #endif
   1569 					}
   1570 					cp++;
   1571 					cc--;
   1572 					if (ISSET(tp->t_lflag, FLUSHO) ||
   1573 					    tp->t_outq.c_cc > hiwat)
   1574 						goto ovhiwat;
   1575 					continue;
   1576 				}
   1577 			}
   1578 			/*
   1579 			 * A bunch of normal characters have been found.
   1580 			 * Transfer them en masse to the output queue and
   1581 			 * continue processing at the top of the loop.
   1582 			 * If there are any further characters in this
   1583 			 * <= OBUFSIZ chunk, the first should be a character
   1584 			 * requiring special handling by ttyoutput.
   1585 			 */
   1586 			tp->t_rocount = 0;
   1587 			i = b_to_q(cp, ce, &tp->t_outq);
   1588 			ce -= i;
   1589 			tp->t_column += ce;
   1590 			cp += ce, cc -= ce, tk_nout += ce;
   1591 			tp->t_outcc += ce;
   1592 			if (i > 0) {
   1593 #ifdef REAL_CLISTS
   1594 				/* No Clists, wait a bit. */
   1595 				ttstart(tp);
   1596 				if (error = ttysleep(tp,
   1597 				    &lbolt, TTOPRI | PCATCH, ttybuf, 0))
   1598 					break;
   1599 				goto loop;
   1600 #else
   1601 				/* out of space */
   1602 				goto overfull;
   1603 #endif
   1604 			}
   1605 			if (ISSET(tp->t_lflag, FLUSHO) ||
   1606 			    tp->t_outq.c_cc > hiwat)
   1607 				break;
   1608 		}
   1609 		ttstart(tp);
   1610 	}
   1611 out:
   1612 	/*
   1613 	 * If cc is nonzero, we leave the uio structure inconsistent, as the
   1614 	 * offset and iov pointers have moved forward, but it doesn't matter
   1615 	 * (the call will either return short or restart with a new uio).
   1616 	 */
   1617 	uio->uio_resid += cc;
   1618 	return (error);
   1619 
   1620 #ifndef REAL_CLISTS
   1621 overfull:
   1622 	/*
   1623 	 * Since we are using ring buffers, if we can't insert any more into
   1624 	 * the output queue, we can assume the ring is full and that someone
   1625 	 * forgot to set the high water mark correctly.  We set it and then
   1626 	 * proceed as normal.
   1627 	 */
   1628 	hiwat = tp->t_outq.c_cc - 1;
   1629 #endif
   1630 
   1631 ovhiwat:
   1632 	ttstart(tp);
   1633 	s = spltty();
   1634 	/*
   1635 	 * This can only occur if FLUSHO is set in t_lflag,
   1636 	 * or if ttstart/oproc is synchronous (or very fast).
   1637 	 */
   1638 	if (tp->t_outq.c_cc <= hiwat) {
   1639 		splx(s);
   1640 		goto loop;
   1641 	}
   1642 	if (flag & IO_NDELAY) {
   1643 		splx(s);
   1644 		uio->uio_resid += cc;
   1645 		return (uio->uio_resid == cnt ? EWOULDBLOCK : 0);
   1646 	}
   1647 	SET(tp->t_state, TS_ASLEEP);
   1648 	error = ttysleep(tp, &tp->t_outq, TTOPRI | PCATCH, ttyout, 0);
   1649 	splx(s);
   1650 	if (error)
   1651 		goto out;
   1652 	goto loop;
   1653 }
   1654 
   1655 /*
   1656  * Rubout one character from the rawq of tp
   1657  * as cleanly as possible.
   1658  */
   1659 void
   1660 ttyrub(c, tp)
   1661 	int c;
   1662 	register struct tty *tp;
   1663 {
   1664 	register u_char *cp;
   1665 	register int savecol;
   1666 	int tabc, s;
   1667 
   1668 	if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
   1669 		return;
   1670 	CLR(tp->t_lflag, FLUSHO);
   1671 	if (ISSET(tp->t_lflag, ECHOE)) {
   1672 		if (tp->t_rocount == 0) {
   1673 			/*
   1674 			 * Screwed by ttwrite; retype
   1675 			 */
   1676 			ttyretype(tp);
   1677 			return;
   1678 		}
   1679 		if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
   1680 			ttyrubo(tp, 2);
   1681 		else {
   1682 			CLR(c, ~TTY_CHARMASK);
   1683 			switch (CCLASS(c)) {
   1684 			case ORDINARY:
   1685 				ttyrubo(tp, 1);
   1686 				break;
   1687 			case BACKSPACE:
   1688 			case CONTROL:
   1689 			case NEWLINE:
   1690 			case RETURN:
   1691 			case VTAB:
   1692 				if (ISSET(tp->t_lflag, ECHOCTL))
   1693 					ttyrubo(tp, 2);
   1694 				break;
   1695 			case TAB:
   1696 				if (tp->t_rocount < tp->t_rawq.c_cc) {
   1697 					ttyretype(tp);
   1698 					return;
   1699 				}
   1700 				s = spltty();
   1701 				savecol = tp->t_column;
   1702 				SET(tp->t_state, TS_CNTTB);
   1703 				SET(tp->t_lflag, FLUSHO);
   1704 				tp->t_column = tp->t_rocol;
   1705 				for (cp = firstc(&tp->t_rawq, &tabc); cp;
   1706 				    cp = nextc(&tp->t_rawq, cp, &tabc))
   1707 					ttyecho(tabc, tp);
   1708 				CLR(tp->t_lflag, FLUSHO);
   1709 				CLR(tp->t_state, TS_CNTTB);
   1710 				splx(s);
   1711 
   1712 				/* savecol will now be length of the tab. */
   1713 				savecol -= tp->t_column;
   1714 				tp->t_column += savecol;
   1715 				if (savecol > 8)
   1716 					savecol = 8;	/* overflow screw */
   1717 				while (--savecol >= 0)
   1718 					(void)ttyoutput('\b', tp);
   1719 				break;
   1720 			default:			/* XXX */
   1721 #define	PANICSTR	"ttyrub: would panic c = %d, val = %d\n"
   1722 				(void)printf(PANICSTR, c, CCLASS(c));
   1723 #ifdef notdef
   1724 				panic(PANICSTR, c, CCLASS(c));
   1725 #endif
   1726 			}
   1727 		}
   1728 	} else if (ISSET(tp->t_lflag, ECHOPRT)) {
   1729 		if (!ISSET(tp->t_state, TS_ERASE)) {
   1730 			SET(tp->t_state, TS_ERASE);
   1731 			(void)ttyoutput('\\', tp);
   1732 		}
   1733 		ttyecho(c, tp);
   1734 	} else
   1735 		ttyecho(tp->t_cc[VERASE], tp);
   1736 	--tp->t_rocount;
   1737 }
   1738 
   1739 /*
   1740  * Back over cnt characters, erasing them.
   1741  */
   1742 static void
   1743 ttyrubo(tp, cnt)
   1744 	register struct tty *tp;
   1745 	int cnt;
   1746 {
   1747 
   1748 	while (cnt-- > 0) {
   1749 		(void)ttyoutput('\b', tp);
   1750 		(void)ttyoutput(' ', tp);
   1751 		(void)ttyoutput('\b', tp);
   1752 	}
   1753 }
   1754 
   1755 /*
   1756  * ttyretype --
   1757  *	Reprint the rawq line.  Note, it is assumed that c_cc has already
   1758  *	been checked.
   1759  */
   1760 void
   1761 ttyretype(tp)
   1762 	register struct tty *tp;
   1763 {
   1764 	register u_char *cp;
   1765 	int s, c;
   1766 
   1767 	/* Echo the reprint character. */
   1768 	if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
   1769 		ttyecho(tp->t_cc[VREPRINT], tp);
   1770 
   1771 	(void)ttyoutput('\n', tp);
   1772 
   1773 	s = spltty();
   1774 	for (cp = firstc(&tp->t_canq, &c); cp; cp = nextc(&tp->t_canq, cp, &c))
   1775 		ttyecho(c, tp);
   1776 	for (cp = firstc(&tp->t_rawq, &c); cp; cp = nextc(&tp->t_rawq, cp, &c))
   1777 		ttyecho(c, tp);
   1778 	CLR(tp->t_state, TS_ERASE);
   1779 	splx(s);
   1780 
   1781 	tp->t_rocount = tp->t_rawq.c_cc;
   1782 	tp->t_rocol = 0;
   1783 }
   1784 
   1785 /*
   1786  * Echo a typed character to the terminal.
   1787  */
   1788 static void
   1789 ttyecho(c, tp)
   1790 	register int c;
   1791 	register struct tty *tp;
   1792 {
   1793 
   1794 	if (!ISSET(tp->t_state, TS_CNTTB))
   1795 		CLR(tp->t_lflag, FLUSHO);
   1796 	if ((!ISSET(tp->t_lflag, ECHO) &&
   1797 	    (!ISSET(tp->t_lflag, ECHONL) || c != '\n')) ||
   1798 	    ISSET(tp->t_lflag, EXTPROC))
   1799 		return;
   1800 	if (((ISSET(tp->t_lflag, ECHOCTL) &&
   1801 	     (ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n')) ||
   1802 	    ISSET(c, TTY_CHARMASK) == 0177)) {
   1803 		(void)ttyoutput('^', tp);
   1804 		CLR(c, ~TTY_CHARMASK);
   1805 		if (c == 0177)
   1806 			c = '?';
   1807 		else
   1808 			c += 'A' - 1;
   1809 	}
   1810 	(void)ttyoutput(c, tp);
   1811 }
   1812 
   1813 /*
   1814  * Wake up any readers on a tty.
   1815  */
   1816 void
   1817 ttwakeup(tp)
   1818 	register struct tty *tp;
   1819 {
   1820 
   1821 	selwakeup(&tp->t_rsel);
   1822 	if (ISSET(tp->t_state, TS_ASYNC))
   1823 		pgsignal(tp->t_pgrp, SIGIO, 1);
   1824 	wakeup((caddr_t)&tp->t_rawq);
   1825 }
   1826 
   1827 /*
   1828  * Look up a code for a specified speed in a conversion table;
   1829  * used by drivers to map software speed values to hardware parameters.
   1830  */
   1831 int
   1832 ttspeedtab(speed, table)
   1833 	int speed;
   1834 	register struct speedtab *table;
   1835 {
   1836 
   1837 	for ( ; table->sp_speed != -1; table++)
   1838 		if (table->sp_speed == speed)
   1839 			return (table->sp_code);
   1840 	return (-1);
   1841 }
   1842 
   1843 /*
   1844  * Set tty hi and low water marks.
   1845  *
   1846  * Try to arrange the dynamics so there's about one second
   1847  * from hi to low water.
   1848  */
   1849 void
   1850 ttsetwater(tp)
   1851 	struct tty *tp;
   1852 {
   1853 	register int cps, x;
   1854 
   1855 #define CLAMP(x, h, l)	((x) > h ? h : ((x) < l) ? l : (x))
   1856 
   1857 	cps = tp->t_ospeed / 10;
   1858 	tp->t_lowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
   1859 	x += cps;
   1860 	x = CLAMP(x, TTMAXHIWAT, TTMINHIWAT);
   1861 	tp->t_hiwat = roundup(x, CBSIZE);
   1862 #undef	CLAMP
   1863 }
   1864 
   1865 /*
   1866  * Report on state of foreground process group.
   1867  */
   1868 void
   1869 ttyinfo(tp)
   1870 	register struct tty *tp;
   1871 {
   1872 	register struct proc *p, *pick;
   1873 	struct timeval utime, stime;
   1874 	int tmp;
   1875 
   1876 	if (ttycheckoutq(tp,0) == 0)
   1877 		return;
   1878 
   1879 	/* Print load average. */
   1880 	tmp = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
   1881 	ttyprintf(tp, "load: %d.%02d ", tmp / 100, tmp % 100);
   1882 
   1883 	if (tp->t_session == NULL)
   1884 		ttyprintf(tp, "not a controlling terminal\n");
   1885 	else if (tp->t_pgrp == NULL)
   1886 		ttyprintf(tp, "no foreground process group\n");
   1887 	else if ((p = tp->t_pgrp->pg_members.lh_first) == 0)
   1888 		ttyprintf(tp, "empty foreground process group\n");
   1889 	else {
   1890 		/* Pick interesting process. */
   1891 		for (pick = NULL; p != 0; p = p->p_pglist.le_next)
   1892 			if (proc_compare(pick, p))
   1893 				pick = p;
   1894 
   1895 		ttyprintf(tp, " cmd: %s %d [%s] ", pick->p_comm, pick->p_pid,
   1896 		    pick->p_stat == SRUN ? "running" :
   1897 		    pick->p_wmesg ? pick->p_wmesg : "iowait");
   1898 
   1899 		calcru(pick, &utime, &stime, NULL);
   1900 
   1901 		/* Round up and print user time. */
   1902 		utime.tv_usec += 5000;
   1903 		if (utime.tv_usec >= 1000000) {
   1904 			utime.tv_sec += 1;
   1905 			utime.tv_usec -= 1000000;
   1906 		}
   1907 		ttyprintf(tp, "%ld.%02ldu ", utime.tv_sec,
   1908 		    utime.tv_usec / 10000);
   1909 
   1910 		/* Round up and print system time. */
   1911 		stime.tv_usec += 5000;
   1912 		if (stime.tv_usec >= 1000000) {
   1913 			stime.tv_sec += 1;
   1914 			stime.tv_usec -= 1000000;
   1915 		}
   1916 		ttyprintf(tp, "%ld.%02lds ", stime.tv_sec,
   1917 		    stime.tv_usec / 10000);
   1918 
   1919 #define	pgtok(a)	(((u_long) ((a) * NBPG) / 1024))
   1920 		/* Print percentage cpu, resident set size. */
   1921 		tmp = (pick->p_pctcpu * 10000 + FSCALE / 2) >> FSHIFT;
   1922 		ttyprintf(tp, "%d%% %ldk\n",
   1923 		    tmp / 100,
   1924 		    pick->p_stat == SIDL || pick->p_stat == SZOMB ? 0 :
   1925 #ifdef pmap_resident_count
   1926 			pgtok(pmap_resident_count(&pick->p_vmspace->vm_pmap))
   1927 #else
   1928 			pgtok(pick->p_vmspace->vm_rssize)
   1929 #endif
   1930 			);
   1931 	}
   1932 	tp->t_rocount = 0;	/* so pending input will be retyped if BS */
   1933 }
   1934 
   1935 /*
   1936  * Returns 1 if p2 is "better" than p1
   1937  *
   1938  * The algorithm for picking the "interesting" process is thus:
   1939  *
   1940  *	1) Only foreground processes are eligible - implied.
   1941  *	2) Runnable processes are favored over anything else.  The runner
   1942  *	   with the highest cpu utilization is picked (p_estcpu).  Ties are
   1943  *	   broken by picking the highest pid.
   1944  *	3) The sleeper with the shortest sleep time is next.  With ties,
   1945  *	   we pick out just "short-term" sleepers (P_SINTR == 0).
   1946  *	4) Further ties are broken by picking the highest pid.
   1947  */
   1948 #define ISRUN(p)	(((p)->p_stat == SRUN) || ((p)->p_stat == SIDL))
   1949 #define TESTAB(a, b)    ((a)<<1 | (b))
   1950 #define ONLYA   2
   1951 #define ONLYB   1
   1952 #define BOTH    3
   1953 
   1954 static int
   1955 proc_compare(p1, p2)
   1956 	register struct proc *p1, *p2;
   1957 {
   1958 
   1959 	if (p1 == NULL)
   1960 		return (1);
   1961 	/*
   1962 	 * see if at least one of them is runnable
   1963 	 */
   1964 	switch (TESTAB(ISRUN(p1), ISRUN(p2))) {
   1965 	case ONLYA:
   1966 		return (0);
   1967 	case ONLYB:
   1968 		return (1);
   1969 	case BOTH:
   1970 		/*
   1971 		 * tie - favor one with highest recent cpu utilization
   1972 		 */
   1973 		if (p2->p_estcpu > p1->p_estcpu)
   1974 			return (1);
   1975 		if (p1->p_estcpu > p2->p_estcpu)
   1976 			return (0);
   1977 		return (p2->p_pid > p1->p_pid);	/* tie - return highest pid */
   1978 	}
   1979 	/*
   1980  	 * weed out zombies
   1981 	 */
   1982 	switch (TESTAB(p1->p_stat == SZOMB, p2->p_stat == SZOMB)) {
   1983 	case ONLYA:
   1984 		return (1);
   1985 	case ONLYB:
   1986 		return (0);
   1987 	case BOTH:
   1988 		return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
   1989 	}
   1990 	/*
   1991 	 * pick the one with the smallest sleep time
   1992 	 */
   1993 	if (p2->p_slptime > p1->p_slptime)
   1994 		return (0);
   1995 	if (p1->p_slptime > p2->p_slptime)
   1996 		return (1);
   1997 	/*
   1998 	 * favor one sleeping in a non-interruptible sleep
   1999 	 */
   2000 	if (p1->p_flag & P_SINTR && (p2->p_flag & P_SINTR) == 0)
   2001 		return (1);
   2002 	if (p2->p_flag & P_SINTR && (p1->p_flag & P_SINTR) == 0)
   2003 		return (0);
   2004 	return (p2->p_pid > p1->p_pid);		/* tie - return highest pid */
   2005 }
   2006 
   2007 /*
   2008  * Output char to tty; console putchar style.
   2009  */
   2010 int
   2011 tputchar(c, tp)
   2012 	int c;
   2013 	struct tty *tp;
   2014 {
   2015 	register int s;
   2016 
   2017 	s = spltty();
   2018 	if (ISSET(tp->t_state,
   2019 	    TS_CARR_ON | TS_ISOPEN) != (TS_CARR_ON | TS_ISOPEN)) {
   2020 		splx(s);
   2021 		return (-1);
   2022 	}
   2023 	if (c == '\n')
   2024 		(void)ttyoutput('\r', tp);
   2025 	(void)ttyoutput(c, tp);
   2026 	ttstart(tp);
   2027 	splx(s);
   2028 	return (0);
   2029 }
   2030 
   2031 /*
   2032  * Sleep on chan, returning ERESTART if tty changed while we napped and
   2033  * returning any errors (e.g. EINTR/ETIMEDOUT) reported by tsleep.  If
   2034  * the tty is revoked, restarting a pending call will redo validation done
   2035  * at the start of the call.
   2036  */
   2037 int
   2038 ttysleep(tp, chan, pri, wmesg, timo)
   2039 	struct tty *tp;
   2040 	void *chan;
   2041 	int pri, timo;
   2042 	char *wmesg;
   2043 {
   2044 	int error;
   2045 	short gen;
   2046 
   2047 	gen = tp->t_gen;
   2048 	if ((error = tsleep(chan, pri, wmesg, timo)) != 0)
   2049 		return (error);
   2050 	return (tp->t_gen == gen ? 0 : ERESTART);
   2051 }
   2052 
   2053 /*
   2054  * Initialise the global tty list.
   2055  */
   2056 void
   2057 tty_init()
   2058 {
   2059 
   2060 	TAILQ_INIT(&ttylist);
   2061 	tty_count = 0;
   2062 }
   2063 
   2064 /*
   2065  * Attach a tty to the tty list.
   2066  *
   2067  * This should be called ONLY once per real tty (including pty's).
   2068  * eg, on the sparc, the keyboard and mouse have struct tty's that are
   2069  * distinctly NOT usable as tty's, and thus should not be attached to
   2070  * the ttylist.  This is why this call is not done from ttymalloc().
   2071  *
   2072  * Device drivers should attach tty's at a similar time that they are
   2073  * ttymalloc()'ed, or, for the case of statically allocated struct tty's
   2074  * either in the attach or (first) open routine.
   2075  */
   2076 void
   2077 tty_attach(tp)
   2078 	struct tty *tp;
   2079 {
   2080 
   2081 	TAILQ_INSERT_TAIL(&ttylist, tp, tty_link);
   2082 	++tty_count;
   2083 }
   2084 
   2085 /*
   2086  * Remove a tty from the tty list.
   2087  */
   2088 void
   2089 tty_detach(tp)
   2090 	struct tty *tp;
   2091 {
   2092 
   2093 	--tty_count;
   2094 #ifdef DIAGNOSTIC
   2095 	if (tty_count < 0)
   2096 		panic("tty_detach: tty_count < 0");
   2097 #endif
   2098 	TAILQ_REMOVE(&ttylist, tp, tty_link);
   2099 }
   2100 
   2101 /*
   2102  * Allocate a tty structure and its associated buffers.
   2103  */
   2104 struct tty *
   2105 ttymalloc()
   2106 {
   2107 	struct tty *tp;
   2108 
   2109 	MALLOC(tp, struct tty *, sizeof(struct tty), M_TTYS, M_WAITOK);
   2110 	bzero(tp, sizeof *tp);
   2111 	/* XXX: default to 4096 chars for now */
   2112 	clalloc(&tp->t_rawq, 4096, 1);
   2113 	clalloc(&tp->t_canq, 4096, 1);
   2114 	/* output queue doesn't need quoting */
   2115 	clalloc(&tp->t_outq, 4096, 0);
   2116 	return(tp);
   2117 }
   2118 
   2119 /*
   2120  * Free a tty structure and its buffers.
   2121  *
   2122  * Be sure to call tty_detach() for any tty that has been
   2123  * tty_attach()ed.
   2124  */
   2125 void
   2126 ttyfree(tp)
   2127 	struct tty *tp;
   2128 {
   2129 
   2130 	clfree(&tp->t_rawq);
   2131 	clfree(&tp->t_canq);
   2132 	clfree(&tp->t_outq);
   2133 	FREE(tp, M_TTYS);
   2134 }
   2135