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