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