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