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