tty.c revision 188096
1/*-
2 * Copyright (c) 2008 Ed Schouten <ed@FreeBSD.org>
3 * All rights reserved.
4 *
5 * Portions of this software were developed under sponsorship from Snow
6 * B.V., the Netherlands.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 */
29
30#include <sys/cdefs.h>
31__FBSDID("$FreeBSD: head/sys/kern/tty.c 188096 2009-02-03 19:58:28Z ed $");
32
33#include "opt_compat.h"
34
35#include <sys/param.h>
36#include <sys/conf.h>
37#include <sys/cons.h>
38#include <sys/fcntl.h>
39#include <sys/file.h>
40#include <sys/filedesc.h>
41#include <sys/filio.h>
42#ifdef COMPAT_43TTY
43#include <sys/ioctl_compat.h>
44#endif /* COMPAT_43TTY */
45#include <sys/kernel.h>
46#include <sys/limits.h>
47#include <sys/malloc.h>
48#include <sys/mount.h>
49#include <sys/poll.h>
50#include <sys/priv.h>
51#include <sys/proc.h>
52#include <sys/serial.h>
53#include <sys/signal.h>
54#include <sys/stat.h>
55#include <sys/sx.h>
56#include <sys/sysctl.h>
57#include <sys/systm.h>
58#include <sys/tty.h>
59#include <sys/ttycom.h>
60#define TTYDEFCHARS
61#include <sys/ttydefaults.h>
62#undef TTYDEFCHARS
63#include <sys/ucred.h>
64#include <sys/vnode.h>
65
66#include <machine/stdarg.h>
67
68static MALLOC_DEFINE(M_TTY, "tty", "tty device");
69
70static void tty_rel_free(struct tty *tp);
71
72static TAILQ_HEAD(, tty) tty_list = TAILQ_HEAD_INITIALIZER(tty_list);
73static struct sx tty_list_sx;
74SX_SYSINIT(tty_list, &tty_list_sx, "tty list");
75static unsigned int tty_list_count = 0;
76
77/* Character device of /dev/console. */
78static struct cdev	*dev_console;
79static const char	*dev_console_filename;
80
81/*
82 * Flags that are supported and stored by this implementation.
83 */
84#define TTYSUP_IFLAG	(IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK|ISTRIP|\
85			INLCR|IGNCR|ICRNL|IXON|IXOFF|IXANY|IMAXBEL)
86#define TTYSUP_OFLAG	(OPOST|ONLCR|TAB3|ONOEOT|OCRNL|ONOCR|ONLRET)
87#define TTYSUP_LFLAG	(ECHOKE|ECHOE|ECHOK|ECHO|ECHONL|ECHOPRT|\
88			ECHOCTL|ISIG|ICANON|ALTWERASE|IEXTEN|TOSTOP|\
89			FLUSHO|NOKERNINFO|NOFLSH)
90#define TTYSUP_CFLAG	(CIGNORE|CSIZE|CSTOPB|CREAD|PARENB|PARODD|\
91			HUPCL|CLOCAL|CCTS_OFLOW|CRTS_IFLOW|CDTR_IFLOW|\
92			CDSR_OFLOW|CCAR_OFLOW)
93
94#define	TTY_CALLOUT(tp,d) ((d) != (tp)->t_dev && (d) != dev_console)
95
96/*
97 * Set TTY buffer sizes.
98 */
99
100#define	TTYBUF_MAX	65536
101
102static void
103tty_watermarks(struct tty *tp)
104{
105	size_t bs;
106
107	/* Provide an input buffer for 0.2 seconds of data. */
108	bs = MIN(tp->t_termios.c_ispeed / 5, TTYBUF_MAX);
109	ttyinq_setsize(&tp->t_inq, tp, bs);
110
111	/* Set low watermark at 10% (when 90% is available). */
112	tp->t_inlow = (ttyinq_getsize(&tp->t_inq) * 9) / 10;
113
114	/* Provide an ouput buffer for 0.2 seconds of data. */
115	bs = MIN(tp->t_termios.c_ospeed / 5, TTYBUF_MAX);
116	ttyoutq_setsize(&tp->t_outq, tp, bs);
117
118	/* Set low watermark at 10% (when 90% is available). */
119	tp->t_outlow = (ttyoutq_getsize(&tp->t_outq) * 9) / 10;
120}
121
122static int
123tty_drain(struct tty *tp)
124{
125	int error;
126
127	if (ttyhook_hashook(tp, getc_inject))
128		/* buffer is inaccessible */
129		return (0);
130
131	while (ttyoutq_bytesused(&tp->t_outq) > 0) {
132		ttydevsw_outwakeup(tp);
133		/* Could be handled synchronously. */
134		if (ttyoutq_bytesused(&tp->t_outq) == 0)
135			return (0);
136
137		/* Wait for data to be drained. */
138		error = tty_wait(tp, &tp->t_outwait);
139		if (error)
140			return (error);
141	}
142
143	return (0);
144}
145
146/*
147 * Though ttydev_enter() and ttydev_leave() seem to be related, they
148 * don't have to be used together. ttydev_enter() is used by the cdev
149 * operations to prevent an actual operation from being processed when
150 * the TTY has been abandoned. ttydev_leave() is used by ttydev_open()
151 * and ttydev_close() to determine whether per-TTY data should be
152 * deallocated.
153 */
154
155static __inline int
156ttydev_enter(struct tty *tp)
157{
158	tty_lock(tp);
159
160	if (tty_gone(tp) || !tty_opened(tp)) {
161		/* Device is already gone. */
162		tty_unlock(tp);
163		return (ENXIO);
164	}
165
166	return (0);
167}
168
169static void
170ttydev_leave(struct tty *tp)
171{
172	tty_lock_assert(tp, MA_OWNED);
173
174	if (tty_opened(tp) || tp->t_flags & TF_OPENCLOSE) {
175		/* Device is still opened somewhere. */
176		tty_unlock(tp);
177		return;
178	}
179
180	tp->t_flags |= TF_OPENCLOSE;
181
182	/* Stop asynchronous I/O. */
183	funsetown(&tp->t_sigio);
184
185	/* Remove console TTY. */
186	if (constty == tp)
187		constty_clear();
188
189	/* Drain any output. */
190	MPASS((tp->t_flags & TF_STOPPED) == 0);
191	if (!tty_gone(tp))
192		tty_drain(tp);
193
194	ttydisc_close(tp);
195
196	/* Destroy associated buffers already. */
197	ttyinq_free(&tp->t_inq);
198	tp->t_inlow = 0;
199	ttyoutq_free(&tp->t_outq);
200	tp->t_outlow = 0;
201
202	knlist_clear(&tp->t_inpoll.si_note, 1);
203	knlist_clear(&tp->t_outpoll.si_note, 1);
204
205	if (!tty_gone(tp))
206		ttydevsw_close(tp);
207
208	tp->t_flags &= ~TF_OPENCLOSE;
209	tty_rel_free(tp);
210}
211
212/*
213 * Operations that are exposed through the character device in /dev.
214 */
215static int
216ttydev_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
217{
218	struct tty *tp = dev->si_drv1;
219	int error = 0;
220
221	/* Disallow access when the TTY belongs to a different prison. */
222	if (dev->si_cred != NULL &&
223	    dev->si_cred->cr_prison != td->td_ucred->cr_prison &&
224	    priv_check(td, PRIV_TTY_PRISON)) {
225		return (EPERM);
226	}
227
228	tty_lock(tp);
229	if (tty_gone(tp)) {
230		/* Device is already gone. */
231		tty_unlock(tp);
232		return (ENXIO);
233	}
234	/*
235	 * Prevent the TTY from being opened when being torn down or
236	 * built up by unrelated processes.
237	 */
238	if (tp->t_flags & TF_OPENCLOSE) {
239		tty_unlock(tp);
240		return (EBUSY);
241	}
242	tp->t_flags |= TF_OPENCLOSE;
243
244	/*
245	 * Make sure the "tty" and "cua" device cannot be opened at the
246	 * same time.
247	 */
248	if (TTY_CALLOUT(tp, dev)) {
249		if (tp->t_flags & TF_OPENED_IN) {
250			error = EBUSY;
251			goto done;
252		}
253	} else {
254		if (tp->t_flags & TF_OPENED_OUT) {
255			error = EBUSY;
256			goto done;
257		}
258	}
259
260	if (tp->t_flags & TF_EXCLUDE && priv_check(td, PRIV_TTY_EXCLUSIVE)) {
261		error = EBUSY;
262		goto done;
263	}
264
265	if (!tty_opened(tp)) {
266		/* Set proper termios flags. */
267		if (TTY_CALLOUT(tp, dev)) {
268			tp->t_termios = tp->t_termios_init_out;
269		} else {
270			tp->t_termios = tp->t_termios_init_in;
271		}
272		ttydevsw_param(tp, &tp->t_termios);
273
274		ttydevsw_modem(tp, SER_DTR|SER_RTS, 0);
275
276		error = ttydevsw_open(tp);
277		if (error != 0)
278			goto done;
279
280		ttydisc_open(tp);
281		tty_watermarks(tp);
282	}
283
284	/* Wait for Carrier Detect. */
285	if (!TTY_CALLOUT(tp, dev) && (oflags & O_NONBLOCK) == 0 &&
286	    (tp->t_termios.c_cflag & CLOCAL) == 0) {
287		while ((ttydevsw_modem(tp, 0, 0) & SER_DCD) == 0) {
288			error = tty_wait(tp, &tp->t_dcdwait);
289			if (error != 0)
290				goto done;
291		}
292	}
293
294	if (TTY_CALLOUT(tp, dev)) {
295		tp->t_flags |= TF_OPENED_OUT;
296	} else {
297		tp->t_flags |= TF_OPENED_IN;
298	}
299
300done:	tp->t_flags &= ~TF_OPENCLOSE;
301	ttydev_leave(tp);
302
303	return (error);
304}
305
306static int
307ttydev_close(struct cdev *dev, int fflag, int devtype, struct thread *td)
308{
309	struct tty *tp = dev->si_drv1;
310
311	/*
312	 * Don't actually close the device if it is being used as the
313	 * console.
314	 */
315	if (dev_console_filename != NULL &&
316	    strcmp(dev_console_filename, tty_devname(tp)) == 0)
317		return (0);
318
319	tty_lock(tp);
320
321	/*
322	 * This can only be called once. The callin and the callout
323	 * devices cannot be opened at the same time.
324	 */
325	MPASS((tp->t_flags & TF_OPENED) != TF_OPENED);
326	tp->t_flags &= ~(TF_OPENED|TF_EXCLUDE|TF_STOPPED);
327
328	/* Properly wake up threads that are stuck - revoke(). */
329	tp->t_revokecnt++;
330	tty_wakeup(tp, FREAD|FWRITE);
331	cv_broadcast(&tp->t_bgwait);
332
333	ttydev_leave(tp);
334
335	return (0);
336}
337
338static __inline int
339tty_is_ctty(struct tty *tp, struct proc *p)
340{
341	tty_lock_assert(tp, MA_OWNED);
342
343	return (p->p_session == tp->t_session && p->p_flag & P_CONTROLT);
344}
345
346static int
347tty_wait_background(struct tty *tp, struct thread *td, int sig)
348{
349	struct proc *p = td->td_proc;
350	struct pgrp *pg;
351	int error;
352
353	MPASS(sig == SIGTTIN || sig == SIGTTOU);
354	tty_lock_assert(tp, MA_OWNED);
355
356	for (;;) {
357		PROC_LOCK(p);
358		/*
359		 * The process should only sleep, when:
360		 * - This terminal is the controling terminal
361		 * - Its process group is not the foreground process
362		 *   group
363		 * - The parent process isn't waiting for the child to
364		 *   exit
365		 * - the signal to send to the process isn't masked
366		 */
367		if (!tty_is_ctty(tp, p) ||
368		    p->p_pgrp == tp->t_pgrp || p->p_flag & P_PPWAIT ||
369		    SIGISMEMBER(p->p_sigacts->ps_sigignore, sig) ||
370		    SIGISMEMBER(td->td_sigmask, sig)) {
371			/* Allow the action to happen. */
372			PROC_UNLOCK(p);
373			return (0);
374		}
375
376		/*
377		 * Send the signal and sleep until we're the new
378		 * foreground process group.
379		 */
380		pg = p->p_pgrp;
381		PROC_UNLOCK(p);
382		if (pg->pg_jobc == 0)
383			return (EIO);
384		PGRP_LOCK(pg);
385		pgsignal(pg, sig, 1);
386		PGRP_UNLOCK(pg);
387
388		error = tty_wait(tp, &tp->t_bgwait);
389		if (error)
390			return (error);
391	}
392}
393
394static int
395ttydev_read(struct cdev *dev, struct uio *uio, int ioflag)
396{
397	struct tty *tp = dev->si_drv1;
398	int error;
399
400	error = ttydev_enter(tp);
401	if (error)
402		goto done;
403
404	error = tty_wait_background(tp, curthread, SIGTTIN);
405	if (error) {
406		tty_unlock(tp);
407		goto done;
408	}
409
410	error = ttydisc_read(tp, uio, ioflag);
411	tty_unlock(tp);
412
413	/*
414	 * The read() call should not throw an error when the device is
415	 * being destroyed. Silently convert it to an EOF.
416	 */
417done:	if (error == ENXIO)
418		error = 0;
419	return (error);
420}
421
422static int
423ttydev_write(struct cdev *dev, struct uio *uio, int ioflag)
424{
425	struct tty *tp = dev->si_drv1;
426	int error;
427
428	error = ttydev_enter(tp);
429	if (error)
430		return (error);
431
432	if (tp->t_termios.c_lflag & TOSTOP) {
433		error = tty_wait_background(tp, curthread, SIGTTOU);
434		if (error) {
435			tty_unlock(tp);
436			return (error);
437		}
438	}
439
440	error = ttydisc_write(tp, uio, ioflag);
441	tty_unlock(tp);
442
443	return (error);
444}
445
446static int
447ttydev_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
448    struct thread *td)
449{
450	struct tty *tp = dev->si_drv1;
451	int error;
452
453	error = ttydev_enter(tp);
454	if (error)
455		return (error);
456
457	switch (cmd) {
458	case TIOCCBRK:
459	case TIOCCONS:
460	case TIOCDRAIN:
461	case TIOCEXCL:
462	case TIOCFLUSH:
463	case TIOCNXCL:
464	case TIOCSBRK:
465	case TIOCSCTTY:
466	case TIOCSETA:
467	case TIOCSETAF:
468	case TIOCSETAW:
469	case TIOCSPGRP:
470	case TIOCSTART:
471	case TIOCSTAT:
472	case TIOCSTOP:
473	case TIOCSWINSZ:
474#if 0
475	case TIOCSDRAINWAIT:
476	case TIOCSETD:
477	case TIOCSTI:
478#endif
479#ifdef COMPAT_43TTY
480	case  TIOCLBIC:
481	case  TIOCLBIS:
482	case  TIOCLSET:
483	case  TIOCSETC:
484	case OTIOCSETD:
485	case  TIOCSETN:
486	case  TIOCSETP:
487	case  TIOCSLTC:
488#endif /* COMPAT_43TTY */
489		/*
490		 * If the ioctl() causes the TTY to be modified, let it
491		 * wait in the background.
492		 */
493		error = tty_wait_background(tp, curthread, SIGTTOU);
494		if (error)
495			goto done;
496	}
497
498	error = tty_ioctl(tp, cmd, data, td);
499done:	tty_unlock(tp);
500
501	return (error);
502}
503
504static int
505ttydev_poll(struct cdev *dev, int events, struct thread *td)
506{
507	struct tty *tp = dev->si_drv1;
508	int error, revents = 0;
509
510	error = ttydev_enter(tp);
511	if (error) {
512		/* Don't return the error here, but the event mask. */
513		return (events &
514		    (POLLHUP|POLLIN|POLLRDNORM|POLLOUT|POLLWRNORM));
515	}
516
517	if (events & (POLLIN|POLLRDNORM)) {
518		/* See if we can read something. */
519		if (ttydisc_read_poll(tp) > 0)
520			revents |= events & (POLLIN|POLLRDNORM);
521	}
522	if (events & (POLLOUT|POLLWRNORM)) {
523		/* See if we can write something. */
524		if (ttydisc_write_poll(tp) > 0)
525			revents |= events & (POLLOUT|POLLWRNORM);
526	}
527	if (tp->t_flags & TF_ZOMBIE)
528		/* Hangup flag on zombie state. */
529		revents |= events & POLLHUP;
530
531	if (revents == 0) {
532		if (events & (POLLIN|POLLRDNORM))
533			selrecord(td, &tp->t_inpoll);
534		if (events & (POLLOUT|POLLWRNORM))
535			selrecord(td, &tp->t_outpoll);
536	}
537
538	tty_unlock(tp);
539
540	return (revents);
541}
542
543static int
544ttydev_mmap(struct cdev *dev, vm_offset_t offset, vm_paddr_t *paddr, int nprot)
545{
546	struct tty *tp = dev->si_drv1;
547	int error;
548
549	/* Handle mmap() through the driver. */
550
551	error = ttydev_enter(tp);
552	if (error)
553		return (-1);
554	error = ttydevsw_mmap(tp, offset, paddr, nprot);
555	tty_unlock(tp);
556
557	return (error);
558}
559
560/*
561 * kqueue support.
562 */
563
564static void
565tty_kqops_read_detach(struct knote *kn)
566{
567	struct tty *tp = kn->kn_hook;
568
569	knlist_remove(&tp->t_inpoll.si_note, kn, 0);
570}
571
572static int
573tty_kqops_read_event(struct knote *kn, long hint)
574{
575	struct tty *tp = kn->kn_hook;
576
577	tty_lock_assert(tp, MA_OWNED);
578
579	if (tty_gone(tp) || tp->t_flags & TF_ZOMBIE) {
580		kn->kn_flags |= EV_EOF;
581		return (1);
582	} else {
583		kn->kn_data = ttydisc_read_poll(tp);
584		return (kn->kn_data > 0);
585	}
586}
587
588static void
589tty_kqops_write_detach(struct knote *kn)
590{
591	struct tty *tp = kn->kn_hook;
592
593	knlist_remove(&tp->t_outpoll.si_note, kn, 0);
594}
595
596static int
597tty_kqops_write_event(struct knote *kn, long hint)
598{
599	struct tty *tp = kn->kn_hook;
600
601	tty_lock_assert(tp, MA_OWNED);
602
603	if (tty_gone(tp)) {
604		kn->kn_flags |= EV_EOF;
605		return (1);
606	} else {
607		kn->kn_data = ttydisc_write_poll(tp);
608		return (kn->kn_data > 0);
609	}
610}
611
612static struct filterops tty_kqops_read =
613    { 1, NULL, tty_kqops_read_detach, tty_kqops_read_event };
614static struct filterops tty_kqops_write =
615    { 1, NULL, tty_kqops_write_detach, tty_kqops_write_event };
616
617static int
618ttydev_kqfilter(struct cdev *dev, struct knote *kn)
619{
620	struct tty *tp = dev->si_drv1;
621	int error;
622
623	error = ttydev_enter(tp);
624	if (error)
625		return (error);
626
627	switch (kn->kn_filter) {
628	case EVFILT_READ:
629		kn->kn_hook = tp;
630		kn->kn_fop = &tty_kqops_read;
631		knlist_add(&tp->t_inpoll.si_note, kn, 1);
632		break;
633	case EVFILT_WRITE:
634		kn->kn_hook = tp;
635		kn->kn_fop = &tty_kqops_write;
636		knlist_add(&tp->t_outpoll.si_note, kn, 1);
637		break;
638	default:
639		error = EINVAL;
640		break;
641	}
642
643	tty_unlock(tp);
644	return (error);
645}
646
647static struct cdevsw ttydev_cdevsw = {
648	.d_version	= D_VERSION,
649	.d_open		= ttydev_open,
650	.d_close	= ttydev_close,
651	.d_read		= ttydev_read,
652	.d_write	= ttydev_write,
653	.d_ioctl	= ttydev_ioctl,
654	.d_kqfilter	= ttydev_kqfilter,
655	.d_poll		= ttydev_poll,
656	.d_mmap		= ttydev_mmap,
657	.d_name		= "ttydev",
658	.d_flags	= D_TTY,
659};
660
661/*
662 * Init/lock-state devices
663 */
664
665static int
666ttyil_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
667{
668	struct tty *tp = dev->si_drv1;
669	int error = 0;
670
671	tty_lock(tp);
672	if (tty_gone(tp))
673		error = ENODEV;
674	tty_unlock(tp);
675
676	return (error);
677}
678
679static int
680ttyil_close(struct cdev *dev, int flag, int mode, struct thread *td)
681{
682	return (0);
683}
684
685static int
686ttyil_rdwr(struct cdev *dev, struct uio *uio, int ioflag)
687{
688	return (ENODEV);
689}
690
691static int
692ttyil_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
693    struct thread *td)
694{
695	struct tty *tp = dev->si_drv1;
696	int error = 0;
697
698	tty_lock(tp);
699	if (tty_gone(tp)) {
700		error = ENODEV;
701		goto done;
702	}
703
704	switch (cmd) {
705	case TIOCGETA:
706		/* Obtain terminal flags through tcgetattr(). */
707		bcopy(dev->si_drv2, data, sizeof(struct termios));
708		break;
709	case TIOCSETA:
710		/* Set terminal flags through tcsetattr(). */
711		error = priv_check(td, PRIV_TTY_SETA);
712		if (error)
713			break;
714		bcopy(data, dev->si_drv2, sizeof(struct termios));
715		break;
716	case TIOCGETD:
717		*(int *)data = TTYDISC;
718		break;
719	case TIOCGWINSZ:
720		bzero(data, sizeof(struct winsize));
721		break;
722	default:
723		error = ENOTTY;
724	}
725
726done:	tty_unlock(tp);
727	return (error);
728}
729
730static struct cdevsw ttyil_cdevsw = {
731	.d_version	= D_VERSION,
732	.d_open		= ttyil_open,
733	.d_close	= ttyil_close,
734	.d_read		= ttyil_rdwr,
735	.d_write	= ttyil_rdwr,
736	.d_ioctl	= ttyil_ioctl,
737	.d_name		= "ttyil",
738	.d_flags	= D_TTY,
739};
740
741static void
742tty_init_termios(struct tty *tp)
743{
744	struct termios *t = &tp->t_termios_init_in;
745
746	t->c_cflag = TTYDEF_CFLAG;
747	t->c_iflag = TTYDEF_IFLAG;
748	t->c_lflag = TTYDEF_LFLAG;
749	t->c_oflag = TTYDEF_OFLAG;
750	t->c_ispeed = TTYDEF_SPEED;
751	t->c_ospeed = TTYDEF_SPEED;
752	bcopy(ttydefchars, &t->c_cc, sizeof ttydefchars);
753
754	tp->t_termios_init_out = *t;
755}
756
757void
758tty_init_console(struct tty *tp, speed_t s)
759{
760	struct termios *ti = &tp->t_termios_init_in;
761	struct termios *to = &tp->t_termios_init_out;
762
763	if (s != 0) {
764		ti->c_ispeed = ti->c_ospeed = s;
765		to->c_ispeed = to->c_ospeed = s;
766	}
767
768	ti->c_cflag |= CLOCAL;
769	to->c_cflag |= CLOCAL;
770}
771
772/*
773 * Standard device routine implementations, mostly meant for
774 * pseudo-terminal device drivers. When a driver creates a new terminal
775 * device class, missing routines are patched.
776 */
777
778static int
779ttydevsw_defopen(struct tty *tp)
780{
781
782	return (0);
783}
784
785static void
786ttydevsw_defclose(struct tty *tp)
787{
788}
789
790static void
791ttydevsw_defoutwakeup(struct tty *tp)
792{
793
794	panic("Terminal device has output, while not implemented");
795}
796
797static void
798ttydevsw_definwakeup(struct tty *tp)
799{
800}
801
802static int
803ttydevsw_defioctl(struct tty *tp, u_long cmd, caddr_t data, struct thread *td)
804{
805
806	return (ENOIOCTL);
807}
808
809static int
810ttydevsw_defparam(struct tty *tp, struct termios *t)
811{
812
813	/* Use a fake baud rate, we're not a real device. */
814	t->c_ispeed = t->c_ospeed = TTYDEF_SPEED;
815
816	return (0);
817}
818
819static int
820ttydevsw_defmodem(struct tty *tp, int sigon, int sigoff)
821{
822
823	/* Simulate a carrier to make the TTY layer happy. */
824	return (SER_DCD);
825}
826
827static int
828ttydevsw_defmmap(struct tty *tp, vm_offset_t offset, vm_paddr_t *paddr,
829    int nprot)
830{
831
832	return (-1);
833}
834
835static void
836ttydevsw_defpktnotify(struct tty *tp, char event)
837{
838}
839
840static void
841ttydevsw_deffree(void *softc)
842{
843
844	panic("Terminal device freed without a free-handler");
845}
846
847/*
848 * TTY allocation and deallocation. TTY devices can be deallocated when
849 * the driver doesn't use it anymore, when the TTY isn't a session's
850 * controlling TTY and when the device node isn't opened through devfs.
851 */
852
853struct tty *
854tty_alloc(struct ttydevsw *tsw, void *sc, struct mtx *mutex)
855{
856	struct tty *tp;
857
858	/* Make sure the driver defines all routines. */
859#define PATCH_FUNC(x) do {				\
860	if (tsw->tsw_ ## x == NULL)			\
861		tsw->tsw_ ## x = ttydevsw_def ## x;	\
862} while (0)
863	PATCH_FUNC(open);
864	PATCH_FUNC(close);
865	PATCH_FUNC(outwakeup);
866	PATCH_FUNC(inwakeup);
867	PATCH_FUNC(ioctl);
868	PATCH_FUNC(param);
869	PATCH_FUNC(modem);
870	PATCH_FUNC(mmap);
871	PATCH_FUNC(pktnotify);
872	PATCH_FUNC(free);
873#undef PATCH_FUNC
874
875	tp = malloc(sizeof(struct tty), M_TTY, M_WAITOK|M_ZERO);
876	tp->t_devsw = tsw;
877	tp->t_devswsoftc = sc;
878	tp->t_flags = tsw->tsw_flags;
879
880	tty_init_termios(tp);
881
882	cv_init(&tp->t_inwait, "ttyin");
883	cv_init(&tp->t_outwait, "ttyout");
884	cv_init(&tp->t_bgwait, "ttybg");
885	cv_init(&tp->t_dcdwait, "ttydcd");
886
887	/* Allow drivers to use a custom mutex to lock the TTY. */
888	if (mutex != NULL) {
889		tp->t_mtx = mutex;
890	} else {
891		tp->t_mtx = &tp->t_mtxobj;
892		mtx_init(&tp->t_mtxobj, "ttymtx", NULL, MTX_DEF);
893	}
894
895	knlist_init(&tp->t_inpoll.si_note, tp->t_mtx, NULL, NULL, NULL);
896	knlist_init(&tp->t_outpoll.si_note, tp->t_mtx, NULL, NULL, NULL);
897
898	sx_xlock(&tty_list_sx);
899	TAILQ_INSERT_TAIL(&tty_list, tp, t_list);
900	tty_list_count++;
901	sx_xunlock(&tty_list_sx);
902
903	return (tp);
904}
905
906static void
907tty_dealloc(void *arg)
908{
909	struct tty *tp = arg;
910
911	sx_xlock(&tty_list_sx);
912	TAILQ_REMOVE(&tty_list, tp, t_list);
913	tty_list_count--;
914	sx_xunlock(&tty_list_sx);
915
916	/* Make sure we haven't leaked buffers. */
917	MPASS(ttyinq_getsize(&tp->t_inq) == 0);
918	MPASS(ttyoutq_getsize(&tp->t_outq) == 0);
919
920	knlist_destroy(&tp->t_inpoll.si_note);
921	knlist_destroy(&tp->t_outpoll.si_note);
922
923	cv_destroy(&tp->t_inwait);
924	cv_destroy(&tp->t_outwait);
925	cv_destroy(&tp->t_bgwait);
926	cv_destroy(&tp->t_dcdwait);
927
928	if (tp->t_mtx == &tp->t_mtxobj)
929		mtx_destroy(&tp->t_mtxobj);
930	ttydevsw_free(tp);
931	free(tp, M_TTY);
932}
933
934static void
935tty_rel_free(struct tty *tp)
936{
937	struct cdev *dev;
938
939	tty_lock_assert(tp, MA_OWNED);
940
941#define	TF_ACTIVITY	(TF_GONE|TF_OPENED|TF_HOOK|TF_OPENCLOSE)
942	if (tp->t_sessioncnt != 0 || (tp->t_flags & TF_ACTIVITY) != TF_GONE) {
943		/* TTY is still in use. */
944		tty_unlock(tp);
945		return;
946	}
947
948	/* TTY can be deallocated. */
949	dev = tp->t_dev;
950	tp->t_dev = NULL;
951	tty_unlock(tp);
952
953	destroy_dev_sched_cb(dev, tty_dealloc, tp);
954}
955
956void
957tty_rel_pgrp(struct tty *tp, struct pgrp *pg)
958{
959	MPASS(tp->t_sessioncnt > 0);
960	tty_lock_assert(tp, MA_OWNED);
961
962	if (tp->t_pgrp == pg)
963		tp->t_pgrp = NULL;
964
965	tty_unlock(tp);
966}
967
968void
969tty_rel_sess(struct tty *tp, struct session *sess)
970{
971	MPASS(tp->t_sessioncnt > 0);
972
973	/* Current session has left. */
974	if (tp->t_session == sess) {
975		tp->t_session = NULL;
976		MPASS(tp->t_pgrp == NULL);
977	}
978	tp->t_sessioncnt--;
979	tty_rel_free(tp);
980}
981
982void
983tty_rel_gone(struct tty *tp)
984{
985	MPASS(!tty_gone(tp));
986
987	/* Simulate carrier removal. */
988	ttydisc_modem(tp, 0);
989
990	/* Wake up all blocked threads. */
991	tty_wakeup(tp, FREAD|FWRITE);
992	cv_broadcast(&tp->t_bgwait);
993	cv_broadcast(&tp->t_dcdwait);
994
995	tp->t_flags |= TF_GONE;
996	tty_rel_free(tp);
997}
998
999/*
1000 * Exposing information about current TTY's through sysctl
1001 */
1002
1003static void
1004tty_to_xtty(struct tty *tp, struct xtty *xt)
1005{
1006	tty_lock_assert(tp, MA_OWNED);
1007
1008	xt->xt_size = sizeof(struct xtty);
1009	xt->xt_insize = ttyinq_getsize(&tp->t_inq);
1010	xt->xt_incc = ttyinq_bytescanonicalized(&tp->t_inq);
1011	xt->xt_inlc = ttyinq_bytesline(&tp->t_inq);
1012	xt->xt_inlow = tp->t_inlow;
1013	xt->xt_outsize = ttyoutq_getsize(&tp->t_outq);
1014	xt->xt_outcc = ttyoutq_bytesused(&tp->t_outq);
1015	xt->xt_outlow = tp->t_outlow;
1016	xt->xt_column = tp->t_column;
1017	xt->xt_pgid = tp->t_pgrp ? tp->t_pgrp->pg_id : 0;
1018	xt->xt_sid = tp->t_session ? tp->t_session->s_sid : 0;
1019	xt->xt_flags = tp->t_flags;
1020	xt->xt_dev = tp->t_dev ? dev2udev(tp->t_dev) : NODEV;
1021}
1022
1023static int
1024sysctl_kern_ttys(SYSCTL_HANDLER_ARGS)
1025{
1026	unsigned long lsize;
1027	struct xtty *xtlist, *xt;
1028	struct tty *tp;
1029	int error;
1030
1031	sx_slock(&tty_list_sx);
1032	lsize = tty_list_count * sizeof(struct xtty);
1033	if (lsize == 0) {
1034		sx_sunlock(&tty_list_sx);
1035		return (0);
1036	}
1037
1038	xtlist = xt = malloc(lsize, M_TEMP, M_WAITOK);
1039
1040	TAILQ_FOREACH(tp, &tty_list, t_list) {
1041		tty_lock(tp);
1042		tty_to_xtty(tp, xt);
1043		tty_unlock(tp);
1044		xt++;
1045	}
1046	sx_sunlock(&tty_list_sx);
1047
1048	error = SYSCTL_OUT(req, xtlist, lsize);
1049	free(xtlist, M_TEMP);
1050	return (error);
1051}
1052
1053SYSCTL_PROC(_kern, OID_AUTO, ttys, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
1054	0, 0, sysctl_kern_ttys, "S,xtty", "List of TTYs");
1055
1056/*
1057 * Device node creation. Device has been set up, now we can expose it to
1058 * the user.
1059 */
1060
1061void
1062tty_makedev(struct tty *tp, struct ucred *cred, const char *fmt, ...)
1063{
1064	va_list ap;
1065	struct cdev *dev;
1066	const char *prefix = "tty";
1067	char name[SPECNAMELEN - 3]; /* for "tty" and "cua". */
1068	uid_t uid;
1069	gid_t gid;
1070	mode_t mode;
1071
1072	/* Remove "tty" prefix from devices like PTY's. */
1073	if (tp->t_flags & TF_NOPREFIX)
1074		prefix = "";
1075
1076	va_start(ap, fmt);
1077	vsnrprintf(name, sizeof name, 32, fmt, ap);
1078	va_end(ap);
1079
1080	if (cred == NULL) {
1081		/* System device. */
1082		uid = UID_ROOT;
1083		gid = GID_WHEEL;
1084		mode = S_IRUSR|S_IWUSR;
1085	} else {
1086		/* User device. */
1087		uid = cred->cr_ruid;
1088		gid = GID_TTY;
1089		mode = S_IRUSR|S_IWUSR|S_IWGRP;
1090	}
1091
1092	/* Master call-in device. */
1093	dev = make_dev_cred(&ttydev_cdevsw, 0, cred,
1094	    uid, gid, mode, "%s%s", prefix, name);
1095	dev->si_drv1 = tp;
1096	tp->t_dev = dev;
1097
1098	/* Slave call-in devices. */
1099	if (tp->t_flags & TF_INITLOCK) {
1100		dev = make_dev_cred(&ttyil_cdevsw, 0, cred,
1101		    uid, gid, mode, "%s%s.init", prefix, name);
1102		dev_depends(tp->t_dev, dev);
1103		dev->si_drv1 = tp;
1104		dev->si_drv2 = &tp->t_termios_init_in;
1105
1106		dev = make_dev_cred(&ttyil_cdevsw, 0, cred,
1107		    uid, gid, mode, "%s%s.lock", prefix, name);
1108		dev_depends(tp->t_dev, dev);
1109		dev->si_drv1 = tp;
1110		dev->si_drv2 = &tp->t_termios_lock_in;
1111	}
1112
1113	/* Call-out devices. */
1114	if (tp->t_flags & TF_CALLOUT) {
1115		dev = make_dev_cred(&ttydev_cdevsw, 0, cred,
1116		    UID_UUCP, GID_DIALER, 0660, "cua%s", name);
1117		dev_depends(tp->t_dev, dev);
1118		dev->si_drv1 = tp;
1119
1120		/* Slave call-out devices. */
1121		if (tp->t_flags & TF_INITLOCK) {
1122			dev = make_dev_cred(&ttyil_cdevsw, 0, cred,
1123			    UID_UUCP, GID_DIALER, 0660, "cua%s.init", name);
1124			dev_depends(tp->t_dev, dev);
1125			dev->si_drv1 = tp;
1126			dev->si_drv2 = &tp->t_termios_init_out;
1127
1128			dev = make_dev_cred(&ttyil_cdevsw, 0, cred,
1129			    UID_UUCP, GID_DIALER, 0660, "cua%s.lock", name);
1130			dev_depends(tp->t_dev, dev);
1131			dev->si_drv1 = tp;
1132			dev->si_drv2 = &tp->t_termios_lock_out;
1133		}
1134	}
1135}
1136
1137/*
1138 * Signalling processes.
1139 */
1140
1141void
1142tty_signal_sessleader(struct tty *tp, int sig)
1143{
1144	struct proc *p;
1145
1146	tty_lock_assert(tp, MA_OWNED);
1147	MPASS(sig >= 1 && sig < NSIG);
1148
1149	/* Make signals start output again. */
1150	tp->t_flags &= ~TF_STOPPED;
1151
1152	if (tp->t_session != NULL && tp->t_session->s_leader != NULL) {
1153		p = tp->t_session->s_leader;
1154		PROC_LOCK(p);
1155		psignal(p, sig);
1156		PROC_UNLOCK(p);
1157	}
1158}
1159
1160void
1161tty_signal_pgrp(struct tty *tp, int sig)
1162{
1163	tty_lock_assert(tp, MA_OWNED);
1164	MPASS(sig >= 1 && sig < NSIG);
1165
1166	/* Make signals start output again. */
1167	tp->t_flags &= ~TF_STOPPED;
1168
1169	if (sig == SIGINFO && !(tp->t_termios.c_lflag & NOKERNINFO))
1170		tty_info(tp);
1171	if (tp->t_pgrp != NULL) {
1172		PGRP_LOCK(tp->t_pgrp);
1173		pgsignal(tp->t_pgrp, sig, 1);
1174		PGRP_UNLOCK(tp->t_pgrp);
1175	}
1176}
1177
1178void
1179tty_wakeup(struct tty *tp, int flags)
1180{
1181	if (tp->t_flags & TF_ASYNC && tp->t_sigio != NULL)
1182		pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
1183
1184	if (flags & FWRITE) {
1185		cv_broadcast(&tp->t_outwait);
1186		selwakeup(&tp->t_outpoll);
1187		KNOTE_LOCKED(&tp->t_outpoll.si_note, 0);
1188	}
1189	if (flags & FREAD) {
1190		cv_broadcast(&tp->t_inwait);
1191		selwakeup(&tp->t_inpoll);
1192		KNOTE_LOCKED(&tp->t_inpoll.si_note, 0);
1193	}
1194}
1195
1196int
1197tty_wait(struct tty *tp, struct cv *cv)
1198{
1199	int error;
1200	int revokecnt = tp->t_revokecnt;
1201
1202	tty_lock_assert(tp, MA_OWNED|MA_NOTRECURSED);
1203	MPASS(!tty_gone(tp));
1204
1205	error = cv_wait_sig(cv, tp->t_mtx);
1206
1207	/* Restart the system call when we may have been revoked. */
1208	if (tp->t_revokecnt != revokecnt)
1209		return (ERESTART);
1210
1211	/* Bail out when the device slipped away. */
1212	if (tty_gone(tp))
1213		return (ENXIO);
1214
1215	return (error);
1216}
1217
1218int
1219tty_timedwait(struct tty *tp, struct cv *cv, int hz)
1220{
1221	int error;
1222	int revokecnt = tp->t_revokecnt;
1223
1224	tty_lock_assert(tp, MA_OWNED|MA_NOTRECURSED);
1225	MPASS(!tty_gone(tp));
1226
1227	error = cv_timedwait_sig(cv, tp->t_mtx, hz);
1228
1229	/* Restart the system call when we may have been revoked. */
1230	if (tp->t_revokecnt != revokecnt)
1231		return (ERESTART);
1232
1233	/* Bail out when the device slipped away. */
1234	if (tty_gone(tp))
1235		return (ENXIO);
1236
1237	return (error);
1238}
1239
1240void
1241tty_flush(struct tty *tp, int flags)
1242{
1243	if (flags & FWRITE) {
1244		tp->t_flags &= ~TF_HIWAT_OUT;
1245		ttyoutq_flush(&tp->t_outq);
1246		tty_wakeup(tp, FWRITE);
1247		ttydevsw_pktnotify(tp, TIOCPKT_FLUSHWRITE);
1248	}
1249	if (flags & FREAD) {
1250		tty_hiwat_in_unblock(tp);
1251		ttyinq_flush(&tp->t_inq);
1252		ttydevsw_inwakeup(tp);
1253		ttydevsw_pktnotify(tp, TIOCPKT_FLUSHREAD);
1254	}
1255}
1256
1257static int
1258tty_generic_ioctl(struct tty *tp, u_long cmd, void *data, struct thread *td)
1259{
1260	int error;
1261
1262	switch (cmd) {
1263	/*
1264	 * Modem commands.
1265	 * The SER_* and TIOCM_* flags are the same, but one bit
1266	 * shifted. I don't know why.
1267	 */
1268	case TIOCSDTR:
1269		ttydevsw_modem(tp, SER_DTR, 0);
1270		return (0);
1271	case TIOCCDTR:
1272		ttydevsw_modem(tp, 0, SER_DTR);
1273		return (0);
1274	case TIOCMSET: {
1275		int bits = *(int *)data;
1276		ttydevsw_modem(tp,
1277		    (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1,
1278		    ((~bits) & (TIOCM_DTR | TIOCM_RTS)) >> 1);
1279		return (0);
1280	}
1281	case TIOCMBIS: {
1282		int bits = *(int *)data;
1283		ttydevsw_modem(tp, (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1, 0);
1284		return (0);
1285	}
1286	case TIOCMBIC: {
1287		int bits = *(int *)data;
1288		ttydevsw_modem(tp, 0, (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1);
1289		return (0);
1290	}
1291	case TIOCMGET:
1292		*(int *)data = TIOCM_LE + (ttydevsw_modem(tp, 0, 0) << 1);
1293		return (0);
1294
1295	case FIOASYNC:
1296		if (*(int *)data)
1297			tp->t_flags |= TF_ASYNC;
1298		else
1299			tp->t_flags &= ~TF_ASYNC;
1300		return (0);
1301	case FIONBIO:
1302		/* This device supports non-blocking operation. */
1303		return (0);
1304	case FIONREAD:
1305		*(int *)data = ttyinq_bytescanonicalized(&tp->t_inq);
1306		return (0);
1307	case FIOSETOWN:
1308		if (tp->t_session != NULL && !tty_is_ctty(tp, td->td_proc))
1309			/* Not allowed to set ownership. */
1310			return (ENOTTY);
1311
1312		/* Temporarily unlock the TTY to set ownership. */
1313		tty_unlock(tp);
1314		error = fsetown(*(int *)data, &tp->t_sigio);
1315		tty_lock(tp);
1316		return (error);
1317	case FIOGETOWN:
1318		if (tp->t_session != NULL && !tty_is_ctty(tp, td->td_proc))
1319			/* Not allowed to set ownership. */
1320			return (ENOTTY);
1321
1322		/* Get ownership. */
1323		*(int *)data = fgetown(&tp->t_sigio);
1324		return (0);
1325	case TIOCGETA:
1326		/* Obtain terminal flags through tcgetattr(). */
1327		bcopy(&tp->t_termios, data, sizeof(struct termios));
1328		return (0);
1329	case TIOCSETA:
1330	case TIOCSETAW:
1331	case TIOCSETAF: {
1332		struct termios *t = data;
1333
1334		/*
1335		 * Who makes up these funny rules? According to POSIX,
1336		 * input baud rate is set equal to the output baud rate
1337		 * when zero.
1338		 */
1339		if (t->c_ispeed == 0)
1340			t->c_ispeed = t->c_ospeed;
1341
1342		/* Discard any unsupported bits. */
1343		t->c_iflag &= TTYSUP_IFLAG;
1344		t->c_oflag &= TTYSUP_OFLAG;
1345		t->c_lflag &= TTYSUP_LFLAG;
1346		t->c_cflag &= TTYSUP_CFLAG;
1347
1348		/* Set terminal flags through tcsetattr(). */
1349		if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
1350			error = tty_drain(tp);
1351			if (error)
1352				return (error);
1353			if (cmd == TIOCSETAF)
1354				tty_flush(tp, FREAD);
1355		}
1356
1357		/*
1358		 * Only call param() when the flags really change.
1359		 */
1360		if ((t->c_cflag & CIGNORE) == 0 &&
1361		    (tp->t_termios.c_cflag != t->c_cflag ||
1362		    tp->t_termios.c_ispeed != t->c_ispeed ||
1363		    tp->t_termios.c_ospeed != t->c_ospeed)) {
1364			error = ttydevsw_param(tp, t);
1365			if (error)
1366				return (error);
1367
1368			/* XXX: CLOCAL? */
1369
1370			tp->t_termios.c_cflag = t->c_cflag & ~CIGNORE;
1371			tp->t_termios.c_ispeed = t->c_ispeed;
1372			tp->t_termios.c_ospeed = t->c_ospeed;
1373
1374			/* Baud rate has changed - update watermarks. */
1375			tty_watermarks(tp);
1376		}
1377
1378		/* Copy new non-device driver parameters. */
1379		tp->t_termios.c_iflag = t->c_iflag;
1380		tp->t_termios.c_oflag = t->c_oflag;
1381		tp->t_termios.c_lflag = t->c_lflag;
1382		bcopy(t->c_cc, &tp->t_termios.c_cc, sizeof(t->c_cc));
1383
1384		ttydisc_optimize(tp);
1385
1386		if ((t->c_lflag & ICANON) == 0) {
1387			/*
1388			 * When in non-canonical mode, wake up all
1389			 * readers. Canonicalize any partial input. VMIN
1390			 * and VTIME could also be adjusted.
1391			 */
1392			ttyinq_canonicalize(&tp->t_inq);
1393			tty_wakeup(tp, FREAD);
1394		}
1395
1396		/*
1397		 * For packet mode: notify the PTY consumer that VSTOP
1398		 * and VSTART may have been changed.
1399		 */
1400		if (tp->t_termios.c_iflag & IXON &&
1401		    tp->t_termios.c_cc[VSTOP] == CTRL('S') &&
1402		    tp->t_termios.c_cc[VSTART] == CTRL('Q'))
1403			ttydevsw_pktnotify(tp, TIOCPKT_DOSTOP);
1404		else
1405			ttydevsw_pktnotify(tp, TIOCPKT_NOSTOP);
1406		return (0);
1407	}
1408	case TIOCGETD:
1409		/* For compatibility - we only support TTYDISC. */
1410		*(int *)data = TTYDISC;
1411		return (0);
1412	case TIOCGPGRP:
1413		if (!tty_is_ctty(tp, td->td_proc))
1414			return (ENOTTY);
1415
1416		if (tp->t_pgrp != NULL)
1417			*(int *)data = tp->t_pgrp->pg_id;
1418		else
1419			*(int *)data = NO_PID;
1420		return (0);
1421	case TIOCGSID:
1422		if (!tty_is_ctty(tp, td->td_proc))
1423			return (ENOTTY);
1424
1425		MPASS(tp->t_session);
1426		*(int *)data = tp->t_session->s_sid;
1427		return (0);
1428	case TIOCSCTTY: {
1429		struct proc *p = td->td_proc;
1430
1431		/* XXX: This looks awful. */
1432		tty_unlock(tp);
1433		sx_xlock(&proctree_lock);
1434		tty_lock(tp);
1435
1436		if (!SESS_LEADER(p)) {
1437			/* Only the session leader may do this. */
1438			sx_xunlock(&proctree_lock);
1439			return (EPERM);
1440		}
1441
1442		if (tp->t_session != NULL && tp->t_session == p->p_session) {
1443			/* This is already our controlling TTY. */
1444			sx_xunlock(&proctree_lock);
1445			return (0);
1446		}
1447
1448		if (!SESS_LEADER(p) || p->p_session->s_ttyvp != NULL ||
1449		    (tp->t_session != NULL && tp->t_session->s_ttyvp != NULL)) {
1450			/*
1451			 * There is already a relation between a TTY and
1452			 * a session, or the caller is not the session
1453			 * leader.
1454			 *
1455			 * Allow the TTY to be stolen when the vnode is
1456			 * NULL, but the reference to the TTY is still
1457			 * active.
1458			 */
1459			sx_xunlock(&proctree_lock);
1460			return (EPERM);
1461		}
1462
1463		/* Connect the session to the TTY. */
1464		tp->t_session = p->p_session;
1465		tp->t_session->s_ttyp = tp;
1466		tp->t_sessioncnt++;
1467		sx_xunlock(&proctree_lock);
1468
1469		/* Assign foreground process group. */
1470		tp->t_pgrp = p->p_pgrp;
1471		PROC_LOCK(p);
1472		p->p_flag |= P_CONTROLT;
1473		PROC_UNLOCK(p);
1474
1475		return (0);
1476	}
1477	case TIOCSPGRP: {
1478		struct pgrp *pg;
1479
1480		/*
1481		 * XXX: Temporarily unlock the TTY to locate the process
1482		 * group. This code would be lot nicer if we would ever
1483		 * decompose proctree_lock.
1484		 */
1485		tty_unlock(tp);
1486		sx_slock(&proctree_lock);
1487		pg = pgfind(*(int *)data);
1488		if (pg != NULL)
1489			PGRP_UNLOCK(pg);
1490		if (pg == NULL || pg->pg_session != td->td_proc->p_session) {
1491			sx_sunlock(&proctree_lock);
1492			tty_lock(tp);
1493			return (EPERM);
1494		}
1495		tty_lock(tp);
1496
1497		/*
1498		 * Determine if this TTY is the controlling TTY after
1499		 * relocking the TTY.
1500		 */
1501		if (!tty_is_ctty(tp, td->td_proc)) {
1502			sx_sunlock(&proctree_lock);
1503			return (ENOTTY);
1504		}
1505		tp->t_pgrp = pg;
1506		sx_sunlock(&proctree_lock);
1507
1508		/* Wake up the background process groups. */
1509		cv_broadcast(&tp->t_bgwait);
1510		return (0);
1511	}
1512	case TIOCFLUSH: {
1513		int flags = *(int *)data;
1514
1515		if (flags == 0)
1516			flags = (FREAD|FWRITE);
1517		else
1518			flags &= (FREAD|FWRITE);
1519		tty_flush(tp, flags);
1520		return (0);
1521	}
1522	case TIOCDRAIN:
1523		/* Drain TTY output. */
1524		return tty_drain(tp);
1525	case TIOCCONS:
1526		/* Set terminal as console TTY. */
1527		if (*(int *)data) {
1528			error = priv_check(td, PRIV_TTY_CONSOLE);
1529			if (error)
1530				return (error);
1531
1532			/*
1533			 * XXX: constty should really need to be locked!
1534			 * XXX: allow disconnected constty's to be stolen!
1535			 */
1536
1537			if (constty == tp)
1538				return (0);
1539			if (constty != NULL)
1540				return (EBUSY);
1541
1542			tty_unlock(tp);
1543			constty_set(tp);
1544			tty_lock(tp);
1545		} else if (constty == tp) {
1546			constty_clear();
1547		}
1548		return (0);
1549	case TIOCGWINSZ:
1550		/* Obtain window size. */
1551		bcopy(&tp->t_winsize, data, sizeof(struct winsize));
1552		return (0);
1553	case TIOCSWINSZ:
1554		/* Set window size. */
1555		if (bcmp(&tp->t_winsize, data, sizeof(struct winsize)) == 0)
1556			return (0);
1557		bcopy(data, &tp->t_winsize, sizeof(struct winsize));
1558		tty_signal_pgrp(tp, SIGWINCH);
1559		return (0);
1560	case TIOCEXCL:
1561		tp->t_flags |= TF_EXCLUDE;
1562		return (0);
1563	case TIOCNXCL:
1564		tp->t_flags &= ~TF_EXCLUDE;
1565		return (0);
1566	case TIOCOUTQ:
1567		*(unsigned int *)data = ttyoutq_bytesused(&tp->t_outq);
1568		return (0);
1569	case TIOCSTOP:
1570		tp->t_flags |= TF_STOPPED;
1571		ttydevsw_pktnotify(tp, TIOCPKT_STOP);
1572		return (0);
1573	case TIOCSTART:
1574		tp->t_flags &= ~TF_STOPPED;
1575		ttydevsw_outwakeup(tp);
1576		ttydevsw_pktnotify(tp, TIOCPKT_START);
1577		return (0);
1578	case TIOCSTAT:
1579		tty_info(tp);
1580		return (0);
1581	}
1582
1583#ifdef COMPAT_43TTY
1584	return tty_ioctl_compat(tp, cmd, data, td);
1585#else /* !COMPAT_43TTY */
1586	return (ENOIOCTL);
1587#endif /* COMPAT_43TTY */
1588}
1589
1590int
1591tty_ioctl(struct tty *tp, u_long cmd, void *data, struct thread *td)
1592{
1593	int error;
1594
1595	tty_lock_assert(tp, MA_OWNED);
1596
1597	if (tty_gone(tp))
1598		return (ENXIO);
1599
1600	error = ttydevsw_ioctl(tp, cmd, data, td);
1601	if (error == ENOIOCTL)
1602		error = tty_generic_ioctl(tp, cmd, data, td);
1603
1604	return (error);
1605}
1606
1607dev_t
1608tty_udev(struct tty *tp)
1609{
1610	if (tp->t_dev)
1611		return dev2udev(tp->t_dev);
1612	else
1613		return NODEV;
1614}
1615
1616int
1617tty_checkoutq(struct tty *tp)
1618{
1619
1620	/* 256 bytes should be enough to print a log message. */
1621	return (ttyoutq_bytesleft(&tp->t_outq) >= 256);
1622}
1623
1624void
1625tty_hiwat_in_block(struct tty *tp)
1626{
1627
1628	if ((tp->t_flags & TF_HIWAT_IN) == 0 &&
1629	    tp->t_termios.c_iflag & IXOFF &&
1630	    tp->t_termios.c_cc[VSTOP] != _POSIX_VDISABLE) {
1631		/*
1632		 * Input flow control. Only enter the high watermark when we
1633		 * can successfully store the VSTOP character.
1634		 */
1635		if (ttyoutq_write_nofrag(&tp->t_outq,
1636		    &tp->t_termios.c_cc[VSTOP], 1) == 0)
1637			tp->t_flags |= TF_HIWAT_IN;
1638	} else {
1639		/* No input flow control. */
1640		tp->t_flags |= TF_HIWAT_IN;
1641	}
1642}
1643
1644void
1645tty_hiwat_in_unblock(struct tty *tp)
1646{
1647
1648	if (tp->t_flags & TF_HIWAT_IN &&
1649	    tp->t_termios.c_iflag & IXOFF &&
1650	    tp->t_termios.c_cc[VSTART] != _POSIX_VDISABLE) {
1651		/*
1652		 * Input flow control. Only leave the high watermark when we
1653		 * can successfully store the VSTART character.
1654		 */
1655		if (ttyoutq_write_nofrag(&tp->t_outq,
1656		    &tp->t_termios.c_cc[VSTART], 1) == 0)
1657			tp->t_flags &= ~TF_HIWAT_IN;
1658	} else {
1659		/* No input flow control. */
1660		tp->t_flags &= ~TF_HIWAT_IN;
1661	}
1662
1663	if (!tty_gone(tp))
1664		ttydevsw_inwakeup(tp);
1665}
1666
1667/*
1668 * TTY hooks interface.
1669 */
1670
1671static int
1672ttyhook_defrint(struct tty *tp, char c, int flags)
1673{
1674
1675	if (ttyhook_rint_bypass(tp, &c, 1) != 1)
1676		return (-1);
1677
1678	return (0);
1679}
1680
1681int
1682ttyhook_register(struct tty **rtp, struct proc *p, int fd,
1683    struct ttyhook *th, void *softc)
1684{
1685	struct tty *tp;
1686	struct file *fp;
1687	struct cdev *dev;
1688	struct cdevsw *cdp;
1689	struct filedesc *fdp;
1690	int error;
1691
1692	/* Validate the file descriptor. */
1693	if ((fdp = p->p_fd) == NULL)
1694		return (EBADF);
1695	FILEDESC_SLOCK(fdp);
1696	if ((fp = fget_locked(fdp, fd)) == NULL || fp->f_ops == &badfileops) {
1697		FILEDESC_SUNLOCK(fdp);
1698		return (EBADF);
1699	}
1700
1701	/* Make sure the vnode is bound to a character device. */
1702	error = EINVAL;
1703	if (fp->f_type != DTYPE_VNODE || fp->f_vnode->v_type != VCHR ||
1704	    fp->f_vnode->v_rdev == NULL)
1705		goto done1;
1706	dev = fp->f_vnode->v_rdev;
1707
1708	/* Make sure it is a TTY. */
1709	cdp = dev_refthread(dev);
1710	if (cdp == NULL)
1711		goto done1;
1712	if (cdp != &ttydev_cdevsw)
1713		goto done2;
1714	tp = dev->si_drv1;
1715
1716	/* Try to attach the hook to the TTY. */
1717	error = EBUSY;
1718	tty_lock(tp);
1719	MPASS((tp->t_hook == NULL) == ((tp->t_flags & TF_HOOK) == 0));
1720	if (tp->t_flags & TF_HOOK)
1721		goto done3;
1722
1723	tp->t_flags |= TF_HOOK;
1724	tp->t_hook = th;
1725	tp->t_hooksoftc = softc;
1726	*rtp = tp;
1727	error = 0;
1728
1729	/* Maybe we can switch into bypass mode now. */
1730	ttydisc_optimize(tp);
1731
1732	/* Silently convert rint() calls to rint_bypass() when possible. */
1733	if (!ttyhook_hashook(tp, rint) && ttyhook_hashook(tp, rint_bypass))
1734		th->th_rint = ttyhook_defrint;
1735
1736done3:	tty_unlock(tp);
1737done2:	dev_relthread(dev);
1738done1:	FILEDESC_SUNLOCK(fdp);
1739	return (error);
1740}
1741
1742void
1743ttyhook_unregister(struct tty *tp)
1744{
1745
1746	tty_lock_assert(tp, MA_OWNED);
1747	MPASS(tp->t_flags & TF_HOOK);
1748
1749	/* Disconnect the hook. */
1750	tp->t_flags &= ~TF_HOOK;
1751	tp->t_hook = NULL;
1752
1753	/* Maybe we need to leave bypass mode. */
1754	ttydisc_optimize(tp);
1755
1756	/* Maybe deallocate the TTY as well. */
1757	tty_rel_free(tp);
1758}
1759
1760/*
1761 * /dev/console handling.
1762 */
1763
1764static int
1765ttyconsdev_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
1766{
1767	struct tty *tp;
1768
1769	/* System has no console device. */
1770	if (dev_console_filename == NULL)
1771		return (ENXIO);
1772
1773	/* Look up corresponding TTY by device name. */
1774	sx_slock(&tty_list_sx);
1775	TAILQ_FOREACH(tp, &tty_list, t_list) {
1776		if (strcmp(dev_console_filename, tty_devname(tp)) == 0) {
1777			dev_console->si_drv1 = tp;
1778			break;
1779		}
1780	}
1781	sx_sunlock(&tty_list_sx);
1782
1783	/* System console has no TTY associated. */
1784	if (dev_console->si_drv1 == NULL)
1785		return (ENXIO);
1786
1787	return (ttydev_open(dev, oflags, devtype, td));
1788}
1789
1790static int
1791ttyconsdev_write(struct cdev *dev, struct uio *uio, int ioflag)
1792{
1793
1794	log_console(uio);
1795
1796	return (ttydev_write(dev, uio, ioflag));
1797}
1798
1799/*
1800 * /dev/console is a little different than normal TTY's. Unlike regular
1801 * TTY device nodes, this device node will not revoke the entire TTY
1802 * upon closure and all data written to it will be logged.
1803 */
1804static struct cdevsw ttyconsdev_cdevsw = {
1805	.d_version	= D_VERSION,
1806	.d_open		= ttyconsdev_open,
1807	.d_read		= ttydev_read,
1808	.d_write	= ttyconsdev_write,
1809	.d_ioctl	= ttydev_ioctl,
1810	.d_kqfilter	= ttydev_kqfilter,
1811	.d_poll		= ttydev_poll,
1812	.d_mmap		= ttydev_mmap,
1813	.d_name		= "ttyconsdev",
1814	.d_flags	= D_TTY,
1815};
1816
1817static void
1818ttyconsdev_init(void *unused)
1819{
1820
1821	dev_console = make_dev(&ttyconsdev_cdevsw, 0, UID_ROOT, GID_WHEEL,
1822	    0600, "console");
1823}
1824
1825SYSINIT(tty, SI_SUB_DRIVERS, SI_ORDER_FIRST, ttyconsdev_init, NULL);
1826
1827void
1828ttyconsdev_select(const char *name)
1829{
1830
1831	dev_console_filename = name;
1832}
1833
1834/*
1835 * Debugging routines.
1836 */
1837
1838#include "opt_ddb.h"
1839#ifdef DDB
1840#include <ddb/ddb.h>
1841#include <ddb/db_sym.h>
1842
1843static struct {
1844	int flag;
1845	char val;
1846} ttystates[] = {
1847#if 0
1848	{ TF_NOPREFIX,	'N' },
1849#endif
1850	{ TF_INITLOCK,	'I' },
1851	{ TF_CALLOUT,	'C' },
1852
1853	/* Keep these together -> 'Oi' and 'Oo'. */
1854	{ TF_OPENED,	'O' },
1855	{ TF_OPENED_IN,	'i' },
1856	{ TF_OPENED_OUT,'o' },
1857
1858	{ TF_GONE,	'G' },
1859	{ TF_OPENCLOSE,	'B' },
1860	{ TF_ASYNC,	'Y' },
1861	{ TF_LITERAL,	'L' },
1862
1863	/* Keep these together -> 'Hi' and 'Ho'. */
1864	{ TF_HIWAT,	'H' },
1865	{ TF_HIWAT_IN,	'i' },
1866	{ TF_HIWAT_OUT,	'o' },
1867
1868	{ TF_STOPPED,	'S' },
1869	{ TF_EXCLUDE,	'X' },
1870	{ TF_BYPASS,	'l' },
1871	{ TF_ZOMBIE,	'Z' },
1872	{ TF_HOOK,	's' },
1873
1874	{ 0,	       '\0' },
1875};
1876
1877#define	TTY_FLAG_BITS \
1878	"\20\1NOPREFIX\2INITLOCK\3CALLOUT\4OPENED_IN\5OPENED_OUT\6GONE" \
1879	"\7OPENCLOSE\10ASYNC\11LITERAL\12HIWAT_IN\13HIWAT_OUT\14STOPPED" \
1880	"\15EXCLUDE\16BYPASS\17ZOMBIE\20HOOK"
1881
1882#define DB_PRINTSYM(name, addr) \
1883	db_printf("%s  " #name ": ", sep); \
1884	db_printsym((db_addr_t) addr, DB_STGY_ANY); \
1885	db_printf("\n");
1886
1887static void
1888_db_show_devsw(const char *sep, const struct ttydevsw *tsw)
1889{
1890	db_printf("%sdevsw: ", sep);
1891	db_printsym((db_addr_t)tsw, DB_STGY_ANY);
1892	db_printf(" (%p)\n", tsw);
1893	DB_PRINTSYM(open, tsw->tsw_open);
1894	DB_PRINTSYM(close, tsw->tsw_close);
1895	DB_PRINTSYM(outwakeup, tsw->tsw_outwakeup);
1896	DB_PRINTSYM(inwakeup, tsw->tsw_inwakeup);
1897	DB_PRINTSYM(ioctl, tsw->tsw_ioctl);
1898	DB_PRINTSYM(param, tsw->tsw_param);
1899	DB_PRINTSYM(modem, tsw->tsw_modem);
1900	DB_PRINTSYM(mmap, tsw->tsw_mmap);
1901	DB_PRINTSYM(pktnotify, tsw->tsw_pktnotify);
1902	DB_PRINTSYM(free, tsw->tsw_free);
1903}
1904static void
1905_db_show_hooks(const char *sep, const struct ttyhook *th)
1906{
1907	db_printf("%shook: ", sep);
1908	db_printsym((db_addr_t)th, DB_STGY_ANY);
1909	db_printf(" (%p)\n", th);
1910	if (th == NULL)
1911		return;
1912	DB_PRINTSYM(rint, th->th_rint);
1913	DB_PRINTSYM(rint_bypass, th->th_rint_bypass);
1914	DB_PRINTSYM(rint_done, th->th_rint_done);
1915	DB_PRINTSYM(rint_poll, th->th_rint_poll);
1916	DB_PRINTSYM(getc_inject, th->th_getc_inject);
1917	DB_PRINTSYM(getc_capture, th->th_getc_capture);
1918	DB_PRINTSYM(getc_poll, th->th_getc_poll);
1919	DB_PRINTSYM(close, th->th_close);
1920}
1921
1922static void
1923_db_show_termios(const char *name, const struct termios *t)
1924{
1925
1926	db_printf("%s: iflag 0x%x oflag 0x%x cflag 0x%x "
1927	    "lflag 0x%x ispeed %u ospeed %u\n", name,
1928	    t->c_iflag, t->c_oflag, t->c_cflag, t->c_lflag,
1929	    t->c_ispeed, t->c_ospeed);
1930}
1931
1932/* DDB command to show TTY statistics. */
1933DB_SHOW_COMMAND(tty, db_show_tty)
1934{
1935	struct tty *tp;
1936
1937	if (!have_addr) {
1938		db_printf("usage: show tty <addr>\n");
1939		return;
1940	}
1941	tp = (struct tty *)addr;
1942
1943	db_printf("0x%p: %s\n", tp, tty_devname(tp));
1944	db_printf("\tmtx: %p\n", tp->t_mtx);
1945	db_printf("\tflags: %b\n", tp->t_flags, TTY_FLAG_BITS);
1946	db_printf("\trevokecnt: %u\n", tp->t_revokecnt);
1947
1948	/* Buffering mechanisms. */
1949	db_printf("\tinq: %p begin %u linestart %u reprint %u end %u "
1950	    "nblocks %u quota %u\n", &tp->t_inq, tp->t_inq.ti_begin,
1951	    tp->t_inq.ti_linestart, tp->t_inq.ti_reprint, tp->t_inq.ti_end,
1952	    tp->t_inq.ti_nblocks, tp->t_inq.ti_quota);
1953	db_printf("\toutq: %p begin %u end %u nblocks %u quota %u\n",
1954	    &tp->t_outq, tp->t_outq.to_begin, tp->t_outq.to_end,
1955	    tp->t_outq.to_nblocks, tp->t_outq.to_quota);
1956	db_printf("\tinlow: %zu\n", tp->t_inlow);
1957	db_printf("\toutlow: %zu\n", tp->t_outlow);
1958	_db_show_termios("\ttermios", &tp->t_termios);
1959	db_printf("\twinsize: row %u col %u xpixel %u ypixel %u\n",
1960	    tp->t_winsize.ws_row, tp->t_winsize.ws_col,
1961	    tp->t_winsize.ws_xpixel, tp->t_winsize.ws_ypixel);
1962	db_printf("\tcolumn: %u\n", tp->t_column);
1963	db_printf("\twritepos: %u\n", tp->t_writepos);
1964	db_printf("\tcompatflags: 0x%x\n", tp->t_compatflags);
1965
1966	/* Init/lock-state devices. */
1967	_db_show_termios("\ttermios_init_in", &tp->t_termios_init_in);
1968	_db_show_termios("\ttermios_init_out", &tp->t_termios_init_out);
1969	_db_show_termios("\ttermios_lock_in", &tp->t_termios_lock_in);
1970	_db_show_termios("\ttermios_lock_out", &tp->t_termios_lock_out);
1971
1972	/* Hooks */
1973	_db_show_devsw("\t", tp->t_devsw);
1974	_db_show_hooks("\t", tp->t_hook);
1975
1976	/* Process info. */
1977	db_printf("\tpgrp: %p gid %d jobc %d\n", tp->t_pgrp,
1978	    tp->t_pgrp ? tp->t_pgrp->pg_id : 0,
1979	    tp->t_pgrp ? tp->t_pgrp->pg_jobc : 0);
1980	db_printf("\tsession: %p", tp->t_session);
1981	if (tp->t_session != NULL)
1982	    db_printf(" count %u leader %p tty %p sid %d login %s",
1983		tp->t_session->s_count, tp->t_session->s_leader,
1984		tp->t_session->s_ttyp, tp->t_session->s_sid,
1985		tp->t_session->s_login);
1986	db_printf("\n");
1987	db_printf("\tsessioncnt: %u\n", tp->t_sessioncnt);
1988	db_printf("\tdevswsoftc: %p\n", tp->t_devswsoftc);
1989	db_printf("\thooksoftc: %p\n", tp->t_hooksoftc);
1990	db_printf("\tdev: %p\n", tp->t_dev);
1991}
1992
1993/* DDB command to list TTYs. */
1994DB_SHOW_ALL_COMMAND(ttys, db_show_all_ttys)
1995{
1996	struct tty *tp;
1997	size_t isiz, osiz;
1998	int i, j;
1999
2000	/* Make the output look like `pstat -t'. */
2001	db_printf("PTR        ");
2002#if defined(__LP64__)
2003	db_printf("        ");
2004#endif
2005	db_printf("      LINE   INQ  CAN  LIN  LOW  OUTQ  USE  LOW   "
2006	    "COL  SESS  PGID STATE\n");
2007
2008	TAILQ_FOREACH(tp, &tty_list, t_list) {
2009		isiz = tp->t_inq.ti_nblocks * TTYINQ_DATASIZE;
2010		osiz = tp->t_outq.to_nblocks * TTYOUTQ_DATASIZE;
2011
2012		db_printf("%p %10s %5zu %4u %4u %4zu %5zu %4u %4zu %5u %5d %5d ",
2013		    tp,
2014		    tty_devname(tp),
2015		    isiz,
2016		    tp->t_inq.ti_linestart - tp->t_inq.ti_begin,
2017		    tp->t_inq.ti_end - tp->t_inq.ti_linestart,
2018		    isiz - tp->t_inlow,
2019		    osiz,
2020		    tp->t_outq.to_end - tp->t_outq.to_begin,
2021		    osiz - tp->t_outlow,
2022		    MIN(tp->t_column, 99999),
2023		    tp->t_session ? tp->t_session->s_sid : 0,
2024		    tp->t_pgrp ? tp->t_pgrp->pg_id : 0);
2025
2026		/* Flag bits. */
2027		for (i = j = 0; ttystates[i].flag; i++)
2028			if (tp->t_flags & ttystates[i].flag) {
2029				db_printf("%c", ttystates[i].val);
2030				j++;
2031			}
2032		if (j == 0)
2033			db_printf("-");
2034		db_printf("\n");
2035	}
2036}
2037#endif /* DDB */
2038