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