tty.c revision 72576
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 72576 2001-02-17 19:40:22Z jlemon $
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 (putc('\r', &tp->t_outq))
671			return (c);
672	}
673	tk_nout++;
674	tp->t_outcc++;
675	if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
676		return (c);
677
678	col = tp->t_column;
679	switch (CCLASS(c)) {
680	case BACKSPACE:
681		if (col > 0)
682			--col;
683		break;
684	case CONTROL:
685		break;
686	case NEWLINE:
687	case RETURN:
688		col = 0;
689		break;
690	case ORDINARY:
691		++col;
692		break;
693	case TAB:
694		col = (col + 8) & ~7;
695		break;
696	}
697	tp->t_column = col;
698	return (-1);
699}
700
701/*
702 * Ioctls for all tty devices.  Called after line-discipline specific ioctl
703 * has been called to do discipline-specific functions and/or reject any
704 * of these ioctl commands.
705 */
706/* ARGSUSED */
707int
708ttioctl(tp, cmd, data, flag)
709	register struct tty *tp;
710	u_long cmd;
711	int flag;
712	void *data;
713{
714	register struct proc *p;
715	int s, error;
716
717	p = curproc;			/* XXX */
718
719	/* If the ioctl involves modification, hang if in the background. */
720	switch (cmd) {
721	case  TIOCCBRK:
722	case  TIOCCONS:
723	case  TIOCDRAIN:
724	case  TIOCEXCL:
725	case  TIOCFLUSH:
726#ifdef TIOCHPCL
727	case  TIOCHPCL:
728#endif
729	case  TIOCNXCL:
730	case  TIOCSBRK:
731	case  TIOCSCTTY:
732	case  TIOCSDRAINWAIT:
733	case  TIOCSETA:
734	case  TIOCSETAF:
735	case  TIOCSETAW:
736	case  TIOCSETD:
737	case  TIOCSPGRP:
738	case  TIOCSTART:
739	case  TIOCSTAT:
740	case  TIOCSTI:
741	case  TIOCSTOP:
742	case  TIOCSWINSZ:
743#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
744	case  TIOCLBIC:
745	case  TIOCLBIS:
746	case  TIOCLSET:
747	case  TIOCSETC:
748	case OTIOCSETD:
749	case  TIOCSETN:
750	case  TIOCSETP:
751	case  TIOCSLTC:
752#endif
753		while (isbackground(p, tp) && !(p->p_flag & P_PPWAIT) &&
754		    !SIGISMEMBER(p->p_sigignore, SIGTTOU) &&
755		    !SIGISMEMBER(p->p_sigmask, SIGTTOU)) {
756			if (p->p_pgrp->pg_jobc == 0)
757				return (EIO);
758			pgsignal(p->p_pgrp, SIGTTOU, 1);
759			error = ttysleep(tp, &lbolt, TTOPRI | PCATCH, "ttybg1",
760					 0);
761			if (error)
762				return (error);
763		}
764		break;
765	}
766
767	switch (cmd) {			/* Process the ioctl. */
768	case FIOASYNC:			/* set/clear async i/o */
769		s = spltty();
770		if (*(int *)data)
771			SET(tp->t_state, TS_ASYNC);
772		else
773			CLR(tp->t_state, TS_ASYNC);
774		splx(s);
775		break;
776	case FIONBIO:			/* set/clear non-blocking i/o */
777		break;			/* XXX: delete. */
778	case FIONREAD:			/* get # bytes to read */
779		s = spltty();
780		*(int *)data = ttnread(tp);
781		splx(s);
782		break;
783
784	case FIOSETOWN:
785		/*
786		 * Policy -- Don't allow FIOSETOWN on someone else's
787		 *           controlling tty
788		 */
789		if (tp->t_session != NULL && !isctty(p, tp))
790			return (ENOTTY);
791
792		error = fsetown(*(int *)data, &tp->t_sigio);
793		if (error)
794			return (error);
795		break;
796	case FIOGETOWN:
797		if (tp->t_session != NULL && !isctty(p, tp))
798			return (ENOTTY);
799		*(int *)data = fgetown(tp->t_sigio);
800		break;
801
802	case TIOCEXCL:			/* set exclusive use of tty */
803		s = spltty();
804		SET(tp->t_state, TS_XCLUDE);
805		splx(s);
806		break;
807	case TIOCFLUSH: {		/* flush buffers */
808		register int flags = *(int *)data;
809
810		if (flags == 0)
811			flags = FREAD | FWRITE;
812		else
813			flags &= FREAD | FWRITE;
814		ttyflush(tp, flags);
815		break;
816	}
817	case TIOCCONS:			/* become virtual console */
818		if (*(int *)data) {
819			if (constty && constty != tp &&
820			    ISSET(constty->t_state, TS_CONNECTED))
821				return (EBUSY);
822#ifndef	UCONSOLE
823			if ((error = suser(p)) != 0)
824				return (error);
825#endif
826			constty = tp;
827		} else if (tp == constty)
828			constty = NULL;
829		break;
830	case TIOCDRAIN:			/* wait till output drained */
831		error = ttywait(tp);
832		if (error)
833			return (error);
834		break;
835	case TIOCGETA: {		/* get termios struct */
836		struct termios *t = (struct termios *)data;
837
838		bcopy(&tp->t_termios, t, sizeof(struct termios));
839		break;
840	}
841	case TIOCGETD:			/* get line discipline */
842		*(int *)data = tp->t_line;
843		break;
844	case TIOCGWINSZ:		/* get window size */
845		*(struct winsize *)data = tp->t_winsize;
846		break;
847	case TIOCGPGRP:			/* get pgrp of tty */
848		if (!isctty(p, tp))
849			return (ENOTTY);
850		*(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
851		break;
852#ifdef TIOCHPCL
853	case TIOCHPCL:			/* hang up on last close */
854		s = spltty();
855		SET(tp->t_cflag, HUPCL);
856		splx(s);
857		break;
858#endif
859	case TIOCNXCL:			/* reset exclusive use of tty */
860		s = spltty();
861		CLR(tp->t_state, TS_XCLUDE);
862		splx(s);
863		break;
864	case TIOCOUTQ:			/* output queue size */
865		*(int *)data = tp->t_outq.c_cc;
866		break;
867	case TIOCSETA:			/* set termios struct */
868	case TIOCSETAW:			/* drain output, set */
869	case TIOCSETAF: {		/* drn out, fls in, set */
870		register struct termios *t = (struct termios *)data;
871
872		if (t->c_ispeed == 0)
873			t->c_ispeed = t->c_ospeed;
874		if (t->c_ispeed == 0)
875			t->c_ispeed = tp->t_ospeed;
876		if (t->c_ispeed == 0)
877			return (EINVAL);
878		s = spltty();
879		if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
880			error = ttywait(tp);
881			if (error) {
882				splx(s);
883				return (error);
884			}
885			if (cmd == TIOCSETAF)
886				ttyflush(tp, FREAD);
887		}
888		if (!ISSET(t->c_cflag, CIGNORE)) {
889			/*
890			 * Set device hardware.
891			 */
892			if (tp->t_param && (error = (*tp->t_param)(tp, t))) {
893				splx(s);
894				return (error);
895			}
896			if (ISSET(t->c_cflag, CLOCAL) &&
897			    !ISSET(tp->t_cflag, CLOCAL)) {
898				/*
899				 * XXX disconnections would be too hard to
900				 * get rid of without this kludge.  The only
901				 * way to get rid of controlling terminals
902				 * is to exit from the session leader.
903				 */
904				CLR(tp->t_state, TS_ZOMBIE);
905
906				wakeup(TSA_CARR_ON(tp));
907				ttwakeup(tp);
908				ttwwakeup(tp);
909			}
910			if ((ISSET(tp->t_state, TS_CARR_ON) ||
911			     ISSET(t->c_cflag, CLOCAL)) &&
912			    !ISSET(tp->t_state, TS_ZOMBIE))
913				SET(tp->t_state, TS_CONNECTED);
914			else
915				CLR(tp->t_state, TS_CONNECTED);
916			tp->t_cflag = t->c_cflag;
917			tp->t_ispeed = t->c_ispeed;
918			if (t->c_ospeed != 0)
919				tp->t_ospeed = t->c_ospeed;
920			ttsetwater(tp);
921		}
922		if (ISSET(t->c_lflag, ICANON) != ISSET(tp->t_lflag, ICANON) &&
923		    cmd != TIOCSETAF) {
924			if (ISSET(t->c_lflag, ICANON))
925				SET(tp->t_lflag, PENDIN);
926			else {
927				/*
928				 * XXX we really shouldn't allow toggling
929				 * ICANON while we're in a non-termios line
930				 * discipline.  Now we have to worry about
931				 * panicing for a null queue.
932				 */
933				if (tp->t_canq.c_cbreserved > 0 &&
934				    tp->t_rawq.c_cbreserved > 0) {
935					catq(&tp->t_rawq, &tp->t_canq);
936					/*
937					 * XXX the queue limits may be
938					 * different, so the old queue
939					 * swapping method no longer works.
940					 */
941					catq(&tp->t_canq, &tp->t_rawq);
942				}
943				CLR(tp->t_lflag, PENDIN);
944			}
945			ttwakeup(tp);
946		}
947		tp->t_iflag = t->c_iflag;
948		tp->t_oflag = t->c_oflag;
949		/*
950		 * Make the EXTPROC bit read only.
951		 */
952		if (ISSET(tp->t_lflag, EXTPROC))
953			SET(t->c_lflag, EXTPROC);
954		else
955			CLR(t->c_lflag, EXTPROC);
956		tp->t_lflag = t->c_lflag | ISSET(tp->t_lflag, PENDIN);
957		if (t->c_cc[VMIN] != tp->t_cc[VMIN] ||
958		    t->c_cc[VTIME] != tp->t_cc[VTIME])
959			ttwakeup(tp);
960		bcopy(t->c_cc, tp->t_cc, sizeof(t->c_cc));
961		splx(s);
962		break;
963	}
964	case TIOCSETD: {		/* set line discipline */
965		register int t = *(int *)data;
966		dev_t device = tp->t_dev;
967
968		if ((u_int)t >= nlinesw)
969			return (ENXIO);
970		if (t != tp->t_line) {
971			s = spltty();
972			(*linesw[tp->t_line].l_close)(tp, flag);
973			error = (*linesw[t].l_open)(device, tp);
974			if (error) {
975				(void)(*linesw[tp->t_line].l_open)(device, tp);
976				splx(s);
977				return (error);
978			}
979			tp->t_line = t;
980			splx(s);
981		}
982		break;
983	}
984	case TIOCSTART:			/* start output, like ^Q */
985		s = spltty();
986		if (ISSET(tp->t_state, TS_TTSTOP) ||
987		    ISSET(tp->t_lflag, FLUSHO)) {
988			CLR(tp->t_lflag, FLUSHO);
989			CLR(tp->t_state, TS_TTSTOP);
990			ttstart(tp);
991		}
992		splx(s);
993		break;
994	case TIOCSTI:			/* simulate terminal input */
995		if ((flag & FREAD) == 0 && suser(p))
996			return (EPERM);
997		if (!isctty(p, tp) && suser(p))
998			return (EACCES);
999		s = spltty();
1000		(*linesw[tp->t_line].l_rint)(*(u_char *)data, tp);
1001		splx(s);
1002		break;
1003	case TIOCSTOP:			/* stop output, like ^S */
1004		s = spltty();
1005		if (!ISSET(tp->t_state, TS_TTSTOP)) {
1006			SET(tp->t_state, TS_TTSTOP);
1007			(*tp->t_stop)(tp, 0);
1008		}
1009		splx(s);
1010		break;
1011	case TIOCSCTTY:			/* become controlling tty */
1012		/* Session ctty vnode pointer set in vnode layer. */
1013		if (!SESS_LEADER(p) ||
1014		    ((p->p_session->s_ttyvp || tp->t_session) &&
1015		    (tp->t_session != p->p_session)))
1016			return (EPERM);
1017		tp->t_session = p->p_session;
1018		tp->t_pgrp = p->p_pgrp;
1019		p->p_session->s_ttyp = tp;
1020		p->p_flag |= P_CONTROLT;
1021		break;
1022	case TIOCSPGRP: {		/* set pgrp of tty */
1023		register struct pgrp *pgrp = pgfind(*(int *)data);
1024
1025		if (!isctty(p, tp))
1026			return (ENOTTY);
1027		else if (pgrp == NULL || pgrp->pg_session != p->p_session)
1028			return (EPERM);
1029		tp->t_pgrp = pgrp;
1030		break;
1031	}
1032	case TIOCSTAT:			/* simulate control-T */
1033		s = spltty();
1034		ttyinfo(tp);
1035		splx(s);
1036		break;
1037	case TIOCSWINSZ:		/* set window size */
1038		if (bcmp((caddr_t)&tp->t_winsize, data,
1039		    sizeof (struct winsize))) {
1040			tp->t_winsize = *(struct winsize *)data;
1041			pgsignal(tp->t_pgrp, SIGWINCH, 1);
1042		}
1043		break;
1044	case TIOCSDRAINWAIT:
1045		error = suser(p);
1046		if (error)
1047			return (error);
1048		tp->t_timeout = *(int *)data * hz;
1049		wakeup(TSA_OCOMPLETE(tp));
1050		wakeup(TSA_OLOWAT(tp));
1051		break;
1052	case TIOCGDRAINWAIT:
1053		*(int *)data = tp->t_timeout / hz;
1054		break;
1055	default:
1056#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
1057		return (ttcompat(tp, cmd, data, flag));
1058#else
1059		return (ENOIOCTL);
1060#endif
1061	}
1062	return (0);
1063}
1064
1065int
1066ttypoll(dev, events, p)
1067	dev_t dev;
1068	int events;
1069	struct proc *p;
1070{
1071	int s;
1072	int revents = 0;
1073	struct tty *tp;
1074
1075	tp = dev->si_tty;
1076	if (tp == NULL)	/* XXX used to return ENXIO, but that means true! */
1077		return ((events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM))
1078			| POLLHUP);
1079
1080	s = spltty();
1081	if (events & (POLLIN | POLLRDNORM)) {
1082		if (ttnread(tp) > 0 || ISSET(tp->t_state, TS_ZOMBIE))
1083			revents |= events & (POLLIN | POLLRDNORM);
1084		else
1085			selrecord(p, &tp->t_rsel);
1086	}
1087	if (events & (POLLOUT | POLLWRNORM)) {
1088		if ((tp->t_outq.c_cc <= tp->t_olowat &&
1089		     ISSET(tp->t_state, TS_CONNECTED))
1090		    || ISSET(tp->t_state, TS_ZOMBIE))
1091			revents |= events & (POLLOUT | POLLWRNORM);
1092		else
1093			selrecord(p, &tp->t_wsel);
1094	}
1095	splx(s);
1096	return (revents);
1097}
1098
1099static struct filterops ttyread_filtops =
1100	{ 1, NULL, filt_ttyrdetach, filt_ttyread };
1101static struct filterops ttywrite_filtops =
1102	{ 1, NULL, filt_ttywdetach, filt_ttywrite };
1103
1104int
1105ttykqfilter(dev, kn)
1106	dev_t dev;
1107	struct knote *kn;
1108{
1109	struct tty *tp = dev->si_tty;
1110	struct klist *klist;
1111	int s;
1112
1113	switch (kn->kn_filter) {
1114	case EVFILT_READ:
1115		klist = &tp->t_rsel.si_note;
1116		kn->kn_fop = &ttyread_filtops;
1117		break;
1118	case EVFILT_WRITE:
1119		klist = &tp->t_wsel.si_note;
1120		kn->kn_fop = &ttywrite_filtops;
1121		break;
1122	default:
1123		return (1);
1124	}
1125
1126	kn->kn_hook = (caddr_t)dev;
1127
1128	s = spltty();
1129	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
1130	splx(s);
1131
1132	return (0);
1133}
1134
1135static void
1136filt_ttyrdetach(struct knote *kn)
1137{
1138	struct tty *tp = ((dev_t)kn->kn_hook)->si_tty;
1139	int s = spltty();
1140
1141	SLIST_REMOVE(&tp->t_rsel.si_note, kn, knote, kn_selnext);
1142	splx(s);
1143}
1144
1145static int
1146filt_ttyread(struct knote *kn, long hint)
1147{
1148	struct tty *tp = ((dev_t)kn->kn_hook)->si_tty;
1149
1150	kn->kn_data = ttnread(tp);
1151	if (ISSET(tp->t_state, TS_ZOMBIE)) {
1152		kn->kn_flags |= EV_EOF;
1153		return (1);
1154	}
1155	return (kn->kn_data > 0);
1156}
1157
1158static void
1159filt_ttywdetach(struct knote *kn)
1160{
1161	struct tty *tp = ((dev_t)kn->kn_hook)->si_tty;
1162	int s = spltty();
1163
1164	SLIST_REMOVE(&tp->t_wsel.si_note, kn, knote, kn_selnext);
1165	splx(s);
1166}
1167
1168static int
1169filt_ttywrite(kn, hint)
1170	struct knote *kn;
1171	long hint;
1172{
1173	struct tty *tp = ((dev_t)kn->kn_hook)->si_tty;
1174
1175	kn->kn_data = tp->t_outq.c_cc;
1176	if (ISSET(tp->t_state, TS_ZOMBIE))
1177		return (1);
1178	return (kn->kn_data <= tp->t_olowat &&
1179	    ISSET(tp->t_state, TS_CONNECTED));
1180}
1181
1182/*
1183 * Must be called at spltty().
1184 */
1185static int
1186ttnread(tp)
1187	struct tty *tp;
1188{
1189	int nread;
1190
1191	if (ISSET(tp->t_lflag, PENDIN))
1192		ttypend(tp);
1193	nread = tp->t_canq.c_cc;
1194	if (!ISSET(tp->t_lflag, ICANON)) {
1195		nread += tp->t_rawq.c_cc;
1196		if (nread < tp->t_cc[VMIN] && tp->t_cc[VTIME] == 0)
1197			nread = 0;
1198	}
1199	return (nread);
1200}
1201
1202/*
1203 * Wait for output to drain.
1204 */
1205int
1206ttywait(tp)
1207	register struct tty *tp;
1208{
1209	int error, s;
1210
1211	error = 0;
1212	s = spltty();
1213	while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1214	       ISSET(tp->t_state, TS_CONNECTED) && tp->t_oproc) {
1215		(*tp->t_oproc)(tp);
1216		if ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1217		    ISSET(tp->t_state, TS_CONNECTED)) {
1218			SET(tp->t_state, TS_SO_OCOMPLETE);
1219			error = ttysleep(tp, TSA_OCOMPLETE(tp),
1220					 TTOPRI | PCATCH, "ttywai",
1221					 tp->t_timeout);
1222			if (error) {
1223				if (error == EWOULDBLOCK)
1224					error = EIO;
1225				break;
1226			}
1227		} else
1228			break;
1229	}
1230	if (!error && (tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)))
1231		error = EIO;
1232	splx(s);
1233	return (error);
1234}
1235
1236/*
1237 * Flush if successfully wait.
1238 */
1239static int
1240ttywflush(tp)
1241	struct tty *tp;
1242{
1243	int error;
1244
1245	if ((error = ttywait(tp)) == 0)
1246		ttyflush(tp, FREAD);
1247	return (error);
1248}
1249
1250/*
1251 * Flush tty read and/or write queues, notifying anyone waiting.
1252 */
1253void
1254ttyflush(tp, rw)
1255	register struct tty *tp;
1256	int rw;
1257{
1258	register int s;
1259
1260	s = spltty();
1261#if 0
1262again:
1263#endif
1264	if (rw & FWRITE) {
1265		FLUSHQ(&tp->t_outq);
1266		CLR(tp->t_state, TS_TTSTOP);
1267	}
1268	(*tp->t_stop)(tp, rw);
1269	if (rw & FREAD) {
1270		FLUSHQ(&tp->t_canq);
1271		FLUSHQ(&tp->t_rawq);
1272		CLR(tp->t_lflag, PENDIN);
1273		tp->t_rocount = 0;
1274		tp->t_rocol = 0;
1275		CLR(tp->t_state, TS_LOCAL);
1276		ttwakeup(tp);
1277		if (ISSET(tp->t_state, TS_TBLOCK)) {
1278			if (rw & FWRITE)
1279				FLUSHQ(&tp->t_outq);
1280			ttyunblock(tp);
1281
1282			/*
1283			 * Don't let leave any state that might clobber the
1284			 * next line discipline (although we should do more
1285			 * to send the START char).  Not clearing the state
1286			 * may have caused the "putc to a clist with no
1287			 * reserved cblocks" panic/printf.
1288			 */
1289			CLR(tp->t_state, TS_TBLOCK);
1290
1291#if 0 /* forget it, sleeping isn't always safe and we don't know when it is */
1292			if (ISSET(tp->t_iflag, IXOFF)) {
1293				/*
1294				 * XXX wait a bit in the hope that the stop
1295				 * character (if any) will go out.  Waiting
1296				 * isn't good since it allows races.  This
1297				 * will be fixed when the stop character is
1298				 * put in a special queue.  Don't bother with
1299				 * the checks in ttywait() since the timeout
1300				 * will save us.
1301				 */
1302				SET(tp->t_state, TS_SO_OCOMPLETE);
1303				ttysleep(tp, TSA_OCOMPLETE(tp), TTOPRI,
1304					 "ttyfls", hz / 10);
1305				/*
1306				 * Don't try sending the stop character again.
1307				 */
1308				CLR(tp->t_state, TS_TBLOCK);
1309				goto again;
1310			}
1311#endif
1312		}
1313	}
1314	if (rw & FWRITE) {
1315		FLUSHQ(&tp->t_outq);
1316		ttwwakeup(tp);
1317	}
1318	splx(s);
1319}
1320
1321/*
1322 * Copy in the default termios characters.
1323 */
1324void
1325termioschars(t)
1326	struct termios *t;
1327{
1328
1329	bcopy(ttydefchars, t->c_cc, sizeof t->c_cc);
1330}
1331
1332/*
1333 * Old interface.
1334 */
1335void
1336ttychars(tp)
1337	struct tty *tp;
1338{
1339
1340	termioschars(&tp->t_termios);
1341}
1342
1343/*
1344 * Handle input high water.  Send stop character for the IXOFF case.  Turn
1345 * on our input flow control bit and propagate the changes to the driver.
1346 * XXX the stop character should be put in a special high priority queue.
1347 */
1348void
1349ttyblock(tp)
1350	struct tty *tp;
1351{
1352
1353	SET(tp->t_state, TS_TBLOCK);
1354	if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
1355	    putc(tp->t_cc[VSTOP], &tp->t_outq) != 0)
1356		CLR(tp->t_state, TS_TBLOCK);	/* try again later */
1357	ttstart(tp);
1358}
1359
1360/*
1361 * Handle input low water.  Send start character for the IXOFF case.  Turn
1362 * off our input flow control bit and propagate the changes to the driver.
1363 * XXX the start character should be put in a special high priority queue.
1364 */
1365static void
1366ttyunblock(tp)
1367	struct tty *tp;
1368{
1369
1370	CLR(tp->t_state, TS_TBLOCK);
1371	if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTART] != _POSIX_VDISABLE &&
1372	    putc(tp->t_cc[VSTART], &tp->t_outq) != 0)
1373		SET(tp->t_state, TS_TBLOCK);	/* try again later */
1374	ttstart(tp);
1375}
1376
1377#ifdef notyet
1378/* Not used by any current (i386) drivers. */
1379/*
1380 * Restart after an inter-char delay.
1381 */
1382void
1383ttrstrt(tp_arg)
1384	void *tp_arg;
1385{
1386	struct tty *tp;
1387	int s;
1388
1389	KASSERT(tp_arg != NULL, ("ttrstrt"));
1390
1391	tp = tp_arg;
1392	s = spltty();
1393
1394	CLR(tp->t_state, TS_TIMEOUT);
1395	ttstart(tp);
1396
1397	splx(s);
1398}
1399#endif
1400
1401int
1402ttstart(tp)
1403	struct tty *tp;
1404{
1405
1406	if (tp->t_oproc != NULL)	/* XXX: Kludge for pty. */
1407		(*tp->t_oproc)(tp);
1408	return (0);
1409}
1410
1411/*
1412 * "close" a line discipline
1413 */
1414int
1415ttylclose(tp, flag)
1416	struct tty *tp;
1417	int flag;
1418{
1419
1420	if (flag & FNONBLOCK || ttywflush(tp))
1421		ttyflush(tp, FREAD | FWRITE);
1422	return (0);
1423}
1424
1425/*
1426 * Handle modem control transition on a tty.
1427 * Flag indicates new state of carrier.
1428 * Returns 0 if the line should be turned off, otherwise 1.
1429 */
1430int
1431ttymodem(tp, flag)
1432	register struct tty *tp;
1433	int flag;
1434{
1435
1436	if (ISSET(tp->t_state, TS_CARR_ON) && ISSET(tp->t_cflag, MDMBUF)) {
1437		/*
1438		 * MDMBUF: do flow control according to carrier flag
1439		 * XXX TS_CAR_OFLOW doesn't do anything yet.  TS_TTSTOP
1440		 * works if IXON and IXANY are clear.
1441		 */
1442		if (flag) {
1443			CLR(tp->t_state, TS_CAR_OFLOW);
1444			CLR(tp->t_state, TS_TTSTOP);
1445			ttstart(tp);
1446		} else if (!ISSET(tp->t_state, TS_CAR_OFLOW)) {
1447			SET(tp->t_state, TS_CAR_OFLOW);
1448			SET(tp->t_state, TS_TTSTOP);
1449			(*tp->t_stop)(tp, 0);
1450		}
1451	} else if (flag == 0) {
1452		/*
1453		 * Lost carrier.
1454		 */
1455		CLR(tp->t_state, TS_CARR_ON);
1456		if (ISSET(tp->t_state, TS_ISOPEN) &&
1457		    !ISSET(tp->t_cflag, CLOCAL)) {
1458			SET(tp->t_state, TS_ZOMBIE);
1459			CLR(tp->t_state, TS_CONNECTED);
1460			if (tp->t_session && tp->t_session->s_leader)
1461				psignal(tp->t_session->s_leader, SIGHUP);
1462			ttyflush(tp, FREAD | FWRITE);
1463			return (0);
1464		}
1465	} else {
1466		/*
1467		 * Carrier now on.
1468		 */
1469		SET(tp->t_state, TS_CARR_ON);
1470		if (!ISSET(tp->t_state, TS_ZOMBIE))
1471			SET(tp->t_state, TS_CONNECTED);
1472		wakeup(TSA_CARR_ON(tp));
1473		ttwakeup(tp);
1474		ttwwakeup(tp);
1475	}
1476	return (1);
1477}
1478
1479/*
1480 * Reinput pending characters after state switch
1481 * call at spltty().
1482 */
1483static void
1484ttypend(tp)
1485	register struct tty *tp;
1486{
1487	struct clist tq;
1488	register int c;
1489
1490	CLR(tp->t_lflag, PENDIN);
1491	SET(tp->t_state, TS_TYPEN);
1492	/*
1493	 * XXX this assumes too much about clist internals.  It may even
1494	 * fail if the cblock slush pool is empty.  We can't allocate more
1495	 * cblocks here because we are called from an interrupt handler
1496	 * and clist_alloc_cblocks() can wait.
1497	 */
1498	tq = tp->t_rawq;
1499	bzero(&tp->t_rawq, sizeof tp->t_rawq);
1500	tp->t_rawq.c_cbmax = tq.c_cbmax;
1501	tp->t_rawq.c_cbreserved = tq.c_cbreserved;
1502	while ((c = getc(&tq)) >= 0)
1503		ttyinput(c, tp);
1504	CLR(tp->t_state, TS_TYPEN);
1505}
1506
1507/*
1508 * Process a read call on a tty device.
1509 */
1510int
1511ttread(tp, uio, flag)
1512	register struct tty *tp;
1513	struct uio *uio;
1514	int flag;
1515{
1516	register struct clist *qp;
1517	register int c;
1518	register tcflag_t lflag;
1519	register cc_t *cc = tp->t_cc;
1520	register struct proc *p = curproc;
1521	int s, first, error = 0;
1522	int has_stime = 0, last_cc = 0;
1523	long slp = 0;		/* XXX this should be renamed `timo'. */
1524	struct timeval stime;
1525
1526loop:
1527	s = spltty();
1528	lflag = tp->t_lflag;
1529	/*
1530	 * take pending input first
1531	 */
1532	if (ISSET(lflag, PENDIN)) {
1533		ttypend(tp);
1534		splx(s);	/* reduce latency */
1535		s = spltty();
1536		lflag = tp->t_lflag;	/* XXX ttypend() clobbers it */
1537	}
1538
1539	/*
1540	 * Hang process if it's in the background.
1541	 */
1542	if (isbackground(p, tp)) {
1543		splx(s);
1544		if (SIGISMEMBER(p->p_sigignore, SIGTTIN) ||
1545		    SIGISMEMBER(p->p_sigmask, SIGTTIN) ||
1546		    (p->p_flag & P_PPWAIT) || p->p_pgrp->pg_jobc == 0)
1547			return (EIO);
1548		pgsignal(p->p_pgrp, SIGTTIN, 1);
1549		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, "ttybg2", 0);
1550		if (error)
1551			return (error);
1552		goto loop;
1553	}
1554
1555	if (ISSET(tp->t_state, TS_ZOMBIE)) {
1556		splx(s);
1557		return (0);	/* EOF */
1558	}
1559
1560	/*
1561	 * If canonical, use the canonical queue,
1562	 * else use the raw queue.
1563	 *
1564	 * (should get rid of clists...)
1565	 */
1566	qp = ISSET(lflag, ICANON) ? &tp->t_canq : &tp->t_rawq;
1567
1568	if (flag & IO_NDELAY) {
1569		if (qp->c_cc > 0)
1570			goto read;
1571		if (!ISSET(lflag, ICANON) && cc[VMIN] == 0) {
1572			splx(s);
1573			return (0);
1574		}
1575		splx(s);
1576		return (EWOULDBLOCK);
1577	}
1578	if (!ISSET(lflag, ICANON)) {
1579		int m = cc[VMIN];
1580		long t = cc[VTIME];
1581		struct timeval timecopy;
1582
1583		/*
1584		 * Check each of the four combinations.
1585		 * (m > 0 && t == 0) is the normal read case.
1586		 * It should be fairly efficient, so we check that and its
1587		 * companion case (m == 0 && t == 0) first.
1588		 * For the other two cases, we compute the target sleep time
1589		 * into slp.
1590		 */
1591		if (t == 0) {
1592			if (qp->c_cc < m)
1593				goto sleep;
1594			if (qp->c_cc > 0)
1595				goto read;
1596
1597			/* m, t and qp->c_cc are all 0.  0 is enough input. */
1598			splx(s);
1599			return (0);
1600		}
1601		t *= 100000;		/* time in us */
1602#define diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 1000000 + \
1603			 ((t1).tv_usec - (t2).tv_usec))
1604		if (m > 0) {
1605			if (qp->c_cc <= 0)
1606				goto sleep;
1607			if (qp->c_cc >= m)
1608				goto read;
1609			getmicrotime(&timecopy);
1610			if (!has_stime) {
1611				/* first character, start timer */
1612				has_stime = 1;
1613				stime = timecopy;
1614				slp = t;
1615			} else if (qp->c_cc > last_cc) {
1616				/* got a character, restart timer */
1617				stime = timecopy;
1618				slp = t;
1619			} else {
1620				/* nothing, check expiration */
1621				slp = t - diff(timecopy, stime);
1622				if (slp <= 0)
1623					goto read;
1624			}
1625			last_cc = qp->c_cc;
1626		} else {	/* m == 0 */
1627			if (qp->c_cc > 0)
1628				goto read;
1629			getmicrotime(&timecopy);
1630			if (!has_stime) {
1631				has_stime = 1;
1632				stime = timecopy;
1633				slp = t;
1634			} else {
1635				slp = t - diff(timecopy, stime);
1636				if (slp <= 0) {
1637					/* Timed out, but 0 is enough input. */
1638					splx(s);
1639					return (0);
1640				}
1641			}
1642		}
1643#undef diff
1644		/*
1645		 * Rounding down may make us wake up just short
1646		 * of the target, so we round up.
1647		 * The formula is ceiling(slp * hz/1000000).
1648		 * 32-bit arithmetic is enough for hz < 169.
1649		 * XXX see tvtohz() for how to avoid overflow if hz
1650		 * is large (divide by `tick' and/or arrange to
1651		 * use tvtohz() if hz is large).
1652		 */
1653		slp = (long) (((u_long)slp * hz) + 999999) / 1000000;
1654		goto sleep;
1655	}
1656	if (qp->c_cc <= 0) {
1657sleep:
1658		/*
1659		 * There is no input, or not enough input and we can block.
1660		 */
1661		error = ttysleep(tp, TSA_HUP_OR_INPUT(tp), TTIPRI | PCATCH,
1662				 ISSET(tp->t_state, TS_CONNECTED) ?
1663				 "ttyin" : "ttyhup", (int)slp);
1664		splx(s);
1665		if (error == EWOULDBLOCK)
1666			error = 0;
1667		else if (error)
1668			return (error);
1669		/*
1670		 * XXX what happens if another process eats some input
1671		 * while we are asleep (not just here)?  It would be
1672		 * safest to detect changes and reset our state variables
1673		 * (has_stime and last_cc).
1674		 */
1675		slp = 0;
1676		goto loop;
1677	}
1678read:
1679	splx(s);
1680	/*
1681	 * Input present, check for input mapping and processing.
1682	 */
1683	first = 1;
1684	if (ISSET(lflag, ICANON | ISIG))
1685		goto slowcase;
1686	for (;;) {
1687		char ibuf[IBUFSIZ];
1688		int icc;
1689
1690		icc = imin(uio->uio_resid, IBUFSIZ);
1691		icc = q_to_b(qp, ibuf, icc);
1692		if (icc <= 0) {
1693			if (first)
1694				goto loop;
1695			break;
1696		}
1697		error = uiomove(ibuf, icc, uio);
1698		/*
1699		 * XXX if there was an error then we should ungetc() the
1700		 * unmoved chars and reduce icc here.
1701		 */
1702#ifdef DEV_SNP
1703		if (ISSET(tp->t_lflag, ECHO) &&
1704		    ISSET(tp->t_state, TS_SNOOP) && tp->t_sc != NULL)
1705			snpin((struct snoop *)tp->t_sc, ibuf, icc);
1706#endif
1707		if (error)
1708			break;
1709 		if (uio->uio_resid == 0)
1710			break;
1711		first = 0;
1712	}
1713	goto out;
1714slowcase:
1715	for (;;) {
1716		c = getc(qp);
1717		if (c < 0) {
1718			if (first)
1719				goto loop;
1720			break;
1721		}
1722		/*
1723		 * delayed suspend (^Y)
1724		 */
1725		if (CCEQ(cc[VDSUSP], c) &&
1726		    ISSET(lflag, IEXTEN | ISIG) == (IEXTEN | ISIG)) {
1727			pgsignal(tp->t_pgrp, SIGTSTP, 1);
1728			if (first) {
1729				error = ttysleep(tp, &lbolt, TTIPRI | PCATCH,
1730						 "ttybg3", 0);
1731				if (error)
1732					break;
1733				goto loop;
1734			}
1735			break;
1736		}
1737		/*
1738		 * Interpret EOF only in canonical mode.
1739		 */
1740		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
1741			break;
1742		/*
1743		 * Give user character.
1744		 */
1745 		error = ureadc(c, uio);
1746		if (error)
1747			/* XXX should ungetc(c, qp). */
1748			break;
1749#ifdef DEV_SNP
1750		/*
1751		 * Only snoop directly on input in echo mode.  Non-echoed
1752		 * input will be snooped later iff the application echoes it.
1753		 */
1754		if (ISSET(tp->t_lflag, ECHO) &&
1755		    ISSET(tp->t_state, TS_SNOOP) && tp->t_sc != NULL)
1756			snpinc((struct snoop *)tp->t_sc, (char)c);
1757#endif
1758 		if (uio->uio_resid == 0)
1759			break;
1760		/*
1761		 * In canonical mode check for a "break character"
1762		 * marking the end of a "line of input".
1763		 */
1764		if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
1765			break;
1766		first = 0;
1767	}
1768
1769out:
1770	/*
1771	 * Look to unblock input now that (presumably)
1772	 * the input queue has gone down.
1773	 */
1774	s = spltty();
1775	if (ISSET(tp->t_state, TS_TBLOCK) &&
1776	    tp->t_rawq.c_cc + tp->t_canq.c_cc <= tp->t_ilowat)
1777		ttyunblock(tp);
1778	splx(s);
1779
1780	return (error);
1781}
1782
1783/*
1784 * Check the output queue on tp for space for a kernel message (from uprintf
1785 * or tprintf).  Allow some space over the normal hiwater mark so we don't
1786 * lose messages due to normal flow control, but don't let the tty run amok.
1787 * Sleeps here are not interruptible, but we return prematurely if new signals
1788 * arrive.
1789 */
1790int
1791ttycheckoutq(tp, wait)
1792	register struct tty *tp;
1793	int wait;
1794{
1795	int hiwat, s;
1796	sigset_t oldmask;
1797
1798	hiwat = tp->t_ohiwat;
1799	SIGEMPTYSET(oldmask);
1800	s = spltty();
1801	if (wait)
1802		oldmask = curproc->p_siglist;
1803	if (tp->t_outq.c_cc > hiwat + OBUFSIZ + 100)
1804		while (tp->t_outq.c_cc > hiwat) {
1805			ttstart(tp);
1806			if (tp->t_outq.c_cc <= hiwat)
1807				break;
1808			if (!(wait && SIGSETEQ(curproc->p_siglist, oldmask))) {
1809				splx(s);
1810				return (0);
1811			}
1812			SET(tp->t_state, TS_SO_OLOWAT);
1813			tsleep(TSA_OLOWAT(tp), PZERO - 1, "ttoutq", hz);
1814		}
1815	splx(s);
1816	return (1);
1817}
1818
1819/*
1820 * Process a write call on a tty device.
1821 */
1822int
1823ttwrite(tp, uio, flag)
1824	register struct tty *tp;
1825	register struct uio *uio;
1826	int flag;
1827{
1828	register char *cp = NULL;
1829	register int cc, ce;
1830	register struct proc *p;
1831	int i, hiwat, cnt, error, s;
1832	char obuf[OBUFSIZ];
1833
1834	hiwat = tp->t_ohiwat;
1835	cnt = uio->uio_resid;
1836	error = 0;
1837	cc = 0;
1838loop:
1839	s = spltty();
1840	if (ISSET(tp->t_state, TS_ZOMBIE)) {
1841		splx(s);
1842		if (uio->uio_resid == cnt)
1843			error = EIO;
1844		goto out;
1845	}
1846	if (!ISSET(tp->t_state, TS_CONNECTED)) {
1847		if (flag & IO_NDELAY) {
1848			splx(s);
1849			error = EWOULDBLOCK;
1850			goto out;
1851		}
1852		error = ttysleep(tp, TSA_CARR_ON(tp), TTIPRI | PCATCH,
1853				 "ttydcd", 0);
1854		splx(s);
1855		if (error)
1856			goto out;
1857		goto loop;
1858	}
1859	splx(s);
1860	/*
1861	 * Hang the process if it's in the background.
1862	 */
1863	p = curproc;
1864	if (isbackground(p, tp) &&
1865	    ISSET(tp->t_lflag, TOSTOP) && !(p->p_flag & P_PPWAIT) &&
1866	    !SIGISMEMBER(p->p_sigignore, SIGTTOU) &&
1867	    !SIGISMEMBER(p->p_sigmask, SIGTTOU)) {
1868		if (p->p_pgrp->pg_jobc == 0) {
1869			error = EIO;
1870			goto out;
1871		}
1872		pgsignal(p->p_pgrp, SIGTTOU, 1);
1873		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, "ttybg4", 0);
1874		if (error)
1875			goto out;
1876		goto loop;
1877	}
1878	/*
1879	 * Process the user's data in at most OBUFSIZ chunks.  Perform any
1880	 * output translation.  Keep track of high water mark, sleep on
1881	 * overflow awaiting device aid in acquiring new space.
1882	 */
1883	while (uio->uio_resid > 0 || cc > 0) {
1884		if (ISSET(tp->t_lflag, FLUSHO)) {
1885			uio->uio_resid = 0;
1886			return (0);
1887		}
1888		if (tp->t_outq.c_cc > hiwat)
1889			goto ovhiwat;
1890		/*
1891		 * Grab a hunk of data from the user, unless we have some
1892		 * leftover from last time.
1893		 */
1894		if (cc == 0) {
1895			cc = imin(uio->uio_resid, OBUFSIZ);
1896			cp = obuf;
1897			error = uiomove(cp, cc, uio);
1898			if (error) {
1899				cc = 0;
1900				break;
1901			}
1902#ifdef DEV_SNP
1903			if (ISSET(tp->t_state, TS_SNOOP) && tp->t_sc != NULL)
1904				snpin((struct snoop *)tp->t_sc, cp, cc);
1905#endif
1906		}
1907		/*
1908		 * If nothing fancy need be done, grab those characters we
1909		 * can handle without any of ttyoutput's processing and
1910		 * just transfer them to the output q.  For those chars
1911		 * which require special processing (as indicated by the
1912		 * bits in char_type), call ttyoutput.  After processing
1913		 * a hunk of data, look for FLUSHO so ^O's will take effect
1914		 * immediately.
1915		 */
1916		while (cc > 0) {
1917			if (!ISSET(tp->t_oflag, OPOST))
1918				ce = cc;
1919			else {
1920				ce = cc - scanc((u_int)cc, (u_char *)cp,
1921						char_type, CCLASSMASK);
1922				/*
1923				 * If ce is zero, then we're processing
1924				 * a special character through ttyoutput.
1925				 */
1926				if (ce == 0) {
1927					tp->t_rocount = 0;
1928					if (ttyoutput(*cp, tp) >= 0) {
1929						/* No Clists, wait a bit. */
1930						ttstart(tp);
1931						if (flag & IO_NDELAY) {
1932							error = EWOULDBLOCK;
1933							goto out;
1934						}
1935						error = ttysleep(tp, &lbolt,
1936								 TTOPRI|PCATCH,
1937								 "ttybf1", 0);
1938						if (error)
1939							goto out;
1940						goto loop;
1941					}
1942					cp++;
1943					cc--;
1944					if (ISSET(tp->t_lflag, FLUSHO) ||
1945					    tp->t_outq.c_cc > hiwat)
1946						goto ovhiwat;
1947					continue;
1948				}
1949			}
1950			/*
1951			 * A bunch of normal characters have been found.
1952			 * Transfer them en masse to the output queue and
1953			 * continue processing at the top of the loop.
1954			 * If there are any further characters in this
1955			 * <= OBUFSIZ chunk, the first should be a character
1956			 * requiring special handling by ttyoutput.
1957			 */
1958			tp->t_rocount = 0;
1959			i = b_to_q(cp, ce, &tp->t_outq);
1960			ce -= i;
1961			tp->t_column += ce;
1962			cp += ce, cc -= ce, tk_nout += ce;
1963			tp->t_outcc += ce;
1964			if (i > 0) {
1965				/* No Clists, wait a bit. */
1966				ttstart(tp);
1967				if (flag & IO_NDELAY) {
1968					error = EWOULDBLOCK;
1969					goto out;
1970				}
1971				error = ttysleep(tp, &lbolt, TTOPRI | PCATCH,
1972						 "ttybf2", 0);
1973				if (error)
1974					goto out;
1975				goto loop;
1976			}
1977			if (ISSET(tp->t_lflag, FLUSHO) ||
1978			    tp->t_outq.c_cc > hiwat)
1979				break;
1980		}
1981		ttstart(tp);
1982	}
1983out:
1984	/*
1985	 * If cc is nonzero, we leave the uio structure inconsistent, as the
1986	 * offset and iov pointers have moved forward, but it doesn't matter
1987	 * (the call will either return short or restart with a new uio).
1988	 */
1989	uio->uio_resid += cc;
1990	return (error);
1991
1992ovhiwat:
1993	ttstart(tp);
1994	s = spltty();
1995	/*
1996	 * This can only occur if FLUSHO is set in t_lflag,
1997	 * or if ttstart/oproc is synchronous (or very fast).
1998	 */
1999	if (tp->t_outq.c_cc <= hiwat) {
2000		splx(s);
2001		goto loop;
2002	}
2003	if (flag & IO_NDELAY) {
2004		splx(s);
2005		uio->uio_resid += cc;
2006		return (uio->uio_resid == cnt ? EWOULDBLOCK : 0);
2007	}
2008	SET(tp->t_state, TS_SO_OLOWAT);
2009	error = ttysleep(tp, TSA_OLOWAT(tp), TTOPRI | PCATCH, "ttywri",
2010			 tp->t_timeout);
2011	splx(s);
2012	if (error == EWOULDBLOCK)
2013		error = EIO;
2014	if (error)
2015		goto out;
2016	goto loop;
2017}
2018
2019/*
2020 * Rubout one character from the rawq of tp
2021 * as cleanly as possible.
2022 */
2023static void
2024ttyrub(c, tp)
2025	register int c;
2026	register struct tty *tp;
2027{
2028	register char *cp;
2029	register int savecol;
2030	int tabc, s;
2031
2032	if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
2033		return;
2034	CLR(tp->t_lflag, FLUSHO);
2035	if (ISSET(tp->t_lflag, ECHOE)) {
2036		if (tp->t_rocount == 0) {
2037			/*
2038			 * Screwed by ttwrite; retype
2039			 */
2040			ttyretype(tp);
2041			return;
2042		}
2043		if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
2044			ttyrubo(tp, 2);
2045		else {
2046			CLR(c, ~TTY_CHARMASK);
2047			switch (CCLASS(c)) {
2048			case ORDINARY:
2049				ttyrubo(tp, 1);
2050				break;
2051			case BACKSPACE:
2052			case CONTROL:
2053			case NEWLINE:
2054			case RETURN:
2055			case VTAB:
2056				if (ISSET(tp->t_lflag, ECHOCTL))
2057					ttyrubo(tp, 2);
2058				break;
2059			case TAB:
2060				if (tp->t_rocount < tp->t_rawq.c_cc) {
2061					ttyretype(tp);
2062					return;
2063				}
2064				s = spltty();
2065				savecol = tp->t_column;
2066				SET(tp->t_state, TS_CNTTB);
2067				SET(tp->t_lflag, FLUSHO);
2068				tp->t_column = tp->t_rocol;
2069				cp = tp->t_rawq.c_cf;
2070				if (cp)
2071					tabc = *cp;	/* XXX FIX NEXTC */
2072				for (; cp; cp = nextc(&tp->t_rawq, cp, &tabc))
2073					ttyecho(tabc, tp);
2074				CLR(tp->t_lflag, FLUSHO);
2075				CLR(tp->t_state, TS_CNTTB);
2076				splx(s);
2077
2078				/* savecol will now be length of the tab. */
2079				savecol -= tp->t_column;
2080				tp->t_column += savecol;
2081				if (savecol > 8)
2082					savecol = 8;	/* overflow screw */
2083				while (--savecol >= 0)
2084					(void)ttyoutput('\b', tp);
2085				break;
2086			default:			/* XXX */
2087#define	PANICSTR	"ttyrub: would panic c = %d, val = %d\n"
2088				(void)printf(PANICSTR, c, CCLASS(c));
2089#ifdef notdef
2090				panic(PANICSTR, c, CCLASS(c));
2091#endif
2092			}
2093		}
2094	} else if (ISSET(tp->t_lflag, ECHOPRT)) {
2095		if (!ISSET(tp->t_state, TS_ERASE)) {
2096			SET(tp->t_state, TS_ERASE);
2097			(void)ttyoutput('\\', tp);
2098		}
2099		ttyecho(c, tp);
2100	} else {
2101		ttyecho(tp->t_cc[VERASE], tp);
2102		/*
2103		 * This code may be executed not only when an ERASE key
2104		 * is pressed, but also when ^U (KILL) or ^W (WERASE) are.
2105		 * So, I didn't think it was worthwhile to pass the extra
2106		 * information (which would need an extra parameter,
2107		 * changing every call) needed to distinguish the ERASE2
2108		 * case from the ERASE.
2109		 */
2110	}
2111	--tp->t_rocount;
2112}
2113
2114/*
2115 * Back over cnt characters, erasing them.
2116 */
2117static void
2118ttyrubo(tp, cnt)
2119	register struct tty *tp;
2120	int cnt;
2121{
2122
2123	while (cnt-- > 0) {
2124		(void)ttyoutput('\b', tp);
2125		(void)ttyoutput(' ', tp);
2126		(void)ttyoutput('\b', tp);
2127	}
2128}
2129
2130/*
2131 * ttyretype --
2132 *	Reprint the rawq line.  Note, it is assumed that c_cc has already
2133 *	been checked.
2134 */
2135static void
2136ttyretype(tp)
2137	register struct tty *tp;
2138{
2139	register char *cp;
2140	int s, c;
2141
2142	/* Echo the reprint character. */
2143	if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
2144		ttyecho(tp->t_cc[VREPRINT], tp);
2145
2146	(void)ttyoutput('\n', tp);
2147
2148	/*
2149	 * XXX
2150	 * FIX: NEXTC IS BROKEN - DOESN'T CHECK QUOTE
2151	 * BIT OF FIRST CHAR.
2152	 */
2153	s = spltty();
2154	for (cp = tp->t_canq.c_cf, c = (cp != NULL ? *cp : 0);
2155	    cp != NULL; cp = nextc(&tp->t_canq, cp, &c))
2156		ttyecho(c, tp);
2157	for (cp = tp->t_rawq.c_cf, c = (cp != NULL ? *cp : 0);
2158	    cp != NULL; cp = nextc(&tp->t_rawq, cp, &c))
2159		ttyecho(c, tp);
2160	CLR(tp->t_state, TS_ERASE);
2161	splx(s);
2162
2163	tp->t_rocount = tp->t_rawq.c_cc;
2164	tp->t_rocol = 0;
2165}
2166
2167/*
2168 * Echo a typed character to the terminal.
2169 */
2170static void
2171ttyecho(c, tp)
2172	register int c;
2173	register struct tty *tp;
2174{
2175
2176	if (!ISSET(tp->t_state, TS_CNTTB))
2177		CLR(tp->t_lflag, FLUSHO);
2178	if ((!ISSET(tp->t_lflag, ECHO) &&
2179	     (c != '\n' || !ISSET(tp->t_lflag, ECHONL))) ||
2180	    ISSET(tp->t_lflag, EXTPROC))
2181		return;
2182	if (ISSET(tp->t_lflag, ECHOCTL) &&
2183	    ((ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n') ||
2184	    ISSET(c, TTY_CHARMASK) == 0177)) {
2185		(void)ttyoutput('^', tp);
2186		CLR(c, ~TTY_CHARMASK);
2187		if (c == 0177)
2188			c = '?';
2189		else
2190			c += 'A' - 1;
2191	}
2192	(void)ttyoutput(c, tp);
2193}
2194
2195/*
2196 * Wake up any readers on a tty.
2197 */
2198void
2199ttwakeup(tp)
2200	register struct tty *tp;
2201{
2202
2203	if (tp->t_rsel.si_pid != 0)
2204		selwakeup(&tp->t_rsel);
2205	if (ISSET(tp->t_state, TS_ASYNC) && tp->t_sigio != NULL)
2206		pgsigio(tp->t_sigio, SIGIO, (tp->t_session != NULL));
2207	wakeup(TSA_HUP_OR_INPUT(tp));
2208	KNOTE(&tp->t_rsel.si_note, 0);
2209}
2210
2211/*
2212 * Wake up any writers on a tty.
2213 */
2214void
2215ttwwakeup(tp)
2216	register struct tty *tp;
2217{
2218
2219	if (tp->t_wsel.si_pid != 0 && tp->t_outq.c_cc <= tp->t_olowat)
2220		selwakeup(&tp->t_wsel);
2221	if (ISSET(tp->t_state, TS_ASYNC) && tp->t_sigio != NULL)
2222		pgsigio(tp->t_sigio, SIGIO, (tp->t_session != NULL));
2223	if (ISSET(tp->t_state, TS_BUSY | TS_SO_OCOMPLETE) ==
2224	    TS_SO_OCOMPLETE && tp->t_outq.c_cc == 0) {
2225		CLR(tp->t_state, TS_SO_OCOMPLETE);
2226		wakeup(TSA_OCOMPLETE(tp));
2227	}
2228	if (ISSET(tp->t_state, TS_SO_OLOWAT) &&
2229	    tp->t_outq.c_cc <= tp->t_olowat) {
2230		CLR(tp->t_state, TS_SO_OLOWAT);
2231		wakeup(TSA_OLOWAT(tp));
2232	}
2233	KNOTE(&tp->t_wsel.si_note, 0);
2234}
2235
2236/*
2237 * Look up a code for a specified speed in a conversion table;
2238 * used by drivers to map software speed values to hardware parameters.
2239 */
2240int
2241ttspeedtab(speed, table)
2242	int speed;
2243	register struct speedtab *table;
2244{
2245
2246	for ( ; table->sp_speed != -1; table++)
2247		if (table->sp_speed == speed)
2248			return (table->sp_code);
2249	return (-1);
2250}
2251
2252/*
2253 * Set input and output watermarks and buffer sizes.  For input, the
2254 * high watermark is about one second's worth of input above empty, the
2255 * low watermark is slightly below high water, and the buffer size is a
2256 * driver-dependent amount above high water.  For output, the watermarks
2257 * are near the ends of the buffer, with about 1 second's worth of input
2258 * between them.  All this only applies to the standard line discipline.
2259 */
2260void
2261ttsetwater(tp)
2262	struct tty *tp;
2263{
2264	register int cps, ttmaxhiwat, x;
2265
2266	/* Input. */
2267	clist_alloc_cblocks(&tp->t_canq, TTYHOG, 512);
2268	switch (tp->t_ispeedwat) {
2269	case (speed_t)-1:
2270		cps = tp->t_ispeed / 10;
2271		break;
2272	case 0:
2273		/*
2274		 * This case is for old drivers that don't know about
2275		 * t_ispeedwat.  Arrange for them to get the old buffer
2276		 * sizes and watermarks.
2277		 */
2278		cps = TTYHOG - 2 * 256;
2279		tp->t_ififosize = 2 * 256;
2280		break;
2281	default:
2282		cps = tp->t_ispeedwat / 10;
2283		break;
2284	}
2285	tp->t_ihiwat = cps;
2286	tp->t_ilowat = 7 * cps / 8;
2287	x = cps + tp->t_ififosize;
2288	clist_alloc_cblocks(&tp->t_rawq, x, x);
2289
2290	/* Output. */
2291	switch (tp->t_ospeedwat) {
2292	case (speed_t)-1:
2293		cps = tp->t_ospeed / 10;
2294		ttmaxhiwat = 2 * TTMAXHIWAT;
2295		break;
2296	case 0:
2297		cps = tp->t_ospeed / 10;
2298		ttmaxhiwat = TTMAXHIWAT;
2299		break;
2300	default:
2301		cps = tp->t_ospeedwat / 10;
2302		ttmaxhiwat = 8 * TTMAXHIWAT;
2303		break;
2304	}
2305#define CLAMP(x, h, l)	((x) > h ? h : ((x) < l) ? l : (x))
2306	tp->t_olowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
2307	x += cps;
2308	x = CLAMP(x, ttmaxhiwat, TTMINHIWAT);	/* XXX clamps are too magic */
2309	tp->t_ohiwat = roundup(x, CBSIZE);	/* XXX for compat */
2310	x = imax(tp->t_ohiwat, TTMAXHIWAT);	/* XXX for compat/safety */
2311	x += OBUFSIZ + 100;
2312	clist_alloc_cblocks(&tp->t_outq, x, x);
2313#undef	CLAMP
2314}
2315
2316/*
2317 * Report on state of foreground process group.
2318 */
2319void
2320ttyinfo(tp)
2321	register struct tty *tp;
2322{
2323	register struct proc *p, *pick;
2324	struct timeval utime, stime;
2325	const char *stmp;
2326	long ltmp;
2327	int tmp;
2328
2329	if (ttycheckoutq(tp,0) == 0)
2330		return;
2331
2332	/* Print load average. */
2333	tmp = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
2334	ttyprintf(tp, "load: %d.%02d ", tmp / 100, tmp % 100);
2335
2336	if (tp->t_session == NULL)
2337		ttyprintf(tp, "not a controlling terminal\n");
2338	else if (tp->t_pgrp == NULL)
2339		ttyprintf(tp, "no foreground process group\n");
2340	else if ((p = LIST_FIRST(&tp->t_pgrp->pg_members)) == 0)
2341		ttyprintf(tp, "empty foreground process group\n");
2342	else {
2343		mtx_lock_spin(&sched_lock);
2344
2345		/* Pick interesting process. */
2346		for (pick = NULL; p != 0; p = LIST_NEXT(p, p_pglist))
2347			if (proc_compare(pick, p))
2348				pick = p;
2349
2350		stmp = pick->p_stat == SRUN ? "running" :
2351		    pick->p_wmesg ? pick->p_wmesg : "iowait";
2352		calcru(pick, &utime, &stime, NULL);
2353		ltmp = pick->p_stat == SIDL || pick->p_stat == SWAIT ||
2354		    pick->p_stat == SZOMB ? 0 :
2355		    pgtok(vmspace_resident_count(pick->p_vmspace));
2356		mtx_unlock_spin(&sched_lock);
2357
2358		ttyprintf(tp, " cmd: %s %d [%s] ", pick->p_comm, pick->p_pid,
2359		    stmp);
2360
2361		/* Print user time. */
2362		ttyprintf(tp, "%ld.%02ldu ",
2363		    utime.tv_sec, utime.tv_usec / 10000);
2364
2365		/* Print system time. */
2366		ttyprintf(tp, "%ld.%02lds ",
2367		    stime.tv_sec, stime.tv_usec / 10000);
2368
2369		/* Print percentage cpu, resident set size. */
2370		ttyprintf(tp, "%d%% %ldk\n", tmp / 100, ltmp);
2371	}
2372	tp->t_rocount = 0;	/* so pending input will be retyped if BS */
2373}
2374
2375/*
2376 * Returns 1 if p2 is "better" than p1
2377 *
2378 * The algorithm for picking the "interesting" process is thus:
2379 *
2380 *	1) Only foreground processes are eligible - implied.
2381 *	2) Runnable processes are favored over anything else.  The runner
2382 *	   with the highest cpu utilization is picked (p_estcpu).  Ties are
2383 *	   broken by picking the highest pid.
2384 *	3) The sleeper with the shortest sleep time is next.  With ties,
2385 *	   we pick out just "short-term" sleepers (P_SINTR == 0).
2386 *	4) Further ties are broken by picking the highest pid.
2387 */
2388#define ISRUN(p)	(((p)->p_stat == SRUN) || ((p)->p_stat == SIDL))
2389#define TESTAB(a, b)    ((a)<<1 | (b))
2390#define ONLYA   2
2391#define ONLYB   1
2392#define BOTH    3
2393
2394static int
2395proc_compare(p1, p2)
2396	register struct proc *p1, *p2;
2397{
2398
2399	mtx_assert(&sched_lock, MA_OWNED);
2400	if (p1 == NULL)
2401		return (1);
2402
2403	/*
2404	 * see if at least one of them is runnable
2405	 */
2406	switch (TESTAB(ISRUN(p1), ISRUN(p2))) {
2407	case ONLYA:
2408		return (0);
2409	case ONLYB:
2410		return (1);
2411	case BOTH:
2412		/*
2413		 * tie - favor one with highest recent cpu utilization
2414		 */
2415		if (p2->p_estcpu > p1->p_estcpu)
2416			return (1);
2417		if (p1->p_estcpu > p2->p_estcpu)
2418			return (0);
2419		return (p2->p_pid > p1->p_pid);	/* tie - return highest pid */
2420	}
2421	/*
2422 	 * weed out zombies
2423	 */
2424	switch (TESTAB(p1->p_stat == SZOMB, p2->p_stat == SZOMB)) {
2425	case ONLYA:
2426		return (1);
2427	case ONLYB:
2428		return (0);
2429	case BOTH:
2430		return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
2431	}
2432
2433	/*
2434	 * pick the one with the smallest sleep time
2435	 */
2436	if (p2->p_slptime > p1->p_slptime)
2437		return (0);
2438	if (p1->p_slptime > p2->p_slptime)
2439		return (1);
2440	/*
2441	 * favor one sleeping in a non-interruptible sleep
2442	 */
2443	if (p1->p_sflag & PS_SINTR && (p2->p_sflag & PS_SINTR) == 0)
2444		return (1);
2445	if (p2->p_sflag & PS_SINTR && (p1->p_sflag & PS_SINTR) == 0)
2446		return (0);
2447	return (p2->p_pid > p1->p_pid);		/* tie - return highest pid */
2448}
2449
2450/*
2451 * Output char to tty; console putchar style.
2452 */
2453int
2454tputchar(c, tp)
2455	int c;
2456	struct tty *tp;
2457{
2458	register int s;
2459
2460	s = spltty();
2461	if (!ISSET(tp->t_state, TS_CONNECTED)) {
2462		splx(s);
2463		return (-1);
2464	}
2465	if (c == '\n')
2466		(void)ttyoutput('\r', tp);
2467	(void)ttyoutput(c, tp);
2468	ttstart(tp);
2469	splx(s);
2470	return (0);
2471}
2472
2473/*
2474 * Sleep on chan, returning ERESTART if tty changed while we napped and
2475 * returning any errors (e.g. EINTR/EWOULDBLOCK) reported by tsleep.  If
2476 * the tty is revoked, restarting a pending call will redo validation done
2477 * at the start of the call.
2478 */
2479int
2480ttysleep(tp, chan, pri, wmesg, timo)
2481	struct tty *tp;
2482	void *chan;
2483	int pri, timo;
2484	char *wmesg;
2485{
2486	int error;
2487	int gen;
2488
2489	gen = tp->t_gen;
2490	error = tsleep(chan, pri, wmesg, timo);
2491	if (error)
2492		return (error);
2493	return (tp->t_gen == gen ? 0 : ERESTART);
2494}
2495
2496/*
2497 * Allocate a tty struct.  Clists in the struct will be allocated by
2498 * ttyopen().
2499 */
2500struct tty *
2501ttymalloc(tp)
2502	struct tty *tp;
2503{
2504
2505	if (tp)
2506		return(tp);
2507        tp = malloc(sizeof *tp, M_TTYS, M_WAITOK | M_ZERO);
2508	ttyregister(tp);
2509        return (tp);
2510}
2511
2512#if 0 /* XXX not yet usable: session leader holds a ref (see kern_exit.c). */
2513/*
2514 * Free a tty struct.  Clists in the struct should have been freed by
2515 * ttyclose().
2516 */
2517void
2518ttyfree(tp)
2519	struct tty *tp;
2520{
2521        free(tp, M_TTYS);
2522}
2523#endif /* 0 */
2524
2525void
2526ttyregister(tp)
2527	struct tty *tp;
2528{
2529	tp->t_timeout = -1;
2530	SLIST_INSERT_HEAD(&tty_list, tp, t_list);
2531}
2532
2533static int
2534sysctl_kern_ttys(SYSCTL_HANDLER_ARGS)
2535{
2536	int error;
2537	struct tty *tp, t;
2538	SLIST_FOREACH(tp, &tty_list, t_list) {
2539		t = *tp;
2540		if (t.t_dev)
2541			t.t_dev = (dev_t)dev2udev(t.t_dev);
2542		error = SYSCTL_OUT(req, (caddr_t)&t, sizeof(t));
2543		if (error)
2544			return (error);
2545	}
2546	return (0);
2547}
2548
2549SYSCTL_PROC(_kern, OID_AUTO, ttys, CTLTYPE_OPAQUE|CTLFLAG_RD,
2550	0, 0, sysctl_kern_ttys, "S,tty", "All struct ttys");
2551
2552void
2553nottystop(tp, rw)
2554	struct tty *tp;
2555	int rw;
2556{
2557
2558	return;
2559}
2560
2561int
2562ttyread(dev, uio, flag)
2563	dev_t dev;
2564	struct uio *uio;
2565	int flag;
2566{
2567	struct tty *tp;
2568
2569	tp = dev->si_tty;
2570	if (tp == NULL)
2571		return (ENODEV);
2572	return ((*linesw[tp->t_line].l_read)(tp, uio, flag));
2573}
2574
2575int
2576ttywrite(dev, uio, flag)
2577	dev_t dev;
2578	struct uio *uio;
2579	int flag;
2580{
2581	struct tty *tp;
2582
2583	tp = dev->si_tty;
2584	if (tp == NULL)
2585		return (ENODEV);
2586	return ((*linesw[tp->t_line].l_write)(tp, uio, flag));
2587}
2588