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