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