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