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"
37 #include <sys/param.h>
38 #include <sys/capsicum.h>
41 #include <sys/fcntl.h>
43 #include <sys/filedesc.h>
44 #include <sys/filio.h>
46 #include <sys/ioctl_compat.h>
47 #endif /* COMPAT_43TTY */
48 #include <sys/kernel.h>
49 #include <sys/limits.h>
50 #include <sys/malloc.h>
51 #include <sys/mount.h>
55 #include <sys/serial.h>
56 #include <sys/signal.h>
59 #include <sys/sysctl.h>
60 #include <sys/systm.h>
62 #include <sys/ttycom.h>
64 #include <sys/ttydefaults.h>
66 #include <sys/ucred.h>
67 #include <sys/vnode.h>
69 #include <machine/stdarg.h>
71 static MALLOC_DEFINE(M_TTY, "tty", "tty device");
73 static void tty_rel_free(struct tty *tp);
75 static TAILQ_HEAD(, tty) tty_list = TAILQ_HEAD_INITIALIZER(tty_list);
76 static struct sx tty_list_sx;
77 SX_SYSINIT(tty_list, &tty_list_sx, "tty list");
78 static unsigned int tty_list_count = 0;
80 /* Character device of /dev/console. */
81 static struct cdev *dev_console;
82 static const char *dev_console_filename;
85 * Flags that are supported and stored by this implementation.
87 #define TTYSUP_IFLAG (IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK|ISTRIP|\
88 INLCR|IGNCR|ICRNL|IXON|IXOFF|IXANY|IMAXBEL)
89 #define TTYSUP_OFLAG (OPOST|ONLCR|TAB3|ONOEOT|OCRNL|ONOCR|ONLRET)
90 #define TTYSUP_LFLAG (ECHOKE|ECHOE|ECHOK|ECHO|ECHONL|ECHOPRT|\
91 ECHOCTL|ISIG|ICANON|ALTWERASE|IEXTEN|TOSTOP|\
92 FLUSHO|NOKERNINFO|NOFLSH)
93 #define TTYSUP_CFLAG (CIGNORE|CSIZE|CSTOPB|CREAD|PARENB|PARODD|\
94 HUPCL|CLOCAL|CCTS_OFLOW|CRTS_IFLOW|CDTR_IFLOW|\
95 CDSR_OFLOW|CCAR_OFLOW)
97 #define TTY_CALLOUT(tp,d) (dev2unit(d) & TTYUNIT_CALLOUT)
99 static int tty_drainwait = 5 * 60;
100 SYSCTL_INT(_kern, OID_AUTO, tty_drainwait, CTLFLAG_RWTUN,
101 &tty_drainwait, 0, "Default output drain timeout in seconds");
104 * Set TTY buffer sizes.
107 #define TTYBUF_MAX 65536
110 * Allocate buffer space if necessary, and set low watermarks, based on speed.
111 * Note that the ttyxxxq_setsize() functions may drop and then reacquire the tty
112 * lock during memory allocation. They will return ENXIO if the tty disappears
116 tty_watermarks(struct tty *tp)
121 /* Provide an input buffer for 2 seconds of data. */
122 if (tp->t_termios.c_cflag & CREAD)
123 bs = MIN(tp->t_termios.c_ispeed / 5, TTYBUF_MAX);
124 error = ttyinq_setsize(&tp->t_inq, tp, bs);
128 /* Set low watermark at 10% (when 90% is available). */
129 tp->t_inlow = (ttyinq_getallocatedsize(&tp->t_inq) * 9) / 10;
131 /* Provide an output buffer for 2 seconds of data. */
132 bs = MIN(tp->t_termios.c_ospeed / 5, TTYBUF_MAX);
133 error = ttyoutq_setsize(&tp->t_outq, tp, bs);
137 /* Set low watermark at 10% (when 90% is available). */
138 tp->t_outlow = (ttyoutq_getallocatedsize(&tp->t_outq) * 9) / 10;
144 tty_drain(struct tty *tp, int leaving)
146 sbintime_t timeout_at;
150 if (ttyhook_hashook(tp, getc_inject))
151 /* buffer is inaccessible */
155 * For close(), use the recent historic timeout of "1 second without
156 * making progress". For tcdrain(), use t_drainwait as the timeout,
157 * with zero meaning "no timeout" which gives POSIX behavior.
160 timeout_at = getsbinuptime() + SBT_1S;
161 else if (tp->t_drainwait != 0)
162 timeout_at = getsbinuptime() + SBT_1S * tp->t_drainwait;
167 * Poll the output buffer and the hardware for completion, at 10 Hz.
168 * Polling is required for devices which are not able to signal an
169 * interrupt when the transmitter becomes idle (most USB serial devs).
170 * The unusual structure of this loop ensures we check for busy one more
171 * time after tty_timedwait() returns EWOULDBLOCK, so that success has
172 * higher priority than timeout if the IO completed in the last 100mS.
175 bytes = ttyoutq_bytesused(&tp->t_outq);
177 if (ttyoutq_bytesused(&tp->t_outq) == 0 && !ttydevsw_busy(tp))
181 ttydevsw_outwakeup(tp);
182 error = tty_timedwait(tp, &tp->t_outwait, hz / 10);
183 if (error != 0 && error != EWOULDBLOCK)
185 else if (timeout_at == 0 || getsbinuptime() < timeout_at)
187 else if (leaving && ttyoutq_bytesused(&tp->t_outq) < bytes) {
188 /* In close, making progress, grant an extra second. */
190 timeout_at += SBT_1S;
191 bytes = ttyoutq_bytesused(&tp->t_outq);
197 * Though ttydev_enter() and ttydev_leave() seem to be related, they
198 * don't have to be used together. ttydev_enter() is used by the cdev
199 * operations to prevent an actual operation from being processed when
200 * the TTY has been abandoned. ttydev_leave() is used by ttydev_open()
201 * and ttydev_close() to determine whether per-TTY data should be
206 ttydev_enter(struct tty *tp)
211 if (tty_gone(tp) || !tty_opened(tp)) {
212 /* Device is already gone. */
221 ttydev_leave(struct tty *tp)
224 tty_assert_locked(tp);
226 if (tty_opened(tp) || tp->t_flags & TF_OPENCLOSE) {
227 /* Device is still opened somewhere. */
232 tp->t_flags |= TF_OPENCLOSE;
234 /* Remove console TTY. */
238 /* Drain any output. */
244 /* Free i/o queues now since they might be large. */
245 ttyinq_free(&tp->t_inq);
247 ttyoutq_free(&tp->t_outq);
250 knlist_clear(&tp->t_inpoll.si_note, 1);
251 knlist_clear(&tp->t_outpoll.si_note, 1);
256 tp->t_flags &= ~TF_OPENCLOSE;
257 cv_broadcast(&tp->t_dcdwait);
262 * Operations that are exposed through the character device in /dev.
265 ttydev_open(struct cdev *dev, int oflags, int devtype __unused,
275 /* Device is already gone. */
281 * Block when other processes are currently opening or closing
284 while (tp->t_flags & TF_OPENCLOSE) {
285 error = tty_wait(tp, &tp->t_dcdwait);
291 tp->t_flags |= TF_OPENCLOSE;
294 * Make sure the "tty" and "cua" device cannot be opened at the
295 * same time. The console is a "tty" device.
297 if (TTY_CALLOUT(tp, dev)) {
298 if (tp->t_flags & (TF_OPENED_CONS | TF_OPENED_IN)) {
303 if (tp->t_flags & TF_OPENED_OUT) {
309 if (tp->t_flags & TF_EXCLUDE && priv_check(td, PRIV_TTY_EXCLUSIVE)) {
314 if (!tty_opened(tp)) {
315 /* Set proper termios flags. */
316 if (TTY_CALLOUT(tp, dev))
317 tp->t_termios = tp->t_termios_init_out;
319 tp->t_termios = tp->t_termios_init_in;
320 ttydevsw_param(tp, &tp->t_termios);
321 /* Prevent modem control on callout devices and /dev/console. */
322 if (TTY_CALLOUT(tp, dev) || dev == dev_console)
323 tp->t_termios.c_cflag |= CLOCAL;
325 ttydevsw_modem(tp, SER_DTR|SER_RTS, 0);
327 error = ttydevsw_open(tp);
332 error = tty_watermarks(tp);
337 /* Wait for Carrier Detect. */
338 if ((oflags & O_NONBLOCK) == 0 &&
339 (tp->t_termios.c_cflag & CLOCAL) == 0) {
340 while ((ttydevsw_modem(tp, 0, 0) & SER_DCD) == 0) {
341 error = tty_wait(tp, &tp->t_dcdwait);
347 if (dev == dev_console)
348 tp->t_flags |= TF_OPENED_CONS;
349 else if (TTY_CALLOUT(tp, dev))
350 tp->t_flags |= TF_OPENED_OUT;
352 tp->t_flags |= TF_OPENED_IN;
353 MPASS((tp->t_flags & (TF_OPENED_CONS | TF_OPENED_IN)) == 0 ||
354 (tp->t_flags & TF_OPENED_OUT) == 0);
356 done: tp->t_flags &= ~TF_OPENCLOSE;
357 cv_broadcast(&tp->t_dcdwait);
364 ttydev_close(struct cdev *dev, int fflag, int devtype __unused,
365 struct thread *td __unused)
367 struct tty *tp = dev->si_drv1;
372 * Don't actually close the device if it is being used as the
375 MPASS((tp->t_flags & (TF_OPENED_CONS | TF_OPENED_IN)) == 0 ||
376 (tp->t_flags & TF_OPENED_OUT) == 0);
377 if (dev == dev_console)
378 tp->t_flags &= ~TF_OPENED_CONS;
380 tp->t_flags &= ~(TF_OPENED_IN|TF_OPENED_OUT);
382 if (tp->t_flags & TF_OPENED) {
387 /* If revoking, flush output now to avoid draining it later. */
389 tty_flush(tp, FWRITE);
391 tp->t_flags &= ~TF_EXCLUDE;
393 /* Properly wake up threads that are stuck - revoke(). */
395 tty_wakeup(tp, FREAD|FWRITE);
396 cv_broadcast(&tp->t_bgwait);
397 cv_broadcast(&tp->t_dcdwait);
405 tty_is_ctty(struct tty *tp, struct proc *p)
408 tty_assert_locked(tp);
410 return (p->p_session == tp->t_session && p->p_flag & P_CONTROLT);
414 tty_wait_background(struct tty *tp, struct thread *td, int sig)
421 MPASS(sig == SIGTTIN || sig == SIGTTOU);
422 tty_assert_locked(tp);
431 * pg may no longer be our process group.
432 * Re-check after locking.
434 if (p->p_pgrp != pg) {
441 * The process should only sleep, when:
442 * - This terminal is the controlling terminal
443 * - Its process group is not the foreground process
445 * - The parent process isn't waiting for the child to
447 * - the signal to send to the process isn't masked
449 if (!tty_is_ctty(tp, p) || p->p_pgrp == tp->t_pgrp) {
450 /* Allow the action to happen. */
456 if (SIGISMEMBER(p->p_sigacts->ps_sigignore, sig) ||
457 SIGISMEMBER(td->td_sigmask, sig)) {
458 /* Only allow them in write()/ioctl(). */
461 return (sig == SIGTTOU ? 0 : EIO);
464 if ((p->p_flag & P_PPWAIT) != 0 || pg->pg_jobc == 0) {
465 /* Don't allow the action to happen. */
473 * Send the signal and sleep until we're the new
474 * foreground process group.
478 ksi.ksi_code = SI_KERNEL;
483 pgsignal(pg, ksi.ksi_signo, 1, &ksi);
486 error = tty_wait(tp, &tp->t_bgwait);
493 ttydev_read(struct cdev *dev, struct uio *uio, int ioflag)
495 struct tty *tp = dev->si_drv1;
498 error = ttydev_enter(tp);
501 error = ttydisc_read(tp, uio, ioflag);
505 * The read() call should not throw an error when the device is
506 * being destroyed. Silently convert it to an EOF.
508 done: if (error == ENXIO)
514 ttydev_write(struct cdev *dev, struct uio *uio, int ioflag)
516 struct tty *tp = dev->si_drv1;
519 error = ttydev_enter(tp);
523 if (tp->t_termios.c_lflag & TOSTOP) {
524 error = tty_wait_background(tp, curthread, SIGTTOU);
529 if (ioflag & IO_NDELAY && tp->t_flags & TF_BUSY_OUT) {
530 /* Allow non-blocking writes to bypass serialization. */
531 error = ttydisc_write(tp, uio, ioflag);
533 /* Serialize write() calls. */
534 while (tp->t_flags & TF_BUSY_OUT) {
535 error = tty_wait(tp, &tp->t_outserwait);
540 tp->t_flags |= TF_BUSY_OUT;
541 error = ttydisc_write(tp, uio, ioflag);
542 tp->t_flags &= ~TF_BUSY_OUT;
543 cv_signal(&tp->t_outserwait);
546 done: tty_unlock(tp);
551 ttydev_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
554 struct tty *tp = dev->si_drv1;
557 error = ttydev_enter(tp);
592 #endif /* COMPAT_43TTY */
594 * If the ioctl() causes the TTY to be modified, let it
595 * wait in the background.
597 error = tty_wait_background(tp, curthread, SIGTTOU);
602 if (cmd == TIOCSETA || cmd == TIOCSETAW || cmd == TIOCSETAF) {
603 struct termios *old = &tp->t_termios;
604 struct termios *new = (struct termios *)data;
605 struct termios *lock = TTY_CALLOUT(tp, dev) ?
606 &tp->t_termios_lock_out : &tp->t_termios_lock_in;
610 * Lock state devices. Just overwrite the values of the
611 * commands that are currently in use.
613 new->c_iflag = (old->c_iflag & lock->c_iflag) |
614 (new->c_iflag & ~lock->c_iflag);
615 new->c_oflag = (old->c_oflag & lock->c_oflag) |
616 (new->c_oflag & ~lock->c_oflag);
617 new->c_cflag = (old->c_cflag & lock->c_cflag) |
618 (new->c_cflag & ~lock->c_cflag);
619 new->c_lflag = (old->c_lflag & lock->c_lflag) |
620 (new->c_lflag & ~lock->c_lflag);
621 for (cc = 0; cc < NCCS; ++cc)
623 new->c_cc[cc] = old->c_cc[cc];
625 new->c_ispeed = old->c_ispeed;
627 new->c_ospeed = old->c_ospeed;
630 error = tty_ioctl(tp, cmd, data, fflag, td);
631 done: tty_unlock(tp);
637 ttydev_poll(struct cdev *dev, int events, struct thread *td)
639 struct tty *tp = dev->si_drv1;
640 int error, revents = 0;
642 error = ttydev_enter(tp);
644 return ((events & (POLLIN|POLLRDNORM)) | POLLHUP);
646 if (events & (POLLIN|POLLRDNORM)) {
647 /* See if we can read something. */
648 if (ttydisc_read_poll(tp) > 0)
649 revents |= events & (POLLIN|POLLRDNORM);
652 if (tp->t_flags & TF_ZOMBIE) {
653 /* Hangup flag on zombie state. */
655 } else if (events & (POLLOUT|POLLWRNORM)) {
656 /* See if we can write something. */
657 if (ttydisc_write_poll(tp) > 0)
658 revents |= events & (POLLOUT|POLLWRNORM);
662 if (events & (POLLIN|POLLRDNORM))
663 selrecord(td, &tp->t_inpoll);
664 if (events & (POLLOUT|POLLWRNORM))
665 selrecord(td, &tp->t_outpoll);
674 ttydev_mmap(struct cdev *dev, vm_ooffset_t offset, vm_paddr_t *paddr,
675 int nprot, vm_memattr_t *memattr)
677 struct tty *tp = dev->si_drv1;
680 /* Handle mmap() through the driver. */
682 error = ttydev_enter(tp);
685 error = ttydevsw_mmap(tp, offset, paddr, nprot, memattr);
696 tty_kqops_read_detach(struct knote *kn)
698 struct tty *tp = kn->kn_hook;
700 knlist_remove(&tp->t_inpoll.si_note, kn, 0);
704 tty_kqops_read_event(struct knote *kn, long hint __unused)
706 struct tty *tp = kn->kn_hook;
708 tty_assert_locked(tp);
710 if (tty_gone(tp) || tp->t_flags & TF_ZOMBIE) {
711 kn->kn_flags |= EV_EOF;
714 kn->kn_data = ttydisc_read_poll(tp);
715 return (kn->kn_data > 0);
720 tty_kqops_write_detach(struct knote *kn)
722 struct tty *tp = kn->kn_hook;
724 knlist_remove(&tp->t_outpoll.si_note, kn, 0);
728 tty_kqops_write_event(struct knote *kn, long hint __unused)
730 struct tty *tp = kn->kn_hook;
732 tty_assert_locked(tp);
735 kn->kn_flags |= EV_EOF;
738 kn->kn_data = ttydisc_write_poll(tp);
739 return (kn->kn_data > 0);
743 static struct filterops tty_kqops_read = {
745 .f_detach = tty_kqops_read_detach,
746 .f_event = tty_kqops_read_event,
749 static struct filterops tty_kqops_write = {
751 .f_detach = tty_kqops_write_detach,
752 .f_event = tty_kqops_write_event,
756 ttydev_kqfilter(struct cdev *dev, struct knote *kn)
758 struct tty *tp = dev->si_drv1;
761 error = ttydev_enter(tp);
765 switch (kn->kn_filter) {
768 kn->kn_fop = &tty_kqops_read;
769 knlist_add(&tp->t_inpoll.si_note, kn, 1);
773 kn->kn_fop = &tty_kqops_write;
774 knlist_add(&tp->t_outpoll.si_note, kn, 1);
785 static struct cdevsw ttydev_cdevsw = {
786 .d_version = D_VERSION,
787 .d_open = ttydev_open,
788 .d_close = ttydev_close,
789 .d_read = ttydev_read,
790 .d_write = ttydev_write,
791 .d_ioctl = ttydev_ioctl,
792 .d_kqfilter = ttydev_kqfilter,
793 .d_poll = ttydev_poll,
794 .d_mmap = ttydev_mmap,
800 * Init/lock-state devices
804 ttyil_open(struct cdev *dev, int oflags __unused, int devtype __unused,
821 ttyil_close(struct cdev *dev __unused, int flag __unused, int mode __unused,
822 struct thread *td __unused)
829 ttyil_rdwr(struct cdev *dev __unused, struct uio *uio __unused,
837 ttyil_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
840 struct tty *tp = dev->si_drv1;
849 error = ttydevsw_cioctl(tp, dev2unit(dev), cmd, data, td);
850 if (error != ENOIOCTL)
856 /* Obtain terminal flags through tcgetattr(). */
857 *(struct termios*)data = *(struct termios*)dev->si_drv2;
860 /* Set terminal flags through tcsetattr(). */
861 error = priv_check(td, PRIV_TTY_SETA);
864 *(struct termios*)dev->si_drv2 = *(struct termios*)data;
867 *(int *)data = TTYDISC;
870 bzero(data, sizeof(struct winsize));
876 done: tty_unlock(tp);
880 static struct cdevsw ttyil_cdevsw = {
881 .d_version = D_VERSION,
882 .d_open = ttyil_open,
883 .d_close = ttyil_close,
884 .d_read = ttyil_rdwr,
885 .d_write = ttyil_rdwr,
886 .d_ioctl = ttyil_ioctl,
892 tty_init_termios(struct tty *tp)
894 struct termios *t = &tp->t_termios_init_in;
896 t->c_cflag = TTYDEF_CFLAG;
897 t->c_iflag = TTYDEF_IFLAG;
898 t->c_lflag = TTYDEF_LFLAG;
899 t->c_oflag = TTYDEF_OFLAG;
900 t->c_ispeed = TTYDEF_SPEED;
901 t->c_ospeed = TTYDEF_SPEED;
902 memcpy(&t->c_cc, ttydefchars, sizeof ttydefchars);
904 tp->t_termios_init_out = *t;
908 tty_init_console(struct tty *tp, speed_t s)
910 struct termios *ti = &tp->t_termios_init_in;
911 struct termios *to = &tp->t_termios_init_out;
914 ti->c_ispeed = ti->c_ospeed = s;
915 to->c_ispeed = to->c_ospeed = s;
918 ti->c_cflag |= CLOCAL;
919 to->c_cflag |= CLOCAL;
923 * Standard device routine implementations, mostly meant for
924 * pseudo-terminal device drivers. When a driver creates a new terminal
925 * device class, missing routines are patched.
929 ttydevsw_defopen(struct tty *tp __unused)
936 ttydevsw_defclose(struct tty *tp __unused)
942 ttydevsw_defoutwakeup(struct tty *tp __unused)
945 panic("Terminal device has output, while not implemented");
949 ttydevsw_definwakeup(struct tty *tp __unused)
955 ttydevsw_defioctl(struct tty *tp __unused, u_long cmd __unused,
956 caddr_t data __unused, struct thread *td __unused)
963 ttydevsw_defcioctl(struct tty *tp __unused, int unit __unused,
964 u_long cmd __unused, caddr_t data __unused, struct thread *td __unused)
971 ttydevsw_defparam(struct tty *tp __unused, struct termios *t)
975 * Allow the baud rate to be adjusted for pseudo-devices, but at
976 * least restrict it to 115200 to prevent excessive buffer
977 * usage. Also disallow 0, to prevent foot shooting.
979 if (t->c_ispeed < B50)
981 else if (t->c_ispeed > B115200)
982 t->c_ispeed = B115200;
983 if (t->c_ospeed < B50)
985 else if (t->c_ospeed > B115200)
986 t->c_ospeed = B115200;
993 ttydevsw_defmodem(struct tty *tp __unused, int sigon __unused,
997 /* Simulate a carrier to make the TTY layer happy. */
1002 ttydevsw_defmmap(struct tty *tp __unused, vm_ooffset_t offset __unused,
1003 vm_paddr_t *paddr __unused, int nprot __unused,
1004 vm_memattr_t *memattr __unused)
1011 ttydevsw_defpktnotify(struct tty *tp __unused, char event __unused)
1017 ttydevsw_deffree(void *softc __unused)
1020 panic("Terminal device freed without a free-handler");
1024 ttydevsw_defbusy(struct tty *tp __unused)
1031 * TTY allocation and deallocation. TTY devices can be deallocated when
1032 * the driver doesn't use it anymore, when the TTY isn't a session's
1033 * controlling TTY and when the device node isn't opened through devfs.
1037 tty_alloc(struct ttydevsw *tsw, void *sc)
1040 return (tty_alloc_mutex(tsw, sc, NULL));
1044 tty_alloc_mutex(struct ttydevsw *tsw, void *sc, struct mtx *mutex)
1048 /* Make sure the driver defines all routines. */
1049 #define PATCH_FUNC(x) do { \
1050 if (tsw->tsw_ ## x == NULL) \
1051 tsw->tsw_ ## x = ttydevsw_def ## x; \
1055 PATCH_FUNC(outwakeup);
1056 PATCH_FUNC(inwakeup);
1062 PATCH_FUNC(pktnotify);
1067 tp = malloc(sizeof(struct tty), M_TTY, M_WAITOK|M_ZERO);
1069 tp->t_devswsoftc = sc;
1070 tp->t_flags = tsw->tsw_flags;
1071 tp->t_drainwait = tty_drainwait;
1073 tty_init_termios(tp);
1075 cv_init(&tp->t_inwait, "ttyin");
1076 cv_init(&tp->t_outwait, "ttyout");
1077 cv_init(&tp->t_outserwait, "ttyosr");
1078 cv_init(&tp->t_bgwait, "ttybg");
1079 cv_init(&tp->t_dcdwait, "ttydcd");
1081 /* Allow drivers to use a custom mutex to lock the TTY. */
1082 if (mutex != NULL) {
1085 tp->t_mtx = &tp->t_mtxobj;
1086 mtx_init(&tp->t_mtxobj, "ttymtx", NULL, MTX_DEF);
1089 knlist_init_mtx(&tp->t_inpoll.si_note, tp->t_mtx);
1090 knlist_init_mtx(&tp->t_outpoll.si_note, tp->t_mtx);
1096 tty_dealloc(void *arg)
1098 struct tty *tp = arg;
1101 * ttyydev_leave() usually frees the i/o queues earlier, but it is
1102 * not always called between queue allocation and here. The queues
1103 * may be allocated by ioctls on a pty control device without the
1104 * corresponding pty slave device ever being open, or after it is
1107 ttyinq_free(&tp->t_inq);
1108 ttyoutq_free(&tp->t_outq);
1109 seldrain(&tp->t_inpoll);
1110 seldrain(&tp->t_outpoll);
1111 knlist_destroy(&tp->t_inpoll.si_note);
1112 knlist_destroy(&tp->t_outpoll.si_note);
1114 cv_destroy(&tp->t_inwait);
1115 cv_destroy(&tp->t_outwait);
1116 cv_destroy(&tp->t_bgwait);
1117 cv_destroy(&tp->t_dcdwait);
1118 cv_destroy(&tp->t_outserwait);
1120 if (tp->t_mtx == &tp->t_mtxobj)
1121 mtx_destroy(&tp->t_mtxobj);
1127 tty_rel_free(struct tty *tp)
1131 tty_assert_locked(tp);
1133 #define TF_ACTIVITY (TF_GONE|TF_OPENED|TF_HOOK|TF_OPENCLOSE)
1134 if (tp->t_sessioncnt != 0 || (tp->t_flags & TF_ACTIVITY) != TF_GONE) {
1135 /* TTY is still in use. */
1140 /* Stop asynchronous I/O. */
1141 funsetown(&tp->t_sigio);
1143 /* TTY can be deallocated. */
1149 sx_xlock(&tty_list_sx);
1150 TAILQ_REMOVE(&tty_list, tp, t_list);
1152 sx_xunlock(&tty_list_sx);
1153 destroy_dev_sched_cb(dev, tty_dealloc, tp);
1158 tty_rel_pgrp(struct tty *tp, struct pgrp *pg)
1161 MPASS(tp->t_sessioncnt > 0);
1162 tty_assert_locked(tp);
1164 if (tp->t_pgrp == pg)
1171 tty_rel_sess(struct tty *tp, struct session *sess)
1174 MPASS(tp->t_sessioncnt > 0);
1176 /* Current session has left. */
1177 if (tp->t_session == sess) {
1178 tp->t_session = NULL;
1179 MPASS(tp->t_pgrp == NULL);
1186 tty_rel_gone(struct tty *tp)
1189 tty_assert_locked(tp);
1190 MPASS(!tty_gone(tp));
1192 /* Simulate carrier removal. */
1193 ttydisc_modem(tp, 0);
1195 /* Wake up all blocked threads. */
1196 tty_wakeup(tp, FREAD|FWRITE);
1197 cv_broadcast(&tp->t_bgwait);
1198 cv_broadcast(&tp->t_dcdwait);
1200 tp->t_flags |= TF_GONE;
1205 tty_drop_ctty(struct tty *tp, struct proc *p)
1207 struct session *session;
1211 * This looks terrible, but it's generally safe as long as the tty
1212 * hasn't gone away while we had the lock dropped. All of our sanity
1213 * checking that this operation is OK happens after we've picked it back
1214 * up, so other state changes are generally not fatal and the potential
1215 * for this particular operation to happen out-of-order in a
1216 * multithreaded scenario is likely a non-issue.
1219 sx_xlock(&proctree_lock);
1222 sx_xunlock(&proctree_lock);
1227 * If the session doesn't have a controlling TTY, or if we weren't
1228 * invoked on the controlling TTY, we'll return ENOIOCTL as we've
1229 * historically done.
1231 session = p->p_session;
1232 if (session->s_ttyp == NULL || session->s_ttyp != tp) {
1233 sx_xunlock(&proctree_lock);
1237 if (!SESS_LEADER(p)) {
1238 sx_xunlock(&proctree_lock);
1244 vp = session->s_ttyvp;
1245 session->s_ttyp = NULL;
1246 session->s_ttyvp = NULL;
1247 session->s_ttydp = NULL;
1248 SESS_UNLOCK(session);
1251 p->p_flag &= ~P_CONTROLT;
1253 sx_xunlock(&proctree_lock);
1256 * If we did have a vnode, release our reference. Ordinarily we manage
1257 * these at the devfs layer, but we can't necessarily know that we were
1258 * invoked on the vnode referenced in the session (i.e. the vnode we
1259 * hold a reference to). We explicitly don't check VBAD/VI_DOOMED here
1260 * to avoid a vnode leak -- in circumstances elsewhere where we'd hit a
1261 * VI_DOOMED vnode, release has been deferred until the controlling TTY
1262 * is either changed or released.
1270 * Exposing information about current TTY's through sysctl
1274 tty_to_xtty(struct tty *tp, struct xtty *xt)
1277 tty_assert_locked(tp);
1279 xt->xt_size = sizeof(struct xtty);
1280 xt->xt_insize = ttyinq_getsize(&tp->t_inq);
1281 xt->xt_incc = ttyinq_bytescanonicalized(&tp->t_inq);
1282 xt->xt_inlc = ttyinq_bytesline(&tp->t_inq);
1283 xt->xt_inlow = tp->t_inlow;
1284 xt->xt_outsize = ttyoutq_getsize(&tp->t_outq);
1285 xt->xt_outcc = ttyoutq_bytesused(&tp->t_outq);
1286 xt->xt_outlow = tp->t_outlow;
1287 xt->xt_column = tp->t_column;
1288 xt->xt_pgid = tp->t_pgrp ? tp->t_pgrp->pg_id : 0;
1289 xt->xt_sid = tp->t_session ? tp->t_session->s_sid : 0;
1290 xt->xt_flags = tp->t_flags;
1291 xt->xt_dev = tp->t_dev ? dev2udev(tp->t_dev) : (uint32_t)NODEV;
1295 sysctl_kern_ttys(SYSCTL_HANDLER_ARGS)
1297 unsigned long lsize;
1298 struct xtty *xtlist, *xt;
1302 sx_slock(&tty_list_sx);
1303 lsize = tty_list_count * sizeof(struct xtty);
1305 sx_sunlock(&tty_list_sx);
1309 xtlist = xt = malloc(lsize, M_TTY, M_WAITOK);
1311 TAILQ_FOREACH(tp, &tty_list, t_list) {
1313 tty_to_xtty(tp, xt);
1317 sx_sunlock(&tty_list_sx);
1319 error = SYSCTL_OUT(req, xtlist, lsize);
1320 free(xtlist, M_TTY);
1324 SYSCTL_PROC(_kern, OID_AUTO, ttys, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
1325 0, 0, sysctl_kern_ttys, "S,xtty", "List of TTYs");
1328 * Device node creation. Device has been set up, now we can expose it to
1333 tty_makedevf(struct tty *tp, struct ucred *cred, int flags,
1334 const char *fmt, ...)
1337 struct make_dev_args args;
1338 struct cdev *dev, *init, *lock, *cua, *cinit, *clock;
1339 const char *prefix = "tty";
1340 char name[SPECNAMELEN - 3]; /* for "tty" and "cua". */
1346 /* Remove "tty" prefix from devices like PTY's. */
1347 if (tp->t_flags & TF_NOPREFIX)
1351 vsnrprintf(name, sizeof name, 32, fmt, ap);
1355 /* System device. */
1358 mode = S_IRUSR|S_IWUSR;
1361 uid = cred->cr_ruid;
1363 mode = S_IRUSR|S_IWUSR|S_IWGRP;
1366 flags = flags & TTYMK_CLONING ? MAKEDEV_REF : 0;
1367 flags |= MAKEDEV_CHECKNAME;
1369 /* Master call-in device. */
1370 make_dev_args_init(&args);
1371 args.mda_flags = flags;
1372 args.mda_devsw = &ttydev_cdevsw;
1376 args.mda_mode = mode;
1377 args.mda_si_drv1 = tp;
1378 error = make_dev_s(&args, &dev, "%s%s", prefix, name);
1383 init = lock = cua = cinit = clock = NULL;
1385 /* Slave call-in devices. */
1386 if (tp->t_flags & TF_INITLOCK) {
1387 args.mda_devsw = &ttyil_cdevsw;
1388 args.mda_unit = TTYUNIT_INIT;
1389 args.mda_si_drv1 = tp;
1390 args.mda_si_drv2 = &tp->t_termios_init_in;
1391 error = make_dev_s(&args, &init, "%s%s.init", prefix, name);
1394 dev_depends(dev, init);
1396 args.mda_unit = TTYUNIT_LOCK;
1397 args.mda_si_drv2 = &tp->t_termios_lock_in;
1398 error = make_dev_s(&args, &lock, "%s%s.lock", prefix, name);
1401 dev_depends(dev, lock);
1404 /* Call-out devices. */
1405 if (tp->t_flags & TF_CALLOUT) {
1406 make_dev_args_init(&args);
1407 args.mda_flags = flags;
1408 args.mda_devsw = &ttydev_cdevsw;
1410 args.mda_uid = UID_UUCP;
1411 args.mda_gid = GID_DIALER;
1412 args.mda_mode = 0660;
1413 args.mda_unit = TTYUNIT_CALLOUT;
1414 args.mda_si_drv1 = tp;
1415 error = make_dev_s(&args, &cua, "cua%s", name);
1418 dev_depends(dev, cua);
1420 /* Slave call-out devices. */
1421 if (tp->t_flags & TF_INITLOCK) {
1422 args.mda_devsw = &ttyil_cdevsw;
1423 args.mda_unit = TTYUNIT_CALLOUT | TTYUNIT_INIT;
1424 args.mda_si_drv2 = &tp->t_termios_init_out;
1425 error = make_dev_s(&args, &cinit, "cua%s.init", name);
1428 dev_depends(dev, cinit);
1430 args.mda_unit = TTYUNIT_CALLOUT | TTYUNIT_LOCK;
1431 args.mda_si_drv2 = &tp->t_termios_lock_out;
1432 error = make_dev_s(&args, &clock, "cua%s.lock", name);
1435 dev_depends(dev, clock);
1439 sx_xlock(&tty_list_sx);
1440 TAILQ_INSERT_TAIL(&tty_list, tp, t_list);
1442 sx_xunlock(&tty_list_sx);
1461 * Signalling processes.
1465 tty_signal_sessleader(struct tty *tp, int sig)
1470 tty_assert_locked(tp);
1471 MPASS(sig >= 1 && sig < NSIG);
1473 /* Make signals start output again. */
1474 tp->t_flags &= ~TF_STOPPED;
1477 * Load s_leader exactly once to avoid race where s_leader is
1478 * set to NULL by a concurrent invocation of killjobc() by the
1479 * session leader. Note that we are not holding t_session's
1480 * lock for the read.
1482 if ((s = tp->t_session) != NULL &&
1483 (p = atomic_load_ptr(&s->s_leader)) != NULL) {
1485 kern_psignal(p, sig);
1491 tty_signal_pgrp(struct tty *tp, int sig)
1495 tty_assert_locked(tp);
1496 MPASS(sig >= 1 && sig < NSIG);
1498 /* Make signals start output again. */
1499 tp->t_flags &= ~TF_STOPPED;
1501 if (sig == SIGINFO && !(tp->t_termios.c_lflag & NOKERNINFO))
1503 if (tp->t_pgrp != NULL) {
1504 ksiginfo_init(&ksi);
1505 ksi.ksi_signo = sig;
1506 ksi.ksi_code = SI_KERNEL;
1507 PGRP_LOCK(tp->t_pgrp);
1508 pgsignal(tp->t_pgrp, sig, 1, &ksi);
1509 PGRP_UNLOCK(tp->t_pgrp);
1514 tty_wakeup(struct tty *tp, int flags)
1517 if (tp->t_flags & TF_ASYNC && tp->t_sigio != NULL)
1518 pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
1520 if (flags & FWRITE) {
1521 cv_broadcast(&tp->t_outwait);
1522 selwakeup(&tp->t_outpoll);
1523 KNOTE_LOCKED(&tp->t_outpoll.si_note, 0);
1525 if (flags & FREAD) {
1526 cv_broadcast(&tp->t_inwait);
1527 selwakeup(&tp->t_inpoll);
1528 KNOTE_LOCKED(&tp->t_inpoll.si_note, 0);
1533 tty_wait(struct tty *tp, struct cv *cv)
1536 int revokecnt = tp->t_revokecnt;
1538 tty_lock_assert(tp, MA_OWNED|MA_NOTRECURSED);
1539 MPASS(!tty_gone(tp));
1541 error = cv_wait_sig(cv, tp->t_mtx);
1543 /* Bail out when the device slipped away. */
1547 /* Restart the system call when we may have been revoked. */
1548 if (tp->t_revokecnt != revokecnt)
1555 tty_timedwait(struct tty *tp, struct cv *cv, int hz)
1558 int revokecnt = tp->t_revokecnt;
1560 tty_lock_assert(tp, MA_OWNED|MA_NOTRECURSED);
1561 MPASS(!tty_gone(tp));
1563 error = cv_timedwait_sig(cv, tp->t_mtx, hz);
1565 /* Bail out when the device slipped away. */
1569 /* Restart the system call when we may have been revoked. */
1570 if (tp->t_revokecnt != revokecnt)
1577 tty_flush(struct tty *tp, int flags)
1580 if (flags & FWRITE) {
1581 tp->t_flags &= ~TF_HIWAT_OUT;
1582 ttyoutq_flush(&tp->t_outq);
1583 tty_wakeup(tp, FWRITE);
1584 if (!tty_gone(tp)) {
1585 ttydevsw_outwakeup(tp);
1586 ttydevsw_pktnotify(tp, TIOCPKT_FLUSHWRITE);
1589 if (flags & FREAD) {
1590 tty_hiwat_in_unblock(tp);
1591 ttyinq_flush(&tp->t_inq);
1592 tty_wakeup(tp, FREAD);
1593 if (!tty_gone(tp)) {
1594 ttydevsw_inwakeup(tp);
1595 ttydevsw_pktnotify(tp, TIOCPKT_FLUSHREAD);
1601 tty_set_winsize(struct tty *tp, const struct winsize *wsz)
1604 if (memcmp(&tp->t_winsize, wsz, sizeof(*wsz)) == 0)
1606 tp->t_winsize = *wsz;
1607 tty_signal_pgrp(tp, SIGWINCH);
1611 tty_generic_ioctl(struct tty *tp, u_long cmd, void *data, int fflag,
1619 * The SER_* and TIOCM_* flags are the same, but one bit
1620 * shifted. I don't know why.
1623 ttydevsw_modem(tp, SER_DTR, 0);
1626 ttydevsw_modem(tp, 0, SER_DTR);
1629 int bits = *(int *)data;
1631 (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1,
1632 ((~bits) & (TIOCM_DTR | TIOCM_RTS)) >> 1);
1636 int bits = *(int *)data;
1637 ttydevsw_modem(tp, (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1, 0);
1641 int bits = *(int *)data;
1642 ttydevsw_modem(tp, 0, (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1);
1646 *(int *)data = TIOCM_LE + (ttydevsw_modem(tp, 0, 0) << 1);
1651 tp->t_flags |= TF_ASYNC;
1653 tp->t_flags &= ~TF_ASYNC;
1656 /* This device supports non-blocking operation. */
1659 *(int *)data = ttyinq_bytescanonicalized(&tp->t_inq);
1663 *(int *)data = ttyoutq_bytesused(&tp->t_outq);
1666 if (tp->t_session != NULL && !tty_is_ctty(tp, td->td_proc))
1667 /* Not allowed to set ownership. */
1670 /* Temporarily unlock the TTY to set ownership. */
1672 error = fsetown(*(int *)data, &tp->t_sigio);
1676 if (tp->t_session != NULL && !tty_is_ctty(tp, td->td_proc))
1677 /* Not allowed to set ownership. */
1680 /* Get ownership. */
1681 *(int *)data = fgetown(&tp->t_sigio);
1684 /* Obtain terminal flags through tcgetattr(). */
1685 *(struct termios*)data = tp->t_termios;
1690 struct termios *t = data;
1693 * Who makes up these funny rules? According to POSIX,
1694 * input baud rate is set equal to the output baud rate
1697 if (t->c_ispeed == 0)
1698 t->c_ispeed = t->c_ospeed;
1700 /* Discard any unsupported bits. */
1701 t->c_iflag &= TTYSUP_IFLAG;
1702 t->c_oflag &= TTYSUP_OFLAG;
1703 t->c_lflag &= TTYSUP_LFLAG;
1704 t->c_cflag &= TTYSUP_CFLAG;
1706 /* Set terminal flags through tcsetattr(). */
1707 if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
1708 error = tty_drain(tp, 0);
1711 if (cmd == TIOCSETAF)
1712 tty_flush(tp, FREAD);
1716 * Only call param() when the flags really change.
1718 if ((t->c_cflag & CIGNORE) == 0 &&
1719 (tp->t_termios.c_cflag != t->c_cflag ||
1720 ((tp->t_termios.c_iflag ^ t->c_iflag) &
1721 (IXON|IXOFF|IXANY)) ||
1722 tp->t_termios.c_ispeed != t->c_ispeed ||
1723 tp->t_termios.c_ospeed != t->c_ospeed)) {
1724 error = ttydevsw_param(tp, t);
1730 tp->t_termios.c_cflag = t->c_cflag & ~CIGNORE;
1731 tp->t_termios.c_ispeed = t->c_ispeed;
1732 tp->t_termios.c_ospeed = t->c_ospeed;
1734 /* Baud rate has changed - update watermarks. */
1735 error = tty_watermarks(tp);
1740 /* Copy new non-device driver parameters. */
1741 tp->t_termios.c_iflag = t->c_iflag;
1742 tp->t_termios.c_oflag = t->c_oflag;
1743 tp->t_termios.c_lflag = t->c_lflag;
1744 memcpy(&tp->t_termios.c_cc, t->c_cc, sizeof t->c_cc);
1746 ttydisc_optimize(tp);
1748 if ((t->c_lflag & ICANON) == 0) {
1750 * When in non-canonical mode, wake up all
1751 * readers. Canonicalize any partial input. VMIN
1752 * and VTIME could also be adjusted.
1754 ttyinq_canonicalize(&tp->t_inq);
1755 tty_wakeup(tp, FREAD);
1759 * For packet mode: notify the PTY consumer that VSTOP
1760 * and VSTART may have been changed.
1762 if (tp->t_termios.c_iflag & IXON &&
1763 tp->t_termios.c_cc[VSTOP] == CTRL('S') &&
1764 tp->t_termios.c_cc[VSTART] == CTRL('Q'))
1765 ttydevsw_pktnotify(tp, TIOCPKT_DOSTOP);
1767 ttydevsw_pktnotify(tp, TIOCPKT_NOSTOP);
1771 /* For compatibility - we only support TTYDISC. */
1772 *(int *)data = TTYDISC;
1775 if (!tty_is_ctty(tp, td->td_proc))
1778 if (tp->t_pgrp != NULL)
1779 *(int *)data = tp->t_pgrp->pg_id;
1781 *(int *)data = NO_PID;
1784 if (!tty_is_ctty(tp, td->td_proc))
1787 MPASS(tp->t_session);
1788 *(int *)data = tp->t_session->s_sid;
1791 return (tty_drop_ctty(tp, td->td_proc));
1793 struct proc *p = td->td_proc;
1795 /* XXX: This looks awful. */
1797 sx_xlock(&proctree_lock);
1800 if (!SESS_LEADER(p)) {
1801 /* Only the session leader may do this. */
1802 sx_xunlock(&proctree_lock);
1806 if (tp->t_session != NULL && tp->t_session == p->p_session) {
1807 /* This is already our controlling TTY. */
1808 sx_xunlock(&proctree_lock);
1812 if (p->p_session->s_ttyp != NULL ||
1813 (tp->t_session != NULL && tp->t_session->s_ttyvp != NULL &&
1814 tp->t_session->s_ttyvp->v_type != VBAD)) {
1816 * There is already a relation between a TTY and
1817 * a session, or the caller is not the session
1820 * Allow the TTY to be stolen when the vnode is
1821 * invalid, but the reference to the TTY is
1822 * still active. This allows immediate reuse of
1823 * TTYs of which the session leader has been
1824 * killed or the TTY revoked.
1826 sx_xunlock(&proctree_lock);
1830 /* Connect the session to the TTY. */
1831 tp->t_session = p->p_session;
1832 tp->t_session->s_ttyp = tp;
1835 /* Assign foreground process group. */
1836 tp->t_pgrp = p->p_pgrp;
1838 p->p_flag |= P_CONTROLT;
1841 sx_xunlock(&proctree_lock);
1848 * XXX: Temporarily unlock the TTY to locate the process
1849 * group. This code would be lot nicer if we would ever
1850 * decompose proctree_lock.
1853 sx_slock(&proctree_lock);
1854 pg = pgfind(*(int *)data);
1857 if (pg == NULL || pg->pg_session != td->td_proc->p_session) {
1858 sx_sunlock(&proctree_lock);
1865 * Determine if this TTY is the controlling TTY after
1866 * relocking the TTY.
1868 if (!tty_is_ctty(tp, td->td_proc)) {
1869 sx_sunlock(&proctree_lock);
1873 sx_sunlock(&proctree_lock);
1875 /* Wake up the background process groups. */
1876 cv_broadcast(&tp->t_bgwait);
1880 int flags = *(int *)data;
1883 flags = (FREAD|FWRITE);
1885 flags &= (FREAD|FWRITE);
1886 tty_flush(tp, flags);
1890 /* Drain TTY output. */
1891 return tty_drain(tp, 0);
1892 case TIOCGDRAINWAIT:
1893 *(int *)data = tp->t_drainwait;
1895 case TIOCSDRAINWAIT:
1896 error = priv_check(td, PRIV_TTY_DRAINWAIT);
1898 tp->t_drainwait = *(int *)data;
1901 /* Set terminal as console TTY. */
1903 error = priv_check(td, PRIV_TTY_CONSOLE);
1908 * XXX: constty should really need to be locked!
1909 * XXX: allow disconnected constty's to be stolen!
1914 if (constty != NULL)
1920 } else if (constty == tp) {
1925 /* Obtain window size. */
1926 *(struct winsize*)data = tp->t_winsize;
1929 /* Set window size. */
1930 tty_set_winsize(tp, data);
1933 tp->t_flags |= TF_EXCLUDE;
1936 tp->t_flags &= ~TF_EXCLUDE;
1939 tp->t_flags |= TF_STOPPED;
1940 ttydevsw_pktnotify(tp, TIOCPKT_STOP);
1943 tp->t_flags &= ~TF_STOPPED;
1944 ttydevsw_outwakeup(tp);
1945 ttydevsw_pktnotify(tp, TIOCPKT_START);
1951 if ((fflag & FREAD) == 0 && priv_check(td, PRIV_TTY_STI))
1953 if (!tty_is_ctty(tp, td->td_proc) &&
1954 priv_check(td, PRIV_TTY_STI))
1956 ttydisc_rint(tp, *(char *)data, 0);
1957 ttydisc_rint_done(tp);
1962 return tty_ioctl_compat(tp, cmd, data, fflag, td);
1963 #else /* !COMPAT_43TTY */
1965 #endif /* COMPAT_43TTY */
1969 tty_ioctl(struct tty *tp, u_long cmd, void *data, int fflag, struct thread *td)
1973 tty_assert_locked(tp);
1978 error = ttydevsw_ioctl(tp, cmd, data, td);
1979 if (error == ENOIOCTL)
1980 error = tty_generic_ioctl(tp, cmd, data, fflag, td);
1986 tty_udev(struct tty *tp)
1990 return (dev2udev(tp->t_dev));
1996 tty_checkoutq(struct tty *tp)
1999 /* 256 bytes should be enough to print a log message. */
2000 return (ttyoutq_bytesleft(&tp->t_outq) >= 256);
2004 tty_hiwat_in_block(struct tty *tp)
2007 if ((tp->t_flags & TF_HIWAT_IN) == 0 &&
2008 tp->t_termios.c_iflag & IXOFF &&
2009 tp->t_termios.c_cc[VSTOP] != _POSIX_VDISABLE) {
2011 * Input flow control. Only enter the high watermark when we
2012 * can successfully store the VSTOP character.
2014 if (ttyoutq_write_nofrag(&tp->t_outq,
2015 &tp->t_termios.c_cc[VSTOP], 1) == 0)
2016 tp->t_flags |= TF_HIWAT_IN;
2018 /* No input flow control. */
2019 tp->t_flags |= TF_HIWAT_IN;
2024 tty_hiwat_in_unblock(struct tty *tp)
2027 if (tp->t_flags & TF_HIWAT_IN &&
2028 tp->t_termios.c_iflag & IXOFF &&
2029 tp->t_termios.c_cc[VSTART] != _POSIX_VDISABLE) {
2031 * Input flow control. Only leave the high watermark when we
2032 * can successfully store the VSTART character.
2034 if (ttyoutq_write_nofrag(&tp->t_outq,
2035 &tp->t_termios.c_cc[VSTART], 1) == 0)
2036 tp->t_flags &= ~TF_HIWAT_IN;
2038 /* No input flow control. */
2039 tp->t_flags &= ~TF_HIWAT_IN;
2043 ttydevsw_inwakeup(tp);
2047 * TTY hooks interface.
2051 ttyhook_defrint(struct tty *tp, char c, int flags)
2054 if (ttyhook_rint_bypass(tp, &c, 1) != 1)
2061 ttyhook_register(struct tty **rtp, struct proc *p, int fd, struct ttyhook *th,
2068 struct filedesc *fdp;
2069 cap_rights_t rights;
2072 /* Validate the file descriptor. */
2074 error = fget_unlocked(fdp, fd, cap_rights_init(&rights, CAP_TTYHOOK),
2078 if (fp->f_ops == &badfileops) {
2084 * Make sure the vnode is bound to a character device.
2085 * Unlocked check for the vnode type is ok there, because we
2086 * only shall prevent calling devvn_refthread on the file that
2087 * never has been opened over a character device.
2089 if (fp->f_type != DTYPE_VNODE || fp->f_vnode->v_type != VCHR) {
2094 /* Make sure it is a TTY. */
2095 cdp = devvn_refthread(fp->f_vnode, &dev, &ref);
2100 if (dev != fp->f_data) {
2104 if (cdp != &ttydev_cdevsw) {
2110 /* Try to attach the hook to the TTY. */
2113 MPASS((tp->t_hook == NULL) == ((tp->t_flags & TF_HOOK) == 0));
2114 if (tp->t_flags & TF_HOOK)
2117 tp->t_flags |= TF_HOOK;
2119 tp->t_hooksoftc = softc;
2123 /* Maybe we can switch into bypass mode now. */
2124 ttydisc_optimize(tp);
2126 /* Silently convert rint() calls to rint_bypass() when possible. */
2127 if (!ttyhook_hashook(tp, rint) && ttyhook_hashook(tp, rint_bypass))
2128 th->th_rint = ttyhook_defrint;
2130 done3: tty_unlock(tp);
2131 done2: dev_relthread(dev, ref);
2132 done1: fdrop(fp, curthread);
2137 ttyhook_unregister(struct tty *tp)
2140 tty_assert_locked(tp);
2141 MPASS(tp->t_flags & TF_HOOK);
2143 /* Disconnect the hook. */
2144 tp->t_flags &= ~TF_HOOK;
2147 /* Maybe we need to leave bypass mode. */
2148 ttydisc_optimize(tp);
2150 /* Maybe deallocate the TTY as well. */
2155 * /dev/console handling.
2159 ttyconsdev_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
2163 /* System has no console device. */
2164 if (dev_console_filename == NULL)
2167 /* Look up corresponding TTY by device name. */
2168 sx_slock(&tty_list_sx);
2169 TAILQ_FOREACH(tp, &tty_list, t_list) {
2170 if (strcmp(dev_console_filename, tty_devname(tp)) == 0) {
2171 dev_console->si_drv1 = tp;
2175 sx_sunlock(&tty_list_sx);
2177 /* System console has no TTY associated. */
2178 if (dev_console->si_drv1 == NULL)
2181 return (ttydev_open(dev, oflags, devtype, td));
2185 ttyconsdev_write(struct cdev *dev, struct uio *uio, int ioflag)
2190 return (ttydev_write(dev, uio, ioflag));
2194 * /dev/console is a little different than normal TTY's. When opened,
2195 * it determines which TTY to use. When data gets written to it, it
2196 * will be logged in the kernel message buffer.
2198 static struct cdevsw ttyconsdev_cdevsw = {
2199 .d_version = D_VERSION,
2200 .d_open = ttyconsdev_open,
2201 .d_close = ttydev_close,
2202 .d_read = ttydev_read,
2203 .d_write = ttyconsdev_write,
2204 .d_ioctl = ttydev_ioctl,
2205 .d_kqfilter = ttydev_kqfilter,
2206 .d_poll = ttydev_poll,
2207 .d_mmap = ttydev_mmap,
2208 .d_name = "ttyconsdev",
2213 ttyconsdev_init(void *unused __unused)
2216 dev_console = make_dev_credf(MAKEDEV_ETERNAL, &ttyconsdev_cdevsw, 0,
2217 NULL, UID_ROOT, GID_WHEEL, 0600, "console");
2220 SYSINIT(tty, SI_SUB_DRIVERS, SI_ORDER_FIRST, ttyconsdev_init, NULL);
2223 ttyconsdev_select(const char *name)
2226 dev_console_filename = name;
2230 * Debugging routines.
2233 #include "opt_ddb.h"
2235 #include <ddb/ddb.h>
2236 #include <ddb/db_sym.h>
2238 static const struct {
2243 { TF_NOPREFIX, 'N' },
2245 { TF_INITLOCK, 'I' },
2246 { TF_CALLOUT, 'C' },
2248 /* Keep these together -> 'Oi' and 'Oo'. */
2250 { TF_OPENED_IN, 'i' },
2251 { TF_OPENED_OUT, 'o' },
2252 { TF_OPENED_CONS, 'c' },
2255 { TF_OPENCLOSE, 'B' },
2257 { TF_LITERAL, 'L' },
2259 /* Keep these together -> 'Hi' and 'Ho'. */
2261 { TF_HIWAT_IN, 'i' },
2262 { TF_HIWAT_OUT, 'o' },
2264 { TF_STOPPED, 'S' },
2265 { TF_EXCLUDE, 'X' },
2270 /* Keep these together -> 'bi' and 'bo'. */
2272 { TF_BUSY_IN, 'i' },
2273 { TF_BUSY_OUT, 'o' },
2278 #define TTY_FLAG_BITS \
2279 "\20\1NOPREFIX\2INITLOCK\3CALLOUT\4OPENED_IN" \
2280 "\5OPENED_OUT\6OPENED_CONS\7GONE\10OPENCLOSE" \
2281 "\11ASYNC\12LITERAL\13HIWAT_IN\14HIWAT_OUT" \
2282 "\15STOPPED\16EXCLUDE\17BYPASS\20ZOMBIE" \
2283 "\21HOOK\22BUSY_IN\23BUSY_OUT"
2285 #define DB_PRINTSYM(name, addr) \
2286 db_printf("%s " #name ": ", sep); \
2287 db_printsym((db_addr_t) addr, DB_STGY_ANY); \
2291 _db_show_devsw(const char *sep, const struct ttydevsw *tsw)
2294 db_printf("%sdevsw: ", sep);
2295 db_printsym((db_addr_t)tsw, DB_STGY_ANY);
2296 db_printf(" (%p)\n", tsw);
2297 DB_PRINTSYM(open, tsw->tsw_open);
2298 DB_PRINTSYM(close, tsw->tsw_close);
2299 DB_PRINTSYM(outwakeup, tsw->tsw_outwakeup);
2300 DB_PRINTSYM(inwakeup, tsw->tsw_inwakeup);
2301 DB_PRINTSYM(ioctl, tsw->tsw_ioctl);
2302 DB_PRINTSYM(param, tsw->tsw_param);
2303 DB_PRINTSYM(modem, tsw->tsw_modem);
2304 DB_PRINTSYM(mmap, tsw->tsw_mmap);
2305 DB_PRINTSYM(pktnotify, tsw->tsw_pktnotify);
2306 DB_PRINTSYM(free, tsw->tsw_free);
2310 _db_show_hooks(const char *sep, const struct ttyhook *th)
2313 db_printf("%shook: ", sep);
2314 db_printsym((db_addr_t)th, DB_STGY_ANY);
2315 db_printf(" (%p)\n", th);
2318 DB_PRINTSYM(rint, th->th_rint);
2319 DB_PRINTSYM(rint_bypass, th->th_rint_bypass);
2320 DB_PRINTSYM(rint_done, th->th_rint_done);
2321 DB_PRINTSYM(rint_poll, th->th_rint_poll);
2322 DB_PRINTSYM(getc_inject, th->th_getc_inject);
2323 DB_PRINTSYM(getc_capture, th->th_getc_capture);
2324 DB_PRINTSYM(getc_poll, th->th_getc_poll);
2325 DB_PRINTSYM(close, th->th_close);
2329 _db_show_termios(const char *name, const struct termios *t)
2332 db_printf("%s: iflag 0x%x oflag 0x%x cflag 0x%x "
2333 "lflag 0x%x ispeed %u ospeed %u\n", name,
2334 t->c_iflag, t->c_oflag, t->c_cflag, t->c_lflag,
2335 t->c_ispeed, t->c_ospeed);
2338 /* DDB command to show TTY statistics. */
2339 DB_SHOW_COMMAND(tty, db_show_tty)
2344 db_printf("usage: show tty <addr>\n");
2347 tp = (struct tty *)addr;
2349 db_printf("%p: %s\n", tp, tty_devname(tp));
2350 db_printf("\tmtx: %p\n", tp->t_mtx);
2351 db_printf("\tflags: 0x%b\n", tp->t_flags, TTY_FLAG_BITS);
2352 db_printf("\trevokecnt: %u\n", tp->t_revokecnt);
2354 /* Buffering mechanisms. */
2355 db_printf("\tinq: %p begin %u linestart %u reprint %u end %u "
2356 "nblocks %u quota %u\n", &tp->t_inq, tp->t_inq.ti_begin,
2357 tp->t_inq.ti_linestart, tp->t_inq.ti_reprint, tp->t_inq.ti_end,
2358 tp->t_inq.ti_nblocks, tp->t_inq.ti_quota);
2359 db_printf("\toutq: %p begin %u end %u nblocks %u quota %u\n",
2360 &tp->t_outq, tp->t_outq.to_begin, tp->t_outq.to_end,
2361 tp->t_outq.to_nblocks, tp->t_outq.to_quota);
2362 db_printf("\tinlow: %zu\n", tp->t_inlow);
2363 db_printf("\toutlow: %zu\n", tp->t_outlow);
2364 _db_show_termios("\ttermios", &tp->t_termios);
2365 db_printf("\twinsize: row %u col %u xpixel %u ypixel %u\n",
2366 tp->t_winsize.ws_row, tp->t_winsize.ws_col,
2367 tp->t_winsize.ws_xpixel, tp->t_winsize.ws_ypixel);
2368 db_printf("\tcolumn: %u\n", tp->t_column);
2369 db_printf("\twritepos: %u\n", tp->t_writepos);
2370 db_printf("\tcompatflags: 0x%x\n", tp->t_compatflags);
2372 /* Init/lock-state devices. */
2373 _db_show_termios("\ttermios_init_in", &tp->t_termios_init_in);
2374 _db_show_termios("\ttermios_init_out", &tp->t_termios_init_out);
2375 _db_show_termios("\ttermios_lock_in", &tp->t_termios_lock_in);
2376 _db_show_termios("\ttermios_lock_out", &tp->t_termios_lock_out);
2379 _db_show_devsw("\t", tp->t_devsw);
2380 _db_show_hooks("\t", tp->t_hook);
2383 db_printf("\tpgrp: %p gid %d jobc %d\n", tp->t_pgrp,
2384 tp->t_pgrp ? tp->t_pgrp->pg_id : 0,
2385 tp->t_pgrp ? tp->t_pgrp->pg_jobc : 0);
2386 db_printf("\tsession: %p", tp->t_session);
2387 if (tp->t_session != NULL)
2388 db_printf(" count %u leader %p tty %p sid %d login %s",
2389 tp->t_session->s_count, tp->t_session->s_leader,
2390 tp->t_session->s_ttyp, tp->t_session->s_sid,
2391 tp->t_session->s_login);
2393 db_printf("\tsessioncnt: %u\n", tp->t_sessioncnt);
2394 db_printf("\tdevswsoftc: %p\n", tp->t_devswsoftc);
2395 db_printf("\thooksoftc: %p\n", tp->t_hooksoftc);
2396 db_printf("\tdev: %p\n", tp->t_dev);
2399 /* DDB command to list TTYs. */
2400 DB_SHOW_ALL_COMMAND(ttys, db_show_all_ttys)
2406 /* Make the output look like `pstat -t'. */
2408 #if defined(__LP64__)
2411 db_printf(" LINE INQ CAN LIN LOW OUTQ USE LOW "
2412 "COL SESS PGID STATE\n");
2414 TAILQ_FOREACH(tp, &tty_list, t_list) {
2415 isiz = tp->t_inq.ti_nblocks * TTYINQ_DATASIZE;
2416 osiz = tp->t_outq.to_nblocks * TTYOUTQ_DATASIZE;
2418 db_printf("%p %10s %5zu %4u %4u %4zu %5zu %4u %4zu %5u %5d "
2419 "%5d ", tp, tty_devname(tp), isiz,
2420 tp->t_inq.ti_linestart - tp->t_inq.ti_begin,
2421 tp->t_inq.ti_end - tp->t_inq.ti_linestart,
2422 isiz - tp->t_inlow, osiz,
2423 tp->t_outq.to_end - tp->t_outq.to_begin,
2424 osiz - tp->t_outlow, MIN(tp->t_column, 99999),
2425 tp->t_session ? tp->t_session->s_sid : 0,
2426 tp->t_pgrp ? tp->t_pgrp->pg_id : 0);
2429 for (i = j = 0; ttystates[i].flag; i++)
2430 if (tp->t_flags & ttystates[i].flag) {
2431 db_printf("%c", ttystates[i].val);