xref: /freebsd/sys/kern/tty.c (revision d2387d42b8da231a5b95cbc313825fb2aadf26f6)
1 /*-
2  * Copyright (c) 1982, 1986, 1990, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Copyright (c) 2002 Networks Associates Technologies, Inc.
11  * All rights reserved.
12  *
13  * Portions of this software were developed for the FreeBSD Project by
14  * ThinkSec AS and NAI Labs, the Security Research Division of Network
15  * Associates, Inc.  under DARPA/SPAWAR contract N66001-01-C-8035
16  * ("CBOSS"), as part of the DARPA CHATS research program.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  * 1. Redistributions of source code must retain the above copyright
22  *    notice, this list of conditions and the following disclaimer.
23  * 2. Redistributions in binary form must reproduce the above copyright
24  *    notice, this list of conditions and the following disclaimer in the
25  *    documentation and/or other materials provided with the distribution.
26  * 3. All advertising materials mentioning features or use of this software
27  *    must display the following acknowledgement:
28  *	This product includes software developed by the University of
29  *	California, Berkeley and its contributors.
30  * 4. Neither the name of the University nor the names of its contributors
31  *    may be used to endorse or promote products derived from this software
32  *    without specific prior written permission.
33  *
34  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
35  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
36  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
37  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
38  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
39  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
40  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
41  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
42  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
43  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
44  * SUCH DAMAGE.
45  *
46  *	@(#)tty.c	8.8 (Berkeley) 1/21/94
47  */
48 
49 /*-
50  * TODO:
51  *	o Fix races for sending the start char in ttyflush().
52  *	o Handle inter-byte timeout for "MIN > 0, TIME > 0" in ttyselect().
53  *	  With luck, there will be MIN chars before select() returns().
54  *	o Handle CLOCAL consistently for ptys.  Perhaps disallow setting it.
55  *	o Don't allow input in TS_ZOMBIE case.  It would be visible through
56  *	  FIONREAD.
57  *	o Do the new sio locking stuff here and use it to avoid special
58  *	  case for EXTPROC?
59  *	o Lock PENDIN too?
60  *	o Move EXTPROC and/or PENDIN to t_state?
61  *	o Wrap most of ttioctl in spltty/splx.
62  *	o Implement TIOCNOTTY or remove it from <sys/ioctl.h>.
63  *	o Send STOP if IXOFF is toggled off while TS_TBLOCK is set.
64  *	o Don't allow certain termios flags to affect disciplines other
65  *	  than TTYDISC.  Cancel their effects before switch disciplines
66  *	  and ignore them if they are set while we are in another
67  *	  discipline.
68  *	o Now that historical speed conversions are handled here, don't
69  *	  do them in drivers.
70  *	o Check for TS_CARR_ON being set while everything is closed and not
71  *	  waiting for carrier.  TS_CARR_ON isn't cleared if nothing is open,
72  *	  so it would live until the next open even if carrier drops.
73  *	o Restore TS_WOPEN since it is useful in pstat.  It must be cleared
74  *	  only when _all_ openers leave open().
75  */
76 
77 #include <sys/cdefs.h>
78 __FBSDID("$FreeBSD$");
79 
80 #include "opt_compat.h"
81 #include "opt_tty.h"
82 
83 #include <sys/param.h>
84 #include <sys/systm.h>
85 #include <sys/filio.h>
86 #include <sys/lock.h>
87 #include <sys/mutex.h>
88 #include <sys/namei.h>
89 #include <sys/sx.h>
90 #if defined(COMPAT_43) || defined(COMPAT_SUNOS)
91 #include <sys/ioctl_compat.h>
92 #endif
93 #include <sys/proc.h>
94 #define	TTYDEFCHARS
95 #include <sys/tty.h>
96 #undef	TTYDEFCHARS
97 #include <sys/fcntl.h>
98 #include <sys/conf.h>
99 #include <sys/poll.h>
100 #include <sys/kernel.h>
101 #include <sys/vnode.h>
102 #include <sys/signalvar.h>
103 #include <sys/resourcevar.h>
104 #include <sys/malloc.h>
105 #include <sys/filedesc.h>
106 #include <sys/sched.h>
107 #include <sys/sysctl.h>
108 
109 #include <vm/vm.h>
110 #include <vm/pmap.h>
111 #include <vm/vm_map.h>
112 
113 MALLOC_DEFINE(M_TTYS, "ttys", "tty data structures");
114 
115 long tk_cancc;
116 long tk_nin;
117 long tk_nout;
118 long tk_rawcc;
119 
120 static int	proc_compare(struct proc *p1, struct proc *p2);
121 static int	ttnread(struct tty *tp);
122 static void	ttyecho(int c, struct tty *tp);
123 static int	ttyoutput(int c, struct tty *tp);
124 static void	ttypend(struct tty *tp);
125 static void	ttyretype(struct tty *tp);
126 static void	ttyrub(int c, struct tty *tp);
127 static void	ttyrubo(struct tty *tp, int cnt);
128 static void	ttyunblock(struct tty *tp);
129 static int	ttywflush(struct tty *tp);
130 static int	filt_ttyread(struct knote *kn, long hint);
131 static void	filt_ttyrdetach(struct knote *kn);
132 static int	filt_ttywrite(struct knote *kn, long hint);
133 static void	filt_ttywdetach(struct knote *kn);
134 
135 /*
136  * Table with character classes and parity. The 8th bit indicates parity,
137  * the 7th bit indicates the character is an alphameric or underscore (for
138  * ALTWERASE), and the low 6 bits indicate delay type.  If the low 6 bits
139  * are 0 then the character needs no special processing on output; classes
140  * other than 0 might be translated or (not currently) require delays.
141  */
142 #define	E	0x00	/* Even parity. */
143 #define	O	0x80	/* Odd parity. */
144 #define	PARITY(c)	(char_type[c] & O)
145 
146 #define	ALPHA	0x40	/* Alpha or underscore. */
147 #define	ISALPHA(c)	(char_type[(c) & TTY_CHARMASK] & ALPHA)
148 
149 #define	CCLASSMASK	0x3f
150 #define	CCLASS(c)	(char_type[c] & CCLASSMASK)
151 
152 #define	BS	BACKSPACE
153 #define	CC	CONTROL
154 #define	CR	RETURN
155 #define	NA	ORDINARY | ALPHA
156 #define	NL	NEWLINE
157 #define	NO	ORDINARY
158 #define	TB	TAB
159 #define	VT	VTAB
160 
161 static u_char const char_type[] = {
162 	E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC,	/* nul - bel */
163 	O|BS, E|TB, E|NL, O|CC, E|VT, O|CR, O|CC, E|CC, /* bs - si */
164 	O|CC, E|CC, E|CC, O|CC, E|CC, O|CC, O|CC, E|CC, /* dle - etb */
165 	E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC, /* can - us */
166 	O|NO, E|NO, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* sp - ' */
167 	E|NO, O|NO, O|NO, E|NO, O|NO, E|NO, E|NO, O|NO, /* ( - / */
168 	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* 0 - 7 */
169 	O|NA, E|NA, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* 8 - ? */
170 	O|NO, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* @ - G */
171 	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* H - O */
172 	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* P - W */
173 	O|NA, E|NA, E|NA, O|NO, E|NO, O|NO, O|NO, O|NA, /* X - _ */
174 	E|NO, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* ` - g */
175 	O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* h - o */
176 	O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* p - w */
177 	E|NA, O|NA, O|NA, E|NO, O|NO, E|NO, E|NO, O|CC, /* x - del */
178 	/*
179 	 * Meta chars; should be settable per character set;
180 	 * for now, treat them all as normal characters.
181 	 */
182 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
183 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
184 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
185 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
186 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
187 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
188 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
189 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
190 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
191 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
192 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
193 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
194 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
195 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
196 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
197 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
198 };
199 #undef	BS
200 #undef	CC
201 #undef	CR
202 #undef	NA
203 #undef	NL
204 #undef	NO
205 #undef	TB
206 #undef	VT
207 
208 /* Macros to clear/set/test flags. */
209 #define	SET(t, f)	(t) |= (f)
210 #define	CLR(t, f)	(t) &= ~(f)
211 #define	ISSET(t, f)	((t) & (f))
212 
213 #undef MAX_INPUT		/* XXX wrong in <sys/syslimits.h> */
214 #define	MAX_INPUT	TTYHOG	/* XXX limit is usually larger for !ICANON */
215 
216 /*
217  * list of struct tty where pstat(8) can pick it up with sysctl
218  */
219 static SLIST_HEAD(, tty) tty_list;
220 
221 static int  drainwait = 5*60;
222 SYSCTL_INT(_kern, OID_AUTO, drainwait, CTLFLAG_RW, &drainwait,
223 	0, "Output drain timeout in seconds");
224 
225 /*
226  * Initial open of tty, or (re)entry to standard tty line discipline.
227  */
228 int
229 ttyopen(dev_t device, struct tty *tp)
230 {
231 	int s;
232 
233 	s = spltty();
234 	tp->t_dev = device;
235 	if (!ISSET(tp->t_state, TS_ISOPEN)) {
236 		SET(tp->t_state, TS_ISOPEN);
237 		if (ISSET(tp->t_cflag, CLOCAL))
238 			SET(tp->t_state, TS_CONNECTED);
239 		bzero(&tp->t_winsize, sizeof(tp->t_winsize));
240 	}
241 	/* XXX don't hang forever on output */
242 	if (tp->t_timeout < 0)
243 		tp->t_timeout = drainwait*hz;
244 	ttsetwater(tp);
245 	splx(s);
246 	return (0);
247 }
248 
249 /*
250  * Handle close() on a tty line: flush and set to initial state,
251  * bumping generation number so that pending read/write calls
252  * can detect recycling of the tty.
253  * XXX our caller should have done `spltty(); l_close(); ttyclose();'
254  * and l_close() should have flushed, but we repeat the spltty() and
255  * the flush in case there are buggy callers.
256  */
257 int
258 ttyclose(struct tty *tp)
259 {
260 	int s;
261 
262 	funsetown(&tp->t_sigio);
263 	s = spltty();
264 	if (constty == tp)
265 		constty_clear();
266 
267 	ttyflush(tp, FREAD | FWRITE);
268 	clist_free_cblocks(&tp->t_canq);
269 	clist_free_cblocks(&tp->t_outq);
270 	clist_free_cblocks(&tp->t_rawq);
271 
272 	tp->t_gen++;
273 	tp->t_line = TTYDISC;
274 	tp->t_pgrp = NULL;
275 	tp->t_session = NULL;
276 	tp->t_state = 0;
277 	splx(s);
278 	return (0);
279 }
280 
281 #define	FLUSHQ(q) {							\
282 	if ((q)->c_cc)							\
283 		ndflush(q, (q)->c_cc);					\
284 }
285 
286 /* Is 'c' a line delimiter ("break" character)? */
287 #define	TTBREAKC(c, lflag)							\
288 	((c) == '\n' || (((c) == cc[VEOF] ||				\
289 	  (c) == cc[VEOL] || ((c) == cc[VEOL2] && lflag & IEXTEN)) &&	\
290 	 (c) != _POSIX_VDISABLE))
291 
292 /*
293  * Process input of a single character received on a tty.
294  */
295 int
296 ttyinput(int c, struct tty *tp)
297 {
298 	tcflag_t iflag, lflag;
299 	cc_t *cc;
300 	int i, err;
301 
302 	/*
303 	 * If input is pending take it first.
304 	 */
305 	lflag = tp->t_lflag;
306 	if (ISSET(lflag, PENDIN))
307 		ttypend(tp);
308 	/*
309 	 * Gather stats.
310 	 */
311 	if (ISSET(lflag, ICANON)) {
312 		++tk_cancc;
313 		++tp->t_cancc;
314 	} else {
315 		++tk_rawcc;
316 		++tp->t_rawcc;
317 	}
318 	++tk_nin;
319 
320 	/*
321 	 * Block further input iff:
322 	 * current input > threshold AND input is available to user program
323 	 * AND input flow control is enabled and not yet invoked.
324 	 * The 3 is slop for PARMRK.
325 	 */
326 	iflag = tp->t_iflag;
327 	if (tp->t_rawq.c_cc + tp->t_canq.c_cc > tp->t_ihiwat - 3 &&
328 	    (!ISSET(lflag, ICANON) || tp->t_canq.c_cc != 0) &&
329 	    (ISSET(tp->t_cflag, CRTS_IFLOW) || ISSET(iflag, IXOFF)) &&
330 	    !ISSET(tp->t_state, TS_TBLOCK))
331 		ttyblock(tp);
332 
333 	/* Handle exceptional conditions (break, parity, framing). */
334 	cc = tp->t_cc;
335 	err = (ISSET(c, TTY_ERRORMASK));
336 	if (err) {
337 		CLR(c, TTY_ERRORMASK);
338 		if (ISSET(err, TTY_BI)) {
339 			if (ISSET(iflag, IGNBRK))
340 				return (0);
341 			if (ISSET(iflag, BRKINT)) {
342 				ttyflush(tp, FREAD | FWRITE);
343 				if (tp->t_pgrp != NULL) {
344 					PGRP_LOCK(tp->t_pgrp);
345 					pgsignal(tp->t_pgrp, SIGINT, 1);
346 					PGRP_UNLOCK(tp->t_pgrp);
347 				}
348 				goto endcase;
349 			}
350 			if (ISSET(iflag, PARMRK))
351 				goto parmrk;
352 		} else if ((ISSET(err, TTY_PE) && ISSET(iflag, INPCK))
353 			|| ISSET(err, TTY_FE)) {
354 			if (ISSET(iflag, IGNPAR))
355 				return (0);
356 			else if (ISSET(iflag, PARMRK)) {
357 parmrk:
358 				if (tp->t_rawq.c_cc + tp->t_canq.c_cc >
359 				    MAX_INPUT - 3)
360 					goto input_overflow;
361 				(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
362 				(void)putc(0 | TTY_QUOTE, &tp->t_rawq);
363 				(void)putc(c | TTY_QUOTE, &tp->t_rawq);
364 				goto endcase;
365 			} else
366 				c = 0;
367 		}
368 	}
369 
370 	if (!ISSET(tp->t_state, TS_TYPEN) && ISSET(iflag, ISTRIP))
371 		CLR(c, 0x80);
372 	if (!ISSET(lflag, EXTPROC)) {
373 		/*
374 		 * Check for literal nexting very first
375 		 */
376 		if (ISSET(tp->t_state, TS_LNCH)) {
377 			SET(c, TTY_QUOTE);
378 			CLR(tp->t_state, TS_LNCH);
379 		}
380 		/*
381 		 * Scan for special characters.  This code
382 		 * is really just a big case statement with
383 		 * non-constant cases.  The bottom of the
384 		 * case statement is labeled ``endcase'', so goto
385 		 * it after a case match, or similar.
386 		 */
387 
388 		/*
389 		 * Control chars which aren't controlled
390 		 * by ICANON, ISIG, or IXON.
391 		 */
392 		if (ISSET(lflag, IEXTEN)) {
393 			if (CCEQ(cc[VLNEXT], c)) {
394 				if (ISSET(lflag, ECHO)) {
395 					if (ISSET(lflag, ECHOE)) {
396 						(void)ttyoutput('^', tp);
397 						(void)ttyoutput('\b', tp);
398 					} else
399 						ttyecho(c, tp);
400 				}
401 				SET(tp->t_state, TS_LNCH);
402 				goto endcase;
403 			}
404 			if (CCEQ(cc[VDISCARD], c)) {
405 				if (ISSET(lflag, FLUSHO))
406 					CLR(tp->t_lflag, FLUSHO);
407 				else {
408 					ttyflush(tp, FWRITE);
409 					ttyecho(c, tp);
410 					if (tp->t_rawq.c_cc + tp->t_canq.c_cc)
411 						ttyretype(tp);
412 					SET(tp->t_lflag, FLUSHO);
413 				}
414 				goto startoutput;
415 			}
416 		}
417 		/*
418 		 * Signals.
419 		 */
420 		if (ISSET(lflag, ISIG)) {
421 			if (CCEQ(cc[VINTR], c) || CCEQ(cc[VQUIT], c)) {
422 				if (!ISSET(lflag, NOFLSH))
423 					ttyflush(tp, FREAD | FWRITE);
424 				ttyecho(c, tp);
425 				if (tp->t_pgrp != NULL) {
426 					PGRP_LOCK(tp->t_pgrp);
427 					pgsignal(tp->t_pgrp,
428 					    CCEQ(cc[VINTR], c) ? SIGINT : SIGQUIT, 1);
429 					PGRP_UNLOCK(tp->t_pgrp);
430 				}
431 				goto endcase;
432 			}
433 			if (CCEQ(cc[VSUSP], c)) {
434 				if (!ISSET(lflag, NOFLSH))
435 					ttyflush(tp, FREAD);
436 				ttyecho(c, tp);
437 				if (tp->t_pgrp != NULL) {
438 					PGRP_LOCK(tp->t_pgrp);
439 					pgsignal(tp->t_pgrp, SIGTSTP, 1);
440 					PGRP_UNLOCK(tp->t_pgrp);
441 				}
442 				goto endcase;
443 			}
444 		}
445 		/*
446 		 * Handle start/stop characters.
447 		 */
448 		if (ISSET(iflag, IXON)) {
449 			if (CCEQ(cc[VSTOP], c)) {
450 				if (!ISSET(tp->t_state, TS_TTSTOP)) {
451 					SET(tp->t_state, TS_TTSTOP);
452 					(*tp->t_stop)(tp, 0);
453 					return (0);
454 				}
455 				if (!CCEQ(cc[VSTART], c))
456 					return (0);
457 				/*
458 				 * if VSTART == VSTOP then toggle
459 				 */
460 				goto endcase;
461 			}
462 			if (CCEQ(cc[VSTART], c))
463 				goto restartoutput;
464 		}
465 		/*
466 		 * IGNCR, ICRNL, & INLCR
467 		 */
468 		if (c == '\r') {
469 			if (ISSET(iflag, IGNCR))
470 				return (0);
471 			else if (ISSET(iflag, ICRNL))
472 				c = '\n';
473 		} else if (c == '\n' && ISSET(iflag, INLCR))
474 			c = '\r';
475 	}
476 	if (!ISSET(tp->t_lflag, EXTPROC) && ISSET(lflag, ICANON)) {
477 		/*
478 		 * From here on down canonical mode character
479 		 * processing takes place.
480 		 */
481 		/*
482 		 * erase or erase2 (^H / ^?)
483 		 */
484 		if (CCEQ(cc[VERASE], c) || CCEQ(cc[VERASE2], c) ) {
485 			if (tp->t_rawq.c_cc)
486 				ttyrub(unputc(&tp->t_rawq), tp);
487 			goto endcase;
488 		}
489 		/*
490 		 * kill (^U)
491 		 */
492 		if (CCEQ(cc[VKILL], c)) {
493 			if (ISSET(lflag, ECHOKE) &&
494 			    tp->t_rawq.c_cc == tp->t_rocount &&
495 			    !ISSET(lflag, ECHOPRT))
496 				while (tp->t_rawq.c_cc)
497 					ttyrub(unputc(&tp->t_rawq), tp);
498 			else {
499 				ttyecho(c, tp);
500 				if (ISSET(lflag, ECHOK) ||
501 				    ISSET(lflag, ECHOKE))
502 					ttyecho('\n', tp);
503 				FLUSHQ(&tp->t_rawq);
504 				tp->t_rocount = 0;
505 			}
506 			CLR(tp->t_state, TS_LOCAL);
507 			goto endcase;
508 		}
509 		/*
510 		 * word erase (^W)
511 		 */
512 		if (CCEQ(cc[VWERASE], c) && ISSET(lflag, IEXTEN)) {
513 			int ctype;
514 
515 			/*
516 			 * erase whitespace
517 			 */
518 			while ((c = unputc(&tp->t_rawq)) == ' ' || c == '\t')
519 				ttyrub(c, tp);
520 			if (c == -1)
521 				goto endcase;
522 			/*
523 			 * erase last char of word and remember the
524 			 * next chars type (for ALTWERASE)
525 			 */
526 			ttyrub(c, tp);
527 			c = unputc(&tp->t_rawq);
528 			if (c == -1)
529 				goto endcase;
530 			if (c == ' ' || c == '\t') {
531 				(void)putc(c, &tp->t_rawq);
532 				goto endcase;
533 			}
534 			ctype = ISALPHA(c);
535 			/*
536 			 * erase rest of word
537 			 */
538 			do {
539 				ttyrub(c, tp);
540 				c = unputc(&tp->t_rawq);
541 				if (c == -1)
542 					goto endcase;
543 			} while (c != ' ' && c != '\t' &&
544 			    (!ISSET(lflag, ALTWERASE) || ISALPHA(c) == ctype));
545 			(void)putc(c, &tp->t_rawq);
546 			goto endcase;
547 		}
548 		/*
549 		 * reprint line (^R)
550 		 */
551 		if (CCEQ(cc[VREPRINT], c) && ISSET(lflag, IEXTEN)) {
552 			ttyretype(tp);
553 			goto endcase;
554 		}
555 		/*
556 		 * ^T - kernel info and generate SIGINFO
557 		 */
558 		if (CCEQ(cc[VSTATUS], c) && ISSET(lflag, IEXTEN)) {
559 			if (ISSET(lflag, ISIG) && tp->t_pgrp != NULL) {
560 				PGRP_LOCK(tp->t_pgrp);
561 				pgsignal(tp->t_pgrp, SIGINFO, 1);
562 				PGRP_UNLOCK(tp->t_pgrp);
563 			}
564 			if (!ISSET(lflag, NOKERNINFO))
565 				ttyinfo(tp);
566 			goto endcase;
567 		}
568 	}
569 	/*
570 	 * Check for input buffer overflow
571 	 */
572 	if (tp->t_rawq.c_cc + tp->t_canq.c_cc >= MAX_INPUT) {
573 input_overflow:
574 		if (ISSET(iflag, IMAXBEL)) {
575 			if (tp->t_outq.c_cc < tp->t_ohiwat)
576 				(void)ttyoutput(CTRL('g'), tp);
577 		}
578 		goto endcase;
579 	}
580 
581 	if (   c == 0377 && ISSET(iflag, PARMRK) && !ISSET(iflag, ISTRIP)
582 	     && ISSET(iflag, IGNBRK|IGNPAR) != (IGNBRK|IGNPAR))
583 		(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
584 
585 	/*
586 	 * Put data char in q for user and
587 	 * wakeup on seeing a line delimiter.
588 	 */
589 	if (putc(c, &tp->t_rawq) >= 0) {
590 		if (!ISSET(lflag, ICANON)) {
591 			ttwakeup(tp);
592 			ttyecho(c, tp);
593 			goto endcase;
594 		}
595 		if (TTBREAKC(c, lflag)) {
596 			tp->t_rocount = 0;
597 			catq(&tp->t_rawq, &tp->t_canq);
598 			ttwakeup(tp);
599 		} else if (tp->t_rocount++ == 0)
600 			tp->t_rocol = tp->t_column;
601 		if (ISSET(tp->t_state, TS_ERASE)) {
602 			/*
603 			 * end of prterase \.../
604 			 */
605 			CLR(tp->t_state, TS_ERASE);
606 			(void)ttyoutput('/', tp);
607 		}
608 		i = tp->t_column;
609 		ttyecho(c, tp);
610 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ECHO)) {
611 			/*
612 			 * Place the cursor over the '^' of the ^D.
613 			 */
614 			i = imin(2, tp->t_column - i);
615 			while (i > 0) {
616 				(void)ttyoutput('\b', tp);
617 				i--;
618 			}
619 		}
620 	}
621 endcase:
622 	/*
623 	 * IXANY means allow any character to restart output.
624 	 */
625 	if (ISSET(tp->t_state, TS_TTSTOP) &&
626 	    !ISSET(iflag, IXANY) && cc[VSTART] != cc[VSTOP])
627 		return (0);
628 restartoutput:
629 	CLR(tp->t_lflag, FLUSHO);
630 	CLR(tp->t_state, TS_TTSTOP);
631 startoutput:
632 	return (ttstart(tp));
633 }
634 
635 /*
636  * Output a single character on a tty, doing output processing
637  * as needed (expanding tabs, newline processing, etc.).
638  * Returns < 0 if succeeds, otherwise returns char to resend.
639  * Must be recursive.
640  */
641 static int
642 ttyoutput(int c, struct tty *tp)
643 {
644 	tcflag_t oflag;
645 	int col, s;
646 
647 	oflag = tp->t_oflag;
648 	if (!ISSET(oflag, OPOST)) {
649 		if (ISSET(tp->t_lflag, FLUSHO))
650 			return (-1);
651 		if (putc(c, &tp->t_outq))
652 			return (c);
653 		tk_nout++;
654 		tp->t_outcc++;
655 		return (-1);
656 	}
657 	/*
658 	 * Do tab expansion if OXTABS is set.  Special case if we external
659 	 * processing, we don't do the tab expansion because we'll probably
660 	 * get it wrong.  If tab expansion needs to be done, let it happen
661 	 * externally.
662 	 */
663 	CLR(c, ~TTY_CHARMASK);
664 	if (c == '\t' &&
665 	    ISSET(oflag, OXTABS) && !ISSET(tp->t_lflag, EXTPROC)) {
666 		c = 8 - (tp->t_column & 7);
667 		if (!ISSET(tp->t_lflag, FLUSHO)) {
668 			s = spltty();		/* Don't interrupt tabs. */
669 			c -= b_to_q("        ", c, &tp->t_outq);
670 			tk_nout += c;
671 			tp->t_outcc += c;
672 			splx(s);
673 		}
674 		tp->t_column += c;
675 		return (c ? -1 : '\t');
676 	}
677 	if (c == CEOT && ISSET(oflag, ONOEOT))
678 		return (-1);
679 
680 	/*
681 	 * Newline translation: if ONLCR is set,
682 	 * translate newline into "\r\n".
683 	 */
684 	if (c == '\n' && ISSET(tp->t_oflag, ONLCR)) {
685 		tk_nout++;
686 		tp->t_outcc++;
687 		if (!ISSET(tp->t_lflag, FLUSHO) && putc('\r', &tp->t_outq))
688 			return (c);
689 	}
690 	/* If OCRNL is set, translate "\r" into "\n". */
691 	else if (c == '\r' && ISSET(tp->t_oflag, OCRNL))
692 		c = '\n';
693 	/* If ONOCR is set, don't transmit CRs when on column 0. */
694 	else if (c == '\r' && ISSET(tp->t_oflag, ONOCR) && tp->t_column == 0)
695 		return (-1);
696 
697 	tk_nout++;
698 	tp->t_outcc++;
699 	if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
700 		return (c);
701 
702 	col = tp->t_column;
703 	switch (CCLASS(c)) {
704 	case BACKSPACE:
705 		if (col > 0)
706 			--col;
707 		break;
708 	case CONTROL:
709 		break;
710 	case NEWLINE:
711 		if (ISSET(tp->t_oflag, ONLCR | ONLRET))
712 			col = 0;
713 		break;
714 	case RETURN:
715 		col = 0;
716 		break;
717 	case ORDINARY:
718 		++col;
719 		break;
720 	case TAB:
721 		col = (col + 8) & ~7;
722 		break;
723 	}
724 	tp->t_column = col;
725 	return (-1);
726 }
727 
728 /*
729  * Ioctls for all tty devices.  Called after line-discipline specific ioctl
730  * has been called to do discipline-specific functions and/or reject any
731  * of these ioctl commands.
732  */
733 /* ARGSUSED */
734 int
735 ttioctl(struct tty *tp, u_long cmd, void *data, int flag)
736 {
737 	struct proc *p;
738 	struct thread *td;
739 	struct pgrp *pgrp;
740 	int s, error;
741 
742 	td = curthread;			/* XXX */
743 	p = td->td_proc;
744 
745 	/* If the ioctl involves modification, hang if in the background. */
746 	switch (cmd) {
747 	case  TIOCCBRK:
748 	case  TIOCCONS:
749 	case  TIOCDRAIN:
750 	case  TIOCEXCL:
751 	case  TIOCFLUSH:
752 #ifdef TIOCHPCL
753 	case  TIOCHPCL:
754 #endif
755 	case  TIOCNXCL:
756 	case  TIOCSBRK:
757 	case  TIOCSCTTY:
758 	case  TIOCSDRAINWAIT:
759 	case  TIOCSETA:
760 	case  TIOCSETAF:
761 	case  TIOCSETAW:
762 	case  TIOCSETD:
763 	case  TIOCSPGRP:
764 	case  TIOCSTART:
765 	case  TIOCSTAT:
766 	case  TIOCSTI:
767 	case  TIOCSTOP:
768 	case  TIOCSWINSZ:
769 #if defined(COMPAT_43) || defined(COMPAT_SUNOS)
770 	case  TIOCLBIC:
771 	case  TIOCLBIS:
772 	case  TIOCLSET:
773 	case  TIOCSETC:
774 	case OTIOCSETD:
775 	case  TIOCSETN:
776 	case  TIOCSETP:
777 	case  TIOCSLTC:
778 #endif
779 		sx_slock(&proctree_lock);
780 		PROC_LOCK(p);
781 		while (isbackground(p, tp) && !(p->p_flag & P_PPWAIT) &&
782 		    !SIGISMEMBER(p->p_sigacts->ps_sigignore, SIGTTOU) &&
783 		    !SIGISMEMBER(td->td_sigmask, SIGTTOU)) {
784 			pgrp = p->p_pgrp;
785 			PROC_UNLOCK(p);
786 			if (pgrp->pg_jobc == 0) {
787 				sx_sunlock(&proctree_lock);
788 				return (EIO);
789 			}
790 			PGRP_LOCK(pgrp);
791 			sx_sunlock(&proctree_lock);
792 			pgsignal(pgrp, SIGTTOU, 1);
793 			PGRP_UNLOCK(pgrp);
794 			error = ttysleep(tp, &lbolt, TTOPRI | PCATCH, "ttybg1",
795 					 0);
796 			if (error)
797 				return (error);
798 			sx_slock(&proctree_lock);
799 			PROC_LOCK(p);
800 		}
801 		PROC_UNLOCK(p);
802 		sx_sunlock(&proctree_lock);
803 		break;
804 	}
805 
806 	switch (cmd) {			/* Process the ioctl. */
807 	case FIOASYNC:			/* set/clear async i/o */
808 		s = spltty();
809 		if (*(int *)data)
810 			SET(tp->t_state, TS_ASYNC);
811 		else
812 			CLR(tp->t_state, TS_ASYNC);
813 		splx(s);
814 		break;
815 	case FIONBIO:			/* set/clear non-blocking i/o */
816 		break;			/* XXX: delete. */
817 	case FIONREAD:			/* get # bytes to read */
818 		s = spltty();
819 		*(int *)data = ttnread(tp);
820 		splx(s);
821 		break;
822 
823 	case FIOSETOWN:
824 		/*
825 		 * Policy -- Don't allow FIOSETOWN on someone else's
826 		 *           controlling tty
827 		 */
828 		if (tp->t_session != NULL && !isctty(p, tp))
829 			return (ENOTTY);
830 
831 		error = fsetown(*(int *)data, &tp->t_sigio);
832 		if (error)
833 			return (error);
834 		break;
835 	case FIOGETOWN:
836 		if (tp->t_session != NULL && !isctty(p, tp))
837 			return (ENOTTY);
838 		*(int *)data = fgetown(&tp->t_sigio);
839 		break;
840 
841 	case TIOCEXCL:			/* set exclusive use of tty */
842 		s = spltty();
843 		SET(tp->t_state, TS_XCLUDE);
844 		splx(s);
845 		break;
846 	case TIOCFLUSH: {		/* flush buffers */
847 		int flags = *(int *)data;
848 
849 		if (flags == 0)
850 			flags = FREAD | FWRITE;
851 		else
852 			flags &= FREAD | FWRITE;
853 		ttyflush(tp, flags);
854 		break;
855 	}
856 	case TIOCCONS:			/* become virtual console */
857 		if (*(int *)data) {
858 			struct nameidata nid;
859 
860 			if (constty && constty != tp &&
861 			    ISSET(constty->t_state, TS_CONNECTED))
862 				return (EBUSY);
863 
864 			/* Ensure user can open the real console. */
865 			NDINIT(&nid, LOOKUP, LOCKLEAF | FOLLOW, UIO_SYSSPACE,
866 			    "/dev/console", td);
867 			if ((error = namei(&nid)) != 0)
868 				return (error);
869 			NDFREE(&nid, NDF_ONLY_PNBUF);
870 			error = VOP_ACCESS(nid.ni_vp, VREAD, td->td_ucred, td);
871 			vput(nid.ni_vp);
872 			if (error)
873 				return (error);
874 
875 			constty_set(tp);
876 		} else if (tp == constty)
877 			constty_clear();
878 		break;
879 	case TIOCDRAIN:			/* wait till output drained */
880 		error = ttywait(tp);
881 		if (error)
882 			return (error);
883 		break;
884 	case TIOCGETA: {		/* get termios struct */
885 		struct termios *t = (struct termios *)data;
886 
887 		bcopy(&tp->t_termios, t, sizeof(struct termios));
888 		break;
889 	}
890 	case TIOCGETD:			/* get line discipline */
891 		*(int *)data = tp->t_line;
892 		break;
893 	case TIOCGWINSZ:		/* get window size */
894 		*(struct winsize *)data = tp->t_winsize;
895 		break;
896 	case TIOCGPGRP:			/* get pgrp of tty */
897 		if (!isctty(p, tp))
898 			return (ENOTTY);
899 		*(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
900 		break;
901 #ifdef TIOCHPCL
902 	case TIOCHPCL:			/* hang up on last close */
903 		s = spltty();
904 		SET(tp->t_cflag, HUPCL);
905 		splx(s);
906 		break;
907 #endif
908 	case TIOCNXCL:			/* reset exclusive use of tty */
909 		s = spltty();
910 		CLR(tp->t_state, TS_XCLUDE);
911 		splx(s);
912 		break;
913 	case TIOCOUTQ:			/* output queue size */
914 		*(int *)data = tp->t_outq.c_cc;
915 		break;
916 	case TIOCSETA:			/* set termios struct */
917 	case TIOCSETAW:			/* drain output, set */
918 	case TIOCSETAF: {		/* drn out, fls in, set */
919 		struct termios *t = (struct termios *)data;
920 
921 		if (t->c_ispeed == 0)
922 			t->c_ispeed = t->c_ospeed;
923 		if (t->c_ispeed == 0)
924 			t->c_ispeed = tp->t_ospeed;
925 		if (t->c_ispeed == 0)
926 			return (EINVAL);
927 		s = spltty();
928 		if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
929 			error = ttywait(tp);
930 			if (error) {
931 				splx(s);
932 				return (error);
933 			}
934 			if (cmd == TIOCSETAF)
935 				ttyflush(tp, FREAD);
936 		}
937 		if (!ISSET(t->c_cflag, CIGNORE)) {
938 			/*
939 			 * Set device hardware.
940 			 */
941 			if (tp->t_param && (error = (*tp->t_param)(tp, t))) {
942 				splx(s);
943 				return (error);
944 			}
945 			if (ISSET(t->c_cflag, CLOCAL) &&
946 			    !ISSET(tp->t_cflag, CLOCAL)) {
947 				/*
948 				 * XXX disconnections would be too hard to
949 				 * get rid of without this kludge.  The only
950 				 * way to get rid of controlling terminals
951 				 * is to exit from the session leader.
952 				 */
953 				CLR(tp->t_state, TS_ZOMBIE);
954 
955 				wakeup(TSA_CARR_ON(tp));
956 				ttwakeup(tp);
957 				ttwwakeup(tp);
958 			}
959 			if ((ISSET(tp->t_state, TS_CARR_ON) ||
960 			     ISSET(t->c_cflag, CLOCAL)) &&
961 			    !ISSET(tp->t_state, TS_ZOMBIE))
962 				SET(tp->t_state, TS_CONNECTED);
963 			else
964 				CLR(tp->t_state, TS_CONNECTED);
965 			tp->t_cflag = t->c_cflag;
966 			tp->t_ispeed = t->c_ispeed;
967 			if (t->c_ospeed != 0)
968 				tp->t_ospeed = t->c_ospeed;
969 			ttsetwater(tp);
970 		}
971 		if (ISSET(t->c_lflag, ICANON) != ISSET(tp->t_lflag, ICANON) &&
972 		    cmd != TIOCSETAF) {
973 			if (ISSET(t->c_lflag, ICANON))
974 				SET(tp->t_lflag, PENDIN);
975 			else {
976 				/*
977 				 * XXX we really shouldn't allow toggling
978 				 * ICANON while we're in a non-termios line
979 				 * discipline.  Now we have to worry about
980 				 * panicing for a null queue.
981 				 */
982 				if (tp->t_canq.c_cbreserved > 0 &&
983 				    tp->t_rawq.c_cbreserved > 0) {
984 					catq(&tp->t_rawq, &tp->t_canq);
985 					/*
986 					 * XXX the queue limits may be
987 					 * different, so the old queue
988 					 * swapping method no longer works.
989 					 */
990 					catq(&tp->t_canq, &tp->t_rawq);
991 				}
992 				CLR(tp->t_lflag, PENDIN);
993 			}
994 			ttwakeup(tp);
995 		}
996 		tp->t_iflag = t->c_iflag;
997 		tp->t_oflag = t->c_oflag;
998 		/*
999 		 * Make the EXTPROC bit read only.
1000 		 */
1001 		if (ISSET(tp->t_lflag, EXTPROC))
1002 			SET(t->c_lflag, EXTPROC);
1003 		else
1004 			CLR(t->c_lflag, EXTPROC);
1005 		tp->t_lflag = t->c_lflag | ISSET(tp->t_lflag, PENDIN);
1006 		if (t->c_cc[VMIN] != tp->t_cc[VMIN] ||
1007 		    t->c_cc[VTIME] != tp->t_cc[VTIME])
1008 			ttwakeup(tp);
1009 		bcopy(t->c_cc, tp->t_cc, sizeof(t->c_cc));
1010 		splx(s);
1011 		break;
1012 	}
1013 	case TIOCSETD: {		/* set line discipline */
1014 		int t = *(int *)data;
1015 		dev_t device = tp->t_dev;
1016 
1017 		if ((u_int)t >= nlinesw)
1018 			return (ENXIO);
1019 		if (t != tp->t_line) {
1020 			s = spltty();
1021 			(*linesw[tp->t_line].l_close)(tp, flag);
1022 			error = (*linesw[t].l_open)(device, tp);
1023 			if (error) {
1024 				(void)(*linesw[tp->t_line].l_open)(device, tp);
1025 				splx(s);
1026 				return (error);
1027 			}
1028 			tp->t_line = t;
1029 			splx(s);
1030 		}
1031 		break;
1032 	}
1033 	case TIOCSTART:			/* start output, like ^Q */
1034 		s = spltty();
1035 		if (ISSET(tp->t_state, TS_TTSTOP) ||
1036 		    ISSET(tp->t_lflag, FLUSHO)) {
1037 			CLR(tp->t_lflag, FLUSHO);
1038 			CLR(tp->t_state, TS_TTSTOP);
1039 			ttstart(tp);
1040 		}
1041 		splx(s);
1042 		break;
1043 	case TIOCSTI:			/* simulate terminal input */
1044 		if ((flag & FREAD) == 0 && suser(td))
1045 			return (EPERM);
1046 		if (!isctty(p, tp) && suser(td))
1047 			return (EACCES);
1048 		s = spltty();
1049 		(*linesw[tp->t_line].l_rint)(*(u_char *)data, tp);
1050 		splx(s);
1051 		break;
1052 	case TIOCSTOP:			/* stop output, like ^S */
1053 		s = spltty();
1054 		if (!ISSET(tp->t_state, TS_TTSTOP)) {
1055 			SET(tp->t_state, TS_TTSTOP);
1056 			(*tp->t_stop)(tp, 0);
1057 		}
1058 		splx(s);
1059 		break;
1060 	case TIOCSCTTY:			/* become controlling tty */
1061 		/* Session ctty vnode pointer set in vnode layer. */
1062 		sx_slock(&proctree_lock);
1063 		if (!SESS_LEADER(p) ||
1064 		    ((p->p_session->s_ttyvp || tp->t_session) &&
1065 		     (tp->t_session != p->p_session))) {
1066 			sx_sunlock(&proctree_lock);
1067 			return (EPERM);
1068 		}
1069 		tp->t_session = p->p_session;
1070 		tp->t_pgrp = p->p_pgrp;
1071 		SESS_LOCK(p->p_session);
1072 		p->p_session->s_ttyp = tp;
1073 		SESS_UNLOCK(p->p_session);
1074 		PROC_LOCK(p);
1075 		p->p_flag |= P_CONTROLT;
1076 		PROC_UNLOCK(p);
1077 		sx_sunlock(&proctree_lock);
1078 		break;
1079 	case TIOCSPGRP: {		/* set pgrp of tty */
1080 		sx_slock(&proctree_lock);
1081 		pgrp = pgfind(*(int *)data);
1082 		if (!isctty(p, tp)) {
1083 			if (pgrp != NULL)
1084 				PGRP_UNLOCK(pgrp);
1085 			sx_sunlock(&proctree_lock);
1086 			return (ENOTTY);
1087 		}
1088 		if (pgrp == NULL) {
1089 			sx_sunlock(&proctree_lock);
1090 			return (EPERM);
1091 		}
1092 		PGRP_UNLOCK(pgrp);
1093 		if (pgrp->pg_session != p->p_session) {
1094 			sx_sunlock(&proctree_lock);
1095 			return (EPERM);
1096 		}
1097 		sx_sunlock(&proctree_lock);
1098 		tp->t_pgrp = pgrp;
1099 		break;
1100 	}
1101 	case TIOCSTAT:			/* simulate control-T */
1102 		s = spltty();
1103 		ttyinfo(tp);
1104 		splx(s);
1105 		break;
1106 	case TIOCSWINSZ:		/* set window size */
1107 		if (bcmp((caddr_t)&tp->t_winsize, data,
1108 		    sizeof (struct winsize))) {
1109 			tp->t_winsize = *(struct winsize *)data;
1110 			if (tp->t_pgrp != NULL) {
1111 				PGRP_LOCK(tp->t_pgrp);
1112 				pgsignal(tp->t_pgrp, SIGWINCH, 1);
1113 				PGRP_UNLOCK(tp->t_pgrp);
1114 			}
1115 		}
1116 		break;
1117 	case TIOCSDRAINWAIT:
1118 		error = suser(td);
1119 		if (error)
1120 			return (error);
1121 		tp->t_timeout = *(int *)data * hz;
1122 		wakeup(TSA_OCOMPLETE(tp));
1123 		wakeup(TSA_OLOWAT(tp));
1124 		break;
1125 	case TIOCGDRAINWAIT:
1126 		*(int *)data = tp->t_timeout / hz;
1127 		break;
1128 	default:
1129 #if defined(COMPAT_43) || defined(COMPAT_SUNOS)
1130 		return (ttcompat(tp, cmd, data, flag));
1131 #else
1132 		return (ENOIOCTL);
1133 #endif
1134 	}
1135 	return (0);
1136 }
1137 
1138 int
1139 ttypoll(dev_t dev, int events, struct thread *td)
1140 {
1141 	int s;
1142 	int revents = 0;
1143 	struct tty *tp;
1144 
1145 	KASSERT(devsw(dev)->d_flags & D_TTY,
1146 	    ("ttypoll() called on non D_TTY device (%s)", devtoname(dev)));
1147 	tp = dev->si_tty;
1148 	KASSERT(tp != NULL,
1149 	    ("ttypoll(): no tty pointer on device (%s)", devtoname(dev)));
1150 	if (tp == NULL)	/* XXX used to return ENXIO, but that means true! */
1151 		return ((events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM))
1152 			| POLLHUP);
1153 
1154 	s = spltty();
1155 	if (events & (POLLIN | POLLRDNORM)) {
1156 		if (ttnread(tp) > 0 || ISSET(tp->t_state, TS_ZOMBIE))
1157 			revents |= events & (POLLIN | POLLRDNORM);
1158 		else
1159 			selrecord(td, &tp->t_rsel);
1160 	}
1161 	if (events & (POLLOUT | POLLWRNORM)) {
1162 		if ((tp->t_outq.c_cc <= tp->t_olowat &&
1163 		     ISSET(tp->t_state, TS_CONNECTED))
1164 		    || ISSET(tp->t_state, TS_ZOMBIE))
1165 			revents |= events & (POLLOUT | POLLWRNORM);
1166 		else
1167 			selrecord(td, &tp->t_wsel);
1168 	}
1169 	splx(s);
1170 	return (revents);
1171 }
1172 
1173 static struct filterops ttyread_filtops =
1174 	{ 1, NULL, filt_ttyrdetach, filt_ttyread };
1175 static struct filterops ttywrite_filtops =
1176 	{ 1, NULL, filt_ttywdetach, filt_ttywrite };
1177 
1178 int
1179 ttykqfilter(dev_t dev, struct knote *kn)
1180 {
1181 	struct tty *tp;
1182 	struct klist *klist;
1183 	int s;
1184 
1185 	KASSERT(devsw(dev)->d_flags & D_TTY,
1186 	    ("ttykqfilter() called on non D_TTY device (%s)", devtoname(dev)));
1187 	tp = dev->si_tty;
1188 	KASSERT(tp != NULL,
1189 	    ("ttykqfilter(): no tty pointer on device (%s)", devtoname(dev)));
1190 	switch (kn->kn_filter) {
1191 	case EVFILT_READ:
1192 		klist = &tp->t_rsel.si_note;
1193 		kn->kn_fop = &ttyread_filtops;
1194 		break;
1195 	case EVFILT_WRITE:
1196 		klist = &tp->t_wsel.si_note;
1197 		kn->kn_fop = &ttywrite_filtops;
1198 		break;
1199 	default:
1200 		return (1);
1201 	}
1202 
1203 	kn->kn_hook = (caddr_t)dev;
1204 
1205 	s = spltty();
1206 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
1207 	splx(s);
1208 
1209 	return (0);
1210 }
1211 
1212 static void
1213 filt_ttyrdetach(struct knote *kn)
1214 {
1215 	struct tty *tp = ((dev_t)kn->kn_hook)->si_tty;
1216 	int s = spltty();
1217 
1218 	SLIST_REMOVE(&tp->t_rsel.si_note, kn, knote, kn_selnext);
1219 	splx(s);
1220 }
1221 
1222 static int
1223 filt_ttyread(struct knote *kn, long hint)
1224 {
1225 	struct tty *tp = ((dev_t)kn->kn_hook)->si_tty;
1226 
1227 	kn->kn_data = ttnread(tp);
1228 	if (ISSET(tp->t_state, TS_ZOMBIE)) {
1229 		kn->kn_flags |= EV_EOF;
1230 		return (1);
1231 	}
1232 	return (kn->kn_data > 0);
1233 }
1234 
1235 static void
1236 filt_ttywdetach(struct knote *kn)
1237 {
1238 	struct tty *tp = ((dev_t)kn->kn_hook)->si_tty;
1239 	int s = spltty();
1240 
1241 	SLIST_REMOVE(&tp->t_wsel.si_note, kn, knote, kn_selnext);
1242 	splx(s);
1243 }
1244 
1245 static int
1246 filt_ttywrite(struct knote *kn, long hint)
1247 {
1248 	struct tty *tp = ((dev_t)kn->kn_hook)->si_tty;
1249 
1250 	kn->kn_data = tp->t_outq.c_cc;
1251 	if (ISSET(tp->t_state, TS_ZOMBIE))
1252 		return (1);
1253 	return (kn->kn_data <= tp->t_olowat &&
1254 	    ISSET(tp->t_state, TS_CONNECTED));
1255 }
1256 
1257 /*
1258  * Must be called at spltty().
1259  */
1260 static int
1261 ttnread(struct tty *tp)
1262 {
1263 	int nread;
1264 
1265 	if (ISSET(tp->t_lflag, PENDIN))
1266 		ttypend(tp);
1267 	nread = tp->t_canq.c_cc;
1268 	if (!ISSET(tp->t_lflag, ICANON)) {
1269 		nread += tp->t_rawq.c_cc;
1270 		if (nread < tp->t_cc[VMIN] && tp->t_cc[VTIME] == 0)
1271 			nread = 0;
1272 	}
1273 	return (nread);
1274 }
1275 
1276 /*
1277  * Wait for output to drain.
1278  */
1279 int
1280 ttywait(struct tty *tp)
1281 {
1282 	int error, s;
1283 
1284 	error = 0;
1285 	s = spltty();
1286 	while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1287 	       ISSET(tp->t_state, TS_CONNECTED) && tp->t_oproc) {
1288 		(*tp->t_oproc)(tp);
1289 		if ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1290 		    ISSET(tp->t_state, TS_CONNECTED)) {
1291 			SET(tp->t_state, TS_SO_OCOMPLETE);
1292 			error = ttysleep(tp, TSA_OCOMPLETE(tp),
1293 					 TTOPRI | PCATCH, "ttywai",
1294 					 tp->t_timeout);
1295 			if (error) {
1296 				if (error == EWOULDBLOCK)
1297 					error = EIO;
1298 				break;
1299 			}
1300 		} else
1301 			break;
1302 	}
1303 	if (!error && (tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)))
1304 		error = EIO;
1305 	splx(s);
1306 	return (error);
1307 }
1308 
1309 /*
1310  * Flush if successfully wait.
1311  */
1312 static int
1313 ttywflush(struct tty *tp)
1314 {
1315 	int error;
1316 
1317 	if ((error = ttywait(tp)) == 0)
1318 		ttyflush(tp, FREAD);
1319 	return (error);
1320 }
1321 
1322 /*
1323  * Flush tty read and/or write queues, notifying anyone waiting.
1324  */
1325 void
1326 ttyflush(struct tty *tp, int rw)
1327 {
1328 	int s;
1329 
1330 	s = spltty();
1331 #if 0
1332 again:
1333 #endif
1334 	if (rw & FWRITE) {
1335 		FLUSHQ(&tp->t_outq);
1336 		CLR(tp->t_state, TS_TTSTOP);
1337 	}
1338 	(*tp->t_stop)(tp, rw);
1339 	if (rw & FREAD) {
1340 		FLUSHQ(&tp->t_canq);
1341 		FLUSHQ(&tp->t_rawq);
1342 		CLR(tp->t_lflag, PENDIN);
1343 		tp->t_rocount = 0;
1344 		tp->t_rocol = 0;
1345 		CLR(tp->t_state, TS_LOCAL);
1346 		ttwakeup(tp);
1347 		if (ISSET(tp->t_state, TS_TBLOCK)) {
1348 			if (rw & FWRITE)
1349 				FLUSHQ(&tp->t_outq);
1350 			ttyunblock(tp);
1351 
1352 			/*
1353 			 * Don't let leave any state that might clobber the
1354 			 * next line discipline (although we should do more
1355 			 * to send the START char).  Not clearing the state
1356 			 * may have caused the "putc to a clist with no
1357 			 * reserved cblocks" panic/printf.
1358 			 */
1359 			CLR(tp->t_state, TS_TBLOCK);
1360 
1361 #if 0 /* forget it, sleeping isn't always safe and we don't know when it is */
1362 			if (ISSET(tp->t_iflag, IXOFF)) {
1363 				/*
1364 				 * XXX wait a bit in the hope that the stop
1365 				 * character (if any) will go out.  Waiting
1366 				 * isn't good since it allows races.  This
1367 				 * will be fixed when the stop character is
1368 				 * put in a special queue.  Don't bother with
1369 				 * the checks in ttywait() since the timeout
1370 				 * will save us.
1371 				 */
1372 				SET(tp->t_state, TS_SO_OCOMPLETE);
1373 				ttysleep(tp, TSA_OCOMPLETE(tp), TTOPRI,
1374 					 "ttyfls", hz / 10);
1375 				/*
1376 				 * Don't try sending the stop character again.
1377 				 */
1378 				CLR(tp->t_state, TS_TBLOCK);
1379 				goto again;
1380 			}
1381 #endif
1382 		}
1383 	}
1384 	if (rw & FWRITE) {
1385 		FLUSHQ(&tp->t_outq);
1386 		ttwwakeup(tp);
1387 	}
1388 	splx(s);
1389 }
1390 
1391 /*
1392  * Copy in the default termios characters.
1393  */
1394 void
1395 termioschars(struct termios *t)
1396 {
1397 
1398 	bcopy(ttydefchars, t->c_cc, sizeof t->c_cc);
1399 }
1400 
1401 /*
1402  * Old interface.
1403  */
1404 void
1405 ttychars(struct tty *tp)
1406 {
1407 
1408 	termioschars(&tp->t_termios);
1409 }
1410 
1411 /*
1412  * Handle input high water.  Send stop character for the IXOFF case.  Turn
1413  * on our input flow control bit and propagate the changes to the driver.
1414  * XXX the stop character should be put in a special high priority queue.
1415  */
1416 void
1417 ttyblock(struct tty *tp)
1418 {
1419 
1420 	SET(tp->t_state, TS_TBLOCK);
1421 	if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
1422 	    putc(tp->t_cc[VSTOP], &tp->t_outq) != 0)
1423 		CLR(tp->t_state, TS_TBLOCK);	/* try again later */
1424 	ttstart(tp);
1425 }
1426 
1427 /*
1428  * Handle input low water.  Send start character for the IXOFF case.  Turn
1429  * off our input flow control bit and propagate the changes to the driver.
1430  * XXX the start character should be put in a special high priority queue.
1431  */
1432 static void
1433 ttyunblock(struct tty *tp)
1434 {
1435 
1436 	CLR(tp->t_state, TS_TBLOCK);
1437 	if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTART] != _POSIX_VDISABLE &&
1438 	    putc(tp->t_cc[VSTART], &tp->t_outq) != 0)
1439 		SET(tp->t_state, TS_TBLOCK);	/* try again later */
1440 	ttstart(tp);
1441 }
1442 
1443 #ifdef notyet
1444 /* Not used by any current (i386) drivers. */
1445 /*
1446  * Restart after an inter-char delay.
1447  */
1448 void
1449 ttrstrt(void *tp_arg)
1450 {
1451 	struct tty *tp;
1452 	int s;
1453 
1454 	KASSERT(tp_arg != NULL, ("ttrstrt"));
1455 
1456 	tp = tp_arg;
1457 	s = spltty();
1458 
1459 	CLR(tp->t_state, TS_TIMEOUT);
1460 	ttstart(tp);
1461 
1462 	splx(s);
1463 }
1464 #endif
1465 
1466 int
1467 ttstart(struct tty *tp)
1468 {
1469 
1470 	if (tp->t_oproc != NULL)	/* XXX: Kludge for pty. */
1471 		(*tp->t_oproc)(tp);
1472 	return (0);
1473 }
1474 
1475 /*
1476  * "close" a line discipline
1477  */
1478 int
1479 ttylclose(struct tty *tp, int flag)
1480 {
1481 
1482 	if (flag & FNONBLOCK || ttywflush(tp))
1483 		ttyflush(tp, FREAD | FWRITE);
1484 	return (0);
1485 }
1486 
1487 /*
1488  * Handle modem control transition on a tty.
1489  * Flag indicates new state of carrier.
1490  * Returns 0 if the line should be turned off, otherwise 1.
1491  */
1492 int
1493 ttymodem(struct tty *tp, int flag)
1494 {
1495 
1496 	if (ISSET(tp->t_state, TS_CARR_ON) && ISSET(tp->t_cflag, MDMBUF)) {
1497 		/*
1498 		 * MDMBUF: do flow control according to carrier flag
1499 		 * XXX TS_CAR_OFLOW doesn't do anything yet.  TS_TTSTOP
1500 		 * works if IXON and IXANY are clear.
1501 		 */
1502 		if (flag) {
1503 			CLR(tp->t_state, TS_CAR_OFLOW);
1504 			CLR(tp->t_state, TS_TTSTOP);
1505 			ttstart(tp);
1506 		} else if (!ISSET(tp->t_state, TS_CAR_OFLOW)) {
1507 			SET(tp->t_state, TS_CAR_OFLOW);
1508 			SET(tp->t_state, TS_TTSTOP);
1509 			(*tp->t_stop)(tp, 0);
1510 		}
1511 	} else if (flag == 0) {
1512 		/*
1513 		 * Lost carrier.
1514 		 */
1515 		CLR(tp->t_state, TS_CARR_ON);
1516 		if (ISSET(tp->t_state, TS_ISOPEN) &&
1517 		    !ISSET(tp->t_cflag, CLOCAL)) {
1518 			SET(tp->t_state, TS_ZOMBIE);
1519 			CLR(tp->t_state, TS_CONNECTED);
1520 			if (tp->t_session) {
1521 				sx_slock(&proctree_lock);
1522 				if (tp->t_session->s_leader) {
1523 					struct proc *p;
1524 
1525 					p = tp->t_session->s_leader;
1526 					PROC_LOCK(p);
1527 					psignal(p, SIGHUP);
1528 					PROC_UNLOCK(p);
1529 				}
1530 				sx_sunlock(&proctree_lock);
1531 			}
1532 			ttyflush(tp, FREAD | FWRITE);
1533 			return (0);
1534 		}
1535 	} else {
1536 		/*
1537 		 * Carrier now on.
1538 		 */
1539 		SET(tp->t_state, TS_CARR_ON);
1540 		if (!ISSET(tp->t_state, TS_ZOMBIE))
1541 			SET(tp->t_state, TS_CONNECTED);
1542 		wakeup(TSA_CARR_ON(tp));
1543 		ttwakeup(tp);
1544 		ttwwakeup(tp);
1545 	}
1546 	return (1);
1547 }
1548 
1549 /*
1550  * Reinput pending characters after state switch
1551  * call at spltty().
1552  */
1553 static void
1554 ttypend(struct tty *tp)
1555 {
1556 	struct clist tq;
1557 	int c;
1558 
1559 	CLR(tp->t_lflag, PENDIN);
1560 	SET(tp->t_state, TS_TYPEN);
1561 	/*
1562 	 * XXX this assumes too much about clist internals.  It may even
1563 	 * fail if the cblock slush pool is empty.  We can't allocate more
1564 	 * cblocks here because we are called from an interrupt handler
1565 	 * and clist_alloc_cblocks() can wait.
1566 	 */
1567 	tq = tp->t_rawq;
1568 	bzero(&tp->t_rawq, sizeof tp->t_rawq);
1569 	tp->t_rawq.c_cbmax = tq.c_cbmax;
1570 	tp->t_rawq.c_cbreserved = tq.c_cbreserved;
1571 	while ((c = getc(&tq)) >= 0)
1572 		ttyinput(c, tp);
1573 	CLR(tp->t_state, TS_TYPEN);
1574 }
1575 
1576 /*
1577  * Process a read call on a tty device.
1578  */
1579 int
1580 ttread(struct tty *tp, struct uio *uio, int flag)
1581 {
1582 	struct clist *qp;
1583 	int c;
1584 	tcflag_t lflag;
1585 	cc_t *cc = tp->t_cc;
1586 	struct thread *td;
1587 	struct proc *p;
1588 	int s, first, error = 0;
1589 	int has_stime = 0, last_cc = 0;
1590 	long slp = 0;		/* XXX this should be renamed `timo'. */
1591 	struct timeval stime;
1592 	struct pgrp *pg;
1593 
1594 	td = curthread;
1595 	p = td->td_proc;
1596 loop:
1597 	s = spltty();
1598 	lflag = tp->t_lflag;
1599 	/*
1600 	 * take pending input first
1601 	 */
1602 	if (ISSET(lflag, PENDIN)) {
1603 		ttypend(tp);
1604 		splx(s);	/* reduce latency */
1605 		s = spltty();
1606 		lflag = tp->t_lflag;	/* XXX ttypend() clobbers it */
1607 	}
1608 
1609 	/*
1610 	 * Hang process if it's in the background.
1611 	 */
1612 	if (isbackground(p, tp)) {
1613 		splx(s);
1614 		sx_slock(&proctree_lock);
1615 		PROC_LOCK(p);
1616 		if (SIGISMEMBER(p->p_sigacts->ps_sigignore, SIGTTIN) ||
1617 		    SIGISMEMBER(td->td_sigmask, SIGTTIN) ||
1618 		    (p->p_flag & P_PPWAIT) || p->p_pgrp->pg_jobc == 0) {
1619 			PROC_UNLOCK(p);
1620 			sx_sunlock(&proctree_lock);
1621 			return (EIO);
1622 		}
1623 		pg = p->p_pgrp;
1624 		PROC_UNLOCK(p);
1625 		PGRP_LOCK(pg);
1626 		sx_sunlock(&proctree_lock);
1627 		pgsignal(pg, SIGTTIN, 1);
1628 		PGRP_UNLOCK(pg);
1629 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, "ttybg2", 0);
1630 		if (error)
1631 			return (error);
1632 		goto loop;
1633 	}
1634 
1635 	if (ISSET(tp->t_state, TS_ZOMBIE)) {
1636 		splx(s);
1637 		return (0);	/* EOF */
1638 	}
1639 
1640 	/*
1641 	 * If canonical, use the canonical queue,
1642 	 * else use the raw queue.
1643 	 *
1644 	 * (should get rid of clists...)
1645 	 */
1646 	qp = ISSET(lflag, ICANON) ? &tp->t_canq : &tp->t_rawq;
1647 
1648 	if (flag & IO_NDELAY) {
1649 		if (qp->c_cc > 0)
1650 			goto read;
1651 		if (!ISSET(lflag, ICANON) && cc[VMIN] == 0) {
1652 			splx(s);
1653 			return (0);
1654 		}
1655 		splx(s);
1656 		return (EWOULDBLOCK);
1657 	}
1658 	if (!ISSET(lflag, ICANON)) {
1659 		int m = cc[VMIN];
1660 		long t = cc[VTIME];
1661 		struct timeval timecopy;
1662 
1663 		/*
1664 		 * Check each of the four combinations.
1665 		 * (m > 0 && t == 0) is the normal read case.
1666 		 * It should be fairly efficient, so we check that and its
1667 		 * companion case (m == 0 && t == 0) first.
1668 		 * For the other two cases, we compute the target sleep time
1669 		 * into slp.
1670 		 */
1671 		if (t == 0) {
1672 			if (qp->c_cc < m)
1673 				goto sleep;
1674 			if (qp->c_cc > 0)
1675 				goto read;
1676 
1677 			/* m, t and qp->c_cc are all 0.  0 is enough input. */
1678 			splx(s);
1679 			return (0);
1680 		}
1681 		t *= 100000;		/* time in us */
1682 #define diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 1000000 + \
1683 			 ((t1).tv_usec - (t2).tv_usec))
1684 		if (m > 0) {
1685 			if (qp->c_cc <= 0)
1686 				goto sleep;
1687 			if (qp->c_cc >= m)
1688 				goto read;
1689 			getmicrotime(&timecopy);
1690 			if (!has_stime) {
1691 				/* first character, start timer */
1692 				has_stime = 1;
1693 				stime = timecopy;
1694 				slp = t;
1695 			} else if (qp->c_cc > last_cc) {
1696 				/* got a character, restart timer */
1697 				stime = timecopy;
1698 				slp = t;
1699 			} else {
1700 				/* nothing, check expiration */
1701 				slp = t - diff(timecopy, stime);
1702 				if (slp <= 0)
1703 					goto read;
1704 			}
1705 			last_cc = qp->c_cc;
1706 		} else {	/* m == 0 */
1707 			if (qp->c_cc > 0)
1708 				goto read;
1709 			getmicrotime(&timecopy);
1710 			if (!has_stime) {
1711 				has_stime = 1;
1712 				stime = timecopy;
1713 				slp = t;
1714 			} else {
1715 				slp = t - diff(timecopy, stime);
1716 				if (slp <= 0) {
1717 					/* Timed out, but 0 is enough input. */
1718 					splx(s);
1719 					return (0);
1720 				}
1721 			}
1722 		}
1723 #undef diff
1724 		/*
1725 		 * Rounding down may make us wake up just short
1726 		 * of the target, so we round up.
1727 		 * The formula is ceiling(slp * hz/1000000).
1728 		 * 32-bit arithmetic is enough for hz < 169.
1729 		 * XXX see tvtohz() for how to avoid overflow if hz
1730 		 * is large (divide by `tick' and/or arrange to
1731 		 * use tvtohz() if hz is large).
1732 		 */
1733 		slp = (long) (((u_long)slp * hz) + 999999) / 1000000;
1734 		goto sleep;
1735 	}
1736 	if (qp->c_cc <= 0) {
1737 sleep:
1738 		/*
1739 		 * There is no input, or not enough input and we can block.
1740 		 */
1741 		error = ttysleep(tp, TSA_HUP_OR_INPUT(tp), TTIPRI | PCATCH,
1742 				 ISSET(tp->t_state, TS_CONNECTED) ?
1743 				 "ttyin" : "ttyhup", (int)slp);
1744 		splx(s);
1745 		if (error == EWOULDBLOCK)
1746 			error = 0;
1747 		else if (error)
1748 			return (error);
1749 		/*
1750 		 * XXX what happens if another process eats some input
1751 		 * while we are asleep (not just here)?  It would be
1752 		 * safest to detect changes and reset our state variables
1753 		 * (has_stime and last_cc).
1754 		 */
1755 		slp = 0;
1756 		goto loop;
1757 	}
1758 read:
1759 	splx(s);
1760 	/*
1761 	 * Input present, check for input mapping and processing.
1762 	 */
1763 	first = 1;
1764 	if (ISSET(lflag, ICANON | ISIG))
1765 		goto slowcase;
1766 	for (;;) {
1767 		char ibuf[IBUFSIZ];
1768 		int icc;
1769 
1770 		icc = imin(uio->uio_resid, IBUFSIZ);
1771 		icc = q_to_b(qp, ibuf, icc);
1772 		if (icc <= 0) {
1773 			if (first)
1774 				goto loop;
1775 			break;
1776 		}
1777 		error = uiomove(ibuf, icc, uio);
1778 		/*
1779 		 * XXX if there was an error then we should ungetc() the
1780 		 * unmoved chars and reduce icc here.
1781 		 */
1782 		if (error)
1783 			break;
1784 		if (uio->uio_resid == 0)
1785 			break;
1786 		first = 0;
1787 	}
1788 	goto out;
1789 slowcase:
1790 	for (;;) {
1791 		c = getc(qp);
1792 		if (c < 0) {
1793 			if (first)
1794 				goto loop;
1795 			break;
1796 		}
1797 		/*
1798 		 * delayed suspend (^Y)
1799 		 */
1800 		if (CCEQ(cc[VDSUSP], c) &&
1801 		    ISSET(lflag, IEXTEN | ISIG) == (IEXTEN | ISIG)) {
1802 			if (tp->t_pgrp != NULL) {
1803 				PGRP_LOCK(tp->t_pgrp);
1804 				pgsignal(tp->t_pgrp, SIGTSTP, 1);
1805 				PGRP_UNLOCK(tp->t_pgrp);
1806 			}
1807 			if (first) {
1808 				error = ttysleep(tp, &lbolt, TTIPRI | PCATCH,
1809 						 "ttybg3", 0);
1810 				if (error)
1811 					break;
1812 				goto loop;
1813 			}
1814 			break;
1815 		}
1816 		/*
1817 		 * Interpret EOF only in canonical mode.
1818 		 */
1819 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
1820 			break;
1821 		/*
1822 		 * Give user character.
1823 		 */
1824 		error = ureadc(c, uio);
1825 		if (error)
1826 			/* XXX should ungetc(c, qp). */
1827 			break;
1828 		if (uio->uio_resid == 0)
1829 			break;
1830 		/*
1831 		 * In canonical mode check for a "break character"
1832 		 * marking the end of a "line of input".
1833 		 */
1834 		if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
1835 			break;
1836 		first = 0;
1837 	}
1838 
1839 out:
1840 	/*
1841 	 * Look to unblock input now that (presumably)
1842 	 * the input queue has gone down.
1843 	 */
1844 	s = spltty();
1845 	if (ISSET(tp->t_state, TS_TBLOCK) &&
1846 	    tp->t_rawq.c_cc + tp->t_canq.c_cc <= tp->t_ilowat)
1847 		ttyunblock(tp);
1848 	splx(s);
1849 
1850 	return (error);
1851 }
1852 
1853 /*
1854  * Check the output queue on tp for space for a kernel message (from uprintf
1855  * or tprintf).  Allow some space over the normal hiwater mark so we don't
1856  * lose messages due to normal flow control, but don't let the tty run amok.
1857  * Sleeps here are not interruptible, but we return prematurely if new signals
1858  * arrive.
1859  */
1860 int
1861 ttycheckoutq(struct tty *tp, int wait)
1862 {
1863 	int hiwat, s;
1864 	sigset_t oldmask;
1865 	struct thread *td;
1866 	struct proc *p;
1867 
1868 	td = curthread;
1869 	p = td->td_proc;
1870 	hiwat = tp->t_ohiwat;
1871 	SIGEMPTYSET(oldmask);
1872 	s = spltty();
1873 	if (wait) {
1874 		PROC_LOCK(p);
1875 		oldmask = td->td_siglist;
1876 		PROC_UNLOCK(p);
1877 	}
1878 	if (tp->t_outq.c_cc > hiwat + OBUFSIZ + 100)
1879 		while (tp->t_outq.c_cc > hiwat) {
1880 			ttstart(tp);
1881 			if (tp->t_outq.c_cc <= hiwat)
1882 				break;
1883 			if (!wait) {
1884 				splx(s);
1885 				return (0);
1886 			}
1887 			PROC_LOCK(p);
1888 			if (!SIGSETEQ(td->td_siglist, oldmask)) {
1889 				PROC_UNLOCK(p);
1890 				splx(s);
1891 				return (0);
1892 			}
1893 			PROC_UNLOCK(p);
1894 			SET(tp->t_state, TS_SO_OLOWAT);
1895 			tsleep(TSA_OLOWAT(tp), PZERO - 1, "ttoutq", hz);
1896 		}
1897 	splx(s);
1898 	return (1);
1899 }
1900 
1901 /*
1902  * Process a write call on a tty device.
1903  */
1904 int
1905 ttwrite(struct tty *tp, struct uio *uio, int flag)
1906 {
1907 	char *cp = NULL;
1908 	int cc, ce;
1909 	struct thread *td;
1910 	struct proc *p;
1911 	int i, hiwat, cnt, error, s;
1912 	char obuf[OBUFSIZ];
1913 
1914 	hiwat = tp->t_ohiwat;
1915 	cnt = uio->uio_resid;
1916 	error = 0;
1917 	cc = 0;
1918 	td = curthread;
1919 	p = td->td_proc;
1920 loop:
1921 	s = spltty();
1922 	if (ISSET(tp->t_state, TS_ZOMBIE)) {
1923 		splx(s);
1924 		if (uio->uio_resid == cnt)
1925 			error = EIO;
1926 		goto out;
1927 	}
1928 	if (!ISSET(tp->t_state, TS_CONNECTED)) {
1929 		if (flag & IO_NDELAY) {
1930 			splx(s);
1931 			error = EWOULDBLOCK;
1932 			goto out;
1933 		}
1934 		error = ttysleep(tp, TSA_CARR_ON(tp), TTIPRI | PCATCH,
1935 				 "ttydcd", 0);
1936 		splx(s);
1937 		if (error)
1938 			goto out;
1939 		goto loop;
1940 	}
1941 	splx(s);
1942 	/*
1943 	 * Hang the process if it's in the background.
1944 	 */
1945 	sx_slock(&proctree_lock);
1946 	PROC_LOCK(p);
1947 	if (isbackground(p, tp) &&
1948 	    ISSET(tp->t_lflag, TOSTOP) && !(p->p_flag & P_PPWAIT) &&
1949 	    !SIGISMEMBER(p->p_sigacts->ps_sigignore, SIGTTOU) &&
1950 	    !SIGISMEMBER(td->td_sigmask, SIGTTOU)) {
1951 		if (p->p_pgrp->pg_jobc == 0) {
1952 			PROC_UNLOCK(p);
1953 			sx_sunlock(&proctree_lock);
1954 			error = EIO;
1955 			goto out;
1956 		}
1957 		PROC_UNLOCK(p);
1958 		PGRP_LOCK(p->p_pgrp);
1959 		sx_sunlock(&proctree_lock);
1960 		pgsignal(p->p_pgrp, SIGTTOU, 1);
1961 		PGRP_UNLOCK(p->p_pgrp);
1962 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, "ttybg4", 0);
1963 		if (error)
1964 			goto out;
1965 		goto loop;
1966 	} else {
1967 		PROC_UNLOCK(p);
1968 		sx_sunlock(&proctree_lock);
1969 	}
1970 	/*
1971 	 * Process the user's data in at most OBUFSIZ chunks.  Perform any
1972 	 * output translation.  Keep track of high water mark, sleep on
1973 	 * overflow awaiting device aid in acquiring new space.
1974 	 */
1975 	while (uio->uio_resid > 0 || cc > 0) {
1976 		if (ISSET(tp->t_lflag, FLUSHO)) {
1977 			uio->uio_resid = 0;
1978 			return (0);
1979 		}
1980 		if (tp->t_outq.c_cc > hiwat)
1981 			goto ovhiwat;
1982 		/*
1983 		 * Grab a hunk of data from the user, unless we have some
1984 		 * leftover from last time.
1985 		 */
1986 		if (cc == 0) {
1987 			cc = imin(uio->uio_resid, OBUFSIZ);
1988 			cp = obuf;
1989 			error = uiomove(cp, cc, uio);
1990 			if (error) {
1991 				cc = 0;
1992 				break;
1993 			}
1994 		}
1995 		/*
1996 		 * If nothing fancy need be done, grab those characters we
1997 		 * can handle without any of ttyoutput's processing and
1998 		 * just transfer them to the output q.  For those chars
1999 		 * which require special processing (as indicated by the
2000 		 * bits in char_type), call ttyoutput.  After processing
2001 		 * a hunk of data, look for FLUSHO so ^O's will take effect
2002 		 * immediately.
2003 		 */
2004 		while (cc > 0) {
2005 			if (!ISSET(tp->t_oflag, OPOST))
2006 				ce = cc;
2007 			else {
2008 				ce = cc - scanc((u_int)cc, (u_char *)cp,
2009 						char_type, CCLASSMASK);
2010 				/*
2011 				 * If ce is zero, then we're processing
2012 				 * a special character through ttyoutput.
2013 				 */
2014 				if (ce == 0) {
2015 					tp->t_rocount = 0;
2016 					if (ttyoutput(*cp, tp) >= 0) {
2017 						/* No Clists, wait a bit. */
2018 						ttstart(tp);
2019 						if (flag & IO_NDELAY) {
2020 							error = EWOULDBLOCK;
2021 							goto out;
2022 						}
2023 						error = ttysleep(tp, &lbolt,
2024 								 TTOPRI|PCATCH,
2025 								 "ttybf1", 0);
2026 						if (error)
2027 							goto out;
2028 						goto loop;
2029 					}
2030 					cp++;
2031 					cc--;
2032 					if (ISSET(tp->t_lflag, FLUSHO) ||
2033 					    tp->t_outq.c_cc > hiwat)
2034 						goto ovhiwat;
2035 					continue;
2036 				}
2037 			}
2038 			/*
2039 			 * A bunch of normal characters have been found.
2040 			 * Transfer them en masse to the output queue and
2041 			 * continue processing at the top of the loop.
2042 			 * If there are any further characters in this
2043 			 * <= OBUFSIZ chunk, the first should be a character
2044 			 * requiring special handling by ttyoutput.
2045 			 */
2046 			tp->t_rocount = 0;
2047 			i = b_to_q(cp, ce, &tp->t_outq);
2048 			ce -= i;
2049 			tp->t_column += ce;
2050 			cp += ce, cc -= ce, tk_nout += ce;
2051 			tp->t_outcc += ce;
2052 			if (i > 0) {
2053 				/* No Clists, wait a bit. */
2054 				ttstart(tp);
2055 				if (flag & IO_NDELAY) {
2056 					error = EWOULDBLOCK;
2057 					goto out;
2058 				}
2059 				error = ttysleep(tp, &lbolt, TTOPRI | PCATCH,
2060 						 "ttybf2", 0);
2061 				if (error)
2062 					goto out;
2063 				goto loop;
2064 			}
2065 			if (ISSET(tp->t_lflag, FLUSHO) ||
2066 			    tp->t_outq.c_cc > hiwat)
2067 				break;
2068 		}
2069 		ttstart(tp);
2070 	}
2071 out:
2072 	/*
2073 	 * If cc is nonzero, we leave the uio structure inconsistent, as the
2074 	 * offset and iov pointers have moved forward, but it doesn't matter
2075 	 * (the call will either return short or restart with a new uio).
2076 	 */
2077 	uio->uio_resid += cc;
2078 	return (error);
2079 
2080 ovhiwat:
2081 	ttstart(tp);
2082 	s = spltty();
2083 	/*
2084 	 * This can only occur if FLUSHO is set in t_lflag,
2085 	 * or if ttstart/oproc is synchronous (or very fast).
2086 	 */
2087 	if (tp->t_outq.c_cc <= hiwat) {
2088 		splx(s);
2089 		goto loop;
2090 	}
2091 	if (flag & IO_NDELAY) {
2092 		splx(s);
2093 		uio->uio_resid += cc;
2094 		return (uio->uio_resid == cnt ? EWOULDBLOCK : 0);
2095 	}
2096 	SET(tp->t_state, TS_SO_OLOWAT);
2097 	error = ttysleep(tp, TSA_OLOWAT(tp), TTOPRI | PCATCH, "ttywri",
2098 			 tp->t_timeout);
2099 	splx(s);
2100 	if (error == EWOULDBLOCK)
2101 		error = EIO;
2102 	if (error)
2103 		goto out;
2104 	goto loop;
2105 }
2106 
2107 /*
2108  * Rubout one character from the rawq of tp
2109  * as cleanly as possible.
2110  */
2111 static void
2112 ttyrub(int c, struct tty *tp)
2113 {
2114 	char *cp;
2115 	int savecol;
2116 	int tabc, s;
2117 
2118 	if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
2119 		return;
2120 	CLR(tp->t_lflag, FLUSHO);
2121 	if (ISSET(tp->t_lflag, ECHOE)) {
2122 		if (tp->t_rocount == 0) {
2123 			/*
2124 			 * Screwed by ttwrite; retype
2125 			 */
2126 			ttyretype(tp);
2127 			return;
2128 		}
2129 		if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
2130 			ttyrubo(tp, 2);
2131 		else {
2132 			CLR(c, ~TTY_CHARMASK);
2133 			switch (CCLASS(c)) {
2134 			case ORDINARY:
2135 				ttyrubo(tp, 1);
2136 				break;
2137 			case BACKSPACE:
2138 			case CONTROL:
2139 			case NEWLINE:
2140 			case RETURN:
2141 			case VTAB:
2142 				if (ISSET(tp->t_lflag, ECHOCTL))
2143 					ttyrubo(tp, 2);
2144 				break;
2145 			case TAB:
2146 				if (tp->t_rocount < tp->t_rawq.c_cc) {
2147 					ttyretype(tp);
2148 					return;
2149 				}
2150 				s = spltty();
2151 				savecol = tp->t_column;
2152 				SET(tp->t_state, TS_CNTTB);
2153 				SET(tp->t_lflag, FLUSHO);
2154 				tp->t_column = tp->t_rocol;
2155 				cp = tp->t_rawq.c_cf;
2156 				if (cp)
2157 					tabc = *cp;	/* XXX FIX NEXTC */
2158 				for (; cp; cp = nextc(&tp->t_rawq, cp, &tabc))
2159 					ttyecho(tabc, tp);
2160 				CLR(tp->t_lflag, FLUSHO);
2161 				CLR(tp->t_state, TS_CNTTB);
2162 				splx(s);
2163 
2164 				/* savecol will now be length of the tab. */
2165 				savecol -= tp->t_column;
2166 				tp->t_column += savecol;
2167 				if (savecol > 8)
2168 					savecol = 8;	/* overflow screw */
2169 				while (--savecol >= 0)
2170 					(void)ttyoutput('\b', tp);
2171 				break;
2172 			default:			/* XXX */
2173 #define	PANICSTR	"ttyrub: would panic c = %d, val = %d\n"
2174 				(void)printf(PANICSTR, c, CCLASS(c));
2175 #ifdef notdef
2176 				panic(PANICSTR, c, CCLASS(c));
2177 #endif
2178 			}
2179 		}
2180 	} else if (ISSET(tp->t_lflag, ECHOPRT)) {
2181 		if (!ISSET(tp->t_state, TS_ERASE)) {
2182 			SET(tp->t_state, TS_ERASE);
2183 			(void)ttyoutput('\\', tp);
2184 		}
2185 		ttyecho(c, tp);
2186 	} else {
2187 		ttyecho(tp->t_cc[VERASE], tp);
2188 		/*
2189 		 * This code may be executed not only when an ERASE key
2190 		 * is pressed, but also when ^U (KILL) or ^W (WERASE) are.
2191 		 * So, I didn't think it was worthwhile to pass the extra
2192 		 * information (which would need an extra parameter,
2193 		 * changing every call) needed to distinguish the ERASE2
2194 		 * case from the ERASE.
2195 		 */
2196 	}
2197 	--tp->t_rocount;
2198 }
2199 
2200 /*
2201  * Back over cnt characters, erasing them.
2202  */
2203 static void
2204 ttyrubo(struct tty *tp, int cnt)
2205 {
2206 
2207 	while (cnt-- > 0) {
2208 		(void)ttyoutput('\b', tp);
2209 		(void)ttyoutput(' ', tp);
2210 		(void)ttyoutput('\b', tp);
2211 	}
2212 }
2213 
2214 /*
2215  * ttyretype --
2216  *	Reprint the rawq line.  Note, it is assumed that c_cc has already
2217  *	been checked.
2218  */
2219 static void
2220 ttyretype(struct tty *tp)
2221 {
2222 	char *cp;
2223 	int s, c;
2224 
2225 	/* Echo the reprint character. */
2226 	if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
2227 		ttyecho(tp->t_cc[VREPRINT], tp);
2228 
2229 	(void)ttyoutput('\n', tp);
2230 
2231 	/*
2232 	 * XXX
2233 	 * FIX: NEXTC IS BROKEN - DOESN'T CHECK QUOTE
2234 	 * BIT OF FIRST CHAR.
2235 	 */
2236 	s = spltty();
2237 	for (cp = tp->t_canq.c_cf, c = (cp != NULL ? *cp : 0);
2238 	    cp != NULL; cp = nextc(&tp->t_canq, cp, &c))
2239 		ttyecho(c, tp);
2240 	for (cp = tp->t_rawq.c_cf, c = (cp != NULL ? *cp : 0);
2241 	    cp != NULL; cp = nextc(&tp->t_rawq, cp, &c))
2242 		ttyecho(c, tp);
2243 	CLR(tp->t_state, TS_ERASE);
2244 	splx(s);
2245 
2246 	tp->t_rocount = tp->t_rawq.c_cc;
2247 	tp->t_rocol = 0;
2248 }
2249 
2250 /*
2251  * Echo a typed character to the terminal.
2252  */
2253 static void
2254 ttyecho(int c, struct tty *tp)
2255 {
2256 
2257 	if (!ISSET(tp->t_state, TS_CNTTB))
2258 		CLR(tp->t_lflag, FLUSHO);
2259 	if ((!ISSET(tp->t_lflag, ECHO) &&
2260 	     (c != '\n' || !ISSET(tp->t_lflag, ECHONL))) ||
2261 	    ISSET(tp->t_lflag, EXTPROC))
2262 		return;
2263 	if (ISSET(tp->t_lflag, ECHOCTL) &&
2264 	    ((ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n') ||
2265 	    ISSET(c, TTY_CHARMASK) == 0177)) {
2266 		(void)ttyoutput('^', tp);
2267 		CLR(c, ~TTY_CHARMASK);
2268 		if (c == 0177)
2269 			c = '?';
2270 		else
2271 			c += 'A' - 1;
2272 	}
2273 	(void)ttyoutput(c, tp);
2274 }
2275 
2276 /*
2277  * Wake up any readers on a tty.
2278  */
2279 void
2280 ttwakeup(struct tty *tp)
2281 {
2282 
2283 	if (SEL_WAITING(&tp->t_rsel))
2284 		selwakeuppri(&tp->t_rsel, TTIPRI);
2285 	if (ISSET(tp->t_state, TS_ASYNC) && tp->t_sigio != NULL)
2286 		pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
2287 	wakeup(TSA_HUP_OR_INPUT(tp));
2288 	KNOTE(&tp->t_rsel.si_note, 0);
2289 }
2290 
2291 /*
2292  * Wake up any writers on a tty.
2293  */
2294 void
2295 ttwwakeup(struct tty *tp)
2296 {
2297 
2298 	if (SEL_WAITING(&tp->t_wsel) && tp->t_outq.c_cc <= tp->t_olowat)
2299 		selwakeuppri(&tp->t_wsel, TTOPRI);
2300 	if (ISSET(tp->t_state, TS_ASYNC) && tp->t_sigio != NULL)
2301 		pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
2302 	if (ISSET(tp->t_state, TS_BUSY | TS_SO_OCOMPLETE) ==
2303 	    TS_SO_OCOMPLETE && tp->t_outq.c_cc == 0) {
2304 		CLR(tp->t_state, TS_SO_OCOMPLETE);
2305 		wakeup(TSA_OCOMPLETE(tp));
2306 	}
2307 	if (ISSET(tp->t_state, TS_SO_OLOWAT) &&
2308 	    tp->t_outq.c_cc <= tp->t_olowat) {
2309 		CLR(tp->t_state, TS_SO_OLOWAT);
2310 		wakeup(TSA_OLOWAT(tp));
2311 	}
2312 	KNOTE(&tp->t_wsel.si_note, 0);
2313 }
2314 
2315 /*
2316  * Look up a code for a specified speed in a conversion table;
2317  * used by drivers to map software speed values to hardware parameters.
2318  */
2319 int
2320 ttspeedtab(int speed, struct speedtab *table)
2321 {
2322 
2323 	for ( ; table->sp_speed != -1; table++)
2324 		if (table->sp_speed == speed)
2325 			return (table->sp_code);
2326 	return (-1);
2327 }
2328 
2329 /*
2330  * Set input and output watermarks and buffer sizes.  For input, the
2331  * high watermark is about one second's worth of input above empty, the
2332  * low watermark is slightly below high water, and the buffer size is a
2333  * driver-dependent amount above high water.  For output, the watermarks
2334  * are near the ends of the buffer, with about 1 second's worth of input
2335  * between them.  All this only applies to the standard line discipline.
2336  */
2337 void
2338 ttsetwater(struct tty *tp)
2339 {
2340 	int cps, ttmaxhiwat, x;
2341 
2342 	/* Input. */
2343 	clist_alloc_cblocks(&tp->t_canq, TTYHOG, 512);
2344 	switch (tp->t_ispeedwat) {
2345 	case (speed_t)-1:
2346 		cps = tp->t_ispeed / 10;
2347 		break;
2348 	case 0:
2349 		/*
2350 		 * This case is for old drivers that don't know about
2351 		 * t_ispeedwat.  Arrange for them to get the old buffer
2352 		 * sizes and watermarks.
2353 		 */
2354 		cps = TTYHOG - 2 * 256;
2355 		tp->t_ififosize = 2 * 256;
2356 		break;
2357 	default:
2358 		cps = tp->t_ispeedwat / 10;
2359 		break;
2360 	}
2361 	tp->t_ihiwat = cps;
2362 	tp->t_ilowat = 7 * cps / 8;
2363 	x = cps + tp->t_ififosize;
2364 	clist_alloc_cblocks(&tp->t_rawq, x, x);
2365 
2366 	/* Output. */
2367 	switch (tp->t_ospeedwat) {
2368 	case (speed_t)-1:
2369 		cps = tp->t_ospeed / 10;
2370 		ttmaxhiwat = 2 * TTMAXHIWAT;
2371 		break;
2372 	case 0:
2373 		cps = tp->t_ospeed / 10;
2374 		ttmaxhiwat = TTMAXHIWAT;
2375 		break;
2376 	default:
2377 		cps = tp->t_ospeedwat / 10;
2378 		ttmaxhiwat = 8 * TTMAXHIWAT;
2379 		break;
2380 	}
2381 #define CLAMP(x, h, l)	((x) > h ? h : ((x) < l) ? l : (x))
2382 	tp->t_olowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
2383 	x += cps;
2384 	x = CLAMP(x, ttmaxhiwat, TTMINHIWAT);	/* XXX clamps are too magic */
2385 	tp->t_ohiwat = roundup(x, CBSIZE);	/* XXX for compat */
2386 	x = imax(tp->t_ohiwat, TTMAXHIWAT);	/* XXX for compat/safety */
2387 	x += OBUFSIZ + 100;
2388 	clist_alloc_cblocks(&tp->t_outq, x, x);
2389 #undef	CLAMP
2390 }
2391 
2392 /*
2393  * Report on state of foreground process group.
2394  */
2395 void
2396 ttyinfo(struct tty *tp)
2397 {
2398 	struct timeval utime, stime;
2399 	struct proc *p, *pick;
2400 	struct thread *td;
2401 	const char *stateprefix, *state;
2402 	long rss;
2403 	int load, pctcpu;
2404 
2405 	if (ttycheckoutq(tp,0) == 0)
2406 		return;
2407 
2408 	/* Print load average. */
2409 	load = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
2410 	ttyprintf(tp, "load: %d.%02d ", load / 100, load % 100);
2411 
2412 	/*
2413 	 * On return following a ttyprintf(), we set tp->t_rocount to 0 so
2414 	 * that pending input will be retyped on BS.
2415 	 */
2416 	if (tp->t_session == NULL) {
2417 		ttyprintf(tp, "not a controlling terminal\n");
2418 		tp->t_rocount = 0;
2419 		return;
2420 	}
2421 	if (tp->t_pgrp == NULL) {
2422 		ttyprintf(tp, "no foreground process group\n");
2423 		tp->t_rocount = 0;
2424 		return;
2425 	}
2426 	PGRP_LOCK(tp->t_pgrp);
2427 	if ((p = LIST_FIRST(&tp->t_pgrp->pg_members)) == 0) {
2428 		PGRP_UNLOCK(tp->t_pgrp);
2429 		ttyprintf(tp, "empty foreground process group\n");
2430 		tp->t_rocount = 0;
2431 		return;
2432 	}
2433 
2434 	/*
2435 	 * Pick the most interesting process and copy some of its
2436 	 * state for printing later.  sched_lock must be held for
2437 	 * most parts of this.  Holding it throughout is simplest
2438 	 * and prevents even unimportant inconsistencies in the
2439 	 * copy of the state, but may increase interrupt latency
2440 	 * too much.
2441 	 */
2442 	mtx_lock_spin(&sched_lock);
2443 	for (pick = NULL; p != 0; p = LIST_NEXT(p, p_pglist))
2444 		if (proc_compare(pick, p))
2445 			pick = p;
2446 	PGRP_UNLOCK(tp->t_pgrp);
2447 
2448 	td = FIRST_THREAD_IN_PROC(pick);	/* XXXKSE */
2449 #if 0
2450 	KASSERT(td != NULL, ("ttyinfo: no thread"));
2451 #else
2452 	if (td == NULL) {
2453 		mtx_unlock_spin(&sched_lock);
2454 		ttyprintf(tp, "foreground process without thread\n");
2455 		tp->t_rocount = 0;
2456 		return;
2457 	}
2458 #endif
2459 	stateprefix = "";
2460 	if (TD_IS_RUNNING(td))
2461 		state = "running";
2462 	else if (TD_ON_RUNQ(td) || TD_CAN_RUN(td))
2463 		state = "runnable";
2464 	else if (TD_IS_SLEEPING(td)) {
2465 		/* XXX: If we're sleeping, are we ever not in a queue? */
2466 		if (TD_ON_SLEEPQ(td))
2467 			state = td->td_wmesg;
2468 		else
2469 			state = "sleeping without queue";
2470 	} else if (TD_ON_LOCK(td)) {
2471 		state = td->td_lockname;
2472 		stateprefix = "*";
2473 	} else if (TD_IS_SUSPENDED(td))
2474 		state = "suspended";
2475 	else if (TD_AWAITING_INTR(td))
2476 		state = "intrwait";
2477 	else
2478 		state = "unknown";
2479 	calcru(pick, &utime, &stime, NULL);
2480 	pctcpu = (sched_pctcpu(td) * 10000 + FSCALE / 2) >> FSHIFT;
2481 	if (pick->p_state == PRS_NEW || pick->p_state == PRS_ZOMBIE)
2482 		rss = 0;
2483 	else
2484 		rss = pgtok(vmspace_resident_count(pick->p_vmspace));
2485 	mtx_unlock_spin(&sched_lock);
2486 
2487 	/* Print command, pid, state, utime, stime, %cpu, and rss. */
2488 	ttyprintf(tp,
2489 	    " cmd: %s %d [%s%s] %ld.%02ldu %ld.%02lds %d%% %ldk\n",
2490 	    pick->p_comm, pick->p_pid, stateprefix, state,
2491 	    (long)utime.tv_sec, utime.tv_usec / 10000,
2492 	    (long)stime.tv_sec, stime.tv_usec / 10000,
2493 	    pctcpu / 100, rss);
2494 	tp->t_rocount = 0;
2495 }
2496 
2497 /*
2498  * Returns 1 if p2 is "better" than p1
2499  *
2500  * The algorithm for picking the "interesting" process is thus:
2501  *
2502  *	1) Only foreground processes are eligible - implied.
2503  *	2) Runnable processes are favored over anything else.  The runner
2504  *	   with the highest cpu utilization is picked (p_estcpu).  Ties are
2505  *	   broken by picking the highest pid.
2506  *	3) The sleeper with the shortest sleep time is next.  With ties,
2507  *	   we pick out just "short-term" sleepers (P_SINTR == 0).
2508  *	4) Further ties are broken by picking the highest pid.
2509  */
2510 #define ISRUN(p, val)						\
2511 do {								\
2512 	struct thread *td;					\
2513 	val = 0;						\
2514 	FOREACH_THREAD_IN_PROC(p, td) {				\
2515 		if (TD_ON_RUNQ(td) ||				\
2516 		    TD_IS_RUNNING(td)) {			\
2517 			val = 1;				\
2518 			break;					\
2519 		}						\
2520 	}							\
2521 } while (0)
2522 
2523 #define TESTAB(a, b)    ((a)<<1 | (b))
2524 #define ONLYA   2
2525 #define ONLYB   1
2526 #define BOTH    3
2527 
2528 static int
2529 proc_compare(struct proc *p1, struct proc *p2)
2530 {
2531 
2532 	int esta, estb;
2533 	struct ksegrp *kg;
2534 	mtx_assert(&sched_lock, MA_OWNED);
2535 	if (p1 == NULL)
2536 		return (1);
2537 
2538 	ISRUN(p1, esta);
2539 	ISRUN(p2, estb);
2540 
2541 	/*
2542 	 * see if at least one of them is runnable
2543 	 */
2544 	switch (TESTAB(esta, estb)) {
2545 	case ONLYA:
2546 		return (0);
2547 	case ONLYB:
2548 		return (1);
2549 	case BOTH:
2550 		/*
2551 		 * tie - favor one with highest recent cpu utilization
2552 		 */
2553 		esta = estb = 0;
2554 		FOREACH_KSEGRP_IN_PROC(p1,kg) {
2555 			esta += kg->kg_estcpu;
2556 		}
2557 		FOREACH_KSEGRP_IN_PROC(p2,kg) {
2558 			estb += kg->kg_estcpu;
2559 		}
2560 		if (estb > esta)
2561 			return (1);
2562 		if (esta > estb)
2563 			return (0);
2564 		return (p2->p_pid > p1->p_pid);	/* tie - return highest pid */
2565 	}
2566 	/*
2567 	 * weed out zombies
2568 	 */
2569 	switch (TESTAB(p1->p_state == PRS_ZOMBIE, p2->p_state == PRS_ZOMBIE)) {
2570 	case ONLYA:
2571 		return (1);
2572 	case ONLYB:
2573 		return (0);
2574 	case BOTH:
2575 		return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
2576 	}
2577 
2578 #if 0 /* XXXKSE */
2579 	/*
2580 	 * pick the one with the smallest sleep time
2581 	 */
2582 	if (p2->p_slptime > p1->p_slptime)
2583 		return (0);
2584 	if (p1->p_slptime > p2->p_slptime)
2585 		return (1);
2586 	/*
2587 	 * favor one sleeping in a non-interruptible sleep
2588 	 */
2589 	if (p1->p_sflag & PS_SINTR && (p2->p_sflag & PS_SINTR) == 0)
2590 		return (1);
2591 	if (p2->p_sflag & PS_SINTR && (p1->p_sflag & PS_SINTR) == 0)
2592 		return (0);
2593 #endif
2594 	return (p2->p_pid > p1->p_pid);		/* tie - return highest pid */
2595 }
2596 
2597 /*
2598  * Output char to tty; console putchar style.
2599  */
2600 int
2601 tputchar(int c, struct tty *tp)
2602 {
2603 	int s;
2604 
2605 	s = spltty();
2606 	if (!ISSET(tp->t_state, TS_CONNECTED)) {
2607 		splx(s);
2608 		return (-1);
2609 	}
2610 	if (c == '\n')
2611 		(void)ttyoutput('\r', tp);
2612 	(void)ttyoutput(c, tp);
2613 	ttstart(tp);
2614 	splx(s);
2615 	return (0);
2616 }
2617 
2618 /*
2619  * Sleep on chan, returning ERESTART if tty changed while we napped and
2620  * returning any errors (e.g. EINTR/EWOULDBLOCK) reported by tsleep.  If
2621  * the tty is revoked, restarting a pending call will redo validation done
2622  * at the start of the call.
2623  */
2624 int
2625 ttysleep(struct tty *tp, void *chan, int pri, char *wmesg, int timo)
2626 {
2627 	int error;
2628 	int gen;
2629 
2630 	gen = tp->t_gen;
2631 	error = tsleep(chan, pri, wmesg, timo);
2632 	if (error)
2633 		return (error);
2634 	return (tp->t_gen == gen ? 0 : ERESTART);
2635 }
2636 
2637 /*
2638  * Allocate a tty struct.  Clists in the struct will be allocated by
2639  * ttyopen().
2640  */
2641 struct tty *
2642 ttymalloc(struct tty *tp)
2643 {
2644 
2645 	if (tp)
2646 		return(tp);
2647 	tp = malloc(sizeof *tp, M_TTYS, M_WAITOK | M_ZERO);
2648 	ttyregister(tp);
2649 	return (tp);
2650 }
2651 
2652 #if 0 /* XXX not yet usable: session leader holds a ref (see kern_exit.c). */
2653 /*
2654  * Free a tty struct.  Clists in the struct should have been freed by
2655  * ttyclose().
2656  */
2657 void
2658 ttyfree(struct tty *tp)
2659 {
2660 	free(tp, M_TTYS);
2661 }
2662 #endif /* 0 */
2663 
2664 void
2665 ttyregister(struct tty *tp)
2666 {
2667 	tp->t_timeout = -1;
2668 	SLIST_INSERT_HEAD(&tty_list, tp, t_list);
2669 }
2670 
2671 static int
2672 sysctl_kern_ttys(SYSCTL_HANDLER_ARGS)
2673 {
2674 	struct tty *tp;
2675 	struct xtty xt;
2676 	int error;
2677 
2678 	SLIST_FOREACH(tp, &tty_list, t_list) {
2679 		bzero(&xt, sizeof xt);
2680 		xt.xt_size = sizeof xt;
2681 #define XT_COPY(field) xt.xt_##field = tp->t_##field
2682 		xt.xt_rawcc = tp->t_rawq.c_cc;
2683 		xt.xt_cancc = tp->t_canq.c_cc;
2684 		xt.xt_outcc = tp->t_outq.c_cc;
2685 		XT_COPY(line);
2686 		if (tp->t_dev)
2687 			xt.xt_dev = dev2udev(tp->t_dev);
2688 		XT_COPY(state);
2689 		XT_COPY(flags);
2690 		XT_COPY(timeout);
2691 		if (tp->t_pgrp)
2692 			xt.xt_pgid = tp->t_pgrp->pg_id;
2693 		if (tp->t_session)
2694 			xt.xt_sid = tp->t_session->s_sid;
2695 		XT_COPY(termios);
2696 		XT_COPY(winsize);
2697 		XT_COPY(column);
2698 		XT_COPY(rocount);
2699 		XT_COPY(rocol);
2700 		XT_COPY(ififosize);
2701 		XT_COPY(ihiwat);
2702 		XT_COPY(ilowat);
2703 		XT_COPY(ispeedwat);
2704 		XT_COPY(ohiwat);
2705 		XT_COPY(olowat);
2706 		XT_COPY(ospeedwat);
2707 #undef XT_COPY
2708 		error = SYSCTL_OUT(req, &xt, sizeof xt);
2709 		if (error)
2710 			return (error);
2711 	}
2712 	return (0);
2713 }
2714 
2715 SYSCTL_PROC(_kern, OID_AUTO, ttys, CTLTYPE_OPAQUE|CTLFLAG_RD,
2716 	0, 0, sysctl_kern_ttys, "S,xtty", "All ttys");
2717 SYSCTL_LONG(_kern, OID_AUTO, tty_nin, CTLFLAG_RD,
2718 	&tk_nin, 0, "Total TTY in characters");
2719 SYSCTL_LONG(_kern, OID_AUTO, tty_nout, CTLFLAG_RD,
2720 	&tk_nout, 0, "Total TTY out characters");
2721 
2722 void
2723 nottystop(struct tty *tp, int rw)
2724 {
2725 
2726 	return;
2727 }
2728 
2729 int
2730 ttyread(dev_t dev, struct uio *uio, int flag)
2731 {
2732 	struct tty *tp;
2733 
2734 	KASSERT(devsw(dev)->d_flags & D_TTY,
2735 	    ("ttyread() called on non D_TTY device (%s)", devtoname(dev)));
2736 	tp = dev->si_tty;
2737 	KASSERT(tp != NULL,
2738 	    ("ttyread(): no tty pointer on device (%s)", devtoname(dev)));
2739 	if (tp == NULL)
2740 		return (ENODEV);
2741 	return ((*linesw[tp->t_line].l_read)(tp, uio, flag));
2742 }
2743 
2744 int
2745 ttywrite(dev_t dev, struct uio *uio, int flag)
2746 {
2747 	struct tty *tp;
2748 
2749 	KASSERT(devsw(dev)->d_flags & D_TTY,
2750 	    ("ttywrite() called on non D_TTY device (%s)", devtoname(dev)));
2751 	tp = dev->si_tty;
2752 	KASSERT(tp != NULL,
2753 	    ("ttywrite(): no tty pointer on device (%s)", devtoname(dev)));
2754 	if (tp == NULL)
2755 		return (ENODEV);
2756 	return ((*linesw[tp->t_line].l_write)(tp, uio, flag));
2757 }
2758