tty.c revision 180801
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 180801 2008-07-25 14:31:00Z ed $");
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/cons.h>
82#include <sys/filio.h>
83#include <sys/lock.h>
84#include <sys/mutex.h>
85#include <sys/namei.h>
86#include <sys/sx.h>
87#if defined(COMPAT_43TTY)
88#include <sys/ioctl_compat.h>
89#endif
90#include <sys/priv.h>
91#include <sys/proc.h>
92#define	TTYDEFCHARS
93#include <sys/tty.h>
94#undef	TTYDEFCHARS
95#include <sys/fcntl.h>
96#include <sys/conf.h>
97#include <sys/poll.h>
98#include <sys/kernel.h>
99#include <sys/vnode.h>
100#include <sys/serial.h>
101#include <sys/signalvar.h>
102#include <sys/malloc.h>
103#include <sys/filedesc.h>
104#include <sys/sysctl.h>
105#include <sys/timepps.h>
106
107#include <machine/stdarg.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	d_open_t	ttysopen;
117static	d_close_t	ttysclose;
118static	d_read_t	ttysrdwr;
119static	d_ioctl_t	ttysioctl;
120static	d_purge_t	ttypurge;
121
122/* Default cdevsw for common tty devices */
123static struct cdevsw tty_cdevsw = {
124	.d_version =	D_VERSION,
125	.d_open =	ttyopen,
126	.d_close =	ttyclose,
127	.d_ioctl =	ttyioctl,
128	.d_purge =	ttypurge,
129	.d_name =	"ttydrv",
130	.d_flags =	D_TTY | D_NEEDGIANT,
131};
132
133/* Cdevsw for slave tty devices */
134static struct cdevsw ttys_cdevsw = {
135	.d_version =	D_VERSION,
136	.d_open =	ttysopen,
137	.d_close =	ttysclose,
138	.d_read =	ttysrdwr,
139	.d_write =	ttysrdwr,
140	.d_ioctl =	ttysioctl,
141	.d_name =	"TTYS",
142	.d_flags =	D_TTY | D_NEEDGIANT,
143};
144
145static int	ttnread(struct tty *tp);
146static void	ttyecho(int c, struct tty *tp);
147static int	ttyoutput(int c, struct tty *tp);
148static void	ttypend(struct tty *tp);
149static void	ttyretype(struct tty *tp);
150static void	ttyrub(int c, struct tty *tp);
151static void	ttyrubo(struct tty *tp, int cnt);
152static void	ttyunblock(struct tty *tp);
153static int	ttywflush(struct tty *tp);
154static int	filt_ttyread(struct knote *kn, long hint);
155static void	filt_ttyrdetach(struct knote *kn);
156static int	filt_ttywrite(struct knote *kn, long hint);
157static void	filt_ttywdetach(struct knote *kn);
158
159/*
160 * Table with character classes and parity. The 8th bit indicates parity,
161 * the 7th bit indicates the character is an alphameric or underscore (for
162 * ALTWERASE), and the low 6 bits indicate delay type.  If the low 6 bits
163 * are 0 then the character needs no special processing on output; classes
164 * other than 0 might be translated or (not currently) require delays.
165 */
166#define	E	0x00	/* Even parity. */
167#define	O	0x80	/* Odd parity. */
168#define	PARITY(c)	(char_type[c] & O)
169
170#define	ALPHA	0x40	/* Alpha or underscore. */
171#define	ISALPHA(c)	(char_type[(c) & TTY_CHARMASK] & ALPHA)
172
173#define	CCLASSMASK	0x3f
174#define	CCLASS(c)	(char_type[c] & CCLASSMASK)
175
176#define	BS	BACKSPACE
177#define	CC	CONTROL
178#define	CR	RETURN
179#define	NA	ORDINARY | ALPHA
180#define	NL	NEWLINE
181#define	NO	ORDINARY
182#define	TB	TAB
183#define	VT	VTAB
184
185static u_char const char_type[] = {
186	E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC,	/* nul - bel */
187	O|BS, E|TB, E|NL, O|CC, E|VT, O|CR, O|CC, E|CC, /* bs - si */
188	O|CC, E|CC, E|CC, O|CC, E|CC, O|CC, O|CC, E|CC, /* dle - etb */
189	E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC, /* can - us */
190	O|NO, E|NO, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* sp - ' */
191	E|NO, O|NO, O|NO, E|NO, O|NO, E|NO, E|NO, O|NO, /* ( - / */
192	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* 0 - 7 */
193	O|NA, E|NA, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* 8 - ? */
194	O|NO, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* @ - G */
195	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* H - O */
196	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* P - W */
197	O|NA, E|NA, E|NA, O|NO, E|NO, O|NO, O|NO, O|NA, /* X - _ */
198	E|NO, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* ` - g */
199	O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* h - o */
200	O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* p - w */
201	E|NA, O|NA, O|NA, E|NO, O|NO, E|NO, E|NO, O|CC, /* x - del */
202	/*
203	 * Meta chars; should be settable per character set;
204	 * for now, treat them all as normal characters.
205	 */
206	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
207	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
208	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
209	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
210	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
211	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
212	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
213	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
214	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
215	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
216	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
217	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
218	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
219	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
220	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
221	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
222};
223#undef	BS
224#undef	CC
225#undef	CR
226#undef	NA
227#undef	NL
228#undef	NO
229#undef	TB
230#undef	VT
231
232/* Macros to clear/set/test flags. */
233#define	SET(t, f)	(t) |= (f)
234#define	CLR(t, f)	(t) &= ~(f)
235#define	ISSET(t, f)	((t) & (f))
236
237#undef MAX_INPUT		/* XXX wrong in <sys/syslimits.h> */
238#define	MAX_INPUT	TTYHOG	/* XXX limit is usually larger for !ICANON */
239
240/*
241 * list of struct tty where pstat(8) can pick it up with sysctl
242 *
243 * The lock order is to grab the list mutex before the tty mutex.
244 * Together with additions going on the tail of the list, this allows
245 * the sysctl to avoid doing retries.
246 */
247static	TAILQ_HEAD(, tty) tty_list = TAILQ_HEAD_INITIALIZER(tty_list);
248static struct mtx tty_list_mutex;
249MTX_SYSINIT(tty_list, &tty_list_mutex, "ttylist", MTX_DEF);
250
251static struct unrhdr *tty_unit;
252
253static int  drainwait = 5*60;
254SYSCTL_INT(_kern, OID_AUTO, drainwait, CTLFLAG_RW, &drainwait,
255	0, "Output drain timeout in seconds");
256
257static struct tty *
258tty_gettp(struct cdev *dev)
259{
260	struct tty *tp;
261	struct cdevsw *csw;
262
263	csw = dev_refthread(dev);
264	if (csw == NULL)
265		return (NULL);
266	KASSERT(csw->d_flags & D_TTY,
267	    ("non D_TTY (%s) in tty code", devtoname(dev)));
268	tp = dev->si_tty;
269	dev_relthread(dev);
270	KASSERT(tp != NULL,
271	    ("no tty pointer on (%s) in tty code", devtoname(dev)));
272	return (tp);
273}
274
275/*
276 * Initial open of tty, or (re)entry to standard tty line discipline.
277 */
278int
279tty_open(struct cdev *device, struct tty *tp)
280{
281	int s;
282
283	s = spltty();
284	tp->t_dev = device;
285	tp->t_hotchar = 0;
286	if (!ISSET(tp->t_state, TS_ISOPEN)) {
287		ttyref(tp);
288		SET(tp->t_state, TS_ISOPEN);
289		if (ISSET(tp->t_cflag, CLOCAL))
290			SET(tp->t_state, TS_CONNECTED);
291		bzero(&tp->t_winsize, sizeof(tp->t_winsize));
292	}
293	/* XXX don't hang forever on output */
294	if (tp->t_timeout < 0)
295		tp->t_timeout = drainwait*hz;
296	ttsetwater(tp);
297	splx(s);
298	return (0);
299}
300
301/*
302 * Handle close() on a tty line: flush and set to initial state,
303 * bumping generation number so that pending read/write calls
304 * can detect recycling of the tty.
305 * XXX our caller should have done `spltty(); l_close(); tty_close();'
306 * and l_close() should have flushed, but we repeat the spltty() and
307 * the flush in case there are buggy callers.
308 */
309int
310tty_close(struct tty *tp)
311{
312	int ostate, s;
313
314	funsetown(&tp->t_sigio);
315	s = spltty();
316	if (constty == tp)
317		constty_clear();
318
319	ttyflush(tp, FREAD | FWRITE);
320	clist_free_cblocks(&tp->t_canq);
321	clist_free_cblocks(&tp->t_outq);
322	clist_free_cblocks(&tp->t_rawq);
323
324	tp->t_gen++;
325	tp->t_line = TTYDISC;
326	tp->t_hotchar = 0;
327	tp->t_pgrp = NULL;
328	tp->t_session = NULL;
329	ostate = tp->t_state;
330	tp->t_state = 0;
331	knlist_clear(&tp->t_rsel.si_note, 0);
332	knlist_clear(&tp->t_wsel.si_note, 0);
333	/*
334	 * Both final close and revocation close might end up calling
335	 * this method.  Only the thread clearing TS_ISOPEN should
336	 * release the reference to the tty.
337	 */
338	if (ISSET(ostate, TS_ISOPEN))
339		ttyrel(tp);
340	splx(s);
341	return (0);
342}
343
344#define	FLUSHQ(q) {							\
345	if ((q)->c_cc)							\
346		ndflush(q, (q)->c_cc);					\
347}
348
349/* Is 'c' a line delimiter ("break" character)? */
350#define	TTBREAKC(c, lflag)							\
351	((c) == '\n' || (((c) == cc[VEOF] ||				\
352	  (c) == cc[VEOL] || ((c) == cc[VEOL2] && lflag & IEXTEN)) &&	\
353	 (c) != _POSIX_VDISABLE))
354
355/*
356 * Process input of a single character received on a tty.
357 */
358int
359ttyinput(int c, struct tty *tp)
360{
361	tcflag_t iflag, lflag;
362	cc_t *cc;
363	int i, err;
364
365	/*
366	 * If input is pending take it first.
367	 */
368	lflag = tp->t_lflag;
369	if (ISSET(lflag, PENDIN))
370		ttypend(tp);
371	/*
372	 * Gather stats.
373	 */
374	if (ISSET(lflag, ICANON)) {
375		++tk_cancc;
376		++tp->t_cancc;
377	} else {
378		++tk_rawcc;
379		++tp->t_rawcc;
380	}
381	++tk_nin;
382
383	/*
384	 * Block further input iff:
385	 * current input > threshold AND input is available to user program
386	 * AND input flow control is enabled and not yet invoked.
387	 * The 3 is slop for PARMRK.
388	 */
389	iflag = tp->t_iflag;
390	if (tp->t_rawq.c_cc + tp->t_canq.c_cc > tp->t_ihiwat - 3 &&
391	    (!ISSET(lflag, ICANON) || tp->t_canq.c_cc != 0) &&
392	    (ISSET(tp->t_cflag, CRTS_IFLOW) || ISSET(iflag, IXOFF)) &&
393	    !ISSET(tp->t_state, TS_TBLOCK))
394		ttyblock(tp);
395
396	/* Handle exceptional conditions (break, parity, framing). */
397	cc = tp->t_cc;
398	err = (ISSET(c, TTY_ERRORMASK));
399	if (err) {
400		CLR(c, TTY_ERRORMASK);
401		if (ISSET(err, TTY_BI)) {
402			if (ISSET(iflag, IGNBRK))
403				return (0);
404			if (ISSET(iflag, BRKINT)) {
405				ttyflush(tp, FREAD | FWRITE);
406				if (tp->t_pgrp != NULL) {
407					PGRP_LOCK(tp->t_pgrp);
408					pgsignal(tp->t_pgrp, SIGINT, 1);
409					PGRP_UNLOCK(tp->t_pgrp);
410				}
411				goto endcase;
412			}
413			if (ISSET(iflag, PARMRK))
414				goto parmrk;
415		} else if ((ISSET(err, TTY_PE) && ISSET(iflag, INPCK))
416			|| ISSET(err, TTY_FE)) {
417			if (ISSET(iflag, IGNPAR))
418				return (0);
419			else if (ISSET(iflag, PARMRK)) {
420parmrk:
421				if (tp->t_rawq.c_cc + tp->t_canq.c_cc >
422				    MAX_INPUT - 3)
423					goto input_overflow;
424				(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
425				(void)putc(0 | TTY_QUOTE, &tp->t_rawq);
426				(void)putc(c | TTY_QUOTE, &tp->t_rawq);
427				goto endcase;
428			} else
429				c = 0;
430		}
431	}
432
433	if (!ISSET(tp->t_state, TS_TYPEN) && ISSET(iflag, ISTRIP))
434		CLR(c, 0x80);
435	if (!ISSET(lflag, EXTPROC)) {
436		/*
437		 * Check for literal nexting very first
438		 */
439		if (ISSET(tp->t_state, TS_LNCH)) {
440			SET(c, TTY_QUOTE);
441			CLR(tp->t_state, TS_LNCH);
442		}
443		/*
444		 * Scan for special characters.  This code
445		 * is really just a big case statement with
446		 * non-constant cases.  The bottom of the
447		 * case statement is labeled ``endcase'', so goto
448		 * it after a case match, or similar.
449		 */
450
451		/*
452		 * Control chars which aren't controlled
453		 * by ICANON, ISIG, or IXON.
454		 */
455		if (ISSET(lflag, IEXTEN)) {
456			if (CCEQ(cc[VLNEXT], c)) {
457				if (ISSET(lflag, ECHO)) {
458					if (ISSET(lflag, ECHOE)) {
459						(void)ttyoutput('^', tp);
460						(void)ttyoutput('\b', tp);
461					} else
462						ttyecho(c, tp);
463				}
464				SET(tp->t_state, TS_LNCH);
465				goto endcase;
466			}
467			if (CCEQ(cc[VDISCARD], c)) {
468				if (ISSET(lflag, FLUSHO))
469					CLR(tp->t_lflag, FLUSHO);
470				else {
471					ttyflush(tp, FWRITE);
472					ttyecho(c, tp);
473					if (tp->t_rawq.c_cc + tp->t_canq.c_cc)
474						ttyretype(tp);
475					SET(tp->t_lflag, FLUSHO);
476				}
477				goto startoutput;
478			}
479		}
480		/*
481		 * Signals.
482		 */
483		if (ISSET(lflag, ISIG)) {
484			if (CCEQ(cc[VINTR], c) || CCEQ(cc[VQUIT], c)) {
485				if (!ISSET(lflag, NOFLSH))
486					ttyflush(tp, FREAD | FWRITE);
487				ttyecho(c, tp);
488				if (tp->t_pgrp != NULL) {
489					PGRP_LOCK(tp->t_pgrp);
490					pgsignal(tp->t_pgrp,
491					    CCEQ(cc[VINTR], c) ? SIGINT : SIGQUIT, 1);
492					PGRP_UNLOCK(tp->t_pgrp);
493				}
494				goto endcase;
495			}
496			if (CCEQ(cc[VSUSP], c)) {
497				if (!ISSET(lflag, NOFLSH))
498					ttyflush(tp, FREAD);
499				ttyecho(c, tp);
500				if (tp->t_pgrp != NULL) {
501					PGRP_LOCK(tp->t_pgrp);
502					pgsignal(tp->t_pgrp, SIGTSTP, 1);
503					PGRP_UNLOCK(tp->t_pgrp);
504				}
505				goto endcase;
506			}
507		}
508		/*
509		 * Handle start/stop characters.
510		 */
511		if (ISSET(iflag, IXON)) {
512			if (CCEQ(cc[VSTOP], c)) {
513				if (!ISSET(tp->t_state, TS_TTSTOP)) {
514					SET(tp->t_state, TS_TTSTOP);
515					tt_stop(tp, 0);
516					return (0);
517				}
518				if (!CCEQ(cc[VSTART], c))
519					return (0);
520				/*
521				 * if VSTART == VSTOP then toggle
522				 */
523				goto endcase;
524			}
525			if (CCEQ(cc[VSTART], c))
526				goto restartoutput;
527		}
528		/*
529		 * IGNCR, ICRNL, & INLCR
530		 */
531		if (c == '\r') {
532			if (ISSET(iflag, IGNCR))
533				return (0);
534			else if (ISSET(iflag, ICRNL))
535				c = '\n';
536		} else if (c == '\n' && ISSET(iflag, INLCR))
537			c = '\r';
538	}
539	if (!ISSET(tp->t_lflag, EXTPROC) && ISSET(lflag, ICANON)) {
540		/*
541		 * From here on down canonical mode character
542		 * processing takes place.
543		 */
544		/*
545		 * erase or erase2 (^H / ^?)
546		 */
547		if (CCEQ(cc[VERASE], c) || CCEQ(cc[VERASE2], c) ) {
548			if (tp->t_rawq.c_cc)
549				ttyrub(unputc(&tp->t_rawq), tp);
550			goto endcase;
551		}
552		/*
553		 * kill (^U)
554		 */
555		if (CCEQ(cc[VKILL], c)) {
556			if (ISSET(lflag, ECHOKE) &&
557			    tp->t_rawq.c_cc == tp->t_rocount &&
558			    !ISSET(lflag, ECHOPRT))
559				while (tp->t_rawq.c_cc)
560					ttyrub(unputc(&tp->t_rawq), tp);
561			else {
562				ttyecho(c, tp);
563				if (ISSET(lflag, ECHOK) ||
564				    ISSET(lflag, ECHOKE))
565					ttyecho('\n', tp);
566				FLUSHQ(&tp->t_rawq);
567				tp->t_rocount = 0;
568			}
569			CLR(tp->t_state, TS_LOCAL);
570			goto endcase;
571		}
572		/*
573		 * word erase (^W)
574		 */
575		if (CCEQ(cc[VWERASE], c) && ISSET(lflag, IEXTEN)) {
576			int ctype;
577
578			/*
579			 * erase whitespace
580			 */
581			while ((c = unputc(&tp->t_rawq)) == ' ' || c == '\t')
582				ttyrub(c, tp);
583			if (c == -1)
584				goto endcase;
585			/*
586			 * erase last char of word and remember the
587			 * next chars type (for ALTWERASE)
588			 */
589			ttyrub(c, tp);
590			c = unputc(&tp->t_rawq);
591			if (c == -1)
592				goto endcase;
593			if (c == ' ' || c == '\t') {
594				(void)putc(c, &tp->t_rawq);
595				goto endcase;
596			}
597			ctype = ISALPHA(c);
598			/*
599			 * erase rest of word
600			 */
601			do {
602				ttyrub(c, tp);
603				c = unputc(&tp->t_rawq);
604				if (c == -1)
605					goto endcase;
606			} while (c != ' ' && c != '\t' &&
607			    (!ISSET(lflag, ALTWERASE) || ISALPHA(c) == ctype));
608			(void)putc(c, &tp->t_rawq);
609			goto endcase;
610		}
611		/*
612		 * reprint line (^R)
613		 */
614		if (CCEQ(cc[VREPRINT], c) && ISSET(lflag, IEXTEN)) {
615			ttyretype(tp);
616			goto endcase;
617		}
618		/*
619		 * ^T - kernel info and generate SIGINFO
620		 */
621		if (CCEQ(cc[VSTATUS], c) && ISSET(lflag, IEXTEN)) {
622			if (ISSET(lflag, ISIG) && tp->t_pgrp != NULL) {
623				PGRP_LOCK(tp->t_pgrp);
624				pgsignal(tp->t_pgrp, SIGINFO, 1);
625				PGRP_UNLOCK(tp->t_pgrp);
626			}
627			if (!ISSET(lflag, NOKERNINFO))
628				ttyinfo(tp);
629			goto endcase;
630		}
631	}
632	/*
633	 * Check for input buffer overflow
634	 */
635	if (tp->t_rawq.c_cc + tp->t_canq.c_cc >= MAX_INPUT) {
636input_overflow:
637		if (ISSET(iflag, IMAXBEL)) {
638			if (tp->t_outq.c_cc < tp->t_ohiwat)
639				(void)ttyoutput(CTRL('g'), tp);
640		}
641		goto endcase;
642	}
643
644	if (   c == 0377 && ISSET(iflag, PARMRK) && !ISSET(iflag, ISTRIP)
645	     && ISSET(iflag, IGNBRK|IGNPAR) != (IGNBRK|IGNPAR))
646		(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
647
648	/*
649	 * Put data char in q for user and
650	 * wakeup on seeing a line delimiter.
651	 */
652	if (putc(c, &tp->t_rawq) >= 0) {
653		if (!ISSET(lflag, ICANON)) {
654			ttwakeup(tp);
655			ttyecho(c, tp);
656			goto endcase;
657		}
658		if (TTBREAKC(c, lflag)) {
659			tp->t_rocount = 0;
660			catq(&tp->t_rawq, &tp->t_canq);
661			ttwakeup(tp);
662		} else if (tp->t_rocount++ == 0)
663			tp->t_rocol = tp->t_column;
664		if (ISSET(tp->t_state, TS_ERASE)) {
665			/*
666			 * end of prterase \.../
667			 */
668			CLR(tp->t_state, TS_ERASE);
669			(void)ttyoutput('/', tp);
670		}
671		i = tp->t_column;
672		ttyecho(c, tp);
673		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ECHO)) {
674			/*
675			 * Place the cursor over the '^' of the ^D.
676			 */
677			i = imin(2, tp->t_column - i);
678			while (i > 0) {
679				(void)ttyoutput('\b', tp);
680				i--;
681			}
682		}
683	}
684endcase:
685	/*
686	 * IXANY means allow any character to restart output.
687	 */
688	if (ISSET(tp->t_state, TS_TTSTOP) &&
689	    !ISSET(iflag, IXANY) && cc[VSTART] != cc[VSTOP])
690		return (0);
691restartoutput:
692	CLR(tp->t_lflag, FLUSHO);
693	CLR(tp->t_state, TS_TTSTOP);
694startoutput:
695	return (ttstart(tp));
696}
697
698/*
699 * Output a single character on a tty, doing output processing
700 * as needed (expanding tabs, newline processing, etc.).
701 * Returns < 0 if succeeds, otherwise returns char to resend.
702 * Must be recursive.
703 */
704static int
705ttyoutput(int c, struct tty *tp)
706{
707	tcflag_t oflag;
708	int col, s;
709
710	oflag = tp->t_oflag;
711	if (!ISSET(oflag, OPOST)) {
712		if (ISSET(tp->t_lflag, FLUSHO))
713			return (-1);
714		if (putc(c, &tp->t_outq))
715			return (c);
716		tk_nout++;
717		tp->t_outcc++;
718		return (-1);
719	}
720	/*
721	 * Do tab expansion if OXTABS is set.  Special case if we external
722	 * processing, we don't do the tab expansion because we'll probably
723	 * get it wrong.  If tab expansion needs to be done, let it happen
724	 * externally.
725	 */
726	CLR(c, ~TTY_CHARMASK);
727	if (c == '\t' &&
728	    ISSET(oflag, OXTABS) && !ISSET(tp->t_lflag, EXTPROC)) {
729		c = 8 - (tp->t_column & 7);
730		if (!ISSET(tp->t_lflag, FLUSHO)) {
731			s = spltty();		/* Don't interrupt tabs. */
732			c -= b_to_q("        ", c, &tp->t_outq);
733			tk_nout += c;
734			tp->t_outcc += c;
735			splx(s);
736		}
737		tp->t_column += c;
738		return (c ? -1 : '\t');
739	}
740	if (c == CEOT && ISSET(oflag, ONOEOT))
741		return (-1);
742
743	/*
744	 * Newline translation: if ONLCR is set,
745	 * translate newline into "\r\n".
746	 */
747	if (c == '\n' && ISSET(tp->t_oflag, ONLCR)) {
748		tk_nout++;
749		tp->t_outcc++;
750		if (!ISSET(tp->t_lflag, FLUSHO) && putc('\r', &tp->t_outq))
751			return (c);
752	}
753	/* If OCRNL is set, translate "\r" into "\n". */
754	else if (c == '\r' && ISSET(tp->t_oflag, OCRNL))
755		c = '\n';
756	/* If ONOCR is set, don't transmit CRs when on column 0. */
757	else if (c == '\r' && ISSET(tp->t_oflag, ONOCR) && tp->t_column == 0)
758		return (-1);
759
760	tk_nout++;
761	tp->t_outcc++;
762	if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
763		return (c);
764
765	col = tp->t_column;
766	switch (CCLASS(c)) {
767	case BACKSPACE:
768		if (col > 0)
769			--col;
770		break;
771	case CONTROL:
772		break;
773	case NEWLINE:
774		if (ISSET(tp->t_oflag, ONLCR | ONLRET))
775			col = 0;
776		break;
777	case RETURN:
778		col = 0;
779		break;
780	case ORDINARY:
781		++col;
782		break;
783	case TAB:
784		col = (col + 8) & ~7;
785		break;
786	}
787	tp->t_column = col;
788	return (-1);
789}
790
791/*
792 * Ioctls for all tty devices.  Called after line-discipline specific ioctl
793 * has been called to do discipline-specific functions and/or reject any
794 * of these ioctl commands.
795 */
796/* ARGSUSED */
797int
798ttioctl(struct tty *tp, u_long cmd, void *data, int flag)
799{
800	struct proc *p;
801	struct thread *td;
802	struct pgrp *pgrp;
803	int s, error, bits, sig, sig2;
804
805	td = curthread;			/* XXX */
806	p = td->td_proc;
807
808	/* If the ioctl involves modification, hang if in the background. */
809	switch (cmd) {
810	case  TIOCCBRK:
811	case  TIOCCONS:
812	case  TIOCDRAIN:
813	case  TIOCEXCL:
814	case  TIOCFLUSH:
815#ifdef TIOCHPCL
816	case  TIOCHPCL:
817#endif
818	case  TIOCNXCL:
819	case  TIOCSBRK:
820	case  TIOCSCTTY:
821	case  TIOCSDRAINWAIT:
822	case  TIOCSETA:
823	case  TIOCSETAF:
824	case  TIOCSETAW:
825	case  TIOCSETD:
826	case  TIOCSPGRP:
827	case  TIOCSTART:
828	case  TIOCSTAT:
829	case  TIOCSTI:
830	case  TIOCSTOP:
831	case  TIOCSWINSZ:
832#if defined(COMPAT_43TTY)
833	case  TIOCLBIC:
834	case  TIOCLBIS:
835	case  TIOCLSET:
836	case  TIOCSETC:
837	case OTIOCSETD:
838	case  TIOCSETN:
839	case  TIOCSETP:
840	case  TIOCSLTC:
841#endif
842		sx_slock(&proctree_lock);
843		PROC_LOCK(p);
844		while (isbackground(p, tp) && !(p->p_flag & P_PPWAIT) &&
845		    !SIGISMEMBER(p->p_sigacts->ps_sigignore, SIGTTOU) &&
846		    !SIGISMEMBER(td->td_sigmask, SIGTTOU)) {
847			pgrp = p->p_pgrp;
848			PROC_UNLOCK(p);
849			if (pgrp->pg_jobc == 0) {
850				sx_sunlock(&proctree_lock);
851				return (EIO);
852			}
853			PGRP_LOCK(pgrp);
854			sx_sunlock(&proctree_lock);
855			pgsignal(pgrp, SIGTTOU, 1);
856			PGRP_UNLOCK(pgrp);
857			error = ttysleep(tp, &lbolt, TTOPRI | PCATCH, "ttybg1",
858					 0);
859			if (error)
860				return (error);
861			sx_slock(&proctree_lock);
862			PROC_LOCK(p);
863		}
864		PROC_UNLOCK(p);
865		sx_sunlock(&proctree_lock);
866		break;
867	}
868
869
870	if (tp->t_modem != NULL) {
871		switch (cmd) {
872		case TIOCSDTR:
873			tt_modem(tp, SER_DTR, 0);
874			return (0);
875		case TIOCCDTR:
876			tt_modem(tp, 0, SER_DTR);
877			return (0);
878		case TIOCMSET:
879			bits = *(int *)data;
880			sig = (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1;
881			sig2 = ((~bits) & (TIOCM_DTR | TIOCM_RTS)) >> 1;
882			tt_modem(tp, sig, sig2);
883			return (0);
884		case TIOCMBIS:
885			bits = *(int *)data;
886			sig = (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1;
887			tt_modem(tp, sig, 0);
888			return (0);
889		case TIOCMBIC:
890			bits = *(int *)data;
891			sig = (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1;
892			tt_modem(tp, 0, sig);
893			return (0);
894		case TIOCMGET:
895			sig = tt_modem(tp, 0, 0);
896			/* See <sys/serial.h. for the "<< 1" stuff */
897			bits = TIOCM_LE + (sig << 1);
898			*(int *)data = bits;
899			return (0);
900		default:
901			break;
902		}
903	}
904
905	if (tp->t_pps != NULL) {
906		error = pps_ioctl(cmd, data, tp->t_pps);
907		if (error != ENOIOCTL)
908			return (error);
909	}
910
911	switch (cmd) {			/* Process the ioctl. */
912	case FIOASYNC:			/* set/clear async i/o */
913		s = spltty();
914		if (*(int *)data)
915			SET(tp->t_state, TS_ASYNC);
916		else
917			CLR(tp->t_state, TS_ASYNC);
918		splx(s);
919		break;
920	case FIONBIO:			/* set/clear non-blocking i/o */
921		break;			/* XXX: delete. */
922	case FIONREAD:			/* get # bytes to read */
923		s = spltty();
924		*(int *)data = ttnread(tp);
925		splx(s);
926		break;
927
928	case FIOSETOWN:
929		/*
930		 * Policy -- Don't allow FIOSETOWN on someone else's
931		 *           controlling tty
932		 */
933		if (tp->t_session != NULL && !isctty(p, tp))
934			return (ENOTTY);
935
936		error = fsetown(*(int *)data, &tp->t_sigio);
937		if (error)
938			return (error);
939		break;
940	case FIOGETOWN:
941		if (tp->t_session != NULL && !isctty(p, tp))
942			return (ENOTTY);
943		*(int *)data = fgetown(&tp->t_sigio);
944		break;
945
946	case TIOCEXCL:			/* set exclusive use of tty */
947		s = spltty();
948		SET(tp->t_state, TS_XCLUDE);
949		splx(s);
950		break;
951	case TIOCFLUSH: {		/* flush buffers */
952		int flags = *(int *)data;
953
954		if (flags == 0)
955			flags = FREAD | FWRITE;
956		else
957			flags &= FREAD | FWRITE;
958		ttyflush(tp, flags);
959		break;
960	}
961	case TIOCCONS:			/* become virtual console */
962		if (*(int *)data) {
963			struct nameidata nid;
964
965			if (constty && constty != tp &&
966			    ISSET(constty->t_state, TS_CONNECTED))
967				return (EBUSY);
968
969			/* Ensure user can open the real console. */
970			NDINIT(&nid, LOOKUP, LOCKLEAF | FOLLOW, UIO_SYSSPACE,
971			    "/dev/console", td);
972			if ((error = namei(&nid)) != 0)
973				return (error);
974			NDFREE(&nid, NDF_ONLY_PNBUF);
975			error = VOP_ACCESS(nid.ni_vp, VREAD, td->td_ucred, td);
976			vput(nid.ni_vp);
977			if (error)
978				return (error);
979
980			constty_set(tp);
981		} else if (tp == constty)
982			constty_clear();
983		break;
984	case TIOCDRAIN:			/* wait till output drained */
985		error = ttywait(tp);
986		if (error)
987			return (error);
988		break;
989	case TIOCGETA: {		/* get termios struct */
990		struct termios *t = (struct termios *)data;
991
992		bcopy(&tp->t_termios, t, sizeof(struct termios));
993		break;
994	}
995	case TIOCGETD:			/* get line discipline */
996		*(int *)data = tp->t_line;
997		break;
998	case TIOCGWINSZ:		/* get window size */
999		*(struct winsize *)data = tp->t_winsize;
1000		break;
1001	case TIOCGPGRP:			/* get pgrp of tty */
1002		if (!isctty(p, tp))
1003			return (ENOTTY);
1004		*(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
1005		break;
1006	case TIOCGSID:                  /* get sid of tty */
1007		if (!isctty(p, tp))
1008			return (ENOTTY);
1009		*(int *)data = tp->t_session->s_sid;
1010		break;
1011#ifdef TIOCHPCL
1012	case TIOCHPCL:			/* hang up on last close */
1013		s = spltty();
1014		SET(tp->t_cflag, HUPCL);
1015		splx(s);
1016		break;
1017#endif
1018	case TIOCMGDTRWAIT:
1019		*(int *)data = tp->t_dtr_wait * 100 / hz;
1020		break;
1021	case TIOCMSDTRWAIT:
1022		/* must be root since the wait applies to following logins */
1023		error = priv_check(td, PRIV_TTY_DTRWAIT);
1024		if (error)
1025			return (error);
1026		tp->t_dtr_wait = *(int *)data * hz / 100;
1027		break;
1028	case TIOCNXCL:			/* reset exclusive use of tty */
1029		s = spltty();
1030		CLR(tp->t_state, TS_XCLUDE);
1031		splx(s);
1032		break;
1033	case TIOCOUTQ:			/* output queue size */
1034		*(int *)data = tp->t_outq.c_cc;
1035		break;
1036	case TIOCSETA:			/* set termios struct */
1037	case TIOCSETAW:			/* drain output, set */
1038	case TIOCSETAF: {		/* drn out, fls in, set */
1039		struct termios *t = (struct termios *)data;
1040
1041		if (t->c_ispeed == 0)
1042			t->c_ispeed = t->c_ospeed;
1043		if (t->c_ispeed == 0)
1044			t->c_ispeed = tp->t_ospeed;
1045		if (t->c_ispeed == 0)
1046			return (EINVAL);
1047		s = spltty();
1048		if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
1049			error = ttywait(tp);
1050			if (error) {
1051				splx(s);
1052				return (error);
1053			}
1054			if (cmd == TIOCSETAF)
1055				ttyflush(tp, FREAD);
1056		}
1057		if (!ISSET(t->c_cflag, CIGNORE)) {
1058			/*
1059			 * Set device hardware.
1060			 */
1061			error = tt_param(tp, t);
1062			if (error) {
1063				splx(s);
1064				return (error);
1065			}
1066			if (ISSET(t->c_cflag, CLOCAL) &&
1067			    !ISSET(tp->t_cflag, CLOCAL)) {
1068				/*
1069				 * XXX disconnections would be too hard to
1070				 * get rid of without this kludge.  The only
1071				 * way to get rid of controlling terminals
1072				 * is to exit from the session leader.
1073				 */
1074				CLR(tp->t_state, TS_ZOMBIE);
1075
1076				wakeup(TSA_CARR_ON(tp));
1077				ttwakeup(tp);
1078				ttwwakeup(tp);
1079			}
1080			if ((ISSET(tp->t_state, TS_CARR_ON) ||
1081			     ISSET(t->c_cflag, CLOCAL)) &&
1082			    !ISSET(tp->t_state, TS_ZOMBIE))
1083				SET(tp->t_state, TS_CONNECTED);
1084			else
1085				CLR(tp->t_state, TS_CONNECTED);
1086			tp->t_cflag = t->c_cflag;
1087			tp->t_ispeed = t->c_ispeed;
1088			if (t->c_ospeed != 0)
1089				tp->t_ospeed = t->c_ospeed;
1090			ttsetwater(tp);
1091		}
1092		if (ISSET(t->c_lflag, ICANON) != ISSET(tp->t_lflag, ICANON) &&
1093		    cmd != TIOCSETAF) {
1094			if (ISSET(t->c_lflag, ICANON))
1095				SET(tp->t_lflag, PENDIN);
1096			else {
1097				/*
1098				 * XXX we really shouldn't allow toggling
1099				 * ICANON while we're in a non-termios line
1100				 * discipline.  Now we have to worry about
1101				 * panicing for a null queue.
1102				 */
1103				if (tp->t_canq.c_cbreserved > 0 &&
1104				    tp->t_rawq.c_cbreserved > 0) {
1105					catq(&tp->t_rawq, &tp->t_canq);
1106					/*
1107					 * XXX the queue limits may be
1108					 * different, so the old queue
1109					 * swapping method no longer works.
1110					 */
1111					catq(&tp->t_canq, &tp->t_rawq);
1112				}
1113				CLR(tp->t_lflag, PENDIN);
1114			}
1115			ttwakeup(tp);
1116		}
1117		tp->t_iflag = t->c_iflag;
1118		tp->t_oflag = t->c_oflag;
1119		/*
1120		 * Make the EXTPROC bit read only.
1121		 */
1122		if (ISSET(tp->t_lflag, EXTPROC))
1123			SET(t->c_lflag, EXTPROC);
1124		else
1125			CLR(t->c_lflag, EXTPROC);
1126		tp->t_lflag = t->c_lflag | ISSET(tp->t_lflag, PENDIN);
1127		if (t->c_cc[VMIN] != tp->t_cc[VMIN] ||
1128		    t->c_cc[VTIME] != tp->t_cc[VTIME])
1129			ttwakeup(tp);
1130		bcopy(t->c_cc, tp->t_cc, sizeof(t->c_cc));
1131		splx(s);
1132		break;
1133	}
1134	case TIOCSETD: {		/* set line discipline */
1135		int t = *(int *)data;
1136
1137		if ((u_int)t >= nlinesw)
1138			return (ENXIO);
1139		if (t == tp->t_line)
1140			return (0);
1141		s = spltty();
1142		ttyld_close(tp, flag);
1143		tp->t_line = t;
1144		/* XXX: we should use the correct cdev here */
1145		error = ttyld_open(tp, tp->t_dev);
1146		if (error) {
1147			/*
1148			 * If we fail to switch line discipline we cannot
1149			 * fall back to the previous, because we can not
1150			 * trust that ldisc to open successfully either.
1151			 * Fall back to the default ldisc which we know
1152			 * will allways succeed.
1153			 */
1154			tp->t_line = TTYDISC;
1155			(void)ttyld_open(tp, tp->t_dev);
1156		}
1157		splx(s);
1158		return (error);
1159		break;
1160	}
1161	case TIOCSTART:			/* start output, like ^Q */
1162		s = spltty();
1163		if (ISSET(tp->t_state, TS_TTSTOP) ||
1164		    ISSET(tp->t_lflag, FLUSHO)) {
1165			CLR(tp->t_lflag, FLUSHO);
1166			CLR(tp->t_state, TS_TTSTOP);
1167			ttstart(tp);
1168		}
1169		splx(s);
1170		break;
1171	case TIOCSTI:			/* simulate terminal input */
1172		if ((flag & FREAD) == 0 && priv_check(td, PRIV_TTY_STI))
1173			return (EPERM);
1174		if (!isctty(p, tp) && priv_check(td, PRIV_TTY_STI))
1175			return (EACCES);
1176		s = spltty();
1177		ttyld_rint(tp, *(u_char *)data);
1178		splx(s);
1179		break;
1180	case TIOCSTOP:			/* stop output, like ^S */
1181		s = spltty();
1182		if (!ISSET(tp->t_state, TS_TTSTOP)) {
1183			SET(tp->t_state, TS_TTSTOP);
1184			tt_stop(tp, 0);
1185		}
1186		splx(s);
1187		break;
1188	case TIOCSCTTY:			/* become controlling tty */
1189		/* Session ctty vnode pointer set in vnode layer. */
1190		sx_slock(&proctree_lock);
1191		if (!SESS_LEADER(p) ||
1192		    ((p->p_session->s_ttyvp || tp->t_session) &&
1193		     (tp->t_session != p->p_session))) {
1194			sx_sunlock(&proctree_lock);
1195			return (EPERM);
1196		}
1197		tp->t_session = p->p_session;
1198		tp->t_pgrp = p->p_pgrp;
1199		SESS_LOCK(p->p_session);
1200		ttyref(tp);		/* ttyrel(): kern_proc.c:pgdelete() */
1201		p->p_session->s_ttyp = tp;
1202		SESS_UNLOCK(p->p_session);
1203		PROC_LOCK(p);
1204		p->p_flag |= P_CONTROLT;
1205		PROC_UNLOCK(p);
1206		sx_sunlock(&proctree_lock);
1207		break;
1208	case TIOCSPGRP: {		/* set pgrp of tty */
1209		sx_slock(&proctree_lock);
1210		pgrp = pgfind(*(int *)data);
1211		if (!isctty(p, tp)) {
1212			if (pgrp != NULL)
1213				PGRP_UNLOCK(pgrp);
1214			sx_sunlock(&proctree_lock);
1215			return (ENOTTY);
1216		}
1217		if (pgrp == NULL) {
1218			sx_sunlock(&proctree_lock);
1219			return (EPERM);
1220		}
1221		PGRP_UNLOCK(pgrp);
1222		if (pgrp->pg_session != p->p_session) {
1223			sx_sunlock(&proctree_lock);
1224			return (EPERM);
1225		}
1226		sx_sunlock(&proctree_lock);
1227		tp->t_pgrp = pgrp;
1228		break;
1229	}
1230	case TIOCSTAT:			/* simulate control-T */
1231		s = spltty();
1232		ttyinfo(tp);
1233		splx(s);
1234		break;
1235	case TIOCSWINSZ:		/* set window size */
1236		if (bcmp((caddr_t)&tp->t_winsize, data,
1237		    sizeof (struct winsize))) {
1238			tp->t_winsize = *(struct winsize *)data;
1239			if (tp->t_pgrp != NULL) {
1240				PGRP_LOCK(tp->t_pgrp);
1241				pgsignal(tp->t_pgrp, SIGWINCH, 1);
1242				PGRP_UNLOCK(tp->t_pgrp);
1243			}
1244		}
1245		break;
1246	case TIOCSDRAINWAIT:
1247		error = priv_check(td, PRIV_TTY_DRAINWAIT);
1248		if (error)
1249			return (error);
1250		tp->t_timeout = *(int *)data * hz;
1251		wakeup(TSA_OCOMPLETE(tp));
1252		wakeup(TSA_OLOWAT(tp));
1253		break;
1254	case TIOCGDRAINWAIT:
1255		*(int *)data = tp->t_timeout / hz;
1256		break;
1257	case TIOCSBRK:
1258		return (tt_break(tp, 1));
1259	case TIOCCBRK:
1260		return (tt_break(tp, 0));
1261	default:
1262#if defined(COMPAT_43TTY)
1263		return (ttcompat(tp, cmd, data, flag));
1264#else
1265		return (ENOIOCTL);
1266#endif
1267	}
1268	return (0);
1269}
1270
1271int
1272ttypoll(struct cdev *dev, int events, struct thread *td)
1273{
1274	int s;
1275	int revents = 0;
1276	struct tty *tp;
1277
1278	tp = tty_gettp(dev);
1279
1280	if (tp == NULL)	/* XXX used to return ENXIO, but that means true! */
1281		return ((events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM))
1282			| POLLHUP);
1283
1284	s = spltty();
1285	if (events & (POLLIN | POLLRDNORM)) {
1286		if (ISSET(tp->t_state, TS_ZOMBIE))
1287			revents |= (events & (POLLIN | POLLRDNORM)) |
1288			    POLLHUP;
1289		else if (ttnread(tp) > 0)
1290			revents |= events & (POLLIN | POLLRDNORM);
1291		else
1292			selrecord(td, &tp->t_rsel);
1293	}
1294	if (events & POLLOUT) {
1295		if (ISSET(tp->t_state, TS_ZOMBIE))
1296			revents |= POLLHUP;
1297		else if (tp->t_outq.c_cc <= tp->t_olowat &&
1298		    ISSET(tp->t_state, TS_CONNECTED))
1299			revents |= events & POLLOUT;
1300		else
1301			selrecord(td, &tp->t_wsel);
1302	}
1303	splx(s);
1304	return (revents);
1305}
1306
1307static struct filterops ttyread_filtops =
1308	{ 1, NULL, filt_ttyrdetach, filt_ttyread };
1309static struct filterops ttywrite_filtops =
1310	{ 1, NULL, filt_ttywdetach, filt_ttywrite };
1311
1312int
1313ttykqfilter(struct cdev *dev, struct knote *kn)
1314{
1315	struct tty *tp;
1316	struct knlist *klist;
1317	int s;
1318
1319	tp = tty_gettp(dev);
1320	if (tp == NULL || (tp->t_state & TS_GONE))
1321		return (ENODEV);
1322
1323	switch (kn->kn_filter) {
1324	case EVFILT_READ:
1325		klist = &tp->t_rsel.si_note;
1326		kn->kn_fop = &ttyread_filtops;
1327		break;
1328	case EVFILT_WRITE:
1329		klist = &tp->t_wsel.si_note;
1330		kn->kn_fop = &ttywrite_filtops;
1331		break;
1332	default:
1333		return (EINVAL);
1334	}
1335
1336	kn->kn_hook = (caddr_t)tp;
1337
1338	s = spltty();
1339	knlist_add(klist, kn, 0);
1340	splx(s);
1341
1342	return (0);
1343}
1344
1345static void
1346filt_ttyrdetach(struct knote *kn)
1347{
1348	struct tty *tp = (struct tty *)kn->kn_hook;
1349	int s = spltty();
1350
1351	knlist_remove(&tp->t_rsel.si_note, kn, 0);
1352	splx(s);
1353}
1354
1355static int
1356filt_ttyread(struct knote *kn, long hint)
1357{
1358	struct tty *tp = (struct tty *)kn->kn_hook;
1359
1360	kn->kn_data = ttnread(tp);
1361	if ((tp->t_state & TS_GONE) || ISSET(tp->t_state, TS_ZOMBIE)) {
1362		kn->kn_flags |= EV_EOF;
1363		return (1);
1364	}
1365	return (kn->kn_data > 0);
1366}
1367
1368static void
1369filt_ttywdetach(struct knote *kn)
1370{
1371	struct tty *tp = (struct tty *)kn->kn_hook;
1372	int s = spltty();
1373
1374	knlist_remove(&tp->t_wsel.si_note, kn, 0);
1375	splx(s);
1376}
1377
1378static int
1379filt_ttywrite(struct knote *kn, long hint)
1380{
1381	struct tty *tp = (struct tty *)kn->kn_hook;
1382
1383	kn->kn_data = tp->t_outq.c_cc;
1384	if ((tp->t_state & TS_GONE) || ISSET(tp->t_state, TS_ZOMBIE))
1385		return (1);
1386	return (kn->kn_data <= tp->t_olowat &&
1387	    ISSET(tp->t_state, TS_CONNECTED));
1388}
1389
1390/*
1391 * Must be called at spltty().
1392 */
1393static int
1394ttnread(struct tty *tp)
1395{
1396	int nread;
1397
1398	if (ISSET(tp->t_lflag, PENDIN))
1399		ttypend(tp);
1400	nread = tp->t_canq.c_cc;
1401	if (!ISSET(tp->t_lflag, ICANON)) {
1402		nread += tp->t_rawq.c_cc;
1403		if (nread < tp->t_cc[VMIN] && tp->t_cc[VTIME] == 0)
1404			nread = 0;
1405	}
1406	return (nread);
1407}
1408
1409/*
1410 * Wait for output to drain.
1411 */
1412int
1413ttywait(struct tty *tp)
1414{
1415	int error, s;
1416
1417	error = 0;
1418	s = spltty();
1419	while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1420	       ISSET(tp->t_state, TS_CONNECTED) && tp->t_oproc) {
1421		tt_oproc(tp);
1422		if ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1423		    ISSET(tp->t_state, TS_CONNECTED)) {
1424			SET(tp->t_state, TS_SO_OCOMPLETE);
1425			error = ttysleep(tp, TSA_OCOMPLETE(tp),
1426					 TTOPRI | PCATCH, "ttywai",
1427					 tp->t_timeout);
1428			if (error) {
1429				if (error == EWOULDBLOCK)
1430					error = EIO;
1431				break;
1432			}
1433		} else
1434			break;
1435	}
1436	if (!error && (tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)))
1437		error = EIO;
1438	splx(s);
1439	return (error);
1440}
1441
1442/*
1443 * Flush if successfully wait.
1444 */
1445static int
1446ttywflush(struct tty *tp)
1447{
1448	int error;
1449
1450	if ((error = ttywait(tp)) == 0)
1451		ttyflush(tp, FREAD);
1452	return (error);
1453}
1454
1455/*
1456 * Flush tty read and/or write queues, notifying anyone waiting.
1457 */
1458void
1459ttyflush(struct tty *tp, int rw)
1460{
1461	int s;
1462
1463	s = spltty();
1464#if 0
1465again:
1466#endif
1467	if (rw & FWRITE) {
1468		FLUSHQ(&tp->t_outq);
1469		CLR(tp->t_state, TS_TTSTOP);
1470	}
1471	tt_stop(tp, rw);
1472	if (rw & FREAD) {
1473		FLUSHQ(&tp->t_canq);
1474		FLUSHQ(&tp->t_rawq);
1475		CLR(tp->t_lflag, PENDIN);
1476		tp->t_rocount = 0;
1477		tp->t_rocol = 0;
1478		CLR(tp->t_state, TS_LOCAL);
1479		ttwakeup(tp);
1480		if (ISSET(tp->t_state, TS_TBLOCK)) {
1481			if (rw & FWRITE)
1482				FLUSHQ(&tp->t_outq);
1483			ttyunblock(tp);
1484
1485			/*
1486			 * Don't let leave any state that might clobber the
1487			 * next line discipline (although we should do more
1488			 * to send the START char).  Not clearing the state
1489			 * may have caused the "putc to a clist with no
1490			 * reserved cblocks" panic/printf.
1491			 */
1492			CLR(tp->t_state, TS_TBLOCK);
1493
1494#if 0 /* forget it, sleeping isn't always safe and we don't know when it is */
1495			if (ISSET(tp->t_iflag, IXOFF)) {
1496				/*
1497				 * XXX wait a bit in the hope that the stop
1498				 * character (if any) will go out.  Waiting
1499				 * isn't good since it allows races.  This
1500				 * will be fixed when the stop character is
1501				 * put in a special queue.  Don't bother with
1502				 * the checks in ttywait() since the timeout
1503				 * will save us.
1504				 */
1505				SET(tp->t_state, TS_SO_OCOMPLETE);
1506				ttysleep(tp, TSA_OCOMPLETE(tp), TTOPRI,
1507					 "ttyfls", hz / 10);
1508				/*
1509				 * Don't try sending the stop character again.
1510				 */
1511				CLR(tp->t_state, TS_TBLOCK);
1512				goto again;
1513			}
1514#endif
1515		}
1516	}
1517	if (rw & FWRITE) {
1518		FLUSHQ(&tp->t_outq);
1519		ttwwakeup(tp);
1520	}
1521	splx(s);
1522}
1523
1524/*
1525 * Copy in the default termios characters.
1526 */
1527void
1528termioschars(struct termios *t)
1529{
1530
1531	bcopy(ttydefchars, t->c_cc, sizeof t->c_cc);
1532}
1533
1534/*
1535 * Old interface.
1536 */
1537void
1538ttychars(struct tty *tp)
1539{
1540
1541	termioschars(&tp->t_termios);
1542}
1543
1544/*
1545 * Handle input high water.  Send stop character for the IXOFF case.  Turn
1546 * on our input flow control bit and propagate the changes to the driver.
1547 * XXX the stop character should be put in a special high priority queue.
1548 */
1549void
1550ttyblock(struct tty *tp)
1551{
1552
1553	SET(tp->t_state, TS_TBLOCK);
1554	if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
1555	    putc(tp->t_cc[VSTOP], &tp->t_outq) != 0)
1556		CLR(tp->t_state, TS_TBLOCK);	/* try again later */
1557	ttstart(tp);
1558}
1559
1560/*
1561 * Handle input low water.  Send start character for the IXOFF case.  Turn
1562 * off our input flow control bit and propagate the changes to the driver.
1563 * XXX the start character should be put in a special high priority queue.
1564 */
1565static void
1566ttyunblock(struct tty *tp)
1567{
1568
1569	CLR(tp->t_state, TS_TBLOCK);
1570	if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTART] != _POSIX_VDISABLE &&
1571	    putc(tp->t_cc[VSTART], &tp->t_outq) != 0)
1572		SET(tp->t_state, TS_TBLOCK);	/* try again later */
1573	ttstart(tp);
1574}
1575
1576#ifdef notyet
1577/* Not used by any current (i386) drivers. */
1578/*
1579 * Restart after an inter-char delay.
1580 */
1581void
1582ttrstrt(void *tp_arg)
1583{
1584	struct tty *tp;
1585	int s;
1586
1587	KASSERT(tp_arg != NULL, ("ttrstrt"));
1588
1589	tp = tp_arg;
1590	s = spltty();
1591
1592	CLR(tp->t_state, TS_TIMEOUT);
1593	ttstart(tp);
1594
1595	splx(s);
1596}
1597#endif
1598
1599int
1600ttstart(struct tty *tp)
1601{
1602
1603	tt_oproc(tp);
1604	return (0);
1605}
1606
1607/*
1608 * "close" a line discipline
1609 */
1610int
1611ttylclose(struct tty *tp, int flag)
1612{
1613
1614	if (flag & FNONBLOCK || ttywflush(tp))
1615		ttyflush(tp, FREAD | FWRITE);
1616	return (0);
1617}
1618
1619/*
1620 * Handle modem control transition on a tty.
1621 * Flag indicates new state of carrier.
1622 * Returns 0 if the line should be turned off, otherwise 1.
1623 */
1624int
1625ttymodem(struct tty *tp, int flag)
1626{
1627
1628	if (ISSET(tp->t_state, TS_CARR_ON) && ISSET(tp->t_cflag, MDMBUF)) {
1629		/*
1630		 * MDMBUF: do flow control according to carrier flag
1631		 * XXX TS_CAR_OFLOW doesn't do anything yet.  TS_TTSTOP
1632		 * works if IXON and IXANY are clear.
1633		 */
1634		if (flag) {
1635			CLR(tp->t_state, TS_CAR_OFLOW);
1636			CLR(tp->t_state, TS_TTSTOP);
1637			ttstart(tp);
1638		} else if (!ISSET(tp->t_state, TS_CAR_OFLOW)) {
1639			SET(tp->t_state, TS_CAR_OFLOW);
1640			SET(tp->t_state, TS_TTSTOP);
1641			tt_stop(tp, 0);
1642		}
1643	} else if (flag == 0) {
1644		/*
1645		 * Lost carrier.
1646		 */
1647		CLR(tp->t_state, TS_CARR_ON);
1648		if (ISSET(tp->t_state, TS_ISOPEN) &&
1649		    !ISSET(tp->t_cflag, CLOCAL)) {
1650			SET(tp->t_state, TS_ZOMBIE);
1651			CLR(tp->t_state, TS_CONNECTED);
1652			if (tp->t_session) {
1653				sx_slock(&proctree_lock);
1654				if (tp->t_session && tp->t_session->s_leader) {
1655					struct proc *p;
1656
1657					p = tp->t_session->s_leader;
1658					PROC_LOCK(p);
1659					psignal(p, SIGHUP);
1660					PROC_UNLOCK(p);
1661				}
1662				sx_sunlock(&proctree_lock);
1663			}
1664			ttyflush(tp, FREAD | FWRITE);
1665			return (0);
1666		}
1667	} else {
1668		/*
1669		 * Carrier now on.
1670		 */
1671		SET(tp->t_state, TS_CARR_ON);
1672		if (!ISSET(tp->t_state, TS_ZOMBIE))
1673			SET(tp->t_state, TS_CONNECTED);
1674		wakeup(TSA_CARR_ON(tp));
1675		ttwakeup(tp);
1676		ttwwakeup(tp);
1677	}
1678	return (1);
1679}
1680
1681/*
1682 * Reinput pending characters after state switch
1683 * call at spltty().
1684 */
1685static void
1686ttypend(struct tty *tp)
1687{
1688	struct clist tq;
1689	int c;
1690
1691	CLR(tp->t_lflag, PENDIN);
1692	SET(tp->t_state, TS_TYPEN);
1693	/*
1694	 * XXX this assumes too much about clist internals.  It may even
1695	 * fail if the cblock slush pool is empty.  We can't allocate more
1696	 * cblocks here because we are called from an interrupt handler
1697	 * and clist_alloc_cblocks() can wait.
1698	 */
1699	tq = tp->t_rawq;
1700	bzero(&tp->t_rawq, sizeof tp->t_rawq);
1701	tp->t_rawq.c_cbmax = tq.c_cbmax;
1702	tp->t_rawq.c_cbreserved = tq.c_cbreserved;
1703	while ((c = getc(&tq)) >= 0)
1704		ttyinput(c, tp);
1705	CLR(tp->t_state, TS_TYPEN);
1706}
1707
1708/*
1709 * Process a read call on a tty device.
1710 */
1711int
1712ttread(struct tty *tp, struct uio *uio, int flag)
1713{
1714	struct clist *qp;
1715	int c;
1716	tcflag_t lflag;
1717	cc_t *cc = tp->t_cc;
1718	struct thread *td;
1719	struct proc *p;
1720	int s, first, error = 0;
1721	int has_stime = 0, last_cc = 0;
1722	long slp = 0;		/* XXX this should be renamed `timo'. */
1723	struct timeval stime = { 0, 0 };
1724	struct pgrp *pg;
1725
1726	td = curthread;
1727	p = td->td_proc;
1728loop:
1729	s = spltty();
1730	lflag = tp->t_lflag;
1731	/*
1732	 * take pending input first
1733	 */
1734	if (ISSET(lflag, PENDIN)) {
1735		ttypend(tp);
1736		splx(s);	/* reduce latency */
1737		s = spltty();
1738		lflag = tp->t_lflag;	/* XXX ttypend() clobbers it */
1739	}
1740
1741	/*
1742	 * Hang process if it's in the background.
1743	 */
1744	if (isbackground(p, tp)) {
1745		splx(s);
1746		sx_slock(&proctree_lock);
1747		PROC_LOCK(p);
1748		if (SIGISMEMBER(p->p_sigacts->ps_sigignore, SIGTTIN) ||
1749		    SIGISMEMBER(td->td_sigmask, SIGTTIN) ||
1750		    (p->p_flag & P_PPWAIT) || p->p_pgrp->pg_jobc == 0) {
1751			PROC_UNLOCK(p);
1752			sx_sunlock(&proctree_lock);
1753			return (EIO);
1754		}
1755		pg = p->p_pgrp;
1756		PROC_UNLOCK(p);
1757		PGRP_LOCK(pg);
1758		sx_sunlock(&proctree_lock);
1759		pgsignal(pg, SIGTTIN, 1);
1760		PGRP_UNLOCK(pg);
1761		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, "ttybg2", 0);
1762		if (error)
1763			return (error);
1764		goto loop;
1765	}
1766
1767	if (ISSET(tp->t_state, TS_ZOMBIE)) {
1768		splx(s);
1769		return (0);	/* EOF */
1770	}
1771
1772	/*
1773	 * If canonical, use the canonical queue,
1774	 * else use the raw queue.
1775	 *
1776	 * (should get rid of clists...)
1777	 */
1778	qp = ISSET(lflag, ICANON) ? &tp->t_canq : &tp->t_rawq;
1779
1780	if (flag & IO_NDELAY) {
1781		if (qp->c_cc > 0)
1782			goto read;
1783		if (!ISSET(lflag, ICANON) && cc[VMIN] == 0) {
1784			splx(s);
1785			return (0);
1786		}
1787		splx(s);
1788		return (EWOULDBLOCK);
1789	}
1790	if (!ISSET(lflag, ICANON)) {
1791		int m = cc[VMIN];
1792		long t = cc[VTIME];
1793		struct timeval timecopy;
1794
1795		/*
1796		 * Check each of the four combinations.
1797		 * (m > 0 && t == 0) is the normal read case.
1798		 * It should be fairly efficient, so we check that and its
1799		 * companion case (m == 0 && t == 0) first.
1800		 * For the other two cases, we compute the target sleep time
1801		 * into slp.
1802		 */
1803		if (t == 0) {
1804			if (qp->c_cc < m)
1805				goto sleep;
1806			if (qp->c_cc > 0)
1807				goto read;
1808
1809			/* m, t and qp->c_cc are all 0.  0 is enough input. */
1810			splx(s);
1811			return (0);
1812		}
1813		t *= 100000;		/* time in us */
1814#define diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 1000000 + \
1815			 ((t1).tv_usec - (t2).tv_usec))
1816		if (m > 0) {
1817			if (qp->c_cc <= 0)
1818				goto sleep;
1819			if (qp->c_cc >= m)
1820				goto read;
1821			getmicrotime(&timecopy);
1822			if (!has_stime) {
1823				/* first character, start timer */
1824				has_stime = 1;
1825				stime = timecopy;
1826				slp = t;
1827			} else if (qp->c_cc > last_cc) {
1828				/* got a character, restart timer */
1829				stime = timecopy;
1830				slp = t;
1831			} else {
1832				/* nothing, check expiration */
1833				slp = t - diff(timecopy, stime);
1834				if (slp <= 0)
1835					goto read;
1836			}
1837			last_cc = qp->c_cc;
1838		} else {	/* m == 0 */
1839			if (qp->c_cc > 0)
1840				goto read;
1841			getmicrotime(&timecopy);
1842			if (!has_stime) {
1843				has_stime = 1;
1844				stime = timecopy;
1845				slp = t;
1846			} else {
1847				slp = t - diff(timecopy, stime);
1848				if (slp <= 0) {
1849					/* Timed out, but 0 is enough input. */
1850					splx(s);
1851					return (0);
1852				}
1853			}
1854		}
1855#undef diff
1856		if (slp != 0) {
1857			struct timeval tv;	/* XXX style bug. */
1858
1859			tv.tv_sec = slp / 1000000;
1860			tv.tv_usec = slp % 1000000;
1861			slp = tvtohz(&tv);
1862			/*
1863			 * XXX bad variable names.  slp was the timeout in
1864			 * usec.  Now it is the timeout in ticks.
1865			 */
1866		}
1867		goto sleep;
1868	}
1869	if (qp->c_cc <= 0) {
1870sleep:
1871		/*
1872		 * There is no input, or not enough input and we can block.
1873		 */
1874		error = ttysleep(tp, TSA_HUP_OR_INPUT(tp), TTIPRI | PCATCH,
1875				 ISSET(tp->t_state, TS_CONNECTED) ?
1876				 "ttyin" : "ttyhup", (int)slp);
1877		splx(s);
1878		if (error == EWOULDBLOCK)
1879			error = 0;
1880		else if (error)
1881			return (error);
1882		/*
1883		 * XXX what happens if another process eats some input
1884		 * while we are asleep (not just here)?  It would be
1885		 * safest to detect changes and reset our state variables
1886		 * (has_stime and last_cc).
1887		 */
1888		slp = 0;
1889		goto loop;
1890	}
1891read:
1892	splx(s);
1893	/*
1894	 * Input present, check for input mapping and processing.
1895	 */
1896	first = 1;
1897	if (ISSET(lflag, ICANON | ISIG))
1898		goto slowcase;
1899	for (;;) {
1900		char ibuf[IBUFSIZ];
1901		int icc;
1902
1903		icc = imin(uio->uio_resid, IBUFSIZ);
1904		icc = q_to_b(qp, ibuf, icc);
1905		if (icc <= 0) {
1906			if (first)
1907				goto loop;
1908			break;
1909		}
1910		error = uiomove(ibuf, icc, uio);
1911		/*
1912		 * XXX if there was an error then we should ungetc() the
1913		 * unmoved chars and reduce icc here.
1914		 */
1915		if (error)
1916			break;
1917		if (uio->uio_resid == 0)
1918			break;
1919		first = 0;
1920	}
1921	goto out;
1922slowcase:
1923	for (;;) {
1924		c = getc(qp);
1925		if (c < 0) {
1926			if (first)
1927				goto loop;
1928			break;
1929		}
1930		/*
1931		 * delayed suspend (^Y)
1932		 */
1933		if (CCEQ(cc[VDSUSP], c) &&
1934		    ISSET(lflag, IEXTEN | ISIG) == (IEXTEN | ISIG)) {
1935			if (tp->t_pgrp != NULL) {
1936				PGRP_LOCK(tp->t_pgrp);
1937				pgsignal(tp->t_pgrp, SIGTSTP, 1);
1938				PGRP_UNLOCK(tp->t_pgrp);
1939			}
1940			if (first) {
1941				error = ttysleep(tp, &lbolt, TTIPRI | PCATCH,
1942						 "ttybg3", 0);
1943				if (error)
1944					break;
1945				goto loop;
1946			}
1947			break;
1948		}
1949		/*
1950		 * Interpret EOF only in canonical mode.
1951		 */
1952		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
1953			break;
1954		/*
1955		 * Give user character.
1956		 */
1957		error = ureadc(c, uio);
1958		if (error)
1959			/* XXX should ungetc(c, qp). */
1960			break;
1961		if (uio->uio_resid == 0)
1962			break;
1963		/*
1964		 * In canonical mode check for a "break character"
1965		 * marking the end of a "line of input".
1966		 */
1967		if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
1968			break;
1969		first = 0;
1970	}
1971
1972out:
1973	/*
1974	 * Look to unblock input now that (presumably)
1975	 * the input queue has gone down.
1976	 */
1977	s = spltty();
1978	if (ISSET(tp->t_state, TS_TBLOCK) &&
1979	    tp->t_rawq.c_cc + tp->t_canq.c_cc <= tp->t_ilowat)
1980		ttyunblock(tp);
1981	splx(s);
1982
1983	return (error);
1984}
1985
1986/*
1987 * Check the output queue on tp for space for a kernel message (from uprintf
1988 * or tprintf).  Allow some space over the normal hiwater mark so we don't
1989 * lose messages due to normal flow control, but don't let the tty run amok.
1990 * Sleeps here are not interruptible, but we return prematurely if new signals
1991 * arrive.
1992 */
1993int
1994ttycheckoutq(struct tty *tp, int wait)
1995{
1996	int hiwat, s;
1997	sigset_t oldmask;
1998	struct thread *td;
1999	struct proc *p;
2000
2001	td = curthread;
2002	p = td->td_proc;
2003	hiwat = tp->t_ohiwat;
2004	SIGEMPTYSET(oldmask);
2005	s = spltty();
2006	if (wait) {
2007		PROC_LOCK(p);
2008		oldmask = td->td_siglist;
2009		PROC_UNLOCK(p);
2010	}
2011	if (tp->t_outq.c_cc > hiwat + OBUFSIZ + 100)
2012		while (tp->t_outq.c_cc > hiwat) {
2013			ttstart(tp);
2014			if (tp->t_outq.c_cc <= hiwat)
2015				break;
2016			if (!wait) {
2017				splx(s);
2018				return (0);
2019			}
2020			PROC_LOCK(p);
2021			if (!SIGSETEQ(td->td_siglist, oldmask)) {
2022				PROC_UNLOCK(p);
2023				splx(s);
2024				return (0);
2025			}
2026			PROC_UNLOCK(p);
2027			SET(tp->t_state, TS_SO_OLOWAT);
2028			tsleep(TSA_OLOWAT(tp), PZERO - 1, "ttoutq", hz);
2029		}
2030	splx(s);
2031	return (1);
2032}
2033
2034/*
2035 * Process a write call on a tty device.
2036 */
2037int
2038ttwrite(struct tty *tp, struct uio *uio, int flag)
2039{
2040	char *cp = NULL;
2041	int cc, ce;
2042	struct thread *td;
2043	struct proc *p;
2044	int i, hiwat, cnt, error, s;
2045	char obuf[OBUFSIZ];
2046
2047	hiwat = tp->t_ohiwat;
2048	cnt = uio->uio_resid;
2049	error = 0;
2050	cc = 0;
2051	td = curthread;
2052	p = td->td_proc;
2053loop:
2054	s = spltty();
2055	if (ISSET(tp->t_state, TS_ZOMBIE)) {
2056		splx(s);
2057		if (uio->uio_resid == cnt)
2058			error = EIO;
2059		goto out;
2060	}
2061	if (!ISSET(tp->t_state, TS_CONNECTED)) {
2062		if (flag & IO_NDELAY) {
2063			splx(s);
2064			error = EWOULDBLOCK;
2065			goto out;
2066		}
2067		error = ttysleep(tp, TSA_CARR_ON(tp), TTIPRI | PCATCH,
2068				 "ttywdcd", 0);
2069		splx(s);
2070		if (error)
2071			goto out;
2072		goto loop;
2073	}
2074	splx(s);
2075	/*
2076	 * Hang the process if it's in the background.
2077	 */
2078	sx_slock(&proctree_lock);
2079	PROC_LOCK(p);
2080	if (isbackground(p, tp) &&
2081	    ISSET(tp->t_lflag, TOSTOP) && !(p->p_flag & P_PPWAIT) &&
2082	    !SIGISMEMBER(p->p_sigacts->ps_sigignore, SIGTTOU) &&
2083	    !SIGISMEMBER(td->td_sigmask, SIGTTOU)) {
2084		if (p->p_pgrp->pg_jobc == 0) {
2085			PROC_UNLOCK(p);
2086			sx_sunlock(&proctree_lock);
2087			error = EIO;
2088			goto out;
2089		}
2090		PROC_UNLOCK(p);
2091		PGRP_LOCK(p->p_pgrp);
2092		sx_sunlock(&proctree_lock);
2093		pgsignal(p->p_pgrp, SIGTTOU, 1);
2094		PGRP_UNLOCK(p->p_pgrp);
2095		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, "ttybg4", 0);
2096		if (error)
2097			goto out;
2098		goto loop;
2099	} else {
2100		PROC_UNLOCK(p);
2101		sx_sunlock(&proctree_lock);
2102	}
2103	/*
2104	 * Process the user's data in at most OBUFSIZ chunks.  Perform any
2105	 * output translation.  Keep track of high water mark, sleep on
2106	 * overflow awaiting device aid in acquiring new space.
2107	 */
2108	while (uio->uio_resid > 0 || cc > 0) {
2109		if (ISSET(tp->t_lflag, FLUSHO)) {
2110			uio->uio_resid = 0;
2111			return (0);
2112		}
2113		if (tp->t_outq.c_cc > hiwat)
2114			goto ovhiwat;
2115		/*
2116		 * Grab a hunk of data from the user, unless we have some
2117		 * leftover from last time.
2118		 */
2119		if (cc == 0) {
2120			cc = imin(uio->uio_resid, OBUFSIZ);
2121			cp = obuf;
2122			error = uiomove(cp, cc, uio);
2123			if (error) {
2124				cc = 0;
2125				break;
2126			}
2127		}
2128		/*
2129		 * If nothing fancy need be done, grab those characters we
2130		 * can handle without any of ttyoutput's processing and
2131		 * just transfer them to the output q.  For those chars
2132		 * which require special processing (as indicated by the
2133		 * bits in char_type), call ttyoutput.  After processing
2134		 * a hunk of data, look for FLUSHO so ^O's will take effect
2135		 * immediately.
2136		 */
2137		while (cc > 0) {
2138			if (!ISSET(tp->t_oflag, OPOST))
2139				ce = cc;
2140			else {
2141				ce = cc - scanc((u_int)cc, (u_char *)cp,
2142						char_type, CCLASSMASK);
2143				/*
2144				 * If ce is zero, then we're processing
2145				 * a special character through ttyoutput.
2146				 */
2147				if (ce == 0) {
2148					tp->t_rocount = 0;
2149					if (ttyoutput(*cp, tp) >= 0) {
2150						/* No Clists, wait a bit. */
2151						ttstart(tp);
2152						if (flag & IO_NDELAY) {
2153							error = EWOULDBLOCK;
2154							goto out;
2155						}
2156						error = ttysleep(tp, &lbolt,
2157								 TTOPRI|PCATCH,
2158								 "ttybf1", 0);
2159						if (error)
2160							goto out;
2161						goto loop;
2162					}
2163					cp++;
2164					cc--;
2165					if (ISSET(tp->t_lflag, FLUSHO) ||
2166					    tp->t_outq.c_cc > hiwat)
2167						goto ovhiwat;
2168					continue;
2169				}
2170			}
2171			/*
2172			 * A bunch of normal characters have been found.
2173			 * Transfer them en masse to the output queue and
2174			 * continue processing at the top of the loop.
2175			 * If there are any further characters in this
2176			 * <= OBUFSIZ chunk, the first should be a character
2177			 * requiring special handling by ttyoutput.
2178			 */
2179			tp->t_rocount = 0;
2180			i = b_to_q(cp, ce, &tp->t_outq);
2181			ce -= i;
2182			tp->t_column += ce;
2183			cp += ce, cc -= ce, tk_nout += ce;
2184			tp->t_outcc += ce;
2185			if (i > 0) {
2186				/* No Clists, wait a bit. */
2187				ttstart(tp);
2188				if (flag & IO_NDELAY) {
2189					error = EWOULDBLOCK;
2190					goto out;
2191				}
2192				error = ttysleep(tp, &lbolt, TTOPRI | PCATCH,
2193						 "ttybf2", 0);
2194				if (error)
2195					goto out;
2196				goto loop;
2197			}
2198			if (ISSET(tp->t_lflag, FLUSHO) ||
2199			    tp->t_outq.c_cc > hiwat)
2200				break;
2201		}
2202		ttstart(tp);
2203	}
2204out:
2205	/*
2206	 * If cc is nonzero, we leave the uio structure inconsistent, as the
2207	 * offset and iov pointers have moved forward, but it doesn't matter
2208	 * (the call will either return short or restart with a new uio).
2209	 */
2210	uio->uio_resid += cc;
2211	return (error);
2212
2213ovhiwat:
2214	ttstart(tp);
2215	s = spltty();
2216	/*
2217	 * This can only occur if FLUSHO is set in t_lflag,
2218	 * or if ttstart/oproc is synchronous (or very fast).
2219	 */
2220	if (tp->t_outq.c_cc <= hiwat) {
2221		splx(s);
2222		goto loop;
2223	}
2224	if (flag & IO_NDELAY) {
2225		splx(s);
2226		uio->uio_resid += cc;
2227		return (uio->uio_resid == cnt ? EWOULDBLOCK : 0);
2228	}
2229	SET(tp->t_state, TS_SO_OLOWAT);
2230	error = ttysleep(tp, TSA_OLOWAT(tp), TTOPRI | PCATCH, "ttywri",
2231			 tp->t_timeout);
2232	splx(s);
2233	if (error == EWOULDBLOCK)
2234		error = EIO;
2235	if (error)
2236		goto out;
2237	goto loop;
2238}
2239
2240/*
2241 * Rubout one character from the rawq of tp
2242 * as cleanly as possible.
2243 */
2244static void
2245ttyrub(int c, struct tty *tp)
2246{
2247	char *cp;
2248	int savecol;
2249	int tabc, s;
2250
2251	if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
2252		return;
2253	CLR(tp->t_lflag, FLUSHO);
2254	if (ISSET(tp->t_lflag, ECHOE)) {
2255		if (tp->t_rocount == 0) {
2256			/*
2257			 * Screwed by ttwrite; retype
2258			 */
2259			ttyretype(tp);
2260			return;
2261		}
2262		if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
2263			ttyrubo(tp, 2);
2264		else {
2265			CLR(c, ~TTY_CHARMASK);
2266			switch (CCLASS(c)) {
2267			case ORDINARY:
2268				ttyrubo(tp, 1);
2269				break;
2270			case BACKSPACE:
2271			case CONTROL:
2272			case NEWLINE:
2273			case RETURN:
2274			case VTAB:
2275				if (ISSET(tp->t_lflag, ECHOCTL))
2276					ttyrubo(tp, 2);
2277				break;
2278			case TAB:
2279				if (tp->t_rocount < tp->t_rawq.c_cc) {
2280					ttyretype(tp);
2281					return;
2282				}
2283				s = spltty();
2284				savecol = tp->t_column;
2285				SET(tp->t_state, TS_CNTTB);
2286				SET(tp->t_lflag, FLUSHO);
2287				tp->t_column = tp->t_rocol;
2288				cp = tp->t_rawq.c_cf;
2289				if (cp)
2290					tabc = *cp;	/* XXX FIX NEXTC */
2291				for (; cp; cp = nextc(&tp->t_rawq, cp, &tabc))
2292					ttyecho(tabc, tp);
2293				CLR(tp->t_lflag, FLUSHO);
2294				CLR(tp->t_state, TS_CNTTB);
2295				splx(s);
2296
2297				/* savecol will now be length of the tab. */
2298				savecol -= tp->t_column;
2299				tp->t_column += savecol;
2300				if (savecol > 8)
2301					savecol = 8;	/* overflow screw */
2302				while (--savecol >= 0)
2303					(void)ttyoutput('\b', tp);
2304				break;
2305			default:			/* XXX */
2306#define	PANICSTR	"ttyrub: would panic c = %d, val = %d\n"
2307				(void)printf(PANICSTR, c, CCLASS(c));
2308#ifdef notdef
2309				panic(PANICSTR, c, CCLASS(c));
2310#endif
2311			}
2312		}
2313	} else if (ISSET(tp->t_lflag, ECHOPRT)) {
2314		if (!ISSET(tp->t_state, TS_ERASE)) {
2315			SET(tp->t_state, TS_ERASE);
2316			(void)ttyoutput('\\', tp);
2317		}
2318		ttyecho(c, tp);
2319	} else {
2320		ttyecho(tp->t_cc[VERASE], tp);
2321		/*
2322		 * This code may be executed not only when an ERASE key
2323		 * is pressed, but also when ^U (KILL) or ^W (WERASE) are.
2324		 * So, I didn't think it was worthwhile to pass the extra
2325		 * information (which would need an extra parameter,
2326		 * changing every call) needed to distinguish the ERASE2
2327		 * case from the ERASE.
2328		 */
2329	}
2330	--tp->t_rocount;
2331}
2332
2333/*
2334 * Back over cnt characters, erasing them.
2335 */
2336static void
2337ttyrubo(struct tty *tp, int cnt)
2338{
2339
2340	while (cnt-- > 0) {
2341		(void)ttyoutput('\b', tp);
2342		(void)ttyoutput(' ', tp);
2343		(void)ttyoutput('\b', tp);
2344	}
2345}
2346
2347/*
2348 * ttyretype --
2349 *	Reprint the rawq line.  Note, it is assumed that c_cc has already
2350 *	been checked.
2351 */
2352static void
2353ttyretype(struct tty *tp)
2354{
2355	char *cp;
2356	int s, c;
2357
2358	/* Echo the reprint character. */
2359	if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
2360		ttyecho(tp->t_cc[VREPRINT], tp);
2361
2362	(void)ttyoutput('\n', tp);
2363
2364	/*
2365	 * XXX
2366	 * FIX: NEXTC IS BROKEN - DOESN'T CHECK QUOTE
2367	 * BIT OF FIRST CHAR.
2368	 */
2369	s = spltty();
2370	for (cp = tp->t_canq.c_cf, c = (cp != NULL ? *cp : 0);
2371	    cp != NULL; cp = nextc(&tp->t_canq, cp, &c))
2372		ttyecho(c, tp);
2373	for (cp = tp->t_rawq.c_cf, c = (cp != NULL ? *cp : 0);
2374	    cp != NULL; cp = nextc(&tp->t_rawq, cp, &c))
2375		ttyecho(c, tp);
2376	CLR(tp->t_state, TS_ERASE);
2377	splx(s);
2378
2379	tp->t_rocount = tp->t_rawq.c_cc;
2380	tp->t_rocol = 0;
2381}
2382
2383/*
2384 * Echo a typed character to the terminal.
2385 */
2386static void
2387ttyecho(int c, struct tty *tp)
2388{
2389
2390	if (!ISSET(tp->t_state, TS_CNTTB))
2391		CLR(tp->t_lflag, FLUSHO);
2392	if ((!ISSET(tp->t_lflag, ECHO) &&
2393	     (c != '\n' || !ISSET(tp->t_lflag, ECHONL))) ||
2394	    ISSET(tp->t_lflag, EXTPROC))
2395		return;
2396	if (ISSET(tp->t_lflag, ECHOCTL) &&
2397	    ((ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n') ||
2398	    ISSET(c, TTY_CHARMASK) == 0177)) {
2399		(void)ttyoutput('^', tp);
2400		CLR(c, ~TTY_CHARMASK);
2401		if (c == 0177)
2402			c = '?';
2403		else
2404			c += 'A' - 1;
2405	}
2406	(void)ttyoutput(c, tp);
2407}
2408
2409/*
2410 * Wake up any readers on a tty.
2411 */
2412void
2413ttwakeup(struct tty *tp)
2414{
2415
2416	if (SEL_WAITING(&tp->t_rsel))
2417		selwakeuppri(&tp->t_rsel, TTIPRI);
2418	if (ISSET(tp->t_state, TS_ASYNC) && tp->t_sigio != NULL)
2419		pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
2420	wakeup(TSA_HUP_OR_INPUT(tp));
2421	KNOTE_UNLOCKED(&tp->t_rsel.si_note, 0);
2422}
2423
2424/*
2425 * Wake up any writers on a tty.
2426 */
2427void
2428ttwwakeup(struct tty *tp)
2429{
2430
2431	if (SEL_WAITING(&tp->t_wsel) && tp->t_outq.c_cc <= tp->t_olowat)
2432		selwakeuppri(&tp->t_wsel, TTOPRI);
2433	if (ISSET(tp->t_state, TS_ASYNC) && tp->t_sigio != NULL)
2434		pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
2435	if (ISSET(tp->t_state, TS_BUSY | TS_SO_OCOMPLETE) ==
2436	    TS_SO_OCOMPLETE && tp->t_outq.c_cc == 0) {
2437		CLR(tp->t_state, TS_SO_OCOMPLETE);
2438		wakeup(TSA_OCOMPLETE(tp));
2439	}
2440	if (ISSET(tp->t_state, TS_SO_OLOWAT) &&
2441	    tp->t_outq.c_cc <= tp->t_olowat) {
2442		CLR(tp->t_state, TS_SO_OLOWAT);
2443		wakeup(TSA_OLOWAT(tp));
2444	}
2445	KNOTE_UNLOCKED(&tp->t_wsel.si_note, 0);
2446}
2447
2448/*
2449 * Look up a code for a specified speed in a conversion table;
2450 * used by drivers to map software speed values to hardware parameters.
2451 */
2452int
2453ttspeedtab(int speed, struct speedtab *table)
2454{
2455
2456	for ( ; table->sp_speed != -1; table++)
2457		if (table->sp_speed == speed)
2458			return (table->sp_code);
2459	return (-1);
2460}
2461
2462/*
2463 * Set input and output watermarks and buffer sizes.  For input, the
2464 * high watermark is about one second's worth of input above empty, the
2465 * low watermark is slightly below high water, and the buffer size is a
2466 * driver-dependent amount above high water.  For output, the watermarks
2467 * are near the ends of the buffer, with about 1 second's worth of input
2468 * between them.  All this only applies to the standard line discipline.
2469 */
2470void
2471ttsetwater(struct tty *tp)
2472{
2473	int cps, ttmaxhiwat, x;
2474
2475	/* Input. */
2476	clist_alloc_cblocks(&tp->t_canq, TTYHOG, 512);
2477	switch (tp->t_ispeedwat) {
2478	case (speed_t)-1:
2479		cps = tp->t_ispeed / 10;
2480		break;
2481	case 0:
2482		/*
2483		 * This case is for old drivers that don't know about
2484		 * t_ispeedwat.  Arrange for them to get the old buffer
2485		 * sizes and watermarks.
2486		 */
2487		cps = TTYHOG - 2 * 256;
2488		tp->t_ififosize = 2 * 256;
2489		break;
2490	default:
2491		cps = tp->t_ispeedwat / 10;
2492		break;
2493	}
2494	tp->t_ihiwat = cps;
2495	tp->t_ilowat = 7 * cps / 8;
2496	x = cps + tp->t_ififosize;
2497	clist_alloc_cblocks(&tp->t_rawq, x, x);
2498
2499	/* Output. */
2500	switch (tp->t_ospeedwat) {
2501	case (speed_t)-1:
2502		cps = tp->t_ospeed / 10;
2503		ttmaxhiwat = 2 * TTMAXHIWAT;
2504		break;
2505	case 0:
2506		cps = tp->t_ospeed / 10;
2507		ttmaxhiwat = TTMAXHIWAT;
2508		break;
2509	default:
2510		cps = tp->t_ospeedwat / 10;
2511		ttmaxhiwat = 8 * TTMAXHIWAT;
2512		break;
2513	}
2514#define CLAMP(x, h, l)	((x) > h ? h : ((x) < l) ? l : (x))
2515	tp->t_olowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
2516	x += cps;
2517	x = CLAMP(x, ttmaxhiwat, TTMINHIWAT);	/* XXX clamps are too magic */
2518	tp->t_ohiwat = roundup(x, CBSIZE);	/* XXX for compat */
2519	x = imax(tp->t_ohiwat, TTMAXHIWAT);	/* XXX for compat/safety */
2520	x += OBUFSIZ + 100;
2521	clist_alloc_cblocks(&tp->t_outq, x, x);
2522#undef	CLAMP
2523}
2524
2525/*
2526 * Output char to tty; console putchar style.
2527 */
2528int
2529tputchar(int c, struct tty *tp)
2530{
2531	int s;
2532
2533	s = spltty();
2534	if (!ISSET(tp->t_state, TS_CONNECTED)) {
2535		splx(s);
2536		return (-1);
2537	}
2538	if (c == '\n')
2539		(void)ttyoutput('\r', tp);
2540	(void)ttyoutput(c, tp);
2541	ttstart(tp);
2542	splx(s);
2543	return (0);
2544}
2545
2546/*
2547 * Sleep on chan, returning ERESTART if tty changed while we napped and
2548 * returning any errors (e.g. EINTR/EWOULDBLOCK) reported by tsleep.  If
2549 * the tty is revoked, restarting a pending call will redo validation done
2550 * at the start of the call.
2551 */
2552int
2553ttysleep(struct tty *tp, void *chan, int pri, char *wmesg, int timo)
2554{
2555	int error;
2556	int gen;
2557
2558	gen = tp->t_gen;
2559	error = tsleep(chan, pri, wmesg, timo);
2560	if (tp->t_state & TS_GONE)
2561		return (ENXIO);
2562	if (error)
2563		return (error);
2564	return (tp->t_gen == gen ? 0 : ERESTART);
2565}
2566
2567/*
2568 * Gain a reference to a TTY
2569 */
2570int
2571ttyref(struct tty *tp)
2572{
2573	int i;
2574
2575	mtx_lock(&tp->t_mtx);
2576	KASSERT(tp->t_refcnt > 0,
2577	    ("ttyref(): tty refcnt is %d (%s)",
2578	    tp->t_refcnt, tp->t_dev != NULL ? devtoname(tp->t_dev) : "??"));
2579	i = ++tp->t_refcnt;
2580	mtx_unlock(&tp->t_mtx);
2581	return (i);
2582}
2583
2584/*
2585 * Drop a reference to a TTY.
2586 * When reference count drops to zero, we free it.
2587 */
2588int
2589ttyrel(struct tty *tp)
2590{
2591	int i;
2592
2593	mtx_lock(&tty_list_mutex);
2594	mtx_lock(&tp->t_mtx);
2595	KASSERT(tp->t_refcnt > 0,
2596	    ("ttyrel(): tty refcnt is %d (%s)",
2597	    tp->t_refcnt, tp->t_dev != NULL ? devtoname(tp->t_dev) : "??"));
2598	i = --tp->t_refcnt;
2599	if (i != 0) {
2600		mtx_unlock(&tp->t_mtx);
2601		mtx_unlock(&tty_list_mutex);
2602		return (i);
2603	}
2604	TAILQ_REMOVE(&tty_list, tp, t_list);
2605	mtx_unlock(&tp->t_mtx);
2606	mtx_unlock(&tty_list_mutex);
2607	knlist_destroy(&tp->t_rsel.si_note);
2608	knlist_destroy(&tp->t_wsel.si_note);
2609	mtx_destroy(&tp->t_mtx);
2610	free(tp, M_TTYS);
2611	return (i);
2612}
2613
2614/*
2615 * Allocate a tty struct.  Clists in the struct will be allocated by
2616 * tty_open().
2617 */
2618struct tty *
2619ttyalloc()
2620{
2621	struct tty *tp;
2622
2623	tp = malloc(sizeof *tp, M_TTYS, M_WAITOK | M_ZERO);
2624	mtx_init(&tp->t_mtx, "tty", NULL, MTX_DEF);
2625
2626	/*
2627	 * Set up the initial state
2628	 */
2629	tp->t_refcnt = 1;
2630	tp->t_timeout = -1;
2631	tp->t_dtr_wait = 3 * hz;
2632
2633	ttyinitmode(tp, 0, 0);
2634	bcopy(ttydefchars, tp->t_init_in.c_cc, sizeof tp->t_init_in.c_cc);
2635
2636	/* Make callout the same as callin */
2637	tp->t_init_out = tp->t_init_in;
2638
2639	mtx_lock(&tty_list_mutex);
2640	TAILQ_INSERT_TAIL(&tty_list, tp, t_list);
2641	mtx_unlock(&tty_list_mutex);
2642	knlist_init(&tp->t_rsel.si_note, &tp->t_mtx, NULL, NULL, NULL);
2643	knlist_init(&tp->t_wsel.si_note, &tp->t_mtx, NULL, NULL, NULL);
2644	return (tp);
2645}
2646
2647static void
2648ttypurge(struct cdev *dev)
2649{
2650
2651	if (dev->si_tty == NULL)
2652		return;
2653	ttygone(dev->si_tty);
2654}
2655
2656/*
2657 * ttycreate()
2658 *
2659 * Create the device entries for this tty thereby opening it for business.
2660 *
2661 * The flags argument controls if "cua" units are created.
2662 *
2663 * The t_sc filed is copied to si_drv1 in the created cdevs.  This
2664 * is particularly important for ->t_cioctl() users.
2665 *
2666 * XXX: implement the init and lock devices by cloning.
2667 */
2668
2669int
2670ttycreate(struct tty *tp, int flags, const char *fmt, ...)
2671{
2672	char namebuf[SPECNAMELEN - 3];		/* XXX space for "tty" */
2673	struct cdevsw *csw = NULL;
2674	int unit = 0;
2675	va_list ap;
2676	struct cdev *cp;
2677	int i, minor, sminor, sunit;
2678
2679	mtx_assert(&Giant, MA_OWNED);
2680
2681	if (tty_unit == NULL)
2682		tty_unit = new_unrhdr(0, 0xffff, NULL);
2683
2684	sunit = alloc_unr(tty_unit);
2685	tp->t_devunit = sunit;
2686
2687	if (csw == NULL) {
2688		csw = &tty_cdevsw;
2689		unit = sunit;
2690	}
2691	KASSERT(csw->d_purge == NULL || csw->d_purge == ttypurge,
2692	    ("tty should not have d_purge"));
2693
2694	csw->d_purge = ttypurge;
2695
2696	minor = unit2minor(unit);
2697	sminor = unit2minor(sunit);
2698	va_start(ap, fmt);
2699	i = vsnrprintf(namebuf, sizeof namebuf, 32, fmt, ap);
2700	va_end(ap);
2701	KASSERT(i < sizeof namebuf, ("Too long tty name (%s)", namebuf));
2702
2703	cp = make_dev(csw, minor,
2704	    UID_ROOT, GID_WHEEL, 0600, "tty%s", namebuf);
2705	tp->t_dev = cp;
2706	tp->t_mdev = cp;
2707	cp->si_tty = tp;
2708	cp->si_drv1 = tp->t_sc;
2709
2710	cp = make_dev(&ttys_cdevsw, sminor | MINOR_INIT,
2711	    UID_ROOT, GID_WHEEL, 0600, "tty%s.init", namebuf);
2712	dev_depends(tp->t_dev, cp);
2713	cp->si_drv1 = tp->t_sc;
2714	cp->si_drv2 = &tp->t_init_in;
2715	cp->si_tty = tp;
2716
2717	cp = make_dev(&ttys_cdevsw, sminor | MINOR_LOCK,
2718	    UID_ROOT, GID_WHEEL, 0600, "tty%s.lock", namebuf);
2719	dev_depends(tp->t_dev, cp);
2720	cp->si_drv1 = tp->t_sc;
2721	cp->si_drv2 = &tp->t_lock_in;
2722	cp->si_tty = tp;
2723
2724	if (flags & TS_CALLOUT) {
2725		cp = make_dev(csw, minor | MINOR_CALLOUT,
2726		    UID_UUCP, GID_DIALER, 0660, "cua%s", namebuf);
2727		dev_depends(tp->t_dev, cp);
2728		cp->si_drv1 = tp->t_sc;
2729		cp->si_tty = tp;
2730
2731		cp = make_dev(&ttys_cdevsw, sminor | MINOR_CALLOUT | MINOR_INIT,
2732		    UID_UUCP, GID_DIALER, 0660, "cua%s.init", namebuf);
2733		dev_depends(tp->t_dev, cp);
2734		cp->si_drv1 = tp->t_sc;
2735		cp->si_drv2 = &tp->t_init_out;
2736		cp->si_tty = tp;
2737
2738		cp = make_dev(&ttys_cdevsw, sminor | MINOR_CALLOUT | MINOR_LOCK,
2739		    UID_UUCP, GID_DIALER, 0660, "cua%s.lock", namebuf);
2740		dev_depends(tp->t_dev, cp);
2741		cp->si_drv1 = tp->t_sc;
2742		cp->si_drv2 = &tp->t_lock_out;
2743		cp->si_tty = tp;
2744	}
2745
2746	return (0);
2747}
2748
2749/*
2750 * This function is called when the hardware disappears.  We set a flag
2751 * and wake up stuff so all sleeping threads will notice.
2752 */
2753void
2754ttygone(struct tty *tp)
2755{
2756
2757	tp->t_state |= TS_GONE;
2758	if (SEL_WAITING(&tp->t_rsel))
2759		selwakeuppri(&tp->t_rsel, TTIPRI);
2760	if (SEL_WAITING(&tp->t_wsel))
2761		selwakeuppri(&tp->t_wsel, TTOPRI);
2762	if (ISSET(tp->t_state, TS_ASYNC) && tp->t_sigio != NULL)
2763		pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
2764	wakeup(&tp->t_dtr_wait);
2765	wakeup(TSA_CARR_ON(tp));
2766	wakeup(TSA_HUP_OR_INPUT(tp));
2767	wakeup(TSA_OCOMPLETE(tp));
2768	wakeup(TSA_OLOWAT(tp));
2769	KNOTE_UNLOCKED(&tp->t_rsel.si_note, 0);
2770	KNOTE_UNLOCKED(&tp->t_wsel.si_note, 0);
2771	tt_purge(tp);
2772}
2773
2774/*
2775 * ttyfree()
2776 *
2777 * Called when the driver is ready to free the tty structure.
2778 *
2779 * XXX: This shall sleep until all threads have left the driver.
2780 */
2781void
2782ttyfree(struct tty *tp)
2783{
2784	struct cdev *dev;
2785	u_int unit;
2786
2787	mtx_assert(&Giant, MA_OWNED);
2788	ttygone(tp);
2789	unit = tp->t_devunit;
2790	dev = tp->t_mdev;
2791	dev->si_tty = NULL;
2792	tp->t_dev = NULL;
2793	destroy_dev(dev);
2794	ttyrel(tp);
2795	free_unr(tty_unit, unit);
2796}
2797
2798static int
2799sysctl_kern_ttys(SYSCTL_HANDLER_ARGS)
2800{
2801	struct tty *tp, *tp2;
2802	struct xtty xt;
2803	int error;
2804
2805	error = 0;
2806	mtx_lock(&tty_list_mutex);
2807	tp = TAILQ_FIRST(&tty_list);
2808	if (tp != NULL)
2809		ttyref(tp);
2810	while (tp != NULL) {
2811		if (tp->t_state & TS_GONE)
2812			goto nexttp;
2813		bzero(&xt, sizeof xt);
2814		xt.xt_size = sizeof xt;
2815#define XT_COPY(field) xt.xt_##field = tp->t_##field
2816		xt.xt_rawcc = tp->t_rawq.c_cc;
2817		xt.xt_cancc = tp->t_canq.c_cc;
2818		xt.xt_outcc = tp->t_outq.c_cc;
2819		XT_COPY(line);
2820
2821		/*
2822		 * XXX: We hold the tty list lock while doing this to
2823		 * work around a race with pty/pts tty destruction.
2824		 * They set t_dev to NULL and then call ttyrel() to
2825		 * free the structure which will block on the list
2826		 * lock before they call destroy_dev() on the cdev
2827		 * backing t_dev.
2828		 *
2829		 * XXX: ttyfree() now does the same since it has been
2830		 * fixed to not leak ttys.
2831		 */
2832		if (tp->t_dev != NULL)
2833			xt.xt_dev = dev2udev(tp->t_dev);
2834		XT_COPY(state);
2835		XT_COPY(flags);
2836		XT_COPY(timeout);
2837		if (tp->t_pgrp != NULL)
2838			xt.xt_pgid = tp->t_pgrp->pg_id;
2839		if (tp->t_session != NULL)
2840			xt.xt_sid = tp->t_session->s_sid;
2841		XT_COPY(termios);
2842		XT_COPY(winsize);
2843		XT_COPY(column);
2844		XT_COPY(rocount);
2845		XT_COPY(rocol);
2846		XT_COPY(ififosize);
2847		XT_COPY(ihiwat);
2848		XT_COPY(ilowat);
2849		XT_COPY(ispeedwat);
2850		XT_COPY(ohiwat);
2851		XT_COPY(olowat);
2852		XT_COPY(ospeedwat);
2853#undef XT_COPY
2854		mtx_unlock(&tty_list_mutex);
2855		error = SYSCTL_OUT(req, &xt, sizeof xt);
2856		if (error != 0) {
2857			ttyrel(tp);
2858			return (error);
2859		}
2860		mtx_lock(&tty_list_mutex);
2861nexttp:		tp2 = TAILQ_NEXT(tp, t_list);
2862		if (tp2 != NULL)
2863			ttyref(tp2);
2864		mtx_unlock(&tty_list_mutex);
2865		ttyrel(tp);
2866		tp = tp2;
2867		mtx_lock(&tty_list_mutex);
2868	}
2869	mtx_unlock(&tty_list_mutex);
2870	return (0);
2871}
2872
2873SYSCTL_PROC(_kern, OID_AUTO, ttys, CTLTYPE_OPAQUE|CTLFLAG_RD,
2874	0, 0, sysctl_kern_ttys, "S,xtty", "All ttys");
2875SYSCTL_LONG(_kern, OID_AUTO, tty_nin, CTLFLAG_RD,
2876	&tk_nin, 0, "Total TTY in characters");
2877SYSCTL_LONG(_kern, OID_AUTO, tty_nout, CTLFLAG_RD,
2878	&tk_nout, 0, "Total TTY out characters");
2879
2880void
2881nottystop(struct tty *tp, int rw)
2882{
2883
2884	return;
2885}
2886
2887int
2888ttyopen(struct cdev *dev, int flag, int mode, struct thread *td)
2889{
2890	int		error;
2891	int		s;
2892	struct tty	*tp;
2893
2894	tp = dev->si_tty;
2895
2896	s = spltty();
2897	/*
2898	 * We jump to this label after all non-interrupted sleeps to pick
2899	 * up any changes of the device state.
2900	 */
2901open_top:
2902	if (tp->t_state & TS_GONE)
2903		return (ENXIO);
2904	error = ttydtrwaitsleep(tp);
2905	if (error)
2906		goto out;
2907	if (tp->t_state & TS_ISOPEN) {
2908		/*
2909		 * The device is open, so everything has been initialized.
2910		 * Handle conflicts.
2911		 */
2912		if (ISCALLOUT(dev) && !tp->t_actout)
2913			return (EBUSY);
2914		if (tp->t_actout && !ISCALLOUT(dev)) {
2915			if (flag & O_NONBLOCK)
2916				return (EBUSY);
2917			error =	tsleep(&tp->t_actout,
2918				       TTIPRI | PCATCH, "ttybi", 0);
2919			if (error != 0 || (tp->t_state & TS_GONE))
2920				goto out;
2921			goto open_top;
2922		}
2923		if (tp->t_state & TS_XCLUDE && priv_check(td,
2924		    PRIV_TTY_EXCLUSIVE))
2925			return (EBUSY);
2926	} else {
2927		/*
2928		 * The device isn't open, so there are no conflicts.
2929		 * Initialize it.  Initialization is done twice in many
2930		 * cases: to preempt sleeping callin opens if we are
2931		 * callout, and to complete a callin open after DCD rises.
2932		 */
2933		tp->t_termios = ISCALLOUT(dev) ? tp->t_init_out : tp->t_init_in;
2934		tp->t_cflag = tp->t_termios.c_cflag;
2935		if (tp->t_modem != NULL)
2936			tt_modem(tp, SER_DTR | SER_RTS, 0);
2937		++tp->t_wopeners;
2938		error = tt_param(tp, &tp->t_termios);
2939		--tp->t_wopeners;
2940		if (error == 0)
2941			error = tt_open(tp, dev);
2942		if (error != 0)
2943			goto out;
2944		if (ISCALLOUT(dev) || (tt_modem(tp, 0, 0) & SER_DCD))
2945			ttyld_modem(tp, 1);
2946	}
2947	/*
2948	 * Wait for DCD if necessary.
2949	 */
2950	if (!(tp->t_state & TS_CARR_ON) && !ISCALLOUT(dev)
2951	    && !(tp->t_cflag & CLOCAL) && !(flag & O_NONBLOCK)) {
2952		++tp->t_wopeners;
2953		error = tsleep(TSA_CARR_ON(tp), TTIPRI | PCATCH, "ttydcd", 0);
2954		--tp->t_wopeners;
2955		if (error != 0 || (tp->t_state & TS_GONE))
2956			goto out;
2957		goto open_top;
2958	}
2959	error =	ttyld_open(tp, dev);
2960	ttyldoptim(tp);
2961	if (tp->t_state & TS_ISOPEN && ISCALLOUT(dev))
2962		tp->t_actout = TRUE;
2963out:
2964	splx(s);
2965	if (!(tp->t_state & TS_ISOPEN) && tp->t_wopeners == 0)
2966		tt_close(tp);
2967	return (error);
2968}
2969
2970int
2971ttyclose(struct cdev *dev, int flag, int mode, struct thread *td)
2972{
2973	struct tty *tp;
2974
2975	tp = dev->si_tty;
2976	ttyld_close(tp, flag);
2977	ttyldoptim(tp);
2978	tt_close(tp);
2979	tp->t_do_timestamp = 0;
2980	if (tp->t_pps != NULL)
2981		tp->t_pps->ppsparam.mode = 0;
2982	tty_close(tp);
2983	return (0);
2984}
2985
2986int
2987ttyread(struct cdev *dev, struct uio *uio, int flag)
2988{
2989	struct tty *tp;
2990
2991	tp = tty_gettp(dev);
2992
2993	if (tp == NULL || (tp->t_state & TS_GONE))
2994		return (ENODEV);
2995	return (ttyld_read(tp, uio, flag));
2996}
2997
2998int
2999ttywrite(struct cdev *dev, struct uio *uio, int flag)
3000{
3001	struct tty *tp;
3002
3003	tp = tty_gettp(dev);
3004
3005	if (tp == NULL || (tp->t_state & TS_GONE))
3006		return (ENODEV);
3007	return (ttyld_write(tp, uio, flag));
3008}
3009
3010int
3011ttyioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
3012{
3013	struct	tty *tp;
3014	int	error;
3015
3016	tp = dev->si_tty;
3017
3018	if (cmd == TIOCSETA || cmd == TIOCSETAW || cmd == TIOCSETAF) {
3019		int cc;
3020		struct termios *dt = (struct termios *)data;
3021		struct termios *lt =
3022		    ISCALLOUT(dev) ?  &tp->t_lock_out : &tp->t_lock_in;
3023
3024		dt->c_iflag = (tp->t_iflag & lt->c_iflag)
3025		    | (dt->c_iflag & ~lt->c_iflag);
3026		dt->c_oflag = (tp->t_oflag & lt->c_oflag)
3027		    | (dt->c_oflag & ~lt->c_oflag);
3028		dt->c_cflag = (tp->t_cflag & lt->c_cflag)
3029		    | (dt->c_cflag & ~lt->c_cflag);
3030		dt->c_lflag = (tp->t_lflag & lt->c_lflag)
3031		    | (dt->c_lflag & ~lt->c_lflag);
3032		for (cc = 0; cc < NCCS; ++cc)
3033		    if (lt->c_cc[cc] != 0)
3034		        dt->c_cc[cc] = tp->t_cc[cc];
3035		if (lt->c_ispeed != 0)
3036		    dt->c_ispeed = tp->t_ispeed;
3037		if (lt->c_ospeed != 0)
3038		    dt->c_ospeed = tp->t_ospeed;
3039	}
3040
3041	error = ttyld_ioctl(tp, cmd, data, flag, td);
3042	if (error == ENOIOCTL)
3043		error = ttioctl(tp, cmd, data, flag);
3044	ttyldoptim(tp);
3045	if (error != ENOIOCTL)
3046		return (error);
3047	return (ENOTTY);
3048}
3049
3050void
3051ttyldoptim(struct tty *tp)
3052{
3053	struct termios	*t;
3054
3055	t = &tp->t_termios;
3056	if (!(t->c_iflag & (ICRNL | IGNCR | IMAXBEL | INLCR | ISTRIP | IXON))
3057	    && (!(t->c_iflag & BRKINT) || (t->c_iflag & IGNBRK))
3058	    && (!(t->c_iflag & PARMRK)
3059		|| (t->c_iflag & (IGNPAR | IGNBRK)) == (IGNPAR | IGNBRK))
3060	    && !(t->c_lflag & (ECHO | ICANON | IEXTEN | ISIG | PENDIN))
3061	    && linesw[tp->t_line]->l_rint == ttyinput)
3062		tp->t_state |= TS_CAN_BYPASS_L_RINT;
3063	else
3064		tp->t_state &= ~TS_CAN_BYPASS_L_RINT;
3065}
3066
3067static void
3068ttydtrwaitwakeup(void *arg)
3069{
3070	struct tty *tp;
3071
3072	tp = arg;
3073	tp->t_state &= ~TS_DTR_WAIT;
3074	wakeup(&tp->t_dtr_wait);
3075}
3076
3077
3078void
3079ttydtrwaitstart(struct tty *tp)
3080{
3081
3082	if (tp->t_dtr_wait == 0)
3083		return;
3084	if (tp->t_state & TS_DTR_WAIT)
3085		return;
3086	timeout(ttydtrwaitwakeup, tp, tp->t_dtr_wait);
3087	tp->t_state |= TS_DTR_WAIT;
3088}
3089
3090int
3091ttydtrwaitsleep(struct tty *tp)
3092{
3093	int error;
3094
3095	error = 0;
3096	while (error == 0) {
3097		if (tp->t_state & TS_GONE)
3098			error = ENXIO;
3099		else if (!(tp->t_state & TS_DTR_WAIT))
3100			break;
3101		else
3102			error = tsleep(&tp->t_dtr_wait, TTIPRI | PCATCH,
3103			    "dtrwait", 0);
3104	}
3105	return (error);
3106}
3107
3108static int
3109ttysopen(struct cdev *dev, int flag, int mode, struct thread *td)
3110{
3111	struct tty *tp;
3112
3113	tp = dev->si_tty;
3114	KASSERT(tp != NULL,
3115	    ("ttysopen(): no tty pointer on device (%s)", devtoname(dev)));
3116	if (tp->t_state & TS_GONE)
3117		return (ENODEV);
3118	return (0);
3119}
3120
3121static int
3122ttysclose(struct cdev *dev, int flag, int mode, struct thread *td)
3123{
3124
3125	return (0);
3126}
3127
3128static int
3129ttysrdwr(struct cdev *dev, struct uio *uio, int flag)
3130{
3131
3132	return (ENODEV);
3133}
3134
3135static int
3136ttysioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
3137{
3138	struct tty	*tp;
3139	int		error;
3140	struct termios	*ct;
3141
3142	tp = dev->si_tty;
3143	KASSERT(tp != NULL,
3144	    ("ttysopen(): no tty pointer on device (%s)", devtoname(dev)));
3145	if (tp->t_state & TS_GONE)
3146		return (ENODEV);
3147	ct = dev->si_drv2;
3148	switch (cmd) {
3149	case TIOCSETA:
3150		error = priv_check(td, PRIV_TTY_SETA);
3151		if (error != 0)
3152			return (error);
3153		*ct = *(struct termios *)data;
3154		return (0);
3155	case TIOCGETA:
3156		*(struct termios *)data = *ct;
3157		return (0);
3158	case TIOCGETD:
3159		*(int *)data = TTYDISC;
3160		return (0);
3161	case TIOCGWINSZ:
3162		bzero(data, sizeof(struct winsize));
3163		return (0);
3164	default:
3165		if (tp->t_cioctl != NULL)
3166			return(tp->t_cioctl(dev, cmd, data, flag, td));
3167		return (ENOTTY);
3168	}
3169}
3170
3171/*
3172 * Initialize a tty to sane modes.
3173 */
3174void
3175ttyinitmode(struct tty *tp, int echo, int speed)
3176{
3177
3178	if (speed == 0)
3179		speed = TTYDEF_SPEED;
3180	tp->t_init_in.c_iflag = TTYDEF_IFLAG;
3181	tp->t_init_in.c_oflag = TTYDEF_OFLAG;
3182	tp->t_init_in.c_cflag = TTYDEF_CFLAG;
3183	if (echo)
3184		tp->t_init_in.c_lflag = TTYDEF_LFLAG_ECHO;
3185	else
3186		tp->t_init_in.c_lflag = TTYDEF_LFLAG_NOECHO;
3187
3188	tp->t_init_in.c_ispeed = tp->t_init_in.c_ospeed = speed;
3189	termioschars(&tp->t_init_in);
3190	tp->t_init_out = tp->t_init_in;
3191	tp->t_termios = tp->t_init_in;
3192}
3193
3194/*
3195 * Use more "normal" termios paramters for consoles.
3196 */
3197void
3198ttyconsolemode(struct tty *tp, int speed)
3199{
3200
3201	if (speed == 0)
3202		speed = TTYDEF_SPEED;
3203	ttyinitmode(tp, 1, speed);
3204	tp->t_init_in.c_cflag |= CLOCAL;
3205	tp->t_lock_out.c_cflag = tp->t_lock_in.c_cflag = CLOCAL;
3206	tp->t_lock_out.c_ispeed = tp->t_lock_out.c_ospeed =
3207	tp->t_lock_in.c_ispeed = tp->t_lock_in.c_ospeed = speed;
3208	tp->t_init_out = tp->t_init_in;
3209	tp->t_termios = tp->t_init_in;
3210	ttsetwater(tp);
3211}
3212
3213/*
3214 * Record the relationship between the serial ports notion of modem control
3215 * signals and the one used in certain ioctls in a way the compiler can enforce
3216 * XXX: We should define TIOCM_* in terms of SER_ if we can limit the
3217 * XXX: consequences of the #include work that would take.
3218 */
3219CTASSERT(SER_DTR == TIOCM_DTR / 2);
3220CTASSERT(SER_RTS == TIOCM_RTS / 2);
3221CTASSERT(SER_STX == TIOCM_ST / 2);
3222CTASSERT(SER_SRX == TIOCM_SR / 2);
3223CTASSERT(SER_CTS == TIOCM_CTS / 2);
3224CTASSERT(SER_DCD == TIOCM_DCD / 2);
3225CTASSERT(SER_RI == TIOCM_RI / 2);
3226CTASSERT(SER_DSR == TIOCM_DSR / 2);
3227
3228