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