curproc is null if no one is running, but ignore curproc unless wait is true
[unix-history] / usr / src / sys / kern / tty.c
index 0abd03a..02dd8ea 100644 (file)
@@ -1,21 +1,19 @@
-/*
- * Copyright (c) 1982, 1986 Regents of the University of California.
- * All rights reserved.  The Berkeley software License Agreement
- * specifies the terms and conditions for redistribution.
+/*-
+ * Copyright (c) 1982, 1986, 1990 The Regents of the University of California.
+ * Copyright (c) 1991 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * %sccs.include.redist.c%
  *
  *
- *     @(#)tty.c       7.16 (Berkeley) %G%
+ *     @(#)tty.c       7.45 (Berkeley) %G%
  */
 
 #include "param.h"
 #include "systm.h"
  */
 
 #include "param.h"
 #include "systm.h"
-#include "dir.h"
-#include "user.h"
 #include "ioctl.h"
 #include "ioctl.h"
-#include "tty.h"
 #define TTYDEFCHARS
 #define TTYDEFCHARS
-#include "ttydefaults.h"
+#include "tty.h"
 #undef TTYDEFCHARS
 #undef TTYDEFCHARS
-#include "termios.h"
 #define TTYDEFCHARS
 #include "ttydefaults.h"
 #undef TTYDEFCHARS
 #define TTYDEFCHARS
 #include "ttydefaults.h"
 #undef TTYDEFCHARS
 #include "dkstat.h"
 #include "uio.h"
 #include "kernel.h"
 #include "dkstat.h"
 #include "uio.h"
 #include "kernel.h"
+#include "vnode.h"
 #include "syslog.h"
 
 #include "syslog.h"
 
-#include "machine/reg.h"
+#include "vm/vm.h"
 #include "syslog.h"
 
 #include "syslog.h"
 
+static int proc_compare __P((struct proc *p1, struct proc *p2));
+
+/* symbolic sleep message strings */
+char ttyin[] = "ttyin";
+char ttyout[] = "ttyout";
+char ttopen[] = "ttyopn";
+char ttclos[] = "ttycls";
+char ttybg[] = "ttybg";
+char ttybuf[] = "ttybuf";
+
 /*
  * Table giving parity for characters and indicating
  * character classes to tty driver. The 8th bit
  * indicates parity, the 7th bit indicates the character
  * is an alphameric or underscore (for ALTWERASE), and the 
  * low 6 bits indicate delay type.  If the low 6 bits are 0
 /*
  * Table giving parity for characters and indicating
  * character classes to tty driver. The 8th bit
  * indicates parity, the 7th bit indicates the character
  * is an alphameric or underscore (for ALTWERASE), and the 
  * low 6 bits indicate delay type.  If the low 6 bits are 0
- * then the character needs no special processing on output.
+ * then the character needs no special processing on output;
+ * classes other than 0 might be translated or (not currently)
+ * require delays.
  */
  */
+#define        PARITY(c)       (partab[c] & 0x80)
+#define        ISALPHA(c)      (partab[(c)&TTY_CHARMASK] & 0x40)
+#define        CCLASSMASK      0x3f
+#define        CCLASS(c)       (partab[c] & CCLASSMASK)
+
+#define        E       0x00    /* even parity */
+#define        O       0x80    /* odd parity */
+#define        ALPHA   0x40    /* alpha or underscore */
+
+#define        NO      ORDINARY
+#define        NA      ORDINARY|ALPHA
+#define        CC      CONTROL
+#define        BS      BACKSPACE
+#define        NL      NEWLINE
+#define        TB      TAB
+#define        VT      VTAB
+#define        CR      RETURN
 
 char partab[] = {
 
 char partab[] = {
-       0001,0201,0201,0001,0201,0001,0001,0201,        /* nul - bel */
-       0202,0004,0003,0201,0005,0206,0201,0001,        /* bs - si */
-       0201,0001,0001,0201,0001,0201,0201,0001,        /* dle - etb */
-       0001,0201,0201,0001,0201,0001,0001,0201,        /* can - us */
-       0200,0000,0000,0200,0000,0200,0200,0000,        /* sp - ' */
-       0000,0200,0200,0000,0200,0000,0000,0200,        /* ( - / */
-       0100,0300,0300,0100,0300,0100,0100,0300,        /* 0 - 7 */
-       0300,0100,0000,0200,0000,0200,0200,0000,        /* 8 - ? */
-       0200,0100,0100,0300,0100,0300,0300,0100,        /* @ - G */
-       0100,0300,0300,0100,0300,0100,0100,0300,        /* H - O */
-       0100,0300,0300,0100,0300,0100,0100,0300,        /* P - W */
-       0300,0100,0100,0200,0000,0200,0200,0300,        /* X - _ */
-       0000,0300,0300,0100,0300,0100,0100,0300,        /* ` - g */
-       0300,0100,0100,0300,0100,0300,0300,0100,        /* h - o */
-       0300,0100,0100,0300,0100,0300,0300,0100,        /* p - w */
-       0100,0300,0300,0000,0200,0000,0000,0201,        /* x - del */
+       E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC, /* nul - bel */
+       O|BS, E|TB, E|NL, O|CC, E|VT, O|CR, O|CC, E|CC, /* bs - si */
+       O|CC, E|CC, E|CC, O|CC, E|CC, O|CC, O|CC, E|CC, /* dle - etb */
+       E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC, /* can - us */
+       O|NO, E|NO, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* sp - ' */
+       E|NO, O|NO, O|NO, E|NO, O|NO, E|NO, E|NO, O|NO, /* ( - / */
+       E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* 0 - 7 */
+       O|NA, E|NA, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* 8 - ? */
+       O|NO, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* @ - G */
+       E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* H - O */
+       E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* P - W */
+       O|NA, E|NA, E|NA, O|NO, E|NO, O|NO, O|NO, O|NA, /* X - _ */
+       E|NO, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* ` - g */
+       O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* h - o */
+       O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* p - w */
+       E|NA, O|NA, O|NA, E|NO, O|NO, E|NO, E|NO, O|CC, /* x - del */
        /*
        /*
-        * meta chars
+        * "meta" chars; should be settable per charset.
+        * For now, treat all as normal characters.
         */
         */
-       0001,0201,0201,0001,0201,0001,0001,0201,        /* nul - bel */
-       0202,0004,0003,0201,0005,0206,0201,0001,        /* bs - si */
-       0201,0001,0001,0201,0001,0201,0201,0001,        /* dle - etb */
-       0001,0201,0201,0001,0201,0001,0001,0201,        /* can - us */
-       0200,0000,0000,0200,0000,0200,0200,0000,        /* sp - ' */
-       0000,0200,0200,0000,0200,0000,0000,0200,        /* ( - / */
-       0100,0300,0300,0100,0300,0100,0100,0300,        /* 0 - 7 */
-       0300,0100,0000,0200,0000,0200,0200,0000,        /* 8 - ? */
-       0200,0100,0100,0300,0100,0300,0300,0100,        /* @ - G */
-       0100,0300,0300,0100,0300,0100,0100,0300,        /* H - O */
-       0100,0300,0300,0100,0300,0100,0100,0300,        /* P - W */
-       0300,0100,0100,0200,0000,0200,0200,0300,        /* X - _ */
-       0000,0300,0300,0100,0300,0100,0100,0300,        /* ` - g */
-       0300,0100,0100,0300,0100,0300,0300,0100,        /* h - o */
-       0300,0100,0100,0300,0100,0300,0300,0100,        /* p - w */
-       0100,0300,0300,0000,0200,0000,0000,0201,        /* x - del */
+       NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
+       NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
+       NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
+       NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
+       NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
+       NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
+       NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
+       NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
+       NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
+       NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
+       NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
+       NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
+       NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
+       NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
+       NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
+       NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
 };
 };
+#undef NO
+#undef NA
+#undef CC
+#undef BS
+#undef NL
+#undef TB
+#undef VT
+#undef CR
 
 extern struct tty *constty;            /* temporary virtual console */
 
 extern struct tty *constty;            /* temporary virtual console */
-extern char partab[], maptab[];
 
 /*
  * Is 'c' a line delimiter ("break" character)?
  */
 
 /*
  * Is 'c' a line delimiter ("break" character)?
  */
-#define ttbreakc(c) (c == '\n' || CCEQ(cc[VEOF], c) || \
-               CCEQ(cc[VEOL], c) || CCEQ(cc[VEOL2], c))
+#define ttbreakc(c) ((c) == '\n' || ((c) == cc[VEOF] || \
+       (c) == cc[VEOL] || (c) == cc[VEOL2]) && (c) != _POSIX_VDISABLE)
 
 /*
  * Debugging aids
 
 /*
  * Debugging aids
@@ -101,19 +137,22 @@ extern char partab[], maptab[];
 ttychars(tp)
        struct tty *tp;
 {
 ttychars(tp)
        struct tty *tp;
 {
+
        bcopy(ttydefchars, tp->t_cc, sizeof(ttydefchars));
 }
 
 /*
  *
        bcopy(ttydefchars, tp->t_cc, sizeof(ttydefchars));
 }
 
 /*
  *
- * Wait for output to drain, then flush input waiting.
+ * Flush tty after output has drained.
  */
 ttywflush(tp)
        struct tty *tp;
 {
  */
 ttywflush(tp)
        struct tty *tp;
 {
+       int error;
 
 
-       ttywait(tp);
-       ttyflush(tp, FREAD);
+       if ((error = ttywait(tp)) == 0)
+               ttyflush(tp, FREAD);
+       return (error);
 }
 
 /*
 }
 
 /*
@@ -125,20 +164,30 @@ ttywflush(tp)
 ttywait(tp)
        register struct tty *tp;
 {
 ttywait(tp)
        register struct tty *tp;
 {
-       int s = spltty();
+       int error = 0, s = spltty();
 
        while ((tp->t_outq.c_cc || tp->t_state&TS_BUSY) &&
            (tp->t_state&TS_CARR_ON || tp->t_cflag&CLOCAL) && 
            tp->t_oproc) {
                (*tp->t_oproc)(tp);
                tp->t_state |= TS_ASLEEP;
 
        while ((tp->t_outq.c_cc || tp->t_state&TS_BUSY) &&
            (tp->t_state&TS_CARR_ON || tp->t_cflag&CLOCAL) && 
            tp->t_oproc) {
                (*tp->t_oproc)(tp);
                tp->t_state |= TS_ASLEEP;
-               sleep((caddr_t)&tp->t_outq, TTOPRI);
+               if (error = ttysleep(tp, (caddr_t)&tp->t_outq, 
+                   TTOPRI | PCATCH, ttyout, 0))
+                       break;
        }
        splx(s);
        }
        splx(s);
+       return (error);
+}
+
+#define        flushq(qq) { \
+       register struct clist *q = qq; \
+       if (q->c_cc) \
+               ndflush(q, q->c_cc); \
 }
 
 /*
 }
 
 /*
- * Flush all TTY queues
+ * Flush TTY read and/or write queues,
+ * notifying anyone waiting.
  */
 ttyflush(tp, rw)
        register struct tty *tp;
  */
 ttyflush(tp, rw)
        register struct tty *tp;
@@ -147,23 +196,23 @@ ttyflush(tp, rw)
 
        s = spltty();
        if (rw & FREAD) {
 
        s = spltty();
        if (rw & FREAD) {
-               while (getc(&tp->t_canq) >= 0)
-                       ;
+               flushq(&tp->t_canq);
+               flushq(&tp->t_rawq);
+               tp->t_rocount = 0;
+               tp->t_rocol = 0;
+               tp->t_state &= ~TS_LOCAL;
                ttwakeup(tp);
        }
        if (rw & FWRITE) {
                ttwakeup(tp);
        }
        if (rw & FWRITE) {
-               wakeup((caddr_t)&tp->t_outq); /* XXX? what about selwakeup? */
                tp->t_state &= ~TS_TTSTOP;
                (*cdevsw[major(tp->t_dev)].d_stop)(tp, rw);
                tp->t_state &= ~TS_TTSTOP;
                (*cdevsw[major(tp->t_dev)].d_stop)(tp, rw);
-               while (getc(&tp->t_outq) >= 0)
-                       ;
-       }
-       if (rw & FREAD) {
-               while (getc(&tp->t_rawq) >= 0)
-                       ;
-               tp->t_rocount = 0;
-               tp->t_rocol = 0;
-               tp->t_state &= ~TS_LOCAL;
+               flushq(&tp->t_outq);
+               wakeup((caddr_t)&tp->t_outq);
+               if (tp->t_wsel) {
+                       selwakeup(tp->t_wsel, tp->t_state & TS_WCOLL);
+                       tp->t_wsel = 0;
+                       tp->t_state &= ~TS_WCOLL;
+               }
        }
        splx(s);
 }
        }
        splx(s);
 }
@@ -185,7 +234,7 @@ ttyblock(tp)
         * Block further input iff:
         * Current input > threshold AND input is available to user program
         */
         * Block further input iff:
         * Current input > threshold AND input is available to user program
         */
-       if (x >= TTYHOG/2 && 
+       if (x >= TTYHOG/2 && (tp->t_state & TS_TBLOCK) == 0 &&
            (!(tp->t_lflag&ICANON)) || (tp->t_canq.c_cc > 0) &&
            tp->t_cc[VSTOP] != POSIX_V_DISABLE) {
                if (putc(tp->t_cc[VSTOP], &tp->t_outq)==0) {
            (!(tp->t_lflag&ICANON)) || (tp->t_canq.c_cc > 0) &&
            tp->t_cc[VSTOP] != POSIX_V_DISABLE) {
                if (putc(tp->t_cc[VSTOP], &tp->t_outq)==0) {
@@ -195,50 +244,43 @@ ttyblock(tp)
        }
 }
 
        }
 }
 
-/*
- * Restart typewriter output following a delay
- * timeout.
- * The name of the routine is passed to the timeout
- * subroutine and it is called during a clock interrupt.
- */
-ttrstrt(tp)
+ttstart(tp)
        struct tty *tp;
 {
 
        struct tty *tp;
 {
 
-       if (tp == 0)
-               panic("ttrstrt");
-       tp->t_state &= ~TS_TIMEOUT;
-       ttstart(tp);
+       if (tp->t_oproc)                /* kludge for pty */
+               (*tp->t_oproc)(tp);
 }
 
 }
 
-/*
- * Start output on the typewriter. It is used from the top half
- * after some characters have been put on the output queue,
- * from the interrupt routine to transmit the next
- * character, and after a timeout has finished.
- */
-ttstart(tp)
+ttrstrt(tp)                            /* XXX */
        struct tty *tp;
 {
 
        struct tty *tp;
 {
 
-       if (tp->t_oproc)                /* kludge for pty */
-               (*tp->t_oproc)(tp);
+#ifdef DIAGNOSTIC
+       if (tp == 0)
+               panic("ttrstrt");
+#endif
+       tp->t_state &= ~TS_TIMEOUT;
+       ttstart(tp);
 }
 
 }
 
+
 /*
 /*
- * Common code for tty ioctls.
+ * Common code for ioctls on tty devices.
+ * Called after line-discipline-specific ioctl
+ * has been called to do discipline-specific functions
+ * and/or reject any of these ioctl commands.
  */
 /*ARGSUSED*/
 ttioctl(tp, com, data, flag)
        register struct tty *tp;
        caddr_t data;
 {
  */
 /*ARGSUSED*/
 ttioctl(tp, com, data, flag)
        register struct tty *tp;
        caddr_t data;
 {
+       register struct proc *p = curproc;              /* XXX */
        extern int nldisp;
        extern int nldisp;
-       int softset = 0;
        int soft;
        int s, error;
 
        int soft;
        int s, error;
 
-
        /*
         * If the ioctl involves modification,
         * hang if in the background.
        /*
         * If the ioctl involves modification,
         * hang if in the background.
@@ -252,17 +294,24 @@ ttioctl(tp, com, data, flag)
        case TIOCSETA:
        case TIOCSETAW:
        case TIOCSETAF:
        case TIOCSETA:
        case TIOCSETAW:
        case TIOCSETAF:
-       case TIOCSETAS:
-       case TIOCSETAWS:
-       case TIOCSETAFS:
-               while (u.u_procp->p_pgid != tp->t_pgid &&
-                  tp == u.u_ttyp &&
-                  u.u_procp->p_pgrp->pg_jobc &&
-                  (u.u_procp->p_flag&SVFORK) == 0 &&
-                  !(u.u_procp->p_sigignore & sigmask(SIGTTOU)) &&
-                  !(u.u_procp->p_sigmask & sigmask(SIGTTOU))) {
-                       pgsignal(u.u_procp->p_pgrp, SIGTTOU);
-                       sleep((caddr_t)&lbolt, TTOPRI);
+#ifdef COMPAT_43
+       case TIOCSETP:
+       case TIOCSETN:
+       case TIOCSETC:
+       case TIOCSLTC:
+       case TIOCLBIS:
+       case TIOCLBIC:
+       case TIOCLSET:
+       case OTIOCSETD:
+#endif
+               while (isbackground(curproc, tp) && 
+                  p->p_pgrp->pg_jobc && (p->p_flag&SPPWAIT) == 0 &&
+                  (p->p_sigignore & sigmask(SIGTTOU)) == 0 &&
+                  (p->p_sigmask & sigmask(SIGTTOU)) == 0) {
+                       pgsignal(p->p_pgrp, SIGTTOU, 1);
+                       if (error = ttysleep(tp, (caddr_t)&lbolt, 
+                           TTOPRI | PCATCH, ttybg, 0)) 
+                               return (error);
                }
                break;
        }
                }
                break;
        }
@@ -282,13 +331,12 @@ ttioctl(tp, com, data, flag)
                register int t = *(int *)data;
                dev_t dev = tp->t_dev;
                dev_t dev = tp->t_dev;
                register int t = *(int *)data;
                dev_t dev = tp->t_dev;
                dev_t dev = tp->t_dev;
-               int error = 0;
 
                if ((unsigned)t >= nldisp)
                        return (ENXIO);
                if (t != tp->t_line) {
                        s = spltty();
 
                if ((unsigned)t >= nldisp)
                        return (ENXIO);
                if (t != tp->t_line) {
                        s = spltty();
-                       (*linesw[tp->t_line].l_close)(tp);
+                       (*linesw[tp->t_line].l_close)(tp, flag);
                        error = (*linesw[t].l_open)(dev, tp);
                        if (error) {
                                (void)(*linesw[tp->t_line].l_open)(dev, tp);
                        error = (*linesw[t].l_open)(dev, tp);
                        if (error) {
                                (void)(*linesw[tp->t_line].l_open)(dev, tp);
@@ -369,9 +417,9 @@ ttioctl(tp, com, data, flag)
         * Simulate typing of a character at the terminal.
         */
        case TIOCSTI:
         * Simulate typing of a character at the terminal.
         */
        case TIOCSTI:
-               if (u.u_uid && (flag & FREAD) == 0)
+               if (p->p_ucred->cr_uid && (flag & FREAD) == 0)
                        return (EPERM);
                        return (EPERM);
-               if (u.u_uid && u.u_ttyp != tp)
+               if (p->p_ucred->cr_uid && !isctty(p, tp))
                        return (EACCES);
                (*linesw[tp->t_line].l_rint)(*(char *)data, tp);
                break;
                        return (EACCES);
                (*linesw[tp->t_line].l_rint)(*(char *)data, tp);
                break;
@@ -414,6 +462,13 @@ ttioctl(tp, com, data, flag)
                }
                tp->t_iflag = t->c_iflag;
                tp->t_oflag = t->c_oflag;
                }
                tp->t_iflag = t->c_iflag;
                tp->t_oflag = t->c_oflag;
+               /*
+                * Make the EXTPROC bit read only.
+                */
+               if (tp->t_lflag&EXTPROC)
+                       t->c_lflag |= EXTPROC;
+               else
+                       t->c_lflag &= ~EXTPROC;
                tp->t_lflag = t->c_lflag;
                bcopy(t->c_cc, tp->t_cc, sizeof(t->c_cc));
                splx(s);
                tp->t_lflag = t->c_lflag;
                bcopy(t->c_cc, tp->t_cc, sizeof(t->c_cc));
                splx(s);
@@ -426,30 +481,27 @@ ttioctl(tp, com, data, flag)
         * Set terminal process group.
         */
        case TIOCSPGRP: {
         * Set terminal process group.
         */
        case TIOCSPGRP: {
-               register struct proc *p = u.u_procp;
                register struct pgrp *pgrp = pgfind(*(int *)data);
 
                register struct pgrp *pgrp = pgfind(*(int *)data);
 
-               if (u.u_uid && 
-                   (tp != u.u_ttyp ||
-                   (pgrp && pgrp->pg_session != p->p_session))) {
-                       if (u.u_ttyp == NULL)
-                               return (ENOTTY);
-                       else
-                               return (EPERM);
-               }
-               tp->t_pgid = *(int *)data;
+               if (!isctty(p, tp))
+                       return (ENOTTY);
+               else if (pgrp == NULL || pgrp->pg_session != p->p_session)
+                       return (EPERM);
+               tp->t_pgrp = pgrp;
                break;
        }
 
        case TIOCGPGRP:
                break;
        }
 
        case TIOCGPGRP:
-               *(int *)data = tp->t_pgid;
+               if (!isctty(p, tp))
+                       return (ENOTTY);
+               *(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
                break;
 
        case TIOCSWINSZ:
                if (bcmp((caddr_t)&tp->t_winsize, data,
                    sizeof (struct winsize))) {
                        tp->t_winsize = *(struct winsize *)data;
                break;
 
        case TIOCSWINSZ:
                if (bcmp((caddr_t)&tp->t_winsize, data,
                    sizeof (struct winsize))) {
                        tp->t_winsize = *(struct winsize *)data;
-                       gsignal(tp->t_pgid, SIGWINCH);
+                       pgsignal(tp->t_pgrp, SIGWINCH, 1);
                }
                break;
 
                }
                break;
 
@@ -459,10 +511,12 @@ ttioctl(tp, com, data, flag)
 
        case TIOCCONS:
                if (*(int *)data) {
 
        case TIOCCONS:
                if (*(int *)data) {
-                       if (constty != NULL)
+                       if (constty && constty != tp &&
+                           (constty->t_state & (TS_CARR_ON|TS_ISOPEN)) ==
+                           (TS_CARR_ON|TS_ISOPEN))
                                return (EBUSY);
 #ifndef        UCONSOLE
                                return (EBUSY);
 #ifndef        UCONSOLE
-                       if (error = suser(u.u_cred, &u.u_acflag))
+                       if (error = suser(p->p_ucred, &p->p_acflag))
                                return (error);
 #endif
                        constty = tp;
                                return (error);
 #endif
                        constty = tp;
@@ -470,22 +524,10 @@ ttioctl(tp, com, data, flag)
                        constty = NULL;
                break;
 
                        constty = NULL;
                break;
 
-#ifdef COMPAT_43
-       case TIOCGETP:
-       case TIOCSETP:
-       case TIOCSETN:
-       case TIOCGETC:
-       case TIOCSETC:
-       case TIOCSLTC:
-       case TIOCGLTC:
-       case TIOCLBIS:
-       case TIOCLBIC:
-       case TIOCLSET:
-       case TIOCLGET:
-       case TIOCGETDCOMPAT:
-       case TIOCSETDCOMPAT:
-               return(ttcompat(tp, com, data, flag));
-#endif
+       case TIOCDRAIN:
+               if (error = ttywait(tp))
+                       return (error);
+               break;
 
        /* allow old ioctls for now */
        case TIOCGETP:
 
        /* allow old ioctls for now */
        case TIOCGETP:
@@ -502,7 +544,11 @@ ttioctl(tp, com, data, flag)
                return(ottioctl(tp, com, data, flag));
 
        default:
                return(ottioctl(tp, com, data, flag));
 
        default:
+#ifdef COMPAT_43
+               return (ttcompat(tp, com, data, flag));
+#else
                return (-1);
                return (-1);
+#endif
        }
        return (0);
 }
        }
        return (0);
 }
@@ -573,12 +619,12 @@ ttselect(dev, rw)
        case FREAD:
                nread = ttnread(tp);
                if (nread > 0 || 
        case FREAD:
                nread = ttnread(tp);
                if (nread > 0 || 
-                  (!(tp->t_cflag&CLOCAL) && !(tp->t_state&TS_CARR_ON)))
+                  ((tp->t_cflag&CLOCAL) == 0 && (tp->t_state&TS_CARR_ON) == 0))
                        goto win;
                if (tp->t_rsel && tp->t_rsel->p_wchan == (caddr_t)&selwait)
                        tp->t_state |= TS_RCOLL;
                else
                        goto win;
                if (tp->t_rsel && tp->t_rsel->p_wchan == (caddr_t)&selwait)
                        tp->t_state |= TS_RCOLL;
                else
-                       tp->t_rsel = u.u_procp;
+                       tp->t_rsel = curproc;
                break;
 
        case FWRITE:
                break;
 
        case FWRITE:
@@ -587,7 +633,7 @@ ttselect(dev, rw)
                if (tp->t_wsel && tp->t_wsel->p_wchan == (caddr_t)&selwait)
                        tp->t_state |= TS_WCOLL;
                else
                if (tp->t_wsel && tp->t_wsel->p_wchan == (caddr_t)&selwait)
                        tp->t_state |= TS_WCOLL;
                else
-                       tp->t_wsel = u.u_procp;
+                       tp->t_wsel = curproc;
                break;
        }
        splx(s);
                break;
        }
        splx(s);
@@ -598,13 +644,12 @@ win:
 }
 
 /*
 }
 
 /*
- * Initial open of tty, or (re)entry to line discipline.
+ * Initial open of tty, or (re)entry to standard tty line discipline.
  */
 ttyopen(dev, tp)
        dev_t dev;
        register struct tty *tp;
 {
  */
 ttyopen(dev, tp)
        dev_t dev;
        register struct tty *tp;
 {
-       register struct proc *pp;
 
        tp->t_dev = dev;
 
 
        tp->t_dev = dev;
 
@@ -623,15 +668,21 @@ ttyopen(dev, tp)
 /*
  * "close" a line discipline
  */
 /*
  * "close" a line discipline
  */
-ttylclose(tp)
-       register struct tty *tp;
+ttylclose(tp, flag)
+       struct tty *tp;
+       int flag;
 {
 
 {
 
-       ttywflush(tp);
+       if (flag&IO_NDELAY)
+               ttyflush(tp, FREAD|FWRITE);
+       else
+               ttywflush(tp);
 }
 
 /*
 }
 
 /*
- * clean tp on last close
+ * Handle close() on a tty line: flush and set to initial state,
+ * bumping generation number so that pending read/write calls
+ * can detect recycling of the tty.
  */
 ttyclose(tp)
        register struct tty *tp;
  */
 ttyclose(tp)
        register struct tty *tp;
@@ -639,8 +690,11 @@ ttyclose(tp)
        if (constty == tp)
                constty = NULL;
        ttyflush(tp, FREAD|FWRITE);
        if (constty == tp)
                constty = NULL;
        ttyflush(tp, FREAD|FWRITE);
-       tp->t_pgid = 0;
+       tp->t_session = NULL;
+       tp->t_pgrp = NULL;
        tp->t_state = 0;
        tp->t_state = 0;
+       tp->t_gen++;
+       return (0);
 }
 
 /*
 }
 
 /*
@@ -668,13 +722,11 @@ ttymodem(tp, flag)
                 * Lost carrier.
                 */
                tp->t_state &= ~TS_CARR_ON;
                 * Lost carrier.
                 */
                tp->t_state &= ~TS_CARR_ON;
-               if (tp->t_state & TS_ISOPEN) {
-                       if ((tp->t_lflag & NOHANG) == 0) {
-                               gsignal(tp->t_pgid, SIGHUP);
-                               gsignal(tp->t_pgid, SIGCONT);
-                               ttyflush(tp, FREAD|FWRITE);
-                               return (0);
-                       }
+               if (tp->t_state&TS_ISOPEN && (tp->t_cflag&CLOCAL) == 0) {
+                       if (tp->t_session && tp->t_session->s_leader)
+                               psignal(tp->t_session->s_leader, SIGHUP);
+                       ttyflush(tp, FREAD|FWRITE);
+                       return (0);
                }
        } else {
                /*
                }
        } else {
                /*
@@ -697,9 +749,15 @@ nullmodem(tp, flag)
        
        if (flag)
                tp->t_state |= TS_CARR_ON;
        
        if (flag)
                tp->t_state |= TS_CARR_ON;
-       else
+       else {
                tp->t_state &= ~TS_CARR_ON;
                tp->t_state &= ~TS_CARR_ON;
-       return (flag);
+               if ((tp->t_cflag&CLOCAL) == 0) {
+                       if (tp->t_session && tp->t_session->s_leader)
+                               psignal(tp->t_session->s_leader, SIGHUP);
+                       return (0);
+               }
+       }
+       return (1);
 }
 
 /*
 }
 
 /*
@@ -723,13 +781,7 @@ ttypend(tp)
 }
 
 /*
 }
 
 /*
- *
- *
- * Place a character on raw TTY input queue,
- * putting in delimiters and waking up top
- * half as needed.  Also echo if required.
- * The arguments are the character and the
- * appropriate tty structure.
+ * Process input of a single character received on a tty.
  */
 ttyinput(c, tp)
        register c;
  */
 ttyinput(c, tp)
        register c;
@@ -792,21 +844,7 @@ ttyinput(c, tp)
         * In tandem mode, check high water mark.
         */
        if ((tp->t_state&TS_TYPEN) == 0 && (iflag&ISTRIP))
         * In tandem mode, check high water mark.
         */
        if ((tp->t_state&TS_TYPEN) == 0 && (iflag&ISTRIP))
-               c &= 0177;
-       /*
-        * Check for literal nexting very first
-        */
-       if (tp->t_state&TS_LNCH) {
-               c |= TTY_QUOTE;
-               tp->t_state &= ~TS_LNCH;
-       }
-       /*
-        * Scan for special characters.  This code
-        * is really just a big case statement with
-        * non-constant cases.  The bottom of the
-        * case statement is labeled ``endcase'', so goto
-        * it after a case match, or similar.
-        */
+               c &= ~0x80;
 
        /*
         * Extensions to POSIX input modes which aren't controlled
 
        /*
         * Extensions to POSIX input modes which aren't controlled
@@ -816,46 +854,25 @@ ttyinput(c, tp)
                if (CCEQ(cc[VLNEXT],c) && (iflag&ISTRIP)) {
                        if (lflag&ECHO)
                                ttyout("^\b", tp); /*XXX - presumes too much */
                if (CCEQ(cc[VLNEXT],c) && (iflag&ISTRIP)) {
                        if (lflag&ECHO)
                                ttyout("^\b", tp); /*XXX - presumes too much */
-                       tp->t_state |= TS_LNCH;
-                       goto endcase;
                }
                }
-               if (CCEQ(cc[VFLUSHO],c)) {
-                       if (lflag&FLUSHO)
-                               tp->t_lflag &= ~FLUSHO;
-                       else {
-                               ttyflush(tp, FWRITE);
+               /*
+                * Signals.
+                */
+               if (lflag&ISIG) {
+                       if (CCEQ(cc[VINTR], c) || CCEQ(cc[VQUIT], c)) {
+                               if ((lflag&NOFLSH) == 0)
+                                       ttyflush(tp, FREAD|FWRITE);
                                ttyecho(c, tp);
                                ttyecho(c, tp);
-                               if (tp->t_rawq.c_cc + tp->t_canq.c_cc)
-                                       ttyretype(tp);
                                tp->t_lflag |= FLUSHO;
                        }
                                tp->t_lflag |= FLUSHO;
                        }
-                       goto startoutput;
-               }
-       }
-
-       /*
-        * Signals.
-        */
-       if (lflag&ISIG) {
-               if (CCEQ(cc[VINTR], c) || CCEQ(cc[VQUIT], c)) {
-                       if ((lflag&NOFLSH) == 0)
-                               ttyflush(tp, FREAD|FWRITE);
-                       ttyecho(c, tp);
-                       gsignal(tp->t_pgrp, CCEQ(cc[VINTR],c) ? 
-                               SIGINT : SIGQUIT);
-                       goto endcase;
-               }
-               if (CCEQ(cc[VSUSP],c)) {
-                       if ((lflag&NOFLSH) == 0)
-                               ttyflush(tp, FREAD);
-                       ttyecho(c, tp);
-                       gsignal(tp->t_pgid, SIGTSTP);
-                       goto endcase;
+                       if (CCEQ(cc[VSUSP], c)) {
+                               if ((lflag&NOFLSH) == 0)
+                                       ttyflush(tp, FREAD);
+                               ttyecho(c, tp);
+                               pgsignal(tp->t_pgrp, SIGTSTP, 1);
+                               goto endcase;
+                       }
                }
                }
-       }
-       /*
-        * Handle start/stop characters.
-        */
        if (iflag&IXON) {
                if (CCEQ(cc[VSTOP],c)) {
                        if ((tp->t_state&TS_TTSTOP) == 0) {
        if (iflag&IXON) {
                if (CCEQ(cc[VSTOP],c)) {
                        if ((tp->t_state&TS_TTSTOP) == 0) {
@@ -873,78 +890,6 @@ ttyinput(c, tp)
                if (CCEQ(cc[VSTART], c))
                        goto restartoutput;
        }
                if (CCEQ(cc[VSTART], c))
                        goto restartoutput;
        }
-       /*
-        * IGNCR, ICRNL, & INLCR
-        */
-       if (c == '\r') {
-               if (iflag&IGNCR)
-                       goto endcase;
-               else if (iflag&ICRNL)
-                       c = '\n';
-       }
-       else if (c == '\n' && iflag&INLCR)
-               c = '\r';
-       else if (c == '\n' && iflag&INLCR)
-               c = '\r';
-       /*
-        * Non canonical mode, don't process line editing
-        * characters; check high water mark for wakeup.
-        * 
-        * 
-        */
-       if (!(lflag&ICANON)) {
-               if (tp->t_rawq.c_cc > TTYHOG) {
-                       if (iflag&IMAXBEL) {
-                               if (tp->t_outq.c_cc < tp->t_hiwat)
-                                       (void) ttyoutput(CTRL('g'), tp);
-                       } else
-                               ttyflush(tp, FREAD | FWRITE);
-               } else {
-                       if (putc(c, &tp->t_rawq) >= 0) {
-                               ttwakeup(tp);
-                               ttyecho(c, tp);
-                       }
-               }
-               goto endcase;
-       }
-       /*
-        * From here on down canonical mode character
-        * processing takes place.
-        */
-
-       /* 
-        * Oldstyle quoting of erase, kill, and eof chars.
-        *
-        * Historically is '\' , but can be changed (read: disabled)
-        * with the VQUOTE subscript.
-        */
-
-       /*
-        * erase (^H / ^?)
-        */
-       if (CCEQ(cc[VERASE], c)) {
-               if (tp->t_rawq.c_cc)
-                       ttyrub(unputc(&tp->t_rawq), tp);
-               goto endcase;
-       }
-               if (lflag&ECHOKE && tp->t_rawq.c_cc == tp->t_rocount &&
-                   !(lflag&ECHOPRT)) {
-                       while (tp->t_rawq.c_cc)
-                               ttyrub(unputc(&tp->t_rawq), tp);
-               } else {
-                       ttyecho(c, tp);
-                       if (lflag&ECHOK || lflag&ECHOKE)
-                               ttyecho('\n', tp);
-                       while (getc(&tp->t_rawq) > 0)
-                               ;
-                       tp->t_rocount = 0;
-               }
-               tp->t_state &= ~TS_LOCAL;
-               goto endcase;
-       }
-       /*
-        * word erase (^W)
-        */
                        c = unputc(&tp->t_rawq);
                } while (c != ' ' && c != '\t');
                (void) putc(c, &tp->t_rawq);
                        c = unputc(&tp->t_rawq);
                } while (c != ' ' && c != '\t');
                (void) putc(c, &tp->t_rawq);
@@ -957,17 +902,10 @@ ttyinput(c, tp)
                ttyretype(tp);
                goto endcase;
        }
                ttyretype(tp);
                goto endcase;
        }
-       /*
-        * reprint line (^R)
-        */
-       if (CCEQ(cc[VREPRINT], c)) {
-               ttyretype(tp);
-               goto endcase;
-       }
        /*
         * Check for input buffer overflow
         */
        /*
         * Check for input buffer overflow
         */
-       if (tp->t_rawq.c_cc+tp->t_canq.c_cc >= TTYHOG) {
+       if (tp->t_rawq.c_cc + tp->t_canq.c_cc >= TTYHOG) {
                if (iflag&IMAXBEL) {
                        if (tp->t_outq.c_cc < TTHIWAT(tp))
                                (void) ttyoutput(CTRL('g'), tp);
                if (iflag&IMAXBEL) {
                        if (tp->t_outq.c_cc < TTHIWAT(tp))
                                (void) ttyoutput(CTRL('g'), tp);
@@ -980,6 +918,11 @@ ttyinput(c, tp)
         * wakeup on seeing a line delimiter.
         */
        if (putc(c, &tp->t_rawq) >= 0) {
         * wakeup on seeing a line delimiter.
         */
        if (putc(c, &tp->t_rawq) >= 0) {
+               if ((lflag&ICANON) == 0) {
+                       ttwakeup(tp);
+                       ttyecho(c, tp);
+                       goto endcase;
+               }
                if (ttbreakc(c)) {
                        tp->t_rocount = 0;
                        catq(&tp->t_rawq, &tp->t_canq);
                if (ttbreakc(c)) {
                        tp->t_rocount = 0;
                        catq(&tp->t_rawq, &tp->t_canq);
@@ -1027,20 +970,16 @@ startoutput:
 }
 
 /*
 }
 
 /*
- * Put character on TTY output queue, adding delays,
- * expanding tabs, and handling the CR/NL bit.
- * This is called both from the top half for output,
- * and from interrupt level for echoing.
- * The arguments are the character and the tty structure.
- * Returns < 0 if putc succeeds, otherwise returns char to resend
+ * Output a single character on a tty, doing output processing
+ * as needed (expanding tabs, newline processing, etc.).
+ * Returns < 0 if putc succeeds, otherwise returns char to resend.
  * Must be recursive.
  */
 ttyoutput(c, tp)
        register c;
        register struct tty *tp;
 {
  * Must be recursive.
  */
 ttyoutput(c, tp)
        register c;
        register struct tty *tp;
 {
-       register char *colp;
-       register ctype;
+       register int col;
        if (!(tp->t_oflag&OPOST)) {
                if (tp->t_lflag&FLUSHO) 
                        return (-1);
        if (!(tp->t_oflag&OPOST)) {
                if (tp->t_lflag&FLUSHO) 
                        return (-1);
@@ -1052,7 +991,11 @@ ttyoutput(c, tp)
        }
        c &= 0377;
        /*
        }
        c &= 0377;
        /*
-        * Turn tabs to spaces as required
+        * Do tab expansion if OXTABS is set.
+        * Special case if we have external processing, we don't
+        * do the tab expansion because we'll probably get it
+        * wrong.  If tab expansion needs to be done, let it
+        * happen externally.
         */
        if (c == '\t' && tp->t_oflag&OXTABS ) {
                register int s;
         */
        if (c == '\t' && tp->t_oflag&OXTABS ) {
                register int s;
@@ -1069,102 +1012,51 @@ ttyoutput(c, tp)
                return (c ? -1 : '\t');
        }
        if (c == CEOT && oflag&ONOEOT)
                return (c ? -1 : '\t');
        }
        if (c == CEOT && oflag&ONOEOT)
-               return(-1);
+               return (-1);
        tk_nout++;
        tp->t_outcc++;
 #ifdef notdef
        /*
        tk_nout++;
        tp->t_outcc++;
 #ifdef notdef
        /*
-        * turn <nl> to <cr><lf> if desired.
+        * Newline translation: if ONLCR is set,
+        * translate newline into "\r\n".
         */
 #endif
        if ((tp->t_lflag&FLUSHO) == 0 && putc(c, &tp->t_outq))
                return (c);
        if ((tp->t_lflag&FLUSHO) == 0 && putc(c, &tp->t_outq))
                return (c);
         */
 #endif
        if ((tp->t_lflag&FLUSHO) == 0 && putc(c, &tp->t_outq))
                return (c);
        if ((tp->t_lflag&FLUSHO) == 0 && putc(c, &tp->t_outq))
                return (c);
-       /*
-        * Calculate delays.
-        * The numbers here represent clock ticks
-        * and are not necessarily optimal for all terminals.
-        *
-        * SHOULD JUST ALLOW USER TO SPECIFY DELAYS
-        *
-        * (actually, should THROW AWAY terminals which need delays)
-        */
-       colp = &tp->t_col;
-       ctype = partab[c];
-       c = 0;
-       switch (ctype&077) {
+
+       col = tp->t_col;
+       switch (CCLASS(c)) {
 
        case ORDINARY:
 
        case ORDINARY:
-               (*colp)++;
+               col++;
 
        case CONTROL:
                break;
 
        case BACKSPACE:
 
        case CONTROL:
                break;
 
        case BACKSPACE:
-               if (*colp)
-                       (*colp)--;
+               if (col > 0)
+                       col--;
                break;
 
                break;
 
-       /*
-        * This macro is close enough to the correct thing;
-        * it should be replaced by real user settable delays
-        * in any event...
-        */
-#define        mstohz(ms)      (((ms) * hz) >> 10)
        case NEWLINE:
        case NEWLINE:
-               ctype = (tp->t_flags >> 8) & 03;
-               if (ctype == 1) { /* tty 37 */
-                       if (*colp > 0) {
-                               c = (((unsigned)*colp) >> 4) + 3;
-                               if ((unsigned)c > 6)
-                                       c = 6;
-                       }
-               } else if (ctype == 2) /* vt05 */
-                       c = mstohz(100);
-               *colp = 0;
+               col = 0;
                break;
 
        case TAB:
                break;
 
        case TAB:
-               ctype = (tp->t_flags >> 10) & 03;
-               if (ctype == 1) { /* tty 37 */
-                       c = 1 - (*colp | ~07);
-                       if (c < 5)
-                               c = 0;
-               }
-               *colp |= 07;
-               (*colp)++;
-               break;
-
-       case VTAB:
-               if (tp->t_flags&VTDELAY) /* tty 37 */
-                       c = 0177;
+               col = (col + 8) &~ 0x7;
                break;
 
        case RETURN:
                break;
 
        case RETURN:
-               ctype = (tp->t_flags >> 12) & 03;
-               if (ctype == 1) /* tn 300 */
-                       c = mstohz(83);
-               else if (ctype == 2) /* ti 700 */
-                       c = mstohz(166);
-               else if (ctype == 3) { /* concept 100 */
-                       int i;
-
-                       if ((i = *colp) >= 0)
-                               for (; i < 9; i++)
-                                       (void) putc(0177, &tp->t_outq);
-               }
-               *colp = 0;
+               col = 0;
        }
        }
-       if (c && (tp->t_lflag&FLUSHO) == 0)
-               (void) putc(c|TTY_QUOTE, &tp->t_outq);
+       tp->t_col = col;
        return (-1);
 }
        return (-1);
 }
-#undef mstohz
 
 /*
 
 /*
- * Called from device's read routine after it has
- * calculated the tty-structure given as argument.
+ * Process a read call on a tty device.
  */
 ttread(tp, uio, flag)
        register struct tty *tp;
  */
 ttread(tp, uio, flag)
        register struct tty *tp;
@@ -1179,71 +1071,63 @@ ttread(tp, uio, flag)
 
 
 loop:
 
 
 loop:
+       lflag = tp->t_lflag;
        s = spltty();
        /*
         * take pending input first 
         */
        if (tp->t_lflag&PENDIN)
                ttypend(tp);
        s = spltty();
        /*
         * take pending input first 
         */
        if (tp->t_lflag&PENDIN)
                ttypend(tp);
-       /*
-        * Handle carrier.
-        */
-       if (!(tp->t_state&TS_CARR_ON) && !(tp->t_cflag&CLOCAL)) {
-               if (tp->t_state&TS_ISOPEN) {
-                       splx(s);
-                       return (0);     /* EOF */
-               } else if (flag&FNDELAY) {
-                       splx(s);
-                       return (EWOULDBLOCK);
-               } else {
-                       /*
-                        * sleep awaiting carrier
-                        */
-                       sleep((caddr_t)&tp->t_rawq, TTIPRI);
-                       splx(s);
-                       goto loop;
-               }
-       }
        splx(s);
        splx(s);
+
        /*
         * Hang process if it's in the background.
         */
        /*
         * Hang process if it's in the background.
         */
-       if (u.u_ttyp == tp && u.u_procp->p_pgid != tp->t_pgid) {
-               if ((u.u_procp->p_sigignore & sigmask(SIGTTIN)) ||
-                  (u.u_procp->p_sigmask & sigmask(SIGTTIN)) ||
-                   u.u_procp->p_flag&SVFORK || u.u_procp->p_pgrp->pg_jobc == 0)
+       if (isbackground(p, tp)) {
+               if ((p->p_sigignore & sigmask(SIGTTIN)) ||
+                  (p->p_sigmask & sigmask(SIGTTIN)) ||
+                   p->p_flag&SPPWAIT || p->p_pgrp->pg_jobc == 0)
                        return (EIO);
                        return (EIO);
-               pgsignal(u.u_procp->p_pgrp, SIGTTIN);
-               sleep((caddr_t)&lbolt, TTIPRI);
+               pgsignal(p->p_pgrp, SIGTTIN, 1);
+               if (error = ttysleep(tp, (caddr_t)&lbolt, TTIPRI | PCATCH, 
+                   ttybg, 0)) 
+                       return (error);
                goto loop;
        }
                goto loop;
        }
+
        /*
         * If canonical, use the canonical queue,
         * else use the raw queue.
         */
        qp = lflag&ICANON ? &tp->t_canq : &tp->t_rawq;
        /*
         * If canonical, use the canonical queue,
         * else use the raw queue.
         */
        qp = lflag&ICANON ? &tp->t_canq : &tp->t_rawq;
+
        /*
        /*
-        * No input, sleep on rawq awaiting hardware
-        * receipt and notification.
+        * If there is no input, sleep on rawq
+        * awaiting hardware receipt and notification.
+        * If we have data, we don't need to check for carrier.
         */
        s = spltty();
        if (qp->c_cc <= 0) {
         */
        s = spltty();
        if (qp->c_cc <= 0) {
-               /** XXX ??? ask mike why TS_CARR_ON was (once) necessary here
-               if ((tp->t_state&TS_CARR_ON) == 0 ||
-                   (tp->t_state&TS_NBIO)) {
+               int carrier;
+
+               carrier = (tp->t_state&TS_CARR_ON) || (tp->t_cflag&CLOCAL);
+               if (!carrier && tp->t_state&TS_ISOPEN) {
                        splx(s);
                        splx(s);
-                       return (EWOULDBLOCK);
+                       return (0);     /* EOF */
                }
                }
-               **/
-               if (flag&FNDELAY) {
+               if (flag & IO_NDELAY) {
                        splx(s);
                        return (EWOULDBLOCK);
                }
                        splx(s);
                        return (EWOULDBLOCK);
                }
-               sleep((caddr_t)&tp->t_rawq, TTIPRI);
+               error = ttysleep(tp, (caddr_t)&tp->t_rawq, TTIPRI | PCATCH,
+                   carrier ? ttyin : ttopen, 0);
                splx(s);
                splx(s);
+               if (error)
+                       return (error);
                goto loop;
        }
        splx(s);
                goto loop;
        }
        splx(s);
+
        /*
         * Input present, check for input mapping and processing.
         */
        /*
         * Input present, check for input mapping and processing.
         */
@@ -1253,9 +1137,11 @@ loop:
                 * delayed suspend (^Y)
                 */
                if (CCEQ(cc[VDSUSP], c) && lflag&ISIG) {
                 * delayed suspend (^Y)
                 */
                if (CCEQ(cc[VDSUSP], c) && lflag&ISIG) {
-                       gsignal(tp->t_pgid, SIGTSTP);
+                       pgsignal(tp->t_pgrp, SIGTSTP, 1);
                        if (first) {
                        if (first) {
-                               sleep((caddr_t)&lbolt, TTIPRI);
+                               if (error = ttysleep(tp, (caddr_t)&lbolt,
+                                   TTIPRI | PCATCH, ttybg, 0))
+                                       break;
                                goto loop;
                        }
                        break;
                                goto loop;
                        }
                        break;
@@ -1280,10 +1166,8 @@ loop:
                if (lflag&ICANON && ttbreakc(c)) {
                        break;
                }
                if (lflag&ICANON && ttbreakc(c)) {
                        break;
                }
-               }
                first = 0;
        }
                first = 0;
        }
-checktandem:
        /*
         * Look to unblock output now that (presumably)
         * the input queue has gone down.
        /*
         * Look to unblock output now that (presumably)
         * the input queue has gone down.
@@ -1312,14 +1196,16 @@ ttycheckoutq(tp, wait)
        int wait;
 {
        int hiwat, s, oldsig;
        int wait;
 {
        int hiwat, s, oldsig;
+       extern int wakeup();
 
        hiwat = tp->t_hiwat;
        s = spltty();
 
        hiwat = tp->t_hiwat;
        s = spltty();
-       oldsig = u.u_procp->p_sig;
+       if (wait)
+               oldsig = curproc->p_sig;
        if (tp->t_outq.c_cc > hiwat + 200)
                while (tp->t_outq.c_cc > hiwat) {
                        ttstart(tp);
        if (tp->t_outq.c_cc > hiwat + 200)
                while (tp->t_outq.c_cc > hiwat) {
                        ttstart(tp);
-                       if (wait == 0 || u.u_procp->p_sig != oldsig) {
+                       if (wait == 0 || curproc->p_sig != oldsig) {
                                splx(s);
                                return (0);
                        }
                                splx(s);
                                return (0);
                        }
@@ -1332,15 +1218,15 @@ ttycheckoutq(tp, wait)
 }
 
 /*
 }
 
 /*
- * Called from the device's write routine after it has
- * calculated the tty-structure given as argument.
+ * Process a write call on a tty device.
  */
 ttwrite(tp, uio, flag)
        register struct tty *tp;
        register struct uio *uio;
 {
        register char *cp;
  */
 ttwrite(tp, uio, flag)
        register struct tty *tp;
        register struct uio *uio;
 {
        register char *cp;
-       register int cc, ce, c;
+       register int cc = 0, ce;
+       register struct proc *p = curproc;
        int i, hiwat, cnt, error, s;
        char obuf[OBUFSIZ];
 
        int i, hiwat, cnt, error, s;
        char obuf[OBUFSIZ];
 
@@ -1349,19 +1235,23 @@ ttwrite(tp, uio, flag)
        error = 0;
 loop:
        s = spltty();
        error = 0;
 loop:
        s = spltty();
-       if (!(tp->t_state&TS_CARR_ON) && !(tp->t_cflag&CLOCAL)) {
+       if ((tp->t_state&TS_CARR_ON) == 0 && (tp->t_cflag&CLOCAL) == 0) {
                if (tp->t_state&TS_ISOPEN) {
                        splx(s);
                        return (EIO);
                if (tp->t_state&TS_ISOPEN) {
                        splx(s);
                        return (EIO);
-               } else if (flag&FNDELAY) {
+               } else if (flag & IO_NDELAY) {
                        splx(s);
                        splx(s);
-                       return (EWOULDBLOCK);
+                       error = EWOULDBLOCK;
+                       goto out;
                } else {
                        /*
                         * sleep awaiting carrier
                         */
                } else {
                        /*
                         * sleep awaiting carrier
                         */
-                       sleep((caddr_t)&tp->t_rawq, TTIPRI);
+                       error = ttysleep(tp, (caddr_t)&tp->t_rawq, 
+                                       TTIPRI | PCATCH,ttopen, 0);
                        splx(s);
                        splx(s);
+                       if (error)
+                               goto out;
                        goto loop;
                }
        }
                        goto loop;
                }
        }
@@ -1369,45 +1259,43 @@ loop:
        /*
         * Hang the process if it's in the background.
         */
        /*
         * Hang the process if it's in the background.
         */
-           (tp->t_lflag&TOSTOP) && (u.u_procp->p_flag&SVFORK)==0 &&
-           !(u.u_procp->p_sigignore & sigmask(SIGTTOU)) &&
-           !(u.u_procp->p_sigmask & sigmask(SIGTTOU)) &&
-            u.u_procp->p_pgrp->pg_jobc) {
-               pgsignal(u.u_procp->p_pgrp, SIGTTOU);
-               sleep((caddr_t)&lbolt, TTIPRI);
+       if (isbackground(p, tp) && 
+           tp->t_lflag&TOSTOP && (p->p_flag&SPPWAIT) == 0 &&
+           (p->p_sigignore & sigmask(SIGTTOU)) == 0 &&
+           (p->p_sigmask & sigmask(SIGTTOU)) == 0 &&
+            p->p_pgrp->pg_jobc) {
+               pgsignal(p->p_pgrp, SIGTTOU, 1);
+               if (error = ttysleep(tp, (caddr_t)&lbolt, TTIPRI | PCATCH, 
+                   ttybg, 0))
+                       goto out;
                goto loop;
        }
        /*
         * Process the user's data in at most OBUFSIZ
                goto loop;
        }
        /*
         * Process the user's data in at most OBUFSIZ
-        * chunks.  Perform lower case simulation and
-        * similar hacks.  Keep track of high water
-        * mark, sleep on overflow awaiting device aid
-        * in acquiring new space.
+        * chunks.  Perform any output translation.
+        * Keep track of high water mark, sleep on overflow
+        * awaiting device aid in acquiring new space.
         */
         */
-       while (uio->uio_resid > 0) {
-               if (tp->t_outq.c_cc > hiwat) {
-                       cc = 0;
-                       goto ovhiwat;
+       while (uio->uio_resid > 0 || cc > 0) {
+               if (tp->t_lflag&FLUSHO) {
+                       uio->uio_resid = 0;
+                       return (0);
                }
                }
+               if (tp->t_outq.c_cc > hiwat)
+                       goto ovhiwat;
                /*
                /*
-                * Grab a hunk of data from the user.
+                * Grab a hunk of data from the user,
+                * unless we have some leftover from last time.
                 */
                 */
-               cc = uio->uio_iov->iov_len;
                if (cc == 0) {
                if (cc == 0) {
-                       uio->uio_iovcnt--;
-                       uio->uio_iov++;
-                       if (uio->uio_iovcnt <= 0)
-                               panic("ttwrite");
-                       continue;
+                       cc = min(uio->uio_resid, OBUFSIZ);
+                       cp = obuf;
+                       error = uiomove(cp, cc, uio);
+                       if (error) {
+                               cc = 0;
+                               break;
+                       }
                }
                }
-               if (cc > OBUFSIZ)
-                       cc = OBUFSIZ;
-               cp = obuf;
-               error = uiomove(cp, cc, UIO_WRITE, uio);
-               if (error)
-                       break;
-               if (tp->t_lflag&FLUSHO)
-                       continue;
 #ifdef notdef
                /*
                 * If nothing fancy need be done, grab those characters we
 #ifdef notdef
                /*
                 * If nothing fancy need be done, grab those characters we
@@ -1423,7 +1311,7 @@ loop:
                                ce = cc;
                        else {
                                ce = cc - scanc((unsigned)cc, (u_char *)cp,
                                ce = cc;
                        else {
                                ce = cc - scanc((unsigned)cc, (u_char *)cp,
-                                  (u_char *)partab, 077);
+                                  (u_char *)partab, CCLASSMASK);
                                /*
                                 * If ce is zero, then we're processing
                                 * a special character through ttyoutput.
                                /*
                                 * If ce is zero, then we're processing
                                 * a special character through ttyoutput.
@@ -1433,13 +1321,10 @@ loop:
                                        if (ttyoutput(*cp, tp) >= 0) {
                                            /* no c-lists, wait a bit */
                                            ttstart(tp);
                                        if (ttyoutput(*cp, tp) >= 0) {
                                            /* no c-lists, wait a bit */
                                            ttstart(tp);
-                                           sleep((caddr_t)&lbolt, TTOPRI);
-                                           if (cc != 0) {
-                                               uio->uio_iov->iov_base -= cc;
-                                               uio->uio_iov->iov_len += cc;
-                                               uio->uio_resid += cc;
-                                               uio->uio_offset -= cc;
-                                           }
+                                           if (error = ttysleep(tp, 
+                                               (caddr_t)&lbolt,
+                                                TTOPRI | PCATCH, ttybuf, 0))
+                                                   break;
                                            goto loop;
                                        }
                                        cp++, cc--;
                                            goto loop;
                                        }
                                        cp++, cc--;
@@ -1466,27 +1351,28 @@ loop:
                        if (i > 0) {
                                /* out of c-lists, wait a bit */
                                ttstart(tp);
                        if (i > 0) {
                                /* out of c-lists, wait a bit */
                                ttstart(tp);
-                               sleep((caddr_t)&lbolt, TTOPRI);
-                               uio->uio_iov->iov_base -= cc;
-                               uio->uio_iov->iov_len += cc;
-                               uio->uio_resid += cc;
-                               uio->uio_offset -= cc;
+                               if (error = ttysleep(tp, (caddr_t)&lbolt,
+                                           TTOPRI | PCATCH, ttybuf, 0))
+                                       break;
                                goto loop;
                        }
                        if (tp->t_lflag&FLUSHO || tp->t_outq.c_cc > hiwat)
                                goto loop;
                        }
                        if (tp->t_lflag&FLUSHO || tp->t_outq.c_cc > hiwat)
-                               goto ovhiwat;
+                               break;
                }
                ttstart(tp);
                ttstart(tp);
        }
                }
                ttstart(tp);
                ttstart(tp);
        }
+out:
+       /*
+        * If cc is nonzero, we leave the uio structure inconsistent,
+        * as the offset and iov pointers have moved forward,
+        * but it doesn't matter (the call will either return short
+        * or restart with a new uio).
+        */
+       uio->uio_resid += cc;
        return (error);
        return (error);
+
 ovhiwat:
 ovhiwat:
-       if (cc != 0) {
-               uio->uio_iov->iov_base -= cc;
-               uio->uio_iov->iov_len += cc;
-               uio->uio_resid += cc;
-               uio->uio_offset -= cc;
-       }
        ttstart(tp);
        s = spltty();
        /*
        ttstart(tp);
        s = spltty();
        /*
@@ -1497,15 +1383,18 @@ ovhiwat:
                splx(s);
                goto loop;
        }
                splx(s);
                goto loop;
        }
-       if (flag&FNDELAY) {
+       if (flag & IO_NDELAY) {
                splx(s);
                splx(s);
+               uio->uio_resid += cc;
                if (uio->uio_resid == cnt)
                        return (EWOULDBLOCK);
                return (0);
        }
        tp->t_state |= TS_ASLEEP;
                if (uio->uio_resid == cnt)
                        return (EWOULDBLOCK);
                return (0);
        }
        tp->t_state |= TS_ASLEEP;
-       sleep((caddr_t)&tp->t_outq, TTOPRI);
+       error = ttysleep(tp, (caddr_t)&tp->t_outq, TTOPRI | PCATCH, ttyout, 0);
        splx(s);
        splx(s);
+       if (error)
+               goto out;
        goto loop;
 }
 
        goto loop;
 }
 
@@ -1535,7 +1424,7 @@ ttyrub(c, tp)
                /* if tab or newline was escaped  - XXX - not 8bit */
                if (c == ('\t'|TTY_QUOTE) || c == ('\n'|TTY_QUOTE))
                        ttyrubo(tp, 2);
                /* if tab or newline was escaped  - XXX - not 8bit */
                if (c == ('\t'|TTY_QUOTE) || c == ('\n'|TTY_QUOTE))
                        ttyrubo(tp, 2);
-               else switch (partab[c&=0377]&077) {
+               else switch (CCLASS(c &= TTY_CHARMASK)) {
 
                case ORDINARY:
 #ifdef notdef
 
                case ORDINARY:
 #ifdef notdef
@@ -1546,6 +1435,7 @@ ttyrub(c, tp)
                case BACKSPACE:
                case CONTROL:
                case RETURN:
                case BACKSPACE:
                case CONTROL:
                case RETURN:
+               case NEWLINE:
                        if (tp->t_lflag&ECHOCTL)
                                ttyrubo(tp, 2);
                        break;
                        if (tp->t_lflag&ECHOCTL)
                                ttyrubo(tp, 2);
                        break;
@@ -1581,7 +1471,7 @@ ttyrub(c, tp)
                default:
                        /* XXX */
                        printf("ttyrub: would panic c = %d, val = %d\n",
                default:
                        /* XXX */
                        printf("ttyrub: would panic c = %d, val = %d\n",
-                               c, partab[c&=0377]&077);
+                               c, CCLASS(c));
                        /*panic("ttyrub");*/
                }
        } else if (tp->t_lflag&ECHOPRT) {
                        /*panic("ttyrub");*/
                }
        } else if (tp->t_lflag&ECHOPRT) {
@@ -1606,7 +1496,7 @@ ttyrubo(tp, cnt)
        register char *rubostring = tp->t_lflag&ECHOE ? "\b \b" : "\b";
 
        while (--cnt >= 0)
        register char *rubostring = tp->t_lflag&ECHOE ? "\b \b" : "\b";
 
        while (--cnt >= 0)
-               ttyout("\b \b", tp);
+               ttyoutstr("\b \b", tp);
 }
 
 /*
 }
 
 /*
@@ -1651,7 +1541,8 @@ ttyecho(c, tp)
        if ((tp->t_lflag&ECHO) == 0 && !(tp->t_lflag&ECHONL && c == '\n'))
                return;
        if (tp->t_lflag&ECHOCTL) {
        if ((tp->t_lflag&ECHO) == 0 && !(tp->t_lflag&ECHONL && c == '\n'))
                return;
        if (tp->t_lflag&ECHOCTL) {
-               if ((c&TTY_CHARMASK)<=037 && c!='\t' && c!='\n' || c==0177) {
+               if ((c&TTY_CHARMASK) <= 037 && c != '\t' && c != '\n' ||
+                   c == 0177) {
                        (void) ttyoutput('^', tp);
                        c &= TTY_CHARMASK;
                        if (c == 0177)
                        (void) ttyoutput('^', tp);
                        c &= TTY_CHARMASK;
                        if (c == 0177)
@@ -1665,7 +1556,7 @@ ttyecho(c, tp)
        (void) ttyoutput(c, tp);
  * send string cp to tp
  */
        (void) ttyoutput(c, tp);
  * send string cp to tp
  */
-ttyout(cp, tp)
+ttyoutstr(cp, tp)
        register char *cp;
        register struct tty *tp;
 {
        register char *cp;
        register struct tty *tp;
 {
@@ -1675,8 +1566,11 @@ ttyout(cp, tp)
                (void) ttyoutput(c, tp);
 }
 
                (void) ttyoutput(c, tp);
 }
 
+/*
+ * Wake up any readers on a tty.
+ */
 ttwakeup(tp)
 ttwakeup(tp)
-       struct tty *tp;
+       register struct tty *tp;
 {
 
        if (tp->t_rsel) {
 {
 
        if (tp->t_rsel) {
@@ -1685,10 +1579,24 @@ ttwakeup(tp)
                tp->t_rsel = 0;
        }
        if (tp->t_state & TS_ASYNC)
                tp->t_rsel = 0;
        }
        if (tp->t_state & TS_ASYNC)
-               gsignal(tp->t_pgid, SIGIO); 
+               pgsignal(tp->t_pgrp, SIGIO, 1); 
        wakeup((caddr_t)&tp->t_rawq);
 }
 
        wakeup((caddr_t)&tp->t_rawq);
 }
 
+/*
+ * Look up a code for a specified speed in a conversion table;
+ * used by drivers to map software speed values to hardware parameters.
+ */
+ttspeedtab(speed, table)
+       register struct speedtab *table;
+{
+
+       for ( ; table->sp_speed != -1; table++)
+               if (table->sp_speed == speed)
+                       return (table->sp_code);
+       return (-1);
+}
+
 /*
  * set tty hi and low water marks
  *
 /*
  * set tty hi and low water marks
  *
@@ -1710,13 +1618,183 @@ ttsetwater(tp)
 #undef clamp
 }
 
 #undef clamp
 }
 
-ttspeedtab(speed, table)
-       struct speedtab table[];
+/*
+ * Report on state of foreground process group.
+ */
+ttyinfo(tp)
+       register struct tty *tp;
+{
+       register struct proc *p, *pick;
+       struct timeval utime, stime;
+       int tmp;
+
+       if (ttycheckoutq(tp,0) == 0) 
+               return;
+
+       /* Print load average. */
+       tmp = (averunnable[0] * 100 + FSCALE / 2) >> FSHIFT;
+       ttyprintf(tp, "load: %d.%02d ", tmp / 100, tmp % 100);
+
+       if (tp->t_session == NULL)
+               ttyprintf(tp, "not a controlling terminal\n");
+       else if (tp->t_pgrp == NULL)
+               ttyprintf(tp, "no foreground process group\n");
+       else if ((p = tp->t_pgrp->pg_mem) == NULL)
+               ttyprintf(tp, "empty foreground process group\n");
+       else {
+               /* Pick interesting process. */
+               for (pick = NULL; p != NULL; p = p->p_pgrpnxt)
+                       if (proc_compare(pick, p))
+                               pick = p;
+
+               ttyprintf(tp, " cmd: %s %d [%s] ", pick->p_comm, pick->p_pid,
+                   pick->p_stat == SRUN ? "running" :
+                   pick->p_wmesg ? pick->p_wmesg : "iowait");
+
+               /*
+                * Lock out clock if process is running; get user/system
+                * cpu time.
+                */
+               if (curproc == pick)
+                       tmp = splclock();
+               utime = pick->p_utime;
+               stime = pick->p_stime;
+               if (curproc == pick)
+                       splx(tmp);
+
+               /* Print user time. */
+               ttyprintf(tp, "%d.%02du ",
+                   utime.tv_sec, (utime.tv_usec + 5000) / 10000);
+
+               /* Print system time. */
+               ttyprintf(tp, "%d.%02ds ",
+                   stime.tv_sec, (stime.tv_usec + 5000) / 10000);
+
+#define        pgtok(a)        (((a) * NBPG) / 1024)
+               /* Print percentage cpu, resident set size. */
+               tmp = pick->p_pctcpu * 10000 + FSCALE / 2 >> FSHIFT;
+               ttyprintf(tp, "%d%% %dk\n",
+                  tmp / 100, pgtok(pick->p_vmspace->vm_rssize));
+       }
+       tp->t_rocount = 0;      /* so pending input will be retyped if BS */
+}
+
+/*
+ * Returns 1 if p2 is "better" than p1
+ *
+ * The algorithm for picking the "interesting" process is thus:
+ *
+ *     1) (Only foreground processes are eligable - implied)
+ *     2) Runnable processes are favored over anything
+ *        else.  The runner with the highest cpu
+ *        utilization is picked (p_cpu).  Ties are
+ *        broken by picking the highest pid.
+ *     3  Next, the sleeper with the shortest sleep
+ *        time is favored.  With ties, we pick out
+ *        just "short-term" sleepers (SSINTR == 0).
+ *        Further ties are broken by picking the highest
+ *        pid.
+ *
+ */
+#define isrun(p)       (((p)->p_stat == SRUN) || ((p)->p_stat == SIDL))
+#define TESTAB(a, b)    ((a)<<1 | (b))
+#define ONLYA   2
+#define ONLYB   1
+#define BOTH    3
+
+static int
+proc_compare(p1, p2)
+       register struct proc *p1, *p2;
+{
+
+       if (p1 == NULL)
+               return (1);
+       /*
+        * see if at least one of them is runnable
+        */
+       switch (TESTAB(isrun(p1), isrun(p2))) {
+       case ONLYA:
+               return (0);
+       case ONLYB:
+               return (1);
+       case BOTH:
+               /*
+                * tie - favor one with highest recent cpu utilization
+                */
+               if (p2->p_cpu > p1->p_cpu)
+                       return (1);
+               if (p1->p_cpu > p2->p_cpu)
+                       return (0);
+               return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
+       }
+       /*
+        * weed out zombies
+        */
+       switch (TESTAB(p1->p_stat == SZOMB, p2->p_stat == SZOMB)) {
+       case ONLYA:
+               return (1);
+       case ONLYB:
+               return (0);
+       case BOTH:
+               return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
+       }
+       /* 
+        * pick the one with the smallest sleep time
+        */
+       if (p2->p_slptime > p1->p_slptime)
+               return (0);
+       if (p1->p_slptime > p2->p_slptime)
+               return (1);
+       /*
+        * favor one sleeping in a non-interruptible sleep
+        */
+       if (p1->p_flag&SSINTR && (p2->p_flag&SSINTR) == 0)
+               return (1);
+       if (p2->p_flag&SSINTR && (p1->p_flag&SSINTR) == 0)
+               return (0);
+       return (p2->p_pid > p1->p_pid);         /* tie - return highest pid */
+}
+
+/*
+ * Output char to tty; console putchar style.
+ */
+tputchar(c, tp)
+       int c;
+       struct tty *tp;
 {
 {
-       register int i;
+       register s = spltty();
 
 
-       for (i = 0; table[i].sp_speed != -1; i++)
-               if (table[i].sp_speed == speed)
-                       return(table[i].sp_code);
-       return(-1);
+       if ((tp->t_state & (TS_CARR_ON|TS_ISOPEN)) == (TS_CARR_ON|TS_ISOPEN)) {
+               if (c == '\n')
+                       (void) ttyoutput('\r', tp);
+               (void) ttyoutput(c, tp);
+               ttstart(tp);
+               splx(s);
+               return (0);
+       }
+       splx(s);
+       return (-1);
+}
+
+/*
+ * Sleep on chan, returning ERESTART if tty changed
+ * while we napped and returning any errors (e.g. EINTR/ETIMEDOUT)
+ * reported by tsleep.  If the tty is revoked, restarting a pending
+ * call will redo validation done at the start of the call.
+ */
+ttysleep(tp, chan, pri, wmesg, timo)
+       struct tty *tp;
+       caddr_t chan;
+       int pri;
+       char *wmesg;
+       int timo;
+{
+       int error;
+       short gen = tp->t_gen;
+
+       if (error = tsleep(chan, pri, wmesg, timo))
+               return (error);
+       if (tp->t_gen != gen)
+               return (ERESTART);
+       return (0);
 }
 }