xref: /freebsd/sys/kern/tty_pts.c (revision 74ca7bf1d4c7173d5575ba168bc4b5f6d181ff5a)
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/poll.h>
54 #include <sys/proc.h>
55 #include <sys/racct.h>
56 #include <sys/resourcevar.h>
57 #include <sys/serial.h>
58 #include <sys/stat.h>
59 #include <sys/syscall.h>
60 #include <sys/syscallsubr.h>
61 #include <sys/sysctl.h>
62 #include <sys/sysent.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 		struct fiodgname_arg *fgn;
286 		const char *p;
287 		int i;
288 
289 		/* Reverse device name lookups, for ptsname() and ttyname(). */
290 		fgn = data;
291 		p = tty_devname(tp);
292 		i = strlen(p) + 1;
293 		if (i > fgn->len)
294 			return (EINVAL);
295 		return copyout(p, fgn->buf, i);
296 	}
297 
298 	/*
299 	 * We need to implement TIOCGPGRP and TIOCGSID here again. When
300 	 * called on the pseudo-terminal master, it should not check if
301 	 * the terminal is the foreground terminal of the calling
302 	 * process.
303 	 *
304 	 * TIOCGETA is also implemented here. Various Linux PTY routines
305 	 * often call isatty(), which is implemented by tcgetattr().
306 	 */
307 #ifdef PTS_LINUX
308 	case TIOCGETA:
309 		/* Obtain terminal flags through tcgetattr(). */
310 		tty_lock(tp);
311 		*(struct termios*)data = tp->t_termios;
312 		tty_unlock(tp);
313 		return (0);
314 #endif /* PTS_LINUX */
315 	case TIOCSETAF:
316 	case TIOCSETAW:
317 		/*
318 		 * We must make sure we turn tcsetattr() calls of TCSAFLUSH and
319 		 * TCSADRAIN into something different. If an application would
320 		 * call TCSAFLUSH or TCSADRAIN on the master descriptor, it may
321 		 * deadlock waiting for all data to be read.
322 		 */
323 		cmd = TIOCSETA;
324 		break;
325 #if defined(PTS_COMPAT) || defined(PTS_LINUX)
326 	case TIOCGPTN:
327 		/*
328 		 * Get the device unit number.
329 		 */
330 		if (psc->pts_unit < 0)
331 			return (ENOTTY);
332 		*(unsigned int *)data = psc->pts_unit;
333 		return (0);
334 #endif /* PTS_COMPAT || PTS_LINUX */
335 	case TIOCGPGRP:
336 		/* Get the foreground process group ID. */
337 		tty_lock(tp);
338 		if (tp->t_pgrp != NULL)
339 			*(int *)data = tp->t_pgrp->pg_id;
340 		else
341 			*(int *)data = NO_PID;
342 		tty_unlock(tp);
343 		return (0);
344 	case TIOCGSID:
345 		/* Get the session leader process ID. */
346 		tty_lock(tp);
347 		if (tp->t_session == NULL)
348 			error = ENOTTY;
349 		else
350 			*(int *)data = tp->t_session->s_sid;
351 		tty_unlock(tp);
352 		return (error);
353 	case TIOCPTMASTER:
354 		/* Yes, we are a pseudo-terminal master. */
355 		return (0);
356 	case TIOCSIG:
357 		/* Signal the foreground process group. */
358 		sig = *(int *)data;
359 		if (sig < 1 || sig >= NSIG)
360 			return (EINVAL);
361 
362 		tty_lock(tp);
363 		tty_signal_pgrp(tp, sig);
364 		tty_unlock(tp);
365 		return (0);
366 	case TIOCPKT:
367 		/* Enable/disable packet mode. */
368 		tty_lock(tp);
369 		if (*(int *)data)
370 			psc->pts_flags |= PTS_PKT;
371 		else
372 			psc->pts_flags &= ~PTS_PKT;
373 		tty_unlock(tp);
374 		return (0);
375 	}
376 
377 	/* Just redirect this ioctl to the slave device. */
378 	tty_lock(tp);
379 	error = tty_ioctl(tp, cmd, data, fp->f_flag, td);
380 	tty_unlock(tp);
381 	if (error == ENOIOCTL)
382 		error = ENOTTY;
383 
384 	return (error);
385 }
386 
387 static int
388 ptsdev_poll(struct file *fp, int events, struct ucred *active_cred,
389     struct thread *td)
390 {
391 	struct tty *tp = fp->f_data;
392 	struct pts_softc *psc = tty_softc(tp);
393 	int revents = 0;
394 
395 	tty_lock(tp);
396 
397 	if (psc->pts_flags & PTS_FINISHED) {
398 		/* Slave device is not opened. */
399 		tty_unlock(tp);
400 		return ((events & (POLLIN|POLLRDNORM)) | POLLHUP);
401 	}
402 
403 	if (events & (POLLIN|POLLRDNORM)) {
404 		/* See if we can getc something. */
405 		if (ttydisc_getc_poll(tp) ||
406 		    (psc->pts_flags & PTS_PKT && psc->pts_pkt))
407 			revents |= events & (POLLIN|POLLRDNORM);
408 	}
409 	if (events & (POLLOUT|POLLWRNORM)) {
410 		/* See if we can rint something. */
411 		if (ttydisc_rint_poll(tp))
412 			revents |= events & (POLLOUT|POLLWRNORM);
413 	}
414 
415 	/*
416 	 * No need to check for POLLHUP here. This device cannot be used
417 	 * as a callout device, which means we always have a carrier,
418 	 * because the master is.
419 	 */
420 
421 	if (revents == 0) {
422 		/*
423 		 * This code might look misleading, but the naming of
424 		 * poll events on this side is the opposite of the slave
425 		 * device.
426 		 */
427 		if (events & (POLLIN|POLLRDNORM))
428 			selrecord(td, &psc->pts_outpoll);
429 		if (events & (POLLOUT|POLLWRNORM))
430 			selrecord(td, &psc->pts_inpoll);
431 	}
432 
433 	tty_unlock(tp);
434 
435 	return (revents);
436 }
437 
438 /*
439  * kqueue support.
440  */
441 
442 static void
443 pts_kqops_read_detach(struct knote *kn)
444 {
445 	struct file *fp = kn->kn_fp;
446 	struct tty *tp = fp->f_data;
447 	struct pts_softc *psc = tty_softc(tp);
448 
449 	knlist_remove(&psc->pts_outpoll.si_note, kn, 0);
450 }
451 
452 static int
453 pts_kqops_read_event(struct knote *kn, long hint)
454 {
455 	struct file *fp = kn->kn_fp;
456 	struct tty *tp = fp->f_data;
457 	struct pts_softc *psc = tty_softc(tp);
458 
459 	if (psc->pts_flags & PTS_FINISHED) {
460 		kn->kn_flags |= EV_EOF;
461 		return (1);
462 	} else {
463 		kn->kn_data = ttydisc_getc_poll(tp);
464 		return (kn->kn_data > 0);
465 	}
466 }
467 
468 static void
469 pts_kqops_write_detach(struct knote *kn)
470 {
471 	struct file *fp = kn->kn_fp;
472 	struct tty *tp = fp->f_data;
473 	struct pts_softc *psc = tty_softc(tp);
474 
475 	knlist_remove(&psc->pts_inpoll.si_note, kn, 0);
476 }
477 
478 static int
479 pts_kqops_write_event(struct knote *kn, long hint)
480 {
481 	struct file *fp = kn->kn_fp;
482 	struct tty *tp = fp->f_data;
483 	struct pts_softc *psc = tty_softc(tp);
484 
485 	if (psc->pts_flags & PTS_FINISHED) {
486 		kn->kn_flags |= EV_EOF;
487 		return (1);
488 	} else {
489 		kn->kn_data = ttydisc_rint_poll(tp);
490 		return (kn->kn_data > 0);
491 	}
492 }
493 
494 static struct filterops pts_kqops_read = {
495 	.f_isfd = 1,
496 	.f_detach = pts_kqops_read_detach,
497 	.f_event = pts_kqops_read_event,
498 };
499 static struct filterops pts_kqops_write = {
500 	.f_isfd = 1,
501 	.f_detach = pts_kqops_write_detach,
502 	.f_event = pts_kqops_write_event,
503 };
504 
505 static int
506 ptsdev_kqfilter(struct file *fp, struct knote *kn)
507 {
508 	struct tty *tp = fp->f_data;
509 	struct pts_softc *psc = tty_softc(tp);
510 	int error = 0;
511 
512 	tty_lock(tp);
513 
514 	switch (kn->kn_filter) {
515 	case EVFILT_READ:
516 		kn->kn_fop = &pts_kqops_read;
517 		knlist_add(&psc->pts_outpoll.si_note, kn, 1);
518 		break;
519 	case EVFILT_WRITE:
520 		kn->kn_fop = &pts_kqops_write;
521 		knlist_add(&psc->pts_inpoll.si_note, kn, 1);
522 		break;
523 	default:
524 		error = EINVAL;
525 		break;
526 	}
527 
528 	tty_unlock(tp);
529 	return (error);
530 }
531 
532 static int
533 ptsdev_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
534     struct thread *td)
535 {
536 	struct tty *tp = fp->f_data;
537 #ifdef PTS_EXTERNAL
538 	struct pts_softc *psc = tty_softc(tp);
539 #endif /* PTS_EXTERNAL */
540 	struct cdev *dev = tp->t_dev;
541 
542 	/*
543 	 * According to POSIX, we must implement an fstat(). This also
544 	 * makes this implementation compatible with Linux binaries,
545 	 * because Linux calls fstat() on the pseudo-terminal master to
546 	 * obtain st_rdev.
547 	 *
548 	 * XXX: POSIX also mentions we must fill in st_dev, but how?
549 	 */
550 
551 	bzero(sb, sizeof *sb);
552 #ifdef PTS_EXTERNAL
553 	if (psc->pts_cdev != NULL)
554 		sb->st_ino = sb->st_rdev = dev2udev(psc->pts_cdev);
555 	else
556 #endif /* PTS_EXTERNAL */
557 		sb->st_ino = sb->st_rdev = tty_udev(tp);
558 
559 	sb->st_atim = dev->si_atime;
560 	sb->st_ctim = dev->si_ctime;
561 	sb->st_mtim = dev->si_mtime;
562 	sb->st_uid = dev->si_uid;
563 	sb->st_gid = dev->si_gid;
564 	sb->st_mode = dev->si_mode | S_IFCHR;
565 
566 	return (0);
567 }
568 
569 static int
570 ptsdev_close(struct file *fp, struct thread *td)
571 {
572 	struct tty *tp = fp->f_data;
573 
574 	/* Deallocate TTY device. */
575 	tty_lock(tp);
576 	tty_rel_gone(tp);
577 
578 	/*
579 	 * Open of /dev/ptmx or /dev/ptyXX changes the type of file
580 	 * from DTYPE_VNODE to DTYPE_PTS. vn_open() increases vnode
581 	 * use count, we need to decrement it, and possibly do other
582 	 * required cleanup.
583 	 */
584 	if (fp->f_vnode != NULL)
585 		return (vnops.fo_close(fp, td));
586 
587 	return (0);
588 }
589 
590 static int
591 ptsdev_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
592 {
593 	struct tty *tp;
594 
595 	kif->kf_type = KF_TYPE_PTS;
596 	tp = fp->f_data;
597 	kif->kf_un.kf_pts.kf_pts_dev = tty_udev(tp);
598 	kif->kf_un.kf_pts.kf_pts_dev_freebsd11 =
599 	    kif->kf_un.kf_pts.kf_pts_dev; /* truncate */
600 	strlcpy(kif->kf_path, tty_devname(tp), sizeof(kif->kf_path));
601 	return (0);
602 }
603 
604 static struct fileops ptsdev_ops = {
605 	.fo_read	= ptsdev_read,
606 	.fo_write	= ptsdev_write,
607 	.fo_truncate	= invfo_truncate,
608 	.fo_ioctl	= ptsdev_ioctl,
609 	.fo_poll	= ptsdev_poll,
610 	.fo_kqfilter	= ptsdev_kqfilter,
611 	.fo_stat	= ptsdev_stat,
612 	.fo_close	= ptsdev_close,
613 	.fo_chmod	= invfo_chmod,
614 	.fo_chown	= invfo_chown,
615 	.fo_sendfile	= invfo_sendfile,
616 	.fo_fill_kinfo	= ptsdev_fill_kinfo,
617 	.fo_flags	= DFLAG_PASSABLE,
618 };
619 
620 /*
621  * Driver-side hooks.
622  */
623 
624 static void
625 ptsdrv_outwakeup(struct tty *tp)
626 {
627 	struct pts_softc *psc = tty_softc(tp);
628 
629 	cv_broadcast(&psc->pts_outwait);
630 	selwakeup(&psc->pts_outpoll);
631 	KNOTE_LOCKED(&psc->pts_outpoll.si_note, 0);
632 }
633 
634 static void
635 ptsdrv_inwakeup(struct tty *tp)
636 {
637 	struct pts_softc *psc = tty_softc(tp);
638 
639 	cv_broadcast(&psc->pts_inwait);
640 	selwakeup(&psc->pts_inpoll);
641 	KNOTE_LOCKED(&psc->pts_inpoll.si_note, 0);
642 }
643 
644 static int
645 ptsdrv_open(struct tty *tp)
646 {
647 	struct pts_softc *psc = tty_softc(tp);
648 
649 	psc->pts_flags &= ~PTS_FINISHED;
650 
651 	return (0);
652 }
653 
654 static void
655 ptsdrv_close(struct tty *tp)
656 {
657 	struct pts_softc *psc = tty_softc(tp);
658 
659 	/* Wake up any blocked readers/writers. */
660 	psc->pts_flags |= PTS_FINISHED;
661 	ptsdrv_outwakeup(tp);
662 	ptsdrv_inwakeup(tp);
663 }
664 
665 static void
666 ptsdrv_pktnotify(struct tty *tp, char event)
667 {
668 	struct pts_softc *psc = tty_softc(tp);
669 
670 	/*
671 	 * Clear conflicting flags.
672 	 */
673 
674 	switch (event) {
675 	case TIOCPKT_STOP:
676 		psc->pts_pkt &= ~TIOCPKT_START;
677 		break;
678 	case TIOCPKT_START:
679 		psc->pts_pkt &= ~TIOCPKT_STOP;
680 		break;
681 	case TIOCPKT_NOSTOP:
682 		psc->pts_pkt &= ~TIOCPKT_DOSTOP;
683 		break;
684 	case TIOCPKT_DOSTOP:
685 		psc->pts_pkt &= ~TIOCPKT_NOSTOP;
686 		break;
687 	}
688 
689 	psc->pts_pkt |= event;
690 	ptsdrv_outwakeup(tp);
691 }
692 
693 static void
694 ptsdrv_free(void *softc)
695 {
696 	struct pts_softc *psc = softc;
697 
698 	/* Make device number available again. */
699 	if (psc->pts_unit >= 0)
700 		free_unr(pts_pool, psc->pts_unit);
701 
702 	chgptscnt(psc->pts_cred->cr_ruidinfo, -1, 0);
703 	racct_sub_cred(psc->pts_cred, RACCT_NPTS, 1);
704 	crfree(psc->pts_cred);
705 
706 	seldrain(&psc->pts_inpoll);
707 	seldrain(&psc->pts_outpoll);
708 	knlist_destroy(&psc->pts_inpoll.si_note);
709 	knlist_destroy(&psc->pts_outpoll.si_note);
710 
711 #ifdef PTS_EXTERNAL
712 	/* Destroy master device as well. */
713 	if (psc->pts_cdev != NULL)
714 		destroy_dev_sched(psc->pts_cdev);
715 #endif /* PTS_EXTERNAL */
716 
717 	free(psc, M_PTS);
718 }
719 
720 static struct ttydevsw pts_class = {
721 	.tsw_flags	= TF_NOPREFIX,
722 	.tsw_outwakeup	= ptsdrv_outwakeup,
723 	.tsw_inwakeup	= ptsdrv_inwakeup,
724 	.tsw_open	= ptsdrv_open,
725 	.tsw_close	= ptsdrv_close,
726 	.tsw_pktnotify	= ptsdrv_pktnotify,
727 	.tsw_free	= ptsdrv_free,
728 };
729 
730 #ifndef PTS_EXTERNAL
731 static
732 #endif /* !PTS_EXTERNAL */
733 int
734 pts_alloc(int fflags, struct thread *td, struct file *fp)
735 {
736 	int unit, ok, error;
737 	struct tty *tp;
738 	struct pts_softc *psc;
739 	struct proc *p = td->td_proc;
740 	struct ucred *cred = td->td_ucred;
741 
742 	/* Resource limiting. */
743 	PROC_LOCK(p);
744 	error = racct_add(p, RACCT_NPTS, 1);
745 	if (error != 0) {
746 		PROC_UNLOCK(p);
747 		return (EAGAIN);
748 	}
749 	ok = chgptscnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_NPTS));
750 	if (!ok) {
751 		racct_sub(p, RACCT_NPTS, 1);
752 		PROC_UNLOCK(p);
753 		return (EAGAIN);
754 	}
755 	PROC_UNLOCK(p);
756 
757 	/* Try to allocate a new pts unit number. */
758 	unit = alloc_unr(pts_pool);
759 	if (unit < 0) {
760 		racct_sub(p, RACCT_NPTS, 1);
761 		chgptscnt(cred->cr_ruidinfo, -1, 0);
762 		return (EAGAIN);
763 	}
764 
765 	/* Allocate TTY and softc. */
766 	psc = malloc(sizeof(struct pts_softc), M_PTS, M_WAITOK|M_ZERO);
767 	cv_init(&psc->pts_inwait, "ptsin");
768 	cv_init(&psc->pts_outwait, "ptsout");
769 
770 	psc->pts_unit = unit;
771 	psc->pts_cred = crhold(cred);
772 
773 	tp = tty_alloc(&pts_class, psc);
774 	knlist_init_mtx(&psc->pts_inpoll.si_note, tp->t_mtx);
775 	knlist_init_mtx(&psc->pts_outpoll.si_note, tp->t_mtx);
776 
777 	/* Expose the slave device as well. */
778 	tty_makedev(tp, td->td_ucred, "pts/%u", psc->pts_unit);
779 
780 	finit(fp, fflags, DTYPE_PTS, tp, &ptsdev_ops);
781 
782 	return (0);
783 }
784 
785 #ifdef PTS_EXTERNAL
786 int
787 pts_alloc_external(int fflags, struct thread *td, struct file *fp,
788     struct cdev *dev, const char *name)
789 {
790 	int ok, error;
791 	struct tty *tp;
792 	struct pts_softc *psc;
793 	struct proc *p = td->td_proc;
794 	struct ucred *cred = td->td_ucred;
795 
796 	/* Resource limiting. */
797 	PROC_LOCK(p);
798 	error = racct_add(p, RACCT_NPTS, 1);
799 	if (error != 0) {
800 		PROC_UNLOCK(p);
801 		return (EAGAIN);
802 	}
803 	ok = chgptscnt(cred->cr_ruidinfo, 1, lim_cur(td, RLIMIT_NPTS));
804 	if (!ok) {
805 		racct_sub(p, RACCT_NPTS, 1);
806 		PROC_UNLOCK(p);
807 		return (EAGAIN);
808 	}
809 	PROC_UNLOCK(p);
810 
811 	/* Allocate TTY and softc. */
812 	psc = malloc(sizeof(struct pts_softc), M_PTS, M_WAITOK|M_ZERO);
813 	cv_init(&psc->pts_inwait, "ptsin");
814 	cv_init(&psc->pts_outwait, "ptsout");
815 
816 	psc->pts_unit = -1;
817 	psc->pts_cdev = dev;
818 	psc->pts_cred = crhold(cred);
819 
820 	tp = tty_alloc(&pts_class, psc);
821 	knlist_init_mtx(&psc->pts_inpoll.si_note, tp->t_mtx);
822 	knlist_init_mtx(&psc->pts_outpoll.si_note, tp->t_mtx);
823 
824 	/* Expose the slave device as well. */
825 	tty_makedev(tp, td->td_ucred, "%s", name);
826 
827 	finit(fp, fflags, DTYPE_PTS, tp, &ptsdev_ops);
828 
829 	return (0);
830 }
831 #endif /* PTS_EXTERNAL */
832 
833 int
834 sys_posix_openpt(struct thread *td, struct posix_openpt_args *uap)
835 {
836 	int error, fd;
837 	struct file *fp;
838 
839 	/*
840 	 * POSIX states it's unspecified when other flags are passed. We
841 	 * don't allow this.
842 	 */
843 	if (uap->flags & ~(O_RDWR|O_NOCTTY|O_CLOEXEC))
844 		return (EINVAL);
845 
846 	error = falloc(td, &fp, &fd, uap->flags);
847 	if (error)
848 		return (error);
849 
850 	/* Allocate the actual pseudo-TTY. */
851 	error = pts_alloc(FFLAGS(uap->flags & O_ACCMODE), td, fp);
852 	if (error != 0) {
853 		fdclose(td, fp, fd);
854 		fdrop(fp, td);
855 		return (error);
856 	}
857 
858 	/* Pass it back to userspace. */
859 	td->td_retval[0] = fd;
860 	fdrop(fp, td);
861 
862 	return (0);
863 }
864 
865 static void
866 pts_init(void *unused)
867 {
868 
869 	pts_pool = new_unrhdr(0, INT_MAX, NULL);
870 }
871 
872 SYSINIT(pts, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, pts_init, NULL);
873