xref: /xnu-12377.81.4/bsd/kern/tty.c (revision 043036a2b3718f7f0be807e2870f8f47d3fa0796)
1 /*
2  * Copyright (c) 1997-2019 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, 1990, 1991, 1993
30  *      The Regents of the University of California.  All rights reserved.
31  * (c) UNIX System Laboratories, Inc.
32  * All or some portions of this file are derived from material licensed
33  * to the University of California by American Telephone and Telegraph
34  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
35  * the permission of UNIX System Laboratories, Inc.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  * 3. All advertising materials mentioning features or use of this software
46  *    must display the following acknowledgement:
47  *      This product includes software developed by the University of
48  *      California, Berkeley and its contributors.
49  * 4. Neither the name of the University nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63  * SUCH DAMAGE.
64  *
65  *	@(#)tty.c	8.8 (Berkeley) 1/21/94
66  */
67 /*-
68  * TODO:
69  *	o Fix races for sending the start char in ttyflush().
70  *	o Handle inter-byte timeout for "MIN > 0, TIME > 0" in ttyselect().
71  *	  With luck, there will be MIN chars before select() returns().
72  *	o Handle CLOCAL consistently for ptys.  Perhaps disallow setting it.
73  *	o Don't allow input in TS_ZOMBIE case.  It would be visible through
74  *	  FIONREAD.
75  *	o Do the new sio locking stuff here and use it to avoid special
76  *	  case for EXTPROC?
77  *	o Lock PENDIN too?
78  *	o Move EXTPROC and/or PENDIN to t_state?
79  *	o Wrap most of ttioctl in spltty/splx.
80  *	o Implement TIOCNOTTY or remove it from <sys/ioctl.h>.
81  *	o Send STOP if IXOFF is toggled off while TS_TBLOCK is set.
82  *	o Don't allow certain termios flags to affect disciplines other
83  *	  than TTYDISC.  Cancel their effects before switch disciplines
84  *	  and ignore them if they are set while we are in another
85  *	  discipline.
86  *	o Handle c_ispeed = 0 to c_ispeed = c_ospeed conversion here instead
87  *	  of in drivers and fix drivers that write to tp->t_termios.
88  *	o Check for TS_CARR_ON being set while everything is closed and not
89  *	  waiting for carrier.  TS_CARR_ON isn't cleared if nothing is open,
90  *	  so it would live until the next open even if carrier drops.
91  *	o Restore TS_WOPEN since it is useful in pstat.  It must be cleared
92  *	  only when _all_ openers leave open().
93  */
94 #include <sys/param.h>
95 #define TTYDEFCHARS 1
96 #include <sys/systm.h>
97 #undef  TTYDEFCHARS
98 #include <sys/ioctl.h>
99 #include <sys/proc_internal.h>
100 #include <sys/kauth.h>
101 #include <sys/file_internal.h>
102 #include <sys/conf.h>
103 #include <sys/dkstat.h>
104 #include <sys/uio_internal.h>
105 #include <sys/kernel.h>
106 #include <sys/vnode.h>
107 #include <sys/syslog.h>
108 #include <sys/user.h>
109 #include <sys/signalvar.h>
110 #include <sys/signalvar.h>
111 #include <sys/malloc.h>
112 
113 #include <dev/kmreg_com.h>
114 #include <machine/cons.h>
115 #include <sys/resource.h>       /* averunnable */
116 #include <kern/waitq.h>
117 #include <libkern/section_keywords.h>
118 
119 static LCK_GRP_DECLARE(tty_lck_grp, "tty");
120 os_refgrp_decl(static, t_refgrp, "tty", NULL);
121 
122 __private_extern__ int ttnread(struct tty *tp);
123 static void     ttyecho(int c, struct tty *tp);
124 static int      ttyoutput(int c, struct tty *tp);
125 static void     ttypend(struct tty *tp);
126 static void     ttyretype(struct tty *tp);
127 static void     ttyrub(int c, struct tty *tp);
128 static void     ttyrubo(struct tty *tp, int count);
129 static void     ttystop(struct tty *tp, int rw);
130 static void     ttyunblock(struct tty *tp);
131 static int      ttywflush(struct tty *tp);
132 static int      proc_compare(proc_t p1, proc_t p2);
133 
134 void ttyhold(struct tty *tp);
135 static void     ttydeallocate(struct tty *tp);
136 
137 static bool     isbackground(proc_t p, struct tty *tp);
138 static bool     isctty(proc_t p, struct tty *tp);
139 static bool     isctty_sp(proc_t p, struct tty *tp, struct session *sessp);
140 
141 __private_extern__ void termios32to64(struct termios32 *in, struct user_termios *out);
142 __private_extern__ void termios64to32(struct user_termios *in, struct termios32 *out);
143 
144 /*
145  * Table with character classes and parity. The 8th bit indicates parity,
146  * the 7th bit indicates the character is an alphameric or underscore (for
147  * ALTWERASE), and the low 6 bits indicate delay type.  If the low 6 bits
148  * are 0 then the character needs no special processing on output; classes
149  * other than 0 might be translated or (not currently) require delays.
150  */
151 #define E       0x00    /* Even parity. */
152 #define O       0x80    /* Odd parity. */
153 #define PARITY(c)       (char_type[c] & O)
154 
155 #define ALPHA   0x40    /* Alpha or underscore. */
156 #define ISALPHA(c)      (char_type[(c) & TTY_CHARMASK] & ALPHA)
157 
158 #define CCLASSMASK      0x3f
159 #define CCLASS(c)       (char_type[c] & CCLASSMASK)
160 /* 0b10xxxxxx is the mask for UTF-8 continuations */
161 #define CCONT(c)        ((c & 0xc0) == 0x80)
162 
163 #define BS      BACKSPACE
164 #define CC      CONTROL
165 #define CR      RETURN
166 #define NA      ORDINARY | ALPHA
167 #define NL      NEWLINE
168 #define NO      ORDINARY
169 #define TB      TAB
170 #define VT      VTAB
171 
172 static u_char const char_type[] = {
173 	E | CC, O | CC, O | CC, E | CC, O | CC, E | CC, E | CC, O | CC, /* nul - bel */
174 	O | BS, E | TB, E | NL, O | CC, E | VT, O | CR, O | CC, E | CC, /* bs - si */
175 	O | CC, E | CC, E | CC, O | CC, E | CC, O | CC, O | CC, E | CC, /* dle - etb */
176 	E | CC, O | CC, O | CC, E | CC, O | CC, E | CC, E | CC, O | CC, /* can - us */
177 	O | NO, E | NO, E | NO, O | NO, E | NO, O | NO, O | NO, E | NO, /* sp - ' */
178 	E | NO, O | NO, O | NO, E | NO, O | NO, E | NO, E | NO, O | NO, /* ( - / */
179 	E | NA, O | NA, O | NA, E | NA, O | NA, E | NA, E | NA, O | NA, /* 0 - 7 */
180 	O | NA, E | NA, E | NO, O | NO, E | NO, O | NO, O | NO, E | NO, /* 8 - ? */
181 	O | NO, E | NA, E | NA, O | NA, E | NA, O | NA, O | NA, E | NA, /* @ - G */
182 	E | NA, O | NA, O | NA, E | NA, O | NA, E | NA, E | NA, O | NA, /* H - O */
183 	E | NA, O | NA, O | NA, E | NA, O | NA, E | NA, E | NA, O | NA, /* P - W */
184 	O | NA, E | NA, E | NA, O | NO, E | NO, O | NO, O | NO, O | NA, /* X - _ */
185 	E | NO, O | NA, O | NA, E | NA, O | NA, E | NA, E | NA, O | NA, /* ` - g */
186 	O | NA, E | NA, E | NA, O | NA, E | NA, O | NA, O | NA, E | NA, /* h - o */
187 	O | NA, E | NA, E | NA, O | NA, E | NA, O | NA, O | NA, E | NA, /* p - w */
188 	E | NA, O | NA, O | NA, E | NO, O | NO, E | NO, E | NO, O | CC, /* x - del */
189 	/*
190 	 * Meta chars; should be settable per character set;
191 	 * for now, treat them all as normal characters.
192 	 */
193 	NA, NA, NA, NA, NA, NA, NA, NA,
194 	NA, NA, NA, NA, NA, NA, NA, NA,
195 	NA, NA, NA, NA, NA, NA, NA, NA,
196 	NA, NA, NA, NA, NA, NA, NA, NA,
197 	NA, NA, NA, NA, NA, NA, NA, NA,
198 	NA, NA, NA, NA, NA, NA, NA, NA,
199 	NA, NA, NA, NA, NA, NA, NA, NA,
200 	NA, NA, NA, NA, NA, NA, NA, NA,
201 	NA, NA, NA, NA, NA, NA, NA, NA,
202 	NA, NA, NA, NA, NA, NA, NA, NA,
203 	NA, NA, NA, NA, NA, NA, NA, NA,
204 	NA, NA, NA, NA, NA, NA, NA, NA,
205 	NA, NA, NA, NA, NA, NA, NA, NA,
206 	NA, NA, NA, NA, NA, NA, NA, NA,
207 	NA, NA, NA, NA, NA, NA, NA, NA,
208 	NA, NA, NA, NA, NA, NA, NA, NA,
209 };
210 #undef  BS
211 #undef  CC
212 #undef  CR
213 #undef  NA
214 #undef  NL
215 #undef  NO
216 #undef  TB
217 #undef  VT
218 
219 /* Macros to clear/set/test flags. */
220 #define SET(t, f)       (t) |= (f)
221 #define CLR(t, f)       (t) &= ~(f)
222 #define ISSET(t, f)     ((t) & (f))
223 
224 /*
225  * Input control starts when we would not be able to fit the maximum
226  * contents of the ping-pong buffers and finishes when we would be able
227  * to fit that much plus 1/8 more.
228  */
229 #define I_HIGH_WATER    (TTYHOG - 2 * 256)      /* XXX */
230 #define I_LOW_WATER     ((TTYHOG - 2 * 256) * 7 / 8)    /* XXX */
231 
232 __private_extern__ void
termios32to64(struct termios32 * in,struct user_termios * out)233 termios32to64(struct termios32 *in, struct user_termios *out)
234 {
235 	out->c_iflag = (user_tcflag_t)in->c_iflag;
236 	out->c_oflag = (user_tcflag_t)in->c_oflag;
237 	out->c_cflag = (user_tcflag_t)in->c_cflag;
238 	out->c_lflag = (user_tcflag_t)in->c_lflag;
239 
240 	/* bcopy is OK, since this type is ILP32/LP64 size invariant */
241 	bcopy(in->c_cc, out->c_cc, sizeof(in->c_cc));
242 
243 	out->c_ispeed = (user_speed_t)in->c_ispeed;
244 	out->c_ospeed = (user_speed_t)in->c_ospeed;
245 }
246 
247 __private_extern__ void
termios64to32(struct user_termios * in,struct termios32 * out)248 termios64to32(struct user_termios *in, struct termios32 *out)
249 {
250 	out->c_iflag = (uint32_t)in->c_iflag;
251 	out->c_oflag = (uint32_t)in->c_oflag;
252 	out->c_cflag = (uint32_t)in->c_cflag;
253 	out->c_lflag = (uint32_t)in->c_lflag;
254 
255 	/* bcopy is OK, since this type is ILP32/LP64 size invariant */
256 	bcopy(in->c_cc, out->c_cc, sizeof(in->c_cc));
257 
258 	out->c_ispeed = (uint32_t)MIN(in->c_ispeed, UINT32_MAX);
259 	out->c_ospeed = (uint32_t)MIN(in->c_ospeed, UINT32_MAX);
260 }
261 
262 
263 /*
264  * tty_lock
265  *
266  * Lock the requested tty structure.
267  *
268  * Parameters:	tp				The tty we want to lock
269  *
270  * Returns:	void
271  *
272  * Locks:	On return, tp is locked
273  */
274 void
tty_lock(struct tty * tp)275 tty_lock(struct tty *tp)
276 {
277 	TTY_LOCK_NOTOWNED(tp);  /* debug assert */
278 	ttyhold(tp);
279 	lck_mtx_lock(&tp->t_lock);
280 	os_atomic_store(&tp->t_locked_thread, current_thread(), relaxed);
281 }
282 
283 /*
284  * tty_lock
285  *
286  * Try locking the requested tty structure.
287  *
288  * Parameters:	tp				The tty we want to lock
289  *
290  * Returns:	true if locked, false otherwise
291  *
292  */
293 bool
tty_trylock(struct tty * tp)294 tty_trylock(struct tty *tp)
295 {
296 	TTY_LOCK_NOTOWNED(tp);  /* debug assert */
297 	ttyhold(tp);
298 	if (lck_mtx_try_lock(&tp->t_lock)) {
299 		/* locked */
300 		os_atomic_store(&tp->t_locked_thread, current_thread(), relaxed);
301 		return true;
302 	} else {
303 		/* not locked */
304 		ttyfree(tp);
305 		return false;
306 	}
307 }
308 
309 
310 bool
tty_islocked(struct tty * tp)311 tty_islocked(struct tty *tp)
312 {
313 	thread_t owner = os_atomic_load(&tp->t_locked_thread, relaxed);
314 	return owner == current_thread();
315 }
316 
317 
318 /*
319  * tty_unlock
320  *
321  * Unlock the requested tty structure.
322  *
323  * Parameters:	tp				The tty we want to unlock
324  *
325  * Returns:	void
326  *
327  * Locks:	On return, tp is unlocked
328  */
329 void
tty_unlock(struct tty * tp)330 tty_unlock(struct tty *tp)
331 {
332 	TTY_LOCK_OWNED(tp);     /* debug assert */
333 	os_atomic_store(&tp->t_locked_thread, NULL, relaxed);
334 	lck_mtx_unlock(&tp->t_lock);
335 	ttyfree(tp);
336 }
337 
338 /*
339  * ttyopen (LDISC)
340  *
341  * Initial open of tty, or (re)entry to standard tty line discipline.
342  *
343  * Locks:	Assumes tty_lock() is held prior to calling.
344  */
345 int
ttyopen(dev_t device,struct tty * tp)346 ttyopen(dev_t device, struct tty *tp)
347 {
348 	TTY_LOCK_OWNED(tp);     /* debug assert */
349 
350 	tp->t_dev = device;
351 
352 	if (!ISSET(tp->t_state, TS_ISOPEN)) {
353 		SET(tp->t_state, TS_ISOPEN);
354 		if (ISSET(tp->t_cflag, CLOCAL)) {
355 			SET(tp->t_state, TS_CONNECTED);
356 		}
357 		bzero(&tp->t_winsize, sizeof(tp->t_winsize));
358 	}
359 
360 	return 0;
361 }
362 
363 /*
364  * ttyclose
365  *
366  * Handle close() on a tty line: flush and set to initial state,
367  * bumping generation number so that pending read/write calls
368  * can detect recycling of the tty.
369  * XXX our caller should have done `spltty(); l_close(); ttyclose();'
370  * and l_close() should have flushed, but we repeat the spltty() and
371  * the flush in case there are buggy callers.
372  *
373  * Locks:	Assumes tty_lock() is held prior to calling.
374  */
375 int
ttyclose(struct tty * tp)376 ttyclose(struct tty *tp)
377 {
378 	struct pgrp * oldpg;
379 	struct session *oldsessp;
380 	struct tty *freetp = TTY_NULL;
381 	struct tty *constty = TTY_NULL;
382 
383 	TTY_LOCK_OWNED(tp);     /* debug assert */
384 
385 	constty = copy_constty();
386 
387 	if (constty == tp) {
388 		ttyfree_locked(constty);
389 		constty = NULL;
390 		freetp = set_constty(NULL);
391 		if (freetp) {
392 			if (freetp == tp) {
393 				ttyfree_locked(freetp);
394 			} else {
395 				ttyfree(freetp);
396 			}
397 			freetp = NULL;
398 		}
399 
400 
401 		/*
402 		 * Closing current console tty; disable printing of console
403 		 * messages at bottom-level driver.
404 		 */
405 		(*cdevsw[major(tp->t_dev)].d_ioctl)
406 		(tp->t_dev, KMIOCDISABLCONS, NULL, 0, current_proc());
407 	}
408 
409 	if (constty != NULL) {
410 		if (constty == tp) {
411 			ttyfree_locked(constty);
412 		} else {
413 			ttyfree(constty);
414 		}
415 		constty = NULL;
416 	}
417 
418 	ttyflush(tp, FREAD | FWRITE);
419 
420 	tp->t_gen++;
421 	tp->t_line = TTYDISC;
422 
423 	proc_list_lock();
424 	oldpg = tp->t_pgrp;
425 	oldsessp = tp->t_session;
426 	if (oldsessp != SESSION_NULL) {
427 		session_lock(oldsessp);
428 		freetp = session_clear_tty_locked(oldsessp);
429 		session_unlock(oldsessp);
430 	}
431 	tp->t_pgrp = NULL;
432 	tp->t_session = NULL;
433 	proc_list_unlock();
434 	tty_unlock(tp);
435 
436 	/* drop the reference on prev session and pgrp */
437 	if (oldsessp) {
438 		session_rele(oldsessp);
439 		if (freetp) {
440 			ttyfree(freetp);
441 		}
442 	}
443 	pgrp_rele(oldpg);
444 
445 	/* SAFE: All callers drop the lock on return */
446 	tty_lock(tp);
447 
448 	tp->t_state = 0;
449 
450 	/*
451 	 * The tty is closed - mark knote as being revoked and autodetach it from the
452 	 * tty
453 	 */
454 	knote(&tp->t_wsel.si_note, NOTE_REVOKE, true);
455 	selthreadclear(&tp->t_wsel);
456 	knote(&tp->t_rsel.si_note, NOTE_REVOKE, true);
457 	selthreadclear(&tp->t_rsel);
458 
459 	return 0;
460 }
461 
462 #define FLUSHQ(q) {                                                     \
463 	if ((q)->c_cc)                                                  \
464 	        ndflush(q, (q)->c_cc);                                  \
465 }
466 
467 /* Is 'c' a line delimiter ("break" character)? */
468 #define TTBREAKC(c, lflag)                                                      \
469 	((c) == '\n' || (((c) == cc[VEOF] ||                            \
470 	  (c) == cc[VEOL] || ((c) == cc[VEOL2] && lflag & IEXTEN)) &&   \
471 	 (c) != _POSIX_VDISABLE))
472 
473 /*
474  * ttyinput (LDISC)
475  *
476  * Process input of a single character received on a tty.
477  *
478  * Parameters:	c			The character received
479  *		tp			The tty on which it was received
480  *
481  * Returns:	.
482  *
483  * Locks:	Assumes tty_lock() is held prior to calling.
484  */
485 int
ttyinput(int c,struct tty * tp)486 ttyinput(int c, struct tty *tp)
487 {
488 	tcflag_t iflag, lflag;
489 	cc_t *cc;
490 	int i, err;
491 	int retval = 0;                 /* default return value */
492 
493 	TTY_LOCK_OWNED(tp);     /* debug assert */
494 
495 	/*
496 	 * If input is pending take it first.
497 	 */
498 	lflag = tp->t_lflag;
499 	if (ISSET(lflag, PENDIN)) {
500 		ttypend(tp);
501 	}
502 	/*
503 	 * Gather stats.
504 	 */
505 	if (ISSET(lflag, ICANON)) {
506 		++tk_cancc;
507 		++tp->t_cancc;
508 	} else {
509 		++tk_rawcc;
510 		++tp->t_rawcc;
511 	}
512 	++tk_nin;
513 
514 	/*
515 	 * Block further input iff:
516 	 * current input > threshold AND input is available to user program
517 	 * AND input flow control is enabled and not yet invoked.
518 	 * The 3 is slop for PARMRK.
519 	 */
520 	iflag = tp->t_iflag;
521 	if (tp->t_rawq.c_cc + tp->t_canq.c_cc > I_HIGH_WATER - 3 &&
522 	    (!ISSET(lflag, ICANON) || tp->t_canq.c_cc != 0) &&
523 	    (ISSET(tp->t_cflag, CRTS_IFLOW) || ISSET(iflag, IXOFF)) &&
524 	    !ISSET(tp->t_state, TS_TBLOCK)) {
525 		ttyblock(tp);
526 	}
527 
528 	/* Handle exceptional conditions (break, parity, framing). */
529 	cc = tp->t_cc;
530 	err = (ISSET(c, TTY_ERRORMASK));
531 	if (err) {
532 		CLR(c, TTY_ERRORMASK);
533 		if (ISSET(err, TTY_BI)) {
534 			if (ISSET(iflag, IGNBRK)) {
535 				goto out;
536 			}
537 			if (ISSET(iflag, BRKINT)) {
538 				ttyflush(tp, FREAD | FWRITE);
539 				/* SAFE: All callers drop the lock on return */
540 				tty_pgsignal_locked(tp, SIGINT, 1);
541 				goto endcase;
542 			}
543 			if (ISSET(iflag, PARMRK)) {
544 				goto parmrk;
545 			}
546 		} else if ((ISSET(err, TTY_PE) && ISSET(iflag, INPCK))
547 		    || ISSET(err, TTY_FE)) {
548 			if (ISSET(iflag, IGNPAR)) {
549 				goto out;
550 			} else if (ISSET(iflag, PARMRK)) {
551 parmrk:
552 				if (tp->t_rawq.c_cc + tp->t_canq.c_cc >
553 				    MAX_INPUT - 3) {
554 					goto input_overflow;
555 				}
556 				(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
557 				(void)putc(0 | TTY_QUOTE, &tp->t_rawq);
558 				(void)putc(c | TTY_QUOTE, &tp->t_rawq);
559 				goto endcase;
560 			} else {
561 				c = 0;
562 			}
563 		}
564 	}
565 
566 	if (!ISSET(tp->t_state, TS_TYPEN) && ISSET(iflag, ISTRIP)) {
567 		CLR(c, 0x80);
568 	}
569 	if (!ISSET(lflag, EXTPROC)) {
570 		/*
571 		 * Check for literal nexting very first
572 		 */
573 		if (ISSET(tp->t_state, TS_LNCH)) {
574 			SET(c, TTY_QUOTE);
575 			CLR(tp->t_state, TS_LNCH);
576 		}
577 		/*
578 		 * Scan for special characters.  This code
579 		 * is really just a big case statement with
580 		 * non-constant cases.  The bottom of the
581 		 * case statement is labeled ``endcase'', so goto
582 		 * it after a case match, or similar.
583 		 */
584 
585 		/*
586 		 * Control chars which aren't controlled
587 		 * by ICANON, ISIG, or IXON.
588 		 */
589 		if (ISSET(lflag, IEXTEN)) {
590 			if (CCEQ(cc[VLNEXT], c)) {
591 				if (ISSET(lflag, ECHO)) {
592 					if (ISSET(lflag, ECHOE)) {
593 						(void)ttyoutput('^', tp);
594 						(void)ttyoutput('\b', tp);
595 					} else {
596 						ttyecho(c, tp);
597 					}
598 				}
599 				SET(tp->t_state, TS_LNCH);
600 				goto endcase;
601 			}
602 			if (CCEQ(cc[VDISCARD], c)) {
603 				if (ISSET(lflag, FLUSHO)) {
604 					CLR(tp->t_lflag, FLUSHO);
605 				} else {
606 					ttyflush(tp, FWRITE);
607 					ttyecho(c, tp);
608 					if (tp->t_rawq.c_cc + tp->t_canq.c_cc) {
609 						ttyretype(tp);
610 					}
611 					SET(tp->t_lflag, FLUSHO);
612 				}
613 				goto startoutput;
614 			}
615 		}
616 		/*
617 		 * Signals.
618 		 */
619 		if (ISSET(lflag, ISIG)) {
620 			if (CCEQ(cc[VINTR], c) || CCEQ(cc[VQUIT], c)) {
621 				if (!ISSET(lflag, NOFLSH)) {
622 					ttyflush(tp, FREAD | FWRITE);
623 				}
624 				ttyecho(c, tp);
625 				/*
626 				 * SAFE: All callers drop the lock on return;
627 				 * SAFE: if we lose a threaded race on change
628 				 * SAFE: of the interrupt character, we could
629 				 * SAFE: have lost that race anyway due to the
630 				 * SAFE: scheduler executing threads in
631 				 * SAFE: priority order rather than "last
632 				 * SAFE: active thread" order (FEATURE).
633 				 */
634 				tty_pgsignal_locked(tp,
635 				    CCEQ(cc[VINTR], c) ? SIGINT : SIGQUIT, 1);
636 				goto endcase;
637 			}
638 			if (CCEQ(cc[VSUSP], c)) {
639 				if (!ISSET(lflag, NOFLSH)) {
640 					ttyflush(tp, FREAD);
641 				}
642 				ttyecho(c, tp);
643 				/* SAFE: All callers drop the lock on return */
644 				tty_pgsignal_locked(tp, SIGTSTP, 1);
645 				goto endcase;
646 			}
647 		}
648 		/*
649 		 * Handle start/stop characters.
650 		 */
651 		if (ISSET(iflag, IXON)) {
652 			if (CCEQ(cc[VSTOP], c)) {
653 				if (!ISSET(tp->t_state, TS_TTSTOP)) {
654 					SET(tp->t_state, TS_TTSTOP);
655 					ttystop(tp, 0);
656 					goto out;
657 				}
658 				if (!CCEQ(cc[VSTART], c)) {
659 					goto out;
660 				}
661 				/*
662 				 * if VSTART == VSTOP then toggle
663 				 */
664 				goto endcase;
665 			}
666 			if (CCEQ(cc[VSTART], c)) {
667 				goto restartoutput;
668 			}
669 		}
670 		/*
671 		 * IGNCR, ICRNL, & INLCR
672 		 */
673 		if (c == '\r') {
674 			if (ISSET(iflag, IGNCR)) {
675 				goto out;
676 			} else if (ISSET(iflag, ICRNL)) {
677 				c = '\n';
678 			}
679 		} else if (c == '\n' && ISSET(iflag, INLCR)) {
680 			c = '\r';
681 		}
682 	}
683 	if (!ISSET(tp->t_lflag, EXTPROC) && ISSET(lflag, ICANON)) {
684 		/*
685 		 * From here on down canonical mode character
686 		 * processing takes place.
687 		 */
688 		/*
689 		 * erase (^H / ^?)
690 		 */
691 		if (CCEQ(cc[VERASE], c)) {
692 			if (tp->t_rawq.c_cc) {
693 				if (ISSET(iflag, IUTF8)) {
694 					do {
695 						ttyrub((c = unputc(&tp->t_rawq)), tp);
696 					} while (tp->t_rawq.c_cc && CCONT(c));
697 				} else {
698 					ttyrub(unputc(&tp->t_rawq), tp);
699 				}
700 			}
701 			goto endcase;
702 		}
703 		/*
704 		 * kill (^U)
705 		 */
706 		if (CCEQ(cc[VKILL], c)) {
707 			if (ISSET(lflag, ECHOKE) &&
708 			    tp->t_rawq.c_cc == tp->t_rocount &&
709 			    !ISSET(lflag, ECHOPRT)) {
710 				while (tp->t_rawq.c_cc) {
711 					ttyrub(unputc(&tp->t_rawq), tp);
712 				}
713 			} else {
714 				ttyecho(c, tp);
715 				if (ISSET(lflag, ECHOK) ||
716 				    ISSET(lflag, ECHOKE)) {
717 					ttyecho('\n', tp);
718 				}
719 				FLUSHQ(&tp->t_rawq);
720 				tp->t_rocount = 0;
721 			}
722 			CLR(tp->t_state, TS_LOCAL);
723 			goto endcase;
724 		}
725 		/*
726 		 * word erase (^W)
727 		 */
728 		if (CCEQ(cc[VWERASE], c) && ISSET(lflag, IEXTEN)) {
729 			int ctype;
730 
731 			/*
732 			 * erase whitespace
733 			 */
734 			while ((c = unputc(&tp->t_rawq)) == ' ' || c == '\t') {
735 				ttyrub(c, tp);
736 			}
737 			if (c == -1) {
738 				goto endcase;
739 			}
740 			/*
741 			 * erase last char of word and remember the
742 			 * next chars type (for ALTWERASE)
743 			 */
744 			ttyrub(c, tp);
745 			c = unputc(&tp->t_rawq);
746 			if (c == -1) {
747 				goto endcase;
748 			}
749 			if (c == ' ' || c == '\t') {
750 				(void)putc(c, &tp->t_rawq);
751 				goto endcase;
752 			}
753 			ctype = ISALPHA(c);
754 			/*
755 			 * erase rest of word
756 			 */
757 			do {
758 				ttyrub(c, tp);
759 				c = unputc(&tp->t_rawq);
760 				if (c == -1) {
761 					goto endcase;
762 				}
763 			} while (c != ' ' && c != '\t' &&
764 			    (!ISSET(lflag, ALTWERASE) || ISALPHA(c) == ctype));
765 			(void)putc(c, &tp->t_rawq);
766 			goto endcase;
767 		}
768 		/*
769 		 * reprint line (^R)
770 		 */
771 		if (CCEQ(cc[VREPRINT], c) && ISSET(lflag, IEXTEN)) {
772 			ttyretype(tp);
773 			goto endcase;
774 		}
775 		/*
776 		 * ^T - kernel info and generate SIGINFO
777 		 */
778 		if (CCEQ(cc[VSTATUS], c) && ISSET(lflag, IEXTEN)) {
779 			if (ISSET(lflag, ISIG)) {
780 				/* SAFE: All callers drop the lock on return */
781 				tty_pgsignal_locked(tp, SIGINFO, 1);
782 			}
783 			if (!ISSET(lflag, NOKERNINFO)) {
784 				ttyinfo_locked(tp);
785 			}
786 			goto endcase;
787 		}
788 	}
789 	/*
790 	 * Check for input buffer overflow
791 	 */
792 	if (tp->t_rawq.c_cc + tp->t_canq.c_cc >= MAX_INPUT) {
793 input_overflow:
794 		if (ISSET(iflag, IMAXBEL)) {
795 			if (tp->t_outq.c_cc < tp->t_hiwat) {
796 				(void)ttyoutput(CTRL('g'), tp);
797 			}
798 		}
799 		goto endcase;
800 	}
801 
802 	if (c == 0377 && ISSET(iflag, PARMRK) && !ISSET(iflag, ISTRIP)
803 	    && ISSET(iflag, IGNBRK | IGNPAR) != (IGNBRK | IGNPAR)) {
804 		(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
805 	}
806 
807 	/*
808 	 * Put data char in q for user and
809 	 * wakeup on seeing a line delimiter.
810 	 */
811 	if (putc(c, &tp->t_rawq) >= 0) {
812 		if (!ISSET(lflag, ICANON)) {
813 			ttwakeup(tp);
814 			ttyecho(c, tp);
815 			goto endcase;
816 		}
817 		if (TTBREAKC(c, lflag)) {
818 			tp->t_rocount = 0;
819 			catq(&tp->t_rawq, &tp->t_canq);
820 			ttwakeup(tp);
821 		} else if (tp->t_rocount++ == 0) {
822 			tp->t_rocol = tp->t_column;
823 		}
824 		if (ISSET(tp->t_state, TS_ERASE)) {
825 			/*
826 			 * end of prterase \.../
827 			 */
828 			CLR(tp->t_state, TS_ERASE);
829 			(void)ttyoutput('/', tp);
830 		}
831 		i = tp->t_column;
832 		ttyecho(c, tp);
833 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ECHO)) {
834 			/*
835 			 * Place the cursor over the '^' of the ^D.
836 			 */
837 			i = min(2, tp->t_column - i);
838 			while (i > 0) {
839 				(void)ttyoutput('\b', tp);
840 				i--;
841 			}
842 		}
843 	}
844 
845 endcase:
846 	/*
847 	 * IXANY means allow any character to restart output.
848 	 */
849 	if (ISSET(tp->t_state, TS_TTSTOP) &&
850 	    !ISSET(iflag, IXANY) && cc[VSTART] != cc[VSTOP]) {
851 		goto out;
852 	}
853 
854 restartoutput:
855 	CLR(tp->t_lflag, FLUSHO);
856 	CLR(tp->t_state, TS_TTSTOP);
857 
858 startoutput:
859 	/* Start the output */
860 	retval = ttstart(tp);
861 
862 out:
863 	return retval;
864 }
865 
866 
867 /*
868  * ttyoutput
869  *
870  * Output a single character on a tty, doing output processing
871  * as needed (expanding tabs, newline processing, etc.).
872  *
873  * Parameters:	c			The character to output
874  *		tp			The tty on which to output on the tty
875  *
876  * Returns:	< 0			Success
877  *		>= 0			Character to resend (failure)
878  *
879  * Locks:	Assumes tp is locked on entry, remains locked on exit
880  *
881  * Notes:	Must be recursive.
882  */
883 static int
ttyoutput(int c,struct tty * tp)884 ttyoutput(int c, struct tty *tp)
885 {
886 	tcflag_t oflag;
887 	int col;
888 
889 	TTY_LOCK_OWNED(tp);     /* debug assert */
890 
891 	oflag = tp->t_oflag;
892 	if (!ISSET(oflag, OPOST)) {
893 		if (ISSET(tp->t_lflag, FLUSHO)) {
894 			return -1;
895 		}
896 		if (putc(c, &tp->t_outq)) {
897 			return c;
898 		}
899 		tk_nout++;
900 		tp->t_outcc++;
901 		return -1;
902 	}
903 	/*
904 	 * Do tab expansion if OXTABS is set.  Special case if we external
905 	 * processing, we don't do the tab expansion because we'll probably
906 	 * get it wrong.  If tab expansion needs to be done, let it happen
907 	 * externally.
908 	 */
909 	CLR(c, ~TTY_CHARMASK);
910 	if (c == '\t' &&
911 	    ISSET(oflag, OXTABS) && !ISSET(tp->t_lflag, EXTPROC)) {
912 		col = c = 8 - (tp->t_column & 7);
913 		if (!ISSET(tp->t_lflag, FLUSHO)) {
914 			c -= b_to_q((const u_char *)"        ", c, &tp->t_outq);
915 			tk_nout += c;
916 			tp->t_outcc += c;
917 		}
918 		tp->t_column += c;
919 		return c == col ? -1 : '\t';
920 	}
921 	if (c == CEOT && ISSET(oflag, ONOEOT)) {
922 		return -1;
923 	}
924 
925 	/*
926 	 * Newline translation: if ONLCR is set,
927 	 * translate newline into "\r\n".
928 	 */
929 	if (c == '\n' && ISSET(tp->t_oflag, ONLCR)) {
930 		tk_nout++;
931 		tp->t_outcc++;
932 		if (putc('\r', &tp->t_outq)) {
933 			return c;
934 		}
935 	}
936 	/* If OCRNL is set, translate "\r" into "\n". */
937 	else if (c == '\r' && ISSET(tp->t_oflag, OCRNL)) {
938 		c = '\n';
939 	}
940 	/* If ONOCR is set, don't transmit CRs when on column 0. */
941 	else if (c == '\r' && ISSET(tp->t_oflag, ONOCR) && tp->t_column == 0) {
942 		return -1;
943 	}
944 	tk_nout++;
945 	tp->t_outcc++;
946 	if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq)) {
947 		return c;
948 	}
949 
950 	col = tp->t_column;
951 	switch (CCLASS(c)) {
952 	case BACKSPACE:
953 		if (col > 0) {
954 			--col;
955 		}
956 		break;
957 	case CONTROL:
958 		break;
959 	case NEWLINE:
960 	case RETURN:
961 		col = 0;
962 		break;
963 	case ORDINARY:
964 		++col;
965 		break;
966 	case TAB:
967 		col = (col + 8) & ~7;
968 		break;
969 	}
970 	tp->t_column = col;
971 	return -1;
972 }
973 
974 /*
975  * ttioctl
976  *
977  * Identical to ttioctl_locked, only the lock is not held
978  *
979  * Parameters:	<See ttioctl_locked()>
980  *
981  * Returns:	<See ttioctl_locked()>
982  *
983  * Locks:	This function assumes the tty_lock() is not held on entry;
984  *		it takes the lock, and releases it before returning.
985  *
986  * Notes:	This is supported to ensure the line discipline interfaces
987  *		all have the same locking semantics.
988  *
989  *		This function is called from
990  */
991 int
ttioctl(struct tty * tp,u_long cmd,caddr_t data,int flag,proc_t p)992 ttioctl(struct tty *tp, u_long cmd, caddr_t data, int flag, proc_t p)
993 {
994 	int     retval;
995 
996 	tty_lock(tp);
997 	retval = ttioctl_locked(tp, cmd, data, flag, p);
998 	tty_unlock(tp);
999 
1000 	return retval;
1001 }
1002 
1003 
1004 /*
1005  * ttioctl_locked
1006  *
1007  * Ioctls for all tty devices.
1008  *
1009  * Parameters:	tp			Tty on which ioctl() is being called
1010  *		cmd			ioctl() command parameter
1011  *		data			ioctl() data argument (if any)
1012  *		flag			fileglob open modes from fcntl.h;
1013  *					if called internally, this is usually
1014  *					set to 0, rather than something useful
1015  *		p			Process context for the call; if the
1016  *					call is proxied to a worker thread,
1017  *					this will not be the current process!!!
1018  *
1019  * Returns:	0			Success
1020  *		EIO			I/O error (no process group, job
1021  *					control, etc.)
1022  *		EINTR			Interrupted by signal
1023  *		EBUSY			Attempt to become the console while
1024  *					the console is busy
1025  *		ENOTTY			TIOCGPGRP on a non-controlling tty
1026  *		EINVAL			Invalid baud rate
1027  *		ENXIO			TIOCSETD of invalid line discipline
1028  *		EPERM			TIOCSTI, not root, not open for read
1029  *		EACCES			TIOCSTI, not root, not your controlling
1030  *					tty
1031  *		EPERM			TIOCSCTTY failed
1032  *		ENOTTY/EINVAL/EPERM	TIOCSPGRP failed
1033  *		EPERM			TIOCSDRAINWAIT as non-root user
1034  *	suser:EPERM			Console control denied
1035  *	ttywait:EIO			t_timeout too small/expired
1036  *	ttywait:ERESTART		Upper layer must redrive the call;
1037  *					this is usually done by the Libc
1038  *					stub in user space
1039  *	ttywait:EINTR			Interrupted (usually a signal)
1040  *	ttcompat:EINVAL
1041  *	ttcompat:ENOTTY
1042  *	ttcompat:EIOCTL
1043  *	ttcompat:ENOTTY			TIOCGSID, if no session or session
1044  *					leader
1045  *	ttcompat:ENOTTY			All unrecognized ioctls
1046  *	*tp->t_param:?			TIOCSETA* underlying function
1047  *	*linesw[t].l_open:?		TIOCSETD line discipline open failure
1048  *
1049  *
1050  * Locks:	This function assumes that the tty_lock() is held for the
1051  *		tp at the time of the call.  The lock remains held on return.
1052  *
1053  * Notes:	This function is called after line-discipline specific ioctl
1054  *		has been called to do discipline-specific functions and/or
1055  *		reject any of these ioctl() commands.
1056  *
1057  *		This function calls ttcompat(), which can re-call ttioctl()
1058  *		to a depth of one (FORTRAN style mutual recursion); at some
1059  *		point, we should just in-line ttcompat() here.
1060  */
1061 int
ttioctl_locked(struct tty * tp,u_long cmd,caddr_t data,int flag,proc_t p)1062 ttioctl_locked(struct tty *tp, u_long cmd, caddr_t data, int flag, proc_t p)
1063 {
1064 	int error = 0;
1065 	int bogusData = 1;
1066 	struct uthread *ut;
1067 	struct pgrp *pg, *oldpg;
1068 	struct session *sessp, *oldsessp;
1069 	struct tty *oldtp, *freetp;
1070 
1071 	TTY_LOCK_OWNED(tp);     /* debug assert */
1072 
1073 	ut = current_uthread();
1074 	/* If the ioctl involves modification, signal if in the background. */
1075 	switch (cmd) {
1076 	case TIOCIXON:
1077 	case TIOCIXOFF:
1078 	case TIOCDRAIN:
1079 	case TIOCFLUSH:
1080 	case TIOCSTOP:
1081 	case TIOCSTART:
1082 	case TIOCSETA_32:
1083 	case TIOCSETA_64:
1084 	case TIOCSETD:
1085 	case TIOCSETAF_32:
1086 	case TIOCSETAF_64:
1087 	case TIOCSETAW_32:
1088 	case TIOCSETAW_64:
1089 	case TIOCSPGRP:
1090 	case TIOCSTAT:
1091 	case TIOCSTI:
1092 	case TIOCSWINSZ:
1093 	case TIOCLBIC:
1094 	case TIOCLBIS:
1095 	case TIOCLSET:
1096 	case TIOCSETC:
1097 	case OTIOCSETD:
1098 	case TIOCSETN:
1099 	case TIOCSETP:
1100 	case TIOCSLTC:
1101 		while (isbackground(p, tp) &&
1102 		    (p->p_lflag & P_LPPWAIT) == 0 &&
1103 		    (p->p_sigignore & sigmask(SIGTTOU)) == 0 &&
1104 		    (ut->uu_sigmask & sigmask(SIGTTOU)) == 0) {
1105 			pg = proc_pgrp(p, NULL);
1106 			if (pg == PGRP_NULL) {
1107 				error = EIO;
1108 				goto out;
1109 			}
1110 			/* SAFE: All callers drop the lock on return */
1111 			tty_unlock(tp);
1112 			if (pg->pg_jobc == 0) {
1113 				pgrp_rele(pg);
1114 				tty_lock(tp);
1115 				error = EIO;
1116 				goto out;
1117 			}
1118 			pgsignal(pg, SIGTTOU, 1);
1119 			pgrp_rele(pg);
1120 			tty_lock(tp);
1121 
1122 
1123 			/*
1124 			 * We signalled ourself, so we need to act as if we
1125 			 * have been "interrupted" from a "sleep" to act on
1126 			 * the signal.  If it's a signal that stops the
1127 			 * process, that's handled in the signal sending code.
1128 			 */
1129 			error = EINTR;
1130 			goto out;
1131 		}
1132 		break;
1133 	}
1134 
1135 	switch (cmd) {                  /* Process the ioctl. */
1136 	/*
1137 	 * Note: FIOASYNC and FIONBIO (only) can be called on pty primaries
1138 	 * before the replica side is open.
1139 	 */
1140 	case FIOASYNC:                  /* set/clear async i/o */
1141 		if (*(int *)data) {
1142 			SET(tp->t_state, TS_ASYNC);
1143 		} else {
1144 			CLR(tp->t_state, TS_ASYNC);
1145 		}
1146 		break;
1147 	case FIONBIO:                   /* set/clear non-blocking i/o */
1148 		break;                  /* XXX: delete. */
1149 	case FIONREAD:                  /* get # bytes to read */
1150 		*(int *)data = ttnread(tp);
1151 		break;
1152 	case TIOCEXCL:                  /* set exclusive use of tty */
1153 		SET(tp->t_state, TS_XCLUDE);
1154 		break;
1155 	case TIOCFLUSH: {               /* flush buffers */
1156 		int flags = *(int *)data;
1157 
1158 		if (flags == 0) {
1159 			flags = FREAD | FWRITE;
1160 		} else {
1161 			flags &= FREAD | FWRITE;
1162 		}
1163 		ttyflush(tp, flags);
1164 		break;
1165 	}
1166 	case TIOCSCONS: {
1167 		/* Set current console device to this line */
1168 		data = (caddr_t) &bogusData;
1169 	}
1170 		OS_FALLTHROUGH;
1171 	case TIOCCONS: {                        /* become virtual console */
1172 		struct tty *constty = NULL;
1173 		constty = copy_constty();
1174 		if (*(int *)data) {
1175 			if (constty && constty != tp &&
1176 			    ISSET(constty->t_state, TS_CONNECTED)) {
1177 				error = EBUSY;
1178 				// constty != tp, so constty is not locked
1179 				ttyfree(constty);
1180 				constty = NULL;
1181 				goto out;
1182 			}
1183 			if ((error = suser(kauth_cred_get(), &p->p_acflag))) {
1184 				if (constty) {
1185 					if (constty == tp) {
1186 						ttyfree_locked(constty);
1187 					} else {
1188 						ttyfree(constty);
1189 					}
1190 					constty = NULL;
1191 				}
1192 				goto out;
1193 			}
1194 			if (tp != constty) {
1195 				freetp = set_constty(tp);
1196 				if (freetp != NULL) {
1197 					if (freetp == tp) {
1198 						ttyfree_locked(freetp);
1199 					} else {
1200 						ttyfree(freetp);
1201 					}
1202 					freetp = NULL;
1203 				}
1204 				if (constty != NULL) {
1205 					// constty != tp, so constty is not locked
1206 					ttyfree(constty);
1207 				}
1208 				constty = copy_constty();
1209 			}
1210 		} else if (tp == constty) {
1211 			freetp = set_constty(NULL);
1212 			if (freetp != NULL) {
1213 				if (freetp == tp) {
1214 					ttyfree_locked(freetp);
1215 				} else {
1216 					ttyfree(freetp);
1217 				}
1218 				freetp = NULL;
1219 			}
1220 			// constty == tp, so constty is locked
1221 			ttyfree_locked(constty);
1222 			constty = NULL;
1223 		}
1224 		if (constty) {
1225 			(*cdevsw[major(constty->t_dev)].d_ioctl)
1226 			(constty->t_dev, KMIOCDISABLCONS, NULL, 0, p);
1227 		} else {
1228 			(*cdevsw[major(tp->t_dev)].d_ioctl)
1229 			(tp->t_dev, KMIOCDISABLCONS, NULL, 0, p);
1230 		}
1231 		if (constty != NULL) {
1232 			if (constty == tp) {
1233 				ttyfree_locked(constty);
1234 			} else {
1235 				ttyfree(constty);
1236 			}
1237 		}
1238 		break;
1239 	}
1240 	case TIOCDRAIN:                 /* wait till output drained */
1241 		error = ttywait(tp);
1242 		if (error) {
1243 			goto out;
1244 		}
1245 		break;
1246 	case TIOCGETA_32:               /* get termios struct */
1247 #ifdef __LP64__
1248 		termios64to32((struct user_termios *)&tp->t_termios, (struct termios32 *)data);
1249 #else
1250 		bcopy(&tp->t_termios, data, sizeof(struct termios));
1251 #endif
1252 		break;
1253 	case TIOCGETA_64:               /* get termios struct */
1254 #ifdef __LP64__
1255 		bcopy(&tp->t_termios, data, sizeof(struct termios));
1256 #else
1257 		termios32to64((struct termios32 *)&tp->t_termios, (struct user_termios *)data);
1258 #endif
1259 		break;
1260 	case TIOCGETD:                  /* get line discipline */
1261 		*(int *)data = tp->t_line;
1262 		break;
1263 	case TIOCGWINSZ:                /* get window size */
1264 		*(struct winsize *)data = tp->t_winsize;
1265 		break;
1266 	case TIOCGPGRP:                 /* get pgrp of tty */
1267 		if (!isctty(p, tp)) {
1268 			error = ENOTTY;
1269 			goto out;
1270 		}
1271 		*(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
1272 		break;
1273 #ifdef TIOCHPCL
1274 	case TIOCHPCL:                  /* hang up on last close */
1275 		SET(tp->t_cflag, HUPCL);
1276 		break;
1277 #endif
1278 	case TIOCNXCL:                  /* reset exclusive use of tty */
1279 		CLR(tp->t_state, TS_XCLUDE);
1280 		break;
1281 	case TIOCOUTQ:                  /* output queue size */
1282 		*(int *)data = tp->t_outq.c_cc;
1283 		break;
1284 	case TIOCSETA_32:                       /* set termios struct */
1285 	case TIOCSETA_64:
1286 	case TIOCSETAW_32:                      /* drain output, set */
1287 	case TIOCSETAW_64:
1288 	case TIOCSETAF_32:              /* drn out, fls in, set */
1289 	case TIOCSETAF_64:
1290 	{               /* drn out, fls in, set */
1291 		struct termios *t = (struct termios *)data;
1292 		struct termios lcl_termios;
1293 
1294 #ifdef __LP64__
1295 		if (cmd == TIOCSETA_32 || cmd == TIOCSETAW_32 || cmd == TIOCSETAF_32) {
1296 			termios32to64((struct termios32 *)data, (struct user_termios *)&lcl_termios);
1297 			t = &lcl_termios;
1298 		}
1299 #else
1300 		if (cmd == TIOCSETA_64 || cmd == TIOCSETAW_64 || cmd == TIOCSETAF_64) {
1301 			termios64to32((struct user_termios *)data, (struct termios32 *)&lcl_termios);
1302 			t = &lcl_termios;
1303 		}
1304 #endif
1305 #if 0
1306 		/* XXX bogus test; always false */
1307 		if (t->c_ispeed < 0 || t->c_ospeed < 0) {
1308 			error = EINVAL;
1309 			goto out;
1310 		}
1311 #endif  /* 0 - leave in; may end up being a conformance issue */
1312 		if (t->c_ispeed == 0) {
1313 			t->c_ispeed = t->c_ospeed;
1314 		}
1315 		if (cmd == TIOCSETAW_32 || cmd == TIOCSETAF_32 ||
1316 		    cmd == TIOCSETAW_64 || cmd == TIOCSETAF_64) {
1317 			error = ttywait(tp);
1318 			if (error) {
1319 				goto out;
1320 			}
1321 			if (cmd == TIOCSETAF_32 || cmd == TIOCSETAF_64) {
1322 				ttyflush(tp, FREAD);
1323 			}
1324 		}
1325 		if (!ISSET(t->c_cflag, CIGNORE)) {
1326 			/*
1327 			 * Set device hardware.
1328 			 */
1329 			if (tp->t_param && (error = (*tp->t_param)(tp, t))) {
1330 				goto out;
1331 			}
1332 			if (ISSET(t->c_cflag, CLOCAL) &&
1333 			    !ISSET(tp->t_cflag, CLOCAL)) {
1334 				/*
1335 				 * XXX disconnections would be too hard to
1336 				 * get rid of without this kludge.  The only
1337 				 * way to get rid of controlling terminals
1338 				 * is to exit from the session leader.
1339 				 */
1340 				CLR(tp->t_state, TS_ZOMBIE);
1341 
1342 				wakeup(TSA_CARR_ON(tp));
1343 				ttwakeup(tp);
1344 				ttwwakeup(tp);
1345 			}
1346 			if ((ISSET(tp->t_state, TS_CARR_ON) ||
1347 			    ISSET(t->c_cflag, CLOCAL)) &&
1348 			    !ISSET(tp->t_state, TS_ZOMBIE)) {
1349 				SET(tp->t_state, TS_CONNECTED);
1350 			} else {
1351 				CLR(tp->t_state, TS_CONNECTED);
1352 			}
1353 			tp->t_cflag = t->c_cflag;
1354 			tp->t_ispeed = t->c_ispeed;
1355 			tp->t_ospeed = t->c_ospeed;
1356 			ttsetwater(tp);
1357 		}
1358 		if (ISSET(t->c_lflag, ICANON) != ISSET(tp->t_lflag, ICANON) &&
1359 		    cmd != TIOCSETAF_32 && cmd != TIOCSETAF_64) {
1360 			if (ISSET(t->c_lflag, ICANON)) {
1361 				SET(tp->t_lflag, PENDIN);
1362 			} else {
1363 				/*
1364 				 * XXX we really shouldn't allow toggling
1365 				 * ICANON while we're in a non-termios line
1366 				 * discipline.  Now we have to worry about
1367 				 * panicing for a null queue.
1368 				 */
1369 				if (tp->t_rawq.c_cs && tp->t_canq.c_cs) {
1370 					struct clist tq;
1371 
1372 					catq(&tp->t_rawq, &tp->t_canq);
1373 					tq = tp->t_rawq;
1374 					tp->t_rawq = tp->t_canq;
1375 					tp->t_canq = tq;
1376 				}
1377 				CLR(tp->t_lflag, PENDIN);
1378 			}
1379 			ttwakeup(tp);
1380 		}
1381 		tp->t_iflag = t->c_iflag;
1382 		tp->t_oflag = t->c_oflag;
1383 		/*
1384 		 * Make the EXTPROC bit read only.
1385 		 */
1386 		if (ISSET(tp->t_lflag, EXTPROC)) {
1387 			SET(t->c_lflag, EXTPROC);
1388 		} else {
1389 			CLR(t->c_lflag, EXTPROC);
1390 		}
1391 		tp->t_lflag = t->c_lflag | ISSET(tp->t_lflag, PENDIN);
1392 		if (t->c_cc[VMIN] != tp->t_cc[VMIN] ||
1393 		    t->c_cc[VTIME] != tp->t_cc[VTIME]) {
1394 			ttwakeup(tp);
1395 		}
1396 		bcopy(t->c_cc, tp->t_cc, sizeof(t->c_cc));
1397 		break;
1398 	}
1399 	case TIOCSETD: {                /* set line discipline */
1400 		int t = *(int *)data;
1401 		dev_t device = tp->t_dev;
1402 
1403 		if (t >= nlinesw || t < 0) {
1404 			error = ENXIO;
1405 			goto out;
1406 		}
1407 		/*
1408 		 * If the new line discipline is not equal to the old one,
1409 		 * close the old one and open the new one.
1410 		 */
1411 		if (t != tp->t_line) {
1412 			(*linesw[tp->t_line].l_close)(tp, flag);
1413 			error = (*linesw[t].l_open)(device, tp);
1414 			if (error) {
1415 				/* This is racy; it's possible to lose both */
1416 				(void)(*linesw[tp->t_line].l_open)(device, tp);
1417 				goto out;
1418 			}
1419 			tp->t_line = t;
1420 		}
1421 		break;
1422 	}
1423 	case TIOCSTART:                 /* start output, like ^Q */
1424 		if (ISSET(tp->t_state, TS_TTSTOP) ||
1425 		    ISSET(tp->t_lflag, FLUSHO)) {
1426 			CLR(tp->t_lflag, FLUSHO);
1427 			CLR(tp->t_state, TS_TTSTOP);
1428 			ttstart(tp);
1429 		}
1430 		break;
1431 	case TIOCSTI:                   /* simulate terminal input */
1432 		if (suser(kauth_cred_get(), NULL) && (flag & FREAD) == 0) {
1433 			error = EPERM;
1434 			goto out;
1435 		}
1436 		if (suser(kauth_cred_get(), NULL) && !isctty(p, tp)) {
1437 			error = EACCES;
1438 			goto out;
1439 		}
1440 		(*linesw[tp->t_line].l_rint)(*(u_char *)data, tp);
1441 		break;
1442 	case TIOCSTOP:                  /* stop output, like ^S */
1443 		if (!ISSET(tp->t_state, TS_TTSTOP)) {
1444 			SET(tp->t_state, TS_TTSTOP);
1445 			ttystop(tp, 0);
1446 		}
1447 		break;
1448 	case TIOCIXON:
1449 		ttyunblock(tp);
1450 		break;
1451 	case TIOCIXOFF:
1452 		ttyblock(tp);
1453 		break;
1454 	case TIOCSCTTY:                 /* become controlling tty */
1455 		/* Session ctty vnode pointer set in vnode layer. */
1456 		pg = proc_pgrp(p, &sessp);
1457 		if (pg == PGRP_NULL) {
1458 			error = EPERM;
1459 			goto out;
1460 		}
1461 
1462 		/*
1463 		 * This can only be done by a session leader.
1464 		 */
1465 		if (!SESS_LEADER(p, sessp)) {
1466 			/* SAFE: All callers drop the lock on return */
1467 			tty_unlock(tp);
1468 			pgrp_rele(pg);
1469 			tty_lock(tp);
1470 			error = EPERM;
1471 			goto out;
1472 		}
1473 		/*
1474 		 * If this terminal is already the controlling terminal for the
1475 		 * session, nothing to do here.
1476 		 */
1477 		if (tp->t_session == sessp) {
1478 			/* SAFE: All callers drop the lock on return */
1479 			tty_unlock(tp);
1480 			pgrp_rele(pg);
1481 			tty_lock(tp);
1482 			error = 0;
1483 			goto out;
1484 		}
1485 
1486 		/*
1487 		 * Deny if the terminal is already attached to another session or
1488 		 * the session already has a terminal vnode.
1489 		 */
1490 		proc_list_lock();
1491 		session_lock(sessp);
1492 		if (sessp->s_ttyvp || tp->t_session) {
1493 			session_unlock(sessp);
1494 			proc_list_unlock();
1495 			/* SAFE: All callers drop the lock on return */
1496 			tty_unlock(tp);
1497 			pgrp_rele(pg);
1498 			tty_lock(tp);
1499 			error = EPERM;
1500 			goto out;
1501 		}
1502 
1503 		sessp->s_ttypgrpid = pg->pg_id;
1504 		oldtp = session_set_tty_locked(sessp, tp);
1505 
1506 		oldpg = tp->t_pgrp;
1507 		oldsessp = tp->t_session;
1508 		tp->t_pgrp = pg; /* donate pg ref */
1509 		tp->t_session = session_ref(sessp);
1510 		session_unlock(sessp);
1511 
1512 		if (oldsessp) {
1513 			session_lock(oldsessp);
1514 			freetp = session_clear_tty_locked(oldsessp);
1515 			session_unlock(oldsessp);
1516 		}
1517 
1518 		os_atomic_or(&p->p_flag, P_CONTROLT, relaxed);
1519 		proc_list_unlock();
1520 		tty_unlock(tp);
1521 
1522 		if (oldsessp) {
1523 			session_rele(oldsessp);
1524 			if (freetp) {
1525 				ttyfree(freetp);
1526 			}
1527 		}
1528 		pgrp_rele(oldpg);
1529 		if (NULL != oldtp) {
1530 			ttyfree(oldtp);
1531 		}
1532 
1533 		/* SAFE: All callers drop the lock on return */
1534 		tty_lock(tp);
1535 		break;
1536 
1537 	case TIOCSPGRP: {               /* set pgrp of tty */
1538 		struct pgrp *pgrp = PGRP_NULL;
1539 
1540 		pg = proc_pgrp(p, &sessp);
1541 		if (!isctty_sp(p, tp, sessp)) {
1542 			pgrp_rele(pg);
1543 			error = ENOTTY;
1544 			goto out;
1545 		} else if ((pgrp = pgrp_find(*(int *)data)) == PGRP_NULL) {
1546 			pgrp_rele(pg);
1547 			error = EINVAL;
1548 			goto out;
1549 		} else if (pgrp->pg_session != sessp) {
1550 			/* SAFE: All callers drop the lock on return */
1551 			tty_unlock(tp);
1552 			pgrp_rele(pg);
1553 			pgrp_rele(pgrp);
1554 			tty_lock(tp);
1555 			error = EPERM;
1556 			goto out;
1557 		}
1558 
1559 		proc_list_lock();
1560 		oldpg = tp->t_pgrp;
1561 		tp->t_pgrp = pgrp;
1562 		proc_list_unlock();
1563 
1564 		session_lock(sessp);
1565 		sessp->s_ttypgrpid = pgrp->pg_id;
1566 		session_unlock(sessp);
1567 
1568 		/*
1569 		 * Wakeup readers to recheck if they are still the foreground
1570 		 * process group.
1571 		 *
1572 		 * ttwakeup() isn't called because the readers aren't getting
1573 		 * woken up because there is something to read but to force
1574 		 * the re-evaluation of their foreground process group status.
1575 		 *
1576 		 * Ordinarily leaving these readers waiting wouldn't be an issue
1577 		 * as launchd would send them a termination signal eventually
1578 		 * (if nobody else does). But if this terminal happens to be
1579 		 * /dev/console, launchd itself could get blocked forever behind
1580 		 * a revoke of /dev/console and leave the system deadlocked.
1581 		 */
1582 		wakeup(TSA_HUP_OR_INPUT(tp));
1583 
1584 		/* SAFE: All callers drop the lock on return */
1585 		tty_unlock(tp);
1586 		pgrp_rele(oldpg);
1587 		pgrp_rele(pg);
1588 		tty_lock(tp);
1589 		break;
1590 	}
1591 	case TIOCSTAT:                  /* simulate control-T */
1592 		ttyinfo_locked(tp);
1593 		break;
1594 	case TIOCSWINSZ:                /* set window size */
1595 		if (bcmp((caddr_t)&tp->t_winsize, data,
1596 		    sizeof(struct winsize))) {
1597 			tp->t_winsize = *(struct winsize *)data;
1598 			/* SAFE: All callers drop the lock on return */
1599 			tty_pgsignal_locked(tp, SIGWINCH, 1);
1600 		}
1601 		break;
1602 	case TIOCSDRAINWAIT:
1603 		error = suser(kauth_cred_get(), &p->p_acflag);
1604 		if (error) {
1605 			goto out;
1606 		}
1607 		tp->t_timeout = *(int *)data * hz;
1608 		wakeup(TSA_OCOMPLETE(tp));
1609 		wakeup(TSA_OLOWAT(tp));
1610 		break;
1611 	case TIOCGDRAINWAIT:
1612 		*(int *)data = tp->t_timeout / hz;
1613 		break;
1614 	case TIOCREVOKE:
1615 		SET(tp->t_state, TS_REVOKE);
1616 		tp->t_gen++;
1617 		/*
1618 		 * At this time, only this wait channel is woken up as only
1619 		 * ttread has been problematic. It is possible we may need
1620 		 * to add wake up other tty wait addresses as well.
1621 		 */
1622 		wakeup(TSA_HUP_OR_INPUT(tp));
1623 		break;
1624 	case TIOCREVOKECLEAR:
1625 		CLR(tp->t_state, TS_REVOKE);
1626 		break;
1627 	default:
1628 		error = ttcompat(tp, cmd, data, flag, p);
1629 		goto out;
1630 	}
1631 
1632 	error = 0;
1633 out:
1634 	return error;
1635 }
1636 
1637 
1638 /*
1639  * Locks:	Assumes tp is locked on entry, remains locked on exit
1640  */
1641 int
ttyselect(struct tty * tp,int rw,void * wql,proc_t p)1642 ttyselect(struct tty *tp, int rw, void *wql, proc_t p)
1643 {
1644 	int retval = 0;
1645 	/*
1646 	 * Attaching knotes to TTYs needs to call selrecord in order to hook
1647 	 * up the waitq to the selinfo, regardless of data being ready.  See
1648 	 * filt_ttyattach.
1649 	 */
1650 	bool needs_selrecord = rw & FMARK;
1651 	rw &= ~FMARK;
1652 
1653 	if (tp == NULL) {
1654 		return ENXIO;
1655 	}
1656 
1657 	TTY_LOCK_OWNED(tp);
1658 
1659 	if (tp->t_state & TS_ZOMBIE) {
1660 		retval = 1;
1661 		goto out;
1662 	}
1663 
1664 	switch (rw) {
1665 	case FREAD:
1666 		retval = ttnread(tp);
1667 		if (retval > 0) {
1668 			break;
1669 		}
1670 
1671 		selrecord(p, &tp->t_rsel, wql);
1672 		break;
1673 	case FWRITE:
1674 		if ((tp->t_outq.c_cc <= tp->t_lowat) &&
1675 		    (tp->t_state & TS_CONNECTED)) {
1676 			retval = tp->t_hiwat - tp->t_outq.c_cc;
1677 			break;
1678 		}
1679 
1680 		selrecord(p, &tp->t_wsel, wql);
1681 		break;
1682 	}
1683 
1684 out:
1685 	if (retval > 0 && needs_selrecord) {
1686 		switch (rw) {
1687 		case FREAD:
1688 			selrecord(p, &tp->t_rsel, wql);
1689 			break;
1690 		case FWRITE:
1691 			selrecord(p, &tp->t_wsel, wql);
1692 			break;
1693 		}
1694 	}
1695 
1696 	return retval;
1697 }
1698 
1699 
1700 /*
1701  * This is a wrapper for compatibility with the select vector used by
1702  * cdevsw.  It relies on a proper xxxdevtotty routine.
1703  *
1704  * Locks:	Assumes tty_lock() is not held prior to calling.
1705  */
1706 int
ttselect(dev_t dev,int rw,void * wql,proc_t p)1707 ttselect(dev_t dev, int rw, void *wql, proc_t p)
1708 {
1709 	int     rv;
1710 	struct tty *tp = cdevsw[major(dev)].d_ttys[minor(dev)];
1711 
1712 	tty_lock(tp);
1713 	rv =  ttyselect(tp, rw, wql, p);
1714 	tty_unlock(tp);
1715 
1716 	return rv;
1717 }
1718 
1719 
1720 /*
1721  * Locks:	Assumes tp is locked on entry, remains locked on exit
1722  */
1723 __private_extern__ int
ttnread(struct tty * tp)1724 ttnread(struct tty *tp)
1725 {
1726 	int nread;
1727 
1728 	TTY_LOCK_OWNED(tp);     /* debug assert */
1729 
1730 	if (ISSET(tp->t_lflag, PENDIN)) {
1731 		ttypend(tp);
1732 	}
1733 	nread = tp->t_canq.c_cc;
1734 	if (!ISSET(tp->t_lflag, ICANON)) {
1735 		nread += tp->t_rawq.c_cc;
1736 		if (nread < tp->t_cc[VMIN] && tp->t_cc[VTIME] == 0) {
1737 			nread = 0;
1738 		}
1739 	}
1740 	return nread;
1741 }
1742 
1743 
1744 /*
1745  * ttywait
1746  *
1747  * Wait for output to drain.
1748  *
1749  * Parameters:	tp			Tty on which to wait for output to drain
1750  *
1751  * Returns:	0			Success
1752  *		EIO			t_timeout too small/expired
1753  *	ttysleep:ERESTART		Upper layer must redrive the call;
1754  *					this is usually done by the Libc
1755  *					stub in user space
1756  *	ttysleep:EINTR			Interrupted (usually a signal)
1757  *
1758  * Notes:	Called from proc_exit() and vproc_exit().
1759  *
1760  * Locks:	Assumes tp is locked on entry, remains locked on exit
1761  */
1762 int
ttywait(struct tty * tp)1763 ttywait(struct tty *tp)
1764 {
1765 	int error;
1766 
1767 	TTY_LOCK_OWNED(tp);     /* debug assert */
1768 
1769 	error = 0;
1770 	while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1771 	    ISSET(tp->t_state, TS_CONNECTED) && tp->t_oproc) {
1772 		(*tp->t_oproc)(tp);
1773 		if ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1774 		    ISSET(tp->t_state, TS_CONNECTED)) {
1775 			SET(tp->t_state, TS_SO_OCOMPLETE);
1776 			error = ttysleep(tp, TSA_OCOMPLETE(tp),
1777 			    TTOPRI | PCATCH, "ttywai",
1778 			    tp->t_timeout);
1779 			if (error) {
1780 				if (error == EWOULDBLOCK) {
1781 					error = EIO;
1782 				}
1783 				break;
1784 			}
1785 		} else {
1786 			break;
1787 		}
1788 	}
1789 	if (!error && (tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY))) {
1790 		error = EIO;
1791 	}
1792 	return error;
1793 }
1794 
1795 /*
1796  * Stop the underlying device driver.
1797  *
1798  * Locks:	Assumes tty_lock() is held prior to calling.
1799  */
1800 static void
ttystop(struct tty * tp,int rw)1801 ttystop(struct tty *tp, int rw)
1802 {
1803 	TTY_LOCK_OWNED(tp);     /* debug assert */
1804 
1805 	(*cdevsw[major(tp->t_dev)].d_stop)(tp, rw);
1806 }
1807 
1808 /*
1809  * Flush if successfully wait.
1810  *
1811  * Locks:	Assumes tty_lock() is held prior to calling.
1812  */
1813 static int
ttywflush(struct tty * tp)1814 ttywflush(struct tty *tp)
1815 {
1816 	int error;
1817 
1818 	TTY_LOCK_OWNED(tp);     /* debug assert */
1819 
1820 	if ((error = ttywait(tp)) == 0) {
1821 		ttyflush(tp, FREAD);
1822 	}
1823 	return error;
1824 }
1825 
1826 /*
1827  * Flush tty read and/or write queues, notifying anyone waiting.
1828  *
1829  * Locks:	Assumes tty_lock() is held prior to calling.
1830  */
1831 void
ttyflush(struct tty * tp,int rw)1832 ttyflush(struct tty *tp, int rw)
1833 {
1834 	TTY_LOCK_OWNED(tp);     /* debug assert */
1835 
1836 #if 0
1837 again:
1838 #endif
1839 	if (rw & FWRITE) {
1840 		FLUSHQ(&tp->t_outq);
1841 		CLR(tp->t_state, TS_TTSTOP);
1842 	}
1843 	ttystop(tp, rw);
1844 	if (rw & FREAD) {
1845 		FLUSHQ(&tp->t_canq);
1846 		FLUSHQ(&tp->t_rawq);
1847 		CLR(tp->t_lflag, PENDIN);
1848 		tp->t_rocount = 0;
1849 		tp->t_rocol = 0;
1850 		CLR(tp->t_state, TS_LOCAL);
1851 		ttwakeup(tp);
1852 		if (ISSET(tp->t_state, TS_TBLOCK)) {
1853 			if (rw & FWRITE) {
1854 				FLUSHQ(&tp->t_outq);
1855 			}
1856 			ttyunblock(tp);
1857 
1858 			/*
1859 			 * Don't let leave any state that might clobber the
1860 			 * next line discipline (although we should do more
1861 			 * to send the START char).  Not clearing the state
1862 			 * may have caused the "putc to a clist with no
1863 			 * reserved cblocks" panic/printf.
1864 			 */
1865 			CLR(tp->t_state, TS_TBLOCK);
1866 
1867 #if 0 /* forget it, sleeping isn't always safe and we don't know when it is */
1868 			if (ISSET(tp->t_iflag, IXOFF)) {
1869 				/*
1870 				 * XXX wait a bit in the hope that the stop
1871 				 * character (if any) will go out.  Waiting
1872 				 * isn't good since it allows races.  This
1873 				 * will be fixed when the stop character is
1874 				 * put in a special queue.  Don't bother with
1875 				 * the checks in ttywait() since the timeout
1876 				 * will save us.
1877 				 */
1878 				SET(tp->t_state, TS_SO_OCOMPLETE);
1879 				ttysleep(tp, TSA_OCOMPLETE(tp), TTOPRI,
1880 				    "ttyfls", hz / 10);
1881 				/*
1882 				 * Don't try sending the stop character again.
1883 				 */
1884 				CLR(tp->t_state, TS_TBLOCK);
1885 				goto again;
1886 			}
1887 #endif
1888 		}
1889 	}
1890 	if (rw & FWRITE) {
1891 		FLUSHQ(&tp->t_outq);
1892 		ttwwakeup(tp);
1893 	}
1894 }
1895 
1896 /*
1897  * Copy in the default termios characters.
1898  *
1899  * Locks:	Assumes tty_lock() is held prior to calling.
1900  *
1901  * Notes:	No assertion; tp is not in scope.
1902  */
1903 void
termioschars(struct termios * t)1904 termioschars(struct termios *t)
1905 {
1906 	bcopy(ttydefchars, t->c_cc, sizeof t->c_cc);
1907 }
1908 
1909 
1910 /*
1911  * Handle input high water.  Send stop character for the IXOFF case.  Turn
1912  * on our input flow control bit and propagate the changes to the driver.
1913  * XXX the stop character should be put in a special high priority queue.
1914  *
1915  * Locks:	Assumes tty_lock() is held for the call.
1916  */
1917 void
ttyblock(struct tty * tp)1918 ttyblock(struct tty *tp)
1919 {
1920 	TTY_LOCK_OWNED(tp);     /* debug assert */
1921 
1922 	SET(tp->t_state, TS_TBLOCK);
1923 	if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
1924 	    putc(tp->t_cc[VSTOP], &tp->t_outq) != 0) {
1925 		CLR(tp->t_state, TS_TBLOCK);    /* try again later */
1926 	}
1927 	ttstart(tp);
1928 }
1929 
1930 
1931 /*
1932  * Handle input low water.  Send start character for the IXOFF case.  Turn
1933  * off our input flow control bit and propagate the changes to the driver.
1934  * XXX the start character should be put in a special high priority queue.
1935  *
1936  * Locks:	Assumes tty_lock() is held for the call.
1937  */
1938 static void
ttyunblock(struct tty * tp)1939 ttyunblock(struct tty *tp)
1940 {
1941 	TTY_LOCK_OWNED(tp);     /* debug assert */
1942 
1943 	CLR(tp->t_state, TS_TBLOCK);
1944 	if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTART] != _POSIX_VDISABLE &&
1945 	    putc(tp->t_cc[VSTART], &tp->t_outq) != 0) {
1946 		SET(tp->t_state, TS_TBLOCK);    /* try again later */
1947 	}
1948 	ttstart(tp);
1949 }
1950 
1951 
1952 /*
1953  * ttstart
1954  *
1955  * Start tty output
1956  *
1957  * Parameters:	tp			tty on which to start output
1958  *
1959  * Returns:	0			Success
1960  *
1961  * Locks:	Assumes tty_lock() is held for the call.
1962  *
1963  * Notes:	This function might as well be void; it always returns success
1964  *
1965  *		Called from ttioctl_locked(), LDISC routines, and
1966  *		ttycheckoutq(), ttyblock(), ttyunblock(), and tputchar()
1967  */
1968 int
ttstart(struct tty * tp)1969 ttstart(struct tty *tp)
1970 {
1971 	TTY_LOCK_OWNED(tp);     /* debug assert */
1972 
1973 	if (tp->t_oproc != NULL) {      /* XXX: Kludge for pty. */
1974 		(*tp->t_oproc)(tp);
1975 	}
1976 
1977 	return 0;
1978 }
1979 
1980 
1981 /*
1982  * ttylclose (LDISC)
1983  *
1984  * "close" a line discipline
1985  *
1986  * Locks:	Assumes tty_lock() is held prior to calling.
1987  */
1988 int
ttylclose(struct tty * tp,int flag)1989 ttylclose(struct tty *tp, int flag)
1990 {
1991 	TTY_LOCK_OWNED(tp);     /* debug assert */
1992 
1993 	if ((flag & FNONBLOCK) || ttywflush(tp)) {
1994 		ttyflush(tp, FREAD | FWRITE);
1995 	}
1996 
1997 	return 0;
1998 }
1999 
2000 
2001 /*
2002  * ttymodem (LDISC)
2003  *
2004  * Handle modem control transition on a tty.
2005  * Flag indicates new state of carrier.
2006  * Returns 0 if the line should be turned off, otherwise 1.
2007  *
2008  * Locks:	Assumes tty_lock() is held prior to calling.
2009  */
2010 int
ttymodem(struct tty * tp,int flag)2011 ttymodem(struct tty *tp, int flag)
2012 {
2013 	int rval = 1;           /* default return value */
2014 
2015 	TTY_LOCK_OWNED(tp);     /* debug assert */
2016 
2017 	if (ISSET(tp->t_state, TS_CARR_ON) && ISSET(tp->t_cflag, MDMBUF)) {
2018 		/*
2019 		 * MDMBUF: do flow control according to carrier flag
2020 		 * XXX TS_CAR_OFLOW doesn't do anything yet.  TS_TTSTOP
2021 		 * works if IXON and IXANY are clear.
2022 		 */
2023 		if (flag) {
2024 			CLR(tp->t_state, TS_CAR_OFLOW);
2025 			CLR(tp->t_state, TS_TTSTOP);
2026 			ttstart(tp);
2027 		} else if (!ISSET(tp->t_state, TS_CAR_OFLOW)) {
2028 			SET(tp->t_state, TS_CAR_OFLOW);
2029 			SET(tp->t_state, TS_TTSTOP);
2030 			ttystop(tp, 0);
2031 		}
2032 	} else if (flag == 0) {
2033 		/*
2034 		 * Lost carrier.
2035 		 */
2036 		CLR(tp->t_state, TS_CARR_ON);
2037 		if (ISSET(tp->t_state, TS_ISOPEN) &&
2038 		    !ISSET(tp->t_cflag, CLOCAL)) {
2039 			SET(tp->t_state, TS_ZOMBIE);
2040 			CLR(tp->t_state, TS_CONNECTED);
2041 			if (tp->t_session && tp->t_session->s_leader) {
2042 				psignal(tp->t_session->s_leader, SIGHUP);
2043 			}
2044 			ttyflush(tp, FREAD | FWRITE);
2045 			rval = 0;
2046 			goto out;
2047 		}
2048 	} else {
2049 		/*
2050 		 * Carrier now on.
2051 		 */
2052 		SET(tp->t_state, TS_CARR_ON);
2053 		if (!ISSET(tp->t_state, TS_ZOMBIE)) {
2054 			SET(tp->t_state, TS_CONNECTED);
2055 		}
2056 		wakeup(TSA_CARR_ON(tp));
2057 		ttwakeup(tp);
2058 		ttwwakeup(tp);
2059 	}
2060 
2061 out:
2062 	return rval;
2063 }
2064 
2065 
2066 /*
2067  * Reinput pending characters after state switch
2068  * call at spltty().
2069  *
2070  * Locks:	Assumes tty_lock() is held for the call.
2071  */
2072 static void
ttypend(struct tty * tp)2073 ttypend(struct tty *tp)
2074 {
2075 	struct clist tq;
2076 	int c;
2077 
2078 	TTY_LOCK_OWNED(tp);     /* debug assert */
2079 
2080 	CLR(tp->t_lflag, PENDIN);
2081 	SET(tp->t_state, TS_TYPEN);
2082 	tq = tp->t_rawq;
2083 	tp->t_rawq.c_cc = 0;
2084 	tp->t_rawq.c_cf = tp->t_rawq.c_cl = NULL;
2085 	while ((c = getc(&tq)) >= 0) {
2086 		ttyinput(c, tp);
2087 	}
2088 	CLR(tp->t_state, TS_TYPEN);
2089 }
2090 
2091 
2092 /*
2093  * ttread (LDISC)
2094  *
2095  * Process a read call on a tty device.
2096  *
2097  * Locks:	Assumes tty_lock() is held prior to calling.
2098  */
2099 int
ttread(struct tty * tp,struct uio * uio,int flag)2100 ttread(struct tty *tp, struct uio *uio, int flag)
2101 {
2102 	struct clist *qp;
2103 	int c;
2104 	tcflag_t lflag;
2105 	cc_t *cc = tp->t_cc;
2106 	proc_t p = current_proc();
2107 	int first, error = 0;
2108 	int has_etime = 0, last_cc = 0;
2109 	long slp = 0;           /* XXX this should be renamed `timo'. */
2110 	struct uthread *ut;
2111 	struct pgrp * pg;
2112 
2113 	TTY_LOCK_OWNED(tp);     /* debug assert */
2114 
2115 	ut = current_uthread();
2116 
2117 loop:
2118 	lflag = tp->t_lflag;
2119 	/*
2120 	 * take pending input first
2121 	 */
2122 	if (ISSET(lflag, PENDIN)) {
2123 		ttypend(tp);
2124 		lflag = tp->t_lflag;    /* XXX ttypend() clobbers it */
2125 	}
2126 
2127 	/*
2128 	 * Signal the process if it's in the background. If the terminal is
2129 	 * getting revoked, everybody is in the background.
2130 	 */
2131 	if (isbackground(p, tp) || ISSET(tp->t_state, TS_REVOKE)) {
2132 		if ((p->p_sigignore & sigmask(SIGTTIN)) ||
2133 		    (ut->uu_sigmask & sigmask(SIGTTIN)) ||
2134 		    p->p_lflag & P_LPPWAIT) {
2135 			error = EIO;
2136 			goto err;
2137 		}
2138 		pg = proc_pgrp(p, NULL);
2139 		if (pg == PGRP_NULL) {
2140 			error = EIO;
2141 			goto err;
2142 		}
2143 		if (pg->pg_jobc == 0) {
2144 			/* SAFE: All callers drop the lock on return */
2145 			tty_unlock(tp);
2146 			pgrp_rele(pg);
2147 			tty_lock(tp);
2148 			error = EIO;
2149 			goto err;
2150 		}
2151 		/* SAFE: All callers drop the lock on return */
2152 		tty_unlock(tp);
2153 		pgsignal(pg, SIGTTIN, 1);
2154 		pgrp_rele(pg);
2155 		tty_lock(tp);
2156 
2157 		/*
2158 		 * We signalled ourself, so we need to act as if we
2159 		 * have been "interrupted" from a "sleep" to act on
2160 		 * the signal.  If it's a signal that stops the
2161 		 * process, that's handled in the signal sending code.
2162 		 */
2163 		error = EINTR;
2164 		goto err;
2165 	}
2166 
2167 	if (ISSET(tp->t_state, TS_ZOMBIE)) {
2168 		/* EOF - returning 0 */
2169 		goto err;
2170 	}
2171 
2172 	/*
2173 	 * If canonical, use the canonical queue,
2174 	 * else use the raw queue.
2175 	 *
2176 	 * (should get rid of clists...)
2177 	 */
2178 	qp = ISSET(lflag, ICANON) ? &tp->t_canq : &tp->t_rawq;
2179 
2180 	if (flag & IO_NDELAY) {
2181 		if (qp->c_cc > 0) {
2182 			goto read;
2183 		}
2184 		if (ISSET(lflag, ICANON) || cc[VMIN] != 0) {
2185 			error = EWOULDBLOCK;
2186 		}
2187 		/* else polling - returning 0 */
2188 		goto err;
2189 	}
2190 	if (!ISSET(lflag, ICANON)) {
2191 		int m = cc[VMIN];
2192 		long t = cc[VTIME];
2193 		struct timeval timecopy;
2194 		struct timeval etime = {.tv_sec = 0, .tv_usec = 0};     /* protected by !has_etime */
2195 
2196 		/*
2197 		 * Check each of the four combinations.
2198 		 * (m > 0 && t == 0) is the normal read case.
2199 		 * It should be fairly efficient, so we check that and its
2200 		 * companion case (m == 0 && t == 0) first.
2201 		 * For the other two cases, we compute the target sleep time
2202 		 * into slp.
2203 		 */
2204 		if (t == 0) {
2205 			if (qp->c_cc < m) {
2206 				goto sleep;
2207 			}
2208 			if (qp->c_cc > 0) {
2209 				goto read;
2210 			}
2211 
2212 			/* m, t and qp->c_cc are all 0.  0 is enough input. */
2213 			goto err;
2214 		}
2215 		t *= 100000;            /* time in us */
2216 #define diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 1000000 + \
2217 	                 ((t1).tv_usec - (t2).tv_usec))
2218 		if (m > 0) {
2219 			if (qp->c_cc <= 0) {
2220 				goto sleep;
2221 			}
2222 			if (qp->c_cc >= m) {
2223 				goto read;
2224 			}
2225 			microuptime(&timecopy);
2226 			if (!has_etime || qp->c_cc > last_cc) {
2227 				/* first character or got a character, start timer */
2228 				has_etime = 1;
2229 
2230 				etime.tv_sec = t / 1000000;
2231 				etime.tv_usec =
2232 				    (__darwin_suseconds_t)(t - (etime.tv_sec * 1000000));
2233 				timeradd(&etime, &timecopy, &etime);
2234 
2235 				slp = t;
2236 			} else {
2237 				/* nothing, check expiration */
2238 				if (timercmp(&etime, &timecopy, <=)) {
2239 					goto read;
2240 				}
2241 
2242 				slp = diff(etime, timecopy);
2243 			}
2244 			last_cc = qp->c_cc;
2245 		} else {        /* m == 0 */
2246 			if (qp->c_cc > 0) {
2247 				goto read;
2248 			}
2249 			microuptime(&timecopy);
2250 			if (!has_etime) {
2251 				has_etime = 1;
2252 
2253 				etime.tv_sec = t / 1000000;
2254 				etime.tv_usec =
2255 				    (__darwin_suseconds_t)(t - (etime.tv_sec * 1000000));
2256 				timeradd(&etime, &timecopy, &etime);
2257 
2258 				slp = t;
2259 			} else {
2260 				if (timercmp(&etime, &timecopy, <=)) {
2261 					/* Timed out, but 0 is enough input. */
2262 					goto err;
2263 				}
2264 				slp = diff(etime, timecopy);
2265 			}
2266 		}
2267 #undef diff
2268 		/*
2269 		 * Rounding down may make us wake up just short
2270 		 * of the target, so we round up.
2271 		 * The formula is ceiling(slp * hz/1000000).
2272 		 * 32-bit arithmetic is enough for hz < 169.
2273 		 * XXX see hzto() for how to avoid overflow if hz
2274 		 * is large (divide by `tick' and/or arrange to
2275 		 * use hzto() if hz is large).
2276 		 */
2277 		slp = (long) (((u_int32_t)slp * hz) + 999999) / 1000000;
2278 		goto sleep;
2279 	}
2280 	if (qp->c_cc <= 0) {
2281 sleep:
2282 		/*
2283 		 * There is no input, or not enough input and we can block.
2284 		 */
2285 		error = ttysleep(tp, TSA_HUP_OR_INPUT(tp), TTIPRI | PCATCH,
2286 		    ISSET(tp->t_state, TS_CONNECTED) ?
2287 		    "ttyin" : "ttyhup", (int)slp);
2288 		if (error == EWOULDBLOCK) {
2289 			error = 0;
2290 		} else if (error) {
2291 			goto err;
2292 		}
2293 		/*
2294 		 * XXX what happens if another process eats some input
2295 		 * while we are asleep (not just here)?  It would be
2296 		 * safest to detect changes and reset our state variables
2297 		 * (has_stime and last_cc).
2298 		 */
2299 		slp = 0;
2300 		goto loop;
2301 	}
2302 read:
2303 	/*
2304 	 * Input present, check for input mapping and processing.
2305 	 */
2306 	first = 1;
2307 	if (ISSET(lflag, ICANON)
2308 	    || (ISSET(lflag, IEXTEN | ISIG) == (IEXTEN | ISIG))) {
2309 		goto slowcase;
2310 	}
2311 	for (;;) {
2312 		char ibuf[IBUFSIZ];
2313 		int icc;
2314 		ssize_t size = uio_resid(uio);
2315 		if (size < 0) {
2316 			error = ERANGE;
2317 			break;
2318 		}
2319 
2320 		icc = (int)MIN(size, IBUFSIZ);
2321 		icc = q_to_b(qp, (u_char *)ibuf, icc);
2322 		if (icc <= 0) {
2323 			if (first) {
2324 				goto loop;
2325 			}
2326 			break;
2327 		}
2328 		error = uiomove(ibuf, icc, uio);
2329 		/*
2330 		 * XXX if there was an error then we should ungetc() the
2331 		 * unmoved chars and reduce icc here.
2332 		 */
2333 		if (error) {
2334 			break;
2335 		}
2336 		if (uio_resid(uio) == 0) {
2337 			break;
2338 		}
2339 		first = 0;
2340 	}
2341 	goto out;
2342 slowcase:
2343 	for (;;) {
2344 		c = getc(qp);
2345 		if (c < 0) {
2346 			if (first) {
2347 				goto loop;
2348 			}
2349 			break;
2350 		}
2351 		/*
2352 		 * delayed suspend (^Y)
2353 		 */
2354 		if (CCEQ(cc[VDSUSP], c) &&
2355 		    ISSET(lflag, IEXTEN | ISIG) == (IEXTEN | ISIG)) {
2356 			/*
2357 			 * SAFE: All callers drop the lock on return and
2358 			 * SAFE: current thread will not change out from
2359 			 * SAFE: under us in the "goto loop" case.
2360 			 */
2361 			tty_pgsignal_locked(tp, SIGTSTP, 1);
2362 			if (first) {
2363 				error = ttysleep(tp, &ttread, TTIPRI | PCATCH,
2364 				    "ttybg3", hz);
2365 				if (error) {
2366 					break;
2367 				}
2368 				goto loop;
2369 			}
2370 			break;
2371 		}
2372 		/*
2373 		 * Interpret EOF only in canonical mode.
2374 		 */
2375 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON)) {
2376 			break;
2377 		}
2378 		/*
2379 		 * Give user character.
2380 		 */
2381 		error = ureadc(c, uio);
2382 		if (error) {
2383 			/* XXX should ungetc(c, qp). */
2384 			break;
2385 		}
2386 		if (uio_resid(uio) == 0) {
2387 			break;
2388 		}
2389 		/*
2390 		 * In canonical mode check for a "break character"
2391 		 * marking the end of a "line of input".
2392 		 */
2393 		if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag)) {
2394 			break;
2395 		}
2396 		first = 0;
2397 	}
2398 
2399 out:
2400 	/*
2401 	 * Look to unblock input now that (presumably)
2402 	 * the input queue has gone down.
2403 	 */
2404 	if (ISSET(tp->t_state, TS_TBLOCK) &&
2405 	    tp->t_rawq.c_cc + tp->t_canq.c_cc <= I_LOW_WATER) {
2406 		ttyunblock(tp);
2407 	}
2408 
2409 err:
2410 	return error;
2411 }
2412 
2413 
2414 /*
2415  * Check the output queue on tp for space for a kernel message (from uprintf
2416  * or tprintf).  Allow some space over the normal hiwater mark so we don't
2417  * lose messages due to normal flow control, but don't let the tty run amok.
2418  * Sleeps here are not interruptible, but we return prematurely if new signals
2419  * arrive.
2420  *
2421  * Locks:	Assumes tty_lock() is held before calling
2422  *
2423  * Notes:	This function is called from tprintf() in subr_prf.c
2424  */
2425 int
ttycheckoutq(struct tty * tp,int wait)2426 ttycheckoutq(struct tty *tp, int wait)
2427 {
2428 	int hiwat;
2429 	sigset_t oldsig;
2430 	struct uthread *ut;
2431 
2432 	TTY_LOCK_OWNED(tp);     /* debug assert */
2433 
2434 	ut = current_uthread();
2435 
2436 	hiwat = tp->t_hiwat;
2437 	oldsig = wait ? ut->uu_siglist : 0;
2438 	if (tp->t_outq.c_cc > hiwat + OBUFSIZ + 100) {
2439 		while (tp->t_outq.c_cc > hiwat) {
2440 			ttstart(tp);
2441 			if (tp->t_outq.c_cc <= hiwat) {
2442 				break;
2443 			}
2444 			if (wait == 0 || ut->uu_siglist != oldsig) {
2445 				return 0;
2446 			}
2447 			SET(tp->t_state, TS_SO_OLOWAT);
2448 			ttysleep(tp, TSA_OLOWAT(tp), PZERO - 1, "ttoutq", hz);
2449 		}
2450 	}
2451 	return 1;
2452 }
2453 
2454 
2455 /*
2456  * ttwrite (LDISC)
2457  *
2458  * Process a write call on a tty device.
2459  *
2460  * Locks:	Assumes tty_lock() is held prior to calling.
2461  */
2462 int
ttwrite(struct tty * tp,struct uio * uio,int flag)2463 ttwrite(struct tty *tp, struct uio *uio, int flag)
2464 {
2465 	char *cp = NULL;
2466 	int cc, ce;
2467 	proc_t p;
2468 	int i, hiwat, error;
2469 	user_ssize_t count;
2470 	char obuf[OBUFSIZ];
2471 	struct uthread *ut;
2472 	struct pgrp * pg;
2473 
2474 	TTY_LOCK_OWNED(tp);     /* debug assert */
2475 
2476 	ut = current_uthread();
2477 	hiwat = tp->t_hiwat;
2478 	count = uio_resid(uio);
2479 	error = 0;
2480 	cc = 0;
2481 loop:
2482 	if (ISSET(tp->t_state, TS_ZOMBIE)) {
2483 		if (uio_resid(uio) == count) {
2484 			error = EIO;
2485 		}
2486 		goto out;
2487 	}
2488 	if (!ISSET(tp->t_state, TS_CONNECTED)) {
2489 		if (flag & IO_NDELAY) {
2490 			error = EWOULDBLOCK;
2491 			goto out;
2492 		}
2493 		error = ttysleep(tp, TSA_CARR_ON(tp), TTIPRI | PCATCH,
2494 		    "ttydcd", 0);
2495 		if (error) {
2496 			goto out;
2497 		}
2498 		goto loop;
2499 	}
2500 	/*
2501 	 * Signal the process if it's in the background.
2502 	 */
2503 	p = current_proc();
2504 	if (isbackground(p, tp) &&
2505 	    ISSET(tp->t_lflag, TOSTOP) && (p->p_lflag & P_LPPWAIT) == 0 &&
2506 	    (p->p_sigignore & sigmask(SIGTTOU)) == 0 &&
2507 	    (ut->uu_sigmask & sigmask(SIGTTOU)) == 0) {
2508 		pg = proc_pgrp(p, NULL);
2509 		if (pg == PGRP_NULL) {
2510 			error = EIO;
2511 			goto out;
2512 		}
2513 		if (pg->pg_jobc == 0) {
2514 			/* SAFE: All callers drop the lock on return */
2515 			tty_unlock(tp);
2516 			pgrp_rele(pg);
2517 			tty_lock(tp);
2518 			error = EIO;
2519 			goto out;
2520 		}
2521 		/* SAFE: All callers drop the lock on return */
2522 		tty_unlock(tp);
2523 		pgsignal(pg, SIGTTOU, 1);
2524 		pgrp_rele(pg);
2525 		tty_lock(tp);
2526 		/*
2527 		 * We signalled ourself, so we need to act as if we
2528 		 * have been "interrupted" from a "sleep" to act on
2529 		 * the signal.  If it's a signal that stops the
2530 		 * process, that's handled in the signal sending code.
2531 		 */
2532 		error = EINTR;
2533 		goto out;
2534 	}
2535 	/*
2536 	 * Process the user's data in at most OBUFSIZ chunks.  Perform any
2537 	 * output translation.  Keep track of high water mark, sleep on
2538 	 * overflow awaiting device aid in acquiring new space.
2539 	 */
2540 	while (uio_resid(uio) > 0 || cc > 0) {
2541 		if (ISSET(tp->t_lflag, FLUSHO)) {
2542 			uio_setresid(uio, 0);
2543 			return 0;
2544 		}
2545 		if (tp->t_outq.c_cc > hiwat) {
2546 			goto ovhiwat;
2547 		}
2548 		/*
2549 		 * Grab a hunk of data from the user, unless we have some
2550 		 * leftover from last time.
2551 		 */
2552 		if (cc == 0) {
2553 			ssize_t size = uio_resid(uio);
2554 			if (size < 0) {
2555 				error = ERANGE;
2556 				break;
2557 			}
2558 			cc = (int)MIN((size_t)size, OBUFSIZ);
2559 			cp = obuf;
2560 			error = uiomove(cp, cc, uio);
2561 			if (error) {
2562 				cc = 0;
2563 				break;
2564 			}
2565 		}
2566 		/*
2567 		 * If nothing fancy need be done, grab those characters we
2568 		 * can handle without any of ttyoutput's processing and
2569 		 * just transfer them to the output q.  For those chars
2570 		 * which require special processing (as indicated by the
2571 		 * bits in char_type), call ttyoutput.  After processing
2572 		 * a hunk of data, look for FLUSHO so ^O's will take effect
2573 		 * immediately.
2574 		 */
2575 		while (cc > 0) {
2576 			if (!ISSET(tp->t_oflag, OPOST)) {
2577 				ce = cc;
2578 			} else {
2579 				ce = (int)((size_t)cc - scanc((size_t)cc,
2580 				    (u_char *)cp, char_type, CCLASSMASK));
2581 				/*
2582 				 * If ce is zero, then we're processing
2583 				 * a special character through ttyoutput.
2584 				 */
2585 				if (ce == 0) {
2586 					tp->t_rocount = 0;
2587 					if (ttyoutput(*cp, tp) >= 0) {
2588 						/* out of space */
2589 						goto overfull;
2590 					}
2591 					cp++;
2592 					cc--;
2593 					if (ISSET(tp->t_lflag, FLUSHO) ||
2594 					    tp->t_outq.c_cc > hiwat) {
2595 						goto ovhiwat;
2596 					}
2597 					continue;
2598 				}
2599 			}
2600 			/*
2601 			 * A bunch of normal characters have been found.
2602 			 * Transfer them en masse to the output queue and
2603 			 * continue processing at the top of the loop.
2604 			 * If there are any further characters in this
2605 			 * <= OBUFSIZ chunk, the first should be a character
2606 			 * requiring special handling by ttyoutput.
2607 			 */
2608 			tp->t_rocount = 0;
2609 			i = b_to_q((u_char *)cp, ce, &tp->t_outq);
2610 			ce -= i;
2611 			tp->t_column += ce;
2612 			cp += ce;
2613 			cc -= ce;
2614 			tk_nout += ce;
2615 			tp->t_outcc += ce;
2616 			if (i > 0) {
2617 				/* out of space */
2618 				goto overfull;
2619 			}
2620 			if (ISSET(tp->t_lflag, FLUSHO) ||
2621 			    tp->t_outq.c_cc > hiwat) {
2622 				break;
2623 			}
2624 		}
2625 		ttstart(tp);
2626 	}
2627 out:
2628 	/*
2629 	 * If cc is nonzero, we leave the uio structure inconsistent, as the
2630 	 * offset and iov pointers have moved forward, but it doesn't matter
2631 	 * (the call will either return short or restart with a new uio).
2632 	 */
2633 	uio_setresid(uio, (uio_resid(uio) + cc));
2634 	return error;
2635 
2636 overfull:
2637 
2638 	/*
2639 	 * Since we are using ring buffers, if we can't insert any more into
2640 	 * the output queue, we can assume the ring is full and that someone
2641 	 * forgot to set the high water mark correctly.  We set it and then
2642 	 * proceed as normal.
2643 	 */
2644 	hiwat = tp->t_outq.c_cc - 1;
2645 
2646 ovhiwat:
2647 	ttstart(tp);
2648 	/*
2649 	 * This can only occur if FLUSHO is set in t_lflag,
2650 	 * or if ttstart/oproc is synchronous (or very fast).
2651 	 */
2652 	if (tp->t_outq.c_cc <= hiwat) {
2653 		goto loop;
2654 	}
2655 	if (flag & IO_NDELAY) {
2656 		uio_setresid(uio, (uio_resid(uio) + cc));
2657 		return uio_resid(uio) == count ? EWOULDBLOCK : 0;
2658 	}
2659 	SET(tp->t_state, TS_SO_OLOWAT);
2660 	error = ttysleep(tp, TSA_OLOWAT(tp), TTOPRI | PCATCH, "ttywri",
2661 	    tp->t_timeout);
2662 	if (error == EWOULDBLOCK) {
2663 		error = EIO;
2664 	}
2665 	if (error) {
2666 		goto out;
2667 	}
2668 	goto loop;
2669 }
2670 
2671 
2672 /*
2673  * Rubout one character from the rawq of tp
2674  * as cleanly as possible.
2675  *
2676  * Locks:	Assumes tty_lock() is held prior to calling.
2677  */
2678 static void
ttyrub(int c,struct tty * tp)2679 ttyrub(int c, struct tty *tp)
2680 {
2681 	u_char *cp;
2682 	int savecol;
2683 	int tabc;
2684 
2685 	TTY_LOCK_OWNED(tp);     /* debug assert */
2686 
2687 	if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC)) {
2688 		return;
2689 	}
2690 	CLR(tp->t_lflag, FLUSHO);
2691 	if (ISSET(tp->t_lflag, ECHOE)) {
2692 		if (tp->t_rocount == 0) {
2693 			/*
2694 			 * Messed up by ttwrite; retype
2695 			 */
2696 			ttyretype(tp);
2697 			return;
2698 		}
2699 		if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE)) {
2700 			ttyrubo(tp, 2);
2701 		} else {
2702 			CLR(c, ~TTY_CHARMASK);
2703 			switch (CCLASS(c)) {
2704 			case ORDINARY:
2705 				if (!(ISSET(tp->t_iflag, IUTF8) && CCONT(c))) {
2706 					ttyrubo(tp, 1);
2707 				}
2708 				break;
2709 			case BACKSPACE:
2710 			case CONTROL:
2711 			case NEWLINE:
2712 			case RETURN:
2713 			case VTAB:
2714 				if (ISSET(tp->t_lflag, ECHOCTL)) {
2715 					ttyrubo(tp, 2);
2716 				}
2717 				break;
2718 			case TAB:
2719 				if (tp->t_rocount < tp->t_rawq.c_cc) {
2720 					ttyretype(tp);
2721 					return;
2722 				}
2723 				savecol = tp->t_column;
2724 				SET(tp->t_state, TS_CNTTB);
2725 				SET(tp->t_lflag, FLUSHO);
2726 				tp->t_column = tp->t_rocol;
2727 				for (cp = firstc(&tp->t_rawq, &tabc); cp;
2728 				    cp = nextc(&tp->t_rawq, cp, &tabc)) {
2729 					ttyecho(tabc, tp);
2730 				}
2731 				CLR(tp->t_lflag, FLUSHO);
2732 				CLR(tp->t_state, TS_CNTTB);
2733 
2734 				/* savecol will now be length of the tab. */
2735 				savecol -= tp->t_column;
2736 				tp->t_column += savecol;
2737 				if (savecol > 8) {
2738 					savecol = 8;    /* overflow fixup */
2739 				}
2740 				while (--savecol >= 0) {
2741 					(void)ttyoutput('\b', tp);
2742 				}
2743 				break;
2744 			default:                        /* XXX */
2745 #define PANICSTR        "ttyrub: would panic c = %d, val = %d\n"
2746 				printf(PANICSTR, c, CCLASS(c));
2747 #ifdef notdef
2748 				panic(PANICSTR, c, CCLASS(c));
2749 #endif
2750 			}
2751 		}
2752 	} else if (ISSET(tp->t_lflag, ECHOPRT)) {
2753 		if (!ISSET(tp->t_state, TS_ERASE)) {
2754 			SET(tp->t_state, TS_ERASE);
2755 			(void)ttyoutput('\\', tp);
2756 		}
2757 		ttyecho(c, tp);
2758 	} else {
2759 		ttyecho(tp->t_cc[VERASE], tp);
2760 	}
2761 	--tp->t_rocount;
2762 }
2763 
2764 
2765 /*
2766  * Back over count characters, erasing them.
2767  *
2768  * Locks:	Assumes tty_lock() is held prior to calling.
2769  */
2770 static void
ttyrubo(struct tty * tp,int count)2771 ttyrubo(struct tty *tp, int count)
2772 {
2773 	TTY_LOCK_OWNED(tp);     /* debug assert */
2774 
2775 	while (count-- > 0) {
2776 		(void)ttyoutput('\b', tp);
2777 		(void)ttyoutput(' ', tp);
2778 		(void)ttyoutput('\b', tp);
2779 	}
2780 }
2781 
2782 
2783 /*
2784  * ttyretype --
2785  *	Reprint the rawq line.  Note, it is assumed that c_cc has already
2786  *	been checked.
2787  *
2788  * Locks:	Assumes tty_lock() is held prior to calling.
2789  */
2790 static void
ttyretype(struct tty * tp)2791 ttyretype(struct tty *tp)
2792 {
2793 	u_char *cp;
2794 	int c;
2795 
2796 	TTY_LOCK_OWNED(tp);     /* debug assert */
2797 
2798 	/* Echo the reprint character. */
2799 	if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE) {
2800 		ttyecho(tp->t_cc[VREPRINT], tp);
2801 	}
2802 
2803 	(void)ttyoutput('\n', tp);
2804 
2805 	/*
2806 	 * FREEBSD XXX
2807 	 * FIX: NEXTC IS BROKEN - DOESN'T CHECK QUOTE
2808 	 * BIT OF FIRST CHAR.
2809 	 */
2810 	for (cp = firstc(&tp->t_canq, &c); cp; cp = nextc(&tp->t_canq, cp, &c)) {
2811 		ttyecho(c, tp);
2812 	}
2813 	for (cp = firstc(&tp->t_rawq, &c); cp; cp = nextc(&tp->t_rawq, cp, &c)) {
2814 		ttyecho(c, tp);
2815 	}
2816 	CLR(tp->t_state, TS_ERASE);
2817 
2818 	tp->t_rocount = tp->t_rawq.c_cc;
2819 	tp->t_rocol = 0;
2820 }
2821 
2822 
2823 /*
2824  * Echo a typed character to the terminal.
2825  *
2826  * Locks:	Assumes tty_lock() is held prior to calling.
2827  */
2828 static void
ttyecho(int c,struct tty * tp)2829 ttyecho(int c, struct tty *tp)
2830 {
2831 	TTY_LOCK_OWNED(tp);     /* debug assert */
2832 
2833 	if (!ISSET(tp->t_state, TS_CNTTB)) {
2834 		CLR(tp->t_lflag, FLUSHO);
2835 	}
2836 	if ((!ISSET(tp->t_lflag, ECHO) &&
2837 	    (c != '\n' || !ISSET(tp->t_lflag, ECHONL))) ||
2838 	    ISSET(tp->t_lflag, EXTPROC)) {
2839 		return;
2840 	}
2841 	if (ISSET(tp->t_lflag, ECHOCTL) &&
2842 	    ((ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n') ||
2843 	    ISSET(c, TTY_CHARMASK) == 0177)) {
2844 		(void)ttyoutput('^', tp);
2845 		CLR(c, ~TTY_CHARMASK);
2846 		if (c == 0177) {
2847 			c = '?';
2848 		} else {
2849 			c += 'A' - 1;
2850 		}
2851 	}
2852 	(void)ttyoutput(c, tp);
2853 }
2854 
2855 static void
ttwakeup_knote(struct selinfo * sip,long hint)2856 ttwakeup_knote(struct selinfo *sip, long hint)
2857 {
2858 	if ((sip->si_flags & SI_KNPOSTING) == 0) {
2859 		sip->si_flags |= SI_KNPOSTING;
2860 		KNOTE(&sip->si_note, hint);
2861 		sip->si_flags &= ~SI_KNPOSTING;
2862 	}
2863 }
2864 
2865 
2866 /*
2867  * Wake up any readers on a tty.
2868  *
2869  * Locks:	Assumes tty_lock() is held for the call.
2870  */
2871 void
ttwakeup(struct tty * tp)2872 ttwakeup(struct tty *tp)
2873 {
2874 	TTY_LOCK_OWNED(tp);     /* debug assert */
2875 
2876 	selwakeup(&tp->t_rsel);
2877 	ttwakeup_knote(&tp->t_rsel, 0);
2878 	if (ISSET(tp->t_state, TS_ASYNC)) {
2879 		/*
2880 		 * XXX: Callers may not revalidate it the tty is closed
2881 		 * XXX: out from under them by another thread, but we do
2882 		 * XXX: not support queued signals.  This should be safe,
2883 		 * XXX: since the process we intend to wakeup is in the
2884 		 * XXX: process group, and will wake up because of the
2885 		 * XXX: signal anyway.
2886 		 */
2887 		tty_pgsignal_locked(tp, SIGIO, 1);
2888 	}
2889 	wakeup(TSA_HUP_OR_INPUT(tp));
2890 }
2891 
2892 
2893 /*
2894  * ttwwakeup (LDISC)
2895  *
2896  * Wake up any writers on a tty.
2897  *
2898  * Locks:	Assumes tty_lock() is held prior to calling.
2899  */
2900 void
ttwwakeup(struct tty * tp)2901 ttwwakeup(struct tty *tp)
2902 {
2903 	TTY_LOCK_OWNED(tp);     /* debug assert */
2904 
2905 	if (tp->t_outq.c_cc <= tp->t_lowat) {
2906 		selwakeup(&tp->t_wsel);
2907 		ttwakeup_knote(&tp->t_wsel, 0);
2908 	}
2909 	if (ISSET(tp->t_state, TS_BUSY | TS_SO_OCOMPLETE) ==
2910 	    TS_SO_OCOMPLETE && tp->t_outq.c_cc == 0) {
2911 		CLR(tp->t_state, TS_SO_OCOMPLETE);
2912 		wakeup(TSA_OCOMPLETE(tp));
2913 	}
2914 	if (ISSET(tp->t_state, TS_SO_OLOWAT) &&
2915 	    tp->t_outq.c_cc <= tp->t_lowat) {
2916 		CLR(tp->t_state, TS_SO_OLOWAT);
2917 		wakeup(TSA_OLOWAT(tp));
2918 	}
2919 }
2920 
2921 
2922 /*
2923  * Look up a code for a specified speed in a conversion table;
2924  * used by drivers to map software speed values to hardware parameters.
2925  *
2926  * Notes:	No locks are assumed for this function; it does not
2927  *		directly access struct tty.
2928  */
2929 int
ttspeedtab(int speed,struct speedtab * table)2930 ttspeedtab(int speed, struct speedtab *table)
2931 {
2932 	for (; table->sp_speed != -1; table++) {
2933 		if (table->sp_speed == speed) {
2934 			return table->sp_code;
2935 		}
2936 	}
2937 	return -1;
2938 }
2939 
2940 
2941 /*
2942  * Set tty hi and low water marks.
2943  *
2944  * Try to arrange the dynamics so there's about one second
2945  * from hi to low water.
2946  *
2947  * Locks:	Assumes tty_lock() is held prior to calling.
2948  */
2949 void
ttsetwater(struct tty * tp)2950 ttsetwater(struct tty *tp)
2951 {
2952 	speed_t cps;
2953 	unsigned int x;
2954 
2955 	TTY_LOCK_OWNED(tp);     /* debug assert */
2956 
2957 #define CLAMP(x, h, l)  ((x) > h ? h : ((x) < l) ? l : (x))
2958 
2959 	cps = tp->t_ospeed / 10;
2960 	static_assert(TTMAXLOWAT <= UINT_MAX, "max low water fits in unsigned int");
2961 	static_assert(TTMINLOWAT <= UINT_MAX, "min low water fits in unsigned int");
2962 	tp->t_lowat = x = (unsigned int)CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
2963 	x += cps;
2964 	x = CLAMP(x, TTMAXHIWAT, TTMINHIWAT);
2965 	tp->t_hiwat = roundup(x, CBSIZE);
2966 #undef  CLAMP
2967 }
2968 
2969 /* ttyinfo has been converted to the MACH kernel */
2970 #include <mach/thread_info.h>
2971 
2972 /* XXX Should be in Mach header <kern/thread.h>, but doesn't work */
2973 extern kern_return_t    thread_info_internal(thread_t thread,
2974     thread_flavor_t flavor,
2975     thread_info_t thread_info_out,
2976     mach_msg_type_number_t *thread_info_count);
2977 
2978 
2979 /*
2980  * Report on state of foreground process group.
2981  *
2982  * Locks:	Assumes tty_lock() is held prior to calling.
2983  */
2984 void
ttyinfo_locked(struct tty * tp)2985 ttyinfo_locked(struct tty *tp)
2986 {
2987 	int             load;
2988 	uthread_t       uthread;
2989 	proc_t          p;
2990 	proc_t          pick;
2991 	pid_t pickpid;
2992 	const char      *state;
2993 	struct timeval  utime;
2994 	struct timeval  stime;
2995 	thread_basic_info_data_t        basic_info;
2996 	mach_msg_type_number_t          mmtn = THREAD_BASIC_INFO_COUNT;
2997 	struct pgrp * pg;
2998 
2999 	TTY_LOCK_OWNED(tp);     /* debug assert */
3000 
3001 	if (ttycheckoutq(tp, 0) == 0) {
3002 		return;
3003 	}
3004 
3005 	/* Print load average. */
3006 	load = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
3007 	ttyprintf(tp, "load: %d.%02d ", load / 100, load % 100);
3008 
3009 	/*
3010 	 * On return following a ttyprintf(), we set tp->t_rocount to 0 so
3011 	 * that pending input will be retyped on BS.
3012 	 */
3013 	if (tp->t_session == NULL) {
3014 		ttyprintf(tp, "not a controlling terminal\n");
3015 		tp->t_rocount = 0;
3016 		return;
3017 	}
3018 	if (tp->t_pgrp == NULL) {
3019 		ttyprintf(tp, "no foreground process group\n");
3020 		tp->t_rocount = 0;
3021 		return;
3022 	}
3023 
3024 	/* get a reference on the process group before locking it */
3025 	pg = tty_pgrp_locked(tp);
3026 
3027 	pgrp_lock(pg);
3028 	/* the proc_compare is non blocking fn, no need to use iterator */
3029 	pick = NULL;
3030 	LIST_FOREACH(p, &pg->pg_members, p_pglist) {
3031 		if (proc_compare(pick, p)) {
3032 			pick = p;
3033 			pickpid = proc_getpid(p);
3034 		} else {
3035 			pickpid = proc_getpid(pick);
3036 		}
3037 	}
3038 	pgrp_unlock(pg);
3039 	/* SAFE: All callers drop the lock on return */
3040 	tty_unlock(tp);
3041 	pgrp_rele(pg);
3042 
3043 	pick = proc_find(pickpid);
3044 	if (pick == PROC_NULL) {
3045 		tty_lock(tp);
3046 		return;
3047 	}
3048 
3049 	tty_lock(tp);
3050 	proc_lock(pick);
3051 	if (TAILQ_EMPTY(&pick->p_uthlist) ||
3052 	    (uthread = TAILQ_FIRST(&pick->p_uthlist)) == NULL ||
3053 	    (thread_info_internal(get_machthread(uthread), THREAD_BASIC_INFO, (thread_info_t)&basic_info, &mmtn) != KERN_SUCCESS)) {
3054 		proc_unlock(pick);
3055 		ttyprintf(tp, "foreground process without thread\n");
3056 		tp->t_rocount = 0;
3057 		proc_rele(pick);
3058 		return;
3059 	}
3060 	proc_unlock(pick);
3061 
3062 	switch (basic_info.run_state) {
3063 	case TH_STATE_RUNNING:
3064 		state = "running";
3065 		break;
3066 	case TH_STATE_STOPPED:
3067 		state = "stopped";
3068 		break;
3069 	case TH_STATE_WAITING:
3070 		state = "waiting";
3071 		break;
3072 	case TH_STATE_UNINTERRUPTIBLE:
3073 		state = "uninterruptible";
3074 		break;
3075 	case TH_STATE_HALTED:
3076 		state = "halted";
3077 		break;
3078 	default:
3079 		state = "unknown";
3080 		break;
3081 	}
3082 	calcru(pick, &utime, &stime, NULL);
3083 
3084 	/* Print command, pid, state, utime, and stime */
3085 	ttyprintf(tp, " cmd: %s %d %s %ld.%02du %ld.%02ds\n",
3086 	    pick->p_comm,
3087 	    proc_getpid(pick),
3088 	    state,
3089 	    (long)utime.tv_sec, utime.tv_usec / 10000,
3090 	    (long)stime.tv_sec, stime.tv_usec / 10000);
3091 
3092 	proc_rele(pick);
3093 	tp->t_rocount = 0;
3094 }
3095 
3096 
3097 /*
3098  * Returns 1 if p2 is "better" than p1
3099  *
3100  * The algorithm for picking the "interesting" process is thus:
3101  *
3102  *	1) Only foreground processes are eligible - implied.
3103  *	2) Runnable processes are favored over anything else.  The runner
3104  *	   with the highest cpu utilization is picked (p_estcpu).  Ties are
3105  *	   broken by picking the highest pid.
3106  *	3) The sleeper with the shortest sleep time is next.
3107  *	4) Further ties are broken by picking the highest pid.
3108  */
3109 #define ISRUN(p)        (((p)->p_stat == SRUN) || ((p)->p_stat == SIDL))
3110 #define TESTAB(a, b)    ((a)<<1 | (b))
3111 #define ONLYA   2
3112 #define ONLYB   1
3113 #define BOTH    3
3114 
3115 /*
3116  * Locks:	pgrp_lock(p2) held on call to this function
3117  *		tty_lock(tp) for p2's tty, for which p2 is the foreground
3118  *			process, held on call to this function
3119  */
3120 static int
proc_compare(proc_t p1,proc_t p2)3121 proc_compare(proc_t p1, proc_t p2)
3122 {
3123 	/* NOTE THIS FN needs to be NON BLOCKING */
3124 
3125 	if (p1 == NULL) {
3126 		return 1;
3127 	}
3128 	/*
3129 	 * see if at least one of them is runnable
3130 	 */
3131 	switch (TESTAB(ISRUN(p1), ISRUN(p2))) {
3132 	case ONLYA:
3133 		return 0;
3134 	case ONLYB:
3135 		return 1;
3136 	case BOTH:
3137 		/*
3138 		 * tie - favor one with highest recent cpu utilization
3139 		 */
3140 #ifdef _PROC_HAS_SCHEDINFO_
3141 		/* Without the support the fields are always zero */
3142 		if (p2->p_estcpu > p1->p_estcpu) {
3143 			return 1;
3144 		}
3145 		if (p1->p_estcpu > p2->p_estcpu) {
3146 			return 0;
3147 		}
3148 #endif /* _PROC_HAS_SCHEDINFO_ */
3149 		return proc_getpid(p2) > proc_getpid(p1); /* tie - return highest pid */
3150 	}
3151 	/*
3152 	 * weed out zombies
3153 	 */
3154 	switch (TESTAB(p1->p_stat == SZOMB, p2->p_stat == SZOMB)) {
3155 	case ONLYA:
3156 		return 1;
3157 	case ONLYB:
3158 		return 0;
3159 	case BOTH:
3160 		return proc_getpid(p2) > proc_getpid(p1); /* tie - return highest pid */
3161 	}
3162 	/*
3163 	 * pick the one with the smallest sleep time
3164 	 */
3165 #ifdef _PROC_HAS_SCHEDINFO_
3166 	/* Without the support the fields are always zero */
3167 	if (p2->p_slptime > p1->p_slptime) {
3168 		return 0;
3169 	}
3170 	if (p1->p_slptime > p2->p_slptime) {
3171 		return 1;
3172 	}
3173 #endif /* _PROC_HAS_SCHEDINFO_ */
3174 	return proc_getpid(p2) > proc_getpid(p1);         /* tie - return highest pid */
3175 }
3176 
3177 
3178 /*
3179  * Output char to tty; console putchar style.
3180  *
3181  * Locks:	Assumes tty_lock() is held prior to calling.
3182  *
3183  * Notes:	Only ever called from putchar() in subr_prf.c
3184  */
3185 int
tputchar(int c,struct tty * tp)3186 tputchar(int c, struct tty *tp)
3187 {
3188 	TTY_LOCK_OWNED(tp);     /* debug assert */
3189 
3190 	if (!ISSET(tp->t_state, TS_CONNECTED)) {
3191 		return -1;
3192 	}
3193 	if (c == '\n') {
3194 		(void)ttyoutput('\r', tp);
3195 	}
3196 	(void)ttyoutput(c, tp);
3197 	ttstart(tp);
3198 	return 0;
3199 }
3200 
3201 
3202 /*
3203  * ttysleep
3204  *
3205  * Sleep on a wait channel waiting for an interrupt or a condition to come
3206  * true so that we are woken up.
3207  *
3208  * Parameters:	tp			Tty going to sleep
3209  *		chan			The sleep channel (usually an address
3210  *					of a structure member)
3211  *		pri			priority and flags
3212  *		wmesg			Wait message; shows up in debugger,
3213  *					should show up in "ps", but doesn't
3214  *		timo			Timeout for the sleep
3215  *
3216  * Returns:	0			Condition came true
3217  *		ERESTART		Upper layer must redrive the call;
3218  *					this is usually done by the Libc
3219  *					stub in user space
3220  *	msleep0:EINTR			Interrupted (usually a signal)
3221  *	msleep0:ERESTART		Interrupted (usually a masked signal)
3222  *	msleep0:EWOULDBLOCK		Timeout (timo) already expired
3223  *
3224  * Locks:	Assumes tty_lock() is held prior to calling.
3225  *
3226  * Sleep on chan, returning ERESTART if tty changed while we napped and
3227  * returning any errors (e.g. EINTR/EWOULDBLOCK) reported by msleep0.  If
3228  * the tty is revoked, restarting a pending call will redo validation done
3229  * at the start of the call.
3230  */
3231 int
ttysleep(struct tty * tp,void * chan,int pri,const char * wmesg,int timo)3232 ttysleep(struct tty *tp, void *chan, int pri, const char *wmesg, int timo)
3233 {
3234 	int error;
3235 	int gen;
3236 
3237 	TTY_LOCK_OWNED(tp);
3238 
3239 	if (tp->t_state & TS_REVOKE) {
3240 		return ERESTART;
3241 	}
3242 
3243 	gen = tp->t_gen;
3244 	/* Use of msleep0() avoids conversion timo/timespec/timo */
3245 	error = msleep0(chan, &tp->t_lock, pri, wmesg, timo, (int (*)(int))0);
3246 	if (error) {
3247 		return error;
3248 	}
3249 	return tp->t_gen == gen ? 0 : ERESTART;
3250 }
3251 
3252 
3253 /*
3254  * Allocate a tty structure and its associated buffers.
3255  *
3256  * Parameters:	void
3257  *
3258  * Returns:	!NULL				Address of new struct tty
3259  *		NULL				Error ("ENOMEM")
3260  *
3261  * Locks:	The tty_lock() of the returned tty is not held when it
3262  *		is returned.
3263  */
3264 struct tty *
ttymalloc(void)3265 ttymalloc(void)
3266 {
3267 	struct tty *tp;
3268 
3269 	tp = kalloc_type(struct tty, Z_WAITOK | Z_ZERO | Z_NOFAIL);
3270 	/* XXX: default to TTYCLSIZE(1024) chars for now */
3271 	clalloc(&tp->t_rawq, TTYCLSIZE, 1);
3272 	clalloc(&tp->t_canq, TTYCLSIZE, 1);
3273 	/* output queue doesn't need quoting */
3274 	clalloc(&tp->t_outq, TTYCLSIZE, 0);
3275 	lck_mtx_init(&tp->t_lock, &tty_lck_grp, LCK_ATTR_NULL);
3276 	klist_init(&tp->t_rsel.si_note);
3277 	klist_init(&tp->t_wsel.si_note);
3278 	os_ref_init_raw(&tp->t_refcnt, &t_refgrp);
3279 	return tp;
3280 }
3281 
3282 /*
3283  * Increment the reference count on a tty.
3284  */
3285 void
ttyhold(struct tty * tp)3286 ttyhold(struct tty *tp)
3287 {
3288 	assert(tp != NULL);
3289 	os_ref_retain_raw(&tp->t_refcnt, &t_refgrp);
3290 }
3291 
3292 /*
3293  * Drops a reference count on a tty structure; if the reference count reaches
3294  * zero, then also frees the structure and associated buffers.
3295  */
3296 void
ttyfree(struct tty * tp)3297 ttyfree(struct tty *tp)
3298 {
3299 	assert(tp != NULL);
3300 	TTY_LOCK_NOTOWNED(tp);
3301 
3302 	if (os_ref_release_raw(&tp->t_refcnt, &t_refgrp) == 0) {
3303 		ttydeallocate(tp);
3304 	}
3305 }
3306 
3307 /*
3308  * Drops a reference count on a tty structure while holding the tty lock.
3309  * Panics if the last reference is dropped.
3310  */
3311 void
ttyfree_locked(struct tty * tp)3312 ttyfree_locked(struct tty *tp)
3313 {
3314 	assert(tp != NULL);
3315 	TTY_LOCK_OWNED(tp);
3316 	os_ref_release_live_raw(&tp->t_refcnt, &t_refgrp);
3317 }
3318 
3319 /*
3320  * Deallocate a tty structure and its buffers.
3321  *
3322  * Locks:	The tty_lock() is assumed to not be held at the time of
3323  *		the free; this function destroys the mutex.
3324  */
3325 static void
ttydeallocate(struct tty * tp)3326 ttydeallocate(struct tty *tp)
3327 {
3328 	TTY_LOCK_NOTOWNED(tp);  /* debug assert */
3329 
3330 #if DEBUG
3331 	if (!(SLIST_EMPTY(&tp->t_rsel.si_note) && SLIST_EMPTY(&tp->t_wsel.si_note))) {
3332 		panic("knotes hooked into a tty when the tty is freed.");
3333 	}
3334 #endif /* DEBUG */
3335 
3336 	clfree(&tp->t_rawq);
3337 	clfree(&tp->t_canq);
3338 	clfree(&tp->t_outq);
3339 	lck_mtx_destroy(&tp->t_lock, &tty_lck_grp);
3340 	kfree_type(struct tty, tp);
3341 }
3342 
3343 
3344 /*
3345  * Locks:	Assumes tty_lock() is held prior to calling.
3346  */
3347 static bool
isbackground(proc_t p,struct tty * tp)3348 isbackground(proc_t p, struct tty *tp)
3349 {
3350 	TTY_LOCK_OWNED(tp);
3351 
3352 	if (tp->t_pgrp == NULL ||
3353 	    (uintptr_t)tp->t_pgrp == smr_unsafe_load(&p->p_pgrp)) {
3354 		return false;
3355 	}
3356 
3357 	if (tp->t_session == SESSION_NULL) {
3358 		return false;
3359 	}
3360 
3361 	/*
3362 	 * same as isctty_sp(p, tp, p->p_pgrp->pg_session)
3363 	 * without dereferencing p->p_pgrp
3364 	 */
3365 	return tp->t_session->s_sid == proc_sessionid(p) && (p->p_flag & P_CONTROLT);
3366 }
3367 
3368 static bool
isctty(proc_t p,struct tty * tp)3369 isctty(proc_t p, struct tty  *tp)
3370 {
3371 	struct session *sessp;
3372 	struct pgrp *pg;
3373 	bool retval = false;
3374 
3375 	pg = proc_pgrp(p, &sessp);
3376 	retval = isctty_sp(p, tp, sessp);
3377 	pgrp_rele(pg);
3378 
3379 	return retval;
3380 }
3381 
3382 static bool
isctty_sp(proc_t p,struct tty * tp,struct session * sessp)3383 isctty_sp(proc_t p, struct tty *tp, struct session *sessp)
3384 {
3385 	return sessp == tp->t_session && (p->p_flag & P_CONTROLT);
3386 }
3387 
3388 
3389 static int  filt_ttyattach(struct knote *kn, struct kevent_qos_s *kev);
3390 static void filt_ttydetach(struct knote *kn);
3391 static int  filt_ttyevent(struct knote *kn, long hint);
3392 static int  filt_ttytouch(struct knote *kn, struct kevent_qos_s *kev);
3393 static int  filt_ttyprocess(struct knote *kn, struct kevent_qos_s *kev);
3394 
3395 SECURITY_READ_ONLY_EARLY(struct filterops) tty_filtops = {
3396 	.f_isfd    = 1,
3397 	.f_attach  = filt_ttyattach,
3398 	.f_detach  = filt_ttydetach,
3399 	.f_event   = filt_ttyevent,
3400 	.f_touch   = filt_ttytouch,
3401 	.f_process = filt_ttyprocess
3402 };
3403 
3404 /*
3405  * Called with struct tty locked. Returns non-zero if there is data to be read
3406  * or written.
3407  */
3408 static int
filt_tty_common(struct knote * kn,struct kevent_qos_s * kev,struct tty * tp)3409 filt_tty_common(struct knote *kn, struct kevent_qos_s *kev, struct tty *tp)
3410 {
3411 	int retval = 0;
3412 	int64_t data = 0;
3413 
3414 	TTY_LOCK_OWNED(tp); /* debug assert */
3415 
3416 	switch (kn->kn_filter) {
3417 	case EVFILT_READ:
3418 		/*
3419 		 * ttnread can change the tty state,
3420 		 * hence must be done upfront, before any other check.
3421 		 */
3422 		data = ttnread(tp);
3423 		retval = (data != 0);
3424 		break;
3425 	case EVFILT_WRITE:
3426 		if ((tp->t_outq.c_cc <= tp->t_lowat) &&
3427 		    (tp->t_state & TS_CONNECTED)) {
3428 			data = tp->t_hiwat - tp->t_outq.c_cc;
3429 			retval = (data != 0);
3430 		}
3431 		break;
3432 	default:
3433 		panic("tty kevent: unexpected filter: %d, kn = %p, tty = %p",
3434 		    kn->kn_filter, kn, tp);
3435 		break;
3436 	}
3437 
3438 	/*
3439 	 * TODO(mwidmann, jandrus): For native knote low watermark support,
3440 	 * check the kn_sfflags for NOTE_LOWAT and check against kn_sdata.
3441 	 *
3442 	 * res = ((kn->kn_sfflags & NOTE_LOWAT) != 0) ?
3443 	 *        (kn->kn_data >= kn->kn_sdata) : kn->kn_data;
3444 	 */
3445 
3446 	if (tp->t_state & TS_ZOMBIE) {
3447 		kn->kn_flags |= EV_EOF;
3448 	}
3449 	if (kn->kn_flags & EV_EOF) {
3450 		retval = 1;
3451 	}
3452 	if (retval && kev) {
3453 		knote_fill_kevent(kn, kev, data);
3454 	}
3455 
3456 	return retval;
3457 }
3458 
3459 /*
3460  * Find the struct tty from a waitq, which is a member of one of the two struct
3461  * selinfos inside the struct tty.  Use the seltype to determine which selinfo.
3462  */
3463 static struct tty *
tty_from_waitq(struct waitq * wq,int seltype)3464 tty_from_waitq(struct waitq *wq, int seltype)
3465 {
3466 	/*
3467 	 * The waitq is part of the selinfo structure managed by the driver.
3468 	 * For certain drivers, we want to hook the knote into the selinfo
3469 	 * structure's si_note field so selwakeup can call KNOTE.
3470 	 *
3471 	 * For TTY drivers, the selinfo structure is somewhere in the struct
3472 	 * tty. There are two different selinfo structures, and the one used
3473 	 * corresponds to the type of filter requested.
3474 	 */
3475 	switch (seltype) {
3476 	case FREAD:
3477 		return __container_of(wq, struct tty, t_rsel.si_waitq);
3478 	case FWRITE:
3479 		return __container_of(wq, struct tty, t_wsel.si_waitq);
3480 	default:
3481 		return NULL;
3482 	}
3483 }
3484 
3485 static struct tty *
tty_from_knote(struct knote * kn)3486 tty_from_knote(struct knote *kn)
3487 {
3488 	return (struct tty *)knote_kn_hook_get_raw(kn);
3489 }
3490 
3491 static int
filt_ttyattach(struct knote * kn,__unused struct kevent_qos_s * kev)3492 filt_ttyattach(struct knote *kn, __unused struct kevent_qos_s *kev)
3493 {
3494 	uthread_t uth = current_uthread();
3495 	vfs_context_t ctx = vfs_context_current();
3496 	vnode_t vp = (vnode_t)fp_get_data(kn->kn_fp);
3497 	struct select_set *old_wqs;
3498 	int selres;
3499 
3500 	/*
3501 	 * This function should be called from spec_kqfilter (spec_vnops.c),
3502 	 * so most of the knote data structure should already be initialized.
3503 	 */
3504 
3505 	/* don't support offsets in ttys or drivers that don't use struct tty */
3506 	if (kn->kn_vnode_use_ofst || !kn->kn_vnode_kqok) {
3507 		knote_set_error(kn, ENOTSUP);
3508 		return 0;
3509 	}
3510 
3511 	/*
3512 	 * Connect the struct tty to the knote through the selinfo structure
3513 	 * referenced by the waitq within the selinfo.
3514 	 *
3515 	 * FMARK forces selects to always call selrecord, even if data is
3516 	 * available.  See ttselect, ptsselect, ptcselect.
3517 	 *
3518 	 * selres also contains the data currently available in the tty.
3519 	 */
3520 	selspec_record_hook_t block = ^(struct selinfo *si){
3521 		struct tty *tp;
3522 
3523 		tp = tty_from_waitq(&si->si_waitq, knote_get_seltype(kn));
3524 		TTY_LOCK_OWNED(tp);
3525 
3526 		/* Attach the knote to selinfo's klist and take a ref */
3527 		ttyhold(tp);
3528 		knote_kn_hook_set_raw(kn, tp);
3529 		KNOTE_ATTACH(&si->si_note, kn);
3530 	};
3531 
3532 	old_wqs = uth->uu_selset;
3533 	uth->uu_selset = SELSPEC_RECORD_MARKER;
3534 	selres = VNOP_SELECT(vp, knote_get_seltype(kn) | FMARK, 0, block, ctx);
3535 	uth->uu_selset = old_wqs;
3536 
3537 	if (knote_kn_hook_get_raw(kn) == NULL) {
3538 		/*
3539 		 * The driver didn't call selrecord --
3540 		 * there's no tty hooked up so we can't attach.
3541 		 */
3542 		knote_set_error(kn, ENOTTY);
3543 		return 0;
3544 	}
3545 
3546 	return selres;
3547 }
3548 
3549 static void
filt_ttydetach(struct knote * kn)3550 filt_ttydetach(struct knote *kn)
3551 {
3552 	struct tty *tp = tty_from_knote(kn);
3553 
3554 	tty_lock(tp);
3555 
3556 	if (!KNOTE_IS_AUTODETACHED(kn)) {
3557 		switch (kn->kn_filter) {
3558 		case EVFILT_READ:
3559 			KNOTE_DETACH(&tp->t_rsel.si_note, kn);
3560 			break;
3561 		case EVFILT_WRITE:
3562 			KNOTE_DETACH(&tp->t_wsel.si_note, kn);
3563 			break;
3564 		default:
3565 			panic("invalid knote %p detach, filter: %d", kn, kn->kn_filter);
3566 			break;
3567 		}
3568 	}
3569 
3570 	// Remove dangling reference
3571 	knote_kn_hook_set_raw(kn, NULL);
3572 
3573 	tty_unlock(tp);
3574 	ttyfree(tp);
3575 }
3576 
3577 static int
filt_ttyevent(struct knote * kn,long hint)3578 filt_ttyevent(struct knote *kn, long hint)
3579 {
3580 	struct tty *tp = tty_from_knote(kn);
3581 	int ret;
3582 
3583 	TTY_LOCK_OWNED(tp);
3584 
3585 	if (hint & NOTE_REVOKE) {
3586 		kn->kn_flags |= EV_EOF | EV_ONESHOT;
3587 		ret = 1;
3588 	} else {
3589 		ret = filt_tty_common(kn, NULL, tp);
3590 	}
3591 
3592 	return ret;
3593 }
3594 
3595 static int
filt_ttytouch(struct knote * kn,struct kevent_qos_s * kev)3596 filt_ttytouch(struct knote *kn, struct kevent_qos_s *kev)
3597 {
3598 	struct tty *tp = tty_from_knote(kn);
3599 	int res = 0;
3600 
3601 	tty_lock(tp);
3602 
3603 	kn->kn_sdata = kev->data;
3604 	kn->kn_sfflags = kev->fflags;
3605 
3606 	if (kn->kn_vnode_kqok) {
3607 		res = filt_tty_common(kn, NULL, tp);
3608 	}
3609 
3610 	tty_unlock(tp);
3611 
3612 	return res;
3613 }
3614 
3615 static int
filt_ttyprocess(struct knote * kn,struct kevent_qos_s * kev)3616 filt_ttyprocess(struct knote *kn, struct kevent_qos_s *kev)
3617 {
3618 	struct tty *tp = tty_from_knote(kn);
3619 	int res;
3620 
3621 	tty_lock(tp);
3622 
3623 	res = filt_tty_common(kn, kev, tp);
3624 
3625 	tty_unlock(tp);
3626 
3627 	return res;
3628 }
3629