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