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