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