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