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