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