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