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