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