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