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