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