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