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