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