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