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