Home | History | Annotate | Line # | Download | only in kern
tty.c revision 1.119.4.1
      1 /*	$NetBSD: tty.c,v 1.119.4.1 2002/04/26 17:56:24 he 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 const char	ttyin[] = "ttyin";
     78 const 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 struct pool tty_pool;
    172 
    173 int
    174 ttyopen(tp, dialout, nonblock)
    175 	struct tty *tp;
    176 	int dialout, nonblock;
    177 {
    178 	int s;
    179 	int error;
    180 
    181 	s = spltty();
    182 
    183 	if (dialout) {
    184 		/*
    185 		 * If the device is already open for non-dialout, fail.
    186 		 * Otherwise, set TS_DIALOUT to block any pending non-dialout
    187 		 * opens.
    188 		 */
    189 		if (ISSET(tp->t_state, TS_ISOPEN) &&
    190 		    !ISSET(tp->t_state, TS_DIALOUT)) {
    191 			splx(s);
    192 			return (EBUSY);
    193 		}
    194 		SET(tp->t_state, TS_DIALOUT);
    195 	} else {
    196 		if (!nonblock) {
    197 			/*
    198 			 * Wait for carrier.  Also wait for any dialout
    199 			 * processes to close the tty first.
    200 			 */
    201 			while (ISSET(tp->t_state, TS_DIALOUT) ||
    202 			       (!ISSET(tp->t_state, TS_CARR_ON) &&
    203 				!ISSET(tp->t_cflag, CLOCAL | MDMBUF))) {
    204 				tp->t_wopen++;
    205 				error = ttysleep(tp, &tp->t_rawq,
    206 				    TTIPRI | PCATCH, ttopen, 0);
    207 				tp->t_wopen--;
    208 				if (error) {
    209 					splx(s);
    210 					return (error);
    211 				}
    212 			}
    213 		} else {
    214 			/*
    215 			 * Don't allow a non-blocking non-dialout open if the
    216 			 * device is already open for dialout.
    217 			 */
    218 		        if (ISSET(tp->t_state, TS_DIALOUT)) {
    219 				splx(s);
    220 				return (EBUSY);
    221 			}
    222 		}
    223 	}
    224 
    225 	splx(s);
    226 	return (0);
    227 }
    228 
    229 /*
    230  * Initial open of tty, or (re)entry to standard tty line discipline.
    231  */
    232 int
    233 ttylopen(device, tp)
    234 	dev_t device;
    235 	struct tty *tp;
    236 {
    237 	int s;
    238 
    239 	s = spltty();
    240 	tp->t_dev = device;
    241 	if (!ISSET(tp->t_state, TS_ISOPEN)) {
    242 		SET(tp->t_state, TS_ISOPEN);
    243 		memset(&tp->t_winsize, 0, sizeof(tp->t_winsize));
    244 #ifdef COMPAT_OLDTTY
    245 		tp->t_flags = 0;
    246 #endif
    247 	}
    248 	splx(s);
    249 	return (0);
    250 }
    251 
    252 /*
    253  * Handle close() on a tty line: flush and set to initial state,
    254  * bumping generation number so that pending read/write calls
    255  * can detect recycling of the tty.
    256  */
    257 int
    258 ttyclose(tp)
    259 	struct tty *tp;
    260 {
    261 	extern struct tty *constty;	/* Temporary virtual console. */
    262 
    263 	if (constty == tp)
    264 		constty = NULL;
    265 
    266 	ttyflush(tp, FREAD | FWRITE);
    267 
    268 	tp->t_gen++;
    269 	tp->t_pgrp = NULL;
    270 	if (tp->t_session != NULL) {
    271 		SESSRELE(tp->t_session);
    272 		tp->t_session = NULL;
    273 	}
    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 	int c;
    301 	struct tty *tp;
    302 {
    303 	int iflag, lflag;
    304 	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 	int c;
    643 	struct tty *tp;
    644 {
    645 	long oflag;
    646 	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 	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 		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 		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 		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 		SESSHOLD(p->p_session);
    986 		tp->t_session = p->p_session;
    987 		tp->t_pgrp = p->p_pgrp;
    988 		p->p_session->s_ttyp = tp;
    989 		p->p_flag |= P_CONTROLT;
    990 		break;
    991 	case TIOCSPGRP: {		/* set pgrp of tty */
    992 		struct pgrp *pgrp = pgfind(*(int *)data);
    993 
    994 		if (!isctty(p, tp))
    995 			return (ENOTTY);
    996 		else if (pgrp == NULL)
    997 			return (EINVAL);
    998 		else if (pgrp->pg_session != p->p_session)
    999 			return (EPERM);
   1000 		tp->t_pgrp = pgrp;
   1001 		break;
   1002 	}
   1003 	case TIOCSTAT:			/* get load avg stats */
   1004 		ttyinfo(tp);
   1005 		break;
   1006 	case TIOCSWINSZ:		/* set window size */
   1007 		if (memcmp((caddr_t)&tp->t_winsize, data,
   1008 		    sizeof(struct winsize))) {
   1009 			tp->t_winsize = *(struct winsize *)data;
   1010 			pgsignal(tp->t_pgrp, SIGWINCH, 1);
   1011 		}
   1012 		break;
   1013 	default:
   1014 #ifdef COMPAT_OLDTTY
   1015 		return (ttcompat(tp, cmd, data, flag, p));
   1016 #else
   1017 		return (-1);
   1018 #endif
   1019 	}
   1020 	return (0);
   1021 }
   1022 
   1023 int
   1024 ttpoll(dev, events, p)
   1025 	dev_t dev;
   1026 	int events;
   1027 	struct proc *p;
   1028 {
   1029 	struct tty *tp = (*cdevsw[major(dev)].d_tty)(dev);
   1030 	int revents = 0;
   1031 	int s = spltty();
   1032 
   1033 	if (events & (POLLIN | POLLRDNORM))
   1034 		if (ttnread(tp) > 0)
   1035 			revents |= events & (POLLIN | POLLRDNORM);
   1036 
   1037 	if (events & (POLLOUT | POLLWRNORM))
   1038 		if (tp->t_outq.c_cc <= tp->t_lowat)
   1039 			revents |= events & (POLLOUT | POLLWRNORM);
   1040 
   1041 	if (events & POLLHUP)
   1042 		if (!CONNECTED(tp))
   1043 			revents |= POLLHUP;
   1044 
   1045 	if (revents == 0) {
   1046 		if (events & (POLLIN | POLLHUP | POLLRDNORM))
   1047 			selrecord(p, &tp->t_rsel);
   1048 
   1049 		if (events & (POLLOUT | POLLWRNORM))
   1050 			selrecord(p, &tp->t_wsel);
   1051 	}
   1052 
   1053 	splx(s);
   1054 	return (revents);
   1055 }
   1056 
   1057 static int
   1058 ttnread(tp)
   1059 	struct tty *tp;
   1060 {
   1061 	int nread;
   1062 
   1063 	if (ISSET(tp->t_lflag, PENDIN))
   1064 		ttypend(tp);
   1065 	nread = tp->t_canq.c_cc;
   1066 	if (!ISSET(tp->t_lflag, ICANON)) {
   1067 		nread += tp->t_rawq.c_cc;
   1068 		if (nread < tp->t_cc[VMIN] && !tp->t_cc[VTIME])
   1069 			nread = 0;
   1070 	}
   1071 	return (nread);
   1072 }
   1073 
   1074 /*
   1075  * Wait for output to drain.
   1076  */
   1077 int
   1078 ttywait(tp)
   1079 	struct tty *tp;
   1080 {
   1081 	int error, s;
   1082 
   1083 	error = 0;
   1084 	s = spltty();
   1085 	while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
   1086 	    CONNECTED(tp) && tp->t_oproc) {
   1087 		(*tp->t_oproc)(tp);
   1088 		SET(tp->t_state, TS_ASLEEP);
   1089 		error = ttysleep(tp, &tp->t_outq, TTOPRI | PCATCH, ttyout, 0);
   1090 		if (error)
   1091 			break;
   1092 	}
   1093 	splx(s);
   1094 	return (error);
   1095 }
   1096 
   1097 /*
   1098  * Flush if successfully wait.
   1099  */
   1100 int
   1101 ttywflush(tp)
   1102 	struct tty *tp;
   1103 {
   1104 	int error;
   1105 
   1106 	if ((error = ttywait(tp)) == 0)
   1107 		ttyflush(tp, FREAD);
   1108 	return (error);
   1109 }
   1110 
   1111 /*
   1112  * Flush tty read and/or write queues, notifying anyone waiting.
   1113  */
   1114 void
   1115 ttyflush(tp, rw)
   1116 	struct tty *tp;
   1117 	int rw;
   1118 {
   1119 	int s;
   1120 
   1121 	s = spltty();
   1122 	if (rw & FREAD) {
   1123 		FLUSHQ(&tp->t_canq);
   1124 		FLUSHQ(&tp->t_rawq);
   1125 		tp->t_rocount = 0;
   1126 		tp->t_rocol = 0;
   1127 		CLR(tp->t_state, TS_LOCAL);
   1128 		ttwakeup(tp);
   1129 	}
   1130 	if (rw & FWRITE) {
   1131 		CLR(tp->t_state, TS_TTSTOP);
   1132 		(*cdevsw[major(tp->t_dev)].d_stop)(tp, rw);
   1133 		FLUSHQ(&tp->t_outq);
   1134 		wakeup((caddr_t)&tp->t_outq);
   1135 		selwakeup(&tp->t_wsel);
   1136 	}
   1137 	splx(s);
   1138 }
   1139 
   1140 /*
   1141  * Copy in the default termios characters.
   1142  */
   1143 void
   1144 ttychars(tp)
   1145 	struct tty *tp;
   1146 {
   1147 
   1148 	memcpy(tp->t_cc, ttydefchars, sizeof(ttydefchars));
   1149 }
   1150 
   1151 /*
   1152  * Send stop character on input overflow.
   1153  */
   1154 static void
   1155 ttyblock(tp)
   1156 	struct tty *tp;
   1157 {
   1158 	int total;
   1159 
   1160 	total = tp->t_rawq.c_cc + tp->t_canq.c_cc;
   1161 	if (tp->t_rawq.c_cc > TTYHOG) {
   1162 		ttyflush(tp, FREAD | FWRITE);
   1163 		CLR(tp->t_state, TS_TBLOCK);
   1164 	}
   1165 	/*
   1166 	 * Block further input iff: current input > threshold
   1167 	 * AND input is available to user program.
   1168 	 */
   1169 	if (total >= TTYHOG / 2 &&
   1170 	    !ISSET(tp->t_state, TS_TBLOCK) &&
   1171 	    (!ISSET(tp->t_lflag, ICANON) || tp->t_canq.c_cc > 0)) {
   1172 		if (ISSET(tp->t_iflag, IXOFF) &&
   1173 		    tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
   1174 		    putc(tp->t_cc[VSTOP], &tp->t_outq) == 0) {
   1175 			SET(tp->t_state, TS_TBLOCK);
   1176 			ttstart(tp);
   1177 		}
   1178 		/* Try to block remote output via hardware flow control. */
   1179 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
   1180 		    (*tp->t_hwiflow)(tp, 1) != 0)
   1181 			SET(tp->t_state, TS_TBLOCK);
   1182 	}
   1183 }
   1184 
   1185 void
   1186 ttrstrt(tp_arg)
   1187 	void *tp_arg;
   1188 {
   1189 	struct tty *tp;
   1190 	int s;
   1191 
   1192 #ifdef DIAGNOSTIC
   1193 	if (tp_arg == NULL)
   1194 		panic("ttrstrt");
   1195 #endif
   1196 	tp = tp_arg;
   1197 	s = spltty();
   1198 
   1199 	CLR(tp->t_state, TS_TIMEOUT);
   1200 	ttstart(tp);
   1201 
   1202 	splx(s);
   1203 }
   1204 
   1205 int
   1206 ttstart(tp)
   1207 	struct tty *tp;
   1208 {
   1209 
   1210 	if (tp->t_oproc != NULL)	/* XXX: Kludge for pty. */
   1211 		(*tp->t_oproc)(tp);
   1212 	return (0);
   1213 }
   1214 
   1215 /*
   1216  * "close" a line discipline
   1217  */
   1218 int
   1219 ttylclose(tp, flag)
   1220 	struct tty *tp;
   1221 	int flag;
   1222 {
   1223 
   1224 	if (flag & FNONBLOCK)
   1225 		ttyflush(tp, FREAD | FWRITE);
   1226 	else
   1227 		ttywflush(tp);
   1228 	return (0);
   1229 }
   1230 
   1231 /*
   1232  * Handle modem control transition on a tty.
   1233  * Flag indicates new state of carrier.
   1234  * Returns 0 if the line should be turned off, otherwise 1.
   1235  */
   1236 int
   1237 ttymodem(tp, flag)
   1238 	struct tty *tp;
   1239 	int flag;
   1240 {
   1241 
   1242 	if (flag == 0) {
   1243 		if (ISSET(tp->t_state, TS_CARR_ON)) {
   1244 			/*
   1245 			 * Lost carrier.
   1246 			 */
   1247 			CLR(tp->t_state, TS_CARR_ON);
   1248 			if (ISSET(tp->t_state, TS_ISOPEN) && !CONNECTED(tp)) {
   1249 				if (tp->t_session && tp->t_session->s_leader)
   1250 					psignal(tp->t_session->s_leader, SIGHUP);
   1251 				ttyflush(tp, FREAD | FWRITE);
   1252 				return (0);
   1253 			}
   1254 		}
   1255 	} else {
   1256 		if (!ISSET(tp->t_state, TS_CARR_ON)) {
   1257 			/*
   1258 			 * Carrier now on.
   1259 			 */
   1260 			SET(tp->t_state, TS_CARR_ON);
   1261 			ttwakeup(tp);
   1262 		}
   1263 	}
   1264 	return (1);
   1265 }
   1266 
   1267 /*
   1268  * Default modem control routine (for other line disciplines).
   1269  * Return argument flag, to turn off device on carrier drop.
   1270  */
   1271 int
   1272 nullmodem(tp, flag)
   1273 	struct tty *tp;
   1274 	int flag;
   1275 {
   1276 
   1277 	if (flag)
   1278 		SET(tp->t_state, TS_CARR_ON);
   1279 	else {
   1280 		CLR(tp->t_state, TS_CARR_ON);
   1281 		if (!CONNECTED(tp)) {
   1282 			if (tp->t_session && tp->t_session->s_leader)
   1283 				psignal(tp->t_session->s_leader, SIGHUP);
   1284 			return (0);
   1285 		}
   1286 	}
   1287 	return (1);
   1288 }
   1289 
   1290 /*
   1291  * Reinput pending characters after state switch
   1292  * call at spltty().
   1293  */
   1294 void
   1295 ttypend(tp)
   1296 	struct tty *tp;
   1297 {
   1298 	struct clist tq;
   1299 	int c;
   1300 
   1301 	CLR(tp->t_lflag, PENDIN);
   1302 	SET(tp->t_state, TS_TYPEN);
   1303 	tq = tp->t_rawq;
   1304 	tp->t_rawq.c_cc = 0;
   1305 	tp->t_rawq.c_cf = tp->t_rawq.c_cl = 0;
   1306 	while ((c = getc(&tq)) >= 0)
   1307 		ttyinput(c, tp);
   1308 	CLR(tp->t_state, TS_TYPEN);
   1309 }
   1310 
   1311 /*
   1312  * Process a read call on a tty device.
   1313  */
   1314 int
   1315 ttread(tp, uio, flag)
   1316 	struct tty *tp;
   1317 	struct uio *uio;
   1318 	int flag;
   1319 {
   1320 	struct clist *qp;
   1321 	int c;
   1322 	long lflag;
   1323 	u_char *cc = tp->t_cc;
   1324 	struct proc *p = curproc;
   1325 	int s, first, error = 0;
   1326 	struct timeval stime;
   1327 	int has_stime = 0, last_cc = 0;
   1328 	long slp = 0;
   1329 
   1330 loop:	lflag = tp->t_lflag;
   1331 	s = spltty();
   1332 	/*
   1333 	 * take pending input first
   1334 	 */
   1335 	if (ISSET(lflag, PENDIN))
   1336 		ttypend(tp);
   1337 	splx(s);
   1338 
   1339 	/*
   1340 	 * Hang process if it's in the background.
   1341 	 */
   1342 	if (isbackground(p, tp)) {
   1343 		if (sigismember(&p->p_sigignore, SIGTTIN) ||
   1344 		    sigismember(&p->p_sigmask, SIGTTIN) ||
   1345 		    p->p_flag & P_PPWAIT || p->p_pgrp->pg_jobc == 0)
   1346 			return (EIO);
   1347 		pgsignal(p->p_pgrp, SIGTTIN, 1);
   1348 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, ttybg, 0);
   1349 		if (error)
   1350 			return (error);
   1351 		goto loop;
   1352 	}
   1353 
   1354 	s = spltty();
   1355 	if (!ISSET(lflag, ICANON)) {
   1356 		int m = cc[VMIN];
   1357 		long t = cc[VTIME];
   1358 
   1359 		qp = &tp->t_rawq;
   1360 		/*
   1361 		 * Check each of the four combinations.
   1362 		 * (m > 0 && t == 0) is the normal read case.
   1363 		 * It should be fairly efficient, so we check that and its
   1364 		 * companion case (m == 0 && t == 0) first.
   1365 		 * For the other two cases, we compute the target sleep time
   1366 		 * into slp.
   1367 		 */
   1368 		if (t == 0) {
   1369 			if (qp->c_cc < m)
   1370 				goto sleep;
   1371 			goto read;
   1372 		}
   1373 		t *= 100000;		/* time in us */
   1374 #define diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 1000000 + \
   1375 			 ((t1).tv_usec - (t2).tv_usec))
   1376 		if (m > 0) {
   1377 			if (qp->c_cc <= 0)
   1378 				goto sleep;
   1379 			if (qp->c_cc >= m)
   1380 				goto read;
   1381 			if (!has_stime) {
   1382 				/* first character, start timer */
   1383 				has_stime = 1;
   1384 				stime = time;
   1385 				slp = t;
   1386 			} else if (qp->c_cc > last_cc) {
   1387 				/* got a character, restart timer */
   1388 				stime = time;
   1389 				slp = t;
   1390 			} else {
   1391 				/* nothing, check expiration */
   1392 				slp = t - diff(time, stime);
   1393 			}
   1394 		} else {	/* m == 0 */
   1395 			if (qp->c_cc > 0)
   1396 				goto read;
   1397 			if (!has_stime) {
   1398 				has_stime = 1;
   1399 				stime = time;
   1400 				slp = t;
   1401 			} else
   1402 				slp = t - diff(time, stime);
   1403 		}
   1404 		last_cc = qp->c_cc;
   1405 #undef diff
   1406 		if (slp > 0) {
   1407 			/*
   1408 			 * Rounding down may make us wake up just short
   1409 			 * of the target, so we round up.
   1410 			 * The formula is ceiling(slp * hz/1000000).
   1411 			 * 32-bit arithmetic is enough for hz < 169.
   1412 			 *
   1413 			 * Also, use plain wakeup() not ttwakeup().
   1414 			 */
   1415 			slp = (long) (((u_long)slp * hz) + 999999) / 1000000;
   1416 			goto sleep;
   1417 		}
   1418 	} else if ((qp = &tp->t_canq)->c_cc <= 0) {
   1419 		int carrier;
   1420 
   1421 sleep:
   1422 		/*
   1423 		 * If there is no input, sleep on rawq
   1424 		 * awaiting hardware receipt and notification.
   1425 		 * If we have data, we don't need to check for carrier.
   1426 		 */
   1427 		carrier = CONNECTED(tp);
   1428 		if (!carrier && ISSET(tp->t_state, TS_ISOPEN)) {
   1429 			splx(s);
   1430 			return (0);	/* EOF */
   1431 		}
   1432 		if (flag & IO_NDELAY) {
   1433 			splx(s);
   1434 			return (EWOULDBLOCK);
   1435 		}
   1436 		error = ttysleep(tp, &tp->t_rawq, TTIPRI | PCATCH,
   1437 		    carrier ? ttyin : ttopen, slp);
   1438 		splx(s);
   1439 		/* VMIN == 0: any quantity read satisfies */
   1440 		if (cc[VMIN] == 0 && error == EWOULDBLOCK)
   1441 			return (0);
   1442 		if (error && error != EWOULDBLOCK)
   1443 			return (error);
   1444 		goto loop;
   1445 	}
   1446 read:
   1447 	splx(s);
   1448 
   1449 	/*
   1450 	 * Input present, check for input mapping and processing.
   1451 	 */
   1452 	first = 1;
   1453 	while ((c = getc(qp)) >= 0) {
   1454 		/*
   1455 		 * delayed suspend (^Y)
   1456 		 */
   1457 		if (CCEQ(cc[VDSUSP], c) &&
   1458 		    ISSET(lflag, IEXTEN|ISIG) == (IEXTEN|ISIG)) {
   1459 			pgsignal(tp->t_pgrp, SIGTSTP, 1);
   1460 			if (first) {
   1461 				error = ttysleep(tp, &lbolt,
   1462 						 TTIPRI | PCATCH, ttybg, 0);
   1463 				if (error)
   1464 					break;
   1465 				goto loop;
   1466 			}
   1467 			break;
   1468 		}
   1469 		/*
   1470 		 * Interpret EOF only in canonical mode.
   1471 		 */
   1472 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
   1473 			break;
   1474 		/*
   1475 		 * Give user character.
   1476 		 */
   1477  		error = ureadc(c, uio);
   1478 		if (error)
   1479 			break;
   1480  		if (uio->uio_resid == 0)
   1481 			break;
   1482 		/*
   1483 		 * In canonical mode check for a "break character"
   1484 		 * marking the end of a "line of input".
   1485 		 */
   1486 		if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
   1487 			break;
   1488 		first = 0;
   1489 	}
   1490 	/*
   1491 	 * Look to unblock output now that (presumably)
   1492 	 * the input queue has gone down.
   1493 	 */
   1494 	s = spltty();
   1495 	if (ISSET(tp->t_state, TS_TBLOCK) && tp->t_rawq.c_cc < TTYHOG/5) {
   1496 		if (ISSET(tp->t_iflag, IXOFF) &&
   1497 		    cc[VSTART] != _POSIX_VDISABLE &&
   1498 		    putc(cc[VSTART], &tp->t_outq) == 0) {
   1499 			CLR(tp->t_state, TS_TBLOCK);
   1500 			ttstart(tp);
   1501 		}
   1502 		/* Try to unblock remote output via hardware flow control. */
   1503 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
   1504 		    (*tp->t_hwiflow)(tp, 0) != 0)
   1505 			CLR(tp->t_state, TS_TBLOCK);
   1506 	}
   1507 	splx(s);
   1508 	return (error);
   1509 }
   1510 
   1511 /*
   1512  * Check the output queue on tp for space for a kernel message (from uprintf
   1513  * or tprintf).  Allow some space over the normal hiwater mark so we don't
   1514  * lose messages due to normal flow control, but don't let the tty run amok.
   1515  * Sleeps here are not interruptible, but we return prematurely if new signals
   1516  * arrive.
   1517  */
   1518 int
   1519 ttycheckoutq(tp, wait)
   1520 	struct tty *tp;
   1521 	int wait;
   1522 {
   1523 	int hiwat, s;
   1524 	int error;
   1525 
   1526 	hiwat = tp->t_hiwat;
   1527 	s = spltty();
   1528 	if (tp->t_outq.c_cc > hiwat + 200)
   1529 		while (tp->t_outq.c_cc > hiwat) {
   1530 			ttstart(tp);
   1531 			if (wait == 0) {
   1532 				splx(s);
   1533 				return (0);
   1534 			}
   1535 			callout_reset(&tp->t_outq_ch, hz,
   1536 			    (void (*)__P((void *)))wakeup, &tp->t_outq);
   1537 			SET(tp->t_state, TS_ASLEEP);
   1538 			error = tsleep(&tp->t_outq, (PZERO - 1) | PCATCH,
   1539 			    "ttckoutq", 0);
   1540 			if (error == EINTR)
   1541 				wait = 0;
   1542 		}
   1543 	splx(s);
   1544 	return (1);
   1545 }
   1546 
   1547 /*
   1548  * Process a write call on a tty device.
   1549  */
   1550 int
   1551 ttwrite(tp, uio, flag)
   1552 	struct tty *tp;
   1553 	struct uio *uio;
   1554 	int flag;
   1555 {
   1556 	u_char *cp = NULL;
   1557 	int cc, ce;
   1558 	struct proc *p;
   1559 	int i, hiwat, cnt, error, s;
   1560 	u_char obuf[OBUFSIZ];
   1561 
   1562 	hiwat = tp->t_hiwat;
   1563 	cnt = uio->uio_resid;
   1564 	error = 0;
   1565 	cc = 0;
   1566 loop:
   1567 	s = spltty();
   1568 	if (!CONNECTED(tp)) {
   1569 		if (ISSET(tp->t_state, TS_ISOPEN)) {
   1570 			splx(s);
   1571 			return (EIO);
   1572 		} else if (flag & IO_NDELAY) {
   1573 			splx(s);
   1574 			error = EWOULDBLOCK;
   1575 			goto out;
   1576 		} else {
   1577 			/* Sleep awaiting carrier. */
   1578 			error = ttysleep(tp,
   1579 			    &tp->t_rawq, TTIPRI | PCATCH, ttopen, 0);
   1580 			splx(s);
   1581 			if (error)
   1582 				goto out;
   1583 			goto loop;
   1584 		}
   1585 	}
   1586 	splx(s);
   1587 	/*
   1588 	 * Hang the process if it's in the background.
   1589 	 */
   1590 	p = curproc;
   1591 	if (isbackground(p, tp) &&
   1592 	    ISSET(tp->t_lflag, TOSTOP) && (p->p_flag & P_PPWAIT) == 0 &&
   1593 	    !sigismember(&p->p_sigignore, SIGTTOU) &&
   1594 	    !sigismember(&p->p_sigmask, SIGTTOU)) {
   1595 		if (p->p_pgrp->pg_jobc == 0) {
   1596 			error = EIO;
   1597 			goto out;
   1598 		}
   1599 		pgsignal(p->p_pgrp, SIGTTOU, 1);
   1600 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, ttybg, 0);
   1601 		if (error)
   1602 			goto out;
   1603 		goto loop;
   1604 	}
   1605 	/*
   1606 	 * Process the user's data in at most OBUFSIZ chunks.  Perform any
   1607 	 * output translation.  Keep track of high water mark, sleep on
   1608 	 * overflow awaiting device aid in acquiring new space.
   1609 	 */
   1610 	while (uio->uio_resid > 0 || cc > 0) {
   1611 		if (ISSET(tp->t_lflag, FLUSHO)) {
   1612 			uio->uio_resid = 0;
   1613 			return (0);
   1614 		}
   1615 		if (tp->t_outq.c_cc > hiwat)
   1616 			goto ovhiwat;
   1617 		/*
   1618 		 * Grab a hunk of data from the user, unless we have some
   1619 		 * leftover from last time.
   1620 		 */
   1621 		if (cc == 0) {
   1622 			cc = min(uio->uio_resid, OBUFSIZ);
   1623 			cp = obuf;
   1624 			error = uiomove(cp, cc, uio);
   1625 			if (error) {
   1626 				cc = 0;
   1627 				break;
   1628 			}
   1629 		}
   1630 		/*
   1631 		 * If nothing fancy need be done, grab those characters we
   1632 		 * can handle without any of ttyoutput's processing and
   1633 		 * just transfer them to the output q.  For those chars
   1634 		 * which require special processing (as indicated by the
   1635 		 * bits in char_type), call ttyoutput.  After processing
   1636 		 * a hunk of data, look for FLUSHO so ^O's will take effect
   1637 		 * immediately.
   1638 		 */
   1639 		while (cc > 0) {
   1640 			if (!ISSET(tp->t_oflag, OPOST))
   1641 				ce = cc;
   1642 			else {
   1643 				ce = cc - scanc((u_int)cc, cp, char_type,
   1644 				    CCLASSMASK);
   1645 				/*
   1646 				 * If ce is zero, then we're processing
   1647 				 * a special character through ttyoutput.
   1648 				 */
   1649 				if (ce == 0) {
   1650 					tp->t_rocount = 0;
   1651 					if (ttyoutput(*cp, tp) >= 0) {
   1652 						/* out of space */
   1653 						goto overfull;
   1654 					}
   1655 					cp++;
   1656 					cc--;
   1657 					if (ISSET(tp->t_lflag, FLUSHO) ||
   1658 					    tp->t_outq.c_cc > hiwat)
   1659 						goto ovhiwat;
   1660 					continue;
   1661 				}
   1662 			}
   1663 			/*
   1664 			 * A bunch of normal characters have been found.
   1665 			 * Transfer them en masse to the output queue and
   1666 			 * continue processing at the top of the loop.
   1667 			 * If there are any further characters in this
   1668 			 * <= OBUFSIZ chunk, the first should be a character
   1669 			 * requiring special handling by ttyoutput.
   1670 			 */
   1671 			tp->t_rocount = 0;
   1672 			i = b_to_q(cp, ce, &tp->t_outq);
   1673 			ce -= i;
   1674 			tp->t_column += ce;
   1675 			cp += ce, cc -= ce, tk_nout += ce;
   1676 			tp->t_outcc += ce;
   1677 			if (i > 0) {
   1678 				/* out of space */
   1679 				goto overfull;
   1680 			}
   1681 			if (ISSET(tp->t_lflag, FLUSHO) ||
   1682 			    tp->t_outq.c_cc > hiwat)
   1683 				break;
   1684 		}
   1685 		ttstart(tp);
   1686 	}
   1687 out:
   1688 	/*
   1689 	 * If cc is nonzero, we leave the uio structure inconsistent, as the
   1690 	 * offset and iov pointers have moved forward, but it doesn't matter
   1691 	 * (the call will either return short or restart with a new uio).
   1692 	 */
   1693 	uio->uio_resid += cc;
   1694 	return (error);
   1695 
   1696 overfull:
   1697 	/*
   1698 	 * Since we are using ring buffers, if we can't insert any more into
   1699 	 * the output queue, we can assume the ring is full and that someone
   1700 	 * forgot to set the high water mark correctly.  We set it and then
   1701 	 * proceed as normal.
   1702 	 */
   1703 	hiwat = tp->t_outq.c_cc - 1;
   1704 
   1705 ovhiwat:
   1706 	ttstart(tp);
   1707 	s = spltty();
   1708 	/*
   1709 	 * This can only occur if FLUSHO is set in t_lflag,
   1710 	 * or if ttstart/oproc is synchronous (or very fast).
   1711 	 */
   1712 	if (tp->t_outq.c_cc <= hiwat) {
   1713 		splx(s);
   1714 		goto loop;
   1715 	}
   1716 	if (flag & IO_NDELAY) {
   1717 		splx(s);
   1718 		uio->uio_resid += cc;
   1719 		return (uio->uio_resid == cnt ? EWOULDBLOCK : 0);
   1720 	}
   1721 	SET(tp->t_state, TS_ASLEEP);
   1722 	error = ttysleep(tp, &tp->t_outq, TTOPRI | PCATCH, ttyout, 0);
   1723 	splx(s);
   1724 	if (error)
   1725 		goto out;
   1726 	goto loop;
   1727 }
   1728 
   1729 /*
   1730  * Rubout one character from the rawq of tp
   1731  * as cleanly as possible.
   1732  */
   1733 void
   1734 ttyrub(c, tp)
   1735 	int c;
   1736 	struct tty *tp;
   1737 {
   1738 	u_char *cp;
   1739 	int savecol;
   1740 	int tabc, s;
   1741 
   1742 	if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
   1743 		return;
   1744 	CLR(tp->t_lflag, FLUSHO);
   1745 	if (ISSET(tp->t_lflag, ECHOE)) {
   1746 		if (tp->t_rocount == 0) {
   1747 			/*
   1748 			 * Screwed by ttwrite; retype
   1749 			 */
   1750 			ttyretype(tp);
   1751 			return;
   1752 		}
   1753 		if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
   1754 			ttyrubo(tp, 2);
   1755 		else {
   1756 			CLR(c, ~TTY_CHARMASK);
   1757 			switch (CCLASS(c)) {
   1758 			case ORDINARY:
   1759 				ttyrubo(tp, 1);
   1760 				break;
   1761 			case BACKSPACE:
   1762 			case CONTROL:
   1763 			case NEWLINE:
   1764 			case RETURN:
   1765 			case VTAB:
   1766 				if (ISSET(tp->t_lflag, ECHOCTL))
   1767 					ttyrubo(tp, 2);
   1768 				break;
   1769 			case TAB:
   1770 				if (tp->t_rocount < tp->t_rawq.c_cc) {
   1771 					ttyretype(tp);
   1772 					return;
   1773 				}
   1774 				s = spltty();
   1775 				savecol = tp->t_column;
   1776 				SET(tp->t_state, TS_CNTTB);
   1777 				SET(tp->t_lflag, FLUSHO);
   1778 				tp->t_column = tp->t_rocol;
   1779 				for (cp = firstc(&tp->t_rawq, &tabc); cp;
   1780 				    cp = nextc(&tp->t_rawq, cp, &tabc))
   1781 					ttyecho(tabc, tp);
   1782 				CLR(tp->t_lflag, FLUSHO);
   1783 				CLR(tp->t_state, TS_CNTTB);
   1784 				splx(s);
   1785 
   1786 				/* savecol will now be length of the tab. */
   1787 				savecol -= tp->t_column;
   1788 				tp->t_column += savecol;
   1789 				if (savecol > 8)
   1790 					savecol = 8;	/* overflow screw */
   1791 				while (--savecol >= 0)
   1792 					(void)ttyoutput('\b', tp);
   1793 				break;
   1794 			default:			/* XXX */
   1795 #define	PANICSTR	"ttyrub: would panic c = %d, val = %d\n"
   1796 				(void)printf(PANICSTR, c, CCLASS(c));
   1797 #ifdef notdef
   1798 				panic(PANICSTR, c, CCLASS(c));
   1799 #endif
   1800 			}
   1801 		}
   1802 	} else if (ISSET(tp->t_lflag, ECHOPRT)) {
   1803 		if (!ISSET(tp->t_state, TS_ERASE)) {
   1804 			SET(tp->t_state, TS_ERASE);
   1805 			(void)ttyoutput('\\', tp);
   1806 		}
   1807 		ttyecho(c, tp);
   1808 	} else
   1809 		ttyecho(tp->t_cc[VERASE], tp);
   1810 	--tp->t_rocount;
   1811 }
   1812 
   1813 /*
   1814  * Back over cnt characters, erasing them.
   1815  */
   1816 static void
   1817 ttyrubo(tp, cnt)
   1818 	struct tty *tp;
   1819 	int cnt;
   1820 {
   1821 
   1822 	while (cnt-- > 0) {
   1823 		(void)ttyoutput('\b', tp);
   1824 		(void)ttyoutput(' ', tp);
   1825 		(void)ttyoutput('\b', tp);
   1826 	}
   1827 }
   1828 
   1829 /*
   1830  * ttyretype --
   1831  *	Reprint the rawq line.  Note, it is assumed that c_cc has already
   1832  *	been checked.
   1833  */
   1834 void
   1835 ttyretype(tp)
   1836 	struct tty *tp;
   1837 {
   1838 	u_char *cp;
   1839 	int s, c;
   1840 
   1841 	/* Echo the reprint character. */
   1842 	if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
   1843 		ttyecho(tp->t_cc[VREPRINT], tp);
   1844 
   1845 	(void)ttyoutput('\n', tp);
   1846 
   1847 	s = spltty();
   1848 	for (cp = firstc(&tp->t_canq, &c); cp; cp = nextc(&tp->t_canq, cp, &c))
   1849 		ttyecho(c, tp);
   1850 	for (cp = firstc(&tp->t_rawq, &c); cp; cp = nextc(&tp->t_rawq, cp, &c))
   1851 		ttyecho(c, tp);
   1852 	CLR(tp->t_state, TS_ERASE);
   1853 	splx(s);
   1854 
   1855 	tp->t_rocount = tp->t_rawq.c_cc;
   1856 	tp->t_rocol = 0;
   1857 }
   1858 
   1859 /*
   1860  * Echo a typed character to the terminal.
   1861  */
   1862 static void
   1863 ttyecho(c, tp)
   1864 	int c;
   1865 	struct tty *tp;
   1866 {
   1867 
   1868 	if (!ISSET(tp->t_state, TS_CNTTB))
   1869 		CLR(tp->t_lflag, FLUSHO);
   1870 	if ((!ISSET(tp->t_lflag, ECHO) &&
   1871 	    (!ISSET(tp->t_lflag, ECHONL) || c != '\n')) ||
   1872 	    ISSET(tp->t_lflag, EXTPROC))
   1873 		return;
   1874 	if (((ISSET(tp->t_lflag, ECHOCTL) &&
   1875 	     (ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n')) ||
   1876 	    ISSET(c, TTY_CHARMASK) == 0177)) {
   1877 		(void)ttyoutput('^', tp);
   1878 		CLR(c, ~TTY_CHARMASK);
   1879 		if (c == 0177)
   1880 			c = '?';
   1881 		else
   1882 			c += 'A' - 1;
   1883 	}
   1884 	(void)ttyoutput(c, tp);
   1885 }
   1886 
   1887 /*
   1888  * Wake up any readers on a tty.
   1889  */
   1890 void
   1891 ttwakeup(tp)
   1892 	struct tty *tp;
   1893 {
   1894 
   1895 	selwakeup(&tp->t_rsel);
   1896 	if (ISSET(tp->t_state, TS_ASYNC))
   1897 		pgsignal(tp->t_pgrp, SIGIO, 1);
   1898 	wakeup((caddr_t)&tp->t_rawq);
   1899 }
   1900 
   1901 /*
   1902  * Look up a code for a specified speed in a conversion table;
   1903  * used by drivers to map software speed values to hardware parameters.
   1904  */
   1905 int
   1906 ttspeedtab(speed, table)
   1907 	int speed;
   1908 	struct speedtab *table;
   1909 {
   1910 
   1911 	for ( ; table->sp_speed != -1; table++)
   1912 		if (table->sp_speed == speed)
   1913 			return (table->sp_code);
   1914 	return (-1);
   1915 }
   1916 
   1917 /*
   1918  * Set tty hi and low water marks.
   1919  *
   1920  * Try to arrange the dynamics so there's about one second
   1921  * from hi to low water.
   1922  */
   1923 void
   1924 ttsetwater(tp)
   1925 	struct tty *tp;
   1926 {
   1927 	int cps, x;
   1928 
   1929 #define CLAMP(x, h, l)	((x) > h ? h : ((x) < l) ? l : (x))
   1930 
   1931 	cps = tp->t_ospeed / 10;
   1932 	tp->t_lowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
   1933 	x += cps;
   1934 	x = CLAMP(x, TTMAXHIWAT, TTMINHIWAT);
   1935 	tp->t_hiwat = roundup(x, CBSIZE);
   1936 #undef	CLAMP
   1937 }
   1938 
   1939 /*
   1940  * Report on state of foreground process group.
   1941  */
   1942 void
   1943 ttyinfo(tp)
   1944 	struct tty *tp;
   1945 {
   1946 	struct proc *p, *pick;
   1947 	struct timeval utime, stime;
   1948 	int tmp;
   1949 
   1950 	if (ttycheckoutq(tp,0) == 0)
   1951 		return;
   1952 
   1953 	/* Print load average. */
   1954 	tmp = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
   1955 	ttyprintf(tp, "load: %d.%02d ", tmp / 100, tmp % 100);
   1956 
   1957 	if (tp->t_session == NULL)
   1958 		ttyprintf(tp, "not a controlling terminal\n");
   1959 	else if (tp->t_pgrp == NULL)
   1960 		ttyprintf(tp, "no foreground process group\n");
   1961 	else if ((p = tp->t_pgrp->pg_members.lh_first) == 0)
   1962 		ttyprintf(tp, "empty foreground process group\n");
   1963 	else {
   1964 		/* Pick interesting process. */
   1965 		for (pick = NULL; p != NULL; p = p->p_pglist.le_next)
   1966 			if (proc_compare(pick, p))
   1967 				pick = p;
   1968 
   1969 		ttyprintf(tp, " cmd: %s %d [%s] ", pick->p_comm, pick->p_pid,
   1970 		    pick->p_stat == SONPROC ? "running" :
   1971 		    pick->p_stat == SRUN ? "runnable" :
   1972 		    pick->p_wmesg ? pick->p_wmesg : "iowait");
   1973 
   1974 		calcru(pick, &utime, &stime, NULL);
   1975 
   1976 		/* Round up and print user time. */
   1977 		utime.tv_usec += 5000;
   1978 		if (utime.tv_usec >= 1000000) {
   1979 			utime.tv_sec += 1;
   1980 			utime.tv_usec -= 1000000;
   1981 		}
   1982 		ttyprintf(tp, "%ld.%02ldu ", (long int)utime.tv_sec,
   1983 		    (long int)utime.tv_usec / 10000);
   1984 
   1985 		/* Round up and print system time. */
   1986 		stime.tv_usec += 5000;
   1987 		if (stime.tv_usec >= 1000000) {
   1988 			stime.tv_sec += 1;
   1989 			stime.tv_usec -= 1000000;
   1990 		}
   1991 		ttyprintf(tp, "%ld.%02lds ", (long int)stime.tv_sec,
   1992 		    (long int)stime.tv_usec / 10000);
   1993 
   1994 #define	pgtok(a)	(((u_long) ((a) * NBPG) / 1024))
   1995 		/* Print percentage cpu. */
   1996 		tmp = (pick->p_pctcpu * 10000 + FSCALE / 2) >> FSHIFT;
   1997 		ttyprintf(tp, "%d%% ", tmp / 100);
   1998 
   1999 		/* Print resident set size. */
   2000 		if (pick->p_stat == SIDL || P_ZOMBIE(pick))
   2001 			tmp = 0;
   2002 		else {
   2003 			struct vmspace *vm = pick->p_vmspace;
   2004 			tmp = pgtok(vm_resident_count(vm));
   2005 		}
   2006 		ttyprintf(tp, "%dk\n", tmp);
   2007 	}
   2008 	tp->t_rocount = 0;	/* so pending input will be retyped if BS */
   2009 }
   2010 
   2011 /*
   2012  * Returns 1 if p2 is "better" than p1
   2013  *
   2014  * The algorithm for picking the "interesting" process is thus:
   2015  *
   2016  *	1) Only foreground processes are eligible - implied.
   2017  *	2) Runnable processes are favored over anything else.  The runner
   2018  *	   with the highest cpu utilization is picked (p_estcpu).  Ties are
   2019  *	   broken by picking the highest pid.
   2020  *	3) The sleeper with the shortest sleep time is next.  With ties,
   2021  *	   we pick out just "short-term" sleepers (P_SINTR == 0).
   2022  *	4) Further ties are broken by picking the highest pid.
   2023  */
   2024 #define ISRUN(p)	(((p)->p_stat == SRUN) || ((p)->p_stat == SIDL) || \
   2025 			 ((p)->p_stat == SONPROC))
   2026 #define TESTAB(a, b)    ((a)<<1 | (b))
   2027 #define ONLYA   2
   2028 #define ONLYB   1
   2029 #define BOTH    3
   2030 
   2031 static int
   2032 proc_compare(p1, p2)
   2033 	struct proc *p1, *p2;
   2034 {
   2035 
   2036 	if (p1 == NULL)
   2037 		return (1);
   2038 	/*
   2039 	 * see if at least one of them is runnable
   2040 	 */
   2041 	switch (TESTAB(ISRUN(p1), ISRUN(p2))) {
   2042 	case ONLYA:
   2043 		return (0);
   2044 	case ONLYB:
   2045 		return (1);
   2046 	case BOTH:
   2047 		/*
   2048 		 * tie - favor one with highest recent cpu utilization
   2049 		 */
   2050 		if (p2->p_estcpu > p1->p_estcpu)
   2051 			return (1);
   2052 		if (p1->p_estcpu > p2->p_estcpu)
   2053 			return (0);
   2054 		return (p2->p_pid > p1->p_pid);	/* tie - return highest pid */
   2055 	}
   2056 	/*
   2057  	 * weed out zombies
   2058 	 */
   2059 	switch (TESTAB(P_ZOMBIE(p1), P_ZOMBIE(p2))) {
   2060 	case ONLYA:
   2061 		return (1);
   2062 	case ONLYB:
   2063 		return (0);
   2064 	case BOTH:
   2065 		return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
   2066 	}
   2067 	/*
   2068 	 * pick the one with the smallest sleep time
   2069 	 */
   2070 	if (p2->p_slptime > p1->p_slptime)
   2071 		return (0);
   2072 	if (p1->p_slptime > p2->p_slptime)
   2073 		return (1);
   2074 	/*
   2075 	 * favor one sleeping in a non-interruptible sleep
   2076 	 */
   2077 	if (p1->p_flag & P_SINTR && (p2->p_flag & P_SINTR) == 0)
   2078 		return (1);
   2079 	if (p2->p_flag & P_SINTR && (p1->p_flag & P_SINTR) == 0)
   2080 		return (0);
   2081 	return (p2->p_pid > p1->p_pid);		/* tie - return highest pid */
   2082 }
   2083 
   2084 /*
   2085  * Output char to tty; console putchar style.
   2086  */
   2087 int
   2088 tputchar(c, tp)
   2089 	int c;
   2090 	struct tty *tp;
   2091 {
   2092 	int s;
   2093 
   2094 	s = spltty();
   2095 	if (ISSET(tp->t_state,
   2096 	    TS_CARR_ON | TS_ISOPEN) != (TS_CARR_ON | TS_ISOPEN)) {
   2097 		splx(s);
   2098 		return (-1);
   2099 	}
   2100 	if (c == '\n')
   2101 		(void)ttyoutput('\r', tp);
   2102 	(void)ttyoutput(c, tp);
   2103 	ttstart(tp);
   2104 	splx(s);
   2105 	return (0);
   2106 }
   2107 
   2108 /*
   2109  * Sleep on chan, returning ERESTART if tty changed while we napped and
   2110  * returning any errors (e.g. EINTR/ETIMEDOUT) reported by tsleep.  If
   2111  * the tty is revoked, restarting a pending call will redo validation done
   2112  * at the start of the call.
   2113  */
   2114 int
   2115 ttysleep(tp, chan, pri, wmesg, timo)
   2116 	struct tty *tp;
   2117 	void *chan;
   2118 	int pri, timo;
   2119 	const char *wmesg;
   2120 {
   2121 	int error;
   2122 	short gen;
   2123 
   2124 	gen = tp->t_gen;
   2125 	if ((error = tsleep(chan, pri, wmesg, timo)) != 0)
   2126 		return (error);
   2127 	return (tp->t_gen == gen ? 0 : ERESTART);
   2128 }
   2129 
   2130 /*
   2131  * Initialise the global tty list.
   2132  */
   2133 void
   2134 tty_init()
   2135 {
   2136 
   2137 	TAILQ_INIT(&ttylist);
   2138 	tty_count = 0;
   2139 
   2140 	pool_init(&tty_pool, sizeof(struct tty), 0, 0, 0, "ttypl",
   2141 	    0, pool_page_alloc_nointr, pool_page_free_nointr, M_TTYS);
   2142 }
   2143 
   2144 /*
   2145  * Attach a tty to the tty list.
   2146  *
   2147  * This should be called ONLY once per real tty (including pty's).
   2148  * eg, on the sparc, the keyboard and mouse have struct tty's that are
   2149  * distinctly NOT usable as tty's, and thus should not be attached to
   2150  * the ttylist.  This is why this call is not done from ttymalloc().
   2151  *
   2152  * Device drivers should attach tty's at a similar time that they are
   2153  * ttymalloc()'ed, or, for the case of statically allocated struct tty's
   2154  * either in the attach or (first) open routine.
   2155  */
   2156 void
   2157 tty_attach(tp)
   2158 	struct tty *tp;
   2159 {
   2160 
   2161 	TAILQ_INSERT_TAIL(&ttylist, tp, tty_link);
   2162 	++tty_count;
   2163 }
   2164 
   2165 /*
   2166  * Remove a tty from the tty list.
   2167  */
   2168 void
   2169 tty_detach(tp)
   2170 	struct tty *tp;
   2171 {
   2172 
   2173 	--tty_count;
   2174 #ifdef DIAGNOSTIC
   2175 	if (tty_count < 0)
   2176 		panic("tty_detach: tty_count < 0");
   2177 #endif
   2178 	TAILQ_REMOVE(&ttylist, tp, tty_link);
   2179 }
   2180 
   2181 /*
   2182  * Allocate a tty structure and its associated buffers.
   2183  */
   2184 struct tty *
   2185 ttymalloc()
   2186 {
   2187 	struct tty *tp;
   2188 
   2189 	tp = pool_get(&tty_pool, PR_WAITOK);
   2190 	memset(tp, 0, sizeof(*tp));
   2191 	callout_init(&tp->t_outq_ch);
   2192 	callout_init(&tp->t_rstrt_ch);
   2193 	/* XXX: default to 1024 chars for now */
   2194 	clalloc(&tp->t_rawq, 1024, 1);
   2195 	clalloc(&tp->t_canq, 1024, 1);
   2196 	/* output queue doesn't need quoting */
   2197 	clalloc(&tp->t_outq, 1024, 0);
   2198 	return(tp);
   2199 }
   2200 
   2201 /*
   2202  * Free a tty structure and its buffers.
   2203  *
   2204  * Be sure to call tty_detach() for any tty that has been
   2205  * tty_attach()ed.
   2206  */
   2207 void
   2208 ttyfree(tp)
   2209 	struct tty *tp;
   2210 {
   2211 
   2212 	callout_stop(&tp->t_outq_ch);
   2213 	callout_stop(&tp->t_rstrt_ch);
   2214 	clfree(&tp->t_rawq);
   2215 	clfree(&tp->t_canq);
   2216 	clfree(&tp->t_outq);
   2217 	pool_put(&tty_pool, tp);
   2218 }
   2219