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