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