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