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