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