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