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