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