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