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