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