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