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