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