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