2 * SPDX-License-Identifier: BSD-2-Clause
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 #include "opt_capsicum.h"
34 #include "opt_printf.h"
36 #include <sys/param.h>
37 #include <sys/capsicum.h>
40 #include <sys/fcntl.h>
42 #include <sys/filedesc.h>
43 #include <sys/filio.h>
45 #include <sys/ioctl_compat.h>
46 #endif /* COMPAT_43TTY */
47 #include <sys/kernel.h>
48 #include <sys/limits.h>
49 #include <sys/malloc.h>
50 #include <sys/mount.h>
54 #include <sys/serial.h>
55 #include <sys/signal.h>
58 #include <sys/sysctl.h>
59 #include <sys/systm.h>
61 #include <sys/ttycom.h>
63 #include <sys/ttydefaults.h>
65 #include <sys/ucred.h>
66 #include <sys/vnode.h>
68 #include <fs/devfs/devfs.h>
70 #include <machine/stdarg.h>
72 static MALLOC_DEFINE(M_TTY, "tty", "tty device");
74 static void tty_rel_free(struct tty *tp);
76 static TAILQ_HEAD(, tty) tty_list = TAILQ_HEAD_INITIALIZER(tty_list);
77 static struct sx tty_list_sx;
78 SX_SYSINIT(tty_list, &tty_list_sx, "tty list");
79 static unsigned int tty_list_count = 0;
81 /* Character device of /dev/console. */
82 static struct cdev *dev_console;
83 static const char *dev_console_filename;
86 * Flags that are supported and stored by this implementation.
88 #define TTYSUP_IFLAG (IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK|ISTRIP|INLCR|\
89 IGNCR|ICRNL|IXON|IXOFF|IXANY|IMAXBEL|IUTF8)
90 #define TTYSUP_OFLAG (OPOST|ONLCR|TAB3|ONOEOT|OCRNL|ONOCR|ONLRET)
91 #define TTYSUP_LFLAG (ECHOKE|ECHOE|ECHOK|ECHO|ECHONL|ECHOPRT|\
92 ECHOCTL|ISIG|ICANON|ALTWERASE|IEXTEN|TOSTOP|\
93 FLUSHO|NOKERNINFO|NOFLSH)
94 #define TTYSUP_CFLAG (CIGNORE|CSIZE|CSTOPB|CREAD|PARENB|PARODD|\
95 HUPCL|CLOCAL|CCTS_OFLOW|CRTS_IFLOW|CDTR_IFLOW|\
96 CDSR_OFLOW|CCAR_OFLOW|CNO_RTSDTR)
98 #define TTY_CALLOUT(tp,d) (dev2unit(d) & TTYUNIT_CALLOUT)
100 static int tty_drainwait = 5 * 60;
101 SYSCTL_INT(_kern, OID_AUTO, tty_drainwait, CTLFLAG_RWTUN,
102 &tty_drainwait, 0, "Default output drain timeout in seconds");
105 * Set TTY buffer sizes.
108 #define TTYBUF_MAX 65536
110 #ifdef PRINTF_BUFR_SIZE
111 #define TTY_PRBUF_SIZE PRINTF_BUFR_SIZE
113 #define TTY_PRBUF_SIZE 256
117 * Allocate buffer space if necessary, and set low watermarks, based on speed.
118 * Note that the ttyxxxq_setsize() functions may drop and then reacquire the tty
119 * lock during memory allocation. They will return ENXIO if the tty disappears
123 tty_watermarks(struct tty *tp)
128 /* Provide an input buffer for 2 seconds of data. */
129 if (tp->t_termios.c_cflag & CREAD)
130 bs = MIN(tp->t_termios.c_ispeed / 5, TTYBUF_MAX);
131 error = ttyinq_setsize(&tp->t_inq, tp, bs);
135 /* Set low watermark at 10% (when 90% is available). */
136 tp->t_inlow = (ttyinq_getallocatedsize(&tp->t_inq) * 9) / 10;
138 /* Provide an output buffer for 2 seconds of data. */
139 bs = MIN(tp->t_termios.c_ospeed / 5, TTYBUF_MAX);
140 error = ttyoutq_setsize(&tp->t_outq, tp, bs);
144 /* Set low watermark at 10% (when 90% is available). */
145 tp->t_outlow = (ttyoutq_getallocatedsize(&tp->t_outq) * 9) / 10;
151 tty_drain(struct tty *tp, int leaving)
153 sbintime_t timeout_at;
157 if (ttyhook_hashook(tp, getc_inject))
158 /* buffer is inaccessible */
162 * For close(), use the recent historic timeout of "1 second without
163 * making progress". For tcdrain(), use t_drainwait as the timeout,
164 * with zero meaning "no timeout" which gives POSIX behavior.
167 timeout_at = getsbinuptime() + SBT_1S;
168 else if (tp->t_drainwait != 0)
169 timeout_at = getsbinuptime() + SBT_1S * tp->t_drainwait;
174 * Poll the output buffer and the hardware for completion, at 10 Hz.
175 * Polling is required for devices which are not able to signal an
176 * interrupt when the transmitter becomes idle (most USB serial devs).
177 * The unusual structure of this loop ensures we check for busy one more
178 * time after tty_timedwait() returns EWOULDBLOCK, so that success has
179 * higher priority than timeout if the IO completed in the last 100mS.
182 bytes = ttyoutq_bytesused(&tp->t_outq);
184 if (ttyoutq_bytesused(&tp->t_outq) == 0 && !ttydevsw_busy(tp))
188 ttydevsw_outwakeup(tp);
189 error = tty_timedwait(tp, &tp->t_outwait, hz / 10);
190 if (error != 0 && error != EWOULDBLOCK)
192 else if (timeout_at == 0 || getsbinuptime() < timeout_at)
194 else if (leaving && ttyoutq_bytesused(&tp->t_outq) < bytes) {
195 /* In close, making progress, grant an extra second. */
197 timeout_at += SBT_1S;
198 bytes = ttyoutq_bytesused(&tp->t_outq);
204 * Though ttydev_enter() and ttydev_leave() seem to be related, they
205 * don't have to be used together. ttydev_enter() is used by the cdev
206 * operations to prevent an actual operation from being processed when
207 * the TTY has been abandoned. ttydev_leave() is used by ttydev_open()
208 * and ttydev_close() to determine whether per-TTY data should be
213 ttydev_enter(struct tty *tp)
218 if (tty_gone(tp) || !tty_opened(tp)) {
219 /* Device is already gone. */
228 ttydev_leave(struct tty *tp)
231 tty_assert_locked(tp);
233 if (tty_opened(tp) || tp->t_flags & TF_OPENCLOSE) {
234 /* Device is still opened somewhere. */
239 tp->t_flags |= TF_OPENCLOSE;
241 /* Remove console TTY. */
244 /* Drain any output. */
250 /* Free i/o queues now since they might be large. */
251 ttyinq_free(&tp->t_inq);
253 ttyoutq_free(&tp->t_outq);
259 tp->t_flags &= ~TF_OPENCLOSE;
260 cv_broadcast(&tp->t_dcdwait);
265 * Operations that are exposed through the character device in /dev.
268 ttydev_open(struct cdev *dev, int oflags, int devtype __unused,
278 /* Device is already gone. */
284 * Block when other processes are currently opening or closing
287 while (tp->t_flags & TF_OPENCLOSE) {
288 error = tty_wait(tp, &tp->t_dcdwait);
294 tp->t_flags |= TF_OPENCLOSE;
297 * Make sure the "tty" and "cua" device cannot be opened at the
298 * same time. The console is a "tty" device.
300 if (TTY_CALLOUT(tp, dev)) {
301 if (tp->t_flags & (TF_OPENED_CONS | TF_OPENED_IN)) {
306 if (tp->t_flags & TF_OPENED_OUT) {
312 if (tp->t_flags & TF_EXCLUDE && priv_check(td, PRIV_TTY_EXCLUSIVE)) {
317 if (!tty_opened(tp)) {
318 /* Set proper termios flags. */
319 if (TTY_CALLOUT(tp, dev))
320 tp->t_termios = tp->t_termios_init_out;
322 tp->t_termios = tp->t_termios_init_in;
323 ttydevsw_param(tp, &tp->t_termios);
324 /* Prevent modem control on callout devices and /dev/console. */
325 if (TTY_CALLOUT(tp, dev) || dev == dev_console)
326 tp->t_termios.c_cflag |= CLOCAL;
328 if ((tp->t_termios.c_cflag & CNO_RTSDTR) == 0)
329 ttydevsw_modem(tp, SER_DTR|SER_RTS, 0);
331 error = ttydevsw_open(tp);
336 error = tty_watermarks(tp);
341 /* Wait for Carrier Detect. */
342 if ((oflags & O_NONBLOCK) == 0 &&
343 (tp->t_termios.c_cflag & CLOCAL) == 0) {
344 while ((ttydevsw_modem(tp, 0, 0) & SER_DCD) == 0) {
345 error = tty_wait(tp, &tp->t_dcdwait);
351 if (dev == dev_console)
352 tp->t_flags |= TF_OPENED_CONS;
353 else if (TTY_CALLOUT(tp, dev))
354 tp->t_flags |= TF_OPENED_OUT;
356 tp->t_flags |= TF_OPENED_IN;
357 MPASS((tp->t_flags & (TF_OPENED_CONS | TF_OPENED_IN)) == 0 ||
358 (tp->t_flags & TF_OPENED_OUT) == 0);
360 done: tp->t_flags &= ~TF_OPENCLOSE;
361 cv_broadcast(&tp->t_dcdwait);
368 ttydev_close(struct cdev *dev, int fflag, int devtype __unused,
371 struct tty *tp = dev->si_drv1;
376 * Don't actually close the device if it is being used as the
379 MPASS((tp->t_flags & (TF_OPENED_CONS | TF_OPENED_IN)) == 0 ||
380 (tp->t_flags & TF_OPENED_OUT) == 0);
381 if (dev == dev_console)
382 tp->t_flags &= ~TF_OPENED_CONS;
384 tp->t_flags &= ~(TF_OPENED_IN|TF_OPENED_OUT);
386 if (tp->t_flags & TF_OPENED) {
391 /* If revoking, flush output now to avoid draining it later. */
392 if ((fflag & FREVOKE) != 0) {
393 tty_flush(tp, FWRITE);
394 knlist_delete(&tp->t_inpoll.si_note, td, 1);
395 knlist_delete(&tp->t_outpoll.si_note, td, 1);
398 tp->t_flags &= ~TF_EXCLUDE;
400 /* Properly wake up threads that are stuck - revoke(). */
402 tty_wakeup(tp, FREAD|FWRITE);
403 cv_broadcast(&tp->t_bgwait);
404 cv_broadcast(&tp->t_dcdwait);
412 tty_is_ctty(struct tty *tp, struct proc *p)
415 tty_assert_locked(tp);
417 return (p->p_session == tp->t_session && p->p_flag & P_CONTROLT);
421 tty_wait_background(struct tty *tp, struct thread *td, int sig)
428 MPASS(sig == SIGTTIN || sig == SIGTTOU);
429 tty_assert_locked(tp);
438 * pg may no longer be our process group.
439 * Re-check after locking.
441 if (p->p_pgrp != pg) {
448 * The process should only sleep, when:
449 * - This terminal is the controlling terminal
450 * - Its process group is not the foreground process
452 * - The parent process isn't waiting for the child to
454 * - the signal to send to the process isn't masked
456 if (!tty_is_ctty(tp, p) || p->p_pgrp == tp->t_pgrp) {
457 /* Allow the action to happen. */
463 if (SIGISMEMBER(p->p_sigacts->ps_sigignore, sig) ||
464 SIGISMEMBER(td->td_sigmask, sig)) {
465 /* Only allow them in write()/ioctl(). */
468 return (sig == SIGTTOU ? 0 : EIO);
471 if ((p->p_flag & P_PPWAIT) != 0 ||
472 (pg->pg_flags & PGRP_ORPHANED) != 0) {
473 /* Don't allow the action to happen. */
481 * Send the signal and sleep until we're the new
482 * foreground process group.
486 ksi.ksi_code = SI_KERNEL;
491 pgsignal(pg, ksi.ksi_signo, 1, &ksi);
494 error = tty_wait(tp, &tp->t_bgwait);
501 ttydev_read(struct cdev *dev, struct uio *uio, int ioflag)
503 struct tty *tp = dev->si_drv1;
506 error = ttydev_enter(tp);
509 error = ttydisc_read(tp, uio, ioflag);
513 * The read() call should not throw an error when the device is
514 * being destroyed. Silently convert it to an EOF.
516 done: if (error == ENXIO)
522 ttydev_write(struct cdev *dev, struct uio *uio, int ioflag)
524 struct tty *tp = dev->si_drv1;
527 error = ttydev_enter(tp);
531 if (tp->t_termios.c_lflag & TOSTOP) {
532 error = tty_wait_background(tp, curthread, SIGTTOU);
537 if (ioflag & IO_NDELAY && tp->t_flags & TF_BUSY_OUT) {
538 /* Allow non-blocking writes to bypass serialization. */
539 error = ttydisc_write(tp, uio, ioflag);
541 /* Serialize write() calls. */
542 while (tp->t_flags & TF_BUSY_OUT) {
543 error = tty_wait(tp, &tp->t_outserwait);
548 tp->t_flags |= TF_BUSY_OUT;
549 defer = sigdeferstop(SIGDEFERSTOP_ERESTART);
550 error = ttydisc_write(tp, uio, ioflag);
552 tp->t_flags &= ~TF_BUSY_OUT;
553 cv_signal(&tp->t_outserwait);
556 done: tty_unlock(tp);
561 ttydev_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
564 struct tty *tp = dev->si_drv1;
567 error = ttydev_enter(tp);
602 #endif /* COMPAT_43TTY */
604 * If the ioctl() causes the TTY to be modified, let it
605 * wait in the background.
607 error = tty_wait_background(tp, curthread, SIGTTOU);
612 if (cmd == TIOCSETA || cmd == TIOCSETAW || cmd == TIOCSETAF) {
613 struct termios *old = &tp->t_termios;
614 struct termios *new = (struct termios *)data;
615 struct termios *lock = TTY_CALLOUT(tp, dev) ?
616 &tp->t_termios_lock_out : &tp->t_termios_lock_in;
620 * Lock state devices. Just overwrite the values of the
621 * commands that are currently in use.
623 new->c_iflag = (old->c_iflag & lock->c_iflag) |
624 (new->c_iflag & ~lock->c_iflag);
625 new->c_oflag = (old->c_oflag & lock->c_oflag) |
626 (new->c_oflag & ~lock->c_oflag);
627 new->c_cflag = (old->c_cflag & lock->c_cflag) |
628 (new->c_cflag & ~lock->c_cflag);
629 new->c_lflag = (old->c_lflag & lock->c_lflag) |
630 (new->c_lflag & ~lock->c_lflag);
631 for (cc = 0; cc < NCCS; ++cc)
633 new->c_cc[cc] = old->c_cc[cc];
635 new->c_ispeed = old->c_ispeed;
637 new->c_ospeed = old->c_ospeed;
640 error = tty_ioctl(tp, cmd, data, fflag, td);
641 done: tty_unlock(tp);
647 ttydev_poll(struct cdev *dev, int events, struct thread *td)
649 struct tty *tp = dev->si_drv1;
650 int error, revents = 0;
652 error = ttydev_enter(tp);
654 return ((events & (POLLIN|POLLRDNORM)) | POLLHUP);
656 if (events & (POLLIN|POLLRDNORM)) {
657 /* See if we can read something. */
658 if (ttydisc_read_poll(tp) > 0)
659 revents |= events & (POLLIN|POLLRDNORM);
662 if (tp->t_flags & TF_ZOMBIE) {
663 /* Hangup flag on zombie state. */
665 } else if (events & (POLLOUT|POLLWRNORM)) {
666 /* See if we can write something. */
667 if (ttydisc_write_poll(tp) > 0)
668 revents |= events & (POLLOUT|POLLWRNORM);
672 if (events & (POLLIN|POLLRDNORM))
673 selrecord(td, &tp->t_inpoll);
674 if (events & (POLLOUT|POLLWRNORM))
675 selrecord(td, &tp->t_outpoll);
684 ttydev_mmap(struct cdev *dev, vm_ooffset_t offset, vm_paddr_t *paddr,
685 int nprot, vm_memattr_t *memattr)
687 struct tty *tp = dev->si_drv1;
690 /* Handle mmap() through the driver. */
692 error = ttydev_enter(tp);
695 error = ttydevsw_mmap(tp, offset, paddr, nprot, memattr);
706 tty_kqops_read_detach(struct knote *kn)
708 struct tty *tp = kn->kn_hook;
710 knlist_remove(&tp->t_inpoll.si_note, kn, 0);
714 tty_kqops_read_event(struct knote *kn, long hint __unused)
716 struct tty *tp = kn->kn_hook;
718 tty_assert_locked(tp);
720 if (tty_gone(tp) || tp->t_flags & TF_ZOMBIE) {
721 kn->kn_flags |= EV_EOF;
724 kn->kn_data = ttydisc_read_poll(tp);
725 return (kn->kn_data > 0);
730 tty_kqops_write_detach(struct knote *kn)
732 struct tty *tp = kn->kn_hook;
734 knlist_remove(&tp->t_outpoll.si_note, kn, 0);
738 tty_kqops_write_event(struct knote *kn, long hint __unused)
740 struct tty *tp = kn->kn_hook;
742 tty_assert_locked(tp);
745 kn->kn_flags |= EV_EOF;
748 kn->kn_data = ttydisc_write_poll(tp);
749 return (kn->kn_data > 0);
753 static struct filterops tty_kqops_read = {
755 .f_detach = tty_kqops_read_detach,
756 .f_event = tty_kqops_read_event,
759 static struct filterops tty_kqops_write = {
761 .f_detach = tty_kqops_write_detach,
762 .f_event = tty_kqops_write_event,
766 ttydev_kqfilter(struct cdev *dev, struct knote *kn)
768 struct tty *tp = dev->si_drv1;
771 error = ttydev_enter(tp);
775 switch (kn->kn_filter) {
778 kn->kn_fop = &tty_kqops_read;
779 knlist_add(&tp->t_inpoll.si_note, kn, 1);
783 kn->kn_fop = &tty_kqops_write;
784 knlist_add(&tp->t_outpoll.si_note, kn, 1);
795 static struct cdevsw ttydev_cdevsw = {
796 .d_version = D_VERSION,
797 .d_open = ttydev_open,
798 .d_close = ttydev_close,
799 .d_read = ttydev_read,
800 .d_write = ttydev_write,
801 .d_ioctl = ttydev_ioctl,
802 .d_kqfilter = ttydev_kqfilter,
803 .d_poll = ttydev_poll,
804 .d_mmap = ttydev_mmap,
810 * Init/lock-state devices
814 ttyil_open(struct cdev *dev, int oflags __unused, int devtype __unused,
831 ttyil_close(struct cdev *dev __unused, int flag __unused, int mode __unused,
832 struct thread *td __unused)
839 ttyil_rdwr(struct cdev *dev __unused, struct uio *uio __unused,
847 ttyil_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
850 struct tty *tp = dev->si_drv1;
859 error = ttydevsw_cioctl(tp, dev2unit(dev), cmd, data, td);
860 if (error != ENOIOCTL)
866 /* Obtain terminal flags through tcgetattr(). */
867 *(struct termios*)data = *(struct termios*)dev->si_drv2;
870 /* Set terminal flags through tcsetattr(). */
871 error = priv_check(td, PRIV_TTY_SETA);
874 *(struct termios*)dev->si_drv2 = *(struct termios*)data;
877 *(int *)data = TTYDISC;
880 bzero(data, sizeof(struct winsize));
886 done: tty_unlock(tp);
890 static struct cdevsw ttyil_cdevsw = {
891 .d_version = D_VERSION,
892 .d_open = ttyil_open,
893 .d_close = ttyil_close,
894 .d_read = ttyil_rdwr,
895 .d_write = ttyil_rdwr,
896 .d_ioctl = ttyil_ioctl,
902 tty_init_termios(struct tty *tp)
904 struct termios *t = &tp->t_termios_init_in;
906 t->c_cflag = TTYDEF_CFLAG;
907 t->c_iflag = TTYDEF_IFLAG;
908 t->c_lflag = TTYDEF_LFLAG;
909 t->c_oflag = TTYDEF_OFLAG;
910 t->c_ispeed = TTYDEF_SPEED;
911 t->c_ospeed = TTYDEF_SPEED;
912 memcpy(&t->c_cc, ttydefchars, sizeof ttydefchars);
914 tp->t_termios_init_out = *t;
918 tty_init_console(struct tty *tp, speed_t s)
920 struct termios *ti = &tp->t_termios_init_in;
921 struct termios *to = &tp->t_termios_init_out;
924 ti->c_ispeed = ti->c_ospeed = s;
925 to->c_ispeed = to->c_ospeed = s;
928 ti->c_cflag |= CLOCAL;
929 to->c_cflag |= CLOCAL;
933 * Standard device routine implementations, mostly meant for
934 * pseudo-terminal device drivers. When a driver creates a new terminal
935 * device class, missing routines are patched.
939 ttydevsw_defopen(struct tty *tp __unused)
946 ttydevsw_defclose(struct tty *tp __unused)
952 ttydevsw_defoutwakeup(struct tty *tp __unused)
955 panic("Terminal device has output, while not implemented");
959 ttydevsw_definwakeup(struct tty *tp __unused)
965 ttydevsw_defioctl(struct tty *tp __unused, u_long cmd __unused,
966 caddr_t data __unused, struct thread *td __unused)
973 ttydevsw_defcioctl(struct tty *tp __unused, int unit __unused,
974 u_long cmd __unused, caddr_t data __unused, struct thread *td __unused)
981 ttydevsw_defparam(struct tty *tp __unused, struct termios *t)
985 * Allow the baud rate to be adjusted for pseudo-devices, but at
986 * least restrict it to 115200 to prevent excessive buffer
987 * usage. Also disallow 0, to prevent foot shooting.
989 if (t->c_ispeed < B50)
991 else if (t->c_ispeed > B115200)
992 t->c_ispeed = B115200;
993 if (t->c_ospeed < B50)
995 else if (t->c_ospeed > B115200)
996 t->c_ospeed = B115200;
1003 ttydevsw_defmodem(struct tty *tp __unused, int sigon __unused,
1004 int sigoff __unused)
1007 /* Simulate a carrier to make the TTY layer happy. */
1012 ttydevsw_defmmap(struct tty *tp __unused, vm_ooffset_t offset __unused,
1013 vm_paddr_t *paddr __unused, int nprot __unused,
1014 vm_memattr_t *memattr __unused)
1021 ttydevsw_defpktnotify(struct tty *tp __unused, char event __unused)
1027 ttydevsw_deffree(void *softc __unused)
1030 panic("Terminal device freed without a free-handler");
1034 ttydevsw_defbusy(struct tty *tp __unused)
1041 * TTY allocation and deallocation. TTY devices can be deallocated when
1042 * the driver doesn't use it anymore, when the TTY isn't a session's
1043 * controlling TTY and when the device node isn't opened through devfs.
1047 tty_alloc(struct ttydevsw *tsw, void *sc)
1050 return (tty_alloc_mutex(tsw, sc, NULL));
1054 tty_alloc_mutex(struct ttydevsw *tsw, void *sc, struct mtx *mutex)
1058 /* Make sure the driver defines all routines. */
1059 #define PATCH_FUNC(x) do { \
1060 if (tsw->tsw_ ## x == NULL) \
1061 tsw->tsw_ ## x = ttydevsw_def ## x; \
1065 PATCH_FUNC(outwakeup);
1066 PATCH_FUNC(inwakeup);
1072 PATCH_FUNC(pktnotify);
1077 tp = malloc(sizeof(struct tty) + TTY_PRBUF_SIZE, M_TTY,
1079 tp->t_prbufsz = TTY_PRBUF_SIZE;
1081 tp->t_devswsoftc = sc;
1082 tp->t_flags = tsw->tsw_flags;
1083 tp->t_drainwait = tty_drainwait;
1085 tty_init_termios(tp);
1087 cv_init(&tp->t_inwait, "ttyin");
1088 cv_init(&tp->t_outwait, "ttyout");
1089 cv_init(&tp->t_outserwait, "ttyosr");
1090 cv_init(&tp->t_bgwait, "ttybg");
1091 cv_init(&tp->t_dcdwait, "ttydcd");
1093 /* Allow drivers to use a custom mutex to lock the TTY. */
1094 if (mutex != NULL) {
1097 tp->t_mtx = &tp->t_mtxobj;
1098 mtx_init(&tp->t_mtxobj, "ttymtx", NULL, MTX_DEF);
1101 knlist_init_mtx(&tp->t_inpoll.si_note, tp->t_mtx);
1102 knlist_init_mtx(&tp->t_outpoll.si_note, tp->t_mtx);
1108 tty_dealloc(void *arg)
1110 struct tty *tp = arg;
1113 * ttyydev_leave() usually frees the i/o queues earlier, but it is
1114 * not always called between queue allocation and here. The queues
1115 * may be allocated by ioctls on a pty control device without the
1116 * corresponding pty slave device ever being open, or after it is
1119 ttyinq_free(&tp->t_inq);
1120 ttyoutq_free(&tp->t_outq);
1121 seldrain(&tp->t_inpoll);
1122 seldrain(&tp->t_outpoll);
1123 knlist_clear(&tp->t_inpoll.si_note, 0);
1124 knlist_clear(&tp->t_outpoll.si_note, 0);
1125 knlist_destroy(&tp->t_inpoll.si_note);
1126 knlist_destroy(&tp->t_outpoll.si_note);
1128 cv_destroy(&tp->t_inwait);
1129 cv_destroy(&tp->t_outwait);
1130 cv_destroy(&tp->t_bgwait);
1131 cv_destroy(&tp->t_dcdwait);
1132 cv_destroy(&tp->t_outserwait);
1134 if (tp->t_mtx == &tp->t_mtxobj)
1135 mtx_destroy(&tp->t_mtxobj);
1141 tty_rel_free(struct tty *tp)
1145 tty_assert_locked(tp);
1147 #define TF_ACTIVITY (TF_GONE|TF_OPENED|TF_HOOK|TF_OPENCLOSE)
1148 if (tp->t_sessioncnt != 0 || (tp->t_flags & TF_ACTIVITY) != TF_GONE) {
1149 /* TTY is still in use. */
1154 /* Stop asynchronous I/O. */
1155 funsetown(&tp->t_sigio);
1157 /* TTY can be deallocated. */
1163 sx_xlock(&tty_list_sx);
1164 TAILQ_REMOVE(&tty_list, tp, t_list);
1166 sx_xunlock(&tty_list_sx);
1167 destroy_dev_sched_cb(dev, tty_dealloc, tp);
1172 tty_rel_pgrp(struct tty *tp, struct pgrp *pg)
1175 MPASS(tp->t_sessioncnt > 0);
1176 tty_assert_locked(tp);
1178 if (tp->t_pgrp == pg)
1185 tty_rel_sess(struct tty *tp, struct session *sess)
1188 MPASS(tp->t_sessioncnt > 0);
1190 /* Current session has left. */
1191 if (tp->t_session == sess) {
1192 tp->t_session = NULL;
1193 MPASS(tp->t_pgrp == NULL);
1200 tty_rel_gone(struct tty *tp)
1203 tty_assert_locked(tp);
1204 MPASS(!tty_gone(tp));
1206 /* Simulate carrier removal. */
1207 ttydisc_modem(tp, 0);
1209 /* Wake up all blocked threads. */
1210 tty_wakeup(tp, FREAD|FWRITE);
1211 cv_broadcast(&tp->t_bgwait);
1212 cv_broadcast(&tp->t_dcdwait);
1214 tp->t_flags |= TF_GONE;
1219 tty_drop_ctty(struct tty *tp, struct proc *p)
1221 struct session *session;
1225 * This looks terrible, but it's generally safe as long as the tty
1226 * hasn't gone away while we had the lock dropped. All of our sanity
1227 * checking that this operation is OK happens after we've picked it back
1228 * up, so other state changes are generally not fatal and the potential
1229 * for this particular operation to happen out-of-order in a
1230 * multithreaded scenario is likely a non-issue.
1233 sx_xlock(&proctree_lock);
1236 sx_xunlock(&proctree_lock);
1241 * If the session doesn't have a controlling TTY, or if we weren't
1242 * invoked on the controlling TTY, we'll return ENOIOCTL as we've
1243 * historically done.
1245 session = p->p_session;
1246 if (session->s_ttyp == NULL || session->s_ttyp != tp) {
1247 sx_xunlock(&proctree_lock);
1251 if (!SESS_LEADER(p)) {
1252 sx_xunlock(&proctree_lock);
1258 vp = session->s_ttyvp;
1259 session->s_ttyp = NULL;
1260 session->s_ttyvp = NULL;
1261 session->s_ttydp = NULL;
1262 SESS_UNLOCK(session);
1265 p->p_flag &= ~P_CONTROLT;
1267 sx_xunlock(&proctree_lock);
1270 * If we did have a vnode, release our reference. Ordinarily we manage
1271 * these at the devfs layer, but we can't necessarily know that we were
1272 * invoked on the vnode referenced in the session (i.e. the vnode we
1273 * hold a reference to). We explicitly don't check VBAD/VIRF_DOOMED here
1274 * to avoid a vnode leak -- in circumstances elsewhere where we'd hit a
1275 * VIRF_DOOMED vnode, release has been deferred until the controlling TTY
1276 * is either changed or released.
1279 devfs_ctty_unref(vp);
1284 * Exposing information about current TTY's through sysctl
1288 tty_to_xtty(struct tty *tp, struct xtty *xt)
1291 tty_assert_locked(tp);
1293 memset(xt, 0, sizeof(*xt));
1294 xt->xt_size = sizeof(struct xtty);
1295 xt->xt_insize = ttyinq_getsize(&tp->t_inq);
1296 xt->xt_incc = ttyinq_bytescanonicalized(&tp->t_inq);
1297 xt->xt_inlc = ttyinq_bytesline(&tp->t_inq);
1298 xt->xt_inlow = tp->t_inlow;
1299 xt->xt_outsize = ttyoutq_getsize(&tp->t_outq);
1300 xt->xt_outcc = ttyoutq_bytesused(&tp->t_outq);
1301 xt->xt_outlow = tp->t_outlow;
1302 xt->xt_column = tp->t_column;
1303 xt->xt_pgid = tp->t_pgrp ? tp->t_pgrp->pg_id : 0;
1304 xt->xt_sid = tp->t_session ? tp->t_session->s_sid : 0;
1305 xt->xt_flags = tp->t_flags;
1306 xt->xt_dev = tp->t_dev ? dev2udev(tp->t_dev) : (uint32_t)NODEV;
1310 sysctl_kern_ttys(SYSCTL_HANDLER_ARGS)
1312 unsigned long lsize;
1313 struct thread *td = curthread;
1314 struct xtty *xtlist, *xt;
1319 sx_slock(&tty_list_sx);
1320 lsize = tty_list_count * sizeof(struct xtty);
1322 sx_sunlock(&tty_list_sx);
1326 xtlist = xt = malloc(lsize, M_TTY, M_WAITOK);
1328 TAILQ_FOREACH(tp, &tty_list, t_list) {
1330 if (tp->t_session != NULL) {
1331 p = tp->t_session->s_leader;
1333 cansee = (p_cansee(td, p) == 0);
1336 cansee = !jailed(td->td_ucred);
1339 tty_to_xtty(tp, xt);
1344 sx_sunlock(&tty_list_sx);
1346 lsize = (xt - xtlist) * sizeof(struct xtty);
1348 error = SYSCTL_OUT(req, xtlist, lsize);
1352 free(xtlist, M_TTY);
1356 SYSCTL_PROC(_kern, OID_AUTO, ttys, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
1357 0, 0, sysctl_kern_ttys, "S,xtty", "List of TTYs");
1360 * Device node creation. Device has been set up, now we can expose it to
1365 tty_makedevf(struct tty *tp, struct ucred *cred, int flags,
1366 const char *fmt, ...)
1369 struct make_dev_args args;
1370 struct cdev *dev, *init, *lock, *cua, *cinit, *clock;
1371 const char *prefix = "tty";
1372 char name[SPECNAMELEN - 3]; /* for "tty" and "cua". */
1378 /* Remove "tty" prefix from devices like PTY's. */
1379 if (tp->t_flags & TF_NOPREFIX)
1383 vsnrprintf(name, sizeof name, 32, fmt, ap);
1387 /* System device. */
1390 mode = S_IRUSR|S_IWUSR;
1393 uid = cred->cr_ruid;
1395 mode = S_IRUSR|S_IWUSR|S_IWGRP;
1398 flags = flags & TTYMK_CLONING ? MAKEDEV_REF : 0;
1399 flags |= MAKEDEV_CHECKNAME;
1401 /* Master call-in device. */
1402 make_dev_args_init(&args);
1403 args.mda_flags = flags;
1404 args.mda_devsw = &ttydev_cdevsw;
1408 args.mda_mode = mode;
1409 args.mda_si_drv1 = tp;
1410 error = make_dev_s(&args, &dev, "%s%s", prefix, name);
1415 init = lock = cua = cinit = clock = NULL;
1417 /* Slave call-in devices. */
1418 if (tp->t_flags & TF_INITLOCK) {
1419 args.mda_devsw = &ttyil_cdevsw;
1420 args.mda_unit = TTYUNIT_INIT;
1421 args.mda_si_drv1 = tp;
1422 args.mda_si_drv2 = &tp->t_termios_init_in;
1423 error = make_dev_s(&args, &init, "%s%s.init", prefix, name);
1426 dev_depends(dev, init);
1428 args.mda_unit = TTYUNIT_LOCK;
1429 args.mda_si_drv2 = &tp->t_termios_lock_in;
1430 error = make_dev_s(&args, &lock, "%s%s.lock", prefix, name);
1433 dev_depends(dev, lock);
1436 /* Call-out devices. */
1437 if (tp->t_flags & TF_CALLOUT) {
1438 make_dev_args_init(&args);
1439 args.mda_flags = flags;
1440 args.mda_devsw = &ttydev_cdevsw;
1442 args.mda_uid = UID_UUCP;
1443 args.mda_gid = GID_DIALER;
1444 args.mda_mode = 0660;
1445 args.mda_unit = TTYUNIT_CALLOUT;
1446 args.mda_si_drv1 = tp;
1447 error = make_dev_s(&args, &cua, "cua%s", name);
1450 dev_depends(dev, cua);
1452 /* Slave call-out devices. */
1453 if (tp->t_flags & TF_INITLOCK) {
1454 args.mda_devsw = &ttyil_cdevsw;
1455 args.mda_unit = TTYUNIT_CALLOUT | TTYUNIT_INIT;
1456 args.mda_si_drv2 = &tp->t_termios_init_out;
1457 error = make_dev_s(&args, &cinit, "cua%s.init", name);
1460 dev_depends(dev, cinit);
1462 args.mda_unit = TTYUNIT_CALLOUT | TTYUNIT_LOCK;
1463 args.mda_si_drv2 = &tp->t_termios_lock_out;
1464 error = make_dev_s(&args, &clock, "cua%s.lock", name);
1467 dev_depends(dev, clock);
1471 sx_xlock(&tty_list_sx);
1472 TAILQ_INSERT_TAIL(&tty_list, tp, t_list);
1474 sx_xunlock(&tty_list_sx);
1493 * Signalling processes.
1497 tty_signal_sessleader(struct tty *tp, int sig)
1502 tty_assert_locked(tp);
1503 MPASS(sig >= 1 && sig < NSIG);
1505 /* Make signals start output again. */
1506 tp->t_flags &= ~TF_STOPPED;
1507 tp->t_termios.c_lflag &= ~FLUSHO;
1510 * Load s_leader exactly once to avoid race where s_leader is
1511 * set to NULL by a concurrent invocation of killjobc() by the
1512 * session leader. Note that we are not holding t_session's
1513 * lock for the read.
1515 if ((s = tp->t_session) != NULL &&
1516 (p = atomic_load_ptr(&s->s_leader)) != NULL) {
1518 kern_psignal(p, sig);
1524 tty_signal_pgrp(struct tty *tp, int sig)
1528 tty_assert_locked(tp);
1529 MPASS(sig >= 1 && sig < NSIG);
1531 /* Make signals start output again. */
1532 tp->t_flags &= ~TF_STOPPED;
1533 tp->t_termios.c_lflag &= ~FLUSHO;
1535 if (sig == SIGINFO && !(tp->t_termios.c_lflag & NOKERNINFO))
1537 if (tp->t_pgrp != NULL) {
1538 ksiginfo_init(&ksi);
1539 ksi.ksi_signo = sig;
1540 ksi.ksi_code = SI_KERNEL;
1541 PGRP_LOCK(tp->t_pgrp);
1542 pgsignal(tp->t_pgrp, sig, 1, &ksi);
1543 PGRP_UNLOCK(tp->t_pgrp);
1548 tty_wakeup(struct tty *tp, int flags)
1551 if (tp->t_flags & TF_ASYNC && tp->t_sigio != NULL)
1552 pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
1554 if (flags & FWRITE) {
1555 cv_broadcast(&tp->t_outwait);
1556 selwakeup(&tp->t_outpoll);
1557 KNOTE_LOCKED(&tp->t_outpoll.si_note, 0);
1559 if (flags & FREAD) {
1560 cv_broadcast(&tp->t_inwait);
1561 selwakeup(&tp->t_inpoll);
1562 KNOTE_LOCKED(&tp->t_inpoll.si_note, 0);
1567 tty_wait(struct tty *tp, struct cv *cv)
1570 int revokecnt = tp->t_revokecnt;
1572 tty_lock_assert(tp, MA_OWNED|MA_NOTRECURSED);
1573 MPASS(!tty_gone(tp));
1575 error = cv_wait_sig(cv, tp->t_mtx);
1577 /* Bail out when the device slipped away. */
1581 /* Restart the system call when we may have been revoked. */
1582 if (tp->t_revokecnt != revokecnt)
1589 tty_timedwait(struct tty *tp, struct cv *cv, int hz)
1592 int revokecnt = tp->t_revokecnt;
1594 tty_lock_assert(tp, MA_OWNED|MA_NOTRECURSED);
1595 MPASS(!tty_gone(tp));
1597 error = cv_timedwait_sig(cv, tp->t_mtx, hz);
1599 /* Bail out when the device slipped away. */
1603 /* Restart the system call when we may have been revoked. */
1604 if (tp->t_revokecnt != revokecnt)
1611 tty_flush(struct tty *tp, int flags)
1614 if (flags & FWRITE) {
1615 tp->t_flags &= ~TF_HIWAT_OUT;
1616 ttyoutq_flush(&tp->t_outq);
1617 tty_wakeup(tp, FWRITE);
1618 if (!tty_gone(tp)) {
1619 ttydevsw_outwakeup(tp);
1620 ttydevsw_pktnotify(tp, TIOCPKT_FLUSHWRITE);
1623 if (flags & FREAD) {
1624 tty_hiwat_in_unblock(tp);
1625 ttyinq_flush(&tp->t_inq);
1626 tty_wakeup(tp, FREAD);
1627 if (!tty_gone(tp)) {
1628 ttydevsw_inwakeup(tp);
1629 ttydevsw_pktnotify(tp, TIOCPKT_FLUSHREAD);
1635 tty_set_winsize(struct tty *tp, const struct winsize *wsz)
1638 if (memcmp(&tp->t_winsize, wsz, sizeof(*wsz)) == 0)
1640 tp->t_winsize = *wsz;
1641 tty_signal_pgrp(tp, SIGWINCH);
1645 tty_generic_ioctl(struct tty *tp, u_long cmd, void *data, int fflag,
1653 * The SER_* and TIOCM_* flags are the same, but one bit
1654 * shifted. I don't know why.
1657 ttydevsw_modem(tp, SER_DTR, 0);
1660 ttydevsw_modem(tp, 0, SER_DTR);
1663 int bits = *(int *)data;
1665 (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1,
1666 ((~bits) & (TIOCM_DTR | TIOCM_RTS)) >> 1);
1670 int bits = *(int *)data;
1671 ttydevsw_modem(tp, (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1, 0);
1675 int bits = *(int *)data;
1676 ttydevsw_modem(tp, 0, (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1);
1680 *(int *)data = TIOCM_LE + (ttydevsw_modem(tp, 0, 0) << 1);
1685 tp->t_flags |= TF_ASYNC;
1687 tp->t_flags &= ~TF_ASYNC;
1690 /* This device supports non-blocking operation. */
1693 *(int *)data = ttydisc_bytesavail(tp);
1697 *(int *)data = ttyoutq_bytesused(&tp->t_outq);
1700 if (tp->t_session != NULL && !tty_is_ctty(tp, td->td_proc))
1701 /* Not allowed to set ownership. */
1704 /* Temporarily unlock the TTY to set ownership. */
1706 error = fsetown(*(int *)data, &tp->t_sigio);
1710 if (tp->t_session != NULL && !tty_is_ctty(tp, td->td_proc))
1711 /* Not allowed to set ownership. */
1714 /* Get ownership. */
1715 *(int *)data = fgetown(&tp->t_sigio);
1718 /* Obtain terminal flags through tcgetattr(). */
1719 *(struct termios*)data = tp->t_termios;
1724 struct termios *t = data;
1725 bool canonicalize = false;
1728 * Who makes up these funny rules? According to POSIX,
1729 * input baud rate is set equal to the output baud rate
1732 if (t->c_ispeed == 0)
1733 t->c_ispeed = t->c_ospeed;
1735 /* Discard any unsupported bits. */
1736 t->c_iflag &= TTYSUP_IFLAG;
1737 t->c_oflag &= TTYSUP_OFLAG;
1738 t->c_lflag &= TTYSUP_LFLAG;
1739 t->c_cflag &= TTYSUP_CFLAG;
1741 /* Set terminal flags through tcsetattr(). */
1742 if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
1743 error = tty_drain(tp, 0);
1746 if (cmd == TIOCSETAF)
1747 tty_flush(tp, FREAD);
1751 * Only call param() when the flags really change.
1753 if ((t->c_cflag & CIGNORE) == 0 &&
1754 (tp->t_termios.c_cflag != t->c_cflag ||
1755 ((tp->t_termios.c_iflag ^ t->c_iflag) &
1756 (IXON|IXOFF|IXANY)) ||
1757 tp->t_termios.c_ispeed != t->c_ispeed ||
1758 tp->t_termios.c_ospeed != t->c_ospeed)) {
1759 error = ttydevsw_param(tp, t);
1765 tp->t_termios.c_cflag = t->c_cflag & ~CIGNORE;
1766 tp->t_termios.c_ispeed = t->c_ispeed;
1767 tp->t_termios.c_ospeed = t->c_ospeed;
1769 /* Baud rate has changed - update watermarks. */
1770 error = tty_watermarks(tp);
1776 * We'll canonicalize any partial input if we're transitioning
1777 * ICANON one way or the other. If we're going from -ICANON ->
1778 * ICANON, then in the worst case scenario we're in the middle
1779 * of a line but both ttydisc_read() and FIONREAD will search
1780 * for one of our line terminals.
1782 if ((t->c_lflag & ICANON) != (tp->t_termios.c_lflag & ICANON))
1783 canonicalize = true;
1784 else if (tp->t_termios.c_cc[VEOF] != t->c_cc[VEOF] ||
1785 tp->t_termios.c_cc[VEOL] != t->c_cc[VEOL])
1786 canonicalize = true;
1788 /* Copy new non-device driver parameters. */
1789 tp->t_termios.c_iflag = t->c_iflag;
1790 tp->t_termios.c_oflag = t->c_oflag;
1791 tp->t_termios.c_lflag = t->c_lflag;
1792 memcpy(&tp->t_termios.c_cc, t->c_cc, sizeof t->c_cc);
1794 ttydisc_optimize(tp);
1797 ttydisc_canonicalize(tp);
1798 if ((t->c_lflag & ICANON) == 0) {
1800 * When in non-canonical mode, wake up all
1801 * readers. Any partial input has already been
1802 * canonicalized above if we were in canonical mode.
1803 * VMIN and VTIME could also be adjusted.
1805 tty_wakeup(tp, FREAD);
1809 * For packet mode: notify the PTY consumer that VSTOP
1810 * and VSTART may have been changed.
1812 if (tp->t_termios.c_iflag & IXON &&
1813 tp->t_termios.c_cc[VSTOP] == CTRL('S') &&
1814 tp->t_termios.c_cc[VSTART] == CTRL('Q'))
1815 ttydevsw_pktnotify(tp, TIOCPKT_DOSTOP);
1817 ttydevsw_pktnotify(tp, TIOCPKT_NOSTOP);
1821 /* For compatibility - we only support TTYDISC. */
1822 *(int *)data = TTYDISC;
1825 if (!tty_is_ctty(tp, td->td_proc))
1828 if (tp->t_pgrp != NULL)
1829 *(int *)data = tp->t_pgrp->pg_id;
1831 *(int *)data = NO_PID;
1834 if (!tty_is_ctty(tp, td->td_proc))
1837 MPASS(tp->t_session);
1838 *(int *)data = tp->t_session->s_sid;
1841 return (tty_drop_ctty(tp, td->td_proc));
1843 struct proc *p = td->td_proc;
1845 /* XXX: This looks awful. */
1847 sx_xlock(&proctree_lock);
1850 if (!SESS_LEADER(p)) {
1851 /* Only the session leader may do this. */
1852 sx_xunlock(&proctree_lock);
1856 if (tp->t_session != NULL && tp->t_session == p->p_session) {
1857 /* This is already our controlling TTY. */
1858 sx_xunlock(&proctree_lock);
1862 if (p->p_session->s_ttyp != NULL ||
1863 (tp->t_session != NULL && tp->t_session->s_ttyvp != NULL &&
1864 tp->t_session->s_ttyvp->v_type != VBAD)) {
1866 * There is already a relation between a TTY and
1867 * a session, or the caller is not the session
1870 * Allow the TTY to be stolen when the vnode is
1871 * invalid, but the reference to the TTY is
1872 * still active. This allows immediate reuse of
1873 * TTYs of which the session leader has been
1874 * killed or the TTY revoked.
1876 sx_xunlock(&proctree_lock);
1880 /* Connect the session to the TTY. */
1881 tp->t_session = p->p_session;
1882 tp->t_session->s_ttyp = tp;
1885 /* Assign foreground process group. */
1886 tp->t_pgrp = p->p_pgrp;
1888 p->p_flag |= P_CONTROLT;
1891 sx_xunlock(&proctree_lock);
1898 * XXX: Temporarily unlock the TTY to locate the process
1899 * group. This code would be lot nicer if we would ever
1900 * decompose proctree_lock.
1903 sx_slock(&proctree_lock);
1904 pg = pgfind(*(int *)data);
1907 if (pg == NULL || pg->pg_session != td->td_proc->p_session) {
1908 sx_sunlock(&proctree_lock);
1915 * Determine if this TTY is the controlling TTY after
1916 * relocking the TTY.
1918 if (!tty_is_ctty(tp, td->td_proc)) {
1919 sx_sunlock(&proctree_lock);
1923 sx_sunlock(&proctree_lock);
1925 /* Wake up the background process groups. */
1926 cv_broadcast(&tp->t_bgwait);
1930 int flags = *(int *)data;
1933 flags = (FREAD|FWRITE);
1935 flags &= (FREAD|FWRITE);
1936 tty_flush(tp, flags);
1940 /* Drain TTY output. */
1941 return tty_drain(tp, 0);
1942 case TIOCGDRAINWAIT:
1943 *(int *)data = tp->t_drainwait;
1945 case TIOCSDRAINWAIT:
1946 error = priv_check(td, PRIV_TTY_DRAINWAIT);
1948 tp->t_drainwait = *(int *)data;
1951 /* Set terminal as console TTY. */
1953 error = priv_check(td, PRIV_TTY_CONSOLE);
1956 error = constty_set(tp);
1958 error = constty_clear(tp);
1962 /* Obtain window size. */
1963 *(struct winsize*)data = tp->t_winsize;
1966 /* Set window size. */
1967 tty_set_winsize(tp, data);
1970 tp->t_flags |= TF_EXCLUDE;
1973 tp->t_flags &= ~TF_EXCLUDE;
1976 tp->t_flags |= TF_STOPPED;
1977 ttydevsw_pktnotify(tp, TIOCPKT_STOP);
1980 tp->t_flags &= ~TF_STOPPED;
1981 tp->t_termios.c_lflag &= ~FLUSHO;
1982 ttydevsw_outwakeup(tp);
1983 ttydevsw_pktnotify(tp, TIOCPKT_START);
1989 if ((fflag & FREAD) == 0 && priv_check(td, PRIV_TTY_STI))
1991 if (!tty_is_ctty(tp, td->td_proc) &&
1992 priv_check(td, PRIV_TTY_STI))
1994 ttydisc_rint(tp, *(char *)data, 0);
1995 ttydisc_rint_done(tp);
2000 return tty_ioctl_compat(tp, cmd, data, fflag, td);
2001 #else /* !COMPAT_43TTY */
2003 #endif /* COMPAT_43TTY */
2007 tty_ioctl(struct tty *tp, u_long cmd, void *data, int fflag, struct thread *td)
2011 tty_assert_locked(tp);
2016 error = ttydevsw_ioctl(tp, cmd, data, td);
2017 if (error == ENOIOCTL)
2018 error = tty_generic_ioctl(tp, cmd, data, fflag, td);
2024 tty_udev(struct tty *tp)
2028 return (dev2udev(tp->t_dev));
2034 tty_checkoutq(struct tty *tp)
2037 /* 256 bytes should be enough to print a log message. */
2038 return (ttyoutq_bytesleft(&tp->t_outq) >= 256);
2042 tty_hiwat_in_block(struct tty *tp)
2045 if ((tp->t_flags & TF_HIWAT_IN) == 0 &&
2046 tp->t_termios.c_iflag & IXOFF &&
2047 tp->t_termios.c_cc[VSTOP] != _POSIX_VDISABLE) {
2049 * Input flow control. Only enter the high watermark when we
2050 * can successfully store the VSTOP character.
2052 if (ttyoutq_write_nofrag(&tp->t_outq,
2053 &tp->t_termios.c_cc[VSTOP], 1) == 0)
2054 tp->t_flags |= TF_HIWAT_IN;
2056 /* No input flow control. */
2057 tp->t_flags |= TF_HIWAT_IN;
2062 tty_hiwat_in_unblock(struct tty *tp)
2065 if (tp->t_flags & TF_HIWAT_IN &&
2066 tp->t_termios.c_iflag & IXOFF &&
2067 tp->t_termios.c_cc[VSTART] != _POSIX_VDISABLE) {
2069 * Input flow control. Only leave the high watermark when we
2070 * can successfully store the VSTART character.
2072 if (ttyoutq_write_nofrag(&tp->t_outq,
2073 &tp->t_termios.c_cc[VSTART], 1) == 0)
2074 tp->t_flags &= ~TF_HIWAT_IN;
2076 /* No input flow control. */
2077 tp->t_flags &= ~TF_HIWAT_IN;
2081 ttydevsw_inwakeup(tp);
2085 * TTY hooks interface.
2089 ttyhook_defrint(struct tty *tp, char c, int flags)
2092 if (ttyhook_rint_bypass(tp, &c, 1) != 1)
2099 ttyhook_register(struct tty **rtp, struct proc *p, int fd, struct ttyhook *th,
2106 struct filedesc *fdp;
2107 cap_rights_t rights;
2110 /* Validate the file descriptor. */
2112 * XXX this code inspects a file descriptor from a different process,
2113 * but there is no dedicated routine to do it in fd code, making the
2114 * ordeal highly questionable.
2117 FILEDESC_SLOCK(fdp);
2118 error = fget_cap_noref(fdp, fd, cap_rights_init_one(&rights, CAP_TTYHOOK),
2120 if (error == 0 && !fhold(fp))
2122 FILEDESC_SUNLOCK(fdp);
2125 if (fp->f_ops == &badfileops) {
2131 * Make sure the vnode is bound to a character device.
2132 * Unlocked check for the vnode type is ok there, because we
2133 * only shall prevent calling devvn_refthread on the file that
2134 * never has been opened over a character device.
2136 if (fp->f_type != DTYPE_VNODE || fp->f_vnode->v_type != VCHR) {
2141 /* Make sure it is a TTY. */
2142 cdp = devvn_refthread(fp->f_vnode, &dev, &ref);
2147 if (dev != fp->f_data) {
2151 if (cdp != &ttydev_cdevsw) {
2157 /* Try to attach the hook to the TTY. */
2160 MPASS((tp->t_hook == NULL) == ((tp->t_flags & TF_HOOK) == 0));
2161 if (tp->t_flags & TF_HOOK)
2164 tp->t_flags |= TF_HOOK;
2166 tp->t_hooksoftc = softc;
2170 /* Maybe we can switch into bypass mode now. */
2171 ttydisc_optimize(tp);
2173 /* Silently convert rint() calls to rint_bypass() when possible. */
2174 if (!ttyhook_hashook(tp, rint) && ttyhook_hashook(tp, rint_bypass))
2175 th->th_rint = ttyhook_defrint;
2177 done3: tty_unlock(tp);
2178 done2: dev_relthread(dev, ref);
2179 done1: fdrop(fp, curthread);
2184 ttyhook_unregister(struct tty *tp)
2187 tty_assert_locked(tp);
2188 MPASS(tp->t_flags & TF_HOOK);
2190 /* Disconnect the hook. */
2191 tp->t_flags &= ~TF_HOOK;
2194 /* Maybe we need to leave bypass mode. */
2195 ttydisc_optimize(tp);
2197 /* Maybe deallocate the TTY as well. */
2202 * /dev/console handling.
2206 ttyconsdev_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
2210 /* System has no console device. */
2211 if (dev_console_filename == NULL)
2214 /* Look up corresponding TTY by device name. */
2215 sx_slock(&tty_list_sx);
2216 TAILQ_FOREACH(tp, &tty_list, t_list) {
2217 if (strcmp(dev_console_filename, tty_devname(tp)) == 0) {
2218 dev_console->si_drv1 = tp;
2222 sx_sunlock(&tty_list_sx);
2224 /* System console has no TTY associated. */
2225 if (dev_console->si_drv1 == NULL)
2228 return (ttydev_open(dev, oflags, devtype, td));
2232 ttyconsdev_write(struct cdev *dev, struct uio *uio, int ioflag)
2237 return (ttydev_write(dev, uio, ioflag));
2241 * /dev/console is a little different than normal TTY's. When opened,
2242 * it determines which TTY to use. When data gets written to it, it
2243 * will be logged in the kernel message buffer.
2245 static struct cdevsw ttyconsdev_cdevsw = {
2246 .d_version = D_VERSION,
2247 .d_open = ttyconsdev_open,
2248 .d_close = ttydev_close,
2249 .d_read = ttydev_read,
2250 .d_write = ttyconsdev_write,
2251 .d_ioctl = ttydev_ioctl,
2252 .d_kqfilter = ttydev_kqfilter,
2253 .d_poll = ttydev_poll,
2254 .d_mmap = ttydev_mmap,
2255 .d_name = "ttyconsdev",
2260 ttyconsdev_init(void *unused __unused)
2263 dev_console = make_dev_credf(MAKEDEV_ETERNAL, &ttyconsdev_cdevsw, 0,
2264 NULL, UID_ROOT, GID_WHEEL, 0600, "console");
2267 SYSINIT(tty, SI_SUB_DRIVERS, SI_ORDER_FIRST, ttyconsdev_init, NULL);
2270 ttyconsdev_select(const char *name)
2273 dev_console_filename = name;
2277 * Debugging routines.
2280 #include "opt_ddb.h"
2282 #include <ddb/ddb.h>
2283 #include <ddb/db_sym.h>
2285 static const struct {
2290 { TF_NOPREFIX, 'N' },
2292 { TF_INITLOCK, 'I' },
2293 { TF_CALLOUT, 'C' },
2295 /* Keep these together -> 'Oi' and 'Oo'. */
2297 { TF_OPENED_IN, 'i' },
2298 { TF_OPENED_OUT, 'o' },
2299 { TF_OPENED_CONS, 'c' },
2302 { TF_OPENCLOSE, 'B' },
2304 { TF_LITERAL, 'L' },
2306 /* Keep these together -> 'Hi' and 'Ho'. */
2308 { TF_HIWAT_IN, 'i' },
2309 { TF_HIWAT_OUT, 'o' },
2311 { TF_STOPPED, 'S' },
2312 { TF_EXCLUDE, 'X' },
2317 /* Keep these together -> 'bi' and 'bo'. */
2319 { TF_BUSY_IN, 'i' },
2320 { TF_BUSY_OUT, 'o' },
2325 #define TTY_FLAG_BITS \
2326 "\20\1NOPREFIX\2INITLOCK\3CALLOUT\4OPENED_IN" \
2327 "\5OPENED_OUT\6OPENED_CONS\7GONE\10OPENCLOSE" \
2328 "\11ASYNC\12LITERAL\13HIWAT_IN\14HIWAT_OUT" \
2329 "\15STOPPED\16EXCLUDE\17BYPASS\20ZOMBIE" \
2330 "\21HOOK\22BUSY_IN\23BUSY_OUT"
2332 #define DB_PRINTSYM(name, addr) \
2333 db_printf("%s " #name ": ", sep); \
2334 db_printsym((db_addr_t) addr, DB_STGY_ANY); \
2338 _db_show_devsw(const char *sep, const struct ttydevsw *tsw)
2341 db_printf("%sdevsw: ", sep);
2342 db_printsym((db_addr_t)tsw, DB_STGY_ANY);
2343 db_printf(" (%p)\n", tsw);
2344 DB_PRINTSYM(open, tsw->tsw_open);
2345 DB_PRINTSYM(close, tsw->tsw_close);
2346 DB_PRINTSYM(outwakeup, tsw->tsw_outwakeup);
2347 DB_PRINTSYM(inwakeup, tsw->tsw_inwakeup);
2348 DB_PRINTSYM(ioctl, tsw->tsw_ioctl);
2349 DB_PRINTSYM(param, tsw->tsw_param);
2350 DB_PRINTSYM(modem, tsw->tsw_modem);
2351 DB_PRINTSYM(mmap, tsw->tsw_mmap);
2352 DB_PRINTSYM(pktnotify, tsw->tsw_pktnotify);
2353 DB_PRINTSYM(free, tsw->tsw_free);
2357 _db_show_hooks(const char *sep, const struct ttyhook *th)
2360 db_printf("%shook: ", sep);
2361 db_printsym((db_addr_t)th, DB_STGY_ANY);
2362 db_printf(" (%p)\n", th);
2365 DB_PRINTSYM(rint, th->th_rint);
2366 DB_PRINTSYM(rint_bypass, th->th_rint_bypass);
2367 DB_PRINTSYM(rint_done, th->th_rint_done);
2368 DB_PRINTSYM(rint_poll, th->th_rint_poll);
2369 DB_PRINTSYM(getc_inject, th->th_getc_inject);
2370 DB_PRINTSYM(getc_capture, th->th_getc_capture);
2371 DB_PRINTSYM(getc_poll, th->th_getc_poll);
2372 DB_PRINTSYM(close, th->th_close);
2376 _db_show_termios(const char *name, const struct termios *t)
2379 db_printf("%s: iflag 0x%x oflag 0x%x cflag 0x%x "
2380 "lflag 0x%x ispeed %u ospeed %u\n", name,
2381 t->c_iflag, t->c_oflag, t->c_cflag, t->c_lflag,
2382 t->c_ispeed, t->c_ospeed);
2385 /* DDB command to show TTY statistics. */
2386 DB_SHOW_COMMAND(tty, db_show_tty)
2391 db_printf("usage: show tty <addr>\n");
2394 tp = (struct tty *)addr;
2396 db_printf("%p: %s\n", tp, tty_devname(tp));
2397 db_printf("\tmtx: %p\n", tp->t_mtx);
2398 db_printf("\tflags: 0x%b\n", tp->t_flags, TTY_FLAG_BITS);
2399 db_printf("\trevokecnt: %u\n", tp->t_revokecnt);
2401 /* Buffering mechanisms. */
2402 db_printf("\tinq: %p begin %u linestart %u reprint %u end %u "
2403 "nblocks %u quota %u\n", &tp->t_inq, tp->t_inq.ti_begin,
2404 tp->t_inq.ti_linestart, tp->t_inq.ti_reprint, tp->t_inq.ti_end,
2405 tp->t_inq.ti_nblocks, tp->t_inq.ti_quota);
2406 db_printf("\toutq: %p begin %u end %u nblocks %u quota %u\n",
2407 &tp->t_outq, tp->t_outq.to_begin, tp->t_outq.to_end,
2408 tp->t_outq.to_nblocks, tp->t_outq.to_quota);
2409 db_printf("\tinlow: %zu\n", tp->t_inlow);
2410 db_printf("\toutlow: %zu\n", tp->t_outlow);
2411 _db_show_termios("\ttermios", &tp->t_termios);
2412 db_printf("\twinsize: row %u col %u xpixel %u ypixel %u\n",
2413 tp->t_winsize.ws_row, tp->t_winsize.ws_col,
2414 tp->t_winsize.ws_xpixel, tp->t_winsize.ws_ypixel);
2415 db_printf("\tcolumn: %u\n", tp->t_column);
2416 db_printf("\twritepos: %u\n", tp->t_writepos);
2417 db_printf("\tcompatflags: 0x%x\n", tp->t_compatflags);
2419 /* Init/lock-state devices. */
2420 _db_show_termios("\ttermios_init_in", &tp->t_termios_init_in);
2421 _db_show_termios("\ttermios_init_out", &tp->t_termios_init_out);
2422 _db_show_termios("\ttermios_lock_in", &tp->t_termios_lock_in);
2423 _db_show_termios("\ttermios_lock_out", &tp->t_termios_lock_out);
2426 _db_show_devsw("\t", tp->t_devsw);
2427 _db_show_hooks("\t", tp->t_hook);
2430 db_printf("\tpgrp: %p gid %d\n", tp->t_pgrp,
2431 tp->t_pgrp ? tp->t_pgrp->pg_id : 0);
2432 db_printf("\tsession: %p", tp->t_session);
2433 if (tp->t_session != NULL)
2434 db_printf(" count %u leader %p tty %p sid %d login %s",
2435 tp->t_session->s_count, tp->t_session->s_leader,
2436 tp->t_session->s_ttyp, tp->t_session->s_sid,
2437 tp->t_session->s_login);
2439 db_printf("\tsessioncnt: %u\n", tp->t_sessioncnt);
2440 db_printf("\tdevswsoftc: %p\n", tp->t_devswsoftc);
2441 db_printf("\thooksoftc: %p\n", tp->t_hooksoftc);
2442 db_printf("\tdev: %p\n", tp->t_dev);
2445 /* DDB command to list TTYs. */
2446 DB_SHOW_ALL_COMMAND(ttys, db_show_all_ttys)
2452 /* Make the output look like `pstat -t'. */
2454 #if defined(__LP64__)
2457 db_printf(" LINE INQ CAN LIN LOW OUTQ USE LOW "
2458 "COL SESS PGID STATE\n");
2460 TAILQ_FOREACH(tp, &tty_list, t_list) {
2461 isiz = tp->t_inq.ti_nblocks * TTYINQ_DATASIZE;
2462 osiz = tp->t_outq.to_nblocks * TTYOUTQ_DATASIZE;
2464 db_printf("%p %10s %5zu %4u %4u %4zu %5zu %4u %4zu %5u %5d "
2465 "%5d ", tp, tty_devname(tp), isiz,
2466 tp->t_inq.ti_linestart - tp->t_inq.ti_begin,
2467 tp->t_inq.ti_end - tp->t_inq.ti_linestart,
2468 isiz - tp->t_inlow, osiz,
2469 tp->t_outq.to_end - tp->t_outq.to_begin,
2470 osiz - tp->t_outlow, MIN(tp->t_column, 99999),
2471 tp->t_session ? tp->t_session->s_sid : 0,
2472 tp->t_pgrp ? tp->t_pgrp->pg_id : 0);
2475 for (i = j = 0; ttystates[i].flag; i++)
2476 if (tp->t_flags & ttystates[i].flag) {
2477 db_printf("%c", ttystates[i].val);