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