xref: /netbsd-src/sys/kern/tty_pty.c (revision abb0f93cd77b67f080613360c65701f85e5f5cfe)
1 /*	$NetBSD: tty_pty.c,v 1.119 2009/10/14 19:25:39 dsl 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  */
38 
39 #include <sys/cdefs.h>
40 __KERNEL_RCSID(0, "$NetBSD: tty_pty.c,v 1.119 2009/10/14 19:25:39 dsl Exp $");
41 
42 #include "opt_ptm.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/ioctl.h>
47 #include <sys/ioctl_compat.h>
48 #include <sys/proc.h>
49 #include <sys/tty.h>
50 #include <sys/stat.h>
51 #include <sys/file.h>
52 #include <sys/kernel.h>
53 #include <sys/vnode.h>
54 #include <sys/namei.h>
55 #include <sys/signalvar.h>
56 #include <sys/uio.h>
57 #include <sys/filedesc.h>
58 #include <sys/conf.h>
59 #include <sys/poll.h>
60 #include <sys/pty.h>
61 #include <sys/kauth.h>
62 
63 #define	DEFAULT_NPTYS		16	/* default number of initial ptys */
64 #define DEFAULT_MAXPTYS		992	/* default maximum number of ptys */
65 
66 #define BUFSIZ 100		/* Chunk size iomoved to/from user */
67 
68 struct	pt_softc {
69 	struct	tty *pt_tty;
70 	int	pt_flags;
71 	struct	selinfo pt_selr, pt_selw;
72 	u_char	pt_send;
73 	u_char	pt_ucntl;
74 };
75 
76 static struct pt_softc **pt_softc = NULL;	/* pty array */
77 static int maxptys = DEFAULT_MAXPTYS;	/* maximum number of ptys (sysctable) */
78 kmutex_t pt_softc_mutex;
79 int npty = 0;			/* for pstat -t */
80 
81 #define	PF_PKT		0x08		/* packet mode */
82 #define	PF_STOPPED	0x10		/* user told stopped */
83 #define	PF_REMOTE	0x20		/* remote and flow controlled input */
84 #define	PF_NOSTOP	0x40
85 #define PF_UCNTL	0x80		/* user control mode */
86 
87 void	ptyattach(int);
88 void	ptcwakeup(struct tty *, int);
89 void	ptsstart(struct tty *);
90 int	pty_maxptys(int, int);
91 
92 static struct pt_softc **ptyarralloc(int);
93 
94 dev_type_open(ptcopen);
95 dev_type_close(ptcclose);
96 dev_type_read(ptcread);
97 dev_type_write(ptcwrite);
98 dev_type_poll(ptcpoll);
99 dev_type_kqfilter(ptckqfilter);
100 
101 dev_type_open(ptsopen);
102 dev_type_close(ptsclose);
103 dev_type_read(ptsread);
104 dev_type_write(ptswrite);
105 dev_type_stop(ptsstop);
106 dev_type_poll(ptspoll);
107 
108 dev_type_ioctl(ptyioctl);
109 dev_type_tty(ptytty);
110 
111 const struct cdevsw ptc_cdevsw = {
112 	ptcopen, ptcclose, ptcread, ptcwrite, ptyioctl,
113 	nullstop, ptytty, ptcpoll, nommap, ptckqfilter, D_TTY
114 };
115 
116 const struct cdevsw pts_cdevsw = {
117 	ptsopen, ptsclose, ptsread, ptswrite, ptyioctl,
118 	ptsstop, ptytty, ptspoll, nommap, ttykqfilter, D_TTY
119 };
120 
121 #if defined(pmax)
122 const struct cdevsw ptc_ultrix_cdevsw = {
123 	ptcopen, ptcclose, ptcread, ptcwrite, ptyioctl,
124 	nullstop, ptytty, ptcpoll, nommap, ptckqfilter, D_TTY
125 };
126 
127 const struct cdevsw pts_ultrix_cdevsw = {
128 	ptsopen, ptsclose, ptsread, ptswrite, ptyioctl,
129 	ptsstop, ptytty, ptspoll, nommap, ttykqfilter, D_TTY
130 };
131 #endif /* defined(pmax) */
132 
133 /*
134  * Check if a pty is free to use.
135  */
136 int
137 pty_isfree(int minor, int lock)
138 {
139 	struct pt_softc *pt = pt_softc[minor];
140 	if (lock)
141 		mutex_enter(&pt_softc_mutex);
142 	minor = pt == NULL || pt->pt_tty == NULL ||
143 	    pt->pt_tty->t_oproc == NULL;
144 	if (lock)
145 		mutex_exit(&pt_softc_mutex);
146 	return minor;
147 }
148 
149 /*
150  * Allocate and zero array of nelem elements.
151  */
152 static struct pt_softc **
153 ptyarralloc(int nelem)
154 {
155 	struct pt_softc **pt;
156 	nelem += 10;
157 	pt = kmem_zalloc(nelem * sizeof(*pt), KM_SLEEP);
158 	return pt;
159 }
160 
161 static void
162 ptyarrfree(struct pt_softc **pt, int nelem)
163 {
164 
165 	nelem += 10;
166 	kmem_free(pt, nelem * sizeof(*pt));
167 }
168 
169 /*
170  * Check if the minor is correct and ensure necessary structures
171  * are properly allocated.
172  */
173 int
174 pty_check(int ptn)
175 {
176 	struct pt_softc *pti;
177 
178 	if (ptn >= npty) {
179 		struct pt_softc **newpt, **oldpt;
180 		int newnpty;
181 		int oldnpty;
182 
183 		/* check if the requested pty can be granted */
184 		if (ptn >= maxptys) {
185 	    limit_reached:
186 			tablefull("pty", "increase kern.maxptys");
187 			return (ENXIO);
188 		}
189 
190 		/* Allocate a larger pty array */
191 		for (newnpty = npty; newnpty <= ptn;)
192 			newnpty *= 2;
193 		if (newnpty > maxptys)
194 			newnpty = maxptys;
195 		newpt = ptyarralloc(newnpty);
196 
197 		/*
198 		 * Now grab the pty array mutex - we need to ensure
199 		 * that the pty array is consistent while copying it's
200 		 * content to newly allocated, larger space; we also
201 		 * need to be safe against pty_maxptys().
202 		 */
203 		mutex_enter(&pt_softc_mutex);
204 
205 		if (newnpty >= maxptys) {
206 			/* limit cut away beneath us... */
207 			if (ptn >= maxptys) {
208 				mutex_exit(&pt_softc_mutex);
209 				ptyarrfree(newpt, newnpty);
210 				goto limit_reached;
211 			}
212 			newnpty = maxptys;
213 		}
214 
215 		/*
216 		 * If the pty array was not enlarged while we were waiting
217 		 * for mutex, copy current contents of pt_softc[] to newly
218 		 * allocated array and start using the new bigger array.
219 		 */
220 		if (newnpty > npty) {
221 			memcpy(newpt, pt_softc, npty*sizeof(struct pt_softc *));
222 			oldpt = pt_softc;
223 			oldnpty = npty;
224 			pt_softc = newpt;
225 			npty = newnpty;
226 		} else {
227 			/* was enlarged when waited for lock, free new space */
228 			oldpt = newpt;
229 			oldnpty = newnpty;
230 		}
231 
232 		mutex_exit(&pt_softc_mutex);
233 		ptyarrfree(oldpt, oldnpty);
234 	}
235 
236 	/*
237 	 * If the entry is not yet allocated, allocate one. The mutex is
238 	 * needed so that the state of pt_softc[] array is consistant
239 	 * in case it has been lengthened above.
240 	 */
241 	if (!pt_softc[ptn]) {
242 		pti = kmem_zalloc(sizeof(*pti), KM_SLEEP);
243 
244 		selinit(&pti->pt_selr);
245 		selinit(&pti->pt_selw);
246 		pti->pt_tty = ttymalloc();
247 
248 		mutex_enter(&pt_softc_mutex);
249 
250 		/*
251 		 * Check the entry again - it might have been
252 		 * added while we were waiting for mutex.
253 		 */
254 		if (pt_softc[ptn]) {
255 			mutex_exit(&pt_softc_mutex);
256 			ttyfree(pti->pt_tty);
257 			seldestroy(&pti->pt_selr);
258 			seldestroy(&pti->pt_selw);
259 			kmem_free(pti, sizeof(*pti));
260 			return (0);
261 		}
262 		tty_attach(pti->pt_tty);
263 		pt_softc[ptn] = pti;
264 
265 		mutex_exit(&pt_softc_mutex);
266 	}
267 
268 	return (0);
269 }
270 
271 /*
272  * Set maxpty in thread-safe way. Returns 0 in case of error, otherwise
273  * new value of maxptys.
274  */
275 int
276 pty_maxptys(int newmax, int set)
277 {
278 	if (!set)
279 		return (maxptys);
280 
281 	/*
282 	 * We have to grab the pt_softc lock, so that we would pick correct
283 	 * value of npty (might be modified in pty_check()).
284 	 */
285 	mutex_enter(&pt_softc_mutex);
286 
287 	/*
288 	 * The value cannot be set to value lower than the highest pty
289 	 * number ever allocated.
290 	 */
291 	if (newmax >= npty)
292 		maxptys = newmax;
293 	else
294 		newmax = 0;
295 
296 	mutex_exit(&pt_softc_mutex);
297 
298 	return newmax;
299 }
300 
301 /*
302  * Establish n (or default if n is 1) ptys in the system.
303  */
304 void
305 ptyattach(int n)
306 {
307 
308 	mutex_init(&pt_softc_mutex, MUTEX_DEFAULT, IPL_NONE);
309 
310 	/* maybe should allow 0 => none? */
311 	if (n <= 1)
312 		n = DEFAULT_NPTYS;
313 	pt_softc = ptyarralloc(n);
314 	npty = n;
315 #ifndef NO_DEV_PTM
316 	ptmattach(1);
317 #endif
318 }
319 
320 /*ARGSUSED*/
321 int
322 ptsopen(dev_t dev, int flag, int devtype, struct lwp *l)
323 {
324 	struct pt_softc *pti;
325 	struct tty *tp;
326 	int error;
327 	int ptn = minor(dev);
328 
329 	if ((error = pty_check(ptn)) != 0)
330 		return (error);
331 
332 	mutex_spin_enter(&tty_lock);
333 	pti = pt_softc[ptn];
334 	tp = pti->pt_tty;
335 	if (!ISSET(tp->t_state, TS_ISOPEN)) {
336 		ttychars(tp);		/* Set up default chars */
337 		tp->t_iflag = TTYDEF_IFLAG;
338 		tp->t_oflag = TTYDEF_OFLAG;
339 		tp->t_lflag = TTYDEF_LFLAG;
340 		tp->t_cflag = TTYDEF_CFLAG;
341 		tp->t_ispeed = tp->t_ospeed = TTYDEF_SPEED;
342 		ttsetwater(tp);		/* would be done in xxparam() */
343 	} else if (kauth_authorize_device_tty(l->l_cred, KAUTH_DEVICE_TTY_OPEN,
344 	    tp) != 0) {
345 		mutex_spin_exit(&tty_lock);
346 		return (EBUSY);
347 	}
348 	if (tp->t_oproc)			/* Ctrlr still around. */
349 		SET(tp->t_state, TS_CARR_ON);
350 	if (!ISSET(flag, O_NONBLOCK)) {
351 		while (!ISSET(tp->t_state, TS_CARR_ON)) {
352 			tp->t_wopen++;
353 			error = ttysleep(tp, &tp->t_rawcv, true, 0);
354 			tp->t_wopen--;
355 			if (error) {
356 				mutex_spin_exit(&tty_lock);
357 				return (error);
358 			}
359 		}
360 	}
361 	mutex_spin_exit(&tty_lock);
362 	error = (*tp->t_linesw->l_open)(dev, tp);
363 	ptcwakeup(tp, FREAD|FWRITE);
364 	return (error);
365 }
366 
367 int
368 ptsclose(dev_t dev, int flag, int mode, struct lwp *l)
369 {
370 	struct pt_softc *pti = pt_softc[minor(dev)];
371 	struct tty *tp = pti->pt_tty;
372 	int error;
373 
374 	error = (*tp->t_linesw->l_close)(tp, flag);
375 	error |= ttyclose(tp);
376 	ptcwakeup(tp, FREAD|FWRITE);
377 	return (error);
378 }
379 
380 int
381 ptsread(dev_t dev, struct uio *uio, int flag)
382 {
383 	struct proc *p = curproc;
384 	struct pt_softc *pti = pt_softc[minor(dev)];
385 	struct tty *tp = pti->pt_tty;
386 	int error = 0;
387 	int cc, c;
388 
389 again:
390 	if (pti->pt_flags & PF_REMOTE) {
391 		mutex_spin_enter(&tty_lock);
392 		while (isbackground(p, tp)) {	/* XXXSMP */
393 			if (sigismasked(curlwp, SIGTTIN) ||
394 			    p->p_pgrp->pg_jobc == 0 ||
395 			    p->p_lflag & PL_PPWAIT) {
396 				mutex_spin_exit(&tty_lock);
397 				return (EIO);
398 			}
399 			ttysig(tp, TTYSIG_PG1, SIGTTIN);
400 			error = ttysleep(tp, &lbolt, true, 0);
401 			if (error) {
402 				mutex_spin_exit(&tty_lock);
403 				return (error);
404 			}
405 		}
406 		if (tp->t_canq.c_cc == 0) {
407 			if (flag & IO_NDELAY) {
408 				mutex_spin_exit(&tty_lock);
409 				return (EWOULDBLOCK);
410 			}
411 			error = ttysleep(tp, &tp->t_cancv, true, 0);
412 			mutex_spin_exit(&tty_lock);
413 			if (error)
414 				return (error);
415 			goto again;
416 		}
417 		while(error == 0 && tp->t_canq.c_cc > 1 && uio->uio_resid > 0) {
418 			c = getc(&tp->t_canq);
419 			mutex_spin_exit(&tty_lock);
420 			error = ureadc(c, uio);
421 			mutex_spin_enter(&tty_lock);
422 			/* Re-check terminal state here? */
423 		}
424 		if (tp->t_canq.c_cc == 1)
425 			(void) getc(&tp->t_canq);
426 		cc = tp->t_canq.c_cc;
427 		mutex_spin_exit(&tty_lock);
428 		if (cc)
429 			return (error);
430 	} else if (tp->t_oproc)
431 		error = (*tp->t_linesw->l_read)(tp, uio, flag);
432 	ptcwakeup(tp, FWRITE);
433 	return (error);
434 }
435 
436 /*
437  * Write to pseudo-tty.
438  * Wakeups of controlling tty will happen
439  * indirectly, when tty driver calls ptsstart.
440  */
441 int
442 ptswrite(dev_t dev, struct uio *uio, int flag)
443 {
444 	struct pt_softc *pti = pt_softc[minor(dev)];
445 	struct tty *tp = pti->pt_tty;
446 
447 	if (tp->t_oproc == 0)
448 		return (EIO);
449 	return ((*tp->t_linesw->l_write)(tp, uio, flag));
450 }
451 
452 /*
453  * Poll pseudo-tty.
454  */
455 int
456 ptspoll(dev_t dev, int events, struct lwp *l)
457 {
458 	struct pt_softc *pti = pt_softc[minor(dev)];
459 	struct tty *tp = pti->pt_tty;
460 
461 	if (tp->t_oproc == 0)
462 		return (POLLHUP);
463 
464 	return ((*tp->t_linesw->l_poll)(tp, events, l));
465 }
466 
467 /*
468  * Start output on pseudo-tty.
469  * Wake up process polling or sleeping for input from controlling tty.
470  */
471 void
472 ptsstart(struct tty *tp)
473 {
474 	struct pt_softc *pti = pt_softc[minor(tp->t_dev)];
475 
476 	KASSERT(mutex_owned(&tty_lock));
477 
478 	if (ISSET(tp->t_state, TS_TTSTOP))
479 		return;
480 	if (pti->pt_flags & PF_STOPPED) {
481 		pti->pt_flags &= ~PF_STOPPED;
482 		pti->pt_send = TIOCPKT_START;
483 	}
484 
485 	selnotify(&pti->pt_selr, 0, NOTE_SUBMIT);
486 	cv_broadcast(&tp->t_outcvf);
487 }
488 
489 /*
490  * Stop output.
491  */
492 void
493 ptsstop(struct tty *tp, int flush)
494 {
495 	struct pt_softc *pti = pt_softc[minor(tp->t_dev)];
496 
497 	KASSERT(mutex_owned(&tty_lock));
498 
499 	/* note: FLUSHREAD and FLUSHWRITE already ok */
500 	if (flush == 0) {
501 		flush = TIOCPKT_STOP;
502 		pti->pt_flags |= PF_STOPPED;
503 	} else
504 		pti->pt_flags &= ~PF_STOPPED;
505 	pti->pt_send |= flush;
506 
507 	/* change of perspective */
508 	if (flush & FREAD) {
509 		selnotify(&pti->pt_selw, 0, NOTE_SUBMIT);
510 		cv_broadcast(&tp->t_rawcvf);
511 	}
512 	if (flush & FWRITE) {
513 		selnotify(&pti->pt_selr, 0, NOTE_SUBMIT);
514 		cv_broadcast(&tp->t_outcvf);
515 	}
516 }
517 
518 void
519 ptcwakeup(struct tty *tp, int flag)
520 {
521 	struct pt_softc *pti = pt_softc[minor(tp->t_dev)];
522 
523 	mutex_spin_enter(&tty_lock);
524 	if (flag & FREAD) {
525 		selnotify(&pti->pt_selr, 0, NOTE_SUBMIT);
526 		cv_broadcast(&tp->t_outcvf);
527 	}
528 	if (flag & FWRITE) {
529 		selnotify(&pti->pt_selw, 0, NOTE_SUBMIT);
530 		cv_broadcast(&tp->t_rawcvf);
531 	}
532 	mutex_spin_exit(&tty_lock);
533 }
534 
535 /*ARGSUSED*/
536 int
537 ptcopen(dev_t dev, int flag, int devtype, struct lwp *l)
538 {
539 	struct pt_softc *pti;
540 	struct tty *tp;
541 	int error;
542 	int ptn = minor(dev);
543 
544 	if ((error = pty_check(ptn)) != 0)
545 		return (error);
546 
547 	pti = pt_softc[ptn];
548 	tp = pti->pt_tty;
549 
550 	mutex_spin_enter(&tty_lock);
551 	if (tp->t_oproc) {
552 		mutex_spin_exit(&tty_lock);
553 		return (EIO);
554 	}
555 	tp->t_oproc = ptsstart;
556 	mutex_spin_exit(&tty_lock);
557 	(void)(*tp->t_linesw->l_modem)(tp, 1);
558 	CLR(tp->t_lflag, EXTPROC);
559 	pti->pt_flags = 0;
560 	pti->pt_send = 0;
561 	pti->pt_ucntl = 0;
562 	return (0);
563 }
564 
565 /*ARGSUSED*/
566 int
567 ptcclose(dev_t dev, int flag, int devtype, struct lwp *l)
568 {
569 	struct pt_softc *pti = pt_softc[minor(dev)];
570 	struct tty *tp = pti->pt_tty;
571 
572 	(void)(*tp->t_linesw->l_modem)(tp, 0);
573 	mutex_spin_enter(&tty_lock);
574 	CLR(tp->t_state, TS_CARR_ON);
575 	tp->t_oproc = 0;		/* mark closed */
576 	mutex_spin_exit(&tty_lock);
577 	return (0);
578 }
579 
580 int
581 ptcread(dev_t dev, struct uio *uio, int flag)
582 {
583 	struct pt_softc *pti = pt_softc[minor(dev)];
584 	struct tty *tp = pti->pt_tty;
585 	u_char bf[BUFSIZ];
586 	int error = 0, cc;
587 	int c;
588 
589 	if (uio->uio_resid <= 0)
590 		return EINVAL;
591 
592 	/*
593 	 * We want to block until the slave
594 	 * is open, and there's something to read;
595 	 * but if we lost the slave or we're NBIO,
596 	 * then return the appropriate error instead.
597 	 */
598 	mutex_spin_enter(&tty_lock);
599 	for (;;) {
600 		if (ISSET(tp->t_state, TS_ISOPEN)) {
601 			if (pti->pt_flags & PF_PKT && (c = pti->pt_send)) {
602 				pti->pt_send = 0;
603 				mutex_spin_exit(&tty_lock);
604 				error = ureadc(c, uio);
605 				if (error)
606 					return (error);
607 				/*
608 				 * Since we don't have the tty locked, there's
609 				 * a risk of messing up `t_termios'. This is
610 				 * relevant only if the tty got closed and then
611 				 * opened again while we were out uiomoving.
612 				 */
613 				if (pti->pt_send & TIOCPKT_IOCTL) {
614 					cc = min(uio->uio_resid,
615 						sizeof(tp->t_termios));
616 					uiomove((void *) &tp->t_termios,
617 						cc, uio);
618 				}
619 				return (0);
620 			}
621 			if (pti->pt_flags & PF_UCNTL && (c = pti->pt_ucntl)) {
622 				pti->pt_ucntl = 0;
623 				mutex_spin_exit(&tty_lock);
624 				error = ureadc(c, uio);
625 				if (error)
626 					return (error);
627 				return (0);
628 			}
629 			if (tp->t_outq.c_cc && !ISSET(tp->t_state, TS_TTSTOP))
630 				break;
631 		}
632 		if (!ISSET(tp->t_state, TS_CARR_ON)) {
633 			error = 0;	/* EOF */
634 			goto out;
635 		}
636 		if (flag & IO_NDELAY) {
637 			error = EWOULDBLOCK;
638 			goto out;
639 		}
640 		error = cv_wait_sig(&tp->t_outcvf, &tty_lock);
641 		if (error)
642 			goto out;
643 	}
644 
645 	if (pti->pt_flags & (PF_PKT|PF_UCNTL)) {
646 		mutex_spin_exit(&tty_lock);
647 		error = ureadc(0, uio);
648 		mutex_spin_enter(&tty_lock);
649 		if (error == 0 && !ISSET(tp->t_state, TS_ISOPEN))
650 			error = EIO;
651 	}
652 	while (uio->uio_resid > 0 && error == 0) {
653 		cc = q_to_b(&tp->t_outq, bf, min(uio->uio_resid, BUFSIZ));
654 		if (cc <= 0)
655 			break;
656 		mutex_spin_exit(&tty_lock);
657 		error = uiomove(bf, cc, uio);
658 		mutex_spin_enter(&tty_lock);
659 		if (error == 0 && !ISSET(tp->t_state, TS_ISOPEN))
660 			error = EIO;
661 	}
662 	ttypull(tp);
663 out:
664 	mutex_spin_exit(&tty_lock);
665 	return (error);
666 }
667 
668 
669 int
670 ptcwrite(dev_t dev, struct uio *uio, int flag)
671 {
672 	struct pt_softc *pti = pt_softc[minor(dev)];
673 	struct tty *tp = pti->pt_tty;
674 	u_char *cp = NULL;
675 	int cc = 0;
676 	u_char locbuf[BUFSIZ];
677 	int cnt = 0;
678 	int error = 0;
679 
680 again:
681 	mutex_spin_enter(&tty_lock);
682 	if (!ISSET(tp->t_state, TS_ISOPEN))
683 		goto block;
684 	if (pti->pt_flags & PF_REMOTE) {
685 		if (tp->t_canq.c_cc)
686 			goto block;
687 		while (uio->uio_resid > 0 && tp->t_canq.c_cc < TTYHOG - 1) {
688 			if (cc == 0) {
689 				cc = min(uio->uio_resid, BUFSIZ);
690 				cc = min(cc, TTYHOG - 1 - tp->t_canq.c_cc);
691 				cp = locbuf;
692 				mutex_spin_exit(&tty_lock);
693 				error = uiomove((void *)cp, cc, uio);
694 				if (error)
695 					return (error);
696 				mutex_spin_enter(&tty_lock);
697 				/* check again for safety */
698 				if (!ISSET(tp->t_state, TS_ISOPEN)) {
699 					/*
700 					 * adjust for data copied in but not
701 					 * written
702 					 */
703 					uio->uio_resid += cc;
704 					error = EIO;
705 					goto out;
706 				}
707 			}
708 			if (cc)
709 				(void) b_to_q(cp, cc, &tp->t_canq);
710 			cc = 0;
711 		}
712 		(void) putc(0, &tp->t_canq);
713 		ttwakeup(tp);
714 		cv_broadcast(&tp->t_cancv);
715 		error = 0;
716 		goto out;
717 	}
718 	while (uio->uio_resid > 0) {
719 		if (cc == 0) {
720 			cc = min(uio->uio_resid, BUFSIZ);
721 			cp = locbuf;
722 			mutex_spin_exit(&tty_lock);
723 			error = uiomove((void *)cp, cc, uio);
724 			if (error)
725 				return (error);
726 			mutex_spin_enter(&tty_lock);
727 			/* check again for safety */
728 			if (!ISSET(tp->t_state, TS_ISOPEN)) {
729 				/* adjust for data copied in but not written */
730 				uio->uio_resid += cc;
731 				error = EIO;
732 				goto out;
733 			}
734 		}
735 		while (cc > 0) {
736 			if ((tp->t_rawq.c_cc + tp->t_canq.c_cc) >= TTYHOG - 2 &&
737 			   (tp->t_canq.c_cc > 0 || !ISSET(tp->t_lflag, ICANON))) {
738 				cv_broadcast(&tp->t_rawcv);
739 				goto block;
740 			}
741 			/* XXX - should change l_rint to be called with lock
742 			 *	 see also tty.c:ttyinput_wlock()
743 			 */
744 			mutex_spin_exit(&tty_lock);
745 			(*tp->t_linesw->l_rint)(*cp++, tp);
746 			mutex_spin_enter(&tty_lock);
747 			cnt++;
748 			cc--;
749 		}
750 		cc = 0;
751 	}
752 	error = 0;
753 	goto out;
754 
755 block:
756 	/*
757 	 * Come here to wait for slave to open, for space
758 	 * in outq, or space in rawq.
759 	 */
760 	if (!ISSET(tp->t_state, TS_CARR_ON)) {
761 		/* adjust for data copied in but not written */
762 		uio->uio_resid += cc;
763 		error = EIO;
764 		goto out;
765 	}
766 	if (flag & IO_NDELAY) {
767 		/* adjust for data copied in but not written */
768 		uio->uio_resid += cc;
769 		error = cnt == 0 ? EWOULDBLOCK : 0;
770 		goto out;
771 	}
772 	error = cv_wait_sig(&tp->t_rawcvf, &tty_lock);
773 	mutex_spin_exit(&tty_lock);
774 	if (error) {
775 		/* adjust for data copied in but not written */
776 		uio->uio_resid += cc;
777 		return (error);
778 	}
779 	goto again;
780 
781 out:
782 	mutex_spin_exit(&tty_lock);
783 	return (error);
784 }
785 
786 int
787 ptcpoll(dev_t dev, int events, struct lwp *l)
788 {
789 	struct pt_softc *pti = pt_softc[minor(dev)];
790 	struct tty *tp = pti->pt_tty;
791 	int revents = 0;
792 
793 	mutex_spin_enter(&tty_lock);
794 
795 	if (events & (POLLIN | POLLRDNORM))
796 		if (ISSET(tp->t_state, TS_ISOPEN) &&
797 		    ((tp->t_outq.c_cc > 0 && !ISSET(tp->t_state, TS_TTSTOP)) ||
798 		     ((pti->pt_flags & PF_PKT) && pti->pt_send) ||
799 		     ((pti->pt_flags & PF_UCNTL) && pti->pt_ucntl)))
800 			revents |= events & (POLLIN | POLLRDNORM);
801 
802 	if (events & (POLLOUT | POLLWRNORM))
803 		if (ISSET(tp->t_state, TS_ISOPEN) &&
804 		    ((pti->pt_flags & PF_REMOTE) ?
805 		     (tp->t_canq.c_cc == 0) :
806 		     ((tp->t_rawq.c_cc + tp->t_canq.c_cc < TTYHOG-2) ||
807 		      (tp->t_canq.c_cc == 0 && ISSET(tp->t_lflag, ICANON)))))
808 			revents |= events & (POLLOUT | POLLWRNORM);
809 
810 	if (events & POLLHUP)
811 		if (!ISSET(tp->t_state, TS_CARR_ON))
812 			revents |= POLLHUP;
813 
814 	if (revents == 0) {
815 		if (events & (POLLIN | POLLHUP | POLLRDNORM))
816 			selrecord(l, &pti->pt_selr);
817 
818 		if (events & (POLLOUT | POLLWRNORM))
819 			selrecord(l, &pti->pt_selw);
820 	}
821 
822 	mutex_spin_exit(&tty_lock);
823 
824 	return (revents);
825 }
826 
827 static void
828 filt_ptcrdetach(struct knote *kn)
829 {
830 	struct pt_softc *pti;
831 	struct tty	*tp;
832 
833 	pti = kn->kn_hook;
834 	tp = pti->pt_tty;
835 
836 	mutex_spin_enter(&tty_lock);
837 	SLIST_REMOVE(&pti->pt_selr.sel_klist, kn, knote, kn_selnext);
838 	mutex_spin_exit(&tty_lock);
839 }
840 
841 static int
842 filt_ptcread(struct knote *kn, long hint)
843 {
844 	struct pt_softc *pti;
845 	struct tty	*tp;
846 	int canread;
847 
848 	pti = kn->kn_hook;
849 	tp = pti->pt_tty;
850 
851 	if ((hint & NOTE_SUBMIT) == 0) {
852 		mutex_spin_enter(&tty_lock);
853 	}
854 
855 	canread = (ISSET(tp->t_state, TS_ISOPEN) &&
856 		    ((tp->t_outq.c_cc > 0 && !ISSET(tp->t_state, TS_TTSTOP)) ||
857 		     ((pti->pt_flags & PF_PKT) && pti->pt_send) ||
858 		     ((pti->pt_flags & PF_UCNTL) && pti->pt_ucntl)));
859 
860 	if (canread) {
861 		/*
862 		 * c_cc is number of characters after output post-processing;
863 		 * the amount of data actually read(2) depends on
864 		 * setting of input flags for the terminal.
865 		 */
866 		kn->kn_data = tp->t_outq.c_cc;
867 		if (((pti->pt_flags & PF_PKT) && pti->pt_send) ||
868 		    ((pti->pt_flags & PF_UCNTL) && pti->pt_ucntl))
869 			kn->kn_data++;
870 	}
871 
872 	if ((hint & NOTE_SUBMIT) == 0) {
873 		mutex_spin_exit(&tty_lock);
874 	}
875 
876 	return (canread);
877 }
878 
879 static void
880 filt_ptcwdetach(struct knote *kn)
881 {
882 	struct pt_softc *pti;
883 	struct tty	*tp;
884 
885 	pti = kn->kn_hook;
886 	tp = pti->pt_tty;
887 
888 	mutex_spin_enter(&tty_lock);
889 	SLIST_REMOVE(&pti->pt_selw.sel_klist, kn, knote, kn_selnext);
890 	mutex_spin_exit(&tty_lock);
891 }
892 
893 static int
894 filt_ptcwrite(struct knote *kn, long hint)
895 {
896 	struct pt_softc *pti;
897 	struct tty	*tp;
898 	int canwrite;
899 	int nwrite;
900 
901 	pti = kn->kn_hook;
902 	tp = pti->pt_tty;
903 
904 	if ((hint & NOTE_SUBMIT) == 0) {
905 		mutex_spin_enter(&tty_lock);
906 	}
907 
908 	canwrite = (ISSET(tp->t_state, TS_ISOPEN) &&
909 		    ((pti->pt_flags & PF_REMOTE) ?
910 		     (tp->t_canq.c_cc == 0) :
911 		     ((tp->t_rawq.c_cc + tp->t_canq.c_cc < TTYHOG-2) ||
912 		      (tp->t_canq.c_cc == 0 && ISSET(tp->t_lflag, ICANON)))));
913 
914 	if (canwrite) {
915 		if (pti->pt_flags & PF_REMOTE)
916 			nwrite = tp->t_canq.c_cn;
917 		else {
918 			/* this is guaranteed to be > 0 due to above check */
919 			nwrite = tp->t_canq.c_cn
920 				- (tp->t_rawq.c_cc + tp->t_canq.c_cc);
921 		}
922 		kn->kn_data = nwrite;
923 	}
924 
925 	if ((hint & NOTE_SUBMIT) == 0) {
926 		mutex_spin_exit(&tty_lock);
927 	}
928 
929 	return (canwrite);
930 }
931 
932 static const struct filterops ptcread_filtops =
933 	{ 1, NULL, filt_ptcrdetach, filt_ptcread };
934 static const struct filterops ptcwrite_filtops =
935 	{ 1, NULL, filt_ptcwdetach, filt_ptcwrite };
936 
937 int
938 ptckqfilter(dev_t dev, struct knote *kn)
939 {
940 	struct pt_softc *pti = pt_softc[minor(dev)];
941 	struct klist	*klist;
942 
943 	switch (kn->kn_filter) {
944 	case EVFILT_READ:
945 		klist = &pti->pt_selr.sel_klist;
946 		kn->kn_fop = &ptcread_filtops;
947 		break;
948 	case EVFILT_WRITE:
949 		klist = &pti->pt_selw.sel_klist;
950 		kn->kn_fop = &ptcwrite_filtops;
951 		break;
952 	default:
953 		return (EINVAL);
954 	}
955 
956 	kn->kn_hook = pti;
957 
958 	mutex_spin_enter(&tty_lock);
959 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
960 	mutex_spin_exit(&tty_lock);
961 
962 	return (0);
963 }
964 
965 struct tty *
966 ptytty(dev_t dev)
967 {
968 	struct pt_softc *pti = pt_softc[minor(dev)];
969 	struct tty *tp = pti->pt_tty;
970 
971 	return (tp);
972 }
973 
974 /*ARGSUSED*/
975 int
976 ptyioctl(dev_t dev, u_long cmd, void *data, int flag, struct lwp *l)
977 {
978 	struct pt_softc *pti = pt_softc[minor(dev)];
979 	struct tty *tp = pti->pt_tty;
980 	const struct cdevsw *cdev;
981 	u_char *cc = tp->t_cc;
982 	int stop, error, sig;
983 
984 	/*
985 	 * IF CONTROLLER STTY THEN MUST FLUSH TO PREVENT A HANG.
986 	 * ttywflush(tp) will hang if there are characters in the outq.
987 	 */
988 	if (cmd == TIOCEXT) {
989 		/*
990 		 * When the EXTPROC bit is being toggled, we need
991 		 * to send an TIOCPKT_IOCTL if the packet driver
992 		 * is turned on.
993 		 */
994 		if (*(int *)data) {
995 			if (pti->pt_flags & PF_PKT) {
996 				pti->pt_send |= TIOCPKT_IOCTL;
997 				ptcwakeup(tp, FREAD);
998 			}
999 			SET(tp->t_lflag, EXTPROC);
1000 		} else {
1001 			if (ISSET(tp->t_lflag, EXTPROC) &&
1002 			    (pti->pt_flags & PF_PKT)) {
1003 				pti->pt_send |= TIOCPKT_IOCTL;
1004 				ptcwakeup(tp, FREAD);
1005 			}
1006 			CLR(tp->t_lflag, EXTPROC);
1007 		}
1008 		return(0);
1009 	}
1010 
1011 #ifndef NO_DEV_PTM
1012 	/* Allow getting the name from either the master or the slave */
1013 	if (cmd == TIOCPTSNAME)
1014 		return pty_fill_ptmget(l, dev, -1, -1, data);
1015 #endif
1016 
1017 	cdev = cdevsw_lookup(dev);
1018 	if (cdev != NULL && cdev->d_open == ptcopen)
1019 		switch (cmd) {
1020 #ifndef NO_DEV_PTM
1021 		case TIOCGRANTPT:
1022 			return pty_grant_slave(l, dev);
1023 #endif
1024 
1025 		case TIOCGPGRP:
1026 			/*
1027 			 * We avoid calling ttioctl on the controller since,
1028 			 * in that case, tp must be the controlling terminal.
1029 			 */
1030 			*(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : 0;
1031 			return (0);
1032 
1033 		case TIOCPKT:
1034 			if (*(int *)data) {
1035 				if (pti->pt_flags & PF_UCNTL)
1036 					return (EINVAL);
1037 				pti->pt_flags |= PF_PKT;
1038 			} else
1039 				pti->pt_flags &= ~PF_PKT;
1040 			return (0);
1041 
1042 		case TIOCUCNTL:
1043 			if (*(int *)data) {
1044 				if (pti->pt_flags & PF_PKT)
1045 					return (EINVAL);
1046 				pti->pt_flags |= PF_UCNTL;
1047 			} else
1048 				pti->pt_flags &= ~PF_UCNTL;
1049 			return (0);
1050 
1051 		case TIOCREMOTE:
1052 			if (*(int *)data)
1053 				pti->pt_flags |= PF_REMOTE;
1054 			else
1055 				pti->pt_flags &= ~PF_REMOTE;
1056 			mutex_spin_enter(&tty_lock);
1057 			ttyflush(tp, FREAD|FWRITE);
1058 			mutex_spin_exit(&tty_lock);
1059 			return (0);
1060 
1061 		case TIOCSETP:
1062 		case TIOCSETN:
1063 		case TIOCSETD:
1064 		case TIOCSETA:
1065 		case TIOCSETAW:
1066 		case TIOCSETAF:
1067 			mutex_spin_enter(&tty_lock);
1068 			ndflush(&tp->t_outq, tp->t_outq.c_cc);
1069 			mutex_spin_exit(&tty_lock);
1070 			break;
1071 
1072 		case TIOCSIG:
1073 			sig = (int)(long)*(void **)data;
1074 			if (sig <= 0 || sig >= NSIG)
1075 				return (EINVAL);
1076 			mutex_spin_enter(&tty_lock);
1077 			if (!ISSET(tp->t_lflag, NOFLSH))
1078 				ttyflush(tp, FREAD|FWRITE);
1079 			tp->t_state |= TS_SIGINFO;
1080 			ttysig(tp, TTYSIG_PG1, sig);
1081 			mutex_spin_exit(&tty_lock);
1082 			return (0);
1083 
1084 		case FIONREAD:
1085 			mutex_spin_enter(&tty_lock);
1086 			*(int *)data = tp->t_outq.c_cc;
1087 			mutex_spin_exit(&tty_lock);
1088 			return (0);
1089 		}
1090 
1091 	error = (*tp->t_linesw->l_ioctl)(tp, cmd, data, flag, l);
1092 	if (error == EPASSTHROUGH)
1093 		 error = ttioctl(tp, cmd, data, flag, l);
1094 	if (error == EPASSTHROUGH) {
1095 		if (pti->pt_flags & PF_UCNTL &&
1096 		    (cmd & ~0xff) == UIOCCMD(0)) {
1097 			if (cmd & 0xff) {
1098 				pti->pt_ucntl = (u_char)cmd;
1099 				ptcwakeup(tp, FREAD);
1100 			}
1101 			return (0);
1102 		}
1103 	}
1104 	/*
1105 	 * If external processing and packet mode send ioctl packet.
1106 	 */
1107 	if (ISSET(tp->t_lflag, EXTPROC) && (pti->pt_flags & PF_PKT)) {
1108 		switch(cmd) {
1109 		case TIOCSETA:
1110 		case TIOCSETAW:
1111 		case TIOCSETAF:
1112 		case TIOCSETP:
1113 		case TIOCSETN:
1114 		case TIOCSETC:
1115 		case TIOCSLTC:
1116 		case TIOCLBIS:
1117 		case TIOCLBIC:
1118 		case TIOCLSET:
1119 			pti->pt_send |= TIOCPKT_IOCTL;
1120 			ptcwakeup(tp, FREAD);
1121 		default:
1122 			break;
1123 		}
1124 	}
1125 	stop = ISSET(tp->t_iflag, IXON) && CCEQ(cc[VSTOP], CTRL('s'))
1126 		&& CCEQ(cc[VSTART], CTRL('q'));
1127 	if (pti->pt_flags & PF_NOSTOP) {
1128 		if (stop) {
1129 			pti->pt_send &= ~TIOCPKT_NOSTOP;
1130 			pti->pt_send |= TIOCPKT_DOSTOP;
1131 			pti->pt_flags &= ~PF_NOSTOP;
1132 			ptcwakeup(tp, FREAD);
1133 		}
1134 	} else {
1135 		if (!stop) {
1136 			pti->pt_send &= ~TIOCPKT_DOSTOP;
1137 			pti->pt_send |= TIOCPKT_NOSTOP;
1138 			pti->pt_flags |= PF_NOSTOP;
1139 			ptcwakeup(tp, FREAD);
1140 		}
1141 	}
1142 	return (error);
1143 }
1144