xref: /netbsd-src/sys/kern/tty.c (revision 0dd5877adce57db949b16ae963e5a6831cccdfb6)
1 /*	$NetBSD: tty.c,v 1.131 2002/02/08 18:36:53 christos 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.131 2002/02/08 18:36:53 christos 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 	tp->t_session = NULL;
271 	tp->t_state = 0;
272 	return (0);
273 }
274 
275 #define	FLUSHQ(q) {							\
276 	if ((q)->c_cc)							\
277 		ndflush(q, (q)->c_cc);					\
278 }
279 
280 /*
281  * This macro is used in canonical mode input processing, where a read
282  * request shall not return unless a 'line delimiter' ('\n') or 'break'
283  * (EOF, EOL, EOL2) character (or a signal) has been received. As EOL2
284  * is an extension to the POSIX.1 defined set of special characters,
285  * recognize it only if IEXTEN is set in the set of local flags.
286  */
287 #define	TTBREAKC(c, lflg)						\
288 	((c) == '\n' || (((c) == cc[VEOF] || (c) == cc[VEOL] ||		\
289 	((c) == cc[VEOL2] && ISSET(lflg, IEXTEN))) && (c) != _POSIX_VDISABLE))
290 
291 
292 /*
293  * Process input of a single character received on a tty.
294  */
295 int
296 ttyinput(int c, struct tty *tp)
297 {
298 	int	iflag, lflag, i, error;
299 	u_char	*cc;
300 
301 	/*
302 	 * Unless the receiver is enabled, drop incoming data.
303 	 */
304 	if (!ISSET(tp->t_cflag, CREAD))
305 		return (0);
306 
307 	/*
308 	 * If input is pending take it first.
309 	 */
310 	lflag = tp->t_lflag;
311 	if (ISSET(lflag, PENDIN))
312 		ttypend(tp);
313 	/*
314 	 * Gather stats.
315 	 */
316 	if (ISSET(lflag, ICANON)) {
317 		++tk_cancc;
318 		++tp->t_cancc;
319 	} else {
320 		++tk_rawcc;
321 		++tp->t_rawcc;
322 	}
323 	++tk_nin;
324 
325 	cc = tp->t_cc;
326 
327 	/*
328 	 * Handle exceptional conditions (break, parity, framing).
329 	 */
330 	iflag = tp->t_iflag;
331 	if ((error = (ISSET(c, TTY_ERRORMASK))) != 0) {
332 		CLR(c, TTY_ERRORMASK);
333 		if (ISSET(error, TTY_FE) && c == 0) {		/* Break. */
334 			if (ISSET(iflag, IGNBRK))
335 				return (0);
336 			else if (ISSET(iflag, BRKINT)) {
337 				ttyflush(tp, FREAD | FWRITE);
338 				pgsignal(tp->t_pgrp, SIGINT, 1);
339 				return (0);
340 			}
341 			else if (ISSET(iflag, PARMRK))
342 				goto parmrk;
343 		}
344 		else if ((ISSET(error, TTY_PE) && ISSET(iflag, INPCK)) ||
345 		    ISSET(error, TTY_FE)) {
346 			if (ISSET(iflag, IGNPAR))
347 				return (0);
348 			else if (ISSET(iflag, PARMRK)) {
349  parmrk:			(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
350 				(void)putc(0    | TTY_QUOTE, &tp->t_rawq);
351 				(void)putc(c    | TTY_QUOTE, &tp->t_rawq);
352 				return (0);
353 			}
354 			else
355 				c = 0;
356 		}
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 					(*cdevsw[major(tp->t_dev)].d_stop)(tp,
446 					   0);
447 					return (0);
448 				}
449 				if (!CCEQ(cc[VSTART], c))
450 					return (0);
451 				/*
452 				 * if VSTART == VSTOP then toggle
453 				 */
454 				goto endcase;
455 			}
456 			if (CCEQ(cc[VSTART], c))
457 				goto restartoutput;
458 		}
459 		/*
460 		 * IGNCR, ICRNL, & INLCR
461 		 */
462 		if (c == '\r') {
463 			if (ISSET(iflag, IGNCR))
464 				goto endcase;
465 			else if (ISSET(iflag, ICRNL))
466 				c = '\n';
467 		} else if (c == '\n' && ISSET(iflag, INLCR))
468 			c = '\r';
469 	}
470 	if (!ISSET(tp->t_lflag, EXTPROC) && ISSET(lflag, ICANON)) {
471 		/*
472 		 * From here on down canonical mode character
473 		 * processing takes place.
474 		 */
475 		/*
476 		 * erase (^H / ^?)
477 		 */
478 		if (CCEQ(cc[VERASE], c)) {
479 			if (tp->t_rawq.c_cc)
480 				ttyrub(unputc(&tp->t_rawq), tp);
481 			goto endcase;
482 		}
483 		/*
484 		 * kill (^U)
485 		 */
486 		if (CCEQ(cc[VKILL], c)) {
487 			if (ISSET(lflag, ECHOKE) &&
488 			    tp->t_rawq.c_cc == tp->t_rocount &&
489 			    !ISSET(lflag, ECHOPRT))
490 				while (tp->t_rawq.c_cc)
491 					ttyrub(unputc(&tp->t_rawq), tp);
492 			else {
493 				ttyecho(c, tp);
494 				if (ISSET(lflag, ECHOK) ||
495 				    ISSET(lflag, ECHOKE))
496 					ttyecho('\n', tp);
497 				FLUSHQ(&tp->t_rawq);
498 				tp->t_rocount = 0;
499 			}
500 			CLR(tp->t_state, TS_LOCAL);
501 			goto endcase;
502 		}
503 		/*
504 		 * Extensions to the POSIX.1 GTI set of functions.
505 		 */
506 		if (ISSET(lflag, IEXTEN)) {
507 			/*
508 			 * word erase (^W)
509 			 */
510 			if (CCEQ(cc[VWERASE], c)) {
511 				int alt = ISSET(lflag, ALTWERASE);
512 				int ctype;
513 
514 				/*
515 				 * erase whitespace
516 				 */
517 				while ((c = unputc(&tp->t_rawq)) == ' ' ||
518 				       c == '\t')
519 					ttyrub(c, tp);
520 				if (c == -1)
521 					goto endcase;
522 				/*
523 				 * erase last char of word and remember the
524 				 * next chars type (for ALTWERASE)
525 				 */
526 				ttyrub(c, tp);
527 				c = unputc(&tp->t_rawq);
528 				if (c == -1)
529 					goto endcase;
530 				if (c == ' ' || c == '\t') {
531 					(void)putc(c, &tp->t_rawq);
532 					goto endcase;
533 				}
534 				ctype = ISALPHA(c);
535 				/*
536 				 * erase rest of word
537 				 */
538 				do {
539 					ttyrub(c, tp);
540 					c = unputc(&tp->t_rawq);
541 					if (c == -1)
542 						goto endcase;
543 				} while (c != ' ' && c != '\t' &&
544 				         (alt == 0 || ISALPHA(c) == ctype));
545 				(void)putc(c, &tp->t_rawq);
546 				goto endcase;
547 			}
548 			/*
549 			 * reprint line (^R)
550 			 */
551 			if (CCEQ(cc[VREPRINT], c)) {
552 				ttyretype(tp);
553 				goto endcase;
554 			}
555 			/*
556 			 * ^T - kernel info and generate SIGINFO
557 			 */
558 			if (CCEQ(cc[VSTATUS], c)) {
559 				if (ISSET(lflag, ISIG))
560 					pgsignal(tp->t_pgrp, SIGINFO, 1);
561 				if (!ISSET(lflag, NOKERNINFO))
562 					ttyinfo(tp);
563 				goto endcase;
564 			}
565 		}
566 	}
567 	/*
568 	 * Check for input buffer overflow
569 	 */
570 	if (tp->t_rawq.c_cc + tp->t_canq.c_cc >= TTYHOG) {
571 		if (ISSET(iflag, IMAXBEL)) {
572 			if (tp->t_outq.c_cc < tp->t_hiwat)
573 				(void)ttyoutput(CTRL('g'), tp);
574 		} else
575 			ttyflush(tp, FREAD | FWRITE);
576 		goto endcase;
577 	}
578 	/*
579 	 * Put data char in q for user and
580 	 * wakeup on seeing a line delimiter.
581 	 */
582 	if (putc(c, &tp->t_rawq) >= 0) {
583 		if (!ISSET(lflag, ICANON)) {
584 			ttwakeup(tp);
585 			ttyecho(c, tp);
586 			goto endcase;
587 		}
588 		if (TTBREAKC(c, lflag)) {
589 			tp->t_rocount = 0;
590 			catq(&tp->t_rawq, &tp->t_canq);
591 			ttwakeup(tp);
592 		} else if (tp->t_rocount++ == 0)
593 			tp->t_rocol = tp->t_column;
594 		if (ISSET(tp->t_state, TS_ERASE)) {
595 			/*
596 			 * end of prterase \.../
597 			 */
598 			CLR(tp->t_state, TS_ERASE);
599 			(void)ttyoutput('/', tp);
600 		}
601 		i = tp->t_column;
602 		ttyecho(c, tp);
603 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ECHO)) {
604 			/*
605 			 * Place the cursor over the '^' of the ^D.
606 			 */
607 			i = min(2, tp->t_column - i);
608 			while (i > 0) {
609 				(void)ttyoutput('\b', tp);
610 				i--;
611 			}
612 		}
613 	}
614  endcase:
615 	/*
616 	 * IXANY means allow any character to restart output.
617 	 */
618 	if (ISSET(tp->t_state, TS_TTSTOP) &&
619 	    !ISSET(iflag, IXANY) && cc[VSTART] != cc[VSTOP])
620 		return (0);
621  restartoutput:
622 	CLR(tp->t_lflag, FLUSHO);
623 	CLR(tp->t_state, TS_TTSTOP);
624  startoutput:
625 	return (ttstart(tp));
626 }
627 
628 /*
629  * Output a single character on a tty, doing output processing
630  * as needed (expanding tabs, newline processing, etc.).
631  * Returns < 0 if succeeds, otherwise returns char to resend.
632  * Must be recursive.
633  */
634 int
635 ttyoutput(int c, struct tty *tp)
636 {
637 	long	oflag;
638 	int	col, notout, s;
639 
640 	oflag = tp->t_oflag;
641 	if (!ISSET(oflag, OPOST)) {
642 		tk_nout++;
643 		tp->t_outcc++;
644 		if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
645 			return (c);
646 		return (-1);
647 	}
648 	/*
649 	 * Do tab expansion if OXTABS is set.  Special case if we do external
650 	 * processing, we don't do the tab expansion because we'll probably
651 	 * get it wrong.  If tab expansion needs to be done, let it happen
652 	 * externally.
653 	 */
654 	CLR(c, ~TTY_CHARMASK);
655 	if (c == '\t' &&
656 	    ISSET(oflag, OXTABS) && !ISSET(tp->t_lflag, EXTPROC)) {
657 		c = 8 - (tp->t_column & 7);
658 		if (ISSET(tp->t_lflag, FLUSHO)) {
659 			notout = 0;
660 		} else {
661 			s = spltty();		/* Don't interrupt tabs. */
662 			notout = b_to_q("        ", c, &tp->t_outq);
663 			c -= notout;
664 			tk_nout += c;
665 			tp->t_outcc += c;
666 			splx(s);
667 		}
668 		tp->t_column += c;
669 		return (notout ? '\t' : -1);
670 	}
671 	if (c == CEOT && ISSET(oflag, ONOEOT))
672 		return (-1);
673 
674 	/*
675 	 * Newline translation: if ONLCR is set,
676 	 * translate newline into "\r\n".
677 	 */
678 	if (c == '\n' && ISSET(tp->t_oflag, ONLCR)) {
679 		tk_nout++;
680 		tp->t_outcc++;
681 		if (!ISSET(tp->t_lflag, FLUSHO) && putc('\r', &tp->t_outq))
682 			return (c);
683 	}
684 	/* If OCRNL is set, translate "\r" into "\n". */
685 	else if (c == '\r' && ISSET(tp->t_oflag, OCRNL))
686 		c = '\n';
687 	/* If ONOCR is set, don't transmit CRs when on column 0. */
688 	else if (c == '\r' && ISSET(tp->t_oflag, ONOCR) && tp->t_column == 0)
689 		return (-1);
690 
691 	tk_nout++;
692 	tp->t_outcc++;
693 	if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
694 		return (c);
695 
696 	col = tp->t_column;
697 	switch (CCLASS(c)) {
698 	case BACKSPACE:
699 		if (col > 0)
700 			--col;
701 		break;
702 	case CONTROL:
703 		break;
704 	case NEWLINE:
705 		if (ISSET(tp->t_oflag, ONLCR | ONLRET))
706 			col = 0;
707 		break;
708 	case RETURN:
709 		col = 0;
710 		break;
711 	case ORDINARY:
712 		++col;
713 		break;
714 	case TAB:
715 		col = (col + 8) & ~7;
716 		break;
717 	}
718 	tp->t_column = col;
719 	return (-1);
720 }
721 
722 /*
723  * Ioctls for all tty devices.  Called after line-discipline specific ioctl
724  * has been called to do discipline-specific functions and/or reject any
725  * of these ioctl commands.
726  */
727 /* ARGSUSED */
728 int
729 ttioctl(struct tty *tp, u_long cmd, caddr_t data, int flag, struct proc *p)
730 {
731 	extern struct tty *constty;	/* Temporary virtual console. */
732 	extern int	nlinesw;
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 ((u_int)t >= nlinesw)
930 			return (ENXIO);
931 		lp = linesw[t];
932 		goto setldisc;
933 	}
934 	case TIOCSLINED: {		/* set line discipline */
935 		char *name = (char *)data;
936 		dev_t device;
937 
938 		/* Null terminate to prevent buffer overflow */
939 		name[TTLINEDNAMELEN - 1] = '\0';
940 		lp = ttyldisc_lookup(name);
941 
942  setldisc:
943 		if (lp == NULL)
944 			return (ENXIO);
945 
946 		if (lp != tp->t_linesw) {
947 			device = tp->t_dev;
948 			s = spltty();
949 			(*tp->t_linesw->l_close)(tp, flag);
950 			error = (*lp->l_open)(device, tp);
951 			if (error) {
952 				(void)(*tp->t_linesw->l_open)(device, tp);
953 				splx(s);
954 				return (error);
955 			}
956 			tp->t_linesw = lp;
957 			splx(s);
958 		}
959 		break;
960 	}
961 	case TIOCSTART:			/* start output, like ^Q */
962 		s = spltty();
963 		if (ISSET(tp->t_state, TS_TTSTOP) ||
964 		    ISSET(tp->t_lflag, FLUSHO)) {
965 			CLR(tp->t_lflag, FLUSHO);
966 			CLR(tp->t_state, TS_TTSTOP);
967 			ttstart(tp);
968 		}
969 		splx(s);
970 		break;
971 	case TIOCSTI:			/* simulate terminal input */
972 		if (p->p_ucred->cr_uid && (flag & FREAD) == 0)
973 			return (EPERM);
974 		if (p->p_ucred->cr_uid && !isctty(p, tp))
975 			return (EACCES);
976 		(*tp->t_linesw->l_rint)(*(u_char *)data, tp);
977 		break;
978 	case TIOCSTOP:			/* stop output, like ^S */
979 		s = spltty();
980 		if (!ISSET(tp->t_state, TS_TTSTOP)) {
981 			SET(tp->t_state, TS_TTSTOP);
982 			(*cdevsw[major(tp->t_dev)].d_stop)(tp, 0);
983 		}
984 		splx(s);
985 		break;
986 	case TIOCSCTTY:			/* become controlling tty */
987 		/* Session ctty vnode pointer set in vnode layer. */
988 		if (!SESS_LEADER(p) ||
989 		    ((p->p_session->s_ttyvp || tp->t_session) &&
990 		     (tp->t_session != p->p_session)))
991 			return (EPERM);
992 		tp->t_session = p->p_session;
993 		tp->t_pgrp = p->p_pgrp;
994 		p->p_session->s_ttyp = tp;
995 		p->p_flag |= P_CONTROLT;
996 		break;
997 	case TIOCSPGRP: {		/* set pgrp of tty */
998 		struct pgrp *pgrp = pgfind(*(int *)data);
999 
1000 		if (!isctty(p, tp))
1001 			return (ENOTTY);
1002 		else if (pgrp == NULL)
1003 			return (EINVAL);
1004 		else if (pgrp->pg_session != p->p_session)
1005 			return (EPERM);
1006 		tp->t_pgrp = pgrp;
1007 		break;
1008 	}
1009 	case TIOCSTAT:			/* get load avg stats */
1010 		ttyinfo(tp);
1011 		break;
1012 	case TIOCSWINSZ:		/* set window size */
1013 		if (memcmp((caddr_t)&tp->t_winsize, data,
1014 		    sizeof(struct winsize))) {
1015 			tp->t_winsize = *(struct winsize *)data;
1016 			pgsignal(tp->t_pgrp, SIGWINCH, 1);
1017 		}
1018 		break;
1019 	default:
1020 #ifdef COMPAT_OLDTTY
1021 		return (ttcompat(tp, cmd, data, flag, p));
1022 #else
1023 		return (-1);
1024 #endif
1025 	}
1026 	return (0);
1027 }
1028 
1029 int
1030 ttpoll(struct tty *tp, int events, struct proc *p)
1031 {
1032 	int	revents, s;
1033 
1034 	revents = 0;
1035 	s = spltty();
1036 	if (events & (POLLIN | POLLRDNORM))
1037 		if (ttnread(tp) > 0)
1038 			revents |= events & (POLLIN | POLLRDNORM);
1039 
1040 	if (events & (POLLOUT | POLLWRNORM))
1041 		if (tp->t_outq.c_cc <= tp->t_lowat)
1042 			revents |= events & (POLLOUT | POLLWRNORM);
1043 
1044 	if (events & POLLHUP)
1045 		if (!CONNECTED(tp))
1046 			revents |= POLLHUP;
1047 
1048 	if (revents == 0) {
1049 		if (events & (POLLIN | POLLHUP | POLLRDNORM))
1050 			selrecord(p, &tp->t_rsel);
1051 
1052 		if (events & (POLLOUT | POLLWRNORM))
1053 			selrecord(p, &tp->t_wsel);
1054 	}
1055 
1056 	splx(s);
1057 	return (revents);
1058 }
1059 
1060 static int
1061 ttnread(struct tty *tp)
1062 {
1063 	int	nread;
1064 
1065 	if (ISSET(tp->t_lflag, PENDIN))
1066 		ttypend(tp);
1067 	nread = tp->t_canq.c_cc;
1068 	if (!ISSET(tp->t_lflag, ICANON)) {
1069 		nread += tp->t_rawq.c_cc;
1070 		if (nread < tp->t_cc[VMIN] && !tp->t_cc[VTIME])
1071 			nread = 0;
1072 	}
1073 	return (nread);
1074 }
1075 
1076 /*
1077  * Wait for output to drain.
1078  */
1079 int
1080 ttywait(tp)
1081 	struct tty *tp;
1082 {
1083 	int	error, s;
1084 
1085 	error = 0;
1086 	s = spltty();
1087 	while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1088 	    CONNECTED(tp) && tp->t_oproc) {
1089 		(*tp->t_oproc)(tp);
1090 		SET(tp->t_state, TS_ASLEEP);
1091 		error = ttysleep(tp, &tp->t_outq, TTOPRI | PCATCH, ttyout, 0);
1092 		if (error)
1093 			break;
1094 	}
1095 	splx(s);
1096 	return (error);
1097 }
1098 
1099 /*
1100  * Flush if successfully wait.
1101  */
1102 int
1103 ttywflush(struct tty *tp)
1104 {
1105 	int	error;
1106 
1107 	if ((error = ttywait(tp)) == 0)
1108 		ttyflush(tp, FREAD);
1109 	return (error);
1110 }
1111 
1112 /*
1113  * Flush tty read and/or write queues, notifying anyone waiting.
1114  */
1115 void
1116 ttyflush(struct tty *tp, int rw)
1117 {
1118 	int	s;
1119 
1120 	s = spltty();
1121 	if (rw & FREAD) {
1122 		FLUSHQ(&tp->t_canq);
1123 		FLUSHQ(&tp->t_rawq);
1124 		tp->t_rocount = 0;
1125 		tp->t_rocol = 0;
1126 		CLR(tp->t_state, TS_LOCAL);
1127 		ttwakeup(tp);
1128 	}
1129 	if (rw & FWRITE) {
1130 		CLR(tp->t_state, TS_TTSTOP);
1131 		(*cdevsw[major(tp->t_dev)].d_stop)(tp, rw);
1132 		FLUSHQ(&tp->t_outq);
1133 		wakeup((caddr_t)&tp->t_outq);
1134 		selwakeup(&tp->t_wsel);
1135 	}
1136 	splx(s);
1137 }
1138 
1139 /*
1140  * Copy in the default termios characters.
1141  */
1142 void
1143 ttychars(struct tty *tp)
1144 {
1145 
1146 	memcpy(tp->t_cc, ttydefchars, sizeof(ttydefchars));
1147 }
1148 
1149 /*
1150  * Send stop character on input overflow.
1151  */
1152 static void
1153 ttyblock(struct tty *tp)
1154 {
1155 	int	total;
1156 
1157 	total = tp->t_rawq.c_cc + tp->t_canq.c_cc;
1158 	if (tp->t_rawq.c_cc > TTYHOG) {
1159 		ttyflush(tp, FREAD | FWRITE);
1160 		CLR(tp->t_state, TS_TBLOCK);
1161 	}
1162 	/*
1163 	 * Block further input iff: current input > threshold
1164 	 * AND input is available to user program.
1165 	 */
1166 	if (total >= TTYHOG / 2 &&
1167 	    !ISSET(tp->t_state, TS_TBLOCK) &&
1168 	    (!ISSET(tp->t_lflag, ICANON) || tp->t_canq.c_cc > 0)) {
1169 		if (ISSET(tp->t_iflag, IXOFF) &&
1170 		    tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
1171 		    putc(tp->t_cc[VSTOP], &tp->t_outq) == 0) {
1172 			SET(tp->t_state, TS_TBLOCK);
1173 			ttstart(tp);
1174 		}
1175 		/* Try to block remote output via hardware flow control. */
1176 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
1177 		    (*tp->t_hwiflow)(tp, 1) != 0)
1178 			SET(tp->t_state, TS_TBLOCK);
1179 	}
1180 }
1181 
1182 void
1183 ttrstrt(void *tp_arg)
1184 {
1185 	struct tty	*tp;
1186 	int		s;
1187 
1188 #ifdef DIAGNOSTIC
1189 	if (tp_arg == NULL)
1190 		panic("ttrstrt");
1191 #endif
1192 	tp = tp_arg;
1193 	s = spltty();
1194 
1195 	CLR(tp->t_state, TS_TIMEOUT);
1196 	ttstart(tp);
1197 
1198 	splx(s);
1199 }
1200 
1201 int
1202 ttstart(struct tty *tp)
1203 {
1204 
1205 	if (tp->t_oproc != NULL)	/* XXX: Kludge for pty. */
1206 		(*tp->t_oproc)(tp);
1207 	return (0);
1208 }
1209 
1210 /*
1211  * "close" a line discipline
1212  */
1213 int
1214 ttylclose(struct tty *tp, int flag)
1215 {
1216 
1217 	if (flag & FNONBLOCK)
1218 		ttyflush(tp, FREAD | FWRITE);
1219 	else
1220 		ttywflush(tp);
1221 	return (0);
1222 }
1223 
1224 /*
1225  * Handle modem control transition on a tty.
1226  * Flag indicates new state of carrier.
1227  * Returns 0 if the line should be turned off, otherwise 1.
1228  */
1229 int
1230 ttymodem(struct tty *tp, int flag)
1231 {
1232 
1233 	if (flag == 0) {
1234 		if (ISSET(tp->t_state, TS_CARR_ON)) {
1235 			/*
1236 			 * Lost carrier.
1237 			 */
1238 			CLR(tp->t_state, TS_CARR_ON);
1239 			if (ISSET(tp->t_state, TS_ISOPEN) && !CONNECTED(tp)) {
1240 				if (tp->t_session && tp->t_session->s_leader)
1241 					psignal(tp->t_session->s_leader, SIGHUP);
1242 				ttyflush(tp, FREAD | FWRITE);
1243 				return (0);
1244 			}
1245 		}
1246 	} else {
1247 		if (!ISSET(tp->t_state, TS_CARR_ON)) {
1248 			/*
1249 			 * Carrier now on.
1250 			 */
1251 			SET(tp->t_state, TS_CARR_ON);
1252 			ttwakeup(tp);
1253 		}
1254 	}
1255 	return (1);
1256 }
1257 
1258 /*
1259  * Default modem control routine (for other line disciplines).
1260  * Return argument flag, to turn off device on carrier drop.
1261  */
1262 int
1263 nullmodem(struct tty *tp, int flag)
1264 {
1265 
1266 	if (flag)
1267 		SET(tp->t_state, TS_CARR_ON);
1268 	else {
1269 		CLR(tp->t_state, TS_CARR_ON);
1270 		if (!CONNECTED(tp)) {
1271 			if (tp->t_session && tp->t_session->s_leader)
1272 				psignal(tp->t_session->s_leader, SIGHUP);
1273 			return (0);
1274 		}
1275 	}
1276 	return (1);
1277 }
1278 
1279 /*
1280  * Reinput pending characters after state switch
1281  * call at spltty().
1282  */
1283 void
1284 ttypend(struct tty *tp)
1285 {
1286 	struct clist	tq;
1287 	int		c;
1288 
1289 	CLR(tp->t_lflag, PENDIN);
1290 	SET(tp->t_state, TS_TYPEN);
1291 	tq = tp->t_rawq;
1292 	tp->t_rawq.c_cc = 0;
1293 	tp->t_rawq.c_cf = tp->t_rawq.c_cl = 0;
1294 	while ((c = getc(&tq)) >= 0)
1295 		ttyinput(c, tp);
1296 	CLR(tp->t_state, TS_TYPEN);
1297 }
1298 
1299 /*
1300  * Process a read call on a tty device.
1301  */
1302 int
1303 ttread(struct tty *tp, struct uio *uio, int flag)
1304 {
1305 	struct clist	*qp;
1306 	u_char		*cc;
1307 	struct proc	*p;
1308 	int		c, s, first, error, has_stime, last_cc;
1309 	long		lflag, slp;
1310 	struct timeval	stime;
1311 
1312 	cc = tp->t_cc;
1313 	p = curproc;
1314 	error = 0;
1315 	has_stime = 0;
1316 	last_cc = 0;
1317 	slp = 0;
1318 
1319  loop:
1320 	lflag = tp->t_lflag;
1321 	s = spltty();
1322 	/*
1323 	 * take pending input first
1324 	 */
1325 	if (ISSET(lflag, PENDIN))
1326 		ttypend(tp);
1327 	splx(s);
1328 
1329 	/*
1330 	 * Hang process if it's in the background.
1331 	 */
1332 	if (isbackground(p, tp)) {
1333 		if (sigismember(&p->p_sigctx.ps_sigignore, SIGTTIN) ||
1334 		    sigismember(&p->p_sigctx.ps_sigmask, SIGTTIN) ||
1335 		    p->p_flag & P_PPWAIT || p->p_pgrp->pg_jobc == 0)
1336 			return (EIO);
1337 		pgsignal(p->p_pgrp, SIGTTIN, 1);
1338 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, ttybg, 0);
1339 		if (error)
1340 			return (error);
1341 		goto loop;
1342 	}
1343 
1344 	s = spltty();
1345 	if (!ISSET(lflag, ICANON)) {
1346 		int m = cc[VMIN];
1347 		long t = cc[VTIME];
1348 
1349 		qp = &tp->t_rawq;
1350 		/*
1351 		 * Check each of the four combinations.
1352 		 * (m > 0 && t == 0) is the normal read case.
1353 		 * It should be fairly efficient, so we check that and its
1354 		 * companion case (m == 0 && t == 0) first.
1355 		 * For the other two cases, we compute the target sleep time
1356 		 * into slp.
1357 		 */
1358 		if (t == 0) {
1359 			if (qp->c_cc < m)
1360 				goto sleep;
1361 			goto read;
1362 		}
1363 		t *= 100000;		/* time in us */
1364 #define	diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 1000000 + \
1365 			 ((t1).tv_usec - (t2).tv_usec))
1366 		if (m > 0) {
1367 			if (qp->c_cc <= 0)
1368 				goto sleep;
1369 			if (qp->c_cc >= m)
1370 				goto read;
1371 			if (!has_stime) {
1372 				/* first character, start timer */
1373 				has_stime = 1;
1374 				stime = time;
1375 				slp = t;
1376 			} else if (qp->c_cc > last_cc) {
1377 				/* got a character, restart timer */
1378 				stime = time;
1379 				slp = t;
1380 			} else {
1381 				/* nothing, check expiration */
1382 				slp = t - diff(time, stime);
1383 			}
1384 		} else {	/* m == 0 */
1385 			if (qp->c_cc > 0)
1386 				goto read;
1387 			if (!has_stime) {
1388 				has_stime = 1;
1389 				stime = time;
1390 				slp = t;
1391 			} else
1392 				slp = t - diff(time, stime);
1393 		}
1394 		last_cc = qp->c_cc;
1395 #undef diff
1396 		if (slp > 0) {
1397 			/*
1398 			 * Rounding down may make us wake up just short
1399 			 * of the target, so we round up.
1400 			 * The formula is ceiling(slp * hz/1000000).
1401 			 * 32-bit arithmetic is enough for hz < 169.
1402 			 *
1403 			 * Also, use plain wakeup() not ttwakeup().
1404 			 */
1405 			slp = (long) (((u_long)slp * hz) + 999999) / 1000000;
1406 			goto sleep;
1407 		}
1408 	} else if ((qp = &tp->t_canq)->c_cc <= 0) {
1409 		int	carrier;
1410 
1411  sleep:
1412 		/*
1413 		 * If there is no input, sleep on rawq
1414 		 * awaiting hardware receipt and notification.
1415 		 * If we have data, we don't need to check for carrier.
1416 		 */
1417 		carrier = CONNECTED(tp);
1418 		if (!carrier && ISSET(tp->t_state, TS_ISOPEN)) {
1419 			splx(s);
1420 			return (0);	/* EOF */
1421 		}
1422 		if (flag & IO_NDELAY) {
1423 			splx(s);
1424 			return (EWOULDBLOCK);
1425 		}
1426 		error = ttysleep(tp, &tp->t_rawq, TTIPRI | PCATCH,
1427 		    carrier ? ttyin : ttopen, slp);
1428 		splx(s);
1429 		/* VMIN == 0: any quantity read satisfies */
1430 		if (cc[VMIN] == 0 && error == EWOULDBLOCK)
1431 			return (0);
1432 		if (error && error != EWOULDBLOCK)
1433 			return (error);
1434 		goto loop;
1435 	}
1436  read:
1437 	splx(s);
1438 
1439 	/*
1440 	 * Input present, check for input mapping and processing.
1441 	 */
1442 	first = 1;
1443 	while ((c = getc(qp)) >= 0) {
1444 		/*
1445 		 * delayed suspend (^Y)
1446 		 */
1447 		if (CCEQ(cc[VDSUSP], c) &&
1448 		    ISSET(lflag, IEXTEN|ISIG) == (IEXTEN|ISIG)) {
1449 			pgsignal(tp->t_pgrp, SIGTSTP, 1);
1450 			if (first) {
1451 				error = ttysleep(tp, &lbolt,
1452 						 TTIPRI | PCATCH, ttybg, 0);
1453 				if (error)
1454 					break;
1455 				goto loop;
1456 			}
1457 			break;
1458 		}
1459 		/*
1460 		 * Interpret EOF only in canonical mode.
1461 		 */
1462 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
1463 			break;
1464 		/*
1465 		 * Give user character.
1466 		 */
1467  		error = ureadc(c, uio);
1468 		if (error)
1469 			break;
1470  		if (uio->uio_resid == 0)
1471 			break;
1472 		/*
1473 		 * In canonical mode check for a "break character"
1474 		 * marking the end of a "line of input".
1475 		 */
1476 		if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
1477 			break;
1478 		first = 0;
1479 	}
1480 	/*
1481 	 * Look to unblock output now that (presumably)
1482 	 * the input queue has gone down.
1483 	 */
1484 	s = spltty();
1485 	if (ISSET(tp->t_state, TS_TBLOCK) && tp->t_rawq.c_cc < TTYHOG/5) {
1486 		if (ISSET(tp->t_iflag, IXOFF) &&
1487 		    cc[VSTART] != _POSIX_VDISABLE &&
1488 		    putc(cc[VSTART], &tp->t_outq) == 0) {
1489 			CLR(tp->t_state, TS_TBLOCK);
1490 			ttstart(tp);
1491 		}
1492 		/* Try to unblock remote output via hardware flow control. */
1493 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
1494 		    (*tp->t_hwiflow)(tp, 0) != 0)
1495 			CLR(tp->t_state, TS_TBLOCK);
1496 	}
1497 	splx(s);
1498 	return (error);
1499 }
1500 
1501 /*
1502  * Check the output queue on tp for space for a kernel message (from uprintf
1503  * or tprintf).  Allow some space over the normal hiwater mark so we don't
1504  * lose messages due to normal flow control, but don't let the tty run amok.
1505  * Sleeps here are not interruptible, but we return prematurely if new signals
1506  * arrive.
1507  */
1508 int
1509 ttycheckoutq(struct tty *tp, int wait)
1510 {
1511 	int	hiwat, s, error;
1512 
1513 	hiwat = tp->t_hiwat;
1514 	s = spltty();
1515 	if (tp->t_outq.c_cc > hiwat + 200)
1516 		while (tp->t_outq.c_cc > hiwat) {
1517 			ttstart(tp);
1518 			if (wait == 0) {
1519 				splx(s);
1520 				return (0);
1521 			}
1522 			callout_reset(&tp->t_outq_ch, hz,
1523 			    (void (*)__P((void *)))wakeup, &tp->t_outq);
1524 			SET(tp->t_state, TS_ASLEEP);
1525 			error = tsleep(&tp->t_outq, (PZERO - 1) | PCATCH,
1526 			    "ttckoutq", 0);
1527 			if (error == EINTR)
1528 				wait = 0;
1529 		}
1530 	splx(s);
1531 	return (1);
1532 }
1533 
1534 /*
1535  * Process a write call on a tty device.
1536  */
1537 int
1538 ttwrite(struct tty *tp, struct uio *uio, int flag)
1539 {
1540 	u_char		*cp;
1541 	struct proc	*p;
1542 	int		cc, ce, i, hiwat, cnt, error, s;
1543 	u_char		obuf[OBUFSIZ];
1544 
1545 	cp = NULL;
1546 	hiwat = tp->t_hiwat;
1547 	cnt = uio->uio_resid;
1548 	error = 0;
1549 	cc = 0;
1550  loop:
1551 	s = spltty();
1552 	if (!CONNECTED(tp)) {
1553 		if (ISSET(tp->t_state, TS_ISOPEN)) {
1554 			splx(s);
1555 			return (EIO);
1556 		} else if (flag & IO_NDELAY) {
1557 			splx(s);
1558 			error = EWOULDBLOCK;
1559 			goto out;
1560 		} else {
1561 			/* Sleep awaiting carrier. */
1562 			error = ttysleep(tp,
1563 			    &tp->t_rawq, TTIPRI | PCATCH, ttopen, 0);
1564 			splx(s);
1565 			if (error)
1566 				goto out;
1567 			goto loop;
1568 		}
1569 	}
1570 	splx(s);
1571 	/*
1572 	 * Hang the process if it's in the background.
1573 	 */
1574 	p = curproc;
1575 	if (isbackground(p, tp) &&
1576 	    ISSET(tp->t_lflag, TOSTOP) && (p->p_flag & P_PPWAIT) == 0 &&
1577 	    !sigismember(&p->p_sigctx.ps_sigignore, SIGTTOU) &&
1578 	    !sigismember(&p->p_sigctx.ps_sigmask, SIGTTOU)) {
1579 		if (p->p_pgrp->pg_jobc == 0) {
1580 			error = EIO;
1581 			goto out;
1582 		}
1583 		pgsignal(p->p_pgrp, SIGTTOU, 1);
1584 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, ttybg, 0);
1585 		if (error)
1586 			goto out;
1587 		goto loop;
1588 	}
1589 	/*
1590 	 * Process the user's data in at most OBUFSIZ chunks.  Perform any
1591 	 * output translation.  Keep track of high water mark, sleep on
1592 	 * overflow awaiting device aid in acquiring new space.
1593 	 */
1594 	while (uio->uio_resid > 0 || cc > 0) {
1595 		if (ISSET(tp->t_lflag, FLUSHO)) {
1596 			uio->uio_resid = 0;
1597 			return (0);
1598 		}
1599 		if (tp->t_outq.c_cc > hiwat)
1600 			goto ovhiwat;
1601 		/*
1602 		 * Grab a hunk of data from the user, unless we have some
1603 		 * leftover from last time.
1604 		 */
1605 		if (cc == 0) {
1606 			cc = min(uio->uio_resid, OBUFSIZ);
1607 			cp = obuf;
1608 			error = uiomove(cp, cc, uio);
1609 			if (error) {
1610 				cc = 0;
1611 				break;
1612 			}
1613 		}
1614 		/*
1615 		 * If nothing fancy need be done, grab those characters we
1616 		 * can handle without any of ttyoutput's processing and
1617 		 * just transfer them to the output q.  For those chars
1618 		 * which require special processing (as indicated by the
1619 		 * bits in char_type), call ttyoutput.  After processing
1620 		 * a hunk of data, look for FLUSHO so ^O's will take effect
1621 		 * immediately.
1622 		 */
1623 		while (cc > 0) {
1624 			if (!ISSET(tp->t_oflag, OPOST))
1625 				ce = cc;
1626 			else {
1627 				ce = cc - scanc((u_int)cc, cp, char_type,
1628 				    CCLASSMASK);
1629 				/*
1630 				 * If ce is zero, then we're processing
1631 				 * a special character through ttyoutput.
1632 				 */
1633 				if (ce == 0) {
1634 					tp->t_rocount = 0;
1635 					if (ttyoutput(*cp, tp) >= 0) {
1636 						/* out of space */
1637 						goto overfull;
1638 					}
1639 					cp++;
1640 					cc--;
1641 					if (ISSET(tp->t_lflag, FLUSHO) ||
1642 					    tp->t_outq.c_cc > hiwat)
1643 						goto ovhiwat;
1644 					continue;
1645 				}
1646 			}
1647 			/*
1648 			 * A bunch of normal characters have been found.
1649 			 * Transfer them en masse to the output queue and
1650 			 * continue processing at the top of the loop.
1651 			 * If there are any further characters in this
1652 			 * <= OBUFSIZ chunk, the first should be a character
1653 			 * requiring special handling by ttyoutput.
1654 			 */
1655 			tp->t_rocount = 0;
1656 			i = b_to_q(cp, ce, &tp->t_outq);
1657 			ce -= i;
1658 			tp->t_column += ce;
1659 			cp += ce, cc -= ce, tk_nout += ce;
1660 			tp->t_outcc += ce;
1661 			if (i > 0) {
1662 				/* out of space */
1663 				goto overfull;
1664 			}
1665 			if (ISSET(tp->t_lflag, FLUSHO) ||
1666 			    tp->t_outq.c_cc > hiwat)
1667 				break;
1668 		}
1669 		ttstart(tp);
1670 	}
1671  out:
1672 	/*
1673 	 * If cc is nonzero, we leave the uio structure inconsistent, as the
1674 	 * offset and iov pointers have moved forward, but it doesn't matter
1675 	 * (the call will either return short or restart with a new uio).
1676 	 */
1677 	uio->uio_resid += cc;
1678 	return (error);
1679 
1680  overfull:
1681 	/*
1682 	 * Since we are using ring buffers, if we can't insert any more into
1683 	 * the output queue, we can assume the ring is full and that someone
1684 	 * forgot to set the high water mark correctly.  We set it and then
1685 	 * proceed as normal.
1686 	 */
1687 	hiwat = tp->t_outq.c_cc - 1;
1688 
1689  ovhiwat:
1690 	ttstart(tp);
1691 	s = spltty();
1692 	/*
1693 	 * This can only occur if FLUSHO is set in t_lflag,
1694 	 * or if ttstart/oproc is synchronous (or very fast).
1695 	 */
1696 	if (tp->t_outq.c_cc <= hiwat) {
1697 		splx(s);
1698 		goto loop;
1699 	}
1700 	if (flag & IO_NDELAY) {
1701 		splx(s);
1702 		uio->uio_resid += cc;
1703 		return (uio->uio_resid == cnt ? EWOULDBLOCK : 0);
1704 	}
1705 	SET(tp->t_state, TS_ASLEEP);
1706 	error = ttysleep(tp, &tp->t_outq, TTOPRI | PCATCH, ttyout, 0);
1707 	splx(s);
1708 	if (error)
1709 		goto out;
1710 	goto loop;
1711 }
1712 
1713 /*
1714  * Rubout one character from the rawq of tp
1715  * as cleanly as possible.
1716  */
1717 void
1718 ttyrub(int c, struct tty *tp)
1719 {
1720 	u_char	*cp;
1721 	int	savecol, tabc, s;
1722 
1723 	if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
1724 		return;
1725 	CLR(tp->t_lflag, FLUSHO);
1726 	if (ISSET(tp->t_lflag, ECHOE)) {
1727 		if (tp->t_rocount == 0) {
1728 			/*
1729 			 * Screwed by ttwrite; retype
1730 			 */
1731 			ttyretype(tp);
1732 			return;
1733 		}
1734 		if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
1735 			ttyrubo(tp, 2);
1736 		else {
1737 			CLR(c, ~TTY_CHARMASK);
1738 			switch (CCLASS(c)) {
1739 			case ORDINARY:
1740 				ttyrubo(tp, 1);
1741 				break;
1742 			case BACKSPACE:
1743 			case CONTROL:
1744 			case NEWLINE:
1745 			case RETURN:
1746 			case VTAB:
1747 				if (ISSET(tp->t_lflag, ECHOCTL))
1748 					ttyrubo(tp, 2);
1749 				break;
1750 			case TAB:
1751 				if (tp->t_rocount < tp->t_rawq.c_cc) {
1752 					ttyretype(tp);
1753 					return;
1754 				}
1755 				s = spltty();
1756 				savecol = tp->t_column;
1757 				SET(tp->t_state, TS_CNTTB);
1758 				SET(tp->t_lflag, FLUSHO);
1759 				tp->t_column = tp->t_rocol;
1760 				for (cp = firstc(&tp->t_rawq, &tabc); cp;
1761 				    cp = nextc(&tp->t_rawq, cp, &tabc))
1762 					ttyecho(tabc, tp);
1763 				CLR(tp->t_lflag, FLUSHO);
1764 				CLR(tp->t_state, TS_CNTTB);
1765 				splx(s);
1766 
1767 				/* savecol will now be length of the tab. */
1768 				savecol -= tp->t_column;
1769 				tp->t_column += savecol;
1770 				if (savecol > 8)
1771 					savecol = 8;	/* overflow screw */
1772 				while (--savecol >= 0)
1773 					(void)ttyoutput('\b', tp);
1774 				break;
1775 			default:			/* XXX */
1776 #define	PANICSTR	"ttyrub: would panic c = %d, val = %d\n"
1777 				(void)printf(PANICSTR, c, CCLASS(c));
1778 #ifdef notdef
1779 				panic(PANICSTR, c, CCLASS(c));
1780 #endif
1781 			}
1782 		}
1783 	} else if (ISSET(tp->t_lflag, ECHOPRT)) {
1784 		if (!ISSET(tp->t_state, TS_ERASE)) {
1785 			SET(tp->t_state, TS_ERASE);
1786 			(void)ttyoutput('\\', tp);
1787 		}
1788 		ttyecho(c, tp);
1789 	} else
1790 		ttyecho(tp->t_cc[VERASE], tp);
1791 	--tp->t_rocount;
1792 }
1793 
1794 /*
1795  * Back over cnt characters, erasing them.
1796  */
1797 static void
1798 ttyrubo(struct tty *tp, int cnt)
1799 {
1800 
1801 	while (cnt-- > 0) {
1802 		(void)ttyoutput('\b', tp);
1803 		(void)ttyoutput(' ', tp);
1804 		(void)ttyoutput('\b', tp);
1805 	}
1806 }
1807 
1808 /*
1809  * ttyretype --
1810  *	Reprint the rawq line.  Note, it is assumed that c_cc has already
1811  *	been checked.
1812  */
1813 void
1814 ttyretype(struct tty *tp)
1815 {
1816 	u_char	*cp;
1817 	int	s, c;
1818 
1819 	/* Echo the reprint character. */
1820 	if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
1821 		ttyecho(tp->t_cc[VREPRINT], tp);
1822 
1823 	(void)ttyoutput('\n', tp);
1824 
1825 	s = spltty();
1826 	for (cp = firstc(&tp->t_canq, &c); cp; cp = nextc(&tp->t_canq, cp, &c))
1827 		ttyecho(c, tp);
1828 	for (cp = firstc(&tp->t_rawq, &c); cp; cp = nextc(&tp->t_rawq, cp, &c))
1829 		ttyecho(c, tp);
1830 	CLR(tp->t_state, TS_ERASE);
1831 	splx(s);
1832 
1833 	tp->t_rocount = tp->t_rawq.c_cc;
1834 	tp->t_rocol = 0;
1835 }
1836 
1837 /*
1838  * Echo a typed character to the terminal.
1839  */
1840 static void
1841 ttyecho(int c, struct tty *tp)
1842 {
1843 
1844 	if (!ISSET(tp->t_state, TS_CNTTB))
1845 		CLR(tp->t_lflag, FLUSHO);
1846 	if ((!ISSET(tp->t_lflag, ECHO) &&
1847 	    (!ISSET(tp->t_lflag, ECHONL) || c != '\n')) ||
1848 	    ISSET(tp->t_lflag, EXTPROC))
1849 		return;
1850 	if (((ISSET(tp->t_lflag, ECHOCTL) &&
1851 	     (ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n')) ||
1852 	    ISSET(c, TTY_CHARMASK) == 0177)) {
1853 		(void)ttyoutput('^', tp);
1854 		CLR(c, ~TTY_CHARMASK);
1855 		if (c == 0177)
1856 			c = '?';
1857 		else
1858 			c += 'A' - 1;
1859 	}
1860 	(void)ttyoutput(c, tp);
1861 }
1862 
1863 /*
1864  * Wake up any readers on a tty.
1865  */
1866 void
1867 ttwakeup(struct tty *tp)
1868 {
1869 
1870 	selwakeup(&tp->t_rsel);
1871 	if (ISSET(tp->t_state, TS_ASYNC))
1872 		pgsignal(tp->t_pgrp, SIGIO, 1);
1873 	wakeup((caddr_t)&tp->t_rawq);
1874 }
1875 
1876 /*
1877  * Look up a code for a specified speed in a conversion table;
1878  * used by drivers to map software speed values to hardware parameters.
1879  */
1880 int
1881 ttspeedtab(int speed, struct speedtab *table)
1882 {
1883 
1884 	for ( ; table->sp_speed != -1; table++)
1885 		if (table->sp_speed == speed)
1886 			return (table->sp_code);
1887 	return (-1);
1888 }
1889 
1890 /*
1891  * Set tty hi and low water marks.
1892  *
1893  * Try to arrange the dynamics so there's about one second
1894  * from hi to low water.
1895  */
1896 void
1897 ttsetwater(struct tty *tp)
1898 {
1899 	int	cps, x;
1900 
1901 #define	CLAMP(x, h, l)	((x) > h ? h : ((x) < l) ? l : (x))
1902 
1903 	cps = tp->t_ospeed / 10;
1904 	tp->t_lowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
1905 	x += cps;
1906 	x = CLAMP(x, TTMAXHIWAT, TTMINHIWAT);
1907 	tp->t_hiwat = roundup(x, CBSIZE);
1908 #undef	CLAMP
1909 }
1910 
1911 /*
1912  * Report on state of foreground process group.
1913  */
1914 void
1915 ttyinfo(struct tty *tp)
1916 {
1917 	struct proc	*p, *pick;
1918 	struct timeval	utime, stime;
1919 	int		tmp;
1920 
1921 	if (ttycheckoutq(tp,0) == 0)
1922 		return;
1923 
1924 	/* Print load average. */
1925 	tmp = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
1926 	ttyprintf(tp, "load: %d.%02d ", tmp / 100, tmp % 100);
1927 
1928 	if (tp->t_session == NULL)
1929 		ttyprintf(tp, "not a controlling terminal\n");
1930 	else if (tp->t_pgrp == NULL)
1931 		ttyprintf(tp, "no foreground process group\n");
1932 	else if ((p = tp->t_pgrp->pg_members.lh_first) == 0)
1933 		ttyprintf(tp, "empty foreground process group\n");
1934 	else {
1935 		/* Pick interesting process. */
1936 		for (pick = NULL; p != NULL; p = p->p_pglist.le_next)
1937 			if (proc_compare(pick, p))
1938 				pick = p;
1939 
1940 		ttyprintf(tp, " cmd: %s %d [%s] ", pick->p_comm, pick->p_pid,
1941 		    pick->p_stat == SONPROC ? "running" :
1942 		    pick->p_stat == SRUN ? "runnable" :
1943 		    pick->p_wmesg ? pick->p_wmesg : "iowait");
1944 
1945 		calcru(pick, &utime, &stime, NULL);
1946 
1947 		/* Round up and print user time. */
1948 		utime.tv_usec += 5000;
1949 		if (utime.tv_usec >= 1000000) {
1950 			utime.tv_sec += 1;
1951 			utime.tv_usec -= 1000000;
1952 		}
1953 		ttyprintf(tp, "%ld.%02ldu ", (long int)utime.tv_sec,
1954 		    (long int)utime.tv_usec / 10000);
1955 
1956 		/* Round up and print system time. */
1957 		stime.tv_usec += 5000;
1958 		if (stime.tv_usec >= 1000000) {
1959 			stime.tv_sec += 1;
1960 			stime.tv_usec -= 1000000;
1961 		}
1962 		ttyprintf(tp, "%ld.%02lds ", (long int)stime.tv_sec,
1963 		    (long int)stime.tv_usec / 10000);
1964 
1965 #define	pgtok(a)	(((u_long) ((a) * PAGE_SIZE) / 1024))
1966 		/* Print percentage cpu. */
1967 		tmp = (pick->p_pctcpu * 10000 + FSCALE / 2) >> FSHIFT;
1968 		ttyprintf(tp, "%d%% ", tmp / 100);
1969 
1970 		/* Print resident set size. */
1971 		if (pick->p_stat == SIDL || P_ZOMBIE(pick))
1972 			tmp = 0;
1973 		else {
1974 			struct vmspace *vm = pick->p_vmspace;
1975 			tmp = pgtok(vm_resident_count(vm));
1976 		}
1977 		ttyprintf(tp, "%dk\n", tmp);
1978 	}
1979 	tp->t_rocount = 0;	/* so pending input will be retyped if BS */
1980 }
1981 
1982 /*
1983  * Returns 1 if p2 is "better" than p1
1984  *
1985  * The algorithm for picking the "interesting" process is thus:
1986  *
1987  *	1) Only foreground processes are eligible - implied.
1988  *	2) Runnable processes are favored over anything else.  The runner
1989  *	   with the highest cpu utilization is picked (p_estcpu).  Ties are
1990  *	   broken by picking the highest pid.
1991  *	3) The sleeper with the shortest sleep time is next.  With ties,
1992  *	   we pick out just "short-term" sleepers (P_SINTR == 0).
1993  *	4) Further ties are broken by picking the highest pid.
1994  */
1995 #define	ISRUN(p)	(((p)->p_stat == SRUN) || ((p)->p_stat == SIDL) || \
1996 			 ((p)->p_stat == SONPROC))
1997 #define	TESTAB(a, b)    ((a)<<1 | (b))
1998 #define	ONLYA   2
1999 #define	ONLYB   1
2000 #define	BOTH    3
2001 
2002 static int
2003 proc_compare(struct proc *p1, struct proc *p2)
2004 {
2005 
2006 	if (p1 == NULL)
2007 		return (1);
2008 	/*
2009 	 * see if at least one of them is runnable
2010 	 */
2011 	switch (TESTAB(ISRUN(p1), ISRUN(p2))) {
2012 	case ONLYA:
2013 		return (0);
2014 	case ONLYB:
2015 		return (1);
2016 	case BOTH:
2017 		/*
2018 		 * tie - favor one with highest recent cpu utilization
2019 		 */
2020 		if (p2->p_estcpu > p1->p_estcpu)
2021 			return (1);
2022 		if (p1->p_estcpu > p2->p_estcpu)
2023 			return (0);
2024 		return (p2->p_pid > p1->p_pid);	/* tie - return highest pid */
2025 	}
2026 	/*
2027  	 * weed out zombies
2028 	 */
2029 	switch (TESTAB(P_ZOMBIE(p1), P_ZOMBIE(p2))) {
2030 	case ONLYA:
2031 		return (1);
2032 	case ONLYB:
2033 		return (0);
2034 	case BOTH:
2035 		return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
2036 	}
2037 	/*
2038 	 * pick the one with the smallest sleep time
2039 	 */
2040 	if (p2->p_slptime > p1->p_slptime)
2041 		return (0);
2042 	if (p1->p_slptime > p2->p_slptime)
2043 		return (1);
2044 	/*
2045 	 * favor one sleeping in a non-interruptible sleep
2046 	 */
2047 	if (p1->p_flag & P_SINTR && (p2->p_flag & P_SINTR) == 0)
2048 		return (1);
2049 	if (p2->p_flag & P_SINTR && (p1->p_flag & P_SINTR) == 0)
2050 		return (0);
2051 	return (p2->p_pid > p1->p_pid);		/* tie - return highest pid */
2052 }
2053 
2054 /*
2055  * Output char to tty; console putchar style.
2056  */
2057 int
2058 tputchar(int c, struct tty *tp)
2059 {
2060 	int	s;
2061 
2062 	s = spltty();
2063 	if (ISSET(tp->t_state,
2064 	    TS_CARR_ON | TS_ISOPEN) != (TS_CARR_ON | TS_ISOPEN)) {
2065 		splx(s);
2066 		return (-1);
2067 	}
2068 	if (c == '\n')
2069 		(void)ttyoutput('\r', tp);
2070 	(void)ttyoutput(c, tp);
2071 	ttstart(tp);
2072 	splx(s);
2073 	return (0);
2074 }
2075 
2076 /*
2077  * Sleep on chan, returning ERESTART if tty changed while we napped and
2078  * returning any errors (e.g. EINTR/ETIMEDOUT) reported by tsleep.  If
2079  * the tty is revoked, restarting a pending call will redo validation done
2080  * at the start of the call.
2081  */
2082 int
2083 ttysleep(struct tty *tp, void *chan, int pri, const char *wmesg, int timo)
2084 {
2085 	int	error;
2086 	short	gen;
2087 
2088 	gen = tp->t_gen;
2089 	if ((error = tsleep(chan, pri, wmesg, timo)) != 0)
2090 		return (error);
2091 	return (tp->t_gen == gen ? 0 : ERESTART);
2092 }
2093 
2094 /*
2095  * Initialise the global tty list.
2096  */
2097 void
2098 tty_init(void)
2099 {
2100 	ttyldisc_init();
2101 
2102 	TAILQ_INIT(&ttylist);
2103 	tty_count = 0;
2104 
2105 	pool_init(&tty_pool, sizeof(struct tty), 0, 0, 0, "ttypl",
2106 	    0, pool_page_alloc_nointr, pool_page_free_nointr, M_TTYS);
2107 }
2108 
2109 /*
2110  * Attach a tty to the tty list.
2111  *
2112  * This should be called ONLY once per real tty (including pty's).
2113  * eg, on the sparc, the keyboard and mouse have struct tty's that are
2114  * distinctly NOT usable as tty's, and thus should not be attached to
2115  * the ttylist.  This is why this call is not done from ttymalloc().
2116  *
2117  * Device drivers should attach tty's at a similar time that they are
2118  * ttymalloc()'ed, or, for the case of statically allocated struct tty's
2119  * either in the attach or (first) open routine.
2120  */
2121 void
2122 tty_attach(struct tty *tp)
2123 {
2124 
2125 	TAILQ_INSERT_TAIL(&ttylist, tp, tty_link);
2126 	++tty_count;
2127 }
2128 
2129 /*
2130  * Remove a tty from the tty list.
2131  */
2132 void
2133 tty_detach(struct tty *tp)
2134 {
2135 
2136 	--tty_count;
2137 #ifdef DIAGNOSTIC
2138 	if (tty_count < 0)
2139 		panic("tty_detach: tty_count < 0");
2140 #endif
2141 	TAILQ_REMOVE(&ttylist, tp, tty_link);
2142 }
2143 
2144 /*
2145  * Allocate a tty structure and its associated buffers.
2146  */
2147 struct tty *
2148 ttymalloc(void)
2149 {
2150 	struct tty	*tp;
2151 
2152 	tp = pool_get(&tty_pool, PR_WAITOK);
2153 	memset(tp, 0, sizeof(*tp));
2154 	callout_init(&tp->t_outq_ch);
2155 	callout_init(&tp->t_rstrt_ch);
2156 	/* XXX: default to 1024 chars for now */
2157 	clalloc(&tp->t_rawq, 1024, 1);
2158 	clalloc(&tp->t_canq, 1024, 1);
2159 	/* output queue doesn't need quoting */
2160 	clalloc(&tp->t_outq, 1024, 0);
2161 	/* Set default line discipline. */
2162 	tp->t_linesw = linesw[0];
2163 	return(tp);
2164 }
2165 
2166 /*
2167  * Free a tty structure and its buffers.
2168  *
2169  * Be sure to call tty_detach() for any tty that has been
2170  * tty_attach()ed.
2171  */
2172 void
2173 ttyfree(struct tty *tp)
2174 {
2175 
2176 	callout_stop(&tp->t_outq_ch);
2177 	callout_stop(&tp->t_rstrt_ch);
2178 	clfree(&tp->t_rawq);
2179 	clfree(&tp->t_canq);
2180 	clfree(&tp->t_outq);
2181 	pool_put(&tty_pool, tp);
2182 }
2183