xref: /freebsd/sys/kern/tty_pts.c (revision 2be1a816b9ff69588e55be0a84cbe2a31efc0f2f)
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 		LIST_INSERT_HEAD(&pt_list, pt, pt_list);
198 		mtx_unlock(&pt_mtx);
199 	} else {
200 		nb = next_avail_nb++;
201 		mtx_unlock(&pt_mtx);
202 		pt = malloc(sizeof(*pt), M_PTY, M_WAITOK | M_ZERO);
203 		mtx_lock(&pt_mtx);
204 		pt->pt_num = nb;
205 		LIST_INSERT_HEAD(&pt_list, pt, pt_list);
206 		mtx_unlock(&pt_mtx);
207 		pt->pt_tty = ttyalloc();
208 	}
209 	return (pt);
210 }
211 
212 /*
213  * Release a pty descriptor back to the pool for reuse.  The pty number
214  * remains allocated.
215  */
216 static void
217 pty_release(void *v)
218 {
219 	struct pt_desc *pt = (struct pt_desc *)v;
220 
221 	mtx_lock(&pt_mtx);
222 	KASSERT(pt->pt_ptc_open == 0 && pt->pt_pts_open == 0,
223 	    ("pty_release: pts/%d freed while open\n", pt->pt_num));
224 	KASSERT(pt->pt_devs == NULL && pt->pt_devc == NULL,
225 	    ("pty_release: pts/%d freed whith non-null struct cdev\n", pt->pt_num));
226 	nb_allocated--;
227 	LIST_REMOVE(pt, pt_list);
228 	LIST_INSERT_HEAD(&pt_free_list, pt, pt_list);
229 	mtx_unlock(&pt_mtx);
230 }
231 
232 /*
233  * Given a pty descriptor, if both endpoints are closed, release all
234  * resources and destroy the device nodes to flush file system level
235  * state for the tty (owner, avoid races, etc).
236  */
237 static void
238 pty_maybecleanup(struct pt_desc *pt)
239 {
240 	struct cdev *pt_devs, *pt_devc;
241 
242 	if (pt->pt_ptc_open || pt->pt_pts_open)
243 		return;
244 
245 	if (pt->pt_tty->t_refcnt > 1)
246 		return;
247 
248 	if (bootverbose)
249 		printf("destroying pty %d\n", pt->pt_num);
250 
251 	pt_devs = pt->pt_devs;
252 	pt_devc = pt->pt_devc;
253 	pt->pt_devs = pt->pt_devc = NULL;
254 	pt->pt_tty->t_dev = NULL;
255 	pt_devc->si_drv1 = NULL;
256 	ttyrel(pt->pt_tty);
257 	pt->pt_tty = NULL;
258 	destroy_dev_sched(pt_devs);
259 	destroy_dev_sched_cb(pt_devc, pty_release, pt);
260 }
261 
262 /*ARGSUSED*/
263 static int
264 ptsopen(struct cdev *dev, int flag, int devtype, struct thread *td)
265 {
266 	struct tty *tp;
267 	int error;
268 	struct pt_desc *pt;
269 
270 	pt = dev->si_drv1;
271 	tp = dev->si_tty;
272 	if ((tp->t_state & TS_ISOPEN) == 0)
273 		ttyinitmode(tp, 1, 0);
274 	else if (tp->t_state & TS_XCLUDE && priv_check(td,
275 	    PRIV_TTY_EXCLUSIVE)) {
276 		return (EBUSY);
277 	} else if (pt->pt_prison != td->td_ucred->cr_prison &&
278 	    priv_check(td, PRIV_TTY_PRISON)) {
279 		return (EBUSY);
280 	}
281 	if (tp->t_oproc)			/* Ctrlr still around. */
282 		ttyld_modem(tp, 1);
283 	while ((tp->t_state & TS_CARR_ON) == 0) {
284 		if (flag & FNONBLOCK)
285 			break;
286 		error = ttysleep(tp, TSA_CARR_ON(tp), TTIPRI | PCATCH,
287 				 "ptsopn", 0);
288 		if (error)
289 			return (error);
290 	}
291 	error = ttyld_open(tp, dev);
292 	if (error == 0) {
293 		ptcwakeup(tp, FREAD|FWRITE);
294 		pt->pt_pts_open = 1;
295 	}
296 	return (error);
297 }
298 
299 static int
300 ptsclose(struct cdev *dev, int flag, int mode, struct thread *td)
301 {
302 	struct pt_desc *pt = dev->si_drv1;
303 	struct tty *tp;
304 	int err;
305 
306 	tp = dev->si_tty;
307 	err = ttyld_close(tp, flag);
308 	ptsstop(tp, FREAD|FWRITE);
309 	(void) tty_close(tp);
310 	pt->pt_pts_open = 0;
311 	pty_maybecleanup(pt);
312 	return (err);
313 }
314 
315 static int
316 ptsread(struct cdev *dev, struct uio *uio, int flag)
317 {
318 	struct tty *tp = dev->si_tty;
319 	int error = 0;
320 
321 	if (tp->t_oproc)
322 		error = ttyld_read(tp, uio, flag);
323 	ptcwakeup(tp, FWRITE);
324 	return (error);
325 }
326 
327 /*
328  * Write to pseudo-tty.
329  * Wakeups of controlling tty will happen
330  * indirectly, when tty driver calls ptsstart.
331  */
332 static int
333 ptswrite(struct cdev *dev, struct uio *uio, int flag)
334 {
335 	struct tty *tp;
336 
337 	tp = dev->si_tty;
338 	if (tp->t_oproc == 0)
339 		return (EIO);
340 	return (ttyld_write(tp, uio, flag));
341 }
342 
343 /*
344  * Start output on pseudo-tty.
345  * Wake up process selecting or sleeping for input from controlling tty.
346  */
347 static void
348 ptsstart(struct tty *tp)
349 {
350 	struct pt_desc *pt = tp->t_dev->si_drv1;
351 
352 	if (tp->t_state & TS_TTSTOP)
353 		return;
354 	if (pt->pt_flags & PF_STOPPED) {
355 		pt->pt_flags &= ~PF_STOPPED;
356 		pt->pt_send = TIOCPKT_START;
357 	}
358 	ptcwakeup(tp, FREAD);
359 }
360 
361 static void
362 ptcwakeup(struct tty *tp, int flag)
363 {
364 	struct pt_desc *pt = tp->t_dev->si_drv1;
365 
366 	if (flag & FREAD) {
367 		selwakeup(&pt->pt_selr);
368 		wakeup(TSA_PTC_READ(tp));
369 	}
370 	if (flag & FWRITE) {
371 		selwakeup(&pt->pt_selw);
372 		wakeup(TSA_PTC_WRITE(tp));
373 	}
374 }
375 
376 /*
377  * ptcopen implementes exclusive access to the master/control device
378  * as well as creating the slave device based on the credential of the
379  * process opening the master.  By creating the slave here, we avoid
380  * a race to access the master in terms of having a process with access
381  * to an incorrectly owned slave, but it does create the possibility
382  * that a racing process can cause a ptmx user to get EIO if it gets
383  * there first.  Consumers of ptmx must look for EIO and retry if it
384  * happens.  VFS locking may actually prevent this from occurring due
385  * to the lookup into devfs holding the vnode lock through open, but
386  * it's better to be careful.
387  */
388 static int
389 ptcopen(struct cdev *dev, int flag, int devtype, struct thread *td)
390 {
391 	struct pt_desc *pt;
392 	struct tty *tp;
393 	struct cdev *devs;
394 
395 	pt = dev->si_drv1;
396 	if (pt == NULL)
397 		return (EIO);
398 	/*
399 	 * In case we have destroyed the struct tty at the last connect time,
400 	 * we need to recreate it.
401 	 */
402 	if (pt->pt_tty == NULL) {
403 		pt->pt_tty = ttyalloc();
404 		dev->si_tty = pt->pt_tty;
405 	}
406 	tp = dev->si_tty;
407 	if (tp->t_oproc)
408 		return (EIO);
409 
410 	/*
411 	 * XXX: Might want to make the ownership/permissions here more
412 	 * configurable.
413 	 */
414 	if (pt->pt_devs)
415 		devs = pt->pt_devs;
416 	else
417 		pt->pt_devs = devs = make_dev_cred(&pts_cdevsw,
418 		    NUM_TO_MINOR(pt->pt_num),
419 		    td->td_ucred, UID_ROOT, GID_WHEEL, 0666, "pts/%d",
420 		    pt->pt_num);
421 	devs->si_drv1 = pt;
422 	devs->si_tty = pt->pt_tty;
423 	pt->pt_tty->t_dev = devs;
424 
425 	tp->t_timeout = -1;
426 	tp->t_oproc = ptsstart;
427 	tp->t_stop = ptsstop;
428 	ttyld_modem(tp, 1);
429 	tp->t_lflag &= ~EXTPROC;
430 	pt = dev->si_drv1;
431 	pt->pt_prison = td->td_ucred->cr_prison;
432 	pt->pt_flags = 0;
433 	pt->pt_send = 0;
434 	pt->pt_ucntl = 0;
435 	pt->pt_ptc_open = 1;
436 	return (0);
437 }
438 
439 static int
440 ptcclose(struct cdev *dev, int flags, int fmt, struct thread *td)
441 {
442 	struct pt_desc *pt = dev->si_drv1;
443 	struct tty *tp;
444 
445 	tp = dev->si_tty;
446 	ttyld_modem(tp, 0);
447 
448 	/*
449 	 * XXX MDMBUF makes no sense for ptys but would inhibit the above
450 	 * l_modem().  CLOCAL makes sense but isn't supported.   Special
451 	 * l_modem()s that ignore carrier drop make no sense for ptys but
452 	 * may be in use because other parts of the line discipline make
453 	 * sense for ptys.  Recover by doing everything that a normal
454 	 * ttymodem() would have done except for sending a SIGHUP.
455 	 */
456 	if (tp->t_state & TS_ISOPEN) {
457 		tp->t_state &= ~(TS_CARR_ON | TS_CONNECTED);
458 		tp->t_state |= TS_ZOMBIE;
459 		ttyflush(tp, FREAD | FWRITE);
460 	}
461 
462 	tp->t_oproc = 0;		/* mark closed */
463 	pt->pt_ptc_open = 0;
464 	pty_maybecleanup(pt);
465 	return (0);
466 }
467 
468 static int
469 ptcread(struct cdev *dev, struct uio *uio, int flag)
470 {
471 	struct tty *tp = dev->si_tty;
472 	struct pt_desc *pt = dev->si_drv1;
473 	char buf[BUFSIZ];
474 	int error = 0, cc;
475 
476 	/*
477 	 * We want to block until the slave
478 	 * is open, and there's something to read;
479 	 * but if we lost the slave or we're NBIO,
480 	 * then return the appropriate error instead.
481 	 */
482 	for (;;) {
483 		if (tp->t_state&TS_ISOPEN) {
484 			if (pt->pt_flags&PF_PKT && pt->pt_send) {
485 				error = ureadc((int)pt->pt_send, uio);
486 				if (error)
487 					return (error);
488 				if (pt->pt_send & TIOCPKT_IOCTL) {
489 					cc = min(uio->uio_resid,
490 						sizeof(tp->t_termios));
491 					uiomove(&tp->t_termios, cc, uio);
492 				}
493 				pt->pt_send = 0;
494 				return (0);
495 			}
496 			if (pt->pt_flags&PF_UCNTL && pt->pt_ucntl) {
497 				error = ureadc((int)pt->pt_ucntl, uio);
498 				if (error)
499 					return (error);
500 				pt->pt_ucntl = 0;
501 				return (0);
502 			}
503 			if (tp->t_outq.c_cc && (tp->t_state&TS_TTSTOP) == 0)
504 				break;
505 		}
506 		if ((tp->t_state & TS_CONNECTED) == 0)
507 			return (0);	/* EOF */
508 		if (flag & O_NONBLOCK)
509 			return (EWOULDBLOCK);
510 		error = tsleep(TSA_PTC_READ(tp), TTIPRI | PCATCH, "ptcin", 0);
511 		if (error)
512 			return (error);
513 	}
514 	if (pt->pt_flags & (PF_PKT|PF_UCNTL))
515 		error = ureadc(0, uio);
516 	while (uio->uio_resid > 0 && error == 0) {
517 		cc = q_to_b(&tp->t_outq, buf, min(uio->uio_resid, BUFSIZ));
518 		if (cc <= 0)
519 			break;
520 		error = uiomove(buf, cc, uio);
521 	}
522 	ttwwakeup(tp);
523 	return (error);
524 }
525 
526 static void
527 ptsstop(struct tty *tp, int flush)
528 {
529 	struct pt_desc *pt = tp->t_dev->si_drv1;
530 	int flag;
531 
532 	/* note: FLUSHREAD and FLUSHWRITE already ok */
533 	if (flush == 0) {
534 		flush = TIOCPKT_STOP;
535 		pt->pt_flags |= PF_STOPPED;
536 	} else
537 		pt->pt_flags &= ~PF_STOPPED;
538 	pt->pt_send |= flush;
539 	/* change of perspective */
540 	flag = 0;
541 	if (flush & FREAD)
542 		flag |= FWRITE;
543 	if (flush & FWRITE)
544 		flag |= FREAD;
545 	ptcwakeup(tp, flag);
546 }
547 
548 static int
549 ptcpoll(struct cdev *dev, int events, struct thread *td)
550 {
551 	struct tty *tp = dev->si_tty;
552 	struct pt_desc *pt = dev->si_drv1;
553 	int revents = 0;
554 	int s;
555 
556 	if ((tp->t_state & TS_CONNECTED) == 0)
557 		return (events &
558 		   (POLLHUP | POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM));
559 
560 	/*
561 	 * Need to block timeouts (ttrstart).
562 	 */
563 	s = spltty();
564 
565 	if (events & (POLLIN | POLLRDNORM))
566 		if ((tp->t_state & TS_ISOPEN) &&
567 		    ((tp->t_outq.c_cc && (tp->t_state & TS_TTSTOP) == 0) ||
568 		     ((pt->pt_flags & PF_PKT) && pt->pt_send) ||
569 		     ((pt->pt_flags & PF_UCNTL) && pt->pt_ucntl)))
570 			revents |= events & (POLLIN | POLLRDNORM);
571 
572 	if (events & (POLLOUT | POLLWRNORM))
573 		if (tp->t_state & TS_ISOPEN &&
574 		     (((tp->t_rawq.c_cc + tp->t_canq.c_cc < TTYHOG - 2) ||
575 		      (tp->t_canq.c_cc == 0 && (tp->t_lflag & ICANON)))))
576 			revents |= events & (POLLOUT | POLLWRNORM);
577 
578 	if (events & POLLHUP)
579 		if ((tp->t_state & TS_CARR_ON) == 0)
580 			revents |= POLLHUP;
581 
582 	if (revents == 0) {
583 		if (events & (POLLIN | POLLRDNORM))
584 			selrecord(td, &pt->pt_selr);
585 
586 		if (events & (POLLOUT | POLLWRNORM))
587 			selrecord(td, &pt->pt_selw);
588 	}
589 	splx(s);
590 
591 	return (revents);
592 }
593 
594 static int
595 ptcwrite(struct cdev *dev, struct uio *uio, int flag)
596 {
597 	struct tty *tp = dev->si_tty;
598 	u_char *cp = 0;
599 	int cc = 0;
600 	u_char locbuf[BUFSIZ];
601 	int cnt = 0;
602 	int error = 0;
603 
604 again:
605 	if ((tp->t_state&TS_ISOPEN) == 0)
606 		goto block;
607 	while (uio->uio_resid > 0 || cc > 0) {
608 		if (cc == 0) {
609 			cc = min(uio->uio_resid, BUFSIZ);
610 			cp = locbuf;
611 			error = uiomove(cp, cc, uio);
612 			if (error)
613 				return (error);
614 			/* check again for safety */
615 			if ((tp->t_state & TS_ISOPEN) == 0) {
616 				/* adjust for data copied in but not written */
617 				uio->uio_resid += cc;
618 				return (EIO);
619 			}
620 		}
621 		while (cc > 0) {
622 			if ((tp->t_rawq.c_cc + tp->t_canq.c_cc) >= TTYHOG - 2 &&
623 			   (tp->t_canq.c_cc > 0 || !(tp->t_lflag&ICANON))) {
624 				wakeup(TSA_HUP_OR_INPUT(tp));
625 				goto block;
626 			}
627 			ttyld_rint(tp, *cp++);
628 			cnt++;
629 			cc--;
630 		}
631 		cc = 0;
632 	}
633 	return (0);
634 block:
635 	/*
636 	 * Come here to wait for slave to open, for space
637 	 * in outq, or space in rawq, or an empty canq.
638 	 */
639 	if ((tp->t_state & TS_CONNECTED) == 0) {
640 		/* adjust for data copied in but not written */
641 		uio->uio_resid += cc;
642 		return (EIO);
643 	}
644 	if (flag & IO_NDELAY) {
645 		/* adjust for data copied in but not written */
646 		uio->uio_resid += cc;
647 		if (cnt == 0)
648 			return (EWOULDBLOCK);
649 		return (0);
650 	}
651 	error = tsleep(TSA_PTC_WRITE(tp), TTOPRI | PCATCH, "ptcout", 0);
652 	if (error) {
653 		/* adjust for data copied in but not written */
654 		uio->uio_resid += cc;
655 		return (error);
656 	}
657 	goto again;
658 }
659 
660 static int
661 ptcioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
662 {
663 	struct tty *tp = dev->si_tty;
664 	struct pt_desc *pt = dev->si_drv1;
665 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
666     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
667 	int ival;
668 #endif
669 
670 	switch (cmd) {
671 
672 	case TIOCGPGRP:
673 		/*
674 		 * We avoid calling ttioctl on the controller since,
675 		 * in that case, tp must be the controlling terminal.
676 		 */
677 		*(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : 0;
678 		return (0);
679 
680 	case TIOCPKT:
681 		if (*(int *)data) {
682 			if (pt->pt_flags & PF_UCNTL)
683 				return (EINVAL);
684 			pt->pt_flags |= PF_PKT;
685 		} else
686 			pt->pt_flags &= ~PF_PKT;
687 		return (0);
688 
689 	case TIOCUCNTL:
690 		if (*(int *)data) {
691 			if (pt->pt_flags & PF_PKT)
692 				return (EINVAL);
693 			pt->pt_flags |= PF_UCNTL;
694 		} else
695 			pt->pt_flags &= ~PF_UCNTL;
696 		return (0);
697 	case TIOCGPTN:
698 		*(unsigned int *)data = pt->pt_num;
699 		return (0);
700 	}
701 
702 	/*
703 	 * The rest of the ioctls shouldn't be called until
704 	 * the slave is open.
705 	 */
706 	if ((tp->t_state & TS_ISOPEN) == 0) {
707 		if (cmd == TIOCGETA) {
708 			/*
709 			 * TIOCGETA is used by isatty() to make sure it's
710 			 * a tty. Linux openpty() calls isatty() very early,
711 			 * before the slave is opened, so don't actually
712 			 * fill the struct termios, but just let isatty()
713 			 * know it's a tty.
714 			 */
715 			return (0);
716 		}
717 		if (cmd != FIONBIO && cmd != FIOASYNC)
718 			return (EAGAIN);
719 	}
720 
721 	switch (cmd) {
722 #ifdef COMPAT_43TTY
723 	case TIOCSETP:
724 	case TIOCSETN:
725 #endif
726 	case TIOCSETD:
727 	case TIOCSETA:
728 	case TIOCSETAW:
729 	case TIOCSETAF:
730 		/*
731 		 * IF CONTROLLER STTY THEN MUST FLUSH TO PREVENT A HANG.
732 		 * ttywflush(tp) will hang if there are characters in
733 		 * the outq.
734 		 */
735 		ndflush(&tp->t_outq, tp->t_outq.c_cc);
736 		break;
737 
738 #if defined(COMPAT_FREEBSD6) || defined(COMPAT_FREEBSD5) || \
739     defined(COMPAT_FREEBSD4) || defined(COMPAT_43)
740 	case _IO('t', 95):
741 		ival = IOCPARM_IVAL(data);
742 		data = (caddr_t)&ival;
743 		/* FALLTHROUGH */
744 #endif
745 	case TIOCSIG:
746 		if (*(unsigned int *)data >= NSIG ||
747 		    *(unsigned int *)data == 0)
748 			return(EINVAL);
749 		if ((tp->t_lflag&NOFLSH) == 0)
750 			ttyflush(tp, FREAD|FWRITE);
751 		if (tp->t_pgrp != NULL) {
752 			PGRP_LOCK(tp->t_pgrp);
753 			pgsignal(tp->t_pgrp, *(unsigned int *)data, 1);
754 			PGRP_UNLOCK(tp->t_pgrp);
755 		}
756 		if ((*(unsigned int *)data == SIGINFO) &&
757 		    ((tp->t_lflag&NOKERNINFO) == 0))
758 			ttyinfo(tp);
759 		return(0);
760 	}
761 	return (ptsioctl(dev, cmd, data, flag, td));
762 }
763 /*ARGSUSED*/
764 static int
765 ptsioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
766 {
767 	struct tty *tp = dev->si_tty;
768 	struct pt_desc *pt = dev->si_drv1;
769 	u_char *cc = tp->t_cc;
770 	int stop, error;
771 
772 	if (cmd == TIOCEXT) {
773 		/*
774 		 * When the EXTPROC bit is being toggled, we need
775 		 * to send an TIOCPKT_IOCTL if the packet driver
776 		 * is turned on.
777 		 */
778 		if (*(int *)data) {
779 			if (pt->pt_flags & PF_PKT) {
780 				pt->pt_send |= TIOCPKT_IOCTL;
781 				ptcwakeup(tp, FREAD);
782 			}
783 			tp->t_lflag |= EXTPROC;
784 		} else {
785 			if ((tp->t_lflag & EXTPROC) &&
786 			    (pt->pt_flags & PF_PKT)) {
787 				pt->pt_send |= TIOCPKT_IOCTL;
788 				ptcwakeup(tp, FREAD);
789 			}
790 			tp->t_lflag &= ~EXTPROC;
791 		}
792 		return(0);
793 	}
794 	error = ttioctl(tp, cmd, data, flag);
795 	if (error == ENOTTY) {
796 		if (pt->pt_flags & PF_UCNTL &&
797 		    (cmd & ~0xff) == UIOCCMD(0)) {
798 			if (cmd & 0xff) {
799 				pt->pt_ucntl = (u_char)cmd;
800 				ptcwakeup(tp, FREAD);
801 			}
802 			return (0);
803 		}
804 		error = ENOTTY;
805 	}
806 	/*
807 	 * If external processing and packet mode send ioctl packet.
808 	 */
809 	if ((tp->t_lflag&EXTPROC) && (pt->pt_flags & PF_PKT)) {
810 		switch(cmd) {
811 		case TIOCSETA:
812 		case TIOCSETAW:
813 		case TIOCSETAF:
814 #ifdef COMPAT_43TTY
815 		case TIOCSETP:
816 		case TIOCSETN:
817 		case TIOCSETC:
818 		case TIOCSLTC:
819 		case TIOCLBIS:
820 		case TIOCLBIC:
821 		case TIOCLSET:
822 #endif
823 			pt->pt_send |= TIOCPKT_IOCTL;
824 			ptcwakeup(tp, FREAD);
825 			break;
826 		default:
827 			break;
828 		}
829 	}
830 	stop = (tp->t_iflag & IXON) && CCEQ(cc[VSTOP], CTRL('s'))
831 		&& CCEQ(cc[VSTART], CTRL('q'));
832 	if (pt->pt_flags & PF_NOSTOP) {
833 		if (stop) {
834 			pt->pt_send &= ~TIOCPKT_NOSTOP;
835 			pt->pt_send |= TIOCPKT_DOSTOP;
836 			pt->pt_flags &= ~PF_NOSTOP;
837 			ptcwakeup(tp, FREAD);
838 		}
839 	} else {
840 		if (!stop) {
841 			pt->pt_send &= ~TIOCPKT_DOSTOP;
842 			pt->pt_send |= TIOCPKT_NOSTOP;
843 			pt->pt_flags |= PF_NOSTOP;
844 			ptcwakeup(tp, FREAD);
845 		}
846 	}
847 	return (error);
848 }
849 
850 /*
851  * Match lookups on /dev/ptmx, find the next free pty (if any), set up
852  * the pty descriptor, register it, and return a reference to the master.
853  *
854  * pts == /dev/pts/xxx (oldstyle: ttyp...)
855  * ptc == /dev/pty/xxx (oldstyle: ptyp...)
856  */
857 static void
858 pty_clone(void *arg, struct ucred *cred, char *name, int namelen,
859     struct cdev **dev)
860 {
861 	struct pt_desc *pt;
862 	struct cdev *devc;
863 
864 	if (!use_pts)
865 		return;
866 
867 	if (*dev != NULL)
868 		return;
869 
870 	if (strcmp(name, "ptmx") != 0)
871 		return;
872 
873 	mtx_lock(&Giant);
874 	pt = pty_new();
875 	if (pt == NULL) {
876 		mtx_unlock(&Giant);
877 		return;
878 	}
879 
880 	/*
881 	 * XXX: Lack of locking here considered worrying.  We expose the
882 	 * pts/pty device nodes before they are fully initialized, although
883 	 * Giant likely protects us (unless make_dev blocks...?).
884 	 *
885 	 * XXX: If a process performs a lookup on /dev/ptmx but never an
886 	 * open, we won't GC the device node.  We should have a callout
887 	 * sometime later that GC's device instances that were never
888 	 * opened, or some way to tell devfs that "this had better be for
889 	 * an open() or we won't create a device".
890 	 */
891 	pt->pt_devc = devc = make_dev_credf(MAKEDEV_REF, &ptc_cdevsw,
892 	    NUM_TO_MINOR(pt->pt_num), cred, UID_ROOT, GID_WHEEL, 0666,
893 	    "pty/%d", pt->pt_num);
894 
895 	devc->si_drv1 = pt;
896 	devc->si_tty = pt->pt_tty;
897 	*dev = devc;
898 	mtx_unlock(&Giant);
899 
900 	if (bootverbose)
901 		printf("pty_clone: allocated pty %d to uid %d\n", pt->pt_num,
902 	    cred->cr_ruid);
903 
904 	return;
905 }
906 
907 static void
908 pty_drvinit(void *unused)
909 {
910 
911 	mtx_init(&pt_mtx, "pt_mtx", NULL, MTX_DEF);
912 	LIST_INIT(&pt_list);
913 	LIST_INIT(&pt_free_list);
914 	EVENTHANDLER_REGISTER(dev_clone, pty_clone, 0, 1000);
915 }
916 
917 SYSINIT(ptydev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE,pty_drvinit,NULL);
918