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