xref: /xnu-11417.140.69/bsd/kern/tty_dev.c (revision 43a90889846e00bfb5cf1d255cdc0a701a1e05a4)
1 /*
2  * Copyright (c) 1997-2020 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /*
29  * Copyright (c) 1982, 1986, 1989, 1993
30  *      The Regents of the University of California.  All rights reserved.
31  *
32  * Redistribution and use in source and binary forms, with or without
33  * modification, are permitted provided that the following conditions
34  * are met:
35  * 1. Redistributions of source code must retain the above copyright
36  *    notice, this list of conditions and the following disclaimer.
37  * 2. Redistributions in binary form must reproduce the above copyright
38  *    notice, this list of conditions and the following disclaimer in the
39  *    documentation and/or other materials provided with the distribution.
40  * 3. All advertising materials mentioning features or use of this software
41  *    must display the following acknowledgement:
42  *      This product includes software developed by the University of
43  *      California, Berkeley and its contributors.
44  * 4. Neither the name of the University nor the names of its contributors
45  *    may be used to endorse or promote products derived from this software
46  *    without specific prior written permission.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58  * SUCH DAMAGE.
59  *
60  *	@(#)tty_pty.c	8.4 (Berkeley) 2/20/95
61  */
62 
63 /* Common callbacks for the pseudo-teletype driver (pty/tty)
64  * and cloning pseudo-teletype driver (ptmx/pts).
65  */
66 
67 #include <sys/param.h>
68 #include <sys/systm.h>
69 #include <sys/ioctl.h>
70 #include <sys/proc_internal.h>
71 #include <sys/kauth.h>
72 #include <sys/tty.h>
73 #include <sys/conf.h>
74 #include <sys/file_internal.h>
75 #include <sys/uio_internal.h>
76 #include <sys/kernel.h>
77 #include <sys/vnode.h>
78 #include <sys/vnode_internal.h>         /* _devfs_setattr() */
79 #include <sys/stat.h>                   /* _devfs_setattr() */
80 #include <sys/user.h>
81 #include <sys/signalvar.h>
82 #include <sys/sysctl.h>
83 #include <miscfs/devfs/devfs.h>
84 #include <miscfs/devfs/devfsdefs.h>     /* DEVFS_LOCK()/DEVFS_UNLOCK() */
85 #include <dev/kmreg_com.h>
86 #include <machine/cons.h>
87 
88 #if CONFIG_MACF
89 #include <security/mac_framework.h>
90 #endif
91 
92 #include "tty_dev.h"
93 
94 /* XXX belongs in devfs somewhere - LATER */
95 static int _devfs_setattr(void *, unsigned short, uid_t, gid_t);
96 
97 /*
98  * Forward declarations
99  */
100 static void ptcwakeup(struct tty *tp, int flag);
101 __XNU_PRIVATE_EXTERN    d_open_t        ptsopen;
102 __XNU_PRIVATE_EXTERN    d_close_t       ptsclose;
103 __XNU_PRIVATE_EXTERN    d_read_t        ptsread;
104 __XNU_PRIVATE_EXTERN    d_write_t       ptswrite;
105 __XNU_PRIVATE_EXTERN    d_ioctl_t       ptyioctl;       /* common ioctl */
106 __XNU_PRIVATE_EXTERN    d_stop_t        ptsstop;
107 __XNU_PRIVATE_EXTERN    d_reset_t       ptsreset;
108 __XNU_PRIVATE_EXTERN    d_select_t      ptsselect;
109 __XNU_PRIVATE_EXTERN    d_open_t        ptcopen;
110 __XNU_PRIVATE_EXTERN    d_close_t       ptcclose;
111 __XNU_PRIVATE_EXTERN    d_read_t        ptcread;
112 __XNU_PRIVATE_EXTERN    d_write_t       ptcwrite;
113 __XNU_PRIVATE_EXTERN    d_stop_t        ptcstop;        /* NO-OP */
114 __XNU_PRIVATE_EXTERN    d_reset_t       ptcreset;
115 __XNU_PRIVATE_EXTERN    d_select_t      ptcselect;
116 
117 /*
118  * XXX Should be devfs function... and use VATTR mechanisms, per
119  * XXX vnode_setattr2(); only we maybe can't really get back to the
120  * XXX vnode here for cloning devices (but it works for *cloned* devices
121  * XXX that are not themselves cloning).
122  *
123  * Returns:	0			Success
124  *	namei:???
125  *	vnode_setattr:???
126  */
127 static int
_devfs_setattr(void * handle,unsigned short mode,uid_t uid,gid_t gid)128 _devfs_setattr(void * handle, unsigned short mode, uid_t uid, gid_t gid)
129 {
130 	devdirent_t             *direntp = (devdirent_t *)handle;
131 	devnode_t               *devnodep;
132 	int                     error = EACCES;
133 	vfs_context_t           ctx = vfs_context_current();
134 	struct vnode_attr       va;
135 
136 	VATTR_INIT(&va);
137 	VATTR_SET(&va, va_uid, uid);
138 	VATTR_SET(&va, va_gid, gid);
139 	VATTR_SET(&va, va_mode, mode & ALLPERMS);
140 
141 	/*
142 	 * If the TIOCPTYGRANT loses the race with the clone operation because
143 	 * this function is not part of devfs, and therefore can't take the
144 	 * devfs lock to protect the direntp update, then force user space to
145 	 * redrive the grant request.
146 	 */
147 	if (direntp == NULL || (devnodep = direntp->de_dnp) == NULL) {
148 		error = ERESTART;
149 		goto out;
150 	}
151 
152 	/*
153 	 * Only do this if we are operating on device that doesn't clone
154 	 * each time it's referenced.  We perform a lookup on the device
155 	 * to insure we get the right instance.  We can't just use the call
156 	 * to devfs_dntovn() to get the vp for the operation, because
157 	 * dn_dvm may not have been initialized.
158 	 */
159 	if (devnodep->dn_clone == NULL) {
160 		struct nameidata nd;
161 		char name[128];
162 
163 		snprintf(name, sizeof(name), "/dev/%s", direntp->de_name);
164 		NDINIT(&nd, LOOKUP, OP_SETATTR, FOLLOW, UIO_SYSSPACE, CAST_USER_ADDR_T(name), ctx);
165 		error = namei(&nd);
166 		if (error) {
167 			goto out;
168 		}
169 		error = vnode_setattr(nd.ni_vp, &va, ctx);
170 		vnode_put(nd.ni_vp);
171 		nameidone(&nd);
172 		goto out;
173 	}
174 
175 out:
176 	return error;
177 }
178 
179 #define BUFSIZ 100              /* Chunk size iomoved to/from user */
180 
181 static struct tty_dev_t *tty_dev_head;
182 
183 __private_extern__ void
tty_dev_register(struct tty_dev_t * driver)184 tty_dev_register(struct tty_dev_t *driver)
185 {
186 	if (driver) {
187 		driver->next = tty_dev_head;
188 		tty_dev_head = driver;
189 	}
190 }
191 
192 /*
193  * Given a minor number, return the corresponding structure for that minor
194  * number.  If there isn't one, and the create flag is specified, we create
195  * one if possible.
196  *
197  * Parameters:	minor			Minor number of ptmx device
198  *		open_flag		PF_OPEN_M	First open of primary
199  *					PF_OPEN_S	First open of replica
200  *					0		Just want ioctl struct
201  *
202  * Returns:	NULL			Did not exist/could not create
203  *		!NULL			structure corresponding minor number
204  *
205  * Locks:	tty_lock() on ptmx_ioctl->pt_tty NOT held on entry or exit.
206  */
207 
208 static struct tty_dev_t *
pty_get_driver(dev_t dev)209 pty_get_driver(dev_t dev)
210 {
211 	int major = major(dev);
212 	struct tty_dev_t *driver;
213 	for (driver = tty_dev_head; driver != NULL; driver = driver->next) {
214 		if ((driver->primary == major || driver->replica == major)) {
215 			break;
216 		}
217 	}
218 	return driver;
219 }
220 
221 static struct ptmx_ioctl *
pty_get_ioctl(dev_t dev,int open_flag,struct tty_dev_t ** out_driver)222 pty_get_ioctl(dev_t dev, int open_flag, struct tty_dev_t **out_driver)
223 {
224 	struct tty_dev_t *driver = pty_get_driver(dev);
225 	struct ptmx_ioctl *out = NULL;
226 	if (out_driver) {
227 		*out_driver = driver;
228 	}
229 	if (driver && driver->open) {
230 		out = driver->open(minor(dev), open_flag);
231 		if (!out) {
232 			printf("pty_get_ioctl: driver->open returned NULL\n");
233 		}
234 		return out;
235 	}
236 	return NULL;
237 }
238 
239 /*
240  * Locks:	tty_lock() of old_ptmx_ioctl->pt_tty NOT held for this call.
241  */
242 static int
pty_free_ioctl(dev_t dev,int open_flag)243 pty_free_ioctl(dev_t dev, int open_flag)
244 {
245 	struct tty_dev_t *driver = pty_get_driver(dev);
246 	if (driver && driver->free) {
247 		return driver->free(minor(dev), open_flag);
248 	}
249 	return 0;
250 }
251 
252 static int
pty_get_name(dev_t dev,char * buffer,size_t size)253 pty_get_name(dev_t dev, char *buffer, size_t size)
254 {
255 	struct tty_dev_t *driver = pty_get_driver(dev);
256 	if (driver && driver->name) {
257 		return driver->name(minor(dev), buffer, size);
258 	}
259 	return 0;
260 }
261 
262 __private_extern__ int
ptsopen(dev_t dev,int flag,__unused int devtype,__unused struct proc * p)263 ptsopen(dev_t dev, int flag, __unused int devtype, __unused struct proc *p)
264 {
265 	int error;
266 	struct tty_dev_t *driver;
267 	bool free_ptmx_ioctl = true;
268 	struct ptmx_ioctl *pti = pty_get_ioctl(dev, PF_OPEN_S, &driver);
269 	if (pti == NULL) {
270 		return ENXIO;
271 	}
272 	if (!(pti->pt_flags & PF_UNLOCKED)) {
273 		error = EAGAIN;
274 		goto out_free;
275 	}
276 
277 	struct tty *tp = pti->pt_tty;
278 	tty_lock(tp);
279 
280 	if ((tp->t_state & TS_ISOPEN) == 0) {
281 		termioschars(&tp->t_termios);   /* Set up default chars */
282 		tp->t_iflag = TTYDEF_IFLAG;
283 		tp->t_oflag = TTYDEF_OFLAG;
284 		tp->t_lflag = TTYDEF_LFLAG;
285 		tp->t_cflag = TTYDEF_CFLAG;
286 		tp->t_ispeed = tp->t_ospeed = TTYDEF_SPEED;
287 		ttsetwater(tp);         /* would be done in xxparam() */
288 	} else if ((tp->t_state & TS_XCLUDE) && kauth_cred_issuser(kauth_cred_get())) {
289 		error = EBUSY;
290 		goto out_unlock;
291 	}
292 	if (tp->t_oproc) {                      /* Ctrlr still around. */
293 		(void)(*linesw[tp->t_line].l_modem)(tp, 1);
294 	}
295 	while ((tp->t_state & TS_CARR_ON) == 0) {
296 		if (flag & FNONBLOCK) {
297 			break;
298 		}
299 		error = ttysleep(tp, TSA_CARR_ON(tp), TTIPRI | PCATCH, __FUNCTION__, 0);
300 		if (error) {
301 			goto out_unlock;
302 		}
303 	}
304 	error = (*linesw[tp->t_line].l_open)(dev, tp);
305 	/* Successful open; mark as open by the replica */
306 
307 	free_ptmx_ioctl = false;
308 	CLR(tp->t_state, TS_IOCTL_NOT_OK);
309 	if (error == 0) {
310 		ptcwakeup(tp, FREAD | FWRITE);
311 	}
312 
313 out_unlock:
314 	tty_unlock(tp);
315 
316 out_free:
317 	if (free_ptmx_ioctl) {
318 		pty_free_ioctl(dev, PF_OPEN_S);
319 	}
320 
321 	return error;
322 }
323 
324 __private_extern__ int
ptsclose(dev_t dev,int flag,__unused int mode,__unused proc_t p)325 ptsclose(dev_t dev, int flag, __unused int mode, __unused proc_t p)
326 {
327 	int err;
328 
329 	/*
330 	 * This is temporary until the VSX conformance tests
331 	 * are fixed.  They are hanging with a deadlock
332 	 * where close() will not complete without t_timeout set
333 	 */
334 #define FIX_VSX_HANG    1
335 #ifdef  FIX_VSX_HANG
336 	int save_timeout;
337 #endif
338 	struct tty_dev_t *driver;
339 	struct ptmx_ioctl *pti = pty_get_ioctl(dev, 0, &driver);
340 	struct tty *tp;
341 
342 	if (pti == NULL) {
343 		return ENXIO;
344 	}
345 
346 	tp = pti->pt_tty;
347 	tty_lock(tp);
348 #ifdef  FIX_VSX_HANG
349 	save_timeout = tp->t_timeout;
350 	tp->t_timeout = 60;
351 #endif
352 	/*
353 	 * Close the line discipline and backing TTY structures.
354 	 */
355 	err = (*linesw[tp->t_line].l_close)(tp, flag);
356 	(void)ttyclose(tp);
357 
358 	/*
359 	 * Flush data and notify any waiters on the primary side of this PTY.
360 	 */
361 	ptsstop(tp, FREAD | FWRITE);
362 #ifdef  FIX_VSX_HANG
363 	tp->t_timeout = save_timeout;
364 #endif
365 	tty_unlock(tp);
366 
367 	if ((flag & IO_REVOKE) == IO_REVOKE && driver->revoke) {
368 		driver->revoke(minor(dev), tp);
369 	}
370 	/* unconditional, just like ttyclose() */
371 	pty_free_ioctl(dev, PF_OPEN_S);
372 
373 	return err;
374 }
375 
376 __private_extern__ int
ptsread(dev_t dev,struct uio * uio,int flag)377 ptsread(dev_t dev, struct uio *uio, int flag)
378 {
379 	struct ptmx_ioctl *pti = pty_get_ioctl(dev, 0, NULL);
380 	struct tty *tp;
381 	int error = 0;
382 	struct uthread *ut;
383 
384 	if (pti == NULL) {
385 		return ENXIO;
386 	}
387 	tp = pti->pt_tty;
388 	tty_lock(tp);
389 
390 	ut = current_uthread();
391 	if (tp->t_oproc) {
392 		error = (*linesw[tp->t_line].l_read)(tp, uio, flag);
393 	}
394 	ptcwakeup(tp, FWRITE);
395 	tty_unlock(tp);
396 	return error;
397 }
398 
399 /*
400  * Write to pseudo-tty.
401  * Wakeups of controlling tty will happen
402  * indirectly, when tty driver calls ptsstart.
403  */
404 __private_extern__ int
ptswrite(dev_t dev,struct uio * uio,int flag)405 ptswrite(dev_t dev, struct uio *uio, int flag)
406 {
407 	struct ptmx_ioctl *pti = pty_get_ioctl(dev, 0, NULL);
408 	struct tty *tp;
409 	int error;
410 
411 	if (pti == NULL) {
412 		return ENXIO;
413 	}
414 	tp = pti->pt_tty;
415 	tty_lock(tp);
416 
417 	if (tp->t_oproc == 0) {
418 		error = EIO;
419 	} else {
420 		error = (*linesw[tp->t_line].l_write)(tp, uio, flag);
421 	}
422 
423 	tty_unlock(tp);
424 
425 	return error;
426 }
427 
428 /*
429  * Start output on pseudo-tty.
430  * Wake up process selecting or sleeping for input from controlling tty.
431  *
432  * t_oproc for this driver; called from within the line discipline
433  *
434  * Locks:	Assumes tp is locked on entry, remains locked on exit
435  */
436 static void
ptsstart(struct tty * tp)437 ptsstart(struct tty *tp)
438 {
439 	struct ptmx_ioctl *pti = pty_get_ioctl(tp->t_dev, 0, NULL);
440 	if (pti == NULL) {
441 		goto out;
442 	}
443 	if (tp->t_state & TS_TTSTOP) {
444 		goto out;
445 	}
446 	if (pti->pt_flags & PF_STOPPED) {
447 		pti->pt_flags &= ~PF_STOPPED;
448 		pti->pt_send = TIOCPKT_START;
449 	}
450 	ptcwakeup(tp, FREAD);
451 out:
452 	return;
453 }
454 
455 static void
ptcwakeup_knote(struct selinfo * sip,long hint)456 ptcwakeup_knote(struct selinfo *sip, long hint)
457 {
458 	if ((sip->si_flags & SI_KNPOSTING) == 0) {
459 		sip->si_flags |= SI_KNPOSTING;
460 		KNOTE(&sip->si_note, hint);
461 		sip->si_flags &= ~SI_KNPOSTING;
462 	}
463 }
464 
465 /*
466  * Locks:	Assumes tty_lock() is held over this call.
467  */
468 static void
ptcwakeup(struct tty * tp,int flag)469 ptcwakeup(struct tty *tp, int flag)
470 {
471 	struct ptmx_ioctl *pti = pty_get_ioctl(tp->t_dev, 0, NULL);
472 	if (pti == NULL) {
473 		return;
474 	}
475 
476 	if (flag & FREAD) {
477 		selwakeup(&pti->pt_selr);
478 		wakeup(TSA_PTC_READ(tp));
479 		ptcwakeup_knote(&pti->pt_selr, 1);
480 	}
481 	if (flag & FWRITE) {
482 		selwakeup(&pti->pt_selw);
483 		wakeup(TSA_PTC_WRITE(tp));
484 		ptcwakeup_knote(&pti->pt_selw, 1);
485 	}
486 }
487 
488 __private_extern__ int
ptcopen(dev_t dev,__unused int flag,__unused int devtype,__unused proc_t p)489 ptcopen(dev_t dev, __unused int flag, __unused int devtype, __unused proc_t p)
490 {
491 	struct tty_dev_t *driver;
492 	struct ptmx_ioctl *pti = pty_get_ioctl(dev, PF_OPEN_M, &driver);
493 	if (pti == NULL) {
494 		return ENXIO;
495 	} else if (pti == (struct ptmx_ioctl*)-1) {
496 		return EREDRIVEOPEN;
497 	}
498 
499 	struct tty *tp = pti->pt_tty;
500 	tty_lock(tp);
501 
502 	/* If primary is open OR replica is still draining, pty is still busy */
503 	if (tp->t_oproc || (tp->t_state & TS_ISOPEN)) {
504 		tty_unlock(tp);
505 		/*
506 		 * If primary is closed, we are the only reference, so we
507 		 * need to clear the primary open bit
508 		 */
509 		if (!tp->t_oproc) {
510 			pty_free_ioctl(dev, PF_OPEN_M);
511 		}
512 		return EBUSY;
513 	}
514 	tp->t_oproc = ptsstart;
515 	CLR(tp->t_state, TS_ZOMBIE);
516 	SET(tp->t_state, TS_IOCTL_NOT_OK);
517 #ifdef sun4c
518 	tp->t_stop = ptsstop;
519 #endif
520 	(void)(*linesw[tp->t_line].l_modem)(tp, 1);
521 	tp->t_lflag &= ~EXTPROC;
522 
523 	if (driver->open_reset) {
524 		pti->pt_flags = PF_UNLOCKED;
525 		pti->pt_send = 0;
526 		pti->pt_ucntl = 0;
527 	}
528 
529 	tty_unlock(tp);
530 	return 0;
531 }
532 
533 __private_extern__ int
ptcclose(dev_t dev,__unused int flags,__unused int fmt,__unused proc_t p)534 ptcclose(dev_t dev, __unused int flags, __unused int fmt, __unused proc_t p)
535 {
536 	struct tty_dev_t *driver;
537 	struct ptmx_ioctl *pti = pty_get_ioctl(dev, 0, &driver);
538 	struct tty *tp;
539 	struct tty *constty = NULL;
540 	struct tty *freetp = NULL;
541 
542 	if (!pti) {
543 		return ENXIO;
544 	}
545 
546 	tp = pti->pt_tty;
547 	tty_lock(tp);
548 
549 	constty = copy_constty();
550 
551 	if (constty == tp) {
552 		freetp = set_constty(NULL);
553 		if (freetp != NULL) {
554 			if (freetp == tp) {
555 				ttyfree_locked(freetp);
556 			} else {
557 				ttyfree(freetp);
558 			}
559 			freetp = NULL;
560 		}
561 
562 
563 
564 		/*
565 		 * Closing current console tty; disable printing of console
566 		 * messages at bottom-level driver.
567 		 */
568 		(*cdevsw[major(tp->t_dev)].d_ioctl)
569 		(tp->t_dev, KMIOCDISABLCONS, NULL, 0, current_proc());
570 	}
571 
572 	if (constty != NULL) {
573 		if (constty == tp) {
574 			ttyfree_locked(constty);
575 		} else {
576 			ttyfree(constty);
577 		}
578 		constty = NULL;
579 	}
580 
581 	/*
582 	 * XXX MDMBUF makes no sense for PTYs, but would inhibit an `l_modem`.
583 	 * CLOCAL makes sense but isn't supported.  Special `l_modem`s that ignore
584 	 * carrier drop make no sense for PTYs but may be in use because other parts
585 	 * of the line discipline make sense for PTYs.  Recover by doing everything
586 	 * that a normal `ttymodem` would have done except for sending SIGHUP.
587 	 */
588 	(void)(*linesw[tp->t_line].l_modem)(tp, 0);
589 	if (tp->t_state & TS_ISOPEN) {
590 		tp->t_state &= ~(TS_CARR_ON | TS_CONNECTED);
591 		tp->t_state |= TS_ZOMBIE;
592 		ttyflush(tp, FREAD | FWRITE);
593 	}
594 
595 	/*
596 	 * Null out the backing TTY struct's open procedure to prevent starting
597 	 * replicas through `ptsstart`.
598 	 */
599 	tp->t_oproc = NULL;
600 
601 	/*
602 	 * Clear any select or kevent waiters under the lock.
603 	 */
604 	knote(&pti->pt_selr.si_note, NOTE_REVOKE, true);
605 	selthreadclear(&pti->pt_selr);
606 	knote(&pti->pt_selw.si_note, NOTE_REVOKE, true);
607 	selthreadclear(&pti->pt_selw);
608 
609 	tty_unlock(tp);
610 
611 #if CONFIG_MACF
612 	if (driver->mac_notify) {
613 		mac_pty_notify_close(p, tp, dev, NULL);
614 	}
615 #endif
616 	pty_free_ioctl(dev, PF_OPEN_M);
617 
618 	return 0;
619 }
620 
621 __private_extern__ int
ptcread(dev_t dev,struct uio * uio,int flag)622 ptcread(dev_t dev, struct uio *uio, int flag)
623 {
624 	struct ptmx_ioctl *pti = pty_get_ioctl(dev, 0, NULL);
625 	struct tty *tp;
626 	char buf[BUFSIZ];
627 	int error = 0, cc;
628 
629 	if (pti == NULL) {
630 		return ENXIO;
631 	}
632 	tp = pti->pt_tty;
633 	tty_lock(tp);
634 
635 	/*
636 	 * We want to block until the replica
637 	 * is open, and there's something to read;
638 	 * but if we lost the replica or we're NBIO,
639 	 * then return the appropriate error instead.
640 	 */
641 	for (;;) {
642 		if (tp->t_state & TS_ISOPEN) {
643 			if (pti->pt_flags & PF_PKT && pti->pt_send) {
644 				error = ureadc((int)pti->pt_send, uio);
645 				if (error) {
646 					goto out;
647 				}
648 				if (pti->pt_send & TIOCPKT_IOCTL) {
649 #ifdef __LP64__
650 					if (uio->uio_segflg == UIO_USERSPACE32) {
651 						static struct termios32 tio32;
652 						cc = MIN((int)uio_resid(uio), (int)sizeof(tio32));
653 						termios64to32((struct user_termios *)&tp->t_termios,
654 						    (struct termios32 *)&tio32);
655 						uiomove((caddr_t)&tio32, cc, uio);
656 #else
657 					if (uio->uio_segflg == UIO_USERSPACE64) {
658 						static struct user_termios tio64;
659 						cc = MIN((int)uio_resid(uio), (int)sizeof(tio64));
660 						termios32to64((struct termios32 *)&tp->t_termios,
661 						    (struct user_termios *)&tio64);
662 						uiomove((caddr_t)&tio64, cc, uio);
663 #endif
664 					} else {
665 						cc = MIN((int)uio_resid(uio), (int)sizeof(tp->t_termios));
666 						uiomove((caddr_t)&tp->t_termios, cc, uio);
667 					}
668 				}
669 				pti->pt_send = 0;
670 				goto out;
671 			}
672 			if (pti->pt_flags & PF_UCNTL && pti->pt_ucntl) {
673 				error = ureadc((int)pti->pt_ucntl, uio);
674 				if (error) {
675 					goto out;
676 				}
677 				pti->pt_ucntl = 0;
678 				goto out;
679 			}
680 			if (tp->t_outq.c_cc && (tp->t_state & TS_TTSTOP) == 0) {
681 				break;
682 			}
683 		}
684 		if ((tp->t_state & TS_CONNECTED) == 0) {
685 			goto out;       /* EOF */
686 		}
687 		if (flag & IO_NDELAY) {
688 			error = EWOULDBLOCK;
689 			goto out;
690 		}
691 		error = ttysleep(tp, TSA_PTC_READ(tp), TTIPRI | PCATCH, __FUNCTION__, 0);
692 		if (error) {
693 			goto out;
694 		}
695 	}
696 	if (pti->pt_flags & (PF_PKT | PF_UCNTL)) {
697 		error = ureadc(0, uio);
698 	}
699 	while (uio_resid(uio) > 0 && error == 0) {
700 		cc = q_to_b(&tp->t_outq, (u_char *)buf, MIN((int)uio_resid(uio), BUFSIZ));
701 		if (cc <= 0) {
702 			break;
703 		}
704 		error = uiomove(buf, cc, uio);
705 	}
706 	(*linesw[tp->t_line].l_start)(tp);
707 
708 out:
709 	tty_unlock(tp);
710 
711 	return error;
712 }
713 
714 /*
715  * Line discipline callback
716  *
717  * Locks:	tty_lock() is assumed held on entry and exit.
718  */
719 __private_extern__ int
720 ptsstop(struct tty* tp, int flush)
721 {
722 	struct ptmx_ioctl *pti = pty_get_ioctl(tp->t_dev, 0, NULL);
723 	int flag;
724 
725 	if (pti == NULL) {
726 		return ENXIO;
727 	}
728 
729 	/* note: FLUSHREAD and FLUSHWRITE already ok */
730 	if (flush == 0) {
731 		flush = TIOCPKT_STOP;
732 		pti->pt_flags |= PF_STOPPED;
733 	} else {
734 		pti->pt_flags &= ~PF_STOPPED;
735 	}
736 	pti->pt_send |= flush;
737 	/* change of perspective */
738 	flag = 0;
739 	if (flush & FREAD) {
740 		flag |= FWRITE;
741 	}
742 	if (flush & FWRITE) {
743 		flag |= FREAD;
744 	}
745 	ptcwakeup(tp, flag);
746 	return 0;
747 }
748 
749 __private_extern__ int
750 ptsreset(__unused int uban)
751 {
752 	return 0;
753 }
754 
755 int
756 ptsselect(dev_t dev, int rw, void *wql, proc_t p)
757 {
758 	struct ptmx_ioctl *pti = pty_get_ioctl(dev, 0, NULL);
759 	struct tty *tp;
760 	int retval = 0;
761 
762 	if (pti == NULL) {
763 		return ENXIO;
764 	}
765 	tp = pti->pt_tty;
766 	if (tp == NULL) {
767 		return ENXIO;
768 	}
769 
770 	tty_lock(tp);
771 
772 	switch (rw) {
773 	case FREAD:
774 		if (ISSET(tp->t_state, TS_ZOMBIE)) {
775 			retval = 1;
776 			break;
777 		}
778 
779 		retval = ttnread(tp);
780 		if (retval > 0) {
781 			break;
782 		}
783 
784 		selrecord(p, &tp->t_rsel, wql);
785 		break;
786 	case FWRITE:
787 		if (ISSET(tp->t_state, TS_ZOMBIE)) {
788 			retval = 1;
789 			break;
790 		}
791 
792 		if ((tp->t_outq.c_cc <= tp->t_lowat) &&
793 		    ISSET(tp->t_state, TS_CONNECTED)) {
794 			retval = tp->t_hiwat - tp->t_outq.c_cc;
795 			break;
796 		}
797 
798 		selrecord(p, &tp->t_wsel, wql);
799 		break;
800 	}
801 
802 	tty_unlock(tp);
803 	return retval;
804 }
805 
806 __private_extern__ int
807 ptcselect(dev_t dev, int rw, void *wql, proc_t p)
808 {
809 	struct tty_dev_t *driver;
810 	struct ptmx_ioctl *pti = pty_get_ioctl(dev, 0, &driver);
811 	struct tty *tp;
812 	int retval = 0;
813 
814 	if (pti == NULL) {
815 		return ENXIO;
816 	}
817 	tp = pti->pt_tty;
818 	tty_lock(tp);
819 
820 	if ((tp->t_state & TS_CONNECTED) == 0) {
821 		retval = 1;
822 		goto out;
823 	}
824 	switch (rw) {
825 	case FREAD:
826 		/*
827 		 * Need to block timeouts (ttrstart).
828 		 */
829 		if ((tp->t_state & TS_ISOPEN) &&
830 		    tp->t_outq.c_cc && (tp->t_state & TS_TTSTOP) == 0) {
831 			retval = (driver->fix_7828447) ? tp->t_outq.c_cc : 1;
832 			break;
833 		}
834 		OS_FALLTHROUGH;
835 
836 	case 0: /* exceptional */
837 		if ((tp->t_state & TS_ISOPEN) &&
838 		    (((pti->pt_flags & PF_PKT) && pti->pt_send) ||
839 		    ((pti->pt_flags & PF_UCNTL) && pti->pt_ucntl))) {
840 			retval = 1;
841 			break;
842 		}
843 		selrecord(p, &pti->pt_selr, wql);
844 		break;
845 
846 
847 	case FWRITE:
848 		if (tp->t_state & TS_ISOPEN) {
849 			retval = (TTYHOG - 2) - (tp->t_rawq.c_cc + tp->t_canq.c_cc);
850 			if (retval > 0) {
851 				retval = (driver->fix_7828447) ? retval : 1;
852 				break;
853 			}
854 			if (tp->t_canq.c_cc == 0 && (tp->t_lflag & ICANON)) {
855 				retval = 1;
856 				break;
857 			}
858 			retval = 0;
859 		}
860 		selrecord(p, &pti->pt_selw, wql);
861 		break;
862 	}
863 out:
864 	tty_unlock(tp);
865 
866 	return retval;
867 }
868 
869 __private_extern__ int
870 ptcstop(__unused struct tty *tp, __unused int flush)
871 {
872 	return 0;
873 }
874 
875 __private_extern__ int
876 ptcreset(__unused int uban)
877 {
878 	return 0;
879 }
880 
881 __private_extern__ int
882 ptcwrite(dev_t dev, struct uio *uio, int flag)
883 {
884 	struct ptmx_ioctl *pti = pty_get_ioctl(dev, 0, NULL);
885 	struct tty *tp;
886 	u_char *cp = NULL;
887 	int cc = 0;
888 	u_char locbuf[BUFSIZ];
889 	int wcnt = 0;
890 	int error = 0;
891 
892 	if (pti == NULL) {
893 		return ENXIO;
894 	}
895 	tp = pti->pt_tty;
896 	tty_lock(tp);
897 
898 again:
899 	if ((tp->t_state & TS_ISOPEN) == 0) {
900 		goto block;
901 	}
902 	while (uio_resid(uio) > 0 || cc > 0) {
903 		if (cc == 0) {
904 			cc = MIN((int)uio_resid(uio), BUFSIZ);
905 			cp = locbuf;
906 			error = uiomove((caddr_t)cp, cc, uio);
907 			if (error) {
908 				goto out;
909 			}
910 			/* check again for safety */
911 			if ((tp->t_state & TS_ISOPEN) == 0) {
912 				/* adjust for data copied in but not written */
913 				uio_setresid(uio, (uio_resid(uio) + cc));
914 				error = EIO;
915 				goto out;
916 			}
917 		}
918 		while (cc > 0) {
919 			if ((tp->t_rawq.c_cc + tp->t_canq.c_cc) >= TTYHOG - 2 &&
920 			    (tp->t_canq.c_cc > 0 || !(tp->t_lflag & ICANON))) {
921 				wakeup(TSA_HUP_OR_INPUT(tp));
922 				goto block;
923 			}
924 			OS_ANALYZER_SUPPRESS("80961525") (*linesw[tp->t_line].l_rint)(*cp++, tp);
925 			wcnt++;
926 			cc--;
927 		}
928 		cc = 0;
929 	}
930 out:
931 	tty_unlock(tp);
932 
933 	return error;
934 
935 block:
936 	/*
937 	 * Come here to wait for replica to open, for space
938 	 * in outq, or space in rawq, or an empty canq.
939 	 */
940 	if ((tp->t_state & TS_CONNECTED) == 0) {
941 		/* adjust for data copied in but not written */
942 		uio_setresid(uio, (uio_resid(uio) + cc));
943 		error = EIO;
944 		goto out;
945 	}
946 	if (flag & IO_NDELAY) {
947 		/* adjust for data copied in but not written */
948 		uio_setresid(uio, (uio_resid(uio) + cc));
949 		if (wcnt == 0) {
950 			error = EWOULDBLOCK;
951 		}
952 		goto out;
953 	}
954 	error = ttysleep(tp, TSA_PTC_WRITE(tp), TTOPRI | PCATCH, __FUNCTION__, 0);
955 	if (error) {
956 		/* adjust for data copied in but not written */
957 		uio_setresid(uio, (uio_resid(uio) + cc));
958 		goto out;
959 	}
960 	goto again;
961 }
962 
963 /*
964  * ptyioctl: Assumes dev was opened and lock was initilized
965  */
966 __private_extern__ int
967 ptyioctl(dev_t dev, u_long cmd, caddr_t data, int flag, struct proc *p)
968 {
969 	struct tty_dev_t *driver;
970 	struct ptmx_ioctl *pti = pty_get_ioctl(dev, 0, &driver);
971 	struct tty *tp;
972 	int stop, error = 0;
973 	int allow_ext_ioctl = 1;
974 
975 	if (pti == NULL || pti->pt_tty == NULL) {
976 		return ENXIO;
977 	}
978 
979 	if (cmd == KMIOCDISABLCONS) {
980 		return 0;
981 	}
982 
983 	tp = pti->pt_tty;
984 	tty_lock(tp);
985 
986 	u_char *cc = tp->t_cc;
987 
988 	/*
989 	 * Do not permit extended ioctls on the primary side of the pty unless
990 	 * the replica side has been successfully opened and initialized.
991 	 */
992 	if (major(dev) == driver->primary &&
993 	    driver->fix_7070978 &&
994 	    ISSET(tp->t_state, TS_IOCTL_NOT_OK)) {
995 		allow_ext_ioctl = 0;
996 	}
997 
998 	/*
999 	 * IF CONTROLLER STTY THEN MUST FLUSH TO PREVENT A HANG.
1000 	 * ttywflush(tp) will hang if there are characters in the outq.
1001 	 */
1002 	if (cmd == TIOCEXT && allow_ext_ioctl) {
1003 		/*
1004 		 * When the EXTPROC bit is being toggled, we need
1005 		 * to send an TIOCPKT_IOCTL if the packet driver
1006 		 * is turned on.
1007 		 */
1008 		if (*(int *)data) {
1009 			if (pti->pt_flags & PF_PKT) {
1010 				pti->pt_send |= TIOCPKT_IOCTL;
1011 				ptcwakeup(tp, FREAD);
1012 			}
1013 			tp->t_lflag |= EXTPROC;
1014 		} else {
1015 			if ((tp->t_lflag & EXTPROC) &&
1016 			    (pti->pt_flags & PF_PKT)) {
1017 				pti->pt_send |= TIOCPKT_IOCTL;
1018 				ptcwakeup(tp, FREAD);
1019 			}
1020 			tp->t_lflag &= ~EXTPROC;
1021 		}
1022 		goto out;
1023 	} else if (cdevsw[major(dev)].d_open == ptcopen) {
1024 		switch (cmd) {
1025 		case TIOCGPGRP:
1026 			/*
1027 			 * We aviod calling ttioctl on the controller since,
1028 			 * in that case, tp must be the controlling terminal.
1029 			 */
1030 			*(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : 0;
1031 			goto out;
1032 
1033 		case TIOCPKT:
1034 			if (*(int *)data) {
1035 				if (pti->pt_flags & PF_UCNTL) {
1036 					error = EINVAL;
1037 					goto out;
1038 				}
1039 				pti->pt_flags |= PF_PKT;
1040 			} else {
1041 				pti->pt_flags &= ~PF_PKT;
1042 			}
1043 			goto out;
1044 
1045 		case TIOCUCNTL:
1046 			if (*(int *)data) {
1047 				if (pti->pt_flags & PF_PKT) {
1048 					error = EINVAL;
1049 					goto out;
1050 				}
1051 				pti->pt_flags |= PF_UCNTL;
1052 			} else {
1053 				pti->pt_flags &= ~PF_UCNTL;
1054 			}
1055 			goto out;
1056 
1057 		case TIOCSETP:
1058 		case TIOCSETN:
1059 		case TIOCSETD:
1060 		case TIOCSETA_32:
1061 		case TIOCSETAW_32:
1062 		case TIOCSETAF_32:
1063 		case TIOCSETA_64:
1064 		case TIOCSETAW_64:
1065 		case TIOCSETAF_64:
1066 			ndflush(&tp->t_outq, tp->t_outq.c_cc);
1067 			break;
1068 
1069 		case TIOCSIG:
1070 			if (*(unsigned int *)data >= NSIG ||
1071 			    *(unsigned int *)data == 0) {
1072 				error = EINVAL;
1073 				goto out;
1074 			}
1075 			if ((tp->t_lflag & NOFLSH) == 0) {
1076 				ttyflush(tp, FREAD | FWRITE);
1077 			}
1078 			if ((*(unsigned int *)data == SIGINFO) &&
1079 			    ((tp->t_lflag & NOKERNINFO) == 0)) {
1080 				ttyinfo_locked(tp);
1081 			}
1082 			/*
1083 			 * SAFE: All callers drop the lock on return and
1084 			 * SAFE: the linesw[] will short circut this call
1085 			 * SAFE: if the ioctl() is eaten before the lower
1086 			 * SAFE: level code gets to see it.
1087 			 */
1088 			tty_pgsignal_locked(tp, *(unsigned int *)data, 1);
1089 			goto out;
1090 
1091 		case TIOCPTYGRANT:      /* grantpt(3) */
1092 			/*
1093 			 * Change the uid of the replica to that of the calling
1094 			 * thread, change the gid of the replica to GID_TTY,
1095 			 * change the mode to 0620 (rw--w----).
1096 			 */
1097 		{
1098 			error = _devfs_setattr(pti->pt_devhandle, 0620, kauth_getuid(), GID_TTY);
1099 			if (major(dev) == driver->primary) {
1100 				if (driver->mac_notify) {
1101 #if CONFIG_MACF
1102 					if (!error) {
1103 						tty_unlock(tp);
1104 						mac_pty_notify_grant(p, tp, dev, NULL);
1105 						tty_lock(tp);
1106 					}
1107 #endif
1108 				} else {
1109 					error = 0;
1110 				}
1111 			}
1112 			goto out;
1113 		}
1114 
1115 		case TIOCPTYGNAME:      /* ptsname(3) */
1116 			/*
1117 			 * Report the name of the replica device in *data
1118 			 * (128 bytes max.).  Use the same template string
1119 			 * used for calling devfs_make_node() to create it.
1120 			 */
1121 			pty_get_name(dev, data, 128);
1122 			error = 0;
1123 			goto out;
1124 
1125 		case TIOCPTYUNLK:       /* unlockpt(3) */
1126 			/*
1127 			 * Unlock the replica device so that it can be opened.
1128 			 */
1129 			if (major(dev) == driver->primary) {
1130 				pti->pt_flags |= PF_UNLOCKED;
1131 			}
1132 			error = 0;
1133 			goto out;
1134 
1135 		case FIONBIO:           /* set/clear non-blocking i/o */
1136 		case FIOASYNC:
1137 			/*
1138 			 * These probably come from sys_fcntl_nocancel().  Nothing specific
1139 			 * to serial devices here, so they should be allowed even if the
1140 			 * replica is closed.  The implementation in ttioctl_locked() is
1141 			 * safe to call in this case.  Bypass the line discipline's l_ioctl
1142 			 * implementation in case it is not.  In practice l_ioctl is
1143 			 * completely unused anyway (existing line disciplines set it to
1144 			 * l_noioctl, and the loadable line discipline mechanism is used
1145 			 * nowhere and not exposed to third parties).
1146 			 */
1147 			error = ttioctl_locked(tp, cmd, data, flag, p);
1148 			goto out;
1149 		}
1150 
1151 		/*
1152 		 * Fail all other calls; pty primaries are not serial devices;
1153 		 * we only pretend they are when the replica side of the pty is
1154 		 * already open.
1155 		 */
1156 		if (!allow_ext_ioctl) {
1157 			error = ENOTTY;
1158 			goto out;
1159 		}
1160 	}
1161 	error = (*linesw[tp->t_line].l_ioctl)(tp, cmd, data, flag, p);
1162 	if (error == ENOTTY) {
1163 		error = ttioctl_locked(tp, cmd, data, flag, p);
1164 		if (error == ENOTTY) {
1165 			if (pti->pt_flags & PF_UCNTL && (cmd & ~0xff) == UIOCCMD(0)) {
1166 				/* Process the UIOCMD ioctl group */
1167 				if (cmd & 0xff) {
1168 					pti->pt_ucntl = (u_char)cmd;
1169 					ptcwakeup(tp, FREAD);
1170 				}
1171 				error = 0;
1172 				goto out;
1173 			} else if (cmd == TIOCSBRK || cmd == TIOCCBRK) {
1174 				/*
1175 				 * POSIX conformance; rdar://3936338
1176 				 *
1177 				 * Clear ENOTTY in the case of setting or
1178 				 * clearing a break failing because pty's
1179 				 * don't support break like real serial
1180 				 * ports.
1181 				 */
1182 				error = 0;
1183 				goto out;
1184 			}
1185 		}
1186 	}
1187 
1188 	/*
1189 	 * If external processing and packet mode send ioctl packet.
1190 	 */
1191 	if ((tp->t_lflag & EXTPROC) && (pti->pt_flags & PF_PKT)) {
1192 		switch (cmd) {
1193 		case TIOCSETA_32:
1194 		case TIOCSETAW_32:
1195 		case TIOCSETAF_32:
1196 		case TIOCSETA_64:
1197 		case TIOCSETAW_64:
1198 		case TIOCSETAF_64:
1199 		case TIOCSETP:
1200 		case TIOCSETN:
1201 		case TIOCSETC:
1202 		case TIOCSLTC:
1203 		case TIOCLBIS:
1204 		case TIOCLBIC:
1205 		case TIOCLSET:
1206 			pti->pt_send |= TIOCPKT_IOCTL;
1207 			ptcwakeup(tp, FREAD);
1208 			break;
1209 		default:
1210 			break;
1211 		}
1212 	}
1213 	stop = (tp->t_iflag & IXON) && CCEQ(cc[VSTOP], CTRL('s'))
1214 	    && CCEQ(cc[VSTART], CTRL('q'));
1215 	if (pti->pt_flags & PF_NOSTOP) {
1216 		if (stop) {
1217 			pti->pt_send &= ~TIOCPKT_NOSTOP;
1218 			pti->pt_send |= TIOCPKT_DOSTOP;
1219 			pti->pt_flags &= ~PF_NOSTOP;
1220 			ptcwakeup(tp, FREAD);
1221 		}
1222 	} else {
1223 		if (!stop) {
1224 			pti->pt_send &= ~TIOCPKT_DOSTOP;
1225 			pti->pt_send |= TIOCPKT_NOSTOP;
1226 			pti->pt_flags |= PF_NOSTOP;
1227 			ptcwakeup(tp, FREAD);
1228 		}
1229 	}
1230 out:
1231 	tty_unlock(tp);
1232 
1233 	return error;
1234 }
1235