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