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