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