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