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