xref: /openbsd-src/sys/kern/tty.c (revision 1a8dbaac879b9f3335ad7fb25429ce63ac1d6bac)
1 /*	$OpenBSD: tty.c,v 1.164 2020/09/09 16:29:14 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 **, int *, 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 struct rwlock ttylist_lock = RWLOCK_INITIALIZER("ttylist");
174 
175 int64_t tk_cancc, tk_nin, tk_nout, tk_rawcc;
176 
177 /*
178  * Initial open of tty, or (re)entry to standard tty line discipline.
179  */
180 int
181 ttyopen(dev_t device, struct tty *tp, struct proc *p)
182 {
183 	int s;
184 
185 	s = spltty();
186 	tp->t_dev = device;
187 	if (!ISSET(tp->t_state, TS_ISOPEN)) {
188 		SET(tp->t_state, TS_ISOPEN);
189 		memset(&tp->t_winsize, 0, sizeof(tp->t_winsize));
190 		tp->t_column = 0;
191 	}
192 	CLR(tp->t_state, TS_WOPEN);
193 	splx(s);
194 	return (0);
195 }
196 
197 /*
198  * Handle close() on a tty line: flush and set to initial state,
199  * bumping generation number so that pending read/write calls
200  * can detect recycling of the tty.
201  */
202 int
203 ttyclose(struct tty *tp)
204 {
205 	if (constty == tp)
206 		constty = NULL;
207 
208 	ttyflush(tp, FREAD | FWRITE);
209 
210 	tp->t_gen++;
211 	tp->t_pgrp = NULL;
212 	if (tp->t_session)
213 		SESSRELE(tp->t_session);
214 	tp->t_session = NULL;
215 	tp->t_state = 0;
216 	return (0);
217 }
218 
219 #define	FLUSHQ(q) {							\
220 	if ((q)->c_cc)							\
221 		ndflush(q, (q)->c_cc);					\
222 }
223 
224 /* Is 'c' a line delimiter ("break" character)? */
225 #define	TTBREAKC(c, lflag)						\
226 	((c) == '\n' || (((c) == cc[VEOF] || (c) == cc[VEOL] ||		\
227 	((c) == cc[VEOL2] && (lflag & IEXTEN))) && (c) != _POSIX_VDISABLE))
228 
229 
230 /*
231  * Process input of a single character received on a tty.  Returns 0 normally,
232  * 1 if a costly operation was reached.
233  */
234 int
235 ttyinput(int c, struct tty *tp)
236 {
237 	int iflag, lflag;
238 	u_char *cc;
239 	int i, error, ret = 0;
240 	int s;
241 
242 	enqueue_randomness(tp->t_dev << 8 | c);
243 	/*
244 	 * If receiver is not enabled, drop it.
245 	 */
246 	if (!ISSET(tp->t_cflag, CREAD))
247 		return (0);
248 
249 	/*
250 	 * If input is pending take it first.
251 	 */
252 	lflag = tp->t_lflag;
253 	s = spltty();
254 	if (ISSET(lflag, PENDIN))
255 		ttypend(tp);
256 	splx(s);
257 	/*
258 	 * Gather stats.
259 	 */
260 	if (ISSET(lflag, ICANON)) {
261 		++tk_cancc;
262 		++tp->t_cancc;
263 	} else {
264 		++tk_rawcc;
265 		++tp->t_rawcc;
266 	}
267 	++tk_nin;
268 
269 	/* Handle exceptional conditions (break, parity, framing). */
270 	cc = tp->t_cc;
271 	iflag = tp->t_iflag;
272 	if ((error = (ISSET(c, TTY_ERRORMASK))) != 0) {
273 		CLR(c, TTY_ERRORMASK);
274 		if (ISSET(error, TTY_FE) && !c) {	/* Break. */
275 			if (ISSET(iflag, IGNBRK))
276 				return (0);
277 			ttyflush(tp, FREAD | FWRITE);
278 			if (ISSET(iflag, BRKINT)) {
279 			    pgsignal(tp->t_pgrp, SIGINT, 1);
280 			    goto endcase;
281 			}
282 			else if (ISSET(iflag, PARMRK))
283 				goto parmrk;
284 		} else if ((ISSET(error, TTY_PE) && ISSET(iflag, INPCK)) ||
285 		    ISSET(error, TTY_FE)) {
286 			if (ISSET(iflag, IGNPAR))
287 				goto endcase;
288 			else if (ISSET(iflag, PARMRK)) {
289 parmrk:				(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
290 				if (ISSET(iflag, ISTRIP) || c != 0377)
291 					(void)putc(0 | TTY_QUOTE, &tp->t_rawq);
292 				(void)putc(c | TTY_QUOTE, &tp->t_rawq);
293 				goto endcase;
294 			} else
295 				c = 0;
296 		}
297 	}
298 	if (c == 0377 && !ISSET(iflag, ISTRIP) && ISSET(iflag, PARMRK))
299 		goto parmrk;
300 
301 	/*
302 	 * In tandem mode, check high water mark.
303 	 */
304 	if (ISSET(iflag, IXOFF) || ISSET(tp->t_cflag, CHWFLOW))
305 		ttyblock(tp);
306 	if (!ISSET(tp->t_state, TS_TYPEN) && ISSET(iflag, ISTRIP))
307 		CLR(c, 0x80);
308 	if (!ISSET(lflag, EXTPROC)) {
309 		/*
310 		 * Check for literal nexting very first
311 		 */
312 		if (ISSET(tp->t_state, TS_LNCH)) {
313 			SET(c, TTY_QUOTE);
314 			CLR(tp->t_state, TS_LNCH);
315 		}
316 		/*
317 		 * Scan for special characters.  This code
318 		 * is really just a big case statement with
319 		 * non-constant cases.  The bottom of the
320 		 * case statement is labeled ``endcase'', so goto
321 		 * it after a case match, or similar.
322 		 */
323 
324 		/*
325 		 * Control chars which aren't controlled
326 		 * by ICANON, ISIG, or IXON.
327 		 */
328 		if (ISSET(lflag, IEXTEN)) {
329 			if (CCEQ(cc[VLNEXT], c)) {
330 				if (ISSET(lflag, ECHO)) {
331 					if (ISSET(lflag, ECHOE)) {
332 						(void)ttyoutput('^', tp);
333 						(void)ttyoutput('\b', tp);
334 					} else
335 						ttyecho(c, tp);
336 				}
337 				SET(tp->t_state, TS_LNCH);
338 				goto endcase;
339 			}
340 			if (CCEQ(cc[VDISCARD], c)) {
341 				if (ISSET(lflag, FLUSHO))
342 					CLR(tp->t_lflag, FLUSHO);
343 				else {
344 					ttyflush(tp, FWRITE);
345 					ttyecho(c, tp);
346 					if (tp->t_rawq.c_cc + tp->t_canq.c_cc)
347 						ret = ttyretype(tp);
348 					SET(tp->t_lflag, FLUSHO);
349 				}
350 				goto startoutput;
351 			}
352 		}
353 		/*
354 		 * Signals.
355 		 */
356 		if (ISSET(lflag, ISIG)) {
357 			if (CCEQ(cc[VINTR], c) || CCEQ(cc[VQUIT], c)) {
358 				if (!ISSET(lflag, NOFLSH))
359 					ttyflush(tp, FREAD | FWRITE);
360 				ttyecho(c, tp);
361 				pgsignal(tp->t_pgrp,
362 				    CCEQ(cc[VINTR], c) ? SIGINT : SIGQUIT, 1);
363 				goto endcase;
364 			}
365 			if (CCEQ(cc[VSUSP], c)) {
366 				if (!ISSET(lflag, NOFLSH))
367 					ttyflush(tp, FREAD);
368 				ttyecho(c, tp);
369 				pgsignal(tp->t_pgrp, SIGTSTP, 1);
370 				goto endcase;
371 			}
372 		}
373 		/*
374 		 * Handle start/stop characters.
375 		 */
376 		if (ISSET(iflag, IXON)) {
377 			if (CCEQ(cc[VSTOP], c)) {
378 				if (!ISSET(tp->t_state, TS_TTSTOP)) {
379 					SET(tp->t_state, TS_TTSTOP);
380 					(*cdevsw[major(tp->t_dev)].d_stop)(tp,
381 					   0);
382 					return (0);
383 				}
384 				if (!CCEQ(cc[VSTART], c))
385 					return (0);
386 				/*
387 				 * if VSTART == VSTOP then toggle
388 				 */
389 				goto endcase;
390 			}
391 			if (CCEQ(cc[VSTART], c))
392 				goto restartoutput;
393 		}
394 		/*
395 		 * IGNCR, ICRNL, & INLCR
396 		 */
397 		if (c == '\r') {
398 			if (ISSET(iflag, IGNCR))
399 				goto endcase;
400 			else if (ISSET(iflag, ICRNL))
401 				c = '\n';
402 		} else if (c == '\n' && ISSET(iflag, INLCR))
403 			c = '\r';
404 	}
405 	if (!ISSET(tp->t_lflag, EXTPROC) && ISSET(lflag, ICANON)) {
406 		/*
407 		 * From here on down canonical mode character
408 		 * processing takes place.
409 		 */
410 		/*
411 		 * upper case or specials with IUCLC and XCASE
412 		 */
413 		if (ISSET(lflag, XCASE) && ISSET(iflag, IUCLC)) {
414 			if (ISSET(tp->t_state, TS_BKSL)) {
415 				CLR(tp->t_state, TS_BKSL);
416 				switch (c) {
417 				case '\'':
418 					c = '`';
419 					break;
420 				case '!':
421 					c = '|';
422 					break;
423 				case '^':
424 					c = '~';
425 					break;
426 				case '(':
427 					c = '{';
428 					break;
429 				case ')':
430 					c = '}';
431 					break;
432 				}
433 			}
434 			else if (c == '\\') {
435 				SET(tp->t_state, TS_BKSL);
436 				goto endcase;
437 			}
438 			else if (isupper(c))
439 				c = tolower(c);
440 		}
441 		else if (ISSET(iflag, IUCLC) && isupper(c))
442 			c = tolower(c);
443 		/*
444 		 * erase (^H / ^?)
445 		 */
446 		if (CCEQ(cc[VERASE], c)) {
447 			if (tp->t_rawq.c_cc)
448 				ret = ttyrub(unputc(&tp->t_rawq), tp);
449 			goto endcase;
450 		}
451 		/*
452 		 * kill (^U)
453 		 */
454 		if (CCEQ(cc[VKILL], c)) {
455 			if (ISSET(lflag, ECHOKE) &&
456 			    tp->t_rawq.c_cc == tp->t_rocount &&
457 			    !ISSET(lflag, ECHOPRT)) {
458 				while (tp->t_rawq.c_cc)
459 					if (ttyrub(unputc(&tp->t_rawq), tp))
460 						ret = 1;
461 			} else {
462 				ttyecho(c, tp);
463 				if (ISSET(lflag, ECHOK) ||
464 				    ISSET(lflag, ECHOKE))
465 					ttyecho('\n', tp);
466 				FLUSHQ(&tp->t_rawq);
467 				tp->t_rocount = 0;
468 			}
469 			CLR(tp->t_state, TS_LOCAL);
470 			goto endcase;
471 		}
472 		/*
473 		 * word erase (^W)
474 		 */
475 		if (CCEQ(cc[VWERASE], c) && ISSET(lflag, IEXTEN)) {
476 			int alt = ISSET(lflag, ALTWERASE);
477 			int ctype;
478 
479 			/*
480 			 * erase whitespace
481 			 */
482 			while ((c = unputc(&tp->t_rawq)) == ' ' || c == '\t')
483 				if (ttyrub(c, tp))
484 					ret = 1;
485 			if (c == -1)
486 				goto endcase;
487 			/*
488 			 * erase last char of word and remember the
489 			 * next chars type (for ALTWERASE)
490 			 */
491 			if (ttyrub(c, tp))
492 				ret = 1;
493 			c = unputc(&tp->t_rawq);
494 			if (c == -1)
495 				goto endcase;
496 			if (c == ' ' || c == '\t') {
497 				(void)putc(c, &tp->t_rawq);
498 				goto endcase;
499 			}
500 			ctype = ISALPHA(c);
501 			/*
502 			 * erase rest of word
503 			 */
504 			do {
505 				if (ttyrub(c, tp))
506 					ret = 1;
507 				c = unputc(&tp->t_rawq);
508 				if (c == -1)
509 					goto endcase;
510 			} while (c != ' ' && c != '\t' &&
511 			    (alt == 0 || ISALPHA(c) == ctype));
512 			(void)putc(c, &tp->t_rawq);
513 			goto endcase;
514 		}
515 		/*
516 		 * reprint line (^R)
517 		 */
518 		if (CCEQ(cc[VREPRINT], c) && ISSET(lflag, IEXTEN)) {
519 			ret = ttyretype(tp);
520 			goto endcase;
521 		}
522 		/*
523 		 * ^T - kernel info and generate SIGINFO
524 		 */
525 		if (CCEQ(cc[VSTATUS], c) && ISSET(lflag, IEXTEN)) {
526 			if (ISSET(lflag, ISIG))
527 				pgsignal(tp->t_pgrp, SIGINFO, 1);
528 			if (!ISSET(lflag, NOKERNINFO))
529 				ttyinfo(tp);
530 			goto endcase;
531 		}
532 	}
533 	/*
534 	 * Check for input buffer overflow
535 	 */
536 	if (tp->t_rawq.c_cc + tp->t_canq.c_cc >= TTYHOG(tp)) {
537 		if (ISSET(iflag, IMAXBEL)) {
538 			if (tp->t_outq.c_cc < tp->t_hiwat)
539 				(void)ttyoutput(CTRL('g'), tp);
540 		} else
541 			ttyflush(tp, FREAD | FWRITE);
542 		goto endcase;
543 	}
544 	/*
545 	 * Put data char in q for user and
546 	 * wakeup on seeing a line delimiter.
547 	 */
548 	if (putc(c, &tp->t_rawq) >= 0) {
549 		if (!ISSET(lflag, ICANON)) {
550 			ttwakeup(tp);
551 			ttyecho(c, tp);
552 			goto endcase;
553 		}
554 		if (TTBREAKC(c, lflag)) {
555 			tp->t_rocount = 0;
556 			catq(&tp->t_rawq, &tp->t_canq);
557 			ttwakeup(tp);
558 		} else if (tp->t_rocount++ == 0)
559 			tp->t_rocol = tp->t_column;
560 		if (ISSET(tp->t_state, TS_ERASE)) {
561 			/*
562 			 * end of prterase \.../
563 			 */
564 			CLR(tp->t_state, TS_ERASE);
565 			(void)ttyoutput('/', tp);
566 		}
567 		i = tp->t_column;
568 		ttyecho(c, tp);
569 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ECHO)) {
570 			/*
571 			 * Place the cursor over the '^' of the ^D.
572 			 */
573 			i = min(2, tp->t_column - i);
574 			while (i > 0) {
575 				(void)ttyoutput('\b', tp);
576 				i--;
577 			}
578 		}
579 	}
580 endcase:
581 	/*
582 	 * IXANY means allow any character to restart output.
583 	 */
584 	if (ISSET(tp->t_state, TS_TTSTOP) &&
585 	    !ISSET(iflag, IXANY) && cc[VSTART] != cc[VSTOP])
586 		return (ret);
587 restartoutput:
588 	CLR(tp->t_lflag, FLUSHO);
589 	CLR(tp->t_state, TS_TTSTOP);
590 startoutput:
591 	ttstart(tp);
592 	return (ret);
593 }
594 
595 /*
596  * Output a single character on a tty, doing output processing
597  * as needed (expanding tabs, newline processing, etc.).
598  * Returns < 0 if succeeds, otherwise returns char to resend.
599  * Must be recursive.
600  */
601 int
602 ttyoutput(int c, struct tty *tp)
603 {
604 	long oflag;
605 	int col, notout, s, c2;
606 
607 	oflag = tp->t_oflag;
608 	if (!ISSET(oflag, OPOST)) {
609 		tk_nout++;
610 		tp->t_outcc++;
611 		if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
612 			return (c);
613 		return (-1);
614 	}
615 	/*
616 	 * Do tab expansion if OXTABS is set.  Special case if we external
617 	 * processing, we don't do the tab expansion because we'll probably
618 	 * get it wrong.  If tab expansion needs to be done, let it happen
619 	 * externally.
620 	 */
621 	CLR(c, ~TTY_CHARMASK);
622 	if (c == '\t' &&
623 	    ISSET(oflag, OXTABS) && !ISSET(tp->t_lflag, EXTPROC)) {
624 		c = 8 - (tp->t_column & 7);
625 		if (ISSET(tp->t_lflag, FLUSHO)) {
626 			notout = 0;
627 		} else {
628 			s = spltty();		/* Don't interrupt tabs. */
629 			notout = b_to_q("        ", c, &tp->t_outq);
630 			c -= notout;
631 			tk_nout += c;
632 			tp->t_outcc += c;
633 			splx(s);
634 		}
635 		tp->t_column += c;
636 		return (notout ? '\t' : -1);
637 	}
638 	if (c == CEOT && ISSET(oflag, ONOEOT))
639 		return (-1);
640 
641 	/*
642 	 * Newline translation: if ONLCR is set,
643 	 * translate newline into "\r\n".  If OCRNL
644 	 * is set, translate '\r' into '\n'.
645 	 */
646 	if (c == '\n' && ISSET(tp->t_oflag, ONLCR)) {
647 		tk_nout++;
648 		tp->t_outcc++;
649 		if (!ISSET(tp->t_lflag, FLUSHO) && putc('\r', &tp->t_outq))
650 			return (c);
651 		tp->t_column = 0;
652 	}
653 	else if (c == '\r' && ISSET(tp->t_oflag, OCRNL))
654 		c = '\n';
655 
656 	if (ISSET(tp->t_oflag, OLCUC) && islower(c))
657 		c = toupper(c);
658 	else if (ISSET(tp->t_oflag, OLCUC) && ISSET(tp->t_lflag, XCASE)) {
659 		c2 = c;
660 		switch (c) {
661 		case '`':
662 			c2 = '\'';
663 			break;
664 		case '|':
665 			c2 = '!';
666 			break;
667 		case '~':
668 			c2 = '^';
669 			break;
670 		case '{':
671 			c2 = '(';
672 			break;
673 		case '}':
674 			c2 = ')';
675 			break;
676 		}
677 		if (c == '\\' || isupper(c) || c != c2) {
678 			tk_nout++;
679 			tp->t_outcc++;
680 			if (putc('\\', &tp->t_outq))
681 				return (c);
682 			c = c2;
683 		}
684 	}
685 	if (ISSET(tp->t_oflag, ONOCR) && c == '\r' && tp->t_column == 0)
686 		return (-1);
687 
688 	tk_nout++;
689 	tp->t_outcc++;
690 	if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
691 		return (c);
692 
693 	col = tp->t_column;
694 	switch (CCLASS(c)) {
695 	case BACKSPACE:
696 		if (col > 0)
697 			--col;
698 		break;
699 	case CONTROL:
700 		break;
701 	case NEWLINE:
702 		if (ISSET(tp->t_oflag, ONLRET) || ISSET(tp->t_oflag, OCRNL))
703 			col = 0;
704 		break;
705 	case RETURN:
706 		col = 0;
707 		break;
708 	case ORDINARY:
709 		++col;
710 		break;
711 	case TAB:
712 		col = (col + 8) & ~7;
713 		break;
714 	}
715 	tp->t_column = col;
716 	return (-1);
717 }
718 
719 /*
720  * Ioctls for all tty devices.  Called after line-discipline specific ioctl
721  * has been called to do discipline-specific functions and/or reject any
722  * of these ioctl commands.
723  */
724 int
725 ttioctl(struct tty *tp, u_long cmd, caddr_t data, int flag, struct proc *p)
726 {
727 	extern int nlinesw;
728 	struct process *pr = p->p_p;
729 	int s, error;
730 
731 	/* If the ioctl involves modification, hang if in the background. */
732 	switch (cmd) {
733 	case  FIOSETOWN:
734 	case  TIOCFLUSH:
735 	case  TIOCDRAIN:
736 	case  TIOCSBRK:
737 	case  TIOCCBRK:
738 	case  TIOCSETA:
739 	case  TIOCSETD:
740 	case  TIOCSETAF:
741 	case  TIOCSETAW:
742 	case  TIOCSPGRP:
743 	case  TIOCSTAT:
744 	case  TIOCSWINSZ:
745 		while (isbackground(pr, tp) &&
746 		    (pr->ps_flags & PS_PPWAIT) == 0 &&
747 		    !sigismasked(p, SIGTTOU)) {
748 			if (pr->ps_pgrp->pg_jobc == 0)
749 				return (EIO);
750 			pgsignal(pr->ps_pgrp, SIGTTOU, 1);
751 			error = ttysleep(tp, &lbolt, TTOPRI | PCATCH,
752 			    ttybg);
753 			if (error)
754 				return (error);
755 		}
756 		break;
757 	}
758 
759 	switch (cmd) {			/* Process the ioctl. */
760 	case FIOASYNC:			/* set/clear async i/o */
761 		s = spltty();
762 		if (*(int *)data)
763 			SET(tp->t_state, TS_ASYNC);
764 		else
765 			CLR(tp->t_state, TS_ASYNC);
766 		splx(s);
767 		break;
768 	case FIONBIO:			/* set/clear non-blocking i/o */
769 		break;			/* XXX: delete. */
770 	case FIONREAD:			/* get # bytes to read */
771 		s = spltty();
772 		*(int *)data = ttnread(tp);
773 		splx(s);
774 		break;
775 	case TIOCEXCL:			/* set exclusive use of tty */
776 		s = spltty();
777 		SET(tp->t_state, TS_XCLUDE);
778 		splx(s);
779 		break;
780 	case TIOCFLUSH: {		/* flush buffers */
781 		int flags = *(int *)data;
782 
783 		if (flags == 0)
784 			flags = FREAD | FWRITE;
785 		else
786 			flags &= FREAD | FWRITE;
787 		ttyflush(tp, flags);
788 		break;
789 	}
790 	case TIOCCONS: {		/* become virtual console */
791 		if (*(int *)data) {
792 			struct nameidata nid;
793 
794 			if (constty != NULL && constty != tp &&
795 			    ISSET(constty->t_state, TS_CARR_ON | TS_ISOPEN) ==
796 			    (TS_CARR_ON | TS_ISOPEN))
797 				return (EBUSY);
798 
799 			/* ensure user can open the real console */
800 			NDINIT(&nid, LOOKUP, FOLLOW, UIO_SYSSPACE, "/dev/console", p);
801 			nid.ni_pledge = PLEDGE_RPATH | PLEDGE_WPATH;
802 			nid.ni_unveil = UNVEIL_READ | UNVEIL_WRITE;
803 			error = namei(&nid);
804 			if (error)
805 				return (error);
806 			vn_lock(nid.ni_vp, LK_EXCLUSIVE | LK_RETRY);
807 			error = VOP_ACCESS(nid.ni_vp, VREAD, p->p_ucred, p);
808 			VOP_UNLOCK(nid.ni_vp);
809 			vrele(nid.ni_vp);
810 			if (error)
811 				return (error);
812 
813 			constty = tp;
814 		} else if (tp == constty)
815 			constty = NULL;
816 		break;
817 	}
818 	case TIOCDRAIN:			/* wait till output drained */
819 		if ((error = ttywait(tp)) != 0)
820 			return (error);
821 		break;
822 	case TIOCGETA: {		/* get termios struct */
823 		struct termios *t = (struct termios *)data;
824 
825 		memcpy(t, &tp->t_termios, sizeof(struct termios));
826 		break;
827 	}
828 	case TIOCGETD:			/* get line discipline */
829 		*(int *)data = tp->t_line;
830 		break;
831 	case TIOCGWINSZ:		/* get window size */
832 		*(struct winsize *)data = tp->t_winsize;
833 		break;
834 	case TIOCGTSTAMP:
835 		s = spltty();
836 		*(struct timeval *)data = tp->t_tv;
837 		splx(s);
838 		break;
839 	case FIOGETOWN:			/* get pgrp of tty */
840 		if (!isctty(pr, tp) && suser(p))
841 			return (ENOTTY);
842 		*(int *)data = tp->t_pgrp ? -tp->t_pgrp->pg_id : 0;
843 		break;
844 	case TIOCGPGRP:			/* get pgrp of tty */
845 		if (!isctty(pr, tp) && suser(p))
846 			return (ENOTTY);
847 		*(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
848 		break;
849 	case TIOCGSID:			/* get sid of tty */
850 		if (!isctty(pr, tp))
851 			return (ENOTTY);
852 		*(int *)data = tp->t_session->s_leader->ps_pid;
853 		break;
854 #ifdef TIOCHPCL
855 	case TIOCHPCL:			/* hang up on last close */
856 		s = spltty();
857 		SET(tp->t_cflag, HUPCL);
858 		splx(s);
859 		break;
860 #endif
861 	case TIOCNXCL:			/* reset exclusive use of tty */
862 		s = spltty();
863 		CLR(tp->t_state, TS_XCLUDE);
864 		splx(s);
865 		break;
866 	case TIOCOUTQ:			/* output queue size */
867 		*(int *)data = tp->t_outq.c_cc;
868 		break;
869 	case TIOCSETA:			/* set termios struct */
870 	case TIOCSETAW:			/* drain output, set */
871 	case TIOCSETAF: {		/* drn out, fls in, set */
872 		struct termios *t = (struct termios *)data;
873 
874 		s = spltty();
875 		if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
876 			if ((error = ttywait(tp)) != 0) {
877 				splx(s);
878 				return (error);
879 			}
880 			if (cmd == TIOCSETAF)
881 				ttyflush(tp, FREAD);
882 		}
883 		if (!ISSET(t->c_cflag, CIGNORE)) {
884 			/*
885 			 * Some minor validation is necessary.
886 			 */
887 			if (t->c_ispeed < 0 || t->c_ospeed < 0) {
888 				splx(s);
889 				return (EINVAL);
890 			}
891 			/*
892 			 * Set device hardware.
893 			 */
894 			if (tp->t_param && (error = (*tp->t_param)(tp, t))) {
895 				splx(s);
896 				return (error);
897 			} else {
898 				if (!ISSET(tp->t_state, TS_CARR_ON) &&
899 				    ISSET(tp->t_cflag, CLOCAL) &&
900 				    !ISSET(t->c_cflag, CLOCAL)) {
901 					CLR(tp->t_state, TS_ISOPEN);
902 					SET(tp->t_state, TS_WOPEN);
903 					ttwakeup(tp);
904 				}
905 				tp->t_cflag = t->c_cflag;
906 				tp->t_ispeed = t->c_ispeed;
907 				tp->t_ospeed = t->c_ospeed;
908 				if (t->c_ospeed == 0 && tp->t_session &&
909 				    tp->t_session->s_leader)
910 					prsignal(tp->t_session->s_leader,
911 					    SIGHUP);
912 			}
913 			ttsetwater(tp);
914 		}
915 		if (cmd != TIOCSETAF) {
916 			if (ISSET(t->c_lflag, ICANON) !=
917 			    ISSET(tp->t_lflag, ICANON)) {
918 				if (ISSET(t->c_lflag, ICANON)) {
919 					SET(tp->t_lflag, PENDIN);
920 					ttwakeup(tp);
921 				} else {
922 					struct clist tq;
923 
924 					catq(&tp->t_rawq, &tp->t_canq);
925 					tq = tp->t_rawq;
926 					tp->t_rawq = tp->t_canq;
927 					tp->t_canq = tq;
928 					CLR(tp->t_lflag, PENDIN);
929 				}
930 			}
931 		}
932 		tp->t_iflag = t->c_iflag;
933 		tp->t_oflag = t->c_oflag;
934 		/*
935 		 * Make the EXTPROC bit read only.
936 		 */
937 		if (ISSET(tp->t_lflag, EXTPROC))
938 			SET(t->c_lflag, EXTPROC);
939 		else
940 			CLR(t->c_lflag, EXTPROC);
941 		tp->t_lflag = t->c_lflag | ISSET(tp->t_lflag, PENDIN);
942 		memcpy(tp->t_cc, t->c_cc, sizeof(t->c_cc));
943 		splx(s);
944 		break;
945 	}
946 	case TIOCSETD: {		/* set line discipline */
947 		int t = *(int *)data;
948 		dev_t device = tp->t_dev;
949 
950 		if ((u_int)t >= nlinesw)
951 			return (ENXIO);
952 		if (t != tp->t_line) {
953 			s = spltty();
954 			(*linesw[tp->t_line].l_close)(tp, flag, p);
955 			error = (*linesw[t].l_open)(device, tp, p);
956 			if (error) {
957 				(*linesw[tp->t_line].l_open)(device, tp, p);
958 				splx(s);
959 				return (error);
960 			}
961 			tp->t_line = t;
962 			splx(s);
963 		}
964 		break;
965 	}
966 	case TIOCSTART:			/* start output, like ^Q */
967 		s = spltty();
968 		if (ISSET(tp->t_state, TS_TTSTOP) ||
969 		    ISSET(tp->t_lflag, FLUSHO)) {
970 			CLR(tp->t_lflag, FLUSHO);
971 			CLR(tp->t_state, TS_TTSTOP);
972 			ttstart(tp);
973 		}
974 		splx(s);
975 		break;
976 	case TIOCSTOP:			/* stop output, like ^S */
977 		s = spltty();
978 		if (!ISSET(tp->t_state, TS_TTSTOP)) {
979 			SET(tp->t_state, TS_TTSTOP);
980 			(*cdevsw[major(tp->t_dev)].d_stop)(tp, 0);
981 		}
982 		splx(s);
983 		break;
984 	case TIOCSCTTY:			/* become controlling tty */
985 		/* Session ctty vnode pointer set in vnode layer. */
986 		if (!SESS_LEADER(pr) ||
987 		    ((pr->ps_session->s_ttyvp || tp->t_session) &&
988 		     (tp->t_session != pr->ps_session)))
989 			return (EPERM);
990 		if (tp->t_session)
991 			SESSRELE(tp->t_session);
992 		SESSHOLD(pr->ps_session);
993 		tp->t_session = pr->ps_session;
994 		tp->t_pgrp = pr->ps_pgrp;
995 		pr->ps_session->s_ttyp = tp;
996 		atomic_setbits_int(&pr->ps_flags, PS_CONTROLT);
997 		break;
998 	case FIOSETOWN: {		/* set pgrp of tty */
999 		struct pgrp *pgrp;
1000 		struct process *pr1;
1001 		pid_t pgid = *(int *)data;
1002 
1003 		if (!isctty(pr, tp))
1004 			return (ENOTTY);
1005 		if (pgid < 0) {
1006 			pgrp = pgfind(-pgid);
1007 		} else {
1008 			pr1 = prfind(pgid);
1009 			if (pr1 == NULL)
1010 				return (ESRCH);
1011 			pgrp = pr1->ps_pgrp;
1012 		}
1013 		if (pgrp == NULL)
1014 			return (EINVAL);
1015 		else if (pgrp->pg_session != pr->ps_session)
1016 			return (EPERM);
1017 		tp->t_pgrp = pgrp;
1018 		break;
1019 	}
1020 	case TIOCSPGRP: {		/* set pgrp of tty */
1021 		struct pgrp *pgrp = pgfind(*(int *)data);
1022 
1023 		if (!isctty(pr, tp))
1024 			return (ENOTTY);
1025 		else if (pgrp == NULL)
1026 			return (EINVAL);
1027 		else if (pgrp->pg_session != pr->ps_session)
1028 			return (EPERM);
1029 		tp->t_pgrp = pgrp;
1030 		break;
1031 	}
1032 	case TIOCSTAT:			/* get load avg stats */
1033 		ttyinfo(tp);
1034 		break;
1035 	case TIOCSWINSZ:		/* set window size */
1036 		if (bcmp((caddr_t)&tp->t_winsize, data,
1037 		    sizeof (struct winsize))) {
1038 			tp->t_winsize = *(struct winsize *)data;
1039 			pgsignal(tp->t_pgrp, SIGWINCH, 1);
1040 		}
1041 		break;
1042 	case TIOCSTSTAMP: {
1043 		struct tstamps *ts = (struct tstamps *)data;
1044 
1045 		s = spltty();
1046 		CLR(tp->t_flags, TS_TSTAMPDCDSET);
1047 		CLR(tp->t_flags, TS_TSTAMPCTSSET);
1048 		CLR(tp->t_flags, TS_TSTAMPDCDCLR);
1049 		CLR(tp->t_flags, TS_TSTAMPCTSCLR);
1050 		if (ISSET(ts->ts_set, TIOCM_CAR))
1051 			SET(tp->t_flags, TS_TSTAMPDCDSET);
1052 		if (ISSET(ts->ts_set, TIOCM_CTS))
1053 			SET(tp->t_flags, TS_TSTAMPCTSSET);
1054 		if (ISSET(ts->ts_clr, TIOCM_CAR))
1055 			SET(tp->t_flags, TS_TSTAMPDCDCLR);
1056 		if (ISSET(ts->ts_clr, TIOCM_CTS))
1057 			SET(tp->t_flags, TS_TSTAMPCTSCLR);
1058 		splx(s);
1059 		break;
1060 	}
1061 	default:
1062 		return (-1);
1063 	}
1064 	return (0);
1065 }
1066 
1067 int
1068 ttpoll(dev_t device, int events, struct proc *p)
1069 {
1070 	struct tty *tp;
1071 	int revents, s;
1072 
1073 	tp = (*cdevsw[major(device)].d_tty)(device);
1074 
1075 	revents = 0;
1076 	s = spltty();
1077 	if (events & (POLLIN | POLLRDNORM)) {
1078 		if (ttnread(tp) > 0 || (!ISSET(tp->t_cflag, CLOCAL) &&
1079 		    !ISSET(tp->t_state, TS_CARR_ON)))
1080 			revents |= events & (POLLIN | POLLRDNORM);
1081 	}
1082 	/* NOTE: POLLHUP and POLLOUT/POLLWRNORM are mutually exclusive */
1083 	if (!ISSET(tp->t_cflag, CLOCAL) && !ISSET(tp->t_state, TS_CARR_ON)) {
1084 		revents |= POLLHUP;
1085 	} else if (events & (POLLOUT | POLLWRNORM)) {
1086 		if (tp->t_outq.c_cc <= tp->t_lowat)
1087 			revents |= events & (POLLOUT | POLLWRNORM);
1088 	}
1089 	if (revents == 0) {
1090 		if (events & (POLLIN | POLLRDNORM))
1091 			selrecord(p, &tp->t_rsel);
1092 		if (events & (POLLOUT | POLLWRNORM))
1093 			selrecord(p, &tp->t_wsel);
1094 	}
1095 	splx(s);
1096 	return (revents);
1097 }
1098 
1099 const struct filterops ttyread_filtops = {
1100 	.f_flags	= FILTEROP_ISFD,
1101 	.f_attach	= NULL,
1102 	.f_detach	= filt_ttyrdetach,
1103 	.f_event	= filt_ttyread,
1104 };
1105 
1106 const struct filterops ttywrite_filtops = {
1107 	.f_flags	= FILTEROP_ISFD,
1108 	.f_attach	= NULL,
1109 	.f_detach	= filt_ttywdetach,
1110 	.f_event	= filt_ttywrite,
1111 };
1112 
1113 int
1114 ttkqfilter(dev_t dev, struct knote *kn)
1115 {
1116 	struct tty *tp = (*cdevsw[major(dev)].d_tty)(dev);
1117 	struct klist *klist;
1118 	int s;
1119 
1120 	switch (kn->kn_filter) {
1121 	case EVFILT_READ:
1122 		klist = &tp->t_rsel.si_note;
1123 		kn->kn_fop = &ttyread_filtops;
1124 		break;
1125 	case EVFILT_WRITE:
1126 		klist = &tp->t_wsel.si_note;
1127 		kn->kn_fop = &ttywrite_filtops;
1128 		break;
1129 	default:
1130 		return (EINVAL);
1131 	}
1132 
1133 	kn->kn_hook = tp;
1134 
1135 	s = spltty();
1136 	klist_insert(klist, kn);
1137 	splx(s);
1138 
1139 	return (0);
1140 }
1141 
1142 void
1143 filt_ttyrdetach(struct knote *kn)
1144 {
1145 	struct tty *tp = kn->kn_hook;
1146 	int s;
1147 
1148 	s = spltty();
1149 	klist_remove(&tp->t_rsel.si_note, kn);
1150 	splx(s);
1151 }
1152 
1153 int
1154 filt_ttyread(struct knote *kn, long hint)
1155 {
1156 	struct tty *tp = kn->kn_hook;
1157 	int s;
1158 
1159 	s = spltty();
1160 	kn->kn_data = ttnread(tp);
1161 	splx(s);
1162 	if (!ISSET(tp->t_cflag, CLOCAL) && !ISSET(tp->t_state, TS_CARR_ON)) {
1163 		kn->kn_flags |= EV_EOF;
1164 		if (kn->kn_flags & __EV_POLL)
1165 			kn->kn_flags |= __EV_HUP;
1166 		return (1);
1167 	}
1168 	return (kn->kn_data > 0);
1169 }
1170 
1171 void
1172 filt_ttywdetach(struct knote *kn)
1173 {
1174 	struct tty *tp = kn->kn_hook;
1175 	int s;
1176 
1177 	s = spltty();
1178 	klist_remove(&tp->t_wsel.si_note, kn);
1179 	splx(s);
1180 }
1181 
1182 int
1183 filt_ttywrite(struct knote *kn, long hint)
1184 {
1185 	struct tty *tp = kn->kn_hook;
1186 	int canwrite, s;
1187 
1188 	s = spltty();
1189 	kn->kn_data = tp->t_outq.c_cn - tp->t_outq.c_cc;
1190 	canwrite = (tp->t_outq.c_cc <= tp->t_lowat);
1191 	splx(s);
1192 	return (canwrite);
1193 }
1194 
1195 static int
1196 ttnread(struct tty *tp)
1197 {
1198 	int nread;
1199 
1200 	splassert(IPL_TTY);
1201 
1202 	if (ISSET(tp->t_lflag, PENDIN))
1203 		ttypend(tp);
1204 	nread = tp->t_canq.c_cc;
1205 	if (!ISSET(tp->t_lflag, ICANON)) {
1206 		nread += tp->t_rawq.c_cc;
1207 		if (nread < tp->t_cc[VMIN] && !tp->t_cc[VTIME])
1208 			nread = 0;
1209 	}
1210 	return (nread);
1211 }
1212 
1213 /*
1214  * Wait for output to drain, or if this times out, flush it.
1215  */
1216 int
1217 ttywait_nsec(struct tty *tp, uint64_t nsecs)
1218 {
1219 	int error, s;
1220 
1221 	error = 0;
1222 	s = spltty();
1223 	while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1224 	    (ISSET(tp->t_state, TS_CARR_ON) || ISSET(tp->t_cflag, CLOCAL)) &&
1225 	    tp->t_oproc) {
1226 		(*tp->t_oproc)(tp);
1227 		if ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1228 		    (ISSET(tp->t_state, TS_CARR_ON) || ISSET(tp->t_cflag, CLOCAL))
1229 		    && tp->t_oproc) {
1230 			SET(tp->t_state, TS_ASLEEP);
1231 			error = ttysleep_nsec(tp, &tp->t_outq, TTOPRI | PCATCH,
1232 			    ttyout, nsecs);
1233 			if (error == EWOULDBLOCK)
1234 				ttyflush(tp, FWRITE);
1235 			if (error)
1236 				break;
1237 		} else
1238 			break;
1239 	}
1240 	splx(s);
1241 	return (error);
1242 }
1243 
1244 int
1245 ttywait(struct tty *tp)
1246 {
1247 	return (ttywait_nsec(tp, INFSLP));
1248 }
1249 
1250 /*
1251  * Flush if successfully wait.
1252  */
1253 int
1254 ttywflush(struct tty *tp)
1255 {
1256 	int error;
1257 
1258 	error = ttywait_nsec(tp, SEC_TO_NSEC(5));
1259 	if (error == 0 || error == EWOULDBLOCK)
1260 		ttyflush(tp, FREAD);
1261 	return (error);
1262 }
1263 
1264 /*
1265  * Flush tty read and/or write queues, notifying anyone waiting.
1266  */
1267 void
1268 ttyflush(struct tty *tp, int rw)
1269 {
1270 	int s;
1271 
1272 	s = spltty();
1273 	if (rw & FREAD) {
1274 		FLUSHQ(&tp->t_canq);
1275 		FLUSHQ(&tp->t_rawq);
1276 		tp->t_rocount = 0;
1277 		tp->t_rocol = 0;
1278 		CLR(tp->t_state, TS_LOCAL);
1279 		ttyunblock(tp);
1280 		ttwakeup(tp);
1281 	}
1282 	if (rw & FWRITE) {
1283 		CLR(tp->t_state, TS_TTSTOP);
1284 		(*cdevsw[major(tp->t_dev)].d_stop)(tp, rw);
1285 		FLUSHQ(&tp->t_outq);
1286 		wakeup((caddr_t)&tp->t_outq);
1287 		selwakeup(&tp->t_wsel);
1288 	}
1289 	splx(s);
1290 }
1291 
1292 /*
1293  * Copy in the default termios characters.
1294  */
1295 void
1296 ttychars(struct tty *tp)
1297 {
1298 
1299 	memcpy(tp->t_cc, ttydefchars, sizeof(ttydefchars));
1300 }
1301 
1302 /*
1303  * Send stop character on input overflow.
1304  */
1305 static void
1306 ttyblock(struct tty *tp)
1307 {
1308 	int total;
1309 
1310 	total = tp->t_rawq.c_cc + tp->t_canq.c_cc;
1311 	if (tp->t_rawq.c_cc > TTYHOG(tp)) {
1312 		ttyflush(tp, FREAD | FWRITE);
1313 		CLR(tp->t_state, TS_TBLOCK);
1314 	}
1315 	/*
1316 	 * Block further input iff: current input > threshold
1317 	 * AND input is available to user program.
1318 	 */
1319 	if ((total >= TTYHOG(tp) / 2 &&
1320 	     !ISSET(tp->t_state, TS_TBLOCK) &&
1321 	     !ISSET(tp->t_lflag, ICANON)) || tp->t_canq.c_cc > 0) {
1322 		if (ISSET(tp->t_iflag, IXOFF) &&
1323 		    tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
1324 		    putc(tp->t_cc[VSTOP], &tp->t_outq) == 0) {
1325 			SET(tp->t_state, TS_TBLOCK);
1326 			ttstart(tp);
1327 		}
1328 		/* Try to block remote output via hardware flow control. */
1329 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
1330 		    (*tp->t_hwiflow)(tp, 1) != 0)
1331 			SET(tp->t_state, TS_TBLOCK);
1332 	}
1333 }
1334 
1335 void
1336 ttrstrt(void *arg)
1337 {
1338 	struct tty *tp = (struct tty *)arg;
1339 	int s;
1340 
1341 #ifdef DIAGNOSTIC
1342 	if (tp == NULL)
1343 		panic("ttrstrt");
1344 #endif
1345 	s = spltty();
1346 	CLR(tp->t_state, TS_TIMEOUT);
1347 	ttstart(tp);
1348 	splx(s);
1349 }
1350 
1351 int
1352 ttstart(struct tty *tp)
1353 {
1354 
1355 	if (tp->t_oproc != NULL)	/* XXX: Kludge for pty. */
1356 		(*tp->t_oproc)(tp);
1357 	return (0);
1358 }
1359 
1360 /*
1361  * "close" a line discipline
1362  */
1363 int
1364 ttylclose(struct tty *tp, int flag, struct proc *p)
1365 {
1366 
1367 	if (flag & FNONBLOCK)
1368 		ttyflush(tp, FREAD | FWRITE);
1369 	else
1370 		ttywflush(tp);
1371 	return (0);
1372 }
1373 
1374 /*
1375  * Handle modem control transition on a tty.
1376  * Flag indicates new state of carrier.
1377  * Returns 0 if the line should be turned off, otherwise 1.
1378  */
1379 int
1380 ttymodem(struct tty *tp, int flag)
1381 {
1382 
1383 	if (!ISSET(tp->t_state, TS_WOPEN) && ISSET(tp->t_cflag, MDMBUF)) {
1384 		/*
1385 		 * MDMBUF: do flow control according to carrier flag
1386 		 */
1387 		if (flag) {
1388 			CLR(tp->t_state, TS_TTSTOP);
1389 			ttstart(tp);
1390 		} else if (!ISSET(tp->t_state, TS_TTSTOP)) {
1391 			SET(tp->t_state, TS_TTSTOP);
1392 			(*cdevsw[major(tp->t_dev)].d_stop)(tp, 0);
1393 		}
1394 	} else if (flag == 0) {
1395 		/*
1396 		 * Lost carrier.
1397 		 */
1398 		CLR(tp->t_state, TS_CARR_ON);
1399 		if (ISSET(tp->t_state, TS_ISOPEN) &&
1400 		    !ISSET(tp->t_cflag, CLOCAL)) {
1401 			if (tp->t_session && tp->t_session->s_leader)
1402 				prsignal(tp->t_session->s_leader, SIGHUP);
1403 			ttyflush(tp, FREAD | FWRITE);
1404 			return (0);
1405 		}
1406 	} else {
1407 		/*
1408 		 * Carrier now on.
1409 		 */
1410 		SET(tp->t_state, TS_CARR_ON);
1411 		ttwakeup(tp);
1412 	}
1413 	return (1);
1414 }
1415 
1416 /*
1417  * Default modem control routine (for other line disciplines).
1418  * Return argument flag, to turn off device on carrier drop.
1419  */
1420 int
1421 nullmodem(struct tty *tp, int flag)
1422 {
1423 
1424 	if (flag)
1425 		SET(tp->t_state, TS_CARR_ON);
1426 	else {
1427 		CLR(tp->t_state, TS_CARR_ON);
1428 		if (ISSET(tp->t_state, TS_ISOPEN) &&
1429 		    !ISSET(tp->t_cflag, CLOCAL)) {
1430 			if (tp->t_session && tp->t_session->s_leader)
1431 				prsignal(tp->t_session->s_leader, SIGHUP);
1432 			ttyflush(tp, FREAD | FWRITE);
1433 			return (0);
1434 		}
1435 	}
1436 	return (1);
1437 }
1438 
1439 /*
1440  * Reinput pending characters after state switch
1441  * call at spltty().
1442  */
1443 void
1444 ttypend(struct tty *tp)
1445 {
1446 	struct clist tq;
1447 	int c;
1448 
1449 	splassert(IPL_TTY);
1450 
1451 	CLR(tp->t_lflag, PENDIN);
1452 	SET(tp->t_state, TS_TYPEN);
1453 	tq = tp->t_rawq;
1454 	tp->t_rawq.c_cc = 0;
1455 	tp->t_rawq.c_cf = tp->t_rawq.c_cl = 0;
1456 	while ((c = getc(&tq)) >= 0)
1457 		ttyinput(c, tp);
1458 	CLR(tp->t_state, TS_TYPEN);
1459 }
1460 
1461 void ttvtimeout(void *);
1462 
1463 void
1464 ttvtimeout(void *arg)
1465 {
1466 	struct tty *tp = (struct tty *)arg;
1467 
1468 	wakeup(&tp->t_rawq);
1469 }
1470 
1471 /*
1472  * Process a read call on a tty device.
1473  */
1474 int
1475 ttread(struct tty *tp, struct uio *uio, int flag)
1476 {
1477 	struct timeout *stime = NULL;
1478 	struct proc *p = curproc;
1479 	struct process *pr = p->p_p;
1480 	int s, first, error = 0;
1481 	u_char *cc = tp->t_cc;
1482 	struct clist *qp;
1483 	int last_cc = 0;
1484 	long lflag;
1485 	int c;
1486 
1487 loop:	lflag = tp->t_lflag;
1488 	s = spltty();
1489 	/*
1490 	 * take pending input first
1491 	 */
1492 	if (ISSET(lflag, PENDIN))
1493 		ttypend(tp);
1494 	splx(s);
1495 
1496 	/*
1497 	 * Hang process if it's in the background.
1498 	 */
1499 	if (isbackground(pr, tp)) {
1500 		if (sigismasked(p, SIGTTIN) ||
1501 		    pr->ps_flags & PS_PPWAIT || pr->ps_pgrp->pg_jobc == 0) {
1502 			error = EIO;
1503 			goto out;
1504 		}
1505 		pgsignal(pr->ps_pgrp, SIGTTIN, 1);
1506 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, ttybg);
1507 		if (error)
1508 			goto out;
1509 		goto loop;
1510 	}
1511 
1512 	s = spltty();
1513 	if (!ISSET(lflag, ICANON)) {
1514 		int min = cc[VMIN];
1515 		int time = cc[VTIME] * 100;	/* tenths of a second (ms) */
1516 
1517 		qp = &tp->t_rawq;
1518 		/*
1519 		 * Check each of the four combinations.
1520 		 * (min > 0 && time == 0) is the normal read case.
1521 		 * It should be fairly efficient, so we check that and its
1522 		 * companion case (min == 0 && time == 0) first.
1523 		 */
1524 		if (time == 0) {
1525 			if (qp->c_cc < min)
1526 				goto sleep;
1527 			goto read;
1528 		}
1529 		if (min > 0) {
1530 			if (qp->c_cc <= 0)
1531 				goto sleep;
1532 			if (qp->c_cc >= min)
1533 				goto read;
1534 			if (stime == NULL) {
1535 alloc_timer:
1536 				stime = malloc(sizeof(*stime), M_TEMP, M_WAITOK);
1537 				timeout_set(stime, ttvtimeout, tp);
1538 				timeout_add_msec(stime, time);
1539 			} else if (qp->c_cc > last_cc) {
1540 				/* got a character, restart timer */
1541 				timeout_add_msec(stime, time);
1542 			}
1543 		} else {	/* min == 0 */
1544 			if (qp->c_cc > 0)
1545 				goto read;
1546 			if (stime == NULL) {
1547 				goto alloc_timer;
1548 			}
1549 		}
1550 		last_cc = qp->c_cc;
1551 		if (stime && !timeout_triggered(stime)) {
1552 			goto sleep;
1553 		}
1554 	} else if ((qp = &tp->t_canq)->c_cc <= 0) {
1555 		int carrier;
1556 
1557 sleep:
1558 		/*
1559 		 * If there is no input, sleep on rawq
1560 		 * awaiting hardware receipt and notification.
1561 		 * If we have data, we don't need to check for carrier.
1562 		 */
1563 		carrier = ISSET(tp->t_state, TS_CARR_ON) ||
1564 		    ISSET(tp->t_cflag, CLOCAL);
1565 		if (!carrier && ISSET(tp->t_state, TS_ISOPEN)) {
1566 			splx(s);
1567 			error = 0;
1568 			goto out;
1569 		}
1570 		if (flag & IO_NDELAY) {
1571 			splx(s);
1572 			error = EWOULDBLOCK;
1573 			goto out;
1574 		}
1575 		error = ttysleep(tp, &tp->t_rawq, TTIPRI | PCATCH,
1576 		    carrier ? ttyin : ttopen);
1577 		splx(s);
1578 		if (stime && timeout_triggered(stime))
1579 			error = EWOULDBLOCK;
1580 		if (cc[VMIN] == 0 && error == EWOULDBLOCK) {
1581 			error = 0;
1582 			goto out;
1583 		}
1584 		if (error && error != EWOULDBLOCK)
1585 			goto out;
1586 		error = 0;
1587 		goto loop;
1588 	}
1589 read:
1590 	splx(s);
1591 
1592 	/*
1593 	 * Input present, check for input mapping and processing.
1594 	 */
1595 	first = 1;
1596 	while ((c = getc(qp)) >= 0) {
1597 		/*
1598 		 * delayed suspend (^Y)
1599 		 */
1600 		if (CCEQ(cc[VDSUSP], c) &&
1601 		    ISSET(lflag, IEXTEN | ISIG) == (IEXTEN | ISIG)) {
1602 			pgsignal(tp->t_pgrp, SIGTSTP, 1);
1603 			if (first) {
1604 				error = ttysleep(tp, &lbolt, TTIPRI | PCATCH,
1605 				    ttybg);
1606 				if (error)
1607 					break;
1608 				goto loop;
1609 			}
1610 			break;
1611 		}
1612 		/*
1613 		 * Interpret EOF only in canonical mode.
1614 		 */
1615 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
1616 			break;
1617 		/*
1618 		 * Give user character.
1619 		 */
1620 		error = ureadc(c, uio);
1621 		if (error)
1622 			break;
1623 		if (uio->uio_resid == 0)
1624 			break;
1625 		/*
1626 		 * In canonical mode check for a "break character"
1627 		 * marking the end of a "line of input".
1628 		 */
1629 		if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
1630 			break;
1631 		first = 0;
1632 	}
1633 	/*
1634 	 * Look to unblock output now that (presumably)
1635 	 * the input queue has gone down.
1636 	 */
1637 	s = spltty();
1638 	if (tp->t_rawq.c_cc < TTYHOG(tp)/5)
1639 		ttyunblock(tp);
1640 	splx(s);
1641 
1642 out:
1643 	if (stime) {
1644 		timeout_del(stime);
1645 		free(stime, M_TEMP, sizeof(*stime));
1646 	}
1647 	return (error);
1648 }
1649 
1650 /* Call at spltty */
1651 void
1652 ttyunblock(struct tty *tp)
1653 {
1654 	u_char *cc = tp->t_cc;
1655 
1656 	splassert(IPL_TTY);
1657 
1658 	if (ISSET(tp->t_state, TS_TBLOCK)) {
1659 		if (ISSET(tp->t_iflag, IXOFF) &&
1660 		    cc[VSTART] != _POSIX_VDISABLE &&
1661 		    putc(cc[VSTART], &tp->t_outq) == 0) {
1662 			CLR(tp->t_state, TS_TBLOCK);
1663 			ttstart(tp);
1664 		}
1665 		/* Try to unblock remote output via hardware flow control. */
1666 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
1667 		    (*tp->t_hwiflow)(tp, 0) != 0)
1668 			CLR(tp->t_state, TS_TBLOCK);
1669 	}
1670 }
1671 
1672 /*
1673  * Check the output queue on tp for space for a kernel message (from uprintf
1674  * or tprintf).  Allow some space over the normal hiwater mark so we don't
1675  * lose messages due to normal flow control, but don't let the tty run amok.
1676  * Sleeps here are not interruptible, but we return prematurely if new signals
1677  * arrive.
1678  */
1679 int
1680 ttycheckoutq(struct tty *tp, int wait)
1681 {
1682 	int hiwat, s, oldsig;
1683 
1684 	hiwat = tp->t_hiwat;
1685 	s = spltty();
1686 	oldsig = wait ? SIGPENDING(curproc) : 0;
1687 	if (tp->t_outq.c_cc > hiwat + TTHIWATMINSPACE)
1688 		while (tp->t_outq.c_cc > hiwat) {
1689 			ttstart(tp);
1690 			if (wait == 0 || SIGPENDING(curproc) != oldsig) {
1691 				splx(s);
1692 				return (0);
1693 			}
1694 			SET(tp->t_state, TS_ASLEEP);
1695 			tsleep_nsec(&tp->t_outq, PZERO - 1, "ttckoutq",
1696 			    SEC_TO_NSEC(1));
1697 		}
1698 	splx(s);
1699 	return (1);
1700 }
1701 
1702 /*
1703  * Process a write call on a tty device.
1704  */
1705 int
1706 ttwrite(struct tty *tp, struct uio *uio, int flag)
1707 {
1708 	u_char *cp = NULL;
1709 	int cc, ce, obufcc = 0;
1710 	struct proc *p;
1711 	struct process *pr;
1712 	int hiwat, error, s;
1713 	size_t cnt;
1714 	u_char obuf[OBUFSIZ];
1715 
1716 	hiwat = tp->t_hiwat;
1717 	cnt = uio->uio_resid;
1718 	error = 0;
1719 	cc = 0;
1720 loop:
1721 	s = spltty();
1722 	if (!ISSET(tp->t_state, TS_CARR_ON) &&
1723 	    !ISSET(tp->t_cflag, CLOCAL)) {
1724 		if (ISSET(tp->t_state, TS_ISOPEN)) {
1725 			splx(s);
1726 			error = EIO;
1727 			goto done;
1728 		} else if (flag & IO_NDELAY) {
1729 			splx(s);
1730 			error = EWOULDBLOCK;
1731 			goto out;
1732 		} else {
1733 			/* Sleep awaiting carrier. */
1734 			error = ttysleep(tp,
1735 			    &tp->t_rawq, TTIPRI | PCATCH, ttopen);
1736 			splx(s);
1737 			if (error)
1738 				goto out;
1739 			goto loop;
1740 		}
1741 	}
1742 	splx(s);
1743 	/*
1744 	 * Hang the process if it's in the background.
1745 	 */
1746 	p = curproc;
1747 	pr = p->p_p;
1748 	if (isbackground(pr, tp) &&
1749 	    ISSET(tp->t_lflag, TOSTOP) && (pr->ps_flags & PS_PPWAIT) == 0 &&
1750 	    !sigismasked(p, SIGTTOU)) {
1751 		if (pr->ps_pgrp->pg_jobc == 0) {
1752 			error = EIO;
1753 			goto out;
1754 		}
1755 		pgsignal(pr->ps_pgrp, SIGTTOU, 1);
1756 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, ttybg);
1757 		if (error)
1758 			goto out;
1759 		goto loop;
1760 	}
1761 	/*
1762 	 * Process the user's data in at most OBUFSIZ chunks.  Perform any
1763 	 * output translation.  Keep track of high water mark, sleep on
1764 	 * overflow awaiting device aid in acquiring new space.
1765 	 */
1766 	while (uio->uio_resid > 0 || cc > 0) {
1767 		if (ISSET(tp->t_lflag, FLUSHO)) {
1768 			uio->uio_resid = 0;
1769 			goto done;
1770 		}
1771 		if (tp->t_outq.c_cc > hiwat)
1772 			goto ovhiwat;
1773 		/*
1774 		 * Grab a hunk of data from the user, unless we have some
1775 		 * leftover from last time.
1776 		 */
1777 		if (cc == 0) {
1778 			cc = MIN(uio->uio_resid, OBUFSIZ);
1779 			cp = obuf;
1780 			error = uiomove(cp, cc, uio);
1781 			if (error) {
1782 				cc = 0;
1783 				break;
1784 			}
1785 			if (cc > obufcc)
1786 				obufcc = cc;
1787 
1788 			/* duplicate /dev/console output into console buffer */
1789 			if (consbufp && cn_tab &&
1790 			    cn_tab->cn_dev == tp->t_dev && tp->t_gen == 0) {
1791 				int i;
1792 				for (i = 0; i < cc; i++) {
1793 					char c = cp[i];
1794 					if (c != '\0' && c != '\r' && c != 0177)
1795 						msgbuf_putchar(consbufp, c);
1796 				}
1797 			}
1798 		}
1799 		/*
1800 		 * If nothing fancy need be done, grab those characters we
1801 		 * can handle without any of ttyoutput's processing and
1802 		 * just transfer them to the output q.  For those chars
1803 		 * which require special processing (as indicated by the
1804 		 * bits in char_type), call ttyoutput.  After processing
1805 		 * a hunk of data, look for FLUSHO so ^O's will take effect
1806 		 * immediately.
1807 		 */
1808 		while (cc > 0) {
1809 			int i;
1810 			if (!ISSET(tp->t_oflag, OPOST))
1811 				ce = cc;
1812 			else {
1813 				ce = cc - scanc((u_int)cc, cp, char_type,
1814 				    CCLASSMASK);
1815 				/*
1816 				 * If ce is zero, then we're processing
1817 				 * a special character through ttyoutput.
1818 				 */
1819 				if (ce == 0) {
1820 					tp->t_rocount = 0;
1821 					if (ttyoutput(*cp, tp) >= 0) {
1822 						/* out of space */
1823 						goto ovhiwat;
1824 					}
1825 					cp++;
1826 					cc--;
1827 					if (ISSET(tp->t_lflag, FLUSHO) ||
1828 					    tp->t_outq.c_cc > hiwat)
1829 						goto ovhiwat;
1830 					continue;
1831 				}
1832 			}
1833 			/*
1834 			 * A bunch of normal characters have been found.
1835 			 * Transfer them en masse to the output queue and
1836 			 * continue processing at the top of the loop.
1837 			 * If there are any further characters in this
1838 			 * <= OBUFSIZ chunk, the first should be a character
1839 			 * requiring special handling by ttyoutput.
1840 			 */
1841 			tp->t_rocount = 0;
1842 			i = b_to_q(cp, ce, &tp->t_outq);
1843 			ce -= i;
1844 			tp->t_column += ce;
1845 			cp += ce, cc -= ce, tk_nout += ce;
1846 			tp->t_outcc += ce;
1847 			if (i > 0) {
1848 				/* out of space */
1849 				goto ovhiwat;
1850 			}
1851 			if (ISSET(tp->t_lflag, FLUSHO) ||
1852 			    tp->t_outq.c_cc > hiwat)
1853 				break;
1854 		}
1855 		ttstart(tp);
1856 	}
1857 out:
1858 	/*
1859 	 * If cc is nonzero, we leave the uio structure inconsistent, as the
1860 	 * offset and iov pointers have moved forward, but it doesn't matter
1861 	 * (the call will either return short or restart with a new uio).
1862 	 */
1863 	uio->uio_resid += cc;
1864 done:
1865 	if (obufcc)
1866 		explicit_bzero(obuf, obufcc);
1867 	return (error);
1868 
1869 ovhiwat:
1870 	ttstart(tp);
1871 	s = spltty();
1872 	/*
1873 	 * This can only occur if FLUSHO is set in t_lflag,
1874 	 * or if ttstart/oproc is synchronous (or very fast).
1875 	 */
1876 	if (tp->t_outq.c_cc <= hiwat) {
1877 		splx(s);
1878 		goto loop;
1879 	}
1880 	if (flag & IO_NDELAY) {
1881 		splx(s);
1882 		uio->uio_resid += cc;
1883 		if (obufcc)
1884 			explicit_bzero(obuf, obufcc);
1885 		return (uio->uio_resid == cnt ? EWOULDBLOCK : 0);
1886 	}
1887 	SET(tp->t_state, TS_ASLEEP);
1888 	error = ttysleep(tp, &tp->t_outq, TTOPRI | PCATCH, ttyout);
1889 	splx(s);
1890 	if (error)
1891 		goto out;
1892 	goto loop;
1893 }
1894 
1895 /*
1896  * Rubout one character from the rawq of tp
1897  * as cleanly as possible.
1898  */
1899 int
1900 ttyrub(int c, struct tty *tp)
1901 {
1902 	u_char *cp;
1903 	int savecol;
1904 	int tabc, s;
1905 
1906 	if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
1907 		return 0;
1908 	CLR(tp->t_lflag, FLUSHO);
1909 	if (ISSET(tp->t_lflag, ECHOE)) {
1910 		if (tp->t_rocount == 0) {
1911 			/*
1912 			 * Screwed by ttwrite; retype
1913 			 */
1914 			return ttyretype(tp);
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 					return ttyretype(tp);
1935 				s = spltty();
1936 				savecol = tp->t_column;
1937 				SET(tp->t_state, TS_CNTTB);
1938 				SET(tp->t_lflag, FLUSHO);
1939 				tp->t_column = tp->t_rocol;
1940 				for (cp = firstc(&tp->t_rawq, &tabc); cp;
1941 				    cp = nextc(&tp->t_rawq, cp, &tabc))
1942 					ttyecho(tabc, tp);
1943 				CLR(tp->t_lflag, FLUSHO);
1944 				CLR(tp->t_state, TS_CNTTB);
1945 				splx(s);
1946 
1947 				/* savecol will now be length of the tab. */
1948 				savecol -= tp->t_column;
1949 				tp->t_column += savecol;
1950 				if (savecol > 8)
1951 					savecol = 8;	/* overflow screw */
1952 				while (--savecol >= 0)
1953 					(void)ttyoutput('\b', tp);
1954 				break;
1955 			default:			/* XXX */
1956 #define	PANICSTR	"ttyrub: would panic c = %d, val = %d\n"
1957 				(void)printf(PANICSTR, c, CCLASS(c));
1958 #ifdef notdef
1959 				panic(PANICSTR, c, CCLASS(c));
1960 #endif
1961 			}
1962 		}
1963 	} else if (ISSET(tp->t_lflag, ECHOPRT)) {
1964 		if (!ISSET(tp->t_state, TS_ERASE)) {
1965 			SET(tp->t_state, TS_ERASE);
1966 			(void)ttyoutput('\\', tp);
1967 		}
1968 		ttyecho(c, tp);
1969 	} else
1970 		ttyecho(tp->t_cc[VERASE], tp);
1971 	--tp->t_rocount;
1972 	return 0;
1973 }
1974 
1975 /*
1976  * Back over cnt characters, erasing them.
1977  */
1978 static void
1979 ttyrubo(struct tty *tp, int cnt)
1980 {
1981 
1982 	while (cnt-- > 0) {
1983 		(void)ttyoutput('\b', tp);
1984 		(void)ttyoutput(' ', tp);
1985 		(void)ttyoutput('\b', tp);
1986 	}
1987 }
1988 
1989 /*
1990  * ttyretype --
1991  *	Reprint the rawq line.  Note, it is assumed that c_cc has already
1992  *	been checked.
1993  */
1994 int
1995 ttyretype(struct tty *tp)
1996 {
1997 	u_char *cp;
1998 	int s, c;
1999 
2000 	/* Echo the reprint character. */
2001 	if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
2002 		ttyecho(tp->t_cc[VREPRINT], tp);
2003 
2004 	(void)ttyoutput('\n', tp);
2005 
2006 	s = spltty();
2007 	for (cp = firstc(&tp->t_canq, &c); cp; cp = nextc(&tp->t_canq, cp, &c))
2008 		ttyecho(c, tp);
2009 	for (cp = firstc(&tp->t_rawq, &c); cp; cp = nextc(&tp->t_rawq, cp, &c))
2010 		ttyecho(c, tp);
2011 	CLR(tp->t_state, TS_ERASE);
2012 	splx(s);
2013 
2014 	tp->t_rocount = tp->t_rawq.c_cc;
2015 	tp->t_rocol = 0;
2016 	return (1);
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 	rw_enter_write(&ttylist_lock);
2349 	TAILQ_INSERT_TAIL(&ttylist, tp, tty_link);
2350 	++tty_count;
2351 	rw_exit_write(&ttylist_lock);
2352 
2353 	timeout_set(&tp->t_rstrt_to, ttrstrt, tp);
2354 
2355 	return(tp);
2356 }
2357 
2358 
2359 /*
2360  * Free a tty structure and its buffers, after removing it from the tty list.
2361  */
2362 void
2363 ttyfree(struct tty *tp)
2364 {
2365 	int s;
2366 
2367 	rw_enter_write(&ttylist_lock);
2368 	--tty_count;
2369 #ifdef DIAGNOSTIC
2370 	if (tty_count < 0)
2371 		panic("ttyfree: tty_count < 0");
2372 #endif
2373 	TAILQ_REMOVE(&ttylist, tp, tty_link);
2374 	rw_exit_write(&ttylist_lock);
2375 
2376 	s = spltty();
2377 	klist_invalidate(&tp->t_rsel.si_note);
2378 	klist_invalidate(&tp->t_wsel.si_note);
2379 	splx(s);
2380 
2381 	clfree(&tp->t_rawq);
2382 	clfree(&tp->t_canq);
2383 	clfree(&tp->t_outq);
2384 	free(tp, M_TTYS, sizeof(*tp));
2385 }
2386 
2387 void
2388 ttystats_init(struct itty **ttystats, int *ttycp, size_t *ttystatssiz)
2389 {
2390 	int ntty = 0, ttyc;
2391 	struct itty *itp;
2392 	struct tty *tp;
2393 
2394 	ttyc = tty_count;
2395 	*ttystatssiz = ttyc * sizeof(struct itty);
2396 	*ttystats = mallocarray(ttyc, sizeof(struct itty),
2397 	    M_SYSCTL, M_WAITOK|M_ZERO);
2398 
2399 	rw_enter_write(&ttylist_lock);
2400 	for (tp = TAILQ_FIRST(&ttylist), itp = *ttystats; tp && ntty++ < ttyc;
2401 	    tp = TAILQ_NEXT(tp, tty_link), itp++) {
2402 		itp->t_dev = tp->t_dev;
2403 		itp->t_rawq_c_cc = tp->t_rawq.c_cc;
2404 		itp->t_canq_c_cc = tp->t_canq.c_cc;
2405 		itp->t_outq_c_cc = tp->t_outq.c_cc;
2406 		itp->t_hiwat = tp->t_hiwat;
2407 		itp->t_lowat = tp->t_lowat;
2408 		if (ISSET(tp->t_oflag, OPOST))
2409 			itp->t_column = tp->t_column;
2410 		itp->t_state = tp->t_state;
2411 		itp->t_session = tp->t_session;
2412 		if (tp->t_pgrp)
2413 			itp->t_pgrp_pg_id = tp->t_pgrp->pg_id;
2414 		else
2415 			itp->t_pgrp_pg_id = 0;
2416 		itp->t_line = tp->t_line;
2417 	}
2418 	rw_exit_write(&ttylist_lock);
2419 	*ttycp = ntty;
2420 }
2421 
2422 /*
2423  * Return tty-related information.
2424  */
2425 int
2426 sysctl_tty(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
2427     size_t newlen)
2428 {
2429 	int err;
2430 
2431 	if (namelen != 1)
2432 		return (ENOTDIR);
2433 
2434 	switch (name[0]) {
2435 	case KERN_TTY_TKNIN:
2436 		return (sysctl_rdquad(oldp, oldlenp, newp, tk_nin));
2437 	case KERN_TTY_TKNOUT:
2438 		return (sysctl_rdquad(oldp, oldlenp, newp, tk_nout));
2439 	case KERN_TTY_TKRAWCC:
2440 		return (sysctl_rdquad(oldp, oldlenp, newp, tk_rawcc));
2441 	case KERN_TTY_TKCANCC:
2442 		return (sysctl_rdquad(oldp, oldlenp, newp, tk_cancc));
2443 	case KERN_TTY_INFO:
2444 	    {
2445 		struct itty *ttystats;
2446 		size_t ttystatssiz;
2447 		int ttyc;
2448 
2449 		ttystats_init(&ttystats, &ttyc, &ttystatssiz);
2450 		err = sysctl_rdstruct(oldp, oldlenp, newp, ttystats,
2451 		    ttyc * sizeof(struct itty));
2452 		free(ttystats, M_SYSCTL, ttystatssiz);
2453 		return (err);
2454 	    }
2455 	default:
2456 #if NPTY > 0
2457 		return (sysctl_pty(name, namelen, oldp, oldlenp, newp, newlen));
2458 #else
2459 		return (EOPNOTSUPP);
2460 #endif
2461 	}
2462 	/* NOTREACHED */
2463 }
2464 
2465 void
2466 ttytstamp(struct tty *tp, int octs, int ncts, int odcd, int ndcd)
2467 {
2468 	int doit = 0;
2469 
2470 	if (ncts ^ octs)
2471 		doit |= ncts ? ISSET(tp->t_flags, TS_TSTAMPCTSSET) :
2472 		    ISSET(tp->t_flags, TS_TSTAMPCTSCLR);
2473 	if (ndcd ^ odcd)
2474 		doit |= ndcd ? ISSET(tp->t_flags, TS_TSTAMPDCDSET) :
2475 		    ISSET(tp->t_flags, TS_TSTAMPDCDCLR);
2476 
2477 	if (doit)
2478 		microtime(&tp->t_tv);
2479 }
2480