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