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