xref: /openbsd-src/sys/kern/tty.c (revision d89ec533011f513df1010f142a111086a0785f09)
1 /*	$OpenBSD: tty.c,v 1.173 2021/12/15 15:30:47 visa 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 #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 const struct filterops ttyexcept_filtops = {
1115 	.f_flags	= FILTEROP_ISFD,
1116 	.f_attach	= NULL,
1117 	.f_detach	= filt_ttyrdetach,
1118 	.f_event	= filt_ttyexcept,
1119 };
1120 
1121 int
1122 ttkqfilter(dev_t dev, struct knote *kn)
1123 {
1124 	struct tty *tp = (*cdevsw[major(dev)].d_tty)(dev);
1125 	struct klist *klist;
1126 	int s;
1127 
1128 	switch (kn->kn_filter) {
1129 	case EVFILT_READ:
1130 		klist = &tp->t_rsel.si_note;
1131 		kn->kn_fop = &ttyread_filtops;
1132 		break;
1133 	case EVFILT_WRITE:
1134 		klist = &tp->t_wsel.si_note;
1135 		kn->kn_fop = &ttywrite_filtops;
1136 		break;
1137 	case EVFILT_EXCEPT:
1138 		if (kn->kn_flags & __EV_SELECT) {
1139 			/* Prevent triggering exceptfds. */
1140 			return (EPERM);
1141 		}
1142 		if ((kn->kn_flags & __EV_POLL) == 0) {
1143 			/* Disallow usage through kevent(2). */
1144 			return (EINVAL);
1145 		}
1146 		klist = &tp->t_rsel.si_note;
1147 		kn->kn_fop = &ttyexcept_filtops;
1148 		break;
1149 	default:
1150 		return (EINVAL);
1151 	}
1152 
1153 	kn->kn_hook = tp;
1154 
1155 	s = spltty();
1156 	klist_insert_locked(klist, kn);
1157 	splx(s);
1158 
1159 	return (0);
1160 }
1161 
1162 void
1163 filt_ttyrdetach(struct knote *kn)
1164 {
1165 	struct tty *tp = kn->kn_hook;
1166 	int s;
1167 
1168 	s = spltty();
1169 	klist_remove_locked(&tp->t_rsel.si_note, kn);
1170 	splx(s);
1171 }
1172 
1173 int
1174 filt_ttyread(struct knote *kn, long hint)
1175 {
1176 	struct tty *tp = kn->kn_hook;
1177 	int active, s;
1178 
1179 	s = spltty();
1180 	kn->kn_data = ttnread(tp);
1181 	active = (kn->kn_data > 0);
1182 	if (!ISSET(tp->t_cflag, CLOCAL) && !ISSET(tp->t_state, TS_CARR_ON)) {
1183 		kn->kn_flags |= EV_EOF;
1184 		if (kn->kn_flags & __EV_POLL)
1185 			kn->kn_flags |= __EV_HUP;
1186 		active = 1;
1187 	} else {
1188 		kn->kn_flags &= ~(EV_EOF | __EV_HUP);
1189 	}
1190 	splx(s);
1191 	return (active);
1192 }
1193 
1194 void
1195 filt_ttywdetach(struct knote *kn)
1196 {
1197 	struct tty *tp = kn->kn_hook;
1198 	int s;
1199 
1200 	s = spltty();
1201 	klist_remove_locked(&tp->t_wsel.si_note, kn);
1202 	splx(s);
1203 }
1204 
1205 int
1206 filt_ttywrite(struct knote *kn, long hint)
1207 {
1208 	struct tty *tp = kn->kn_hook;
1209 	int active, s;
1210 
1211 	s = spltty();
1212 	kn->kn_data = tp->t_outq.c_cn - tp->t_outq.c_cc;
1213 	active = (tp->t_outq.c_cc <= tp->t_lowat);
1214 
1215 	/* Write-side HUP condition is only for poll(2) and select(2). */
1216 	if (kn->kn_flags & (__EV_POLL | __EV_SELECT)) {
1217 		if (!ISSET(tp->t_cflag, CLOCAL) &&
1218 		    !ISSET(tp->t_state, TS_CARR_ON)) {
1219 			kn->kn_flags |= __EV_HUP;
1220 			active = 1;
1221 		} else {
1222 			kn->kn_flags &= ~__EV_HUP;
1223 		}
1224 	}
1225 	splx(s);
1226 	return (active);
1227 }
1228 
1229 int
1230 filt_ttyexcept(struct knote *kn, long hint)
1231 {
1232 	struct tty *tp = kn->kn_hook;
1233 	int active = 0;
1234 	int s;
1235 
1236 	s = spltty();
1237 	if (kn->kn_flags & __EV_POLL) {
1238 		if (!ISSET(tp->t_cflag, CLOCAL) &&
1239 		    !ISSET(tp->t_state, TS_CARR_ON)) {
1240 			kn->kn_flags |= __EV_HUP;
1241 			active = 1;
1242 		} else {
1243 			kn->kn_flags &= ~__EV_HUP;
1244 		}
1245 	}
1246 	splx(s);
1247 	return (active);
1248 }
1249 
1250 static int
1251 ttnread(struct tty *tp)
1252 {
1253 	int nread;
1254 
1255 	splassert(IPL_TTY);
1256 
1257 	if (ISSET(tp->t_lflag, PENDIN))
1258 		ttypend(tp);
1259 	nread = tp->t_canq.c_cc;
1260 	if (!ISSET(tp->t_lflag, ICANON)) {
1261 		nread += tp->t_rawq.c_cc;
1262 		if (nread < tp->t_cc[VMIN] && !tp->t_cc[VTIME])
1263 			nread = 0;
1264 	}
1265 	return (nread);
1266 }
1267 
1268 /*
1269  * Wait for output to drain, or if this times out, flush it.
1270  */
1271 int
1272 ttywait_nsec(struct tty *tp, uint64_t nsecs)
1273 {
1274 	int error, s;
1275 
1276 	error = 0;
1277 	s = spltty();
1278 	while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1279 	    (ISSET(tp->t_state, TS_CARR_ON) || ISSET(tp->t_cflag, CLOCAL)) &&
1280 	    tp->t_oproc) {
1281 		(*tp->t_oproc)(tp);
1282 		if ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1283 		    (ISSET(tp->t_state, TS_CARR_ON) || ISSET(tp->t_cflag, CLOCAL))
1284 		    && tp->t_oproc) {
1285 			SET(tp->t_state, TS_ASLEEP);
1286 			error = ttysleep_nsec(tp, &tp->t_outq, TTOPRI | PCATCH,
1287 			    ttyout, nsecs);
1288 			if (error == EWOULDBLOCK)
1289 				ttyflush(tp, FWRITE);
1290 			if (error)
1291 				break;
1292 		} else
1293 			break;
1294 	}
1295 	splx(s);
1296 	return (error);
1297 }
1298 
1299 int
1300 ttywait(struct tty *tp)
1301 {
1302 	return (ttywait_nsec(tp, INFSLP));
1303 }
1304 
1305 /*
1306  * Flush if successfully wait.
1307  */
1308 int
1309 ttywflush(struct tty *tp)
1310 {
1311 	int error;
1312 
1313 	error = ttywait_nsec(tp, SEC_TO_NSEC(5));
1314 	if (error == 0 || error == EWOULDBLOCK)
1315 		ttyflush(tp, FREAD);
1316 	return (error);
1317 }
1318 
1319 /*
1320  * Flush tty read and/or write queues, notifying anyone waiting.
1321  */
1322 void
1323 ttyflush(struct tty *tp, int rw)
1324 {
1325 	int s;
1326 
1327 	s = spltty();
1328 	if (rw & FREAD) {
1329 		FLUSHQ(&tp->t_canq);
1330 		FLUSHQ(&tp->t_rawq);
1331 		tp->t_rocount = 0;
1332 		tp->t_rocol = 0;
1333 		CLR(tp->t_state, TS_LOCAL);
1334 		ttyunblock(tp);
1335 		ttwakeup(tp);
1336 	}
1337 	if (rw & FWRITE) {
1338 		CLR(tp->t_state, TS_TTSTOP);
1339 		(*cdevsw[major(tp->t_dev)].d_stop)(tp, rw);
1340 		FLUSHQ(&tp->t_outq);
1341 		wakeup((caddr_t)&tp->t_outq);
1342 		selwakeup(&tp->t_wsel);
1343 	}
1344 	splx(s);
1345 }
1346 
1347 /*
1348  * Copy in the default termios characters.
1349  */
1350 void
1351 ttychars(struct tty *tp)
1352 {
1353 
1354 	memcpy(tp->t_cc, ttydefchars, sizeof(ttydefchars));
1355 }
1356 
1357 /*
1358  * Send stop character on input overflow.
1359  */
1360 static void
1361 ttyblock(struct tty *tp)
1362 {
1363 	int total;
1364 
1365 	total = tp->t_rawq.c_cc + tp->t_canq.c_cc;
1366 	if (tp->t_rawq.c_cc > TTYHOG(tp)) {
1367 		ttyflush(tp, FREAD | FWRITE);
1368 		CLR(tp->t_state, TS_TBLOCK);
1369 	}
1370 	/*
1371 	 * Block further input iff: current input > threshold
1372 	 * AND input is available to user program.
1373 	 */
1374 	if ((total >= TTYHOG(tp) / 2 &&
1375 	     !ISSET(tp->t_state, TS_TBLOCK) &&
1376 	     !ISSET(tp->t_lflag, ICANON)) || tp->t_canq.c_cc > 0) {
1377 		if (ISSET(tp->t_iflag, IXOFF) &&
1378 		    tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
1379 		    putc(tp->t_cc[VSTOP], &tp->t_outq) == 0) {
1380 			SET(tp->t_state, TS_TBLOCK);
1381 			ttstart(tp);
1382 		}
1383 		/* Try to block remote output via hardware flow control. */
1384 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
1385 		    (*tp->t_hwiflow)(tp, 1) != 0)
1386 			SET(tp->t_state, TS_TBLOCK);
1387 	}
1388 }
1389 
1390 void
1391 ttrstrt(void *arg)
1392 {
1393 	struct tty *tp = (struct tty *)arg;
1394 	int s;
1395 
1396 #ifdef DIAGNOSTIC
1397 	if (tp == NULL)
1398 		panic("ttrstrt");
1399 #endif
1400 	s = spltty();
1401 	CLR(tp->t_state, TS_TIMEOUT);
1402 	ttstart(tp);
1403 	splx(s);
1404 }
1405 
1406 int
1407 ttstart(struct tty *tp)
1408 {
1409 
1410 	if (tp->t_oproc != NULL)	/* XXX: Kludge for pty. */
1411 		(*tp->t_oproc)(tp);
1412 	return (0);
1413 }
1414 
1415 /*
1416  * "close" a line discipline
1417  */
1418 int
1419 ttylclose(struct tty *tp, int flag, struct proc *p)
1420 {
1421 
1422 	if (flag & FNONBLOCK)
1423 		ttyflush(tp, FREAD | FWRITE);
1424 	else
1425 		ttywflush(tp);
1426 	return (0);
1427 }
1428 
1429 /*
1430  * Handle modem control transition on a tty.
1431  * Flag indicates new state of carrier.
1432  * Returns 0 if the line should be turned off, otherwise 1.
1433  */
1434 int
1435 ttymodem(struct tty *tp, int flag)
1436 {
1437 
1438 	if (!ISSET(tp->t_state, TS_WOPEN) && ISSET(tp->t_cflag, MDMBUF)) {
1439 		/*
1440 		 * MDMBUF: do flow control according to carrier flag
1441 		 */
1442 		if (flag) {
1443 			CLR(tp->t_state, TS_TTSTOP);
1444 			ttstart(tp);
1445 		} else if (!ISSET(tp->t_state, TS_TTSTOP)) {
1446 			SET(tp->t_state, TS_TTSTOP);
1447 			(*cdevsw[major(tp->t_dev)].d_stop)(tp, 0);
1448 		}
1449 	} else if (flag == 0) {
1450 		/*
1451 		 * Lost carrier.
1452 		 */
1453 		CLR(tp->t_state, TS_CARR_ON);
1454 		if (ISSET(tp->t_state, TS_ISOPEN) &&
1455 		    !ISSET(tp->t_cflag, CLOCAL)) {
1456 			if (tp->t_session && tp->t_session->s_leader)
1457 				prsignal(tp->t_session->s_leader, SIGHUP);
1458 			ttyflush(tp, FREAD | FWRITE);
1459 			return (0);
1460 		}
1461 	} else {
1462 		/*
1463 		 * Carrier now on.
1464 		 */
1465 		SET(tp->t_state, TS_CARR_ON);
1466 		ttwakeup(tp);
1467 	}
1468 	return (1);
1469 }
1470 
1471 /*
1472  * Default modem control routine (for other line disciplines).
1473  * Return argument flag, to turn off device on carrier drop.
1474  */
1475 int
1476 nullmodem(struct tty *tp, int flag)
1477 {
1478 
1479 	if (flag)
1480 		SET(tp->t_state, TS_CARR_ON);
1481 	else {
1482 		CLR(tp->t_state, TS_CARR_ON);
1483 		if (ISSET(tp->t_state, TS_ISOPEN) &&
1484 		    !ISSET(tp->t_cflag, CLOCAL)) {
1485 			if (tp->t_session && tp->t_session->s_leader)
1486 				prsignal(tp->t_session->s_leader, SIGHUP);
1487 			ttyflush(tp, FREAD | FWRITE);
1488 			return (0);
1489 		}
1490 	}
1491 	return (1);
1492 }
1493 
1494 /*
1495  * Reinput pending characters after state switch
1496  * call at spltty().
1497  */
1498 void
1499 ttypend(struct tty *tp)
1500 {
1501 	struct clist tq;
1502 	int c;
1503 
1504 	splassert(IPL_TTY);
1505 
1506 	CLR(tp->t_lflag, PENDIN);
1507 	SET(tp->t_state, TS_TYPEN);
1508 	tq = tp->t_rawq;
1509 	tp->t_rawq.c_cc = 0;
1510 	tp->t_rawq.c_cf = tp->t_rawq.c_cl = NULL;
1511 	while ((c = getc(&tq)) >= 0)
1512 		ttyinput(c, tp);
1513 	CLR(tp->t_state, TS_TYPEN);
1514 }
1515 
1516 void ttvtimeout(void *);
1517 
1518 void
1519 ttvtimeout(void *arg)
1520 {
1521 	struct tty *tp = (struct tty *)arg;
1522 
1523 	wakeup(&tp->t_rawq);
1524 }
1525 
1526 /*
1527  * Process a read call on a tty device.
1528  */
1529 int
1530 ttread(struct tty *tp, struct uio *uio, int flag)
1531 {
1532 	struct timeout *stime = NULL;
1533 	struct proc *p = curproc;
1534 	struct process *pr = p->p_p;
1535 	int s, first, error = 0;
1536 	u_char *cc = tp->t_cc;
1537 	struct clist *qp;
1538 	int last_cc = 0;
1539 	long lflag;
1540 	int c;
1541 
1542 loop:	lflag = tp->t_lflag;
1543 	s = spltty();
1544 	/*
1545 	 * take pending input first
1546 	 */
1547 	if (ISSET(lflag, PENDIN))
1548 		ttypend(tp);
1549 	splx(s);
1550 
1551 	/*
1552 	 * Hang process if it's in the background.
1553 	 */
1554 	if (isbackground(pr, tp)) {
1555 		if (sigismasked(p, SIGTTIN) ||
1556 		    pr->ps_flags & PS_PPWAIT || pr->ps_pgrp->pg_jobc == 0) {
1557 			error = EIO;
1558 			goto out;
1559 		}
1560 		pgsignal(pr->ps_pgrp, SIGTTIN, 1);
1561 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, ttybg);
1562 		if (error)
1563 			goto out;
1564 		goto loop;
1565 	}
1566 
1567 	s = spltty();
1568 	if (!ISSET(lflag, ICANON)) {
1569 		int min = cc[VMIN];
1570 		int time = cc[VTIME] * 100;	/* tenths of a second (ms) */
1571 
1572 		qp = &tp->t_rawq;
1573 		/*
1574 		 * Check each of the four combinations.
1575 		 * (min > 0 && time == 0) is the normal read case.
1576 		 * It should be fairly efficient, so we check that and its
1577 		 * companion case (min == 0 && time == 0) first.
1578 		 */
1579 		if (time == 0) {
1580 			if (qp->c_cc < min)
1581 				goto sleep;
1582 			goto read;
1583 		}
1584 		if (min > 0) {
1585 			if (qp->c_cc <= 0)
1586 				goto sleep;
1587 			if (qp->c_cc >= min)
1588 				goto read;
1589 			if (stime == NULL) {
1590 alloc_timer:
1591 				stime = malloc(sizeof(*stime), M_TEMP, M_WAITOK);
1592 				timeout_set(stime, ttvtimeout, tp);
1593 				timeout_add_msec(stime, time);
1594 			} else if (qp->c_cc > last_cc) {
1595 				/* got a character, restart timer */
1596 				timeout_add_msec(stime, time);
1597 			}
1598 		} else {	/* min == 0 */
1599 			if (qp->c_cc > 0)
1600 				goto read;
1601 			if (stime == NULL) {
1602 				goto alloc_timer;
1603 			}
1604 		}
1605 		last_cc = qp->c_cc;
1606 		if (stime && !timeout_triggered(stime)) {
1607 			goto sleep;
1608 		}
1609 	} else if ((qp = &tp->t_canq)->c_cc <= 0) {
1610 		int carrier;
1611 
1612 sleep:
1613 		/*
1614 		 * If there is no input, sleep on rawq
1615 		 * awaiting hardware receipt and notification.
1616 		 * If we have data, we don't need to check for carrier.
1617 		 */
1618 		carrier = ISSET(tp->t_state, TS_CARR_ON) ||
1619 		    ISSET(tp->t_cflag, CLOCAL);
1620 		if (!carrier && ISSET(tp->t_state, TS_ISOPEN)) {
1621 			splx(s);
1622 			error = 0;
1623 			goto out;
1624 		}
1625 		if (flag & IO_NDELAY) {
1626 			splx(s);
1627 			error = EWOULDBLOCK;
1628 			goto out;
1629 		}
1630 		error = ttysleep(tp, &tp->t_rawq, TTIPRI | PCATCH,
1631 		    carrier ? ttyin : ttopen);
1632 		splx(s);
1633 		if (stime && timeout_triggered(stime))
1634 			error = EWOULDBLOCK;
1635 		if (cc[VMIN] == 0 && error == EWOULDBLOCK) {
1636 			error = 0;
1637 			goto out;
1638 		}
1639 		if (error && error != EWOULDBLOCK)
1640 			goto out;
1641 		error = 0;
1642 		goto loop;
1643 	}
1644 read:
1645 	splx(s);
1646 
1647 	/*
1648 	 * Input present, check for input mapping and processing.
1649 	 */
1650 	first = 1;
1651 	while ((c = getc(qp)) >= 0) {
1652 		/*
1653 		 * delayed suspend (^Y)
1654 		 */
1655 		if (CCEQ(cc[VDSUSP], c) &&
1656 		    ISSET(lflag, IEXTEN | ISIG) == (IEXTEN | ISIG)) {
1657 			pgsignal(tp->t_pgrp, SIGTSTP, 1);
1658 			if (first) {
1659 				error = ttysleep(tp, &lbolt, TTIPRI | PCATCH,
1660 				    ttybg);
1661 				if (error)
1662 					break;
1663 				goto loop;
1664 			}
1665 			break;
1666 		}
1667 		/*
1668 		 * Interpret EOF only in canonical mode.
1669 		 */
1670 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
1671 			break;
1672 		/*
1673 		 * Give user character.
1674 		 */
1675 		error = ureadc(c, uio);
1676 		if (error)
1677 			break;
1678 		if (uio->uio_resid == 0)
1679 			break;
1680 		/*
1681 		 * In canonical mode check for a "break character"
1682 		 * marking the end of a "line of input".
1683 		 */
1684 		if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
1685 			break;
1686 		first = 0;
1687 	}
1688 	/*
1689 	 * Look to unblock output now that (presumably)
1690 	 * the input queue has gone down.
1691 	 */
1692 	s = spltty();
1693 	if (tp->t_rawq.c_cc < TTYHOG(tp)/5)
1694 		ttyunblock(tp);
1695 	splx(s);
1696 
1697 out:
1698 	if (stime) {
1699 		timeout_del(stime);
1700 		free(stime, M_TEMP, sizeof(*stime));
1701 	}
1702 	return (error);
1703 }
1704 
1705 /* Call at spltty */
1706 void
1707 ttyunblock(struct tty *tp)
1708 {
1709 	u_char *cc = tp->t_cc;
1710 
1711 	splassert(IPL_TTY);
1712 
1713 	if (ISSET(tp->t_state, TS_TBLOCK)) {
1714 		if (ISSET(tp->t_iflag, IXOFF) &&
1715 		    cc[VSTART] != _POSIX_VDISABLE &&
1716 		    putc(cc[VSTART], &tp->t_outq) == 0) {
1717 			CLR(tp->t_state, TS_TBLOCK);
1718 			ttstart(tp);
1719 		}
1720 		/* Try to unblock remote output via hardware flow control. */
1721 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
1722 		    (*tp->t_hwiflow)(tp, 0) != 0)
1723 			CLR(tp->t_state, TS_TBLOCK);
1724 	}
1725 }
1726 
1727 /*
1728  * Check the output queue on tp for space for a kernel message (from uprintf
1729  * or tprintf).  Allow some space over the normal hiwater mark so we don't
1730  * lose messages due to normal flow control, but don't let the tty run amok.
1731  * Sleeps here are not interruptible, but we return prematurely if new signals
1732  * arrive.
1733  */
1734 int
1735 ttycheckoutq(struct tty *tp, int wait)
1736 {
1737 	int hiwat, s, oldsig;
1738 
1739 	hiwat = tp->t_hiwat;
1740 	s = spltty();
1741 	oldsig = wait ? SIGPENDING(curproc) : 0;
1742 	if (tp->t_outq.c_cc > hiwat + TTHIWATMINSPACE)
1743 		while (tp->t_outq.c_cc > hiwat) {
1744 			ttstart(tp);
1745 			if (wait == 0 || SIGPENDING(curproc) != oldsig) {
1746 				splx(s);
1747 				return (0);
1748 			}
1749 			SET(tp->t_state, TS_ASLEEP);
1750 			tsleep_nsec(&tp->t_outq, PZERO - 1, "ttckoutq",
1751 			    SEC_TO_NSEC(1));
1752 		}
1753 	splx(s);
1754 	return (1);
1755 }
1756 
1757 /*
1758  * Process a write call on a tty device.
1759  */
1760 int
1761 ttwrite(struct tty *tp, struct uio *uio, int flag)
1762 {
1763 	u_char *cp = NULL;
1764 	int cc, ce, obufcc = 0;
1765 	struct proc *p;
1766 	struct process *pr;
1767 	int hiwat, error, s;
1768 	size_t cnt;
1769 	u_char obuf[OBUFSIZ];
1770 
1771 	hiwat = tp->t_hiwat;
1772 	cnt = uio->uio_resid;
1773 	error = 0;
1774 	cc = 0;
1775 loop:
1776 	s = spltty();
1777 	if (!ISSET(tp->t_state, TS_CARR_ON) &&
1778 	    !ISSET(tp->t_cflag, CLOCAL)) {
1779 		if (ISSET(tp->t_state, TS_ISOPEN)) {
1780 			splx(s);
1781 			error = EIO;
1782 			goto done;
1783 		} else if (flag & IO_NDELAY) {
1784 			splx(s);
1785 			error = EWOULDBLOCK;
1786 			goto out;
1787 		} else {
1788 			/* Sleep awaiting carrier. */
1789 			error = ttysleep(tp,
1790 			    &tp->t_rawq, TTIPRI | PCATCH, ttopen);
1791 			splx(s);
1792 			if (error)
1793 				goto out;
1794 			goto loop;
1795 		}
1796 	}
1797 	splx(s);
1798 	/*
1799 	 * Hang the process if it's in the background.
1800 	 */
1801 	p = curproc;
1802 	pr = p->p_p;
1803 	if (isbackground(pr, tp) &&
1804 	    ISSET(tp->t_lflag, TOSTOP) && (pr->ps_flags & PS_PPWAIT) == 0 &&
1805 	    !sigismasked(p, SIGTTOU)) {
1806 		if (pr->ps_pgrp->pg_jobc == 0) {
1807 			error = EIO;
1808 			goto out;
1809 		}
1810 		pgsignal(pr->ps_pgrp, SIGTTOU, 1);
1811 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, ttybg);
1812 		if (error)
1813 			goto out;
1814 		goto loop;
1815 	}
1816 	/*
1817 	 * Process the user's data in at most OBUFSIZ chunks.  Perform any
1818 	 * output translation.  Keep track of high water mark, sleep on
1819 	 * overflow awaiting device aid in acquiring new space.
1820 	 */
1821 	while (uio->uio_resid > 0 || cc > 0) {
1822 		if (ISSET(tp->t_lflag, FLUSHO)) {
1823 			uio->uio_resid = 0;
1824 			goto done;
1825 		}
1826 		if (tp->t_outq.c_cc > hiwat)
1827 			goto ovhiwat;
1828 		/*
1829 		 * Grab a hunk of data from the user, unless we have some
1830 		 * leftover from last time.
1831 		 */
1832 		if (cc == 0) {
1833 			cc = MIN(uio->uio_resid, OBUFSIZ);
1834 			cp = obuf;
1835 			error = uiomove(cp, cc, uio);
1836 			if (error) {
1837 				cc = 0;
1838 				break;
1839 			}
1840 			if (cc > obufcc)
1841 				obufcc = cc;
1842 
1843 			/* duplicate /dev/console output into console buffer */
1844 			if (consbufp && cn_tab &&
1845 			    cn_tab->cn_dev == tp->t_dev && tp->t_gen == 0) {
1846 				int i;
1847 				for (i = 0; i < cc; i++) {
1848 					char c = cp[i];
1849 					if (c != '\0' && c != '\r' && c != 0177)
1850 						msgbuf_putchar(consbufp, c);
1851 				}
1852 			}
1853 		}
1854 		/*
1855 		 * If nothing fancy need be done, grab those characters we
1856 		 * can handle without any of ttyoutput's processing and
1857 		 * just transfer them to the output q.  For those chars
1858 		 * which require special processing (as indicated by the
1859 		 * bits in char_type), call ttyoutput.  After processing
1860 		 * a hunk of data, look for FLUSHO so ^O's will take effect
1861 		 * immediately.
1862 		 */
1863 		while (cc > 0) {
1864 			int i;
1865 			if (!ISSET(tp->t_oflag, OPOST))
1866 				ce = cc;
1867 			else {
1868 				ce = cc - scanc((u_int)cc, cp, char_type,
1869 				    CCLASSMASK);
1870 				/*
1871 				 * If ce is zero, then we're processing
1872 				 * a special character through ttyoutput.
1873 				 */
1874 				if (ce == 0) {
1875 					tp->t_rocount = 0;
1876 					if (ttyoutput(*cp, tp) >= 0) {
1877 						/* out of space */
1878 						goto ovhiwat;
1879 					}
1880 					cp++;
1881 					cc--;
1882 					if (ISSET(tp->t_lflag, FLUSHO) ||
1883 					    tp->t_outq.c_cc > hiwat)
1884 						goto ovhiwat;
1885 					continue;
1886 				}
1887 			}
1888 			/*
1889 			 * A bunch of normal characters have been found.
1890 			 * Transfer them en masse to the output queue and
1891 			 * continue processing at the top of the loop.
1892 			 * If there are any further characters in this
1893 			 * <= OBUFSIZ chunk, the first should be a character
1894 			 * requiring special handling by ttyoutput.
1895 			 */
1896 			tp->t_rocount = 0;
1897 			i = b_to_q(cp, ce, &tp->t_outq);
1898 			ce -= i;
1899 			tp->t_column += ce;
1900 			cp += ce, cc -= ce, tk_nout += ce;
1901 			tp->t_outcc += ce;
1902 			if (i > 0) {
1903 				/* out of space */
1904 				goto ovhiwat;
1905 			}
1906 			if (ISSET(tp->t_lflag, FLUSHO) ||
1907 			    tp->t_outq.c_cc > hiwat)
1908 				break;
1909 		}
1910 		ttstart(tp);
1911 	}
1912 out:
1913 	/*
1914 	 * If cc is nonzero, we leave the uio structure inconsistent, as the
1915 	 * offset and iov pointers have moved forward, but it doesn't matter
1916 	 * (the call will either return short or restart with a new uio).
1917 	 */
1918 	uio->uio_resid += cc;
1919 done:
1920 	if (obufcc)
1921 		explicit_bzero(obuf, obufcc);
1922 	return (error);
1923 
1924 ovhiwat:
1925 	ttstart(tp);
1926 	s = spltty();
1927 	/*
1928 	 * This can only occur if FLUSHO is set in t_lflag,
1929 	 * or if ttstart/oproc is synchronous (or very fast).
1930 	 */
1931 	if (tp->t_outq.c_cc <= hiwat) {
1932 		splx(s);
1933 		goto loop;
1934 	}
1935 	if (flag & IO_NDELAY) {
1936 		splx(s);
1937 		uio->uio_resid += cc;
1938 		if (obufcc)
1939 			explicit_bzero(obuf, obufcc);
1940 		return (uio->uio_resid == cnt ? EWOULDBLOCK : 0);
1941 	}
1942 	SET(tp->t_state, TS_ASLEEP);
1943 	error = ttysleep(tp, &tp->t_outq, TTOPRI | PCATCH, ttyout);
1944 	splx(s);
1945 	if (error)
1946 		goto out;
1947 	goto loop;
1948 }
1949 
1950 /*
1951  * Rubout one character from the rawq of tp
1952  * as cleanly as possible.
1953  */
1954 int
1955 ttyrub(int c, struct tty *tp)
1956 {
1957 	u_char *cp;
1958 	int savecol;
1959 	int tabc, s, cc;
1960 
1961 	if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
1962 		return 0;
1963 	CLR(tp->t_lflag, FLUSHO);
1964 	if (ISSET(tp->t_lflag, ECHOE)) {
1965 		if (tp->t_rocount == 0) {
1966 			/*
1967 			 * Screwed by ttwrite; retype
1968 			 */
1969 			return ttyretype(tp);
1970 		}
1971 		if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
1972 			ttyrubo(tp, 2);
1973 		else {
1974 			CLR(c, ~TTY_CHARMASK);
1975 			switch (CCLASS(c)) {
1976 			case ORDINARY:
1977 				ttyrubo(tp, 1);
1978 				break;
1979 			case BACKSPACE:
1980 			case CONTROL:
1981 			case NEWLINE:
1982 			case RETURN:
1983 			case VTAB:
1984 				if (ISSET(tp->t_lflag, ECHOCTL))
1985 					ttyrubo(tp, 2);
1986 				break;
1987 			case TAB:
1988 				if (tp->t_rocount < tp->t_rawq.c_cc)
1989 					return ttyretype(tp);
1990 				s = spltty();
1991 				savecol = tp->t_column;
1992 				SET(tp->t_state, TS_CNTTB);
1993 				SET(tp->t_lflag, FLUSHO);
1994 				tp->t_column = tp->t_rocol;
1995 				for (cp = firstc(&tp->t_rawq, &tabc, &cc); cp;
1996 				    cp = nextc(&tp->t_rawq, cp, &tabc, &cc))
1997 					ttyecho(tabc, tp);
1998 				CLR(tp->t_lflag, FLUSHO);
1999 				CLR(tp->t_state, TS_CNTTB);
2000 				splx(s);
2001 
2002 				/* savecol will now be length of the tab. */
2003 				savecol -= tp->t_column;
2004 				tp->t_column += savecol;
2005 				if (savecol > 8)
2006 					savecol = 8;	/* overflow screw */
2007 				while (--savecol >= 0)
2008 					(void)ttyoutput('\b', tp);
2009 				break;
2010 			default:			/* XXX */
2011 #define	PANICSTR	"ttyrub: would panic c = %d, val = %d"
2012 				(void)printf(PANICSTR "\n", c, CCLASS(c));
2013 #ifdef notdef
2014 				panic(PANICSTR, c, CCLASS(c));
2015 #endif
2016 			}
2017 		}
2018 	} else if (ISSET(tp->t_lflag, ECHOPRT)) {
2019 		if (!ISSET(tp->t_state, TS_ERASE)) {
2020 			SET(tp->t_state, TS_ERASE);
2021 			(void)ttyoutput('\\', tp);
2022 		}
2023 		ttyecho(c, tp);
2024 	} else
2025 		ttyecho(tp->t_cc[VERASE], tp);
2026 	--tp->t_rocount;
2027 	return 0;
2028 }
2029 
2030 /*
2031  * Back over cnt characters, erasing them.
2032  */
2033 static void
2034 ttyrubo(struct tty *tp, int cnt)
2035 {
2036 
2037 	while (cnt-- > 0) {
2038 		(void)ttyoutput('\b', tp);
2039 		(void)ttyoutput(' ', tp);
2040 		(void)ttyoutput('\b', tp);
2041 	}
2042 }
2043 
2044 /*
2045  * ttyretype --
2046  *	Reprint the rawq line.  Note, it is assumed that c_cc has already
2047  *	been checked.
2048  */
2049 int
2050 ttyretype(struct tty *tp)
2051 {
2052 	u_char *cp;
2053 	int s, c, cc;
2054 
2055 	/* Echo the reprint character. */
2056 	if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
2057 		ttyecho(tp->t_cc[VREPRINT], tp);
2058 
2059 	(void)ttyoutput('\n', tp);
2060 
2061 	s = spltty();
2062 	for (cp = firstc(&tp->t_canq, &c, &cc); cp;
2063 	    cp = nextc(&tp->t_canq, cp, &c, &cc))
2064 		ttyecho(c, tp);
2065 	for (cp = firstc(&tp->t_rawq, &c, &cc); cp;
2066 	    cp = nextc(&tp->t_rawq, cp, &c, &cc))
2067 		ttyecho(c, tp);
2068 	CLR(tp->t_state, TS_ERASE);
2069 	splx(s);
2070 
2071 	tp->t_rocount = tp->t_rawq.c_cc;
2072 	tp->t_rocol = 0;
2073 	return (1);
2074 }
2075 
2076 /*
2077  * Echo a typed character to the terminal.
2078  */
2079 static void
2080 ttyecho(int c, struct tty *tp)
2081 {
2082 
2083 	if (!ISSET(tp->t_state, TS_CNTTB))
2084 		CLR(tp->t_lflag, FLUSHO);
2085 	if ((!ISSET(tp->t_lflag, ECHO) &&
2086 	    (!ISSET(tp->t_lflag, ECHONL) || c != '\n')) ||
2087 	    ISSET(tp->t_lflag, EXTPROC))
2088 		return;
2089 	if (((ISSET(tp->t_lflag, ECHOCTL) &&
2090 	     (ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n')) ||
2091 	    ISSET(c, TTY_CHARMASK) == 0177)) {
2092 		(void)ttyoutput('^', tp);
2093 		CLR(c, ~TTY_CHARMASK);
2094 		if (c == 0177)
2095 			c = '?';
2096 		else
2097 			c += 'A' - 1;
2098 	}
2099 	(void)ttyoutput(c, tp);
2100 }
2101 
2102 /*
2103  * Wakeup any writers if necessary.
2104  */
2105 void
2106 ttwakeupwr(struct tty *tp)
2107 {
2108 
2109 	if (tp->t_outq.c_cc <= tp->t_lowat) {
2110 		if (ISSET(tp->t_state, TS_ASLEEP)) {
2111 			CLR(tp->t_state, TS_ASLEEP);
2112 			wakeup(&tp->t_outq);
2113 		}
2114 		selwakeup(&tp->t_wsel);
2115 	}
2116 }
2117 
2118 /*
2119  * Wake up any readers on a tty.
2120  */
2121 void
2122 ttwakeup(struct tty *tp)
2123 {
2124 
2125 	selwakeup(&tp->t_rsel);
2126 	if (ISSET(tp->t_state, TS_ASYNC))
2127 		pgsignal(tp->t_pgrp, SIGIO, 1);
2128 	wakeup((caddr_t)&tp->t_rawq);
2129 }
2130 
2131 /*
2132  * Look up a code for a specified speed in a conversion table;
2133  * used by drivers to map software speed values to hardware parameters.
2134  */
2135 int
2136 ttspeedtab(int speed, const struct speedtab *table)
2137 {
2138 
2139 	for ( ; table->sp_speed != -1; table++)
2140 		if (table->sp_speed == speed)
2141 			return (table->sp_code);
2142 	return (-1);
2143 }
2144 
2145 /*
2146  * Set tty hi and low water marks.
2147  *
2148  * Try to arrange the dynamics so there's about one second
2149  * from hi to low water.
2150  */
2151 void
2152 ttsetwater(struct tty *tp)
2153 {
2154 	int cps, x;
2155 
2156 #define CLAMP(x, h, l)	((x) > h ? h : ((x) < l) ? l : (x))
2157 
2158 	cps = tp->t_ospeed / 10;
2159 	tp->t_lowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
2160 	x += cps;
2161 	tp->t_hiwat = CLAMP(x, tp->t_outq.c_cn - TTHIWATMINSPACE, TTMINHIWAT);
2162 #undef	CLAMP
2163 }
2164 
2165 /*
2166  * Get the total estcpu for a process, summing across threads.
2167  * Returns true if at least one thread is runnable/running.
2168  */
2169 static int
2170 process_sum(struct process *pr, fixpt_t *estcpup)
2171 {
2172 	struct proc *p;
2173 	fixpt_t estcpu;
2174 	int ret;
2175 
2176 	ret = 0;
2177 	estcpu = 0;
2178 	TAILQ_FOREACH(p, &pr->ps_threads, p_thr_link) {
2179 		if (p->p_stat == SRUN || p->p_stat == SONPROC)
2180 			ret = 1;
2181 		estcpu += p->p_pctcpu;
2182 	}
2183 
2184 	*estcpup = estcpu;
2185 	return (ret);
2186 }
2187 
2188 /*
2189  * Report on state of foreground process group.
2190  */
2191 void
2192 ttyinfo(struct tty *tp)
2193 {
2194 	struct process *pr, *pickpr;
2195 	struct proc *p, *pick;
2196 	struct timespec utime, stime;
2197 	int tmp;
2198 
2199 	if (ttycheckoutq(tp,0) == 0)
2200 		return;
2201 
2202 	/* Print load average. */
2203 	tmp = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
2204 	ttyprintf(tp, "load: %d.%02d ", tmp / 100, tmp % 100);
2205 
2206 	if (tp->t_session == NULL)
2207 		ttyprintf(tp, "not a controlling terminal\n");
2208 	else if (tp->t_pgrp == NULL)
2209 		ttyprintf(tp, "no foreground process group\n");
2210 	else if ((pr = LIST_FIRST(&tp->t_pgrp->pg_members)) == NULL)
2211 empty:		ttyprintf(tp, "empty foreground process group\n");
2212 	else {
2213 		const char *state;
2214 		fixpt_t pctcpu, pctcpu2;
2215 		int run, run2;
2216 		int calc_pctcpu;
2217 		long rss = 0;
2218 
2219 		/*
2220 		 * Pick the most active process:
2221 		 *  - prefer at least one running/runnable thread
2222 		 *  - prefer higher total pctcpu
2223 		 *  - prefer non-zombie
2224 		 * Otherwise take the most recently added to this process group
2225 		 */
2226 		pickpr = pr;
2227 		run = process_sum(pickpr, &pctcpu);
2228 		while ((pr = LIST_NEXT(pr, ps_pglist)) != NULL) {
2229 			run2 = process_sum(pr, &pctcpu2);
2230 			if (run) {
2231 				/*
2232 				 * pick is running; is p running w/same or
2233 				 * more cpu?
2234 				 */
2235 				if (run2 && pctcpu2 >= pctcpu)
2236 					goto update_pickpr;
2237 				continue;
2238 			}
2239 			/* pick isn't running; is p running *or* w/more cpu? */
2240 			if (run2 || pctcpu2 > pctcpu)
2241 				goto update_pickpr;
2242 
2243 			/* if p has less cpu or is zombie, then it's worse */
2244 			if (pctcpu2 < pctcpu || (pr->ps_flags & PS_ZOMBIE))
2245 				continue;
2246 update_pickpr:
2247 			pickpr = pr;
2248 			run = run2;
2249 			pctcpu = pctcpu2;
2250 		}
2251 
2252 		/* Calculate percentage cpu, resident set size. */
2253 		calc_pctcpu = (pctcpu * 10000 + FSCALE / 2) >> FSHIFT;
2254 		if ((pickpr->ps_flags & (PS_EMBRYO | PS_ZOMBIE)) == 0 &&
2255 		    pickpr->ps_vmspace != NULL)
2256 			rss = vm_resident_count(pickpr->ps_vmspace);
2257 
2258 		calctsru(&pickpr->ps_tu, &utime, &stime, NULL);
2259 
2260 		/* Round up and print user time. */
2261 		utime.tv_nsec += 5000000;
2262 		if (utime.tv_nsec >= 1000000000) {
2263 			utime.tv_sec += 1;
2264 			utime.tv_nsec -= 1000000000;
2265 		}
2266 
2267 		/* Round up and print system time. */
2268 		stime.tv_nsec += 5000000;
2269 		if (stime.tv_nsec >= 1000000000) {
2270 			stime.tv_sec += 1;
2271 			stime.tv_nsec -= 1000000000;
2272 		}
2273 
2274 		/*
2275 		 * Find the most active thread:
2276 		 *  - prefer runnable
2277 		 *  - prefer higher pctcpu
2278 		 *  - prefer living
2279 		 * Otherwise take the newest thread
2280 		 */
2281 		pick = p = TAILQ_FIRST(&pickpr->ps_threads);
2282 		if (p == NULL)
2283 			goto empty;
2284 		run = p->p_stat == SRUN || p->p_stat == SONPROC;
2285 		pctcpu = p->p_pctcpu;
2286 		while ((p = TAILQ_NEXT(p, p_thr_link)) != NULL) {
2287 			run2 = p->p_stat == SRUN || p->p_stat == SONPROC;
2288 			pctcpu2 = p->p_pctcpu;
2289 			if (run) {
2290 				/*
2291 				 * pick is running; is p running w/same or
2292 				 * more cpu?
2293 				 */
2294 				if (run2 && pctcpu2 >= pctcpu)
2295 					goto update_pick;
2296 				continue;
2297 			}
2298 			/* pick isn't running; is p running *or* w/more cpu? */
2299 			if (run2 || pctcpu2 > pctcpu)
2300 				goto update_pick;
2301 
2302 			/* if p has less cpu or is exiting, then it's worse */
2303 			if (pctcpu2 < pctcpu || p->p_flag & P_WEXIT)
2304 				continue;
2305 update_pick:
2306 			pick = p;
2307 			run = run2;
2308 			pctcpu = p->p_pctcpu;
2309 		}
2310 		state = pick->p_stat == SONPROC ? "running" :
2311 		        pick->p_stat == SRUN ? "runnable" :
2312 		        pick->p_wmesg ? pick->p_wmesg : "iowait";
2313 
2314 		ttyprintf(tp,
2315 		    " cmd: %s %d [%s] %lld.%02ldu %lld.%02lds %d%% %ldk\n",
2316 		    pickpr->ps_comm, pickpr->ps_pid, state,
2317 		    (long long)utime.tv_sec, utime.tv_nsec / 10000000,
2318 		    (long long)stime.tv_sec, stime.tv_nsec / 10000000,
2319 		    calc_pctcpu / 100, rss);
2320 	}
2321 	tp->t_rocount = 0;	/* so pending input will be retyped if BS */
2322 }
2323 
2324 /*
2325  * Output char to tty; console putchar style.
2326  */
2327 int
2328 tputchar(int c, struct tty *tp)
2329 {
2330 	int s;
2331 
2332 	s = spltty();
2333 	if (ISSET(tp->t_state, TS_ISOPEN) == 0 ||
2334 	    !(ISSET(tp->t_state, TS_CARR_ON) || ISSET(tp->t_cflag, CLOCAL))) {
2335 		splx(s);
2336 		return (-1);
2337 	}
2338 	if (c == '\n')
2339 		(void)ttyoutput('\r', tp);
2340 	(void)ttyoutput(c, tp);
2341 	ttstart(tp);
2342 	splx(s);
2343 	return (0);
2344 }
2345 
2346 /*
2347  * Sleep on chan, returning ERESTART if tty changed while we napped and
2348  * returning any errors (e.g. EINTR/ETIMEDOUT) reported by tsleep.  If
2349  * the tty is revoked, restarting a pending call will redo validation done
2350  * at the start of the call.
2351  */
2352 int
2353 ttysleep(struct tty *tp, void *chan, int pri, char *wmesg)
2354 {
2355 	return (ttysleep_nsec(tp, chan, pri, wmesg, INFSLP));
2356 }
2357 
2358 int
2359 ttysleep_nsec(struct tty *tp, void *chan, int pri, char *wmesg, uint64_t nsecs)
2360 {
2361 	int error;
2362 	short gen;
2363 
2364 	gen = tp->t_gen;
2365 	if ((error = tsleep_nsec(chan, pri, wmesg, nsecs)) != 0)
2366 		return (error);
2367 	return (tp->t_gen == gen ? 0 : ERESTART);
2368 }
2369 
2370 /*
2371  * Initialise the global tty list.
2372  */
2373 void
2374 tty_init(void)
2375 {
2376 
2377 	TAILQ_INIT(&ttylist);
2378 	tty_count = 0;
2379 }
2380 
2381 /*
2382  * Allocate a tty structure and its associated buffers, and attach it to the
2383  * tty list.
2384  */
2385 struct tty *
2386 ttymalloc(int baud)
2387 {
2388 	struct tty *tp;
2389 
2390 	tp = malloc(sizeof(struct tty), M_TTYS, M_WAITOK|M_ZERO);
2391 
2392 	if (baud == 0)
2393 		baud = 115200;
2394 
2395 	if (baud <= 9600)
2396 		tp->t_qlen = 1024;
2397 	else if (baud <= 115200)
2398 		tp->t_qlen = 4096;
2399 	else
2400 		tp->t_qlen = 8192;
2401 	clalloc(&tp->t_rawq, tp->t_qlen, 1);
2402 	clalloc(&tp->t_canq, tp->t_qlen, 1);
2403 	/* output queue doesn't need quoting */
2404 	clalloc(&tp->t_outq, tp->t_qlen, 0);
2405 
2406 	rw_enter_write(&ttylist_lock);
2407 	TAILQ_INSERT_TAIL(&ttylist, tp, tty_link);
2408 	++tty_count;
2409 	rw_exit_write(&ttylist_lock);
2410 
2411 	timeout_set(&tp->t_rstrt_to, ttrstrt, tp);
2412 
2413 	return(tp);
2414 }
2415 
2416 
2417 /*
2418  * Free a tty structure and its buffers, after removing it from the tty list.
2419  */
2420 void
2421 ttyfree(struct tty *tp)
2422 {
2423 	int s;
2424 
2425 	rw_enter_write(&ttylist_lock);
2426 	--tty_count;
2427 #ifdef DIAGNOSTIC
2428 	if (tty_count < 0)
2429 		panic("ttyfree: tty_count < 0");
2430 #endif
2431 	TAILQ_REMOVE(&ttylist, tp, tty_link);
2432 	rw_exit_write(&ttylist_lock);
2433 
2434 	s = spltty();
2435 	klist_invalidate(&tp->t_rsel.si_note);
2436 	klist_invalidate(&tp->t_wsel.si_note);
2437 	splx(s);
2438 
2439 	clfree(&tp->t_rawq);
2440 	clfree(&tp->t_canq);
2441 	clfree(&tp->t_outq);
2442 	free(tp, M_TTYS, sizeof(*tp));
2443 }
2444 
2445 void
2446 ttystats_init(struct itty **ttystats, int *ttycp, size_t *ttystatssiz)
2447 {
2448 	int ntty = 0, ttyc;
2449 	struct itty *itp;
2450 	struct tty *tp;
2451 
2452 	ttyc = tty_count;
2453 	*ttystatssiz = ttyc * sizeof(struct itty);
2454 	*ttystats = mallocarray(ttyc, sizeof(struct itty),
2455 	    M_SYSCTL, M_WAITOK|M_ZERO);
2456 
2457 	rw_enter_write(&ttylist_lock);
2458 	for (tp = TAILQ_FIRST(&ttylist), itp = *ttystats; tp && ntty++ < ttyc;
2459 	    tp = TAILQ_NEXT(tp, tty_link), itp++) {
2460 		itp->t_dev = tp->t_dev;
2461 		itp->t_rawq_c_cc = tp->t_rawq.c_cc;
2462 		itp->t_canq_c_cc = tp->t_canq.c_cc;
2463 		itp->t_outq_c_cc = tp->t_outq.c_cc;
2464 		itp->t_hiwat = tp->t_hiwat;
2465 		itp->t_lowat = tp->t_lowat;
2466 		if (ISSET(tp->t_oflag, OPOST))
2467 			itp->t_column = tp->t_column;
2468 		itp->t_state = tp->t_state;
2469 		itp->t_session = tp->t_session;
2470 		if (tp->t_pgrp)
2471 			itp->t_pgrp_pg_id = tp->t_pgrp->pg_id;
2472 		else
2473 			itp->t_pgrp_pg_id = 0;
2474 		itp->t_line = tp->t_line;
2475 	}
2476 	rw_exit_write(&ttylist_lock);
2477 	*ttycp = ntty;
2478 }
2479 
2480 /*
2481  * Return tty-related information.
2482  */
2483 int
2484 sysctl_tty(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
2485     size_t newlen)
2486 {
2487 	int err;
2488 
2489 	if (namelen != 1)
2490 		return (ENOTDIR);
2491 
2492 	switch (name[0]) {
2493 	case KERN_TTY_TKNIN:
2494 		return (sysctl_rdquad(oldp, oldlenp, newp, tk_nin));
2495 	case KERN_TTY_TKNOUT:
2496 		return (sysctl_rdquad(oldp, oldlenp, newp, tk_nout));
2497 	case KERN_TTY_TKRAWCC:
2498 		return (sysctl_rdquad(oldp, oldlenp, newp, tk_rawcc));
2499 	case KERN_TTY_TKCANCC:
2500 		return (sysctl_rdquad(oldp, oldlenp, newp, tk_cancc));
2501 	case KERN_TTY_INFO:
2502 	    {
2503 		struct itty *ttystats;
2504 		size_t ttystatssiz;
2505 		int ttyc;
2506 
2507 		ttystats_init(&ttystats, &ttyc, &ttystatssiz);
2508 		err = sysctl_rdstruct(oldp, oldlenp, newp, ttystats,
2509 		    ttyc * sizeof(struct itty));
2510 		free(ttystats, M_SYSCTL, ttystatssiz);
2511 		return (err);
2512 	    }
2513 	default:
2514 #if NPTY > 0
2515 		return (sysctl_pty(name, namelen, oldp, oldlenp, newp, newlen));
2516 #else
2517 		return (EOPNOTSUPP);
2518 #endif
2519 	}
2520 	/* NOTREACHED */
2521 }
2522 
2523 void
2524 ttytstamp(struct tty *tp, int octs, int ncts, int odcd, int ndcd)
2525 {
2526 	int doit = 0;
2527 
2528 	if (ncts ^ octs)
2529 		doit |= ncts ? ISSET(tp->t_flags, TS_TSTAMPCTSSET) :
2530 		    ISSET(tp->t_flags, TS_TSTAMPCTSCLR);
2531 	if (ndcd ^ odcd)
2532 		doit |= ndcd ? ISSET(tp->t_flags, TS_TSTAMPDCDSET) :
2533 		    ISSET(tp->t_flags, TS_TSTAMPDCDCLR);
2534 
2535 	if (doit)
2536 		microtime(&tp->t_tv);
2537 }
2538