xref: /netbsd-src/sys/kern/tty.c (revision b5677b36047b601b9addaaa494a58ceae82c2a6c)
1 /*	$NetBSD: tty.c,v 1.230 2009/01/22 20:40:20 drochner 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.230 2009/01/22 20:40:20 drochner 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 	mutex_enter(proc_lock);
348 	if (sess != NULL)
349 		SESSRELE(sess);
350 	mutex_exit(proc_lock);
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 			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 (flag & IO_NDELAY) {
1799 			mutex_spin_exit(&tty_lock);
1800 			return (EWOULDBLOCK);
1801 		}
1802 		error = ttysleep(tp, &tp->t_rawcv, true, slp);
1803 		mutex_spin_exit(&tty_lock);
1804 		/* VMIN == 0: any quantity read satisfies */
1805 		if (cc[VMIN] == 0 && error == EWOULDBLOCK)
1806 			return (0);
1807 		if (error && error != EWOULDBLOCK)
1808 			return (error);
1809 		goto loop;
1810 	}
1811  read:
1812 	mutex_spin_exit(&tty_lock);
1813 
1814 	/*
1815 	 * Input present, check for input mapping and processing.
1816 	 */
1817 	first = 1;
1818 	while ((c = getc(qp)) >= 0) {
1819 		/*
1820 		 * delayed suspend (^Y)
1821 		 */
1822 		if (CCEQ(cc[VDSUSP], c) &&
1823 		    ISSET(lflag, IEXTEN|ISIG) == (IEXTEN|ISIG)) {
1824 			mutex_spin_enter(&tty_lock);
1825 			ttysig(tp, TTYSIG_PG1, SIGTSTP);
1826 			if (first) {
1827 				error = ttysleep(tp, &lbolt, true, 0);
1828 				mutex_spin_exit(&tty_lock);
1829 				if (error)
1830 					break;
1831 				goto loop;
1832 			} else
1833 				mutex_spin_exit(&tty_lock);
1834 			break;
1835 		}
1836 		/*
1837 		 * Interpret EOF only in canonical mode.
1838 		 */
1839 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
1840 			break;
1841 		/*
1842 		 * Give user character.
1843 		 */
1844  		error = ureadc(c, uio);
1845 		if (error)
1846 			break;
1847  		if (uio->uio_resid == 0)
1848 			break;
1849 		/*
1850 		 * In canonical mode check for a "break character"
1851 		 * marking the end of a "line of input".
1852 		 */
1853 		if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
1854 			break;
1855 		first = 0;
1856 	}
1857 	/*
1858 	 * Look to unblock output now that (presumably)
1859 	 * the input queue has gone down.
1860 	 */
1861 	mutex_spin_enter(&tty_lock);
1862 	if (ISSET(tp->t_state, TS_TBLOCK) && tp->t_rawq.c_cc < TTYHOG / 5) {
1863 		if (ISSET(tp->t_iflag, IXOFF) &&
1864 		    cc[VSTART] != _POSIX_VDISABLE &&
1865 		    putc(cc[VSTART], &tp->t_outq) == 0) {
1866 			CLR(tp->t_state, TS_TBLOCK);
1867 			ttstart(tp);
1868 		}
1869 		/* Try to unblock remote output via hardware flow control. */
1870 		if (ISSET(tp->t_cflag, CHWFLOW) && tp->t_hwiflow &&
1871 		    (*tp->t_hwiflow)(tp, 0) != 0)
1872 			CLR(tp->t_state, TS_TBLOCK);
1873 	}
1874 	mutex_spin_exit(&tty_lock);
1875 
1876 	return (error);
1877 }
1878 
1879 /*
1880  * Check the output queue on tp for space for a kernel message (from uprintf
1881  * or tprintf).  Allow some space over the normal hiwater mark so we don't
1882  * lose messages due to normal flow control, but don't let the tty run amok.
1883  * Sleeps here are not interruptible, but we return prematurely if new signals
1884  * arrive.
1885  * Call with tty lock held.
1886  */
1887 static int
1888 ttycheckoutq_wlock(struct tty *tp, int wait)
1889 {
1890 	int	hiwat, error;
1891 
1892 	KASSERT(mutex_owned(&tty_lock));
1893 
1894 	hiwat = tp->t_hiwat;
1895 	if (tp->t_outq.c_cc > hiwat + 200)
1896 		while (tp->t_outq.c_cc > hiwat) {
1897 			ttstart(tp);
1898 			if (wait == 0)
1899 				return (0);
1900 			error = ttysleep(tp, &tp->t_outcv, true, hz);
1901 			if (error == EINTR)
1902 				wait = 0;
1903 		}
1904 
1905 	return (1);
1906 }
1907 
1908 int
1909 ttycheckoutq(struct tty *tp, int wait)
1910 {
1911 	int	r;
1912 
1913 	mutex_spin_enter(&tty_lock);
1914 	r = ttycheckoutq_wlock(tp, wait);
1915 	mutex_spin_exit(&tty_lock);
1916 
1917 	return (r);
1918 }
1919 
1920 /*
1921  * Process a write call on a tty device.
1922  */
1923 int
1924 ttwrite(struct tty *tp, struct uio *uio, int flag)
1925 {
1926 	u_char		*cp;
1927 	struct proc	*p;
1928 	int		cc, ce, i, hiwat, error;
1929 	u_char		obuf[OBUFSIZ];
1930 
1931 	cp = NULL;
1932 	hiwat = tp->t_hiwat;
1933 	error = 0;
1934 	cc = 0;
1935  loop:
1936 	mutex_spin_enter(&tty_lock);
1937 	if (!CONNECTED(tp)) {
1938 		if (ISSET(tp->t_state, TS_ISOPEN)) {
1939 			mutex_spin_exit(&tty_lock);
1940 			return (EIO);
1941 		} else if (flag & IO_NDELAY) {
1942 			mutex_spin_exit(&tty_lock);
1943 			error = EWOULDBLOCK;
1944 			goto out;
1945 		} else {
1946 			/* Sleep awaiting carrier. */
1947 			error = ttysleep(tp, &tp->t_rawcv, true, 0);
1948 			mutex_spin_exit(&tty_lock);
1949 			if (error)
1950 				goto out;
1951 			goto loop;
1952 		}
1953 	}
1954 
1955 	/*
1956 	 * Hang the process if it's in the background.
1957 	 */
1958 	p = curproc;
1959 	if (isbackground(p, tp) &&
1960 	    ISSET(tp->t_lflag, TOSTOP) && (p->p_lflag & PL_PPWAIT) == 0 &&
1961 	    !sigismasked(curlwp, SIGTTOU)) {
1962 		if (p->p_pgrp->pg_jobc == 0) {
1963 			error = EIO;
1964 			mutex_spin_exit(&tty_lock);
1965 			goto out;
1966 		}
1967 		mutex_spin_exit(&tty_lock);
1968 
1969 		mutex_enter(proc_lock);
1970 		pgsignal(p->p_pgrp, SIGTTOU, 1);
1971 		mutex_exit(proc_lock);
1972 
1973 		mutex_spin_enter(&tty_lock);
1974 		error = ttysleep(tp, &lbolt, true, 0);
1975 		mutex_spin_exit(&tty_lock);
1976 		if (error)
1977 			goto out;
1978 		goto loop;
1979 	}
1980 	mutex_spin_exit(&tty_lock);
1981 
1982 	/*
1983 	 * Process the user's data in at most OBUFSIZ chunks.  Perform any
1984 	 * output translation.  Keep track of high water mark, sleep on
1985 	 * overflow awaiting device aid in acquiring new space.
1986 	 */
1987 	while (uio->uio_resid > 0 || cc > 0) {
1988 		if (ISSET(tp->t_lflag, FLUSHO)) {
1989 			uio->uio_resid = 0;
1990 			return (0);
1991 		}
1992 		if (tp->t_outq.c_cc > hiwat)
1993 			goto ovhiwat;
1994 		/*
1995 		 * Grab a hunk of data from the user, unless we have some
1996 		 * leftover from last time.
1997 		 */
1998 		if (cc == 0) {
1999 			cc = min(uio->uio_resid, OBUFSIZ);
2000 			cp = obuf;
2001 			error = uiomove(cp, cc, uio);
2002 			if (error) {
2003 				cc = 0;
2004 				goto out;
2005 			}
2006 		}
2007 		/*
2008 		 * If nothing fancy need be done, grab those characters we
2009 		 * can handle without any of ttyoutput's processing and
2010 		 * just transfer them to the output q.  For those chars
2011 		 * which require special processing (as indicated by the
2012 		 * bits in char_type), call ttyoutput.  After processing
2013 		 * a hunk of data, look for FLUSHO so ^O's will take effect
2014 		 * immediately.
2015 		 */
2016 		mutex_spin_enter(&tty_lock);
2017 		while (cc > 0) {
2018 			if (!ISSET(tp->t_oflag, OPOST))
2019 				ce = cc;
2020 			else {
2021 				ce = cc - scanc((u_int)cc, cp, char_type,
2022 				    CCLASSMASK);
2023 				/*
2024 				 * If ce is zero, then we're processing
2025 				 * a special character through ttyoutput.
2026 				 */
2027 				if (ce == 0) {
2028 					tp->t_rocount = 0;
2029 					if (ttyoutput(*cp, tp) >= 0) {
2030 						/* out of space */
2031 						mutex_spin_exit(&tty_lock);
2032 						goto overfull;
2033 					}
2034 					cp++;
2035 					cc--;
2036 					if (ISSET(tp->t_lflag, FLUSHO) ||
2037 					    tp->t_outq.c_cc > hiwat) {
2038 						mutex_spin_exit(&tty_lock);
2039 						goto ovhiwat;
2040 					}
2041 					continue;
2042 				}
2043 			}
2044 			/*
2045 			 * A bunch of normal characters have been found.
2046 			 * Transfer them en masse to the output queue and
2047 			 * continue processing at the top of the loop.
2048 			 * If there are any further characters in this
2049 			 * <= OBUFSIZ chunk, the first should be a character
2050 			 * requiring special handling by ttyoutput.
2051 			 */
2052 			tp->t_rocount = 0;
2053 			i = b_to_q(cp, ce, &tp->t_outq);
2054 			ce -= i;
2055 			tp->t_column += ce;
2056 			cp += ce, cc -= ce, tk_nout += ce;
2057 			tp->t_outcc += ce;
2058 			if (i > 0) {
2059 				/* out of space */
2060 				mutex_spin_exit(&tty_lock);
2061 				goto overfull;
2062 			}
2063 			if (ISSET(tp->t_lflag, FLUSHO) ||
2064 			    tp->t_outq.c_cc > hiwat)
2065 				break;
2066 		}
2067 		ttstart(tp);
2068 		mutex_spin_exit(&tty_lock);
2069 	}
2070 
2071  out:
2072 	/*
2073 	 * If cc is nonzero, we leave the uio structure inconsistent, as the
2074 	 * offset and iov pointers have moved forward, but it doesn't matter
2075 	 * (the call will either return short or restart with a new uio).
2076 	 */
2077 	uio->uio_resid += cc;
2078 	return (error);
2079 
2080  overfull:
2081 	/*
2082 	 * Since we are using ring buffers, if we can't insert any more into
2083 	 * the output queue, we can assume the ring is full and that someone
2084 	 * forgot to set the high water mark correctly.  We set it and then
2085 	 * proceed as normal.
2086 	 */
2087 	hiwat = tp->t_outq.c_cc - 1;
2088 
2089  ovhiwat:
2090 	mutex_spin_enter(&tty_lock);
2091 	ttstart(tp);
2092 	/*
2093 	 * This can only occur if FLUSHO is set in t_lflag,
2094 	 * or if ttstart/oproc is synchronous (or very fast).
2095 	 */
2096 	if (tp->t_outq.c_cc <= hiwat) {
2097 		mutex_spin_exit(&tty_lock);
2098 		goto loop;
2099 	}
2100 	if (flag & IO_NDELAY) {
2101 		mutex_spin_exit(&tty_lock);
2102 		error = EWOULDBLOCK;
2103 		goto out;
2104 	}
2105 	error = ttysleep(tp, &tp->t_outcv, true, 0);
2106 	mutex_spin_exit(&tty_lock);
2107 	if (error)
2108 		goto out;
2109 	goto loop;
2110 }
2111 
2112 /*
2113  * Try to pull more output from the producer.  Return non-zero if
2114  * there is output ready to be sent.
2115  */
2116 bool
2117 ttypull(struct tty *tp)
2118 {
2119 
2120 	/* XXXSMP not yet KASSERT(mutex_owned(&tty_lock)); */
2121 
2122 	if (tp->t_outq.c_cc <= tp->t_lowat) {
2123 		cv_broadcast(&tp->t_outcv);
2124 		selnotify(&tp->t_wsel, 0, NOTE_SUBMIT);
2125 	}
2126 	return tp->t_outq.c_cc != 0;
2127 }
2128 
2129 /*
2130  * Rubout one character from the rawq of tp
2131  * as cleanly as possible.
2132  * Called with tty lock held.
2133  */
2134 void
2135 ttyrub(int c, struct tty *tp)
2136 {
2137 	u_char	*cp;
2138 	int	savecol, tabc;
2139 
2140 	KASSERT(mutex_owned(&tty_lock));
2141 
2142 	if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
2143 		return;
2144 	CLR(tp->t_lflag, FLUSHO);
2145 	if (ISSET(tp->t_lflag, ECHOE)) {
2146 		if (tp->t_rocount == 0) {
2147 			/*
2148 			 * Screwed by ttwrite; retype
2149 			 */
2150 			ttyretype(tp);
2151 			return;
2152 		}
2153 		if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
2154 			ttyrubo(tp, 2);
2155 		else {
2156 			CLR(c, ~TTY_CHARMASK);
2157 			switch (CCLASS(c)) {
2158 			case ORDINARY:
2159 				ttyrubo(tp, 1);
2160 				break;
2161 			case BACKSPACE:
2162 			case CONTROL:
2163 			case NEWLINE:
2164 			case RETURN:
2165 			case VTAB:
2166 				if (ISSET(tp->t_lflag, ECHOCTL))
2167 					ttyrubo(tp, 2);
2168 				break;
2169 			case TAB:
2170 				if (tp->t_rocount < tp->t_rawq.c_cc) {
2171 					ttyretype(tp);
2172 					return;
2173 				}
2174 				savecol = tp->t_column;
2175 				SET(tp->t_state, TS_CNTTB);
2176 				SET(tp->t_lflag, FLUSHO);
2177 				tp->t_column = tp->t_rocol;
2178 				for (cp = firstc(&tp->t_rawq, &tabc); cp;
2179 				    cp = nextc(&tp->t_rawq, cp, &tabc))
2180 					ttyecho(tabc, tp);
2181 				CLR(tp->t_lflag, FLUSHO);
2182 				CLR(tp->t_state, TS_CNTTB);
2183 
2184 				/* savecol will now be length of the tab. */
2185 				savecol -= tp->t_column;
2186 				tp->t_column += savecol;
2187 				if (savecol > 8)
2188 					savecol = 8;	/* overflow screw */
2189 				while (--savecol >= 0)
2190 					(void)ttyoutput('\b', tp);
2191 				break;
2192 			default:			/* XXX */
2193 				(void)printf("ttyrub: would panic c = %d, "
2194 				    "val = %d\n", c, CCLASS(c));
2195 			}
2196 		}
2197 	} else if (ISSET(tp->t_lflag, ECHOPRT)) {
2198 		if (!ISSET(tp->t_state, TS_ERASE)) {
2199 			SET(tp->t_state, TS_ERASE);
2200 			(void)ttyoutput('\\', tp);
2201 		}
2202 		ttyecho(c, tp);
2203 	} else
2204 		ttyecho(tp->t_cc[VERASE], tp);
2205 	--tp->t_rocount;
2206 }
2207 
2208 /*
2209  * Back over cnt characters, erasing them.
2210  * Called with tty lock held.
2211  */
2212 static void
2213 ttyrubo(struct tty *tp, int cnt)
2214 {
2215 
2216 	KASSERT(mutex_owned(&tty_lock));
2217 
2218 	while (cnt-- > 0) {
2219 		(void)ttyoutput('\b', tp);
2220 		(void)ttyoutput(' ', tp);
2221 		(void)ttyoutput('\b', tp);
2222 	}
2223 }
2224 
2225 /*
2226  * ttyretype --
2227  *	Reprint the rawq line.  Note, it is assumed that c_cc has already
2228  *	been checked.
2229  *
2230  * Called with tty lock held.
2231  */
2232 void
2233 ttyretype(struct tty *tp)
2234 {
2235 	u_char	*cp;
2236 	int	c;
2237 
2238 	KASSERT(mutex_owned(&tty_lock));
2239 
2240 	/* Echo the reprint character. */
2241 	if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
2242 		ttyecho(tp->t_cc[VREPRINT], tp);
2243 
2244 	(void)ttyoutput('\n', tp);
2245 
2246 	for (cp = firstc(&tp->t_canq, &c); cp; cp = nextc(&tp->t_canq, cp, &c))
2247 		ttyecho(c, tp);
2248 	for (cp = firstc(&tp->t_rawq, &c); cp; cp = nextc(&tp->t_rawq, cp, &c))
2249 		ttyecho(c, tp);
2250 	CLR(tp->t_state, TS_ERASE);
2251 
2252 	tp->t_rocount = tp->t_rawq.c_cc;
2253 	tp->t_rocol = 0;
2254 }
2255 
2256 /*
2257  * Echo a typed character to the terminal.
2258  * Called with tty lock held.
2259  */
2260 static void
2261 ttyecho(int c, struct tty *tp)
2262 {
2263 
2264 	KASSERT(mutex_owned(&tty_lock));
2265 
2266 	if (!ISSET(tp->t_state, TS_CNTTB))
2267 		CLR(tp->t_lflag, FLUSHO);
2268 	if ((!ISSET(tp->t_lflag, ECHO) &&
2269 	    (!ISSET(tp->t_lflag, ECHONL) || c != '\n')) ||
2270 	    ISSET(tp->t_lflag, EXTPROC))
2271 		return;
2272 	if (((ISSET(tp->t_lflag, ECHOCTL) &&
2273 	    (ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n')) ||
2274 	    ISSET(c, TTY_CHARMASK) == 0177)) {
2275 		(void)ttyoutput('^', tp);
2276 		CLR(c, ~TTY_CHARMASK);
2277 		if (c == 0177)
2278 			c = '?';
2279 		else
2280 			c += 'A' - 1;
2281 	}
2282 	(void)ttyoutput(c, tp);
2283 }
2284 
2285 /*
2286  * Wake up any readers on a tty.
2287  * Called with tty lock held.
2288  */
2289 void
2290 ttwakeup(struct tty *tp)
2291 {
2292 
2293 	KASSERT(mutex_owned(&tty_lock));
2294 
2295 	selnotify(&tp->t_rsel, 0, NOTE_SUBMIT);
2296 	if (ISSET(tp->t_state, TS_ASYNC))
2297 		ttysig(tp, TTYSIG_PG2, SIGIO);
2298 	cv_broadcast(&tp->t_rawcv);
2299 }
2300 
2301 /*
2302  * Look up a code for a specified speed in a conversion table;
2303  * used by drivers to map software speed values to hardware parameters.
2304  */
2305 int
2306 ttspeedtab(int speed, const struct speedtab *table)
2307 {
2308 
2309 	for (; table->sp_speed != -1; table++)
2310 		if (table->sp_speed == speed)
2311 			return (table->sp_code);
2312 	return (-1);
2313 }
2314 
2315 /*
2316  * Set tty hi and low water marks.
2317  *
2318  * Try to arrange the dynamics so there's about one second
2319  * from hi to low water.
2320  */
2321 void
2322 ttsetwater(struct tty *tp)
2323 {
2324 	int	cps, x;
2325 
2326 	/* XXX not yet KASSERT(mutex_owned(&tty_lock)); */
2327 
2328 #define	CLAMP(x, h, l)	((x) > h ? h : ((x) < l) ? l : (x))
2329 
2330 	cps = tp->t_ospeed / 10;
2331 	tp->t_lowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
2332 	x += cps;
2333 	x = CLAMP(x, TTMAXHIWAT, TTMINHIWAT);
2334 	tp->t_hiwat = roundup(x, CBSIZE);
2335 #undef	CLAMP
2336 }
2337 
2338 /*
2339  * Prepare report on state of foreground process group.
2340  * Call with proc_lock held.
2341  */
2342 void
2343 ttygetinfo(struct tty *tp, int fromsig, char *buf, size_t bufsz)
2344 {
2345 	struct lwp	*l;
2346 	struct proc	*p, *pick = NULL;
2347 	struct timeval	utime, stime;
2348 	int		tmp;
2349 	fixpt_t		pctcpu = 0;
2350 	const char	*msg;
2351 	char		lmsg[100];
2352 	long		rss;
2353 
2354 	KASSERT(mutex_owned(proc_lock));
2355 
2356 	*buf = '\0';
2357 
2358 	if (tp->t_session == NULL)
2359 		msg = "not a controlling terminal\n";
2360 	else if (tp->t_pgrp == NULL)
2361 		msg = "no foreground process group\n";
2362 	else if ((p = LIST_FIRST(&tp->t_pgrp->pg_members)) == NULL)
2363 		msg = "empty foreground process group\n";
2364 	else {
2365 		/* Pick interesting process. */
2366 		for (; p != NULL; p = LIST_NEXT(p, p_pglist)) {
2367 			struct proc *oldpick;
2368 
2369 			if (pick == NULL) {
2370 				pick = p;
2371 				continue;
2372 			}
2373 			if (pick->p_lock < p->p_lock) {
2374 				mutex_enter(pick->p_lock);
2375 				mutex_enter(p->p_lock);
2376 			} else if (pick->p_lock > p->p_lock) {
2377 				mutex_enter(p->p_lock);
2378 				mutex_enter(pick->p_lock);
2379 			} else
2380 				mutex_enter(p->p_lock);
2381 			oldpick = pick;
2382 			if (proc_compare(pick, p))
2383 				pick = p;
2384 			mutex_exit(p->p_lock);
2385 			if (p->p_lock != oldpick->p_lock)
2386 				mutex_exit(oldpick->p_lock);
2387 		}
2388 		if (fromsig &&
2389 		    (SIGACTION_PS(pick->p_sigacts, SIGINFO).sa_flags &
2390 		    SA_NOKERNINFO))
2391 			return;
2392 		msg = NULL;
2393 	}
2394 
2395 	/* Print load average. */
2396 	tmp = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
2397 	snprintf(lmsg, sizeof(lmsg), "load: %d.%02d ", tmp / 100, tmp % 100);
2398 	strlcat(buf, lmsg, bufsz);
2399 
2400 	if (pick == NULL) {
2401 		strlcat(buf, msg, bufsz);
2402 		return;
2403 	}
2404 
2405 	snprintf(lmsg, sizeof(lmsg), " cmd: %s %d [", pick->p_comm,
2406 	    pick->p_pid);
2407 	strlcat(buf, lmsg, bufsz);
2408 
2409 	mutex_enter(pick->p_lock);
2410 	LIST_FOREACH(l, &pick->p_lwps, l_sibling) {
2411 		lwp_lock(l);
2412 		snprintf(lmsg, sizeof(lmsg), "%s%s",
2413 		    l->l_stat == LSONPROC ? "running" :
2414 		    l->l_stat == LSRUN ? "runnable" :
2415 		    l->l_wchan ? l->l_wmesg : "iowait",
2416 		    (LIST_NEXT(l, l_sibling) != NULL) ? " " : "] ");
2417 		lwp_unlock(l);
2418 		strlcat(buf, lmsg, bufsz);
2419 		pctcpu += l->l_pctcpu;
2420 	}
2421 	pctcpu += pick->p_pctcpu;
2422 	calcru(pick, &utime, &stime, NULL, NULL);
2423 	mutex_exit(pick->p_lock);
2424 
2425 	/* Round up and print user+system time, %CPU and RSS. */
2426 	utime.tv_usec += 5000;
2427 	if (utime.tv_usec >= 1000000) {
2428 		utime.tv_sec += 1;
2429 		utime.tv_usec -= 1000000;
2430 	}
2431 	stime.tv_usec += 5000;
2432 	if (stime.tv_usec >= 1000000) {
2433 		stime.tv_sec += 1;
2434 		stime.tv_usec -= 1000000;
2435 	}
2436 #define	pgtok(a)	(((u_long) ((a) * PAGE_SIZE) / 1024))
2437 	tmp = (pctcpu * 10000 + FSCALE / 2) >> FSHIFT;
2438 	if (pick->p_stat == SIDL || P_ZOMBIE(pick))
2439 		rss = 0;
2440 	else
2441 		rss = pgtok(vm_resident_count(pick->p_vmspace));
2442 
2443 	snprintf(lmsg, sizeof(lmsg), "%ld.%02ldu %ld.%02lds %d%% %ldk",
2444 	    (long)utime.tv_sec, (long)utime.tv_usec / 10000,
2445 	    (long)stime.tv_sec, (long)stime.tv_usec / 10000,
2446 	    tmp / 100, rss);
2447 	strlcat(buf, lmsg, bufsz);
2448 }
2449 
2450 /*
2451  * Print report on state of foreground process group.
2452  * Call with tty_lock held.
2453  */
2454 void
2455 ttyputinfo(struct tty *tp, char *buf)
2456 {
2457 
2458 	KASSERT(mutex_owned(&tty_lock));
2459 
2460 	if (ttycheckoutq_wlock(tp, 0) == 0)
2461 		return;
2462 	ttyprintf_nolock(tp, "%s\n", buf);
2463 	tp->t_rocount = 0;	/* so pending input will be retyped if BS */
2464 }
2465 
2466 /*
2467  * Returns 1 if p2 is "better" than p1
2468  *
2469  * The algorithm for picking the "interesting" process is thus:
2470  *
2471  *	1) Only foreground processes are eligible - implied.
2472  *	2) Runnable processes are favored over anything else.  The runner
2473  *	   with the highest CPU utilization is picked (l_pctcpu).  Ties are
2474  *	   broken by picking the highest pid.
2475  *	3) The sleeper with the shortest sleep time is next.  With ties,
2476  *	   we pick out just "short-term" sleepers (P_SINTR == 0).
2477  *	4) Further ties are broken by picking the highest pid.
2478  */
2479 #define	ISRUN(p)	((p)->p_nrlwps > 0)
2480 #define	TESTAB(a, b)	((a)<<1 | (b))
2481 #define	ONLYA	2
2482 #define	ONLYB	1
2483 #define	BOTH	3
2484 
2485 static int
2486 proc_compare(struct proc *p1, struct proc *p2)
2487 {
2488 	lwp_t *l1, *l2;
2489 
2490 	KASSERT(mutex_owned(p1->p_lock));
2491 	KASSERT(mutex_owned(p2->p_lock));
2492 
2493 	if ((l1 = LIST_FIRST(&p1->p_lwps)) == NULL)
2494 		return (1);
2495 	if ((l2 = LIST_FIRST(&p2->p_lwps)) == NULL)
2496 		return (0);
2497 	/*
2498 	 * see if at least one of them is runnable
2499 	 */
2500 	switch (TESTAB(ISRUN(p1), ISRUN(p2))) {
2501 	case ONLYA:
2502 		return (0);
2503 	case ONLYB:
2504 		return (1);
2505 	case BOTH:
2506 		/*
2507 		 * tie - favor one with highest recent CPU utilization
2508 		 */
2509 		if (l2->l_pctcpu > l1->l_pctcpu)
2510 			return (1);
2511 		return (p2->p_pid > p1->p_pid);	/* tie - return highest pid */
2512 	}
2513 	/*
2514  	 * weed out zombies
2515 	 */
2516 	switch (TESTAB(P_ZOMBIE(p1), P_ZOMBIE(p2))) {
2517 	case ONLYA:
2518 		return (1);
2519 	case ONLYB:
2520 		return (0);
2521 	case BOTH:
2522 		return (p2->p_pid > p1->p_pid);	/* tie - return highest pid */
2523 	}
2524 	/*
2525 	 * pick the one with the smallest sleep time
2526 	 */
2527 	if (l2->l_slptime > l2->l_slptime)
2528 		return (0);
2529 	if (l2->l_slptime > l2->l_slptime)
2530 		return (1);
2531 	/*
2532 	 * favor one sleeping in a non-interruptible sleep
2533 	 */
2534 	if (l2->l_flag & LW_SINTR && (l2->l_flag & LW_SINTR) == 0)
2535 		return (1);
2536 	if (l2->l_flag & LW_SINTR && (l2->l_flag & LW_SINTR) == 0)
2537 		return (0);
2538 	return (p2->p_pid > p1->p_pid);		/* tie - return highest pid */
2539 }
2540 
2541 /*
2542  * Output char to tty; console putchar style.
2543  * Can be called with tty lock held through kprintf() machinery..
2544  */
2545 int
2546 tputchar(int c, int flags, struct tty *tp)
2547 {
2548 	int r = 0;
2549 
2550 	if ((flags & NOLOCK) == 0)
2551 		mutex_spin_enter(&tty_lock);
2552 	if (!CONNECTED(tp)) {
2553 		r = -1;
2554 		goto out;
2555 	}
2556 	if (c == '\n')
2557 		(void)ttyoutput('\r', tp);
2558 	(void)ttyoutput(c, tp);
2559 	ttstart(tp);
2560 out:
2561 	if ((flags & NOLOCK) == 0)
2562 		mutex_spin_exit(&tty_lock);
2563 	return (r);
2564 }
2565 
2566 /*
2567  * Sleep on chan, returning ERESTART if tty changed while we napped and
2568  * returning any errors (e.g. EINTR/ETIMEDOUT) reported by tsleep.  If
2569  * the tty is revoked, restarting a pending call will redo validation done
2570  * at the start of the call.
2571  *
2572  * Must be called with the tty lock held.
2573  */
2574 int
2575 ttysleep(struct tty *tp, kcondvar_t *cv, bool catch, int timo)
2576 {
2577 	int	error;
2578 	short	gen;
2579 
2580 	KASSERT(mutex_owned(&tty_lock));
2581 
2582 	gen = tp->t_gen;
2583 	if (catch)
2584 		error = cv_timedwait_sig(cv, &tty_lock, timo);
2585 	else
2586 		error = cv_timedwait(cv, &tty_lock, timo);
2587 	if (error != 0)
2588 		return (error);
2589 	return (tp->t_gen == gen ? 0 : ERESTART);
2590 }
2591 
2592 /*
2593  * Attach a tty to the tty list.
2594  *
2595  * This should be called ONLY once per real tty (including pty's).
2596  * eg, on the sparc, the keyboard and mouse have struct tty's that are
2597  * distinctly NOT usable as tty's, and thus should not be attached to
2598  * the ttylist.  This is why this call is not done from ttymalloc().
2599  *
2600  * Device drivers should attach tty's at a similar time that they are
2601  * ttymalloc()'ed, or, for the case of statically allocated struct tty's
2602  * either in the attach or (first) open routine.
2603  */
2604 void
2605 tty_attach(struct tty *tp)
2606 {
2607 
2608 	mutex_spin_enter(&tty_lock);
2609 	TAILQ_INSERT_TAIL(&ttylist, tp, tty_link);
2610 	++tty_count;
2611 	mutex_spin_exit(&tty_lock);
2612 }
2613 
2614 /*
2615  * Remove a tty from the tty list.
2616  */
2617 void
2618 tty_detach(struct tty *tp)
2619 {
2620 
2621 	mutex_spin_enter(&tty_lock);
2622 	--tty_count;
2623 #ifdef DIAGNOSTIC
2624 	if (tty_count < 0)
2625 		panic("tty_detach: tty_count < 0");
2626 #endif
2627 	TAILQ_REMOVE(&ttylist, tp, tty_link);
2628 	mutex_spin_exit(&tty_lock);
2629 }
2630 
2631 /*
2632  * Allocate a tty structure and its associated buffers.
2633  */
2634 struct tty *
2635 ttymalloc(void)
2636 {
2637 	struct tty	*tp;
2638 	int i;
2639 
2640 	tp = kmem_zalloc(sizeof(*tp), KM_SLEEP);
2641 	callout_init(&tp->t_rstrt_ch, 0);
2642 	callout_setfunc(&tp->t_rstrt_ch, ttrstrt, tp);
2643 	/* XXX: default to 1024 chars for now */
2644 	clalloc(&tp->t_rawq, 1024, 1);
2645 	cv_init(&tp->t_rawcv, "ttyraw");
2646 	cv_init(&tp->t_rawcvf, "ttyrawf");
2647 	clalloc(&tp->t_canq, 1024, 1);
2648 	cv_init(&tp->t_cancv, "ttycan");
2649 	cv_init(&tp->t_cancvf, "ttycanf");
2650 	/* output queue doesn't need quoting */
2651 	clalloc(&tp->t_outq, 1024, 0);
2652 	cv_init(&tp->t_outcv, "ttyout");
2653 	cv_init(&tp->t_outcvf, "ttyoutf");
2654 	/* Set default line discipline. */
2655 	tp->t_linesw = ttyldisc_default();
2656 	selinit(&tp->t_rsel);
2657 	selinit(&tp->t_wsel);
2658 	for (i = 0; i < TTYSIG_COUNT; i++)
2659 		sigemptyset(&tp->t_sigs[i]);
2660 	return (tp);
2661 }
2662 
2663 /*
2664  * Free a tty structure and its buffers.
2665  *
2666  * Be sure to call tty_detach() for any tty that has been
2667  * tty_attach()ed.
2668  */
2669 void
2670 ttyfree(struct tty *tp)
2671 {
2672 	int i;
2673 
2674 	mutex_enter(proc_lock);
2675 	mutex_enter(&tty_lock);
2676 	for (i = 0; i < TTYSIG_COUNT; i++)
2677 		sigemptyset(&tp->t_sigs[i]);
2678 	if (tp->t_sigcount != 0)
2679 		TAILQ_REMOVE(&tty_sigqueue, tp, t_sigqueue);
2680 	mutex_exit(&tty_lock);
2681 	mutex_exit(proc_lock);
2682 
2683 	callout_halt(&tp->t_rstrt_ch, NULL);
2684 	callout_destroy(&tp->t_rstrt_ch);
2685 	ttyldisc_release(tp->t_linesw);
2686 	clfree(&tp->t_rawq);
2687 	clfree(&tp->t_canq);
2688 	clfree(&tp->t_outq);
2689 	cv_destroy(&tp->t_rawcv);
2690 	cv_destroy(&tp->t_rawcvf);
2691 	cv_destroy(&tp->t_cancv);
2692 	cv_destroy(&tp->t_cancvf);
2693 	cv_destroy(&tp->t_outcv);
2694 	cv_destroy(&tp->t_outcvf);
2695 	seldestroy(&tp->t_rsel);
2696 	seldestroy(&tp->t_wsel);
2697 	kmem_free(tp, sizeof(*tp));
2698 }
2699 
2700 /*
2701  * ttyprintf_nolock: send a message to a specific tty, without locking.
2702  *
2703  * => should be used only by tty driver or anything that knows the
2704  *    underlying tty will not be revoked(2)'d away.  [otherwise,
2705  *    use tprintf]
2706  */
2707 static void
2708 ttyprintf_nolock(struct tty *tp, const char *fmt, ...)
2709 {
2710 	va_list ap;
2711 
2712 	/* No mutex needed; going to process TTY. */
2713 	va_start(ap, fmt);
2714 	kprintf(fmt, TOTTY|NOLOCK, tp, NULL, ap);
2715 	va_end(ap);
2716 }
2717 
2718 /*
2719  * Initialize the tty subsystem.
2720  */
2721 void
2722 tty_init(void)
2723 {
2724 
2725 	mutex_init(&tty_lock, MUTEX_DEFAULT, IPL_VM);
2726 	rw_init(&ttcompat_lock);
2727 	tty_sigsih = softint_establish(SOFTINT_CLOCK, ttysigintr, NULL);
2728 	KASSERT(tty_sigsih != NULL);
2729 }
2730 
2731 /*
2732  * Send a signal from a tty to its process group or session leader.
2733  * Handoff to the target is deferred to a soft interrupt.
2734  */
2735 void
2736 ttysig(struct tty *tp, enum ttysigtype st, int sig)
2737 {
2738 	sigset_t *sp;
2739 
2740 	/* XXXSMP not yet KASSERT(mutex_owned(&tty_lock)); */
2741 
2742 	sp = &tp->t_sigs[st];
2743 	if (sigismember(sp, sig))
2744 		return;
2745 	sigaddset(sp, sig);
2746 	if (tp->t_sigcount++ == 0)
2747 		TAILQ_INSERT_TAIL(&tty_sigqueue, tp, t_sigqueue);
2748 	softint_schedule(tty_sigsih);
2749 }
2750 
2751 /*
2752  * Deliver deferred signals from ttys.  Note that the process groups
2753  * and sessions associated with the ttys may have changed from when
2754  * the signal was originally sent, but in practice it should not matter.
2755  * For signals produced as a result of a syscall, the soft interrupt
2756  * will fire before the syscall returns to the user.
2757  */
2758 static void
2759 ttysigintr(void *cookie)
2760 {
2761 	struct tty *tp;
2762 	enum ttysigtype st;
2763 	struct pgrp *pgrp;
2764 	struct session *sess;
2765 	int sig, lflag;
2766 	char infobuf[200];
2767 
2768 	mutex_enter(proc_lock);
2769 	mutex_spin_enter(&tty_lock);
2770 	while ((tp = TAILQ_FIRST(&tty_sigqueue)) != NULL) {
2771 		KASSERT(tp->t_sigcount > 0);
2772 		for (st = 0; st < TTYSIG_COUNT; st++) {
2773 			if ((sig = firstsig(&tp->t_sigs[st])) != 0)
2774 				break;
2775 		}
2776 		KASSERT(st < TTYSIG_COUNT);
2777 		sigdelset(&tp->t_sigs[st], sig);
2778 		if (--tp->t_sigcount == 0)
2779 			TAILQ_REMOVE(&tty_sigqueue, tp, t_sigqueue);
2780 		pgrp = tp->t_pgrp;
2781 		sess = tp->t_session;
2782 		lflag = tp->t_lflag;
2783 		if  (sig == SIGINFO) {
2784 			if (ISSET(tp->t_state, TS_SIGINFO)) {
2785 				/* Via ioctl: ignore tty option. */
2786 				tp->t_state &= ~TS_SIGINFO;
2787 				lflag |= ISIG;
2788 			}
2789 			if (!ISSET(lflag, NOKERNINFO)) {
2790 				mutex_spin_exit(&tty_lock);
2791 				ttygetinfo(tp, 1, infobuf, sizeof(infobuf));
2792 				mutex_spin_enter(&tty_lock);
2793 				ttyputinfo(tp, infobuf);
2794 			}
2795 			if (!ISSET(lflag, ISIG))
2796 				continue;
2797 		}
2798 		mutex_spin_exit(&tty_lock);
2799 		KASSERT(sig != 0);
2800 		switch (st) {
2801 		case TTYSIG_PG1:
2802 			if (pgrp != NULL)
2803 				pgsignal(pgrp, sig, 1);
2804 			break;
2805 		case TTYSIG_PG2:
2806 			if (pgrp != NULL)
2807 				pgsignal(pgrp, sig, sess != NULL);
2808 			break;
2809 		case TTYSIG_LEADER:
2810 			if (sess != NULL && sess->s_leader != NULL)
2811 				psignal(sess->s_leader, sig);
2812 			break;
2813 		default:
2814 			/* NOTREACHED */
2815 			break;
2816 		}
2817 		mutex_spin_enter(&tty_lock);
2818 	}
2819 	mutex_spin_exit(&tty_lock);
2820 	mutex_exit(proc_lock);
2821 }
2822