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