Home | History | Annotate | Line # | Download | only in kern
tty.c revision 1.163
      1 /*	$NetBSD: tty.c,v 1.163 2004/03/05 07:27:22 dbj 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.163 2004/03/05 07:27:22 dbj 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 		s = spltty();
   1169 		TTY_LOCK(tp);
   1170 		ttyinfo(tp);
   1171 		TTY_UNLOCK(tp);
   1172 		splx(s);
   1173 		break;
   1174 	case TIOCSWINSZ:		/* set window size */
   1175 		if (memcmp((caddr_t)&tp->t_winsize, data,
   1176 		    sizeof(struct winsize))) {
   1177 			tp->t_winsize = *(struct winsize *)data;
   1178 			pgsignal(tp->t_pgrp, SIGWINCH, 1);
   1179 		}
   1180 		break;
   1181 	default:
   1182 #ifdef COMPAT_OLDTTY
   1183 		return (ttcompat(tp, cmd, data, flag, p));
   1184 #else
   1185 		return (EPASSTHROUGH);
   1186 #endif
   1187 	}
   1188 	return (0);
   1189 }
   1190 
   1191 int
   1192 ttpoll(struct tty *tp, int events, struct proc *p)
   1193 {
   1194 	int	revents, s;
   1195 
   1196 	revents = 0;
   1197 	s = spltty();
   1198 	TTY_LOCK(tp);
   1199 	if (events & (POLLIN | POLLRDNORM))
   1200 		if (ttnread(tp) > 0)
   1201 			revents |= events & (POLLIN | POLLRDNORM);
   1202 
   1203 	if (events & (POLLOUT | POLLWRNORM))
   1204 		if (tp->t_outq.c_cc <= tp->t_lowat)
   1205 			revents |= events & (POLLOUT | POLLWRNORM);
   1206 
   1207 	if (events & POLLHUP)
   1208 		if (!CONNECTED(tp))
   1209 			revents |= POLLHUP;
   1210 
   1211 	if (revents == 0) {
   1212 		if (events & (POLLIN | POLLHUP | POLLRDNORM))
   1213 			selrecord(p, &tp->t_rsel);
   1214 
   1215 		if (events & (POLLOUT | POLLWRNORM))
   1216 			selrecord(p, &tp->t_wsel);
   1217 	}
   1218 
   1219 	TTY_UNLOCK(tp);
   1220 	splx(s);
   1221 	return (revents);
   1222 }
   1223 
   1224 static void
   1225 filt_ttyrdetach(struct knote *kn)
   1226 {
   1227 	struct tty	*tp;
   1228 	int		s;
   1229 
   1230 	tp = kn->kn_hook;
   1231 	s = spltty();
   1232 	SLIST_REMOVE(&tp->t_rsel.sel_klist, kn, knote, kn_selnext);
   1233 	splx(s);
   1234 }
   1235 
   1236 static int
   1237 filt_ttyread(struct knote *kn, long hint)
   1238 {
   1239 	struct tty	*tp;
   1240 	int		s;
   1241 
   1242 	tp = kn->kn_hook;
   1243 	s = spltty();
   1244 	if ((hint & NOTE_SUBMIT) == 0)
   1245 		TTY_LOCK(tp);
   1246 	kn->kn_data = ttnread(tp);
   1247 	if ((hint & NOTE_SUBMIT) == 0)
   1248 		TTY_UNLOCK(tp);
   1249 	splx(s);
   1250 	return (kn->kn_data > 0);
   1251 }
   1252 
   1253 static void
   1254 filt_ttywdetach(struct knote *kn)
   1255 {
   1256 	struct tty	*tp;
   1257 	int		s;
   1258 
   1259 	tp = kn->kn_hook;
   1260 	s = spltty();
   1261 	TTY_LOCK(tp);
   1262 	SLIST_REMOVE(&tp->t_wsel.sel_klist, kn, knote, kn_selnext);
   1263 	TTY_UNLOCK(tp);
   1264 	splx(s);
   1265 }
   1266 
   1267 static int
   1268 filt_ttywrite(struct knote *kn, long hint)
   1269 {
   1270 	struct tty	*tp;
   1271 	int		canwrite, s;
   1272 
   1273 	tp = kn->kn_hook;
   1274 	s = spltty();
   1275 	if ((hint & NOTE_SUBMIT) == 0)
   1276 		TTY_LOCK(tp);
   1277 	kn->kn_data = tp->t_outq.c_cn - tp->t_outq.c_cc;
   1278 	canwrite = (tp->t_outq.c_cc <= tp->t_lowat) && CONNECTED(tp);
   1279 	if ((hint & NOTE_SUBMIT) == 0)
   1280 		TTY_UNLOCK(tp);
   1281 	splx(s);
   1282 	return (canwrite);
   1283 }
   1284 
   1285 static const struct filterops ttyread_filtops =
   1286 	{ 1, NULL, filt_ttyrdetach, filt_ttyread };
   1287 static const struct filterops ttywrite_filtops =
   1288 	{ 1, NULL, filt_ttywdetach, filt_ttywrite };
   1289 
   1290 int
   1291 ttykqfilter(dev_t dev, struct knote *kn)
   1292 {
   1293 	struct tty	*tp;
   1294 	struct klist	*klist;
   1295 	int		s;
   1296 	const struct cdevsw	*cdev;
   1297 
   1298         if (((cdev = cdevsw_lookup(dev)) == NULL) ||
   1299 	    (cdev->d_tty == NULL) ||
   1300 	    ((tp = (*cdev->d_tty)(dev)) == NULL))
   1301 		return (ENXIO);
   1302 
   1303 	switch (kn->kn_filter) {
   1304 	case EVFILT_READ:
   1305 		klist = &tp->t_rsel.sel_klist;
   1306 		kn->kn_fop = &ttyread_filtops;
   1307 		break;
   1308 	case EVFILT_WRITE:
   1309 		klist = &tp->t_wsel.sel_klist;
   1310 		kn->kn_fop = &ttywrite_filtops;
   1311 		break;
   1312 	default:
   1313 		return (1);
   1314 	}
   1315 
   1316 	kn->kn_hook = tp;
   1317 
   1318 	s = spltty();
   1319 	TTY_LOCK(tp);
   1320 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
   1321 	TTY_UNLOCK(tp);
   1322 	splx(s);
   1323 
   1324 	return (0);
   1325 }
   1326 
   1327 /*
   1328  * Find the number of chars ready to be read from this tty.
   1329  * Call at spltty() and with the tty slock held.
   1330  */
   1331 static int
   1332 ttnread(struct tty *tp)
   1333 {
   1334 	int	nread;
   1335 
   1336 	if (ISSET(tp->t_lflag, PENDIN))
   1337 		ttypend(tp);
   1338 	nread = tp->t_canq.c_cc;
   1339 	if (!ISSET(tp->t_lflag, ICANON)) {
   1340 		nread += tp->t_rawq.c_cc;
   1341 		if (nread < tp->t_cc[VMIN] && !tp->t_cc[VTIME])
   1342 			nread = 0;
   1343 	}
   1344 	return (nread);
   1345 }
   1346 
   1347 /*
   1348  * Wait for output to drain.
   1349  */
   1350 int
   1351 ttywait(struct tty *tp)
   1352 {
   1353 	int	error, s;
   1354 
   1355 	error = 0;
   1356 	s = spltty();
   1357 	TTY_LOCK(tp);
   1358 	while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
   1359 	    CONNECTED(tp) && tp->t_oproc) {
   1360 		(*tp->t_oproc)(tp);
   1361 		SET(tp->t_state, TS_ASLEEP);
   1362 		error = ttysleep(tp, &tp->t_outq, TTOPRI | PCATCH, ttyout, 0);
   1363 		if (error)
   1364 			break;
   1365 	}
   1366 	TTY_UNLOCK(tp);
   1367 	splx(s);
   1368 	return (error);
   1369 }
   1370 
   1371 /*
   1372  * Flush if successfully wait.
   1373  */
   1374 int
   1375 ttywflush(struct tty *tp)
   1376 {
   1377 	int	error;
   1378 	int	s;
   1379 
   1380 	if ((error = ttywait(tp)) == 0) {
   1381 		s = spltty();
   1382 		TTY_LOCK(tp);
   1383 		ttyflush(tp, FREAD);
   1384 		TTY_UNLOCK(tp);
   1385 		splx(s);
   1386 	}
   1387 	return (error);
   1388 }
   1389 
   1390 /*
   1391  * Flush tty read and/or write queues, notifying anyone waiting.
   1392  * Call at spltty() and with the tty slock held.
   1393  */
   1394 void
   1395 ttyflush(struct tty *tp, int rw)
   1396 {
   1397 	const struct cdevsw *cdev;
   1398 
   1399 	if (rw & FREAD) {
   1400 		FLUSHQ(&tp->t_canq);
   1401 		FLUSHQ(&tp->t_rawq);
   1402 		tp->t_rocount = 0;
   1403 		tp->t_rocol = 0;
   1404 		CLR(tp->t_state, TS_LOCAL);
   1405 		ttwakeup(tp);
   1406 	}
   1407 	if (rw & FWRITE) {
   1408 		CLR(tp->t_state, TS_TTSTOP);
   1409 		cdev = cdevsw_lookup(tp->t_dev);
   1410 		if (cdev != NULL)
   1411 			(*cdev->d_stop)(tp, rw);
   1412 		FLUSHQ(&tp->t_outq);
   1413 		wakeup((caddr_t)&tp->t_outq);
   1414 		selnotify(&tp->t_wsel, NOTE_SUBMIT);
   1415 	}
   1416 }
   1417 
   1418 /*
   1419  * Copy in the default termios characters.
   1420  */
   1421 void
   1422 ttychars(struct tty *tp)
   1423 {
   1424 
   1425 	memcpy(tp->t_cc, ttydefchars, sizeof(ttydefchars));
   1426 }
   1427 
   1428 /*
   1429  * Send stop character on input overflow.
   1430  * Call at spltty() and with the tty slock held.
   1431  */
   1432 static void
   1433 ttyblock(struct tty *tp)
   1434 {
   1435 	int	total;
   1436 
   1437 	total = tp->t_rawq.c_cc + tp->t_canq.c_cc;
   1438 	if (tp->t_rawq.c_cc > TTYHOG) {
   1439 		ttyflush(tp, FREAD | FWRITE);
   1440 		CLR(tp->t_state, TS_TBLOCK);
   1441 	}
   1442 	/*
   1443 	 * Block further input iff: current input > threshold
   1444 	 * AND input is available to user program.
   1445 	 */
   1446 	if (total >= TTYHOG / 2 &&
   1447 	    !ISSET(tp->t_state, TS_TBLOCK) &&
   1448 	    (!ISSET(tp->t_lflag, ICANON) || tp->t_canq.c_cc > 0)) {
   1449 		if (ISSET(tp->t_iflag, IXOFF) &&
   1450 		    tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
   1451 		    putc(tp->t_cc[VSTOP], &tp->t_outq) == 0) {
   1452 			SET(tp->t_state, TS_TBLOCK);
   1453 			ttstart(tp);
   1454 		}
   1455 		/* Try to block remote output via hardware flow control. */
   1456 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
   1457 		    (*tp->t_hwiflow)(tp, 1) != 0)
   1458 			SET(tp->t_state, TS_TBLOCK);
   1459 	}
   1460 }
   1461 
   1462 /*
   1463  * Delayed line discipline output
   1464  */
   1465 void
   1466 ttrstrt(void *tp_arg)
   1467 {
   1468 	struct tty	*tp;
   1469 	int		s;
   1470 
   1471 #ifdef DIAGNOSTIC
   1472 	if (tp_arg == NULL)
   1473 		panic("ttrstrt");
   1474 #endif
   1475 	tp = tp_arg;
   1476 	s = spltty();
   1477 	TTY_LOCK(tp);
   1478 
   1479 	CLR(tp->t_state, TS_TIMEOUT);
   1480 	ttstart(tp); /* XXX - Shouldn't this be tp->l_start(tp)? */
   1481 
   1482 	TTY_UNLOCK(tp);
   1483 	splx(s);
   1484 }
   1485 
   1486 /*
   1487  * start a line discipline
   1488  * Always call at spltty() and with tty slock held?
   1489  */
   1490 int
   1491 ttstart(struct tty *tp)
   1492 {
   1493 
   1494 	if (tp->t_oproc != NULL)	/* XXX: Kludge for pty. */
   1495 		(*tp->t_oproc)(tp);
   1496 	return (0);
   1497 }
   1498 
   1499 /*
   1500  * "close" a line discipline
   1501  */
   1502 int
   1503 ttylclose(struct tty *tp, int flag)
   1504 {
   1505 	int s;
   1506 
   1507 	if (flag & FNONBLOCK) {
   1508 		s = spltty();
   1509 		TTY_LOCK(tp);
   1510 		ttyflush(tp, FREAD | FWRITE);
   1511 		TTY_UNLOCK(tp);
   1512 		splx(s);
   1513 	} else
   1514 		ttywflush(tp);
   1515 	return (0);
   1516 }
   1517 
   1518 /*
   1519  * Handle modem control transition on a tty.
   1520  * Flag indicates new state of carrier.
   1521  * Returns 0 if the line should be turned off, otherwise 1.
   1522  *
   1523  * Must be called at spltty().
   1524  */
   1525 int
   1526 ttymodem(struct tty *tp, int flag)
   1527 {
   1528 
   1529 	TTY_LOCK(tp);
   1530 	if (flag == 0) {
   1531 		if (ISSET(tp->t_state, TS_CARR_ON)) {
   1532 			/*
   1533 			 * Lost carrier.
   1534 			 */
   1535 			CLR(tp->t_state, TS_CARR_ON);
   1536 			if (ISSET(tp->t_state, TS_ISOPEN) && !CONNECTED(tp)) {
   1537 				if (tp->t_session && tp->t_session->s_leader)
   1538 					psignal(tp->t_session->s_leader,
   1539 					    SIGHUP);
   1540 				ttyflush(tp, FREAD | FWRITE);
   1541 				TTY_UNLOCK(tp);
   1542 				return (0);
   1543 			}
   1544 		}
   1545 	} else {
   1546 		if (!ISSET(tp->t_state, TS_CARR_ON)) {
   1547 			/*
   1548 			 * Carrier now on.
   1549 			 */
   1550 			SET(tp->t_state, TS_CARR_ON);
   1551 			ttwakeup(tp);
   1552 		}
   1553 	}
   1554 	TTY_UNLOCK(tp);
   1555 	return (1);
   1556 }
   1557 
   1558 /*
   1559  * Default modem control routine (for other line disciplines).
   1560  * Return argument flag, to turn off device on carrier drop.
   1561  *
   1562  * Must be called at spltty().
   1563  */
   1564 int
   1565 nullmodem(struct tty *tp, int flag)
   1566 {
   1567 
   1568 	TTY_LOCK(tp);
   1569 	if (flag)
   1570 		SET(tp->t_state, TS_CARR_ON);
   1571 	else {
   1572 		CLR(tp->t_state, TS_CARR_ON);
   1573 		if (!CONNECTED(tp)) {
   1574 			if (tp->t_session && tp->t_session->s_leader)
   1575 				psignal(tp->t_session->s_leader, SIGHUP);
   1576 			TTY_UNLOCK(tp);
   1577 			return (0);
   1578 		}
   1579 	}
   1580 	TTY_UNLOCK(tp);
   1581 	return (1);
   1582 }
   1583 
   1584 /*
   1585  * Reinput pending characters after state switch.
   1586  * Call at spltty() and with the tty slock held.
   1587  */
   1588 void
   1589 ttypend(struct tty *tp)
   1590 {
   1591 	struct clist	tq;
   1592 	int		c;
   1593 
   1594 	CLR(tp->t_lflag, PENDIN);
   1595 	SET(tp->t_state, TS_TYPEN);
   1596 	tq = tp->t_rawq;
   1597 	tp->t_rawq.c_cc = 0;
   1598 	tp->t_rawq.c_cf = tp->t_rawq.c_cl = 0;
   1599 	while ((c = getc(&tq)) >= 0)
   1600 		ttyinput_wlock(c, tp);
   1601 	CLR(tp->t_state, TS_TYPEN);
   1602 }
   1603 
   1604 /*
   1605  * Process a read call on a tty device.
   1606  */
   1607 int
   1608 ttread(struct tty *tp, struct uio *uio, int flag)
   1609 {
   1610 	struct clist	*qp;
   1611 	u_char		*cc;
   1612 	struct proc	*p;
   1613 	int		c, s, first, error, has_stime, last_cc;
   1614 	long		lflag, slp;
   1615 	struct timeval	stime;
   1616 
   1617 	cc = tp->t_cc;
   1618 	p = curproc;
   1619 	error = 0;
   1620 	has_stime = 0;
   1621 	last_cc = 0;
   1622 	slp = 0;
   1623 
   1624  loop:
   1625 	s = spltty();
   1626 	TTY_LOCK(tp);
   1627 	lflag = tp->t_lflag;
   1628 	/*
   1629 	 * take pending input first
   1630 	 */
   1631 	if (ISSET(lflag, PENDIN))
   1632 		ttypend(tp);
   1633 
   1634 	/*
   1635 	 * Hang process if it's in the background.
   1636 	 */
   1637 	if (isbackground(p, tp)) {
   1638 		if (sigismember(&p->p_sigctx.ps_sigignore, SIGTTIN) ||
   1639 		    sigismember(&p->p_sigctx.ps_sigmask, SIGTTIN) ||
   1640 		    p->p_flag & P_PPWAIT || p->p_pgrp->pg_jobc == 0) {
   1641 			TTY_UNLOCK(tp);
   1642 			splx(s);
   1643 			return (EIO);
   1644 		}
   1645 		pgsignal(p->p_pgrp, SIGTTIN, 1);
   1646 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH | PNORELOCK, ttybg, 0);
   1647 		splx(s);
   1648 		if (error)
   1649 			return (error);
   1650 		goto loop;
   1651 	}
   1652 
   1653 	if (!ISSET(lflag, ICANON)) {
   1654 		int m = cc[VMIN];
   1655 		long t = cc[VTIME];
   1656 
   1657 		qp = &tp->t_rawq;
   1658 		/*
   1659 		 * Check each of the four combinations.
   1660 		 * (m > 0 && t == 0) is the normal read case.
   1661 		 * It should be fairly efficient, so we check that and its
   1662 		 * companion case (m == 0 && t == 0) first.
   1663 		 * For the other two cases, we compute the target sleep time
   1664 		 * into slp.
   1665 		 */
   1666 		if (t == 0) {
   1667 			if (qp->c_cc < m)
   1668 				goto sleep;
   1669 			goto read;
   1670 		}
   1671 		t *= hz;		/* time in deca-ticks */
   1672 /*
   1673  * Time difference in deca-ticks, split division to avoid numeric overflow.
   1674  * Ok for hz < ~200kHz
   1675  */
   1676 #define	diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 10 * hz + \
   1677 			 ((t1).tv_usec - (t2).tv_usec) / 100 * hz / 1000)
   1678 		if (m > 0) {
   1679 			if (qp->c_cc <= 0)
   1680 				goto sleep;
   1681 			if (qp->c_cc >= m)
   1682 				goto read;
   1683 			if (!has_stime) {
   1684 				/* first character, start timer */
   1685 				has_stime = 1;
   1686 				stime = time;
   1687 				slp = t;
   1688 			} else if (qp->c_cc > last_cc) {
   1689 				/* got a character, restart timer */
   1690 				stime = time;
   1691 				slp = t;
   1692 			} else {
   1693 				/* nothing, check expiration */
   1694 				slp = t - diff(time, stime);
   1695 			}
   1696 		} else {	/* m == 0 */
   1697 			if (qp->c_cc > 0)
   1698 				goto read;
   1699 			if (!has_stime) {
   1700 				has_stime = 1;
   1701 				stime = time;
   1702 				slp = t;
   1703 			} else
   1704 				slp = t - diff(time, stime);
   1705 		}
   1706 		last_cc = qp->c_cc;
   1707 #undef diff
   1708 		if (slp > 0) {
   1709 			/*
   1710 			 * Convert deca-ticks back to ticks.
   1711 			 * Rounding down may make us wake up just short
   1712 			 * of the target, so we round up.
   1713 			 * Maybe we should do 'slp/10 + 1' because the
   1714 			 * first tick maybe almost immediate.
   1715 			 * However it is more useful for a program that sets
   1716 			 * VTIME=10 to wakeup every second not every 1.01
   1717 			 * seconds (if hz=100).
   1718 			 */
   1719 			slp = (slp + 9)/ 10;
   1720 			goto sleep;
   1721 		}
   1722 	} else if ((qp = &tp->t_canq)->c_cc <= 0) {
   1723 		int	carrier;
   1724 
   1725  sleep:
   1726 		/*
   1727 		 * If there is no input, sleep on rawq
   1728 		 * awaiting hardware receipt and notification.
   1729 		 * If we have data, we don't need to check for carrier.
   1730 		 */
   1731 		carrier = CONNECTED(tp);
   1732 		if (!carrier && ISSET(tp->t_state, TS_ISOPEN)) {
   1733 			TTY_UNLOCK(tp);
   1734 			splx(s);
   1735 			return (0);	/* EOF */
   1736 		}
   1737 		if (flag & IO_NDELAY) {
   1738 			TTY_UNLOCK(tp);
   1739 			splx(s);
   1740 			return (EWOULDBLOCK);
   1741 		}
   1742 		error = ttysleep(tp, &tp->t_rawq, TTIPRI | PCATCH | PNORELOCK,
   1743 		    carrier ? ttyin : ttopen, slp);
   1744 		splx(s);
   1745 		/* VMIN == 0: any quantity read satisfies */
   1746 		if (cc[VMIN] == 0 && error == EWOULDBLOCK)
   1747 			return (0);
   1748 		if (error && error != EWOULDBLOCK)
   1749 			return (error);
   1750 		goto loop;
   1751 	}
   1752  read:
   1753 	TTY_UNLOCK(tp);
   1754 	splx(s);
   1755 
   1756 	/*
   1757 	 * Input present, check for input mapping and processing.
   1758 	 */
   1759 	first = 1;
   1760 	while ((c = getc(qp)) >= 0) {
   1761 		/*
   1762 		 * delayed suspend (^Y)
   1763 		 */
   1764 		if (CCEQ(cc[VDSUSP], c) &&
   1765 		    ISSET(lflag, IEXTEN|ISIG) == (IEXTEN|ISIG)) {
   1766 			pgsignal(tp->t_pgrp, SIGTSTP, 1);
   1767 			if (first) {
   1768 				s = spltty();
   1769 				TTY_LOCK(tp);
   1770 				error = ttysleep(tp, &lbolt,
   1771 				    TTIPRI | PCATCH | PNORELOCK, ttybg, 0);
   1772 				splx(s);
   1773 				if (error)
   1774 					break;
   1775 				goto loop;
   1776 			}
   1777 			break;
   1778 		}
   1779 		/*
   1780 		 * Interpret EOF only in canonical mode.
   1781 		 */
   1782 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
   1783 			break;
   1784 		/*
   1785 		 * Give user character.
   1786 		 */
   1787  		error = ureadc(c, uio);
   1788 		if (error)
   1789 			break;
   1790  		if (uio->uio_resid == 0)
   1791 			break;
   1792 		/*
   1793 		 * In canonical mode check for a "break character"
   1794 		 * marking the end of a "line of input".
   1795 		 */
   1796 		if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
   1797 			break;
   1798 		first = 0;
   1799 	}
   1800 	/*
   1801 	 * Look to unblock output now that (presumably)
   1802 	 * the input queue has gone down.
   1803 	 */
   1804 	s = spltty();
   1805 	TTY_LOCK(tp);
   1806 	if (ISSET(tp->t_state, TS_TBLOCK) && tp->t_rawq.c_cc < TTYHOG / 5) {
   1807 		if (ISSET(tp->t_iflag, IXOFF) &&
   1808 		    cc[VSTART] != _POSIX_VDISABLE &&
   1809 		    putc(cc[VSTART], &tp->t_outq) == 0) {
   1810 			CLR(tp->t_state, TS_TBLOCK);
   1811 			ttstart(tp);
   1812 		}
   1813 		/* Try to unblock remote output via hardware flow control. */
   1814 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
   1815 		    (*tp->t_hwiflow)(tp, 0) != 0)
   1816 			CLR(tp->t_state, TS_TBLOCK);
   1817 	}
   1818 	TTY_UNLOCK(tp);
   1819 	splx(s);
   1820 	return (error);
   1821 }
   1822 
   1823 /*
   1824  * Check the output queue on tp for space for a kernel message (from uprintf
   1825  * or tprintf).  Allow some space over the normal hiwater mark so we don't
   1826  * lose messages due to normal flow control, but don't let the tty run amok.
   1827  * Sleeps here are not interruptible, but we return prematurely if new signals
   1828  * arrive.
   1829  * Call with tty slock held.
   1830  */
   1831 static int
   1832 ttycheckoutq_wlock(struct tty *tp, int wait)
   1833 {
   1834 	int	hiwat, s, error;
   1835 
   1836 	hiwat = tp->t_hiwat;
   1837 	s = spltty();
   1838 	if (tp->t_outq.c_cc > hiwat + 200)
   1839 		while (tp->t_outq.c_cc > hiwat) {
   1840 			ttstart(tp);
   1841 			if (wait == 0) {
   1842 				splx(s);
   1843 				return (0);
   1844 			}
   1845 			SET(tp->t_state, TS_ASLEEP);
   1846 			error = ltsleep(&tp->t_outq, (PZERO - 1) | PCATCH,
   1847 			    "ttckoutq", hz, &tp->t_slock);
   1848 			if (error == EINTR)
   1849 				wait = 0;
   1850 		}
   1851 
   1852 	splx(s);
   1853 	return (1);
   1854 }
   1855 
   1856 int
   1857 ttycheckoutq(struct tty *tp, int wait)
   1858 {
   1859 	int	r, s;
   1860 
   1861 	s = spltty();
   1862 	TTY_LOCK(tp);
   1863 	r = ttycheckoutq_wlock(tp, wait);
   1864 	TTY_UNLOCK(tp);
   1865 	splx(s);
   1866 	return (r);
   1867 }
   1868 
   1869 /*
   1870  * Process a write call on a tty device.
   1871  */
   1872 int
   1873 ttwrite(struct tty *tp, struct uio *uio, int flag)
   1874 {
   1875 	u_char		*cp;
   1876 	struct proc	*p;
   1877 	int		cc, ce, i, hiwat, error, s;
   1878 	size_t		cnt;
   1879 	u_char		obuf[OBUFSIZ];
   1880 
   1881 	cp = NULL;
   1882 	hiwat = tp->t_hiwat;
   1883 	cnt = uio->uio_resid;
   1884 	error = 0;
   1885 	cc = 0;
   1886  loop:
   1887 	s = spltty();
   1888 	TTY_LOCK(tp);
   1889 	if (!CONNECTED(tp)) {
   1890 		if (ISSET(tp->t_state, TS_ISOPEN)) {
   1891 			TTY_UNLOCK(tp);
   1892 			splx(s);
   1893 			return (EIO);
   1894 		} else if (flag & IO_NDELAY) {
   1895 			TTY_UNLOCK(tp);
   1896 			splx(s);
   1897 			error = EWOULDBLOCK;
   1898 			goto out;
   1899 		} else {
   1900 			/* Sleep awaiting carrier. */
   1901 			error = ttysleep(tp,
   1902 			    &tp->t_rawq, TTIPRI | PCATCH | PNORELOCK, ttopen, 0);
   1903 			splx(s);
   1904 			if (error)
   1905 				goto out;
   1906 			goto loop;
   1907 		}
   1908 	}
   1909 	TTY_UNLOCK(tp);
   1910 	splx(s);
   1911 	/*
   1912 	 * Hang the process if it's in the background.
   1913 	 */
   1914 	p = curproc;
   1915 	if (isbackground(p, tp) &&
   1916 	    ISSET(tp->t_lflag, TOSTOP) && (p->p_flag & P_PPWAIT) == 0 &&
   1917 	    !sigismember(&p->p_sigctx.ps_sigignore, SIGTTOU) &&
   1918 	    !sigismember(&p->p_sigctx.ps_sigmask, SIGTTOU)) {
   1919 		if (p->p_pgrp->pg_jobc == 0) {
   1920 			error = EIO;
   1921 			goto out;
   1922 		}
   1923 		pgsignal(p->p_pgrp, SIGTTOU, 1);
   1924 		s = spltty();
   1925 		TTY_LOCK(tp);
   1926 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH | PNORELOCK, ttybg, 0);
   1927 		splx(s);
   1928 		if (error)
   1929 			goto out;
   1930 		goto loop;
   1931 	}
   1932 	/*
   1933 	 * Process the user's data in at most OBUFSIZ chunks.  Perform any
   1934 	 * output translation.  Keep track of high water mark, sleep on
   1935 	 * overflow awaiting device aid in acquiring new space.
   1936 	 */
   1937 	while (uio->uio_resid > 0 || cc > 0) {
   1938 		if (ISSET(tp->t_lflag, FLUSHO)) {
   1939 			TTY_UNLOCK(tp);
   1940 			uio->uio_resid = 0;
   1941 			return (0);
   1942 		}
   1943 		if (tp->t_outq.c_cc > hiwat)
   1944 			goto ovhiwat;
   1945 		/*
   1946 		 * Grab a hunk of data from the user, unless we have some
   1947 		 * leftover from last time.
   1948 		 */
   1949 		if (cc == 0) {
   1950 			cc = min(uio->uio_resid, OBUFSIZ);
   1951 			cp = obuf;
   1952 			error = uiomove(cp, cc, uio);
   1953 			if (error) {
   1954 				cc = 0;
   1955 				goto out;
   1956 			}
   1957 		}
   1958 		/*
   1959 		 * If nothing fancy need be done, grab those characters we
   1960 		 * can handle without any of ttyoutput's processing and
   1961 		 * just transfer them to the output q.  For those chars
   1962 		 * which require special processing (as indicated by the
   1963 		 * bits in char_type), call ttyoutput.  After processing
   1964 		 * a hunk of data, look for FLUSHO so ^O's will take effect
   1965 		 * immediately.
   1966 		 */
   1967 		s = spltty();
   1968 		TTY_LOCK(tp);
   1969 		while (cc > 0) {
   1970 			if (!ISSET(tp->t_oflag, OPOST))
   1971 				ce = cc;
   1972 			else {
   1973 				ce = cc - scanc((u_int)cc, cp, char_type,
   1974 				    CCLASSMASK);
   1975 				/*
   1976 				 * If ce is zero, then we're processing
   1977 				 * a special character through ttyoutput.
   1978 				 */
   1979 				if (ce == 0) {
   1980 					tp->t_rocount = 0;
   1981 					if (ttyoutput(*cp, tp) >= 0) {
   1982 						/* out of space */
   1983 						TTY_UNLOCK(tp);
   1984 						splx(s);
   1985 						goto overfull;
   1986 					}
   1987 					cp++;
   1988 					cc--;
   1989 					if (ISSET(tp->t_lflag, FLUSHO) ||
   1990 					    tp->t_outq.c_cc > hiwat) {
   1991 						TTY_UNLOCK(tp);
   1992 						splx(s);
   1993 						goto ovhiwat;
   1994 					}
   1995 					continue;
   1996 				}
   1997 			}
   1998 			/*
   1999 			 * A bunch of normal characters have been found.
   2000 			 * Transfer them en masse to the output queue and
   2001 			 * continue processing at the top of the loop.
   2002 			 * If there are any further characters in this
   2003 			 * <= OBUFSIZ chunk, the first should be a character
   2004 			 * requiring special handling by ttyoutput.
   2005 			 */
   2006 			tp->t_rocount = 0;
   2007 			i = b_to_q(cp, ce, &tp->t_outq);
   2008 			ce -= i;
   2009 			tp->t_column += ce;
   2010 			cp += ce, cc -= ce, tk_nout += ce;
   2011 			tp->t_outcc += ce;
   2012 			if (i > 0) {
   2013 				/* out of space */
   2014 				TTY_UNLOCK(tp);
   2015 				splx(s);
   2016 				goto overfull;
   2017 			}
   2018 			if (ISSET(tp->t_lflag, FLUSHO) ||
   2019 			    tp->t_outq.c_cc > hiwat)
   2020 				break;
   2021 		}
   2022 		TTY_UNLOCK(tp);
   2023 		splx(s);
   2024 		ttstart(tp);
   2025 	}
   2026 
   2027  out:
   2028 	/*
   2029 	 * If cc is nonzero, we leave the uio structure inconsistent, as the
   2030 	 * offset and iov pointers have moved forward, but it doesn't matter
   2031 	 * (the call will either return short or restart with a new uio).
   2032 	 */
   2033 	uio->uio_resid += cc;
   2034 	return (error);
   2035 
   2036  overfull:
   2037 	/*
   2038 	 * Since we are using ring buffers, if we can't insert any more into
   2039 	 * the output queue, we can assume the ring is full and that someone
   2040 	 * forgot to set the high water mark correctly.  We set it and then
   2041 	 * proceed as normal.
   2042 	 */
   2043 	hiwat = tp->t_outq.c_cc - 1;
   2044 
   2045  ovhiwat:
   2046 	ttstart(tp);
   2047 	s = spltty();
   2048 	TTY_LOCK(tp);
   2049 	/*
   2050 	 * This can only occur if FLUSHO is set in t_lflag,
   2051 	 * or if ttstart/oproc is synchronous (or very fast).
   2052 	 */
   2053 	if (tp->t_outq.c_cc <= hiwat) {
   2054 		TTY_UNLOCK(tp);
   2055 		splx(s);
   2056 		goto loop;
   2057 	}
   2058 	if (flag & IO_NDELAY) {
   2059 		TTY_UNLOCK(tp);
   2060 		splx(s);
   2061 		error = (uio->uio_resid == cnt) ? EWOULDBLOCK : 0;
   2062 		goto out;
   2063 	}
   2064 	SET(tp->t_state, TS_ASLEEP);
   2065 	error = ttysleep(tp, &tp->t_outq, TTOPRI | PCATCH | PNORELOCK, ttyout, 0);
   2066 	splx(s);
   2067 	if (error)
   2068 		goto out;
   2069 	goto loop;
   2070 }
   2071 
   2072 /*
   2073  * Rubout one character from the rawq of tp
   2074  * as cleanly as possible.
   2075  * Called with tty slock held.
   2076  */
   2077 void
   2078 ttyrub(int c, struct tty *tp)
   2079 {
   2080 	u_char	*cp;
   2081 	int	savecol, tabc, s;
   2082 
   2083 	if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
   2084 		return;
   2085 	CLR(tp->t_lflag, FLUSHO);
   2086 	if (ISSET(tp->t_lflag, ECHOE)) {
   2087 		if (tp->t_rocount == 0) {
   2088 			/*
   2089 			 * Screwed by ttwrite; retype
   2090 			 */
   2091 			ttyretype(tp);
   2092 			return;
   2093 		}
   2094 		if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
   2095 			ttyrubo(tp, 2);
   2096 		else {
   2097 			CLR(c, ~TTY_CHARMASK);
   2098 			switch (CCLASS(c)) {
   2099 			case ORDINARY:
   2100 				ttyrubo(tp, 1);
   2101 				break;
   2102 			case BACKSPACE:
   2103 			case CONTROL:
   2104 			case NEWLINE:
   2105 			case RETURN:
   2106 			case VTAB:
   2107 				if (ISSET(tp->t_lflag, ECHOCTL))
   2108 					ttyrubo(tp, 2);
   2109 				break;
   2110 			case TAB:
   2111 				if (tp->t_rocount < tp->t_rawq.c_cc) {
   2112 					ttyretype(tp);
   2113 					return;
   2114 				}
   2115 				s = spltty();
   2116 				savecol = tp->t_column;
   2117 				SET(tp->t_state, TS_CNTTB);
   2118 				SET(tp->t_lflag, FLUSHO);
   2119 				tp->t_column = tp->t_rocol;
   2120 				for (cp = firstc(&tp->t_rawq, &tabc); cp;
   2121 				    cp = nextc(&tp->t_rawq, cp, &tabc))
   2122 					ttyecho(tabc, tp);
   2123 				CLR(tp->t_lflag, FLUSHO);
   2124 				CLR(tp->t_state, TS_CNTTB);
   2125 				splx(s);
   2126 
   2127 				/* savecol will now be length of the tab. */
   2128 				savecol -= tp->t_column;
   2129 				tp->t_column += savecol;
   2130 				if (savecol > 8)
   2131 					savecol = 8;	/* overflow screw */
   2132 				while (--savecol >= 0)
   2133 					(void)ttyoutput('\b', tp);
   2134 				break;
   2135 			default:			/* XXX */
   2136 #define	PANICSTR	"ttyrub: would panic c = %d, val = %d\n"
   2137 				(void)printf(PANICSTR, c, CCLASS(c));
   2138 #ifdef notdef
   2139 				panic(PANICSTR, c, CCLASS(c));
   2140 #endif
   2141 			}
   2142 		}
   2143 	} else if (ISSET(tp->t_lflag, ECHOPRT)) {
   2144 		if (!ISSET(tp->t_state, TS_ERASE)) {
   2145 			SET(tp->t_state, TS_ERASE);
   2146 			(void)ttyoutput('\\', tp);
   2147 		}
   2148 		ttyecho(c, tp);
   2149 	} else
   2150 		ttyecho(tp->t_cc[VERASE], tp);
   2151 	--tp->t_rocount;
   2152 }
   2153 
   2154 /*
   2155  * Back over cnt characters, erasing them.
   2156  * Called with tty slock held.
   2157  */
   2158 static void
   2159 ttyrubo(struct tty *tp, int cnt)
   2160 {
   2161 
   2162 	while (cnt-- > 0) {
   2163 		(void)ttyoutput('\b', tp);
   2164 		(void)ttyoutput(' ', tp);
   2165 		(void)ttyoutput('\b', tp);
   2166 	}
   2167 }
   2168 
   2169 /*
   2170  * ttyretype --
   2171  *	Reprint the rawq line.  Note, it is assumed that c_cc has already
   2172  *	been checked.
   2173  *
   2174  * Called with tty slock held.
   2175  */
   2176 void
   2177 ttyretype(struct tty *tp)
   2178 {
   2179 	u_char	*cp;
   2180 	int	s, c;
   2181 
   2182 	/* Echo the reprint character. */
   2183 	if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
   2184 		ttyecho(tp->t_cc[VREPRINT], tp);
   2185 
   2186 	(void)ttyoutput('\n', tp);
   2187 
   2188 	s = spltty();
   2189 	for (cp = firstc(&tp->t_canq, &c); cp; cp = nextc(&tp->t_canq, cp, &c))
   2190 		ttyecho(c, tp);
   2191 	for (cp = firstc(&tp->t_rawq, &c); cp; cp = nextc(&tp->t_rawq, cp, &c))
   2192 		ttyecho(c, tp);
   2193 	CLR(tp->t_state, TS_ERASE);
   2194 	splx(s);
   2195 
   2196 	tp->t_rocount = tp->t_rawq.c_cc;
   2197 	tp->t_rocol = 0;
   2198 }
   2199 
   2200 /*
   2201  * Echo a typed character to the terminal.
   2202  * Called with tty slock held.
   2203  */
   2204 static void
   2205 ttyecho(int c, struct tty *tp)
   2206 {
   2207 
   2208 	if (!ISSET(tp->t_state, TS_CNTTB))
   2209 		CLR(tp->t_lflag, FLUSHO);
   2210 	if ((!ISSET(tp->t_lflag, ECHO) &&
   2211 	    (!ISSET(tp->t_lflag, ECHONL) || c != '\n')) ||
   2212 	    ISSET(tp->t_lflag, EXTPROC))
   2213 		return;
   2214 	if (((ISSET(tp->t_lflag, ECHOCTL) &&
   2215 	    (ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n')) ||
   2216 	    ISSET(c, TTY_CHARMASK) == 0177)) {
   2217 		(void)ttyoutput('^', tp);
   2218 		CLR(c, ~TTY_CHARMASK);
   2219 		if (c == 0177)
   2220 			c = '?';
   2221 		else
   2222 			c += 'A' - 1;
   2223 	}
   2224 	(void)ttyoutput(c, tp);
   2225 }
   2226 
   2227 /*
   2228  * Wake up any readers on a tty.
   2229  * Called with tty slock held.
   2230  */
   2231 void
   2232 ttwakeup(struct tty *tp)
   2233 {
   2234 
   2235 	selnotify(&tp->t_rsel, NOTE_SUBMIT);
   2236 	if (ISSET(tp->t_state, TS_ASYNC))
   2237 		pgsignal(tp->t_pgrp, SIGIO, 1);
   2238 	wakeup((caddr_t)&tp->t_rawq);
   2239 }
   2240 
   2241 /*
   2242  * Look up a code for a specified speed in a conversion table;
   2243  * used by drivers to map software speed values to hardware parameters.
   2244  */
   2245 int
   2246 ttspeedtab(int speed, struct speedtab *table)
   2247 {
   2248 
   2249 	for (; table->sp_speed != -1; table++)
   2250 		if (table->sp_speed == speed)
   2251 			return (table->sp_code);
   2252 	return (-1);
   2253 }
   2254 
   2255 /*
   2256  * Set tty hi and low water marks.
   2257  *
   2258  * Try to arrange the dynamics so there's about one second
   2259  * from hi to low water.
   2260  */
   2261 void
   2262 ttsetwater(struct tty *tp)
   2263 {
   2264 	int	cps, x;
   2265 
   2266 #define	CLAMP(x, h, l)	((x) > h ? h : ((x) < l) ? l : (x))
   2267 
   2268 	cps = tp->t_ospeed / 10;
   2269 	tp->t_lowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
   2270 	x += cps;
   2271 	x = CLAMP(x, TTMAXHIWAT, TTMINHIWAT);
   2272 	tp->t_hiwat = roundup(x, CBSIZE);
   2273 #undef	CLAMP
   2274 }
   2275 
   2276 /*
   2277  * Report on state of foreground process group.
   2278  * Call with tty slock held.
   2279  */
   2280 void
   2281 ttyinfo(struct tty *tp)
   2282 {
   2283 	struct lwp	*l;
   2284 	struct proc	*p, *pick;
   2285 	struct timeval	utime, stime;
   2286 	int		tmp;
   2287 
   2288 	if (ttycheckoutq_wlock(tp, 0) == 0)
   2289 		return;
   2290 
   2291 	/* Print load average. */
   2292 	tmp = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
   2293 	ttyprintf_nolock(tp, "load: %d.%02d ", tmp / 100, tmp % 100);
   2294 
   2295 	if (tp->t_session == NULL)
   2296 		ttyprintf_nolock(tp, "not a controlling terminal\n");
   2297 	else if (tp->t_pgrp == NULL)
   2298 		ttyprintf_nolock(tp, "no foreground process group\n");
   2299 	else if ((p = LIST_FIRST(&tp->t_pgrp->pg_members)) == 0)
   2300 		ttyprintf_nolock(tp, "empty foreground process group\n");
   2301 	else {
   2302 		/* Pick interesting process. */
   2303 		for (pick = NULL; p != NULL; p = LIST_NEXT(p, p_pglist))
   2304 			if (proc_compare(pick, p))
   2305 				pick = p;
   2306 
   2307 		ttyprintf_nolock(tp, " cmd: %s %d [", pick->p_comm, pick->p_pid);
   2308 		LIST_FOREACH(l, &pick->p_lwps, l_sibling)
   2309 		    ttyprintf_nolock(tp, "%s%s",
   2310 		    l->l_stat == LSONPROC ? "running" :
   2311 		    l->l_stat == LSRUN ? "runnable" :
   2312 		    l->l_wmesg ? l->l_wmesg : "iowait",
   2313 			(LIST_NEXT(l, l_sibling) != NULL) ? " " : "] ");
   2314 
   2315 		calcru(pick, &utime, &stime, NULL);
   2316 
   2317 		/* Round up and print user time. */
   2318 		utime.tv_usec += 5000;
   2319 		if (utime.tv_usec >= 1000000) {
   2320 			utime.tv_sec += 1;
   2321 			utime.tv_usec -= 1000000;
   2322 		}
   2323 		ttyprintf_nolock(tp, "%ld.%02ldu ", (long int)utime.tv_sec,
   2324 		    (long int)utime.tv_usec / 10000);
   2325 
   2326 		/* Round up and print system time. */
   2327 		stime.tv_usec += 5000;
   2328 		if (stime.tv_usec >= 1000000) {
   2329 			stime.tv_sec += 1;
   2330 			stime.tv_usec -= 1000000;
   2331 		}
   2332 		ttyprintf_nolock(tp, "%ld.%02lds ", (long int)stime.tv_sec,
   2333 		    (long int)stime.tv_usec / 10000);
   2334 
   2335 #define	pgtok(a)	(((u_long) ((a) * PAGE_SIZE) / 1024))
   2336 		/* Print percentage CPU. */
   2337 		tmp = (pick->p_pctcpu * 10000 + FSCALE / 2) >> FSHIFT;
   2338 		ttyprintf_nolock(tp, "%d%% ", tmp / 100);
   2339 
   2340 		/* Print resident set size. */
   2341 		if (pick->p_stat == SIDL || P_ZOMBIE(pick))
   2342 			tmp = 0;
   2343 		else {
   2344 			struct vmspace *vm = pick->p_vmspace;
   2345 			tmp = pgtok(vm_resident_count(vm));
   2346 		}
   2347 		ttyprintf_nolock(tp, "%dk\n", tmp);
   2348 	}
   2349 	tp->t_rocount = 0;	/* so pending input will be retyped if BS */
   2350 }
   2351 
   2352 /*
   2353  * Returns 1 if p2 is "better" than p1
   2354  *
   2355  * The algorithm for picking the "interesting" process is thus:
   2356  *
   2357  *	1) Only foreground processes are eligible - implied.
   2358  *	2) Runnable processes are favored over anything else.  The runner
   2359  *	   with the highest CPU utilization is picked (p_estcpu).  Ties are
   2360  *	   broken by picking the highest pid.
   2361  *	3) The sleeper with the shortest sleep time is next.  With ties,
   2362  *	   we pick out just "short-term" sleepers (P_SINTR == 0).
   2363  *	4) Further ties are broken by picking the highest pid.
   2364  */
   2365 #define	ISRUN(p)	((p)->p_nrlwps > 0)
   2366 #define	TESTAB(a, b)	((a)<<1 | (b))
   2367 #define	ONLYA	2
   2368 #define	ONLYB	1
   2369 #define	BOTH	3
   2370 
   2371 static int
   2372 proc_compare(struct proc *p1, struct proc *p2)
   2373 {
   2374 
   2375 	if (p1 == NULL)
   2376 		return (1);
   2377 	/*
   2378 	 * see if at least one of them is runnable
   2379 	 */
   2380 	switch (TESTAB(ISRUN(p1), ISRUN(p2))) {
   2381 	case ONLYA:
   2382 		return (0);
   2383 	case ONLYB:
   2384 		return (1);
   2385 	case BOTH:
   2386 		/*
   2387 		 * tie - favor one with highest recent CPU utilization
   2388 		 */
   2389 		if (p2->p_estcpu > p1->p_estcpu)
   2390 			return (1);
   2391 		if (p1->p_estcpu > p2->p_estcpu)
   2392 			return (0);
   2393 		return (p2->p_pid > p1->p_pid);	/* tie - return highest pid */
   2394 	}
   2395 	/*
   2396  	 * weed out zombies
   2397 	 */
   2398 	switch (TESTAB(P_ZOMBIE(p1), P_ZOMBIE(p2))) {
   2399 	case ONLYA:
   2400 		return (1);
   2401 	case ONLYB:
   2402 		return (0);
   2403 	case BOTH:
   2404 		return (p2->p_pid > p1->p_pid);	/* tie - return highest pid */
   2405 	}
   2406 #if 0 /* XXX NJWLWP */
   2407 	/*
   2408 	 * pick the one with the smallest sleep time
   2409 	 */
   2410 	if (p2->p_slptime > p1->p_slptime)
   2411 		return (0);
   2412 	if (p1->p_slptime > p2->p_slptime)
   2413 		return (1);
   2414 	/*
   2415 	 * favor one sleeping in a non-interruptible sleep
   2416 	 */
   2417 	if (p1->p_flag & P_SINTR && (p2->p_flag & P_SINTR) == 0)
   2418 		return (1);
   2419 	if (p2->p_flag & P_SINTR && (p1->p_flag & P_SINTR) == 0)
   2420 		return (0);
   2421 #endif
   2422 	return (p2->p_pid > p1->p_pid);		/* tie - return highest pid */
   2423 }
   2424 
   2425 /*
   2426  * Output char to tty; console putchar style.
   2427  * Can be called with tty lock held through kprintf() machinery..
   2428  */
   2429 int
   2430 tputchar(int c, int flags, struct tty *tp)
   2431 {
   2432 	int s, r = 0;
   2433 
   2434 	s = spltty();
   2435 	if ((flags & NOLOCK) == 0)
   2436 		simple_lock(&tp->t_slock);
   2437 	if (!CONNECTED(tp)) {
   2438 		r = -1;
   2439 		goto out;
   2440 	}
   2441 	if (c == '\n')
   2442 		(void)ttyoutput('\r', tp);
   2443 	(void)ttyoutput(c, tp);
   2444 	ttstart(tp);
   2445 out:
   2446 	if ((flags & NOLOCK) == 0)
   2447 		TTY_UNLOCK(tp);
   2448 	splx(s);
   2449 	return (r);
   2450 }
   2451 
   2452 /*
   2453  * Sleep on chan, returning ERESTART if tty changed while we napped and
   2454  * returning any errors (e.g. EINTR/ETIMEDOUT) reported by tsleep.  If
   2455  * the tty is revoked, restarting a pending call will redo validation done
   2456  * at the start of the call.
   2457  *
   2458  * Must be called with the tty slock held.
   2459  */
   2460 int
   2461 ttysleep(struct tty *tp, void *chan, int pri, const char *wmesg, int timo)
   2462 {
   2463 	int	error;
   2464 	short	gen;
   2465 
   2466 	gen = tp->t_gen;
   2467 	if ((error = ltsleep(chan, pri, wmesg, timo, &tp->t_slock)) != 0)
   2468 		return (error);
   2469 	return (tp->t_gen == gen ? 0 : ERESTART);
   2470 }
   2471 
   2472 /*
   2473  * Initialise the global tty list.
   2474  */
   2475 void
   2476 tty_init(void)
   2477 {
   2478 
   2479 	ttyldisc_init();
   2480 
   2481 	TAILQ_INIT(&ttylist);
   2482 	tty_count = 0;
   2483 
   2484 	pool_init(&tty_pool, sizeof(struct tty), 0, 0, 0, "ttypl",
   2485 	    &pool_allocator_nointr);
   2486 }
   2487 
   2488 /*
   2489  * Attach a tty to the tty list.
   2490  *
   2491  * This should be called ONLY once per real tty (including pty's).
   2492  * eg, on the sparc, the keyboard and mouse have struct tty's that are
   2493  * distinctly NOT usable as tty's, and thus should not be attached to
   2494  * the ttylist.  This is why this call is not done from ttymalloc().
   2495  *
   2496  * Device drivers should attach tty's at a similar time that they are
   2497  * ttymalloc()'ed, or, for the case of statically allocated struct tty's
   2498  * either in the attach or (first) open routine.
   2499  */
   2500 void
   2501 tty_attach(struct tty *tp)
   2502 {
   2503 
   2504 	simple_lock(&ttylist_slock);
   2505 	TAILQ_INSERT_TAIL(&ttylist, tp, tty_link);
   2506 	++tty_count;
   2507 	simple_unlock(&ttylist_slock);
   2508 }
   2509 
   2510 /*
   2511  * Remove a tty from the tty list.
   2512  */
   2513 void
   2514 tty_detach(struct tty *tp)
   2515 {
   2516 
   2517 	simple_lock(&ttylist_slock);
   2518 	--tty_count;
   2519 #ifdef DIAGNOSTIC
   2520 	if (tty_count < 0)
   2521 		panic("tty_detach: tty_count < 0");
   2522 #endif
   2523 	TAILQ_REMOVE(&ttylist, tp, tty_link);
   2524 	simple_unlock(&ttylist_slock);
   2525 }
   2526 
   2527 /*
   2528  * Allocate a tty structure and its associated buffers.
   2529  */
   2530 struct tty *
   2531 ttymalloc(void)
   2532 {
   2533 	struct tty	*tp;
   2534 
   2535 	tp = pool_get(&tty_pool, PR_WAITOK);
   2536 	memset(tp, 0, sizeof(*tp));
   2537 	simple_lock_init(&tp->t_slock);
   2538 	callout_init(&tp->t_rstrt_ch);
   2539 	/* XXX: default to 1024 chars for now */
   2540 	clalloc(&tp->t_rawq, 1024, 1);
   2541 	clalloc(&tp->t_canq, 1024, 1);
   2542 	/* output queue doesn't need quoting */
   2543 	clalloc(&tp->t_outq, 1024, 0);
   2544 	/* Set default line discipline. */
   2545 	tp->t_linesw = linesw[0];
   2546 	return (tp);
   2547 }
   2548 
   2549 /*
   2550  * Free a tty structure and its buffers.
   2551  *
   2552  * Be sure to call tty_detach() for any tty that has been
   2553  * tty_attach()ed.
   2554  */
   2555 void
   2556 ttyfree(struct tty *tp)
   2557 {
   2558 
   2559 	callout_stop(&tp->t_rstrt_ch);
   2560 	clfree(&tp->t_rawq);
   2561 	clfree(&tp->t_canq);
   2562 	clfree(&tp->t_outq);
   2563 	pool_put(&tty_pool, tp);
   2564 }
   2565 
   2566 /*
   2567  * ttyprintf_nolock: send a message to a specific tty, without locking.
   2568  *
   2569  * => should be used only by tty driver or anything that knows the
   2570  *    underlying tty will not be revoked(2)'d away.  [otherwise,
   2571  *    use tprintf]
   2572  */
   2573 static void
   2574 ttyprintf_nolock(struct tty *tp, const char *fmt, ...)
   2575 {
   2576 	va_list ap;
   2577 
   2578 	/* No mutex needed; going to process TTY. */
   2579 	va_start(ap, fmt);
   2580 	kprintf(fmt, TOTTY|NOLOCK, tp, NULL, ap);
   2581 	va_end(ap);
   2582 }
   2583