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