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