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