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