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