xref: /freebsd/sys/kern/tty.c (revision d1f97f76a596d948f6e61cc0dd67c8a96220ec29)
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 = 0;
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 
781 	switch (cmd) {
782 	case TIOCGETA:
783 		/* Obtain terminal flags through tcgetattr(). */
784 		*(struct termios*)data = *(struct termios*)dev->si_drv2;
785 		break;
786 	case TIOCSETA:
787 		/* Set terminal flags through tcsetattr(). */
788 		error = priv_check(td, PRIV_TTY_SETA);
789 		if (error)
790 			break;
791 		*(struct termios*)dev->si_drv2 = *(struct termios*)data;
792 		break;
793 	case TIOCGETD:
794 		*(int *)data = TTYDISC;
795 		break;
796 	case TIOCGWINSZ:
797 		bzero(data, sizeof(struct winsize));
798 		break;
799 	default:
800 		error = ENOTTY;
801 	}
802 
803 done:	tty_unlock(tp);
804 	return (error);
805 }
806 
807 static struct cdevsw ttyil_cdevsw = {
808 	.d_version	= D_VERSION,
809 	.d_open		= ttyil_open,
810 	.d_close	= ttyil_close,
811 	.d_read		= ttyil_rdwr,
812 	.d_write	= ttyil_rdwr,
813 	.d_ioctl	= ttyil_ioctl,
814 	.d_name		= "ttyil",
815 	.d_flags	= D_TTY,
816 };
817 
818 static void
819 tty_init_termios(struct tty *tp)
820 {
821 	struct termios *t = &tp->t_termios_init_in;
822 
823 	t->c_cflag = TTYDEF_CFLAG;
824 	t->c_iflag = TTYDEF_IFLAG;
825 	t->c_lflag = TTYDEF_LFLAG;
826 	t->c_oflag = TTYDEF_OFLAG;
827 	t->c_ispeed = TTYDEF_SPEED;
828 	t->c_ospeed = TTYDEF_SPEED;
829 	memcpy(&t->c_cc, ttydefchars, sizeof ttydefchars);
830 
831 	tp->t_termios_init_out = *t;
832 }
833 
834 void
835 tty_init_console(struct tty *tp, speed_t s)
836 {
837 	struct termios *ti = &tp->t_termios_init_in;
838 	struct termios *to = &tp->t_termios_init_out;
839 
840 	if (s != 0) {
841 		ti->c_ispeed = ti->c_ospeed = s;
842 		to->c_ispeed = to->c_ospeed = s;
843 	}
844 
845 	ti->c_cflag |= CLOCAL;
846 	to->c_cflag |= CLOCAL;
847 }
848 
849 /*
850  * Standard device routine implementations, mostly meant for
851  * pseudo-terminal device drivers. When a driver creates a new terminal
852  * device class, missing routines are patched.
853  */
854 
855 static int
856 ttydevsw_defopen(struct tty *tp)
857 {
858 
859 	return (0);
860 }
861 
862 static void
863 ttydevsw_defclose(struct tty *tp)
864 {
865 }
866 
867 static void
868 ttydevsw_defoutwakeup(struct tty *tp)
869 {
870 
871 	panic("Terminal device has output, while not implemented");
872 }
873 
874 static void
875 ttydevsw_definwakeup(struct tty *tp)
876 {
877 }
878 
879 static int
880 ttydevsw_defioctl(struct tty *tp, u_long cmd, caddr_t data, struct thread *td)
881 {
882 
883 	return (ENOIOCTL);
884 }
885 
886 static int
887 ttydevsw_defcioctl(struct tty *tp, int unit, u_long cmd, caddr_t data, struct thread *td)
888 {
889 
890 	return (ENOIOCTL);
891 }
892 
893 static int
894 ttydevsw_defparam(struct tty *tp, struct termios *t)
895 {
896 
897 	/*
898 	 * Allow the baud rate to be adjusted for pseudo-devices, but at
899 	 * least restrict it to 115200 to prevent excessive buffer
900 	 * usage.  Also disallow 0, to prevent foot shooting.
901 	 */
902 	if (t->c_ispeed < B50)
903 		t->c_ispeed = B50;
904 	else if (t->c_ispeed > B115200)
905 		t->c_ispeed = B115200;
906 	if (t->c_ospeed < B50)
907 		t->c_ospeed = B50;
908 	else if (t->c_ospeed > B115200)
909 		t->c_ospeed = B115200;
910 	t->c_cflag |= CREAD;
911 
912 	return (0);
913 }
914 
915 static int
916 ttydevsw_defmodem(struct tty *tp, int sigon, int sigoff)
917 {
918 
919 	/* Simulate a carrier to make the TTY layer happy. */
920 	return (SER_DCD);
921 }
922 
923 static int
924 ttydevsw_defmmap(struct tty *tp, vm_ooffset_t offset, vm_paddr_t *paddr,
925     int nprot, vm_memattr_t *memattr)
926 {
927 
928 	return (-1);
929 }
930 
931 static void
932 ttydevsw_defpktnotify(struct tty *tp, char event)
933 {
934 }
935 
936 static void
937 ttydevsw_deffree(void *softc)
938 {
939 
940 	panic("Terminal device freed without a free-handler");
941 }
942 
943 /*
944  * TTY allocation and deallocation. TTY devices can be deallocated when
945  * the driver doesn't use it anymore, when the TTY isn't a session's
946  * controlling TTY and when the device node isn't opened through devfs.
947  */
948 
949 struct tty *
950 tty_alloc(struct ttydevsw *tsw, void *sc)
951 {
952 
953 	return (tty_alloc_mutex(tsw, sc, NULL));
954 }
955 
956 struct tty *
957 tty_alloc_mutex(struct ttydevsw *tsw, void *sc, struct mtx *mutex)
958 {
959 	struct tty *tp;
960 
961 	/* Make sure the driver defines all routines. */
962 #define PATCH_FUNC(x) do {				\
963 	if (tsw->tsw_ ## x == NULL)			\
964 		tsw->tsw_ ## x = ttydevsw_def ## x;	\
965 } while (0)
966 	PATCH_FUNC(open);
967 	PATCH_FUNC(close);
968 	PATCH_FUNC(outwakeup);
969 	PATCH_FUNC(inwakeup);
970 	PATCH_FUNC(ioctl);
971 	PATCH_FUNC(cioctl);
972 	PATCH_FUNC(param);
973 	PATCH_FUNC(modem);
974 	PATCH_FUNC(mmap);
975 	PATCH_FUNC(pktnotify);
976 	PATCH_FUNC(free);
977 #undef PATCH_FUNC
978 
979 	tp = malloc(sizeof(struct tty), M_TTY, M_WAITOK|M_ZERO);
980 	tp->t_devsw = tsw;
981 	tp->t_devswsoftc = sc;
982 	tp->t_flags = tsw->tsw_flags;
983 
984 	tty_init_termios(tp);
985 
986 	cv_init(&tp->t_inwait, "ttyin");
987 	cv_init(&tp->t_outwait, "ttyout");
988 	cv_init(&tp->t_outserwait, "ttyosr");
989 	cv_init(&tp->t_bgwait, "ttybg");
990 	cv_init(&tp->t_dcdwait, "ttydcd");
991 
992 	/* Allow drivers to use a custom mutex to lock the TTY. */
993 	if (mutex != NULL) {
994 		tp->t_mtx = mutex;
995 	} else {
996 		tp->t_mtx = &tp->t_mtxobj;
997 		mtx_init(&tp->t_mtxobj, "ttymtx", NULL, MTX_DEF);
998 	}
999 
1000 	knlist_init_mtx(&tp->t_inpoll.si_note, tp->t_mtx);
1001 	knlist_init_mtx(&tp->t_outpoll.si_note, tp->t_mtx);
1002 
1003 	sx_xlock(&tty_list_sx);
1004 	TAILQ_INSERT_TAIL(&tty_list, tp, t_list);
1005 	tty_list_count++;
1006 	sx_xunlock(&tty_list_sx);
1007 
1008 	return (tp);
1009 }
1010 
1011 static void
1012 tty_dealloc(void *arg)
1013 {
1014 	struct tty *tp = arg;
1015 
1016 	sx_xlock(&tty_list_sx);
1017 	TAILQ_REMOVE(&tty_list, tp, t_list);
1018 	tty_list_count--;
1019 	sx_xunlock(&tty_list_sx);
1020 
1021 	/* Make sure we haven't leaked buffers. */
1022 	MPASS(ttyinq_getsize(&tp->t_inq) == 0);
1023 	MPASS(ttyoutq_getsize(&tp->t_outq) == 0);
1024 
1025 	seldrain(&tp->t_inpoll);
1026 	seldrain(&tp->t_outpoll);
1027 	knlist_destroy(&tp->t_inpoll.si_note);
1028 	knlist_destroy(&tp->t_outpoll.si_note);
1029 
1030 	cv_destroy(&tp->t_inwait);
1031 	cv_destroy(&tp->t_outwait);
1032 	cv_destroy(&tp->t_bgwait);
1033 	cv_destroy(&tp->t_dcdwait);
1034 	cv_destroy(&tp->t_outserwait);
1035 
1036 	if (tp->t_mtx == &tp->t_mtxobj)
1037 		mtx_destroy(&tp->t_mtxobj);
1038 	ttydevsw_free(tp);
1039 	free(tp, M_TTY);
1040 }
1041 
1042 static void
1043 tty_rel_free(struct tty *tp)
1044 {
1045 	struct cdev *dev;
1046 
1047 	tty_lock_assert(tp, MA_OWNED);
1048 
1049 #define	TF_ACTIVITY	(TF_GONE|TF_OPENED|TF_HOOK|TF_OPENCLOSE)
1050 	if (tp->t_sessioncnt != 0 || (tp->t_flags & TF_ACTIVITY) != TF_GONE) {
1051 		/* TTY is still in use. */
1052 		tty_unlock(tp);
1053 		return;
1054 	}
1055 
1056 	/* TTY can be deallocated. */
1057 	dev = tp->t_dev;
1058 	tp->t_dev = NULL;
1059 	tty_unlock(tp);
1060 
1061 	if (dev != NULL)
1062 		destroy_dev_sched_cb(dev, tty_dealloc, tp);
1063 }
1064 
1065 void
1066 tty_rel_pgrp(struct tty *tp, struct pgrp *pg)
1067 {
1068 	MPASS(tp->t_sessioncnt > 0);
1069 	tty_lock_assert(tp, MA_OWNED);
1070 
1071 	if (tp->t_pgrp == pg)
1072 		tp->t_pgrp = NULL;
1073 
1074 	tty_unlock(tp);
1075 }
1076 
1077 void
1078 tty_rel_sess(struct tty *tp, struct session *sess)
1079 {
1080 	MPASS(tp->t_sessioncnt > 0);
1081 
1082 	/* Current session has left. */
1083 	if (tp->t_session == sess) {
1084 		tp->t_session = NULL;
1085 		MPASS(tp->t_pgrp == NULL);
1086 	}
1087 	tp->t_sessioncnt--;
1088 	tty_rel_free(tp);
1089 }
1090 
1091 void
1092 tty_rel_gone(struct tty *tp)
1093 {
1094 	MPASS(!tty_gone(tp));
1095 
1096 	/* Simulate carrier removal. */
1097 	ttydisc_modem(tp, 0);
1098 
1099 	/* Wake up all blocked threads. */
1100 	tty_wakeup(tp, FREAD|FWRITE);
1101 	cv_broadcast(&tp->t_bgwait);
1102 	cv_broadcast(&tp->t_dcdwait);
1103 
1104 	tp->t_flags |= TF_GONE;
1105 	tty_rel_free(tp);
1106 }
1107 
1108 /*
1109  * Exposing information about current TTY's through sysctl
1110  */
1111 
1112 static void
1113 tty_to_xtty(struct tty *tp, struct xtty *xt)
1114 {
1115 	tty_lock_assert(tp, MA_OWNED);
1116 
1117 	xt->xt_size = sizeof(struct xtty);
1118 	xt->xt_insize = ttyinq_getsize(&tp->t_inq);
1119 	xt->xt_incc = ttyinq_bytescanonicalized(&tp->t_inq);
1120 	xt->xt_inlc = ttyinq_bytesline(&tp->t_inq);
1121 	xt->xt_inlow = tp->t_inlow;
1122 	xt->xt_outsize = ttyoutq_getsize(&tp->t_outq);
1123 	xt->xt_outcc = ttyoutq_bytesused(&tp->t_outq);
1124 	xt->xt_outlow = tp->t_outlow;
1125 	xt->xt_column = tp->t_column;
1126 	xt->xt_pgid = tp->t_pgrp ? tp->t_pgrp->pg_id : 0;
1127 	xt->xt_sid = tp->t_session ? tp->t_session->s_sid : 0;
1128 	xt->xt_flags = tp->t_flags;
1129 	xt->xt_dev = tp->t_dev ? dev2udev(tp->t_dev) : NODEV;
1130 }
1131 
1132 static int
1133 sysctl_kern_ttys(SYSCTL_HANDLER_ARGS)
1134 {
1135 	unsigned long lsize;
1136 	struct xtty *xtlist, *xt;
1137 	struct tty *tp;
1138 	int error;
1139 
1140 	sx_slock(&tty_list_sx);
1141 	lsize = tty_list_count * sizeof(struct xtty);
1142 	if (lsize == 0) {
1143 		sx_sunlock(&tty_list_sx);
1144 		return (0);
1145 	}
1146 
1147 	xtlist = xt = malloc(lsize, M_TTY, M_WAITOK);
1148 
1149 	TAILQ_FOREACH(tp, &tty_list, t_list) {
1150 		tty_lock(tp);
1151 		tty_to_xtty(tp, xt);
1152 		tty_unlock(tp);
1153 		xt++;
1154 	}
1155 	sx_sunlock(&tty_list_sx);
1156 
1157 	error = SYSCTL_OUT(req, xtlist, lsize);
1158 	free(xtlist, M_TTY);
1159 	return (error);
1160 }
1161 
1162 SYSCTL_PROC(_kern, OID_AUTO, ttys, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
1163 	0, 0, sysctl_kern_ttys, "S,xtty", "List of TTYs");
1164 
1165 /*
1166  * Device node creation. Device has been set up, now we can expose it to
1167  * the user.
1168  */
1169 
1170 void
1171 tty_makedev(struct tty *tp, struct ucred *cred, const char *fmt, ...)
1172 {
1173 	va_list ap;
1174 	struct cdev *dev;
1175 	const char *prefix = "tty";
1176 	char name[SPECNAMELEN - 3]; /* for "tty" and "cua". */
1177 	uid_t uid;
1178 	gid_t gid;
1179 	mode_t mode;
1180 
1181 	/* Remove "tty" prefix from devices like PTY's. */
1182 	if (tp->t_flags & TF_NOPREFIX)
1183 		prefix = "";
1184 
1185 	va_start(ap, fmt);
1186 	vsnrprintf(name, sizeof name, 32, fmt, ap);
1187 	va_end(ap);
1188 
1189 	if (cred == NULL) {
1190 		/* System device. */
1191 		uid = UID_ROOT;
1192 		gid = GID_WHEEL;
1193 		mode = S_IRUSR|S_IWUSR;
1194 	} else {
1195 		/* User device. */
1196 		uid = cred->cr_ruid;
1197 		gid = GID_TTY;
1198 		mode = S_IRUSR|S_IWUSR|S_IWGRP;
1199 	}
1200 
1201 	/* Master call-in device. */
1202 	dev = make_dev_cred(&ttydev_cdevsw, 0, cred,
1203 	    uid, gid, mode, "%s%s", prefix, name);
1204 	dev->si_drv1 = tp;
1205 	tp->t_dev = dev;
1206 
1207 	/* Slave call-in devices. */
1208 	if (tp->t_flags & TF_INITLOCK) {
1209 		dev = make_dev_cred(&ttyil_cdevsw, TTYUNIT_INIT, cred,
1210 		    uid, gid, mode, "%s%s.init", prefix, name);
1211 		dev_depends(tp->t_dev, dev);
1212 		dev->si_drv1 = tp;
1213 		dev->si_drv2 = &tp->t_termios_init_in;
1214 
1215 		dev = make_dev_cred(&ttyil_cdevsw, TTYUNIT_LOCK, cred,
1216 		    uid, gid, mode, "%s%s.lock", prefix, name);
1217 		dev_depends(tp->t_dev, dev);
1218 		dev->si_drv1 = tp;
1219 		dev->si_drv2 = &tp->t_termios_lock_in;
1220 	}
1221 
1222 	/* Call-out devices. */
1223 	if (tp->t_flags & TF_CALLOUT) {
1224 		dev = make_dev_cred(&ttydev_cdevsw, TTYUNIT_CALLOUT, cred,
1225 		    UID_UUCP, GID_DIALER, 0660, "cua%s", name);
1226 		dev_depends(tp->t_dev, dev);
1227 		dev->si_drv1 = tp;
1228 
1229 		/* Slave call-out devices. */
1230 		if (tp->t_flags & TF_INITLOCK) {
1231 			dev = make_dev_cred(&ttyil_cdevsw,
1232 			    TTYUNIT_CALLOUT | TTYUNIT_INIT, cred,
1233 			    UID_UUCP, GID_DIALER, 0660, "cua%s.init", name);
1234 			dev_depends(tp->t_dev, dev);
1235 			dev->si_drv1 = tp;
1236 			dev->si_drv2 = &tp->t_termios_init_out;
1237 
1238 			dev = make_dev_cred(&ttyil_cdevsw,
1239 			    TTYUNIT_CALLOUT | TTYUNIT_LOCK, cred,
1240 			    UID_UUCP, GID_DIALER, 0660, "cua%s.lock", name);
1241 			dev_depends(tp->t_dev, dev);
1242 			dev->si_drv1 = tp;
1243 			dev->si_drv2 = &tp->t_termios_lock_out;
1244 		}
1245 	}
1246 }
1247 
1248 /*
1249  * Signalling processes.
1250  */
1251 
1252 void
1253 tty_signal_sessleader(struct tty *tp, int sig)
1254 {
1255 	struct proc *p;
1256 
1257 	tty_lock_assert(tp, MA_OWNED);
1258 	MPASS(sig >= 1 && sig < NSIG);
1259 
1260 	/* Make signals start output again. */
1261 	tp->t_flags &= ~TF_STOPPED;
1262 
1263 	if (tp->t_session != NULL && tp->t_session->s_leader != NULL) {
1264 		p = tp->t_session->s_leader;
1265 		PROC_LOCK(p);
1266 		psignal(p, sig);
1267 		PROC_UNLOCK(p);
1268 	}
1269 }
1270 
1271 void
1272 tty_signal_pgrp(struct tty *tp, int sig)
1273 {
1274 	ksiginfo_t ksi;
1275 
1276 	tty_lock_assert(tp, MA_OWNED);
1277 	MPASS(sig >= 1 && sig < NSIG);
1278 
1279 	/* Make signals start output again. */
1280 	tp->t_flags &= ~TF_STOPPED;
1281 
1282 	if (sig == SIGINFO && !(tp->t_termios.c_lflag & NOKERNINFO))
1283 		tty_info(tp);
1284 	if (tp->t_pgrp != NULL) {
1285 		ksiginfo_init(&ksi);
1286 		ksi.ksi_signo = sig;
1287 		ksi.ksi_code = SI_KERNEL;
1288 		PGRP_LOCK(tp->t_pgrp);
1289 		pgsignal(tp->t_pgrp, sig, 1, &ksi);
1290 		PGRP_UNLOCK(tp->t_pgrp);
1291 	}
1292 }
1293 
1294 void
1295 tty_wakeup(struct tty *tp, int flags)
1296 {
1297 	if (tp->t_flags & TF_ASYNC && tp->t_sigio != NULL)
1298 		pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
1299 
1300 	if (flags & FWRITE) {
1301 		cv_broadcast(&tp->t_outwait);
1302 		selwakeup(&tp->t_outpoll);
1303 		KNOTE_LOCKED(&tp->t_outpoll.si_note, 0);
1304 	}
1305 	if (flags & FREAD) {
1306 		cv_broadcast(&tp->t_inwait);
1307 		selwakeup(&tp->t_inpoll);
1308 		KNOTE_LOCKED(&tp->t_inpoll.si_note, 0);
1309 	}
1310 }
1311 
1312 int
1313 tty_wait(struct tty *tp, struct cv *cv)
1314 {
1315 	int error;
1316 	int revokecnt = tp->t_revokecnt;
1317 
1318 	tty_lock_assert(tp, MA_OWNED|MA_NOTRECURSED);
1319 	MPASS(!tty_gone(tp));
1320 
1321 	error = cv_wait_sig(cv, tp->t_mtx);
1322 
1323 	/* Restart the system call when we may have been revoked. */
1324 	if (tp->t_revokecnt != revokecnt)
1325 		return (ERESTART);
1326 
1327 	/* Bail out when the device slipped away. */
1328 	if (tty_gone(tp))
1329 		return (ENXIO);
1330 
1331 	return (error);
1332 }
1333 
1334 int
1335 tty_timedwait(struct tty *tp, struct cv *cv, int hz)
1336 {
1337 	int error;
1338 	int revokecnt = tp->t_revokecnt;
1339 
1340 	tty_lock_assert(tp, MA_OWNED|MA_NOTRECURSED);
1341 	MPASS(!tty_gone(tp));
1342 
1343 	error = cv_timedwait_sig(cv, tp->t_mtx, hz);
1344 
1345 	/* Restart the system call when we may have been revoked. */
1346 	if (tp->t_revokecnt != revokecnt)
1347 		return (ERESTART);
1348 
1349 	/* Bail out when the device slipped away. */
1350 	if (tty_gone(tp))
1351 		return (ENXIO);
1352 
1353 	return (error);
1354 }
1355 
1356 void
1357 tty_flush(struct tty *tp, int flags)
1358 {
1359 	if (flags & FWRITE) {
1360 		tp->t_flags &= ~TF_HIWAT_OUT;
1361 		ttyoutq_flush(&tp->t_outq);
1362 		tty_wakeup(tp, FWRITE);
1363 		ttydevsw_pktnotify(tp, TIOCPKT_FLUSHWRITE);
1364 	}
1365 	if (flags & FREAD) {
1366 		tty_hiwat_in_unblock(tp);
1367 		ttyinq_flush(&tp->t_inq);
1368 		ttydevsw_inwakeup(tp);
1369 		ttydevsw_pktnotify(tp, TIOCPKT_FLUSHREAD);
1370 	}
1371 }
1372 
1373 static int
1374 tty_generic_ioctl(struct tty *tp, u_long cmd, void *data, int fflag,
1375     struct thread *td)
1376 {
1377 	int error;
1378 
1379 	switch (cmd) {
1380 	/*
1381 	 * Modem commands.
1382 	 * The SER_* and TIOCM_* flags are the same, but one bit
1383 	 * shifted. I don't know why.
1384 	 */
1385 	case TIOCSDTR:
1386 		ttydevsw_modem(tp, SER_DTR, 0);
1387 		return (0);
1388 	case TIOCCDTR:
1389 		ttydevsw_modem(tp, 0, SER_DTR);
1390 		return (0);
1391 	case TIOCMSET: {
1392 		int bits = *(int *)data;
1393 		ttydevsw_modem(tp,
1394 		    (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1,
1395 		    ((~bits) & (TIOCM_DTR | TIOCM_RTS)) >> 1);
1396 		return (0);
1397 	}
1398 	case TIOCMBIS: {
1399 		int bits = *(int *)data;
1400 		ttydevsw_modem(tp, (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1, 0);
1401 		return (0);
1402 	}
1403 	case TIOCMBIC: {
1404 		int bits = *(int *)data;
1405 		ttydevsw_modem(tp, 0, (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1);
1406 		return (0);
1407 	}
1408 	case TIOCMGET:
1409 		*(int *)data = TIOCM_LE + (ttydevsw_modem(tp, 0, 0) << 1);
1410 		return (0);
1411 
1412 	case FIOASYNC:
1413 		if (*(int *)data)
1414 			tp->t_flags |= TF_ASYNC;
1415 		else
1416 			tp->t_flags &= ~TF_ASYNC;
1417 		return (0);
1418 	case FIONBIO:
1419 		/* This device supports non-blocking operation. */
1420 		return (0);
1421 	case FIONREAD:
1422 		*(int *)data = ttyinq_bytescanonicalized(&tp->t_inq);
1423 		return (0);
1424 	case FIONWRITE:
1425 	case TIOCOUTQ:
1426 		*(int *)data = ttyoutq_bytesused(&tp->t_outq);
1427 		return (0);
1428 	case FIOSETOWN:
1429 		if (tp->t_session != NULL && !tty_is_ctty(tp, td->td_proc))
1430 			/* Not allowed to set ownership. */
1431 			return (ENOTTY);
1432 
1433 		/* Temporarily unlock the TTY to set ownership. */
1434 		tty_unlock(tp);
1435 		error = fsetown(*(int *)data, &tp->t_sigio);
1436 		tty_lock(tp);
1437 		return (error);
1438 	case FIOGETOWN:
1439 		if (tp->t_session != NULL && !tty_is_ctty(tp, td->td_proc))
1440 			/* Not allowed to set ownership. */
1441 			return (ENOTTY);
1442 
1443 		/* Get ownership. */
1444 		*(int *)data = fgetown(&tp->t_sigio);
1445 		return (0);
1446 	case TIOCGETA:
1447 		/* Obtain terminal flags through tcgetattr(). */
1448 		*(struct termios*)data = tp->t_termios;
1449 		return (0);
1450 	case TIOCSETA:
1451 	case TIOCSETAW:
1452 	case TIOCSETAF: {
1453 		struct termios *t = data;
1454 
1455 		/*
1456 		 * Who makes up these funny rules? According to POSIX,
1457 		 * input baud rate is set equal to the output baud rate
1458 		 * when zero.
1459 		 */
1460 		if (t->c_ispeed == 0)
1461 			t->c_ispeed = t->c_ospeed;
1462 
1463 		/* Discard any unsupported bits. */
1464 		t->c_iflag &= TTYSUP_IFLAG;
1465 		t->c_oflag &= TTYSUP_OFLAG;
1466 		t->c_lflag &= TTYSUP_LFLAG;
1467 		t->c_cflag &= TTYSUP_CFLAG;
1468 
1469 		/* Set terminal flags through tcsetattr(). */
1470 		if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
1471 			error = tty_drain(tp);
1472 			if (error)
1473 				return (error);
1474 			if (cmd == TIOCSETAF)
1475 				tty_flush(tp, FREAD);
1476 		}
1477 
1478 		/*
1479 		 * Only call param() when the flags really change.
1480 		 */
1481 		if ((t->c_cflag & CIGNORE) == 0 &&
1482 		    (tp->t_termios.c_cflag != t->c_cflag ||
1483 		    tp->t_termios.c_ispeed != t->c_ispeed ||
1484 		    tp->t_termios.c_ospeed != t->c_ospeed)) {
1485 			error = ttydevsw_param(tp, t);
1486 			if (error)
1487 				return (error);
1488 
1489 			/* XXX: CLOCAL? */
1490 
1491 			tp->t_termios.c_cflag = t->c_cflag & ~CIGNORE;
1492 			tp->t_termios.c_ispeed = t->c_ispeed;
1493 			tp->t_termios.c_ospeed = t->c_ospeed;
1494 
1495 			/* Baud rate has changed - update watermarks. */
1496 			tty_watermarks(tp);
1497 		}
1498 
1499 		/* Copy new non-device driver parameters. */
1500 		tp->t_termios.c_iflag = t->c_iflag;
1501 		tp->t_termios.c_oflag = t->c_oflag;
1502 		tp->t_termios.c_lflag = t->c_lflag;
1503 		memcpy(&tp->t_termios.c_cc, t->c_cc, sizeof t->c_cc);
1504 
1505 		ttydisc_optimize(tp);
1506 
1507 		if ((t->c_lflag & ICANON) == 0) {
1508 			/*
1509 			 * When in non-canonical mode, wake up all
1510 			 * readers. Canonicalize any partial input. VMIN
1511 			 * and VTIME could also be adjusted.
1512 			 */
1513 			ttyinq_canonicalize(&tp->t_inq);
1514 			tty_wakeup(tp, FREAD);
1515 		}
1516 
1517 		/*
1518 		 * For packet mode: notify the PTY consumer that VSTOP
1519 		 * and VSTART may have been changed.
1520 		 */
1521 		if (tp->t_termios.c_iflag & IXON &&
1522 		    tp->t_termios.c_cc[VSTOP] == CTRL('S') &&
1523 		    tp->t_termios.c_cc[VSTART] == CTRL('Q'))
1524 			ttydevsw_pktnotify(tp, TIOCPKT_DOSTOP);
1525 		else
1526 			ttydevsw_pktnotify(tp, TIOCPKT_NOSTOP);
1527 		return (0);
1528 	}
1529 	case TIOCGETD:
1530 		/* For compatibility - we only support TTYDISC. */
1531 		*(int *)data = TTYDISC;
1532 		return (0);
1533 	case TIOCGPGRP:
1534 		if (!tty_is_ctty(tp, td->td_proc))
1535 			return (ENOTTY);
1536 
1537 		if (tp->t_pgrp != NULL)
1538 			*(int *)data = tp->t_pgrp->pg_id;
1539 		else
1540 			*(int *)data = NO_PID;
1541 		return (0);
1542 	case TIOCGSID:
1543 		if (!tty_is_ctty(tp, td->td_proc))
1544 			return (ENOTTY);
1545 
1546 		MPASS(tp->t_session);
1547 		*(int *)data = tp->t_session->s_sid;
1548 		return (0);
1549 	case TIOCSCTTY: {
1550 		struct proc *p = td->td_proc;
1551 
1552 		/* XXX: This looks awful. */
1553 		tty_unlock(tp);
1554 		sx_xlock(&proctree_lock);
1555 		tty_lock(tp);
1556 
1557 		if (!SESS_LEADER(p)) {
1558 			/* Only the session leader may do this. */
1559 			sx_xunlock(&proctree_lock);
1560 			return (EPERM);
1561 		}
1562 
1563 		if (tp->t_session != NULL && tp->t_session == p->p_session) {
1564 			/* This is already our controlling TTY. */
1565 			sx_xunlock(&proctree_lock);
1566 			return (0);
1567 		}
1568 
1569 		if (p->p_session->s_ttyp != NULL ||
1570 		    (tp->t_session != NULL && tp->t_session->s_ttyvp != NULL &&
1571 		    tp->t_session->s_ttyvp->v_type != VBAD)) {
1572 			/*
1573 			 * There is already a relation between a TTY and
1574 			 * a session, or the caller is not the session
1575 			 * leader.
1576 			 *
1577 			 * Allow the TTY to be stolen when the vnode is
1578 			 * invalid, but the reference to the TTY is
1579 			 * still active.  This allows immediate reuse of
1580 			 * TTYs of which the session leader has been
1581 			 * killed or the TTY revoked.
1582 			 */
1583 			sx_xunlock(&proctree_lock);
1584 			return (EPERM);
1585 		}
1586 
1587 		/* Connect the session to the TTY. */
1588 		tp->t_session = p->p_session;
1589 		tp->t_session->s_ttyp = tp;
1590 		tp->t_sessioncnt++;
1591 		sx_xunlock(&proctree_lock);
1592 
1593 		/* Assign foreground process group. */
1594 		tp->t_pgrp = p->p_pgrp;
1595 		PROC_LOCK(p);
1596 		p->p_flag |= P_CONTROLT;
1597 		PROC_UNLOCK(p);
1598 
1599 		return (0);
1600 	}
1601 	case TIOCSPGRP: {
1602 		struct pgrp *pg;
1603 
1604 		/*
1605 		 * XXX: Temporarily unlock the TTY to locate the process
1606 		 * group. This code would be lot nicer if we would ever
1607 		 * decompose proctree_lock.
1608 		 */
1609 		tty_unlock(tp);
1610 		sx_slock(&proctree_lock);
1611 		pg = pgfind(*(int *)data);
1612 		if (pg != NULL)
1613 			PGRP_UNLOCK(pg);
1614 		if (pg == NULL || pg->pg_session != td->td_proc->p_session) {
1615 			sx_sunlock(&proctree_lock);
1616 			tty_lock(tp);
1617 			return (EPERM);
1618 		}
1619 		tty_lock(tp);
1620 
1621 		/*
1622 		 * Determine if this TTY is the controlling TTY after
1623 		 * relocking the TTY.
1624 		 */
1625 		if (!tty_is_ctty(tp, td->td_proc)) {
1626 			sx_sunlock(&proctree_lock);
1627 			return (ENOTTY);
1628 		}
1629 		tp->t_pgrp = pg;
1630 		sx_sunlock(&proctree_lock);
1631 
1632 		/* Wake up the background process groups. */
1633 		cv_broadcast(&tp->t_bgwait);
1634 		return (0);
1635 	}
1636 	case TIOCFLUSH: {
1637 		int flags = *(int *)data;
1638 
1639 		if (flags == 0)
1640 			flags = (FREAD|FWRITE);
1641 		else
1642 			flags &= (FREAD|FWRITE);
1643 		tty_flush(tp, flags);
1644 		return (0);
1645 	}
1646 	case TIOCDRAIN:
1647 		/* Drain TTY output. */
1648 		return tty_drain(tp);
1649 	case TIOCCONS:
1650 		/* Set terminal as console TTY. */
1651 		if (*(int *)data) {
1652 			error = priv_check(td, PRIV_TTY_CONSOLE);
1653 			if (error)
1654 				return (error);
1655 
1656 			/*
1657 			 * XXX: constty should really need to be locked!
1658 			 * XXX: allow disconnected constty's to be stolen!
1659 			 */
1660 
1661 			if (constty == tp)
1662 				return (0);
1663 			if (constty != NULL)
1664 				return (EBUSY);
1665 
1666 			tty_unlock(tp);
1667 			constty_set(tp);
1668 			tty_lock(tp);
1669 		} else if (constty == tp) {
1670 			constty_clear();
1671 		}
1672 		return (0);
1673 	case TIOCGWINSZ:
1674 		/* Obtain window size. */
1675 		*(struct winsize*)data = tp->t_winsize;
1676 		return (0);
1677 	case TIOCSWINSZ:
1678 		/* Set window size. */
1679 		if (bcmp(&tp->t_winsize, data, sizeof(struct winsize)) == 0)
1680 			return (0);
1681 		tp->t_winsize = *(struct winsize*)data;
1682 		tty_signal_pgrp(tp, SIGWINCH);
1683 		return (0);
1684 	case TIOCEXCL:
1685 		tp->t_flags |= TF_EXCLUDE;
1686 		return (0);
1687 	case TIOCNXCL:
1688 		tp->t_flags &= ~TF_EXCLUDE;
1689 		return (0);
1690 	case TIOCSTOP:
1691 		tp->t_flags |= TF_STOPPED;
1692 		ttydevsw_pktnotify(tp, TIOCPKT_STOP);
1693 		return (0);
1694 	case TIOCSTART:
1695 		tp->t_flags &= ~TF_STOPPED;
1696 		ttydevsw_outwakeup(tp);
1697 		ttydevsw_pktnotify(tp, TIOCPKT_START);
1698 		return (0);
1699 	case TIOCSTAT:
1700 		tty_info(tp);
1701 		return (0);
1702 	case TIOCSTI:
1703 		if ((fflag & FREAD) == 0 && priv_check(td, PRIV_TTY_STI))
1704 			return (EPERM);
1705 		if (!tty_is_ctty(tp, td->td_proc) &&
1706 		    priv_check(td, PRIV_TTY_STI))
1707 			return (EACCES);
1708 		ttydisc_rint(tp, *(char *)data, 0);
1709 		ttydisc_rint_done(tp);
1710 		return (0);
1711 	}
1712 
1713 #ifdef COMPAT_43TTY
1714 	return tty_ioctl_compat(tp, cmd, data, fflag, td);
1715 #else /* !COMPAT_43TTY */
1716 	return (ENOIOCTL);
1717 #endif /* COMPAT_43TTY */
1718 }
1719 
1720 int
1721 tty_ioctl(struct tty *tp, u_long cmd, void *data, int fflag, struct thread *td)
1722 {
1723 	int error;
1724 
1725 	tty_lock_assert(tp, MA_OWNED);
1726 
1727 	if (tty_gone(tp))
1728 		return (ENXIO);
1729 
1730 	error = ttydevsw_ioctl(tp, cmd, data, td);
1731 	if (error == ENOIOCTL)
1732 		error = tty_generic_ioctl(tp, cmd, data, fflag, td);
1733 
1734 	return (error);
1735 }
1736 
1737 dev_t
1738 tty_udev(struct tty *tp)
1739 {
1740 	if (tp->t_dev)
1741 		return dev2udev(tp->t_dev);
1742 	else
1743 		return NODEV;
1744 }
1745 
1746 int
1747 tty_checkoutq(struct tty *tp)
1748 {
1749 
1750 	/* 256 bytes should be enough to print a log message. */
1751 	return (ttyoutq_bytesleft(&tp->t_outq) >= 256);
1752 }
1753 
1754 void
1755 tty_hiwat_in_block(struct tty *tp)
1756 {
1757 
1758 	if ((tp->t_flags & TF_HIWAT_IN) == 0 &&
1759 	    tp->t_termios.c_iflag & IXOFF &&
1760 	    tp->t_termios.c_cc[VSTOP] != _POSIX_VDISABLE) {
1761 		/*
1762 		 * Input flow control. Only enter the high watermark when we
1763 		 * can successfully store the VSTOP character.
1764 		 */
1765 		if (ttyoutq_write_nofrag(&tp->t_outq,
1766 		    &tp->t_termios.c_cc[VSTOP], 1) == 0)
1767 			tp->t_flags |= TF_HIWAT_IN;
1768 	} else {
1769 		/* No input flow control. */
1770 		tp->t_flags |= TF_HIWAT_IN;
1771 	}
1772 }
1773 
1774 void
1775 tty_hiwat_in_unblock(struct tty *tp)
1776 {
1777 
1778 	if (tp->t_flags & TF_HIWAT_IN &&
1779 	    tp->t_termios.c_iflag & IXOFF &&
1780 	    tp->t_termios.c_cc[VSTART] != _POSIX_VDISABLE) {
1781 		/*
1782 		 * Input flow control. Only leave the high watermark when we
1783 		 * can successfully store the VSTART character.
1784 		 */
1785 		if (ttyoutq_write_nofrag(&tp->t_outq,
1786 		    &tp->t_termios.c_cc[VSTART], 1) == 0)
1787 			tp->t_flags &= ~TF_HIWAT_IN;
1788 	} else {
1789 		/* No input flow control. */
1790 		tp->t_flags &= ~TF_HIWAT_IN;
1791 	}
1792 
1793 	if (!tty_gone(tp))
1794 		ttydevsw_inwakeup(tp);
1795 }
1796 
1797 /*
1798  * TTY hooks interface.
1799  */
1800 
1801 static int
1802 ttyhook_defrint(struct tty *tp, char c, int flags)
1803 {
1804 
1805 	if (ttyhook_rint_bypass(tp, &c, 1) != 1)
1806 		return (-1);
1807 
1808 	return (0);
1809 }
1810 
1811 int
1812 ttyhook_register(struct tty **rtp, struct proc *p, int fd,
1813     struct ttyhook *th, void *softc)
1814 {
1815 	struct tty *tp;
1816 	struct file *fp;
1817 #ifdef CAPABILITIES
1818 	struct file *fp_cap;
1819 #endif
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 	fp_cap = fp;
1839 	error = cap_funwrap(fp_cap, CAP_TTYHOOK, &fp);
1840 	if (error)
1841 		return (error);
1842 #endif
1843 
1844 	/*
1845 	 * Make sure the vnode is bound to a character device.
1846 	 * Unlocked check for the vnode type is ok there, because we
1847 	 * only shall prevent calling devvn_refthread on the file that
1848 	 * never has been opened over a character device.
1849 	 */
1850 	if (fp->f_type != DTYPE_VNODE || fp->f_vnode->v_type != VCHR) {
1851 		error = EINVAL;
1852 		goto done1;
1853 	}
1854 
1855 	/* Make sure it is a TTY. */
1856 	cdp = devvn_refthread(fp->f_vnode, &dev, &ref);
1857 	if (cdp == NULL) {
1858 		error = ENXIO;
1859 		goto done1;
1860 	}
1861 	if (dev != fp->f_data) {
1862 		error = ENXIO;
1863 		goto done2;
1864 	}
1865 	if (cdp != &ttydev_cdevsw) {
1866 		error = ENOTTY;
1867 		goto done2;
1868 	}
1869 	tp = dev->si_drv1;
1870 
1871 	/* Try to attach the hook to the TTY. */
1872 	error = EBUSY;
1873 	tty_lock(tp);
1874 	MPASS((tp->t_hook == NULL) == ((tp->t_flags & TF_HOOK) == 0));
1875 	if (tp->t_flags & TF_HOOK)
1876 		goto done3;
1877 
1878 	tp->t_flags |= TF_HOOK;
1879 	tp->t_hook = th;
1880 	tp->t_hooksoftc = softc;
1881 	*rtp = tp;
1882 	error = 0;
1883 
1884 	/* Maybe we can switch into bypass mode now. */
1885 	ttydisc_optimize(tp);
1886 
1887 	/* Silently convert rint() calls to rint_bypass() when possible. */
1888 	if (!ttyhook_hashook(tp, rint) && ttyhook_hashook(tp, rint_bypass))
1889 		th->th_rint = ttyhook_defrint;
1890 
1891 done3:	tty_unlock(tp);
1892 done2:	dev_relthread(dev, ref);
1893 done1:	fdrop(fp, curthread);
1894 	return (error);
1895 }
1896 
1897 void
1898 ttyhook_unregister(struct tty *tp)
1899 {
1900 
1901 	tty_lock_assert(tp, MA_OWNED);
1902 	MPASS(tp->t_flags & TF_HOOK);
1903 
1904 	/* Disconnect the hook. */
1905 	tp->t_flags &= ~TF_HOOK;
1906 	tp->t_hook = NULL;
1907 
1908 	/* Maybe we need to leave bypass mode. */
1909 	ttydisc_optimize(tp);
1910 
1911 	/* Maybe deallocate the TTY as well. */
1912 	tty_rel_free(tp);
1913 }
1914 
1915 /*
1916  * /dev/console handling.
1917  */
1918 
1919 static int
1920 ttyconsdev_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
1921 {
1922 	struct tty *tp;
1923 
1924 	/* System has no console device. */
1925 	if (dev_console_filename == NULL)
1926 		return (ENXIO);
1927 
1928 	/* Look up corresponding TTY by device name. */
1929 	sx_slock(&tty_list_sx);
1930 	TAILQ_FOREACH(tp, &tty_list, t_list) {
1931 		if (strcmp(dev_console_filename, tty_devname(tp)) == 0) {
1932 			dev_console->si_drv1 = tp;
1933 			break;
1934 		}
1935 	}
1936 	sx_sunlock(&tty_list_sx);
1937 
1938 	/* System console has no TTY associated. */
1939 	if (dev_console->si_drv1 == NULL)
1940 		return (ENXIO);
1941 
1942 	return (ttydev_open(dev, oflags, devtype, td));
1943 }
1944 
1945 static int
1946 ttyconsdev_write(struct cdev *dev, struct uio *uio, int ioflag)
1947 {
1948 
1949 	log_console(uio);
1950 
1951 	return (ttydev_write(dev, uio, ioflag));
1952 }
1953 
1954 /*
1955  * /dev/console is a little different than normal TTY's.  When opened,
1956  * it determines which TTY to use.  When data gets written to it, it
1957  * will be logged in the kernel message buffer.
1958  */
1959 static struct cdevsw ttyconsdev_cdevsw = {
1960 	.d_version	= D_VERSION,
1961 	.d_open		= ttyconsdev_open,
1962 	.d_close	= ttydev_close,
1963 	.d_read		= ttydev_read,
1964 	.d_write	= ttyconsdev_write,
1965 	.d_ioctl	= ttydev_ioctl,
1966 	.d_kqfilter	= ttydev_kqfilter,
1967 	.d_poll		= ttydev_poll,
1968 	.d_mmap		= ttydev_mmap,
1969 	.d_name		= "ttyconsdev",
1970 	.d_flags	= D_TTY,
1971 };
1972 
1973 static void
1974 ttyconsdev_init(void *unused)
1975 {
1976 
1977 	dev_console = make_dev_credf(MAKEDEV_ETERNAL, &ttyconsdev_cdevsw, 0,
1978 	    NULL, UID_ROOT, GID_WHEEL, 0600, "console");
1979 }
1980 
1981 SYSINIT(tty, SI_SUB_DRIVERS, SI_ORDER_FIRST, ttyconsdev_init, NULL);
1982 
1983 void
1984 ttyconsdev_select(const char *name)
1985 {
1986 
1987 	dev_console_filename = name;
1988 }
1989 
1990 /*
1991  * Debugging routines.
1992  */
1993 
1994 #include "opt_ddb.h"
1995 #ifdef DDB
1996 #include <ddb/ddb.h>
1997 #include <ddb/db_sym.h>
1998 
1999 static struct {
2000 	int flag;
2001 	char val;
2002 } ttystates[] = {
2003 #if 0
2004 	{ TF_NOPREFIX,		'N' },
2005 #endif
2006 	{ TF_INITLOCK,		'I' },
2007 	{ TF_CALLOUT,		'C' },
2008 
2009 	/* Keep these together -> 'Oi' and 'Oo'. */
2010 	{ TF_OPENED,		'O' },
2011 	{ TF_OPENED_IN,		'i' },
2012 	{ TF_OPENED_OUT,	'o' },
2013 	{ TF_OPENED_CONS,	'c' },
2014 
2015 	{ TF_GONE,		'G' },
2016 	{ TF_OPENCLOSE,		'B' },
2017 	{ TF_ASYNC,		'Y' },
2018 	{ TF_LITERAL,		'L' },
2019 
2020 	/* Keep these together -> 'Hi' and 'Ho'. */
2021 	{ TF_HIWAT,		'H' },
2022 	{ TF_HIWAT_IN,		'i' },
2023 	{ TF_HIWAT_OUT,		'o' },
2024 
2025 	{ TF_STOPPED,		'S' },
2026 	{ TF_EXCLUDE,		'X' },
2027 	{ TF_BYPASS,		'l' },
2028 	{ TF_ZOMBIE,		'Z' },
2029 	{ TF_HOOK,		's' },
2030 
2031 	/* Keep these together -> 'bi' and 'bo'. */
2032 	{ TF_BUSY,		'b' },
2033 	{ TF_BUSY_IN,		'i' },
2034 	{ TF_BUSY_OUT,		'o' },
2035 
2036 	{ 0,			'\0'},
2037 };
2038 
2039 #define	TTY_FLAG_BITS \
2040 	"\20\1NOPREFIX\2INITLOCK\3CALLOUT\4OPENED_IN\5OPENED_OUT\6GONE" \
2041 	"\7OPENCLOSE\10ASYNC\11LITERAL\12HIWAT_IN\13HIWAT_OUT\14STOPPED" \
2042 	"\15EXCLUDE\16BYPASS\17ZOMBIE\20HOOK"
2043 
2044 #define DB_PRINTSYM(name, addr) \
2045 	db_printf("%s  " #name ": ", sep); \
2046 	db_printsym((db_addr_t) addr, DB_STGY_ANY); \
2047 	db_printf("\n");
2048 
2049 static void
2050 _db_show_devsw(const char *sep, const struct ttydevsw *tsw)
2051 {
2052 	db_printf("%sdevsw: ", sep);
2053 	db_printsym((db_addr_t)tsw, DB_STGY_ANY);
2054 	db_printf(" (%p)\n", tsw);
2055 	DB_PRINTSYM(open, tsw->tsw_open);
2056 	DB_PRINTSYM(close, tsw->tsw_close);
2057 	DB_PRINTSYM(outwakeup, tsw->tsw_outwakeup);
2058 	DB_PRINTSYM(inwakeup, tsw->tsw_inwakeup);
2059 	DB_PRINTSYM(ioctl, tsw->tsw_ioctl);
2060 	DB_PRINTSYM(param, tsw->tsw_param);
2061 	DB_PRINTSYM(modem, tsw->tsw_modem);
2062 	DB_PRINTSYM(mmap, tsw->tsw_mmap);
2063 	DB_PRINTSYM(pktnotify, tsw->tsw_pktnotify);
2064 	DB_PRINTSYM(free, tsw->tsw_free);
2065 }
2066 static void
2067 _db_show_hooks(const char *sep, const struct ttyhook *th)
2068 {
2069 	db_printf("%shook: ", sep);
2070 	db_printsym((db_addr_t)th, DB_STGY_ANY);
2071 	db_printf(" (%p)\n", th);
2072 	if (th == NULL)
2073 		return;
2074 	DB_PRINTSYM(rint, th->th_rint);
2075 	DB_PRINTSYM(rint_bypass, th->th_rint_bypass);
2076 	DB_PRINTSYM(rint_done, th->th_rint_done);
2077 	DB_PRINTSYM(rint_poll, th->th_rint_poll);
2078 	DB_PRINTSYM(getc_inject, th->th_getc_inject);
2079 	DB_PRINTSYM(getc_capture, th->th_getc_capture);
2080 	DB_PRINTSYM(getc_poll, th->th_getc_poll);
2081 	DB_PRINTSYM(close, th->th_close);
2082 }
2083 
2084 static void
2085 _db_show_termios(const char *name, const struct termios *t)
2086 {
2087 
2088 	db_printf("%s: iflag 0x%x oflag 0x%x cflag 0x%x "
2089 	    "lflag 0x%x ispeed %u ospeed %u\n", name,
2090 	    t->c_iflag, t->c_oflag, t->c_cflag, t->c_lflag,
2091 	    t->c_ispeed, t->c_ospeed);
2092 }
2093 
2094 /* DDB command to show TTY statistics. */
2095 DB_SHOW_COMMAND(tty, db_show_tty)
2096 {
2097 	struct tty *tp;
2098 
2099 	if (!have_addr) {
2100 		db_printf("usage: show tty <addr>\n");
2101 		return;
2102 	}
2103 	tp = (struct tty *)addr;
2104 
2105 	db_printf("0x%p: %s\n", tp, tty_devname(tp));
2106 	db_printf("\tmtx: %p\n", tp->t_mtx);
2107 	db_printf("\tflags: %b\n", tp->t_flags, TTY_FLAG_BITS);
2108 	db_printf("\trevokecnt: %u\n", tp->t_revokecnt);
2109 
2110 	/* Buffering mechanisms. */
2111 	db_printf("\tinq: %p begin %u linestart %u reprint %u end %u "
2112 	    "nblocks %u quota %u\n", &tp->t_inq, tp->t_inq.ti_begin,
2113 	    tp->t_inq.ti_linestart, tp->t_inq.ti_reprint, tp->t_inq.ti_end,
2114 	    tp->t_inq.ti_nblocks, tp->t_inq.ti_quota);
2115 	db_printf("\toutq: %p begin %u end %u nblocks %u quota %u\n",
2116 	    &tp->t_outq, tp->t_outq.to_begin, tp->t_outq.to_end,
2117 	    tp->t_outq.to_nblocks, tp->t_outq.to_quota);
2118 	db_printf("\tinlow: %zu\n", tp->t_inlow);
2119 	db_printf("\toutlow: %zu\n", tp->t_outlow);
2120 	_db_show_termios("\ttermios", &tp->t_termios);
2121 	db_printf("\twinsize: row %u col %u xpixel %u ypixel %u\n",
2122 	    tp->t_winsize.ws_row, tp->t_winsize.ws_col,
2123 	    tp->t_winsize.ws_xpixel, tp->t_winsize.ws_ypixel);
2124 	db_printf("\tcolumn: %u\n", tp->t_column);
2125 	db_printf("\twritepos: %u\n", tp->t_writepos);
2126 	db_printf("\tcompatflags: 0x%x\n", tp->t_compatflags);
2127 
2128 	/* Init/lock-state devices. */
2129 	_db_show_termios("\ttermios_init_in", &tp->t_termios_init_in);
2130 	_db_show_termios("\ttermios_init_out", &tp->t_termios_init_out);
2131 	_db_show_termios("\ttermios_lock_in", &tp->t_termios_lock_in);
2132 	_db_show_termios("\ttermios_lock_out", &tp->t_termios_lock_out);
2133 
2134 	/* Hooks */
2135 	_db_show_devsw("\t", tp->t_devsw);
2136 	_db_show_hooks("\t", tp->t_hook);
2137 
2138 	/* Process info. */
2139 	db_printf("\tpgrp: %p gid %d jobc %d\n", tp->t_pgrp,
2140 	    tp->t_pgrp ? tp->t_pgrp->pg_id : 0,
2141 	    tp->t_pgrp ? tp->t_pgrp->pg_jobc : 0);
2142 	db_printf("\tsession: %p", tp->t_session);
2143 	if (tp->t_session != NULL)
2144 	    db_printf(" count %u leader %p tty %p sid %d login %s",
2145 		tp->t_session->s_count, tp->t_session->s_leader,
2146 		tp->t_session->s_ttyp, tp->t_session->s_sid,
2147 		tp->t_session->s_login);
2148 	db_printf("\n");
2149 	db_printf("\tsessioncnt: %u\n", tp->t_sessioncnt);
2150 	db_printf("\tdevswsoftc: %p\n", tp->t_devswsoftc);
2151 	db_printf("\thooksoftc: %p\n", tp->t_hooksoftc);
2152 	db_printf("\tdev: %p\n", tp->t_dev);
2153 }
2154 
2155 /* DDB command to list TTYs. */
2156 DB_SHOW_ALL_COMMAND(ttys, db_show_all_ttys)
2157 {
2158 	struct tty *tp;
2159 	size_t isiz, osiz;
2160 	int i, j;
2161 
2162 	/* Make the output look like `pstat -t'. */
2163 	db_printf("PTR        ");
2164 #if defined(__LP64__)
2165 	db_printf("        ");
2166 #endif
2167 	db_printf("      LINE   INQ  CAN  LIN  LOW  OUTQ  USE  LOW   "
2168 	    "COL  SESS  PGID STATE\n");
2169 
2170 	TAILQ_FOREACH(tp, &tty_list, t_list) {
2171 		isiz = tp->t_inq.ti_nblocks * TTYINQ_DATASIZE;
2172 		osiz = tp->t_outq.to_nblocks * TTYOUTQ_DATASIZE;
2173 
2174 		db_printf("%p %10s %5zu %4u %4u %4zu %5zu %4u %4zu %5u %5d %5d ",
2175 		    tp,
2176 		    tty_devname(tp),
2177 		    isiz,
2178 		    tp->t_inq.ti_linestart - tp->t_inq.ti_begin,
2179 		    tp->t_inq.ti_end - tp->t_inq.ti_linestart,
2180 		    isiz - tp->t_inlow,
2181 		    osiz,
2182 		    tp->t_outq.to_end - tp->t_outq.to_begin,
2183 		    osiz - tp->t_outlow,
2184 		    MIN(tp->t_column, 99999),
2185 		    tp->t_session ? tp->t_session->s_sid : 0,
2186 		    tp->t_pgrp ? tp->t_pgrp->pg_id : 0);
2187 
2188 		/* Flag bits. */
2189 		for (i = j = 0; ttystates[i].flag; i++)
2190 			if (tp->t_flags & ttystates[i].flag) {
2191 				db_printf("%c", ttystates[i].val);
2192 				j++;
2193 			}
2194 		if (j == 0)
2195 			db_printf("-");
2196 		db_printf("\n");
2197 	}
2198 }
2199 #endif /* DDB */
2200