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>
93 #include <sys/fcntl.h>
96 #include <sys/kernel.h>
97 #include <sys/vnode.h>
98 #include <sys/serial.h>
99 #include <sys/signalvar.h>
100 #include <sys/resourcevar.h>
101 #include <sys/malloc.h>
102 #include <sys/filedesc.h>
103 #include <sys/sched.h>
104 #include <sys/sysctl.h>
105 #include <sys/timepps.h>
107 #include <machine/stdarg.h>
111 #include <vm/vm_map.h>
113 MALLOC_DEFINE(M_TTYS, "ttys", "tty data structures");
120 static d_open_t ttysopen;
121 static d_close_t ttysclose;
122 static d_read_t ttysrdwr;
123 static d_ioctl_t ttysioctl;
124 static d_purge_t ttypurge;
126 /* Default cdevsw for common tty devices */
127 static struct cdevsw tty_cdevsw = {
128 .d_version = D_VERSION,
134 .d_flags = D_TTY | D_NEEDGIANT,
137 /* Cdevsw for slave tty devices */
138 static struct cdevsw ttys_cdevsw = {
139 .d_version = D_VERSION,
141 .d_close = ttysclose,
144 .d_ioctl = ttysioctl,
146 .d_flags = D_TTY | D_NEEDGIANT,
149 static int proc_compare(struct proc *p1, struct proc *p2);
150 static int ttnread(struct tty *tp);
151 static void ttyecho(int c, struct tty *tp);
152 static int ttyoutput(int c, struct tty *tp);
153 static void ttypend(struct tty *tp);
154 static void ttyretype(struct tty *tp);
155 static void ttyrub(int c, struct tty *tp);
156 static void ttyrubo(struct tty *tp, int cnt);
157 static void ttyunblock(struct tty *tp);
158 static int ttywflush(struct tty *tp);
159 static int filt_ttyread(struct knote *kn, long hint);
160 static void filt_ttyrdetach(struct knote *kn);
161 static int filt_ttywrite(struct knote *kn, long hint);
162 static void filt_ttywdetach(struct knote *kn);
165 * Table with character classes and parity. The 8th bit indicates parity,
166 * the 7th bit indicates the character is an alphameric or underscore (for
167 * ALTWERASE), and the low 6 bits indicate delay type. If the low 6 bits
168 * are 0 then the character needs no special processing on output; classes
169 * other than 0 might be translated or (not currently) require delays.
171 #define E 0x00 /* Even parity. */
172 #define O 0x80 /* Odd parity. */
173 #define PARITY(c) (char_type[c] & O)
175 #define ALPHA 0x40 /* Alpha or underscore. */
176 #define ISALPHA(c) (char_type[(c) & TTY_CHARMASK] & ALPHA)
178 #define CCLASSMASK 0x3f
179 #define CCLASS(c) (char_type[c] & CCLASSMASK)
184 #define NA ORDINARY | ALPHA
190 static u_char const char_type[] = {
191 E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC, /* nul - bel */
192 O|BS, E|TB, E|NL, O|CC, E|VT, O|CR, O|CC, E|CC, /* bs - si */
193 O|CC, E|CC, E|CC, O|CC, E|CC, O|CC, O|CC, E|CC, /* dle - etb */
194 E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC, /* can - us */
195 O|NO, E|NO, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* sp - ' */
196 E|NO, O|NO, O|NO, E|NO, O|NO, E|NO, E|NO, O|NO, /* ( - / */
197 E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* 0 - 7 */
198 O|NA, E|NA, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* 8 - ? */
199 O|NO, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* @ - G */
200 E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* H - O */
201 E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* P - W */
202 O|NA, E|NA, E|NA, O|NO, E|NO, O|NO, O|NO, O|NA, /* X - _ */
203 E|NO, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* ` - g */
204 O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* h - o */
205 O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* p - w */
206 E|NA, O|NA, O|NA, E|NO, O|NO, E|NO, E|NO, O|CC, /* x - del */
208 * Meta chars; should be settable per character set;
209 * for now, treat them all as normal characters.
211 NA, NA, NA, NA, NA, NA, NA, NA,
212 NA, NA, NA, NA, NA, NA, NA, NA,
213 NA, NA, NA, NA, NA, NA, NA, NA,
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,
237 /* Macros to clear/set/test flags. */
238 #define SET(t, f) (t) |= (f)
239 #define CLR(t, f) (t) &= ~(f)
240 #define ISSET(t, f) ((t) & (f))
242 #undef MAX_INPUT /* XXX wrong in <sys/syslimits.h> */
243 #define MAX_INPUT TTYHOG /* XXX limit is usually larger for !ICANON */
246 * list of struct tty where pstat(8) can pick it up with sysctl
248 * The lock order is to grab the list mutex before the tty mutex.
249 * Together with additions going on the tail of the list, this allows
250 * the sysctl to avoid doing retries.
252 static TAILQ_HEAD(, tty) tty_list = TAILQ_HEAD_INITIALIZER(tty_list);
253 static struct mtx tty_list_mutex;
254 MTX_SYSINIT(tty_list, &tty_list_mutex, "ttylist", MTX_DEF);
256 static struct unrhdr *tty_unit;
258 static int drainwait = 5*60;
259 SYSCTL_INT(_kern, OID_AUTO, drainwait, CTLFLAG_RW, &drainwait,
260 0, "Output drain timeout in seconds");
263 tty_gettp(struct cdev *dev)
268 csw = dev_refthread(dev);
269 KASSERT(csw != NULL, ("No cdevsw in ttycode (%s)", devtoname(dev)));
270 KASSERT(csw->d_flags & D_TTY,
271 ("non D_TTY (%s) in tty code", devtoname(dev)));
275 ("no tty pointer on (%s) in tty code", devtoname(dev)));
280 * Initial open of tty, or (re)entry to standard tty line discipline.
283 tty_open(struct cdev *device, struct tty *tp)
290 if (!ISSET(tp->t_state, TS_ISOPEN)) {
292 SET(tp->t_state, TS_ISOPEN);
293 if (ISSET(tp->t_cflag, CLOCAL))
294 SET(tp->t_state, TS_CONNECTED);
295 bzero(&tp->t_winsize, sizeof(tp->t_winsize));
297 /* XXX don't hang forever on output */
298 if (tp->t_timeout < 0)
299 tp->t_timeout = drainwait*hz;
306 * Handle close() on a tty line: flush and set to initial state,
307 * bumping generation number so that pending read/write calls
308 * can detect recycling of the tty.
309 * XXX our caller should have done `spltty(); l_close(); tty_close();'
310 * and l_close() should have flushed, but we repeat the spltty() and
311 * the flush in case there are buggy callers.
314 tty_close(struct tty *tp)
318 funsetown(&tp->t_sigio);
323 ttyflush(tp, FREAD | FWRITE);
324 clist_free_cblocks(&tp->t_canq);
325 clist_free_cblocks(&tp->t_outq);
326 clist_free_cblocks(&tp->t_rawq);
329 tp->t_line = TTYDISC;
332 tp->t_session = NULL;
334 knlist_clear(&tp->t_rsel.si_note, 0);
335 knlist_clear(&tp->t_wsel.si_note, 0);
341 #define FLUSHQ(q) { \
343 ndflush(q, (q)->c_cc); \
346 /* Is 'c' a line delimiter ("break" character)? */
347 #define TTBREAKC(c, lflag) \
348 ((c) == '\n' || (((c) == cc[VEOF] || \
349 (c) == cc[VEOL] || ((c) == cc[VEOL2] && lflag & IEXTEN)) && \
350 (c) != _POSIX_VDISABLE))
353 * Process input of a single character received on a tty.
356 ttyinput(int c, struct tty *tp)
358 tcflag_t iflag, lflag;
363 * If input is pending take it first.
366 if (ISSET(lflag, PENDIN))
371 if (ISSET(lflag, ICANON)) {
381 * Block further input iff:
382 * current input > threshold AND input is available to user program
383 * AND input flow control is enabled and not yet invoked.
384 * The 3 is slop for PARMRK.
387 if (tp->t_rawq.c_cc + tp->t_canq.c_cc > tp->t_ihiwat - 3 &&
388 (!ISSET(lflag, ICANON) || tp->t_canq.c_cc != 0) &&
389 (ISSET(tp->t_cflag, CRTS_IFLOW) || ISSET(iflag, IXOFF)) &&
390 !ISSET(tp->t_state, TS_TBLOCK))
393 /* Handle exceptional conditions (break, parity, framing). */
395 err = (ISSET(c, TTY_ERRORMASK));
397 CLR(c, TTY_ERRORMASK);
398 if (ISSET(err, TTY_BI)) {
399 if (ISSET(iflag, IGNBRK))
401 if (ISSET(iflag, BRKINT)) {
402 ttyflush(tp, FREAD | FWRITE);
403 if (tp->t_pgrp != NULL) {
404 PGRP_LOCK(tp->t_pgrp);
405 pgsignal(tp->t_pgrp, SIGINT, 1);
406 PGRP_UNLOCK(tp->t_pgrp);
410 if (ISSET(iflag, PARMRK))
412 } else if ((ISSET(err, TTY_PE) && ISSET(iflag, INPCK))
413 || ISSET(err, TTY_FE)) {
414 if (ISSET(iflag, IGNPAR))
416 else if (ISSET(iflag, PARMRK)) {
418 if (tp->t_rawq.c_cc + tp->t_canq.c_cc >
421 (void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
422 (void)putc(0 | TTY_QUOTE, &tp->t_rawq);
423 (void)putc(c | TTY_QUOTE, &tp->t_rawq);
430 if (!ISSET(tp->t_state, TS_TYPEN) && ISSET(iflag, ISTRIP))
432 if (!ISSET(lflag, EXTPROC)) {
434 * Check for literal nexting very first
436 if (ISSET(tp->t_state, TS_LNCH)) {
438 CLR(tp->t_state, TS_LNCH);
441 * Scan for special characters. This code
442 * is really just a big case statement with
443 * non-constant cases. The bottom of the
444 * case statement is labeled ``endcase'', so goto
445 * it after a case match, or similar.
449 * Control chars which aren't controlled
450 * by ICANON, ISIG, or IXON.
452 if (ISSET(lflag, IEXTEN)) {
453 if (CCEQ(cc[VLNEXT], c)) {
454 if (ISSET(lflag, ECHO)) {
455 if (ISSET(lflag, ECHOE)) {
456 (void)ttyoutput('^', tp);
457 (void)ttyoutput('\b', tp);
461 SET(tp->t_state, TS_LNCH);
464 if (CCEQ(cc[VDISCARD], c)) {
465 if (ISSET(lflag, FLUSHO))
466 CLR(tp->t_lflag, FLUSHO);
468 ttyflush(tp, FWRITE);
470 if (tp->t_rawq.c_cc + tp->t_canq.c_cc)
472 SET(tp->t_lflag, FLUSHO);
480 if (ISSET(lflag, ISIG)) {
481 if (CCEQ(cc[VINTR], c) || CCEQ(cc[VQUIT], c)) {
482 if (!ISSET(lflag, NOFLSH))
483 ttyflush(tp, FREAD | FWRITE);
485 if (tp->t_pgrp != NULL) {
486 PGRP_LOCK(tp->t_pgrp);
488 CCEQ(cc[VINTR], c) ? SIGINT : SIGQUIT, 1);
489 PGRP_UNLOCK(tp->t_pgrp);
493 if (CCEQ(cc[VSUSP], c)) {
494 if (!ISSET(lflag, NOFLSH))
497 if (tp->t_pgrp != NULL) {
498 PGRP_LOCK(tp->t_pgrp);
499 pgsignal(tp->t_pgrp, SIGTSTP, 1);
500 PGRP_UNLOCK(tp->t_pgrp);
506 * Handle start/stop characters.
508 if (ISSET(iflag, IXON)) {
509 if (CCEQ(cc[VSTOP], c)) {
510 if (!ISSET(tp->t_state, TS_TTSTOP)) {
511 SET(tp->t_state, TS_TTSTOP);
515 if (!CCEQ(cc[VSTART], c))
518 * if VSTART == VSTOP then toggle
522 if (CCEQ(cc[VSTART], c))
526 * IGNCR, ICRNL, & INLCR
529 if (ISSET(iflag, IGNCR))
531 else if (ISSET(iflag, ICRNL))
533 } else if (c == '\n' && ISSET(iflag, INLCR))
536 if (!ISSET(tp->t_lflag, EXTPROC) && ISSET(lflag, ICANON)) {
538 * From here on down canonical mode character
539 * processing takes place.
542 * erase or erase2 (^H / ^?)
544 if (CCEQ(cc[VERASE], c) || CCEQ(cc[VERASE2], c) ) {
546 ttyrub(unputc(&tp->t_rawq), tp);
552 if (CCEQ(cc[VKILL], c)) {
553 if (ISSET(lflag, ECHOKE) &&
554 tp->t_rawq.c_cc == tp->t_rocount &&
555 !ISSET(lflag, ECHOPRT))
556 while (tp->t_rawq.c_cc)
557 ttyrub(unputc(&tp->t_rawq), tp);
560 if (ISSET(lflag, ECHOK) ||
561 ISSET(lflag, ECHOKE))
566 CLR(tp->t_state, TS_LOCAL);
572 if (CCEQ(cc[VWERASE], c) && ISSET(lflag, IEXTEN)) {
578 while ((c = unputc(&tp->t_rawq)) == ' ' || c == '\t')
583 * erase last char of word and remember the
584 * next chars type (for ALTWERASE)
587 c = unputc(&tp->t_rawq);
590 if (c == ' ' || c == '\t') {
591 (void)putc(c, &tp->t_rawq);
600 c = unputc(&tp->t_rawq);
603 } while (c != ' ' && c != '\t' &&
604 (!ISSET(lflag, ALTWERASE) || ISALPHA(c) == ctype));
605 (void)putc(c, &tp->t_rawq);
611 if (CCEQ(cc[VREPRINT], c) && ISSET(lflag, IEXTEN)) {
616 * ^T - kernel info and generate SIGINFO
618 if (CCEQ(cc[VSTATUS], c) && ISSET(lflag, IEXTEN)) {
619 if (ISSET(lflag, ISIG) && tp->t_pgrp != NULL) {
620 PGRP_LOCK(tp->t_pgrp);
621 pgsignal(tp->t_pgrp, SIGINFO, 1);
622 PGRP_UNLOCK(tp->t_pgrp);
624 if (!ISSET(lflag, NOKERNINFO))
630 * Check for input buffer overflow
632 if (tp->t_rawq.c_cc + tp->t_canq.c_cc >= MAX_INPUT) {
634 if (ISSET(iflag, IMAXBEL)) {
635 if (tp->t_outq.c_cc < tp->t_ohiwat)
636 (void)ttyoutput(CTRL('g'), tp);
641 if ( c == 0377 && ISSET(iflag, PARMRK) && !ISSET(iflag, ISTRIP)
642 && ISSET(iflag, IGNBRK|IGNPAR) != (IGNBRK|IGNPAR))
643 (void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
646 * Put data char in q for user and
647 * wakeup on seeing a line delimiter.
649 if (putc(c, &tp->t_rawq) >= 0) {
650 if (!ISSET(lflag, ICANON)) {
655 if (TTBREAKC(c, lflag)) {
657 catq(&tp->t_rawq, &tp->t_canq);
659 } else if (tp->t_rocount++ == 0)
660 tp->t_rocol = tp->t_column;
661 if (ISSET(tp->t_state, TS_ERASE)) {
663 * end of prterase \.../
665 CLR(tp->t_state, TS_ERASE);
666 (void)ttyoutput('/', tp);
670 if (CCEQ(cc[VEOF], c) && ISSET(lflag, ECHO)) {
672 * Place the cursor over the '^' of the ^D.
674 i = imin(2, tp->t_column - i);
676 (void)ttyoutput('\b', tp);
683 * IXANY means allow any character to restart output.
685 if (ISSET(tp->t_state, TS_TTSTOP) &&
686 !ISSET(iflag, IXANY) && cc[VSTART] != cc[VSTOP])
689 CLR(tp->t_lflag, FLUSHO);
690 CLR(tp->t_state, TS_TTSTOP);
692 return (ttstart(tp));
696 * Output a single character on a tty, doing output processing
697 * as needed (expanding tabs, newline processing, etc.).
698 * Returns < 0 if succeeds, otherwise returns char to resend.
702 ttyoutput(int c, struct tty *tp)
708 if (!ISSET(oflag, OPOST)) {
709 if (ISSET(tp->t_lflag, FLUSHO))
711 if (putc(c, &tp->t_outq))
718 * Do tab expansion if OXTABS is set. Special case if we external
719 * processing, we don't do the tab expansion because we'll probably
720 * get it wrong. If tab expansion needs to be done, let it happen
723 CLR(c, ~TTY_CHARMASK);
725 ISSET(oflag, OXTABS) && !ISSET(tp->t_lflag, EXTPROC)) {
726 c = 8 - (tp->t_column & 7);
727 if (!ISSET(tp->t_lflag, FLUSHO)) {
728 s = spltty(); /* Don't interrupt tabs. */
729 c -= b_to_q(" ", c, &tp->t_outq);
735 return (c ? -1 : '\t');
737 if (c == CEOT && ISSET(oflag, ONOEOT))
741 * Newline translation: if ONLCR is set,
742 * translate newline into "\r\n".
744 if (c == '\n' && ISSET(tp->t_oflag, ONLCR)) {
747 if (!ISSET(tp->t_lflag, FLUSHO) && putc('\r', &tp->t_outq))
750 /* If OCRNL is set, translate "\r" into "\n". */
751 else if (c == '\r' && ISSET(tp->t_oflag, OCRNL))
753 /* If ONOCR is set, don't transmit CRs when on column 0. */
754 else if (c == '\r' && ISSET(tp->t_oflag, ONOCR) && tp->t_column == 0)
759 if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
771 if (ISSET(tp->t_oflag, ONLCR | ONLRET))
781 col = (col + 8) & ~7;
789 * Ioctls for all tty devices. Called after line-discipline specific ioctl
790 * has been called to do discipline-specific functions and/or reject any
791 * of these ioctl commands.
795 ttioctl(struct tty *tp, u_long cmd, void *data, int flag)
800 int s, error, bits, sig, sig2;
802 td = curthread; /* XXX */
805 /* If the ioctl involves modification, hang if in the background. */
829 #if defined(COMPAT_43TTY)
839 sx_slock(&proctree_lock);
841 while (isbackground(p, tp) && !(p->p_flag & P_PPWAIT) &&
842 !SIGISMEMBER(p->p_sigacts->ps_sigignore, SIGTTOU) &&
843 !SIGISMEMBER(td->td_sigmask, SIGTTOU)) {
846 if (pgrp->pg_jobc == 0) {
847 sx_sunlock(&proctree_lock);
851 sx_sunlock(&proctree_lock);
852 pgsignal(pgrp, SIGTTOU, 1);
854 error = ttysleep(tp, &lbolt, TTOPRI | PCATCH, "ttybg1",
858 sx_slock(&proctree_lock);
862 sx_sunlock(&proctree_lock);
867 if (tp->t_modem != NULL) {
870 tt_modem(tp, SER_DTR, 0);
873 tt_modem(tp, 0, SER_DTR);
877 sig = (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1;
878 sig2 = ((~bits) & (TIOCM_DTR | TIOCM_RTS)) >> 1;
879 tt_modem(tp, sig, sig2);
883 sig = (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1;
884 tt_modem(tp, sig, 0);
888 sig = (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1;
889 tt_modem(tp, 0, sig);
892 sig = tt_modem(tp, 0, 0);
893 /* See <sys/serial.h. for the "<< 1" stuff */
894 bits = TIOCM_LE + (sig << 1);
902 if (tp->t_pps != NULL) {
903 error = pps_ioctl(cmd, data, tp->t_pps);
904 if (error != ENOIOCTL)
908 switch (cmd) { /* Process the ioctl. */
909 case FIOASYNC: /* set/clear async i/o */
912 SET(tp->t_state, TS_ASYNC);
914 CLR(tp->t_state, TS_ASYNC);
917 case FIONBIO: /* set/clear non-blocking i/o */
918 break; /* XXX: delete. */
919 case FIONREAD: /* get # bytes to read */
921 *(int *)data = ttnread(tp);
927 * Policy -- Don't allow FIOSETOWN on someone else's
930 if (tp->t_session != NULL && !isctty(p, tp))
933 error = fsetown(*(int *)data, &tp->t_sigio);
938 if (tp->t_session != NULL && !isctty(p, tp))
940 *(int *)data = fgetown(&tp->t_sigio);
943 case TIOCEXCL: /* set exclusive use of tty */
945 SET(tp->t_state, TS_XCLUDE);
948 case TIOCFLUSH: { /* flush buffers */
949 int flags = *(int *)data;
952 flags = FREAD | FWRITE;
954 flags &= FREAD | FWRITE;
958 case TIOCCONS: /* become virtual console */
960 struct nameidata nid;
962 if (constty && constty != tp &&
963 ISSET(constty->t_state, TS_CONNECTED))
966 /* Ensure user can open the real console. */
967 NDINIT(&nid, LOOKUP, LOCKLEAF | FOLLOW, UIO_SYSSPACE,
969 if ((error = namei(&nid)) != 0)
971 NDFREE(&nid, NDF_ONLY_PNBUF);
972 error = VOP_ACCESS(nid.ni_vp, VREAD, td->td_ucred, td);
978 } else if (tp == constty)
981 case TIOCDRAIN: /* wait till output drained */
986 case TIOCGETA: { /* get termios struct */
987 struct termios *t = (struct termios *)data;
989 bcopy(&tp->t_termios, t, sizeof(struct termios));
992 case TIOCGETD: /* get line discipline */
993 *(int *)data = tp->t_line;
995 case TIOCGWINSZ: /* get window size */
996 *(struct winsize *)data = tp->t_winsize;
998 case TIOCGPGRP: /* get pgrp of tty */
1001 *(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
1004 case TIOCHPCL: /* hang up on last close */
1006 SET(tp->t_cflag, HUPCL);
1011 *(int *)data = tp->t_dtr_wait * 100 / hz;
1014 /* must be root since the wait applies to following logins */
1018 tp->t_dtr_wait = *(int *)data * hz / 100;
1020 case TIOCNXCL: /* reset exclusive use of tty */
1022 CLR(tp->t_state, TS_XCLUDE);
1025 case TIOCOUTQ: /* output queue size */
1026 *(int *)data = tp->t_outq.c_cc;
1028 case TIOCSETA: /* set termios struct */
1029 case TIOCSETAW: /* drain output, set */
1030 case TIOCSETAF: { /* drn out, fls in, set */
1031 struct termios *t = (struct termios *)data;
1033 if (t->c_ispeed == 0)
1034 t->c_ispeed = t->c_ospeed;
1035 if (t->c_ispeed == 0)
1036 t->c_ispeed = tp->t_ospeed;
1037 if (t->c_ispeed == 0)
1040 if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
1041 error = ttywait(tp);
1046 if (cmd == TIOCSETAF)
1047 ttyflush(tp, FREAD);
1049 if (!ISSET(t->c_cflag, CIGNORE)) {
1051 * Set device hardware.
1053 error = tt_param(tp, t);
1058 if (ISSET(t->c_cflag, CLOCAL) &&
1059 !ISSET(tp->t_cflag, CLOCAL)) {
1061 * XXX disconnections would be too hard to
1062 * get rid of without this kludge. The only
1063 * way to get rid of controlling terminals
1064 * is to exit from the session leader.
1066 CLR(tp->t_state, TS_ZOMBIE);
1068 wakeup(TSA_CARR_ON(tp));
1072 if ((ISSET(tp->t_state, TS_CARR_ON) ||
1073 ISSET(t->c_cflag, CLOCAL)) &&
1074 !ISSET(tp->t_state, TS_ZOMBIE))
1075 SET(tp->t_state, TS_CONNECTED);
1077 CLR(tp->t_state, TS_CONNECTED);
1078 tp->t_cflag = t->c_cflag;
1079 tp->t_ispeed = t->c_ispeed;
1080 if (t->c_ospeed != 0)
1081 tp->t_ospeed = t->c_ospeed;
1084 if (ISSET(t->c_lflag, ICANON) != ISSET(tp->t_lflag, ICANON) &&
1086 if (ISSET(t->c_lflag, ICANON))
1087 SET(tp->t_lflag, PENDIN);
1090 * XXX we really shouldn't allow toggling
1091 * ICANON while we're in a non-termios line
1092 * discipline. Now we have to worry about
1093 * panicing for a null queue.
1095 if (tp->t_canq.c_cbreserved > 0 &&
1096 tp->t_rawq.c_cbreserved > 0) {
1097 catq(&tp->t_rawq, &tp->t_canq);
1099 * XXX the queue limits may be
1100 * different, so the old queue
1101 * swapping method no longer works.
1103 catq(&tp->t_canq, &tp->t_rawq);
1105 CLR(tp->t_lflag, PENDIN);
1109 tp->t_iflag = t->c_iflag;
1110 tp->t_oflag = t->c_oflag;
1112 * Make the EXTPROC bit read only.
1114 if (ISSET(tp->t_lflag, EXTPROC))
1115 SET(t->c_lflag, EXTPROC);
1117 CLR(t->c_lflag, EXTPROC);
1118 tp->t_lflag = t->c_lflag | ISSET(tp->t_lflag, PENDIN);
1119 if (t->c_cc[VMIN] != tp->t_cc[VMIN] ||
1120 t->c_cc[VTIME] != tp->t_cc[VTIME])
1122 bcopy(t->c_cc, tp->t_cc, sizeof(t->c_cc));
1126 case TIOCSETD: { /* set line discipline */
1127 int t = *(int *)data;
1129 if ((u_int)t >= nlinesw)
1131 if (t == tp->t_line)
1134 ttyld_close(tp, flag);
1136 /* XXX: we should use the correct cdev here */
1137 error = ttyld_open(tp, tp->t_dev);
1140 * If we fail to switch line discipline we cannot
1141 * fall back to the previous, because we can not
1142 * trust that ldisc to open successfully either.
1143 * Fall back to the default ldisc which we know
1144 * will allways succeed.
1146 tp->t_line = TTYDISC;
1147 (void)ttyld_open(tp, tp->t_dev);
1153 case TIOCSTART: /* start output, like ^Q */
1155 if (ISSET(tp->t_state, TS_TTSTOP) ||
1156 ISSET(tp->t_lflag, FLUSHO)) {
1157 CLR(tp->t_lflag, FLUSHO);
1158 CLR(tp->t_state, TS_TTSTOP);
1163 case TIOCSTI: /* simulate terminal input */
1164 if ((flag & FREAD) == 0 && suser(td))
1166 if (!isctty(p, tp) && suser(td))
1169 ttyld_rint(tp, *(u_char *)data);
1172 case TIOCSTOP: /* stop output, like ^S */
1174 if (!ISSET(tp->t_state, TS_TTSTOP)) {
1175 SET(tp->t_state, TS_TTSTOP);
1180 case TIOCSCTTY: /* become controlling tty */
1181 /* Session ctty vnode pointer set in vnode layer. */
1182 sx_slock(&proctree_lock);
1183 if (!SESS_LEADER(p) ||
1184 ((p->p_session->s_ttyvp || tp->t_session) &&
1185 (tp->t_session != p->p_session))) {
1186 sx_sunlock(&proctree_lock);
1189 tp->t_session = p->p_session;
1190 tp->t_pgrp = p->p_pgrp;
1191 SESS_LOCK(p->p_session);
1192 ttyref(tp); /* ttyrel(): kern_proc.c:pgdelete() */
1193 p->p_session->s_ttyp = tp;
1194 SESS_UNLOCK(p->p_session);
1196 p->p_flag |= P_CONTROLT;
1198 sx_sunlock(&proctree_lock);
1200 case TIOCSPGRP: { /* set pgrp of tty */
1201 sx_slock(&proctree_lock);
1202 pgrp = pgfind(*(int *)data);
1203 if (!isctty(p, tp)) {
1206 sx_sunlock(&proctree_lock);
1210 sx_sunlock(&proctree_lock);
1214 if (pgrp->pg_session != p->p_session) {
1215 sx_sunlock(&proctree_lock);
1218 sx_sunlock(&proctree_lock);
1222 case TIOCSTAT: /* simulate control-T */
1227 case TIOCSWINSZ: /* set window size */
1228 if (bcmp((caddr_t)&tp->t_winsize, data,
1229 sizeof (struct winsize))) {
1230 tp->t_winsize = *(struct winsize *)data;
1231 if (tp->t_pgrp != NULL) {
1232 PGRP_LOCK(tp->t_pgrp);
1233 pgsignal(tp->t_pgrp, SIGWINCH, 1);
1234 PGRP_UNLOCK(tp->t_pgrp);
1238 case TIOCSDRAINWAIT:
1242 tp->t_timeout = *(int *)data * hz;
1243 wakeup(TSA_OCOMPLETE(tp));
1244 wakeup(TSA_OLOWAT(tp));
1246 case TIOCGDRAINWAIT:
1247 *(int *)data = tp->t_timeout / hz;
1250 return (tt_break(tp, 1));
1252 return (tt_break(tp, 0));
1254 #if defined(COMPAT_43TTY)
1255 return (ttcompat(tp, cmd, data, flag));
1264 ttypoll(struct cdev *dev, int events, struct thread *td)
1270 tp = tty_gettp(dev);
1272 if (tp == NULL) /* XXX used to return ENXIO, but that means true! */
1273 return ((events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM))
1277 if (events & (POLLIN | POLLRDNORM)) {
1278 if (ISSET(tp->t_state, TS_ZOMBIE))
1279 revents |= (events & (POLLIN | POLLRDNORM)) |
1281 else if (ttnread(tp) > 0)
1282 revents |= events & (POLLIN | POLLRDNORM);
1284 selrecord(td, &tp->t_rsel);
1286 if (events & POLLOUT) {
1287 if (ISSET(tp->t_state, TS_ZOMBIE))
1289 else if (tp->t_outq.c_cc <= tp->t_olowat &&
1290 ISSET(tp->t_state, TS_CONNECTED))
1291 revents |= events & POLLOUT;
1293 selrecord(td, &tp->t_wsel);
1299 static struct filterops ttyread_filtops =
1300 { 1, NULL, filt_ttyrdetach, filt_ttyread };
1301 static struct filterops ttywrite_filtops =
1302 { 1, NULL, filt_ttywdetach, filt_ttywrite };
1305 ttykqfilter(struct cdev *dev, struct knote *kn)
1308 struct knlist *klist;
1311 tp = tty_gettp(dev);
1313 switch (kn->kn_filter) {
1315 klist = &tp->t_rsel.si_note;
1316 kn->kn_fop = &ttyread_filtops;
1319 klist = &tp->t_wsel.si_note;
1320 kn->kn_fop = &ttywrite_filtops;
1326 kn->kn_hook = (caddr_t)dev;
1329 knlist_add(klist, kn, 0);
1336 filt_ttyrdetach(struct knote *kn)
1338 struct tty *tp = ((struct cdev *)kn->kn_hook)->si_tty;
1341 knlist_remove(&tp->t_rsel.si_note, kn, 0);
1346 filt_ttyread(struct knote *kn, long hint)
1348 struct tty *tp = ((struct cdev *)kn->kn_hook)->si_tty;
1350 kn->kn_data = ttnread(tp);
1351 if (ISSET(tp->t_state, TS_ZOMBIE)) {
1352 kn->kn_flags |= EV_EOF;
1355 return (kn->kn_data > 0);
1359 filt_ttywdetach(struct knote *kn)
1361 struct tty *tp = ((struct cdev *)kn->kn_hook)->si_tty;
1364 knlist_remove(&tp->t_wsel.si_note, kn, 0);
1369 filt_ttywrite(struct knote *kn, long hint)
1371 struct tty *tp = ((struct cdev *)kn->kn_hook)->si_tty;
1373 kn->kn_data = tp->t_outq.c_cc;
1374 if (ISSET(tp->t_state, TS_ZOMBIE))
1376 return (kn->kn_data <= tp->t_olowat &&
1377 ISSET(tp->t_state, TS_CONNECTED));
1381 * Must be called at spltty().
1384 ttnread(struct tty *tp)
1388 if (ISSET(tp->t_lflag, PENDIN))
1390 nread = tp->t_canq.c_cc;
1391 if (!ISSET(tp->t_lflag, ICANON)) {
1392 nread += tp->t_rawq.c_cc;
1393 if (nread < tp->t_cc[VMIN] && tp->t_cc[VTIME] == 0)
1400 * Wait for output to drain.
1403 ttywait(struct tty *tp)
1409 while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1410 ISSET(tp->t_state, TS_CONNECTED) && tp->t_oproc) {
1412 if ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1413 ISSET(tp->t_state, TS_CONNECTED)) {
1414 SET(tp->t_state, TS_SO_OCOMPLETE);
1415 error = ttysleep(tp, TSA_OCOMPLETE(tp),
1416 TTOPRI | PCATCH, "ttywai",
1419 if (error == EWOULDBLOCK)
1426 if (!error && (tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)))
1433 * Flush if successfully wait.
1436 ttywflush(struct tty *tp)
1440 if ((error = ttywait(tp)) == 0)
1441 ttyflush(tp, FREAD);
1446 * Flush tty read and/or write queues, notifying anyone waiting.
1449 ttyflush(struct tty *tp, int rw)
1458 FLUSHQ(&tp->t_outq);
1459 CLR(tp->t_state, TS_TTSTOP);
1463 FLUSHQ(&tp->t_canq);
1464 FLUSHQ(&tp->t_rawq);
1465 CLR(tp->t_lflag, PENDIN);
1468 CLR(tp->t_state, TS_LOCAL);
1470 if (ISSET(tp->t_state, TS_TBLOCK)) {
1472 FLUSHQ(&tp->t_outq);
1476 * Don't let leave any state that might clobber the
1477 * next line discipline (although we should do more
1478 * to send the START char). Not clearing the state
1479 * may have caused the "putc to a clist with no
1480 * reserved cblocks" panic/printf.
1482 CLR(tp->t_state, TS_TBLOCK);
1484 #if 0 /* forget it, sleeping isn't always safe and we don't know when it is */
1485 if (ISSET(tp->t_iflag, IXOFF)) {
1487 * XXX wait a bit in the hope that the stop
1488 * character (if any) will go out. Waiting
1489 * isn't good since it allows races. This
1490 * will be fixed when the stop character is
1491 * put in a special queue. Don't bother with
1492 * the checks in ttywait() since the timeout
1495 SET(tp->t_state, TS_SO_OCOMPLETE);
1496 ttysleep(tp, TSA_OCOMPLETE(tp), TTOPRI,
1499 * Don't try sending the stop character again.
1501 CLR(tp->t_state, TS_TBLOCK);
1508 FLUSHQ(&tp->t_outq);
1515 * Copy in the default termios characters.
1518 termioschars(struct termios *t)
1521 bcopy(ttydefchars, t->c_cc, sizeof t->c_cc);
1528 ttychars(struct tty *tp)
1531 termioschars(&tp->t_termios);
1535 * Handle input high water. Send stop character for the IXOFF case. Turn
1536 * on our input flow control bit and propagate the changes to the driver.
1537 * XXX the stop character should be put in a special high priority queue.
1540 ttyblock(struct tty *tp)
1543 SET(tp->t_state, TS_TBLOCK);
1544 if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
1545 putc(tp->t_cc[VSTOP], &tp->t_outq) != 0)
1546 CLR(tp->t_state, TS_TBLOCK); /* try again later */
1551 * Handle input low water. Send start character for the IXOFF case. Turn
1552 * off our input flow control bit and propagate the changes to the driver.
1553 * XXX the start character should be put in a special high priority queue.
1556 ttyunblock(struct tty *tp)
1559 CLR(tp->t_state, TS_TBLOCK);
1560 if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTART] != _POSIX_VDISABLE &&
1561 putc(tp->t_cc[VSTART], &tp->t_outq) != 0)
1562 SET(tp->t_state, TS_TBLOCK); /* try again later */
1567 /* Not used by any current (i386) drivers. */
1569 * Restart after an inter-char delay.
1572 ttrstrt(void *tp_arg)
1577 KASSERT(tp_arg != NULL, ("ttrstrt"));
1582 CLR(tp->t_state, TS_TIMEOUT);
1590 ttstart(struct tty *tp)
1598 * "close" a line discipline
1601 ttylclose(struct tty *tp, int flag)
1604 if (flag & FNONBLOCK || ttywflush(tp))
1605 ttyflush(tp, FREAD | FWRITE);
1610 * Handle modem control transition on a tty.
1611 * Flag indicates new state of carrier.
1612 * Returns 0 if the line should be turned off, otherwise 1.
1615 ttymodem(struct tty *tp, int flag)
1618 if (ISSET(tp->t_state, TS_CARR_ON) && ISSET(tp->t_cflag, MDMBUF)) {
1620 * MDMBUF: do flow control according to carrier flag
1621 * XXX TS_CAR_OFLOW doesn't do anything yet. TS_TTSTOP
1622 * works if IXON and IXANY are clear.
1625 CLR(tp->t_state, TS_CAR_OFLOW);
1626 CLR(tp->t_state, TS_TTSTOP);
1628 } else if (!ISSET(tp->t_state, TS_CAR_OFLOW)) {
1629 SET(tp->t_state, TS_CAR_OFLOW);
1630 SET(tp->t_state, TS_TTSTOP);
1633 } else if (flag == 0) {
1637 CLR(tp->t_state, TS_CARR_ON);
1638 if (ISSET(tp->t_state, TS_ISOPEN) &&
1639 !ISSET(tp->t_cflag, CLOCAL)) {
1640 SET(tp->t_state, TS_ZOMBIE);
1641 CLR(tp->t_state, TS_CONNECTED);
1642 if (tp->t_session) {
1643 sx_slock(&proctree_lock);
1644 if (tp->t_session->s_leader) {
1647 p = tp->t_session->s_leader;
1652 sx_sunlock(&proctree_lock);
1654 ttyflush(tp, FREAD | FWRITE);
1661 SET(tp->t_state, TS_CARR_ON);
1662 if (!ISSET(tp->t_state, TS_ZOMBIE))
1663 SET(tp->t_state, TS_CONNECTED);
1664 wakeup(TSA_CARR_ON(tp));
1672 * Reinput pending characters after state switch
1676 ttypend(struct tty *tp)
1681 CLR(tp->t_lflag, PENDIN);
1682 SET(tp->t_state, TS_TYPEN);
1684 * XXX this assumes too much about clist internals. It may even
1685 * fail if the cblock slush pool is empty. We can't allocate more
1686 * cblocks here because we are called from an interrupt handler
1687 * and clist_alloc_cblocks() can wait.
1690 bzero(&tp->t_rawq, sizeof tp->t_rawq);
1691 tp->t_rawq.c_cbmax = tq.c_cbmax;
1692 tp->t_rawq.c_cbreserved = tq.c_cbreserved;
1693 while ((c = getc(&tq)) >= 0)
1695 CLR(tp->t_state, TS_TYPEN);
1699 * Process a read call on a tty device.
1702 ttread(struct tty *tp, struct uio *uio, int flag)
1707 cc_t *cc = tp->t_cc;
1710 int s, first, error = 0;
1711 int has_stime = 0, last_cc = 0;
1712 long slp = 0; /* XXX this should be renamed `timo'. */
1713 struct timeval stime;
1720 lflag = tp->t_lflag;
1722 * take pending input first
1724 if (ISSET(lflag, PENDIN)) {
1726 splx(s); /* reduce latency */
1728 lflag = tp->t_lflag; /* XXX ttypend() clobbers it */
1732 * Hang process if it's in the background.
1734 if (isbackground(p, tp)) {
1736 sx_slock(&proctree_lock);
1738 if (SIGISMEMBER(p->p_sigacts->ps_sigignore, SIGTTIN) ||
1739 SIGISMEMBER(td->td_sigmask, SIGTTIN) ||
1740 (p->p_flag & P_PPWAIT) || p->p_pgrp->pg_jobc == 0) {
1742 sx_sunlock(&proctree_lock);
1748 sx_sunlock(&proctree_lock);
1749 pgsignal(pg, SIGTTIN, 1);
1751 error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, "ttybg2", 0);
1757 if (ISSET(tp->t_state, TS_ZOMBIE)) {
1759 return (0); /* EOF */
1763 * If canonical, use the canonical queue,
1764 * else use the raw queue.
1766 * (should get rid of clists...)
1768 qp = ISSET(lflag, ICANON) ? &tp->t_canq : &tp->t_rawq;
1770 if (flag & IO_NDELAY) {
1773 if (!ISSET(lflag, ICANON) && cc[VMIN] == 0) {
1778 return (EWOULDBLOCK);
1780 if (!ISSET(lflag, ICANON)) {
1783 struct timeval timecopy;
1786 * Check each of the four combinations.
1787 * (m > 0 && t == 0) is the normal read case.
1788 * It should be fairly efficient, so we check that and its
1789 * companion case (m == 0 && t == 0) first.
1790 * For the other two cases, we compute the target sleep time
1799 /* m, t and qp->c_cc are all 0. 0 is enough input. */
1803 t *= 100000; /* time in us */
1804 #define diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 1000000 + \
1805 ((t1).tv_usec - (t2).tv_usec))
1811 getmicrotime(&timecopy);
1813 /* first character, start timer */
1817 } else if (qp->c_cc > last_cc) {
1818 /* got a character, restart timer */
1822 /* nothing, check expiration */
1823 slp = t - diff(timecopy, stime);
1828 } else { /* m == 0 */
1831 getmicrotime(&timecopy);
1837 slp = t - diff(timecopy, stime);
1839 /* Timed out, but 0 is enough input. */
1847 struct timeval tv; /* XXX style bug. */
1849 tv.tv_sec = slp / 1000000;
1850 tv.tv_usec = slp % 1000000;
1853 * XXX bad variable names. slp was the timeout in
1854 * usec. Now it is the timeout in ticks.
1859 if (qp->c_cc <= 0) {
1862 * There is no input, or not enough input and we can block.
1864 error = ttysleep(tp, TSA_HUP_OR_INPUT(tp), TTIPRI | PCATCH,
1865 ISSET(tp->t_state, TS_CONNECTED) ?
1866 "ttyin" : "ttyhup", (int)slp);
1868 if (error == EWOULDBLOCK)
1873 * XXX what happens if another process eats some input
1874 * while we are asleep (not just here)? It would be
1875 * safest to detect changes and reset our state variables
1876 * (has_stime and last_cc).
1884 * Input present, check for input mapping and processing.
1887 if (ISSET(lflag, ICANON | ISIG))
1893 icc = imin(uio->uio_resid, IBUFSIZ);
1894 icc = q_to_b(qp, ibuf, icc);
1900 error = uiomove(ibuf, icc, uio);
1902 * XXX if there was an error then we should ungetc() the
1903 * unmoved chars and reduce icc here.
1907 if (uio->uio_resid == 0)
1921 * delayed suspend (^Y)
1923 if (CCEQ(cc[VDSUSP], c) &&
1924 ISSET(lflag, IEXTEN | ISIG) == (IEXTEN | ISIG)) {
1925 if (tp->t_pgrp != NULL) {
1926 PGRP_LOCK(tp->t_pgrp);
1927 pgsignal(tp->t_pgrp, SIGTSTP, 1);
1928 PGRP_UNLOCK(tp->t_pgrp);
1931 error = ttysleep(tp, &lbolt, TTIPRI | PCATCH,
1940 * Interpret EOF only in canonical mode.
1942 if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
1945 * Give user character.
1947 error = ureadc(c, uio);
1949 /* XXX should ungetc(c, qp). */
1951 if (uio->uio_resid == 0)
1954 * In canonical mode check for a "break character"
1955 * marking the end of a "line of input".
1957 if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
1964 * Look to unblock input now that (presumably)
1965 * the input queue has gone down.
1968 if (ISSET(tp->t_state, TS_TBLOCK) &&
1969 tp->t_rawq.c_cc + tp->t_canq.c_cc <= tp->t_ilowat)
1977 * Check the output queue on tp for space for a kernel message (from uprintf
1978 * or tprintf). Allow some space over the normal hiwater mark so we don't
1979 * lose messages due to normal flow control, but don't let the tty run amok.
1980 * Sleeps here are not interruptible, but we return prematurely if new signals
1984 ttycheckoutq(struct tty *tp, int wait)
1993 hiwat = tp->t_ohiwat;
1994 SIGEMPTYSET(oldmask);
1998 oldmask = td->td_siglist;
2001 if (tp->t_outq.c_cc > hiwat + OBUFSIZ + 100)
2002 while (tp->t_outq.c_cc > hiwat) {
2004 if (tp->t_outq.c_cc <= hiwat)
2011 if (!SIGSETEQ(td->td_siglist, oldmask)) {
2017 SET(tp->t_state, TS_SO_OLOWAT);
2018 tsleep(TSA_OLOWAT(tp), PZERO - 1, "ttoutq", hz);
2025 * Process a write call on a tty device.
2028 ttwrite(struct tty *tp, struct uio *uio, int flag)
2034 int i, hiwat, cnt, error, s;
2037 hiwat = tp->t_ohiwat;
2038 cnt = uio->uio_resid;
2045 if (ISSET(tp->t_state, TS_ZOMBIE)) {
2047 if (uio->uio_resid == cnt)
2051 if (!ISSET(tp->t_state, TS_CONNECTED)) {
2052 if (flag & IO_NDELAY) {
2054 error = EWOULDBLOCK;
2057 error = ttysleep(tp, TSA_CARR_ON(tp), TTIPRI | PCATCH,
2066 * Hang the process if it's in the background.
2068 sx_slock(&proctree_lock);
2070 if (isbackground(p, tp) &&
2071 ISSET(tp->t_lflag, TOSTOP) && !(p->p_flag & P_PPWAIT) &&
2072 !SIGISMEMBER(p->p_sigacts->ps_sigignore, SIGTTOU) &&
2073 !SIGISMEMBER(td->td_sigmask, SIGTTOU)) {
2074 if (p->p_pgrp->pg_jobc == 0) {
2076 sx_sunlock(&proctree_lock);
2081 PGRP_LOCK(p->p_pgrp);
2082 sx_sunlock(&proctree_lock);
2083 pgsignal(p->p_pgrp, SIGTTOU, 1);
2084 PGRP_UNLOCK(p->p_pgrp);
2085 error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, "ttybg4", 0);
2091 sx_sunlock(&proctree_lock);
2094 * Process the user's data in at most OBUFSIZ chunks. Perform any
2095 * output translation. Keep track of high water mark, sleep on
2096 * overflow awaiting device aid in acquiring new space.
2098 while (uio->uio_resid > 0 || cc > 0) {
2099 if (ISSET(tp->t_lflag, FLUSHO)) {
2103 if (tp->t_outq.c_cc > hiwat)
2106 * Grab a hunk of data from the user, unless we have some
2107 * leftover from last time.
2110 cc = imin(uio->uio_resid, OBUFSIZ);
2112 error = uiomove(cp, cc, uio);
2119 * If nothing fancy need be done, grab those characters we
2120 * can handle without any of ttyoutput's processing and
2121 * just transfer them to the output q. For those chars
2122 * which require special processing (as indicated by the
2123 * bits in char_type), call ttyoutput. After processing
2124 * a hunk of data, look for FLUSHO so ^O's will take effect
2128 if (!ISSET(tp->t_oflag, OPOST))
2131 ce = cc - scanc((u_int)cc, (u_char *)cp,
2132 char_type, CCLASSMASK);
2134 * If ce is zero, then we're processing
2135 * a special character through ttyoutput.
2139 if (ttyoutput(*cp, tp) >= 0) {
2140 /* No Clists, wait a bit. */
2142 if (flag & IO_NDELAY) {
2143 error = EWOULDBLOCK;
2146 error = ttysleep(tp, &lbolt,
2155 if (ISSET(tp->t_lflag, FLUSHO) ||
2156 tp->t_outq.c_cc > hiwat)
2162 * A bunch of normal characters have been found.
2163 * Transfer them en masse to the output queue and
2164 * continue processing at the top of the loop.
2165 * If there are any further characters in this
2166 * <= OBUFSIZ chunk, the first should be a character
2167 * requiring special handling by ttyoutput.
2170 i = b_to_q(cp, ce, &tp->t_outq);
2173 cp += ce, cc -= ce, tk_nout += ce;
2176 /* No Clists, wait a bit. */
2178 if (flag & IO_NDELAY) {
2179 error = EWOULDBLOCK;
2182 error = ttysleep(tp, &lbolt, TTOPRI | PCATCH,
2188 if (ISSET(tp->t_lflag, FLUSHO) ||
2189 tp->t_outq.c_cc > hiwat)
2196 * If cc is nonzero, we leave the uio structure inconsistent, as the
2197 * offset and iov pointers have moved forward, but it doesn't matter
2198 * (the call will either return short or restart with a new uio).
2200 uio->uio_resid += cc;
2207 * This can only occur if FLUSHO is set in t_lflag,
2208 * or if ttstart/oproc is synchronous (or very fast).
2210 if (tp->t_outq.c_cc <= hiwat) {
2214 if (flag & IO_NDELAY) {
2216 uio->uio_resid += cc;
2217 return (uio->uio_resid == cnt ? EWOULDBLOCK : 0);
2219 SET(tp->t_state, TS_SO_OLOWAT);
2220 error = ttysleep(tp, TSA_OLOWAT(tp), TTOPRI | PCATCH, "ttywri",
2223 if (error == EWOULDBLOCK)
2231 * Rubout one character from the rawq of tp
2232 * as cleanly as possible.
2235 ttyrub(int c, struct tty *tp)
2241 if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
2243 CLR(tp->t_lflag, FLUSHO);
2244 if (ISSET(tp->t_lflag, ECHOE)) {
2245 if (tp->t_rocount == 0) {
2247 * Screwed by ttwrite; retype
2252 if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
2255 CLR(c, ~TTY_CHARMASK);
2256 switch (CCLASS(c)) {
2265 if (ISSET(tp->t_lflag, ECHOCTL))
2269 if (tp->t_rocount < tp->t_rawq.c_cc) {
2274 savecol = tp->t_column;
2275 SET(tp->t_state, TS_CNTTB);
2276 SET(tp->t_lflag, FLUSHO);
2277 tp->t_column = tp->t_rocol;
2278 cp = tp->t_rawq.c_cf;
2280 tabc = *cp; /* XXX FIX NEXTC */
2281 for (; cp; cp = nextc(&tp->t_rawq, cp, &tabc))
2283 CLR(tp->t_lflag, FLUSHO);
2284 CLR(tp->t_state, TS_CNTTB);
2287 /* savecol will now be length of the tab. */
2288 savecol -= tp->t_column;
2289 tp->t_column += savecol;
2291 savecol = 8; /* overflow screw */
2292 while (--savecol >= 0)
2293 (void)ttyoutput('\b', tp);
2296 #define PANICSTR "ttyrub: would panic c = %d, val = %d\n"
2297 (void)printf(PANICSTR, c, CCLASS(c));
2299 panic(PANICSTR, c, CCLASS(c));
2303 } else if (ISSET(tp->t_lflag, ECHOPRT)) {
2304 if (!ISSET(tp->t_state, TS_ERASE)) {
2305 SET(tp->t_state, TS_ERASE);
2306 (void)ttyoutput('\\', tp);
2310 ttyecho(tp->t_cc[VERASE], tp);
2312 * This code may be executed not only when an ERASE key
2313 * is pressed, but also when ^U (KILL) or ^W (WERASE) are.
2314 * So, I didn't think it was worthwhile to pass the extra
2315 * information (which would need an extra parameter,
2316 * changing every call) needed to distinguish the ERASE2
2317 * case from the ERASE.
2324 * Back over cnt characters, erasing them.
2327 ttyrubo(struct tty *tp, int cnt)
2331 (void)ttyoutput('\b', tp);
2332 (void)ttyoutput(' ', tp);
2333 (void)ttyoutput('\b', tp);
2339 * Reprint the rawq line. Note, it is assumed that c_cc has already
2343 ttyretype(struct tty *tp)
2348 /* Echo the reprint character. */
2349 if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
2350 ttyecho(tp->t_cc[VREPRINT], tp);
2352 (void)ttyoutput('\n', tp);
2356 * FIX: NEXTC IS BROKEN - DOESN'T CHECK QUOTE
2357 * BIT OF FIRST CHAR.
2360 for (cp = tp->t_canq.c_cf, c = (cp != NULL ? *cp : 0);
2361 cp != NULL; cp = nextc(&tp->t_canq, cp, &c))
2363 for (cp = tp->t_rawq.c_cf, c = (cp != NULL ? *cp : 0);
2364 cp != NULL; cp = nextc(&tp->t_rawq, cp, &c))
2366 CLR(tp->t_state, TS_ERASE);
2369 tp->t_rocount = tp->t_rawq.c_cc;
2374 * Echo a typed character to the terminal.
2377 ttyecho(int c, struct tty *tp)
2380 if (!ISSET(tp->t_state, TS_CNTTB))
2381 CLR(tp->t_lflag, FLUSHO);
2382 if ((!ISSET(tp->t_lflag, ECHO) &&
2383 (c != '\n' || !ISSET(tp->t_lflag, ECHONL))) ||
2384 ISSET(tp->t_lflag, EXTPROC))
2386 if (ISSET(tp->t_lflag, ECHOCTL) &&
2387 ((ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n') ||
2388 ISSET(c, TTY_CHARMASK) == 0177)) {
2389 (void)ttyoutput('^', tp);
2390 CLR(c, ~TTY_CHARMASK);
2396 (void)ttyoutput(c, tp);
2400 * Wake up any readers on a tty.
2403 ttwakeup(struct tty *tp)
2406 if (SEL_WAITING(&tp->t_rsel))
2407 selwakeuppri(&tp->t_rsel, TTIPRI);
2408 if (ISSET(tp->t_state, TS_ASYNC) && tp->t_sigio != NULL)
2409 pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
2410 wakeup(TSA_HUP_OR_INPUT(tp));
2411 KNOTE_UNLOCKED(&tp->t_rsel.si_note, 0);
2415 * Wake up any writers on a tty.
2418 ttwwakeup(struct tty *tp)
2421 if (SEL_WAITING(&tp->t_wsel) && tp->t_outq.c_cc <= tp->t_olowat)
2422 selwakeuppri(&tp->t_wsel, TTOPRI);
2423 if (ISSET(tp->t_state, TS_ASYNC) && tp->t_sigio != NULL)
2424 pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
2425 if (ISSET(tp->t_state, TS_BUSY | TS_SO_OCOMPLETE) ==
2426 TS_SO_OCOMPLETE && tp->t_outq.c_cc == 0) {
2427 CLR(tp->t_state, TS_SO_OCOMPLETE);
2428 wakeup(TSA_OCOMPLETE(tp));
2430 if (ISSET(tp->t_state, TS_SO_OLOWAT) &&
2431 tp->t_outq.c_cc <= tp->t_olowat) {
2432 CLR(tp->t_state, TS_SO_OLOWAT);
2433 wakeup(TSA_OLOWAT(tp));
2435 KNOTE_UNLOCKED(&tp->t_wsel.si_note, 0);
2439 * Look up a code for a specified speed in a conversion table;
2440 * used by drivers to map software speed values to hardware parameters.
2443 ttspeedtab(int speed, struct speedtab *table)
2446 for ( ; table->sp_speed != -1; table++)
2447 if (table->sp_speed == speed)
2448 return (table->sp_code);
2453 * Set input and output watermarks and buffer sizes. For input, the
2454 * high watermark is about one second's worth of input above empty, the
2455 * low watermark is slightly below high water, and the buffer size is a
2456 * driver-dependent amount above high water. For output, the watermarks
2457 * are near the ends of the buffer, with about 1 second's worth of input
2458 * between them. All this only applies to the standard line discipline.
2461 ttsetwater(struct tty *tp)
2463 int cps, ttmaxhiwat, x;
2466 clist_alloc_cblocks(&tp->t_canq, TTYHOG, 512);
2467 switch (tp->t_ispeedwat) {
2469 cps = tp->t_ispeed / 10;
2473 * This case is for old drivers that don't know about
2474 * t_ispeedwat. Arrange for them to get the old buffer
2475 * sizes and watermarks.
2477 cps = TTYHOG - 2 * 256;
2478 tp->t_ififosize = 2 * 256;
2481 cps = tp->t_ispeedwat / 10;
2485 tp->t_ilowat = 7 * cps / 8;
2486 x = cps + tp->t_ififosize;
2487 clist_alloc_cblocks(&tp->t_rawq, x, x);
2490 switch (tp->t_ospeedwat) {
2492 cps = tp->t_ospeed / 10;
2493 ttmaxhiwat = 2 * TTMAXHIWAT;
2496 cps = tp->t_ospeed / 10;
2497 ttmaxhiwat = TTMAXHIWAT;
2500 cps = tp->t_ospeedwat / 10;
2501 ttmaxhiwat = 8 * TTMAXHIWAT;
2504 #define CLAMP(x, h, l) ((x) > h ? h : ((x) < l) ? l : (x))
2505 tp->t_olowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
2507 x = CLAMP(x, ttmaxhiwat, TTMINHIWAT); /* XXX clamps are too magic */
2508 tp->t_ohiwat = roundup(x, CBSIZE); /* XXX for compat */
2509 x = imax(tp->t_ohiwat, TTMAXHIWAT); /* XXX for compat/safety */
2511 clist_alloc_cblocks(&tp->t_outq, x, x);
2516 * Report on state of foreground process group.
2519 ttyinfo(struct tty *tp)
2521 struct timeval utime, stime;
2522 struct proc *p, *pick;
2524 const char *stateprefix, *state;
2528 char comm[MAXCOMLEN + 1];
2530 if (ttycheckoutq(tp,0) == 0)
2533 /* Print load average. */
2534 load = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
2535 ttyprintf(tp, "load: %d.%02d ", load / 100, load % 100);
2538 * On return following a ttyprintf(), we set tp->t_rocount to 0 so
2539 * that pending input will be retyped on BS.
2541 if (tp->t_session == NULL) {
2542 ttyprintf(tp, "not a controlling terminal\n");
2546 if (tp->t_pgrp == NULL) {
2547 ttyprintf(tp, "no foreground process group\n");
2551 PGRP_LOCK(tp->t_pgrp);
2552 if (LIST_EMPTY(&tp->t_pgrp->pg_members)) {
2553 PGRP_UNLOCK(tp->t_pgrp);
2554 ttyprintf(tp, "empty foreground process group\n");
2560 * Pick the most interesting process and copy some of its
2561 * state for printing later. sched_lock must be held for
2562 * most parts of this. Holding it throughout is simplest
2563 * and prevents even unimportant inconsistencies in the
2564 * copy of the state, but may increase interrupt latency
2568 mtx_lock_spin(&sched_lock);
2569 LIST_FOREACH(p, &tp->t_pgrp->pg_members, p_pglist)
2570 if (proc_compare(pick, p))
2573 td = FIRST_THREAD_IN_PROC(pick); /* XXXKSE */
2575 KASSERT(td != NULL, ("ttyinfo: no thread"));
2578 mtx_unlock_spin(&sched_lock);
2579 PGRP_UNLOCK(tp->t_pgrp);
2580 ttyprintf(tp, "foreground process without thread\n");
2586 if (TD_IS_RUNNING(td))
2588 else if (TD_ON_RUNQ(td) || TD_CAN_RUN(td))
2590 else if (TD_IS_SLEEPING(td)) {
2591 /* XXX: If we're sleeping, are we ever not in a queue? */
2592 if (TD_ON_SLEEPQ(td))
2593 state = td->td_wmesg;
2595 state = "sleeping without queue";
2596 } else if (TD_ON_LOCK(td)) {
2597 state = td->td_lockname;
2599 } else if (TD_IS_SUSPENDED(td))
2600 state = "suspended";
2601 else if (TD_AWAITING_INTR(td))
2605 pctcpu = (sched_pctcpu(td) * 10000 + FSCALE / 2) >> FSHIFT;
2606 if (pick->p_state == PRS_NEW || pick->p_state == PRS_ZOMBIE)
2609 rss = pgtok(vmspace_resident_count(pick->p_vmspace));
2610 mtx_unlock_spin(&sched_lock);
2612 PGRP_UNLOCK(tp->t_pgrp);
2613 calcru(pick, &utime, &stime);
2615 bcopy(pick->p_comm, comm, sizeof(comm));
2618 /* Print command, pid, state, utime, stime, %cpu, and rss. */
2620 " cmd: %s %d [%s%s] %ld.%02ldu %ld.%02lds %d%% %ldk\n",
2621 comm, pid, stateprefix, state,
2622 (long)utime.tv_sec, utime.tv_usec / 10000,
2623 (long)stime.tv_sec, stime.tv_usec / 10000,
2629 * Returns 1 if p2 is "better" than p1
2631 * The algorithm for picking the "interesting" process is thus:
2633 * 1) Only foreground processes are eligible - implied.
2634 * 2) Runnable processes are favored over anything else. The runner
2635 * with the highest cpu utilization is picked (p_estcpu). Ties are
2636 * broken by picking the highest pid.
2637 * 3) The sleeper with the shortest sleep time is next. With ties,
2638 * we pick out just "short-term" sleepers (P_SINTR == 0).
2639 * 4) Further ties are broken by picking the highest pid.
2641 #define ISRUN(p, val) \
2643 struct thread *td; \
2645 FOREACH_THREAD_IN_PROC(p, td) { \
2646 if (TD_ON_RUNQ(td) || \
2647 TD_IS_RUNNING(td)) { \
2654 #define TESTAB(a, b) ((a)<<1 | (b))
2660 proc_compare(struct proc *p1, struct proc *p2)
2665 mtx_assert(&sched_lock, MA_OWNED);
2673 * see if at least one of them is runnable
2675 switch (TESTAB(esta, estb)) {
2682 * tie - favor one with highest recent cpu utilization
2685 FOREACH_KSEGRP_IN_PROC(p1,kg) {
2686 esta += kg->kg_estcpu;
2688 FOREACH_KSEGRP_IN_PROC(p2,kg) {
2689 estb += kg->kg_estcpu;
2695 return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
2700 switch (TESTAB(p1->p_state == PRS_ZOMBIE, p2->p_state == PRS_ZOMBIE)) {
2706 return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
2711 * pick the one with the smallest sleep time
2713 if (p2->p_slptime > p1->p_slptime)
2715 if (p1->p_slptime > p2->p_slptime)
2718 * favor one sleeping in a non-interruptible sleep
2720 if (p1->p_sflag & PS_SINTR && (p2->p_sflag & PS_SINTR) == 0)
2722 if (p2->p_sflag & PS_SINTR && (p1->p_sflag & PS_SINTR) == 0)
2725 return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
2729 * Output char to tty; console putchar style.
2732 tputchar(int c, struct tty *tp)
2737 if (!ISSET(tp->t_state, TS_CONNECTED)) {
2742 (void)ttyoutput('\r', tp);
2743 (void)ttyoutput(c, tp);
2750 * Sleep on chan, returning ERESTART if tty changed while we napped and
2751 * returning any errors (e.g. EINTR/EWOULDBLOCK) reported by tsleep. If
2752 * the tty is revoked, restarting a pending call will redo validation done
2753 * at the start of the call.
2756 ttysleep(struct tty *tp, void *chan, int pri, char *wmesg, int timo)
2762 error = tsleep(chan, pri, wmesg, timo);
2763 if (tp->t_state & TS_GONE)
2767 return (tp->t_gen == gen ? 0 : ERESTART);
2771 * Gain a reference to a TTY
2774 ttyref(struct tty *tp)
2778 mtx_lock(&tp->t_mtx);
2779 KASSERT(tp->t_refcnt > 0,
2780 ("ttyref(): tty refcnt is %d (%s)",
2781 tp->t_refcnt, tp->t_dev != NULL ? devtoname(tp->t_dev) : "??"));
2783 mtx_unlock(&tp->t_mtx);
2788 * Drop a reference to a TTY.
2789 * When reference count drops to zero, we free it.
2792 ttyrel(struct tty *tp)
2796 mtx_lock(&tty_list_mutex);
2797 mtx_lock(&tp->t_mtx);
2798 KASSERT(tp->t_refcnt > 0,
2799 ("ttyrel(): tty refcnt is %d (%s)",
2800 tp->t_refcnt, tp->t_dev != NULL ? devtoname(tp->t_dev) : "??"));
2803 mtx_unlock(&tp->t_mtx);
2804 mtx_unlock(&tty_list_mutex);
2807 TAILQ_REMOVE(&tty_list, tp, t_list);
2808 mtx_unlock(&tp->t_mtx);
2809 mtx_unlock(&tty_list_mutex);
2810 knlist_destroy(&tp->t_rsel.si_note);
2811 knlist_destroy(&tp->t_wsel.si_note);
2812 mtx_destroy(&tp->t_mtx);
2818 * Allocate a tty struct. Clists in the struct will be allocated by
2826 tp = malloc(sizeof *tp, M_TTYS, M_WAITOK | M_ZERO);
2827 mtx_init(&tp->t_mtx, "tty", NULL, MTX_DEF);
2830 * Set up the initial state
2834 tp->t_dtr_wait = 3 * hz;
2836 ttyinitmode(tp, 0, 0);
2837 bcopy(ttydefchars, tp->t_init_in.c_cc, sizeof tp->t_init_in.c_cc);
2839 /* Make callout the same as callin */
2840 tp->t_init_out = tp->t_init_in;
2842 mtx_lock(&tty_list_mutex);
2843 TAILQ_INSERT_TAIL(&tty_list, tp, t_list);
2844 mtx_unlock(&tty_list_mutex);
2845 knlist_init(&tp->t_rsel.si_note, &tp->t_mtx, NULL, NULL, NULL);
2846 knlist_init(&tp->t_wsel.si_note, &tp->t_mtx, NULL, NULL, NULL);
2851 ttypurge(struct cdev *dev)
2854 if (dev->si_tty == NULL)
2856 ttygone(dev->si_tty);
2862 * Create the device entries for this tty thereby opening it for business.
2864 * The flags argument controls if "cua" units are created.
2866 * The t_sc filed is copied to si_drv1 in the created cdevs. This
2867 * is particularly important for ->t_cioctl() users.
2869 * XXX: implement the init and lock devices by cloning.
2873 ttycreate(struct tty *tp, int flags, const char *fmt, ...)
2875 char namebuf[SPECNAMELEN - 3]; /* XXX space for "tty" */
2876 struct cdevsw *csw = NULL;
2880 int i, minor, sminor, sunit;
2882 mtx_assert(&Giant, MA_OWNED);
2884 if (tty_unit == NULL)
2885 tty_unit = new_unrhdr(0, 0xffff, NULL);
2887 sunit = alloc_unr(tty_unit);
2888 tp->t_devunit = sunit;
2894 KASSERT(csw->d_purge == NULL || csw->d_purge == ttypurge,
2895 ("tty should not have d_purge"));
2897 csw->d_purge = ttypurge;
2899 minor = unit2minor(unit);
2900 sminor = unit2minor(sunit);
2902 i = vsnrprintf(namebuf, sizeof namebuf, 32, fmt, ap);
2904 KASSERT(i < sizeof namebuf, ("Too long tty name (%s)", namebuf));
2906 cp = make_dev(csw, minor,
2907 UID_ROOT, GID_WHEEL, 0600, "tty%s", namebuf);
2911 cp->si_drv1 = tp->t_sc;
2913 cp = make_dev(&ttys_cdevsw, sminor | MINOR_INIT,
2914 UID_ROOT, GID_WHEEL, 0600, "tty%s.init", namebuf);
2915 dev_depends(tp->t_dev, cp);
2916 cp->si_drv1 = tp->t_sc;
2917 cp->si_drv2 = &tp->t_init_in;
2920 cp = make_dev(&ttys_cdevsw, sminor | MINOR_LOCK,
2921 UID_ROOT, GID_WHEEL, 0600, "tty%s.lock", namebuf);
2922 dev_depends(tp->t_dev, cp);
2923 cp->si_drv1 = tp->t_sc;
2924 cp->si_drv2 = &tp->t_lock_in;
2927 if (flags & TS_CALLOUT) {
2928 cp = make_dev(csw, minor | MINOR_CALLOUT,
2929 UID_UUCP, GID_DIALER, 0660, "cua%s", namebuf);
2930 dev_depends(tp->t_dev, cp);
2931 cp->si_drv1 = tp->t_sc;
2934 cp = make_dev(&ttys_cdevsw, sminor | MINOR_CALLOUT | MINOR_INIT,
2935 UID_UUCP, GID_DIALER, 0660, "cua%s.init", namebuf);
2936 dev_depends(tp->t_dev, cp);
2937 cp->si_drv1 = tp->t_sc;
2938 cp->si_drv2 = &tp->t_init_out;
2941 cp = make_dev(&ttys_cdevsw, sminor | MINOR_CALLOUT | MINOR_LOCK,
2942 UID_UUCP, GID_DIALER, 0660, "cua%s.lock", namebuf);
2943 dev_depends(tp->t_dev, cp);
2944 cp->si_drv1 = tp->t_sc;
2945 cp->si_drv2 = &tp->t_lock_out;
2953 * This function is called when the hardware disappears. We set a flag
2954 * and wake up stuff so all sleeping threads will notice.
2957 ttygone(struct tty *tp)
2960 tp->t_state |= TS_GONE;
2961 wakeup(&tp->t_dtr_wait);
2962 wakeup(TSA_CARR_ON(tp));
2963 wakeup(TSA_HUP_OR_INPUT(tp));
2964 wakeup(TSA_OCOMPLETE(tp));
2965 wakeup(TSA_OLOWAT(tp));
2972 * Called when the driver is ready to free the tty structure.
2974 * XXX: This shall sleep until all threads have left the driver.
2978 ttyfree(struct tty *tp)
2982 mtx_assert(&Giant, MA_OWNED);
2984 unit = tp->t_devunit;
2985 destroy_dev(tp->t_mdev);
2986 free_unr(tty_unit, unit);
2990 sysctl_kern_ttys(SYSCTL_HANDLER_ARGS)
2992 struct tty *tp, *tp2;
2997 mtx_lock(&tty_list_mutex);
2998 tp = TAILQ_FIRST(&tty_list);
3001 mtx_unlock(&tty_list_mutex);
3002 while (tp != NULL) {
3003 bzero(&xt, sizeof xt);
3004 xt.xt_size = sizeof xt;
3005 #define XT_COPY(field) xt.xt_##field = tp->t_##field
3006 xt.xt_rawcc = tp->t_rawq.c_cc;
3007 xt.xt_cancc = tp->t_canq.c_cc;
3008 xt.xt_outcc = tp->t_outq.c_cc;
3010 if (tp->t_dev != NULL)
3011 xt.xt_dev = dev2udev(tp->t_dev);
3015 if (tp->t_pgrp != NULL)
3016 xt.xt_pgid = tp->t_pgrp->pg_id;
3017 if (tp->t_session != NULL)
3018 xt.xt_sid = tp->t_session->s_sid;
3032 error = SYSCTL_OUT(req, &xt, sizeof xt);
3037 mtx_lock(&tty_list_mutex);
3038 tp2 = TAILQ_NEXT(tp, t_list);
3041 mtx_unlock(&tty_list_mutex);
3048 SYSCTL_PROC(_kern, OID_AUTO, ttys, CTLTYPE_OPAQUE|CTLFLAG_RD,
3049 0, 0, sysctl_kern_ttys, "S,xtty", "All ttys");
3050 SYSCTL_LONG(_kern, OID_AUTO, tty_nin, CTLFLAG_RD,
3051 &tk_nin, 0, "Total TTY in characters");
3052 SYSCTL_LONG(_kern, OID_AUTO, tty_nout, CTLFLAG_RD,
3053 &tk_nout, 0, "Total TTY out characters");
3056 nottystop(struct tty *tp, int rw)
3063 ttyopen(struct cdev *dev, int flag, int mode, struct thread *td)
3072 * We jump to this label after all non-interrupted sleeps to pick
3073 * up any changes of the device state.
3076 if (tp->t_state & TS_GONE)
3078 error = ttydtrwaitsleep(tp);
3081 if (tp->t_state & TS_ISOPEN) {
3083 * The device is open, so everything has been initialized.
3086 if (ISCALLOUT(dev) && !tp->t_actout)
3088 if (tp->t_actout && !ISCALLOUT(dev)) {
3089 if (flag & O_NONBLOCK)
3091 error = tsleep(&tp->t_actout,
3092 TTIPRI | PCATCH, "ttybi", 0);
3093 if (error != 0 || (tp->t_flags & TS_GONE))
3097 if (tp->t_state & TS_XCLUDE && suser(td))
3101 * The device isn't open, so there are no conflicts.
3102 * Initialize it. Initialization is done twice in many
3103 * cases: to preempt sleeping callin opens if we are
3104 * callout, and to complete a callin open after DCD rises.
3106 tp->t_termios = ISCALLOUT(dev) ? tp->t_init_out : tp->t_init_in;
3107 tp->t_cflag = tp->t_termios.c_cflag;
3108 if (tp->t_modem != NULL)
3109 tt_modem(tp, SER_DTR | SER_RTS, 0);
3111 error = tt_param(tp, &tp->t_termios);
3114 error = tt_open(tp, dev);
3117 if (ISCALLOUT(dev) || (tt_modem(tp, 0, 0) & SER_DCD))
3121 * Wait for DCD if necessary.
3123 if (!(tp->t_state & TS_CARR_ON) && !ISCALLOUT(dev)
3124 && !(tp->t_cflag & CLOCAL) && !(flag & O_NONBLOCK)) {
3126 error = tsleep(TSA_CARR_ON(tp), TTIPRI | PCATCH, "ttydcd", 0);
3128 if (error != 0 || (tp->t_state & TS_GONE))
3132 error = ttyld_open(tp, dev);
3134 if (tp->t_state & TS_ISOPEN && ISCALLOUT(dev))
3135 tp->t_actout = TRUE;
3138 if (!(tp->t_state & TS_ISOPEN) && tp->t_wopeners == 0)
3144 ttyclose(struct cdev *dev, int flag, int mode, struct thread *td)
3149 ttyld_close(tp, flag);
3152 tp->t_do_timestamp = 0;
3153 if (tp->t_pps != NULL)
3154 tp->t_pps->ppsparam.mode = 0;
3160 ttyread(struct cdev *dev, struct uio *uio, int flag)
3164 tp = tty_gettp(dev);
3166 if (tp->t_state & TS_GONE)
3168 return (ttyld_read(tp, uio, flag));
3172 ttywrite(struct cdev *dev, struct uio *uio, int flag)
3176 tp = tty_gettp(dev);
3178 if (tp->t_state & TS_GONE)
3180 return (ttyld_write(tp, uio, flag));
3184 ttyioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
3191 if (cmd == TIOCSETA || cmd == TIOCSETAW || cmd == TIOCSETAF) {
3193 struct termios *dt = (struct termios *)data;
3194 struct termios *lt =
3195 ISCALLOUT(dev) ? &tp->t_lock_out : &tp->t_lock_in;
3197 dt->c_iflag = (tp->t_iflag & lt->c_iflag)
3198 | (dt->c_iflag & ~lt->c_iflag);
3199 dt->c_oflag = (tp->t_oflag & lt->c_oflag)
3200 | (dt->c_oflag & ~lt->c_oflag);
3201 dt->c_cflag = (tp->t_cflag & lt->c_cflag)
3202 | (dt->c_cflag & ~lt->c_cflag);
3203 dt->c_lflag = (tp->t_lflag & lt->c_lflag)
3204 | (dt->c_lflag & ~lt->c_lflag);
3205 for (cc = 0; cc < NCCS; ++cc)
3206 if (lt->c_cc[cc] != 0)
3207 dt->c_cc[cc] = tp->t_cc[cc];
3208 if (lt->c_ispeed != 0)
3209 dt->c_ispeed = tp->t_ispeed;
3210 if (lt->c_ospeed != 0)
3211 dt->c_ospeed = tp->t_ospeed;
3214 error = ttyld_ioctl(tp, cmd, data, flag, td);
3215 if (error == ENOIOCTL)
3216 error = ttioctl(tp, cmd, data, flag);
3218 if (error != ENOIOCTL)
3224 ttyldoptim(struct tty *tp)
3229 if (!(t->c_iflag & (ICRNL | IGNCR | IMAXBEL | INLCR | ISTRIP | IXON))
3230 && (!(t->c_iflag & BRKINT) || (t->c_iflag & IGNBRK))
3231 && (!(t->c_iflag & PARMRK)
3232 || (t->c_iflag & (IGNPAR | IGNBRK)) == (IGNPAR | IGNBRK))
3233 && !(t->c_lflag & (ECHO | ICANON | IEXTEN | ISIG | PENDIN))
3234 && linesw[tp->t_line]->l_rint == ttyinput)
3235 tp->t_state |= TS_CAN_BYPASS_L_RINT;
3237 tp->t_state &= ~TS_CAN_BYPASS_L_RINT;
3241 ttydtrwaitwakeup(void *arg)
3246 tp->t_state &= ~TS_DTR_WAIT;
3247 wakeup(&tp->t_dtr_wait);
3252 ttydtrwaitstart(struct tty *tp)
3255 if (tp->t_dtr_wait == 0)
3257 if (tp->t_state & TS_DTR_WAIT)
3259 timeout(ttydtrwaitwakeup, tp, tp->t_dtr_wait);
3260 tp->t_state |= TS_DTR_WAIT;
3264 ttydtrwaitsleep(struct tty *tp)
3269 while (error == 0) {
3270 if (tp->t_state & TS_GONE)
3272 else if (!(tp->t_state & TS_DTR_WAIT))
3275 error = tsleep(&tp->t_dtr_wait, TTIPRI | PCATCH,
3282 ttysopen(struct cdev *dev, int flag, int mode, struct thread *td)
3288 ("ttysopen(): no tty pointer on device (%s)", devtoname(dev)));
3289 if (tp->t_state & TS_GONE)
3295 ttysclose(struct cdev *dev, int flag, int mode, struct thread *td)
3302 ttysrdwr(struct cdev *dev, struct uio *uio, int flag)
3309 ttysioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
3317 ("ttysopen(): no tty pointer on device (%s)", devtoname(dev)));
3318 if (tp->t_state & TS_GONE)
3326 *ct = *(struct termios *)data;
3329 *(struct termios *)data = *ct;
3332 *(int *)data = TTYDISC;
3335 bzero(data, sizeof(struct winsize));
3338 if (tp->t_cioctl != NULL)
3339 return(tp->t_cioctl(dev, cmd, data, flag, td));
3345 * Initialize a tty to sane modes.
3348 ttyinitmode(struct tty *tp, int echo, int speed)
3352 speed = TTYDEF_SPEED;
3353 tp->t_init_in.c_iflag = TTYDEF_IFLAG;
3354 tp->t_init_in.c_oflag = TTYDEF_OFLAG;
3355 tp->t_init_in.c_cflag = TTYDEF_CFLAG;
3357 tp->t_init_in.c_lflag = TTYDEF_LFLAG_ECHO;
3359 tp->t_init_in.c_lflag = TTYDEF_LFLAG_NOECHO;
3361 tp->t_init_in.c_ispeed = tp->t_init_in.c_ospeed = speed;
3362 termioschars(&tp->t_init_in);
3363 tp->t_init_out = tp->t_init_in;
3364 tp->t_termios = tp->t_init_in;
3368 * Use more "normal" termios paramters for consoles.
3371 ttyconsolemode(struct tty *tp, int speed)
3375 speed = TTYDEF_SPEED;
3376 ttyinitmode(tp, 1, speed);
3377 tp->t_init_in.c_cflag |= CLOCAL;
3378 tp->t_lock_out.c_cflag = tp->t_lock_in.c_cflag = CLOCAL;
3379 tp->t_lock_out.c_ispeed = tp->t_lock_out.c_ospeed =
3380 tp->t_lock_in.c_ispeed = tp->t_lock_in.c_ospeed = speed;
3381 tp->t_init_out = tp->t_init_in;
3382 tp->t_termios = tp->t_init_in;
3387 * Record the relationship between the serial ports notion of modem control
3388 * signals and the one used in certain ioctls in a way the compiler can enforce
3389 * XXX: We should define TIOCM_* in terms of SER_ if we can limit the
3390 * XXX: consequences of the #include work that would take.
3392 CTASSERT(SER_DTR == TIOCM_DTR / 2);
3393 CTASSERT(SER_RTS == TIOCM_RTS / 2);
3394 CTASSERT(SER_STX == TIOCM_ST / 2);
3395 CTASSERT(SER_SRX == TIOCM_SR / 2);
3396 CTASSERT(SER_CTS == TIOCM_CTS / 2);
3397 CTASSERT(SER_DCD == TIOCM_DCD / 2);
3398 CTASSERT(SER_RI == TIOCM_RI / 2);
3399 CTASSERT(SER_DSR == TIOCM_DSR / 2);