Home | History | Annotate | Line # | Download | only in kern
tty_pty.c revision 1.70.2.4
      1 /*	$NetBSD: tty_pty.c,v 1.70.2.4 2004/09/21 13:35:16 skrll 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.70.2.4 2004/09/21 13:35:16 skrll 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 lwp *, dev_t);
    126 static int pty_alloc_master(struct lwp *, int *, dev_t *);
    127 static int pty_alloc_slave(struct lwp *, 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, l)
    346 	dev_t dev;
    347 	int flag, devtype;
    348 	struct lwp *l;
    349 {
    350 	struct proc *p = l->l_proc;
    351 	struct pt_softc *pti;
    352 	struct tty *tp;
    353 	int error;
    354 	int ptn = minor(dev);
    355 	int s;
    356 
    357 	if ((error = check_pty(ptn)))
    358 		return (error);
    359 
    360 	pti = pt_softc[ptn];
    361 	tp = pti->pt_tty;
    362 
    363 	if (!ISSET(tp->t_state, TS_ISOPEN)) {
    364 		ttychars(tp);		/* Set up default chars */
    365 		tp->t_iflag = TTYDEF_IFLAG;
    366 		tp->t_oflag = TTYDEF_OFLAG;
    367 		tp->t_lflag = TTYDEF_LFLAG;
    368 		tp->t_cflag = TTYDEF_CFLAG;
    369 		tp->t_ispeed = tp->t_ospeed = TTYDEF_SPEED;
    370 		ttsetwater(tp);		/* would be done in xxparam() */
    371 	} else if (ISSET(tp->t_state, TS_XCLUDE) && p->p_ucred->cr_uid != 0)
    372 		return (EBUSY);
    373 	if (tp->t_oproc)			/* Ctrlr still around. */
    374 		SET(tp->t_state, TS_CARR_ON);
    375 
    376 	if (!ISSET(flag, O_NONBLOCK)) {
    377 		s = spltty();
    378 		TTY_LOCK(tp);
    379 		while (!ISSET(tp->t_state, TS_CARR_ON)) {
    380 			tp->t_wopen++;
    381 			error = ttysleep(tp, &tp->t_rawq, TTIPRI | PCATCH,
    382 			    ttopen, 0);
    383 			tp->t_wopen--;
    384 			if (error) {
    385 				TTY_UNLOCK(tp);
    386 				splx(s);
    387 				return (error);
    388 			}
    389 		}
    390 		TTY_UNLOCK(tp);
    391 		splx(s);
    392 	}
    393 	error = (*tp->t_linesw->l_open)(dev, tp);
    394 	ptcwakeup(tp, FREAD|FWRITE);
    395 	return (error);
    396 }
    397 
    398 int
    399 ptsclose(dev, flag, mode, l)
    400 	dev_t dev;
    401 	int flag, mode;
    402 	struct lwp *l;
    403 {
    404 	struct pt_softc *pti = pt_softc[minor(dev)];
    405 	struct tty *tp = pti->pt_tty;
    406 	int error;
    407 
    408 	error = (*tp->t_linesw->l_close)(tp, flag);
    409 	error |= ttyclose(tp);
    410 	ptcwakeup(tp, FREAD|FWRITE);
    411 	return (error);
    412 }
    413 
    414 int
    415 ptsread(dev, uio, flag)
    416 	dev_t dev;
    417 	struct uio *uio;
    418 	int flag;
    419 {
    420 	struct proc *p = curproc;
    421 	struct pt_softc *pti = pt_softc[minor(dev)];
    422 	struct tty *tp = pti->pt_tty;
    423 	int error = 0;
    424 	int cc;
    425 	int s;
    426 
    427 again:
    428 	if (pti->pt_flags & PF_REMOTE) {
    429 		while (isbackground(p, tp)) {
    430 			if (sigismasked(p, SIGTTIN) ||
    431 			    p->p_pgrp->pg_jobc == 0 ||
    432 			    p->p_flag & P_PPWAIT)
    433 				return (EIO);
    434 			pgsignal(p->p_pgrp, SIGTTIN, 1);
    435 			s = spltty();
    436 			TTY_LOCK(tp);
    437 			error = ttysleep(tp, (caddr_t)&lbolt,
    438 					 TTIPRI | PCATCH | PNORELOCK, ttybg, 0);
    439 			splx(s);
    440 			if (error)
    441 				return (error);
    442 		}
    443 		s = spltty();
    444 		TTY_LOCK(tp);
    445 		if (tp->t_canq.c_cc == 0) {
    446 			if (flag & IO_NDELAY) {
    447 				TTY_UNLOCK(tp);
    448 				splx(s);
    449 				return (EWOULDBLOCK);
    450 			}
    451 			error = ttysleep(tp, (caddr_t)&tp->t_canq,
    452 					 TTIPRI | PCATCH | PNORELOCK, ttyin, 0);
    453 			if (error)
    454 				return (error);
    455 			goto again;
    456 		}
    457 		while(error == 0 && tp->t_canq.c_cc > 1 && uio->uio_resid > 0) {
    458 			TTY_UNLOCK(tp);
    459 			splx(s);
    460 			error = ureadc(getc(&tp->t_canq), uio);
    461 			s = spltty();
    462 			TTY_LOCK(tp);
    463 			/* Re-check terminal state here? */
    464 		}
    465 		if (tp->t_canq.c_cc == 1)
    466 			(void) getc(&tp->t_canq);
    467 		cc = tp->t_canq.c_cc;
    468 		TTY_UNLOCK(tp);
    469 		splx(s);
    470 		if (cc)
    471 			return (error);
    472 	} else
    473 		if (tp->t_oproc)
    474 			error = (*tp->t_linesw->l_read)(tp, uio, flag);
    475 	ptcwakeup(tp, FWRITE);
    476 	return (error);
    477 }
    478 
    479 /*
    480  * Write to pseudo-tty.
    481  * Wakeups of controlling tty will happen
    482  * indirectly, when tty driver calls ptsstart.
    483  */
    484 int
    485 ptswrite(dev, uio, flag)
    486 	dev_t dev;
    487 	struct uio *uio;
    488 	int flag;
    489 {
    490 	struct pt_softc *pti = pt_softc[minor(dev)];
    491 	struct tty *tp = pti->pt_tty;
    492 
    493 	if (tp->t_oproc == 0)
    494 		return (EIO);
    495 	return ((*tp->t_linesw->l_write)(tp, uio, flag));
    496 }
    497 
    498 /*
    499  * Poll pseudo-tty.
    500  */
    501 int
    502 ptspoll(dev, events, l)
    503 	dev_t dev;
    504 	int events;
    505 	struct lwp *l;
    506 {
    507 	struct pt_softc *pti = pt_softc[minor(dev)];
    508 	struct tty *tp = pti->pt_tty;
    509 
    510 	if (tp->t_oproc == 0)
    511 		return (EIO);
    512 
    513 	return ((*tp->t_linesw->l_poll)(tp, events, l));
    514 }
    515 
    516 /*
    517  * Start output on pseudo-tty.
    518  * Wake up process polling or sleeping for input from controlling tty.
    519  * Called with tty slock held.
    520  */
    521 void
    522 ptsstart(tp)
    523 	struct tty *tp;
    524 {
    525 	struct pt_softc *pti = pt_softc[minor(tp->t_dev)];
    526 
    527 	if (ISSET(tp->t_state, TS_TTSTOP))
    528 		return;
    529 	if (pti->pt_flags & PF_STOPPED) {
    530 		pti->pt_flags &= ~PF_STOPPED;
    531 		pti->pt_send = TIOCPKT_START;
    532 	}
    533 
    534 	selnotify(&pti->pt_selr, NOTE_SUBMIT);
    535 	wakeup((caddr_t)&tp->t_outq.c_cf);
    536 }
    537 
    538 /*
    539  * Stop output.
    540  * Called with tty slock held.
    541  */
    542 void
    543 ptsstop(tp, flush)
    544 	struct tty *tp;
    545 	int flush;
    546 {
    547 	struct pt_softc *pti = pt_softc[minor(tp->t_dev)];
    548 
    549 	/* note: FLUSHREAD and FLUSHWRITE already ok */
    550 	if (flush == 0) {
    551 		flush = TIOCPKT_STOP;
    552 		pti->pt_flags |= PF_STOPPED;
    553 	} else
    554 		pti->pt_flags &= ~PF_STOPPED;
    555 	pti->pt_send |= flush;
    556 
    557 	/* change of perspective */
    558 	if (flush & FREAD) {
    559 		selnotify(&pti->pt_selw, NOTE_SUBMIT);
    560 		wakeup((caddr_t)&tp->t_rawq.c_cf);
    561 	}
    562 	if (flush & FWRITE) {
    563 		selnotify(&pti->pt_selr, NOTE_SUBMIT);
    564 		wakeup((caddr_t)&tp->t_outq.c_cf);
    565 	}
    566 }
    567 
    568 void
    569 ptcwakeup(tp, flag)
    570 	struct tty *tp;
    571 	int flag;
    572 {
    573 	struct pt_softc *pti = pt_softc[minor(tp->t_dev)];
    574 	int s;
    575 
    576 	s = spltty();
    577 	TTY_LOCK(tp);
    578 	if (flag & FREAD) {
    579 		selnotify(&pti->pt_selr, NOTE_SUBMIT);
    580 		wakeup((caddr_t)&tp->t_outq.c_cf);
    581 	}
    582 	if (flag & FWRITE) {
    583 		selnotify(&pti->pt_selw, NOTE_SUBMIT);
    584 		wakeup((caddr_t)&tp->t_rawq.c_cf);
    585 	}
    586 	TTY_UNLOCK(tp);
    587 	splx(s);
    588 }
    589 
    590 /*ARGSUSED*/
    591 int
    592 ptcopen(dev, flag, devtype, l)
    593 	dev_t dev;
    594 	int flag, devtype;
    595 	struct lwp *l;
    596 {
    597 	struct pt_softc *pti;
    598 	struct tty *tp;
    599 	int error;
    600 	int ptn = minor(dev);
    601 	int s;
    602 
    603 	if ((error = check_pty(ptn)))
    604 		return (error);
    605 
    606 	pti = pt_softc[ptn];
    607 	tp = pti->pt_tty;
    608 
    609 	s = spltty();
    610 	TTY_LOCK(tp);
    611 	if (tp->t_oproc) {
    612 		TTY_UNLOCK(tp);
    613 		splx(s);
    614 		return (EIO);
    615 	}
    616 	tp->t_oproc = ptsstart;
    617 	TTY_UNLOCK(tp);
    618 	splx(s);
    619 	(void)(*tp->t_linesw->l_modem)(tp, 1);
    620 	CLR(tp->t_lflag, EXTPROC);
    621 	pti->pt_flags = 0;
    622 	pti->pt_send = 0;
    623 	pti->pt_ucntl = 0;
    624 	return (0);
    625 }
    626 
    627 /*ARGSUSED*/
    628 int
    629 ptcclose(dev, flag, devtype, l)
    630 	dev_t dev;
    631 	int flag, devtype;
    632 	struct lwp *l;
    633 {
    634 	struct pt_softc *pti = pt_softc[minor(dev)];
    635 	struct tty *tp = pti->pt_tty;
    636 	int s;
    637 
    638 	(void)(*tp->t_linesw->l_modem)(tp, 0);
    639 	CLR(tp->t_state, TS_CARR_ON);
    640 	s = spltty();
    641 	TTY_LOCK(tp);
    642 	tp->t_oproc = 0;		/* mark closed */
    643 	TTY_UNLOCK(tp);
    644 	splx(s);
    645 	return (0);
    646 }
    647 
    648 int
    649 ptcread(dev, uio, flag)
    650 	dev_t dev;
    651 	struct uio *uio;
    652 	int flag;
    653 {
    654 	struct pt_softc *pti = pt_softc[minor(dev)];
    655 	struct tty *tp = pti->pt_tty;
    656 	u_char buf[BUFSIZ];
    657 	int error = 0, cc;
    658 	int s;
    659 
    660 	/*
    661 	 * We want to block until the slave
    662 	 * is open, and there's something to read;
    663 	 * but if we lost the slave or we're NBIO,
    664 	 * then return the appropriate error instead.
    665 	 */
    666 	s = spltty();
    667 	TTY_LOCK(tp);
    668 	for (;;) {
    669 		if (ISSET(tp->t_state, TS_ISOPEN)) {
    670 			if (pti->pt_flags & PF_PKT && pti->pt_send) {
    671 				TTY_UNLOCK(tp);
    672 				splx(s);
    673 				error = ureadc((int)pti->pt_send, uio);
    674 				if (error)
    675 					return (error);
    676 				/*
    677 				 * Since we don't have the tty locked, there's
    678 				 * a risk of messing up `t_termios'. This is
    679 				 * relevant only if the tty got closed and then
    680 				 * opened again while we were out uiomoving.
    681 				 */
    682 				if (pti->pt_send & TIOCPKT_IOCTL) {
    683 					cc = min(uio->uio_resid,
    684 						sizeof(tp->t_termios));
    685 					uiomove((caddr_t) &tp->t_termios,
    686 						cc, uio);
    687 				}
    688 				pti->pt_send = 0;
    689 				return (0);
    690 			}
    691 			if (pti->pt_flags & PF_UCNTL && pti->pt_ucntl) {
    692 				TTY_UNLOCK(tp);
    693 				splx(s);
    694 				error = ureadc((int)pti->pt_ucntl, uio);
    695 				if (error)
    696 					return (error);
    697 				pti->pt_ucntl = 0;
    698 				return (0);
    699 			}
    700 			if (tp->t_outq.c_cc && !ISSET(tp->t_state, TS_TTSTOP))
    701 				break;
    702 		}
    703 		if (!ISSET(tp->t_state, TS_CARR_ON)) {
    704 			error = 0;	/* EOF */
    705 			goto out;
    706 		}
    707 		if (flag & IO_NDELAY) {
    708 			error = EWOULDBLOCK;
    709 			goto out;
    710 		}
    711 		error = ltsleep((caddr_t)&tp->t_outq.c_cf, TTIPRI | PCATCH,
    712 				ttyin, 0, &tp->t_slock);
    713 		if (error)
    714 			goto out;
    715 	}
    716 
    717 	if (pti->pt_flags & (PF_PKT|PF_UCNTL)) {
    718 		TTY_UNLOCK(tp);
    719 		splx(s);
    720 		error = ureadc(0, uio);
    721 		s = spltty();
    722 		TTY_LOCK(tp);
    723 		if (error == 0 && !ISSET(tp->t_state, TS_ISOPEN))
    724 			error = EIO;
    725 	}
    726 	while (uio->uio_resid > 0 && error == 0) {
    727 		cc = q_to_b(&tp->t_outq, buf, min(uio->uio_resid, BUFSIZ));
    728 		if (cc <= 0)
    729 			break;
    730 		TTY_UNLOCK(tp);
    731 		splx(s);
    732 		error = uiomove(buf, cc, uio);
    733 		s = spltty();
    734 		TTY_LOCK(tp);
    735 		if (error == 0 && !ISSET(tp->t_state, TS_ISOPEN))
    736 			error = EIO;
    737 	}
    738 
    739 	if (tp->t_outq.c_cc <= tp->t_lowat) {
    740 		if (ISSET(tp->t_state, TS_ASLEEP)) {
    741 			CLR(tp->t_state, TS_ASLEEP);
    742 			wakeup((caddr_t)&tp->t_outq);
    743 		}
    744 		selnotify(&tp->t_wsel, NOTE_SUBMIT);
    745 	}
    746 out:
    747 	TTY_UNLOCK(tp);
    748 	splx(s);
    749 	return (error);
    750 }
    751 
    752 
    753 int
    754 ptcwrite(dev, uio, flag)
    755 	dev_t dev;
    756 	struct uio *uio;
    757 	int flag;
    758 {
    759 	struct pt_softc *pti = pt_softc[minor(dev)];
    760 	struct tty *tp = pti->pt_tty;
    761 	u_char *cp = NULL;
    762 	int cc = 0;
    763 	u_char locbuf[BUFSIZ];
    764 	int cnt = 0;
    765 	int error = 0;
    766 	int s;
    767 
    768 again:
    769 	s = spltty();
    770 	TTY_LOCK(tp);
    771 	if (!ISSET(tp->t_state, TS_ISOPEN))
    772 		goto block;
    773 	if (pti->pt_flags & PF_REMOTE) {
    774 		if (tp->t_canq.c_cc)
    775 			goto block;
    776 		while (uio->uio_resid > 0 && tp->t_canq.c_cc < TTYHOG - 1) {
    777 			if (cc == 0) {
    778 				cc = min(uio->uio_resid, BUFSIZ);
    779 				cc = min(cc, TTYHOG - 1 - tp->t_canq.c_cc);
    780 				cp = locbuf;
    781 				TTY_UNLOCK(tp);
    782 				splx(s);
    783 				error = uiomove((caddr_t)cp, cc, uio);
    784 				if (error)
    785 					return (error);
    786 				s = spltty();
    787 				TTY_LOCK(tp);
    788 				/* check again for safety */
    789 				if (!ISSET(tp->t_state, TS_ISOPEN)) {
    790 					error = EIO;
    791 					goto out;
    792 				}
    793 			}
    794 			if (cc)
    795 				(void) b_to_q(cp, cc, &tp->t_canq);
    796 			cc = 0;
    797 		}
    798 		(void) putc(0, &tp->t_canq);
    799 		ttwakeup(tp);
    800 		wakeup((caddr_t)&tp->t_canq);
    801 		error = 0;
    802 		goto out;
    803 	}
    804 	while (uio->uio_resid > 0) {
    805 		if (cc == 0) {
    806 			cc = min(uio->uio_resid, BUFSIZ);
    807 			cp = locbuf;
    808 			TTY_UNLOCK(tp);
    809 			splx(s);
    810 			error = uiomove((caddr_t)cp, cc, uio);
    811 			if (error)
    812 				return (error);
    813 			s = spltty();
    814 			TTY_LOCK(tp);
    815 			/* check again for safety */
    816 			if (!ISSET(tp->t_state, TS_ISOPEN)) {
    817 				error = EIO;
    818 				goto out;
    819 			}
    820 		}
    821 		while (cc > 0) {
    822 			if ((tp->t_rawq.c_cc + tp->t_canq.c_cc) >= TTYHOG - 2 &&
    823 			   (tp->t_canq.c_cc > 0 || !ISSET(tp->t_lflag, ICANON))) {
    824 				wakeup((caddr_t)&tp->t_rawq);
    825 				goto block;
    826 			}
    827 			/* XXX - should change l_rint to be called with lock
    828 			 *	 see also tty.c:ttyinput_wlock()
    829 			 */
    830 			TTY_UNLOCK(tp);
    831 			splx(s);
    832 			(*tp->t_linesw->l_rint)(*cp++, tp);
    833 			s = spltty();
    834 			TTY_LOCK(tp);
    835 			cnt++;
    836 			cc--;
    837 		}
    838 		cc = 0;
    839 	}
    840 	error = 0;
    841 	goto out;
    842 
    843 block:
    844 	/*
    845 	 * Come here to wait for slave to open, for space
    846 	 * in outq, or space in rawq.
    847 	 */
    848 	if (!ISSET(tp->t_state, TS_CARR_ON)) {
    849 		error = EIO;
    850 		goto out;
    851 	}
    852 	if (flag & IO_NDELAY) {
    853 		/* adjust for data copied in but not written */
    854 		uio->uio_resid += cc;
    855 		error = cnt == 0 ? EWOULDBLOCK : 0;
    856 		goto out;
    857 	}
    858 	error = ltsleep((caddr_t)&tp->t_rawq.c_cf, TTOPRI | PCATCH | PNORELOCK,
    859 		       ttyout, 0, &tp->t_slock);
    860 	splx(s);
    861 	if (error) {
    862 		/* adjust for data copied in but not written */
    863 		uio->uio_resid += cc;
    864 		return (error);
    865 	}
    866 	goto again;
    867 
    868 out:
    869 	TTY_UNLOCK(tp);
    870 	splx(s);
    871 	return (error);
    872 }
    873 
    874 int
    875 ptcpoll(dev, events, l)
    876 	dev_t dev;
    877 	int events;
    878 	struct lwp *l;
    879 {
    880 	struct pt_softc *pti = pt_softc[minor(dev)];
    881 	struct tty *tp = pti->pt_tty;
    882 	int revents = 0;
    883 	int s = splsoftclock();
    884 
    885 	if (events & (POLLIN | POLLRDNORM))
    886 		if (ISSET(tp->t_state, TS_ISOPEN) &&
    887 		    ((tp->t_outq.c_cc > 0 && !ISSET(tp->t_state, TS_TTSTOP)) ||
    888 		     ((pti->pt_flags & PF_PKT) && pti->pt_send) ||
    889 		     ((pti->pt_flags & PF_UCNTL) && pti->pt_ucntl)))
    890 			revents |= events & (POLLIN | POLLRDNORM);
    891 
    892 	if (events & (POLLOUT | POLLWRNORM))
    893 		if (ISSET(tp->t_state, TS_ISOPEN) &&
    894 		    ((pti->pt_flags & PF_REMOTE) ?
    895 		     (tp->t_canq.c_cc == 0) :
    896 		     ((tp->t_rawq.c_cc + tp->t_canq.c_cc < TTYHOG-2) ||
    897 		      (tp->t_canq.c_cc == 0 && ISSET(tp->t_lflag, ICANON)))))
    898 			revents |= events & (POLLOUT | POLLWRNORM);
    899 
    900 	if (events & POLLHUP)
    901 		if (!ISSET(tp->t_state, TS_CARR_ON))
    902 			revents |= POLLHUP;
    903 
    904 	if (revents == 0) {
    905 		if (events & (POLLIN | POLLHUP | POLLRDNORM))
    906 			selrecord(l, &pti->pt_selr);
    907 
    908 		if (events & (POLLOUT | POLLWRNORM))
    909 			selrecord(l, &pti->pt_selw);
    910 	}
    911 
    912 	splx(s);
    913 	return (revents);
    914 }
    915 
    916 static void
    917 filt_ptcrdetach(struct knote *kn)
    918 {
    919 	struct pt_softc *pti;
    920 	int		s;
    921 
    922 	pti = kn->kn_hook;
    923 	s = spltty();
    924 	SLIST_REMOVE(&pti->pt_selr.sel_klist, kn, knote, kn_selnext);
    925 	splx(s);
    926 }
    927 
    928 static int
    929 filt_ptcread(struct knote *kn, long hint)
    930 {
    931 	struct pt_softc *pti;
    932 	struct tty	*tp;
    933 	int canread;
    934 
    935 	pti = kn->kn_hook;
    936 	tp = pti->pt_tty;
    937 
    938 	canread = (ISSET(tp->t_state, TS_ISOPEN) &&
    939 		    ((tp->t_outq.c_cc > 0 && !ISSET(tp->t_state, TS_TTSTOP)) ||
    940 		     ((pti->pt_flags & PF_PKT) && pti->pt_send) ||
    941 		     ((pti->pt_flags & PF_UCNTL) && pti->pt_ucntl)));
    942 
    943 	if (canread) {
    944 		/*
    945 		 * c_cc is number of characters after output post-processing;
    946 		 * the amount of data actually read(2) depends on
    947 		 * setting of input flags for the terminal.
    948 		 */
    949 		kn->kn_data = tp->t_outq.c_cc;
    950 		if (((pti->pt_flags & PF_PKT) && pti->pt_send) ||
    951 		    ((pti->pt_flags & PF_UCNTL) && pti->pt_ucntl))
    952 			kn->kn_data++;
    953 	}
    954 
    955 	return (canread);
    956 }
    957 
    958 static void
    959 filt_ptcwdetach(struct knote *kn)
    960 {
    961 	struct pt_softc *pti;
    962 	int		s;
    963 
    964 	pti = kn->kn_hook;
    965 	s = spltty();
    966 	SLIST_REMOVE(&pti->pt_selw.sel_klist, kn, knote, kn_selnext);
    967 	splx(s);
    968 }
    969 
    970 static int
    971 filt_ptcwrite(struct knote *kn, long hint)
    972 {
    973 	struct pt_softc *pti;
    974 	struct tty	*tp;
    975 	int canwrite;
    976 	int nwrite;
    977 
    978 	pti = kn->kn_hook;
    979 	tp = pti->pt_tty;
    980 
    981 	canwrite = (ISSET(tp->t_state, TS_ISOPEN) &&
    982 		    ((pti->pt_flags & PF_REMOTE) ?
    983 		     (tp->t_canq.c_cc == 0) :
    984 		     ((tp->t_rawq.c_cc + tp->t_canq.c_cc < TTYHOG-2) ||
    985 		      (tp->t_canq.c_cc == 0 && ISSET(tp->t_lflag, ICANON)))));
    986 
    987 	if (canwrite) {
    988 		if (pti->pt_flags & PF_REMOTE)
    989 			nwrite = tp->t_canq.c_cn;
    990 		else {
    991 			/* this is guaranteed to be > 0 due to above check */
    992 			nwrite = tp->t_canq.c_cn
    993 				- (tp->t_rawq.c_cc + tp->t_canq.c_cc);
    994 		}
    995 		kn->kn_data = nwrite;
    996 	}
    997 
    998 	return (canwrite);
    999 }
   1000 
   1001 static const struct filterops ptcread_filtops =
   1002 	{ 1, NULL, filt_ptcrdetach, filt_ptcread };
   1003 static const struct filterops ptcwrite_filtops =
   1004 	{ 1, NULL, filt_ptcwdetach, filt_ptcwrite };
   1005 
   1006 int
   1007 ptckqfilter(dev_t dev, struct knote *kn)
   1008 {
   1009 	struct pt_softc *pti = pt_softc[minor(dev)];
   1010 	struct klist	*klist;
   1011 	int		s;
   1012 
   1013 	switch (kn->kn_filter) {
   1014 	case EVFILT_READ:
   1015 		klist = &pti->pt_selr.sel_klist;
   1016 		kn->kn_fop = &ptcread_filtops;
   1017 		break;
   1018 	case EVFILT_WRITE:
   1019 		klist = &pti->pt_selw.sel_klist;
   1020 		kn->kn_fop = &ptcwrite_filtops;
   1021 		break;
   1022 	default:
   1023 		return (1);
   1024 	}
   1025 
   1026 	kn->kn_hook = pti;
   1027 
   1028 	s = spltty();
   1029 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
   1030 	splx(s);
   1031 
   1032 	return (0);
   1033 }
   1034 
   1035 struct tty *
   1036 ptytty(dev)
   1037 	dev_t dev;
   1038 {
   1039 	struct pt_softc *pti = pt_softc[minor(dev)];
   1040 	struct tty *tp = pti->pt_tty;
   1041 
   1042 	return (tp);
   1043 }
   1044 
   1045 /*ARGSUSED*/
   1046 int
   1047 ptyioctl(dev, cmd, data, flag, l)
   1048 	dev_t dev;
   1049 	u_long cmd;
   1050 	caddr_t data;
   1051 	int flag;
   1052 	struct lwp *l;
   1053 {
   1054 	struct pt_softc *pti = pt_softc[minor(dev)];
   1055 	struct tty *tp = pti->pt_tty;
   1056 	const struct cdevsw *cdev;
   1057 	u_char *cc = tp->t_cc;
   1058 	int stop, error, sig;
   1059 	int s;
   1060 
   1061 	cdev = cdevsw_lookup(dev);
   1062 	/*
   1063 	 * IF CONTROLLER STTY THEN MUST FLUSH TO PREVENT A HANG.
   1064 	 * ttywflush(tp) will hang if there are characters in the outq.
   1065 	 */
   1066 	if (cmd == TIOCEXT) {
   1067 		/*
   1068 		 * When the EXTPROC bit is being toggled, we need
   1069 		 * to send an TIOCPKT_IOCTL if the packet driver
   1070 		 * is turned on.
   1071 		 */
   1072 		if (*(int *)data) {
   1073 			if (pti->pt_flags & PF_PKT) {
   1074 				pti->pt_send |= TIOCPKT_IOCTL;
   1075 				ptcwakeup(tp, FREAD);
   1076 			}
   1077 			SET(tp->t_lflag, EXTPROC);
   1078 		} else {
   1079 			if (ISSET(tp->t_lflag, EXTPROC) &&
   1080 			    (pti->pt_flags & PF_PKT)) {
   1081 				pti->pt_send |= TIOCPKT_IOCTL;
   1082 				ptcwakeup(tp, FREAD);
   1083 			}
   1084 			CLR(tp->t_lflag, EXTPROC);
   1085 		}
   1086 		return(0);
   1087 	}
   1088 
   1089 	if (cdev != NULL && cdev->d_open == ptcopen)
   1090 		switch (cmd) {
   1091 #ifndef NO_DEV_PTM
   1092 		case TIOCGRANTPT:
   1093 			return pty_grant_slave(l, dev);
   1094 
   1095 		case TIOCPTSNAME:
   1096 			pty_fill_ptmget(dev, -1, -1, data);
   1097 			return 0;
   1098 #endif
   1099 
   1100 		case TIOCGPGRP:
   1101 			/*
   1102 			 * We avoid calling ttioctl on the controller since,
   1103 			 * in that case, tp must be the controlling terminal.
   1104 			 */
   1105 			*(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : 0;
   1106 			return (0);
   1107 
   1108 		case TIOCPKT:
   1109 			if (*(int *)data) {
   1110 				if (pti->pt_flags & PF_UCNTL)
   1111 					return (EINVAL);
   1112 				pti->pt_flags |= PF_PKT;
   1113 			} else
   1114 				pti->pt_flags &= ~PF_PKT;
   1115 			return (0);
   1116 
   1117 		case TIOCUCNTL:
   1118 			if (*(int *)data) {
   1119 				if (pti->pt_flags & PF_PKT)
   1120 					return (EINVAL);
   1121 				pti->pt_flags |= PF_UCNTL;
   1122 			} else
   1123 				pti->pt_flags &= ~PF_UCNTL;
   1124 			return (0);
   1125 
   1126 		case TIOCREMOTE:
   1127 			if (*(int *)data)
   1128 				pti->pt_flags |= PF_REMOTE;
   1129 			else
   1130 				pti->pt_flags &= ~PF_REMOTE;
   1131 			s = spltty();
   1132 			TTY_LOCK(tp);
   1133 			ttyflush(tp, FREAD|FWRITE);
   1134 			TTY_UNLOCK(tp);
   1135 			splx(s);
   1136 			return (0);
   1137 
   1138 #ifdef COMPAT_OLDTTY
   1139 		case TIOCSETP:
   1140 		case TIOCSETN:
   1141 #endif
   1142 		case TIOCSETD:
   1143 		case TIOCSETA:
   1144 		case TIOCSETAW:
   1145 		case TIOCSETAF:
   1146 			TTY_LOCK(tp);
   1147 			ndflush(&tp->t_outq, tp->t_outq.c_cc);
   1148 			TTY_UNLOCK(tp);
   1149 			break;
   1150 
   1151 		case TIOCSIG:
   1152 			sig = (int)(long)*(caddr_t *)data;
   1153 			if (sig <= 0 || sig >= NSIG)
   1154 				return (EINVAL);
   1155 			TTY_LOCK(tp);
   1156 			if (!ISSET(tp->t_lflag, NOFLSH))
   1157 				ttyflush(tp, FREAD|FWRITE);
   1158 			if ((sig == SIGINFO) &&
   1159 			    (!ISSET(tp->t_lflag, NOKERNINFO)))
   1160 				ttyinfo(tp);
   1161 			TTY_UNLOCK(tp);
   1162 			pgsignal(tp->t_pgrp, sig, 1);
   1163 			return(0);
   1164 		}
   1165 
   1166 	error = (*tp->t_linesw->l_ioctl)(tp, cmd, data, flag, l);
   1167 	if (error == EPASSTHROUGH)
   1168 		 error = ttioctl(tp, cmd, data, flag, l);
   1169 	if (error == EPASSTHROUGH) {
   1170 		if (pti->pt_flags & PF_UCNTL &&
   1171 		    (cmd & ~0xff) == UIOCCMD(0)) {
   1172 			if (cmd & 0xff) {
   1173 				pti->pt_ucntl = (u_char)cmd;
   1174 				ptcwakeup(tp, FREAD);
   1175 			}
   1176 			return (0);
   1177 		}
   1178 	}
   1179 	/*
   1180 	 * If external processing and packet mode send ioctl packet.
   1181 	 */
   1182 	if (ISSET(tp->t_lflag, EXTPROC) && (pti->pt_flags & PF_PKT)) {
   1183 		switch(cmd) {
   1184 		case TIOCSETA:
   1185 		case TIOCSETAW:
   1186 		case TIOCSETAF:
   1187 #ifdef COMPAT_OLDTTY
   1188 		case TIOCSETP:
   1189 		case TIOCSETN:
   1190 		case TIOCSETC:
   1191 		case TIOCSLTC:
   1192 		case TIOCLBIS:
   1193 		case TIOCLBIC:
   1194 		case TIOCLSET:
   1195 #endif
   1196 			pti->pt_send |= TIOCPKT_IOCTL;
   1197 			ptcwakeup(tp, FREAD);
   1198 		default:
   1199 			break;
   1200 		}
   1201 	}
   1202 	stop = ISSET(tp->t_iflag, IXON) && CCEQ(cc[VSTOP], CTRL('s'))
   1203 		&& CCEQ(cc[VSTART], CTRL('q'));
   1204 	if (pti->pt_flags & PF_NOSTOP) {
   1205 		if (stop) {
   1206 			pti->pt_send &= ~TIOCPKT_NOSTOP;
   1207 			pti->pt_send |= TIOCPKT_DOSTOP;
   1208 			pti->pt_flags &= ~PF_NOSTOP;
   1209 			ptcwakeup(tp, FREAD);
   1210 		}
   1211 	} else {
   1212 		if (!stop) {
   1213 			pti->pt_send &= ~TIOCPKT_DOSTOP;
   1214 			pti->pt_send |= TIOCPKT_NOSTOP;
   1215 			pti->pt_flags |= PF_NOSTOP;
   1216 			ptcwakeup(tp, FREAD);
   1217 		}
   1218 	}
   1219 	return (error);
   1220 }
   1221 
   1222 #ifndef NO_DEV_PTM
   1223 /*
   1224  * Check if a pty is free to use.
   1225  */
   1226 static __inline int
   1227 pty_isfree_locked(int minor)
   1228 {
   1229 	struct pt_softc *pt = pt_softc[minor];
   1230 	return (pt == NULL || pt->pt_tty == NULL ||
   1231 	    pt->pt_tty->t_oproc == NULL);
   1232 }
   1233 
   1234 static int
   1235 pty_isfree(int minor)
   1236 {
   1237 	int isfree;
   1238 
   1239 	simple_lock(&pt_softc_mutex);
   1240 	isfree = pty_isfree_locked(minor);
   1241 	simple_unlock(&pt_softc_mutex);
   1242 	return(isfree);
   1243 }
   1244 
   1245 static char *
   1246 pty_makename(char *buf, dev_t dev, char c)
   1247 {
   1248 	size_t nt;
   1249 	dev_t minor = minor(dev);
   1250 
   1251 	(void)memcpy(buf, TTY_TEMPLATE, TTY_NAMESIZE);
   1252 
   1253 	buf[5] = c;
   1254 
   1255 	if (minor < 256) {
   1256 		nt = sizeof(TTY_OLD_SUFFIX) - 1;
   1257 		buf[8] = TTY_LETTERS[minor / nt];
   1258 		buf[9] = TTY_OLD_SUFFIX[minor % nt];
   1259 	} else {
   1260 		minor -= 256;
   1261 		nt = sizeof(TTY_NEW_SUFFIX) - sizeof(TTY_OLD_SUFFIX);
   1262 		buf[8] = TTY_LETTERS[minor / nt];
   1263 		buf[9] = TTY_NEW_SUFFIX[minor % nt];
   1264 	}
   1265 	return buf;
   1266 }
   1267 
   1268 static dev_t
   1269 pty_getfree(void)
   1270 {
   1271 	int i;
   1272 
   1273 	simple_lock(&pt_softc_mutex);
   1274 	for (i = 0; i < npty; i++) {
   1275 		if (pty_isfree_locked(i))
   1276 			break;
   1277 	}
   1278 	simple_unlock(&pt_softc_mutex);
   1279 	return (makedev(pts_major, i));
   1280 }
   1281 
   1282 /*
   1283  * Hacked up version of vn_open. We _only_ handle ptys and only open
   1284  * them with FREAD|FWRITE and never deal with creat or stuff like that.
   1285  *
   1286  * We need it because we have to fake up root credentials to open the pty.
   1287  */
   1288 static int
   1289 ptm_vn_open(struct nameidata *ndp)
   1290 {
   1291 	struct vnode *vp;
   1292 	struct lwp *l = ndp->ni_cnd.cn_lwp;
   1293 	struct ucred *cred;
   1294 	int error;
   1295 
   1296 	if ((error = namei(ndp)) != 0)
   1297 		return (error);
   1298 	vp = ndp->ni_vp;
   1299 	if (vp->v_type != VCHR) {
   1300 		error = EINVAL;
   1301 		goto bad;
   1302 	}
   1303 
   1304 	/*
   1305 	 * Get us a fresh cred with root privileges.
   1306 	 */
   1307 	cred = crget();
   1308 	error = VOP_OPEN(vp, FREAD|FWRITE, cred, l);
   1309 	crfree(cred);
   1310 
   1311 	if (error)
   1312 		goto bad;
   1313 
   1314 	vp->v_writecount++;
   1315 
   1316 	return (0);
   1317 bad:
   1318 	vput(vp);
   1319 	return (error);
   1320 }
   1321 
   1322 static int
   1323 pty_alloc_master(struct lwp *l, int *fd, dev_t *dev)
   1324 {
   1325 	int error;
   1326 	struct nameidata nd;
   1327 	struct pt_softc *pti;
   1328 	struct file *fp;
   1329 	struct proc *p = l->l_proc;
   1330 	int md;
   1331 	char name[TTY_NAMESIZE];
   1332 
   1333 	if ((error = falloc(p, &fp, fd)) != 0) {
   1334 		DPRINTF(("falloc %d\n", error));
   1335 		return error;
   1336 	}
   1337 retry:
   1338 	/* Find and open a free master pty. */
   1339 	*dev = pty_getfree();
   1340 	md = minor(*dev);
   1341 	if ((error = check_pty(md)) != 0) {
   1342 		DPRINTF(("ckeck_pty %d\n", error));
   1343 		goto bad;
   1344 	}
   1345 	pti = pt_softc[md];
   1346 	NDINIT(&nd, LOOKUP, NOFOLLOW|LOCKLEAF, UIO_SYSSPACE,
   1347 	    pty_makename(name, *dev, 'p'), l);
   1348 	if ((error = ptm_vn_open(&nd)) != 0) {
   1349 		/*
   1350 		 * Check if the master open failed because we lost
   1351 		 * the race to grab it.
   1352 		 */
   1353 		if (error == EIO && !pty_isfree(md))
   1354 			goto retry;
   1355 		DPRINTF(("ptm_vn_open %d\n", error));
   1356 		goto bad;
   1357 	}
   1358 	fp->f_flag = FREAD|FWRITE;
   1359 	fp->f_type = DTYPE_VNODE;
   1360 	fp->f_ops = &vnops;
   1361 	fp->f_data = nd.ni_vp;
   1362 	VOP_UNLOCK(nd.ni_vp, 0);
   1363 	FILE_SET_MATURE(fp);
   1364 	FILE_UNUSE(fp, l);
   1365 	return 0;
   1366 bad:
   1367 	FILE_UNUSE(fp, l);
   1368 	fdremove(p->p_fd, *fd);
   1369 	ffree(fp);
   1370 	return error;
   1371 }
   1372 
   1373 static int
   1374 pty_grant_slave(struct lwp *l, dev_t dev)
   1375 {
   1376 	int error;
   1377 	struct nameidata nd;
   1378 	char name[TTY_NAMESIZE];
   1379 
   1380 	/*
   1381 	 * Open the slave.
   1382 	 * namei -> setattr -> unlock -> revoke -> vrele ->
   1383 	 * namei -> open -> unlock
   1384 	 * Three stage rocket:
   1385 	 * 1. Change the owner and permissions on the slave.
   1386 	 * 2. Revoke all the users of the slave.
   1387 	 * 3. open the slave.
   1388 	 */
   1389 	NDINIT(&nd, LOOKUP, NOFOLLOW|LOCKLEAF, UIO_SYSSPACE,
   1390 	    pty_makename(name, dev, 't'), l);
   1391 	if ((error = namei(&nd)) != 0) {
   1392 		DPRINTF(("namei %d\n", error));
   1393 		return error;
   1394 	}
   1395 	if ((nd.ni_vp->v_mount->mnt_flag & MNT_RDONLY) == 0) {
   1396 		struct vattr vattr;
   1397 		struct ucred *cred;
   1398 		gid_t gid = _TTY_GID;
   1399 		/* get real uid */
   1400 		uid_t uid = l->l_proc->p_cred->p_ruid;
   1401 
   1402 		VATTR_NULL(&vattr);
   1403 		vattr.va_uid = uid;
   1404 		vattr.va_gid = gid;
   1405 		vattr.va_mode = (S_IRUSR|S_IWUSR|S_IWGRP) & ALLPERMS;
   1406 		/* Get a fake cred to pretend we're root. */
   1407 		cred = crget();
   1408 		error = VOP_SETATTR(nd.ni_vp, &vattr, cred, l);
   1409 		crfree(cred);
   1410 		if (error) {
   1411 			DPRINTF(("setattr %d\n", error));
   1412 			VOP_UNLOCK(nd.ni_vp, 0);
   1413 			vrele(nd.ni_vp);
   1414 			return error;
   1415 		}
   1416 	}
   1417 	VOP_UNLOCK(nd.ni_vp, 0);
   1418 	if (nd.ni_vp->v_usecount > 1 ||
   1419 	    (nd.ni_vp->v_flag & (VALIASED | VLAYER)))
   1420 		VOP_REVOKE(nd.ni_vp, REVOKEALL);
   1421 
   1422 	/*
   1423 	 * The vnode is useless after the revoke, we need to
   1424 	 * namei again.
   1425 	 */
   1426 	vrele(nd.ni_vp);
   1427 	return 0;
   1428 }
   1429 
   1430 static int
   1431 pty_alloc_slave(struct lwp *l, int *fd, dev_t dev)
   1432 {
   1433 	int error;
   1434 	struct file *fp;
   1435 	struct proc *p = l->l_proc;
   1436 	struct nameidata nd;
   1437 	char name[TTY_NAMESIZE];
   1438 
   1439 	/* Grab a filedescriptor for the slave */
   1440 	if ((error = falloc(p, &fp, fd)) != 0) {
   1441 		DPRINTF(("falloc %d\n", error));
   1442 		return error;
   1443 	}
   1444 
   1445 	NDINIT(&nd, LOOKUP, NOFOLLOW|LOCKLEAF, UIO_SYSSPACE,
   1446 	    pty_makename(name, dev, 't'), l);
   1447 
   1448 	/* now open it */
   1449 	if ((error = ptm_vn_open(&nd)) != 0) {
   1450 		DPRINTF(("vn_open %d\n", error));
   1451 		FILE_UNUSE(fp, l);
   1452 		fdremove(p->p_fd, *fd);
   1453 		ffree(fp);
   1454 		return error;
   1455 	}
   1456 	fp->f_flag = FREAD|FWRITE;
   1457 	fp->f_type = DTYPE_VNODE;
   1458 	fp->f_ops = &vnops;
   1459 	fp->f_data = nd.ni_vp;
   1460 	VOP_UNLOCK(nd.ni_vp, 0);
   1461 	FILE_SET_MATURE(fp);
   1462 	FILE_UNUSE(fp, l);
   1463 	return 0;
   1464 }
   1465 
   1466 static void
   1467 pty_fill_ptmget(dev_t dev, int cfd, int sfd, void *data)
   1468 {
   1469 	struct ptmget *ptm = data;
   1470 	ptm->cfd = cfd;
   1471 	ptm->sfd = sfd;
   1472 	(void)pty_makename(ptm->cn, dev, 'p');
   1473 	(void)pty_makename(ptm->sn, dev, 't');
   1474 }
   1475 
   1476 void
   1477 /*ARGSUSED*/
   1478 ptmattach(int n)
   1479 {
   1480 	/* find the major and minor of the pty devices */
   1481 	if ((pts_major = cdevsw_lookup_major(&pts_cdevsw)) == -1)
   1482 		panic("ptmattach: Can't find pty slave in cdevsw");
   1483 }
   1484 
   1485 int
   1486 /*ARGSUSED*/
   1487 ptmopen(dev_t dev, int flag, int mode, struct lwp *l)
   1488 {
   1489 	int error;
   1490 	int fd;
   1491 
   1492 	switch(minor(dev)) {
   1493 	case 0:		/* /dev/ptmx */
   1494 		if ((error = pty_alloc_master(l, &fd, &dev)) != 0)
   1495 			return error;
   1496 		curlwp->l_dupfd = fd;
   1497 		return ENXIO;
   1498 	case 1:		/* /dev/ptm */
   1499 		return 0;
   1500 	default:
   1501 		return ENODEV;
   1502 	}
   1503 
   1504 }
   1505 
   1506 int
   1507 /*ARGSUSED*/
   1508 ptmclose(dev_t dev, int flag, int mode, struct lwp *l)
   1509 {
   1510 	return (0);
   1511 }
   1512 
   1513 int
   1514 /*ARGSUSED*/
   1515 ptmioctl(dev_t dev, u_long cmd, caddr_t data, int flag, struct lwp *l)
   1516 {
   1517 	int error;
   1518 	dev_t newdev;
   1519 	int cfd, sfd;
   1520 	struct file *fp;
   1521 	struct proc *p = l->l_proc;
   1522 
   1523 	error = 0;
   1524 	switch (cmd) {
   1525 	case TIOCPTMGET:
   1526 		if ((error = pty_alloc_master(l, &cfd, &newdev)) != 0)
   1527 			return error;
   1528 
   1529 		if ((error = pty_grant_slave(l, newdev)) != 0)
   1530 			goto bad;
   1531 
   1532 		if ((error = pty_alloc_slave(l, &sfd, newdev)) != 0)
   1533 			goto bad;
   1534 
   1535 		/* now, put the indices and names into struct ptmget */
   1536 		pty_fill_ptmget(newdev, cfd, sfd, data);
   1537 		return 0;
   1538 	default:
   1539 		DPRINTF(("ptmioctl EINVAL\n"));
   1540 		return EINVAL;
   1541 	}
   1542 bad:
   1543 	fp = fd_getfile(p->p_fd, cfd);
   1544 	fdremove(p->p_fd, cfd);
   1545 	ffree(fp);
   1546 	return error;
   1547 }
   1548 #endif
   1549