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