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