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