xref: /openbsd-src/sys/kern/tty.c (revision 2b0358df1d88d06ef4139321dd05bd5e05d91eaf)
1 /*	$OpenBSD: tty.c,v 1.79 2008/12/24 11:20:31 kettenis 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 int	ttystats_init(void);
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)
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 			 * Set device hardware.
880 			 */
881 			if (tp->t_param && (error = (*tp->t_param)(tp, t))) {
882 				splx(s);
883 				return (error);
884 			} else {
885 				if (!ISSET(tp->t_state, TS_CARR_ON) &&
886 				    ISSET(tp->t_cflag, CLOCAL) &&
887 				    !ISSET(t->c_cflag, CLOCAL)) {
888 					CLR(tp->t_state, TS_ISOPEN);
889 					SET(tp->t_state, TS_WOPEN);
890 					ttwakeup(tp);
891 				}
892 				tp->t_cflag = t->c_cflag;
893 				tp->t_ispeed = t->c_ispeed;
894 				tp->t_ospeed = t->c_ospeed;
895 				if (t->c_ospeed == 0 && tp->t_session &&
896 				    tp->t_session->s_leader)
897 					psignal(tp->t_session->s_leader,
898 					    SIGHUP);
899 			}
900 			ttsetwater(tp);
901 		}
902 		if (cmd != TIOCSETAF) {
903 			if (ISSET(t->c_lflag, ICANON) !=
904 			    ISSET(tp->t_lflag, ICANON)) {
905 				if (ISSET(t->c_lflag, ICANON)) {
906 					SET(tp->t_lflag, PENDIN);
907 					ttwakeup(tp);
908 				} else {
909 					struct clist tq;
910 
911 					catq(&tp->t_rawq, &tp->t_canq);
912 					tq = tp->t_rawq;
913 					tp->t_rawq = tp->t_canq;
914 					tp->t_canq = tq;
915 					CLR(tp->t_lflag, PENDIN);
916 				}
917 			}
918 		}
919 		tp->t_iflag = t->c_iflag;
920 		tp->t_oflag = t->c_oflag;
921 		/*
922 		 * Make the EXTPROC bit read only.
923 		 */
924 		if (ISSET(tp->t_lflag, EXTPROC))
925 			SET(t->c_lflag, EXTPROC);
926 		else
927 			CLR(t->c_lflag, EXTPROC);
928 		tp->t_lflag = t->c_lflag | ISSET(tp->t_lflag, PENDIN);
929 		bcopy(t->c_cc, tp->t_cc, sizeof(t->c_cc));
930 		splx(s);
931 		break;
932 	}
933 	case TIOCSETD: {		/* set line discipline */
934 		int t = *(int *)data;
935 		dev_t device = tp->t_dev;
936 
937 		if ((u_int)t >= nlinesw)
938 			return (ENXIO);
939 		if (t != tp->t_line) {
940 			s = spltty();
941 			(*linesw[tp->t_line].l_close)(tp, flag);
942 			error = (*linesw[t].l_open)(device, tp);
943 			if (error) {
944 				(void)(*linesw[tp->t_line].l_open)(device, tp);
945 				splx(s);
946 				return (error);
947 			}
948 			tp->t_line = t;
949 			splx(s);
950 		}
951 		break;
952 	}
953 	case TIOCSTART:			/* start output, like ^Q */
954 		s = spltty();
955 		if (ISSET(tp->t_state, TS_TTSTOP) ||
956 		    ISSET(tp->t_lflag, FLUSHO)) {
957 			CLR(tp->t_lflag, FLUSHO);
958 			CLR(tp->t_state, TS_TTSTOP);
959 			ttstart(tp);
960 		}
961 		splx(s);
962 		break;
963 	case TIOCSTI:			/* simulate terminal input */
964 		if (p->p_ucred->cr_uid && (flag & FREAD) == 0)
965 			return (EPERM);
966 		if (p->p_ucred->cr_uid && !isctty(p, tp))
967 			return (EACCES);
968 		(*linesw[tp->t_line].l_rint)(*(u_char *)data, tp);
969 		break;
970 	case TIOCSTOP:			/* stop output, like ^S */
971 		s = spltty();
972 		if (!ISSET(tp->t_state, TS_TTSTOP)) {
973 			SET(tp->t_state, TS_TTSTOP);
974 			(*cdevsw[major(tp->t_dev)].d_stop)(tp, 0);
975 		}
976 		splx(s);
977 		break;
978 	case TIOCSCTTY:			/* become controlling tty */
979 		/* Session ctty vnode pointer set in vnode layer. */
980 		if (!SESS_LEADER(p) ||
981 		    ((p->p_session->s_ttyvp || tp->t_session) &&
982 		     (tp->t_session != p->p_session)))
983 			return (EPERM);
984 		if (tp->t_session)
985 			SESSRELE(tp->t_session);
986 		SESSHOLD(p->p_session);
987 		tp->t_session = p->p_session;
988 		tp->t_pgrp = p->p_pgrp;
989 		p->p_session->s_ttyp = tp;
990 		atomic_setbits_int(&p->p_flag, P_CONTROLT);
991 		break;
992 	case TIOCSPGRP: {		/* set pgrp of tty */
993 		struct pgrp *pgrp = pgfind(*(int *)data);
994 
995 		if (!isctty(p, tp))
996 			return (ENOTTY);
997 		else if (pgrp == NULL)
998 			return (EINVAL);
999 		else if (pgrp->pg_session != p->p_session)
1000 			return (EPERM);
1001 		tp->t_pgrp = pgrp;
1002 		break;
1003 	}
1004 	case TIOCSTAT:			/* get load avg stats */
1005 		ttyinfo(tp);
1006 		break;
1007 	case TIOCSWINSZ:		/* set window size */
1008 		if (bcmp((caddr_t)&tp->t_winsize, data,
1009 		    sizeof (struct winsize))) {
1010 			tp->t_winsize = *(struct winsize *)data;
1011 			pgsignal(tp->t_pgrp, SIGWINCH, 1);
1012 		}
1013 		break;
1014 	case TIOCSTSTAMP: {
1015 		struct tstamps *ts = (struct tstamps *)data;
1016 
1017 		s = spltty();
1018 		CLR(tp->t_flags, TS_TSTAMPDCDSET);
1019 		CLR(tp->t_flags, TS_TSTAMPCTSSET);
1020 		CLR(tp->t_flags, TS_TSTAMPDCDCLR);
1021 		CLR(tp->t_flags, TS_TSTAMPCTSCLR);
1022 		if (ISSET(ts->ts_set, TIOCM_CAR))
1023 			SET(tp->t_flags, TS_TSTAMPDCDSET);
1024 		if (ISSET(ts->ts_set, TIOCM_CTS))
1025 			SET(tp->t_flags, TS_TSTAMPCTSSET);
1026 		if (ISSET(ts->ts_clr, TIOCM_CAR))
1027 			SET(tp->t_flags, TS_TSTAMPDCDCLR);
1028 		if (ISSET(ts->ts_clr, TIOCM_CTS))
1029 			SET(tp->t_flags, TS_TSTAMPCTSCLR);
1030 		splx(s);
1031 		break;
1032 	}
1033 	default:
1034 #ifdef COMPAT_OLDTTY
1035 		return (ttcompat(tp, cmd, data, flag, p));
1036 #else
1037 		return (-1);
1038 #endif
1039 	}
1040 	return (0);
1041 }
1042 
1043 int
1044 ttpoll(dev_t device, int events, struct proc *p)
1045 {
1046 	struct tty *tp;
1047 	int revents, s;
1048 
1049 	tp = (*cdevsw[major(device)].d_tty)(device);
1050 
1051 	revents = 0;
1052 	s = spltty();
1053 	if (events & (POLLIN | POLLRDNORM)) {
1054 		if (ttnread(tp) > 0 || (!ISSET(tp->t_cflag, CLOCAL) &&
1055 		    !ISSET(tp->t_state, TS_CARR_ON)))
1056 			revents |= events & (POLLIN | POLLRDNORM);
1057 	}
1058 	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 (1);
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 filt_ttyrdetach(struct knote *kn)
1108 {
1109 	dev_t dev = (dev_t)((u_long)kn->kn_hook);
1110 	struct tty *tp = (*cdevsw[major(dev)].d_tty)(dev);
1111 	int s = spltty();
1112 
1113 	SLIST_REMOVE(&tp->t_rsel.si_note, kn, knote, kn_selnext);
1114 	splx(s);
1115 }
1116 
1117 int
1118 filt_ttyread(struct knote *kn, long hint)
1119 {
1120 	dev_t dev = (dev_t)((u_long)kn->kn_hook);
1121 	struct tty *tp = (*cdevsw[major(dev)].d_tty)(dev);
1122 	int s;
1123 
1124 	s = spltty();
1125 	kn->kn_data = ttnread(tp);
1126 	splx(s);
1127 	if (!ISSET(tp->t_cflag, CLOCAL) && !ISSET(tp->t_state, TS_CARR_ON)) {
1128 		kn->kn_flags |= EV_EOF;
1129 		return (1);
1130 	}
1131 	return (kn->kn_data > 0);
1132 }
1133 
1134 void
1135 filt_ttywdetach(struct knote *kn)
1136 {
1137 	dev_t dev = (dev_t)((u_long)kn->kn_hook);
1138 	struct tty *tp = (*cdevsw[major(dev)].d_tty)(dev);
1139 	int s = spltty();
1140 
1141 	SLIST_REMOVE(&tp->t_wsel.si_note, kn, knote, kn_selnext);
1142 	splx(s);
1143 }
1144 
1145 int
1146 filt_ttywrite(struct knote *kn, long hint)
1147 {
1148 	dev_t dev = (dev_t)((u_long)kn->kn_hook);
1149 	struct tty *tp = (*cdevsw[major(dev)].d_tty)(dev);
1150 	int canwrite, s;
1151 
1152 	s = spltty();
1153 	kn->kn_data = tp->t_outq.c_cn - tp->t_outq.c_cc;
1154 	canwrite = (tp->t_outq.c_cc <= tp->t_lowat);
1155 	splx(s);
1156 	return (canwrite);
1157 }
1158 
1159 static int
1160 ttnread(struct tty *tp)
1161 {
1162 	int nread;
1163 
1164 	splassert(IPL_TTY);
1165 
1166 	if (ISSET(tp->t_lflag, PENDIN))
1167 		ttypend(tp);
1168 	nread = tp->t_canq.c_cc;
1169 	if (!ISSET(tp->t_lflag, ICANON)) {
1170 		nread += tp->t_rawq.c_cc;
1171 		if (nread < tp->t_cc[VMIN] && !tp->t_cc[VTIME])
1172 			nread = 0;
1173 	}
1174 	return (nread);
1175 }
1176 
1177 /*
1178  * Wait for output to drain.
1179  */
1180 int
1181 ttywait(struct tty *tp)
1182 {
1183 	int error, s;
1184 
1185 	error = 0;
1186 	s = spltty();
1187 	while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1188 	    (ISSET(tp->t_state, TS_CARR_ON) || ISSET(tp->t_cflag, CLOCAL)) &&
1189 	    tp->t_oproc) {
1190 		(*tp->t_oproc)(tp);
1191 		if ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1192 		    (ISSET(tp->t_state, TS_CARR_ON) || ISSET(tp->t_cflag, CLOCAL))
1193 		    && tp->t_oproc) {
1194 			SET(tp->t_state, TS_ASLEEP);
1195 			error = ttysleep(tp, &tp->t_outq, TTOPRI | PCATCH, ttyout, 0);
1196 			if (error)
1197 				break;
1198 		} else
1199 			break;
1200 	}
1201 	splx(s);
1202 	return (error);
1203 }
1204 
1205 /*
1206  * Flush if successfully wait.
1207  */
1208 int
1209 ttywflush(struct tty *tp)
1210 {
1211 	int error;
1212 
1213 	if ((error = ttywait(tp)) == 0)
1214 		ttyflush(tp, FREAD);
1215 	return (error);
1216 }
1217 
1218 /*
1219  * Flush tty read and/or write queues, notifying anyone waiting.
1220  */
1221 void
1222 ttyflush(struct tty *tp, int rw)
1223 {
1224 	int s;
1225 
1226 	s = spltty();
1227 	if (rw & FREAD) {
1228 		FLUSHQ(&tp->t_canq);
1229 		FLUSHQ(&tp->t_rawq);
1230 		tp->t_rocount = 0;
1231 		tp->t_rocol = 0;
1232 		CLR(tp->t_state, TS_LOCAL);
1233 		ttyunblock(tp);
1234 		ttwakeup(tp);
1235 	}
1236 	if (rw & FWRITE) {
1237 		CLR(tp->t_state, TS_TTSTOP);
1238 		(*cdevsw[major(tp->t_dev)].d_stop)(tp, rw);
1239 		FLUSHQ(&tp->t_outq);
1240 		wakeup((caddr_t)&tp->t_outq);
1241 		selwakeup(&tp->t_wsel);
1242 	}
1243 	splx(s);
1244 }
1245 
1246 /*
1247  * Copy in the default termios characters.
1248  */
1249 void
1250 ttychars(struct tty *tp)
1251 {
1252 
1253 	bcopy(ttydefchars, tp->t_cc, sizeof(ttydefchars));
1254 }
1255 
1256 /*
1257  * Send stop character on input overflow.
1258  */
1259 static void
1260 ttyblock(struct tty *tp)
1261 {
1262 	int total;
1263 
1264 	total = tp->t_rawq.c_cc + tp->t_canq.c_cc;
1265 	if (tp->t_rawq.c_cc > TTYHOG) {
1266 		ttyflush(tp, FREAD | FWRITE);
1267 		CLR(tp->t_state, TS_TBLOCK);
1268 	}
1269 	/*
1270 	 * Block further input iff: current input > threshold
1271 	 * AND input is available to user program.
1272 	 */
1273 	if ((total >= TTYHOG / 2 &&
1274 	     !ISSET(tp->t_state, TS_TBLOCK) &&
1275 	     !ISSET(tp->t_lflag, ICANON)) || tp->t_canq.c_cc > 0) {
1276 		if (ISSET(tp->t_iflag, IXOFF) &&
1277 		    tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
1278 		    putc(tp->t_cc[VSTOP], &tp->t_outq) == 0) {
1279 			SET(tp->t_state, TS_TBLOCK);
1280 			ttstart(tp);
1281 		}
1282 		/* Try to block remote output via hardware flow control. */
1283 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
1284 		    (*tp->t_hwiflow)(tp, 1) != 0)
1285 			SET(tp->t_state, TS_TBLOCK);
1286 	}
1287 }
1288 
1289 void
1290 ttrstrt(void *tp_arg)
1291 {
1292 	struct tty *tp;
1293 	int s;
1294 
1295 #ifdef DIAGNOSTIC
1296 	if (tp_arg == NULL)
1297 		panic("ttrstrt");
1298 #endif
1299 	tp = tp_arg;
1300 	s = spltty();
1301 
1302 	CLR(tp->t_state, TS_TIMEOUT);
1303 	ttstart(tp);
1304 
1305 	splx(s);
1306 }
1307 
1308 int
1309 ttstart(struct tty *tp)
1310 {
1311 
1312 	if (tp->t_oproc != NULL)	/* XXX: Kludge for pty. */
1313 		(*tp->t_oproc)(tp);
1314 	return (0);
1315 }
1316 
1317 /*
1318  * "close" a line discipline
1319  */
1320 int
1321 ttylclose(struct tty *tp, int flag)
1322 {
1323 
1324 	if (flag & FNONBLOCK)
1325 		ttyflush(tp, FREAD | FWRITE);
1326 	else
1327 		ttywflush(tp);
1328 	return (0);
1329 }
1330 
1331 /*
1332  * Handle modem control transition on a tty.
1333  * Flag indicates new state of carrier.
1334  * Returns 0 if the line should be turned off, otherwise 1.
1335  */
1336 int
1337 ttymodem(struct tty *tp, int flag)
1338 {
1339 
1340 	if (!ISSET(tp->t_state, TS_WOPEN) && ISSET(tp->t_cflag, MDMBUF)) {
1341 		/*
1342 		 * MDMBUF: do flow control according to carrier flag
1343 		 */
1344 		if (flag) {
1345 			CLR(tp->t_state, TS_TTSTOP);
1346 			ttstart(tp);
1347 		} else if (!ISSET(tp->t_state, TS_TTSTOP)) {
1348 			SET(tp->t_state, TS_TTSTOP);
1349 			(*cdevsw[major(tp->t_dev)].d_stop)(tp, 0);
1350 		}
1351 	} else if (flag == 0) {
1352 		/*
1353 		 * Lost carrier.
1354 		 */
1355 		CLR(tp->t_state, TS_CARR_ON);
1356 		if (ISSET(tp->t_state, TS_ISOPEN) &&
1357 		    !ISSET(tp->t_cflag, CLOCAL)) {
1358 			if (tp->t_session && tp->t_session->s_leader)
1359 				psignal(tp->t_session->s_leader, SIGHUP);
1360 			ttyflush(tp, FREAD | FWRITE);
1361 			return (0);
1362 		}
1363 	} else {
1364 		/*
1365 		 * Carrier now on.
1366 		 */
1367 		SET(tp->t_state, TS_CARR_ON);
1368 		ttwakeup(tp);
1369 	}
1370 	return (1);
1371 }
1372 
1373 /*
1374  * Default modem control routine (for other line disciplines).
1375  * Return argument flag, to turn off device on carrier drop.
1376  */
1377 int
1378 nullmodem(struct tty *tp, int flag)
1379 {
1380 
1381 	if (flag)
1382 		SET(tp->t_state, TS_CARR_ON);
1383 	else {
1384 		CLR(tp->t_state, TS_CARR_ON);
1385 		if (ISSET(tp->t_state, TS_ISOPEN) &&
1386 		    !ISSET(tp->t_cflag, CLOCAL)) {
1387 			if (tp->t_session && tp->t_session->s_leader)
1388 				psignal(tp->t_session->s_leader, SIGHUP);
1389 			ttyflush(tp, FREAD | FWRITE);
1390 			return (0);
1391 		}
1392 	}
1393 	return (1);
1394 }
1395 
1396 /*
1397  * Reinput pending characters after state switch
1398  * call at spltty().
1399  */
1400 void
1401 ttypend(struct tty *tp)
1402 {
1403 	struct clist tq;
1404 	int c;
1405 
1406 	splassert(IPL_TTY);
1407 
1408 	CLR(tp->t_lflag, PENDIN);
1409 	SET(tp->t_state, TS_TYPEN);
1410 	tq = tp->t_rawq;
1411 	tp->t_rawq.c_cc = 0;
1412 	tp->t_rawq.c_cf = tp->t_rawq.c_cl = 0;
1413 	while ((c = getc(&tq)) >= 0)
1414 		ttyinput(c, tp);
1415 	CLR(tp->t_state, TS_TYPEN);
1416 }
1417 
1418 void ttvtimeout(void *);
1419 
1420 void
1421 ttvtimeout(void *arg)
1422 {
1423 	struct tty *tp = (struct tty *)arg;
1424 
1425 	wakeup(&tp->t_rawq);
1426 }
1427 
1428 /*
1429  * Process a read call on a tty device.
1430  */
1431 int
1432 ttread(struct tty *tp, struct uio *uio, int flag)
1433 {
1434 	struct timeout *stime = NULL;
1435 	struct proc *p = curproc;
1436 	int s, first, error = 0;
1437 	u_char *cc = tp->t_cc;
1438 	struct clist *qp;
1439 	int last_cc = 0;
1440 	long lflag;
1441 	int c;
1442 
1443 loop:	lflag = tp->t_lflag;
1444 	s = spltty();
1445 	/*
1446 	 * take pending input first
1447 	 */
1448 	if (ISSET(lflag, PENDIN))
1449 		ttypend(tp);
1450 	splx(s);
1451 
1452 	/*
1453 	 * Hang process if it's in the background.
1454 	 */
1455 	if (isbackground(p, tp)) {
1456 		if ((p->p_sigignore & sigmask(SIGTTIN)) ||
1457 		   (p->p_sigmask & sigmask(SIGTTIN)) ||
1458 		    p->p_flag & P_PPWAIT || p->p_pgrp->pg_jobc == 0) {
1459 			error = EIO;
1460 			goto out;
1461 		}
1462 		pgsignal(p->p_pgrp, SIGTTIN, 1);
1463 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, ttybg, 0);
1464 		if (error)
1465 			goto out;
1466 		goto loop;
1467 	}
1468 
1469 	s = spltty();
1470 	if (!ISSET(lflag, ICANON)) {
1471 		int m = cc[VMIN];
1472 		long t;
1473 
1474 		/*
1475 		 * Note - since cc[VTIME] is a u_char, this won't overflow
1476 		 * until we have 32-bit longs and a hz > 8388608.
1477 		 * Hopefully this code and 32-bit longs are obsolete by then.
1478 		 */
1479 		t = cc[VTIME] * hz / 10;
1480 
1481 		qp = &tp->t_rawq;
1482 		/*
1483 		 * Check each of the four combinations.
1484 		 * (m > 0 && t == 0) is the normal read case.
1485 		 * It should be fairly efficient, so we check that and its
1486 		 * companion case (m == 0 && t == 0) first.
1487 		 */
1488 		if (t == 0) {
1489 			if (qp->c_cc < m)
1490 				goto sleep;
1491 			goto read;
1492 		}
1493 		if (m > 0) {
1494 			if (qp->c_cc <= 0)
1495 				goto sleep;
1496 			if (qp->c_cc >= m)
1497 				goto read;
1498 			if (stime == NULL) {
1499 alloc_timer:
1500 				stime = malloc(sizeof(*stime), M_TEMP, M_WAITOK);
1501 				timeout_set(stime, ttvtimeout, tp);
1502 				timeout_add(stime, t);
1503 			} else if (qp->c_cc > last_cc) {
1504 				/* got a character, restart timer */
1505 				timeout_add(stime, t);
1506 			}
1507 		} else {	/* m == 0 */
1508 			if (qp->c_cc > 0)
1509 				goto read;
1510 			if (stime == NULL) {
1511 				goto alloc_timer;
1512 			}
1513 		}
1514 		last_cc = qp->c_cc;
1515 		if (stime && !timeout_triggered(stime)) {
1516 			goto sleep;
1517 		}
1518 	} else if ((qp = &tp->t_canq)->c_cc <= 0) {
1519 		int carrier;
1520 
1521 sleep:
1522 		/*
1523 		 * If there is no input, sleep on rawq
1524 		 * awaiting hardware receipt and notification.
1525 		 * If we have data, we don't need to check for carrier.
1526 		 */
1527 		carrier = ISSET(tp->t_state, TS_CARR_ON) ||
1528 		    ISSET(tp->t_cflag, CLOCAL);
1529 		if (!carrier && ISSET(tp->t_state, TS_ISOPEN)) {
1530 			splx(s);
1531 			error = 0;
1532 			goto out;
1533 		}
1534 		if (flag & IO_NDELAY) {
1535 			splx(s);
1536 			error = EWOULDBLOCK;
1537 			goto out;
1538 		}
1539 		error = ttysleep(tp, &tp->t_rawq, TTIPRI | PCATCH,
1540 		    carrier ? ttyin : ttopen, 0);
1541 		splx(s);
1542 		if (stime && timeout_triggered(stime))
1543 			error = EWOULDBLOCK;
1544 		if (cc[VMIN] == 0 && error == EWOULDBLOCK) {
1545 			error = 0;
1546 			goto out;
1547 		}
1548 		if (error && error != EWOULDBLOCK)
1549 			goto out;
1550 		error = 0;
1551 		goto loop;
1552 	}
1553 read:
1554 	splx(s);
1555 
1556 	/*
1557 	 * Input present, check for input mapping and processing.
1558 	 */
1559 	first = 1;
1560 	while ((c = getc(qp)) >= 0) {
1561 		/*
1562 		 * delayed suspend (^Y)
1563 		 */
1564 		if (CCEQ(cc[VDSUSP], c) &&
1565 		    ISSET(lflag, IEXTEN | ISIG) == (IEXTEN | ISIG)) {
1566 			pgsignal(tp->t_pgrp, SIGTSTP, 1);
1567 			if (first) {
1568 				error = ttysleep(tp, &lbolt, TTIPRI | PCATCH,
1569 				    ttybg, 0);
1570 				if (error)
1571 					break;
1572 				goto loop;
1573 			}
1574 			break;
1575 		}
1576 		/*
1577 		 * Interpret EOF only in canonical mode.
1578 		 */
1579 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
1580 			break;
1581 		/*
1582 		 * Give user character.
1583 		 */
1584  		error = ureadc(c, uio);
1585 		if (error)
1586 			break;
1587  		if (uio->uio_resid == 0)
1588 			break;
1589 		/*
1590 		 * In canonical mode check for a "break character"
1591 		 * marking the end of a "line of input".
1592 		 */
1593 		if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
1594 			break;
1595 		first = 0;
1596 	}
1597 	/*
1598 	 * Look to unblock output now that (presumably)
1599 	 * the input queue has gone down.
1600 	 */
1601 	s = spltty();
1602 	if (tp->t_rawq.c_cc < TTYHOG/5)
1603 		ttyunblock(tp);
1604 	splx(s);
1605 
1606 out:
1607 	if (stime) {
1608 		timeout_del(stime);
1609 		free(stime, M_TEMP);
1610 	}
1611 	return (error);
1612 }
1613 
1614 /* Call at spltty */
1615 void
1616 ttyunblock(struct tty *tp)
1617 {
1618 	u_char *cc = tp->t_cc;
1619 
1620 	splassert(IPL_TTY);
1621 
1622 	if (ISSET(tp->t_state, TS_TBLOCK)) {
1623 		if (ISSET(tp->t_iflag, IXOFF) &&
1624 		    cc[VSTART] != _POSIX_VDISABLE &&
1625 		    putc(cc[VSTART], &tp->t_outq) == 0) {
1626 			CLR(tp->t_state, TS_TBLOCK);
1627 			ttstart(tp);
1628 		}
1629 		/* Try to unblock remote output via hardware flow control. */
1630 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
1631 		    (*tp->t_hwiflow)(tp, 0) != 0)
1632 			CLR(tp->t_state, TS_TBLOCK);
1633 	}
1634 }
1635 
1636 /*
1637  * Check the output queue on tp for space for a kernel message (from uprintf
1638  * or tprintf).  Allow some space over the normal hiwater mark so we don't
1639  * lose messages due to normal flow control, but don't let the tty run amok.
1640  * Sleeps here are not interruptible, but we return prematurely if new signals
1641  * arrive.
1642  */
1643 int
1644 ttycheckoutq(struct tty *tp, int wait)
1645 {
1646 	int hiwat, s, oldsig;
1647 
1648 	hiwat = tp->t_hiwat;
1649 	s = spltty();
1650 	oldsig = wait ? curproc->p_siglist : 0;
1651 	if (tp->t_outq.c_cc > hiwat + 200)
1652 		while (tp->t_outq.c_cc > hiwat) {
1653 			ttstart(tp);
1654 			if (wait == 0 || curproc->p_siglist != oldsig) {
1655 				splx(s);
1656 				return (0);
1657 			}
1658 			SET(tp->t_state, TS_ASLEEP);
1659 			tsleep(&tp->t_outq, PZERO - 1, "ttckoutq", hz);
1660 		}
1661 	splx(s);
1662 	return (1);
1663 }
1664 
1665 /*
1666  * Process a write call on a tty device.
1667  */
1668 int
1669 ttwrite(struct tty *tp, struct uio *uio, int flag)
1670 {
1671 	u_char *cp = NULL;
1672 	int cc, ce, obufcc = 0;
1673 	struct proc *p;
1674 	int i, hiwat, error, s;
1675 	size_t cnt;
1676 	u_char obuf[OBUFSIZ];
1677 
1678 	hiwat = tp->t_hiwat;
1679 	cnt = uio->uio_resid;
1680 	error = 0;
1681 	cc = 0;
1682 loop:
1683 	s = spltty();
1684 	if (!ISSET(tp->t_state, TS_CARR_ON) &&
1685 	    !ISSET(tp->t_cflag, CLOCAL)) {
1686 		if (ISSET(tp->t_state, TS_ISOPEN)) {
1687 			splx(s);
1688 			error = EIO;
1689 			goto done;
1690 		} else if (flag & IO_NDELAY) {
1691 			splx(s);
1692 			error = EWOULDBLOCK;
1693 			goto out;
1694 		} else {
1695 			/* Sleep awaiting carrier. */
1696 			error = ttysleep(tp,
1697 			    &tp->t_rawq, TTIPRI | PCATCH, ttopen, 0);
1698 			splx(s);
1699 			if (error)
1700 				goto out;
1701 			goto loop;
1702 		}
1703 	}
1704 	splx(s);
1705 	/*
1706 	 * Hang the process if it's in the background.
1707 	 */
1708 	p = curproc;
1709 	if (isbackground(p, tp) &&
1710 	    ISSET(tp->t_lflag, TOSTOP) && (p->p_flag & P_PPWAIT) == 0 &&
1711 	    (p->p_sigignore & sigmask(SIGTTOU)) == 0 &&
1712 	    (p->p_sigmask & sigmask(SIGTTOU)) == 0) {
1713 		if (p->p_pgrp->pg_jobc == 0) {
1714 			error = EIO;
1715 			goto out;
1716 		}
1717 		pgsignal(p->p_pgrp, SIGTTOU, 1);
1718 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, ttybg, 0);
1719 		if (error)
1720 			goto out;
1721 		goto loop;
1722 	}
1723 	/*
1724 	 * Process the user's data in at most OBUFSIZ chunks.  Perform any
1725 	 * output translation.  Keep track of high water mark, sleep on
1726 	 * overflow awaiting device aid in acquiring new space.
1727 	 */
1728 	while (uio->uio_resid > 0 || cc > 0) {
1729 		if (ISSET(tp->t_lflag, FLUSHO)) {
1730 			uio->uio_resid = 0;
1731 			goto done;
1732 		}
1733 		if (tp->t_outq.c_cc > hiwat)
1734 			goto ovhiwat;
1735 		/*
1736 		 * Grab a hunk of data from the user, unless we have some
1737 		 * leftover from last time.
1738 		 */
1739 		if (cc == 0) {
1740 			cc = MIN(uio->uio_resid, OBUFSIZ);
1741 			cp = obuf;
1742 			error = uiomove(cp, cc, uio);
1743 			if (error) {
1744 				cc = 0;
1745 				break;
1746 			}
1747 			if (cc > obufcc)
1748 				obufcc = cc;
1749 		}
1750 		/*
1751 		 * If nothing fancy need be done, grab those characters we
1752 		 * can handle without any of ttyoutput's processing and
1753 		 * just transfer them to the output q.  For those chars
1754 		 * which require special processing (as indicated by the
1755 		 * bits in char_type), call ttyoutput.  After processing
1756 		 * a hunk of data, look for FLUSHO so ^O's will take effect
1757 		 * immediately.
1758 		 */
1759 		while (cc > 0) {
1760 			if (!ISSET(tp->t_oflag, OPOST))
1761 				ce = cc;
1762 			else {
1763 				ce = cc - scanc((u_int)cc, cp, char_type,
1764 				    CCLASSMASK);
1765 				/*
1766 				 * If ce is zero, then we're processing
1767 				 * a special character through ttyoutput.
1768 				 */
1769 				if (ce == 0) {
1770 					tp->t_rocount = 0;
1771 					if (ttyoutput(*cp, tp) >= 0) {
1772 						/* out of space */
1773 						goto overfull;
1774 					}
1775 					cp++;
1776 					cc--;
1777 					if (ISSET(tp->t_lflag, FLUSHO) ||
1778 					    tp->t_outq.c_cc > hiwat)
1779 						goto ovhiwat;
1780 					continue;
1781 				}
1782 			}
1783 			/*
1784 			 * A bunch of normal characters have been found.
1785 			 * Transfer them en masse to the output queue and
1786 			 * continue processing at the top of the loop.
1787 			 * If there are any further characters in this
1788 			 * <= OBUFSIZ chunk, the first should be a character
1789 			 * requiring special handling by ttyoutput.
1790 			 */
1791 			tp->t_rocount = 0;
1792 			i = b_to_q(cp, ce, &tp->t_outq);
1793 			ce -= i;
1794 			tp->t_column += ce;
1795 			cp += ce, cc -= ce, tk_nout += ce;
1796 			tp->t_outcc += ce;
1797 			if (i > 0) {
1798 				/* out of space */
1799 				goto overfull;
1800 			}
1801 			if (ISSET(tp->t_lflag, FLUSHO) ||
1802 			    tp->t_outq.c_cc > hiwat)
1803 				break;
1804 		}
1805 		ttstart(tp);
1806 	}
1807 out:
1808 	/*
1809 	 * If cc is nonzero, we leave the uio structure inconsistent, as the
1810 	 * offset and iov pointers have moved forward, but it doesn't matter
1811 	 * (the call will either return short or restart with a new uio).
1812 	 */
1813 	uio->uio_resid += cc;
1814 done:
1815 	if (obufcc)
1816 		bzero(obuf, obufcc);
1817 	return (error);
1818 
1819 overfull:
1820 	/*
1821 	 * Since we are using ring buffers, if we can't insert any more into
1822 	 * the output queue, we can assume the ring is full and that someone
1823 	 * forgot to set the high water mark correctly.  We set it and then
1824 	 * proceed as normal.
1825 	 */
1826 	hiwat = tp->t_outq.c_cc - 1;
1827 
1828 ovhiwat:
1829 	ttstart(tp);
1830 	s = spltty();
1831 	/*
1832 	 * This can only occur if FLUSHO is set in t_lflag,
1833 	 * or if ttstart/oproc is synchronous (or very fast).
1834 	 */
1835 	if (tp->t_outq.c_cc <= hiwat) {
1836 		splx(s);
1837 		goto loop;
1838 	}
1839 	if (flag & IO_NDELAY) {
1840 		splx(s);
1841 		uio->uio_resid += cc;
1842 		if (obufcc)
1843 			bzero(obuf, obufcc);
1844 		return (uio->uio_resid == cnt ? EWOULDBLOCK : 0);
1845 	}
1846 	SET(tp->t_state, TS_ASLEEP);
1847 	error = ttysleep(tp, &tp->t_outq, TTOPRI | PCATCH, ttyout, 0);
1848 	splx(s);
1849 	if (error)
1850 		goto out;
1851 	goto loop;
1852 }
1853 
1854 /*
1855  * Rubout one character from the rawq of tp
1856  * as cleanly as possible.
1857  */
1858 void
1859 ttyrub(int c, struct tty *tp)
1860 {
1861 	u_char *cp;
1862 	int savecol;
1863 	int tabc, s;
1864 
1865 	if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
1866 		return;
1867 	CLR(tp->t_lflag, FLUSHO);
1868 	if (ISSET(tp->t_lflag, ECHOE)) {
1869 		if (tp->t_rocount == 0) {
1870 			/*
1871 			 * Screwed by ttwrite; retype
1872 			 */
1873 			ttyretype(tp);
1874 			return;
1875 		}
1876 		if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
1877 			ttyrubo(tp, 2);
1878 		else {
1879 			CLR(c, ~TTY_CHARMASK);
1880 			switch (CCLASS(c)) {
1881 			case ORDINARY:
1882 				ttyrubo(tp, 1);
1883 				break;
1884 			case BACKSPACE:
1885 			case CONTROL:
1886 			case NEWLINE:
1887 			case RETURN:
1888 			case VTAB:
1889 				if (ISSET(tp->t_lflag, ECHOCTL))
1890 					ttyrubo(tp, 2);
1891 				break;
1892 			case TAB:
1893 				if (tp->t_rocount < tp->t_rawq.c_cc) {
1894 					ttyretype(tp);
1895 					return;
1896 				}
1897 				s = spltty();
1898 				savecol = tp->t_column;
1899 				SET(tp->t_state, TS_CNTTB);
1900 				SET(tp->t_lflag, FLUSHO);
1901 				tp->t_column = tp->t_rocol;
1902 				for (cp = firstc(&tp->t_rawq, &tabc); cp;
1903 				    cp = nextc(&tp->t_rawq, cp, &tabc))
1904 					ttyecho(tabc, tp);
1905 				CLR(tp->t_lflag, FLUSHO);
1906 				CLR(tp->t_state, TS_CNTTB);
1907 				splx(s);
1908 
1909 				/* savecol will now be length of the tab. */
1910 				savecol -= tp->t_column;
1911 				tp->t_column += savecol;
1912 				if (savecol > 8)
1913 					savecol = 8;	/* overflow screw */
1914 				while (--savecol >= 0)
1915 					(void)ttyoutput('\b', tp);
1916 				break;
1917 			default:			/* XXX */
1918 #define	PANICSTR	"ttyrub: would panic c = %d, val = %d\n"
1919 				(void)printf(PANICSTR, c, CCLASS(c));
1920 #ifdef notdef
1921 				panic(PANICSTR, c, CCLASS(c));
1922 #endif
1923 			}
1924 		}
1925 	} else if (ISSET(tp->t_lflag, ECHOPRT)) {
1926 		if (!ISSET(tp->t_state, TS_ERASE)) {
1927 			SET(tp->t_state, TS_ERASE);
1928 			(void)ttyoutput('\\', tp);
1929 		}
1930 		ttyecho(c, tp);
1931 	} else
1932 		ttyecho(tp->t_cc[VERASE], tp);
1933 	--tp->t_rocount;
1934 }
1935 
1936 /*
1937  * Back over cnt characters, erasing them.
1938  */
1939 static void
1940 ttyrubo(struct tty *tp, int cnt)
1941 {
1942 
1943 	while (cnt-- > 0) {
1944 		(void)ttyoutput('\b', tp);
1945 		(void)ttyoutput(' ', tp);
1946 		(void)ttyoutput('\b', tp);
1947 	}
1948 }
1949 
1950 /*
1951  * ttyretype --
1952  *	Reprint the rawq line.  Note, it is assumed that c_cc has already
1953  *	been checked.
1954  */
1955 void
1956 ttyretype(struct tty *tp)
1957 {
1958 	u_char *cp;
1959 	int s, c;
1960 
1961 	/* Echo the reprint character. */
1962 	if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
1963 		ttyecho(tp->t_cc[VREPRINT], tp);
1964 
1965 	(void)ttyoutput('\n', tp);
1966 
1967 	s = spltty();
1968 	for (cp = firstc(&tp->t_canq, &c); cp; cp = nextc(&tp->t_canq, cp, &c))
1969 		ttyecho(c, tp);
1970 	for (cp = firstc(&tp->t_rawq, &c); cp; cp = nextc(&tp->t_rawq, cp, &c))
1971 		ttyecho(c, tp);
1972 	CLR(tp->t_state, TS_ERASE);
1973 	splx(s);
1974 
1975 	tp->t_rocount = tp->t_rawq.c_cc;
1976 	tp->t_rocol = 0;
1977 }
1978 
1979 /*
1980  * Echo a typed character to the terminal.
1981  */
1982 static void
1983 ttyecho(int c, struct tty *tp)
1984 {
1985 
1986 	if (!ISSET(tp->t_state, TS_CNTTB))
1987 		CLR(tp->t_lflag, FLUSHO);
1988 	if ((!ISSET(tp->t_lflag, ECHO) &&
1989 	    (!ISSET(tp->t_lflag, ECHONL) || c != '\n')) ||
1990 	    ISSET(tp->t_lflag, EXTPROC))
1991 		return;
1992 	if (((ISSET(tp->t_lflag, ECHOCTL) &&
1993 	     (ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n')) ||
1994 	    ISSET(c, TTY_CHARMASK) == 0177)) {
1995 		(void)ttyoutput('^', tp);
1996 		CLR(c, ~TTY_CHARMASK);
1997 		if (c == 0177)
1998 			c = '?';
1999 		else
2000 			c += 'A' - 1;
2001 	}
2002 	(void)ttyoutput(c, tp);
2003 }
2004 
2005 /*
2006  * Wake up any readers on a tty.
2007  */
2008 void
2009 ttwakeup(struct tty *tp)
2010 {
2011 
2012 	selwakeup(&tp->t_rsel);
2013 	if (ISSET(tp->t_state, TS_ASYNC))
2014 		pgsignal(tp->t_pgrp, SIGIO, 1);
2015 	wakeup((caddr_t)&tp->t_rawq);
2016 	KNOTE(&tp->t_rsel.si_note, 0);
2017 }
2018 
2019 /*
2020  * Look up a code for a specified speed in a conversion table;
2021  * used by drivers to map software speed values to hardware parameters.
2022  */
2023 int
2024 ttspeedtab(int speed, const struct speedtab *table)
2025 {
2026 
2027 	for ( ; table->sp_speed != -1; table++)
2028 		if (table->sp_speed == speed)
2029 			return (table->sp_code);
2030 	return (-1);
2031 }
2032 
2033 /*
2034  * Set tty hi and low water marks.
2035  *
2036  * Try to arrange the dynamics so there's about one second
2037  * from hi to low water.
2038  */
2039 void
2040 ttsetwater(struct tty *tp)
2041 {
2042 	int cps, x;
2043 
2044 #define CLAMP(x, h, l)	((x) > h ? h : ((x) < l) ? l : (x))
2045 
2046 	cps = tp->t_ospeed / 10;
2047 	tp->t_lowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
2048 	x += cps;
2049 	x = CLAMP(x, TTMAXHIWAT, TTMINHIWAT);
2050 	tp->t_hiwat = roundup(x, CBSIZE);
2051 #undef	CLAMP
2052 }
2053 
2054 /*
2055  * Report on state of foreground process group.
2056  */
2057 void
2058 ttyinfo(struct tty *tp)
2059 {
2060 	struct proc *p, *pick;
2061 	struct timeval utime, stime;
2062 	int tmp;
2063 
2064 	if (ttycheckoutq(tp,0) == 0)
2065 		return;
2066 
2067 	/* Print load average. */
2068 	tmp = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
2069 	ttyprintf(tp, "load: %d.%02d ", tmp / 100, tmp % 100);
2070 
2071 	if (tp->t_session == NULL)
2072 		ttyprintf(tp, "not a controlling terminal\n");
2073 	else if (tp->t_pgrp == NULL)
2074 		ttyprintf(tp, "no foreground process group\n");
2075 	else if ((p = LIST_FIRST(&tp->t_pgrp->pg_members)) == NULL)
2076 		ttyprintf(tp, "empty foreground process group\n");
2077 	else {
2078 		int pctcpu;
2079 		long rss;
2080 
2081 		/* Pick interesting process. */
2082 		for (pick = NULL; p != 0; p = LIST_NEXT(p, p_pglist))
2083 			if (proc_compare(pick, p))
2084 				pick = p;
2085 
2086 		/* Calculate percentage cpu, resident set size. */
2087 		pctcpu = (pick->p_pctcpu * 10000 + FSCALE / 2) >> FSHIFT;
2088 		rss = pick->p_stat == SIDL || P_ZOMBIE(pick) ? 0 :
2089 		    vm_resident_count(pick->p_vmspace);
2090 
2091 		calcru(pick, &utime, &stime, NULL);
2092 
2093 		/* Round up and print user time. */
2094 		utime.tv_usec += 5000;
2095 		if (utime.tv_usec >= 1000000) {
2096 			utime.tv_sec += 1;
2097 			utime.tv_usec -= 1000000;
2098 		}
2099 
2100 		/* Round up and print system time. */
2101 		stime.tv_usec += 5000;
2102 		if (stime.tv_usec >= 1000000) {
2103 			stime.tv_sec += 1;
2104 			stime.tv_usec -= 1000000;
2105 		}
2106 
2107 		ttyprintf(tp,
2108 		    " cmd: %s %d [%s] %ld.%02ldu %ld.%02lds %d%% %ldk\n",
2109 		    pick->p_comm, pick->p_pid,
2110 		    pick->p_stat == SONPROC ? "running" :
2111 		    pick->p_stat == SRUN ? "runnable" :
2112 		    pick->p_wmesg ? pick->p_wmesg : "iowait",
2113 		    utime.tv_sec, utime.tv_usec / 10000,
2114 		    stime.tv_sec, stime.tv_usec / 10000, pctcpu / 100, rss);
2115 	}
2116 	tp->t_rocount = 0;	/* so pending input will be retyped if BS */
2117 }
2118 
2119 /*
2120  * Returns 1 if p2 is "better" than p1
2121  *
2122  * The algorithm for picking the "interesting" process is thus:
2123  *
2124  *	1) Only foreground processes are eligible - implied.
2125  *	2) Runnable processes are favored over anything else.  The runner
2126  *	   with the highest cpu utilization is picked (p_estcpu).  Ties are
2127  *	   broken by picking the highest pid.
2128  *	3) The sleeper with the shortest sleep time is next.  With ties,
2129  *	   we pick out just "short-term" sleepers (P_SINTR == 0).
2130  *	4) Further ties are broken by picking the highest pid.
2131  */
2132 #define ISRUN(p)	(((p)->p_stat == SRUN) || ((p)->p_stat == SIDL) || \
2133 			 ((p)->p_stat == SONPROC))
2134 #define TESTAB(a, b)    ((a)<<1 | (b))
2135 #define ONLYA   2
2136 #define ONLYB   1
2137 #define BOTH    3
2138 
2139 static int
2140 proc_compare(struct proc *p1, struct proc *p2)
2141 {
2142 
2143 	if (p1 == NULL)
2144 		return (1);
2145 	/*
2146 	 * see if at least one of them is runnable
2147 	 */
2148 	switch (TESTAB(ISRUN(p1), ISRUN(p2))) {
2149 	case ONLYA:
2150 		return (0);
2151 	case ONLYB:
2152 		return (1);
2153 	case BOTH:
2154 		/*
2155 		 * tie - favor one with highest recent cpu utilization
2156 		 */
2157 		if (p2->p_estcpu > p1->p_estcpu)
2158 			return (1);
2159 		if (p1->p_estcpu > p2->p_estcpu)
2160 			return (0);
2161 		return (p2->p_pid > p1->p_pid);	/* tie - return highest pid */
2162 	}
2163 	/*
2164  	 * weed out zombies
2165 	 */
2166 	switch (TESTAB(P_ZOMBIE(p1), P_ZOMBIE(p2))) {
2167 	case ONLYA:
2168 		return (1);
2169 	case ONLYB:
2170 		return (0);
2171 	case BOTH:
2172 		return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
2173 	}
2174 	/*
2175 	 * pick the one with the smallest sleep time
2176 	 */
2177 	if (p2->p_slptime > p1->p_slptime)
2178 		return (0);
2179 	if (p1->p_slptime > p2->p_slptime)
2180 		return (1);
2181 	/*
2182 	 * favor one sleeping in a non-interruptible sleep
2183 	 */
2184 	if (p1->p_flag & P_SINTR && (p2->p_flag & P_SINTR) == 0)
2185 		return (1);
2186 	if (p2->p_flag & P_SINTR && (p1->p_flag & P_SINTR) == 0)
2187 		return (0);
2188 	return (p2->p_pid > p1->p_pid);		/* tie - return highest pid */
2189 }
2190 
2191 /*
2192  * Output char to tty; console putchar style.
2193  */
2194 int
2195 tputchar(int c, struct tty *tp)
2196 {
2197 	int s;
2198 
2199 	s = spltty();
2200 	if (ISSET(tp->t_state, TS_ISOPEN) == 0 ||
2201 	    !(ISSET(tp->t_state, TS_CARR_ON) || ISSET(tp->t_cflag, CLOCAL))) {
2202 		splx(s);
2203 		return (-1);
2204 	}
2205 	if (c == '\n')
2206 		(void)ttyoutput('\r', tp);
2207 	(void)ttyoutput(c, tp);
2208 	ttstart(tp);
2209 	splx(s);
2210 	return (0);
2211 }
2212 
2213 /*
2214  * Sleep on chan, returning ERESTART if tty changed while we napped and
2215  * returning any errors (e.g. EINTR/ETIMEDOUT) reported by tsleep.  If
2216  * the tty is revoked, restarting a pending call will redo validation done
2217  * at the start of the call.
2218  */
2219 int
2220 ttysleep(struct tty *tp, void *chan, int pri, char *wmesg, int timo)
2221 {
2222 	int error;
2223 	short gen;
2224 
2225 	gen = tp->t_gen;
2226 	if ((error = tsleep(chan, pri, wmesg, timo)) != 0)
2227 		return (error);
2228 	return (tp->t_gen == gen ? 0 : ERESTART);
2229 }
2230 
2231 /*
2232  * Initialise the global tty list.
2233  */
2234 void
2235 tty_init(void)
2236 {
2237 
2238 	TAILQ_INIT(&ttylist);
2239 	tty_count = 0;
2240 }
2241 
2242 /*
2243  * Allocate a tty structure and its associated buffers, and attach it to the
2244  * tty list.
2245  */
2246 struct tty *
2247 ttymalloc(void)
2248 {
2249 	struct tty *tp;
2250 
2251 	tp = malloc(sizeof(struct tty), M_TTYS, M_WAITOK|M_ZERO);
2252 
2253 	/* XXX: default to 1024 chars for now */
2254 	clalloc(&tp->t_rawq, 1024, 1);
2255 	clalloc(&tp->t_canq, 1024, 1);
2256 	/* output queue doesn't need quoting */
2257 	clalloc(&tp->t_outq, 1024, 0);
2258 
2259 	TAILQ_INSERT_TAIL(&ttylist, tp, tty_link);
2260 	++tty_count;
2261 	timeout_set(&tp->t_rstrt_to, ttrstrt, tp);
2262 
2263 	return(tp);
2264 }
2265 
2266 
2267 /*
2268  * Free a tty structure and its buffers, after removing it from the tty list.
2269  */
2270 void
2271 ttyfree(struct tty *tp)
2272 {
2273 
2274 	--tty_count;
2275 #ifdef DIAGNOSTIC
2276 	if (tty_count < 0)
2277 		panic("ttyfree: tty_count < 0");
2278 #endif
2279 	TAILQ_REMOVE(&ttylist, tp, tty_link);
2280 
2281 	clfree(&tp->t_rawq);
2282 	clfree(&tp->t_canq);
2283 	clfree(&tp->t_outq);
2284 	free(tp, M_TTYS);
2285 }
2286 
2287 struct itty *ttystats;
2288 
2289 int
2290 ttystats_init(void)
2291 {
2292 	struct itty *itp;
2293 	struct tty *tp;
2294 
2295 	ttystats = malloc(tty_count * sizeof(struct itty),
2296 	    M_SYSCTL, M_WAITOK);
2297 	for (tp = TAILQ_FIRST(&ttylist), itp = ttystats; tp;
2298 	    tp = TAILQ_NEXT(tp, tty_link), itp++) {
2299 		itp->t_dev = tp->t_dev;
2300 		itp->t_rawq_c_cc = tp->t_rawq.c_cc;
2301 		itp->t_canq_c_cc = tp->t_canq.c_cc;
2302 		itp->t_outq_c_cc = tp->t_outq.c_cc;
2303 		itp->t_hiwat = tp->t_hiwat;
2304 		itp->t_lowat = tp->t_lowat;
2305 		itp->t_column = tp->t_column;
2306 		itp->t_state = tp->t_state;
2307 		itp->t_session = tp->t_session;
2308 		if (tp->t_pgrp)
2309 			itp->t_pgrp_pg_id = tp->t_pgrp->pg_id;
2310 		else
2311 			itp->t_pgrp_pg_id = 0;
2312 		itp->t_line = tp->t_line;
2313 	}
2314 	return (0);
2315 }
2316 
2317 /*
2318  * Return tty-related information.
2319  */
2320 int
2321 sysctl_tty(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
2322     size_t newlen)
2323 {
2324 	int err;
2325 
2326 	if (namelen != 1)
2327 		return (ENOTDIR);
2328 
2329 	switch (name[0]) {
2330 	case KERN_TTY_TKNIN:
2331 		return (sysctl_rdquad(oldp, oldlenp, newp, tk_nin));
2332 	case KERN_TTY_TKNOUT:
2333 		return (sysctl_rdquad(oldp, oldlenp, newp, tk_nout));
2334 	case KERN_TTY_TKRAWCC:
2335 		return (sysctl_rdquad(oldp, oldlenp, newp, tk_rawcc));
2336 	case KERN_TTY_TKCANCC:
2337 		return (sysctl_rdquad(oldp, oldlenp, newp, tk_cancc));
2338 	case KERN_TTY_INFO:
2339 		err = ttystats_init();
2340 		if (err)
2341 			return (err);
2342 		err = sysctl_rdstruct(oldp, oldlenp, newp, ttystats,
2343 		    tty_count * sizeof(struct itty));
2344 		free(ttystats, M_SYSCTL);
2345 		return (err);
2346 	default:
2347 #if NPTY > 0
2348 		return (sysctl_pty(name, namelen, oldp, oldlenp, newp, newlen));
2349 #else
2350 		return (EOPNOTSUPP);
2351 #endif
2352 	}
2353 	/* NOTREACHED */
2354 }
2355 
2356 void
2357 ttytstamp(struct tty *tp, int octs, int ncts, int odcd, int ndcd)
2358 {
2359 	int doit = 0;
2360 
2361 	if (ncts ^ octs)
2362 		doit |= ncts ? ISSET(tp->t_flags, TS_TSTAMPCTSSET) :
2363 		    ISSET(tp->t_flags, TS_TSTAMPCTSCLR);
2364 	if (ndcd ^ odcd)
2365 		doit |= ndcd ? ISSET(tp->t_flags, TS_TSTAMPDCDSET) :
2366 		    ISSET(tp->t_flags, TS_TSTAMPDCDCLR);
2367 
2368 	if (doit)
2369 		microtime(&tp->t_tv);
2370 }
2371