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