Initial import from FreeBSD RELENG_4:
[dragonfly.git] / sys / kern / tty.c
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  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      @(#)tty.c       8.8 (Berkeley) 1/21/94
39  * $FreeBSD: src/sys/kern/tty.c,v 1.129.2.5 2002/03/11 01:32:31 dd Exp $
40  */
41
42 /*-
43  * TODO:
44  *      o Fix races for sending the start char in ttyflush().
45  *      o Handle inter-byte timeout for "MIN > 0, TIME > 0" in ttyselect().
46  *        With luck, there will be MIN chars before select() returns().
47  *      o Handle CLOCAL consistently for ptys.  Perhaps disallow setting it.
48  *      o Don't allow input in TS_ZOMBIE case.  It would be visible through
49  *        FIONREAD.
50  *      o Do the new sio locking stuff here and use it to avoid special
51  *        case for EXTPROC?
52  *      o Lock PENDIN too?
53  *      o Move EXTPROC and/or PENDIN to t_state?
54  *      o Wrap most of ttioctl in spltty/splx.
55  *      o Implement TIOCNOTTY or remove it from <sys/ioctl.h>.
56  *      o Send STOP if IXOFF is toggled off while TS_TBLOCK is set.
57  *      o Don't allow certain termios flags to affect disciplines other
58  *        than TTYDISC.  Cancel their effects before switch disciplines
59  *        and ignore them if they are set while we are in another
60  *        discipline.
61  *      o Now that historical speed conversions are handled here, don't
62  *        do them in drivers.
63  *      o Check for TS_CARR_ON being set while everything is closed and not
64  *        waiting for carrier.  TS_CARR_ON isn't cleared if nothing is open,
65  *        so it would live until the next open even if carrier drops.
66  *      o Restore TS_WOPEN since it is useful in pstat.  It must be cleared
67  *        only when _all_ openers leave open().
68  */
69
70 #include "opt_compat.h"
71 #include "opt_uconsole.h"
72
73 #include <sys/param.h>
74 #include <sys/systm.h>
75 #include <sys/filio.h>
76 #if defined(COMPAT_43) || defined(COMPAT_SUNOS)
77 #include <sys/ioctl_compat.h>
78 #endif
79 #include <sys/proc.h>
80 #define TTYDEFCHARS
81 #include <sys/tty.h>
82 #undef  TTYDEFCHARS
83 #include <sys/fcntl.h>
84 #include <sys/conf.h>
85 #include <sys/dkstat.h>
86 #include <sys/poll.h>
87 #include <sys/kernel.h>
88 #include <sys/vnode.h>
89 #include <sys/signalvar.h>
90 #include <sys/resourcevar.h>
91 #include <sys/malloc.h>
92 #include <sys/filedesc.h>
93 #include <sys/sysctl.h>
94
95 #include <vm/vm.h>
96 #include <sys/lock.h>
97 #include <vm/pmap.h>
98 #include <vm/vm_map.h>
99
100 MALLOC_DEFINE(M_TTYS, "ttys", "tty data structures");
101
102 static int      proc_compare __P((struct proc *p1, struct proc *p2));
103 static int      ttnread __P((struct tty *tp));
104 static void     ttyecho __P((int c, struct tty *tp));
105 static int      ttyoutput __P((int c, register struct tty *tp));
106 static void     ttypend __P((struct tty *tp));
107 static void     ttyretype __P((struct tty *tp));
108 static void     ttyrub __P((int c, struct tty *tp));
109 static void     ttyrubo __P((struct tty *tp, int cnt));
110 static void     ttyunblock __P((struct tty *tp));
111 static int      ttywflush __P((struct tty *tp));
112 static int      filt_ttyread __P((struct knote *kn, long hint));
113 static void     filt_ttyrdetach __P((struct knote *kn));
114 static int      filt_ttywrite __P((struct knote *kn, long hint));
115 static void     filt_ttywdetach __P((struct knote *kn));
116
117 /*
118  * Table with character classes and parity. The 8th bit indicates parity,
119  * the 7th bit indicates the character is an alphameric or underscore (for
120  * ALTWERASE), and the low 6 bits indicate delay type.  If the low 6 bits
121  * are 0 then the character needs no special processing on output; classes
122  * other than 0 might be translated or (not currently) require delays.
123  */
124 #define E       0x00    /* Even parity. */
125 #define O       0x80    /* Odd parity. */
126 #define PARITY(c)       (char_type[c] & O)
127
128 #define ALPHA   0x40    /* Alpha or underscore. */
129 #define ISALPHA(c)      (char_type[(c) & TTY_CHARMASK] & ALPHA)
130
131 #define CCLASSMASK      0x3f
132 #define CCLASS(c)       (char_type[c] & CCLASSMASK)
133
134 #define BS      BACKSPACE
135 #define CC      CONTROL
136 #define CR      RETURN
137 #define NA      ORDINARY | ALPHA
138 #define NL      NEWLINE
139 #define NO      ORDINARY
140 #define TB      TAB
141 #define VT      VTAB
142
143 static u_char const char_type[] = {
144         E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC, /* nul - bel */
145         O|BS, E|TB, E|NL, O|CC, E|VT, O|CR, O|CC, E|CC, /* bs - si */
146         O|CC, E|CC, E|CC, O|CC, E|CC, O|CC, O|CC, E|CC, /* dle - etb */
147         E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC, /* can - us */
148         O|NO, E|NO, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* sp - ' */
149         E|NO, O|NO, O|NO, E|NO, O|NO, E|NO, E|NO, O|NO, /* ( - / */
150         E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* 0 - 7 */
151         O|NA, E|NA, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* 8 - ? */
152         O|NO, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* @ - G */
153         E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* H - O */
154         E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* P - W */
155         O|NA, E|NA, E|NA, O|NO, E|NO, O|NO, O|NO, O|NA, /* X - _ */
156         E|NO, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* ` - g */
157         O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* h - o */
158         O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* p - w */
159         E|NA, O|NA, O|NA, E|NO, O|NO, E|NO, E|NO, O|CC, /* x - del */
160         /*
161          * Meta chars; should be settable per character set;
162          * for now, treat them all as normal characters.
163          */
164         NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
165         NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
166         NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
167         NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
168         NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
169         NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
170         NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
171         NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
172         NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
173         NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
174         NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
175         NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
176         NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
177         NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
178         NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
179         NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
180 };
181 #undef  BS
182 #undef  CC
183 #undef  CR
184 #undef  NA
185 #undef  NL
186 #undef  NO
187 #undef  TB
188 #undef  VT
189
190 /* Macros to clear/set/test flags. */
191 #define SET(t, f)       (t) |= (f)
192 #define CLR(t, f)       (t) &= ~(f)
193 #define ISSET(t, f)     ((t) & (f))
194
195 #undef MAX_INPUT                /* XXX wrong in <sys/syslimits.h> */
196 #define MAX_INPUT       TTYHOG  /* XXX limit is usually larger for !ICANON */
197
198 /*
199  * list of struct tty where pstat(8) can pick it up with sysctl
200  */
201 static SLIST_HEAD(, tty) tty_list;
202
203 /*
204  * Initial open of tty, or (re)entry to standard tty line discipline.
205  */
206 int
207 ttyopen(device, tp)
208         dev_t device;
209         register struct tty *tp;
210 {
211         int s;
212
213         s = spltty();
214         tp->t_dev = device;
215         if (!ISSET(tp->t_state, TS_ISOPEN)) {
216                 SET(tp->t_state, TS_ISOPEN);
217                 if (ISSET(tp->t_cflag, CLOCAL))
218                         SET(tp->t_state, TS_CONNECTED);
219                 bzero(&tp->t_winsize, sizeof(tp->t_winsize));
220         }
221         ttsetwater(tp);
222         splx(s);
223         return (0);
224 }
225
226 /*
227  * Handle close() on a tty line: flush and set to initial state,
228  * bumping generation number so that pending read/write calls
229  * can detect recycling of the tty.
230  * XXX our caller should have done `spltty(); l_close(); ttyclose();'
231  * and l_close() should have flushed, but we repeat the spltty() and
232  * the flush in case there are buggy callers.
233  */
234 int
235 ttyclose(tp)
236         register struct tty *tp;
237 {
238         int s;
239
240         funsetown(tp->t_sigio);
241         s = spltty();
242         if (constty == tp)
243                 constty = NULL;
244
245         ttyflush(tp, FREAD | FWRITE);
246         clist_free_cblocks(&tp->t_canq);
247         clist_free_cblocks(&tp->t_outq);
248         clist_free_cblocks(&tp->t_rawq);
249
250         tp->t_gen++;
251         tp->t_line = TTYDISC;
252         tp->t_pgrp = NULL;
253         tp->t_session = NULL;
254         tp->t_state = 0;
255         splx(s);
256         return (0);
257 }
258
259 #define FLUSHQ(q) {                                                     \
260         if ((q)->c_cc)                                                  \
261                 ndflush(q, (q)->c_cc);                                  \
262 }
263
264 /* Is 'c' a line delimiter ("break" character)? */
265 #define TTBREAKC(c, lflag)                                                      \
266         ((c) == '\n' || (((c) == cc[VEOF] ||                            \
267           (c) == cc[VEOL] || ((c) == cc[VEOL2] && lflag & IEXTEN)) &&   \
268          (c) != _POSIX_VDISABLE))
269
270 /*
271  * Process input of a single character received on a tty.
272  */
273 int
274 ttyinput(c, tp)
275         register int c;
276         register struct tty *tp;
277 {
278         register tcflag_t iflag, lflag;
279         register cc_t *cc;
280         int i, err;
281
282         /*
283          * If input is pending take it first.
284          */
285         lflag = tp->t_lflag;
286         if (ISSET(lflag, PENDIN))
287                 ttypend(tp);
288         /*
289          * Gather stats.
290          */
291         if (ISSET(lflag, ICANON)) {
292                 ++tk_cancc;
293                 ++tp->t_cancc;
294         } else {
295                 ++tk_rawcc;
296                 ++tp->t_rawcc;
297         }
298         ++tk_nin;
299
300         /*
301          * Block further input iff:
302          * current input > threshold AND input is available to user program
303          * AND input flow control is enabled and not yet invoked.
304          * The 3 is slop for PARMRK.
305          */
306         iflag = tp->t_iflag;
307         if (tp->t_rawq.c_cc + tp->t_canq.c_cc > tp->t_ihiwat - 3 &&
308             (!ISSET(lflag, ICANON) || tp->t_canq.c_cc != 0) &&
309             (ISSET(tp->t_cflag, CRTS_IFLOW) || ISSET(iflag, IXOFF)) &&
310             !ISSET(tp->t_state, TS_TBLOCK))
311                 ttyblock(tp);
312
313         /* Handle exceptional conditions (break, parity, framing). */
314         cc = tp->t_cc;
315         err = (ISSET(c, TTY_ERRORMASK));
316         if (err) {
317                 CLR(c, TTY_ERRORMASK);
318                 if (ISSET(err, TTY_BI)) {
319                         if (ISSET(iflag, IGNBRK))
320                                 return (0);
321                         if (ISSET(iflag, BRKINT)) {
322                                 ttyflush(tp, FREAD | FWRITE);
323                                 pgsignal(tp->t_pgrp, SIGINT, 1);
324                                 goto endcase;
325                         }
326                         if (ISSET(iflag, PARMRK))
327                                 goto parmrk;
328                 } else if ((ISSET(err, TTY_PE) && ISSET(iflag, INPCK))
329                         || ISSET(err, TTY_FE)) {
330                         if (ISSET(iflag, IGNPAR))
331                                 return (0);
332                         else if (ISSET(iflag, PARMRK)) {
333 parmrk:
334                                 if (tp->t_rawq.c_cc + tp->t_canq.c_cc >
335                                     MAX_INPUT - 3)
336                                         goto input_overflow;
337                                 (void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
338                                 (void)putc(0 | TTY_QUOTE, &tp->t_rawq);
339                                 (void)putc(c | TTY_QUOTE, &tp->t_rawq);
340                                 goto endcase;
341                         } else
342                                 c = 0;
343                 }
344         }
345
346         if (!ISSET(tp->t_state, TS_TYPEN) && ISSET(iflag, ISTRIP))
347                 CLR(c, 0x80);
348         if (!ISSET(lflag, EXTPROC)) {
349                 /*
350                  * Check for literal nexting very first
351                  */
352                 if (ISSET(tp->t_state, TS_LNCH)) {
353                         SET(c, TTY_QUOTE);
354                         CLR(tp->t_state, TS_LNCH);
355                 }
356                 /*
357                  * Scan for special characters.  This code
358                  * is really just a big case statement with
359                  * non-constant cases.  The bottom of the
360                  * case statement is labeled ``endcase'', so goto
361                  * it after a case match, or similar.
362                  */
363
364                 /*
365                  * Control chars which aren't controlled
366                  * by ICANON, ISIG, or IXON.
367                  */
368                 if (ISSET(lflag, IEXTEN)) {
369                         if (CCEQ(cc[VLNEXT], c)) {
370                                 if (ISSET(lflag, ECHO)) {
371                                         if (ISSET(lflag, ECHOE)) {
372                                                 (void)ttyoutput('^', tp);
373                                                 (void)ttyoutput('\b', tp);
374                                         } else
375                                                 ttyecho(c, tp);
376                                 }
377                                 SET(tp->t_state, TS_LNCH);
378                                 goto endcase;
379                         }
380                         if (CCEQ(cc[VDISCARD], c)) {
381                                 if (ISSET(lflag, FLUSHO))
382                                         CLR(tp->t_lflag, FLUSHO);
383                                 else {
384                                         ttyflush(tp, FWRITE);
385                                         ttyecho(c, tp);
386                                         if (tp->t_rawq.c_cc + tp->t_canq.c_cc)
387                                                 ttyretype(tp);
388                                         SET(tp->t_lflag, FLUSHO);
389                                 }
390                                 goto startoutput;
391                         }
392                 }
393                 /*
394                  * Signals.
395                  */
396                 if (ISSET(lflag, ISIG)) {
397                         if (CCEQ(cc[VINTR], c) || CCEQ(cc[VQUIT], c)) {
398                                 if (!ISSET(lflag, NOFLSH))
399                                         ttyflush(tp, FREAD | FWRITE);
400                                 ttyecho(c, tp);
401                                 pgsignal(tp->t_pgrp,
402                                     CCEQ(cc[VINTR], c) ? SIGINT : SIGQUIT, 1);
403                                 goto endcase;
404                         }
405                         if (CCEQ(cc[VSUSP], c)) {
406                                 if (!ISSET(lflag, NOFLSH))
407                                         ttyflush(tp, FREAD);
408                                 ttyecho(c, tp);
409                                 pgsignal(tp->t_pgrp, SIGTSTP, 1);
410                                 goto endcase;
411                         }
412                 }
413                 /*
414                  * Handle start/stop characters.
415                  */
416                 if (ISSET(iflag, IXON)) {
417                         if (CCEQ(cc[VSTOP], c)) {
418                                 if (!ISSET(tp->t_state, TS_TTSTOP)) {
419                                         SET(tp->t_state, TS_TTSTOP);
420                                         (*tp->t_stop)(tp, 0);
421                                         return (0);
422                                 }
423                                 if (!CCEQ(cc[VSTART], c))
424                                         return (0);
425                                 /*
426                                  * if VSTART == VSTOP then toggle
427                                  */
428                                 goto endcase;
429                         }
430                         if (CCEQ(cc[VSTART], c))
431                                 goto restartoutput;
432                 }
433                 /*
434                  * IGNCR, ICRNL, & INLCR
435                  */
436                 if (c == '\r') {
437                         if (ISSET(iflag, IGNCR))
438                                 return (0);
439                         else if (ISSET(iflag, ICRNL))
440                                 c = '\n';
441                 } else if (c == '\n' && ISSET(iflag, INLCR))
442                         c = '\r';
443         }
444         if (!ISSET(tp->t_lflag, EXTPROC) && ISSET(lflag, ICANON)) {
445                 /*
446                  * From here on down canonical mode character
447                  * processing takes place.
448                  */
449                 /*
450                  * erase or erase2 (^H / ^?)
451                  */
452                 if (CCEQ(cc[VERASE], c) || CCEQ(cc[VERASE2], c) ) {
453                         if (tp->t_rawq.c_cc)
454                                 ttyrub(unputc(&tp->t_rawq), tp);
455                         goto endcase;
456                 }
457                 /*
458                  * kill (^U)
459                  */
460                 if (CCEQ(cc[VKILL], c)) {
461                         if (ISSET(lflag, ECHOKE) &&
462                             tp->t_rawq.c_cc == tp->t_rocount &&
463                             !ISSET(lflag, ECHOPRT))
464                                 while (tp->t_rawq.c_cc)
465                                         ttyrub(unputc(&tp->t_rawq), tp);
466                         else {
467                                 ttyecho(c, tp);
468                                 if (ISSET(lflag, ECHOK) ||
469                                     ISSET(lflag, ECHOKE))
470                                         ttyecho('\n', tp);
471                                 FLUSHQ(&tp->t_rawq);
472                                 tp->t_rocount = 0;
473                         }
474                         CLR(tp->t_state, TS_LOCAL);
475                         goto endcase;
476                 }
477                 /*
478                  * word erase (^W)
479                  */
480                 if (CCEQ(cc[VWERASE], c) && ISSET(lflag, IEXTEN)) {
481                         int ctype;
482
483                         /*
484                          * erase whitespace
485                          */
486                         while ((c = unputc(&tp->t_rawq)) == ' ' || c == '\t')
487                                 ttyrub(c, tp);
488                         if (c == -1)
489                                 goto endcase;
490                         /*
491                          * erase last char of word and remember the
492                          * next chars type (for ALTWERASE)
493                          */
494                         ttyrub(c, tp);
495                         c = unputc(&tp->t_rawq);
496                         if (c == -1)
497                                 goto endcase;
498                         if (c == ' ' || c == '\t') {
499                                 (void)putc(c, &tp->t_rawq);
500                                 goto endcase;
501                         }
502                         ctype = ISALPHA(c);
503                         /*
504                          * erase rest of word
505                          */
506                         do {
507                                 ttyrub(c, tp);
508                                 c = unputc(&tp->t_rawq);
509                                 if (c == -1)
510                                         goto endcase;
511                         } while (c != ' ' && c != '\t' &&
512                             (!ISSET(lflag, ALTWERASE) || ISALPHA(c) == ctype));
513                         (void)putc(c, &tp->t_rawq);
514                         goto endcase;
515                 }
516                 /*
517                  * reprint line (^R)
518                  */
519                 if (CCEQ(cc[VREPRINT], c) && ISSET(lflag, IEXTEN)) {
520                         ttyretype(tp);
521                         goto endcase;
522                 }
523                 /*
524                  * ^T - kernel info and generate SIGINFO
525                  */
526                 if (CCEQ(cc[VSTATUS], c) && ISSET(lflag, IEXTEN)) {
527                         if (ISSET(lflag, ISIG))
528                                 pgsignal(tp->t_pgrp, SIGINFO, 1);
529                         if (!ISSET(lflag, NOKERNINFO))
530                                 ttyinfo(tp);
531                         goto endcase;
532                 }
533         }
534         /*
535          * Check for input buffer overflow
536          */
537         if (tp->t_rawq.c_cc + tp->t_canq.c_cc >= MAX_INPUT) {
538 input_overflow:
539                 if (ISSET(iflag, IMAXBEL)) {
540                         if (tp->t_outq.c_cc < tp->t_ohiwat)
541                                 (void)ttyoutput(CTRL('g'), tp);
542                 }
543                 goto endcase;
544         }
545
546         if (   c == 0377 && ISSET(iflag, PARMRK) && !ISSET(iflag, ISTRIP)
547              && ISSET(iflag, IGNBRK|IGNPAR) != (IGNBRK|IGNPAR))
548                 (void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
549
550         /*
551          * Put data char in q for user and
552          * wakeup on seeing a line delimiter.
553          */
554         if (putc(c, &tp->t_rawq) >= 0) {
555                 if (!ISSET(lflag, ICANON)) {
556                         ttwakeup(tp);
557                         ttyecho(c, tp);
558                         goto endcase;
559                 }
560                 if (TTBREAKC(c, lflag)) {
561                         tp->t_rocount = 0;
562                         catq(&tp->t_rawq, &tp->t_canq);
563                         ttwakeup(tp);
564                 } else if (tp->t_rocount++ == 0)
565                         tp->t_rocol = tp->t_column;
566                 if (ISSET(tp->t_state, TS_ERASE)) {
567                         /*
568                          * end of prterase \.../
569                          */
570                         CLR(tp->t_state, TS_ERASE);
571                         (void)ttyoutput('/', tp);
572                 }
573                 i = tp->t_column;
574                 ttyecho(c, tp);
575                 if (CCEQ(cc[VEOF], c) && ISSET(lflag, ECHO)) {
576                         /*
577                          * Place the cursor over the '^' of the ^D.
578                          */
579                         i = imin(2, tp->t_column - i);
580                         while (i > 0) {
581                                 (void)ttyoutput('\b', tp);
582                                 i--;
583                         }
584                 }
585         }
586 endcase:
587         /*
588          * IXANY means allow any character to restart output.
589          */
590         if (ISSET(tp->t_state, TS_TTSTOP) &&
591             !ISSET(iflag, IXANY) && cc[VSTART] != cc[VSTOP])
592                 return (0);
593 restartoutput:
594         CLR(tp->t_lflag, FLUSHO);
595         CLR(tp->t_state, TS_TTSTOP);
596 startoutput:
597         return (ttstart(tp));
598 }
599
600 /*
601  * Output a single character on a tty, doing output processing
602  * as needed (expanding tabs, newline processing, etc.).
603  * Returns < 0 if succeeds, otherwise returns char to resend.
604  * Must be recursive.
605  */
606 static int
607 ttyoutput(c, tp)
608         register int c;
609         register struct tty *tp;
610 {
611         register tcflag_t oflag;
612         register int col, s;
613
614         oflag = tp->t_oflag;
615         if (!ISSET(oflag, OPOST)) {
616                 if (ISSET(tp->t_lflag, FLUSHO))
617                         return (-1);
618                 if (putc(c, &tp->t_outq))
619                         return (c);
620                 tk_nout++;
621                 tp->t_outcc++;
622                 return (-1);
623         }
624         /*
625          * Do tab expansion if OXTABS is set.  Special case if we external
626          * processing, we don't do the tab expansion because we'll probably
627          * get it wrong.  If tab expansion needs to be done, let it happen
628          * externally.
629          */
630         CLR(c, ~TTY_CHARMASK);
631         if (c == '\t' &&
632             ISSET(oflag, OXTABS) && !ISSET(tp->t_lflag, EXTPROC)) {
633                 c = 8 - (tp->t_column & 7);
634                 if (!ISSET(tp->t_lflag, FLUSHO)) {
635                         s = spltty();           /* Don't interrupt tabs. */
636                         c -= b_to_q("        ", c, &tp->t_outq);
637                         tk_nout += c;
638                         tp->t_outcc += c;
639                         splx(s);
640                 }
641                 tp->t_column += c;
642                 return (c ? -1 : '\t');
643         }
644         if (c == CEOT && ISSET(oflag, ONOEOT))
645                 return (-1);
646
647         /*
648          * Newline translation: if ONLCR is set,
649          * translate newline into "\r\n".
650          */
651         if (c == '\n' && ISSET(tp->t_oflag, ONLCR)) {
652                 tk_nout++;
653                 tp->t_outcc++;
654                 if (!ISSET(tp->t_lflag, FLUSHO) && putc('\r', &tp->t_outq))
655                         return (c);
656         }
657         /* If OCRNL is set, translate "\r" into "\n". */
658         else if (c == '\r' && ISSET(tp->t_oflag, OCRNL))
659                 c = '\n';
660         /* If ONOCR is set, don't transmit CRs when on column 0. */
661         else if (c == '\r' && ISSET(tp->t_oflag, ONOCR) && tp->t_column == 0)
662                 return (-1);
663
664         tk_nout++;
665         tp->t_outcc++;
666         if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
667                 return (c);
668
669         col = tp->t_column;
670         switch (CCLASS(c)) {
671         case BACKSPACE:
672                 if (col > 0)
673                         --col;
674                 break;
675         case CONTROL:
676                 break;
677         case NEWLINE:
678                 if (ISSET(tp->t_oflag, ONLCR | ONLRET))
679                         col = 0;
680                 break;
681         case RETURN:
682                 col = 0;
683                 break;
684         case ORDINARY:
685                 ++col;
686                 break;
687         case TAB:
688                 col = (col + 8) & ~7;
689                 break;
690         }
691         tp->t_column = col;
692         return (-1);
693 }
694
695 /*
696  * Ioctls for all tty devices.  Called after line-discipline specific ioctl
697  * has been called to do discipline-specific functions and/or reject any
698  * of these ioctl commands.
699  */
700 /* ARGSUSED */
701 int
702 ttioctl(tp, cmd, data, flag)
703         register struct tty *tp;
704         u_long cmd;
705         int flag;
706         void *data;
707 {
708         register struct proc *p;
709         int s, error;
710
711         p = curproc;                    /* XXX */
712
713         /* If the ioctl involves modification, hang if in the background. */
714         switch (cmd) {
715         case  TIOCCBRK:
716         case  TIOCCONS:
717         case  TIOCDRAIN:
718         case  TIOCEXCL:
719         case  TIOCFLUSH:
720 #ifdef TIOCHPCL
721         case  TIOCHPCL:
722 #endif
723         case  TIOCNXCL:
724         case  TIOCSBRK:
725         case  TIOCSCTTY:
726         case  TIOCSDRAINWAIT:
727         case  TIOCSETA:
728         case  TIOCSETAF:
729         case  TIOCSETAW:
730         case  TIOCSETD:
731         case  TIOCSPGRP:
732         case  TIOCSTART:
733         case  TIOCSTAT:
734         case  TIOCSTI:
735         case  TIOCSTOP:
736         case  TIOCSWINSZ:
737 #if defined(COMPAT_43) || defined(COMPAT_SUNOS)
738         case  TIOCLBIC:
739         case  TIOCLBIS:
740         case  TIOCLSET:
741         case  TIOCSETC:
742         case OTIOCSETD:
743         case  TIOCSETN:
744         case  TIOCSETP:
745         case  TIOCSLTC:
746 #endif
747                 while (isbackground(p, tp) && !(p->p_flag & P_PPWAIT) &&
748                     !SIGISMEMBER(p->p_sigignore, SIGTTOU) &&
749                     !SIGISMEMBER(p->p_sigmask, SIGTTOU)) {
750                         if (p->p_pgrp->pg_jobc == 0)
751                                 return (EIO);
752                         pgsignal(p->p_pgrp, SIGTTOU, 1);
753                         error = ttysleep(tp, &lbolt, TTOPRI | PCATCH, "ttybg1",
754                                          0);
755                         if (error)
756                                 return (error);
757                 }
758                 break;
759         }
760
761         switch (cmd) {                  /* Process the ioctl. */
762         case FIOASYNC:                  /* set/clear async i/o */
763                 s = spltty();
764                 if (*(int *)data)
765                         SET(tp->t_state, TS_ASYNC);
766                 else
767                         CLR(tp->t_state, TS_ASYNC);
768                 splx(s);
769                 break;
770         case FIONBIO:                   /* set/clear non-blocking i/o */
771                 break;                  /* XXX: delete. */
772         case FIONREAD:                  /* get # bytes to read */
773                 s = spltty();
774                 *(int *)data = ttnread(tp);
775                 splx(s);
776                 break;
777
778         case FIOSETOWN:
779                 /*
780                  * Policy -- Don't allow FIOSETOWN on someone else's 
781                  *           controlling tty
782                  */
783                 if (tp->t_session != NULL && !isctty(p, tp))
784                         return (ENOTTY);
785
786                 error = fsetown(*(int *)data, &tp->t_sigio);
787                 if (error)
788                         return (error);
789                 break;
790         case FIOGETOWN:
791                 if (tp->t_session != NULL && !isctty(p, tp))
792                         return (ENOTTY);
793                 *(int *)data = fgetown(tp->t_sigio);
794                 break;
795
796         case TIOCEXCL:                  /* set exclusive use of tty */
797                 s = spltty();
798                 SET(tp->t_state, TS_XCLUDE);
799                 splx(s);
800                 break;
801         case TIOCFLUSH: {               /* flush buffers */
802                 register int flags = *(int *)data;
803
804                 if (flags == 0)
805                         flags = FREAD | FWRITE;
806                 else
807                         flags &= FREAD | FWRITE;
808                 ttyflush(tp, flags);
809                 break;
810         }
811         case TIOCCONS:                  /* become virtual console */
812                 if (*(int *)data) {
813                         if (constty && constty != tp &&
814                             ISSET(constty->t_state, TS_CONNECTED))
815                                 return (EBUSY);
816 #ifndef UCONSOLE
817                         if ((error = suser(p)) != 0)
818                                 return (error);
819 #endif
820                         constty = tp;
821                 } else if (tp == constty)
822                         constty = NULL;
823                 break;
824         case TIOCDRAIN:                 /* wait till output drained */
825                 error = ttywait(tp);
826                 if (error)
827                         return (error);
828                 break;
829         case TIOCGETA: {                /* get termios struct */
830                 struct termios *t = (struct termios *)data;
831
832                 bcopy(&tp->t_termios, t, sizeof(struct termios));
833                 break;
834         }
835         case TIOCGETD:                  /* get line discipline */
836                 *(int *)data = tp->t_line;
837                 break;
838         case TIOCGWINSZ:                /* get window size */
839                 *(struct winsize *)data = tp->t_winsize;
840                 break;
841         case TIOCGPGRP:                 /* get pgrp of tty */
842                 if (!isctty(p, tp))
843                         return (ENOTTY);
844                 *(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
845                 break;
846 #ifdef TIOCHPCL
847         case TIOCHPCL:                  /* hang up on last close */
848                 s = spltty();
849                 SET(tp->t_cflag, HUPCL);
850                 splx(s);
851                 break;
852 #endif
853         case TIOCNXCL:                  /* reset exclusive use of tty */
854                 s = spltty();
855                 CLR(tp->t_state, TS_XCLUDE);
856                 splx(s);
857                 break;
858         case TIOCOUTQ:                  /* output queue size */
859                 *(int *)data = tp->t_outq.c_cc;
860                 break;
861         case TIOCSETA:                  /* set termios struct */
862         case TIOCSETAW:                 /* drain output, set */
863         case TIOCSETAF: {               /* drn out, fls in, set */
864                 register struct termios *t = (struct termios *)data;
865
866                 if (t->c_ispeed == 0)
867                         t->c_ispeed = t->c_ospeed;
868                 if (t->c_ispeed == 0)
869                         t->c_ispeed = tp->t_ospeed;
870                 if (t->c_ispeed == 0)
871                         return (EINVAL);
872                 s = spltty();
873                 if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
874                         error = ttywait(tp);
875                         if (error) {
876                                 splx(s);
877                                 return (error);
878                         }
879                         if (cmd == TIOCSETAF)
880                                 ttyflush(tp, FREAD);
881                 }
882                 if (!ISSET(t->c_cflag, CIGNORE)) {
883                         /*
884                          * Set device hardware.
885                          */
886                         if (tp->t_param && (error = (*tp->t_param)(tp, t))) {
887                                 splx(s);
888                                 return (error);
889                         }
890                         if (ISSET(t->c_cflag, CLOCAL) &&
891                             !ISSET(tp->t_cflag, CLOCAL)) {
892                                 /*
893                                  * XXX disconnections would be too hard to
894                                  * get rid of without this kludge.  The only
895                                  * way to get rid of controlling terminals
896                                  * is to exit from the session leader.
897                                  */
898                                 CLR(tp->t_state, TS_ZOMBIE);
899
900                                 wakeup(TSA_CARR_ON(tp));
901                                 ttwakeup(tp);
902                                 ttwwakeup(tp);
903                         }
904                         if ((ISSET(tp->t_state, TS_CARR_ON) ||
905                              ISSET(t->c_cflag, CLOCAL)) &&
906                             !ISSET(tp->t_state, TS_ZOMBIE))
907                                 SET(tp->t_state, TS_CONNECTED);
908                         else
909                                 CLR(tp->t_state, TS_CONNECTED);
910                         tp->t_cflag = t->c_cflag;
911                         tp->t_ispeed = t->c_ispeed;
912                         if (t->c_ospeed != 0)
913                                 tp->t_ospeed = t->c_ospeed;
914                         ttsetwater(tp);
915                 }
916                 if (ISSET(t->c_lflag, ICANON) != ISSET(tp->t_lflag, ICANON) &&
917                     cmd != TIOCSETAF) {
918                         if (ISSET(t->c_lflag, ICANON))
919                                 SET(tp->t_lflag, PENDIN);
920                         else {
921                                 /*
922                                  * XXX we really shouldn't allow toggling
923                                  * ICANON while we're in a non-termios line
924                                  * discipline.  Now we have to worry about
925                                  * panicing for a null queue.
926                                  */
927                                 if (tp->t_canq.c_cbreserved > 0 &&
928                                     tp->t_rawq.c_cbreserved > 0) {
929                                         catq(&tp->t_rawq, &tp->t_canq);
930                                         /*
931                                          * XXX the queue limits may be
932                                          * different, so the old queue
933                                          * swapping method no longer works.
934                                          */
935                                         catq(&tp->t_canq, &tp->t_rawq);
936                                 }
937                                 CLR(tp->t_lflag, PENDIN);
938                         }
939                         ttwakeup(tp);
940                 }
941                 tp->t_iflag = t->c_iflag;
942                 tp->t_oflag = t->c_oflag;
943                 /*
944                  * Make the EXTPROC bit read only.
945                  */
946                 if (ISSET(tp->t_lflag, EXTPROC))
947                         SET(t->c_lflag, EXTPROC);
948                 else
949                         CLR(t->c_lflag, EXTPROC);
950                 tp->t_lflag = t->c_lflag | ISSET(tp->t_lflag, PENDIN);
951                 if (t->c_cc[VMIN] != tp->t_cc[VMIN] ||
952                     t->c_cc[VTIME] != tp->t_cc[VTIME])
953                         ttwakeup(tp);
954                 bcopy(t->c_cc, tp->t_cc, sizeof(t->c_cc));
955                 splx(s);
956                 break;
957         }
958         case TIOCSETD: {                /* set line discipline */
959                 register int t = *(int *)data;
960                 dev_t device = tp->t_dev;
961
962                 if ((u_int)t >= nlinesw)
963                         return (ENXIO);
964                 if (t != tp->t_line) {
965                         s = spltty();
966                         (*linesw[tp->t_line].l_close)(tp, flag);
967                         error = (*linesw[t].l_open)(device, tp);
968                         if (error) {
969                                 (void)(*linesw[tp->t_line].l_open)(device, tp);
970                                 splx(s);
971                                 return (error);
972                         }
973                         tp->t_line = t;
974                         splx(s);
975                 }
976                 break;
977         }
978         case TIOCSTART:                 /* start output, like ^Q */
979                 s = spltty();
980                 if (ISSET(tp->t_state, TS_TTSTOP) ||
981                     ISSET(tp->t_lflag, FLUSHO)) {
982                         CLR(tp->t_lflag, FLUSHO);
983                         CLR(tp->t_state, TS_TTSTOP);
984                         ttstart(tp);
985                 }
986                 splx(s);
987                 break;
988         case TIOCSTI:                   /* simulate terminal input */
989                 if ((flag & FREAD) == 0 && suser(p))
990                         return (EPERM);
991                 if (!isctty(p, tp) && suser(p))
992                         return (EACCES);
993                 s = spltty();
994                 (*linesw[tp->t_line].l_rint)(*(u_char *)data, tp);
995                 splx(s);
996                 break;
997         case TIOCSTOP:                  /* stop output, like ^S */
998                 s = spltty();
999                 if (!ISSET(tp->t_state, TS_TTSTOP)) {
1000                         SET(tp->t_state, TS_TTSTOP);
1001                         (*tp->t_stop)(tp, 0);
1002                 }
1003                 splx(s);
1004                 break;
1005         case TIOCSCTTY:                 /* become controlling tty */
1006                 /* Session ctty vnode pointer set in vnode layer. */
1007                 if (!SESS_LEADER(p) ||
1008                     ((p->p_session->s_ttyvp || tp->t_session) &&
1009                     (tp->t_session != p->p_session)))
1010                         return (EPERM);
1011                 tp->t_session = p->p_session;
1012                 tp->t_pgrp = p->p_pgrp;
1013                 p->p_session->s_ttyp = tp;
1014                 p->p_flag |= P_CONTROLT;
1015                 break;
1016         case TIOCSPGRP: {               /* set pgrp of tty */
1017                 register struct pgrp *pgrp = pgfind(*(int *)data);
1018
1019                 if (!isctty(p, tp))
1020                         return (ENOTTY);
1021                 else if (pgrp == NULL || pgrp->pg_session != p->p_session)
1022                         return (EPERM);
1023                 tp->t_pgrp = pgrp;
1024                 break;
1025         }
1026         case TIOCSTAT:                  /* simulate control-T */
1027                 s = spltty();
1028                 ttyinfo(tp);
1029                 splx(s);
1030                 break;
1031         case TIOCSWINSZ:                /* set window size */
1032                 if (bcmp((caddr_t)&tp->t_winsize, data,
1033                     sizeof (struct winsize))) {
1034                         tp->t_winsize = *(struct winsize *)data;
1035                         pgsignal(tp->t_pgrp, SIGWINCH, 1);
1036                 }
1037                 break;
1038         case TIOCSDRAINWAIT:
1039                 error = suser(p);
1040                 if (error)
1041                         return (error);
1042                 tp->t_timeout = *(int *)data * hz;
1043                 wakeup(TSA_OCOMPLETE(tp));
1044                 wakeup(TSA_OLOWAT(tp));
1045                 break;
1046         case TIOCGDRAINWAIT:
1047                 *(int *)data = tp->t_timeout / hz;
1048                 break;
1049         default:
1050 #if defined(COMPAT_43) || defined(COMPAT_SUNOS)
1051                 return (ttcompat(tp, cmd, data, flag));
1052 #else
1053                 return (ENOIOCTL);
1054 #endif
1055         }
1056         return (0);
1057 }
1058
1059 int
1060 ttypoll(dev, events, p)
1061         dev_t dev;
1062         int events;
1063         struct proc *p;
1064 {
1065         int s;
1066         int revents = 0;
1067         struct tty *tp;
1068
1069         tp = dev->si_tty;
1070         if (tp == NULL) /* XXX used to return ENXIO, but that means true! */
1071                 return ((events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM))
1072                         | POLLHUP);
1073
1074         s = spltty();
1075         if (events & (POLLIN | POLLRDNORM)) {
1076                 if (ttnread(tp) > 0 || ISSET(tp->t_state, TS_ZOMBIE))
1077                         revents |= events & (POLLIN | POLLRDNORM);
1078                 else
1079                         selrecord(p, &tp->t_rsel);
1080         }
1081         if (events & (POLLOUT | POLLWRNORM)) {
1082                 if ((tp->t_outq.c_cc <= tp->t_olowat &&
1083                      ISSET(tp->t_state, TS_CONNECTED))
1084                     || ISSET(tp->t_state, TS_ZOMBIE))
1085                         revents |= events & (POLLOUT | POLLWRNORM);
1086                 else
1087                         selrecord(p, &tp->t_wsel);
1088         }
1089         splx(s);
1090         return (revents);
1091 }
1092
1093 static struct filterops ttyread_filtops =
1094         { 1, NULL, filt_ttyrdetach, filt_ttyread };
1095 static struct filterops ttywrite_filtops =
1096         { 1, NULL, filt_ttywdetach, filt_ttywrite };
1097
1098 int
1099 ttykqfilter(dev, kn)
1100         dev_t dev;
1101         struct knote *kn;
1102 {
1103         struct tty *tp = dev->si_tty;
1104         struct klist *klist;
1105         int s;
1106
1107         switch (kn->kn_filter) {
1108         case EVFILT_READ:
1109                 klist = &tp->t_rsel.si_note;
1110                 kn->kn_fop = &ttyread_filtops;
1111                 break;
1112         case EVFILT_WRITE:
1113                 klist = &tp->t_wsel.si_note;
1114                 kn->kn_fop = &ttywrite_filtops;
1115                 break;
1116         default:
1117                 return (1);
1118         }
1119
1120         kn->kn_hook = (caddr_t)dev;
1121
1122         s = spltty();
1123         SLIST_INSERT_HEAD(klist, kn, kn_selnext);
1124         splx(s);
1125
1126         return (0);
1127 }
1128
1129 static void
1130 filt_ttyrdetach(struct knote *kn)
1131 {
1132         struct tty *tp = ((dev_t)kn->kn_hook)->si_tty;
1133         int s = spltty();
1134
1135         SLIST_REMOVE(&tp->t_rsel.si_note, kn, knote, kn_selnext);
1136         splx(s);
1137 }
1138
1139 static int
1140 filt_ttyread(struct knote *kn, long hint)
1141 {
1142         struct tty *tp = ((dev_t)kn->kn_hook)->si_tty;
1143
1144         kn->kn_data = ttnread(tp);
1145         if (ISSET(tp->t_state, TS_ZOMBIE)) {
1146                 kn->kn_flags |= EV_EOF;
1147                 return (1);
1148         }
1149         return (kn->kn_data > 0);
1150 }
1151
1152 static void
1153 filt_ttywdetach(struct knote *kn)
1154 {
1155         struct tty *tp = ((dev_t)kn->kn_hook)->si_tty;
1156         int s = spltty();
1157
1158         SLIST_REMOVE(&tp->t_wsel.si_note, kn, knote, kn_selnext);
1159         splx(s);
1160 }
1161
1162 static int
1163 filt_ttywrite(kn, hint)
1164         struct knote *kn;
1165         long hint;
1166 {
1167         struct tty *tp = ((dev_t)kn->kn_hook)->si_tty;
1168
1169         kn->kn_data = tp->t_outq.c_cc;
1170         if (ISSET(tp->t_state, TS_ZOMBIE))
1171                 return (1);
1172         return (kn->kn_data <= tp->t_olowat &&
1173             ISSET(tp->t_state, TS_CONNECTED));
1174 }
1175
1176 /*
1177  * Must be called at spltty().
1178  */
1179 static int
1180 ttnread(tp)
1181         struct tty *tp;
1182 {
1183         int nread;
1184
1185         if (ISSET(tp->t_lflag, PENDIN))
1186                 ttypend(tp);
1187         nread = tp->t_canq.c_cc;
1188         if (!ISSET(tp->t_lflag, ICANON)) {
1189                 nread += tp->t_rawq.c_cc;
1190                 if (nread < tp->t_cc[VMIN] && tp->t_cc[VTIME] == 0)
1191                         nread = 0;
1192         }
1193         return (nread);
1194 }
1195
1196 /*
1197  * Wait for output to drain.
1198  */
1199 int
1200 ttywait(tp)
1201         register struct tty *tp;
1202 {
1203         int error, s;
1204
1205         error = 0;
1206         s = spltty();
1207         while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1208                ISSET(tp->t_state, TS_CONNECTED) && tp->t_oproc) {
1209                 (*tp->t_oproc)(tp);
1210                 if ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1211                     ISSET(tp->t_state, TS_CONNECTED)) {
1212                         SET(tp->t_state, TS_SO_OCOMPLETE);
1213                         error = ttysleep(tp, TSA_OCOMPLETE(tp),
1214                                          TTOPRI | PCATCH, "ttywai",
1215                                          tp->t_timeout);
1216                         if (error) {
1217                                 if (error == EWOULDBLOCK)
1218                                         error = EIO;
1219                                 break;
1220                         }
1221                 } else
1222                         break;
1223         }
1224         if (!error && (tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)))
1225                 error = EIO;
1226         splx(s);
1227         return (error);
1228 }
1229
1230 /*
1231  * Flush if successfully wait.
1232  */
1233 static int
1234 ttywflush(tp)
1235         struct tty *tp;
1236 {
1237         int error;
1238
1239         if ((error = ttywait(tp)) == 0)
1240                 ttyflush(tp, FREAD);
1241         return (error);
1242 }
1243
1244 /*
1245  * Flush tty read and/or write queues, notifying anyone waiting.
1246  */
1247 void
1248 ttyflush(tp, rw)
1249         register struct tty *tp;
1250         int rw;
1251 {
1252         register int s;
1253
1254         s = spltty();
1255 #if 0
1256 again:
1257 #endif
1258         if (rw & FWRITE) {
1259                 FLUSHQ(&tp->t_outq);
1260                 CLR(tp->t_state, TS_TTSTOP);
1261         }
1262         (*tp->t_stop)(tp, rw);
1263         if (rw & FREAD) {
1264                 FLUSHQ(&tp->t_canq);
1265                 FLUSHQ(&tp->t_rawq);
1266                 CLR(tp->t_lflag, PENDIN);
1267                 tp->t_rocount = 0;
1268                 tp->t_rocol = 0;
1269                 CLR(tp->t_state, TS_LOCAL);
1270                 ttwakeup(tp);
1271                 if (ISSET(tp->t_state, TS_TBLOCK)) {
1272                         if (rw & FWRITE)
1273                                 FLUSHQ(&tp->t_outq);
1274                         ttyunblock(tp);
1275
1276                         /*
1277                          * Don't let leave any state that might clobber the
1278                          * next line discipline (although we should do more
1279                          * to send the START char).  Not clearing the state
1280                          * may have caused the "putc to a clist with no
1281                          * reserved cblocks" panic/printf.
1282                          */
1283                         CLR(tp->t_state, TS_TBLOCK);
1284
1285 #if 0 /* forget it, sleeping isn't always safe and we don't know when it is */
1286                         if (ISSET(tp->t_iflag, IXOFF)) {
1287                                 /*
1288                                  * XXX wait a bit in the hope that the stop
1289                                  * character (if any) will go out.  Waiting
1290                                  * isn't good since it allows races.  This
1291                                  * will be fixed when the stop character is
1292                                  * put in a special queue.  Don't bother with
1293                                  * the checks in ttywait() since the timeout
1294                                  * will save us.
1295                                  */
1296                                 SET(tp->t_state, TS_SO_OCOMPLETE);
1297                                 ttysleep(tp, TSA_OCOMPLETE(tp), TTOPRI,
1298                                          "ttyfls", hz / 10);
1299                                 /*
1300                                  * Don't try sending the stop character again.
1301                                  */
1302                                 CLR(tp->t_state, TS_TBLOCK);
1303                                 goto again;
1304                         }
1305 #endif
1306                 }
1307         }
1308         if (rw & FWRITE) {
1309                 FLUSHQ(&tp->t_outq);
1310                 ttwwakeup(tp);
1311         }
1312         splx(s);
1313 }
1314
1315 /*
1316  * Copy in the default termios characters.
1317  */
1318 void
1319 termioschars(t)
1320         struct termios *t;
1321 {
1322
1323         bcopy(ttydefchars, t->c_cc, sizeof t->c_cc);
1324 }
1325
1326 /*
1327  * Old interface.
1328  */
1329 void
1330 ttychars(tp)
1331         struct tty *tp;
1332 {
1333
1334         termioschars(&tp->t_termios);
1335 }
1336
1337 /*
1338  * Handle input high water.  Send stop character for the IXOFF case.  Turn
1339  * on our input flow control bit and propagate the changes to the driver.
1340  * XXX the stop character should be put in a special high priority queue.
1341  */
1342 void
1343 ttyblock(tp)
1344         struct tty *tp;
1345 {
1346
1347         SET(tp->t_state, TS_TBLOCK);
1348         if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
1349             putc(tp->t_cc[VSTOP], &tp->t_outq) != 0)
1350                 CLR(tp->t_state, TS_TBLOCK);    /* try again later */
1351         ttstart(tp);
1352 }
1353
1354 /*
1355  * Handle input low water.  Send start character for the IXOFF case.  Turn
1356  * off our input flow control bit and propagate the changes to the driver.
1357  * XXX the start character should be put in a special high priority queue.
1358  */
1359 static void
1360 ttyunblock(tp)
1361         struct tty *tp;
1362 {
1363
1364         CLR(tp->t_state, TS_TBLOCK);
1365         if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTART] != _POSIX_VDISABLE &&
1366             putc(tp->t_cc[VSTART], &tp->t_outq) != 0)
1367                 SET(tp->t_state, TS_TBLOCK);    /* try again later */
1368         ttstart(tp);
1369 }
1370
1371 #ifdef notyet
1372 /* Not used by any current (i386) drivers. */
1373 /*
1374  * Restart after an inter-char delay.
1375  */
1376 void
1377 ttrstrt(tp_arg)
1378         void *tp_arg;
1379 {
1380         struct tty *tp;
1381         int s;
1382
1383         KASSERT(tp_arg != NULL, ("ttrstrt"));
1384
1385         tp = tp_arg;
1386         s = spltty();
1387
1388         CLR(tp->t_state, TS_TIMEOUT);
1389         ttstart(tp);
1390
1391         splx(s);
1392 }
1393 #endif
1394
1395 int
1396 ttstart(tp)
1397         struct tty *tp;
1398 {
1399
1400         if (tp->t_oproc != NULL)        /* XXX: Kludge for pty. */
1401                 (*tp->t_oproc)(tp);
1402         return (0);
1403 }
1404
1405 /*
1406  * "close" a line discipline
1407  */
1408 int
1409 ttylclose(tp, flag)
1410         struct tty *tp;
1411         int flag;
1412 {
1413
1414         if (flag & FNONBLOCK || ttywflush(tp))
1415                 ttyflush(tp, FREAD | FWRITE);
1416         return (0);
1417 }
1418
1419 /*
1420  * Handle modem control transition on a tty.
1421  * Flag indicates new state of carrier.
1422  * Returns 0 if the line should be turned off, otherwise 1.
1423  */
1424 int
1425 ttymodem(tp, flag)
1426         register struct tty *tp;
1427         int flag;
1428 {
1429
1430         if (ISSET(tp->t_state, TS_CARR_ON) && ISSET(tp->t_cflag, MDMBUF)) {
1431                 /*
1432                  * MDMBUF: do flow control according to carrier flag
1433                  * XXX TS_CAR_OFLOW doesn't do anything yet.  TS_TTSTOP
1434                  * works if IXON and IXANY are clear.
1435                  */
1436                 if (flag) {
1437                         CLR(tp->t_state, TS_CAR_OFLOW);
1438                         CLR(tp->t_state, TS_TTSTOP);
1439                         ttstart(tp);
1440                 } else if (!ISSET(tp->t_state, TS_CAR_OFLOW)) {
1441                         SET(tp->t_state, TS_CAR_OFLOW);
1442                         SET(tp->t_state, TS_TTSTOP);
1443                         (*tp->t_stop)(tp, 0);
1444                 }
1445         } else if (flag == 0) {
1446                 /*
1447                  * Lost carrier.
1448                  */
1449                 CLR(tp->t_state, TS_CARR_ON);
1450                 if (ISSET(tp->t_state, TS_ISOPEN) &&
1451                     !ISSET(tp->t_cflag, CLOCAL)) {
1452                         SET(tp->t_state, TS_ZOMBIE);
1453                         CLR(tp->t_state, TS_CONNECTED);
1454                         if (tp->t_session && tp->t_session->s_leader)
1455                                 psignal(tp->t_session->s_leader, SIGHUP);
1456                         ttyflush(tp, FREAD | FWRITE);
1457                         return (0);
1458                 }
1459         } else {
1460                 /*
1461                  * Carrier now on.
1462                  */
1463                 SET(tp->t_state, TS_CARR_ON);
1464                 if (!ISSET(tp->t_state, TS_ZOMBIE))
1465                         SET(tp->t_state, TS_CONNECTED);
1466                 wakeup(TSA_CARR_ON(tp));
1467                 ttwakeup(tp);
1468                 ttwwakeup(tp);
1469         }
1470         return (1);
1471 }
1472
1473 /*
1474  * Reinput pending characters after state switch
1475  * call at spltty().
1476  */
1477 static void
1478 ttypend(tp)
1479         register struct tty *tp;
1480 {
1481         struct clist tq;
1482         register int c;
1483
1484         CLR(tp->t_lflag, PENDIN);
1485         SET(tp->t_state, TS_TYPEN);
1486         /*
1487          * XXX this assumes too much about clist internals.  It may even
1488          * fail if the cblock slush pool is empty.  We can't allocate more
1489          * cblocks here because we are called from an interrupt handler
1490          * and clist_alloc_cblocks() can wait.
1491          */
1492         tq = tp->t_rawq;
1493         bzero(&tp->t_rawq, sizeof tp->t_rawq);
1494         tp->t_rawq.c_cbmax = tq.c_cbmax;
1495         tp->t_rawq.c_cbreserved = tq.c_cbreserved;
1496         while ((c = getc(&tq)) >= 0)
1497                 ttyinput(c, tp);
1498         CLR(tp->t_state, TS_TYPEN);
1499 }
1500
1501 /*
1502  * Process a read call on a tty device.
1503  */
1504 int
1505 ttread(tp, uio, flag)
1506         register struct tty *tp;
1507         struct uio *uio;
1508         int flag;
1509 {
1510         register struct clist *qp;
1511         register int c;
1512         register tcflag_t lflag;
1513         register cc_t *cc = tp->t_cc;
1514         register struct proc *p = curproc;
1515         int s, first, error = 0;
1516         int has_stime = 0, last_cc = 0;
1517         long slp = 0;           /* XXX this should be renamed `timo'. */
1518         struct timeval stime;
1519
1520 loop:
1521         s = spltty();
1522         lflag = tp->t_lflag;
1523         /*
1524          * take pending input first
1525          */
1526         if (ISSET(lflag, PENDIN)) {
1527                 ttypend(tp);
1528                 splx(s);        /* reduce latency */
1529                 s = spltty();
1530                 lflag = tp->t_lflag;    /* XXX ttypend() clobbers it */
1531         }
1532
1533         /*
1534          * Hang process if it's in the background.
1535          */
1536         if (isbackground(p, tp)) {
1537                 splx(s);
1538                 if (SIGISMEMBER(p->p_sigignore, SIGTTIN) ||
1539                     SIGISMEMBER(p->p_sigmask, SIGTTIN) ||
1540                     (p->p_flag & P_PPWAIT) || p->p_pgrp->pg_jobc == 0)
1541                         return (EIO);
1542                 pgsignal(p->p_pgrp, SIGTTIN, 1);
1543                 error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, "ttybg2", 0);
1544                 if (error)
1545                         return (error);
1546                 goto loop;
1547         }
1548
1549         if (ISSET(tp->t_state, TS_ZOMBIE)) {
1550                 splx(s);
1551                 return (0);     /* EOF */
1552         }
1553
1554         /*
1555          * If canonical, use the canonical queue,
1556          * else use the raw queue.
1557          *
1558          * (should get rid of clists...)
1559          */
1560         qp = ISSET(lflag, ICANON) ? &tp->t_canq : &tp->t_rawq;
1561
1562         if (flag & IO_NDELAY) {
1563                 if (qp->c_cc > 0)
1564                         goto read;
1565                 if (!ISSET(lflag, ICANON) && cc[VMIN] == 0) {
1566                         splx(s);
1567                         return (0);
1568                 }
1569                 splx(s);
1570                 return (EWOULDBLOCK);
1571         }
1572         if (!ISSET(lflag, ICANON)) {
1573                 int m = cc[VMIN];
1574                 long t = cc[VTIME];
1575                 struct timeval timecopy;
1576
1577                 /*
1578                  * Check each of the four combinations.
1579                  * (m > 0 && t == 0) is the normal read case.
1580                  * It should be fairly efficient, so we check that and its
1581                  * companion case (m == 0 && t == 0) first.
1582                  * For the other two cases, we compute the target sleep time
1583                  * into slp.
1584                  */
1585                 if (t == 0) {
1586                         if (qp->c_cc < m)
1587                                 goto sleep;
1588                         if (qp->c_cc > 0)
1589                                 goto read;
1590
1591                         /* m, t and qp->c_cc are all 0.  0 is enough input. */
1592                         splx(s);
1593                         return (0);
1594                 }
1595                 t *= 100000;            /* time in us */
1596 #define diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 1000000 + \
1597                          ((t1).tv_usec - (t2).tv_usec))
1598                 if (m > 0) {
1599                         if (qp->c_cc <= 0)
1600                                 goto sleep;
1601                         if (qp->c_cc >= m)
1602                                 goto read;
1603                         getmicrotime(&timecopy);
1604                         if (!has_stime) {
1605                                 /* first character, start timer */
1606                                 has_stime = 1;
1607                                 stime = timecopy;
1608                                 slp = t;
1609                         } else if (qp->c_cc > last_cc) {
1610                                 /* got a character, restart timer */
1611                                 stime = timecopy;
1612                                 slp = t;
1613                         } else {
1614                                 /* nothing, check expiration */
1615                                 slp = t - diff(timecopy, stime);
1616                                 if (slp <= 0)
1617                                         goto read;
1618                         }
1619                         last_cc = qp->c_cc;
1620                 } else {        /* m == 0 */
1621                         if (qp->c_cc > 0)
1622                                 goto read;
1623                         getmicrotime(&timecopy);
1624                         if (!has_stime) {
1625                                 has_stime = 1;
1626                                 stime = timecopy;
1627                                 slp = t;
1628                         } else {
1629                                 slp = t - diff(timecopy, stime);
1630                                 if (slp <= 0) {
1631                                         /* Timed out, but 0 is enough input. */
1632                                         splx(s);
1633                                         return (0);
1634                                 }
1635                         }
1636                 }
1637 #undef diff
1638                 /*
1639                  * Rounding down may make us wake up just short
1640                  * of the target, so we round up.
1641                  * The formula is ceiling(slp * hz/1000000).
1642                  * 32-bit arithmetic is enough for hz < 169.
1643                  * XXX see tvtohz() for how to avoid overflow if hz
1644                  * is large (divide by `tick' and/or arrange to
1645                  * use tvtohz() if hz is large).
1646                  */
1647                 slp = (long) (((u_long)slp * hz) + 999999) / 1000000;
1648                 goto sleep;
1649         }
1650         if (qp->c_cc <= 0) {
1651 sleep:
1652                 /*
1653                  * There is no input, or not enough input and we can block.
1654                  */
1655                 error = ttysleep(tp, TSA_HUP_OR_INPUT(tp), TTIPRI | PCATCH,
1656                                  ISSET(tp->t_state, TS_CONNECTED) ?
1657                                  "ttyin" : "ttyhup", (int)slp);
1658                 splx(s);
1659                 if (error == EWOULDBLOCK)
1660                         error = 0;
1661                 else if (error)
1662                         return (error);
1663                 /*
1664                  * XXX what happens if another process eats some input
1665                  * while we are asleep (not just here)?  It would be
1666                  * safest to detect changes and reset our state variables
1667                  * (has_stime and last_cc).
1668                  */
1669                 slp = 0;
1670                 goto loop;
1671         }
1672 read:
1673         splx(s);
1674         /*
1675          * Input present, check for input mapping and processing.
1676          */
1677         first = 1;
1678         if (ISSET(lflag, ICANON | ISIG))
1679                 goto slowcase;
1680         for (;;) {
1681                 char ibuf[IBUFSIZ];
1682                 int icc;
1683
1684                 icc = imin(uio->uio_resid, IBUFSIZ);
1685                 icc = q_to_b(qp, ibuf, icc);
1686                 if (icc <= 0) {
1687                         if (first)
1688                                 goto loop;
1689                         break;
1690                 }
1691                 error = uiomove(ibuf, icc, uio);
1692                 /*
1693                  * XXX if there was an error then we should ungetc() the
1694                  * unmoved chars and reduce icc here.
1695                  */
1696                 if (error)
1697                         break;
1698                 if (uio->uio_resid == 0)
1699                         break;
1700                 first = 0;
1701         }
1702         goto out;
1703 slowcase:
1704         for (;;) {
1705                 c = getc(qp);
1706                 if (c < 0) {
1707                         if (first)
1708                                 goto loop;
1709                         break;
1710                 }
1711                 /*
1712                  * delayed suspend (^Y)
1713                  */
1714                 if (CCEQ(cc[VDSUSP], c) &&
1715                     ISSET(lflag, IEXTEN | ISIG) == (IEXTEN | ISIG)) {
1716                         pgsignal(tp->t_pgrp, SIGTSTP, 1);
1717                         if (first) {
1718                                 error = ttysleep(tp, &lbolt, TTIPRI | PCATCH,
1719                                                  "ttybg3", 0);
1720                                 if (error)
1721                                         break;
1722                                 goto loop;
1723                         }
1724                         break;
1725                 }
1726                 /*
1727                  * Interpret EOF only in canonical mode.
1728                  */
1729                 if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
1730                         break;
1731                 /*
1732                  * Give user character.
1733                  */
1734                 error = ureadc(c, uio);
1735                 if (error)
1736                         /* XXX should ungetc(c, qp). */
1737                         break;
1738                 if (uio->uio_resid == 0)
1739                         break;
1740                 /*
1741                  * In canonical mode check for a "break character"
1742                  * marking the end of a "line of input".
1743                  */
1744                 if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
1745                         break;
1746                 first = 0;
1747         }
1748
1749 out:
1750         /*
1751          * Look to unblock input now that (presumably)
1752          * the input queue has gone down.
1753          */
1754         s = spltty();
1755         if (ISSET(tp->t_state, TS_TBLOCK) &&
1756             tp->t_rawq.c_cc + tp->t_canq.c_cc <= tp->t_ilowat)
1757                 ttyunblock(tp);
1758         splx(s);
1759
1760         return (error);
1761 }
1762
1763 /*
1764  * Check the output queue on tp for space for a kernel message (from uprintf
1765  * or tprintf).  Allow some space over the normal hiwater mark so we don't
1766  * lose messages due to normal flow control, but don't let the tty run amok.
1767  * Sleeps here are not interruptible, but we return prematurely if new signals
1768  * arrive.
1769  */
1770 int
1771 ttycheckoutq(tp, wait)
1772         register struct tty *tp;
1773         int wait;
1774 {
1775         int hiwat, s;
1776         sigset_t oldmask;
1777
1778         hiwat = tp->t_ohiwat;
1779         SIGEMPTYSET(oldmask);
1780         s = spltty();
1781         if (wait)
1782                 oldmask = curproc->p_siglist;
1783         if (tp->t_outq.c_cc > hiwat + OBUFSIZ + 100)
1784                 while (tp->t_outq.c_cc > hiwat) {
1785                         ttstart(tp);
1786                         if (tp->t_outq.c_cc <= hiwat)
1787                                 break;
1788                         if (!(wait && SIGSETEQ(curproc->p_siglist, oldmask))) {
1789                                 splx(s);
1790                                 return (0);
1791                         }
1792                         SET(tp->t_state, TS_SO_OLOWAT);
1793                         tsleep(TSA_OLOWAT(tp), PZERO - 1, "ttoutq", hz);
1794                 }
1795         splx(s);
1796         return (1);
1797 }
1798
1799 /*
1800  * Process a write call on a tty device.
1801  */
1802 int
1803 ttwrite(tp, uio, flag)
1804         register struct tty *tp;
1805         register struct uio *uio;
1806         int flag;
1807 {
1808         register char *cp = NULL;
1809         register int cc, ce;
1810         register struct proc *p;
1811         int i, hiwat, cnt, error, s;
1812         char obuf[OBUFSIZ];
1813
1814         hiwat = tp->t_ohiwat;
1815         cnt = uio->uio_resid;
1816         error = 0;
1817         cc = 0;
1818 loop:
1819         s = spltty();
1820         if (ISSET(tp->t_state, TS_ZOMBIE)) {
1821                 splx(s);
1822                 if (uio->uio_resid == cnt)
1823                         error = EIO;
1824                 goto out;
1825         }
1826         if (!ISSET(tp->t_state, TS_CONNECTED)) {
1827                 if (flag & IO_NDELAY) {
1828                         splx(s);
1829                         error = EWOULDBLOCK;
1830                         goto out;
1831                 }
1832                 error = ttysleep(tp, TSA_CARR_ON(tp), TTIPRI | PCATCH,
1833                                  "ttydcd", 0);
1834                 splx(s);
1835                 if (error)
1836                         goto out;
1837                 goto loop;
1838         }
1839         splx(s);
1840         /*
1841          * Hang the process if it's in the background.
1842          */
1843         p = curproc;
1844         if (isbackground(p, tp) &&
1845             ISSET(tp->t_lflag, TOSTOP) && !(p->p_flag & P_PPWAIT) &&
1846             !SIGISMEMBER(p->p_sigignore, SIGTTOU) &&
1847             !SIGISMEMBER(p->p_sigmask, SIGTTOU)) {
1848                 if (p->p_pgrp->pg_jobc == 0) {
1849                         error = EIO;
1850                         goto out;
1851                 }
1852                 pgsignal(p->p_pgrp, SIGTTOU, 1);
1853                 error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, "ttybg4", 0);
1854                 if (error)
1855                         goto out;
1856                 goto loop;
1857         }
1858         /*
1859          * Process the user's data in at most OBUFSIZ chunks.  Perform any
1860          * output translation.  Keep track of high water mark, sleep on
1861          * overflow awaiting device aid in acquiring new space.
1862          */
1863         while (uio->uio_resid > 0 || cc > 0) {
1864                 if (ISSET(tp->t_lflag, FLUSHO)) {
1865                         uio->uio_resid = 0;
1866                         return (0);
1867                 }
1868                 if (tp->t_outq.c_cc > hiwat)
1869                         goto ovhiwat;
1870                 /*
1871                  * Grab a hunk of data from the user, unless we have some
1872                  * leftover from last time.
1873                  */
1874                 if (cc == 0) {
1875                         cc = imin(uio->uio_resid, OBUFSIZ);
1876                         cp = obuf;
1877                         error = uiomove(cp, cc, uio);
1878                         if (error) {
1879                                 cc = 0;
1880                                 break;
1881                         }
1882                 }
1883                 /*
1884                  * If nothing fancy need be done, grab those characters we
1885                  * can handle without any of ttyoutput's processing and
1886                  * just transfer them to the output q.  For those chars
1887                  * which require special processing (as indicated by the
1888                  * bits in char_type), call ttyoutput.  After processing
1889                  * a hunk of data, look for FLUSHO so ^O's will take effect
1890                  * immediately.
1891                  */
1892                 while (cc > 0) {
1893                         if (!ISSET(tp->t_oflag, OPOST))
1894                                 ce = cc;
1895                         else {
1896                                 ce = cc - scanc((u_int)cc, (u_char *)cp,
1897                                                 char_type, CCLASSMASK);
1898                                 /*
1899                                  * If ce is zero, then we're processing
1900                                  * a special character through ttyoutput.
1901                                  */
1902                                 if (ce == 0) {
1903                                         tp->t_rocount = 0;
1904                                         if (ttyoutput(*cp, tp) >= 0) {
1905                                                 /* No Clists, wait a bit. */
1906                                                 ttstart(tp);
1907                                                 if (flag & IO_NDELAY) {
1908                                                         error = EWOULDBLOCK;
1909                                                         goto out;
1910                                                 }
1911                                                 error = ttysleep(tp, &lbolt,
1912                                                                  TTOPRI|PCATCH,
1913                                                                  "ttybf1", 0);
1914                                                 if (error)
1915                                                         goto out;
1916                                                 goto loop;
1917                                         }
1918                                         cp++;
1919                                         cc--;
1920                                         if (ISSET(tp->t_lflag, FLUSHO) ||
1921                                             tp->t_outq.c_cc > hiwat)
1922                                                 goto ovhiwat;
1923                                         continue;
1924                                 }
1925                         }
1926                         /*
1927                          * A bunch of normal characters have been found.
1928                          * Transfer them en masse to the output queue and
1929                          * continue processing at the top of the loop.
1930                          * If there are any further characters in this
1931                          * <= OBUFSIZ chunk, the first should be a character
1932                          * requiring special handling by ttyoutput.
1933                          */
1934                         tp->t_rocount = 0;
1935                         i = b_to_q(cp, ce, &tp->t_outq);
1936                         ce -= i;
1937                         tp->t_column += ce;
1938                         cp += ce, cc -= ce, tk_nout += ce;
1939                         tp->t_outcc += ce;
1940                         if (i > 0) {
1941                                 /* No Clists, wait a bit. */
1942                                 ttstart(tp);
1943                                 if (flag & IO_NDELAY) {
1944                                         error = EWOULDBLOCK;
1945                                         goto out;
1946                                 }
1947                                 error = ttysleep(tp, &lbolt, TTOPRI | PCATCH,
1948                                                  "ttybf2", 0);
1949                                 if (error)
1950                                         goto out;
1951                                 goto loop;
1952                         }
1953                         if (ISSET(tp->t_lflag, FLUSHO) ||
1954                             tp->t_outq.c_cc > hiwat)
1955                                 break;
1956                 }
1957                 ttstart(tp);
1958         }
1959 out:
1960         /*
1961          * If cc is nonzero, we leave the uio structure inconsistent, as the
1962          * offset and iov pointers have moved forward, but it doesn't matter
1963          * (the call will either return short or restart with a new uio).
1964          */
1965         uio->uio_resid += cc;
1966         return (error);
1967
1968 ovhiwat:
1969         ttstart(tp);
1970         s = spltty();
1971         /*
1972          * This can only occur if FLUSHO is set in t_lflag,
1973          * or if ttstart/oproc is synchronous (or very fast).
1974          */
1975         if (tp->t_outq.c_cc <= hiwat) {
1976                 splx(s);
1977                 goto loop;
1978         }
1979         if (flag & IO_NDELAY) {
1980                 splx(s);
1981                 uio->uio_resid += cc;
1982                 return (uio->uio_resid == cnt ? EWOULDBLOCK : 0);
1983         }
1984         SET(tp->t_state, TS_SO_OLOWAT);
1985         error = ttysleep(tp, TSA_OLOWAT(tp), TTOPRI | PCATCH, "ttywri",
1986                          tp->t_timeout);
1987         splx(s);
1988         if (error == EWOULDBLOCK)
1989                 error = EIO;
1990         if (error)
1991                 goto out;
1992         goto loop;
1993 }
1994
1995 /*
1996  * Rubout one character from the rawq of tp
1997  * as cleanly as possible.
1998  */
1999 static void
2000 ttyrub(c, tp)
2001         register int c;
2002         register struct tty *tp;
2003 {
2004         register char *cp;
2005         register int savecol;
2006         int tabc, s;
2007
2008         if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
2009                 return;
2010         CLR(tp->t_lflag, FLUSHO);
2011         if (ISSET(tp->t_lflag, ECHOE)) {
2012                 if (tp->t_rocount == 0) {
2013                         /*
2014                          * Screwed by ttwrite; retype
2015                          */
2016                         ttyretype(tp);
2017                         return;
2018                 }
2019                 if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
2020                         ttyrubo(tp, 2);
2021                 else {
2022                         CLR(c, ~TTY_CHARMASK);
2023                         switch (CCLASS(c)) {
2024                         case ORDINARY:
2025                                 ttyrubo(tp, 1);
2026                                 break;
2027                         case BACKSPACE:
2028                         case CONTROL:
2029                         case NEWLINE:
2030                         case RETURN:
2031                         case VTAB:
2032                                 if (ISSET(tp->t_lflag, ECHOCTL))
2033                                         ttyrubo(tp, 2);
2034                                 break;
2035                         case TAB:
2036                                 if (tp->t_rocount < tp->t_rawq.c_cc) {
2037                                         ttyretype(tp);
2038                                         return;
2039                                 }
2040                                 s = spltty();
2041                                 savecol = tp->t_column;
2042                                 SET(tp->t_state, TS_CNTTB);
2043                                 SET(tp->t_lflag, FLUSHO);
2044                                 tp->t_column = tp->t_rocol;
2045                                 cp = tp->t_rawq.c_cf;
2046                                 if (cp)
2047                                         tabc = *cp;     /* XXX FIX NEXTC */
2048                                 for (; cp; cp = nextc(&tp->t_rawq, cp, &tabc))
2049                                         ttyecho(tabc, tp);
2050                                 CLR(tp->t_lflag, FLUSHO);
2051                                 CLR(tp->t_state, TS_CNTTB);
2052                                 splx(s);
2053
2054                                 /* savecol will now be length of the tab. */
2055                                 savecol -= tp->t_column;
2056                                 tp->t_column += savecol;
2057                                 if (savecol > 8)
2058                                         savecol = 8;    /* overflow screw */
2059                                 while (--savecol >= 0)
2060                                         (void)ttyoutput('\b', tp);
2061                                 break;
2062                         default:                        /* XXX */
2063 #define PANICSTR        "ttyrub: would panic c = %d, val = %d\n"
2064                                 (void)printf(PANICSTR, c, CCLASS(c));
2065 #ifdef notdef
2066                                 panic(PANICSTR, c, CCLASS(c));
2067 #endif
2068                         }
2069                 }
2070         } else if (ISSET(tp->t_lflag, ECHOPRT)) {
2071                 if (!ISSET(tp->t_state, TS_ERASE)) {
2072                         SET(tp->t_state, TS_ERASE);
2073                         (void)ttyoutput('\\', tp);
2074                 }
2075                 ttyecho(c, tp);
2076         } else {
2077                 ttyecho(tp->t_cc[VERASE], tp);
2078                 /*
2079                  * This code may be executed not only when an ERASE key
2080                  * is pressed, but also when ^U (KILL) or ^W (WERASE) are.
2081                  * So, I didn't think it was worthwhile to pass the extra
2082                  * information (which would need an extra parameter,
2083                  * changing every call) needed to distinguish the ERASE2
2084                  * case from the ERASE.
2085                  */
2086         }
2087         --tp->t_rocount;
2088 }
2089
2090 /*
2091  * Back over cnt characters, erasing them.
2092  */
2093 static void
2094 ttyrubo(tp, cnt)
2095         register struct tty *tp;
2096         int cnt;
2097 {
2098
2099         while (cnt-- > 0) {
2100                 (void)ttyoutput('\b', tp);
2101                 (void)ttyoutput(' ', tp);
2102                 (void)ttyoutput('\b', tp);
2103         }
2104 }
2105
2106 /*
2107  * ttyretype --
2108  *      Reprint the rawq line.  Note, it is assumed that c_cc has already
2109  *      been checked.
2110  */
2111 static void
2112 ttyretype(tp)
2113         register struct tty *tp;
2114 {
2115         register char *cp;
2116         int s, c;
2117
2118         /* Echo the reprint character. */
2119         if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
2120                 ttyecho(tp->t_cc[VREPRINT], tp);
2121
2122         (void)ttyoutput('\n', tp);
2123
2124         /*
2125          * XXX
2126          * FIX: NEXTC IS BROKEN - DOESN'T CHECK QUOTE
2127          * BIT OF FIRST CHAR.
2128          */
2129         s = spltty();
2130         for (cp = tp->t_canq.c_cf, c = (cp != NULL ? *cp : 0);
2131             cp != NULL; cp = nextc(&tp->t_canq, cp, &c))
2132                 ttyecho(c, tp);
2133         for (cp = tp->t_rawq.c_cf, c = (cp != NULL ? *cp : 0);
2134             cp != NULL; cp = nextc(&tp->t_rawq, cp, &c))
2135                 ttyecho(c, tp);
2136         CLR(tp->t_state, TS_ERASE);
2137         splx(s);
2138
2139         tp->t_rocount = tp->t_rawq.c_cc;
2140         tp->t_rocol = 0;
2141 }
2142
2143 /*
2144  * Echo a typed character to the terminal.
2145  */
2146 static void
2147 ttyecho(c, tp)
2148         register int c;
2149         register struct tty *tp;
2150 {
2151
2152         if (!ISSET(tp->t_state, TS_CNTTB))
2153                 CLR(tp->t_lflag, FLUSHO);
2154         if ((!ISSET(tp->t_lflag, ECHO) &&
2155              (c != '\n' || !ISSET(tp->t_lflag, ECHONL))) ||
2156             ISSET(tp->t_lflag, EXTPROC))
2157                 return;
2158         if (ISSET(tp->t_lflag, ECHOCTL) &&
2159             ((ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n') ||
2160             ISSET(c, TTY_CHARMASK) == 0177)) {
2161                 (void)ttyoutput('^', tp);
2162                 CLR(c, ~TTY_CHARMASK);
2163                 if (c == 0177)
2164                         c = '?';
2165                 else
2166                         c += 'A' - 1;
2167         }
2168         (void)ttyoutput(c, tp);
2169 }
2170
2171 /*
2172  * Wake up any readers on a tty.
2173  */
2174 void
2175 ttwakeup(tp)
2176         register struct tty *tp;
2177 {
2178
2179         if (tp->t_rsel.si_pid != 0)
2180                 selwakeup(&tp->t_rsel);
2181         if (ISSET(tp->t_state, TS_ASYNC) && tp->t_sigio != NULL)
2182                 pgsigio(tp->t_sigio, SIGIO, (tp->t_session != NULL));
2183         wakeup(TSA_HUP_OR_INPUT(tp));
2184         KNOTE(&tp->t_rsel.si_note, 0);
2185 }
2186
2187 /*
2188  * Wake up any writers on a tty.
2189  */
2190 void
2191 ttwwakeup(tp)
2192         register struct tty *tp;
2193 {
2194
2195         if (tp->t_wsel.si_pid != 0 && tp->t_outq.c_cc <= tp->t_olowat)
2196                 selwakeup(&tp->t_wsel);
2197         if (ISSET(tp->t_state, TS_ASYNC) && tp->t_sigio != NULL)
2198                 pgsigio(tp->t_sigio, SIGIO, (tp->t_session != NULL));
2199         if (ISSET(tp->t_state, TS_BUSY | TS_SO_OCOMPLETE) ==
2200             TS_SO_OCOMPLETE && tp->t_outq.c_cc == 0) {
2201                 CLR(tp->t_state, TS_SO_OCOMPLETE);
2202                 wakeup(TSA_OCOMPLETE(tp));
2203         }
2204         if (ISSET(tp->t_state, TS_SO_OLOWAT) &&
2205             tp->t_outq.c_cc <= tp->t_olowat) {
2206                 CLR(tp->t_state, TS_SO_OLOWAT);
2207                 wakeup(TSA_OLOWAT(tp));
2208         }
2209         KNOTE(&tp->t_wsel.si_note, 0);
2210 }
2211
2212 /*
2213  * Look up a code for a specified speed in a conversion table;
2214  * used by drivers to map software speed values to hardware parameters.
2215  */
2216 int
2217 ttspeedtab(speed, table)
2218         int speed;
2219         register struct speedtab *table;
2220 {
2221
2222         for ( ; table->sp_speed != -1; table++)
2223                 if (table->sp_speed == speed)
2224                         return (table->sp_code);
2225         return (-1);
2226 }
2227
2228 /*
2229  * Set input and output watermarks and buffer sizes.  For input, the
2230  * high watermark is about one second's worth of input above empty, the
2231  * low watermark is slightly below high water, and the buffer size is a
2232  * driver-dependent amount above high water.  For output, the watermarks
2233  * are near the ends of the buffer, with about 1 second's worth of input
2234  * between them.  All this only applies to the standard line discipline.
2235  */
2236 void
2237 ttsetwater(tp)
2238         struct tty *tp;
2239 {
2240         register int cps, ttmaxhiwat, x;
2241
2242         /* Input. */
2243         clist_alloc_cblocks(&tp->t_canq, TTYHOG, 512);
2244         switch (tp->t_ispeedwat) {
2245         case (speed_t)-1:
2246                 cps = tp->t_ispeed / 10;
2247                 break;
2248         case 0:
2249                 /*
2250                  * This case is for old drivers that don't know about
2251                  * t_ispeedwat.  Arrange for them to get the old buffer
2252                  * sizes and watermarks.
2253                  */
2254                 cps = TTYHOG - 2 * 256;
2255                 tp->t_ififosize = 2 * 256;
2256                 break;
2257         default:
2258                 cps = tp->t_ispeedwat / 10;
2259                 break;
2260         }
2261         tp->t_ihiwat = cps;
2262         tp->t_ilowat = 7 * cps / 8;
2263         x = cps + tp->t_ififosize;
2264         clist_alloc_cblocks(&tp->t_rawq, x, x);
2265
2266         /* Output. */
2267         switch (tp->t_ospeedwat) {
2268         case (speed_t)-1:
2269                 cps = tp->t_ospeed / 10;
2270                 ttmaxhiwat = 2 * TTMAXHIWAT;
2271                 break;
2272         case 0:
2273                 cps = tp->t_ospeed / 10;
2274                 ttmaxhiwat = TTMAXHIWAT;
2275                 break;
2276         default:
2277                 cps = tp->t_ospeedwat / 10;
2278                 ttmaxhiwat = 8 * TTMAXHIWAT;
2279                 break;
2280         }
2281 #define CLAMP(x, h, l)  ((x) > h ? h : ((x) < l) ? l : (x))
2282         tp->t_olowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
2283         x += cps;
2284         x = CLAMP(x, ttmaxhiwat, TTMINHIWAT);   /* XXX clamps are too magic */
2285         tp->t_ohiwat = roundup(x, CBSIZE);      /* XXX for compat */
2286         x = imax(tp->t_ohiwat, TTMAXHIWAT);     /* XXX for compat/safety */
2287         x += OBUFSIZ + 100;
2288         clist_alloc_cblocks(&tp->t_outq, x, x);
2289 #undef  CLAMP
2290 }
2291
2292 /*
2293  * Report on state of foreground process group.
2294  */
2295 void
2296 ttyinfo(tp)
2297         register struct tty *tp;
2298 {
2299         register struct proc *p, *pick;
2300         struct timeval utime, stime;
2301         int tmp;
2302
2303         if (ttycheckoutq(tp,0) == 0)
2304                 return;
2305
2306         /* Print load average. */
2307         tmp = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
2308         ttyprintf(tp, "load: %d.%02d ", tmp / 100, tmp % 100);
2309
2310         if (tp->t_session == NULL)
2311                 ttyprintf(tp, "not a controlling terminal\n");
2312         else if (tp->t_pgrp == NULL)
2313                 ttyprintf(tp, "no foreground process group\n");
2314         else if ((p = LIST_FIRST(&tp->t_pgrp->pg_members)) == 0)
2315                 ttyprintf(tp, "empty foreground process group\n");
2316         else {
2317                 /* Pick interesting process. */
2318                 for (pick = NULL; p != 0; p = LIST_NEXT(p, p_pglist))
2319                         if (proc_compare(pick, p))
2320                                 pick = p;
2321
2322                 ttyprintf(tp, " cmd: %s %d [%s] ", pick->p_comm, pick->p_pid,
2323                     pick->p_stat == SRUN ? "running" :
2324                     pick->p_wmesg ? pick->p_wmesg : "iowait");
2325
2326                 if (pick->p_flag & P_INMEM) {
2327                         calcru(pick, &utime, &stime, NULL);
2328
2329                         /* Print user time. */
2330                         ttyprintf(tp, "%ld.%02ldu ",
2331                             utime.tv_sec, utime.tv_usec / 10000);
2332
2333                         /* Print system time. */
2334                         ttyprintf(tp, "%ld.%02lds ",
2335                             stime.tv_sec, stime.tv_usec / 10000);
2336                 } else
2337                         ttyprintf(tp, "?.??u ?.??s ");
2338
2339                 /* Print percentage cpu, resident set size. */
2340                 tmp = (pick->p_pctcpu * 10000 + FSCALE / 2) >> FSHIFT;
2341                 ttyprintf(tp, "%d%% %ldk\n",
2342                     tmp / 100,
2343                     pick->p_stat == SIDL || pick->p_stat == SZOMB ? 0 :
2344                     (long)pgtok(vmspace_resident_count(pick->p_vmspace)));
2345         }
2346         tp->t_rocount = 0;      /* so pending input will be retyped if BS */
2347 }
2348
2349 /*
2350  * Returns 1 if p2 is "better" than p1
2351  *
2352  * The algorithm for picking the "interesting" process is thus:
2353  *
2354  *      1) Only foreground processes are eligible - implied.
2355  *      2) Runnable processes are favored over anything else.  The runner
2356  *         with the highest cpu utilization is picked (p_estcpu).  Ties are
2357  *         broken by picking the highest pid.
2358  *      3) The sleeper with the shortest sleep time is next.  With ties,
2359  *         we pick out just "short-term" sleepers (P_SINTR == 0).
2360  *      4) Further ties are broken by picking the highest pid.
2361  */
2362 #define ISRUN(p)        (((p)->p_stat == SRUN) || ((p)->p_stat == SIDL))
2363 #define TESTAB(a, b)    ((a)<<1 | (b))
2364 #define ONLYA   2
2365 #define ONLYB   1
2366 #define BOTH    3
2367
2368 static int
2369 proc_compare(p1, p2)
2370         register struct proc *p1, *p2;
2371 {
2372
2373         if (p1 == NULL)
2374                 return (1);
2375         /*
2376          * see if at least one of them is runnable
2377          */
2378         switch (TESTAB(ISRUN(p1), ISRUN(p2))) {
2379         case ONLYA:
2380                 return (0);
2381         case ONLYB:
2382                 return (1);
2383         case BOTH:
2384                 /*
2385                  * tie - favor one with highest recent cpu utilization
2386                  */
2387                 if (p2->p_estcpu > p1->p_estcpu)
2388                         return (1);
2389                 if (p1->p_estcpu > p2->p_estcpu)
2390                         return (0);
2391                 return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
2392         }
2393         /*
2394          * weed out zombies
2395          */
2396         switch (TESTAB(p1->p_stat == SZOMB, p2->p_stat == SZOMB)) {
2397         case ONLYA:
2398                 return (1);
2399         case ONLYB:
2400                 return (0);
2401         case BOTH:
2402                 return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
2403         }
2404         /*
2405          * pick the one with the smallest sleep time
2406          */
2407         if (p2->p_slptime > p1->p_slptime)
2408                 return (0);
2409         if (p1->p_slptime > p2->p_slptime)
2410                 return (1);
2411         /*
2412          * favor one sleeping in a non-interruptible sleep
2413          */
2414         if (p1->p_flag & P_SINTR && (p2->p_flag & P_SINTR) == 0)
2415                 return (1);
2416         if (p2->p_flag & P_SINTR && (p1->p_flag & P_SINTR) == 0)
2417                 return (0);
2418         return (p2->p_pid > p1->p_pid);         /* tie - return highest pid */
2419 }
2420
2421 /*
2422  * Output char to tty; console putchar style.
2423  */
2424 int
2425 tputchar(c, tp)
2426         int c;
2427         struct tty *tp;
2428 {
2429         register int s;
2430
2431         s = spltty();
2432         if (!ISSET(tp->t_state, TS_CONNECTED)) {
2433                 splx(s);
2434                 return (-1);
2435         }
2436         if (c == '\n')
2437                 (void)ttyoutput('\r', tp);
2438         (void)ttyoutput(c, tp);
2439         ttstart(tp);
2440         splx(s);
2441         return (0);
2442 }
2443
2444 /*
2445  * Sleep on chan, returning ERESTART if tty changed while we napped and
2446  * returning any errors (e.g. EINTR/EWOULDBLOCK) reported by tsleep.  If
2447  * the tty is revoked, restarting a pending call will redo validation done
2448  * at the start of the call.
2449  */
2450 int
2451 ttysleep(tp, chan, pri, wmesg, timo)
2452         struct tty *tp;
2453         void *chan;
2454         int pri, timo;
2455         char *wmesg;
2456 {
2457         int error;
2458         int gen;
2459
2460         gen = tp->t_gen;
2461         error = tsleep(chan, pri, wmesg, timo);
2462         if (error)
2463                 return (error);
2464         return (tp->t_gen == gen ? 0 : ERESTART);
2465 }
2466
2467 /*
2468  * Allocate a tty struct.  Clists in the struct will be allocated by
2469  * ttyopen().
2470  */
2471 struct tty *
2472 ttymalloc(tp)
2473         struct tty *tp;
2474 {
2475
2476         if (tp)
2477                 return(tp);
2478         tp = malloc(sizeof *tp, M_TTYS, M_WAITOK);
2479         bzero(tp, sizeof *tp);
2480         ttyregister(tp);
2481         return (tp);
2482 }
2483
2484 #if 0 /* XXX not yet usable: session leader holds a ref (see kern_exit.c). */
2485 /*
2486  * Free a tty struct.  Clists in the struct should have been freed by
2487  * ttyclose().
2488  */
2489 void
2490 ttyfree(tp)
2491         struct tty *tp;
2492 {
2493         free(tp, M_TTYS);
2494 }
2495 #endif /* 0 */
2496
2497 void
2498 ttyregister(tp)
2499         struct tty *tp;
2500 {
2501         SLIST_INSERT_HEAD(&tty_list, tp, t_list);
2502 }
2503
2504 static int
2505 sysctl_kern_ttys(SYSCTL_HANDLER_ARGS)
2506 {
2507         int error;
2508         struct tty *tp, t;
2509         SLIST_FOREACH(tp, &tty_list, t_list) {
2510                 t = *tp;
2511                 if (t.t_dev)
2512                         t.t_dev = (dev_t)dev2udev(t.t_dev);
2513                 error = SYSCTL_OUT(req, (caddr_t)&t, sizeof(t));
2514                 if (error)
2515                         return (error);
2516         }
2517         return (0);
2518 }
2519
2520 SYSCTL_PROC(_kern, OID_AUTO, ttys, CTLTYPE_OPAQUE|CTLFLAG_RD,
2521         0, 0, sysctl_kern_ttys, "S,tty", "All struct ttys");
2522
2523 void
2524 nottystop(tp, rw)
2525         struct tty *tp;
2526         int rw;
2527 {
2528
2529         return;
2530 }
2531
2532 int
2533 ttyread(dev, uio, flag)
2534         dev_t dev;
2535         struct uio *uio;
2536         int flag;
2537 {
2538         struct tty *tp;
2539
2540         tp = dev->si_tty;
2541         if (tp == NULL)
2542                 return (ENODEV);
2543         return ((*linesw[tp->t_line].l_read)(tp, uio, flag));
2544 }
2545
2546 int
2547 ttywrite(dev, uio, flag)
2548         dev_t dev;
2549         struct uio *uio;
2550         int flag;
2551 {
2552         struct tty *tp;
2553
2554         tp = dev->si_tty;
2555         if (tp == NULL)
2556                 return (ENODEV);
2557         return ((*linesw[tp->t_line].l_write)(tp, uio, flag));
2558 }