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