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