tty.c revision 12855
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.75 1995/12/14 22:32:39 bde 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			if (rw & FWRITE)
1170				FLUSHQ(&tp->t_outq);
1171			ttyunblock(tp);
1172
1173			/*
1174			 * Don't let leave any state that might clobber the
1175			 * next line discipline (although we should do more
1176			 * to send the START char).  Not clearing the state
1177			 * may have caused the "putc to a clist with no
1178			 * reserved cblocks" panic/printf.
1179			 */
1180			CLR(tp->t_state, TS_TBLOCK);
1181
1182#if 0 /* forget it, sleeping isn't always safe and we don't know when it is */
1183			if (ISSET(tp->t_iflag, IXOFF)) {
1184				/*
1185				 * XXX wait a bit in the hope that the stop
1186				 * character (if any) will go out.  Waiting
1187				 * isn't good since it allows races.  This
1188				 * will be fixed when the stop character is
1189				 * put in a special queue.  Don't bother with
1190				 * the checks in ttywait() since the timeout
1191				 * will save us.
1192				 */
1193				SET(tp->t_state, TS_SO_OCOMPLETE);
1194				ttysleep(tp, TSA_OCOMPLETE(tp), TTOPRI,
1195					 "ttyfls", hz / 10);
1196				/*
1197				 * Don't try sending the stop character again.
1198				 */
1199				CLR(tp->t_state, TS_TBLOCK);
1200				goto again;
1201			}
1202#endif
1203		}
1204	}
1205	if (rw & FWRITE) {
1206		FLUSHQ(&tp->t_outq);
1207		ttwwakeup(tp);
1208	}
1209	splx(s);
1210}
1211
1212/*
1213 * Copy in the default termios characters.
1214 */
1215void
1216termioschars(t)
1217	struct termios *t;
1218{
1219
1220	bcopy(ttydefchars, t->c_cc, sizeof t->c_cc);
1221}
1222
1223/*
1224 * Old interface.
1225 */
1226void
1227ttychars(tp)
1228	struct tty *tp;
1229{
1230
1231	termioschars(&tp->t_termios);
1232}
1233
1234/*
1235 * Handle input high water.  Send stop character for the IXOFF case.  Turn
1236 * on our input flow control bit and propagate the changes to the driver.
1237 * XXX the stop character should be put in a special high priority queue.
1238 */
1239void
1240ttyblock(tp)
1241	struct tty *tp;
1242{
1243
1244	SET(tp->t_state, TS_TBLOCK);
1245	if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
1246	    putc(tp->t_cc[VSTOP], &tp->t_outq) != 0)
1247		CLR(tp->t_state, TS_TBLOCK);	/* try again later */
1248	ttstart(tp);
1249}
1250
1251/*
1252 * Handle input low water.  Send start character for the IXOFF case.  Turn
1253 * off our input flow control bit and propagate the changes to the driver.
1254 * XXX the start character should be put in a special high priority queue.
1255 */
1256static void
1257ttyunblock(tp)
1258	struct tty *tp;
1259{
1260
1261	CLR(tp->t_state, TS_TBLOCK);
1262	if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTART] != _POSIX_VDISABLE &&
1263	    putc(tp->t_cc[VSTART], &tp->t_outq) != 0)
1264		SET(tp->t_state, TS_TBLOCK);	/* try again later */
1265	ttstart(tp);
1266}
1267
1268#ifdef notyet
1269/* Not used by any current (i386) drivers. */
1270/*
1271 * Restart after an inter-char delay.
1272 */
1273void
1274ttrstrt(tp_arg)
1275	void *tp_arg;
1276{
1277	struct tty *tp;
1278	int s;
1279
1280#ifdef DIAGNOSTIC
1281	if (tp_arg == NULL)
1282		panic("ttrstrt");
1283#endif
1284	tp = tp_arg;
1285	s = spltty();
1286
1287	CLR(tp->t_state, TS_TIMEOUT);
1288	ttstart(tp);
1289
1290	splx(s);
1291}
1292#endif
1293
1294int
1295ttstart(tp)
1296	struct tty *tp;
1297{
1298
1299	if (tp->t_oproc != NULL)	/* XXX: Kludge for pty. */
1300		(*tp->t_oproc)(tp);
1301	return (0);
1302}
1303
1304/*
1305 * "close" a line discipline
1306 */
1307int
1308ttylclose(tp, flag)
1309	struct tty *tp;
1310	int flag;
1311{
1312
1313	if (flag & FNONBLOCK || ttywflush(tp))
1314		ttyflush(tp, FREAD | FWRITE);
1315	return (0);
1316}
1317
1318/*
1319 * Handle modem control transition on a tty.
1320 * Flag indicates new state of carrier.
1321 * Returns 0 if the line should be turned off, otherwise 1.
1322 */
1323int
1324ttymodem(tp, flag)
1325	register struct tty *tp;
1326	int flag;
1327{
1328
1329	if (ISSET(tp->t_state, TS_CARR_ON) && ISSET(tp->t_cflag, MDMBUF)) {
1330		/*
1331		 * MDMBUF: do flow control according to carrier flag
1332		 * XXX TS_CAR_OFLOW doesn't do anything yet.  TS_TTSTOP
1333		 * works if IXON and IXANY are clear.
1334		 */
1335		if (flag) {
1336			CLR(tp->t_state, TS_CAR_OFLOW);
1337			CLR(tp->t_state, TS_TTSTOP);
1338			ttstart(tp);
1339		} else if (!ISSET(tp->t_state, TS_CAR_OFLOW)) {
1340			SET(tp->t_state, TS_CAR_OFLOW);
1341			SET(tp->t_state, TS_TTSTOP);
1342#ifdef sun4c						/* XXX */
1343			(*tp->t_stop)(tp, 0);
1344#else
1345			(*cdevsw[major(tp->t_dev)]->d_stop)(tp, 0);
1346#endif
1347		}
1348	} else if (flag == 0) {
1349		/*
1350		 * Lost carrier.
1351		 */
1352		CLR(tp->t_state, TS_CARR_ON);
1353		if (ISSET(tp->t_state, TS_ISOPEN) &&
1354		    !ISSET(tp->t_cflag, CLOCAL)) {
1355			SET(tp->t_state, TS_ZOMBIE);
1356			CLR(tp->t_state, TS_CONNECTED);
1357			if (tp->t_session && tp->t_session->s_leader)
1358				psignal(tp->t_session->s_leader, SIGHUP);
1359			ttyflush(tp, FREAD | FWRITE);
1360			return (0);
1361		}
1362	} else {
1363		/*
1364		 * Carrier now on.
1365		 */
1366		SET(tp->t_state, TS_CARR_ON);
1367		if (!ISSET(tp->t_state, TS_ZOMBIE))
1368			SET(tp->t_state, TS_CONNECTED);
1369		wakeup(TSA_CARR_ON(tp));
1370		ttwakeup(tp);
1371		ttwwakeup(tp);
1372	}
1373	return (1);
1374}
1375
1376/*
1377 * Reinput pending characters after state switch
1378 * call at spltty().
1379 */
1380static void
1381ttypend(tp)
1382	register struct tty *tp;
1383{
1384	struct clist tq;
1385	register int c;
1386
1387	CLR(tp->t_lflag, PENDIN);
1388	SET(tp->t_state, TS_TYPEN);
1389	/*
1390	 * XXX this assumes too much about clist internals.  It may even
1391	 * fail if the cblock slush pool is empty.  We can't allocate more
1392	 * cblocks here because we are called from an interrupt handler
1393	 * and clist_alloc_cblocks() can wait.
1394	 */
1395	tq = tp->t_rawq;
1396	bzero(&tp->t_rawq, sizeof tp->t_rawq);
1397	tp->t_rawq.c_cbmax = tq.c_cbmax;
1398	tp->t_rawq.c_cbreserved = tq.c_cbreserved;
1399	while ((c = getc(&tq)) >= 0)
1400		ttyinput(c, tp);
1401	CLR(tp->t_state, TS_TYPEN);
1402}
1403
1404/*
1405 * Process a read call on a tty device.
1406 */
1407int
1408ttread(tp, uio, flag)
1409	register struct tty *tp;
1410	struct uio *uio;
1411	int flag;
1412{
1413	register struct clist *qp;
1414	register int c;
1415	register tcflag_t lflag;
1416	register cc_t *cc = tp->t_cc;
1417	register struct proc *p = curproc;
1418	int s, first, error = 0;
1419	int has_stime = 0, last_cc = 0;
1420	long slp = 0;		/* XXX this should be renamed `timo'. */
1421
1422loop:
1423	s = spltty();
1424	lflag = tp->t_lflag;
1425	/*
1426	 * take pending input first
1427	 */
1428	if (ISSET(lflag, PENDIN)) {
1429		ttypend(tp);
1430		splx(s);	/* reduce latency */
1431		s = spltty();
1432		lflag = tp->t_lflag;	/* XXX ttypend() clobbers it */
1433	}
1434
1435	/*
1436	 * Hang process if it's in the background.
1437	 */
1438	if (isbackground(p, tp)) {
1439		splx(s);
1440		if ((p->p_sigignore & sigmask(SIGTTIN)) ||
1441		   (p->p_sigmask & sigmask(SIGTTIN)) ||
1442		    p->p_flag & P_PPWAIT || p->p_pgrp->pg_jobc == 0)
1443			return (EIO);
1444		pgsignal(p->p_pgrp, SIGTTIN, 1);
1445		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, "ttybg2", 0);
1446		if (error)
1447			return (error);
1448		goto loop;
1449	}
1450
1451	if (ISSET(tp->t_state, TS_ZOMBIE)) {
1452		splx(s);
1453		return (0);	/* EOF */
1454	}
1455
1456	/*
1457	 * If canonical, use the canonical queue,
1458	 * else use the raw queue.
1459	 *
1460	 * (should get rid of clists...)
1461	 */
1462	qp = ISSET(lflag, ICANON) ? &tp->t_canq : &tp->t_rawq;
1463
1464	if (flag & IO_NDELAY) {
1465		if (qp->c_cc > 0)
1466			goto read;
1467		if (!ISSET(lflag, ICANON) && cc[VMIN] == 0) {
1468			splx(s);
1469			return (0);
1470		}
1471		splx(s);
1472		return (EWOULDBLOCK);
1473	}
1474	if (!ISSET(lflag, ICANON)) {
1475		int m = cc[VMIN];
1476		long t = cc[VTIME];
1477		struct timeval stime, timecopy;
1478		int x;
1479
1480		/*
1481		 * Check each of the four combinations.
1482		 * (m > 0 && t == 0) is the normal read case.
1483		 * It should be fairly efficient, so we check that and its
1484		 * companion case (m == 0 && t == 0) first.
1485		 * For the other two cases, we compute the target sleep time
1486		 * into slp.
1487		 */
1488		if (t == 0) {
1489			if (qp->c_cc < m)
1490				goto sleep;
1491			if (qp->c_cc > 0)
1492				goto read;
1493
1494			/* m, t and qp->c_cc are all 0.  0 is enough input. */
1495			splx(s);
1496			return (0);
1497		}
1498		t *= 100000;		/* time in us */
1499#define diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 1000000 + \
1500			 ((t1).tv_usec - (t2).tv_usec))
1501		if (m > 0) {
1502			if (qp->c_cc <= 0)
1503				goto sleep;
1504			if (qp->c_cc >= m)
1505				goto read;
1506			x = splclock();
1507			timecopy = time;
1508			splx(x);
1509			if (!has_stime) {
1510				/* first character, start timer */
1511				has_stime = 1;
1512				stime = timecopy;
1513				slp = t;
1514			} else if (qp->c_cc > last_cc) {
1515				/* got a character, restart timer */
1516				stime = timecopy;
1517				slp = t;
1518			} else {
1519				/* nothing, check expiration */
1520				slp = t - diff(timecopy, stime);
1521				if (slp <= 0)
1522					goto read;
1523			}
1524			last_cc = qp->c_cc;
1525		} else {	/* m == 0 */
1526			if (qp->c_cc > 0)
1527				goto read;
1528			x = splclock();
1529			timecopy = time;
1530			splx(x);
1531			if (!has_stime) {
1532				has_stime = 1;
1533				stime = timecopy;
1534				slp = t;
1535			} else {
1536				slp = t - diff(timecopy, stime);
1537				if (slp <= 0) {
1538					/* Timed out, but 0 is enough input. */
1539					splx(s);
1540					return (0);
1541				}
1542			}
1543		}
1544#undef diff
1545		/*
1546		 * Rounding down may make us wake up just short
1547		 * of the target, so we round up.
1548		 * The formula is ceiling(slp * hz/1000000).
1549		 * 32-bit arithmetic is enough for hz < 169.
1550		 * XXX see hzto() for how to avoid overflow if hz
1551		 * is large (divide by `tick' and/or arrange to
1552		 * use hzto() if hz is large).
1553		 */
1554		slp = (long) (((u_long)slp * hz) + 999999) / 1000000;
1555		goto sleep;
1556	}
1557	if (qp->c_cc <= 0) {
1558sleep:
1559		/*
1560		 * There is no input, or not enough input and we can block.
1561		 */
1562		error = ttysleep(tp, TSA_HUP_OR_INPUT(tp), TTIPRI | PCATCH,
1563				 ISSET(tp->t_state, TS_CONNECTED) ?
1564				 "ttyin" : "ttyhup", (int)slp);
1565		splx(s);
1566		if (error == EWOULDBLOCK)
1567			error = 0;
1568		else if (error)
1569			return (error);
1570		/*
1571		 * XXX what happens if another process eats some input
1572		 * while we are asleep (not just here)?  It would be
1573		 * safest to detect changes and reset our state variables
1574		 * (has_stime and last_cc).
1575		 */
1576		slp = 0;
1577		goto loop;
1578	}
1579read:
1580	splx(s);
1581	/*
1582	 * Input present, check for input mapping and processing.
1583	 */
1584	first = 1;
1585	if (ISSET(lflag, ICANON | ISIG))
1586		goto slowcase;
1587	for (;;) {
1588		char ibuf[IBUFSIZ];
1589		int icc;
1590
1591		icc = imin(uio->uio_resid, IBUFSIZ);
1592		icc = q_to_b(qp, ibuf, icc);
1593		if (icc <= 0) {
1594			if (first)
1595				goto loop;
1596			break;
1597		}
1598		error = uiomove(ibuf, icc, uio);
1599		/*
1600		 * XXX if there was an error then we should ungetc() the
1601		 * unmoved chars and reduce icc here.
1602		 */
1603#if NSNP > 0
1604		if (ISSET(tp->t_lflag, ECHO) &&
1605		    ISSET(tp->t_state, TS_SNOOP) && tp->t_sc != NULL)
1606			snpin((struct snoop *)tp->t_sc, ibuf, icc);
1607#endif
1608		if (error)
1609			break;
1610 		if (uio->uio_resid == 0)
1611			break;
1612		first = 0;
1613	}
1614	goto out;
1615slowcase:
1616	for (;;) {
1617		c = getc(qp);
1618		if (c < 0) {
1619			if (first)
1620				goto loop;
1621			break;
1622		}
1623		/*
1624		 * delayed suspend (^Y)
1625		 */
1626		if (CCEQ(cc[VDSUSP], c) && ISSET(lflag, ISIG)) {
1627			pgsignal(tp->t_pgrp, SIGTSTP, 1);
1628			if (first) {
1629				error = ttysleep(tp, &lbolt, TTIPRI | PCATCH,
1630						 "ttybg3", 0);
1631				if (error)
1632					break;
1633				goto loop;
1634			}
1635			break;
1636		}
1637		/*
1638		 * Interpret EOF only in canonical mode.
1639		 */
1640		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
1641			break;
1642		/*
1643		 * Give user character.
1644		 */
1645 		error = ureadc(c, uio);
1646		if (error)
1647			/* XXX should ungetc(c, qp). */
1648			break;
1649#if NSNP > 0
1650		/*
1651		 * Only snoop directly on input in echo mode.  Non-echoed
1652		 * input will be snooped later iff the application echoes it.
1653		 */
1654		if (ISSET(tp->t_lflag, ECHO) &&
1655		    ISSET(tp->t_state, TS_SNOOP) && tp->t_sc != NULL)
1656			snpinc((struct snoop *)tp->t_sc, (char)c);
1657#endif
1658 		if (uio->uio_resid == 0)
1659			break;
1660		/*
1661		 * In canonical mode check for a "break character"
1662		 * marking the end of a "line of input".
1663		 */
1664		if (ISSET(lflag, ICANON) && TTBREAKC(c))
1665			break;
1666		first = 0;
1667	}
1668
1669out:
1670	/*
1671	 * Look to unblock input now that (presumably)
1672	 * the input queue has gone down.
1673	 */
1674	s = spltty();
1675	if (ISSET(tp->t_state, TS_TBLOCK) &&
1676	    tp->t_rawq.c_cc + tp->t_canq.c_cc <= I_LOW_WATER)
1677		ttyunblock(tp);
1678	splx(s);
1679
1680	return (error);
1681}
1682
1683/*
1684 * Check the output queue on tp for space for a kernel message (from uprintf
1685 * or tprintf).  Allow some space over the normal hiwater mark so we don't
1686 * lose messages due to normal flow control, but don't let the tty run amok.
1687 * Sleeps here are not interruptible, but we return prematurely if new signals
1688 * arrive.
1689 */
1690int
1691ttycheckoutq(tp, wait)
1692	register struct tty *tp;
1693	int wait;
1694{
1695	int hiwat, s, oldsig;
1696
1697	hiwat = tp->t_hiwat;
1698	s = spltty();
1699	oldsig = wait ? curproc->p_siglist : 0;
1700	if (tp->t_outq.c_cc > hiwat + 200)
1701		while (tp->t_outq.c_cc > hiwat) {
1702			ttstart(tp);
1703			if (tp->t_outq.c_cc <= hiwat)
1704				break;
1705			if (wait == 0 || curproc->p_siglist != oldsig) {
1706				splx(s);
1707				return (0);
1708			}
1709			SET(tp->t_state, TS_SO_OLOWAT);
1710			tsleep(TSA_OLOWAT(tp), PZERO - 1, "ttoutq", hz);
1711		}
1712	splx(s);
1713	return (1);
1714}
1715
1716/*
1717 * Process a write call on a tty device.
1718 */
1719int
1720ttwrite(tp, uio, flag)
1721	register struct tty *tp;
1722	register struct uio *uio;
1723	int flag;
1724{
1725	register char *cp = NULL;
1726	register int cc, ce;
1727	register struct proc *p;
1728	int i, hiwat, cnt, error, s;
1729	char obuf[OBUFSIZ];
1730
1731	hiwat = tp->t_hiwat;
1732	cnt = uio->uio_resid;
1733	error = 0;
1734	cc = 0;
1735loop:
1736	s = spltty();
1737	if (ISSET(tp->t_state, TS_ZOMBIE)) {
1738		splx(s);
1739		if (uio->uio_resid == cnt)
1740			error = EIO;
1741		goto out;
1742	}
1743	if (!ISSET(tp->t_state, TS_CONNECTED)) {
1744		if (flag & IO_NDELAY) {
1745			splx(s);
1746			error = EWOULDBLOCK;
1747			goto out;
1748		}
1749		error = ttysleep(tp, TSA_CARR_ON(tp), TTIPRI | PCATCH,
1750				 "ttydcd", 0);
1751		splx(s);
1752		if (error)
1753			goto out;
1754		goto loop;
1755	}
1756	splx(s);
1757	/*
1758	 * Hang the process if it's in the background.
1759	 */
1760	p = curproc;
1761	if (isbackground(p, tp) &&
1762	    ISSET(tp->t_lflag, TOSTOP) && (p->p_flag & P_PPWAIT) == 0 &&
1763	    (p->p_sigignore & sigmask(SIGTTOU)) == 0 &&
1764	    (p->p_sigmask & sigmask(SIGTTOU)) == 0 &&
1765	     p->p_pgrp->pg_jobc) {
1766		pgsignal(p->p_pgrp, SIGTTOU, 1);
1767		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, "ttybg4", 0);
1768		if (error)
1769			goto out;
1770		goto loop;
1771	}
1772	/*
1773	 * Process the user's data in at most OBUFSIZ chunks.  Perform any
1774	 * output translation.  Keep track of high water mark, sleep on
1775	 * overflow awaiting device aid in acquiring new space.
1776	 */
1777	while (uio->uio_resid > 0 || cc > 0) {
1778		if (ISSET(tp->t_lflag, FLUSHO)) {
1779			uio->uio_resid = 0;
1780			return (0);
1781		}
1782		if (tp->t_outq.c_cc > hiwat)
1783			goto ovhiwat;
1784		/*
1785		 * Grab a hunk of data from the user, unless we have some
1786		 * leftover from last time.
1787		 */
1788		if (cc == 0) {
1789			cc = imin(uio->uio_resid, OBUFSIZ);
1790			cp = obuf;
1791			error = uiomove(cp, cc, uio);
1792			if (error) {
1793				cc = 0;
1794				break;
1795			}
1796#if NSNP > 0
1797			if (ISSET(tp->t_state, TS_SNOOP) && tp->t_sc != NULL)
1798				snpin((struct snoop *)tp->t_sc, cp, cc);
1799#endif
1800		}
1801		/*
1802		 * If nothing fancy need be done, grab those characters we
1803		 * can handle without any of ttyoutput's processing and
1804		 * just transfer them to the output q.  For those chars
1805		 * which require special processing (as indicated by the
1806		 * bits in char_type), call ttyoutput.  After processing
1807		 * a hunk of data, look for FLUSHO so ^O's will take effect
1808		 * immediately.
1809		 */
1810		while (cc > 0) {
1811			if (!ISSET(tp->t_oflag, OPOST))
1812				ce = cc;
1813			else {
1814				ce = cc - scanc((u_int)cc, (u_char *)cp,
1815				   (u_char *)char_type, CCLASSMASK);
1816				/*
1817				 * If ce is zero, then we're processing
1818				 * a special character through ttyoutput.
1819				 */
1820				if (ce == 0) {
1821					tp->t_rocount = 0;
1822					if (ttyoutput(*cp, tp) >= 0) {
1823						/* No Clists, wait a bit. */
1824						ttstart(tp);
1825						if (flag & IO_NDELAY) {
1826							error = EWOULDBLOCK;
1827							goto out;
1828						}
1829						error = ttysleep(tp, &lbolt,
1830								 TTOPRI|PCATCH,
1831								 "ttybf1", 0);
1832						if (error)
1833							goto out;
1834						goto loop;
1835					}
1836					cp++;
1837					cc--;
1838					if (ISSET(tp->t_lflag, FLUSHO) ||
1839					    tp->t_outq.c_cc > hiwat)
1840						goto ovhiwat;
1841					continue;
1842				}
1843			}
1844			/*
1845			 * A bunch of normal characters have been found.
1846			 * Transfer them en masse to the output queue and
1847			 * continue processing at the top of the loop.
1848			 * If there are any further characters in this
1849			 * <= OBUFSIZ chunk, the first should be a character
1850			 * requiring special handling by ttyoutput.
1851			 */
1852			tp->t_rocount = 0;
1853			i = b_to_q(cp, ce, &tp->t_outq);
1854			ce -= i;
1855			tp->t_column += ce;
1856			cp += ce, cc -= ce, tk_nout += ce;
1857			tp->t_outcc += ce;
1858			if (i > 0) {
1859				/* No Clists, wait a bit. */
1860				ttstart(tp);
1861				if (flag & IO_NDELAY) {
1862					error = EWOULDBLOCK;
1863					goto out;
1864				}
1865				error = ttysleep(tp, &lbolt, TTOPRI | PCATCH,
1866						 "ttybf2", 0);
1867				if (error)
1868					goto out;
1869				goto loop;
1870			}
1871			if (ISSET(tp->t_lflag, FLUSHO) ||
1872			    tp->t_outq.c_cc > hiwat)
1873				break;
1874		}
1875		ttstart(tp);
1876	}
1877out:
1878	/*
1879	 * If cc is nonzero, we leave the uio structure inconsistent, as the
1880	 * offset and iov pointers have moved forward, but it doesn't matter
1881	 * (the call will either return short or restart with a new uio).
1882	 */
1883	uio->uio_resid += cc;
1884	return (error);
1885
1886ovhiwat:
1887	ttstart(tp);
1888	s = spltty();
1889	/*
1890	 * This can only occur if FLUSHO is set in t_lflag,
1891	 * or if ttstart/oproc is synchronous (or very fast).
1892	 */
1893	if (tp->t_outq.c_cc <= hiwat) {
1894		splx(s);
1895		goto loop;
1896	}
1897	if (flag & IO_NDELAY) {
1898		splx(s);
1899		uio->uio_resid += cc;
1900		return (uio->uio_resid == cnt ? EWOULDBLOCK : 0);
1901	}
1902	SET(tp->t_state, TS_SO_OLOWAT);
1903	error = ttysleep(tp, TSA_OLOWAT(tp), TTOPRI | PCATCH, "ttywri",
1904			 tp->t_timeout);
1905	splx(s);
1906	if (error == EWOULDBLOCK)
1907		error = EIO;
1908	if (error)
1909		goto out;
1910	goto loop;
1911}
1912
1913/*
1914 * Rubout one character from the rawq of tp
1915 * as cleanly as possible.
1916 */
1917static void
1918ttyrub(c, tp)
1919	register int c;
1920	register struct tty *tp;
1921{
1922	register char *cp;
1923	register int savecol;
1924	int tabc, s;
1925
1926	if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
1927		return;
1928	CLR(tp->t_lflag, FLUSHO);
1929	if (ISSET(tp->t_lflag, ECHOE)) {
1930		if (tp->t_rocount == 0) {
1931			/*
1932			 * Screwed by ttwrite; retype
1933			 */
1934			ttyretype(tp);
1935			return;
1936		}
1937		if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
1938			ttyrubo(tp, 2);
1939		else {
1940			CLR(c, ~TTY_CHARMASK);
1941			switch (CCLASS(c)) {
1942			case ORDINARY:
1943				ttyrubo(tp, 1);
1944				break;
1945			case BACKSPACE:
1946			case CONTROL:
1947			case NEWLINE:
1948			case RETURN:
1949			case VTAB:
1950				if (ISSET(tp->t_lflag, ECHOCTL))
1951					ttyrubo(tp, 2);
1952				break;
1953			case TAB:
1954				if (tp->t_rocount < tp->t_rawq.c_cc) {
1955					ttyretype(tp);
1956					return;
1957				}
1958				s = spltty();
1959				savecol = tp->t_column;
1960				SET(tp->t_state, TS_CNTTB);
1961				SET(tp->t_lflag, FLUSHO);
1962				tp->t_column = tp->t_rocol;
1963				cp = tp->t_rawq.c_cf;
1964				if (cp)
1965					tabc = *cp;	/* XXX FIX NEXTC */
1966				for (; cp; cp = nextc(&tp->t_rawq, cp, &tabc))
1967					ttyecho(tabc, tp);
1968				CLR(tp->t_lflag, FLUSHO);
1969				CLR(tp->t_state, TS_CNTTB);
1970				splx(s);
1971
1972				/* savecol will now be length of the tab. */
1973				savecol -= tp->t_column;
1974				tp->t_column += savecol;
1975				if (savecol > 8)
1976					savecol = 8;	/* overflow screw */
1977				while (--savecol >= 0)
1978					(void)ttyoutput('\b', tp);
1979				break;
1980			default:			/* XXX */
1981#define	PANICSTR	"ttyrub: would panic c = %d, val = %d\n"
1982				(void)printf(PANICSTR, c, CCLASS(c));
1983#ifdef notdef
1984				panic(PANICSTR, c, CCLASS(c));
1985#endif
1986			}
1987		}
1988	} else if (ISSET(tp->t_lflag, ECHOPRT)) {
1989		if (!ISSET(tp->t_state, TS_ERASE)) {
1990			SET(tp->t_state, TS_ERASE);
1991			(void)ttyoutput('\\', tp);
1992		}
1993		ttyecho(c, tp);
1994	} else
1995		ttyecho(tp->t_cc[VERASE], tp);
1996	--tp->t_rocount;
1997}
1998
1999/*
2000 * Back over cnt characters, erasing them.
2001 */
2002static void
2003ttyrubo(tp, cnt)
2004	register struct tty *tp;
2005	int cnt;
2006{
2007
2008	while (cnt-- > 0) {
2009		(void)ttyoutput('\b', tp);
2010		(void)ttyoutput(' ', tp);
2011		(void)ttyoutput('\b', tp);
2012	}
2013}
2014
2015/*
2016 * ttyretype --
2017 *	Reprint the rawq line.  Note, it is assumed that c_cc has already
2018 *	been checked.
2019 */
2020static void
2021ttyretype(tp)
2022	register struct tty *tp;
2023{
2024	register char *cp;
2025	int s, c;
2026
2027	/* Echo the reprint character. */
2028	if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
2029		ttyecho(tp->t_cc[VREPRINT], tp);
2030
2031	(void)ttyoutput('\n', tp);
2032
2033	/*
2034	 * XXX
2035	 * FIX: NEXTC IS BROKEN - DOESN'T CHECK QUOTE
2036	 * BIT OF FIRST CHAR.
2037	 */
2038	s = spltty();
2039	for (cp = tp->t_canq.c_cf, c = (cp != NULL ? *cp : 0);
2040	    cp != NULL; cp = nextc(&tp->t_canq, cp, &c))
2041		ttyecho(c, tp);
2042	for (cp = tp->t_rawq.c_cf, c = (cp != NULL ? *cp : 0);
2043	    cp != NULL; cp = nextc(&tp->t_rawq, cp, &c))
2044		ttyecho(c, tp);
2045	CLR(tp->t_state, TS_ERASE);
2046	splx(s);
2047
2048	tp->t_rocount = tp->t_rawq.c_cc;
2049	tp->t_rocol = 0;
2050}
2051
2052/*
2053 * Echo a typed character to the terminal.
2054 */
2055static void
2056ttyecho(c, tp)
2057	register int c;
2058	register struct tty *tp;
2059{
2060
2061	if (!ISSET(tp->t_state, TS_CNTTB))
2062		CLR(tp->t_lflag, FLUSHO);
2063	if ((!ISSET(tp->t_lflag, ECHO) &&
2064	     (c != '\n' || !ISSET(tp->t_lflag, ECHONL))) ||
2065	    ISSET(tp->t_lflag, EXTPROC))
2066		return;
2067	if (ISSET(tp->t_lflag, ECHOCTL) &&
2068	    ((ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n') ||
2069	    ISSET(c, TTY_CHARMASK) == 0177)) {
2070		(void)ttyoutput('^', tp);
2071		CLR(c, ~TTY_CHARMASK);
2072		if (c == 0177)
2073			c = '?';
2074		else
2075			c += 'A' - 1;
2076	}
2077	(void)ttyoutput(c, tp);
2078}
2079
2080/*
2081 * Wake up any readers on a tty.
2082 */
2083void
2084ttwakeup(tp)
2085	register struct tty *tp;
2086{
2087
2088	if (tp->t_rsel.si_pid != 0)
2089		selwakeup(&tp->t_rsel);
2090	if (ISSET(tp->t_state, TS_ASYNC))
2091		pgsignal(tp->t_pgrp, SIGIO, 1);
2092	wakeup(TSA_HUP_OR_INPUT(tp));
2093}
2094
2095/*
2096 * Wake up any writers on a tty.
2097 */
2098void
2099ttwwakeup(tp)
2100	register struct tty *tp;
2101{
2102
2103	if (tp->t_wsel.si_pid != 0 && tp->t_outq.c_cc <= tp->t_lowat)
2104		selwakeup(&tp->t_wsel);
2105	if (ISSET(tp->t_state, TS_BUSY | TS_SO_OCOMPLETE) ==
2106	    TS_SO_OCOMPLETE && tp->t_outq.c_cc == 0) {
2107		CLR(tp->t_state, TS_SO_OCOMPLETE);
2108		wakeup(TSA_OCOMPLETE(tp));
2109	}
2110	if (ISSET(tp->t_state, TS_SO_OLOWAT) &&
2111	    tp->t_outq.c_cc <= tp->t_lowat) {
2112		CLR(tp->t_state, TS_SO_OLOWAT);
2113		wakeup(TSA_OLOWAT(tp));
2114	}
2115}
2116
2117/*
2118 * Look up a code for a specified speed in a conversion table;
2119 * used by drivers to map software speed values to hardware parameters.
2120 */
2121int
2122ttspeedtab(speed, table)
2123	int speed;
2124	register struct speedtab *table;
2125{
2126
2127	for ( ; table->sp_speed != -1; table++)
2128		if (table->sp_speed == speed)
2129			return (table->sp_code);
2130	return (-1);
2131}
2132
2133/*
2134 * Set tty hi and low water marks.
2135 *
2136 * Try to arrange the dynamics so there's about one second
2137 * from hi to low water.
2138 *
2139 */
2140void
2141ttsetwater(tp)
2142	struct tty *tp;
2143{
2144	register int cps, x;
2145
2146#define CLAMP(x, h, l)	((x) > h ? h : ((x) < l) ? l : (x))
2147
2148	cps = tp->t_ospeed / 10;
2149	tp->t_lowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
2150	x += cps;
2151	x = CLAMP(x, TTMAXHIWAT, TTMINHIWAT);
2152	tp->t_hiwat = roundup(x, CBSIZE);
2153#undef	CLAMP
2154}
2155
2156/*
2157 * Report on state of foreground process group.
2158 */
2159void
2160ttyinfo(tp)
2161	register struct tty *tp;
2162{
2163	register struct proc *p, *pick;
2164	struct timeval utime, stime;
2165	int tmp;
2166
2167	if (ttycheckoutq(tp,0) == 0)
2168		return;
2169
2170	/* Print load average. */
2171	tmp = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
2172	ttyprintf(tp, "load: %d.%02d ", tmp / 100, tmp % 100);
2173
2174	if (tp->t_session == NULL)
2175		ttyprintf(tp, "not a controlling terminal\n");
2176	else if (tp->t_pgrp == NULL)
2177		ttyprintf(tp, "no foreground process group\n");
2178	else if ((p = tp->t_pgrp->pg_mem) == NULL)
2179		ttyprintf(tp, "empty foreground process group\n");
2180	else {
2181		/* Pick interesting process. */
2182		for (pick = NULL; p != NULL; p = p->p_pgrpnxt)
2183			if (proc_compare(pick, p))
2184				pick = p;
2185
2186		ttyprintf(tp, " cmd: %s %d [%s] ", pick->p_comm, pick->p_pid,
2187		    pick->p_stat == SRUN ? "running" :
2188		    pick->p_wmesg ? pick->p_wmesg : "iowait");
2189
2190		calcru(pick, &utime, &stime, NULL);
2191
2192		/* Print user time. */
2193		ttyprintf(tp, "%d.%02du ",
2194		    utime.tv_sec, utime.tv_usec / 10000);
2195
2196		/* Print system time. */
2197		ttyprintf(tp, "%d.%02ds ",
2198		    stime.tv_sec, stime.tv_usec / 10000);
2199
2200#define	pgtok(a)	(((a) * NBPG) / 1024)
2201		/* Print percentage cpu, resident set size. */
2202		tmp = (pick->p_pctcpu * 10000 + FSCALE / 2) >> FSHIFT;
2203		ttyprintf(tp, "%d%% %dk\n",
2204		    tmp / 100,
2205		    pick->p_stat == SIDL || pick->p_stat == SZOMB ? 0 :
2206#ifdef pmap_resident_count
2207			pgtok(pmap_resident_count(&pick->p_vmspace->vm_pmap))
2208#else
2209			pgtok(pick->p_vmspace->vm_rssize)
2210#endif
2211			);
2212	}
2213	tp->t_rocount = 0;	/* so pending input will be retyped if BS */
2214}
2215
2216/*
2217 * Returns 1 if p2 is "better" than p1
2218 *
2219 * The algorithm for picking the "interesting" process is thus:
2220 *
2221 *	1) Only foreground processes are eligible - implied.
2222 *	2) Runnable processes are favored over anything else.  The runner
2223 *	   with the highest cpu utilization is picked (p_estcpu).  Ties are
2224 *	   broken by picking the highest pid.
2225 *	3) The sleeper with the shortest sleep time is next.  With ties,
2226 *	   we pick out just "short-term" sleepers (P_SINTR == 0).
2227 *	4) Further ties are broken by picking the highest pid.
2228 */
2229#define ISRUN(p)	(((p)->p_stat == SRUN) || ((p)->p_stat == SIDL))
2230#define TESTAB(a, b)    ((a)<<1 | (b))
2231#define ONLYA   2
2232#define ONLYB   1
2233#define BOTH    3
2234
2235static int
2236proc_compare(p1, p2)
2237	register struct proc *p1, *p2;
2238{
2239
2240	if (p1 == NULL)
2241		return (1);
2242	/*
2243	 * see if at least one of them is runnable
2244	 */
2245	switch (TESTAB(ISRUN(p1), ISRUN(p2))) {
2246	case ONLYA:
2247		return (0);
2248	case ONLYB:
2249		return (1);
2250	case BOTH:
2251		/*
2252		 * tie - favor one with highest recent cpu utilization
2253		 */
2254		if (p2->p_estcpu > p1->p_estcpu)
2255			return (1);
2256		if (p1->p_estcpu > p2->p_estcpu)
2257			return (0);
2258		return (p2->p_pid > p1->p_pid);	/* tie - return highest pid */
2259	}
2260	/*
2261 	 * weed out zombies
2262	 */
2263	switch (TESTAB(p1->p_stat == SZOMB, p2->p_stat == SZOMB)) {
2264	case ONLYA:
2265		return (1);
2266	case ONLYB:
2267		return (0);
2268	case BOTH:
2269		return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
2270	}
2271	/*
2272	 * pick the one with the smallest sleep time
2273	 */
2274	if (p2->p_slptime > p1->p_slptime)
2275		return (0);
2276	if (p1->p_slptime > p2->p_slptime)
2277		return (1);
2278	/*
2279	 * favor one sleeping in a non-interruptible sleep
2280	 */
2281	if (p1->p_flag & P_SINTR && (p2->p_flag & P_SINTR) == 0)
2282		return (1);
2283	if (p2->p_flag & P_SINTR && (p1->p_flag & P_SINTR) == 0)
2284		return (0);
2285	return (p2->p_pid > p1->p_pid);		/* tie - return highest pid */
2286}
2287
2288/*
2289 * Output char to tty; console putchar style.
2290 */
2291int
2292tputchar(c, tp)
2293	int c;
2294	struct tty *tp;
2295{
2296	register int s;
2297
2298	s = spltty();
2299	if (!ISSET(tp->t_state, TS_CONNECTED)) {
2300		splx(s);
2301		return (-1);
2302	}
2303	if (c == '\n')
2304		(void)ttyoutput('\r', tp);
2305	(void)ttyoutput(c, tp);
2306	ttstart(tp);
2307	splx(s);
2308	return (0);
2309}
2310
2311/*
2312 * Sleep on chan, returning ERESTART if tty changed while we napped and
2313 * returning any errors (e.g. EINTR/ETIMEDOUT) reported by tsleep.  If
2314 * the tty is revoked, restarting a pending call will redo validation done
2315 * at the start of the call.
2316 */
2317int
2318ttysleep(tp, chan, pri, wmesg, timo)
2319	struct tty *tp;
2320	void *chan;
2321	int pri, timo;
2322	char *wmesg;
2323{
2324	int error;
2325	int gen;
2326
2327	gen = tp->t_gen;
2328	error = tsleep(chan, pri, wmesg, timo);
2329	if (error)
2330		return (error);
2331	return (tp->t_gen == gen ? 0 : ERESTART);
2332}
2333
2334#ifdef notyet
2335/*
2336 * XXX this is usable not useful or used.  Most tty drivers have
2337 * ifdefs for using ttymalloc() but assume a different interface.
2338 */
2339/*
2340 * Allocate a tty struct.  Clists in the struct will be allocated by
2341 * ttyopen().
2342 */
2343struct tty *
2344ttymalloc()
2345{
2346        struct tty *tp;
2347
2348        tp = malloc(sizeof *tp, M_TTYS, M_WAITOK);
2349        bzero(tp, sizeof *tp);
2350        return (tp);
2351}
2352#endif
2353
2354#if 0 /* XXX not yet usable: session leader holds a ref (see kern_exit.c). */
2355/*
2356 * Free a tty struct.  Clists in the struct should have been freed by
2357 * ttyclose().
2358 */
2359void
2360ttyfree(tp)
2361	struct tty *tp;
2362{
2363        free(tp, M_TTYS);
2364}
2365#endif /* 0 */
2366