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