xref: /freebsd/sys/kern/tty.c (revision 9aaf4e3be61fc20a84347b7c2c524256a4b93a43)
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/kernel.h>
48 #include <sys/limits.h>
49 #include <sys/malloc.h>
50 #include <sys/mount.h>
51 #include <sys/poll.h>
52 #include <sys/priv.h>
53 #include <sys/proc.h>
54 #include <sys/serial.h>
55 #include <sys/signal.h>
56 #include <sys/stat.h>
57 #include <sys/sx.h>
58 #include <sys/sysctl.h>
59 #include <sys/systm.h>
60 #include <sys/tty.h>
61 #include <sys/ttycom.h>
62 #define TTYDEFCHARS
63 #include <sys/ttydefaults.h>
64 #undef TTYDEFCHARS
65 #include <sys/ucred.h>
66 #include <sys/vnode.h>
67 
68 #include <fs/devfs/devfs.h>
69 
70 #include <machine/stdarg.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 /*
105  * Set TTY buffer sizes.
106  */
107 
108 #define	TTYBUF_MAX	65536
109 
110 #ifdef PRINTF_BUFR_SIZE
111 #define	TTY_PRBUF_SIZE	PRINTF_BUFR_SIZE
112 #else
113 #define	TTY_PRBUF_SIZE	256
114 #endif
115 
116 /*
117  * Allocate buffer space if necessary, and set low watermarks, based on speed.
118  * Note that the ttyxxxq_setsize() functions may drop and then reacquire the tty
119  * lock during memory allocation.  They will return ENXIO if the tty disappears
120  * while unlocked.
121  */
122 static int
123 tty_watermarks(struct tty *tp)
124 {
125 	size_t bs = 0;
126 	int error;
127 
128 	/* Provide an input buffer for 2 seconds of data. */
129 	if (tp->t_termios.c_cflag & CREAD)
130 		bs = MIN(tp->t_termios.c_ispeed / 5, TTYBUF_MAX);
131 	error = ttyinq_setsize(&tp->t_inq, tp, bs);
132 	if (error != 0)
133 		return (error);
134 
135 	/* Set low watermark at 10% (when 90% is available). */
136 	tp->t_inlow = (ttyinq_getallocatedsize(&tp->t_inq) * 9) / 10;
137 
138 	/* Provide an output buffer for 2 seconds of data. */
139 	bs = MIN(tp->t_termios.c_ospeed / 5, TTYBUF_MAX);
140 	error = ttyoutq_setsize(&tp->t_outq, tp, bs);
141 	if (error != 0)
142 		return (error);
143 
144 	/* Set low watermark at 10% (when 90% is available). */
145 	tp->t_outlow = (ttyoutq_getallocatedsize(&tp->t_outq) * 9) / 10;
146 
147 	return (0);
148 }
149 
150 static int
151 tty_drain(struct tty *tp, int leaving)
152 {
153 	sbintime_t timeout_at;
154 	size_t bytes;
155 	int error;
156 
157 	if (ttyhook_hashook(tp, getc_inject))
158 		/* buffer is inaccessible */
159 		return (0);
160 
161 	/*
162 	 * For close(), use the recent historic timeout of "1 second without
163 	 * making progress".  For tcdrain(), use t_drainwait as the timeout,
164 	 * with zero meaning "no timeout" which gives POSIX behavior.
165 	 */
166 	if (leaving)
167 		timeout_at = getsbinuptime() + SBT_1S;
168 	else if (tp->t_drainwait != 0)
169 		timeout_at = getsbinuptime() + SBT_1S * tp->t_drainwait;
170 	else
171 		timeout_at = 0;
172 
173 	/*
174 	 * Poll the output buffer and the hardware for completion, at 10 Hz.
175 	 * Polling is required for devices which are not able to signal an
176 	 * interrupt when the transmitter becomes idle (most USB serial devs).
177 	 * The unusual structure of this loop ensures we check for busy one more
178 	 * time after tty_timedwait() returns EWOULDBLOCK, so that success has
179 	 * higher priority than timeout if the IO completed in the last 100mS.
180 	 */
181 	error = 0;
182 	bytes = ttyoutq_bytesused(&tp->t_outq);
183 	for (;;) {
184 		if (ttyoutq_bytesused(&tp->t_outq) == 0 && !ttydevsw_busy(tp))
185 			return (0);
186 		if (error != 0)
187 			return (error);
188 		ttydevsw_outwakeup(tp);
189 		error = tty_timedwait(tp, &tp->t_outwait, hz / 10);
190 		if (error != 0 && error != EWOULDBLOCK)
191 			return (error);
192 		else if (timeout_at == 0 || getsbinuptime() < timeout_at)
193 			error = 0;
194 		else if (leaving && ttyoutq_bytesused(&tp->t_outq) < bytes) {
195 			/* In close, making progress, grant an extra second. */
196 			error = 0;
197 			timeout_at += SBT_1S;
198 			bytes = ttyoutq_bytesused(&tp->t_outq);
199 		}
200 	}
201 }
202 
203 /*
204  * Though ttydev_enter() and ttydev_leave() seem to be related, they
205  * don't have to be used together. ttydev_enter() is used by the cdev
206  * operations to prevent an actual operation from being processed when
207  * the TTY has been abandoned. ttydev_leave() is used by ttydev_open()
208  * and ttydev_close() to determine whether per-TTY data should be
209  * deallocated.
210  */
211 
212 static __inline int
213 ttydev_enter(struct tty *tp)
214 {
215 
216 	tty_lock(tp);
217 
218 	if (tty_gone(tp) || !tty_opened(tp)) {
219 		/* Device is already gone. */
220 		tty_unlock(tp);
221 		return (ENXIO);
222 	}
223 
224 	return (0);
225 }
226 
227 static void
228 ttydev_leave(struct tty *tp)
229 {
230 
231 	tty_assert_locked(tp);
232 
233 	if (tty_opened(tp) || tp->t_flags & TF_OPENCLOSE) {
234 		/* Device is still opened somewhere. */
235 		tty_unlock(tp);
236 		return;
237 	}
238 
239 	tp->t_flags |= TF_OPENCLOSE;
240 
241 	/* Remove console TTY. */
242 	constty_clear(tp);
243 
244 	/* Drain any output. */
245 	if (!tty_gone(tp))
246 		tty_drain(tp, 1);
247 
248 	ttydisc_close(tp);
249 
250 	/* Free i/o queues now since they might be large. */
251 	ttyinq_free(&tp->t_inq);
252 	tp->t_inlow = 0;
253 	ttyoutq_free(&tp->t_outq);
254 	tp->t_outlow = 0;
255 
256 	knlist_clear(&tp->t_inpoll.si_note, 1);
257 	knlist_clear(&tp->t_outpoll.si_note, 1);
258 
259 	if (!tty_gone(tp))
260 		ttydevsw_close(tp);
261 
262 	tp->t_flags &= ~TF_OPENCLOSE;
263 	cv_broadcast(&tp->t_dcdwait);
264 	tty_rel_free(tp);
265 }
266 
267 /*
268  * Operations that are exposed through the character device in /dev.
269  */
270 static int
271 ttydev_open(struct cdev *dev, int oflags, int devtype __unused,
272     struct thread *td)
273 {
274 	struct tty *tp;
275 	int error;
276 
277 	tp = dev->si_drv1;
278 	error = 0;
279 	tty_lock(tp);
280 	if (tty_gone(tp)) {
281 		/* Device is already gone. */
282 		tty_unlock(tp);
283 		return (ENXIO);
284 	}
285 
286 	/*
287 	 * Block when other processes are currently opening or closing
288 	 * the TTY.
289 	 */
290 	while (tp->t_flags & TF_OPENCLOSE) {
291 		error = tty_wait(tp, &tp->t_dcdwait);
292 		if (error != 0) {
293 			tty_unlock(tp);
294 			return (error);
295 		}
296 	}
297 	tp->t_flags |= TF_OPENCLOSE;
298 
299 	/*
300 	 * Make sure the "tty" and "cua" device cannot be opened at the
301 	 * same time.  The console is a "tty" device.
302 	 */
303 	if (TTY_CALLOUT(tp, dev)) {
304 		if (tp->t_flags & (TF_OPENED_CONS | TF_OPENED_IN)) {
305 			error = EBUSY;
306 			goto done;
307 		}
308 	} else {
309 		if (tp->t_flags & TF_OPENED_OUT) {
310 			error = EBUSY;
311 			goto done;
312 		}
313 	}
314 
315 	if (tp->t_flags & TF_EXCLUDE && priv_check(td, PRIV_TTY_EXCLUSIVE)) {
316 		error = EBUSY;
317 		goto done;
318 	}
319 
320 	if (!tty_opened(tp)) {
321 		/* Set proper termios flags. */
322 		if (TTY_CALLOUT(tp, dev))
323 			tp->t_termios = tp->t_termios_init_out;
324 		else
325 			tp->t_termios = tp->t_termios_init_in;
326 		ttydevsw_param(tp, &tp->t_termios);
327 		/* Prevent modem control on callout devices and /dev/console. */
328 		if (TTY_CALLOUT(tp, dev) || dev == dev_console)
329 			tp->t_termios.c_cflag |= CLOCAL;
330 
331 		if ((tp->t_termios.c_cflag & CNO_RTSDTR) == 0)
332 			ttydevsw_modem(tp, SER_DTR|SER_RTS, 0);
333 
334 		error = ttydevsw_open(tp);
335 		if (error != 0)
336 			goto done;
337 
338 		ttydisc_open(tp);
339 		error = tty_watermarks(tp);
340 		if (error != 0)
341 			goto done;
342 	}
343 
344 	/* Wait for Carrier Detect. */
345 	if ((oflags & O_NONBLOCK) == 0 &&
346 	    (tp->t_termios.c_cflag & CLOCAL) == 0) {
347 		while ((ttydevsw_modem(tp, 0, 0) & SER_DCD) == 0) {
348 			error = tty_wait(tp, &tp->t_dcdwait);
349 			if (error != 0)
350 				goto done;
351 		}
352 	}
353 
354 	if (dev == dev_console)
355 		tp->t_flags |= TF_OPENED_CONS;
356 	else if (TTY_CALLOUT(tp, dev))
357 		tp->t_flags |= TF_OPENED_OUT;
358 	else
359 		tp->t_flags |= TF_OPENED_IN;
360 	MPASS((tp->t_flags & (TF_OPENED_CONS | TF_OPENED_IN)) == 0 ||
361 	    (tp->t_flags & TF_OPENED_OUT) == 0);
362 
363 done:	tp->t_flags &= ~TF_OPENCLOSE;
364 	cv_broadcast(&tp->t_dcdwait);
365 	ttydev_leave(tp);
366 
367 	return (error);
368 }
369 
370 static int
371 ttydev_close(struct cdev *dev, int fflag, int devtype __unused,
372     struct thread *td __unused)
373 {
374 	struct tty *tp = dev->si_drv1;
375 
376 	tty_lock(tp);
377 
378 	/*
379 	 * Don't actually close the device if it is being used as the
380 	 * console.
381 	 */
382 	MPASS((tp->t_flags & (TF_OPENED_CONS | TF_OPENED_IN)) == 0 ||
383 	    (tp->t_flags & TF_OPENED_OUT) == 0);
384 	if (dev == dev_console)
385 		tp->t_flags &= ~TF_OPENED_CONS;
386 	else
387 		tp->t_flags &= ~(TF_OPENED_IN|TF_OPENED_OUT);
388 
389 	if (tp->t_flags & TF_OPENED) {
390 		tty_unlock(tp);
391 		return (0);
392 	}
393 
394 	/* If revoking, flush output now to avoid draining it later. */
395 	if (fflag & FREVOKE)
396 		tty_flush(tp, FWRITE);
397 
398 	tp->t_flags &= ~TF_EXCLUDE;
399 
400 	/* Properly wake up threads that are stuck - revoke(). */
401 	tp->t_revokecnt++;
402 	tty_wakeup(tp, FREAD|FWRITE);
403 	cv_broadcast(&tp->t_bgwait);
404 	cv_broadcast(&tp->t_dcdwait);
405 
406 	ttydev_leave(tp);
407 
408 	return (0);
409 }
410 
411 static __inline int
412 tty_is_ctty(struct tty *tp, struct proc *p)
413 {
414 
415 	tty_assert_locked(tp);
416 
417 	return (p->p_session == tp->t_session && p->p_flag & P_CONTROLT);
418 }
419 
420 int
421 tty_wait_background(struct tty *tp, struct thread *td, int sig)
422 {
423 	struct proc *p;
424 	struct pgrp *pg;
425 	ksiginfo_t ksi;
426 	int error;
427 
428 	MPASS(sig == SIGTTIN || sig == SIGTTOU);
429 	tty_assert_locked(tp);
430 
431 	p = td->td_proc;
432 	for (;;) {
433 		pg = p->p_pgrp;
434 		PGRP_LOCK(pg);
435 		PROC_LOCK(p);
436 
437 		/*
438 		 * pg may no longer be our process group.
439 		 * Re-check after locking.
440 		 */
441 		if (p->p_pgrp != pg) {
442 			PROC_UNLOCK(p);
443 			PGRP_UNLOCK(pg);
444 			continue;
445 		}
446 
447 		/*
448 		 * The process should only sleep, when:
449 		 * - This terminal is the controlling terminal
450 		 * - Its process group is not the foreground process
451 		 *   group
452 		 * - The parent process isn't waiting for the child to
453 		 *   exit
454 		 * - the signal to send to the process isn't masked
455 		 */
456 		if (!tty_is_ctty(tp, p) || p->p_pgrp == tp->t_pgrp) {
457 			/* Allow the action to happen. */
458 			PROC_UNLOCK(p);
459 			PGRP_UNLOCK(pg);
460 			return (0);
461 		}
462 
463 		if (SIGISMEMBER(p->p_sigacts->ps_sigignore, sig) ||
464 		    SIGISMEMBER(td->td_sigmask, sig)) {
465 			/* Only allow them in write()/ioctl(). */
466 			PROC_UNLOCK(p);
467 			PGRP_UNLOCK(pg);
468 			return (sig == SIGTTOU ? 0 : EIO);
469 		}
470 
471 		if ((p->p_flag & P_PPWAIT) != 0 ||
472 		    (pg->pg_flags & PGRP_ORPHANED) != 0) {
473 			/* Don't allow the action to happen. */
474 			PROC_UNLOCK(p);
475 			PGRP_UNLOCK(pg);
476 			return (EIO);
477 		}
478 		PROC_UNLOCK(p);
479 
480 		/*
481 		 * Send the signal and sleep until we're the new
482 		 * foreground process group.
483 		 */
484 		if (sig != 0) {
485 			ksiginfo_init(&ksi);
486 			ksi.ksi_code = SI_KERNEL;
487 			ksi.ksi_signo = sig;
488 			sig = 0;
489 		}
490 
491 		pgsignal(pg, ksi.ksi_signo, 1, &ksi);
492 		PGRP_UNLOCK(pg);
493 
494 		error = tty_wait(tp, &tp->t_bgwait);
495 		if (error)
496 			return (error);
497 	}
498 }
499 
500 static int
501 ttydev_read(struct cdev *dev, struct uio *uio, int ioflag)
502 {
503 	struct tty *tp = dev->si_drv1;
504 	int error;
505 
506 	error = ttydev_enter(tp);
507 	if (error)
508 		goto done;
509 	error = ttydisc_read(tp, uio, ioflag);
510 	tty_unlock(tp);
511 
512 	/*
513 	 * The read() call should not throw an error when the device is
514 	 * being destroyed. Silently convert it to an EOF.
515 	 */
516 done:	if (error == ENXIO)
517 		error = 0;
518 	return (error);
519 }
520 
521 static int
522 ttydev_write(struct cdev *dev, struct uio *uio, int ioflag)
523 {
524 	struct tty *tp = dev->si_drv1;
525 	int defer, error;
526 
527 	error = ttydev_enter(tp);
528 	if (error)
529 		return (error);
530 
531 	if (tp->t_termios.c_lflag & TOSTOP) {
532 		error = tty_wait_background(tp, curthread, SIGTTOU);
533 		if (error)
534 			goto done;
535 	}
536 
537 	if (ioflag & IO_NDELAY && tp->t_flags & TF_BUSY_OUT) {
538 		/* Allow non-blocking writes to bypass serialization. */
539 		error = ttydisc_write(tp, uio, ioflag);
540 	} else {
541 		/* Serialize write() calls. */
542 		while (tp->t_flags & TF_BUSY_OUT) {
543 			error = tty_wait(tp, &tp->t_outserwait);
544 			if (error)
545 				goto done;
546 		}
547 
548 		tp->t_flags |= TF_BUSY_OUT;
549 		defer = sigdeferstop(SIGDEFERSTOP_ERESTART);
550 		error = ttydisc_write(tp, uio, ioflag);
551 		sigallowstop(defer);
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 	memset(xt, 0, sizeof(*xt));
1292 	xt->xt_size = sizeof(struct xtty);
1293 	xt->xt_insize = ttyinq_getsize(&tp->t_inq);
1294 	xt->xt_incc = ttyinq_bytescanonicalized(&tp->t_inq);
1295 	xt->xt_inlc = ttyinq_bytesline(&tp->t_inq);
1296 	xt->xt_inlow = tp->t_inlow;
1297 	xt->xt_outsize = ttyoutq_getsize(&tp->t_outq);
1298 	xt->xt_outcc = ttyoutq_bytesused(&tp->t_outq);
1299 	xt->xt_outlow = tp->t_outlow;
1300 	xt->xt_column = tp->t_column;
1301 	xt->xt_pgid = tp->t_pgrp ? tp->t_pgrp->pg_id : 0;
1302 	xt->xt_sid = tp->t_session ? tp->t_session->s_sid : 0;
1303 	xt->xt_flags = tp->t_flags;
1304 	xt->xt_dev = tp->t_dev ? dev2udev(tp->t_dev) : (uint32_t)NODEV;
1305 }
1306 
1307 static int
1308 sysctl_kern_ttys(SYSCTL_HANDLER_ARGS)
1309 {
1310 	unsigned long lsize;
1311 	struct xtty *xtlist, *xt;
1312 	struct tty *tp;
1313 	int error;
1314 
1315 	sx_slock(&tty_list_sx);
1316 	lsize = tty_list_count * sizeof(struct xtty);
1317 	if (lsize == 0) {
1318 		sx_sunlock(&tty_list_sx);
1319 		return (0);
1320 	}
1321 
1322 	xtlist = xt = malloc(lsize, M_TTY, M_WAITOK);
1323 
1324 	TAILQ_FOREACH(tp, &tty_list, t_list) {
1325 		tty_lock(tp);
1326 		tty_to_xtty(tp, xt);
1327 		tty_unlock(tp);
1328 		xt++;
1329 	}
1330 	sx_sunlock(&tty_list_sx);
1331 
1332 	error = SYSCTL_OUT(req, xtlist, lsize);
1333 	free(xtlist, M_TTY);
1334 	return (error);
1335 }
1336 
1337 SYSCTL_PROC(_kern, OID_AUTO, ttys, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
1338 	0, 0, sysctl_kern_ttys, "S,xtty", "List of TTYs");
1339 
1340 /*
1341  * Device node creation. Device has been set up, now we can expose it to
1342  * the user.
1343  */
1344 
1345 int
1346 tty_makedevf(struct tty *tp, struct ucred *cred, int flags,
1347     const char *fmt, ...)
1348 {
1349 	va_list ap;
1350 	struct make_dev_args args;
1351 	struct cdev *dev, *init, *lock, *cua, *cinit, *clock;
1352 	const char *prefix = "tty";
1353 	char name[SPECNAMELEN - 3]; /* for "tty" and "cua". */
1354 	uid_t uid;
1355 	gid_t gid;
1356 	mode_t mode;
1357 	int error;
1358 
1359 	/* Remove "tty" prefix from devices like PTY's. */
1360 	if (tp->t_flags & TF_NOPREFIX)
1361 		prefix = "";
1362 
1363 	va_start(ap, fmt);
1364 	vsnrprintf(name, sizeof name, 32, fmt, ap);
1365 	va_end(ap);
1366 
1367 	if (cred == NULL) {
1368 		/* System device. */
1369 		uid = UID_ROOT;
1370 		gid = GID_WHEEL;
1371 		mode = S_IRUSR|S_IWUSR;
1372 	} else {
1373 		/* User device. */
1374 		uid = cred->cr_ruid;
1375 		gid = GID_TTY;
1376 		mode = S_IRUSR|S_IWUSR|S_IWGRP;
1377 	}
1378 
1379 	flags = flags & TTYMK_CLONING ? MAKEDEV_REF : 0;
1380 	flags |= MAKEDEV_CHECKNAME;
1381 
1382 	/* Master call-in device. */
1383 	make_dev_args_init(&args);
1384 	args.mda_flags = flags;
1385 	args.mda_devsw = &ttydev_cdevsw;
1386 	args.mda_cr = cred;
1387 	args.mda_uid = uid;
1388 	args.mda_gid = gid;
1389 	args.mda_mode = mode;
1390 	args.mda_si_drv1 = tp;
1391 	error = make_dev_s(&args, &dev, "%s%s", prefix, name);
1392 	if (error != 0)
1393 		return (error);
1394 	tp->t_dev = dev;
1395 
1396 	init = lock = cua = cinit = clock = NULL;
1397 
1398 	/* Slave call-in devices. */
1399 	if (tp->t_flags & TF_INITLOCK) {
1400 		args.mda_devsw = &ttyil_cdevsw;
1401 		args.mda_unit = TTYUNIT_INIT;
1402 		args.mda_si_drv1 = tp;
1403 		args.mda_si_drv2 = &tp->t_termios_init_in;
1404 		error = make_dev_s(&args, &init, "%s%s.init", prefix, name);
1405 		if (error != 0)
1406 			goto fail;
1407 		dev_depends(dev, init);
1408 
1409 		args.mda_unit = TTYUNIT_LOCK;
1410 		args.mda_si_drv2 = &tp->t_termios_lock_in;
1411 		error = make_dev_s(&args, &lock, "%s%s.lock", prefix, name);
1412 		if (error != 0)
1413 			goto fail;
1414 		dev_depends(dev, lock);
1415 	}
1416 
1417 	/* Call-out devices. */
1418 	if (tp->t_flags & TF_CALLOUT) {
1419 		make_dev_args_init(&args);
1420 		args.mda_flags = flags;
1421 		args.mda_devsw = &ttydev_cdevsw;
1422 		args.mda_cr = cred;
1423 		args.mda_uid = UID_UUCP;
1424 		args.mda_gid = GID_DIALER;
1425 		args.mda_mode = 0660;
1426 		args.mda_unit = TTYUNIT_CALLOUT;
1427 		args.mda_si_drv1 = tp;
1428 		error = make_dev_s(&args, &cua, "cua%s", name);
1429 		if (error != 0)
1430 			goto fail;
1431 		dev_depends(dev, cua);
1432 
1433 		/* Slave call-out devices. */
1434 		if (tp->t_flags & TF_INITLOCK) {
1435 			args.mda_devsw = &ttyil_cdevsw;
1436 			args.mda_unit = TTYUNIT_CALLOUT | TTYUNIT_INIT;
1437 			args.mda_si_drv2 = &tp->t_termios_init_out;
1438 			error = make_dev_s(&args, &cinit, "cua%s.init", name);
1439 			if (error != 0)
1440 				goto fail;
1441 			dev_depends(dev, cinit);
1442 
1443 			args.mda_unit = TTYUNIT_CALLOUT | TTYUNIT_LOCK;
1444 			args.mda_si_drv2 = &tp->t_termios_lock_out;
1445 			error = make_dev_s(&args, &clock, "cua%s.lock", name);
1446 			if (error != 0)
1447 				goto fail;
1448 			dev_depends(dev, clock);
1449 		}
1450 	}
1451 
1452 	sx_xlock(&tty_list_sx);
1453 	TAILQ_INSERT_TAIL(&tty_list, tp, t_list);
1454 	tty_list_count++;
1455 	sx_xunlock(&tty_list_sx);
1456 
1457 	return (0);
1458 
1459 fail:
1460 	destroy_dev(dev);
1461 	if (init)
1462 		destroy_dev(init);
1463 	if (lock)
1464 		destroy_dev(lock);
1465 	if (cinit)
1466 		destroy_dev(cinit);
1467 	if (clock)
1468 		destroy_dev(clock);
1469 
1470 	return (error);
1471 }
1472 
1473 /*
1474  * Signalling processes.
1475  */
1476 
1477 void
1478 tty_signal_sessleader(struct tty *tp, int sig)
1479 {
1480 	struct proc *p;
1481 	struct session *s;
1482 
1483 	tty_assert_locked(tp);
1484 	MPASS(sig >= 1 && sig < NSIG);
1485 
1486 	/* Make signals start output again. */
1487 	tp->t_flags &= ~TF_STOPPED;
1488 	tp->t_termios.c_lflag &= ~FLUSHO;
1489 
1490 	/*
1491 	 * Load s_leader exactly once to avoid race where s_leader is
1492 	 * set to NULL by a concurrent invocation of killjobc() by the
1493 	 * session leader.  Note that we are not holding t_session's
1494 	 * lock for the read.
1495 	 */
1496 	if ((s = tp->t_session) != NULL &&
1497 	    (p = atomic_load_ptr(&s->s_leader)) != NULL) {
1498 		PROC_LOCK(p);
1499 		kern_psignal(p, sig);
1500 		PROC_UNLOCK(p);
1501 	}
1502 }
1503 
1504 void
1505 tty_signal_pgrp(struct tty *tp, int sig)
1506 {
1507 	ksiginfo_t ksi;
1508 
1509 	tty_assert_locked(tp);
1510 	MPASS(sig >= 1 && sig < NSIG);
1511 
1512 	/* Make signals start output again. */
1513 	tp->t_flags &= ~TF_STOPPED;
1514 	tp->t_termios.c_lflag &= ~FLUSHO;
1515 
1516 	if (sig == SIGINFO && !(tp->t_termios.c_lflag & NOKERNINFO))
1517 		tty_info(tp);
1518 	if (tp->t_pgrp != NULL) {
1519 		ksiginfo_init(&ksi);
1520 		ksi.ksi_signo = sig;
1521 		ksi.ksi_code = SI_KERNEL;
1522 		PGRP_LOCK(tp->t_pgrp);
1523 		pgsignal(tp->t_pgrp, sig, 1, &ksi);
1524 		PGRP_UNLOCK(tp->t_pgrp);
1525 	}
1526 }
1527 
1528 void
1529 tty_wakeup(struct tty *tp, int flags)
1530 {
1531 
1532 	if (tp->t_flags & TF_ASYNC && tp->t_sigio != NULL)
1533 		pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
1534 
1535 	if (flags & FWRITE) {
1536 		cv_broadcast(&tp->t_outwait);
1537 		selwakeup(&tp->t_outpoll);
1538 		KNOTE_LOCKED(&tp->t_outpoll.si_note, 0);
1539 	}
1540 	if (flags & FREAD) {
1541 		cv_broadcast(&tp->t_inwait);
1542 		selwakeup(&tp->t_inpoll);
1543 		KNOTE_LOCKED(&tp->t_inpoll.si_note, 0);
1544 	}
1545 }
1546 
1547 int
1548 tty_wait(struct tty *tp, struct cv *cv)
1549 {
1550 	int error;
1551 	int revokecnt = tp->t_revokecnt;
1552 
1553 	tty_lock_assert(tp, MA_OWNED|MA_NOTRECURSED);
1554 	MPASS(!tty_gone(tp));
1555 
1556 	error = cv_wait_sig(cv, tp->t_mtx);
1557 
1558 	/* Bail out when the device slipped away. */
1559 	if (tty_gone(tp))
1560 		return (ENXIO);
1561 
1562 	/* Restart the system call when we may have been revoked. */
1563 	if (tp->t_revokecnt != revokecnt)
1564 		return (ERESTART);
1565 
1566 	return (error);
1567 }
1568 
1569 int
1570 tty_timedwait(struct tty *tp, struct cv *cv, int hz)
1571 {
1572 	int error;
1573 	int revokecnt = tp->t_revokecnt;
1574 
1575 	tty_lock_assert(tp, MA_OWNED|MA_NOTRECURSED);
1576 	MPASS(!tty_gone(tp));
1577 
1578 	error = cv_timedwait_sig(cv, tp->t_mtx, hz);
1579 
1580 	/* Bail out when the device slipped away. */
1581 	if (tty_gone(tp))
1582 		return (ENXIO);
1583 
1584 	/* Restart the system call when we may have been revoked. */
1585 	if (tp->t_revokecnt != revokecnt)
1586 		return (ERESTART);
1587 
1588 	return (error);
1589 }
1590 
1591 void
1592 tty_flush(struct tty *tp, int flags)
1593 {
1594 
1595 	if (flags & FWRITE) {
1596 		tp->t_flags &= ~TF_HIWAT_OUT;
1597 		ttyoutq_flush(&tp->t_outq);
1598 		tty_wakeup(tp, FWRITE);
1599 		if (!tty_gone(tp)) {
1600 			ttydevsw_outwakeup(tp);
1601 			ttydevsw_pktnotify(tp, TIOCPKT_FLUSHWRITE);
1602 		}
1603 	}
1604 	if (flags & FREAD) {
1605 		tty_hiwat_in_unblock(tp);
1606 		ttyinq_flush(&tp->t_inq);
1607 		tty_wakeup(tp, FREAD);
1608 		if (!tty_gone(tp)) {
1609 			ttydevsw_inwakeup(tp);
1610 			ttydevsw_pktnotify(tp, TIOCPKT_FLUSHREAD);
1611 		}
1612 	}
1613 }
1614 
1615 void
1616 tty_set_winsize(struct tty *tp, const struct winsize *wsz)
1617 {
1618 
1619 	if (memcmp(&tp->t_winsize, wsz, sizeof(*wsz)) == 0)
1620 		return;
1621 	tp->t_winsize = *wsz;
1622 	tty_signal_pgrp(tp, SIGWINCH);
1623 }
1624 
1625 static int
1626 tty_generic_ioctl(struct tty *tp, u_long cmd, void *data, int fflag,
1627     struct thread *td)
1628 {
1629 	int error;
1630 
1631 	switch (cmd) {
1632 	/*
1633 	 * Modem commands.
1634 	 * The SER_* and TIOCM_* flags are the same, but one bit
1635 	 * shifted. I don't know why.
1636 	 */
1637 	case TIOCSDTR:
1638 		ttydevsw_modem(tp, SER_DTR, 0);
1639 		return (0);
1640 	case TIOCCDTR:
1641 		ttydevsw_modem(tp, 0, SER_DTR);
1642 		return (0);
1643 	case TIOCMSET: {
1644 		int bits = *(int *)data;
1645 		ttydevsw_modem(tp,
1646 		    (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1,
1647 		    ((~bits) & (TIOCM_DTR | TIOCM_RTS)) >> 1);
1648 		return (0);
1649 	}
1650 	case TIOCMBIS: {
1651 		int bits = *(int *)data;
1652 		ttydevsw_modem(tp, (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1, 0);
1653 		return (0);
1654 	}
1655 	case TIOCMBIC: {
1656 		int bits = *(int *)data;
1657 		ttydevsw_modem(tp, 0, (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1);
1658 		return (0);
1659 	}
1660 	case TIOCMGET:
1661 		*(int *)data = TIOCM_LE + (ttydevsw_modem(tp, 0, 0) << 1);
1662 		return (0);
1663 
1664 	case FIOASYNC:
1665 		if (*(int *)data)
1666 			tp->t_flags |= TF_ASYNC;
1667 		else
1668 			tp->t_flags &= ~TF_ASYNC;
1669 		return (0);
1670 	case FIONBIO:
1671 		/* This device supports non-blocking operation. */
1672 		return (0);
1673 	case FIONREAD:
1674 		*(int *)data = ttyinq_bytescanonicalized(&tp->t_inq);
1675 		return (0);
1676 	case FIONWRITE:
1677 	case TIOCOUTQ:
1678 		*(int *)data = ttyoutq_bytesused(&tp->t_outq);
1679 		return (0);
1680 	case FIOSETOWN:
1681 		if (tp->t_session != NULL && !tty_is_ctty(tp, td->td_proc))
1682 			/* Not allowed to set ownership. */
1683 			return (ENOTTY);
1684 
1685 		/* Temporarily unlock the TTY to set ownership. */
1686 		tty_unlock(tp);
1687 		error = fsetown(*(int *)data, &tp->t_sigio);
1688 		tty_lock(tp);
1689 		return (error);
1690 	case FIOGETOWN:
1691 		if (tp->t_session != NULL && !tty_is_ctty(tp, td->td_proc))
1692 			/* Not allowed to set ownership. */
1693 			return (ENOTTY);
1694 
1695 		/* Get ownership. */
1696 		*(int *)data = fgetown(&tp->t_sigio);
1697 		return (0);
1698 	case TIOCGETA:
1699 		/* Obtain terminal flags through tcgetattr(). */
1700 		*(struct termios*)data = tp->t_termios;
1701 		return (0);
1702 	case TIOCSETA:
1703 	case TIOCSETAW:
1704 	case TIOCSETAF: {
1705 		struct termios *t = data;
1706 
1707 		/*
1708 		 * Who makes up these funny rules? According to POSIX,
1709 		 * input baud rate is set equal to the output baud rate
1710 		 * when zero.
1711 		 */
1712 		if (t->c_ispeed == 0)
1713 			t->c_ispeed = t->c_ospeed;
1714 
1715 		/* Discard any unsupported bits. */
1716 		t->c_iflag &= TTYSUP_IFLAG;
1717 		t->c_oflag &= TTYSUP_OFLAG;
1718 		t->c_lflag &= TTYSUP_LFLAG;
1719 		t->c_cflag &= TTYSUP_CFLAG;
1720 
1721 		/* Set terminal flags through tcsetattr(). */
1722 		if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
1723 			error = tty_drain(tp, 0);
1724 			if (error)
1725 				return (error);
1726 			if (cmd == TIOCSETAF)
1727 				tty_flush(tp, FREAD);
1728 		}
1729 
1730 		/*
1731 		 * Only call param() when the flags really change.
1732 		 */
1733 		if ((t->c_cflag & CIGNORE) == 0 &&
1734 		    (tp->t_termios.c_cflag != t->c_cflag ||
1735 		    ((tp->t_termios.c_iflag ^ t->c_iflag) &
1736 		    (IXON|IXOFF|IXANY)) ||
1737 		    tp->t_termios.c_ispeed != t->c_ispeed ||
1738 		    tp->t_termios.c_ospeed != t->c_ospeed)) {
1739 			error = ttydevsw_param(tp, t);
1740 			if (error)
1741 				return (error);
1742 
1743 			/* XXX: CLOCAL? */
1744 
1745 			tp->t_termios.c_cflag = t->c_cflag & ~CIGNORE;
1746 			tp->t_termios.c_ispeed = t->c_ispeed;
1747 			tp->t_termios.c_ospeed = t->c_ospeed;
1748 
1749 			/* Baud rate has changed - update watermarks. */
1750 			error = tty_watermarks(tp);
1751 			if (error)
1752 				return (error);
1753 		}
1754 
1755 		/* Copy new non-device driver parameters. */
1756 		tp->t_termios.c_iflag = t->c_iflag;
1757 		tp->t_termios.c_oflag = t->c_oflag;
1758 		tp->t_termios.c_lflag = t->c_lflag;
1759 		memcpy(&tp->t_termios.c_cc, t->c_cc, sizeof t->c_cc);
1760 
1761 		ttydisc_optimize(tp);
1762 
1763 		if ((t->c_lflag & ICANON) == 0) {
1764 			/*
1765 			 * When in non-canonical mode, wake up all
1766 			 * readers. Canonicalize any partial input. VMIN
1767 			 * and VTIME could also be adjusted.
1768 			 */
1769 			ttyinq_canonicalize(&tp->t_inq);
1770 			tty_wakeup(tp, FREAD);
1771 		}
1772 
1773 		/*
1774 		 * For packet mode: notify the PTY consumer that VSTOP
1775 		 * and VSTART may have been changed.
1776 		 */
1777 		if (tp->t_termios.c_iflag & IXON &&
1778 		    tp->t_termios.c_cc[VSTOP] == CTRL('S') &&
1779 		    tp->t_termios.c_cc[VSTART] == CTRL('Q'))
1780 			ttydevsw_pktnotify(tp, TIOCPKT_DOSTOP);
1781 		else
1782 			ttydevsw_pktnotify(tp, TIOCPKT_NOSTOP);
1783 		return (0);
1784 	}
1785 	case TIOCGETD:
1786 		/* For compatibility - we only support TTYDISC. */
1787 		*(int *)data = TTYDISC;
1788 		return (0);
1789 	case TIOCGPGRP:
1790 		if (!tty_is_ctty(tp, td->td_proc))
1791 			return (ENOTTY);
1792 
1793 		if (tp->t_pgrp != NULL)
1794 			*(int *)data = tp->t_pgrp->pg_id;
1795 		else
1796 			*(int *)data = NO_PID;
1797 		return (0);
1798 	case TIOCGSID:
1799 		if (!tty_is_ctty(tp, td->td_proc))
1800 			return (ENOTTY);
1801 
1802 		MPASS(tp->t_session);
1803 		*(int *)data = tp->t_session->s_sid;
1804 		return (0);
1805 	case TIOCNOTTY:
1806 		return (tty_drop_ctty(tp, td->td_proc));
1807 	case TIOCSCTTY: {
1808 		struct proc *p = td->td_proc;
1809 
1810 		/* XXX: This looks awful. */
1811 		tty_unlock(tp);
1812 		sx_xlock(&proctree_lock);
1813 		tty_lock(tp);
1814 
1815 		if (!SESS_LEADER(p)) {
1816 			/* Only the session leader may do this. */
1817 			sx_xunlock(&proctree_lock);
1818 			return (EPERM);
1819 		}
1820 
1821 		if (tp->t_session != NULL && tp->t_session == p->p_session) {
1822 			/* This is already our controlling TTY. */
1823 			sx_xunlock(&proctree_lock);
1824 			return (0);
1825 		}
1826 
1827 		if (p->p_session->s_ttyp != NULL ||
1828 		    (tp->t_session != NULL && tp->t_session->s_ttyvp != NULL &&
1829 		    tp->t_session->s_ttyvp->v_type != VBAD)) {
1830 			/*
1831 			 * There is already a relation between a TTY and
1832 			 * a session, or the caller is not the session
1833 			 * leader.
1834 			 *
1835 			 * Allow the TTY to be stolen when the vnode is
1836 			 * invalid, but the reference to the TTY is
1837 			 * still active.  This allows immediate reuse of
1838 			 * TTYs of which the session leader has been
1839 			 * killed or the TTY revoked.
1840 			 */
1841 			sx_xunlock(&proctree_lock);
1842 			return (EPERM);
1843 		}
1844 
1845 		/* Connect the session to the TTY. */
1846 		tp->t_session = p->p_session;
1847 		tp->t_session->s_ttyp = tp;
1848 		tp->t_sessioncnt++;
1849 
1850 		/* Assign foreground process group. */
1851 		tp->t_pgrp = p->p_pgrp;
1852 		PROC_LOCK(p);
1853 		p->p_flag |= P_CONTROLT;
1854 		PROC_UNLOCK(p);
1855 
1856 		sx_xunlock(&proctree_lock);
1857 		return (0);
1858 	}
1859 	case TIOCSPGRP: {
1860 		struct pgrp *pg;
1861 
1862 		/*
1863 		 * XXX: Temporarily unlock the TTY to locate the process
1864 		 * group. This code would be lot nicer if we would ever
1865 		 * decompose proctree_lock.
1866 		 */
1867 		tty_unlock(tp);
1868 		sx_slock(&proctree_lock);
1869 		pg = pgfind(*(int *)data);
1870 		if (pg != NULL)
1871 			PGRP_UNLOCK(pg);
1872 		if (pg == NULL || pg->pg_session != td->td_proc->p_session) {
1873 			sx_sunlock(&proctree_lock);
1874 			tty_lock(tp);
1875 			return (EPERM);
1876 		}
1877 		tty_lock(tp);
1878 
1879 		/*
1880 		 * Determine if this TTY is the controlling TTY after
1881 		 * relocking the TTY.
1882 		 */
1883 		if (!tty_is_ctty(tp, td->td_proc)) {
1884 			sx_sunlock(&proctree_lock);
1885 			return (ENOTTY);
1886 		}
1887 		tp->t_pgrp = pg;
1888 		sx_sunlock(&proctree_lock);
1889 
1890 		/* Wake up the background process groups. */
1891 		cv_broadcast(&tp->t_bgwait);
1892 		return (0);
1893 	}
1894 	case TIOCFLUSH: {
1895 		int flags = *(int *)data;
1896 
1897 		if (flags == 0)
1898 			flags = (FREAD|FWRITE);
1899 		else
1900 			flags &= (FREAD|FWRITE);
1901 		tty_flush(tp, flags);
1902 		return (0);
1903 	}
1904 	case TIOCDRAIN:
1905 		/* Drain TTY output. */
1906 		return tty_drain(tp, 0);
1907 	case TIOCGDRAINWAIT:
1908 		*(int *)data = tp->t_drainwait;
1909 		return (0);
1910 	case TIOCSDRAINWAIT:
1911 		error = priv_check(td, PRIV_TTY_DRAINWAIT);
1912 		if (error == 0)
1913 			tp->t_drainwait = *(int *)data;
1914 		return (error);
1915 	case TIOCCONS:
1916 		/* Set terminal as console TTY. */
1917 		if (*(int *)data) {
1918 			error = priv_check(td, PRIV_TTY_CONSOLE);
1919 			if (error)
1920 				return (error);
1921 			error = constty_set(tp);
1922 		} else {
1923 			error = constty_clear(tp);
1924 		}
1925 		return (error);
1926 	case TIOCGWINSZ:
1927 		/* Obtain window size. */
1928 		*(struct winsize*)data = tp->t_winsize;
1929 		return (0);
1930 	case TIOCSWINSZ:
1931 		/* Set window size. */
1932 		tty_set_winsize(tp, data);
1933 		return (0);
1934 	case TIOCEXCL:
1935 		tp->t_flags |= TF_EXCLUDE;
1936 		return (0);
1937 	case TIOCNXCL:
1938 		tp->t_flags &= ~TF_EXCLUDE;
1939 		return (0);
1940 	case TIOCSTOP:
1941 		tp->t_flags |= TF_STOPPED;
1942 		ttydevsw_pktnotify(tp, TIOCPKT_STOP);
1943 		return (0);
1944 	case TIOCSTART:
1945 		tp->t_flags &= ~TF_STOPPED;
1946 		tp->t_termios.c_lflag &= ~FLUSHO;
1947 		ttydevsw_outwakeup(tp);
1948 		ttydevsw_pktnotify(tp, TIOCPKT_START);
1949 		return (0);
1950 	case TIOCSTAT:
1951 		tty_info(tp);
1952 		return (0);
1953 	case TIOCSTI:
1954 		if ((fflag & FREAD) == 0 && priv_check(td, PRIV_TTY_STI))
1955 			return (EPERM);
1956 		if (!tty_is_ctty(tp, td->td_proc) &&
1957 		    priv_check(td, PRIV_TTY_STI))
1958 			return (EACCES);
1959 		ttydisc_rint(tp, *(char *)data, 0);
1960 		ttydisc_rint_done(tp);
1961 		return (0);
1962 	}
1963 
1964 #ifdef COMPAT_43TTY
1965 	return tty_ioctl_compat(tp, cmd, data, fflag, td);
1966 #else /* !COMPAT_43TTY */
1967 	return (ENOIOCTL);
1968 #endif /* COMPAT_43TTY */
1969 }
1970 
1971 int
1972 tty_ioctl(struct tty *tp, u_long cmd, void *data, int fflag, struct thread *td)
1973 {
1974 	int error;
1975 
1976 	tty_assert_locked(tp);
1977 
1978 	if (tty_gone(tp))
1979 		return (ENXIO);
1980 
1981 	error = ttydevsw_ioctl(tp, cmd, data, td);
1982 	if (error == ENOIOCTL)
1983 		error = tty_generic_ioctl(tp, cmd, data, fflag, td);
1984 
1985 	return (error);
1986 }
1987 
1988 dev_t
1989 tty_udev(struct tty *tp)
1990 {
1991 
1992 	if (tp->t_dev)
1993 		return (dev2udev(tp->t_dev));
1994 	else
1995 		return (NODEV);
1996 }
1997 
1998 int
1999 tty_checkoutq(struct tty *tp)
2000 {
2001 
2002 	/* 256 bytes should be enough to print a log message. */
2003 	return (ttyoutq_bytesleft(&tp->t_outq) >= 256);
2004 }
2005 
2006 void
2007 tty_hiwat_in_block(struct tty *tp)
2008 {
2009 
2010 	if ((tp->t_flags & TF_HIWAT_IN) == 0 &&
2011 	    tp->t_termios.c_iflag & IXOFF &&
2012 	    tp->t_termios.c_cc[VSTOP] != _POSIX_VDISABLE) {
2013 		/*
2014 		 * Input flow control. Only enter the high watermark when we
2015 		 * can successfully store the VSTOP character.
2016 		 */
2017 		if (ttyoutq_write_nofrag(&tp->t_outq,
2018 		    &tp->t_termios.c_cc[VSTOP], 1) == 0)
2019 			tp->t_flags |= TF_HIWAT_IN;
2020 	} else {
2021 		/* No input flow control. */
2022 		tp->t_flags |= TF_HIWAT_IN;
2023 	}
2024 }
2025 
2026 void
2027 tty_hiwat_in_unblock(struct tty *tp)
2028 {
2029 
2030 	if (tp->t_flags & TF_HIWAT_IN &&
2031 	    tp->t_termios.c_iflag & IXOFF &&
2032 	    tp->t_termios.c_cc[VSTART] != _POSIX_VDISABLE) {
2033 		/*
2034 		 * Input flow control. Only leave the high watermark when we
2035 		 * can successfully store the VSTART character.
2036 		 */
2037 		if (ttyoutq_write_nofrag(&tp->t_outq,
2038 		    &tp->t_termios.c_cc[VSTART], 1) == 0)
2039 			tp->t_flags &= ~TF_HIWAT_IN;
2040 	} else {
2041 		/* No input flow control. */
2042 		tp->t_flags &= ~TF_HIWAT_IN;
2043 	}
2044 
2045 	if (!tty_gone(tp))
2046 		ttydevsw_inwakeup(tp);
2047 }
2048 
2049 /*
2050  * TTY hooks interface.
2051  */
2052 
2053 static int
2054 ttyhook_defrint(struct tty *tp, char c, int flags)
2055 {
2056 
2057 	if (ttyhook_rint_bypass(tp, &c, 1) != 1)
2058 		return (-1);
2059 
2060 	return (0);
2061 }
2062 
2063 int
2064 ttyhook_register(struct tty **rtp, struct proc *p, int fd, struct ttyhook *th,
2065     void *softc)
2066 {
2067 	struct tty *tp;
2068 	struct file *fp;
2069 	struct cdev *dev;
2070 	struct cdevsw *cdp;
2071 	struct filedesc *fdp;
2072 	cap_rights_t rights;
2073 	int error, ref;
2074 
2075 	/* Validate the file descriptor. */
2076 	/*
2077 	 * XXX this code inspects a file descriptor from a different process,
2078 	 * but there is no dedicated routine to do it in fd code, making the
2079 	 * ordeal highly questionable.
2080 	 */
2081 	fdp = p->p_fd;
2082 	FILEDESC_SLOCK(fdp);
2083 	error = fget_cap_noref(fdp, fd, cap_rights_init_one(&rights, CAP_TTYHOOK),
2084 	    &fp, NULL);
2085 	if (error == 0 && !fhold(fp))
2086 		error = EBADF;
2087 	FILEDESC_SUNLOCK(fdp);
2088 	if (error != 0)
2089 		return (error);
2090 	if (fp->f_ops == &badfileops) {
2091 		error = EBADF;
2092 		goto done1;
2093 	}
2094 
2095 	/*
2096 	 * Make sure the vnode is bound to a character device.
2097 	 * Unlocked check for the vnode type is ok there, because we
2098 	 * only shall prevent calling devvn_refthread on the file that
2099 	 * never has been opened over a character device.
2100 	 */
2101 	if (fp->f_type != DTYPE_VNODE || fp->f_vnode->v_type != VCHR) {
2102 		error = EINVAL;
2103 		goto done1;
2104 	}
2105 
2106 	/* Make sure it is a TTY. */
2107 	cdp = devvn_refthread(fp->f_vnode, &dev, &ref);
2108 	if (cdp == NULL) {
2109 		error = ENXIO;
2110 		goto done1;
2111 	}
2112 	if (dev != fp->f_data) {
2113 		error = ENXIO;
2114 		goto done2;
2115 	}
2116 	if (cdp != &ttydev_cdevsw) {
2117 		error = ENOTTY;
2118 		goto done2;
2119 	}
2120 	tp = dev->si_drv1;
2121 
2122 	/* Try to attach the hook to the TTY. */
2123 	error = EBUSY;
2124 	tty_lock(tp);
2125 	MPASS((tp->t_hook == NULL) == ((tp->t_flags & TF_HOOK) == 0));
2126 	if (tp->t_flags & TF_HOOK)
2127 		goto done3;
2128 
2129 	tp->t_flags |= TF_HOOK;
2130 	tp->t_hook = th;
2131 	tp->t_hooksoftc = softc;
2132 	*rtp = tp;
2133 	error = 0;
2134 
2135 	/* Maybe we can switch into bypass mode now. */
2136 	ttydisc_optimize(tp);
2137 
2138 	/* Silently convert rint() calls to rint_bypass() when possible. */
2139 	if (!ttyhook_hashook(tp, rint) && ttyhook_hashook(tp, rint_bypass))
2140 		th->th_rint = ttyhook_defrint;
2141 
2142 done3:	tty_unlock(tp);
2143 done2:	dev_relthread(dev, ref);
2144 done1:	fdrop(fp, curthread);
2145 	return (error);
2146 }
2147 
2148 void
2149 ttyhook_unregister(struct tty *tp)
2150 {
2151 
2152 	tty_assert_locked(tp);
2153 	MPASS(tp->t_flags & TF_HOOK);
2154 
2155 	/* Disconnect the hook. */
2156 	tp->t_flags &= ~TF_HOOK;
2157 	tp->t_hook = NULL;
2158 
2159 	/* Maybe we need to leave bypass mode. */
2160 	ttydisc_optimize(tp);
2161 
2162 	/* Maybe deallocate the TTY as well. */
2163 	tty_rel_free(tp);
2164 }
2165 
2166 /*
2167  * /dev/console handling.
2168  */
2169 
2170 static int
2171 ttyconsdev_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
2172 {
2173 	struct tty *tp;
2174 
2175 	/* System has no console device. */
2176 	if (dev_console_filename == NULL)
2177 		return (ENXIO);
2178 
2179 	/* Look up corresponding TTY by device name. */
2180 	sx_slock(&tty_list_sx);
2181 	TAILQ_FOREACH(tp, &tty_list, t_list) {
2182 		if (strcmp(dev_console_filename, tty_devname(tp)) == 0) {
2183 			dev_console->si_drv1 = tp;
2184 			break;
2185 		}
2186 	}
2187 	sx_sunlock(&tty_list_sx);
2188 
2189 	/* System console has no TTY associated. */
2190 	if (dev_console->si_drv1 == NULL)
2191 		return (ENXIO);
2192 
2193 	return (ttydev_open(dev, oflags, devtype, td));
2194 }
2195 
2196 static int
2197 ttyconsdev_write(struct cdev *dev, struct uio *uio, int ioflag)
2198 {
2199 
2200 	log_console(uio);
2201 
2202 	return (ttydev_write(dev, uio, ioflag));
2203 }
2204 
2205 /*
2206  * /dev/console is a little different than normal TTY's.  When opened,
2207  * it determines which TTY to use.  When data gets written to it, it
2208  * will be logged in the kernel message buffer.
2209  */
2210 static struct cdevsw ttyconsdev_cdevsw = {
2211 	.d_version	= D_VERSION,
2212 	.d_open		= ttyconsdev_open,
2213 	.d_close	= ttydev_close,
2214 	.d_read		= ttydev_read,
2215 	.d_write	= ttyconsdev_write,
2216 	.d_ioctl	= ttydev_ioctl,
2217 	.d_kqfilter	= ttydev_kqfilter,
2218 	.d_poll		= ttydev_poll,
2219 	.d_mmap		= ttydev_mmap,
2220 	.d_name		= "ttyconsdev",
2221 	.d_flags	= D_TTY,
2222 };
2223 
2224 static void
2225 ttyconsdev_init(void *unused __unused)
2226 {
2227 
2228 	dev_console = make_dev_credf(MAKEDEV_ETERNAL, &ttyconsdev_cdevsw, 0,
2229 	    NULL, UID_ROOT, GID_WHEEL, 0600, "console");
2230 }
2231 
2232 SYSINIT(tty, SI_SUB_DRIVERS, SI_ORDER_FIRST, ttyconsdev_init, NULL);
2233 
2234 void
2235 ttyconsdev_select(const char *name)
2236 {
2237 
2238 	dev_console_filename = name;
2239 }
2240 
2241 /*
2242  * Debugging routines.
2243  */
2244 
2245 #include "opt_ddb.h"
2246 #ifdef DDB
2247 #include <ddb/ddb.h>
2248 #include <ddb/db_sym.h>
2249 
2250 static const struct {
2251 	int flag;
2252 	char val;
2253 } ttystates[] = {
2254 #if 0
2255 	{ TF_NOPREFIX,		'N' },
2256 #endif
2257 	{ TF_INITLOCK,		'I' },
2258 	{ TF_CALLOUT,		'C' },
2259 
2260 	/* Keep these together -> 'Oi' and 'Oo'. */
2261 	{ TF_OPENED,		'O' },
2262 	{ TF_OPENED_IN,		'i' },
2263 	{ TF_OPENED_OUT,	'o' },
2264 	{ TF_OPENED_CONS,	'c' },
2265 
2266 	{ TF_GONE,		'G' },
2267 	{ TF_OPENCLOSE,		'B' },
2268 	{ TF_ASYNC,		'Y' },
2269 	{ TF_LITERAL,		'L' },
2270 
2271 	/* Keep these together -> 'Hi' and 'Ho'. */
2272 	{ TF_HIWAT,		'H' },
2273 	{ TF_HIWAT_IN,		'i' },
2274 	{ TF_HIWAT_OUT,		'o' },
2275 
2276 	{ TF_STOPPED,		'S' },
2277 	{ TF_EXCLUDE,		'X' },
2278 	{ TF_BYPASS,		'l' },
2279 	{ TF_ZOMBIE,		'Z' },
2280 	{ TF_HOOK,		's' },
2281 
2282 	/* Keep these together -> 'bi' and 'bo'. */
2283 	{ TF_BUSY,		'b' },
2284 	{ TF_BUSY_IN,		'i' },
2285 	{ TF_BUSY_OUT,		'o' },
2286 
2287 	{ 0,			'\0'},
2288 };
2289 
2290 #define	TTY_FLAG_BITS \
2291 	"\20\1NOPREFIX\2INITLOCK\3CALLOUT\4OPENED_IN" \
2292 	"\5OPENED_OUT\6OPENED_CONS\7GONE\10OPENCLOSE" \
2293 	"\11ASYNC\12LITERAL\13HIWAT_IN\14HIWAT_OUT" \
2294 	"\15STOPPED\16EXCLUDE\17BYPASS\20ZOMBIE" \
2295 	"\21HOOK\22BUSY_IN\23BUSY_OUT"
2296 
2297 #define DB_PRINTSYM(name, addr) \
2298 	db_printf("%s  " #name ": ", sep); \
2299 	db_printsym((db_addr_t) addr, DB_STGY_ANY); \
2300 	db_printf("\n");
2301 
2302 static void
2303 _db_show_devsw(const char *sep, const struct ttydevsw *tsw)
2304 {
2305 
2306 	db_printf("%sdevsw: ", sep);
2307 	db_printsym((db_addr_t)tsw, DB_STGY_ANY);
2308 	db_printf(" (%p)\n", tsw);
2309 	DB_PRINTSYM(open, tsw->tsw_open);
2310 	DB_PRINTSYM(close, tsw->tsw_close);
2311 	DB_PRINTSYM(outwakeup, tsw->tsw_outwakeup);
2312 	DB_PRINTSYM(inwakeup, tsw->tsw_inwakeup);
2313 	DB_PRINTSYM(ioctl, tsw->tsw_ioctl);
2314 	DB_PRINTSYM(param, tsw->tsw_param);
2315 	DB_PRINTSYM(modem, tsw->tsw_modem);
2316 	DB_PRINTSYM(mmap, tsw->tsw_mmap);
2317 	DB_PRINTSYM(pktnotify, tsw->tsw_pktnotify);
2318 	DB_PRINTSYM(free, tsw->tsw_free);
2319 }
2320 
2321 static void
2322 _db_show_hooks(const char *sep, const struct ttyhook *th)
2323 {
2324 
2325 	db_printf("%shook: ", sep);
2326 	db_printsym((db_addr_t)th, DB_STGY_ANY);
2327 	db_printf(" (%p)\n", th);
2328 	if (th == NULL)
2329 		return;
2330 	DB_PRINTSYM(rint, th->th_rint);
2331 	DB_PRINTSYM(rint_bypass, th->th_rint_bypass);
2332 	DB_PRINTSYM(rint_done, th->th_rint_done);
2333 	DB_PRINTSYM(rint_poll, th->th_rint_poll);
2334 	DB_PRINTSYM(getc_inject, th->th_getc_inject);
2335 	DB_PRINTSYM(getc_capture, th->th_getc_capture);
2336 	DB_PRINTSYM(getc_poll, th->th_getc_poll);
2337 	DB_PRINTSYM(close, th->th_close);
2338 }
2339 
2340 static void
2341 _db_show_termios(const char *name, const struct termios *t)
2342 {
2343 
2344 	db_printf("%s: iflag 0x%x oflag 0x%x cflag 0x%x "
2345 	    "lflag 0x%x ispeed %u ospeed %u\n", name,
2346 	    t->c_iflag, t->c_oflag, t->c_cflag, t->c_lflag,
2347 	    t->c_ispeed, t->c_ospeed);
2348 }
2349 
2350 /* DDB command to show TTY statistics. */
2351 DB_SHOW_COMMAND(tty, db_show_tty)
2352 {
2353 	struct tty *tp;
2354 
2355 	if (!have_addr) {
2356 		db_printf("usage: show tty <addr>\n");
2357 		return;
2358 	}
2359 	tp = (struct tty *)addr;
2360 
2361 	db_printf("%p: %s\n", tp, tty_devname(tp));
2362 	db_printf("\tmtx: %p\n", tp->t_mtx);
2363 	db_printf("\tflags: 0x%b\n", tp->t_flags, TTY_FLAG_BITS);
2364 	db_printf("\trevokecnt: %u\n", tp->t_revokecnt);
2365 
2366 	/* Buffering mechanisms. */
2367 	db_printf("\tinq: %p begin %u linestart %u reprint %u end %u "
2368 	    "nblocks %u quota %u\n", &tp->t_inq, tp->t_inq.ti_begin,
2369 	    tp->t_inq.ti_linestart, tp->t_inq.ti_reprint, tp->t_inq.ti_end,
2370 	    tp->t_inq.ti_nblocks, tp->t_inq.ti_quota);
2371 	db_printf("\toutq: %p begin %u end %u nblocks %u quota %u\n",
2372 	    &tp->t_outq, tp->t_outq.to_begin, tp->t_outq.to_end,
2373 	    tp->t_outq.to_nblocks, tp->t_outq.to_quota);
2374 	db_printf("\tinlow: %zu\n", tp->t_inlow);
2375 	db_printf("\toutlow: %zu\n", tp->t_outlow);
2376 	_db_show_termios("\ttermios", &tp->t_termios);
2377 	db_printf("\twinsize: row %u col %u xpixel %u ypixel %u\n",
2378 	    tp->t_winsize.ws_row, tp->t_winsize.ws_col,
2379 	    tp->t_winsize.ws_xpixel, tp->t_winsize.ws_ypixel);
2380 	db_printf("\tcolumn: %u\n", tp->t_column);
2381 	db_printf("\twritepos: %u\n", tp->t_writepos);
2382 	db_printf("\tcompatflags: 0x%x\n", tp->t_compatflags);
2383 
2384 	/* Init/lock-state devices. */
2385 	_db_show_termios("\ttermios_init_in", &tp->t_termios_init_in);
2386 	_db_show_termios("\ttermios_init_out", &tp->t_termios_init_out);
2387 	_db_show_termios("\ttermios_lock_in", &tp->t_termios_lock_in);
2388 	_db_show_termios("\ttermios_lock_out", &tp->t_termios_lock_out);
2389 
2390 	/* Hooks */
2391 	_db_show_devsw("\t", tp->t_devsw);
2392 	_db_show_hooks("\t", tp->t_hook);
2393 
2394 	/* Process info. */
2395 	db_printf("\tpgrp: %p gid %d\n", tp->t_pgrp,
2396 	    tp->t_pgrp ? tp->t_pgrp->pg_id : 0);
2397 	db_printf("\tsession: %p", tp->t_session);
2398 	if (tp->t_session != NULL)
2399 	    db_printf(" count %u leader %p tty %p sid %d login %s",
2400 		tp->t_session->s_count, tp->t_session->s_leader,
2401 		tp->t_session->s_ttyp, tp->t_session->s_sid,
2402 		tp->t_session->s_login);
2403 	db_printf("\n");
2404 	db_printf("\tsessioncnt: %u\n", tp->t_sessioncnt);
2405 	db_printf("\tdevswsoftc: %p\n", tp->t_devswsoftc);
2406 	db_printf("\thooksoftc: %p\n", tp->t_hooksoftc);
2407 	db_printf("\tdev: %p\n", tp->t_dev);
2408 }
2409 
2410 /* DDB command to list TTYs. */
2411 DB_SHOW_ALL_COMMAND(ttys, db_show_all_ttys)
2412 {
2413 	struct tty *tp;
2414 	size_t isiz, osiz;
2415 	int i, j;
2416 
2417 	/* Make the output look like `pstat -t'. */
2418 	db_printf("PTR        ");
2419 #if defined(__LP64__)
2420 	db_printf("        ");
2421 #endif
2422 	db_printf("      LINE   INQ  CAN  LIN  LOW  OUTQ  USE  LOW   "
2423 	    "COL  SESS  PGID STATE\n");
2424 
2425 	TAILQ_FOREACH(tp, &tty_list, t_list) {
2426 		isiz = tp->t_inq.ti_nblocks * TTYINQ_DATASIZE;
2427 		osiz = tp->t_outq.to_nblocks * TTYOUTQ_DATASIZE;
2428 
2429 		db_printf("%p %10s %5zu %4u %4u %4zu %5zu %4u %4zu %5u %5d "
2430 		    "%5d ", tp, tty_devname(tp), isiz,
2431 		    tp->t_inq.ti_linestart - tp->t_inq.ti_begin,
2432 		    tp->t_inq.ti_end - tp->t_inq.ti_linestart,
2433 		    isiz - tp->t_inlow, osiz,
2434 		    tp->t_outq.to_end - tp->t_outq.to_begin,
2435 		    osiz - tp->t_outlow, MIN(tp->t_column, 99999),
2436 		    tp->t_session ? tp->t_session->s_sid : 0,
2437 		    tp->t_pgrp ? tp->t_pgrp->pg_id : 0);
2438 
2439 		/* Flag bits. */
2440 		for (i = j = 0; ttystates[i].flag; i++)
2441 			if (tp->t_flags & ttystates[i].flag) {
2442 				db_printf("%c", ttystates[i].val);
2443 				j++;
2444 			}
2445 		if (j == 0)
2446 			db_printf("-");
2447 		db_printf("\n");
2448 	}
2449 }
2450 #endif /* DDB */
2451