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