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