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