2 * Copyright (c) 1982, 1986, 1990, 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
10 * Copyright (c) 2002 Networks Associates Technologies, Inc.
11 * All rights reserved.
13 * Portions of this software were developed for the FreeBSD Project by
14 * ThinkSec AS and NAI Labs, the Security Research Division of Network
15 * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035
16 * ("CBOSS"), as part of the DARPA CHATS research program.
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions
21 * 1. Redistributions of source code must retain the above copyright
22 * notice, this list of conditions and the following disclaimer.
23 * 2. Redistributions in binary form must reproduce the above copyright
24 * notice, this list of conditions and the following disclaimer in the
25 * documentation and/or other materials provided with the distribution.
26 * 4. Neither the name of the University nor the names of its contributors
27 * may be used to endorse or promote products derived from this software
28 * without specific prior written permission.
30 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
42 * @(#)tty.c 8.8 (Berkeley) 1/21/94
47 * o Fix races for sending the start char in ttyflush().
48 * o Handle inter-byte timeout for "MIN > 0, TIME > 0" in ttyselect().
49 * With luck, there will be MIN chars before select() returns().
50 * o Handle CLOCAL consistently for ptys. Perhaps disallow setting it.
51 * o Don't allow input in TS_ZOMBIE case. It would be visible through
53 * o Do the new sio locking stuff here and use it to avoid special
56 * o Move EXTPROC and/or PENDIN to t_state?
57 * o Wrap most of ttioctl in spltty/splx.
58 * o Implement TIOCNOTTY or remove it from <sys/ioctl.h>.
59 * o Send STOP if IXOFF is toggled off while TS_TBLOCK is set.
60 * o Don't allow certain termios flags to affect disciplines other
61 * than TTYDISC. Cancel their effects before switch disciplines
62 * and ignore them if they are set while we are in another
64 * o Now that historical speed conversions are handled here, don't
66 * o Check for TS_CARR_ON being set while everything is closed and not
67 * waiting for carrier. TS_CARR_ON isn't cleared if nothing is open,
68 * so it would live until the next open even if carrier drops.
69 * o Restore TS_WOPEN since it is useful in pstat. It must be cleared
70 * only when _all_ openers leave open().
73 #include <sys/cdefs.h>
74 __FBSDID("$FreeBSD$");
76 #include "opt_compat.h"
79 #include <sys/param.h>
80 #include <sys/systm.h>
81 #include <sys/filio.h>
83 #include <sys/mutex.h>
84 #include <sys/namei.h>
86 #if defined(COMPAT_43TTY)
87 #include <sys/ioctl_compat.h>
94 #include <sys/fcntl.h>
97 #include <sys/kernel.h>
98 #include <sys/vnode.h>
99 #include <sys/serial.h>
100 #include <sys/signalvar.h>
101 #include <sys/resourcevar.h>
102 #include <sys/malloc.h>
103 #include <sys/filedesc.h>
104 #include <sys/sched.h>
105 #include <sys/sysctl.h>
106 #include <sys/timepps.h>
108 #include <machine/stdarg.h>
112 #include <vm/vm_map.h>
114 MALLOC_DEFINE(M_TTYS, "ttys", "tty data structures");
121 static d_open_t ttysopen;
122 static d_close_t ttysclose;
123 static d_read_t ttysrdwr;
124 static d_ioctl_t ttysioctl;
125 static d_purge_t ttypurge;
127 /* Default cdevsw for common tty devices */
128 static struct cdevsw tty_cdevsw = {
129 .d_version = D_VERSION,
135 .d_flags = D_TTY | D_NEEDGIANT,
138 /* Cdevsw for slave tty devices */
139 static struct cdevsw ttys_cdevsw = {
140 .d_version = D_VERSION,
142 .d_close = ttysclose,
145 .d_ioctl = ttysioctl,
147 .d_flags = D_TTY | D_NEEDGIANT,
150 static int proc_sum(struct proc *, int *);
151 static int proc_compare(struct proc *, struct proc *);
152 static int thread_compare(struct thread *, struct thread *);
153 static int ttnread(struct tty *tp);
154 static void ttyecho(int c, struct tty *tp);
155 static int ttyoutput(int c, struct tty *tp);
156 static void ttypend(struct tty *tp);
157 static void ttyretype(struct tty *tp);
158 static void ttyrub(int c, struct tty *tp);
159 static void ttyrubo(struct tty *tp, int cnt);
160 static void ttyunblock(struct tty *tp);
161 static int ttywflush(struct tty *tp);
162 static int filt_ttyread(struct knote *kn, long hint);
163 static void filt_ttyrdetach(struct knote *kn);
164 static int filt_ttywrite(struct knote *kn, long hint);
165 static void filt_ttywdetach(struct knote *kn);
168 * Table with character classes and parity. The 8th bit indicates parity,
169 * the 7th bit indicates the character is an alphameric or underscore (for
170 * ALTWERASE), and the low 6 bits indicate delay type. If the low 6 bits
171 * are 0 then the character needs no special processing on output; classes
172 * other than 0 might be translated or (not currently) require delays.
174 #define E 0x00 /* Even parity. */
175 #define O 0x80 /* Odd parity. */
176 #define PARITY(c) (char_type[c] & O)
178 #define ALPHA 0x40 /* Alpha or underscore. */
179 #define ISALPHA(c) (char_type[(c) & TTY_CHARMASK] & ALPHA)
181 #define CCLASSMASK 0x3f
182 #define CCLASS(c) (char_type[c] & CCLASSMASK)
187 #define NA ORDINARY | ALPHA
193 static u_char const char_type[] = {
194 E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC, /* nul - bel */
195 O|BS, E|TB, E|NL, O|CC, E|VT, O|CR, O|CC, E|CC, /* bs - si */
196 O|CC, E|CC, E|CC, O|CC, E|CC, O|CC, O|CC, E|CC, /* dle - etb */
197 E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC, /* can - us */
198 O|NO, E|NO, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* sp - ' */
199 E|NO, O|NO, O|NO, E|NO, O|NO, E|NO, E|NO, O|NO, /* ( - / */
200 E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* 0 - 7 */
201 O|NA, E|NA, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* 8 - ? */
202 O|NO, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* @ - G */
203 E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* H - O */
204 E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* P - W */
205 O|NA, E|NA, E|NA, O|NO, E|NO, O|NO, O|NO, O|NA, /* X - _ */
206 E|NO, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* ` - g */
207 O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* h - o */
208 O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* p - w */
209 E|NA, O|NA, O|NA, E|NO, O|NO, E|NO, E|NO, O|CC, /* x - del */
211 * Meta chars; should be settable per character set;
212 * for now, treat them all as normal characters.
214 NA, NA, NA, NA, NA, NA, NA, NA,
215 NA, NA, NA, NA, NA, NA, NA, NA,
216 NA, NA, NA, NA, NA, NA, NA, NA,
217 NA, NA, NA, NA, NA, NA, NA, NA,
218 NA, NA, NA, NA, NA, NA, NA, NA,
219 NA, NA, NA, NA, NA, NA, NA, NA,
220 NA, NA, NA, NA, NA, NA, NA, NA,
221 NA, NA, NA, NA, NA, NA, NA, NA,
222 NA, NA, NA, NA, NA, NA, NA, NA,
223 NA, NA, NA, NA, NA, NA, NA, NA,
224 NA, NA, NA, NA, NA, NA, NA, NA,
225 NA, NA, NA, NA, NA, NA, NA, NA,
226 NA, NA, NA, NA, NA, NA, NA, NA,
227 NA, NA, NA, NA, NA, NA, NA, NA,
228 NA, NA, NA, NA, NA, NA, NA, NA,
229 NA, NA, NA, NA, NA, NA, NA, NA,
240 /* Macros to clear/set/test flags. */
241 #define SET(t, f) (t) |= (f)
242 #define CLR(t, f) (t) &= ~(f)
243 #define ISSET(t, f) ((t) & (f))
245 #undef MAX_INPUT /* XXX wrong in <sys/syslimits.h> */
246 #define MAX_INPUT TTYHOG /* XXX limit is usually larger for !ICANON */
249 * list of struct tty where pstat(8) can pick it up with sysctl
251 * The lock order is to grab the list mutex before the tty mutex.
252 * Together with additions going on the tail of the list, this allows
253 * the sysctl to avoid doing retries.
255 static TAILQ_HEAD(, tty) tty_list = TAILQ_HEAD_INITIALIZER(tty_list);
256 static struct mtx tty_list_mutex;
257 MTX_SYSINIT(tty_list, &tty_list_mutex, "ttylist", MTX_DEF);
259 static struct unrhdr *tty_unit;
261 static int drainwait = 5*60;
262 SYSCTL_INT(_kern, OID_AUTO, drainwait, CTLFLAG_RW, &drainwait,
263 0, "Output drain timeout in seconds");
266 tty_gettp(struct cdev *dev)
271 csw = dev_refthread(dev);
272 KASSERT(csw != NULL, ("No cdevsw in ttycode (%s)", devtoname(dev)));
273 KASSERT(csw->d_flags & D_TTY,
274 ("non D_TTY (%s) in tty code", devtoname(dev)));
278 ("no tty pointer on (%s) in tty code", devtoname(dev)));
283 * Initial open of tty, or (re)entry to standard tty line discipline.
286 tty_open(struct cdev *device, struct tty *tp)
293 if (!ISSET(tp->t_state, TS_ISOPEN)) {
295 SET(tp->t_state, TS_ISOPEN);
296 if (ISSET(tp->t_cflag, CLOCAL))
297 SET(tp->t_state, TS_CONNECTED);
298 bzero(&tp->t_winsize, sizeof(tp->t_winsize));
300 /* XXX don't hang forever on output */
301 if (tp->t_timeout < 0)
302 tp->t_timeout = drainwait*hz;
309 * Handle close() on a tty line: flush and set to initial state,
310 * bumping generation number so that pending read/write calls
311 * can detect recycling of the tty.
312 * XXX our caller should have done `spltty(); l_close(); tty_close();'
313 * and l_close() should have flushed, but we repeat the spltty() and
314 * the flush in case there are buggy callers.
317 tty_close(struct tty *tp)
321 funsetown(&tp->t_sigio);
326 ttyflush(tp, FREAD | FWRITE);
327 clist_free_cblocks(&tp->t_canq);
328 clist_free_cblocks(&tp->t_outq);
329 clist_free_cblocks(&tp->t_rawq);
332 tp->t_line = TTYDISC;
335 tp->t_session = NULL;
336 ostate = tp->t_state;
338 knlist_clear(&tp->t_rsel.si_note, 0);
339 knlist_clear(&tp->t_wsel.si_note, 0);
341 * Both final close and revocation close might end up calling
342 * this method. Only the thread clearing TS_ISOPEN should
343 * release the reference to the tty.
345 if (ISSET(ostate, TS_ISOPEN))
351 #define FLUSHQ(q) { \
353 ndflush(q, (q)->c_cc); \
356 /* Is 'c' a line delimiter ("break" character)? */
357 #define TTBREAKC(c, lflag) \
358 ((c) == '\n' || (((c) == cc[VEOF] || \
359 (c) == cc[VEOL] || ((c) == cc[VEOL2] && lflag & IEXTEN)) && \
360 (c) != _POSIX_VDISABLE))
363 * Process input of a single character received on a tty.
366 ttyinput(int c, struct tty *tp)
368 tcflag_t iflag, lflag;
373 * If input is pending take it first.
376 if (ISSET(lflag, PENDIN))
381 if (ISSET(lflag, ICANON)) {
391 * Block further input iff:
392 * current input > threshold AND input is available to user program
393 * AND input flow control is enabled and not yet invoked.
394 * The 3 is slop for PARMRK.
397 if (tp->t_rawq.c_cc + tp->t_canq.c_cc > tp->t_ihiwat - 3 &&
398 (!ISSET(lflag, ICANON) || tp->t_canq.c_cc != 0) &&
399 (ISSET(tp->t_cflag, CRTS_IFLOW) || ISSET(iflag, IXOFF)) &&
400 !ISSET(tp->t_state, TS_TBLOCK))
403 /* Handle exceptional conditions (break, parity, framing). */
405 err = (ISSET(c, TTY_ERRORMASK));
407 CLR(c, TTY_ERRORMASK);
408 if (ISSET(err, TTY_BI)) {
409 if (ISSET(iflag, IGNBRK))
411 if (ISSET(iflag, BRKINT)) {
412 ttyflush(tp, FREAD | FWRITE);
413 if (tp->t_pgrp != NULL) {
414 PGRP_LOCK(tp->t_pgrp);
415 pgsignal(tp->t_pgrp, SIGINT, 1);
416 PGRP_UNLOCK(tp->t_pgrp);
420 if (ISSET(iflag, PARMRK))
422 } else if ((ISSET(err, TTY_PE) && ISSET(iflag, INPCK))
423 || ISSET(err, TTY_FE)) {
424 if (ISSET(iflag, IGNPAR))
426 else if (ISSET(iflag, PARMRK)) {
428 if (tp->t_rawq.c_cc + tp->t_canq.c_cc >
431 (void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
432 (void)putc(0 | TTY_QUOTE, &tp->t_rawq);
433 (void)putc(c | TTY_QUOTE, &tp->t_rawq);
440 if (!ISSET(tp->t_state, TS_TYPEN) && ISSET(iflag, ISTRIP))
442 if (!ISSET(lflag, EXTPROC)) {
444 * Check for literal nexting very first
446 if (ISSET(tp->t_state, TS_LNCH)) {
448 CLR(tp->t_state, TS_LNCH);
451 * Scan for special characters. This code
452 * is really just a big case statement with
453 * non-constant cases. The bottom of the
454 * case statement is labeled ``endcase'', so goto
455 * it after a case match, or similar.
459 * Control chars which aren't controlled
460 * by ICANON, ISIG, or IXON.
462 if (ISSET(lflag, IEXTEN)) {
463 if (CCEQ(cc[VLNEXT], c)) {
464 if (ISSET(lflag, ECHO)) {
465 if (ISSET(lflag, ECHOE)) {
466 (void)ttyoutput('^', tp);
467 (void)ttyoutput('\b', tp);
471 SET(tp->t_state, TS_LNCH);
474 if (CCEQ(cc[VDISCARD], c)) {
475 if (ISSET(lflag, FLUSHO))
476 CLR(tp->t_lflag, FLUSHO);
478 ttyflush(tp, FWRITE);
480 if (tp->t_rawq.c_cc + tp->t_canq.c_cc)
482 SET(tp->t_lflag, FLUSHO);
490 if (ISSET(lflag, ISIG)) {
491 if (CCEQ(cc[VINTR], c) || CCEQ(cc[VQUIT], c)) {
492 if (!ISSET(lflag, NOFLSH))
493 ttyflush(tp, FREAD | FWRITE);
495 if (tp->t_pgrp != NULL) {
496 PGRP_LOCK(tp->t_pgrp);
498 CCEQ(cc[VINTR], c) ? SIGINT : SIGQUIT, 1);
499 PGRP_UNLOCK(tp->t_pgrp);
503 if (CCEQ(cc[VSUSP], c)) {
504 if (!ISSET(lflag, NOFLSH))
507 if (tp->t_pgrp != NULL) {
508 PGRP_LOCK(tp->t_pgrp);
509 pgsignal(tp->t_pgrp, SIGTSTP, 1);
510 PGRP_UNLOCK(tp->t_pgrp);
516 * Handle start/stop characters.
518 if (ISSET(iflag, IXON)) {
519 if (CCEQ(cc[VSTOP], c)) {
520 if (!ISSET(tp->t_state, TS_TTSTOP)) {
521 SET(tp->t_state, TS_TTSTOP);
525 if (!CCEQ(cc[VSTART], c))
528 * if VSTART == VSTOP then toggle
532 if (CCEQ(cc[VSTART], c))
536 * IGNCR, ICRNL, & INLCR
539 if (ISSET(iflag, IGNCR))
541 else if (ISSET(iflag, ICRNL))
543 } else if (c == '\n' && ISSET(iflag, INLCR))
546 if (!ISSET(tp->t_lflag, EXTPROC) && ISSET(lflag, ICANON)) {
548 * From here on down canonical mode character
549 * processing takes place.
552 * erase or erase2 (^H / ^?)
554 if (CCEQ(cc[VERASE], c) || CCEQ(cc[VERASE2], c) ) {
556 ttyrub(unputc(&tp->t_rawq), tp);
562 if (CCEQ(cc[VKILL], c)) {
563 if (ISSET(lflag, ECHOKE) &&
564 tp->t_rawq.c_cc == tp->t_rocount &&
565 !ISSET(lflag, ECHOPRT))
566 while (tp->t_rawq.c_cc)
567 ttyrub(unputc(&tp->t_rawq), tp);
570 if (ISSET(lflag, ECHOK) ||
571 ISSET(lflag, ECHOKE))
576 CLR(tp->t_state, TS_LOCAL);
582 if (CCEQ(cc[VWERASE], c) && ISSET(lflag, IEXTEN)) {
588 while ((c = unputc(&tp->t_rawq)) == ' ' || c == '\t')
593 * erase last char of word and remember the
594 * next chars type (for ALTWERASE)
597 c = unputc(&tp->t_rawq);
600 if (c == ' ' || c == '\t') {
601 (void)putc(c, &tp->t_rawq);
610 c = unputc(&tp->t_rawq);
613 } while (c != ' ' && c != '\t' &&
614 (!ISSET(lflag, ALTWERASE) || ISALPHA(c) == ctype));
615 (void)putc(c, &tp->t_rawq);
621 if (CCEQ(cc[VREPRINT], c) && ISSET(lflag, IEXTEN)) {
626 * ^T - kernel info and generate SIGINFO
628 if (CCEQ(cc[VSTATUS], c) && ISSET(lflag, IEXTEN)) {
629 if (ISSET(lflag, ISIG) && tp->t_pgrp != NULL) {
630 PGRP_LOCK(tp->t_pgrp);
631 pgsignal(tp->t_pgrp, SIGINFO, 1);
632 PGRP_UNLOCK(tp->t_pgrp);
634 if (!ISSET(lflag, NOKERNINFO))
640 * Check for input buffer overflow
642 if (tp->t_rawq.c_cc + tp->t_canq.c_cc >= MAX_INPUT) {
644 if (ISSET(iflag, IMAXBEL)) {
645 if (tp->t_outq.c_cc < tp->t_ohiwat)
646 (void)ttyoutput(CTRL('g'), tp);
651 if ( c == 0377 && ISSET(iflag, PARMRK) && !ISSET(iflag, ISTRIP)
652 && ISSET(iflag, IGNBRK|IGNPAR) != (IGNBRK|IGNPAR))
653 (void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
656 * Put data char in q for user and
657 * wakeup on seeing a line delimiter.
659 if (putc(c, &tp->t_rawq) >= 0) {
660 if (!ISSET(lflag, ICANON)) {
665 if (TTBREAKC(c, lflag)) {
667 catq(&tp->t_rawq, &tp->t_canq);
669 } else if (tp->t_rocount++ == 0)
670 tp->t_rocol = tp->t_column;
671 if (ISSET(tp->t_state, TS_ERASE)) {
673 * end of prterase \.../
675 CLR(tp->t_state, TS_ERASE);
676 (void)ttyoutput('/', tp);
680 if (CCEQ(cc[VEOF], c) && ISSET(lflag, ECHO)) {
682 * Place the cursor over the '^' of the ^D.
684 i = imin(2, tp->t_column - i);
686 (void)ttyoutput('\b', tp);
693 * IXANY means allow any character to restart output.
695 if (ISSET(tp->t_state, TS_TTSTOP) &&
696 !ISSET(iflag, IXANY) && cc[VSTART] != cc[VSTOP])
699 CLR(tp->t_lflag, FLUSHO);
700 CLR(tp->t_state, TS_TTSTOP);
702 return (ttstart(tp));
706 * Output a single character on a tty, doing output processing
707 * as needed (expanding tabs, newline processing, etc.).
708 * Returns < 0 if succeeds, otherwise returns char to resend.
712 ttyoutput(int c, struct tty *tp)
718 if (!ISSET(oflag, OPOST)) {
719 if (ISSET(tp->t_lflag, FLUSHO))
721 if (putc(c, &tp->t_outq))
728 * Do tab expansion if OXTABS is set. Special case if we external
729 * processing, we don't do the tab expansion because we'll probably
730 * get it wrong. If tab expansion needs to be done, let it happen
733 CLR(c, ~TTY_CHARMASK);
735 ISSET(oflag, OXTABS) && !ISSET(tp->t_lflag, EXTPROC)) {
736 c = 8 - (tp->t_column & 7);
737 if (!ISSET(tp->t_lflag, FLUSHO)) {
738 s = spltty(); /* Don't interrupt tabs. */
739 c -= b_to_q(" ", c, &tp->t_outq);
745 return (c ? -1 : '\t');
747 if (c == CEOT && ISSET(oflag, ONOEOT))
751 * Newline translation: if ONLCR is set,
752 * translate newline into "\r\n".
754 if (c == '\n' && ISSET(tp->t_oflag, ONLCR)) {
757 if (!ISSET(tp->t_lflag, FLUSHO) && putc('\r', &tp->t_outq))
760 /* If OCRNL is set, translate "\r" into "\n". */
761 else if (c == '\r' && ISSET(tp->t_oflag, OCRNL))
763 /* If ONOCR is set, don't transmit CRs when on column 0. */
764 else if (c == '\r' && ISSET(tp->t_oflag, ONOCR) && tp->t_column == 0)
769 if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
781 if (ISSET(tp->t_oflag, ONLCR | ONLRET))
791 col = (col + 8) & ~7;
799 * Ioctls for all tty devices. Called after line-discipline specific ioctl
800 * has been called to do discipline-specific functions and/or reject any
801 * of these ioctl commands.
805 ttioctl(struct tty *tp, u_long cmd, void *data, int flag)
810 int s, error, bits, sig, sig2;
812 td = curthread; /* XXX */
815 /* If the ioctl involves modification, hang if in the background. */
839 #if defined(COMPAT_43TTY)
849 sx_slock(&proctree_lock);
851 while (isbackground(p, tp) && !(p->p_flag & P_PPWAIT) &&
852 !SIGISMEMBER(p->p_sigacts->ps_sigignore, SIGTTOU) &&
853 !SIGISMEMBER(td->td_sigmask, SIGTTOU)) {
856 if (pgrp->pg_jobc == 0) {
857 sx_sunlock(&proctree_lock);
861 sx_sunlock(&proctree_lock);
862 pgsignal(pgrp, SIGTTOU, 1);
864 error = ttysleep(tp, &lbolt, TTOPRI | PCATCH, "ttybg1",
868 sx_slock(&proctree_lock);
872 sx_sunlock(&proctree_lock);
877 if (tp->t_modem != NULL) {
880 tt_modem(tp, SER_DTR, 0);
883 tt_modem(tp, 0, SER_DTR);
887 sig = (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1;
888 sig2 = ((~bits) & (TIOCM_DTR | TIOCM_RTS)) >> 1;
889 tt_modem(tp, sig, sig2);
893 sig = (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1;
894 tt_modem(tp, sig, 0);
898 sig = (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1;
899 tt_modem(tp, 0, sig);
902 sig = tt_modem(tp, 0, 0);
903 /* See <sys/serial.h. for the "<< 1" stuff */
904 bits = TIOCM_LE + (sig << 1);
912 if (tp->t_pps != NULL) {
913 error = pps_ioctl(cmd, data, tp->t_pps);
914 if (error != ENOIOCTL)
918 switch (cmd) { /* Process the ioctl. */
919 case FIOASYNC: /* set/clear async i/o */
922 SET(tp->t_state, TS_ASYNC);
924 CLR(tp->t_state, TS_ASYNC);
927 case FIONBIO: /* set/clear non-blocking i/o */
928 break; /* XXX: delete. */
929 case FIONREAD: /* get # bytes to read */
931 *(int *)data = ttnread(tp);
937 * Policy -- Don't allow FIOSETOWN on someone else's
940 if (tp->t_session != NULL && !isctty(p, tp))
943 error = fsetown(*(int *)data, &tp->t_sigio);
948 if (tp->t_session != NULL && !isctty(p, tp))
950 *(int *)data = fgetown(&tp->t_sigio);
953 case TIOCEXCL: /* set exclusive use of tty */
955 SET(tp->t_state, TS_XCLUDE);
958 case TIOCFLUSH: { /* flush buffers */
959 int flags = *(int *)data;
962 flags = FREAD | FWRITE;
964 flags &= FREAD | FWRITE;
968 case TIOCCONS: /* become virtual console */
970 struct nameidata nid;
972 if (constty && constty != tp &&
973 ISSET(constty->t_state, TS_CONNECTED))
976 /* Ensure user can open the real console. */
977 NDINIT(&nid, LOOKUP, LOCKLEAF | FOLLOW, UIO_SYSSPACE,
979 if ((error = namei(&nid)) != 0)
981 NDFREE(&nid, NDF_ONLY_PNBUF);
982 error = VOP_ACCESS(nid.ni_vp, VREAD, td->td_ucred, td);
988 } else if (tp == constty)
991 case TIOCDRAIN: /* wait till output drained */
996 case TIOCGETA: { /* get termios struct */
997 struct termios *t = (struct termios *)data;
999 bcopy(&tp->t_termios, t, sizeof(struct termios));
1002 case TIOCGETD: /* get line discipline */
1003 *(int *)data = tp->t_line;
1005 case TIOCGWINSZ: /* get window size */
1006 *(struct winsize *)data = tp->t_winsize;
1008 case TIOCGPGRP: /* get pgrp of tty */
1011 *(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
1014 case TIOCHPCL: /* hang up on last close */
1016 SET(tp->t_cflag, HUPCL);
1021 *(int *)data = tp->t_dtr_wait * 100 / hz;
1024 /* must be root since the wait applies to following logins */
1025 error = priv_check(td, PRIV_TTY_DTRWAIT);
1028 tp->t_dtr_wait = *(int *)data * hz / 100;
1030 case TIOCNXCL: /* reset exclusive use of tty */
1032 CLR(tp->t_state, TS_XCLUDE);
1035 case TIOCOUTQ: /* output queue size */
1036 *(int *)data = tp->t_outq.c_cc;
1038 case TIOCSETA: /* set termios struct */
1039 case TIOCSETAW: /* drain output, set */
1040 case TIOCSETAF: { /* drn out, fls in, set */
1041 struct termios *t = (struct termios *)data;
1043 if (t->c_ispeed == 0)
1044 t->c_ispeed = t->c_ospeed;
1045 if (t->c_ispeed == 0)
1046 t->c_ispeed = tp->t_ospeed;
1047 if (t->c_ispeed == 0)
1050 if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
1051 error = ttywait(tp);
1056 if (cmd == TIOCSETAF)
1057 ttyflush(tp, FREAD);
1059 if (!ISSET(t->c_cflag, CIGNORE)) {
1061 * Set device hardware.
1063 error = tt_param(tp, t);
1068 if (ISSET(t->c_cflag, CLOCAL) &&
1069 !ISSET(tp->t_cflag, CLOCAL)) {
1071 * XXX disconnections would be too hard to
1072 * get rid of without this kludge. The only
1073 * way to get rid of controlling terminals
1074 * is to exit from the session leader.
1076 CLR(tp->t_state, TS_ZOMBIE);
1078 wakeup(TSA_CARR_ON(tp));
1082 if ((ISSET(tp->t_state, TS_CARR_ON) ||
1083 ISSET(t->c_cflag, CLOCAL)) &&
1084 !ISSET(tp->t_state, TS_ZOMBIE))
1085 SET(tp->t_state, TS_CONNECTED);
1087 CLR(tp->t_state, TS_CONNECTED);
1088 tp->t_cflag = t->c_cflag;
1089 tp->t_ispeed = t->c_ispeed;
1090 if (t->c_ospeed != 0)
1091 tp->t_ospeed = t->c_ospeed;
1094 if (ISSET(t->c_lflag, ICANON) != ISSET(tp->t_lflag, ICANON) &&
1096 if (ISSET(t->c_lflag, ICANON))
1097 SET(tp->t_lflag, PENDIN);
1100 * XXX we really shouldn't allow toggling
1101 * ICANON while we're in a non-termios line
1102 * discipline. Now we have to worry about
1103 * panicing for a null queue.
1105 if (tp->t_canq.c_cbreserved > 0 &&
1106 tp->t_rawq.c_cbreserved > 0) {
1107 catq(&tp->t_rawq, &tp->t_canq);
1109 * XXX the queue limits may be
1110 * different, so the old queue
1111 * swapping method no longer works.
1113 catq(&tp->t_canq, &tp->t_rawq);
1115 CLR(tp->t_lflag, PENDIN);
1119 tp->t_iflag = t->c_iflag;
1120 tp->t_oflag = t->c_oflag;
1122 * Make the EXTPROC bit read only.
1124 if (ISSET(tp->t_lflag, EXTPROC))
1125 SET(t->c_lflag, EXTPROC);
1127 CLR(t->c_lflag, EXTPROC);
1128 tp->t_lflag = t->c_lflag | ISSET(tp->t_lflag, PENDIN);
1129 if (t->c_cc[VMIN] != tp->t_cc[VMIN] ||
1130 t->c_cc[VTIME] != tp->t_cc[VTIME])
1132 bcopy(t->c_cc, tp->t_cc, sizeof(t->c_cc));
1136 case TIOCSETD: { /* set line discipline */
1137 int t = *(int *)data;
1139 if ((u_int)t >= nlinesw)
1141 if (t == tp->t_line)
1144 ttyld_close(tp, flag);
1146 /* XXX: we should use the correct cdev here */
1147 error = ttyld_open(tp, tp->t_dev);
1150 * If we fail to switch line discipline we cannot
1151 * fall back to the previous, because we can not
1152 * trust that ldisc to open successfully either.
1153 * Fall back to the default ldisc which we know
1154 * will allways succeed.
1156 tp->t_line = TTYDISC;
1157 (void)ttyld_open(tp, tp->t_dev);
1163 case TIOCSTART: /* start output, like ^Q */
1165 if (ISSET(tp->t_state, TS_TTSTOP) ||
1166 ISSET(tp->t_lflag, FLUSHO)) {
1167 CLR(tp->t_lflag, FLUSHO);
1168 CLR(tp->t_state, TS_TTSTOP);
1173 case TIOCSTI: /* simulate terminal input */
1174 if ((flag & FREAD) == 0 && priv_check(td, PRIV_TTY_STI))
1176 if (!isctty(p, tp) && priv_check(td, PRIV_TTY_STI))
1179 ttyld_rint(tp, *(u_char *)data);
1182 case TIOCSTOP: /* stop output, like ^S */
1184 if (!ISSET(tp->t_state, TS_TTSTOP)) {
1185 SET(tp->t_state, TS_TTSTOP);
1190 case TIOCSCTTY: /* become controlling tty */
1191 /* Session ctty vnode pointer set in vnode layer. */
1192 sx_slock(&proctree_lock);
1193 if (!SESS_LEADER(p) ||
1194 ((p->p_session->s_ttyvp || tp->t_session) &&
1195 (tp->t_session != p->p_session))) {
1196 sx_sunlock(&proctree_lock);
1199 tp->t_session = p->p_session;
1200 tp->t_pgrp = p->p_pgrp;
1201 SESS_LOCK(p->p_session);
1202 ttyref(tp); /* ttyrel(): kern_proc.c:pgdelete() */
1203 p->p_session->s_ttyp = tp;
1204 SESS_UNLOCK(p->p_session);
1206 p->p_flag |= P_CONTROLT;
1208 sx_sunlock(&proctree_lock);
1210 case TIOCSPGRP: { /* set pgrp of tty */
1211 sx_slock(&proctree_lock);
1212 pgrp = pgfind(*(int *)data);
1213 if (!isctty(p, tp)) {
1216 sx_sunlock(&proctree_lock);
1220 sx_sunlock(&proctree_lock);
1224 if (pgrp->pg_session != p->p_session) {
1225 sx_sunlock(&proctree_lock);
1228 sx_sunlock(&proctree_lock);
1232 case TIOCSTAT: /* simulate control-T */
1237 case TIOCSWINSZ: /* set window size */
1238 if (bcmp((caddr_t)&tp->t_winsize, data,
1239 sizeof (struct winsize))) {
1240 tp->t_winsize = *(struct winsize *)data;
1241 if (tp->t_pgrp != NULL) {
1242 PGRP_LOCK(tp->t_pgrp);
1243 pgsignal(tp->t_pgrp, SIGWINCH, 1);
1244 PGRP_UNLOCK(tp->t_pgrp);
1248 case TIOCSDRAINWAIT:
1249 error = priv_check(td, PRIV_TTY_DRAINWAIT);
1252 tp->t_timeout = *(int *)data * hz;
1253 wakeup(TSA_OCOMPLETE(tp));
1254 wakeup(TSA_OLOWAT(tp));
1256 case TIOCGDRAINWAIT:
1257 *(int *)data = tp->t_timeout / hz;
1260 return (tt_break(tp, 1));
1262 return (tt_break(tp, 0));
1264 #if defined(COMPAT_43TTY)
1265 return (ttcompat(tp, cmd, data, flag));
1274 ttypoll(struct cdev *dev, int events, struct thread *td)
1280 tp = tty_gettp(dev);
1282 if (tp == NULL) /* XXX used to return ENXIO, but that means true! */
1283 return ((events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM))
1287 if (events & (POLLIN | POLLRDNORM)) {
1288 if (ISSET(tp->t_state, TS_ZOMBIE))
1289 revents |= (events & (POLLIN | POLLRDNORM)) |
1291 else if (ttnread(tp) > 0)
1292 revents |= events & (POLLIN | POLLRDNORM);
1294 selrecord(td, &tp->t_rsel);
1296 if (events & POLLOUT) {
1297 if (ISSET(tp->t_state, TS_ZOMBIE))
1299 else if (tp->t_outq.c_cc <= tp->t_olowat &&
1300 ISSET(tp->t_state, TS_CONNECTED))
1301 revents |= events & POLLOUT;
1303 selrecord(td, &tp->t_wsel);
1309 static struct filterops ttyread_filtops =
1310 { 1, NULL, filt_ttyrdetach, filt_ttyread };
1311 static struct filterops ttywrite_filtops =
1312 { 1, NULL, filt_ttywdetach, filt_ttywrite };
1315 ttykqfilter(struct cdev *dev, struct knote *kn)
1318 struct knlist *klist;
1321 tp = tty_gettp(dev);
1322 if (tp->t_state & TS_GONE)
1325 switch (kn->kn_filter) {
1327 klist = &tp->t_rsel.si_note;
1328 kn->kn_fop = &ttyread_filtops;
1331 klist = &tp->t_wsel.si_note;
1332 kn->kn_fop = &ttywrite_filtops;
1338 kn->kn_hook = (caddr_t)tp;
1341 knlist_add(klist, kn, 0);
1348 filt_ttyrdetach(struct knote *kn)
1350 struct tty *tp = (struct tty *)kn->kn_hook;
1353 knlist_remove(&tp->t_rsel.si_note, kn, 0);
1358 filt_ttyread(struct knote *kn, long hint)
1360 struct tty *tp = (struct tty *)kn->kn_hook;
1362 kn->kn_data = ttnread(tp);
1363 if ((tp->t_state & TS_GONE) || ISSET(tp->t_state, TS_ZOMBIE)) {
1364 kn->kn_flags |= EV_EOF;
1367 return (kn->kn_data > 0);
1371 filt_ttywdetach(struct knote *kn)
1373 struct tty *tp = (struct tty *)kn->kn_hook;
1376 knlist_remove(&tp->t_wsel.si_note, kn, 0);
1381 filt_ttywrite(struct knote *kn, long hint)
1383 struct tty *tp = (struct tty *)kn->kn_hook;
1385 kn->kn_data = tp->t_outq.c_cc;
1386 if ((tp->t_state & TS_GONE) || ISSET(tp->t_state, TS_ZOMBIE))
1388 return (kn->kn_data <= tp->t_olowat &&
1389 ISSET(tp->t_state, TS_CONNECTED));
1393 * Must be called at spltty().
1396 ttnread(struct tty *tp)
1400 if (ISSET(tp->t_lflag, PENDIN))
1402 nread = tp->t_canq.c_cc;
1403 if (!ISSET(tp->t_lflag, ICANON)) {
1404 nread += tp->t_rawq.c_cc;
1405 if (nread < tp->t_cc[VMIN] && tp->t_cc[VTIME] == 0)
1412 * Wait for output to drain.
1415 ttywait(struct tty *tp)
1421 while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1422 ISSET(tp->t_state, TS_CONNECTED) && tp->t_oproc) {
1424 if ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1425 ISSET(tp->t_state, TS_CONNECTED)) {
1426 SET(tp->t_state, TS_SO_OCOMPLETE);
1427 error = ttysleep(tp, TSA_OCOMPLETE(tp),
1428 TTOPRI | PCATCH, "ttywai",
1431 if (error == EWOULDBLOCK)
1438 if (!error && (tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)))
1445 * Flush if successfully wait.
1448 ttywflush(struct tty *tp)
1452 if ((error = ttywait(tp)) == 0)
1453 ttyflush(tp, FREAD);
1458 * Flush tty read and/or write queues, notifying anyone waiting.
1461 ttyflush(struct tty *tp, int rw)
1470 FLUSHQ(&tp->t_outq);
1471 CLR(tp->t_state, TS_TTSTOP);
1475 FLUSHQ(&tp->t_canq);
1476 FLUSHQ(&tp->t_rawq);
1477 CLR(tp->t_lflag, PENDIN);
1480 CLR(tp->t_state, TS_LOCAL);
1482 if (ISSET(tp->t_state, TS_TBLOCK)) {
1484 FLUSHQ(&tp->t_outq);
1488 * Don't let leave any state that might clobber the
1489 * next line discipline (although we should do more
1490 * to send the START char). Not clearing the state
1491 * may have caused the "putc to a clist with no
1492 * reserved cblocks" panic/printf.
1494 CLR(tp->t_state, TS_TBLOCK);
1496 #if 0 /* forget it, sleeping isn't always safe and we don't know when it is */
1497 if (ISSET(tp->t_iflag, IXOFF)) {
1499 * XXX wait a bit in the hope that the stop
1500 * character (if any) will go out. Waiting
1501 * isn't good since it allows races. This
1502 * will be fixed when the stop character is
1503 * put in a special queue. Don't bother with
1504 * the checks in ttywait() since the timeout
1507 SET(tp->t_state, TS_SO_OCOMPLETE);
1508 ttysleep(tp, TSA_OCOMPLETE(tp), TTOPRI,
1511 * Don't try sending the stop character again.
1513 CLR(tp->t_state, TS_TBLOCK);
1520 FLUSHQ(&tp->t_outq);
1527 * Copy in the default termios characters.
1530 termioschars(struct termios *t)
1533 bcopy(ttydefchars, t->c_cc, sizeof t->c_cc);
1540 ttychars(struct tty *tp)
1543 termioschars(&tp->t_termios);
1547 * Handle input high water. Send stop character for the IXOFF case. Turn
1548 * on our input flow control bit and propagate the changes to the driver.
1549 * XXX the stop character should be put in a special high priority queue.
1552 ttyblock(struct tty *tp)
1555 SET(tp->t_state, TS_TBLOCK);
1556 if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
1557 putc(tp->t_cc[VSTOP], &tp->t_outq) != 0)
1558 CLR(tp->t_state, TS_TBLOCK); /* try again later */
1563 * Handle input low water. Send start character for the IXOFF case. Turn
1564 * off our input flow control bit and propagate the changes to the driver.
1565 * XXX the start character should be put in a special high priority queue.
1568 ttyunblock(struct tty *tp)
1571 CLR(tp->t_state, TS_TBLOCK);
1572 if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTART] != _POSIX_VDISABLE &&
1573 putc(tp->t_cc[VSTART], &tp->t_outq) != 0)
1574 SET(tp->t_state, TS_TBLOCK); /* try again later */
1579 /* Not used by any current (i386) drivers. */
1581 * Restart after an inter-char delay.
1584 ttrstrt(void *tp_arg)
1589 KASSERT(tp_arg != NULL, ("ttrstrt"));
1594 CLR(tp->t_state, TS_TIMEOUT);
1602 ttstart(struct tty *tp)
1610 * "close" a line discipline
1613 ttylclose(struct tty *tp, int flag)
1616 if (flag & FNONBLOCK || ttywflush(tp))
1617 ttyflush(tp, FREAD | FWRITE);
1622 * Handle modem control transition on a tty.
1623 * Flag indicates new state of carrier.
1624 * Returns 0 if the line should be turned off, otherwise 1.
1627 ttymodem(struct tty *tp, int flag)
1630 if (ISSET(tp->t_state, TS_CARR_ON) && ISSET(tp->t_cflag, MDMBUF)) {
1632 * MDMBUF: do flow control according to carrier flag
1633 * XXX TS_CAR_OFLOW doesn't do anything yet. TS_TTSTOP
1634 * works if IXON and IXANY are clear.
1637 CLR(tp->t_state, TS_CAR_OFLOW);
1638 CLR(tp->t_state, TS_TTSTOP);
1640 } else if (!ISSET(tp->t_state, TS_CAR_OFLOW)) {
1641 SET(tp->t_state, TS_CAR_OFLOW);
1642 SET(tp->t_state, TS_TTSTOP);
1645 } else if (flag == 0) {
1649 CLR(tp->t_state, TS_CARR_ON);
1650 if (ISSET(tp->t_state, TS_ISOPEN) &&
1651 !ISSET(tp->t_cflag, CLOCAL)) {
1652 SET(tp->t_state, TS_ZOMBIE);
1653 CLR(tp->t_state, TS_CONNECTED);
1654 if (tp->t_session) {
1655 sx_slock(&proctree_lock);
1656 if (tp->t_session && tp->t_session->s_leader) {
1659 p = tp->t_session->s_leader;
1664 sx_sunlock(&proctree_lock);
1666 ttyflush(tp, FREAD | FWRITE);
1673 SET(tp->t_state, TS_CARR_ON);
1674 if (!ISSET(tp->t_state, TS_ZOMBIE))
1675 SET(tp->t_state, TS_CONNECTED);
1676 wakeup(TSA_CARR_ON(tp));
1684 * Reinput pending characters after state switch
1688 ttypend(struct tty *tp)
1693 CLR(tp->t_lflag, PENDIN);
1694 SET(tp->t_state, TS_TYPEN);
1696 * XXX this assumes too much about clist internals. It may even
1697 * fail if the cblock slush pool is empty. We can't allocate more
1698 * cblocks here because we are called from an interrupt handler
1699 * and clist_alloc_cblocks() can wait.
1702 bzero(&tp->t_rawq, sizeof tp->t_rawq);
1703 tp->t_rawq.c_cbmax = tq.c_cbmax;
1704 tp->t_rawq.c_cbreserved = tq.c_cbreserved;
1705 while ((c = getc(&tq)) >= 0)
1707 CLR(tp->t_state, TS_TYPEN);
1711 * Process a read call on a tty device.
1714 ttread(struct tty *tp, struct uio *uio, int flag)
1719 cc_t *cc = tp->t_cc;
1722 int s, first, error = 0;
1723 int has_stime = 0, last_cc = 0;
1724 long slp = 0; /* XXX this should be renamed `timo'. */
1725 struct timeval stime = { 0, 0 };
1732 lflag = tp->t_lflag;
1734 * take pending input first
1736 if (ISSET(lflag, PENDIN)) {
1738 splx(s); /* reduce latency */
1740 lflag = tp->t_lflag; /* XXX ttypend() clobbers it */
1744 * Hang process if it's in the background.
1746 if (isbackground(p, tp)) {
1748 sx_slock(&proctree_lock);
1750 if (SIGISMEMBER(p->p_sigacts->ps_sigignore, SIGTTIN) ||
1751 SIGISMEMBER(td->td_sigmask, SIGTTIN) ||
1752 (p->p_flag & P_PPWAIT) || p->p_pgrp->pg_jobc == 0) {
1754 sx_sunlock(&proctree_lock);
1760 sx_sunlock(&proctree_lock);
1761 pgsignal(pg, SIGTTIN, 1);
1763 error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, "ttybg2", 0);
1769 if (ISSET(tp->t_state, TS_ZOMBIE)) {
1771 return (0); /* EOF */
1775 * If canonical, use the canonical queue,
1776 * else use the raw queue.
1778 * (should get rid of clists...)
1780 qp = ISSET(lflag, ICANON) ? &tp->t_canq : &tp->t_rawq;
1782 if (flag & IO_NDELAY) {
1785 if (!ISSET(lflag, ICANON) && cc[VMIN] == 0) {
1790 return (EWOULDBLOCK);
1792 if (!ISSET(lflag, ICANON)) {
1795 struct timeval timecopy;
1798 * Check each of the four combinations.
1799 * (m > 0 && t == 0) is the normal read case.
1800 * It should be fairly efficient, so we check that and its
1801 * companion case (m == 0 && t == 0) first.
1802 * For the other two cases, we compute the target sleep time
1811 /* m, t and qp->c_cc are all 0. 0 is enough input. */
1815 t *= 100000; /* time in us */
1816 #define diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 1000000 + \
1817 ((t1).tv_usec - (t2).tv_usec))
1823 getmicrotime(&timecopy);
1825 /* first character, start timer */
1829 } else if (qp->c_cc > last_cc) {
1830 /* got a character, restart timer */
1834 /* nothing, check expiration */
1835 slp = t - diff(timecopy, stime);
1840 } else { /* m == 0 */
1843 getmicrotime(&timecopy);
1849 slp = t - diff(timecopy, stime);
1851 /* Timed out, but 0 is enough input. */
1859 struct timeval tv; /* XXX style bug. */
1861 tv.tv_sec = slp / 1000000;
1862 tv.tv_usec = slp % 1000000;
1865 * XXX bad variable names. slp was the timeout in
1866 * usec. Now it is the timeout in ticks.
1871 if (qp->c_cc <= 0) {
1874 * There is no input, or not enough input and we can block.
1876 error = ttysleep(tp, TSA_HUP_OR_INPUT(tp), TTIPRI | PCATCH,
1877 ISSET(tp->t_state, TS_CONNECTED) ?
1878 "ttyin" : "ttyhup", (int)slp);
1880 if (error == EWOULDBLOCK)
1885 * XXX what happens if another process eats some input
1886 * while we are asleep (not just here)? It would be
1887 * safest to detect changes and reset our state variables
1888 * (has_stime and last_cc).
1896 * Input present, check for input mapping and processing.
1899 if (ISSET(lflag, ICANON | ISIG))
1905 icc = imin(uio->uio_resid, IBUFSIZ);
1906 icc = q_to_b(qp, ibuf, icc);
1912 error = uiomove(ibuf, icc, uio);
1914 * XXX if there was an error then we should ungetc() the
1915 * unmoved chars and reduce icc here.
1919 if (uio->uio_resid == 0)
1933 * delayed suspend (^Y)
1935 if (CCEQ(cc[VDSUSP], c) &&
1936 ISSET(lflag, IEXTEN | ISIG) == (IEXTEN | ISIG)) {
1937 if (tp->t_pgrp != NULL) {
1938 PGRP_LOCK(tp->t_pgrp);
1939 pgsignal(tp->t_pgrp, SIGTSTP, 1);
1940 PGRP_UNLOCK(tp->t_pgrp);
1943 error = ttysleep(tp, &lbolt, TTIPRI | PCATCH,
1952 * Interpret EOF only in canonical mode.
1954 if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
1957 * Give user character.
1959 error = ureadc(c, uio);
1961 /* XXX should ungetc(c, qp). */
1963 if (uio->uio_resid == 0)
1966 * In canonical mode check for a "break character"
1967 * marking the end of a "line of input".
1969 if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
1976 * Look to unblock input now that (presumably)
1977 * the input queue has gone down.
1980 if (ISSET(tp->t_state, TS_TBLOCK) &&
1981 tp->t_rawq.c_cc + tp->t_canq.c_cc <= tp->t_ilowat)
1989 * Check the output queue on tp for space for a kernel message (from uprintf
1990 * or tprintf). Allow some space over the normal hiwater mark so we don't
1991 * lose messages due to normal flow control, but don't let the tty run amok.
1992 * Sleeps here are not interruptible, but we return prematurely if new signals
1996 ttycheckoutq(struct tty *tp, int wait)
2005 hiwat = tp->t_ohiwat;
2006 SIGEMPTYSET(oldmask);
2010 oldmask = td->td_siglist;
2013 if (tp->t_outq.c_cc > hiwat + OBUFSIZ + 100)
2014 while (tp->t_outq.c_cc > hiwat) {
2016 if (tp->t_outq.c_cc <= hiwat)
2023 if (!SIGSETEQ(td->td_siglist, oldmask)) {
2029 SET(tp->t_state, TS_SO_OLOWAT);
2030 tsleep(TSA_OLOWAT(tp), PZERO - 1, "ttoutq", hz);
2037 * Process a write call on a tty device.
2040 ttwrite(struct tty *tp, struct uio *uio, int flag)
2046 int i, hiwat, cnt, error, s;
2049 hiwat = tp->t_ohiwat;
2050 cnt = uio->uio_resid;
2057 if (ISSET(tp->t_state, TS_ZOMBIE)) {
2059 if (uio->uio_resid == cnt)
2063 if (!ISSET(tp->t_state, TS_CONNECTED)) {
2064 if (flag & IO_NDELAY) {
2066 error = EWOULDBLOCK;
2069 error = ttysleep(tp, TSA_CARR_ON(tp), TTIPRI | PCATCH,
2078 * Hang the process if it's in the background.
2080 sx_slock(&proctree_lock);
2082 if (isbackground(p, tp) &&
2083 ISSET(tp->t_lflag, TOSTOP) && !(p->p_flag & P_PPWAIT) &&
2084 !SIGISMEMBER(p->p_sigacts->ps_sigignore, SIGTTOU) &&
2085 !SIGISMEMBER(td->td_sigmask, SIGTTOU)) {
2086 if (p->p_pgrp->pg_jobc == 0) {
2088 sx_sunlock(&proctree_lock);
2093 PGRP_LOCK(p->p_pgrp);
2094 sx_sunlock(&proctree_lock);
2095 pgsignal(p->p_pgrp, SIGTTOU, 1);
2096 PGRP_UNLOCK(p->p_pgrp);
2097 error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, "ttybg4", 0);
2103 sx_sunlock(&proctree_lock);
2106 * Process the user's data in at most OBUFSIZ chunks. Perform any
2107 * output translation. Keep track of high water mark, sleep on
2108 * overflow awaiting device aid in acquiring new space.
2110 while (uio->uio_resid > 0 || cc > 0) {
2111 if (ISSET(tp->t_lflag, FLUSHO)) {
2115 if (tp->t_outq.c_cc > hiwat)
2118 * Grab a hunk of data from the user, unless we have some
2119 * leftover from last time.
2122 cc = imin(uio->uio_resid, OBUFSIZ);
2124 error = uiomove(cp, cc, uio);
2131 * If nothing fancy need be done, grab those characters we
2132 * can handle without any of ttyoutput's processing and
2133 * just transfer them to the output q. For those chars
2134 * which require special processing (as indicated by the
2135 * bits in char_type), call ttyoutput. After processing
2136 * a hunk of data, look for FLUSHO so ^O's will take effect
2140 if (!ISSET(tp->t_oflag, OPOST))
2143 ce = cc - scanc((u_int)cc, (u_char *)cp,
2144 char_type, CCLASSMASK);
2146 * If ce is zero, then we're processing
2147 * a special character through ttyoutput.
2151 if (ttyoutput(*cp, tp) >= 0) {
2152 /* No Clists, wait a bit. */
2154 if (flag & IO_NDELAY) {
2155 error = EWOULDBLOCK;
2158 error = ttysleep(tp, &lbolt,
2167 if (ISSET(tp->t_lflag, FLUSHO) ||
2168 tp->t_outq.c_cc > hiwat)
2174 * A bunch of normal characters have been found.
2175 * Transfer them en masse to the output queue and
2176 * continue processing at the top of the loop.
2177 * If there are any further characters in this
2178 * <= OBUFSIZ chunk, the first should be a character
2179 * requiring special handling by ttyoutput.
2182 i = b_to_q(cp, ce, &tp->t_outq);
2185 cp += ce, cc -= ce, tk_nout += ce;
2188 /* No Clists, wait a bit. */
2190 if (flag & IO_NDELAY) {
2191 error = EWOULDBLOCK;
2194 error = ttysleep(tp, &lbolt, TTOPRI | PCATCH,
2200 if (ISSET(tp->t_lflag, FLUSHO) ||
2201 tp->t_outq.c_cc > hiwat)
2208 * If cc is nonzero, we leave the uio structure inconsistent, as the
2209 * offset and iov pointers have moved forward, but it doesn't matter
2210 * (the call will either return short or restart with a new uio).
2212 uio->uio_resid += cc;
2219 * This can only occur if FLUSHO is set in t_lflag,
2220 * or if ttstart/oproc is synchronous (or very fast).
2222 if (tp->t_outq.c_cc <= hiwat) {
2226 if (flag & IO_NDELAY) {
2228 uio->uio_resid += cc;
2229 return (uio->uio_resid == cnt ? EWOULDBLOCK : 0);
2231 SET(tp->t_state, TS_SO_OLOWAT);
2232 error = ttysleep(tp, TSA_OLOWAT(tp), TTOPRI | PCATCH, "ttywri",
2235 if (error == EWOULDBLOCK)
2243 * Rubout one character from the rawq of tp
2244 * as cleanly as possible.
2247 ttyrub(int c, struct tty *tp)
2253 if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
2255 CLR(tp->t_lflag, FLUSHO);
2256 if (ISSET(tp->t_lflag, ECHOE)) {
2257 if (tp->t_rocount == 0) {
2259 * Screwed by ttwrite; retype
2264 if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
2267 CLR(c, ~TTY_CHARMASK);
2268 switch (CCLASS(c)) {
2277 if (ISSET(tp->t_lflag, ECHOCTL))
2281 if (tp->t_rocount < tp->t_rawq.c_cc) {
2286 savecol = tp->t_column;
2287 SET(tp->t_state, TS_CNTTB);
2288 SET(tp->t_lflag, FLUSHO);
2289 tp->t_column = tp->t_rocol;
2290 cp = tp->t_rawq.c_cf;
2292 tabc = *cp; /* XXX FIX NEXTC */
2293 for (; cp; cp = nextc(&tp->t_rawq, cp, &tabc))
2295 CLR(tp->t_lflag, FLUSHO);
2296 CLR(tp->t_state, TS_CNTTB);
2299 /* savecol will now be length of the tab. */
2300 savecol -= tp->t_column;
2301 tp->t_column += savecol;
2303 savecol = 8; /* overflow screw */
2304 while (--savecol >= 0)
2305 (void)ttyoutput('\b', tp);
2308 #define PANICSTR "ttyrub: would panic c = %d, val = %d\n"
2309 (void)printf(PANICSTR, c, CCLASS(c));
2311 panic(PANICSTR, c, CCLASS(c));
2315 } else if (ISSET(tp->t_lflag, ECHOPRT)) {
2316 if (!ISSET(tp->t_state, TS_ERASE)) {
2317 SET(tp->t_state, TS_ERASE);
2318 (void)ttyoutput('\\', tp);
2322 ttyecho(tp->t_cc[VERASE], tp);
2324 * This code may be executed not only when an ERASE key
2325 * is pressed, but also when ^U (KILL) or ^W (WERASE) are.
2326 * So, I didn't think it was worthwhile to pass the extra
2327 * information (which would need an extra parameter,
2328 * changing every call) needed to distinguish the ERASE2
2329 * case from the ERASE.
2336 * Back over cnt characters, erasing them.
2339 ttyrubo(struct tty *tp, int cnt)
2343 (void)ttyoutput('\b', tp);
2344 (void)ttyoutput(' ', tp);
2345 (void)ttyoutput('\b', tp);
2351 * Reprint the rawq line. Note, it is assumed that c_cc has already
2355 ttyretype(struct tty *tp)
2360 /* Echo the reprint character. */
2361 if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
2362 ttyecho(tp->t_cc[VREPRINT], tp);
2364 (void)ttyoutput('\n', tp);
2368 * FIX: NEXTC IS BROKEN - DOESN'T CHECK QUOTE
2369 * BIT OF FIRST CHAR.
2372 for (cp = tp->t_canq.c_cf, c = (cp != NULL ? *cp : 0);
2373 cp != NULL; cp = nextc(&tp->t_canq, cp, &c))
2375 for (cp = tp->t_rawq.c_cf, c = (cp != NULL ? *cp : 0);
2376 cp != NULL; cp = nextc(&tp->t_rawq, cp, &c))
2378 CLR(tp->t_state, TS_ERASE);
2381 tp->t_rocount = tp->t_rawq.c_cc;
2386 * Echo a typed character to the terminal.
2389 ttyecho(int c, struct tty *tp)
2392 if (!ISSET(tp->t_state, TS_CNTTB))
2393 CLR(tp->t_lflag, FLUSHO);
2394 if ((!ISSET(tp->t_lflag, ECHO) &&
2395 (c != '\n' || !ISSET(tp->t_lflag, ECHONL))) ||
2396 ISSET(tp->t_lflag, EXTPROC))
2398 if (ISSET(tp->t_lflag, ECHOCTL) &&
2399 ((ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n') ||
2400 ISSET(c, TTY_CHARMASK) == 0177)) {
2401 (void)ttyoutput('^', tp);
2402 CLR(c, ~TTY_CHARMASK);
2408 (void)ttyoutput(c, tp);
2412 * Wake up any readers on a tty.
2415 ttwakeup(struct tty *tp)
2418 if (SEL_WAITING(&tp->t_rsel))
2419 selwakeuppri(&tp->t_rsel, TTIPRI);
2420 if (ISSET(tp->t_state, TS_ASYNC) && tp->t_sigio != NULL)
2421 pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
2422 wakeup(TSA_HUP_OR_INPUT(tp));
2423 KNOTE_UNLOCKED(&tp->t_rsel.si_note, 0);
2427 * Wake up any writers on a tty.
2430 ttwwakeup(struct tty *tp)
2433 if (SEL_WAITING(&tp->t_wsel) && tp->t_outq.c_cc <= tp->t_olowat)
2434 selwakeuppri(&tp->t_wsel, TTOPRI);
2435 if (ISSET(tp->t_state, TS_ASYNC) && tp->t_sigio != NULL)
2436 pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
2437 if (ISSET(tp->t_state, TS_BUSY | TS_SO_OCOMPLETE) ==
2438 TS_SO_OCOMPLETE && tp->t_outq.c_cc == 0) {
2439 CLR(tp->t_state, TS_SO_OCOMPLETE);
2440 wakeup(TSA_OCOMPLETE(tp));
2442 if (ISSET(tp->t_state, TS_SO_OLOWAT) &&
2443 tp->t_outq.c_cc <= tp->t_olowat) {
2444 CLR(tp->t_state, TS_SO_OLOWAT);
2445 wakeup(TSA_OLOWAT(tp));
2447 KNOTE_UNLOCKED(&tp->t_wsel.si_note, 0);
2451 * Look up a code for a specified speed in a conversion table;
2452 * used by drivers to map software speed values to hardware parameters.
2455 ttspeedtab(int speed, struct speedtab *table)
2458 for ( ; table->sp_speed != -1; table++)
2459 if (table->sp_speed == speed)
2460 return (table->sp_code);
2465 * Set input and output watermarks and buffer sizes. For input, the
2466 * high watermark is about one second's worth of input above empty, the
2467 * low watermark is slightly below high water, and the buffer size is a
2468 * driver-dependent amount above high water. For output, the watermarks
2469 * are near the ends of the buffer, with about 1 second's worth of input
2470 * between them. All this only applies to the standard line discipline.
2473 ttsetwater(struct tty *tp)
2475 int cps, ttmaxhiwat, x;
2478 clist_alloc_cblocks(&tp->t_canq, TTYHOG, 512);
2479 switch (tp->t_ispeedwat) {
2481 cps = tp->t_ispeed / 10;
2485 * This case is for old drivers that don't know about
2486 * t_ispeedwat. Arrange for them to get the old buffer
2487 * sizes and watermarks.
2489 cps = TTYHOG - 2 * 256;
2490 tp->t_ififosize = 2 * 256;
2493 cps = tp->t_ispeedwat / 10;
2497 tp->t_ilowat = 7 * cps / 8;
2498 x = cps + tp->t_ififosize;
2499 clist_alloc_cblocks(&tp->t_rawq, x, x);
2502 switch (tp->t_ospeedwat) {
2504 cps = tp->t_ospeed / 10;
2505 ttmaxhiwat = 2 * TTMAXHIWAT;
2508 cps = tp->t_ospeed / 10;
2509 ttmaxhiwat = TTMAXHIWAT;
2512 cps = tp->t_ospeedwat / 10;
2513 ttmaxhiwat = 8 * TTMAXHIWAT;
2516 #define CLAMP(x, h, l) ((x) > h ? h : ((x) < l) ? l : (x))
2517 tp->t_olowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
2519 x = CLAMP(x, ttmaxhiwat, TTMINHIWAT); /* XXX clamps are too magic */
2520 tp->t_ohiwat = roundup(x, CBSIZE); /* XXX for compat */
2521 x = imax(tp->t_ohiwat, TTMAXHIWAT); /* XXX for compat/safety */
2523 clist_alloc_cblocks(&tp->t_outq, x, x);
2528 * Report on state of foreground process group.
2531 ttyinfo(struct tty *tp)
2533 struct timeval utime, stime;
2534 struct proc *p, *pick;
2535 struct thread *td, *picktd;
2536 const char *stateprefix, *state;
2540 char comm[MAXCOMLEN + 1];
2543 if (ttycheckoutq(tp,0) == 0)
2546 /* Print load average. */
2547 load = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
2548 ttyprintf(tp, "load: %d.%02d ", load / 100, load % 100);
2551 * On return following a ttyprintf(), we set tp->t_rocount to 0 so
2552 * that pending input will be retyped on BS.
2554 if (tp->t_session == NULL) {
2555 ttyprintf(tp, "not a controlling terminal\n");
2559 if (tp->t_pgrp == NULL) {
2560 ttyprintf(tp, "no foreground process group\n");
2564 PGRP_LOCK(tp->t_pgrp);
2565 if (LIST_EMPTY(&tp->t_pgrp->pg_members)) {
2566 PGRP_UNLOCK(tp->t_pgrp);
2567 ttyprintf(tp, "empty foreground process group\n");
2573 * Pick the most interesting process and copy some of its
2574 * state for printing later. This operation could rely on stale
2575 * data as we can't hold the proc slock or thread locks over the
2576 * whole list. However, we're guaranteed not to reference an exited
2577 * thread or proc since we hold the tty locked.
2580 LIST_FOREACH(p, &tp->t_pgrp->pg_members, p_pglist)
2581 if (proc_compare(pick, p))
2586 td = FIRST_THREAD_IN_PROC(pick);
2587 FOREACH_THREAD_IN_PROC(pick, td)
2588 if (thread_compare(picktd, td))
2593 if (TD_IS_RUNNING(td))
2595 else if (TD_ON_RUNQ(td) || TD_CAN_RUN(td))
2597 else if (TD_IS_SLEEPING(td)) {
2598 /* XXX: If we're sleeping, are we ever not in a queue? */
2599 if (TD_ON_SLEEPQ(td))
2600 state = td->td_wmesg;
2602 state = "sleeping without queue";
2603 } else if (TD_ON_LOCK(td)) {
2604 state = td->td_lockname;
2606 } else if (TD_IS_SUSPENDED(td))
2607 state = "suspended";
2608 else if (TD_AWAITING_INTR(td))
2612 pctcpu = (sched_pctcpu(td) * 10000 + FSCALE / 2) >> FSHIFT;
2614 if (pick->p_state == PRS_NEW || pick->p_state == PRS_ZOMBIE)
2617 rss = pgtok(vmspace_resident_count(pick->p_vmspace));
2620 PGRP_UNLOCK(tp->t_pgrp);
2621 rufetchcalc(pick, &ru, &utime, &stime);
2623 bcopy(pick->p_comm, comm, sizeof(comm));
2626 /* Print command, pid, state, utime, stime, %cpu, and rss. */
2628 " cmd: %s %d [%s%s] %ld.%02ldu %ld.%02lds %d%% %ldk\n",
2629 comm, pid, stateprefix, state,
2630 (long)utime.tv_sec, utime.tv_usec / 10000,
2631 (long)stime.tv_sec, stime.tv_usec / 10000,
2637 * Returns 1 if p2 is "better" than p1
2639 * The algorithm for picking the "interesting" process is thus:
2641 * 1) Only foreground processes are eligible - implied.
2642 * 2) Runnable processes are favored over anything else. The runner
2643 * with the highest cpu utilization is picked (p_estcpu). Ties are
2644 * broken by picking the highest pid.
2645 * 3) The sleeper with the shortest sleep time is next. With ties,
2646 * we pick out just "short-term" sleepers (P_SINTR == 0).
2647 * 4) Further ties are broken by picking the highest pid.
2650 #define TESTAB(a, b) ((a)<<1 | (b))
2656 proc_sum(struct proc *p, int *estcpup)
2664 FOREACH_THREAD_IN_PROC(p, td) {
2666 if (TD_ON_RUNQ(td) ||
2669 estcpu += sched_pctcpu(td);
2678 thread_compare(struct thread *td, struct thread *td2)
2688 * Fetch running stats, pctcpu usage, and interruptable flag.
2691 runa = TD_IS_RUNNING(td) | TD_ON_RUNQ(td);
2692 slpa = td->td_flags & TDF_SINTR;
2693 esta = sched_pctcpu(td);
2696 runb = TD_IS_RUNNING(td2) | TD_ON_RUNQ(td2);
2697 estb = sched_pctcpu(td2);
2698 slpb = td2->td_flags & TDF_SINTR;
2701 * see if at least one of them is runnable
2703 switch (TESTAB(runa, runb)) {
2712 * favor one with highest recent cpu utilization
2719 * favor one sleeping in a non-interruptible sleep
2721 switch (TESTAB(slpa, slpb)) {
2734 proc_compare(struct proc *p1, struct proc *p2)
2744 * Fetch various stats about these processes. After we drop the
2745 * lock the information could be stale but the race is unimportant.
2748 runa = proc_sum(p1, &esta);
2751 runb = proc_sum(p2, &estb);
2755 * see if at least one of them is runnable
2757 switch (TESTAB(runa, runb)) {
2766 * favor one with highest recent cpu utilization
2775 switch (TESTAB(p1->p_state == PRS_ZOMBIE, p2->p_state == PRS_ZOMBIE)) {
2784 return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
2788 * Output char to tty; console putchar style.
2791 tputchar(int c, struct tty *tp)
2796 if (!ISSET(tp->t_state, TS_CONNECTED)) {
2801 (void)ttyoutput('\r', tp);
2802 (void)ttyoutput(c, tp);
2809 * Sleep on chan, returning ERESTART if tty changed while we napped and
2810 * returning any errors (e.g. EINTR/EWOULDBLOCK) reported by tsleep. If
2811 * the tty is revoked, restarting a pending call will redo validation done
2812 * at the start of the call.
2815 ttysleep(struct tty *tp, void *chan, int pri, char *wmesg, int timo)
2821 error = tsleep(chan, pri, wmesg, timo);
2822 if (tp->t_state & TS_GONE)
2826 return (tp->t_gen == gen ? 0 : ERESTART);
2830 * Gain a reference to a TTY
2833 ttyref(struct tty *tp)
2837 mtx_lock(&tp->t_mtx);
2838 KASSERT(tp->t_refcnt > 0,
2839 ("ttyref(): tty refcnt is %d (%s)",
2840 tp->t_refcnt, tp->t_dev != NULL ? devtoname(tp->t_dev) : "??"));
2842 mtx_unlock(&tp->t_mtx);
2847 * Drop a reference to a TTY.
2848 * When reference count drops to zero, we free it.
2851 ttyrel(struct tty *tp)
2855 mtx_lock(&tty_list_mutex);
2856 mtx_lock(&tp->t_mtx);
2857 KASSERT(tp->t_refcnt > 0,
2858 ("ttyrel(): tty refcnt is %d (%s)",
2859 tp->t_refcnt, tp->t_dev != NULL ? devtoname(tp->t_dev) : "??"));
2862 mtx_unlock(&tp->t_mtx);
2863 mtx_unlock(&tty_list_mutex);
2866 TAILQ_REMOVE(&tty_list, tp, t_list);
2867 mtx_unlock(&tp->t_mtx);
2868 mtx_unlock(&tty_list_mutex);
2869 knlist_destroy(&tp->t_rsel.si_note);
2870 knlist_destroy(&tp->t_wsel.si_note);
2871 mtx_destroy(&tp->t_mtx);
2877 * Allocate a tty struct. Clists in the struct will be allocated by
2885 tp = malloc(sizeof *tp, M_TTYS, M_WAITOK | M_ZERO);
2886 mtx_init(&tp->t_mtx, "tty", NULL, MTX_DEF);
2889 * Set up the initial state
2893 tp->t_dtr_wait = 3 * hz;
2895 ttyinitmode(tp, 0, 0);
2896 bcopy(ttydefchars, tp->t_init_in.c_cc, sizeof tp->t_init_in.c_cc);
2898 /* Make callout the same as callin */
2899 tp->t_init_out = tp->t_init_in;
2901 mtx_lock(&tty_list_mutex);
2902 TAILQ_INSERT_TAIL(&tty_list, tp, t_list);
2903 mtx_unlock(&tty_list_mutex);
2904 knlist_init(&tp->t_rsel.si_note, &tp->t_mtx, NULL, NULL, NULL);
2905 knlist_init(&tp->t_wsel.si_note, &tp->t_mtx, NULL, NULL, NULL);
2910 ttypurge(struct cdev *dev)
2913 if (dev->si_tty == NULL)
2915 ttygone(dev->si_tty);
2921 * Create the device entries for this tty thereby opening it for business.
2923 * The flags argument controls if "cua" units are created.
2925 * The t_sc filed is copied to si_drv1 in the created cdevs. This
2926 * is particularly important for ->t_cioctl() users.
2928 * XXX: implement the init and lock devices by cloning.
2932 ttycreate(struct tty *tp, int flags, const char *fmt, ...)
2934 char namebuf[SPECNAMELEN - 3]; /* XXX space for "tty" */
2935 struct cdevsw *csw = NULL;
2939 int i, minor, sminor, sunit;
2941 mtx_assert(&Giant, MA_OWNED);
2943 if (tty_unit == NULL)
2944 tty_unit = new_unrhdr(0, 0xffff, NULL);
2946 sunit = alloc_unr(tty_unit);
2947 tp->t_devunit = sunit;
2953 KASSERT(csw->d_purge == NULL || csw->d_purge == ttypurge,
2954 ("tty should not have d_purge"));
2956 csw->d_purge = ttypurge;
2958 minor = unit2minor(unit);
2959 sminor = unit2minor(sunit);
2961 i = vsnrprintf(namebuf, sizeof namebuf, 32, fmt, ap);
2963 KASSERT(i < sizeof namebuf, ("Too long tty name (%s)", namebuf));
2965 cp = make_dev(csw, minor,
2966 UID_ROOT, GID_WHEEL, 0600, "tty%s", namebuf);
2970 cp->si_drv1 = tp->t_sc;
2972 cp = make_dev(&ttys_cdevsw, sminor | MINOR_INIT,
2973 UID_ROOT, GID_WHEEL, 0600, "tty%s.init", namebuf);
2974 dev_depends(tp->t_dev, cp);
2975 cp->si_drv1 = tp->t_sc;
2976 cp->si_drv2 = &tp->t_init_in;
2979 cp = make_dev(&ttys_cdevsw, sminor | MINOR_LOCK,
2980 UID_ROOT, GID_WHEEL, 0600, "tty%s.lock", namebuf);
2981 dev_depends(tp->t_dev, cp);
2982 cp->si_drv1 = tp->t_sc;
2983 cp->si_drv2 = &tp->t_lock_in;
2986 if (flags & TS_CALLOUT) {
2987 cp = make_dev(csw, minor | MINOR_CALLOUT,
2988 UID_UUCP, GID_DIALER, 0660, "cua%s", namebuf);
2989 dev_depends(tp->t_dev, cp);
2990 cp->si_drv1 = tp->t_sc;
2993 cp = make_dev(&ttys_cdevsw, sminor | MINOR_CALLOUT | MINOR_INIT,
2994 UID_UUCP, GID_DIALER, 0660, "cua%s.init", namebuf);
2995 dev_depends(tp->t_dev, cp);
2996 cp->si_drv1 = tp->t_sc;
2997 cp->si_drv2 = &tp->t_init_out;
3000 cp = make_dev(&ttys_cdevsw, sminor | MINOR_CALLOUT | MINOR_LOCK,
3001 UID_UUCP, GID_DIALER, 0660, "cua%s.lock", namebuf);
3002 dev_depends(tp->t_dev, cp);
3003 cp->si_drv1 = tp->t_sc;
3004 cp->si_drv2 = &tp->t_lock_out;
3012 * This function is called when the hardware disappears. We set a flag
3013 * and wake up stuff so all sleeping threads will notice.
3016 ttygone(struct tty *tp)
3019 tp->t_state |= TS_GONE;
3020 if (SEL_WAITING(&tp->t_rsel))
3021 selwakeuppri(&tp->t_rsel, TTIPRI);
3022 if (SEL_WAITING(&tp->t_wsel))
3023 selwakeuppri(&tp->t_wsel, TTOPRI);
3024 if (ISSET(tp->t_state, TS_ASYNC) && tp->t_sigio != NULL)
3025 pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
3026 wakeup(&tp->t_dtr_wait);
3027 wakeup(TSA_CARR_ON(tp));
3028 wakeup(TSA_HUP_OR_INPUT(tp));
3029 wakeup(TSA_OCOMPLETE(tp));
3030 wakeup(TSA_OLOWAT(tp));
3031 KNOTE_UNLOCKED(&tp->t_rsel.si_note, 0);
3032 KNOTE_UNLOCKED(&tp->t_wsel.si_note, 0);
3039 * Called when the driver is ready to free the tty structure.
3041 * XXX: This shall sleep until all threads have left the driver.
3045 ttyfree(struct tty *tp)
3049 mtx_assert(&Giant, MA_OWNED);
3051 unit = tp->t_devunit;
3052 destroy_dev(tp->t_mdev);
3053 free_unr(tty_unit, unit);
3057 sysctl_kern_ttys(SYSCTL_HANDLER_ARGS)
3059 struct tty *tp, *tp2;
3064 mtx_lock(&tty_list_mutex);
3065 tp = TAILQ_FIRST(&tty_list);
3068 mtx_unlock(&tty_list_mutex);
3069 while (tp != NULL) {
3070 bzero(&xt, sizeof xt);
3071 xt.xt_size = sizeof xt;
3072 #define XT_COPY(field) xt.xt_##field = tp->t_##field
3073 xt.xt_rawcc = tp->t_rawq.c_cc;
3074 xt.xt_cancc = tp->t_canq.c_cc;
3075 xt.xt_outcc = tp->t_outq.c_cc;
3077 if (tp->t_dev != NULL)
3078 xt.xt_dev = dev2udev(tp->t_dev);
3082 if (tp->t_pgrp != NULL)
3083 xt.xt_pgid = tp->t_pgrp->pg_id;
3084 if (tp->t_session != NULL)
3085 xt.xt_sid = tp->t_session->s_sid;
3099 error = SYSCTL_OUT(req, &xt, sizeof xt);
3104 mtx_lock(&tty_list_mutex);
3105 tp2 = TAILQ_NEXT(tp, t_list);
3108 mtx_unlock(&tty_list_mutex);
3115 SYSCTL_PROC(_kern, OID_AUTO, ttys, CTLTYPE_OPAQUE|CTLFLAG_RD,
3116 0, 0, sysctl_kern_ttys, "S,xtty", "All ttys");
3117 SYSCTL_LONG(_kern, OID_AUTO, tty_nin, CTLFLAG_RD,
3118 &tk_nin, 0, "Total TTY in characters");
3119 SYSCTL_LONG(_kern, OID_AUTO, tty_nout, CTLFLAG_RD,
3120 &tk_nout, 0, "Total TTY out characters");
3123 nottystop(struct tty *tp, int rw)
3130 ttyopen(struct cdev *dev, int flag, int mode, struct thread *td)
3140 * We jump to this label after all non-interrupted sleeps to pick
3141 * up any changes of the device state.
3144 if (tp->t_state & TS_GONE)
3146 error = ttydtrwaitsleep(tp);
3149 if (tp->t_state & TS_ISOPEN) {
3151 * The device is open, so everything has been initialized.
3154 if (ISCALLOUT(dev) && !tp->t_actout)
3156 if (tp->t_actout && !ISCALLOUT(dev)) {
3157 if (flag & O_NONBLOCK)
3159 error = tsleep(&tp->t_actout,
3160 TTIPRI | PCATCH, "ttybi", 0);
3161 if (error != 0 || (tp->t_flags & TS_GONE))
3165 if (tp->t_state & TS_XCLUDE && priv_check(td,
3166 PRIV_TTY_EXCLUSIVE))
3170 * The device isn't open, so there are no conflicts.
3171 * Initialize it. Initialization is done twice in many
3172 * cases: to preempt sleeping callin opens if we are
3173 * callout, and to complete a callin open after DCD rises.
3175 tp->t_termios = ISCALLOUT(dev) ? tp->t_init_out : tp->t_init_in;
3176 tp->t_cflag = tp->t_termios.c_cflag;
3177 if (tp->t_modem != NULL)
3178 tt_modem(tp, SER_DTR | SER_RTS, 0);
3180 error = tt_param(tp, &tp->t_termios);
3183 error = tt_open(tp, dev);
3186 if (ISCALLOUT(dev) || (tt_modem(tp, 0, 0) & SER_DCD))
3190 * Wait for DCD if necessary.
3192 if (!(tp->t_state & TS_CARR_ON) && !ISCALLOUT(dev)
3193 && !(tp->t_cflag & CLOCAL) && !(flag & O_NONBLOCK)) {
3195 error = tsleep(TSA_CARR_ON(tp), TTIPRI | PCATCH, "ttydcd", 0);
3197 if (error != 0 || (tp->t_state & TS_GONE))
3201 error = ttyld_open(tp, dev);
3203 if (tp->t_state & TS_ISOPEN && ISCALLOUT(dev))
3204 tp->t_actout = TRUE;
3207 if (!(tp->t_state & TS_ISOPEN) && tp->t_wopeners == 0)
3213 ttyclose(struct cdev *dev, int flag, int mode, struct thread *td)
3218 ttyld_close(tp, flag);
3221 tp->t_do_timestamp = 0;
3222 if (tp->t_pps != NULL)
3223 tp->t_pps->ppsparam.mode = 0;
3229 ttyread(struct cdev *dev, struct uio *uio, int flag)
3233 tp = tty_gettp(dev);
3235 if (tp->t_state & TS_GONE)
3237 return (ttyld_read(tp, uio, flag));
3241 ttywrite(struct cdev *dev, struct uio *uio, int flag)
3245 tp = tty_gettp(dev);
3247 if (tp->t_state & TS_GONE)
3249 return (ttyld_write(tp, uio, flag));
3253 ttyioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
3260 if (cmd == TIOCSETA || cmd == TIOCSETAW || cmd == TIOCSETAF) {
3262 struct termios *dt = (struct termios *)data;
3263 struct termios *lt =
3264 ISCALLOUT(dev) ? &tp->t_lock_out : &tp->t_lock_in;
3266 dt->c_iflag = (tp->t_iflag & lt->c_iflag)
3267 | (dt->c_iflag & ~lt->c_iflag);
3268 dt->c_oflag = (tp->t_oflag & lt->c_oflag)
3269 | (dt->c_oflag & ~lt->c_oflag);
3270 dt->c_cflag = (tp->t_cflag & lt->c_cflag)
3271 | (dt->c_cflag & ~lt->c_cflag);
3272 dt->c_lflag = (tp->t_lflag & lt->c_lflag)
3273 | (dt->c_lflag & ~lt->c_lflag);
3274 for (cc = 0; cc < NCCS; ++cc)
3275 if (lt->c_cc[cc] != 0)
3276 dt->c_cc[cc] = tp->t_cc[cc];
3277 if (lt->c_ispeed != 0)
3278 dt->c_ispeed = tp->t_ispeed;
3279 if (lt->c_ospeed != 0)
3280 dt->c_ospeed = tp->t_ospeed;
3283 error = ttyld_ioctl(tp, cmd, data, flag, td);
3284 if (error == ENOIOCTL)
3285 error = ttioctl(tp, cmd, data, flag);
3287 if (error != ENOIOCTL)
3293 ttyldoptim(struct tty *tp)
3298 if (!(t->c_iflag & (ICRNL | IGNCR | IMAXBEL | INLCR | ISTRIP | IXON))
3299 && (!(t->c_iflag & BRKINT) || (t->c_iflag & IGNBRK))
3300 && (!(t->c_iflag & PARMRK)
3301 || (t->c_iflag & (IGNPAR | IGNBRK)) == (IGNPAR | IGNBRK))
3302 && !(t->c_lflag & (ECHO | ICANON | IEXTEN | ISIG | PENDIN))
3303 && linesw[tp->t_line]->l_rint == ttyinput)
3304 tp->t_state |= TS_CAN_BYPASS_L_RINT;
3306 tp->t_state &= ~TS_CAN_BYPASS_L_RINT;
3310 ttydtrwaitwakeup(void *arg)
3315 tp->t_state &= ~TS_DTR_WAIT;
3316 wakeup(&tp->t_dtr_wait);
3321 ttydtrwaitstart(struct tty *tp)
3324 if (tp->t_dtr_wait == 0)
3326 if (tp->t_state & TS_DTR_WAIT)
3328 timeout(ttydtrwaitwakeup, tp, tp->t_dtr_wait);
3329 tp->t_state |= TS_DTR_WAIT;
3333 ttydtrwaitsleep(struct tty *tp)
3338 while (error == 0) {
3339 if (tp->t_state & TS_GONE)
3341 else if (!(tp->t_state & TS_DTR_WAIT))
3344 error = tsleep(&tp->t_dtr_wait, TTIPRI | PCATCH,
3351 ttysopen(struct cdev *dev, int flag, int mode, struct thread *td)
3357 ("ttysopen(): no tty pointer on device (%s)", devtoname(dev)));
3358 if (tp->t_state & TS_GONE)
3364 ttysclose(struct cdev *dev, int flag, int mode, struct thread *td)
3371 ttysrdwr(struct cdev *dev, struct uio *uio, int flag)
3378 ttysioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
3386 ("ttysopen(): no tty pointer on device (%s)", devtoname(dev)));
3387 if (tp->t_state & TS_GONE)
3392 error = priv_check(td, PRIV_TTY_SETA);
3395 *ct = *(struct termios *)data;
3398 *(struct termios *)data = *ct;
3401 *(int *)data = TTYDISC;
3404 bzero(data, sizeof(struct winsize));
3407 if (tp->t_cioctl != NULL)
3408 return(tp->t_cioctl(dev, cmd, data, flag, td));
3414 * Initialize a tty to sane modes.
3417 ttyinitmode(struct tty *tp, int echo, int speed)
3421 speed = TTYDEF_SPEED;
3422 tp->t_init_in.c_iflag = TTYDEF_IFLAG;
3423 tp->t_init_in.c_oflag = TTYDEF_OFLAG;
3424 tp->t_init_in.c_cflag = TTYDEF_CFLAG;
3426 tp->t_init_in.c_lflag = TTYDEF_LFLAG_ECHO;
3428 tp->t_init_in.c_lflag = TTYDEF_LFLAG_NOECHO;
3430 tp->t_init_in.c_ispeed = tp->t_init_in.c_ospeed = speed;
3431 termioschars(&tp->t_init_in);
3432 tp->t_init_out = tp->t_init_in;
3433 tp->t_termios = tp->t_init_in;
3437 * Use more "normal" termios paramters for consoles.
3440 ttyconsolemode(struct tty *tp, int speed)
3444 speed = TTYDEF_SPEED;
3445 ttyinitmode(tp, 1, speed);
3446 tp->t_init_in.c_cflag |= CLOCAL;
3447 tp->t_lock_out.c_cflag = tp->t_lock_in.c_cflag = CLOCAL;
3448 tp->t_lock_out.c_ispeed = tp->t_lock_out.c_ospeed =
3449 tp->t_lock_in.c_ispeed = tp->t_lock_in.c_ospeed = speed;
3450 tp->t_init_out = tp->t_init_in;
3451 tp->t_termios = tp->t_init_in;
3456 * Record the relationship between the serial ports notion of modem control
3457 * signals and the one used in certain ioctls in a way the compiler can enforce
3458 * XXX: We should define TIOCM_* in terms of SER_ if we can limit the
3459 * XXX: consequences of the #include work that would take.
3461 CTASSERT(SER_DTR == TIOCM_DTR / 2);
3462 CTASSERT(SER_RTS == TIOCM_RTS / 2);
3463 CTASSERT(SER_STX == TIOCM_ST / 2);
3464 CTASSERT(SER_SRX == TIOCM_SR / 2);
3465 CTASSERT(SER_CTS == TIOCM_CTS / 2);
3466 CTASSERT(SER_DCD == TIOCM_DCD / 2);
3467 CTASSERT(SER_RI == TIOCM_RI / 2);
3468 CTASSERT(SER_DSR == TIOCM_DSR / 2);