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