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