tty.c revision 1.299 1 /* $NetBSD: tty.c,v 1.299 2021/12/05 07:44:53 msaitoh Exp $ */
2
3 /*-
4 * Copyright (c) 2008, 2020 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.299 2021/12/05 07:44:53 msaitoh 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 if (newsize <= 0)
230 return EINVAL;
231
232 newsize = 1 << ilog2(newsize); /* Make it a power of two */
233
234 if (newsize < TTY_MINQSIZE || newsize > TTY_MAXQSIZE)
235 return EINVAL;
236
237 *qsize = newsize;
238 return 0;
239 }
240
241 static int
242 tty_set_qsize(struct tty *tp, int newsize)
243 {
244 struct clist rawq, canq, outq;
245 struct clist orawq, ocanq, ooutq;
246
247 clalloc(&rawq, newsize, 1);
248 clalloc(&canq, newsize, 1);
249 clalloc(&outq, newsize, 0);
250
251 mutex_spin_enter(&tty_lock);
252
253 if (tp->t_outq.c_cc != 0) {
254 mutex_spin_exit(&tty_lock);
255 clfree(&rawq);
256 clfree(&canq);
257 clfree(&outq);
258 return EBUSY;
259 }
260
261 orawq = tp->t_rawq;
262 ocanq = tp->t_canq;
263 ooutq = tp->t_outq;
264
265 tp->t_qsize = newsize;
266 tp->t_rawq = rawq;
267 tp->t_canq = canq;
268 tp->t_outq = outq;
269
270 ttsetwater(tp);
271
272 mutex_spin_exit(&tty_lock);
273
274 clfree(&orawq);
275 clfree(&ocanq);
276 clfree(&ooutq);
277
278 return 0;
279 }
280
281 static int
282 sysctl_kern_tty_qsize(SYSCTLFN_ARGS)
283 {
284 int newsize;
285 int error;
286 struct sysctlnode node;
287 node = *rnode;
288 node.sysctl_data = &newsize;
289
290 newsize = tty_qsize;
291 error = sysctl_lookup(SYSCTLFN_CALL(&node));
292 if (error || newp == NULL)
293 return error;
294
295
296 return tty_get_qsize(&tty_qsize, newsize);
297 }
298
299 static void
300 sysctl_kern_tty_setup(void)
301 {
302 const struct sysctlnode *rnode, *cnode;
303
304 sysctl_createv(NULL, 0, NULL, NULL,
305 CTLFLAG_PERMANENT,
306 CTLTYPE_NODE, "tkstat",
307 SYSCTL_DESCR("Number of characters sent and received "
308 "on ttys"),
309 NULL, 0, NULL, 0,
310 CTL_KERN, KERN_TKSTAT, CTL_EOL);
311
312 sysctl_createv(NULL, 0, NULL, NULL,
313 CTLFLAG_PERMANENT,
314 CTLTYPE_QUAD, "nin",
315 SYSCTL_DESCR("Total number of tty input characters"),
316 NULL, 0, &tk_nin, 0,
317 CTL_KERN, KERN_TKSTAT, KERN_TKSTAT_NIN, CTL_EOL);
318 sysctl_createv(NULL, 0, NULL, NULL,
319 CTLFLAG_PERMANENT,
320 CTLTYPE_QUAD, "nout",
321 SYSCTL_DESCR("Total number of tty output characters"),
322 NULL, 0, &tk_nout, 0,
323 CTL_KERN, KERN_TKSTAT, KERN_TKSTAT_NOUT, CTL_EOL);
324 sysctl_createv(NULL, 0, NULL, NULL,
325 CTLFLAG_PERMANENT,
326 CTLTYPE_QUAD, "cancc",
327 SYSCTL_DESCR("Number of canonical tty input characters"),
328 NULL, 0, &tk_cancc, 0,
329 CTL_KERN, KERN_TKSTAT, KERN_TKSTAT_CANCC, CTL_EOL);
330 sysctl_createv(NULL, 0, NULL, NULL,
331 CTLFLAG_PERMANENT,
332 CTLTYPE_QUAD, "rawcc",
333 SYSCTL_DESCR("Number of raw tty input characters"),
334 NULL, 0, &tk_rawcc, 0,
335 CTL_KERN, KERN_TKSTAT, KERN_TKSTAT_RAWCC, CTL_EOL);
336
337 sysctl_createv(NULL, 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(NULL, 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 if (pgid == INT_MIN) {
1306 mutex_exit(&proc_lock);
1307 return (EINVAL);
1308 }
1309 pgrp = pgrp_find(-pgid);
1310 if (pgrp == NULL) {
1311 mutex_exit(&proc_lock);
1312 return (EINVAL);
1313 }
1314 } else {
1315 struct proc *p1;
1316 p1 = proc_find(pgid);
1317 if (!p1) {
1318 mutex_exit(&proc_lock);
1319 return (ESRCH);
1320 }
1321 pgrp = p1->p_pgrp;
1322 }
1323
1324 if (pgrp->pg_session != p->p_session) {
1325 mutex_exit(&proc_lock);
1326 return (EPERM);
1327 }
1328 mutex_spin_enter(&tty_lock);
1329 tp->t_pgrp = pgrp;
1330 mutex_spin_exit(&tty_lock);
1331 mutex_exit(&proc_lock);
1332 break;
1333 }
1334 case TIOCSPGRP: { /* set pgrp of tty */
1335 struct pgrp *pgrp;
1336 pid_t pgid = *(pid_t *)data;
1337
1338 if (pgid == NO_PGID)
1339 return EINVAL;
1340
1341 mutex_enter(&proc_lock);
1342 if (!isctty(p, tp)) {
1343 mutex_exit(&proc_lock);
1344 return (ENOTTY);
1345 }
1346 pgrp = pgrp_find(pgid);
1347 if (pgrp == NULL || pgrp->pg_session != p->p_session) {
1348 mutex_exit(&proc_lock);
1349 return (EPERM);
1350 }
1351 mutex_spin_enter(&tty_lock);
1352 tp->t_pgrp = pgrp;
1353 mutex_spin_exit(&tty_lock);
1354 mutex_exit(&proc_lock);
1355 break;
1356 }
1357 case TIOCSTAT: /* get load avg stats */
1358 mutex_enter(&proc_lock);
1359 ttygetinfo(tp, 0, infobuf, sizeof(infobuf));
1360 mutex_exit(&proc_lock);
1361
1362 mutex_spin_enter(&tty_lock);
1363 ttyputinfo(tp, infobuf);
1364 mutex_spin_exit(&tty_lock);
1365 break;
1366 case TIOCSWINSZ: /* set window size */
1367 mutex_spin_enter(&tty_lock);
1368 if (memcmp((void *)&tp->t_winsize, data,
1369 sizeof(struct winsize))) {
1370 tp->t_winsize = *(struct winsize *)data;
1371 ttysig(tp, TTYSIG_PG1, SIGWINCH);
1372 }
1373 mutex_spin_exit(&tty_lock);
1374 break;
1375 case TIOCSQSIZE:
1376 if ((error = tty_get_qsize(&s, *(int *)data)) == 0 &&
1377 s != tp->t_qsize)
1378 error = tty_set_qsize(tp, s);
1379 return error;
1380
1381 case TIOCSBRK:
1382 case TIOCCBRK:
1383 case TIOCSDTR:
1384 case TIOCCDTR:
1385 case TIOCSFLAGS:
1386 case TIOCGFLAGS:
1387 case TIOCMSET:
1388 case TIOCMGET:
1389 case TIOCMBIS:
1390 case TIOCMBIC:
1391 /* Handled by the driver layer */
1392 return EPASSTHROUGH;
1393
1394 case TIOCEXT:
1395 case TIOCPTSNAME:
1396 case TIOCGRANTPT:
1397 case TIOCPKT:
1398 case TIOCUCNTL:
1399 case TIOCREMOTE:
1400 case TIOCSIG:
1401 /* for ptys */
1402 return EPASSTHROUGH;
1403
1404 default:
1405 /* Pass through various console ioctls */
1406 switch (IOCGROUP(cmd)) {
1407 case 'c': /* syscons console */
1408 case 'v': /* usl console, video - where one letter */
1409 case 'K': /* usl console, keyboard - aint enough */
1410 case 'V': /* pcvt compat */
1411 case 'W': /* wscons console */
1412 return EPASSTHROUGH;
1413 default:
1414 break;
1415 }
1416
1417 /* We may have to load the compat_60 module for this. */
1418 (void)module_autoload("compat_60", MODULE_CLASS_EXEC);
1419 MODULE_HOOK_CALL(tty_ttioctl_60_hook,
1420 (tp, cmd, data, flag, l), enosys(), error);
1421 if (error != EPASSTHROUGH)
1422 return error;
1423
1424 /* We may have to load the compat_43 module for this. */
1425 (void)module_autoload("compat_43", MODULE_CLASS_EXEC);
1426 MODULE_HOOK_CALL(tty_ttioctl_43_hook,
1427 (tp, cmd, data, flag, l), enosys(), error);
1428 return error;
1429 }
1430 return (0);
1431 }
1432
1433 int
1434 ttpoll(struct tty *tp, int events, struct lwp *l)
1435 {
1436 int revents;
1437
1438 revents = 0;
1439 mutex_spin_enter(&tty_lock);
1440 if (events & (POLLIN | POLLRDNORM))
1441 if (ttnread(tp) > 0)
1442 revents |= events & (POLLIN | POLLRDNORM);
1443
1444 if (events & (POLLOUT | POLLWRNORM))
1445 if (tp->t_outq.c_cc <= tp->t_lowat)
1446 revents |= events & (POLLOUT | POLLWRNORM);
1447
1448 if (events & POLLHUP)
1449 if (!CONNECTED(tp))
1450 revents |= POLLHUP;
1451
1452 if (revents == 0) {
1453 if (events & (POLLIN | POLLHUP | POLLRDNORM))
1454 selrecord(l, &tp->t_rsel);
1455
1456 if (events & (POLLOUT | POLLWRNORM))
1457 selrecord(l, &tp->t_wsel);
1458 }
1459
1460 mutex_spin_exit(&tty_lock);
1461
1462 return (revents);
1463 }
1464
1465 static void
1466 filt_ttyrdetach(struct knote *kn)
1467 {
1468 struct tty *tp;
1469
1470 tp = kn->kn_hook;
1471 mutex_spin_enter(&tty_lock);
1472 selremove_knote(&tp->t_rsel, kn);
1473 mutex_spin_exit(&tty_lock);
1474 }
1475
1476 static int
1477 filt_ttyread(struct knote *kn, long hint)
1478 {
1479 struct tty *tp;
1480 int rv;
1481
1482 tp = kn->kn_hook;
1483 if ((hint & NOTE_SUBMIT) == 0)
1484 mutex_spin_enter(&tty_lock);
1485 kn->kn_data = ttnread(tp);
1486 rv = kn->kn_data > 0;
1487 if ((hint & NOTE_SUBMIT) == 0)
1488 mutex_spin_exit(&tty_lock);
1489 return rv;
1490 }
1491
1492 static void
1493 filt_ttywdetach(struct knote *kn)
1494 {
1495 struct tty *tp;
1496
1497 tp = kn->kn_hook;
1498 mutex_spin_enter(&tty_lock);
1499 selremove_knote(&tp->t_wsel, kn);
1500 mutex_spin_exit(&tty_lock);
1501 }
1502
1503 static int
1504 filt_ttywrite(struct knote *kn, long hint)
1505 {
1506 struct tty *tp;
1507 int canwrite;
1508
1509 tp = kn->kn_hook;
1510 if ((hint & NOTE_SUBMIT) == 0)
1511 mutex_spin_enter(&tty_lock);
1512 kn->kn_data = tp->t_outq.c_cn - tp->t_outq.c_cc;
1513 canwrite = (tp->t_outq.c_cc <= tp->t_lowat) && CONNECTED(tp);
1514 if ((hint & NOTE_SUBMIT) == 0)
1515 mutex_spin_exit(&tty_lock);
1516 return (canwrite);
1517 }
1518
1519 static const struct filterops ttyread_filtops = {
1520 .f_flags = FILTEROP_ISFD | FILTEROP_MPSAFE,
1521 .f_attach = NULL,
1522 .f_detach = filt_ttyrdetach,
1523 .f_event = filt_ttyread,
1524 };
1525
1526 static const struct filterops ttywrite_filtops = {
1527 .f_flags = FILTEROP_ISFD | FILTEROP_MPSAFE,
1528 .f_attach = NULL,
1529 .f_detach = filt_ttywdetach,
1530 .f_event = filt_ttywrite,
1531 };
1532
1533 int
1534 ttykqfilter(dev_t dev, struct knote *kn)
1535 {
1536 struct tty *tp;
1537 struct selinfo *sip;
1538
1539 if ((tp = cdev_tty(dev)) == NULL)
1540 return (ENXIO);
1541
1542 switch (kn->kn_filter) {
1543 case EVFILT_READ:
1544 sip = &tp->t_rsel;
1545 kn->kn_fop = &ttyread_filtops;
1546 break;
1547 case EVFILT_WRITE:
1548 sip = &tp->t_wsel;
1549 kn->kn_fop = &ttywrite_filtops;
1550 break;
1551 default:
1552 return EINVAL;
1553 }
1554
1555 kn->kn_hook = tp;
1556
1557 mutex_spin_enter(&tty_lock);
1558 selrecord_knote(sip, kn);
1559 mutex_spin_exit(&tty_lock);
1560
1561 return (0);
1562 }
1563
1564 /*
1565 * Find the number of chars ready to be read from this tty.
1566 * Call with the tty lock held.
1567 */
1568 static int
1569 ttnread(struct tty *tp)
1570 {
1571 int nread;
1572
1573 KASSERT(mutex_owned(&tty_lock));
1574
1575 if (ISSET(tp->t_lflag, PENDIN))
1576 ttypend(tp);
1577 nread = tp->t_canq.c_cc;
1578 if (!ISSET(tp->t_lflag, ICANON)) {
1579 nread += tp->t_rawq.c_cc;
1580 if (nread < tp->t_cc[VMIN] && !tp->t_cc[VTIME])
1581 nread = 0;
1582 }
1583 return (nread);
1584 }
1585
1586 /*
1587 * Wait for output to drain, or if this times out, flush it.
1588 */
1589 static int
1590 ttywait_timo(struct tty *tp, int timo)
1591 {
1592 int error;
1593
1594 error = 0;
1595
1596 mutex_spin_enter(&tty_lock);
1597 while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1598 CONNECTED(tp) && tp->t_oproc) {
1599 (*tp->t_oproc)(tp);
1600 error = ttysleep(tp, &tp->t_outcv, true, timo);
1601 if (error == EWOULDBLOCK)
1602 ttyflush(tp, FWRITE);
1603 if (error)
1604 break;
1605 }
1606 mutex_spin_exit(&tty_lock);
1607
1608 return (error);
1609 }
1610
1611 /*
1612 * Wait for output to drain.
1613 */
1614 int
1615 ttywait(struct tty *tp)
1616 {
1617 return ttywait_timo(tp, 0);
1618 }
1619
1620 /*
1621 * Flush if successfully wait.
1622 */
1623 int
1624 ttywflush(struct tty *tp)
1625 {
1626 int error;
1627
1628 error = ttywait_timo(tp, 5 * hz);
1629 if (error == 0 || error == EWOULDBLOCK) {
1630 mutex_spin_enter(&tty_lock);
1631 ttyflush(tp, FREAD);
1632 mutex_spin_exit(&tty_lock);
1633 }
1634 return (error);
1635 }
1636
1637 /*
1638 * Flush tty read and/or write queues, notifying anyone waiting.
1639 * Call with the tty lock held.
1640 */
1641 void
1642 ttyflush(struct tty *tp, int rw)
1643 {
1644
1645 KASSERT(mutex_owned(&tty_lock));
1646
1647 if (rw & FREAD) {
1648 FLUSHQ(&tp->t_canq);
1649 FLUSHQ(&tp->t_rawq);
1650 tp->t_rocount = 0;
1651 tp->t_rocol = 0;
1652 CLR(tp->t_state, TS_LOCAL);
1653 ttwakeup(tp);
1654 }
1655 if (rw & FWRITE) {
1656 CLR(tp->t_state, TS_TTSTOP);
1657 cdev_stop(tp, rw);
1658 FLUSHQ(&tp->t_outq);
1659 cv_broadcast(&tp->t_outcv);
1660 selnotify(&tp->t_wsel, 0, NOTE_SUBMIT);
1661 }
1662 }
1663
1664 /*
1665 * Copy in the default termios characters.
1666 */
1667 void
1668 ttychars(struct tty *tp)
1669 {
1670
1671 memcpy(tp->t_cc, ttydefchars, sizeof(ttydefchars));
1672 }
1673
1674 /*
1675 * Send stop character on input overflow.
1676 * Call with the tty lock held.
1677 */
1678 static void
1679 ttyblock(struct tty *tp)
1680 {
1681 int total;
1682
1683 KASSERT(mutex_owned(&tty_lock));
1684
1685 total = tp->t_rawq.c_cc + tp->t_canq.c_cc;
1686 if (tp->t_rawq.c_cc > TTYHOG) {
1687 ttyflush(tp, FREAD | FWRITE);
1688 CLR(tp->t_state, TS_TBLOCK);
1689 }
1690 /*
1691 * Block further input iff: current input > threshold
1692 * AND input is available to user program.
1693 */
1694 if (total >= TTYHOG / 2 &&
1695 !ISSET(tp->t_state, TS_TBLOCK) &&
1696 (!ISSET(tp->t_lflag, ICANON) || tp->t_canq.c_cc > 0)) {
1697 if (ISSET(tp->t_iflag, IXOFF) &&
1698 tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
1699 putc(tp->t_cc[VSTOP], &tp->t_outq) == 0) {
1700 SET(tp->t_state, TS_TBLOCK);
1701 ttstart(tp);
1702 }
1703 /* Try to block remote output via hardware flow control. */
1704 if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
1705 (*tp->t_hwiflow)(tp, 1) != 0)
1706 SET(tp->t_state, TS_TBLOCK);
1707 }
1708 }
1709
1710 /*
1711 * Delayed line discipline output
1712 */
1713 void
1714 ttrstrt(void *tp_arg)
1715 {
1716 struct tty *tp;
1717
1718 #ifdef DIAGNOSTIC
1719 if (tp_arg == NULL)
1720 panic("ttrstrt");
1721 #endif
1722 tp = tp_arg;
1723 mutex_spin_enter(&tty_lock);
1724
1725 CLR(tp->t_state, TS_TIMEOUT);
1726 ttstart(tp); /* XXX - Shouldn't this be tp->l_start(tp)? */
1727
1728 mutex_spin_exit(&tty_lock);
1729 }
1730
1731 /*
1732 * start a line discipline
1733 * Always call with tty lock held?
1734 */
1735 int
1736 ttstart(struct tty *tp)
1737 {
1738
1739 if (tp->t_oproc != NULL) /* XXX: Kludge for pty. */
1740 (*tp->t_oproc)(tp);
1741 return (0);
1742 }
1743
1744 /*
1745 * "close" a line discipline
1746 */
1747 int
1748 ttylclose(struct tty *tp, int flag)
1749 {
1750
1751 if (flag & FNONBLOCK) {
1752 mutex_spin_enter(&tty_lock);
1753 ttyflush(tp, FREAD | FWRITE);
1754 mutex_spin_exit(&tty_lock);
1755 } else
1756 ttywflush(tp);
1757 return (0);
1758 }
1759
1760 /*
1761 * Handle modem control transition on a tty.
1762 * Flag indicates new state of carrier.
1763 * Returns 0 if the line should be turned off, otherwise 1.
1764 */
1765 int
1766 ttymodem(struct tty *tp, int flag)
1767 {
1768
1769 mutex_spin_enter(&tty_lock);
1770 if (flag == 0) {
1771 if (ISSET(tp->t_state, TS_CARR_ON)) {
1772 /*
1773 * Lost carrier.
1774 */
1775 CLR(tp->t_state, TS_CARR_ON);
1776 if (ISSET(tp->t_state, TS_ISOPEN) && !CONNECTED(tp)) {
1777 ttysig(tp, TTYSIG_LEADER, SIGHUP);
1778 ttyflush(tp, FREAD | FWRITE);
1779 mutex_spin_exit(&tty_lock);
1780 return (0);
1781 }
1782 }
1783 } else {
1784 if (!ISSET(tp->t_state, TS_CARR_ON)) {
1785 /*
1786 * Carrier now on.
1787 */
1788 SET(tp->t_state, TS_CARR_ON);
1789 ttwakeup(tp);
1790 }
1791 }
1792 mutex_spin_exit(&tty_lock);
1793
1794 return (1);
1795 }
1796
1797 /*
1798 * Default modem control routine (for other line disciplines).
1799 * Return argument flag, to turn off device on carrier drop.
1800 */
1801 int
1802 nullmodem(struct tty *tp, int flag)
1803 {
1804
1805 mutex_spin_enter(&tty_lock);
1806 if (flag)
1807 SET(tp->t_state, TS_CARR_ON);
1808 else {
1809 CLR(tp->t_state, TS_CARR_ON);
1810 if (!CONNECTED(tp)) {
1811 ttysig(tp, TTYSIG_LEADER, SIGHUP);
1812 mutex_spin_exit(&tty_lock);
1813 return (0);
1814 }
1815 }
1816 mutex_spin_exit(&tty_lock);
1817
1818 return (1);
1819 }
1820
1821 /*
1822 * Reinput pending characters after state switch.
1823 */
1824 void
1825 ttypend(struct tty *tp)
1826 {
1827 struct clist tq;
1828 int c;
1829
1830 KASSERT(mutex_owned(&tty_lock));
1831
1832 CLR(tp->t_lflag, PENDIN);
1833 SET(tp->t_state, TS_TYPEN);
1834 tq = tp->t_rawq;
1835 tp->t_rawq.c_cc = 0;
1836 tp->t_rawq.c_cf = tp->t_rawq.c_cl = 0;
1837 while ((c = getc(&tq)) >= 0)
1838 ttyinput_wlock(c, tp);
1839 CLR(tp->t_state, TS_TYPEN);
1840 }
1841
1842 /*
1843 * Process a read call on a tty device.
1844 */
1845 int
1846 ttread(struct tty *tp, struct uio *uio, int flag)
1847 {
1848 struct clist *qp;
1849 u_char *cc;
1850 struct proc *p;
1851 int c, first, error, has_stime, last_cc;
1852 long lflag, slp;
1853 struct timeval now, stime;
1854
1855 if (uio->uio_resid == 0)
1856 return 0;
1857
1858 stime.tv_usec = 0; /* XXX gcc */
1859 stime.tv_sec = 0; /* XXX gcc */
1860
1861 cc = tp->t_cc;
1862 p = curproc;
1863 error = 0;
1864 has_stime = 0;
1865 last_cc = 0;
1866 slp = 0;
1867
1868 loop:
1869 mutex_spin_enter(&tty_lock);
1870 lflag = tp->t_lflag;
1871 /*
1872 * take pending input first
1873 */
1874 if (ISSET(lflag, PENDIN))
1875 ttypend(tp);
1876
1877 /*
1878 * Hang process if it's in the background.
1879 */
1880 if (isbackground(p, tp)) {
1881 if (sigismasked(curlwp, SIGTTIN) ||
1882 p->p_lflag & PL_PPWAIT || p->p_pgrp->pg_jobc == 0) {
1883 mutex_spin_exit(&tty_lock);
1884 return (EIO);
1885 }
1886 mutex_spin_exit(&tty_lock);
1887
1888 mutex_enter(&proc_lock);
1889 pgsignal(p->p_pgrp, SIGTTIN, 1);
1890 mutex_exit(&proc_lock);
1891
1892 mutex_spin_enter(&tty_lock);
1893 error = ttypause(tp, hz);
1894 mutex_spin_exit(&tty_lock);
1895 if (error)
1896 return (error);
1897 goto loop;
1898 }
1899
1900 if (!ISSET(lflag, ICANON)) {
1901 int m = cc[VMIN];
1902 long t = cc[VTIME];
1903
1904 qp = &tp->t_rawq;
1905 /*
1906 * Check each of the four combinations.
1907 * (m > 0 && t == 0) is the normal read case.
1908 * It should be fairly efficient, so we check that and its
1909 * companion case (m == 0 && t == 0) first.
1910 * For the other two cases, we compute the target sleep time
1911 * into slp.
1912 */
1913 if (t == 0) {
1914 if (qp->c_cc < m)
1915 goto sleep;
1916 goto read;
1917 }
1918 t *= hz; /* time in deca-ticks */
1919 /*
1920 * Time difference in deca-ticks, split division to avoid numeric overflow.
1921 * Ok for hz < ~200kHz
1922 */
1923 #define diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 10 * hz + \
1924 ((t1).tv_usec - (t2).tv_usec) / 100 * hz / 1000)
1925 if (m > 0) {
1926 if (qp->c_cc <= 0)
1927 goto sleep;
1928 if (qp->c_cc >= m)
1929 goto read;
1930 if (!has_stime) {
1931 /* first character, start timer */
1932 has_stime = 1;
1933 getmicrotime(&stime);
1934 slp = t;
1935 } else if (qp->c_cc > last_cc) {
1936 /* got a character, restart timer */
1937 getmicrotime(&stime);
1938 slp = t;
1939 } else {
1940 /* nothing, check expiration */
1941 getmicrotime(&now);
1942 slp = t - diff(now, stime);
1943 }
1944 } else { /* m == 0 */
1945 if (qp->c_cc > 0)
1946 goto read;
1947 if (!has_stime) {
1948 has_stime = 1;
1949 getmicrotime(&stime);
1950 slp = t;
1951 } else {
1952 getmicrotime(&now);
1953 slp = t - diff(now, stime);
1954 }
1955 }
1956 last_cc = qp->c_cc;
1957 #undef diff
1958 if (slp > 0) {
1959 /*
1960 * Convert deca-ticks back to ticks.
1961 * Rounding down may make us wake up just short
1962 * of the target, so we round up.
1963 * Maybe we should do 'slp/10 + 1' because the
1964 * first tick maybe almost immediate.
1965 * However it is more useful for a program that sets
1966 * VTIME=10 to wakeup every second not every 1.01
1967 * seconds (if hz=100).
1968 */
1969 slp = (slp + 9)/ 10;
1970 goto sleep;
1971 }
1972 } else if ((qp = &tp->t_canq)->c_cc <= 0) {
1973 int carrier;
1974
1975 sleep:
1976 /*
1977 * If there is no input, sleep on rawq
1978 * awaiting hardware receipt and notification.
1979 * If we have data, we don't need to check for carrier.
1980 */
1981 carrier = CONNECTED(tp);
1982 if (!carrier && ISSET(tp->t_state, TS_ISOPEN)) {
1983 mutex_spin_exit(&tty_lock);
1984 return (0); /* EOF */
1985 }
1986 if (!has_stime || slp <= 0) {
1987 if (flag & IO_NDELAY) {
1988 mutex_spin_exit(&tty_lock);
1989 return (EWOULDBLOCK);
1990 }
1991 }
1992 error = ttysleep(tp, &tp->t_rawcv, true, slp);
1993 mutex_spin_exit(&tty_lock);
1994 /* VMIN == 0: any quantity read satisfies */
1995 if (cc[VMIN] == 0 && error == EWOULDBLOCK)
1996 return (0);
1997 if (error && error != EWOULDBLOCK)
1998 return (error);
1999 goto loop;
2000 }
2001 read:
2002
2003 /*
2004 * Input present, check for input mapping and processing.
2005 */
2006 first = 1;
2007 while ((c = getc(qp)) >= 0) {
2008 /*
2009 * delayed suspend (^Y)
2010 */
2011 if (CCEQ(cc[VDSUSP], c) &&
2012 ISSET(lflag, IEXTEN|ISIG) == (IEXTEN|ISIG)) {
2013 ttysig(tp, TTYSIG_PG1, SIGTSTP);
2014 if (first) {
2015 error = ttypause(tp, hz);
2016 if (error)
2017 break;
2018 mutex_spin_exit(&tty_lock);
2019 goto loop;
2020 }
2021 break;
2022 }
2023 /*
2024 * Interpret EOF only in canonical mode.
2025 */
2026 if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
2027 break;
2028 /*
2029 * Give user character.
2030 */
2031 mutex_spin_exit(&tty_lock);
2032 error = ureadc(c, uio);
2033 mutex_spin_enter(&tty_lock);
2034 if (error)
2035 break;
2036 if (uio->uio_resid == 0)
2037 break;
2038 /*
2039 * In canonical mode check for a "break character"
2040 * marking the end of a "line of input".
2041 */
2042 if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
2043 break;
2044 first = 0;
2045 }
2046
2047 /*
2048 * Look to unblock output now that (presumably)
2049 * the input queue has gone down.
2050 */
2051 if (ISSET(tp->t_state, TS_TBLOCK) && tp->t_rawq.c_cc < TTYHOG / 5) {
2052 if (ISSET(tp->t_iflag, IXOFF) &&
2053 cc[VSTART] != _POSIX_VDISABLE &&
2054 putc(cc[VSTART], &tp->t_outq) == 0) {
2055 CLR(tp->t_state, TS_TBLOCK);
2056 ttstart(tp);
2057 }
2058 /* Try to unblock remote output via hardware flow control. */
2059 if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
2060 (*tp->t_hwiflow)(tp, 0) != 0)
2061 CLR(tp->t_state, TS_TBLOCK);
2062 }
2063 mutex_spin_exit(&tty_lock);
2064
2065 return (error);
2066 }
2067
2068 /*
2069 * Check the output queue on tp for space for a kernel message (from uprintf
2070 * or tprintf). Allow some space over the normal hiwater mark so we don't
2071 * lose messages due to normal flow control, but don't let the tty run amok.
2072 * Sleeps here are not interruptible, but we return prematurely if new signals
2073 * arrive.
2074 * Call with tty lock held.
2075 */
2076 static int
2077 ttycheckoutq_wlock(struct tty *tp, int wait)
2078 {
2079 int hiwat, error;
2080
2081 KASSERT(mutex_owned(&tty_lock));
2082
2083 hiwat = tp->t_hiwat;
2084 if (tp->t_outq.c_cc > hiwat + 200)
2085 while (tp->t_outq.c_cc > hiwat) {
2086 ttstart(tp);
2087 if (wait == 0)
2088 return (0);
2089 error = ttysleep(tp, &tp->t_outcv, true, hz);
2090 if (error == EINTR)
2091 wait = 0;
2092 }
2093
2094 return (1);
2095 }
2096
2097 int
2098 ttycheckoutq(struct tty *tp, int wait)
2099 {
2100 int r;
2101
2102 mutex_spin_enter(&tty_lock);
2103 r = ttycheckoutq_wlock(tp, wait);
2104 mutex_spin_exit(&tty_lock);
2105
2106 return (r);
2107 }
2108
2109 /*
2110 * Process a write call on a tty device.
2111 */
2112 int
2113 ttwrite(struct tty *tp, struct uio *uio, int flag)
2114 {
2115 u_char *cp;
2116 struct proc *p;
2117 int cc, ce, i, hiwat, error;
2118 u_char obuf[OBUFSIZ];
2119
2120 cp = NULL;
2121 hiwat = tp->t_hiwat;
2122 error = 0;
2123 cc = 0;
2124 loop:
2125 mutex_spin_enter(&tty_lock);
2126 if (!CONNECTED(tp)) {
2127 if (ISSET(tp->t_state, TS_ISOPEN)) {
2128 mutex_spin_exit(&tty_lock);
2129 return (EIO);
2130 } else if (flag & IO_NDELAY) {
2131 mutex_spin_exit(&tty_lock);
2132 error = EWOULDBLOCK;
2133 goto out;
2134 } else {
2135 /* Sleep awaiting carrier. */
2136 error = ttysleep(tp, &tp->t_rawcv, true, 0);
2137 mutex_spin_exit(&tty_lock);
2138 if (error)
2139 goto out;
2140 goto loop;
2141 }
2142 }
2143
2144 /*
2145 * Hang the process if it's in the background.
2146 */
2147 p = curproc;
2148 if (isbackground(p, tp) &&
2149 ISSET(tp->t_lflag, TOSTOP) && (p->p_lflag & PL_PPWAIT) == 0 &&
2150 !sigismasked(curlwp, SIGTTOU)) {
2151 if (p->p_pgrp->pg_jobc == 0) {
2152 error = EIO;
2153 mutex_spin_exit(&tty_lock);
2154 goto out;
2155 }
2156 mutex_spin_exit(&tty_lock);
2157
2158 mutex_enter(&proc_lock);
2159 pgsignal(p->p_pgrp, SIGTTOU, 1);
2160 mutex_exit(&proc_lock);
2161
2162 mutex_spin_enter(&tty_lock);
2163 error = ttypause(tp, hz);
2164 mutex_spin_exit(&tty_lock);
2165 if (error)
2166 goto out;
2167 goto loop;
2168 }
2169 mutex_spin_exit(&tty_lock);
2170
2171 /*
2172 * Process the user's data in at most OBUFSIZ chunks. Perform any
2173 * output translation. Keep track of high water mark, sleep on
2174 * overflow awaiting device aid in acquiring new space.
2175 */
2176 while (uio->uio_resid > 0 || cc > 0) {
2177 if (ISSET(tp->t_lflag, FLUSHO)) {
2178 uio->uio_resid = 0;
2179 return (0);
2180 }
2181 if (tp->t_outq.c_cc > hiwat)
2182 goto ovhiwat;
2183 /*
2184 * Grab a hunk of data from the user, unless we have some
2185 * leftover from last time.
2186 */
2187 if (cc == 0) {
2188 cc = uimin(uio->uio_resid, OBUFSIZ);
2189 cp = obuf;
2190 error = uiomove(cp, cc, uio);
2191 if (error) {
2192 cc = 0;
2193 goto out;
2194 }
2195 }
2196 /*
2197 * If nothing fancy need be done, grab those characters we
2198 * can handle without any of ttyoutput's processing and
2199 * just transfer them to the output q. For those chars
2200 * which require special processing (as indicated by the
2201 * bits in char_type), call ttyoutput. After processing
2202 * a hunk of data, look for FLUSHO so ^O's will take effect
2203 * immediately.
2204 */
2205 mutex_spin_enter(&tty_lock);
2206 while (cc > 0) {
2207 if (!ISSET(tp->t_oflag, OPOST))
2208 ce = cc;
2209 else {
2210 ce = cc - scanc((u_int)cc, cp, char_type,
2211 CCLASSMASK);
2212 /*
2213 * If ce is zero, then we're processing
2214 * a special character through ttyoutput.
2215 */
2216 if (ce == 0) {
2217 tp->t_rocount = 0;
2218 if (ttyoutput(*cp, tp) >= 0) {
2219 /* out of space */
2220 mutex_spin_exit(&tty_lock);
2221 goto overfull;
2222 }
2223 cp++;
2224 cc--;
2225 if (ISSET(tp->t_lflag, FLUSHO) ||
2226 tp->t_outq.c_cc > hiwat) {
2227 mutex_spin_exit(&tty_lock);
2228 goto ovhiwat;
2229 }
2230 continue;
2231 }
2232 }
2233 /*
2234 * A bunch of normal characters have been found.
2235 * Transfer them en masse to the output queue and
2236 * continue processing at the top of the loop.
2237 * If there are any further characters in this
2238 * <= OBUFSIZ chunk, the first should be a character
2239 * requiring special handling by ttyoutput.
2240 */
2241 tp->t_rocount = 0;
2242 i = b_to_q(cp, ce, &tp->t_outq);
2243 ce -= i;
2244 tp->t_column += ce;
2245 cp += ce, cc -= ce, tk_nout += ce;
2246 tp->t_outcc += ce;
2247 if (i > 0) {
2248 /* out of space */
2249 mutex_spin_exit(&tty_lock);
2250 goto overfull;
2251 }
2252 if (ISSET(tp->t_lflag, FLUSHO) ||
2253 tp->t_outq.c_cc > hiwat)
2254 break;
2255 }
2256 ttstart(tp);
2257 mutex_spin_exit(&tty_lock);
2258 }
2259
2260 out:
2261 /*
2262 * If cc is nonzero, we leave the uio structure inconsistent, as the
2263 * offset and iov pointers have moved forward, but it doesn't matter
2264 * (the call will either return short or restart with a new uio).
2265 */
2266 uio->uio_resid += cc;
2267 return (error);
2268
2269 overfull:
2270 /*
2271 * Since we are using ring buffers, if we can't insert any more into
2272 * the output queue, we can assume the ring is full and that someone
2273 * forgot to set the high water mark correctly. We set it and then
2274 * proceed as normal.
2275 */
2276 hiwat = tp->t_outq.c_cc - 1;
2277
2278 ovhiwat:
2279 mutex_spin_enter(&tty_lock);
2280 ttstart(tp);
2281 /*
2282 * This can only occur if FLUSHO is set in t_lflag,
2283 * or if ttstart/oproc is synchronous (or very fast).
2284 */
2285 if (tp->t_outq.c_cc <= hiwat) {
2286 mutex_spin_exit(&tty_lock);
2287 goto loop;
2288 }
2289 if (flag & IO_NDELAY) {
2290 mutex_spin_exit(&tty_lock);
2291 error = EWOULDBLOCK;
2292 goto out;
2293 }
2294 error = ttysleep(tp, &tp->t_outcv, true, 0);
2295 mutex_spin_exit(&tty_lock);
2296 if (error)
2297 goto out;
2298 goto loop;
2299 }
2300
2301 /*
2302 * Try to pull more output from the producer. Return non-zero if
2303 * there is output ready to be sent.
2304 */
2305 bool
2306 ttypull(struct tty *tp)
2307 {
2308
2309 /* XXXSMP not yet KASSERT(mutex_owned(&tty_lock)); */
2310
2311 if (tp->t_outq.c_cc <= tp->t_lowat) {
2312 cv_broadcast(&tp->t_outcv);
2313 selnotify(&tp->t_wsel, 0, NOTE_SUBMIT);
2314 }
2315 return tp->t_outq.c_cc != 0;
2316 }
2317
2318 /*
2319 * Rubout one character from the rawq of tp
2320 * as cleanly as possible.
2321 * Called with tty lock held.
2322 */
2323 void
2324 ttyrub(int c, struct tty *tp)
2325 {
2326 u_char *cp;
2327 int savecol, tabc;
2328
2329 KASSERT(mutex_owned(&tty_lock));
2330
2331 if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
2332 return;
2333 CLR(tp->t_lflag, FLUSHO);
2334 if (ISSET(tp->t_lflag, ECHOE)) {
2335 if (tp->t_rocount == 0) {
2336 /*
2337 * Screwed by ttwrite; retype
2338 */
2339 ttyretype(tp);
2340 return;
2341 }
2342 if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
2343 ttyrubo(tp, 2);
2344 else {
2345 CLR(c, ~TTY_CHARMASK);
2346 switch (CCLASS(c)) {
2347 case ORDINARY:
2348 ttyrubo(tp, 1);
2349 break;
2350 case BACKSPACE:
2351 case CONTROL:
2352 case NEWLINE:
2353 case RETURN:
2354 case VTAB:
2355 if (ISSET(tp->t_lflag, ECHOCTL))
2356 ttyrubo(tp, 2);
2357 break;
2358 case TAB:
2359 if (tp->t_rocount < tp->t_rawq.c_cc) {
2360 ttyretype(tp);
2361 return;
2362 }
2363 savecol = tp->t_column;
2364 SET(tp->t_state, TS_CNTTB);
2365 SET(tp->t_lflag, FLUSHO);
2366 tp->t_column = tp->t_rocol;
2367 for (cp = firstc(&tp->t_rawq, &tabc); cp;
2368 cp = nextc(&tp->t_rawq, cp, &tabc))
2369 ttyecho(tabc, tp);
2370 CLR(tp->t_lflag, FLUSHO);
2371 CLR(tp->t_state, TS_CNTTB);
2372
2373 /* savecol will now be length of the tab. */
2374 savecol -= tp->t_column;
2375 tp->t_column += savecol;
2376 if (savecol > 8)
2377 savecol = 8; /* overflow screw */
2378 while (--savecol >= 0)
2379 (void)ttyoutput('\b', tp);
2380 break;
2381 default: /* XXX */
2382 (void)printf("ttyrub: would panic c = %d, "
2383 "val = %d\n", c, CCLASS(c));
2384 }
2385 }
2386 } else if (ISSET(tp->t_lflag, ECHOPRT)) {
2387 if (!ISSET(tp->t_state, TS_ERASE)) {
2388 SET(tp->t_state, TS_ERASE);
2389 (void)ttyoutput('\\', tp);
2390 }
2391 ttyecho(c, tp);
2392 } else
2393 ttyecho(tp->t_cc[VERASE], tp);
2394 --tp->t_rocount;
2395 }
2396
2397 /*
2398 * Back over cnt characters, erasing them.
2399 * Called with tty lock held.
2400 */
2401 static void
2402 ttyrubo(struct tty *tp, int cnt)
2403 {
2404
2405 KASSERT(mutex_owned(&tty_lock));
2406
2407 while (cnt-- > 0) {
2408 (void)ttyoutput('\b', tp);
2409 (void)ttyoutput(' ', tp);
2410 (void)ttyoutput('\b', tp);
2411 }
2412 }
2413
2414 /*
2415 * ttyretype --
2416 * Reprint the rawq line. Note, it is assumed that c_cc has already
2417 * been checked.
2418 *
2419 * Called with tty lock held.
2420 */
2421 void
2422 ttyretype(struct tty *tp)
2423 {
2424 u_char *cp;
2425 int c;
2426
2427 KASSERT(mutex_owned(&tty_lock));
2428
2429 /* Echo the reprint character. */
2430 if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
2431 ttyecho(tp->t_cc[VREPRINT], tp);
2432
2433 (void)ttyoutput('\n', tp);
2434
2435 for (cp = firstc(&tp->t_canq, &c); cp; cp = nextc(&tp->t_canq, cp, &c))
2436 ttyecho(c, tp);
2437 for (cp = firstc(&tp->t_rawq, &c); cp; cp = nextc(&tp->t_rawq, cp, &c))
2438 ttyecho(c, tp);
2439 CLR(tp->t_state, TS_ERASE);
2440
2441 tp->t_rocount = tp->t_rawq.c_cc;
2442 tp->t_rocol = 0;
2443 }
2444
2445 /*
2446 * Echo a typed character to the terminal.
2447 * Called with tty lock held.
2448 */
2449 static void
2450 ttyecho(int c, struct tty *tp)
2451 {
2452
2453 KASSERT(mutex_owned(&tty_lock));
2454
2455 if (!ISSET(tp->t_state, TS_CNTTB))
2456 CLR(tp->t_lflag, FLUSHO);
2457 if ((!ISSET(tp->t_lflag, ECHO) &&
2458 (!ISSET(tp->t_lflag, ECHONL) || c != '\n')) ||
2459 ISSET(tp->t_lflag, EXTPROC))
2460 return;
2461 if (((ISSET(tp->t_lflag, ECHOCTL) &&
2462 (ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n')) ||
2463 ISSET(c, TTY_CHARMASK) == 0177)) {
2464 (void)ttyoutput('^', tp);
2465 CLR(c, ~TTY_CHARMASK);
2466 if (c == 0177)
2467 c = '?';
2468 else
2469 c += 'A' - 1;
2470 }
2471 (void)ttyoutput(c, tp);
2472 }
2473
2474 /*
2475 * Wake up any readers on a tty.
2476 * Called with tty lock held.
2477 */
2478 void
2479 ttwakeup(struct tty *tp)
2480 {
2481
2482 KASSERT(mutex_owned(&tty_lock));
2483
2484 selnotify(&tp->t_rsel, 0, NOTE_SUBMIT);
2485 if (ISSET(tp->t_state, TS_ASYNC))
2486 ttysig(tp, TTYSIG_PG2, SIGIO);
2487 cv_broadcast(&tp->t_rawcv);
2488 }
2489
2490 /*
2491 * Look up a code for a specified speed in a conversion table;
2492 * used by drivers to map software speed values to hardware parameters.
2493 */
2494 int
2495 ttspeedtab(int speed, const struct speedtab *table)
2496 {
2497
2498 for (; table->sp_speed != -1; table++)
2499 if (table->sp_speed == speed)
2500 return (table->sp_code);
2501 return (-1);
2502 }
2503
2504 /*
2505 * Set tty hi and low water marks.
2506 *
2507 * Try to arrange the dynamics so there's about one second
2508 * from hi to low water.
2509 */
2510 void
2511 ttsetwater(struct tty *tp)
2512 {
2513 int cps, x;
2514
2515 /* XXX not yet KASSERT(mutex_owned(&tty_lock)); */
2516
2517 #define CLAMP(x, h, l) ((x) > h ? h : ((x) < l) ? l : (x))
2518
2519 cps = tp->t_ospeed / 10;
2520 tp->t_lowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
2521 x += cps;
2522 x = CLAMP(x, TTMAXHIWAT, TTMINHIWAT);
2523 tp->t_hiwat = roundup(x, TTROUND);
2524 #undef CLAMP
2525 }
2526
2527 /*
2528 * Prepare report on state of foreground process group.
2529 * Call with &proc_lock held.
2530 */
2531 void
2532 ttygetinfo(struct tty *tp, int fromsig, char *buf, size_t bufsz)
2533 {
2534 struct lwp *l;
2535 struct proc *p, *pick = NULL;
2536 struct timeval utime, stime;
2537 int tmp;
2538 fixpt_t pctcpu = 0;
2539 const char *msg = NULL;
2540 char lmsg[100];
2541 long rss;
2542 bool again = false;
2543
2544 KASSERT(mutex_owned(&proc_lock));
2545
2546 *buf = '\0';
2547
2548 retry:
2549 if (tp->t_session == NULL)
2550 msg = "not a controlling terminal\n";
2551 else if (tp->t_pgrp == NULL)
2552 msg = "no foreground process group\n";
2553 else if ((p = LIST_FIRST(&tp->t_pgrp->pg_members)) == NULL)
2554 msg = "empty foreground process group\n";
2555 else {
2556 /* Pick interesting process. */
2557 for (; p != NULL; p = LIST_NEXT(p, p_pglist)) {
2558 struct proc *oldpick;
2559
2560 if (pick == NULL) {
2561 pick = p;
2562 continue;
2563 }
2564 if (pick->p_lock < p->p_lock) {
2565 mutex_enter(pick->p_lock);
2566 mutex_enter(p->p_lock);
2567 } else if (pick->p_lock > p->p_lock) {
2568 mutex_enter(p->p_lock);
2569 mutex_enter(pick->p_lock);
2570 } else
2571 mutex_enter(p->p_lock);
2572 oldpick = pick;
2573 if (proc_compare_wrapper(pick, p))
2574 pick = p;
2575 mutex_exit(p->p_lock);
2576 if (p->p_lock != oldpick->p_lock)
2577 mutex_exit(oldpick->p_lock);
2578 }
2579
2580 if (pick != NULL) {
2581 mutex_enter(pick->p_lock);
2582 if (P_ZOMBIE(pick)) {
2583 mutex_exit(pick->p_lock);
2584 pick = NULL;
2585 if (!again) {
2586 again = true;
2587 goto retry;
2588 }
2589 msg = "found only zombie processes\n";
2590 }
2591 if (pick && fromsig &&
2592 (SIGACTION_PS(pick->p_sigacts, SIGINFO).sa_flags &
2593 SA_NOKERNINFO)) {
2594 mutex_exit(pick->p_lock);
2595 return;
2596 }
2597 }
2598 }
2599
2600 /* Print load average. */
2601 tmp = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
2602 snprintf(lmsg, sizeof(lmsg), "load: %d.%02d ", tmp / 100, tmp % 100);
2603 strlcat(buf, lmsg, bufsz);
2604
2605 if (pick == NULL) {
2606 strlcat(buf, msg, bufsz);
2607 return;
2608 }
2609
2610 snprintf(lmsg, sizeof(lmsg), " cmd: %s %d [", pick->p_comm,
2611 pick->p_pid);
2612 strlcat(buf, lmsg, bufsz);
2613
2614 KASSERT(mutex_owned(pick->p_lock));
2615 LIST_FOREACH(l, &pick->p_lwps, l_sibling) {
2616 const char *lp;
2617 lwp_lock(l);
2618 #ifdef LWP_PC
2619 #define FMT_RUN "%#"PRIxVADDR
2620 #define VAL_RUNNING (vaddr_t)LWP_PC(l)
2621 #define VAL_RUNNABLE (vaddr_t)LWP_PC(l)
2622 #else
2623 #define FMT_RUN "%s"
2624 #define VAL_RUNNING "running"
2625 #define VAL_RUNNABLE "runnable"
2626 #endif
2627 switch (l->l_stat) {
2628 case LSONPROC:
2629 snprintf(lmsg, sizeof(lmsg), FMT_RUN"/%d", VAL_RUNNING,
2630 cpu_index(l->l_cpu));
2631 lp = lmsg;
2632 break;
2633 case LSRUN:
2634 snprintf(lmsg, sizeof(lmsg), FMT_RUN, VAL_RUNNABLE);
2635 lp = lmsg;
2636 break;
2637 default:
2638 lp = l->l_wchan ? l->l_wmesg : "iowait";
2639 break;
2640 }
2641 strlcat(buf, lp, bufsz);
2642 strlcat(buf, LIST_NEXT(l, l_sibling) != NULL ? " " : "] ",
2643 bufsz);
2644 pctcpu += l->l_pctcpu;
2645 lwp_unlock(l);
2646 }
2647 pctcpu += pick->p_pctcpu;
2648 calcru(pick, &utime, &stime, NULL, NULL);
2649 mutex_exit(pick->p_lock);
2650
2651 /* Round up and print user+system time, %CPU and RSS. */
2652 utime.tv_usec += 5000;
2653 if (utime.tv_usec >= 1000000) {
2654 utime.tv_sec += 1;
2655 utime.tv_usec -= 1000000;
2656 }
2657 stime.tv_usec += 5000;
2658 if (stime.tv_usec >= 1000000) {
2659 stime.tv_sec += 1;
2660 stime.tv_usec -= 1000000;
2661 }
2662 #define pgtok(a) (((u_long) ((a) * PAGE_SIZE) / 1024))
2663 tmp = (pctcpu * 10000 + FSCALE / 2) >> FSHIFT;
2664 if (pick->p_stat == SIDL || P_ZOMBIE(pick))
2665 rss = 0;
2666 else
2667 rss = pgtok(vm_resident_count(pick->p_vmspace));
2668
2669 snprintf(lmsg, sizeof(lmsg), "%ld.%02ldu %ld.%02lds %d%% %ldk",
2670 (long)utime.tv_sec, (long)utime.tv_usec / 10000,
2671 (long)stime.tv_sec, (long)stime.tv_usec / 10000,
2672 tmp / 100, rss);
2673 strlcat(buf, lmsg, bufsz);
2674 }
2675
2676 /*
2677 * Print report on state of foreground process group.
2678 * Call with tty_lock held.
2679 */
2680 void
2681 ttyputinfo(struct tty *tp, char *buf)
2682 {
2683
2684 KASSERT(mutex_owned(&tty_lock));
2685
2686 if (ttycheckoutq_wlock(tp, 0) == 0)
2687 return;
2688 ttyprintf_nolock(tp, "%s\n", buf);
2689 tp->t_rocount = 0; /* so pending input will be retyped if BS */
2690 }
2691
2692 /*
2693 * Returns 1 if p2 has a better chance being the active foreground process
2694 * in a terminal instead of p1.
2695 */
2696 static int
2697 proc_compare_wrapper(struct proc *p1, struct proc *p2)
2698 {
2699 lwp_t *l1, *l2;
2700
2701 KASSERT(mutex_owned(p1->p_lock));
2702 KASSERT(mutex_owned(p2->p_lock));
2703
2704 l1 = LIST_FIRST(&p1->p_lwps);
2705 l2 = LIST_FIRST(&p2->p_lwps);
2706
2707 return proc_compare(p1, l1, p2, l2);
2708 }
2709
2710 /*
2711 * Output char to tty; console putchar style.
2712 * Can be called with tty lock held through kprintf() machinery..
2713 */
2714 int
2715 tputchar(int c, int flags, struct tty *tp)
2716 {
2717 int r = 0;
2718
2719 if ((flags & NOLOCK) == 0)
2720 mutex_spin_enter(&tty_lock);
2721 if (!CONNECTED(tp)) {
2722 r = -1;
2723 goto out;
2724 }
2725 if (c == '\n')
2726 (void)ttyoutput('\r', tp);
2727 (void)ttyoutput(c, tp);
2728 ttstart(tp);
2729 out:
2730 if ((flags & NOLOCK) == 0)
2731 mutex_spin_exit(&tty_lock);
2732 return (r);
2733 }
2734
2735 /*
2736 * Sleep on chan, returning ERESTART if tty changed while we napped and
2737 * returning any errors (e.g. EINTR/EWOULDBLOCK) reported by
2738 * cv_timedwait(_sig).
2739 * If the tty is revoked, restarting a pending call will redo validation done
2740 * at the start of the call.
2741 *
2742 * Must be called with the tty lock held.
2743 */
2744 int
2745 ttysleep(struct tty *tp, kcondvar_t *cv, bool catch_p, int timo)
2746 {
2747 int error;
2748 short gen;
2749
2750 KASSERT(mutex_owned(&tty_lock));
2751
2752 gen = tp->t_gen;
2753 if (cv == NULL)
2754 error = kpause("ttypause", catch_p, timo, &tty_lock);
2755 else if (catch_p)
2756 error = cv_timedwait_sig(cv, &tty_lock, timo);
2757 else
2758 error = cv_timedwait(cv, &tty_lock, timo);
2759 if (error != 0)
2760 return (error);
2761 return (tp->t_gen == gen ? 0 : ERESTART);
2762 }
2763
2764 int
2765 ttypause(struct tty *tp, int timo)
2766 {
2767 int error;
2768
2769 error = ttysleep(tp, NULL, true, timo);
2770 if (error == EWOULDBLOCK)
2771 error = 0;
2772 return error;
2773 }
2774
2775 /*
2776 * Attach a tty to the tty list.
2777 *
2778 * This should be called ONLY once per real tty (including pty's).
2779 * eg, on the sparc, the keyboard and mouse have struct tty's that are
2780 * distinctly NOT usable as tty's, and thus should not be attached to
2781 * the ttylist. This is why this call is not done from tty_alloc().
2782 *
2783 * Device drivers should attach tty's at a similar time that they are
2784 * allocated, or, for the case of statically allocated struct tty's
2785 * either in the attach or (first) open routine.
2786 */
2787 void
2788 tty_attach(struct tty *tp)
2789 {
2790
2791 mutex_spin_enter(&tty_lock);
2792 TAILQ_INSERT_TAIL(&ttylist, tp, tty_link);
2793 ++tty_count;
2794 mutex_spin_exit(&tty_lock);
2795 }
2796
2797 /*
2798 * Remove a tty from the tty list.
2799 */
2800 void
2801 tty_detach(struct tty *tp)
2802 {
2803
2804 mutex_spin_enter(&tty_lock);
2805 --tty_count;
2806 #ifdef DIAGNOSTIC
2807 if (tty_count < 0)
2808 panic("tty_detach: tty_count < 0");
2809 #endif
2810 TAILQ_REMOVE(&ttylist, tp, tty_link);
2811 mutex_spin_exit(&tty_lock);
2812 }
2813
2814 /*
2815 * Allocate a tty structure and its associated buffers.
2816 */
2817 struct tty *
2818 tty_alloc(void)
2819 {
2820 struct tty *tp;
2821 int i;
2822
2823 tp = kmem_zalloc(sizeof(*tp), KM_SLEEP);
2824 callout_init(&tp->t_rstrt_ch, 0);
2825 callout_setfunc(&tp->t_rstrt_ch, ttrstrt, tp);
2826 tp->t_qsize = tty_qsize;
2827 clalloc(&tp->t_rawq, tp->t_qsize, 1);
2828 cv_init(&tp->t_rawcv, "ttyraw");
2829 cv_init(&tp->t_rawcvf, "ttyrawf");
2830 clalloc(&tp->t_canq, tp->t_qsize, 1);
2831 cv_init(&tp->t_cancv, "ttycan");
2832 cv_init(&tp->t_cancvf, "ttycanf");
2833 /* output queue doesn't need quoting */
2834 clalloc(&tp->t_outq, tp->t_qsize, 0);
2835 cv_init(&tp->t_outcv, "ttyout");
2836 cv_init(&tp->t_outcvf, "ttyoutf");
2837 /* Set default line discipline. */
2838 tp->t_linesw = ttyldisc_default();
2839 tp->t_dev = NODEV;
2840 selinit(&tp->t_rsel);
2841 selinit(&tp->t_wsel);
2842 for (i = 0; i < TTYSIG_COUNT; i++) {
2843 sigemptyset(&tp->t_sigs[i]);
2844 }
2845
2846 return tp;
2847 }
2848
2849 /*
2850 * Free a tty structure and its buffers.
2851 *
2852 * Be sure to call tty_detach() for any tty that has been
2853 * tty_attach()ed.
2854 */
2855 void
2856 tty_free(struct tty *tp)
2857 {
2858 int i;
2859
2860 mutex_enter(&proc_lock);
2861 mutex_enter(&tty_lock);
2862 for (i = 0; i < TTYSIG_COUNT; i++)
2863 sigemptyset(&tp->t_sigs[i]);
2864 if (tp->t_sigcount != 0)
2865 TAILQ_REMOVE(&tty_sigqueue, tp, t_sigqueue);
2866 mutex_exit(&tty_lock);
2867 mutex_exit(&proc_lock);
2868
2869 callout_halt(&tp->t_rstrt_ch, NULL);
2870 callout_destroy(&tp->t_rstrt_ch);
2871 ttyldisc_release(tp->t_linesw);
2872 clfree(&tp->t_rawq);
2873 clfree(&tp->t_canq);
2874 clfree(&tp->t_outq);
2875 cv_destroy(&tp->t_rawcv);
2876 cv_destroy(&tp->t_rawcvf);
2877 cv_destroy(&tp->t_cancv);
2878 cv_destroy(&tp->t_cancvf);
2879 cv_destroy(&tp->t_outcv);
2880 cv_destroy(&tp->t_outcvf);
2881 seldestroy(&tp->t_rsel);
2882 seldestroy(&tp->t_wsel);
2883 kmem_free(tp, sizeof(*tp));
2884 }
2885
2886 /*
2887 * ttyprintf_nolock: send a message to a specific tty, without locking.
2888 *
2889 * => should be used only by tty driver or anything that knows the
2890 * underlying tty will not be revoked(2)'d away. [otherwise,
2891 * use tprintf]
2892 */
2893 static void
2894 ttyprintf_nolock(struct tty *tp, const char *fmt, ...)
2895 {
2896 va_list ap;
2897
2898 /* No mutex needed; going to process TTY. */
2899 va_start(ap, fmt);
2900 kprintf(fmt, TOTTY|NOLOCK, tp, NULL, ap);
2901 va_end(ap);
2902 }
2903
2904 static int
2905 tty_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
2906 void *arg0, void *arg1, void *arg2, void *arg3)
2907 {
2908 struct tty *tty;
2909 int result;
2910
2911 result = KAUTH_RESULT_DEFER;
2912
2913 if (action != KAUTH_DEVICE_TTY_OPEN)
2914 return result;
2915
2916 tty = arg0;
2917
2918 /* If it's not opened, we allow. */
2919 if ((tty->t_state & TS_ISOPEN) == 0)
2920 result = KAUTH_RESULT_ALLOW;
2921 else {
2922 /*
2923 * If it's opened, we can only allow if it's not exclusively
2924 * opened; otherwise, that's a privileged operation and we
2925 * let the secmodel handle it.
2926 */
2927 if ((tty->t_state & TS_XCLUDE) == 0)
2928 result = KAUTH_RESULT_ALLOW;
2929 }
2930
2931 return result;
2932 }
2933
2934 /*
2935 * Initialize the tty subsystem.
2936 */
2937 void
2938 tty_init(void)
2939 {
2940
2941 mutex_init(&tty_lock, MUTEX_DEFAULT, IPL_VM);
2942 tty_sigsih = softint_establish(SOFTINT_CLOCK, ttysigintr, NULL);
2943 KASSERT(tty_sigsih != NULL);
2944
2945 tty_listener = kauth_listen_scope(KAUTH_SCOPE_DEVICE,
2946 tty_listener_cb, NULL);
2947
2948 sysctl_kern_tty_setup();
2949 }
2950
2951 /*
2952 * Send a signal from a tty to its process group or session leader.
2953 * Handoff to the target is deferred to a soft interrupt.
2954 */
2955 void
2956 ttysig(struct tty *tp, enum ttysigtype st, int sig)
2957 {
2958 sigset_t *sp;
2959
2960 /* XXXSMP not yet KASSERT(mutex_owned(&tty_lock)); */
2961
2962 sp = &tp->t_sigs[st];
2963 if (sigismember(sp, sig))
2964 return;
2965 sigaddset(sp, sig);
2966 if (tp->t_sigcount++ == 0)
2967 TAILQ_INSERT_TAIL(&tty_sigqueue, tp, t_sigqueue);
2968 softint_schedule(tty_sigsih);
2969 }
2970
2971 /*
2972 * Deliver deferred signals from ttys. Note that the process groups
2973 * and sessions associated with the ttys may have changed from when
2974 * the signal was originally sent, but in practice it should not matter.
2975 * For signals produced as a result of a syscall, the soft interrupt
2976 * will fire before the syscall returns to the user.
2977 */
2978 static void
2979 ttysigintr(void *cookie)
2980 {
2981 struct tty *tp;
2982 enum ttysigtype st;
2983 struct pgrp *pgrp;
2984 struct session *sess;
2985 int sig, lflag;
2986 char infobuf[200];
2987
2988 mutex_enter(&proc_lock);
2989 mutex_spin_enter(&tty_lock);
2990 while ((tp = TAILQ_FIRST(&tty_sigqueue)) != NULL) {
2991 KASSERT(tp->t_sigcount > 0);
2992 for (st = TTYSIG_PG1; st < TTYSIG_COUNT; st++) {
2993 if ((sig = firstsig(&tp->t_sigs[st])) != 0)
2994 break;
2995 }
2996 KASSERT(st < TTYSIG_COUNT);
2997 sigdelset(&tp->t_sigs[st], sig);
2998 if (--tp->t_sigcount == 0)
2999 TAILQ_REMOVE(&tty_sigqueue, tp, t_sigqueue);
3000 pgrp = tp->t_pgrp;
3001 sess = tp->t_session;
3002 lflag = tp->t_lflag;
3003 if (sig == SIGINFO) {
3004 if (ISSET(tp->t_state, TS_SIGINFO)) {
3005 /* Via ioctl: ignore tty option. */
3006 tp->t_state &= ~TS_SIGINFO;
3007 lflag |= ISIG;
3008 }
3009 if (!ISSET(lflag, NOKERNINFO)) {
3010 mutex_spin_exit(&tty_lock);
3011 ttygetinfo(tp, 1, infobuf, sizeof(infobuf));
3012 mutex_spin_enter(&tty_lock);
3013 ttyputinfo(tp, infobuf);
3014 }
3015 if (!ISSET(lflag, ISIG))
3016 continue;
3017 }
3018 mutex_spin_exit(&tty_lock);
3019 KASSERT(sig != 0);
3020 switch (st) {
3021 case TTYSIG_PG1:
3022 if (pgrp != NULL)
3023 pgsignal(pgrp, sig, 1);
3024 break;
3025 case TTYSIG_PG2:
3026 if (pgrp != NULL)
3027 pgsignal(pgrp, sig, sess != NULL);
3028 break;
3029 case TTYSIG_LEADER:
3030 if (sess != NULL && sess->s_leader != NULL)
3031 psignal(sess->s_leader, sig);
3032 break;
3033 default:
3034 /* NOTREACHED */
3035 break;
3036 }
3037 mutex_spin_enter(&tty_lock);
3038 }
3039 mutex_spin_exit(&tty_lock);
3040 mutex_exit(&proc_lock);
3041 }
3042
3043 unsigned char
3044 tty_getctrlchar(struct tty *tp, unsigned which)
3045 {
3046 KASSERT(which < NCCS);
3047 return tp->t_cc[which];
3048 }
3049
3050 void
3051 tty_setctrlchar(struct tty *tp, unsigned which, unsigned char val)
3052 {
3053 KASSERT(which < NCCS);
3054 tp->t_cc[which] = val;
3055 }
3056
3057 int
3058 tty_try_xonxoff(struct tty *tp, unsigned char c)
3059 {
3060 const struct cdevsw *cdev;
3061
3062 if (tp->t_iflag & IXON) {
3063 if (c == tp->t_cc[VSTOP] && tp->t_cc[VSTOP] != _POSIX_VDISABLE) {
3064 if ((tp->t_state & TS_TTSTOP) == 0) {
3065 tp->t_state |= TS_TTSTOP;
3066 cdev = cdevsw_lookup(tp->t_dev);
3067 if (cdev != NULL)
3068 (*cdev->d_stop)(tp, 0);
3069 }
3070 return 0;
3071 }
3072 if (c == tp->t_cc[VSTART] && tp->t_cc[VSTART] != _POSIX_VDISABLE) {
3073 tp->t_state &= ~TS_TTSTOP;
3074 if (tp->t_oproc != NULL) {
3075 mutex_spin_enter(&tty_lock); /* XXX */
3076 (*tp->t_oproc)(tp);
3077 mutex_spin_exit(&tty_lock); /* XXX */
3078 }
3079 return 0;
3080 }
3081 }
3082 return EAGAIN;
3083 }
3084