xref: /openbsd-src/sys/kern/tty_pty.c (revision 4b70baf6e17fc8b27fc1f7fa7929335753fa94c3)
1 /*	$OpenBSD: tty_pty.c,v 1.93 2019/03/11 17:13:31 anton Exp $	*/
2 /*	$NetBSD: tty_pty.c,v 1.33.4.1 1996/06/02 09:08:11 mrg Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1989, 1993
6  *	The Regents of the University of California.  All rights reserved.
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  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)tty_pty.c	8.4 (Berkeley) 2/20/95
33  */
34 
35 /*
36  * Pseudo-teletype Driver
37  * (Actually two drivers, requiring two entries in 'cdevsw')
38  */
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/namei.h>
43 #include <sys/mount.h>
44 #include <sys/ioctl.h>
45 #include <sys/proc.h>
46 #include <sys/tty.h>
47 #include <sys/fcntl.h>
48 #include <sys/file.h>
49 #include <sys/filedesc.h>
50 #include <sys/uio.h>
51 #include <sys/kernel.h>
52 #include <sys/malloc.h>
53 #include <sys/vnode.h>
54 #include <sys/signalvar.h>
55 #include <sys/conf.h>
56 #include <sys/stat.h>
57 #include <sys/sysctl.h>
58 #include <sys/poll.h>
59 #include <sys/pledge.h>
60 #include <sys/rwlock.h>
61 
62 #define BUFSIZ 100		/* Chunk size iomoved to/from user */
63 
64 /*
65  * pts == /dev/tty[p-zP-T][0-9a-zA-Z]
66  * ptc == /dev/pty[p-zP-T][0-9a-zA-Z]
67  */
68 
69 /* XXX this needs to come from somewhere sane, and work with MAKEDEV */
70 #define TTY_LETTERS "pqrstuvwxyzPQRST"
71 #define TTY_SUFFIX "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
72 
73 static int pts_major;
74 
75 struct	pt_softc {
76 	struct	tty *pt_tty;
77 	int	pt_flags;
78 	struct	selinfo pt_selr, pt_selw;
79 	u_char	pt_send;
80 	u_char	pt_ucntl;
81 	char	pty_pn[11];
82 	char	pty_sn[11];
83 };
84 
85 #define	NPTY_MIN		8	/* number of initial ptys */
86 #define NPTY_MAX		992	/* maximum number of ptys supported */
87 
88 static struct pt_softc **pt_softc = NULL;	/* pty array */
89 static int npty = 0;				/* size of pty array */
90 static int maxptys = NPTY_MAX;			/* maximum number of ptys */
91 /* for pty array */
92 struct rwlock pt_softc_lock = RWLOCK_INITIALIZER("ptarrlk");
93 
94 #define	PF_PKT		0x08		/* packet mode */
95 #define	PF_STOPPED	0x10		/* user told stopped */
96 #define	PF_REMOTE	0x20		/* remote and flow controlled input */
97 #define	PF_NOSTOP	0x40
98 #define PF_UCNTL	0x80		/* user control mode */
99 
100 void	ptyattach(int);
101 void	ptcwakeup(struct tty *, int);
102 struct tty *ptytty(dev_t);
103 void	ptsstart(struct tty *);
104 int	sysctl_pty(int *, u_int, void *, size_t *, void *, size_t);
105 
106 void	filt_ptcrdetach(struct knote *);
107 int	filt_ptcread(struct knote *, long);
108 void	filt_ptcwdetach(struct knote *);
109 int	filt_ptcwrite(struct knote *, long);
110 
111 static struct pt_softc **ptyarralloc(int);
112 static int check_pty(int);
113 
114 static gid_t tty_gid = TTY_GID;
115 
116 void	ptydevname(int, struct pt_softc *);
117 dev_t	pty_getfree(void);
118 
119 void	ptmattach(int);
120 int	ptmopen(dev_t, int, int, struct proc *);
121 int	ptmclose(dev_t, int, int, struct proc *);
122 int	ptmioctl(dev_t, u_long, caddr_t, int, struct proc *p);
123 static int ptm_vn_open(struct nameidata *);
124 
125 void
126 ptydevname(int minor, struct pt_softc *pti)
127 {
128 	char buf[11] = "/dev/XtyXX";
129 	int i, j;
130 
131 	i = minor / (sizeof(TTY_SUFFIX) - 1);
132 	j = minor % (sizeof(TTY_SUFFIX) - 1);
133 	if (i >= sizeof(TTY_LETTERS) - 1) {
134 		pti->pty_pn[0] = '\0';
135 		pti->pty_sn[0] = '\0';
136 		return;
137 	}
138 	buf[5] = 'p';
139 	buf[8] = TTY_LETTERS[i];
140 	buf[9] = TTY_SUFFIX[j];
141 	memcpy(pti->pty_pn, buf, sizeof(buf));
142 	buf[5] = 't';
143 	memcpy(pti->pty_sn, buf, sizeof(buf));
144 }
145 
146 /*
147  * Allocate and zero array of nelem elements.
148  */
149 struct pt_softc **
150 ptyarralloc(int nelem)
151 {
152 	struct pt_softc **pt;
153 
154 	pt = mallocarray(nelem, sizeof(struct pt_softc *), M_DEVBUF,
155 	    M_WAITOK|M_ZERO);
156 	return pt;
157 }
158 
159 /*
160  * Check if the minor is correct and ensure necessary structures
161  * are properly allocated.
162  */
163 int
164 check_pty(int dev)
165 {
166 	struct pt_softc *pti;
167 	int minor = minor(dev);
168 
169 	rw_enter_write(&pt_softc_lock);
170 	if (minor >= npty) {
171 		struct pt_softc **newpt;
172 		int newnpty;
173 
174 		/* check if the requested pty can be granted */
175 		if (minor >= maxptys)
176 			goto limit_reached;
177 
178 		/* grow pty array by powers of two, up to maxptys */
179 		for (newnpty = npty; newnpty <= minor; newnpty *= 2)
180 			;
181 
182 		if (newnpty > maxptys)
183 			newnpty = maxptys;
184 		newpt = ptyarralloc(newnpty);
185 
186 		memcpy(newpt, pt_softc, npty * sizeof(struct pt_softc *));
187 		free(pt_softc, M_DEVBUF, npty * sizeof(struct pt_softc *));
188 		pt_softc = newpt;
189 		npty = newnpty;
190 	}
191 
192 	/*
193 	 * If the entry is not yet allocated, allocate one.
194 	 */
195 	if (!pt_softc[minor]) {
196 		pti = malloc(sizeof(struct pt_softc), M_DEVBUF,
197 		    M_WAITOK|M_ZERO);
198 		pti->pt_tty = ttymalloc(1000000);
199 		pti->pt_tty->t_dev = dev;
200 		ptydevname(minor, pti);
201 		pt_softc[minor] = pti;
202 	}
203 	rw_exit_write(&pt_softc_lock);
204 	return (0);
205 limit_reached:
206 	rw_exit_write(&pt_softc_lock);
207 	tablefull("pty");
208 	return (ENXIO);
209 }
210 
211 /*
212  * Establish n (or default if n is 1) ptys in the system.
213  */
214 void
215 ptyattach(int n)
216 {
217 	/* maybe should allow 0 => none? */
218 	if (n <= 1)
219 		n = NPTY_MIN;
220 	pt_softc = ptyarralloc(n);
221 	npty = n;
222 
223 	/*
224 	 * If we have pty, we need ptm too.
225 	 */
226 	ptmattach(1);
227 }
228 
229 int
230 ptsopen(dev_t dev, int flag, int devtype, struct proc *p)
231 {
232 	struct pt_softc *pti;
233 	struct tty *tp;
234 	int error;
235 
236 	if ((error = check_pty(dev)))
237 		return (error);
238 
239 	pti = pt_softc[minor(dev)];
240 	tp = pti->pt_tty;
241 	if ((tp->t_state & TS_ISOPEN) == 0) {
242 		tp->t_state |= TS_WOPEN;
243 		ttychars(tp);		/* Set up default chars */
244 		tp->t_iflag = TTYDEF_IFLAG;
245 		tp->t_oflag = TTYDEF_OFLAG;
246 		tp->t_lflag = TTYDEF_LFLAG;
247 		tp->t_cflag = TTYDEF_CFLAG;
248 		tp->t_ispeed = tp->t_ospeed = B115200;
249 		ttsetwater(tp);		/* would be done in xxparam() */
250 	} else if (tp->t_state & TS_XCLUDE && suser(p) != 0)
251 		return (EBUSY);
252 	if (tp->t_oproc)			/* Ctrlr still around. */
253 		tp->t_state |= TS_CARR_ON;
254 	while ((tp->t_state & TS_CARR_ON) == 0) {
255 		tp->t_state |= TS_WOPEN;
256 		if (flag & FNONBLOCK)
257 			break;
258 		error = ttysleep(tp, &tp->t_rawq, TTIPRI | PCATCH,
259 				 ttopen, 0);
260 		if (error)
261 			return (error);
262 	}
263 	error = (*linesw[tp->t_line].l_open)(dev, tp, p);
264 	ptcwakeup(tp, FREAD|FWRITE);
265 	return (error);
266 }
267 
268 int
269 ptsclose(dev_t dev, int flag, int mode, struct proc *p)
270 {
271 	struct pt_softc *pti = pt_softc[minor(dev)];
272 	struct tty *tp = pti->pt_tty;
273 	int error;
274 
275 	error = (*linesw[tp->t_line].l_close)(tp, flag, p);
276 	error |= ttyclose(tp);
277 	ptcwakeup(tp, FREAD|FWRITE);
278 	return (error);
279 }
280 
281 int
282 ptsread(dev_t dev, struct uio *uio, int flag)
283 {
284 	struct proc *p = curproc;
285 	struct process *pr = p->p_p;
286 	struct pt_softc *pti = pt_softc[minor(dev)];
287 	struct tty *tp = pti->pt_tty;
288 	int error = 0;
289 
290 again:
291 	if (pti->pt_flags & PF_REMOTE) {
292 		while (isbackground(pr, tp)) {
293 			if ((pr->ps_sigacts->ps_sigignore & sigmask(SIGTTIN)) ||
294 			    (p->p_sigmask & sigmask(SIGTTIN)) ||
295 			    pr->ps_pgrp->pg_jobc == 0 ||
296 			    pr->ps_flags & PS_PPWAIT)
297 				return (EIO);
298 			pgsignal(pr->ps_pgrp, SIGTTIN, 1);
299 			error = ttysleep(tp, &lbolt,
300 			    TTIPRI | PCATCH, ttybg, 0);
301 			if (error)
302 				return (error);
303 		}
304 		if (tp->t_canq.c_cc == 0) {
305 			if (flag & IO_NDELAY)
306 				return (EWOULDBLOCK);
307 			error = ttysleep(tp, &tp->t_canq,
308 			    TTIPRI | PCATCH, ttyin, 0);
309 			if (error)
310 				return (error);
311 			goto again;
312 		}
313 		while (tp->t_canq.c_cc > 1 && uio->uio_resid > 0)
314 			if (ureadc(getc(&tp->t_canq), uio) < 0) {
315 				error = EFAULT;
316 				break;
317 			}
318 		if (tp->t_canq.c_cc == 1)
319 			(void) getc(&tp->t_canq);
320 		if (tp->t_canq.c_cc)
321 			return (error);
322 	} else
323 		if (tp->t_oproc)
324 			error = (*linesw[tp->t_line].l_read)(tp, uio, flag);
325 	ptcwakeup(tp, FWRITE);
326 	return (error);
327 }
328 
329 /*
330  * Write to pseudo-tty.
331  * Wakeups of controlling tty will happen
332  * indirectly, when tty driver calls ptsstart.
333  */
334 int
335 ptswrite(dev_t dev, struct uio *uio, int flag)
336 {
337 	struct pt_softc *pti = pt_softc[minor(dev)];
338 	struct tty *tp = pti->pt_tty;
339 
340 	if (tp->t_oproc == 0)
341 		return (EIO);
342 	return ((*linesw[tp->t_line].l_write)(tp, uio, flag));
343 }
344 
345 /*
346  * Start output on pseudo-tty.
347  * Wake up process polling or sleeping for input from controlling tty.
348  */
349 void
350 ptsstart(struct tty *tp)
351 {
352 	struct pt_softc *pti = pt_softc[minor(tp->t_dev)];
353 
354 	if (tp->t_state & TS_TTSTOP)
355 		return;
356 	if (pti->pt_flags & PF_STOPPED) {
357 		pti->pt_flags &= ~PF_STOPPED;
358 		pti->pt_send = TIOCPKT_START;
359 	}
360 	ptcwakeup(tp, FREAD);
361 }
362 
363 int
364 ptsstop(struct tty *tp, int flush)
365 {
366 	struct pt_softc *pti = pt_softc[minor(tp->t_dev)];
367 	int flag;
368 
369 	/* note: FLUSHREAD and FLUSHWRITE already ok */
370 	if (flush == 0) {
371 		flush = TIOCPKT_STOP;
372 		pti->pt_flags |= PF_STOPPED;
373 	} else
374 		pti->pt_flags &= ~PF_STOPPED;
375 	pti->pt_send |= flush;
376 	/* change of perspective */
377 	flag = 0;
378 	if (flush & FREAD)
379 		flag |= FWRITE;
380 	if (flush & FWRITE)
381 		flag |= FREAD;
382 	ptcwakeup(tp, flag);
383 	return 0;
384 }
385 
386 void
387 ptcwakeup(struct tty *tp, int flag)
388 {
389 	struct pt_softc *pti = pt_softc[minor(tp->t_dev)];
390 
391 	if (flag & FREAD) {
392 		selwakeup(&pti->pt_selr);
393 		wakeup(&tp->t_outq.c_cf);
394 	}
395 	if (flag & FWRITE) {
396 		selwakeup(&pti->pt_selw);
397 		wakeup(&tp->t_rawq.c_cf);
398 	}
399 }
400 
401 int ptcopen(dev_t, int, int, struct proc *);
402 
403 int
404 ptcopen(dev_t dev, int flag, int devtype, struct proc *p)
405 {
406 	struct pt_softc *pti;
407 	struct tty *tp;
408 	int error;
409 
410 	if ((error = check_pty(dev)))
411 		return (error);
412 
413 	pti = pt_softc[minor(dev)];
414 	tp = pti->pt_tty;
415 	if (tp->t_oproc)
416 		return (EIO);
417 	tp->t_oproc = ptsstart;
418 	(void)(*linesw[tp->t_line].l_modem)(tp, 1);
419 	tp->t_lflag &= ~EXTPROC;
420 	pti->pt_flags = 0;
421 	pti->pt_send = 0;
422 	pti->pt_ucntl = 0;
423 	return (0);
424 }
425 
426 int
427 ptcclose(dev_t dev, int flag, int devtype, struct proc *p)
428 {
429 	struct pt_softc *pti = pt_softc[minor(dev)];
430 	struct tty *tp = pti->pt_tty;
431 
432 	(void)(*linesw[tp->t_line].l_modem)(tp, 0);
433 	tp->t_state &= ~TS_CARR_ON;
434 	tp->t_oproc = 0;		/* mark closed */
435 	return (0);
436 }
437 
438 int
439 ptcread(dev_t dev, struct uio *uio, int flag)
440 {
441 	struct pt_softc *pti = pt_softc[minor(dev)];
442 	struct tty *tp = pti->pt_tty;
443 	char buf[BUFSIZ];
444 	int error = 0, cc, bufcc = 0;
445 
446 	/*
447 	 * We want to block until the slave
448 	 * is open, and there's something to read;
449 	 * but if we lost the slave or we're NBIO,
450 	 * then return the appropriate error instead.
451 	 */
452 	for (;;) {
453 		if (tp->t_state & TS_ISOPEN) {
454 			if (pti->pt_flags & PF_PKT && pti->pt_send) {
455 				error = ureadc((int)pti->pt_send, uio);
456 				if (error)
457 					return (error);
458 				if (pti->pt_send & TIOCPKT_IOCTL) {
459 					cc = MIN(uio->uio_resid,
460 						sizeof(tp->t_termios));
461 					error = uiomove(&tp->t_termios, cc, uio);
462 					if (error)
463 						return (error);
464 				}
465 				pti->pt_send = 0;
466 				return (0);
467 			}
468 			if (pti->pt_flags & PF_UCNTL && pti->pt_ucntl) {
469 				error = ureadc((int)pti->pt_ucntl, uio);
470 				if (error)
471 					return (error);
472 				pti->pt_ucntl = 0;
473 				return (0);
474 			}
475 			if (tp->t_outq.c_cc && (tp->t_state & TS_TTSTOP) == 0)
476 				break;
477 		}
478 		if ((tp->t_state & TS_CARR_ON) == 0)
479 			return (0);	/* EOF */
480 		if (flag & IO_NDELAY)
481 			return (EWOULDBLOCK);
482 		error = tsleep(&tp->t_outq.c_cf, TTIPRI | PCATCH,
483 		    ttyin, 0);
484 		if (error)
485 			return (error);
486 	}
487 	if (pti->pt_flags & (PF_PKT|PF_UCNTL))
488 		error = ureadc(0, uio);
489 	while (uio->uio_resid > 0 && error == 0) {
490 		cc = MIN(uio->uio_resid, BUFSIZ);
491 		cc = q_to_b(&tp->t_outq, buf, cc);
492 		if (cc > bufcc)
493 			bufcc = cc;
494 		if (cc <= 0)
495 			break;
496 		error = uiomove(buf, cc, uio);
497 	}
498 	ttwakeupwr(tp);
499 	if (bufcc)
500 		explicit_bzero(buf, bufcc);
501 	return (error);
502 }
503 
504 
505 int
506 ptcwrite(dev_t dev, struct uio *uio, int flag)
507 {
508 	struct pt_softc *pti = pt_softc[minor(dev)];
509 	struct tty *tp = pti->pt_tty;
510 	u_char *cp = NULL;
511 	int cc = 0, bufcc = 0;
512 	u_char buf[BUFSIZ];
513 	size_t cnt = 0;
514 	int error = 0;
515 
516 again:
517 	if ((tp->t_state & TS_ISOPEN) == 0)
518 		goto block;
519 	if (pti->pt_flags & PF_REMOTE) {
520 		if (tp->t_canq.c_cc)
521 			goto block;
522 		while (uio->uio_resid > 0 && tp->t_canq.c_cc < TTYHOG(tp) - 1) {
523 			if (cc == 0) {
524 				cc = MIN(uio->uio_resid, BUFSIZ);
525 				cc = min(cc, TTYHOG(tp) - 1 - tp->t_canq.c_cc);
526 				if (cc > bufcc)
527 					bufcc = cc;
528 				cp = buf;
529 				error = uiomove(cp, cc, uio);
530 				if (error)
531 					goto done;
532 				/* check again for safety */
533 				if ((tp->t_state & TS_ISOPEN) == 0) {
534 					error = EIO;
535 					goto done;
536 				}
537 			}
538 			if (cc)
539 				(void) b_to_q((char *)cp, cc, &tp->t_canq);
540 			cc = 0;
541 		}
542 		(void) putc(0, &tp->t_canq);
543 		ttwakeup(tp);
544 		wakeup(&tp->t_canq);
545 		goto done;
546 	}
547 	do {
548 		if (cc == 0) {
549 			cc = MIN(uio->uio_resid, BUFSIZ);
550 			if (cc > bufcc)
551 				bufcc = cc;
552 			cp = buf;
553 			error = uiomove(cp, cc, uio);
554 			if (error)
555 				goto done;
556 			/* check again for safety */
557 			if ((tp->t_state & TS_ISOPEN) == 0) {
558 				error = EIO;
559 				goto done;
560 			}
561 		}
562 		bufcc = cc;
563 		while (cc > 0) {
564 			if ((tp->t_rawq.c_cc + tp->t_canq.c_cc) >= TTYHOG(tp) - 2 &&
565 			   (tp->t_canq.c_cc > 0 || !ISSET(tp->t_lflag, ICANON))) {
566 				wakeup(&tp->t_rawq);
567 				goto block;
568 			}
569 			(*linesw[tp->t_line].l_rint)(*cp++, tp);
570 			cnt++;
571 			cc--;
572 		}
573 		cc = 0;
574 	} while (uio->uio_resid > 0);
575 	goto done;
576 block:
577 	/*
578 	 * Come here to wait for slave to open, for space
579 	 * in outq, or space in rawq.
580 	 */
581 	if ((tp->t_state & TS_CARR_ON) == 0) {
582 		error = EIO;
583 		goto done;
584 	}
585 	if (flag & IO_NDELAY) {
586 		/* adjust for data copied in but not written */
587 		uio->uio_resid += cc;
588 		if (cnt == 0)
589 			error = EWOULDBLOCK;
590 		goto done;
591 	}
592 	error = tsleep(&tp->t_rawq.c_cf, TTOPRI | PCATCH,
593 	    ttyout, 0);
594 	if (error == 0)
595 		goto again;
596 
597 	/* adjust for data copied in but not written */
598 	uio->uio_resid += cc;
599 done:
600 	if (bufcc)
601 		explicit_bzero(buf, bufcc);
602 	return (error);
603 }
604 
605 int
606 ptcpoll(dev_t dev, int events, struct proc *p)
607 {
608 	struct pt_softc *pti = pt_softc[minor(dev)];
609 	struct tty *tp = pti->pt_tty;
610 	int revents = 0, s;
611 
612 	if (!ISSET(tp->t_state, TS_ISOPEN) && ISSET(tp->t_state, TS_CARR_ON))
613 		goto notopen;
614 
615 	if (events & (POLLIN | POLLRDNORM)) {
616 		/*
617 		 * Need to protect access to t_outq
618 		 */
619 		s = spltty();
620 		if ((tp->t_outq.c_cc && !ISSET(tp->t_state, TS_TTSTOP)) ||
621 		    ((pti->pt_flags & PF_PKT) && pti->pt_send) ||
622 		    ((pti->pt_flags & PF_UCNTL) && pti->pt_ucntl))
623 			revents |= events & (POLLIN | POLLRDNORM);
624 		splx(s);
625 	}
626 	/* NOTE: POLLHUP and POLLOUT/POLLWRNORM are mutually exclusive */
627 	if (!ISSET(tp->t_state, TS_CARR_ON)) {
628 		revents |= POLLHUP;
629 	} else if (events & (POLLOUT | POLLWRNORM)) {
630 		if ((pti->pt_flags & PF_REMOTE) ?
631 		    (tp->t_canq.c_cc == 0) :
632 		    ((tp->t_rawq.c_cc + tp->t_canq.c_cc < TTYHOG(tp) - 2) ||
633 		    (tp->t_canq.c_cc == 0 && ISSET(tp->t_lflag, ICANON))))
634 			revents |= events & (POLLOUT | POLLWRNORM);
635 	}
636 	if (events & (POLLPRI | POLLRDBAND)) {
637 		/* If in packet or user control mode, check for data. */
638 		if (((pti->pt_flags & PF_PKT) && pti->pt_send) ||
639 		    ((pti->pt_flags & PF_UCNTL) && pti->pt_ucntl))
640 			revents |= events & (POLLPRI | POLLRDBAND);
641 	}
642 
643 	if (revents == 0) {
644 notopen:
645 		if (events & (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND))
646 			selrecord(p, &pti->pt_selr);
647 		if (events & (POLLOUT | POLLWRNORM))
648 			selrecord(p, &pti->pt_selw);
649 	}
650 
651 	return (revents);
652 }
653 
654 void
655 filt_ptcrdetach(struct knote *kn)
656 {
657 	struct pt_softc *pti = (struct pt_softc *)kn->kn_hook;
658 	int s;
659 
660 	s = spltty();
661 	SLIST_REMOVE(&pti->pt_selr.si_note, kn, knote, kn_selnext);
662 	splx(s);
663 }
664 
665 int
666 filt_ptcread(struct knote *kn, long hint)
667 {
668 	struct pt_softc *pti = (struct pt_softc *)kn->kn_hook;
669 	struct tty *tp;
670 
671 	tp = pti->pt_tty;
672 	kn->kn_data = 0;
673 
674 	if (ISSET(tp->t_state, TS_ISOPEN)) {
675 		if (!ISSET(tp->t_state, TS_TTSTOP))
676 			kn->kn_data = tp->t_outq.c_cc;
677 		if (((pti->pt_flags & PF_PKT) && pti->pt_send) ||
678 		    ((pti->pt_flags & PF_UCNTL) && pti->pt_ucntl))
679 			kn->kn_data++;
680 	}
681 
682 	if (!ISSET(tp->t_state, TS_CARR_ON)) {
683 		kn->kn_flags |= EV_EOF;
684 		return (1);
685 	}
686 
687 	return (kn->kn_data > 0);
688 }
689 
690 void
691 filt_ptcwdetach(struct knote *kn)
692 {
693 	struct pt_softc *pti = (struct pt_softc *)kn->kn_hook;
694 	int s;
695 
696 	s = spltty();
697 	SLIST_REMOVE(&pti->pt_selw.si_note, kn, knote, kn_selnext);
698 	splx(s);
699 }
700 
701 int
702 filt_ptcwrite(struct knote *kn, long hint)
703 {
704 	struct pt_softc *pti = (struct pt_softc *)kn->kn_hook;
705 	struct tty *tp;
706 
707 	tp = pti->pt_tty;
708 	kn->kn_data = 0;
709 
710 	if (ISSET(tp->t_state, TS_ISOPEN)) {
711 		if (ISSET(pti->pt_flags, PF_REMOTE)) {
712 			if (tp->t_canq.c_cc == 0)
713 				kn->kn_data = tp->t_canq.c_cn;
714 		} else if (tp->t_rawq.c_cc + tp->t_canq.c_cc < TTYHOG(tp)-2)
715 			kn->kn_data = tp->t_canq.c_cn -
716 			    (tp->t_rawq.c_cc + tp->t_canq.c_cc);
717 	}
718 
719 	return (kn->kn_data > 0);
720 }
721 
722 struct filterops ptcread_filtops =
723 	{ 1, NULL, filt_ptcrdetach, filt_ptcread };
724 struct filterops ptcwrite_filtops =
725 	{ 1, NULL, filt_ptcwdetach, filt_ptcwrite };
726 
727 int
728 ptckqfilter(dev_t dev, struct knote *kn)
729 {
730 	struct pt_softc *pti = pt_softc[minor(dev)];
731 	struct klist *klist;
732 	int s;
733 
734 	switch (kn->kn_filter) {
735 	case EVFILT_READ:
736 		klist = &pti->pt_selr.si_note;
737 		kn->kn_fop = &ptcread_filtops;
738 		break;
739 	case EVFILT_WRITE:
740 		klist = &pti->pt_selw.si_note;
741 		kn->kn_fop = &ptcwrite_filtops;
742 		break;
743 	default:
744 		return (EINVAL);
745 	}
746 
747 	kn->kn_hook = (caddr_t)pti;
748 
749 	s = spltty();
750 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
751 	splx(s);
752 
753 	return (0);
754 }
755 
756 struct tty *
757 ptytty(dev_t dev)
758 {
759 	struct pt_softc *pti = pt_softc[minor(dev)];
760 	struct tty *tp = pti->pt_tty;
761 
762 	return (tp);
763 }
764 
765 int
766 ptyioctl(dev_t dev, u_long cmd, caddr_t data, int flag, struct proc *p)
767 {
768 	struct pt_softc *pti = pt_softc[minor(dev)];
769 	struct tty *tp = pti->pt_tty;
770 	u_char *cc = tp->t_cc;
771 	int stop, error;
772 
773 	/*
774 	 * IF CONTROLLER STTY THEN MUST FLUSH TO PREVENT A HANG.
775 	 * ttywflush(tp) will hang if there are characters in the outq.
776 	 */
777 	if (cmd == TIOCEXT) {
778 		/*
779 		 * When the EXTPROC bit is being toggled, we need
780 		 * to send an TIOCPKT_IOCTL if the packet driver
781 		 * is turned on.
782 		 */
783 		if (*(int *)data) {
784 			if (pti->pt_flags & PF_PKT) {
785 				pti->pt_send |= TIOCPKT_IOCTL;
786 				ptcwakeup(tp, FREAD);
787 			}
788 			tp->t_lflag |= EXTPROC;
789 		} else {
790 			if ((tp->t_lflag & EXTPROC) &&
791 			    (pti->pt_flags & PF_PKT)) {
792 				pti->pt_send |= TIOCPKT_IOCTL;
793 				ptcwakeup(tp, FREAD);
794 			}
795 			tp->t_lflag &= ~EXTPROC;
796 		}
797 		return(0);
798 	} else if (cdevsw[major(dev)].d_open == ptcopen)
799 		switch (cmd) {
800 
801 		case TIOCGPGRP:
802 			/*
803 			 * We avoid calling ttioctl on the controller since,
804 			 * in that case, tp must be the controlling terminal.
805 			 */
806 			*(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : 0;
807 			return (0);
808 
809 		case TIOCPKT:
810 			if (*(int *)data) {
811 				if (pti->pt_flags & PF_UCNTL)
812 					return (EINVAL);
813 				pti->pt_flags |= PF_PKT;
814 			} else
815 				pti->pt_flags &= ~PF_PKT;
816 			return (0);
817 
818 		case TIOCUCNTL:
819 			if (*(int *)data) {
820 				if (pti->pt_flags & PF_PKT)
821 					return (EINVAL);
822 				pti->pt_flags |= PF_UCNTL;
823 			} else
824 				pti->pt_flags &= ~PF_UCNTL;
825 			return (0);
826 
827 		case TIOCREMOTE:
828 			if (*(int *)data)
829 				pti->pt_flags |= PF_REMOTE;
830 			else
831 				pti->pt_flags &= ~PF_REMOTE;
832 			ttyflush(tp, FREAD|FWRITE);
833 			return (0);
834 
835 		case TIOCSETD:
836 		case TIOCSETA:
837 		case TIOCSETAW:
838 		case TIOCSETAF:
839 			ndflush(&tp->t_outq, tp->t_outq.c_cc);
840 			break;
841 
842 		case TIOCSIG:
843 			if (*(unsigned int *)data >= NSIG ||
844 			    *(unsigned int *)data == 0)
845 				return(EINVAL);
846 			if ((tp->t_lflag & NOFLSH) == 0)
847 				ttyflush(tp, FREAD|FWRITE);
848 			pgsignal(tp->t_pgrp, *(unsigned int *)data, 1);
849 			if ((*(unsigned int *)data == SIGINFO) &&
850 			    ((tp->t_lflag & NOKERNINFO) == 0))
851 				ttyinfo(tp);
852 			return (0);
853 
854 		case FIONREAD:
855 			/*
856 			 * FIONREAD on the master side must return the amount
857 			 * in the output queue rather than the input.
858 			 */
859 			*(int *)data = tp->t_outq.c_cc;
860 			return (0);
861 		}
862 	error = (*linesw[tp->t_line].l_ioctl)(tp, cmd, data, flag, p);
863 	if (error < 0)
864 		 error = ttioctl(tp, cmd, data, flag, p);
865 	if (error < 0) {
866 		/*
867 		 * Translate TIOCSBRK/TIOCCBRK to user mode ioctls to
868 		 * let the master interpret BREAK conditions.
869 		 */
870 		switch (cmd) {
871 		case TIOCSBRK:
872 			cmd = UIOCCMD(TIOCUCNTL_SBRK);
873 			break;
874 		case TIOCCBRK:
875 			cmd = UIOCCMD(TIOCUCNTL_CBRK);
876 			break;
877 		default:
878 			break;
879 		}
880 		if (pti->pt_flags & PF_UCNTL &&
881 		    (cmd & ~0xff) == UIOCCMD(0)) {
882 			if (cmd & 0xff) {
883 				pti->pt_ucntl = (u_char)cmd;
884 				ptcwakeup(tp, FREAD);
885 			}
886 			return (0);
887 		}
888 		error = ENOTTY;
889 	}
890 	/*
891 	 * If external processing and packet mode send ioctl packet.
892 	 */
893 	if ((tp->t_lflag & EXTPROC) && (pti->pt_flags & PF_PKT)) {
894 		switch (cmd) {
895 		case TIOCSETA:
896 		case TIOCSETAW:
897 		case TIOCSETAF:
898 			pti->pt_send |= TIOCPKT_IOCTL;
899 			ptcwakeup(tp, FREAD);
900 		default:
901 			break;
902 		}
903 	}
904 	stop = (tp->t_iflag & IXON) && CCEQ(cc[VSTOP], CTRL('s')) &&
905 	    CCEQ(cc[VSTART], CTRL('q'));
906 	if (pti->pt_flags & PF_NOSTOP) {
907 		if (stop) {
908 			pti->pt_send &= ~TIOCPKT_NOSTOP;
909 			pti->pt_send |= TIOCPKT_DOSTOP;
910 			pti->pt_flags &= ~PF_NOSTOP;
911 			ptcwakeup(tp, FREAD);
912 		}
913 	} else {
914 		if (!stop) {
915 			pti->pt_send &= ~TIOCPKT_DOSTOP;
916 			pti->pt_send |= TIOCPKT_NOSTOP;
917 			pti->pt_flags |= PF_NOSTOP;
918 			ptcwakeup(tp, FREAD);
919 		}
920 	}
921 	return (error);
922 }
923 
924 /*
925  * Return pty-related information.
926  */
927 int
928 sysctl_pty(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
929     size_t newlen)
930 {
931 	if (namelen != 1)
932 		return (ENOTDIR);
933 
934 	switch (name[0]) {
935 	default:
936 		return (EOPNOTSUPP);
937 	}
938 	/* NOTREACHED */
939 }
940 
941 /*
942  * Check if a pty is free to use.
943  */
944 static int
945 pty_isfree_locked(int minor)
946 {
947 	struct pt_softc *pt = pt_softc[minor];
948 
949 	return (pt == NULL || pt->pt_tty == NULL ||
950 	    pt->pt_tty->t_oproc == NULL);
951 }
952 
953 static int
954 pty_isfree(int minor)
955 {
956 	int isfree;
957 
958 	rw_enter_read(&pt_softc_lock);
959 	isfree = pty_isfree_locked(minor);
960 	rw_exit_read(&pt_softc_lock);
961 	return(isfree);
962 }
963 
964 dev_t
965 pty_getfree(void)
966 {
967 	int i;
968 
969 	rw_enter_read(&pt_softc_lock);
970 	for (i = 0; i < npty; i++) {
971 		if (pty_isfree_locked(i))
972 			break;
973 	}
974 	rw_exit_read(&pt_softc_lock);
975 	return (makedev(pts_major, i));
976 }
977 
978 /*
979  * Hacked up version of vn_open. We _only_ handle ptys and only open
980  * them with FREAD|FWRITE and never deal with creat or stuff like that.
981  *
982  * We need it because we have to fake up root credentials to open the pty.
983  */
984 static int
985 ptm_vn_open(struct nameidata *ndp)
986 {
987 	struct proc *p = ndp->ni_cnd.cn_proc;
988 	struct ucred *cred;
989 	struct vattr vattr;
990 	struct vnode *vp;
991 	int error;
992 
993 	if ((error = namei(ndp)) != 0)
994 		return (error);
995 	vp = ndp->ni_vp;
996 	if (vp->v_type != VCHR) {
997 		error = EINVAL;
998 		goto bad;
999 	}
1000 
1001 	/*
1002 	 * Get us a fresh cred with root privileges.
1003 	 */
1004 	cred = crget();
1005 	error = VOP_OPEN(vp, FREAD|FWRITE, cred, p);
1006 	if (!error) {
1007 		/* update atime/mtime */
1008 		VATTR_NULL(&vattr);
1009 		getnanotime(&vattr.va_atime);
1010 		vattr.va_mtime = vattr.va_atime;
1011 		vattr.va_vaflags |= VA_UTIMES_NULL;
1012 		(void)VOP_SETATTR(vp, &vattr, p->p_ucred, p);
1013 	}
1014 	crfree(cred);
1015 
1016 	if (error)
1017 		goto bad;
1018 
1019 	vp->v_writecount++;
1020 
1021 	return (0);
1022 bad:
1023 	vput(vp);
1024 	return (error);
1025 }
1026 
1027 void
1028 ptmattach(int n)
1029 {
1030 	/* find the major and minor of the pty devices */
1031 	int i;
1032 
1033 	for (i = 0; i < nchrdev; i++)
1034 		if (cdevsw[i].d_open == ptsopen)
1035 			break;
1036 
1037 	if (i == nchrdev)
1038 		panic("ptmattach: Can't find pty slave in cdevsw");
1039 
1040 	pts_major = i;
1041 }
1042 
1043 int
1044 ptmopen(dev_t dev, int flag, int mode, struct proc *p)
1045 {
1046 	return(0);
1047 }
1048 
1049 
1050 int
1051 ptmclose(dev_t dev, int flag, int mode, struct proc *p)
1052 {
1053 	return (0);
1054 }
1055 
1056 int
1057 ptmioctl(dev_t dev, u_long cmd, caddr_t data, int flag, struct proc *p)
1058 {
1059 	dev_t newdev, error;
1060 	struct pt_softc * pti;
1061 	struct nameidata cnd, snd;
1062 	struct filedesc *fdp = p->p_fd;
1063 	struct file *cfp = NULL, *sfp = NULL;
1064 	int cindx, sindx;
1065 	uid_t uid;
1066 	gid_t gid;
1067 	struct vattr vattr;
1068 	struct ucred *cred;
1069 	struct ptmget *ptm = (struct ptmget *)data;
1070 
1071 	switch (cmd) {
1072 	case PTMGET:
1073 		fdplock(fdp);
1074 		/* Grab two filedescriptors. */
1075 		if ((error = falloc(p, &cfp, &cindx)) != 0) {
1076 			fdpunlock(fdp);
1077 			break;
1078 		}
1079 		if ((error = falloc(p, &sfp, &sindx)) != 0) {
1080 			fdremove(fdp, cindx);
1081 			closef(cfp, p);
1082 			fdpunlock(fdp);
1083 			break;
1084 		}
1085 
1086 retry:
1087 		/* Find and open a free master pty. */
1088 		newdev = pty_getfree();
1089 		if ((error = check_pty(newdev)))
1090 			goto bad;
1091 		pti = pt_softc[minor(newdev)];
1092 		NDINIT(&cnd, LOOKUP, NOFOLLOW|LOCKLEAF, UIO_SYSSPACE,
1093 		    pti->pty_pn, p);
1094 		cnd.ni_pledge = PLEDGE_RPATH | PLEDGE_WPATH;
1095 		if ((error = ptm_vn_open(&cnd)) != 0) {
1096 			/*
1097 			 * Check if the master open failed because we lost
1098 			 * the race to grab it.
1099 			 */
1100 			if (error == EIO && !pty_isfree(minor(newdev)))
1101 				goto retry;
1102 			goto bad;
1103 		}
1104 		cfp->f_flag = FREAD|FWRITE;
1105 		cfp->f_type = DTYPE_VNODE;
1106 		cfp->f_ops = &vnops;
1107 		cfp->f_data = (caddr_t) cnd.ni_vp;
1108 		VOP_UNLOCK(cnd.ni_vp);
1109 
1110 		/*
1111 		 * Open the slave.
1112 		 * namei -> setattr -> unlock -> revoke -> vrele ->
1113 		 * namei -> open -> unlock
1114 		 * Three stage rocket:
1115 		 * 1. Change the owner and permissions on the slave.
1116 		 * 2. Revoke all the users of the slave.
1117 		 * 3. open the slave.
1118 		 */
1119 		NDINIT(&snd, LOOKUP, NOFOLLOW|LOCKLEAF, UIO_SYSSPACE,
1120 		    pti->pty_sn, p);
1121 		snd.ni_pledge = PLEDGE_RPATH | PLEDGE_WPATH;
1122 		snd.ni_unveil = UNVEIL_READ | UNVEIL_WRITE;
1123 		if ((error = namei(&snd)) != 0)
1124 			goto bad;
1125 		if ((snd.ni_vp->v_mount->mnt_flag & MNT_RDONLY) == 0) {
1126 			gid = tty_gid;
1127 			/* get real uid */
1128 			uid = p->p_ucred->cr_ruid;
1129 
1130 			VATTR_NULL(&vattr);
1131 			vattr.va_uid = uid;
1132 			vattr.va_gid = gid;
1133 			vattr.va_mode = (S_IRUSR|S_IWUSR|S_IWGRP) & ALLPERMS;
1134 			/* Get a fake cred to pretend we're root. */
1135 			cred = crget();
1136 			error = VOP_SETATTR(snd.ni_vp, &vattr, cred, p);
1137 			crfree(cred);
1138 			if (error) {
1139 				vput(snd.ni_vp);
1140 				goto bad;
1141 			}
1142 		}
1143 		VOP_UNLOCK(snd.ni_vp);
1144 		if (snd.ni_vp->v_usecount > 1 ||
1145 		    (snd.ni_vp->v_flag & (VALIASED)))
1146 			VOP_REVOKE(snd.ni_vp, REVOKEALL);
1147 
1148 		/*
1149 		 * The vnode is useless after the revoke, we need to
1150 		 * namei again.
1151 		 */
1152 		vrele(snd.ni_vp);
1153 
1154 		NDINIT(&snd, LOOKUP, NOFOLLOW|LOCKLEAF, UIO_SYSSPACE,
1155 		    pti->pty_sn, p);
1156 		snd.ni_pledge = PLEDGE_RPATH | PLEDGE_WPATH;
1157 		snd.ni_unveil= UNVEIL_READ | UNVEIL_WRITE;
1158 		/* now open it */
1159 		if ((error = ptm_vn_open(&snd)) != 0)
1160 			goto bad;
1161 		sfp->f_flag = FREAD|FWRITE;
1162 		sfp->f_type = DTYPE_VNODE;
1163 		sfp->f_ops = &vnops;
1164 		sfp->f_data = (caddr_t) snd.ni_vp;
1165 		VOP_UNLOCK(snd.ni_vp);
1166 
1167 		/* now, put the indexen and names into struct ptmget */
1168 		ptm->cfd = cindx;
1169 		ptm->sfd = sindx;
1170 		memcpy(ptm->cn, pti->pty_pn, sizeof(pti->pty_pn));
1171 		memcpy(ptm->sn, pti->pty_sn, sizeof(pti->pty_sn));
1172 
1173 		/* insert files now that we've passed all errors */
1174 		fdinsert(fdp, cindx, 0, cfp);
1175 		fdinsert(fdp, sindx, 0, sfp);
1176 		fdpunlock(fdp);
1177 		FRELE(cfp, p);
1178 		FRELE(sfp, p);
1179 		break;
1180 	default:
1181 		error = EINVAL;
1182 		break;
1183 	}
1184 	return (error);
1185 bad:
1186 	fdremove(fdp, cindx);
1187 	closef(cfp, p);
1188 	fdremove(fdp, sindx);
1189 	closef(sfp, p);
1190 	fdpunlock(fdp);
1191 	return (error);
1192 }
1193