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