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