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