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