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