Home | History | Annotate | Line # | Download | only in kern
tty.c revision 1.269
      1 /*	$NetBSD: tty.c,v 1.269 2015/10/18 15:58:23 christos Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2008 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     17  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     18  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     19  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     26  * POSSIBILITY OF SUCH DAMAGE.
     27  */
     28 
     29 /*-
     30  * Copyright (c) 1982, 1986, 1990, 1991, 1993
     31  *	The Regents of the University of California.  All rights reserved.
     32  * (c) UNIX System Laboratories, Inc.
     33  * All or some portions of this file are derived from material licensed
     34  * to the University of California by American Telephone and Telegraph
     35  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     36  * the permission of UNIX System Laboratories, Inc.
     37  *
     38  * Redistribution and use in source and binary forms, with or without
     39  * modification, are permitted provided that the following conditions
     40  * are met:
     41  * 1. Redistributions of source code must retain the above copyright
     42  *    notice, this list of conditions and the following disclaimer.
     43  * 2. Redistributions in binary form must reproduce the above copyright
     44  *    notice, this list of conditions and the following disclaimer in the
     45  *    documentation and/or other materials provided with the distribution.
     46  * 3. Neither the name of the University nor the names of its contributors
     47  *    may be used to endorse or promote products derived from this software
     48  *    without specific prior written permission.
     49  *
     50  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     53  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     60  * SUCH DAMAGE.
     61  *
     62  *	@(#)tty.c	8.13 (Berkeley) 1/9/95
     63  */
     64 
     65 #include <sys/cdefs.h>
     66 __KERNEL_RCSID(0, "$NetBSD: tty.c,v 1.269 2015/10/18 15:58:23 christos Exp $");
     67 
     68 #ifdef _KERNEL_OPT
     69 #include "opt_compat_netbsd.h"
     70 #endif
     71 
     72 #define TTY_ALLOW_PRIVATE
     73 
     74 #include <sys/param.h>
     75 #include <sys/systm.h>
     76 #include <sys/ioctl.h>
     77 #include <sys/proc.h>
     78 #define	TTYDEFCHARS
     79 #include <sys/tty.h>
     80 #undef	TTYDEFCHARS
     81 #include <sys/file.h>
     82 #include <sys/conf.h>
     83 #include <sys/cpu.h>
     84 #include <sys/dkstat.h>
     85 #include <sys/uio.h>
     86 #include <sys/kernel.h>
     87 #include <sys/vnode.h>
     88 #include <sys/syslog.h>
     89 #include <sys/kmem.h>
     90 #include <sys/signalvar.h>
     91 #include <sys/resourcevar.h>
     92 #include <sys/poll.h>
     93 #include <sys/kprintf.h>
     94 #include <sys/namei.h>
     95 #include <sys/sysctl.h>
     96 #include <sys/kauth.h>
     97 #include <sys/intr.h>
     98 #include <sys/ioctl_compat.h>
     99 #include <sys/module.h>
    100 #include <sys/bitops.h>
    101 
    102 #ifdef COMPAT_60
    103 #include <compat/sys/ttycom.h>
    104 #endif /* COMPAT_60 */
    105 
    106 static int	ttnread(struct tty *);
    107 static void	ttyblock(struct tty *);
    108 static void	ttyecho(int, struct tty *);
    109 static void	ttyrubo(struct tty *, int);
    110 static void	ttyprintf_nolock(struct tty *, const char *fmt, ...)
    111     __printflike(2, 3);
    112 static int	proc_compare_wrapper(struct proc *, struct proc *);
    113 static void	ttysigintr(void *);
    114 
    115 /* Symbolic sleep message strings. */
    116 const char	ttclos[] = "ttycls";
    117 const char	ttopen[] = "ttyopn";
    118 const char	ttybg[] = "ttybg";
    119 const char	ttyin[] = "ttyin";
    120 const char	ttyout[] = "ttyout";
    121 
    122 /*
    123  * Used to determine whether we still have a connection.  This is true in
    124  * one of 3 cases:
    125  * 1) We have carrier.
    126  * 2) It's a locally attached terminal, and we are therefore ignoring carrier.
    127  * 3) We're using a flow control mechanism that overloads the carrier signal.
    128  */
    129 #define	CONNECTED(tp)	(ISSET(tp->t_state, TS_CARR_ON) ||	\
    130 			 ISSET(tp->t_cflag, CLOCAL | MDMBUF))
    131 
    132 /*
    133  * Table with character classes and parity. The 8th bit indicates parity,
    134  * the 7th bit indicates the character is an alphameric or underscore (for
    135  * ALTWERASE), and the low 6 bits indicate delay type.  If the low 6 bits
    136  * are 0 then the character needs no special processing on output; classes
    137  * other than 0 might be translated or (not currently) require delays.
    138  */
    139 #define	E	0x00	/* Even parity. */
    140 #define	O	0x80	/* Odd parity. */
    141 #define	PARITY(c)	(char_type[c] & O)
    142 
    143 #define	ALPHA	0x40	/* Alpha or underscore. */
    144 #define	ISALPHA(c)	(char_type[(c) & TTY_CHARMASK] & ALPHA)
    145 
    146 #define	CCLASSMASK	0x3f
    147 #define	CCLASS(c)	(char_type[c] & CCLASSMASK)
    148 
    149 #define	BS	BACKSPACE
    150 #define	CC	CONTROL
    151 #define	CR	RETURN
    152 #define	NA	ORDINARY | ALPHA
    153 #define	NL	NEWLINE
    154 #define	NO	ORDINARY
    155 #define	TB	TAB
    156 #define	VT	VTAB
    157 
    158 unsigned char const char_type[] = {
    159 	E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC,	/* nul - bel */
    160 	O|BS, E|TB, E|NL, O|CC, E|VT, O|CR, O|CC, E|CC,	/* bs - si */
    161 	O|CC, E|CC, E|CC, O|CC, E|CC, O|CC, O|CC, E|CC,	/* dle - etb */
    162 	E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC,	/* can - us */
    163 	O|NO, E|NO, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO,	/* sp - ' */
    164 	E|NO, O|NO, O|NO, E|NO, O|NO, E|NO, E|NO, O|NO,	/* ( - / */
    165 	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA,	/* 0 - 7 */
    166 	O|NA, E|NA, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO,	/* 8 - ? */
    167 	O|NO, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA,	/* @ - G */
    168 	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA,	/* H - O */
    169 	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA,	/* P - W */
    170 	O|NA, E|NA, E|NA, O|NO, E|NO, O|NO, O|NO, O|NA,	/* X - _ */
    171 	E|NO, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA,	/* ` - g */
    172 	O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA,	/* h - o */
    173 	O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA,	/* p - w */
    174 	E|NA, O|NA, O|NA, E|NO, O|NO, E|NO, E|NO, O|CC,	/* x - del */
    175 	/*
    176 	 * Meta chars; should be settable per character set;
    177 	 * for now, treat them all as normal characters.
    178 	 */
    179 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    180 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    181 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    182 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    183 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    184 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    185 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    186 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    187 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    188 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    189 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    190 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    191 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    192 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    193 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    194 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
    195 };
    196 #undef	BS
    197 #undef	CC
    198 #undef	CR
    199 #undef	NA
    200 #undef	NL
    201 #undef	NO
    202 #undef	TB
    203 #undef	VT
    204 
    205 static struct ttylist_head tty_sigqueue = TAILQ_HEAD_INITIALIZER(tty_sigqueue);
    206 static void *tty_sigsih;
    207 
    208 struct ttylist_head ttylist = TAILQ_HEAD_INITIALIZER(ttylist);
    209 int tty_count;
    210 kmutex_t tty_lock;
    211 krwlock_t ttcompat_lock;
    212 int (*ttcompatvec)(struct tty *, u_long, void *, int, struct lwp *);
    213 
    214 uint64_t tk_cancc;
    215 uint64_t tk_nin;
    216 uint64_t tk_nout;
    217 uint64_t tk_rawcc;
    218 
    219 static kauth_listener_t tty_listener;
    220 
    221 #define	TTY_MINQSIZE	0x00400
    222 #define	TTY_MAXQSIZE	0x10000
    223 int tty_qsize = TTY_MINQSIZE;
    224 
    225 static int
    226 tty_get_qsize(int *qsize, int newsize)
    227 {
    228 	newsize = 1 << ilog2(newsize);	/* Make it a power of two */
    229 
    230 	if (newsize < TTY_MINQSIZE || newsize > TTY_MAXQSIZE)
    231 		return EINVAL;
    232 
    233 	*qsize = newsize;
    234 	return 0;
    235 }
    236 
    237 static int
    238 tty_set_qsize(struct tty *tp, int newsize)
    239 {
    240 	struct clist rawq, canq, outq;
    241 	struct clist orawq, ocanq, ooutq;
    242 
    243 	clalloc(&rawq, newsize, 1);
    244 	clalloc(&canq, newsize, 1);
    245 	clalloc(&outq, newsize, 0);
    246 
    247 	mutex_spin_enter(&tty_lock);
    248 
    249 	if (tp->t_outq.c_cc != 0) {
    250 		mutex_spin_exit(&tty_lock);
    251 		clfree(&rawq);
    252 		clfree(&canq);
    253 		clfree(&outq);
    254 		return EBUSY;
    255 	}
    256 
    257 	orawq = tp->t_rawq;
    258 	ocanq = tp->t_canq;
    259 	ooutq = tp->t_outq;
    260 
    261 	tp->t_qsize = newsize;
    262 	tp->t_rawq = rawq;
    263 	tp->t_canq = canq;
    264 	tp->t_outq = outq;
    265 
    266 	ttsetwater(tp);
    267 
    268 	mutex_spin_exit(&tty_lock);
    269 
    270 	clfree(&orawq);
    271 	clfree(&ocanq);
    272 	clfree(&ooutq);
    273 
    274 	return 0;
    275 }
    276 
    277 static int
    278 sysctl_kern_tty_qsize(SYSCTLFN_ARGS)
    279 {
    280 	int newsize;
    281 	int error;
    282 	struct sysctlnode node;
    283 	node = *rnode;
    284 	node.sysctl_data = &newsize;
    285 
    286 	newsize = tty_qsize;
    287 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    288 	if (error || newp == NULL)
    289 		return error;
    290 
    291 
    292 	return tty_get_qsize(&tty_qsize, newsize);
    293 }
    294 
    295 static void
    296 sysctl_kern_tty_setup(void)
    297 {
    298 	const struct sysctlnode *rnode, *cnode;
    299 	struct sysctllog *kern_tkstat_sysctllog, *kern_tty_sysctllog;
    300 
    301 	kern_tkstat_sysctllog = NULL;
    302 	sysctl_createv(&kern_tkstat_sysctllog, 0, NULL, NULL,
    303 		       CTLFLAG_PERMANENT,
    304 		       CTLTYPE_NODE, "tkstat",
    305 		       SYSCTL_DESCR("Number of characters sent and and "
    306 				    "received on ttys"),
    307 		       NULL, 0, NULL, 0,
    308 		       CTL_KERN, KERN_TKSTAT, CTL_EOL);
    309 
    310 	sysctl_createv(&kern_tkstat_sysctllog, 0, NULL, NULL,
    311 		       CTLFLAG_PERMANENT,
    312 		       CTLTYPE_QUAD, "nin",
    313 		       SYSCTL_DESCR("Total number of tty input characters"),
    314 		       NULL, 0, &tk_nin, 0,
    315 		       CTL_KERN, KERN_TKSTAT, KERN_TKSTAT_NIN, CTL_EOL);
    316 	sysctl_createv(&kern_tkstat_sysctllog, 0, NULL, NULL,
    317 		       CTLFLAG_PERMANENT,
    318 		       CTLTYPE_QUAD, "nout",
    319 		       SYSCTL_DESCR("Total number of tty output characters"),
    320 		       NULL, 0, &tk_nout, 0,
    321 		       CTL_KERN, KERN_TKSTAT, KERN_TKSTAT_NOUT, CTL_EOL);
    322 	sysctl_createv(&kern_tkstat_sysctllog, 0, NULL, NULL,
    323 		       CTLFLAG_PERMANENT,
    324 		       CTLTYPE_QUAD, "cancc",
    325 		       SYSCTL_DESCR("Number of canonical tty input characters"),
    326 		       NULL, 0, &tk_cancc, 0,
    327 		       CTL_KERN, KERN_TKSTAT, KERN_TKSTAT_CANCC, CTL_EOL);
    328 	sysctl_createv(&kern_tkstat_sysctllog, 0, NULL, NULL,
    329 		       CTLFLAG_PERMANENT,
    330 		       CTLTYPE_QUAD, "rawcc",
    331 		       SYSCTL_DESCR("Number of raw tty input characters"),
    332 		       NULL, 0, &tk_rawcc, 0,
    333 		       CTL_KERN, KERN_TKSTAT, KERN_TKSTAT_RAWCC, CTL_EOL);
    334 
    335 	kern_tty_sysctllog = NULL;
    336 	sysctl_createv(&kern_tty_sysctllog, 0, NULL, &rnode,
    337 		       CTLFLAG_PERMANENT,
    338 		       CTLTYPE_NODE, "tty", NULL,
    339 		       NULL, 0, NULL, 0,
    340 		       CTL_KERN, CTL_CREATE, CTL_EOL);
    341 	sysctl_createv(&kern_tty_sysctllog, 0, &rnode, &cnode,
    342 		       CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
    343 		       CTLTYPE_INT, "qsize",
    344 		       SYSCTL_DESCR("TTY input and output queue size"),
    345 		       sysctl_kern_tty_qsize, 0, &tty_qsize, 0,
    346 		       CTL_CREATE, CTL_EOL);
    347 }
    348 
    349 int
    350 ttyopen(struct tty *tp, int dialout, int nonblock)
    351 {
    352 	int	error;
    353 
    354 	error = 0;
    355 
    356 	mutex_spin_enter(&tty_lock);
    357 
    358 	if (dialout) {
    359 		/*
    360 		 * If the device is already open for non-dialout, fail.
    361 		 * Otherwise, set TS_DIALOUT to block any pending non-dialout
    362 		 * opens.
    363 		 */
    364 		if (ISSET(tp->t_state, TS_ISOPEN) &&
    365 		    !ISSET(tp->t_state, TS_DIALOUT)) {
    366 			error = EBUSY;
    367 			goto out;
    368 		}
    369 		SET(tp->t_state, TS_DIALOUT);
    370 	} else {
    371 		if (!nonblock) {
    372 			/*
    373 			 * Wait for carrier.  Also wait for any dialout
    374 			 * processes to close the tty first.
    375 			 */
    376 			while (ISSET(tp->t_state, TS_DIALOUT) ||
    377 			       !CONNECTED(tp)) {
    378 				tp->t_wopen++;
    379 				error = ttysleep(tp, &tp->t_rawcv, true, 0);
    380 				tp->t_wopen--;
    381 				if (error)
    382 					goto out;
    383 			}
    384 		} else {
    385 			/*
    386 			 * Don't allow a non-blocking non-dialout open if the
    387 			 * device is already open for dialout.
    388 			 */
    389 			if (ISSET(tp->t_state, TS_DIALOUT)) {
    390 				error = EBUSY;
    391 				goto out;
    392 			}
    393 		}
    394 	}
    395 
    396 out:
    397 	mutex_spin_exit(&tty_lock);
    398 	return (error);
    399 }
    400 
    401 /*
    402  * Initial open of tty, or (re)entry to standard tty line discipline.
    403  */
    404 int
    405 ttylopen(dev_t device, struct tty *tp)
    406 {
    407 
    408 	mutex_spin_enter(&tty_lock);
    409 	tp->t_dev = device;
    410 	if (!ISSET(tp->t_state, TS_ISOPEN)) {
    411 		SET(tp->t_state, TS_ISOPEN);
    412 		memset(&tp->t_winsize, 0, sizeof(tp->t_winsize));
    413 		tp->t_flags = 0;
    414 	}
    415 	mutex_spin_exit(&tty_lock);
    416 	if (tp->t_qsize != tty_qsize)
    417 		tty_set_qsize(tp, tty_qsize);
    418 	return (0);
    419 }
    420 
    421 /*
    422  * Handle close() on a tty line: flush and set to initial state,
    423  * bumping generation number so that pending read/write calls
    424  * can detect recycling of the tty.
    425  */
    426 int
    427 ttyclose(struct tty *tp)
    428 {
    429 	extern struct tty *constty;	/* Temporary virtual console. */
    430 	struct session *sess;
    431 
    432 	mutex_spin_enter(&tty_lock);
    433 
    434 	if (constty == tp)
    435 		constty = NULL;
    436 
    437 	ttyflush(tp, FREAD | FWRITE);
    438 
    439 	tp->t_gen++;
    440 	tp->t_pgrp = NULL;
    441 	tp->t_state = 0;
    442 	sess = tp->t_session;
    443 	tp->t_session = NULL;
    444 
    445 	mutex_spin_exit(&tty_lock);
    446 
    447 	if (sess != NULL) {
    448 		mutex_enter(proc_lock);
    449 		/* Releases proc_lock. */
    450 		proc_sessrele(sess);
    451 	}
    452 	return (0);
    453 }
    454 
    455 #define	FLUSHQ(q) {							\
    456 	if ((q)->c_cc)							\
    457 		ndflush(q, (q)->c_cc);					\
    458 }
    459 
    460 /*
    461  * This macro is used in canonical mode input processing, where a read
    462  * request shall not return unless a 'line delimiter' ('\n') or 'break'
    463  * (EOF, EOL, EOL2) character (or a signal) has been received. As EOL2
    464  * is an extension to the POSIX.1 defined set of special characters,
    465  * recognize it only if IEXTEN is set in the set of local flags.
    466  */
    467 #define	TTBREAKC(c, lflg)						\
    468 	((c) == '\n' || (((c) == cc[VEOF] || (c) == cc[VEOL] ||		\
    469 	((c) == cc[VEOL2] && ISSET(lflg, IEXTEN))) && (c) != _POSIX_VDISABLE))
    470 
    471 
    472 
    473 /*
    474  * ttyinput() helper.
    475  * Call with the tty lock held.
    476  */
    477 /* XXX static */ int
    478 ttyinput_wlock(int c, struct tty *tp)
    479 {
    480 	int	iflag, lflag, i, error;
    481 	u_char	*cc;
    482 
    483 	KASSERT(mutex_owned(&tty_lock));
    484 
    485 	/*
    486 	 * If input is pending take it first.
    487 	 */
    488 	lflag = tp->t_lflag;
    489 	if (ISSET(lflag, PENDIN))
    490 		ttypend(tp);
    491 	/*
    492 	 * Gather stats.
    493 	 */
    494 	if (ISSET(lflag, ICANON)) {
    495 		++tk_cancc;
    496 		++tp->t_cancc;
    497 	} else {
    498 		++tk_rawcc;
    499 		++tp->t_rawcc;
    500 	}
    501 	++tk_nin;
    502 
    503 	cc = tp->t_cc;
    504 
    505 	/*
    506 	 * Handle exceptional conditions (break, parity, framing).
    507 	 */
    508 	iflag = tp->t_iflag;
    509 	if ((error = (ISSET(c, TTY_ERRORMASK))) != 0) {
    510 		CLR(c, TTY_ERRORMASK);
    511 		if (ISSET(error, TTY_FE) && c == 0) {		/* Break. */
    512 			if (ISSET(iflag, IGNBRK))
    513 				return (0);
    514 			else if (ISSET(iflag, BRKINT)) {
    515 				ttyflush(tp, FREAD | FWRITE);
    516 				ttysig(tp, TTYSIG_PG1, SIGINT);
    517 				return (0);
    518 			} else if (ISSET(iflag, PARMRK))
    519 				goto parmrk;
    520 		} else if ((ISSET(error, TTY_PE) && ISSET(iflag, INPCK)) ||
    521 		    ISSET(error, TTY_FE)) {
    522 			if (ISSET(iflag, IGNPAR))
    523 				return (0);
    524 			else if (ISSET(iflag, PARMRK)) {
    525  parmrk:			(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
    526 				(void)putc(0    | TTY_QUOTE, &tp->t_rawq);
    527 				(void)putc(c    | TTY_QUOTE, &tp->t_rawq);
    528 				return (0);
    529 			} else
    530 				c = 0;
    531 		}
    532 	} else if (c == 0377 &&
    533 	    ISSET(iflag, ISTRIP|IGNPAR|INPCK|PARMRK) == (INPCK|PARMRK)) {
    534 		/* "Escape" a valid character of '\377'. */
    535 		(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
    536 		(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
    537 		goto endcase;
    538 	}
    539 
    540 	/*
    541 	 * In tandem mode, check high water mark.
    542 	 */
    543 	if (ISSET(iflag, IXOFF) || ISSET(tp->t_cflag, CHWFLOW))
    544 		ttyblock(tp);
    545 	if (!ISSET(tp->t_state, TS_TYPEN) && ISSET(iflag, ISTRIP))
    546 		CLR(c, 0x80);
    547 	if (!ISSET(lflag, EXTPROC)) {
    548 		/*
    549 		 * Check for literal nexting very first
    550 		 */
    551 		if (ISSET(tp->t_state, TS_LNCH)) {
    552 			SET(c, TTY_QUOTE);
    553 			CLR(tp->t_state, TS_LNCH);
    554 		}
    555 		/*
    556 		 * Scan for special characters.  This code
    557 		 * is really just a big case statement with
    558 		 * non-constant cases.  The bottom of the
    559 		 * case statement is labeled ``endcase'', so goto
    560 		 * it after a case match, or similar.
    561 		 */
    562 
    563 		/*
    564 		 * Control chars which aren't controlled
    565 		 * by ICANON, ISIG, or IXON.
    566 		 */
    567 		if (ISSET(lflag, IEXTEN)) {
    568 			if (CCEQ(cc[VLNEXT], c)) {
    569 				if (ISSET(lflag, ECHO)) {
    570 					if (ISSET(lflag, ECHOE)) {
    571 						(void)ttyoutput('^', tp);
    572 						(void)ttyoutput('\b', tp);
    573 					} else
    574 						ttyecho(c, tp);
    575 				}
    576 				SET(tp->t_state, TS_LNCH);
    577 				goto endcase;
    578 			}
    579 			if (CCEQ(cc[VDISCARD], c)) {
    580 				if (ISSET(lflag, FLUSHO))
    581 					CLR(tp->t_lflag, FLUSHO);
    582 				else {
    583 					ttyflush(tp, FWRITE);
    584 					ttyecho(c, tp);
    585 					if (tp->t_rawq.c_cc + tp->t_canq.c_cc)
    586 						ttyretype(tp);
    587 					SET(tp->t_lflag, FLUSHO);
    588 				}
    589 				goto startoutput;
    590 			}
    591 		}
    592 		/*
    593 		 * Signals.
    594 		 */
    595 		if (ISSET(lflag, ISIG)) {
    596 			if (CCEQ(cc[VINTR], c) || CCEQ(cc[VQUIT], c)) {
    597 				if (!ISSET(lflag, NOFLSH))
    598 					ttyflush(tp, FREAD | FWRITE);
    599 				ttyecho(c, tp);
    600 				ttysig(tp, TTYSIG_PG1, CCEQ(cc[VINTR], c) ?
    601 				    SIGINT : SIGQUIT);
    602 				goto endcase;
    603 			}
    604 			if (CCEQ(cc[VSUSP], c)) {
    605 				if (!ISSET(lflag, NOFLSH))
    606 					ttyflush(tp, FREAD);
    607 				ttyecho(c, tp);
    608 				ttysig(tp, TTYSIG_PG1, SIGTSTP);
    609 				goto endcase;
    610 			}
    611 		}
    612 		/*
    613 		 * Handle start/stop characters.
    614 		 */
    615 		if (ISSET(iflag, IXON)) {
    616 			if (CCEQ(cc[VSTOP], c)) {
    617 				if (!ISSET(tp->t_state, TS_TTSTOP)) {
    618 					SET(tp->t_state, TS_TTSTOP);
    619 					cdev_stop(tp, 0);
    620 					return (0);
    621 				}
    622 				if (!CCEQ(cc[VSTART], c))
    623 					return (0);
    624 				/*
    625 				 * if VSTART == VSTOP then toggle
    626 				 */
    627 				goto endcase;
    628 			}
    629 			if (CCEQ(cc[VSTART], c))
    630 				goto restartoutput;
    631 		}
    632 		/*
    633 		 * IGNCR, ICRNL, & INLCR
    634 		 */
    635 		if (c == '\r') {
    636 			if (ISSET(iflag, IGNCR))
    637 				goto endcase;
    638 			else if (ISSET(iflag, ICRNL))
    639 				c = '\n';
    640 		} else if (c == '\n' && ISSET(iflag, INLCR))
    641 			c = '\r';
    642 	}
    643 	if (!ISSET(lflag, EXTPROC) && ISSET(lflag, ICANON)) {
    644 		/*
    645 		 * From here on down canonical mode character
    646 		 * processing takes place.
    647 		 */
    648 		/*
    649 		 * erase (^H / ^?)
    650 		 */
    651 		if (CCEQ(cc[VERASE], c)) {
    652 			if (tp->t_rawq.c_cc)
    653 				ttyrub(unputc(&tp->t_rawq), tp);
    654 			goto endcase;
    655 		}
    656 		/*
    657 		 * kill (^U)
    658 		 */
    659 		if (CCEQ(cc[VKILL], c)) {
    660 			if (ISSET(lflag, ECHOKE) &&
    661 			    tp->t_rawq.c_cc == tp->t_rocount &&
    662 			    !ISSET(lflag, ECHOPRT))
    663 				while (tp->t_rawq.c_cc)
    664 					ttyrub(unputc(&tp->t_rawq), tp);
    665 			else {
    666 				ttyecho(c, tp);
    667 				if (ISSET(lflag, ECHOK) ||
    668 				    ISSET(lflag, ECHOKE))
    669 					ttyecho('\n', tp);
    670 				FLUSHQ(&tp->t_rawq);
    671 				tp->t_rocount = 0;
    672 			}
    673 			CLR(tp->t_state, TS_LOCAL);
    674 			goto endcase;
    675 		}
    676 		/*
    677 		 * Extensions to the POSIX.1 GTI set of functions.
    678 		 */
    679 		if (ISSET(lflag, IEXTEN)) {
    680 			/*
    681 			 * word erase (^W)
    682 			 */
    683 			if (CCEQ(cc[VWERASE], c)) {
    684 				int alt = ISSET(lflag, ALTWERASE);
    685 				int ctype;
    686 
    687 				/*
    688 				 * erase whitespace
    689 				 */
    690 				while ((c = unputc(&tp->t_rawq)) == ' ' ||
    691 				    c == '\t')
    692 					ttyrub(c, tp);
    693 				if (c == -1)
    694 					goto endcase;
    695 				/*
    696 				 * erase last char of word and remember the
    697 				 * next chars type (for ALTWERASE)
    698 				 */
    699 				ttyrub(c, tp);
    700 				c = unputc(&tp->t_rawq);
    701 				if (c == -1)
    702 					goto endcase;
    703 				if (c == ' ' || c == '\t') {
    704 					(void)putc(c, &tp->t_rawq);
    705 					goto endcase;
    706 				}
    707 				ctype = ISALPHA(c);
    708 				/*
    709 				 * erase rest of word
    710 				 */
    711 				do {
    712 					ttyrub(c, tp);
    713 					c = unputc(&tp->t_rawq);
    714 					if (c == -1)
    715 						goto endcase;
    716 				} while (c != ' ' && c != '\t' &&
    717 				    (alt == 0 || ISALPHA(c) == ctype));
    718 				(void)putc(c, &tp->t_rawq);
    719 				goto endcase;
    720 			}
    721 			/*
    722 			 * reprint line (^R)
    723 			 */
    724 			if (CCEQ(cc[VREPRINT], c)) {
    725 				ttyretype(tp);
    726 				goto endcase;
    727 			}
    728 			/*
    729 			 * ^T - kernel info and generate SIGINFO
    730 			 */
    731 			if (CCEQ(cc[VSTATUS], c)) {
    732 				ttysig(tp, TTYSIG_PG1, SIGINFO);
    733 				goto endcase;
    734 			}
    735 		}
    736 	}
    737 	/*
    738 	 * Check for input buffer overflow
    739 	 */
    740 	if (tp->t_rawq.c_cc + tp->t_canq.c_cc >= TTYHOG) {
    741 		if (ISSET(iflag, IMAXBEL)) {
    742 			if (tp->t_outq.c_cc < tp->t_hiwat)
    743 				(void)ttyoutput(CTRL('g'), tp);
    744 		} else
    745 			ttyflush(tp, FREAD | FWRITE);
    746 		goto endcase;
    747 	}
    748 	/*
    749 	 * Put data char in q for user and
    750 	 * wakeup on seeing a line delimiter.
    751 	 */
    752 	if (putc(c, &tp->t_rawq) >= 0) {
    753 		if (!ISSET(lflag, ICANON)) {
    754 			ttwakeup(tp);
    755 			ttyecho(c, tp);
    756 			goto endcase;
    757 		}
    758 		if (TTBREAKC(c, lflag)) {
    759 			tp->t_rocount = 0;
    760 			catq(&tp->t_rawq, &tp->t_canq);
    761 			ttwakeup(tp);
    762 		} else if (tp->t_rocount++ == 0)
    763 			tp->t_rocol = tp->t_column;
    764 		if (ISSET(tp->t_state, TS_ERASE)) {
    765 			/*
    766 			 * end of prterase \.../
    767 			 */
    768 			CLR(tp->t_state, TS_ERASE);
    769 			(void)ttyoutput('/', tp);
    770 		}
    771 		i = tp->t_column;
    772 		ttyecho(c, tp);
    773 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ECHO)) {
    774 			/*
    775 			 * Place the cursor over the '^' of the ^D.
    776 			 */
    777 			i = min(2, tp->t_column - i);
    778 			while (i > 0) {
    779 				(void)ttyoutput('\b', tp);
    780 				i--;
    781 			}
    782 		}
    783 	}
    784  endcase:
    785 	/*
    786 	 * IXANY means allow any character to restart output.
    787 	 */
    788 	if (ISSET(tp->t_state, TS_TTSTOP) &&
    789 	    !ISSET(iflag, IXANY) && cc[VSTART] != cc[VSTOP]) {
    790 		return (0);
    791 	}
    792  restartoutput:
    793 	CLR(tp->t_lflag, FLUSHO);
    794 	CLR(tp->t_state, TS_TTSTOP);
    795  startoutput:
    796 	return (ttstart(tp));
    797 }
    798 
    799 /*
    800  * Process input of a single character received on a tty.
    801  *
    802  * XXX - this is a hack, all drivers must changed to acquire the
    803  *	 lock before calling linesw->l_rint()
    804  */
    805 int
    806 ttyinput(int c, struct tty *tp)
    807 {
    808 	int error;
    809 
    810 	/*
    811 	 * Unless the receiver is enabled, drop incoming data.
    812 	 */
    813 	if (!ISSET(tp->t_cflag, CREAD))
    814 		return (0);
    815 
    816 	mutex_spin_enter(&tty_lock);
    817 	error = ttyinput_wlock(c, tp);
    818 	mutex_spin_exit(&tty_lock);
    819 
    820 	return (error);
    821 }
    822 
    823 /*
    824  * Output a single character on a tty, doing output processing
    825  * as needed (expanding tabs, newline processing, etc.).
    826  * Returns < 0 if succeeds, otherwise returns char to resend.
    827  * Must be recursive.
    828  *
    829  * Call with tty lock held.
    830  */
    831 int
    832 ttyoutput(int c, struct tty *tp)
    833 {
    834 	long	oflag;
    835 	int	col, notout;
    836 
    837 	KASSERT(mutex_owned(&tty_lock));
    838 
    839 	oflag = tp->t_oflag;
    840 	if (!ISSET(oflag, OPOST)) {
    841 		tk_nout++;
    842 		tp->t_outcc++;
    843 		if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
    844 			return (c);
    845 		return (-1);
    846 	}
    847 	/*
    848 	 * Do tab expansion if OXTABS is set.  Special case if we do external
    849 	 * processing, we don't do the tab expansion because we'll probably
    850 	 * get it wrong.  If tab expansion needs to be done, let it happen
    851 	 * externally.
    852 	 */
    853 	CLR(c, ~TTY_CHARMASK);
    854 	if (c == '\t' &&
    855 	    ISSET(oflag, OXTABS) && !ISSET(tp->t_lflag, EXTPROC)) {
    856 		c = 8 - (tp->t_column & 7);
    857 		if (ISSET(tp->t_lflag, FLUSHO)) {
    858 			notout = 0;
    859 		} else {
    860 			notout = b_to_q("        ", c, &tp->t_outq);
    861 			c -= notout;
    862 			tk_nout += c;
    863 			tp->t_outcc += c;
    864 		}
    865 		tp->t_column += c;
    866 		return (notout ? '\t' : -1);
    867 	}
    868 	if (c == CEOT && ISSET(oflag, ONOEOT))
    869 		return (-1);
    870 
    871 	/*
    872 	 * Newline translation: if ONLCR is set,
    873 	 * translate newline into "\r\n".
    874 	 */
    875 	if (c == '\n' && ISSET(tp->t_oflag, ONLCR)) {
    876 		tk_nout++;
    877 		tp->t_outcc++;
    878 		if (!ISSET(tp->t_lflag, FLUSHO) && putc('\r', &tp->t_outq))
    879 			return (c);
    880 	}
    881 	/* If OCRNL is set, translate "\r" into "\n". */
    882 	else if (c == '\r' && ISSET(tp->t_oflag, OCRNL))
    883 		c = '\n';
    884 	/* If ONOCR is set, don't transmit CRs when on column 0. */
    885 	else if (c == '\r' && ISSET(tp->t_oflag, ONOCR) && tp->t_column == 0)
    886 		return (-1);
    887 
    888 	tk_nout++;
    889 	tp->t_outcc++;
    890 	if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
    891 		return (c);
    892 
    893 	col = tp->t_column;
    894 	switch (CCLASS(c)) {
    895 	case BACKSPACE:
    896 		if (col > 0)
    897 			--col;
    898 		break;
    899 	case CONTROL:
    900 		break;
    901 	case NEWLINE:
    902 		if (ISSET(tp->t_oflag, ONLCR | ONLRET))
    903 			col = 0;
    904 		break;
    905 	case RETURN:
    906 		col = 0;
    907 		break;
    908 	case ORDINARY:
    909 		++col;
    910 		break;
    911 	case TAB:
    912 		col = (col + 8) & ~7;
    913 		break;
    914 	}
    915 	tp->t_column = col;
    916 	return (-1);
    917 }
    918 
    919 /*
    920  * Ioctls for all tty devices.  Called after line-discipline specific ioctl
    921  * has been called to do discipline-specific functions and/or reject any
    922  * of these ioctl commands.
    923  */
    924 /* ARGSUSED */
    925 int
    926 ttioctl(struct tty *tp, u_long cmd, void *data, int flag, struct lwp *l)
    927 {
    928 	extern struct tty *constty;	/* Temporary virtual console. */
    929 	struct proc *p;
    930 	struct linesw	*lp;
    931 	int		s, error;
    932 	struct pathbuf *pb;
    933 	struct nameidata nd;
    934 	char		infobuf[200];
    935 
    936 	KASSERT(l != NULL);
    937 	p = l->l_proc;
    938 
    939 	/* If the ioctl involves modification, hang if in the background. */
    940 	switch (cmd) {
    941 	case  TIOCFLUSH:
    942 	case  TIOCDRAIN:
    943 	case  TIOCSBRK:
    944 	case  TIOCCBRK:
    945 	case  TIOCSTART:
    946 	case  TIOCSETA:
    947 	case  TIOCSETD:
    948 	case  TIOCSLINED:
    949 	case  TIOCSETAF:
    950 	case  TIOCSETAW:
    951 #ifdef notdef
    952 	case  TIOCSPGRP:
    953 	case  FIOSETOWN:
    954 #endif
    955 	case  TIOCSTAT:
    956 	case  TIOCSTI:
    957 	case  TIOCSWINSZ:
    958 	case  TIOCSQSIZE:
    959 	case  TIOCLBIC:
    960 	case  TIOCLBIS:
    961 	case  TIOCLSET:
    962 	case  TIOCSETC:
    963 	case OTIOCSETD:
    964 	case  TIOCSETN:
    965 	case  TIOCSETP:
    966 	case  TIOCSLTC:
    967 		mutex_spin_enter(&tty_lock);
    968 		while (isbackground(curproc, tp) &&
    969 		    p->p_pgrp->pg_jobc && (p->p_lflag & PL_PPWAIT) == 0 &&
    970 		    !sigismasked(l, SIGTTOU)) {
    971 			mutex_spin_exit(&tty_lock);
    972 
    973 			mutex_enter(proc_lock);
    974 			pgsignal(p->p_pgrp, SIGTTOU, 1);
    975 			mutex_exit(proc_lock);
    976 
    977 			mutex_spin_enter(&tty_lock);
    978 			error = ttypause(tp, hz);
    979 			if (error) {
    980 				mutex_spin_exit(&tty_lock);
    981 				return (error);
    982 			}
    983 		}
    984 		mutex_spin_exit(&tty_lock);
    985 		break;
    986 	}
    987 
    988 	switch (cmd) {			/* Process the ioctl. */
    989 	case FIOASYNC:			/* set/clear async i/o */
    990 		mutex_spin_enter(&tty_lock);
    991 		if (*(int *)data)
    992 			SET(tp->t_state, TS_ASYNC);
    993 		else
    994 			CLR(tp->t_state, TS_ASYNC);
    995 		mutex_spin_exit(&tty_lock);
    996 		break;
    997 	case FIONBIO:			/* set/clear non-blocking i/o */
    998 		break;			/* XXX: delete. */
    999 	case FIONREAD:			/* get # bytes to read */
   1000 		mutex_spin_enter(&tty_lock);
   1001 		*(int *)data = ttnread(tp);
   1002 		mutex_spin_exit(&tty_lock);
   1003 		break;
   1004 	case FIONWRITE:			/* get # bytes to written & unsent */
   1005 		mutex_spin_enter(&tty_lock);
   1006 		*(int *)data = tp->t_outq.c_cc;
   1007 		mutex_spin_exit(&tty_lock);
   1008 		break;
   1009 	case FIONSPACE:			/* get # bytes to written & unsent */
   1010 		mutex_spin_enter(&tty_lock);
   1011 		*(int *)data = tp->t_outq.c_cn - tp->t_outq.c_cc;
   1012 		mutex_spin_exit(&tty_lock);
   1013 		break;
   1014 	case TIOCEXCL:			/* set exclusive use of tty */
   1015 		mutex_spin_enter(&tty_lock);
   1016 		SET(tp->t_state, TS_XCLUDE);
   1017 		mutex_spin_exit(&tty_lock);
   1018 		break;
   1019 	case TIOCFLUSH: {		/* flush buffers */
   1020 		int flags = *(int *)data;
   1021 
   1022 		if (flags == 0)
   1023 			flags = FREAD | FWRITE;
   1024 		else
   1025 			flags &= FREAD | FWRITE;
   1026 		mutex_spin_enter(&tty_lock);
   1027 		ttyflush(tp, flags);
   1028 		mutex_spin_exit(&tty_lock);
   1029 		break;
   1030 	}
   1031 	case TIOCCONS:			/* become virtual console */
   1032 		if (*(int *)data) {
   1033 			if (constty && constty != tp &&
   1034 			    ISSET(constty->t_state, TS_CARR_ON | TS_ISOPEN) ==
   1035 			    (TS_CARR_ON | TS_ISOPEN))
   1036 				return EBUSY;
   1037 
   1038 			pb = pathbuf_create("/dev/console");
   1039 			if (pb == NULL) {
   1040 				return ENOMEM;
   1041 			}
   1042 			NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, pb);
   1043 			if ((error = namei(&nd)) != 0) {
   1044 				pathbuf_destroy(pb);
   1045 				return error;
   1046 			}
   1047 			error = VOP_ACCESS(nd.ni_vp, VREAD, l->l_cred);
   1048 			vput(nd.ni_vp);
   1049 			pathbuf_destroy(pb);
   1050 			if (error)
   1051 				return error;
   1052 
   1053 			constty = tp;
   1054 		} else if (tp == constty)
   1055 			constty = NULL;
   1056 		break;
   1057 	case TIOCDRAIN:			/* wait till output drained */
   1058 		if ((error = ttywait(tp)) != 0)
   1059 			return (error);
   1060 		break;
   1061 	case TIOCGETA: {		/* get termios struct */
   1062 		struct termios *t = (struct termios *)data;
   1063 
   1064 		memcpy(t, &tp->t_termios, sizeof(struct termios));
   1065 		break;
   1066 	}
   1067 	case TIOCGETD:			/* get line discipline (old) */
   1068 		*(int *)data = tp->t_linesw->l_no;
   1069 		break;
   1070 	case TIOCGLINED:		/* get line discipline (new) */
   1071 		(void)strncpy((char *)data, tp->t_linesw->l_name,
   1072 		    TTLINEDNAMELEN - 1);
   1073 		break;
   1074 	case TIOCGWINSZ:		/* get window size */
   1075 		*(struct winsize *)data = tp->t_winsize;
   1076 		break;
   1077 	case TIOCGQSIZE:
   1078 		*(int *)data = tp->t_qsize;
   1079 		break;
   1080 	case FIOGETOWN:
   1081 		mutex_enter(proc_lock);
   1082 		if (tp->t_session != NULL && !isctty(p, tp)) {
   1083 			mutex_exit(proc_lock);
   1084 			return (ENOTTY);
   1085 		}
   1086 		*(int *)data = tp->t_pgrp ? -tp->t_pgrp->pg_id : 0;
   1087 		mutex_exit(proc_lock);
   1088 		break;
   1089 	case TIOCGPGRP:			/* get pgrp of tty */
   1090 		mutex_enter(proc_lock);
   1091 		if (!isctty(p, tp)) {
   1092 			mutex_exit(proc_lock);
   1093 			return (ENOTTY);
   1094 		}
   1095 		*(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PGID;
   1096 		mutex_exit(proc_lock);
   1097 		break;
   1098 	case TIOCGSID:			/* get sid of tty */
   1099 		mutex_enter(proc_lock);
   1100 		if (!isctty(p, tp)) {
   1101 			mutex_exit(proc_lock);
   1102 			return (ENOTTY);
   1103 		}
   1104 		*(int *)data = tp->t_session->s_sid;
   1105 		mutex_exit(proc_lock);
   1106 		break;
   1107 #ifdef TIOCHPCL
   1108 	case TIOCHPCL:			/* hang up on last close */
   1109 		mutex_spin_enter(&tty_lock);
   1110 		SET(tp->t_cflag, HUPCL);
   1111 		mutex_spin_exit(&tty_lock);
   1112 		break;
   1113 #endif
   1114 	case TIOCNXCL:			/* reset exclusive use of tty */
   1115 		mutex_spin_enter(&tty_lock);
   1116 		CLR(tp->t_state, TS_XCLUDE);
   1117 		mutex_spin_exit(&tty_lock);
   1118 		break;
   1119 	case TIOCOUTQ:			/* output queue size */
   1120 		*(int *)data = tp->t_outq.c_cc;
   1121 		break;
   1122 	case TIOCSETA:			/* set termios struct */
   1123 	case TIOCSETAW:			/* drain output, set */
   1124 	case TIOCSETAF: {		/* drn out, fls in, set */
   1125 		struct termios *t = (struct termios *)data;
   1126 
   1127 		if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
   1128 			if ((error = ttywait(tp)) != 0)
   1129 				return (error);
   1130 
   1131 			if (cmd == TIOCSETAF) {
   1132 				mutex_spin_enter(&tty_lock);
   1133 				ttyflush(tp, FREAD);
   1134 				mutex_spin_exit(&tty_lock);
   1135 			}
   1136 		}
   1137 
   1138 		s = spltty();
   1139 		/*
   1140 		 * XXXSMP - some drivers call back on us from t_param(), so
   1141 		 *	    don't take the tty spin lock here.
   1142 		 *	    require t_param() to unlock upon callback?
   1143 		 */
   1144 		/* wanted here: mutex_spin_enter(&tty_lock); */
   1145 		if (!ISSET(t->c_cflag, CIGNORE)) {
   1146 			/*
   1147 			 * Set device hardware.
   1148 			 */
   1149 			if (tp->t_param && (error = (*tp->t_param)(tp, t))) {
   1150 				/* wanted here: mutex_spin_exit(&tty_lock); */
   1151 				splx(s);
   1152 				return (error);
   1153 			} else {
   1154 				tp->t_cflag = t->c_cflag;
   1155 				tp->t_ispeed = t->c_ispeed;
   1156 				tp->t_ospeed = t->c_ospeed;
   1157 				if (t->c_ospeed == 0)
   1158 					ttysig(tp, TTYSIG_LEADER, SIGHUP);
   1159 			}
   1160 			ttsetwater(tp);
   1161 		}
   1162 
   1163 		/* delayed lock acquiring */
   1164 		mutex_spin_enter(&tty_lock);
   1165 		if (cmd != TIOCSETAF) {
   1166 			if (ISSET(t->c_lflag, ICANON) !=
   1167 			    ISSET(tp->t_lflag, ICANON)) {
   1168 				if (ISSET(t->c_lflag, ICANON)) {
   1169 					SET(tp->t_lflag, PENDIN);
   1170 					ttwakeup(tp);
   1171 				} else {
   1172 					struct clist tq;
   1173 
   1174 					catq(&tp->t_rawq, &tp->t_canq);
   1175 					tq = tp->t_rawq;
   1176 					tp->t_rawq = tp->t_canq;
   1177 					tp->t_canq = tq;
   1178 					CLR(tp->t_lflag, PENDIN);
   1179 				}
   1180 			}
   1181 		}
   1182 		tp->t_iflag = t->c_iflag;
   1183 		tp->t_oflag = t->c_oflag;
   1184 		/*
   1185 		 * Make the EXTPROC bit read only.
   1186 		 */
   1187 		if (ISSET(tp->t_lflag, EXTPROC))
   1188 			SET(t->c_lflag, EXTPROC);
   1189 		else
   1190 			CLR(t->c_lflag, EXTPROC);
   1191 		tp->t_lflag = t->c_lflag | ISSET(tp->t_lflag, PENDIN);
   1192 		memcpy(tp->t_cc, t->c_cc, sizeof(t->c_cc));
   1193 		mutex_spin_exit(&tty_lock);
   1194 		splx(s);
   1195 		break;
   1196 	}
   1197 	case TIOCSETD:			/* set line discipline (old) */
   1198 		lp = ttyldisc_lookup_bynum(*(int *)data);
   1199 		goto setldisc;
   1200 
   1201 	case TIOCSLINED: {		/* set line discipline (new) */
   1202 		char *name = (char *)data;
   1203 		dev_t device;
   1204 
   1205 		/* Null terminate to prevent buffer overflow */
   1206 		name[TTLINEDNAMELEN - 1] = '\0';
   1207 		lp = ttyldisc_lookup(name);
   1208  setldisc:
   1209 		if (lp == NULL)
   1210 			return (ENXIO);
   1211 
   1212 		if (lp != tp->t_linesw) {
   1213 			device = tp->t_dev;
   1214 			s = spltty();
   1215 			(*tp->t_linesw->l_close)(tp, flag);
   1216 			error = (*lp->l_open)(device, tp);
   1217 			if (error) {
   1218 				(void)(*tp->t_linesw->l_open)(device, tp);
   1219 				splx(s);
   1220 				ttyldisc_release(lp);
   1221 				return (error);
   1222 			}
   1223 			ttyldisc_release(tp->t_linesw);
   1224 			tp->t_linesw = lp;
   1225 			splx(s);
   1226 		} else {
   1227 			/* Drop extra reference. */
   1228 			ttyldisc_release(lp);
   1229 		}
   1230 		break;
   1231 	}
   1232 	case TIOCSTART:			/* start output, like ^Q */
   1233 		mutex_spin_enter(&tty_lock);
   1234 		if (ISSET(tp->t_state, TS_TTSTOP) ||
   1235 		    ISSET(tp->t_lflag, FLUSHO)) {
   1236 			CLR(tp->t_lflag, FLUSHO);
   1237 			CLR(tp->t_state, TS_TTSTOP);
   1238 			ttstart(tp);
   1239 		}
   1240 		mutex_spin_exit(&tty_lock);
   1241 		break;
   1242 	case TIOCSTI:			/* simulate terminal input */
   1243 		if (kauth_authorize_device_tty(l->l_cred, KAUTH_DEVICE_TTY_STI,
   1244 		    tp) != 0) {
   1245 			if (!ISSET(flag, FREAD))
   1246 				return (EPERM);
   1247 			if (!isctty(p, tp))
   1248 				return (EACCES);
   1249 		}
   1250 		(*tp->t_linesw->l_rint)(*(u_char *)data, tp);
   1251 		break;
   1252 	case TIOCSTOP:			/* stop output, like ^S */
   1253 	{
   1254 		mutex_spin_enter(&tty_lock);
   1255 		if (!ISSET(tp->t_state, TS_TTSTOP)) {
   1256 			SET(tp->t_state, TS_TTSTOP);
   1257 			cdev_stop(tp, 0);
   1258 		}
   1259 		mutex_spin_exit(&tty_lock);
   1260 		break;
   1261 	}
   1262 	case TIOCSCTTY:			/* become controlling tty */
   1263 		mutex_enter(proc_lock);
   1264 		mutex_spin_enter(&tty_lock);
   1265 
   1266 		/* Session ctty vnode pointer set in vnode layer. */
   1267 		if (!SESS_LEADER(p) ||
   1268 		    ((p->p_session->s_ttyvp || tp->t_session) &&
   1269 		    (tp->t_session != p->p_session))) {
   1270 			mutex_spin_exit(&tty_lock);
   1271 			mutex_exit(proc_lock);
   1272 			return (EPERM);
   1273 		}
   1274 
   1275 		/*
   1276 		 * `p_session' acquires a reference.
   1277 		 * But note that if `t_session' is set at this point,
   1278 		 * it must equal `p_session', in which case the session
   1279 		 * already has the correct reference count.
   1280 		 */
   1281 		if (tp->t_session == NULL) {
   1282 			proc_sesshold(p->p_session);
   1283 		}
   1284 		tp->t_session = p->p_session;
   1285 		tp->t_pgrp = p->p_pgrp;
   1286 		p->p_session->s_ttyp = tp;
   1287 		p->p_lflag |= PL_CONTROLT;
   1288 		mutex_spin_exit(&tty_lock);
   1289 		mutex_exit(proc_lock);
   1290 		break;
   1291 	case FIOSETOWN: {		/* set pgrp of tty */
   1292 		pid_t pgid = *(pid_t *)data;
   1293 		struct pgrp *pgrp;
   1294 
   1295 		mutex_enter(proc_lock);
   1296 		if (tp->t_session != NULL && !isctty(p, tp)) {
   1297 			mutex_exit(proc_lock);
   1298 			return (ENOTTY);
   1299 		}
   1300 
   1301 		if (pgid < 0) {
   1302 			pgrp = pgrp_find(-pgid);
   1303 			if (pgrp == NULL) {
   1304 				mutex_exit(proc_lock);
   1305 				return (EINVAL);
   1306 			}
   1307 		} else {
   1308 			struct proc *p1;
   1309 			p1 = proc_find(pgid);
   1310 			if (!p1) {
   1311 				mutex_exit(proc_lock);
   1312 				return (ESRCH);
   1313 			}
   1314 			pgrp = p1->p_pgrp;
   1315 		}
   1316 
   1317 		if (pgrp->pg_session != p->p_session) {
   1318 			mutex_exit(proc_lock);
   1319 			return (EPERM);
   1320 		}
   1321 		mutex_spin_enter(&tty_lock);
   1322 		tp->t_pgrp = pgrp;
   1323 		mutex_spin_exit(&tty_lock);
   1324 		mutex_exit(proc_lock);
   1325 		break;
   1326 	}
   1327 	case TIOCSPGRP: {		/* set pgrp of tty */
   1328 		struct pgrp *pgrp;
   1329 		pid_t pgid = *(pid_t *)data;
   1330 
   1331 		if (pgid == NO_PGID)
   1332 			return EINVAL;
   1333 
   1334 		mutex_enter(proc_lock);
   1335 		if (!isctty(p, tp)) {
   1336 			mutex_exit(proc_lock);
   1337 			return (ENOTTY);
   1338 		}
   1339 		pgrp = pgrp_find(pgid);
   1340 		if (pgrp == NULL || pgrp->pg_session != p->p_session) {
   1341 			mutex_exit(proc_lock);
   1342 			return (EPERM);
   1343 		}
   1344 		mutex_spin_enter(&tty_lock);
   1345 		tp->t_pgrp = pgrp;
   1346 		mutex_spin_exit(&tty_lock);
   1347 		mutex_exit(proc_lock);
   1348 		break;
   1349 	}
   1350 	case TIOCSTAT:			/* get load avg stats */
   1351 		mutex_enter(proc_lock);
   1352 		ttygetinfo(tp, 0, infobuf, sizeof(infobuf));
   1353 		mutex_exit(proc_lock);
   1354 
   1355 		mutex_spin_enter(&tty_lock);
   1356 		ttyputinfo(tp, infobuf);
   1357 		mutex_spin_exit(&tty_lock);
   1358 		break;
   1359 	case TIOCSWINSZ:		/* set window size */
   1360 		mutex_spin_enter(&tty_lock);
   1361 		if (memcmp((void *)&tp->t_winsize, data,
   1362 		    sizeof(struct winsize))) {
   1363 			tp->t_winsize = *(struct winsize *)data;
   1364 			ttysig(tp, TTYSIG_PG1, SIGWINCH);
   1365 		}
   1366 		mutex_spin_exit(&tty_lock);
   1367 		break;
   1368 	case TIOCSQSIZE:
   1369 		if ((error = tty_get_qsize(&s, *(int *)data)) == 0 &&
   1370 		    s != tp->t_qsize)
   1371 			error = tty_set_qsize(tp, s);
   1372 		return error;
   1373 
   1374 	case TIOCSBRK:
   1375 	case TIOCCBRK:
   1376 	case TIOCSDTR:
   1377 	case TIOCCDTR:
   1378 	case TIOCSFLAGS:
   1379 	case TIOCGFLAGS:
   1380 	case TIOCMSET:
   1381 	case TIOCMGET:
   1382 	case TIOCMBIS:
   1383 	case TIOCMBIC:
   1384 		/* Handled by the driver layer */
   1385 		return EPASSTHROUGH;
   1386 
   1387 	case TIOCEXT:
   1388 	case TIOCPTSNAME:
   1389 	case TIOCGRANTPT:
   1390 	case TIOCPKT:
   1391 	case TIOCUCNTL:
   1392 	case TIOCREMOTE:
   1393 	case TIOCSIG:
   1394 		/* for ptys */
   1395 		return EPASSTHROUGH;
   1396 
   1397 	default:
   1398 #ifdef COMPAT_60
   1399 		error = compat_60_ttioctl(tp, cmd, data, flag, l);
   1400 		if (error != EPASSTHROUGH)
   1401 			return error;
   1402 #endif /* COMPAT_60 */
   1403 		/* We may have to load the compat module for this. */
   1404 		for (;;) {
   1405 			rw_enter(&ttcompat_lock, RW_READER);
   1406 			if (ttcompatvec != NULL) {
   1407 				break;
   1408 			}
   1409 			rw_exit(&ttcompat_lock);
   1410 			(void)module_autoload("compat", MODULE_CLASS_ANY);
   1411 			if (ttcompatvec == NULL) {
   1412 				return EPASSTHROUGH;
   1413 			}
   1414 		}
   1415 		error = (*ttcompatvec)(tp, cmd, data, flag, l);
   1416 		rw_exit(&ttcompat_lock);
   1417 		return error;
   1418 	}
   1419 	return (0);
   1420 }
   1421 
   1422 int
   1423 ttpoll(struct tty *tp, int events, struct lwp *l)
   1424 {
   1425 	int	revents;
   1426 
   1427 	revents = 0;
   1428 	mutex_spin_enter(&tty_lock);
   1429 	if (events & (POLLIN | POLLRDNORM))
   1430 		if (ttnread(tp) > 0)
   1431 			revents |= events & (POLLIN | POLLRDNORM);
   1432 
   1433 	if (events & (POLLOUT | POLLWRNORM))
   1434 		if (tp->t_outq.c_cc <= tp->t_lowat)
   1435 			revents |= events & (POLLOUT | POLLWRNORM);
   1436 
   1437 	if (events & POLLHUP)
   1438 		if (!CONNECTED(tp))
   1439 			revents |= POLLHUP;
   1440 
   1441 	if (revents == 0) {
   1442 		if (events & (POLLIN | POLLHUP | POLLRDNORM))
   1443 			selrecord(l, &tp->t_rsel);
   1444 
   1445 		if (events & (POLLOUT | POLLWRNORM))
   1446 			selrecord(l, &tp->t_wsel);
   1447 	}
   1448 
   1449 	mutex_spin_exit(&tty_lock);
   1450 
   1451 	return (revents);
   1452 }
   1453 
   1454 static void
   1455 filt_ttyrdetach(struct knote *kn)
   1456 {
   1457 	struct tty	*tp;
   1458 
   1459 	tp = kn->kn_hook;
   1460 	mutex_spin_enter(&tty_lock);
   1461 	SLIST_REMOVE(&tp->t_rsel.sel_klist, kn, knote, kn_selnext);
   1462 	mutex_spin_exit(&tty_lock);
   1463 }
   1464 
   1465 static int
   1466 filt_ttyread(struct knote *kn, long hint)
   1467 {
   1468 	struct tty	*tp;
   1469 
   1470 	tp = kn->kn_hook;
   1471 	if ((hint & NOTE_SUBMIT) == 0)
   1472 		mutex_spin_enter(&tty_lock);
   1473 	kn->kn_data = ttnread(tp);
   1474 	if ((hint & NOTE_SUBMIT) == 0)
   1475 		mutex_spin_exit(&tty_lock);
   1476 	return (kn->kn_data > 0);
   1477 }
   1478 
   1479 static void
   1480 filt_ttywdetach(struct knote *kn)
   1481 {
   1482 	struct tty	*tp;
   1483 
   1484 	tp = kn->kn_hook;
   1485 	mutex_spin_enter(&tty_lock);
   1486 	SLIST_REMOVE(&tp->t_wsel.sel_klist, kn, knote, kn_selnext);
   1487 	mutex_spin_exit(&tty_lock);
   1488 }
   1489 
   1490 static int
   1491 filt_ttywrite(struct knote *kn, long hint)
   1492 {
   1493 	struct tty	*tp;
   1494 	int		canwrite;
   1495 
   1496 	tp = kn->kn_hook;
   1497 	if ((hint & NOTE_SUBMIT) == 0)
   1498 		mutex_spin_enter(&tty_lock);
   1499 	kn->kn_data = tp->t_outq.c_cn - tp->t_outq.c_cc;
   1500 	canwrite = (tp->t_outq.c_cc <= tp->t_lowat) && CONNECTED(tp);
   1501 	if ((hint & NOTE_SUBMIT) == 0)
   1502 		mutex_spin_exit(&tty_lock);
   1503 	return (canwrite);
   1504 }
   1505 
   1506 static const struct filterops ttyread_filtops =
   1507 	{ 1, NULL, filt_ttyrdetach, filt_ttyread };
   1508 static const struct filterops ttywrite_filtops =
   1509 	{ 1, NULL, filt_ttywdetach, filt_ttywrite };
   1510 
   1511 int
   1512 ttykqfilter(dev_t dev, struct knote *kn)
   1513 {
   1514 	struct tty	*tp;
   1515 	struct klist	*klist;
   1516 
   1517 	if ((tp = cdev_tty(dev)) == NULL)
   1518 		return (ENXIO);
   1519 
   1520 	switch (kn->kn_filter) {
   1521 	case EVFILT_READ:
   1522 		klist = &tp->t_rsel.sel_klist;
   1523 		kn->kn_fop = &ttyread_filtops;
   1524 		break;
   1525 	case EVFILT_WRITE:
   1526 		klist = &tp->t_wsel.sel_klist;
   1527 		kn->kn_fop = &ttywrite_filtops;
   1528 		break;
   1529 	default:
   1530 		return EINVAL;
   1531 	}
   1532 
   1533 	kn->kn_hook = tp;
   1534 
   1535 	mutex_spin_enter(&tty_lock);
   1536 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
   1537 	mutex_spin_exit(&tty_lock);
   1538 
   1539 	return (0);
   1540 }
   1541 
   1542 /*
   1543  * Find the number of chars ready to be read from this tty.
   1544  * Call with the tty lock held.
   1545  */
   1546 static int
   1547 ttnread(struct tty *tp)
   1548 {
   1549 	int	nread;
   1550 
   1551 	KASSERT(mutex_owned(&tty_lock));
   1552 
   1553 	if (ISSET(tp->t_lflag, PENDIN))
   1554 		ttypend(tp);
   1555 	nread = tp->t_canq.c_cc;
   1556 	if (!ISSET(tp->t_lflag, ICANON)) {
   1557 		nread += tp->t_rawq.c_cc;
   1558 		if (nread < tp->t_cc[VMIN] && !tp->t_cc[VTIME])
   1559 			nread = 0;
   1560 	}
   1561 	return (nread);
   1562 }
   1563 
   1564 /*
   1565  * Wait for output to drain, or if this times out, flush it.
   1566  */
   1567 static int
   1568 ttywait_timo(struct tty *tp, int timo)
   1569 {
   1570 	int	error;
   1571 
   1572 	error = 0;
   1573 
   1574 	mutex_spin_enter(&tty_lock);
   1575 	while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
   1576 	    CONNECTED(tp) && tp->t_oproc) {
   1577 		(*tp->t_oproc)(tp);
   1578 		error = ttysleep(tp, &tp->t_outcv, true, timo);
   1579 		if (error == EWOULDBLOCK)
   1580 			ttyflush(tp, FWRITE);
   1581 		if (error)
   1582 			break;
   1583 	}
   1584 	mutex_spin_exit(&tty_lock);
   1585 
   1586 	return (error);
   1587 }
   1588 
   1589 /*
   1590  * Wait for output to drain.
   1591  */
   1592 int
   1593 ttywait(struct tty *tp)
   1594 {
   1595 	return ttywait_timo(tp, 0);
   1596 }
   1597 
   1598 /*
   1599  * Flush if successfully wait.
   1600  */
   1601 int
   1602 ttywflush(struct tty *tp)
   1603 {
   1604 	int	error;
   1605 
   1606 	error = ttywait_timo(tp, 5 * hz);
   1607 	if (error == 0 || error == EWOULDBLOCK) {
   1608 		mutex_spin_enter(&tty_lock);
   1609 		ttyflush(tp, FREAD);
   1610 		mutex_spin_exit(&tty_lock);
   1611 	}
   1612 	return (error);
   1613 }
   1614 
   1615 /*
   1616  * Flush tty read and/or write queues, notifying anyone waiting.
   1617  * Call with the tty lock held.
   1618  */
   1619 void
   1620 ttyflush(struct tty *tp, int rw)
   1621 {
   1622 
   1623 	KASSERT(mutex_owned(&tty_lock));
   1624 
   1625 	if (rw & FREAD) {
   1626 		FLUSHQ(&tp->t_canq);
   1627 		FLUSHQ(&tp->t_rawq);
   1628 		tp->t_rocount = 0;
   1629 		tp->t_rocol = 0;
   1630 		CLR(tp->t_state, TS_LOCAL);
   1631 		ttwakeup(tp);
   1632 	}
   1633 	if (rw & FWRITE) {
   1634 		CLR(tp->t_state, TS_TTSTOP);
   1635 		cdev_stop(tp, rw);
   1636 		FLUSHQ(&tp->t_outq);
   1637 		cv_broadcast(&tp->t_outcv);
   1638 		selnotify(&tp->t_wsel, 0, NOTE_SUBMIT);
   1639 	}
   1640 }
   1641 
   1642 /*
   1643  * Copy in the default termios characters.
   1644  */
   1645 void
   1646 ttychars(struct tty *tp)
   1647 {
   1648 
   1649 	memcpy(tp->t_cc, ttydefchars, sizeof(ttydefchars));
   1650 }
   1651 
   1652 /*
   1653  * Send stop character on input overflow.
   1654  * Call with the tty lock held.
   1655  */
   1656 static void
   1657 ttyblock(struct tty *tp)
   1658 {
   1659 	int	total;
   1660 
   1661 	KASSERT(mutex_owned(&tty_lock));
   1662 
   1663 	total = tp->t_rawq.c_cc + tp->t_canq.c_cc;
   1664 	if (tp->t_rawq.c_cc > TTYHOG) {
   1665 		ttyflush(tp, FREAD | FWRITE);
   1666 		CLR(tp->t_state, TS_TBLOCK);
   1667 	}
   1668 	/*
   1669 	 * Block further input iff: current input > threshold
   1670 	 * AND input is available to user program.
   1671 	 */
   1672 	if (total >= TTYHOG / 2 &&
   1673 	    !ISSET(tp->t_state, TS_TBLOCK) &&
   1674 	    (!ISSET(tp->t_lflag, ICANON) || tp->t_canq.c_cc > 0)) {
   1675 		if (ISSET(tp->t_iflag, IXOFF) &&
   1676 		    tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
   1677 		    putc(tp->t_cc[VSTOP], &tp->t_outq) == 0) {
   1678 			SET(tp->t_state, TS_TBLOCK);
   1679 			ttstart(tp);
   1680 		}
   1681 		/* Try to block remote output via hardware flow control. */
   1682 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
   1683 		    (*tp->t_hwiflow)(tp, 1) != 0)
   1684 			SET(tp->t_state, TS_TBLOCK);
   1685 	}
   1686 }
   1687 
   1688 /*
   1689  * Delayed line discipline output
   1690  */
   1691 void
   1692 ttrstrt(void *tp_arg)
   1693 {
   1694 	struct tty	*tp;
   1695 
   1696 #ifdef DIAGNOSTIC
   1697 	if (tp_arg == NULL)
   1698 		panic("ttrstrt");
   1699 #endif
   1700 	tp = tp_arg;
   1701 	mutex_spin_enter(&tty_lock);
   1702 
   1703 	CLR(tp->t_state, TS_TIMEOUT);
   1704 	ttstart(tp); /* XXX - Shouldn't this be tp->l_start(tp)? */
   1705 
   1706 	mutex_spin_exit(&tty_lock);
   1707 }
   1708 
   1709 /*
   1710  * start a line discipline
   1711  * Always call with tty lock held?
   1712  */
   1713 int
   1714 ttstart(struct tty *tp)
   1715 {
   1716 
   1717 	if (tp->t_oproc != NULL)	/* XXX: Kludge for pty. */
   1718 		(*tp->t_oproc)(tp);
   1719 	return (0);
   1720 }
   1721 
   1722 /*
   1723  * "close" a line discipline
   1724  */
   1725 int
   1726 ttylclose(struct tty *tp, int flag)
   1727 {
   1728 
   1729 	if (flag & FNONBLOCK) {
   1730 		mutex_spin_enter(&tty_lock);
   1731 		ttyflush(tp, FREAD | FWRITE);
   1732 		mutex_spin_exit(&tty_lock);
   1733 	} else
   1734 		ttywflush(tp);
   1735 	return (0);
   1736 }
   1737 
   1738 /*
   1739  * Handle modem control transition on a tty.
   1740  * Flag indicates new state of carrier.
   1741  * Returns 0 if the line should be turned off, otherwise 1.
   1742  */
   1743 int
   1744 ttymodem(struct tty *tp, int flag)
   1745 {
   1746 
   1747 	mutex_spin_enter(&tty_lock);
   1748 	if (flag == 0) {
   1749 		if (ISSET(tp->t_state, TS_CARR_ON)) {
   1750 			/*
   1751 			 * Lost carrier.
   1752 			 */
   1753 			CLR(tp->t_state, TS_CARR_ON);
   1754 			if (ISSET(tp->t_state, TS_ISOPEN) && !CONNECTED(tp)) {
   1755 				ttysig(tp, TTYSIG_LEADER, SIGHUP);
   1756 				ttyflush(tp, FREAD | FWRITE);
   1757 				mutex_spin_exit(&tty_lock);
   1758 				return (0);
   1759 			}
   1760 		}
   1761 	} else {
   1762 		if (!ISSET(tp->t_state, TS_CARR_ON)) {
   1763 			/*
   1764 			 * Carrier now on.
   1765 			 */
   1766 			SET(tp->t_state, TS_CARR_ON);
   1767 			ttwakeup(tp);
   1768 		}
   1769 	}
   1770 	mutex_spin_exit(&tty_lock);
   1771 
   1772 	return (1);
   1773 }
   1774 
   1775 /*
   1776  * Default modem control routine (for other line disciplines).
   1777  * Return argument flag, to turn off device on carrier drop.
   1778  */
   1779 int
   1780 nullmodem(struct tty *tp, int flag)
   1781 {
   1782 
   1783 	mutex_spin_enter(&tty_lock);
   1784 	if (flag)
   1785 		SET(tp->t_state, TS_CARR_ON);
   1786 	else {
   1787 		CLR(tp->t_state, TS_CARR_ON);
   1788 		if (!CONNECTED(tp)) {
   1789 			ttysig(tp, TTYSIG_LEADER, SIGHUP);
   1790 			mutex_spin_exit(&tty_lock);
   1791 			return (0);
   1792 		}
   1793 	}
   1794 	mutex_spin_exit(&tty_lock);
   1795 
   1796 	return (1);
   1797 }
   1798 
   1799 /*
   1800  * Reinput pending characters after state switch.
   1801  */
   1802 void
   1803 ttypend(struct tty *tp)
   1804 {
   1805 	struct clist	tq;
   1806 	int		c;
   1807 
   1808 	KASSERT(mutex_owned(&tty_lock));
   1809 
   1810 	CLR(tp->t_lflag, PENDIN);
   1811 	SET(tp->t_state, TS_TYPEN);
   1812 	tq = tp->t_rawq;
   1813 	tp->t_rawq.c_cc = 0;
   1814 	tp->t_rawq.c_cf = tp->t_rawq.c_cl = 0;
   1815 	while ((c = getc(&tq)) >= 0)
   1816 		ttyinput_wlock(c, tp);
   1817 	CLR(tp->t_state, TS_TYPEN);
   1818 }
   1819 
   1820 /*
   1821  * Process a read call on a tty device.
   1822  */
   1823 int
   1824 ttread(struct tty *tp, struct uio *uio, int flag)
   1825 {
   1826 	struct clist	*qp;
   1827 	u_char		*cc;
   1828 	struct proc	*p;
   1829 	int		c, first, error, has_stime, last_cc;
   1830 	long		lflag, slp;
   1831 	struct timeval	now, stime;
   1832 
   1833 	if (uio->uio_resid == 0)
   1834 		return 0;
   1835 
   1836 	stime.tv_usec = 0;	/* XXX gcc */
   1837 	stime.tv_sec = 0;	/* XXX gcc */
   1838 
   1839 	cc = tp->t_cc;
   1840 	p = curproc;
   1841 	error = 0;
   1842 	has_stime = 0;
   1843 	last_cc = 0;
   1844 	slp = 0;
   1845 
   1846  loop:
   1847 	mutex_spin_enter(&tty_lock);
   1848 	lflag = tp->t_lflag;
   1849 	/*
   1850 	 * take pending input first
   1851 	 */
   1852 	if (ISSET(lflag, PENDIN))
   1853 		ttypend(tp);
   1854 
   1855 	/*
   1856 	 * Hang process if it's in the background.
   1857 	 */
   1858 	if (isbackground(p, tp)) {
   1859 		if (sigismasked(curlwp, SIGTTIN) ||
   1860 		    p->p_lflag & PL_PPWAIT || p->p_pgrp->pg_jobc == 0) {
   1861 			mutex_spin_exit(&tty_lock);
   1862 			return (EIO);
   1863 		}
   1864 		mutex_spin_exit(&tty_lock);
   1865 
   1866 		mutex_enter(proc_lock);
   1867 		pgsignal(p->p_pgrp, SIGTTIN, 1);
   1868 		mutex_exit(proc_lock);
   1869 
   1870 		mutex_spin_enter(&tty_lock);
   1871 		error = ttypause(tp, hz);
   1872 		mutex_spin_exit(&tty_lock);
   1873 		if (error)
   1874 			return (error);
   1875 		goto loop;
   1876 	}
   1877 
   1878 	if (!ISSET(lflag, ICANON)) {
   1879 		int m = cc[VMIN];
   1880 		long t = cc[VTIME];
   1881 
   1882 		qp = &tp->t_rawq;
   1883 		/*
   1884 		 * Check each of the four combinations.
   1885 		 * (m > 0 && t == 0) is the normal read case.
   1886 		 * It should be fairly efficient, so we check that and its
   1887 		 * companion case (m == 0 && t == 0) first.
   1888 		 * For the other two cases, we compute the target sleep time
   1889 		 * into slp.
   1890 		 */
   1891 		if (t == 0) {
   1892 			if (qp->c_cc < m)
   1893 				goto sleep;
   1894 			goto read;
   1895 		}
   1896 		t *= hz;		/* time in deca-ticks */
   1897 /*
   1898  * Time difference in deca-ticks, split division to avoid numeric overflow.
   1899  * Ok for hz < ~200kHz
   1900  */
   1901 #define	diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 10 * hz + \
   1902 			 ((t1).tv_usec - (t2).tv_usec) / 100 * hz / 1000)
   1903 		if (m > 0) {
   1904 			if (qp->c_cc <= 0)
   1905 				goto sleep;
   1906 			if (qp->c_cc >= m)
   1907 				goto read;
   1908 			if (!has_stime) {
   1909 				/* first character, start timer */
   1910 				has_stime = 1;
   1911 				getmicrotime(&stime);
   1912 				slp = t;
   1913 			} else if (qp->c_cc > last_cc) {
   1914 				/* got a character, restart timer */
   1915 				getmicrotime(&stime);
   1916 				slp = t;
   1917 			} else {
   1918 				/* nothing, check expiration */
   1919 				getmicrotime(&now);
   1920 				slp = t - diff(now, stime);
   1921 			}
   1922 		} else {	/* m == 0 */
   1923 			if (qp->c_cc > 0)
   1924 				goto read;
   1925 			if (!has_stime) {
   1926 				has_stime = 1;
   1927 				getmicrotime(&stime);
   1928 				slp = t;
   1929 			} else {
   1930 				getmicrotime(&now);
   1931 				slp = t - diff(now, stime);
   1932 			}
   1933 		}
   1934 		last_cc = qp->c_cc;
   1935 #undef diff
   1936 		if (slp > 0) {
   1937 			/*
   1938 			 * Convert deca-ticks back to ticks.
   1939 			 * Rounding down may make us wake up just short
   1940 			 * of the target, so we round up.
   1941 			 * Maybe we should do 'slp/10 + 1' because the
   1942 			 * first tick maybe almost immediate.
   1943 			 * However it is more useful for a program that sets
   1944 			 * VTIME=10 to wakeup every second not every 1.01
   1945 			 * seconds (if hz=100).
   1946 			 */
   1947 			slp = (slp + 9)/ 10;
   1948 			goto sleep;
   1949 		}
   1950 	} else if ((qp = &tp->t_canq)->c_cc <= 0) {
   1951 		int	carrier;
   1952 
   1953  sleep:
   1954 		/*
   1955 		 * If there is no input, sleep on rawq
   1956 		 * awaiting hardware receipt and notification.
   1957 		 * If we have data, we don't need to check for carrier.
   1958 		 */
   1959 		carrier = CONNECTED(tp);
   1960 		if (!carrier && ISSET(tp->t_state, TS_ISOPEN)) {
   1961 			mutex_spin_exit(&tty_lock);
   1962 			return (0);	/* EOF */
   1963 		}
   1964 		if (!has_stime || slp <= 0) {
   1965 			if (flag & IO_NDELAY) {
   1966 				mutex_spin_exit(&tty_lock);
   1967 				return (EWOULDBLOCK);
   1968 			}
   1969 		}
   1970 		error = ttysleep(tp, &tp->t_rawcv, true, slp);
   1971 		mutex_spin_exit(&tty_lock);
   1972 		/* VMIN == 0: any quantity read satisfies */
   1973 		if (cc[VMIN] == 0 && error == EWOULDBLOCK)
   1974 			return (0);
   1975 		if (error && error != EWOULDBLOCK)
   1976 			return (error);
   1977 		goto loop;
   1978 	}
   1979  read:
   1980 
   1981 	/*
   1982 	 * Input present, check for input mapping and processing.
   1983 	 */
   1984 	first = 1;
   1985 	while ((c = getc(qp)) >= 0) {
   1986 		/*
   1987 		 * delayed suspend (^Y)
   1988 		 */
   1989 		if (CCEQ(cc[VDSUSP], c) &&
   1990 		    ISSET(lflag, IEXTEN|ISIG) == (IEXTEN|ISIG)) {
   1991 			ttysig(tp, TTYSIG_PG1, SIGTSTP);
   1992 			if (first) {
   1993 				error = ttypause(tp, hz);
   1994 				if (error)
   1995 					break;
   1996 				mutex_spin_exit(&tty_lock);
   1997 				goto loop;
   1998 			}
   1999 			break;
   2000 		}
   2001 		/*
   2002 		 * Interpret EOF only in canonical mode.
   2003 		 */
   2004 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
   2005 			break;
   2006 		/*
   2007 		 * Give user character.
   2008 		 */
   2009 		mutex_spin_exit(&tty_lock);
   2010  		error = ureadc(c, uio);
   2011 		mutex_spin_enter(&tty_lock);
   2012 		if (error)
   2013 			break;
   2014  		if (uio->uio_resid == 0)
   2015 			break;
   2016 		/*
   2017 		 * In canonical mode check for a "break character"
   2018 		 * marking the end of a "line of input".
   2019 		 */
   2020 		if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
   2021 			break;
   2022 		first = 0;
   2023 	}
   2024 
   2025 	/*
   2026 	 * Look to unblock output now that (presumably)
   2027 	 * the input queue has gone down.
   2028 	 */
   2029 	if (ISSET(tp->t_state, TS_TBLOCK) && tp->t_rawq.c_cc < TTYHOG / 5) {
   2030 		if (ISSET(tp->t_iflag, IXOFF) &&
   2031 		    cc[VSTART] != _POSIX_VDISABLE &&
   2032 		    putc(cc[VSTART], &tp->t_outq) == 0) {
   2033 			CLR(tp->t_state, TS_TBLOCK);
   2034 			ttstart(tp);
   2035 		}
   2036 		/* Try to unblock remote output via hardware flow control. */
   2037 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
   2038 		    (*tp->t_hwiflow)(tp, 0) != 0)
   2039 			CLR(tp->t_state, TS_TBLOCK);
   2040 	}
   2041 	mutex_spin_exit(&tty_lock);
   2042 
   2043 	return (error);
   2044 }
   2045 
   2046 /*
   2047  * Check the output queue on tp for space for a kernel message (from uprintf
   2048  * or tprintf).  Allow some space over the normal hiwater mark so we don't
   2049  * lose messages due to normal flow control, but don't let the tty run amok.
   2050  * Sleeps here are not interruptible, but we return prematurely if new signals
   2051  * arrive.
   2052  * Call with tty lock held.
   2053  */
   2054 static int
   2055 ttycheckoutq_wlock(struct tty *tp, int wait)
   2056 {
   2057 	int	hiwat, error;
   2058 
   2059 	KASSERT(mutex_owned(&tty_lock));
   2060 
   2061 	hiwat = tp->t_hiwat;
   2062 	if (tp->t_outq.c_cc > hiwat + 200)
   2063 		while (tp->t_outq.c_cc > hiwat) {
   2064 			ttstart(tp);
   2065 			if (wait == 0)
   2066 				return (0);
   2067 			error = ttysleep(tp, &tp->t_outcv, true, hz);
   2068 			if (error == EINTR)
   2069 				wait = 0;
   2070 		}
   2071 
   2072 	return (1);
   2073 }
   2074 
   2075 int
   2076 ttycheckoutq(struct tty *tp, int wait)
   2077 {
   2078 	int	r;
   2079 
   2080 	mutex_spin_enter(&tty_lock);
   2081 	r = ttycheckoutq_wlock(tp, wait);
   2082 	mutex_spin_exit(&tty_lock);
   2083 
   2084 	return (r);
   2085 }
   2086 
   2087 /*
   2088  * Process a write call on a tty device.
   2089  */
   2090 int
   2091 ttwrite(struct tty *tp, struct uio *uio, int flag)
   2092 {
   2093 	u_char		*cp;
   2094 	struct proc	*p;
   2095 	int		cc, ce, i, hiwat, error;
   2096 	u_char		obuf[OBUFSIZ];
   2097 
   2098 	cp = NULL;
   2099 	hiwat = tp->t_hiwat;
   2100 	error = 0;
   2101 	cc = 0;
   2102  loop:
   2103 	mutex_spin_enter(&tty_lock);
   2104 	if (!CONNECTED(tp)) {
   2105 		if (ISSET(tp->t_state, TS_ISOPEN)) {
   2106 			mutex_spin_exit(&tty_lock);
   2107 			return (EIO);
   2108 		} else if (flag & IO_NDELAY) {
   2109 			mutex_spin_exit(&tty_lock);
   2110 			error = EWOULDBLOCK;
   2111 			goto out;
   2112 		} else {
   2113 			/* Sleep awaiting carrier. */
   2114 			error = ttysleep(tp, &tp->t_rawcv, true, 0);
   2115 			mutex_spin_exit(&tty_lock);
   2116 			if (error)
   2117 				goto out;
   2118 			goto loop;
   2119 		}
   2120 	}
   2121 
   2122 	/*
   2123 	 * Hang the process if it's in the background.
   2124 	 */
   2125 	p = curproc;
   2126 	if (isbackground(p, tp) &&
   2127 	    ISSET(tp->t_lflag, TOSTOP) && (p->p_lflag & PL_PPWAIT) == 0 &&
   2128 	    !sigismasked(curlwp, SIGTTOU)) {
   2129 		if (p->p_pgrp->pg_jobc == 0) {
   2130 			error = EIO;
   2131 			mutex_spin_exit(&tty_lock);
   2132 			goto out;
   2133 		}
   2134 		mutex_spin_exit(&tty_lock);
   2135 
   2136 		mutex_enter(proc_lock);
   2137 		pgsignal(p->p_pgrp, SIGTTOU, 1);
   2138 		mutex_exit(proc_lock);
   2139 
   2140 		mutex_spin_enter(&tty_lock);
   2141 		error = ttypause(tp, hz);
   2142 		mutex_spin_exit(&tty_lock);
   2143 		if (error)
   2144 			goto out;
   2145 		goto loop;
   2146 	}
   2147 	mutex_spin_exit(&tty_lock);
   2148 
   2149 	/*
   2150 	 * Process the user's data in at most OBUFSIZ chunks.  Perform any
   2151 	 * output translation.  Keep track of high water mark, sleep on
   2152 	 * overflow awaiting device aid in acquiring new space.
   2153 	 */
   2154 	while (uio->uio_resid > 0 || cc > 0) {
   2155 		if (ISSET(tp->t_lflag, FLUSHO)) {
   2156 			uio->uio_resid = 0;
   2157 			return (0);
   2158 		}
   2159 		if (tp->t_outq.c_cc > hiwat)
   2160 			goto ovhiwat;
   2161 		/*
   2162 		 * Grab a hunk of data from the user, unless we have some
   2163 		 * leftover from last time.
   2164 		 */
   2165 		if (cc == 0) {
   2166 			cc = min(uio->uio_resid, OBUFSIZ);
   2167 			cp = obuf;
   2168 			error = uiomove(cp, cc, uio);
   2169 			if (error) {
   2170 				cc = 0;
   2171 				goto out;
   2172 			}
   2173 		}
   2174 		/*
   2175 		 * If nothing fancy need be done, grab those characters we
   2176 		 * can handle without any of ttyoutput's processing and
   2177 		 * just transfer them to the output q.  For those chars
   2178 		 * which require special processing (as indicated by the
   2179 		 * bits in char_type), call ttyoutput.  After processing
   2180 		 * a hunk of data, look for FLUSHO so ^O's will take effect
   2181 		 * immediately.
   2182 		 */
   2183 		mutex_spin_enter(&tty_lock);
   2184 		while (cc > 0) {
   2185 			if (!ISSET(tp->t_oflag, OPOST))
   2186 				ce = cc;
   2187 			else {
   2188 				ce = cc - scanc((u_int)cc, cp, char_type,
   2189 				    CCLASSMASK);
   2190 				/*
   2191 				 * If ce is zero, then we're processing
   2192 				 * a special character through ttyoutput.
   2193 				 */
   2194 				if (ce == 0) {
   2195 					tp->t_rocount = 0;
   2196 					if (ttyoutput(*cp, tp) >= 0) {
   2197 						/* out of space */
   2198 						mutex_spin_exit(&tty_lock);
   2199 						goto overfull;
   2200 					}
   2201 					cp++;
   2202 					cc--;
   2203 					if (ISSET(tp->t_lflag, FLUSHO) ||
   2204 					    tp->t_outq.c_cc > hiwat) {
   2205 						mutex_spin_exit(&tty_lock);
   2206 						goto ovhiwat;
   2207 					}
   2208 					continue;
   2209 				}
   2210 			}
   2211 			/*
   2212 			 * A bunch of normal characters have been found.
   2213 			 * Transfer them en masse to the output queue and
   2214 			 * continue processing at the top of the loop.
   2215 			 * If there are any further characters in this
   2216 			 * <= OBUFSIZ chunk, the first should be a character
   2217 			 * requiring special handling by ttyoutput.
   2218 			 */
   2219 			tp->t_rocount = 0;
   2220 			i = b_to_q(cp, ce, &tp->t_outq);
   2221 			ce -= i;
   2222 			tp->t_column += ce;
   2223 			cp += ce, cc -= ce, tk_nout += ce;
   2224 			tp->t_outcc += ce;
   2225 			if (i > 0) {
   2226 				/* out of space */
   2227 				mutex_spin_exit(&tty_lock);
   2228 				goto overfull;
   2229 			}
   2230 			if (ISSET(tp->t_lflag, FLUSHO) ||
   2231 			    tp->t_outq.c_cc > hiwat)
   2232 				break;
   2233 		}
   2234 		ttstart(tp);
   2235 		mutex_spin_exit(&tty_lock);
   2236 	}
   2237 
   2238  out:
   2239 	/*
   2240 	 * If cc is nonzero, we leave the uio structure inconsistent, as the
   2241 	 * offset and iov pointers have moved forward, but it doesn't matter
   2242 	 * (the call will either return short or restart with a new uio).
   2243 	 */
   2244 	uio->uio_resid += cc;
   2245 	return (error);
   2246 
   2247  overfull:
   2248 	/*
   2249 	 * Since we are using ring buffers, if we can't insert any more into
   2250 	 * the output queue, we can assume the ring is full and that someone
   2251 	 * forgot to set the high water mark correctly.  We set it and then
   2252 	 * proceed as normal.
   2253 	 */
   2254 	hiwat = tp->t_outq.c_cc - 1;
   2255 
   2256  ovhiwat:
   2257 	mutex_spin_enter(&tty_lock);
   2258 	ttstart(tp);
   2259 	/*
   2260 	 * This can only occur if FLUSHO is set in t_lflag,
   2261 	 * or if ttstart/oproc is synchronous (or very fast).
   2262 	 */
   2263 	if (tp->t_outq.c_cc <= hiwat) {
   2264 		mutex_spin_exit(&tty_lock);
   2265 		goto loop;
   2266 	}
   2267 	if (flag & IO_NDELAY) {
   2268 		mutex_spin_exit(&tty_lock);
   2269 		error = EWOULDBLOCK;
   2270 		goto out;
   2271 	}
   2272 	error = ttysleep(tp, &tp->t_outcv, true, 0);
   2273 	mutex_spin_exit(&tty_lock);
   2274 	if (error)
   2275 		goto out;
   2276 	goto loop;
   2277 }
   2278 
   2279 /*
   2280  * Try to pull more output from the producer.  Return non-zero if
   2281  * there is output ready to be sent.
   2282  */
   2283 bool
   2284 ttypull(struct tty *tp)
   2285 {
   2286 
   2287 	/* XXXSMP not yet KASSERT(mutex_owned(&tty_lock)); */
   2288 
   2289 	if (tp->t_outq.c_cc <= tp->t_lowat) {
   2290 		cv_broadcast(&tp->t_outcv);
   2291 		selnotify(&tp->t_wsel, 0, NOTE_SUBMIT);
   2292 	}
   2293 	return tp->t_outq.c_cc != 0;
   2294 }
   2295 
   2296 /*
   2297  * Rubout one character from the rawq of tp
   2298  * as cleanly as possible.
   2299  * Called with tty lock held.
   2300  */
   2301 void
   2302 ttyrub(int c, struct tty *tp)
   2303 {
   2304 	u_char	*cp;
   2305 	int	savecol, tabc;
   2306 
   2307 	KASSERT(mutex_owned(&tty_lock));
   2308 
   2309 	if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
   2310 		return;
   2311 	CLR(tp->t_lflag, FLUSHO);
   2312 	if (ISSET(tp->t_lflag, ECHOE)) {
   2313 		if (tp->t_rocount == 0) {
   2314 			/*
   2315 			 * Screwed by ttwrite; retype
   2316 			 */
   2317 			ttyretype(tp);
   2318 			return;
   2319 		}
   2320 		if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
   2321 			ttyrubo(tp, 2);
   2322 		else {
   2323 			CLR(c, ~TTY_CHARMASK);
   2324 			switch (CCLASS(c)) {
   2325 			case ORDINARY:
   2326 				ttyrubo(tp, 1);
   2327 				break;
   2328 			case BACKSPACE:
   2329 			case CONTROL:
   2330 			case NEWLINE:
   2331 			case RETURN:
   2332 			case VTAB:
   2333 				if (ISSET(tp->t_lflag, ECHOCTL))
   2334 					ttyrubo(tp, 2);
   2335 				break;
   2336 			case TAB:
   2337 				if (tp->t_rocount < tp->t_rawq.c_cc) {
   2338 					ttyretype(tp);
   2339 					return;
   2340 				}
   2341 				savecol = tp->t_column;
   2342 				SET(tp->t_state, TS_CNTTB);
   2343 				SET(tp->t_lflag, FLUSHO);
   2344 				tp->t_column = tp->t_rocol;
   2345 				for (cp = firstc(&tp->t_rawq, &tabc); cp;
   2346 				    cp = nextc(&tp->t_rawq, cp, &tabc))
   2347 					ttyecho(tabc, tp);
   2348 				CLR(tp->t_lflag, FLUSHO);
   2349 				CLR(tp->t_state, TS_CNTTB);
   2350 
   2351 				/* savecol will now be length of the tab. */
   2352 				savecol -= tp->t_column;
   2353 				tp->t_column += savecol;
   2354 				if (savecol > 8)
   2355 					savecol = 8;	/* overflow screw */
   2356 				while (--savecol >= 0)
   2357 					(void)ttyoutput('\b', tp);
   2358 				break;
   2359 			default:			/* XXX */
   2360 				(void)printf("ttyrub: would panic c = %d, "
   2361 				    "val = %d\n", c, CCLASS(c));
   2362 			}
   2363 		}
   2364 	} else if (ISSET(tp->t_lflag, ECHOPRT)) {
   2365 		if (!ISSET(tp->t_state, TS_ERASE)) {
   2366 			SET(tp->t_state, TS_ERASE);
   2367 			(void)ttyoutput('\\', tp);
   2368 		}
   2369 		ttyecho(c, tp);
   2370 	} else
   2371 		ttyecho(tp->t_cc[VERASE], tp);
   2372 	--tp->t_rocount;
   2373 }
   2374 
   2375 /*
   2376  * Back over cnt characters, erasing them.
   2377  * Called with tty lock held.
   2378  */
   2379 static void
   2380 ttyrubo(struct tty *tp, int cnt)
   2381 {
   2382 
   2383 	KASSERT(mutex_owned(&tty_lock));
   2384 
   2385 	while (cnt-- > 0) {
   2386 		(void)ttyoutput('\b', tp);
   2387 		(void)ttyoutput(' ', tp);
   2388 		(void)ttyoutput('\b', tp);
   2389 	}
   2390 }
   2391 
   2392 /*
   2393  * ttyretype --
   2394  *	Reprint the rawq line.  Note, it is assumed that c_cc has already
   2395  *	been checked.
   2396  *
   2397  * Called with tty lock held.
   2398  */
   2399 void
   2400 ttyretype(struct tty *tp)
   2401 {
   2402 	u_char	*cp;
   2403 	int	c;
   2404 
   2405 	KASSERT(mutex_owned(&tty_lock));
   2406 
   2407 	/* Echo the reprint character. */
   2408 	if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
   2409 		ttyecho(tp->t_cc[VREPRINT], tp);
   2410 
   2411 	(void)ttyoutput('\n', tp);
   2412 
   2413 	for (cp = firstc(&tp->t_canq, &c); cp; cp = nextc(&tp->t_canq, cp, &c))
   2414 		ttyecho(c, tp);
   2415 	for (cp = firstc(&tp->t_rawq, &c); cp; cp = nextc(&tp->t_rawq, cp, &c))
   2416 		ttyecho(c, tp);
   2417 	CLR(tp->t_state, TS_ERASE);
   2418 
   2419 	tp->t_rocount = tp->t_rawq.c_cc;
   2420 	tp->t_rocol = 0;
   2421 }
   2422 
   2423 /*
   2424  * Echo a typed character to the terminal.
   2425  * Called with tty lock held.
   2426  */
   2427 static void
   2428 ttyecho(int c, struct tty *tp)
   2429 {
   2430 
   2431 	KASSERT(mutex_owned(&tty_lock));
   2432 
   2433 	if (!ISSET(tp->t_state, TS_CNTTB))
   2434 		CLR(tp->t_lflag, FLUSHO);
   2435 	if ((!ISSET(tp->t_lflag, ECHO) &&
   2436 	    (!ISSET(tp->t_lflag, ECHONL) || c != '\n')) ||
   2437 	    ISSET(tp->t_lflag, EXTPROC))
   2438 		return;
   2439 	if (((ISSET(tp->t_lflag, ECHOCTL) &&
   2440 	    (ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n')) ||
   2441 	    ISSET(c, TTY_CHARMASK) == 0177)) {
   2442 		(void)ttyoutput('^', tp);
   2443 		CLR(c, ~TTY_CHARMASK);
   2444 		if (c == 0177)
   2445 			c = '?';
   2446 		else
   2447 			c += 'A' - 1;
   2448 	}
   2449 	(void)ttyoutput(c, tp);
   2450 }
   2451 
   2452 /*
   2453  * Wake up any readers on a tty.
   2454  * Called with tty lock held.
   2455  */
   2456 void
   2457 ttwakeup(struct tty *tp)
   2458 {
   2459 
   2460 	KASSERT(mutex_owned(&tty_lock));
   2461 
   2462 	selnotify(&tp->t_rsel, 0, NOTE_SUBMIT);
   2463 	if (ISSET(tp->t_state, TS_ASYNC))
   2464 		ttysig(tp, TTYSIG_PG2, SIGIO);
   2465 	cv_broadcast(&tp->t_rawcv);
   2466 }
   2467 
   2468 /*
   2469  * Look up a code for a specified speed in a conversion table;
   2470  * used by drivers to map software speed values to hardware parameters.
   2471  */
   2472 int
   2473 ttspeedtab(int speed, const struct speedtab *table)
   2474 {
   2475 
   2476 	for (; table->sp_speed != -1; table++)
   2477 		if (table->sp_speed == speed)
   2478 			return (table->sp_code);
   2479 	return (-1);
   2480 }
   2481 
   2482 /*
   2483  * Set tty hi and low water marks.
   2484  *
   2485  * Try to arrange the dynamics so there's about one second
   2486  * from hi to low water.
   2487  */
   2488 void
   2489 ttsetwater(struct tty *tp)
   2490 {
   2491 	int	cps, x;
   2492 
   2493 	/* XXX not yet KASSERT(mutex_owned(&tty_lock)); */
   2494 
   2495 #define	CLAMP(x, h, l)	((x) > h ? h : ((x) < l) ? l : (x))
   2496 
   2497 	cps = tp->t_ospeed / 10;
   2498 	tp->t_lowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
   2499 	x += cps;
   2500 	x = CLAMP(x, TTMAXHIWAT, TTMINHIWAT);
   2501 	tp->t_hiwat = roundup(x, TTROUND);
   2502 #undef	CLAMP
   2503 }
   2504 
   2505 /*
   2506  * Prepare report on state of foreground process group.
   2507  * Call with proc_lock held.
   2508  */
   2509 void
   2510 ttygetinfo(struct tty *tp, int fromsig, char *buf, size_t bufsz)
   2511 {
   2512 	struct lwp	*l;
   2513 	struct proc	*p, *pick = NULL;
   2514 	struct timeval	utime, stime;
   2515 	int		tmp;
   2516 	fixpt_t		pctcpu = 0;
   2517 	const char	*msg;
   2518 	char		lmsg[100];
   2519 	long		rss;
   2520 
   2521 	KASSERT(mutex_owned(proc_lock));
   2522 
   2523 	*buf = '\0';
   2524 
   2525 	if (tp->t_session == NULL)
   2526 		msg = "not a controlling terminal\n";
   2527 	else if (tp->t_pgrp == NULL)
   2528 		msg = "no foreground process group\n";
   2529 	else if ((p = LIST_FIRST(&tp->t_pgrp->pg_members)) == NULL)
   2530 		msg = "empty foreground process group\n";
   2531 	else {
   2532 		/* Pick interesting process. */
   2533 		for (; p != NULL; p = LIST_NEXT(p, p_pglist)) {
   2534 			struct proc *oldpick;
   2535 
   2536 			if (pick == NULL) {
   2537 				pick = p;
   2538 				continue;
   2539 			}
   2540 			if (pick->p_lock < p->p_lock) {
   2541 				mutex_enter(pick->p_lock);
   2542 				mutex_enter(p->p_lock);
   2543 			} else if (pick->p_lock > p->p_lock) {
   2544 				mutex_enter(p->p_lock);
   2545 				mutex_enter(pick->p_lock);
   2546 			} else
   2547 				mutex_enter(p->p_lock);
   2548 			oldpick = pick;
   2549 			if (proc_compare_wrapper(pick, p))
   2550 				pick = p;
   2551 			mutex_exit(p->p_lock);
   2552 			if (p->p_lock != oldpick->p_lock)
   2553 				mutex_exit(oldpick->p_lock);
   2554 		}
   2555 		if (fromsig &&
   2556 		    (SIGACTION_PS(pick->p_sigacts, SIGINFO).sa_flags &
   2557 		    SA_NOKERNINFO))
   2558 			return;
   2559 		msg = NULL;
   2560 	}
   2561 
   2562 	/* Print load average. */
   2563 	tmp = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
   2564 	snprintf(lmsg, sizeof(lmsg), "load: %d.%02d ", tmp / 100, tmp % 100);
   2565 	strlcat(buf, lmsg, bufsz);
   2566 
   2567 	if (pick == NULL) {
   2568 		strlcat(buf, msg, bufsz);
   2569 		return;
   2570 	}
   2571 
   2572 	snprintf(lmsg, sizeof(lmsg), " cmd: %s %d [", pick->p_comm,
   2573 	    pick->p_pid);
   2574 	strlcat(buf, lmsg, bufsz);
   2575 
   2576 	mutex_enter(pick->p_lock);
   2577 	LIST_FOREACH(l, &pick->p_lwps, l_sibling) {
   2578 		const char *lp;
   2579 		lwp_lock(l);
   2580 #ifdef LWP_PC
   2581 #define FMT_RUN "%#"PRIxVADDR
   2582 #define VAL_RUNNING (vaddr_t)LWP_PC(l)
   2583 #define VAL_RUNABLE (vaddr_t)LWP_PC(l)
   2584 #else
   2585 #define FMT_RUN "%s"
   2586 #define VAL_RUNNING "running"
   2587 #define VAL_RUNABLE "runnable"
   2588 #endif
   2589 		switch (l->l_stat) {
   2590 		case LSONPROC:
   2591 			snprintf(lmsg, sizeof(lmsg), FMT_RUN"/%d", VAL_RUNNING,
   2592 			    cpu_index(l->l_cpu));
   2593 			lp = lmsg;
   2594 			break;
   2595 		case LSRUN:
   2596 			snprintf(lmsg, sizeof(lmsg), FMT_RUN, VAL_RUNABLE);
   2597 			lp = lmsg;
   2598 			break;
   2599 		default:
   2600 			lp = l->l_wchan ? l->l_wmesg : "iowait";
   2601 			break;
   2602 		}
   2603 		strlcat(buf, lp, bufsz);
   2604 		strlcat(buf, LIST_NEXT(l, l_sibling) != NULL ? " " : "] ",
   2605 		    bufsz);
   2606 		pctcpu += l->l_pctcpu;
   2607 		lwp_unlock(l);
   2608 	}
   2609 	pctcpu += pick->p_pctcpu;
   2610 	calcru(pick, &utime, &stime, NULL, NULL);
   2611 	mutex_exit(pick->p_lock);
   2612 
   2613 	/* Round up and print user+system time, %CPU and RSS. */
   2614 	utime.tv_usec += 5000;
   2615 	if (utime.tv_usec >= 1000000) {
   2616 		utime.tv_sec += 1;
   2617 		utime.tv_usec -= 1000000;
   2618 	}
   2619 	stime.tv_usec += 5000;
   2620 	if (stime.tv_usec >= 1000000) {
   2621 		stime.tv_sec += 1;
   2622 		stime.tv_usec -= 1000000;
   2623 	}
   2624 #define	pgtok(a)	(((u_long) ((a) * PAGE_SIZE) / 1024))
   2625 	tmp = (pctcpu * 10000 + FSCALE / 2) >> FSHIFT;
   2626 	if (pick->p_stat == SIDL || P_ZOMBIE(pick))
   2627 		rss = 0;
   2628 	else
   2629 		rss = pgtok(vm_resident_count(pick->p_vmspace));
   2630 
   2631 	snprintf(lmsg, sizeof(lmsg), "%ld.%02ldu %ld.%02lds %d%% %ldk",
   2632 	    (long)utime.tv_sec, (long)utime.tv_usec / 10000,
   2633 	    (long)stime.tv_sec, (long)stime.tv_usec / 10000,
   2634 	    tmp / 100, rss);
   2635 	strlcat(buf, lmsg, bufsz);
   2636 }
   2637 
   2638 /*
   2639  * Print report on state of foreground process group.
   2640  * Call with tty_lock held.
   2641  */
   2642 void
   2643 ttyputinfo(struct tty *tp, char *buf)
   2644 {
   2645 
   2646 	KASSERT(mutex_owned(&tty_lock));
   2647 
   2648 	if (ttycheckoutq_wlock(tp, 0) == 0)
   2649 		return;
   2650 	ttyprintf_nolock(tp, "%s\n", buf);
   2651 	tp->t_rocount = 0;	/* so pending input will be retyped if BS */
   2652 }
   2653 
   2654 /*
   2655  * Returns 1 if p2 has a better chance being the active foreground process
   2656  * in a terminal instead of p1.
   2657  */
   2658 static int
   2659 proc_compare_wrapper(struct proc *p1, struct proc *p2)
   2660 {
   2661 	lwp_t *l1, *l2;
   2662 
   2663 	KASSERT(mutex_owned(p1->p_lock));
   2664 	KASSERT(mutex_owned(p2->p_lock));
   2665 
   2666 	if ((l1 = LIST_FIRST(&p1->p_lwps)) == NULL)
   2667 		return 1;
   2668 
   2669 	if ((l2 = LIST_FIRST(&p2->p_lwps)) == NULL)
   2670 		return 0;
   2671 
   2672 	return proc_compare(p1, l1, p2, l2);
   2673 }
   2674 
   2675 /*
   2676  * Output char to tty; console putchar style.
   2677  * Can be called with tty lock held through kprintf() machinery..
   2678  */
   2679 int
   2680 tputchar(int c, int flags, struct tty *tp)
   2681 {
   2682 	int r = 0;
   2683 
   2684 	if ((flags & NOLOCK) == 0)
   2685 		mutex_spin_enter(&tty_lock);
   2686 	if (!CONNECTED(tp)) {
   2687 		r = -1;
   2688 		goto out;
   2689 	}
   2690 	if (c == '\n')
   2691 		(void)ttyoutput('\r', tp);
   2692 	(void)ttyoutput(c, tp);
   2693 	ttstart(tp);
   2694 out:
   2695 	if ((flags & NOLOCK) == 0)
   2696 		mutex_spin_exit(&tty_lock);
   2697 	return (r);
   2698 }
   2699 
   2700 /*
   2701  * Sleep on chan, returning ERESTART if tty changed while we napped and
   2702  * returning any errors (e.g. EINTR/EWOULDBLOCK) reported by
   2703  * cv_timedwait(_sig).
   2704  * If the tty is revoked, restarting a pending call will redo validation done
   2705  * at the start of the call.
   2706  *
   2707  * Must be called with the tty lock held.
   2708  */
   2709 int
   2710 ttysleep(struct tty *tp, kcondvar_t *cv, bool catch_p, int timo)
   2711 {
   2712 	int	error;
   2713 	short	gen;
   2714 
   2715 	KASSERT(mutex_owned(&tty_lock));
   2716 
   2717 	gen = tp->t_gen;
   2718 	if (cv == NULL)
   2719 		error = kpause("ttypause", catch_p, timo, &tty_lock);
   2720 	else if (catch_p)
   2721 		error = cv_timedwait_sig(cv, &tty_lock, timo);
   2722 	else
   2723 		error = cv_timedwait(cv, &tty_lock, timo);
   2724 	if (error != 0)
   2725 		return (error);
   2726 	return (tp->t_gen == gen ? 0 : ERESTART);
   2727 }
   2728 
   2729 int
   2730 ttypause(struct tty *tp, int timo)
   2731 {
   2732 	int error;
   2733 
   2734 	error = ttysleep(tp, NULL, true, timo);
   2735 	if (error == EWOULDBLOCK)
   2736 		error = 0;
   2737 	return error;
   2738 }
   2739 
   2740 /*
   2741  * Attach a tty to the tty list.
   2742  *
   2743  * This should be called ONLY once per real tty (including pty's).
   2744  * eg, on the sparc, the keyboard and mouse have struct tty's that are
   2745  * distinctly NOT usable as tty's, and thus should not be attached to
   2746  * the ttylist.  This is why this call is not done from tty_alloc().
   2747  *
   2748  * Device drivers should attach tty's at a similar time that they are
   2749  * allocated, or, for the case of statically allocated struct tty's
   2750  * either in the attach or (first) open routine.
   2751  */
   2752 void
   2753 tty_attach(struct tty *tp)
   2754 {
   2755 
   2756 	mutex_spin_enter(&tty_lock);
   2757 	TAILQ_INSERT_TAIL(&ttylist, tp, tty_link);
   2758 	++tty_count;
   2759 	mutex_spin_exit(&tty_lock);
   2760 }
   2761 
   2762 /*
   2763  * Remove a tty from the tty list.
   2764  */
   2765 void
   2766 tty_detach(struct tty *tp)
   2767 {
   2768 
   2769 	mutex_spin_enter(&tty_lock);
   2770 	--tty_count;
   2771 #ifdef DIAGNOSTIC
   2772 	if (tty_count < 0)
   2773 		panic("tty_detach: tty_count < 0");
   2774 #endif
   2775 	TAILQ_REMOVE(&ttylist, tp, tty_link);
   2776 	mutex_spin_exit(&tty_lock);
   2777 }
   2778 
   2779 /*
   2780  * Allocate a tty structure and its associated buffers.
   2781  */
   2782 struct tty *
   2783 tty_alloc(void)
   2784 {
   2785 	struct tty *tp;
   2786 	int i;
   2787 
   2788 	tp = kmem_zalloc(sizeof(*tp), KM_SLEEP);
   2789 	callout_init(&tp->t_rstrt_ch, 0);
   2790 	callout_setfunc(&tp->t_rstrt_ch, ttrstrt, tp);
   2791 	tp->t_qsize = tty_qsize;
   2792 	clalloc(&tp->t_rawq, tp->t_qsize, 1);
   2793 	cv_init(&tp->t_rawcv, "ttyraw");
   2794 	cv_init(&tp->t_rawcvf, "ttyrawf");
   2795 	clalloc(&tp->t_canq, tp->t_qsize, 1);
   2796 	cv_init(&tp->t_cancv, "ttycan");
   2797 	cv_init(&tp->t_cancvf, "ttycanf");
   2798 	/* output queue doesn't need quoting */
   2799 	clalloc(&tp->t_outq, tp->t_qsize, 0);
   2800 	cv_init(&tp->t_outcv, "ttyout");
   2801 	cv_init(&tp->t_outcvf, "ttyoutf");
   2802 	/* Set default line discipline. */
   2803 	tp->t_linesw = ttyldisc_default();
   2804 	tp->t_dev = NODEV;
   2805 	selinit(&tp->t_rsel);
   2806 	selinit(&tp->t_wsel);
   2807 	for (i = 0; i < TTYSIG_COUNT; i++)  {
   2808 		sigemptyset(&tp->t_sigs[i]);
   2809 	}
   2810 
   2811 	return tp;
   2812 }
   2813 
   2814 /*
   2815  * Free a tty structure and its buffers.
   2816  *
   2817  * Be sure to call tty_detach() for any tty that has been
   2818  * tty_attach()ed.
   2819  */
   2820 void
   2821 tty_free(struct tty *tp)
   2822 {
   2823 	int i;
   2824 
   2825 	mutex_enter(proc_lock);
   2826 	mutex_enter(&tty_lock);
   2827 	for (i = 0; i < TTYSIG_COUNT; i++)
   2828 		sigemptyset(&tp->t_sigs[i]);
   2829 	if (tp->t_sigcount != 0)
   2830 		TAILQ_REMOVE(&tty_sigqueue, tp, t_sigqueue);
   2831 	mutex_exit(&tty_lock);
   2832 	mutex_exit(proc_lock);
   2833 
   2834 	callout_halt(&tp->t_rstrt_ch, NULL);
   2835 	callout_destroy(&tp->t_rstrt_ch);
   2836 	ttyldisc_release(tp->t_linesw);
   2837 	clfree(&tp->t_rawq);
   2838 	clfree(&tp->t_canq);
   2839 	clfree(&tp->t_outq);
   2840 	cv_destroy(&tp->t_rawcv);
   2841 	cv_destroy(&tp->t_rawcvf);
   2842 	cv_destroy(&tp->t_cancv);
   2843 	cv_destroy(&tp->t_cancvf);
   2844 	cv_destroy(&tp->t_outcv);
   2845 	cv_destroy(&tp->t_outcvf);
   2846 	seldestroy(&tp->t_rsel);
   2847 	seldestroy(&tp->t_wsel);
   2848 	kmem_free(tp, sizeof(*tp));
   2849 }
   2850 
   2851 /*
   2852  * ttyprintf_nolock: send a message to a specific tty, without locking.
   2853  *
   2854  * => should be used only by tty driver or anything that knows the
   2855  *    underlying tty will not be revoked(2)'d away.  [otherwise,
   2856  *    use tprintf]
   2857  */
   2858 static void
   2859 ttyprintf_nolock(struct tty *tp, const char *fmt, ...)
   2860 {
   2861 	va_list ap;
   2862 
   2863 	/* No mutex needed; going to process TTY. */
   2864 	va_start(ap, fmt);
   2865 	kprintf(fmt, TOTTY|NOLOCK, tp, NULL, ap);
   2866 	va_end(ap);
   2867 }
   2868 
   2869 static int
   2870 tty_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
   2871     void *arg0, void *arg1, void *arg2, void *arg3)
   2872 {
   2873 	struct tty *tty;
   2874 	int result;
   2875 
   2876 	result = KAUTH_RESULT_DEFER;
   2877 
   2878 	if (action != KAUTH_DEVICE_TTY_OPEN)
   2879 		return result;
   2880 
   2881 	tty = arg0;
   2882 
   2883 	/* If it's not opened, we allow. */
   2884 	if ((tty->t_state & TS_ISOPEN) == 0)
   2885 		result = KAUTH_RESULT_ALLOW;
   2886 	else {
   2887 		/*
   2888 		 * If it's opened, we can only allow if it's not exclusively
   2889 		 * opened; otherwise, that's a privileged operation and we
   2890 		 * let the secmodel handle it.
   2891 		 */
   2892 		if ((tty->t_state & TS_XCLUDE) == 0)
   2893 			result = KAUTH_RESULT_ALLOW;
   2894 	}
   2895 
   2896 	return result;
   2897 }
   2898 
   2899 /*
   2900  * Initialize the tty subsystem.
   2901  */
   2902 void
   2903 tty_init(void)
   2904 {
   2905 
   2906 	mutex_init(&tty_lock, MUTEX_DEFAULT, IPL_VM);
   2907 	rw_init(&ttcompat_lock);
   2908 	tty_sigsih = softint_establish(SOFTINT_CLOCK, ttysigintr, NULL);
   2909 	KASSERT(tty_sigsih != NULL);
   2910 
   2911 	tty_listener = kauth_listen_scope(KAUTH_SCOPE_DEVICE,
   2912 	    tty_listener_cb, NULL);
   2913 
   2914 	sysctl_kern_tty_setup();
   2915 }
   2916 
   2917 /*
   2918  * Send a signal from a tty to its process group or session leader.
   2919  * Handoff to the target is deferred to a soft interrupt.
   2920  */
   2921 void
   2922 ttysig(struct tty *tp, enum ttysigtype st, int sig)
   2923 {
   2924 	sigset_t *sp;
   2925 
   2926 	/* XXXSMP not yet KASSERT(mutex_owned(&tty_lock)); */
   2927 
   2928 	sp = &tp->t_sigs[st];
   2929 	if (sigismember(sp, sig))
   2930 		return;
   2931 	sigaddset(sp, sig);
   2932 	if (tp->t_sigcount++ == 0)
   2933 		TAILQ_INSERT_TAIL(&tty_sigqueue, tp, t_sigqueue);
   2934 	softint_schedule(tty_sigsih);
   2935 }
   2936 
   2937 /*
   2938  * Deliver deferred signals from ttys.  Note that the process groups
   2939  * and sessions associated with the ttys may have changed from when
   2940  * the signal was originally sent, but in practice it should not matter.
   2941  * For signals produced as a result of a syscall, the soft interrupt
   2942  * will fire before the syscall returns to the user.
   2943  */
   2944 static void
   2945 ttysigintr(void *cookie)
   2946 {
   2947 	struct tty *tp;
   2948 	enum ttysigtype st;
   2949 	struct pgrp *pgrp;
   2950 	struct session *sess;
   2951 	int sig, lflag;
   2952 	char infobuf[200];
   2953 
   2954 	mutex_enter(proc_lock);
   2955 	mutex_spin_enter(&tty_lock);
   2956 	while ((tp = TAILQ_FIRST(&tty_sigqueue)) != NULL) {
   2957 		KASSERT(tp->t_sigcount > 0);
   2958 		for (st = TTYSIG_PG1; st < TTYSIG_COUNT; st++) {
   2959 			if ((sig = firstsig(&tp->t_sigs[st])) != 0)
   2960 				break;
   2961 		}
   2962 		KASSERT(st < TTYSIG_COUNT);
   2963 		sigdelset(&tp->t_sigs[st], sig);
   2964 		if (--tp->t_sigcount == 0)
   2965 			TAILQ_REMOVE(&tty_sigqueue, tp, t_sigqueue);
   2966 		pgrp = tp->t_pgrp;
   2967 		sess = tp->t_session;
   2968 		lflag = tp->t_lflag;
   2969 		if  (sig == SIGINFO) {
   2970 			if (ISSET(tp->t_state, TS_SIGINFO)) {
   2971 				/* Via ioctl: ignore tty option. */
   2972 				tp->t_state &= ~TS_SIGINFO;
   2973 				lflag |= ISIG;
   2974 			}
   2975 			if (!ISSET(lflag, NOKERNINFO)) {
   2976 				mutex_spin_exit(&tty_lock);
   2977 				ttygetinfo(tp, 1, infobuf, sizeof(infobuf));
   2978 				mutex_spin_enter(&tty_lock);
   2979 				ttyputinfo(tp, infobuf);
   2980 			}
   2981 			if (!ISSET(lflag, ISIG))
   2982 				continue;
   2983 		}
   2984 		mutex_spin_exit(&tty_lock);
   2985 		KASSERT(sig != 0);
   2986 		switch (st) {
   2987 		case TTYSIG_PG1:
   2988 			if (pgrp != NULL)
   2989 				pgsignal(pgrp, sig, 1);
   2990 			break;
   2991 		case TTYSIG_PG2:
   2992 			if (pgrp != NULL)
   2993 				pgsignal(pgrp, sig, sess != NULL);
   2994 			break;
   2995 		case TTYSIG_LEADER:
   2996 			if (sess != NULL && sess->s_leader != NULL)
   2997 				psignal(sess->s_leader, sig);
   2998 			break;
   2999 		default:
   3000 			/* NOTREACHED */
   3001 			break;
   3002 		}
   3003 		mutex_spin_enter(&tty_lock);
   3004 	}
   3005 	mutex_spin_exit(&tty_lock);
   3006 	mutex_exit(proc_lock);
   3007 }
   3008 
   3009 unsigned char
   3010 tty_getctrlchar(struct tty *tp, unsigned which)
   3011 {
   3012 	KASSERT(which < NCCS);
   3013 	return tp->t_cc[which];
   3014 }
   3015 
   3016 void
   3017 tty_setctrlchar(struct tty *tp, unsigned which, unsigned char val)
   3018 {
   3019 	KASSERT(which < NCCS);
   3020 	tp->t_cc[which] = val;
   3021 }
   3022 
   3023 int
   3024 tty_try_xonxoff(struct tty *tp, unsigned char c)
   3025 {
   3026     const struct cdevsw *cdev;
   3027 
   3028     if (tp->t_iflag & IXON) {
   3029 	if (c == tp->t_cc[VSTOP] && tp->t_cc[VSTOP] != _POSIX_VDISABLE) {
   3030 	    if ((tp->t_state & TS_TTSTOP) == 0) {
   3031 		tp->t_state |= TS_TTSTOP;
   3032 		cdev = cdevsw_lookup(tp->t_dev);
   3033 		if (cdev != NULL)
   3034 			(*cdev->d_stop)(tp, 0);
   3035 	    }
   3036 	    return 0;
   3037 	}
   3038 	if (c == tp->t_cc[VSTART] && tp->t_cc[VSTART] != _POSIX_VDISABLE) {
   3039 	    tp->t_state &= ~TS_TTSTOP;
   3040 	    if (tp->t_oproc != NULL) {
   3041 	        mutex_spin_enter(&tty_lock);	/* XXX */
   3042 		(*tp->t_oproc)(tp);
   3043 	        mutex_spin_exit(&tty_lock);	/* XXX */
   3044 	    }
   3045 	    return 0;
   3046 	}
   3047     }
   3048     return EAGAIN;
   3049 }
   3050