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