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