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