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