tty.c revision 1.158 1 /* $NetBSD: tty.c,v 1.158 2003/09/21 19:17:09 jdolecek 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.158 2003/09/21 19:17:09 jdolecek 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 case FIOSETOWN:
786 #endif
787 case TIOCSTAT:
788 case TIOCSTI:
789 case TIOCSWINSZ:
790 #ifdef COMPAT_OLDTTY
791 case TIOCLBIC:
792 case TIOCLBIS:
793 case TIOCLSET:
794 case TIOCSETC:
795 case OTIOCSETD:
796 case TIOCSETN:
797 case TIOCSETP:
798 case TIOCSLTC:
799 #endif
800 while (isbackground(curproc, tp) &&
801 p->p_pgrp->pg_jobc && (p->p_flag & P_PPWAIT) == 0 &&
802 !sigismasked(p, SIGTTOU)) {
803 pgsignal(p->p_pgrp, SIGTTOU, 1);
804 s = spltty();
805 TTY_LOCK(tp);
806 error = ttysleep(tp, &lbolt,
807 TTOPRI | PCATCH | PNORELOCK, ttybg, 0);
808 splx(s);
809 if (error) {
810 return (error);
811 }
812 }
813 break;
814 }
815
816 switch (cmd) { /* Process the ioctl. */
817 case FIOASYNC: /* set/clear async i/o */
818 s = spltty();
819 TTY_LOCK(tp);
820 if (*(int *)data)
821 SET(tp->t_state, TS_ASYNC);
822 else
823 CLR(tp->t_state, TS_ASYNC);
824 TTY_UNLOCK(tp);
825 splx(s);
826 break;
827 case FIONBIO: /* set/clear non-blocking i/o */
828 break; /* XXX: delete. */
829 case FIONREAD: /* get # bytes to read */
830 s = spltty();
831 TTY_LOCK(tp);
832 *(int *)data = ttnread(tp);
833 TTY_UNLOCK(tp);
834 splx(s);
835 break;
836 case TIOCEXCL: /* set exclusive use of tty */
837 s = spltty();
838 TTY_LOCK(tp);
839 SET(tp->t_state, TS_XCLUDE);
840 splx(s);
841 TTY_UNLOCK(tp);
842 break;
843 case TIOCFLUSH: { /* flush buffers */
844 int flags = *(int *)data;
845
846 if (flags == 0)
847 flags = FREAD | FWRITE;
848 else
849 flags &= FREAD | FWRITE;
850 s = spltty();
851 TTY_LOCK(tp);
852 ttyflush(tp, flags);
853 TTY_UNLOCK(tp);
854 splx(s);
855 break;
856 }
857 case TIOCCONS: /* become virtual console */
858 if (*(int *)data) {
859 if (constty && constty != tp &&
860 ISSET(constty->t_state, TS_CARR_ON | TS_ISOPEN) ==
861 (TS_CARR_ON | TS_ISOPEN))
862 return EBUSY;
863
864 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE,
865 "/dev/console", p);
866 if ((error = namei(&nd)) != 0)
867 return error;
868 error = VOP_ACCESS(nd.ni_vp, VREAD, p->p_ucred, p);
869 vput(nd.ni_vp);
870 if (error)
871 return error;
872
873 constty = tp;
874 } else if (tp == constty)
875 constty = NULL;
876 break;
877 case TIOCDRAIN: /* wait till output drained */
878 if ((error = ttywait(tp)) != 0)
879 return (error);
880 break;
881 case TIOCGETA: { /* get termios struct */
882 struct termios *t = (struct termios *)data;
883
884 memcpy(t, &tp->t_termios, sizeof(struct termios));
885 break;
886 }
887 case TIOCGETD: /* get line discipline */
888 *(int *)data = tp->t_linesw->l_no;
889 break;
890 case TIOCGLINED:
891 (void)strncpy((char *)data, tp->t_linesw->l_name,
892 TTLINEDNAMELEN - 1);
893 break;
894 case TIOCGWINSZ: /* get window size */
895 *(struct winsize *)data = tp->t_winsize;
896 break;
897 case FIOGETOWN:
898 if (!isctty(p, tp))
899 return (ENOTTY);
900 *(int *)data = tp->t_pgrp ? -tp->t_pgrp->pg_id : 0;
901 break;
902 case TIOCGPGRP: /* get pgrp of tty */
903 if (!isctty(p, tp))
904 return (ENOTTY);
905 *(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PGID;
906 break;
907 case TIOCGSID: /* get sid of tty */
908 if (!isctty(p, tp))
909 return (ENOTTY);
910 *(int *)data = tp->t_session->s_sid;
911 break;
912 #ifdef TIOCHPCL
913 case TIOCHPCL: /* hang up on last close */
914 s = spltty();
915 TTY_LOCK(tp);
916 SET(tp->t_cflag, HUPCL);
917 TTY_UNLOCK(tp);
918 splx(s);
919 break;
920 #endif
921 case TIOCNXCL: /* reset exclusive use of tty */
922 s = spltty();
923 TTY_LOCK(tp);
924 CLR(tp->t_state, TS_XCLUDE);
925 TTY_UNLOCK(tp);
926 splx(s);
927 break;
928 case TIOCOUTQ: /* output queue size */
929 *(int *)data = tp->t_outq.c_cc;
930 break;
931 case TIOCSETA: /* set termios struct */
932 case TIOCSETAW: /* drain output, set */
933 case TIOCSETAF: { /* drn out, fls in, set */
934 struct termios *t = (struct termios *)data;
935
936 if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
937 if ((error = ttywait(tp)) != 0)
938 return (error);
939
940 if (cmd == TIOCSETAF) {
941 s = spltty();
942 TTY_LOCK(tp);
943 ttyflush(tp, FREAD);
944 TTY_UNLOCK(tp);
945 splx(s);
946 }
947 }
948
949 s = spltty();
950 /*
951 * XXXSMP - some drivers call back on us from t_param(), so
952 * don't take the tty spin lock here.
953 * require t_param() to unlock upon callback?
954 */
955 /* wanted here: TTY_LOCK(tp); */
956 if (!ISSET(t->c_cflag, CIGNORE)) {
957 /*
958 * Set device hardware.
959 */
960 if (tp->t_param && (error = (*tp->t_param)(tp, t))) {
961 /* wanted here: TTY_UNLOCK(tp); */
962 splx(s);
963 return (error);
964 } else {
965 tp->t_cflag = t->c_cflag;
966 tp->t_ispeed = t->c_ispeed;
967 tp->t_ospeed = t->c_ospeed;
968 if (t->c_ospeed == 0 && tp->t_session &&
969 tp->t_session->s_leader)
970 psignal(tp->t_session->s_leader,
971 SIGHUP);
972 }
973 ttsetwater(tp);
974 }
975
976 /* delayed lock acquiring */TTY_LOCK(tp);
977 if (cmd != TIOCSETAF) {
978 if (ISSET(t->c_lflag, ICANON) !=
979 ISSET(tp->t_lflag, ICANON)) {
980 if (ISSET(t->c_lflag, ICANON)) {
981 SET(tp->t_lflag, PENDIN);
982 ttwakeup(tp);
983 } else {
984 struct clist tq;
985
986 catq(&tp->t_rawq, &tp->t_canq);
987 tq = tp->t_rawq;
988 tp->t_rawq = tp->t_canq;
989 tp->t_canq = tq;
990 CLR(tp->t_lflag, PENDIN);
991 }
992 }
993 }
994 tp->t_iflag = t->c_iflag;
995 tp->t_oflag = t->c_oflag;
996 /*
997 * Make the EXTPROC bit read only.
998 */
999 if (ISSET(tp->t_lflag, EXTPROC))
1000 SET(t->c_lflag, EXTPROC);
1001 else
1002 CLR(t->c_lflag, EXTPROC);
1003 tp->t_lflag = t->c_lflag | ISSET(tp->t_lflag, PENDIN);
1004 memcpy(tp->t_cc, t->c_cc, sizeof(t->c_cc));
1005 TTY_UNLOCK(tp);
1006 splx(s);
1007 break;
1008 }
1009 case TIOCSETD: { /* set line discipline */
1010 int t = *(int *)data;
1011
1012 if (t < 0)
1013 return (EINVAL);
1014 if (t >= nlinesw)
1015 return (ENXIO);
1016 lp = linesw[t];
1017 goto setldisc;
1018 }
1019 case TIOCSLINED: { /* set line discipline */
1020 char *name = (char *)data;
1021 dev_t device;
1022
1023 /* Null terminate to prevent buffer overflow */
1024 name[TTLINEDNAMELEN - 1] = '\0';
1025 lp = ttyldisc_lookup(name);
1026
1027 setldisc:
1028 if (lp == NULL)
1029 return (ENXIO);
1030
1031 if (lp != tp->t_linesw) {
1032 device = tp->t_dev;
1033 s = spltty();
1034 (*tp->t_linesw->l_close)(tp, flag);
1035 error = (*lp->l_open)(device, tp);
1036 if (error) {
1037 (void)(*tp->t_linesw->l_open)(device, tp);
1038 splx(s);
1039 return (error);
1040 }
1041 tp->t_linesw = lp;
1042 splx(s);
1043 }
1044 break;
1045 }
1046 case TIOCSTART: /* start output, like ^Q */
1047 s = spltty();
1048 TTY_LOCK(tp);
1049 if (ISSET(tp->t_state, TS_TTSTOP) ||
1050 ISSET(tp->t_lflag, FLUSHO)) {
1051 CLR(tp->t_lflag, FLUSHO);
1052 CLR(tp->t_state, TS_TTSTOP);
1053 ttstart(tp);
1054 }
1055 TTY_UNLOCK(tp);
1056 splx(s);
1057 break;
1058 case TIOCSTI: /* simulate terminal input */
1059 if (p->p_ucred->cr_uid && (flag & FREAD) == 0)
1060 return (EPERM);
1061 if (p->p_ucred->cr_uid && !isctty(p, tp))
1062 return (EACCES);
1063 (*tp->t_linesw->l_rint)(*(u_char *)data, tp);
1064 break;
1065 case TIOCSTOP: /* stop output, like ^S */
1066 {
1067 const struct cdevsw *cdev;
1068 s = spltty();
1069 TTY_LOCK(tp);
1070 if (!ISSET(tp->t_state, TS_TTSTOP)) {
1071 SET(tp->t_state, TS_TTSTOP);
1072 cdev = cdevsw_lookup(tp->t_dev);
1073 if (cdev != NULL)
1074 (*cdev->d_stop)(tp, 0);
1075 }
1076 TTY_UNLOCK(tp);
1077 splx(s);
1078 break;
1079 }
1080 case TIOCSCTTY: /* become controlling tty */
1081 /* Session ctty vnode pointer set in vnode layer. */
1082 if (!SESS_LEADER(p) ||
1083 ((p->p_session->s_ttyvp || tp->t_session) &&
1084 (tp->t_session != p->p_session)))
1085 return (EPERM);
1086
1087 if (tp->t_session)
1088 SESSRELE(tp->t_session);
1089
1090 SESSHOLD(p->p_session);
1091 tp->t_session = p->p_session;
1092 tp->t_pgrp = p->p_pgrp;
1093 p->p_session->s_ttyp = tp;
1094 p->p_flag |= P_CONTROLT;
1095 break;
1096 case FIOSETOWN: { /* set pgrp of tty */
1097 pid_t pgid = *(int *)data;
1098 struct pgrp *pgrp;
1099
1100 if (!isctty(p, tp))
1101 return (ENOTTY);
1102
1103 if (pgid < 0)
1104 pgrp = pgfind(-pgid);
1105 else {
1106 struct proc *p1 = pfind(pgid);
1107 if (!p1)
1108 return (ESRCH);
1109 pgrp = p1->p_pgrp;
1110 }
1111
1112 if (pgrp == NULL)
1113 return (EINVAL);
1114 else if (pgrp->pg_session != p->p_session)
1115 return (EPERM);
1116 tp->t_pgrp = pgrp;
1117 break;
1118 }
1119 case TIOCSPGRP: { /* set pgrp of tty */
1120 struct pgrp *pgrp = pgfind(*(int *)data);
1121
1122 if (!isctty(p, tp))
1123 return (ENOTTY);
1124 else if (pgrp == NULL)
1125 return (EINVAL);
1126 else if (pgrp->pg_session != p->p_session)
1127 return (EPERM);
1128 tp->t_pgrp = pgrp;
1129 break;
1130 }
1131 case TIOCSTAT: /* get load avg stats */
1132 TTY_LOCK(tp);
1133 ttyinfo(tp);
1134 TTY_UNLOCK(tp);
1135 break;
1136 case TIOCSWINSZ: /* set window size */
1137 if (memcmp((caddr_t)&tp->t_winsize, data,
1138 sizeof(struct winsize))) {
1139 tp->t_winsize = *(struct winsize *)data;
1140 pgsignal(tp->t_pgrp, SIGWINCH, 1);
1141 }
1142 break;
1143 default:
1144 #ifdef COMPAT_OLDTTY
1145 return (ttcompat(tp, cmd, data, flag, p));
1146 #else
1147 return (EPASSTHROUGH);
1148 #endif
1149 }
1150 return (0);
1151 }
1152
1153 int
1154 ttpoll(struct tty *tp, int events, struct proc *p)
1155 {
1156 int revents, s;
1157
1158 revents = 0;
1159 s = spltty();
1160 TTY_LOCK(tp);
1161 if (events & (POLLIN | POLLRDNORM))
1162 if (ttnread(tp) > 0)
1163 revents |= events & (POLLIN | POLLRDNORM);
1164
1165 if (events & (POLLOUT | POLLWRNORM))
1166 if (tp->t_outq.c_cc <= tp->t_lowat)
1167 revents |= events & (POLLOUT | POLLWRNORM);
1168
1169 if (events & POLLHUP)
1170 if (!CONNECTED(tp))
1171 revents |= POLLHUP;
1172
1173 if (revents == 0) {
1174 if (events & (POLLIN | POLLHUP | POLLRDNORM))
1175 selrecord(p, &tp->t_rsel);
1176
1177 if (events & (POLLOUT | POLLWRNORM))
1178 selrecord(p, &tp->t_wsel);
1179 }
1180
1181 TTY_UNLOCK(tp);
1182 splx(s);
1183 return (revents);
1184 }
1185
1186 static void
1187 filt_ttyrdetach(struct knote *kn)
1188 {
1189 struct tty *tp;
1190 int s;
1191
1192 tp = kn->kn_hook;
1193 s = spltty();
1194 SLIST_REMOVE(&tp->t_rsel.sel_klist, kn, knote, kn_selnext);
1195 splx(s);
1196 }
1197
1198 static int
1199 filt_ttyread(struct knote *kn, long hint)
1200 {
1201 struct tty *tp;
1202 int s;
1203
1204 tp = kn->kn_hook;
1205 s = spltty();
1206 TTY_LOCK(tp);
1207 kn->kn_data = ttnread(tp);
1208 TTY_UNLOCK(tp);
1209 splx(s);
1210 return (kn->kn_data > 0);
1211 }
1212
1213 static void
1214 filt_ttywdetach(struct knote *kn)
1215 {
1216 struct tty *tp;
1217 int s;
1218
1219 tp = kn->kn_hook;
1220 s = spltty();
1221 TTY_LOCK(tp);
1222 SLIST_REMOVE(&tp->t_wsel.sel_klist, kn, knote, kn_selnext);
1223 TTY_UNLOCK(tp);
1224 splx(s);
1225 }
1226
1227 static int
1228 filt_ttywrite(struct knote *kn, long hint)
1229 {
1230 struct tty *tp;
1231 int canwrite, s;
1232
1233 tp = kn->kn_hook;
1234 s = spltty();
1235 TTY_LOCK(tp);
1236 kn->kn_data = tp->t_outq.c_cn - tp->t_outq.c_cc;
1237 canwrite = (tp->t_outq.c_cc <= tp->t_lowat) && CONNECTED(tp);
1238 TTY_UNLOCK(tp);
1239 splx(s);
1240 return (canwrite);
1241 }
1242
1243 static const struct filterops ttyread_filtops =
1244 { 1, NULL, filt_ttyrdetach, filt_ttyread };
1245 static const struct filterops ttywrite_filtops =
1246 { 1, NULL, filt_ttywdetach, filt_ttywrite };
1247
1248 int
1249 ttykqfilter(dev_t dev, struct knote *kn)
1250 {
1251 struct tty *tp;
1252 struct klist *klist;
1253 int s;
1254 const struct cdevsw *cdev;
1255
1256 if (((cdev = cdevsw_lookup(dev)) == NULL) ||
1257 (cdev->d_tty == NULL) ||
1258 ((tp = (*cdev->d_tty)(dev)) == NULL))
1259 return (ENXIO);
1260
1261 switch (kn->kn_filter) {
1262 case EVFILT_READ:
1263 klist = &tp->t_rsel.sel_klist;
1264 kn->kn_fop = &ttyread_filtops;
1265 break;
1266 case EVFILT_WRITE:
1267 klist = &tp->t_wsel.sel_klist;
1268 kn->kn_fop = &ttywrite_filtops;
1269 break;
1270 default:
1271 return (1);
1272 }
1273
1274 kn->kn_hook = tp;
1275
1276 s = spltty();
1277 TTY_LOCK(tp);
1278 SLIST_INSERT_HEAD(klist, kn, kn_selnext);
1279 TTY_UNLOCK(tp);
1280 splx(s);
1281
1282 return (0);
1283 }
1284
1285 /*
1286 * Find the number of chars ready to be read from this tty.
1287 * Call at spltty() and with the tty slock held.
1288 */
1289 static int
1290 ttnread(struct tty *tp)
1291 {
1292 int nread;
1293
1294 if (ISSET(tp->t_lflag, PENDIN))
1295 ttypend(tp);
1296 nread = tp->t_canq.c_cc;
1297 if (!ISSET(tp->t_lflag, ICANON)) {
1298 nread += tp->t_rawq.c_cc;
1299 if (nread < tp->t_cc[VMIN] && !tp->t_cc[VTIME])
1300 nread = 0;
1301 }
1302 return (nread);
1303 }
1304
1305 /*
1306 * Wait for output to drain.
1307 */
1308 int
1309 ttywait(struct tty *tp)
1310 {
1311 int error, s;
1312
1313 error = 0;
1314 s = spltty();
1315 TTY_LOCK(tp);
1316 while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1317 CONNECTED(tp) && tp->t_oproc) {
1318 (*tp->t_oproc)(tp);
1319 SET(tp->t_state, TS_ASLEEP);
1320 error = ttysleep(tp, &tp->t_outq, TTOPRI | PCATCH, ttyout, 0);
1321 if (error)
1322 break;
1323 }
1324 TTY_UNLOCK(tp);
1325 splx(s);
1326 return (error);
1327 }
1328
1329 /*
1330 * Flush if successfully wait.
1331 */
1332 int
1333 ttywflush(struct tty *tp)
1334 {
1335 int error;
1336 int s;
1337
1338 if ((error = ttywait(tp)) == 0) {
1339 s = spltty();
1340 TTY_LOCK(tp);
1341 ttyflush(tp, FREAD);
1342 TTY_UNLOCK(tp);
1343 splx(s);
1344 }
1345 return (error);
1346 }
1347
1348 /*
1349 * Flush tty read and/or write queues, notifying anyone waiting.
1350 * Call at spltty() and with the tty slock held.
1351 */
1352 void
1353 ttyflush(struct tty *tp, int rw)
1354 {
1355 const struct cdevsw *cdev;
1356
1357 if (rw & FREAD) {
1358 FLUSHQ(&tp->t_canq);
1359 FLUSHQ(&tp->t_rawq);
1360 tp->t_rocount = 0;
1361 tp->t_rocol = 0;
1362 CLR(tp->t_state, TS_LOCAL);
1363 ttwakeup(tp);
1364 }
1365 if (rw & FWRITE) {
1366 CLR(tp->t_state, TS_TTSTOP);
1367 cdev = cdevsw_lookup(tp->t_dev);
1368 if (cdev != NULL)
1369 (*cdev->d_stop)(tp, rw);
1370 FLUSHQ(&tp->t_outq);
1371 wakeup((caddr_t)&tp->t_outq);
1372 selnotify(&tp->t_wsel, 0);
1373 }
1374 }
1375
1376 /*
1377 * Copy in the default termios characters.
1378 */
1379 void
1380 ttychars(struct tty *tp)
1381 {
1382
1383 memcpy(tp->t_cc, ttydefchars, sizeof(ttydefchars));
1384 }
1385
1386 /*
1387 * Send stop character on input overflow.
1388 * Call at spltty() and with the tty slock held.
1389 */
1390 static void
1391 ttyblock(struct tty *tp)
1392 {
1393 int total;
1394
1395 total = tp->t_rawq.c_cc + tp->t_canq.c_cc;
1396 if (tp->t_rawq.c_cc > TTYHOG) {
1397 ttyflush(tp, FREAD | FWRITE);
1398 CLR(tp->t_state, TS_TBLOCK);
1399 }
1400 /*
1401 * Block further input iff: current input > threshold
1402 * AND input is available to user program.
1403 */
1404 if (total >= TTYHOG / 2 &&
1405 !ISSET(tp->t_state, TS_TBLOCK) &&
1406 (!ISSET(tp->t_lflag, ICANON) || tp->t_canq.c_cc > 0)) {
1407 if (ISSET(tp->t_iflag, IXOFF) &&
1408 tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
1409 putc(tp->t_cc[VSTOP], &tp->t_outq) == 0) {
1410 SET(tp->t_state, TS_TBLOCK);
1411 ttstart(tp);
1412 }
1413 /* Try to block remote output via hardware flow control. */
1414 if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
1415 (*tp->t_hwiflow)(tp, 1) != 0)
1416 SET(tp->t_state, TS_TBLOCK);
1417 }
1418 }
1419
1420 /*
1421 * Delayed line discipline output
1422 */
1423 void
1424 ttrstrt(void *tp_arg)
1425 {
1426 struct tty *tp;
1427 int s;
1428
1429 #ifdef DIAGNOSTIC
1430 if (tp_arg == NULL)
1431 panic("ttrstrt");
1432 #endif
1433 tp = tp_arg;
1434 s = spltty();
1435 TTY_LOCK(tp);
1436
1437 CLR(tp->t_state, TS_TIMEOUT);
1438 ttstart(tp); /* XXX - Shouldn't this be tp->l_start(tp)? */
1439
1440 TTY_UNLOCK(tp);
1441 splx(s);
1442 }
1443
1444 /*
1445 * start a line discipline
1446 * Always call at spltty() and with tty slock held?
1447 */
1448 int
1449 ttstart(struct tty *tp)
1450 {
1451
1452 if (tp->t_oproc != NULL) /* XXX: Kludge for pty. */
1453 (*tp->t_oproc)(tp);
1454 return (0);
1455 }
1456
1457 /*
1458 * "close" a line discipline
1459 */
1460 int
1461 ttylclose(struct tty *tp, int flag)
1462 {
1463 int s;
1464
1465 if (flag & FNONBLOCK) {
1466 s = spltty();
1467 TTY_LOCK(tp);
1468 ttyflush(tp, FREAD | FWRITE);
1469 TTY_UNLOCK(tp);
1470 splx(s);
1471 } else
1472 ttywflush(tp);
1473 return (0);
1474 }
1475
1476 /*
1477 * Handle modem control transition on a tty.
1478 * Flag indicates new state of carrier.
1479 * Returns 0 if the line should be turned off, otherwise 1.
1480 *
1481 * Must be called at spltty().
1482 */
1483 int
1484 ttymodem(struct tty *tp, int flag)
1485 {
1486
1487 TTY_LOCK(tp);
1488 if (flag == 0) {
1489 if (ISSET(tp->t_state, TS_CARR_ON)) {
1490 /*
1491 * Lost carrier.
1492 */
1493 CLR(tp->t_state, TS_CARR_ON);
1494 if (ISSET(tp->t_state, TS_ISOPEN) && !CONNECTED(tp)) {
1495 if (tp->t_session && tp->t_session->s_leader)
1496 psignal(tp->t_session->s_leader,
1497 SIGHUP);
1498 ttyflush(tp, FREAD | FWRITE);
1499 TTY_UNLOCK(tp);
1500 return (0);
1501 }
1502 }
1503 } else {
1504 if (!ISSET(tp->t_state, TS_CARR_ON)) {
1505 /*
1506 * Carrier now on.
1507 */
1508 SET(tp->t_state, TS_CARR_ON);
1509 ttwakeup(tp);
1510 }
1511 }
1512 TTY_UNLOCK(tp);
1513 return (1);
1514 }
1515
1516 /*
1517 * Default modem control routine (for other line disciplines).
1518 * Return argument flag, to turn off device on carrier drop.
1519 *
1520 * Must be called at spltty().
1521 */
1522 int
1523 nullmodem(struct tty *tp, int flag)
1524 {
1525
1526 TTY_LOCK(tp);
1527 if (flag)
1528 SET(tp->t_state, TS_CARR_ON);
1529 else {
1530 CLR(tp->t_state, TS_CARR_ON);
1531 if (!CONNECTED(tp)) {
1532 if (tp->t_session && tp->t_session->s_leader)
1533 psignal(tp->t_session->s_leader, SIGHUP);
1534 TTY_UNLOCK(tp);
1535 return (0);
1536 }
1537 }
1538 TTY_UNLOCK(tp);
1539 return (1);
1540 }
1541
1542 /*
1543 * Reinput pending characters after state switch.
1544 * Call at spltty() and with the tty slock held.
1545 */
1546 void
1547 ttypend(struct tty *tp)
1548 {
1549 struct clist tq;
1550 int c;
1551
1552 CLR(tp->t_lflag, PENDIN);
1553 SET(tp->t_state, TS_TYPEN);
1554 tq = tp->t_rawq;
1555 tp->t_rawq.c_cc = 0;
1556 tp->t_rawq.c_cf = tp->t_rawq.c_cl = 0;
1557 while ((c = getc(&tq)) >= 0)
1558 ttyinput_wlock(c, tp);
1559 CLR(tp->t_state, TS_TYPEN);
1560 }
1561
1562 /*
1563 * Process a read call on a tty device.
1564 */
1565 int
1566 ttread(struct tty *tp, struct uio *uio, int flag)
1567 {
1568 struct clist *qp;
1569 u_char *cc;
1570 struct proc *p;
1571 int c, s, first, error, has_stime, last_cc;
1572 long lflag, slp;
1573 struct timeval stime;
1574
1575 cc = tp->t_cc;
1576 p = curproc;
1577 error = 0;
1578 has_stime = 0;
1579 last_cc = 0;
1580 slp = 0;
1581
1582 loop:
1583 s = spltty();
1584 TTY_LOCK(tp);
1585 lflag = tp->t_lflag;
1586 /*
1587 * take pending input first
1588 */
1589 if (ISSET(lflag, PENDIN))
1590 ttypend(tp);
1591
1592 /*
1593 * Hang process if it's in the background.
1594 */
1595 if (isbackground(p, tp)) {
1596 if (sigismember(&p->p_sigctx.ps_sigignore, SIGTTIN) ||
1597 sigismember(&p->p_sigctx.ps_sigmask, SIGTTIN) ||
1598 p->p_flag & P_PPWAIT || p->p_pgrp->pg_jobc == 0) {
1599 TTY_UNLOCK(tp);
1600 splx(s);
1601 return (EIO);
1602 }
1603 pgsignal(p->p_pgrp, SIGTTIN, 1);
1604 error = ttysleep(tp, &lbolt, TTIPRI | PCATCH | PNORELOCK, ttybg, 0);
1605 splx(s);
1606 if (error)
1607 return (error);
1608 goto loop;
1609 }
1610
1611 if (!ISSET(lflag, ICANON)) {
1612 int m = cc[VMIN];
1613 long t = cc[VTIME];
1614
1615 qp = &tp->t_rawq;
1616 /*
1617 * Check each of the four combinations.
1618 * (m > 0 && t == 0) is the normal read case.
1619 * It should be fairly efficient, so we check that and its
1620 * companion case (m == 0 && t == 0) first.
1621 * For the other two cases, we compute the target sleep time
1622 * into slp.
1623 */
1624 if (t == 0) {
1625 if (qp->c_cc < m)
1626 goto sleep;
1627 goto read;
1628 }
1629 t *= hz; /* time in deca-ticks */
1630 /*
1631 * Time difference in deca-ticks, split division to avoid numeric overflow.
1632 * Ok for hz < ~200kHz
1633 */
1634 #define diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 10 * hz + \
1635 ((t1).tv_usec - (t2).tv_usec) / 100 * hz / 1000)
1636 if (m > 0) {
1637 if (qp->c_cc <= 0)
1638 goto sleep;
1639 if (qp->c_cc >= m)
1640 goto read;
1641 if (!has_stime) {
1642 /* first character, start timer */
1643 has_stime = 1;
1644 stime = time;
1645 slp = t;
1646 } else if (qp->c_cc > last_cc) {
1647 /* got a character, restart timer */
1648 stime = time;
1649 slp = t;
1650 } else {
1651 /* nothing, check expiration */
1652 slp = t - diff(time, stime);
1653 }
1654 } else { /* m == 0 */
1655 if (qp->c_cc > 0)
1656 goto read;
1657 if (!has_stime) {
1658 has_stime = 1;
1659 stime = time;
1660 slp = t;
1661 } else
1662 slp = t - diff(time, stime);
1663 }
1664 last_cc = qp->c_cc;
1665 #undef diff
1666 if (slp > 0) {
1667 /*
1668 * Convert deca-ticks back to ticks.
1669 * Rounding down may make us wake up just short
1670 * of the target, so we round up.
1671 * Maybe we should do 'slp/10 + 1' because the
1672 * first tick maybe almost immediate.
1673 * However it is more useful for a program that sets
1674 * VTIME=10 to wakeup every second not every 1.01
1675 * seconds (if hz=100).
1676 */
1677 slp = (slp + 9)/ 10;
1678 goto sleep;
1679 }
1680 } else if ((qp = &tp->t_canq)->c_cc <= 0) {
1681 int carrier;
1682
1683 sleep:
1684 /*
1685 * If there is no input, sleep on rawq
1686 * awaiting hardware receipt and notification.
1687 * If we have data, we don't need to check for carrier.
1688 */
1689 carrier = CONNECTED(tp);
1690 if (!carrier && ISSET(tp->t_state, TS_ISOPEN)) {
1691 TTY_UNLOCK(tp);
1692 splx(s);
1693 return (0); /* EOF */
1694 }
1695 if (flag & IO_NDELAY) {
1696 TTY_UNLOCK(tp);
1697 splx(s);
1698 return (EWOULDBLOCK);
1699 }
1700 error = ttysleep(tp, &tp->t_rawq, TTIPRI | PCATCH | PNORELOCK,
1701 carrier ? ttyin : ttopen, slp);
1702 splx(s);
1703 /* VMIN == 0: any quantity read satisfies */
1704 if (cc[VMIN] == 0 && error == EWOULDBLOCK)
1705 return (0);
1706 if (error && error != EWOULDBLOCK)
1707 return (error);
1708 goto loop;
1709 }
1710 read:
1711 TTY_UNLOCK(tp);
1712 splx(s);
1713
1714 /*
1715 * Input present, check for input mapping and processing.
1716 */
1717 first = 1;
1718 while ((c = getc(qp)) >= 0) {
1719 /*
1720 * delayed suspend (^Y)
1721 */
1722 if (CCEQ(cc[VDSUSP], c) &&
1723 ISSET(lflag, IEXTEN|ISIG) == (IEXTEN|ISIG)) {
1724 pgsignal(tp->t_pgrp, SIGTSTP, 1);
1725 if (first) {
1726 TTY_LOCK(tp);
1727 error = ttysleep(tp, &lbolt,
1728 TTIPRI | PCATCH | PNORELOCK, ttybg, 0);
1729 if (error)
1730 break;
1731 goto loop;
1732 }
1733 break;
1734 }
1735 /*
1736 * Interpret EOF only in canonical mode.
1737 */
1738 if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
1739 break;
1740 /*
1741 * Give user character.
1742 */
1743 error = ureadc(c, uio);
1744 if (error)
1745 break;
1746 if (uio->uio_resid == 0)
1747 break;
1748 /*
1749 * In canonical mode check for a "break character"
1750 * marking the end of a "line of input".
1751 */
1752 if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
1753 break;
1754 first = 0;
1755 }
1756 /*
1757 * Look to unblock output now that (presumably)
1758 * the input queue has gone down.
1759 */
1760 s = spltty();
1761 TTY_LOCK(tp);
1762 if (ISSET(tp->t_state, TS_TBLOCK) && tp->t_rawq.c_cc < TTYHOG / 5) {
1763 if (ISSET(tp->t_iflag, IXOFF) &&
1764 cc[VSTART] != _POSIX_VDISABLE &&
1765 putc(cc[VSTART], &tp->t_outq) == 0) {
1766 CLR(tp->t_state, TS_TBLOCK);
1767 ttstart(tp);
1768 }
1769 /* Try to unblock remote output via hardware flow control. */
1770 if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
1771 (*tp->t_hwiflow)(tp, 0) != 0)
1772 CLR(tp->t_state, TS_TBLOCK);
1773 }
1774 TTY_UNLOCK(tp);
1775 splx(s);
1776 return (error);
1777 }
1778
1779 /*
1780 * Check the output queue on tp for space for a kernel message (from uprintf
1781 * or tprintf). Allow some space over the normal hiwater mark so we don't
1782 * lose messages due to normal flow control, but don't let the tty run amok.
1783 * Sleeps here are not interruptible, but we return prematurely if new signals
1784 * arrive.
1785 * Call with tty slock held.
1786 */
1787 static int
1788 ttycheckoutq_wlock(struct tty *tp, int wait)
1789 {
1790 int hiwat, s, error;
1791
1792 hiwat = tp->t_hiwat;
1793 s = spltty();
1794 if (tp->t_outq.c_cc > hiwat + 200)
1795 while (tp->t_outq.c_cc > hiwat) {
1796 ttstart(tp);
1797 if (wait == 0) {
1798 splx(s);
1799 return (0);
1800 }
1801 SET(tp->t_state, TS_ASLEEP);
1802 error = ltsleep(&tp->t_outq, (PZERO - 1) | PCATCH,
1803 "ttckoutq", hz, &tp->t_slock);
1804 if (error == EINTR)
1805 wait = 0;
1806 }
1807
1808 splx(s);
1809 return (1);
1810 }
1811
1812 int
1813 ttycheckoutq(struct tty *tp, int wait)
1814 {
1815 int r, s;
1816
1817 s = spltty();
1818 TTY_LOCK(tp);
1819 r = ttycheckoutq_wlock(tp, wait);
1820 TTY_UNLOCK(tp);
1821 splx(s);
1822 return (r);
1823 }
1824
1825 /*
1826 * Process a write call on a tty device.
1827 */
1828 int
1829 ttwrite(struct tty *tp, struct uio *uio, int flag)
1830 {
1831 u_char *cp;
1832 struct proc *p;
1833 int cc, ce, i, hiwat, error, s;
1834 size_t cnt;
1835 u_char obuf[OBUFSIZ];
1836
1837 cp = NULL;
1838 hiwat = tp->t_hiwat;
1839 cnt = uio->uio_resid;
1840 error = 0;
1841 cc = 0;
1842 loop:
1843 s = spltty();
1844 TTY_LOCK(tp);
1845 if (!CONNECTED(tp)) {
1846 if (ISSET(tp->t_state, TS_ISOPEN)) {
1847 TTY_UNLOCK(tp);
1848 splx(s);
1849 return (EIO);
1850 } else if (flag & IO_NDELAY) {
1851 TTY_UNLOCK(tp);
1852 splx(s);
1853 error = EWOULDBLOCK;
1854 goto out;
1855 } else {
1856 /* Sleep awaiting carrier. */
1857 error = ttysleep(tp,
1858 &tp->t_rawq, TTIPRI | PCATCH | PNORELOCK, ttopen, 0);
1859 splx(s);
1860 if (error)
1861 goto out;
1862 goto loop;
1863 }
1864 }
1865 TTY_UNLOCK(tp);
1866 splx(s);
1867 /*
1868 * Hang the process if it's in the background.
1869 */
1870 p = curproc;
1871 if (isbackground(p, tp) &&
1872 ISSET(tp->t_lflag, TOSTOP) && (p->p_flag & P_PPWAIT) == 0 &&
1873 !sigismember(&p->p_sigctx.ps_sigignore, SIGTTOU) &&
1874 !sigismember(&p->p_sigctx.ps_sigmask, SIGTTOU)) {
1875 if (p->p_pgrp->pg_jobc == 0) {
1876 error = EIO;
1877 goto out;
1878 }
1879 pgsignal(p->p_pgrp, SIGTTOU, 1);
1880 s = spltty();
1881 TTY_LOCK(tp);
1882 error = ttysleep(tp, &lbolt, TTIPRI | PCATCH | PNORELOCK, ttybg, 0);
1883 splx(s);
1884 if (error)
1885 goto out;
1886 goto loop;
1887 }
1888 /*
1889 * Process the user's data in at most OBUFSIZ chunks. Perform any
1890 * output translation. Keep track of high water mark, sleep on
1891 * overflow awaiting device aid in acquiring new space.
1892 */
1893 while (uio->uio_resid > 0 || cc > 0) {
1894 if (ISSET(tp->t_lflag, FLUSHO)) {
1895 TTY_UNLOCK(tp);
1896 uio->uio_resid = 0;
1897 return (0);
1898 }
1899 if (tp->t_outq.c_cc > hiwat)
1900 goto ovhiwat;
1901 /*
1902 * Grab a hunk of data from the user, unless we have some
1903 * leftover from last time.
1904 */
1905 if (cc == 0) {
1906 cc = min(uio->uio_resid, OBUFSIZ);
1907 cp = obuf;
1908 error = uiomove(cp, cc, uio);
1909 if (error) {
1910 cc = 0;
1911 goto out;
1912 }
1913 }
1914 /*
1915 * If nothing fancy need be done, grab those characters we
1916 * can handle without any of ttyoutput's processing and
1917 * just transfer them to the output q. For those chars
1918 * which require special processing (as indicated by the
1919 * bits in char_type), call ttyoutput. After processing
1920 * a hunk of data, look for FLUSHO so ^O's will take effect
1921 * immediately.
1922 */
1923 s = spltty();
1924 TTY_LOCK(tp);
1925 while (cc > 0) {
1926 if (!ISSET(tp->t_oflag, OPOST))
1927 ce = cc;
1928 else {
1929 ce = cc - scanc((u_int)cc, cp, char_type,
1930 CCLASSMASK);
1931 /*
1932 * If ce is zero, then we're processing
1933 * a special character through ttyoutput.
1934 */
1935 if (ce == 0) {
1936 tp->t_rocount = 0;
1937 if (ttyoutput(*cp, tp) >= 0) {
1938 /* out of space */
1939 TTY_UNLOCK(tp);
1940 splx(s);
1941 goto overfull;
1942 }
1943 cp++;
1944 cc--;
1945 if (ISSET(tp->t_lflag, FLUSHO) ||
1946 tp->t_outq.c_cc > hiwat) {
1947 TTY_UNLOCK(tp);
1948 splx(s);
1949 goto ovhiwat;
1950 }
1951 continue;
1952 }
1953 }
1954 /*
1955 * A bunch of normal characters have been found.
1956 * Transfer them en masse to the output queue and
1957 * continue processing at the top of the loop.
1958 * If there are any further characters in this
1959 * <= OBUFSIZ chunk, the first should be a character
1960 * requiring special handling by ttyoutput.
1961 */
1962 tp->t_rocount = 0;
1963 i = b_to_q(cp, ce, &tp->t_outq);
1964 ce -= i;
1965 tp->t_column += ce;
1966 cp += ce, cc -= ce, tk_nout += ce;
1967 tp->t_outcc += ce;
1968 if (i > 0) {
1969 /* out of space */
1970 TTY_UNLOCK(tp);
1971 splx(s);
1972 goto overfull;
1973 }
1974 if (ISSET(tp->t_lflag, FLUSHO) ||
1975 tp->t_outq.c_cc > hiwat)
1976 break;
1977 }
1978 TTY_UNLOCK(tp);
1979 splx(s);
1980 ttstart(tp);
1981 }
1982
1983 out:
1984 /*
1985 * If cc is nonzero, we leave the uio structure inconsistent, as the
1986 * offset and iov pointers have moved forward, but it doesn't matter
1987 * (the call will either return short or restart with a new uio).
1988 */
1989 uio->uio_resid += cc;
1990 return (error);
1991
1992 overfull:
1993 /*
1994 * Since we are using ring buffers, if we can't insert any more into
1995 * the output queue, we can assume the ring is full and that someone
1996 * forgot to set the high water mark correctly. We set it and then
1997 * proceed as normal.
1998 */
1999 hiwat = tp->t_outq.c_cc - 1;
2000
2001 ovhiwat:
2002 ttstart(tp);
2003 s = spltty();
2004 TTY_LOCK(tp);
2005 /*
2006 * This can only occur if FLUSHO is set in t_lflag,
2007 * or if ttstart/oproc is synchronous (or very fast).
2008 */
2009 if (tp->t_outq.c_cc <= hiwat) {
2010 TTY_UNLOCK(tp);
2011 splx(s);
2012 goto loop;
2013 }
2014 if (flag & IO_NDELAY) {
2015 TTY_UNLOCK(tp);
2016 splx(s);
2017 error = (uio->uio_resid == cnt) ? EWOULDBLOCK : 0;
2018 goto out;
2019 }
2020 SET(tp->t_state, TS_ASLEEP);
2021 error = ttysleep(tp, &tp->t_outq, TTOPRI | PCATCH | PNORELOCK, ttyout, 0);
2022 splx(s);
2023 if (error)
2024 goto out;
2025 goto loop;
2026 }
2027
2028 /*
2029 * Rubout one character from the rawq of tp
2030 * as cleanly as possible.
2031 * Called with tty slock held.
2032 */
2033 void
2034 ttyrub(int c, struct tty *tp)
2035 {
2036 u_char *cp;
2037 int savecol, tabc, s;
2038
2039 if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
2040 return;
2041 CLR(tp->t_lflag, FLUSHO);
2042 if (ISSET(tp->t_lflag, ECHOE)) {
2043 if (tp->t_rocount == 0) {
2044 /*
2045 * Screwed by ttwrite; retype
2046 */
2047 ttyretype(tp);
2048 return;
2049 }
2050 if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
2051 ttyrubo(tp, 2);
2052 else {
2053 CLR(c, ~TTY_CHARMASK);
2054 switch (CCLASS(c)) {
2055 case ORDINARY:
2056 ttyrubo(tp, 1);
2057 break;
2058 case BACKSPACE:
2059 case CONTROL:
2060 case NEWLINE:
2061 case RETURN:
2062 case VTAB:
2063 if (ISSET(tp->t_lflag, ECHOCTL))
2064 ttyrubo(tp, 2);
2065 break;
2066 case TAB:
2067 if (tp->t_rocount < tp->t_rawq.c_cc) {
2068 ttyretype(tp);
2069 return;
2070 }
2071 s = spltty();
2072 savecol = tp->t_column;
2073 SET(tp->t_state, TS_CNTTB);
2074 SET(tp->t_lflag, FLUSHO);
2075 tp->t_column = tp->t_rocol;
2076 for (cp = firstc(&tp->t_rawq, &tabc); cp;
2077 cp = nextc(&tp->t_rawq, cp, &tabc))
2078 ttyecho(tabc, tp);
2079 CLR(tp->t_lflag, FLUSHO);
2080 CLR(tp->t_state, TS_CNTTB);
2081 splx(s);
2082
2083 /* savecol will now be length of the tab. */
2084 savecol -= tp->t_column;
2085 tp->t_column += savecol;
2086 if (savecol > 8)
2087 savecol = 8; /* overflow screw */
2088 while (--savecol >= 0)
2089 (void)ttyoutput('\b', tp);
2090 break;
2091 default: /* XXX */
2092 #define PANICSTR "ttyrub: would panic c = %d, val = %d\n"
2093 (void)printf(PANICSTR, c, CCLASS(c));
2094 #ifdef notdef
2095 panic(PANICSTR, c, CCLASS(c));
2096 #endif
2097 }
2098 }
2099 } else if (ISSET(tp->t_lflag, ECHOPRT)) {
2100 if (!ISSET(tp->t_state, TS_ERASE)) {
2101 SET(tp->t_state, TS_ERASE);
2102 (void)ttyoutput('\\', tp);
2103 }
2104 ttyecho(c, tp);
2105 } else
2106 ttyecho(tp->t_cc[VERASE], tp);
2107 --tp->t_rocount;
2108 }
2109
2110 /*
2111 * Back over cnt characters, erasing them.
2112 * Called with tty slock held.
2113 */
2114 static void
2115 ttyrubo(struct tty *tp, int cnt)
2116 {
2117
2118 while (cnt-- > 0) {
2119 (void)ttyoutput('\b', tp);
2120 (void)ttyoutput(' ', tp);
2121 (void)ttyoutput('\b', tp);
2122 }
2123 }
2124
2125 /*
2126 * ttyretype --
2127 * Reprint the rawq line. Note, it is assumed that c_cc has already
2128 * been checked.
2129 *
2130 * Called with tty slock held.
2131 */
2132 void
2133 ttyretype(struct tty *tp)
2134 {
2135 u_char *cp;
2136 int s, c;
2137
2138 /* Echo the reprint character. */
2139 if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
2140 ttyecho(tp->t_cc[VREPRINT], tp);
2141
2142 (void)ttyoutput('\n', tp);
2143
2144 s = spltty();
2145 for (cp = firstc(&tp->t_canq, &c); cp; cp = nextc(&tp->t_canq, cp, &c))
2146 ttyecho(c, tp);
2147 for (cp = firstc(&tp->t_rawq, &c); cp; cp = nextc(&tp->t_rawq, cp, &c))
2148 ttyecho(c, tp);
2149 CLR(tp->t_state, TS_ERASE);
2150 splx(s);
2151
2152 tp->t_rocount = tp->t_rawq.c_cc;
2153 tp->t_rocol = 0;
2154 }
2155
2156 /*
2157 * Echo a typed character to the terminal.
2158 * Called with tty slock held.
2159 */
2160 static void
2161 ttyecho(int c, struct tty *tp)
2162 {
2163
2164 if (!ISSET(tp->t_state, TS_CNTTB))
2165 CLR(tp->t_lflag, FLUSHO);
2166 if ((!ISSET(tp->t_lflag, ECHO) &&
2167 (!ISSET(tp->t_lflag, ECHONL) || c != '\n')) ||
2168 ISSET(tp->t_lflag, EXTPROC))
2169 return;
2170 if (((ISSET(tp->t_lflag, ECHOCTL) &&
2171 (ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n')) ||
2172 ISSET(c, TTY_CHARMASK) == 0177)) {
2173 (void)ttyoutput('^', tp);
2174 CLR(c, ~TTY_CHARMASK);
2175 if (c == 0177)
2176 c = '?';
2177 else
2178 c += 'A' - 1;
2179 }
2180 (void)ttyoutput(c, tp);
2181 }
2182
2183 /*
2184 * Wake up any readers on a tty.
2185 * Called with tty slock held.
2186 */
2187 void
2188 ttwakeup(struct tty *tp)
2189 {
2190
2191 selnotify(&tp->t_rsel, 0);
2192 if (ISSET(tp->t_state, TS_ASYNC))
2193 pgsignal(tp->t_pgrp, SIGIO, 1);
2194 wakeup((caddr_t)&tp->t_rawq);
2195 }
2196
2197 /*
2198 * Look up a code for a specified speed in a conversion table;
2199 * used by drivers to map software speed values to hardware parameters.
2200 */
2201 int
2202 ttspeedtab(int speed, struct speedtab *table)
2203 {
2204
2205 for (; table->sp_speed != -1; table++)
2206 if (table->sp_speed == speed)
2207 return (table->sp_code);
2208 return (-1);
2209 }
2210
2211 /*
2212 * Set tty hi and low water marks.
2213 *
2214 * Try to arrange the dynamics so there's about one second
2215 * from hi to low water.
2216 */
2217 void
2218 ttsetwater(struct tty *tp)
2219 {
2220 int cps, x;
2221
2222 #define CLAMP(x, h, l) ((x) > h ? h : ((x) < l) ? l : (x))
2223
2224 cps = tp->t_ospeed / 10;
2225 tp->t_lowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
2226 x += cps;
2227 x = CLAMP(x, TTMAXHIWAT, TTMINHIWAT);
2228 tp->t_hiwat = roundup(x, CBSIZE);
2229 #undef CLAMP
2230 }
2231
2232 /*
2233 * Report on state of foreground process group.
2234 * Call with tty slock held.
2235 */
2236 void
2237 ttyinfo(struct tty *tp)
2238 {
2239 struct lwp *l;
2240 struct proc *p, *pick;
2241 struct timeval utime, stime;
2242 int tmp;
2243
2244 if (ttycheckoutq_wlock(tp, 0) == 0)
2245 return;
2246
2247 /* Print load average. */
2248 tmp = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
2249 ttyprintf_nolock(tp, "load: %d.%02d ", tmp / 100, tmp % 100);
2250
2251 if (tp->t_session == NULL)
2252 ttyprintf_nolock(tp, "not a controlling terminal\n");
2253 else if (tp->t_pgrp == NULL)
2254 ttyprintf_nolock(tp, "no foreground process group\n");
2255 else if ((p = LIST_FIRST(&tp->t_pgrp->pg_members)) == 0)
2256 ttyprintf_nolock(tp, "empty foreground process group\n");
2257 else {
2258 /* Pick interesting process. */
2259 for (pick = NULL; p != NULL; p = LIST_NEXT(p, p_pglist))
2260 if (proc_compare(pick, p))
2261 pick = p;
2262
2263 ttyprintf_nolock(tp, " cmd: %s %d [", pick->p_comm, pick->p_pid);
2264 LIST_FOREACH(l, &pick->p_lwps, l_sibling)
2265 ttyprintf_nolock(tp, "%s%s",
2266 l->l_stat == LSONPROC ? "running" :
2267 l->l_stat == LSRUN ? "runnable" :
2268 l->l_wmesg ? l->l_wmesg : "iowait",
2269 (LIST_NEXT(l, l_sibling) != NULL) ? " " : "] ");
2270
2271 calcru(pick, &utime, &stime, NULL);
2272
2273 /* Round up and print user time. */
2274 utime.tv_usec += 5000;
2275 if (utime.tv_usec >= 1000000) {
2276 utime.tv_sec += 1;
2277 utime.tv_usec -= 1000000;
2278 }
2279 ttyprintf_nolock(tp, "%ld.%02ldu ", (long int)utime.tv_sec,
2280 (long int)utime.tv_usec / 10000);
2281
2282 /* Round up and print system time. */
2283 stime.tv_usec += 5000;
2284 if (stime.tv_usec >= 1000000) {
2285 stime.tv_sec += 1;
2286 stime.tv_usec -= 1000000;
2287 }
2288 ttyprintf_nolock(tp, "%ld.%02lds ", (long int)stime.tv_sec,
2289 (long int)stime.tv_usec / 10000);
2290
2291 #define pgtok(a) (((u_long) ((a) * PAGE_SIZE) / 1024))
2292 /* Print percentage cpu. */
2293 tmp = (pick->p_pctcpu * 10000 + FSCALE / 2) >> FSHIFT;
2294 ttyprintf_nolock(tp, "%d%% ", tmp / 100);
2295
2296 /* Print resident set size. */
2297 if (pick->p_stat == SIDL || P_ZOMBIE(pick))
2298 tmp = 0;
2299 else {
2300 struct vmspace *vm = pick->p_vmspace;
2301 tmp = pgtok(vm_resident_count(vm));
2302 }
2303 ttyprintf_nolock(tp, "%dk\n", tmp);
2304 }
2305 tp->t_rocount = 0; /* so pending input will be retyped if BS */
2306 }
2307
2308 /*
2309 * Returns 1 if p2 is "better" than p1
2310 *
2311 * The algorithm for picking the "interesting" process is thus:
2312 *
2313 * 1) Only foreground processes are eligible - implied.
2314 * 2) Runnable processes are favored over anything else. The runner
2315 * with the highest cpu utilization is picked (p_estcpu). Ties are
2316 * broken by picking the highest pid.
2317 * 3) The sleeper with the shortest sleep time is next. With ties,
2318 * we pick out just "short-term" sleepers (P_SINTR == 0).
2319 * 4) Further ties are broken by picking the highest pid.
2320 */
2321 #define ISRUN(p) ((p)->p_nrlwps > 0)
2322 #define TESTAB(a, b) ((a)<<1 | (b))
2323 #define ONLYA 2
2324 #define ONLYB 1
2325 #define BOTH 3
2326
2327 static int
2328 proc_compare(struct proc *p1, struct proc *p2)
2329 {
2330
2331 if (p1 == NULL)
2332 return (1);
2333 /*
2334 * see if at least one of them is runnable
2335 */
2336 switch (TESTAB(ISRUN(p1), ISRUN(p2))) {
2337 case ONLYA:
2338 return (0);
2339 case ONLYB:
2340 return (1);
2341 case BOTH:
2342 /*
2343 * tie - favor one with highest recent cpu utilization
2344 */
2345 if (p2->p_estcpu > p1->p_estcpu)
2346 return (1);
2347 if (p1->p_estcpu > p2->p_estcpu)
2348 return (0);
2349 return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
2350 }
2351 /*
2352 * weed out zombies
2353 */
2354 switch (TESTAB(P_ZOMBIE(p1), P_ZOMBIE(p2))) {
2355 case ONLYA:
2356 return (1);
2357 case ONLYB:
2358 return (0);
2359 case BOTH:
2360 return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
2361 }
2362 #if 0 /* XXX NJWLWP */
2363 /*
2364 * pick the one with the smallest sleep time
2365 */
2366 if (p2->p_slptime > p1->p_slptime)
2367 return (0);
2368 if (p1->p_slptime > p2->p_slptime)
2369 return (1);
2370 /*
2371 * favor one sleeping in a non-interruptible sleep
2372 */
2373 if (p1->p_flag & P_SINTR && (p2->p_flag & P_SINTR) == 0)
2374 return (1);
2375 if (p2->p_flag & P_SINTR && (p1->p_flag & P_SINTR) == 0)
2376 return (0);
2377 #endif
2378 return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
2379 }
2380
2381 /*
2382 * Output char to tty; console putchar style.
2383 * Can be called with tty lock held through kprintf() machinery..
2384 */
2385 int
2386 tputchar(int c, int flags, struct tty *tp)
2387 {
2388 int s, r = 0;
2389
2390 s = spltty();
2391 if ((flags & NOLOCK) == 0)
2392 simple_lock(&tp->t_slock);
2393 if (!CONNECTED(tp)) {
2394 r = -1;
2395 goto out;
2396 }
2397 if (c == '\n')
2398 (void)ttyoutput('\r', tp);
2399 (void)ttyoutput(c, tp);
2400 ttstart(tp);
2401 out:
2402 if ((flags & NOLOCK) == 0)
2403 TTY_UNLOCK(tp);
2404 splx(s);
2405 return (r);
2406 }
2407
2408 /*
2409 * Sleep on chan, returning ERESTART if tty changed while we napped and
2410 * returning any errors (e.g. EINTR/ETIMEDOUT) reported by tsleep. If
2411 * the tty is revoked, restarting a pending call will redo validation done
2412 * at the start of the call.
2413 *
2414 * Must be called with the tty slock held.
2415 */
2416 int
2417 ttysleep(struct tty *tp, void *chan, int pri, const char *wmesg, int timo)
2418 {
2419 int error;
2420 short gen;
2421
2422 gen = tp->t_gen;
2423 if ((error = ltsleep(chan, pri, wmesg, timo, &tp->t_slock)) != 0)
2424 return (error);
2425 return (tp->t_gen == gen ? 0 : ERESTART);
2426 }
2427
2428 /*
2429 * Initialise the global tty list.
2430 */
2431 void
2432 tty_init(void)
2433 {
2434
2435 ttyldisc_init();
2436
2437 TAILQ_INIT(&ttylist);
2438 tty_count = 0;
2439
2440 pool_init(&tty_pool, sizeof(struct tty), 0, 0, 0, "ttypl",
2441 &pool_allocator_nointr);
2442 }
2443
2444 /*
2445 * Attach a tty to the tty list.
2446 *
2447 * This should be called ONLY once per real tty (including pty's).
2448 * eg, on the sparc, the keyboard and mouse have struct tty's that are
2449 * distinctly NOT usable as tty's, and thus should not be attached to
2450 * the ttylist. This is why this call is not done from ttymalloc().
2451 *
2452 * Device drivers should attach tty's at a similar time that they are
2453 * ttymalloc()'ed, or, for the case of statically allocated struct tty's
2454 * either in the attach or (first) open routine.
2455 */
2456 void
2457 tty_attach(struct tty *tp)
2458 {
2459
2460 simple_lock(&ttylist_slock);
2461 TAILQ_INSERT_TAIL(&ttylist, tp, tty_link);
2462 ++tty_count;
2463 simple_unlock(&ttylist_slock);
2464 }
2465
2466 /*
2467 * Remove a tty from the tty list.
2468 */
2469 void
2470 tty_detach(struct tty *tp)
2471 {
2472
2473 simple_lock(&ttylist_slock);
2474 --tty_count;
2475 #ifdef DIAGNOSTIC
2476 if (tty_count < 0)
2477 panic("tty_detach: tty_count < 0");
2478 #endif
2479 TAILQ_REMOVE(&ttylist, tp, tty_link);
2480 simple_unlock(&ttylist_slock);
2481 }
2482
2483 /*
2484 * Allocate a tty structure and its associated buffers.
2485 */
2486 struct tty *
2487 ttymalloc(void)
2488 {
2489 struct tty *tp;
2490
2491 tp = pool_get(&tty_pool, PR_WAITOK);
2492 memset(tp, 0, sizeof(*tp));
2493 simple_lock_init(&tp->t_slock);
2494 callout_init(&tp->t_rstrt_ch);
2495 /* XXX: default to 1024 chars for now */
2496 clalloc(&tp->t_rawq, 1024, 1);
2497 clalloc(&tp->t_canq, 1024, 1);
2498 /* output queue doesn't need quoting */
2499 clalloc(&tp->t_outq, 1024, 0);
2500 /* Set default line discipline. */
2501 tp->t_linesw = linesw[0];
2502 return (tp);
2503 }
2504
2505 /*
2506 * Free a tty structure and its buffers.
2507 *
2508 * Be sure to call tty_detach() for any tty that has been
2509 * tty_attach()ed.
2510 */
2511 void
2512 ttyfree(struct tty *tp)
2513 {
2514
2515 callout_stop(&tp->t_rstrt_ch);
2516 clfree(&tp->t_rawq);
2517 clfree(&tp->t_canq);
2518 clfree(&tp->t_outq);
2519 pool_put(&tty_pool, tp);
2520 }
2521
2522 /*
2523 * ttyprintf_nolock: send a message to a specific tty, without locking.
2524 *
2525 * => should be used only by tty driver or anything that knows the
2526 * underlying tty will not be revoked(2)'d away. [otherwise,
2527 * use tprintf]
2528 */
2529 static void
2530 ttyprintf_nolock(struct tty *tp, const char *fmt, ...)
2531 {
2532 va_list ap;
2533
2534 /* No mutex needed; going to process TTY. */
2535 va_start(ap, fmt);
2536 kprintf(fmt, TOTTY|NOLOCK, tp, NULL, ap);
2537 va_end(ap);
2538 }
2539