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