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