tty.c revision 1.128.2.7 1 /* $NetBSD: tty.c,v 1.128.2.7 2002/02/11 20:10:24 jdolecek Exp $ */
2
3 /*-
4 * Copyright (c) 1982, 1986, 1990, 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. All advertising materials mentioning features or use of this software
21 * must display the following acknowledgement:
22 * This product includes software developed by the University of
23 * California, Berkeley and its contributors.
24 * 4. Neither the name of the University nor the names of its contributors
25 * may be used to endorse or promote products derived from this software
26 * without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * SUCH DAMAGE.
39 *
40 * @(#)tty.c 8.13 (Berkeley) 1/9/95
41 */
42
43 #include <sys/cdefs.h>
44 __KERNEL_RCSID(0, "$NetBSD: tty.c,v 1.128.2.7 2002/02/11 20:10:24 jdolecek Exp $");
45
46 #include "opt_uconsole.h"
47
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/ioctl.h>
51 #include <sys/proc.h>
52 #define TTYDEFCHARS
53 #include <sys/tty.h>
54 #undef TTYDEFCHARS
55 #include <sys/file.h>
56 #include <sys/conf.h>
57 #include <sys/dkstat.h>
58 #include <sys/uio.h>
59 #include <sys/kernel.h>
60 #include <sys/vnode.h>
61 #include <sys/syslog.h>
62 #include <sys/malloc.h>
63 #include <sys/pool.h>
64 #include <sys/signalvar.h>
65 #include <sys/resourcevar.h>
66 #include <sys/poll.h>
67
68 static int filt_ttyread(struct knote *kn, long hint);
69 static void filt_ttyrdetach(struct knote *kn);
70 static int filt_ttywrite(struct knote *kn, long hint);
71 static void filt_ttywdetach(struct knote *kn);
72 static int ttnread(struct tty *);
73 static void ttyblock(struct tty *);
74 static void ttyecho(int, struct tty *);
75 static void ttyrubo(struct tty *, int);
76 static int proc_compare(struct proc *, struct proc *);
77
78 /* Symbolic sleep message strings. */
79 const char ttclos[] = "ttycls";
80 const char ttopen[] = "ttyopn";
81 const char ttybg[] = "ttybg";
82 const char ttyin[] = "ttyin";
83 const char ttyout[] = "ttyout";
84
85 /*
86 * Used to determine whether we still have a connection. This is true in
87 * one of 3 cases:
88 * 1) We have carrier.
89 * 2) It's a locally attached terminal, and we are therefore ignoring carrier.
90 * 3) We're using a flow control mechanism that overloads the carrier signal.
91 */
92 #define CONNECTED(tp) (ISSET(tp->t_state, TS_CARR_ON) || \
93 ISSET(tp->t_cflag, CLOCAL | MDMBUF))
94
95 /*
96 * Table with character classes and parity. The 8th bit indicates parity,
97 * the 7th bit indicates the character is an alphameric or underscore (for
98 * ALTWERASE), and the low 6 bits indicate delay type. If the low 6 bits
99 * are 0 then the character needs no special processing on output; classes
100 * other than 0 might be translated or (not currently) require delays.
101 */
102 #define E 0x00 /* Even parity. */
103 #define O 0x80 /* Odd parity. */
104 #define PARITY(c) (char_type[c] & O)
105
106 #define ALPHA 0x40 /* Alpha or underscore. */
107 #define ISALPHA(c) (char_type[(c) & TTY_CHARMASK] & ALPHA)
108
109 #define CCLASSMASK 0x3f
110 #define CCLASS(c) (char_type[c] & CCLASSMASK)
111
112 #define BS BACKSPACE
113 #define CC CONTROL
114 #define CR RETURN
115 #define NA ORDINARY | ALPHA
116 #define NL NEWLINE
117 #define NO ORDINARY
118 #define TB TAB
119 #define VT VTAB
120
121 char const char_type[] = {
122 E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC, /* nul - bel */
123 O|BS, E|TB, E|NL, O|CC, E|VT, O|CR, O|CC, E|CC, /* bs - si */
124 O|CC, E|CC, E|CC, O|CC, E|CC, O|CC, O|CC, E|CC, /* dle - etb */
125 E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC, /* can - us */
126 O|NO, E|NO, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* sp - ' */
127 E|NO, O|NO, O|NO, E|NO, O|NO, E|NO, E|NO, O|NO, /* ( - / */
128 E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* 0 - 7 */
129 O|NA, E|NA, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* 8 - ? */
130 O|NO, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* @ - G */
131 E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* H - O */
132 E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* P - W */
133 O|NA, E|NA, E|NA, O|NO, E|NO, O|NO, O|NO, O|NA, /* X - _ */
134 E|NO, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* ` - g */
135 O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* h - o */
136 O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* p - w */
137 E|NA, O|NA, O|NA, E|NO, O|NO, E|NO, E|NO, O|CC, /* x - del */
138 /*
139 * Meta chars; should be settable per character set;
140 * for now, treat them all as normal characters.
141 */
142 NA, NA, NA, NA, NA, NA, NA, NA,
143 NA, NA, NA, NA, NA, NA, NA, NA,
144 NA, NA, NA, NA, NA, NA, NA, NA,
145 NA, NA, NA, NA, NA, NA, NA, NA,
146 NA, NA, NA, NA, NA, NA, NA, NA,
147 NA, NA, NA, NA, NA, NA, NA, NA,
148 NA, NA, NA, NA, NA, NA, NA, NA,
149 NA, NA, NA, NA, NA, NA, NA, NA,
150 NA, NA, NA, NA, NA, NA, NA, NA,
151 NA, NA, NA, NA, NA, NA, NA, NA,
152 NA, NA, NA, NA, NA, NA, NA, NA,
153 NA, NA, NA, NA, NA, NA, NA, NA,
154 NA, NA, NA, NA, NA, NA, NA, NA,
155 NA, NA, NA, NA, NA, NA, NA, NA,
156 NA, NA, NA, NA, NA, NA, NA, NA,
157 NA, NA, NA, NA, NA, NA, NA, NA,
158 };
159 #undef BS
160 #undef CC
161 #undef CR
162 #undef NA
163 #undef NL
164 #undef NO
165 #undef TB
166 #undef VT
167
168 /* Macros to clear/set/test flags. */
169 #define SET(t, f) (t) |= (f)
170 #define CLR(t, f) (t) &= ~((unsigned)(f))
171 #define ISSET(t, f) ((t) & (f))
172
173 struct ttylist_head ttylist; /* TAILQ_HEAD */
174 int tty_count;
175
176 struct pool tty_pool;
177
178 u_int64_t tk_cancc;
179 u_int64_t tk_nin;
180 u_int64_t tk_nout;
181 u_int64_t tk_rawcc;
182
183 int
184 ttyopen(struct tty *tp, int dialout, int nonblock)
185 {
186 int s, error;
187
188 s = spltty();
189
190 if (dialout) {
191 /*
192 * If the device is already open for non-dialout, fail.
193 * Otherwise, set TS_DIALOUT to block any pending non-dialout
194 * opens.
195 */
196 if (ISSET(tp->t_state, TS_ISOPEN) &&
197 !ISSET(tp->t_state, TS_DIALOUT)) {
198 splx(s);
199 return (EBUSY);
200 }
201 SET(tp->t_state, TS_DIALOUT);
202 } else {
203 if (!nonblock) {
204 /*
205 * Wait for carrier. Also wait for any dialout
206 * processes to close the tty first.
207 */
208 while (ISSET(tp->t_state, TS_DIALOUT) ||
209 (!ISSET(tp->t_state, TS_CARR_ON) &&
210 !ISSET(tp->t_cflag, CLOCAL | MDMBUF))) {
211 tp->t_wopen++;
212 error = ttysleep(tp, &tp->t_rawq,
213 TTIPRI | PCATCH, ttopen, 0);
214 tp->t_wopen--;
215 if (error) {
216 splx(s);
217 return (error);
218 }
219 }
220 } else {
221 /*
222 * Don't allow a non-blocking non-dialout open if the
223 * device is already open for dialout.
224 */
225 if (ISSET(tp->t_state, TS_DIALOUT)) {
226 splx(s);
227 return (EBUSY);
228 }
229 }
230 }
231
232 splx(s);
233 return (0);
234 }
235
236 /*
237 * Initial open of tty, or (re)entry to standard tty line discipline.
238 */
239 int
240 ttylopen(dev_t device, struct tty *tp)
241 {
242 int s;
243
244 s = spltty();
245 tp->t_dev = device;
246 if (!ISSET(tp->t_state, TS_ISOPEN)) {
247 SET(tp->t_state, TS_ISOPEN);
248 memset(&tp->t_winsize, 0, sizeof(tp->t_winsize));
249 #ifdef COMPAT_OLDTTY
250 tp->t_flags = 0;
251 #endif
252 }
253 splx(s);
254 return (0);
255 }
256
257 /*
258 * Handle close() on a tty line: flush and set to initial state,
259 * bumping generation number so that pending read/write calls
260 * can detect recycling of the tty.
261 */
262 int
263 ttyclose(struct tty *tp)
264 {
265 extern struct tty *constty; /* Temporary virtual console. */
266
267 if (constty == tp)
268 constty = NULL;
269
270 ttyflush(tp, FREAD | FWRITE);
271
272 tp->t_gen++;
273 tp->t_pgrp = NULL;
274 tp->t_session = NULL;
275 tp->t_state = 0;
276 return (0);
277 }
278
279 #define FLUSHQ(q) { \
280 if ((q)->c_cc) \
281 ndflush(q, (q)->c_cc); \
282 }
283
284 /*
285 * This macro is used in canonical mode input processing, where a read
286 * request shall not return unless a 'line delimiter' ('\n') or 'break'
287 * (EOF, EOL, EOL2) character (or a signal) has been received. As EOL2
288 * is an extension to the POSIX.1 defined set of special characters,
289 * recognize it only if IEXTEN is set in the set of local flags.
290 */
291 #define TTBREAKC(c, lflg) \
292 ((c) == '\n' || (((c) == cc[VEOF] || (c) == cc[VEOL] || \
293 ((c) == cc[VEOL2] && ISSET(lflg, IEXTEN))) && (c) != _POSIX_VDISABLE))
294
295
296 /*
297 * Process input of a single character received on a tty.
298 */
299 int
300 ttyinput(int c, struct tty *tp)
301 {
302 int iflag, lflag, i, error;
303 u_char *cc;
304
305 /*
306 * Unless the receiver is enabled, drop incoming data.
307 */
308 if (!ISSET(tp->t_cflag, CREAD))
309 return (0);
310
311 /*
312 * If input is pending take it first.
313 */
314 lflag = tp->t_lflag;
315 if (ISSET(lflag, PENDIN))
316 ttypend(tp);
317 /*
318 * Gather stats.
319 */
320 if (ISSET(lflag, ICANON)) {
321 ++tk_cancc;
322 ++tp->t_cancc;
323 } else {
324 ++tk_rawcc;
325 ++tp->t_rawcc;
326 }
327 ++tk_nin;
328
329 cc = tp->t_cc;
330
331 /*
332 * Handle exceptional conditions (break, parity, framing).
333 */
334 iflag = tp->t_iflag;
335 if ((error = (ISSET(c, TTY_ERRORMASK))) != 0) {
336 CLR(c, TTY_ERRORMASK);
337 if (ISSET(error, TTY_FE) && c == 0) { /* Break. */
338 if (ISSET(iflag, IGNBRK))
339 return (0);
340 else if (ISSET(iflag, BRKINT)) {
341 ttyflush(tp, FREAD | FWRITE);
342 pgsignal(tp->t_pgrp, SIGINT, 1);
343 return (0);
344 }
345 else if (ISSET(iflag, PARMRK))
346 goto parmrk;
347 }
348 else if ((ISSET(error, TTY_PE) && ISSET(iflag, INPCK)) ||
349 ISSET(error, TTY_FE)) {
350 if (ISSET(iflag, IGNPAR))
351 return (0);
352 else if (ISSET(iflag, PARMRK)) {
353 parmrk: (void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
354 (void)putc(0 | TTY_QUOTE, &tp->t_rawq);
355 (void)putc(c | TTY_QUOTE, &tp->t_rawq);
356 return (0);
357 }
358 else
359 c = 0;
360 }
361 }
362 else if (c == 0377 &&
363 ISSET(iflag, ISTRIP|IGNPAR|INPCK|PARMRK) == (INPCK|PARMRK)) {
364 /* "Escape" a valid character of '\377'. */
365 (void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
366 (void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
367 goto endcase;
368 }
369
370 /*
371 * In tandem mode, check high water mark.
372 */
373 if (ISSET(iflag, IXOFF) || ISSET(tp->t_cflag, CHWFLOW))
374 ttyblock(tp);
375 if (!ISSET(tp->t_state, TS_TYPEN) && ISSET(iflag, ISTRIP))
376 CLR(c, 0x80);
377 if (!ISSET(lflag, EXTPROC)) {
378 /*
379 * Check for literal nexting very first
380 */
381 if (ISSET(tp->t_state, TS_LNCH)) {
382 SET(c, TTY_QUOTE);
383 CLR(tp->t_state, TS_LNCH);
384 }
385 /*
386 * Scan for special characters. This code
387 * is really just a big case statement with
388 * non-constant cases. The bottom of the
389 * case statement is labeled ``endcase'', so goto
390 * it after a case match, or similar.
391 */
392
393 /*
394 * Control chars which aren't controlled
395 * by ICANON, ISIG, or IXON.
396 */
397 if (ISSET(lflag, IEXTEN)) {
398 if (CCEQ(cc[VLNEXT], c)) {
399 if (ISSET(lflag, ECHO)) {
400 if (ISSET(lflag, ECHOE)) {
401 (void)ttyoutput('^', tp);
402 (void)ttyoutput('\b', tp);
403 } else
404 ttyecho(c, tp);
405 }
406 SET(tp->t_state, TS_LNCH);
407 goto endcase;
408 }
409 if (CCEQ(cc[VDISCARD], c)) {
410 if (ISSET(lflag, FLUSHO))
411 CLR(tp->t_lflag, FLUSHO);
412 else {
413 ttyflush(tp, FWRITE);
414 ttyecho(c, tp);
415 if (tp->t_rawq.c_cc + tp->t_canq.c_cc)
416 ttyretype(tp);
417 SET(tp->t_lflag, FLUSHO);
418 }
419 goto startoutput;
420 }
421 }
422 /*
423 * Signals.
424 */
425 if (ISSET(lflag, ISIG)) {
426 if (CCEQ(cc[VINTR], c) || CCEQ(cc[VQUIT], c)) {
427 if (!ISSET(lflag, NOFLSH))
428 ttyflush(tp, FREAD | FWRITE);
429 ttyecho(c, tp);
430 pgsignal(tp->t_pgrp,
431 CCEQ(cc[VINTR], c) ? SIGINT : SIGQUIT, 1);
432 goto endcase;
433 }
434 if (CCEQ(cc[VSUSP], c)) {
435 if (!ISSET(lflag, NOFLSH))
436 ttyflush(tp, FREAD);
437 ttyecho(c, tp);
438 pgsignal(tp->t_pgrp, SIGTSTP, 1);
439 goto endcase;
440 }
441 }
442 /*
443 * Handle start/stop characters.
444 */
445 if (ISSET(iflag, IXON)) {
446 if (CCEQ(cc[VSTOP], c)) {
447 if (!ISSET(tp->t_state, TS_TTSTOP)) {
448 SET(tp->t_state, TS_TTSTOP);
449 (*cdevsw[major(tp->t_dev)].d_stop)(tp,
450 0);
451 return (0);
452 }
453 if (!CCEQ(cc[VSTART], c))
454 return (0);
455 /*
456 * if VSTART == VSTOP then toggle
457 */
458 goto endcase;
459 }
460 if (CCEQ(cc[VSTART], c))
461 goto restartoutput;
462 }
463 /*
464 * IGNCR, ICRNL, & INLCR
465 */
466 if (c == '\r') {
467 if (ISSET(iflag, IGNCR))
468 goto endcase;
469 else if (ISSET(iflag, ICRNL))
470 c = '\n';
471 } else if (c == '\n' && ISSET(iflag, INLCR))
472 c = '\r';
473 }
474 if (!ISSET(tp->t_lflag, EXTPROC) && ISSET(lflag, ICANON)) {
475 /*
476 * From here on down canonical mode character
477 * processing takes place.
478 */
479 /*
480 * erase (^H / ^?)
481 */
482 if (CCEQ(cc[VERASE], c)) {
483 if (tp->t_rawq.c_cc)
484 ttyrub(unputc(&tp->t_rawq), tp);
485 goto endcase;
486 }
487 /*
488 * kill (^U)
489 */
490 if (CCEQ(cc[VKILL], c)) {
491 if (ISSET(lflag, ECHOKE) &&
492 tp->t_rawq.c_cc == tp->t_rocount &&
493 !ISSET(lflag, ECHOPRT))
494 while (tp->t_rawq.c_cc)
495 ttyrub(unputc(&tp->t_rawq), tp);
496 else {
497 ttyecho(c, tp);
498 if (ISSET(lflag, ECHOK) ||
499 ISSET(lflag, ECHOKE))
500 ttyecho('\n', tp);
501 FLUSHQ(&tp->t_rawq);
502 tp->t_rocount = 0;
503 }
504 CLR(tp->t_state, TS_LOCAL);
505 goto endcase;
506 }
507 /*
508 * Extensions to the POSIX.1 GTI set of functions.
509 */
510 if (ISSET(lflag, IEXTEN)) {
511 /*
512 * word erase (^W)
513 */
514 if (CCEQ(cc[VWERASE], c)) {
515 int alt = ISSET(lflag, ALTWERASE);
516 int ctype;
517
518 /*
519 * erase whitespace
520 */
521 while ((c = unputc(&tp->t_rawq)) == ' ' ||
522 c == '\t')
523 ttyrub(c, tp);
524 if (c == -1)
525 goto endcase;
526 /*
527 * erase last char of word and remember the
528 * next chars type (for ALTWERASE)
529 */
530 ttyrub(c, tp);
531 c = unputc(&tp->t_rawq);
532 if (c == -1)
533 goto endcase;
534 if (c == ' ' || c == '\t') {
535 (void)putc(c, &tp->t_rawq);
536 goto endcase;
537 }
538 ctype = ISALPHA(c);
539 /*
540 * erase rest of word
541 */
542 do {
543 ttyrub(c, tp);
544 c = unputc(&tp->t_rawq);
545 if (c == -1)
546 goto endcase;
547 } while (c != ' ' && c != '\t' &&
548 (alt == 0 || ISALPHA(c) == ctype));
549 (void)putc(c, &tp->t_rawq);
550 goto endcase;
551 }
552 /*
553 * reprint line (^R)
554 */
555 if (CCEQ(cc[VREPRINT], c)) {
556 ttyretype(tp);
557 goto endcase;
558 }
559 /*
560 * ^T - kernel info and generate SIGINFO
561 */
562 if (CCEQ(cc[VSTATUS], c)) {
563 if (ISSET(lflag, ISIG))
564 pgsignal(tp->t_pgrp, SIGINFO, 1);
565 if (!ISSET(lflag, NOKERNINFO))
566 ttyinfo(tp);
567 goto endcase;
568 }
569 }
570 }
571 /*
572 * Check for input buffer overflow
573 */
574 if (tp->t_rawq.c_cc + tp->t_canq.c_cc >= TTYHOG) {
575 if (ISSET(iflag, IMAXBEL)) {
576 if (tp->t_outq.c_cc < tp->t_hiwat)
577 (void)ttyoutput(CTRL('g'), tp);
578 } else
579 ttyflush(tp, FREAD | FWRITE);
580 goto endcase;
581 }
582 /*
583 * Put data char in q for user and
584 * wakeup on seeing a line delimiter.
585 */
586 if (putc(c, &tp->t_rawq) >= 0) {
587 if (!ISSET(lflag, ICANON)) {
588 ttwakeup(tp);
589 ttyecho(c, tp);
590 goto endcase;
591 }
592 if (TTBREAKC(c, lflag)) {
593 tp->t_rocount = 0;
594 catq(&tp->t_rawq, &tp->t_canq);
595 ttwakeup(tp);
596 } else if (tp->t_rocount++ == 0)
597 tp->t_rocol = tp->t_column;
598 if (ISSET(tp->t_state, TS_ERASE)) {
599 /*
600 * end of prterase \.../
601 */
602 CLR(tp->t_state, TS_ERASE);
603 (void)ttyoutput('/', tp);
604 }
605 i = tp->t_column;
606 ttyecho(c, tp);
607 if (CCEQ(cc[VEOF], c) && ISSET(lflag, ECHO)) {
608 /*
609 * Place the cursor over the '^' of the ^D.
610 */
611 i = min(2, tp->t_column - i);
612 while (i > 0) {
613 (void)ttyoutput('\b', tp);
614 i--;
615 }
616 }
617 }
618 endcase:
619 /*
620 * IXANY means allow any character to restart output.
621 */
622 if (ISSET(tp->t_state, TS_TTSTOP) &&
623 !ISSET(iflag, IXANY) && cc[VSTART] != cc[VSTOP])
624 return (0);
625 restartoutput:
626 CLR(tp->t_lflag, FLUSHO);
627 CLR(tp->t_state, TS_TTSTOP);
628 startoutput:
629 return (ttstart(tp));
630 }
631
632 /*
633 * Output a single character on a tty, doing output processing
634 * as needed (expanding tabs, newline processing, etc.).
635 * Returns < 0 if succeeds, otherwise returns char to resend.
636 * Must be recursive.
637 */
638 int
639 ttyoutput(int c, struct tty *tp)
640 {
641 long oflag;
642 int col, notout, s;
643
644 oflag = tp->t_oflag;
645 if (!ISSET(oflag, OPOST)) {
646 tk_nout++;
647 tp->t_outcc++;
648 if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
649 return (c);
650 return (-1);
651 }
652 /*
653 * Do tab expansion if OXTABS is set. Special case if we do external
654 * processing, we don't do the tab expansion because we'll probably
655 * get it wrong. If tab expansion needs to be done, let it happen
656 * externally.
657 */
658 CLR(c, ~TTY_CHARMASK);
659 if (c == '\t' &&
660 ISSET(oflag, OXTABS) && !ISSET(tp->t_lflag, EXTPROC)) {
661 c = 8 - (tp->t_column & 7);
662 if (ISSET(tp->t_lflag, FLUSHO)) {
663 notout = 0;
664 } else {
665 s = spltty(); /* Don't interrupt tabs. */
666 notout = b_to_q(" ", c, &tp->t_outq);
667 c -= notout;
668 tk_nout += c;
669 tp->t_outcc += c;
670 splx(s);
671 }
672 tp->t_column += c;
673 return (notout ? '\t' : -1);
674 }
675 if (c == CEOT && ISSET(oflag, ONOEOT))
676 return (-1);
677
678 /*
679 * Newline translation: if ONLCR is set,
680 * translate newline into "\r\n".
681 */
682 if (c == '\n' && ISSET(tp->t_oflag, ONLCR)) {
683 tk_nout++;
684 tp->t_outcc++;
685 if (!ISSET(tp->t_lflag, FLUSHO) && putc('\r', &tp->t_outq))
686 return (c);
687 }
688 /* If OCRNL is set, translate "\r" into "\n". */
689 else if (c == '\r' && ISSET(tp->t_oflag, OCRNL))
690 c = '\n';
691 /* If ONOCR is set, don't transmit CRs when on column 0. */
692 else if (c == '\r' && ISSET(tp->t_oflag, ONOCR) && tp->t_column == 0)
693 return (-1);
694
695 tk_nout++;
696 tp->t_outcc++;
697 if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
698 return (c);
699
700 col = tp->t_column;
701 switch (CCLASS(c)) {
702 case BACKSPACE:
703 if (col > 0)
704 --col;
705 break;
706 case CONTROL:
707 break;
708 case NEWLINE:
709 if (ISSET(tp->t_oflag, ONLCR | ONLRET))
710 col = 0;
711 break;
712 case RETURN:
713 col = 0;
714 break;
715 case ORDINARY:
716 ++col;
717 break;
718 case TAB:
719 col = (col + 8) & ~7;
720 break;
721 }
722 tp->t_column = col;
723 return (-1);
724 }
725
726 /*
727 * Ioctls for all tty devices. Called after line-discipline specific ioctl
728 * has been called to do discipline-specific functions and/or reject any
729 * of these ioctl commands.
730 */
731 /* ARGSUSED */
732 int
733 ttioctl(struct tty *tp, u_long cmd, caddr_t data, int flag, struct proc *p)
734 {
735 extern struct tty *constty; /* Temporary virtual console. */
736 extern int nlinesw;
737 struct linesw *lp;
738 int s, error;
739
740 /* If the ioctl involves modification, hang if in the background. */
741 switch (cmd) {
742 case TIOCFLUSH:
743 case TIOCDRAIN:
744 case TIOCSBRK:
745 case TIOCCBRK:
746 case TIOCSTART:
747 case TIOCSETA:
748 case TIOCSETD:
749 case TIOCSLINED:
750 case TIOCSETAF:
751 case TIOCSETAW:
752 #ifdef notdef
753 case TIOCSPGRP:
754 #endif
755 case TIOCSTAT:
756 case TIOCSTI:
757 case TIOCSWINSZ:
758 #ifdef COMPAT_OLDTTY
759 case TIOCLBIC:
760 case TIOCLBIS:
761 case TIOCLSET:
762 case TIOCSETC:
763 case OTIOCSETD:
764 case TIOCSETN:
765 case TIOCSETP:
766 case TIOCSLTC:
767 #endif
768 while (isbackground(curproc, tp) &&
769 p->p_pgrp->pg_jobc && (p->p_flag & P_PPWAIT) == 0 &&
770 !sigismasked(p, SIGTTOU)) {
771 pgsignal(p->p_pgrp, SIGTTOU, 1);
772 error = ttysleep(tp, &lbolt, TTOPRI | PCATCH, ttybg, 0);
773 if (error)
774 return (error);
775 }
776 break;
777 }
778
779 switch (cmd) { /* Process the ioctl. */
780 case FIOASYNC: /* set/clear async i/o */
781 s = spltty();
782 if (*(int *)data)
783 SET(tp->t_state, TS_ASYNC);
784 else
785 CLR(tp->t_state, TS_ASYNC);
786 splx(s);
787 break;
788 case FIONBIO: /* set/clear non-blocking i/o */
789 break; /* XXX: delete. */
790 case FIONREAD: /* get # bytes to read */
791 *(int *)data = ttnread(tp);
792 break;
793 case TIOCEXCL: /* set exclusive use of tty */
794 s = spltty();
795 SET(tp->t_state, TS_XCLUDE);
796 splx(s);
797 break;
798 case TIOCFLUSH: { /* flush buffers */
799 int flags = *(int *)data;
800
801 if (flags == 0)
802 flags = FREAD | FWRITE;
803 else
804 flags &= FREAD | FWRITE;
805 ttyflush(tp, flags);
806 break;
807 }
808 case TIOCCONS: /* become virtual console */
809 if (*(int *)data) {
810 if (constty && constty != tp &&
811 ISSET(constty->t_state, TS_CARR_ON | TS_ISOPEN) ==
812 (TS_CARR_ON | TS_ISOPEN))
813 return (EBUSY);
814 #ifndef UCONSOLE
815 if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
816 return (error);
817 #endif
818 constty = tp;
819 } else if (tp == constty)
820 constty = NULL;
821 break;
822 case TIOCDRAIN: /* wait till output drained */
823 if ((error = ttywait(tp)) != 0)
824 return (error);
825 break;
826 case TIOCGETA: { /* get termios struct */
827 struct termios *t = (struct termios *)data;
828
829 memcpy(t, &tp->t_termios, sizeof(struct termios));
830 break;
831 }
832 case TIOCGETD: /* get line discipline */
833 *(int *)data = tp->t_linesw->l_no;
834 break;
835 case TIOCGLINED:
836 strncpy((char *)data, tp->t_linesw->l_name,
837 TTLINEDNAMELEN);
838 break;
839 case TIOCGWINSZ: /* get window size */
840 *(struct winsize *)data = tp->t_winsize;
841 break;
842 case TIOCGPGRP: /* get pgrp of tty */
843 if (!isctty(p, tp))
844 return (ENOTTY);
845 *(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
846 break;
847 case TIOCGSID: /* get sid of tty */
848 if (!isctty(p, tp))
849 return (ENOTTY);
850 *(int *)data = tp->t_session->s_sid;
851 break;
852 #ifdef TIOCHPCL
853 case TIOCHPCL: /* hang up on last close */
854 s = spltty();
855 SET(tp->t_cflag, HUPCL);
856 splx(s);
857 break;
858 #endif
859 case TIOCNXCL: /* reset exclusive use of tty */
860 s = spltty();
861 CLR(tp->t_state, TS_XCLUDE);
862 splx(s);
863 break;
864 case TIOCOUTQ: /* output queue size */
865 *(int *)data = tp->t_outq.c_cc;
866 break;
867 case TIOCSETA: /* set termios struct */
868 case TIOCSETAW: /* drain output, set */
869 case TIOCSETAF: { /* drn out, fls in, set */
870 struct termios *t = (struct termios *)data;
871
872 s = spltty();
873 if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
874 if ((error = ttywait(tp)) != 0) {
875 splx(s);
876 return (error);
877 }
878 if (cmd == TIOCSETAF)
879 ttyflush(tp, FREAD);
880 }
881 if (!ISSET(t->c_cflag, CIGNORE)) {
882 /*
883 * Set device hardware.
884 */
885 if (tp->t_param && (error = (*tp->t_param)(tp, t))) {
886 splx(s);
887 return (error);
888 } else {
889 tp->t_cflag = t->c_cflag;
890 tp->t_ispeed = t->c_ispeed;
891 tp->t_ospeed = t->c_ospeed;
892 if (t->c_ospeed == 0 && tp->t_session &&
893 tp->t_session->s_leader)
894 psignal(tp->t_session->s_leader,
895 SIGHUP);
896 }
897 ttsetwater(tp);
898 }
899 if (cmd != TIOCSETAF) {
900 if (ISSET(t->c_lflag, ICANON) !=
901 ISSET(tp->t_lflag, ICANON)) {
902 if (ISSET(t->c_lflag, ICANON)) {
903 SET(tp->t_lflag, PENDIN);
904 ttwakeup(tp);
905 } else {
906 struct clist tq;
907
908 catq(&tp->t_rawq, &tp->t_canq);
909 tq = tp->t_rawq;
910 tp->t_rawq = tp->t_canq;
911 tp->t_canq = tq;
912 CLR(tp->t_lflag, PENDIN);
913 }
914 }
915 }
916 tp->t_iflag = t->c_iflag;
917 tp->t_oflag = t->c_oflag;
918 /*
919 * Make the EXTPROC bit read only.
920 */
921 if (ISSET(tp->t_lflag, EXTPROC))
922 SET(t->c_lflag, EXTPROC);
923 else
924 CLR(t->c_lflag, EXTPROC);
925 tp->t_lflag = t->c_lflag | ISSET(tp->t_lflag, PENDIN);
926 memcpy(tp->t_cc, t->c_cc, sizeof(t->c_cc));
927 splx(s);
928 break;
929 }
930 case TIOCSETD: { /* set line discipline */
931 int t = *(int *)data;
932
933 if ((u_int)t >= nlinesw)
934 return (ENXIO);
935 lp = linesw[t];
936 goto setldisc;
937 }
938 case TIOCSLINED: { /* set line discipline */
939 char *name = (char *)data;
940 dev_t device;
941
942 /* Null terminate to prevent buffer overflow */
943 name[TTLINEDNAMELEN] = 0;
944 lp = ttyldisc_lookup(name);
945
946 setldisc:
947 if (lp == NULL)
948 return (ENXIO);
949
950 if (lp != tp->t_linesw) {
951 device = tp->t_dev;
952 s = spltty();
953 (*tp->t_linesw->l_close)(tp, flag);
954 error = (*lp->l_open)(device, tp);
955 if (error) {
956 (void)(*tp->t_linesw->l_open)(device, tp);
957 splx(s);
958 return (error);
959 }
960 tp->t_linesw = lp;
961 splx(s);
962 }
963 break;
964 }
965 case TIOCSTART: /* start output, like ^Q */
966 s = spltty();
967 if (ISSET(tp->t_state, TS_TTSTOP) ||
968 ISSET(tp->t_lflag, FLUSHO)) {
969 CLR(tp->t_lflag, FLUSHO);
970 CLR(tp->t_state, TS_TTSTOP);
971 ttstart(tp);
972 }
973 splx(s);
974 break;
975 case TIOCSTI: /* simulate terminal input */
976 if (p->p_ucred->cr_uid && (flag & FREAD) == 0)
977 return (EPERM);
978 if (p->p_ucred->cr_uid && !isctty(p, tp))
979 return (EACCES);
980 (*tp->t_linesw->l_rint)(*(u_char *)data, tp);
981 break;
982 case TIOCSTOP: /* stop output, like ^S */
983 s = spltty();
984 if (!ISSET(tp->t_state, TS_TTSTOP)) {
985 SET(tp->t_state, TS_TTSTOP);
986 (*cdevsw[major(tp->t_dev)].d_stop)(tp, 0);
987 }
988 splx(s);
989 break;
990 case TIOCSCTTY: /* become controlling tty */
991 /* Session ctty vnode pointer set in vnode layer. */
992 if (!SESS_LEADER(p) ||
993 ((p->p_session->s_ttyvp || tp->t_session) &&
994 (tp->t_session != p->p_session)))
995 return (EPERM);
996 tp->t_session = p->p_session;
997 tp->t_pgrp = p->p_pgrp;
998 p->p_session->s_ttyp = tp;
999 p->p_flag |= P_CONTROLT;
1000 break;
1001 case TIOCSPGRP: { /* set pgrp of tty */
1002 struct pgrp *pgrp = pgfind(*(int *)data);
1003
1004 if (!isctty(p, tp))
1005 return (ENOTTY);
1006 else if (pgrp == NULL)
1007 return (EINVAL);
1008 else if (pgrp->pg_session != p->p_session)
1009 return (EPERM);
1010 tp->t_pgrp = pgrp;
1011 break;
1012 }
1013 case TIOCSTAT: /* get load avg stats */
1014 ttyinfo(tp);
1015 break;
1016 case TIOCSWINSZ: /* set window size */
1017 if (memcmp((caddr_t)&tp->t_winsize, data,
1018 sizeof(struct winsize))) {
1019 tp->t_winsize = *(struct winsize *)data;
1020 pgsignal(tp->t_pgrp, SIGWINCH, 1);
1021 }
1022 break;
1023 default:
1024 #ifdef COMPAT_OLDTTY
1025 return (ttcompat(tp, cmd, data, flag, p));
1026 #else
1027 return (-1);
1028 #endif
1029 }
1030 return (0);
1031 }
1032
1033 int
1034 ttpoll(struct tty *tp, int events, struct proc *p)
1035 {
1036 int revents, s;
1037
1038 revents = 0;
1039 s = spltty();
1040 if (events & (POLLIN | POLLRDNORM))
1041 if (ttnread(tp) > 0)
1042 revents |= events & (POLLIN | POLLRDNORM);
1043
1044 if (events & (POLLOUT | POLLWRNORM))
1045 if (tp->t_outq.c_cc <= tp->t_lowat)
1046 revents |= events & (POLLOUT | POLLWRNORM);
1047
1048 if (events & POLLHUP)
1049 if (!CONNECTED(tp))
1050 revents |= POLLHUP;
1051
1052 if (revents == 0) {
1053 if (events & (POLLIN | POLLHUP | POLLRDNORM))
1054 selrecord(p, &tp->t_rsel);
1055
1056 if (events & (POLLOUT | POLLWRNORM))
1057 selrecord(p, &tp->t_wsel);
1058 }
1059
1060 splx(s);
1061 return (revents);
1062 }
1063
1064 static const struct filterops ttyread_filtops =
1065 { 1, NULL, filt_ttyrdetach, filt_ttyread };
1066 static const struct filterops ttywrite_filtops =
1067 { 1, NULL, filt_ttywdetach, filt_ttywrite };
1068
1069 int
1070 ttykqfilter(dev_t dev, struct knote *kn)
1071 {
1072 struct tty *tp;
1073 struct klist *klist;
1074 int s;
1075
1076 tp = (*cdevsw[major(dev)].d_tty)(dev);
1077 switch (kn->kn_filter) {
1078 case EVFILT_READ:
1079 klist = &tp->t_rsel.si_klist;
1080 kn->kn_fop = &ttyread_filtops;
1081 break;
1082 case EVFILT_WRITE:
1083 klist = &tp->t_wsel.si_klist;
1084 kn->kn_fop = &ttywrite_filtops;
1085 break;
1086 default:
1087 return (1);
1088 }
1089
1090 kn->kn_hook = (void *) tp;
1091
1092 s = spltty();
1093 SLIST_INSERT_HEAD(klist, kn, kn_selnext);
1094 splx(s);
1095
1096 return (0);
1097 }
1098
1099 static void
1100 filt_ttyrdetach(struct knote *kn)
1101 {
1102 struct tty *tp;
1103 int s;
1104
1105 tp = (void *) kn->kn_hook;
1106 s = spltty();
1107 SLIST_REMOVE(&tp->t_rsel.si_klist, kn, knote, kn_selnext);
1108 splx(s);
1109 }
1110
1111 static int
1112 filt_ttyread(struct knote *kn, long hint)
1113 {
1114 struct tty *tp;
1115
1116 tp = (void *) kn->kn_hook;
1117 kn->kn_data = ttnread(tp);
1118 return (kn->kn_data > 0);
1119 }
1120
1121 static void
1122 filt_ttywdetach(struct knote *kn)
1123 {
1124 struct tty *tp;
1125 int s;
1126
1127 tp = (void *) kn->kn_hook;
1128 s = spltty();
1129 SLIST_REMOVE(&tp->t_wsel.si_klist, kn, knote, kn_selnext);
1130 splx(s);
1131 }
1132
1133 static int
1134 filt_ttywrite(kn, hint)
1135 struct knote *kn;
1136 long hint;
1137 {
1138 struct tty *tp;
1139
1140 tp = (void *) kn->kn_hook;
1141 kn->kn_data = tp->t_outq.c_cc;
1142 return (kn->kn_data <= tp->t_lowat && CONNECTED(tp));
1143 }
1144
1145
1146 static int
1147 ttnread(struct tty *tp)
1148 {
1149 int nread;
1150
1151 if (ISSET(tp->t_lflag, PENDIN))
1152 ttypend(tp);
1153 nread = tp->t_canq.c_cc;
1154 if (!ISSET(tp->t_lflag, ICANON)) {
1155 nread += tp->t_rawq.c_cc;
1156 if (nread < tp->t_cc[VMIN] && !tp->t_cc[VTIME])
1157 nread = 0;
1158 }
1159 return (nread);
1160 }
1161
1162 /*
1163 * Wait for output to drain.
1164 */
1165 int
1166 ttywait(tp)
1167 struct tty *tp;
1168 {
1169 int error, s;
1170
1171 error = 0;
1172 s = spltty();
1173 while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1174 CONNECTED(tp) && tp->t_oproc) {
1175 (*tp->t_oproc)(tp);
1176 SET(tp->t_state, TS_ASLEEP);
1177 error = ttysleep(tp, &tp->t_outq, TTOPRI | PCATCH, ttyout, 0);
1178 if (error)
1179 break;
1180 }
1181 splx(s);
1182 return (error);
1183 }
1184
1185 /*
1186 * Flush if successfully wait.
1187 */
1188 int
1189 ttywflush(struct tty *tp)
1190 {
1191 int error;
1192
1193 if ((error = ttywait(tp)) == 0)
1194 ttyflush(tp, FREAD);
1195 return (error);
1196 }
1197
1198 /*
1199 * Flush tty read and/or write queues, notifying anyone waiting.
1200 */
1201 void
1202 ttyflush(struct tty *tp, int rw)
1203 {
1204 int s;
1205
1206 s = spltty();
1207 if (rw & FREAD) {
1208 FLUSHQ(&tp->t_canq);
1209 FLUSHQ(&tp->t_rawq);
1210 tp->t_rocount = 0;
1211 tp->t_rocol = 0;
1212 CLR(tp->t_state, TS_LOCAL);
1213 ttwakeup(tp);
1214 }
1215 if (rw & FWRITE) {
1216 CLR(tp->t_state, TS_TTSTOP);
1217 (*cdevsw[major(tp->t_dev)].d_stop)(tp, rw);
1218 FLUSHQ(&tp->t_outq);
1219 wakeup((caddr_t)&tp->t_outq);
1220 selnotify(&tp->t_wsel, 0);
1221 }
1222 splx(s);
1223 }
1224
1225 /*
1226 * Copy in the default termios characters.
1227 */
1228 void
1229 ttychars(struct tty *tp)
1230 {
1231
1232 memcpy(tp->t_cc, ttydefchars, sizeof(ttydefchars));
1233 }
1234
1235 /*
1236 * Send stop character on input overflow.
1237 */
1238 static void
1239 ttyblock(struct tty *tp)
1240 {
1241 int total;
1242
1243 total = tp->t_rawq.c_cc + tp->t_canq.c_cc;
1244 if (tp->t_rawq.c_cc > TTYHOG) {
1245 ttyflush(tp, FREAD | FWRITE);
1246 CLR(tp->t_state, TS_TBLOCK);
1247 }
1248 /*
1249 * Block further input iff: current input > threshold
1250 * AND input is available to user program.
1251 */
1252 if (total >= TTYHOG / 2 &&
1253 !ISSET(tp->t_state, TS_TBLOCK) &&
1254 (!ISSET(tp->t_lflag, ICANON) || tp->t_canq.c_cc > 0)) {
1255 if (ISSET(tp->t_iflag, IXOFF) &&
1256 tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
1257 putc(tp->t_cc[VSTOP], &tp->t_outq) == 0) {
1258 SET(tp->t_state, TS_TBLOCK);
1259 ttstart(tp);
1260 }
1261 /* Try to block remote output via hardware flow control. */
1262 if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
1263 (*tp->t_hwiflow)(tp, 1) != 0)
1264 SET(tp->t_state, TS_TBLOCK);
1265 }
1266 }
1267
1268 void
1269 ttrstrt(void *tp_arg)
1270 {
1271 struct tty *tp;
1272 int s;
1273
1274 #ifdef DIAGNOSTIC
1275 if (tp_arg == NULL)
1276 panic("ttrstrt");
1277 #endif
1278 tp = tp_arg;
1279 s = spltty();
1280
1281 CLR(tp->t_state, TS_TIMEOUT);
1282 ttstart(tp);
1283
1284 splx(s);
1285 }
1286
1287 int
1288 ttstart(struct tty *tp)
1289 {
1290
1291 if (tp->t_oproc != NULL) /* XXX: Kludge for pty. */
1292 (*tp->t_oproc)(tp);
1293 return (0);
1294 }
1295
1296 /*
1297 * "close" a line discipline
1298 */
1299 int
1300 ttylclose(struct tty *tp, int flag)
1301 {
1302
1303 if (flag & FNONBLOCK)
1304 ttyflush(tp, FREAD | FWRITE);
1305 else
1306 ttywflush(tp);
1307 return (0);
1308 }
1309
1310 /*
1311 * Handle modem control transition on a tty.
1312 * Flag indicates new state of carrier.
1313 * Returns 0 if the line should be turned off, otherwise 1.
1314 */
1315 int
1316 ttymodem(struct tty *tp, int flag)
1317 {
1318
1319 if (flag == 0) {
1320 if (ISSET(tp->t_state, TS_CARR_ON)) {
1321 /*
1322 * Lost carrier.
1323 */
1324 CLR(tp->t_state, TS_CARR_ON);
1325 if (ISSET(tp->t_state, TS_ISOPEN) && !CONNECTED(tp)) {
1326 if (tp->t_session && tp->t_session->s_leader)
1327 psignal(tp->t_session->s_leader, SIGHUP);
1328 ttyflush(tp, FREAD | FWRITE);
1329 return (0);
1330 }
1331 }
1332 } else {
1333 if (!ISSET(tp->t_state, TS_CARR_ON)) {
1334 /*
1335 * Carrier now on.
1336 */
1337 SET(tp->t_state, TS_CARR_ON);
1338 ttwakeup(tp);
1339 }
1340 }
1341 return (1);
1342 }
1343
1344 /*
1345 * Default modem control routine (for other line disciplines).
1346 * Return argument flag, to turn off device on carrier drop.
1347 */
1348 int
1349 nullmodem(struct tty *tp, int flag)
1350 {
1351
1352 if (flag)
1353 SET(tp->t_state, TS_CARR_ON);
1354 else {
1355 CLR(tp->t_state, TS_CARR_ON);
1356 if (!CONNECTED(tp)) {
1357 if (tp->t_session && tp->t_session->s_leader)
1358 psignal(tp->t_session->s_leader, SIGHUP);
1359 return (0);
1360 }
1361 }
1362 return (1);
1363 }
1364
1365 /*
1366 * Reinput pending characters after state switch
1367 * call at spltty().
1368 */
1369 void
1370 ttypend(struct tty *tp)
1371 {
1372 struct clist tq;
1373 int c;
1374
1375 CLR(tp->t_lflag, PENDIN);
1376 SET(tp->t_state, TS_TYPEN);
1377 tq = tp->t_rawq;
1378 tp->t_rawq.c_cc = 0;
1379 tp->t_rawq.c_cf = tp->t_rawq.c_cl = 0;
1380 while ((c = getc(&tq)) >= 0)
1381 ttyinput(c, tp);
1382 CLR(tp->t_state, TS_TYPEN);
1383 }
1384
1385 /*
1386 * Process a read call on a tty device.
1387 */
1388 int
1389 ttread(struct tty *tp, struct uio *uio, int flag)
1390 {
1391 struct clist *qp;
1392 u_char *cc;
1393 struct proc *p;
1394 int c, s, first, error, has_stime, last_cc;
1395 long lflag, slp;
1396 struct timeval stime;
1397
1398 cc = tp->t_cc;
1399 p = curproc;
1400 error = 0;
1401 has_stime = 0;
1402 last_cc = 0;
1403 slp = 0;
1404
1405 loop:
1406 lflag = tp->t_lflag;
1407 s = spltty();
1408 /*
1409 * take pending input first
1410 */
1411 if (ISSET(lflag, PENDIN))
1412 ttypend(tp);
1413 splx(s);
1414
1415 /*
1416 * Hang process if it's in the background.
1417 */
1418 if (isbackground(p, tp)) {
1419 if (sigismember(&p->p_sigctx.ps_sigignore, SIGTTIN) ||
1420 sigismember(&p->p_sigctx.ps_sigmask, SIGTTIN) ||
1421 p->p_flag & P_PPWAIT || p->p_pgrp->pg_jobc == 0)
1422 return (EIO);
1423 pgsignal(p->p_pgrp, SIGTTIN, 1);
1424 error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, ttybg, 0);
1425 if (error)
1426 return (error);
1427 goto loop;
1428 }
1429
1430 s = spltty();
1431 if (!ISSET(lflag, ICANON)) {
1432 int m = cc[VMIN];
1433 long t = cc[VTIME];
1434
1435 qp = &tp->t_rawq;
1436 /*
1437 * Check each of the four combinations.
1438 * (m > 0 && t == 0) is the normal read case.
1439 * It should be fairly efficient, so we check that and its
1440 * companion case (m == 0 && t == 0) first.
1441 * For the other two cases, we compute the target sleep time
1442 * into slp.
1443 */
1444 if (t == 0) {
1445 if (qp->c_cc < m)
1446 goto sleep;
1447 goto read;
1448 }
1449 t *= 100000; /* time in us */
1450 #define diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 1000000 + \
1451 ((t1).tv_usec - (t2).tv_usec))
1452 if (m > 0) {
1453 if (qp->c_cc <= 0)
1454 goto sleep;
1455 if (qp->c_cc >= m)
1456 goto read;
1457 if (!has_stime) {
1458 /* first character, start timer */
1459 has_stime = 1;
1460 stime = time;
1461 slp = t;
1462 } else if (qp->c_cc > last_cc) {
1463 /* got a character, restart timer */
1464 stime = time;
1465 slp = t;
1466 } else {
1467 /* nothing, check expiration */
1468 slp = t - diff(time, stime);
1469 }
1470 } else { /* m == 0 */
1471 if (qp->c_cc > 0)
1472 goto read;
1473 if (!has_stime) {
1474 has_stime = 1;
1475 stime = time;
1476 slp = t;
1477 } else
1478 slp = t - diff(time, stime);
1479 }
1480 last_cc = qp->c_cc;
1481 #undef diff
1482 if (slp > 0) {
1483 /*
1484 * Rounding down may make us wake up just short
1485 * of the target, so we round up.
1486 * The formula is ceiling(slp * hz/1000000).
1487 * 32-bit arithmetic is enough for hz < 169.
1488 *
1489 * Also, use plain wakeup() not ttwakeup().
1490 */
1491 slp = (long) (((u_long)slp * hz) + 999999) / 1000000;
1492 goto sleep;
1493 }
1494 } else if ((qp = &tp->t_canq)->c_cc <= 0) {
1495 int carrier;
1496
1497 sleep:
1498 /*
1499 * If there is no input, sleep on rawq
1500 * awaiting hardware receipt and notification.
1501 * If we have data, we don't need to check for carrier.
1502 */
1503 carrier = CONNECTED(tp);
1504 if (!carrier && ISSET(tp->t_state, TS_ISOPEN)) {
1505 splx(s);
1506 return (0); /* EOF */
1507 }
1508 if (flag & IO_NDELAY) {
1509 splx(s);
1510 return (EWOULDBLOCK);
1511 }
1512 error = ttysleep(tp, &tp->t_rawq, TTIPRI | PCATCH,
1513 carrier ? ttyin : ttopen, slp);
1514 splx(s);
1515 /* VMIN == 0: any quantity read satisfies */
1516 if (cc[VMIN] == 0 && error == EWOULDBLOCK)
1517 return (0);
1518 if (error && error != EWOULDBLOCK)
1519 return (error);
1520 goto loop;
1521 }
1522 read:
1523 splx(s);
1524
1525 /*
1526 * Input present, check for input mapping and processing.
1527 */
1528 first = 1;
1529 while ((c = getc(qp)) >= 0) {
1530 /*
1531 * delayed suspend (^Y)
1532 */
1533 if (CCEQ(cc[VDSUSP], c) &&
1534 ISSET(lflag, IEXTEN|ISIG) == (IEXTEN|ISIG)) {
1535 pgsignal(tp->t_pgrp, SIGTSTP, 1);
1536 if (first) {
1537 error = ttysleep(tp, &lbolt,
1538 TTIPRI | PCATCH, ttybg, 0);
1539 if (error)
1540 break;
1541 goto loop;
1542 }
1543 break;
1544 }
1545 /*
1546 * Interpret EOF only in canonical mode.
1547 */
1548 if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
1549 break;
1550 /*
1551 * Give user character.
1552 */
1553 error = ureadc(c, uio);
1554 if (error)
1555 break;
1556 if (uio->uio_resid == 0)
1557 break;
1558 /*
1559 * In canonical mode check for a "break character"
1560 * marking the end of a "line of input".
1561 */
1562 if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
1563 break;
1564 first = 0;
1565 }
1566 /*
1567 * Look to unblock output now that (presumably)
1568 * the input queue has gone down.
1569 */
1570 s = spltty();
1571 if (ISSET(tp->t_state, TS_TBLOCK) && tp->t_rawq.c_cc < TTYHOG/5) {
1572 if (ISSET(tp->t_iflag, IXOFF) &&
1573 cc[VSTART] != _POSIX_VDISABLE &&
1574 putc(cc[VSTART], &tp->t_outq) == 0) {
1575 CLR(tp->t_state, TS_TBLOCK);
1576 ttstart(tp);
1577 }
1578 /* Try to unblock remote output via hardware flow control. */
1579 if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
1580 (*tp->t_hwiflow)(tp, 0) != 0)
1581 CLR(tp->t_state, TS_TBLOCK);
1582 }
1583 splx(s);
1584 return (error);
1585 }
1586
1587 /*
1588 * Check the output queue on tp for space for a kernel message (from uprintf
1589 * or tprintf). Allow some space over the normal hiwater mark so we don't
1590 * lose messages due to normal flow control, but don't let the tty run amok.
1591 * Sleeps here are not interruptible, but we return prematurely if new signals
1592 * arrive.
1593 */
1594 int
1595 ttycheckoutq(struct tty *tp, int wait)
1596 {
1597 int hiwat, s, error;
1598
1599 hiwat = tp->t_hiwat;
1600 s = spltty();
1601 if (tp->t_outq.c_cc > hiwat + 200)
1602 while (tp->t_outq.c_cc > hiwat) {
1603 ttstart(tp);
1604 if (wait == 0) {
1605 splx(s);
1606 return (0);
1607 }
1608 callout_reset(&tp->t_outq_ch, hz,
1609 (void (*)__P((void *)))wakeup, &tp->t_outq);
1610 SET(tp->t_state, TS_ASLEEP);
1611 error = tsleep(&tp->t_outq, (PZERO - 1) | PCATCH,
1612 "ttckoutq", 0);
1613 if (error == EINTR)
1614 wait = 0;
1615 }
1616 splx(s);
1617 return (1);
1618 }
1619
1620 /*
1621 * Process a write call on a tty device.
1622 */
1623 int
1624 ttwrite(struct tty *tp, struct uio *uio, int flag)
1625 {
1626 u_char *cp;
1627 struct proc *p;
1628 int cc, ce, i, hiwat, cnt, error, s;
1629 u_char obuf[OBUFSIZ];
1630
1631 cp = NULL;
1632 hiwat = tp->t_hiwat;
1633 cnt = uio->uio_resid;
1634 error = 0;
1635 cc = 0;
1636 loop:
1637 s = spltty();
1638 if (!CONNECTED(tp)) {
1639 if (ISSET(tp->t_state, TS_ISOPEN)) {
1640 splx(s);
1641 return (EIO);
1642 } else if (flag & IO_NDELAY) {
1643 splx(s);
1644 error = EWOULDBLOCK;
1645 goto out;
1646 } else {
1647 /* Sleep awaiting carrier. */
1648 error = ttysleep(tp,
1649 &tp->t_rawq, TTIPRI | PCATCH, ttopen, 0);
1650 splx(s);
1651 if (error)
1652 goto out;
1653 goto loop;
1654 }
1655 }
1656 splx(s);
1657 /*
1658 * Hang the process if it's in the background.
1659 */
1660 p = curproc;
1661 if (isbackground(p, tp) &&
1662 ISSET(tp->t_lflag, TOSTOP) && (p->p_flag & P_PPWAIT) == 0 &&
1663 !sigismember(&p->p_sigctx.ps_sigignore, SIGTTOU) &&
1664 !sigismember(&p->p_sigctx.ps_sigmask, SIGTTOU)) {
1665 if (p->p_pgrp->pg_jobc == 0) {
1666 error = EIO;
1667 goto out;
1668 }
1669 pgsignal(p->p_pgrp, SIGTTOU, 1);
1670 error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, ttybg, 0);
1671 if (error)
1672 goto out;
1673 goto loop;
1674 }
1675 /*
1676 * Process the user's data in at most OBUFSIZ chunks. Perform any
1677 * output translation. Keep track of high water mark, sleep on
1678 * overflow awaiting device aid in acquiring new space.
1679 */
1680 while (uio->uio_resid > 0 || cc > 0) {
1681 if (ISSET(tp->t_lflag, FLUSHO)) {
1682 uio->uio_resid = 0;
1683 return (0);
1684 }
1685 if (tp->t_outq.c_cc > hiwat)
1686 goto ovhiwat;
1687 /*
1688 * Grab a hunk of data from the user, unless we have some
1689 * leftover from last time.
1690 */
1691 if (cc == 0) {
1692 cc = min(uio->uio_resid, OBUFSIZ);
1693 cp = obuf;
1694 error = uiomove(cp, cc, uio);
1695 if (error) {
1696 cc = 0;
1697 break;
1698 }
1699 }
1700 /*
1701 * If nothing fancy need be done, grab those characters we
1702 * can handle without any of ttyoutput's processing and
1703 * just transfer them to the output q. For those chars
1704 * which require special processing (as indicated by the
1705 * bits in char_type), call ttyoutput. After processing
1706 * a hunk of data, look for FLUSHO so ^O's will take effect
1707 * immediately.
1708 */
1709 while (cc > 0) {
1710 if (!ISSET(tp->t_oflag, OPOST))
1711 ce = cc;
1712 else {
1713 ce = cc - scanc((u_int)cc, cp, char_type,
1714 CCLASSMASK);
1715 /*
1716 * If ce is zero, then we're processing
1717 * a special character through ttyoutput.
1718 */
1719 if (ce == 0) {
1720 tp->t_rocount = 0;
1721 if (ttyoutput(*cp, tp) >= 0) {
1722 /* out of space */
1723 goto overfull;
1724 }
1725 cp++;
1726 cc--;
1727 if (ISSET(tp->t_lflag, FLUSHO) ||
1728 tp->t_outq.c_cc > hiwat)
1729 goto ovhiwat;
1730 continue;
1731 }
1732 }
1733 /*
1734 * A bunch of normal characters have been found.
1735 * Transfer them en masse to the output queue and
1736 * continue processing at the top of the loop.
1737 * If there are any further characters in this
1738 * <= OBUFSIZ chunk, the first should be a character
1739 * requiring special handling by ttyoutput.
1740 */
1741 tp->t_rocount = 0;
1742 i = b_to_q(cp, ce, &tp->t_outq);
1743 ce -= i;
1744 tp->t_column += ce;
1745 cp += ce, cc -= ce, tk_nout += ce;
1746 tp->t_outcc += ce;
1747 if (i > 0) {
1748 /* out of space */
1749 goto overfull;
1750 }
1751 if (ISSET(tp->t_lflag, FLUSHO) ||
1752 tp->t_outq.c_cc > hiwat)
1753 break;
1754 }
1755 ttstart(tp);
1756 }
1757 out:
1758 /*
1759 * If cc is nonzero, we leave the uio structure inconsistent, as the
1760 * offset and iov pointers have moved forward, but it doesn't matter
1761 * (the call will either return short or restart with a new uio).
1762 */
1763 uio->uio_resid += cc;
1764 return (error);
1765
1766 overfull:
1767 /*
1768 * Since we are using ring buffers, if we can't insert any more into
1769 * the output queue, we can assume the ring is full and that someone
1770 * forgot to set the high water mark correctly. We set it and then
1771 * proceed as normal.
1772 */
1773 hiwat = tp->t_outq.c_cc - 1;
1774
1775 ovhiwat:
1776 ttstart(tp);
1777 s = spltty();
1778 /*
1779 * This can only occur if FLUSHO is set in t_lflag,
1780 * or if ttstart/oproc is synchronous (or very fast).
1781 */
1782 if (tp->t_outq.c_cc <= hiwat) {
1783 splx(s);
1784 goto loop;
1785 }
1786 if (flag & IO_NDELAY) {
1787 splx(s);
1788 uio->uio_resid += cc;
1789 return (uio->uio_resid == cnt ? EWOULDBLOCK : 0);
1790 }
1791 SET(tp->t_state, TS_ASLEEP);
1792 error = ttysleep(tp, &tp->t_outq, TTOPRI | PCATCH, ttyout, 0);
1793 splx(s);
1794 if (error)
1795 goto out;
1796 goto loop;
1797 }
1798
1799 /*
1800 * Rubout one character from the rawq of tp
1801 * as cleanly as possible.
1802 */
1803 void
1804 ttyrub(int c, struct tty *tp)
1805 {
1806 u_char *cp;
1807 int savecol, tabc, s;
1808
1809 if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
1810 return;
1811 CLR(tp->t_lflag, FLUSHO);
1812 if (ISSET(tp->t_lflag, ECHOE)) {
1813 if (tp->t_rocount == 0) {
1814 /*
1815 * Screwed by ttwrite; retype
1816 */
1817 ttyretype(tp);
1818 return;
1819 }
1820 if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
1821 ttyrubo(tp, 2);
1822 else {
1823 CLR(c, ~TTY_CHARMASK);
1824 switch (CCLASS(c)) {
1825 case ORDINARY:
1826 ttyrubo(tp, 1);
1827 break;
1828 case BACKSPACE:
1829 case CONTROL:
1830 case NEWLINE:
1831 case RETURN:
1832 case VTAB:
1833 if (ISSET(tp->t_lflag, ECHOCTL))
1834 ttyrubo(tp, 2);
1835 break;
1836 case TAB:
1837 if (tp->t_rocount < tp->t_rawq.c_cc) {
1838 ttyretype(tp);
1839 return;
1840 }
1841 s = spltty();
1842 savecol = tp->t_column;
1843 SET(tp->t_state, TS_CNTTB);
1844 SET(tp->t_lflag, FLUSHO);
1845 tp->t_column = tp->t_rocol;
1846 for (cp = firstc(&tp->t_rawq, &tabc); cp;
1847 cp = nextc(&tp->t_rawq, cp, &tabc))
1848 ttyecho(tabc, tp);
1849 CLR(tp->t_lflag, FLUSHO);
1850 CLR(tp->t_state, TS_CNTTB);
1851 splx(s);
1852
1853 /* savecol will now be length of the tab. */
1854 savecol -= tp->t_column;
1855 tp->t_column += savecol;
1856 if (savecol > 8)
1857 savecol = 8; /* overflow screw */
1858 while (--savecol >= 0)
1859 (void)ttyoutput('\b', tp);
1860 break;
1861 default: /* XXX */
1862 #define PANICSTR "ttyrub: would panic c = %d, val = %d\n"
1863 (void)printf(PANICSTR, c, CCLASS(c));
1864 #ifdef notdef
1865 panic(PANICSTR, c, CCLASS(c));
1866 #endif
1867 }
1868 }
1869 } else if (ISSET(tp->t_lflag, ECHOPRT)) {
1870 if (!ISSET(tp->t_state, TS_ERASE)) {
1871 SET(tp->t_state, TS_ERASE);
1872 (void)ttyoutput('\\', tp);
1873 }
1874 ttyecho(c, tp);
1875 } else
1876 ttyecho(tp->t_cc[VERASE], tp);
1877 --tp->t_rocount;
1878 }
1879
1880 /*
1881 * Back over cnt characters, erasing them.
1882 */
1883 static void
1884 ttyrubo(struct tty *tp, int cnt)
1885 {
1886
1887 while (cnt-- > 0) {
1888 (void)ttyoutput('\b', tp);
1889 (void)ttyoutput(' ', tp);
1890 (void)ttyoutput('\b', tp);
1891 }
1892 }
1893
1894 /*
1895 * ttyretype --
1896 * Reprint the rawq line. Note, it is assumed that c_cc has already
1897 * been checked.
1898 */
1899 void
1900 ttyretype(struct tty *tp)
1901 {
1902 u_char *cp;
1903 int s, c;
1904
1905 /* Echo the reprint character. */
1906 if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
1907 ttyecho(tp->t_cc[VREPRINT], tp);
1908
1909 (void)ttyoutput('\n', tp);
1910
1911 s = spltty();
1912 for (cp = firstc(&tp->t_canq, &c); cp; cp = nextc(&tp->t_canq, cp, &c))
1913 ttyecho(c, tp);
1914 for (cp = firstc(&tp->t_rawq, &c); cp; cp = nextc(&tp->t_rawq, cp, &c))
1915 ttyecho(c, tp);
1916 CLR(tp->t_state, TS_ERASE);
1917 splx(s);
1918
1919 tp->t_rocount = tp->t_rawq.c_cc;
1920 tp->t_rocol = 0;
1921 }
1922
1923 /*
1924 * Echo a typed character to the terminal.
1925 */
1926 static void
1927 ttyecho(int c, struct tty *tp)
1928 {
1929
1930 if (!ISSET(tp->t_state, TS_CNTTB))
1931 CLR(tp->t_lflag, FLUSHO);
1932 if ((!ISSET(tp->t_lflag, ECHO) &&
1933 (!ISSET(tp->t_lflag, ECHONL) || c != '\n')) ||
1934 ISSET(tp->t_lflag, EXTPROC))
1935 return;
1936 if (((ISSET(tp->t_lflag, ECHOCTL) &&
1937 (ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n')) ||
1938 ISSET(c, TTY_CHARMASK) == 0177)) {
1939 (void)ttyoutput('^', tp);
1940 CLR(c, ~TTY_CHARMASK);
1941 if (c == 0177)
1942 c = '?';
1943 else
1944 c += 'A' - 1;
1945 }
1946 (void)ttyoutput(c, tp);
1947 }
1948
1949 /*
1950 * Wake up any readers on a tty.
1951 */
1952 void
1953 ttwakeup(struct tty *tp)
1954 {
1955
1956 selnotify(&tp->t_rsel, 0);
1957 if (ISSET(tp->t_state, TS_ASYNC))
1958 pgsignal(tp->t_pgrp, SIGIO, 1);
1959 wakeup((caddr_t)&tp->t_rawq);
1960 }
1961
1962 /*
1963 * Look up a code for a specified speed in a conversion table;
1964 * used by drivers to map software speed values to hardware parameters.
1965 */
1966 int
1967 ttspeedtab(int speed, struct speedtab *table)
1968 {
1969
1970 for ( ; table->sp_speed != -1; table++)
1971 if (table->sp_speed == speed)
1972 return (table->sp_code);
1973 return (-1);
1974 }
1975
1976 /*
1977 * Set tty hi and low water marks.
1978 *
1979 * Try to arrange the dynamics so there's about one second
1980 * from hi to low water.
1981 */
1982 void
1983 ttsetwater(struct tty *tp)
1984 {
1985 int cps, x;
1986
1987 #define CLAMP(x, h, l) ((x) > h ? h : ((x) < l) ? l : (x))
1988
1989 cps = tp->t_ospeed / 10;
1990 tp->t_lowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
1991 x += cps;
1992 x = CLAMP(x, TTMAXHIWAT, TTMINHIWAT);
1993 tp->t_hiwat = roundup(x, CBSIZE);
1994 #undef CLAMP
1995 }
1996
1997 /*
1998 * Report on state of foreground process group.
1999 */
2000 void
2001 ttyinfo(struct tty *tp)
2002 {
2003 struct proc *p, *pick;
2004 struct timeval utime, stime;
2005 int tmp;
2006
2007 if (ttycheckoutq(tp,0) == 0)
2008 return;
2009
2010 /* Print load average. */
2011 tmp = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
2012 ttyprintf(tp, "load: %d.%02d ", tmp / 100, tmp % 100);
2013
2014 if (tp->t_session == NULL)
2015 ttyprintf(tp, "not a controlling terminal\n");
2016 else if (tp->t_pgrp == NULL)
2017 ttyprintf(tp, "no foreground process group\n");
2018 else if ((p = tp->t_pgrp->pg_members.lh_first) == 0)
2019 ttyprintf(tp, "empty foreground process group\n");
2020 else {
2021 /* Pick interesting process. */
2022 for (pick = NULL; p != NULL; p = p->p_pglist.le_next)
2023 if (proc_compare(pick, p))
2024 pick = p;
2025
2026 ttyprintf(tp, " cmd: %s %d [%s] ", pick->p_comm, pick->p_pid,
2027 pick->p_stat == SONPROC ? "running" :
2028 pick->p_stat == SRUN ? "runnable" :
2029 pick->p_wmesg ? pick->p_wmesg : "iowait");
2030
2031 calcru(pick, &utime, &stime, NULL);
2032
2033 /* Round up and print user time. */
2034 utime.tv_usec += 5000;
2035 if (utime.tv_usec >= 1000000) {
2036 utime.tv_sec += 1;
2037 utime.tv_usec -= 1000000;
2038 }
2039 ttyprintf(tp, "%ld.%02ldu ", (long int)utime.tv_sec,
2040 (long int)utime.tv_usec / 10000);
2041
2042 /* Round up and print system time. */
2043 stime.tv_usec += 5000;
2044 if (stime.tv_usec >= 1000000) {
2045 stime.tv_sec += 1;
2046 stime.tv_usec -= 1000000;
2047 }
2048 ttyprintf(tp, "%ld.%02lds ", (long int)stime.tv_sec,
2049 (long int)stime.tv_usec / 10000);
2050
2051 #define pgtok(a) (((u_long) ((a) * PAGE_SIZE) / 1024))
2052 /* Print percentage cpu. */
2053 tmp = (pick->p_pctcpu * 10000 + FSCALE / 2) >> FSHIFT;
2054 ttyprintf(tp, "%d%% ", tmp / 100);
2055
2056 /* Print resident set size. */
2057 if (pick->p_stat == SIDL || P_ZOMBIE(pick))
2058 tmp = 0;
2059 else {
2060 struct vmspace *vm = pick->p_vmspace;
2061 tmp = pgtok(vm_resident_count(vm));
2062 }
2063 ttyprintf(tp, "%dk\n", tmp);
2064 }
2065 tp->t_rocount = 0; /* so pending input will be retyped if BS */
2066 }
2067
2068 /*
2069 * Returns 1 if p2 is "better" than p1
2070 *
2071 * The algorithm for picking the "interesting" process is thus:
2072 *
2073 * 1) Only foreground processes are eligible - implied.
2074 * 2) Runnable processes are favored over anything else. The runner
2075 * with the highest cpu utilization is picked (p_estcpu). Ties are
2076 * broken by picking the highest pid.
2077 * 3) The sleeper with the shortest sleep time is next. With ties,
2078 * we pick out just "short-term" sleepers (P_SINTR == 0).
2079 * 4) Further ties are broken by picking the highest pid.
2080 */
2081 #define ISRUN(p) (((p)->p_stat == SRUN) || ((p)->p_stat == SIDL) || \
2082 ((p)->p_stat == SONPROC))
2083 #define TESTAB(a, b) ((a)<<1 | (b))
2084 #define ONLYA 2
2085 #define ONLYB 1
2086 #define BOTH 3
2087
2088 static int
2089 proc_compare(struct proc *p1, struct proc *p2)
2090 {
2091
2092 if (p1 == NULL)
2093 return (1);
2094 /*
2095 * see if at least one of them is runnable
2096 */
2097 switch (TESTAB(ISRUN(p1), ISRUN(p2))) {
2098 case ONLYA:
2099 return (0);
2100 case ONLYB:
2101 return (1);
2102 case BOTH:
2103 /*
2104 * tie - favor one with highest recent cpu utilization
2105 */
2106 if (p2->p_estcpu > p1->p_estcpu)
2107 return (1);
2108 if (p1->p_estcpu > p2->p_estcpu)
2109 return (0);
2110 return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
2111 }
2112 /*
2113 * weed out zombies
2114 */
2115 switch (TESTAB(P_ZOMBIE(p1), P_ZOMBIE(p2))) {
2116 case ONLYA:
2117 return (1);
2118 case ONLYB:
2119 return (0);
2120 case BOTH:
2121 return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
2122 }
2123 /*
2124 * pick the one with the smallest sleep time
2125 */
2126 if (p2->p_slptime > p1->p_slptime)
2127 return (0);
2128 if (p1->p_slptime > p2->p_slptime)
2129 return (1);
2130 /*
2131 * favor one sleeping in a non-interruptible sleep
2132 */
2133 if (p1->p_flag & P_SINTR && (p2->p_flag & P_SINTR) == 0)
2134 return (1);
2135 if (p2->p_flag & P_SINTR && (p1->p_flag & P_SINTR) == 0)
2136 return (0);
2137 return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
2138 }
2139
2140 /*
2141 * Output char to tty; console putchar style.
2142 */
2143 int
2144 tputchar(int c, struct tty *tp)
2145 {
2146 int s;
2147
2148 s = spltty();
2149 if (ISSET(tp->t_state,
2150 TS_CARR_ON | TS_ISOPEN) != (TS_CARR_ON | TS_ISOPEN)) {
2151 splx(s);
2152 return (-1);
2153 }
2154 if (c == '\n')
2155 (void)ttyoutput('\r', tp);
2156 (void)ttyoutput(c, tp);
2157 ttstart(tp);
2158 splx(s);
2159 return (0);
2160 }
2161
2162 /*
2163 * Sleep on chan, returning ERESTART if tty changed while we napped and
2164 * returning any errors (e.g. EINTR/ETIMEDOUT) reported by tsleep. If
2165 * the tty is revoked, restarting a pending call will redo validation done
2166 * at the start of the call.
2167 */
2168 int
2169 ttysleep(struct tty *tp, void *chan, int pri, const char *wmesg, int timo)
2170 {
2171 int error;
2172 short gen;
2173
2174 gen = tp->t_gen;
2175 if ((error = tsleep(chan, pri, wmesg, timo)) != 0)
2176 return (error);
2177 return (tp->t_gen == gen ? 0 : ERESTART);
2178 }
2179
2180 /*
2181 * Initialise the global tty list.
2182 */
2183 void
2184 tty_init(void)
2185 {
2186 ttyldisc_init();
2187
2188 TAILQ_INIT(&ttylist);
2189 tty_count = 0;
2190
2191 pool_init(&tty_pool, sizeof(struct tty), 0, 0, 0, "ttypl",
2192 0, pool_page_alloc_nointr, pool_page_free_nointr, M_TTYS);
2193 }
2194
2195 /*
2196 * Attach a tty to the tty list.
2197 *
2198 * This should be called ONLY once per real tty (including pty's).
2199 * eg, on the sparc, the keyboard and mouse have struct tty's that are
2200 * distinctly NOT usable as tty's, and thus should not be attached to
2201 * the ttylist. This is why this call is not done from ttymalloc().
2202 *
2203 * Device drivers should attach tty's at a similar time that they are
2204 * ttymalloc()'ed, or, for the case of statically allocated struct tty's
2205 * either in the attach or (first) open routine.
2206 */
2207 void
2208 tty_attach(struct tty *tp)
2209 {
2210
2211 TAILQ_INSERT_TAIL(&ttylist, tp, tty_link);
2212 ++tty_count;
2213 }
2214
2215 /*
2216 * Remove a tty from the tty list.
2217 */
2218 void
2219 tty_detach(struct tty *tp)
2220 {
2221
2222 --tty_count;
2223 #ifdef DIAGNOSTIC
2224 if (tty_count < 0)
2225 panic("tty_detach: tty_count < 0");
2226 #endif
2227 TAILQ_REMOVE(&ttylist, tp, tty_link);
2228 }
2229
2230 /*
2231 * Allocate a tty structure and its associated buffers.
2232 */
2233 struct tty *
2234 ttymalloc(void)
2235 {
2236 struct tty *tp;
2237
2238 tp = pool_get(&tty_pool, PR_WAITOK);
2239 memset(tp, 0, sizeof(*tp));
2240 callout_init(&tp->t_outq_ch);
2241 callout_init(&tp->t_rstrt_ch);
2242 /* XXX: default to 1024 chars for now */
2243 clalloc(&tp->t_rawq, 1024, 1);
2244 clalloc(&tp->t_canq, 1024, 1);
2245 /* output queue doesn't need quoting */
2246 clalloc(&tp->t_outq, 1024, 0);
2247 /* Set default line discipline. */
2248 tp->t_linesw = linesw[0];
2249 return(tp);
2250 }
2251
2252 /*
2253 * Free a tty structure and its buffers.
2254 *
2255 * Be sure to call tty_detach() for any tty that has been
2256 * tty_attach()ed.
2257 */
2258 void
2259 ttyfree(struct tty *tp)
2260 {
2261
2262 callout_stop(&tp->t_outq_ch);
2263 callout_stop(&tp->t_rstrt_ch);
2264 clfree(&tp->t_rawq);
2265 clfree(&tp->t_canq);
2266 clfree(&tp->t_outq);
2267 pool_put(&tty_pool, tp);
2268 }
2269