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