xref: /dflybsd-src/sys/kern/tty.c (revision 5d6897ab88180d0f34082af35f34d78c6c929e73)
1 /*-
2  * Copyright (c) 1982, 1986, 1990, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)tty.c	8.8 (Berkeley) 1/21/94
39  * $FreeBSD: src/sys/kern/tty.c,v 1.129.2.5 2002/03/11 01:32:31 dd Exp $
40  * $DragonFly: src/sys/kern/tty.c,v 1.13 2004/10/07 01:32:03 dillon Exp $
41  */
42 
43 /*-
44  * TODO:
45  *	o Fix races for sending the start char in ttyflush().
46  *	o Handle inter-byte timeout for "MIN > 0, TIME > 0" in ttyselect().
47  *	  With luck, there will be MIN chars before select() returns().
48  *	o Handle CLOCAL consistently for ptys.  Perhaps disallow setting it.
49  *	o Don't allow input in TS_ZOMBIE case.  It would be visible through
50  *	  FIONREAD.
51  *	o Do the new sio locking stuff here and use it to avoid special
52  *	  case for EXTPROC?
53  *	o Lock PENDIN too?
54  *	o Move EXTPROC and/or PENDIN to t_state?
55  *	o Wrap most of ttioctl in spltty/splx.
56  *	o Implement TIOCNOTTY or remove it from <sys/ioctl.h>.
57  *	o Send STOP if IXOFF is toggled off while TS_TBLOCK is set.
58  *	o Don't allow certain termios flags to affect disciplines other
59  *	  than TTYDISC.  Cancel their effects before switch disciplines
60  *	  and ignore them if they are set while we are in another
61  *	  discipline.
62  *	o Now that historical speed conversions are handled here, don't
63  *	  do them in drivers.
64  *	o Check for TS_CARR_ON being set while everything is closed and not
65  *	  waiting for carrier.  TS_CARR_ON isn't cleared if nothing is open,
66  *	  so it would live until the next open even if carrier drops.
67  *	o Restore TS_WOPEN since it is useful in pstat.  It must be cleared
68  *	  only when _all_ openers leave open().
69  */
70 
71 #include "opt_compat.h"
72 #include "opt_uconsole.h"
73 
74 #include <sys/param.h>
75 #include <sys/systm.h>
76 #include <sys/filio.h>
77 #if defined(COMPAT_43) || defined(COMPAT_SUNOS)
78 #include <sys/ioctl_compat.h>
79 #endif
80 #include <sys/proc.h>
81 #define	TTYDEFCHARS
82 #include <sys/tty.h>
83 #include <sys/clist.h>
84 #undef	TTYDEFCHARS
85 #include <sys/fcntl.h>
86 #include <sys/conf.h>
87 #include <sys/dkstat.h>
88 #include <sys/poll.h>
89 #include <sys/kernel.h>
90 #include <sys/vnode.h>
91 #include <sys/signalvar.h>
92 #include <sys/resourcevar.h>
93 #include <sys/malloc.h>
94 #include <sys/filedesc.h>
95 #include <sys/sysctl.h>
96 #include <sys/thread2.h>
97 
98 #include <vm/vm.h>
99 #include <sys/lock.h>
100 #include <vm/pmap.h>
101 #include <vm/vm_map.h>
102 
103 MALLOC_DEFINE(M_TTYS, "ttys", "tty data structures");
104 
105 static int	proc_compare (struct proc *p1, struct proc *p2);
106 static int	ttnread (struct tty *tp);
107 static void	ttyecho (int c, struct tty *tp);
108 static int	ttyoutput (int c, struct tty *tp);
109 static void	ttypend (struct tty *tp);
110 static void	ttyretype (struct tty *tp);
111 static void	ttyrub (int c, struct tty *tp);
112 static void	ttyrubo (struct tty *tp, int cnt);
113 static void	ttyunblock (struct tty *tp);
114 static int	ttywflush (struct tty *tp);
115 static int	filt_ttyread (struct knote *kn, long hint);
116 static void 	filt_ttyrdetach (struct knote *kn);
117 static int	filt_ttywrite (struct knote *kn, long hint);
118 static void 	filt_ttywdetach (struct knote *kn);
119 
120 /*
121  * Table with character classes and parity. The 8th bit indicates parity,
122  * the 7th bit indicates the character is an alphameric or underscore (for
123  * ALTWERASE), and the low 6 bits indicate delay type.  If the low 6 bits
124  * are 0 then the character needs no special processing on output; classes
125  * other than 0 might be translated or (not currently) require delays.
126  */
127 #define	E	0x00	/* Even parity. */
128 #define	O	0x80	/* Odd parity. */
129 #define	PARITY(c)	(char_type[c] & O)
130 
131 #define	ALPHA	0x40	/* Alpha or underscore. */
132 #define	ISALPHA(c)	(char_type[(c) & TTY_CHARMASK] & ALPHA)
133 
134 #define	CCLASSMASK	0x3f
135 #define	CCLASS(c)	(char_type[c] & CCLASSMASK)
136 
137 #define	BS	BACKSPACE
138 #define	CC	CONTROL
139 #define	CR	RETURN
140 #define	NA	ORDINARY | ALPHA
141 #define	NL	NEWLINE
142 #define	NO	ORDINARY
143 #define	TB	TAB
144 #define	VT	VTAB
145 
146 static u_char const char_type[] = {
147 	E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC,	/* nul - bel */
148 	O|BS, E|TB, E|NL, O|CC, E|VT, O|CR, O|CC, E|CC, /* bs - si */
149 	O|CC, E|CC, E|CC, O|CC, E|CC, O|CC, O|CC, E|CC, /* dle - etb */
150 	E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC, /* can - us */
151 	O|NO, E|NO, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* sp - ' */
152 	E|NO, O|NO, O|NO, E|NO, O|NO, E|NO, E|NO, O|NO, /* ( - / */
153 	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* 0 - 7 */
154 	O|NA, E|NA, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* 8 - ? */
155 	O|NO, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* @ - G */
156 	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* H - O */
157 	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* P - W */
158 	O|NA, E|NA, E|NA, O|NO, E|NO, O|NO, O|NO, O|NA, /* X - _ */
159 	E|NO, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* ` - g */
160 	O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* h - o */
161 	O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* p - w */
162 	E|NA, O|NA, O|NA, E|NO, O|NO, E|NO, E|NO, O|CC, /* x - del */
163 	/*
164 	 * Meta chars; should be settable per character set;
165 	 * for now, treat them all as normal characters.
166 	 */
167 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
168 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
169 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
170 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
171 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
172 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
173 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
174 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
175 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
176 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
177 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
178 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
179 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
180 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
181 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
182 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
183 };
184 #undef	BS
185 #undef	CC
186 #undef	CR
187 #undef	NA
188 #undef	NL
189 #undef	NO
190 #undef	TB
191 #undef	VT
192 
193 /* Macros to clear/set/test flags. */
194 #define	SET(t, f)	(t) |= (f)
195 #define	CLR(t, f)	(t) &= ~(f)
196 #define	ISSET(t, f)	((t) & (f))
197 
198 #undef MAX_INPUT		/* XXX wrong in <sys/syslimits.h> */
199 #define	MAX_INPUT	TTYHOG	/* XXX limit is usually larger for !ICANON */
200 
201 /*
202  * list of struct tty where pstat(8) can pick it up with sysctl
203  */
204 static SLIST_HEAD(, tty) tty_list;
205 
206 /*
207  * Initial open of tty, or (re)entry to standard tty line discipline.
208  */
209 int
210 ttyopen(device, tp)
211 	dev_t device;
212 	struct tty *tp;
213 {
214 	int s;
215 
216 	s = spltty();
217 	tp->t_dev = device;
218 	if (!ISSET(tp->t_state, TS_ISOPEN)) {
219 		SET(tp->t_state, TS_ISOPEN);
220 		if (ISSET(tp->t_cflag, CLOCAL))
221 			SET(tp->t_state, TS_CONNECTED);
222 		bzero(&tp->t_winsize, sizeof(tp->t_winsize));
223 	}
224 	ttsetwater(tp);
225 	splx(s);
226 	return (0);
227 }
228 
229 /*
230  * Handle close() on a tty line: flush and set to initial state,
231  * bumping generation number so that pending read/write calls
232  * can detect recycling of the tty.
233  *
234  * XXX our caller should have done `spltty(); l_close(); ttyclose();'
235  * and l_close() should have flushed, but we repeat the spltty() and
236  * the flush in case there are buggy callers.
237  */
238 int
239 ttyclose(tp)
240 	struct tty *tp;
241 {
242 	int s;
243 
244 	funsetown(tp->t_sigio);
245 	s = spltty();
246 	if (constty == tp)
247 		constty = NULL;
248 
249 	ttyflush(tp, FREAD | FWRITE);
250 	clist_free_cblocks(&tp->t_canq);
251 	clist_free_cblocks(&tp->t_outq);
252 	clist_free_cblocks(&tp->t_rawq);
253 
254 	tp->t_gen++;
255 	tp->t_line = TTYDISC;
256 	ttyclearsession(tp);
257 	tp->t_state = 0;
258 	splx(s);
259 	return (0);
260 }
261 
262 /*
263  * Disassociate the tty from its session.  Traditionally this has only been
264  * a half-close, meaning that the session was still allowed to point at the
265  * tty (resulting in the tty in the ps command showing something like 'p0-'),
266  * even though the tty is no longer pointing at the session.
267  *
268  * The half close seems to be useful only for 'ps' output but there is as
269  * yet no reason to remove the feature.  The full-close code is currently
270  * #if 0'd out.  See also sess_rele() in kern/kern_proc.c.
271  */
272 void
273 ttyclearsession(struct tty *tp)
274 {
275 	struct session *sp;
276 
277 	tp->t_pgrp = NULL;
278 	if ((sp = tp->t_session) != NULL) {
279 		tp->t_session = NULL;
280 #ifdef TTY_DO_FULL_CLOSE
281 		/* FULL CLOSE (not yet) */
282 		if (sp->s_ttyp == tp) {
283 			sp->s_ttyp = NULL;
284 		} else {
285 			printf("ttyclearsession: warning: sp->s_ttyp != tp "
286 				"%p/%p\n", sp->s_ttyp, tp);
287 		}
288 #endif
289 	}
290 }
291 
292 #define	FLUSHQ(q) {							\
293 	if ((q)->c_cc)							\
294 		ndflush(q, (q)->c_cc);					\
295 }
296 
297 /* Is 'c' a line delimiter ("break" character)? */
298 #define	TTBREAKC(c, lflag)							\
299 	((c) == '\n' || (((c) == cc[VEOF] ||				\
300 	  (c) == cc[VEOL] || ((c) == cc[VEOL2] && lflag & IEXTEN)) &&	\
301 	 (c) != _POSIX_VDISABLE))
302 
303 /*
304  * Process input of a single character received on a tty.
305  */
306 int
307 ttyinput(c, tp)
308 	int c;
309 	struct tty *tp;
310 {
311 	tcflag_t iflag, lflag;
312 	cc_t *cc;
313 	int i, err;
314 
315 	/*
316 	 * If input is pending take it first.
317 	 */
318 	lflag = tp->t_lflag;
319 	if (ISSET(lflag, PENDIN))
320 		ttypend(tp);
321 	/*
322 	 * Gather stats.
323 	 */
324 	if (ISSET(lflag, ICANON)) {
325 		++tk_cancc;
326 		++tp->t_cancc;
327 	} else {
328 		++tk_rawcc;
329 		++tp->t_rawcc;
330 	}
331 	++tk_nin;
332 
333 	/*
334 	 * Block further input iff:
335 	 * current input > threshold AND input is available to user program
336 	 * AND input flow control is enabled and not yet invoked.
337 	 * The 3 is slop for PARMRK.
338 	 */
339 	iflag = tp->t_iflag;
340 	if (tp->t_rawq.c_cc + tp->t_canq.c_cc > tp->t_ihiwat - 3 &&
341 	    (!ISSET(lflag, ICANON) || tp->t_canq.c_cc != 0) &&
342 	    (ISSET(tp->t_cflag, CRTS_IFLOW) || ISSET(iflag, IXOFF)) &&
343 	    !ISSET(tp->t_state, TS_TBLOCK))
344 		ttyblock(tp);
345 
346 	/* Handle exceptional conditions (break, parity, framing). */
347 	cc = tp->t_cc;
348 	err = (ISSET(c, TTY_ERRORMASK));
349 	if (err) {
350 		CLR(c, TTY_ERRORMASK);
351 		if (ISSET(err, TTY_BI)) {
352 			if (ISSET(iflag, IGNBRK))
353 				return (0);
354 			if (ISSET(iflag, BRKINT)) {
355 				ttyflush(tp, FREAD | FWRITE);
356 				pgsignal(tp->t_pgrp, SIGINT, 1);
357 				goto endcase;
358 			}
359 			if (ISSET(iflag, PARMRK))
360 				goto parmrk;
361 		} else if ((ISSET(err, TTY_PE) && ISSET(iflag, INPCK))
362 			|| ISSET(err, TTY_FE)) {
363 			if (ISSET(iflag, IGNPAR))
364 				return (0);
365 			else if (ISSET(iflag, PARMRK)) {
366 parmrk:
367 				if (tp->t_rawq.c_cc + tp->t_canq.c_cc >
368 				    MAX_INPUT - 3)
369 					goto input_overflow;
370 				(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
371 				(void)putc(0 | TTY_QUOTE, &tp->t_rawq);
372 				(void)putc(c | TTY_QUOTE, &tp->t_rawq);
373 				goto endcase;
374 			} else
375 				c = 0;
376 		}
377 	}
378 
379 	if (!ISSET(tp->t_state, TS_TYPEN) && ISSET(iflag, ISTRIP))
380 		CLR(c, 0x80);
381 	if (!ISSET(lflag, EXTPROC)) {
382 		/*
383 		 * Check for literal nexting very first
384 		 */
385 		if (ISSET(tp->t_state, TS_LNCH)) {
386 			SET(c, TTY_QUOTE);
387 			CLR(tp->t_state, TS_LNCH);
388 		}
389 		/*
390 		 * Scan for special characters.  This code
391 		 * is really just a big case statement with
392 		 * non-constant cases.  The bottom of the
393 		 * case statement is labeled ``endcase'', so goto
394 		 * it after a case match, or similar.
395 		 */
396 
397 		/*
398 		 * Control chars which aren't controlled
399 		 * by ICANON, ISIG, or IXON.
400 		 */
401 		if (ISSET(lflag, IEXTEN)) {
402 			if (CCEQ(cc[VLNEXT], c)) {
403 				if (ISSET(lflag, ECHO)) {
404 					if (ISSET(lflag, ECHOE)) {
405 						(void)ttyoutput('^', tp);
406 						(void)ttyoutput('\b', tp);
407 					} else
408 						ttyecho(c, tp);
409 				}
410 				SET(tp->t_state, TS_LNCH);
411 				goto endcase;
412 			}
413 			if (CCEQ(cc[VDISCARD], c)) {
414 				if (ISSET(lflag, FLUSHO))
415 					CLR(tp->t_lflag, FLUSHO);
416 				else {
417 					ttyflush(tp, FWRITE);
418 					ttyecho(c, tp);
419 					if (tp->t_rawq.c_cc + tp->t_canq.c_cc)
420 						ttyretype(tp);
421 					SET(tp->t_lflag, FLUSHO);
422 				}
423 				goto startoutput;
424 			}
425 		}
426 		/*
427 		 * Signals.
428 		 */
429 		if (ISSET(lflag, ISIG)) {
430 			if (CCEQ(cc[VINTR], c) || CCEQ(cc[VQUIT], c)) {
431 				if (!ISSET(lflag, NOFLSH))
432 					ttyflush(tp, FREAD | FWRITE);
433 				ttyecho(c, tp);
434 				pgsignal(tp->t_pgrp,
435 				    CCEQ(cc[VINTR], c) ? SIGINT : SIGQUIT, 1);
436 				goto endcase;
437 			}
438 			if (CCEQ(cc[VSUSP], c)) {
439 				if (!ISSET(lflag, NOFLSH))
440 					ttyflush(tp, FREAD);
441 				ttyecho(c, tp);
442 				pgsignal(tp->t_pgrp, SIGTSTP, 1);
443 				goto endcase;
444 			}
445 		}
446 		/*
447 		 * Handle start/stop characters.
448 		 */
449 		if (ISSET(iflag, IXON)) {
450 			if (CCEQ(cc[VSTOP], c)) {
451 				if (!ISSET(tp->t_state, TS_TTSTOP)) {
452 					SET(tp->t_state, TS_TTSTOP);
453 					(*tp->t_stop)(tp, 0);
454 					return (0);
455 				}
456 				if (!CCEQ(cc[VSTART], c))
457 					return (0);
458 				/*
459 				 * if VSTART == VSTOP then toggle
460 				 */
461 				goto endcase;
462 			}
463 			if (CCEQ(cc[VSTART], c))
464 				goto restartoutput;
465 		}
466 		/*
467 		 * IGNCR, ICRNL, & INLCR
468 		 */
469 		if (c == '\r') {
470 			if (ISSET(iflag, IGNCR))
471 				return (0);
472 			else if (ISSET(iflag, ICRNL))
473 				c = '\n';
474 		} else if (c == '\n' && ISSET(iflag, INLCR))
475 			c = '\r';
476 	}
477 	if (!ISSET(tp->t_lflag, EXTPROC) && ISSET(lflag, ICANON)) {
478 		/*
479 		 * From here on down canonical mode character
480 		 * processing takes place.
481 		 */
482 		/*
483 		 * erase or erase2 (^H / ^?)
484 		 */
485 		if (CCEQ(cc[VERASE], c) || CCEQ(cc[VERASE2], c) ) {
486 			if (tp->t_rawq.c_cc)
487 				ttyrub(unputc(&tp->t_rawq), tp);
488 			goto endcase;
489 		}
490 		/*
491 		 * kill (^U)
492 		 */
493 		if (CCEQ(cc[VKILL], c)) {
494 			if (ISSET(lflag, ECHOKE) &&
495 			    tp->t_rawq.c_cc == tp->t_rocount &&
496 			    !ISSET(lflag, ECHOPRT))
497 				while (tp->t_rawq.c_cc)
498 					ttyrub(unputc(&tp->t_rawq), tp);
499 			else {
500 				ttyecho(c, tp);
501 				if (ISSET(lflag, ECHOK) ||
502 				    ISSET(lflag, ECHOKE))
503 					ttyecho('\n', tp);
504 				FLUSHQ(&tp->t_rawq);
505 				tp->t_rocount = 0;
506 			}
507 			CLR(tp->t_state, TS_LOCAL);
508 			goto endcase;
509 		}
510 		/*
511 		 * word erase (^W)
512 		 */
513 		if (CCEQ(cc[VWERASE], c) && ISSET(lflag, IEXTEN)) {
514 			int ctype;
515 
516 			/*
517 			 * erase whitespace
518 			 */
519 			while ((c = unputc(&tp->t_rawq)) == ' ' || c == '\t')
520 				ttyrub(c, tp);
521 			if (c == -1)
522 				goto endcase;
523 			/*
524 			 * erase last char of word and remember the
525 			 * next chars type (for ALTWERASE)
526 			 */
527 			ttyrub(c, tp);
528 			c = unputc(&tp->t_rawq);
529 			if (c == -1)
530 				goto endcase;
531 			if (c == ' ' || c == '\t') {
532 				(void)putc(c, &tp->t_rawq);
533 				goto endcase;
534 			}
535 			ctype = ISALPHA(c);
536 			/*
537 			 * erase rest of word
538 			 */
539 			do {
540 				ttyrub(c, tp);
541 				c = unputc(&tp->t_rawq);
542 				if (c == -1)
543 					goto endcase;
544 			} while (c != ' ' && c != '\t' &&
545 			    (!ISSET(lflag, ALTWERASE) || ISALPHA(c) == ctype));
546 			(void)putc(c, &tp->t_rawq);
547 			goto endcase;
548 		}
549 		/*
550 		 * reprint line (^R)
551 		 */
552 		if (CCEQ(cc[VREPRINT], c) && ISSET(lflag, IEXTEN)) {
553 			ttyretype(tp);
554 			goto endcase;
555 		}
556 		/*
557 		 * ^T - kernel info and generate SIGINFO
558 		 */
559 		if (CCEQ(cc[VSTATUS], c) && ISSET(lflag, IEXTEN)) {
560 			if (ISSET(lflag, ISIG))
561 				pgsignal(tp->t_pgrp, SIGINFO, 1);
562 			if (!ISSET(lflag, NOKERNINFO))
563 				ttyinfo(tp);
564 			goto endcase;
565 		}
566 		if (CCEQ(cc[VCHECKPT], c) && ISSET(lflag, IEXTEN)) {
567 			if (ISSET(lflag, ISIG))
568 				pgsignal(tp->t_pgrp, SIGCKPT, 1);
569 			goto endcase;
570 		}
571 	}
572 	/*
573 	 * Check for input buffer overflow
574 	 */
575 	if (tp->t_rawq.c_cc + tp->t_canq.c_cc >= MAX_INPUT) {
576 input_overflow:
577 		if (ISSET(iflag, IMAXBEL)) {
578 			if (tp->t_outq.c_cc < tp->t_ohiwat)
579 				(void)ttyoutput(CTRL('g'), tp);
580 		}
581 		goto endcase;
582 	}
583 
584 	if (   c == 0377 && ISSET(iflag, PARMRK) && !ISSET(iflag, ISTRIP)
585 	     && ISSET(iflag, IGNBRK|IGNPAR) != (IGNBRK|IGNPAR))
586 		(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
587 
588 	/*
589 	 * Put data char in q for user and
590 	 * wakeup on seeing a line delimiter.
591 	 */
592 	if (putc(c, &tp->t_rawq) >= 0) {
593 		if (!ISSET(lflag, ICANON)) {
594 			ttwakeup(tp);
595 			ttyecho(c, tp);
596 			goto endcase;
597 		}
598 		if (TTBREAKC(c, lflag)) {
599 			tp->t_rocount = 0;
600 			catq(&tp->t_rawq, &tp->t_canq);
601 			ttwakeup(tp);
602 		} else if (tp->t_rocount++ == 0)
603 			tp->t_rocol = tp->t_column;
604 		if (ISSET(tp->t_state, TS_ERASE)) {
605 			/*
606 			 * end of prterase \.../
607 			 */
608 			CLR(tp->t_state, TS_ERASE);
609 			(void)ttyoutput('/', tp);
610 		}
611 		i = tp->t_column;
612 		ttyecho(c, tp);
613 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ECHO)) {
614 			/*
615 			 * Place the cursor over the '^' of the ^D.
616 			 */
617 			i = imin(2, tp->t_column - i);
618 			while (i > 0) {
619 				(void)ttyoutput('\b', tp);
620 				i--;
621 			}
622 		}
623 	}
624 endcase:
625 	/*
626 	 * IXANY means allow any character to restart output.
627 	 */
628 	if (ISSET(tp->t_state, TS_TTSTOP) &&
629 	    !ISSET(iflag, IXANY) && cc[VSTART] != cc[VSTOP])
630 		return (0);
631 restartoutput:
632 	CLR(tp->t_lflag, FLUSHO);
633 	CLR(tp->t_state, TS_TTSTOP);
634 startoutput:
635 	return (ttstart(tp));
636 }
637 
638 /*
639  * Output a single character on a tty, doing output processing
640  * as needed (expanding tabs, newline processing, etc.).
641  * Returns < 0 if succeeds, otherwise returns char to resend.
642  * Must be recursive.
643  */
644 static int
645 ttyoutput(c, tp)
646 	int c;
647 	struct tty *tp;
648 {
649 	tcflag_t oflag;
650 	int col, s;
651 
652 	oflag = tp->t_oflag;
653 	if (!ISSET(oflag, OPOST)) {
654 		if (ISSET(tp->t_lflag, FLUSHO))
655 			return (-1);
656 		if (putc(c, &tp->t_outq))
657 			return (c);
658 		tk_nout++;
659 		tp->t_outcc++;
660 		return (-1);
661 	}
662 	/*
663 	 * Do tab expansion if OXTABS is set.  Special case if we external
664 	 * processing, we don't do the tab expansion because we'll probably
665 	 * get it wrong.  If tab expansion needs to be done, let it happen
666 	 * externally.
667 	 */
668 	CLR(c, ~TTY_CHARMASK);
669 	if (c == '\t' &&
670 	    ISSET(oflag, OXTABS) && !ISSET(tp->t_lflag, EXTPROC)) {
671 		c = 8 - (tp->t_column & 7);
672 		if (!ISSET(tp->t_lflag, FLUSHO)) {
673 			s = spltty();		/* Don't interrupt tabs. */
674 			c -= b_to_q("        ", c, &tp->t_outq);
675 			tk_nout += c;
676 			tp->t_outcc += c;
677 			splx(s);
678 		}
679 		tp->t_column += c;
680 		return (c ? -1 : '\t');
681 	}
682 	if (c == CEOT && ISSET(oflag, ONOEOT))
683 		return (-1);
684 
685 	/*
686 	 * Newline translation: if ONLCR is set,
687 	 * translate newline into "\r\n".
688 	 */
689 	if (c == '\n' && ISSET(tp->t_oflag, ONLCR)) {
690 		tk_nout++;
691 		tp->t_outcc++;
692 		if (!ISSET(tp->t_lflag, FLUSHO) && putc('\r', &tp->t_outq))
693 			return (c);
694 	}
695 	/* If OCRNL is set, translate "\r" into "\n". */
696 	else if (c == '\r' && ISSET(tp->t_oflag, OCRNL))
697 		c = '\n';
698 	/* If ONOCR is set, don't transmit CRs when on column 0. */
699 	else if (c == '\r' && ISSET(tp->t_oflag, ONOCR) && tp->t_column == 0)
700 		return (-1);
701 
702 	tk_nout++;
703 	tp->t_outcc++;
704 	if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
705 		return (c);
706 
707 	col = tp->t_column;
708 	switch (CCLASS(c)) {
709 	case BACKSPACE:
710 		if (col > 0)
711 			--col;
712 		break;
713 	case CONTROL:
714 		break;
715 	case NEWLINE:
716 		if (ISSET(tp->t_oflag, ONLCR | ONLRET))
717 			col = 0;
718 		break;
719 	case RETURN:
720 		col = 0;
721 		break;
722 	case ORDINARY:
723 		++col;
724 		break;
725 	case TAB:
726 		col = (col + 8) & ~7;
727 		break;
728 	}
729 	tp->t_column = col;
730 	return (-1);
731 }
732 
733 /*
734  * Ioctls for all tty devices.  Called after line-discipline specific ioctl
735  * has been called to do discipline-specific functions and/or reject any
736  * of these ioctl commands.
737  */
738 /* ARGSUSED */
739 int
740 ttioctl(struct tty *tp, u_long cmd, void *data, int flag)
741 {
742 	struct thread *td = curthread;
743 	struct proc *p = td->td_proc;
744 	int s, error;
745 
746 	KKASSERT(p);
747 
748 	/* If the ioctl involves modification, hang if in the background. */
749 	switch (cmd) {
750 	case  TIOCCBRK:
751 	case  TIOCCONS:
752 	case  TIOCDRAIN:
753 	case  TIOCEXCL:
754 	case  TIOCFLUSH:
755 #ifdef TIOCHPCL
756 	case  TIOCHPCL:
757 #endif
758 	case  TIOCNXCL:
759 	case  TIOCSBRK:
760 	case  TIOCSCTTY:
761 	case  TIOCSDRAINWAIT:
762 	case  TIOCSETA:
763 	case  TIOCSETAF:
764 	case  TIOCSETAW:
765 	case  TIOCSETD:
766 	case  TIOCSPGRP:
767 	case  TIOCSTART:
768 	case  TIOCSTAT:
769 	case  TIOCSTI:
770 	case  TIOCSTOP:
771 	case  TIOCSWINSZ:
772 #if defined(COMPAT_43) || defined(COMPAT_SUNOS)
773 	case  TIOCLBIC:
774 	case  TIOCLBIS:
775 	case  TIOCLSET:
776 	case  TIOCSETC:
777 	case OTIOCSETD:
778 	case  TIOCSETN:
779 	case  TIOCSETP:
780 	case  TIOCSLTC:
781 #endif
782 		while (isbackground(p, tp) && !(p->p_flag & P_PPWAIT) &&
783 		    !SIGISMEMBER(p->p_sigignore, SIGTTOU) &&
784 		    !SIGISMEMBER(p->p_sigmask, SIGTTOU)) {
785 			if (p->p_pgrp->pg_jobc == 0)
786 				return (EIO);
787 			pgsignal(p->p_pgrp, SIGTTOU, 1);
788 			error = ttysleep(tp, &lbolt, PCATCH, "ttybg1",
789 					 0);
790 			if (error)
791 				return (error);
792 		}
793 		break;
794 	}
795 
796 	switch (cmd) {			/* Process the ioctl. */
797 	case FIOASYNC:			/* set/clear async i/o */
798 		s = spltty();
799 		if (*(int *)data)
800 			SET(tp->t_state, TS_ASYNC);
801 		else
802 			CLR(tp->t_state, TS_ASYNC);
803 		splx(s);
804 		break;
805 	case FIONBIO:			/* set/clear non-blocking i/o */
806 		break;			/* XXX: delete. */
807 	case FIONREAD:			/* get # bytes to read */
808 		s = spltty();
809 		*(int *)data = ttnread(tp);
810 		splx(s);
811 		break;
812 
813 	case FIOSETOWN:
814 		/*
815 		 * Policy -- Don't allow FIOSETOWN on someone else's
816 		 *           controlling tty
817 		 */
818 		if (tp->t_session != NULL && !isctty(p, tp))
819 			return (ENOTTY);
820 
821 		error = fsetown(*(int *)data, &tp->t_sigio);
822 		if (error)
823 			return (error);
824 		break;
825 	case FIOGETOWN:
826 		if (tp->t_session != NULL && !isctty(p, tp))
827 			return (ENOTTY);
828 		*(int *)data = fgetown(tp->t_sigio);
829 		break;
830 
831 	case TIOCEXCL:			/* set exclusive use of tty */
832 		s = spltty();
833 		SET(tp->t_state, TS_XCLUDE);
834 		splx(s);
835 		break;
836 	case TIOCFLUSH: {		/* flush buffers */
837 		int flags = *(int *)data;
838 
839 		if (flags == 0)
840 			flags = FREAD | FWRITE;
841 		else
842 			flags &= FREAD | FWRITE;
843 		ttyflush(tp, flags);
844 		break;
845 	}
846 	case TIOCCONS:			/* become virtual console */
847 		if (*(int *)data) {
848 			if (constty && constty != tp &&
849 			    ISSET(constty->t_state, TS_CONNECTED))
850 				return (EBUSY);
851 #ifndef	UCONSOLE
852 			if ((error = suser(td)) != 0)
853 				return (error);
854 #endif
855 			constty = tp;
856 		} else if (tp == constty)
857 			constty = NULL;
858 		break;
859 	case TIOCDRAIN:			/* wait till output drained */
860 		error = ttywait(tp);
861 		if (error)
862 			return (error);
863 		break;
864 	case TIOCGETA: {		/* get termios struct */
865 		struct termios *t = (struct termios *)data;
866 
867 		bcopy(&tp->t_termios, t, sizeof(struct termios));
868 		break;
869 	}
870 	case TIOCGETD:			/* get line discipline */
871 		*(int *)data = tp->t_line;
872 		break;
873 	case TIOCGWINSZ:		/* get window size */
874 		*(struct winsize *)data = tp->t_winsize;
875 		break;
876 	case TIOCGPGRP:			/* get pgrp of tty */
877 		if (!isctty(p, tp))
878 			return (ENOTTY);
879 		*(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
880 		break;
881 #ifdef TIOCHPCL
882 	case TIOCHPCL:			/* hang up on last close */
883 		s = spltty();
884 		SET(tp->t_cflag, HUPCL);
885 		splx(s);
886 		break;
887 #endif
888 	case TIOCNXCL:			/* reset exclusive use of tty */
889 		s = spltty();
890 		CLR(tp->t_state, TS_XCLUDE);
891 		splx(s);
892 		break;
893 	case TIOCOUTQ:			/* output queue size */
894 		*(int *)data = tp->t_outq.c_cc;
895 		break;
896 	case TIOCSETA:			/* set termios struct */
897 	case TIOCSETAW:			/* drain output, set */
898 	case TIOCSETAF: {		/* drn out, fls in, set */
899 		struct termios *t = (struct termios *)data;
900 
901 		if (t->c_ispeed == 0)
902 			t->c_ispeed = t->c_ospeed;
903 		if (t->c_ispeed == 0)
904 			t->c_ispeed = tp->t_ospeed;
905 		if (t->c_ispeed == 0)
906 			return (EINVAL);
907 		s = spltty();
908 		if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
909 			error = ttywait(tp);
910 			if (error) {
911 				splx(s);
912 				return (error);
913 			}
914 			if (cmd == TIOCSETAF)
915 				ttyflush(tp, FREAD);
916 		}
917 		if (!ISSET(t->c_cflag, CIGNORE)) {
918 			/*
919 			 * Set device hardware.
920 			 */
921 			if (tp->t_param && (error = (*tp->t_param)(tp, t))) {
922 				splx(s);
923 				return (error);
924 			}
925 			if (ISSET(t->c_cflag, CLOCAL) &&
926 			    !ISSET(tp->t_cflag, CLOCAL)) {
927 				/*
928 				 * XXX disconnections would be too hard to
929 				 * get rid of without this kludge.  The only
930 				 * way to get rid of controlling terminals
931 				 * is to exit from the session leader.
932 				 */
933 				CLR(tp->t_state, TS_ZOMBIE);
934 
935 				wakeup(TSA_CARR_ON(tp));
936 				ttwakeup(tp);
937 				ttwwakeup(tp);
938 			}
939 			if ((ISSET(tp->t_state, TS_CARR_ON) ||
940 			     ISSET(t->c_cflag, CLOCAL)) &&
941 			    !ISSET(tp->t_state, TS_ZOMBIE))
942 				SET(tp->t_state, TS_CONNECTED);
943 			else
944 				CLR(tp->t_state, TS_CONNECTED);
945 			tp->t_cflag = t->c_cflag;
946 			tp->t_ispeed = t->c_ispeed;
947 			if (t->c_ospeed != 0)
948 				tp->t_ospeed = t->c_ospeed;
949 			ttsetwater(tp);
950 		}
951 		if (ISSET(t->c_lflag, ICANON) != ISSET(tp->t_lflag, ICANON) &&
952 		    cmd != TIOCSETAF) {
953 			if (ISSET(t->c_lflag, ICANON))
954 				SET(tp->t_lflag, PENDIN);
955 			else {
956 				/*
957 				 * XXX we really shouldn't allow toggling
958 				 * ICANON while we're in a non-termios line
959 				 * discipline.  Now we have to worry about
960 				 * panicing for a null queue.
961 				 */
962 				if (tp->t_canq.c_cbreserved > 0 &&
963 				    tp->t_rawq.c_cbreserved > 0) {
964 					catq(&tp->t_rawq, &tp->t_canq);
965 					/*
966 					 * XXX the queue limits may be
967 					 * different, so the old queue
968 					 * swapping method no longer works.
969 					 */
970 					catq(&tp->t_canq, &tp->t_rawq);
971 				}
972 				CLR(tp->t_lflag, PENDIN);
973 			}
974 			ttwakeup(tp);
975 		}
976 		tp->t_iflag = t->c_iflag;
977 		tp->t_oflag = t->c_oflag;
978 		/*
979 		 * Make the EXTPROC bit read only.
980 		 */
981 		if (ISSET(tp->t_lflag, EXTPROC))
982 			SET(t->c_lflag, EXTPROC);
983 		else
984 			CLR(t->c_lflag, EXTPROC);
985 		tp->t_lflag = t->c_lflag | ISSET(tp->t_lflag, PENDIN);
986 		if (t->c_cc[VMIN] != tp->t_cc[VMIN] ||
987 		    t->c_cc[VTIME] != tp->t_cc[VTIME])
988 			ttwakeup(tp);
989 		bcopy(t->c_cc, tp->t_cc, sizeof(t->c_cc));
990 		splx(s);
991 		break;
992 	}
993 	case TIOCSETD: {		/* set line discipline */
994 		int t = *(int *)data;
995 		dev_t device = tp->t_dev;
996 
997 		if ((u_int)t >= nlinesw)
998 			return (ENXIO);
999 		if (t != tp->t_line) {
1000 			s = spltty();
1001 			(*linesw[tp->t_line].l_close)(tp, flag);
1002 			error = (*linesw[t].l_open)(device, tp);
1003 			if (error) {
1004 				(void)(*linesw[tp->t_line].l_open)(device, tp);
1005 				splx(s);
1006 				return (error);
1007 			}
1008 			tp->t_line = t;
1009 			splx(s);
1010 		}
1011 		break;
1012 	}
1013 	case TIOCSTART:			/* start output, like ^Q */
1014 		s = spltty();
1015 		if (ISSET(tp->t_state, TS_TTSTOP) ||
1016 		    ISSET(tp->t_lflag, FLUSHO)) {
1017 			CLR(tp->t_lflag, FLUSHO);
1018 			CLR(tp->t_state, TS_TTSTOP);
1019 			ttstart(tp);
1020 		}
1021 		splx(s);
1022 		break;
1023 	case TIOCSTI:			/* simulate terminal input */
1024 		if ((flag & FREAD) == 0 && suser(td))
1025 			return (EPERM);
1026 		if (!isctty(p, tp) && suser(td))
1027 			return (EACCES);
1028 		s = spltty();
1029 		(*linesw[tp->t_line].l_rint)(*(u_char *)data, tp);
1030 		splx(s);
1031 		break;
1032 	case TIOCSTOP:			/* stop output, like ^S */
1033 		s = spltty();
1034 		if (!ISSET(tp->t_state, TS_TTSTOP)) {
1035 			SET(tp->t_state, TS_TTSTOP);
1036 			(*tp->t_stop)(tp, 0);
1037 		}
1038 		splx(s);
1039 		break;
1040 	case TIOCSCTTY:			/* become controlling tty */
1041 		/* Session ctty vnode pointer set in vnode layer. */
1042 		if (!SESS_LEADER(p) ||
1043 		    ((p->p_session->s_ttyvp || tp->t_session) &&
1044 		    (tp->t_session != p->p_session)))
1045 			return (EPERM);
1046 		tp->t_session = p->p_session;
1047 		tp->t_pgrp = p->p_pgrp;
1048 		p->p_session->s_ttyp = tp;
1049 		p->p_flag |= P_CONTROLT;
1050 		break;
1051 	case TIOCSPGRP: {		/* set pgrp of tty */
1052 		struct pgrp *pgrp = pgfind(*(int *)data);
1053 
1054 		if (!isctty(p, tp))
1055 			return (ENOTTY);
1056 		else if (pgrp == NULL || pgrp->pg_session != p->p_session)
1057 			return (EPERM);
1058 		tp->t_pgrp = pgrp;
1059 		break;
1060 	}
1061 	case TIOCSTAT:			/* simulate control-T */
1062 		s = spltty();
1063 		ttyinfo(tp);
1064 		splx(s);
1065 		break;
1066 	case TIOCSWINSZ:		/* set window size */
1067 		if (bcmp((caddr_t)&tp->t_winsize, data,
1068 		    sizeof (struct winsize))) {
1069 			tp->t_winsize = *(struct winsize *)data;
1070 			pgsignal(tp->t_pgrp, SIGWINCH, 1);
1071 		}
1072 		break;
1073 	case TIOCSDRAINWAIT:
1074 		error = suser(td);
1075 		if (error)
1076 			return (error);
1077 		tp->t_timeout = *(int *)data * hz;
1078 		wakeup(TSA_OCOMPLETE(tp));
1079 		wakeup(TSA_OLOWAT(tp));
1080 		break;
1081 	case TIOCGDRAINWAIT:
1082 		*(int *)data = tp->t_timeout / hz;
1083 		break;
1084 	default:
1085 #if defined(COMPAT_43) || defined(COMPAT_SUNOS)
1086 		return (ttcompat(tp, cmd, data, flag));
1087 #else
1088 		return (ENOIOCTL);
1089 #endif
1090 	}
1091 	return (0);
1092 }
1093 
1094 int
1095 ttypoll(dev, events, td)
1096 	dev_t dev;
1097 	int events;
1098 	struct thread *td;
1099 {
1100 	int s;
1101 	int revents = 0;
1102 	struct tty *tp;
1103 
1104 	tp = dev->si_tty;
1105 	if (tp == NULL)	/* XXX used to return ENXIO, but that means true! */
1106 		return ((events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM))
1107 			| POLLHUP);
1108 
1109 	s = spltty();
1110 	if (events & (POLLIN | POLLRDNORM)) {
1111 		if (ttnread(tp) > 0 || ISSET(tp->t_state, TS_ZOMBIE))
1112 			revents |= events & (POLLIN | POLLRDNORM);
1113 		else
1114 			selrecord(td, &tp->t_rsel);
1115 	}
1116 	if (events & (POLLOUT | POLLWRNORM)) {
1117 		if ((tp->t_outq.c_cc <= tp->t_olowat &&
1118 		     ISSET(tp->t_state, TS_CONNECTED))
1119 		    || ISSET(tp->t_state, TS_ZOMBIE))
1120 			revents |= events & (POLLOUT | POLLWRNORM);
1121 		else
1122 			selrecord(td, &tp->t_wsel);
1123 	}
1124 	splx(s);
1125 	return (revents);
1126 }
1127 
1128 static struct filterops ttyread_filtops =
1129 	{ 1, NULL, filt_ttyrdetach, filt_ttyread };
1130 static struct filterops ttywrite_filtops =
1131 	{ 1, NULL, filt_ttywdetach, filt_ttywrite };
1132 
1133 int
1134 ttykqfilter(dev, kn)
1135 	dev_t dev;
1136 	struct knote *kn;
1137 {
1138 	struct tty *tp = dev->si_tty;
1139 	struct klist *klist;
1140 	int s;
1141 
1142 	switch (kn->kn_filter) {
1143 	case EVFILT_READ:
1144 		klist = &tp->t_rsel.si_note;
1145 		kn->kn_fop = &ttyread_filtops;
1146 		break;
1147 	case EVFILT_WRITE:
1148 		klist = &tp->t_wsel.si_note;
1149 		kn->kn_fop = &ttywrite_filtops;
1150 		break;
1151 	default:
1152 		return (1);
1153 	}
1154 
1155 	kn->kn_hook = (caddr_t)dev;
1156 
1157 	s = spltty();
1158 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
1159 	splx(s);
1160 
1161 	return (0);
1162 }
1163 
1164 static void
1165 filt_ttyrdetach(struct knote *kn)
1166 {
1167 	struct tty *tp = ((dev_t)kn->kn_hook)->si_tty;
1168 	int s = spltty();
1169 
1170 	SLIST_REMOVE(&tp->t_rsel.si_note, kn, knote, kn_selnext);
1171 	splx(s);
1172 }
1173 
1174 static int
1175 filt_ttyread(struct knote *kn, long hint)
1176 {
1177 	struct tty *tp = ((dev_t)kn->kn_hook)->si_tty;
1178 
1179 	kn->kn_data = ttnread(tp);
1180 	if (ISSET(tp->t_state, TS_ZOMBIE)) {
1181 		kn->kn_flags |= EV_EOF;
1182 		return (1);
1183 	}
1184 	return (kn->kn_data > 0);
1185 }
1186 
1187 static void
1188 filt_ttywdetach(struct knote *kn)
1189 {
1190 	struct tty *tp = ((dev_t)kn->kn_hook)->si_tty;
1191 	int s = spltty();
1192 
1193 	SLIST_REMOVE(&tp->t_wsel.si_note, kn, knote, kn_selnext);
1194 	splx(s);
1195 }
1196 
1197 static int
1198 filt_ttywrite(kn, hint)
1199 	struct knote *kn;
1200 	long hint;
1201 {
1202 	struct tty *tp = ((dev_t)kn->kn_hook)->si_tty;
1203 
1204 	kn->kn_data = tp->t_outq.c_cc;
1205 	if (ISSET(tp->t_state, TS_ZOMBIE))
1206 		return (1);
1207 	return (kn->kn_data <= tp->t_olowat &&
1208 	    ISSET(tp->t_state, TS_CONNECTED));
1209 }
1210 
1211 /*
1212  * Must be called at spltty().
1213  */
1214 static int
1215 ttnread(tp)
1216 	struct tty *tp;
1217 {
1218 	int nread;
1219 
1220 	if (ISSET(tp->t_lflag, PENDIN))
1221 		ttypend(tp);
1222 	nread = tp->t_canq.c_cc;
1223 	if (!ISSET(tp->t_lflag, ICANON)) {
1224 		nread += tp->t_rawq.c_cc;
1225 		if (nread < tp->t_cc[VMIN] && tp->t_cc[VTIME] == 0)
1226 			nread = 0;
1227 	}
1228 	return (nread);
1229 }
1230 
1231 /*
1232  * Wait for output to drain.
1233  */
1234 int
1235 ttywait(tp)
1236 	struct tty *tp;
1237 {
1238 	int error, s;
1239 
1240 	error = 0;
1241 	s = spltty();
1242 	while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1243 	       ISSET(tp->t_state, TS_CONNECTED) && tp->t_oproc) {
1244 		(*tp->t_oproc)(tp);
1245 		if ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1246 		    ISSET(tp->t_state, TS_CONNECTED)) {
1247 			SET(tp->t_state, TS_SO_OCOMPLETE);
1248 			error = ttysleep(tp, TSA_OCOMPLETE(tp),
1249 					 PCATCH, "ttywai",
1250 					 tp->t_timeout);
1251 			if (error) {
1252 				if (error == EWOULDBLOCK)
1253 					error = EIO;
1254 				break;
1255 			}
1256 		} else
1257 			break;
1258 	}
1259 	if (!error && (tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)))
1260 		error = EIO;
1261 	splx(s);
1262 	return (error);
1263 }
1264 
1265 /*
1266  * Flush if successfully wait.
1267  */
1268 static int
1269 ttywflush(tp)
1270 	struct tty *tp;
1271 {
1272 	int error;
1273 
1274 	if ((error = ttywait(tp)) == 0)
1275 		ttyflush(tp, FREAD);
1276 	return (error);
1277 }
1278 
1279 /*
1280  * Flush tty read and/or write queues, notifying anyone waiting.
1281  */
1282 void
1283 ttyflush(tp, rw)
1284 	struct tty *tp;
1285 	int rw;
1286 {
1287 	int s;
1288 
1289 	s = spltty();
1290 #if 0
1291 again:
1292 #endif
1293 	if (rw & FWRITE) {
1294 		FLUSHQ(&tp->t_outq);
1295 		CLR(tp->t_state, TS_TTSTOP);
1296 	}
1297 	(*tp->t_stop)(tp, rw);
1298 	if (rw & FREAD) {
1299 		FLUSHQ(&tp->t_canq);
1300 		FLUSHQ(&tp->t_rawq);
1301 		CLR(tp->t_lflag, PENDIN);
1302 		tp->t_rocount = 0;
1303 		tp->t_rocol = 0;
1304 		CLR(tp->t_state, TS_LOCAL);
1305 		ttwakeup(tp);
1306 		if (ISSET(tp->t_state, TS_TBLOCK)) {
1307 			if (rw & FWRITE)
1308 				FLUSHQ(&tp->t_outq);
1309 			ttyunblock(tp);
1310 
1311 			/*
1312 			 * Don't let leave any state that might clobber the
1313 			 * next line discipline (although we should do more
1314 			 * to send the START char).  Not clearing the state
1315 			 * may have caused the "putc to a clist with no
1316 			 * reserved cblocks" panic/printf.
1317 			 */
1318 			CLR(tp->t_state, TS_TBLOCK);
1319 
1320 #if 0 /* forget it, sleeping isn't always safe and we don't know when it is */
1321 			if (ISSET(tp->t_iflag, IXOFF)) {
1322 				/*
1323 				 * XXX wait a bit in the hope that the stop
1324 				 * character (if any) will go out.  Waiting
1325 				 * isn't good since it allows races.  This
1326 				 * will be fixed when the stop character is
1327 				 * put in a special queue.  Don't bother with
1328 				 * the checks in ttywait() since the timeout
1329 				 * will save us.
1330 				 */
1331 				SET(tp->t_state, TS_SO_OCOMPLETE);
1332 				ttysleep(tp, TSA_OCOMPLETE(tp), 0,
1333 					 "ttyfls", hz / 10);
1334 				/*
1335 				 * Don't try sending the stop character again.
1336 				 */
1337 				CLR(tp->t_state, TS_TBLOCK);
1338 				goto again;
1339 			}
1340 #endif
1341 		}
1342 	}
1343 	if (rw & FWRITE) {
1344 		FLUSHQ(&tp->t_outq);
1345 		ttwwakeup(tp);
1346 	}
1347 	splx(s);
1348 }
1349 
1350 /*
1351  * Copy in the default termios characters.
1352  */
1353 void
1354 termioschars(t)
1355 	struct termios *t;
1356 {
1357 
1358 	bcopy(ttydefchars, t->c_cc, sizeof t->c_cc);
1359 }
1360 
1361 /*
1362  * Old interface.
1363  */
1364 void
1365 ttychars(tp)
1366 	struct tty *tp;
1367 {
1368 
1369 	termioschars(&tp->t_termios);
1370 }
1371 
1372 /*
1373  * Handle input high water.  Send stop character for the IXOFF case.  Turn
1374  * on our input flow control bit and propagate the changes to the driver.
1375  * XXX the stop character should be put in a special high priority queue.
1376  */
1377 void
1378 ttyblock(tp)
1379 	struct tty *tp;
1380 {
1381 
1382 	SET(tp->t_state, TS_TBLOCK);
1383 	if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
1384 	    putc(tp->t_cc[VSTOP], &tp->t_outq) != 0)
1385 		CLR(tp->t_state, TS_TBLOCK);	/* try again later */
1386 	ttstart(tp);
1387 }
1388 
1389 /*
1390  * Handle input low water.  Send start character for the IXOFF case.  Turn
1391  * off our input flow control bit and propagate the changes to the driver.
1392  * XXX the start character should be put in a special high priority queue.
1393  */
1394 static void
1395 ttyunblock(tp)
1396 	struct tty *tp;
1397 {
1398 
1399 	CLR(tp->t_state, TS_TBLOCK);
1400 	if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTART] != _POSIX_VDISABLE &&
1401 	    putc(tp->t_cc[VSTART], &tp->t_outq) != 0)
1402 		SET(tp->t_state, TS_TBLOCK);	/* try again later */
1403 	ttstart(tp);
1404 }
1405 
1406 #ifdef notyet
1407 /* Not used by any current (i386) drivers. */
1408 /*
1409  * Restart after an inter-char delay.
1410  */
1411 void
1412 ttrstrt(tp_arg)
1413 	void *tp_arg;
1414 {
1415 	struct tty *tp;
1416 	int s;
1417 
1418 	KASSERT(tp_arg != NULL, ("ttrstrt"));
1419 
1420 	tp = tp_arg;
1421 	s = spltty();
1422 
1423 	CLR(tp->t_state, TS_TIMEOUT);
1424 	ttstart(tp);
1425 
1426 	splx(s);
1427 }
1428 #endif
1429 
1430 int
1431 ttstart(tp)
1432 	struct tty *tp;
1433 {
1434 
1435 	if (tp->t_oproc != NULL)	/* XXX: Kludge for pty. */
1436 		(*tp->t_oproc)(tp);
1437 	return (0);
1438 }
1439 
1440 /*
1441  * "close" a line discipline
1442  */
1443 int
1444 ttylclose(tp, flag)
1445 	struct tty *tp;
1446 	int flag;
1447 {
1448 
1449 	if (flag & FNONBLOCK || ttywflush(tp))
1450 		ttyflush(tp, FREAD | FWRITE);
1451 	return (0);
1452 }
1453 
1454 /*
1455  * Handle modem control transition on a tty.
1456  * Flag indicates new state of carrier.
1457  * Returns 0 if the line should be turned off, otherwise 1.
1458  */
1459 int
1460 ttymodem(tp, flag)
1461 	struct tty *tp;
1462 	int flag;
1463 {
1464 
1465 	if (ISSET(tp->t_state, TS_CARR_ON) && ISSET(tp->t_cflag, MDMBUF)) {
1466 		/*
1467 		 * MDMBUF: do flow control according to carrier flag
1468 		 * XXX TS_CAR_OFLOW doesn't do anything yet.  TS_TTSTOP
1469 		 * works if IXON and IXANY are clear.
1470 		 */
1471 		if (flag) {
1472 			CLR(tp->t_state, TS_CAR_OFLOW);
1473 			CLR(tp->t_state, TS_TTSTOP);
1474 			ttstart(tp);
1475 		} else if (!ISSET(tp->t_state, TS_CAR_OFLOW)) {
1476 			SET(tp->t_state, TS_CAR_OFLOW);
1477 			SET(tp->t_state, TS_TTSTOP);
1478 			(*tp->t_stop)(tp, 0);
1479 		}
1480 	} else if (flag == 0) {
1481 		/*
1482 		 * Lost carrier.
1483 		 */
1484 		CLR(tp->t_state, TS_CARR_ON);
1485 		if (ISSET(tp->t_state, TS_ISOPEN) &&
1486 		    !ISSET(tp->t_cflag, CLOCAL)) {
1487 			SET(tp->t_state, TS_ZOMBIE);
1488 			CLR(tp->t_state, TS_CONNECTED);
1489 			if (tp->t_session && tp->t_session->s_leader)
1490 				psignal(tp->t_session->s_leader, SIGHUP);
1491 			ttyflush(tp, FREAD | FWRITE);
1492 			return (0);
1493 		}
1494 	} else {
1495 		/*
1496 		 * Carrier now on.
1497 		 */
1498 		SET(tp->t_state, TS_CARR_ON);
1499 		if (!ISSET(tp->t_state, TS_ZOMBIE))
1500 			SET(tp->t_state, TS_CONNECTED);
1501 		wakeup(TSA_CARR_ON(tp));
1502 		ttwakeup(tp);
1503 		ttwwakeup(tp);
1504 	}
1505 	return (1);
1506 }
1507 
1508 /*
1509  * Reinput pending characters after state switch
1510  * call at spltty().
1511  */
1512 static void
1513 ttypend(tp)
1514 	struct tty *tp;
1515 {
1516 	struct clist tq;
1517 	int c;
1518 
1519 	CLR(tp->t_lflag, PENDIN);
1520 	SET(tp->t_state, TS_TYPEN);
1521 	/*
1522 	 * XXX this assumes too much about clist internals.  It may even
1523 	 * fail if the cblock slush pool is empty.  We can't allocate more
1524 	 * cblocks here because we are called from an interrupt handler
1525 	 * and clist_alloc_cblocks() can wait.
1526 	 */
1527 	tq = tp->t_rawq;
1528 	bzero(&tp->t_rawq, sizeof tp->t_rawq);
1529 	tp->t_rawq.c_cbmax = tq.c_cbmax;
1530 	tp->t_rawq.c_cbreserved = tq.c_cbreserved;
1531 	while ((c = getc(&tq)) >= 0)
1532 		ttyinput(c, tp);
1533 	CLR(tp->t_state, TS_TYPEN);
1534 }
1535 
1536 /*
1537  * Process a read call on a tty device.
1538  */
1539 int
1540 ttread(tp, uio, flag)
1541 	struct tty *tp;
1542 	struct uio *uio;
1543 	int flag;
1544 {
1545 	struct clist *qp;
1546 	int c;
1547 	tcflag_t lflag;
1548 	cc_t *cc = tp->t_cc;
1549 	struct proc *p = curproc;
1550 	int s, first, error = 0;
1551 	int has_stime = 0, last_cc = 0;
1552 	long slp = 0;		/* XXX this should be renamed `timo'. */
1553 	struct timeval stime;
1554 
1555 loop:
1556 	s = spltty();
1557 	lflag = tp->t_lflag;
1558 	/*
1559 	 * take pending input first
1560 	 */
1561 	if (ISSET(lflag, PENDIN)) {
1562 		ttypend(tp);
1563 		splx(s);	/* reduce latency */
1564 		s = spltty();
1565 		lflag = tp->t_lflag;	/* XXX ttypend() clobbers it */
1566 	}
1567 
1568 	/*
1569 	 * Hang process if it's in the background.
1570 	 */
1571 	if (isbackground(p, tp)) {
1572 		splx(s);
1573 		if (SIGISMEMBER(p->p_sigignore, SIGTTIN) ||
1574 		    SIGISMEMBER(p->p_sigmask, SIGTTIN) ||
1575 		    (p->p_flag & P_PPWAIT) || p->p_pgrp->pg_jobc == 0)
1576 			return (EIO);
1577 		pgsignal(p->p_pgrp, SIGTTIN, 1);
1578 		error = ttysleep(tp, &lbolt, PCATCH, "ttybg2", 0);
1579 		if (error)
1580 			return (error);
1581 		goto loop;
1582 	}
1583 
1584 	if (ISSET(tp->t_state, TS_ZOMBIE)) {
1585 		splx(s);
1586 		return (0);	/* EOF */
1587 	}
1588 
1589 	/*
1590 	 * If canonical, use the canonical queue,
1591 	 * else use the raw queue.
1592 	 *
1593 	 * (should get rid of clists...)
1594 	 */
1595 	qp = ISSET(lflag, ICANON) ? &tp->t_canq : &tp->t_rawq;
1596 
1597 	if (flag & IO_NDELAY) {
1598 		if (qp->c_cc > 0)
1599 			goto read;
1600 		if (!ISSET(lflag, ICANON) && cc[VMIN] == 0) {
1601 			splx(s);
1602 			return (0);
1603 		}
1604 		splx(s);
1605 		return (EWOULDBLOCK);
1606 	}
1607 	if (!ISSET(lflag, ICANON)) {
1608 		int m = cc[VMIN];
1609 		long t = cc[VTIME];
1610 		struct timeval timecopy;
1611 
1612 		/*
1613 		 * Check each of the four combinations.
1614 		 * (m > 0 && t == 0) is the normal read case.
1615 		 * It should be fairly efficient, so we check that and its
1616 		 * companion case (m == 0 && t == 0) first.
1617 		 * For the other two cases, we compute the target sleep time
1618 		 * into slp.
1619 		 */
1620 		if (t == 0) {
1621 			if (qp->c_cc < m)
1622 				goto sleep;
1623 			if (qp->c_cc > 0)
1624 				goto read;
1625 
1626 			/* m, t and qp->c_cc are all 0.  0 is enough input. */
1627 			splx(s);
1628 			return (0);
1629 		}
1630 		t *= 100000;		/* time in us */
1631 #define diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 1000000 + \
1632 			 ((t1).tv_usec - (t2).tv_usec))
1633 		if (m > 0) {
1634 			if (qp->c_cc <= 0)
1635 				goto sleep;
1636 			if (qp->c_cc >= m)
1637 				goto read;
1638 			getmicrotime(&timecopy);
1639 			if (!has_stime) {
1640 				/* first character, start timer */
1641 				has_stime = 1;
1642 				stime = timecopy;
1643 				slp = t;
1644 			} else if (qp->c_cc > last_cc) {
1645 				/* got a character, restart timer */
1646 				stime = timecopy;
1647 				slp = t;
1648 			} else {
1649 				/* nothing, check expiration */
1650 				slp = t - diff(timecopy, stime);
1651 				if (slp <= 0)
1652 					goto read;
1653 			}
1654 			last_cc = qp->c_cc;
1655 		} else {	/* m == 0 */
1656 			if (qp->c_cc > 0)
1657 				goto read;
1658 			getmicrotime(&timecopy);
1659 			if (!has_stime) {
1660 				has_stime = 1;
1661 				stime = timecopy;
1662 				slp = t;
1663 			} else {
1664 				slp = t - diff(timecopy, stime);
1665 				if (slp <= 0) {
1666 					/* Timed out, but 0 is enough input. */
1667 					splx(s);
1668 					return (0);
1669 				}
1670 			}
1671 		}
1672 #undef diff
1673 		/*
1674 		 * Rounding down may make us wake up just short
1675 		 * of the target, so we round up.
1676 		 * The formula is ceiling(slp * hz/1000000).
1677 		 * 32-bit arithmetic is enough for hz < 169.
1678 		 * XXX see tvtohz() for how to avoid overflow if hz
1679 		 * is large (divide by `tick' and/or arrange to
1680 		 * use tvtohz() if hz is large).
1681 		 */
1682 		slp = (long) (((u_long)slp * hz) + 999999) / 1000000;
1683 		goto sleep;
1684 	}
1685 	if (qp->c_cc <= 0) {
1686 sleep:
1687 		/*
1688 		 * There is no input, or not enough input and we can block.
1689 		 */
1690 		error = ttysleep(tp, TSA_HUP_OR_INPUT(tp), PCATCH,
1691 				 ISSET(tp->t_state, TS_CONNECTED) ?
1692 				 "ttyin" : "ttyhup", (int)slp);
1693 		splx(s);
1694 		if (error == EWOULDBLOCK)
1695 			error = 0;
1696 		else if (error)
1697 			return (error);
1698 		/*
1699 		 * XXX what happens if another process eats some input
1700 		 * while we are asleep (not just here)?  It would be
1701 		 * safest to detect changes and reset our state variables
1702 		 * (has_stime and last_cc).
1703 		 */
1704 		slp = 0;
1705 		goto loop;
1706 	}
1707 read:
1708 	splx(s);
1709 	/*
1710 	 * Input present, check for input mapping and processing.
1711 	 */
1712 	first = 1;
1713 	if (ISSET(lflag, ICANON | ISIG))
1714 		goto slowcase;
1715 	for (;;) {
1716 		char ibuf[IBUFSIZ];
1717 		int icc;
1718 
1719 		icc = imin(uio->uio_resid, IBUFSIZ);
1720 		icc = q_to_b(qp, ibuf, icc);
1721 		if (icc <= 0) {
1722 			if (first)
1723 				goto loop;
1724 			break;
1725 		}
1726 		error = uiomove(ibuf, icc, uio);
1727 		/*
1728 		 * XXX if there was an error then we should ungetc() the
1729 		 * unmoved chars and reduce icc here.
1730 		 */
1731 		if (error)
1732 			break;
1733  		if (uio->uio_resid == 0)
1734 			break;
1735 		first = 0;
1736 	}
1737 	goto out;
1738 slowcase:
1739 	for (;;) {
1740 		c = getc(qp);
1741 		if (c < 0) {
1742 			if (first)
1743 				goto loop;
1744 			break;
1745 		}
1746 		/*
1747 		 * delayed suspend (^Y)
1748 		 */
1749 		if (CCEQ(cc[VDSUSP], c) &&
1750 		    ISSET(lflag, IEXTEN | ISIG) == (IEXTEN | ISIG)) {
1751 			pgsignal(tp->t_pgrp, SIGTSTP, 1);
1752 			if (first) {
1753 				error = ttysleep(tp, &lbolt, PCATCH,
1754 						 "ttybg3", 0);
1755 				if (error)
1756 					break;
1757 				goto loop;
1758 			}
1759 			break;
1760 		}
1761 		/*
1762 		 * Interpret EOF only in canonical mode.
1763 		 */
1764 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
1765 			break;
1766 		/*
1767 		 * Give user character.
1768 		 */
1769  		error = ureadc(c, uio);
1770 		if (error)
1771 			/* XXX should ungetc(c, qp). */
1772 			break;
1773  		if (uio->uio_resid == 0)
1774 			break;
1775 		/*
1776 		 * In canonical mode check for a "break character"
1777 		 * marking the end of a "line of input".
1778 		 */
1779 		if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
1780 			break;
1781 		first = 0;
1782 	}
1783 
1784 out:
1785 	/*
1786 	 * Look to unblock input now that (presumably)
1787 	 * the input queue has gone down.
1788 	 */
1789 	s = spltty();
1790 	if (ISSET(tp->t_state, TS_TBLOCK) &&
1791 	    tp->t_rawq.c_cc + tp->t_canq.c_cc <= tp->t_ilowat)
1792 		ttyunblock(tp);
1793 	splx(s);
1794 
1795 	return (error);
1796 }
1797 
1798 /*
1799  * Check the output queue on tp for space for a kernel message (from uprintf
1800  * or tprintf).  Allow some space over the normal hiwater mark so we don't
1801  * lose messages due to normal flow control, but don't let the tty run amok.
1802  * Sleeps here are not interruptible, but we return prematurely if new signals
1803  * arrive.
1804  */
1805 int
1806 ttycheckoutq(tp, wait)
1807 	struct tty *tp;
1808 	int wait;
1809 {
1810 	int hiwat, s;
1811 	sigset_t oldmask;
1812 
1813 	hiwat = tp->t_ohiwat;
1814 	SIGEMPTYSET(oldmask);
1815 	s = spltty();
1816 	if (wait)
1817 		oldmask = curproc->p_siglist;
1818 	if (tp->t_outq.c_cc > hiwat + OBUFSIZ + 100)
1819 		while (tp->t_outq.c_cc > hiwat) {
1820 			ttstart(tp);
1821 			if (tp->t_outq.c_cc <= hiwat)
1822 				break;
1823 			if (!(wait && SIGSETEQ(curproc->p_siglist, oldmask))) {
1824 				splx(s);
1825 				return (0);
1826 			}
1827 			SET(tp->t_state, TS_SO_OLOWAT);
1828 			tsleep(TSA_OLOWAT(tp), 0, "ttoutq", hz);
1829 		}
1830 	splx(s);
1831 	return (1);
1832 }
1833 
1834 /*
1835  * Process a write call on a tty device.
1836  */
1837 int
1838 ttwrite(tp, uio, flag)
1839 	struct tty *tp;
1840 	struct uio *uio;
1841 	int flag;
1842 {
1843 	char *cp = NULL;
1844 	int cc, ce;
1845 	struct proc *p;
1846 	int i, hiwat, cnt, error, s;
1847 	char obuf[OBUFSIZ];
1848 
1849 	hiwat = tp->t_ohiwat;
1850 	cnt = uio->uio_resid;
1851 	error = 0;
1852 	cc = 0;
1853 loop:
1854 	s = spltty();
1855 	if (ISSET(tp->t_state, TS_ZOMBIE)) {
1856 		splx(s);
1857 		if (uio->uio_resid == cnt)
1858 			error = EIO;
1859 		goto out;
1860 	}
1861 	if (!ISSET(tp->t_state, TS_CONNECTED)) {
1862 		if (flag & IO_NDELAY) {
1863 			splx(s);
1864 			error = EWOULDBLOCK;
1865 			goto out;
1866 		}
1867 		error = ttysleep(tp, TSA_CARR_ON(tp), PCATCH, "ttydcd", 0);
1868 		splx(s);
1869 		if (error)
1870 			goto out;
1871 		goto loop;
1872 	}
1873 	splx(s);
1874 	/*
1875 	 * Hang the process if it's in the background.
1876 	 */
1877 	p = curproc;
1878 	if (isbackground(p, tp) &&
1879 	    ISSET(tp->t_lflag, TOSTOP) && !(p->p_flag & P_PPWAIT) &&
1880 	    !SIGISMEMBER(p->p_sigignore, SIGTTOU) &&
1881 	    !SIGISMEMBER(p->p_sigmask, SIGTTOU)) {
1882 		if (p->p_pgrp->pg_jobc == 0) {
1883 			error = EIO;
1884 			goto out;
1885 		}
1886 		pgsignal(p->p_pgrp, SIGTTOU, 1);
1887 		error = ttysleep(tp, &lbolt, PCATCH, "ttybg4", 0);
1888 		if (error)
1889 			goto out;
1890 		goto loop;
1891 	}
1892 	/*
1893 	 * Process the user's data in at most OBUFSIZ chunks.  Perform any
1894 	 * output translation.  Keep track of high water mark, sleep on
1895 	 * overflow awaiting device aid in acquiring new space.
1896 	 */
1897 	while (uio->uio_resid > 0 || cc > 0) {
1898 		if (ISSET(tp->t_lflag, FLUSHO)) {
1899 			uio->uio_resid = 0;
1900 			return (0);
1901 		}
1902 		if (tp->t_outq.c_cc > hiwat)
1903 			goto ovhiwat;
1904 		/*
1905 		 * Grab a hunk of data from the user, unless we have some
1906 		 * leftover from last time.
1907 		 */
1908 		if (cc == 0) {
1909 			cc = imin(uio->uio_resid, OBUFSIZ);
1910 			cp = obuf;
1911 			error = uiomove(cp, cc, uio);
1912 			if (error) {
1913 				cc = 0;
1914 				break;
1915 			}
1916 		}
1917 		/*
1918 		 * If nothing fancy need be done, grab those characters we
1919 		 * can handle without any of ttyoutput's processing and
1920 		 * just transfer them to the output q.  For those chars
1921 		 * which require special processing (as indicated by the
1922 		 * bits in char_type), call ttyoutput.  After processing
1923 		 * a hunk of data, look for FLUSHO so ^O's will take effect
1924 		 * immediately.
1925 		 */
1926 		while (cc > 0) {
1927 			if (!ISSET(tp->t_oflag, OPOST))
1928 				ce = cc;
1929 			else {
1930 				ce = cc - scanc((u_int)cc, (u_char *)cp,
1931 						char_type, CCLASSMASK);
1932 				/*
1933 				 * If ce is zero, then we're processing
1934 				 * a special character through ttyoutput.
1935 				 */
1936 				if (ce == 0) {
1937 					tp->t_rocount = 0;
1938 					if (ttyoutput(*cp, tp) >= 0) {
1939 						/* No Clists, wait a bit. */
1940 						ttstart(tp);
1941 						if (flag & IO_NDELAY) {
1942 							error = EWOULDBLOCK;
1943 							goto out;
1944 						}
1945 						error = ttysleep(tp, &lbolt,
1946 								 PCATCH,
1947 								 "ttybf1", 0);
1948 						if (error)
1949 							goto out;
1950 						goto loop;
1951 					}
1952 					cp++;
1953 					cc--;
1954 					if (ISSET(tp->t_lflag, FLUSHO) ||
1955 					    tp->t_outq.c_cc > hiwat)
1956 						goto ovhiwat;
1957 					continue;
1958 				}
1959 			}
1960 			/*
1961 			 * A bunch of normal characters have been found.
1962 			 * Transfer them en masse to the output queue and
1963 			 * continue processing at the top of the loop.
1964 			 * If there are any further characters in this
1965 			 * <= OBUFSIZ chunk, the first should be a character
1966 			 * requiring special handling by ttyoutput.
1967 			 */
1968 			tp->t_rocount = 0;
1969 			i = b_to_q(cp, ce, &tp->t_outq);
1970 			ce -= i;
1971 			tp->t_column += ce;
1972 			cp += ce, cc -= ce, tk_nout += ce;
1973 			tp->t_outcc += ce;
1974 			if (i > 0) {
1975 				/* No Clists, wait a bit. */
1976 				ttstart(tp);
1977 				if (flag & IO_NDELAY) {
1978 					error = EWOULDBLOCK;
1979 					goto out;
1980 				}
1981 				error = ttysleep(tp, &lbolt, PCATCH,
1982 						 "ttybf2", 0);
1983 				if (error)
1984 					goto out;
1985 				goto loop;
1986 			}
1987 			if (ISSET(tp->t_lflag, FLUSHO) ||
1988 			    tp->t_outq.c_cc > hiwat)
1989 				break;
1990 		}
1991 		ttstart(tp);
1992 	}
1993 out:
1994 	/*
1995 	 * If cc is nonzero, we leave the uio structure inconsistent, as the
1996 	 * offset and iov pointers have moved forward, but it doesn't matter
1997 	 * (the call will either return short or restart with a new uio).
1998 	 */
1999 	uio->uio_resid += cc;
2000 	return (error);
2001 
2002 ovhiwat:
2003 	ttstart(tp);
2004 	s = spltty();
2005 	/*
2006 	 * This can only occur if FLUSHO is set in t_lflag,
2007 	 * or if ttstart/oproc is synchronous (or very fast).
2008 	 */
2009 	if (tp->t_outq.c_cc <= hiwat) {
2010 		splx(s);
2011 		goto loop;
2012 	}
2013 	if (flag & IO_NDELAY) {
2014 		splx(s);
2015 		uio->uio_resid += cc;
2016 		return (uio->uio_resid == cnt ? EWOULDBLOCK : 0);
2017 	}
2018 	SET(tp->t_state, TS_SO_OLOWAT);
2019 	error = ttysleep(tp, TSA_OLOWAT(tp), PCATCH, "ttywri", tp->t_timeout);
2020 	splx(s);
2021 	if (error == EWOULDBLOCK)
2022 		error = EIO;
2023 	if (error)
2024 		goto out;
2025 	goto loop;
2026 }
2027 
2028 /*
2029  * Rubout one character from the rawq of tp
2030  * as cleanly as possible.
2031  */
2032 static void
2033 ttyrub(c, tp)
2034 	int c;
2035 	struct tty *tp;
2036 {
2037 	char *cp;
2038 	int savecol;
2039 	int tabc, s;
2040 
2041 	if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
2042 		return;
2043 	CLR(tp->t_lflag, FLUSHO);
2044 	if (ISSET(tp->t_lflag, ECHOE)) {
2045 		if (tp->t_rocount == 0) {
2046 			/*
2047 			 * Screwed by ttwrite; retype
2048 			 */
2049 			ttyretype(tp);
2050 			return;
2051 		}
2052 		if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
2053 			ttyrubo(tp, 2);
2054 		else {
2055 			CLR(c, ~TTY_CHARMASK);
2056 			switch (CCLASS(c)) {
2057 			case ORDINARY:
2058 				ttyrubo(tp, 1);
2059 				break;
2060 			case BACKSPACE:
2061 			case CONTROL:
2062 			case NEWLINE:
2063 			case RETURN:
2064 			case VTAB:
2065 				if (ISSET(tp->t_lflag, ECHOCTL))
2066 					ttyrubo(tp, 2);
2067 				break;
2068 			case TAB:
2069 				if (tp->t_rocount < tp->t_rawq.c_cc) {
2070 					ttyretype(tp);
2071 					return;
2072 				}
2073 				s = spltty();
2074 				savecol = tp->t_column;
2075 				SET(tp->t_state, TS_CNTTB);
2076 				SET(tp->t_lflag, FLUSHO);
2077 				tp->t_column = tp->t_rocol;
2078 				cp = tp->t_rawq.c_cf;
2079 				if (cp)
2080 					tabc = *cp;	/* XXX FIX NEXTC */
2081 				for (; cp; cp = nextc(&tp->t_rawq, cp, &tabc))
2082 					ttyecho(tabc, tp);
2083 				CLR(tp->t_lflag, FLUSHO);
2084 				CLR(tp->t_state, TS_CNTTB);
2085 				splx(s);
2086 
2087 				/* savecol will now be length of the tab. */
2088 				savecol -= tp->t_column;
2089 				tp->t_column += savecol;
2090 				if (savecol > 8)
2091 					savecol = 8;	/* overflow screw */
2092 				while (--savecol >= 0)
2093 					(void)ttyoutput('\b', tp);
2094 				break;
2095 			default:			/* XXX */
2096 #define	PANICSTR	"ttyrub: would panic c = %d, val = %d\n"
2097 				(void)printf(PANICSTR, c, CCLASS(c));
2098 #ifdef notdef
2099 				panic(PANICSTR, c, CCLASS(c));
2100 #endif
2101 			}
2102 		}
2103 	} else if (ISSET(tp->t_lflag, ECHOPRT)) {
2104 		if (!ISSET(tp->t_state, TS_ERASE)) {
2105 			SET(tp->t_state, TS_ERASE);
2106 			(void)ttyoutput('\\', tp);
2107 		}
2108 		ttyecho(c, tp);
2109 	} else {
2110 		ttyecho(tp->t_cc[VERASE], tp);
2111 		/*
2112 		 * This code may be executed not only when an ERASE key
2113 		 * is pressed, but also when ^U (KILL) or ^W (WERASE) are.
2114 		 * So, I didn't think it was worthwhile to pass the extra
2115 		 * information (which would need an extra parameter,
2116 		 * changing every call) needed to distinguish the ERASE2
2117 		 * case from the ERASE.
2118 		 */
2119 	}
2120 	--tp->t_rocount;
2121 }
2122 
2123 /*
2124  * Back over cnt characters, erasing them.
2125  */
2126 static void
2127 ttyrubo(tp, cnt)
2128 	struct tty *tp;
2129 	int cnt;
2130 {
2131 
2132 	while (cnt-- > 0) {
2133 		(void)ttyoutput('\b', tp);
2134 		(void)ttyoutput(' ', tp);
2135 		(void)ttyoutput('\b', tp);
2136 	}
2137 }
2138 
2139 /*
2140  * ttyretype --
2141  *	Reprint the rawq line.  Note, it is assumed that c_cc has already
2142  *	been checked.
2143  */
2144 static void
2145 ttyretype(tp)
2146 	struct tty *tp;
2147 {
2148 	char *cp;
2149 	int s, c;
2150 
2151 	/* Echo the reprint character. */
2152 	if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
2153 		ttyecho(tp->t_cc[VREPRINT], tp);
2154 
2155 	(void)ttyoutput('\n', tp);
2156 
2157 	/*
2158 	 * XXX
2159 	 * FIX: NEXTC IS BROKEN - DOESN'T CHECK QUOTE
2160 	 * BIT OF FIRST CHAR.
2161 	 */
2162 	s = spltty();
2163 	for (cp = tp->t_canq.c_cf, c = (cp != NULL ? *cp : 0);
2164 	    cp != NULL; cp = nextc(&tp->t_canq, cp, &c))
2165 		ttyecho(c, tp);
2166 	for (cp = tp->t_rawq.c_cf, c = (cp != NULL ? *cp : 0);
2167 	    cp != NULL; cp = nextc(&tp->t_rawq, cp, &c))
2168 		ttyecho(c, tp);
2169 	CLR(tp->t_state, TS_ERASE);
2170 	splx(s);
2171 
2172 	tp->t_rocount = tp->t_rawq.c_cc;
2173 	tp->t_rocol = 0;
2174 }
2175 
2176 /*
2177  * Echo a typed character to the terminal.
2178  */
2179 static void
2180 ttyecho(c, tp)
2181 	int c;
2182 	struct tty *tp;
2183 {
2184 
2185 	if (!ISSET(tp->t_state, TS_CNTTB))
2186 		CLR(tp->t_lflag, FLUSHO);
2187 	if ((!ISSET(tp->t_lflag, ECHO) &&
2188 	     (c != '\n' || !ISSET(tp->t_lflag, ECHONL))) ||
2189 	    ISSET(tp->t_lflag, EXTPROC))
2190 		return;
2191 	if (ISSET(tp->t_lflag, ECHOCTL) &&
2192 	    ((ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n') ||
2193 	    ISSET(c, TTY_CHARMASK) == 0177)) {
2194 		(void)ttyoutput('^', tp);
2195 		CLR(c, ~TTY_CHARMASK);
2196 		if (c == 0177)
2197 			c = '?';
2198 		else
2199 			c += 'A' - 1;
2200 	}
2201 	(void)ttyoutput(c, tp);
2202 }
2203 
2204 /*
2205  * Wake up any readers on a tty.
2206  */
2207 void
2208 ttwakeup(tp)
2209 	struct tty *tp;
2210 {
2211 
2212 	if (tp->t_rsel.si_pid != 0)
2213 		selwakeup(&tp->t_rsel);
2214 	if (ISSET(tp->t_state, TS_ASYNC) && tp->t_sigio != NULL)
2215 		pgsigio(tp->t_sigio, SIGIO, (tp->t_session != NULL));
2216 	wakeup(TSA_HUP_OR_INPUT(tp));
2217 	KNOTE(&tp->t_rsel.si_note, 0);
2218 }
2219 
2220 /*
2221  * Wake up any writers on a tty.
2222  */
2223 void
2224 ttwwakeup(tp)
2225 	struct tty *tp;
2226 {
2227 
2228 	if (tp->t_wsel.si_pid != 0 && tp->t_outq.c_cc <= tp->t_olowat)
2229 		selwakeup(&tp->t_wsel);
2230 	if (ISSET(tp->t_state, TS_ASYNC) && tp->t_sigio != NULL)
2231 		pgsigio(tp->t_sigio, SIGIO, (tp->t_session != NULL));
2232 	if (ISSET(tp->t_state, TS_BUSY | TS_SO_OCOMPLETE) ==
2233 	    TS_SO_OCOMPLETE && tp->t_outq.c_cc == 0) {
2234 		CLR(tp->t_state, TS_SO_OCOMPLETE);
2235 		wakeup(TSA_OCOMPLETE(tp));
2236 	}
2237 	if (ISSET(tp->t_state, TS_SO_OLOWAT) &&
2238 	    tp->t_outq.c_cc <= tp->t_olowat) {
2239 		CLR(tp->t_state, TS_SO_OLOWAT);
2240 		wakeup(TSA_OLOWAT(tp));
2241 	}
2242 	KNOTE(&tp->t_wsel.si_note, 0);
2243 }
2244 
2245 /*
2246  * Look up a code for a specified speed in a conversion table;
2247  * used by drivers to map software speed values to hardware parameters.
2248  */
2249 int
2250 ttspeedtab(speed, table)
2251 	int speed;
2252 	struct speedtab *table;
2253 {
2254 
2255 	for ( ; table->sp_speed != -1; table++)
2256 		if (table->sp_speed == speed)
2257 			return (table->sp_code);
2258 	return (-1);
2259 }
2260 
2261 /*
2262  * Set input and output watermarks and buffer sizes.  For input, the
2263  * high watermark is about one second's worth of input above empty, the
2264  * low watermark is slightly below high water, and the buffer size is a
2265  * driver-dependent amount above high water.  For output, the watermarks
2266  * are near the ends of the buffer, with about 1 second's worth of input
2267  * between them.  All this only applies to the standard line discipline.
2268  */
2269 void
2270 ttsetwater(tp)
2271 	struct tty *tp;
2272 {
2273 	int cps, ttmaxhiwat, x;
2274 
2275 	/* Input. */
2276 	clist_alloc_cblocks(&tp->t_canq, TTYHOG, 512);
2277 	switch (tp->t_ispeedwat) {
2278 	case (speed_t)-1:
2279 		cps = tp->t_ispeed / 10;
2280 		break;
2281 	case 0:
2282 		/*
2283 		 * This case is for old drivers that don't know about
2284 		 * t_ispeedwat.  Arrange for them to get the old buffer
2285 		 * sizes and watermarks.
2286 		 */
2287 		cps = TTYHOG - 2 * 256;
2288 		tp->t_ififosize = 2 * 256;
2289 		break;
2290 	default:
2291 		cps = tp->t_ispeedwat / 10;
2292 		break;
2293 	}
2294 	tp->t_ihiwat = cps;
2295 	tp->t_ilowat = 7 * cps / 8;
2296 	x = cps + tp->t_ififosize;
2297 	clist_alloc_cblocks(&tp->t_rawq, x, x);
2298 
2299 	/* Output. */
2300 	switch (tp->t_ospeedwat) {
2301 	case (speed_t)-1:
2302 		cps = tp->t_ospeed / 10;
2303 		ttmaxhiwat = 2 * TTMAXHIWAT;
2304 		break;
2305 	case 0:
2306 		cps = tp->t_ospeed / 10;
2307 		ttmaxhiwat = TTMAXHIWAT;
2308 		break;
2309 	default:
2310 		cps = tp->t_ospeedwat / 10;
2311 		ttmaxhiwat = 8 * TTMAXHIWAT;
2312 		break;
2313 	}
2314 #define CLAMP(x, h, l)	((x) > h ? h : ((x) < l) ? l : (x))
2315 	tp->t_olowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
2316 	x += cps;
2317 	x = CLAMP(x, ttmaxhiwat, TTMINHIWAT);	/* XXX clamps are too magic */
2318 	tp->t_ohiwat = roundup(x, CBSIZE);	/* XXX for compat */
2319 	x = imax(tp->t_ohiwat, TTMAXHIWAT);	/* XXX for compat/safety */
2320 	x += OBUFSIZ + 100;
2321 	clist_alloc_cblocks(&tp->t_outq, x, x);
2322 #undef	CLAMP
2323 }
2324 
2325 /*
2326  * Report on state of foreground process group.
2327  */
2328 void
2329 ttyinfo(tp)
2330 	struct tty *tp;
2331 {
2332 	struct proc *p, *pick;
2333 	struct timeval utime, stime;
2334 	int tmp;
2335 
2336 	if (ttycheckoutq(tp,0) == 0)
2337 		return;
2338 
2339 	/*
2340 	 * We always print the load average, then figure out what else to
2341 	 * print based on the state of the current process group.
2342 	 */
2343 	tmp = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
2344 	ttyprintf(tp, "load: %d.%02d ", tmp / 100, tmp % 100);
2345 
2346 	if (tp->t_session == NULL) {
2347 		ttyprintf(tp, "not a controlling terminal\n");
2348 	} else if (tp->t_pgrp == NULL) {
2349 		ttyprintf(tp, "no foreground process group\n");
2350 	} else if ((p = LIST_FIRST(&tp->t_pgrp->pg_members)) == 0) {
2351 		ttyprintf(tp, "empty foreground process group\n");
2352 	} else {
2353 		/*
2354 		 * Pick an interesting process.  Note that certain elements,
2355 		 * in particular the wmesg, require a critical section for
2356 		 * safe access (YYY and we are still not MP safe).
2357 		 *
2358 		 * NOTE: p_wmesg is p_thread->td_wmesg, and p_comm is
2359 		 * p_thread->td_comm.
2360 		 */
2361 		char buf[64];
2362 		const char *str;
2363 		int isinmem;
2364 		long vmsz;
2365 		int pctcpu;
2366 
2367 		crit_enter();
2368 
2369 		for (pick = NULL; p != 0; p = LIST_NEXT(p, p_pglist)) {
2370 			if (proc_compare(pick, p))
2371 				pick = p;
2372 		}
2373 
2374 		/*
2375 		 * Figure out what wait/process-state message, and command
2376 		 * buffer to present
2377 		 */
2378 		if (pick->p_thread == NULL)
2379 			str = "exiting";
2380 		else if (pick->p_stat == SRUN)
2381 			str = "running";
2382 		else if (pick->p_wmesg)	/* p_thread must not be NULL */
2383 			str = pick->p_wmesg;
2384 		else
2385 			str = "iowait";
2386 
2387 		snprintf(buf, sizeof(buf), "cmd: %s %d [%s]",
2388 			(pick->p_thread ? pick->p_comm : "?"),
2389 			pick->p_pid, str);
2390 
2391 		/*
2392 		 * Calculate cpu usage, percent cpu, and cmsz.  Note that
2393 		 * 'pick' becomes invalid the moment we exit the critical
2394 		 * section.
2395 		 */
2396 		if (pick->p_thread && (pick->p_flag & P_INMEM)) {
2397 			calcru(pick, &utime, &stime, NULL);
2398 			isinmem = 1;
2399 		} else {
2400 			isinmem = 0;
2401 		}
2402 
2403 		pctcpu = (pick->p_pctcpu * 10000 + FSCALE / 2) >> FSHIFT;
2404 
2405 		if (pick->p_stat == SIDL || pick->p_stat == SZOMB)
2406 		    vmsz = 0;
2407 		else
2408 		    vmsz = pgtok(vmspace_resident_count(pick->p_vmspace));
2409 
2410 		crit_exit();
2411 
2412 		/*
2413 		 * Dump the output
2414 		 */
2415 		ttyprintf(tp, " %s ", buf);
2416 		if (isinmem) {
2417 			ttyprintf(tp, "%ld.%02ldu ",
2418 				utime.tv_sec, utime.tv_usec / 10000);
2419 			ttyprintf(tp, "%ld.%02lds ",
2420 				stime.tv_sec, stime.tv_usec / 10000);
2421 		} else {
2422 			ttyprintf(tp, "?.??u ?.??s ");
2423 		}
2424 		ttyprintf(tp, "%d%% %ldk\n", pctcpu / 100, vmsz);
2425 	}
2426 	tp->t_rocount = 0;	/* so pending input will be retyped if BS */
2427 }
2428 
2429 /*
2430  * Returns 1 if p2 is "better" than p1
2431  *
2432  * The algorithm for picking the "interesting" process is thus:
2433  *
2434  *	1) Only foreground processes are eligible - implied.
2435  *	2) Runnable processes are favored over anything else.  The runner
2436  *	   with the highest cpu utilization is picked (p_estcpu).  Ties are
2437  *	   broken by picking the highest pid.
2438  *	3) The sleeper with the shortest sleep time is next.  With ties,
2439  *	   we pick out just "short-term" sleepers (P_SINTR == 0).
2440  *	4) Further ties are broken by picking the highest pid.
2441  */
2442 #define ISRUN(p)	(((p)->p_stat == SRUN) || ((p)->p_stat == SIDL))
2443 #define TESTAB(a, b)    ((a)<<1 | (b))
2444 #define ONLYA   2
2445 #define ONLYB   1
2446 #define BOTH    3
2447 
2448 static int
2449 proc_compare(p1, p2)
2450 	struct proc *p1, *p2;
2451 {
2452 
2453 	if (p1 == NULL)
2454 		return (1);
2455 	/*
2456 	 * see if at least one of them is runnable
2457 	 */
2458 	switch (TESTAB(ISRUN(p1), ISRUN(p2))) {
2459 	case ONLYA:
2460 		return (0);
2461 	case ONLYB:
2462 		return (1);
2463 	case BOTH:
2464 		/*
2465 		 * tie - favor one with highest recent cpu utilization
2466 		 */
2467 		if (p2->p_estcpu > p1->p_estcpu)
2468 			return (1);
2469 		if (p1->p_estcpu > p2->p_estcpu)
2470 			return (0);
2471 		return (p2->p_pid > p1->p_pid);	/* tie - return highest pid */
2472 	}
2473 	/*
2474  	 * weed out zombies
2475 	 */
2476 	switch (TESTAB(p1->p_stat == SZOMB, p2->p_stat == SZOMB)) {
2477 	case ONLYA:
2478 		return (1);
2479 	case ONLYB:
2480 		return (0);
2481 	case BOTH:
2482 		return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
2483 	}
2484 	/*
2485 	 * pick the one with the smallest sleep time
2486 	 */
2487 	if (p2->p_slptime > p1->p_slptime)
2488 		return (0);
2489 	if (p1->p_slptime > p2->p_slptime)
2490 		return (1);
2491 	/*
2492 	 * favor one sleeping in a non-interruptible sleep
2493 	 */
2494 	if (p1->p_flag & P_SINTR && (p2->p_flag & P_SINTR) == 0)
2495 		return (1);
2496 	if (p2->p_flag & P_SINTR && (p1->p_flag & P_SINTR) == 0)
2497 		return (0);
2498 	return (p2->p_pid > p1->p_pid);		/* tie - return highest pid */
2499 }
2500 
2501 /*
2502  * Output char to tty; console putchar style.
2503  */
2504 int
2505 tputchar(c, tp)
2506 	int c;
2507 	struct tty *tp;
2508 {
2509 	int s;
2510 
2511 	s = spltty();
2512 	if (!ISSET(tp->t_state, TS_CONNECTED)) {
2513 		splx(s);
2514 		return (-1);
2515 	}
2516 	if (c == '\n')
2517 		(void)ttyoutput('\r', tp);
2518 	(void)ttyoutput(c, tp);
2519 	ttstart(tp);
2520 	splx(s);
2521 	return (0);
2522 }
2523 
2524 /*
2525  * Sleep on chan, returning ERESTART if tty changed while we napped and
2526  * returning any errors (e.g. EINTR/EWOULDBLOCK) reported by tsleep.  If
2527  * the tty is revoked, restarting a pending call will redo validation done
2528  * at the start of the call.
2529  */
2530 int
2531 ttysleep(tp, chan, slpflags, wmesg, timo)
2532 	struct tty *tp;
2533 	void *chan;
2534 	int slpflags, timo;
2535 	char *wmesg;
2536 {
2537 	int error;
2538 	int gen;
2539 
2540 	gen = tp->t_gen;
2541 	error = tsleep(chan, slpflags, wmesg, timo);
2542 	if (error)
2543 		return (error);
2544 	return (tp->t_gen == gen ? 0 : ERESTART);
2545 }
2546 
2547 /*
2548  * Allocate a tty struct.  Clists in the struct will be allocated by
2549  * ttyopen().
2550  */
2551 struct tty *
2552 ttymalloc(tp)
2553 	struct tty *tp;
2554 {
2555 
2556 	if (tp)
2557 		return(tp);
2558         tp = malloc(sizeof *tp, M_TTYS, M_WAITOK|M_ZERO);
2559 	ttyregister(tp);
2560         return (tp);
2561 }
2562 
2563 #if 0
2564 /*
2565  * Free a tty struct.  Clists in the struct should have been freed by
2566  * ttyclose().
2567  *
2568  * XXX not yet usable: since we support a half-closed state and do not
2569  * ref count the tty reference from the session, it is possible for a
2570  * session to hold a ref on the tty.  See TTY_DO_FULL_CLOSE.
2571  */
2572 void
2573 ttyfree(tp)
2574 	struct tty *tp;
2575 {
2576         free(tp, M_TTYS);
2577 }
2578 #endif /* 0 */
2579 
2580 void
2581 ttyregister(tp)
2582 	struct tty *tp;
2583 {
2584 	SLIST_INSERT_HEAD(&tty_list, tp, t_list);
2585 }
2586 
2587 static int
2588 sysctl_kern_ttys(SYSCTL_HANDLER_ARGS)
2589 {
2590 	int error;
2591 	struct tty *tp, t;
2592 	SLIST_FOREACH(tp, &tty_list, t_list) {
2593 		t = *tp;
2594 		if (t.t_dev)
2595 			t.t_dev = (dev_t)dev2udev(t.t_dev);
2596 		error = SYSCTL_OUT(req, (caddr_t)&t, sizeof(t));
2597 		if (error)
2598 			return (error);
2599 	}
2600 	return (0);
2601 }
2602 
2603 SYSCTL_PROC(_kern, OID_AUTO, ttys, CTLTYPE_OPAQUE|CTLFLAG_RD,
2604 	0, 0, sysctl_kern_ttys, "S,tty", "All struct ttys");
2605 
2606 void
2607 nottystop(tp, rw)
2608 	struct tty *tp;
2609 	int rw;
2610 {
2611 
2612 	return;
2613 }
2614 
2615 int
2616 ttyread(dev, uio, flag)
2617 	dev_t dev;
2618 	struct uio *uio;
2619 	int flag;
2620 {
2621 	struct tty *tp;
2622 
2623 	tp = dev->si_tty;
2624 	if (tp == NULL)
2625 		return (ENODEV);
2626 	return ((*linesw[tp->t_line].l_read)(tp, uio, flag));
2627 }
2628 
2629 int
2630 ttywrite(dev, uio, flag)
2631 	dev_t dev;
2632 	struct uio *uio;
2633 	int flag;
2634 {
2635 	struct tty *tp;
2636 
2637 	tp = dev->si_tty;
2638 	if (tp == NULL)
2639 		return (ENODEV);
2640 	return ((*linesw[tp->t_line].l_write)(tp, uio, flag));
2641 }
2642