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