1 /*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright (c) 2008 Ed Schouten <ed@FreeBSD.org>
5 * All rights reserved.
6 *
7 * Portions of this software were developed under sponsorship from Snow
8 * B.V., the Netherlands.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
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.
18 *
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
29 * SUCH DAMAGE.
30 */
31
32 #include <sys/cdefs.h>
33 #include "opt_capsicum.h"
34 #include "opt_printf.h"
35
36 #include <sys/param.h>
37 #include <sys/capsicum.h>
38 #include <sys/conf.h>
39 #include <sys/cons.h>
40 #include <sys/fcntl.h>
41 #include <sys/file.h>
42 #include <sys/filedesc.h>
43 #include <sys/filio.h>
44 #ifdef COMPAT_43TTY
45 #include <sys/ioctl_compat.h>
46 #endif /* COMPAT_43TTY */
47 #include <sys/jail.h>
48 #include <sys/kernel.h>
49 #include <sys/limits.h>
50 #include <sys/malloc.h>
51 #include <sys/mount.h>
52 #include <sys/poll.h>
53 #include <sys/priv.h>
54 #include <sys/proc.h>
55 #include <sys/serial.h>
56 #include <sys/signal.h>
57 #include <sys/stat.h>
58 #include <sys/stdarg.h>
59 #include <sys/sx.h>
60 #include <sys/sysctl.h>
61 #include <sys/systm.h>
62 #include <sys/tty.h>
63 #include <sys/ttycom.h>
64 #define TTYDEFCHARS
65 #include <sys/ttydefaults.h>
66 #undef TTYDEFCHARS
67 #include <sys/ucred.h>
68 #include <sys/vnode.h>
69
70 #include <fs/devfs/devfs.h>
71
72 static MALLOC_DEFINE(M_TTY, "tty", "tty device");
73
74 static void tty_rel_free(struct tty *tp);
75
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;
80
81 /* Character device of /dev/console. */
82 static struct cdev *dev_console;
83 static const char *dev_console_filename;
84
85 /*
86 * Flags that are supported and stored by this implementation.
87 */
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)
97
98 #define TTY_CALLOUT(tp,d) (dev2unit(d) & TTYUNIT_CALLOUT)
99
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");
103
104 /*
105 * Set TTY buffer sizes.
106 */
107
108 #define TTYBUF_MAX 65536
109
110 #ifdef PRINTF_BUFR_SIZE
111 #define TTY_PRBUF_SIZE PRINTF_BUFR_SIZE
112 #else
113 #define TTY_PRBUF_SIZE 256
114 #endif
115
116 /*
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
120 * while unlocked.
121 */
122 static int
tty_watermarks(struct tty * tp)123 tty_watermarks(struct tty *tp)
124 {
125 size_t bs = 0;
126 int error;
127
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);
132 if (error != 0)
133 return (error);
134
135 /* Set low watermark at 10% (when 90% is available). */
136 tp->t_inlow = (ttyinq_getallocatedsize(&tp->t_inq) * 9) / 10;
137
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);
141 if (error != 0)
142 return (error);
143
144 /* Set low watermark at 10% (when 90% is available). */
145 tp->t_outlow = (ttyoutq_getallocatedsize(&tp->t_outq) * 9) / 10;
146
147 return (0);
148 }
149
150 static int
tty_drain(struct tty * tp,int leaving)151 tty_drain(struct tty *tp, int leaving)
152 {
153 sbintime_t timeout_at;
154 size_t bytes;
155 int error;
156
157 if (ttyhook_hashook(tp, getc_inject))
158 /* buffer is inaccessible */
159 return (0);
160
161 /*
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.
165 */
166 if (leaving)
167 timeout_at = getsbinuptime() + SBT_1S;
168 else if (tp->t_drainwait != 0)
169 timeout_at = getsbinuptime() + SBT_1S * tp->t_drainwait;
170 else
171 timeout_at = 0;
172
173 /*
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.
180 */
181 error = 0;
182 bytes = ttyoutq_bytesused(&tp->t_outq);
183 for (;;) {
184 if (ttyoutq_bytesused(&tp->t_outq) == 0 && !ttydevsw_busy(tp))
185 return (0);
186 if (error != 0)
187 return (error);
188 ttydevsw_outwakeup(tp);
189 error = tty_timedwait(tp, &tp->t_outwait, hz / 10);
190 if (error != 0 && error != EWOULDBLOCK)
191 return (error);
192 else if (timeout_at == 0 || getsbinuptime() < timeout_at)
193 error = 0;
194 else if (leaving && ttyoutq_bytesused(&tp->t_outq) < bytes) {
195 /* In close, making progress, grant an extra second. */
196 error = 0;
197 timeout_at += SBT_1S;
198 bytes = ttyoutq_bytesused(&tp->t_outq);
199 }
200 }
201 }
202
203 /*
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
209 * deallocated.
210 */
211
212 static __inline int
ttydev_enter(struct tty * tp)213 ttydev_enter(struct tty *tp)
214 {
215
216 tty_lock(tp);
217
218 if (tty_gone(tp) || !tty_opened(tp)) {
219 /* Device is already gone. */
220 tty_unlock(tp);
221 return (ENXIO);
222 }
223
224 return (0);
225 }
226
227 static void
ttydev_leave(struct tty * tp)228 ttydev_leave(struct tty *tp)
229 {
230
231 tty_assert_locked(tp);
232
233 if (tty_opened(tp) || tp->t_flags & TF_OPENCLOSE) {
234 /* Device is still opened somewhere. */
235 tty_unlock(tp);
236 return;
237 }
238
239 tp->t_flags |= TF_OPENCLOSE;
240
241 /* Remove console TTY. */
242 constty_clear(tp);
243
244 /* Drain any output. */
245 if (!tty_gone(tp))
246 tty_drain(tp, 1);
247
248 ttydisc_close(tp);
249
250 /* Free i/o queues now since they might be large. */
251 ttyinq_free(&tp->t_inq);
252 tp->t_inlow = 0;
253 ttyoutq_free(&tp->t_outq);
254 tp->t_outlow = 0;
255
256 if (!tty_gone(tp))
257 ttydevsw_close(tp);
258
259 tp->t_flags &= ~TF_OPENCLOSE;
260 cv_broadcast(&tp->t_dcdwait);
261 tty_rel_free(tp);
262 }
263
264 /*
265 * Operations that are exposed through the character device in /dev.
266 */
267 static int
ttydev_open(struct cdev * dev,int oflags,int devtype __unused,struct thread * td)268 ttydev_open(struct cdev *dev, int oflags, int devtype __unused,
269 struct thread *td)
270 {
271 struct tty *tp;
272 int error;
273
274 tp = dev->si_drv1;
275 error = 0;
276 tty_lock(tp);
277 if (tty_gone(tp)) {
278 /* Device is already gone. */
279 tty_unlock(tp);
280 return (ENXIO);
281 }
282
283 /*
284 * Block when other processes are currently opening or closing
285 * the TTY.
286 */
287 while (tp->t_flags & TF_OPENCLOSE) {
288 error = tty_wait(tp, &tp->t_dcdwait);
289 if (error != 0) {
290 tty_unlock(tp);
291 return (error);
292 }
293 }
294 tp->t_flags |= TF_OPENCLOSE;
295
296 /*
297 * Make sure the "tty" and "cua" device cannot be opened at the
298 * same time. The console is a "tty" device.
299 */
300 if (TTY_CALLOUT(tp, dev)) {
301 if (tp->t_flags & (TF_OPENED_CONS | TF_OPENED_IN)) {
302 error = EBUSY;
303 goto done;
304 }
305 } else {
306 if (tp->t_flags & TF_OPENED_OUT) {
307 error = EBUSY;
308 goto done;
309 }
310 }
311
312 if (tp->t_flags & TF_EXCLUDE && priv_check(td, PRIV_TTY_EXCLUSIVE)) {
313 error = EBUSY;
314 goto done;
315 }
316
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;
321 else
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;
327
328 if ((tp->t_termios.c_cflag & CNO_RTSDTR) == 0)
329 ttydevsw_modem(tp, SER_DTR|SER_RTS, 0);
330
331 error = ttydevsw_open(tp);
332 if (error != 0)
333 goto done;
334
335 ttydisc_open(tp);
336 error = tty_watermarks(tp);
337 if (error != 0)
338 goto done;
339 }
340
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);
346 if (error != 0)
347 goto done;
348 }
349 }
350
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;
355 else
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);
359
360 done: tp->t_flags &= ~TF_OPENCLOSE;
361 cv_broadcast(&tp->t_dcdwait);
362 ttydev_leave(tp);
363
364 return (error);
365 }
366
367 static int
ttydev_close(struct cdev * dev,int fflag,int devtype __unused,struct thread * td)368 ttydev_close(struct cdev *dev, int fflag, int devtype __unused,
369 struct thread *td)
370 {
371 struct tty *tp = dev->si_drv1;
372
373 tty_lock(tp);
374
375 /*
376 * Don't actually close the device if it is being used as the
377 * console.
378 */
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;
383 else
384 tp->t_flags &= ~(TF_OPENED_IN|TF_OPENED_OUT);
385
386 if (tp->t_flags & TF_OPENED) {
387 tty_unlock(tp);
388 return (0);
389 }
390
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);
396 }
397
398 tp->t_flags &= ~TF_EXCLUDE;
399
400 /* Properly wake up threads that are stuck - revoke(). */
401 tp->t_revokecnt++;
402 tty_wakeup(tp, FREAD|FWRITE);
403 cv_broadcast(&tp->t_bgwait);
404 cv_broadcast(&tp->t_dcdwait);
405
406 ttydev_leave(tp);
407
408 return (0);
409 }
410
411 static __inline int
tty_is_ctty(struct tty * tp,struct proc * p)412 tty_is_ctty(struct tty *tp, struct proc *p)
413 {
414
415 tty_assert_locked(tp);
416
417 return (p->p_session == tp->t_session && p->p_flag & P_CONTROLT);
418 }
419
420 int
tty_wait_background(struct tty * tp,struct thread * td,int sig)421 tty_wait_background(struct tty *tp, struct thread *td, int sig)
422 {
423 struct proc *p;
424 struct pgrp *pg;
425 ksiginfo_t ksi;
426 int error;
427
428 MPASS(sig == SIGTTIN || sig == SIGTTOU);
429 tty_assert_locked(tp);
430
431 p = td->td_proc;
432 for (;;) {
433 pg = p->p_pgrp;
434 PGRP_LOCK(pg);
435 PROC_LOCK(p);
436
437 /*
438 * pg may no longer be our process group.
439 * Re-check after locking.
440 */
441 if (p->p_pgrp != pg) {
442 PROC_UNLOCK(p);
443 PGRP_UNLOCK(pg);
444 continue;
445 }
446
447 /*
448 * The process should only sleep, when:
449 * - This terminal is the controlling terminal
450 * - Its process group is not the foreground process
451 * group
452 * - The parent process isn't waiting for the child to
453 * exit
454 * - the signal to send to the process isn't masked
455 */
456 if (!tty_is_ctty(tp, p) || p->p_pgrp == tp->t_pgrp) {
457 /* Allow the action to happen. */
458 PROC_UNLOCK(p);
459 PGRP_UNLOCK(pg);
460 return (0);
461 }
462
463 if (SIGISMEMBER(p->p_sigacts->ps_sigignore, sig) ||
464 SIGISMEMBER(td->td_sigmask, sig)) {
465 /* Only allow them in write()/ioctl(). */
466 PROC_UNLOCK(p);
467 PGRP_UNLOCK(pg);
468 return (sig == SIGTTOU ? 0 : EIO);
469 }
470
471 if ((p->p_flag & P_PPWAIT) != 0 ||
472 (pg->pg_flags & PGRP_ORPHANED) != 0) {
473 /* Don't allow the action to happen. */
474 PROC_UNLOCK(p);
475 PGRP_UNLOCK(pg);
476 return (EIO);
477 }
478 PROC_UNLOCK(p);
479
480 /*
481 * Send the signal and sleep until we're the new
482 * foreground process group.
483 */
484 if (sig != 0) {
485 ksiginfo_init(&ksi);
486 ksi.ksi_code = SI_KERNEL;
487 ksi.ksi_signo = sig;
488 sig = 0;
489 }
490
491 pgsignal(pg, ksi.ksi_signo, 1, &ksi);
492 PGRP_UNLOCK(pg);
493
494 error = tty_wait(tp, &tp->t_bgwait);
495 if (error)
496 return (error);
497 }
498 }
499
500 static int
ttydev_read(struct cdev * dev,struct uio * uio,int ioflag)501 ttydev_read(struct cdev *dev, struct uio *uio, int ioflag)
502 {
503 struct tty *tp = dev->si_drv1;
504 int error;
505
506 error = ttydev_enter(tp);
507 if (error)
508 goto done;
509 error = ttydisc_read(tp, uio, ioflag);
510 tty_unlock(tp);
511
512 /*
513 * The read() call should not throw an error when the device is
514 * being destroyed. Silently convert it to an EOF.
515 */
516 done: if (error == ENXIO)
517 error = 0;
518 return (error);
519 }
520
521 static int
ttydev_write(struct cdev * dev,struct uio * uio,int ioflag)522 ttydev_write(struct cdev *dev, struct uio *uio, int ioflag)
523 {
524 struct tty *tp = dev->si_drv1;
525 int defer, error;
526
527 error = ttydev_enter(tp);
528 if (error)
529 return (error);
530
531 if (tp->t_termios.c_lflag & TOSTOP) {
532 error = tty_wait_background(tp, curthread, SIGTTOU);
533 if (error)
534 goto done;
535 }
536
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);
540 } else {
541 /* Serialize write() calls. */
542 while (tp->t_flags & TF_BUSY_OUT) {
543 error = tty_wait(tp, &tp->t_outserwait);
544 if (error)
545 goto done;
546 }
547
548 tp->t_flags |= TF_BUSY_OUT;
549 defer = sigdeferstop(SIGDEFERSTOP_ERESTART);
550 error = ttydisc_write(tp, uio, ioflag);
551 sigallowstop(defer);
552 tp->t_flags &= ~TF_BUSY_OUT;
553 cv_signal(&tp->t_outserwait);
554 }
555
556 done: tty_unlock(tp);
557 return (error);
558 }
559
560 static int
ttydev_ioctl(struct cdev * dev,u_long cmd,caddr_t data,int fflag,struct thread * td)561 ttydev_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
562 struct thread *td)
563 {
564 struct tty *tp = dev->si_drv1;
565 int error;
566
567 error = ttydev_enter(tp);
568 if (error)
569 return (error);
570
571 switch (cmd) {
572 case TIOCCBRK:
573 case TIOCCONS:
574 case TIOCDRAIN:
575 case TIOCEXCL:
576 case TIOCFLUSH:
577 case TIOCNXCL:
578 case TIOCSBRK:
579 case TIOCSCTTY:
580 case TIOCSETA:
581 case TIOCSETAF:
582 case TIOCSETAW:
583 case TIOCSPGRP:
584 case TIOCSTART:
585 case TIOCSTAT:
586 case TIOCSTI:
587 case TIOCSTOP:
588 case TIOCSWINSZ:
589 #if 0
590 case TIOCSDRAINWAIT:
591 case TIOCSETD:
592 #endif
593 #ifdef COMPAT_43TTY
594 case TIOCLBIC:
595 case TIOCLBIS:
596 case TIOCLSET:
597 case TIOCSETC:
598 case OTIOCSETD:
599 case TIOCSETN:
600 case TIOCSETP:
601 case TIOCSLTC:
602 #endif /* COMPAT_43TTY */
603 /*
604 * If the ioctl() causes the TTY to be modified, let it
605 * wait in the background.
606 */
607 error = tty_wait_background(tp, curthread, SIGTTOU);
608 if (error)
609 goto done;
610 }
611
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;
617 int cc;
618
619 /*
620 * Lock state devices. Just overwrite the values of the
621 * commands that are currently in use.
622 */
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)
632 if (lock->c_cc[cc])
633 new->c_cc[cc] = old->c_cc[cc];
634 if (lock->c_ispeed)
635 new->c_ispeed = old->c_ispeed;
636 if (lock->c_ospeed)
637 new->c_ospeed = old->c_ospeed;
638 }
639
640 error = tty_ioctl(tp, cmd, data, fflag, td);
641 done: tty_unlock(tp);
642
643 return (error);
644 }
645
646 static int
ttydev_poll(struct cdev * dev,int events,struct thread * td)647 ttydev_poll(struct cdev *dev, int events, struct thread *td)
648 {
649 struct tty *tp = dev->si_drv1;
650 int error, revents = 0;
651
652 error = ttydev_enter(tp);
653 if (error)
654 return ((events & (POLLIN|POLLRDNORM)) | POLLHUP);
655
656 if (events & (POLLIN|POLLRDNORM)) {
657 /* See if we can read something. */
658 if (ttydisc_read_poll(tp) > 0)
659 revents |= events & (POLLIN|POLLRDNORM);
660 }
661
662 if (tp->t_flags & TF_ZOMBIE) {
663 /* Hangup flag on zombie state. */
664 revents |= POLLHUP;
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);
669 }
670
671 if (revents == 0) {
672 if (events & (POLLIN|POLLRDNORM))
673 selrecord(td, &tp->t_inpoll);
674 if (events & (POLLOUT|POLLWRNORM))
675 selrecord(td, &tp->t_outpoll);
676 }
677
678 tty_unlock(tp);
679
680 return (revents);
681 }
682
683 static int
ttydev_mmap(struct cdev * dev,vm_ooffset_t offset,vm_paddr_t * paddr,int nprot,vm_memattr_t * memattr)684 ttydev_mmap(struct cdev *dev, vm_ooffset_t offset, vm_paddr_t *paddr,
685 int nprot, vm_memattr_t *memattr)
686 {
687 struct tty *tp = dev->si_drv1;
688 int error;
689
690 /* Handle mmap() through the driver. */
691
692 error = ttydev_enter(tp);
693 if (error)
694 return (-1);
695 error = ttydevsw_mmap(tp, offset, paddr, nprot, memattr);
696 tty_unlock(tp);
697
698 return (error);
699 }
700
701 /*
702 * kqueue support.
703 */
704
705 static void
tty_kqops_read_detach(struct knote * kn)706 tty_kqops_read_detach(struct knote *kn)
707 {
708 struct tty *tp = kn->kn_hook;
709
710 knlist_remove(&tp->t_inpoll.si_note, kn, 0);
711 }
712
713 static int
tty_kqops_read_event(struct knote * kn,long hint __unused)714 tty_kqops_read_event(struct knote *kn, long hint __unused)
715 {
716 struct tty *tp = kn->kn_hook;
717
718 tty_assert_locked(tp);
719
720 if (tty_gone(tp) || tp->t_flags & TF_ZOMBIE) {
721 kn->kn_flags |= EV_EOF;
722 return (1);
723 } else {
724 kn->kn_data = ttydisc_read_poll(tp);
725 return (kn->kn_data > 0);
726 }
727 }
728
729 static void
tty_kqops_write_detach(struct knote * kn)730 tty_kqops_write_detach(struct knote *kn)
731 {
732 struct tty *tp = kn->kn_hook;
733
734 knlist_remove(&tp->t_outpoll.si_note, kn, 0);
735 }
736
737 static int
tty_kqops_write_event(struct knote * kn,long hint __unused)738 tty_kqops_write_event(struct knote *kn, long hint __unused)
739 {
740 struct tty *tp = kn->kn_hook;
741
742 tty_assert_locked(tp);
743
744 if (tty_gone(tp)) {
745 kn->kn_flags |= EV_EOF;
746 return (1);
747 } else {
748 kn->kn_data = ttydisc_write_poll(tp);
749 return (kn->kn_data > 0);
750 }
751 }
752
753 static const struct filterops tty_kqops_read = {
754 .f_isfd = 1,
755 .f_detach = tty_kqops_read_detach,
756 .f_event = tty_kqops_read_event,
757 .f_copy = knote_triv_copy,
758 };
759
760 static const struct filterops tty_kqops_write = {
761 .f_isfd = 1,
762 .f_detach = tty_kqops_write_detach,
763 .f_event = tty_kqops_write_event,
764 .f_copy = knote_triv_copy,
765 };
766
767 static int
ttydev_kqfilter(struct cdev * dev,struct knote * kn)768 ttydev_kqfilter(struct cdev *dev, struct knote *kn)
769 {
770 struct tty *tp = dev->si_drv1;
771 int error;
772
773 error = ttydev_enter(tp);
774 if (error)
775 return (error);
776
777 switch (kn->kn_filter) {
778 case EVFILT_READ:
779 kn->kn_hook = tp;
780 kn->kn_fop = &tty_kqops_read;
781 knlist_add(&tp->t_inpoll.si_note, kn, 1);
782 break;
783 case EVFILT_WRITE:
784 kn->kn_hook = tp;
785 kn->kn_fop = &tty_kqops_write;
786 knlist_add(&tp->t_outpoll.si_note, kn, 1);
787 break;
788 default:
789 error = EINVAL;
790 break;
791 }
792
793 tty_unlock(tp);
794 return (error);
795 }
796
797 static struct cdevsw ttydev_cdevsw = {
798 .d_version = D_VERSION,
799 .d_open = ttydev_open,
800 .d_close = ttydev_close,
801 .d_read = ttydev_read,
802 .d_write = ttydev_write,
803 .d_ioctl = ttydev_ioctl,
804 .d_kqfilter = ttydev_kqfilter,
805 .d_poll = ttydev_poll,
806 .d_mmap = ttydev_mmap,
807 .d_name = "ttydev",
808 .d_flags = D_TTY,
809 };
810
811 /*
812 * Init/lock-state devices
813 */
814
815 static int
ttyil_open(struct cdev * dev,int oflags __unused,int devtype __unused,struct thread * td)816 ttyil_open(struct cdev *dev, int oflags __unused, int devtype __unused,
817 struct thread *td)
818 {
819 struct tty *tp;
820 int error;
821
822 tp = dev->si_drv1;
823 error = 0;
824 tty_lock(tp);
825 if (tty_gone(tp))
826 error = ENODEV;
827 tty_unlock(tp);
828
829 return (error);
830 }
831
832 static int
ttyil_close(struct cdev * dev __unused,int flag __unused,int mode __unused,struct thread * td __unused)833 ttyil_close(struct cdev *dev __unused, int flag __unused, int mode __unused,
834 struct thread *td __unused)
835 {
836
837 return (0);
838 }
839
840 static int
ttyil_rdwr(struct cdev * dev __unused,struct uio * uio __unused,int ioflag __unused)841 ttyil_rdwr(struct cdev *dev __unused, struct uio *uio __unused,
842 int ioflag __unused)
843 {
844
845 return (ENODEV);
846 }
847
848 static int
ttyil_ioctl(struct cdev * dev,u_long cmd,caddr_t data,int fflag,struct thread * td)849 ttyil_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
850 struct thread *td)
851 {
852 struct tty *tp = dev->si_drv1;
853 int error;
854
855 tty_lock(tp);
856 if (tty_gone(tp)) {
857 error = ENODEV;
858 goto done;
859 }
860
861 error = ttydevsw_cioctl(tp, dev2unit(dev), cmd, data, td);
862 if (error != ENOIOCTL)
863 goto done;
864 error = 0;
865
866 switch (cmd) {
867 case TIOCGETA:
868 /* Obtain terminal flags through tcgetattr(). */
869 *(struct termios*)data = *(struct termios*)dev->si_drv2;
870 break;
871 case TIOCSETA:
872 /* Set terminal flags through tcsetattr(). */
873 error = priv_check(td, PRIV_TTY_SETA);
874 if (error)
875 break;
876 *(struct termios*)dev->si_drv2 = *(struct termios*)data;
877 break;
878 case TIOCGETD:
879 *(int *)data = TTYDISC;
880 break;
881 case TIOCGWINSZ:
882 bzero(data, sizeof(struct winsize));
883 break;
884 default:
885 error = ENOTTY;
886 }
887
888 done: tty_unlock(tp);
889 return (error);
890 }
891
892 static struct cdevsw ttyil_cdevsw = {
893 .d_version = D_VERSION,
894 .d_open = ttyil_open,
895 .d_close = ttyil_close,
896 .d_read = ttyil_rdwr,
897 .d_write = ttyil_rdwr,
898 .d_ioctl = ttyil_ioctl,
899 .d_name = "ttyil",
900 .d_flags = D_TTY,
901 };
902
903 static void
tty_init_termios(struct tty * tp)904 tty_init_termios(struct tty *tp)
905 {
906 struct termios *t = &tp->t_termios_init_in;
907
908 t->c_cflag = TTYDEF_CFLAG;
909 t->c_iflag = TTYDEF_IFLAG;
910 t->c_lflag = TTYDEF_LFLAG;
911 t->c_oflag = TTYDEF_OFLAG;
912 t->c_ispeed = TTYDEF_SPEED;
913 t->c_ospeed = TTYDEF_SPEED;
914 memcpy(&t->c_cc, ttydefchars, sizeof ttydefchars);
915
916 tp->t_termios_init_out = *t;
917 }
918
919 void
tty_init_console(struct tty * tp,speed_t s)920 tty_init_console(struct tty *tp, speed_t s)
921 {
922 struct termios *ti = &tp->t_termios_init_in;
923 struct termios *to = &tp->t_termios_init_out;
924
925 if (s != 0) {
926 ti->c_ispeed = ti->c_ospeed = s;
927 to->c_ispeed = to->c_ospeed = s;
928 }
929
930 ti->c_cflag |= CLOCAL;
931 to->c_cflag |= CLOCAL;
932 }
933
934 /*
935 * Standard device routine implementations, mostly meant for
936 * pseudo-terminal device drivers. When a driver creates a new terminal
937 * device class, missing routines are patched.
938 */
939
940 static int
ttydevsw_defopen(struct tty * tp __unused)941 ttydevsw_defopen(struct tty *tp __unused)
942 {
943
944 return (0);
945 }
946
947 static void
ttydevsw_defclose(struct tty * tp __unused)948 ttydevsw_defclose(struct tty *tp __unused)
949 {
950
951 }
952
953 static void
ttydevsw_defoutwakeup(struct tty * tp __unused)954 ttydevsw_defoutwakeup(struct tty *tp __unused)
955 {
956
957 panic("Terminal device has output, while not implemented");
958 }
959
960 static void
ttydevsw_definwakeup(struct tty * tp __unused)961 ttydevsw_definwakeup(struct tty *tp __unused)
962 {
963
964 }
965
966 static int
ttydevsw_defioctl(struct tty * tp __unused,u_long cmd __unused,caddr_t data __unused,struct thread * td __unused)967 ttydevsw_defioctl(struct tty *tp __unused, u_long cmd __unused,
968 caddr_t data __unused, struct thread *td __unused)
969 {
970
971 return (ENOIOCTL);
972 }
973
974 static int
ttydevsw_defcioctl(struct tty * tp __unused,int unit __unused,u_long cmd __unused,caddr_t data __unused,struct thread * td __unused)975 ttydevsw_defcioctl(struct tty *tp __unused, int unit __unused,
976 u_long cmd __unused, caddr_t data __unused, struct thread *td __unused)
977 {
978
979 return (ENOIOCTL);
980 }
981
982 static int
ttydevsw_defparam(struct tty * tp __unused,struct termios * t)983 ttydevsw_defparam(struct tty *tp __unused, struct termios *t)
984 {
985
986 /*
987 * Allow the baud rate to be adjusted for pseudo-devices, but at
988 * least restrict it to 115200 to prevent excessive buffer
989 * usage. Also disallow 0, to prevent foot shooting.
990 */
991 if (t->c_ispeed < B50)
992 t->c_ispeed = B50;
993 else if (t->c_ispeed > B115200)
994 t->c_ispeed = B115200;
995 if (t->c_ospeed < B50)
996 t->c_ospeed = B50;
997 else if (t->c_ospeed > B115200)
998 t->c_ospeed = B115200;
999 t->c_cflag |= CREAD;
1000
1001 return (0);
1002 }
1003
1004 static int
ttydevsw_defmodem(struct tty * tp __unused,int sigon __unused,int sigoff __unused)1005 ttydevsw_defmodem(struct tty *tp __unused, int sigon __unused,
1006 int sigoff __unused)
1007 {
1008
1009 /* Simulate a carrier to make the TTY layer happy. */
1010 return (SER_DCD);
1011 }
1012
1013 static int
ttydevsw_defmmap(struct tty * tp __unused,vm_ooffset_t offset __unused,vm_paddr_t * paddr __unused,int nprot __unused,vm_memattr_t * memattr __unused)1014 ttydevsw_defmmap(struct tty *tp __unused, vm_ooffset_t offset __unused,
1015 vm_paddr_t *paddr __unused, int nprot __unused,
1016 vm_memattr_t *memattr __unused)
1017 {
1018
1019 return (-1);
1020 }
1021
1022 static void
ttydevsw_defpktnotify(struct tty * tp __unused,char event __unused)1023 ttydevsw_defpktnotify(struct tty *tp __unused, char event __unused)
1024 {
1025
1026 }
1027
1028 static void
ttydevsw_deffree(void * softc __unused)1029 ttydevsw_deffree(void *softc __unused)
1030 {
1031
1032 panic("Terminal device freed without a free-handler");
1033 }
1034
1035 static bool
ttydevsw_defbusy(struct tty * tp __unused)1036 ttydevsw_defbusy(struct tty *tp __unused)
1037 {
1038
1039 return (false);
1040 }
1041
1042 /*
1043 * TTY allocation and deallocation. TTY devices can be deallocated when
1044 * the driver doesn't use it anymore, when the TTY isn't a session's
1045 * controlling TTY and when the device node isn't opened through devfs.
1046 */
1047
1048 struct tty *
tty_alloc(struct ttydevsw * tsw,void * sc)1049 tty_alloc(struct ttydevsw *tsw, void *sc)
1050 {
1051
1052 return (tty_alloc_mutex(tsw, sc, NULL));
1053 }
1054
1055 struct tty *
tty_alloc_mutex(struct ttydevsw * tsw,void * sc,struct mtx * mutex)1056 tty_alloc_mutex(struct ttydevsw *tsw, void *sc, struct mtx *mutex)
1057 {
1058 struct tty *tp;
1059
1060 /* Make sure the driver defines all routines. */
1061 #define PATCH_FUNC(x) do { \
1062 if (tsw->tsw_ ## x == NULL) \
1063 tsw->tsw_ ## x = ttydevsw_def ## x; \
1064 } while (0)
1065 PATCH_FUNC(open);
1066 PATCH_FUNC(close);
1067 PATCH_FUNC(outwakeup);
1068 PATCH_FUNC(inwakeup);
1069 PATCH_FUNC(ioctl);
1070 PATCH_FUNC(cioctl);
1071 PATCH_FUNC(param);
1072 PATCH_FUNC(modem);
1073 PATCH_FUNC(mmap);
1074 PATCH_FUNC(pktnotify);
1075 PATCH_FUNC(free);
1076 PATCH_FUNC(busy);
1077 #undef PATCH_FUNC
1078
1079 tp = malloc(sizeof(struct tty) + TTY_PRBUF_SIZE, M_TTY,
1080 M_WAITOK | M_ZERO);
1081 tp->t_prbufsz = TTY_PRBUF_SIZE;
1082 tp->t_devsw = tsw;
1083 tp->t_devswsoftc = sc;
1084 tp->t_flags = tsw->tsw_flags;
1085 tp->t_drainwait = tty_drainwait;
1086
1087 tty_init_termios(tp);
1088
1089 cv_init(&tp->t_inwait, "ttyin");
1090 cv_init(&tp->t_outwait, "ttyout");
1091 cv_init(&tp->t_outserwait, "ttyosr");
1092 cv_init(&tp->t_bgwait, "ttybg");
1093 cv_init(&tp->t_dcdwait, "ttydcd");
1094
1095 /* Allow drivers to use a custom mutex to lock the TTY. */
1096 if (mutex != NULL) {
1097 tp->t_mtx = mutex;
1098 } else {
1099 tp->t_mtx = &tp->t_mtxobj;
1100 mtx_init(&tp->t_mtxobj, "ttymtx", NULL, MTX_DEF);
1101 }
1102
1103 knlist_init_mtx(&tp->t_inpoll.si_note, tp->t_mtx);
1104 knlist_init_mtx(&tp->t_outpoll.si_note, tp->t_mtx);
1105
1106 return (tp);
1107 }
1108
1109 static void
tty_dealloc(void * arg)1110 tty_dealloc(void *arg)
1111 {
1112 struct tty *tp = arg;
1113
1114 /*
1115 * ttyydev_leave() usually frees the i/o queues earlier, but it is
1116 * not always called between queue allocation and here. The queues
1117 * may be allocated by ioctls on a pty control device without the
1118 * corresponding pty slave device ever being open, or after it is
1119 * closed.
1120 */
1121 ttyinq_free(&tp->t_inq);
1122 ttyoutq_free(&tp->t_outq);
1123 seldrain(&tp->t_inpoll);
1124 seldrain(&tp->t_outpoll);
1125 knlist_clear(&tp->t_inpoll.si_note, 0);
1126 knlist_clear(&tp->t_outpoll.si_note, 0);
1127 knlist_destroy(&tp->t_inpoll.si_note);
1128 knlist_destroy(&tp->t_outpoll.si_note);
1129
1130 cv_destroy(&tp->t_inwait);
1131 cv_destroy(&tp->t_outwait);
1132 cv_destroy(&tp->t_bgwait);
1133 cv_destroy(&tp->t_dcdwait);
1134 cv_destroy(&tp->t_outserwait);
1135
1136 if (tp->t_mtx == &tp->t_mtxobj)
1137 mtx_destroy(&tp->t_mtxobj);
1138 ttydevsw_free(tp);
1139 free(tp, M_TTY);
1140 }
1141
1142 static void
tty_rel_free(struct tty * tp)1143 tty_rel_free(struct tty *tp)
1144 {
1145 struct cdev *dev;
1146
1147 tty_assert_locked(tp);
1148
1149 #define TF_ACTIVITY (TF_GONE|TF_OPENED|TF_HOOK|TF_OPENCLOSE)
1150 if (tp->t_sessioncnt != 0 || (tp->t_flags & TF_ACTIVITY) != TF_GONE) {
1151 /* TTY is still in use. */
1152 tty_unlock(tp);
1153 return;
1154 }
1155
1156 /* Stop asynchronous I/O. */
1157 funsetown(&tp->t_sigio);
1158
1159 /* TTY can be deallocated. */
1160 dev = tp->t_dev;
1161 tp->t_dev = NULL;
1162 tty_unlock(tp);
1163
1164 if (dev != NULL) {
1165 sx_xlock(&tty_list_sx);
1166 TAILQ_REMOVE(&tty_list, tp, t_list);
1167 tty_list_count--;
1168 sx_xunlock(&tty_list_sx);
1169 destroy_dev_sched_cb(dev, tty_dealloc, tp);
1170 }
1171 }
1172
1173 void
tty_rel_pgrp(struct tty * tp,struct pgrp * pg)1174 tty_rel_pgrp(struct tty *tp, struct pgrp *pg)
1175 {
1176
1177 MPASS(tp->t_sessioncnt > 0);
1178 tty_assert_locked(tp);
1179
1180 if (tp->t_pgrp == pg)
1181 tp->t_pgrp = NULL;
1182
1183 tty_unlock(tp);
1184 }
1185
1186 void
tty_rel_sess(struct tty * tp,struct session * sess)1187 tty_rel_sess(struct tty *tp, struct session *sess)
1188 {
1189
1190 MPASS(tp->t_sessioncnt > 0);
1191
1192 /* Current session has left. */
1193 if (tp->t_session == sess) {
1194 tp->t_session = NULL;
1195 MPASS(tp->t_pgrp == NULL);
1196 }
1197 tp->t_sessioncnt--;
1198 tty_rel_free(tp);
1199 }
1200
1201 void
tty_rel_gone(struct tty * tp)1202 tty_rel_gone(struct tty *tp)
1203 {
1204
1205 tty_assert_locked(tp);
1206 MPASS(!tty_gone(tp));
1207
1208 /* Simulate carrier removal. */
1209 ttydisc_modem(tp, 0);
1210
1211 /* Wake up all blocked threads. */
1212 tty_wakeup(tp, FREAD|FWRITE);
1213 cv_broadcast(&tp->t_bgwait);
1214 cv_broadcast(&tp->t_dcdwait);
1215
1216 tp->t_flags |= TF_GONE;
1217 tty_rel_free(tp);
1218 }
1219
1220 static int
tty_drop_ctty(struct tty * tp,struct proc * p)1221 tty_drop_ctty(struct tty *tp, struct proc *p)
1222 {
1223 struct session *session;
1224 struct vnode *vp;
1225
1226 /*
1227 * This looks terrible, but it's generally safe as long as the tty
1228 * hasn't gone away while we had the lock dropped. All of our sanity
1229 * checking that this operation is OK happens after we've picked it back
1230 * up, so other state changes are generally not fatal and the potential
1231 * for this particular operation to happen out-of-order in a
1232 * multithreaded scenario is likely a non-issue.
1233 */
1234 tty_unlock(tp);
1235 sx_xlock(&proctree_lock);
1236 tty_lock(tp);
1237 if (tty_gone(tp)) {
1238 sx_xunlock(&proctree_lock);
1239 return (ENODEV);
1240 }
1241
1242 /*
1243 * If the session doesn't have a controlling TTY, or if we weren't
1244 * invoked on the controlling TTY, we'll return ENOIOCTL as we've
1245 * historically done.
1246 */
1247 session = p->p_session;
1248 if (session->s_ttyp == NULL || session->s_ttyp != tp) {
1249 sx_xunlock(&proctree_lock);
1250 return (ENOTTY);
1251 }
1252
1253 if (!SESS_LEADER(p)) {
1254 sx_xunlock(&proctree_lock);
1255 return (EPERM);
1256 }
1257
1258 PROC_LOCK(p);
1259 SESS_LOCK(session);
1260 vp = session->s_ttyvp;
1261 session->s_ttyp = NULL;
1262 session->s_ttyvp = NULL;
1263 session->s_ttydp = NULL;
1264 SESS_UNLOCK(session);
1265
1266 if (tp->t_session == session) {
1267 tp->t_session = NULL;
1268 tp->t_pgrp = NULL;
1269 }
1270 tp->t_sessioncnt--;
1271 p->p_flag &= ~P_CONTROLT;
1272 PROC_UNLOCK(p);
1273 sx_xunlock(&proctree_lock);
1274
1275 /*
1276 * If we did have a vnode, release our reference. Ordinarily we manage
1277 * these at the devfs layer, but we can't necessarily know that we were
1278 * invoked on the vnode referenced in the session (i.e. the vnode we
1279 * hold a reference to). We explicitly don't check VBAD/VIRF_DOOMED here
1280 * to avoid a vnode leak -- in circumstances elsewhere where we'd hit a
1281 * VIRF_DOOMED vnode, release has been deferred until the controlling TTY
1282 * is either changed or released.
1283 */
1284 if (vp != NULL)
1285 devfs_ctty_unref(vp);
1286 return (0);
1287 }
1288
1289 /*
1290 * Exposing information about current TTY's through sysctl
1291 */
1292
1293 static void
tty_to_xtty(struct tty * tp,struct xtty * xt)1294 tty_to_xtty(struct tty *tp, struct xtty *xt)
1295 {
1296
1297 tty_assert_locked(tp);
1298
1299 memset(xt, 0, sizeof(*xt));
1300 xt->xt_size = sizeof(struct xtty);
1301 xt->xt_insize = ttyinq_getsize(&tp->t_inq);
1302 xt->xt_incc = ttyinq_bytescanonicalized(&tp->t_inq);
1303 xt->xt_inlc = ttyinq_bytesline(&tp->t_inq);
1304 xt->xt_inlow = tp->t_inlow;
1305 xt->xt_outsize = ttyoutq_getsize(&tp->t_outq);
1306 xt->xt_outcc = ttyoutq_bytesused(&tp->t_outq);
1307 xt->xt_outlow = tp->t_outlow;
1308 xt->xt_column = tp->t_column;
1309 xt->xt_pgid = tp->t_pgrp ? tp->t_pgrp->pg_id : 0;
1310 xt->xt_sid = tp->t_session ? tp->t_session->s_sid : 0;
1311 xt->xt_flags = tp->t_flags;
1312 xt->xt_dev = tp->t_dev ? dev2udev(tp->t_dev) : (uint32_t)NODEV;
1313 }
1314
1315 static int
sysctl_kern_ttys(SYSCTL_HANDLER_ARGS)1316 sysctl_kern_ttys(SYSCTL_HANDLER_ARGS)
1317 {
1318 unsigned long lsize;
1319 struct thread *td = curthread;
1320 struct xtty *xtlist, *xt;
1321 struct tty *tp;
1322 struct proc *p;
1323 int error;
1324 bool cansee;
1325
1326 sx_slock(&tty_list_sx);
1327 lsize = tty_list_count * sizeof(struct xtty);
1328 if (lsize == 0) {
1329 sx_sunlock(&tty_list_sx);
1330 return (0);
1331 }
1332
1333 xtlist = xt = malloc(lsize, M_TTY, M_WAITOK);
1334
1335 TAILQ_FOREACH(tp, &tty_list, t_list) {
1336 tty_lock(tp);
1337 if (tp->t_session != NULL &&
1338 (p = atomic_load_ptr(&tp->t_session->s_leader)) != NULL) {
1339 PROC_LOCK(p);
1340 cansee = (p_cansee(td, p) == 0);
1341 PROC_UNLOCK(p);
1342 } else {
1343 cansee = !jailed(td->td_ucred);
1344 }
1345 if (cansee) {
1346 tty_to_xtty(tp, xt);
1347 xt++;
1348 }
1349 tty_unlock(tp);
1350 }
1351 sx_sunlock(&tty_list_sx);
1352
1353 lsize = (xt - xtlist) * sizeof(struct xtty);
1354 if (lsize > 0) {
1355 error = SYSCTL_OUT(req, xtlist, lsize);
1356 } else {
1357 error = 0;
1358 }
1359 free(xtlist, M_TTY);
1360 return (error);
1361 }
1362
1363 SYSCTL_PROC(_kern, OID_AUTO, ttys, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
1364 0, 0, sysctl_kern_ttys, "S,xtty", "List of TTYs");
1365
1366 /*
1367 * Device node creation. Device has been set up, now we can expose it to
1368 * the user.
1369 */
1370
1371 int
tty_makedevf(struct tty * tp,struct ucred * cred,int flags,const char * fmt,...)1372 tty_makedevf(struct tty *tp, struct ucred *cred, int flags,
1373 const char *fmt, ...)
1374 {
1375 va_list ap;
1376 struct make_dev_args args;
1377 struct cdev *dev, *init, *lock, *cua, *cinit, *clock;
1378 const char *prefix = "tty";
1379 char name[SPECNAMELEN - 3]; /* for "tty" and "cua". */
1380 uid_t uid;
1381 gid_t gid;
1382 mode_t mode;
1383 int error;
1384
1385 /* Remove "tty" prefix from devices like PTY's. */
1386 if (tp->t_flags & TF_NOPREFIX)
1387 prefix = "";
1388
1389 va_start(ap, fmt);
1390 vsnrprintf(name, sizeof name, 32, fmt, ap);
1391 va_end(ap);
1392
1393 if (cred == NULL) {
1394 /* System device. */
1395 uid = UID_ROOT;
1396 gid = GID_WHEEL;
1397 mode = S_IRUSR|S_IWUSR;
1398 } else {
1399 /* User device. */
1400 uid = cred->cr_ruid;
1401 gid = GID_TTY;
1402 mode = S_IRUSR|S_IWUSR|S_IWGRP;
1403 }
1404
1405 flags = flags & TTYMK_CLONING ? MAKEDEV_REF : 0;
1406 flags |= MAKEDEV_CHECKNAME;
1407
1408 /* Master call-in device. */
1409 make_dev_args_init(&args);
1410 args.mda_flags = flags;
1411 args.mda_devsw = &ttydev_cdevsw;
1412 args.mda_cr = cred;
1413 args.mda_uid = uid;
1414 args.mda_gid = gid;
1415 args.mda_mode = mode;
1416 args.mda_si_drv1 = tp;
1417 error = make_dev_s(&args, &dev, "%s%s", prefix, name);
1418 if (error != 0)
1419 return (error);
1420 tp->t_dev = dev;
1421
1422 init = lock = cua = cinit = clock = NULL;
1423
1424 /* Slave call-in devices. */
1425 if (tp->t_flags & TF_INITLOCK) {
1426 args.mda_devsw = &ttyil_cdevsw;
1427 args.mda_unit = TTYUNIT_INIT;
1428 args.mda_si_drv1 = tp;
1429 args.mda_si_drv2 = &tp->t_termios_init_in;
1430 error = make_dev_s(&args, &init, "%s%s.init", prefix, name);
1431 if (error != 0)
1432 goto fail;
1433 dev_depends(dev, init);
1434
1435 args.mda_unit = TTYUNIT_LOCK;
1436 args.mda_si_drv2 = &tp->t_termios_lock_in;
1437 error = make_dev_s(&args, &lock, "%s%s.lock", prefix, name);
1438 if (error != 0)
1439 goto fail;
1440 dev_depends(dev, lock);
1441 }
1442
1443 /* Call-out devices. */
1444 if (tp->t_flags & TF_CALLOUT) {
1445 make_dev_args_init(&args);
1446 args.mda_flags = flags;
1447 args.mda_devsw = &ttydev_cdevsw;
1448 args.mda_cr = cred;
1449 args.mda_uid = UID_UUCP;
1450 args.mda_gid = GID_DIALER;
1451 args.mda_mode = 0660;
1452 args.mda_unit = TTYUNIT_CALLOUT;
1453 args.mda_si_drv1 = tp;
1454 error = make_dev_s(&args, &cua, "cua%s", name);
1455 if (error != 0)
1456 goto fail;
1457 dev_depends(dev, cua);
1458
1459 /* Slave call-out devices. */
1460 if (tp->t_flags & TF_INITLOCK) {
1461 args.mda_devsw = &ttyil_cdevsw;
1462 args.mda_unit = TTYUNIT_CALLOUT | TTYUNIT_INIT;
1463 args.mda_si_drv2 = &tp->t_termios_init_out;
1464 error = make_dev_s(&args, &cinit, "cua%s.init", name);
1465 if (error != 0)
1466 goto fail;
1467 dev_depends(dev, cinit);
1468
1469 args.mda_unit = TTYUNIT_CALLOUT | TTYUNIT_LOCK;
1470 args.mda_si_drv2 = &tp->t_termios_lock_out;
1471 error = make_dev_s(&args, &clock, "cua%s.lock", name);
1472 if (error != 0)
1473 goto fail;
1474 dev_depends(dev, clock);
1475 }
1476 }
1477
1478 sx_xlock(&tty_list_sx);
1479 TAILQ_INSERT_TAIL(&tty_list, tp, t_list);
1480 tty_list_count++;
1481 sx_xunlock(&tty_list_sx);
1482
1483 return (0);
1484
1485 fail:
1486 destroy_dev(dev);
1487 if (init)
1488 destroy_dev(init);
1489 if (lock)
1490 destroy_dev(lock);
1491 if (cinit)
1492 destroy_dev(cinit);
1493 if (clock)
1494 destroy_dev(clock);
1495
1496 return (error);
1497 }
1498
1499 /*
1500 * Signalling processes.
1501 */
1502
1503 void
tty_signal_sessleader(struct tty * tp,int sig)1504 tty_signal_sessleader(struct tty *tp, int sig)
1505 {
1506 struct proc *p;
1507 struct session *s;
1508
1509 tty_assert_locked(tp);
1510 MPASS(sig >= 1 && sig < NSIG);
1511
1512 /* Make signals start output again. */
1513 tp->t_flags &= ~TF_STOPPED;
1514 tp->t_termios.c_lflag &= ~FLUSHO;
1515
1516 /*
1517 * Load s_leader exactly once to avoid race where s_leader is
1518 * set to NULL by a concurrent invocation of killjobc() by the
1519 * session leader. Note that we are not holding t_session's
1520 * lock for the read.
1521 */
1522 if ((s = tp->t_session) != NULL &&
1523 (p = atomic_load_ptr(&s->s_leader)) != NULL) {
1524 PROC_LOCK(p);
1525 kern_psignal(p, sig);
1526 PROC_UNLOCK(p);
1527 }
1528 }
1529
1530 void
tty_signal_pgrp(struct tty * tp,int sig)1531 tty_signal_pgrp(struct tty *tp, int sig)
1532 {
1533 ksiginfo_t ksi;
1534
1535 tty_assert_locked(tp);
1536 MPASS(sig >= 1 && sig < NSIG);
1537
1538 /* Make signals start output again. */
1539 tp->t_flags &= ~TF_STOPPED;
1540 tp->t_termios.c_lflag &= ~FLUSHO;
1541
1542 if (sig == SIGINFO && !(tp->t_termios.c_lflag & NOKERNINFO))
1543 tty_info(tp);
1544 if (tp->t_pgrp != NULL) {
1545 ksiginfo_init(&ksi);
1546 ksi.ksi_signo = sig;
1547 ksi.ksi_code = SI_KERNEL;
1548 PGRP_LOCK(tp->t_pgrp);
1549 pgsignal(tp->t_pgrp, sig, 1, &ksi);
1550 PGRP_UNLOCK(tp->t_pgrp);
1551 }
1552 }
1553
1554 void
tty_wakeup(struct tty * tp,int flags)1555 tty_wakeup(struct tty *tp, int flags)
1556 {
1557
1558 if (tp->t_flags & TF_ASYNC && tp->t_sigio != NULL)
1559 pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
1560
1561 if (flags & FWRITE) {
1562 cv_broadcast(&tp->t_outwait);
1563 selwakeup(&tp->t_outpoll);
1564 KNOTE_LOCKED(&tp->t_outpoll.si_note, 0);
1565 }
1566 if (flags & FREAD) {
1567 cv_broadcast(&tp->t_inwait);
1568 selwakeup(&tp->t_inpoll);
1569 KNOTE_LOCKED(&tp->t_inpoll.si_note, 0);
1570 }
1571 }
1572
1573 int
tty_wait(struct tty * tp,struct cv * cv)1574 tty_wait(struct tty *tp, struct cv *cv)
1575 {
1576 int error;
1577 int revokecnt = tp->t_revokecnt;
1578
1579 tty_lock_assert(tp, MA_OWNED|MA_NOTRECURSED);
1580 MPASS(!tty_gone(tp));
1581
1582 error = cv_wait_sig(cv, tp->t_mtx);
1583
1584 /* Bail out when the device slipped away. */
1585 if (tty_gone(tp))
1586 return (ENXIO);
1587
1588 /* Restart the system call when we may have been revoked. */
1589 if (tp->t_revokecnt != revokecnt)
1590 return (ERESTART);
1591
1592 return (error);
1593 }
1594
1595 int
tty_timedwait(struct tty * tp,struct cv * cv,int hz)1596 tty_timedwait(struct tty *tp, struct cv *cv, int hz)
1597 {
1598 int error;
1599 int revokecnt = tp->t_revokecnt;
1600
1601 tty_lock_assert(tp, MA_OWNED|MA_NOTRECURSED);
1602 MPASS(!tty_gone(tp));
1603
1604 error = cv_timedwait_sig(cv, tp->t_mtx, hz);
1605
1606 /* Bail out when the device slipped away. */
1607 if (tty_gone(tp))
1608 return (ENXIO);
1609
1610 /* Restart the system call when we may have been revoked. */
1611 if (tp->t_revokecnt != revokecnt)
1612 return (ERESTART);
1613
1614 return (error);
1615 }
1616
1617 void
tty_flush(struct tty * tp,int flags)1618 tty_flush(struct tty *tp, int flags)
1619 {
1620
1621 if (flags & FWRITE) {
1622 tp->t_flags &= ~TF_HIWAT_OUT;
1623 ttyoutq_flush(&tp->t_outq);
1624 tty_wakeup(tp, FWRITE);
1625 if (!tty_gone(tp)) {
1626 ttydevsw_outwakeup(tp);
1627 ttydevsw_pktnotify(tp, TIOCPKT_FLUSHWRITE);
1628 }
1629 }
1630 if (flags & FREAD) {
1631 tty_hiwat_in_unblock(tp);
1632 ttyinq_flush(&tp->t_inq);
1633 tty_wakeup(tp, FREAD);
1634 if (!tty_gone(tp)) {
1635 ttydevsw_inwakeup(tp);
1636 ttydevsw_pktnotify(tp, TIOCPKT_FLUSHREAD);
1637 }
1638 }
1639 }
1640
1641 void
tty_set_winsize(struct tty * tp,const struct winsize * wsz)1642 tty_set_winsize(struct tty *tp, const struct winsize *wsz)
1643 {
1644
1645 if (memcmp(&tp->t_winsize, wsz, sizeof(*wsz)) == 0)
1646 return;
1647 tp->t_winsize = *wsz;
1648 tty_signal_pgrp(tp, SIGWINCH);
1649 }
1650
1651 static int
tty_sti_check(struct tty * tp,int fflag,struct thread * td)1652 tty_sti_check(struct tty *tp, int fflag, struct thread *td)
1653 {
1654 /* Root can bypass all of our constraints. */
1655 if (priv_check(td, PRIV_TTY_STI) == 0)
1656 return (0);
1657
1658 /* Unprivileged users must have it opened for read. */
1659 if ((fflag & FREAD) == 0)
1660 return (EPERM);
1661
1662 /* It must also be their controlling tty. */
1663 if (!tty_is_ctty(tp, td->td_proc))
1664 return (EACCES);
1665
1666 return (0);
1667 }
1668
1669 static int
tty_generic_ioctl(struct tty * tp,u_long cmd,void * data,int fflag,struct thread * td)1670 tty_generic_ioctl(struct tty *tp, u_long cmd, void *data, int fflag,
1671 struct thread *td)
1672 {
1673 int error;
1674
1675 switch (cmd) {
1676 /*
1677 * Modem commands.
1678 * The SER_* and TIOCM_* flags are the same, but one bit
1679 * shifted. I don't know why.
1680 */
1681 case TIOCSDTR:
1682 ttydevsw_modem(tp, SER_DTR, 0);
1683 return (0);
1684 case TIOCCDTR:
1685 ttydevsw_modem(tp, 0, SER_DTR);
1686 return (0);
1687 case TIOCMSET: {
1688 int bits = *(int *)data;
1689 ttydevsw_modem(tp,
1690 (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1,
1691 ((~bits) & (TIOCM_DTR | TIOCM_RTS)) >> 1);
1692 return (0);
1693 }
1694 case TIOCMBIS: {
1695 int bits = *(int *)data;
1696 ttydevsw_modem(tp, (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1, 0);
1697 return (0);
1698 }
1699 case TIOCMBIC: {
1700 int bits = *(int *)data;
1701 ttydevsw_modem(tp, 0, (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1);
1702 return (0);
1703 }
1704 case TIOCMGET:
1705 *(int *)data = TIOCM_LE + (ttydevsw_modem(tp, 0, 0) << 1);
1706 return (0);
1707
1708 case FIOASYNC:
1709 if (*(int *)data)
1710 tp->t_flags |= TF_ASYNC;
1711 else
1712 tp->t_flags &= ~TF_ASYNC;
1713 return (0);
1714 case FIONBIO:
1715 /* This device supports non-blocking operation. */
1716 return (0);
1717 case FIONREAD:
1718 *(int *)data = ttydisc_bytesavail(tp);
1719 return (0);
1720 case FIONWRITE:
1721 case TIOCOUTQ:
1722 *(int *)data = ttyoutq_bytesused(&tp->t_outq);
1723 return (0);
1724 case FIOSETOWN:
1725 if (tp->t_session != NULL && !tty_is_ctty(tp, td->td_proc))
1726 /* Not allowed to set ownership. */
1727 return (ENOTTY);
1728
1729 /* Temporarily unlock the TTY to set ownership. */
1730 tty_unlock(tp);
1731 error = fsetown(*(int *)data, &tp->t_sigio);
1732 tty_lock(tp);
1733 return (error);
1734 case FIOGETOWN:
1735 if (tp->t_session != NULL && !tty_is_ctty(tp, td->td_proc))
1736 /* Not allowed to set ownership. */
1737 return (ENOTTY);
1738
1739 /* Get ownership. */
1740 *(int *)data = fgetown(&tp->t_sigio);
1741 return (0);
1742 case TIOCGETA:
1743 /* Obtain terminal flags through tcgetattr(). */
1744 *(struct termios*)data = tp->t_termios;
1745 return (0);
1746 case TIOCSETA:
1747 case TIOCSETAW:
1748 case TIOCSETAF: {
1749 struct termios *t = data;
1750 bool canonicalize = false;
1751
1752 /*
1753 * Who makes up these funny rules? According to POSIX,
1754 * input baud rate is set equal to the output baud rate
1755 * when zero.
1756 */
1757 if (t->c_ispeed == 0)
1758 t->c_ispeed = t->c_ospeed;
1759
1760 /* Discard any unsupported bits. */
1761 t->c_iflag &= TTYSUP_IFLAG;
1762 t->c_oflag &= TTYSUP_OFLAG;
1763 t->c_lflag &= TTYSUP_LFLAG;
1764 t->c_cflag &= TTYSUP_CFLAG;
1765
1766 /* Set terminal flags through tcsetattr(). */
1767 if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
1768 error = tty_drain(tp, 0);
1769 if (error)
1770 return (error);
1771 if (cmd == TIOCSETAF)
1772 tty_flush(tp, FREAD);
1773 }
1774
1775 /*
1776 * Only call param() when the flags really change.
1777 */
1778 if ((t->c_cflag & CIGNORE) == 0 &&
1779 (tp->t_termios.c_cflag != t->c_cflag ||
1780 ((tp->t_termios.c_iflag ^ t->c_iflag) &
1781 (IXON|IXOFF|IXANY)) ||
1782 tp->t_termios.c_ispeed != t->c_ispeed ||
1783 tp->t_termios.c_ospeed != t->c_ospeed)) {
1784 error = ttydevsw_param(tp, t);
1785 if (error)
1786 return (error);
1787
1788 /* XXX: CLOCAL? */
1789
1790 tp->t_termios.c_cflag = t->c_cflag & ~CIGNORE;
1791 tp->t_termios.c_ispeed = t->c_ispeed;
1792 tp->t_termios.c_ospeed = t->c_ospeed;
1793
1794 /* Baud rate has changed - update watermarks. */
1795 error = tty_watermarks(tp);
1796 if (error)
1797 return (error);
1798 }
1799
1800 /*
1801 * We'll canonicalize any partial input if we're transitioning
1802 * ICANON one way or the other. If we're going from -ICANON ->
1803 * ICANON, then in the worst case scenario we're in the middle
1804 * of a line but both ttydisc_read() and FIONREAD will search
1805 * for one of our line terminals.
1806 */
1807 if ((t->c_lflag & ICANON) != (tp->t_termios.c_lflag & ICANON))
1808 canonicalize = true;
1809 else if (tp->t_termios.c_cc[VEOF] != t->c_cc[VEOF] ||
1810 tp->t_termios.c_cc[VEOL] != t->c_cc[VEOL])
1811 canonicalize = true;
1812
1813 /* Copy new non-device driver parameters. */
1814 tp->t_termios.c_iflag = t->c_iflag;
1815 tp->t_termios.c_oflag = t->c_oflag;
1816 tp->t_termios.c_lflag = t->c_lflag;
1817 memcpy(&tp->t_termios.c_cc, t->c_cc, sizeof t->c_cc);
1818
1819 ttydisc_optimize(tp);
1820
1821 if (canonicalize)
1822 ttydisc_canonicalize(tp);
1823 if ((t->c_lflag & ICANON) == 0) {
1824 /*
1825 * When in non-canonical mode, wake up all
1826 * readers. Any partial input has already been
1827 * canonicalized above if we were in canonical mode.
1828 * VMIN and VTIME could also be adjusted.
1829 */
1830 tty_wakeup(tp, FREAD);
1831 }
1832
1833 /*
1834 * For packet mode: notify the PTY consumer that VSTOP
1835 * and VSTART may have been changed.
1836 */
1837 if (tp->t_termios.c_iflag & IXON &&
1838 tp->t_termios.c_cc[VSTOP] == CTRL('S') &&
1839 tp->t_termios.c_cc[VSTART] == CTRL('Q'))
1840 ttydevsw_pktnotify(tp, TIOCPKT_DOSTOP);
1841 else
1842 ttydevsw_pktnotify(tp, TIOCPKT_NOSTOP);
1843 return (0);
1844 }
1845 case TIOCGETD:
1846 /* For compatibility - we only support TTYDISC. */
1847 *(int *)data = TTYDISC;
1848 return (0);
1849 case TIOCGPGRP:
1850 if (!tty_is_ctty(tp, td->td_proc))
1851 return (ENOTTY);
1852
1853 if (tp->t_pgrp != NULL)
1854 *(int *)data = tp->t_pgrp->pg_id;
1855 else
1856 *(int *)data = NO_PID;
1857 return (0);
1858 case TIOCGSID:
1859 if (!tty_is_ctty(tp, td->td_proc))
1860 return (ENOTTY);
1861
1862 MPASS(tp->t_session);
1863 *(int *)data = tp->t_session->s_sid;
1864 return (0);
1865 case TIOCNOTTY:
1866 return (tty_drop_ctty(tp, td->td_proc));
1867 case TIOCSCTTY: {
1868 struct proc *p = td->td_proc;
1869
1870 /* XXX: This looks awful. */
1871 tty_unlock(tp);
1872 sx_xlock(&proctree_lock);
1873 tty_lock(tp);
1874
1875 if (!SESS_LEADER(p)) {
1876 /* Only the session leader may do this. */
1877 sx_xunlock(&proctree_lock);
1878 return (EPERM);
1879 }
1880
1881 if (tp->t_session != NULL && tp->t_session == p->p_session) {
1882 /* This is already our controlling TTY. */
1883 sx_xunlock(&proctree_lock);
1884 return (0);
1885 }
1886
1887 if (p->p_session->s_ttyp != NULL ||
1888 (tp->t_session != NULL && tp->t_session->s_ttyvp != NULL &&
1889 tp->t_session->s_ttyvp->v_type != VBAD)) {
1890 /*
1891 * There is already a relation between a TTY and
1892 * a session, or the caller is not the session
1893 * leader.
1894 *
1895 * Allow the TTY to be stolen when the vnode is
1896 * invalid, but the reference to the TTY is
1897 * still active. This allows immediate reuse of
1898 * TTYs of which the session leader has been
1899 * killed or the TTY revoked.
1900 */
1901 sx_xunlock(&proctree_lock);
1902 return (EPERM);
1903 }
1904
1905 /* Connect the session to the TTY. */
1906 tp->t_session = p->p_session;
1907 tp->t_session->s_ttyp = tp;
1908 tp->t_sessioncnt++;
1909
1910 /* Assign foreground process group. */
1911 tp->t_pgrp = p->p_pgrp;
1912 PROC_LOCK(p);
1913 p->p_flag |= P_CONTROLT;
1914 PROC_UNLOCK(p);
1915
1916 sx_xunlock(&proctree_lock);
1917 return (0);
1918 }
1919 case TIOCSPGRP: {
1920 struct pgrp *pg;
1921
1922 /*
1923 * XXX: Temporarily unlock the TTY to locate the process
1924 * group. This code would be lot nicer if we would ever
1925 * decompose proctree_lock.
1926 */
1927 tty_unlock(tp);
1928 sx_slock(&proctree_lock);
1929 pg = pgfind(*(int *)data);
1930 if (pg != NULL)
1931 PGRP_UNLOCK(pg);
1932 if (pg == NULL || pg->pg_session != td->td_proc->p_session) {
1933 sx_sunlock(&proctree_lock);
1934 tty_lock(tp);
1935 return (EPERM);
1936 }
1937 tty_lock(tp);
1938
1939 /*
1940 * Determine if this TTY is the controlling TTY after
1941 * relocking the TTY.
1942 */
1943 if (!tty_is_ctty(tp, td->td_proc)) {
1944 sx_sunlock(&proctree_lock);
1945 return (ENOTTY);
1946 }
1947 tp->t_pgrp = pg;
1948 sx_sunlock(&proctree_lock);
1949
1950 /* Wake up the background process groups. */
1951 cv_broadcast(&tp->t_bgwait);
1952 return (0);
1953 }
1954 case TIOCFLUSH: {
1955 int flags = *(int *)data;
1956
1957 if (flags == 0)
1958 flags = (FREAD|FWRITE);
1959 else
1960 flags &= (FREAD|FWRITE);
1961 tty_flush(tp, flags);
1962 return (0);
1963 }
1964 case TIOCDRAIN:
1965 /* Drain TTY output. */
1966 return tty_drain(tp, 0);
1967 case TIOCGDRAINWAIT:
1968 *(int *)data = tp->t_drainwait;
1969 return (0);
1970 case TIOCSDRAINWAIT:
1971 error = priv_check(td, PRIV_TTY_DRAINWAIT);
1972 if (error == 0)
1973 tp->t_drainwait = *(int *)data;
1974 return (error);
1975 case TIOCCONS:
1976 /* Set terminal as console TTY. */
1977 if (*(int *)data) {
1978 error = priv_check(td, PRIV_TTY_CONSOLE);
1979 if (error)
1980 return (error);
1981 error = constty_set(tp);
1982 } else {
1983 error = constty_clear(tp);
1984 }
1985 return (error);
1986 case TIOCGWINSZ:
1987 /* Obtain window size. */
1988 *(struct winsize*)data = tp->t_winsize;
1989 return (0);
1990 case TIOCSWINSZ:
1991 /* Set window size. */
1992 tty_set_winsize(tp, data);
1993 return (0);
1994 case TIOCEXCL:
1995 tp->t_flags |= TF_EXCLUDE;
1996 return (0);
1997 case TIOCNXCL:
1998 tp->t_flags &= ~TF_EXCLUDE;
1999 return (0);
2000 case TIOCSTOP:
2001 tp->t_flags |= TF_STOPPED;
2002 ttydevsw_pktnotify(tp, TIOCPKT_STOP);
2003 return (0);
2004 case TIOCSTART:
2005 tp->t_flags &= ~TF_STOPPED;
2006 tp->t_termios.c_lflag &= ~FLUSHO;
2007 ttydevsw_outwakeup(tp);
2008 ttydevsw_pktnotify(tp, TIOCPKT_START);
2009 return (0);
2010 case TIOCSTAT:
2011 tty_info(tp);
2012 return (0);
2013 case TIOCSTI:
2014 error = tty_sti_check(tp, fflag, td);
2015 if (error != 0)
2016 return (error);
2017 ttydisc_rint(tp, *(char *)data, 0);
2018 ttydisc_rint_done(tp);
2019 return (0);
2020 }
2021
2022 #ifdef COMPAT_43TTY
2023 return tty_ioctl_compat(tp, cmd, data, fflag, td);
2024 #else /* !COMPAT_43TTY */
2025 return (ENOIOCTL);
2026 #endif /* COMPAT_43TTY */
2027 }
2028
2029 int
tty_ioctl(struct tty * tp,u_long cmd,void * data,int fflag,struct thread * td)2030 tty_ioctl(struct tty *tp, u_long cmd, void *data, int fflag, struct thread *td)
2031 {
2032 int error;
2033
2034 tty_assert_locked(tp);
2035
2036 if (tty_gone(tp))
2037 return (ENXIO);
2038
2039 error = ttydevsw_ioctl(tp, cmd, data, td);
2040 if (error == ENOIOCTL)
2041 error = tty_generic_ioctl(tp, cmd, data, fflag, td);
2042
2043 return (error);
2044 }
2045
2046 dev_t
tty_udev(struct tty * tp)2047 tty_udev(struct tty *tp)
2048 {
2049
2050 if (tp->t_dev)
2051 return (dev2udev(tp->t_dev));
2052 else
2053 return (NODEV);
2054 }
2055
2056 int
tty_checkoutq(struct tty * tp)2057 tty_checkoutq(struct tty *tp)
2058 {
2059
2060 /* 256 bytes should be enough to print a log message. */
2061 return (ttyoutq_bytesleft(&tp->t_outq) >= 256);
2062 }
2063
2064 void
tty_hiwat_in_block(struct tty * tp)2065 tty_hiwat_in_block(struct tty *tp)
2066 {
2067
2068 if ((tp->t_flags & TF_HIWAT_IN) == 0 &&
2069 tp->t_termios.c_iflag & IXOFF &&
2070 tp->t_termios.c_cc[VSTOP] != _POSIX_VDISABLE) {
2071 /*
2072 * Input flow control. Only enter the high watermark when we
2073 * can successfully store the VSTOP character.
2074 */
2075 if (ttyoutq_write_nofrag(&tp->t_outq,
2076 &tp->t_termios.c_cc[VSTOP], 1) == 0)
2077 tp->t_flags |= TF_HIWAT_IN;
2078 } else {
2079 /* No input flow control. */
2080 tp->t_flags |= TF_HIWAT_IN;
2081 }
2082 }
2083
2084 void
tty_hiwat_in_unblock(struct tty * tp)2085 tty_hiwat_in_unblock(struct tty *tp)
2086 {
2087
2088 if (tp->t_flags & TF_HIWAT_IN &&
2089 tp->t_termios.c_iflag & IXOFF &&
2090 tp->t_termios.c_cc[VSTART] != _POSIX_VDISABLE) {
2091 /*
2092 * Input flow control. Only leave the high watermark when we
2093 * can successfully store the VSTART character.
2094 */
2095 if (ttyoutq_write_nofrag(&tp->t_outq,
2096 &tp->t_termios.c_cc[VSTART], 1) == 0)
2097 tp->t_flags &= ~TF_HIWAT_IN;
2098 } else {
2099 /* No input flow control. */
2100 tp->t_flags &= ~TF_HIWAT_IN;
2101 }
2102
2103 if (!tty_gone(tp))
2104 ttydevsw_inwakeup(tp);
2105 }
2106
2107 /*
2108 * TTY hooks interface.
2109 */
2110
2111 static int
ttyhook_defrint(struct tty * tp,char c,int flags)2112 ttyhook_defrint(struct tty *tp, char c, int flags)
2113 {
2114
2115 if (ttyhook_rint_bypass(tp, &c, 1) != 1)
2116 return (-1);
2117
2118 return (0);
2119 }
2120
2121 int
ttyhook_register(struct tty ** rtp,struct proc * p,int fd,struct ttyhook * th,void * softc)2122 ttyhook_register(struct tty **rtp, struct proc *p, int fd, struct ttyhook *th,
2123 void *softc)
2124 {
2125 struct tty *tp;
2126 struct file *fp;
2127 struct cdev *dev;
2128 struct cdevsw *cdp;
2129 struct filedesc *fdp;
2130 cap_rights_t rights;
2131 int error, ref;
2132
2133 /* Validate the file descriptor. */
2134 /*
2135 * XXX this code inspects a file descriptor from a different process,
2136 * but there is no dedicated routine to do it in fd code, making the
2137 * ordeal highly questionable.
2138 */
2139 fdp = p->p_fd;
2140 FILEDESC_SLOCK(fdp);
2141 error = fget_cap_noref(fdp, fd, cap_rights_init_one(&rights, CAP_TTYHOOK),
2142 &fp, NULL);
2143 if (error == 0 && !fhold(fp))
2144 error = EBADF;
2145 FILEDESC_SUNLOCK(fdp);
2146 if (error != 0)
2147 return (error);
2148 if (fp->f_ops == &badfileops) {
2149 error = EBADF;
2150 goto done1;
2151 }
2152
2153 /*
2154 * Make sure the vnode is bound to a character device.
2155 * Unlocked check for the vnode type is ok there, because we
2156 * only shall prevent calling devvn_refthread on the file that
2157 * never has been opened over a character device.
2158 */
2159 if (fp->f_type != DTYPE_VNODE || fp->f_vnode->v_type != VCHR) {
2160 error = EINVAL;
2161 goto done1;
2162 }
2163
2164 /* Make sure it is a TTY. */
2165 cdp = devvn_refthread(fp->f_vnode, &dev, &ref);
2166 if (cdp == NULL) {
2167 error = ENXIO;
2168 goto done1;
2169 }
2170 if (dev != fp->f_data) {
2171 error = ENXIO;
2172 goto done2;
2173 }
2174 if (cdp != &ttydev_cdevsw) {
2175 error = ENOTTY;
2176 goto done2;
2177 }
2178 tp = dev->si_drv1;
2179
2180 /* Try to attach the hook to the TTY. */
2181 error = EBUSY;
2182 tty_lock(tp);
2183 MPASS((tp->t_hook == NULL) == ((tp->t_flags & TF_HOOK) == 0));
2184 if (tp->t_flags & TF_HOOK)
2185 goto done3;
2186
2187 tp->t_flags |= TF_HOOK;
2188 tp->t_hook = th;
2189 tp->t_hooksoftc = softc;
2190 *rtp = tp;
2191 error = 0;
2192
2193 /* Maybe we can switch into bypass mode now. */
2194 ttydisc_optimize(tp);
2195
2196 /* Silently convert rint() calls to rint_bypass() when possible. */
2197 if (!ttyhook_hashook(tp, rint) && ttyhook_hashook(tp, rint_bypass))
2198 th->th_rint = ttyhook_defrint;
2199
2200 done3: tty_unlock(tp);
2201 done2: dev_relthread(dev, ref);
2202 done1: fdrop(fp, curthread);
2203 return (error);
2204 }
2205
2206 void
ttyhook_unregister(struct tty * tp)2207 ttyhook_unregister(struct tty *tp)
2208 {
2209
2210 tty_assert_locked(tp);
2211 MPASS(tp->t_flags & TF_HOOK);
2212
2213 /* Disconnect the hook. */
2214 tp->t_flags &= ~TF_HOOK;
2215 tp->t_hook = NULL;
2216
2217 /* Maybe we need to leave bypass mode. */
2218 ttydisc_optimize(tp);
2219
2220 /* Maybe deallocate the TTY as well. */
2221 tty_rel_free(tp);
2222 }
2223
2224 /*
2225 * /dev/console handling.
2226 */
2227
2228 static int
ttyconsdev_open(struct cdev * dev,int oflags,int devtype,struct thread * td)2229 ttyconsdev_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
2230 {
2231 struct tty *tp;
2232
2233 /* System has no console device. */
2234 if (dev_console_filename == NULL)
2235 return (ENXIO);
2236
2237 /* Look up corresponding TTY by device name. */
2238 sx_slock(&tty_list_sx);
2239 TAILQ_FOREACH(tp, &tty_list, t_list) {
2240 if (strcmp(dev_console_filename, tty_devname(tp)) == 0) {
2241 dev_console->si_drv1 = tp;
2242 break;
2243 }
2244 }
2245 sx_sunlock(&tty_list_sx);
2246
2247 /* System console has no TTY associated. */
2248 if (dev_console->si_drv1 == NULL)
2249 return (ENXIO);
2250
2251 return (ttydev_open(dev, oflags, devtype, td));
2252 }
2253
2254 static int
ttyconsdev_write(struct cdev * dev,struct uio * uio,int ioflag)2255 ttyconsdev_write(struct cdev *dev, struct uio *uio, int ioflag)
2256 {
2257
2258 log_console(uio);
2259
2260 return (ttydev_write(dev, uio, ioflag));
2261 }
2262
2263 /*
2264 * /dev/console is a little different than normal TTY's. When opened,
2265 * it determines which TTY to use. When data gets written to it, it
2266 * will be logged in the kernel message buffer.
2267 */
2268 static struct cdevsw ttyconsdev_cdevsw = {
2269 .d_version = D_VERSION,
2270 .d_open = ttyconsdev_open,
2271 .d_close = ttydev_close,
2272 .d_read = ttydev_read,
2273 .d_write = ttyconsdev_write,
2274 .d_ioctl = ttydev_ioctl,
2275 .d_kqfilter = ttydev_kqfilter,
2276 .d_poll = ttydev_poll,
2277 .d_mmap = ttydev_mmap,
2278 .d_name = "ttyconsdev",
2279 .d_flags = D_TTY,
2280 };
2281
2282 static void
ttyconsdev_init(void * unused __unused)2283 ttyconsdev_init(void *unused __unused)
2284 {
2285
2286 dev_console = make_dev_credf(MAKEDEV_ETERNAL, &ttyconsdev_cdevsw, 0,
2287 NULL, UID_ROOT, GID_WHEEL, 0600, "console");
2288 }
2289
2290 SYSINIT(tty, SI_SUB_DRIVERS, SI_ORDER_FIRST, ttyconsdev_init, NULL);
2291
2292 void
ttyconsdev_select(const char * name)2293 ttyconsdev_select(const char *name)
2294 {
2295
2296 dev_console_filename = name;
2297 }
2298
2299 /*
2300 * Debugging routines.
2301 */
2302
2303 #include "opt_ddb.h"
2304 #ifdef DDB
2305 #include <ddb/ddb.h>
2306 #include <ddb/db_sym.h>
2307
2308 static const struct {
2309 int flag;
2310 char val;
2311 } ttystates[] = {
2312 #if 0
2313 { TF_NOPREFIX, 'N' },
2314 #endif
2315 { TF_INITLOCK, 'I' },
2316 { TF_CALLOUT, 'C' },
2317
2318 /* Keep these together -> 'Oi' and 'Oo'. */
2319 { TF_OPENED, 'O' },
2320 { TF_OPENED_IN, 'i' },
2321 { TF_OPENED_OUT, 'o' },
2322 { TF_OPENED_CONS, 'c' },
2323
2324 { TF_GONE, 'G' },
2325 { TF_OPENCLOSE, 'B' },
2326 { TF_ASYNC, 'Y' },
2327 { TF_LITERAL, 'L' },
2328
2329 /* Keep these together -> 'Hi' and 'Ho'. */
2330 { TF_HIWAT, 'H' },
2331 { TF_HIWAT_IN, 'i' },
2332 { TF_HIWAT_OUT, 'o' },
2333
2334 { TF_STOPPED, 'S' },
2335 { TF_EXCLUDE, 'X' },
2336 { TF_BYPASS, 'l' },
2337 { TF_ZOMBIE, 'Z' },
2338 { TF_HOOK, 's' },
2339
2340 /* Keep these together -> 'bi' and 'bo'. */
2341 { TF_BUSY, 'b' },
2342 { TF_BUSY_IN, 'i' },
2343 { TF_BUSY_OUT, 'o' },
2344
2345 { 0, '\0'},
2346 };
2347
2348 #define TTY_FLAG_BITS \
2349 "\20\1NOPREFIX\2INITLOCK\3CALLOUT\4OPENED_IN" \
2350 "\5OPENED_OUT\6OPENED_CONS\7GONE\10OPENCLOSE" \
2351 "\11ASYNC\12LITERAL\13HIWAT_IN\14HIWAT_OUT" \
2352 "\15STOPPED\16EXCLUDE\17BYPASS\20ZOMBIE" \
2353 "\21HOOK\22BUSY_IN\23BUSY_OUT"
2354
2355 #define DB_PRINTSYM(name, addr) \
2356 db_printf("%s " #name ": ", sep); \
2357 db_printsym((db_addr_t) addr, DB_STGY_ANY); \
2358 db_printf("\n");
2359
2360 static void
_db_show_devsw(const char * sep,const struct ttydevsw * tsw)2361 _db_show_devsw(const char *sep, const struct ttydevsw *tsw)
2362 {
2363
2364 db_printf("%sdevsw: ", sep);
2365 db_printsym((db_addr_t)tsw, DB_STGY_ANY);
2366 db_printf(" (%p)\n", tsw);
2367 DB_PRINTSYM(open, tsw->tsw_open);
2368 DB_PRINTSYM(close, tsw->tsw_close);
2369 DB_PRINTSYM(outwakeup, tsw->tsw_outwakeup);
2370 DB_PRINTSYM(inwakeup, tsw->tsw_inwakeup);
2371 DB_PRINTSYM(ioctl, tsw->tsw_ioctl);
2372 DB_PRINTSYM(param, tsw->tsw_param);
2373 DB_PRINTSYM(modem, tsw->tsw_modem);
2374 DB_PRINTSYM(mmap, tsw->tsw_mmap);
2375 DB_PRINTSYM(pktnotify, tsw->tsw_pktnotify);
2376 DB_PRINTSYM(free, tsw->tsw_free);
2377 }
2378
2379 static void
_db_show_hooks(const char * sep,const struct ttyhook * th)2380 _db_show_hooks(const char *sep, const struct ttyhook *th)
2381 {
2382
2383 db_printf("%shook: ", sep);
2384 db_printsym((db_addr_t)th, DB_STGY_ANY);
2385 db_printf(" (%p)\n", th);
2386 if (th == NULL)
2387 return;
2388 DB_PRINTSYM(rint, th->th_rint);
2389 DB_PRINTSYM(rint_bypass, th->th_rint_bypass);
2390 DB_PRINTSYM(rint_done, th->th_rint_done);
2391 DB_PRINTSYM(rint_poll, th->th_rint_poll);
2392 DB_PRINTSYM(getc_inject, th->th_getc_inject);
2393 DB_PRINTSYM(getc_capture, th->th_getc_capture);
2394 DB_PRINTSYM(getc_poll, th->th_getc_poll);
2395 DB_PRINTSYM(close, th->th_close);
2396 }
2397
2398 static void
_db_show_termios(const char * name,const struct termios * t)2399 _db_show_termios(const char *name, const struct termios *t)
2400 {
2401
2402 db_printf("%s: iflag 0x%x oflag 0x%x cflag 0x%x "
2403 "lflag 0x%x ispeed %u ospeed %u\n", name,
2404 t->c_iflag, t->c_oflag, t->c_cflag, t->c_lflag,
2405 t->c_ispeed, t->c_ospeed);
2406 }
2407
2408 /* DDB command to show TTY statistics. */
DB_SHOW_COMMAND(tty,db_show_tty)2409 DB_SHOW_COMMAND(tty, db_show_tty)
2410 {
2411 struct tty *tp;
2412
2413 if (!have_addr) {
2414 db_printf("usage: show tty <addr>\n");
2415 return;
2416 }
2417 tp = (struct tty *)addr;
2418
2419 db_printf("%p: %s\n", tp, tty_devname(tp));
2420 db_printf("\tmtx: %p\n", tp->t_mtx);
2421 db_printf("\tflags: 0x%b\n", tp->t_flags, TTY_FLAG_BITS);
2422 db_printf("\trevokecnt: %u\n", tp->t_revokecnt);
2423
2424 /* Buffering mechanisms. */
2425 db_printf("\tinq: %p begin %u linestart %u reprint %u end %u "
2426 "nblocks %u quota %u\n", &tp->t_inq, tp->t_inq.ti_begin,
2427 tp->t_inq.ti_linestart, tp->t_inq.ti_reprint, tp->t_inq.ti_end,
2428 tp->t_inq.ti_nblocks, tp->t_inq.ti_quota);
2429 db_printf("\toutq: %p begin %u end %u nblocks %u quota %u\n",
2430 &tp->t_outq, tp->t_outq.to_begin, tp->t_outq.to_end,
2431 tp->t_outq.to_nblocks, tp->t_outq.to_quota);
2432 db_printf("\tinlow: %zu\n", tp->t_inlow);
2433 db_printf("\toutlow: %zu\n", tp->t_outlow);
2434 _db_show_termios("\ttermios", &tp->t_termios);
2435 db_printf("\twinsize: row %u col %u xpixel %u ypixel %u\n",
2436 tp->t_winsize.ws_row, tp->t_winsize.ws_col,
2437 tp->t_winsize.ws_xpixel, tp->t_winsize.ws_ypixel);
2438 db_printf("\tcolumn: %u\n", tp->t_column);
2439 db_printf("\twritepos: %u\n", tp->t_writepos);
2440 db_printf("\tcompatflags: 0x%x\n", tp->t_compatflags);
2441
2442 /* Init/lock-state devices. */
2443 _db_show_termios("\ttermios_init_in", &tp->t_termios_init_in);
2444 _db_show_termios("\ttermios_init_out", &tp->t_termios_init_out);
2445 _db_show_termios("\ttermios_lock_in", &tp->t_termios_lock_in);
2446 _db_show_termios("\ttermios_lock_out", &tp->t_termios_lock_out);
2447
2448 /* Hooks */
2449 _db_show_devsw("\t", tp->t_devsw);
2450 _db_show_hooks("\t", tp->t_hook);
2451
2452 /* Process info. */
2453 db_printf("\tpgrp: %p gid %d\n", tp->t_pgrp,
2454 tp->t_pgrp ? tp->t_pgrp->pg_id : 0);
2455 db_printf("\tsession: %p", tp->t_session);
2456 if (tp->t_session != NULL)
2457 db_printf(" count %u leader %p tty %p sid %d login %s",
2458 tp->t_session->s_count, tp->t_session->s_leader,
2459 tp->t_session->s_ttyp, tp->t_session->s_sid,
2460 tp->t_session->s_login);
2461 db_printf("\n");
2462 db_printf("\tsessioncnt: %u\n", tp->t_sessioncnt);
2463 db_printf("\tdevswsoftc: %p\n", tp->t_devswsoftc);
2464 db_printf("\thooksoftc: %p\n", tp->t_hooksoftc);
2465 db_printf("\tdev: %p\n", tp->t_dev);
2466 }
2467
2468 /* DDB command to list TTYs. */
DB_SHOW_ALL_COMMAND(ttys,db_show_all_ttys)2469 DB_SHOW_ALL_COMMAND(ttys, db_show_all_ttys)
2470 {
2471 struct tty *tp;
2472 size_t isiz, osiz;
2473 int i, j;
2474
2475 /* Make the output look like `pstat -t'. */
2476 db_printf("PTR ");
2477 #if defined(__LP64__)
2478 db_printf(" ");
2479 #endif
2480 db_printf(" LINE INQ CAN LIN LOW OUTQ USE LOW "
2481 "COL SESS PGID STATE\n");
2482
2483 TAILQ_FOREACH(tp, &tty_list, t_list) {
2484 isiz = tp->t_inq.ti_nblocks * TTYINQ_DATASIZE;
2485 osiz = tp->t_outq.to_nblocks * TTYOUTQ_DATASIZE;
2486
2487 db_printf("%p %10s %5zu %4u %4u %4zu %5zu %4u %4zu %5u %5d "
2488 "%5d ", tp, tty_devname(tp), isiz,
2489 tp->t_inq.ti_linestart - tp->t_inq.ti_begin,
2490 tp->t_inq.ti_end - tp->t_inq.ti_linestart,
2491 isiz - tp->t_inlow, osiz,
2492 tp->t_outq.to_end - tp->t_outq.to_begin,
2493 osiz - tp->t_outlow, MIN(tp->t_column, 99999),
2494 tp->t_session ? tp->t_session->s_sid : 0,
2495 tp->t_pgrp ? tp->t_pgrp->pg_id : 0);
2496
2497 /* Flag bits. */
2498 for (i = j = 0; ttystates[i].flag; i++)
2499 if (tp->t_flags & ttystates[i].flag) {
2500 db_printf("%c", ttystates[i].val);
2501 j++;
2502 }
2503 if (j == 0)
2504 db_printf("-");
2505 db_printf("\n");
2506 }
2507 }
2508 #endif /* DDB */
2509