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