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