tty.c revision 1.128.2.1 1 /* $NetBSD: tty.c,v 1.128.2.1 2001/07/10 13:48:05 lukem 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 }
1214 splx(s);
1215 }
1216
1217 /*
1218 * Copy in the default termios characters.
1219 */
1220 void
1221 ttychars(struct tty *tp)
1222 {
1223
1224 memcpy(tp->t_cc, ttydefchars, sizeof(ttydefchars));
1225 }
1226
1227 /*
1228 * Send stop character on input overflow.
1229 */
1230 static void
1231 ttyblock(struct tty *tp)
1232 {
1233 int total;
1234
1235 total = tp->t_rawq.c_cc + tp->t_canq.c_cc;
1236 if (tp->t_rawq.c_cc > TTYHOG) {
1237 ttyflush(tp, FREAD | FWRITE);
1238 CLR(tp->t_state, TS_TBLOCK);
1239 }
1240 /*
1241 * Block further input iff: current input > threshold
1242 * AND input is available to user program.
1243 */
1244 if (total >= TTYHOG / 2 &&
1245 !ISSET(tp->t_state, TS_TBLOCK) &&
1246 (!ISSET(tp->t_lflag, ICANON) || tp->t_canq.c_cc > 0)) {
1247 if (ISSET(tp->t_iflag, IXOFF) &&
1248 tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
1249 putc(tp->t_cc[VSTOP], &tp->t_outq) == 0) {
1250 SET(tp->t_state, TS_TBLOCK);
1251 ttstart(tp);
1252 }
1253 /* Try to block remote output via hardware flow control. */
1254 if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
1255 (*tp->t_hwiflow)(tp, 1) != 0)
1256 SET(tp->t_state, TS_TBLOCK);
1257 }
1258 }
1259
1260 void
1261 ttrstrt(void *tp_arg)
1262 {
1263 struct tty *tp;
1264 int s;
1265
1266 #ifdef DIAGNOSTIC
1267 if (tp_arg == NULL)
1268 panic("ttrstrt");
1269 #endif
1270 tp = tp_arg;
1271 s = spltty();
1272
1273 CLR(tp->t_state, TS_TIMEOUT);
1274 ttstart(tp);
1275
1276 splx(s);
1277 }
1278
1279 int
1280 ttstart(struct tty *tp)
1281 {
1282
1283 if (tp->t_oproc != NULL) /* XXX: Kludge for pty. */
1284 (*tp->t_oproc)(tp);
1285 return (0);
1286 }
1287
1288 /*
1289 * "close" a line discipline
1290 */
1291 int
1292 ttylclose(struct tty *tp, int flag)
1293 {
1294
1295 if (flag & FNONBLOCK)
1296 ttyflush(tp, FREAD | FWRITE);
1297 else
1298 ttywflush(tp);
1299 return (0);
1300 }
1301
1302 /*
1303 * Handle modem control transition on a tty.
1304 * Flag indicates new state of carrier.
1305 * Returns 0 if the line should be turned off, otherwise 1.
1306 */
1307 int
1308 ttymodem(struct tty *tp, int flag)
1309 {
1310
1311 if (flag == 0) {
1312 if (ISSET(tp->t_state, TS_CARR_ON)) {
1313 /*
1314 * Lost carrier.
1315 */
1316 CLR(tp->t_state, TS_CARR_ON);
1317 if (ISSET(tp->t_state, TS_ISOPEN) && !CONNECTED(tp)) {
1318 if (tp->t_session && tp->t_session->s_leader)
1319 psignal(tp->t_session->s_leader, SIGHUP);
1320 ttyflush(tp, FREAD | FWRITE);
1321 return (0);
1322 }
1323 }
1324 } else {
1325 if (!ISSET(tp->t_state, TS_CARR_ON)) {
1326 /*
1327 * Carrier now on.
1328 */
1329 SET(tp->t_state, TS_CARR_ON);
1330 ttwakeup(tp);
1331 }
1332 }
1333 return (1);
1334 }
1335
1336 /*
1337 * Default modem control routine (for other line disciplines).
1338 * Return argument flag, to turn off device on carrier drop.
1339 */
1340 int
1341 nullmodem(struct tty *tp, int flag)
1342 {
1343
1344 if (flag)
1345 SET(tp->t_state, TS_CARR_ON);
1346 else {
1347 CLR(tp->t_state, TS_CARR_ON);
1348 if (!CONNECTED(tp)) {
1349 if (tp->t_session && tp->t_session->s_leader)
1350 psignal(tp->t_session->s_leader, SIGHUP);
1351 return (0);
1352 }
1353 }
1354 return (1);
1355 }
1356
1357 /*
1358 * Reinput pending characters after state switch
1359 * call at spltty().
1360 */
1361 void
1362 ttypend(struct tty *tp)
1363 {
1364 struct clist tq;
1365 int c;
1366
1367 CLR(tp->t_lflag, PENDIN);
1368 SET(tp->t_state, TS_TYPEN);
1369 tq = tp->t_rawq;
1370 tp->t_rawq.c_cc = 0;
1371 tp->t_rawq.c_cf = tp->t_rawq.c_cl = 0;
1372 while ((c = getc(&tq)) >= 0)
1373 ttyinput(c, tp);
1374 CLR(tp->t_state, TS_TYPEN);
1375 }
1376
1377 /*
1378 * Process a read call on a tty device.
1379 */
1380 int
1381 ttread(struct tty *tp, struct uio *uio, int flag)
1382 {
1383 struct clist *qp;
1384 u_char *cc;
1385 struct proc *p;
1386 int c, s, first, error, has_stime, last_cc;
1387 long lflag, slp;
1388 struct timeval stime;
1389
1390 cc = tp->t_cc;
1391 p = curproc;
1392 error = 0;
1393 has_stime = 0;
1394 last_cc = 0;
1395 slp = 0;
1396
1397 loop:
1398 lflag = tp->t_lflag;
1399 s = spltty();
1400 /*
1401 * take pending input first
1402 */
1403 if (ISSET(lflag, PENDIN))
1404 ttypend(tp);
1405 splx(s);
1406
1407 /*
1408 * Hang process if it's in the background.
1409 */
1410 if (isbackground(p, tp)) {
1411 if (sigismember(&p->p_sigctx.ps_sigignore, SIGTTIN) ||
1412 sigismember(&p->p_sigctx.ps_sigmask, SIGTTIN) ||
1413 p->p_flag & P_PPWAIT || p->p_pgrp->pg_jobc == 0)
1414 return (EIO);
1415 pgsignal(p->p_pgrp, SIGTTIN, 1);
1416 error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, ttybg, 0);
1417 if (error)
1418 return (error);
1419 goto loop;
1420 }
1421
1422 s = spltty();
1423 if (!ISSET(lflag, ICANON)) {
1424 int m = cc[VMIN];
1425 long t = cc[VTIME];
1426
1427 qp = &tp->t_rawq;
1428 /*
1429 * Check each of the four combinations.
1430 * (m > 0 && t == 0) is the normal read case.
1431 * It should be fairly efficient, so we check that and its
1432 * companion case (m == 0 && t == 0) first.
1433 * For the other two cases, we compute the target sleep time
1434 * into slp.
1435 */
1436 if (t == 0) {
1437 if (qp->c_cc < m)
1438 goto sleep;
1439 goto read;
1440 }
1441 t *= 100000; /* time in us */
1442 #define diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 1000000 + \
1443 ((t1).tv_usec - (t2).tv_usec))
1444 if (m > 0) {
1445 if (qp->c_cc <= 0)
1446 goto sleep;
1447 if (qp->c_cc >= m)
1448 goto read;
1449 if (!has_stime) {
1450 /* first character, start timer */
1451 has_stime = 1;
1452 stime = time;
1453 slp = t;
1454 } else if (qp->c_cc > last_cc) {
1455 /* got a character, restart timer */
1456 stime = time;
1457 slp = t;
1458 } else {
1459 /* nothing, check expiration */
1460 slp = t - diff(time, stime);
1461 }
1462 } else { /* m == 0 */
1463 if (qp->c_cc > 0)
1464 goto read;
1465 if (!has_stime) {
1466 has_stime = 1;
1467 stime = time;
1468 slp = t;
1469 } else
1470 slp = t - diff(time, stime);
1471 }
1472 last_cc = qp->c_cc;
1473 #undef diff
1474 if (slp > 0) {
1475 /*
1476 * Rounding down may make us wake up just short
1477 * of the target, so we round up.
1478 * The formula is ceiling(slp * hz/1000000).
1479 * 32-bit arithmetic is enough for hz < 169.
1480 *
1481 * Also, use plain wakeup() not ttwakeup().
1482 */
1483 slp = (long) (((u_long)slp * hz) + 999999) / 1000000;
1484 goto sleep;
1485 }
1486 } else if ((qp = &tp->t_canq)->c_cc <= 0) {
1487 int carrier;
1488
1489 sleep:
1490 /*
1491 * If there is no input, sleep on rawq
1492 * awaiting hardware receipt and notification.
1493 * If we have data, we don't need to check for carrier.
1494 */
1495 carrier = CONNECTED(tp);
1496 if (!carrier && ISSET(tp->t_state, TS_ISOPEN)) {
1497 splx(s);
1498 return (0); /* EOF */
1499 }
1500 if (flag & IO_NDELAY) {
1501 splx(s);
1502 return (EWOULDBLOCK);
1503 }
1504 error = ttysleep(tp, &tp->t_rawq, TTIPRI | PCATCH,
1505 carrier ? ttyin : ttopen, slp);
1506 splx(s);
1507 /* VMIN == 0: any quantity read satisfies */
1508 if (cc[VMIN] == 0 && error == EWOULDBLOCK)
1509 return (0);
1510 if (error && error != EWOULDBLOCK)
1511 return (error);
1512 goto loop;
1513 }
1514 read:
1515 splx(s);
1516
1517 /*
1518 * Input present, check for input mapping and processing.
1519 */
1520 first = 1;
1521 while ((c = getc(qp)) >= 0) {
1522 /*
1523 * delayed suspend (^Y)
1524 */
1525 if (CCEQ(cc[VDSUSP], c) &&
1526 ISSET(lflag, IEXTEN|ISIG) == (IEXTEN|ISIG)) {
1527 pgsignal(tp->t_pgrp, SIGTSTP, 1);
1528 if (first) {
1529 error = ttysleep(tp, &lbolt,
1530 TTIPRI | PCATCH, ttybg, 0);
1531 if (error)
1532 break;
1533 goto loop;
1534 }
1535 break;
1536 }
1537 /*
1538 * Interpret EOF only in canonical mode.
1539 */
1540 if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
1541 break;
1542 /*
1543 * Give user character.
1544 */
1545 error = ureadc(c, uio);
1546 if (error)
1547 break;
1548 if (uio->uio_resid == 0)
1549 break;
1550 /*
1551 * In canonical mode check for a "break character"
1552 * marking the end of a "line of input".
1553 */
1554 if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
1555 break;
1556 first = 0;
1557 }
1558 /*
1559 * Look to unblock output now that (presumably)
1560 * the input queue has gone down.
1561 */
1562 s = spltty();
1563 if (ISSET(tp->t_state, TS_TBLOCK) && tp->t_rawq.c_cc < TTYHOG/5) {
1564 if (ISSET(tp->t_iflag, IXOFF) &&
1565 cc[VSTART] != _POSIX_VDISABLE &&
1566 putc(cc[VSTART], &tp->t_outq) == 0) {
1567 CLR(tp->t_state, TS_TBLOCK);
1568 ttstart(tp);
1569 }
1570 /* Try to unblock remote output via hardware flow control. */
1571 if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
1572 (*tp->t_hwiflow)(tp, 0) != 0)
1573 CLR(tp->t_state, TS_TBLOCK);
1574 }
1575 splx(s);
1576 return (error);
1577 }
1578
1579 /*
1580 * Check the output queue on tp for space for a kernel message (from uprintf
1581 * or tprintf). Allow some space over the normal hiwater mark so we don't
1582 * lose messages due to normal flow control, but don't let the tty run amok.
1583 * Sleeps here are not interruptible, but we return prematurely if new signals
1584 * arrive.
1585 */
1586 int
1587 ttycheckoutq(struct tty *tp, int wait)
1588 {
1589 int hiwat, s, error;
1590
1591 hiwat = tp->t_hiwat;
1592 s = spltty();
1593 if (tp->t_outq.c_cc > hiwat + 200)
1594 while (tp->t_outq.c_cc > hiwat) {
1595 ttstart(tp);
1596 if (wait == 0) {
1597 splx(s);
1598 return (0);
1599 }
1600 callout_reset(&tp->t_outq_ch, hz,
1601 (void (*)__P((void *)))wakeup, &tp->t_outq);
1602 SET(tp->t_state, TS_ASLEEP);
1603 error = tsleep(&tp->t_outq, (PZERO - 1) | PCATCH,
1604 "ttckoutq", 0);
1605 if (error == EINTR)
1606 wait = 0;
1607 }
1608 splx(s);
1609 return (1);
1610 }
1611
1612 /*
1613 * Process a write call on a tty device.
1614 */
1615 int
1616 ttwrite(struct tty *tp, struct uio *uio, int flag)
1617 {
1618 u_char *cp;
1619 struct proc *p;
1620 int cc, ce, i, hiwat, cnt, error, s;
1621 u_char obuf[OBUFSIZ];
1622
1623 cp = NULL;
1624 hiwat = tp->t_hiwat;
1625 cnt = uio->uio_resid;
1626 error = 0;
1627 cc = 0;
1628 loop:
1629 s = spltty();
1630 if (!CONNECTED(tp)) {
1631 if (ISSET(tp->t_state, TS_ISOPEN)) {
1632 splx(s);
1633 return (EIO);
1634 } else if (flag & IO_NDELAY) {
1635 splx(s);
1636 error = EWOULDBLOCK;
1637 goto out;
1638 } else {
1639 /* Sleep awaiting carrier. */
1640 error = ttysleep(tp,
1641 &tp->t_rawq, TTIPRI | PCATCH, ttopen, 0);
1642 splx(s);
1643 if (error)
1644 goto out;
1645 goto loop;
1646 }
1647 }
1648 splx(s);
1649 /*
1650 * Hang the process if it's in the background.
1651 */
1652 p = curproc;
1653 if (isbackground(p, tp) &&
1654 ISSET(tp->t_lflag, TOSTOP) && (p->p_flag & P_PPWAIT) == 0 &&
1655 !sigismember(&p->p_sigctx.ps_sigignore, SIGTTOU) &&
1656 !sigismember(&p->p_sigctx.ps_sigmask, SIGTTOU)) {
1657 if (p->p_pgrp->pg_jobc == 0) {
1658 error = EIO;
1659 goto out;
1660 }
1661 pgsignal(p->p_pgrp, SIGTTOU, 1);
1662 error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, ttybg, 0);
1663 if (error)
1664 goto out;
1665 goto loop;
1666 }
1667 /*
1668 * Process the user's data in at most OBUFSIZ chunks. Perform any
1669 * output translation. Keep track of high water mark, sleep on
1670 * overflow awaiting device aid in acquiring new space.
1671 */
1672 while (uio->uio_resid > 0 || cc > 0) {
1673 if (ISSET(tp->t_lflag, FLUSHO)) {
1674 uio->uio_resid = 0;
1675 return (0);
1676 }
1677 if (tp->t_outq.c_cc > hiwat)
1678 goto ovhiwat;
1679 /*
1680 * Grab a hunk of data from the user, unless we have some
1681 * leftover from last time.
1682 */
1683 if (cc == 0) {
1684 cc = min(uio->uio_resid, OBUFSIZ);
1685 cp = obuf;
1686 error = uiomove(cp, cc, uio);
1687 if (error) {
1688 cc = 0;
1689 break;
1690 }
1691 }
1692 /*
1693 * If nothing fancy need be done, grab those characters we
1694 * can handle without any of ttyoutput's processing and
1695 * just transfer them to the output q. For those chars
1696 * which require special processing (as indicated by the
1697 * bits in char_type), call ttyoutput. After processing
1698 * a hunk of data, look for FLUSHO so ^O's will take effect
1699 * immediately.
1700 */
1701 while (cc > 0) {
1702 if (!ISSET(tp->t_oflag, OPOST))
1703 ce = cc;
1704 else {
1705 ce = cc - scanc((u_int)cc, cp, char_type,
1706 CCLASSMASK);
1707 /*
1708 * If ce is zero, then we're processing
1709 * a special character through ttyoutput.
1710 */
1711 if (ce == 0) {
1712 tp->t_rocount = 0;
1713 if (ttyoutput(*cp, tp) >= 0) {
1714 /* out of space */
1715 goto overfull;
1716 }
1717 cp++;
1718 cc--;
1719 if (ISSET(tp->t_lflag, FLUSHO) ||
1720 tp->t_outq.c_cc > hiwat)
1721 goto ovhiwat;
1722 continue;
1723 }
1724 }
1725 /*
1726 * A bunch of normal characters have been found.
1727 * Transfer them en masse to the output queue and
1728 * continue processing at the top of the loop.
1729 * If there are any further characters in this
1730 * <= OBUFSIZ chunk, the first should be a character
1731 * requiring special handling by ttyoutput.
1732 */
1733 tp->t_rocount = 0;
1734 i = b_to_q(cp, ce, &tp->t_outq);
1735 ce -= i;
1736 tp->t_column += ce;
1737 cp += ce, cc -= ce, tk_nout += ce;
1738 tp->t_outcc += ce;
1739 if (i > 0) {
1740 /* out of space */
1741 goto overfull;
1742 }
1743 if (ISSET(tp->t_lflag, FLUSHO) ||
1744 tp->t_outq.c_cc > hiwat)
1745 break;
1746 }
1747 ttstart(tp);
1748 }
1749 out:
1750 /*
1751 * If cc is nonzero, we leave the uio structure inconsistent, as the
1752 * offset and iov pointers have moved forward, but it doesn't matter
1753 * (the call will either return short or restart with a new uio).
1754 */
1755 uio->uio_resid += cc;
1756 return (error);
1757
1758 overfull:
1759 /*
1760 * Since we are using ring buffers, if we can't insert any more into
1761 * the output queue, we can assume the ring is full and that someone
1762 * forgot to set the high water mark correctly. We set it and then
1763 * proceed as normal.
1764 */
1765 hiwat = tp->t_outq.c_cc - 1;
1766
1767 ovhiwat:
1768 ttstart(tp);
1769 s = spltty();
1770 /*
1771 * This can only occur if FLUSHO is set in t_lflag,
1772 * or if ttstart/oproc is synchronous (or very fast).
1773 */
1774 if (tp->t_outq.c_cc <= hiwat) {
1775 splx(s);
1776 goto loop;
1777 }
1778 if (flag & IO_NDELAY) {
1779 splx(s);
1780 uio->uio_resid += cc;
1781 return (uio->uio_resid == cnt ? EWOULDBLOCK : 0);
1782 }
1783 SET(tp->t_state, TS_ASLEEP);
1784 error = ttysleep(tp, &tp->t_outq, TTOPRI | PCATCH, ttyout, 0);
1785 splx(s);
1786 if (error)
1787 goto out;
1788 goto loop;
1789 }
1790
1791 /*
1792 * Rubout one character from the rawq of tp
1793 * as cleanly as possible.
1794 */
1795 void
1796 ttyrub(int c, struct tty *tp)
1797 {
1798 u_char *cp;
1799 int savecol, tabc, s;
1800
1801 if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
1802 return;
1803 CLR(tp->t_lflag, FLUSHO);
1804 if (ISSET(tp->t_lflag, ECHOE)) {
1805 if (tp->t_rocount == 0) {
1806 /*
1807 * Screwed by ttwrite; retype
1808 */
1809 ttyretype(tp);
1810 return;
1811 }
1812 if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
1813 ttyrubo(tp, 2);
1814 else {
1815 CLR(c, ~TTY_CHARMASK);
1816 switch (CCLASS(c)) {
1817 case ORDINARY:
1818 ttyrubo(tp, 1);
1819 break;
1820 case BACKSPACE:
1821 case CONTROL:
1822 case NEWLINE:
1823 case RETURN:
1824 case VTAB:
1825 if (ISSET(tp->t_lflag, ECHOCTL))
1826 ttyrubo(tp, 2);
1827 break;
1828 case TAB:
1829 if (tp->t_rocount < tp->t_rawq.c_cc) {
1830 ttyretype(tp);
1831 return;
1832 }
1833 s = spltty();
1834 savecol = tp->t_column;
1835 SET(tp->t_state, TS_CNTTB);
1836 SET(tp->t_lflag, FLUSHO);
1837 tp->t_column = tp->t_rocol;
1838 for (cp = firstc(&tp->t_rawq, &tabc); cp;
1839 cp = nextc(&tp->t_rawq, cp, &tabc))
1840 ttyecho(tabc, tp);
1841 CLR(tp->t_lflag, FLUSHO);
1842 CLR(tp->t_state, TS_CNTTB);
1843 splx(s);
1844
1845 /* savecol will now be length of the tab. */
1846 savecol -= tp->t_column;
1847 tp->t_column += savecol;
1848 if (savecol > 8)
1849 savecol = 8; /* overflow screw */
1850 while (--savecol >= 0)
1851 (void)ttyoutput('\b', tp);
1852 break;
1853 default: /* XXX */
1854 #define PANICSTR "ttyrub: would panic c = %d, val = %d\n"
1855 (void)printf(PANICSTR, c, CCLASS(c));
1856 #ifdef notdef
1857 panic(PANICSTR, c, CCLASS(c));
1858 #endif
1859 }
1860 }
1861 } else if (ISSET(tp->t_lflag, ECHOPRT)) {
1862 if (!ISSET(tp->t_state, TS_ERASE)) {
1863 SET(tp->t_state, TS_ERASE);
1864 (void)ttyoutput('\\', tp);
1865 }
1866 ttyecho(c, tp);
1867 } else
1868 ttyecho(tp->t_cc[VERASE], tp);
1869 --tp->t_rocount;
1870 }
1871
1872 /*
1873 * Back over cnt characters, erasing them.
1874 */
1875 static void
1876 ttyrubo(struct tty *tp, int cnt)
1877 {
1878
1879 while (cnt-- > 0) {
1880 (void)ttyoutput('\b', tp);
1881 (void)ttyoutput(' ', tp);
1882 (void)ttyoutput('\b', tp);
1883 }
1884 }
1885
1886 /*
1887 * ttyretype --
1888 * Reprint the rawq line. Note, it is assumed that c_cc has already
1889 * been checked.
1890 */
1891 void
1892 ttyretype(struct tty *tp)
1893 {
1894 u_char *cp;
1895 int s, c;
1896
1897 /* Echo the reprint character. */
1898 if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
1899 ttyecho(tp->t_cc[VREPRINT], tp);
1900
1901 (void)ttyoutput('\n', tp);
1902
1903 s = spltty();
1904 for (cp = firstc(&tp->t_canq, &c); cp; cp = nextc(&tp->t_canq, cp, &c))
1905 ttyecho(c, tp);
1906 for (cp = firstc(&tp->t_rawq, &c); cp; cp = nextc(&tp->t_rawq, cp, &c))
1907 ttyecho(c, tp);
1908 CLR(tp->t_state, TS_ERASE);
1909 splx(s);
1910
1911 tp->t_rocount = tp->t_rawq.c_cc;
1912 tp->t_rocol = 0;
1913 }
1914
1915 /*
1916 * Echo a typed character to the terminal.
1917 */
1918 static void
1919 ttyecho(int c, struct tty *tp)
1920 {
1921
1922 if (!ISSET(tp->t_state, TS_CNTTB))
1923 CLR(tp->t_lflag, FLUSHO);
1924 if ((!ISSET(tp->t_lflag, ECHO) &&
1925 (!ISSET(tp->t_lflag, ECHONL) || c != '\n')) ||
1926 ISSET(tp->t_lflag, EXTPROC))
1927 return;
1928 if (((ISSET(tp->t_lflag, ECHOCTL) &&
1929 (ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n')) ||
1930 ISSET(c, TTY_CHARMASK) == 0177)) {
1931 (void)ttyoutput('^', tp);
1932 CLR(c, ~TTY_CHARMASK);
1933 if (c == 0177)
1934 c = '?';
1935 else
1936 c += 'A' - 1;
1937 }
1938 (void)ttyoutput(c, tp);
1939 }
1940
1941 /*
1942 * Wake up any readers on a tty.
1943 */
1944 void
1945 ttwakeup(struct tty *tp)
1946 {
1947
1948 selwakeup(&tp->t_rsel);
1949 if (ISSET(tp->t_state, TS_ASYNC))
1950 pgsignal(tp->t_pgrp, SIGIO, 1);
1951 wakeup((caddr_t)&tp->t_rawq);
1952 }
1953
1954 /*
1955 * Look up a code for a specified speed in a conversion table;
1956 * used by drivers to map software speed values to hardware parameters.
1957 */
1958 int
1959 ttspeedtab(int speed, struct speedtab *table)
1960 {
1961
1962 for ( ; table->sp_speed != -1; table++)
1963 if (table->sp_speed == speed)
1964 return (table->sp_code);
1965 return (-1);
1966 }
1967
1968 /*
1969 * Set tty hi and low water marks.
1970 *
1971 * Try to arrange the dynamics so there's about one second
1972 * from hi to low water.
1973 */
1974 void
1975 ttsetwater(struct tty *tp)
1976 {
1977 int cps, x;
1978
1979 #define CLAMP(x, h, l) ((x) > h ? h : ((x) < l) ? l : (x))
1980
1981 cps = tp->t_ospeed / 10;
1982 tp->t_lowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
1983 x += cps;
1984 x = CLAMP(x, TTMAXHIWAT, TTMINHIWAT);
1985 tp->t_hiwat = roundup(x, CBSIZE);
1986 #undef CLAMP
1987 }
1988
1989 /*
1990 * Report on state of foreground process group.
1991 */
1992 void
1993 ttyinfo(struct tty *tp)
1994 {
1995 struct proc *p, *pick;
1996 struct timeval utime, stime;
1997 int tmp;
1998
1999 if (ttycheckoutq(tp,0) == 0)
2000 return;
2001
2002 /* Print load average. */
2003 tmp = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
2004 ttyprintf(tp, "load: %d.%02d ", tmp / 100, tmp % 100);
2005
2006 if (tp->t_session == NULL)
2007 ttyprintf(tp, "not a controlling terminal\n");
2008 else if (tp->t_pgrp == NULL)
2009 ttyprintf(tp, "no foreground process group\n");
2010 else if ((p = tp->t_pgrp->pg_members.lh_first) == 0)
2011 ttyprintf(tp, "empty foreground process group\n");
2012 else {
2013 /* Pick interesting process. */
2014 for (pick = NULL; p != NULL; p = p->p_pglist.le_next)
2015 if (proc_compare(pick, p))
2016 pick = p;
2017
2018 ttyprintf(tp, " cmd: %s %d [%s] ", pick->p_comm, pick->p_pid,
2019 pick->p_stat == SONPROC ? "running" :
2020 pick->p_stat == SRUN ? "runnable" :
2021 pick->p_wmesg ? pick->p_wmesg : "iowait");
2022
2023 calcru(pick, &utime, &stime, NULL);
2024
2025 /* Round up and print user time. */
2026 utime.tv_usec += 5000;
2027 if (utime.tv_usec >= 1000000) {
2028 utime.tv_sec += 1;
2029 utime.tv_usec -= 1000000;
2030 }
2031 ttyprintf(tp, "%ld.%02ldu ", (long int)utime.tv_sec,
2032 (long int)utime.tv_usec / 10000);
2033
2034 /* Round up and print system time. */
2035 stime.tv_usec += 5000;
2036 if (stime.tv_usec >= 1000000) {
2037 stime.tv_sec += 1;
2038 stime.tv_usec -= 1000000;
2039 }
2040 ttyprintf(tp, "%ld.%02lds ", (long int)stime.tv_sec,
2041 (long int)stime.tv_usec / 10000);
2042
2043 #define pgtok(a) (((u_long) ((a) * PAGE_SIZE) / 1024))
2044 /* Print percentage cpu. */
2045 tmp = (pick->p_pctcpu * 10000 + FSCALE / 2) >> FSHIFT;
2046 ttyprintf(tp, "%d%% ", tmp / 100);
2047
2048 /* Print resident set size. */
2049 if (pick->p_stat == SIDL || P_ZOMBIE(pick))
2050 tmp = 0;
2051 else {
2052 struct vmspace *vm = pick->p_vmspace;
2053 tmp = pgtok(vm_resident_count(vm));
2054 }
2055 ttyprintf(tp, "%dk\n", tmp);
2056 }
2057 tp->t_rocount = 0; /* so pending input will be retyped if BS */
2058 }
2059
2060 /*
2061 * Returns 1 if p2 is "better" than p1
2062 *
2063 * The algorithm for picking the "interesting" process is thus:
2064 *
2065 * 1) Only foreground processes are eligible - implied.
2066 * 2) Runnable processes are favored over anything else. The runner
2067 * with the highest cpu utilization is picked (p_estcpu). Ties are
2068 * broken by picking the highest pid.
2069 * 3) The sleeper with the shortest sleep time is next. With ties,
2070 * we pick out just "short-term" sleepers (P_SINTR == 0).
2071 * 4) Further ties are broken by picking the highest pid.
2072 */
2073 #define ISRUN(p) (((p)->p_stat == SRUN) || ((p)->p_stat == SIDL) || \
2074 ((p)->p_stat == SONPROC))
2075 #define TESTAB(a, b) ((a)<<1 | (b))
2076 #define ONLYA 2
2077 #define ONLYB 1
2078 #define BOTH 3
2079
2080 static int
2081 proc_compare(struct proc *p1, struct proc *p2)
2082 {
2083
2084 if (p1 == NULL)
2085 return (1);
2086 /*
2087 * see if at least one of them is runnable
2088 */
2089 switch (TESTAB(ISRUN(p1), ISRUN(p2))) {
2090 case ONLYA:
2091 return (0);
2092 case ONLYB:
2093 return (1);
2094 case BOTH:
2095 /*
2096 * tie - favor one with highest recent cpu utilization
2097 */
2098 if (p2->p_estcpu > p1->p_estcpu)
2099 return (1);
2100 if (p1->p_estcpu > p2->p_estcpu)
2101 return (0);
2102 return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
2103 }
2104 /*
2105 * weed out zombies
2106 */
2107 switch (TESTAB(P_ZOMBIE(p1), P_ZOMBIE(p2))) {
2108 case ONLYA:
2109 return (1);
2110 case ONLYB:
2111 return (0);
2112 case BOTH:
2113 return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
2114 }
2115 /*
2116 * pick the one with the smallest sleep time
2117 */
2118 if (p2->p_slptime > p1->p_slptime)
2119 return (0);
2120 if (p1->p_slptime > p2->p_slptime)
2121 return (1);
2122 /*
2123 * favor one sleeping in a non-interruptible sleep
2124 */
2125 if (p1->p_flag & P_SINTR && (p2->p_flag & P_SINTR) == 0)
2126 return (1);
2127 if (p2->p_flag & P_SINTR && (p1->p_flag & P_SINTR) == 0)
2128 return (0);
2129 return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
2130 }
2131
2132 /*
2133 * Output char to tty; console putchar style.
2134 */
2135 int
2136 tputchar(int c, struct tty *tp)
2137 {
2138 int s;
2139
2140 s = spltty();
2141 if (ISSET(tp->t_state,
2142 TS_CARR_ON | TS_ISOPEN) != (TS_CARR_ON | TS_ISOPEN)) {
2143 splx(s);
2144 return (-1);
2145 }
2146 if (c == '\n')
2147 (void)ttyoutput('\r', tp);
2148 (void)ttyoutput(c, tp);
2149 ttstart(tp);
2150 splx(s);
2151 return (0);
2152 }
2153
2154 /*
2155 * Sleep on chan, returning ERESTART if tty changed while we napped and
2156 * returning any errors (e.g. EINTR/ETIMEDOUT) reported by tsleep. If
2157 * the tty is revoked, restarting a pending call will redo validation done
2158 * at the start of the call.
2159 */
2160 int
2161 ttysleep(struct tty *tp, void *chan, int pri, const char *wmesg, int timo)
2162 {
2163 int error;
2164 short gen;
2165
2166 gen = tp->t_gen;
2167 if ((error = tsleep(chan, pri, wmesg, timo)) != 0)
2168 return (error);
2169 return (tp->t_gen == gen ? 0 : ERESTART);
2170 }
2171
2172 /*
2173 * Initialise the global tty list.
2174 */
2175 void
2176 tty_init(void)
2177 {
2178 ttyldisc_init();
2179
2180 TAILQ_INIT(&ttylist);
2181 tty_count = 0;
2182
2183 pool_init(&tty_pool, sizeof(struct tty), 0, 0, 0, "ttypl",
2184 0, pool_page_alloc_nointr, pool_page_free_nointr, M_TTYS);
2185 }
2186
2187 /*
2188 * Attach a tty to the tty list.
2189 *
2190 * This should be called ONLY once per real tty (including pty's).
2191 * eg, on the sparc, the keyboard and mouse have struct tty's that are
2192 * distinctly NOT usable as tty's, and thus should not be attached to
2193 * the ttylist. This is why this call is not done from ttymalloc().
2194 *
2195 * Device drivers should attach tty's at a similar time that they are
2196 * ttymalloc()'ed, or, for the case of statically allocated struct tty's
2197 * either in the attach or (first) open routine.
2198 */
2199 void
2200 tty_attach(struct tty *tp)
2201 {
2202
2203 TAILQ_INSERT_TAIL(&ttylist, tp, tty_link);
2204 ++tty_count;
2205 }
2206
2207 /*
2208 * Remove a tty from the tty list.
2209 */
2210 void
2211 tty_detach(struct tty *tp)
2212 {
2213
2214 --tty_count;
2215 #ifdef DIAGNOSTIC
2216 if (tty_count < 0)
2217 panic("tty_detach: tty_count < 0");
2218 #endif
2219 TAILQ_REMOVE(&ttylist, tp, tty_link);
2220 }
2221
2222 /*
2223 * Allocate a tty structure and its associated buffers.
2224 */
2225 struct tty *
2226 ttymalloc(void)
2227 {
2228 struct tty *tp;
2229
2230 tp = pool_get(&tty_pool, PR_WAITOK);
2231 memset(tp, 0, sizeof(*tp));
2232 callout_init(&tp->t_outq_ch);
2233 callout_init(&tp->t_rstrt_ch);
2234 /* XXX: default to 1024 chars for now */
2235 clalloc(&tp->t_rawq, 1024, 1);
2236 clalloc(&tp->t_canq, 1024, 1);
2237 /* output queue doesn't need quoting */
2238 clalloc(&tp->t_outq, 1024, 0);
2239 /* Set default line discipline. */
2240 tp->t_linesw = linesw[0];
2241 return(tp);
2242 }
2243
2244 /*
2245 * Free a tty structure and its buffers.
2246 *
2247 * Be sure to call tty_detach() for any tty that has been
2248 * tty_attach()ed.
2249 */
2250 void
2251 ttyfree(struct tty *tp)
2252 {
2253
2254 callout_stop(&tp->t_outq_ch);
2255 callout_stop(&tp->t_rstrt_ch);
2256 clfree(&tp->t_rawq);
2257 clfree(&tp->t_canq);
2258 clfree(&tp->t_outq);
2259 pool_put(&tty_pool, tp);
2260 }
2261