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