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