xref: /freebsd/sys/kern/tty_pts.c (revision cacdd70cc751fb68dec4b86c5e5b8c969b6e26ef)
1 /*
2  * Copyright (c) 2003 Networks Associates Technology, Inc.
3  * Copyright (c) 2006 Robert N. M. Watson
4  * Copyright (c) 2006 Olivier Houchard
5  * All rights reserved.
6  *
7  * This software was developed for the FreeBSD Project in part by Network
8  * Associates Laboratories, the Security Research Division of Network
9  * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"),
10  * as part of the DARPA CHATS research program.
11  *
12  * Copyright (c) 1982, 1986, 1989, 1993
13  *	The Regents of the University of California.  All rights reserved.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions and the following disclaimer.
20  * 2. Redistributions in binary form must reproduce the above copyright
21  *    notice, this list of conditions and the following disclaimer in the
22  *    documentation and/or other materials provided with the distribution.
23  * 4. Neither the name of the University nor the names of its contributors
24  *    may be used to endorse or promote products derived from this software
25  *    without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37  * SUCH DAMAGE.
38  *
39  *	@(#)tty_pty.c	8.4 (Berkeley) 2/20/95
40  */
41 
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44 
45 /*
46  * Pseudo-teletype Driver
47  * (Actually two drivers, requiring two entries in 'cdevsw')
48  */
49 #include "opt_compat.h"
50 #include "opt_tty.h"
51 #include <sys/param.h>
52 #include <sys/systm.h>
53 #include <sys/lock.h>
54 #include <sys/mutex.h>
55 #include <sys/sx.h>
56 #if defined(COMPAT_43TTY)
57 #include <sys/ioctl_compat.h>
58 #endif
59 #include <sys/priv.h>
60 #include <sys/proc.h>
61 #include <sys/queue.h>
62 #include <sys/tty.h>
63 #include <sys/fcntl.h>
64 #include <sys/poll.h>
65 #include <sys/kernel.h>
66 #include <sys/vnode.h>
67 #include <sys/signalvar.h>
68 #include <sys/malloc.h>
69 #include <sys/conf.h>
70 #include <sys/sysctl.h>
71 #include <sys/filio.h>
72 
73 static MALLOC_DEFINE(M_PTY, "ptys", "pty data structures");
74 
75 static void ptsstart(struct tty *tp);
76 static void ptsstop(struct tty *tp, int rw);
77 static void ptcwakeup(struct tty *tp, int flag);
78 
79 static d_open_t		ptsopen;
80 static d_close_t	ptsclose;
81 static d_read_t		ptsread;
82 static d_write_t	ptswrite;
83 static d_ioctl_t	ptsioctl;
84 static d_ioctl_t	ptcioctl;
85 static d_open_t		ptcopen;
86 static d_close_t	ptcclose;
87 static d_read_t		ptcread;
88 static d_write_t	ptcwrite;
89 static d_poll_t		ptcpoll;
90 
91 static struct cdevsw pts_cdevsw = {
92 	.d_version = 	D_VERSION,
93 	.d_open =	ptsopen,
94 	.d_close =	ptsclose,
95 	.d_read =	ptsread,
96 	.d_write =	ptswrite,
97 	.d_ioctl =	ptsioctl,
98 	.d_poll =	ttypoll,
99 	.d_name =	"pts",
100 	.d_flags =	D_TTY | D_NEEDGIANT,
101 	.d_kqfilter =	ttykqfilter,
102 };
103 
104 static struct cdevsw ptc_cdevsw = {
105 	.d_version = 	D_VERSION,
106 	.d_open =	ptcopen,
107 	.d_close =	ptcclose,
108 	.d_read =	ptcread,
109 	.d_write =	ptcwrite,
110 	.d_ioctl =	ptcioctl,
111 	.d_poll =	ptcpoll,
112 	.d_name =	"ptc",
113 	.d_flags =	D_TTY | D_NEEDGIANT,
114 	.d_kqfilter =	ttykqfilter,
115 };
116 
117 #define BUFSIZ 100		/* Chunk size iomoved to/from user */
118 
119 #define TSA_PTC_READ(tp)	((void *)&(tp)->t_outq.c_cf)
120 #define TSA_PTC_WRITE(tp)	((void *)&(tp)->t_rawq.c_cl)
121 #define TSA_PTS_READ(tp)	((void *)&(tp)->t_canq)
122 
123 #define NUM_TO_MINOR(c)		((c & 0xff) | ((c & ~0xff) << 16))
124 /*-
125  * Once a tty is allocated, it cannot (currently) be freed.  As such,
126  * we keep a global list of ptys that have been used so we can recycle
127  * them.  Another list is provided for released pts, which are
128  * not currently allocated, permitting reuse.  pt_flags holds state
129  * associated with a particular session, so isn't overloaded for this.
130  * When a pty descriptor is unused, its number is set to -1 giving
131  * more consistent and traditional allocation orders to pty numbers.
132  *
133  * Locking: (p) indicates that the field is locked by the global pt_mtx.
134  * (c) indicates the value is constant after allocation.   Other fields
135  * await tty locking generally, and are protected by Giant.
136  */
137 struct	pt_desc {
138 	int			 pt_num;	/* (c) pty number */
139 	LIST_ENTRY(pt_desc)	 pt_list;	/* (p) global pty list */
140 
141 	int			 pt_flags;
142 	struct selinfo		 pt_selr, pt_selw;
143 	u_char			 pt_send;
144 	u_char			 pt_ucntl;
145 	struct tty		 *pt_tty;
146 	struct cdev		 *pt_devs, *pt_devc;
147 	int			 pt_pts_open, pt_ptc_open;
148 	struct prison		*pt_prison;
149 };
150 
151 static struct mtx		pt_mtx;
152 static LIST_HEAD(,pt_desc)	pt_list;
153 static LIST_HEAD(,pt_desc)	pt_free_list;
154 
155 #define	PF_PKT		0x008		/* packet mode */
156 #define	PF_STOPPED	0x010		/* user told stopped */
157 #define	PF_NOSTOP	0x040
158 #define PF_UCNTL	0x080		/* user control mode */
159 
160 static unsigned int next_avail_nb;
161 
162 static int use_pts = 0;
163 
164 static unsigned int max_pts = 1000;
165 
166 static unsigned int nb_allocated;
167 
168 TUNABLE_INT("kern.pts.enable", &use_pts);
169 
170 SYSCTL_NODE(_kern, OID_AUTO, pts, CTLFLAG_RD, 0, "pts");
171 
172 SYSCTL_INT(_kern_pts, OID_AUTO, enable, CTLFLAG_RW, &use_pts, 0,
173     "enable pts");
174 
175 SYSCTL_INT(_kern_pts, OID_AUTO, max, CTLFLAG_RW, &max_pts, 0, "max pts");
176 
177 /*
178  * If there's a free pty descriptor in the pty descriptor list, retrieve it.
179  * Otherwise, allocate a new one, initialize it, and hook it up.  If there's
180  * not a tty number, reject.
181  */
182 static struct pt_desc *
183 pty_new(void)
184 {
185 	struct pt_desc *pt;
186 	int nb;
187 
188 	mtx_lock(&pt_mtx);
189 	if (nb_allocated >= max_pts || nb_allocated == 0xffffff) {
190 		mtx_unlock(&pt_mtx);
191 		return (NULL);
192 	}
193 	nb_allocated++;
194 	pt = LIST_FIRST(&pt_free_list);
195 	if (pt) {
196 		LIST_REMOVE(pt, pt_list);
197 	} else {
198 		nb = next_avail_nb++;
199 		mtx_unlock(&pt_mtx);
200 		pt = malloc(sizeof(*pt), M_PTY, M_WAITOK | M_ZERO);
201 		pt->pt_tty = ttyalloc();
202 		mtx_lock(&pt_mtx);
203 		pt->pt_num = nb;
204 	}
205 	LIST_INSERT_HEAD(&pt_list, pt, pt_list);
206 	mtx_unlock(&pt_mtx);
207 	return (pt);
208 }
209 
210 /*
211  * Release a pty descriptor back to the pool for reuse.  The pty number
212  * remains allocated.
213  */
214 static void
215 pty_release(void *v)
216 {
217 	struct pt_desc *pt = (struct pt_desc *)v;
218 
219 	mtx_lock(&pt_mtx);
220 	KASSERT(pt->pt_ptc_open == 0 && pt->pt_pts_open == 0,
221 	    ("pty_release: pts/%d freed while open\n", pt->pt_num));
222 	KASSERT(pt->pt_devs == NULL && pt->pt_devc == NULL,
223 	    ("pty_release: pts/%d freed whith non-null struct cdev\n", pt->pt_num));
224 	nb_allocated--;
225 	LIST_REMOVE(pt, pt_list);
226 	LIST_INSERT_HEAD(&pt_free_list, pt, pt_list);
227 	mtx_unlock(&pt_mtx);
228 }
229 
230 /*
231  * Given a pty descriptor, if both endpoints are closed, release all
232  * resources and destroy the device nodes to flush file system level
233  * state for the tty (owner, avoid races, etc).
234  */
235 static void
236 pty_maybecleanup(struct pt_desc *pt)
237 {
238 	struct cdev *pt_devs, *pt_devc;
239 
240 	if (pt->pt_ptc_open || pt->pt_pts_open)
241 		return;
242 
243 	if (pt->pt_tty->t_refcnt > 1)
244 		return;
245 
246 	if (bootverbose)
247 		printf("destroying pty %d\n", pt->pt_num);
248 
249 	pt_devs = pt->pt_devs;
250 	pt_devc = pt->pt_devc;
251 	pt->pt_devs = pt->pt_devc = NULL;
252 	pt->pt_tty->t_dev = NULL;
253 	pt_devc->si_drv1 = NULL;
254 	ttyrel(pt->pt_tty);
255 	pt->pt_tty = NULL;
256 	destroy_dev_sched(pt_devs);
257 	destroy_dev_sched_cb(pt_devc, pty_release, pt);
258 }
259 
260 /*ARGSUSED*/
261 static int
262 ptsopen(struct cdev *dev, int flag, int devtype, struct thread *td)
263 {
264 	struct tty *tp;
265 	int error;
266 	struct pt_desc *pt;
267 
268 	pt = dev->si_drv1;
269 	tp = dev->si_tty;
270 	if ((tp->t_state & TS_ISOPEN) == 0)
271 		ttyinitmode(tp, 1, 0);
272 	else if (tp->t_state & TS_XCLUDE && priv_check(td,
273 	    PRIV_TTY_EXCLUSIVE)) {
274 		return (EBUSY);
275 	} else if (pt->pt_prison != td->td_ucred->cr_prison &&
276 	    priv_check(td, PRIV_TTY_PRISON)) {
277 		return (EBUSY);
278 	}
279 	if (tp->t_oproc)			/* Ctrlr still around. */
280 		ttyld_modem(tp, 1);
281 	while ((tp->t_state & TS_CARR_ON) == 0) {
282 		if (flag & FNONBLOCK)
283 			break;
284 		error = ttysleep(tp, TSA_CARR_ON(tp), TTIPRI | PCATCH,
285 				 "ptsopn", 0);
286 		if (error)
287 			return (error);
288 	}
289 	error = ttyld_open(tp, dev);
290 	if (error == 0) {
291 		ptcwakeup(tp, FREAD|FWRITE);
292 		pt->pt_pts_open = 1;
293 	}
294 	return (error);
295 }
296 
297 static int
298 ptsclose(struct cdev *dev, int flag, int mode, struct thread *td)
299 {
300 	struct pt_desc *pt = dev->si_drv1;
301 	struct tty *tp;
302 	int err;
303 
304 	tp = dev->si_tty;
305 	err = ttyld_close(tp, flag);
306 	ptsstop(tp, FREAD|FWRITE);
307 	(void) tty_close(tp);
308 	pt->pt_pts_open = 0;
309 	pty_maybecleanup(pt);
310 	return (err);
311 }
312 
313 static int
314 ptsread(struct cdev *dev, struct uio *uio, int flag)
315 {
316 	struct tty *tp = dev->si_tty;
317 	int error = 0;
318 
319 	if (tp->t_oproc)
320 		error = ttyld_read(tp, uio, flag);
321 	ptcwakeup(tp, FWRITE);
322 	return (error);
323 }
324 
325 /*
326  * Write to pseudo-tty.
327  * Wakeups of controlling tty will happen
328  * indirectly, when tty driver calls ptsstart.
329  */
330 static int
331 ptswrite(struct cdev *dev, struct uio *uio, int flag)
332 {
333 	struct tty *tp;
334 
335 	tp = dev->si_tty;
336 	if (tp->t_oproc == 0)
337 		return (EIO);
338 	return (ttyld_write(tp, uio, flag));
339 }
340 
341 /*
342  * Start output on pseudo-tty.
343  * Wake up process selecting or sleeping for input from controlling tty.
344  */
345 static void
346 ptsstart(struct tty *tp)
347 {
348 	struct pt_desc *pt = tp->t_dev->si_drv1;
349 
350 	if (tp->t_state & TS_TTSTOP)
351 		return;
352 	if (pt->pt_flags & PF_STOPPED) {
353 		pt->pt_flags &= ~PF_STOPPED;
354 		pt->pt_send = TIOCPKT_START;
355 	}
356 	ptcwakeup(tp, FREAD);
357 }
358 
359 static void
360 ptcwakeup(struct tty *tp, int flag)
361 {
362 	struct pt_desc *pt = tp->t_dev->si_drv1;
363 
364 	if (flag & FREAD) {
365 		selwakeup(&pt->pt_selr);
366 		wakeup(TSA_PTC_READ(tp));
367 	}
368 	if (flag & FWRITE) {
369 		selwakeup(&pt->pt_selw);
370 		wakeup(TSA_PTC_WRITE(tp));
371 	}
372 }
373 
374 /*
375  * ptcopen implementes exclusive access to the master/control device
376  * as well as creating the slave device based on the credential of the
377  * process opening the master.  By creating the slave here, we avoid
378  * a race to access the master in terms of having a process with access
379  * to an incorrectly owned slave, but it does create the possibility
380  * that a racing process can cause a ptmx user to get EIO if it gets
381  * there first.  Consumers of ptmx must look for EIO and retry if it
382  * happens.  VFS locking may actually prevent this from occurring due
383  * to the lookup into devfs holding the vnode lock through open, but
384  * it's better to be careful.
385  */
386 static int
387 ptcopen(struct cdev *dev, int flag, int devtype, struct thread *td)
388 {
389 	struct pt_desc *pt;
390 	struct tty *tp;
391 	struct cdev *devs;
392 
393 	pt = dev->si_drv1;
394 	if (pt == NULL)
395 		return (EIO);
396 	/*
397 	 * In case we have destroyed the struct tty at the last connect time,
398 	 * we need to recreate it.
399 	 */
400 	if (pt->pt_tty == NULL) {
401 		tp = ttyalloc();
402 		mtx_lock(&pt_mtx);
403 		if (pt->pt_tty == NULL) {
404 			pt->pt_tty = tp;
405 			dev->si_tty = pt->pt_tty;
406 			mtx_unlock(&pt_mtx);
407 		} else {
408 			mtx_unlock(&pt_mtx);
409 			ttyrel(tp);
410 		}
411 	}
412 	tp = dev->si_tty;
413 	if (tp->t_oproc)
414 		return (EIO);
415 
416 	/*
417 	 * XXX: Might want to make the ownership/permissions here more
418 	 * configurable.
419 	 */
420 	if (pt->pt_devs)
421 		devs = pt->pt_devs;
422 	else
423 		pt->pt_devs = devs = make_dev_cred(&pts_cdevsw,
424 		    NUM_TO_MINOR(pt->pt_num),
425 		    td->td_ucred, UID_ROOT, GID_WHEEL, 0666, "pts/%d",
426 		    pt->pt_num);
427 	devs->si_drv1 = pt;
428 	devs->si_tty = pt->pt_tty;
429 	pt->pt_tty->t_dev = devs;
430 
431 	tp->t_timeout = -1;
432 	tp->t_oproc = ptsstart;
433 	tp->t_stop = ptsstop;
434 	ttyld_modem(tp, 1);
435 	tp->t_lflag &= ~EXTPROC;
436 	pt = dev->si_drv1;
437 	pt->pt_prison = td->td_ucred->cr_prison;
438 	pt->pt_flags = 0;
439 	pt->pt_send = 0;
440 	pt->pt_ucntl = 0;
441 	pt->pt_ptc_open = 1;
442 	return (0);
443 }
444 
445 static int
446 ptcclose(struct cdev *dev, int flags, int fmt, struct thread *td)
447 {
448 	struct pt_desc *pt = dev->si_drv1;
449 	struct tty *tp;
450 
451 	tp = dev->si_tty;
452 	ttyld_modem(tp, 0);
453 
454 	/*
455 	 * XXX MDMBUF makes no sense for ptys but would inhibit the above
456 	 * l_modem().  CLOCAL makes sense but isn't supported.   Special
457 	 * l_modem()s that ignore carrier drop make no sense for ptys but
458 	 * may be in use because other parts of the line discipline make
459 	 * sense for ptys.  Recover by doing everything that a normal
460 	 * ttymodem() would have done except for sending a SIGHUP.
461 	 */
462 	if (tp->t_state & TS_ISOPEN) {
463 		tp->t_state &= ~(TS_CARR_ON | TS_CONNECTED);
464 		tp->t_state |= TS_ZOMBIE;
465 		ttyflush(tp, FREAD | FWRITE);
466 	}
467 
468 	tp->t_oproc = 0;		/* mark closed */
469 	pt->pt_ptc_open = 0;
470 	pty_maybecleanup(pt);
471 	return (0);
472 }
473 
474 static int
475 ptcread(struct cdev *dev, struct uio *uio, int flag)
476 {
477 	struct tty *tp = dev->si_tty;
478 	struct pt_desc *pt = dev->si_drv1;
479 	char buf[BUFSIZ];
480 	int error = 0, cc;
481 
482 	/*
483 	 * We want to block until the slave
484 	 * is open, and there's something to read;
485 	 * but if we lost the slave or we're NBIO,
486 	 * then return the appropriate error instead.
487 	 */
488 	for (;;) {
489 		if (tp->t_state&TS_ISOPEN) {
490 			if (pt->pt_flags&PF_PKT && pt->pt_send) {
491 				error = ureadc((int)pt->pt_send, uio);
492 				if (error)
493 					return (error);
494 				if (pt->pt_send & TIOCPKT_IOCTL) {
495 					cc = min(uio->uio_resid,
496 						sizeof(tp->t_termios));
497 					uiomove(&tp->t_termios, cc, uio);
498 				}
499 				pt->pt_send = 0;
500 				return (0);
501 			}
502 			if (pt->pt_flags&PF_UCNTL && pt->pt_ucntl) {
503 				error = ureadc((int)pt->pt_ucntl, uio);
504 				if (error)
505 					return (error);
506 				pt->pt_ucntl = 0;
507 				return (0);
508 			}
509 			if (tp->t_outq.c_cc && (tp->t_state&TS_TTSTOP) == 0)
510 				break;
511 		}
512 		if ((tp->t_state & TS_CONNECTED) == 0)
513 			return (0);	/* EOF */
514 		if (flag & O_NONBLOCK)
515 			return (EWOULDBLOCK);
516 		error = tsleep(TSA_PTC_READ(tp), TTIPRI | PCATCH, "ptcin", 0);
517 		if (error)
518 			return (error);
519 	}
520 	if (pt->pt_flags & (PF_PKT|PF_UCNTL))
521 		error = ureadc(0, uio);
522 	while (uio->uio_resid > 0 && error == 0) {
523 		cc = q_to_b(&tp->t_outq, buf, min(uio->uio_resid, BUFSIZ));
524 		if (cc <= 0)
525 			break;
526 		error = uiomove(buf, cc, uio);
527 	}
528 	ttwwakeup(tp);
529 	return (error);
530 }
531 
532 static void
533 ptsstop(struct tty *tp, int flush)
534 {
535 	struct pt_desc *pt = tp->t_dev->si_drv1;
536 	int flag;
537 
538 	/* note: FLUSHREAD and FLUSHWRITE already ok */
539 	if (flush == 0) {
540 		flush = TIOCPKT_STOP;
541 		pt->pt_flags |= PF_STOPPED;
542 	} else
543 		pt->pt_flags &= ~PF_STOPPED;
544 	pt->pt_send |= flush;
545 	/* change of perspective */
546 	flag = 0;
547 	if (flush & FREAD)
548 		flag |= FWRITE;
549 	if (flush & FWRITE)
550 		flag |= FREAD;
551 	ptcwakeup(tp, flag);
552 }
553 
554 static int
555 ptcpoll(struct cdev *dev, int events, struct thread *td)
556 {
557 	struct tty *tp = dev->si_tty;
558 	struct pt_desc *pt = dev->si_drv1;
559 	int revents = 0;
560 	int s;
561 
562 	if ((tp->t_state & TS_CONNECTED) == 0)
563 		return (events &
564 		   (POLLHUP | POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM));
565 
566 	/*
567 	 * Need to block timeouts (ttrstart).
568 	 */
569 	s = spltty();
570 
571 	if (events & (POLLIN | POLLRDNORM))
572 		if ((tp->t_state & TS_ISOPEN) &&
573 		    ((tp->t_outq.c_cc && (tp->t_state & TS_TTSTOP) == 0) ||
574 		     ((pt->pt_flags & PF_PKT) && pt->pt_send) ||
575 		     ((pt->pt_flags & PF_UCNTL) && pt->pt_ucntl)))
576 			revents |= events & (POLLIN | POLLRDNORM);
577 
578 	if (events & (POLLOUT | POLLWRNORM))
579 		if (tp->t_state & TS_ISOPEN &&
580 		     (((tp->t_rawq.c_cc + tp->t_canq.c_cc < TTYHOG - 2) ||
581 		      (tp->t_canq.c_cc == 0 && (tp->t_lflag & ICANON)))))
582 			revents |= events & (POLLOUT | POLLWRNORM);
583 
584 	if (events & POLLHUP)
585 		if ((tp->t_state & TS_CARR_ON) == 0)
586 			revents |= POLLHUP;
587 
588 	if (revents == 0) {
589 		if (events & (POLLIN | POLLRDNORM))
590 			selrecord(td, &pt->pt_selr);
591 
592 		if (events & (POLLOUT | POLLWRNORM))
593 			selrecord(td, &pt->pt_selw);
594 	}
595 	splx(s);
596 
597 	return (revents);
598 }
599 
600 static int
601 ptcwrite(struct cdev *dev, struct uio *uio, int flag)
602 {
603 	struct tty *tp = dev->si_tty;
604 	u_char *cp = 0;
605 	int cc = 0;
606 	u_char locbuf[BUFSIZ];
607 	int cnt = 0;
608 	int error = 0;
609 
610 again:
611 	if ((tp->t_state&TS_ISOPEN) == 0)
612 		goto block;
613 	while (uio->uio_resid > 0 || cc > 0) {
614 		if (cc == 0) {
615 			cc = min(uio->uio_resid, BUFSIZ);
616 			cp = locbuf;
617 			error = uiomove(cp, cc, uio);
618 			if (error)
619 				return (error);
620 			/* check again for safety */
621 			if ((tp->t_state & TS_ISOPEN) == 0) {
622 				/* adjust for data copied in but not written */
623 				uio->uio_resid += cc;
624 				return (EIO);
625 			}
626 		}
627 		while (cc > 0) {
628 			if ((tp->t_rawq.c_cc + tp->t_canq.c_cc) >= TTYHOG - 2 &&
629 			   (tp->t_canq.c_cc > 0 || !(tp->t_lflag&ICANON))) {
630 				wakeup(TSA_HUP_OR_INPUT(tp));
631 				goto block;
632 			}
633 			ttyld_rint(tp, *cp++);
634 			cnt++;
635 			cc--;
636 		}
637 		cc = 0;
638 	}
639 	return (0);
640 block:
641 	/*
642 	 * Come here to wait for slave to open, for space
643 	 * in outq, or space in rawq, or an empty canq.
644 	 */
645 	if ((tp->t_state & TS_CONNECTED) == 0) {
646 		/* adjust for data copied in but not written */
647 		uio->uio_resid += cc;
648 		return (EIO);
649 	}
650 	if (flag & IO_NDELAY) {
651 		/* adjust for data copied in but not written */
652 		uio->uio_resid += cc;
653 		if (cnt == 0)
654 			return (EWOULDBLOCK);
655 		return (0);
656 	}
657 	error = tsleep(TSA_PTC_WRITE(tp), TTOPRI | PCATCH, "ptcout", 0);
658 	if (error) {
659 		/* adjust for data copied in but not written */
660 		uio->uio_resid += cc;
661 		return (error);
662 	}
663 	goto again;
664 }
665 
666 static int
667 ptcioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
668 {
669 	struct tty *tp = dev->si_tty;
670 	struct pt_desc *pt = dev->si_drv1;
671 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
672     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
673 	int ival;
674 #endif
675 
676 	switch (cmd) {
677 
678 	case TIOCGPGRP:
679 		/*
680 		 * We avoid calling ttioctl on the controller since,
681 		 * in that case, tp must be the controlling terminal.
682 		 */
683 		*(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : 0;
684 		return (0);
685 
686 	case TIOCPKT:
687 		if (*(int *)data) {
688 			if (pt->pt_flags & PF_UCNTL)
689 				return (EINVAL);
690 			pt->pt_flags |= PF_PKT;
691 		} else
692 			pt->pt_flags &= ~PF_PKT;
693 		return (0);
694 
695 	case TIOCUCNTL:
696 		if (*(int *)data) {
697 			if (pt->pt_flags & PF_PKT)
698 				return (EINVAL);
699 			pt->pt_flags |= PF_UCNTL;
700 		} else
701 			pt->pt_flags &= ~PF_UCNTL;
702 		return (0);
703 	case TIOCGPTN:
704 		*(unsigned int *)data = pt->pt_num;
705 		return (0);
706 	}
707 
708 	/*
709 	 * The rest of the ioctls shouldn't be called until
710 	 * the slave is open.
711 	 */
712 	if ((tp->t_state & TS_ISOPEN) == 0) {
713 		if (cmd == TIOCGETA) {
714 			/*
715 			 * TIOCGETA is used by isatty() to make sure it's
716 			 * a tty. Linux openpty() calls isatty() very early,
717 			 * before the slave is opened, so don't actually
718 			 * fill the struct termios, but just let isatty()
719 			 * know it's a tty.
720 			 */
721 			return (0);
722 		}
723 		if (cmd != FIONBIO && cmd != FIOASYNC)
724 			return (EAGAIN);
725 	}
726 
727 	switch (cmd) {
728 #ifdef COMPAT_43TTY
729 	case TIOCSETP:
730 	case TIOCSETN:
731 #endif
732 	case TIOCSETD:
733 	case TIOCSETA:
734 	case TIOCSETAW:
735 	case TIOCSETAF:
736 		/*
737 		 * IF CONTROLLER STTY THEN MUST FLUSH TO PREVENT A HANG.
738 		 * ttywflush(tp) will hang if there are characters in
739 		 * the outq.
740 		 */
741 		ndflush(&tp->t_outq, tp->t_outq.c_cc);
742 		break;
743 
744 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
745     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
746 	case _IO('t', 95):
747 		ival = IOCPARM_IVAL(data);
748 		data = (caddr_t)&ival;
749 		/* FALLTHROUGH */
750 #endif
751 	case TIOCSIG:
752 		if (*(unsigned int *)data >= NSIG ||
753 		    *(unsigned int *)data == 0)
754 			return(EINVAL);
755 		if ((tp->t_lflag&NOFLSH) == 0)
756 			ttyflush(tp, FREAD|FWRITE);
757 		if (tp->t_pgrp != NULL) {
758 			PGRP_LOCK(tp->t_pgrp);
759 			pgsignal(tp->t_pgrp, *(unsigned int *)data, 1);
760 			PGRP_UNLOCK(tp->t_pgrp);
761 		}
762 		if ((*(unsigned int *)data == SIGINFO) &&
763 		    ((tp->t_lflag&NOKERNINFO) == 0))
764 			ttyinfo(tp);
765 		return(0);
766 	}
767 	return (ptsioctl(dev, cmd, data, flag, td));
768 }
769 /*ARGSUSED*/
770 static int
771 ptsioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
772 {
773 	struct tty *tp = dev->si_tty;
774 	struct pt_desc *pt = dev->si_drv1;
775 	u_char *cc = tp->t_cc;
776 	int stop, error;
777 
778 	if (cmd == TIOCEXT) {
779 		/*
780 		 * When the EXTPROC bit is being toggled, we need
781 		 * to send an TIOCPKT_IOCTL if the packet driver
782 		 * is turned on.
783 		 */
784 		if (*(int *)data) {
785 			if (pt->pt_flags & PF_PKT) {
786 				pt->pt_send |= TIOCPKT_IOCTL;
787 				ptcwakeup(tp, FREAD);
788 			}
789 			tp->t_lflag |= EXTPROC;
790 		} else {
791 			if ((tp->t_lflag & EXTPROC) &&
792 			    (pt->pt_flags & PF_PKT)) {
793 				pt->pt_send |= TIOCPKT_IOCTL;
794 				ptcwakeup(tp, FREAD);
795 			}
796 			tp->t_lflag &= ~EXTPROC;
797 		}
798 		return(0);
799 	}
800 	error = ttioctl(tp, cmd, data, flag);
801 	if (error == ENOTTY) {
802 		if (pt->pt_flags & PF_UCNTL &&
803 		    (cmd & ~0xff) == UIOCCMD(0)) {
804 			if (cmd & 0xff) {
805 				pt->pt_ucntl = (u_char)cmd;
806 				ptcwakeup(tp, FREAD);
807 			}
808 			return (0);
809 		}
810 		error = ENOTTY;
811 	}
812 	/*
813 	 * If external processing and packet mode send ioctl packet.
814 	 */
815 	if ((tp->t_lflag&EXTPROC) && (pt->pt_flags & PF_PKT)) {
816 		switch(cmd) {
817 		case TIOCSETA:
818 		case TIOCSETAW:
819 		case TIOCSETAF:
820 #ifdef COMPAT_43TTY
821 		case TIOCSETP:
822 		case TIOCSETN:
823 		case TIOCSETC:
824 		case TIOCSLTC:
825 		case TIOCLBIS:
826 		case TIOCLBIC:
827 		case TIOCLSET:
828 #endif
829 			pt->pt_send |= TIOCPKT_IOCTL;
830 			ptcwakeup(tp, FREAD);
831 			break;
832 		default:
833 			break;
834 		}
835 	}
836 	stop = (tp->t_iflag & IXON) && CCEQ(cc[VSTOP], CTRL('s'))
837 		&& CCEQ(cc[VSTART], CTRL('q'));
838 	if (pt->pt_flags & PF_NOSTOP) {
839 		if (stop) {
840 			pt->pt_send &= ~TIOCPKT_NOSTOP;
841 			pt->pt_send |= TIOCPKT_DOSTOP;
842 			pt->pt_flags &= ~PF_NOSTOP;
843 			ptcwakeup(tp, FREAD);
844 		}
845 	} else {
846 		if (!stop) {
847 			pt->pt_send &= ~TIOCPKT_DOSTOP;
848 			pt->pt_send |= TIOCPKT_NOSTOP;
849 			pt->pt_flags |= PF_NOSTOP;
850 			ptcwakeup(tp, FREAD);
851 		}
852 	}
853 	return (error);
854 }
855 
856 /*
857  * Match lookups on /dev/ptmx, find the next free pty (if any), set up
858  * the pty descriptor, register it, and return a reference to the master.
859  *
860  * pts == /dev/pts/xxx (oldstyle: ttyp...)
861  * ptc == /dev/pty/xxx (oldstyle: ptyp...)
862  */
863 static void
864 pty_clone(void *arg, struct ucred *cred, char *name, int namelen,
865     struct cdev **dev)
866 {
867 	struct pt_desc *pt;
868 	struct cdev *devc;
869 
870 	if (!use_pts)
871 		return;
872 
873 	if (*dev != NULL)
874 		return;
875 
876 	if (strcmp(name, "ptmx") != 0)
877 		return;
878 
879 	mtx_lock(&Giant);
880 	pt = pty_new();
881 	if (pt == NULL) {
882 		mtx_unlock(&Giant);
883 		return;
884 	}
885 
886 	/*
887 	 * XXX: Lack of locking here considered worrying.  We expose the
888 	 * pts/pty device nodes before they are fully initialized, although
889 	 * Giant likely protects us (unless make_dev blocks...?).
890 	 *
891 	 * XXX: If a process performs a lookup on /dev/ptmx but never an
892 	 * open, we won't GC the device node.  We should have a callout
893 	 * sometime later that GC's device instances that were never
894 	 * opened, or some way to tell devfs that "this had better be for
895 	 * an open() or we won't create a device".
896 	 */
897 	pt->pt_devc = devc = make_dev_credf(MAKEDEV_REF, &ptc_cdevsw,
898 	    NUM_TO_MINOR(pt->pt_num), cred, UID_ROOT, GID_WHEEL, 0666,
899 	    "pty/%d", pt->pt_num);
900 
901 	devc->si_drv1 = pt;
902 	devc->si_tty = pt->pt_tty;
903 	*dev = devc;
904 	mtx_unlock(&Giant);
905 
906 	if (bootverbose)
907 		printf("pty_clone: allocated pty %d to uid %d\n", pt->pt_num,
908 	    cred->cr_ruid);
909 
910 	return;
911 }
912 
913 static void
914 pty_drvinit(void *unused)
915 {
916 
917 	mtx_init(&pt_mtx, "pt_mtx", NULL, MTX_DEF);
918 	LIST_INIT(&pt_list);
919 	LIST_INIT(&pt_free_list);
920 	EVENTHANDLER_REGISTER(dev_clone, pty_clone, 0, 1000);
921 }
922 
923 SYSINIT(ptydev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE,pty_drvinit,NULL);
924