Home | History | Annotate | Line # | Download | only in kern
tty.c revision 1.190
      1 /*	$NetBSD: tty.c,v 1.190 2007/02/09 21:55:32 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.190 2007/02/09 21:55:32 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 		/* XXXSMP */
    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_authorize_generic(l->l_cred, KAUTH_GENERIC_ISSUSER,
   1139 		    NULL) != 0) {
   1140 			if (!ISSET(flag, FREAD))
   1141 				return (EPERM);
   1142 			if (!isctty(p, tp))
   1143 				return (EACCES);
   1144 		}
   1145 		(*tp->t_linesw->l_rint)(*(u_char *)data, tp);
   1146 		break;
   1147 	case TIOCSTOP:			/* stop output, like ^S */
   1148 	{
   1149 		const struct cdevsw *cdev;
   1150 		s = spltty();
   1151 		TTY_LOCK(tp);
   1152 		if (!ISSET(tp->t_state, TS_TTSTOP)) {
   1153 			SET(tp->t_state, TS_TTSTOP);
   1154 			cdev = cdevsw_lookup(tp->t_dev);
   1155 			if (cdev != NULL)
   1156 				(*cdev->d_stop)(tp, 0);
   1157 		}
   1158 		TTY_UNLOCK(tp);
   1159 		splx(s);
   1160 		break;
   1161 	}
   1162 	case TIOCSCTTY:			/* become controlling tty */
   1163 		rw_enter(&proclist_lock, RW_WRITER);
   1164 
   1165 		/* Session ctty vnode pointer set in vnode layer. */
   1166 		if (!SESS_LEADER(p) ||
   1167 		    ((p->p_session->s_ttyvp || tp->t_session) &&
   1168 		    (tp->t_session != p->p_session))) {
   1169 			rw_exit(&proclist_lock);
   1170 			return (EPERM);
   1171 		}
   1172 
   1173 		/*
   1174 		 * `p_session' acquires a reference.
   1175 		 * But note that if `t_session' is set at this point,
   1176 		 * it must equal `p_session', in which case the session
   1177 		 * already has the correct reference count.
   1178 		 */
   1179 		if (tp->t_session == NULL)
   1180 			SESSHOLD(p->p_session);
   1181 
   1182 		tp->t_session = p->p_session;
   1183 		tp->t_pgrp = p->p_pgrp;
   1184 		p->p_session->s_ttyp = tp;
   1185 		p->p_lflag |= PL_CONTROLT;
   1186 		rw_exit(&proclist_lock);
   1187 		break;
   1188 	case FIOSETOWN: {		/* set pgrp of tty */
   1189 		pid_t pgid = *(int *)data;
   1190 		struct pgrp *pgrp;
   1191 
   1192 		if (tp->t_session != NULL && !isctty(p, tp))
   1193 			return (ENOTTY);
   1194 
   1195 		if (pgid < 0)
   1196 			pgrp = pgfind(-pgid);
   1197 		else {
   1198 			struct proc *p1 = pfind(pgid);
   1199 			if (!p1)
   1200 				return (ESRCH);
   1201 			pgrp = p1->p_pgrp;
   1202 		}
   1203 
   1204 		if (pgrp == NULL)
   1205 			return (EINVAL);
   1206 		else if (pgrp->pg_session != p->p_session)
   1207 			return (EPERM);
   1208 		tp->t_pgrp = pgrp;
   1209 		break;
   1210 	}
   1211 	case TIOCSPGRP: {		/* set pgrp of tty */
   1212 		struct pgrp *pgrp = pgfind(*(int *)data);
   1213 
   1214 		if (!isctty(p, tp))
   1215 			return (ENOTTY);
   1216 		else if (pgrp == NULL)
   1217 			return (EINVAL);
   1218 		else if (pgrp->pg_session != p->p_session)
   1219 			return (EPERM);
   1220 		tp->t_pgrp = pgrp;
   1221 		break;
   1222 	}
   1223 	case TIOCSTAT:			/* get load avg stats */
   1224 		s = spltty();
   1225 		TTY_LOCK(tp);
   1226 		ttyinfo(tp, 0);
   1227 		TTY_UNLOCK(tp);
   1228 		splx(s);
   1229 		break;
   1230 	case TIOCSWINSZ:		/* set window size */
   1231 		if (memcmp((caddr_t)&tp->t_winsize, data,
   1232 		    sizeof(struct winsize))) {
   1233 			tp->t_winsize = *(struct winsize *)data;
   1234 			mutex_enter(&proclist_mutex);
   1235 			pgsignal(tp->t_pgrp, SIGWINCH, 1);
   1236 			mutex_exit(&proclist_mutex);
   1237 		}
   1238 		break;
   1239 	default:
   1240 #ifdef COMPAT_OLDTTY
   1241 		return (ttcompat(tp, cmd, data, flag, l));
   1242 #else
   1243 		return (EPASSTHROUGH);
   1244 #endif
   1245 	}
   1246 	return (0);
   1247 }
   1248 
   1249 int
   1250 ttpoll(struct tty *tp, int events, struct lwp *l)
   1251 {
   1252 	int	revents, s;
   1253 
   1254 	revents = 0;
   1255 	s = spltty();
   1256 	TTY_LOCK(tp);
   1257 	if (events & (POLLIN | POLLRDNORM))
   1258 		if (ttnread(tp) > 0)
   1259 			revents |= events & (POLLIN | POLLRDNORM);
   1260 
   1261 	if (events & (POLLOUT | POLLWRNORM))
   1262 		if (tp->t_outq.c_cc <= tp->t_lowat)
   1263 			revents |= events & (POLLOUT | POLLWRNORM);
   1264 
   1265 	if (events & POLLHUP)
   1266 		if (!CONNECTED(tp))
   1267 			revents |= POLLHUP;
   1268 
   1269 	if (revents == 0) {
   1270 		if (events & (POLLIN | POLLHUP | POLLRDNORM))
   1271 			selrecord(l, &tp->t_rsel);
   1272 
   1273 		if (events & (POLLOUT | POLLWRNORM))
   1274 			selrecord(l, &tp->t_wsel);
   1275 	}
   1276 
   1277 	TTY_UNLOCK(tp);
   1278 	splx(s);
   1279 	return (revents);
   1280 }
   1281 
   1282 static void
   1283 filt_ttyrdetach(struct knote *kn)
   1284 {
   1285 	struct tty	*tp;
   1286 	int		s;
   1287 
   1288 	tp = kn->kn_hook;
   1289 	s = spltty();
   1290 	TTY_LOCK(tp);
   1291 	SLIST_REMOVE(&tp->t_rsel.sel_klist, kn, knote, kn_selnext);
   1292 	TTY_UNLOCK(tp);
   1293 	splx(s);
   1294 }
   1295 
   1296 static int
   1297 filt_ttyread(struct knote *kn, long hint)
   1298 {
   1299 	struct tty	*tp;
   1300 	int		s;
   1301 
   1302 	tp = kn->kn_hook;
   1303 	s = spltty();
   1304 	if ((hint & NOTE_SUBMIT) == 0)
   1305 		TTY_LOCK(tp);
   1306 	kn->kn_data = ttnread(tp);
   1307 	if ((hint & NOTE_SUBMIT) == 0)
   1308 		TTY_UNLOCK(tp);
   1309 	splx(s);
   1310 	return (kn->kn_data > 0);
   1311 }
   1312 
   1313 static void
   1314 filt_ttywdetach(struct knote *kn)
   1315 {
   1316 	struct tty	*tp;
   1317 	int		s;
   1318 
   1319 	tp = kn->kn_hook;
   1320 	s = spltty();
   1321 	TTY_LOCK(tp);
   1322 	SLIST_REMOVE(&tp->t_wsel.sel_klist, kn, knote, kn_selnext);
   1323 	TTY_UNLOCK(tp);
   1324 	splx(s);
   1325 }
   1326 
   1327 static int
   1328 filt_ttywrite(struct knote *kn, long hint)
   1329 {
   1330 	struct tty	*tp;
   1331 	int		canwrite, s;
   1332 
   1333 	tp = kn->kn_hook;
   1334 	s = spltty();
   1335 	if ((hint & NOTE_SUBMIT) == 0)
   1336 		TTY_LOCK(tp);
   1337 	kn->kn_data = tp->t_outq.c_cn - tp->t_outq.c_cc;
   1338 	canwrite = (tp->t_outq.c_cc <= tp->t_lowat) && CONNECTED(tp);
   1339 	if ((hint & NOTE_SUBMIT) == 0)
   1340 		TTY_UNLOCK(tp);
   1341 	splx(s);
   1342 	return (canwrite);
   1343 }
   1344 
   1345 static const struct filterops ttyread_filtops =
   1346 	{ 1, NULL, filt_ttyrdetach, filt_ttyread };
   1347 static const struct filterops ttywrite_filtops =
   1348 	{ 1, NULL, filt_ttywdetach, filt_ttywrite };
   1349 
   1350 int
   1351 ttykqfilter(dev_t dev, struct knote *kn)
   1352 {
   1353 	struct tty	*tp;
   1354 	struct klist	*klist;
   1355 	int		s;
   1356 	const struct cdevsw	*cdev;
   1357 
   1358         if (((cdev = cdevsw_lookup(dev)) == NULL) ||
   1359 	    (cdev->d_tty == NULL) ||
   1360 	    ((tp = (*cdev->d_tty)(dev)) == NULL))
   1361 		return (ENXIO);
   1362 
   1363 	switch (kn->kn_filter) {
   1364 	case EVFILT_READ:
   1365 		klist = &tp->t_rsel.sel_klist;
   1366 		kn->kn_fop = &ttyread_filtops;
   1367 		break;
   1368 	case EVFILT_WRITE:
   1369 		klist = &tp->t_wsel.sel_klist;
   1370 		kn->kn_fop = &ttywrite_filtops;
   1371 		break;
   1372 	default:
   1373 		return EINVAL;
   1374 	}
   1375 
   1376 	kn->kn_hook = tp;
   1377 
   1378 	s = spltty();
   1379 	TTY_LOCK(tp);
   1380 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
   1381 	TTY_UNLOCK(tp);
   1382 	splx(s);
   1383 
   1384 	return (0);
   1385 }
   1386 
   1387 /*
   1388  * Find the number of chars ready to be read from this tty.
   1389  * Call at spltty() and with the tty slock held.
   1390  */
   1391 static int
   1392 ttnread(struct tty *tp)
   1393 {
   1394 	int	nread;
   1395 
   1396 	if (ISSET(tp->t_lflag, PENDIN))
   1397 		ttypend(tp);
   1398 	nread = tp->t_canq.c_cc;
   1399 	if (!ISSET(tp->t_lflag, ICANON)) {
   1400 		nread += tp->t_rawq.c_cc;
   1401 		if (nread < tp->t_cc[VMIN] && !tp->t_cc[VTIME])
   1402 			nread = 0;
   1403 	}
   1404 	return (nread);
   1405 }
   1406 
   1407 /*
   1408  * Wait for output to drain.
   1409  */
   1410 int
   1411 ttywait(struct tty *tp)
   1412 {
   1413 	int	error, s;
   1414 
   1415 	error = 0;
   1416 	s = spltty();
   1417 	TTY_LOCK(tp);
   1418 	while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
   1419 	    CONNECTED(tp) && tp->t_oproc) {
   1420 		(*tp->t_oproc)(tp);
   1421 		SET(tp->t_state, TS_ASLEEP);
   1422 		error = ttysleep(tp, &tp->t_outq, TTOPRI | PCATCH, ttyout, 0);
   1423 		if (error)
   1424 			break;
   1425 	}
   1426 	TTY_UNLOCK(tp);
   1427 	splx(s);
   1428 	return (error);
   1429 }
   1430 
   1431 /*
   1432  * Flush if successfully wait.
   1433  */
   1434 int
   1435 ttywflush(struct tty *tp)
   1436 {
   1437 	int	error;
   1438 	int	s;
   1439 
   1440 	if ((error = ttywait(tp)) == 0) {
   1441 		s = spltty();
   1442 		TTY_LOCK(tp);
   1443 		ttyflush(tp, FREAD);
   1444 		TTY_UNLOCK(tp);
   1445 		splx(s);
   1446 	}
   1447 	return (error);
   1448 }
   1449 
   1450 /*
   1451  * Flush tty read and/or write queues, notifying anyone waiting.
   1452  * Call at spltty() and with the tty slock held.
   1453  */
   1454 void
   1455 ttyflush(struct tty *tp, int rw)
   1456 {
   1457 	const struct cdevsw *cdev;
   1458 
   1459 	if (rw & FREAD) {
   1460 		FLUSHQ(&tp->t_canq);
   1461 		FLUSHQ(&tp->t_rawq);
   1462 		tp->t_rocount = 0;
   1463 		tp->t_rocol = 0;
   1464 		CLR(tp->t_state, TS_LOCAL);
   1465 		ttwakeup(tp);
   1466 	}
   1467 	if (rw & FWRITE) {
   1468 		CLR(tp->t_state, TS_TTSTOP);
   1469 		cdev = cdevsw_lookup(tp->t_dev);
   1470 		if (cdev != NULL)
   1471 			(*cdev->d_stop)(tp, rw);
   1472 		FLUSHQ(&tp->t_outq);
   1473 		wakeup((caddr_t)&tp->t_outq);
   1474 		selnotify(&tp->t_wsel, NOTE_SUBMIT);
   1475 	}
   1476 }
   1477 
   1478 /*
   1479  * Copy in the default termios characters.
   1480  */
   1481 void
   1482 ttychars(struct tty *tp)
   1483 {
   1484 
   1485 	memcpy(tp->t_cc, ttydefchars, sizeof(ttydefchars));
   1486 }
   1487 
   1488 /*
   1489  * Send stop character on input overflow.
   1490  * Call at spltty() and with the tty slock held.
   1491  */
   1492 static void
   1493 ttyblock(struct tty *tp)
   1494 {
   1495 	int	total;
   1496 
   1497 	total = tp->t_rawq.c_cc + tp->t_canq.c_cc;
   1498 	if (tp->t_rawq.c_cc > TTYHOG) {
   1499 		ttyflush(tp, FREAD | FWRITE);
   1500 		CLR(tp->t_state, TS_TBLOCK);
   1501 	}
   1502 	/*
   1503 	 * Block further input iff: current input > threshold
   1504 	 * AND input is available to user program.
   1505 	 */
   1506 	if (total >= TTYHOG / 2 &&
   1507 	    !ISSET(tp->t_state, TS_TBLOCK) &&
   1508 	    (!ISSET(tp->t_lflag, ICANON) || tp->t_canq.c_cc > 0)) {
   1509 		if (ISSET(tp->t_iflag, IXOFF) &&
   1510 		    tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
   1511 		    putc(tp->t_cc[VSTOP], &tp->t_outq) == 0) {
   1512 			SET(tp->t_state, TS_TBLOCK);
   1513 			ttstart(tp);
   1514 		}
   1515 		/* Try to block remote output via hardware flow control. */
   1516 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
   1517 		    (*tp->t_hwiflow)(tp, 1) != 0)
   1518 			SET(tp->t_state, TS_TBLOCK);
   1519 	}
   1520 }
   1521 
   1522 /*
   1523  * Delayed line discipline output
   1524  */
   1525 void
   1526 ttrstrt(void *tp_arg)
   1527 {
   1528 	struct tty	*tp;
   1529 	int		s;
   1530 
   1531 #ifdef DIAGNOSTIC
   1532 	if (tp_arg == NULL)
   1533 		panic("ttrstrt");
   1534 #endif
   1535 	tp = tp_arg;
   1536 	s = spltty();
   1537 	TTY_LOCK(tp);
   1538 
   1539 	CLR(tp->t_state, TS_TIMEOUT);
   1540 	ttstart(tp); /* XXX - Shouldn't this be tp->l_start(tp)? */
   1541 
   1542 	TTY_UNLOCK(tp);
   1543 	splx(s);
   1544 }
   1545 
   1546 /*
   1547  * start a line discipline
   1548  * Always call at spltty() and with tty slock held?
   1549  */
   1550 int
   1551 ttstart(struct tty *tp)
   1552 {
   1553 
   1554 	if (tp->t_oproc != NULL)	/* XXX: Kludge for pty. */
   1555 		(*tp->t_oproc)(tp);
   1556 	return (0);
   1557 }
   1558 
   1559 /*
   1560  * "close" a line discipline
   1561  */
   1562 int
   1563 ttylclose(struct tty *tp, int flag)
   1564 {
   1565 	int s;
   1566 
   1567 	if (flag & FNONBLOCK) {
   1568 		s = spltty();
   1569 		TTY_LOCK(tp);
   1570 		ttyflush(tp, FREAD | FWRITE);
   1571 		TTY_UNLOCK(tp);
   1572 		splx(s);
   1573 	} else
   1574 		ttywflush(tp);
   1575 	return (0);
   1576 }
   1577 
   1578 /*
   1579  * Handle modem control transition on a tty.
   1580  * Flag indicates new state of carrier.
   1581  * Returns 0 if the line should be turned off, otherwise 1.
   1582  *
   1583  * Must be called at spltty().
   1584  * XXX except that it is often isn't, which should be fixed.
   1585  */
   1586 int
   1587 ttymodem(struct tty *tp, int flag)
   1588 {
   1589 	int s;
   1590 
   1591 	s = spltty();
   1592 	TTY_LOCK(tp);
   1593 	if (flag == 0) {
   1594 		if (ISSET(tp->t_state, TS_CARR_ON)) {
   1595 			/*
   1596 			 * Lost carrier.
   1597 			 */
   1598 			CLR(tp->t_state, TS_CARR_ON);
   1599 			if (ISSET(tp->t_state, TS_ISOPEN) && !CONNECTED(tp)) {
   1600 				if (tp->t_session && tp->t_session->s_leader) {
   1601 					mutex_enter(&proclist_mutex);
   1602 					psignal(tp->t_session->s_leader,
   1603 					    SIGHUP);
   1604 					mutex_exit(&proclist_mutex);
   1605 				}
   1606 				ttyflush(tp, FREAD | FWRITE);
   1607 				TTY_UNLOCK(tp);
   1608 				splx(s);
   1609 				return (0);
   1610 			}
   1611 		}
   1612 	} else {
   1613 		if (!ISSET(tp->t_state, TS_CARR_ON)) {
   1614 			/*
   1615 			 * Carrier now on.
   1616 			 */
   1617 			SET(tp->t_state, TS_CARR_ON);
   1618 			ttwakeup(tp);
   1619 		}
   1620 	}
   1621 	TTY_UNLOCK(tp);
   1622 	splx(s);
   1623 	return (1);
   1624 }
   1625 
   1626 /*
   1627  * Default modem control routine (for other line disciplines).
   1628  * Return argument flag, to turn off device on carrier drop.
   1629  *
   1630  * Must be called at spltty().
   1631  * XXX except that it is often isn't, which should be fixed.
   1632  */
   1633 int
   1634 nullmodem(struct tty *tp, int flag)
   1635 {
   1636 	int s;
   1637 
   1638 	s = spltty();
   1639 	TTY_LOCK(tp);
   1640 	if (flag)
   1641 		SET(tp->t_state, TS_CARR_ON);
   1642 	else {
   1643 		CLR(tp->t_state, TS_CARR_ON);
   1644 		if (!CONNECTED(tp)) {
   1645 			if (tp->t_session && tp->t_session->s_leader) {
   1646 				mutex_enter(&proclist_mutex);
   1647 				psignal(tp->t_session->s_leader, SIGHUP);
   1648 				mutex_exit(&proclist_mutex);
   1649 			}
   1650 			TTY_UNLOCK(tp);
   1651 			splx(s);
   1652 			return (0);
   1653 		}
   1654 	}
   1655 	TTY_UNLOCK(tp);
   1656 	splx(s);
   1657 	return (1);
   1658 }
   1659 
   1660 /*
   1661  * Reinput pending characters after state switch.
   1662  * Call at spltty() and with the tty slock held.
   1663  */
   1664 void
   1665 ttypend(struct tty *tp)
   1666 {
   1667 	struct clist	tq;
   1668 	int		c;
   1669 
   1670 	CLR(tp->t_lflag, PENDIN);
   1671 	SET(tp->t_state, TS_TYPEN);
   1672 	tq = tp->t_rawq;
   1673 	tp->t_rawq.c_cc = 0;
   1674 	tp->t_rawq.c_cf = tp->t_rawq.c_cl = 0;
   1675 	while ((c = getc(&tq)) >= 0)
   1676 		ttyinput_wlock(c, tp);
   1677 	CLR(tp->t_state, TS_TYPEN);
   1678 }
   1679 
   1680 /*
   1681  * Process a read call on a tty device.
   1682  */
   1683 int
   1684 ttread(struct tty *tp, struct uio *uio, int flag)
   1685 {
   1686 	struct clist	*qp;
   1687 	u_char		*cc;
   1688 	struct proc	*p;
   1689 	int		c, s, first, error, has_stime, last_cc;
   1690 	long		lflag, slp;
   1691 	struct timeval	now, stime;
   1692 
   1693 	stime.tv_usec = 0;	/* XXX gcc */
   1694 	stime.tv_sec = 0;	/* XXX gcc */
   1695 
   1696 	cc = tp->t_cc;
   1697 	p = curproc;
   1698 	error = 0;
   1699 	has_stime = 0;
   1700 	last_cc = 0;
   1701 	slp = 0;
   1702 
   1703  loop:
   1704 	s = spltty();
   1705 	TTY_LOCK(tp);
   1706 	lflag = tp->t_lflag;
   1707 	/*
   1708 	 * take pending input first
   1709 	 */
   1710 	if (ISSET(lflag, PENDIN))
   1711 		ttypend(tp);
   1712 
   1713 	/*
   1714 	 * Hang process if it's in the background. XXXSMP
   1715 	 */
   1716 	if (isbackground(p, tp)) {
   1717 		if (sigismember(&p->p_sigctx.ps_sigignore, SIGTTIN) ||
   1718 		    sigismember(&curlwp->l_sigmask, SIGTTIN) ||
   1719 		    p->p_sflag & PS_PPWAIT || p->p_pgrp->pg_jobc == 0) {
   1720 			TTY_UNLOCK(tp);
   1721 			splx(s);
   1722 			return (EIO);
   1723 		}
   1724 		mutex_enter(&proclist_mutex);
   1725 		pgsignal(p->p_pgrp, SIGTTIN, 1);
   1726 		mutex_exit(&proclist_mutex);
   1727 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH | PNORELOCK, ttybg, 0);
   1728 		splx(s);
   1729 		if (error)
   1730 			return (error);
   1731 		goto loop;
   1732 	}
   1733 
   1734 	if (!ISSET(lflag, ICANON)) {
   1735 		int m = cc[VMIN];
   1736 		long t = cc[VTIME];
   1737 
   1738 		qp = &tp->t_rawq;
   1739 		/*
   1740 		 * Check each of the four combinations.
   1741 		 * (m > 0 && t == 0) is the normal read case.
   1742 		 * It should be fairly efficient, so we check that and its
   1743 		 * companion case (m == 0 && t == 0) first.
   1744 		 * For the other two cases, we compute the target sleep time
   1745 		 * into slp.
   1746 		 */
   1747 		if (t == 0) {
   1748 			if (qp->c_cc < m)
   1749 				goto sleep;
   1750 			goto read;
   1751 		}
   1752 		t *= hz;		/* time in deca-ticks */
   1753 /*
   1754  * Time difference in deca-ticks, split division to avoid numeric overflow.
   1755  * Ok for hz < ~200kHz
   1756  */
   1757 #define	diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 10 * hz + \
   1758 			 ((t1).tv_usec - (t2).tv_usec) / 100 * hz / 1000)
   1759 		if (m > 0) {
   1760 			if (qp->c_cc <= 0)
   1761 				goto sleep;
   1762 			if (qp->c_cc >= m)
   1763 				goto read;
   1764 			if (!has_stime) {
   1765 				/* first character, start timer */
   1766 				has_stime = 1;
   1767 				getmicrotime(&stime);
   1768 				slp = t;
   1769 			} else if (qp->c_cc > last_cc) {
   1770 				/* got a character, restart timer */
   1771 				getmicrotime(&stime);
   1772 				slp = t;
   1773 			} else {
   1774 				/* nothing, check expiration */
   1775 				getmicrotime(&now);
   1776 				slp = t - diff(now, stime);
   1777 			}
   1778 		} else {	/* m == 0 */
   1779 			if (qp->c_cc > 0)
   1780 				goto read;
   1781 			if (!has_stime) {
   1782 				has_stime = 1;
   1783 				getmicrotime(&stime);
   1784 				slp = t;
   1785 			} else {
   1786 				getmicrotime(&now);
   1787 				slp = t - diff(now, stime);
   1788 			}
   1789 		}
   1790 		last_cc = qp->c_cc;
   1791 #undef diff
   1792 		if (slp > 0) {
   1793 			/*
   1794 			 * Convert deca-ticks back to ticks.
   1795 			 * Rounding down may make us wake up just short
   1796 			 * of the target, so we round up.
   1797 			 * Maybe we should do 'slp/10 + 1' because the
   1798 			 * first tick maybe almost immediate.
   1799 			 * However it is more useful for a program that sets
   1800 			 * VTIME=10 to wakeup every second not every 1.01
   1801 			 * seconds (if hz=100).
   1802 			 */
   1803 			slp = (slp + 9)/ 10;
   1804 			goto sleep;
   1805 		}
   1806 	} else if ((qp = &tp->t_canq)->c_cc <= 0) {
   1807 		int	carrier;
   1808 
   1809  sleep:
   1810 		/*
   1811 		 * If there is no input, sleep on rawq
   1812 		 * awaiting hardware receipt and notification.
   1813 		 * If we have data, we don't need to check for carrier.
   1814 		 */
   1815 		carrier = CONNECTED(tp);
   1816 		if (!carrier && ISSET(tp->t_state, TS_ISOPEN)) {
   1817 			TTY_UNLOCK(tp);
   1818 			splx(s);
   1819 			return (0);	/* EOF */
   1820 		}
   1821 		if (flag & IO_NDELAY) {
   1822 			TTY_UNLOCK(tp);
   1823 			splx(s);
   1824 			return (EWOULDBLOCK);
   1825 		}
   1826 		error = ttysleep(tp, &tp->t_rawq, TTIPRI | PCATCH | PNORELOCK,
   1827 		    carrier ? ttyin : ttopen, slp);
   1828 		splx(s);
   1829 		/* VMIN == 0: any quantity read satisfies */
   1830 		if (cc[VMIN] == 0 && error == EWOULDBLOCK)
   1831 			return (0);
   1832 		if (error && error != EWOULDBLOCK)
   1833 			return (error);
   1834 		goto loop;
   1835 	}
   1836  read:
   1837 	TTY_UNLOCK(tp);
   1838 	splx(s);
   1839 
   1840 	/*
   1841 	 * Input present, check for input mapping and processing.
   1842 	 */
   1843 	first = 1;
   1844 	while ((c = getc(qp)) >= 0) {
   1845 		/*
   1846 		 * delayed suspend (^Y)
   1847 		 */
   1848 		if (CCEQ(cc[VDSUSP], c) &&
   1849 		    ISSET(lflag, IEXTEN|ISIG) == (IEXTEN|ISIG)) {
   1850 			mutex_enter(&proclist_mutex);
   1851 			pgsignal(tp->t_pgrp, SIGTSTP, 1);
   1852 			mutex_exit(&proclist_mutex);
   1853 			if (first) {
   1854 				s = spltty();
   1855 				TTY_LOCK(tp);
   1856 				error = ttysleep(tp, &lbolt,
   1857 				    TTIPRI | PCATCH | PNORELOCK, ttybg, 0);
   1858 				splx(s);
   1859 				if (error)
   1860 					break;
   1861 				goto loop;
   1862 			}
   1863 			break;
   1864 		}
   1865 		/*
   1866 		 * Interpret EOF only in canonical mode.
   1867 		 */
   1868 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
   1869 			break;
   1870 		/*
   1871 		 * Give user character.
   1872 		 */
   1873  		error = ureadc(c, uio);
   1874 		if (error)
   1875 			break;
   1876  		if (uio->uio_resid == 0)
   1877 			break;
   1878 		/*
   1879 		 * In canonical mode check for a "break character"
   1880 		 * marking the end of a "line of input".
   1881 		 */
   1882 		if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
   1883 			break;
   1884 		first = 0;
   1885 	}
   1886 	/*
   1887 	 * Look to unblock output now that (presumably)
   1888 	 * the input queue has gone down.
   1889 	 */
   1890 	s = spltty();
   1891 	TTY_LOCK(tp);
   1892 	if (ISSET(tp->t_state, TS_TBLOCK) && tp->t_rawq.c_cc < TTYHOG / 5) {
   1893 		if (ISSET(tp->t_iflag, IXOFF) &&
   1894 		    cc[VSTART] != _POSIX_VDISABLE &&
   1895 		    putc(cc[VSTART], &tp->t_outq) == 0) {
   1896 			CLR(tp->t_state, TS_TBLOCK);
   1897 			ttstart(tp);
   1898 		}
   1899 		/* Try to unblock remote output via hardware flow control. */
   1900 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
   1901 		    (*tp->t_hwiflow)(tp, 0) != 0)
   1902 			CLR(tp->t_state, TS_TBLOCK);
   1903 	}
   1904 	TTY_UNLOCK(tp);
   1905 	splx(s);
   1906 	return (error);
   1907 }
   1908 
   1909 /*
   1910  * Check the output queue on tp for space for a kernel message (from uprintf
   1911  * or tprintf).  Allow some space over the normal hiwater mark so we don't
   1912  * lose messages due to normal flow control, but don't let the tty run amok.
   1913  * Sleeps here are not interruptible, but we return prematurely if new signals
   1914  * arrive.
   1915  * Call with tty slock held.
   1916  */
   1917 static int
   1918 ttycheckoutq_wlock(struct tty *tp, int wait)
   1919 {
   1920 	int	hiwat, s, error;
   1921 
   1922 	hiwat = tp->t_hiwat;
   1923 	s = spltty();
   1924 	if (tp->t_outq.c_cc > hiwat + 200)
   1925 		while (tp->t_outq.c_cc > hiwat) {
   1926 			ttstart(tp);
   1927 			if (wait == 0) {
   1928 				splx(s);
   1929 				return (0);
   1930 			}
   1931 			SET(tp->t_state, TS_ASLEEP);
   1932 			error = ltsleep(&tp->t_outq, (PZERO - 1) | PCATCH,
   1933 			    "ttckoutq", hz, &tp->t_slock);
   1934 			if (error == EINTR)
   1935 				wait = 0;
   1936 		}
   1937 
   1938 	splx(s);
   1939 	return (1);
   1940 }
   1941 
   1942 int
   1943 ttycheckoutq(struct tty *tp, int wait)
   1944 {
   1945 	int	r, s;
   1946 
   1947 	s = spltty();
   1948 	TTY_LOCK(tp);
   1949 	r = ttycheckoutq_wlock(tp, wait);
   1950 	TTY_UNLOCK(tp);
   1951 	splx(s);
   1952 	return (r);
   1953 }
   1954 
   1955 /*
   1956  * Process a write call on a tty device.
   1957  */
   1958 int
   1959 ttwrite(struct tty *tp, struct uio *uio, int flag)
   1960 {
   1961 	u_char		*cp;
   1962 	struct proc	*p;
   1963 	int		cc, ce, i, hiwat, error, s;
   1964 	size_t		cnt;
   1965 	u_char		obuf[OBUFSIZ];
   1966 
   1967 	cp = NULL;
   1968 	hiwat = tp->t_hiwat;
   1969 	cnt = uio->uio_resid;
   1970 	error = 0;
   1971 	cc = 0;
   1972  loop:
   1973 	s = spltty();
   1974 	TTY_LOCK(tp);
   1975 	if (!CONNECTED(tp)) {
   1976 		if (ISSET(tp->t_state, TS_ISOPEN)) {
   1977 			TTY_UNLOCK(tp);
   1978 			splx(s);
   1979 			return (EIO);
   1980 		} else if (flag & IO_NDELAY) {
   1981 			TTY_UNLOCK(tp);
   1982 			splx(s);
   1983 			error = EWOULDBLOCK;
   1984 			goto out;
   1985 		} else {
   1986 			/* Sleep awaiting carrier. */
   1987 			error = ttysleep(tp,
   1988 			    &tp->t_rawq, TTIPRI | PCATCH | PNORELOCK, ttopen, 0);
   1989 			splx(s);
   1990 			if (error)
   1991 				goto out;
   1992 			goto loop;
   1993 		}
   1994 	}
   1995 	TTY_UNLOCK(tp);
   1996 	splx(s);
   1997 	/*
   1998 	 * Hang the process if it's in the background. XXXSMP
   1999 	 */
   2000 	p = curproc;
   2001 	if (isbackground(p, tp) &&
   2002 	    ISSET(tp->t_lflag, TOSTOP) && (p->p_sflag & PS_PPWAIT) == 0 &&
   2003 	    !sigismember(&p->p_sigctx.ps_sigignore, SIGTTOU) &&
   2004 	    !sigismember(&curlwp->l_sigmask, SIGTTOU)) {
   2005 		if (p->p_pgrp->pg_jobc == 0) {
   2006 			error = EIO;
   2007 			goto out;
   2008 		}
   2009 		mutex_enter(&proclist_mutex);
   2010 		pgsignal(p->p_pgrp, SIGTTOU, 1);
   2011 		mutex_exit(&proclist_mutex);
   2012 		s = spltty();
   2013 		TTY_LOCK(tp);
   2014 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH | PNORELOCK, ttybg, 0);
   2015 		splx(s);
   2016 		if (error)
   2017 			goto out;
   2018 		goto loop;
   2019 	}
   2020 	/*
   2021 	 * Process the user's data in at most OBUFSIZ chunks.  Perform any
   2022 	 * output translation.  Keep track of high water mark, sleep on
   2023 	 * overflow awaiting device aid in acquiring new space.
   2024 	 */
   2025 	while (uio->uio_resid > 0 || cc > 0) {
   2026 		if (ISSET(tp->t_lflag, FLUSHO)) {
   2027 			uio->uio_resid = 0;
   2028 			return (0);
   2029 		}
   2030 		if (tp->t_outq.c_cc > hiwat)
   2031 			goto ovhiwat;
   2032 		/*
   2033 		 * Grab a hunk of data from the user, unless we have some
   2034 		 * leftover from last time.
   2035 		 */
   2036 		if (cc == 0) {
   2037 			cc = min(uio->uio_resid, OBUFSIZ);
   2038 			cp = obuf;
   2039 			error = uiomove(cp, cc, uio);
   2040 			if (error) {
   2041 				cc = 0;
   2042 				goto out;
   2043 			}
   2044 		}
   2045 		/*
   2046 		 * If nothing fancy need be done, grab those characters we
   2047 		 * can handle without any of ttyoutput's processing and
   2048 		 * just transfer them to the output q.  For those chars
   2049 		 * which require special processing (as indicated by the
   2050 		 * bits in char_type), call ttyoutput.  After processing
   2051 		 * a hunk of data, look for FLUSHO so ^O's will take effect
   2052 		 * immediately.
   2053 		 */
   2054 		s = spltty();
   2055 		TTY_LOCK(tp);
   2056 		while (cc > 0) {
   2057 			if (!ISSET(tp->t_oflag, OPOST))
   2058 				ce = cc;
   2059 			else {
   2060 				ce = cc - scanc((u_int)cc, cp, char_type,
   2061 				    CCLASSMASK);
   2062 				/*
   2063 				 * If ce is zero, then we're processing
   2064 				 * a special character through ttyoutput.
   2065 				 */
   2066 				if (ce == 0) {
   2067 					tp->t_rocount = 0;
   2068 					if (ttyoutput(*cp, tp) >= 0) {
   2069 						/* out of space */
   2070 						TTY_UNLOCK(tp);
   2071 						splx(s);
   2072 						goto overfull;
   2073 					}
   2074 					cp++;
   2075 					cc--;
   2076 					if (ISSET(tp->t_lflag, FLUSHO) ||
   2077 					    tp->t_outq.c_cc > hiwat) {
   2078 						TTY_UNLOCK(tp);
   2079 						splx(s);
   2080 						goto ovhiwat;
   2081 					}
   2082 					continue;
   2083 				}
   2084 			}
   2085 			/*
   2086 			 * A bunch of normal characters have been found.
   2087 			 * Transfer them en masse to the output queue and
   2088 			 * continue processing at the top of the loop.
   2089 			 * If there are any further characters in this
   2090 			 * <= OBUFSIZ chunk, the first should be a character
   2091 			 * requiring special handling by ttyoutput.
   2092 			 */
   2093 			tp->t_rocount = 0;
   2094 			i = b_to_q(cp, ce, &tp->t_outq);
   2095 			ce -= i;
   2096 			tp->t_column += ce;
   2097 			cp += ce, cc -= ce, tk_nout += ce;
   2098 			tp->t_outcc += ce;
   2099 			if (i > 0) {
   2100 				/* out of space */
   2101 				TTY_UNLOCK(tp);
   2102 				splx(s);
   2103 				goto overfull;
   2104 			}
   2105 			if (ISSET(tp->t_lflag, FLUSHO) ||
   2106 			    tp->t_outq.c_cc > hiwat)
   2107 				break;
   2108 		}
   2109 		TTY_UNLOCK(tp);
   2110 		splx(s);
   2111 		ttstart(tp);
   2112 	}
   2113 
   2114  out:
   2115 	/*
   2116 	 * If cc is nonzero, we leave the uio structure inconsistent, as the
   2117 	 * offset and iov pointers have moved forward, but it doesn't matter
   2118 	 * (the call will either return short or restart with a new uio).
   2119 	 */
   2120 	uio->uio_resid += cc;
   2121 	return (error);
   2122 
   2123  overfull:
   2124 	/*
   2125 	 * Since we are using ring buffers, if we can't insert any more into
   2126 	 * the output queue, we can assume the ring is full and that someone
   2127 	 * forgot to set the high water mark correctly.  We set it and then
   2128 	 * proceed as normal.
   2129 	 */
   2130 	hiwat = tp->t_outq.c_cc - 1;
   2131 
   2132  ovhiwat:
   2133 	ttstart(tp);
   2134 	s = spltty();
   2135 	TTY_LOCK(tp);
   2136 	/*
   2137 	 * This can only occur if FLUSHO is set in t_lflag,
   2138 	 * or if ttstart/oproc is synchronous (or very fast).
   2139 	 */
   2140 	if (tp->t_outq.c_cc <= hiwat) {
   2141 		TTY_UNLOCK(tp);
   2142 		splx(s);
   2143 		goto loop;
   2144 	}
   2145 	if (flag & IO_NDELAY) {
   2146 		TTY_UNLOCK(tp);
   2147 		splx(s);
   2148 		error = EWOULDBLOCK;
   2149 		goto out;
   2150 	}
   2151 	SET(tp->t_state, TS_ASLEEP);
   2152 	error = ttysleep(tp, &tp->t_outq, TTOPRI | PCATCH | PNORELOCK, ttyout, 0);
   2153 	splx(s);
   2154 	if (error)
   2155 		goto out;
   2156 	goto loop;
   2157 }
   2158 
   2159 /*
   2160  * Rubout one character from the rawq of tp
   2161  * as cleanly as possible.
   2162  * Called with tty slock held.
   2163  */
   2164 void
   2165 ttyrub(int c, struct tty *tp)
   2166 {
   2167 	u_char	*cp;
   2168 	int	savecol, tabc, s;
   2169 
   2170 	if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
   2171 		return;
   2172 	CLR(tp->t_lflag, FLUSHO);
   2173 	if (ISSET(tp->t_lflag, ECHOE)) {
   2174 		if (tp->t_rocount == 0) {
   2175 			/*
   2176 			 * Screwed by ttwrite; retype
   2177 			 */
   2178 			ttyretype(tp);
   2179 			return;
   2180 		}
   2181 		if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
   2182 			ttyrubo(tp, 2);
   2183 		else {
   2184 			CLR(c, ~TTY_CHARMASK);
   2185 			switch (CCLASS(c)) {
   2186 			case ORDINARY:
   2187 				ttyrubo(tp, 1);
   2188 				break;
   2189 			case BACKSPACE:
   2190 			case CONTROL:
   2191 			case NEWLINE:
   2192 			case RETURN:
   2193 			case VTAB:
   2194 				if (ISSET(tp->t_lflag, ECHOCTL))
   2195 					ttyrubo(tp, 2);
   2196 				break;
   2197 			case TAB:
   2198 				if (tp->t_rocount < tp->t_rawq.c_cc) {
   2199 					ttyretype(tp);
   2200 					return;
   2201 				}
   2202 				s = spltty();
   2203 				savecol = tp->t_column;
   2204 				SET(tp->t_state, TS_CNTTB);
   2205 				SET(tp->t_lflag, FLUSHO);
   2206 				tp->t_column = tp->t_rocol;
   2207 				for (cp = firstc(&tp->t_rawq, &tabc); cp;
   2208 				    cp = nextc(&tp->t_rawq, cp, &tabc))
   2209 					ttyecho(tabc, tp);
   2210 				CLR(tp->t_lflag, FLUSHO);
   2211 				CLR(tp->t_state, TS_CNTTB);
   2212 				splx(s);
   2213 
   2214 				/* savecol will now be length of the tab. */
   2215 				savecol -= tp->t_column;
   2216 				tp->t_column += savecol;
   2217 				if (savecol > 8)
   2218 					savecol = 8;	/* overflow screw */
   2219 				while (--savecol >= 0)
   2220 					(void)ttyoutput('\b', tp);
   2221 				break;
   2222 			default:			/* XXX */
   2223 				(void)printf("ttyrub: would panic c = %d, "
   2224 				    "val = %d\n", c, CCLASS(c));
   2225 			}
   2226 		}
   2227 	} else if (ISSET(tp->t_lflag, ECHOPRT)) {
   2228 		if (!ISSET(tp->t_state, TS_ERASE)) {
   2229 			SET(tp->t_state, TS_ERASE);
   2230 			(void)ttyoutput('\\', tp);
   2231 		}
   2232 		ttyecho(c, tp);
   2233 	} else
   2234 		ttyecho(tp->t_cc[VERASE], tp);
   2235 	--tp->t_rocount;
   2236 }
   2237 
   2238 /*
   2239  * Back over cnt characters, erasing them.
   2240  * Called with tty slock held.
   2241  */
   2242 static void
   2243 ttyrubo(struct tty *tp, int cnt)
   2244 {
   2245 
   2246 	while (cnt-- > 0) {
   2247 		(void)ttyoutput('\b', tp);
   2248 		(void)ttyoutput(' ', tp);
   2249 		(void)ttyoutput('\b', tp);
   2250 	}
   2251 }
   2252 
   2253 /*
   2254  * ttyretype --
   2255  *	Reprint the rawq line.  Note, it is assumed that c_cc has already
   2256  *	been checked.
   2257  *
   2258  * Called with tty slock held.
   2259  */
   2260 void
   2261 ttyretype(struct tty *tp)
   2262 {
   2263 	u_char	*cp;
   2264 	int	s, c;
   2265 
   2266 	/* Echo the reprint character. */
   2267 	if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
   2268 		ttyecho(tp->t_cc[VREPRINT], tp);
   2269 
   2270 	(void)ttyoutput('\n', tp);
   2271 
   2272 	s = spltty();
   2273 	for (cp = firstc(&tp->t_canq, &c); cp; cp = nextc(&tp->t_canq, cp, &c))
   2274 		ttyecho(c, tp);
   2275 	for (cp = firstc(&tp->t_rawq, &c); cp; cp = nextc(&tp->t_rawq, cp, &c))
   2276 		ttyecho(c, tp);
   2277 	CLR(tp->t_state, TS_ERASE);
   2278 	splx(s);
   2279 
   2280 	tp->t_rocount = tp->t_rawq.c_cc;
   2281 	tp->t_rocol = 0;
   2282 }
   2283 
   2284 /*
   2285  * Echo a typed character to the terminal.
   2286  * Called with tty slock held.
   2287  */
   2288 static void
   2289 ttyecho(int c, struct tty *tp)
   2290 {
   2291 
   2292 	if (!ISSET(tp->t_state, TS_CNTTB))
   2293 		CLR(tp->t_lflag, FLUSHO);
   2294 	if ((!ISSET(tp->t_lflag, ECHO) &&
   2295 	    (!ISSET(tp->t_lflag, ECHONL) || c != '\n')) ||
   2296 	    ISSET(tp->t_lflag, EXTPROC))
   2297 		return;
   2298 	if (((ISSET(tp->t_lflag, ECHOCTL) &&
   2299 	    (ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n')) ||
   2300 	    ISSET(c, TTY_CHARMASK) == 0177)) {
   2301 		(void)ttyoutput('^', tp);
   2302 		CLR(c, ~TTY_CHARMASK);
   2303 		if (c == 0177)
   2304 			c = '?';
   2305 		else
   2306 			c += 'A' - 1;
   2307 	}
   2308 	(void)ttyoutput(c, tp);
   2309 }
   2310 
   2311 /*
   2312  * Wake up any readers on a tty.
   2313  * Called with tty slock held.
   2314  */
   2315 void
   2316 ttwakeup(struct tty *tp)
   2317 {
   2318 
   2319 	selnotify(&tp->t_rsel, NOTE_SUBMIT);
   2320 	if (ISSET(tp->t_state, TS_ASYNC)) {
   2321 		mutex_enter(&proclist_mutex);
   2322 		pgsignal(tp->t_pgrp, SIGIO, tp->t_session != NULL);
   2323 		mutex_exit(&proclist_mutex);
   2324 	}
   2325 	wakeup((caddr_t)&tp->t_rawq);
   2326 }
   2327 
   2328 /*
   2329  * Look up a code for a specified speed in a conversion table;
   2330  * used by drivers to map software speed values to hardware parameters.
   2331  */
   2332 int
   2333 ttspeedtab(int speed, const struct speedtab *table)
   2334 {
   2335 
   2336 	for (; table->sp_speed != -1; table++)
   2337 		if (table->sp_speed == speed)
   2338 			return (table->sp_code);
   2339 	return (-1);
   2340 }
   2341 
   2342 /*
   2343  * Set tty hi and low water marks.
   2344  *
   2345  * Try to arrange the dynamics so there's about one second
   2346  * from hi to low water.
   2347  */
   2348 void
   2349 ttsetwater(struct tty *tp)
   2350 {
   2351 	int	cps, x;
   2352 
   2353 #define	CLAMP(x, h, l)	((x) > h ? h : ((x) < l) ? l : (x))
   2354 
   2355 	cps = tp->t_ospeed / 10;
   2356 	tp->t_lowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
   2357 	x += cps;
   2358 	x = CLAMP(x, TTMAXHIWAT, TTMINHIWAT);
   2359 	tp->t_hiwat = roundup(x, CBSIZE);
   2360 #undef	CLAMP
   2361 }
   2362 
   2363 /*
   2364  * Report on state of foreground process group.
   2365  * Call with tty slock held.
   2366  * XXXSMP locking.
   2367  */
   2368 void
   2369 ttyinfo(struct tty *tp, int fromsig)
   2370 {
   2371 	struct lwp	*l;
   2372 	struct proc	*p, *pick = NULL;
   2373 	struct timeval	utime, stime;
   2374 	int		tmp;
   2375 	const char	*msg;
   2376 
   2377 	if (ttycheckoutq_wlock(tp, 0) == 0)
   2378 		return;
   2379 
   2380 	if (tp->t_session == NULL)
   2381 		msg = "not a controlling terminal\n";
   2382 	else if (tp->t_pgrp == NULL)
   2383 		msg = "no foreground process group\n";
   2384 	else if ((p = LIST_FIRST(&tp->t_pgrp->pg_members)) == NULL)
   2385 		msg = "empty foreground process group\n";
   2386 	else {
   2387 		/* Pick interesting process. */
   2388 		for (; p != NULL; p = LIST_NEXT(p, p_pglist))
   2389 			if (proc_compare(pick, p))
   2390 				pick = p;
   2391 		if (fromsig &&
   2392 		    (SIGACTION_PS(pick->p_sigacts, SIGINFO).sa_flags &
   2393 		    SA_NOKERNINFO))
   2394 			return;
   2395 		msg = NULL;
   2396 	}
   2397 
   2398 	/* Print load average. */
   2399 	tmp = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
   2400 	ttyprintf_nolock(tp, "load: %d.%02d ", tmp / 100, tmp % 100);
   2401 
   2402 	if (pick == NULL) {
   2403 		ttyprintf_nolock(tp, msg);
   2404 		tp->t_rocount = 0; /* so pending input will be retyped if BS */
   2405 		return;
   2406 	}
   2407 
   2408 	ttyprintf_nolock(tp, " cmd: %s %d [", pick->p_comm, pick->p_pid);
   2409 	LIST_FOREACH(l, &pick->p_lwps, l_sibling)
   2410 	    ttyprintf_nolock(tp, "%s%s",
   2411 	    l->l_stat == LSONPROC ? "running" :
   2412 	    l->l_stat == LSRUN ? "runnable" :
   2413 	    l->l_wmesg ? l->l_wmesg : "iowait",
   2414 		(LIST_NEXT(l, l_sibling) != NULL) ? " " : "] ");
   2415 
   2416 	mutex_enter(&pick->p_smutex);
   2417 	calcru(pick, &utime, &stime, NULL, NULL);
   2418 	mutex_exit(&pick->p_smutex);
   2419 
   2420 	/* Round up and print user time. */
   2421 	utime.tv_usec += 5000;
   2422 	if (utime.tv_usec >= 1000000) {
   2423 		utime.tv_sec += 1;
   2424 		utime.tv_usec -= 1000000;
   2425 	}
   2426 	ttyprintf_nolock(tp, "%ld.%02ldu ", (long int)utime.tv_sec,
   2427 	    (long int)utime.tv_usec / 10000);
   2428 
   2429 	/* Round up and print system time. */
   2430 	stime.tv_usec += 5000;
   2431 	if (stime.tv_usec >= 1000000) {
   2432 		stime.tv_sec += 1;
   2433 		stime.tv_usec -= 1000000;
   2434 	}
   2435 	ttyprintf_nolock(tp, "%ld.%02lds ", (long int)stime.tv_sec,
   2436 	    (long int)stime.tv_usec / 10000);
   2437 
   2438 #define	pgtok(a)	(((u_long) ((a) * PAGE_SIZE) / 1024))
   2439 	/* Print percentage CPU. */
   2440 	tmp = (pick->p_pctcpu * 10000 + FSCALE / 2) >> FSHIFT;
   2441 	ttyprintf_nolock(tp, "%d%% ", tmp / 100);
   2442 
   2443 	/* Print resident set size. */
   2444 	if (pick->p_stat == SIDL || P_ZOMBIE(pick))
   2445 		tmp = 0;
   2446 	else {
   2447 		struct vmspace *vm = pick->p_vmspace;
   2448 		tmp = pgtok(vm_resident_count(vm));
   2449 	}
   2450 	ttyprintf_nolock(tp, "%dk\n", tmp);
   2451 	tp->t_rocount = 0;	/* so pending input will be retyped if BS */
   2452 }
   2453 
   2454 /*
   2455  * Returns 1 if p2 is "better" than p1
   2456  *
   2457  * The algorithm for picking the "interesting" process is thus:
   2458  *
   2459  *	1) Only foreground processes are eligible - implied.
   2460  *	2) Runnable processes are favored over anything else.  The runner
   2461  *	   with the highest CPU utilization is picked (p_estcpu).  Ties are
   2462  *	   broken by picking the highest pid.
   2463  *	3) The sleeper with the shortest sleep time is next.  With ties,
   2464  *	   we pick out just "short-term" sleepers (P_SINTR == 0).
   2465  *	4) Further ties are broken by picking the highest pid.
   2466  *
   2467  * XXXSMP
   2468  */
   2469 #define	ISRUN(p)	((p)->p_nrlwps > 0)
   2470 #define	TESTAB(a, b)	((a)<<1 | (b))
   2471 #define	ONLYA	2
   2472 #define	ONLYB	1
   2473 #define	BOTH	3
   2474 
   2475 static int
   2476 proc_compare(struct proc *p1, struct proc *p2)
   2477 {
   2478 
   2479 	if (p1 == NULL)
   2480 		return (1);
   2481 	/*
   2482 	 * see if at least one of them is runnable
   2483 	 */
   2484 	switch (TESTAB(ISRUN(p1), ISRUN(p2))) {
   2485 	case ONLYA:
   2486 		return (0);
   2487 	case ONLYB:
   2488 		return (1);
   2489 	case BOTH:
   2490 		/*
   2491 		 * tie - favor one with highest recent CPU utilization
   2492 		 */
   2493 		if (p2->p_estcpu > p1->p_estcpu)
   2494 			return (1);
   2495 		if (p1->p_estcpu > p2->p_estcpu)
   2496 			return (0);
   2497 		return (p2->p_pid > p1->p_pid);	/* tie - return highest pid */
   2498 	}
   2499 	/*
   2500  	 * weed out zombies
   2501 	 */
   2502 	switch (TESTAB(P_ZOMBIE(p1), P_ZOMBIE(p2))) {
   2503 	case ONLYA:
   2504 		return (1);
   2505 	case ONLYB:
   2506 		return (0);
   2507 	case BOTH:
   2508 		return (p2->p_pid > p1->p_pid);	/* tie - return highest pid */
   2509 	}
   2510 #if 0 /* XXX NJWLWP */
   2511 	/*
   2512 	 * pick the one with the smallest sleep time
   2513 	 */
   2514 	if (p2->p_slptime > p1->p_slptime)
   2515 		return (0);
   2516 	if (p1->p_slptime > p2->p_slptime)
   2517 		return (1);
   2518 	/*
   2519 	 * favor one sleeping in a non-interruptible sleep
   2520 	 */
   2521 	if (p1->p_flag & P_SINTR && (p2->p_flag & P_SINTR) == 0)
   2522 		return (1);
   2523 	if (p2->p_flag & P_SINTR && (p1->p_flag & P_SINTR) == 0)
   2524 		return (0);
   2525 #endif
   2526 	return (p2->p_pid > p1->p_pid);		/* tie - return highest pid */
   2527 }
   2528 
   2529 /*
   2530  * Output char to tty; console putchar style.
   2531  * Can be called with tty lock held through kprintf() machinery..
   2532  */
   2533 int
   2534 tputchar(int c, int flags, struct tty *tp)
   2535 {
   2536 	int s, r = 0;
   2537 
   2538 	s = spltty();
   2539 	if ((flags & NOLOCK) == 0)
   2540 		simple_lock(&tp->t_slock);
   2541 	if (!CONNECTED(tp)) {
   2542 		r = -1;
   2543 		goto out;
   2544 	}
   2545 	if (c == '\n')
   2546 		(void)ttyoutput('\r', tp);
   2547 	(void)ttyoutput(c, tp);
   2548 	ttstart(tp);
   2549 out:
   2550 	if ((flags & NOLOCK) == 0)
   2551 		TTY_UNLOCK(tp);
   2552 	splx(s);
   2553 	return (r);
   2554 }
   2555 
   2556 /*
   2557  * Sleep on chan, returning ERESTART if tty changed while we napped and
   2558  * returning any errors (e.g. EINTR/ETIMEDOUT) reported by tsleep.  If
   2559  * the tty is revoked, restarting a pending call will redo validation done
   2560  * at the start of the call.
   2561  *
   2562  * Must be called with the tty slock held.
   2563  */
   2564 int
   2565 ttysleep(struct tty *tp, void *chan, int pri, const char *wmesg, int timo)
   2566 {
   2567 	int	error;
   2568 	short	gen;
   2569 
   2570 	gen = tp->t_gen;
   2571 	if ((error = ltsleep(chan, pri, wmesg, timo, &tp->t_slock)) != 0)
   2572 		return (error);
   2573 	return (tp->t_gen == gen ? 0 : ERESTART);
   2574 }
   2575 
   2576 /*
   2577  * Attach a tty to the tty list.
   2578  *
   2579  * This should be called ONLY once per real tty (including pty's).
   2580  * eg, on the sparc, the keyboard and mouse have struct tty's that are
   2581  * distinctly NOT usable as tty's, and thus should not be attached to
   2582  * the ttylist.  This is why this call is not done from ttymalloc().
   2583  *
   2584  * Device drivers should attach tty's at a similar time that they are
   2585  * ttymalloc()'ed, or, for the case of statically allocated struct tty's
   2586  * either in the attach or (first) open routine.
   2587  */
   2588 void
   2589 tty_attach(struct tty *tp)
   2590 {
   2591 
   2592 	simple_lock(&ttylist_slock);
   2593 	TAILQ_INSERT_TAIL(&ttylist, tp, tty_link);
   2594 	++tty_count;
   2595 	simple_unlock(&ttylist_slock);
   2596 }
   2597 
   2598 /*
   2599  * Remove a tty from the tty list.
   2600  */
   2601 void
   2602 tty_detach(struct tty *tp)
   2603 {
   2604 
   2605 	simple_lock(&ttylist_slock);
   2606 	--tty_count;
   2607 #ifdef DIAGNOSTIC
   2608 	if (tty_count < 0)
   2609 		panic("tty_detach: tty_count < 0");
   2610 #endif
   2611 	TAILQ_REMOVE(&ttylist, tp, tty_link);
   2612 	simple_unlock(&ttylist_slock);
   2613 }
   2614 
   2615 /*
   2616  * Allocate a tty structure and its associated buffers.
   2617  */
   2618 struct tty *
   2619 ttymalloc(void)
   2620 {
   2621 	struct tty	*tp;
   2622 
   2623 	tp = pool_get(&tty_pool, PR_WAITOK);
   2624 	memset(tp, 0, sizeof(*tp));
   2625 	simple_lock_init(&tp->t_slock);
   2626 	callout_init(&tp->t_rstrt_ch);
   2627 	/* XXX: default to 1024 chars for now */
   2628 	clalloc(&tp->t_rawq, 1024, 1);
   2629 	clalloc(&tp->t_canq, 1024, 1);
   2630 	/* output queue doesn't need quoting */
   2631 	clalloc(&tp->t_outq, 1024, 0);
   2632 	/* Set default line discipline. */
   2633 	tp->t_linesw = ttyldisc_default();
   2634 	return (tp);
   2635 }
   2636 
   2637 /*
   2638  * Free a tty structure and its buffers.
   2639  *
   2640  * Be sure to call tty_detach() for any tty that has been
   2641  * tty_attach()ed.
   2642  */
   2643 void
   2644 ttyfree(struct tty *tp)
   2645 {
   2646 
   2647 	callout_stop(&tp->t_rstrt_ch);
   2648 	ttyldisc_release(tp->t_linesw);
   2649 	clfree(&tp->t_rawq);
   2650 	clfree(&tp->t_canq);
   2651 	clfree(&tp->t_outq);
   2652 	pool_put(&tty_pool, tp);
   2653 }
   2654 
   2655 /*
   2656  * ttyprintf_nolock: send a message to a specific tty, without locking.
   2657  *
   2658  * => should be used only by tty driver or anything that knows the
   2659  *    underlying tty will not be revoked(2)'d away.  [otherwise,
   2660  *    use tprintf]
   2661  */
   2662 static void
   2663 ttyprintf_nolock(struct tty *tp, const char *fmt, ...)
   2664 {
   2665 	va_list ap;
   2666 
   2667 	/* No mutex needed; going to process TTY. */
   2668 	va_start(ap, fmt);
   2669 	kprintf(fmt, TOTTY|NOLOCK, tp, NULL, ap);
   2670 	va_end(ap);
   2671 }
   2672