2 * Copyright (c) 2006 Robert N. M. Watson
3 * Copyright (c) 2006 Olivier Houchard
4 * Copyright (c) 2003 Networks Associates Technology, Inc.
7 * This software was developed for the FreeBSD Project in part by Network
8 * Associates Laboratories, the Security Research Division of Network
9 * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"),
10 * as part of the DARPA CHATS research program.
12 * Copyright (c) 1982, 1986, 1989, 1993
13 * The Regents of the University of California. All rights reserved.
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 * notice, this list of conditions and the following disclaimer in the
22 * documentation and/or other materials provided with the distribution.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 * @(#)tty_pty.c 8.4 (Berkeley) 2/20/95
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
46 * Pseudo-teletype Driver
47 * (Actually two drivers, requiring two entries in 'cdevsw')
49 #include "opt_compat.h"
51 #include <sys/param.h>
52 #include <sys/systm.h>
54 #include <sys/mutex.h>
56 #if defined(COMPAT_43TTY)
57 #include <sys/ioctl_compat.h>
61 #include <sys/queue.h>
63 #include <sys/fcntl.h>
65 #include <sys/kernel.h>
66 #include <sys/vnode.h>
67 #include <sys/signalvar.h>
68 #include <sys/malloc.h>
70 #include <sys/sysctl.h>
71 #include <sys/filio.h>
73 static MALLOC_DEFINE(M_PTY, "ptys", "pty data structures");
75 static void ptsstart(struct tty *tp);
76 static void ptsstop(struct tty *tp, int rw);
77 static void ptcwakeup(struct tty *tp, int flag);
79 static d_open_t ptsopen;
80 static d_close_t ptsclose;
81 static d_read_t ptsread;
82 static d_write_t ptswrite;
83 static d_ioctl_t ptsioctl;
84 static d_ioctl_t ptcioctl;
85 static d_open_t ptcopen;
86 static d_close_t ptcclose;
87 static d_read_t ptcread;
88 static d_write_t ptcwrite;
89 static d_poll_t ptcpoll;
91 static struct cdevsw pts_cdevsw = {
92 .d_version = D_VERSION,
100 .d_flags = D_TTY | D_NEEDGIANT,
101 .d_kqfilter = ttykqfilter,
104 static struct cdevsw ptc_cdevsw = {
105 .d_version = D_VERSION,
113 .d_flags = D_TTY | D_NEEDGIANT,
114 .d_kqfilter = ttykqfilter,
117 #define BUFSIZ 100 /* Chunk size iomoved to/from user */
119 #define TSA_PTC_READ(tp) ((void *)&(tp)->t_outq.c_cf)
120 #define TSA_PTC_WRITE(tp) ((void *)&(tp)->t_rawq.c_cl)
121 #define TSA_PTS_READ(tp) ((void *)&(tp)->t_canq)
123 #define NUM_TO_MINOR(c) ((c & 0xff) | ((c & ~0xff) << 16))
125 * Once a tty is allocated, it cannot (currently) be freed. As such,
126 * we keep a global list of ptys that have been used so we can recycle
127 * them. Another list is provided for released pts, which are
128 * not currently allocated, permitting reuse. pt_flags holds state
129 * associated with a particular session, so isn't overloaded for this.
130 * When a pty descriptor is unused, its number is set to -1 giving
131 * more consistent and traditional allocation orders to pty numbers.
133 * Locking: (p) indicates that the field is locked by the global pt_mtx.
134 * (c) indicates the value is constant after allocation. Other fields
135 * await tty locking generally, and are protected by Giant.
138 int pt_num; /* (c) pty number */
139 LIST_ENTRY(pt_desc) pt_list; /* (p) global pty list */
142 struct selinfo pt_selr, pt_selw;
146 struct cdev *pt_devs, *pt_devc;
147 int pt_pts_open, pt_ptc_open;
148 struct prison *pt_prison;
151 static struct mtx pt_mtx;
152 static LIST_HEAD(,pt_desc) pt_list;
153 static LIST_HEAD(,pt_desc) pt_free_list;
155 #define PF_PKT 0x008 /* packet mode */
156 #define PF_STOPPED 0x010 /* user told stopped */
157 #define PF_NOSTOP 0x040
158 #define PF_UCNTL 0x080 /* user control mode */
160 static unsigned int next_avail_nb;
162 static int use_pts = 0;
164 static unsigned int max_pts = 1000;
166 static unsigned int nb_allocated;
168 TUNABLE_INT("kern.pts.enable", &use_pts);
170 SYSCTL_NODE(_kern, OID_AUTO, pts, CTLFLAG_RD, 0, "pts");
172 SYSCTL_INT(_kern_pts, OID_AUTO, enable, CTLFLAG_RW, &use_pts, 0,
175 SYSCTL_INT(_kern_pts, OID_AUTO, max, CTLFLAG_RW, &max_pts, 0, "max pts");
178 * If there's a free pty descriptor in the pty descriptor list, retrieve it.
179 * Otherwise, allocate a new one, initialize it, and hook it up. If there's
180 * not a tty number, reject.
182 static struct pt_desc *
189 if (nb_allocated >= max_pts || nb_allocated == 0xffffff) {
194 pt = LIST_FIRST(&pt_free_list);
196 LIST_REMOVE(pt, pt_list);
197 LIST_INSERT_HEAD(&pt_list, pt, pt_list);
200 nb = next_avail_nb++;
202 pt = malloc(sizeof(*pt), M_PTY, M_WAITOK | M_ZERO);
205 LIST_INSERT_HEAD(&pt_list, pt, pt_list);
207 pt->pt_tty = ttyalloc();
213 * Release a pty descriptor back to the pool for reuse. The pty number
217 pty_release(struct pt_desc *pt)
220 KASSERT(pt->pt_ptc_open == 0 && pt->pt_pts_open == 0,
221 ("pty_release: pts/%d freed while open\n", pt->pt_num));
222 KASSERT(pt->pt_devs == NULL && pt->pt_devc == NULL,
223 ("pty_release: pts/%d freed whith non-null struct cdev\n", pt->pt_num));
224 mtx_assert(&pt_mtx, MA_OWNED);
226 LIST_REMOVE(pt, pt_list);
227 LIST_INSERT_HEAD(&pt_free_list, pt, pt_list);
231 * Given a pty descriptor, if both endpoints are closed, release all
232 * resources and destroy the device nodes to flush file system level
233 * state for the tty (owner, avoid races, etc).
236 pty_maybecleanup(struct pt_desc *pt)
239 if (pt->pt_ptc_open || pt->pt_pts_open)
242 if (pt->pt_tty->t_refcnt > 1)
246 printf("destroying pty %d\n", pt->pt_num);
248 destroy_dev(pt->pt_devs);
249 destroy_dev(pt->pt_devc);
250 pt->pt_devs = pt->pt_devc = NULL;
251 pt->pt_tty->t_dev = NULL;
262 ptsopen(struct cdev *dev, int flag, int devtype, struct thread *td)
270 if ((tp->t_state & TS_ISOPEN) == 0)
271 ttyinitmode(tp, 1, 0);
272 else if (tp->t_state & TS_XCLUDE && priv_check(td,
273 PRIV_TTY_EXCLUSIVE)) {
275 } else if (pt->pt_prison != td->td_ucred->cr_prison &&
276 priv_check(td, PRIV_TTY_PRISON)) {
279 if (tp->t_oproc) /* Ctrlr still around. */
281 while ((tp->t_state & TS_CARR_ON) == 0) {
282 if (flag & FNONBLOCK)
284 error = ttysleep(tp, TSA_CARR_ON(tp), TTIPRI | PCATCH,
289 error = ttyld_open(tp, dev);
291 ptcwakeup(tp, FREAD|FWRITE);
298 ptsclose(struct cdev *dev, int flag, int mode, struct thread *td)
300 struct pt_desc *pt = dev->si_drv1;
305 err = ttyld_close(tp, flag);
306 ptsstop(tp, FREAD|FWRITE);
307 (void) tty_close(tp);
309 pty_maybecleanup(pt);
314 ptsread(struct cdev *dev, struct uio *uio, int flag)
316 struct tty *tp = dev->si_tty;
320 error = ttyld_read(tp, uio, flag);
321 ptcwakeup(tp, FWRITE);
326 * Write to pseudo-tty.
327 * Wakeups of controlling tty will happen
328 * indirectly, when tty driver calls ptsstart.
331 ptswrite(struct cdev *dev, struct uio *uio, int flag)
336 if (tp->t_oproc == 0)
338 return (ttyld_write(tp, uio, flag));
342 * Start output on pseudo-tty.
343 * Wake up process selecting or sleeping for input from controlling tty.
346 ptsstart(struct tty *tp)
348 struct pt_desc *pt = tp->t_dev->si_drv1;
350 if (tp->t_state & TS_TTSTOP)
352 if (pt->pt_flags & PF_STOPPED) {
353 pt->pt_flags &= ~PF_STOPPED;
354 pt->pt_send = TIOCPKT_START;
356 ptcwakeup(tp, FREAD);
360 ptcwakeup(struct tty *tp, int flag)
362 struct pt_desc *pt = tp->t_dev->si_drv1;
365 selwakeup(&pt->pt_selr);
366 wakeup(TSA_PTC_READ(tp));
369 selwakeup(&pt->pt_selw);
370 wakeup(TSA_PTC_WRITE(tp));
375 * ptcopen implementes exclusive access to the master/control device
376 * as well as creating the slave device based on the credential of the
377 * process opening the master. By creating the slave here, we avoid
378 * a race to access the master in terms of having a process with access
379 * to an incorrectly owned slave, but it does create the possibility
380 * that a racing process can cause a ptmx user to get EIO if it gets
381 * there first. Consumers of ptmx must look for EIO and retry if it
382 * happens. VFS locking may actually prevent this from occurring due
383 * to the lookup into devfs holding the vnode lock through open, but
384 * it's better to be careful.
387 ptcopen(struct cdev *dev, int flag, int devtype, struct thread *td)
395 * In case we have destroyed the struct tty at the last connect time,
396 * we need to recreate it.
398 if (pt->pt_tty == NULL) {
399 pt->pt_tty = ttyalloc();
400 dev->si_tty = pt->pt_tty;
407 * XXX: Might want to make the ownership/permissions here more
413 pt->pt_devs = devs = make_dev_cred(&pts_cdevsw,
414 NUM_TO_MINOR(pt->pt_num),
415 td->td_ucred, UID_ROOT, GID_WHEEL, 0666, "pts/%d",
418 devs->si_tty = pt->pt_tty;
419 pt->pt_tty->t_dev = devs;
422 tp->t_oproc = ptsstart;
423 tp->t_stop = ptsstop;
425 tp->t_lflag &= ~EXTPROC;
427 pt->pt_prison = td->td_ucred->cr_prison;
436 ptcclose(struct cdev *dev, int flags, int fmt, struct thread *td)
438 struct pt_desc *pt = dev->si_drv1;
445 * XXX MDMBUF makes no sense for ptys but would inhibit the above
446 * l_modem(). CLOCAL makes sense but isn't supported. Special
447 * l_modem()s that ignore carrier drop make no sense for ptys but
448 * may be in use because other parts of the line discipline make
449 * sense for ptys. Recover by doing everything that a normal
450 * ttymodem() would have done except for sending a SIGHUP.
452 if (tp->t_state & TS_ISOPEN) {
453 tp->t_state &= ~(TS_CARR_ON | TS_CONNECTED);
454 tp->t_state |= TS_ZOMBIE;
455 ttyflush(tp, FREAD | FWRITE);
458 tp->t_oproc = 0; /* mark closed */
460 pty_maybecleanup(pt);
465 ptcread(struct cdev *dev, struct uio *uio, int flag)
467 struct tty *tp = dev->si_tty;
468 struct pt_desc *pt = dev->si_drv1;
473 * We want to block until the slave
474 * is open, and there's something to read;
475 * but if we lost the slave or we're NBIO,
476 * then return the appropriate error instead.
479 if (tp->t_state&TS_ISOPEN) {
480 if (pt->pt_flags&PF_PKT && pt->pt_send) {
481 error = ureadc((int)pt->pt_send, uio);
484 if (pt->pt_send & TIOCPKT_IOCTL) {
485 cc = min(uio->uio_resid,
486 sizeof(tp->t_termios));
487 uiomove(&tp->t_termios, cc, uio);
492 if (pt->pt_flags&PF_UCNTL && pt->pt_ucntl) {
493 error = ureadc((int)pt->pt_ucntl, uio);
499 if (tp->t_outq.c_cc && (tp->t_state&TS_TTSTOP) == 0)
502 if ((tp->t_state & TS_CONNECTED) == 0)
503 return (0); /* EOF */
504 if (flag & O_NONBLOCK)
505 return (EWOULDBLOCK);
506 error = tsleep(TSA_PTC_READ(tp), TTIPRI | PCATCH, "ptcin", 0);
510 if (pt->pt_flags & (PF_PKT|PF_UCNTL))
511 error = ureadc(0, uio);
512 while (uio->uio_resid > 0 && error == 0) {
513 cc = q_to_b(&tp->t_outq, buf, min(uio->uio_resid, BUFSIZ));
516 error = uiomove(buf, cc, uio);
523 ptsstop(struct tty *tp, int flush)
525 struct pt_desc *pt = tp->t_dev->si_drv1;
528 /* note: FLUSHREAD and FLUSHWRITE already ok */
530 flush = TIOCPKT_STOP;
531 pt->pt_flags |= PF_STOPPED;
533 pt->pt_flags &= ~PF_STOPPED;
534 pt->pt_send |= flush;
535 /* change of perspective */
545 ptcpoll(struct cdev *dev, int events, struct thread *td)
547 struct tty *tp = dev->si_tty;
548 struct pt_desc *pt = dev->si_drv1;
552 if ((tp->t_state & TS_CONNECTED) == 0)
554 (POLLHUP | POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM));
557 * Need to block timeouts (ttrstart).
561 if (events & (POLLIN | POLLRDNORM))
562 if ((tp->t_state & TS_ISOPEN) &&
563 ((tp->t_outq.c_cc && (tp->t_state & TS_TTSTOP) == 0) ||
564 ((pt->pt_flags & PF_PKT) && pt->pt_send) ||
565 ((pt->pt_flags & PF_UCNTL) && pt->pt_ucntl)))
566 revents |= events & (POLLIN | POLLRDNORM);
568 if (events & (POLLOUT | POLLWRNORM))
569 if (tp->t_state & TS_ISOPEN &&
570 (((tp->t_rawq.c_cc + tp->t_canq.c_cc < TTYHOG - 2) ||
571 (tp->t_canq.c_cc == 0 && (tp->t_lflag & ICANON)))))
572 revents |= events & (POLLOUT | POLLWRNORM);
574 if (events & POLLHUP)
575 if ((tp->t_state & TS_CARR_ON) == 0)
579 if (events & (POLLIN | POLLRDNORM))
580 selrecord(td, &pt->pt_selr);
582 if (events & (POLLOUT | POLLWRNORM))
583 selrecord(td, &pt->pt_selw);
591 ptcwrite(struct cdev *dev, struct uio *uio, int flag)
593 struct tty *tp = dev->si_tty;
596 u_char locbuf[BUFSIZ];
601 if ((tp->t_state&TS_ISOPEN) == 0)
603 while (uio->uio_resid > 0 || cc > 0) {
605 cc = min(uio->uio_resid, BUFSIZ);
607 error = uiomove(cp, cc, uio);
610 /* check again for safety */
611 if ((tp->t_state & TS_ISOPEN) == 0) {
612 /* adjust for data copied in but not written */
613 uio->uio_resid += cc;
618 if ((tp->t_rawq.c_cc + tp->t_canq.c_cc) >= TTYHOG - 2 &&
619 (tp->t_canq.c_cc > 0 || !(tp->t_lflag&ICANON))) {
620 wakeup(TSA_HUP_OR_INPUT(tp));
623 ttyld_rint(tp, *cp++);
632 * Come here to wait for slave to open, for space
633 * in outq, or space in rawq, or an empty canq.
635 if ((tp->t_state & TS_CONNECTED) == 0) {
636 /* adjust for data copied in but not written */
637 uio->uio_resid += cc;
640 if (flag & IO_NDELAY) {
641 /* adjust for data copied in but not written */
642 uio->uio_resid += cc;
644 return (EWOULDBLOCK);
647 error = tsleep(TSA_PTC_WRITE(tp), TTOPRI | PCATCH, "ptcout", 0);
649 /* adjust for data copied in but not written */
650 uio->uio_resid += cc;
657 ptcioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
659 struct tty *tp = dev->si_tty;
660 struct pt_desc *pt = dev->si_drv1;
661 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
662 defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
670 * We avoid calling ttioctl on the controller since,
671 * in that case, tp must be the controlling terminal.
673 *(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : 0;
678 if (pt->pt_flags & PF_UCNTL)
680 pt->pt_flags |= PF_PKT;
682 pt->pt_flags &= ~PF_PKT;
687 if (pt->pt_flags & PF_PKT)
689 pt->pt_flags |= PF_UCNTL;
691 pt->pt_flags &= ~PF_UCNTL;
694 *(unsigned int *)data = pt->pt_num;
699 * The rest of the ioctls shouldn't be called until
702 if ((tp->t_state & TS_ISOPEN) == 0) {
703 if (cmd == TIOCGETA) {
705 * TIOCGETA is used by isatty() to make sure it's
706 * a tty. Linux openpty() calls isatty() very early,
707 * before the slave is opened, so don't actually
708 * fill the struct termios, but just let isatty()
713 if (cmd != FIONBIO && cmd != FIOASYNC)
727 * IF CONTROLLER STTY THEN MUST FLUSH TO PREVENT A HANG.
728 * ttywflush(tp) will hang if there are characters in
731 ndflush(&tp->t_outq, tp->t_outq.c_cc);
734 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
735 defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
737 ival = IOCPARM_IVAL(data);
738 data = (caddr_t)&ival;
742 if (*(unsigned int *)data >= NSIG ||
743 *(unsigned int *)data == 0)
745 if ((tp->t_lflag&NOFLSH) == 0)
746 ttyflush(tp, FREAD|FWRITE);
747 if (tp->t_pgrp != NULL) {
748 PGRP_LOCK(tp->t_pgrp);
749 pgsignal(tp->t_pgrp, *(unsigned int *)data, 1);
750 PGRP_UNLOCK(tp->t_pgrp);
752 if ((*(unsigned int *)data == SIGINFO) &&
753 ((tp->t_lflag&NOKERNINFO) == 0))
757 return (ptsioctl(dev, cmd, data, flag, td));
761 ptsioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
763 struct tty *tp = dev->si_tty;
764 struct pt_desc *pt = dev->si_drv1;
765 u_char *cc = tp->t_cc;
768 if (cmd == TIOCEXT) {
770 * When the EXTPROC bit is being toggled, we need
771 * to send an TIOCPKT_IOCTL if the packet driver
775 if (pt->pt_flags & PF_PKT) {
776 pt->pt_send |= TIOCPKT_IOCTL;
777 ptcwakeup(tp, FREAD);
779 tp->t_lflag |= EXTPROC;
781 if ((tp->t_lflag & EXTPROC) &&
782 (pt->pt_flags & PF_PKT)) {
783 pt->pt_send |= TIOCPKT_IOCTL;
784 ptcwakeup(tp, FREAD);
786 tp->t_lflag &= ~EXTPROC;
790 error = ttioctl(tp, cmd, data, flag);
791 if (error == ENOTTY) {
792 if (pt->pt_flags & PF_UCNTL &&
793 (cmd & ~0xff) == UIOCCMD(0)) {
795 pt->pt_ucntl = (u_char)cmd;
796 ptcwakeup(tp, FREAD);
803 * If external processing and packet mode send ioctl packet.
805 if ((tp->t_lflag&EXTPROC) && (pt->pt_flags & PF_PKT)) {
819 pt->pt_send |= TIOCPKT_IOCTL;
820 ptcwakeup(tp, FREAD);
826 stop = (tp->t_iflag & IXON) && CCEQ(cc[VSTOP], CTRL('s'))
827 && CCEQ(cc[VSTART], CTRL('q'));
828 if (pt->pt_flags & PF_NOSTOP) {
830 pt->pt_send &= ~TIOCPKT_NOSTOP;
831 pt->pt_send |= TIOCPKT_DOSTOP;
832 pt->pt_flags &= ~PF_NOSTOP;
833 ptcwakeup(tp, FREAD);
837 pt->pt_send &= ~TIOCPKT_DOSTOP;
838 pt->pt_send |= TIOCPKT_NOSTOP;
839 pt->pt_flags |= PF_NOSTOP;
840 ptcwakeup(tp, FREAD);
847 * Match lookups on /dev/ptmx, find the next free pty (if any), set up
848 * the pty descriptor, register it, and return a reference to the master.
850 * pts == /dev/pts/xxx (oldstyle: ttyp...)
851 * ptc == /dev/pty/xxx (oldstyle: ptyp...)
854 pty_clone(void *arg, struct ucred *cred, char *name, int namelen,
866 if (strcmp(name, "ptmx") != 0)
874 * XXX: Lack of locking here considered worrying. We expose the
875 * pts/pty device nodes before they are fully initialized, although
876 * Giant likely protects us (unless make_dev blocks...?).
878 * XXX: If a process performs a lookup on /dev/ptmx but never an
879 * open, we won't GC the device node. We should have a callout
880 * sometime later that GC's device instances that were never
881 * opened, or some way to tell devfs that "this had better be for
882 * an open() or we won't create a device".
884 pt->pt_devc = devc = make_dev_cred(&ptc_cdevsw,
885 NUM_TO_MINOR(pt->pt_num), cred, UID_ROOT, GID_WHEEL, 0666,
886 "pty/%d", pt->pt_num);
890 devc->si_tty = pt->pt_tty;
894 printf("pty_clone: allocated pty %d to uid %d\n", pt->pt_num,
901 pty_drvinit(void *unused)
904 mtx_init(&pt_mtx, "pt_mtx", NULL, MTX_DEF);
906 LIST_INIT(&pt_free_list);
907 EVENTHANDLER_REGISTER(dev_clone, pty_clone, 0, 1000);
910 SYSINIT(ptydev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE,pty_drvinit,NULL)