76e598cf090d836ec367a3db25afe9a1c83ed35c
[dragonfly.git] / sys / kern / tty_pty.c
1 /*
2  * (MPSAFE)
3  *
4  * Copyright (c) 1982, 1986, 1989, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *      This product includes software developed by the University of
18  *      California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  *      @(#)tty_pty.c   8.4 (Berkeley) 2/20/95
36  * $FreeBSD: src/sys/kern/tty_pty.c,v 1.74.2.4 2002/02/20 19:58:13 dillon Exp $
37  * $DragonFly: src/sys/kern/tty_pty.c,v 1.21 2008/08/13 10:29:38 swildner Exp $
38  */
39
40 /*
41  * MPSAFE NOTE: 
42  * Most functions here could use a separate lock to deal with concurrent
43  * access to the 'pt's.
44  *
45  * Right now the tty_token must be held for all this.
46  */
47
48 /*
49  * Pseudo-teletype Driver
50  * (Actually two drivers, requiring two dev_ops structures)
51  */
52 #include "use_pty.h"            /* XXX */
53 #include "opt_compat.h"
54
55 #include <sys/param.h>
56 #include <sys/systm.h>
57 #if defined(COMPAT_43) || defined(COMPAT_SUNOS)
58 #include <sys/ioctl_compat.h>
59 #endif
60 #include <sys/proc.h>
61 #include <sys/priv.h>
62 #include <sys/tty.h>
63 #include <sys/conf.h>
64 #include <sys/fcntl.h>
65 #include <sys/kernel.h>
66 #include <sys/vnode.h>
67 #include <sys/signalvar.h>
68 #include <sys/malloc.h>
69 #include <sys/device.h>
70 #include <sys/thread2.h>
71 #include <sys/devfs.h>
72 #include <sys/stat.h>
73 #include <sys/sysctl.h>
74
75 #define UNIX98_PTYS     1
76
77 MALLOC_DEFINE(M_PTY, "ptys", "pty data structures");
78
79 static void ptsstart (struct tty *tp);
80 static void ptsstop (struct tty *tp, int rw);
81 static void ptcwakeup (struct tty *tp, int flag);
82 static void ptyinit (int n);
83 static int  filt_ptcread (struct knote *kn, long hint);
84 static void filt_ptcrdetach (struct knote *kn);
85 static int  filt_ptcwrite (struct knote *kn, long hint);
86 static void filt_ptcwdetach (struct knote *kn);
87
88 static  d_open_t        ptsopen;
89 static  d_close_t       ptsclose;
90 static  d_read_t        ptsread;
91 static  d_write_t       ptswrite;
92 static  d_ioctl_t       ptyioctl;
93 static  d_open_t        ptcopen;
94 static  d_close_t       ptcclose;
95 static  d_read_t        ptcread;
96 static  d_write_t       ptcwrite;
97 static  d_kqfilter_t    ptckqfilter;
98
99 #ifdef UNIX98_PTYS
100 DEVFS_DECLARE_CLONE_BITMAP(pty);
101
102 static  d_clone_t       ptyclone;
103
104 static int      pty_debug_level = 0;
105
106 static struct dev_ops pts98_ops = {
107         { "pts98", 0, D_TTY },
108         .d_open =       ptsopen,
109         .d_close =      ptsclose,
110         .d_read =       ptsread,
111         .d_write =      ptswrite,
112         .d_ioctl =      ptyioctl,
113         .d_kqfilter =   ttykqfilter,
114         .d_revoke =     ttyrevoke
115 };
116
117 static struct dev_ops ptc98_ops = {
118         { "ptc98", 0, D_TTY | D_MASTER },
119         .d_open =       ptcopen,
120         .d_close =      ptcclose,
121         .d_read =       ptcread,
122         .d_write =      ptcwrite,
123         .d_ioctl =      ptyioctl,
124         .d_kqfilter =   ptckqfilter,
125         .d_revoke =     ttyrevoke
126 };
127 #endif
128
129 #define CDEV_MAJOR_S    5
130 static struct dev_ops pts_ops = {
131         { "pts", CDEV_MAJOR_S, D_TTY },
132         .d_open =       ptsopen,
133         .d_close =      ptsclose,
134         .d_read =       ptsread,
135         .d_write =      ptswrite,
136         .d_ioctl =      ptyioctl,
137         .d_kqfilter =   ttykqfilter,
138         .d_revoke =     ttyrevoke
139 };
140
141 #define CDEV_MAJOR_C    6
142 static struct dev_ops ptc_ops = {
143         { "ptc", CDEV_MAJOR_C, D_TTY | D_MASTER },
144         .d_open =       ptcopen,
145         .d_close =      ptcclose,
146         .d_read =       ptcread,
147         .d_write =      ptcwrite,
148         .d_ioctl =      ptyioctl,
149         .d_kqfilter =   ptckqfilter,
150         .d_revoke =     ttyrevoke
151 };
152
153 #define BUFSIZ 100              /* Chunk size iomoved to/from user */
154
155 struct  pt_ioctl {
156         int     pt_flags;
157         int     pt_flags2;
158         int     pt_refs;        /* Structural references interlock S/MOPEN */
159         int     pt_uminor;
160         struct  kqinfo pt_kqr, pt_kqw;
161         u_char  pt_send;
162         u_char  pt_ucntl;
163         struct tty pt_tty;
164         cdev_t  devs, devc;
165         struct  prison *pt_prison;
166 };
167
168 #define PF_PKT          0x08            /* packet mode */
169 #define PF_STOPPED      0x10            /* user told stopped */
170 #define PF_REMOTE       0x20            /* remote and flow controlled input */
171 #define PF_NOSTOP       0x40
172 #define PF_UCNTL        0x80            /* user control mode */
173
174 #define PF_UNIX98       0x01
175 #define PF_SOPEN        0x02
176 #define PF_MOPEN        0x04
177 #define PF_TERMINATED   0x08
178
179 /*
180  * This function creates and initializes a pts/ptc pair
181  *
182  * pts == /dev/tty[pqrsPQRS][0123456789abcdefghijklmnopqrstuv]
183  * ptc == /dev/pty[pqrsPQRS][0123456789abcdefghijklmnopqrstuv]
184  *
185  * XXX: define and add mapping of upper minor bits to allow more 
186  *      than 256 ptys.
187  */
188 static void
189 ptyinit(int n)
190 {
191         cdev_t devs, devc;
192         char *names = "pqrsPQRS";
193         struct pt_ioctl *pt;
194
195         /* For now we only map the lower 8 bits of the minor */
196         if (n & ~0xff)
197                 return;
198
199         pt = kmalloc(sizeof(*pt), M_PTY, M_WAITOK | M_ZERO);
200         pt->devs = devs = make_dev(&pts_ops, n,
201             0, 0, 0666, "tty%c%r", names[n / 32], n % 32);
202         pt->devc = devc = make_dev(&ptc_ops, n,
203             0, 0, 0666, "pty%c%r", names[n / 32], n % 32);
204
205         pt->pt_tty.t_dev = devs;
206         pt->pt_uminor = n;
207         devs->si_drv1 = devc->si_drv1 = pt;
208         devs->si_tty = devc->si_tty = &pt->pt_tty;
209         devs->si_flags |= SI_OVERRIDE;  /* uid, gid, perms from dev */
210         devc->si_flags |= SI_OVERRIDE;  /* uid, gid, perms from dev */
211         ttyregister(&pt->pt_tty);
212 }
213
214 #ifdef UNIX98_PTYS
215 static int
216 ptyclone(struct dev_clone_args *ap)
217 {
218         int unit;
219         struct pt_ioctl *pt;
220
221         /*
222          * Limit the number of unix98 pty (slave) devices to 1000, as
223          * the utmp(5) format only allows for 8 bytes for the tty,
224          * "pts/XXX".
225          * If this limit is reached, we don't clone and return error
226          * to devfs.
227          */
228         unit = devfs_clone_bitmap_get(&DEVFS_CLONE_BITMAP(pty), 1000);
229
230         if (unit < 0) {
231                 ap->a_dev = NULL;
232                 return 1;
233         }
234
235         pt = kmalloc(sizeof(*pt), M_PTY, M_WAITOK | M_ZERO);
236
237         pt->devc = make_only_dev(&ptc98_ops, unit,
238                                  ap->a_cred->cr_ruid,
239                                  0, 0600, "ptm/%d", unit);
240         pt->devs = make_dev(&pts98_ops, unit,
241                             ap->a_cred->cr_ruid,
242                             GID_TTY, 0620, "pts/%d", unit);
243         ap->a_dev = pt->devc;
244
245         pt->devs->si_flags |= SI_OVERRIDE;      /* uid, gid, perms from dev */
246         pt->devc->si_flags |= SI_OVERRIDE;      /* uid, gid, perms from dev */
247
248         pt->pt_tty.t_dev = pt->devs;
249         pt->pt_flags2 |= PF_UNIX98;
250         pt->pt_uminor = unit;
251         pt->devs->si_drv1 = pt->devc->si_drv1 = pt;
252         pt->devs->si_tty = pt->devc->si_tty = &pt->pt_tty;
253
254         ttyregister(&pt->pt_tty);
255
256         return 0;
257 }
258 #endif
259
260 /*
261  * pti_hold() prevents the pti from being destroyed due to a termination
262  * while a pt*open() is blocked.
263  *
264  * This function returns non-zero if we cannot hold due to a termination
265  * interlock.
266  *
267  * NOTE: Must be called with tty_token held
268  */
269 static int
270 pti_hold(struct pt_ioctl *pti)
271 {
272         if (pti->pt_flags2 & PF_TERMINATED)
273                 return(ENXIO);
274         ++pti->pt_refs;
275         return(0);
276 }
277
278 /*
279  * pti_done() releases the reference and checks to see if both sides have
280  * been closed on a unix98 pty, allowing us to destroy the device and
281  * release resources.
282  *
283  * We do not release resources on non-unix98 ptys.  Those are left
284  * statically allocated.
285  */
286 static void
287 pti_done(struct pt_ioctl *pti)
288 {
289         lwkt_gettoken(&tty_token);
290         if (--pti->pt_refs == 0) {
291 #ifdef UNIX98_PTYS
292                 cdev_t dev;
293                 int uminor_no;
294
295                 /*
296                  * Only unix09 ptys are freed up
297                  */
298                 if ((pti->pt_flags2 & PF_UNIX98) == 0) {
299                         lwkt_reltoken(&tty_token);
300                         return;
301                 }
302
303                 /*
304                  * Interlock open attempts against termination by setting
305                  * PF_TERMINATED.  This allows us to block while cleaning
306                  * out the device infrastructure.
307                  *
308                  * Do not terminate the tty if it still has a session
309                  * association (t_refs).
310                  */
311                 if ((pti->pt_flags2 & (PF_SOPEN|PF_MOPEN)) == 0 &&
312                     pti->pt_tty.t_refs == 0) {
313                         pti->pt_flags2 |= PF_TERMINATED;
314                         uminor_no = pti->pt_uminor;
315
316                         if ((dev = pti->devs) != NULL) {
317                                 dev->si_drv1 = NULL;
318                                 pti->devs = NULL;
319                                 destroy_dev(dev);
320                         }
321                         if ((dev = pti->devc) != NULL) {
322                                 dev->si_drv1 = NULL;
323                                 pti->devc = NULL;
324                                 destroy_dev(dev);
325                         }
326                         ttyunregister(&pti->pt_tty);
327                         devfs_clone_bitmap_put(&DEVFS_CLONE_BITMAP(pty),
328                                                uminor_no);
329                         kfree(pti, M_PTY);
330                 }
331 #endif
332         }
333         lwkt_reltoken(&tty_token);
334 }
335
336 /*ARGSUSED*/
337 static  int
338 ptsopen(struct dev_open_args *ap)
339 {
340         cdev_t dev = ap->a_head.a_dev;
341         struct tty *tp;
342         int error;
343         struct pt_ioctl *pti;
344
345         /*
346          * The pti will already be assigned by the clone code or
347          * pre-created if a non-unix 98 pty.  If si_drv1 is NULL
348          * we are somehow racing a unix98 termination.
349          */
350         if (dev->si_drv1 == NULL)
351                 return(ENXIO);
352         pti = dev->si_drv1;
353
354         lwkt_gettoken(&tty_token);
355         if (pti_hold(pti)) {
356                 lwkt_reltoken(&tty_token);
357                 return(ENXIO);
358         }
359
360         tp = dev->si_tty;
361
362         /*
363          * Reinit most of the tty state if it isn't open.  Handle
364          * exclusive access.
365          */
366         if ((tp->t_state & TS_ISOPEN) == 0) {
367                 ttychars(tp);           /* Set up default chars */
368                 tp->t_iflag = TTYDEF_IFLAG;
369                 tp->t_oflag = TTYDEF_OFLAG;
370                 tp->t_lflag = TTYDEF_LFLAG;
371                 tp->t_cflag = TTYDEF_CFLAG;
372                 tp->t_ispeed = tp->t_ospeed = TTYDEF_SPEED;
373         } else if ((tp->t_state & TS_XCLUDE) &&
374                    priv_check_cred(ap->a_cred, PRIV_ROOT, 0)) {
375                 pti_done(pti);
376                 lwkt_reltoken(&tty_token);
377                 return (EBUSY);
378         } else if (pti->pt_prison != ap->a_cred->cr_prison) {
379                 pti_done(pti);
380                 lwkt_reltoken(&tty_token);
381                 return (EBUSY);
382         }
383
384         /*
385          * If the ptc is already present this will connect us up.  It
386          * is unclear if this is actually needed.
387          *
388          * If neither side is open be sure to clear any left over
389          * ZOMBIE state before continuing.
390          */
391         if (tp->t_oproc)
392                 (void)(*linesw[tp->t_line].l_modem)(tp, 1);
393         else if ((pti->pt_flags2 & PF_SOPEN) == 0)
394                 tp->t_state &= ~TS_ZOMBIE;
395
396         /*
397          * Wait for the carrier (ptc side)
398          */
399         while ((tp->t_state & TS_CARR_ON) == 0) {
400                 if (ap->a_oflags & FNONBLOCK)
401                         break;
402                 error = ttysleep(tp, TSA_CARR_ON(tp), PCATCH, "ptsopn", 0);
403                 if (error) {
404                         pti_done(pti);
405                         lwkt_reltoken(&tty_token);
406                         return (error);
407                 }
408         }
409
410         /*
411          * Mark the tty open and mark the slave side as being open.
412          */
413         error = (*linesw[tp->t_line].l_open)(dev, tp);
414
415         if (error == 0) {
416                 pti->pt_flags2 |= PF_SOPEN;
417                 ptcwakeup(tp, FREAD|FWRITE);
418         }
419         pti_done(pti);
420
421         lwkt_reltoken(&tty_token);
422         return (error);
423 }
424
425 static  int
426 ptsclose(struct dev_close_args *ap)
427 {
428         cdev_t dev = ap->a_head.a_dev;
429         struct tty *tp;
430         struct pt_ioctl *pti = dev->si_drv1;
431         int err;
432
433         lwkt_gettoken(&tty_token);
434         if (pti_hold(pti))
435                 panic("ptsclose on terminated pti");
436
437         /*
438          * Disconnect the slave side
439          */
440         tp = dev->si_tty;
441         err = (*linesw[tp->t_line].l_close)(tp, ap->a_fflag);
442         ptsstop(tp, FREAD|FWRITE);
443         ttyclose(tp);                   /* clears t_state */
444
445         /*
446          * Mark the pty side closed.
447          *
448          * If the ptc is still open mark the tty zombie and wakeup the
449          * ptc.
450          */
451         pti->pt_flags2 &= ~PF_SOPEN;
452         if (tp->t_oproc) {
453                 tp->t_state |= TS_ZOMBIE;
454                 ptcwakeup(tp, FREAD);
455         }
456         pti_done(pti);
457         lwkt_reltoken(&tty_token);
458         return (err);
459 }
460
461 static  int
462 ptsread(struct dev_read_args *ap)
463 {
464         cdev_t dev = ap->a_head.a_dev;
465         struct proc *p = curproc;
466         struct tty *tp = dev->si_tty;
467         struct pt_ioctl *pti = dev->si_drv1;
468         struct lwp *lp;
469
470         int error = 0;
471
472         lp = curthread->td_lwp;
473
474         lwkt_gettoken(&tty_token);
475 again:
476         if (pti->pt_flags & PF_REMOTE) {
477                 while (isbackground(p, tp)) {
478                         if (SIGISMEMBER(p->p_sigignore, SIGTTIN) ||
479                             SIGISMEMBER(lp->lwp_sigmask, SIGTTIN) ||
480                             p->p_pgrp->pg_jobc == 0 || p->p_flag & P_PPWAIT) {
481                                 lwkt_reltoken(&tty_token);
482                                 return (EIO);
483                         }
484                         pgsignal(p->p_pgrp, SIGTTIN, 1);
485                         error = ttysleep(tp, &lbolt, PCATCH, "ptsbg", 0);
486                         if (error) {
487                                 lwkt_reltoken(&tty_token);
488                                 return (error);
489                         }
490                 }
491                 if (tp->t_canq.c_cc == 0) {
492                         if (ap->a_ioflag & IO_NDELAY) {
493                                 lwkt_reltoken(&tty_token);
494                                 return (EWOULDBLOCK);
495                         }
496                         error = ttysleep(tp, TSA_PTS_READ(tp), PCATCH,
497                                          "ptsin", 0);
498                         if (error) {
499                                 lwkt_reltoken(&tty_token);
500                                 return (error);
501                         }
502                         goto again;
503                 }
504                 while (tp->t_canq.c_cc > 1 && ap->a_uio->uio_resid > 0)
505                         if (ureadc(clist_getc(&tp->t_canq), ap->a_uio) < 0) {
506                                 error = EFAULT;
507                                 break;
508                         }
509                 if (tp->t_canq.c_cc == 1)
510                         clist_getc(&tp->t_canq);
511                 if (tp->t_canq.c_cc) {
512                         lwkt_reltoken(&tty_token);
513                         return (error);
514                 }
515         } else
516                 if (tp->t_oproc)
517                         error = (*linesw[tp->t_line].l_read)(tp, ap->a_uio, ap->a_ioflag);
518         ptcwakeup(tp, FWRITE);
519         lwkt_reltoken(&tty_token);
520         return (error);
521 }
522
523 /*
524  * Write to pseudo-tty.
525  * Wakeups of controlling tty will happen
526  * indirectly, when tty driver calls ptsstart.
527  */
528 static  int
529 ptswrite(struct dev_write_args *ap)
530 {
531         cdev_t dev = ap->a_head.a_dev;
532         struct tty *tp;
533         int ret;
534
535         lwkt_gettoken(&tty_token);
536         tp = dev->si_tty;
537         if (tp->t_oproc == 0) {
538                 lwkt_reltoken(&tty_token);
539                 return (EIO);
540         }
541         ret = ((*linesw[tp->t_line].l_write)(tp, ap->a_uio, ap->a_ioflag));
542         lwkt_reltoken(&tty_token);
543         return ret;
544 }
545
546 /*
547  * Start output on pseudo-tty.
548  * Wake up process selecting or sleeping for input from controlling tty.
549  */
550 static void
551 ptsstart(struct tty *tp)
552 {
553         lwkt_gettoken(&tty_token);
554         struct pt_ioctl *pti = tp->t_dev->si_drv1;
555
556         if (tp->t_state & TS_TTSTOP) {
557                 lwkt_reltoken(&tty_token);
558                 return;
559         }
560         if (pti) {
561                 if (pti->pt_flags & PF_STOPPED) {
562                         pti->pt_flags &= ~PF_STOPPED;
563                         pti->pt_send = TIOCPKT_START;
564                 }
565         }
566         ptcwakeup(tp, FREAD);
567         lwkt_reltoken(&tty_token);
568 }
569
570 /*
571  * NOTE: Must be called with tty_token held
572  */
573 static void
574 ptcwakeup(struct tty *tp, int flag)
575 {
576         ASSERT_LWKT_TOKEN_HELD(&tty_token);
577
578         if (flag & FREAD) {
579                 wakeup(TSA_PTC_READ(tp));
580                 KNOTE(&tp->t_rkq.ki_note, 0);
581         }
582         if (flag & FWRITE) {
583                 wakeup(TSA_PTC_WRITE(tp));
584                 KNOTE(&tp->t_wkq.ki_note, 0);
585         }
586 }
587
588 static  int
589 ptcopen(struct dev_open_args *ap)
590 {
591         cdev_t dev = ap->a_head.a_dev;
592         struct tty *tp;
593         struct pt_ioctl *pti;
594
595         /*
596          * The pti will already be assigned by the clone code or
597          * pre-created if a non-unix 98 pty.  If si_drv1 is NULL
598          * we are somehow racing a unix98 termination.
599          */
600         if (dev->si_drv1 == NULL)
601                 return(ENXIO);
602
603         lwkt_gettoken(&tty_token);
604         pti = dev->si_drv1;
605         if (pti_hold(pti)) {
606                 lwkt_reltoken(&tty_token);
607                 return(ENXIO);
608         }
609         if (pti->pt_prison && pti->pt_prison != ap->a_cred->cr_prison) {
610                 pti_done(pti);
611                 lwkt_reltoken(&tty_token);
612                 return(EBUSY);
613         }
614         tp = dev->si_tty;
615         if (tp->t_oproc) {
616                 pti_done(pti);
617                 lwkt_reltoken(&tty_token);
618                 return (EIO);
619         }
620
621         /*
622          * If the slave side is not yet open clear any left over zombie
623          * state before doing our modem control.
624          */
625         if ((pti->pt_flags2 & PF_SOPEN) == 0)
626                 tp->t_state &= ~TS_ZOMBIE;
627
628         tp->t_oproc = ptsstart;
629         tp->t_stop = ptsstop;
630
631         /*
632          * Carrier on!
633          */
634         (void)(*linesw[tp->t_line].l_modem)(tp, 1);
635
636         tp->t_lflag &= ~EXTPROC;
637         pti->pt_prison = ap->a_cred->cr_prison;
638         pti->pt_flags = 0;
639         pti->pt_send = 0;
640         pti->pt_ucntl = 0;
641
642         pti->devs->si_uid = ap->a_cred->cr_uid;
643         pti->devs->si_gid = 0;
644         pti->devs->si_perms = 0600;
645         pti->devc->si_uid = ap->a_cred->cr_uid;
646         pti->devc->si_gid = 0;
647         pti->devc->si_perms = 0600;
648
649         /*
650          * Mark master side open.  This does not cause any events
651          * on the slave side.
652          */
653         pti->pt_flags2 |= PF_MOPEN;
654         pti_done(pti);
655
656         lwkt_reltoken(&tty_token);
657         return (0);
658 }
659
660 static  int
661 ptcclose(struct dev_close_args *ap)
662 {
663         cdev_t dev = ap->a_head.a_dev;
664         struct tty *tp;
665         struct pt_ioctl *pti = dev->si_drv1;
666
667         lwkt_gettoken(&tty_token);
668         if (pti_hold(pti))
669                 panic("ptcclose on terminated pti");
670
671         tp = dev->si_tty;
672         (void)(*linesw[tp->t_line].l_modem)(tp, 0);
673
674         /*
675          * Mark the master side closed.  If the slave is still open
676          * mark the tty ZOMBIE, preventing any new action until both
677          * sides have closed.
678          *
679          * NOTE: The ttyflush() will wake up the slave once we've
680          *       set appropriate flags.  The ZOMBIE flag will be
681          *       cleared when the slave side is closed.
682          */
683         pti->pt_flags2 &= ~PF_MOPEN;
684         if (pti->pt_flags2 & PF_SOPEN) {
685                 tp->t_state |= TS_ZOMBIE;
686         }
687
688         /*
689          * Turn off the carrier and disconnect.  This will notify the slave
690          * side.
691          */
692         if (tp->t_state & TS_ISOPEN) {
693                 tp->t_state &= ~(TS_CARR_ON | TS_CONNECTED);
694                 ttyflush(tp, FREAD | FWRITE);
695         }
696         tp->t_oproc = NULL;             /* mark closed */
697
698         pti->pt_prison = NULL;
699         pti->devs->si_uid = 0;
700         pti->devs->si_gid = 0;
701         pti->devs->si_perms = 0666;
702         pti->devc->si_uid = 0;
703         pti->devc->si_gid = 0;
704         pti->devc->si_perms = 0666;
705
706         pti_done(pti);
707
708         lwkt_reltoken(&tty_token);
709         return (0);
710 }
711
712 static  int
713 ptcread(struct dev_read_args *ap)
714 {
715         cdev_t dev = ap->a_head.a_dev;
716         struct tty *tp = dev->si_tty;
717         struct pt_ioctl *pti = dev->si_drv1;
718         char buf[BUFSIZ];
719         int error = 0, cc;
720
721         lwkt_gettoken(&tty_token);
722         /*
723          * We want to block until the slave
724          * is open, and there's something to read;
725          * but if we lost the slave or we're NBIO,
726          * then return the appropriate error instead.
727          */
728         for (;;) {
729                 if (tp->t_state&TS_ISOPEN) {
730                         if (pti->pt_flags&PF_PKT && pti->pt_send) {
731                                 error = ureadc((int)pti->pt_send, ap->a_uio);
732                                 if (error) {
733                                         lwkt_reltoken(&tty_token);
734                                         return (error);
735                                 }
736                                 if (pti->pt_send & TIOCPKT_IOCTL) {
737                                         cc = (int)szmin(ap->a_uio->uio_resid,
738                                                         sizeof(tp->t_termios));
739                                         uiomove((caddr_t)&tp->t_termios, cc,
740                                                 ap->a_uio);
741                                 }
742                                 pti->pt_send = 0;
743                                 lwkt_reltoken(&tty_token);
744                                 return (0);
745                         }
746                         if (pti->pt_flags&PF_UCNTL && pti->pt_ucntl) {
747                                 error = ureadc((int)pti->pt_ucntl, ap->a_uio);
748                                 if (error) {
749                                         lwkt_reltoken(&tty_token);
750                                         return (error);
751                                 }
752                                 pti->pt_ucntl = 0;
753                                 lwkt_reltoken(&tty_token);
754                                 return (0);
755                         }
756                         if (tp->t_outq.c_cc && (tp->t_state&TS_TTSTOP) == 0)
757                                 break;
758                 }
759                 if ((tp->t_state & TS_CONNECTED) == 0) {
760                         lwkt_reltoken(&tty_token);
761                         return (0);     /* EOF */
762                 }
763                 if (ap->a_ioflag & IO_NDELAY) {
764                         lwkt_reltoken(&tty_token);
765                         return (EWOULDBLOCK);
766                 }
767                 error = tsleep(TSA_PTC_READ(tp), PCATCH, "ptcin", 0);
768                 if (error) {
769                         lwkt_reltoken(&tty_token);
770                         return (error);
771                 }
772         }
773         if (pti->pt_flags & (PF_PKT|PF_UCNTL))
774                 error = ureadc(0, ap->a_uio);
775         while (ap->a_uio->uio_resid > 0 && error == 0) {
776                 cc = q_to_b(&tp->t_outq, buf,
777                             (int)szmin(ap->a_uio->uio_resid, BUFSIZ));
778                 if (cc <= 0)
779                         break;
780                 error = uiomove(buf, (size_t)cc, ap->a_uio);
781         }
782         ttwwakeup(tp);
783         lwkt_reltoken(&tty_token);
784         return (error);
785 }
786
787 static  void
788 ptsstop(struct tty *tp, int flush)
789 {
790         struct pt_ioctl *pti = tp->t_dev->si_drv1;
791         int flag;
792
793         lwkt_gettoken(&tty_token);
794         /* note: FLUSHREAD and FLUSHWRITE already ok */
795         if (pti) {
796                 if (flush == 0) {
797                         flush = TIOCPKT_STOP;
798                         pti->pt_flags |= PF_STOPPED;
799                 } else {
800                         pti->pt_flags &= ~PF_STOPPED;
801                 }
802                 pti->pt_send |= flush;
803                 /* change of perspective */
804         }
805         flag = 0;
806         if (flush & FREAD)
807                 flag |= FWRITE;
808         if (flush & FWRITE)
809                 flag |= FREAD;
810         ptcwakeup(tp, flag);
811
812         lwkt_reltoken(&tty_token);
813 }
814
815 /*
816  * kqueue ops for pseudo-terminals.
817  */
818 static struct filterops ptcread_filtops =
819         { FILTEROP_ISFD, NULL, filt_ptcrdetach, filt_ptcread };
820 static struct filterops ptcwrite_filtops =
821         { FILTEROP_ISFD, NULL, filt_ptcwdetach, filt_ptcwrite };
822
823 static  int
824 ptckqfilter(struct dev_kqfilter_args *ap)
825 {
826         cdev_t dev = ap->a_head.a_dev;
827         struct knote *kn = ap->a_kn;
828         struct tty *tp = dev->si_tty;
829         struct klist *klist;
830
831         lwkt_gettoken(&tty_token);
832         ap->a_result = 0;
833         switch (kn->kn_filter) {
834         case EVFILT_READ:
835                 klist = &tp->t_rkq.ki_note;
836                 kn->kn_fop = &ptcread_filtops;
837                 break;
838         case EVFILT_WRITE:
839                 klist = &tp->t_wkq.ki_note;
840                 kn->kn_fop = &ptcwrite_filtops;
841                 break;
842         default:
843                 ap->a_result = EOPNOTSUPP;
844                 lwkt_reltoken(&tty_token);
845                 return (0);
846         }
847
848         kn->kn_hook = (caddr_t)dev;
849         knote_insert(klist, kn);
850         lwkt_reltoken(&tty_token);
851         return (0);
852 }
853
854 static int
855 filt_ptcread (struct knote *kn, long hint)
856 {
857         struct tty *tp = ((cdev_t)kn->kn_hook)->si_tty;
858         struct pt_ioctl *pti = ((cdev_t)kn->kn_hook)->si_drv1;
859
860         lwkt_gettoken(&tty_token);
861         if (tp->t_state & TS_ZOMBIE) {
862                 kn->kn_flags |= EV_EOF;
863                 lwkt_reltoken(&tty_token);
864                 return (1);
865         }
866
867         if ((tp->t_state & TS_ISOPEN) &&
868             ((tp->t_outq.c_cc && (tp->t_state & TS_TTSTOP) == 0) ||
869              ((pti->pt_flags & PF_PKT) && pti->pt_send) ||
870              ((pti->pt_flags & PF_UCNTL) && pti->pt_ucntl))) {
871                 kn->kn_data = tp->t_outq.c_cc;
872                 lwkt_reltoken(&tty_token);
873                 return(1);
874         } else {
875                 lwkt_reltoken(&tty_token);
876                 return(0);
877         }
878 }
879
880 static int
881 filt_ptcwrite (struct knote *kn, long hint)
882 {
883         struct tty *tp = ((cdev_t)kn->kn_hook)->si_tty;
884         struct pt_ioctl *pti = ((cdev_t)kn->kn_hook)->si_drv1;
885
886         lwkt_gettoken(&tty_token);
887         if (tp->t_state & TS_ZOMBIE) {
888                 kn->kn_flags |= EV_EOF;
889                 lwkt_reltoken(&tty_token);
890                 return (1);
891         }
892
893         if (tp->t_state & TS_ISOPEN &&
894             ((pti->pt_flags & PF_REMOTE) ?
895              (tp->t_canq.c_cc == 0) :
896              ((tp->t_rawq.c_cc + tp->t_canq.c_cc < TTYHOG - 2) ||
897               (tp->t_canq.c_cc == 0 && (tp->t_lflag & ICANON))))) {
898                 kn->kn_data = tp->t_canq.c_cc + tp->t_rawq.c_cc;
899                 lwkt_reltoken(&tty_token);
900                 return(1);
901         } else {
902                 lwkt_reltoken(&tty_token);
903                 return(0);
904         }
905         /* NOTREACHED */
906 }
907
908 static void
909 filt_ptcrdetach (struct knote *kn)
910 {
911         struct tty *tp = ((cdev_t)kn->kn_hook)->si_tty;
912
913         knote_remove(&tp->t_rkq.ki_note, kn);
914 }
915
916 static void
917 filt_ptcwdetach (struct knote *kn)
918 {
919         struct tty *tp = ((cdev_t)kn->kn_hook)->si_tty;
920
921         knote_remove(&tp->t_wkq.ki_note, kn);
922 }
923
924 /*
925  * I/O ops
926  */
927 static  int
928 ptcwrite(struct dev_write_args *ap)
929 {
930         cdev_t dev = ap->a_head.a_dev;
931         struct tty *tp = dev->si_tty;
932         u_char *cp = 0;
933         int cc = 0;
934         u_char locbuf[BUFSIZ];
935         int cnt = 0;
936         struct pt_ioctl *pti = dev->si_drv1;
937         int error = 0;
938
939         lwkt_gettoken(&tty_token);
940 again:
941         if ((tp->t_state&TS_ISOPEN) == 0)
942                 goto block;
943         if (pti->pt_flags & PF_REMOTE) {
944                 if (tp->t_canq.c_cc)
945                         goto block;
946                 while ((ap->a_uio->uio_resid > 0 || cc > 0) &&
947                        tp->t_canq.c_cc < TTYHOG - 1) {
948                         if (cc == 0) {
949                                 cc = (int)szmin(ap->a_uio->uio_resid, BUFSIZ);
950                                 cc = imin(cc, TTYHOG - 1 - tp->t_canq.c_cc);
951                                 cp = locbuf;
952                                 error = uiomove(cp, (size_t)cc, ap->a_uio);
953                                 if (error) {
954                                         lwkt_reltoken(&tty_token);
955                                         return (error);
956                                 }
957                                 /* check again for safety */
958                                 if ((tp->t_state & TS_ISOPEN) == 0) {
959                                         /* adjust as usual */
960                                         ap->a_uio->uio_resid += cc;
961                                         lwkt_reltoken(&tty_token);
962                                         return (EIO);
963                                 }
964                         }
965                         if (cc > 0) {
966                                 cc = b_to_q((char *)cp, cc, &tp->t_canq);
967                                 /*
968                                  * XXX we don't guarantee that the canq size
969                                  * is >= TTYHOG, so the above b_to_q() may
970                                  * leave some bytes uncopied.  However, space
971                                  * is guaranteed for the null terminator if
972                                  * we don't fail here since (TTYHOG - 1) is
973                                  * not a multiple of CBSIZE.
974                                  */
975                                 if (cc > 0)
976                                         break;
977                         }
978                 }
979                 /* adjust for data copied in but not written */
980                 ap->a_uio->uio_resid += cc;
981                 clist_putc(0, &tp->t_canq);
982                 ttwakeup(tp);
983                 wakeup(TSA_PTS_READ(tp));
984                 lwkt_reltoken(&tty_token);
985                 return (0);
986         }
987         while (ap->a_uio->uio_resid > 0 || cc > 0) {
988                 if (cc == 0) {
989                         cc = (int)szmin(ap->a_uio->uio_resid, BUFSIZ);
990                         cp = locbuf;
991                         error = uiomove(cp, (size_t)cc, ap->a_uio);
992                         if (error) {
993                                 lwkt_reltoken(&tty_token);
994                                 return (error);
995                         }
996                         /* check again for safety */
997                         if ((tp->t_state & TS_ISOPEN) == 0) {
998                                 /* adjust for data copied in but not written */
999                                 ap->a_uio->uio_resid += cc;
1000                                 lwkt_reltoken(&tty_token);
1001                                 return (EIO);
1002                         }
1003                 }
1004                 while (cc > 0) {
1005                         if ((tp->t_rawq.c_cc + tp->t_canq.c_cc) >= TTYHOG - 2 &&
1006                            (tp->t_canq.c_cc > 0 || !(tp->t_lflag&ICANON))) {
1007                                 wakeup(TSA_HUP_OR_INPUT(tp));
1008                                 goto block;
1009                         }
1010                         (*linesw[tp->t_line].l_rint)(*cp++, tp);
1011                         cnt++;
1012                         cc--;
1013                 }
1014                 cc = 0;
1015         }
1016         lwkt_reltoken(&tty_token);
1017         return (0);
1018 block:
1019         /*
1020          * Come here to wait for slave to open, for space
1021          * in outq, or space in rawq, or an empty canq.
1022          */
1023         if ((tp->t_state & TS_CONNECTED) == 0) {
1024                 /* adjust for data copied in but not written */
1025                 ap->a_uio->uio_resid += cc;
1026                 lwkt_reltoken(&tty_token);
1027                 return (EIO);
1028         }
1029         if (ap->a_ioflag & IO_NDELAY) {
1030                 /* adjust for data copied in but not written */
1031                 ap->a_uio->uio_resid += cc;
1032                 if (cnt == 0) {
1033                         lwkt_reltoken(&tty_token);
1034                         return (EWOULDBLOCK);
1035                 }
1036                 lwkt_reltoken(&tty_token);
1037                 return (0);
1038         }
1039         error = tsleep(TSA_PTC_WRITE(tp), PCATCH, "ptcout", 0);
1040         if (error) {
1041                 /* adjust for data copied in but not written */
1042                 ap->a_uio->uio_resid += cc;
1043                 lwkt_reltoken(&tty_token);
1044                 return (error);
1045         }
1046         goto again;
1047 }
1048
1049 /*ARGSUSED*/
1050 static  int
1051 ptyioctl(struct dev_ioctl_args *ap)
1052 {
1053         cdev_t dev = ap->a_head.a_dev;
1054         struct tty *tp = dev->si_tty;
1055         struct pt_ioctl *pti = dev->si_drv1;
1056         u_char *cc = tp->t_cc;
1057         int stop, error;
1058
1059         lwkt_gettoken(&tty_token);
1060         if (dev_dflags(dev) & D_MASTER) {
1061                 switch (ap->a_cmd) {
1062
1063                 case TIOCGPGRP:
1064                         /*
1065                          * We avoid calling ttioctl on the controller since,
1066                          * in that case, tp must be the controlling terminal.
1067                          */
1068                         *(int *)ap->a_data = tp->t_pgrp ? tp->t_pgrp->pg_id : 0;
1069                         lwkt_reltoken(&tty_token);
1070                         return (0);
1071
1072                 case TIOCPKT:
1073                         if (*(int *)ap->a_data) {
1074                                 if (pti->pt_flags & PF_UCNTL) {
1075                                         lwkt_reltoken(&tty_token);
1076                                         return (EINVAL);
1077                                 }
1078                                 pti->pt_flags |= PF_PKT;
1079                         } else
1080                                 pti->pt_flags &= ~PF_PKT;
1081                         lwkt_reltoken(&tty_token);
1082                         return (0);
1083
1084                 case TIOCUCNTL:
1085                         if (*(int *)ap->a_data) {
1086                                 if (pti->pt_flags & PF_PKT) {
1087                                         lwkt_reltoken(&tty_token);
1088                                         return (EINVAL);
1089                                 }
1090                                 pti->pt_flags |= PF_UCNTL;
1091                         } else
1092                                 pti->pt_flags &= ~PF_UCNTL;
1093                         lwkt_reltoken(&tty_token);
1094                         return (0);
1095
1096                 case TIOCREMOTE:
1097                         if (*(int *)ap->a_data)
1098                                 pti->pt_flags |= PF_REMOTE;
1099                         else
1100                                 pti->pt_flags &= ~PF_REMOTE;
1101                         ttyflush(tp, FREAD|FWRITE);
1102                         lwkt_reltoken(&tty_token);
1103                         return (0);
1104
1105 #ifdef UNIX98_PTYS
1106                 case TIOCISPTMASTER:
1107                         if ((pti->pt_flags2 & PF_UNIX98) &&
1108                             (pti->devc == dev)) {
1109                                 lwkt_reltoken(&tty_token);
1110                                 return (0);
1111                         } else {
1112                                 lwkt_reltoken(&tty_token);
1113                                 return (EINVAL);
1114                         }
1115                 }
1116 #endif
1117
1118                 /*
1119                  * The rest of the ioctls shouldn't be called until 
1120                  * the slave is open.
1121                  */
1122                 if ((tp->t_state & TS_ISOPEN) == 0) {
1123                         lwkt_reltoken(&tty_token);
1124                         return (EAGAIN);
1125                 }
1126
1127                 switch (ap->a_cmd) {
1128 #ifdef COMPAT_43
1129                 case TIOCSETP:
1130                 case TIOCSETN:
1131 #endif
1132                 case TIOCSETD:
1133                 case TIOCSETA:
1134                 case TIOCSETAW:
1135                 case TIOCSETAF:
1136                         /*
1137                          * IF CONTROLLER STTY THEN MUST FLUSH TO PREVENT A HANG.
1138                          * ttywflush(tp) will hang if there are characters in
1139                          * the outq.
1140                          */
1141                         ndflush(&tp->t_outq, tp->t_outq.c_cc);
1142                         break;
1143
1144                 case TIOCSIG:
1145                         if (*(unsigned int *)ap->a_data >= NSIG ||
1146                             *(unsigned int *)ap->a_data == 0) {
1147                                 lwkt_reltoken(&tty_token);
1148                                 return(EINVAL);
1149                         }
1150                         if ((tp->t_lflag&NOFLSH) == 0)
1151                                 ttyflush(tp, FREAD|FWRITE);
1152                         pgsignal(tp->t_pgrp, *(unsigned int *)ap->a_data, 1);
1153                         if ((*(unsigned int *)ap->a_data == SIGINFO) &&
1154                             ((tp->t_lflag&NOKERNINFO) == 0))
1155                                 ttyinfo(tp);
1156                         lwkt_reltoken(&tty_token);
1157                         return(0);
1158                 }
1159         }
1160         if (ap->a_cmd == TIOCEXT) {
1161                 /*
1162                  * When the EXTPROC bit is being toggled, we need
1163                  * to send an TIOCPKT_IOCTL if the packet driver
1164                  * is turned on.
1165                  */
1166                 if (*(int *)ap->a_data) {
1167                         if (pti->pt_flags & PF_PKT) {
1168                                 pti->pt_send |= TIOCPKT_IOCTL;
1169                                 ptcwakeup(tp, FREAD);
1170                         }
1171                         tp->t_lflag |= EXTPROC;
1172                 } else {
1173                         if ((tp->t_lflag & EXTPROC) &&
1174                             (pti->pt_flags & PF_PKT)) {
1175                                 pti->pt_send |= TIOCPKT_IOCTL;
1176                                 ptcwakeup(tp, FREAD);
1177                         }
1178                         tp->t_lflag &= ~EXTPROC;
1179                 }
1180                 lwkt_reltoken(&tty_token);
1181                 return(0);
1182         }
1183         error = (*linesw[tp->t_line].l_ioctl)(tp, ap->a_cmd, ap->a_data,
1184                                               ap->a_fflag, ap->a_cred);
1185         if (error == ENOIOCTL)
1186                  error = ttioctl(tp, ap->a_cmd, ap->a_data, ap->a_fflag);
1187         if (error == ENOIOCTL) {
1188                 if (pti->pt_flags & PF_UCNTL &&
1189                     (ap->a_cmd & ~0xff) == UIOCCMD(0)) {
1190                         if (ap->a_cmd & 0xff) {
1191                                 pti->pt_ucntl = (u_char)ap->a_cmd;
1192                                 ptcwakeup(tp, FREAD);
1193                         }
1194                         lwkt_reltoken(&tty_token);
1195                         return (0);
1196                 }
1197                 error = ENOTTY;
1198         }
1199         /*
1200          * If external processing and packet mode send ioctl packet.
1201          */
1202         if ((tp->t_lflag&EXTPROC) && (pti->pt_flags & PF_PKT)) {
1203                 switch(ap->a_cmd) {
1204                 case TIOCSETA:
1205                 case TIOCSETAW:
1206                 case TIOCSETAF:
1207 #ifdef COMPAT_43
1208                 case TIOCSETP:
1209                 case TIOCSETN:
1210 #endif
1211 #if defined(COMPAT_43) || defined(COMPAT_SUNOS)
1212                 case TIOCSETC:
1213                 case TIOCSLTC:
1214                 case TIOCLBIS:
1215                 case TIOCLBIC:
1216                 case TIOCLSET:
1217 #endif
1218                         pti->pt_send |= TIOCPKT_IOCTL;
1219                         ptcwakeup(tp, FREAD);
1220                 default:
1221                         break;
1222                 }
1223         }
1224         stop = (tp->t_iflag & IXON) && CCEQ(cc[VSTOP], CTRL('s'))
1225                 && CCEQ(cc[VSTART], CTRL('q'));
1226         if (pti->pt_flags & PF_NOSTOP) {
1227                 if (stop) {
1228                         pti->pt_send &= ~TIOCPKT_NOSTOP;
1229                         pti->pt_send |= TIOCPKT_DOSTOP;
1230                         pti->pt_flags &= ~PF_NOSTOP;
1231                         ptcwakeup(tp, FREAD);
1232                 }
1233         } else {
1234                 if (!stop) {
1235                         pti->pt_send &= ~TIOCPKT_DOSTOP;
1236                         pti->pt_send |= TIOCPKT_NOSTOP;
1237                         pti->pt_flags |= PF_NOSTOP;
1238                         ptcwakeup(tp, FREAD);
1239                 }
1240         }
1241         lwkt_reltoken(&tty_token);
1242         return (error);
1243 }
1244
1245
1246 static void ptc_drvinit (void *unused);
1247
1248 #ifdef UNIX98_PTYS
1249 SYSCTL_INT(_kern, OID_AUTO, pty_debug, CTLFLAG_RW, &pty_debug_level,
1250                 0, "Change pty debug level");
1251 #endif
1252
1253 static void
1254 ptc_drvinit(void *unused)
1255 {
1256         int i;
1257
1258 #ifdef UNIX98_PTYS
1259         /*
1260          * Unix98 pty stuff.
1261          * Create the clonable base device.
1262          */
1263         make_autoclone_dev(&ptc_ops, &DEVFS_CLONE_BITMAP(pty), ptyclone,
1264             0, 0, 0666, "ptmx");
1265 #endif
1266
1267         for (i = 0; i < 256; i++) {
1268                 ptyinit(i);
1269         }
1270 }
1271
1272 SYSINIT(ptcdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE+CDEV_MAJOR_C,ptc_drvinit,NULL)