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