xref: /freebsd/sys/kern/tty_pts.c (revision 30fd7f548767d82b41f7eb90a870f3406db3516f)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2008 Ed Schouten <ed@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Portions of this software were developed under sponsorship from Snow
8  * B.V., the Netherlands.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 /* Add compatibility bits for FreeBSD. */
36 #define PTS_COMPAT
37 /* Add pty(4) compat bits. */
38 #define PTS_EXTERNAL
39 /* Add bits to make Linux binaries work. */
40 #define PTS_LINUX
41 
42 #include <sys/param.h>
43 #include <sys/lock.h>
44 #include <sys/condvar.h>
45 #include <sys/conf.h>
46 #include <sys/fcntl.h>
47 #include <sys/file.h>
48 #include <sys/filedesc.h>
49 #include <sys/filio.h>
50 #include <sys/kernel.h>
51 #include <sys/limits.h>
52 #include <sys/malloc.h>
53 #include <sys/mutex.h>
54 #include <sys/poll.h>
55 #include <sys/proc.h>
56 #include <sys/racct.h>
57 #include <sys/resourcevar.h>
58 #include <sys/serial.h>
59 #include <sys/stat.h>
60 #include <sys/syscall.h>
61 #include <sys/syscallsubr.h>
62 #include <sys/sysctl.h>
63 #include <sys/sysent.h>
64 #include <sys/sysproto.h>
65 #include <sys/systm.h>
66 #include <sys/tty.h>
67 #include <sys/ttycom.h>
68 #include <sys/uio.h>
69 #include <sys/user.h>
70 
71 #include <machine/stdarg.h>
72 
73 /*
74  * Our utmp(5) format is limited to 8-byte TTY line names.  This means
75  * we can at most allocate 1000 pseudo-terminals ("pts/999").  Allow
76  * users to increase this number, assuming they have manually increased
77  * UT_LINESIZE.
78  */
79 static struct unrhdr *pts_pool;
80 
81 static MALLOC_DEFINE(M_PTS, "pts", "pseudo tty device");
82 
83 /*
84  * Per-PTS structure.
85  *
86  * List of locks
87  * (t)	locked by tty_lock()
88  * (c)	const until freeing
89  */
90 struct pts_softc {
91 	int		pts_unit;	/* (c) Device unit number. */
92 	unsigned int	pts_flags;	/* (t) Device flags. */
93 #define	PTS_PKT		0x1	/* Packet mode. */
94 #define	PTS_FINISHED	0x2	/* Return errors on read()/write(). */
95 	char		pts_pkt;	/* (t) Unread packet mode data. */
96 
97 	struct cv	pts_inwait;	/* (t) Blocking write() on master. */
98 	struct selinfo	pts_inpoll;	/* (t) Select queue for write(). */
99 	struct cv	pts_outwait;	/* (t) Blocking read() on master. */
100 	struct selinfo	pts_outpoll;	/* (t) Select queue for read(). */
101 
102 #ifdef PTS_EXTERNAL
103 	struct cdev	*pts_cdev;	/* (c) Master device node. */
104 #endif /* PTS_EXTERNAL */
105 
106 	struct ucred	*pts_cred;	/* (c) Resource limit. */
107 };
108 
109 /*
110  * Controller-side file operations.
111  */
112 
113 static int
114 ptsdev_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
115     int flags, struct thread *td)
116 {
117 	struct tty *tp = fp->f_data;
118 	struct pts_softc *psc = tty_softc(tp);
119 	int error = 0;
120 	char pkt;
121 
122 	if (uio->uio_resid == 0)
123 		return (0);
124 
125 	tty_lock(tp);
126 
127 	for (;;) {
128 		/*
129 		 * Implement packet mode. When packet mode is turned on,
130 		 * the first byte contains a bitmask of events that
131 		 * occurred (start, stop, flush, window size, etc).
132 		 */
133 		if (psc->pts_flags & PTS_PKT && psc->pts_pkt) {
134 			pkt = psc->pts_pkt;
135 			psc->pts_pkt = 0;
136 			tty_unlock(tp);
137 
138 			error = ureadc(pkt, uio);
139 			return (error);
140 		}
141 
142 		/*
143 		 * Transmit regular data.
144 		 *
145 		 * XXX: We shouldn't use ttydisc_getc_poll()! Even
146 		 * though in this implementation, there is likely going
147 		 * to be data, we should just call ttydisc_getc_uio()
148 		 * and use its return value to sleep.
149 		 */
150 		if (ttydisc_getc_poll(tp)) {
151 			if (psc->pts_flags & PTS_PKT) {
152 				/*
153 				 * XXX: Small race. Fortunately PTY
154 				 * consumers aren't multithreaded.
155 				 */
156 
157 				tty_unlock(tp);
158 				error = ureadc(TIOCPKT_DATA, uio);
159 				if (error)
160 					return (error);
161 				tty_lock(tp);
162 			}
163 
164 			error = ttydisc_getc_uio(tp, uio);
165 			break;
166 		}
167 
168 		/* Maybe the device isn't used anyway. */
169 		if (psc->pts_flags & PTS_FINISHED)
170 			break;
171 
172 		/* Wait for more data. */
173 		if (fp->f_flag & O_NONBLOCK) {
174 			error = EWOULDBLOCK;
175 			break;
176 		}
177 		error = cv_wait_sig(&psc->pts_outwait, tp->t_mtx);
178 		if (error != 0)
179 			break;
180 	}
181 
182 	tty_unlock(tp);
183 
184 	return (error);
185 }
186 
187 static int
188 ptsdev_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
189     int flags, struct thread *td)
190 {
191 	struct tty *tp = fp->f_data;
192 	struct pts_softc *psc = tty_softc(tp);
193 	char ib[256], *ibstart;
194 	size_t iblen, rintlen;
195 	int error = 0;
196 
197 	if (uio->uio_resid == 0)
198 		return (0);
199 
200 	for (;;) {
201 		ibstart = ib;
202 		iblen = MIN(uio->uio_resid, sizeof ib);
203 		error = uiomove(ib, iblen, uio);
204 
205 		tty_lock(tp);
206 		if (error != 0) {
207 			iblen = 0;
208 			goto done;
209 		}
210 
211 		/*
212 		 * When possible, avoid the slow path. rint_bypass()
213 		 * copies all input to the input queue at once.
214 		 */
215 		MPASS(iblen > 0);
216 		do {
217 			rintlen = ttydisc_rint_simple(tp, ibstart, iblen);
218 			ibstart += rintlen;
219 			iblen -= rintlen;
220 			if (iblen == 0) {
221 				/* All data written. */
222 				break;
223 			}
224 
225 			/* Maybe the device isn't used anyway. */
226 			if (psc->pts_flags & PTS_FINISHED) {
227 				error = EIO;
228 				goto done;
229 			}
230 
231 			/* Wait for more data. */
232 			if (fp->f_flag & O_NONBLOCK) {
233 				error = EWOULDBLOCK;
234 				goto done;
235 			}
236 
237 			/* Wake up users on the slave side. */
238 			ttydisc_rint_done(tp);
239 			error = cv_wait_sig(&psc->pts_inwait, tp->t_mtx);
240 			if (error != 0)
241 				goto done;
242 		} while (iblen > 0);
243 
244 		if (uio->uio_resid == 0)
245 			break;
246 		tty_unlock(tp);
247 	}
248 
249 done:	ttydisc_rint_done(tp);
250 	tty_unlock(tp);
251 
252 	/*
253 	 * Don't account for the part of the buffer that we couldn't
254 	 * pass to the TTY.
255 	 */
256 	uio->uio_resid += iblen;
257 	return (error);
258 }
259 
260 static int
261 ptsdev_ioctl(struct file *fp, u_long cmd, void *data,
262     struct ucred *active_cred, struct thread *td)
263 {
264 	struct tty *tp = fp->f_data;
265 	struct pts_softc *psc = tty_softc(tp);
266 	int error = 0, sig;
267 
268 	switch (cmd) {
269 	case FIODTYPE:
270 		*(int *)data = D_TTY;
271 		return (0);
272 	case FIONBIO:
273 		/* This device supports non-blocking operation. */
274 		return (0);
275 	case FIONREAD:
276 		tty_lock(tp);
277 		if (psc->pts_flags & PTS_FINISHED) {
278 			/* Force read() to be called. */
279 			*(int *)data = 1;
280 		} else {
281 			*(int *)data = ttydisc_getc_poll(tp);
282 		}
283 		tty_unlock(tp);
284 		return (0);
285 	case FIODGNAME:
286 #ifdef COMPAT_FREEBSD32
287 	case FIODGNAME_32:
288 #endif
289 	{
290 		struct fiodgname_arg *fgn;
291 		const char *p;
292 		int i;
293 
294 		/* Reverse device name lookups, for ptsname() and ttyname(). */
295 		fgn = data;
296 		p = tty_devname(tp);
297 		i = strlen(p) + 1;
298 		if (i > fgn->len)
299 			return (EINVAL);
300 		return (copyout(p, fiodgname_buf_get_ptr(fgn, cmd), i));
301 	}
302 
303 	/*
304 	 * We need to implement TIOCGPGRP and TIOCGSID here again. When
305 	 * called on the pseudo-terminal master, it should not check if
306 	 * the terminal is the foreground terminal of the calling
307 	 * process.
308 	 *
309 	 * TIOCGETA is also implemented here. Various Linux PTY routines
310 	 * often call isatty(), which is implemented by tcgetattr().
311 	 */
312 #ifdef PTS_LINUX
313 	case TIOCGETA:
314 		/* Obtain terminal flags through tcgetattr(). */
315 		tty_lock(tp);
316 		*(struct termios*)data = tp->t_termios;
317 		tty_unlock(tp);
318 		return (0);
319 #endif /* PTS_LINUX */
320 	case TIOCSETAF:
321 	case TIOCSETAW:
322 		/*
323 		 * We must make sure we turn tcsetattr() calls of TCSAFLUSH and
324 		 * TCSADRAIN into something different. If an application would
325 		 * call TCSAFLUSH or TCSADRAIN on the master descriptor, it may
326 		 * deadlock waiting for all data to be read.
327 		 */
328 		cmd = TIOCSETA;
329 		break;
330 #if defined(PTS_COMPAT) || defined(PTS_LINUX)
331 	case TIOCGPTN:
332 		/*
333 		 * Get the device unit number.
334 		 */
335 		if (psc->pts_unit < 0)
336 			return (ENOTTY);
337 		*(unsigned int *)data = psc->pts_unit;
338 		return (0);
339 #endif /* PTS_COMPAT || PTS_LINUX */
340 	case TIOCGPGRP:
341 		/* Get the foreground process group ID. */
342 		tty_lock(tp);
343 		if (tp->t_pgrp != NULL)
344 			*(int *)data = tp->t_pgrp->pg_id;
345 		else
346 			*(int *)data = NO_PID;
347 		tty_unlock(tp);
348 		return (0);
349 	case TIOCGSID:
350 		/* Get the session leader process ID. */
351 		tty_lock(tp);
352 		if (tp->t_session == NULL)
353 			error = ENOTTY;
354 		else
355 			*(int *)data = tp->t_session->s_sid;
356 		tty_unlock(tp);
357 		return (error);
358 	case TIOCPTMASTER:
359 		/* Yes, we are a pseudo-terminal master. */
360 		return (0);
361 	case TIOCSIG:
362 		/* Signal the foreground process group. */
363 		sig = *(int *)data;
364 		if (sig < 1 || sig >= NSIG)
365 			return (EINVAL);
366 
367 		tty_lock(tp);
368 		tty_signal_pgrp(tp, sig);
369 		tty_unlock(tp);
370 		return (0);
371 	case TIOCPKT:
372 		/* Enable/disable packet mode. */
373 		tty_lock(tp);
374 		if (*(int *)data)
375 			psc->pts_flags |= PTS_PKT;
376 		else
377 			psc->pts_flags &= ~PTS_PKT;
378 		tty_unlock(tp);
379 		return (0);
380 	}
381 
382 	/* Just redirect this ioctl to the slave device. */
383 	tty_lock(tp);
384 	error = tty_ioctl(tp, cmd, data, fp->f_flag, td);
385 	tty_unlock(tp);
386 	if (error == ENOIOCTL)
387 		error = ENOTTY;
388 
389 	return (error);
390 }
391 
392 static int
393 ptsdev_poll(struct file *fp, int events, struct ucred *active_cred,
394     struct thread *td)
395 {
396 	struct tty *tp = fp->f_data;
397 	struct pts_softc *psc = tty_softc(tp);
398 	int revents = 0;
399 
400 	tty_lock(tp);
401 
402 	if (psc->pts_flags & PTS_FINISHED) {
403 		/* Slave device is not opened. */
404 		tty_unlock(tp);
405 		return ((events & (POLLIN|POLLRDNORM)) | POLLHUP);
406 	}
407 
408 	if (events & (POLLIN|POLLRDNORM)) {
409 		/* See if we can getc something. */
410 		if (ttydisc_getc_poll(tp) ||
411 		    (psc->pts_flags & PTS_PKT && psc->pts_pkt))
412 			revents |= events & (POLLIN|POLLRDNORM);
413 	}
414 	if (events & (POLLOUT|POLLWRNORM)) {
415 		/* See if we can rint something. */
416 		if (ttydisc_rint_poll(tp))
417 			revents |= events & (POLLOUT|POLLWRNORM);
418 	}
419 
420 	/*
421 	 * No need to check for POLLHUP here. This device cannot be used
422 	 * as a callout device, which means we always have a carrier,
423 	 * because the master is.
424 	 */
425 
426 	if (revents == 0) {
427 		/*
428 		 * This code might look misleading, but the naming of
429 		 * poll events on this side is the opposite of the slave
430 		 * device.
431 		 */
432 		if (events & (POLLIN|POLLRDNORM))
433 			selrecord(td, &psc->pts_outpoll);
434 		if (events & (POLLOUT|POLLWRNORM))
435 			selrecord(td, &psc->pts_inpoll);
436 	}
437 
438 	tty_unlock(tp);
439 
440 	return (revents);
441 }
442 
443 /*
444  * kqueue support.
445  */
446 
447 static void
448 pts_kqops_read_detach(struct knote *kn)
449 {
450 	struct file *fp = kn->kn_fp;
451 	struct tty *tp = fp->f_data;
452 	struct pts_softc *psc = tty_softc(tp);
453 
454 	knlist_remove(&psc->pts_outpoll.si_note, kn, 0);
455 }
456 
457 static int
458 pts_kqops_read_event(struct knote *kn, long hint)
459 {
460 	struct file *fp = kn->kn_fp;
461 	struct tty *tp = fp->f_data;
462 	struct pts_softc *psc = tty_softc(tp);
463 
464 	if (psc->pts_flags & PTS_FINISHED) {
465 		kn->kn_flags |= EV_EOF;
466 		return (1);
467 	} else {
468 		kn->kn_data = ttydisc_getc_poll(tp);
469 		return (kn->kn_data > 0);
470 	}
471 }
472 
473 static void
474 pts_kqops_write_detach(struct knote *kn)
475 {
476 	struct file *fp = kn->kn_fp;
477 	struct tty *tp = fp->f_data;
478 	struct pts_softc *psc = tty_softc(tp);
479 
480 	knlist_remove(&psc->pts_inpoll.si_note, kn, 0);
481 }
482 
483 static int
484 pts_kqops_write_event(struct knote *kn, long hint)
485 {
486 	struct file *fp = kn->kn_fp;
487 	struct tty *tp = fp->f_data;
488 	struct pts_softc *psc = tty_softc(tp);
489 
490 	if (psc->pts_flags & PTS_FINISHED) {
491 		kn->kn_flags |= EV_EOF;
492 		return (1);
493 	} else {
494 		kn->kn_data = ttydisc_rint_poll(tp);
495 		return (kn->kn_data > 0);
496 	}
497 }
498 
499 static struct filterops pts_kqops_read = {
500 	.f_isfd = 1,
501 	.f_detach = pts_kqops_read_detach,
502 	.f_event = pts_kqops_read_event,
503 };
504 static struct filterops pts_kqops_write = {
505 	.f_isfd = 1,
506 	.f_detach = pts_kqops_write_detach,
507 	.f_event = pts_kqops_write_event,
508 };
509 
510 static int
511 ptsdev_kqfilter(struct file *fp, struct knote *kn)
512 {
513 	struct tty *tp = fp->f_data;
514 	struct pts_softc *psc = tty_softc(tp);
515 	int error = 0;
516 
517 	tty_lock(tp);
518 
519 	switch (kn->kn_filter) {
520 	case EVFILT_READ:
521 		kn->kn_fop = &pts_kqops_read;
522 		knlist_add(&psc->pts_outpoll.si_note, kn, 1);
523 		break;
524 	case EVFILT_WRITE:
525 		kn->kn_fop = &pts_kqops_write;
526 		knlist_add(&psc->pts_inpoll.si_note, kn, 1);
527 		break;
528 	default:
529 		error = EINVAL;
530 		break;
531 	}
532 
533 	tty_unlock(tp);
534 	return (error);
535 }
536 
537 static int
538 ptsdev_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
539     struct thread *td)
540 {
541 	struct tty *tp = fp->f_data;
542 #ifdef PTS_EXTERNAL
543 	struct pts_softc *psc = tty_softc(tp);
544 #endif /* PTS_EXTERNAL */
545 	struct cdev *dev = tp->t_dev;
546 
547 	/*
548 	 * According to POSIX, we must implement an fstat(). This also
549 	 * makes this implementation compatible with Linux binaries,
550 	 * because Linux calls fstat() on the pseudo-terminal master to
551 	 * obtain st_rdev.
552 	 *
553 	 * XXX: POSIX also mentions we must fill in st_dev, but how?
554 	 */
555 
556 	bzero(sb, sizeof *sb);
557 #ifdef PTS_EXTERNAL
558 	if (psc->pts_cdev != NULL)
559 		sb->st_ino = sb->st_rdev = dev2udev(psc->pts_cdev);
560 	else
561 #endif /* PTS_EXTERNAL */
562 		sb->st_ino = sb->st_rdev = tty_udev(tp);
563 
564 	sb->st_atim = dev->si_atime;
565 	sb->st_ctim = dev->si_ctime;
566 	sb->st_mtim = dev->si_mtime;
567 	sb->st_uid = dev->si_uid;
568 	sb->st_gid = dev->si_gid;
569 	sb->st_mode = dev->si_mode | S_IFCHR;
570 
571 	return (0);
572 }
573 
574 static int
575 ptsdev_close(struct file *fp, struct thread *td)
576 {
577 	struct tty *tp = fp->f_data;
578 
579 	/* Deallocate TTY device. */
580 	tty_lock(tp);
581 	tty_rel_gone(tp);
582 
583 	/*
584 	 * Open of /dev/ptmx or /dev/ptyXX changes the type of file
585 	 * from DTYPE_VNODE to DTYPE_PTS. vn_open() increases vnode
586 	 * use count, we need to decrement it, and possibly do other
587 	 * required cleanup.
588 	 */
589 	if (fp->f_vnode != NULL)
590 		return (vnops.fo_close(fp, td));
591 
592 	return (0);
593 }
594 
595 static int
596 ptsdev_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
597 {
598 	struct tty *tp;
599 
600 	kif->kf_type = KF_TYPE_PTS;
601 	tp = fp->f_data;
602 	kif->kf_un.kf_pts.kf_pts_dev = tty_udev(tp);
603 	kif->kf_un.kf_pts.kf_pts_dev_freebsd11 =
604 	    kif->kf_un.kf_pts.kf_pts_dev; /* truncate */
605 	strlcpy(kif->kf_path, tty_devname(tp), sizeof(kif->kf_path));
606 	return (0);
607 }
608 
609 static struct fileops ptsdev_ops = {
610 	.fo_read	= ptsdev_read,
611 	.fo_write	= ptsdev_write,
612 	.fo_truncate	= invfo_truncate,
613 	.fo_ioctl	= ptsdev_ioctl,
614 	.fo_poll	= ptsdev_poll,
615 	.fo_kqfilter	= ptsdev_kqfilter,
616 	.fo_stat	= ptsdev_stat,
617 	.fo_close	= ptsdev_close,
618 	.fo_chmod	= invfo_chmod,
619 	.fo_chown	= invfo_chown,
620 	.fo_sendfile	= invfo_sendfile,
621 	.fo_fill_kinfo	= ptsdev_fill_kinfo,
622 	.fo_flags	= DFLAG_PASSABLE,
623 };
624 
625 /*
626  * Driver-side hooks.
627  */
628 
629 static void
630 ptsdrv_outwakeup(struct tty *tp)
631 {
632 	struct pts_softc *psc = tty_softc(tp);
633 
634 	cv_broadcast(&psc->pts_outwait);
635 	selwakeup(&psc->pts_outpoll);
636 	KNOTE_LOCKED(&psc->pts_outpoll.si_note, 0);
637 }
638 
639 static void
640 ptsdrv_inwakeup(struct tty *tp)
641 {
642 	struct pts_softc *psc = tty_softc(tp);
643 
644 	cv_broadcast(&psc->pts_inwait);
645 	selwakeup(&psc->pts_inpoll);
646 	KNOTE_LOCKED(&psc->pts_inpoll.si_note, 0);
647 }
648 
649 static int
650 ptsdrv_open(struct tty *tp)
651 {
652 	struct pts_softc *psc = tty_softc(tp);
653 
654 	psc->pts_flags &= ~PTS_FINISHED;
655 
656 	return (0);
657 }
658 
659 static void
660 ptsdrv_close(struct tty *tp)
661 {
662 	struct pts_softc *psc = tty_softc(tp);
663 
664 	/* Wake up any blocked readers/writers. */
665 	psc->pts_flags |= PTS_FINISHED;
666 	ptsdrv_outwakeup(tp);
667 	ptsdrv_inwakeup(tp);
668 }
669 
670 static void
671 ptsdrv_pktnotify(struct tty *tp, char event)
672 {
673 	struct pts_softc *psc = tty_softc(tp);
674 
675 	/*
676 	 * Clear conflicting flags.
677 	 */
678 
679 	switch (event) {
680 	case TIOCPKT_STOP:
681 		psc->pts_pkt &= ~TIOCPKT_START;
682 		break;
683 	case TIOCPKT_START:
684 		psc->pts_pkt &= ~TIOCPKT_STOP;
685 		break;
686 	case TIOCPKT_NOSTOP:
687 		psc->pts_pkt &= ~TIOCPKT_DOSTOP;
688 		break;
689 	case TIOCPKT_DOSTOP:
690 		psc->pts_pkt &= ~TIOCPKT_NOSTOP;
691 		break;
692 	}
693 
694 	psc->pts_pkt |= event;
695 	ptsdrv_outwakeup(tp);
696 }
697 
698 static void
699 ptsdrv_free(void *softc)
700 {
701 	struct pts_softc *psc = softc;
702 
703 	/* Make device number available again. */
704 	if (psc->pts_unit >= 0)
705 		free_unr(pts_pool, psc->pts_unit);
706 
707 	chgptscnt(psc->pts_cred->cr_ruidinfo, -1, 0);
708 	racct_sub_cred(psc->pts_cred, RACCT_NPTS, 1);
709 	crfree(psc->pts_cred);
710 
711 	seldrain(&psc->pts_inpoll);
712 	seldrain(&psc->pts_outpoll);
713 	knlist_destroy(&psc->pts_inpoll.si_note);
714 	knlist_destroy(&psc->pts_outpoll.si_note);
715 
716 #ifdef PTS_EXTERNAL
717 	/* Destroy master device as well. */
718 	if (psc->pts_cdev != NULL)
719 		destroy_dev_sched(psc->pts_cdev);
720 #endif /* PTS_EXTERNAL */
721 
722 	free(psc, M_PTS);
723 }
724 
725 static struct ttydevsw pts_class = {
726 	.tsw_flags	= TF_NOPREFIX,
727 	.tsw_outwakeup	= ptsdrv_outwakeup,
728 	.tsw_inwakeup	= ptsdrv_inwakeup,
729 	.tsw_open	= ptsdrv_open,
730 	.tsw_close	= ptsdrv_close,
731 	.tsw_pktnotify	= ptsdrv_pktnotify,
732 	.tsw_free	= ptsdrv_free,
733 };
734 
735 #ifndef PTS_EXTERNAL
736 static
737 #endif /* !PTS_EXTERNAL */
738 int
739 pts_alloc(int fflags, struct thread *td, struct file *fp)
740 {
741 	int unit, ok, error;
742 	struct tty *tp;
743 	struct pts_softc *psc;
744 	struct proc *p = td->td_proc;
745 	struct ucred *cred = td->td_ucred;
746 
747 	/* Resource limiting. */
748 	PROC_LOCK(p);
749 	error = racct_add(p, RACCT_NPTS, 1);
750 	if (error != 0) {
751 		PROC_UNLOCK(p);
752 		return (EAGAIN);
753 	}
754 	ok = chgptscnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_NPTS));
755 	if (!ok) {
756 		racct_sub(p, RACCT_NPTS, 1);
757 		PROC_UNLOCK(p);
758 		return (EAGAIN);
759 	}
760 	PROC_UNLOCK(p);
761 
762 	/* Try to allocate a new pts unit number. */
763 	unit = alloc_unr(pts_pool);
764 	if (unit < 0) {
765 		racct_sub(p, RACCT_NPTS, 1);
766 		chgptscnt(cred->cr_ruidinfo, -1, 0);
767 		return (EAGAIN);
768 	}
769 
770 	/* Allocate TTY and softc. */
771 	psc = malloc(sizeof(struct pts_softc), M_PTS, M_WAITOK|M_ZERO);
772 	cv_init(&psc->pts_inwait, "ptsin");
773 	cv_init(&psc->pts_outwait, "ptsout");
774 
775 	psc->pts_unit = unit;
776 	psc->pts_cred = crhold(cred);
777 
778 	tp = tty_alloc(&pts_class, psc);
779 	knlist_init_mtx(&psc->pts_inpoll.si_note, tp->t_mtx);
780 	knlist_init_mtx(&psc->pts_outpoll.si_note, tp->t_mtx);
781 
782 	/* Expose the slave device as well. */
783 	tty_makedev(tp, td->td_ucred, "pts/%u", psc->pts_unit);
784 
785 	finit(fp, fflags, DTYPE_PTS, tp, &ptsdev_ops);
786 
787 	return (0);
788 }
789 
790 #ifdef PTS_EXTERNAL
791 int
792 pts_alloc_external(int fflags, struct thread *td, struct file *fp,
793     struct cdev *dev, const char *name)
794 {
795 	int ok, error;
796 	struct tty *tp;
797 	struct pts_softc *psc;
798 	struct proc *p = td->td_proc;
799 	struct ucred *cred = td->td_ucred;
800 
801 	/* Resource limiting. */
802 	PROC_LOCK(p);
803 	error = racct_add(p, RACCT_NPTS, 1);
804 	if (error != 0) {
805 		PROC_UNLOCK(p);
806 		return (EAGAIN);
807 	}
808 	ok = chgptscnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_NPTS));
809 	if (!ok) {
810 		racct_sub(p, RACCT_NPTS, 1);
811 		PROC_UNLOCK(p);
812 		return (EAGAIN);
813 	}
814 	PROC_UNLOCK(p);
815 
816 	/* Allocate TTY and softc. */
817 	psc = malloc(sizeof(struct pts_softc), M_PTS, M_WAITOK|M_ZERO);
818 	cv_init(&psc->pts_inwait, "ptsin");
819 	cv_init(&psc->pts_outwait, "ptsout");
820 
821 	psc->pts_unit = -1;
822 	psc->pts_cdev = dev;
823 	psc->pts_cred = crhold(cred);
824 
825 	tp = tty_alloc(&pts_class, psc);
826 	knlist_init_mtx(&psc->pts_inpoll.si_note, tp->t_mtx);
827 	knlist_init_mtx(&psc->pts_outpoll.si_note, tp->t_mtx);
828 
829 	/* Expose the slave device as well. */
830 	tty_makedev(tp, td->td_ucred, "%s", name);
831 
832 	finit(fp, fflags, DTYPE_PTS, tp, &ptsdev_ops);
833 
834 	return (0);
835 }
836 #endif /* PTS_EXTERNAL */
837 
838 int
839 sys_posix_openpt(struct thread *td, struct posix_openpt_args *uap)
840 {
841 	int error, fd;
842 	struct file *fp;
843 
844 	/*
845 	 * POSIX states it's unspecified when other flags are passed. We
846 	 * don't allow this.
847 	 */
848 	if (uap->flags & ~(O_RDWR|O_NOCTTY|O_CLOEXEC))
849 		return (EINVAL);
850 
851 	error = falloc(td, &fp, &fd, uap->flags);
852 	if (error)
853 		return (error);
854 
855 	/* Allocate the actual pseudo-TTY. */
856 	error = pts_alloc(FFLAGS(uap->flags & O_ACCMODE), td, fp);
857 	if (error != 0) {
858 		fdclose(td, fp, fd);
859 		fdrop(fp, td);
860 		return (error);
861 	}
862 
863 	/* Pass it back to userspace. */
864 	td->td_retval[0] = fd;
865 	fdrop(fp, td);
866 
867 	return (0);
868 }
869 
870 static void
871 pts_init(void *unused)
872 {
873 
874 	pts_pool = new_unrhdr(0, INT_MAX, NULL);
875 }
876 
877 SYSINIT(pts, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, pts_init, NULL);
878