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