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