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