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