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