tty.c revision 151383
11541Srgrimes/*-
21541Srgrimes * Copyright (c) 1982, 1986, 1990, 1991, 1993
31549Srgrimes *	The Regents of the University of California.  All rights reserved.
41549Srgrimes * (c) UNIX System Laboratories, Inc.
59507Sdg * All or some portions of this file are derived from material licensed
69507Sdg * to the University of California by American Telephone and Telegraph
71541Srgrimes * Co. or Unix System Laboratories, Inc. and are reproduced herein with
81541Srgrimes * the permission of UNIX System Laboratories, Inc.
91541Srgrimes *
101541Srgrimes * Copyright (c) 2002 Networks Associates Technologies, Inc.
111541Srgrimes * All rights reserved.
121541Srgrimes *
131541Srgrimes * Portions of this software were developed for the FreeBSD Project by
141541Srgrimes * ThinkSec AS and NAI Labs, the Security Research Division of Network
151541Srgrimes * Associates, Inc.  under DARPA/SPAWAR contract N66001-01-C-8035
161541Srgrimes * ("CBOSS"), as part of the DARPA CHATS research program.
171541Srgrimes *
181541Srgrimes * Redistribution and use in source and binary forms, with or without
191541Srgrimes * modification, are permitted provided that the following conditions
201541Srgrimes * are met:
211541Srgrimes * 1. Redistributions of source code must retain the above copyright
221541Srgrimes *    notice, this list of conditions and the following disclaimer.
231541Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
241541Srgrimes *    notice, this list of conditions and the following disclaimer in the
251541Srgrimes *    documentation and/or other materials provided with the distribution.
261541Srgrimes * 4. Neither the name of the University nor the names of its contributors
271541Srgrimes *    may be used to endorse or promote products derived from this software
281541Srgrimes *    without specific prior written permission.
291541Srgrimes *
301541Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
311541Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
321541Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
331541Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
341541Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
351541Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
361541Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
371541Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
381541Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
391541Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
401549Srgrimes * SUCH DAMAGE.
4112423Sphk *
421541Srgrimes *	@(#)tty.c	8.8 (Berkeley) 1/21/94
431541Srgrimes */
441541Srgrimes
451541Srgrimes/*-
461541Srgrimes * TODO:
471541Srgrimes *	o Fix races for sending the start char in ttyflush().
481549Srgrimes *	o Handle inter-byte timeout for "MIN > 0, TIME > 0" in ttyselect().
491549Srgrimes *	  With luck, there will be MIN chars before select() returns().
509507Sdg *	o Handle CLOCAL consistently for ptys.  Perhaps disallow setting it.
517695Sdg *	o Don't allow input in TS_ZOMBIE case.  It would be visible through
521549Srgrimes *	  FIONREAD.
531549Srgrimes *	o Do the new sio locking stuff here and use it to avoid special
541541Srgrimes *	  case for EXTPROC?
551541Srgrimes *	o Lock PENDIN too?
565455Sdg *	o Move EXTPROC and/or PENDIN to t_state?
571541Srgrimes *	o Wrap most of ttioctl in spltty/splx.
581541Srgrimes *	o Implement TIOCNOTTY or remove it from <sys/ioctl.h>.
591541Srgrimes *	o Send STOP if IXOFF is toggled off while TS_TBLOCK is set.
601541Srgrimes *	o Don't allow certain termios flags to affect disciplines other
611541Srgrimes *	  than TTYDISC.  Cancel their effects before switch disciplines
629507Sdg *	  and ignore them if they are set while we are in another
631541Srgrimes *	  discipline.
641541Srgrimes *	o Now that historical speed conversions are handled here, don't
651541Srgrimes *	  do them in drivers.
669507Sdg *	o Check for TS_CARR_ON being set while everything is closed and not
671541Srgrimes *	  waiting for carrier.  TS_CARR_ON isn't cleared if nothing is open,
681541Srgrimes *	  so it would live until the next open even if carrier drops.
6911943Sbde *	o Restore TS_WOPEN since it is useful in pstat.  It must be cleared
7011943Sbde *	  only when _all_ openers leave open().
7111943Sbde */
7211943Sbde
7311943Sbde#include <sys/cdefs.h>
7411943Sbde__FBSDID("$FreeBSD: head/sys/kern/tty.c 151383 2005-10-16 20:22:56Z phk $");
751541Srgrimes
769507Sdg#include "opt_compat.h"
771541Srgrimes#include "opt_tty.h"
781541Srgrimes
799507Sdg#include <sys/param.h>
809507Sdg#include <sys/systm.h>
819507Sdg#include <sys/filio.h>
829507Sdg#include <sys/lock.h>
831541Srgrimes#include <sys/mutex.h>
841541Srgrimes#include <sys/namei.h>
8511943Sbde#include <sys/sx.h>
8611943Sbde#ifndef BURN_BRIDGES
8711943Sbde#if defined(COMPAT_43)
8811943Sbde#include <sys/ioctl_compat.h>
8911943Sbde#endif
9010556Sdyson#endif
911541Srgrimes#include <sys/proc.h>
921541Srgrimes#define	TTYDEFCHARS
931541Srgrimes#include <sys/tty.h>
941541Srgrimes#undef	TTYDEFCHARS
959507Sdg#include <sys/fcntl.h>
961549Srgrimes#include <sys/conf.h>
978416Sdg#include <sys/poll.h>
981541Srgrimes#include <sys/kernel.h>
991541Srgrimes#include <sys/vnode.h>
1001549Srgrimes#include <sys/serial.h>
1011541Srgrimes#include <sys/signalvar.h>
1029456Sdg#include <sys/resourcevar.h>
1031541Srgrimes#include <sys/malloc.h>
1041541Srgrimes#include <sys/filedesc.h>
1051541Srgrimes#include <sys/sched.h>
1061541Srgrimes#include <sys/sysctl.h>
1071541Srgrimes#include <sys/timepps.h>
1081541Srgrimes
1091827Sdg#include <machine/stdarg.h>
1101541Srgrimes
1119411Sdg#include <vm/vm.h>
1129411Sdg#include <vm/pmap.h>
1131541Srgrimes#include <vm/vm_map.h>
1149411Sdg
1159411SdgMALLOC_DEFINE(M_TTYS, "ttys", "tty data structures");
1161541Srgrimes
1179411Sdglong tk_cancc;
1189411Sdglong tk_nin;
1199411Sdglong tk_nout;
1209411Sdglong tk_rawcc;
1219411Sdg
1229411Sdgstatic	d_open_t	ttysopen;
1239411Sdgstatic	d_close_t	ttysclose;
1249411Sdgstatic	d_read_t	ttysrdwr;
1259411Sdgstatic	d_ioctl_t	ttysioctl;
1269411Sdgstatic	d_purge_t	ttypurge;
1279507Sdg
1289356Sdg/* Default cdevsw for common tty devices */
1299507Sdgstatic struct cdevsw tty_cdevsw = {
1305455Sdg	.d_version =	D_VERSION,
1319507Sdg	.d_open =	ttyopen,
1321541Srgrimes	.d_close =	ttyclose,
1331541Srgrimes	.d_ioctl =	ttyioctl,
1341541Srgrimes	.d_purge =	ttypurge,
1359507Sdg	.d_name =	"ttydrv",
1369456Sdg	.d_flags =	D_TTY | D_NEEDGIANT,
1371827Sdg};
1381541Srgrimes
1399507Sdg/* Cdevsw for slave tty devices */
1401541Srgrimesstatic struct cdevsw ttys_cdevsw = {
1411541Srgrimes	.d_version =	D_VERSION,
1429507Sdg	.d_open =	ttysopen,
1431549Srgrimes	.d_close =	ttysclose,
1449507Sdg	.d_read =	ttysrdwr,
1459507Sdg	.d_write =	ttysrdwr,
1461541Srgrimes	.d_ioctl =	ttysioctl,
1471541Srgrimes	.d_name =	"TTYS",
1489507Sdg	.d_flags =	D_TTY | D_NEEDGIANT,
1499507Sdg};
1501541Srgrimes
1519507Sdgstatic int	proc_compare(struct proc *p1, struct proc *p2);
1521541Srgrimesstatic int	ttnread(struct tty *tp);
1539411Sdgstatic void	ttyecho(int c, struct tty *tp);
1549411Sdgstatic int	ttyoutput(int c, struct tty *tp);
1557695Sdgstatic void	ttypend(struct tty *tp);
1569411Sdgstatic void	ttyretype(struct tty *tp);
1579411Sdgstatic void	ttyrub(int c, struct tty *tp);
1589411Sdgstatic void	ttyrubo(struct tty *tp, int cnt);
1599411Sdgstatic void	ttyunblock(struct tty *tp);
1609411Sdgstatic int	ttywflush(struct tty *tp);
1619411Sdgstatic int	filt_ttyread(struct knote *kn, long hint);
1629507Sdgstatic void	filt_ttyrdetach(struct knote *kn);
1631541Srgrimesstatic int	filt_ttywrite(struct knote *kn, long hint);
1641541Srgrimesstatic void	filt_ttywdetach(struct knote *kn);
1651549Srgrimes
1669507Sdg/*
1679507Sdg * Table with character classes and parity. The 8th bit indicates parity,
1681541Srgrimes * the 7th bit indicates the character is an alphameric or underscore (for
1699507Sdg * ALTWERASE), and the low 6 bits indicate delay type.  If the low 6 bits
1701541Srgrimes * are 0 then the character needs no special processing on output; classes
1719507Sdg * other than 0 might be translated or (not currently) require delays.
1729507Sdg */
1739507Sdg#define	E	0x00	/* Even parity. */
1749507Sdg#define	O	0x80	/* Odd parity. */
1755455Sdg#define	PARITY(c)	(char_type[c] & O)
1769507Sdg
1779507Sdg#define	ALPHA	0x40	/* Alpha or underscore. */
1789507Sdg#define	ISALPHA(c)	(char_type[(c) & TTY_CHARMASK] & ALPHA)
1795455Sdg
1805455Sdg#define	CCLASSMASK	0x3f
1811541Srgrimes#define	CCLASS(c)	(char_type[c] & CCLASSMASK)
1821541Srgrimes
1839507Sdg#define	BS	BACKSPACE
1841827Sdg#define	CC	CONTROL
1859507Sdg#define	CR	RETURN
1869507Sdg#define	NA	ORDINARY | ALPHA
1879507Sdg#define	NL	NEWLINE
1889507Sdg#define	NO	ORDINARY
1891549Srgrimes#define	TB	TAB
1901541Srgrimes#define	VT	VTAB
1911549Srgrimes
1929507Sdgstatic u_char const char_type[] = {
1939507Sdg	E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC,	/* nul - bel */
1941541Srgrimes	O|BS, E|TB, E|NL, O|CC, E|VT, O|CR, O|CC, E|CC, /* bs - si */
1959507Sdg	O|CC, E|CC, E|CC, O|CC, E|CC, O|CC, O|CC, E|CC, /* dle - etb */
1969507Sdg	E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC, /* can - us */
1971541Srgrimes	O|NO, E|NO, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* sp - ' */
1989507Sdg	E|NO, O|NO, O|NO, E|NO, O|NO, E|NO, E|NO, O|NO, /* ( - / */
1991541Srgrimes	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* 0 - 7 */
20012423Sphk	O|NA, E|NA, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* 8 - ? */
20110556Sdyson	O|NO, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* @ - G */
20211701Sdyson	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* H - O */
20311701Sdyson	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* P - W */
20411701Sdyson	O|NA, E|NA, E|NA, O|NO, E|NO, O|NO, O|NO, O|NA, /* X - _ */
2051541Srgrimes	E|NO, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* ` - g */
2061541Srgrimes	O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* h - o */
2075455Sdg	O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* p - w */
2085455Sdg	E|NA, O|NA, O|NA, E|NO, O|NO, E|NO, E|NO, O|CC, /* x - del */
2091541Srgrimes	/*
2109507Sdg	 * Meta chars; should be settable per character set;
2114797Sdg	 * for now, treat them all as normal characters.
2121541Srgrimes	 */
21311576Sdg	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
21410556Sdyson	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
21510556Sdyson	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
21610556Sdyson	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
21710556Sdyson	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
2188876Srgrimes	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
2199507Sdg	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
22010702Sdyson	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
22110576Sdyson	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
22210556Sdyson	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
22310556Sdyson	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
22410556Sdyson	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
22510556Sdyson	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
22610556Sdyson	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
22710556Sdyson	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
22810669Sdyson	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
22910556Sdyson};
23010669Sdyson#undef	BS
23110669Sdyson#undef	CC
23210669Sdyson#undef	CR
23310669Sdyson#undef	NA
23410669Sdyson#undef	NL
23510556Sdyson#undef	NO
23610576Sdyson#undef	TB
2371541Srgrimes#undef	VT
2381541Srgrimes
2391541Srgrimes/* Macros to clear/set/test flags. */
2401541Srgrimes#define	SET(t, f)	(t) |= (f)
2419507Sdg#define	CLR(t, f)	(t) &= ~(f)
2421541Srgrimes#define	ISSET(t, f)	((t) & (f))
2431541Srgrimes
2441541Srgrimes#undef MAX_INPUT		/* XXX wrong in <sys/syslimits.h> */
2451541Srgrimes#define	MAX_INPUT	TTYHOG	/* XXX limit is usually larger for !ICANON */
2461541Srgrimes
2471541Srgrimes/*
2481541Srgrimes * list of struct tty where pstat(8) can pick it up with sysctl
2491541Srgrimes *
2505455Sdg * The lock order is to grab the list mutex before the tty mutex.
2511541Srgrimes * Together with additions going on the tail of the list, this allows
2529507Sdg * the sysctl to avoid doing retries.
2531541Srgrimes */
2549507Sdgstatic	TAILQ_HEAD(, tty) tty_list = TAILQ_HEAD_INITIALIZER(tty_list);
2551541Srgrimesstatic struct mtx tty_list_mutex;
2561827Sdg
2571541Srgrimesstatic struct unrhdr *tty_unit;
2581541Srgrimes
2591541Srgrimesstatic int  drainwait = 5*60;
2609507SdgSYSCTL_INT(_kern, OID_AUTO, drainwait, CTLFLAG_RW, &drainwait,
2613374Sdg	0, "Output drain timeout in seconds");
2621827Sdg
2631541Srgrimesstatic struct tty *
2641827Sdgtty_gettp(struct cdev *dev)
2651541Srgrimes{
2669507Sdg	struct tty *tp;
2679507Sdg	struct cdevsw *csw;
2685455Sdg
2699507Sdg	csw = dev_refthread(dev);
2705455Sdg	KASSERT(csw != NULL, ("No cdevsw in ttycode (%s)", devtoname(dev)));
2711827Sdg	KASSERT(csw->d_flags & D_TTY,
2721827Sdg	    ("non D_TTY (%s) in tty code", devtoname(dev)));
2731827Sdg	dev_relthread(dev);
2741827Sdg	tp = dev->si_tty;
2751827Sdg	KASSERT(tp != NULL,
2761827Sdg	    ("no tty pointer on (%s) in tty code", devtoname(dev)));
2771827Sdg	return (tp);
2781827Sdg}
2791827Sdg
2801827Sdg/*
2811827Sdg * Initial open of tty, or (re)entry to standard tty line discipline.
2821827Sdg */
2835455Sdgint
2841827Sdgtty_open(struct cdev *device, struct tty *tp)
2851827Sdg{
2861827Sdg	int s;
2871541Srgrimes
2889507Sdg	s = spltty();
2891827Sdg	tp->t_dev = device;
2901541Srgrimes	tp->t_hotchar = 0;
2911541Srgrimes	if (!ISSET(tp->t_state, TS_ISOPEN)) {
2921541Srgrimes		ttyref(tp);
2931541Srgrimes		SET(tp->t_state, TS_ISOPEN);
2941541Srgrimes		if (ISSET(tp->t_cflag, CLOCAL))
2951541Srgrimes			SET(tp->t_state, TS_CONNECTED);
2969507Sdg		bzero(&tp->t_winsize, sizeof(tp->t_winsize));
2971541Srgrimes	}
2989507Sdg	/* XXX don't hang forever on output */
2999507Sdg	if (tp->t_timeout < 0)
3001541Srgrimes		tp->t_timeout = drainwait*hz;
3019507Sdg	ttsetwater(tp);
3029507Sdg	splx(s);
3039507Sdg	return (0);
3049507Sdg}
3059507Sdg
3069507Sdg/*
3079507Sdg * Handle close() on a tty line: flush and set to initial state,
3081827Sdg * bumping generation number so that pending read/write calls
3099507Sdg * can detect recycling of the tty.
3101541Srgrimes * XXX our caller should have done `spltty(); l_close(); tty_close();'
3119507Sdg * and l_close() should have flushed, but we repeat the spltty() and
3129507Sdg * the flush in case there are buggy callers.
3139507Sdg */
3147162Sdgint
3159507Sdgtty_close(struct tty *tp)
3167162Sdg{
3177162Sdg	int s;
3181541Srgrimes
3191541Srgrimes	funsetown(&tp->t_sigio);
3201541Srgrimes	s = spltty();
3211541Srgrimes	if (constty == tp)
3221541Srgrimes		constty_clear();
3237162Sdg
3241541Srgrimes	ttyflush(tp, FREAD | FWRITE);
3257162Sdg	clist_free_cblocks(&tp->t_canq);
3267162Sdg	clist_free_cblocks(&tp->t_outq);
3277162Sdg	clist_free_cblocks(&tp->t_rawq);
3287162Sdg
3291549Srgrimes	tp->t_gen++;
3309507Sdg	tp->t_line = TTYDISC;
3311549Srgrimes	tp->t_hotchar = 0;
3329507Sdg	tp->t_pgrp = NULL;
3331549Srgrimes	tp->t_session = NULL;
3349507Sdg	tp->t_state = 0;
3351549Srgrimes	knlist_clear(&tp->t_rsel.si_note, 0);
3361549Srgrimes	knlist_clear(&tp->t_wsel.si_note, 0);
3371549Srgrimes	ttyrel(tp);
3381549Srgrimes	splx(s);
3399356Sdg	return (0);
3405455Sdg}
3419507Sdg
3425455Sdg#define	FLUSHQ(q) {							\
3439507Sdg	if ((q)->c_cc)							\
3449507Sdg		ndflush(q, (q)->c_cc);					\
3459507Sdg}
3469507Sdg
3479507Sdg/* Is 'c' a line delimiter ("break" character)? */
3481549Srgrimes#define	TTBREAKC(c, lflag)							\
3491541Srgrimes	((c) == '\n' || (((c) == cc[VEOF] ||				\
3501541Srgrimes	  (c) == cc[VEOL] || ((c) == cc[VEOL2] && lflag & IEXTEN)) &&	\
3511549Srgrimes	 (c) != _POSIX_VDISABLE))
3521549Srgrimes
3531549Srgrimes/*
3541541Srgrimes * Process input of a single character received on a tty.
3551549Srgrimes */
3561549Srgrimesint
3571549Srgrimesttyinput(int c, struct tty *tp)
3581549Srgrimes{
3591549Srgrimes	tcflag_t iflag, lflag;
3601549Srgrimes	cc_t *cc;
3611549Srgrimes	int i, err;
3621549Srgrimes
3631549Srgrimes	/*
3646151Sdg	 * If input is pending take it first.
3651549Srgrimes	 */
3661549Srgrimes	lflag = tp->t_lflag;
3676151Sdg	if (ISSET(lflag, PENDIN))
3681549Srgrimes		ttypend(tp);
3695455Sdg	/*
3705455Sdg	 * Gather stats.
3711549Srgrimes	 */
3721549Srgrimes	if (ISSET(lflag, ICANON)) {
3735455Sdg		++tk_cancc;
3745455Sdg		++tp->t_cancc;
3751549Srgrimes	} else {
3765455Sdg		++tk_rawcc;
3775455Sdg		++tp->t_rawcc;
3785455Sdg	}
37911701Sdyson	++tk_nin;
38011701Sdyson
38111701Sdyson	/*
3821549Srgrimes	 * Block further input iff:
3831549Srgrimes	 * current input > threshold AND input is available to user program
3841549Srgrimes	 * AND input flow control is enabled and not yet invoked.
3851549Srgrimes	 * The 3 is slop for PARMRK.
38610551Sdyson	 */
3871549Srgrimes	iflag = tp->t_iflag;
3886151Sdg	if (tp->t_rawq.c_cc + tp->t_canq.c_cc > tp->t_ihiwat - 3 &&
3891549Srgrimes	    (!ISSET(lflag, ICANON) || tp->t_canq.c_cc != 0) &&
3906151Sdg	    (ISSET(tp->t_cflag, CRTS_IFLOW) || ISSET(iflag, IXOFF)) &&
3916626Sdg	    !ISSET(tp->t_state, TS_TBLOCK))
3926151Sdg		ttyblock(tp);
3936151Sdg
3946151Sdg	/* Handle exceptional conditions (break, parity, framing). */
3956151Sdg	cc = tp->t_cc;
3966151Sdg	err = (ISSET(c, TTY_ERRORMASK));
3976151Sdg	if (err) {
3981549Srgrimes		CLR(c, TTY_ERRORMASK);
3991549Srgrimes		if (ISSET(err, TTY_BI)) {
4001549Srgrimes			if (ISSET(iflag, IGNBRK))
4011549Srgrimes				return (0);
4021549Srgrimes			if (ISSET(iflag, BRKINT)) {
4031549Srgrimes				ttyflush(tp, FREAD | FWRITE);
4041549Srgrimes				if (tp->t_pgrp != NULL) {
4051549Srgrimes					PGRP_LOCK(tp->t_pgrp);
4061549Srgrimes					pgsignal(tp->t_pgrp, SIGINT, 1);
4071549Srgrimes					PGRP_UNLOCK(tp->t_pgrp);
4081549Srgrimes				}
4091549Srgrimes				goto endcase;
4109507Sdg			}
4111549Srgrimes			if (ISSET(iflag, PARMRK))
4121549Srgrimes				goto parmrk;
4131549Srgrimes		} else if ((ISSET(err, TTY_PE) && ISSET(iflag, INPCK))
4141549Srgrimes			|| ISSET(err, TTY_FE)) {
4151549Srgrimes			if (ISSET(iflag, IGNPAR))
4161549Srgrimes				return (0);
4179507Sdg			else if (ISSET(iflag, PARMRK)) {
4189507Sdgparmrk:
4191549Srgrimes				if (tp->t_rawq.c_cc + tp->t_canq.c_cc >
4201549Srgrimes				    MAX_INPUT - 3)
4215455Sdg					goto input_overflow;
4225455Sdg				(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
4231549Srgrimes				(void)putc(0 | TTY_QUOTE, &tp->t_rawq);
4241549Srgrimes				(void)putc(c | TTY_QUOTE, &tp->t_rawq);
4251549Srgrimes				goto endcase;
4265455Sdg			} else
4271549Srgrimes				c = 0;
4285455Sdg		}
4291549Srgrimes	}
4309507Sdg
43111701Sdyson	if (!ISSET(tp->t_state, TS_TYPEN) && ISSET(iflag, ISTRIP))
43211701Sdyson		CLR(c, 0x80);
43311701Sdyson	if (!ISSET(lflag, EXTPROC)) {
4341549Srgrimes		/*
4351549Srgrimes		 * Check for literal nexting very first
4367178Sdg		 */
43710551Sdyson		if (ISSET(tp->t_state, TS_LNCH)) {
4381549Srgrimes			SET(c, TTY_QUOTE);
4391549Srgrimes			CLR(tp->t_state, TS_LNCH);
4401549Srgrimes		}
4411827Sdg		/*
4421827Sdg		 * Scan for special characters.  This code
4435455Sdg		 * is really just a big case statement with
4445455Sdg		 * non-constant cases.  The bottom of the
4451549Srgrimes		 * case statement is labeled ``endcase'', so goto
4466151Sdg		 * it after a case match, or similar.
4471827Sdg		 */
4481549Srgrimes
4491549Srgrimes		/*
4501827Sdg		 * Control chars which aren't controlled
4511549Srgrimes		 * by ICANON, ISIG, or IXON.
4521549Srgrimes		 */
4531549Srgrimes		if (ISSET(lflag, IEXTEN)) {
4541549Srgrimes			if (CCEQ(cc[VLNEXT], c)) {
4551827Sdg				if (ISSET(lflag, ECHO)) {
4561549Srgrimes					if (ISSET(lflag, ECHOE)) {
4571827Sdg						(void)ttyoutput('^', tp);
4581549Srgrimes						(void)ttyoutput('\b', tp);
4591549Srgrimes					} else
4606626Sdg						ttyecho(c, tp);
4615455Sdg				}
4621549Srgrimes				SET(tp->t_state, TS_LNCH);
4631549Srgrimes				goto endcase;
4641827Sdg			}
4651827Sdg			if (CCEQ(cc[VDISCARD], c)) {
4661549Srgrimes				if (ISSET(lflag, FLUSHO))
4671549Srgrimes					CLR(tp->t_lflag, FLUSHO);
4681827Sdg				else {
4691549Srgrimes					ttyflush(tp, FWRITE);
4701549Srgrimes					ttyecho(c, tp);
4711549Srgrimes					if (tp->t_rawq.c_cc + tp->t_canq.c_cc)
4729356Sdg						ttyretype(tp);
4731549Srgrimes					SET(tp->t_lflag, FLUSHO);
4741549Srgrimes				}
4751549Srgrimes				goto startoutput;
4761549Srgrimes			}
4771549Srgrimes		}
4781827Sdg		/*
4791827Sdg		 * Signals.
4801827Sdg		 */
4811549Srgrimes		if (ISSET(lflag, ISIG)) {
4821827Sdg			if (CCEQ(cc[VINTR], c) || CCEQ(cc[VQUIT], c)) {
4831549Srgrimes				if (!ISSET(lflag, NOFLSH))
4845455Sdg					ttyflush(tp, FREAD | FWRITE);
48510556Sdyson				ttyecho(c, tp);
4861549Srgrimes				if (tp->t_pgrp != NULL) {
48710669Sdyson					PGRP_LOCK(tp->t_pgrp);
4881549Srgrimes					pgsignal(tp->t_pgrp,
4891549Srgrimes					    CCEQ(cc[VINTR], c) ? SIGINT : SIGQUIT, 1);
4901549Srgrimes					PGRP_UNLOCK(tp->t_pgrp);
4911549Srgrimes				}
4925455Sdg				goto endcase;
49310669Sdyson			}
4941827Sdg			if (CCEQ(cc[VSUSP], c)) {
4954207Sdg				if (!ISSET(lflag, NOFLSH))
4961549Srgrimes					ttyflush(tp, FREAD);
4971549Srgrimes				ttyecho(c, tp);
4981549Srgrimes				if (tp->t_pgrp != NULL) {
4991549Srgrimes					PGRP_LOCK(tp->t_pgrp);
5001549Srgrimes					pgsignal(tp->t_pgrp, SIGTSTP, 1);
5011549Srgrimes					PGRP_UNLOCK(tp->t_pgrp);
5021549Srgrimes				}
5031549Srgrimes				goto endcase;
5041549Srgrimes			}
5051549Srgrimes		}
5069507Sdg		/*
5079507Sdg		 * Handle start/stop characters.
5081549Srgrimes		 */
5091549Srgrimes		if (ISSET(iflag, IXON)) {
5101541Srgrimes			if (CCEQ(cc[VSTOP], c)) {
5111541Srgrimes				if (!ISSET(tp->t_state, TS_TTSTOP)) {
5125455Sdg					SET(tp->t_state, TS_TTSTOP);
5135455Sdg					(*tp->t_stop)(tp, 0);
5141549Srgrimes					return (0);
5151549Srgrimes				}
5161549Srgrimes				if (!CCEQ(cc[VSTART], c))
5171827Sdg					return (0);
5181549Srgrimes				/*
5191549Srgrimes				 * if VSTART == VSTOP then toggle
5201549Srgrimes				 */
5219507Sdg				goto endcase;
5221549Srgrimes			}
5231549Srgrimes			if (CCEQ(cc[VSTART], c))
5241549Srgrimes				goto restartoutput;
5259507Sdg		}
5269507Sdg		/*
5277178Sdg		 * IGNCR, ICRNL, & INLCR
5285455Sdg		 */
5295455Sdg		if (c == '\r') {
5305455Sdg			if (ISSET(iflag, IGNCR))
5315455Sdg				return (0);
5321549Srgrimes			else if (ISSET(iflag, ICRNL))
5337178Sdg				c = '\n';
5341827Sdg		} else if (c == '\n' && ISSET(iflag, INLCR))
5351549Srgrimes			c = '\r';
5361549Srgrimes	}
5371549Srgrimes	if (!ISSET(tp->t_lflag, EXTPROC) && ISSET(lflag, ICANON)) {
5385455Sdg		/*
5391549Srgrimes		 * From here on down canonical mode character
5401549Srgrimes		 * processing takes place.
5411549Srgrimes		 */
5421827Sdg		/*
5431549Srgrimes		 * erase or erase2 (^H / ^?)
5449507Sdg		 */
5451549Srgrimes		if (CCEQ(cc[VERASE], c) || CCEQ(cc[VERASE2], c) ) {
5461549Srgrimes			if (tp->t_rawq.c_cc)
5471549Srgrimes				ttyrub(unputc(&tp->t_rawq), tp);
5481549Srgrimes			goto endcase;
5491549Srgrimes		}
5501549Srgrimes		/*
5511827Sdg		 * kill (^U)
5521549Srgrimes		 */
5531549Srgrimes		if (CCEQ(cc[VKILL], c)) {
5541549Srgrimes			if (ISSET(lflag, ECHOKE) &&
5551549Srgrimes			    tp->t_rawq.c_cc == tp->t_rocount &&
5565455Sdg			    !ISSET(lflag, ECHOPRT))
55710669Sdyson				while (tp->t_rawq.c_cc)
5584207Sdg					ttyrub(unputc(&tp->t_rawq), tp);
5591549Srgrimes			else {
5601549Srgrimes				ttyecho(c, tp);
5611549Srgrimes				if (ISSET(lflag, ECHOK) ||
5621549Srgrimes				    ISSET(lflag, ECHOKE))
5631549Srgrimes					ttyecho('\n', tp);
56410556Sdyson				FLUSHQ(&tp->t_rawq);
5651549Srgrimes				tp->t_rocount = 0;
5669507Sdg			}
5679507Sdg			CLR(tp->t_state, TS_LOCAL);
5681549Srgrimes			goto endcase;
5699507Sdg		}
5709507Sdg		/*
5711549Srgrimes		 * word erase (^W)
57210556Sdyson		 */
57310556Sdyson		if (CCEQ(cc[VWERASE], c) && ISSET(lflag, IEXTEN)) {
57410556Sdyson			int ctype;
57511701Sdyson
57610556Sdyson			/*
57711943Sbde			 * erase whitespace
57810556Sdyson			 */
57910556Sdyson			while ((c = unputc(&tp->t_rawq)) == ' ' || c == '\t')
58010556Sdyson				ttyrub(c, tp);
58110556Sdyson			if (c == -1)
58210556Sdyson				goto endcase;
58310556Sdyson			/*
58410556Sdyson			 * erase last char of word and remember the
58510556Sdyson			 * next chars type (for ALTWERASE)
58610556Sdyson			 */
58710556Sdyson			ttyrub(c, tp);
58810556Sdyson			c = unputc(&tp->t_rawq);
5891541Srgrimes			if (c == -1)
5909507Sdg				goto endcase;
5911549Srgrimes			if (c == ' ' || c == '\t') {
5926151Sdg				(void)putc(c, &tp->t_rawq);
5936151Sdg				goto endcase;
5947178Sdg			}
5955455Sdg			ctype = ISALPHA(c);
5965455Sdg			/*
5971549Srgrimes			 * erase rest of word
5989507Sdg			 */
59911701Sdyson			do {
60011701Sdyson				ttyrub(c, tp);
60111701Sdyson				c = unputc(&tp->t_rawq);
6021549Srgrimes				if (c == -1)
6031549Srgrimes					goto endcase;
6041549Srgrimes			} while (c != ' ' && c != '\t' &&
6051827Sdg			    (!ISSET(lflag, ALTWERASE) || ISALPHA(c) == ctype));
6061549Srgrimes			(void)putc(c, &tp->t_rawq);
6071827Sdg			goto endcase;
6081827Sdg		}
6091549Srgrimes		/*
6105455Sdg		 * reprint line (^R)
6111827Sdg		 */
6121549Srgrimes		if (CCEQ(cc[VREPRINT], c) && ISSET(lflag, IEXTEN)) {
6131887Sdg			ttyretype(tp);
6141549Srgrimes			goto endcase;
61510551Sdyson		}
6161549Srgrimes		/*
6171549Srgrimes		 * ^T - kernel info and generate SIGINFO
6181549Srgrimes		 */
6191549Srgrimes		if (CCEQ(cc[VSTATUS], c) && ISSET(lflag, IEXTEN)) {
6201549Srgrimes			if (ISSET(lflag, ISIG) && tp->t_pgrp != NULL) {
6213612Sdg				PGRP_LOCK(tp->t_pgrp);
6223612Sdg				pgsignal(tp->t_pgrp, SIGINFO, 1);
6239507Sdg				PGRP_UNLOCK(tp->t_pgrp);
6241549Srgrimes			}
6251827Sdg			if (!ISSET(lflag, NOKERNINFO))
6261827Sdg				ttyinfo(tp);
6271827Sdg			goto endcase;
6281827Sdg		}
6291827Sdg	}
6301827Sdg	/*
6315455Sdg	 * Check for input buffer overflow
6321827Sdg	 */
6331549Srgrimes	if (tp->t_rawq.c_cc + tp->t_canq.c_cc >= MAX_INPUT) {
6341549Srgrimesinput_overflow:
6351549Srgrimes		if (ISSET(iflag, IMAXBEL)) {
6361549Srgrimes			if (tp->t_outq.c_cc < tp->t_ohiwat)
6371549Srgrimes				(void)ttyoutput(CTRL('g'), tp);
6383612Sdg		}
6393612Sdg		goto endcase;
6409507Sdg	}
6411549Srgrimes
6421549Srgrimes	if (   c == 0377 && ISSET(iflag, PARMRK) && !ISSET(iflag, ISTRIP)
6435455Sdg	     && ISSET(iflag, IGNBRK|IGNPAR) != (IGNBRK|IGNPAR))
6445455Sdg		(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
6451549Srgrimes
6465455Sdg	/*
6475455Sdg	 * Put data char in q for user and
6485455Sdg	 * wakeup on seeing a line delimiter.
6495455Sdg	 */
6505455Sdg	if (putc(c, &tp->t_rawq) >= 0) {
6511549Srgrimes		if (!ISSET(lflag, ICANON)) {
6525455Sdg			ttwakeup(tp);
6531549Srgrimes			ttyecho(c, tp);
6547178Sdg			goto endcase;
6555455Sdg		}
6565455Sdg		if (TTBREAKC(c, lflag)) {
6575455Sdg			tp->t_rocount = 0;
6581549Srgrimes			catq(&tp->t_rawq, &tp->t_canq);
6596151Sdg			ttwakeup(tp);
6601549Srgrimes		} else if (tp->t_rocount++ == 0)
6616151Sdg			tp->t_rocol = tp->t_column;
6621549Srgrimes		if (ISSET(tp->t_state, TS_ERASE)) {
6636151Sdg			/*
6646151Sdg			 * end of prterase \.../
6656151Sdg			 */
6669507Sdg			CLR(tp->t_state, TS_ERASE);
6679507Sdg			(void)ttyoutput('/', tp);
6689507Sdg		}
6696151Sdg		i = tp->t_column;
6701549Srgrimes		ttyecho(c, tp);
6716151Sdg		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ECHO)) {
6726151Sdg			/*
6736151Sdg			 * Place the cursor over the '^' of the ^D.
6741549Srgrimes			 */
6756151Sdg			i = imin(2, tp->t_column - i);
6769507Sdg			while (i > 0) {
6776151Sdg				(void)ttyoutput('\b', tp);
6789507Sdg				i--;
6796151Sdg			}
6806151Sdg		}
6811549Srgrimes	}
6829507Sdgendcase:
6839507Sdg	/*
6846151Sdg	 * IXANY means allow any character to restart output.
6856151Sdg	 */
6866151Sdg	if (ISSET(tp->t_state, TS_TTSTOP) &&
6876151Sdg	    !ISSET(iflag, IXANY) && cc[VSTART] != cc[VSTOP])
6881549Srgrimes		return (0);
6896151Sdgrestartoutput:
6901549Srgrimes	CLR(tp->t_lflag, FLUSHO);
6911549Srgrimes	CLR(tp->t_state, TS_TTSTOP);
6921549Srgrimesstartoutput:
6931827Sdg	return (ttstart(tp));
6941827Sdg}
6951549Srgrimes
6961549Srgrimes/*
6971549Srgrimes * Output a single character on a tty, doing output processing
6981549Srgrimes * as needed (expanding tabs, newline processing, etc.).
6991549Srgrimes * Returns < 0 if succeeds, otherwise returns char to resend.
7001549Srgrimes * Must be recursive.
7011549Srgrimes */
7021549Srgrimesstatic int
7036151Sdgttyoutput(int c, struct tty *tp)
7041549Srgrimes{
7051549Srgrimes	tcflag_t oflag;
7061549Srgrimes	int col, s;
7075455Sdg
7081827Sdg	oflag = tp->t_oflag;
7091549Srgrimes	if (!ISSET(oflag, OPOST)) {
7101549Srgrimes		if (ISSET(tp->t_lflag, FLUSHO))
7111549Srgrimes			return (-1);
7121549Srgrimes		if (putc(c, &tp->t_outq))
7139507Sdg			return (c);
7149507Sdg		tk_nout++;
7151549Srgrimes		tp->t_outcc++;
7161549Srgrimes		return (-1);
7171549Srgrimes	}
7181549Srgrimes	/*
7191827Sdg	 * Do tab expansion if OXTABS is set.  Special case if we external
7201549Srgrimes	 * processing, we don't do the tab expansion because we'll probably
7211549Srgrimes	 * get it wrong.  If tab expansion needs to be done, let it happen
7225841Sdg	 * externally.
7235455Sdg	 */
7241887Sdg	CLR(c, ~TTY_CHARMASK);
7251549Srgrimes	if (c == '\t' &&
7261549Srgrimes	    ISSET(oflag, OXTABS) && !ISSET(tp->t_lflag, EXTPROC)) {
7271549Srgrimes		c = 8 - (tp->t_column & 7);
7281887Sdg		if (!ISSET(tp->t_lflag, FLUSHO)) {
7291549Srgrimes			s = spltty();		/* Don't interrupt tabs. */
7301549Srgrimes			c -= b_to_q("        ", c, &tp->t_outq);
7311549Srgrimes			tk_nout += c;
7321549Srgrimes			tp->t_outcc += c;
7331549Srgrimes			splx(s);
7341549Srgrimes		}
7351549Srgrimes		tp->t_column += c;
7361827Sdg		return (c ? -1 : '\t');
7371549Srgrimes	}
7381827Sdg	if (c == CEOT && ISSET(oflag, ONOEOT))
7391549Srgrimes		return (-1);
7406626Sdg
7415455Sdg	/*
7421549Srgrimes	 * Newline translation: if ONLCR is set,
7431549Srgrimes	 * translate newline into "\r\n".
7441549Srgrimes	 */
7453612Sdg	if (c == '\n' && ISSET(tp->t_oflag, ONLCR)) {
7463612Sdg		tk_nout++;
7473612Sdg		tp->t_outcc++;
7481549Srgrimes		if (!ISSET(tp->t_lflag, FLUSHO) && putc('\r', &tp->t_outq))
7491549Srgrimes			return (c);
7503612Sdg	}
7511549Srgrimes	/* If OCRNL is set, translate "\r" into "\n". */
7521549Srgrimes	else if (c == '\r' && ISSET(tp->t_oflag, OCRNL))
7531549Srgrimes		c = '\n';
7541549Srgrimes	/* If ONOCR is set, don't transmit CRs when on column 0. */
7559356Sdg	else if (c == '\r' && ISSET(tp->t_oflag, ONOCR) && tp->t_column == 0)
7561549Srgrimes		return (-1);
7571549Srgrimes
7581549Srgrimes	tk_nout++;
7591549Srgrimes	tp->t_outcc++;
7601549Srgrimes	if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
7611549Srgrimes		return (c);
7621549Srgrimes
7631827Sdg	col = tp->t_column;
7641549Srgrimes	switch (CCLASS(c)) {
7655455Sdg	case BACKSPACE:
7661549Srgrimes		if (col > 0)
7671549Srgrimes			--col;
7681549Srgrimes		break;
7691549Srgrimes	case CONTROL:
7701549Srgrimes		break;
7711549Srgrimes	case NEWLINE:
7721549Srgrimes		if (ISSET(tp->t_oflag, ONLCR | ONLRET))
7732386Sdg			col = 0;
7745455Sdg		break;
7755455Sdg	case RETURN:
77610669Sdyson		col = 0;
7771549Srgrimes		break;
7781827Sdg	case ORDINARY:
7791549Srgrimes		++col;
7801827Sdg		break;
7811827Sdg	case TAB:
7821827Sdg		col = (col + 8) & ~7;
7831827Sdg		break;
7841827Sdg	}
7851549Srgrimes	tp->t_column = col;
7861827Sdg	return (-1);
7871549Srgrimes}
7881827Sdg
7891827Sdg/*
7901549Srgrimes * Ioctls for all tty devices.  Called after line-discipline specific ioctl
7911549Srgrimes * has been called to do discipline-specific functions and/or reject any
7925841Sdg * of these ioctl commands.
7931549Srgrimes */
7941549Srgrimes/* ARGSUSED */
7951549Srgrimesint
7961549Srgrimesttioctl(struct tty *tp, u_long cmd, void *data, int flag)
7971549Srgrimes{
7981549Srgrimes	struct proc *p;
7991549Srgrimes	struct thread *td;
8009507Sdg	struct pgrp *pgrp;
8011549Srgrimes	int s, error, bits, sig, sig2;
8024207Sdg
8031549Srgrimes	td = curthread;			/* XXX */
8041549Srgrimes	p = td->td_proc;
80510556Sdyson
80610556Sdyson	/* If the ioctl involves modification, hang if in the background. */
80710556Sdyson	switch (cmd) {
80810556Sdyson	case  TIOCCBRK:
80910556Sdyson	case  TIOCCONS:
81010556Sdyson	case  TIOCDRAIN:
81110556Sdyson	case  TIOCEXCL:
81210556Sdyson	case  TIOCFLUSH:
81310556Sdyson#ifdef TIOCHPCL
81410556Sdyson	case  TIOCHPCL:
81510556Sdyson#endif
81611701Sdyson	case  TIOCNXCL:
81710556Sdyson	case  TIOCSBRK:
81811943Sbde	case  TIOCSCTTY:
81910556Sdyson	case  TIOCSDRAINWAIT:
82010556Sdyson	case  TIOCSETA:
82110556Sdyson	case  TIOCSETAF:
82210556Sdyson	case  TIOCSETAW:
8231549Srgrimes	case  TIOCSETD:
8241549Srgrimes	case  TIOCSPGRP:
8251549Srgrimes	case  TIOCSTART:
82610556Sdyson	case  TIOCSTAT:
82710556Sdyson	case  TIOCSTI:
8289507Sdg	case  TIOCSTOP:
8291549Srgrimes	case  TIOCSWINSZ:
8305455Sdg#ifndef BURN_BRIDGES
8319507Sdg#if defined(COMPAT_43)
8325455Sdg	case  TIOCLBIC:
8331549Srgrimes	case  TIOCLBIS:
8347695Sdg	case  TIOCLSET:
8351549Srgrimes	case  TIOCSETC:
8367695Sdg	case OTIOCSETD:
8377695Sdg	case  TIOCSETN:
8387695Sdg	case  TIOCSETP:
8397695Sdg	case  TIOCSLTC:
8407695Sdg#endif
8411549Srgrimes#endif
8429507Sdg		sx_slock(&proctree_lock);
8431827Sdg		PROC_LOCK(p);
8441549Srgrimes		while (isbackground(p, tp) && !(p->p_flag & P_PPWAIT) &&
8451549Srgrimes		    !SIGISMEMBER(p->p_sigacts->ps_sigignore, SIGTTOU) &&
8465455Sdg		    !SIGISMEMBER(td->td_sigmask, SIGTTOU)) {
8479507Sdg			pgrp = p->p_pgrp;
8487695Sdg			PROC_UNLOCK(p);
8497695Sdg			if (pgrp->pg_jobc == 0) {
8505455Sdg				sx_sunlock(&proctree_lock);
8517178Sdg				return (EIO);
8527695Sdg			}
8537695Sdg			PGRP_LOCK(pgrp);
8541549Srgrimes			sx_sunlock(&proctree_lock);
8559507Sdg			pgsignal(pgrp, SIGTTOU, 1);
8569507Sdg			PGRP_UNLOCK(pgrp);
8579507Sdg			error = ttysleep(tp, &lbolt, TTOPRI | PCATCH, "ttybg1",
8588585Sdg					 0);
8598585Sdg			if (error)
8607695Sdg				return (error);
8618585Sdg			sx_slock(&proctree_lock);
8628585Sdg			PROC_LOCK(p);
8637695Sdg		}
8641549Srgrimes		PROC_UNLOCK(p);
8658585Sdg		sx_sunlock(&proctree_lock);
86612423Sphk		break;
86712423Sphk	}
86812423Sphk
8697695Sdg	if (tp->t_break != NULL) {
8707695Sdg		switch (cmd) {
8711549Srgrimes		case TIOCSBRK:
8721541Srgrimes			tp->t_break(tp, 1);
8737695Sdg			return (0);
8748585Sdg		case TIOCCBRK:
8758585Sdg			tp->t_break(tp, 0);
8767695Sdg			return (0);
8771549Srgrimes		default:
8781827Sdg			break;
8797695Sdg		}
8807695Sdg	}
8817695Sdg
8827695Sdg	if (tp->t_modem != NULL) {
8837695Sdg		switch (cmd) {
8847695Sdg		case TIOCSDTR:
8857695Sdg			tp->t_modem(tp, SER_DTR, 0);
8867695Sdg			return (0);
8877695Sdg		case TIOCCDTR:
8887695Sdg			tp->t_modem(tp, 0, SER_DTR);
8893612Sdg			return (0);
8907695Sdg		case TIOCMSET:
8913612Sdg			bits = *(int *)data;
8928585Sdg			sig = (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1;
8939507Sdg			sig2 = ((~bits) & (TIOCM_DTR | TIOCM_RTS)) >> 1;
8947695Sdg			tp->t_modem(tp, sig, sig2);
8958585Sdg			return (0);
89612423Sphk		case TIOCMBIS:
89712423Sphk			bits = *(int *)data;
8987695Sdg			sig = (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1;
8998585Sdg			tp->t_modem(tp, sig, 0);
9008585Sdg			return (0);
9018585Sdg		case TIOCMBIC:
9027695Sdg			bits = *(int *)data;
9037695Sdg			sig = (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1;
9048585Sdg			tp->t_modem(tp, 0, sig);
9059507Sdg			return (0);
9067695Sdg		case TIOCMGET:
9077695Sdg			sig = tp->t_modem(tp, 0, 0);
9087695Sdg			/* See <sys/serial.h. for the "<< 1" stuff */
9091549Srgrimes			bits = TIOCM_LE + (sig << 1);
9107695Sdg			*(int *)data = bits;
9119507Sdg			return (0);
9129507Sdg		default:
9139507Sdg			break;
9149507Sdg		}
9159507Sdg	}
9167695Sdg
9171549Srgrimes	if (tp->t_pps != NULL) {
9189507Sdg		error = pps_ioctl(cmd, data, tp->t_pps);
9199507Sdg		if (error != ENOIOCTL)
9201549Srgrimes			return (error);
9219507Sdg	}
9227695Sdg
923	switch (cmd) {			/* Process the ioctl. */
924	case FIOASYNC:			/* set/clear async i/o */
925		s = spltty();
926		if (*(int *)data)
927			SET(tp->t_state, TS_ASYNC);
928		else
929			CLR(tp->t_state, TS_ASYNC);
930		splx(s);
931		break;
932	case FIONBIO:			/* set/clear non-blocking i/o */
933		break;			/* XXX: delete. */
934	case FIONREAD:			/* get # bytes to read */
935		s = spltty();
936		*(int *)data = ttnread(tp);
937		splx(s);
938		break;
939
940	case FIOSETOWN:
941		/*
942		 * Policy -- Don't allow FIOSETOWN on someone else's
943		 *           controlling tty
944		 */
945		if (tp->t_session != NULL && !isctty(p, tp))
946			return (ENOTTY);
947
948		error = fsetown(*(int *)data, &tp->t_sigio);
949		if (error)
950			return (error);
951		break;
952	case FIOGETOWN:
953		if (tp->t_session != NULL && !isctty(p, tp))
954			return (ENOTTY);
955		*(int *)data = fgetown(&tp->t_sigio);
956		break;
957
958	case TIOCEXCL:			/* set exclusive use of tty */
959		s = spltty();
960		SET(tp->t_state, TS_XCLUDE);
961		splx(s);
962		break;
963	case TIOCFLUSH: {		/* flush buffers */
964		int flags = *(int *)data;
965
966		if (flags == 0)
967			flags = FREAD | FWRITE;
968		else
969			flags &= FREAD | FWRITE;
970		ttyflush(tp, flags);
971		break;
972	}
973	case TIOCCONS:			/* become virtual console */
974		if (*(int *)data) {
975			struct nameidata nid;
976
977			if (constty && constty != tp &&
978			    ISSET(constty->t_state, TS_CONNECTED))
979				return (EBUSY);
980
981			/* Ensure user can open the real console. */
982			NDINIT(&nid, LOOKUP, LOCKLEAF | FOLLOW, UIO_SYSSPACE,
983			    "/dev/console", td);
984			if ((error = namei(&nid)) != 0)
985				return (error);
986			NDFREE(&nid, NDF_ONLY_PNBUF);
987			error = VOP_ACCESS(nid.ni_vp, VREAD, td->td_ucred, td);
988			vput(nid.ni_vp);
989			if (error)
990				return (error);
991
992			constty_set(tp);
993		} else if (tp == constty)
994			constty_clear();
995		break;
996	case TIOCDRAIN:			/* wait till output drained */
997		error = ttywait(tp);
998		if (error)
999			return (error);
1000		break;
1001	case TIOCGETA: {		/* get termios struct */
1002		struct termios *t = (struct termios *)data;
1003
1004		bcopy(&tp->t_termios, t, sizeof(struct termios));
1005		break;
1006	}
1007	case TIOCGETD:			/* get line discipline */
1008		*(int *)data = tp->t_line;
1009		break;
1010	case TIOCGWINSZ:		/* get window size */
1011		*(struct winsize *)data = tp->t_winsize;
1012		break;
1013	case TIOCGPGRP:			/* get pgrp of tty */
1014		if (!isctty(p, tp))
1015			return (ENOTTY);
1016		*(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
1017		break;
1018#ifdef TIOCHPCL
1019	case TIOCHPCL:			/* hang up on last close */
1020		s = spltty();
1021		SET(tp->t_cflag, HUPCL);
1022		splx(s);
1023		break;
1024#endif
1025	case TIOCMGDTRWAIT:
1026		*(int *)data = tp->t_dtr_wait * 100 / hz;
1027		break;
1028	case TIOCMSDTRWAIT:
1029		/* must be root since the wait applies to following logins */
1030		error = suser(td);
1031		if (error)
1032			return (error);
1033		tp->t_dtr_wait = *(int *)data * hz / 100;
1034		break;
1035	case TIOCNXCL:			/* reset exclusive use of tty */
1036		s = spltty();
1037		CLR(tp->t_state, TS_XCLUDE);
1038		splx(s);
1039		break;
1040	case TIOCOUTQ:			/* output queue size */
1041		*(int *)data = tp->t_outq.c_cc;
1042		break;
1043	case TIOCSETA:			/* set termios struct */
1044	case TIOCSETAW:			/* drain output, set */
1045	case TIOCSETAF: {		/* drn out, fls in, set */
1046		struct termios *t = (struct termios *)data;
1047
1048		if (t->c_ispeed == 0)
1049			t->c_ispeed = t->c_ospeed;
1050		if (t->c_ispeed == 0)
1051			t->c_ispeed = tp->t_ospeed;
1052		if (t->c_ispeed == 0)
1053			return (EINVAL);
1054		s = spltty();
1055		if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
1056			error = ttywait(tp);
1057			if (error) {
1058				splx(s);
1059				return (error);
1060			}
1061			if (cmd == TIOCSETAF)
1062				ttyflush(tp, FREAD);
1063		}
1064		if (!ISSET(t->c_cflag, CIGNORE)) {
1065			/*
1066			 * Set device hardware.
1067			 */
1068			if (tp->t_param && (error = (*tp->t_param)(tp, t))) {
1069				splx(s);
1070				return (error);
1071			}
1072			if (ISSET(t->c_cflag, CLOCAL) &&
1073			    !ISSET(tp->t_cflag, CLOCAL)) {
1074				/*
1075				 * XXX disconnections would be too hard to
1076				 * get rid of without this kludge.  The only
1077				 * way to get rid of controlling terminals
1078				 * is to exit from the session leader.
1079				 */
1080				CLR(tp->t_state, TS_ZOMBIE);
1081
1082				wakeup(TSA_CARR_ON(tp));
1083				ttwakeup(tp);
1084				ttwwakeup(tp);
1085			}
1086			if ((ISSET(tp->t_state, TS_CARR_ON) ||
1087			     ISSET(t->c_cflag, CLOCAL)) &&
1088			    !ISSET(tp->t_state, TS_ZOMBIE))
1089				SET(tp->t_state, TS_CONNECTED);
1090			else
1091				CLR(tp->t_state, TS_CONNECTED);
1092			tp->t_cflag = t->c_cflag;
1093			tp->t_ispeed = t->c_ispeed;
1094			if (t->c_ospeed != 0)
1095				tp->t_ospeed = t->c_ospeed;
1096			ttsetwater(tp);
1097		}
1098		if (ISSET(t->c_lflag, ICANON) != ISSET(tp->t_lflag, ICANON) &&
1099		    cmd != TIOCSETAF) {
1100			if (ISSET(t->c_lflag, ICANON))
1101				SET(tp->t_lflag, PENDIN);
1102			else {
1103				/*
1104				 * XXX we really shouldn't allow toggling
1105				 * ICANON while we're in a non-termios line
1106				 * discipline.  Now we have to worry about
1107				 * panicing for a null queue.
1108				 */
1109				if (tp->t_canq.c_cbreserved > 0 &&
1110				    tp->t_rawq.c_cbreserved > 0) {
1111					catq(&tp->t_rawq, &tp->t_canq);
1112					/*
1113					 * XXX the queue limits may be
1114					 * different, so the old queue
1115					 * swapping method no longer works.
1116					 */
1117					catq(&tp->t_canq, &tp->t_rawq);
1118				}
1119				CLR(tp->t_lflag, PENDIN);
1120			}
1121			ttwakeup(tp);
1122		}
1123		tp->t_iflag = t->c_iflag;
1124		tp->t_oflag = t->c_oflag;
1125		/*
1126		 * Make the EXTPROC bit read only.
1127		 */
1128		if (ISSET(tp->t_lflag, EXTPROC))
1129			SET(t->c_lflag, EXTPROC);
1130		else
1131			CLR(t->c_lflag, EXTPROC);
1132		tp->t_lflag = t->c_lflag | ISSET(tp->t_lflag, PENDIN);
1133		if (t->c_cc[VMIN] != tp->t_cc[VMIN] ||
1134		    t->c_cc[VTIME] != tp->t_cc[VTIME])
1135			ttwakeup(tp);
1136		bcopy(t->c_cc, tp->t_cc, sizeof(t->c_cc));
1137		splx(s);
1138		break;
1139	}
1140	case TIOCSETD: {		/* set line discipline */
1141		int t = *(int *)data;
1142
1143		if ((u_int)t >= nlinesw)
1144			return (ENXIO);
1145		if (t == tp->t_line)
1146			return (0);
1147		s = spltty();
1148		ttyld_close(tp, flag);
1149		tp->t_line = t;
1150		/* XXX: we should use the correct cdev here */
1151		error = ttyld_open(tp, tp->t_dev);
1152		if (error) {
1153			/*
1154			 * If we fail to switch line discipline we cannot
1155			 * fall back to the previous, because we can not
1156			 * trust that ldisc to open successfully either.
1157			 * Fall back to the default ldisc which we know
1158			 * will allways succeed.
1159			 */
1160			tp->t_line = TTYDISC;
1161			(void)ttyld_open(tp, tp->t_dev);
1162		}
1163		splx(s);
1164		return (error);
1165		break;
1166	}
1167	case TIOCSTART:			/* start output, like ^Q */
1168		s = spltty();
1169		if (ISSET(tp->t_state, TS_TTSTOP) ||
1170		    ISSET(tp->t_lflag, FLUSHO)) {
1171			CLR(tp->t_lflag, FLUSHO);
1172			CLR(tp->t_state, TS_TTSTOP);
1173			ttstart(tp);
1174		}
1175		splx(s);
1176		break;
1177	case TIOCSTI:			/* simulate terminal input */
1178		if ((flag & FREAD) == 0 && suser(td))
1179			return (EPERM);
1180		if (!isctty(p, tp) && suser(td))
1181			return (EACCES);
1182		s = spltty();
1183		ttyld_rint(tp, *(u_char *)data);
1184		splx(s);
1185		break;
1186	case TIOCSTOP:			/* stop output, like ^S */
1187		s = spltty();
1188		if (!ISSET(tp->t_state, TS_TTSTOP)) {
1189			SET(tp->t_state, TS_TTSTOP);
1190			(*tp->t_stop)(tp, 0);
1191		}
1192		splx(s);
1193		break;
1194	case TIOCSCTTY:			/* become controlling tty */
1195		/* Session ctty vnode pointer set in vnode layer. */
1196		sx_slock(&proctree_lock);
1197		if (!SESS_LEADER(p) ||
1198		    ((p->p_session->s_ttyvp || tp->t_session) &&
1199		     (tp->t_session != p->p_session))) {
1200			sx_sunlock(&proctree_lock);
1201			return (EPERM);
1202		}
1203		tp->t_session = p->p_session;
1204		tp->t_pgrp = p->p_pgrp;
1205		SESS_LOCK(p->p_session);
1206		ttyref(tp);		/* ttyrel(): kern_proc.c:pgdelete() */
1207		p->p_session->s_ttyp = tp;
1208		SESS_UNLOCK(p->p_session);
1209		PROC_LOCK(p);
1210		p->p_flag |= P_CONTROLT;
1211		PROC_UNLOCK(p);
1212		sx_sunlock(&proctree_lock);
1213		break;
1214	case TIOCSPGRP: {		/* set pgrp of tty */
1215		sx_slock(&proctree_lock);
1216		pgrp = pgfind(*(int *)data);
1217		if (!isctty(p, tp)) {
1218			if (pgrp != NULL)
1219				PGRP_UNLOCK(pgrp);
1220			sx_sunlock(&proctree_lock);
1221			return (ENOTTY);
1222		}
1223		if (pgrp == NULL) {
1224			sx_sunlock(&proctree_lock);
1225			return (EPERM);
1226		}
1227		PGRP_UNLOCK(pgrp);
1228		if (pgrp->pg_session != p->p_session) {
1229			sx_sunlock(&proctree_lock);
1230			return (EPERM);
1231		}
1232		sx_sunlock(&proctree_lock);
1233		tp->t_pgrp = pgrp;
1234		break;
1235	}
1236	case TIOCSTAT:			/* simulate control-T */
1237		s = spltty();
1238		ttyinfo(tp);
1239		splx(s);
1240		break;
1241	case TIOCSWINSZ:		/* set window size */
1242		if (bcmp((caddr_t)&tp->t_winsize, data,
1243		    sizeof (struct winsize))) {
1244			tp->t_winsize = *(struct winsize *)data;
1245			if (tp->t_pgrp != NULL) {
1246				PGRP_LOCK(tp->t_pgrp);
1247				pgsignal(tp->t_pgrp, SIGWINCH, 1);
1248				PGRP_UNLOCK(tp->t_pgrp);
1249			}
1250		}
1251		break;
1252	case TIOCSDRAINWAIT:
1253		error = suser(td);
1254		if (error)
1255			return (error);
1256		tp->t_timeout = *(int *)data * hz;
1257		wakeup(TSA_OCOMPLETE(tp));
1258		wakeup(TSA_OLOWAT(tp));
1259		break;
1260	case TIOCGDRAINWAIT:
1261		*(int *)data = tp->t_timeout / hz;
1262		break;
1263	default:
1264#if defined(COMPAT_43)
1265#ifndef BURN_BRIDGES
1266		return (ttcompat(tp, cmd, data, flag));
1267#else
1268		return (ENOIOCTL);
1269#endif
1270#else
1271		return (ENOIOCTL);
1272#endif
1273	}
1274	return (0);
1275}
1276
1277int
1278ttypoll(struct cdev *dev, int events, struct thread *td)
1279{
1280	int s;
1281	int revents = 0;
1282	struct tty *tp;
1283
1284	tp = tty_gettp(dev);
1285
1286	if (tp == NULL)	/* XXX used to return ENXIO, but that means true! */
1287		return ((events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM))
1288			| POLLHUP);
1289
1290	s = spltty();
1291	if (events & (POLLIN | POLLRDNORM)) {
1292		if (ISSET(tp->t_state, TS_ZOMBIE))
1293			revents |= (events & (POLLIN | POLLRDNORM)) |
1294			    POLLHUP;
1295		else if (ttnread(tp) > 0)
1296			revents |= events & (POLLIN | POLLRDNORM);
1297		else
1298			selrecord(td, &tp->t_rsel);
1299	}
1300	if (events & POLLOUT) {
1301		if (ISSET(tp->t_state, TS_ZOMBIE))
1302			revents |= POLLHUP;
1303		else if (tp->t_outq.c_cc <= tp->t_olowat &&
1304		    ISSET(tp->t_state, TS_CONNECTED))
1305			revents |= events & POLLOUT;
1306		else
1307			selrecord(td, &tp->t_wsel);
1308	}
1309	splx(s);
1310	return (revents);
1311}
1312
1313static struct filterops ttyread_filtops =
1314	{ 1, NULL, filt_ttyrdetach, filt_ttyread };
1315static struct filterops ttywrite_filtops =
1316	{ 1, NULL, filt_ttywdetach, filt_ttywrite };
1317
1318int
1319ttykqfilter(struct cdev *dev, struct knote *kn)
1320{
1321	struct tty *tp;
1322	struct knlist *klist;
1323	int s;
1324
1325	tp = tty_gettp(dev);
1326
1327	switch (kn->kn_filter) {
1328	case EVFILT_READ:
1329		klist = &tp->t_rsel.si_note;
1330		kn->kn_fop = &ttyread_filtops;
1331		break;
1332	case EVFILT_WRITE:
1333		klist = &tp->t_wsel.si_note;
1334		kn->kn_fop = &ttywrite_filtops;
1335		break;
1336	default:
1337		return (EINVAL);
1338	}
1339
1340	kn->kn_hook = (caddr_t)dev;
1341
1342	s = spltty();
1343	knlist_add(klist, kn, 0);
1344	splx(s);
1345
1346	return (0);
1347}
1348
1349static void
1350filt_ttyrdetach(struct knote *kn)
1351{
1352	struct tty *tp = ((struct cdev *)kn->kn_hook)->si_tty;
1353	int s = spltty();
1354
1355	knlist_remove(&tp->t_rsel.si_note, kn, 0);
1356	splx(s);
1357}
1358
1359static int
1360filt_ttyread(struct knote *kn, long hint)
1361{
1362	struct tty *tp = ((struct cdev *)kn->kn_hook)->si_tty;
1363
1364	kn->kn_data = ttnread(tp);
1365	if (ISSET(tp->t_state, TS_ZOMBIE)) {
1366		kn->kn_flags |= EV_EOF;
1367		return (1);
1368	}
1369	return (kn->kn_data > 0);
1370}
1371
1372static void
1373filt_ttywdetach(struct knote *kn)
1374{
1375	struct tty *tp = ((struct cdev *)kn->kn_hook)->si_tty;
1376	int s = spltty();
1377
1378	knlist_remove(&tp->t_wsel.si_note, kn, 0);
1379	splx(s);
1380}
1381
1382static int
1383filt_ttywrite(struct knote *kn, long hint)
1384{
1385	struct tty *tp = ((struct cdev *)kn->kn_hook)->si_tty;
1386
1387	kn->kn_data = tp->t_outq.c_cc;
1388	if (ISSET(tp->t_state, TS_ZOMBIE))
1389		return (1);
1390	return (kn->kn_data <= tp->t_olowat &&
1391	    ISSET(tp->t_state, TS_CONNECTED));
1392}
1393
1394/*
1395 * Must be called at spltty().
1396 */
1397static int
1398ttnread(struct tty *tp)
1399{
1400	int nread;
1401
1402	if (ISSET(tp->t_lflag, PENDIN))
1403		ttypend(tp);
1404	nread = tp->t_canq.c_cc;
1405	if (!ISSET(tp->t_lflag, ICANON)) {
1406		nread += tp->t_rawq.c_cc;
1407		if (nread < tp->t_cc[VMIN] && tp->t_cc[VTIME] == 0)
1408			nread = 0;
1409	}
1410	return (nread);
1411}
1412
1413/*
1414 * Wait for output to drain.
1415 */
1416int
1417ttywait(struct tty *tp)
1418{
1419	int error, s;
1420
1421	error = 0;
1422	s = spltty();
1423	while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1424	       ISSET(tp->t_state, TS_CONNECTED) && tp->t_oproc) {
1425		(*tp->t_oproc)(tp);
1426		if ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1427		    ISSET(tp->t_state, TS_CONNECTED)) {
1428			SET(tp->t_state, TS_SO_OCOMPLETE);
1429			error = ttysleep(tp, TSA_OCOMPLETE(tp),
1430					 TTOPRI | PCATCH, "ttywai",
1431					 tp->t_timeout);
1432			if (error) {
1433				if (error == EWOULDBLOCK)
1434					error = EIO;
1435				break;
1436			}
1437		} else
1438			break;
1439	}
1440	if (!error && (tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)))
1441		error = EIO;
1442	splx(s);
1443	return (error);
1444}
1445
1446/*
1447 * Flush if successfully wait.
1448 */
1449static int
1450ttywflush(struct tty *tp)
1451{
1452	int error;
1453
1454	if ((error = ttywait(tp)) == 0)
1455		ttyflush(tp, FREAD);
1456	return (error);
1457}
1458
1459/*
1460 * Flush tty read and/or write queues, notifying anyone waiting.
1461 */
1462void
1463ttyflush(struct tty *tp, int rw)
1464{
1465	int s;
1466
1467	s = spltty();
1468#if 0
1469again:
1470#endif
1471	if (rw & FWRITE) {
1472		FLUSHQ(&tp->t_outq);
1473		CLR(tp->t_state, TS_TTSTOP);
1474	}
1475	(*tp->t_stop)(tp, rw);
1476	if (rw & FREAD) {
1477		FLUSHQ(&tp->t_canq);
1478		FLUSHQ(&tp->t_rawq);
1479		CLR(tp->t_lflag, PENDIN);
1480		tp->t_rocount = 0;
1481		tp->t_rocol = 0;
1482		CLR(tp->t_state, TS_LOCAL);
1483		ttwakeup(tp);
1484		if (ISSET(tp->t_state, TS_TBLOCK)) {
1485			if (rw & FWRITE)
1486				FLUSHQ(&tp->t_outq);
1487			ttyunblock(tp);
1488
1489			/*
1490			 * Don't let leave any state that might clobber the
1491			 * next line discipline (although we should do more
1492			 * to send the START char).  Not clearing the state
1493			 * may have caused the "putc to a clist with no
1494			 * reserved cblocks" panic/printf.
1495			 */
1496			CLR(tp->t_state, TS_TBLOCK);
1497
1498#if 0 /* forget it, sleeping isn't always safe and we don't know when it is */
1499			if (ISSET(tp->t_iflag, IXOFF)) {
1500				/*
1501				 * XXX wait a bit in the hope that the stop
1502				 * character (if any) will go out.  Waiting
1503				 * isn't good since it allows races.  This
1504				 * will be fixed when the stop character is
1505				 * put in a special queue.  Don't bother with
1506				 * the checks in ttywait() since the timeout
1507				 * will save us.
1508				 */
1509				SET(tp->t_state, TS_SO_OCOMPLETE);
1510				ttysleep(tp, TSA_OCOMPLETE(tp), TTOPRI,
1511					 "ttyfls", hz / 10);
1512				/*
1513				 * Don't try sending the stop character again.
1514				 */
1515				CLR(tp->t_state, TS_TBLOCK);
1516				goto again;
1517			}
1518#endif
1519		}
1520	}
1521	if (rw & FWRITE) {
1522		FLUSHQ(&tp->t_outq);
1523		ttwwakeup(tp);
1524	}
1525	splx(s);
1526}
1527
1528/*
1529 * Copy in the default termios characters.
1530 */
1531void
1532termioschars(struct termios *t)
1533{
1534
1535	bcopy(ttydefchars, t->c_cc, sizeof t->c_cc);
1536}
1537
1538/*
1539 * Old interface.
1540 */
1541void
1542ttychars(struct tty *tp)
1543{
1544
1545	termioschars(&tp->t_termios);
1546}
1547
1548/*
1549 * Handle input high water.  Send stop character for the IXOFF case.  Turn
1550 * on our input flow control bit and propagate the changes to the driver.
1551 * XXX the stop character should be put in a special high priority queue.
1552 */
1553void
1554ttyblock(struct tty *tp)
1555{
1556
1557	SET(tp->t_state, TS_TBLOCK);
1558	if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
1559	    putc(tp->t_cc[VSTOP], &tp->t_outq) != 0)
1560		CLR(tp->t_state, TS_TBLOCK);	/* try again later */
1561	ttstart(tp);
1562}
1563
1564/*
1565 * Handle input low water.  Send start character for the IXOFF case.  Turn
1566 * off our input flow control bit and propagate the changes to the driver.
1567 * XXX the start character should be put in a special high priority queue.
1568 */
1569static void
1570ttyunblock(struct tty *tp)
1571{
1572
1573	CLR(tp->t_state, TS_TBLOCK);
1574	if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTART] != _POSIX_VDISABLE &&
1575	    putc(tp->t_cc[VSTART], &tp->t_outq) != 0)
1576		SET(tp->t_state, TS_TBLOCK);	/* try again later */
1577	ttstart(tp);
1578}
1579
1580#ifdef notyet
1581/* Not used by any current (i386) drivers. */
1582/*
1583 * Restart after an inter-char delay.
1584 */
1585void
1586ttrstrt(void *tp_arg)
1587{
1588	struct tty *tp;
1589	int s;
1590
1591	KASSERT(tp_arg != NULL, ("ttrstrt"));
1592
1593	tp = tp_arg;
1594	s = spltty();
1595
1596	CLR(tp->t_state, TS_TIMEOUT);
1597	ttstart(tp);
1598
1599	splx(s);
1600}
1601#endif
1602
1603int
1604ttstart(struct tty *tp)
1605{
1606
1607	if (tp->t_oproc != NULL)	/* XXX: Kludge for pty. */
1608		(*tp->t_oproc)(tp);
1609	return (0);
1610}
1611
1612/*
1613 * "close" a line discipline
1614 */
1615int
1616ttylclose(struct tty *tp, int flag)
1617{
1618
1619	if (flag & FNONBLOCK || ttywflush(tp))
1620		ttyflush(tp, FREAD | FWRITE);
1621	return (0);
1622}
1623
1624/*
1625 * Handle modem control transition on a tty.
1626 * Flag indicates new state of carrier.
1627 * Returns 0 if the line should be turned off, otherwise 1.
1628 */
1629int
1630ttymodem(struct tty *tp, int flag)
1631{
1632
1633	if (ISSET(tp->t_state, TS_CARR_ON) && ISSET(tp->t_cflag, MDMBUF)) {
1634		/*
1635		 * MDMBUF: do flow control according to carrier flag
1636		 * XXX TS_CAR_OFLOW doesn't do anything yet.  TS_TTSTOP
1637		 * works if IXON and IXANY are clear.
1638		 */
1639		if (flag) {
1640			CLR(tp->t_state, TS_CAR_OFLOW);
1641			CLR(tp->t_state, TS_TTSTOP);
1642			ttstart(tp);
1643		} else if (!ISSET(tp->t_state, TS_CAR_OFLOW)) {
1644			SET(tp->t_state, TS_CAR_OFLOW);
1645			SET(tp->t_state, TS_TTSTOP);
1646			(*tp->t_stop)(tp, 0);
1647		}
1648	} else if (flag == 0) {
1649		/*
1650		 * Lost carrier.
1651		 */
1652		CLR(tp->t_state, TS_CARR_ON);
1653		if (ISSET(tp->t_state, TS_ISOPEN) &&
1654		    !ISSET(tp->t_cflag, CLOCAL)) {
1655			SET(tp->t_state, TS_ZOMBIE);
1656			CLR(tp->t_state, TS_CONNECTED);
1657			if (tp->t_session) {
1658				sx_slock(&proctree_lock);
1659				if (tp->t_session->s_leader) {
1660					struct proc *p;
1661
1662					p = tp->t_session->s_leader;
1663					PROC_LOCK(p);
1664					psignal(p, SIGHUP);
1665					PROC_UNLOCK(p);
1666				}
1667				sx_sunlock(&proctree_lock);
1668			}
1669			ttyflush(tp, FREAD | FWRITE);
1670			return (0);
1671		}
1672	} else {
1673		/*
1674		 * Carrier now on.
1675		 */
1676		SET(tp->t_state, TS_CARR_ON);
1677		if (!ISSET(tp->t_state, TS_ZOMBIE))
1678			SET(tp->t_state, TS_CONNECTED);
1679		wakeup(TSA_CARR_ON(tp));
1680		ttwakeup(tp);
1681		ttwwakeup(tp);
1682	}
1683	return (1);
1684}
1685
1686/*
1687 * Reinput pending characters after state switch
1688 * call at spltty().
1689 */
1690static void
1691ttypend(struct tty *tp)
1692{
1693	struct clist tq;
1694	int c;
1695
1696	CLR(tp->t_lflag, PENDIN);
1697	SET(tp->t_state, TS_TYPEN);
1698	/*
1699	 * XXX this assumes too much about clist internals.  It may even
1700	 * fail if the cblock slush pool is empty.  We can't allocate more
1701	 * cblocks here because we are called from an interrupt handler
1702	 * and clist_alloc_cblocks() can wait.
1703	 */
1704	tq = tp->t_rawq;
1705	bzero(&tp->t_rawq, sizeof tp->t_rawq);
1706	tp->t_rawq.c_cbmax = tq.c_cbmax;
1707	tp->t_rawq.c_cbreserved = tq.c_cbreserved;
1708	while ((c = getc(&tq)) >= 0)
1709		ttyinput(c, tp);
1710	CLR(tp->t_state, TS_TYPEN);
1711}
1712
1713/*
1714 * Process a read call on a tty device.
1715 */
1716int
1717ttread(struct tty *tp, struct uio *uio, int flag)
1718{
1719	struct clist *qp;
1720	int c;
1721	tcflag_t lflag;
1722	cc_t *cc = tp->t_cc;
1723	struct thread *td;
1724	struct proc *p;
1725	int s, first, error = 0;
1726	int has_stime = 0, last_cc = 0;
1727	long slp = 0;		/* XXX this should be renamed `timo'. */
1728	struct timeval stime;
1729	struct pgrp *pg;
1730
1731	td = curthread;
1732	p = td->td_proc;
1733loop:
1734	s = spltty();
1735	lflag = tp->t_lflag;
1736	/*
1737	 * take pending input first
1738	 */
1739	if (ISSET(lflag, PENDIN)) {
1740		ttypend(tp);
1741		splx(s);	/* reduce latency */
1742		s = spltty();
1743		lflag = tp->t_lflag;	/* XXX ttypend() clobbers it */
1744	}
1745
1746	/*
1747	 * Hang process if it's in the background.
1748	 */
1749	if (isbackground(p, tp)) {
1750		splx(s);
1751		sx_slock(&proctree_lock);
1752		PROC_LOCK(p);
1753		if (SIGISMEMBER(p->p_sigacts->ps_sigignore, SIGTTIN) ||
1754		    SIGISMEMBER(td->td_sigmask, SIGTTIN) ||
1755		    (p->p_flag & P_PPWAIT) || p->p_pgrp->pg_jobc == 0) {
1756			PROC_UNLOCK(p);
1757			sx_sunlock(&proctree_lock);
1758			return (EIO);
1759		}
1760		pg = p->p_pgrp;
1761		PROC_UNLOCK(p);
1762		PGRP_LOCK(pg);
1763		sx_sunlock(&proctree_lock);
1764		pgsignal(pg, SIGTTIN, 1);
1765		PGRP_UNLOCK(pg);
1766		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, "ttybg2", 0);
1767		if (error)
1768			return (error);
1769		goto loop;
1770	}
1771
1772	if (ISSET(tp->t_state, TS_ZOMBIE)) {
1773		splx(s);
1774		return (0);	/* EOF */
1775	}
1776
1777	/*
1778	 * If canonical, use the canonical queue,
1779	 * else use the raw queue.
1780	 *
1781	 * (should get rid of clists...)
1782	 */
1783	qp = ISSET(lflag, ICANON) ? &tp->t_canq : &tp->t_rawq;
1784
1785	if (flag & IO_NDELAY) {
1786		if (qp->c_cc > 0)
1787			goto read;
1788		if (!ISSET(lflag, ICANON) && cc[VMIN] == 0) {
1789			splx(s);
1790			return (0);
1791		}
1792		splx(s);
1793		return (EWOULDBLOCK);
1794	}
1795	if (!ISSET(lflag, ICANON)) {
1796		int m = cc[VMIN];
1797		long t = cc[VTIME];
1798		struct timeval timecopy;
1799
1800		/*
1801		 * Check each of the four combinations.
1802		 * (m > 0 && t == 0) is the normal read case.
1803		 * It should be fairly efficient, so we check that and its
1804		 * companion case (m == 0 && t == 0) first.
1805		 * For the other two cases, we compute the target sleep time
1806		 * into slp.
1807		 */
1808		if (t == 0) {
1809			if (qp->c_cc < m)
1810				goto sleep;
1811			if (qp->c_cc > 0)
1812				goto read;
1813
1814			/* m, t and qp->c_cc are all 0.  0 is enough input. */
1815			splx(s);
1816			return (0);
1817		}
1818		t *= 100000;		/* time in us */
1819#define diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 1000000 + \
1820			 ((t1).tv_usec - (t2).tv_usec))
1821		if (m > 0) {
1822			if (qp->c_cc <= 0)
1823				goto sleep;
1824			if (qp->c_cc >= m)
1825				goto read;
1826			getmicrotime(&timecopy);
1827			if (!has_stime) {
1828				/* first character, start timer */
1829				has_stime = 1;
1830				stime = timecopy;
1831				slp = t;
1832			} else if (qp->c_cc > last_cc) {
1833				/* got a character, restart timer */
1834				stime = timecopy;
1835				slp = t;
1836			} else {
1837				/* nothing, check expiration */
1838				slp = t - diff(timecopy, stime);
1839				if (slp <= 0)
1840					goto read;
1841			}
1842			last_cc = qp->c_cc;
1843		} else {	/* m == 0 */
1844			if (qp->c_cc > 0)
1845				goto read;
1846			getmicrotime(&timecopy);
1847			if (!has_stime) {
1848				has_stime = 1;
1849				stime = timecopy;
1850				slp = t;
1851			} else {
1852				slp = t - diff(timecopy, stime);
1853				if (slp <= 0) {
1854					/* Timed out, but 0 is enough input. */
1855					splx(s);
1856					return (0);
1857				}
1858			}
1859		}
1860#undef diff
1861		if (slp != 0) {
1862			struct timeval tv;	/* XXX style bug. */
1863
1864			tv.tv_sec = slp / 1000000;
1865			tv.tv_usec = slp % 1000000;
1866			slp = tvtohz(&tv);
1867			/*
1868			 * XXX bad variable names.  slp was the timeout in
1869			 * usec.  Now it is the timeout in ticks.
1870			 */
1871		}
1872		goto sleep;
1873	}
1874	if (qp->c_cc <= 0) {
1875sleep:
1876		/*
1877		 * There is no input, or not enough input and we can block.
1878		 */
1879		error = ttysleep(tp, TSA_HUP_OR_INPUT(tp), TTIPRI | PCATCH,
1880				 ISSET(tp->t_state, TS_CONNECTED) ?
1881				 "ttyin" : "ttyhup", (int)slp);
1882		splx(s);
1883		if (error == EWOULDBLOCK)
1884			error = 0;
1885		else if (error)
1886			return (error);
1887		/*
1888		 * XXX what happens if another process eats some input
1889		 * while we are asleep (not just here)?  It would be
1890		 * safest to detect changes and reset our state variables
1891		 * (has_stime and last_cc).
1892		 */
1893		slp = 0;
1894		goto loop;
1895	}
1896read:
1897	splx(s);
1898	/*
1899	 * Input present, check for input mapping and processing.
1900	 */
1901	first = 1;
1902	if (ISSET(lflag, ICANON | ISIG))
1903		goto slowcase;
1904	for (;;) {
1905		char ibuf[IBUFSIZ];
1906		int icc;
1907
1908		icc = imin(uio->uio_resid, IBUFSIZ);
1909		icc = q_to_b(qp, ibuf, icc);
1910		if (icc <= 0) {
1911			if (first)
1912				goto loop;
1913			break;
1914		}
1915		error = uiomove(ibuf, icc, uio);
1916		/*
1917		 * XXX if there was an error then we should ungetc() the
1918		 * unmoved chars and reduce icc here.
1919		 */
1920		if (error)
1921			break;
1922		if (uio->uio_resid == 0)
1923			break;
1924		first = 0;
1925	}
1926	goto out;
1927slowcase:
1928	for (;;) {
1929		c = getc(qp);
1930		if (c < 0) {
1931			if (first)
1932				goto loop;
1933			break;
1934		}
1935		/*
1936		 * delayed suspend (^Y)
1937		 */
1938		if (CCEQ(cc[VDSUSP], c) &&
1939		    ISSET(lflag, IEXTEN | ISIG) == (IEXTEN | ISIG)) {
1940			if (tp->t_pgrp != NULL) {
1941				PGRP_LOCK(tp->t_pgrp);
1942				pgsignal(tp->t_pgrp, SIGTSTP, 1);
1943				PGRP_UNLOCK(tp->t_pgrp);
1944			}
1945			if (first) {
1946				error = ttysleep(tp, &lbolt, TTIPRI | PCATCH,
1947						 "ttybg3", 0);
1948				if (error)
1949					break;
1950				goto loop;
1951			}
1952			break;
1953		}
1954		/*
1955		 * Interpret EOF only in canonical mode.
1956		 */
1957		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
1958			break;
1959		/*
1960		 * Give user character.
1961		 */
1962		error = ureadc(c, uio);
1963		if (error)
1964			/* XXX should ungetc(c, qp). */
1965			break;
1966		if (uio->uio_resid == 0)
1967			break;
1968		/*
1969		 * In canonical mode check for a "break character"
1970		 * marking the end of a "line of input".
1971		 */
1972		if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
1973			break;
1974		first = 0;
1975	}
1976
1977out:
1978	/*
1979	 * Look to unblock input now that (presumably)
1980	 * the input queue has gone down.
1981	 */
1982	s = spltty();
1983	if (ISSET(tp->t_state, TS_TBLOCK) &&
1984	    tp->t_rawq.c_cc + tp->t_canq.c_cc <= tp->t_ilowat)
1985		ttyunblock(tp);
1986	splx(s);
1987
1988	return (error);
1989}
1990
1991/*
1992 * Check the output queue on tp for space for a kernel message (from uprintf
1993 * or tprintf).  Allow some space over the normal hiwater mark so we don't
1994 * lose messages due to normal flow control, but don't let the tty run amok.
1995 * Sleeps here are not interruptible, but we return prematurely if new signals
1996 * arrive.
1997 */
1998int
1999ttycheckoutq(struct tty *tp, int wait)
2000{
2001	int hiwat, s;
2002	sigset_t oldmask;
2003	struct thread *td;
2004	struct proc *p;
2005
2006	td = curthread;
2007	p = td->td_proc;
2008	hiwat = tp->t_ohiwat;
2009	SIGEMPTYSET(oldmask);
2010	s = spltty();
2011	if (wait) {
2012		PROC_LOCK(p);
2013		oldmask = td->td_siglist;
2014		PROC_UNLOCK(p);
2015	}
2016	if (tp->t_outq.c_cc > hiwat + OBUFSIZ + 100)
2017		while (tp->t_outq.c_cc > hiwat) {
2018			ttstart(tp);
2019			if (tp->t_outq.c_cc <= hiwat)
2020				break;
2021			if (!wait) {
2022				splx(s);
2023				return (0);
2024			}
2025			PROC_LOCK(p);
2026			if (!SIGSETEQ(td->td_siglist, oldmask)) {
2027				PROC_UNLOCK(p);
2028				splx(s);
2029				return (0);
2030			}
2031			PROC_UNLOCK(p);
2032			SET(tp->t_state, TS_SO_OLOWAT);
2033			tsleep(TSA_OLOWAT(tp), PZERO - 1, "ttoutq", hz);
2034		}
2035	splx(s);
2036	return (1);
2037}
2038
2039/*
2040 * Process a write call on a tty device.
2041 */
2042int
2043ttwrite(struct tty *tp, struct uio *uio, int flag)
2044{
2045	char *cp = NULL;
2046	int cc, ce;
2047	struct thread *td;
2048	struct proc *p;
2049	int i, hiwat, cnt, error, s;
2050	char obuf[OBUFSIZ];
2051
2052	hiwat = tp->t_ohiwat;
2053	cnt = uio->uio_resid;
2054	error = 0;
2055	cc = 0;
2056	td = curthread;
2057	p = td->td_proc;
2058loop:
2059	s = spltty();
2060	if (ISSET(tp->t_state, TS_ZOMBIE)) {
2061		splx(s);
2062		if (uio->uio_resid == cnt)
2063			error = EIO;
2064		goto out;
2065	}
2066	if (!ISSET(tp->t_state, TS_CONNECTED)) {
2067		if (flag & IO_NDELAY) {
2068			splx(s);
2069			error = EWOULDBLOCK;
2070			goto out;
2071		}
2072		error = ttysleep(tp, TSA_CARR_ON(tp), TTIPRI | PCATCH,
2073				 "ttywdcd", 0);
2074		splx(s);
2075		if (error)
2076			goto out;
2077		goto loop;
2078	}
2079	splx(s);
2080	/*
2081	 * Hang the process if it's in the background.
2082	 */
2083	sx_slock(&proctree_lock);
2084	PROC_LOCK(p);
2085	if (isbackground(p, tp) &&
2086	    ISSET(tp->t_lflag, TOSTOP) && !(p->p_flag & P_PPWAIT) &&
2087	    !SIGISMEMBER(p->p_sigacts->ps_sigignore, SIGTTOU) &&
2088	    !SIGISMEMBER(td->td_sigmask, SIGTTOU)) {
2089		if (p->p_pgrp->pg_jobc == 0) {
2090			PROC_UNLOCK(p);
2091			sx_sunlock(&proctree_lock);
2092			error = EIO;
2093			goto out;
2094		}
2095		PROC_UNLOCK(p);
2096		PGRP_LOCK(p->p_pgrp);
2097		sx_sunlock(&proctree_lock);
2098		pgsignal(p->p_pgrp, SIGTTOU, 1);
2099		PGRP_UNLOCK(p->p_pgrp);
2100		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, "ttybg4", 0);
2101		if (error)
2102			goto out;
2103		goto loop;
2104	} else {
2105		PROC_UNLOCK(p);
2106		sx_sunlock(&proctree_lock);
2107	}
2108	/*
2109	 * Process the user's data in at most OBUFSIZ chunks.  Perform any
2110	 * output translation.  Keep track of high water mark, sleep on
2111	 * overflow awaiting device aid in acquiring new space.
2112	 */
2113	while (uio->uio_resid > 0 || cc > 0) {
2114		if (ISSET(tp->t_lflag, FLUSHO)) {
2115			uio->uio_resid = 0;
2116			return (0);
2117		}
2118		if (tp->t_outq.c_cc > hiwat)
2119			goto ovhiwat;
2120		/*
2121		 * Grab a hunk of data from the user, unless we have some
2122		 * leftover from last time.
2123		 */
2124		if (cc == 0) {
2125			cc = imin(uio->uio_resid, OBUFSIZ);
2126			cp = obuf;
2127			error = uiomove(cp, cc, uio);
2128			if (error) {
2129				cc = 0;
2130				break;
2131			}
2132		}
2133		/*
2134		 * If nothing fancy need be done, grab those characters we
2135		 * can handle without any of ttyoutput's processing and
2136		 * just transfer them to the output q.  For those chars
2137		 * which require special processing (as indicated by the
2138		 * bits in char_type), call ttyoutput.  After processing
2139		 * a hunk of data, look for FLUSHO so ^O's will take effect
2140		 * immediately.
2141		 */
2142		while (cc > 0) {
2143			if (!ISSET(tp->t_oflag, OPOST))
2144				ce = cc;
2145			else {
2146				ce = cc - scanc((u_int)cc, (u_char *)cp,
2147						char_type, CCLASSMASK);
2148				/*
2149				 * If ce is zero, then we're processing
2150				 * a special character through ttyoutput.
2151				 */
2152				if (ce == 0) {
2153					tp->t_rocount = 0;
2154					if (ttyoutput(*cp, tp) >= 0) {
2155						/* No Clists, wait a bit. */
2156						ttstart(tp);
2157						if (flag & IO_NDELAY) {
2158							error = EWOULDBLOCK;
2159							goto out;
2160						}
2161						error = ttysleep(tp, &lbolt,
2162								 TTOPRI|PCATCH,
2163								 "ttybf1", 0);
2164						if (error)
2165							goto out;
2166						goto loop;
2167					}
2168					cp++;
2169					cc--;
2170					if (ISSET(tp->t_lflag, FLUSHO) ||
2171					    tp->t_outq.c_cc > hiwat)
2172						goto ovhiwat;
2173					continue;
2174				}
2175			}
2176			/*
2177			 * A bunch of normal characters have been found.
2178			 * Transfer them en masse to the output queue and
2179			 * continue processing at the top of the loop.
2180			 * If there are any further characters in this
2181			 * <= OBUFSIZ chunk, the first should be a character
2182			 * requiring special handling by ttyoutput.
2183			 */
2184			tp->t_rocount = 0;
2185			i = b_to_q(cp, ce, &tp->t_outq);
2186			ce -= i;
2187			tp->t_column += ce;
2188			cp += ce, cc -= ce, tk_nout += ce;
2189			tp->t_outcc += ce;
2190			if (i > 0) {
2191				/* No Clists, wait a bit. */
2192				ttstart(tp);
2193				if (flag & IO_NDELAY) {
2194					error = EWOULDBLOCK;
2195					goto out;
2196				}
2197				error = ttysleep(tp, &lbolt, TTOPRI | PCATCH,
2198						 "ttybf2", 0);
2199				if (error)
2200					goto out;
2201				goto loop;
2202			}
2203			if (ISSET(tp->t_lflag, FLUSHO) ||
2204			    tp->t_outq.c_cc > hiwat)
2205				break;
2206		}
2207		ttstart(tp);
2208	}
2209out:
2210	/*
2211	 * If cc is nonzero, we leave the uio structure inconsistent, as the
2212	 * offset and iov pointers have moved forward, but it doesn't matter
2213	 * (the call will either return short or restart with a new uio).
2214	 */
2215	uio->uio_resid += cc;
2216	return (error);
2217
2218ovhiwat:
2219	ttstart(tp);
2220	s = spltty();
2221	/*
2222	 * This can only occur if FLUSHO is set in t_lflag,
2223	 * or if ttstart/oproc is synchronous (or very fast).
2224	 */
2225	if (tp->t_outq.c_cc <= hiwat) {
2226		splx(s);
2227		goto loop;
2228	}
2229	if (flag & IO_NDELAY) {
2230		splx(s);
2231		uio->uio_resid += cc;
2232		return (uio->uio_resid == cnt ? EWOULDBLOCK : 0);
2233	}
2234	SET(tp->t_state, TS_SO_OLOWAT);
2235	error = ttysleep(tp, TSA_OLOWAT(tp), TTOPRI | PCATCH, "ttywri",
2236			 tp->t_timeout);
2237	splx(s);
2238	if (error == EWOULDBLOCK)
2239		error = EIO;
2240	if (error)
2241		goto out;
2242	goto loop;
2243}
2244
2245/*
2246 * Rubout one character from the rawq of tp
2247 * as cleanly as possible.
2248 */
2249static void
2250ttyrub(int c, struct tty *tp)
2251{
2252	char *cp;
2253	int savecol;
2254	int tabc, s;
2255
2256	if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
2257		return;
2258	CLR(tp->t_lflag, FLUSHO);
2259	if (ISSET(tp->t_lflag, ECHOE)) {
2260		if (tp->t_rocount == 0) {
2261			/*
2262			 * Screwed by ttwrite; retype
2263			 */
2264			ttyretype(tp);
2265			return;
2266		}
2267		if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
2268			ttyrubo(tp, 2);
2269		else {
2270			CLR(c, ~TTY_CHARMASK);
2271			switch (CCLASS(c)) {
2272			case ORDINARY:
2273				ttyrubo(tp, 1);
2274				break;
2275			case BACKSPACE:
2276			case CONTROL:
2277			case NEWLINE:
2278			case RETURN:
2279			case VTAB:
2280				if (ISSET(tp->t_lflag, ECHOCTL))
2281					ttyrubo(tp, 2);
2282				break;
2283			case TAB:
2284				if (tp->t_rocount < tp->t_rawq.c_cc) {
2285					ttyretype(tp);
2286					return;
2287				}
2288				s = spltty();
2289				savecol = tp->t_column;
2290				SET(tp->t_state, TS_CNTTB);
2291				SET(tp->t_lflag, FLUSHO);
2292				tp->t_column = tp->t_rocol;
2293				cp = tp->t_rawq.c_cf;
2294				if (cp)
2295					tabc = *cp;	/* XXX FIX NEXTC */
2296				for (; cp; cp = nextc(&tp->t_rawq, cp, &tabc))
2297					ttyecho(tabc, tp);
2298				CLR(tp->t_lflag, FLUSHO);
2299				CLR(tp->t_state, TS_CNTTB);
2300				splx(s);
2301
2302				/* savecol will now be length of the tab. */
2303				savecol -= tp->t_column;
2304				tp->t_column += savecol;
2305				if (savecol > 8)
2306					savecol = 8;	/* overflow screw */
2307				while (--savecol >= 0)
2308					(void)ttyoutput('\b', tp);
2309				break;
2310			default:			/* XXX */
2311#define	PANICSTR	"ttyrub: would panic c = %d, val = %d\n"
2312				(void)printf(PANICSTR, c, CCLASS(c));
2313#ifdef notdef
2314				panic(PANICSTR, c, CCLASS(c));
2315#endif
2316			}
2317		}
2318	} else if (ISSET(tp->t_lflag, ECHOPRT)) {
2319		if (!ISSET(tp->t_state, TS_ERASE)) {
2320			SET(tp->t_state, TS_ERASE);
2321			(void)ttyoutput('\\', tp);
2322		}
2323		ttyecho(c, tp);
2324	} else {
2325		ttyecho(tp->t_cc[VERASE], tp);
2326		/*
2327		 * This code may be executed not only when an ERASE key
2328		 * is pressed, but also when ^U (KILL) or ^W (WERASE) are.
2329		 * So, I didn't think it was worthwhile to pass the extra
2330		 * information (which would need an extra parameter,
2331		 * changing every call) needed to distinguish the ERASE2
2332		 * case from the ERASE.
2333		 */
2334	}
2335	--tp->t_rocount;
2336}
2337
2338/*
2339 * Back over cnt characters, erasing them.
2340 */
2341static void
2342ttyrubo(struct tty *tp, int cnt)
2343{
2344
2345	while (cnt-- > 0) {
2346		(void)ttyoutput('\b', tp);
2347		(void)ttyoutput(' ', tp);
2348		(void)ttyoutput('\b', tp);
2349	}
2350}
2351
2352/*
2353 * ttyretype --
2354 *	Reprint the rawq line.  Note, it is assumed that c_cc has already
2355 *	been checked.
2356 */
2357static void
2358ttyretype(struct tty *tp)
2359{
2360	char *cp;
2361	int s, c;
2362
2363	/* Echo the reprint character. */
2364	if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
2365		ttyecho(tp->t_cc[VREPRINT], tp);
2366
2367	(void)ttyoutput('\n', tp);
2368
2369	/*
2370	 * XXX
2371	 * FIX: NEXTC IS BROKEN - DOESN'T CHECK QUOTE
2372	 * BIT OF FIRST CHAR.
2373	 */
2374	s = spltty();
2375	for (cp = tp->t_canq.c_cf, c = (cp != NULL ? *cp : 0);
2376	    cp != NULL; cp = nextc(&tp->t_canq, cp, &c))
2377		ttyecho(c, tp);
2378	for (cp = tp->t_rawq.c_cf, c = (cp != NULL ? *cp : 0);
2379	    cp != NULL; cp = nextc(&tp->t_rawq, cp, &c))
2380		ttyecho(c, tp);
2381	CLR(tp->t_state, TS_ERASE);
2382	splx(s);
2383
2384	tp->t_rocount = tp->t_rawq.c_cc;
2385	tp->t_rocol = 0;
2386}
2387
2388/*
2389 * Echo a typed character to the terminal.
2390 */
2391static void
2392ttyecho(int c, struct tty *tp)
2393{
2394
2395	if (!ISSET(tp->t_state, TS_CNTTB))
2396		CLR(tp->t_lflag, FLUSHO);
2397	if ((!ISSET(tp->t_lflag, ECHO) &&
2398	     (c != '\n' || !ISSET(tp->t_lflag, ECHONL))) ||
2399	    ISSET(tp->t_lflag, EXTPROC))
2400		return;
2401	if (ISSET(tp->t_lflag, ECHOCTL) &&
2402	    ((ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n') ||
2403	    ISSET(c, TTY_CHARMASK) == 0177)) {
2404		(void)ttyoutput('^', tp);
2405		CLR(c, ~TTY_CHARMASK);
2406		if (c == 0177)
2407			c = '?';
2408		else
2409			c += 'A' - 1;
2410	}
2411	(void)ttyoutput(c, tp);
2412}
2413
2414/*
2415 * Wake up any readers on a tty.
2416 */
2417void
2418ttwakeup(struct tty *tp)
2419{
2420
2421	if (SEL_WAITING(&tp->t_rsel))
2422		selwakeuppri(&tp->t_rsel, TTIPRI);
2423	if (ISSET(tp->t_state, TS_ASYNC) && tp->t_sigio != NULL)
2424		pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
2425	wakeup(TSA_HUP_OR_INPUT(tp));
2426	KNOTE_UNLOCKED(&tp->t_rsel.si_note, 0);
2427}
2428
2429/*
2430 * Wake up any writers on a tty.
2431 */
2432void
2433ttwwakeup(struct tty *tp)
2434{
2435
2436	if (SEL_WAITING(&tp->t_wsel) && tp->t_outq.c_cc <= tp->t_olowat)
2437		selwakeuppri(&tp->t_wsel, TTOPRI);
2438	if (ISSET(tp->t_state, TS_ASYNC) && tp->t_sigio != NULL)
2439		pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
2440	if (ISSET(tp->t_state, TS_BUSY | TS_SO_OCOMPLETE) ==
2441	    TS_SO_OCOMPLETE && tp->t_outq.c_cc == 0) {
2442		CLR(tp->t_state, TS_SO_OCOMPLETE);
2443		wakeup(TSA_OCOMPLETE(tp));
2444	}
2445	if (ISSET(tp->t_state, TS_SO_OLOWAT) &&
2446	    tp->t_outq.c_cc <= tp->t_olowat) {
2447		CLR(tp->t_state, TS_SO_OLOWAT);
2448		wakeup(TSA_OLOWAT(tp));
2449	}
2450	KNOTE_UNLOCKED(&tp->t_wsel.si_note, 0);
2451}
2452
2453/*
2454 * Look up a code for a specified speed in a conversion table;
2455 * used by drivers to map software speed values to hardware parameters.
2456 */
2457int
2458ttspeedtab(int speed, struct speedtab *table)
2459{
2460
2461	for ( ; table->sp_speed != -1; table++)
2462		if (table->sp_speed == speed)
2463			return (table->sp_code);
2464	return (-1);
2465}
2466
2467/*
2468 * Set input and output watermarks and buffer sizes.  For input, the
2469 * high watermark is about one second's worth of input above empty, the
2470 * low watermark is slightly below high water, and the buffer size is a
2471 * driver-dependent amount above high water.  For output, the watermarks
2472 * are near the ends of the buffer, with about 1 second's worth of input
2473 * between them.  All this only applies to the standard line discipline.
2474 */
2475void
2476ttsetwater(struct tty *tp)
2477{
2478	int cps, ttmaxhiwat, x;
2479
2480	/* Input. */
2481	clist_alloc_cblocks(&tp->t_canq, TTYHOG, 512);
2482	switch (tp->t_ispeedwat) {
2483	case (speed_t)-1:
2484		cps = tp->t_ispeed / 10;
2485		break;
2486	case 0:
2487		/*
2488		 * This case is for old drivers that don't know about
2489		 * t_ispeedwat.  Arrange for them to get the old buffer
2490		 * sizes and watermarks.
2491		 */
2492		cps = TTYHOG - 2 * 256;
2493		tp->t_ififosize = 2 * 256;
2494		break;
2495	default:
2496		cps = tp->t_ispeedwat / 10;
2497		break;
2498	}
2499	tp->t_ihiwat = cps;
2500	tp->t_ilowat = 7 * cps / 8;
2501	x = cps + tp->t_ififosize;
2502	clist_alloc_cblocks(&tp->t_rawq, x, x);
2503
2504	/* Output. */
2505	switch (tp->t_ospeedwat) {
2506	case (speed_t)-1:
2507		cps = tp->t_ospeed / 10;
2508		ttmaxhiwat = 2 * TTMAXHIWAT;
2509		break;
2510	case 0:
2511		cps = tp->t_ospeed / 10;
2512		ttmaxhiwat = TTMAXHIWAT;
2513		break;
2514	default:
2515		cps = tp->t_ospeedwat / 10;
2516		ttmaxhiwat = 8 * TTMAXHIWAT;
2517		break;
2518	}
2519#define CLAMP(x, h, l)	((x) > h ? h : ((x) < l) ? l : (x))
2520	tp->t_olowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
2521	x += cps;
2522	x = CLAMP(x, ttmaxhiwat, TTMINHIWAT);	/* XXX clamps are too magic */
2523	tp->t_ohiwat = roundup(x, CBSIZE);	/* XXX for compat */
2524	x = imax(tp->t_ohiwat, TTMAXHIWAT);	/* XXX for compat/safety */
2525	x += OBUFSIZ + 100;
2526	clist_alloc_cblocks(&tp->t_outq, x, x);
2527#undef	CLAMP
2528}
2529
2530/*
2531 * Report on state of foreground process group.
2532 */
2533void
2534ttyinfo(struct tty *tp)
2535{
2536	struct timeval utime, stime;
2537	struct proc *p, *pick;
2538	struct thread *td;
2539	const char *stateprefix, *state;
2540	long rss;
2541	int load, pctcpu;
2542
2543	if (ttycheckoutq(tp,0) == 0)
2544		return;
2545
2546	/* Print load average. */
2547	load = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
2548	ttyprintf(tp, "load: %d.%02d ", load / 100, load % 100);
2549
2550	/*
2551	 * On return following a ttyprintf(), we set tp->t_rocount to 0 so
2552	 * that pending input will be retyped on BS.
2553	 */
2554	if (tp->t_session == NULL) {
2555		ttyprintf(tp, "not a controlling terminal\n");
2556		tp->t_rocount = 0;
2557		return;
2558	}
2559	if (tp->t_pgrp == NULL) {
2560		ttyprintf(tp, "no foreground process group\n");
2561		tp->t_rocount = 0;
2562		return;
2563	}
2564	sx_slock(&proctree_lock);
2565	if ((p = LIST_FIRST(&tp->t_pgrp->pg_members)) == NULL) {
2566		sx_sunlock(&proctree_lock);
2567		ttyprintf(tp, "empty foreground process group\n");
2568		tp->t_rocount = 0;
2569		return;
2570	}
2571
2572	/*
2573	 * Pick the most interesting process and copy some of its
2574	 * state for printing later.  sched_lock must be held for
2575	 * most parts of this.  Holding it throughout is simplest
2576	 * and prevents even unimportant inconsistencies in the
2577	 * copy of the state, but may increase interrupt latency
2578	 * too much.
2579	 */
2580	mtx_lock_spin(&sched_lock);
2581	for (pick = NULL; p != NULL; p = LIST_NEXT(p, p_pglist))
2582		if (proc_compare(pick, p))
2583			pick = p;
2584
2585	td = FIRST_THREAD_IN_PROC(pick);	/* XXXKSE */
2586#if 0
2587	KASSERT(td != NULL, ("ttyinfo: no thread"));
2588#else
2589	if (td == NULL) {
2590		mtx_unlock_spin(&sched_lock);
2591		sx_sunlock(&proctree_lock);
2592		ttyprintf(tp, "foreground process without thread\n");
2593		tp->t_rocount = 0;
2594		return;
2595	}
2596#endif
2597	stateprefix = "";
2598	if (TD_IS_RUNNING(td))
2599		state = "running";
2600	else if (TD_ON_RUNQ(td) || TD_CAN_RUN(td))
2601		state = "runnable";
2602	else if (TD_IS_SLEEPING(td)) {
2603		/* XXX: If we're sleeping, are we ever not in a queue? */
2604		if (TD_ON_SLEEPQ(td))
2605			state = td->td_wmesg;
2606		else
2607			state = "sleeping without queue";
2608	} else if (TD_ON_LOCK(td)) {
2609		state = td->td_lockname;
2610		stateprefix = "*";
2611	} else if (TD_IS_SUSPENDED(td))
2612		state = "suspended";
2613	else if (TD_AWAITING_INTR(td))
2614		state = "intrwait";
2615	else
2616		state = "unknown";
2617	pctcpu = (sched_pctcpu(td) * 10000 + FSCALE / 2) >> FSHIFT;
2618	if (pick->p_state == PRS_NEW || pick->p_state == PRS_ZOMBIE)
2619		rss = 0;
2620	else
2621		rss = pgtok(vmspace_resident_count(pick->p_vmspace));
2622	mtx_unlock_spin(&sched_lock);
2623	PROC_LOCK(pick);
2624	calcru(pick, &utime, &stime);
2625	PROC_UNLOCK(pick);
2626
2627	/* Print command, pid, state, utime, stime, %cpu, and rss. */
2628	ttyprintf(tp,
2629	    " cmd: %s %d [%s%s] %ld.%02ldu %ld.%02lds %d%% %ldk\n",
2630	    pick->p_comm, pick->p_pid, stateprefix, state,
2631	    (long)utime.tv_sec, utime.tv_usec / 10000,
2632	    (long)stime.tv_sec, stime.tv_usec / 10000,
2633	    pctcpu / 100, rss);
2634	tp->t_rocount = 0;
2635	sx_sunlock(&proctree_lock);
2636}
2637
2638/*
2639 * Returns 1 if p2 is "better" than p1
2640 *
2641 * The algorithm for picking the "interesting" process is thus:
2642 *
2643 *	1) Only foreground processes are eligible - implied.
2644 *	2) Runnable processes are favored over anything else.  The runner
2645 *	   with the highest cpu utilization is picked (p_estcpu).  Ties are
2646 *	   broken by picking the highest pid.
2647 *	3) The sleeper with the shortest sleep time is next.  With ties,
2648 *	   we pick out just "short-term" sleepers (P_SINTR == 0).
2649 *	4) Further ties are broken by picking the highest pid.
2650 */
2651#define ISRUN(p, val)						\
2652do {								\
2653	struct thread *td;					\
2654	val = 0;						\
2655	FOREACH_THREAD_IN_PROC(p, td) {				\
2656		if (TD_ON_RUNQ(td) ||				\
2657		    TD_IS_RUNNING(td)) {			\
2658			val = 1;				\
2659			break;					\
2660		}						\
2661	}							\
2662} while (0)
2663
2664#define TESTAB(a, b)    ((a)<<1 | (b))
2665#define ONLYA   2
2666#define ONLYB   1
2667#define BOTH    3
2668
2669static int
2670proc_compare(struct proc *p1, struct proc *p2)
2671{
2672
2673	int esta, estb;
2674	struct ksegrp *kg;
2675	mtx_assert(&sched_lock, MA_OWNED);
2676	if (p1 == NULL)
2677		return (1);
2678
2679	ISRUN(p1, esta);
2680	ISRUN(p2, estb);
2681
2682	/*
2683	 * see if at least one of them is runnable
2684	 */
2685	switch (TESTAB(esta, estb)) {
2686	case ONLYA:
2687		return (0);
2688	case ONLYB:
2689		return (1);
2690	case BOTH:
2691		/*
2692		 * tie - favor one with highest recent cpu utilization
2693		 */
2694		esta = estb = 0;
2695		FOREACH_KSEGRP_IN_PROC(p1,kg) {
2696			esta += kg->kg_estcpu;
2697		}
2698		FOREACH_KSEGRP_IN_PROC(p2,kg) {
2699			estb += kg->kg_estcpu;
2700		}
2701		if (estb > esta)
2702			return (1);
2703		if (esta > estb)
2704			return (0);
2705		return (p2->p_pid > p1->p_pid);	/* tie - return highest pid */
2706	}
2707	/*
2708	 * weed out zombies
2709	 */
2710	switch (TESTAB(p1->p_state == PRS_ZOMBIE, p2->p_state == PRS_ZOMBIE)) {
2711	case ONLYA:
2712		return (1);
2713	case ONLYB:
2714		return (0);
2715	case BOTH:
2716		return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
2717	}
2718
2719#if 0 /* XXXKSE */
2720	/*
2721	 * pick the one with the smallest sleep time
2722	 */
2723	if (p2->p_slptime > p1->p_slptime)
2724		return (0);
2725	if (p1->p_slptime > p2->p_slptime)
2726		return (1);
2727	/*
2728	 * favor one sleeping in a non-interruptible sleep
2729	 */
2730	if (p1->p_sflag & PS_SINTR && (p2->p_sflag & PS_SINTR) == 0)
2731		return (1);
2732	if (p2->p_sflag & PS_SINTR && (p1->p_sflag & PS_SINTR) == 0)
2733		return (0);
2734#endif
2735	return (p2->p_pid > p1->p_pid);		/* tie - return highest pid */
2736}
2737
2738/*
2739 * Output char to tty; console putchar style.
2740 */
2741int
2742tputchar(int c, struct tty *tp)
2743{
2744	int s;
2745
2746	s = spltty();
2747	if (!ISSET(tp->t_state, TS_CONNECTED)) {
2748		splx(s);
2749		return (-1);
2750	}
2751	if (c == '\n')
2752		(void)ttyoutput('\r', tp);
2753	(void)ttyoutput(c, tp);
2754	ttstart(tp);
2755	splx(s);
2756	return (0);
2757}
2758
2759/*
2760 * Sleep on chan, returning ERESTART if tty changed while we napped and
2761 * returning any errors (e.g. EINTR/EWOULDBLOCK) reported by tsleep.  If
2762 * the tty is revoked, restarting a pending call will redo validation done
2763 * at the start of the call.
2764 */
2765int
2766ttysleep(struct tty *tp, void *chan, int pri, char *wmesg, int timo)
2767{
2768	int error;
2769	int gen;
2770
2771	gen = tp->t_gen;
2772	error = tsleep(chan, pri, wmesg, timo);
2773	if (tp->t_state & TS_GONE)
2774		return (ENXIO);
2775	if (error)
2776		return (error);
2777	return (tp->t_gen == gen ? 0 : ERESTART);
2778}
2779
2780/*
2781 * Gain a reference to a TTY
2782 */
2783int
2784ttyref(struct tty *tp)
2785{
2786	int i;
2787
2788	mtx_lock(&tp->t_mtx);
2789	KASSERT(tp->t_refcnt > 0,
2790	    ("ttyref(): tty refcnt is %d (%s)",
2791	    tp->t_refcnt, tp->t_dev != NULL ? devtoname(tp->t_dev) : "??"));
2792	i = ++tp->t_refcnt;
2793	mtx_unlock(&tp->t_mtx);
2794	return (i);
2795}
2796
2797/*
2798 * Drop a reference to a TTY.
2799 * When reference count drops to zero, we free it.
2800 */
2801int
2802ttyrel(struct tty *tp)
2803{
2804	int i;
2805
2806	mtx_lock(&tty_list_mutex);
2807	mtx_lock(&tp->t_mtx);
2808	KASSERT(tp->t_refcnt > 0,
2809	    ("ttyrel(): tty refcnt is %d (%s)",
2810	    tp->t_refcnt, tp->t_dev != NULL ? devtoname(tp->t_dev) : "??"));
2811	i = --tp->t_refcnt;
2812	if (i != 0) {
2813		mtx_unlock(&tp->t_mtx);
2814		mtx_unlock(&tty_list_mutex);
2815		return (i);
2816	}
2817	TAILQ_REMOVE(&tty_list, tp, t_list);
2818	mtx_unlock(&tp->t_mtx);
2819	mtx_unlock(&tty_list_mutex);
2820	knlist_destroy(&tp->t_rsel.si_note);
2821	knlist_destroy(&tp->t_wsel.si_note);
2822	mtx_destroy(&tp->t_mtx);
2823	free(tp, M_TTYS);
2824	return (i);
2825}
2826
2827/*
2828 * Allocate a tty struct.  Clists in the struct will be allocated by
2829 * tty_open().
2830 */
2831struct tty *
2832ttymalloc(struct tty *tp)
2833{
2834	static int once;
2835
2836	if (!once) {
2837		mtx_init(&tty_list_mutex, "ttylist", NULL, MTX_DEF);
2838		once++;
2839	}
2840
2841	if (tp) {
2842		/*
2843		 * XXX: Either this argument should go away, or we should
2844		 * XXX: require it and do a ttyrel(tp) here and allocate
2845		 * XXX: a new tty.  For now do nothing.
2846		 */
2847		return(tp);
2848	}
2849	tp = malloc(sizeof *tp, M_TTYS, M_WAITOK | M_ZERO);
2850	mtx_init(&tp->t_mtx, "tty", NULL, MTX_DEF);
2851
2852	/*
2853	 * Set up the initial state
2854	 */
2855	tp->t_refcnt = 1;
2856	tp->t_timeout = -1;
2857	tp->t_dtr_wait = 3 * hz;
2858
2859	ttyinitmode(tp, 0, 0);
2860	bcopy(ttydefchars, tp->t_init_in.c_cc, sizeof tp->t_init_in.c_cc);
2861
2862	/* Make callout the same as callin */
2863	tp->t_init_out = tp->t_init_in;
2864
2865	mtx_lock(&tty_list_mutex);
2866	TAILQ_INSERT_TAIL(&tty_list, tp, t_list);
2867	mtx_unlock(&tty_list_mutex);
2868	knlist_init(&tp->t_rsel.si_note, &tp->t_mtx, NULL, NULL, NULL);
2869	knlist_init(&tp->t_wsel.si_note, &tp->t_mtx, NULL, NULL, NULL);
2870	return (tp);
2871}
2872
2873struct tty *
2874ttyalloc()
2875{
2876
2877	return (ttymalloc(NULL));
2878}
2879
2880static void
2881ttypurge(struct cdev *dev)
2882{
2883
2884	if (dev->si_tty == NULL)
2885		return;
2886	ttygone(dev->si_tty);
2887}
2888
2889/*
2890 * ttycreate()
2891 *
2892 * Create the device entries for this tty thereby opening it for business.
2893 *
2894 * The flags argument controls if "cua" units are created.
2895 *
2896 * The t_sc filed is copied to si_drv1 in the created cdevs.  This
2897 * is particularly important for ->t_cioctl() users.
2898 *
2899 * XXX: implement the init and lock devices by cloning.
2900 */
2901
2902int
2903ttycreate(struct tty *tp, int flags, const char *fmt, ...)
2904{
2905	char namebuf[SPECNAMELEN - 3];		/* XXX space for "tty" */
2906	struct cdevsw *csw = NULL;
2907	int unit = 0;
2908	va_list ap;
2909	struct cdev *cp;
2910	int i, minor, sminor, sunit;
2911
2912	mtx_assert(&Giant, MA_OWNED);
2913
2914	if (tty_unit == NULL)
2915		tty_unit = new_unrhdr(0, 0xffff, NULL);
2916
2917	sunit = alloc_unr(tty_unit);
2918	tp->t_devunit = sunit;
2919
2920	if (csw == NULL) {
2921		csw = &tty_cdevsw;
2922		unit = sunit;
2923	}
2924	KASSERT(csw->d_purge == NULL || csw->d_purge == ttypurge,
2925	    ("tty should not have d_purge"));
2926
2927	csw->d_purge = ttypurge;
2928
2929	minor = unit2minor(unit);
2930	sminor = unit2minor(sunit);
2931	va_start(ap, fmt);
2932	i = vsnrprintf(namebuf, sizeof namebuf, 32, fmt, ap);
2933	va_end(ap);
2934	KASSERT(i < sizeof namebuf, ("Too long tty name (%s)", namebuf));
2935
2936	cp = make_dev(csw, minor,
2937	    UID_ROOT, GID_WHEEL, 0600, "tty%s", namebuf);
2938	tp->t_dev = cp;
2939	tp->t_mdev = cp;
2940	cp->si_tty = tp;
2941	cp->si_drv1 = tp->t_sc;
2942
2943	cp = make_dev(&ttys_cdevsw, sminor | MINOR_INIT,
2944	    UID_ROOT, GID_WHEEL, 0600, "tty%s.init", namebuf);
2945	dev_depends(tp->t_dev, cp);
2946	cp->si_drv1 = tp->t_sc;
2947	cp->si_drv2 = &tp->t_init_in;
2948	cp->si_tty = tp;
2949
2950	cp = make_dev(&ttys_cdevsw, sminor | MINOR_LOCK,
2951	    UID_ROOT, GID_WHEEL, 0600, "tty%s.lock", namebuf);
2952	dev_depends(tp->t_dev, cp);
2953	cp->si_drv1 = tp->t_sc;
2954	cp->si_drv2 = &tp->t_lock_in;
2955	cp->si_tty = tp;
2956
2957	if (flags & TS_CALLOUT) {
2958		cp = make_dev(csw, minor | MINOR_CALLOUT,
2959		    UID_UUCP, GID_DIALER, 0660, "cua%s", namebuf);
2960		dev_depends(tp->t_dev, cp);
2961		cp->si_drv1 = tp->t_sc;
2962		cp->si_tty = tp;
2963
2964		cp = make_dev(&ttys_cdevsw, sminor | MINOR_CALLOUT | MINOR_INIT,
2965		    UID_UUCP, GID_DIALER, 0660, "cua%s.init", namebuf);
2966		dev_depends(tp->t_dev, cp);
2967		cp->si_drv1 = tp->t_sc;
2968		cp->si_drv2 = &tp->t_init_out;
2969		cp->si_tty = tp;
2970
2971		cp = make_dev(&ttys_cdevsw, sminor | MINOR_CALLOUT | MINOR_LOCK,
2972		    UID_UUCP, GID_DIALER, 0660, "cua%s.lock", namebuf);
2973		dev_depends(tp->t_dev, cp);
2974		cp->si_drv1 = tp->t_sc;
2975		cp->si_drv2 = &tp->t_lock_out;
2976		cp->si_tty = tp;
2977	}
2978
2979	return (0);
2980}
2981
2982/*
2983 * This function is called when the hardware disappears.  We set a flag
2984 * and wake up stuff so all sleeping threads will notice.
2985 */
2986void
2987ttygone(struct tty *tp)
2988{
2989
2990	tp->t_state |= TS_GONE;
2991	wakeup(&tp->t_dtr_wait);
2992	wakeup(TSA_CARR_ON(tp));
2993	wakeup(TSA_HUP_OR_INPUT(tp));
2994	wakeup(TSA_OCOMPLETE(tp));
2995	wakeup(TSA_OLOWAT(tp));
2996	if (tp->t_purge != NULL)
2997		tp->t_purge(tp);
2998}
2999
3000/*
3001 * ttyfree()
3002 *
3003 * Called when the driver is ready to free the tty structure.
3004 *
3005 * XXX: This shall sleep until all threads have left the driver.
3006 */
3007
3008void
3009ttyfree(struct tty *tp)
3010{
3011	u_int unit;
3012
3013	mtx_assert(&Giant, MA_OWNED);
3014	ttygone(tp);
3015	unit = tp->t_devunit;
3016	destroy_dev(tp->t_mdev);
3017	free_unr(tty_unit, unit);
3018}
3019
3020static int
3021sysctl_kern_ttys(SYSCTL_HANDLER_ARGS)
3022{
3023	struct tty *tp, *tp2;
3024	struct xtty xt;
3025	int error;
3026
3027	error = 0;
3028	mtx_lock(&tty_list_mutex);
3029	tp = TAILQ_FIRST(&tty_list);
3030	if (tp != NULL)
3031		ttyref(tp);
3032	mtx_unlock(&tty_list_mutex);
3033	while (tp != NULL) {
3034		bzero(&xt, sizeof xt);
3035		xt.xt_size = sizeof xt;
3036#define XT_COPY(field) xt.xt_##field = tp->t_##field
3037		xt.xt_rawcc = tp->t_rawq.c_cc;
3038		xt.xt_cancc = tp->t_canq.c_cc;
3039		xt.xt_outcc = tp->t_outq.c_cc;
3040		XT_COPY(line);
3041		if (tp->t_dev != NULL)
3042			xt.xt_dev = dev2udev(tp->t_dev);
3043		XT_COPY(state);
3044		XT_COPY(flags);
3045		XT_COPY(timeout);
3046		if (tp->t_pgrp != NULL)
3047			xt.xt_pgid = tp->t_pgrp->pg_id;
3048		if (tp->t_session != NULL)
3049			xt.xt_sid = tp->t_session->s_sid;
3050		XT_COPY(termios);
3051		XT_COPY(winsize);
3052		XT_COPY(column);
3053		XT_COPY(rocount);
3054		XT_COPY(rocol);
3055		XT_COPY(ififosize);
3056		XT_COPY(ihiwat);
3057		XT_COPY(ilowat);
3058		XT_COPY(ispeedwat);
3059		XT_COPY(ohiwat);
3060		XT_COPY(olowat);
3061		XT_COPY(ospeedwat);
3062#undef XT_COPY
3063		error = SYSCTL_OUT(req, &xt, sizeof xt);
3064		if (error != 0) {
3065			ttyrel(tp);
3066			return (error);
3067		}
3068		mtx_lock(&tty_list_mutex);
3069		tp2 = TAILQ_NEXT(tp, t_list);
3070		if (tp2 != NULL)
3071			ttyref(tp2);
3072		mtx_unlock(&tty_list_mutex);
3073		ttyrel(tp);
3074		tp = tp2;
3075	}
3076	return (0);
3077}
3078
3079SYSCTL_PROC(_kern, OID_AUTO, ttys, CTLTYPE_OPAQUE|CTLFLAG_RD,
3080	0, 0, sysctl_kern_ttys, "S,xtty", "All ttys");
3081SYSCTL_LONG(_kern, OID_AUTO, tty_nin, CTLFLAG_RD,
3082	&tk_nin, 0, "Total TTY in characters");
3083SYSCTL_LONG(_kern, OID_AUTO, tty_nout, CTLFLAG_RD,
3084	&tk_nout, 0, "Total TTY out characters");
3085
3086void
3087nottystop(struct tty *tp, int rw)
3088{
3089
3090	return;
3091}
3092
3093int
3094ttyopen(struct cdev *dev, int flag, int mode, struct thread *td)
3095{
3096	int		error;
3097	int		s;
3098	struct tty	*tp;
3099
3100	tp = dev->si_tty;
3101	s = spltty();
3102	/*
3103	 * We jump to this label after all non-interrupted sleeps to pick
3104	 * up any changes of the device state.
3105	 */
3106open_top:
3107	if (tp->t_state & TS_GONE)
3108		return (ENXIO);
3109	error = ttydtrwaitsleep(tp);
3110	if (error)
3111		goto out;
3112	if (tp->t_state & TS_ISOPEN) {
3113		/*
3114		 * The device is open, so everything has been initialized.
3115		 * Handle conflicts.
3116		 */
3117		if (ISCALLOUT(dev) && !tp->t_actout)
3118			return (EBUSY);
3119		if (tp->t_actout && !ISCALLOUT(dev)) {
3120			if (flag & O_NONBLOCK)
3121				return (EBUSY);
3122			error =	tsleep(&tp->t_actout,
3123				       TTIPRI | PCATCH, "ttybi", 0);
3124			if (error != 0 || (tp->t_flags & TS_GONE))
3125				goto out;
3126			goto open_top;
3127		}
3128		if (tp->t_state & TS_XCLUDE && suser(td))
3129			return (EBUSY);
3130	} else {
3131		/*
3132		 * The device isn't open, so there are no conflicts.
3133		 * Initialize it.  Initialization is done twice in many
3134		 * cases: to preempt sleeping callin opens if we are
3135		 * callout, and to complete a callin open after DCD rises.
3136		 */
3137		tp->t_termios = ISCALLOUT(dev) ? tp->t_init_out : tp->t_init_in;
3138		tp->t_cflag = tp->t_termios.c_cflag;
3139		if (tp->t_modem != NULL)
3140			tp->t_modem(tp, SER_DTR | SER_RTS, 0);
3141		++tp->t_wopeners;
3142		error = tp->t_param(tp, &tp->t_termios);
3143		--tp->t_wopeners;
3144		if (error == 0 && tp->t_open != NULL)
3145			error = tp->t_open(tp, dev);
3146		if (error != 0)
3147			goto out;
3148		if (ISCALLOUT(dev) || (tp->t_modem != NULL &&
3149		    (tp->t_modem(tp, 0, 0) & SER_DCD)))
3150			ttyld_modem(tp, 1);
3151	}
3152	/*
3153	 * Wait for DCD if necessary.
3154	 */
3155	if (!(tp->t_state & TS_CARR_ON) && !ISCALLOUT(dev)
3156	    && !(tp->t_cflag & CLOCAL) && !(flag & O_NONBLOCK)) {
3157		++tp->t_wopeners;
3158		error = tsleep(TSA_CARR_ON(tp), TTIPRI | PCATCH, "ttydcd", 0);
3159		--tp->t_wopeners;
3160		if (error != 0 || (tp->t_state & TS_GONE))
3161			goto out;
3162		goto open_top;
3163	}
3164	error =	ttyld_open(tp, dev);
3165	ttyldoptim(tp);
3166	if (tp->t_state & TS_ISOPEN && ISCALLOUT(dev))
3167		tp->t_actout = TRUE;
3168out:
3169	splx(s);
3170	if (!(tp->t_state & TS_ISOPEN) && tp->t_wopeners == 0 &&
3171	    tp->t_close != NULL)
3172		tp->t_close(tp);
3173	return (error);
3174}
3175
3176int
3177ttyclose(struct cdev *dev, int flag, int mode, struct thread *td)
3178{
3179	struct tty *tp;
3180
3181	tp = dev->si_tty;
3182	ttyld_close(tp, flag);
3183	ttyldoptim(tp);
3184	if (tp->t_close != NULL)
3185		tp->t_close(tp);
3186	tp->t_do_timestamp = 0;
3187	if (tp->t_pps != NULL)
3188		tp->t_pps->ppsparam.mode = 0;
3189	tty_close(tp);
3190	return (0);
3191}
3192
3193int
3194ttyread(struct cdev *dev, struct uio *uio, int flag)
3195{
3196	struct tty *tp;
3197
3198	tp = tty_gettp(dev);
3199
3200	if (tp->t_state & TS_GONE)
3201		return (ENODEV);
3202	return (ttyld_read(tp, uio, flag));
3203}
3204
3205int
3206ttywrite(struct cdev *dev, struct uio *uio, int flag)
3207{
3208	struct tty *tp;
3209
3210	tp = tty_gettp(dev);
3211
3212	if (tp->t_state & TS_GONE)
3213		return (ENODEV);
3214	return (ttyld_write(tp, uio, flag));
3215}
3216
3217int
3218ttyioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
3219{
3220	struct	tty *tp;
3221	int	error;
3222
3223	tp = dev->si_tty;
3224
3225	if (cmd == TIOCSETA || cmd == TIOCSETAW || cmd == TIOCSETAF) {
3226		int cc;
3227		struct termios *dt = (struct termios *)data;
3228		struct termios *lt =
3229		    ISCALLOUT(dev) ?  &tp->t_lock_out : &tp->t_lock_in;
3230
3231		dt->c_iflag = (tp->t_iflag & lt->c_iflag)
3232		    | (dt->c_iflag & ~lt->c_iflag);
3233		dt->c_oflag = (tp->t_oflag & lt->c_oflag)
3234		    | (dt->c_oflag & ~lt->c_oflag);
3235		dt->c_cflag = (tp->t_cflag & lt->c_cflag)
3236		    | (dt->c_cflag & ~lt->c_cflag);
3237		dt->c_lflag = (tp->t_lflag & lt->c_lflag)
3238		    | (dt->c_lflag & ~lt->c_lflag);
3239		for (cc = 0; cc < NCCS; ++cc)
3240		    if (lt->c_cc[cc] != 0)
3241		        dt->c_cc[cc] = tp->t_cc[cc];
3242		if (lt->c_ispeed != 0)
3243		    dt->c_ispeed = tp->t_ispeed;
3244		if (lt->c_ospeed != 0)
3245		    dt->c_ospeed = tp->t_ospeed;
3246	}
3247
3248	error = ttyld_ioctl(tp, cmd, data, flag, td);
3249	if (error == ENOIOCTL)
3250		error = ttioctl(tp, cmd, data, flag);
3251	ttyldoptim(tp);
3252	if (error != ENOIOCTL)
3253		return (error);
3254	return (ENOTTY);
3255}
3256
3257void
3258ttyldoptim(struct tty *tp)
3259{
3260	struct termios	*t;
3261
3262	t = &tp->t_termios;
3263	if (!(t->c_iflag & (ICRNL | IGNCR | IMAXBEL | INLCR | ISTRIP | IXON))
3264	    && (!(t->c_iflag & BRKINT) || (t->c_iflag & IGNBRK))
3265	    && (!(t->c_iflag & PARMRK)
3266		|| (t->c_iflag & (IGNPAR | IGNBRK)) == (IGNPAR | IGNBRK))
3267	    && !(t->c_lflag & (ECHO | ICANON | IEXTEN | ISIG | PENDIN))
3268	    && linesw[tp->t_line]->l_rint == ttyinput)
3269		tp->t_state |= TS_CAN_BYPASS_L_RINT;
3270	else
3271		tp->t_state &= ~TS_CAN_BYPASS_L_RINT;
3272}
3273
3274static void
3275ttydtrwaitwakeup(void *arg)
3276{
3277	struct tty *tp;
3278
3279	tp = arg;
3280	tp->t_state &= ~TS_DTR_WAIT;
3281	wakeup(&tp->t_dtr_wait);
3282}
3283
3284
3285void
3286ttydtrwaitstart(struct tty *tp)
3287{
3288
3289	if (tp->t_dtr_wait == 0)
3290		return;
3291	if (tp->t_state & TS_DTR_WAIT)
3292		return;
3293	timeout(ttydtrwaitwakeup, tp, tp->t_dtr_wait);
3294	tp->t_state |= TS_DTR_WAIT;
3295}
3296
3297int
3298ttydtrwaitsleep(struct tty *tp)
3299{
3300	int error;
3301
3302	error = 0;
3303	while (error == 0) {
3304		if (tp->t_state & TS_GONE)
3305			error = ENXIO;
3306		else if (!(tp->t_state & TS_DTR_WAIT))
3307			break;
3308		else
3309			error = tsleep(&tp->t_dtr_wait, TTIPRI | PCATCH,
3310			    "dtrwait", 0);
3311	}
3312	return (error);
3313}
3314
3315static int
3316ttysopen(struct cdev *dev, int flag, int mode, struct thread *td)
3317{
3318	struct tty *tp;
3319
3320	tp = dev->si_tty;
3321	KASSERT(tp != NULL,
3322	    ("ttysopen(): no tty pointer on device (%s)", devtoname(dev)));
3323	if (tp->t_state & TS_GONE)
3324		return (ENODEV);
3325	return (0);
3326}
3327
3328static int
3329ttysclose(struct cdev *dev, int flag, int mode, struct thread *td)
3330{
3331
3332	return (0);
3333}
3334
3335static int
3336ttysrdwr(struct cdev *dev, struct uio *uio, int flag)
3337{
3338
3339	return (ENODEV);
3340}
3341
3342static int
3343ttysioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
3344{
3345	struct tty	*tp;
3346	int		error;
3347	struct termios	*ct;
3348
3349	tp = dev->si_tty;
3350	KASSERT(tp != NULL,
3351	    ("ttysopen(): no tty pointer on device (%s)", devtoname(dev)));
3352	if (tp->t_state & TS_GONE)
3353		return (ENODEV);
3354	ct = dev->si_drv2;
3355	switch (cmd) {
3356	case TIOCSETA:
3357		error = suser(td);
3358		if (error != 0)
3359			return (error);
3360		*ct = *(struct termios *)data;
3361		return (0);
3362	case TIOCGETA:
3363		*(struct termios *)data = *ct;
3364		return (0);
3365	case TIOCGETD:
3366		*(int *)data = TTYDISC;
3367		return (0);
3368	case TIOCGWINSZ:
3369		bzero(data, sizeof(struct winsize));
3370		return (0);
3371	default:
3372		if (tp->t_cioctl != NULL)
3373			return(tp->t_cioctl(dev, cmd, data, flag, td));
3374		return (ENOTTY);
3375	}
3376}
3377
3378/*
3379 * Initialize a tty to sane modes.
3380 */
3381void
3382ttyinitmode(struct tty *tp, int echo, int speed)
3383{
3384
3385	if (speed == 0)
3386		speed = TTYDEF_SPEED;
3387	tp->t_init_in.c_iflag = TTYDEF_IFLAG;
3388	tp->t_init_in.c_oflag = TTYDEF_OFLAG;
3389	tp->t_init_in.c_cflag = TTYDEF_CFLAG;
3390	if (echo)
3391		tp->t_init_in.c_lflag = TTYDEF_LFLAG_ECHO;
3392	else
3393		tp->t_init_in.c_lflag = TTYDEF_LFLAG_NOECHO;
3394
3395	tp->t_init_in.c_ispeed = tp->t_init_in.c_ospeed = speed;
3396	termioschars(&tp->t_init_in);
3397	tp->t_init_out = tp->t_init_in;
3398	tp->t_termios = tp->t_init_in;
3399}
3400
3401/*
3402 * Use more "normal" termios paramters for consoles.
3403 */
3404void
3405ttyconsolemode(struct tty *tp, int speed)
3406{
3407
3408	if (speed == 0)
3409		speed = TTYDEF_SPEED;
3410	ttyinitmode(tp, 1, speed);
3411	tp->t_init_in.c_cflag |= CLOCAL;
3412	tp->t_lock_out.c_cflag = tp->t_lock_in.c_cflag = CLOCAL;
3413	tp->t_lock_out.c_ispeed = tp->t_lock_out.c_ospeed =
3414	tp->t_lock_in.c_ispeed = tp->t_lock_in.c_ospeed = speed;
3415	tp->t_init_out = tp->t_init_in;
3416	tp->t_termios = tp->t_init_in;
3417}
3418
3419/*
3420 * Record the relationship between the serial ports notion of modem control
3421 * signals and the one used in certain ioctls in a way the compiler can enforce
3422 * XXX: We should define TIOCM_* in terms of SER_ if we can limit the
3423 * XXX: consequences of the #include work that would take.
3424 */
3425CTASSERT(SER_DTR == TIOCM_DTR / 2);
3426CTASSERT(SER_RTS == TIOCM_RTS / 2);
3427CTASSERT(SER_STX == TIOCM_ST / 2);
3428CTASSERT(SER_SRX == TIOCM_SR / 2);
3429CTASSERT(SER_CTS == TIOCM_CTS / 2);
3430CTASSERT(SER_DCD == TIOCM_DCD / 2);
3431CTASSERT(SER_RI == TIOCM_RI / 2);
3432CTASSERT(SER_DSR == TIOCM_DSR / 2);
3433
3434