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