Home | History | Annotate | Line # | Download | only in kern
tty.c revision 1.164
      1 /*	$NetBSD: tty.c,v 1.164 2004/03/09 05:30:24 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.164 2004/03/09 05:30:24 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 	int s;
    681 
    682 	/*
    683 	 * Unless the receiver is enabled, drop incoming data.
    684 	 */
    685 	if (!ISSET(tp->t_cflag, CREAD))
    686 		return (0);
    687 
    688 	s = spltty();
    689 	TTY_LOCK(tp);
    690 	error = ttyinput_wlock(c, tp);
    691 	TTY_UNLOCK(tp);
    692 	splx(s);
    693 	return (error);
    694 }
    695 
    696 /*
    697  * Output a single character on a tty, doing output processing
    698  * as needed (expanding tabs, newline processing, etc.).
    699  * Returns < 0 if succeeds, otherwise returns char to resend.
    700  * Must be recursive.
    701  * Call with tty slock held.
    702  */
    703 int
    704 ttyoutput(int c, struct tty *tp)
    705 {
    706 	long	oflag;
    707 	int	col, notout, s;
    708 
    709 	oflag = tp->t_oflag;
    710 	if (!ISSET(oflag, OPOST)) {
    711 		tk_nout++;
    712 		tp->t_outcc++;
    713 		if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
    714 			return (c);
    715 		return (-1);
    716 	}
    717 	/*
    718 	 * Do tab expansion if OXTABS is set.  Special case if we do external
    719 	 * processing, we don't do the tab expansion because we'll probably
    720 	 * get it wrong.  If tab expansion needs to be done, let it happen
    721 	 * externally.
    722 	 */
    723 	CLR(c, ~TTY_CHARMASK);
    724 	if (c == '\t' &&
    725 	    ISSET(oflag, OXTABS) && !ISSET(tp->t_lflag, EXTPROC)) {
    726 		c = 8 - (tp->t_column & 7);
    727 		if (ISSET(tp->t_lflag, FLUSHO)) {
    728 			notout = 0;
    729 		} else {
    730 			s = spltty();		/* Don't interrupt tabs. */
    731 			notout = b_to_q("        ", c, &tp->t_outq);
    732 			c -= notout;
    733 			tk_nout += c;
    734 			tp->t_outcc += c;
    735 			splx(s);
    736 		}
    737 		tp->t_column += c;
    738 		return (notout ? '\t' : -1);
    739 	}
    740 	if (c == CEOT && ISSET(oflag, ONOEOT))
    741 		return (-1);
    742 
    743 	/*
    744 	 * Newline translation: if ONLCR is set,
    745 	 * translate newline into "\r\n".
    746 	 */
    747 	if (c == '\n' && ISSET(tp->t_oflag, ONLCR)) {
    748 		tk_nout++;
    749 		tp->t_outcc++;
    750 		if (!ISSET(tp->t_lflag, FLUSHO) && putc('\r', &tp->t_outq))
    751 			return (c);
    752 	}
    753 	/* If OCRNL is set, translate "\r" into "\n". */
    754 	else if (c == '\r' && ISSET(tp->t_oflag, OCRNL))
    755 		c = '\n';
    756 	/* If ONOCR is set, don't transmit CRs when on column 0. */
    757 	else if (c == '\r' && ISSET(tp->t_oflag, ONOCR) && tp->t_column == 0)
    758 		return (-1);
    759 
    760 	tk_nout++;
    761 	tp->t_outcc++;
    762 	if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
    763 		return (c);
    764 
    765 	col = tp->t_column;
    766 	switch (CCLASS(c)) {
    767 	case BACKSPACE:
    768 		if (col > 0)
    769 			--col;
    770 		break;
    771 	case CONTROL:
    772 		break;
    773 	case NEWLINE:
    774 		if (ISSET(tp->t_oflag, ONLCR | ONLRET))
    775 			col = 0;
    776 		break;
    777 	case RETURN:
    778 		col = 0;
    779 		break;
    780 	case ORDINARY:
    781 		++col;
    782 		break;
    783 	case TAB:
    784 		col = (col + 8) & ~7;
    785 		break;
    786 	}
    787 	tp->t_column = col;
    788 	return (-1);
    789 }
    790 
    791 /*
    792  * Ioctls for all tty devices.  Called after line-discipline specific ioctl
    793  * has been called to do discipline-specific functions and/or reject any
    794  * of these ioctl commands.
    795  */
    796 /* ARGSUSED */
    797 int
    798 ttioctl(struct tty *tp, u_long cmd, caddr_t data, int flag, struct proc *p)
    799 {
    800 	extern struct tty *constty;	/* Temporary virtual console. */
    801 	struct linesw	*lp;
    802 	int		s, error;
    803 	struct nameidata nd;
    804 
    805 	/* If the ioctl involves modification, hang if in the background. */
    806 	switch (cmd) {
    807 	case  TIOCFLUSH:
    808 	case  TIOCDRAIN:
    809 	case  TIOCSBRK:
    810 	case  TIOCCBRK:
    811 	case  TIOCSTART:
    812 	case  TIOCSETA:
    813 	case  TIOCSETD:
    814 	case  TIOCSLINED:
    815 	case  TIOCSETAF:
    816 	case  TIOCSETAW:
    817 #ifdef notdef
    818 	case  TIOCSPGRP:
    819 	case  FIOSETOWN:
    820 #endif
    821 	case  TIOCSTAT:
    822 	case  TIOCSTI:
    823 	case  TIOCSWINSZ:
    824 #ifdef COMPAT_OLDTTY
    825 	case  TIOCLBIC:
    826 	case  TIOCLBIS:
    827 	case  TIOCLSET:
    828 	case  TIOCSETC:
    829 	case OTIOCSETD:
    830 	case  TIOCSETN:
    831 	case  TIOCSETP:
    832 	case  TIOCSLTC:
    833 #endif
    834 		while (isbackground(curproc, tp) &&
    835 		    p->p_pgrp->pg_jobc && (p->p_flag & P_PPWAIT) == 0 &&
    836 		    !sigismasked(p, SIGTTOU)) {
    837 			pgsignal(p->p_pgrp, SIGTTOU, 1);
    838 			s = spltty();
    839 			TTY_LOCK(tp);
    840 			error = ttysleep(tp, &lbolt,
    841 					 TTOPRI | PCATCH | PNORELOCK, ttybg, 0);
    842 			splx(s);
    843 			if (error) {
    844 				return (error);
    845 			}
    846 		}
    847 		break;
    848 	}
    849 
    850 	switch (cmd) {			/* Process the ioctl. */
    851 	case FIOASYNC:			/* set/clear async i/o */
    852 		s = spltty();
    853 		TTY_LOCK(tp);
    854 		if (*(int *)data)
    855 			SET(tp->t_state, TS_ASYNC);
    856 		else
    857 			CLR(tp->t_state, TS_ASYNC);
    858 		TTY_UNLOCK(tp);
    859 		splx(s);
    860 		break;
    861 	case FIONBIO:			/* set/clear non-blocking i/o */
    862 		break;			/* XXX: delete. */
    863 	case FIONREAD:			/* get # bytes to read */
    864 		s = spltty();
    865 		TTY_LOCK(tp);
    866 		*(int *)data = ttnread(tp);
    867 		TTY_UNLOCK(tp);
    868 		splx(s);
    869 		break;
    870 	case TIOCEXCL:			/* set exclusive use of tty */
    871 		s = spltty();
    872 		TTY_LOCK(tp);
    873 		SET(tp->t_state, TS_XCLUDE);
    874 		splx(s);
    875 		TTY_UNLOCK(tp);
    876 		break;
    877 	case TIOCFLUSH: {		/* flush buffers */
    878 		int flags = *(int *)data;
    879 
    880 		if (flags == 0)
    881 			flags = FREAD | FWRITE;
    882 		else
    883 			flags &= FREAD | FWRITE;
    884 		s = spltty();
    885 		TTY_LOCK(tp);
    886 		ttyflush(tp, flags);
    887 		TTY_UNLOCK(tp);
    888 		splx(s);
    889 		break;
    890 	}
    891 	case TIOCCONS:			/* become virtual console */
    892 		if (*(int *)data) {
    893 			if (constty && constty != tp &&
    894 			    ISSET(constty->t_state, TS_CARR_ON | TS_ISOPEN) ==
    895 			    (TS_CARR_ON | TS_ISOPEN))
    896 				return EBUSY;
    897 
    898 			NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE,
    899 			    "/dev/console", p);
    900 			if ((error = namei(&nd)) != 0)
    901 				return error;
    902 			error = VOP_ACCESS(nd.ni_vp, VREAD, p->p_ucred, p);
    903 			vput(nd.ni_vp);
    904 			if (error)
    905 				return error;
    906 
    907 			constty = tp;
    908 		} else if (tp == constty)
    909 			constty = NULL;
    910 		break;
    911 	case TIOCDRAIN:			/* wait till output drained */
    912 		if ((error = ttywait(tp)) != 0)
    913 			return (error);
    914 		break;
    915 	case TIOCGETA: {		/* get termios struct */
    916 		struct termios *t = (struct termios *)data;
    917 
    918 		memcpy(t, &tp->t_termios, sizeof(struct termios));
    919 		break;
    920 	}
    921 	case TIOCGETD:			/* get line discipline */
    922 		*(int *)data = tp->t_linesw->l_no;
    923 		break;
    924 	case TIOCGLINED:
    925 		(void)strncpy((char *)data, tp->t_linesw->l_name,
    926 		    TTLINEDNAMELEN - 1);
    927 		break;
    928 	case TIOCGWINSZ:		/* get window size */
    929 		*(struct winsize *)data = tp->t_winsize;
    930 		break;
    931 	case FIOGETOWN:
    932 		if (!isctty(p, tp))
    933 			return (ENOTTY);
    934 		*(int *)data = tp->t_pgrp ? -tp->t_pgrp->pg_id : 0;
    935 		break;
    936 	case TIOCGPGRP:			/* get pgrp of tty */
    937 		if (!isctty(p, tp))
    938 			return (ENOTTY);
    939 		*(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PGID;
    940 		break;
    941 	case TIOCGSID:			/* get sid of tty */
    942 		if (!isctty(p, tp))
    943 			return (ENOTTY);
    944 		*(int *)data = tp->t_session->s_sid;
    945 		break;
    946 #ifdef TIOCHPCL
    947 	case TIOCHPCL:			/* hang up on last close */
    948 		s = spltty();
    949 		TTY_LOCK(tp);
    950 		SET(tp->t_cflag, HUPCL);
    951 		TTY_UNLOCK(tp);
    952 		splx(s);
    953 		break;
    954 #endif
    955 	case TIOCNXCL:			/* reset exclusive use of tty */
    956 		s = spltty();
    957 		TTY_LOCK(tp);
    958 		CLR(tp->t_state, TS_XCLUDE);
    959 		TTY_UNLOCK(tp);
    960 		splx(s);
    961 		break;
    962 	case TIOCOUTQ:			/* output queue size */
    963 		*(int *)data = tp->t_outq.c_cc;
    964 		break;
    965 	case TIOCSETA:			/* set termios struct */
    966 	case TIOCSETAW:			/* drain output, set */
    967 	case TIOCSETAF: {		/* drn out, fls in, set */
    968 		struct termios *t = (struct termios *)data;
    969 
    970 		if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
    971 			if ((error = ttywait(tp)) != 0)
    972 				return (error);
    973 
    974 			if (cmd == TIOCSETAF) {
    975 				s = spltty();
    976 				TTY_LOCK(tp);
    977 				ttyflush(tp, FREAD);
    978 				TTY_UNLOCK(tp);
    979 				splx(s);
    980 			}
    981 		}
    982 
    983 		s = spltty();
    984 		/*
    985 		 * XXXSMP - some drivers call back on us from t_param(), so
    986 		 *	    don't take the tty spin lock here.
    987 		 *	    require t_param() to unlock upon callback?
    988 		 */
    989 		/* wanted here: TTY_LOCK(tp); */
    990 		if (!ISSET(t->c_cflag, CIGNORE)) {
    991 			/*
    992 			 * Set device hardware.
    993 			 */
    994 			if (tp->t_param && (error = (*tp->t_param)(tp, t))) {
    995 				/* wanted here: TTY_UNLOCK(tp); */
    996 				splx(s);
    997 				return (error);
    998 			} else {
    999 				tp->t_cflag = t->c_cflag;
   1000 				tp->t_ispeed = t->c_ispeed;
   1001 				tp->t_ospeed = t->c_ospeed;
   1002 				if (t->c_ospeed == 0 && tp->t_session &&
   1003 				    tp->t_session->s_leader)
   1004 					psignal(tp->t_session->s_leader,
   1005 					    SIGHUP);
   1006 			}
   1007 			ttsetwater(tp);
   1008 		}
   1009 
   1010 		/* delayed lock acquiring */TTY_LOCK(tp);
   1011 		if (cmd != TIOCSETAF) {
   1012 			if (ISSET(t->c_lflag, ICANON) !=
   1013 			    ISSET(tp->t_lflag, ICANON)) {
   1014 				if (ISSET(t->c_lflag, ICANON)) {
   1015 					SET(tp->t_lflag, PENDIN);
   1016 					ttwakeup(tp);
   1017 				} else {
   1018 					struct clist tq;
   1019 
   1020 					catq(&tp->t_rawq, &tp->t_canq);
   1021 					tq = tp->t_rawq;
   1022 					tp->t_rawq = tp->t_canq;
   1023 					tp->t_canq = tq;
   1024 					CLR(tp->t_lflag, PENDIN);
   1025 				}
   1026 			}
   1027 		}
   1028 		tp->t_iflag = t->c_iflag;
   1029 		tp->t_oflag = t->c_oflag;
   1030 		/*
   1031 		 * Make the EXTPROC bit read only.
   1032 		 */
   1033 		if (ISSET(tp->t_lflag, EXTPROC))
   1034 			SET(t->c_lflag, EXTPROC);
   1035 		else
   1036 			CLR(t->c_lflag, EXTPROC);
   1037 		tp->t_lflag = t->c_lflag | ISSET(tp->t_lflag, PENDIN);
   1038 		memcpy(tp->t_cc, t->c_cc, sizeof(t->c_cc));
   1039 		TTY_UNLOCK(tp);
   1040 		splx(s);
   1041 		break;
   1042 	}
   1043 	case TIOCSETD: {		/* set line discipline */
   1044 		int t = *(int *)data;
   1045 
   1046 		if (t < 0)
   1047 			return (EINVAL);
   1048 		if (t >= nlinesw)
   1049 			return (ENXIO);
   1050 		lp = linesw[t];
   1051 		goto setldisc;
   1052 	}
   1053 	case TIOCSLINED: {		/* set line discipline */
   1054 		char *name = (char *)data;
   1055 		dev_t device;
   1056 
   1057 		/* Null terminate to prevent buffer overflow */
   1058 		name[TTLINEDNAMELEN - 1] = '\0';
   1059 		lp = ttyldisc_lookup(name);
   1060 
   1061  setldisc:
   1062 		if (lp == NULL)
   1063 			return (ENXIO);
   1064 
   1065 		if (lp != tp->t_linesw) {
   1066 			device = tp->t_dev;
   1067 			s = spltty();
   1068 			(*tp->t_linesw->l_close)(tp, flag);
   1069 			error = (*lp->l_open)(device, tp);
   1070 			if (error) {
   1071 				(void)(*tp->t_linesw->l_open)(device, tp);
   1072 				splx(s);
   1073 				return (error);
   1074 			}
   1075 			tp->t_linesw = lp;
   1076 			splx(s);
   1077 		}
   1078 		break;
   1079 	}
   1080 	case TIOCSTART:			/* start output, like ^Q */
   1081 		s = spltty();
   1082 		TTY_LOCK(tp);
   1083 		if (ISSET(tp->t_state, TS_TTSTOP) ||
   1084 		    ISSET(tp->t_lflag, FLUSHO)) {
   1085 			CLR(tp->t_lflag, FLUSHO);
   1086 			CLR(tp->t_state, TS_TTSTOP);
   1087 			ttstart(tp);
   1088 		}
   1089 		TTY_UNLOCK(tp);
   1090 		splx(s);
   1091 		break;
   1092 	case TIOCSTI:			/* simulate terminal input */
   1093 		if (p->p_ucred->cr_uid && (flag & FREAD) == 0)
   1094 			return (EPERM);
   1095 		if (p->p_ucred->cr_uid && !isctty(p, tp))
   1096 			return (EACCES);
   1097 		(*tp->t_linesw->l_rint)(*(u_char *)data, tp);
   1098 		break;
   1099 	case TIOCSTOP:			/* stop output, like ^S */
   1100 	{
   1101 		const struct cdevsw *cdev;
   1102 		s = spltty();
   1103 		TTY_LOCK(tp);
   1104 		if (!ISSET(tp->t_state, TS_TTSTOP)) {
   1105 			SET(tp->t_state, TS_TTSTOP);
   1106 			cdev = cdevsw_lookup(tp->t_dev);
   1107 			if (cdev != NULL)
   1108 				(*cdev->d_stop)(tp, 0);
   1109 		}
   1110 		TTY_UNLOCK(tp);
   1111 		splx(s);
   1112 		break;
   1113 	}
   1114 	case TIOCSCTTY:			/* become controlling tty */
   1115 		/* Session ctty vnode pointer set in vnode layer. */
   1116 		if (!SESS_LEADER(p) ||
   1117 		    ((p->p_session->s_ttyvp || tp->t_session) &&
   1118 		    (tp->t_session != p->p_session)))
   1119 			return (EPERM);
   1120 
   1121 		/*
   1122 		 * `p_session' acquires a reference.
   1123 		 * But note that if `t_session' is set at this point,
   1124 		 * it must equal `p_session', in which case the session
   1125 		 * already has the correct reference count.
   1126 		 */
   1127 		if (tp->t_session == NULL)
   1128 			SESSHOLD(p->p_session);
   1129 
   1130 		tp->t_session = p->p_session;
   1131 		tp->t_pgrp = p->p_pgrp;
   1132 		p->p_session->s_ttyp = tp;
   1133 		p->p_flag |= P_CONTROLT;
   1134 		break;
   1135 	case FIOSETOWN: {		/* set pgrp of tty */
   1136 		pid_t pgid = *(int *)data;
   1137 		struct pgrp *pgrp;
   1138 
   1139 		if (!isctty(p, tp))
   1140 			return (ENOTTY);
   1141 
   1142 		if (pgid < 0)
   1143 			pgrp = pgfind(-pgid);
   1144 		else {
   1145 			struct proc *p1 = pfind(pgid);
   1146 			if (!p1)
   1147 				return (ESRCH);
   1148 			pgrp = p1->p_pgrp;
   1149 		}
   1150 
   1151 		if (pgrp == NULL)
   1152 			return (EINVAL);
   1153 		else if (pgrp->pg_session != p->p_session)
   1154 			return (EPERM);
   1155 		tp->t_pgrp = pgrp;
   1156 		break;
   1157 	}
   1158 	case TIOCSPGRP: {		/* set pgrp of tty */
   1159 		struct pgrp *pgrp = pgfind(*(int *)data);
   1160 
   1161 		if (!isctty(p, tp))
   1162 			return (ENOTTY);
   1163 		else if (pgrp == NULL)
   1164 			return (EINVAL);
   1165 		else if (pgrp->pg_session != p->p_session)
   1166 			return (EPERM);
   1167 		tp->t_pgrp = pgrp;
   1168 		break;
   1169 	}
   1170 	case TIOCSTAT:			/* get load avg stats */
   1171 		s = spltty();
   1172 		TTY_LOCK(tp);
   1173 		ttyinfo(tp);
   1174 		TTY_UNLOCK(tp);
   1175 		splx(s);
   1176 		break;
   1177 	case TIOCSWINSZ:		/* set window size */
   1178 		if (memcmp((caddr_t)&tp->t_winsize, data,
   1179 		    sizeof(struct winsize))) {
   1180 			tp->t_winsize = *(struct winsize *)data;
   1181 			pgsignal(tp->t_pgrp, SIGWINCH, 1);
   1182 		}
   1183 		break;
   1184 	default:
   1185 #ifdef COMPAT_OLDTTY
   1186 		return (ttcompat(tp, cmd, data, flag, p));
   1187 #else
   1188 		return (EPASSTHROUGH);
   1189 #endif
   1190 	}
   1191 	return (0);
   1192 }
   1193 
   1194 int
   1195 ttpoll(struct tty *tp, int events, struct proc *p)
   1196 {
   1197 	int	revents, s;
   1198 
   1199 	revents = 0;
   1200 	s = spltty();
   1201 	TTY_LOCK(tp);
   1202 	if (events & (POLLIN | POLLRDNORM))
   1203 		if (ttnread(tp) > 0)
   1204 			revents |= events & (POLLIN | POLLRDNORM);
   1205 
   1206 	if (events & (POLLOUT | POLLWRNORM))
   1207 		if (tp->t_outq.c_cc <= tp->t_lowat)
   1208 			revents |= events & (POLLOUT | POLLWRNORM);
   1209 
   1210 	if (events & POLLHUP)
   1211 		if (!CONNECTED(tp))
   1212 			revents |= POLLHUP;
   1213 
   1214 	if (revents == 0) {
   1215 		if (events & (POLLIN | POLLHUP | POLLRDNORM))
   1216 			selrecord(p, &tp->t_rsel);
   1217 
   1218 		if (events & (POLLOUT | POLLWRNORM))
   1219 			selrecord(p, &tp->t_wsel);
   1220 	}
   1221 
   1222 	TTY_UNLOCK(tp);
   1223 	splx(s);
   1224 	return (revents);
   1225 }
   1226 
   1227 static void
   1228 filt_ttyrdetach(struct knote *kn)
   1229 {
   1230 	struct tty	*tp;
   1231 	int		s;
   1232 
   1233 	tp = kn->kn_hook;
   1234 	s = spltty();
   1235 	SLIST_REMOVE(&tp->t_rsel.sel_klist, kn, knote, kn_selnext);
   1236 	splx(s);
   1237 }
   1238 
   1239 static int
   1240 filt_ttyread(struct knote *kn, long hint)
   1241 {
   1242 	struct tty	*tp;
   1243 	int		s;
   1244 
   1245 	tp = kn->kn_hook;
   1246 	s = spltty();
   1247 	if ((hint & NOTE_SUBMIT) == 0)
   1248 		TTY_LOCK(tp);
   1249 	kn->kn_data = ttnread(tp);
   1250 	if ((hint & NOTE_SUBMIT) == 0)
   1251 		TTY_UNLOCK(tp);
   1252 	splx(s);
   1253 	return (kn->kn_data > 0);
   1254 }
   1255 
   1256 static void
   1257 filt_ttywdetach(struct knote *kn)
   1258 {
   1259 	struct tty	*tp;
   1260 	int		s;
   1261 
   1262 	tp = kn->kn_hook;
   1263 	s = spltty();
   1264 	TTY_LOCK(tp);
   1265 	SLIST_REMOVE(&tp->t_wsel.sel_klist, kn, knote, kn_selnext);
   1266 	TTY_UNLOCK(tp);
   1267 	splx(s);
   1268 }
   1269 
   1270 static int
   1271 filt_ttywrite(struct knote *kn, long hint)
   1272 {
   1273 	struct tty	*tp;
   1274 	int		canwrite, s;
   1275 
   1276 	tp = kn->kn_hook;
   1277 	s = spltty();
   1278 	if ((hint & NOTE_SUBMIT) == 0)
   1279 		TTY_LOCK(tp);
   1280 	kn->kn_data = tp->t_outq.c_cn - tp->t_outq.c_cc;
   1281 	canwrite = (tp->t_outq.c_cc <= tp->t_lowat) && CONNECTED(tp);
   1282 	if ((hint & NOTE_SUBMIT) == 0)
   1283 		TTY_UNLOCK(tp);
   1284 	splx(s);
   1285 	return (canwrite);
   1286 }
   1287 
   1288 static const struct filterops ttyread_filtops =
   1289 	{ 1, NULL, filt_ttyrdetach, filt_ttyread };
   1290 static const struct filterops ttywrite_filtops =
   1291 	{ 1, NULL, filt_ttywdetach, filt_ttywrite };
   1292 
   1293 int
   1294 ttykqfilter(dev_t dev, struct knote *kn)
   1295 {
   1296 	struct tty	*tp;
   1297 	struct klist	*klist;
   1298 	int		s;
   1299 	const struct cdevsw	*cdev;
   1300 
   1301         if (((cdev = cdevsw_lookup(dev)) == NULL) ||
   1302 	    (cdev->d_tty == NULL) ||
   1303 	    ((tp = (*cdev->d_tty)(dev)) == NULL))
   1304 		return (ENXIO);
   1305 
   1306 	switch (kn->kn_filter) {
   1307 	case EVFILT_READ:
   1308 		klist = &tp->t_rsel.sel_klist;
   1309 		kn->kn_fop = &ttyread_filtops;
   1310 		break;
   1311 	case EVFILT_WRITE:
   1312 		klist = &tp->t_wsel.sel_klist;
   1313 		kn->kn_fop = &ttywrite_filtops;
   1314 		break;
   1315 	default:
   1316 		return (1);
   1317 	}
   1318 
   1319 	kn->kn_hook = tp;
   1320 
   1321 	s = spltty();
   1322 	TTY_LOCK(tp);
   1323 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
   1324 	TTY_UNLOCK(tp);
   1325 	splx(s);
   1326 
   1327 	return (0);
   1328 }
   1329 
   1330 /*
   1331  * Find the number of chars ready to be read from this tty.
   1332  * Call at spltty() and with the tty slock held.
   1333  */
   1334 static int
   1335 ttnread(struct tty *tp)
   1336 {
   1337 	int	nread;
   1338 
   1339 	if (ISSET(tp->t_lflag, PENDIN))
   1340 		ttypend(tp);
   1341 	nread = tp->t_canq.c_cc;
   1342 	if (!ISSET(tp->t_lflag, ICANON)) {
   1343 		nread += tp->t_rawq.c_cc;
   1344 		if (nread < tp->t_cc[VMIN] && !tp->t_cc[VTIME])
   1345 			nread = 0;
   1346 	}
   1347 	return (nread);
   1348 }
   1349 
   1350 /*
   1351  * Wait for output to drain.
   1352  */
   1353 int
   1354 ttywait(struct tty *tp)
   1355 {
   1356 	int	error, s;
   1357 
   1358 	error = 0;
   1359 	s = spltty();
   1360 	TTY_LOCK(tp);
   1361 	while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
   1362 	    CONNECTED(tp) && tp->t_oproc) {
   1363 		(*tp->t_oproc)(tp);
   1364 		SET(tp->t_state, TS_ASLEEP);
   1365 		error = ttysleep(tp, &tp->t_outq, TTOPRI | PCATCH, ttyout, 0);
   1366 		if (error)
   1367 			break;
   1368 	}
   1369 	TTY_UNLOCK(tp);
   1370 	splx(s);
   1371 	return (error);
   1372 }
   1373 
   1374 /*
   1375  * Flush if successfully wait.
   1376  */
   1377 int
   1378 ttywflush(struct tty *tp)
   1379 {
   1380 	int	error;
   1381 	int	s;
   1382 
   1383 	if ((error = ttywait(tp)) == 0) {
   1384 		s = spltty();
   1385 		TTY_LOCK(tp);
   1386 		ttyflush(tp, FREAD);
   1387 		TTY_UNLOCK(tp);
   1388 		splx(s);
   1389 	}
   1390 	return (error);
   1391 }
   1392 
   1393 /*
   1394  * Flush tty read and/or write queues, notifying anyone waiting.
   1395  * Call at spltty() and with the tty slock held.
   1396  */
   1397 void
   1398 ttyflush(struct tty *tp, int rw)
   1399 {
   1400 	const struct cdevsw *cdev;
   1401 
   1402 	if (rw & FREAD) {
   1403 		FLUSHQ(&tp->t_canq);
   1404 		FLUSHQ(&tp->t_rawq);
   1405 		tp->t_rocount = 0;
   1406 		tp->t_rocol = 0;
   1407 		CLR(tp->t_state, TS_LOCAL);
   1408 		ttwakeup(tp);
   1409 	}
   1410 	if (rw & FWRITE) {
   1411 		CLR(tp->t_state, TS_TTSTOP);
   1412 		cdev = cdevsw_lookup(tp->t_dev);
   1413 		if (cdev != NULL)
   1414 			(*cdev->d_stop)(tp, rw);
   1415 		FLUSHQ(&tp->t_outq);
   1416 		wakeup((caddr_t)&tp->t_outq);
   1417 		selnotify(&tp->t_wsel, NOTE_SUBMIT);
   1418 	}
   1419 }
   1420 
   1421 /*
   1422  * Copy in the default termios characters.
   1423  */
   1424 void
   1425 ttychars(struct tty *tp)
   1426 {
   1427 
   1428 	memcpy(tp->t_cc, ttydefchars, sizeof(ttydefchars));
   1429 }
   1430 
   1431 /*
   1432  * Send stop character on input overflow.
   1433  * Call at spltty() and with the tty slock held.
   1434  */
   1435 static void
   1436 ttyblock(struct tty *tp)
   1437 {
   1438 	int	total;
   1439 
   1440 	total = tp->t_rawq.c_cc + tp->t_canq.c_cc;
   1441 	if (tp->t_rawq.c_cc > TTYHOG) {
   1442 		ttyflush(tp, FREAD | FWRITE);
   1443 		CLR(tp->t_state, TS_TBLOCK);
   1444 	}
   1445 	/*
   1446 	 * Block further input iff: current input > threshold
   1447 	 * AND input is available to user program.
   1448 	 */
   1449 	if (total >= TTYHOG / 2 &&
   1450 	    !ISSET(tp->t_state, TS_TBLOCK) &&
   1451 	    (!ISSET(tp->t_lflag, ICANON) || tp->t_canq.c_cc > 0)) {
   1452 		if (ISSET(tp->t_iflag, IXOFF) &&
   1453 		    tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
   1454 		    putc(tp->t_cc[VSTOP], &tp->t_outq) == 0) {
   1455 			SET(tp->t_state, TS_TBLOCK);
   1456 			ttstart(tp);
   1457 		}
   1458 		/* Try to block remote output via hardware flow control. */
   1459 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
   1460 		    (*tp->t_hwiflow)(tp, 1) != 0)
   1461 			SET(tp->t_state, TS_TBLOCK);
   1462 	}
   1463 }
   1464 
   1465 /*
   1466  * Delayed line discipline output
   1467  */
   1468 void
   1469 ttrstrt(void *tp_arg)
   1470 {
   1471 	struct tty	*tp;
   1472 	int		s;
   1473 
   1474 #ifdef DIAGNOSTIC
   1475 	if (tp_arg == NULL)
   1476 		panic("ttrstrt");
   1477 #endif
   1478 	tp = tp_arg;
   1479 	s = spltty();
   1480 	TTY_LOCK(tp);
   1481 
   1482 	CLR(tp->t_state, TS_TIMEOUT);
   1483 	ttstart(tp); /* XXX - Shouldn't this be tp->l_start(tp)? */
   1484 
   1485 	TTY_UNLOCK(tp);
   1486 	splx(s);
   1487 }
   1488 
   1489 /*
   1490  * start a line discipline
   1491  * Always call at spltty() and with tty slock held?
   1492  */
   1493 int
   1494 ttstart(struct tty *tp)
   1495 {
   1496 
   1497 	if (tp->t_oproc != NULL)	/* XXX: Kludge for pty. */
   1498 		(*tp->t_oproc)(tp);
   1499 	return (0);
   1500 }
   1501 
   1502 /*
   1503  * "close" a line discipline
   1504  */
   1505 int
   1506 ttylclose(struct tty *tp, int flag)
   1507 {
   1508 	int s;
   1509 
   1510 	if (flag & FNONBLOCK) {
   1511 		s = spltty();
   1512 		TTY_LOCK(tp);
   1513 		ttyflush(tp, FREAD | FWRITE);
   1514 		TTY_UNLOCK(tp);
   1515 		splx(s);
   1516 	} else
   1517 		ttywflush(tp);
   1518 	return (0);
   1519 }
   1520 
   1521 /*
   1522  * Handle modem control transition on a tty.
   1523  * Flag indicates new state of carrier.
   1524  * Returns 0 if the line should be turned off, otherwise 1.
   1525  *
   1526  * Must be called at spltty().
   1527  * XXX except that it is often isn't, which should be fixed.
   1528  */
   1529 int
   1530 ttymodem(struct tty *tp, int flag)
   1531 {
   1532 	int s;
   1533 
   1534 	s = spltty();
   1535 	TTY_LOCK(tp);
   1536 	if (flag == 0) {
   1537 		if (ISSET(tp->t_state, TS_CARR_ON)) {
   1538 			/*
   1539 			 * Lost carrier.
   1540 			 */
   1541 			CLR(tp->t_state, TS_CARR_ON);
   1542 			if (ISSET(tp->t_state, TS_ISOPEN) && !CONNECTED(tp)) {
   1543 				if (tp->t_session && tp->t_session->s_leader)
   1544 					psignal(tp->t_session->s_leader,
   1545 					    SIGHUP);
   1546 				ttyflush(tp, FREAD | FWRITE);
   1547 				TTY_UNLOCK(tp);
   1548 				splx(s);
   1549 				return (0);
   1550 			}
   1551 		}
   1552 	} else {
   1553 		if (!ISSET(tp->t_state, TS_CARR_ON)) {
   1554 			/*
   1555 			 * Carrier now on.
   1556 			 */
   1557 			SET(tp->t_state, TS_CARR_ON);
   1558 			ttwakeup(tp);
   1559 		}
   1560 	}
   1561 	TTY_UNLOCK(tp);
   1562 	splx(s);
   1563 	return (1);
   1564 }
   1565 
   1566 /*
   1567  * Default modem control routine (for other line disciplines).
   1568  * Return argument flag, to turn off device on carrier drop.
   1569  *
   1570  * Must be called at spltty().
   1571  * XXX except that it is often isn't, which should be fixed.
   1572  */
   1573 int
   1574 nullmodem(struct tty *tp, int flag)
   1575 {
   1576 	int s;
   1577 
   1578 	s = spltty();
   1579 	TTY_LOCK(tp);
   1580 	if (flag)
   1581 		SET(tp->t_state, TS_CARR_ON);
   1582 	else {
   1583 		CLR(tp->t_state, TS_CARR_ON);
   1584 		if (!CONNECTED(tp)) {
   1585 			if (tp->t_session && tp->t_session->s_leader)
   1586 				psignal(tp->t_session->s_leader, SIGHUP);
   1587 			TTY_UNLOCK(tp);
   1588 			splx(s);
   1589 			return (0);
   1590 		}
   1591 	}
   1592 	TTY_UNLOCK(tp);
   1593 	splx(s);
   1594 	return (1);
   1595 }
   1596 
   1597 /*
   1598  * Reinput pending characters after state switch.
   1599  * Call at spltty() and with the tty slock held.
   1600  */
   1601 void
   1602 ttypend(struct tty *tp)
   1603 {
   1604 	struct clist	tq;
   1605 	int		c;
   1606 
   1607 	CLR(tp->t_lflag, PENDIN);
   1608 	SET(tp->t_state, TS_TYPEN);
   1609 	tq = tp->t_rawq;
   1610 	tp->t_rawq.c_cc = 0;
   1611 	tp->t_rawq.c_cf = tp->t_rawq.c_cl = 0;
   1612 	while ((c = getc(&tq)) >= 0)
   1613 		ttyinput_wlock(c, tp);
   1614 	CLR(tp->t_state, TS_TYPEN);
   1615 }
   1616 
   1617 /*
   1618  * Process a read call on a tty device.
   1619  */
   1620 int
   1621 ttread(struct tty *tp, struct uio *uio, int flag)
   1622 {
   1623 	struct clist	*qp;
   1624 	u_char		*cc;
   1625 	struct proc	*p;
   1626 	int		c, s, first, error, has_stime, last_cc;
   1627 	long		lflag, slp;
   1628 	struct timeval	stime;
   1629 
   1630 	cc = tp->t_cc;
   1631 	p = curproc;
   1632 	error = 0;
   1633 	has_stime = 0;
   1634 	last_cc = 0;
   1635 	slp = 0;
   1636 
   1637  loop:
   1638 	s = spltty();
   1639 	TTY_LOCK(tp);
   1640 	lflag = tp->t_lflag;
   1641 	/*
   1642 	 * take pending input first
   1643 	 */
   1644 	if (ISSET(lflag, PENDIN))
   1645 		ttypend(tp);
   1646 
   1647 	/*
   1648 	 * Hang process if it's in the background.
   1649 	 */
   1650 	if (isbackground(p, tp)) {
   1651 		if (sigismember(&p->p_sigctx.ps_sigignore, SIGTTIN) ||
   1652 		    sigismember(&p->p_sigctx.ps_sigmask, SIGTTIN) ||
   1653 		    p->p_flag & P_PPWAIT || p->p_pgrp->pg_jobc == 0) {
   1654 			TTY_UNLOCK(tp);
   1655 			splx(s);
   1656 			return (EIO);
   1657 		}
   1658 		pgsignal(p->p_pgrp, SIGTTIN, 1);
   1659 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH | PNORELOCK, ttybg, 0);
   1660 		splx(s);
   1661 		if (error)
   1662 			return (error);
   1663 		goto loop;
   1664 	}
   1665 
   1666 	if (!ISSET(lflag, ICANON)) {
   1667 		int m = cc[VMIN];
   1668 		long t = cc[VTIME];
   1669 
   1670 		qp = &tp->t_rawq;
   1671 		/*
   1672 		 * Check each of the four combinations.
   1673 		 * (m > 0 && t == 0) is the normal read case.
   1674 		 * It should be fairly efficient, so we check that and its
   1675 		 * companion case (m == 0 && t == 0) first.
   1676 		 * For the other two cases, we compute the target sleep time
   1677 		 * into slp.
   1678 		 */
   1679 		if (t == 0) {
   1680 			if (qp->c_cc < m)
   1681 				goto sleep;
   1682 			goto read;
   1683 		}
   1684 		t *= hz;		/* time in deca-ticks */
   1685 /*
   1686  * Time difference in deca-ticks, split division to avoid numeric overflow.
   1687  * Ok for hz < ~200kHz
   1688  */
   1689 #define	diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 10 * hz + \
   1690 			 ((t1).tv_usec - (t2).tv_usec) / 100 * hz / 1000)
   1691 		if (m > 0) {
   1692 			if (qp->c_cc <= 0)
   1693 				goto sleep;
   1694 			if (qp->c_cc >= m)
   1695 				goto read;
   1696 			if (!has_stime) {
   1697 				/* first character, start timer */
   1698 				has_stime = 1;
   1699 				stime = time;
   1700 				slp = t;
   1701 			} else if (qp->c_cc > last_cc) {
   1702 				/* got a character, restart timer */
   1703 				stime = time;
   1704 				slp = t;
   1705 			} else {
   1706 				/* nothing, check expiration */
   1707 				slp = t - diff(time, stime);
   1708 			}
   1709 		} else {	/* m == 0 */
   1710 			if (qp->c_cc > 0)
   1711 				goto read;
   1712 			if (!has_stime) {
   1713 				has_stime = 1;
   1714 				stime = time;
   1715 				slp = t;
   1716 			} else
   1717 				slp = t - diff(time, stime);
   1718 		}
   1719 		last_cc = qp->c_cc;
   1720 #undef diff
   1721 		if (slp > 0) {
   1722 			/*
   1723 			 * Convert deca-ticks back to ticks.
   1724 			 * Rounding down may make us wake up just short
   1725 			 * of the target, so we round up.
   1726 			 * Maybe we should do 'slp/10 + 1' because the
   1727 			 * first tick maybe almost immediate.
   1728 			 * However it is more useful for a program that sets
   1729 			 * VTIME=10 to wakeup every second not every 1.01
   1730 			 * seconds (if hz=100).
   1731 			 */
   1732 			slp = (slp + 9)/ 10;
   1733 			goto sleep;
   1734 		}
   1735 	} else if ((qp = &tp->t_canq)->c_cc <= 0) {
   1736 		int	carrier;
   1737 
   1738  sleep:
   1739 		/*
   1740 		 * If there is no input, sleep on rawq
   1741 		 * awaiting hardware receipt and notification.
   1742 		 * If we have data, we don't need to check for carrier.
   1743 		 */
   1744 		carrier = CONNECTED(tp);
   1745 		if (!carrier && ISSET(tp->t_state, TS_ISOPEN)) {
   1746 			TTY_UNLOCK(tp);
   1747 			splx(s);
   1748 			return (0);	/* EOF */
   1749 		}
   1750 		if (flag & IO_NDELAY) {
   1751 			TTY_UNLOCK(tp);
   1752 			splx(s);
   1753 			return (EWOULDBLOCK);
   1754 		}
   1755 		error = ttysleep(tp, &tp->t_rawq, TTIPRI | PCATCH | PNORELOCK,
   1756 		    carrier ? ttyin : ttopen, slp);
   1757 		splx(s);
   1758 		/* VMIN == 0: any quantity read satisfies */
   1759 		if (cc[VMIN] == 0 && error == EWOULDBLOCK)
   1760 			return (0);
   1761 		if (error && error != EWOULDBLOCK)
   1762 			return (error);
   1763 		goto loop;
   1764 	}
   1765  read:
   1766 	TTY_UNLOCK(tp);
   1767 	splx(s);
   1768 
   1769 	/*
   1770 	 * Input present, check for input mapping and processing.
   1771 	 */
   1772 	first = 1;
   1773 	while ((c = getc(qp)) >= 0) {
   1774 		/*
   1775 		 * delayed suspend (^Y)
   1776 		 */
   1777 		if (CCEQ(cc[VDSUSP], c) &&
   1778 		    ISSET(lflag, IEXTEN|ISIG) == (IEXTEN|ISIG)) {
   1779 			pgsignal(tp->t_pgrp, SIGTSTP, 1);
   1780 			if (first) {
   1781 				s = spltty();
   1782 				TTY_LOCK(tp);
   1783 				error = ttysleep(tp, &lbolt,
   1784 				    TTIPRI | PCATCH | PNORELOCK, ttybg, 0);
   1785 				splx(s);
   1786 				if (error)
   1787 					break;
   1788 				goto loop;
   1789 			}
   1790 			break;
   1791 		}
   1792 		/*
   1793 		 * Interpret EOF only in canonical mode.
   1794 		 */
   1795 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
   1796 			break;
   1797 		/*
   1798 		 * Give user character.
   1799 		 */
   1800  		error = ureadc(c, uio);
   1801 		if (error)
   1802 			break;
   1803  		if (uio->uio_resid == 0)
   1804 			break;
   1805 		/*
   1806 		 * In canonical mode check for a "break character"
   1807 		 * marking the end of a "line of input".
   1808 		 */
   1809 		if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
   1810 			break;
   1811 		first = 0;
   1812 	}
   1813 	/*
   1814 	 * Look to unblock output now that (presumably)
   1815 	 * the input queue has gone down.
   1816 	 */
   1817 	s = spltty();
   1818 	TTY_LOCK(tp);
   1819 	if (ISSET(tp->t_state, TS_TBLOCK) && tp->t_rawq.c_cc < TTYHOG / 5) {
   1820 		if (ISSET(tp->t_iflag, IXOFF) &&
   1821 		    cc[VSTART] != _POSIX_VDISABLE &&
   1822 		    putc(cc[VSTART], &tp->t_outq) == 0) {
   1823 			CLR(tp->t_state, TS_TBLOCK);
   1824 			ttstart(tp);
   1825 		}
   1826 		/* Try to unblock remote output via hardware flow control. */
   1827 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
   1828 		    (*tp->t_hwiflow)(tp, 0) != 0)
   1829 			CLR(tp->t_state, TS_TBLOCK);
   1830 	}
   1831 	TTY_UNLOCK(tp);
   1832 	splx(s);
   1833 	return (error);
   1834 }
   1835 
   1836 /*
   1837  * Check the output queue on tp for space for a kernel message (from uprintf
   1838  * or tprintf).  Allow some space over the normal hiwater mark so we don't
   1839  * lose messages due to normal flow control, but don't let the tty run amok.
   1840  * Sleeps here are not interruptible, but we return prematurely if new signals
   1841  * arrive.
   1842  * Call with tty slock held.
   1843  */
   1844 static int
   1845 ttycheckoutq_wlock(struct tty *tp, int wait)
   1846 {
   1847 	int	hiwat, s, error;
   1848 
   1849 	hiwat = tp->t_hiwat;
   1850 	s = spltty();
   1851 	if (tp->t_outq.c_cc > hiwat + 200)
   1852 		while (tp->t_outq.c_cc > hiwat) {
   1853 			ttstart(tp);
   1854 			if (wait == 0) {
   1855 				splx(s);
   1856 				return (0);
   1857 			}
   1858 			SET(tp->t_state, TS_ASLEEP);
   1859 			error = ltsleep(&tp->t_outq, (PZERO - 1) | PCATCH,
   1860 			    "ttckoutq", hz, &tp->t_slock);
   1861 			if (error == EINTR)
   1862 				wait = 0;
   1863 		}
   1864 
   1865 	splx(s);
   1866 	return (1);
   1867 }
   1868 
   1869 int
   1870 ttycheckoutq(struct tty *tp, int wait)
   1871 {
   1872 	int	r, s;
   1873 
   1874 	s = spltty();
   1875 	TTY_LOCK(tp);
   1876 	r = ttycheckoutq_wlock(tp, wait);
   1877 	TTY_UNLOCK(tp);
   1878 	splx(s);
   1879 	return (r);
   1880 }
   1881 
   1882 /*
   1883  * Process a write call on a tty device.
   1884  */
   1885 int
   1886 ttwrite(struct tty *tp, struct uio *uio, int flag)
   1887 {
   1888 	u_char		*cp;
   1889 	struct proc	*p;
   1890 	int		cc, ce, i, hiwat, error, s;
   1891 	size_t		cnt;
   1892 	u_char		obuf[OBUFSIZ];
   1893 
   1894 	cp = NULL;
   1895 	hiwat = tp->t_hiwat;
   1896 	cnt = uio->uio_resid;
   1897 	error = 0;
   1898 	cc = 0;
   1899  loop:
   1900 	s = spltty();
   1901 	TTY_LOCK(tp);
   1902 	if (!CONNECTED(tp)) {
   1903 		if (ISSET(tp->t_state, TS_ISOPEN)) {
   1904 			TTY_UNLOCK(tp);
   1905 			splx(s);
   1906 			return (EIO);
   1907 		} else if (flag & IO_NDELAY) {
   1908 			TTY_UNLOCK(tp);
   1909 			splx(s);
   1910 			error = EWOULDBLOCK;
   1911 			goto out;
   1912 		} else {
   1913 			/* Sleep awaiting carrier. */
   1914 			error = ttysleep(tp,
   1915 			    &tp->t_rawq, TTIPRI | PCATCH | PNORELOCK, ttopen, 0);
   1916 			splx(s);
   1917 			if (error)
   1918 				goto out;
   1919 			goto loop;
   1920 		}
   1921 	}
   1922 	TTY_UNLOCK(tp);
   1923 	splx(s);
   1924 	/*
   1925 	 * Hang the process if it's in the background.
   1926 	 */
   1927 	p = curproc;
   1928 	if (isbackground(p, tp) &&
   1929 	    ISSET(tp->t_lflag, TOSTOP) && (p->p_flag & P_PPWAIT) == 0 &&
   1930 	    !sigismember(&p->p_sigctx.ps_sigignore, SIGTTOU) &&
   1931 	    !sigismember(&p->p_sigctx.ps_sigmask, SIGTTOU)) {
   1932 		if (p->p_pgrp->pg_jobc == 0) {
   1933 			error = EIO;
   1934 			goto out;
   1935 		}
   1936 		pgsignal(p->p_pgrp, SIGTTOU, 1);
   1937 		s = spltty();
   1938 		TTY_LOCK(tp);
   1939 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH | PNORELOCK, ttybg, 0);
   1940 		splx(s);
   1941 		if (error)
   1942 			goto out;
   1943 		goto loop;
   1944 	}
   1945 	/*
   1946 	 * Process the user's data in at most OBUFSIZ chunks.  Perform any
   1947 	 * output translation.  Keep track of high water mark, sleep on
   1948 	 * overflow awaiting device aid in acquiring new space.
   1949 	 */
   1950 	while (uio->uio_resid > 0 || cc > 0) {
   1951 		if (ISSET(tp->t_lflag, FLUSHO)) {
   1952 			TTY_UNLOCK(tp);
   1953 			uio->uio_resid = 0;
   1954 			return (0);
   1955 		}
   1956 		if (tp->t_outq.c_cc > hiwat)
   1957 			goto ovhiwat;
   1958 		/*
   1959 		 * Grab a hunk of data from the user, unless we have some
   1960 		 * leftover from last time.
   1961 		 */
   1962 		if (cc == 0) {
   1963 			cc = min(uio->uio_resid, OBUFSIZ);
   1964 			cp = obuf;
   1965 			error = uiomove(cp, cc, uio);
   1966 			if (error) {
   1967 				cc = 0;
   1968 				goto out;
   1969 			}
   1970 		}
   1971 		/*
   1972 		 * If nothing fancy need be done, grab those characters we
   1973 		 * can handle without any of ttyoutput's processing and
   1974 		 * just transfer them to the output q.  For those chars
   1975 		 * which require special processing (as indicated by the
   1976 		 * bits in char_type), call ttyoutput.  After processing
   1977 		 * a hunk of data, look for FLUSHO so ^O's will take effect
   1978 		 * immediately.
   1979 		 */
   1980 		s = spltty();
   1981 		TTY_LOCK(tp);
   1982 		while (cc > 0) {
   1983 			if (!ISSET(tp->t_oflag, OPOST))
   1984 				ce = cc;
   1985 			else {
   1986 				ce = cc - scanc((u_int)cc, cp, char_type,
   1987 				    CCLASSMASK);
   1988 				/*
   1989 				 * If ce is zero, then we're processing
   1990 				 * a special character through ttyoutput.
   1991 				 */
   1992 				if (ce == 0) {
   1993 					tp->t_rocount = 0;
   1994 					if (ttyoutput(*cp, tp) >= 0) {
   1995 						/* out of space */
   1996 						TTY_UNLOCK(tp);
   1997 						splx(s);
   1998 						goto overfull;
   1999 					}
   2000 					cp++;
   2001 					cc--;
   2002 					if (ISSET(tp->t_lflag, FLUSHO) ||
   2003 					    tp->t_outq.c_cc > hiwat) {
   2004 						TTY_UNLOCK(tp);
   2005 						splx(s);
   2006 						goto ovhiwat;
   2007 					}
   2008 					continue;
   2009 				}
   2010 			}
   2011 			/*
   2012 			 * A bunch of normal characters have been found.
   2013 			 * Transfer them en masse to the output queue and
   2014 			 * continue processing at the top of the loop.
   2015 			 * If there are any further characters in this
   2016 			 * <= OBUFSIZ chunk, the first should be a character
   2017 			 * requiring special handling by ttyoutput.
   2018 			 */
   2019 			tp->t_rocount = 0;
   2020 			i = b_to_q(cp, ce, &tp->t_outq);
   2021 			ce -= i;
   2022 			tp->t_column += ce;
   2023 			cp += ce, cc -= ce, tk_nout += ce;
   2024 			tp->t_outcc += ce;
   2025 			if (i > 0) {
   2026 				/* out of space */
   2027 				TTY_UNLOCK(tp);
   2028 				splx(s);
   2029 				goto overfull;
   2030 			}
   2031 			if (ISSET(tp->t_lflag, FLUSHO) ||
   2032 			    tp->t_outq.c_cc > hiwat)
   2033 				break;
   2034 		}
   2035 		TTY_UNLOCK(tp);
   2036 		splx(s);
   2037 		ttstart(tp);
   2038 	}
   2039 
   2040  out:
   2041 	/*
   2042 	 * If cc is nonzero, we leave the uio structure inconsistent, as the
   2043 	 * offset and iov pointers have moved forward, but it doesn't matter
   2044 	 * (the call will either return short or restart with a new uio).
   2045 	 */
   2046 	uio->uio_resid += cc;
   2047 	return (error);
   2048 
   2049  overfull:
   2050 	/*
   2051 	 * Since we are using ring buffers, if we can't insert any more into
   2052 	 * the output queue, we can assume the ring is full and that someone
   2053 	 * forgot to set the high water mark correctly.  We set it and then
   2054 	 * proceed as normal.
   2055 	 */
   2056 	hiwat = tp->t_outq.c_cc - 1;
   2057 
   2058  ovhiwat:
   2059 	ttstart(tp);
   2060 	s = spltty();
   2061 	TTY_LOCK(tp);
   2062 	/*
   2063 	 * This can only occur if FLUSHO is set in t_lflag,
   2064 	 * or if ttstart/oproc is synchronous (or very fast).
   2065 	 */
   2066 	if (tp->t_outq.c_cc <= hiwat) {
   2067 		TTY_UNLOCK(tp);
   2068 		splx(s);
   2069 		goto loop;
   2070 	}
   2071 	if (flag & IO_NDELAY) {
   2072 		TTY_UNLOCK(tp);
   2073 		splx(s);
   2074 		error = (uio->uio_resid == cnt) ? EWOULDBLOCK : 0;
   2075 		goto out;
   2076 	}
   2077 	SET(tp->t_state, TS_ASLEEP);
   2078 	error = ttysleep(tp, &tp->t_outq, TTOPRI | PCATCH | PNORELOCK, ttyout, 0);
   2079 	splx(s);
   2080 	if (error)
   2081 		goto out;
   2082 	goto loop;
   2083 }
   2084 
   2085 /*
   2086  * Rubout one character from the rawq of tp
   2087  * as cleanly as possible.
   2088  * Called with tty slock held.
   2089  */
   2090 void
   2091 ttyrub(int c, struct tty *tp)
   2092 {
   2093 	u_char	*cp;
   2094 	int	savecol, tabc, s;
   2095 
   2096 	if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
   2097 		return;
   2098 	CLR(tp->t_lflag, FLUSHO);
   2099 	if (ISSET(tp->t_lflag, ECHOE)) {
   2100 		if (tp->t_rocount == 0) {
   2101 			/*
   2102 			 * Screwed by ttwrite; retype
   2103 			 */
   2104 			ttyretype(tp);
   2105 			return;
   2106 		}
   2107 		if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
   2108 			ttyrubo(tp, 2);
   2109 		else {
   2110 			CLR(c, ~TTY_CHARMASK);
   2111 			switch (CCLASS(c)) {
   2112 			case ORDINARY:
   2113 				ttyrubo(tp, 1);
   2114 				break;
   2115 			case BACKSPACE:
   2116 			case CONTROL:
   2117 			case NEWLINE:
   2118 			case RETURN:
   2119 			case VTAB:
   2120 				if (ISSET(tp->t_lflag, ECHOCTL))
   2121 					ttyrubo(tp, 2);
   2122 				break;
   2123 			case TAB:
   2124 				if (tp->t_rocount < tp->t_rawq.c_cc) {
   2125 					ttyretype(tp);
   2126 					return;
   2127 				}
   2128 				s = spltty();
   2129 				savecol = tp->t_column;
   2130 				SET(tp->t_state, TS_CNTTB);
   2131 				SET(tp->t_lflag, FLUSHO);
   2132 				tp->t_column = tp->t_rocol;
   2133 				for (cp = firstc(&tp->t_rawq, &tabc); cp;
   2134 				    cp = nextc(&tp->t_rawq, cp, &tabc))
   2135 					ttyecho(tabc, tp);
   2136 				CLR(tp->t_lflag, FLUSHO);
   2137 				CLR(tp->t_state, TS_CNTTB);
   2138 				splx(s);
   2139 
   2140 				/* savecol will now be length of the tab. */
   2141 				savecol -= tp->t_column;
   2142 				tp->t_column += savecol;
   2143 				if (savecol > 8)
   2144 					savecol = 8;	/* overflow screw */
   2145 				while (--savecol >= 0)
   2146 					(void)ttyoutput('\b', tp);
   2147 				break;
   2148 			default:			/* XXX */
   2149 #define	PANICSTR	"ttyrub: would panic c = %d, val = %d\n"
   2150 				(void)printf(PANICSTR, c, CCLASS(c));
   2151 #ifdef notdef
   2152 				panic(PANICSTR, c, CCLASS(c));
   2153 #endif
   2154 			}
   2155 		}
   2156 	} else if (ISSET(tp->t_lflag, ECHOPRT)) {
   2157 		if (!ISSET(tp->t_state, TS_ERASE)) {
   2158 			SET(tp->t_state, TS_ERASE);
   2159 			(void)ttyoutput('\\', tp);
   2160 		}
   2161 		ttyecho(c, tp);
   2162 	} else
   2163 		ttyecho(tp->t_cc[VERASE], tp);
   2164 	--tp->t_rocount;
   2165 }
   2166 
   2167 /*
   2168  * Back over cnt characters, erasing them.
   2169  * Called with tty slock held.
   2170  */
   2171 static void
   2172 ttyrubo(struct tty *tp, int cnt)
   2173 {
   2174 
   2175 	while (cnt-- > 0) {
   2176 		(void)ttyoutput('\b', tp);
   2177 		(void)ttyoutput(' ', tp);
   2178 		(void)ttyoutput('\b', tp);
   2179 	}
   2180 }
   2181 
   2182 /*
   2183  * ttyretype --
   2184  *	Reprint the rawq line.  Note, it is assumed that c_cc has already
   2185  *	been checked.
   2186  *
   2187  * Called with tty slock held.
   2188  */
   2189 void
   2190 ttyretype(struct tty *tp)
   2191 {
   2192 	u_char	*cp;
   2193 	int	s, c;
   2194 
   2195 	/* Echo the reprint character. */
   2196 	if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
   2197 		ttyecho(tp->t_cc[VREPRINT], tp);
   2198 
   2199 	(void)ttyoutput('\n', tp);
   2200 
   2201 	s = spltty();
   2202 	for (cp = firstc(&tp->t_canq, &c); cp; cp = nextc(&tp->t_canq, cp, &c))
   2203 		ttyecho(c, tp);
   2204 	for (cp = firstc(&tp->t_rawq, &c); cp; cp = nextc(&tp->t_rawq, cp, &c))
   2205 		ttyecho(c, tp);
   2206 	CLR(tp->t_state, TS_ERASE);
   2207 	splx(s);
   2208 
   2209 	tp->t_rocount = tp->t_rawq.c_cc;
   2210 	tp->t_rocol = 0;
   2211 }
   2212 
   2213 /*
   2214  * Echo a typed character to the terminal.
   2215  * Called with tty slock held.
   2216  */
   2217 static void
   2218 ttyecho(int c, struct tty *tp)
   2219 {
   2220 
   2221 	if (!ISSET(tp->t_state, TS_CNTTB))
   2222 		CLR(tp->t_lflag, FLUSHO);
   2223 	if ((!ISSET(tp->t_lflag, ECHO) &&
   2224 	    (!ISSET(tp->t_lflag, ECHONL) || c != '\n')) ||
   2225 	    ISSET(tp->t_lflag, EXTPROC))
   2226 		return;
   2227 	if (((ISSET(tp->t_lflag, ECHOCTL) &&
   2228 	    (ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n')) ||
   2229 	    ISSET(c, TTY_CHARMASK) == 0177)) {
   2230 		(void)ttyoutput('^', tp);
   2231 		CLR(c, ~TTY_CHARMASK);
   2232 		if (c == 0177)
   2233 			c = '?';
   2234 		else
   2235 			c += 'A' - 1;
   2236 	}
   2237 	(void)ttyoutput(c, tp);
   2238 }
   2239 
   2240 /*
   2241  * Wake up any readers on a tty.
   2242  * Called with tty slock held.
   2243  */
   2244 void
   2245 ttwakeup(struct tty *tp)
   2246 {
   2247 
   2248 	selnotify(&tp->t_rsel, NOTE_SUBMIT);
   2249 	if (ISSET(tp->t_state, TS_ASYNC))
   2250 		pgsignal(tp->t_pgrp, SIGIO, 1);
   2251 	wakeup((caddr_t)&tp->t_rawq);
   2252 }
   2253 
   2254 /*
   2255  * Look up a code for a specified speed in a conversion table;
   2256  * used by drivers to map software speed values to hardware parameters.
   2257  */
   2258 int
   2259 ttspeedtab(int speed, struct speedtab *table)
   2260 {
   2261 
   2262 	for (; table->sp_speed != -1; table++)
   2263 		if (table->sp_speed == speed)
   2264 			return (table->sp_code);
   2265 	return (-1);
   2266 }
   2267 
   2268 /*
   2269  * Set tty hi and low water marks.
   2270  *
   2271  * Try to arrange the dynamics so there's about one second
   2272  * from hi to low water.
   2273  */
   2274 void
   2275 ttsetwater(struct tty *tp)
   2276 {
   2277 	int	cps, x;
   2278 
   2279 #define	CLAMP(x, h, l)	((x) > h ? h : ((x) < l) ? l : (x))
   2280 
   2281 	cps = tp->t_ospeed / 10;
   2282 	tp->t_lowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
   2283 	x += cps;
   2284 	x = CLAMP(x, TTMAXHIWAT, TTMINHIWAT);
   2285 	tp->t_hiwat = roundup(x, CBSIZE);
   2286 #undef	CLAMP
   2287 }
   2288 
   2289 /*
   2290  * Report on state of foreground process group.
   2291  * Call with tty slock held.
   2292  */
   2293 void
   2294 ttyinfo(struct tty *tp)
   2295 {
   2296 	struct lwp	*l;
   2297 	struct proc	*p, *pick;
   2298 	struct timeval	utime, stime;
   2299 	int		tmp;
   2300 
   2301 	if (ttycheckoutq_wlock(tp, 0) == 0)
   2302 		return;
   2303 
   2304 	/* Print load average. */
   2305 	tmp = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
   2306 	ttyprintf_nolock(tp, "load: %d.%02d ", tmp / 100, tmp % 100);
   2307 
   2308 	if (tp->t_session == NULL)
   2309 		ttyprintf_nolock(tp, "not a controlling terminal\n");
   2310 	else if (tp->t_pgrp == NULL)
   2311 		ttyprintf_nolock(tp, "no foreground process group\n");
   2312 	else if ((p = LIST_FIRST(&tp->t_pgrp->pg_members)) == 0)
   2313 		ttyprintf_nolock(tp, "empty foreground process group\n");
   2314 	else {
   2315 		/* Pick interesting process. */
   2316 		for (pick = NULL; p != NULL; p = LIST_NEXT(p, p_pglist))
   2317 			if (proc_compare(pick, p))
   2318 				pick = p;
   2319 
   2320 		ttyprintf_nolock(tp, " cmd: %s %d [", pick->p_comm, pick->p_pid);
   2321 		LIST_FOREACH(l, &pick->p_lwps, l_sibling)
   2322 		    ttyprintf_nolock(tp, "%s%s",
   2323 		    l->l_stat == LSONPROC ? "running" :
   2324 		    l->l_stat == LSRUN ? "runnable" :
   2325 		    l->l_wmesg ? l->l_wmesg : "iowait",
   2326 			(LIST_NEXT(l, l_sibling) != NULL) ? " " : "] ");
   2327 
   2328 		calcru(pick, &utime, &stime, NULL);
   2329 
   2330 		/* Round up and print user time. */
   2331 		utime.tv_usec += 5000;
   2332 		if (utime.tv_usec >= 1000000) {
   2333 			utime.tv_sec += 1;
   2334 			utime.tv_usec -= 1000000;
   2335 		}
   2336 		ttyprintf_nolock(tp, "%ld.%02ldu ", (long int)utime.tv_sec,
   2337 		    (long int)utime.tv_usec / 10000);
   2338 
   2339 		/* Round up and print system time. */
   2340 		stime.tv_usec += 5000;
   2341 		if (stime.tv_usec >= 1000000) {
   2342 			stime.tv_sec += 1;
   2343 			stime.tv_usec -= 1000000;
   2344 		}
   2345 		ttyprintf_nolock(tp, "%ld.%02lds ", (long int)stime.tv_sec,
   2346 		    (long int)stime.tv_usec / 10000);
   2347 
   2348 #define	pgtok(a)	(((u_long) ((a) * PAGE_SIZE) / 1024))
   2349 		/* Print percentage CPU. */
   2350 		tmp = (pick->p_pctcpu * 10000 + FSCALE / 2) >> FSHIFT;
   2351 		ttyprintf_nolock(tp, "%d%% ", tmp / 100);
   2352 
   2353 		/* Print resident set size. */
   2354 		if (pick->p_stat == SIDL || P_ZOMBIE(pick))
   2355 			tmp = 0;
   2356 		else {
   2357 			struct vmspace *vm = pick->p_vmspace;
   2358 			tmp = pgtok(vm_resident_count(vm));
   2359 		}
   2360 		ttyprintf_nolock(tp, "%dk\n", tmp);
   2361 	}
   2362 	tp->t_rocount = 0;	/* so pending input will be retyped if BS */
   2363 }
   2364 
   2365 /*
   2366  * Returns 1 if p2 is "better" than p1
   2367  *
   2368  * The algorithm for picking the "interesting" process is thus:
   2369  *
   2370  *	1) Only foreground processes are eligible - implied.
   2371  *	2) Runnable processes are favored over anything else.  The runner
   2372  *	   with the highest CPU utilization is picked (p_estcpu).  Ties are
   2373  *	   broken by picking the highest pid.
   2374  *	3) The sleeper with the shortest sleep time is next.  With ties,
   2375  *	   we pick out just "short-term" sleepers (P_SINTR == 0).
   2376  *	4) Further ties are broken by picking the highest pid.
   2377  */
   2378 #define	ISRUN(p)	((p)->p_nrlwps > 0)
   2379 #define	TESTAB(a, b)	((a)<<1 | (b))
   2380 #define	ONLYA	2
   2381 #define	ONLYB	1
   2382 #define	BOTH	3
   2383 
   2384 static int
   2385 proc_compare(struct proc *p1, struct proc *p2)
   2386 {
   2387 
   2388 	if (p1 == NULL)
   2389 		return (1);
   2390 	/*
   2391 	 * see if at least one of them is runnable
   2392 	 */
   2393 	switch (TESTAB(ISRUN(p1), ISRUN(p2))) {
   2394 	case ONLYA:
   2395 		return (0);
   2396 	case ONLYB:
   2397 		return (1);
   2398 	case BOTH:
   2399 		/*
   2400 		 * tie - favor one with highest recent CPU utilization
   2401 		 */
   2402 		if (p2->p_estcpu > p1->p_estcpu)
   2403 			return (1);
   2404 		if (p1->p_estcpu > p2->p_estcpu)
   2405 			return (0);
   2406 		return (p2->p_pid > p1->p_pid);	/* tie - return highest pid */
   2407 	}
   2408 	/*
   2409  	 * weed out zombies
   2410 	 */
   2411 	switch (TESTAB(P_ZOMBIE(p1), P_ZOMBIE(p2))) {
   2412 	case ONLYA:
   2413 		return (1);
   2414 	case ONLYB:
   2415 		return (0);
   2416 	case BOTH:
   2417 		return (p2->p_pid > p1->p_pid);	/* tie - return highest pid */
   2418 	}
   2419 #if 0 /* XXX NJWLWP */
   2420 	/*
   2421 	 * pick the one with the smallest sleep time
   2422 	 */
   2423 	if (p2->p_slptime > p1->p_slptime)
   2424 		return (0);
   2425 	if (p1->p_slptime > p2->p_slptime)
   2426 		return (1);
   2427 	/*
   2428 	 * favor one sleeping in a non-interruptible sleep
   2429 	 */
   2430 	if (p1->p_flag & P_SINTR && (p2->p_flag & P_SINTR) == 0)
   2431 		return (1);
   2432 	if (p2->p_flag & P_SINTR && (p1->p_flag & P_SINTR) == 0)
   2433 		return (0);
   2434 #endif
   2435 	return (p2->p_pid > p1->p_pid);		/* tie - return highest pid */
   2436 }
   2437 
   2438 /*
   2439  * Output char to tty; console putchar style.
   2440  * Can be called with tty lock held through kprintf() machinery..
   2441  */
   2442 int
   2443 tputchar(int c, int flags, struct tty *tp)
   2444 {
   2445 	int s, r = 0;
   2446 
   2447 	s = spltty();
   2448 	if ((flags & NOLOCK) == 0)
   2449 		simple_lock(&tp->t_slock);
   2450 	if (!CONNECTED(tp)) {
   2451 		r = -1;
   2452 		goto out;
   2453 	}
   2454 	if (c == '\n')
   2455 		(void)ttyoutput('\r', tp);
   2456 	(void)ttyoutput(c, tp);
   2457 	ttstart(tp);
   2458 out:
   2459 	if ((flags & NOLOCK) == 0)
   2460 		TTY_UNLOCK(tp);
   2461 	splx(s);
   2462 	return (r);
   2463 }
   2464 
   2465 /*
   2466  * Sleep on chan, returning ERESTART if tty changed while we napped and
   2467  * returning any errors (e.g. EINTR/ETIMEDOUT) reported by tsleep.  If
   2468  * the tty is revoked, restarting a pending call will redo validation done
   2469  * at the start of the call.
   2470  *
   2471  * Must be called with the tty slock held.
   2472  */
   2473 int
   2474 ttysleep(struct tty *tp, void *chan, int pri, const char *wmesg, int timo)
   2475 {
   2476 	int	error;
   2477 	short	gen;
   2478 
   2479 	gen = tp->t_gen;
   2480 	if ((error = ltsleep(chan, pri, wmesg, timo, &tp->t_slock)) != 0)
   2481 		return (error);
   2482 	return (tp->t_gen == gen ? 0 : ERESTART);
   2483 }
   2484 
   2485 /*
   2486  * Initialise the global tty list.
   2487  */
   2488 void
   2489 tty_init(void)
   2490 {
   2491 
   2492 	ttyldisc_init();
   2493 
   2494 	TAILQ_INIT(&ttylist);
   2495 	tty_count = 0;
   2496 
   2497 	pool_init(&tty_pool, sizeof(struct tty), 0, 0, 0, "ttypl",
   2498 	    &pool_allocator_nointr);
   2499 }
   2500 
   2501 /*
   2502  * Attach a tty to the tty list.
   2503  *
   2504  * This should be called ONLY once per real tty (including pty's).
   2505  * eg, on the sparc, the keyboard and mouse have struct tty's that are
   2506  * distinctly NOT usable as tty's, and thus should not be attached to
   2507  * the ttylist.  This is why this call is not done from ttymalloc().
   2508  *
   2509  * Device drivers should attach tty's at a similar time that they are
   2510  * ttymalloc()'ed, or, for the case of statically allocated struct tty's
   2511  * either in the attach or (first) open routine.
   2512  */
   2513 void
   2514 tty_attach(struct tty *tp)
   2515 {
   2516 
   2517 	simple_lock(&ttylist_slock);
   2518 	TAILQ_INSERT_TAIL(&ttylist, tp, tty_link);
   2519 	++tty_count;
   2520 	simple_unlock(&ttylist_slock);
   2521 }
   2522 
   2523 /*
   2524  * Remove a tty from the tty list.
   2525  */
   2526 void
   2527 tty_detach(struct tty *tp)
   2528 {
   2529 
   2530 	simple_lock(&ttylist_slock);
   2531 	--tty_count;
   2532 #ifdef DIAGNOSTIC
   2533 	if (tty_count < 0)
   2534 		panic("tty_detach: tty_count < 0");
   2535 #endif
   2536 	TAILQ_REMOVE(&ttylist, tp, tty_link);
   2537 	simple_unlock(&ttylist_slock);
   2538 }
   2539 
   2540 /*
   2541  * Allocate a tty structure and its associated buffers.
   2542  */
   2543 struct tty *
   2544 ttymalloc(void)
   2545 {
   2546 	struct tty	*tp;
   2547 
   2548 	tp = pool_get(&tty_pool, PR_WAITOK);
   2549 	memset(tp, 0, sizeof(*tp));
   2550 	simple_lock_init(&tp->t_slock);
   2551 	callout_init(&tp->t_rstrt_ch);
   2552 	/* XXX: default to 1024 chars for now */
   2553 	clalloc(&tp->t_rawq, 1024, 1);
   2554 	clalloc(&tp->t_canq, 1024, 1);
   2555 	/* output queue doesn't need quoting */
   2556 	clalloc(&tp->t_outq, 1024, 0);
   2557 	/* Set default line discipline. */
   2558 	tp->t_linesw = linesw[0];
   2559 	return (tp);
   2560 }
   2561 
   2562 /*
   2563  * Free a tty structure and its buffers.
   2564  *
   2565  * Be sure to call tty_detach() for any tty that has been
   2566  * tty_attach()ed.
   2567  */
   2568 void
   2569 ttyfree(struct tty *tp)
   2570 {
   2571 
   2572 	callout_stop(&tp->t_rstrt_ch);
   2573 	clfree(&tp->t_rawq);
   2574 	clfree(&tp->t_canq);
   2575 	clfree(&tp->t_outq);
   2576 	pool_put(&tty_pool, tp);
   2577 }
   2578 
   2579 /*
   2580  * ttyprintf_nolock: send a message to a specific tty, without locking.
   2581  *
   2582  * => should be used only by tty driver or anything that knows the
   2583  *    underlying tty will not be revoked(2)'d away.  [otherwise,
   2584  *    use tprintf]
   2585  */
   2586 static void
   2587 ttyprintf_nolock(struct tty *tp, const char *fmt, ...)
   2588 {
   2589 	va_list ap;
   2590 
   2591 	/* No mutex needed; going to process TTY. */
   2592 	va_start(ap, fmt);
   2593 	kprintf(fmt, TOTTY|NOLOCK, tp, NULL, ap);
   2594 	va_end(ap);
   2595 }
   2596