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