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