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