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