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