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