2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2008 Ed Schouten <ed@FreeBSD.org>
7 * Portions of this software were developed under sponsorship from Snow
8 * B.V., the Netherlands.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
35 #include "opt_capsicum.h"
36 #include "opt_printf.h"
38 #include <sys/param.h>
39 #include <sys/capsicum.h>
42 #include <sys/fcntl.h>
44 #include <sys/filedesc.h>
45 #include <sys/filio.h>
47 #include <sys/ioctl_compat.h>
48 #endif /* COMPAT_43TTY */
49 #include <sys/kernel.h>
50 #include <sys/limits.h>
51 #include <sys/malloc.h>
52 #include <sys/mount.h>
56 #include <sys/serial.h>
57 #include <sys/signal.h>
60 #include <sys/sysctl.h>
61 #include <sys/systm.h>
63 #include <sys/ttycom.h>
65 #include <sys/ttydefaults.h>
67 #include <sys/ucred.h>
68 #include <sys/vnode.h>
70 #include <fs/devfs/devfs.h>
72 #include <machine/stdarg.h>
74 static MALLOC_DEFINE(M_TTY, "tty", "tty device");
76 static void tty_rel_free(struct tty *tp);
78 static TAILQ_HEAD(, tty) tty_list = TAILQ_HEAD_INITIALIZER(tty_list);
79 static struct sx tty_list_sx;
80 SX_SYSINIT(tty_list, &tty_list_sx, "tty list");
81 static unsigned int tty_list_count = 0;
83 /* Character device of /dev/console. */
84 static struct cdev *dev_console;
85 static const char *dev_console_filename;
88 * Flags that are supported and stored by this implementation.
90 #define TTYSUP_IFLAG (IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK|ISTRIP|\
91 INLCR|IGNCR|ICRNL|IXON|IXOFF|IXANY|IMAXBEL)
92 #define TTYSUP_OFLAG (OPOST|ONLCR|TAB3|ONOEOT|OCRNL|ONOCR|ONLRET)
93 #define TTYSUP_LFLAG (ECHOKE|ECHOE|ECHOK|ECHO|ECHONL|ECHOPRT|\
94 ECHOCTL|ISIG|ICANON|ALTWERASE|IEXTEN|TOSTOP|\
95 FLUSHO|NOKERNINFO|NOFLSH)
96 #define TTYSUP_CFLAG (CIGNORE|CSIZE|CSTOPB|CREAD|PARENB|PARODD|\
97 HUPCL|CLOCAL|CCTS_OFLOW|CRTS_IFLOW|CDTR_IFLOW|\
98 CDSR_OFLOW|CCAR_OFLOW|CNO_RTSDTR)
100 #define TTY_CALLOUT(tp,d) (dev2unit(d) & TTYUNIT_CALLOUT)
102 static int tty_drainwait = 5 * 60;
103 SYSCTL_INT(_kern, OID_AUTO, tty_drainwait, CTLFLAG_RWTUN,
104 &tty_drainwait, 0, "Default output drain timeout in seconds");
107 * Set TTY buffer sizes.
110 #define TTYBUF_MAX 65536
112 #ifdef PRINTF_BUFR_SIZE
113 #define TTY_PRBUF_SIZE PRINTF_BUFR_SIZE
115 #define TTY_PRBUF_SIZE 256
119 * Allocate buffer space if necessary, and set low watermarks, based on speed.
120 * Note that the ttyxxxq_setsize() functions may drop and then reacquire the tty
121 * lock during memory allocation. They will return ENXIO if the tty disappears
125 tty_watermarks(struct tty *tp)
130 /* Provide an input buffer for 2 seconds of data. */
131 if (tp->t_termios.c_cflag & CREAD)
132 bs = MIN(tp->t_termios.c_ispeed / 5, TTYBUF_MAX);
133 error = ttyinq_setsize(&tp->t_inq, tp, bs);
137 /* Set low watermark at 10% (when 90% is available). */
138 tp->t_inlow = (ttyinq_getallocatedsize(&tp->t_inq) * 9) / 10;
140 /* Provide an output buffer for 2 seconds of data. */
141 bs = MIN(tp->t_termios.c_ospeed / 5, TTYBUF_MAX);
142 error = ttyoutq_setsize(&tp->t_outq, tp, bs);
146 /* Set low watermark at 10% (when 90% is available). */
147 tp->t_outlow = (ttyoutq_getallocatedsize(&tp->t_outq) * 9) / 10;
153 tty_drain(struct tty *tp, int leaving)
155 sbintime_t timeout_at;
159 if (ttyhook_hashook(tp, getc_inject))
160 /* buffer is inaccessible */
164 * For close(), use the recent historic timeout of "1 second without
165 * making progress". For tcdrain(), use t_drainwait as the timeout,
166 * with zero meaning "no timeout" which gives POSIX behavior.
169 timeout_at = getsbinuptime() + SBT_1S;
170 else if (tp->t_drainwait != 0)
171 timeout_at = getsbinuptime() + SBT_1S * tp->t_drainwait;
176 * Poll the output buffer and the hardware for completion, at 10 Hz.
177 * Polling is required for devices which are not able to signal an
178 * interrupt when the transmitter becomes idle (most USB serial devs).
179 * The unusual structure of this loop ensures we check for busy one more
180 * time after tty_timedwait() returns EWOULDBLOCK, so that success has
181 * higher priority than timeout if the IO completed in the last 100mS.
184 bytes = ttyoutq_bytesused(&tp->t_outq);
186 if (ttyoutq_bytesused(&tp->t_outq) == 0 && !ttydevsw_busy(tp))
190 ttydevsw_outwakeup(tp);
191 error = tty_timedwait(tp, &tp->t_outwait, hz / 10);
192 if (error != 0 && error != EWOULDBLOCK)
194 else if (timeout_at == 0 || getsbinuptime() < timeout_at)
196 else if (leaving && ttyoutq_bytesused(&tp->t_outq) < bytes) {
197 /* In close, making progress, grant an extra second. */
199 timeout_at += SBT_1S;
200 bytes = ttyoutq_bytesused(&tp->t_outq);
206 * Though ttydev_enter() and ttydev_leave() seem to be related, they
207 * don't have to be used together. ttydev_enter() is used by the cdev
208 * operations to prevent an actual operation from being processed when
209 * the TTY has been abandoned. ttydev_leave() is used by ttydev_open()
210 * and ttydev_close() to determine whether per-TTY data should be
215 ttydev_enter(struct tty *tp)
220 if (tty_gone(tp) || !tty_opened(tp)) {
221 /* Device is already gone. */
230 ttydev_leave(struct tty *tp)
233 tty_assert_locked(tp);
235 if (tty_opened(tp) || tp->t_flags & TF_OPENCLOSE) {
236 /* Device is still opened somewhere. */
241 tp->t_flags |= TF_OPENCLOSE;
243 /* Remove console TTY. */
247 /* Drain any output. */
253 /* Free i/o queues now since they might be large. */
254 ttyinq_free(&tp->t_inq);
256 ttyoutq_free(&tp->t_outq);
259 knlist_clear(&tp->t_inpoll.si_note, 1);
260 knlist_clear(&tp->t_outpoll.si_note, 1);
265 tp->t_flags &= ~TF_OPENCLOSE;
266 cv_broadcast(&tp->t_dcdwait);
271 * Operations that are exposed through the character device in /dev.
274 ttydev_open(struct cdev *dev, int oflags, int devtype __unused,
284 /* Device is already gone. */
290 * Block when other processes are currently opening or closing
293 while (tp->t_flags & TF_OPENCLOSE) {
294 error = tty_wait(tp, &tp->t_dcdwait);
300 tp->t_flags |= TF_OPENCLOSE;
303 * Make sure the "tty" and "cua" device cannot be opened at the
304 * same time. The console is a "tty" device.
306 if (TTY_CALLOUT(tp, dev)) {
307 if (tp->t_flags & (TF_OPENED_CONS | TF_OPENED_IN)) {
312 if (tp->t_flags & TF_OPENED_OUT) {
318 if (tp->t_flags & TF_EXCLUDE && priv_check(td, PRIV_TTY_EXCLUSIVE)) {
323 if (!tty_opened(tp)) {
324 /* Set proper termios flags. */
325 if (TTY_CALLOUT(tp, dev))
326 tp->t_termios = tp->t_termios_init_out;
328 tp->t_termios = tp->t_termios_init_in;
329 ttydevsw_param(tp, &tp->t_termios);
330 /* Prevent modem control on callout devices and /dev/console. */
331 if (TTY_CALLOUT(tp, dev) || dev == dev_console)
332 tp->t_termios.c_cflag |= CLOCAL;
334 if ((tp->t_termios.c_cflag & CNO_RTSDTR) == 0)
335 ttydevsw_modem(tp, SER_DTR|SER_RTS, 0);
337 error = ttydevsw_open(tp);
342 error = tty_watermarks(tp);
347 /* Wait for Carrier Detect. */
348 if ((oflags & O_NONBLOCK) == 0 &&
349 (tp->t_termios.c_cflag & CLOCAL) == 0) {
350 while ((ttydevsw_modem(tp, 0, 0) & SER_DCD) == 0) {
351 error = tty_wait(tp, &tp->t_dcdwait);
357 if (dev == dev_console)
358 tp->t_flags |= TF_OPENED_CONS;
359 else if (TTY_CALLOUT(tp, dev))
360 tp->t_flags |= TF_OPENED_OUT;
362 tp->t_flags |= TF_OPENED_IN;
363 MPASS((tp->t_flags & (TF_OPENED_CONS | TF_OPENED_IN)) == 0 ||
364 (tp->t_flags & TF_OPENED_OUT) == 0);
366 done: tp->t_flags &= ~TF_OPENCLOSE;
367 cv_broadcast(&tp->t_dcdwait);
374 ttydev_close(struct cdev *dev, int fflag, int devtype __unused,
375 struct thread *td __unused)
377 struct tty *tp = dev->si_drv1;
382 * Don't actually close the device if it is being used as the
385 MPASS((tp->t_flags & (TF_OPENED_CONS | TF_OPENED_IN)) == 0 ||
386 (tp->t_flags & TF_OPENED_OUT) == 0);
387 if (dev == dev_console)
388 tp->t_flags &= ~TF_OPENED_CONS;
390 tp->t_flags &= ~(TF_OPENED_IN|TF_OPENED_OUT);
392 if (tp->t_flags & TF_OPENED) {
397 /* If revoking, flush output now to avoid draining it later. */
399 tty_flush(tp, FWRITE);
401 tp->t_flags &= ~TF_EXCLUDE;
403 /* Properly wake up threads that are stuck - revoke(). */
405 tty_wakeup(tp, FREAD|FWRITE);
406 cv_broadcast(&tp->t_bgwait);
407 cv_broadcast(&tp->t_dcdwait);
415 tty_is_ctty(struct tty *tp, struct proc *p)
418 tty_assert_locked(tp);
420 return (p->p_session == tp->t_session && p->p_flag & P_CONTROLT);
424 tty_wait_background(struct tty *tp, struct thread *td, int sig)
431 MPASS(sig == SIGTTIN || sig == SIGTTOU);
432 tty_assert_locked(tp);
441 * pg may no longer be our process group.
442 * Re-check after locking.
444 if (p->p_pgrp != pg) {
451 * The process should only sleep, when:
452 * - This terminal is the controlling terminal
453 * - Its process group is not the foreground process
455 * - The parent process isn't waiting for the child to
457 * - the signal to send to the process isn't masked
459 if (!tty_is_ctty(tp, p) || p->p_pgrp == tp->t_pgrp) {
460 /* Allow the action to happen. */
466 if (SIGISMEMBER(p->p_sigacts->ps_sigignore, sig) ||
467 SIGISMEMBER(td->td_sigmask, sig)) {
468 /* Only allow them in write()/ioctl(). */
471 return (sig == SIGTTOU ? 0 : EIO);
474 if ((p->p_flag & P_PPWAIT) != 0 ||
475 (pg->pg_flags & PGRP_ORPHANED) != 0) {
476 /* Don't allow the action to happen. */
484 * Send the signal and sleep until we're the new
485 * foreground process group.
489 ksi.ksi_code = SI_KERNEL;
494 pgsignal(pg, ksi.ksi_signo, 1, &ksi);
497 error = tty_wait(tp, &tp->t_bgwait);
504 ttydev_read(struct cdev *dev, struct uio *uio, int ioflag)
506 struct tty *tp = dev->si_drv1;
509 error = ttydev_enter(tp);
512 error = ttydisc_read(tp, uio, ioflag);
516 * The read() call should not throw an error when the device is
517 * being destroyed. Silently convert it to an EOF.
519 done: if (error == ENXIO)
525 ttydev_write(struct cdev *dev, struct uio *uio, int ioflag)
527 struct tty *tp = dev->si_drv1;
530 error = ttydev_enter(tp);
534 if (tp->t_termios.c_lflag & TOSTOP) {
535 error = tty_wait_background(tp, curthread, SIGTTOU);
540 if (ioflag & IO_NDELAY && tp->t_flags & TF_BUSY_OUT) {
541 /* Allow non-blocking writes to bypass serialization. */
542 error = ttydisc_write(tp, uio, ioflag);
544 /* Serialize write() calls. */
545 while (tp->t_flags & TF_BUSY_OUT) {
546 error = tty_wait(tp, &tp->t_outserwait);
551 tp->t_flags |= TF_BUSY_OUT;
552 error = ttydisc_write(tp, uio, ioflag);
553 tp->t_flags &= ~TF_BUSY_OUT;
554 cv_signal(&tp->t_outserwait);
557 done: tty_unlock(tp);
562 ttydev_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
565 struct tty *tp = dev->si_drv1;
568 error = ttydev_enter(tp);
603 #endif /* COMPAT_43TTY */
605 * If the ioctl() causes the TTY to be modified, let it
606 * wait in the background.
608 error = tty_wait_background(tp, curthread, SIGTTOU);
613 if (cmd == TIOCSETA || cmd == TIOCSETAW || cmd == TIOCSETAF) {
614 struct termios *old = &tp->t_termios;
615 struct termios *new = (struct termios *)data;
616 struct termios *lock = TTY_CALLOUT(tp, dev) ?
617 &tp->t_termios_lock_out : &tp->t_termios_lock_in;
621 * Lock state devices. Just overwrite the values of the
622 * commands that are currently in use.
624 new->c_iflag = (old->c_iflag & lock->c_iflag) |
625 (new->c_iflag & ~lock->c_iflag);
626 new->c_oflag = (old->c_oflag & lock->c_oflag) |
627 (new->c_oflag & ~lock->c_oflag);
628 new->c_cflag = (old->c_cflag & lock->c_cflag) |
629 (new->c_cflag & ~lock->c_cflag);
630 new->c_lflag = (old->c_lflag & lock->c_lflag) |
631 (new->c_lflag & ~lock->c_lflag);
632 for (cc = 0; cc < NCCS; ++cc)
634 new->c_cc[cc] = old->c_cc[cc];
636 new->c_ispeed = old->c_ispeed;
638 new->c_ospeed = old->c_ospeed;
641 error = tty_ioctl(tp, cmd, data, fflag, td);
642 done: tty_unlock(tp);
648 ttydev_poll(struct cdev *dev, int events, struct thread *td)
650 struct tty *tp = dev->si_drv1;
651 int error, revents = 0;
653 error = ttydev_enter(tp);
655 return ((events & (POLLIN|POLLRDNORM)) | POLLHUP);
657 if (events & (POLLIN|POLLRDNORM)) {
658 /* See if we can read something. */
659 if (ttydisc_read_poll(tp) > 0)
660 revents |= events & (POLLIN|POLLRDNORM);
663 if (tp->t_flags & TF_ZOMBIE) {
664 /* Hangup flag on zombie state. */
666 } else if (events & (POLLOUT|POLLWRNORM)) {
667 /* See if we can write something. */
668 if (ttydisc_write_poll(tp) > 0)
669 revents |= events & (POLLOUT|POLLWRNORM);
673 if (events & (POLLIN|POLLRDNORM))
674 selrecord(td, &tp->t_inpoll);
675 if (events & (POLLOUT|POLLWRNORM))
676 selrecord(td, &tp->t_outpoll);
685 ttydev_mmap(struct cdev *dev, vm_ooffset_t offset, vm_paddr_t *paddr,
686 int nprot, vm_memattr_t *memattr)
688 struct tty *tp = dev->si_drv1;
691 /* Handle mmap() through the driver. */
693 error = ttydev_enter(tp);
696 error = ttydevsw_mmap(tp, offset, paddr, nprot, memattr);
707 tty_kqops_read_detach(struct knote *kn)
709 struct tty *tp = kn->kn_hook;
711 knlist_remove(&tp->t_inpoll.si_note, kn, 0);
715 tty_kqops_read_event(struct knote *kn, long hint __unused)
717 struct tty *tp = kn->kn_hook;
719 tty_assert_locked(tp);
721 if (tty_gone(tp) || tp->t_flags & TF_ZOMBIE) {
722 kn->kn_flags |= EV_EOF;
725 kn->kn_data = ttydisc_read_poll(tp);
726 return (kn->kn_data > 0);
731 tty_kqops_write_detach(struct knote *kn)
733 struct tty *tp = kn->kn_hook;
735 knlist_remove(&tp->t_outpoll.si_note, kn, 0);
739 tty_kqops_write_event(struct knote *kn, long hint __unused)
741 struct tty *tp = kn->kn_hook;
743 tty_assert_locked(tp);
746 kn->kn_flags |= EV_EOF;
749 kn->kn_data = ttydisc_write_poll(tp);
750 return (kn->kn_data > 0);
754 static struct filterops tty_kqops_read = {
756 .f_detach = tty_kqops_read_detach,
757 .f_event = tty_kqops_read_event,
760 static struct filterops tty_kqops_write = {
762 .f_detach = tty_kqops_write_detach,
763 .f_event = tty_kqops_write_event,
767 ttydev_kqfilter(struct cdev *dev, struct knote *kn)
769 struct tty *tp = dev->si_drv1;
772 error = ttydev_enter(tp);
776 switch (kn->kn_filter) {
779 kn->kn_fop = &tty_kqops_read;
780 knlist_add(&tp->t_inpoll.si_note, kn, 1);
784 kn->kn_fop = &tty_kqops_write;
785 knlist_add(&tp->t_outpoll.si_note, kn, 1);
796 static struct cdevsw ttydev_cdevsw = {
797 .d_version = D_VERSION,
798 .d_open = ttydev_open,
799 .d_close = ttydev_close,
800 .d_read = ttydev_read,
801 .d_write = ttydev_write,
802 .d_ioctl = ttydev_ioctl,
803 .d_kqfilter = ttydev_kqfilter,
804 .d_poll = ttydev_poll,
805 .d_mmap = ttydev_mmap,
811 * Init/lock-state devices
815 ttyil_open(struct cdev *dev, int oflags __unused, int devtype __unused,
832 ttyil_close(struct cdev *dev __unused, int flag __unused, int mode __unused,
833 struct thread *td __unused)
840 ttyil_rdwr(struct cdev *dev __unused, struct uio *uio __unused,
848 ttyil_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
851 struct tty *tp = dev->si_drv1;
860 error = ttydevsw_cioctl(tp, dev2unit(dev), cmd, data, td);
861 if (error != ENOIOCTL)
867 /* Obtain terminal flags through tcgetattr(). */
868 *(struct termios*)data = *(struct termios*)dev->si_drv2;
871 /* Set terminal flags through tcsetattr(). */
872 error = priv_check(td, PRIV_TTY_SETA);
875 *(struct termios*)dev->si_drv2 = *(struct termios*)data;
878 *(int *)data = TTYDISC;
881 bzero(data, sizeof(struct winsize));
887 done: tty_unlock(tp);
891 static struct cdevsw ttyil_cdevsw = {
892 .d_version = D_VERSION,
893 .d_open = ttyil_open,
894 .d_close = ttyil_close,
895 .d_read = ttyil_rdwr,
896 .d_write = ttyil_rdwr,
897 .d_ioctl = ttyil_ioctl,
903 tty_init_termios(struct tty *tp)
905 struct termios *t = &tp->t_termios_init_in;
907 t->c_cflag = TTYDEF_CFLAG;
908 t->c_iflag = TTYDEF_IFLAG;
909 t->c_lflag = TTYDEF_LFLAG;
910 t->c_oflag = TTYDEF_OFLAG;
911 t->c_ispeed = TTYDEF_SPEED;
912 t->c_ospeed = TTYDEF_SPEED;
913 memcpy(&t->c_cc, ttydefchars, sizeof ttydefchars);
915 tp->t_termios_init_out = *t;
919 tty_init_console(struct tty *tp, speed_t s)
921 struct termios *ti = &tp->t_termios_init_in;
922 struct termios *to = &tp->t_termios_init_out;
925 ti->c_ispeed = ti->c_ospeed = s;
926 to->c_ispeed = to->c_ospeed = s;
929 ti->c_cflag |= CLOCAL;
930 to->c_cflag |= CLOCAL;
934 * Standard device routine implementations, mostly meant for
935 * pseudo-terminal device drivers. When a driver creates a new terminal
936 * device class, missing routines are patched.
940 ttydevsw_defopen(struct tty *tp __unused)
947 ttydevsw_defclose(struct tty *tp __unused)
953 ttydevsw_defoutwakeup(struct tty *tp __unused)
956 panic("Terminal device has output, while not implemented");
960 ttydevsw_definwakeup(struct tty *tp __unused)
966 ttydevsw_defioctl(struct tty *tp __unused, u_long cmd __unused,
967 caddr_t data __unused, struct thread *td __unused)
974 ttydevsw_defcioctl(struct tty *tp __unused, int unit __unused,
975 u_long cmd __unused, caddr_t data __unused, struct thread *td __unused)
982 ttydevsw_defparam(struct tty *tp __unused, struct termios *t)
986 * Allow the baud rate to be adjusted for pseudo-devices, but at
987 * least restrict it to 115200 to prevent excessive buffer
988 * usage. Also disallow 0, to prevent foot shooting.
990 if (t->c_ispeed < B50)
992 else if (t->c_ispeed > B115200)
993 t->c_ispeed = B115200;
994 if (t->c_ospeed < B50)
996 else if (t->c_ospeed > B115200)
997 t->c_ospeed = B115200;
1004 ttydevsw_defmodem(struct tty *tp __unused, int sigon __unused,
1005 int sigoff __unused)
1008 /* Simulate a carrier to make the TTY layer happy. */
1013 ttydevsw_defmmap(struct tty *tp __unused, vm_ooffset_t offset __unused,
1014 vm_paddr_t *paddr __unused, int nprot __unused,
1015 vm_memattr_t *memattr __unused)
1022 ttydevsw_defpktnotify(struct tty *tp __unused, char event __unused)
1028 ttydevsw_deffree(void *softc __unused)
1031 panic("Terminal device freed without a free-handler");
1035 ttydevsw_defbusy(struct tty *tp __unused)
1042 * TTY allocation and deallocation. TTY devices can be deallocated when
1043 * the driver doesn't use it anymore, when the TTY isn't a session's
1044 * controlling TTY and when the device node isn't opened through devfs.
1048 tty_alloc(struct ttydevsw *tsw, void *sc)
1051 return (tty_alloc_mutex(tsw, sc, NULL));
1055 tty_alloc_mutex(struct ttydevsw *tsw, void *sc, struct mtx *mutex)
1059 /* Make sure the driver defines all routines. */
1060 #define PATCH_FUNC(x) do { \
1061 if (tsw->tsw_ ## x == NULL) \
1062 tsw->tsw_ ## x = ttydevsw_def ## x; \
1066 PATCH_FUNC(outwakeup);
1067 PATCH_FUNC(inwakeup);
1073 PATCH_FUNC(pktnotify);
1078 tp = malloc(sizeof(struct tty) + TTY_PRBUF_SIZE, M_TTY,
1080 tp->t_prbufsz = TTY_PRBUF_SIZE;
1082 tp->t_devswsoftc = sc;
1083 tp->t_flags = tsw->tsw_flags;
1084 tp->t_drainwait = tty_drainwait;
1086 tty_init_termios(tp);
1088 cv_init(&tp->t_inwait, "ttyin");
1089 cv_init(&tp->t_outwait, "ttyout");
1090 cv_init(&tp->t_outserwait, "ttyosr");
1091 cv_init(&tp->t_bgwait, "ttybg");
1092 cv_init(&tp->t_dcdwait, "ttydcd");
1094 /* Allow drivers to use a custom mutex to lock the TTY. */
1095 if (mutex != NULL) {
1098 tp->t_mtx = &tp->t_mtxobj;
1099 mtx_init(&tp->t_mtxobj, "ttymtx", NULL, MTX_DEF);
1102 knlist_init_mtx(&tp->t_inpoll.si_note, tp->t_mtx);
1103 knlist_init_mtx(&tp->t_outpoll.si_note, tp->t_mtx);
1109 tty_dealloc(void *arg)
1111 struct tty *tp = arg;
1114 * ttyydev_leave() usually frees the i/o queues earlier, but it is
1115 * not always called between queue allocation and here. The queues
1116 * may be allocated by ioctls on a pty control device without the
1117 * corresponding pty slave device ever being open, or after it is
1120 ttyinq_free(&tp->t_inq);
1121 ttyoutq_free(&tp->t_outq);
1122 seldrain(&tp->t_inpoll);
1123 seldrain(&tp->t_outpoll);
1124 knlist_destroy(&tp->t_inpoll.si_note);
1125 knlist_destroy(&tp->t_outpoll.si_note);
1127 cv_destroy(&tp->t_inwait);
1128 cv_destroy(&tp->t_outwait);
1129 cv_destroy(&tp->t_bgwait);
1130 cv_destroy(&tp->t_dcdwait);
1131 cv_destroy(&tp->t_outserwait);
1133 if (tp->t_mtx == &tp->t_mtxobj)
1134 mtx_destroy(&tp->t_mtxobj);
1140 tty_rel_free(struct tty *tp)
1144 tty_assert_locked(tp);
1146 #define TF_ACTIVITY (TF_GONE|TF_OPENED|TF_HOOK|TF_OPENCLOSE)
1147 if (tp->t_sessioncnt != 0 || (tp->t_flags & TF_ACTIVITY) != TF_GONE) {
1148 /* TTY is still in use. */
1153 /* Stop asynchronous I/O. */
1154 funsetown(&tp->t_sigio);
1156 /* TTY can be deallocated. */
1162 sx_xlock(&tty_list_sx);
1163 TAILQ_REMOVE(&tty_list, tp, t_list);
1165 sx_xunlock(&tty_list_sx);
1166 destroy_dev_sched_cb(dev, tty_dealloc, tp);
1171 tty_rel_pgrp(struct tty *tp, struct pgrp *pg)
1174 MPASS(tp->t_sessioncnt > 0);
1175 tty_assert_locked(tp);
1177 if (tp->t_pgrp == pg)
1184 tty_rel_sess(struct tty *tp, struct session *sess)
1187 MPASS(tp->t_sessioncnt > 0);
1189 /* Current session has left. */
1190 if (tp->t_session == sess) {
1191 tp->t_session = NULL;
1192 MPASS(tp->t_pgrp == NULL);
1199 tty_rel_gone(struct tty *tp)
1202 tty_assert_locked(tp);
1203 MPASS(!tty_gone(tp));
1205 /* Simulate carrier removal. */
1206 ttydisc_modem(tp, 0);
1208 /* Wake up all blocked threads. */
1209 tty_wakeup(tp, FREAD|FWRITE);
1210 cv_broadcast(&tp->t_bgwait);
1211 cv_broadcast(&tp->t_dcdwait);
1213 tp->t_flags |= TF_GONE;
1218 tty_drop_ctty(struct tty *tp, struct proc *p)
1220 struct session *session;
1224 * This looks terrible, but it's generally safe as long as the tty
1225 * hasn't gone away while we had the lock dropped. All of our sanity
1226 * checking that this operation is OK happens after we've picked it back
1227 * up, so other state changes are generally not fatal and the potential
1228 * for this particular operation to happen out-of-order in a
1229 * multithreaded scenario is likely a non-issue.
1232 sx_xlock(&proctree_lock);
1235 sx_xunlock(&proctree_lock);
1240 * If the session doesn't have a controlling TTY, or if we weren't
1241 * invoked on the controlling TTY, we'll return ENOIOCTL as we've
1242 * historically done.
1244 session = p->p_session;
1245 if (session->s_ttyp == NULL || session->s_ttyp != tp) {
1246 sx_xunlock(&proctree_lock);
1250 if (!SESS_LEADER(p)) {
1251 sx_xunlock(&proctree_lock);
1257 vp = session->s_ttyvp;
1258 session->s_ttyp = NULL;
1259 session->s_ttyvp = NULL;
1260 session->s_ttydp = NULL;
1261 SESS_UNLOCK(session);
1264 p->p_flag &= ~P_CONTROLT;
1266 sx_xunlock(&proctree_lock);
1269 * If we did have a vnode, release our reference. Ordinarily we manage
1270 * these at the devfs layer, but we can't necessarily know that we were
1271 * invoked on the vnode referenced in the session (i.e. the vnode we
1272 * hold a reference to). We explicitly don't check VBAD/VIRF_DOOMED here
1273 * to avoid a vnode leak -- in circumstances elsewhere where we'd hit a
1274 * VIRF_DOOMED vnode, release has been deferred until the controlling TTY
1275 * is either changed or released.
1278 devfs_ctty_unref(vp);
1283 * Exposing information about current TTY's through sysctl
1287 tty_to_xtty(struct tty *tp, struct xtty *xt)
1290 tty_assert_locked(tp);
1292 xt->xt_size = sizeof(struct xtty);
1293 xt->xt_insize = ttyinq_getsize(&tp->t_inq);
1294 xt->xt_incc = ttyinq_bytescanonicalized(&tp->t_inq);
1295 xt->xt_inlc = ttyinq_bytesline(&tp->t_inq);
1296 xt->xt_inlow = tp->t_inlow;
1297 xt->xt_outsize = ttyoutq_getsize(&tp->t_outq);
1298 xt->xt_outcc = ttyoutq_bytesused(&tp->t_outq);
1299 xt->xt_outlow = tp->t_outlow;
1300 xt->xt_column = tp->t_column;
1301 xt->xt_pgid = tp->t_pgrp ? tp->t_pgrp->pg_id : 0;
1302 xt->xt_sid = tp->t_session ? tp->t_session->s_sid : 0;
1303 xt->xt_flags = tp->t_flags;
1304 xt->xt_dev = tp->t_dev ? dev2udev(tp->t_dev) : (uint32_t)NODEV;
1308 sysctl_kern_ttys(SYSCTL_HANDLER_ARGS)
1310 unsigned long lsize;
1311 struct xtty *xtlist, *xt;
1315 sx_slock(&tty_list_sx);
1316 lsize = tty_list_count * sizeof(struct xtty);
1318 sx_sunlock(&tty_list_sx);
1322 xtlist = xt = malloc(lsize, M_TTY, M_WAITOK);
1324 TAILQ_FOREACH(tp, &tty_list, t_list) {
1326 tty_to_xtty(tp, xt);
1330 sx_sunlock(&tty_list_sx);
1332 error = SYSCTL_OUT(req, xtlist, lsize);
1333 free(xtlist, M_TTY);
1337 SYSCTL_PROC(_kern, OID_AUTO, ttys, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
1338 0, 0, sysctl_kern_ttys, "S,xtty", "List of TTYs");
1341 * Device node creation. Device has been set up, now we can expose it to
1346 tty_makedevf(struct tty *tp, struct ucred *cred, int flags,
1347 const char *fmt, ...)
1350 struct make_dev_args args;
1351 struct cdev *dev, *init, *lock, *cua, *cinit, *clock;
1352 const char *prefix = "tty";
1353 char name[SPECNAMELEN - 3]; /* for "tty" and "cua". */
1359 /* Remove "tty" prefix from devices like PTY's. */
1360 if (tp->t_flags & TF_NOPREFIX)
1364 vsnrprintf(name, sizeof name, 32, fmt, ap);
1368 /* System device. */
1371 mode = S_IRUSR|S_IWUSR;
1374 uid = cred->cr_ruid;
1376 mode = S_IRUSR|S_IWUSR|S_IWGRP;
1379 flags = flags & TTYMK_CLONING ? MAKEDEV_REF : 0;
1380 flags |= MAKEDEV_CHECKNAME;
1382 /* Master call-in device. */
1383 make_dev_args_init(&args);
1384 args.mda_flags = flags;
1385 args.mda_devsw = &ttydev_cdevsw;
1389 args.mda_mode = mode;
1390 args.mda_si_drv1 = tp;
1391 error = make_dev_s(&args, &dev, "%s%s", prefix, name);
1396 init = lock = cua = cinit = clock = NULL;
1398 /* Slave call-in devices. */
1399 if (tp->t_flags & TF_INITLOCK) {
1400 args.mda_devsw = &ttyil_cdevsw;
1401 args.mda_unit = TTYUNIT_INIT;
1402 args.mda_si_drv1 = tp;
1403 args.mda_si_drv2 = &tp->t_termios_init_in;
1404 error = make_dev_s(&args, &init, "%s%s.init", prefix, name);
1407 dev_depends(dev, init);
1409 args.mda_unit = TTYUNIT_LOCK;
1410 args.mda_si_drv2 = &tp->t_termios_lock_in;
1411 error = make_dev_s(&args, &lock, "%s%s.lock", prefix, name);
1414 dev_depends(dev, lock);
1417 /* Call-out devices. */
1418 if (tp->t_flags & TF_CALLOUT) {
1419 make_dev_args_init(&args);
1420 args.mda_flags = flags;
1421 args.mda_devsw = &ttydev_cdevsw;
1423 args.mda_uid = UID_UUCP;
1424 args.mda_gid = GID_DIALER;
1425 args.mda_mode = 0660;
1426 args.mda_unit = TTYUNIT_CALLOUT;
1427 args.mda_si_drv1 = tp;
1428 error = make_dev_s(&args, &cua, "cua%s", name);
1431 dev_depends(dev, cua);
1433 /* Slave call-out devices. */
1434 if (tp->t_flags & TF_INITLOCK) {
1435 args.mda_devsw = &ttyil_cdevsw;
1436 args.mda_unit = TTYUNIT_CALLOUT | TTYUNIT_INIT;
1437 args.mda_si_drv2 = &tp->t_termios_init_out;
1438 error = make_dev_s(&args, &cinit, "cua%s.init", name);
1441 dev_depends(dev, cinit);
1443 args.mda_unit = TTYUNIT_CALLOUT | TTYUNIT_LOCK;
1444 args.mda_si_drv2 = &tp->t_termios_lock_out;
1445 error = make_dev_s(&args, &clock, "cua%s.lock", name);
1448 dev_depends(dev, clock);
1452 sx_xlock(&tty_list_sx);
1453 TAILQ_INSERT_TAIL(&tty_list, tp, t_list);
1455 sx_xunlock(&tty_list_sx);
1474 * Signalling processes.
1478 tty_signal_sessleader(struct tty *tp, int sig)
1483 tty_assert_locked(tp);
1484 MPASS(sig >= 1 && sig < NSIG);
1486 /* Make signals start output again. */
1487 tp->t_flags &= ~TF_STOPPED;
1488 tp->t_termios.c_lflag &= ~FLUSHO;
1491 * Load s_leader exactly once to avoid race where s_leader is
1492 * set to NULL by a concurrent invocation of killjobc() by the
1493 * session leader. Note that we are not holding t_session's
1494 * lock for the read.
1496 if ((s = tp->t_session) != NULL &&
1497 (p = atomic_load_ptr(&s->s_leader)) != NULL) {
1499 kern_psignal(p, sig);
1505 tty_signal_pgrp(struct tty *tp, int sig)
1509 tty_assert_locked(tp);
1510 MPASS(sig >= 1 && sig < NSIG);
1512 /* Make signals start output again. */
1513 tp->t_flags &= ~TF_STOPPED;
1514 tp->t_termios.c_lflag &= ~FLUSHO;
1516 if (sig == SIGINFO && !(tp->t_termios.c_lflag & NOKERNINFO))
1518 if (tp->t_pgrp != NULL) {
1519 ksiginfo_init(&ksi);
1520 ksi.ksi_signo = sig;
1521 ksi.ksi_code = SI_KERNEL;
1522 PGRP_LOCK(tp->t_pgrp);
1523 pgsignal(tp->t_pgrp, sig, 1, &ksi);
1524 PGRP_UNLOCK(tp->t_pgrp);
1529 tty_wakeup(struct tty *tp, int flags)
1532 if (tp->t_flags & TF_ASYNC && tp->t_sigio != NULL)
1533 pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
1535 if (flags & FWRITE) {
1536 cv_broadcast(&tp->t_outwait);
1537 selwakeup(&tp->t_outpoll);
1538 KNOTE_LOCKED(&tp->t_outpoll.si_note, 0);
1540 if (flags & FREAD) {
1541 cv_broadcast(&tp->t_inwait);
1542 selwakeup(&tp->t_inpoll);
1543 KNOTE_LOCKED(&tp->t_inpoll.si_note, 0);
1548 tty_wait(struct tty *tp, struct cv *cv)
1551 int revokecnt = tp->t_revokecnt;
1553 tty_lock_assert(tp, MA_OWNED|MA_NOTRECURSED);
1554 MPASS(!tty_gone(tp));
1556 error = cv_wait_sig(cv, tp->t_mtx);
1558 /* Bail out when the device slipped away. */
1562 /* Restart the system call when we may have been revoked. */
1563 if (tp->t_revokecnt != revokecnt)
1570 tty_timedwait(struct tty *tp, struct cv *cv, int hz)
1573 int revokecnt = tp->t_revokecnt;
1575 tty_lock_assert(tp, MA_OWNED|MA_NOTRECURSED);
1576 MPASS(!tty_gone(tp));
1578 error = cv_timedwait_sig(cv, tp->t_mtx, hz);
1580 /* Bail out when the device slipped away. */
1584 /* Restart the system call when we may have been revoked. */
1585 if (tp->t_revokecnt != revokecnt)
1592 tty_flush(struct tty *tp, int flags)
1595 if (flags & FWRITE) {
1596 tp->t_flags &= ~TF_HIWAT_OUT;
1597 ttyoutq_flush(&tp->t_outq);
1598 tty_wakeup(tp, FWRITE);
1599 if (!tty_gone(tp)) {
1600 ttydevsw_outwakeup(tp);
1601 ttydevsw_pktnotify(tp, TIOCPKT_FLUSHWRITE);
1604 if (flags & FREAD) {
1605 tty_hiwat_in_unblock(tp);
1606 ttyinq_flush(&tp->t_inq);
1607 tty_wakeup(tp, FREAD);
1608 if (!tty_gone(tp)) {
1609 ttydevsw_inwakeup(tp);
1610 ttydevsw_pktnotify(tp, TIOCPKT_FLUSHREAD);
1616 tty_set_winsize(struct tty *tp, const struct winsize *wsz)
1619 if (memcmp(&tp->t_winsize, wsz, sizeof(*wsz)) == 0)
1621 tp->t_winsize = *wsz;
1622 tty_signal_pgrp(tp, SIGWINCH);
1626 tty_generic_ioctl(struct tty *tp, u_long cmd, void *data, int fflag,
1634 * The SER_* and TIOCM_* flags are the same, but one bit
1635 * shifted. I don't know why.
1638 ttydevsw_modem(tp, SER_DTR, 0);
1641 ttydevsw_modem(tp, 0, SER_DTR);
1644 int bits = *(int *)data;
1646 (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1,
1647 ((~bits) & (TIOCM_DTR | TIOCM_RTS)) >> 1);
1651 int bits = *(int *)data;
1652 ttydevsw_modem(tp, (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1, 0);
1656 int bits = *(int *)data;
1657 ttydevsw_modem(tp, 0, (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1);
1661 *(int *)data = TIOCM_LE + (ttydevsw_modem(tp, 0, 0) << 1);
1666 tp->t_flags |= TF_ASYNC;
1668 tp->t_flags &= ~TF_ASYNC;
1671 /* This device supports non-blocking operation. */
1674 *(int *)data = ttyinq_bytescanonicalized(&tp->t_inq);
1678 *(int *)data = ttyoutq_bytesused(&tp->t_outq);
1681 if (tp->t_session != NULL && !tty_is_ctty(tp, td->td_proc))
1682 /* Not allowed to set ownership. */
1685 /* Temporarily unlock the TTY to set ownership. */
1687 error = fsetown(*(int *)data, &tp->t_sigio);
1691 if (tp->t_session != NULL && !tty_is_ctty(tp, td->td_proc))
1692 /* Not allowed to set ownership. */
1695 /* Get ownership. */
1696 *(int *)data = fgetown(&tp->t_sigio);
1699 /* Obtain terminal flags through tcgetattr(). */
1700 *(struct termios*)data = tp->t_termios;
1705 struct termios *t = data;
1708 * Who makes up these funny rules? According to POSIX,
1709 * input baud rate is set equal to the output baud rate
1712 if (t->c_ispeed == 0)
1713 t->c_ispeed = t->c_ospeed;
1715 /* Discard any unsupported bits. */
1716 t->c_iflag &= TTYSUP_IFLAG;
1717 t->c_oflag &= TTYSUP_OFLAG;
1718 t->c_lflag &= TTYSUP_LFLAG;
1719 t->c_cflag &= TTYSUP_CFLAG;
1721 /* Set terminal flags through tcsetattr(). */
1722 if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
1723 error = tty_drain(tp, 0);
1726 if (cmd == TIOCSETAF)
1727 tty_flush(tp, FREAD);
1731 * Only call param() when the flags really change.
1733 if ((t->c_cflag & CIGNORE) == 0 &&
1734 (tp->t_termios.c_cflag != t->c_cflag ||
1735 ((tp->t_termios.c_iflag ^ t->c_iflag) &
1736 (IXON|IXOFF|IXANY)) ||
1737 tp->t_termios.c_ispeed != t->c_ispeed ||
1738 tp->t_termios.c_ospeed != t->c_ospeed)) {
1739 error = ttydevsw_param(tp, t);
1745 tp->t_termios.c_cflag = t->c_cflag & ~CIGNORE;
1746 tp->t_termios.c_ispeed = t->c_ispeed;
1747 tp->t_termios.c_ospeed = t->c_ospeed;
1749 /* Baud rate has changed - update watermarks. */
1750 error = tty_watermarks(tp);
1755 /* Copy new non-device driver parameters. */
1756 tp->t_termios.c_iflag = t->c_iflag;
1757 tp->t_termios.c_oflag = t->c_oflag;
1758 tp->t_termios.c_lflag = t->c_lflag;
1759 memcpy(&tp->t_termios.c_cc, t->c_cc, sizeof t->c_cc);
1761 ttydisc_optimize(tp);
1763 if ((t->c_lflag & ICANON) == 0) {
1765 * When in non-canonical mode, wake up all
1766 * readers. Canonicalize any partial input. VMIN
1767 * and VTIME could also be adjusted.
1769 ttyinq_canonicalize(&tp->t_inq);
1770 tty_wakeup(tp, FREAD);
1774 * For packet mode: notify the PTY consumer that VSTOP
1775 * and VSTART may have been changed.
1777 if (tp->t_termios.c_iflag & IXON &&
1778 tp->t_termios.c_cc[VSTOP] == CTRL('S') &&
1779 tp->t_termios.c_cc[VSTART] == CTRL('Q'))
1780 ttydevsw_pktnotify(tp, TIOCPKT_DOSTOP);
1782 ttydevsw_pktnotify(tp, TIOCPKT_NOSTOP);
1786 /* For compatibility - we only support TTYDISC. */
1787 *(int *)data = TTYDISC;
1790 if (!tty_is_ctty(tp, td->td_proc))
1793 if (tp->t_pgrp != NULL)
1794 *(int *)data = tp->t_pgrp->pg_id;
1796 *(int *)data = NO_PID;
1799 if (!tty_is_ctty(tp, td->td_proc))
1802 MPASS(tp->t_session);
1803 *(int *)data = tp->t_session->s_sid;
1806 return (tty_drop_ctty(tp, td->td_proc));
1808 struct proc *p = td->td_proc;
1810 /* XXX: This looks awful. */
1812 sx_xlock(&proctree_lock);
1815 if (!SESS_LEADER(p)) {
1816 /* Only the session leader may do this. */
1817 sx_xunlock(&proctree_lock);
1821 if (tp->t_session != NULL && tp->t_session == p->p_session) {
1822 /* This is already our controlling TTY. */
1823 sx_xunlock(&proctree_lock);
1827 if (p->p_session->s_ttyp != NULL ||
1828 (tp->t_session != NULL && tp->t_session->s_ttyvp != NULL &&
1829 tp->t_session->s_ttyvp->v_type != VBAD)) {
1831 * There is already a relation between a TTY and
1832 * a session, or the caller is not the session
1835 * Allow the TTY to be stolen when the vnode is
1836 * invalid, but the reference to the TTY is
1837 * still active. This allows immediate reuse of
1838 * TTYs of which the session leader has been
1839 * killed or the TTY revoked.
1841 sx_xunlock(&proctree_lock);
1845 /* Connect the session to the TTY. */
1846 tp->t_session = p->p_session;
1847 tp->t_session->s_ttyp = tp;
1850 /* Assign foreground process group. */
1851 tp->t_pgrp = p->p_pgrp;
1853 p->p_flag |= P_CONTROLT;
1856 sx_xunlock(&proctree_lock);
1863 * XXX: Temporarily unlock the TTY to locate the process
1864 * group. This code would be lot nicer if we would ever
1865 * decompose proctree_lock.
1868 sx_slock(&proctree_lock);
1869 pg = pgfind(*(int *)data);
1872 if (pg == NULL || pg->pg_session != td->td_proc->p_session) {
1873 sx_sunlock(&proctree_lock);
1880 * Determine if this TTY is the controlling TTY after
1881 * relocking the TTY.
1883 if (!tty_is_ctty(tp, td->td_proc)) {
1884 sx_sunlock(&proctree_lock);
1888 sx_sunlock(&proctree_lock);
1890 /* Wake up the background process groups. */
1891 cv_broadcast(&tp->t_bgwait);
1895 int flags = *(int *)data;
1898 flags = (FREAD|FWRITE);
1900 flags &= (FREAD|FWRITE);
1901 tty_flush(tp, flags);
1905 /* Drain TTY output. */
1906 return tty_drain(tp, 0);
1907 case TIOCGDRAINWAIT:
1908 *(int *)data = tp->t_drainwait;
1910 case TIOCSDRAINWAIT:
1911 error = priv_check(td, PRIV_TTY_DRAINWAIT);
1913 tp->t_drainwait = *(int *)data;
1916 /* Set terminal as console TTY. */
1918 error = priv_check(td, PRIV_TTY_CONSOLE);
1923 * XXX: constty should really need to be locked!
1924 * XXX: allow disconnected constty's to be stolen!
1929 if (constty != NULL)
1935 } else if (constty == tp) {
1940 /* Obtain window size. */
1941 *(struct winsize*)data = tp->t_winsize;
1944 /* Set window size. */
1945 tty_set_winsize(tp, data);
1948 tp->t_flags |= TF_EXCLUDE;
1951 tp->t_flags &= ~TF_EXCLUDE;
1954 tp->t_flags |= TF_STOPPED;
1955 ttydevsw_pktnotify(tp, TIOCPKT_STOP);
1958 tp->t_flags &= ~TF_STOPPED;
1959 tp->t_termios.c_lflag &= ~FLUSHO;
1960 ttydevsw_outwakeup(tp);
1961 ttydevsw_pktnotify(tp, TIOCPKT_START);
1967 if ((fflag & FREAD) == 0 && priv_check(td, PRIV_TTY_STI))
1969 if (!tty_is_ctty(tp, td->td_proc) &&
1970 priv_check(td, PRIV_TTY_STI))
1972 ttydisc_rint(tp, *(char *)data, 0);
1973 ttydisc_rint_done(tp);
1978 return tty_ioctl_compat(tp, cmd, data, fflag, td);
1979 #else /* !COMPAT_43TTY */
1981 #endif /* COMPAT_43TTY */
1985 tty_ioctl(struct tty *tp, u_long cmd, void *data, int fflag, struct thread *td)
1989 tty_assert_locked(tp);
1994 error = ttydevsw_ioctl(tp, cmd, data, td);
1995 if (error == ENOIOCTL)
1996 error = tty_generic_ioctl(tp, cmd, data, fflag, td);
2002 tty_udev(struct tty *tp)
2006 return (dev2udev(tp->t_dev));
2012 tty_checkoutq(struct tty *tp)
2015 /* 256 bytes should be enough to print a log message. */
2016 return (ttyoutq_bytesleft(&tp->t_outq) >= 256);
2020 tty_hiwat_in_block(struct tty *tp)
2023 if ((tp->t_flags & TF_HIWAT_IN) == 0 &&
2024 tp->t_termios.c_iflag & IXOFF &&
2025 tp->t_termios.c_cc[VSTOP] != _POSIX_VDISABLE) {
2027 * Input flow control. Only enter the high watermark when we
2028 * can successfully store the VSTOP character.
2030 if (ttyoutq_write_nofrag(&tp->t_outq,
2031 &tp->t_termios.c_cc[VSTOP], 1) == 0)
2032 tp->t_flags |= TF_HIWAT_IN;
2034 /* No input flow control. */
2035 tp->t_flags |= TF_HIWAT_IN;
2040 tty_hiwat_in_unblock(struct tty *tp)
2043 if (tp->t_flags & TF_HIWAT_IN &&
2044 tp->t_termios.c_iflag & IXOFF &&
2045 tp->t_termios.c_cc[VSTART] != _POSIX_VDISABLE) {
2047 * Input flow control. Only leave the high watermark when we
2048 * can successfully store the VSTART character.
2050 if (ttyoutq_write_nofrag(&tp->t_outq,
2051 &tp->t_termios.c_cc[VSTART], 1) == 0)
2052 tp->t_flags &= ~TF_HIWAT_IN;
2054 /* No input flow control. */
2055 tp->t_flags &= ~TF_HIWAT_IN;
2059 ttydevsw_inwakeup(tp);
2063 * TTY hooks interface.
2067 ttyhook_defrint(struct tty *tp, char c, int flags)
2070 if (ttyhook_rint_bypass(tp, &c, 1) != 1)
2077 ttyhook_register(struct tty **rtp, struct proc *p, int fd, struct ttyhook *th,
2084 struct filedesc *fdp;
2085 cap_rights_t rights;
2088 /* Validate the file descriptor. */
2090 error = fget_unlocked(fdp, fd, cap_rights_init_one(&rights, CAP_TTYHOOK),
2094 if (fp->f_ops == &badfileops) {
2100 * Make sure the vnode is bound to a character device.
2101 * Unlocked check for the vnode type is ok there, because we
2102 * only shall prevent calling devvn_refthread on the file that
2103 * never has been opened over a character device.
2105 if (fp->f_type != DTYPE_VNODE || fp->f_vnode->v_type != VCHR) {
2110 /* Make sure it is a TTY. */
2111 cdp = devvn_refthread(fp->f_vnode, &dev, &ref);
2116 if (dev != fp->f_data) {
2120 if (cdp != &ttydev_cdevsw) {
2126 /* Try to attach the hook to the TTY. */
2129 MPASS((tp->t_hook == NULL) == ((tp->t_flags & TF_HOOK) == 0));
2130 if (tp->t_flags & TF_HOOK)
2133 tp->t_flags |= TF_HOOK;
2135 tp->t_hooksoftc = softc;
2139 /* Maybe we can switch into bypass mode now. */
2140 ttydisc_optimize(tp);
2142 /* Silently convert rint() calls to rint_bypass() when possible. */
2143 if (!ttyhook_hashook(tp, rint) && ttyhook_hashook(tp, rint_bypass))
2144 th->th_rint = ttyhook_defrint;
2146 done3: tty_unlock(tp);
2147 done2: dev_relthread(dev, ref);
2148 done1: fdrop(fp, curthread);
2153 ttyhook_unregister(struct tty *tp)
2156 tty_assert_locked(tp);
2157 MPASS(tp->t_flags & TF_HOOK);
2159 /* Disconnect the hook. */
2160 tp->t_flags &= ~TF_HOOK;
2163 /* Maybe we need to leave bypass mode. */
2164 ttydisc_optimize(tp);
2166 /* Maybe deallocate the TTY as well. */
2171 * /dev/console handling.
2175 ttyconsdev_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
2179 /* System has no console device. */
2180 if (dev_console_filename == NULL)
2183 /* Look up corresponding TTY by device name. */
2184 sx_slock(&tty_list_sx);
2185 TAILQ_FOREACH(tp, &tty_list, t_list) {
2186 if (strcmp(dev_console_filename, tty_devname(tp)) == 0) {
2187 dev_console->si_drv1 = tp;
2191 sx_sunlock(&tty_list_sx);
2193 /* System console has no TTY associated. */
2194 if (dev_console->si_drv1 == NULL)
2197 return (ttydev_open(dev, oflags, devtype, td));
2201 ttyconsdev_write(struct cdev *dev, struct uio *uio, int ioflag)
2206 return (ttydev_write(dev, uio, ioflag));
2210 * /dev/console is a little different than normal TTY's. When opened,
2211 * it determines which TTY to use. When data gets written to it, it
2212 * will be logged in the kernel message buffer.
2214 static struct cdevsw ttyconsdev_cdevsw = {
2215 .d_version = D_VERSION,
2216 .d_open = ttyconsdev_open,
2217 .d_close = ttydev_close,
2218 .d_read = ttydev_read,
2219 .d_write = ttyconsdev_write,
2220 .d_ioctl = ttydev_ioctl,
2221 .d_kqfilter = ttydev_kqfilter,
2222 .d_poll = ttydev_poll,
2223 .d_mmap = ttydev_mmap,
2224 .d_name = "ttyconsdev",
2229 ttyconsdev_init(void *unused __unused)
2232 dev_console = make_dev_credf(MAKEDEV_ETERNAL, &ttyconsdev_cdevsw, 0,
2233 NULL, UID_ROOT, GID_WHEEL, 0600, "console");
2236 SYSINIT(tty, SI_SUB_DRIVERS, SI_ORDER_FIRST, ttyconsdev_init, NULL);
2239 ttyconsdev_select(const char *name)
2242 dev_console_filename = name;
2246 * Debugging routines.
2249 #include "opt_ddb.h"
2251 #include <ddb/ddb.h>
2252 #include <ddb/db_sym.h>
2254 static const struct {
2259 { TF_NOPREFIX, 'N' },
2261 { TF_INITLOCK, 'I' },
2262 { TF_CALLOUT, 'C' },
2264 /* Keep these together -> 'Oi' and 'Oo'. */
2266 { TF_OPENED_IN, 'i' },
2267 { TF_OPENED_OUT, 'o' },
2268 { TF_OPENED_CONS, 'c' },
2271 { TF_OPENCLOSE, 'B' },
2273 { TF_LITERAL, 'L' },
2275 /* Keep these together -> 'Hi' and 'Ho'. */
2277 { TF_HIWAT_IN, 'i' },
2278 { TF_HIWAT_OUT, 'o' },
2280 { TF_STOPPED, 'S' },
2281 { TF_EXCLUDE, 'X' },
2286 /* Keep these together -> 'bi' and 'bo'. */
2288 { TF_BUSY_IN, 'i' },
2289 { TF_BUSY_OUT, 'o' },
2294 #define TTY_FLAG_BITS \
2295 "\20\1NOPREFIX\2INITLOCK\3CALLOUT\4OPENED_IN" \
2296 "\5OPENED_OUT\6OPENED_CONS\7GONE\10OPENCLOSE" \
2297 "\11ASYNC\12LITERAL\13HIWAT_IN\14HIWAT_OUT" \
2298 "\15STOPPED\16EXCLUDE\17BYPASS\20ZOMBIE" \
2299 "\21HOOK\22BUSY_IN\23BUSY_OUT"
2301 #define DB_PRINTSYM(name, addr) \
2302 db_printf("%s " #name ": ", sep); \
2303 db_printsym((db_addr_t) addr, DB_STGY_ANY); \
2307 _db_show_devsw(const char *sep, const struct ttydevsw *tsw)
2310 db_printf("%sdevsw: ", sep);
2311 db_printsym((db_addr_t)tsw, DB_STGY_ANY);
2312 db_printf(" (%p)\n", tsw);
2313 DB_PRINTSYM(open, tsw->tsw_open);
2314 DB_PRINTSYM(close, tsw->tsw_close);
2315 DB_PRINTSYM(outwakeup, tsw->tsw_outwakeup);
2316 DB_PRINTSYM(inwakeup, tsw->tsw_inwakeup);
2317 DB_PRINTSYM(ioctl, tsw->tsw_ioctl);
2318 DB_PRINTSYM(param, tsw->tsw_param);
2319 DB_PRINTSYM(modem, tsw->tsw_modem);
2320 DB_PRINTSYM(mmap, tsw->tsw_mmap);
2321 DB_PRINTSYM(pktnotify, tsw->tsw_pktnotify);
2322 DB_PRINTSYM(free, tsw->tsw_free);
2326 _db_show_hooks(const char *sep, const struct ttyhook *th)
2329 db_printf("%shook: ", sep);
2330 db_printsym((db_addr_t)th, DB_STGY_ANY);
2331 db_printf(" (%p)\n", th);
2334 DB_PRINTSYM(rint, th->th_rint);
2335 DB_PRINTSYM(rint_bypass, th->th_rint_bypass);
2336 DB_PRINTSYM(rint_done, th->th_rint_done);
2337 DB_PRINTSYM(rint_poll, th->th_rint_poll);
2338 DB_PRINTSYM(getc_inject, th->th_getc_inject);
2339 DB_PRINTSYM(getc_capture, th->th_getc_capture);
2340 DB_PRINTSYM(getc_poll, th->th_getc_poll);
2341 DB_PRINTSYM(close, th->th_close);
2345 _db_show_termios(const char *name, const struct termios *t)
2348 db_printf("%s: iflag 0x%x oflag 0x%x cflag 0x%x "
2349 "lflag 0x%x ispeed %u ospeed %u\n", name,
2350 t->c_iflag, t->c_oflag, t->c_cflag, t->c_lflag,
2351 t->c_ispeed, t->c_ospeed);
2354 /* DDB command to show TTY statistics. */
2355 DB_SHOW_COMMAND(tty, db_show_tty)
2360 db_printf("usage: show tty <addr>\n");
2363 tp = (struct tty *)addr;
2365 db_printf("%p: %s\n", tp, tty_devname(tp));
2366 db_printf("\tmtx: %p\n", tp->t_mtx);
2367 db_printf("\tflags: 0x%b\n", tp->t_flags, TTY_FLAG_BITS);
2368 db_printf("\trevokecnt: %u\n", tp->t_revokecnt);
2370 /* Buffering mechanisms. */
2371 db_printf("\tinq: %p begin %u linestart %u reprint %u end %u "
2372 "nblocks %u quota %u\n", &tp->t_inq, tp->t_inq.ti_begin,
2373 tp->t_inq.ti_linestart, tp->t_inq.ti_reprint, tp->t_inq.ti_end,
2374 tp->t_inq.ti_nblocks, tp->t_inq.ti_quota);
2375 db_printf("\toutq: %p begin %u end %u nblocks %u quota %u\n",
2376 &tp->t_outq, tp->t_outq.to_begin, tp->t_outq.to_end,
2377 tp->t_outq.to_nblocks, tp->t_outq.to_quota);
2378 db_printf("\tinlow: %zu\n", tp->t_inlow);
2379 db_printf("\toutlow: %zu\n", tp->t_outlow);
2380 _db_show_termios("\ttermios", &tp->t_termios);
2381 db_printf("\twinsize: row %u col %u xpixel %u ypixel %u\n",
2382 tp->t_winsize.ws_row, tp->t_winsize.ws_col,
2383 tp->t_winsize.ws_xpixel, tp->t_winsize.ws_ypixel);
2384 db_printf("\tcolumn: %u\n", tp->t_column);
2385 db_printf("\twritepos: %u\n", tp->t_writepos);
2386 db_printf("\tcompatflags: 0x%x\n", tp->t_compatflags);
2388 /* Init/lock-state devices. */
2389 _db_show_termios("\ttermios_init_in", &tp->t_termios_init_in);
2390 _db_show_termios("\ttermios_init_out", &tp->t_termios_init_out);
2391 _db_show_termios("\ttermios_lock_in", &tp->t_termios_lock_in);
2392 _db_show_termios("\ttermios_lock_out", &tp->t_termios_lock_out);
2395 _db_show_devsw("\t", tp->t_devsw);
2396 _db_show_hooks("\t", tp->t_hook);
2399 db_printf("\tpgrp: %p gid %d\n", tp->t_pgrp,
2400 tp->t_pgrp ? tp->t_pgrp->pg_id : 0);
2401 db_printf("\tsession: %p", tp->t_session);
2402 if (tp->t_session != NULL)
2403 db_printf(" count %u leader %p tty %p sid %d login %s",
2404 tp->t_session->s_count, tp->t_session->s_leader,
2405 tp->t_session->s_ttyp, tp->t_session->s_sid,
2406 tp->t_session->s_login);
2408 db_printf("\tsessioncnt: %u\n", tp->t_sessioncnt);
2409 db_printf("\tdevswsoftc: %p\n", tp->t_devswsoftc);
2410 db_printf("\thooksoftc: %p\n", tp->t_hooksoftc);
2411 db_printf("\tdev: %p\n", tp->t_dev);
2414 /* DDB command to list TTYs. */
2415 DB_SHOW_ALL_COMMAND(ttys, db_show_all_ttys)
2421 /* Make the output look like `pstat -t'. */
2423 #if defined(__LP64__)
2426 db_printf(" LINE INQ CAN LIN LOW OUTQ USE LOW "
2427 "COL SESS PGID STATE\n");
2429 TAILQ_FOREACH(tp, &tty_list, t_list) {
2430 isiz = tp->t_inq.ti_nblocks * TTYINQ_DATASIZE;
2431 osiz = tp->t_outq.to_nblocks * TTYOUTQ_DATASIZE;
2433 db_printf("%p %10s %5zu %4u %4u %4zu %5zu %4u %4zu %5u %5d "
2434 "%5d ", tp, tty_devname(tp), isiz,
2435 tp->t_inq.ti_linestart - tp->t_inq.ti_begin,
2436 tp->t_inq.ti_end - tp->t_inq.ti_linestart,
2437 isiz - tp->t_inlow, osiz,
2438 tp->t_outq.to_end - tp->t_outq.to_begin,
2439 osiz - tp->t_outlow, MIN(tp->t_column, 99999),
2440 tp->t_session ? tp->t_session->s_sid : 0,
2441 tp->t_pgrp ? tp->t_pgrp->pg_id : 0);
2444 for (i = j = 0; ttystates[i].flag; i++)
2445 if (tp->t_flags & ttystates[i].flag) {
2446 db_printf("%c", ttystates[i].val);