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