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