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