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