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