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