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