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