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