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