xref: /openbsd-src/sys/kern/tty.c (revision c020cf82e0cc147236f01a8dca7052034cf9d30d)
1 /*	$OpenBSD: tty.c,v 1.157 2020/06/15 15:29:40 mpi Exp $	*/
2 /*	$NetBSD: tty.c,v 1.68.4.2 1996/06/06 16:04:52 thorpej Exp $	*/
3 
4 /*-
5  * Copyright (c) 1982, 1986, 1990, 1991, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  * (c) UNIX System Laboratories, Inc.
8  * All or some portions of this file are derived from material licensed
9  * to the University of California by American Telephone and Telegraph
10  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
11  * the permission of UNIX System Laboratories, Inc.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *	@(#)tty.c	8.8 (Berkeley) 1/21/94
38  */
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/ioctl.h>
43 #include <sys/proc.h>
44 #define	TTYDEFCHARS
45 #include <sys/tty.h>
46 #undef	TTYDEFCHARS
47 #include <sys/fcntl.h>
48 #include <sys/conf.h>
49 #include <sys/uio.h>
50 #include <sys/kernel.h>
51 #include <sys/vnode.h>
52 #include <sys/lock.h>
53 #include <sys/syslog.h>
54 #include <sys/malloc.h>
55 #include <sys/msgbuf.h>
56 #include <sys/signalvar.h>
57 #include <sys/resourcevar.h>
58 #include <sys/sysctl.h>
59 #include <sys/pool.h>
60 #include <sys/poll.h>
61 #include <sys/unistd.h>
62 #include <sys/pledge.h>
63 
64 #include <sys/namei.h>
65 
66 #include <uvm/uvm_extern.h>
67 
68 #include <dev/cons.h>
69 
70 #include "pty.h"
71 
72 static int ttnread(struct tty *);
73 static void ttyblock(struct tty *);
74 void ttyunblock(struct tty *);
75 static void ttyecho(int, struct tty *);
76 static void ttyrubo(struct tty *, int);
77 int	filt_ttyread(struct knote *kn, long hint);
78 void 	filt_ttyrdetach(struct knote *kn);
79 int	filt_ttywrite(struct knote *kn, long hint);
80 void 	filt_ttywdetach(struct knote *kn);
81 void	ttystats_init(struct itty **, size_t *);
82 int	ttywait_nsec(struct tty *, uint64_t);
83 int	ttysleep_nsec(struct tty *, void *, int, char *, uint64_t);
84 
85 /* Symbolic sleep message strings. */
86 char ttclos[]	= "ttycls";
87 char ttopen[]	= "ttyopn";
88 char ttybg[]	= "ttybg";
89 char ttyin[]	= "ttyin";
90 char ttyout[]	= "ttyout";
91 
92 /*
93  * Table with character classes and parity. The 8th bit indicates parity,
94  * the 7th bit indicates the character is an alphameric or underscore (for
95  * ALTWERASE), and the low 6 bits indicate delay type.  If the low 6 bits
96  * are 0 then the character needs no special processing on output; classes
97  * other than 0 might be translated or (not currently) require delays.
98  */
99 #define	E	0x00	/* Even parity. */
100 #define	O	0x80	/* Odd parity. */
101 #define	PARITY(c)	(char_type[c] & O)
102 
103 #define	ALPHA	0x40	/* Alpha or underscore. */
104 #define	ISALPHA(c)	(char_type[(c) & TTY_CHARMASK] & ALPHA)
105 
106 #define	CCLASSMASK	0x3f
107 #define	CCLASS(c)	(char_type[c] & CCLASSMASK)
108 
109 #define	BS	BACKSPACE
110 #define	CC	CONTROL
111 #define	CR	RETURN
112 #define	NA	ORDINARY | ALPHA
113 #define	NL	NEWLINE
114 #define	NO	ORDINARY
115 #define	TB	TAB
116 #define	VT	VTAB
117 
118 u_char const char_type[] = {
119 	E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC,	/* nul - bel */
120 	O|BS, E|TB, E|NL, O|CC, E|VT, O|CR, O|CC, E|CC, /* bs - si */
121 	O|CC, E|CC, E|CC, O|CC, E|CC, O|CC, O|CC, E|CC, /* dle - etb */
122 	E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC, /* can - us */
123 	O|NO, E|NO, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* sp - ' */
124 	E|NO, O|NO, O|NO, E|NO, O|NO, E|NO, E|NO, O|NO, /* ( - / */
125 	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* 0 - 7 */
126 	O|NA, E|NA, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* 8 - ? */
127 	O|NO, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* @ - G */
128 	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* H - O */
129 	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* P - W */
130 	O|NA, E|NA, E|NA, O|NO, E|NO, O|NO, O|NO, O|NA, /* X - _ */
131 	E|NO, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* ` - g */
132 	O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* h - o */
133 	O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* p - w */
134 	E|NA, O|NA, O|NA, E|NO, O|NO, E|NO, E|NO, O|CC, /* x - del */
135 	/*
136 	 * Meta chars; should be settable per character set;
137 	 * for now, treat them all as normal characters.
138 	 */
139 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
140 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
141 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
142 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
143 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
144 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
145 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
146 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
147 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
148 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
149 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
150 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
151 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
152 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
153 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
154 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
155 };
156 #undef	BS
157 #undef	CC
158 #undef	CR
159 #undef	NA
160 #undef	NL
161 #undef	NO
162 #undef	TB
163 #undef	VT
164 
165 #define	islower(c)	((c) >= 'a' && (c) <= 'z')
166 #define	isupper(c)	((c) >= 'A' && (c) <= 'Z')
167 
168 #define	tolower(c)	((c) - 'A' + 'a')
169 #define	toupper(c)	((c) - 'a' + 'A')
170 
171 struct ttylist_head ttylist;	/* TAILQ_HEAD */
172 int tty_count;
173 
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 	enqueue_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  FIOSETOWN:
727 	case  TIOCFLUSH:
728 	case  TIOCDRAIN:
729 	case  TIOCSBRK:
730 	case  TIOCCBRK:
731 	case  TIOCSETA:
732 	case  TIOCSETD:
733 	case  TIOCSETAF:
734 	case  TIOCSETAW:
735 	case  TIOCSPGRP:
736 	case  TIOCSTAT:
737 	case  TIOCSWINSZ:
738 		while (isbackground(pr, tp) &&
739 		    (pr->ps_flags & PS_PPWAIT) == 0 &&
740 		    (pr->ps_sigacts->ps_sigignore & sigmask(SIGTTOU)) == 0 &&
741 		    (p->p_sigmask & sigmask(SIGTTOU)) == 0) {
742 			if (pr->ps_pgrp->pg_jobc == 0)
743 				return (EIO);
744 			pgsignal(pr->ps_pgrp, SIGTTOU, 1);
745 			error = ttysleep(tp, &lbolt, TTOPRI | PCATCH,
746 			    ttybg);
747 			if (error)
748 				return (error);
749 		}
750 		break;
751 	}
752 
753 	switch (cmd) {			/* Process the ioctl. */
754 	case FIOASYNC:			/* set/clear async i/o */
755 		s = spltty();
756 		if (*(int *)data)
757 			SET(tp->t_state, TS_ASYNC);
758 		else
759 			CLR(tp->t_state, TS_ASYNC);
760 		splx(s);
761 		break;
762 	case FIONBIO:			/* set/clear non-blocking i/o */
763 		break;			/* XXX: delete. */
764 	case FIONREAD:			/* get # bytes to read */
765 		s = spltty();
766 		*(int *)data = ttnread(tp);
767 		splx(s);
768 		break;
769 	case TIOCEXCL:			/* set exclusive use of tty */
770 		s = spltty();
771 		SET(tp->t_state, TS_XCLUDE);
772 		splx(s);
773 		break;
774 	case TIOCFLUSH: {		/* flush buffers */
775 		int flags = *(int *)data;
776 
777 		if (flags == 0)
778 			flags = FREAD | FWRITE;
779 		else
780 			flags &= FREAD | FWRITE;
781 		ttyflush(tp, flags);
782 		break;
783 	}
784 	case TIOCCONS: {		/* become virtual console */
785 		if (*(int *)data) {
786 			struct nameidata nid;
787 
788 			if (constty != NULL && constty != tp &&
789 			    ISSET(constty->t_state, TS_CARR_ON | TS_ISOPEN) ==
790 			    (TS_CARR_ON | TS_ISOPEN))
791 				return (EBUSY);
792 
793 			/* ensure user can open the real console */
794 			NDINIT(&nid, LOOKUP, FOLLOW, UIO_SYSSPACE, "/dev/console", p);
795 			nid.ni_pledge = PLEDGE_RPATH | PLEDGE_WPATH;
796 			nid.ni_unveil = UNVEIL_READ | UNVEIL_WRITE;
797 			error = namei(&nid);
798 			if (error)
799 				return (error);
800 			vn_lock(nid.ni_vp, LK_EXCLUSIVE | LK_RETRY);
801 			error = VOP_ACCESS(nid.ni_vp, VREAD, p->p_ucred, p);
802 			VOP_UNLOCK(nid.ni_vp);
803 			vrele(nid.ni_vp);
804 			if (error)
805 				return (error);
806 
807 			constty = tp;
808 		} else if (tp == constty)
809 			constty = NULL;
810 		break;
811 	}
812 	case TIOCDRAIN:			/* wait till output drained */
813 		if ((error = ttywait(tp)) != 0)
814 			return (error);
815 		break;
816 	case TIOCGETA: {		/* get termios struct */
817 		struct termios *t = (struct termios *)data;
818 
819 		memcpy(t, &tp->t_termios, sizeof(struct termios));
820 		break;
821 	}
822 	case TIOCGETD:			/* get line discipline */
823 		*(int *)data = tp->t_line;
824 		break;
825 	case TIOCGWINSZ:		/* get window size */
826 		*(struct winsize *)data = tp->t_winsize;
827 		break;
828 	case TIOCGTSTAMP:
829 		s = spltty();
830 		*(struct timeval *)data = tp->t_tv;
831 		splx(s);
832 		break;
833 	case FIOGETOWN:			/* get pgrp of tty */
834 		if (!isctty(pr, tp) && suser(p))
835 			return (ENOTTY);
836 		*(int *)data = tp->t_pgrp ? -tp->t_pgrp->pg_id : 0;
837 		break;
838 	case TIOCGPGRP:			/* get pgrp of tty */
839 		if (!isctty(pr, tp) && suser(p))
840 			return (ENOTTY);
841 		*(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
842 		break;
843 	case TIOCGSID:			/* get sid of tty */
844 		if (!isctty(pr, tp))
845 			return (ENOTTY);
846 		*(int *)data = tp->t_session->s_leader->ps_pid;
847 		break;
848 #ifdef TIOCHPCL
849 	case TIOCHPCL:			/* hang up on last close */
850 		s = spltty();
851 		SET(tp->t_cflag, HUPCL);
852 		splx(s);
853 		break;
854 #endif
855 	case TIOCNXCL:			/* reset exclusive use of tty */
856 		s = spltty();
857 		CLR(tp->t_state, TS_XCLUDE);
858 		splx(s);
859 		break;
860 	case TIOCOUTQ:			/* output queue size */
861 		*(int *)data = tp->t_outq.c_cc;
862 		break;
863 	case TIOCSETA:			/* set termios struct */
864 	case TIOCSETAW:			/* drain output, set */
865 	case TIOCSETAF: {		/* drn out, fls in, set */
866 		struct termios *t = (struct termios *)data;
867 
868 		s = spltty();
869 		if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
870 			if ((error = ttywait(tp)) != 0) {
871 				splx(s);
872 				return (error);
873 			}
874 			if (cmd == TIOCSETAF)
875 				ttyflush(tp, FREAD);
876 		}
877 		if (!ISSET(t->c_cflag, CIGNORE)) {
878 			/*
879 			 * Some minor validation is necessary.
880 			 */
881 			if (t->c_ispeed < 0 || t->c_ospeed < 0) {
882 				splx(s);
883 				return (EINVAL);
884 			}
885 			/*
886 			 * Set device hardware.
887 			 */
888 			if (tp->t_param && (error = (*tp->t_param)(tp, t))) {
889 				splx(s);
890 				return (error);
891 			} else {
892 				if (!ISSET(tp->t_state, TS_CARR_ON) &&
893 				    ISSET(tp->t_cflag, CLOCAL) &&
894 				    !ISSET(t->c_cflag, CLOCAL)) {
895 					CLR(tp->t_state, TS_ISOPEN);
896 					SET(tp->t_state, TS_WOPEN);
897 					ttwakeup(tp);
898 				}
899 				tp->t_cflag = t->c_cflag;
900 				tp->t_ispeed = t->c_ispeed;
901 				tp->t_ospeed = t->c_ospeed;
902 				if (t->c_ospeed == 0 && tp->t_session &&
903 				    tp->t_session->s_leader)
904 					prsignal(tp->t_session->s_leader,
905 					    SIGHUP);
906 			}
907 			ttsetwater(tp);
908 		}
909 		if (cmd != TIOCSETAF) {
910 			if (ISSET(t->c_lflag, ICANON) !=
911 			    ISSET(tp->t_lflag, ICANON)) {
912 				if (ISSET(t->c_lflag, ICANON)) {
913 					SET(tp->t_lflag, PENDIN);
914 					ttwakeup(tp);
915 				} else {
916 					struct clist tq;
917 
918 					catq(&tp->t_rawq, &tp->t_canq);
919 					tq = tp->t_rawq;
920 					tp->t_rawq = tp->t_canq;
921 					tp->t_canq = tq;
922 					CLR(tp->t_lflag, PENDIN);
923 				}
924 			}
925 		}
926 		tp->t_iflag = t->c_iflag;
927 		tp->t_oflag = t->c_oflag;
928 		/*
929 		 * Make the EXTPROC bit read only.
930 		 */
931 		if (ISSET(tp->t_lflag, EXTPROC))
932 			SET(t->c_lflag, EXTPROC);
933 		else
934 			CLR(t->c_lflag, EXTPROC);
935 		tp->t_lflag = t->c_lflag | ISSET(tp->t_lflag, PENDIN);
936 		memcpy(tp->t_cc, t->c_cc, sizeof(t->c_cc));
937 		splx(s);
938 		break;
939 	}
940 	case TIOCSETD: {		/* set line discipline */
941 		int t = *(int *)data;
942 		dev_t device = tp->t_dev;
943 
944 		if ((u_int)t >= nlinesw)
945 			return (ENXIO);
946 		if (t != tp->t_line) {
947 			s = spltty();
948 			(*linesw[tp->t_line].l_close)(tp, flag, p);
949 			error = (*linesw[t].l_open)(device, tp, p);
950 			if (error) {
951 				(*linesw[tp->t_line].l_open)(device, tp, p);
952 				splx(s);
953 				return (error);
954 			}
955 			tp->t_line = t;
956 			splx(s);
957 		}
958 		break;
959 	}
960 	case TIOCSTART:			/* start output, like ^Q */
961 		s = spltty();
962 		if (ISSET(tp->t_state, TS_TTSTOP) ||
963 		    ISSET(tp->t_lflag, FLUSHO)) {
964 			CLR(tp->t_lflag, FLUSHO);
965 			CLR(tp->t_state, TS_TTSTOP);
966 			ttstart(tp);
967 		}
968 		splx(s);
969 		break;
970 	case TIOCSTOP:			/* stop output, like ^S */
971 		s = spltty();
972 		if (!ISSET(tp->t_state, TS_TTSTOP)) {
973 			SET(tp->t_state, TS_TTSTOP);
974 			(*cdevsw[major(tp->t_dev)].d_stop)(tp, 0);
975 		}
976 		splx(s);
977 		break;
978 	case TIOCSCTTY:			/* become controlling tty */
979 		/* Session ctty vnode pointer set in vnode layer. */
980 		if (!SESS_LEADER(pr) ||
981 		    ((pr->ps_session->s_ttyvp || tp->t_session) &&
982 		     (tp->t_session != pr->ps_session)))
983 			return (EPERM);
984 		if (tp->t_session)
985 			SESSRELE(tp->t_session);
986 		SESSHOLD(pr->ps_session);
987 		tp->t_session = pr->ps_session;
988 		tp->t_pgrp = pr->ps_pgrp;
989 		pr->ps_session->s_ttyp = tp;
990 		atomic_setbits_int(&pr->ps_flags, PS_CONTROLT);
991 		break;
992 	case FIOSETOWN: {		/* set pgrp of tty */
993 		struct pgrp *pgrp;
994 		struct process *pr1;
995 		pid_t pgid = *(int *)data;
996 
997 		if (!isctty(pr, tp))
998 			return (ENOTTY);
999 		if (pgid < 0) {
1000 			pgrp = pgfind(-pgid);
1001 		} else {
1002 			pr1 = prfind(pgid);
1003 			if (pr1 == NULL)
1004 				return (ESRCH);
1005 			pgrp = pr1->ps_pgrp;
1006 		}
1007 		if (pgrp == NULL)
1008 			return (EINVAL);
1009 		else if (pgrp->pg_session != pr->ps_session)
1010 			return (EPERM);
1011 		tp->t_pgrp = pgrp;
1012 		break;
1013 	}
1014 	case TIOCSPGRP: {		/* set pgrp of tty */
1015 		struct pgrp *pgrp = pgfind(*(int *)data);
1016 
1017 		if (!isctty(pr, tp))
1018 			return (ENOTTY);
1019 		else if (pgrp == NULL)
1020 			return (EINVAL);
1021 		else if (pgrp->pg_session != pr->ps_session)
1022 			return (EPERM);
1023 		tp->t_pgrp = pgrp;
1024 		break;
1025 	}
1026 	case TIOCSTAT:			/* get load avg stats */
1027 		ttyinfo(tp);
1028 		break;
1029 	case TIOCSWINSZ:		/* set window size */
1030 		if (bcmp((caddr_t)&tp->t_winsize, data,
1031 		    sizeof (struct winsize))) {
1032 			tp->t_winsize = *(struct winsize *)data;
1033 			pgsignal(tp->t_pgrp, SIGWINCH, 1);
1034 		}
1035 		break;
1036 	case TIOCSTSTAMP: {
1037 		struct tstamps *ts = (struct tstamps *)data;
1038 
1039 		s = spltty();
1040 		CLR(tp->t_flags, TS_TSTAMPDCDSET);
1041 		CLR(tp->t_flags, TS_TSTAMPCTSSET);
1042 		CLR(tp->t_flags, TS_TSTAMPDCDCLR);
1043 		CLR(tp->t_flags, TS_TSTAMPCTSCLR);
1044 		if (ISSET(ts->ts_set, TIOCM_CAR))
1045 			SET(tp->t_flags, TS_TSTAMPDCDSET);
1046 		if (ISSET(ts->ts_set, TIOCM_CTS))
1047 			SET(tp->t_flags, TS_TSTAMPCTSSET);
1048 		if (ISSET(ts->ts_clr, TIOCM_CAR))
1049 			SET(tp->t_flags, TS_TSTAMPDCDCLR);
1050 		if (ISSET(ts->ts_clr, TIOCM_CTS))
1051 			SET(tp->t_flags, TS_TSTAMPCTSCLR);
1052 		splx(s);
1053 		break;
1054 	}
1055 	default:
1056 		return (-1);
1057 	}
1058 	return (0);
1059 }
1060 
1061 int
1062 ttpoll(dev_t device, int events, struct proc *p)
1063 {
1064 	struct tty *tp;
1065 	int revents, s;
1066 
1067 	tp = (*cdevsw[major(device)].d_tty)(device);
1068 
1069 	revents = 0;
1070 	s = spltty();
1071 	if (events & (POLLIN | POLLRDNORM)) {
1072 		if (ttnread(tp) > 0 || (!ISSET(tp->t_cflag, CLOCAL) &&
1073 		    !ISSET(tp->t_state, TS_CARR_ON)))
1074 			revents |= events & (POLLIN | POLLRDNORM);
1075 	}
1076 	/* NOTE: POLLHUP and POLLOUT/POLLWRNORM are mutually exclusive */
1077 	if (!ISSET(tp->t_cflag, CLOCAL) && !ISSET(tp->t_state, TS_CARR_ON)) {
1078 		revents |= POLLHUP;
1079 	} else if (events & (POLLOUT | POLLWRNORM)) {
1080 		if (tp->t_outq.c_cc <= tp->t_lowat)
1081 			revents |= events & (POLLOUT | POLLWRNORM);
1082 	}
1083 	if (revents == 0) {
1084 		if (events & (POLLIN | POLLRDNORM))
1085 			selrecord(p, &tp->t_rsel);
1086 		if (events & (POLLOUT | POLLWRNORM))
1087 			selrecord(p, &tp->t_wsel);
1088 	}
1089 	splx(s);
1090 	return (revents);
1091 }
1092 
1093 const struct filterops ttyread_filtops = {
1094 	.f_flags	= FILTEROP_ISFD,
1095 	.f_attach	= NULL,
1096 	.f_detach	= filt_ttyrdetach,
1097 	.f_event	= filt_ttyread,
1098 };
1099 
1100 const struct filterops ttywrite_filtops = {
1101 	.f_flags	= FILTEROP_ISFD,
1102 	.f_attach	= NULL,
1103 	.f_detach	= filt_ttywdetach,
1104 	.f_event	= filt_ttywrite,
1105 };
1106 
1107 int
1108 ttkqfilter(dev_t dev, struct knote *kn)
1109 {
1110 	struct tty *tp = (*cdevsw[major(dev)].d_tty)(dev);
1111 	struct klist *klist;
1112 	int s;
1113 
1114 	switch (kn->kn_filter) {
1115 	case EVFILT_READ:
1116 		klist = &tp->t_rsel.si_note;
1117 		kn->kn_fop = &ttyread_filtops;
1118 		break;
1119 	case EVFILT_WRITE:
1120 		klist = &tp->t_wsel.si_note;
1121 		kn->kn_fop = &ttywrite_filtops;
1122 		break;
1123 	default:
1124 		return (EINVAL);
1125 	}
1126 
1127 	kn->kn_hook = tp;
1128 
1129 	s = spltty();
1130 	klist_insert(klist, kn);
1131 	splx(s);
1132 
1133 	return (0);
1134 }
1135 
1136 void
1137 filt_ttyrdetach(struct knote *kn)
1138 {
1139 	struct tty *tp = kn->kn_hook;
1140 	int s;
1141 
1142 	s = spltty();
1143 	klist_remove(&tp->t_rsel.si_note, kn);
1144 	splx(s);
1145 }
1146 
1147 int
1148 filt_ttyread(struct knote *kn, long hint)
1149 {
1150 	struct tty *tp = kn->kn_hook;
1151 	int s;
1152 
1153 	s = spltty();
1154 	kn->kn_data = ttnread(tp);
1155 	splx(s);
1156 	if (!ISSET(tp->t_cflag, CLOCAL) && !ISSET(tp->t_state, TS_CARR_ON)) {
1157 		kn->kn_flags |= EV_EOF;
1158 		if (kn->kn_flags & __EV_POLL)
1159 			kn->kn_flags |= __EV_HUP;
1160 		return (1);
1161 	}
1162 	return (kn->kn_data > 0);
1163 }
1164 
1165 void
1166 filt_ttywdetach(struct knote *kn)
1167 {
1168 	struct tty *tp = kn->kn_hook;
1169 	int s;
1170 
1171 	s = spltty();
1172 	klist_remove(&tp->t_wsel.si_note, kn);
1173 	splx(s);
1174 }
1175 
1176 int
1177 filt_ttywrite(struct knote *kn, long hint)
1178 {
1179 	struct tty *tp = kn->kn_hook;
1180 	int canwrite, s;
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, or if this times out, flush it.
1209  */
1210 int
1211 ttywait_nsec(struct tty *tp, uint64_t nsecs)
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_nsec(tp, &tp->t_outq, TTOPRI | PCATCH,
1226 			    ttyout, nsecs);
1227 			if (error == EWOULDBLOCK)
1228 				ttyflush(tp, FWRITE);
1229 			if (error)
1230 				break;
1231 		} else
1232 			break;
1233 	}
1234 	splx(s);
1235 	return (error);
1236 }
1237 
1238 int
1239 ttywait(struct tty *tp)
1240 {
1241 	return (ttywait_nsec(tp, INFSLP));
1242 }
1243 
1244 /*
1245  * Flush if successfully wait.
1246  */
1247 int
1248 ttywflush(struct tty *tp)
1249 {
1250 	int error;
1251 
1252 	error = ttywait_nsec(tp, SEC_TO_NSEC(5));
1253 	if (error == 0 || error == EWOULDBLOCK)
1254 		ttyflush(tp, FREAD);
1255 	return (error);
1256 }
1257 
1258 /*
1259  * Flush tty read and/or write queues, notifying anyone waiting.
1260  */
1261 void
1262 ttyflush(struct tty *tp, int rw)
1263 {
1264 	int s;
1265 
1266 	s = spltty();
1267 	if (rw & FREAD) {
1268 		FLUSHQ(&tp->t_canq);
1269 		FLUSHQ(&tp->t_rawq);
1270 		tp->t_rocount = 0;
1271 		tp->t_rocol = 0;
1272 		CLR(tp->t_state, TS_LOCAL);
1273 		ttyunblock(tp);
1274 		ttwakeup(tp);
1275 	}
1276 	if (rw & FWRITE) {
1277 		CLR(tp->t_state, TS_TTSTOP);
1278 		(*cdevsw[major(tp->t_dev)].d_stop)(tp, rw);
1279 		FLUSHQ(&tp->t_outq);
1280 		wakeup((caddr_t)&tp->t_outq);
1281 		selwakeup(&tp->t_wsel);
1282 	}
1283 	splx(s);
1284 }
1285 
1286 /*
1287  * Copy in the default termios characters.
1288  */
1289 void
1290 ttychars(struct tty *tp)
1291 {
1292 
1293 	memcpy(tp->t_cc, ttydefchars, sizeof(ttydefchars));
1294 }
1295 
1296 /*
1297  * Send stop character on input overflow.
1298  */
1299 static void
1300 ttyblock(struct tty *tp)
1301 {
1302 	int total;
1303 
1304 	total = tp->t_rawq.c_cc + tp->t_canq.c_cc;
1305 	if (tp->t_rawq.c_cc > TTYHOG(tp)) {
1306 		ttyflush(tp, FREAD | FWRITE);
1307 		CLR(tp->t_state, TS_TBLOCK);
1308 	}
1309 	/*
1310 	 * Block further input iff: current input > threshold
1311 	 * AND input is available to user program.
1312 	 */
1313 	if ((total >= TTYHOG(tp) / 2 &&
1314 	     !ISSET(tp->t_state, TS_TBLOCK) &&
1315 	     !ISSET(tp->t_lflag, ICANON)) || tp->t_canq.c_cc > 0) {
1316 		if (ISSET(tp->t_iflag, IXOFF) &&
1317 		    tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
1318 		    putc(tp->t_cc[VSTOP], &tp->t_outq) == 0) {
1319 			SET(tp->t_state, TS_TBLOCK);
1320 			ttstart(tp);
1321 		}
1322 		/* Try to block remote output via hardware flow control. */
1323 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
1324 		    (*tp->t_hwiflow)(tp, 1) != 0)
1325 			SET(tp->t_state, TS_TBLOCK);
1326 	}
1327 }
1328 
1329 void
1330 ttrstrt(void *tp_arg)
1331 {
1332 	struct tty *tp;
1333 	int s;
1334 
1335 #ifdef DIAGNOSTIC
1336 	if (tp_arg == NULL)
1337 		panic("ttrstrt");
1338 #endif
1339 	tp = tp_arg;
1340 	s = spltty();
1341 
1342 	CLR(tp->t_state, TS_TIMEOUT);
1343 	ttstart(tp);
1344 
1345 	splx(s);
1346 }
1347 
1348 int
1349 ttstart(struct tty *tp)
1350 {
1351 
1352 	if (tp->t_oproc != NULL)	/* XXX: Kludge for pty. */
1353 		(*tp->t_oproc)(tp);
1354 	return (0);
1355 }
1356 
1357 /*
1358  * "close" a line discipline
1359  */
1360 int
1361 ttylclose(struct tty *tp, int flag, struct proc *p)
1362 {
1363 
1364 	if (flag & FNONBLOCK)
1365 		ttyflush(tp, FREAD | FWRITE);
1366 	else
1367 		ttywflush(tp);
1368 	return (0);
1369 }
1370 
1371 /*
1372  * Handle modem control transition on a tty.
1373  * Flag indicates new state of carrier.
1374  * Returns 0 if the line should be turned off, otherwise 1.
1375  */
1376 int
1377 ttymodem(struct tty *tp, int flag)
1378 {
1379 
1380 	if (!ISSET(tp->t_state, TS_WOPEN) && ISSET(tp->t_cflag, MDMBUF)) {
1381 		/*
1382 		 * MDMBUF: do flow control according to carrier flag
1383 		 */
1384 		if (flag) {
1385 			CLR(tp->t_state, TS_TTSTOP);
1386 			ttstart(tp);
1387 		} else if (!ISSET(tp->t_state, TS_TTSTOP)) {
1388 			SET(tp->t_state, TS_TTSTOP);
1389 			(*cdevsw[major(tp->t_dev)].d_stop)(tp, 0);
1390 		}
1391 	} else if (flag == 0) {
1392 		/*
1393 		 * Lost carrier.
1394 		 */
1395 		CLR(tp->t_state, TS_CARR_ON);
1396 		if (ISSET(tp->t_state, TS_ISOPEN) &&
1397 		    !ISSET(tp->t_cflag, CLOCAL)) {
1398 			if (tp->t_session && tp->t_session->s_leader)
1399 				prsignal(tp->t_session->s_leader, SIGHUP);
1400 			ttyflush(tp, FREAD | FWRITE);
1401 			return (0);
1402 		}
1403 	} else {
1404 		/*
1405 		 * Carrier now on.
1406 		 */
1407 		SET(tp->t_state, TS_CARR_ON);
1408 		ttwakeup(tp);
1409 	}
1410 	return (1);
1411 }
1412 
1413 /*
1414  * Default modem control routine (for other line disciplines).
1415  * Return argument flag, to turn off device on carrier drop.
1416  */
1417 int
1418 nullmodem(struct tty *tp, int flag)
1419 {
1420 
1421 	if (flag)
1422 		SET(tp->t_state, TS_CARR_ON);
1423 	else {
1424 		CLR(tp->t_state, TS_CARR_ON);
1425 		if (ISSET(tp->t_state, TS_ISOPEN) &&
1426 		    !ISSET(tp->t_cflag, CLOCAL)) {
1427 			if (tp->t_session && tp->t_session->s_leader)
1428 				prsignal(tp->t_session->s_leader, SIGHUP);
1429 			ttyflush(tp, FREAD | FWRITE);
1430 			return (0);
1431 		}
1432 	}
1433 	return (1);
1434 }
1435 
1436 /*
1437  * Reinput pending characters after state switch
1438  * call at spltty().
1439  */
1440 void
1441 ttypend(struct tty *tp)
1442 {
1443 	struct clist tq;
1444 	int c;
1445 
1446 	splassert(IPL_TTY);
1447 
1448 	CLR(tp->t_lflag, PENDIN);
1449 	SET(tp->t_state, TS_TYPEN);
1450 	tq = tp->t_rawq;
1451 	tp->t_rawq.c_cc = 0;
1452 	tp->t_rawq.c_cf = tp->t_rawq.c_cl = 0;
1453 	while ((c = getc(&tq)) >= 0)
1454 		ttyinput(c, tp);
1455 	CLR(tp->t_state, TS_TYPEN);
1456 }
1457 
1458 void ttvtimeout(void *);
1459 
1460 void
1461 ttvtimeout(void *arg)
1462 {
1463 	struct tty *tp = (struct tty *)arg;
1464 
1465 	wakeup(&tp->t_rawq);
1466 }
1467 
1468 /*
1469  * Process a read call on a tty device.
1470  */
1471 int
1472 ttread(struct tty *tp, struct uio *uio, int flag)
1473 {
1474 	struct timeout *stime = NULL;
1475 	struct proc *p = curproc;
1476 	struct process *pr = p->p_p;
1477 	int s, first, error = 0;
1478 	u_char *cc = tp->t_cc;
1479 	struct clist *qp;
1480 	int last_cc = 0;
1481 	long lflag;
1482 	int c;
1483 
1484 loop:	lflag = tp->t_lflag;
1485 	s = spltty();
1486 	/*
1487 	 * take pending input first
1488 	 */
1489 	if (ISSET(lflag, PENDIN))
1490 		ttypend(tp);
1491 	splx(s);
1492 
1493 	/*
1494 	 * Hang process if it's in the background.
1495 	 */
1496 	if (isbackground(pr, tp)) {
1497 		if ((pr->ps_sigacts->ps_sigignore & sigmask(SIGTTIN)) ||
1498 		   (p->p_sigmask & sigmask(SIGTTIN)) ||
1499 		    pr->ps_flags & PS_PPWAIT || pr->ps_pgrp->pg_jobc == 0) {
1500 			error = EIO;
1501 			goto out;
1502 		}
1503 		pgsignal(pr->ps_pgrp, SIGTTIN, 1);
1504 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, ttybg);
1505 		if (error)
1506 			goto out;
1507 		goto loop;
1508 	}
1509 
1510 	s = spltty();
1511 	if (!ISSET(lflag, ICANON)) {
1512 		int min = cc[VMIN];
1513 		int time = cc[VTIME] * 100;	/* tenths of a second (ms) */
1514 
1515 		qp = &tp->t_rawq;
1516 		/*
1517 		 * Check each of the four combinations.
1518 		 * (min > 0 && time == 0) is the normal read case.
1519 		 * It should be fairly efficient, so we check that and its
1520 		 * companion case (min == 0 && time == 0) first.
1521 		 */
1522 		if (time == 0) {
1523 			if (qp->c_cc < min)
1524 				goto sleep;
1525 			goto read;
1526 		}
1527 		if (min > 0) {
1528 			if (qp->c_cc <= 0)
1529 				goto sleep;
1530 			if (qp->c_cc >= min)
1531 				goto read;
1532 			if (stime == NULL) {
1533 alloc_timer:
1534 				stime = malloc(sizeof(*stime), M_TEMP, M_WAITOK);
1535 				timeout_set(stime, ttvtimeout, tp);
1536 				timeout_add_msec(stime, time);
1537 			} else if (qp->c_cc > last_cc) {
1538 				/* got a character, restart timer */
1539 				timeout_add_msec(stime, time);
1540 			}
1541 		} else {	/* min == 0 */
1542 			if (qp->c_cc > 0)
1543 				goto read;
1544 			if (stime == NULL) {
1545 				goto alloc_timer;
1546 			}
1547 		}
1548 		last_cc = qp->c_cc;
1549 		if (stime && !timeout_triggered(stime)) {
1550 			goto sleep;
1551 		}
1552 	} else if ((qp = &tp->t_canq)->c_cc <= 0) {
1553 		int carrier;
1554 
1555 sleep:
1556 		/*
1557 		 * If there is no input, sleep on rawq
1558 		 * awaiting hardware receipt and notification.
1559 		 * If we have data, we don't need to check for carrier.
1560 		 */
1561 		carrier = ISSET(tp->t_state, TS_CARR_ON) ||
1562 		    ISSET(tp->t_cflag, CLOCAL);
1563 		if (!carrier && ISSET(tp->t_state, TS_ISOPEN)) {
1564 			splx(s);
1565 			error = 0;
1566 			goto out;
1567 		}
1568 		if (flag & IO_NDELAY) {
1569 			splx(s);
1570 			error = EWOULDBLOCK;
1571 			goto out;
1572 		}
1573 		error = ttysleep(tp, &tp->t_rawq, TTIPRI | PCATCH,
1574 		    carrier ? ttyin : ttopen);
1575 		splx(s);
1576 		if (stime && timeout_triggered(stime))
1577 			error = EWOULDBLOCK;
1578 		if (cc[VMIN] == 0 && error == EWOULDBLOCK) {
1579 			error = 0;
1580 			goto out;
1581 		}
1582 		if (error && error != EWOULDBLOCK)
1583 			goto out;
1584 		error = 0;
1585 		goto loop;
1586 	}
1587 read:
1588 	splx(s);
1589 
1590 	/*
1591 	 * Input present, check for input mapping and processing.
1592 	 */
1593 	first = 1;
1594 	while ((c = getc(qp)) >= 0) {
1595 		/*
1596 		 * delayed suspend (^Y)
1597 		 */
1598 		if (CCEQ(cc[VDSUSP], c) &&
1599 		    ISSET(lflag, IEXTEN | ISIG) == (IEXTEN | ISIG)) {
1600 			pgsignal(tp->t_pgrp, SIGTSTP, 1);
1601 			if (first) {
1602 				error = ttysleep(tp, &lbolt, TTIPRI | PCATCH,
1603 				    ttybg);
1604 				if (error)
1605 					break;
1606 				goto loop;
1607 			}
1608 			break;
1609 		}
1610 		/*
1611 		 * Interpret EOF only in canonical mode.
1612 		 */
1613 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
1614 			break;
1615 		/*
1616 		 * Give user character.
1617 		 */
1618 		error = ureadc(c, uio);
1619 		if (error)
1620 			break;
1621 		if (uio->uio_resid == 0)
1622 			break;
1623 		/*
1624 		 * In canonical mode check for a "break character"
1625 		 * marking the end of a "line of input".
1626 		 */
1627 		if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
1628 			break;
1629 		first = 0;
1630 	}
1631 	/*
1632 	 * Look to unblock output now that (presumably)
1633 	 * the input queue has gone down.
1634 	 */
1635 	s = spltty();
1636 	if (tp->t_rawq.c_cc < TTYHOG(tp)/5)
1637 		ttyunblock(tp);
1638 	splx(s);
1639 
1640 out:
1641 	if (stime) {
1642 		timeout_del(stime);
1643 		free(stime, M_TEMP, sizeof(*stime));
1644 	}
1645 	return (error);
1646 }
1647 
1648 /* Call at spltty */
1649 void
1650 ttyunblock(struct tty *tp)
1651 {
1652 	u_char *cc = tp->t_cc;
1653 
1654 	splassert(IPL_TTY);
1655 
1656 	if (ISSET(tp->t_state, TS_TBLOCK)) {
1657 		if (ISSET(tp->t_iflag, IXOFF) &&
1658 		    cc[VSTART] != _POSIX_VDISABLE &&
1659 		    putc(cc[VSTART], &tp->t_outq) == 0) {
1660 			CLR(tp->t_state, TS_TBLOCK);
1661 			ttstart(tp);
1662 		}
1663 		/* Try to unblock remote output via hardware flow control. */
1664 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
1665 		    (*tp->t_hwiflow)(tp, 0) != 0)
1666 			CLR(tp->t_state, TS_TBLOCK);
1667 	}
1668 }
1669 
1670 /*
1671  * Check the output queue on tp for space for a kernel message (from uprintf
1672  * or tprintf).  Allow some space over the normal hiwater mark so we don't
1673  * lose messages due to normal flow control, but don't let the tty run amok.
1674  * Sleeps here are not interruptible, but we return prematurely if new signals
1675  * arrive.
1676  */
1677 int
1678 ttycheckoutq(struct tty *tp, int wait)
1679 {
1680 	int hiwat, s, oldsig;
1681 
1682 	hiwat = tp->t_hiwat;
1683 	s = spltty();
1684 	oldsig = wait ? SIGPENDING(curproc) : 0;
1685 	if (tp->t_outq.c_cc > hiwat + TTHIWATMINSPACE)
1686 		while (tp->t_outq.c_cc > hiwat) {
1687 			ttstart(tp);
1688 			if (wait == 0 || SIGPENDING(curproc) != oldsig) {
1689 				splx(s);
1690 				return (0);
1691 			}
1692 			SET(tp->t_state, TS_ASLEEP);
1693 			tsleep_nsec(&tp->t_outq, PZERO - 1, "ttckoutq",
1694 			    SEC_TO_NSEC(1));
1695 		}
1696 	splx(s);
1697 	return (1);
1698 }
1699 
1700 /*
1701  * Process a write call on a tty device.
1702  */
1703 int
1704 ttwrite(struct tty *tp, struct uio *uio, int flag)
1705 {
1706 	u_char *cp = NULL;
1707 	int cc, ce, obufcc = 0;
1708 	struct proc *p;
1709 	struct process *pr;
1710 	int hiwat, error, s;
1711 	size_t cnt;
1712 	u_char obuf[OBUFSIZ];
1713 
1714 	hiwat = tp->t_hiwat;
1715 	cnt = uio->uio_resid;
1716 	error = 0;
1717 	cc = 0;
1718 loop:
1719 	s = spltty();
1720 	if (!ISSET(tp->t_state, TS_CARR_ON) &&
1721 	    !ISSET(tp->t_cflag, CLOCAL)) {
1722 		if (ISSET(tp->t_state, TS_ISOPEN)) {
1723 			splx(s);
1724 			error = EIO;
1725 			goto done;
1726 		} else if (flag & IO_NDELAY) {
1727 			splx(s);
1728 			error = EWOULDBLOCK;
1729 			goto out;
1730 		} else {
1731 			/* Sleep awaiting carrier. */
1732 			error = ttysleep(tp,
1733 			    &tp->t_rawq, TTIPRI | PCATCH, ttopen);
1734 			splx(s);
1735 			if (error)
1736 				goto out;
1737 			goto loop;
1738 		}
1739 	}
1740 	splx(s);
1741 	/*
1742 	 * Hang the process if it's in the background.
1743 	 */
1744 	p = curproc;
1745 	pr = p->p_p;
1746 	if (isbackground(pr, tp) &&
1747 	    ISSET(tp->t_lflag, TOSTOP) && (pr->ps_flags & PS_PPWAIT) == 0 &&
1748 	    (pr->ps_sigacts->ps_sigignore & sigmask(SIGTTOU)) == 0 &&
1749 	    (p->p_sigmask & sigmask(SIGTTOU)) == 0) {
1750 		if (pr->ps_pgrp->pg_jobc == 0) {
1751 			error = EIO;
1752 			goto out;
1753 		}
1754 		pgsignal(pr->ps_pgrp, SIGTTOU, 1);
1755 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, ttybg);
1756 		if (error)
1757 			goto out;
1758 		goto loop;
1759 	}
1760 	/*
1761 	 * Process the user's data in at most OBUFSIZ chunks.  Perform any
1762 	 * output translation.  Keep track of high water mark, sleep on
1763 	 * overflow awaiting device aid in acquiring new space.
1764 	 */
1765 	while (uio->uio_resid > 0 || cc > 0) {
1766 		if (ISSET(tp->t_lflag, FLUSHO)) {
1767 			uio->uio_resid = 0;
1768 			goto done;
1769 		}
1770 		if (tp->t_outq.c_cc > hiwat)
1771 			goto ovhiwat;
1772 		/*
1773 		 * Grab a hunk of data from the user, unless we have some
1774 		 * leftover from last time.
1775 		 */
1776 		if (cc == 0) {
1777 			cc = MIN(uio->uio_resid, OBUFSIZ);
1778 			cp = obuf;
1779 			error = uiomove(cp, cc, uio);
1780 			if (error) {
1781 				cc = 0;
1782 				break;
1783 			}
1784 			if (cc > obufcc)
1785 				obufcc = cc;
1786 
1787 			/* duplicate /dev/console output into console buffer */
1788 			if (consbufp && cn_tab &&
1789 			    cn_tab->cn_dev == tp->t_dev && tp->t_gen == 0) {
1790 				int i;
1791 				for (i = 0; i < cc; i++) {
1792 					char c = cp[i];
1793 					if (c != '\0' && c != '\r' && c != 0177)
1794 						msgbuf_putchar(consbufp, c);
1795 				}
1796 			}
1797 		}
1798 		/*
1799 		 * If nothing fancy need be done, grab those characters we
1800 		 * can handle without any of ttyoutput's processing and
1801 		 * just transfer them to the output q.  For those chars
1802 		 * which require special processing (as indicated by the
1803 		 * bits in char_type), call ttyoutput.  After processing
1804 		 * a hunk of data, look for FLUSHO so ^O's will take effect
1805 		 * immediately.
1806 		 */
1807 		while (cc > 0) {
1808 			int i;
1809 			if (!ISSET(tp->t_oflag, OPOST))
1810 				ce = cc;
1811 			else {
1812 				ce = cc - scanc((u_int)cc, cp, char_type,
1813 				    CCLASSMASK);
1814 				/*
1815 				 * If ce is zero, then we're processing
1816 				 * a special character through ttyoutput.
1817 				 */
1818 				if (ce == 0) {
1819 					tp->t_rocount = 0;
1820 					if (ttyoutput(*cp, tp) >= 0) {
1821 						/* out of space */
1822 						goto ovhiwat;
1823 					}
1824 					cp++;
1825 					cc--;
1826 					if (ISSET(tp->t_lflag, FLUSHO) ||
1827 					    tp->t_outq.c_cc > hiwat)
1828 						goto ovhiwat;
1829 					continue;
1830 				}
1831 			}
1832 			/*
1833 			 * A bunch of normal characters have been found.
1834 			 * Transfer them en masse to the output queue and
1835 			 * continue processing at the top of the loop.
1836 			 * If there are any further characters in this
1837 			 * <= OBUFSIZ chunk, the first should be a character
1838 			 * requiring special handling by ttyoutput.
1839 			 */
1840 			tp->t_rocount = 0;
1841 			i = b_to_q(cp, ce, &tp->t_outq);
1842 			ce -= i;
1843 			tp->t_column += ce;
1844 			cp += ce, cc -= ce, tk_nout += ce;
1845 			tp->t_outcc += ce;
1846 			if (i > 0) {
1847 				/* out of space */
1848 				goto ovhiwat;
1849 			}
1850 			if (ISSET(tp->t_lflag, FLUSHO) ||
1851 			    tp->t_outq.c_cc > hiwat)
1852 				break;
1853 		}
1854 		ttstart(tp);
1855 	}
1856 out:
1857 	/*
1858 	 * If cc is nonzero, we leave the uio structure inconsistent, as the
1859 	 * offset and iov pointers have moved forward, but it doesn't matter
1860 	 * (the call will either return short or restart with a new uio).
1861 	 */
1862 	uio->uio_resid += cc;
1863 done:
1864 	if (obufcc)
1865 		explicit_bzero(obuf, obufcc);
1866 	return (error);
1867 
1868 ovhiwat:
1869 	ttstart(tp);
1870 	s = spltty();
1871 	/*
1872 	 * This can only occur if FLUSHO is set in t_lflag,
1873 	 * or if ttstart/oproc is synchronous (or very fast).
1874 	 */
1875 	if (tp->t_outq.c_cc <= hiwat) {
1876 		splx(s);
1877 		goto loop;
1878 	}
1879 	if (flag & IO_NDELAY) {
1880 		splx(s);
1881 		uio->uio_resid += cc;
1882 		if (obufcc)
1883 			explicit_bzero(obuf, obufcc);
1884 		return (uio->uio_resid == cnt ? EWOULDBLOCK : 0);
1885 	}
1886 	SET(tp->t_state, TS_ASLEEP);
1887 	error = ttysleep(tp, &tp->t_outq, TTOPRI | PCATCH, ttyout);
1888 	splx(s);
1889 	if (error)
1890 		goto out;
1891 	goto loop;
1892 }
1893 
1894 /*
1895  * Rubout one character from the rawq of tp
1896  * as cleanly as possible.
1897  */
1898 void
1899 ttyrub(int c, struct tty *tp)
1900 {
1901 	u_char *cp;
1902 	int savecol;
1903 	int tabc, s;
1904 
1905 	if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
1906 		return;
1907 	CLR(tp->t_lflag, FLUSHO);
1908 	if (ISSET(tp->t_lflag, ECHOE)) {
1909 		if (tp->t_rocount == 0) {
1910 			/*
1911 			 * Screwed by ttwrite; retype
1912 			 */
1913 			ttyretype(tp);
1914 			return;
1915 		}
1916 		if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
1917 			ttyrubo(tp, 2);
1918 		else {
1919 			CLR(c, ~TTY_CHARMASK);
1920 			switch (CCLASS(c)) {
1921 			case ORDINARY:
1922 				ttyrubo(tp, 1);
1923 				break;
1924 			case BACKSPACE:
1925 			case CONTROL:
1926 			case NEWLINE:
1927 			case RETURN:
1928 			case VTAB:
1929 				if (ISSET(tp->t_lflag, ECHOCTL))
1930 					ttyrubo(tp, 2);
1931 				break;
1932 			case TAB:
1933 				if (tp->t_rocount < tp->t_rawq.c_cc) {
1934 					ttyretype(tp);
1935 					return;
1936 				}
1937 				s = spltty();
1938 				savecol = tp->t_column;
1939 				SET(tp->t_state, TS_CNTTB);
1940 				SET(tp->t_lflag, FLUSHO);
1941 				tp->t_column = tp->t_rocol;
1942 				for (cp = firstc(&tp->t_rawq, &tabc); cp;
1943 				    cp = nextc(&tp->t_rawq, cp, &tabc))
1944 					ttyecho(tabc, tp);
1945 				CLR(tp->t_lflag, FLUSHO);
1946 				CLR(tp->t_state, TS_CNTTB);
1947 				splx(s);
1948 
1949 				/* savecol will now be length of the tab. */
1950 				savecol -= tp->t_column;
1951 				tp->t_column += savecol;
1952 				if (savecol > 8)
1953 					savecol = 8;	/* overflow screw */
1954 				while (--savecol >= 0)
1955 					(void)ttyoutput('\b', tp);
1956 				break;
1957 			default:			/* XXX */
1958 #define	PANICSTR	"ttyrub: would panic c = %d, val = %d\n"
1959 				(void)printf(PANICSTR, c, CCLASS(c));
1960 #ifdef notdef
1961 				panic(PANICSTR, c, CCLASS(c));
1962 #endif
1963 			}
1964 		}
1965 	} else if (ISSET(tp->t_lflag, ECHOPRT)) {
1966 		if (!ISSET(tp->t_state, TS_ERASE)) {
1967 			SET(tp->t_state, TS_ERASE);
1968 			(void)ttyoutput('\\', tp);
1969 		}
1970 		ttyecho(c, tp);
1971 	} else
1972 		ttyecho(tp->t_cc[VERASE], tp);
1973 	--tp->t_rocount;
1974 }
1975 
1976 /*
1977  * Back over cnt characters, erasing them.
1978  */
1979 static void
1980 ttyrubo(struct tty *tp, int cnt)
1981 {
1982 
1983 	while (cnt-- > 0) {
1984 		(void)ttyoutput('\b', tp);
1985 		(void)ttyoutput(' ', tp);
1986 		(void)ttyoutput('\b', tp);
1987 	}
1988 }
1989 
1990 /*
1991  * ttyretype --
1992  *	Reprint the rawq line.  Note, it is assumed that c_cc has already
1993  *	been checked.
1994  */
1995 void
1996 ttyretype(struct tty *tp)
1997 {
1998 	u_char *cp;
1999 	int s, c;
2000 
2001 	/* Echo the reprint character. */
2002 	if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
2003 		ttyecho(tp->t_cc[VREPRINT], tp);
2004 
2005 	(void)ttyoutput('\n', tp);
2006 
2007 	s = spltty();
2008 	for (cp = firstc(&tp->t_canq, &c); cp; cp = nextc(&tp->t_canq, cp, &c))
2009 		ttyecho(c, tp);
2010 	for (cp = firstc(&tp->t_rawq, &c); cp; cp = nextc(&tp->t_rawq, cp, &c))
2011 		ttyecho(c, tp);
2012 	CLR(tp->t_state, TS_ERASE);
2013 	splx(s);
2014 
2015 	tp->t_rocount = tp->t_rawq.c_cc;
2016 	tp->t_rocol = 0;
2017 }
2018 
2019 /*
2020  * Echo a typed character to the terminal.
2021  */
2022 static void
2023 ttyecho(int c, struct tty *tp)
2024 {
2025 
2026 	if (!ISSET(tp->t_state, TS_CNTTB))
2027 		CLR(tp->t_lflag, FLUSHO);
2028 	if ((!ISSET(tp->t_lflag, ECHO) &&
2029 	    (!ISSET(tp->t_lflag, ECHONL) || c != '\n')) ||
2030 	    ISSET(tp->t_lflag, EXTPROC))
2031 		return;
2032 	if (((ISSET(tp->t_lflag, ECHOCTL) &&
2033 	     (ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n')) ||
2034 	    ISSET(c, TTY_CHARMASK) == 0177)) {
2035 		(void)ttyoutput('^', tp);
2036 		CLR(c, ~TTY_CHARMASK);
2037 		if (c == 0177)
2038 			c = '?';
2039 		else
2040 			c += 'A' - 1;
2041 	}
2042 	(void)ttyoutput(c, tp);
2043 }
2044 
2045 /*
2046  * Wakeup any writers if necessary.
2047  */
2048 void
2049 ttwakeupwr(struct tty *tp)
2050 {
2051 
2052 	if (tp->t_outq.c_cc <= tp->t_lowat) {
2053 		if (ISSET(tp->t_state, TS_ASLEEP)) {
2054 			CLR(tp->t_state, TS_ASLEEP);
2055 			wakeup(&tp->t_outq);
2056 		}
2057 		selwakeup(&tp->t_wsel);
2058 	}
2059 }
2060 
2061 /*
2062  * Wake up any readers on a tty.
2063  */
2064 void
2065 ttwakeup(struct tty *tp)
2066 {
2067 
2068 	selwakeup(&tp->t_rsel);
2069 	if (ISSET(tp->t_state, TS_ASYNC))
2070 		pgsignal(tp->t_pgrp, SIGIO, 1);
2071 	wakeup((caddr_t)&tp->t_rawq);
2072 }
2073 
2074 /*
2075  * Look up a code for a specified speed in a conversion table;
2076  * used by drivers to map software speed values to hardware parameters.
2077  */
2078 int
2079 ttspeedtab(int speed, const struct speedtab *table)
2080 {
2081 
2082 	for ( ; table->sp_speed != -1; table++)
2083 		if (table->sp_speed == speed)
2084 			return (table->sp_code);
2085 	return (-1);
2086 }
2087 
2088 /*
2089  * Set tty hi and low water marks.
2090  *
2091  * Try to arrange the dynamics so there's about one second
2092  * from hi to low water.
2093  */
2094 void
2095 ttsetwater(struct tty *tp)
2096 {
2097 	int cps, x;
2098 
2099 #define CLAMP(x, h, l)	((x) > h ? h : ((x) < l) ? l : (x))
2100 
2101 	cps = tp->t_ospeed / 10;
2102 	tp->t_lowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
2103 	x += cps;
2104 	tp->t_hiwat = CLAMP(x, tp->t_outq.c_cn - TTHIWATMINSPACE, TTMINHIWAT);
2105 #undef	CLAMP
2106 }
2107 
2108 /*
2109  * Get the total estcpu for a process, summing across threads.
2110  * Returns true if at least one thread is runnable/running.
2111  */
2112 static int
2113 process_sum(struct process *pr, fixpt_t *estcpup)
2114 {
2115 	struct proc *p;
2116 	fixpt_t estcpu;
2117 	int ret;
2118 
2119 	ret = 0;
2120 	estcpu = 0;
2121 	TAILQ_FOREACH(p, &pr->ps_threads, p_thr_link) {
2122 		if (p->p_stat == SRUN || p->p_stat == SONPROC)
2123 			ret = 1;
2124 		estcpu += p->p_pctcpu;
2125 	}
2126 
2127 	*estcpup = estcpu;
2128 	return (ret);
2129 }
2130 
2131 /*
2132  * Report on state of foreground process group.
2133  */
2134 void
2135 ttyinfo(struct tty *tp)
2136 {
2137 	struct process *pr, *pickpr;
2138 	struct proc *p, *pick;
2139 	struct timespec utime, stime;
2140 	int tmp;
2141 
2142 	if (ttycheckoutq(tp,0) == 0)
2143 		return;
2144 
2145 	/* Print load average. */
2146 	tmp = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
2147 	ttyprintf(tp, "load: %d.%02d ", tmp / 100, tmp % 100);
2148 
2149 	if (tp->t_session == NULL)
2150 		ttyprintf(tp, "not a controlling terminal\n");
2151 	else if (tp->t_pgrp == NULL)
2152 		ttyprintf(tp, "no foreground process group\n");
2153 	else if ((pr = LIST_FIRST(&tp->t_pgrp->pg_members)) == NULL)
2154 empty:		ttyprintf(tp, "empty foreground process group\n");
2155 	else {
2156 		const char *state;
2157 		fixpt_t pctcpu, pctcpu2;
2158 		int run, run2;
2159 		int calc_pctcpu;
2160 		long rss;
2161 
2162 		/*
2163 		 * Pick the most active process:
2164 		 *  - prefer at least one running/runnable thread
2165 		 *  - prefer higher total pctcpu
2166 		 *  - prefer non-zombie
2167 		 * Otherwise take the most recently added to this process group
2168 		 */
2169 		pickpr = pr;
2170 		run = process_sum(pickpr, &pctcpu);
2171 		while ((pr = LIST_NEXT(pr, ps_pglist)) != NULL) {
2172 			run2 = process_sum(pr, &pctcpu2);
2173 			if (run) {
2174 				/*
2175 				 * pick is running; is p running w/same or
2176 				 * more cpu?
2177 				 */
2178 				if (run2 && pctcpu2 >= pctcpu)
2179 					goto update_pickpr;
2180 				continue;
2181 			}
2182 			/* pick isn't running; is p running *or* w/more cpu? */
2183 			if (run2 || pctcpu2 > pctcpu)
2184 				goto update_pickpr;
2185 
2186 			/* if p has less cpu or is zombie, then it's worse */
2187 			if (pctcpu2 < pctcpu || (pr->ps_flags & PS_ZOMBIE))
2188 				continue;
2189 update_pickpr:
2190 			pickpr = pr;
2191 			run = run2;
2192 			pctcpu = pctcpu2;
2193 		}
2194 
2195 		/* Calculate percentage cpu, resident set size. */
2196 		calc_pctcpu = (pctcpu * 10000 + FSCALE / 2) >> FSHIFT;
2197 		rss = (pickpr->ps_flags & (PS_EMBRYO | PS_ZOMBIE)) ? 0 :
2198 		    vm_resident_count(pickpr->ps_vmspace);
2199 
2200 		calctsru(&pickpr->ps_tu, &utime, &stime, NULL);
2201 
2202 		/* Round up and print user time. */
2203 		utime.tv_nsec += 5000000;
2204 		if (utime.tv_nsec >= 1000000000) {
2205 			utime.tv_sec += 1;
2206 			utime.tv_nsec -= 1000000000;
2207 		}
2208 
2209 		/* Round up and print system time. */
2210 		stime.tv_nsec += 5000000;
2211 		if (stime.tv_nsec >= 1000000000) {
2212 			stime.tv_sec += 1;
2213 			stime.tv_nsec -= 1000000000;
2214 		}
2215 
2216 		/*
2217 		 * Find the most active thread:
2218 		 *  - prefer runnable
2219 		 *  - prefer higher pctcpu
2220 		 *  - prefer living
2221 		 * Otherwise take the newest thread
2222 		 */
2223 		pick = p = TAILQ_FIRST(&pickpr->ps_threads);
2224 		if (p == NULL)
2225 			goto empty;
2226 		run = p->p_stat == SRUN || p->p_stat == SONPROC;
2227 		pctcpu = p->p_pctcpu;
2228 		while ((p = TAILQ_NEXT(p, p_thr_link)) != NULL) {
2229 			run2 = p->p_stat == SRUN || p->p_stat == SONPROC;
2230 			pctcpu2 = p->p_pctcpu;
2231 			if (run) {
2232 				/*
2233 				 * pick is running; is p running w/same or
2234 				 * more cpu?
2235 				 */
2236 				if (run2 && pctcpu2 >= pctcpu)
2237 					goto update_pick;
2238 				continue;
2239 			}
2240 			/* pick isn't running; is p running *or* w/more cpu? */
2241 			if (run2 || pctcpu2 > pctcpu)
2242 				goto update_pick;
2243 
2244 			/* if p has less cpu or is exiting, then it's worse */
2245 			if (pctcpu2 < pctcpu || p->p_flag & P_WEXIT)
2246 				continue;
2247 update_pick:
2248 			pick = p;
2249 			run = run2;
2250 			pctcpu = p->p_pctcpu;
2251 		}
2252 		state = pick->p_stat == SONPROC ? "running" :
2253 		        pick->p_stat == SRUN ? "runnable" :
2254 		        pick->p_wmesg ? pick->p_wmesg : "iowait";
2255 
2256 		ttyprintf(tp,
2257 		    " cmd: %s %d [%s] %lld.%02ldu %lld.%02lds %d%% %ldk\n",
2258 		    pickpr->ps_comm, pickpr->ps_pid, state,
2259 		    (long long)utime.tv_sec, utime.tv_nsec / 10000000,
2260 		    (long long)stime.tv_sec, stime.tv_nsec / 10000000,
2261 		    calc_pctcpu / 100, rss);
2262 	}
2263 	tp->t_rocount = 0;	/* so pending input will be retyped if BS */
2264 }
2265 
2266 /*
2267  * Output char to tty; console putchar style.
2268  */
2269 int
2270 tputchar(int c, struct tty *tp)
2271 {
2272 	int s;
2273 
2274 	s = spltty();
2275 	if (ISSET(tp->t_state, TS_ISOPEN) == 0 ||
2276 	    !(ISSET(tp->t_state, TS_CARR_ON) || ISSET(tp->t_cflag, CLOCAL))) {
2277 		splx(s);
2278 		return (-1);
2279 	}
2280 	if (c == '\n')
2281 		(void)ttyoutput('\r', tp);
2282 	(void)ttyoutput(c, tp);
2283 	ttstart(tp);
2284 	splx(s);
2285 	return (0);
2286 }
2287 
2288 /*
2289  * Sleep on chan, returning ERESTART if tty changed while we napped and
2290  * returning any errors (e.g. EINTR/ETIMEDOUT) reported by tsleep.  If
2291  * the tty is revoked, restarting a pending call will redo validation done
2292  * at the start of the call.
2293  */
2294 int
2295 ttysleep(struct tty *tp, void *chan, int pri, char *wmesg)
2296 {
2297 	return (ttysleep_nsec(tp, chan, pri, wmesg, INFSLP));
2298 }
2299 
2300 int
2301 ttysleep_nsec(struct tty *tp, void *chan, int pri, char *wmesg, uint64_t nsecs)
2302 {
2303 	int error;
2304 	short gen;
2305 
2306 	gen = tp->t_gen;
2307 	if ((error = tsleep_nsec(chan, pri, wmesg, nsecs)) != 0)
2308 		return (error);
2309 	return (tp->t_gen == gen ? 0 : ERESTART);
2310 }
2311 
2312 /*
2313  * Initialise the global tty list.
2314  */
2315 void
2316 tty_init(void)
2317 {
2318 
2319 	TAILQ_INIT(&ttylist);
2320 	tty_count = 0;
2321 }
2322 
2323 /*
2324  * Allocate a tty structure and its associated buffers, and attach it to the
2325  * tty list.
2326  */
2327 struct tty *
2328 ttymalloc(int baud)
2329 {
2330 	struct tty *tp;
2331 
2332 	tp = malloc(sizeof(struct tty), M_TTYS, M_WAITOK|M_ZERO);
2333 
2334 	if (baud == 0)
2335 		baud = 115200;
2336 
2337 	if (baud <= 9600)
2338 		tp->t_qlen = 1024;
2339 	else if (baud <= 115200)
2340 		tp->t_qlen = 4096;
2341 	else
2342 		tp->t_qlen = 8192;
2343 	clalloc(&tp->t_rawq, tp->t_qlen, 1);
2344 	clalloc(&tp->t_canq, tp->t_qlen, 1);
2345 	/* output queue doesn't need quoting */
2346 	clalloc(&tp->t_outq, tp->t_qlen, 0);
2347 
2348 	TAILQ_INSERT_TAIL(&ttylist, tp, tty_link);
2349 	++tty_count;
2350 	timeout_set(&tp->t_rstrt_to, ttrstrt, tp);
2351 
2352 	return(tp);
2353 }
2354 
2355 
2356 /*
2357  * Free a tty structure and its buffers, after removing it from the tty list.
2358  */
2359 void
2360 ttyfree(struct tty *tp)
2361 {
2362 	int s;
2363 
2364 	--tty_count;
2365 #ifdef DIAGNOSTIC
2366 	if (tty_count < 0)
2367 		panic("ttyfree: tty_count < 0");
2368 #endif
2369 	TAILQ_REMOVE(&ttylist, tp, tty_link);
2370 
2371 	s = spltty();
2372 	klist_invalidate(&tp->t_rsel.si_note);
2373 	klist_invalidate(&tp->t_wsel.si_note);
2374 	splx(s);
2375 
2376 	clfree(&tp->t_rawq);
2377 	clfree(&tp->t_canq);
2378 	clfree(&tp->t_outq);
2379 	free(tp, M_TTYS, sizeof(*tp));
2380 }
2381 
2382 void
2383 ttystats_init(struct itty **ttystats, size_t *ttystatssiz)
2384 {
2385 	struct itty *itp;
2386 	struct tty *tp;
2387 
2388 	*ttystatssiz = tty_count * sizeof(struct itty);
2389 	*ttystats = mallocarray(tty_count, sizeof(struct itty),
2390 	    M_SYSCTL, M_WAITOK|M_ZERO);
2391 	for (tp = TAILQ_FIRST(&ttylist), itp = *ttystats; tp;
2392 	    tp = TAILQ_NEXT(tp, tty_link), itp++) {
2393 		itp->t_dev = tp->t_dev;
2394 		itp->t_rawq_c_cc = tp->t_rawq.c_cc;
2395 		itp->t_canq_c_cc = tp->t_canq.c_cc;
2396 		itp->t_outq_c_cc = tp->t_outq.c_cc;
2397 		itp->t_hiwat = tp->t_hiwat;
2398 		itp->t_lowat = tp->t_lowat;
2399 		itp->t_column = tp->t_column;
2400 		itp->t_state = tp->t_state;
2401 		itp->t_session = tp->t_session;
2402 		if (tp->t_pgrp)
2403 			itp->t_pgrp_pg_id = tp->t_pgrp->pg_id;
2404 		else
2405 			itp->t_pgrp_pg_id = 0;
2406 		itp->t_line = tp->t_line;
2407 	}
2408 }
2409 
2410 /*
2411  * Return tty-related information.
2412  */
2413 int
2414 sysctl_tty(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
2415     size_t newlen)
2416 {
2417 	int err;
2418 
2419 	if (namelen != 1)
2420 		return (ENOTDIR);
2421 
2422 	switch (name[0]) {
2423 	case KERN_TTY_TKNIN:
2424 		return (sysctl_rdquad(oldp, oldlenp, newp, tk_nin));
2425 	case KERN_TTY_TKNOUT:
2426 		return (sysctl_rdquad(oldp, oldlenp, newp, tk_nout));
2427 	case KERN_TTY_TKRAWCC:
2428 		return (sysctl_rdquad(oldp, oldlenp, newp, tk_rawcc));
2429 	case KERN_TTY_TKCANCC:
2430 		return (sysctl_rdquad(oldp, oldlenp, newp, tk_cancc));
2431 	case KERN_TTY_INFO:
2432 	    {
2433 		struct itty *ttystats;
2434 		size_t ttystatssiz;
2435 
2436 		ttystats_init(&ttystats, &ttystatssiz);
2437 		err = sysctl_rdstruct(oldp, oldlenp, newp, ttystats,
2438 		    tty_count * sizeof(struct itty));
2439 		free(ttystats, M_SYSCTL, ttystatssiz);
2440 		return (err);
2441 	    }
2442 	default:
2443 #if NPTY > 0
2444 		return (sysctl_pty(name, namelen, oldp, oldlenp, newp, newlen));
2445 #else
2446 		return (EOPNOTSUPP);
2447 #endif
2448 	}
2449 	/* NOTREACHED */
2450 }
2451 
2452 void
2453 ttytstamp(struct tty *tp, int octs, int ncts, int odcd, int ndcd)
2454 {
2455 	int doit = 0;
2456 
2457 	if (ncts ^ octs)
2458 		doit |= ncts ? ISSET(tp->t_flags, TS_TSTAMPCTSSET) :
2459 		    ISSET(tp->t_flags, TS_TSTAMPCTSCLR);
2460 	if (ndcd ^ odcd)
2461 		doit |= ndcd ? ISSET(tp->t_flags, TS_TSTAMPDCDSET) :
2462 		    ISSET(tp->t_flags, TS_TSTAMPDCDCLR);
2463 
2464 	if (doit)
2465 		microtime(&tp->t_tv);
2466 }
2467