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>
60 #include <sys/queue.h>
62 #include <sys/fcntl.h>
64 #include <sys/kernel.h>
65 #include <sys/vnode.h>
66 #include <sys/signalvar.h>
67 #include <sys/malloc.h>
69 #include <sys/sysctl.h>
70 #include <sys/filio.h>
72 static MALLOC_DEFINE(M_PTY, "ptys", "pty data structures");
74 static void ptsstart(struct tty *tp);
75 static void ptsstop(struct tty *tp, int rw);
76 static void ptcwakeup(struct tty *tp, int flag);
78 static d_open_t ptsopen;
79 static d_close_t ptsclose;
80 static d_read_t ptsread;
81 static d_write_t ptswrite;
82 static d_ioctl_t ptsioctl;
83 static d_ioctl_t ptcioctl;
84 static d_open_t ptcopen;
85 static d_close_t ptcclose;
86 static d_read_t ptcread;
87 static d_write_t ptcwrite;
88 static d_poll_t ptcpoll;
90 static struct cdevsw pts_cdevsw = {
91 .d_version = D_VERSION,
99 .d_flags = D_TTY | D_NEEDGIANT,
100 .d_kqfilter = ttykqfilter,
103 static struct cdevsw ptc_cdevsw = {
104 .d_version = D_VERSION,
112 .d_flags = D_TTY | D_NEEDGIANT,
113 .d_kqfilter = ttykqfilter,
116 #define BUFSIZ 100 /* Chunk size iomoved to/from user */
118 #define TSA_PTC_READ(tp) ((void *)&(tp)->t_outq.c_cf)
119 #define TSA_PTC_WRITE(tp) ((void *)&(tp)->t_rawq.c_cl)
120 #define TSA_PTS_READ(tp) ((void *)&(tp)->t_canq)
122 #define NUM_TO_MINOR(c) ((c & 0xff) | ((c & ~0xff) << 16))
124 * Once a tty is allocated, it cannot (currently) be freed. As such,
125 * we keep a global list of ptys that have been used so we can recycle
126 * them. An another list is provided for released pts, whiiich are
127 * not currently allocated, permitting reuse. pt_flags holds state
128 * associated with a particular session, so isn't overloaded for this.
129 * When a pty descriptor is unused, its number is set to -1 giving
130 * more consistent and traditional allocation orders to pty numbers.
132 * Locking: (p) indicates that the field is locked by the global pt_mtx.
133 * (c) indicates the value is constant after allocation. Other fields
134 * await tty locking generally, and are protected by Giant.
137 int pt_num; /* (c) pty number */
138 LIST_ENTRY(pt_desc) pt_list; /* (p) global pty list */
141 struct selinfo pt_selr, pt_selw;
145 struct cdev *pt_devs, *pt_devc;
146 int pt_pts_open, pt_ptc_open;
147 struct prison *pt_prison;
150 static struct mtx pt_mtx;
151 static LIST_HEAD(,pt_desc) pt_list;
152 static LIST_HEAD(,pt_desc) pt_free_list;
154 #define PF_PKT 0x008 /* packet mode */
155 #define PF_STOPPED 0x010 /* user told stopped */
156 #define PF_NOSTOP 0x040
157 #define PF_UCNTL 0x080 /* user control mode */
159 static unsigned int next_avail_nb;
161 static int use_pts = 0;
163 static unsigned int max_pts = 1000;
165 static unsigned int nb_allocated;
167 TUNABLE_INT("kern.pts.enable", &use_pts);
169 SYSCTL_NODE(_kern, OID_AUTO, pts, CTLFLAG_RD, 0, "pts");
171 SYSCTL_INT(_kern_pts, OID_AUTO, enable, CTLFLAG_RW, &use_pts, 0,
174 SYSCTL_INT(_kern_pts, OID_AUTO, max, CTLFLAG_RW, &max_pts, 0, "max pts");
177 * If there's a free pty descriptor in the pty descriptor list, retrieve it.
178 * Otherwise, allocate a new one, initialize it, and hook it up. If there's
179 * not a tty number, reject.
181 static struct pt_desc *
188 if (nb_allocated >= max_pts || nb_allocated == 0xffffff) {
192 pt = LIST_FIRST(&pt_free_list);
194 LIST_REMOVE(pt, pt_list);
195 LIST_INSERT_HEAD(&pt_list, pt, pt_list);
198 nb = next_avail_nb++;
200 pt = malloc(sizeof(*pt), M_PTY, M_WAITOK | M_ZERO);
203 LIST_INSERT_HEAD(&pt_list, pt, pt_list);
205 pt->pt_tty = ttyalloc();
212 * Release a pty descriptor back to the pool for reuse. The pty number
216 pty_release(struct pt_desc *pt)
219 KASSERT(pt->pt_ptc_open == 0 && pt->pt_pts_open == 0,
220 ("pty_release: pts/%d freed while open\n", pt->pt_num));
221 KASSERT(pt->pt_devs == NULL && pt->pt_devc == NULL,
222 ("pty_release: pts/%d freed whith non-null struct cdev\n", pt->pt_num));
223 mtx_assert(&pt_mtx, MA_OWNED);
225 LIST_REMOVE(pt, pt_list);
226 LIST_INSERT_HEAD(&pt_free_list, pt, pt_list);
230 * Given a pty descriptor, if both endpoints are closed, release all
231 * resources and destroy the device nodes to flush file system level
232 * state for the tty (owner, avoid races, etc).
235 pty_maybecleanup(struct pt_desc *pt)
238 if (pt->pt_ptc_open || pt->pt_pts_open)
242 printf("destroying pty %d\n", pt->pt_num);
244 destroy_dev(pt->pt_devs);
245 destroy_dev(pt->pt_devc);
246 pt->pt_devs = pt->pt_devc = NULL;
247 pt->pt_tty->t_dev = NULL;
256 ptsopen(struct cdev *dev, int flag, int devtype, struct thread *td)
264 if ((tp->t_state & TS_ISOPEN) == 0)
265 ttyinitmode(tp, 1, 0);
266 else if (tp->t_state & TS_XCLUDE && suser(td)) {
268 } else if (pt->pt_prison != td->td_ucred->cr_prison && suser(td)) {
271 if (tp->t_oproc) /* Ctrlr still around. */
273 while ((tp->t_state & TS_CARR_ON) == 0) {
276 error = ttysleep(tp, TSA_CARR_ON(tp), TTIPRI | PCATCH,
281 error = ttyld_open(tp, dev);
283 ptcwakeup(tp, FREAD|FWRITE);
290 ptsclose(struct cdev *dev, int flag, int mode, struct thread *td)
292 struct pt_desc *pt = dev->si_drv1;
297 err = ttyld_close(tp, flag);
298 ptsstop(tp, FREAD|FWRITE);
299 (void) tty_close(tp);
301 pty_maybecleanup(pt);
306 ptsread(struct cdev *dev, struct uio *uio, int flag)
308 struct tty *tp = dev->si_tty;
312 error = ttyld_read(tp, uio, flag);
313 ptcwakeup(tp, FWRITE);
318 * Write to pseudo-tty.
319 * Wakeups of controlling tty will happen
320 * indirectly, when tty driver calls ptsstart.
323 ptswrite(struct cdev *dev, struct uio *uio, int flag)
328 if (tp->t_oproc == 0)
330 return (ttyld_write(tp, uio, flag));
334 * Start output on pseudo-tty.
335 * Wake up process selecting or sleeping for input from controlling tty.
338 ptsstart(struct tty *tp)
340 struct pt_desc *pt = tp->t_dev->si_drv1;
342 if (tp->t_state & TS_TTSTOP)
344 if (pt->pt_flags & PF_STOPPED) {
345 pt->pt_flags &= ~PF_STOPPED;
346 pt->pt_send = TIOCPKT_START;
348 ptcwakeup(tp, FREAD);
352 ptcwakeup(struct tty *tp, int flag)
354 struct pt_desc *pt = tp->t_dev->si_drv1;
357 selwakeup(&pt->pt_selr);
358 wakeup(TSA_PTC_READ(tp));
361 selwakeup(&pt->pt_selw);
362 wakeup(TSA_PTC_WRITE(tp));
367 * ptcopen implementes exclusive access to the master/control device
368 * as well as creating the slave device based on the credential of the
369 * process opening the master. By creating the slave here, we avoid
370 * a race to access the master in terms of having a process with access
371 * to an incorrectly owned slave, but it does create the possibility
372 * that a racing process can cause a ptmx user to get EIO if it gets
373 * there first. Consumers of ptmx must look for EIO and retry if it
374 * happens. VFS locking may actually prevent this from occurring due
375 * to the lookup into devfs holding the vnode lock through open, but
376 * it's better to be careful.
379 ptcopen(struct cdev *dev, int flag, int devtype, struct thread *td)
381 struct pt_desc *pt = dev->si_drv1;
390 * XXX: Might want to make the ownership/permissions here more
396 pt->pt_devs = devs = make_dev_cred(&pts_cdevsw,
397 NUM_TO_MINOR(pt->pt_num),
398 td->td_ucred, UID_ROOT, GID_WHEEL, 0666, "pts/%d",
401 devs->si_tty = pt->pt_tty;
402 pt->pt_tty->t_dev = devs;
405 tp->t_oproc = ptsstart;
406 tp->t_stop = ptsstop;
408 tp->t_lflag &= ~EXTPROC;
410 pt->pt_prison = td->td_ucred->cr_prison;
419 ptcclose(struct cdev *dev, int flags, int fmt, struct thread *td)
421 struct pt_desc *pt = dev->si_drv1;
428 * XXX MDMBUF makes no sense for ptys but would inhibit the above
429 * l_modem(). CLOCAL makes sense but isn't supported. Special
430 * l_modem()s that ignore carrier drop make no sense for ptys but
431 * may be in use because other parts of the line discipline make
432 * sense for ptys. Recover by doing everything that a normal
433 * ttymodem() would have done except for sending a SIGHUP.
435 if (tp->t_state & TS_ISOPEN) {
436 tp->t_state &= ~(TS_CARR_ON | TS_CONNECTED);
437 tp->t_state |= TS_ZOMBIE;
438 ttyflush(tp, FREAD | FWRITE);
441 tp->t_oproc = 0; /* mark closed */
443 pty_maybecleanup(pt);
448 ptcread(struct cdev *dev, struct uio *uio, int flag)
450 struct tty *tp = dev->si_tty;
451 struct pt_desc *pt = dev->si_drv1;
456 * We want to block until the slave
457 * is open, and there's something to read;
458 * but if we lost the slave or we're NBIO,
459 * then return the appropriate error instead.
462 if (tp->t_state&TS_ISOPEN) {
463 if (pt->pt_flags&PF_PKT && pt->pt_send) {
464 error = ureadc((int)pt->pt_send, uio);
467 if (pt->pt_send & TIOCPKT_IOCTL) {
468 cc = min(uio->uio_resid,
469 sizeof(tp->t_termios));
470 uiomove(&tp->t_termios, cc, uio);
475 if (pt->pt_flags&PF_UCNTL && pt->pt_ucntl) {
476 error = ureadc((int)pt->pt_ucntl, uio);
482 if (tp->t_outq.c_cc && (tp->t_state&TS_TTSTOP) == 0)
485 if ((tp->t_state & TS_CONNECTED) == 0)
486 return (0); /* EOF */
487 if (flag & O_NONBLOCK)
488 return (EWOULDBLOCK);
489 error = tsleep(TSA_PTC_READ(tp), TTIPRI | PCATCH, "ptcin", 0);
493 if (pt->pt_flags & (PF_PKT|PF_UCNTL))
494 error = ureadc(0, uio);
495 while (uio->uio_resid > 0 && error == 0) {
496 cc = q_to_b(&tp->t_outq, buf, min(uio->uio_resid, BUFSIZ));
499 error = uiomove(buf, cc, uio);
506 ptsstop(struct tty *tp, int flush)
508 struct pt_desc *pt = tp->t_dev->si_drv1;
511 /* note: FLUSHREAD and FLUSHWRITE already ok */
513 flush = TIOCPKT_STOP;
514 pt->pt_flags |= PF_STOPPED;
516 pt->pt_flags &= ~PF_STOPPED;
517 pt->pt_send |= flush;
518 /* change of perspective */
528 ptcpoll(struct cdev *dev, int events, struct thread *td)
530 struct tty *tp = dev->si_tty;
531 struct pt_desc *pt = dev->si_drv1;
535 if ((tp->t_state & TS_CONNECTED) == 0)
537 (POLLHUP | POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM));
540 * Need to block timeouts (ttrstart).
544 if (events & (POLLIN | POLLRDNORM))
545 if ((tp->t_state & TS_ISOPEN) &&
546 ((tp->t_outq.c_cc && (tp->t_state & TS_TTSTOP) == 0) ||
547 ((pt->pt_flags & PF_PKT) && pt->pt_send) ||
548 ((pt->pt_flags & PF_UCNTL) && pt->pt_ucntl)))
549 revents |= events & (POLLIN | POLLRDNORM);
551 if (events & (POLLOUT | POLLWRNORM))
552 if (tp->t_state & TS_ISOPEN &&
553 (((tp->t_rawq.c_cc + tp->t_canq.c_cc < TTYHOG - 2) ||
554 (tp->t_canq.c_cc == 0 && (tp->t_lflag & ICANON)))))
555 revents |= events & (POLLOUT | POLLWRNORM);
557 if (events & POLLHUP)
558 if ((tp->t_state & TS_CARR_ON) == 0)
562 if (events & (POLLIN | POLLRDNORM))
563 selrecord(td, &pt->pt_selr);
565 if (events & (POLLOUT | POLLWRNORM))
566 selrecord(td, &pt->pt_selw);
574 ptcwrite(struct cdev *dev, struct uio *uio, int flag)
576 struct tty *tp = dev->si_tty;
579 u_char locbuf[BUFSIZ];
584 if ((tp->t_state&TS_ISOPEN) == 0)
586 while (uio->uio_resid > 0 || cc > 0) {
588 cc = min(uio->uio_resid, BUFSIZ);
590 error = uiomove(cp, cc, uio);
593 /* check again for safety */
594 if ((tp->t_state & TS_ISOPEN) == 0) {
595 /* adjust for data copied in but not written */
596 uio->uio_resid += cc;
601 if ((tp->t_rawq.c_cc + tp->t_canq.c_cc) >= TTYHOG - 2 &&
602 (tp->t_canq.c_cc > 0 || !(tp->t_lflag&ICANON))) {
603 wakeup(TSA_HUP_OR_INPUT(tp));
606 ttyld_rint(tp, *cp++);
615 * Come here to wait for slave to open, for space
616 * in outq, or space in rawq, or an empty canq.
618 if ((tp->t_state & TS_CONNECTED) == 0) {
619 /* adjust for data copied in but not written */
620 uio->uio_resid += cc;
623 if (flag & IO_NDELAY) {
624 /* adjust for data copied in but not written */
625 uio->uio_resid += cc;
627 return (EWOULDBLOCK);
630 error = tsleep(TSA_PTC_WRITE(tp), TTOPRI | PCATCH, "ptcout", 0);
632 /* adjust for data copied in but not written */
633 uio->uio_resid += cc;
640 ptcioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
642 struct tty *tp = dev->si_tty;
643 struct pt_desc *pt = dev->si_drv1;
649 * We avoid calling ttioctl on the controller since,
650 * in that case, tp must be the controlling terminal.
652 *(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : 0;
657 if (pt->pt_flags & PF_UCNTL)
659 pt->pt_flags |= PF_PKT;
661 pt->pt_flags &= ~PF_PKT;
666 if (pt->pt_flags & PF_PKT)
668 pt->pt_flags |= PF_UCNTL;
670 pt->pt_flags &= ~PF_UCNTL;
673 *(unsigned int *)data = pt->pt_num;
678 * The rest of the ioctls shouldn't be called until
681 if ((tp->t_state & TS_ISOPEN) == 0) {
682 if (cmd == TIOCGETA) {
684 * TIOCGETA is used by isatty() to make sure it's
685 * a tty. Linux openpty() calls isatty() very early,
686 * before the slave is opened, so don't actually
687 * fill the struct termios, but just let isatty()
692 if (cmd != FIONBIO && cmd != FIOASYNC)
706 * IF CONTROLLER STTY THEN MUST FLUSH TO PREVENT A HANG.
707 * ttywflush(tp) will hang if there are characters in
710 ndflush(&tp->t_outq, tp->t_outq.c_cc);
714 if (*(unsigned int *)data >= NSIG ||
715 *(unsigned int *)data == 0)
717 if ((tp->t_lflag&NOFLSH) == 0)
718 ttyflush(tp, FREAD|FWRITE);
719 if (tp->t_pgrp != NULL) {
720 PGRP_LOCK(tp->t_pgrp);
721 pgsignal(tp->t_pgrp, *(unsigned int *)data, 1);
722 PGRP_UNLOCK(tp->t_pgrp);
724 if ((*(unsigned int *)data == SIGINFO) &&
725 ((tp->t_lflag&NOKERNINFO) == 0))
729 return (ptsioctl(dev, cmd, data, flag, td));
733 ptsioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
735 struct tty *tp = dev->si_tty;
736 struct pt_desc *pt = dev->si_drv1;
737 u_char *cc = tp->t_cc;
740 if (cmd == TIOCEXT) {
742 * When the EXTPROC bit is being toggled, we need
743 * to send an TIOCPKT_IOCTL if the packet driver
747 if (pt->pt_flags & PF_PKT) {
748 pt->pt_send |= TIOCPKT_IOCTL;
749 ptcwakeup(tp, FREAD);
751 tp->t_lflag |= EXTPROC;
753 if ((tp->t_lflag & EXTPROC) &&
754 (pt->pt_flags & PF_PKT)) {
755 pt->pt_send |= TIOCPKT_IOCTL;
756 ptcwakeup(tp, FREAD);
758 tp->t_lflag &= ~EXTPROC;
762 error = ttioctl(tp, cmd, data, flag);
763 if (error == ENOTTY) {
764 if (pt->pt_flags & PF_UCNTL &&
765 (cmd & ~0xff) == UIOCCMD(0)) {
767 pt->pt_ucntl = (u_char)cmd;
768 ptcwakeup(tp, FREAD);
775 * If external processing and packet mode send ioctl packet.
777 if ((tp->t_lflag&EXTPROC) && (pt->pt_flags & PF_PKT)) {
791 pt->pt_send |= TIOCPKT_IOCTL;
792 ptcwakeup(tp, FREAD);
798 stop = (tp->t_iflag & IXON) && CCEQ(cc[VSTOP], CTRL('s'))
799 && CCEQ(cc[VSTART], CTRL('q'));
800 if (pt->pt_flags & PF_NOSTOP) {
802 pt->pt_send &= ~TIOCPKT_NOSTOP;
803 pt->pt_send |= TIOCPKT_DOSTOP;
804 pt->pt_flags &= ~PF_NOSTOP;
805 ptcwakeup(tp, FREAD);
809 pt->pt_send &= ~TIOCPKT_DOSTOP;
810 pt->pt_send |= TIOCPKT_NOSTOP;
811 pt->pt_flags |= PF_NOSTOP;
812 ptcwakeup(tp, FREAD);
819 * Match lookups on /dev/ptmx, find the next free pty (if any), set up
820 * the pty descriptor, register it, and return a reference to the master.
822 * pts == /dev/pts/xxx (oldstyle: ttyp...)
823 * ptc == /dev/pty/xxx (oldstyle: ptyp...)
826 pty_clone(void *arg, struct ucred *cred, char *name, int namelen,
838 if (strcmp(name, "ptmx") != 0)
846 * XXX: Lack of locking here considered worrying. We expose the
847 * pts/pty device nodes before they are fully initialized, although
848 * Giant likely protects us (unless make_dev blocks...?).
850 * XXX: If a process performs a lookup on /dev/ptmx but never an
851 * open, we won't GC the device node. We should have a callout
852 * sometime later that GC's device instances that were never
853 * opened, or some way to tell devfs that "this had better be for
854 * an open() or we won't create a device".
856 pt->pt_devc = devc = make_dev_cred(&ptc_cdevsw,
857 NUM_TO_MINOR(pt->pt_num), cred, UID_ROOT, GID_WHEEL, 0666,
858 "pty/%d", pt->pt_num);
862 devc->si_tty = pt->pt_tty;
866 printf("pty_clone: allocated pty %d to uid %d\n", pt->pt_num,
873 pty_drvinit(void *unused)
876 mtx_init(&pt_mtx, "pt_mtx", NULL, MTX_DEF);
878 LIST_INIT(&pt_free_list);
879 EVENTHANDLER_REGISTER(dev_clone, pty_clone, 0, 1000);
882 SYSINIT(ptydev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE,pty_drvinit,NULL)