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