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