xref: /netbsd-src/sys/kern/tty_pty.c (revision de1dfb1250df962f1ff3a011772cf58e605aed11)
1 /*	$NetBSD: tty_pty.c,v 1.80 2004/06/18 15:02:53 christos Exp $	*/
2 
3 /*
4  * Copyright (c) 1982, 1986, 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	@(#)tty_pty.c	8.4 (Berkeley) 2/20/95
32  */
33 
34 /*
35  * Pseudo-teletype Driver
36  * (Actually two drivers, requiring two entries in 'cdevsw')
37  * Additional multiplexor driver /dev/ptm{,x}
38  */
39 
40 #include <sys/cdefs.h>
41 __KERNEL_RCSID(0, "$NetBSD: tty_pty.c,v 1.80 2004/06/18 15:02:53 christos Exp $");
42 
43 #include "opt_compat_sunos.h"
44 #include "opt_ptm.h"
45 
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/ioctl.h>
49 #include <sys/proc.h>
50 #include <sys/tty.h>
51 #include <sys/stat.h>
52 #include <sys/file.h>
53 #include <sys/uio.h>
54 #include <sys/kernel.h>
55 #include <sys/vnode.h>
56 #include <sys/namei.h>
57 #include <sys/signalvar.h>
58 #include <sys/uio.h>
59 #include <sys/filedesc.h>
60 #include <sys/conf.h>
61 #include <sys/poll.h>
62 #include <sys/malloc.h>
63 
64 #define	DEFAULT_NPTYS		16	/* default number of initial ptys */
65 #define DEFAULT_MAXPTYS		992	/* default maximum number of ptys */
66 
67 #ifdef DEBUG_PTM
68 #define DPRINTF(a) uprintf a
69 #else
70 #define DPRINTF(a)
71 #endif
72 
73 /* Macros to clear/set/test flags. */
74 #define	SET(t, f)	(t) |= (f)
75 #define	CLR(t, f)	(t) &= ~((unsigned)(f))
76 #define	ISSET(t, f)	((t) & (f))
77 
78 #define BUFSIZ 100		/* Chunk size iomoved to/from user */
79 
80 /*
81  * pts == /dev/tty[pqrs]?
82  * ptc == /dev/pty[pqrs]?
83  */
84 
85 #define TTY_TEMPLATE	"/dev/XtyXX"
86 #define TTY_NAMESIZE	sizeof(TTY_TEMPLATE)
87 /* XXX this needs to come from somewhere sane, and work with MAKEDEV */
88 #define TTY_LETTERS	"pqrstuvwxyzPQRST"
89 #define TTY_OLD_SUFFIX  "0123456789abcdef"
90 #define TTY_NEW_SUFFIX  "ghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
91 
92 struct	pt_softc {
93 	struct	tty *pt_tty;
94 	int	pt_flags;
95 	struct	selinfo pt_selr, pt_selw;
96 	u_char	pt_send;
97 	u_char	pt_ucntl;
98 };
99 
100 static struct pt_softc **pt_softc = NULL;	/* pty array */
101 static int npty = 0;			/* for pstat -t */
102 static int maxptys = DEFAULT_MAXPTYS;	/* maximum number of ptys (sysctable) */
103 static struct simplelock pt_softc_mutex = SIMPLELOCK_INITIALIZER;
104 
105 #define	PF_PKT		0x08		/* packet mode */
106 #define	PF_STOPPED	0x10		/* user told stopped */
107 #define	PF_REMOTE	0x20		/* remote and flow controlled input */
108 #define	PF_NOSTOP	0x40
109 #define PF_UCNTL	0x80		/* user control mode */
110 
111 void	ptyattach(int);
112 void	ptcwakeup(struct tty *, int);
113 void	ptsstart(struct tty *);
114 int	pty_maxptys(int, int);
115 
116 static struct pt_softc **ptyarralloc(int);
117 static int check_pty(int);
118 
119 #ifndef NO_DEV_PTM
120 
121 static int pts_major;
122 
123 static dev_t pty_getfree(void);
124 static char *pty_makename(char *, dev_t, char);
125 static int pty_grant_slave(struct proc *, dev_t);
126 static int pty_alloc_master(struct proc *, int *, dev_t *);
127 static int pty_alloc_slave(struct proc *, int *, dev_t);
128 static void pty_fill_ptmget(dev_t, int, int, void *);
129 
130 void ptmattach(int);
131 
132 dev_type_open(ptmopen);
133 dev_type_close(ptmclose);
134 dev_type_ioctl(ptmioctl);
135 
136 const struct cdevsw ptm_cdevsw = {
137 	ptmopen, ptmclose, noread, nowrite, ptmioctl,
138 	nullstop, notty, nopoll, nommap, nokqfilter, D_TTY
139 };
140 #else
141 const struct cdevsw ptm_cdevsw = {
142 	noopen, noclose, noread, nowrite, noioctl,
143 	nostop, notty, nopoll, nommap, nokqfilter, D_TTY
144 };
145 #endif
146 
147 dev_type_open(ptcopen);
148 dev_type_close(ptcclose);
149 dev_type_read(ptcread);
150 dev_type_write(ptcwrite);
151 dev_type_poll(ptcpoll);
152 dev_type_kqfilter(ptckqfilter);
153 
154 dev_type_open(ptsopen);
155 dev_type_close(ptsclose);
156 dev_type_read(ptsread);
157 dev_type_write(ptswrite);
158 dev_type_stop(ptsstop);
159 dev_type_poll(ptspoll);
160 
161 dev_type_ioctl(ptyioctl);
162 dev_type_tty(ptytty);
163 
164 const struct cdevsw ptc_cdevsw = {
165 	ptcopen, ptcclose, ptcread, ptcwrite, ptyioctl,
166 	nullstop, ptytty, ptcpoll, nommap, ptckqfilter, D_TTY
167 };
168 
169 const struct cdevsw pts_cdevsw = {
170 	ptsopen, ptsclose, ptsread, ptswrite, ptyioctl,
171 	ptsstop, ptytty, ptspoll, nommap, ttykqfilter, D_TTY
172 };
173 
174 #if defined(pmax)
175 const struct cdevsw ptc_ultrix_cdevsw = {
176 	ptcopen, ptcclose, ptcread, ptcwrite, ptyioctl,
177 	nullstop, ptytty, ptcpoll, nommap, ptckqfilter, D_TTY
178 };
179 
180 const struct cdevsw pts_ultrix_cdevsw = {
181 	ptsopen, ptsclose, ptsread, ptswrite, ptyioctl,
182 	ptsstop, ptytty, ptspoll, nommap, ttykqfilter, D_TTY
183 };
184 #endif /* defined(pmax) */
185 
186 /*
187  * Allocate and zero array of nelem elements.
188  */
189 static struct pt_softc **
190 ptyarralloc(nelem)
191 	int nelem;
192 {
193 	struct pt_softc **pt;
194 	nelem += 10;
195 	pt = malloc(nelem * sizeof *pt, M_DEVBUF, M_WAITOK | M_ZERO);
196 	return pt;
197 }
198 
199 /*
200  * Check if the minor is correct and ensure necessary structures
201  * are properly allocated.
202  */
203 static int
204 check_pty(int ptn)
205 {
206 	struct pt_softc *pti;
207 
208 	if (ptn >= npty) {
209 		struct pt_softc **newpt, **oldpt;
210 		int newnpty;
211 
212 		/* check if the requested pty can be granted */
213 		if (ptn >= maxptys) {
214 	    limit_reached:
215 			tablefull("pty", "increase kern.maxptys");
216 			return (ENXIO);
217 		}
218 
219 		/* Allocate a larger pty array */
220 		for (newnpty = npty; newnpty <= ptn;)
221 			newnpty *= 2;
222 		if (newnpty > maxptys)
223 			newnpty = maxptys;
224 		newpt = ptyarralloc(newnpty);
225 
226 		/*
227 		 * Now grab the pty array mutex - we need to ensure
228 		 * that the pty array is consistent while copying it's
229 		 * content to newly allocated, larger space; we also
230 		 * need to be safe against pty_maxptys().
231 		 */
232 		simple_lock(&pt_softc_mutex);
233 
234 		if (newnpty >= maxptys) {
235 			/* limit cut away beneath us... */
236 			newnpty = maxptys;
237 			if (ptn >= newnpty) {
238 				simple_unlock(&pt_softc_mutex);
239 				free(newpt, M_DEVBUF);
240 				goto limit_reached;
241 			}
242 		}
243 
244 		/*
245 		 * If the pty array was not enlarged while we were waiting
246 		 * for mutex, copy current contents of pt_softc[] to newly
247 		 * allocated array and start using the new bigger array.
248 		 */
249 		if (newnpty > npty) {
250 			memcpy(newpt, pt_softc, npty*sizeof(struct pt_softc *));
251 			oldpt = pt_softc;
252 			pt_softc = newpt;
253 			npty = newnpty;
254 		} else {
255 			/* was enlarged when waited for lock, free new space */
256 			oldpt = newpt;
257 		}
258 
259 		simple_unlock(&pt_softc_mutex);
260 		free(oldpt, M_DEVBUF);
261 	}
262 
263 	/*
264 	 * If the entry is not yet allocated, allocate one. The mutex is
265 	 * needed so that the state of pt_softc[] array is consistant
266 	 * in case it has been lengthened above.
267 	 */
268 	if (!pt_softc[ptn]) {
269 		MALLOC(pti, struct pt_softc *, sizeof(struct pt_softc),
270 			M_DEVBUF, M_WAITOK);
271 		memset(pti, 0, sizeof(struct pt_softc));
272 
273 	 	pti->pt_tty = ttymalloc();
274 
275 		simple_lock(&pt_softc_mutex);
276 
277 		/*
278 		 * Check the entry again - it might have been
279 		 * added while we were waiting for mutex.
280 		 */
281 		if (!pt_softc[ptn]) {
282 			tty_attach(pti->pt_tty);
283 			pt_softc[ptn] = pti;
284 		} else {
285 			ttyfree(pti->pt_tty);
286 			free(pti, M_DEVBUF);
287 		}
288 
289 		simple_unlock(&pt_softc_mutex);
290 	}
291 
292 	return (0);
293 }
294 
295 /*
296  * Set maxpty in thread-safe way. Returns 0 in case of error, otherwise
297  * new value of maxptys.
298  */
299 int
300 pty_maxptys(newmax, set)
301 	int newmax, set;
302 {
303 	if (!set)
304 		return (maxptys);
305 
306 	/*
307 	 * We have to grab the pt_softc lock, so that we would pick correct
308 	 * value of npty (might be modified in check_pty()).
309 	 */
310 	simple_lock(&pt_softc_mutex);
311 
312 	/*
313 	 * The value cannot be set to value lower than the highest pty
314 	 * number ever allocated.
315 	 */
316 	if (newmax >= npty)
317 		maxptys = newmax;
318 	else
319 		newmax = 0;
320 
321 	simple_unlock(&pt_softc_mutex);
322 
323 	return newmax;
324 }
325 
326 /*
327  * Establish n (or default if n is 1) ptys in the system.
328  */
329 void
330 ptyattach(n)
331 	int n;
332 {
333 	/* maybe should allow 0 => none? */
334 	if (n <= 1)
335 		n = DEFAULT_NPTYS;
336 	pt_softc = ptyarralloc(n);
337 	npty = n;
338 #ifndef NO_DEV_PTM
339 	ptmattach(1);
340 #endif
341 }
342 
343 /*ARGSUSED*/
344 int
345 ptsopen(dev, flag, devtype, p)
346 	dev_t dev;
347 	int flag, devtype;
348 	struct proc *p;
349 {
350 	struct pt_softc *pti;
351 	struct tty *tp;
352 	int error;
353 	int ptn = minor(dev);
354 	int s;
355 
356 	if ((error = check_pty(ptn)))
357 		return (error);
358 
359 	pti = pt_softc[ptn];
360 	tp = pti->pt_tty;
361 
362 	if (!ISSET(tp->t_state, TS_ISOPEN)) {
363 		ttychars(tp);		/* Set up default chars */
364 		tp->t_iflag = TTYDEF_IFLAG;
365 		tp->t_oflag = TTYDEF_OFLAG;
366 		tp->t_lflag = TTYDEF_LFLAG;
367 		tp->t_cflag = TTYDEF_CFLAG;
368 		tp->t_ispeed = tp->t_ospeed = TTYDEF_SPEED;
369 		ttsetwater(tp);		/* would be done in xxparam() */
370 	} else if (ISSET(tp->t_state, TS_XCLUDE) && p->p_ucred->cr_uid != 0)
371 		return (EBUSY);
372 	if (tp->t_oproc)			/* Ctrlr still around. */
373 		SET(tp->t_state, TS_CARR_ON);
374 
375 	if (!ISSET(flag, O_NONBLOCK)) {
376 		s = spltty();
377 		TTY_LOCK(tp);
378 		while (!ISSET(tp->t_state, TS_CARR_ON)) {
379 			tp->t_wopen++;
380 			error = ttysleep(tp, &tp->t_rawq, TTIPRI | PCATCH,
381 			    ttopen, 0);
382 			tp->t_wopen--;
383 			if (error) {
384 				TTY_UNLOCK(tp);
385 				splx(s);
386 				return (error);
387 			}
388 		}
389 		TTY_UNLOCK(tp);
390 		splx(s);
391 	}
392 	error = (*tp->t_linesw->l_open)(dev, tp);
393 	ptcwakeup(tp, FREAD|FWRITE);
394 	return (error);
395 }
396 
397 int
398 ptsclose(dev, flag, mode, p)
399 	dev_t dev;
400 	int flag, mode;
401 	struct proc *p;
402 {
403 	struct pt_softc *pti = pt_softc[minor(dev)];
404 	struct tty *tp = pti->pt_tty;
405 	int error;
406 
407 	error = (*tp->t_linesw->l_close)(tp, flag);
408 	error |= ttyclose(tp);
409 	ptcwakeup(tp, FREAD|FWRITE);
410 	return (error);
411 }
412 
413 int
414 ptsread(dev, uio, flag)
415 	dev_t dev;
416 	struct uio *uio;
417 	int flag;
418 {
419 	struct proc *p = curproc;
420 	struct pt_softc *pti = pt_softc[minor(dev)];
421 	struct tty *tp = pti->pt_tty;
422 	int error = 0;
423 	int cc;
424 	int s;
425 
426 again:
427 	if (pti->pt_flags & PF_REMOTE) {
428 		while (isbackground(p, tp)) {
429 			if (sigismasked(p, SIGTTIN) ||
430 			    p->p_pgrp->pg_jobc == 0 ||
431 			    p->p_flag & P_PPWAIT)
432 				return (EIO);
433 			pgsignal(p->p_pgrp, SIGTTIN, 1);
434 			s = spltty();
435 			TTY_LOCK(tp);
436 			error = ttysleep(tp, (caddr_t)&lbolt,
437 					 TTIPRI | PCATCH | PNORELOCK, ttybg, 0);
438 			splx(s);
439 			if (error)
440 				return (error);
441 		}
442 		s = spltty();
443 		TTY_LOCK(tp);
444 		if (tp->t_canq.c_cc == 0) {
445 			if (flag & IO_NDELAY) {
446 				TTY_UNLOCK(tp);
447 				splx(s);
448 				return (EWOULDBLOCK);
449 			}
450 			error = ttysleep(tp, (caddr_t)&tp->t_canq,
451 					 TTIPRI | PCATCH | PNORELOCK, ttyin, 0);
452 			if (error)
453 				return (error);
454 			goto again;
455 		}
456 		while(error == 0 && tp->t_canq.c_cc > 1 && uio->uio_resid > 0) {
457 			TTY_UNLOCK(tp);
458 			splx(s);
459 			error = ureadc(getc(&tp->t_canq), uio);
460 			s = spltty();
461 			TTY_LOCK(tp);
462 			/* Re-check terminal state here? */
463 		}
464 		if (tp->t_canq.c_cc == 1)
465 			(void) getc(&tp->t_canq);
466 		cc = tp->t_canq.c_cc;
467 		TTY_UNLOCK(tp);
468 		splx(s);
469 		if (cc)
470 			return (error);
471 	} else
472 		if (tp->t_oproc)
473 			error = (*tp->t_linesw->l_read)(tp, uio, flag);
474 	ptcwakeup(tp, FWRITE);
475 	return (error);
476 }
477 
478 /*
479  * Write to pseudo-tty.
480  * Wakeups of controlling tty will happen
481  * indirectly, when tty driver calls ptsstart.
482  */
483 int
484 ptswrite(dev, uio, flag)
485 	dev_t dev;
486 	struct uio *uio;
487 	int flag;
488 {
489 	struct pt_softc *pti = pt_softc[minor(dev)];
490 	struct tty *tp = pti->pt_tty;
491 
492 	if (tp->t_oproc == 0)
493 		return (EIO);
494 	return ((*tp->t_linesw->l_write)(tp, uio, flag));
495 }
496 
497 /*
498  * Poll pseudo-tty.
499  */
500 int
501 ptspoll(dev, events, p)
502 	dev_t dev;
503 	int events;
504 	struct proc *p;
505 {
506 	struct pt_softc *pti = pt_softc[minor(dev)];
507 	struct tty *tp = pti->pt_tty;
508 
509 	if (tp->t_oproc == 0)
510 		return (EIO);
511 
512 	return ((*tp->t_linesw->l_poll)(tp, events, p));
513 }
514 
515 /*
516  * Start output on pseudo-tty.
517  * Wake up process polling or sleeping for input from controlling tty.
518  * Called with tty slock held.
519  */
520 void
521 ptsstart(tp)
522 	struct tty *tp;
523 {
524 	struct pt_softc *pti = pt_softc[minor(tp->t_dev)];
525 
526 	if (ISSET(tp->t_state, TS_TTSTOP))
527 		return;
528 	if (pti->pt_flags & PF_STOPPED) {
529 		pti->pt_flags &= ~PF_STOPPED;
530 		pti->pt_send = TIOCPKT_START;
531 	}
532 
533 	selnotify(&pti->pt_selr, NOTE_SUBMIT);
534 	wakeup((caddr_t)&tp->t_outq.c_cf);
535 }
536 
537 /*
538  * Stop output.
539  * Called with tty slock held.
540  */
541 void
542 ptsstop(tp, flush)
543 	struct tty *tp;
544 	int flush;
545 {
546 	struct pt_softc *pti = pt_softc[minor(tp->t_dev)];
547 
548 	/* note: FLUSHREAD and FLUSHWRITE already ok */
549 	if (flush == 0) {
550 		flush = TIOCPKT_STOP;
551 		pti->pt_flags |= PF_STOPPED;
552 	} else
553 		pti->pt_flags &= ~PF_STOPPED;
554 	pti->pt_send |= flush;
555 
556 	/* change of perspective */
557 	if (flush & FREAD) {
558 		selnotify(&pti->pt_selw, NOTE_SUBMIT);
559 		wakeup((caddr_t)&tp->t_rawq.c_cf);
560 	}
561 	if (flush & FWRITE) {
562 		selnotify(&pti->pt_selr, NOTE_SUBMIT);
563 		wakeup((caddr_t)&tp->t_outq.c_cf);
564 	}
565 }
566 
567 void
568 ptcwakeup(tp, flag)
569 	struct tty *tp;
570 	int flag;
571 {
572 	struct pt_softc *pti = pt_softc[minor(tp->t_dev)];
573 	int s;
574 
575 	s = spltty();
576 	TTY_LOCK(tp);
577 	if (flag & FREAD) {
578 		selnotify(&pti->pt_selr, NOTE_SUBMIT);
579 		wakeup((caddr_t)&tp->t_outq.c_cf);
580 	}
581 	if (flag & FWRITE) {
582 		selnotify(&pti->pt_selw, NOTE_SUBMIT);
583 		wakeup((caddr_t)&tp->t_rawq.c_cf);
584 	}
585 	TTY_UNLOCK(tp);
586 	splx(s);
587 }
588 
589 /*ARGSUSED*/
590 int
591 ptcopen(dev, flag, devtype, p)
592 	dev_t dev;
593 	int flag, devtype;
594 	struct proc *p;
595 {
596 	struct pt_softc *pti;
597 	struct tty *tp;
598 	int error;
599 	int ptn = minor(dev);
600 	int s;
601 
602 	if ((error = check_pty(ptn)))
603 		return (error);
604 
605 	pti = pt_softc[ptn];
606 	tp = pti->pt_tty;
607 
608 	s = spltty();
609 	TTY_LOCK(tp);
610 	if (tp->t_oproc) {
611 		TTY_UNLOCK(tp);
612 		splx(s);
613 		return (EIO);
614 	}
615 	tp->t_oproc = ptsstart;
616 	TTY_UNLOCK(tp);
617 	splx(s);
618 	(void)(*tp->t_linesw->l_modem)(tp, 1);
619 	CLR(tp->t_lflag, EXTPROC);
620 	pti->pt_flags = 0;
621 	pti->pt_send = 0;
622 	pti->pt_ucntl = 0;
623 	return (0);
624 }
625 
626 /*ARGSUSED*/
627 int
628 ptcclose(dev, flag, devtype, p)
629 	dev_t dev;
630 	int flag, devtype;
631 	struct proc *p;
632 {
633 	struct pt_softc *pti = pt_softc[minor(dev)];
634 	struct tty *tp = pti->pt_tty;
635 	int s;
636 
637 	(void)(*tp->t_linesw->l_modem)(tp, 0);
638 	CLR(tp->t_state, TS_CARR_ON);
639 	s = spltty();
640 	TTY_LOCK(tp);
641 	tp->t_oproc = 0;		/* mark closed */
642 	TTY_UNLOCK(tp);
643 	splx(s);
644 	return (0);
645 }
646 
647 int
648 ptcread(dev, uio, flag)
649 	dev_t dev;
650 	struct uio *uio;
651 	int flag;
652 {
653 	struct pt_softc *pti = pt_softc[minor(dev)];
654 	struct tty *tp = pti->pt_tty;
655 	u_char buf[BUFSIZ];
656 	int error = 0, cc;
657 	int s;
658 
659 	/*
660 	 * We want to block until the slave
661 	 * is open, and there's something to read;
662 	 * but if we lost the slave or we're NBIO,
663 	 * then return the appropriate error instead.
664 	 */
665 	s = spltty();
666 	TTY_LOCK(tp);
667 	for (;;) {
668 		if (ISSET(tp->t_state, TS_ISOPEN)) {
669 			if (pti->pt_flags & PF_PKT && pti->pt_send) {
670 				TTY_UNLOCK(tp);
671 				splx(s);
672 				error = ureadc((int)pti->pt_send, uio);
673 				if (error)
674 					return (error);
675 				/*
676 				 * Since we don't have the tty locked, there's
677 				 * a risk of messing up `t_termios'. This is
678 				 * relevant only if the tty got closed and then
679 				 * opened again while we were out uiomoving.
680 				 */
681 				if (pti->pt_send & TIOCPKT_IOCTL) {
682 					cc = min(uio->uio_resid,
683 						sizeof(tp->t_termios));
684 					uiomove((caddr_t) &tp->t_termios,
685 						cc, uio);
686 				}
687 				pti->pt_send = 0;
688 				return (0);
689 			}
690 			if (pti->pt_flags & PF_UCNTL && pti->pt_ucntl) {
691 				TTY_UNLOCK(tp);
692 				splx(s);
693 				error = ureadc((int)pti->pt_ucntl, uio);
694 				if (error)
695 					return (error);
696 				pti->pt_ucntl = 0;
697 				return (0);
698 			}
699 			if (tp->t_outq.c_cc && !ISSET(tp->t_state, TS_TTSTOP))
700 				break;
701 		}
702 		if (!ISSET(tp->t_state, TS_CARR_ON)) {
703 			error = 0;	/* EOF */
704 			goto out;
705 		}
706 		if (flag & IO_NDELAY) {
707 			error = EWOULDBLOCK;
708 			goto out;
709 		}
710 		error = ltsleep((caddr_t)&tp->t_outq.c_cf, TTIPRI | PCATCH,
711 				ttyin, 0, &tp->t_slock);
712 		if (error)
713 			goto out;
714 	}
715 
716 	if (pti->pt_flags & (PF_PKT|PF_UCNTL)) {
717 		TTY_UNLOCK(tp);
718 		splx(s);
719 		error = ureadc(0, uio);
720 		s = spltty();
721 		TTY_LOCK(tp);
722 		if (error == 0 && !ISSET(tp->t_state, TS_ISOPEN))
723 			error = EIO;
724 	}
725 	while (uio->uio_resid > 0 && error == 0) {
726 		cc = q_to_b(&tp->t_outq, buf, min(uio->uio_resid, BUFSIZ));
727 		if (cc <= 0)
728 			break;
729 		TTY_UNLOCK(tp);
730 		splx(s);
731 		error = uiomove(buf, cc, uio);
732 		s = spltty();
733 		TTY_LOCK(tp);
734 		if (error == 0 && !ISSET(tp->t_state, TS_ISOPEN))
735 			error = EIO;
736 	}
737 
738 	if (tp->t_outq.c_cc <= tp->t_lowat) {
739 		if (ISSET(tp->t_state, TS_ASLEEP)) {
740 			CLR(tp->t_state, TS_ASLEEP);
741 			wakeup((caddr_t)&tp->t_outq);
742 		}
743 		selnotify(&tp->t_wsel, NOTE_SUBMIT);
744 	}
745 out:
746 	TTY_UNLOCK(tp);
747 	splx(s);
748 	return (error);
749 }
750 
751 
752 int
753 ptcwrite(dev, uio, flag)
754 	dev_t dev;
755 	struct uio *uio;
756 	int flag;
757 {
758 	struct pt_softc *pti = pt_softc[minor(dev)];
759 	struct tty *tp = pti->pt_tty;
760 	u_char *cp = NULL;
761 	int cc = 0;
762 	u_char locbuf[BUFSIZ];
763 	int cnt = 0;
764 	int error = 0;
765 	int s;
766 
767 again:
768 	s = spltty();
769 	TTY_LOCK(tp);
770 	if (!ISSET(tp->t_state, TS_ISOPEN))
771 		goto block;
772 	if (pti->pt_flags & PF_REMOTE) {
773 		if (tp->t_canq.c_cc)
774 			goto block;
775 		while (uio->uio_resid > 0 && tp->t_canq.c_cc < TTYHOG - 1) {
776 			if (cc == 0) {
777 				cc = min(uio->uio_resid, BUFSIZ);
778 				cc = min(cc, TTYHOG - 1 - tp->t_canq.c_cc);
779 				cp = locbuf;
780 				TTY_UNLOCK(tp);
781 				splx(s);
782 				error = uiomove((caddr_t)cp, cc, uio);
783 				if (error)
784 					return (error);
785 				s = spltty();
786 				TTY_LOCK(tp);
787 				/* check again for safety */
788 				if (!ISSET(tp->t_state, TS_ISOPEN)) {
789 					error = EIO;
790 					goto out;
791 				}
792 			}
793 			if (cc)
794 				(void) b_to_q(cp, cc, &tp->t_canq);
795 			cc = 0;
796 		}
797 		(void) putc(0, &tp->t_canq);
798 		ttwakeup(tp);
799 		wakeup((caddr_t)&tp->t_canq);
800 		error = 0;
801 		goto out;
802 	}
803 	while (uio->uio_resid > 0) {
804 		if (cc == 0) {
805 			cc = min(uio->uio_resid, BUFSIZ);
806 			cp = locbuf;
807 			TTY_UNLOCK(tp);
808 			splx(s);
809 			error = uiomove((caddr_t)cp, cc, uio);
810 			if (error)
811 				return (error);
812 			s = spltty();
813 			TTY_LOCK(tp);
814 			/* check again for safety */
815 			if (!ISSET(tp->t_state, TS_ISOPEN)) {
816 				error = EIO;
817 				goto out;
818 			}
819 		}
820 		while (cc > 0) {
821 			if ((tp->t_rawq.c_cc + tp->t_canq.c_cc) >= TTYHOG - 2 &&
822 			   (tp->t_canq.c_cc > 0 || !ISSET(tp->t_lflag, ICANON))) {
823 				wakeup((caddr_t)&tp->t_rawq);
824 				goto block;
825 			}
826 			/* XXX - should change l_rint to be called with lock
827 			 *	 see also tty.c:ttyinput_wlock()
828 			 */
829 			TTY_UNLOCK(tp);
830 			splx(s);
831 			(*tp->t_linesw->l_rint)(*cp++, tp);
832 			s = spltty();
833 			TTY_LOCK(tp);
834 			cnt++;
835 			cc--;
836 		}
837 		cc = 0;
838 	}
839 	error = 0;
840 	goto out;
841 
842 block:
843 	/*
844 	 * Come here to wait for slave to open, for space
845 	 * in outq, or space in rawq.
846 	 */
847 	if (!ISSET(tp->t_state, TS_CARR_ON)) {
848 		error = EIO;
849 		goto out;
850 	}
851 	if (flag & IO_NDELAY) {
852 		/* adjust for data copied in but not written */
853 		uio->uio_resid += cc;
854 		error = cnt == 0 ? EWOULDBLOCK : 0;
855 		goto out;
856 	}
857 	error = ltsleep((caddr_t)&tp->t_rawq.c_cf, TTOPRI | PCATCH | PNORELOCK,
858 		       ttyout, 0, &tp->t_slock);
859 	splx(s);
860 	if (error) {
861 		/* adjust for data copied in but not written */
862 		uio->uio_resid += cc;
863 		return (error);
864 	}
865 	goto again;
866 
867 out:
868 	TTY_UNLOCK(tp);
869 	splx(s);
870 	return (error);
871 }
872 
873 int
874 ptcpoll(dev, events, p)
875 	dev_t dev;
876 	int events;
877 	struct proc *p;
878 {
879 	struct pt_softc *pti = pt_softc[minor(dev)];
880 	struct tty *tp = pti->pt_tty;
881 	int revents = 0;
882 	int s = splsoftclock();
883 
884 	if (events & (POLLIN | POLLRDNORM))
885 		if (ISSET(tp->t_state, TS_ISOPEN) &&
886 		    ((tp->t_outq.c_cc > 0 && !ISSET(tp->t_state, TS_TTSTOP)) ||
887 		     ((pti->pt_flags & PF_PKT) && pti->pt_send) ||
888 		     ((pti->pt_flags & PF_UCNTL) && pti->pt_ucntl)))
889 			revents |= events & (POLLIN | POLLRDNORM);
890 
891 	if (events & (POLLOUT | POLLWRNORM))
892 		if (ISSET(tp->t_state, TS_ISOPEN) &&
893 		    ((pti->pt_flags & PF_REMOTE) ?
894 		     (tp->t_canq.c_cc == 0) :
895 		     ((tp->t_rawq.c_cc + tp->t_canq.c_cc < TTYHOG-2) ||
896 		      (tp->t_canq.c_cc == 0 && ISSET(tp->t_lflag, ICANON)))))
897 			revents |= events & (POLLOUT | POLLWRNORM);
898 
899 	if (events & POLLHUP)
900 		if (!ISSET(tp->t_state, TS_CARR_ON))
901 			revents |= POLLHUP;
902 
903 	if (revents == 0) {
904 		if (events & (POLLIN | POLLHUP | POLLRDNORM))
905 			selrecord(p, &pti->pt_selr);
906 
907 		if (events & (POLLOUT | POLLWRNORM))
908 			selrecord(p, &pti->pt_selw);
909 	}
910 
911 	splx(s);
912 	return (revents);
913 }
914 
915 static void
916 filt_ptcrdetach(struct knote *kn)
917 {
918 	struct pt_softc *pti;
919 	int		s;
920 
921 	pti = kn->kn_hook;
922 	s = spltty();
923 	SLIST_REMOVE(&pti->pt_selr.sel_klist, kn, knote, kn_selnext);
924 	splx(s);
925 }
926 
927 static int
928 filt_ptcread(struct knote *kn, long hint)
929 {
930 	struct pt_softc *pti;
931 	struct tty	*tp;
932 	int canread;
933 
934 	pti = kn->kn_hook;
935 	tp = pti->pt_tty;
936 
937 	canread = (ISSET(tp->t_state, TS_ISOPEN) &&
938 		    ((tp->t_outq.c_cc > 0 && !ISSET(tp->t_state, TS_TTSTOP)) ||
939 		     ((pti->pt_flags & PF_PKT) && pti->pt_send) ||
940 		     ((pti->pt_flags & PF_UCNTL) && pti->pt_ucntl)));
941 
942 	if (canread) {
943 		/*
944 		 * c_cc is number of characters after output post-processing;
945 		 * the amount of data actually read(2) depends on
946 		 * setting of input flags for the terminal.
947 		 */
948 		kn->kn_data = tp->t_outq.c_cc;
949 		if (((pti->pt_flags & PF_PKT) && pti->pt_send) ||
950 		    ((pti->pt_flags & PF_UCNTL) && pti->pt_ucntl))
951 			kn->kn_data++;
952 	}
953 
954 	return (canread);
955 }
956 
957 static void
958 filt_ptcwdetach(struct knote *kn)
959 {
960 	struct pt_softc *pti;
961 	int		s;
962 
963 	pti = kn->kn_hook;
964 	s = spltty();
965 	SLIST_REMOVE(&pti->pt_selw.sel_klist, kn, knote, kn_selnext);
966 	splx(s);
967 }
968 
969 static int
970 filt_ptcwrite(struct knote *kn, long hint)
971 {
972 	struct pt_softc *pti;
973 	struct tty	*tp;
974 	int canwrite;
975 	int nwrite;
976 
977 	pti = kn->kn_hook;
978 	tp = pti->pt_tty;
979 
980 	canwrite = (ISSET(tp->t_state, TS_ISOPEN) &&
981 		    ((pti->pt_flags & PF_REMOTE) ?
982 		     (tp->t_canq.c_cc == 0) :
983 		     ((tp->t_rawq.c_cc + tp->t_canq.c_cc < TTYHOG-2) ||
984 		      (tp->t_canq.c_cc == 0 && ISSET(tp->t_lflag, ICANON)))));
985 
986 	if (canwrite) {
987 		if (pti->pt_flags & PF_REMOTE)
988 			nwrite = tp->t_canq.c_cn;
989 		else {
990 			/* this is guaranteed to be > 0 due to above check */
991 			nwrite = tp->t_canq.c_cn
992 				- (tp->t_rawq.c_cc + tp->t_canq.c_cc);
993 		}
994 		kn->kn_data = nwrite;
995 	}
996 
997 	return (canwrite);
998 }
999 
1000 static const struct filterops ptcread_filtops =
1001 	{ 1, NULL, filt_ptcrdetach, filt_ptcread };
1002 static const struct filterops ptcwrite_filtops =
1003 	{ 1, NULL, filt_ptcwdetach, filt_ptcwrite };
1004 
1005 int
1006 ptckqfilter(dev_t dev, struct knote *kn)
1007 {
1008 	struct pt_softc *pti = pt_softc[minor(dev)];
1009 	struct klist	*klist;
1010 	int		s;
1011 
1012 	switch (kn->kn_filter) {
1013 	case EVFILT_READ:
1014 		klist = &pti->pt_selr.sel_klist;
1015 		kn->kn_fop = &ptcread_filtops;
1016 		break;
1017 	case EVFILT_WRITE:
1018 		klist = &pti->pt_selw.sel_klist;
1019 		kn->kn_fop = &ptcwrite_filtops;
1020 		break;
1021 	default:
1022 		return (1);
1023 	}
1024 
1025 	kn->kn_hook = pti;
1026 
1027 	s = spltty();
1028 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
1029 	splx(s);
1030 
1031 	return (0);
1032 }
1033 
1034 struct tty *
1035 ptytty(dev)
1036 	dev_t dev;
1037 {
1038 	struct pt_softc *pti = pt_softc[minor(dev)];
1039 	struct tty *tp = pti->pt_tty;
1040 
1041 	return (tp);
1042 }
1043 
1044 /*ARGSUSED*/
1045 int
1046 ptyioctl(dev, cmd, data, flag, p)
1047 	dev_t dev;
1048 	u_long cmd;
1049 	caddr_t data;
1050 	int flag;
1051 	struct proc *p;
1052 {
1053 	struct pt_softc *pti = pt_softc[minor(dev)];
1054 	struct tty *tp = pti->pt_tty;
1055 	const struct cdevsw *cdev;
1056 	u_char *cc = tp->t_cc;
1057 	int stop, error, sig;
1058 	int s;
1059 
1060 	cdev = cdevsw_lookup(dev);
1061 	/*
1062 	 * IF CONTROLLER STTY THEN MUST FLUSH TO PREVENT A HANG.
1063 	 * ttywflush(tp) will hang if there are characters in the outq.
1064 	 */
1065 	if (cmd == TIOCEXT) {
1066 		/*
1067 		 * When the EXTPROC bit is being toggled, we need
1068 		 * to send an TIOCPKT_IOCTL if the packet driver
1069 		 * is turned on.
1070 		 */
1071 		if (*(int *)data) {
1072 			if (pti->pt_flags & PF_PKT) {
1073 				pti->pt_send |= TIOCPKT_IOCTL;
1074 				ptcwakeup(tp, FREAD);
1075 			}
1076 			SET(tp->t_lflag, EXTPROC);
1077 		} else {
1078 			if (ISSET(tp->t_lflag, EXTPROC) &&
1079 			    (pti->pt_flags & PF_PKT)) {
1080 				pti->pt_send |= TIOCPKT_IOCTL;
1081 				ptcwakeup(tp, FREAD);
1082 			}
1083 			CLR(tp->t_lflag, EXTPROC);
1084 		}
1085 		return(0);
1086 	}
1087 
1088 	if (cdev != NULL && cdev->d_open == ptcopen)
1089 		switch (cmd) {
1090 #ifndef NO_DEV_PTM
1091 		case TIOCGRANTPT:
1092 			return pty_grant_slave(p, dev);
1093 
1094 		case TIOCPTSNAME:
1095 			pty_fill_ptmget(dev, -1, -1, data);
1096 			return 0;
1097 #endif
1098 
1099 		case TIOCGPGRP:
1100 			/*
1101 			 * We avoid calling ttioctl on the controller since,
1102 			 * in that case, tp must be the controlling terminal.
1103 			 */
1104 			*(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : 0;
1105 			return (0);
1106 
1107 		case TIOCPKT:
1108 			if (*(int *)data) {
1109 				if (pti->pt_flags & PF_UCNTL)
1110 					return (EINVAL);
1111 				pti->pt_flags |= PF_PKT;
1112 			} else
1113 				pti->pt_flags &= ~PF_PKT;
1114 			return (0);
1115 
1116 		case TIOCUCNTL:
1117 			if (*(int *)data) {
1118 				if (pti->pt_flags & PF_PKT)
1119 					return (EINVAL);
1120 				pti->pt_flags |= PF_UCNTL;
1121 			} else
1122 				pti->pt_flags &= ~PF_UCNTL;
1123 			return (0);
1124 
1125 		case TIOCREMOTE:
1126 			if (*(int *)data)
1127 				pti->pt_flags |= PF_REMOTE;
1128 			else
1129 				pti->pt_flags &= ~PF_REMOTE;
1130 			s = spltty();
1131 			TTY_LOCK(tp);
1132 			ttyflush(tp, FREAD|FWRITE);
1133 			TTY_UNLOCK(tp);
1134 			splx(s);
1135 			return (0);
1136 
1137 #ifdef COMPAT_OLDTTY
1138 		case TIOCSETP:
1139 		case TIOCSETN:
1140 #endif
1141 		case TIOCSETD:
1142 		case TIOCSETA:
1143 		case TIOCSETAW:
1144 		case TIOCSETAF:
1145 			TTY_LOCK(tp);
1146 			ndflush(&tp->t_outq, tp->t_outq.c_cc);
1147 			TTY_UNLOCK(tp);
1148 			break;
1149 
1150 		case TIOCSIG:
1151 			sig = (int)(long)*(caddr_t *)data;
1152 			if (sig <= 0 || sig >= NSIG)
1153 				return (EINVAL);
1154 			TTY_LOCK(tp);
1155 			if (!ISSET(tp->t_lflag, NOFLSH))
1156 				ttyflush(tp, FREAD|FWRITE);
1157 			if ((sig == SIGINFO) &&
1158 			    (!ISSET(tp->t_lflag, NOKERNINFO)))
1159 				ttyinfo(tp);
1160 			TTY_UNLOCK(tp);
1161 			pgsignal(tp->t_pgrp, sig, 1);
1162 			return(0);
1163 		}
1164 
1165 	error = (*tp->t_linesw->l_ioctl)(tp, cmd, data, flag, p);
1166 	if (error == EPASSTHROUGH)
1167 		 error = ttioctl(tp, cmd, data, flag, p);
1168 	if (error == EPASSTHROUGH) {
1169 		if (pti->pt_flags & PF_UCNTL &&
1170 		    (cmd & ~0xff) == UIOCCMD(0)) {
1171 			if (cmd & 0xff) {
1172 				pti->pt_ucntl = (u_char)cmd;
1173 				ptcwakeup(tp, FREAD);
1174 			}
1175 			return (0);
1176 		}
1177 	}
1178 	/*
1179 	 * If external processing and packet mode send ioctl packet.
1180 	 */
1181 	if (ISSET(tp->t_lflag, EXTPROC) && (pti->pt_flags & PF_PKT)) {
1182 		switch(cmd) {
1183 		case TIOCSETA:
1184 		case TIOCSETAW:
1185 		case TIOCSETAF:
1186 #ifdef COMPAT_OLDTTY
1187 		case TIOCSETP:
1188 		case TIOCSETN:
1189 		case TIOCSETC:
1190 		case TIOCSLTC:
1191 		case TIOCLBIS:
1192 		case TIOCLBIC:
1193 		case TIOCLSET:
1194 #endif
1195 			pti->pt_send |= TIOCPKT_IOCTL;
1196 			ptcwakeup(tp, FREAD);
1197 		default:
1198 			break;
1199 		}
1200 	}
1201 	stop = ISSET(tp->t_iflag, IXON) && CCEQ(cc[VSTOP], CTRL('s'))
1202 		&& CCEQ(cc[VSTART], CTRL('q'));
1203 	if (pti->pt_flags & PF_NOSTOP) {
1204 		if (stop) {
1205 			pti->pt_send &= ~TIOCPKT_NOSTOP;
1206 			pti->pt_send |= TIOCPKT_DOSTOP;
1207 			pti->pt_flags &= ~PF_NOSTOP;
1208 			ptcwakeup(tp, FREAD);
1209 		}
1210 	} else {
1211 		if (!stop) {
1212 			pti->pt_send &= ~TIOCPKT_DOSTOP;
1213 			pti->pt_send |= TIOCPKT_NOSTOP;
1214 			pti->pt_flags |= PF_NOSTOP;
1215 			ptcwakeup(tp, FREAD);
1216 		}
1217 	}
1218 	return (error);
1219 }
1220 
1221 #ifndef NO_DEV_PTM
1222 /*
1223  * Check if a pty is free to use.
1224  */
1225 static __inline int
1226 pty_isfree_locked(int minor)
1227 {
1228 	struct pt_softc *pt = pt_softc[minor];
1229 	return (pt == NULL || pt->pt_tty == NULL ||
1230 	    pt->pt_tty->t_oproc == NULL);
1231 }
1232 
1233 static int
1234 pty_isfree(int minor)
1235 {
1236 	int isfree;
1237 
1238 	simple_lock(&pt_softc_mutex);
1239 	isfree = pty_isfree_locked(minor);
1240 	simple_unlock(&pt_softc_mutex);
1241 	return(isfree);
1242 }
1243 
1244 static char *
1245 pty_makename(char *buf, dev_t dev, char c)
1246 {
1247 	size_t nt;
1248 	dev_t minor = minor(dev);
1249 
1250 	(void)memcpy(buf, TTY_TEMPLATE, TTY_NAMESIZE);
1251 
1252 	buf[5] = c;
1253 
1254 	if (minor < 256) {
1255 		nt = sizeof(TTY_OLD_SUFFIX) - 1;
1256 		buf[8] = TTY_LETTERS[minor / nt];
1257 		buf[9] = TTY_OLD_SUFFIX[minor % nt];
1258 	} else {
1259 		minor -= 256;
1260 		nt = sizeof(TTY_NEW_SUFFIX) - sizeof(TTY_OLD_SUFFIX);
1261 		buf[8] = TTY_LETTERS[minor / nt];
1262 		buf[9] = TTY_NEW_SUFFIX[minor % nt];
1263 	}
1264 	return buf;
1265 }
1266 
1267 static dev_t
1268 pty_getfree(void)
1269 {
1270 	int i;
1271 
1272 	simple_lock(&pt_softc_mutex);
1273 	for (i = 0; i < npty; i++) {
1274 		if (pty_isfree_locked(i))
1275 			break;
1276 	}
1277 	simple_unlock(&pt_softc_mutex);
1278 	return (makedev(pts_major, i));
1279 }
1280 
1281 /*
1282  * Hacked up version of vn_open. We _only_ handle ptys and only open
1283  * them with FREAD|FWRITE and never deal with creat or stuff like that.
1284  *
1285  * We need it because we have to fake up root credentials to open the pty.
1286  */
1287 static int
1288 ptm_vn_open(struct nameidata *ndp)
1289 {
1290 	struct vnode *vp;
1291 	struct proc *p = ndp->ni_cnd.cn_proc;
1292 	struct ucred *cred;
1293 	int error;
1294 
1295 	if ((error = namei(ndp)) != 0)
1296 		return (error);
1297 	vp = ndp->ni_vp;
1298 	if (vp->v_type != VCHR) {
1299 		error = EINVAL;
1300 		goto bad;
1301 	}
1302 
1303 	/*
1304 	 * Get us a fresh cred with root privileges.
1305 	 */
1306 	cred = crget();
1307 	error = VOP_OPEN(vp, FREAD|FWRITE, cred, p);
1308 	crfree(cred);
1309 
1310 	if (error)
1311 		goto bad;
1312 
1313 	vp->v_writecount++;
1314 
1315 	return (0);
1316 bad:
1317 	vput(vp);
1318 	return (error);
1319 }
1320 
1321 static int
1322 pty_alloc_master(struct proc *p, int *fd, dev_t *dev)
1323 {
1324 	int error;
1325 	struct nameidata nd;
1326 	struct pt_softc *pti;
1327 	struct file *fp;
1328 	int md;
1329 	char name[TTY_NAMESIZE];
1330 
1331 	if ((error = falloc(p, &fp, fd)) != 0) {
1332 		DPRINTF(("falloc %d\n", error));
1333 		return error;
1334 	}
1335 retry:
1336 	/* Find and open a free master pty. */
1337 	*dev = pty_getfree();
1338 	md = minor(*dev);
1339 	if ((error = check_pty(md)) != 0) {
1340 		DPRINTF(("ckeck_pty %d\n", error));
1341 		goto bad;
1342 	}
1343 	pti = pt_softc[md];
1344 	NDINIT(&nd, LOOKUP, NOFOLLOW|LOCKLEAF, UIO_SYSSPACE,
1345 	    pty_makename(name, *dev, 'p'), p);
1346 	if ((error = ptm_vn_open(&nd)) != 0) {
1347 		/*
1348 		 * Check if the master open failed because we lost
1349 		 * the race to grab it.
1350 		 */
1351 		if (error == EIO && !pty_isfree(md))
1352 			goto retry;
1353 		DPRINTF(("ptm_vn_open %d\n", error));
1354 		goto bad;
1355 	}
1356 	fp->f_flag = FREAD|FWRITE;
1357 	fp->f_type = DTYPE_VNODE;
1358 	fp->f_ops = &vnops;
1359 	fp->f_data = nd.ni_vp;
1360 	VOP_UNLOCK(nd.ni_vp, 0);
1361 	FILE_SET_MATURE(fp);
1362 	FILE_UNUSE(fp, p);
1363 	return 0;
1364 bad:
1365 	FILE_UNUSE(fp, p);
1366 	fdremove(p->p_fd, *fd);
1367 	ffree(fp);
1368 	return error;
1369 }
1370 
1371 static int
1372 pty_grant_slave(struct proc *p, dev_t dev)
1373 {
1374 	int error;
1375 	struct nameidata nd;
1376 	char name[TTY_NAMESIZE];
1377 
1378 	/*
1379 	 * Open the slave.
1380 	 * namei -> setattr -> unlock -> revoke -> vrele ->
1381 	 * namei -> open -> unlock
1382 	 * Three stage rocket:
1383 	 * 1. Change the owner and permissions on the slave.
1384 	 * 2. Revoke all the users of the slave.
1385 	 * 3. open the slave.
1386 	 */
1387 	NDINIT(&nd, LOOKUP, NOFOLLOW|LOCKLEAF, UIO_SYSSPACE,
1388 	    pty_makename(name, dev, 't'), p);
1389 	if ((error = namei(&nd)) != 0) {
1390 		DPRINTF(("namei %d\n", error));
1391 		return error;
1392 	}
1393 	if ((nd.ni_vp->v_mount->mnt_flag & MNT_RDONLY) == 0) {
1394 		struct vattr vattr;
1395 		struct ucred *cred;
1396 		gid_t gid = _TTY_GID;
1397 		/* get real uid */
1398 		uid_t uid = p->p_cred->p_ruid;
1399 
1400 		VATTR_NULL(&vattr);
1401 		vattr.va_uid = uid;
1402 		vattr.va_gid = gid;
1403 		vattr.va_mode = (S_IRUSR|S_IWUSR|S_IWGRP) & ALLPERMS;
1404 		/* Get a fake cred to pretend we're root. */
1405 		cred = crget();
1406 		error = VOP_SETATTR(nd.ni_vp, &vattr, cred, p);
1407 		crfree(cred);
1408 		if (error) {
1409 			DPRINTF(("setattr %d\n", error));
1410 			VOP_UNLOCK(nd.ni_vp, 0);
1411 			vrele(nd.ni_vp);
1412 			return error;
1413 		}
1414 	}
1415 	VOP_UNLOCK(nd.ni_vp, 0);
1416 	if (nd.ni_vp->v_usecount > 1 ||
1417 	    (nd.ni_vp->v_flag & (VALIASED | VLAYER)))
1418 		VOP_REVOKE(nd.ni_vp, REVOKEALL);
1419 
1420 	/*
1421 	 * The vnode is useless after the revoke, we need to
1422 	 * namei again.
1423 	 */
1424 	vrele(nd.ni_vp);
1425 	return 0;
1426 }
1427 
1428 static int
1429 pty_alloc_slave(struct proc *p, int *fd, dev_t dev)
1430 {
1431 	int error;
1432 	struct file *fp;
1433 	struct nameidata nd;
1434 	char name[TTY_NAMESIZE];
1435 
1436 	/* Grab a filedescriptor for the slave */
1437 	if ((error = falloc(p, &fp, fd)) != 0) {
1438 		DPRINTF(("falloc %d\n", error));
1439 		return error;
1440 	}
1441 
1442 	NDINIT(&nd, LOOKUP, NOFOLLOW|LOCKLEAF, UIO_SYSSPACE,
1443 	    pty_makename(name, dev, 't'), p);
1444 
1445 	/* now open it */
1446 	if ((error = ptm_vn_open(&nd)) != 0) {
1447 		DPRINTF(("vn_open %d\n", error));
1448 		FILE_UNUSE(fp, p);
1449 		fdremove(p->p_fd, *fd);
1450 		ffree(fp);
1451 		return error;
1452 	}
1453 	fp->f_flag = FREAD|FWRITE;
1454 	fp->f_type = DTYPE_VNODE;
1455 	fp->f_ops = &vnops;
1456 	fp->f_data = nd.ni_vp;
1457 	VOP_UNLOCK(nd.ni_vp, 0);
1458 	FILE_SET_MATURE(fp);
1459 	FILE_UNUSE(fp, p);
1460 	return 0;
1461 }
1462 
1463 static void
1464 pty_fill_ptmget(dev_t dev, int cfd, int sfd, void *data)
1465 {
1466 	struct ptmget *ptm = data;
1467 	ptm->cfd = cfd;
1468 	ptm->sfd = sfd;
1469 	(void)pty_makename(ptm->cn, dev, 'p');
1470 	(void)pty_makename(ptm->sn, dev, 't');
1471 }
1472 
1473 void
1474 /*ARGSUSED*/
1475 ptmattach(int n)
1476 {
1477 	/* find the major and minor of the pty devices */
1478 	if ((pts_major = cdevsw_lookup_major(&pts_cdevsw)) == -1)
1479 		panic("ptmattach: Can't find pty slave in cdevsw");
1480 }
1481 
1482 int
1483 /*ARGSUSED*/
1484 ptmopen(dev_t dev, int flag, int mode, struct proc *p)
1485 {
1486 	int error;
1487 	int fd;
1488 
1489 	switch(minor(dev)) {
1490 	case 0:		/* /dev/ptmx */
1491 		if ((error = pty_alloc_master(p, &fd, &dev)) != 0)
1492 			return error;
1493 		curlwp->l_dupfd = fd;
1494 		return ENXIO;
1495 	case 1:		/* /dev/ptm */
1496 		return 0;
1497 	default:
1498 		return ENODEV;
1499 	}
1500 
1501 }
1502 
1503 int
1504 /*ARGSUSED*/
1505 ptmclose(dev_t dev, int flag, int mode, struct proc *p)
1506 {
1507 	return (0);
1508 }
1509 
1510 int
1511 /*ARGSUSED*/
1512 ptmioctl(dev_t dev, u_long cmd, caddr_t data, int flag, struct proc *p)
1513 {
1514 	int error;
1515 	dev_t newdev;
1516 	int cfd, sfd;
1517 	struct file *fp;
1518 
1519 	error = 0;
1520 	switch (cmd) {
1521 	case TIOCPTMGET:
1522 		if ((error = pty_alloc_master(p, &cfd, &newdev)) != 0)
1523 			return error;
1524 
1525 		if ((error = pty_grant_slave(p, newdev)) != 0)
1526 			goto bad;
1527 
1528 		if ((error = pty_alloc_slave(p, &sfd, newdev)) != 0)
1529 			goto bad;
1530 
1531 		/* now, put the indices and names into struct ptmget */
1532 		pty_fill_ptmget(newdev, cfd, sfd, data);
1533 		return 0;
1534 	default:
1535 		DPRINTF(("ptmioctl EINVAL\n"));
1536 		return EINVAL;
1537 	}
1538 bad:
1539 	fp = fd_getfile(p->p_fd, cfd);
1540 	fdremove(p->p_fd, cfd);
1541 	ffree(fp);
1542 	return error;
1543 }
1544 #endif
1545