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