Home | History | Annotate | Line # | Download | only in kern
tty.c revision 1.125.2.11
      1 /*	$NetBSD: tty.c,v 1.125.2.11 2002/07/12 01:40:21 nathanw 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.125.2.11 2002/07/12 01:40:21 nathanw 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 	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(int c, struct tty *tp)
    300 {
    301 	int	iflag, lflag, i, error;
    302 	u_char	*cc;
    303 
    304 	/*
    305 	 * Unless the receiver is enabled, drop incoming data.
    306 	 */
    307 	if (!ISSET(tp->t_cflag, CREAD))
    308 		return (0);
    309 
    310 	/*
    311 	 * If input is pending take it first.
    312 	 */
    313 	lflag = tp->t_lflag;
    314 	if (ISSET(lflag, PENDIN))
    315 		ttypend(tp);
    316 	/*
    317 	 * Gather stats.
    318 	 */
    319 	if (ISSET(lflag, ICANON)) {
    320 		++tk_cancc;
    321 		++tp->t_cancc;
    322 	} else {
    323 		++tk_rawcc;
    324 		++tp->t_rawcc;
    325 	}
    326 	++tk_nin;
    327 
    328 	cc = tp->t_cc;
    329 
    330 	/*
    331 	 * Handle exceptional conditions (break, parity, framing).
    332 	 */
    333 	iflag = tp->t_iflag;
    334 	if ((error = (ISSET(c, TTY_ERRORMASK))) != 0) {
    335 		CLR(c, TTY_ERRORMASK);
    336 		if (ISSET(error, TTY_FE) && c == 0) {		/* Break. */
    337 			if (ISSET(iflag, IGNBRK))
    338 				return (0);
    339 			else if (ISSET(iflag, BRKINT)) {
    340 				ttyflush(tp, FREAD | FWRITE);
    341 				pgsignal(tp->t_pgrp, SIGINT, 1);
    342 				return (0);
    343 			} else if (ISSET(iflag, PARMRK))
    344 				goto parmrk;
    345 		} else if ((ISSET(error, TTY_PE) && ISSET(iflag, INPCK)) ||
    346 		    ISSET(error, TTY_FE)) {
    347 			if (ISSET(iflag, IGNPAR))
    348 				return (0);
    349 			else if (ISSET(iflag, PARMRK)) {
    350  parmrk:			(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
    351 				(void)putc(0    | TTY_QUOTE, &tp->t_rawq);
    352 				(void)putc(c    | TTY_QUOTE, &tp->t_rawq);
    353 				return (0);
    354 			} else
    355 				c = 0;
    356 		}
    357 	} else if (c == 0377 &&
    358 	    ISSET(iflag, ISTRIP|IGNPAR|INPCK|PARMRK) == (INPCK|PARMRK)) {
    359 		/* "Escape" a valid character of '\377'. */
    360 		(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
    361 		(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
    362 		goto endcase;
    363 	}
    364 
    365 	/*
    366 	 * In tandem mode, check high water mark.
    367 	 */
    368 	if (ISSET(iflag, IXOFF) || ISSET(tp->t_cflag, CHWFLOW))
    369 		ttyblock(tp);
    370 	if (!ISSET(tp->t_state, TS_TYPEN) && ISSET(iflag, ISTRIP))
    371 		CLR(c, 0x80);
    372 	if (!ISSET(lflag, EXTPROC)) {
    373 		/*
    374 		 * Check for literal nexting very first
    375 		 */
    376 		if (ISSET(tp->t_state, TS_LNCH)) {
    377 			SET(c, TTY_QUOTE);
    378 			CLR(tp->t_state, TS_LNCH);
    379 		}
    380 		/*
    381 		 * Scan for special characters.  This code
    382 		 * is really just a big case statement with
    383 		 * non-constant cases.  The bottom of the
    384 		 * case statement is labeled ``endcase'', so goto
    385 		 * it after a case match, or similar.
    386 		 */
    387 
    388 		/*
    389 		 * Control chars which aren't controlled
    390 		 * by ICANON, ISIG, or IXON.
    391 		 */
    392 		if (ISSET(lflag, IEXTEN)) {
    393 			if (CCEQ(cc[VLNEXT], c)) {
    394 				if (ISSET(lflag, ECHO)) {
    395 					if (ISSET(lflag, ECHOE)) {
    396 						(void)ttyoutput('^', tp);
    397 						(void)ttyoutput('\b', tp);
    398 					} else
    399 						ttyecho(c, tp);
    400 				}
    401 				SET(tp->t_state, TS_LNCH);
    402 				goto endcase;
    403 			}
    404 			if (CCEQ(cc[VDISCARD], c)) {
    405 				if (ISSET(lflag, FLUSHO))
    406 					CLR(tp->t_lflag, FLUSHO);
    407 				else {
    408 					ttyflush(tp, FWRITE);
    409 					ttyecho(c, tp);
    410 					if (tp->t_rawq.c_cc + tp->t_canq.c_cc)
    411 						ttyretype(tp);
    412 					SET(tp->t_lflag, FLUSHO);
    413 				}
    414 				goto startoutput;
    415 			}
    416 		}
    417 		/*
    418 		 * Signals.
    419 		 */
    420 		if (ISSET(lflag, ISIG)) {
    421 			if (CCEQ(cc[VINTR], c) || CCEQ(cc[VQUIT], c)) {
    422 				if (!ISSET(lflag, NOFLSH))
    423 					ttyflush(tp, FREAD | FWRITE);
    424 				ttyecho(c, tp);
    425 				pgsignal(tp->t_pgrp,
    426 				    CCEQ(cc[VINTR], c) ? SIGINT : SIGQUIT, 1);
    427 				goto endcase;
    428 			}
    429 			if (CCEQ(cc[VSUSP], c)) {
    430 				if (!ISSET(lflag, NOFLSH))
    431 					ttyflush(tp, FREAD);
    432 				ttyecho(c, tp);
    433 				pgsignal(tp->t_pgrp, SIGTSTP, 1);
    434 				goto endcase;
    435 			}
    436 		}
    437 		/*
    438 		 * Handle start/stop characters.
    439 		 */
    440 		if (ISSET(iflag, IXON)) {
    441 			if (CCEQ(cc[VSTOP], c)) {
    442 				if (!ISSET(tp->t_state, TS_TTSTOP)) {
    443 					SET(tp->t_state, TS_TTSTOP);
    444 					(*cdevsw[major(tp->t_dev)].d_stop)(tp,
    445 					   0);
    446 					return (0);
    447 				}
    448 				if (!CCEQ(cc[VSTART], c))
    449 					return (0);
    450 				/*
    451 				 * if VSTART == VSTOP then toggle
    452 				 */
    453 				goto endcase;
    454 			}
    455 			if (CCEQ(cc[VSTART], c))
    456 				goto restartoutput;
    457 		}
    458 		/*
    459 		 * IGNCR, ICRNL, & INLCR
    460 		 */
    461 		if (c == '\r') {
    462 			if (ISSET(iflag, IGNCR))
    463 				goto endcase;
    464 			else if (ISSET(iflag, ICRNL))
    465 				c = '\n';
    466 		} else if (c == '\n' && ISSET(iflag, INLCR))
    467 			c = '\r';
    468 	}
    469 	if (!ISSET(tp->t_lflag, EXTPROC) && ISSET(lflag, ICANON)) {
    470 		/*
    471 		 * From here on down canonical mode character
    472 		 * processing takes place.
    473 		 */
    474 		/*
    475 		 * erase (^H / ^?)
    476 		 */
    477 		if (CCEQ(cc[VERASE], c)) {
    478 			if (tp->t_rawq.c_cc)
    479 				ttyrub(unputc(&tp->t_rawq), tp);
    480 			goto endcase;
    481 		}
    482 		/*
    483 		 * kill (^U)
    484 		 */
    485 		if (CCEQ(cc[VKILL], c)) {
    486 			if (ISSET(lflag, ECHOKE) &&
    487 			    tp->t_rawq.c_cc == tp->t_rocount &&
    488 			    !ISSET(lflag, ECHOPRT))
    489 				while (tp->t_rawq.c_cc)
    490 					ttyrub(unputc(&tp->t_rawq), tp);
    491 			else {
    492 				ttyecho(c, tp);
    493 				if (ISSET(lflag, ECHOK) ||
    494 				    ISSET(lflag, ECHOKE))
    495 					ttyecho('\n', tp);
    496 				FLUSHQ(&tp->t_rawq);
    497 				tp->t_rocount = 0;
    498 			}
    499 			CLR(tp->t_state, TS_LOCAL);
    500 			goto endcase;
    501 		}
    502 		/*
    503 		 * Extensions to the POSIX.1 GTI set of functions.
    504 		 */
    505 		if (ISSET(lflag, IEXTEN)) {
    506 			/*
    507 			 * word erase (^W)
    508 			 */
    509 			if (CCEQ(cc[VWERASE], c)) {
    510 				int alt = ISSET(lflag, ALTWERASE);
    511 				int ctype;
    512 
    513 				/*
    514 				 * erase whitespace
    515 				 */
    516 				while ((c = unputc(&tp->t_rawq)) == ' ' ||
    517 				    c == '\t')
    518 					ttyrub(c, tp);
    519 				if (c == -1)
    520 					goto endcase;
    521 				/*
    522 				 * erase last char of word and remember the
    523 				 * next chars type (for ALTWERASE)
    524 				 */
    525 				ttyrub(c, tp);
    526 				c = unputc(&tp->t_rawq);
    527 				if (c == -1)
    528 					goto endcase;
    529 				if (c == ' ' || c == '\t') {
    530 					(void)putc(c, &tp->t_rawq);
    531 					goto endcase;
    532 				}
    533 				ctype = ISALPHA(c);
    534 				/*
    535 				 * erase rest of word
    536 				 */
    537 				do {
    538 					ttyrub(c, tp);
    539 					c = unputc(&tp->t_rawq);
    540 					if (c == -1)
    541 						goto endcase;
    542 				} while (c != ' ' && c != '\t' &&
    543 				    (alt == 0 || ISALPHA(c) == ctype));
    544 				(void)putc(c, &tp->t_rawq);
    545 				goto endcase;
    546 			}
    547 			/*
    548 			 * reprint line (^R)
    549 			 */
    550 			if (CCEQ(cc[VREPRINT], c)) {
    551 				ttyretype(tp);
    552 				goto endcase;
    553 			}
    554 			/*
    555 			 * ^T - kernel info and generate SIGINFO
    556 			 */
    557 			if (CCEQ(cc[VSTATUS], c)) {
    558 				if (!ISSET(lflag, NOKERNINFO))
    559 					ttyinfo(tp);
    560 				if (ISSET(lflag, ISIG))
    561 					pgsignal(tp->t_pgrp, SIGINFO, 1);
    562 				goto endcase;
    563 			}
    564 		}
    565 	}
    566 	/*
    567 	 * Check for input buffer overflow
    568 	 */
    569 	if (tp->t_rawq.c_cc + tp->t_canq.c_cc >= TTYHOG) {
    570 		if (ISSET(iflag, IMAXBEL)) {
    571 			if (tp->t_outq.c_cc < tp->t_hiwat)
    572 				(void)ttyoutput(CTRL('g'), tp);
    573 		} else
    574 			ttyflush(tp, FREAD | FWRITE);
    575 		goto endcase;
    576 	}
    577 	/*
    578 	 * Put data char in q for user and
    579 	 * wakeup on seeing a line delimiter.
    580 	 */
    581 	if (putc(c, &tp->t_rawq) >= 0) {
    582 		if (!ISSET(lflag, ICANON)) {
    583 			ttwakeup(tp);
    584 			ttyecho(c, tp);
    585 			goto endcase;
    586 		}
    587 		if (TTBREAKC(c, lflag)) {
    588 			tp->t_rocount = 0;
    589 			catq(&tp->t_rawq, &tp->t_canq);
    590 			ttwakeup(tp);
    591 		} else if (tp->t_rocount++ == 0)
    592 			tp->t_rocol = tp->t_column;
    593 		if (ISSET(tp->t_state, TS_ERASE)) {
    594 			/*
    595 			 * end of prterase \.../
    596 			 */
    597 			CLR(tp->t_state, TS_ERASE);
    598 			(void)ttyoutput('/', tp);
    599 		}
    600 		i = tp->t_column;
    601 		ttyecho(c, tp);
    602 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ECHO)) {
    603 			/*
    604 			 * Place the cursor over the '^' of the ^D.
    605 			 */
    606 			i = min(2, tp->t_column - i);
    607 			while (i > 0) {
    608 				(void)ttyoutput('\b', tp);
    609 				i--;
    610 			}
    611 		}
    612 	}
    613  endcase:
    614 	/*
    615 	 * IXANY means allow any character to restart output.
    616 	 */
    617 	if (ISSET(tp->t_state, TS_TTSTOP) &&
    618 	    !ISSET(iflag, IXANY) && cc[VSTART] != cc[VSTOP])
    619 		return (0);
    620  restartoutput:
    621 	CLR(tp->t_lflag, FLUSHO);
    622 	CLR(tp->t_state, TS_TTSTOP);
    623  startoutput:
    624 	return (ttstart(tp));
    625 }
    626 
    627 /*
    628  * Output a single character on a tty, doing output processing
    629  * as needed (expanding tabs, newline processing, etc.).
    630  * Returns < 0 if succeeds, otherwise returns char to resend.
    631  * Must be recursive.
    632  */
    633 int
    634 ttyoutput(int c, struct tty *tp)
    635 {
    636 	long	oflag;
    637 	int	col, notout, s;
    638 
    639 	oflag = tp->t_oflag;
    640 	if (!ISSET(oflag, OPOST)) {
    641 		tk_nout++;
    642 		tp->t_outcc++;
    643 		if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
    644 			return (c);
    645 		return (-1);
    646 	}
    647 	/*
    648 	 * Do tab expansion if OXTABS is set.  Special case if we do external
    649 	 * processing, we don't do the tab expansion because we'll probably
    650 	 * get it wrong.  If tab expansion needs to be done, let it happen
    651 	 * externally.
    652 	 */
    653 	CLR(c, ~TTY_CHARMASK);
    654 	if (c == '\t' &&
    655 	    ISSET(oflag, OXTABS) && !ISSET(tp->t_lflag, EXTPROC)) {
    656 		c = 8 - (tp->t_column & 7);
    657 		if (ISSET(tp->t_lflag, FLUSHO)) {
    658 			notout = 0;
    659 		} else {
    660 			s = spltty();		/* Don't interrupt tabs. */
    661 			notout = b_to_q("        ", c, &tp->t_outq);
    662 			c -= notout;
    663 			tk_nout += c;
    664 			tp->t_outcc += c;
    665 			splx(s);
    666 		}
    667 		tp->t_column += c;
    668 		return (notout ? '\t' : -1);
    669 	}
    670 	if (c == CEOT && ISSET(oflag, ONOEOT))
    671 		return (-1);
    672 
    673 	/*
    674 	 * Newline translation: if ONLCR is set,
    675 	 * translate newline into "\r\n".
    676 	 */
    677 	if (c == '\n' && ISSET(tp->t_oflag, ONLCR)) {
    678 		tk_nout++;
    679 		tp->t_outcc++;
    680 		if (!ISSET(tp->t_lflag, FLUSHO) && putc('\r', &tp->t_outq))
    681 			return (c);
    682 	}
    683 	/* If OCRNL is set, translate "\r" into "\n". */
    684 	else if (c == '\r' && ISSET(tp->t_oflag, OCRNL))
    685 		c = '\n';
    686 	/* If ONOCR is set, don't transmit CRs when on column 0. */
    687 	else if (c == '\r' && ISSET(tp->t_oflag, ONOCR) && tp->t_column == 0)
    688 		return (-1);
    689 
    690 	tk_nout++;
    691 	tp->t_outcc++;
    692 	if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
    693 		return (c);
    694 
    695 	col = tp->t_column;
    696 	switch (CCLASS(c)) {
    697 	case BACKSPACE:
    698 		if (col > 0)
    699 			--col;
    700 		break;
    701 	case CONTROL:
    702 		break;
    703 	case NEWLINE:
    704 		if (ISSET(tp->t_oflag, ONLCR | ONLRET))
    705 			col = 0;
    706 		break;
    707 	case RETURN:
    708 		col = 0;
    709 		break;
    710 	case ORDINARY:
    711 		++col;
    712 		break;
    713 	case TAB:
    714 		col = (col + 8) & ~7;
    715 		break;
    716 	}
    717 	tp->t_column = col;
    718 	return (-1);
    719 }
    720 
    721 /*
    722  * Ioctls for all tty devices.  Called after line-discipline specific ioctl
    723  * has been called to do discipline-specific functions and/or reject any
    724  * of these ioctl commands.
    725  */
    726 /* ARGSUSED */
    727 int
    728 ttioctl(struct tty *tp, u_long cmd, caddr_t data, int flag, struct proc *p)
    729 {
    730 	extern struct tty *constty;	/* Temporary virtual console. */
    731 	struct linesw	*lp;
    732 	int		s, error;
    733 
    734 	/* If the ioctl involves modification, hang if in the background. */
    735 	switch (cmd) {
    736 	case  TIOCFLUSH:
    737 	case  TIOCDRAIN:
    738 	case  TIOCSBRK:
    739 	case  TIOCCBRK:
    740 	case  TIOCSTART:
    741 	case  TIOCSETA:
    742 	case  TIOCSETD:
    743 	case  TIOCSLINED:
    744 	case  TIOCSETAF:
    745 	case  TIOCSETAW:
    746 #ifdef notdef
    747 	case  TIOCSPGRP:
    748 #endif
    749 	case  TIOCSTAT:
    750 	case  TIOCSTI:
    751 	case  TIOCSWINSZ:
    752 #ifdef COMPAT_OLDTTY
    753 	case  TIOCLBIC:
    754 	case  TIOCLBIS:
    755 	case  TIOCLSET:
    756 	case  TIOCSETC:
    757 	case OTIOCSETD:
    758 	case  TIOCSETN:
    759 	case  TIOCSETP:
    760 	case  TIOCSLTC:
    761 #endif
    762 		while (isbackground(curproc, tp) &&
    763 		    p->p_pgrp->pg_jobc && (p->p_flag & P_PPWAIT) == 0 &&
    764 		    !sigismasked(p, SIGTTOU)) {
    765 			pgsignal(p->p_pgrp, SIGTTOU, 1);
    766 			error = ttysleep(tp, &lbolt, TTOPRI | PCATCH, ttybg, 0);
    767 			if (error)
    768 				return (error);
    769 		}
    770 		break;
    771 	}
    772 
    773 	switch (cmd) {			/* Process the ioctl. */
    774 	case FIOASYNC:			/* set/clear async i/o */
    775 		s = spltty();
    776 		if (*(int *)data)
    777 			SET(tp->t_state, TS_ASYNC);
    778 		else
    779 			CLR(tp->t_state, TS_ASYNC);
    780 		splx(s);
    781 		break;
    782 	case FIONBIO:			/* set/clear non-blocking i/o */
    783 		break;			/* XXX: delete. */
    784 	case FIONREAD:			/* get # bytes to read */
    785 		*(int *)data = ttnread(tp);
    786 		break;
    787 	case TIOCEXCL:			/* set exclusive use of tty */
    788 		s = spltty();
    789 		SET(tp->t_state, TS_XCLUDE);
    790 		splx(s);
    791 		break;
    792 	case TIOCFLUSH: {		/* flush buffers */
    793 		int flags = *(int *)data;
    794 
    795 		if (flags == 0)
    796 			flags = FREAD | FWRITE;
    797 		else
    798 			flags &= FREAD | FWRITE;
    799 		ttyflush(tp, flags);
    800 		break;
    801 	}
    802 	case TIOCCONS:			/* become virtual console */
    803 		if (*(int *)data) {
    804 			if (constty && constty != tp &&
    805 			    ISSET(constty->t_state, TS_CARR_ON | TS_ISOPEN) ==
    806 			    (TS_CARR_ON | TS_ISOPEN))
    807 				return (EBUSY);
    808 #ifndef	UCONSOLE
    809 			if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
    810 				return (error);
    811 #endif
    812 			constty = tp;
    813 		} else if (tp == constty)
    814 			constty = NULL;
    815 		break;
    816 	case TIOCDRAIN:			/* wait till output drained */
    817 		if ((error = ttywait(tp)) != 0)
    818 			return (error);
    819 		break;
    820 	case TIOCGETA: {		/* get termios struct */
    821 		struct termios *t = (struct termios *)data;
    822 
    823 		memcpy(t, &tp->t_termios, sizeof(struct termios));
    824 		break;
    825 	}
    826 	case TIOCGETD:			/* get line discipline */
    827 		*(int *)data = tp->t_linesw->l_no;
    828 		break;
    829 	case TIOCGLINED:
    830 		(void)strncpy((char *)data, tp->t_linesw->l_name,
    831 		    TTLINEDNAMELEN - 1);
    832 		break;
    833 	case TIOCGWINSZ:		/* get window size */
    834 		*(struct winsize *)data = tp->t_winsize;
    835 		break;
    836 	case TIOCGPGRP:			/* get pgrp of tty */
    837 		if (!isctty(p, tp))
    838 			return (ENOTTY);
    839 		*(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
    840 		break;
    841 	case TIOCGSID:			/* get sid of tty */
    842 		if (!isctty(p, tp))
    843 			return (ENOTTY);
    844 		*(int *)data = tp->t_session->s_sid;
    845 		break;
    846 #ifdef TIOCHPCL
    847 	case TIOCHPCL:			/* hang up on last close */
    848 		s = spltty();
    849 		SET(tp->t_cflag, HUPCL);
    850 		splx(s);
    851 		break;
    852 #endif
    853 	case TIOCNXCL:			/* reset exclusive use of tty */
    854 		s = spltty();
    855 		CLR(tp->t_state, TS_XCLUDE);
    856 		splx(s);
    857 		break;
    858 	case TIOCOUTQ:			/* output queue size */
    859 		*(int *)data = tp->t_outq.c_cc;
    860 		break;
    861 	case TIOCSETA:			/* set termios struct */
    862 	case TIOCSETAW:			/* drain output, set */
    863 	case TIOCSETAF: {		/* drn out, fls in, set */
    864 		struct termios *t = (struct termios *)data;
    865 
    866 		s = spltty();
    867 		if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
    868 			if ((error = ttywait(tp)) != 0) {
    869 				splx(s);
    870 				return (error);
    871 			}
    872 			if (cmd == TIOCSETAF)
    873 				ttyflush(tp, FREAD);
    874 		}
    875 		if (!ISSET(t->c_cflag, CIGNORE)) {
    876 			/*
    877 			 * Set device hardware.
    878 			 */
    879 			if (tp->t_param && (error = (*tp->t_param)(tp, t))) {
    880 				splx(s);
    881 				return (error);
    882 			} else {
    883 				tp->t_cflag = t->c_cflag;
    884 				tp->t_ispeed = t->c_ispeed;
    885 				tp->t_ospeed = t->c_ospeed;
    886 				if (t->c_ospeed == 0 && tp->t_session &&
    887 				    tp->t_session->s_leader)
    888 					psignal(tp->t_session->s_leader,
    889 					    SIGHUP);
    890 			}
    891 			ttsetwater(tp);
    892 		}
    893 		if (cmd != TIOCSETAF) {
    894 			if (ISSET(t->c_lflag, ICANON) !=
    895 			    ISSET(tp->t_lflag, ICANON)) {
    896 				if (ISSET(t->c_lflag, ICANON)) {
    897 					SET(tp->t_lflag, PENDIN);
    898 					ttwakeup(tp);
    899 				} else {
    900 					struct clist tq;
    901 
    902 					catq(&tp->t_rawq, &tp->t_canq);
    903 					tq = tp->t_rawq;
    904 					tp->t_rawq = tp->t_canq;
    905 					tp->t_canq = tq;
    906 					CLR(tp->t_lflag, PENDIN);
    907 				}
    908 			}
    909 		}
    910 		tp->t_iflag = t->c_iflag;
    911 		tp->t_oflag = t->c_oflag;
    912 		/*
    913 		 * Make the EXTPROC bit read only.
    914 		 */
    915 		if (ISSET(tp->t_lflag, EXTPROC))
    916 			SET(t->c_lflag, EXTPROC);
    917 		else
    918 			CLR(t->c_lflag, EXTPROC);
    919 		tp->t_lflag = t->c_lflag | ISSET(tp->t_lflag, PENDIN);
    920 		memcpy(tp->t_cc, t->c_cc, sizeof(t->c_cc));
    921 		splx(s);
    922 		break;
    923 	}
    924 	case TIOCSETD: {		/* set line discipline */
    925 		int t = *(int *)data;
    926 
    927 		if ((u_int)t >= nlinesw)
    928 			return (ENXIO);
    929 		lp = linesw[t];
    930 		goto setldisc;
    931 	}
    932 	case TIOCSLINED: {		/* set line discipline */
    933 		char *name = (char *)data;
    934 		dev_t device;
    935 
    936 		/* Null terminate to prevent buffer overflow */
    937 		name[TTLINEDNAMELEN - 1] = '\0';
    938 		lp = ttyldisc_lookup(name);
    939 
    940  setldisc:
    941 		if (lp == NULL)
    942 			return (ENXIO);
    943 
    944 		if (lp != tp->t_linesw) {
    945 			device = tp->t_dev;
    946 			s = spltty();
    947 			(*tp->t_linesw->l_close)(tp, flag);
    948 			error = (*lp->l_open)(device, tp);
    949 			if (error) {
    950 				(void)(*tp->t_linesw->l_open)(device, tp);
    951 				splx(s);
    952 				return (error);
    953 			}
    954 			tp->t_linesw = lp;
    955 			splx(s);
    956 		}
    957 		break;
    958 	}
    959 	case TIOCSTART:			/* start output, like ^Q */
    960 		s = spltty();
    961 		if (ISSET(tp->t_state, TS_TTSTOP) ||
    962 		    ISSET(tp->t_lflag, FLUSHO)) {
    963 			CLR(tp->t_lflag, FLUSHO);
    964 			CLR(tp->t_state, TS_TTSTOP);
    965 			ttstart(tp);
    966 		}
    967 		splx(s);
    968 		break;
    969 	case TIOCSTI:			/* simulate terminal input */
    970 		if (p->p_ucred->cr_uid && (flag & FREAD) == 0)
    971 			return (EPERM);
    972 		if (p->p_ucred->cr_uid && !isctty(p, tp))
    973 			return (EACCES);
    974 		(*tp->t_linesw->l_rint)(*(u_char *)data, tp);
    975 		break;
    976 	case TIOCSTOP:			/* stop output, like ^S */
    977 		s = spltty();
    978 		if (!ISSET(tp->t_state, TS_TTSTOP)) {
    979 			SET(tp->t_state, TS_TTSTOP);
    980 			(*cdevsw[major(tp->t_dev)].d_stop)(tp, 0);
    981 		}
    982 		splx(s);
    983 		break;
    984 	case TIOCSCTTY:			/* become controlling tty */
    985 		/* Session ctty vnode pointer set in vnode layer. */
    986 		if (!SESS_LEADER(p) ||
    987 		    ((p->p_session->s_ttyvp || tp->t_session) &&
    988 		    (tp->t_session != p->p_session)))
    989 			return (EPERM);
    990 		SESSHOLD(p->p_session);
    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 (EPASSTHROUGH);
   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(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(struct tty *tp)
   1102 {
   1103 	int	error;
   1104 
   1105 	if ((error = ttywait(tp)) == 0)
   1106 		ttyflush(tp, FREAD);
   1107 	return (error);
   1108 }
   1109 
   1110 /*
   1111  * Flush tty read and/or write queues, notifying anyone waiting.
   1112  */
   1113 void
   1114 ttyflush(struct tty *tp, int rw)
   1115 {
   1116 	int	s;
   1117 
   1118 	s = spltty();
   1119 	if (rw & FREAD) {
   1120 		FLUSHQ(&tp->t_canq);
   1121 		FLUSHQ(&tp->t_rawq);
   1122 		tp->t_rocount = 0;
   1123 		tp->t_rocol = 0;
   1124 		CLR(tp->t_state, TS_LOCAL);
   1125 		ttwakeup(tp);
   1126 	}
   1127 	if (rw & FWRITE) {
   1128 		CLR(tp->t_state, TS_TTSTOP);
   1129 		(*cdevsw[major(tp->t_dev)].d_stop)(tp, rw);
   1130 		FLUSHQ(&tp->t_outq);
   1131 		wakeup((caddr_t)&tp->t_outq);
   1132 		selwakeup(&tp->t_wsel);
   1133 	}
   1134 	splx(s);
   1135 }
   1136 
   1137 /*
   1138  * Copy in the default termios characters.
   1139  */
   1140 void
   1141 ttychars(struct tty *tp)
   1142 {
   1143 
   1144 	memcpy(tp->t_cc, ttydefchars, sizeof(ttydefchars));
   1145 }
   1146 
   1147 /*
   1148  * Send stop character on input overflow.
   1149  */
   1150 static void
   1151 ttyblock(struct tty *tp)
   1152 {
   1153 	int	total;
   1154 
   1155 	total = tp->t_rawq.c_cc + tp->t_canq.c_cc;
   1156 	if (tp->t_rawq.c_cc > TTYHOG) {
   1157 		ttyflush(tp, FREAD | FWRITE);
   1158 		CLR(tp->t_state, TS_TBLOCK);
   1159 	}
   1160 	/*
   1161 	 * Block further input iff: current input > threshold
   1162 	 * AND input is available to user program.
   1163 	 */
   1164 	if (total >= TTYHOG / 2 &&
   1165 	    !ISSET(tp->t_state, TS_TBLOCK) &&
   1166 	    (!ISSET(tp->t_lflag, ICANON) || tp->t_canq.c_cc > 0)) {
   1167 		if (ISSET(tp->t_iflag, IXOFF) &&
   1168 		    tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
   1169 		    putc(tp->t_cc[VSTOP], &tp->t_outq) == 0) {
   1170 			SET(tp->t_state, TS_TBLOCK);
   1171 			ttstart(tp);
   1172 		}
   1173 		/* Try to block remote output via hardware flow control. */
   1174 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
   1175 		    (*tp->t_hwiflow)(tp, 1) != 0)
   1176 			SET(tp->t_state, TS_TBLOCK);
   1177 	}
   1178 }
   1179 
   1180 void
   1181 ttrstrt(void *tp_arg)
   1182 {
   1183 	struct tty	*tp;
   1184 	int		s;
   1185 
   1186 #ifdef DIAGNOSTIC
   1187 	if (tp_arg == NULL)
   1188 		panic("ttrstrt");
   1189 #endif
   1190 	tp = tp_arg;
   1191 	s = spltty();
   1192 
   1193 	CLR(tp->t_state, TS_TIMEOUT);
   1194 	ttstart(tp);
   1195 
   1196 	splx(s);
   1197 }
   1198 
   1199 int
   1200 ttstart(struct tty *tp)
   1201 {
   1202 
   1203 	if (tp->t_oproc != NULL)	/* XXX: Kludge for pty. */
   1204 		(*tp->t_oproc)(tp);
   1205 	return (0);
   1206 }
   1207 
   1208 /*
   1209  * "close" a line discipline
   1210  */
   1211 int
   1212 ttylclose(struct tty *tp, int flag)
   1213 {
   1214 
   1215 	if (flag & FNONBLOCK)
   1216 		ttyflush(tp, FREAD | FWRITE);
   1217 	else
   1218 		ttywflush(tp);
   1219 	return (0);
   1220 }
   1221 
   1222 /*
   1223  * Handle modem control transition on a tty.
   1224  * Flag indicates new state of carrier.
   1225  * Returns 0 if the line should be turned off, otherwise 1.
   1226  */
   1227 int
   1228 ttymodem(struct tty *tp, int flag)
   1229 {
   1230 
   1231 	if (flag == 0) {
   1232 		if (ISSET(tp->t_state, TS_CARR_ON)) {
   1233 			/*
   1234 			 * Lost carrier.
   1235 			 */
   1236 			CLR(tp->t_state, TS_CARR_ON);
   1237 			if (ISSET(tp->t_state, TS_ISOPEN) && !CONNECTED(tp)) {
   1238 				if (tp->t_session && tp->t_session->s_leader)
   1239 					psignal(tp->t_session->s_leader,
   1240 					    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 lwp	*l;
   1917 	struct proc	*p, *pick;
   1918 	struct timeval	utime, stime;
   1919 	int		tmp;
   1920 
   1921 	if (ttycheckoutq(tp, 0) == 0)
   1922 		return;
   1923 
   1924 	/* Print load average. */
   1925 	tmp = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
   1926 	ttyprintf(tp, "load: %d.%02d ", tmp / 100, tmp % 100);
   1927 
   1928 	if (tp->t_session == NULL)
   1929 		ttyprintf(tp, "not a controlling terminal\n");
   1930 	else if (tp->t_pgrp == NULL)
   1931 		ttyprintf(tp, "no foreground process group\n");
   1932 	else if ((p = tp->t_pgrp->pg_members.lh_first) == 0)
   1933 		ttyprintf(tp, "empty foreground process group\n");
   1934 	else {
   1935 		/* Pick interesting process. */
   1936 		for (pick = NULL; p != NULL; p = p->p_pglist.le_next)
   1937 			if (proc_compare(pick, p))
   1938 				pick = p;
   1939 
   1940 		ttyprintf(tp, " cmd: %s %d [", pick->p_comm, pick->p_pid);
   1941 		LIST_FOREACH(l, &pick->p_lwps, l_sibling)
   1942 		    ttyprintf(tp, "%s%s",
   1943 		    l->l_stat == LSONPROC ? "running" :
   1944 		    l->l_stat == LSRUN ? "runnable" :
   1945 		    l->l_wmesg ? l->l_wmesg : "iowait",
   1946 			(LIST_NEXT(l, l_sibling) != NULL) ? " " : "] ");
   1947 
   1948 		calcru(pick, &utime, &stime, NULL);
   1949 
   1950 		/* Round up and print user time. */
   1951 		utime.tv_usec += 5000;
   1952 		if (utime.tv_usec >= 1000000) {
   1953 			utime.tv_sec += 1;
   1954 			utime.tv_usec -= 1000000;
   1955 		}
   1956 		ttyprintf(tp, "%ld.%02ldu ", (long int)utime.tv_sec,
   1957 		    (long int)utime.tv_usec / 10000);
   1958 
   1959 		/* Round up and print system time. */
   1960 		stime.tv_usec += 5000;
   1961 		if (stime.tv_usec >= 1000000) {
   1962 			stime.tv_sec += 1;
   1963 			stime.tv_usec -= 1000000;
   1964 		}
   1965 		ttyprintf(tp, "%ld.%02lds ", (long int)stime.tv_sec,
   1966 		    (long int)stime.tv_usec / 10000);
   1967 
   1968 #define	pgtok(a)	(((u_long) ((a) * PAGE_SIZE) / 1024))
   1969 		/* Print percentage cpu. */
   1970 		tmp = (pick->p_pctcpu * 10000 + FSCALE / 2) >> FSHIFT;
   1971 		ttyprintf(tp, "%d%% ", tmp / 100);
   1972 
   1973 		/* Print resident set size. */
   1974 		if (pick->p_stat == SIDL || P_ZOMBIE(pick))
   1975 			tmp = 0;
   1976 		else {
   1977 			struct vmspace *vm = pick->p_vmspace;
   1978 			tmp = pgtok(vm_resident_count(vm));
   1979 		}
   1980 		ttyprintf(tp, "%dk\n", tmp);
   1981 	}
   1982 	tp->t_rocount = 0;	/* so pending input will be retyped if BS */
   1983 }
   1984 
   1985 /*
   1986  * Returns 1 if p2 is "better" than p1
   1987  *
   1988  * The algorithm for picking the "interesting" process is thus:
   1989  *
   1990  *	1) Only foreground processes are eligible - implied.
   1991  *	2) Runnable processes are favored over anything else.  The runner
   1992  *	   with the highest cpu utilization is picked (p_estcpu).  Ties are
   1993  *	   broken by picking the highest pid.
   1994  *	3) The sleeper with the shortest sleep time is next.  With ties,
   1995  *	   we pick out just "short-term" sleepers (P_SINTR == 0).
   1996  *	4) Further ties are broken by picking the highest pid.
   1997  */
   1998 #define	ISRUN(p)	((p)->p_nrlwps > 0)
   1999 #define	TESTAB(a, b)	((a)<<1 | (b))
   2000 #define	ONLYA	2
   2001 #define	ONLYB	1
   2002 #define	BOTH	3
   2003 
   2004 static int
   2005 proc_compare(struct proc *p1, struct proc *p2)
   2006 {
   2007 
   2008 	if (p1 == NULL)
   2009 		return (1);
   2010 	/*
   2011 	 * see if at least one of them is runnable
   2012 	 */
   2013 	switch (TESTAB(ISRUN(p1), ISRUN(p2))) {
   2014 	case ONLYA:
   2015 		return (0);
   2016 	case ONLYB:
   2017 		return (1);
   2018 	case BOTH:
   2019 		/*
   2020 		 * tie - favor one with highest recent cpu utilization
   2021 		 */
   2022 		if (p2->p_estcpu > p1->p_estcpu)
   2023 			return (1);
   2024 		if (p1->p_estcpu > p2->p_estcpu)
   2025 			return (0);
   2026 		return (p2->p_pid > p1->p_pid);	/* tie - return highest pid */
   2027 	}
   2028 	/*
   2029  	 * weed out zombies
   2030 	 */
   2031 	switch (TESTAB(P_ZOMBIE(p1), P_ZOMBIE(p2))) {
   2032 	case ONLYA:
   2033 		return (1);
   2034 	case ONLYB:
   2035 		return (0);
   2036 	case BOTH:
   2037 		return (p2->p_pid > p1->p_pid);	/* tie - return highest pid */
   2038 	}
   2039 #if 0 /* XXX NJWLWP */
   2040 	/*
   2041 	 * pick the one with the smallest sleep time
   2042 	 */
   2043 	if (p2->p_slptime > p1->p_slptime)
   2044 		return (0);
   2045 	if (p1->p_slptime > p2->p_slptime)
   2046 		return (1);
   2047 	/*
   2048 	 * favor one sleeping in a non-interruptible sleep
   2049 	 */
   2050 	if (p1->p_flag & P_SINTR && (p2->p_flag & P_SINTR) == 0)
   2051 		return (1);
   2052 	if (p2->p_flag & P_SINTR && (p1->p_flag & P_SINTR) == 0)
   2053 		return (0);
   2054 #endif
   2055 	return (p2->p_pid > p1->p_pid);		/* tie - return highest pid */
   2056 }
   2057 
   2058 /*
   2059  * Output char to tty; console putchar style.
   2060  */
   2061 int
   2062 tputchar(int c, struct tty *tp)
   2063 {
   2064 	int	s;
   2065 
   2066 	s = spltty();
   2067 	if (ISSET(tp->t_state,
   2068 	    TS_CARR_ON | TS_ISOPEN) != (TS_CARR_ON | TS_ISOPEN)) {
   2069 		splx(s);
   2070 		return (-1);
   2071 	}
   2072 	if (c == '\n')
   2073 		(void)ttyoutput('\r', tp);
   2074 	(void)ttyoutput(c, tp);
   2075 	ttstart(tp);
   2076 	splx(s);
   2077 	return (0);
   2078 }
   2079 
   2080 /*
   2081  * Sleep on chan, returning ERESTART if tty changed while we napped and
   2082  * returning any errors (e.g. EINTR/ETIMEDOUT) reported by tsleep.  If
   2083  * the tty is revoked, restarting a pending call will redo validation done
   2084  * at the start of the call.
   2085  */
   2086 int
   2087 ttysleep(struct tty *tp, void *chan, int pri, const char *wmesg, int timo)
   2088 {
   2089 	int	error;
   2090 	short	gen;
   2091 
   2092 	gen = tp->t_gen;
   2093 	if ((error = tsleep(chan, pri, wmesg, timo)) != 0)
   2094 		return (error);
   2095 	return (tp->t_gen == gen ? 0 : ERESTART);
   2096 }
   2097 
   2098 /*
   2099  * Initialise the global tty list.
   2100  */
   2101 void
   2102 tty_init(void)
   2103 {
   2104 
   2105 	ttyldisc_init();
   2106 
   2107 	TAILQ_INIT(&ttylist);
   2108 	tty_count = 0;
   2109 
   2110 	pool_init(&tty_pool, sizeof(struct tty), 0, 0, 0, "ttypl",
   2111 	    &pool_allocator_nointr);
   2112 }
   2113 
   2114 /*
   2115  * Attach a tty to the tty list.
   2116  *
   2117  * This should be called ONLY once per real tty (including pty's).
   2118  * eg, on the sparc, the keyboard and mouse have struct tty's that are
   2119  * distinctly NOT usable as tty's, and thus should not be attached to
   2120  * the ttylist.  This is why this call is not done from ttymalloc().
   2121  *
   2122  * Device drivers should attach tty's at a similar time that they are
   2123  * ttymalloc()'ed, or, for the case of statically allocated struct tty's
   2124  * either in the attach or (first) open routine.
   2125  */
   2126 void
   2127 tty_attach(struct tty *tp)
   2128 {
   2129 
   2130 	TAILQ_INSERT_TAIL(&ttylist, tp, tty_link);
   2131 	++tty_count;
   2132 }
   2133 
   2134 /*
   2135  * Remove a tty from the tty list.
   2136  */
   2137 void
   2138 tty_detach(struct tty *tp)
   2139 {
   2140 
   2141 	--tty_count;
   2142 #ifdef DIAGNOSTIC
   2143 	if (tty_count < 0)
   2144 		panic("tty_detach: tty_count < 0");
   2145 #endif
   2146 	TAILQ_REMOVE(&ttylist, tp, tty_link);
   2147 }
   2148 
   2149 /*
   2150  * Allocate a tty structure and its associated buffers.
   2151  */
   2152 struct tty *
   2153 ttymalloc(void)
   2154 {
   2155 	struct tty	*tp;
   2156 
   2157 	tp = pool_get(&tty_pool, PR_WAITOK);
   2158 	memset(tp, 0, sizeof(*tp));
   2159 	callout_init(&tp->t_outq_ch);
   2160 	callout_init(&tp->t_rstrt_ch);
   2161 	/* XXX: default to 1024 chars for now */
   2162 	clalloc(&tp->t_rawq, 1024, 1);
   2163 	clalloc(&tp->t_canq, 1024, 1);
   2164 	/* output queue doesn't need quoting */
   2165 	clalloc(&tp->t_outq, 1024, 0);
   2166 	/* Set default line discipline. */
   2167 	tp->t_linesw = linesw[0];
   2168 	return (tp);
   2169 }
   2170 
   2171 /*
   2172  * Free a tty structure and its buffers.
   2173  *
   2174  * Be sure to call tty_detach() for any tty that has been
   2175  * tty_attach()ed.
   2176  */
   2177 void
   2178 ttyfree(struct tty *tp)
   2179 {
   2180 
   2181 	callout_stop(&tp->t_outq_ch);
   2182 	callout_stop(&tp->t_rstrt_ch);
   2183 	clfree(&tp->t_rawq);
   2184 	clfree(&tp->t_canq);
   2185 	clfree(&tp->t_outq);
   2186 	pool_put(&tty_pool, tp);
   2187 }
   2188