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