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