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