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