xref: /freebsd/sys/kern/tty.c (revision 13014ca04aad1931d41958b56f71a2c65b9a7a2c)
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_compat.h"
34 
35 #include <sys/param.h>
36 #include <sys/conf.h>
37 #include <sys/cons.h>
38 #include <sys/fcntl.h>
39 #include <sys/file.h>
40 #include <sys/filio.h>
41 #ifdef COMPAT_43TTY
42 #include <sys/ioctl_compat.h>
43 #endif /* COMPAT_43TTY */
44 #include <sys/kernel.h>
45 #include <sys/limits.h>
46 #include <sys/malloc.h>
47 #include <sys/mount.h>
48 #include <sys/poll.h>
49 #include <sys/priv.h>
50 #include <sys/proc.h>
51 #include <sys/serial.h>
52 #include <sys/signal.h>
53 #include <sys/stat.h>
54 #include <sys/sx.h>
55 #include <sys/sysctl.h>
56 #include <sys/systm.h>
57 #include <sys/tty.h>
58 #include <sys/ttycom.h>
59 #define TTYDEFCHARS
60 #include <sys/ttydefaults.h>
61 #undef TTYDEFCHARS
62 #include <sys/ucred.h>
63 #include <sys/vnode.h>
64 
65 #include <machine/stdarg.h>
66 
67 static MALLOC_DEFINE(M_TTY, "tty", "tty device");
68 
69 static void tty_rel_free(struct tty *tp);
70 
71 static TAILQ_HEAD(, tty) tty_list = TAILQ_HEAD_INITIALIZER(tty_list);
72 static struct sx tty_list_sx;
73 SX_SYSINIT(tty_list, &tty_list_sx, "tty list");
74 static unsigned int tty_list_count = 0;
75 
76 /*
77  * Flags that are supported and stored by this implementation.
78  */
79 #define TTYSUP_IFLAG	(IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK|ISTRIP|\
80 			INLCR|IGNCR|ICRNL|IXON|IXOFF|IXANY|IMAXBEL)
81 #define TTYSUP_OFLAG	(OPOST|ONLCR|TAB3|ONOEOT|OCRNL|ONOCR|ONLRET)
82 #define TTYSUP_LFLAG	(ECHOKE|ECHOE|ECHOK|ECHO|ECHONL|ECHOPRT|\
83 			ECHOCTL|ISIG|ICANON|ALTWERASE|IEXTEN|TOSTOP|\
84 			FLUSHO|NOKERNINFO|NOFLSH)
85 #define TTYSUP_CFLAG	(CIGNORE|CSIZE|CSTOPB|CREAD|PARENB|PARODD|\
86 			HUPCL|CLOCAL|CCTS_OFLOW|CRTS_IFLOW|CDTR_IFLOW|\
87 			CDSR_OFLOW|CCAR_OFLOW)
88 
89 #define TTY_CALLOUT(tp,d) ((tp)->t_dev != (d))
90 
91 /*
92  * Set TTY buffer sizes.
93  */
94 
95 static void
96 tty_watermarks(struct tty *tp)
97 {
98 	speed_t sp;
99 
100 	/* Provide an input buffer for 0.2 seconds of data. */
101 	sp = MAX(tp->t_termios.c_ispeed, 0);
102 	ttyinq_setsize(&tp->t_inq, tp, sp / 5);
103 
104 	/* Set low watermark at 10% (when 90% is available). */
105 	tp->t_inlow = (ttyinq_getsize(&tp->t_inq) * 9) / 10;
106 
107 	/* Provide an ouput buffer for 0.2 seconds of data. */
108 	sp = MAX(tp->t_termios.c_ospeed, 0);
109 	ttyoutq_setsize(&tp->t_outq, tp, sp / 5);
110 
111 	/* Set low watermark at 10% (when 90% is available). */
112 	tp->t_outlow = (ttyoutq_getsize(&tp->t_outq) * 9) / 10;
113 }
114 
115 static int
116 tty_drain(struct tty *tp)
117 {
118 	int error;
119 
120 	while (ttyoutq_bytesused(&tp->t_outq) > 0) {
121 		ttydevsw_outwakeup(tp);
122 		/* Could be handled synchronously. */
123 		if (ttyoutq_bytesused(&tp->t_outq) == 0)
124 			return (0);
125 
126 		/* Wait for data to be drained. */
127 		error = tty_wait(tp, &tp->t_outwait);
128 		if (error)
129 			return (error);
130 	}
131 
132 	return (0);
133 }
134 
135 /*
136  * Because the revoke() call already calls d_close() without making sure
137  * all threads are purged from the TTY, we can only destroy the buffers
138  * and such when the last thread leaves the TTY. ttydev_enter() and
139  * ttydev_leave() are called from within the cdev functions, to make
140  * sure we can garbage collect the TTY.
141  */
142 
143 static __inline int
144 ttydev_enter(struct tty *tp)
145 {
146 	tty_lock(tp);
147 
148 	if (tty_gone(tp) || !tty_opened(tp)) {
149 		/* Device is already gone. */
150 		tty_unlock(tp);
151 		return (ENXIO);
152 	}
153 
154 	return (0);
155 }
156 
157 static void
158 ttydev_leave(struct tty *tp)
159 {
160 	tty_lock_assert(tp, MA_OWNED);
161 
162 	if (tty_opened(tp) || tp->t_flags & TF_OPENCLOSE) {
163 		/* Device is still opened somewhere. */
164 		tty_unlock(tp);
165 		return;
166 	}
167 
168 	tp->t_flags |= TF_OPENCLOSE;
169 
170 	/* Stop asynchronous I/O. */
171 	funsetown(&tp->t_sigio);
172 
173 	/* Remove console TTY. */
174 	if (constty == tp)
175 		constty_clear();
176 
177 	/* Drain any output. */
178 	MPASS((tp->t_flags & TF_STOPPED) == 0);
179 	if (!tty_gone(tp))
180 		tty_drain(tp);
181 
182 	ttydisc_close(tp);
183 
184 	/* Destroy associated buffers already. */
185 	ttyinq_free(&tp->t_inq);
186 	tp->t_inlow = 0;
187 	ttyoutq_free(&tp->t_outq);
188 	tp->t_outlow = 0;
189 
190 	knlist_clear(&tp->t_inpoll.si_note, 1);
191 	knlist_clear(&tp->t_outpoll.si_note, 1);
192 
193 	if (!tty_gone(tp))
194 		ttydevsw_close(tp);
195 
196 	tp->t_flags &= ~TF_OPENCLOSE;
197 	tty_rel_free(tp);
198 }
199 
200 /*
201  * Operations that are exposed through the character device in /dev.
202  */
203 static int
204 ttydev_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
205 {
206 	struct tty *tp = dev->si_drv1;
207 	int error = 0;
208 
209 	/* Disallow access when the TTY belongs to a different prison. */
210 	if (dev->si_cred != NULL &&
211 	    dev->si_cred->cr_prison != td->td_ucred->cr_prison &&
212 	    priv_check(td, PRIV_TTY_PRISON)) {
213 		return (EPERM);
214 	}
215 
216 	tty_lock(tp);
217 	if (tty_gone(tp)) {
218 		/* Device is already gone. */
219 		tty_unlock(tp);
220 		return (ENXIO);
221 	}
222 	/*
223 	 * Prevent the TTY from being opened when being torn down or
224 	 * built up by unrelated processes.
225 	 */
226 	if (tp->t_flags & TF_OPENCLOSE) {
227 		tty_unlock(tp);
228 		return (EBUSY);
229 	}
230 	tp->t_flags |= TF_OPENCLOSE;
231 
232 	/*
233 	 * Make sure the "tty" and "cua" device cannot be opened at the
234 	 * same time.
235 	 */
236 	if (TTY_CALLOUT(tp, dev)) {
237 		if (tp->t_flags & TF_OPENED_IN) {
238 			error = EBUSY;
239 			goto done;
240 		}
241 	} else {
242 		if (tp->t_flags & TF_OPENED_OUT) {
243 			error = EBUSY;
244 			goto done;
245 		}
246 	}
247 
248 	if (tp->t_flags & TF_EXCLUDE && priv_check(td, PRIV_TTY_EXCLUSIVE)) {
249 		error = EBUSY;
250 		goto done;
251 	}
252 
253 	if (!tty_opened(tp)) {
254 		/* Set proper termios flags. */
255 		if (TTY_CALLOUT(tp, dev)) {
256 			tp->t_termios = tp->t_termios_init_out;
257 		} else {
258 			tp->t_termios = tp->t_termios_init_in;
259 		}
260 		ttydevsw_param(tp, &tp->t_termios);
261 
262 		ttydevsw_modem(tp, SER_DTR|SER_RTS, 0);
263 
264 		error = ttydevsw_open(tp);
265 		if (error != 0)
266 			goto done;
267 
268 		ttydisc_open(tp);
269 		tty_watermarks(tp);
270 	}
271 
272 	/* Wait for Carrier Detect. */
273 	if (!TTY_CALLOUT(tp, dev) && (oflags & O_NONBLOCK) == 0 &&
274 	    (tp->t_termios.c_cflag & CLOCAL) == 0) {
275 		while ((ttydevsw_modem(tp, 0, 0) & SER_DCD) == 0) {
276 			error = tty_wait(tp, &tp->t_dcdwait);
277 			if (error != 0)
278 				goto done;
279 		}
280 	}
281 
282 	if (TTY_CALLOUT(tp, dev)) {
283 		tp->t_flags |= TF_OPENED_OUT;
284 	} else {
285 		tp->t_flags |= TF_OPENED_IN;
286 	}
287 
288 done:	tp->t_flags &= ~TF_OPENCLOSE;
289 	ttydev_leave(tp);
290 	return (error);
291 }
292 
293 static int
294 ttydev_close(struct cdev *dev, int fflag, int devtype, struct thread *td)
295 {
296 	struct tty *tp = dev->si_drv1;
297 
298 	tty_lock(tp);
299 
300 	/*
301 	 * This can only be called once. The callin and the callout
302 	 * devices cannot be opened at the same time.
303 	 */
304 	MPASS((tp->t_flags & TF_OPENED) != TF_OPENED);
305 	tp->t_flags &= ~(TF_OPENED|TF_EXCLUDE|TF_STOPPED);
306 
307 	/* Properly wake up threads that are stuck - revoke(). */
308 	tp->t_revokecnt++;
309 	tty_wakeup(tp, FREAD|FWRITE);
310 	cv_broadcast(&tp->t_bgwait);
311 
312 	ttydev_leave(tp);
313 
314 	return (0);
315 }
316 
317 static __inline int
318 tty_is_ctty(struct tty *tp, struct proc *p)
319 {
320 	tty_lock_assert(tp, MA_OWNED);
321 
322 	return (p->p_session == tp->t_session && p->p_flag & P_CONTROLT);
323 }
324 
325 static int
326 tty_wait_background(struct tty *tp, struct thread *td, int sig)
327 {
328 	struct proc *p = td->td_proc;
329 	struct pgrp *pg;
330 	int error;
331 
332 	MPASS(sig == SIGTTIN || sig == SIGTTOU);
333 	tty_lock_assert(tp, MA_OWNED);
334 
335 	for (;;) {
336 		PROC_LOCK(p);
337 		/*
338 		 * The process should only sleep, when:
339 		 * - This terminal is the controling terminal
340 		 * - Its process group is not the foreground process
341 		 *   group
342 		 * - The parent process isn't waiting for the child to
343 		 *   exit
344 		 * - the signal to send to the process isn't masked
345 		 */
346 		if (!tty_is_ctty(tp, p) ||
347 		    p->p_pgrp == tp->t_pgrp || p->p_flag & P_PPWAIT ||
348 		    SIGISMEMBER(p->p_sigacts->ps_sigignore, sig) ||
349 		    SIGISMEMBER(td->td_sigmask, sig)) {
350 			/* Allow the action to happen. */
351 			PROC_UNLOCK(p);
352 			return (0);
353 		}
354 
355 		/*
356 		 * Send the signal and sleep until we're the new
357 		 * foreground process group.
358 		 */
359 		pg = p->p_pgrp;
360 		PROC_UNLOCK(p);
361 		if (pg->pg_jobc == 0)
362 			return (EIO);
363 		PGRP_LOCK(pg);
364 		pgsignal(pg, sig, 1);
365 		PGRP_UNLOCK(pg);
366 
367 		error = tty_wait(tp, &tp->t_bgwait);
368 		if (error)
369 			return (error);
370 	}
371 }
372 
373 static int
374 ttydev_read(struct cdev *dev, struct uio *uio, int ioflag)
375 {
376 	struct tty *tp = dev->si_drv1;
377 	int error;
378 
379 	error = ttydev_enter(tp);
380 	if (error)
381 		return (0);
382 
383 	error = tty_wait_background(tp, curthread, SIGTTIN);
384 	if (error)
385 		goto done;
386 
387 	error = ttydisc_read(tp, uio, ioflag);
388 done:	ttydev_leave(tp);
389 
390 	/*
391 	 * The read() and write() calls should not throw an error when
392 	 * the device is ripped offline.
393 	 */
394 	if (error == ENXIO)
395 		return (0);
396 
397 	return (error);
398 }
399 
400 static int
401 ttydev_write(struct cdev *dev, struct uio *uio, int ioflag)
402 {
403 	struct tty *tp = dev->si_drv1;
404 	int error;
405 
406 	error = ttydev_enter(tp);
407 	if (error)
408 		return (0);
409 
410 	if (tp->t_termios.c_lflag & TOSTOP) {
411 		error = tty_wait_background(tp, curthread, SIGTTOU);
412 		if (error)
413 			goto done;
414 	}
415 
416 	error = ttydisc_write(tp, uio, ioflag);
417 done:	ttydev_leave(tp);
418 
419 	/*
420 	 * The read() and write() calls should not throw an error when
421 	 * the device is ripped offline.
422 	 */
423 	if (error == ENXIO)
424 		return (0);
425 
426 	return (error);
427 }
428 
429 static int
430 ttydev_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
431     struct thread *td)
432 {
433 	struct tty *tp = dev->si_drv1;
434 	int error;
435 
436 	error = ttydev_enter(tp);
437 	if (error)
438 		return (error);
439 
440 	switch (cmd) {
441 	case TIOCCBRK:
442 	case TIOCCONS:
443 	case TIOCDRAIN:
444 	case TIOCEXCL:
445 	case TIOCFLUSH:
446 	case TIOCNXCL:
447 	case TIOCSBRK:
448 	case TIOCSCTTY:
449 	case TIOCSETA:
450 	case TIOCSETAF:
451 	case TIOCSETAW:
452 	case TIOCSPGRP:
453 	case TIOCSTART:
454 	case TIOCSTAT:
455 	case TIOCSTOP:
456 	case TIOCSWINSZ:
457 #if 0
458 	case TIOCSDRAINWAIT:
459 	case TIOCSETD:
460 	case TIOCSTI:
461 #endif
462 #ifdef COMPAT_43TTY
463 	case  TIOCLBIC:
464 	case  TIOCLBIS:
465 	case  TIOCLSET:
466 	case  TIOCSETC:
467 	case OTIOCSETD:
468 	case  TIOCSETN:
469 	case  TIOCSETP:
470 	case  TIOCSLTC:
471 #endif /* COMPAT_43TTY */
472 		/*
473 		 * If the ioctl() causes the TTY to be modified, let it
474 		 * wait in the background.
475 		 */
476 		error = tty_wait_background(tp, curthread, SIGTTOU);
477 		if (error)
478 			goto done;
479 	}
480 
481 	error = tty_ioctl(tp, cmd, data, td);
482 done:	ttydev_leave(tp);
483 
484 	return (error);
485 }
486 
487 static int
488 ttydev_poll(struct cdev *dev, int events, struct thread *td)
489 {
490 	struct tty *tp = dev->si_drv1;
491 	int error, revents = 0;
492 
493 	error = ttydev_enter(tp);
494 	if (error) {
495 		/* Don't return the error here, but the event mask. */
496 		return (events &
497 		    (POLLHUP|POLLIN|POLLRDNORM|POLLOUT|POLLWRNORM));
498 	}
499 
500 	if (events & (POLLIN|POLLRDNORM)) {
501 		/* See if we can read something. */
502 		if (ttydisc_read_poll(tp) > 0)
503 			revents |= events & (POLLIN|POLLRDNORM);
504 	}
505 	if (events & (POLLOUT|POLLWRNORM)) {
506 		/* See if we can write something. */
507 		if (ttydisc_write_poll(tp) > 0)
508 			revents |= events & (POLLOUT|POLLWRNORM);
509 	}
510 	if (tp->t_flags & TF_ZOMBIE)
511 		/* Hangup flag on zombie state. */
512 		revents |= events & POLLHUP;
513 
514 	if (revents == 0) {
515 		if (events & (POLLIN|POLLRDNORM))
516 			selrecord(td, &tp->t_inpoll);
517 		if (events & (POLLOUT|POLLWRNORM))
518 			selrecord(td, &tp->t_outpoll);
519 	}
520 
521 	ttydev_leave(tp);
522 
523 	return (revents);
524 }
525 
526 static int
527 ttydev_mmap(struct cdev *dev, vm_offset_t offset, vm_paddr_t *paddr, int nprot)
528 {
529 	struct tty *tp = dev->si_drv1;
530 	int error;
531 
532 	/* Handle mmap() through the driver. */
533 
534 	error = ttydev_enter(tp);
535 	if (error)
536 		return (-1);
537 	error = ttydevsw_mmap(tp, offset, paddr, nprot);
538 	ttydev_leave(tp);
539 
540 	return (error);
541 }
542 
543 /*
544  * kqueue support.
545  */
546 
547 static void
548 tty_kqops_read_detach(struct knote *kn)
549 {
550 	struct tty *tp = kn->kn_hook;
551 
552 	knlist_remove(&tp->t_inpoll.si_note, kn, 0);
553 }
554 
555 static int
556 tty_kqops_read_event(struct knote *kn, long hint)
557 {
558 	struct tty *tp = kn->kn_hook;
559 
560 	tty_lock_assert(tp, MA_OWNED);
561 
562 	if (tty_gone(tp) || tp->t_flags & TF_ZOMBIE) {
563 		kn->kn_flags |= EV_EOF;
564 		return (1);
565 	} else {
566 		kn->kn_data = ttydisc_read_poll(tp);
567 		return (kn->kn_data > 0);
568 	}
569 }
570 
571 static void
572 tty_kqops_write_detach(struct knote *kn)
573 {
574 	struct tty *tp = kn->kn_hook;
575 
576 	knlist_remove(&tp->t_outpoll.si_note, kn, 0);
577 }
578 
579 static int
580 tty_kqops_write_event(struct knote *kn, long hint)
581 {
582 	struct tty *tp = kn->kn_hook;
583 
584 	tty_lock_assert(tp, MA_OWNED);
585 
586 	if (tty_gone(tp)) {
587 		kn->kn_flags |= EV_EOF;
588 		return (1);
589 	} else {
590 		kn->kn_data = ttydisc_write_poll(tp);
591 		return (kn->kn_data > 0);
592 	}
593 }
594 
595 static struct filterops tty_kqops_read =
596     { 1, NULL, tty_kqops_read_detach, tty_kqops_read_event };
597 static struct filterops tty_kqops_write =
598     { 1, NULL, tty_kqops_write_detach, tty_kqops_write_event };
599 
600 static int
601 ttydev_kqfilter(struct cdev *dev, struct knote *kn)
602 {
603 	struct tty *tp = dev->si_drv1;
604 	int error;
605 
606 	error = ttydev_enter(tp);
607 	if (error)
608 		return (error);
609 
610 	switch (kn->kn_filter) {
611 	case EVFILT_READ:
612 		kn->kn_hook = tp;
613 		kn->kn_fop = &tty_kqops_read;
614 		knlist_add(&tp->t_inpoll.si_note, kn, 1);
615 		break;
616 	case EVFILT_WRITE:
617 		kn->kn_hook = tp;
618 		kn->kn_fop = &tty_kqops_write;
619 		knlist_add(&tp->t_outpoll.si_note, kn, 1);
620 		break;
621 	default:
622 		error = EINVAL;
623 		break;
624 	}
625 
626 	ttydev_leave(tp);
627 	return (error);
628 }
629 
630 static struct cdevsw ttydev_cdevsw = {
631 	.d_version	= D_VERSION,
632 	.d_open		= ttydev_open,
633 	.d_close	= ttydev_close,
634 	.d_read		= ttydev_read,
635 	.d_write	= ttydev_write,
636 	.d_ioctl	= ttydev_ioctl,
637 	.d_kqfilter	= ttydev_kqfilter,
638 	.d_poll		= ttydev_poll,
639 	.d_mmap		= ttydev_mmap,
640 	.d_name		= "ttydev",
641 	.d_flags	= D_TTY,
642 };
643 
644 /*
645  * Init/lock-state devices
646  */
647 
648 static int
649 ttyil_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
650 {
651 	struct tty *tp = dev->si_drv1;
652 	int error = 0;
653 
654 	tty_lock(tp);
655 	if (tty_gone(tp))
656 		error = ENODEV;
657 	tty_unlock(tp);
658 
659 	return (error);
660 }
661 
662 static int
663 ttyil_close(struct cdev *dev, int flag, int mode, struct thread *td)
664 {
665 	return (0);
666 }
667 
668 static int
669 ttyil_rdwr(struct cdev *dev, struct uio *uio, int ioflag)
670 {
671 	return (ENODEV);
672 }
673 
674 static int
675 ttyil_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
676     struct thread *td)
677 {
678 	struct tty *tp = dev->si_drv1;
679 	int error = 0;
680 
681 	tty_lock(tp);
682 	if (tty_gone(tp)) {
683 		error = ENODEV;
684 		goto done;
685 	}
686 
687 	switch (cmd) {
688 	case TIOCGETA:
689 		/* Obtain terminal flags through tcgetattr(). */
690 		bcopy(dev->si_drv2, data, sizeof(struct termios));
691 		break;
692 	case TIOCSETA:
693 		/* Set terminal flags through tcsetattr(). */
694 		error = priv_check(td, PRIV_TTY_SETA);
695 		if (error)
696 			break;
697 		bcopy(data, dev->si_drv2, sizeof(struct termios));
698 		break;
699 	case TIOCGETD:
700 		*(int *)data = TTYDISC;
701 		break;
702 	case TIOCGWINSZ:
703 		bzero(data, sizeof(struct winsize));
704 		break;
705 	default:
706 		error = ENOTTY;
707 	}
708 
709 done:	tty_unlock(tp);
710 	return (error);
711 }
712 
713 static struct cdevsw ttyil_cdevsw = {
714 	.d_version	= D_VERSION,
715 	.d_open		= ttyil_open,
716 	.d_close	= ttyil_close,
717 	.d_read		= ttyil_rdwr,
718 	.d_write	= ttyil_rdwr,
719 	.d_ioctl	= ttyil_ioctl,
720 	.d_name		= "ttyil",
721 	.d_flags	= D_TTY,
722 };
723 
724 static void
725 tty_init_termios(struct tty *tp)
726 {
727 	struct termios *t = &tp->t_termios_init_in;
728 
729 	t->c_cflag = TTYDEF_CFLAG;
730 	t->c_iflag = TTYDEF_IFLAG;
731 	t->c_lflag = TTYDEF_LFLAG;
732 	t->c_oflag = TTYDEF_OFLAG;
733 	t->c_ispeed = TTYDEF_SPEED;
734 	t->c_ospeed = TTYDEF_SPEED;
735 	bcopy(ttydefchars, &t->c_cc, sizeof ttydefchars);
736 
737 	tp->t_termios_init_out = *t;
738 }
739 
740 void
741 tty_init_console(struct tty *tp, speed_t s)
742 {
743 	struct termios *ti = &tp->t_termios_init_in;
744 	struct termios *to = &tp->t_termios_init_out;
745 
746 	if (s != 0) {
747 		ti->c_ispeed = ti->c_ospeed = s;
748 		to->c_ispeed = to->c_ospeed = s;
749 	}
750 
751 	ti->c_cflag |= CLOCAL;
752 	to->c_cflag |= CLOCAL;
753 }
754 
755 /*
756  * Standard device routine implementations, mostly meant for
757  * pseudo-terminal device drivers. When a driver creates a new terminal
758  * device class, missing routines are patched.
759  */
760 
761 static int
762 ttydevsw_defopen(struct tty *tp)
763 {
764 
765 	return (0);
766 }
767 
768 static void
769 ttydevsw_defclose(struct tty *tp)
770 {
771 }
772 
773 static void
774 ttydevsw_defoutwakeup(struct tty *tp)
775 {
776 
777 	panic("Terminal device has output, while not implemented");
778 }
779 
780 static void
781 ttydevsw_definwakeup(struct tty *tp)
782 {
783 }
784 
785 static int
786 ttydevsw_defioctl(struct tty *tp, u_long cmd, caddr_t data, struct thread *td)
787 {
788 
789 	return (ENOIOCTL);
790 }
791 
792 static int
793 ttydevsw_defparam(struct tty *tp, struct termios *t)
794 {
795 
796 	/* Use a fake baud rate, we're not a real device. */
797 	t->c_ispeed = t->c_ospeed = TTYDEF_SPEED_PSEUDO;
798 
799 	return (0);
800 }
801 
802 static int
803 ttydevsw_defmodem(struct tty *tp, int sigon, int sigoff)
804 {
805 
806 	/* Simulate a carrier to make the TTY layer happy. */
807 	return (SER_DCD);
808 }
809 
810 static int
811 ttydevsw_defmmap(struct tty *tp, vm_offset_t offset, vm_paddr_t *paddr,
812     int nprot)
813 {
814 
815 	return (-1);
816 }
817 
818 static void
819 ttydevsw_defpktnotify(struct tty *tp, char event)
820 {
821 }
822 
823 static void
824 ttydevsw_deffree(void *softc)
825 {
826 
827 	panic("Terminal device freed without a free-handler");
828 }
829 
830 /*
831  * TTY allocation and deallocation. TTY devices can be deallocated when
832  * the driver doesn't use it anymore, when the TTY isn't a session's
833  * controlling TTY and when the device node isn't opened through devfs.
834  */
835 
836 struct tty *
837 tty_alloc(struct ttydevsw *tsw, void *sc, struct mtx *mutex)
838 {
839 	struct tty *tp;
840 
841 	/* Make sure the driver defines all routines. */
842 #define PATCH_FUNC(x) do {				\
843 	if (tsw->tsw_ ## x == NULL)			\
844 		tsw->tsw_ ## x = ttydevsw_def ## x;	\
845 } while (0)
846 	PATCH_FUNC(open);
847 	PATCH_FUNC(close);
848 	PATCH_FUNC(outwakeup);
849 	PATCH_FUNC(inwakeup);
850 	PATCH_FUNC(ioctl);
851 	PATCH_FUNC(param);
852 	PATCH_FUNC(modem);
853 	PATCH_FUNC(mmap);
854 	PATCH_FUNC(pktnotify);
855 	PATCH_FUNC(free);
856 #undef PATCH_FUNC
857 
858 	tp = malloc(sizeof(struct tty), M_TTY, M_WAITOK|M_ZERO);
859 	tp->t_devsw = tsw;
860 	tp->t_devswsoftc = sc;
861 	tp->t_flags = tsw->tsw_flags;
862 
863 	tty_init_termios(tp);
864 
865 	cv_init(&tp->t_inwait, "tty input");
866 	cv_init(&tp->t_outwait, "tty output");
867 	cv_init(&tp->t_bgwait, "tty background");
868 	cv_init(&tp->t_dcdwait, "tty dcd");
869 
870 	ttyinq_init(&tp->t_inq);
871 	ttyoutq_init(&tp->t_outq);
872 
873 	/* Allow drivers to use a custom mutex to lock the TTY. */
874 	if (mutex != NULL) {
875 		tp->t_mtx = mutex;
876 	} else {
877 		tp->t_mtx = &tp->t_mtxobj;
878 		mtx_init(&tp->t_mtxobj, "tty lock", NULL, MTX_DEF);
879 	}
880 
881 	knlist_init(&tp->t_inpoll.si_note, tp->t_mtx, NULL, NULL, NULL);
882 	knlist_init(&tp->t_outpoll.si_note, tp->t_mtx, NULL, NULL, NULL);
883 
884 	sx_xlock(&tty_list_sx);
885 	TAILQ_INSERT_TAIL(&tty_list, tp, t_list);
886 	tty_list_count++;
887 	sx_xunlock(&tty_list_sx);
888 
889 	return (tp);
890 }
891 
892 static void
893 tty_dealloc(void *arg)
894 {
895 	struct tty *tp = arg;
896 
897 	sx_xlock(&tty_list_sx);
898 	TAILQ_REMOVE(&tty_list, tp, t_list);
899 	tty_list_count--;
900 	sx_xunlock(&tty_list_sx);
901 
902 	/* Make sure we haven't leaked buffers. */
903 	MPASS(ttyinq_getsize(&tp->t_inq) == 0);
904 	MPASS(ttyoutq_getsize(&tp->t_outq) == 0);
905 
906 	knlist_destroy(&tp->t_inpoll.si_note);
907 	knlist_destroy(&tp->t_outpoll.si_note);
908 
909 	cv_destroy(&tp->t_inwait);
910 	cv_destroy(&tp->t_outwait);
911 	cv_destroy(&tp->t_bgwait);
912 	cv_destroy(&tp->t_dcdwait);
913 
914 	if (tp->t_mtx == &tp->t_mtxobj)
915 		mtx_destroy(&tp->t_mtxobj);
916 	ttydevsw_free(tp);
917 	free(tp, M_TTY);
918 }
919 
920 static void
921 tty_rel_free(struct tty *tp)
922 {
923 	struct cdev *dev;
924 
925 	tty_lock_assert(tp, MA_OWNED);
926 
927 #define	TF_ACTIVITY	(TF_GONE|TF_OPENED|TF_HOOK|TF_OPENCLOSE)
928 	if (tp->t_sessioncnt != 0 || (tp->t_flags & TF_ACTIVITY) != TF_GONE) {
929 		/* TTY is still in use. */
930 		tty_unlock(tp);
931 		return;
932 	}
933 
934 	/* TTY can be deallocated. */
935 	dev = tp->t_dev;
936 	tp->t_dev = NULL;
937 	tty_unlock(tp);
938 
939 	destroy_dev_sched_cb(dev, tty_dealloc, tp);
940 }
941 
942 void
943 tty_rel_pgrp(struct tty *tp, struct pgrp *pg)
944 {
945 	MPASS(tp->t_sessioncnt > 0);
946 	tty_lock_assert(tp, MA_OWNED);
947 
948 	if (tp->t_pgrp == pg)
949 		tp->t_pgrp = NULL;
950 
951 	tty_unlock(tp);
952 }
953 
954 void
955 tty_rel_sess(struct tty *tp, struct session *sess)
956 {
957 	MPASS(tp->t_sessioncnt > 0);
958 
959 	/* Current session has left. */
960 	if (tp->t_session == sess) {
961 		tp->t_session = NULL;
962 		MPASS(tp->t_pgrp == NULL);
963 	}
964 	tp->t_sessioncnt--;
965 	tty_rel_free(tp);
966 }
967 
968 void
969 tty_rel_gone(struct tty *tp)
970 {
971 	MPASS(!tty_gone(tp));
972 
973 	/* Simulate carrier removal. */
974 	ttydisc_modem(tp, 0);
975 
976 	/* Wake up misc. blocked threads. */
977 	cv_broadcast(&tp->t_bgwait);
978 	cv_broadcast(&tp->t_dcdwait);
979 
980 	tp->t_flags |= TF_GONE;
981 	tty_rel_free(tp);
982 }
983 
984 /*
985  * Exposing information about current TTY's through sysctl
986  */
987 
988 static void
989 tty_to_xtty(struct tty *tp, struct xtty *xt)
990 {
991 	tty_lock_assert(tp, MA_OWNED);
992 
993 	xt->xt_size = sizeof(struct xtty);
994 	xt->xt_insize = ttyinq_getsize(&tp->t_inq);
995 	xt->xt_incc = ttyinq_bytescanonicalized(&tp->t_inq);
996 	xt->xt_inlc = ttyinq_bytesline(&tp->t_inq);
997 	xt->xt_inlow = tp->t_inlow;
998 	xt->xt_outsize = ttyoutq_getsize(&tp->t_outq);
999 	xt->xt_outcc = ttyoutq_bytesused(&tp->t_outq);
1000 	xt->xt_outlow = tp->t_outlow;
1001 	xt->xt_column = tp->t_column;
1002 	xt->xt_pgid = tp->t_pgrp ? tp->t_pgrp->pg_id : 0;
1003 	xt->xt_sid = tp->t_session ? tp->t_session->s_sid : 0;
1004 	xt->xt_flags = tp->t_flags;
1005 	xt->xt_dev = tp->t_dev ? dev2udev(tp->t_dev) : NODEV;
1006 }
1007 
1008 static int
1009 sysctl_kern_ttys(SYSCTL_HANDLER_ARGS)
1010 {
1011 	unsigned long lsize;
1012 	struct xtty *xtlist, *xt;
1013 	struct tty *tp;
1014 	int error;
1015 
1016 	sx_slock(&tty_list_sx);
1017 	lsize = tty_list_count * sizeof(struct xtty);
1018 	if (lsize == 0) {
1019 		sx_sunlock(&tty_list_sx);
1020 		return (0);
1021 	}
1022 
1023 	xtlist = xt = malloc(lsize, M_TEMP, M_WAITOK);
1024 
1025 	TAILQ_FOREACH(tp, &tty_list, t_list) {
1026 		tty_lock(tp);
1027 		tty_to_xtty(tp, xt);
1028 		tty_unlock(tp);
1029 		xt++;
1030 	}
1031 	sx_sunlock(&tty_list_sx);
1032 
1033 	error = SYSCTL_OUT(req, xtlist, lsize);
1034 	free(xtlist, M_TEMP);
1035 	return (error);
1036 }
1037 
1038 SYSCTL_PROC(_kern, OID_AUTO, ttys, CTLTYPE_OPAQUE|CTLFLAG_RD,
1039 	0, 0, sysctl_kern_ttys, "S,xtty", "List of TTYs");
1040 
1041 /*
1042  * Device node creation. Device has been set up, now we can expose it to
1043  * the user.
1044  */
1045 
1046 void
1047 tty_makedev(struct tty *tp, struct ucred *cred, const char *fmt, ...)
1048 {
1049 	va_list ap;
1050 	struct cdev *dev;
1051 	const char *prefix = "tty";
1052 	char name[SPECNAMELEN - 3]; /* for "tty" and "cua". */
1053 	uid_t uid;
1054 	gid_t gid;
1055 	mode_t mode;
1056 
1057 	/* Remove "tty" prefix from devices like PTY's. */
1058 	if (tp->t_flags & TF_NOPREFIX)
1059 		prefix = "";
1060 
1061 	va_start(ap, fmt);
1062 	vsnrprintf(name, sizeof name, 32, fmt, ap);
1063 	va_end(ap);
1064 
1065 	if (cred == NULL) {
1066 		/* System device. */
1067 		uid = UID_ROOT;
1068 		gid = GID_WHEEL;
1069 		mode = S_IRUSR|S_IWUSR;
1070 	} else {
1071 		/* User device. */
1072 		uid = cred->cr_ruid;
1073 		gid = GID_TTY;
1074 		mode = S_IRUSR|S_IWUSR|S_IWGRP;
1075 	}
1076 
1077 	/* Master call-in device. */
1078 	dev = make_dev_cred(&ttydev_cdevsw, 0, cred,
1079 	    uid, gid, mode, "%s%s", prefix, name);
1080 	dev->si_drv1 = tp;
1081 	tp->t_dev = dev;
1082 
1083 	/* Slave call-in devices. */
1084 	if (tp->t_flags & TF_INITLOCK) {
1085 		dev = make_dev_cred(&ttyil_cdevsw, 0, cred,
1086 		    uid, gid, mode, "%s%s.init", prefix, name);
1087 		dev_depends(tp->t_dev, dev);
1088 		dev->si_drv1 = tp;
1089 		dev->si_drv2 = &tp->t_termios_init_in;
1090 
1091 		dev = make_dev_cred(&ttyil_cdevsw, 0, cred,
1092 		    uid, gid, mode, "%s%s.lock", prefix, name);
1093 		dev_depends(tp->t_dev, dev);
1094 		dev->si_drv1 = tp;
1095 		dev->si_drv2 = &tp->t_termios_lock_in;
1096 	}
1097 
1098 	/* Call-out devices. */
1099 	if (tp->t_flags & TF_CALLOUT) {
1100 		dev = make_dev_cred(&ttydev_cdevsw, 0, cred,
1101 		    UID_UUCP, GID_DIALER, 0660, "cua%s", name);
1102 		dev_depends(tp->t_dev, dev);
1103 		dev->si_drv1 = tp;
1104 
1105 		/* Slave call-out devices. */
1106 		if (tp->t_flags & TF_INITLOCK) {
1107 			dev = make_dev_cred(&ttyil_cdevsw, 0, cred,
1108 			    UID_UUCP, GID_DIALER, 0660, "cua%s.init", name);
1109 			dev_depends(tp->t_dev, dev);
1110 			dev->si_drv1 = tp;
1111 			dev->si_drv2 = &tp->t_termios_init_out;
1112 
1113 			dev = make_dev_cred(&ttyil_cdevsw, 0, cred,
1114 			    UID_UUCP, GID_DIALER, 0660, "cua%s.lock", name);
1115 			dev_depends(tp->t_dev, dev);
1116 			dev->si_drv1 = tp;
1117 			dev->si_drv2 = &tp->t_termios_lock_out;
1118 		}
1119 	}
1120 }
1121 
1122 /*
1123  * Signalling processes.
1124  */
1125 
1126 void
1127 tty_signal_sessleader(struct tty *tp, int sig)
1128 {
1129 	struct proc *p;
1130 
1131 	tty_lock_assert(tp, MA_OWNED);
1132 	MPASS(sig >= 1 && sig < NSIG);
1133 
1134 	/* Make signals start output again. */
1135 	tp->t_flags &= ~TF_STOPPED;
1136 
1137 	if (tp->t_session != NULL && tp->t_session->s_leader != NULL) {
1138 		p = tp->t_session->s_leader;
1139 		PROC_LOCK(p);
1140 		psignal(p, sig);
1141 		PROC_UNLOCK(p);
1142 	}
1143 }
1144 
1145 void
1146 tty_signal_pgrp(struct tty *tp, int sig)
1147 {
1148 	tty_lock_assert(tp, MA_OWNED);
1149 	MPASS(sig >= 1 && sig < NSIG);
1150 
1151 	/* Make signals start output again. */
1152 	tp->t_flags &= ~TF_STOPPED;
1153 
1154 	if (sig == SIGINFO && !(tp->t_termios.c_lflag & NOKERNINFO))
1155 		tty_info(tp);
1156 	if (tp->t_pgrp != NULL) {
1157 		PGRP_LOCK(tp->t_pgrp);
1158 		pgsignal(tp->t_pgrp, sig, 1);
1159 		PGRP_UNLOCK(tp->t_pgrp);
1160 	}
1161 }
1162 
1163 void
1164 tty_wakeup(struct tty *tp, int flags)
1165 {
1166 	if (tp->t_flags & TF_ASYNC && tp->t_sigio != NULL)
1167 		pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
1168 
1169 	if (flags & FWRITE) {
1170 		cv_broadcast(&tp->t_outwait);
1171 		selwakeup(&tp->t_outpoll);
1172 		KNOTE_LOCKED(&tp->t_outpoll.si_note, 0);
1173 	}
1174 	if (flags & FREAD) {
1175 		cv_broadcast(&tp->t_inwait);
1176 		selwakeup(&tp->t_inpoll);
1177 		KNOTE_LOCKED(&tp->t_inpoll.si_note, 0);
1178 	}
1179 }
1180 
1181 int
1182 tty_wait(struct tty *tp, struct cv *cv)
1183 {
1184 	int error;
1185 	int revokecnt = tp->t_revokecnt;
1186 
1187 #if 0
1188 	/* XXX: /dev/console also picks up Giant. */
1189 	tty_lock_assert(tp, MA_OWNED|MA_NOTRECURSED);
1190 #endif
1191 	tty_lock_assert(tp, MA_OWNED);
1192 
1193 	error = cv_wait_sig(cv, tp->t_mtx);
1194 
1195 	/* Restart the system call when we may have been revoked. */
1196 	if (tp->t_revokecnt != revokecnt)
1197 		return (ERESTART);
1198 
1199 	/* Bail out when the device slipped away. */
1200 	if (tty_gone(tp))
1201 		return (ENXIO);
1202 
1203 	return (error);
1204 }
1205 
1206 int
1207 tty_timedwait(struct tty *tp, struct cv *cv, int hz)
1208 {
1209 	int error;
1210 	int revokecnt = tp->t_revokecnt;
1211 
1212 #if 0
1213 	/* XXX: /dev/console also picks up Giant. */
1214 	tty_lock_assert(tp, MA_OWNED|MA_NOTRECURSED);
1215 #endif
1216 	tty_lock_assert(tp, MA_OWNED);
1217 
1218 	error = cv_timedwait_sig(cv, tp->t_mtx, hz);
1219 
1220 	/* Restart the system call when we may have been revoked. */
1221 	if (tp->t_revokecnt != revokecnt)
1222 		return (ERESTART);
1223 
1224 	/* Bail out when the device slipped away. */
1225 	if (tty_gone(tp))
1226 		return (ENXIO);
1227 
1228 	return (error);
1229 }
1230 
1231 void
1232 tty_flush(struct tty *tp, int flags)
1233 {
1234 	if (flags & FWRITE) {
1235 		tp->t_flags &= ~TF_HIWAT_OUT;
1236 		ttyoutq_flush(&tp->t_outq);
1237 		tty_wakeup(tp, FWRITE);
1238 		ttydevsw_pktnotify(tp, TIOCPKT_FLUSHWRITE);
1239 	}
1240 	if (flags & FREAD) {
1241 		tty_hiwat_in_unblock(tp);
1242 		ttyinq_flush(&tp->t_inq);
1243 		ttydevsw_inwakeup(tp);
1244 		ttydevsw_pktnotify(tp, TIOCPKT_FLUSHREAD);
1245 	}
1246 }
1247 
1248 static int
1249 tty_generic_ioctl(struct tty *tp, u_long cmd, void *data, struct thread *td)
1250 {
1251 	int error;
1252 
1253 	switch (cmd) {
1254 	/*
1255 	 * Modem commands.
1256 	 * The SER_* and TIOCM_* flags are the same, but one bit
1257 	 * shifted. I don't know why.
1258 	 */
1259 	case TIOCSDTR:
1260 		ttydevsw_modem(tp, SER_DTR, 0);
1261 		return (0);
1262 	case TIOCCDTR:
1263 		ttydevsw_modem(tp, 0, SER_DTR);
1264 		return (0);
1265 	case TIOCMSET: {
1266 		int bits = *(int *)data;
1267 		ttydevsw_modem(tp,
1268 		    (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1,
1269 		    ((~bits) & (TIOCM_DTR | TIOCM_RTS)) >> 1);
1270 		return (0);
1271 	}
1272 	case TIOCMBIS: {
1273 		int bits = *(int *)data;
1274 		ttydevsw_modem(tp, (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1, 0);
1275 		return (0);
1276 	}
1277 	case TIOCMBIC: {
1278 		int bits = *(int *)data;
1279 		ttydevsw_modem(tp, 0, (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1);
1280 		return (0);
1281 	}
1282 	case TIOCMGET:
1283 		*(int *)data = TIOCM_LE + (ttydevsw_modem(tp, 0, 0) << 1);
1284 		return (0);
1285 
1286 	case FIOASYNC:
1287 		if (*(int *)data)
1288 			tp->t_flags |= TF_ASYNC;
1289 		else
1290 			tp->t_flags &= ~TF_ASYNC;
1291 		return (0);
1292 	case FIONBIO:
1293 		/* This device supports non-blocking operation. */
1294 		return (0);
1295 	case FIONREAD:
1296 		*(int *)data = ttyinq_bytescanonicalized(&tp->t_inq);
1297 		return (0);
1298 	case FIOSETOWN:
1299 		if (tp->t_session != NULL && !tty_is_ctty(tp, td->td_proc))
1300 			/* Not allowed to set ownership. */
1301 			return (ENOTTY);
1302 
1303 		/* Temporarily unlock the TTY to set ownership. */
1304 		tty_unlock(tp);
1305 		error = fsetown(*(int *)data, &tp->t_sigio);
1306 		tty_lock(tp);
1307 		return (error);
1308 	case FIOGETOWN:
1309 		if (tp->t_session != NULL && !tty_is_ctty(tp, td->td_proc))
1310 			/* Not allowed to set ownership. */
1311 			return (ENOTTY);
1312 
1313 		/* Get ownership. */
1314 		*(int *)data = fgetown(&tp->t_sigio);
1315 		return (0);
1316 	case TIOCGETA:
1317 		/* Obtain terminal flags through tcgetattr(). */
1318 		bcopy(&tp->t_termios, data, sizeof(struct termios));
1319 		return (0);
1320 	case TIOCSETA:
1321 	case TIOCSETAW:
1322 	case TIOCSETAF: {
1323 		struct termios *t = data;
1324 
1325 		/*
1326 		 * Who makes up these funny rules? According to POSIX,
1327 		 * input baud rate is set equal to the output baud rate
1328 		 * when zero.
1329 		 */
1330 		if (t->c_ispeed == 0)
1331 			t->c_ispeed = t->c_ospeed;
1332 
1333 		/* Discard any unsupported bits. */
1334 		t->c_iflag &= TTYSUP_IFLAG;
1335 		t->c_oflag &= TTYSUP_OFLAG;
1336 		t->c_lflag &= TTYSUP_LFLAG;
1337 		t->c_cflag &= TTYSUP_CFLAG;
1338 
1339 		/* Set terminal flags through tcsetattr(). */
1340 		if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
1341 			error = tty_drain(tp);
1342 			if (error)
1343 				return (error);
1344 			if (cmd == TIOCSETAF)
1345 				tty_flush(tp, FREAD);
1346 		}
1347 
1348 		/*
1349 		 * Only call param() when the flags really change.
1350 		 */
1351 		if ((t->c_cflag & CIGNORE) == 0 &&
1352 		    (tp->t_termios.c_cflag != t->c_cflag ||
1353 		    tp->t_termios.c_ispeed != t->c_ispeed ||
1354 		    tp->t_termios.c_ospeed != t->c_ospeed)) {
1355 			error = ttydevsw_param(tp, t);
1356 			if (error)
1357 				return (error);
1358 
1359 			/* XXX: CLOCAL? */
1360 
1361 			tp->t_termios.c_cflag = t->c_cflag & ~CIGNORE;
1362 			tp->t_termios.c_ispeed = t->c_ispeed;
1363 			tp->t_termios.c_ospeed = t->c_ospeed;
1364 
1365 			/* Baud rate has changed - update watermarks. */
1366 			tty_watermarks(tp);
1367 		}
1368 
1369 		/* Copy new non-device driver parameters. */
1370 		tp->t_termios.c_iflag = t->c_iflag;
1371 		tp->t_termios.c_oflag = t->c_oflag;
1372 		tp->t_termios.c_lflag = t->c_lflag;
1373 		bcopy(t->c_cc, &tp->t_termios.c_cc, sizeof(t->c_cc));
1374 
1375 		ttydisc_optimize(tp);
1376 
1377 		if ((t->c_lflag & ICANON) == 0) {
1378 			/*
1379 			 * When in non-canonical mode, wake up all
1380 			 * readers. Canonicalize any partial input. VMIN
1381 			 * and VTIME could also be adjusted.
1382 			 */
1383 			ttyinq_canonicalize(&tp->t_inq);
1384 			tty_wakeup(tp, FREAD);
1385 		}
1386 
1387 		/*
1388 		 * For packet mode: notify the PTY consumer that VSTOP
1389 		 * and VSTART may have been changed.
1390 		 */
1391 		if (tp->t_termios.c_iflag & IXON &&
1392 		    tp->t_termios.c_cc[VSTOP] == CTRL('S') &&
1393 		    tp->t_termios.c_cc[VSTART] == CTRL('Q'))
1394 			ttydevsw_pktnotify(tp, TIOCPKT_DOSTOP);
1395 		else
1396 			ttydevsw_pktnotify(tp, TIOCPKT_NOSTOP);
1397 		return (0);
1398 	}
1399 	case TIOCGETD:
1400 		/* For compatibility - we only support TTYDISC. */
1401 		*(int *)data = TTYDISC;
1402 		return (0);
1403 	case TIOCGPGRP:
1404 		if (!tty_is_ctty(tp, td->td_proc))
1405 			return (ENOTTY);
1406 
1407 		if (tp->t_pgrp != NULL)
1408 			*(int *)data = tp->t_pgrp->pg_id;
1409 		else
1410 			*(int *)data = NO_PID;
1411 		return (0);
1412 	case TIOCGSID:
1413 		if (!tty_is_ctty(tp, td->td_proc))
1414 			return (ENOTTY);
1415 
1416 		MPASS(tp->t_session);
1417 		*(int *)data = tp->t_session->s_sid;
1418 		return (0);
1419 	case TIOCSCTTY: {
1420 		struct proc *p = td->td_proc;
1421 
1422 		/* XXX: This looks awful. */
1423 		tty_unlock(tp);
1424 		sx_xlock(&proctree_lock);
1425 		tty_lock(tp);
1426 
1427 		if (!SESS_LEADER(p)) {
1428 			/* Only the session leader may do this. */
1429 			sx_xunlock(&proctree_lock);
1430 			return (EPERM);
1431 		}
1432 
1433 		if (tp->t_session != NULL && tp->t_session == p->p_session) {
1434 			/* This is already our controlling TTY. */
1435 			sx_xunlock(&proctree_lock);
1436 			return (0);
1437 		}
1438 
1439 		if (!SESS_LEADER(p) || p->p_session->s_ttyvp != NULL ||
1440 		    (tp->t_session != NULL && tp->t_session->s_ttyvp != NULL)) {
1441 			/*
1442 			 * There is already a relation between a TTY and
1443 			 * a session, or the caller is not the session
1444 			 * leader.
1445 			 *
1446 			 * Allow the TTY to be stolen when the vnode is
1447 			 * NULL, but the reference to the TTY is still
1448 			 * active.
1449 			 */
1450 			sx_xunlock(&proctree_lock);
1451 			return (EPERM);
1452 		}
1453 
1454 		/* Connect the session to the TTY. */
1455 		tp->t_session = p->p_session;
1456 		tp->t_session->s_ttyp = tp;
1457 		tp->t_sessioncnt++;
1458 		sx_xunlock(&proctree_lock);
1459 
1460 		/* Assign foreground process group. */
1461 		tp->t_pgrp = p->p_pgrp;
1462 		PROC_LOCK(p);
1463 		p->p_flag |= P_CONTROLT;
1464 		PROC_UNLOCK(p);
1465 
1466 		return (0);
1467 	}
1468 	case TIOCSPGRP: {
1469 		struct pgrp *pg;
1470 
1471 		/*
1472 		 * XXX: Temporarily unlock the TTY to locate the process
1473 		 * group. This code would be lot nicer if we would ever
1474 		 * decompose proctree_lock.
1475 		 */
1476 		tty_unlock(tp);
1477 		sx_slock(&proctree_lock);
1478 		pg = pgfind(*(int *)data);
1479 		if (pg != NULL)
1480 			PGRP_UNLOCK(pg);
1481 		if (pg == NULL || pg->pg_session != td->td_proc->p_session) {
1482 			sx_sunlock(&proctree_lock);
1483 			tty_lock(tp);
1484 			return (EPERM);
1485 		}
1486 		tty_lock(tp);
1487 
1488 		/*
1489 		 * Determine if this TTY is the controlling TTY after
1490 		 * relocking the TTY.
1491 		 */
1492 		if (!tty_is_ctty(tp, td->td_proc)) {
1493 			sx_sunlock(&proctree_lock);
1494 			return (ENOTTY);
1495 		}
1496 		tp->t_pgrp = pg;
1497 		sx_sunlock(&proctree_lock);
1498 
1499 		/* Wake up the background process groups. */
1500 		cv_broadcast(&tp->t_bgwait);
1501 		return (0);
1502 	}
1503 	case TIOCFLUSH: {
1504 		int flags = *(int *)data;
1505 
1506 		if (flags == 0)
1507 			flags = (FREAD|FWRITE);
1508 		else
1509 			flags &= (FREAD|FWRITE);
1510 		tty_flush(tp, flags);
1511 		return (0);
1512 	}
1513 	case TIOCDRAIN:
1514 		/* Drain TTY output. */
1515 		return tty_drain(tp);
1516 	case TIOCCONS:
1517 		/* Set terminal as console TTY. */
1518 		if (*(int *)data) {
1519 			error = priv_check(td, PRIV_TTY_CONSOLE);
1520 			if (error)
1521 				return (error);
1522 
1523 			/*
1524 			 * XXX: constty should really need to be locked!
1525 			 * XXX: allow disconnected constty's to be stolen!
1526 			 */
1527 
1528 			if (constty == tp)
1529 				return (0);
1530 			if (constty != NULL)
1531 				return (EBUSY);
1532 
1533 			tty_unlock(tp);
1534 			constty_set(tp);
1535 			tty_lock(tp);
1536 		} else if (constty == tp) {
1537 			constty_clear();
1538 		}
1539 		return (0);
1540 	case TIOCGWINSZ:
1541 		/* Obtain window size. */
1542 		bcopy(&tp->t_winsize, data, sizeof(struct winsize));
1543 		return (0);
1544 	case TIOCSWINSZ:
1545 		/* Set window size. */
1546 		if (bcmp(&tp->t_winsize, data, sizeof(struct winsize)) == 0)
1547 			return (0);
1548 		bcopy(data, &tp->t_winsize, sizeof(struct winsize));
1549 		tty_signal_pgrp(tp, SIGWINCH);
1550 		return (0);
1551 	case TIOCEXCL:
1552 		tp->t_flags |= TF_EXCLUDE;
1553 		return (0);
1554 	case TIOCNXCL:
1555 		tp->t_flags &= ~TF_EXCLUDE;
1556 		return (0);
1557 	case TIOCOUTQ:
1558 		*(unsigned int *)data = ttyoutq_bytesused(&tp->t_outq);
1559 		return (0);
1560 	case TIOCSTOP:
1561 		tp->t_flags |= TF_STOPPED;
1562 		ttydevsw_pktnotify(tp, TIOCPKT_STOP);
1563 		return (0);
1564 	case TIOCSTART:
1565 		tp->t_flags &= ~TF_STOPPED;
1566 		ttydevsw_outwakeup(tp);
1567 		ttydevsw_pktnotify(tp, TIOCPKT_START);
1568 		return (0);
1569 	case TIOCSTAT:
1570 		tty_info(tp);
1571 		return (0);
1572 	}
1573 
1574 #ifdef COMPAT_43TTY
1575 	return tty_ioctl_compat(tp, cmd, data, td);
1576 #else /* !COMPAT_43TTY */
1577 	return (ENOIOCTL);
1578 #endif /* COMPAT_43TTY */
1579 }
1580 
1581 int
1582 tty_ioctl(struct tty *tp, u_long cmd, void *data, struct thread *td)
1583 {
1584 	int error;
1585 
1586 	tty_lock_assert(tp, MA_OWNED);
1587 
1588 	if (tty_gone(tp))
1589 		return (ENXIO);
1590 
1591 	error = ttydevsw_ioctl(tp, cmd, data, td);
1592 	if (error == ENOIOCTL)
1593 		error = tty_generic_ioctl(tp, cmd, data, td);
1594 
1595 	return (error);
1596 }
1597 
1598 dev_t
1599 tty_udev(struct tty *tp)
1600 {
1601 	if (tp->t_dev)
1602 		return dev2udev(tp->t_dev);
1603 	else
1604 		return NODEV;
1605 }
1606 
1607 int
1608 tty_checkoutq(struct tty *tp)
1609 {
1610 
1611 	/* 256 bytes should be enough to print a log message. */
1612 	return (ttyoutq_bytesleft(&tp->t_outq) >= 256);
1613 }
1614 
1615 void
1616 tty_hiwat_in_block(struct tty *tp)
1617 {
1618 
1619 	if ((tp->t_flags & TF_HIWAT_IN) == 0 &&
1620 	    tp->t_termios.c_iflag & IXOFF &&
1621 	    tp->t_termios.c_cc[VSTOP] != _POSIX_VDISABLE) {
1622 		/*
1623 		 * Input flow control. Only enter the high watermark when we
1624 		 * can successfully store the VSTOP character.
1625 		 */
1626 		if (ttyoutq_write_nofrag(&tp->t_outq,
1627 		    &tp->t_termios.c_cc[VSTOP], 1) == 0)
1628 			tp->t_flags |= TF_HIWAT_IN;
1629 	} else {
1630 		/* No input flow control. */
1631 		tp->t_flags |= TF_HIWAT_IN;
1632 	}
1633 }
1634 
1635 void
1636 tty_hiwat_in_unblock(struct tty *tp)
1637 {
1638 
1639 	if (tp->t_flags & TF_HIWAT_IN &&
1640 	    tp->t_termios.c_iflag & IXOFF &&
1641 	    tp->t_termios.c_cc[VSTART] != _POSIX_VDISABLE) {
1642 		/*
1643 		 * Input flow control. Only leave the high watermark when we
1644 		 * can successfully store the VSTART character.
1645 		 */
1646 		if (ttyoutq_write_nofrag(&tp->t_outq,
1647 		    &tp->t_termios.c_cc[VSTART], 1) == 0)
1648 			tp->t_flags &= ~TF_HIWAT_IN;
1649 	} else {
1650 		/* No input flow control. */
1651 		tp->t_flags &= ~TF_HIWAT_IN;
1652 	}
1653 
1654 	if (!tty_gone(tp))
1655 		ttydevsw_inwakeup(tp);
1656 }
1657 
1658 static int
1659 ttyhook_defrint(struct tty *tp, char c, int flags)
1660 {
1661 
1662 	if (ttyhook_rint_bypass(tp, &c, 1) != 1)
1663 		return (-1);
1664 
1665 	return (0);
1666 }
1667 
1668 int
1669 ttyhook_register(struct tty **rtp, struct thread *td, int fd,
1670     struct ttyhook *th, void *softc)
1671 {
1672 	struct tty *tp;
1673 	struct file *fp;
1674 	struct cdev *dev;
1675 	struct cdevsw *cdp;
1676 	int error;
1677 
1678 	/* Validate the file descriptor. */
1679 	if (fget(td, fd, &fp) != 0)
1680 		return (EINVAL);
1681 
1682 	/* Make sure the vnode is bound to a character device. */
1683 	error = EINVAL;
1684 	if (fp->f_type != DTYPE_VNODE || fp->f_vnode->v_type != VCHR ||
1685 	    fp->f_vnode->v_rdev == NULL)
1686 		goto done1;
1687 	dev = fp->f_vnode->v_rdev;
1688 
1689 	/* Make sure it is a TTY. */
1690 	cdp = dev_refthread(dev);
1691 	if (cdp == NULL)
1692 		goto done1;
1693 	if ((cdp->d_flags & D_TTY) == 0)
1694 		goto done2;
1695 	tp = dev->si_drv1;
1696 
1697 	/* Try to attach the hook to the TTY. */
1698 	error = EBUSY;
1699 	tty_lock(tp);
1700 	MPASS((tp->t_hook == NULL) == ((tp->t_flags & TF_HOOK) == 0));
1701 	if (tp->t_flags & TF_HOOK)
1702 		goto done3;
1703 
1704 	tp->t_flags |= TF_HOOK;
1705 	tp->t_hook = th;
1706 	tp->t_hooksoftc = softc;
1707 	*rtp = tp;
1708 	error = 0;
1709 
1710 	/* Maybe we can switch into bypass mode now. */
1711 	ttydisc_optimize(tp);
1712 
1713 	/* Silently convert rint() calls to rint_bypass() when possible. */
1714 	if (!ttyhook_hashook(tp, rint) && ttyhook_hashook(tp, rint_bypass))
1715 		th->th_rint = ttyhook_defrint;
1716 
1717 done3:	tty_unlock(tp);
1718 done2:	dev_relthread(dev);
1719 done1:	fdrop(fp, td);
1720 	return (error);
1721 }
1722 
1723 void
1724 ttyhook_unregister(struct tty *tp)
1725 {
1726 
1727 	tty_lock_assert(tp, MA_OWNED);
1728 	MPASS(tp->t_flags & TF_HOOK);
1729 
1730 	/* Disconnect the hook. */
1731 	tp->t_flags &= ~TF_HOOK;
1732 	tp->t_hook = NULL;
1733 
1734 	/* Maybe we need to leave bypass mode. */
1735 	ttydisc_optimize(tp);
1736 
1737 	/* Maybe deallocate the TTY as well. */
1738 	tty_rel_free(tp);
1739 }
1740 
1741 #include "opt_ddb.h"
1742 #ifdef DDB
1743 #include <ddb/ddb.h>
1744 
1745 static struct {
1746 	int flag;
1747 	char val;
1748 } ttystates[] = {
1749 #if 0
1750 	{ TF_NOPREFIX,	'N' },
1751 #endif
1752 	{ TF_INITLOCK,	'I' },
1753 	{ TF_CALLOUT,	'C' },
1754 
1755 	/* Keep these together -> 'Oi' and 'Oo'. */
1756 	{ TF_OPENED,	'O' },
1757 	{ TF_OPENED_IN,	'i' },
1758 	{ TF_OPENED_OUT,'o' },
1759 
1760 	{ TF_GONE,	'G' },
1761 	{ TF_OPENCLOSE,	'B' },
1762 	{ TF_ASYNC,	'Y' },
1763 	{ TF_LITERAL,	'L' },
1764 
1765 	/* Keep these together -> 'Hi' and 'Ho'. */
1766 	{ TF_HIWAT,	'H' },
1767 	{ TF_HIWAT_IN,	'i' },
1768 	{ TF_HIWAT_OUT,	'o' },
1769 
1770 	{ TF_STOPPED,	'S' },
1771 	{ TF_EXCLUDE,	'X' },
1772 	{ TF_BYPASS,	'l' },
1773 	{ TF_ZOMBIE,	'Z' },
1774 	{ TF_HOOK,	's' },
1775 
1776 	{ 0,	       '\0' },
1777 };
1778 
1779 /* DDB command to show TTY statistics. */
1780 DB_SHOW_COMMAND(ttys, db_show_ttys)
1781 {
1782 	struct tty *tp;
1783 	size_t isiz, osiz;
1784 	int i, j;
1785 
1786 	/* Make the output look like `pstat -t'. */
1787 	db_printf("      LINE   INQ  CAN  LIN  LOW  OUTQ  USE  LOW   "
1788 	    "COL  SESS  PGID STATE\n");
1789 
1790 	TAILQ_FOREACH(tp, &tty_list, t_list) {
1791 		isiz = tp->t_inq.ti_nblocks * TTYINQ_DATASIZE;
1792 		osiz = tp->t_outq.to_nblocks * TTYOUTQ_DATASIZE;
1793 
1794 		db_printf("%10s %5zu %4u %4u %4zu %5zu %4u %4zu %5u %5d %5d ",
1795 		    tty_devname(tp),
1796 		    isiz,
1797 		    tp->t_inq.ti_linestart - tp->t_inq.ti_begin,
1798 		    tp->t_inq.ti_end - tp->t_inq.ti_linestart,
1799 		    isiz - tp->t_inlow,
1800 		    osiz,
1801 		    tp->t_outq.to_end - tp->t_outq.to_begin,
1802 		    osiz - tp->t_outlow,
1803 		    tp->t_column,
1804 		    tp->t_session ? tp->t_session->s_sid : 0,
1805 		    tp->t_pgrp ? tp->t_pgrp->pg_id : 0);
1806 
1807 		/* Flag bits. */
1808 		for (i = j = 0; ttystates[i].flag; i++)
1809 			if (tp->t_flags & ttystates[i].flag) {
1810 				db_printf("%c", ttystates[i].val);
1811 				j++;
1812 			}
1813 		if (j == 0)
1814 			db_printf("-");
1815 		db_printf("\n");
1816 	}
1817 }
1818 #endif /* DDB */
1819