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