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