The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/kern/tty.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    1 /*-
    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.
    9  *
   10  * Copyright (c) 2002 Networks Associates Technologies, Inc.
   11  * All rights reserved.
   12  *
   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.
   17  *
   18  * Redistribution and use in source and binary forms, with or without
   19  * modification, are permitted provided that the following conditions
   20  * are met:
   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.
   29  *
   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
   40  * SUCH DAMAGE.
   41  *
   42  *      @(#)tty.c       8.8 (Berkeley) 1/21/94
   43  */
   44 
   45 /*-
   46  * TODO:
   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
   52  *        FIONREAD.
   53  *      o Do the new sio locking stuff here and use it to avoid special
   54  *        case for EXTPROC?
   55  *      o Lock PENDIN too?
   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
   63  *        discipline.
   64  *      o Now that historical speed conversions are handled here, don't
   65  *        do them in drivers.
   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().
   71  */
   72 
   73 #include <sys/cdefs.h>
   74 __FBSDID("$FreeBSD: releng/6.2/sys/kern/tty.c 165441 2006-12-21 16:25:42Z mbr $");
   75 
   76 #include "opt_compat.h"
   77 #include "opt_tty.h"
   78 
   79 #include <sys/param.h>
   80 #include <sys/systm.h>
   81 #include <sys/filio.h>
   82 #include <sys/lock.h>
   83 #include <sys/mutex.h>
   84 #include <sys/namei.h>
   85 #include <sys/sx.h>
   86 #ifndef BURN_BRIDGES
   87 #if defined(COMPAT_43)
   88 #include <sys/ioctl_compat.h>
   89 #endif
   90 #endif
   91 #include <sys/proc.h>
   92 #define TTYDEFCHARS
   93 #include <sys/tty.h>
   94 #undef  TTYDEFCHARS
   95 #include <sys/fcntl.h>
   96 #include <sys/conf.h>
   97 #include <sys/poll.h>
   98 #include <sys/kernel.h>
   99 #include <sys/vnode.h>
  100 #include <sys/serial.h>
  101 #include <sys/signalvar.h>
  102 #include <sys/resourcevar.h>
  103 #include <sys/malloc.h>
  104 #include <sys/filedesc.h>
  105 #include <sys/sched.h>
  106 #include <sys/sysctl.h>
  107 #include <sys/timepps.h>
  108 
  109 #include <machine/stdarg.h>
  110 
  111 #include <vm/vm.h>
  112 #include <vm/pmap.h>
  113 #include <vm/vm_map.h>
  114 
  115 MALLOC_DEFINE(M_TTYS, "ttys", "tty data structures");
  116 
  117 long tk_cancc;
  118 long tk_nin;
  119 long tk_nout;
  120 long tk_rawcc;
  121 
  122 static  d_open_t        ttysopen;
  123 static  d_close_t       ttysclose;
  124 static  d_read_t        ttysrdwr;
  125 static  d_ioctl_t       ttysioctl;
  126 static  d_purge_t       ttypurge;
  127 
  128 /* Default cdevsw for common tty devices */
  129 static struct cdevsw tty_cdevsw = {
  130         .d_version =    D_VERSION,
  131         .d_open =       ttyopen,
  132         .d_close =      ttyclose,
  133         .d_ioctl =      ttyioctl,
  134         .d_purge =      ttypurge,
  135         .d_name =       "ttydrv",
  136         .d_flags =      D_TTY | D_NEEDGIANT,
  137 };
  138 
  139 /* Cdevsw for slave tty devices */
  140 static struct cdevsw ttys_cdevsw = {
  141         .d_version =    D_VERSION,
  142         .d_open =       ttysopen,
  143         .d_close =      ttysclose,
  144         .d_read =       ttysrdwr,
  145         .d_write =      ttysrdwr,
  146         .d_ioctl =      ttysioctl,
  147         .d_name =       "TTYS",
  148         .d_flags =      D_TTY | D_NEEDGIANT,
  149 };
  150 
  151 static int      proc_compare(struct proc *p1, struct proc *p2);
  152 static int      ttnread(struct tty *tp);
  153 static void     ttyecho(int c, struct tty *tp);
  154 static int      ttyoutput(int c, struct tty *tp);
  155 static void     ttypend(struct tty *tp);
  156 static void     ttyretype(struct tty *tp);
  157 static void     ttyrub(int c, struct tty *tp);
  158 static void     ttyrubo(struct tty *tp, int cnt);
  159 static void     ttyunblock(struct tty *tp);
  160 static int      ttywflush(struct tty *tp);
  161 static int      filt_ttyread(struct knote *kn, long hint);
  162 static void     filt_ttyrdetach(struct knote *kn);
  163 static int      filt_ttywrite(struct knote *kn, long hint);
  164 static void     filt_ttywdetach(struct knote *kn);
  165 
  166 /*
  167  * Table with character classes and parity. The 8th bit indicates parity,
  168  * the 7th bit indicates the character is an alphameric or underscore (for
  169  * ALTWERASE), and the low 6 bits indicate delay type.  If the low 6 bits
  170  * are 0 then the character needs no special processing on output; classes
  171  * other than 0 might be translated or (not currently) require delays.
  172  */
  173 #define E       0x00    /* Even parity. */
  174 #define O       0x80    /* Odd parity. */
  175 #define PARITY(c)       (char_type[c] & O)
  176 
  177 #define ALPHA   0x40    /* Alpha or underscore. */
  178 #define ISALPHA(c)      (char_type[(c) & TTY_CHARMASK] & ALPHA)
  179 
  180 #define CCLASSMASK      0x3f
  181 #define CCLASS(c)       (char_type[c] & CCLASSMASK)
  182 
  183 #define BS      BACKSPACE
  184 #define CC      CONTROL
  185 #define CR      RETURN
  186 #define NA      ORDINARY | ALPHA
  187 #define NL      NEWLINE
  188 #define NO      ORDINARY
  189 #define TB      TAB
  190 #define VT      VTAB
  191 
  192 static u_char const char_type[] = {
  193         E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC, /* nul - bel */
  194         O|BS, E|TB, E|NL, O|CC, E|VT, O|CR, O|CC, E|CC, /* bs - si */
  195         O|CC, E|CC, E|CC, O|CC, E|CC, O|CC, O|CC, E|CC, /* dle - etb */
  196         E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC, /* can - us */
  197         O|NO, E|NO, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* sp - ' */
  198         E|NO, O|NO, O|NO, E|NO, O|NO, E|NO, E|NO, O|NO, /* ( - / */
  199         E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* 0 - 7 */
  200         O|NA, E|NA, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* 8 - ? */
  201         O|NO, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* @ - G */
  202         E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* H - O */
  203         E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* P - W */
  204         O|NA, E|NA, E|NA, O|NO, E|NO, O|NO, O|NO, O|NA, /* X - _ */
  205         E|NO, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* ` - g */
  206         O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* h - o */
  207         O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* p - w */
  208         E|NA, O|NA, O|NA, E|NO, O|NO, E|NO, E|NO, O|CC, /* x - del */
  209         /*
  210          * Meta chars; should be settable per character set;
  211          * for now, treat them all as normal characters.
  212          */
  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,
  227         NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
  228         NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
  229 };
  230 #undef  BS
  231 #undef  CC
  232 #undef  CR
  233 #undef  NA
  234 #undef  NL
  235 #undef  NO
  236 #undef  TB
  237 #undef  VT
  238 
  239 /* Macros to clear/set/test flags. */
  240 #define SET(t, f)       (t) |= (f)
  241 #define CLR(t, f)       (t) &= ~(f)
  242 #define ISSET(t, f)     ((t) & (f))
  243 
  244 #undef MAX_INPUT                /* XXX wrong in <sys/syslimits.h> */
  245 #define MAX_INPUT       TTYHOG  /* XXX limit is usually larger for !ICANON */
  246 
  247 /*
  248  * list of struct tty where pstat(8) can pick it up with sysctl
  249  *
  250  * The lock order is to grab the list mutex before the tty mutex.
  251  * Together with additions going on the tail of the list, this allows
  252  * the sysctl to avoid doing retries.
  253  */
  254 static  TAILQ_HEAD(, tty) tty_list = TAILQ_HEAD_INITIALIZER(tty_list);
  255 static struct mtx tty_list_mutex;
  256 
  257 static struct unrhdr *tty_unit;
  258 
  259 static int  drainwait = 5*60;
  260 SYSCTL_INT(_kern, OID_AUTO, drainwait, CTLFLAG_RW, &drainwait,
  261         0, "Output drain timeout in seconds");
  262 
  263 static struct tty *
  264 tty_gettp(struct cdev *dev)
  265 {
  266         struct tty *tp;
  267         struct cdevsw *csw;
  268 
  269         csw = dev_refthread(dev);
  270         KASSERT(csw != NULL, ("No cdevsw in ttycode (%s)", devtoname(dev)));
  271         KASSERT(csw->d_flags & D_TTY,
  272             ("non D_TTY (%s) in tty code", devtoname(dev)));
  273         dev_relthread(dev);
  274         tp = dev->si_tty;
  275         KASSERT(tp != NULL,
  276             ("no tty pointer on (%s) in tty code", devtoname(dev)));
  277         return (tp);
  278 }
  279 
  280 /*
  281  * Initial open of tty, or (re)entry to standard tty line discipline.
  282  */
  283 int
  284 tty_open(struct cdev *device, struct tty *tp)
  285 {
  286         int s;
  287 
  288         s = spltty();
  289         tp->t_dev = device;
  290         tp->t_hotchar = 0;
  291         if (!ISSET(tp->t_state, TS_ISOPEN)) {
  292                 ttyref(tp);
  293                 SET(tp->t_state, TS_ISOPEN);
  294                 if (ISSET(tp->t_cflag, CLOCAL))
  295                         SET(tp->t_state, TS_CONNECTED);
  296                 bzero(&tp->t_winsize, sizeof(tp->t_winsize));
  297         }
  298         /* XXX don't hang forever on output */
  299         if (tp->t_timeout < 0)
  300                 tp->t_timeout = drainwait*hz;
  301         ttsetwater(tp);
  302         splx(s);
  303         return (0);
  304 }
  305 
  306 /*
  307  * Handle close() on a tty line: flush and set to initial state,
  308  * bumping generation number so that pending read/write calls
  309  * can detect recycling of the tty.
  310  * XXX our caller should have done `spltty(); l_close(); tty_close();'
  311  * and l_close() should have flushed, but we repeat the spltty() and
  312  * the flush in case there are buggy callers.
  313  */
  314 int
  315 tty_close(struct tty *tp)
  316 {
  317         int ostate, s;
  318 
  319         funsetown(&tp->t_sigio);
  320         s = spltty();
  321         if (constty == tp)
  322                 constty_clear();
  323 
  324         ttyflush(tp, FREAD | FWRITE);
  325         clist_free_cblocks(&tp->t_canq);
  326         clist_free_cblocks(&tp->t_outq);
  327         clist_free_cblocks(&tp->t_rawq);
  328 
  329         tp->t_gen++;
  330         tp->t_line = TTYDISC;
  331         tp->t_hotchar = 0;
  332         tp->t_pgrp = NULL;
  333         tp->t_session = NULL;
  334         ostate = tp->t_state;
  335         tp->t_state = 0;
  336         knlist_clear(&tp->t_rsel.si_note, 0);
  337         knlist_clear(&tp->t_wsel.si_note, 0);
  338         /*
  339          * Both final close and revocation close might end up calling
  340          * this method.  Only the thread clearing TS_ISOPEN should
  341          * release the reference to the tty.
  342          */
  343         if (ISSET(ostate, TS_ISOPEN))
  344                 ttyrel(tp);
  345         splx(s);
  346         return (0);
  347 }
  348 
  349 #define FLUSHQ(q) {                                                     \
  350         if ((q)->c_cc)                                                  \
  351                 ndflush(q, (q)->c_cc);                                  \
  352 }
  353 
  354 /* Is 'c' a line delimiter ("break" character)? */
  355 #define TTBREAKC(c, lflag)                                                      \
  356         ((c) == '\n' || (((c) == cc[VEOF] ||                            \
  357           (c) == cc[VEOL] || ((c) == cc[VEOL2] && lflag & IEXTEN)) &&   \
  358          (c) != _POSIX_VDISABLE))
  359 
  360 /*
  361  * Process input of a single character received on a tty.
  362  */
  363 int
  364 ttyinput(int c, struct tty *tp)
  365 {
  366         tcflag_t iflag, lflag;
  367         cc_t *cc;
  368         int i, err;
  369 
  370         /*
  371          * If input is pending take it first.
  372          */
  373         lflag = tp->t_lflag;
  374         if (ISSET(lflag, PENDIN))
  375                 ttypend(tp);
  376         /*
  377          * Gather stats.
  378          */
  379         if (ISSET(lflag, ICANON)) {
  380                 ++tk_cancc;
  381                 ++tp->t_cancc;
  382         } else {
  383                 ++tk_rawcc;
  384                 ++tp->t_rawcc;
  385         }
  386         ++tk_nin;
  387 
  388         /*
  389          * Block further input iff:
  390          * current input > threshold AND input is available to user program
  391          * AND input flow control is enabled and not yet invoked.
  392          * The 3 is slop for PARMRK.
  393          */
  394         iflag = tp->t_iflag;
  395         if (tp->t_rawq.c_cc + tp->t_canq.c_cc > tp->t_ihiwat - 3 &&
  396             (!ISSET(lflag, ICANON) || tp->t_canq.c_cc != 0) &&
  397             (ISSET(tp->t_cflag, CRTS_IFLOW) || ISSET(iflag, IXOFF)) &&
  398             !ISSET(tp->t_state, TS_TBLOCK))
  399                 ttyblock(tp);
  400 
  401         /* Handle exceptional conditions (break, parity, framing). */
  402         cc = tp->t_cc;
  403         err = (ISSET(c, TTY_ERRORMASK));
  404         if (err) {
  405                 CLR(c, TTY_ERRORMASK);
  406                 if (ISSET(err, TTY_BI)) {
  407                         if (ISSET(iflag, IGNBRK))
  408                                 return (0);
  409                         if (ISSET(iflag, BRKINT)) {
  410                                 ttyflush(tp, FREAD | FWRITE);
  411                                 if (tp->t_pgrp != NULL) {
  412                                         PGRP_LOCK(tp->t_pgrp);
  413                                         pgsignal(tp->t_pgrp, SIGINT, 1);
  414                                         PGRP_UNLOCK(tp->t_pgrp);
  415                                 }
  416                                 goto endcase;
  417                         }
  418                         if (ISSET(iflag, PARMRK))
  419                                 goto parmrk;
  420                 } else if ((ISSET(err, TTY_PE) && ISSET(iflag, INPCK))
  421                         || ISSET(err, TTY_FE)) {
  422                         if (ISSET(iflag, IGNPAR))
  423                                 return (0);
  424                         else if (ISSET(iflag, PARMRK)) {
  425 parmrk:
  426                                 if (tp->t_rawq.c_cc + tp->t_canq.c_cc >
  427                                     MAX_INPUT - 3)
  428                                         goto input_overflow;
  429                                 (void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
  430                                 (void)putc(0 | TTY_QUOTE, &tp->t_rawq);
  431                                 (void)putc(c | TTY_QUOTE, &tp->t_rawq);
  432                                 goto endcase;
  433                         } else
  434                                 c = 0;
  435                 }
  436         }
  437 
  438         if (!ISSET(tp->t_state, TS_TYPEN) && ISSET(iflag, ISTRIP))
  439                 CLR(c, 0x80);
  440         if (!ISSET(lflag, EXTPROC)) {
  441                 /*
  442                  * Check for literal nexting very first
  443                  */
  444                 if (ISSET(tp->t_state, TS_LNCH)) {
  445                         SET(c, TTY_QUOTE);
  446                         CLR(tp->t_state, TS_LNCH);
  447                 }
  448                 /*
  449                  * Scan for special characters.  This code
  450                  * is really just a big case statement with
  451                  * non-constant cases.  The bottom of the
  452                  * case statement is labeled ``endcase'', so goto
  453                  * it after a case match, or similar.
  454                  */
  455 
  456                 /*
  457                  * Control chars which aren't controlled
  458                  * by ICANON, ISIG, or IXON.
  459                  */
  460                 if (ISSET(lflag, IEXTEN)) {
  461                         if (CCEQ(cc[VLNEXT], c)) {
  462                                 if (ISSET(lflag, ECHO)) {
  463                                         if (ISSET(lflag, ECHOE)) {
  464                                                 (void)ttyoutput('^', tp);
  465                                                 (void)ttyoutput('\b', tp);
  466                                         } else
  467                                                 ttyecho(c, tp);
  468                                 }
  469                                 SET(tp->t_state, TS_LNCH);
  470                                 goto endcase;
  471                         }
  472                         if (CCEQ(cc[VDISCARD], c)) {
  473                                 if (ISSET(lflag, FLUSHO))
  474                                         CLR(tp->t_lflag, FLUSHO);
  475                                 else {
  476                                         ttyflush(tp, FWRITE);
  477                                         ttyecho(c, tp);
  478                                         if (tp->t_rawq.c_cc + tp->t_canq.c_cc)
  479                                                 ttyretype(tp);
  480                                         SET(tp->t_lflag, FLUSHO);
  481                                 }
  482                                 goto startoutput;
  483                         }
  484                 }
  485                 /*
  486                  * Signals.
  487                  */
  488                 if (ISSET(lflag, ISIG)) {
  489                         if (CCEQ(cc[VINTR], c) || CCEQ(cc[VQUIT], c)) {
  490                                 if (!ISSET(lflag, NOFLSH))
  491                                         ttyflush(tp, FREAD | FWRITE);
  492                                 ttyecho(c, tp);
  493                                 if (tp->t_pgrp != NULL) {
  494                                         PGRP_LOCK(tp->t_pgrp);
  495                                         pgsignal(tp->t_pgrp,
  496                                             CCEQ(cc[VINTR], c) ? SIGINT : SIGQUIT, 1);
  497                                         PGRP_UNLOCK(tp->t_pgrp);
  498                                 }
  499                                 goto endcase;
  500                         }
  501                         if (CCEQ(cc[VSUSP], c)) {
  502                                 if (!ISSET(lflag, NOFLSH))
  503                                         ttyflush(tp, FREAD);
  504                                 ttyecho(c, tp);
  505                                 if (tp->t_pgrp != NULL) {
  506                                         PGRP_LOCK(tp->t_pgrp);
  507                                         pgsignal(tp->t_pgrp, SIGTSTP, 1);
  508                                         PGRP_UNLOCK(tp->t_pgrp);
  509                                 }
  510                                 goto endcase;
  511                         }
  512                 }
  513                 /*
  514                  * Handle start/stop characters.
  515                  */
  516                 if (ISSET(iflag, IXON)) {
  517                         if (CCEQ(cc[VSTOP], c)) {
  518                                 if (!ISSET(tp->t_state, TS_TTSTOP)) {
  519                                         SET(tp->t_state, TS_TTSTOP);
  520                                         (*tp->t_stop)(tp, 0);
  521                                         return (0);
  522                                 }
  523                                 if (!CCEQ(cc[VSTART], c))
  524                                         return (0);
  525                                 /*
  526                                  * if VSTART == VSTOP then toggle
  527                                  */
  528                                 goto endcase;
  529                         }
  530                         if (CCEQ(cc[VSTART], c))
  531                                 goto restartoutput;
  532                 }
  533                 /*
  534                  * IGNCR, ICRNL, & INLCR
  535                  */
  536                 if (c == '\r') {
  537                         if (ISSET(iflag, IGNCR))
  538                                 return (0);
  539                         else if (ISSET(iflag, ICRNL))
  540                                 c = '\n';
  541                 } else if (c == '\n' && ISSET(iflag, INLCR))
  542                         c = '\r';
  543         }
  544         if (!ISSET(tp->t_lflag, EXTPROC) && ISSET(lflag, ICANON)) {
  545                 /*
  546                  * From here on down canonical mode character
  547                  * processing takes place.
  548                  */
  549                 /*
  550                  * erase or erase2 (^H / ^?)
  551                  */
  552                 if (CCEQ(cc[VERASE], c) || CCEQ(cc[VERASE2], c) ) {
  553                         if (tp->t_rawq.c_cc)
  554                                 ttyrub(unputc(&tp->t_rawq), tp);
  555                         goto endcase;
  556                 }
  557                 /*
  558                  * kill (^U)
  559                  */
  560                 if (CCEQ(cc[VKILL], c)) {
  561                         if (ISSET(lflag, ECHOKE) &&
  562                             tp->t_rawq.c_cc == tp->t_rocount &&
  563                             !ISSET(lflag, ECHOPRT))
  564                                 while (tp->t_rawq.c_cc)
  565                                         ttyrub(unputc(&tp->t_rawq), tp);
  566                         else {
  567                                 ttyecho(c, tp);
  568                                 if (ISSET(lflag, ECHOK) ||
  569                                     ISSET(lflag, ECHOKE))
  570                                         ttyecho('\n', tp);
  571                                 FLUSHQ(&tp->t_rawq);
  572                                 tp->t_rocount = 0;
  573                         }
  574                         CLR(tp->t_state, TS_LOCAL);
  575                         goto endcase;
  576                 }
  577                 /*
  578                  * word erase (^W)
  579                  */
  580                 if (CCEQ(cc[VWERASE], c) && ISSET(lflag, IEXTEN)) {
  581                         int ctype;
  582 
  583                         /*
  584                          * erase whitespace
  585                          */
  586                         while ((c = unputc(&tp->t_rawq)) == ' ' || c == '\t')
  587                                 ttyrub(c, tp);
  588                         if (c == -1)
  589                                 goto endcase;
  590                         /*
  591                          * erase last char of word and remember the
  592                          * next chars type (for ALTWERASE)
  593                          */
  594                         ttyrub(c, tp);
  595                         c = unputc(&tp->t_rawq);
  596                         if (c == -1)
  597                                 goto endcase;
  598                         if (c == ' ' || c == '\t') {
  599                                 (void)putc(c, &tp->t_rawq);
  600                                 goto endcase;
  601                         }
  602                         ctype = ISALPHA(c);
  603                         /*
  604                          * erase rest of word
  605                          */
  606                         do {
  607                                 ttyrub(c, tp);
  608                                 c = unputc(&tp->t_rawq);
  609                                 if (c == -1)
  610                                         goto endcase;
  611                         } while (c != ' ' && c != '\t' &&
  612                             (!ISSET(lflag, ALTWERASE) || ISALPHA(c) == ctype));
  613                         (void)putc(c, &tp->t_rawq);
  614                         goto endcase;
  615                 }
  616                 /*
  617                  * reprint line (^R)
  618                  */
  619                 if (CCEQ(cc[VREPRINT], c) && ISSET(lflag, IEXTEN)) {
  620                         ttyretype(tp);
  621                         goto endcase;
  622                 }
  623                 /*
  624                  * ^T - kernel info and generate SIGINFO
  625                  */
  626                 if (CCEQ(cc[VSTATUS], c) && ISSET(lflag, IEXTEN)) {
  627                         if (ISSET(lflag, ISIG) && tp->t_pgrp != NULL) {
  628                                 PGRP_LOCK(tp->t_pgrp);
  629                                 pgsignal(tp->t_pgrp, SIGINFO, 1);
  630                                 PGRP_UNLOCK(tp->t_pgrp);
  631                         }
  632                         if (!ISSET(lflag, NOKERNINFO))
  633                                 ttyinfo(tp);
  634                         goto endcase;
  635                 }
  636         }
  637         /*
  638          * Check for input buffer overflow
  639          */
  640         if (tp->t_rawq.c_cc + tp->t_canq.c_cc >= MAX_INPUT) {
  641 input_overflow:
  642                 if (ISSET(iflag, IMAXBEL)) {
  643                         if (tp->t_outq.c_cc < tp->t_ohiwat)
  644                                 (void)ttyoutput(CTRL('g'), tp);
  645                 }
  646                 goto endcase;
  647         }
  648 
  649         if (   c == 0377 && ISSET(iflag, PARMRK) && !ISSET(iflag, ISTRIP)
  650              && ISSET(iflag, IGNBRK|IGNPAR) != (IGNBRK|IGNPAR))
  651                 (void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
  652 
  653         /*
  654          * Put data char in q for user and
  655          * wakeup on seeing a line delimiter.
  656          */
  657         if (putc(c, &tp->t_rawq) >= 0) {
  658                 if (!ISSET(lflag, ICANON)) {
  659                         ttwakeup(tp);
  660                         ttyecho(c, tp);
  661                         goto endcase;
  662                 }
  663                 if (TTBREAKC(c, lflag)) {
  664                         tp->t_rocount = 0;
  665                         catq(&tp->t_rawq, &tp->t_canq);
  666                         ttwakeup(tp);
  667                 } else if (tp->t_rocount++ == 0)
  668                         tp->t_rocol = tp->t_column;
  669                 if (ISSET(tp->t_state, TS_ERASE)) {
  670                         /*
  671                          * end of prterase \.../
  672                          */
  673                         CLR(tp->t_state, TS_ERASE);
  674                         (void)ttyoutput('/', tp);
  675                 }
  676                 i = tp->t_column;
  677                 ttyecho(c, tp);
  678                 if (CCEQ(cc[VEOF], c) && ISSET(lflag, ECHO)) {
  679                         /*
  680                          * Place the cursor over the '^' of the ^D.
  681                          */
  682                         i = imin(2, tp->t_column - i);
  683                         while (i > 0) {
  684                                 (void)ttyoutput('\b', tp);
  685                                 i--;
  686                         }
  687                 }
  688         }
  689 endcase:
  690         /*
  691          * IXANY means allow any character to restart output.
  692          */
  693         if (ISSET(tp->t_state, TS_TTSTOP) &&
  694             !ISSET(iflag, IXANY) && cc[VSTART] != cc[VSTOP])
  695                 return (0);
  696 restartoutput:
  697         CLR(tp->t_lflag, FLUSHO);
  698         CLR(tp->t_state, TS_TTSTOP);
  699 startoutput:
  700         return (ttstart(tp));
  701 }
  702 
  703 /*
  704  * Output a single character on a tty, doing output processing
  705  * as needed (expanding tabs, newline processing, etc.).
  706  * Returns < 0 if succeeds, otherwise returns char to resend.
  707  * Must be recursive.
  708  */
  709 static int
  710 ttyoutput(int c, struct tty *tp)
  711 {
  712         tcflag_t oflag;
  713         int col, s;
  714 
  715         oflag = tp->t_oflag;
  716         if (!ISSET(oflag, OPOST)) {
  717                 if (ISSET(tp->t_lflag, FLUSHO))
  718                         return (-1);
  719                 if (putc(c, &tp->t_outq))
  720                         return (c);
  721                 tk_nout++;
  722                 tp->t_outcc++;
  723                 return (-1);
  724         }
  725         /*
  726          * Do tab expansion if OXTABS is set.  Special case if we external
  727          * processing, we don't do the tab expansion because we'll probably
  728          * get it wrong.  If tab expansion needs to be done, let it happen
  729          * externally.
  730          */
  731         CLR(c, ~TTY_CHARMASK);
  732         if (c == '\t' &&
  733             ISSET(oflag, OXTABS) && !ISSET(tp->t_lflag, EXTPROC)) {
  734                 c = 8 - (tp->t_column & 7);
  735                 if (!ISSET(tp->t_lflag, FLUSHO)) {
  736                         s = spltty();           /* Don't interrupt tabs. */
  737                         c -= b_to_q("        ", c, &tp->t_outq);
  738                         tk_nout += c;
  739                         tp->t_outcc += c;
  740                         splx(s);
  741                 }
  742                 tp->t_column += c;
  743                 return (c ? -1 : '\t');
  744         }
  745         if (c == CEOT && ISSET(oflag, ONOEOT))
  746                 return (-1);
  747 
  748         /*
  749          * Newline translation: if ONLCR is set,
  750          * translate newline into "\r\n".
  751          */
  752         if (c == '\n' && ISSET(tp->t_oflag, ONLCR)) {
  753                 tk_nout++;
  754                 tp->t_outcc++;
  755                 if (!ISSET(tp->t_lflag, FLUSHO) && putc('\r', &tp->t_outq))
  756                         return (c);
  757         }
  758         /* If OCRNL is set, translate "\r" into "\n". */
  759         else if (c == '\r' && ISSET(tp->t_oflag, OCRNL))
  760                 c = '\n';
  761         /* If ONOCR is set, don't transmit CRs when on column 0. */
  762         else if (c == '\r' && ISSET(tp->t_oflag, ONOCR) && tp->t_column == 0)
  763                 return (-1);
  764 
  765         tk_nout++;
  766         tp->t_outcc++;
  767         if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
  768                 return (c);
  769 
  770         col = tp->t_column;
  771         switch (CCLASS(c)) {
  772         case BACKSPACE:
  773                 if (col > 0)
  774                         --col;
  775                 break;
  776         case CONTROL:
  777                 break;
  778         case NEWLINE:
  779                 if (ISSET(tp->t_oflag, ONLCR | ONLRET))
  780                         col = 0;
  781                 break;
  782         case RETURN:
  783                 col = 0;
  784                 break;
  785         case ORDINARY:
  786                 ++col;
  787                 break;
  788         case TAB:
  789                 col = (col + 8) & ~7;
  790                 break;
  791         }
  792         tp->t_column = col;
  793         return (-1);
  794 }
  795 
  796 /*
  797  * Ioctls for all tty devices.  Called after line-discipline specific ioctl
  798  * has been called to do discipline-specific functions and/or reject any
  799  * of these ioctl commands.
  800  */
  801 /* ARGSUSED */
  802 int
  803 ttioctl(struct tty *tp, u_long cmd, void *data, int flag)
  804 {
  805         struct proc *p;
  806         struct thread *td;
  807         struct pgrp *pgrp;
  808         int s, error, bits, sig, sig2;
  809 
  810         td = curthread;                 /* XXX */
  811         p = td->td_proc;
  812 
  813         /* If the ioctl involves modification, hang if in the background. */
  814         switch (cmd) {
  815         case  TIOCCBRK:
  816         case  TIOCCONS:
  817         case  TIOCDRAIN:
  818         case  TIOCEXCL:
  819         case  TIOCFLUSH:
  820 #ifdef TIOCHPCL
  821         case  TIOCHPCL:
  822 #endif
  823         case  TIOCNXCL:
  824         case  TIOCSBRK:
  825         case  TIOCSCTTY:
  826         case  TIOCSDRAINWAIT:
  827         case  TIOCSETA:
  828         case  TIOCSETAF:
  829         case  TIOCSETAW:
  830         case  TIOCSETD:
  831         case  TIOCSPGRP:
  832         case  TIOCSTART:
  833         case  TIOCSTAT:
  834         case  TIOCSTI:
  835         case  TIOCSTOP:
  836         case  TIOCSWINSZ:
  837 #ifndef BURN_BRIDGES
  838 #if defined(COMPAT_43)
  839         case  TIOCLBIC:
  840         case  TIOCLBIS:
  841         case  TIOCLSET:
  842         case  TIOCSETC:
  843         case OTIOCSETD:
  844         case  TIOCSETN:
  845         case  TIOCSETP:
  846         case  TIOCSLTC:
  847 #endif
  848 #endif
  849                 sx_slock(&proctree_lock);
  850                 PROC_LOCK(p);
  851                 while (isbackground(p, tp) && !(p->p_flag & P_PPWAIT) &&
  852                     !SIGISMEMBER(p->p_sigacts->ps_sigignore, SIGTTOU) &&
  853                     !SIGISMEMBER(td->td_sigmask, SIGTTOU)) {
  854                         pgrp = p->p_pgrp;
  855                         PROC_UNLOCK(p);
  856                         if (pgrp->pg_jobc == 0) {
  857                                 sx_sunlock(&proctree_lock);
  858                                 return (EIO);
  859                         }
  860                         PGRP_LOCK(pgrp);
  861                         sx_sunlock(&proctree_lock);
  862                         pgsignal(pgrp, SIGTTOU, 1);
  863                         PGRP_UNLOCK(pgrp);
  864                         error = ttysleep(tp, &lbolt, TTOPRI | PCATCH, "ttybg1",
  865                                          0);
  866                         if (error)
  867                                 return (error);
  868                         sx_slock(&proctree_lock);
  869                         PROC_LOCK(p);
  870                 }
  871                 PROC_UNLOCK(p);
  872                 sx_sunlock(&proctree_lock);
  873                 break;
  874         }
  875 
  876         if (tp->t_break != NULL) {
  877                 switch (cmd) {
  878                 case TIOCSBRK:
  879                         tp->t_break(tp, 1);
  880                         return (0);
  881                 case TIOCCBRK:
  882                         tp->t_break(tp, 0);
  883                         return (0);
  884                 default:
  885                         break;
  886                 }
  887         }
  888 
  889         if (tp->t_modem != NULL) {
  890                 switch (cmd) {
  891                 case TIOCSDTR:
  892                         tp->t_modem(tp, SER_DTR, 0);
  893                         return (0);
  894                 case TIOCCDTR:
  895                         tp->t_modem(tp, 0, SER_DTR);
  896                         return (0);
  897                 case TIOCMSET:
  898                         bits = *(int *)data;
  899                         sig = (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1;
  900                         sig2 = ((~bits) & (TIOCM_DTR | TIOCM_RTS)) >> 1;
  901                         tp->t_modem(tp, sig, sig2);
  902                         return (0);
  903                 case TIOCMBIS:
  904                         bits = *(int *)data;
  905                         sig = (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1;
  906                         tp->t_modem(tp, sig, 0);
  907                         return (0);
  908                 case TIOCMBIC:
  909                         bits = *(int *)data;
  910                         sig = (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1;
  911                         tp->t_modem(tp, 0, sig);
  912                         return (0);
  913                 case TIOCMGET:
  914                         sig = tp->t_modem(tp, 0, 0);
  915                         /* See <sys/serial.h. for the "<< 1" stuff */
  916                         bits = TIOCM_LE + (sig << 1);
  917                         *(int *)data = bits;
  918                         return (0);
  919                 default:
  920                         break;
  921                 }
  922         }
  923 
  924         if (tp->t_pps != NULL) {
  925                 error = pps_ioctl(cmd, data, tp->t_pps);
  926                 if (error != ENOIOCTL)
  927                         return (error);
  928         }
  929 
  930         switch (cmd) {                  /* Process the ioctl. */
  931         case FIOASYNC:                  /* set/clear async i/o */
  932                 s = spltty();
  933                 if (*(int *)data)
  934                         SET(tp->t_state, TS_ASYNC);
  935                 else
  936                         CLR(tp->t_state, TS_ASYNC);
  937                 splx(s);
  938                 break;
  939         case FIONBIO:                   /* set/clear non-blocking i/o */
  940                 break;                  /* XXX: delete. */
  941         case FIONREAD:                  /* get # bytes to read */
  942                 s = spltty();
  943                 *(int *)data = ttnread(tp);
  944                 splx(s);
  945                 break;
  946 
  947         case FIOSETOWN:
  948                 /*
  949                  * Policy -- Don't allow FIOSETOWN on someone else's
  950                  *           controlling tty
  951                  */
  952                 if (tp->t_session != NULL && !isctty(p, tp))
  953                         return (ENOTTY);
  954 
  955                 error = fsetown(*(int *)data, &tp->t_sigio);
  956                 if (error)
  957                         return (error);
  958                 break;
  959         case FIOGETOWN:
  960                 if (tp->t_session != NULL && !isctty(p, tp))
  961                         return (ENOTTY);
  962                 *(int *)data = fgetown(&tp->t_sigio);
  963                 break;
  964 
  965         case TIOCEXCL:                  /* set exclusive use of tty */
  966                 s = spltty();
  967                 SET(tp->t_state, TS_XCLUDE);
  968                 splx(s);
  969                 break;
  970         case TIOCFLUSH: {               /* flush buffers */
  971                 int flags = *(int *)data;
  972 
  973                 if (flags == 0)
  974                         flags = FREAD | FWRITE;
  975                 else
  976                         flags &= FREAD | FWRITE;
  977                 ttyflush(tp, flags);
  978                 break;
  979         }
  980         case TIOCCONS:                  /* become virtual console */
  981                 if (*(int *)data) {
  982                         struct nameidata nid;
  983 
  984                         if (constty && constty != tp &&
  985                             ISSET(constty->t_state, TS_CONNECTED))
  986                                 return (EBUSY);
  987 
  988                         /* Ensure user can open the real console. */
  989                         NDINIT(&nid, LOOKUP, LOCKLEAF | FOLLOW, UIO_SYSSPACE,
  990                             "/dev/console", td);
  991                         if ((error = namei(&nid)) != 0)
  992                                 return (error);
  993                         NDFREE(&nid, NDF_ONLY_PNBUF);
  994                         error = VOP_ACCESS(nid.ni_vp, VREAD, td->td_ucred, td);
  995                         vput(nid.ni_vp);
  996                         if (error)
  997                                 return (error);
  998 
  999                         constty_set(tp);
 1000                 } else if (tp == constty)
 1001                         constty_clear();
 1002                 break;
 1003         case TIOCDRAIN:                 /* wait till output drained */
 1004                 error = ttywait(tp);
 1005                 if (error)
 1006                         return (error);
 1007                 break;
 1008         case TIOCGETA: {                /* get termios struct */
 1009                 struct termios *t = (struct termios *)data;
 1010 
 1011                 bcopy(&tp->t_termios, t, sizeof(struct termios));
 1012                 break;
 1013         }
 1014         case TIOCGETD:                  /* get line discipline */
 1015                 *(int *)data = tp->t_line;
 1016                 break;
 1017         case TIOCGWINSZ:                /* get window size */
 1018                 *(struct winsize *)data = tp->t_winsize;
 1019                 break;
 1020         case TIOCGPGRP:                 /* get pgrp of tty */
 1021                 if (!isctty(p, tp))
 1022                         return (ENOTTY);
 1023                 *(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
 1024                 break;
 1025 #ifdef TIOCHPCL
 1026         case TIOCHPCL:                  /* hang up on last close */
 1027                 s = spltty();
 1028                 SET(tp->t_cflag, HUPCL);
 1029                 splx(s);
 1030                 break;
 1031 #endif
 1032         case TIOCMGDTRWAIT:
 1033                 *(int *)data = tp->t_dtr_wait * 100 / hz;
 1034                 break;
 1035         case TIOCMSDTRWAIT:
 1036                 /* must be root since the wait applies to following logins */
 1037                 error = suser(td);
 1038                 if (error)
 1039                         return (error);
 1040                 tp->t_dtr_wait = *(int *)data * hz / 100;
 1041                 break;
 1042         case TIOCNXCL:                  /* reset exclusive use of tty */
 1043                 s = spltty();
 1044                 CLR(tp->t_state, TS_XCLUDE);
 1045                 splx(s);
 1046                 break;
 1047         case TIOCOUTQ:                  /* output queue size */
 1048                 *(int *)data = tp->t_outq.c_cc;
 1049                 break;
 1050         case TIOCSETA:                  /* set termios struct */
 1051         case TIOCSETAW:                 /* drain output, set */
 1052         case TIOCSETAF: {               /* drn out, fls in, set */
 1053                 struct termios *t = (struct termios *)data;
 1054 
 1055                 if (t->c_ispeed == 0)
 1056                         t->c_ispeed = t->c_ospeed;
 1057                 if (t->c_ispeed == 0)
 1058                         t->c_ispeed = tp->t_ospeed;
 1059                 if (t->c_ispeed == 0)
 1060                         return (EINVAL);
 1061                 s = spltty();
 1062                 if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
 1063                         error = ttywait(tp);
 1064                         if (error) {
 1065                                 splx(s);
 1066                                 return (error);
 1067                         }
 1068                         if (cmd == TIOCSETAF)
 1069                                 ttyflush(tp, FREAD);
 1070                 }
 1071                 if (!ISSET(t->c_cflag, CIGNORE)) {
 1072                         /*
 1073                          * Set device hardware.
 1074                          */
 1075                         if (tp->t_param && (error = (*tp->t_param)(tp, t))) {
 1076                                 splx(s);
 1077                                 return (error);
 1078                         }
 1079                         if (ISSET(t->c_cflag, CLOCAL) &&
 1080                             !ISSET(tp->t_cflag, CLOCAL)) {
 1081                                 /*
 1082                                  * XXX disconnections would be too hard to
 1083                                  * get rid of without this kludge.  The only
 1084                                  * way to get rid of controlling terminals
 1085                                  * is to exit from the session leader.
 1086                                  */
 1087                                 CLR(tp->t_state, TS_ZOMBIE);
 1088 
 1089                                 wakeup(TSA_CARR_ON(tp));
 1090                                 ttwakeup(tp);
 1091                                 ttwwakeup(tp);
 1092                         }
 1093                         if ((ISSET(tp->t_state, TS_CARR_ON) ||
 1094                              ISSET(t->c_cflag, CLOCAL)) &&
 1095                             !ISSET(tp->t_state, TS_ZOMBIE))
 1096                                 SET(tp->t_state, TS_CONNECTED);
 1097                         else
 1098                                 CLR(tp->t_state, TS_CONNECTED);
 1099                         tp->t_cflag = t->c_cflag;
 1100                         tp->t_ispeed = t->c_ispeed;
 1101                         if (t->c_ospeed != 0)
 1102                                 tp->t_ospeed = t->c_ospeed;
 1103                         ttsetwater(tp);
 1104                 }
 1105                 if (ISSET(t->c_lflag, ICANON) != ISSET(tp->t_lflag, ICANON) &&
 1106                     cmd != TIOCSETAF) {
 1107                         if (ISSET(t->c_lflag, ICANON))
 1108                                 SET(tp->t_lflag, PENDIN);
 1109                         else {
 1110                                 /*
 1111                                  * XXX we really shouldn't allow toggling
 1112                                  * ICANON while we're in a non-termios line
 1113                                  * discipline.  Now we have to worry about
 1114                                  * panicing for a null queue.
 1115                                  */
 1116                                 if (tp->t_canq.c_cbreserved > 0 &&
 1117                                     tp->t_rawq.c_cbreserved > 0) {
 1118                                         catq(&tp->t_rawq, &tp->t_canq);
 1119                                         /*
 1120                                          * XXX the queue limits may be
 1121                                          * different, so the old queue
 1122                                          * swapping method no longer works.
 1123                                          */
 1124                                         catq(&tp->t_canq, &tp->t_rawq);
 1125                                 }
 1126                                 CLR(tp->t_lflag, PENDIN);
 1127                         }
 1128                         ttwakeup(tp);
 1129                 }
 1130                 tp->t_iflag = t->c_iflag;
 1131                 tp->t_oflag = t->c_oflag;
 1132                 /*
 1133                  * Make the EXTPROC bit read only.
 1134                  */
 1135                 if (ISSET(tp->t_lflag, EXTPROC))
 1136                         SET(t->c_lflag, EXTPROC);
 1137                 else
 1138                         CLR(t->c_lflag, EXTPROC);
 1139                 tp->t_lflag = t->c_lflag | ISSET(tp->t_lflag, PENDIN);
 1140                 if (t->c_cc[VMIN] != tp->t_cc[VMIN] ||
 1141                     t->c_cc[VTIME] != tp->t_cc[VTIME])
 1142                         ttwakeup(tp);
 1143                 bcopy(t->c_cc, tp->t_cc, sizeof(t->c_cc));
 1144                 splx(s);
 1145                 break;
 1146         }
 1147         case TIOCSETD: {                /* set line discipline */
 1148                 int t = *(int *)data;
 1149 
 1150                 if ((u_int)t >= nlinesw)
 1151                         return (ENXIO);
 1152                 if (t == tp->t_line)
 1153                         return (0);
 1154                 s = spltty();
 1155                 ttyld_close(tp, flag);
 1156                 tp->t_line = t;
 1157                 /* XXX: we should use the correct cdev here */
 1158                 error = ttyld_open(tp, tp->t_dev);
 1159                 if (error) {
 1160                         /*
 1161                          * If we fail to switch line discipline we cannot
 1162                          * fall back to the previous, because we can not
 1163                          * trust that ldisc to open successfully either.
 1164                          * Fall back to the default ldisc which we know 
 1165                          * will allways succeed.
 1166                          */
 1167                         tp->t_line = TTYDISC;
 1168                         (void)ttyld_open(tp, tp->t_dev);
 1169                 }
 1170                 splx(s);
 1171                 return (error);
 1172                 break;
 1173         }
 1174         case TIOCSTART:                 /* start output, like ^Q */
 1175                 s = spltty();
 1176                 if (ISSET(tp->t_state, TS_TTSTOP) ||
 1177                     ISSET(tp->t_lflag, FLUSHO)) {
 1178                         CLR(tp->t_lflag, FLUSHO);
 1179                         CLR(tp->t_state, TS_TTSTOP);
 1180                         ttstart(tp);
 1181                 }
 1182                 splx(s);
 1183                 break;
 1184         case TIOCSTI:                   /* simulate terminal input */
 1185                 if ((flag & FREAD) == 0 && suser(td))
 1186                         return (EPERM);
 1187                 if (!isctty(p, tp) && suser(td))
 1188                         return (EACCES);
 1189                 s = spltty();
 1190                 ttyld_rint(tp, *(u_char *)data);
 1191                 splx(s);
 1192                 break;
 1193         case TIOCSTOP:                  /* stop output, like ^S */
 1194                 s = spltty();
 1195                 if (!ISSET(tp->t_state, TS_TTSTOP)) {
 1196                         SET(tp->t_state, TS_TTSTOP);
 1197                         (*tp->t_stop)(tp, 0);
 1198                 }
 1199                 splx(s);
 1200                 break;
 1201         case TIOCSCTTY:                 /* become controlling tty */
 1202                 /* Session ctty vnode pointer set in vnode layer. */
 1203                 sx_slock(&proctree_lock);
 1204                 if (!SESS_LEADER(p) ||
 1205                     ((p->p_session->s_ttyvp || tp->t_session) &&
 1206                      (tp->t_session != p->p_session))) {
 1207                         sx_sunlock(&proctree_lock);
 1208                         return (EPERM);
 1209                 }
 1210                 tp->t_session = p->p_session;
 1211                 tp->t_pgrp = p->p_pgrp;
 1212                 SESS_LOCK(p->p_session);
 1213                 ttyref(tp);             /* ttyrel(): kern_proc.c:pgdelete() */
 1214                 p->p_session->s_ttyp = tp;
 1215                 SESS_UNLOCK(p->p_session);
 1216                 PROC_LOCK(p);
 1217                 p->p_flag |= P_CONTROLT;
 1218                 PROC_UNLOCK(p);
 1219                 sx_sunlock(&proctree_lock);
 1220                 break;
 1221         case TIOCSPGRP: {               /* set pgrp of tty */
 1222                 sx_slock(&proctree_lock);
 1223                 pgrp = pgfind(*(int *)data);
 1224                 if (!isctty(p, tp)) {
 1225                         if (pgrp != NULL)
 1226                                 PGRP_UNLOCK(pgrp);
 1227                         sx_sunlock(&proctree_lock);
 1228                         return (ENOTTY);
 1229                 }
 1230                 if (pgrp == NULL) {
 1231                         sx_sunlock(&proctree_lock);
 1232                         return (EPERM);
 1233                 }
 1234                 PGRP_UNLOCK(pgrp);
 1235                 if (pgrp->pg_session != p->p_session) {
 1236                         sx_sunlock(&proctree_lock);
 1237                         return (EPERM);
 1238                 }
 1239                 sx_sunlock(&proctree_lock);
 1240                 tp->t_pgrp = pgrp;
 1241                 break;
 1242         }
 1243         case TIOCSTAT:                  /* simulate control-T */
 1244                 s = spltty();
 1245                 ttyinfo(tp);
 1246                 splx(s);
 1247                 break;
 1248         case TIOCSWINSZ:                /* set window size */
 1249                 if (bcmp((caddr_t)&tp->t_winsize, data,
 1250                     sizeof (struct winsize))) {
 1251                         tp->t_winsize = *(struct winsize *)data;
 1252                         if (tp->t_pgrp != NULL) {
 1253                                 PGRP_LOCK(tp->t_pgrp);
 1254                                 pgsignal(tp->t_pgrp, SIGWINCH, 1);
 1255                                 PGRP_UNLOCK(tp->t_pgrp);
 1256                         }
 1257                 }
 1258                 break;
 1259         case TIOCSDRAINWAIT:
 1260                 error = suser(td);
 1261                 if (error)
 1262                         return (error);
 1263                 tp->t_timeout = *(int *)data * hz;
 1264                 wakeup(TSA_OCOMPLETE(tp));
 1265                 wakeup(TSA_OLOWAT(tp));
 1266                 break;
 1267         case TIOCGDRAINWAIT:
 1268                 *(int *)data = tp->t_timeout / hz;
 1269                 break;
 1270         default:
 1271 #if defined(COMPAT_43)
 1272 #ifndef BURN_BRIDGES
 1273                 return (ttcompat(tp, cmd, data, flag));
 1274 #else
 1275                 return (ENOIOCTL);
 1276 #endif
 1277 #else
 1278                 return (ENOIOCTL);
 1279 #endif
 1280         }
 1281         return (0);
 1282 }
 1283 
 1284 int
 1285 ttypoll(struct cdev *dev, int events, struct thread *td)
 1286 {
 1287         int s;
 1288         int revents = 0;
 1289         struct tty *tp;
 1290 
 1291         tp = tty_gettp(dev);
 1292 
 1293         if (tp == NULL) /* XXX used to return ENXIO, but that means true! */
 1294                 return ((events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM))
 1295                         | POLLHUP);
 1296 
 1297         s = spltty();
 1298         if (events & (POLLIN | POLLRDNORM)) {
 1299                 if (ISSET(tp->t_state, TS_ZOMBIE))
 1300                         revents |= (events & (POLLIN | POLLRDNORM)) |
 1301                             POLLHUP;
 1302                 else if (ttnread(tp) > 0)
 1303                         revents |= events & (POLLIN | POLLRDNORM);
 1304                 else
 1305                         selrecord(td, &tp->t_rsel);
 1306         }
 1307         if (events & POLLOUT) {
 1308                 if (ISSET(tp->t_state, TS_ZOMBIE))
 1309                         revents |= POLLHUP;
 1310                 else if (tp->t_outq.c_cc <= tp->t_olowat &&
 1311                     ISSET(tp->t_state, TS_CONNECTED))
 1312                         revents |= events & POLLOUT;
 1313                 else
 1314                         selrecord(td, &tp->t_wsel);
 1315         }
 1316         splx(s);
 1317         return (revents);
 1318 }
 1319 
 1320 static struct filterops ttyread_filtops =
 1321         { 1, NULL, filt_ttyrdetach, filt_ttyread };
 1322 static struct filterops ttywrite_filtops =
 1323         { 1, NULL, filt_ttywdetach, filt_ttywrite };
 1324 
 1325 int
 1326 ttykqfilter(struct cdev *dev, struct knote *kn)
 1327 {
 1328         struct tty *tp;
 1329         struct knlist *klist;
 1330         int s;
 1331 
 1332         tp = tty_gettp(dev);
 1333 
 1334         switch (kn->kn_filter) {
 1335         case EVFILT_READ:
 1336                 klist = &tp->t_rsel.si_note;
 1337                 kn->kn_fop = &ttyread_filtops;
 1338                 break;
 1339         case EVFILT_WRITE:
 1340                 klist = &tp->t_wsel.si_note;
 1341                 kn->kn_fop = &ttywrite_filtops;
 1342                 break;
 1343         default:
 1344                 return (EINVAL);
 1345         }
 1346 
 1347         kn->kn_hook = (caddr_t)dev;
 1348 
 1349         s = spltty();
 1350         knlist_add(klist, kn, 0);
 1351         splx(s);
 1352 
 1353         return (0);
 1354 }
 1355 
 1356 static void
 1357 filt_ttyrdetach(struct knote *kn)
 1358 {
 1359         struct tty *tp = ((struct cdev *)kn->kn_hook)->si_tty;
 1360         int s = spltty();
 1361 
 1362         knlist_remove(&tp->t_rsel.si_note, kn, 0);
 1363         splx(s);
 1364 }
 1365 
 1366 static int
 1367 filt_ttyread(struct knote *kn, long hint)
 1368 {
 1369         struct tty *tp = ((struct cdev *)kn->kn_hook)->si_tty;
 1370 
 1371         kn->kn_data = ttnread(tp);
 1372         if (ISSET(tp->t_state, TS_ZOMBIE)) {
 1373                 kn->kn_flags |= EV_EOF;
 1374                 return (1);
 1375         }
 1376         return (kn->kn_data > 0);
 1377 }
 1378 
 1379 static void
 1380 filt_ttywdetach(struct knote *kn)
 1381 {
 1382         struct tty *tp = ((struct cdev *)kn->kn_hook)->si_tty;
 1383         int s = spltty();
 1384 
 1385         knlist_remove(&tp->t_wsel.si_note, kn, 0);
 1386         splx(s);
 1387 }
 1388 
 1389 static int
 1390 filt_ttywrite(struct knote *kn, long hint)
 1391 {
 1392         struct tty *tp = ((struct cdev *)kn->kn_hook)->si_tty;
 1393 
 1394         kn->kn_data = tp->t_outq.c_cc;
 1395         if (ISSET(tp->t_state, TS_ZOMBIE))
 1396                 return (1);
 1397         return (kn->kn_data <= tp->t_olowat &&
 1398             ISSET(tp->t_state, TS_CONNECTED));
 1399 }
 1400 
 1401 /*
 1402  * Must be called at spltty().
 1403  */
 1404 static int
 1405 ttnread(struct tty *tp)
 1406 {
 1407         int nread;
 1408 
 1409         if (ISSET(tp->t_lflag, PENDIN))
 1410                 ttypend(tp);
 1411         nread = tp->t_canq.c_cc;
 1412         if (!ISSET(tp->t_lflag, ICANON)) {
 1413                 nread += tp->t_rawq.c_cc;
 1414                 if (nread < tp->t_cc[VMIN] && tp->t_cc[VTIME] == 0)
 1415                         nread = 0;
 1416         }
 1417         return (nread);
 1418 }
 1419 
 1420 /*
 1421  * Wait for output to drain.
 1422  */
 1423 int
 1424 ttywait(struct tty *tp)
 1425 {
 1426         int error, s;
 1427 
 1428         error = 0;
 1429         s = spltty();
 1430         while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
 1431                ISSET(tp->t_state, TS_CONNECTED) && tp->t_oproc) {
 1432                 (*tp->t_oproc)(tp);
 1433                 if ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
 1434                     ISSET(tp->t_state, TS_CONNECTED)) {
 1435                         SET(tp->t_state, TS_SO_OCOMPLETE);
 1436                         error = ttysleep(tp, TSA_OCOMPLETE(tp),
 1437                                          TTOPRI | PCATCH, "ttywai",
 1438                                          tp->t_timeout);
 1439                         if (error) {
 1440                                 if (error == EWOULDBLOCK)
 1441                                         error = EIO;
 1442                                 break;
 1443                         }
 1444                 } else
 1445                         break;
 1446         }
 1447         if (!error && (tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)))
 1448                 error = EIO;
 1449         splx(s);
 1450         return (error);
 1451 }
 1452 
 1453 /*
 1454  * Flush if successfully wait.
 1455  */
 1456 static int
 1457 ttywflush(struct tty *tp)
 1458 {
 1459         int error;
 1460 
 1461         if ((error = ttywait(tp)) == 0)
 1462                 ttyflush(tp, FREAD);
 1463         return (error);
 1464 }
 1465 
 1466 /*
 1467  * Flush tty read and/or write queues, notifying anyone waiting.
 1468  */
 1469 void
 1470 ttyflush(struct tty *tp, int rw)
 1471 {
 1472         int s;
 1473 
 1474         s = spltty();
 1475 #if 0
 1476 again:
 1477 #endif
 1478         if (rw & FWRITE) {
 1479                 FLUSHQ(&tp->t_outq);
 1480                 CLR(tp->t_state, TS_TTSTOP);
 1481         }
 1482         (*tp->t_stop)(tp, rw);
 1483         if (rw & FREAD) {
 1484                 FLUSHQ(&tp->t_canq);
 1485                 FLUSHQ(&tp->t_rawq);
 1486                 CLR(tp->t_lflag, PENDIN);
 1487                 tp->t_rocount = 0;
 1488                 tp->t_rocol = 0;
 1489                 CLR(tp->t_state, TS_LOCAL);
 1490                 ttwakeup(tp);
 1491                 if (ISSET(tp->t_state, TS_TBLOCK)) {
 1492                         if (rw & FWRITE)
 1493                                 FLUSHQ(&tp->t_outq);
 1494                         ttyunblock(tp);
 1495 
 1496                         /*
 1497                          * Don't let leave any state that might clobber the
 1498                          * next line discipline (although we should do more
 1499                          * to send the START char).  Not clearing the state
 1500                          * may have caused the "putc to a clist with no
 1501                          * reserved cblocks" panic/printf.
 1502                          */
 1503                         CLR(tp->t_state, TS_TBLOCK);
 1504 
 1505 #if 0 /* forget it, sleeping isn't always safe and we don't know when it is */
 1506                         if (ISSET(tp->t_iflag, IXOFF)) {
 1507                                 /*
 1508                                  * XXX wait a bit in the hope that the stop
 1509                                  * character (if any) will go out.  Waiting
 1510                                  * isn't good since it allows races.  This
 1511                                  * will be fixed when the stop character is
 1512                                  * put in a special queue.  Don't bother with
 1513                                  * the checks in ttywait() since the timeout
 1514                                  * will save us.
 1515                                  */
 1516                                 SET(tp->t_state, TS_SO_OCOMPLETE);
 1517                                 ttysleep(tp, TSA_OCOMPLETE(tp), TTOPRI,
 1518                                          "ttyfls", hz / 10);
 1519                                 /*
 1520                                  * Don't try sending the stop character again.
 1521                                  */
 1522                                 CLR(tp->t_state, TS_TBLOCK);
 1523                                 goto again;
 1524                         }
 1525 #endif
 1526                 }
 1527         }
 1528         if (rw & FWRITE) {
 1529                 FLUSHQ(&tp->t_outq);
 1530                 ttwwakeup(tp);
 1531         }
 1532         splx(s);
 1533 }
 1534 
 1535 /*
 1536  * Copy in the default termios characters.
 1537  */
 1538 void
 1539 termioschars(struct termios *t)
 1540 {
 1541 
 1542         bcopy(ttydefchars, t->c_cc, sizeof t->c_cc);
 1543 }
 1544 
 1545 /*
 1546  * Old interface.
 1547  */
 1548 void
 1549 ttychars(struct tty *tp)
 1550 {
 1551 
 1552         termioschars(&tp->t_termios);
 1553 }
 1554 
 1555 /*
 1556  * Handle input high water.  Send stop character for the IXOFF case.  Turn
 1557  * on our input flow control bit and propagate the changes to the driver.
 1558  * XXX the stop character should be put in a special high priority queue.
 1559  */
 1560 void
 1561 ttyblock(struct tty *tp)
 1562 {
 1563 
 1564         SET(tp->t_state, TS_TBLOCK);
 1565         if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
 1566             putc(tp->t_cc[VSTOP], &tp->t_outq) != 0)
 1567                 CLR(tp->t_state, TS_TBLOCK);    /* try again later */
 1568         ttstart(tp);
 1569 }
 1570 
 1571 /*
 1572  * Handle input low water.  Send start character for the IXOFF case.  Turn
 1573  * off our input flow control bit and propagate the changes to the driver.
 1574  * XXX the start character should be put in a special high priority queue.
 1575  */
 1576 static void
 1577 ttyunblock(struct tty *tp)
 1578 {
 1579 
 1580         CLR(tp->t_state, TS_TBLOCK);
 1581         if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTART] != _POSIX_VDISABLE &&
 1582             putc(tp->t_cc[VSTART], &tp->t_outq) != 0)
 1583                 SET(tp->t_state, TS_TBLOCK);    /* try again later */
 1584         ttstart(tp);
 1585 }
 1586 
 1587 #ifdef notyet
 1588 /* Not used by any current (i386) drivers. */
 1589 /*
 1590  * Restart after an inter-char delay.
 1591  */
 1592 void
 1593 ttrstrt(void *tp_arg)
 1594 {
 1595         struct tty *tp;
 1596         int s;
 1597 
 1598         KASSERT(tp_arg != NULL, ("ttrstrt"));
 1599 
 1600         tp = tp_arg;
 1601         s = spltty();
 1602 
 1603         CLR(tp->t_state, TS_TIMEOUT);
 1604         ttstart(tp);
 1605 
 1606         splx(s);
 1607 }
 1608 #endif
 1609 
 1610 int
 1611 ttstart(struct tty *tp)
 1612 {
 1613 
 1614         if (tp->t_oproc != NULL)        /* XXX: Kludge for pty. */
 1615                 (*tp->t_oproc)(tp);
 1616         return (0);
 1617 }
 1618 
 1619 /*
 1620  * "close" a line discipline
 1621  */
 1622 int
 1623 ttylclose(struct tty *tp, int flag)
 1624 {
 1625 
 1626         if (flag & FNONBLOCK || ttywflush(tp))
 1627                 ttyflush(tp, FREAD | FWRITE);
 1628         return (0);
 1629 }
 1630 
 1631 /*
 1632  * Handle modem control transition on a tty.
 1633  * Flag indicates new state of carrier.
 1634  * Returns 0 if the line should be turned off, otherwise 1.
 1635  */
 1636 int
 1637 ttymodem(struct tty *tp, int flag)
 1638 {
 1639 
 1640         if (ISSET(tp->t_state, TS_CARR_ON) && ISSET(tp->t_cflag, MDMBUF)) {
 1641                 /*
 1642                  * MDMBUF: do flow control according to carrier flag
 1643                  * XXX TS_CAR_OFLOW doesn't do anything yet.  TS_TTSTOP
 1644                  * works if IXON and IXANY are clear.
 1645                  */
 1646                 if (flag) {
 1647                         CLR(tp->t_state, TS_CAR_OFLOW);
 1648                         CLR(tp->t_state, TS_TTSTOP);
 1649                         ttstart(tp);
 1650                 } else if (!ISSET(tp->t_state, TS_CAR_OFLOW)) {
 1651                         SET(tp->t_state, TS_CAR_OFLOW);
 1652                         SET(tp->t_state, TS_TTSTOP);
 1653                         (*tp->t_stop)(tp, 0);
 1654                 }
 1655         } else if (flag == 0) {
 1656                 /*
 1657                  * Lost carrier.
 1658                  */
 1659                 CLR(tp->t_state, TS_CARR_ON);
 1660                 if (ISSET(tp->t_state, TS_ISOPEN) &&
 1661                     !ISSET(tp->t_cflag, CLOCAL)) {
 1662                         SET(tp->t_state, TS_ZOMBIE);
 1663                         CLR(tp->t_state, TS_CONNECTED);
 1664                         if (tp->t_session) {
 1665                                 sx_slock(&proctree_lock);
 1666                                 if (tp->t_session && tp->t_session->s_leader) {
 1667                                         struct proc *p;
 1668 
 1669                                         p = tp->t_session->s_leader;
 1670                                         PROC_LOCK(p);
 1671                                         psignal(p, SIGHUP);
 1672                                         PROC_UNLOCK(p);
 1673                                 }
 1674                                 sx_sunlock(&proctree_lock);
 1675                         }
 1676                         ttyflush(tp, FREAD | FWRITE);
 1677                         return (0);
 1678                 }
 1679         } else {
 1680                 /*
 1681                  * Carrier now on.
 1682                  */
 1683                 SET(tp->t_state, TS_CARR_ON);
 1684                 if (!ISSET(tp->t_state, TS_ZOMBIE))
 1685                         SET(tp->t_state, TS_CONNECTED);
 1686                 wakeup(TSA_CARR_ON(tp));
 1687                 ttwakeup(tp);
 1688                 ttwwakeup(tp);
 1689         }
 1690         return (1);
 1691 }
 1692 
 1693 /*
 1694  * Reinput pending characters after state switch
 1695  * call at spltty().
 1696  */
 1697 static void
 1698 ttypend(struct tty *tp)
 1699 {
 1700         struct clist tq;
 1701         int c;
 1702 
 1703         CLR(tp->t_lflag, PENDIN);
 1704         SET(tp->t_state, TS_TYPEN);
 1705         /*
 1706          * XXX this assumes too much about clist internals.  It may even
 1707          * fail if the cblock slush pool is empty.  We can't allocate more
 1708          * cblocks here because we are called from an interrupt handler
 1709          * and clist_alloc_cblocks() can wait.
 1710          */
 1711         tq = tp->t_rawq;
 1712         bzero(&tp->t_rawq, sizeof tp->t_rawq);
 1713         tp->t_rawq.c_cbmax = tq.c_cbmax;
 1714         tp->t_rawq.c_cbreserved = tq.c_cbreserved;
 1715         while ((c = getc(&tq)) >= 0)
 1716                 ttyinput(c, tp);
 1717         CLR(tp->t_state, TS_TYPEN);
 1718 }
 1719 
 1720 /*
 1721  * Process a read call on a tty device.
 1722  */
 1723 int
 1724 ttread(struct tty *tp, struct uio *uio, int flag)
 1725 {
 1726         struct clist *qp;
 1727         int c;
 1728         tcflag_t lflag;
 1729         cc_t *cc = tp->t_cc;
 1730         struct thread *td;
 1731         struct proc *p;
 1732         int s, first, error = 0;
 1733         int has_stime = 0, last_cc = 0;
 1734         long slp = 0;           /* XXX this should be renamed `timo'. */
 1735         struct timeval stime;
 1736         struct pgrp *pg;
 1737 
 1738         td = curthread;
 1739         p = td->td_proc;
 1740 loop:
 1741         s = spltty();
 1742         lflag = tp->t_lflag;
 1743         /*
 1744          * take pending input first
 1745          */
 1746         if (ISSET(lflag, PENDIN)) {
 1747                 ttypend(tp);
 1748                 splx(s);        /* reduce latency */
 1749                 s = spltty();
 1750                 lflag = tp->t_lflag;    /* XXX ttypend() clobbers it */
 1751         }
 1752 
 1753         /*
 1754          * Hang process if it's in the background.
 1755          */
 1756         if (isbackground(p, tp)) {
 1757                 splx(s);
 1758                 sx_slock(&proctree_lock);
 1759                 PROC_LOCK(p);
 1760                 if (SIGISMEMBER(p->p_sigacts->ps_sigignore, SIGTTIN) ||
 1761                     SIGISMEMBER(td->td_sigmask, SIGTTIN) ||
 1762                     (p->p_flag & P_PPWAIT) || p->p_pgrp->pg_jobc == 0) {
 1763                         PROC_UNLOCK(p);
 1764                         sx_sunlock(&proctree_lock);
 1765                         return (EIO);
 1766                 }
 1767                 pg = p->p_pgrp;
 1768                 PROC_UNLOCK(p);
 1769                 PGRP_LOCK(pg);
 1770                 sx_sunlock(&proctree_lock);
 1771                 pgsignal(pg, SIGTTIN, 1);
 1772                 PGRP_UNLOCK(pg);
 1773                 error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, "ttybg2", 0);
 1774                 if (error)
 1775                         return (error);
 1776                 goto loop;
 1777         }
 1778 
 1779         if (ISSET(tp->t_state, TS_ZOMBIE)) {
 1780                 splx(s);
 1781                 return (0);     /* EOF */
 1782         }
 1783 
 1784         /*
 1785          * If canonical, use the canonical queue,
 1786          * else use the raw queue.
 1787          *
 1788          * (should get rid of clists...)
 1789          */
 1790         qp = ISSET(lflag, ICANON) ? &tp->t_canq : &tp->t_rawq;
 1791 
 1792         if (flag & IO_NDELAY) {
 1793                 if (qp->c_cc > 0)
 1794                         goto read;
 1795                 if (!ISSET(lflag, ICANON) && cc[VMIN] == 0) {
 1796                         splx(s);
 1797                         return (0);
 1798                 }
 1799                 splx(s);
 1800                 return (EWOULDBLOCK);
 1801         }
 1802         if (!ISSET(lflag, ICANON)) {
 1803                 int m = cc[VMIN];
 1804                 long t = cc[VTIME];
 1805                 struct timeval timecopy;
 1806 
 1807                 /*
 1808                  * Check each of the four combinations.
 1809                  * (m > 0 && t == 0) is the normal read case.
 1810                  * It should be fairly efficient, so we check that and its
 1811                  * companion case (m == 0 && t == 0) first.
 1812                  * For the other two cases, we compute the target sleep time
 1813                  * into slp.
 1814                  */
 1815                 if (t == 0) {
 1816                         if (qp->c_cc < m)
 1817                                 goto sleep;
 1818                         if (qp->c_cc > 0)
 1819                                 goto read;
 1820 
 1821                         /* m, t and qp->c_cc are all 0.  0 is enough input. */
 1822                         splx(s);
 1823                         return (0);
 1824                 }
 1825                 t *= 100000;            /* time in us */
 1826 #define diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 1000000 + \
 1827                          ((t1).tv_usec - (t2).tv_usec))
 1828                 if (m > 0) {
 1829                         if (qp->c_cc <= 0)
 1830                                 goto sleep;
 1831                         if (qp->c_cc >= m)
 1832                                 goto read;
 1833                         getmicrotime(&timecopy);
 1834                         if (!has_stime) {
 1835                                 /* first character, start timer */
 1836                                 has_stime = 1;
 1837                                 stime = timecopy;
 1838                                 slp = t;
 1839                         } else if (qp->c_cc > last_cc) {
 1840                                 /* got a character, restart timer */
 1841                                 stime = timecopy;
 1842                                 slp = t;
 1843                         } else {
 1844                                 /* nothing, check expiration */
 1845                                 slp = t - diff(timecopy, stime);
 1846                                 if (slp <= 0)
 1847                                         goto read;
 1848                         }
 1849                         last_cc = qp->c_cc;
 1850                 } else {        /* m == 0 */
 1851                         if (qp->c_cc > 0)
 1852                                 goto read;
 1853                         getmicrotime(&timecopy);
 1854                         if (!has_stime) {
 1855                                 has_stime = 1;
 1856                                 stime = timecopy;
 1857                                 slp = t;
 1858                         } else {
 1859                                 slp = t - diff(timecopy, stime);
 1860                                 if (slp <= 0) {
 1861                                         /* Timed out, but 0 is enough input. */
 1862                                         splx(s);
 1863                                         return (0);
 1864                                 }
 1865                         }
 1866                 }
 1867 #undef diff
 1868                 if (slp != 0) {
 1869                         struct timeval tv;      /* XXX style bug. */
 1870 
 1871                         tv.tv_sec = slp / 1000000;
 1872                         tv.tv_usec = slp % 1000000;
 1873                         slp = tvtohz(&tv);
 1874                         /*
 1875                          * XXX bad variable names.  slp was the timeout in
 1876                          * usec.  Now it is the timeout in ticks.
 1877                          */
 1878                 }
 1879                 goto sleep;
 1880         }
 1881         if (qp->c_cc <= 0) {
 1882 sleep:
 1883                 /*
 1884                  * There is no input, or not enough input and we can block.
 1885                  */
 1886                 error = ttysleep(tp, TSA_HUP_OR_INPUT(tp), TTIPRI | PCATCH,
 1887                                  ISSET(tp->t_state, TS_CONNECTED) ?
 1888                                  "ttyin" : "ttyhup", (int)slp);
 1889                 splx(s);
 1890                 if (error == EWOULDBLOCK)
 1891                         error = 0;
 1892                 else if (error)
 1893                         return (error);
 1894                 /*
 1895                  * XXX what happens if another process eats some input
 1896                  * while we are asleep (not just here)?  It would be
 1897                  * safest to detect changes and reset our state variables
 1898                  * (has_stime and last_cc).
 1899                  */
 1900                 slp = 0;
 1901                 goto loop;
 1902         }
 1903 read:
 1904         splx(s);
 1905         /*
 1906          * Input present, check for input mapping and processing.
 1907          */
 1908         first = 1;
 1909         if (ISSET(lflag, ICANON | ISIG))
 1910                 goto slowcase;
 1911         for (;;) {
 1912                 char ibuf[IBUFSIZ];
 1913                 int icc;
 1914 
 1915                 icc = imin(uio->uio_resid, IBUFSIZ);
 1916                 icc = q_to_b(qp, ibuf, icc);
 1917                 if (icc <= 0) {
 1918                         if (first)
 1919                                 goto loop;
 1920                         break;
 1921                 }
 1922                 error = uiomove(ibuf, icc, uio);
 1923                 /*
 1924                  * XXX if there was an error then we should ungetc() the
 1925                  * unmoved chars and reduce icc here.
 1926                  */
 1927                 if (error)
 1928                         break;
 1929                 if (uio->uio_resid == 0)
 1930                         break;
 1931                 first = 0;
 1932         }
 1933         goto out;
 1934 slowcase:
 1935         for (;;) {
 1936                 c = getc(qp);
 1937                 if (c < 0) {
 1938                         if (first)
 1939                                 goto loop;
 1940                         break;
 1941                 }
 1942                 /*
 1943                  * delayed suspend (^Y)
 1944                  */
 1945                 if (CCEQ(cc[VDSUSP], c) &&
 1946                     ISSET(lflag, IEXTEN | ISIG) == (IEXTEN | ISIG)) {
 1947                         if (tp->t_pgrp != NULL) {
 1948                                 PGRP_LOCK(tp->t_pgrp);
 1949                                 pgsignal(tp->t_pgrp, SIGTSTP, 1);
 1950                                 PGRP_UNLOCK(tp->t_pgrp);
 1951                         }
 1952                         if (first) {
 1953                                 error = ttysleep(tp, &lbolt, TTIPRI | PCATCH,
 1954                                                  "ttybg3", 0);
 1955                                 if (error)
 1956                                         break;
 1957                                 goto loop;
 1958                         }
 1959                         break;
 1960                 }
 1961                 /*
 1962                  * Interpret EOF only in canonical mode.
 1963                  */
 1964                 if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
 1965                         break;
 1966                 /*
 1967                  * Give user character.
 1968                  */
 1969                 error = ureadc(c, uio);
 1970                 if (error)
 1971                         /* XXX should ungetc(c, qp). */
 1972                         break;
 1973                 if (uio->uio_resid == 0)
 1974                         break;
 1975                 /*
 1976                  * In canonical mode check for a "break character"
 1977                  * marking the end of a "line of input".
 1978                  */
 1979                 if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
 1980                         break;
 1981                 first = 0;
 1982         }
 1983 
 1984 out:
 1985         /*
 1986          * Look to unblock input now that (presumably)
 1987          * the input queue has gone down.
 1988          */
 1989         s = spltty();
 1990         if (ISSET(tp->t_state, TS_TBLOCK) &&
 1991             tp->t_rawq.c_cc + tp->t_canq.c_cc <= tp->t_ilowat)
 1992                 ttyunblock(tp);
 1993         splx(s);
 1994 
 1995         return (error);
 1996 }
 1997 
 1998 /*
 1999  * Check the output queue on tp for space for a kernel message (from uprintf
 2000  * or tprintf).  Allow some space over the normal hiwater mark so we don't
 2001  * lose messages due to normal flow control, but don't let the tty run amok.
 2002  * Sleeps here are not interruptible, but we return prematurely if new signals
 2003  * arrive.
 2004  */
 2005 int
 2006 ttycheckoutq(struct tty *tp, int wait)
 2007 {
 2008         int hiwat, s;
 2009         sigset_t oldmask;
 2010         struct thread *td;
 2011         struct proc *p;
 2012 
 2013         td = curthread;
 2014         p = td->td_proc;
 2015         hiwat = tp->t_ohiwat;
 2016         SIGEMPTYSET(oldmask);
 2017         s = spltty();
 2018         if (wait) {
 2019                 PROC_LOCK(p);
 2020                 oldmask = td->td_siglist;
 2021                 PROC_UNLOCK(p);
 2022         }
 2023         if (tp->t_outq.c_cc > hiwat + OBUFSIZ + 100)
 2024                 while (tp->t_outq.c_cc > hiwat) {
 2025                         ttstart(tp);
 2026                         if (tp->t_outq.c_cc <= hiwat)
 2027                                 break;
 2028                         if (!wait) {
 2029                                 splx(s);
 2030                                 return (0);
 2031                         }
 2032                         PROC_LOCK(p);
 2033                         if (!SIGSETEQ(td->td_siglist, oldmask)) {
 2034                                 PROC_UNLOCK(p);
 2035                                 splx(s);
 2036                                 return (0);
 2037                         }
 2038                         PROC_UNLOCK(p);
 2039                         SET(tp->t_state, TS_SO_OLOWAT);
 2040                         tsleep(TSA_OLOWAT(tp), PZERO - 1, "ttoutq", hz);
 2041                 }
 2042         splx(s);
 2043         return (1);
 2044 }
 2045 
 2046 /*
 2047  * Process a write call on a tty device.
 2048  */
 2049 int
 2050 ttwrite(struct tty *tp, struct uio *uio, int flag)
 2051 {
 2052         char *cp = NULL;
 2053         int cc, ce;
 2054         struct thread *td;
 2055         struct proc *p;
 2056         int i, hiwat, cnt, error, s;
 2057         char obuf[OBUFSIZ];
 2058 
 2059         hiwat = tp->t_ohiwat;
 2060         cnt = uio->uio_resid;
 2061         error = 0;
 2062         cc = 0;
 2063         td = curthread;
 2064         p = td->td_proc;
 2065 loop:
 2066         s = spltty();
 2067         if (ISSET(tp->t_state, TS_ZOMBIE)) {
 2068                 splx(s);
 2069                 if (uio->uio_resid == cnt)
 2070                         error = EIO;
 2071                 goto out;
 2072         }
 2073         if (!ISSET(tp->t_state, TS_CONNECTED)) {
 2074                 if (flag & IO_NDELAY) {
 2075                         splx(s);
 2076                         error = EWOULDBLOCK;
 2077                         goto out;
 2078                 }
 2079                 error = ttysleep(tp, TSA_CARR_ON(tp), TTIPRI | PCATCH,
 2080                                  "ttywdcd", 0);
 2081                 splx(s);
 2082                 if (error)
 2083                         goto out;
 2084                 goto loop;
 2085         }
 2086         splx(s);
 2087         /*
 2088          * Hang the process if it's in the background.
 2089          */
 2090         sx_slock(&proctree_lock);
 2091         PROC_LOCK(p);
 2092         if (isbackground(p, tp) &&
 2093             ISSET(tp->t_lflag, TOSTOP) && !(p->p_flag & P_PPWAIT) &&
 2094             !SIGISMEMBER(p->p_sigacts->ps_sigignore, SIGTTOU) &&
 2095             !SIGISMEMBER(td->td_sigmask, SIGTTOU)) {
 2096                 if (p->p_pgrp->pg_jobc == 0) {
 2097                         PROC_UNLOCK(p);
 2098                         sx_sunlock(&proctree_lock);
 2099                         error = EIO;
 2100                         goto out;
 2101                 }
 2102                 PROC_UNLOCK(p);
 2103                 PGRP_LOCK(p->p_pgrp);
 2104                 sx_sunlock(&proctree_lock);
 2105                 pgsignal(p->p_pgrp, SIGTTOU, 1);
 2106                 PGRP_UNLOCK(p->p_pgrp);
 2107                 error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, "ttybg4", 0);
 2108                 if (error)
 2109                         goto out;
 2110                 goto loop;
 2111         } else {
 2112                 PROC_UNLOCK(p);
 2113                 sx_sunlock(&proctree_lock);
 2114         }
 2115         /*
 2116          * Process the user's data in at most OBUFSIZ chunks.  Perform any
 2117          * output translation.  Keep track of high water mark, sleep on
 2118          * overflow awaiting device aid in acquiring new space.
 2119          */
 2120         while (uio->uio_resid > 0 || cc > 0) {
 2121                 if (ISSET(tp->t_lflag, FLUSHO)) {
 2122                         uio->uio_resid = 0;
 2123                         return (0);
 2124                 }
 2125                 if (tp->t_outq.c_cc > hiwat)
 2126                         goto ovhiwat;
 2127                 /*
 2128                  * Grab a hunk of data from the user, unless we have some
 2129                  * leftover from last time.
 2130                  */
 2131                 if (cc == 0) {
 2132                         cc = imin(uio->uio_resid, OBUFSIZ);
 2133                         cp = obuf;
 2134                         error = uiomove(cp, cc, uio);
 2135                         if (error) {
 2136                                 cc = 0;
 2137                                 break;
 2138                         }
 2139                 }
 2140                 /*
 2141                  * If nothing fancy need be done, grab those characters we
 2142                  * can handle without any of ttyoutput's processing and
 2143                  * just transfer them to the output q.  For those chars
 2144                  * which require special processing (as indicated by the
 2145                  * bits in char_type), call ttyoutput.  After processing
 2146                  * a hunk of data, look for FLUSHO so ^O's will take effect
 2147                  * immediately.
 2148                  */
 2149                 while (cc > 0) {
 2150                         if (!ISSET(tp->t_oflag, OPOST))
 2151                                 ce = cc;
 2152                         else {
 2153                                 ce = cc - scanc((u_int)cc, (u_char *)cp,
 2154                                                 char_type, CCLASSMASK);
 2155                                 /*
 2156                                  * If ce is zero, then we're processing
 2157                                  * a special character through ttyoutput.
 2158                                  */
 2159                                 if (ce == 0) {
 2160                                         tp->t_rocount = 0;
 2161                                         if (ttyoutput(*cp, tp) >= 0) {
 2162                                                 /* No Clists, wait a bit. */
 2163                                                 ttstart(tp);
 2164                                                 if (flag & IO_NDELAY) {
 2165                                                         error = EWOULDBLOCK;
 2166                                                         goto out;
 2167                                                 }
 2168                                                 error = ttysleep(tp, &lbolt,
 2169                                                                  TTOPRI|PCATCH,
 2170                                                                  "ttybf1", 0);
 2171                                                 if (error)
 2172                                                         goto out;
 2173                                                 goto loop;
 2174                                         }
 2175                                         cp++;
 2176                                         cc--;
 2177                                         if (ISSET(tp->t_lflag, FLUSHO) ||
 2178                                             tp->t_outq.c_cc > hiwat)
 2179                                                 goto ovhiwat;
 2180                                         continue;
 2181                                 }
 2182                         }
 2183                         /*
 2184                          * A bunch of normal characters have been found.
 2185                          * Transfer them en masse to the output queue and
 2186                          * continue processing at the top of the loop.
 2187                          * If there are any further characters in this
 2188                          * <= OBUFSIZ chunk, the first should be a character
 2189                          * requiring special handling by ttyoutput.
 2190                          */
 2191                         tp->t_rocount = 0;
 2192                         i = b_to_q(cp, ce, &tp->t_outq);
 2193                         ce -= i;
 2194                         tp->t_column += ce;
 2195                         cp += ce, cc -= ce, tk_nout += ce;
 2196                         tp->t_outcc += ce;
 2197                         if (i > 0) {
 2198                                 /* No Clists, wait a bit. */
 2199                                 ttstart(tp);
 2200                                 if (flag & IO_NDELAY) {
 2201                                         error = EWOULDBLOCK;
 2202                                         goto out;
 2203                                 }
 2204                                 error = ttysleep(tp, &lbolt, TTOPRI | PCATCH,
 2205                                                  "ttybf2", 0);
 2206                                 if (error)
 2207                                         goto out;
 2208                                 goto loop;
 2209                         }
 2210                         if (ISSET(tp->t_lflag, FLUSHO) ||
 2211                             tp->t_outq.c_cc > hiwat)
 2212                                 break;
 2213                 }
 2214                 ttstart(tp);
 2215         }
 2216 out:
 2217         /*
 2218          * If cc is nonzero, we leave the uio structure inconsistent, as the
 2219          * offset and iov pointers have moved forward, but it doesn't matter
 2220          * (the call will either return short or restart with a new uio).
 2221          */
 2222         uio->uio_resid += cc;
 2223         return (error);
 2224 
 2225 ovhiwat:
 2226         ttstart(tp);
 2227         s = spltty();
 2228         /*
 2229          * This can only occur if FLUSHO is set in t_lflag,
 2230          * or if ttstart/oproc is synchronous (or very fast).
 2231          */
 2232         if (tp->t_outq.c_cc <= hiwat) {
 2233                 splx(s);
 2234                 goto loop;
 2235         }
 2236         if (flag & IO_NDELAY) {
 2237                 splx(s);
 2238                 uio->uio_resid += cc;
 2239                 return (uio->uio_resid == cnt ? EWOULDBLOCK : 0);
 2240         }
 2241         SET(tp->t_state, TS_SO_OLOWAT);
 2242         error = ttysleep(tp, TSA_OLOWAT(tp), TTOPRI | PCATCH, "ttywri",
 2243                          tp->t_timeout);
 2244         splx(s);
 2245         if (error == EWOULDBLOCK)
 2246                 error = EIO;
 2247         if (error)
 2248                 goto out;
 2249         goto loop;
 2250 }
 2251 
 2252 /*
 2253  * Rubout one character from the rawq of tp
 2254  * as cleanly as possible.
 2255  */
 2256 static void
 2257 ttyrub(int c, struct tty *tp)
 2258 {
 2259         char *cp;
 2260         int savecol;
 2261         int tabc, s;
 2262 
 2263         if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
 2264                 return;
 2265         CLR(tp->t_lflag, FLUSHO);
 2266         if (ISSET(tp->t_lflag, ECHOE)) {
 2267                 if (tp->t_rocount == 0) {
 2268                         /*
 2269                          * Screwed by ttwrite; retype
 2270                          */
 2271                         ttyretype(tp);
 2272                         return;
 2273                 }
 2274                 if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
 2275                         ttyrubo(tp, 2);
 2276                 else {
 2277                         CLR(c, ~TTY_CHARMASK);
 2278                         switch (CCLASS(c)) {
 2279                         case ORDINARY:
 2280                                 ttyrubo(tp, 1);
 2281                                 break;
 2282                         case BACKSPACE:
 2283                         case CONTROL:
 2284                         case NEWLINE:
 2285                         case RETURN:
 2286                         case VTAB:
 2287                                 if (ISSET(tp->t_lflag, ECHOCTL))
 2288                                         ttyrubo(tp, 2);
 2289                                 break;
 2290                         case TAB:
 2291                                 if (tp->t_rocount < tp->t_rawq.c_cc) {
 2292                                         ttyretype(tp);
 2293                                         return;
 2294                                 }
 2295                                 s = spltty();
 2296                                 savecol = tp->t_column;
 2297                                 SET(tp->t_state, TS_CNTTB);
 2298                                 SET(tp->t_lflag, FLUSHO);
 2299                                 tp->t_column = tp->t_rocol;
 2300                                 cp = tp->t_rawq.c_cf;
 2301                                 if (cp)
 2302                                         tabc = *cp;     /* XXX FIX NEXTC */
 2303                                 for (; cp; cp = nextc(&tp->t_rawq, cp, &tabc))
 2304                                         ttyecho(tabc, tp);
 2305                                 CLR(tp->t_lflag, FLUSHO);
 2306                                 CLR(tp->t_state, TS_CNTTB);
 2307                                 splx(s);
 2308 
 2309                                 /* savecol will now be length of the tab. */
 2310                                 savecol -= tp->t_column;
 2311                                 tp->t_column += savecol;
 2312                                 if (savecol > 8)
 2313                                         savecol = 8;    /* overflow screw */
 2314                                 while (--savecol >= 0)
 2315                                         (void)ttyoutput('\b', tp);
 2316                                 break;
 2317                         default:                        /* XXX */
 2318 #define PANICSTR        "ttyrub: would panic c = %d, val = %d\n"
 2319                                 (void)printf(PANICSTR, c, CCLASS(c));
 2320 #ifdef notdef
 2321                                 panic(PANICSTR, c, CCLASS(c));
 2322 #endif
 2323                         }
 2324                 }
 2325         } else if (ISSET(tp->t_lflag, ECHOPRT)) {
 2326                 if (!ISSET(tp->t_state, TS_ERASE)) {
 2327                         SET(tp->t_state, TS_ERASE);
 2328                         (void)ttyoutput('\\', tp);
 2329                 }
 2330                 ttyecho(c, tp);
 2331         } else {
 2332                 ttyecho(tp->t_cc[VERASE], tp);
 2333                 /*
 2334                  * This code may be executed not only when an ERASE key
 2335                  * is pressed, but also when ^U (KILL) or ^W (WERASE) are.
 2336                  * So, I didn't think it was worthwhile to pass the extra
 2337                  * information (which would need an extra parameter,
 2338                  * changing every call) needed to distinguish the ERASE2
 2339                  * case from the ERASE.
 2340                  */
 2341         }
 2342         --tp->t_rocount;
 2343 }
 2344 
 2345 /*
 2346  * Back over cnt characters, erasing them.
 2347  */
 2348 static void
 2349 ttyrubo(struct tty *tp, int cnt)
 2350 {
 2351 
 2352         while (cnt-- > 0) {
 2353                 (void)ttyoutput('\b', tp);
 2354                 (void)ttyoutput(' ', tp);
 2355                 (void)ttyoutput('\b', tp);
 2356         }
 2357 }
 2358 
 2359 /*
 2360  * ttyretype --
 2361  *      Reprint the rawq line.  Note, it is assumed that c_cc has already
 2362  *      been checked.
 2363  */
 2364 static void
 2365 ttyretype(struct tty *tp)
 2366 {
 2367         char *cp;
 2368         int s, c;
 2369 
 2370         /* Echo the reprint character. */
 2371         if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
 2372                 ttyecho(tp->t_cc[VREPRINT], tp);
 2373 
 2374         (void)ttyoutput('\n', tp);
 2375 
 2376         /*
 2377          * XXX
 2378          * FIX: NEXTC IS BROKEN - DOESN'T CHECK QUOTE
 2379          * BIT OF FIRST CHAR.
 2380          */
 2381         s = spltty();
 2382         for (cp = tp->t_canq.c_cf, c = (cp != NULL ? *cp : 0);
 2383             cp != NULL; cp = nextc(&tp->t_canq, cp, &c))
 2384                 ttyecho(c, tp);
 2385         for (cp = tp->t_rawq.c_cf, c = (cp != NULL ? *cp : 0);
 2386             cp != NULL; cp = nextc(&tp->t_rawq, cp, &c))
 2387                 ttyecho(c, tp);
 2388         CLR(tp->t_state, TS_ERASE);
 2389         splx(s);
 2390 
 2391         tp->t_rocount = tp->t_rawq.c_cc;
 2392         tp->t_rocol = 0;
 2393 }
 2394 
 2395 /*
 2396  * Echo a typed character to the terminal.
 2397  */
 2398 static void
 2399 ttyecho(int c, struct tty *tp)
 2400 {
 2401 
 2402         if (!ISSET(tp->t_state, TS_CNTTB))
 2403                 CLR(tp->t_lflag, FLUSHO);
 2404         if ((!ISSET(tp->t_lflag, ECHO) &&
 2405              (c != '\n' || !ISSET(tp->t_lflag, ECHONL))) ||
 2406             ISSET(tp->t_lflag, EXTPROC))
 2407                 return;
 2408         if (ISSET(tp->t_lflag, ECHOCTL) &&
 2409             ((ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n') ||
 2410             ISSET(c, TTY_CHARMASK) == 0177)) {
 2411                 (void)ttyoutput('^', tp);
 2412                 CLR(c, ~TTY_CHARMASK);
 2413                 if (c == 0177)
 2414                         c = '?';
 2415                 else
 2416                         c += 'A' - 1;
 2417         }
 2418         (void)ttyoutput(c, tp);
 2419 }
 2420 
 2421 /*
 2422  * Wake up any readers on a tty.
 2423  */
 2424 void
 2425 ttwakeup(struct tty *tp)
 2426 {
 2427 
 2428         if (SEL_WAITING(&tp->t_rsel))
 2429                 selwakeuppri(&tp->t_rsel, TTIPRI);
 2430         if (ISSET(tp->t_state, TS_ASYNC) && tp->t_sigio != NULL)
 2431                 pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
 2432         wakeup(TSA_HUP_OR_INPUT(tp));
 2433         KNOTE_UNLOCKED(&tp->t_rsel.si_note, 0);
 2434 }
 2435 
 2436 /*
 2437  * Wake up any writers on a tty.
 2438  */
 2439 void
 2440 ttwwakeup(struct tty *tp)
 2441 {
 2442 
 2443         if (SEL_WAITING(&tp->t_wsel) && tp->t_outq.c_cc <= tp->t_olowat)
 2444                 selwakeuppri(&tp->t_wsel, TTOPRI);
 2445         if (ISSET(tp->t_state, TS_ASYNC) && tp->t_sigio != NULL)
 2446                 pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
 2447         if (ISSET(tp->t_state, TS_BUSY | TS_SO_OCOMPLETE) ==
 2448             TS_SO_OCOMPLETE && tp->t_outq.c_cc == 0) {
 2449                 CLR(tp->t_state, TS_SO_OCOMPLETE);
 2450                 wakeup(TSA_OCOMPLETE(tp));
 2451         }
 2452         if (ISSET(tp->t_state, TS_SO_OLOWAT) &&
 2453             tp->t_outq.c_cc <= tp->t_olowat) {
 2454                 CLR(tp->t_state, TS_SO_OLOWAT);
 2455                 wakeup(TSA_OLOWAT(tp));
 2456         }
 2457         KNOTE_UNLOCKED(&tp->t_wsel.si_note, 0);
 2458 }
 2459 
 2460 /*
 2461  * Look up a code for a specified speed in a conversion table;
 2462  * used by drivers to map software speed values to hardware parameters.
 2463  */
 2464 int
 2465 ttspeedtab(int speed, struct speedtab *table)
 2466 {
 2467 
 2468         for ( ; table->sp_speed != -1; table++)
 2469                 if (table->sp_speed == speed)
 2470                         return (table->sp_code);
 2471         return (-1);
 2472 }
 2473 
 2474 /*
 2475  * Set input and output watermarks and buffer sizes.  For input, the
 2476  * high watermark is about one second's worth of input above empty, the
 2477  * low watermark is slightly below high water, and the buffer size is a
 2478  * driver-dependent amount above high water.  For output, the watermarks
 2479  * are near the ends of the buffer, with about 1 second's worth of input
 2480  * between them.  All this only applies to the standard line discipline.
 2481  */
 2482 void
 2483 ttsetwater(struct tty *tp)
 2484 {
 2485         int cps, ttmaxhiwat, x;
 2486 
 2487         /* Input. */
 2488         clist_alloc_cblocks(&tp->t_canq, TTYHOG, 512);
 2489         switch (tp->t_ispeedwat) {
 2490         case (speed_t)-1:
 2491                 cps = tp->t_ispeed / 10;
 2492                 break;
 2493         case 0:
 2494                 /*
 2495                  * This case is for old drivers that don't know about
 2496                  * t_ispeedwat.  Arrange for them to get the old buffer
 2497                  * sizes and watermarks.
 2498                  */
 2499                 cps = TTYHOG - 2 * 256;
 2500                 tp->t_ififosize = 2 * 256;
 2501                 break;
 2502         default:
 2503                 cps = tp->t_ispeedwat / 10;
 2504                 break;
 2505         }
 2506         tp->t_ihiwat = cps;
 2507         tp->t_ilowat = 7 * cps / 8;
 2508         x = cps + tp->t_ififosize;
 2509         clist_alloc_cblocks(&tp->t_rawq, x, x);
 2510 
 2511         /* Output. */
 2512         switch (tp->t_ospeedwat) {
 2513         case (speed_t)-1:
 2514                 cps = tp->t_ospeed / 10;
 2515                 ttmaxhiwat = 2 * TTMAXHIWAT;
 2516                 break;
 2517         case 0:
 2518                 cps = tp->t_ospeed / 10;
 2519                 ttmaxhiwat = TTMAXHIWAT;
 2520                 break;
 2521         default:
 2522                 cps = tp->t_ospeedwat / 10;
 2523                 ttmaxhiwat = 8 * TTMAXHIWAT;
 2524                 break;
 2525         }
 2526 #define CLAMP(x, h, l)  ((x) > h ? h : ((x) < l) ? l : (x))
 2527         tp->t_olowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
 2528         x += cps;
 2529         x = CLAMP(x, ttmaxhiwat, TTMINHIWAT);   /* XXX clamps are too magic */
 2530         tp->t_ohiwat = roundup(x, CBSIZE);      /* XXX for compat */
 2531         x = imax(tp->t_ohiwat, TTMAXHIWAT);     /* XXX for compat/safety */
 2532         x += OBUFSIZ + 100;
 2533         clist_alloc_cblocks(&tp->t_outq, x, x);
 2534 #undef  CLAMP
 2535 }
 2536 
 2537 /*
 2538  * Report on state of foreground process group.
 2539  */
 2540 void
 2541 ttyinfo(struct tty *tp)
 2542 {
 2543         struct timeval utime, stime;
 2544         struct proc *p, *pick;
 2545         struct thread *td;
 2546         const char *stateprefix, *state;
 2547         long rss;
 2548         int load, pctcpu;
 2549         pid_t pid;
 2550         char comm[MAXCOMLEN + 1];
 2551 
 2552         if (ttycheckoutq(tp,0) == 0)
 2553                 return;
 2554 
 2555         /* Print load average. */
 2556         load = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
 2557         ttyprintf(tp, "load: %d.%02d ", load / 100, load % 100);
 2558 
 2559         /*
 2560          * On return following a ttyprintf(), we set tp->t_rocount to 0 so
 2561          * that pending input will be retyped on BS.
 2562          */
 2563         if (tp->t_session == NULL) {
 2564                 ttyprintf(tp, "not a controlling terminal\n");
 2565                 tp->t_rocount = 0;
 2566                 return;
 2567         }
 2568         if (tp->t_pgrp == NULL) {
 2569                 ttyprintf(tp, "no foreground process group\n");
 2570                 tp->t_rocount = 0;
 2571                 return;
 2572         }
 2573         PGRP_LOCK(tp->t_pgrp);
 2574         if (LIST_EMPTY(&tp->t_pgrp->pg_members)) {
 2575                 PGRP_UNLOCK(tp->t_pgrp);
 2576                 ttyprintf(tp, "empty foreground process group\n");
 2577                 tp->t_rocount = 0;
 2578                 return;
 2579         }
 2580 
 2581         /*
 2582          * Pick the most interesting process and copy some of its
 2583          * state for printing later.  sched_lock must be held for
 2584          * most parts of this.  Holding it throughout is simplest
 2585          * and prevents even unimportant inconsistencies in the
 2586          * copy of the state, but may increase interrupt latency
 2587          * too much.
 2588          */
 2589         pick = NULL;
 2590         mtx_lock_spin(&sched_lock);
 2591         LIST_FOREACH(p, &tp->t_pgrp->pg_members, p_pglist)
 2592                 if (proc_compare(pick, p))
 2593                         pick = p;
 2594 
 2595         td = FIRST_THREAD_IN_PROC(pick);        /* XXXKSE */
 2596 #if 0
 2597         KASSERT(td != NULL, ("ttyinfo: no thread"));
 2598 #else
 2599         if (td == NULL) {
 2600                 mtx_unlock_spin(&sched_lock);
 2601                 PGRP_UNLOCK(tp->t_pgrp);
 2602                 ttyprintf(tp, "foreground process without thread\n");
 2603                 tp->t_rocount = 0;
 2604                 return;
 2605         }
 2606 #endif
 2607         stateprefix = "";
 2608         if (TD_IS_RUNNING(td))
 2609                 state = "running";
 2610         else if (TD_ON_RUNQ(td) || TD_CAN_RUN(td))
 2611                 state = "runnable";
 2612         else if (TD_IS_SLEEPING(td)) {
 2613                 /* XXX: If we're sleeping, are we ever not in a queue? */
 2614                 if (TD_ON_SLEEPQ(td))
 2615                         state = td->td_wmesg;
 2616                 else
 2617                         state = "sleeping without queue";
 2618         } else if (TD_ON_LOCK(td)) {
 2619                 state = td->td_lockname;
 2620                 stateprefix = "*";
 2621         } else if (TD_IS_SUSPENDED(td))
 2622                 state = "suspended";
 2623         else if (TD_AWAITING_INTR(td))
 2624                 state = "intrwait";
 2625         else
 2626                 state = "unknown";
 2627         pctcpu = (sched_pctcpu(td) * 10000 + FSCALE / 2) >> FSHIFT;
 2628         if (pick->p_state == PRS_NEW || pick->p_state == PRS_ZOMBIE)
 2629                 rss = 0;
 2630         else
 2631                 rss = pgtok(vmspace_resident_count(pick->p_vmspace));
 2632         mtx_unlock_spin(&sched_lock);
 2633         PROC_LOCK(pick);
 2634         PGRP_UNLOCK(tp->t_pgrp);
 2635         calcru(pick, &utime, &stime);
 2636         pid = pick->p_pid;
 2637         bcopy(pick->p_comm, comm, sizeof(comm));
 2638         PROC_UNLOCK(pick);
 2639 
 2640         /* Print command, pid, state, utime, stime, %cpu, and rss. */
 2641         ttyprintf(tp,
 2642             " cmd: %s %d [%s%s] %ld.%02ldu %ld.%02lds %d%% %ldk\n",
 2643             comm, pid, stateprefix, state,
 2644             (long)utime.tv_sec, utime.tv_usec / 10000,
 2645             (long)stime.tv_sec, stime.tv_usec / 10000,
 2646             pctcpu / 100, rss);
 2647         tp->t_rocount = 0;
 2648 }
 2649 
 2650 /*
 2651  * Returns 1 if p2 is "better" than p1
 2652  *
 2653  * The algorithm for picking the "interesting" process is thus:
 2654  *
 2655  *      1) Only foreground processes are eligible - implied.
 2656  *      2) Runnable processes are favored over anything else.  The runner
 2657  *         with the highest cpu utilization is picked (p_estcpu).  Ties are
 2658  *         broken by picking the highest pid.
 2659  *      3) The sleeper with the shortest sleep time is next.  With ties,
 2660  *         we pick out just "short-term" sleepers (P_SINTR == 0).
 2661  *      4) Further ties are broken by picking the highest pid.
 2662  */
 2663 #define ISRUN(p, val)                                           \
 2664 do {                                                            \
 2665         struct thread *td;                                      \
 2666         val = 0;                                                \
 2667         FOREACH_THREAD_IN_PROC(p, td) {                         \
 2668                 if (TD_ON_RUNQ(td) ||                           \
 2669                     TD_IS_RUNNING(td)) {                        \
 2670                         val = 1;                                \
 2671                         break;                                  \
 2672                 }                                               \
 2673         }                                                       \
 2674 } while (0)
 2675 
 2676 #define TESTAB(a, b)    ((a)<<1 | (b))
 2677 #define ONLYA   2
 2678 #define ONLYB   1
 2679 #define BOTH    3
 2680 
 2681 static int
 2682 proc_compare(struct proc *p1, struct proc *p2)
 2683 {
 2684 
 2685         int esta, estb;
 2686         struct ksegrp *kg;
 2687         mtx_assert(&sched_lock, MA_OWNED);
 2688         if (p1 == NULL)
 2689                 return (1);
 2690 
 2691         ISRUN(p1, esta);
 2692         ISRUN(p2, estb);
 2693         
 2694         /*
 2695          * see if at least one of them is runnable
 2696          */
 2697         switch (TESTAB(esta, estb)) {
 2698         case ONLYA:
 2699                 return (0);
 2700         case ONLYB:
 2701                 return (1);
 2702         case BOTH:
 2703                 /*
 2704                  * tie - favor one with highest recent cpu utilization
 2705                  */
 2706                 esta = estb = 0;
 2707                 FOREACH_KSEGRP_IN_PROC(p1,kg) {
 2708                         esta += kg->kg_estcpu;
 2709                 }
 2710                 FOREACH_KSEGRP_IN_PROC(p2,kg) {
 2711                         estb += kg->kg_estcpu;
 2712                 }
 2713                 if (estb > esta)
 2714                         return (1);
 2715                 if (esta > estb)
 2716                         return (0);
 2717                 return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
 2718         }
 2719         /*
 2720          * weed out zombies
 2721          */
 2722         switch (TESTAB(p1->p_state == PRS_ZOMBIE, p2->p_state == PRS_ZOMBIE)) {
 2723         case ONLYA:
 2724                 return (1);
 2725         case ONLYB:
 2726                 return (0);
 2727         case BOTH:
 2728                 return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
 2729         }
 2730 
 2731 #if 0 /* XXXKSE */
 2732         /*
 2733          * pick the one with the smallest sleep time
 2734          */
 2735         if (p2->p_slptime > p1->p_slptime)
 2736                 return (0);
 2737         if (p1->p_slptime > p2->p_slptime)
 2738                 return (1);
 2739         /*
 2740          * favor one sleeping in a non-interruptible sleep
 2741          */
 2742         if (p1->p_sflag & PS_SINTR && (p2->p_sflag & PS_SINTR) == 0)
 2743                 return (1);
 2744         if (p2->p_sflag & PS_SINTR && (p1->p_sflag & PS_SINTR) == 0)
 2745                 return (0);
 2746 #endif
 2747         return (p2->p_pid > p1->p_pid);         /* tie - return highest pid */
 2748 }
 2749 
 2750 /*
 2751  * Output char to tty; console putchar style.
 2752  */
 2753 int
 2754 tputchar(int c, struct tty *tp)
 2755 {
 2756         int s;
 2757 
 2758         s = spltty();
 2759         if (!ISSET(tp->t_state, TS_CONNECTED)) {
 2760                 splx(s);
 2761                 return (-1);
 2762         }
 2763         if (c == '\n')
 2764                 (void)ttyoutput('\r', tp);
 2765         (void)ttyoutput(c, tp);
 2766         ttstart(tp);
 2767         splx(s);
 2768         return (0);
 2769 }
 2770 
 2771 /*
 2772  * Sleep on chan, returning ERESTART if tty changed while we napped and
 2773  * returning any errors (e.g. EINTR/EWOULDBLOCK) reported by tsleep.  If
 2774  * the tty is revoked, restarting a pending call will redo validation done
 2775  * at the start of the call.
 2776  */
 2777 int
 2778 ttysleep(struct tty *tp, void *chan, int pri, char *wmesg, int timo)
 2779 {
 2780         int error;
 2781         int gen;
 2782 
 2783         gen = tp->t_gen;
 2784         error = tsleep(chan, pri, wmesg, timo);
 2785         if (tp->t_state & TS_GONE)
 2786                 return (ENXIO);
 2787         if (error)
 2788                 return (error);
 2789         return (tp->t_gen == gen ? 0 : ERESTART);
 2790 }
 2791 
 2792 /*
 2793  * Gain a reference to a TTY
 2794  */
 2795 int
 2796 ttyref(struct tty *tp)
 2797 {
 2798         int i;
 2799         
 2800         mtx_lock(&tp->t_mtx);
 2801         KASSERT(tp->t_refcnt > 0,
 2802             ("ttyref(): tty refcnt is %d (%s)",
 2803             tp->t_refcnt, tp->t_dev != NULL ? devtoname(tp->t_dev) : "??"));
 2804         i = ++tp->t_refcnt;
 2805         mtx_unlock(&tp->t_mtx);
 2806         return (i);
 2807 }
 2808 
 2809 /*
 2810  * Drop a reference to a TTY.
 2811  * When reference count drops to zero, we free it.
 2812  */
 2813 int
 2814 ttyrel(struct tty *tp)
 2815 {
 2816         int i;
 2817         
 2818         mtx_lock(&tty_list_mutex);
 2819         mtx_lock(&tp->t_mtx);
 2820         KASSERT(tp->t_refcnt > 0,
 2821             ("ttyrel(): tty refcnt is %d (%s)",
 2822             tp->t_refcnt, tp->t_dev != NULL ? devtoname(tp->t_dev) : "??"));
 2823         i = --tp->t_refcnt;
 2824         if (i != 0) {
 2825                 mtx_unlock(&tp->t_mtx);
 2826                 mtx_unlock(&tty_list_mutex);
 2827                 return (i);
 2828         }
 2829         TAILQ_REMOVE(&tty_list, tp, t_list);
 2830         mtx_unlock(&tp->t_mtx);
 2831         mtx_unlock(&tty_list_mutex);
 2832         knlist_destroy(&tp->t_rsel.si_note);
 2833         knlist_destroy(&tp->t_wsel.si_note);
 2834         mtx_destroy(&tp->t_mtx);
 2835         free(tp, M_TTYS);
 2836         return (i);
 2837 }
 2838 
 2839 /*
 2840  * Allocate a tty struct.  Clists in the struct will be allocated by
 2841  * tty_open().
 2842  */
 2843 struct tty *
 2844 ttymalloc(struct tty *tp)
 2845 {
 2846         static int once;
 2847 
 2848         if (!once) {
 2849                 mtx_init(&tty_list_mutex, "ttylist", NULL, MTX_DEF);
 2850                 once++;
 2851         }
 2852 
 2853         if (tp) {
 2854                 /*
 2855                  * XXX: Either this argument should go away, or we should
 2856                  * XXX: require it and do a ttyrel(tp) here and allocate
 2857                  * XXX: a new tty.  For now do nothing.
 2858                  */
 2859                 return(tp);
 2860         }
 2861         tp = malloc(sizeof *tp, M_TTYS, M_WAITOK | M_ZERO);
 2862         mtx_init(&tp->t_mtx, "tty", NULL, MTX_DEF);
 2863 
 2864         /*
 2865          * Set up the initial state
 2866          */
 2867         tp->t_refcnt = 1;
 2868         tp->t_timeout = -1;
 2869         tp->t_dtr_wait = 3 * hz;
 2870 
 2871         ttyinitmode(tp, 0, 0);
 2872         bcopy(ttydefchars, tp->t_init_in.c_cc, sizeof tp->t_init_in.c_cc);
 2873 
 2874         /* Make callout the same as callin */
 2875         tp->t_init_out = tp->t_init_in;
 2876 
 2877         mtx_lock(&tty_list_mutex);
 2878         TAILQ_INSERT_TAIL(&tty_list, tp, t_list);
 2879         mtx_unlock(&tty_list_mutex);
 2880         knlist_init(&tp->t_rsel.si_note, &tp->t_mtx, NULL, NULL, NULL);
 2881         knlist_init(&tp->t_wsel.si_note, &tp->t_mtx, NULL, NULL, NULL);
 2882         return (tp);
 2883 }
 2884 
 2885 struct tty *
 2886 ttyalloc()
 2887 {
 2888 
 2889         return (ttymalloc(NULL));
 2890 }
 2891 
 2892 static void
 2893 ttypurge(struct cdev *dev)
 2894 {
 2895 
 2896         if (dev->si_tty == NULL)
 2897                 return;
 2898         ttygone(dev->si_tty);
 2899 }
 2900 
 2901 /*
 2902  * ttycreate()
 2903  *
 2904  * Create the device entries for this tty thereby opening it for business.
 2905  *
 2906  * The flags argument controls if "cua" units are created.
 2907  *
 2908  * The t_sc filed is copied to si_drv1 in the created cdevs.  This 
 2909  * is particularly important for ->t_cioctl() users.
 2910  *
 2911  * XXX: implement the init and lock devices by cloning.
 2912  */
 2913 
 2914 int 
 2915 ttycreate(struct tty *tp, struct cdevsw *csw, int unit, int flags, const char *fmt, ...)
 2916 {
 2917         char namebuf[SPECNAMELEN - 3];          /* XXX space for "tty" */
 2918         va_list ap;
 2919         struct cdev *cp;
 2920         int i, minor, sminor, sunit;
 2921 
 2922         mtx_assert(&Giant, MA_OWNED);
 2923 
 2924         if (tty_unit == NULL)
 2925                 tty_unit = new_unrhdr(0, 0xffff, NULL);
 2926 
 2927         sunit = alloc_unr(tty_unit);
 2928         tp->t_devunit = sunit;
 2929 
 2930         if (csw == NULL) {
 2931                 csw = &tty_cdevsw;
 2932                 unit = sunit;
 2933         }
 2934         KASSERT(csw->d_purge == NULL || csw->d_purge == ttypurge,
 2935             ("tty should not have d_purge"));
 2936 
 2937         csw->d_purge = ttypurge;
 2938 
 2939         minor = unit2minor(unit);
 2940         sminor = unit2minor(sunit);
 2941         va_start(ap, fmt);
 2942         i = vsnrprintf(namebuf, sizeof namebuf, 32, fmt, ap);
 2943         va_end(ap);
 2944         KASSERT(i < sizeof namebuf, ("Too long tty name (%s)", namebuf));
 2945 
 2946         cp = make_dev(csw, minor,
 2947             UID_ROOT, GID_WHEEL, 0600, "tty%s", namebuf);
 2948         tp->t_dev = cp;
 2949         tp->t_mdev = cp;
 2950         cp->si_tty = tp;
 2951         cp->si_drv1 = tp->t_sc;
 2952 
 2953         cp = make_dev(&ttys_cdevsw, sminor | MINOR_INIT,
 2954             UID_ROOT, GID_WHEEL, 0600, "tty%s.init", namebuf);
 2955         dev_depends(tp->t_dev, cp);
 2956         cp->si_drv1 = tp->t_sc;
 2957         cp->si_drv2 = &tp->t_init_in;
 2958         cp->si_tty = tp;
 2959 
 2960         cp = make_dev(&ttys_cdevsw, sminor | MINOR_LOCK,
 2961             UID_ROOT, GID_WHEEL, 0600, "tty%s.lock", namebuf);
 2962         dev_depends(tp->t_dev, cp);
 2963         cp->si_drv1 = tp->t_sc;
 2964         cp->si_drv2 = &tp->t_lock_in;
 2965         cp->si_tty = tp;
 2966 
 2967         if (flags & MINOR_CALLOUT) {
 2968                 cp = make_dev(csw, minor | MINOR_CALLOUT,
 2969                     UID_UUCP, GID_DIALER, 0660, "cua%s", namebuf);
 2970                 dev_depends(tp->t_dev, cp);
 2971                 cp->si_drv1 = tp->t_sc;
 2972                 cp->si_tty = tp;
 2973 
 2974                 cp = make_dev(&ttys_cdevsw, sminor | MINOR_CALLOUT | MINOR_INIT,
 2975                     UID_UUCP, GID_DIALER, 0660, "cua%s.init", namebuf);
 2976                 dev_depends(tp->t_dev, cp);
 2977                 cp->si_drv1 = tp->t_sc;
 2978                 cp->si_drv2 = &tp->t_init_out;
 2979                 cp->si_tty = tp;
 2980 
 2981                 cp = make_dev(&ttys_cdevsw, sminor | MINOR_CALLOUT | MINOR_LOCK,
 2982                     UID_UUCP, GID_DIALER, 0660, "cua%s.lock", namebuf);
 2983                 dev_depends(tp->t_dev, cp);
 2984                 cp->si_drv1 = tp->t_sc;
 2985                 cp->si_drv2 = &tp->t_lock_out;
 2986                 cp->si_tty = tp;
 2987         }
 2988 
 2989         return (0);
 2990 }
 2991 
 2992 /*
 2993  * This function is called when the hardware disappears.  We set a flag
 2994  * and wake up stuff so all sleeping threads will notice.
 2995  */
 2996 void    
 2997 ttygone(struct tty *tp)
 2998 {
 2999 
 3000         tp->t_state |= TS_GONE;
 3001         wakeup(&tp->t_dtr_wait);
 3002         wakeup(TSA_CARR_ON(tp));
 3003         wakeup(TSA_HUP_OR_INPUT(tp));
 3004         wakeup(TSA_OCOMPLETE(tp));
 3005         wakeup(TSA_OLOWAT(tp));
 3006         if (tp->t_purge != NULL)
 3007                 tp->t_purge(tp);
 3008 }
 3009 
 3010 /*
 3011  * ttyfree()
 3012  *    
 3013  * Called when the driver is ready to free the tty structure.
 3014  *
 3015  * XXX: This shall sleep until all threads have left the driver.
 3016  */
 3017  
 3018 void
 3019 ttyfree(struct tty *tp)
 3020 {
 3021         u_int unit;
 3022  
 3023         mtx_assert(&Giant, MA_OWNED);
 3024         ttygone(tp);
 3025         unit = tp->t_devunit;
 3026         destroy_dev(tp->t_mdev);
 3027         free_unr(tty_unit, unit);
 3028 }
 3029 
 3030 static int
 3031 sysctl_kern_ttys(SYSCTL_HANDLER_ARGS)
 3032 {
 3033         struct tty *tp, *tp2;
 3034         struct xtty xt;
 3035         int error;
 3036 
 3037         error = 0;
 3038         mtx_lock(&tty_list_mutex);
 3039         tp = TAILQ_FIRST(&tty_list);
 3040         if (tp != NULL)
 3041                 ttyref(tp);
 3042         mtx_unlock(&tty_list_mutex);
 3043         while (tp != NULL) {
 3044                 bzero(&xt, sizeof xt);
 3045                 xt.xt_size = sizeof xt;
 3046 #define XT_COPY(field) xt.xt_##field = tp->t_##field
 3047                 xt.xt_rawcc = tp->t_rawq.c_cc;
 3048                 xt.xt_cancc = tp->t_canq.c_cc;
 3049                 xt.xt_outcc = tp->t_outq.c_cc;
 3050                 XT_COPY(line);
 3051                 if (tp->t_dev != NULL)
 3052                         xt.xt_dev = dev2udev(tp->t_dev);
 3053                 XT_COPY(state);
 3054                 XT_COPY(flags);
 3055                 XT_COPY(timeout);
 3056                 if (tp->t_pgrp != NULL)
 3057                         xt.xt_pgid = tp->t_pgrp->pg_id;
 3058                 if (tp->t_session != NULL)
 3059                         xt.xt_sid = tp->t_session->s_sid;
 3060                 XT_COPY(termios);
 3061                 XT_COPY(winsize);
 3062                 XT_COPY(column);
 3063                 XT_COPY(rocount);
 3064                 XT_COPY(rocol);
 3065                 XT_COPY(ififosize);
 3066                 XT_COPY(ihiwat);
 3067                 XT_COPY(ilowat);
 3068                 XT_COPY(ispeedwat);
 3069                 XT_COPY(ohiwat);
 3070                 XT_COPY(olowat);
 3071                 XT_COPY(ospeedwat);
 3072 #undef XT_COPY
 3073                 error = SYSCTL_OUT(req, &xt, sizeof xt);
 3074                 if (error != 0) {
 3075                         ttyrel(tp);
 3076                         return (error);
 3077                 }
 3078                 mtx_lock(&tty_list_mutex);
 3079                 tp2 = TAILQ_NEXT(tp, t_list);
 3080                 if (tp2 != NULL)
 3081                         ttyref(tp2);
 3082                 mtx_unlock(&tty_list_mutex);
 3083                 ttyrel(tp);
 3084                 tp = tp2;
 3085         }
 3086         return (0);
 3087 }
 3088 
 3089 SYSCTL_PROC(_kern, OID_AUTO, ttys, CTLTYPE_OPAQUE|CTLFLAG_RD,
 3090         0, 0, sysctl_kern_ttys, "S,xtty", "All ttys");
 3091 SYSCTL_LONG(_kern, OID_AUTO, tty_nin, CTLFLAG_RD,
 3092         &tk_nin, 0, "Total TTY in characters");
 3093 SYSCTL_LONG(_kern, OID_AUTO, tty_nout, CTLFLAG_RD,
 3094         &tk_nout, 0, "Total TTY out characters");
 3095 
 3096 void
 3097 nottystop(struct tty *tp, int rw)
 3098 {
 3099 
 3100         return;
 3101 }
 3102 
 3103 int
 3104 ttyopen(struct cdev *dev, int flag, int mode, struct thread *td)
 3105 {
 3106         int             error;
 3107         int             s;
 3108         struct tty      *tp;
 3109 
 3110         tp = dev->si_tty;
 3111         s = spltty();
 3112         /*
 3113          * We jump to this label after all non-interrupted sleeps to pick
 3114          * up any changes of the device state.
 3115          */
 3116 open_top:
 3117         if (tp->t_state & TS_GONE)
 3118                 return (ENXIO);
 3119         error = ttydtrwaitsleep(tp);
 3120         if (error)
 3121                 goto out;
 3122         if (tp->t_state & TS_ISOPEN) {
 3123                 /*
 3124                  * The device is open, so everything has been initialized.
 3125                  * Handle conflicts.
 3126                  */
 3127                 if (ISCALLOUT(dev) && !tp->t_actout)
 3128                         return (EBUSY);
 3129                 if (tp->t_actout && !ISCALLOUT(dev)) {
 3130                         if (flag & O_NONBLOCK)
 3131                                 return (EBUSY);
 3132                         error = tsleep(&tp->t_actout,
 3133                                        TTIPRI | PCATCH, "ttybi", 0);
 3134                         if (error != 0 || (tp->t_flags & TS_GONE))
 3135                                 goto out;
 3136                         goto open_top;
 3137                 }
 3138                 if (tp->t_state & TS_XCLUDE && suser(td))
 3139                         return (EBUSY);
 3140         } else {
 3141                 /*
 3142                  * The device isn't open, so there are no conflicts.
 3143                  * Initialize it.  Initialization is done twice in many
 3144                  * cases: to preempt sleeping callin opens if we are
 3145                  * callout, and to complete a callin open after DCD rises.
 3146                  */
 3147                 tp->t_termios = ISCALLOUT(dev) ? tp->t_init_out : tp->t_init_in;
 3148                 tp->t_cflag = tp->t_termios.c_cflag;
 3149                 if (tp->t_modem != NULL)
 3150                         tp->t_modem(tp, SER_DTR | SER_RTS, 0);
 3151                 ++tp->t_wopeners;
 3152                 error = tp->t_param(tp, &tp->t_termios);
 3153                 --tp->t_wopeners;
 3154                 if (error == 0 && tp->t_open != NULL)
 3155                         error = tp->t_open(tp, dev);
 3156                 if (error != 0)
 3157                         goto out;
 3158                 if (ISCALLOUT(dev) || (tp->t_modem != NULL &&
 3159                     (tp->t_modem(tp, 0, 0) & SER_DCD)))
 3160                         ttyld_modem(tp, 1);
 3161         }
 3162         /*
 3163          * Wait for DCD if necessary.
 3164          */
 3165         if (!(tp->t_state & TS_CARR_ON) && !ISCALLOUT(dev)
 3166             && !(tp->t_cflag & CLOCAL) && !(flag & O_NONBLOCK)) {
 3167                 ++tp->t_wopeners;
 3168                 error = tsleep(TSA_CARR_ON(tp), TTIPRI | PCATCH, "ttydcd", 0);
 3169                 --tp->t_wopeners;
 3170                 if (error != 0 || (tp->t_state & TS_GONE))
 3171                         goto out;
 3172                 goto open_top;
 3173         }
 3174         error = ttyld_open(tp, dev);
 3175         ttyldoptim(tp);
 3176         if (tp->t_state & TS_ISOPEN && ISCALLOUT(dev))
 3177                 tp->t_actout = TRUE;
 3178 out:
 3179         splx(s);
 3180         if (!(tp->t_state & TS_ISOPEN) && tp->t_wopeners == 0 &&
 3181             tp->t_close != NULL)
 3182                 tp->t_close(tp);
 3183         return (error);
 3184 }
 3185 
 3186 int
 3187 ttyclose(struct cdev *dev, int flag, int mode, struct thread *td)
 3188 {
 3189         struct tty *tp;
 3190 
 3191         tp = dev->si_tty;
 3192         ttyld_close(tp, flag);
 3193         ttyldoptim(tp);
 3194         if (tp->t_close != NULL)
 3195                 tp->t_close(tp);
 3196         tp->t_do_timestamp = 0;
 3197         if (tp->t_pps != NULL)
 3198                 tp->t_pps->ppsparam.mode = 0;
 3199         tty_close(tp);
 3200         return (0);
 3201 }
 3202 
 3203 int
 3204 ttyread(struct cdev *dev, struct uio *uio, int flag)
 3205 {
 3206         struct tty *tp;
 3207 
 3208         tp = tty_gettp(dev);
 3209 
 3210         if (tp->t_state & TS_GONE)
 3211                 return (ENODEV);
 3212         return (ttyld_read(tp, uio, flag));
 3213 }
 3214 
 3215 int
 3216 ttywrite(struct cdev *dev, struct uio *uio, int flag)
 3217 {
 3218         struct tty *tp;
 3219 
 3220         tp = tty_gettp(dev);
 3221 
 3222         if (tp->t_state & TS_GONE)
 3223                 return (ENODEV);
 3224         return (ttyld_write(tp, uio, flag));
 3225 }
 3226 
 3227 int
 3228 ttyioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
 3229 {
 3230         struct  tty *tp;
 3231         int     error;
 3232 
 3233         tp = dev->si_tty;
 3234 
 3235         if (cmd == TIOCSETA || cmd == TIOCSETAW || cmd == TIOCSETAF) {
 3236                 int cc;
 3237                 struct termios *dt = (struct termios *)data;
 3238                 struct termios *lt =
 3239                     ISCALLOUT(dev) ?  &tp->t_lock_out : &tp->t_lock_in;
 3240 
 3241                 dt->c_iflag = (tp->t_iflag & lt->c_iflag)
 3242                     | (dt->c_iflag & ~lt->c_iflag);
 3243                 dt->c_oflag = (tp->t_oflag & lt->c_oflag)
 3244                     | (dt->c_oflag & ~lt->c_oflag);
 3245                 dt->c_cflag = (tp->t_cflag & lt->c_cflag)
 3246                     | (dt->c_cflag & ~lt->c_cflag);
 3247                 dt->c_lflag = (tp->t_lflag & lt->c_lflag)
 3248                     | (dt->c_lflag & ~lt->c_lflag);
 3249                 for (cc = 0; cc < NCCS; ++cc)
 3250                     if (lt->c_cc[cc] != 0)
 3251                         dt->c_cc[cc] = tp->t_cc[cc];
 3252                 if (lt->c_ispeed != 0)
 3253                     dt->c_ispeed = tp->t_ispeed;
 3254                 if (lt->c_ospeed != 0)
 3255                     dt->c_ospeed = tp->t_ospeed;
 3256         }
 3257 
 3258         error = ttyld_ioctl(tp, cmd, data, flag, td);
 3259         if (error == ENOIOCTL)
 3260                 error = ttioctl(tp, cmd, data, flag);
 3261         ttyldoptim(tp);
 3262         if (error != ENOIOCTL)
 3263                 return (error);
 3264         return (ENOTTY);
 3265 }
 3266 
 3267 void
 3268 ttyldoptim(struct tty *tp)
 3269 {
 3270         struct termios  *t;
 3271 
 3272         t = &tp->t_termios;
 3273         if (!(t->c_iflag & (ICRNL | IGNCR | IMAXBEL | INLCR | ISTRIP | IXON))
 3274             && (!(t->c_iflag & BRKINT) || (t->c_iflag & IGNBRK))
 3275             && (!(t->c_iflag & PARMRK)
 3276                 || (t->c_iflag & (IGNPAR | IGNBRK)) == (IGNPAR | IGNBRK))
 3277             && !(t->c_lflag & (ECHO | ICANON | IEXTEN | ISIG | PENDIN))
 3278             && linesw[tp->t_line]->l_rint == ttyinput)
 3279                 tp->t_state |= TS_CAN_BYPASS_L_RINT;
 3280         else
 3281                 tp->t_state &= ~TS_CAN_BYPASS_L_RINT;
 3282 }
 3283 
 3284 static void
 3285 ttydtrwaitwakeup(void *arg)
 3286 {
 3287         struct tty *tp;
 3288 
 3289         tp = arg;
 3290         tp->t_state &= ~TS_DTR_WAIT;
 3291         wakeup(&tp->t_dtr_wait);
 3292 }
 3293 
 3294 
 3295 void    
 3296 ttydtrwaitstart(struct tty *tp)
 3297 {
 3298 
 3299         if (tp->t_dtr_wait == 0)
 3300                 return;
 3301         if (tp->t_state & TS_DTR_WAIT)
 3302                 return;
 3303         timeout(ttydtrwaitwakeup, tp, tp->t_dtr_wait);
 3304         tp->t_state |= TS_DTR_WAIT;
 3305 }
 3306 
 3307 int
 3308 ttydtrwaitsleep(struct tty *tp)
 3309 {
 3310         int error;
 3311 
 3312         error = 0;
 3313         while (error == 0) {
 3314                 if (tp->t_state & TS_GONE)
 3315                         error = ENXIO;
 3316                 else if (!(tp->t_state & TS_DTR_WAIT))
 3317                         break;
 3318                 else
 3319                         error = tsleep(&tp->t_dtr_wait, TTIPRI | PCATCH,
 3320                             "dtrwait", 0);
 3321         }
 3322         return (error);
 3323 }
 3324 
 3325 static int
 3326 ttysopen(struct cdev *dev, int flag, int mode, struct thread *td)
 3327 {
 3328         struct tty *tp;
 3329 
 3330         tp = dev->si_tty;
 3331         KASSERT(tp != NULL,
 3332             ("ttysopen(): no tty pointer on device (%s)", devtoname(dev)));
 3333         if (tp->t_state & TS_GONE)
 3334                 return (ENODEV);
 3335         return (0);
 3336 }
 3337 
 3338 static int
 3339 ttysclose(struct cdev *dev, int flag, int mode, struct thread *td)
 3340 {
 3341 
 3342         return (0);
 3343 }
 3344 
 3345 static int
 3346 ttysrdwr(struct cdev *dev, struct uio *uio, int flag)
 3347 {
 3348 
 3349         return (ENODEV);
 3350 }
 3351 
 3352 static int
 3353 ttysioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
 3354 {
 3355         struct tty      *tp;
 3356         int             error;
 3357         struct termios  *ct;
 3358 
 3359         tp = dev->si_tty;
 3360         KASSERT(tp != NULL,
 3361             ("ttysopen(): no tty pointer on device (%s)", devtoname(dev)));
 3362         if (tp->t_state & TS_GONE)
 3363                 return (ENODEV);
 3364         ct = dev->si_drv2;
 3365         switch (cmd) {
 3366         case TIOCSETA:
 3367                 error = suser(td);
 3368                 if (error != 0)
 3369                         return (error);
 3370                 *ct = *(struct termios *)data;
 3371                 return (0);
 3372         case TIOCGETA:
 3373                 *(struct termios *)data = *ct;
 3374                 return (0);
 3375         case TIOCGETD:
 3376                 *(int *)data = TTYDISC;
 3377                 return (0);
 3378         case TIOCGWINSZ:
 3379                 bzero(data, sizeof(struct winsize));
 3380                 return (0);
 3381         default:
 3382                 if (tp->t_cioctl != NULL)
 3383                         return(tp->t_cioctl(dev, cmd, data, flag, td));
 3384                 return (ENOTTY);
 3385         }
 3386 }
 3387 
 3388 /*
 3389  * Initialize a tty to sane modes.
 3390  */
 3391 void
 3392 ttyinitmode(struct tty *tp, int echo, int speed)
 3393 {
 3394 
 3395         if (speed == 0)
 3396                 speed = TTYDEF_SPEED;
 3397         tp->t_init_in.c_iflag = TTYDEF_IFLAG;
 3398         tp->t_init_in.c_oflag = TTYDEF_OFLAG;
 3399         tp->t_init_in.c_cflag = TTYDEF_CFLAG;
 3400         if (echo)
 3401                 tp->t_init_in.c_lflag = TTYDEF_LFLAG_ECHO;
 3402         else
 3403                 tp->t_init_in.c_lflag = TTYDEF_LFLAG_NOECHO;
 3404 
 3405         tp->t_init_in.c_ispeed = tp->t_init_in.c_ospeed = speed;
 3406         termioschars(&tp->t_init_in);
 3407         tp->t_init_out = tp->t_init_in;
 3408         tp->t_termios = tp->t_init_in;
 3409 }
 3410 
 3411 /*
 3412  * Use more "normal" termios paramters for consoles.
 3413  */
 3414 void
 3415 ttyconsolemode(struct tty *tp, int speed)
 3416 {
 3417 
 3418         if (speed == 0)
 3419                 speed = TTYDEF_SPEED;
 3420         ttyinitmode(tp, 1, speed);
 3421         tp->t_init_in.c_cflag |= CLOCAL;
 3422         tp->t_lock_out.c_cflag = tp->t_lock_in.c_cflag = CLOCAL;
 3423         tp->t_lock_out.c_ispeed = tp->t_lock_out.c_ospeed =
 3424         tp->t_lock_in.c_ispeed = tp->t_lock_in.c_ospeed = speed;
 3425         tp->t_init_out = tp->t_init_in;
 3426         tp->t_termios = tp->t_init_in;
 3427 }
 3428 
 3429 /*
 3430  * Record the relationship between the serial ports notion of modem control
 3431  * signals and the one used in certain ioctls in a way the compiler can enforce
 3432  * XXX: We should define TIOCM_* in terms of SER_ if we can limit the
 3433  * XXX: consequences of the #include work that would take.
 3434  */
 3435 CTASSERT(SER_DTR == TIOCM_DTR / 2);
 3436 CTASSERT(SER_RTS == TIOCM_RTS / 2);
 3437 CTASSERT(SER_STX == TIOCM_ST / 2);
 3438 CTASSERT(SER_SRX == TIOCM_SR / 2);
 3439 CTASSERT(SER_CTS == TIOCM_CTS / 2);
 3440 CTASSERT(SER_DCD == TIOCM_DCD / 2);
 3441 CTASSERT(SER_RI == TIOCM_RI / 2);
 3442 CTASSERT(SER_DSR == TIOCM_DSR / 2);
 3443 

Cache object: 331ad0b41436d9e61d2e7f73126a028b


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.