xref: /freebsd/sys/kern/tty.c (revision 262e143bd46171a6415a5b28af260a5efa2a3db8)
1 /*-
2  * Copyright (c) 1982, 1986, 1990, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Copyright (c) 2002 Networks Associates Technologies, Inc.
11  * All rights reserved.
12  *
13  * Portions of this software were developed for the FreeBSD Project by
14  * ThinkSec AS and NAI Labs, the Security Research Division of Network
15  * Associates, Inc.  under DARPA/SPAWAR contract N66001-01-C-8035
16  * ("CBOSS"), as part of the DARPA CHATS research program.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  * 1. Redistributions of source code must retain the above copyright
22  *    notice, this list of conditions and the following disclaimer.
23  * 2. Redistributions in binary form must reproduce the above copyright
24  *    notice, this list of conditions and the following disclaimer in the
25  *    documentation and/or other materials provided with the distribution.
26  * 4. Neither the name of the University nor the names of its contributors
27  *    may be used to endorse or promote products derived from this software
28  *    without specific prior written permission.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40  * SUCH DAMAGE.
41  *
42  *	@(#)tty.c	8.8 (Berkeley) 1/21/94
43  */
44 
45 /*-
46  * TODO:
47  *	o Fix races for sending the start char in ttyflush().
48  *	o Handle inter-byte timeout for "MIN > 0, TIME > 0" in ttyselect().
49  *	  With luck, there will be MIN chars before select() returns().
50  *	o Handle CLOCAL consistently for ptys.  Perhaps disallow setting it.
51  *	o Don't allow input in TS_ZOMBIE case.  It would be visible through
52  *	  FIONREAD.
53  *	o Do the new sio locking stuff here and use it to avoid special
54  *	  case for EXTPROC?
55  *	o Lock PENDIN too?
56  *	o Move EXTPROC and/or PENDIN to t_state?
57  *	o Wrap most of ttioctl in spltty/splx.
58  *	o Implement TIOCNOTTY or remove it from <sys/ioctl.h>.
59  *	o Send STOP if IXOFF is toggled off while TS_TBLOCK is set.
60  *	o Don't allow certain termios flags to affect disciplines other
61  *	  than TTYDISC.  Cancel their effects before switch disciplines
62  *	  and ignore them if they are set while we are in another
63  *	  discipline.
64  *	o Now that historical speed conversions are handled here, don't
65  *	  do them in drivers.
66  *	o Check for TS_CARR_ON being set while everything is closed and not
67  *	  waiting for carrier.  TS_CARR_ON isn't cleared if nothing is open,
68  *	  so it would live until the next open even if carrier drops.
69  *	o Restore TS_WOPEN since it is useful in pstat.  It must be cleared
70  *	  only when _all_ openers leave open().
71  */
72 
73 #include <sys/cdefs.h>
74 __FBSDID("$FreeBSD$");
75 
76 #include "opt_compat.h"
77 #include "opt_tty.h"
78 
79 #include <sys/param.h>
80 #include <sys/systm.h>
81 #include <sys/filio.h>
82 #include <sys/lock.h>
83 #include <sys/mutex.h>
84 #include <sys/namei.h>
85 #include <sys/sx.h>
86 #ifndef BURN_BRIDGES
87 #if defined(COMPAT_43)
88 #include <sys/ioctl_compat.h>
89 #endif
90 #endif
91 #include <sys/proc.h>
92 #define	TTYDEFCHARS
93 #include <sys/tty.h>
94 #undef	TTYDEFCHARS
95 #include <sys/fcntl.h>
96 #include <sys/conf.h>
97 #include <sys/poll.h>
98 #include <sys/kernel.h>
99 #include <sys/vnode.h>
100 #include <sys/serial.h>
101 #include <sys/signalvar.h>
102 #include <sys/resourcevar.h>
103 #include <sys/malloc.h>
104 #include <sys/filedesc.h>
105 #include <sys/sched.h>
106 #include <sys/sysctl.h>
107 #include <sys/timepps.h>
108 
109 #include <machine/stdarg.h>
110 
111 #include <vm/vm.h>
112 #include <vm/pmap.h>
113 #include <vm/vm_map.h>
114 
115 MALLOC_DEFINE(M_TTYS, "ttys", "tty data structures");
116 
117 long tk_cancc;
118 long tk_nin;
119 long tk_nout;
120 long tk_rawcc;
121 
122 static	d_open_t	ttysopen;
123 static	d_close_t	ttysclose;
124 static	d_read_t	ttysrdwr;
125 static	d_ioctl_t	ttysioctl;
126 static	d_purge_t	ttypurge;
127 
128 /* Default cdevsw for common tty devices */
129 static struct cdevsw tty_cdevsw = {
130 	.d_version =	D_VERSION,
131 	.d_open =	ttyopen,
132 	.d_close =	ttyclose,
133 	.d_ioctl =	ttyioctl,
134 	.d_purge =	ttypurge,
135 	.d_name =	"ttydrv",
136 	.d_flags =	D_TTY | D_NEEDGIANT,
137 };
138 
139 /* Cdevsw for slave tty devices */
140 static struct cdevsw ttys_cdevsw = {
141 	.d_version =	D_VERSION,
142 	.d_open =	ttysopen,
143 	.d_close =	ttysclose,
144 	.d_read =	ttysrdwr,
145 	.d_write =	ttysrdwr,
146 	.d_ioctl =	ttysioctl,
147 	.d_name =	"TTYS",
148 	.d_flags =	D_TTY | D_NEEDGIANT,
149 };
150 
151 static int	proc_compare(struct proc *p1, struct proc *p2);
152 static int	ttnread(struct tty *tp);
153 static void	ttyecho(int c, struct tty *tp);
154 static int	ttyoutput(int c, struct tty *tp);
155 static void	ttypend(struct tty *tp);
156 static void	ttyretype(struct tty *tp);
157 static void	ttyrub(int c, struct tty *tp);
158 static void	ttyrubo(struct tty *tp, int cnt);
159 static void	ttyunblock(struct tty *tp);
160 static int	ttywflush(struct tty *tp);
161 static int	filt_ttyread(struct knote *kn, long hint);
162 static void	filt_ttyrdetach(struct knote *kn);
163 static int	filt_ttywrite(struct knote *kn, long hint);
164 static void	filt_ttywdetach(struct knote *kn);
165 
166 /*
167  * Table with character classes and parity. The 8th bit indicates parity,
168  * the 7th bit indicates the character is an alphameric or underscore (for
169  * ALTWERASE), and the low 6 bits indicate delay type.  If the low 6 bits
170  * are 0 then the character needs no special processing on output; classes
171  * other than 0 might be translated or (not currently) require delays.
172  */
173 #define	E	0x00	/* Even parity. */
174 #define	O	0x80	/* Odd parity. */
175 #define	PARITY(c)	(char_type[c] & O)
176 
177 #define	ALPHA	0x40	/* Alpha or underscore. */
178 #define	ISALPHA(c)	(char_type[(c) & TTY_CHARMASK] & ALPHA)
179 
180 #define	CCLASSMASK	0x3f
181 #define	CCLASS(c)	(char_type[c] & CCLASSMASK)
182 
183 #define	BS	BACKSPACE
184 #define	CC	CONTROL
185 #define	CR	RETURN
186 #define	NA	ORDINARY | ALPHA
187 #define	NL	NEWLINE
188 #define	NO	ORDINARY
189 #define	TB	TAB
190 #define	VT	VTAB
191 
192 static u_char const char_type[] = {
193 	E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC,	/* nul - bel */
194 	O|BS, E|TB, E|NL, O|CC, E|VT, O|CR, O|CC, E|CC, /* bs - si */
195 	O|CC, E|CC, E|CC, O|CC, E|CC, O|CC, O|CC, E|CC, /* dle - etb */
196 	E|CC, O|CC, O|CC, E|CC, O|CC, E|CC, E|CC, O|CC, /* can - us */
197 	O|NO, E|NO, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* sp - ' */
198 	E|NO, O|NO, O|NO, E|NO, O|NO, E|NO, E|NO, O|NO, /* ( - / */
199 	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* 0 - 7 */
200 	O|NA, E|NA, E|NO, O|NO, E|NO, O|NO, O|NO, E|NO, /* 8 - ? */
201 	O|NO, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* @ - G */
202 	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* H - O */
203 	E|NA, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* P - W */
204 	O|NA, E|NA, E|NA, O|NO, E|NO, O|NO, O|NO, O|NA, /* X - _ */
205 	E|NO, O|NA, O|NA, E|NA, O|NA, E|NA, E|NA, O|NA, /* ` - g */
206 	O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* h - o */
207 	O|NA, E|NA, E|NA, O|NA, E|NA, O|NA, O|NA, E|NA, /* p - w */
208 	E|NA, O|NA, O|NA, E|NO, O|NO, E|NO, E|NO, O|CC, /* x - del */
209 	/*
210 	 * Meta chars; should be settable per character set;
211 	 * for now, treat them all as normal characters.
212 	 */
213 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
214 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
215 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
216 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
217 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
218 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
219 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
220 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
221 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
222 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
223 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
224 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
225 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
226 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
227 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
228 	NA,   NA,   NA,   NA,   NA,   NA,   NA,   NA,
229 };
230 #undef	BS
231 #undef	CC
232 #undef	CR
233 #undef	NA
234 #undef	NL
235 #undef	NO
236 #undef	TB
237 #undef	VT
238 
239 /* Macros to clear/set/test flags. */
240 #define	SET(t, f)	(t) |= (f)
241 #define	CLR(t, f)	(t) &= ~(f)
242 #define	ISSET(t, f)	((t) & (f))
243 
244 #undef MAX_INPUT		/* XXX wrong in <sys/syslimits.h> */
245 #define	MAX_INPUT	TTYHOG	/* XXX limit is usually larger for !ICANON */
246 
247 /*
248  * list of struct tty where pstat(8) can pick it up with sysctl
249  *
250  * The lock order is to grab the list mutex before the tty mutex.
251  * Together with additions going on the tail of the list, this allows
252  * the sysctl to avoid doing retries.
253  */
254 static	TAILQ_HEAD(, tty) tty_list = TAILQ_HEAD_INITIALIZER(tty_list);
255 static struct mtx tty_list_mutex;
256 
257 static struct unrhdr *tty_unit;
258 
259 static int  drainwait = 5*60;
260 SYSCTL_INT(_kern, OID_AUTO, drainwait, CTLFLAG_RW, &drainwait,
261 	0, "Output drain timeout in seconds");
262 
263 static struct tty *
264 tty_gettp(struct cdev *dev)
265 {
266 	struct tty *tp;
267 	struct cdevsw *csw;
268 
269 	csw = dev_refthread(dev);
270 	KASSERT(csw != NULL, ("No cdevsw in ttycode (%s)", devtoname(dev)));
271 	KASSERT(csw->d_flags & D_TTY,
272 	    ("non D_TTY (%s) in tty code", devtoname(dev)));
273 	dev_relthread(dev);
274 	tp = dev->si_tty;
275 	KASSERT(tp != NULL,
276 	    ("no tty pointer on (%s) in tty code", devtoname(dev)));
277 	return (tp);
278 }
279 
280 /*
281  * Initial open of tty, or (re)entry to standard tty line discipline.
282  */
283 int
284 tty_open(struct cdev *device, struct tty *tp)
285 {
286 	int s;
287 
288 	s = spltty();
289 	tp->t_dev = device;
290 	tp->t_hotchar = 0;
291 	if (!ISSET(tp->t_state, TS_ISOPEN)) {
292 		ttyref(tp);
293 		SET(tp->t_state, TS_ISOPEN);
294 		if (ISSET(tp->t_cflag, CLOCAL))
295 			SET(tp->t_state, TS_CONNECTED);
296 		bzero(&tp->t_winsize, sizeof(tp->t_winsize));
297 	}
298 	/* XXX don't hang forever on output */
299 	if (tp->t_timeout < 0)
300 		tp->t_timeout = drainwait*hz;
301 	ttsetwater(tp);
302 	splx(s);
303 	return (0);
304 }
305 
306 /*
307  * Handle close() on a tty line: flush and set to initial state,
308  * bumping generation number so that pending read/write calls
309  * can detect recycling of the tty.
310  * XXX our caller should have done `spltty(); l_close(); tty_close();'
311  * and l_close() should have flushed, but we repeat the spltty() and
312  * the flush in case there are buggy callers.
313  */
314 int
315 tty_close(struct tty *tp)
316 {
317 	int s;
318 
319 	funsetown(&tp->t_sigio);
320 	s = spltty();
321 	if (constty == tp)
322 		constty_clear();
323 
324 	ttyflush(tp, FREAD | FWRITE);
325 	clist_free_cblocks(&tp->t_canq);
326 	clist_free_cblocks(&tp->t_outq);
327 	clist_free_cblocks(&tp->t_rawq);
328 
329 	tp->t_gen++;
330 	tp->t_line = TTYDISC;
331 	tp->t_hotchar = 0;
332 	tp->t_pgrp = NULL;
333 	tp->t_session = NULL;
334 	tp->t_state = 0;
335 	knlist_clear(&tp->t_rsel.si_note, 0);
336 	knlist_clear(&tp->t_wsel.si_note, 0);
337 	ttyrel(tp);
338 	splx(s);
339 	return (0);
340 }
341 
342 #define	FLUSHQ(q) {							\
343 	if ((q)->c_cc)							\
344 		ndflush(q, (q)->c_cc);					\
345 }
346 
347 /* Is 'c' a line delimiter ("break" character)? */
348 #define	TTBREAKC(c, lflag)							\
349 	((c) == '\n' || (((c) == cc[VEOF] ||				\
350 	  (c) == cc[VEOL] || ((c) == cc[VEOL2] && lflag & IEXTEN)) &&	\
351 	 (c) != _POSIX_VDISABLE))
352 
353 /*
354  * Process input of a single character received on a tty.
355  */
356 int
357 ttyinput(int c, struct tty *tp)
358 {
359 	tcflag_t iflag, lflag;
360 	cc_t *cc;
361 	int i, err;
362 
363 	/*
364 	 * If input is pending take it first.
365 	 */
366 	lflag = tp->t_lflag;
367 	if (ISSET(lflag, PENDIN))
368 		ttypend(tp);
369 	/*
370 	 * Gather stats.
371 	 */
372 	if (ISSET(lflag, ICANON)) {
373 		++tk_cancc;
374 		++tp->t_cancc;
375 	} else {
376 		++tk_rawcc;
377 		++tp->t_rawcc;
378 	}
379 	++tk_nin;
380 
381 	/*
382 	 * Block further input iff:
383 	 * current input > threshold AND input is available to user program
384 	 * AND input flow control is enabled and not yet invoked.
385 	 * The 3 is slop for PARMRK.
386 	 */
387 	iflag = tp->t_iflag;
388 	if (tp->t_rawq.c_cc + tp->t_canq.c_cc > tp->t_ihiwat - 3 &&
389 	    (!ISSET(lflag, ICANON) || tp->t_canq.c_cc != 0) &&
390 	    (ISSET(tp->t_cflag, CRTS_IFLOW) || ISSET(iflag, IXOFF)) &&
391 	    !ISSET(tp->t_state, TS_TBLOCK))
392 		ttyblock(tp);
393 
394 	/* Handle exceptional conditions (break, parity, framing). */
395 	cc = tp->t_cc;
396 	err = (ISSET(c, TTY_ERRORMASK));
397 	if (err) {
398 		CLR(c, TTY_ERRORMASK);
399 		if (ISSET(err, TTY_BI)) {
400 			if (ISSET(iflag, IGNBRK))
401 				return (0);
402 			if (ISSET(iflag, BRKINT)) {
403 				ttyflush(tp, FREAD | FWRITE);
404 				if (tp->t_pgrp != NULL) {
405 					PGRP_LOCK(tp->t_pgrp);
406 					pgsignal(tp->t_pgrp, SIGINT, 1);
407 					PGRP_UNLOCK(tp->t_pgrp);
408 				}
409 				goto endcase;
410 			}
411 			if (ISSET(iflag, PARMRK))
412 				goto parmrk;
413 		} else if ((ISSET(err, TTY_PE) && ISSET(iflag, INPCK))
414 			|| ISSET(err, TTY_FE)) {
415 			if (ISSET(iflag, IGNPAR))
416 				return (0);
417 			else if (ISSET(iflag, PARMRK)) {
418 parmrk:
419 				if (tp->t_rawq.c_cc + tp->t_canq.c_cc >
420 				    MAX_INPUT - 3)
421 					goto input_overflow;
422 				(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
423 				(void)putc(0 | TTY_QUOTE, &tp->t_rawq);
424 				(void)putc(c | TTY_QUOTE, &tp->t_rawq);
425 				goto endcase;
426 			} else
427 				c = 0;
428 		}
429 	}
430 
431 	if (!ISSET(tp->t_state, TS_TYPEN) && ISSET(iflag, ISTRIP))
432 		CLR(c, 0x80);
433 	if (!ISSET(lflag, EXTPROC)) {
434 		/*
435 		 * Check for literal nexting very first
436 		 */
437 		if (ISSET(tp->t_state, TS_LNCH)) {
438 			SET(c, TTY_QUOTE);
439 			CLR(tp->t_state, TS_LNCH);
440 		}
441 		/*
442 		 * Scan for special characters.  This code
443 		 * is really just a big case statement with
444 		 * non-constant cases.  The bottom of the
445 		 * case statement is labeled ``endcase'', so goto
446 		 * it after a case match, or similar.
447 		 */
448 
449 		/*
450 		 * Control chars which aren't controlled
451 		 * by ICANON, ISIG, or IXON.
452 		 */
453 		if (ISSET(lflag, IEXTEN)) {
454 			if (CCEQ(cc[VLNEXT], c)) {
455 				if (ISSET(lflag, ECHO)) {
456 					if (ISSET(lflag, ECHOE)) {
457 						(void)ttyoutput('^', tp);
458 						(void)ttyoutput('\b', tp);
459 					} else
460 						ttyecho(c, tp);
461 				}
462 				SET(tp->t_state, TS_LNCH);
463 				goto endcase;
464 			}
465 			if (CCEQ(cc[VDISCARD], c)) {
466 				if (ISSET(lflag, FLUSHO))
467 					CLR(tp->t_lflag, FLUSHO);
468 				else {
469 					ttyflush(tp, FWRITE);
470 					ttyecho(c, tp);
471 					if (tp->t_rawq.c_cc + tp->t_canq.c_cc)
472 						ttyretype(tp);
473 					SET(tp->t_lflag, FLUSHO);
474 				}
475 				goto startoutput;
476 			}
477 		}
478 		/*
479 		 * Signals.
480 		 */
481 		if (ISSET(lflag, ISIG)) {
482 			if (CCEQ(cc[VINTR], c) || CCEQ(cc[VQUIT], c)) {
483 				if (!ISSET(lflag, NOFLSH))
484 					ttyflush(tp, FREAD | FWRITE);
485 				ttyecho(c, tp);
486 				if (tp->t_pgrp != NULL) {
487 					PGRP_LOCK(tp->t_pgrp);
488 					pgsignal(tp->t_pgrp,
489 					    CCEQ(cc[VINTR], c) ? SIGINT : SIGQUIT, 1);
490 					PGRP_UNLOCK(tp->t_pgrp);
491 				}
492 				goto endcase;
493 			}
494 			if (CCEQ(cc[VSUSP], c)) {
495 				if (!ISSET(lflag, NOFLSH))
496 					ttyflush(tp, FREAD);
497 				ttyecho(c, tp);
498 				if (tp->t_pgrp != NULL) {
499 					PGRP_LOCK(tp->t_pgrp);
500 					pgsignal(tp->t_pgrp, SIGTSTP, 1);
501 					PGRP_UNLOCK(tp->t_pgrp);
502 				}
503 				goto endcase;
504 			}
505 		}
506 		/*
507 		 * Handle start/stop characters.
508 		 */
509 		if (ISSET(iflag, IXON)) {
510 			if (CCEQ(cc[VSTOP], c)) {
511 				if (!ISSET(tp->t_state, TS_TTSTOP)) {
512 					SET(tp->t_state, TS_TTSTOP);
513 					tt_stop(tp, 0);
514 					return (0);
515 				}
516 				if (!CCEQ(cc[VSTART], c))
517 					return (0);
518 				/*
519 				 * if VSTART == VSTOP then toggle
520 				 */
521 				goto endcase;
522 			}
523 			if (CCEQ(cc[VSTART], c))
524 				goto restartoutput;
525 		}
526 		/*
527 		 * IGNCR, ICRNL, & INLCR
528 		 */
529 		if (c == '\r') {
530 			if (ISSET(iflag, IGNCR))
531 				return (0);
532 			else if (ISSET(iflag, ICRNL))
533 				c = '\n';
534 		} else if (c == '\n' && ISSET(iflag, INLCR))
535 			c = '\r';
536 	}
537 	if (!ISSET(tp->t_lflag, EXTPROC) && ISSET(lflag, ICANON)) {
538 		/*
539 		 * From here on down canonical mode character
540 		 * processing takes place.
541 		 */
542 		/*
543 		 * erase or erase2 (^H / ^?)
544 		 */
545 		if (CCEQ(cc[VERASE], c) || CCEQ(cc[VERASE2], c) ) {
546 			if (tp->t_rawq.c_cc)
547 				ttyrub(unputc(&tp->t_rawq), tp);
548 			goto endcase;
549 		}
550 		/*
551 		 * kill (^U)
552 		 */
553 		if (CCEQ(cc[VKILL], c)) {
554 			if (ISSET(lflag, ECHOKE) &&
555 			    tp->t_rawq.c_cc == tp->t_rocount &&
556 			    !ISSET(lflag, ECHOPRT))
557 				while (tp->t_rawq.c_cc)
558 					ttyrub(unputc(&tp->t_rawq), tp);
559 			else {
560 				ttyecho(c, tp);
561 				if (ISSET(lflag, ECHOK) ||
562 				    ISSET(lflag, ECHOKE))
563 					ttyecho('\n', tp);
564 				FLUSHQ(&tp->t_rawq);
565 				tp->t_rocount = 0;
566 			}
567 			CLR(tp->t_state, TS_LOCAL);
568 			goto endcase;
569 		}
570 		/*
571 		 * word erase (^W)
572 		 */
573 		if (CCEQ(cc[VWERASE], c) && ISSET(lflag, IEXTEN)) {
574 			int ctype;
575 
576 			/*
577 			 * erase whitespace
578 			 */
579 			while ((c = unputc(&tp->t_rawq)) == ' ' || c == '\t')
580 				ttyrub(c, tp);
581 			if (c == -1)
582 				goto endcase;
583 			/*
584 			 * erase last char of word and remember the
585 			 * next chars type (for ALTWERASE)
586 			 */
587 			ttyrub(c, tp);
588 			c = unputc(&tp->t_rawq);
589 			if (c == -1)
590 				goto endcase;
591 			if (c == ' ' || c == '\t') {
592 				(void)putc(c, &tp->t_rawq);
593 				goto endcase;
594 			}
595 			ctype = ISALPHA(c);
596 			/*
597 			 * erase rest of word
598 			 */
599 			do {
600 				ttyrub(c, tp);
601 				c = unputc(&tp->t_rawq);
602 				if (c == -1)
603 					goto endcase;
604 			} while (c != ' ' && c != '\t' &&
605 			    (!ISSET(lflag, ALTWERASE) || ISALPHA(c) == ctype));
606 			(void)putc(c, &tp->t_rawq);
607 			goto endcase;
608 		}
609 		/*
610 		 * reprint line (^R)
611 		 */
612 		if (CCEQ(cc[VREPRINT], c) && ISSET(lflag, IEXTEN)) {
613 			ttyretype(tp);
614 			goto endcase;
615 		}
616 		/*
617 		 * ^T - kernel info and generate SIGINFO
618 		 */
619 		if (CCEQ(cc[VSTATUS], c) && ISSET(lflag, IEXTEN)) {
620 			if (ISSET(lflag, ISIG) && tp->t_pgrp != NULL) {
621 				PGRP_LOCK(tp->t_pgrp);
622 				pgsignal(tp->t_pgrp, SIGINFO, 1);
623 				PGRP_UNLOCK(tp->t_pgrp);
624 			}
625 			if (!ISSET(lflag, NOKERNINFO))
626 				ttyinfo(tp);
627 			goto endcase;
628 		}
629 	}
630 	/*
631 	 * Check for input buffer overflow
632 	 */
633 	if (tp->t_rawq.c_cc + tp->t_canq.c_cc >= MAX_INPUT) {
634 input_overflow:
635 		if (ISSET(iflag, IMAXBEL)) {
636 			if (tp->t_outq.c_cc < tp->t_ohiwat)
637 				(void)ttyoutput(CTRL('g'), tp);
638 		}
639 		goto endcase;
640 	}
641 
642 	if (   c == 0377 && ISSET(iflag, PARMRK) && !ISSET(iflag, ISTRIP)
643 	     && ISSET(iflag, IGNBRK|IGNPAR) != (IGNBRK|IGNPAR))
644 		(void)putc(0377 | TTY_QUOTE, &tp->t_rawq);
645 
646 	/*
647 	 * Put data char in q for user and
648 	 * wakeup on seeing a line delimiter.
649 	 */
650 	if (putc(c, &tp->t_rawq) >= 0) {
651 		if (!ISSET(lflag, ICANON)) {
652 			ttwakeup(tp);
653 			ttyecho(c, tp);
654 			goto endcase;
655 		}
656 		if (TTBREAKC(c, lflag)) {
657 			tp->t_rocount = 0;
658 			catq(&tp->t_rawq, &tp->t_canq);
659 			ttwakeup(tp);
660 		} else if (tp->t_rocount++ == 0)
661 			tp->t_rocol = tp->t_column;
662 		if (ISSET(tp->t_state, TS_ERASE)) {
663 			/*
664 			 * end of prterase \.../
665 			 */
666 			CLR(tp->t_state, TS_ERASE);
667 			(void)ttyoutput('/', tp);
668 		}
669 		i = tp->t_column;
670 		ttyecho(c, tp);
671 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ECHO)) {
672 			/*
673 			 * Place the cursor over the '^' of the ^D.
674 			 */
675 			i = imin(2, tp->t_column - i);
676 			while (i > 0) {
677 				(void)ttyoutput('\b', tp);
678 				i--;
679 			}
680 		}
681 	}
682 endcase:
683 	/*
684 	 * IXANY means allow any character to restart output.
685 	 */
686 	if (ISSET(tp->t_state, TS_TTSTOP) &&
687 	    !ISSET(iflag, IXANY) && cc[VSTART] != cc[VSTOP])
688 		return (0);
689 restartoutput:
690 	CLR(tp->t_lflag, FLUSHO);
691 	CLR(tp->t_state, TS_TTSTOP);
692 startoutput:
693 	return (ttstart(tp));
694 }
695 
696 /*
697  * Output a single character on a tty, doing output processing
698  * as needed (expanding tabs, newline processing, etc.).
699  * Returns < 0 if succeeds, otherwise returns char to resend.
700  * Must be recursive.
701  */
702 static int
703 ttyoutput(int c, struct tty *tp)
704 {
705 	tcflag_t oflag;
706 	int col, s;
707 
708 	oflag = tp->t_oflag;
709 	if (!ISSET(oflag, OPOST)) {
710 		if (ISSET(tp->t_lflag, FLUSHO))
711 			return (-1);
712 		if (putc(c, &tp->t_outq))
713 			return (c);
714 		tk_nout++;
715 		tp->t_outcc++;
716 		return (-1);
717 	}
718 	/*
719 	 * Do tab expansion if OXTABS is set.  Special case if we external
720 	 * processing, we don't do the tab expansion because we'll probably
721 	 * get it wrong.  If tab expansion needs to be done, let it happen
722 	 * externally.
723 	 */
724 	CLR(c, ~TTY_CHARMASK);
725 	if (c == '\t' &&
726 	    ISSET(oflag, OXTABS) && !ISSET(tp->t_lflag, EXTPROC)) {
727 		c = 8 - (tp->t_column & 7);
728 		if (!ISSET(tp->t_lflag, FLUSHO)) {
729 			s = spltty();		/* Don't interrupt tabs. */
730 			c -= b_to_q("        ", c, &tp->t_outq);
731 			tk_nout += c;
732 			tp->t_outcc += c;
733 			splx(s);
734 		}
735 		tp->t_column += c;
736 		return (c ? -1 : '\t');
737 	}
738 	if (c == CEOT && ISSET(oflag, ONOEOT))
739 		return (-1);
740 
741 	/*
742 	 * Newline translation: if ONLCR is set,
743 	 * translate newline into "\r\n".
744 	 */
745 	if (c == '\n' && ISSET(tp->t_oflag, ONLCR)) {
746 		tk_nout++;
747 		tp->t_outcc++;
748 		if (!ISSET(tp->t_lflag, FLUSHO) && putc('\r', &tp->t_outq))
749 			return (c);
750 	}
751 	/* If OCRNL is set, translate "\r" into "\n". */
752 	else if (c == '\r' && ISSET(tp->t_oflag, OCRNL))
753 		c = '\n';
754 	/* If ONOCR is set, don't transmit CRs when on column 0. */
755 	else if (c == '\r' && ISSET(tp->t_oflag, ONOCR) && tp->t_column == 0)
756 		return (-1);
757 
758 	tk_nout++;
759 	tp->t_outcc++;
760 	if (!ISSET(tp->t_lflag, FLUSHO) && putc(c, &tp->t_outq))
761 		return (c);
762 
763 	col = tp->t_column;
764 	switch (CCLASS(c)) {
765 	case BACKSPACE:
766 		if (col > 0)
767 			--col;
768 		break;
769 	case CONTROL:
770 		break;
771 	case NEWLINE:
772 		if (ISSET(tp->t_oflag, ONLCR | ONLRET))
773 			col = 0;
774 		break;
775 	case RETURN:
776 		col = 0;
777 		break;
778 	case ORDINARY:
779 		++col;
780 		break;
781 	case TAB:
782 		col = (col + 8) & ~7;
783 		break;
784 	}
785 	tp->t_column = col;
786 	return (-1);
787 }
788 
789 /*
790  * Ioctls for all tty devices.  Called after line-discipline specific ioctl
791  * has been called to do discipline-specific functions and/or reject any
792  * of these ioctl commands.
793  */
794 /* ARGSUSED */
795 int
796 ttioctl(struct tty *tp, u_long cmd, void *data, int flag)
797 {
798 	struct proc *p;
799 	struct thread *td;
800 	struct pgrp *pgrp;
801 	int s, error, bits, sig, sig2;
802 
803 	td = curthread;			/* XXX */
804 	p = td->td_proc;
805 
806 	/* If the ioctl involves modification, hang if in the background. */
807 	switch (cmd) {
808 	case  TIOCCBRK:
809 	case  TIOCCONS:
810 	case  TIOCDRAIN:
811 	case  TIOCEXCL:
812 	case  TIOCFLUSH:
813 #ifdef TIOCHPCL
814 	case  TIOCHPCL:
815 #endif
816 	case  TIOCNXCL:
817 	case  TIOCSBRK:
818 	case  TIOCSCTTY:
819 	case  TIOCSDRAINWAIT:
820 	case  TIOCSETA:
821 	case  TIOCSETAF:
822 	case  TIOCSETAW:
823 	case  TIOCSETD:
824 	case  TIOCSPGRP:
825 	case  TIOCSTART:
826 	case  TIOCSTAT:
827 	case  TIOCSTI:
828 	case  TIOCSTOP:
829 	case  TIOCSWINSZ:
830 #ifndef BURN_BRIDGES
831 #if defined(COMPAT_43)
832 	case  TIOCLBIC:
833 	case  TIOCLBIS:
834 	case  TIOCLSET:
835 	case  TIOCSETC:
836 	case OTIOCSETD:
837 	case  TIOCSETN:
838 	case  TIOCSETP:
839 	case  TIOCSLTC:
840 #endif
841 #endif
842 		sx_slock(&proctree_lock);
843 		PROC_LOCK(p);
844 		while (isbackground(p, tp) && !(p->p_flag & P_PPWAIT) &&
845 		    !SIGISMEMBER(p->p_sigacts->ps_sigignore, SIGTTOU) &&
846 		    !SIGISMEMBER(td->td_sigmask, SIGTTOU)) {
847 			pgrp = p->p_pgrp;
848 			PROC_UNLOCK(p);
849 			if (pgrp->pg_jobc == 0) {
850 				sx_sunlock(&proctree_lock);
851 				return (EIO);
852 			}
853 			PGRP_LOCK(pgrp);
854 			sx_sunlock(&proctree_lock);
855 			pgsignal(pgrp, SIGTTOU, 1);
856 			PGRP_UNLOCK(pgrp);
857 			error = ttysleep(tp, &lbolt, TTOPRI | PCATCH, "ttybg1",
858 					 0);
859 			if (error)
860 				return (error);
861 			sx_slock(&proctree_lock);
862 			PROC_LOCK(p);
863 		}
864 		PROC_UNLOCK(p);
865 		sx_sunlock(&proctree_lock);
866 		break;
867 	}
868 
869 
870 	if (tp->t_modem != NULL) {
871 		switch (cmd) {
872 		case TIOCSDTR:
873 			tt_modem(tp, SER_DTR, 0);
874 			return (0);
875 		case TIOCCDTR:
876 			tt_modem(tp, 0, SER_DTR);
877 			return (0);
878 		case TIOCMSET:
879 			bits = *(int *)data;
880 			sig = (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1;
881 			sig2 = ((~bits) & (TIOCM_DTR | TIOCM_RTS)) >> 1;
882 			tt_modem(tp, sig, sig2);
883 			return (0);
884 		case TIOCMBIS:
885 			bits = *(int *)data;
886 			sig = (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1;
887 			tt_modem(tp, sig, 0);
888 			return (0);
889 		case TIOCMBIC:
890 			bits = *(int *)data;
891 			sig = (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1;
892 			tt_modem(tp, 0, sig);
893 			return (0);
894 		case TIOCMGET:
895 			sig = tt_modem(tp, 0, 0);
896 			/* See <sys/serial.h. for the "<< 1" stuff */
897 			bits = TIOCM_LE + (sig << 1);
898 			*(int *)data = bits;
899 			return (0);
900 		default:
901 			break;
902 		}
903 	}
904 
905 	if (tp->t_pps != NULL) {
906 		error = pps_ioctl(cmd, data, tp->t_pps);
907 		if (error != ENOIOCTL)
908 			return (error);
909 	}
910 
911 	switch (cmd) {			/* Process the ioctl. */
912 	case FIOASYNC:			/* set/clear async i/o */
913 		s = spltty();
914 		if (*(int *)data)
915 			SET(tp->t_state, TS_ASYNC);
916 		else
917 			CLR(tp->t_state, TS_ASYNC);
918 		splx(s);
919 		break;
920 	case FIONBIO:			/* set/clear non-blocking i/o */
921 		break;			/* XXX: delete. */
922 	case FIONREAD:			/* get # bytes to read */
923 		s = spltty();
924 		*(int *)data = ttnread(tp);
925 		splx(s);
926 		break;
927 
928 	case FIOSETOWN:
929 		/*
930 		 * Policy -- Don't allow FIOSETOWN on someone else's
931 		 *           controlling tty
932 		 */
933 		if (tp->t_session != NULL && !isctty(p, tp))
934 			return (ENOTTY);
935 
936 		error = fsetown(*(int *)data, &tp->t_sigio);
937 		if (error)
938 			return (error);
939 		break;
940 	case FIOGETOWN:
941 		if (tp->t_session != NULL && !isctty(p, tp))
942 			return (ENOTTY);
943 		*(int *)data = fgetown(&tp->t_sigio);
944 		break;
945 
946 	case TIOCEXCL:			/* set exclusive use of tty */
947 		s = spltty();
948 		SET(tp->t_state, TS_XCLUDE);
949 		splx(s);
950 		break;
951 	case TIOCFLUSH: {		/* flush buffers */
952 		int flags = *(int *)data;
953 
954 		if (flags == 0)
955 			flags = FREAD | FWRITE;
956 		else
957 			flags &= FREAD | FWRITE;
958 		ttyflush(tp, flags);
959 		break;
960 	}
961 	case TIOCCONS:			/* become virtual console */
962 		if (*(int *)data) {
963 			struct nameidata nid;
964 
965 			if (constty && constty != tp &&
966 			    ISSET(constty->t_state, TS_CONNECTED))
967 				return (EBUSY);
968 
969 			/* Ensure user can open the real console. */
970 			NDINIT(&nid, LOOKUP, LOCKLEAF | FOLLOW, UIO_SYSSPACE,
971 			    "/dev/console", td);
972 			if ((error = namei(&nid)) != 0)
973 				return (error);
974 			NDFREE(&nid, NDF_ONLY_PNBUF);
975 			error = VOP_ACCESS(nid.ni_vp, VREAD, td->td_ucred, td);
976 			vput(nid.ni_vp);
977 			if (error)
978 				return (error);
979 
980 			constty_set(tp);
981 		} else if (tp == constty)
982 			constty_clear();
983 		break;
984 	case TIOCDRAIN:			/* wait till output drained */
985 		error = ttywait(tp);
986 		if (error)
987 			return (error);
988 		break;
989 	case TIOCGETA: {		/* get termios struct */
990 		struct termios *t = (struct termios *)data;
991 
992 		bcopy(&tp->t_termios, t, sizeof(struct termios));
993 		break;
994 	}
995 	case TIOCGETD:			/* get line discipline */
996 		*(int *)data = tp->t_line;
997 		break;
998 	case TIOCGWINSZ:		/* get window size */
999 		*(struct winsize *)data = tp->t_winsize;
1000 		break;
1001 	case TIOCGPGRP:			/* get pgrp of tty */
1002 		if (!isctty(p, tp))
1003 			return (ENOTTY);
1004 		*(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : NO_PID;
1005 		break;
1006 #ifdef TIOCHPCL
1007 	case TIOCHPCL:			/* hang up on last close */
1008 		s = spltty();
1009 		SET(tp->t_cflag, HUPCL);
1010 		splx(s);
1011 		break;
1012 #endif
1013 	case TIOCMGDTRWAIT:
1014 		*(int *)data = tp->t_dtr_wait * 100 / hz;
1015 		break;
1016 	case TIOCMSDTRWAIT:
1017 		/* must be root since the wait applies to following logins */
1018 		error = suser(td);
1019 		if (error)
1020 			return (error);
1021 		tp->t_dtr_wait = *(int *)data * hz / 100;
1022 		break;
1023 	case TIOCNXCL:			/* reset exclusive use of tty */
1024 		s = spltty();
1025 		CLR(tp->t_state, TS_XCLUDE);
1026 		splx(s);
1027 		break;
1028 	case TIOCOUTQ:			/* output queue size */
1029 		*(int *)data = tp->t_outq.c_cc;
1030 		break;
1031 	case TIOCSETA:			/* set termios struct */
1032 	case TIOCSETAW:			/* drain output, set */
1033 	case TIOCSETAF: {		/* drn out, fls in, set */
1034 		struct termios *t = (struct termios *)data;
1035 
1036 		if (t->c_ispeed == 0)
1037 			t->c_ispeed = t->c_ospeed;
1038 		if (t->c_ispeed == 0)
1039 			t->c_ispeed = tp->t_ospeed;
1040 		if (t->c_ispeed == 0)
1041 			return (EINVAL);
1042 		s = spltty();
1043 		if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
1044 			error = ttywait(tp);
1045 			if (error) {
1046 				splx(s);
1047 				return (error);
1048 			}
1049 			if (cmd == TIOCSETAF)
1050 				ttyflush(tp, FREAD);
1051 		}
1052 		if (!ISSET(t->c_cflag, CIGNORE)) {
1053 			/*
1054 			 * Set device hardware.
1055 			 */
1056 			error = tt_param(tp, t);
1057 			if (error) {
1058 				splx(s);
1059 				return (error);
1060 			}
1061 			if (ISSET(t->c_cflag, CLOCAL) &&
1062 			    !ISSET(tp->t_cflag, CLOCAL)) {
1063 				/*
1064 				 * XXX disconnections would be too hard to
1065 				 * get rid of without this kludge.  The only
1066 				 * way to get rid of controlling terminals
1067 				 * is to exit from the session leader.
1068 				 */
1069 				CLR(tp->t_state, TS_ZOMBIE);
1070 
1071 				wakeup(TSA_CARR_ON(tp));
1072 				ttwakeup(tp);
1073 				ttwwakeup(tp);
1074 			}
1075 			if ((ISSET(tp->t_state, TS_CARR_ON) ||
1076 			     ISSET(t->c_cflag, CLOCAL)) &&
1077 			    !ISSET(tp->t_state, TS_ZOMBIE))
1078 				SET(tp->t_state, TS_CONNECTED);
1079 			else
1080 				CLR(tp->t_state, TS_CONNECTED);
1081 			tp->t_cflag = t->c_cflag;
1082 			tp->t_ispeed = t->c_ispeed;
1083 			if (t->c_ospeed != 0)
1084 				tp->t_ospeed = t->c_ospeed;
1085 			ttsetwater(tp);
1086 		}
1087 		if (ISSET(t->c_lflag, ICANON) != ISSET(tp->t_lflag, ICANON) &&
1088 		    cmd != TIOCSETAF) {
1089 			if (ISSET(t->c_lflag, ICANON))
1090 				SET(tp->t_lflag, PENDIN);
1091 			else {
1092 				/*
1093 				 * XXX we really shouldn't allow toggling
1094 				 * ICANON while we're in a non-termios line
1095 				 * discipline.  Now we have to worry about
1096 				 * panicing for a null queue.
1097 				 */
1098 				if (tp->t_canq.c_cbreserved > 0 &&
1099 				    tp->t_rawq.c_cbreserved > 0) {
1100 					catq(&tp->t_rawq, &tp->t_canq);
1101 					/*
1102 					 * XXX the queue limits may be
1103 					 * different, so the old queue
1104 					 * swapping method no longer works.
1105 					 */
1106 					catq(&tp->t_canq, &tp->t_rawq);
1107 				}
1108 				CLR(tp->t_lflag, PENDIN);
1109 			}
1110 			ttwakeup(tp);
1111 		}
1112 		tp->t_iflag = t->c_iflag;
1113 		tp->t_oflag = t->c_oflag;
1114 		/*
1115 		 * Make the EXTPROC bit read only.
1116 		 */
1117 		if (ISSET(tp->t_lflag, EXTPROC))
1118 			SET(t->c_lflag, EXTPROC);
1119 		else
1120 			CLR(t->c_lflag, EXTPROC);
1121 		tp->t_lflag = t->c_lflag | ISSET(tp->t_lflag, PENDIN);
1122 		if (t->c_cc[VMIN] != tp->t_cc[VMIN] ||
1123 		    t->c_cc[VTIME] != tp->t_cc[VTIME])
1124 			ttwakeup(tp);
1125 		bcopy(t->c_cc, tp->t_cc, sizeof(t->c_cc));
1126 		splx(s);
1127 		break;
1128 	}
1129 	case TIOCSETD: {		/* set line discipline */
1130 		int t = *(int *)data;
1131 
1132 		if ((u_int)t >= nlinesw)
1133 			return (ENXIO);
1134 		if (t == tp->t_line)
1135 			return (0);
1136 		s = spltty();
1137 		ttyld_close(tp, flag);
1138 		tp->t_line = t;
1139 		/* XXX: we should use the correct cdev here */
1140 		error = ttyld_open(tp, tp->t_dev);
1141 		if (error) {
1142 			/*
1143 			 * If we fail to switch line discipline we cannot
1144 			 * fall back to the previous, because we can not
1145 			 * trust that ldisc to open successfully either.
1146 			 * Fall back to the default ldisc which we know
1147 			 * will allways succeed.
1148 			 */
1149 			tp->t_line = TTYDISC;
1150 			(void)ttyld_open(tp, tp->t_dev);
1151 		}
1152 		splx(s);
1153 		return (error);
1154 		break;
1155 	}
1156 	case TIOCSTART:			/* start output, like ^Q */
1157 		s = spltty();
1158 		if (ISSET(tp->t_state, TS_TTSTOP) ||
1159 		    ISSET(tp->t_lflag, FLUSHO)) {
1160 			CLR(tp->t_lflag, FLUSHO);
1161 			CLR(tp->t_state, TS_TTSTOP);
1162 			ttstart(tp);
1163 		}
1164 		splx(s);
1165 		break;
1166 	case TIOCSTI:			/* simulate terminal input */
1167 		if ((flag & FREAD) == 0 && suser(td))
1168 			return (EPERM);
1169 		if (!isctty(p, tp) && suser(td))
1170 			return (EACCES);
1171 		s = spltty();
1172 		ttyld_rint(tp, *(u_char *)data);
1173 		splx(s);
1174 		break;
1175 	case TIOCSTOP:			/* stop output, like ^S */
1176 		s = spltty();
1177 		if (!ISSET(tp->t_state, TS_TTSTOP)) {
1178 			SET(tp->t_state, TS_TTSTOP);
1179 			tt_stop(tp, 0);
1180 		}
1181 		splx(s);
1182 		break;
1183 	case TIOCSCTTY:			/* become controlling tty */
1184 		/* Session ctty vnode pointer set in vnode layer. */
1185 		sx_slock(&proctree_lock);
1186 		if (!SESS_LEADER(p) ||
1187 		    ((p->p_session->s_ttyvp || tp->t_session) &&
1188 		     (tp->t_session != p->p_session))) {
1189 			sx_sunlock(&proctree_lock);
1190 			return (EPERM);
1191 		}
1192 		tp->t_session = p->p_session;
1193 		tp->t_pgrp = p->p_pgrp;
1194 		SESS_LOCK(p->p_session);
1195 		ttyref(tp);		/* ttyrel(): kern_proc.c:pgdelete() */
1196 		p->p_session->s_ttyp = tp;
1197 		SESS_UNLOCK(p->p_session);
1198 		PROC_LOCK(p);
1199 		p->p_flag |= P_CONTROLT;
1200 		PROC_UNLOCK(p);
1201 		sx_sunlock(&proctree_lock);
1202 		break;
1203 	case TIOCSPGRP: {		/* set pgrp of tty */
1204 		sx_slock(&proctree_lock);
1205 		pgrp = pgfind(*(int *)data);
1206 		if (!isctty(p, tp)) {
1207 			if (pgrp != NULL)
1208 				PGRP_UNLOCK(pgrp);
1209 			sx_sunlock(&proctree_lock);
1210 			return (ENOTTY);
1211 		}
1212 		if (pgrp == NULL) {
1213 			sx_sunlock(&proctree_lock);
1214 			return (EPERM);
1215 		}
1216 		PGRP_UNLOCK(pgrp);
1217 		if (pgrp->pg_session != p->p_session) {
1218 			sx_sunlock(&proctree_lock);
1219 			return (EPERM);
1220 		}
1221 		sx_sunlock(&proctree_lock);
1222 		tp->t_pgrp = pgrp;
1223 		break;
1224 	}
1225 	case TIOCSTAT:			/* simulate control-T */
1226 		s = spltty();
1227 		ttyinfo(tp);
1228 		splx(s);
1229 		break;
1230 	case TIOCSWINSZ:		/* set window size */
1231 		if (bcmp((caddr_t)&tp->t_winsize, data,
1232 		    sizeof (struct winsize))) {
1233 			tp->t_winsize = *(struct winsize *)data;
1234 			if (tp->t_pgrp != NULL) {
1235 				PGRP_LOCK(tp->t_pgrp);
1236 				pgsignal(tp->t_pgrp, SIGWINCH, 1);
1237 				PGRP_UNLOCK(tp->t_pgrp);
1238 			}
1239 		}
1240 		break;
1241 	case TIOCSDRAINWAIT:
1242 		error = suser(td);
1243 		if (error)
1244 			return (error);
1245 		tp->t_timeout = *(int *)data * hz;
1246 		wakeup(TSA_OCOMPLETE(tp));
1247 		wakeup(TSA_OLOWAT(tp));
1248 		break;
1249 	case TIOCGDRAINWAIT:
1250 		*(int *)data = tp->t_timeout / hz;
1251 		break;
1252 	case TIOCSBRK:
1253 		return (tt_break(tp, 1));
1254 	case TIOCCBRK:
1255 		return (tt_break(tp, 0));
1256 	default:
1257 #if defined(COMPAT_43)
1258 #ifndef BURN_BRIDGES
1259 		return (ttcompat(tp, cmd, data, flag));
1260 #else
1261 		return (ENOIOCTL);
1262 #endif
1263 #else
1264 		return (ENOIOCTL);
1265 #endif
1266 	}
1267 	return (0);
1268 }
1269 
1270 int
1271 ttypoll(struct cdev *dev, int events, struct thread *td)
1272 {
1273 	int s;
1274 	int revents = 0;
1275 	struct tty *tp;
1276 
1277 	tp = tty_gettp(dev);
1278 
1279 	if (tp == NULL)	/* XXX used to return ENXIO, but that means true! */
1280 		return ((events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM))
1281 			| POLLHUP);
1282 
1283 	s = spltty();
1284 	if (events & (POLLIN | POLLRDNORM)) {
1285 		if (ISSET(tp->t_state, TS_ZOMBIE))
1286 			revents |= (events & (POLLIN | POLLRDNORM)) |
1287 			    POLLHUP;
1288 		else if (ttnread(tp) > 0)
1289 			revents |= events & (POLLIN | POLLRDNORM);
1290 		else
1291 			selrecord(td, &tp->t_rsel);
1292 	}
1293 	if (events & POLLOUT) {
1294 		if (ISSET(tp->t_state, TS_ZOMBIE))
1295 			revents |= POLLHUP;
1296 		else if (tp->t_outq.c_cc <= tp->t_olowat &&
1297 		    ISSET(tp->t_state, TS_CONNECTED))
1298 			revents |= events & POLLOUT;
1299 		else
1300 			selrecord(td, &tp->t_wsel);
1301 	}
1302 	splx(s);
1303 	return (revents);
1304 }
1305 
1306 static struct filterops ttyread_filtops =
1307 	{ 1, NULL, filt_ttyrdetach, filt_ttyread };
1308 static struct filterops ttywrite_filtops =
1309 	{ 1, NULL, filt_ttywdetach, filt_ttywrite };
1310 
1311 int
1312 ttykqfilter(struct cdev *dev, struct knote *kn)
1313 {
1314 	struct tty *tp;
1315 	struct knlist *klist;
1316 	int s;
1317 
1318 	tp = tty_gettp(dev);
1319 
1320 	switch (kn->kn_filter) {
1321 	case EVFILT_READ:
1322 		klist = &tp->t_rsel.si_note;
1323 		kn->kn_fop = &ttyread_filtops;
1324 		break;
1325 	case EVFILT_WRITE:
1326 		klist = &tp->t_wsel.si_note;
1327 		kn->kn_fop = &ttywrite_filtops;
1328 		break;
1329 	default:
1330 		return (EINVAL);
1331 	}
1332 
1333 	kn->kn_hook = (caddr_t)dev;
1334 
1335 	s = spltty();
1336 	knlist_add(klist, kn, 0);
1337 	splx(s);
1338 
1339 	return (0);
1340 }
1341 
1342 static void
1343 filt_ttyrdetach(struct knote *kn)
1344 {
1345 	struct tty *tp = ((struct cdev *)kn->kn_hook)->si_tty;
1346 	int s = spltty();
1347 
1348 	knlist_remove(&tp->t_rsel.si_note, kn, 0);
1349 	splx(s);
1350 }
1351 
1352 static int
1353 filt_ttyread(struct knote *kn, long hint)
1354 {
1355 	struct tty *tp = ((struct cdev *)kn->kn_hook)->si_tty;
1356 
1357 	kn->kn_data = ttnread(tp);
1358 	if (ISSET(tp->t_state, TS_ZOMBIE)) {
1359 		kn->kn_flags |= EV_EOF;
1360 		return (1);
1361 	}
1362 	return (kn->kn_data > 0);
1363 }
1364 
1365 static void
1366 filt_ttywdetach(struct knote *kn)
1367 {
1368 	struct tty *tp = ((struct cdev *)kn->kn_hook)->si_tty;
1369 	int s = spltty();
1370 
1371 	knlist_remove(&tp->t_wsel.si_note, kn, 0);
1372 	splx(s);
1373 }
1374 
1375 static int
1376 filt_ttywrite(struct knote *kn, long hint)
1377 {
1378 	struct tty *tp = ((struct cdev *)kn->kn_hook)->si_tty;
1379 
1380 	kn->kn_data = tp->t_outq.c_cc;
1381 	if (ISSET(tp->t_state, TS_ZOMBIE))
1382 		return (1);
1383 	return (kn->kn_data <= tp->t_olowat &&
1384 	    ISSET(tp->t_state, TS_CONNECTED));
1385 }
1386 
1387 /*
1388  * Must be called at spltty().
1389  */
1390 static int
1391 ttnread(struct tty *tp)
1392 {
1393 	int nread;
1394 
1395 	if (ISSET(tp->t_lflag, PENDIN))
1396 		ttypend(tp);
1397 	nread = tp->t_canq.c_cc;
1398 	if (!ISSET(tp->t_lflag, ICANON)) {
1399 		nread += tp->t_rawq.c_cc;
1400 		if (nread < tp->t_cc[VMIN] && tp->t_cc[VTIME] == 0)
1401 			nread = 0;
1402 	}
1403 	return (nread);
1404 }
1405 
1406 /*
1407  * Wait for output to drain.
1408  */
1409 int
1410 ttywait(struct tty *tp)
1411 {
1412 	int error, s;
1413 
1414 	error = 0;
1415 	s = spltty();
1416 	while ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1417 	       ISSET(tp->t_state, TS_CONNECTED) && tp->t_oproc) {
1418 		tt_oproc(tp);
1419 		if ((tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)) &&
1420 		    ISSET(tp->t_state, TS_CONNECTED)) {
1421 			SET(tp->t_state, TS_SO_OCOMPLETE);
1422 			error = ttysleep(tp, TSA_OCOMPLETE(tp),
1423 					 TTOPRI | PCATCH, "ttywai",
1424 					 tp->t_timeout);
1425 			if (error) {
1426 				if (error == EWOULDBLOCK)
1427 					error = EIO;
1428 				break;
1429 			}
1430 		} else
1431 			break;
1432 	}
1433 	if (!error && (tp->t_outq.c_cc || ISSET(tp->t_state, TS_BUSY)))
1434 		error = EIO;
1435 	splx(s);
1436 	return (error);
1437 }
1438 
1439 /*
1440  * Flush if successfully wait.
1441  */
1442 static int
1443 ttywflush(struct tty *tp)
1444 {
1445 	int error;
1446 
1447 	if ((error = ttywait(tp)) == 0)
1448 		ttyflush(tp, FREAD);
1449 	return (error);
1450 }
1451 
1452 /*
1453  * Flush tty read and/or write queues, notifying anyone waiting.
1454  */
1455 void
1456 ttyflush(struct tty *tp, int rw)
1457 {
1458 	int s;
1459 
1460 	s = spltty();
1461 #if 0
1462 again:
1463 #endif
1464 	if (rw & FWRITE) {
1465 		FLUSHQ(&tp->t_outq);
1466 		CLR(tp->t_state, TS_TTSTOP);
1467 	}
1468 	tt_stop(tp, rw);
1469 	if (rw & FREAD) {
1470 		FLUSHQ(&tp->t_canq);
1471 		FLUSHQ(&tp->t_rawq);
1472 		CLR(tp->t_lflag, PENDIN);
1473 		tp->t_rocount = 0;
1474 		tp->t_rocol = 0;
1475 		CLR(tp->t_state, TS_LOCAL);
1476 		ttwakeup(tp);
1477 		if (ISSET(tp->t_state, TS_TBLOCK)) {
1478 			if (rw & FWRITE)
1479 				FLUSHQ(&tp->t_outq);
1480 			ttyunblock(tp);
1481 
1482 			/*
1483 			 * Don't let leave any state that might clobber the
1484 			 * next line discipline (although we should do more
1485 			 * to send the START char).  Not clearing the state
1486 			 * may have caused the "putc to a clist with no
1487 			 * reserved cblocks" panic/printf.
1488 			 */
1489 			CLR(tp->t_state, TS_TBLOCK);
1490 
1491 #if 0 /* forget it, sleeping isn't always safe and we don't know when it is */
1492 			if (ISSET(tp->t_iflag, IXOFF)) {
1493 				/*
1494 				 * XXX wait a bit in the hope that the stop
1495 				 * character (if any) will go out.  Waiting
1496 				 * isn't good since it allows races.  This
1497 				 * will be fixed when the stop character is
1498 				 * put in a special queue.  Don't bother with
1499 				 * the checks in ttywait() since the timeout
1500 				 * will save us.
1501 				 */
1502 				SET(tp->t_state, TS_SO_OCOMPLETE);
1503 				ttysleep(tp, TSA_OCOMPLETE(tp), TTOPRI,
1504 					 "ttyfls", hz / 10);
1505 				/*
1506 				 * Don't try sending the stop character again.
1507 				 */
1508 				CLR(tp->t_state, TS_TBLOCK);
1509 				goto again;
1510 			}
1511 #endif
1512 		}
1513 	}
1514 	if (rw & FWRITE) {
1515 		FLUSHQ(&tp->t_outq);
1516 		ttwwakeup(tp);
1517 	}
1518 	splx(s);
1519 }
1520 
1521 /*
1522  * Copy in the default termios characters.
1523  */
1524 void
1525 termioschars(struct termios *t)
1526 {
1527 
1528 	bcopy(ttydefchars, t->c_cc, sizeof t->c_cc);
1529 }
1530 
1531 /*
1532  * Old interface.
1533  */
1534 void
1535 ttychars(struct tty *tp)
1536 {
1537 
1538 	termioschars(&tp->t_termios);
1539 }
1540 
1541 /*
1542  * Handle input high water.  Send stop character for the IXOFF case.  Turn
1543  * on our input flow control bit and propagate the changes to the driver.
1544  * XXX the stop character should be put in a special high priority queue.
1545  */
1546 void
1547 ttyblock(struct tty *tp)
1548 {
1549 
1550 	SET(tp->t_state, TS_TBLOCK);
1551 	if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTOP] != _POSIX_VDISABLE &&
1552 	    putc(tp->t_cc[VSTOP], &tp->t_outq) != 0)
1553 		CLR(tp->t_state, TS_TBLOCK);	/* try again later */
1554 	ttstart(tp);
1555 }
1556 
1557 /*
1558  * Handle input low water.  Send start character for the IXOFF case.  Turn
1559  * off our input flow control bit and propagate the changes to the driver.
1560  * XXX the start character should be put in a special high priority queue.
1561  */
1562 static void
1563 ttyunblock(struct tty *tp)
1564 {
1565 
1566 	CLR(tp->t_state, TS_TBLOCK);
1567 	if (ISSET(tp->t_iflag, IXOFF) && tp->t_cc[VSTART] != _POSIX_VDISABLE &&
1568 	    putc(tp->t_cc[VSTART], &tp->t_outq) != 0)
1569 		SET(tp->t_state, TS_TBLOCK);	/* try again later */
1570 	ttstart(tp);
1571 }
1572 
1573 #ifdef notyet
1574 /* Not used by any current (i386) drivers. */
1575 /*
1576  * Restart after an inter-char delay.
1577  */
1578 void
1579 ttrstrt(void *tp_arg)
1580 {
1581 	struct tty *tp;
1582 	int s;
1583 
1584 	KASSERT(tp_arg != NULL, ("ttrstrt"));
1585 
1586 	tp = tp_arg;
1587 	s = spltty();
1588 
1589 	CLR(tp->t_state, TS_TIMEOUT);
1590 	ttstart(tp);
1591 
1592 	splx(s);
1593 }
1594 #endif
1595 
1596 int
1597 ttstart(struct tty *tp)
1598 {
1599 
1600 	tt_oproc(tp);
1601 	return (0);
1602 }
1603 
1604 /*
1605  * "close" a line discipline
1606  */
1607 int
1608 ttylclose(struct tty *tp, int flag)
1609 {
1610 
1611 	if (flag & FNONBLOCK || ttywflush(tp))
1612 		ttyflush(tp, FREAD | FWRITE);
1613 	return (0);
1614 }
1615 
1616 /*
1617  * Handle modem control transition on a tty.
1618  * Flag indicates new state of carrier.
1619  * Returns 0 if the line should be turned off, otherwise 1.
1620  */
1621 int
1622 ttymodem(struct tty *tp, int flag)
1623 {
1624 
1625 	if (ISSET(tp->t_state, TS_CARR_ON) && ISSET(tp->t_cflag, MDMBUF)) {
1626 		/*
1627 		 * MDMBUF: do flow control according to carrier flag
1628 		 * XXX TS_CAR_OFLOW doesn't do anything yet.  TS_TTSTOP
1629 		 * works if IXON and IXANY are clear.
1630 		 */
1631 		if (flag) {
1632 			CLR(tp->t_state, TS_CAR_OFLOW);
1633 			CLR(tp->t_state, TS_TTSTOP);
1634 			ttstart(tp);
1635 		} else if (!ISSET(tp->t_state, TS_CAR_OFLOW)) {
1636 			SET(tp->t_state, TS_CAR_OFLOW);
1637 			SET(tp->t_state, TS_TTSTOP);
1638 			tt_stop(tp, 0);
1639 		}
1640 	} else if (flag == 0) {
1641 		/*
1642 		 * Lost carrier.
1643 		 */
1644 		CLR(tp->t_state, TS_CARR_ON);
1645 		if (ISSET(tp->t_state, TS_ISOPEN) &&
1646 		    !ISSET(tp->t_cflag, CLOCAL)) {
1647 			SET(tp->t_state, TS_ZOMBIE);
1648 			CLR(tp->t_state, TS_CONNECTED);
1649 			if (tp->t_session) {
1650 				sx_slock(&proctree_lock);
1651 				if (tp->t_session->s_leader) {
1652 					struct proc *p;
1653 
1654 					p = tp->t_session->s_leader;
1655 					PROC_LOCK(p);
1656 					psignal(p, SIGHUP);
1657 					PROC_UNLOCK(p);
1658 				}
1659 				sx_sunlock(&proctree_lock);
1660 			}
1661 			ttyflush(tp, FREAD | FWRITE);
1662 			return (0);
1663 		}
1664 	} else {
1665 		/*
1666 		 * Carrier now on.
1667 		 */
1668 		SET(tp->t_state, TS_CARR_ON);
1669 		if (!ISSET(tp->t_state, TS_ZOMBIE))
1670 			SET(tp->t_state, TS_CONNECTED);
1671 		wakeup(TSA_CARR_ON(tp));
1672 		ttwakeup(tp);
1673 		ttwwakeup(tp);
1674 	}
1675 	return (1);
1676 }
1677 
1678 /*
1679  * Reinput pending characters after state switch
1680  * call at spltty().
1681  */
1682 static void
1683 ttypend(struct tty *tp)
1684 {
1685 	struct clist tq;
1686 	int c;
1687 
1688 	CLR(tp->t_lflag, PENDIN);
1689 	SET(tp->t_state, TS_TYPEN);
1690 	/*
1691 	 * XXX this assumes too much about clist internals.  It may even
1692 	 * fail if the cblock slush pool is empty.  We can't allocate more
1693 	 * cblocks here because we are called from an interrupt handler
1694 	 * and clist_alloc_cblocks() can wait.
1695 	 */
1696 	tq = tp->t_rawq;
1697 	bzero(&tp->t_rawq, sizeof tp->t_rawq);
1698 	tp->t_rawq.c_cbmax = tq.c_cbmax;
1699 	tp->t_rawq.c_cbreserved = tq.c_cbreserved;
1700 	while ((c = getc(&tq)) >= 0)
1701 		ttyinput(c, tp);
1702 	CLR(tp->t_state, TS_TYPEN);
1703 }
1704 
1705 /*
1706  * Process a read call on a tty device.
1707  */
1708 int
1709 ttread(struct tty *tp, struct uio *uio, int flag)
1710 {
1711 	struct clist *qp;
1712 	int c;
1713 	tcflag_t lflag;
1714 	cc_t *cc = tp->t_cc;
1715 	struct thread *td;
1716 	struct proc *p;
1717 	int s, first, error = 0;
1718 	int has_stime = 0, last_cc = 0;
1719 	long slp = 0;		/* XXX this should be renamed `timo'. */
1720 	struct timeval stime;
1721 	struct pgrp *pg;
1722 
1723 	td = curthread;
1724 	p = td->td_proc;
1725 loop:
1726 	s = spltty();
1727 	lflag = tp->t_lflag;
1728 	/*
1729 	 * take pending input first
1730 	 */
1731 	if (ISSET(lflag, PENDIN)) {
1732 		ttypend(tp);
1733 		splx(s);	/* reduce latency */
1734 		s = spltty();
1735 		lflag = tp->t_lflag;	/* XXX ttypend() clobbers it */
1736 	}
1737 
1738 	/*
1739 	 * Hang process if it's in the background.
1740 	 */
1741 	if (isbackground(p, tp)) {
1742 		splx(s);
1743 		sx_slock(&proctree_lock);
1744 		PROC_LOCK(p);
1745 		if (SIGISMEMBER(p->p_sigacts->ps_sigignore, SIGTTIN) ||
1746 		    SIGISMEMBER(td->td_sigmask, SIGTTIN) ||
1747 		    (p->p_flag & P_PPWAIT) || p->p_pgrp->pg_jobc == 0) {
1748 			PROC_UNLOCK(p);
1749 			sx_sunlock(&proctree_lock);
1750 			return (EIO);
1751 		}
1752 		pg = p->p_pgrp;
1753 		PROC_UNLOCK(p);
1754 		PGRP_LOCK(pg);
1755 		sx_sunlock(&proctree_lock);
1756 		pgsignal(pg, SIGTTIN, 1);
1757 		PGRP_UNLOCK(pg);
1758 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, "ttybg2", 0);
1759 		if (error)
1760 			return (error);
1761 		goto loop;
1762 	}
1763 
1764 	if (ISSET(tp->t_state, TS_ZOMBIE)) {
1765 		splx(s);
1766 		return (0);	/* EOF */
1767 	}
1768 
1769 	/*
1770 	 * If canonical, use the canonical queue,
1771 	 * else use the raw queue.
1772 	 *
1773 	 * (should get rid of clists...)
1774 	 */
1775 	qp = ISSET(lflag, ICANON) ? &tp->t_canq : &tp->t_rawq;
1776 
1777 	if (flag & IO_NDELAY) {
1778 		if (qp->c_cc > 0)
1779 			goto read;
1780 		if (!ISSET(lflag, ICANON) && cc[VMIN] == 0) {
1781 			splx(s);
1782 			return (0);
1783 		}
1784 		splx(s);
1785 		return (EWOULDBLOCK);
1786 	}
1787 	if (!ISSET(lflag, ICANON)) {
1788 		int m = cc[VMIN];
1789 		long t = cc[VTIME];
1790 		struct timeval timecopy;
1791 
1792 		/*
1793 		 * Check each of the four combinations.
1794 		 * (m > 0 && t == 0) is the normal read case.
1795 		 * It should be fairly efficient, so we check that and its
1796 		 * companion case (m == 0 && t == 0) first.
1797 		 * For the other two cases, we compute the target sleep time
1798 		 * into slp.
1799 		 */
1800 		if (t == 0) {
1801 			if (qp->c_cc < m)
1802 				goto sleep;
1803 			if (qp->c_cc > 0)
1804 				goto read;
1805 
1806 			/* m, t and qp->c_cc are all 0.  0 is enough input. */
1807 			splx(s);
1808 			return (0);
1809 		}
1810 		t *= 100000;		/* time in us */
1811 #define diff(t1, t2) (((t1).tv_sec - (t2).tv_sec) * 1000000 + \
1812 			 ((t1).tv_usec - (t2).tv_usec))
1813 		if (m > 0) {
1814 			if (qp->c_cc <= 0)
1815 				goto sleep;
1816 			if (qp->c_cc >= m)
1817 				goto read;
1818 			getmicrotime(&timecopy);
1819 			if (!has_stime) {
1820 				/* first character, start timer */
1821 				has_stime = 1;
1822 				stime = timecopy;
1823 				slp = t;
1824 			} else if (qp->c_cc > last_cc) {
1825 				/* got a character, restart timer */
1826 				stime = timecopy;
1827 				slp = t;
1828 			} else {
1829 				/* nothing, check expiration */
1830 				slp = t - diff(timecopy, stime);
1831 				if (slp <= 0)
1832 					goto read;
1833 			}
1834 			last_cc = qp->c_cc;
1835 		} else {	/* m == 0 */
1836 			if (qp->c_cc > 0)
1837 				goto read;
1838 			getmicrotime(&timecopy);
1839 			if (!has_stime) {
1840 				has_stime = 1;
1841 				stime = timecopy;
1842 				slp = t;
1843 			} else {
1844 				slp = t - diff(timecopy, stime);
1845 				if (slp <= 0) {
1846 					/* Timed out, but 0 is enough input. */
1847 					splx(s);
1848 					return (0);
1849 				}
1850 			}
1851 		}
1852 #undef diff
1853 		if (slp != 0) {
1854 			struct timeval tv;	/* XXX style bug. */
1855 
1856 			tv.tv_sec = slp / 1000000;
1857 			tv.tv_usec = slp % 1000000;
1858 			slp = tvtohz(&tv);
1859 			/*
1860 			 * XXX bad variable names.  slp was the timeout in
1861 			 * usec.  Now it is the timeout in ticks.
1862 			 */
1863 		}
1864 		goto sleep;
1865 	}
1866 	if (qp->c_cc <= 0) {
1867 sleep:
1868 		/*
1869 		 * There is no input, or not enough input and we can block.
1870 		 */
1871 		error = ttysleep(tp, TSA_HUP_OR_INPUT(tp), TTIPRI | PCATCH,
1872 				 ISSET(tp->t_state, TS_CONNECTED) ?
1873 				 "ttyin" : "ttyhup", (int)slp);
1874 		splx(s);
1875 		if (error == EWOULDBLOCK)
1876 			error = 0;
1877 		else if (error)
1878 			return (error);
1879 		/*
1880 		 * XXX what happens if another process eats some input
1881 		 * while we are asleep (not just here)?  It would be
1882 		 * safest to detect changes and reset our state variables
1883 		 * (has_stime and last_cc).
1884 		 */
1885 		slp = 0;
1886 		goto loop;
1887 	}
1888 read:
1889 	splx(s);
1890 	/*
1891 	 * Input present, check for input mapping and processing.
1892 	 */
1893 	first = 1;
1894 	if (ISSET(lflag, ICANON | ISIG))
1895 		goto slowcase;
1896 	for (;;) {
1897 		char ibuf[IBUFSIZ];
1898 		int icc;
1899 
1900 		icc = imin(uio->uio_resid, IBUFSIZ);
1901 		icc = q_to_b(qp, ibuf, icc);
1902 		if (icc <= 0) {
1903 			if (first)
1904 				goto loop;
1905 			break;
1906 		}
1907 		error = uiomove(ibuf, icc, uio);
1908 		/*
1909 		 * XXX if there was an error then we should ungetc() the
1910 		 * unmoved chars and reduce icc here.
1911 		 */
1912 		if (error)
1913 			break;
1914 		if (uio->uio_resid == 0)
1915 			break;
1916 		first = 0;
1917 	}
1918 	goto out;
1919 slowcase:
1920 	for (;;) {
1921 		c = getc(qp);
1922 		if (c < 0) {
1923 			if (first)
1924 				goto loop;
1925 			break;
1926 		}
1927 		/*
1928 		 * delayed suspend (^Y)
1929 		 */
1930 		if (CCEQ(cc[VDSUSP], c) &&
1931 		    ISSET(lflag, IEXTEN | ISIG) == (IEXTEN | ISIG)) {
1932 			if (tp->t_pgrp != NULL) {
1933 				PGRP_LOCK(tp->t_pgrp);
1934 				pgsignal(tp->t_pgrp, SIGTSTP, 1);
1935 				PGRP_UNLOCK(tp->t_pgrp);
1936 			}
1937 			if (first) {
1938 				error = ttysleep(tp, &lbolt, TTIPRI | PCATCH,
1939 						 "ttybg3", 0);
1940 				if (error)
1941 					break;
1942 				goto loop;
1943 			}
1944 			break;
1945 		}
1946 		/*
1947 		 * Interpret EOF only in canonical mode.
1948 		 */
1949 		if (CCEQ(cc[VEOF], c) && ISSET(lflag, ICANON))
1950 			break;
1951 		/*
1952 		 * Give user character.
1953 		 */
1954 		error = ureadc(c, uio);
1955 		if (error)
1956 			/* XXX should ungetc(c, qp). */
1957 			break;
1958 		if (uio->uio_resid == 0)
1959 			break;
1960 		/*
1961 		 * In canonical mode check for a "break character"
1962 		 * marking the end of a "line of input".
1963 		 */
1964 		if (ISSET(lflag, ICANON) && TTBREAKC(c, lflag))
1965 			break;
1966 		first = 0;
1967 	}
1968 
1969 out:
1970 	/*
1971 	 * Look to unblock input now that (presumably)
1972 	 * the input queue has gone down.
1973 	 */
1974 	s = spltty();
1975 	if (ISSET(tp->t_state, TS_TBLOCK) &&
1976 	    tp->t_rawq.c_cc + tp->t_canq.c_cc <= tp->t_ilowat)
1977 		ttyunblock(tp);
1978 	splx(s);
1979 
1980 	return (error);
1981 }
1982 
1983 /*
1984  * Check the output queue on tp for space for a kernel message (from uprintf
1985  * or tprintf).  Allow some space over the normal hiwater mark so we don't
1986  * lose messages due to normal flow control, but don't let the tty run amok.
1987  * Sleeps here are not interruptible, but we return prematurely if new signals
1988  * arrive.
1989  */
1990 int
1991 ttycheckoutq(struct tty *tp, int wait)
1992 {
1993 	int hiwat, s;
1994 	sigset_t oldmask;
1995 	struct thread *td;
1996 	struct proc *p;
1997 
1998 	td = curthread;
1999 	p = td->td_proc;
2000 	hiwat = tp->t_ohiwat;
2001 	SIGEMPTYSET(oldmask);
2002 	s = spltty();
2003 	if (wait) {
2004 		PROC_LOCK(p);
2005 		oldmask = td->td_siglist;
2006 		PROC_UNLOCK(p);
2007 	}
2008 	if (tp->t_outq.c_cc > hiwat + OBUFSIZ + 100)
2009 		while (tp->t_outq.c_cc > hiwat) {
2010 			ttstart(tp);
2011 			if (tp->t_outq.c_cc <= hiwat)
2012 				break;
2013 			if (!wait) {
2014 				splx(s);
2015 				return (0);
2016 			}
2017 			PROC_LOCK(p);
2018 			if (!SIGSETEQ(td->td_siglist, oldmask)) {
2019 				PROC_UNLOCK(p);
2020 				splx(s);
2021 				return (0);
2022 			}
2023 			PROC_UNLOCK(p);
2024 			SET(tp->t_state, TS_SO_OLOWAT);
2025 			tsleep(TSA_OLOWAT(tp), PZERO - 1, "ttoutq", hz);
2026 		}
2027 	splx(s);
2028 	return (1);
2029 }
2030 
2031 /*
2032  * Process a write call on a tty device.
2033  */
2034 int
2035 ttwrite(struct tty *tp, struct uio *uio, int flag)
2036 {
2037 	char *cp = NULL;
2038 	int cc, ce;
2039 	struct thread *td;
2040 	struct proc *p;
2041 	int i, hiwat, cnt, error, s;
2042 	char obuf[OBUFSIZ];
2043 
2044 	hiwat = tp->t_ohiwat;
2045 	cnt = uio->uio_resid;
2046 	error = 0;
2047 	cc = 0;
2048 	td = curthread;
2049 	p = td->td_proc;
2050 loop:
2051 	s = spltty();
2052 	if (ISSET(tp->t_state, TS_ZOMBIE)) {
2053 		splx(s);
2054 		if (uio->uio_resid == cnt)
2055 			error = EIO;
2056 		goto out;
2057 	}
2058 	if (!ISSET(tp->t_state, TS_CONNECTED)) {
2059 		if (flag & IO_NDELAY) {
2060 			splx(s);
2061 			error = EWOULDBLOCK;
2062 			goto out;
2063 		}
2064 		error = ttysleep(tp, TSA_CARR_ON(tp), TTIPRI | PCATCH,
2065 				 "ttywdcd", 0);
2066 		splx(s);
2067 		if (error)
2068 			goto out;
2069 		goto loop;
2070 	}
2071 	splx(s);
2072 	/*
2073 	 * Hang the process if it's in the background.
2074 	 */
2075 	sx_slock(&proctree_lock);
2076 	PROC_LOCK(p);
2077 	if (isbackground(p, tp) &&
2078 	    ISSET(tp->t_lflag, TOSTOP) && !(p->p_flag & P_PPWAIT) &&
2079 	    !SIGISMEMBER(p->p_sigacts->ps_sigignore, SIGTTOU) &&
2080 	    !SIGISMEMBER(td->td_sigmask, SIGTTOU)) {
2081 		if (p->p_pgrp->pg_jobc == 0) {
2082 			PROC_UNLOCK(p);
2083 			sx_sunlock(&proctree_lock);
2084 			error = EIO;
2085 			goto out;
2086 		}
2087 		PROC_UNLOCK(p);
2088 		PGRP_LOCK(p->p_pgrp);
2089 		sx_sunlock(&proctree_lock);
2090 		pgsignal(p->p_pgrp, SIGTTOU, 1);
2091 		PGRP_UNLOCK(p->p_pgrp);
2092 		error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, "ttybg4", 0);
2093 		if (error)
2094 			goto out;
2095 		goto loop;
2096 	} else {
2097 		PROC_UNLOCK(p);
2098 		sx_sunlock(&proctree_lock);
2099 	}
2100 	/*
2101 	 * Process the user's data in at most OBUFSIZ chunks.  Perform any
2102 	 * output translation.  Keep track of high water mark, sleep on
2103 	 * overflow awaiting device aid in acquiring new space.
2104 	 */
2105 	while (uio->uio_resid > 0 || cc > 0) {
2106 		if (ISSET(tp->t_lflag, FLUSHO)) {
2107 			uio->uio_resid = 0;
2108 			return (0);
2109 		}
2110 		if (tp->t_outq.c_cc > hiwat)
2111 			goto ovhiwat;
2112 		/*
2113 		 * Grab a hunk of data from the user, unless we have some
2114 		 * leftover from last time.
2115 		 */
2116 		if (cc == 0) {
2117 			cc = imin(uio->uio_resid, OBUFSIZ);
2118 			cp = obuf;
2119 			error = uiomove(cp, cc, uio);
2120 			if (error) {
2121 				cc = 0;
2122 				break;
2123 			}
2124 		}
2125 		/*
2126 		 * If nothing fancy need be done, grab those characters we
2127 		 * can handle without any of ttyoutput's processing and
2128 		 * just transfer them to the output q.  For those chars
2129 		 * which require special processing (as indicated by the
2130 		 * bits in char_type), call ttyoutput.  After processing
2131 		 * a hunk of data, look for FLUSHO so ^O's will take effect
2132 		 * immediately.
2133 		 */
2134 		while (cc > 0) {
2135 			if (!ISSET(tp->t_oflag, OPOST))
2136 				ce = cc;
2137 			else {
2138 				ce = cc - scanc((u_int)cc, (u_char *)cp,
2139 						char_type, CCLASSMASK);
2140 				/*
2141 				 * If ce is zero, then we're processing
2142 				 * a special character through ttyoutput.
2143 				 */
2144 				if (ce == 0) {
2145 					tp->t_rocount = 0;
2146 					if (ttyoutput(*cp, tp) >= 0) {
2147 						/* No Clists, wait a bit. */
2148 						ttstart(tp);
2149 						if (flag & IO_NDELAY) {
2150 							error = EWOULDBLOCK;
2151 							goto out;
2152 						}
2153 						error = ttysleep(tp, &lbolt,
2154 								 TTOPRI|PCATCH,
2155 								 "ttybf1", 0);
2156 						if (error)
2157 							goto out;
2158 						goto loop;
2159 					}
2160 					cp++;
2161 					cc--;
2162 					if (ISSET(tp->t_lflag, FLUSHO) ||
2163 					    tp->t_outq.c_cc > hiwat)
2164 						goto ovhiwat;
2165 					continue;
2166 				}
2167 			}
2168 			/*
2169 			 * A bunch of normal characters have been found.
2170 			 * Transfer them en masse to the output queue and
2171 			 * continue processing at the top of the loop.
2172 			 * If there are any further characters in this
2173 			 * <= OBUFSIZ chunk, the first should be a character
2174 			 * requiring special handling by ttyoutput.
2175 			 */
2176 			tp->t_rocount = 0;
2177 			i = b_to_q(cp, ce, &tp->t_outq);
2178 			ce -= i;
2179 			tp->t_column += ce;
2180 			cp += ce, cc -= ce, tk_nout += ce;
2181 			tp->t_outcc += ce;
2182 			if (i > 0) {
2183 				/* No Clists, wait a bit. */
2184 				ttstart(tp);
2185 				if (flag & IO_NDELAY) {
2186 					error = EWOULDBLOCK;
2187 					goto out;
2188 				}
2189 				error = ttysleep(tp, &lbolt, TTOPRI | PCATCH,
2190 						 "ttybf2", 0);
2191 				if (error)
2192 					goto out;
2193 				goto loop;
2194 			}
2195 			if (ISSET(tp->t_lflag, FLUSHO) ||
2196 			    tp->t_outq.c_cc > hiwat)
2197 				break;
2198 		}
2199 		ttstart(tp);
2200 	}
2201 out:
2202 	/*
2203 	 * If cc is nonzero, we leave the uio structure inconsistent, as the
2204 	 * offset and iov pointers have moved forward, but it doesn't matter
2205 	 * (the call will either return short or restart with a new uio).
2206 	 */
2207 	uio->uio_resid += cc;
2208 	return (error);
2209 
2210 ovhiwat:
2211 	ttstart(tp);
2212 	s = spltty();
2213 	/*
2214 	 * This can only occur if FLUSHO is set in t_lflag,
2215 	 * or if ttstart/oproc is synchronous (or very fast).
2216 	 */
2217 	if (tp->t_outq.c_cc <= hiwat) {
2218 		splx(s);
2219 		goto loop;
2220 	}
2221 	if (flag & IO_NDELAY) {
2222 		splx(s);
2223 		uio->uio_resid += cc;
2224 		return (uio->uio_resid == cnt ? EWOULDBLOCK : 0);
2225 	}
2226 	SET(tp->t_state, TS_SO_OLOWAT);
2227 	error = ttysleep(tp, TSA_OLOWAT(tp), TTOPRI | PCATCH, "ttywri",
2228 			 tp->t_timeout);
2229 	splx(s);
2230 	if (error == EWOULDBLOCK)
2231 		error = EIO;
2232 	if (error)
2233 		goto out;
2234 	goto loop;
2235 }
2236 
2237 /*
2238  * Rubout one character from the rawq of tp
2239  * as cleanly as possible.
2240  */
2241 static void
2242 ttyrub(int c, struct tty *tp)
2243 {
2244 	char *cp;
2245 	int savecol;
2246 	int tabc, s;
2247 
2248 	if (!ISSET(tp->t_lflag, ECHO) || ISSET(tp->t_lflag, EXTPROC))
2249 		return;
2250 	CLR(tp->t_lflag, FLUSHO);
2251 	if (ISSET(tp->t_lflag, ECHOE)) {
2252 		if (tp->t_rocount == 0) {
2253 			/*
2254 			 * Screwed by ttwrite; retype
2255 			 */
2256 			ttyretype(tp);
2257 			return;
2258 		}
2259 		if (c == ('\t' | TTY_QUOTE) || c == ('\n' | TTY_QUOTE))
2260 			ttyrubo(tp, 2);
2261 		else {
2262 			CLR(c, ~TTY_CHARMASK);
2263 			switch (CCLASS(c)) {
2264 			case ORDINARY:
2265 				ttyrubo(tp, 1);
2266 				break;
2267 			case BACKSPACE:
2268 			case CONTROL:
2269 			case NEWLINE:
2270 			case RETURN:
2271 			case VTAB:
2272 				if (ISSET(tp->t_lflag, ECHOCTL))
2273 					ttyrubo(tp, 2);
2274 				break;
2275 			case TAB:
2276 				if (tp->t_rocount < tp->t_rawq.c_cc) {
2277 					ttyretype(tp);
2278 					return;
2279 				}
2280 				s = spltty();
2281 				savecol = tp->t_column;
2282 				SET(tp->t_state, TS_CNTTB);
2283 				SET(tp->t_lflag, FLUSHO);
2284 				tp->t_column = tp->t_rocol;
2285 				cp = tp->t_rawq.c_cf;
2286 				if (cp)
2287 					tabc = *cp;	/* XXX FIX NEXTC */
2288 				for (; cp; cp = nextc(&tp->t_rawq, cp, &tabc))
2289 					ttyecho(tabc, tp);
2290 				CLR(tp->t_lflag, FLUSHO);
2291 				CLR(tp->t_state, TS_CNTTB);
2292 				splx(s);
2293 
2294 				/* savecol will now be length of the tab. */
2295 				savecol -= tp->t_column;
2296 				tp->t_column += savecol;
2297 				if (savecol > 8)
2298 					savecol = 8;	/* overflow screw */
2299 				while (--savecol >= 0)
2300 					(void)ttyoutput('\b', tp);
2301 				break;
2302 			default:			/* XXX */
2303 #define	PANICSTR	"ttyrub: would panic c = %d, val = %d\n"
2304 				(void)printf(PANICSTR, c, CCLASS(c));
2305 #ifdef notdef
2306 				panic(PANICSTR, c, CCLASS(c));
2307 #endif
2308 			}
2309 		}
2310 	} else if (ISSET(tp->t_lflag, ECHOPRT)) {
2311 		if (!ISSET(tp->t_state, TS_ERASE)) {
2312 			SET(tp->t_state, TS_ERASE);
2313 			(void)ttyoutput('\\', tp);
2314 		}
2315 		ttyecho(c, tp);
2316 	} else {
2317 		ttyecho(tp->t_cc[VERASE], tp);
2318 		/*
2319 		 * This code may be executed not only when an ERASE key
2320 		 * is pressed, but also when ^U (KILL) or ^W (WERASE) are.
2321 		 * So, I didn't think it was worthwhile to pass the extra
2322 		 * information (which would need an extra parameter,
2323 		 * changing every call) needed to distinguish the ERASE2
2324 		 * case from the ERASE.
2325 		 */
2326 	}
2327 	--tp->t_rocount;
2328 }
2329 
2330 /*
2331  * Back over cnt characters, erasing them.
2332  */
2333 static void
2334 ttyrubo(struct tty *tp, int cnt)
2335 {
2336 
2337 	while (cnt-- > 0) {
2338 		(void)ttyoutput('\b', tp);
2339 		(void)ttyoutput(' ', tp);
2340 		(void)ttyoutput('\b', tp);
2341 	}
2342 }
2343 
2344 /*
2345  * ttyretype --
2346  *	Reprint the rawq line.  Note, it is assumed that c_cc has already
2347  *	been checked.
2348  */
2349 static void
2350 ttyretype(struct tty *tp)
2351 {
2352 	char *cp;
2353 	int s, c;
2354 
2355 	/* Echo the reprint character. */
2356 	if (tp->t_cc[VREPRINT] != _POSIX_VDISABLE)
2357 		ttyecho(tp->t_cc[VREPRINT], tp);
2358 
2359 	(void)ttyoutput('\n', tp);
2360 
2361 	/*
2362 	 * XXX
2363 	 * FIX: NEXTC IS BROKEN - DOESN'T CHECK QUOTE
2364 	 * BIT OF FIRST CHAR.
2365 	 */
2366 	s = spltty();
2367 	for (cp = tp->t_canq.c_cf, c = (cp != NULL ? *cp : 0);
2368 	    cp != NULL; cp = nextc(&tp->t_canq, cp, &c))
2369 		ttyecho(c, tp);
2370 	for (cp = tp->t_rawq.c_cf, c = (cp != NULL ? *cp : 0);
2371 	    cp != NULL; cp = nextc(&tp->t_rawq, cp, &c))
2372 		ttyecho(c, tp);
2373 	CLR(tp->t_state, TS_ERASE);
2374 	splx(s);
2375 
2376 	tp->t_rocount = tp->t_rawq.c_cc;
2377 	tp->t_rocol = 0;
2378 }
2379 
2380 /*
2381  * Echo a typed character to the terminal.
2382  */
2383 static void
2384 ttyecho(int c, struct tty *tp)
2385 {
2386 
2387 	if (!ISSET(tp->t_state, TS_CNTTB))
2388 		CLR(tp->t_lflag, FLUSHO);
2389 	if ((!ISSET(tp->t_lflag, ECHO) &&
2390 	     (c != '\n' || !ISSET(tp->t_lflag, ECHONL))) ||
2391 	    ISSET(tp->t_lflag, EXTPROC))
2392 		return;
2393 	if (ISSET(tp->t_lflag, ECHOCTL) &&
2394 	    ((ISSET(c, TTY_CHARMASK) <= 037 && c != '\t' && c != '\n') ||
2395 	    ISSET(c, TTY_CHARMASK) == 0177)) {
2396 		(void)ttyoutput('^', tp);
2397 		CLR(c, ~TTY_CHARMASK);
2398 		if (c == 0177)
2399 			c = '?';
2400 		else
2401 			c += 'A' - 1;
2402 	}
2403 	(void)ttyoutput(c, tp);
2404 }
2405 
2406 /*
2407  * Wake up any readers on a tty.
2408  */
2409 void
2410 ttwakeup(struct tty *tp)
2411 {
2412 
2413 	if (SEL_WAITING(&tp->t_rsel))
2414 		selwakeuppri(&tp->t_rsel, TTIPRI);
2415 	if (ISSET(tp->t_state, TS_ASYNC) && tp->t_sigio != NULL)
2416 		pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
2417 	wakeup(TSA_HUP_OR_INPUT(tp));
2418 	KNOTE_UNLOCKED(&tp->t_rsel.si_note, 0);
2419 }
2420 
2421 /*
2422  * Wake up any writers on a tty.
2423  */
2424 void
2425 ttwwakeup(struct tty *tp)
2426 {
2427 
2428 	if (SEL_WAITING(&tp->t_wsel) && tp->t_outq.c_cc <= tp->t_olowat)
2429 		selwakeuppri(&tp->t_wsel, TTOPRI);
2430 	if (ISSET(tp->t_state, TS_ASYNC) && tp->t_sigio != NULL)
2431 		pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
2432 	if (ISSET(tp->t_state, TS_BUSY | TS_SO_OCOMPLETE) ==
2433 	    TS_SO_OCOMPLETE && tp->t_outq.c_cc == 0) {
2434 		CLR(tp->t_state, TS_SO_OCOMPLETE);
2435 		wakeup(TSA_OCOMPLETE(tp));
2436 	}
2437 	if (ISSET(tp->t_state, TS_SO_OLOWAT) &&
2438 	    tp->t_outq.c_cc <= tp->t_olowat) {
2439 		CLR(tp->t_state, TS_SO_OLOWAT);
2440 		wakeup(TSA_OLOWAT(tp));
2441 	}
2442 	KNOTE_UNLOCKED(&tp->t_wsel.si_note, 0);
2443 }
2444 
2445 /*
2446  * Look up a code for a specified speed in a conversion table;
2447  * used by drivers to map software speed values to hardware parameters.
2448  */
2449 int
2450 ttspeedtab(int speed, struct speedtab *table)
2451 {
2452 
2453 	for ( ; table->sp_speed != -1; table++)
2454 		if (table->sp_speed == speed)
2455 			return (table->sp_code);
2456 	return (-1);
2457 }
2458 
2459 /*
2460  * Set input and output watermarks and buffer sizes.  For input, the
2461  * high watermark is about one second's worth of input above empty, the
2462  * low watermark is slightly below high water, and the buffer size is a
2463  * driver-dependent amount above high water.  For output, the watermarks
2464  * are near the ends of the buffer, with about 1 second's worth of input
2465  * between them.  All this only applies to the standard line discipline.
2466  */
2467 void
2468 ttsetwater(struct tty *tp)
2469 {
2470 	int cps, ttmaxhiwat, x;
2471 
2472 	/* Input. */
2473 	clist_alloc_cblocks(&tp->t_canq, TTYHOG, 512);
2474 	switch (tp->t_ispeedwat) {
2475 	case (speed_t)-1:
2476 		cps = tp->t_ispeed / 10;
2477 		break;
2478 	case 0:
2479 		/*
2480 		 * This case is for old drivers that don't know about
2481 		 * t_ispeedwat.  Arrange for them to get the old buffer
2482 		 * sizes and watermarks.
2483 		 */
2484 		cps = TTYHOG - 2 * 256;
2485 		tp->t_ififosize = 2 * 256;
2486 		break;
2487 	default:
2488 		cps = tp->t_ispeedwat / 10;
2489 		break;
2490 	}
2491 	tp->t_ihiwat = cps;
2492 	tp->t_ilowat = 7 * cps / 8;
2493 	x = cps + tp->t_ififosize;
2494 	clist_alloc_cblocks(&tp->t_rawq, x, x);
2495 
2496 	/* Output. */
2497 	switch (tp->t_ospeedwat) {
2498 	case (speed_t)-1:
2499 		cps = tp->t_ospeed / 10;
2500 		ttmaxhiwat = 2 * TTMAXHIWAT;
2501 		break;
2502 	case 0:
2503 		cps = tp->t_ospeed / 10;
2504 		ttmaxhiwat = TTMAXHIWAT;
2505 		break;
2506 	default:
2507 		cps = tp->t_ospeedwat / 10;
2508 		ttmaxhiwat = 8 * TTMAXHIWAT;
2509 		break;
2510 	}
2511 #define CLAMP(x, h, l)	((x) > h ? h : ((x) < l) ? l : (x))
2512 	tp->t_olowat = x = CLAMP(cps / 2, TTMAXLOWAT, TTMINLOWAT);
2513 	x += cps;
2514 	x = CLAMP(x, ttmaxhiwat, TTMINHIWAT);	/* XXX clamps are too magic */
2515 	tp->t_ohiwat = roundup(x, CBSIZE);	/* XXX for compat */
2516 	x = imax(tp->t_ohiwat, TTMAXHIWAT);	/* XXX for compat/safety */
2517 	x += OBUFSIZ + 100;
2518 	clist_alloc_cblocks(&tp->t_outq, x, x);
2519 #undef	CLAMP
2520 }
2521 
2522 /*
2523  * Report on state of foreground process group.
2524  */
2525 void
2526 ttyinfo(struct tty *tp)
2527 {
2528 	struct timeval utime, stime;
2529 	struct proc *p, *pick;
2530 	struct thread *td;
2531 	const char *stateprefix, *state;
2532 	long rss;
2533 	int load, pctcpu;
2534 	pid_t pid;
2535 	char comm[MAXCOMLEN + 1];
2536 
2537 	if (ttycheckoutq(tp,0) == 0)
2538 		return;
2539 
2540 	/* Print load average. */
2541 	load = (averunnable.ldavg[0] * 100 + FSCALE / 2) >> FSHIFT;
2542 	ttyprintf(tp, "load: %d.%02d ", load / 100, load % 100);
2543 
2544 	/*
2545 	 * On return following a ttyprintf(), we set tp->t_rocount to 0 so
2546 	 * that pending input will be retyped on BS.
2547 	 */
2548 	if (tp->t_session == NULL) {
2549 		ttyprintf(tp, "not a controlling terminal\n");
2550 		tp->t_rocount = 0;
2551 		return;
2552 	}
2553 	if (tp->t_pgrp == NULL) {
2554 		ttyprintf(tp, "no foreground process group\n");
2555 		tp->t_rocount = 0;
2556 		return;
2557 	}
2558 	PGRP_LOCK(tp->t_pgrp);
2559 	if (LIST_EMPTY(&tp->t_pgrp->pg_members)) {
2560 		PGRP_UNLOCK(tp->t_pgrp);
2561 		ttyprintf(tp, "empty foreground process group\n");
2562 		tp->t_rocount = 0;
2563 		return;
2564 	}
2565 
2566 	/*
2567 	 * Pick the most interesting process and copy some of its
2568 	 * state for printing later.  sched_lock must be held for
2569 	 * most parts of this.  Holding it throughout is simplest
2570 	 * and prevents even unimportant inconsistencies in the
2571 	 * copy of the state, but may increase interrupt latency
2572 	 * too much.
2573 	 */
2574 	pick = NULL;
2575 	mtx_lock_spin(&sched_lock);
2576 	LIST_FOREACH(p, &tp->t_pgrp->pg_members, p_pglist)
2577 		if (proc_compare(pick, p))
2578 			pick = p;
2579 
2580 	td = FIRST_THREAD_IN_PROC(pick);	/* XXXKSE */
2581 #if 0
2582 	KASSERT(td != NULL, ("ttyinfo: no thread"));
2583 #else
2584 	if (td == NULL) {
2585 		mtx_unlock_spin(&sched_lock);
2586 		PGRP_UNLOCK(tp->t_pgrp);
2587 		ttyprintf(tp, "foreground process without thread\n");
2588 		tp->t_rocount = 0;
2589 		return;
2590 	}
2591 #endif
2592 	stateprefix = "";
2593 	if (TD_IS_RUNNING(td))
2594 		state = "running";
2595 	else if (TD_ON_RUNQ(td) || TD_CAN_RUN(td))
2596 		state = "runnable";
2597 	else if (TD_IS_SLEEPING(td)) {
2598 		/* XXX: If we're sleeping, are we ever not in a queue? */
2599 		if (TD_ON_SLEEPQ(td))
2600 			state = td->td_wmesg;
2601 		else
2602 			state = "sleeping without queue";
2603 	} else if (TD_ON_LOCK(td)) {
2604 		state = td->td_lockname;
2605 		stateprefix = "*";
2606 	} else if (TD_IS_SUSPENDED(td))
2607 		state = "suspended";
2608 	else if (TD_AWAITING_INTR(td))
2609 		state = "intrwait";
2610 	else
2611 		state = "unknown";
2612 	pctcpu = (sched_pctcpu(td) * 10000 + FSCALE / 2) >> FSHIFT;
2613 	if (pick->p_state == PRS_NEW || pick->p_state == PRS_ZOMBIE)
2614 		rss = 0;
2615 	else
2616 		rss = pgtok(vmspace_resident_count(pick->p_vmspace));
2617 	mtx_unlock_spin(&sched_lock);
2618 	PROC_LOCK(pick);
2619 	PGRP_UNLOCK(tp->t_pgrp);
2620 	calcru(pick, &utime, &stime);
2621 	pid = pick->p_pid;
2622 	bcopy(pick->p_comm, comm, sizeof(comm));
2623 	PROC_UNLOCK(pick);
2624 
2625 	/* Print command, pid, state, utime, stime, %cpu, and rss. */
2626 	ttyprintf(tp,
2627 	    " cmd: %s %d [%s%s] %ld.%02ldu %ld.%02lds %d%% %ldk\n",
2628 	    comm, pid, stateprefix, state,
2629 	    (long)utime.tv_sec, utime.tv_usec / 10000,
2630 	    (long)stime.tv_sec, stime.tv_usec / 10000,
2631 	    pctcpu / 100, rss);
2632 	tp->t_rocount = 0;
2633 }
2634 
2635 /*
2636  * Returns 1 if p2 is "better" than p1
2637  *
2638  * The algorithm for picking the "interesting" process is thus:
2639  *
2640  *	1) Only foreground processes are eligible - implied.
2641  *	2) Runnable processes are favored over anything else.  The runner
2642  *	   with the highest cpu utilization is picked (p_estcpu).  Ties are
2643  *	   broken by picking the highest pid.
2644  *	3) The sleeper with the shortest sleep time is next.  With ties,
2645  *	   we pick out just "short-term" sleepers (P_SINTR == 0).
2646  *	4) Further ties are broken by picking the highest pid.
2647  */
2648 #define ISRUN(p, val)						\
2649 do {								\
2650 	struct thread *td;					\
2651 	val = 0;						\
2652 	FOREACH_THREAD_IN_PROC(p, td) {				\
2653 		if (TD_ON_RUNQ(td) ||				\
2654 		    TD_IS_RUNNING(td)) {			\
2655 			val = 1;				\
2656 			break;					\
2657 		}						\
2658 	}							\
2659 } while (0)
2660 
2661 #define TESTAB(a, b)    ((a)<<1 | (b))
2662 #define ONLYA   2
2663 #define ONLYB   1
2664 #define BOTH    3
2665 
2666 static int
2667 proc_compare(struct proc *p1, struct proc *p2)
2668 {
2669 
2670 	int esta, estb;
2671 	struct ksegrp *kg;
2672 	mtx_assert(&sched_lock, MA_OWNED);
2673 	if (p1 == NULL)
2674 		return (1);
2675 
2676 	ISRUN(p1, esta);
2677 	ISRUN(p2, estb);
2678 
2679 	/*
2680 	 * see if at least one of them is runnable
2681 	 */
2682 	switch (TESTAB(esta, estb)) {
2683 	case ONLYA:
2684 		return (0);
2685 	case ONLYB:
2686 		return (1);
2687 	case BOTH:
2688 		/*
2689 		 * tie - favor one with highest recent cpu utilization
2690 		 */
2691 		esta = estb = 0;
2692 		FOREACH_KSEGRP_IN_PROC(p1,kg) {
2693 			esta += kg->kg_estcpu;
2694 		}
2695 		FOREACH_KSEGRP_IN_PROC(p2,kg) {
2696 			estb += kg->kg_estcpu;
2697 		}
2698 		if (estb > esta)
2699 			return (1);
2700 		if (esta > estb)
2701 			return (0);
2702 		return (p2->p_pid > p1->p_pid);	/* tie - return highest pid */
2703 	}
2704 	/*
2705 	 * weed out zombies
2706 	 */
2707 	switch (TESTAB(p1->p_state == PRS_ZOMBIE, p2->p_state == PRS_ZOMBIE)) {
2708 	case ONLYA:
2709 		return (1);
2710 	case ONLYB:
2711 		return (0);
2712 	case BOTH:
2713 		return (p2->p_pid > p1->p_pid); /* tie - return highest pid */
2714 	}
2715 
2716 #if 0 /* XXXKSE */
2717 	/*
2718 	 * pick the one with the smallest sleep time
2719 	 */
2720 	if (p2->p_slptime > p1->p_slptime)
2721 		return (0);
2722 	if (p1->p_slptime > p2->p_slptime)
2723 		return (1);
2724 	/*
2725 	 * favor one sleeping in a non-interruptible sleep
2726 	 */
2727 	if (p1->p_sflag & PS_SINTR && (p2->p_sflag & PS_SINTR) == 0)
2728 		return (1);
2729 	if (p2->p_sflag & PS_SINTR && (p1->p_sflag & PS_SINTR) == 0)
2730 		return (0);
2731 #endif
2732 	return (p2->p_pid > p1->p_pid);		/* tie - return highest pid */
2733 }
2734 
2735 /*
2736  * Output char to tty; console putchar style.
2737  */
2738 int
2739 tputchar(int c, struct tty *tp)
2740 {
2741 	int s;
2742 
2743 	s = spltty();
2744 	if (!ISSET(tp->t_state, TS_CONNECTED)) {
2745 		splx(s);
2746 		return (-1);
2747 	}
2748 	if (c == '\n')
2749 		(void)ttyoutput('\r', tp);
2750 	(void)ttyoutput(c, tp);
2751 	ttstart(tp);
2752 	splx(s);
2753 	return (0);
2754 }
2755 
2756 /*
2757  * Sleep on chan, returning ERESTART if tty changed while we napped and
2758  * returning any errors (e.g. EINTR/EWOULDBLOCK) reported by tsleep.  If
2759  * the tty is revoked, restarting a pending call will redo validation done
2760  * at the start of the call.
2761  */
2762 int
2763 ttysleep(struct tty *tp, void *chan, int pri, char *wmesg, int timo)
2764 {
2765 	int error;
2766 	int gen;
2767 
2768 	gen = tp->t_gen;
2769 	error = tsleep(chan, pri, wmesg, timo);
2770 	if (tp->t_state & TS_GONE)
2771 		return (ENXIO);
2772 	if (error)
2773 		return (error);
2774 	return (tp->t_gen == gen ? 0 : ERESTART);
2775 }
2776 
2777 /*
2778  * Gain a reference to a TTY
2779  */
2780 int
2781 ttyref(struct tty *tp)
2782 {
2783 	int i;
2784 
2785 	mtx_lock(&tp->t_mtx);
2786 	KASSERT(tp->t_refcnt > 0,
2787 	    ("ttyref(): tty refcnt is %d (%s)",
2788 	    tp->t_refcnt, tp->t_dev != NULL ? devtoname(tp->t_dev) : "??"));
2789 	i = ++tp->t_refcnt;
2790 	mtx_unlock(&tp->t_mtx);
2791 	return (i);
2792 }
2793 
2794 /*
2795  * Drop a reference to a TTY.
2796  * When reference count drops to zero, we free it.
2797  */
2798 int
2799 ttyrel(struct tty *tp)
2800 {
2801 	int i;
2802 
2803 	mtx_lock(&tty_list_mutex);
2804 	mtx_lock(&tp->t_mtx);
2805 	KASSERT(tp->t_refcnt > 0,
2806 	    ("ttyrel(): tty refcnt is %d (%s)",
2807 	    tp->t_refcnt, tp->t_dev != NULL ? devtoname(tp->t_dev) : "??"));
2808 	i = --tp->t_refcnt;
2809 	if (i != 0) {
2810 		mtx_unlock(&tp->t_mtx);
2811 		mtx_unlock(&tty_list_mutex);
2812 		return (i);
2813 	}
2814 	TAILQ_REMOVE(&tty_list, tp, t_list);
2815 	mtx_unlock(&tp->t_mtx);
2816 	mtx_unlock(&tty_list_mutex);
2817 	knlist_destroy(&tp->t_rsel.si_note);
2818 	knlist_destroy(&tp->t_wsel.si_note);
2819 	mtx_destroy(&tp->t_mtx);
2820 	free(tp, M_TTYS);
2821 	return (i);
2822 }
2823 
2824 /*
2825  * Allocate a tty struct.  Clists in the struct will be allocated by
2826  * tty_open().
2827  */
2828 struct tty *
2829 ttymalloc(struct tty *tp)
2830 {
2831 	static int once;
2832 
2833 	if (!once) {
2834 		mtx_init(&tty_list_mutex, "ttylist", NULL, MTX_DEF);
2835 		once++;
2836 	}
2837 
2838 	if (tp) {
2839 		/*
2840 		 * XXX: Either this argument should go away, or we should
2841 		 * XXX: require it and do a ttyrel(tp) here and allocate
2842 		 * XXX: a new tty.  For now do nothing.
2843 		 */
2844 		return(tp);
2845 	}
2846 	tp = malloc(sizeof *tp, M_TTYS, M_WAITOK | M_ZERO);
2847 	mtx_init(&tp->t_mtx, "tty", NULL, MTX_DEF);
2848 
2849 	/*
2850 	 * Set up the initial state
2851 	 */
2852 	tp->t_refcnt = 1;
2853 	tp->t_timeout = -1;
2854 	tp->t_dtr_wait = 3 * hz;
2855 
2856 	ttyinitmode(tp, 0, 0);
2857 	bcopy(ttydefchars, tp->t_init_in.c_cc, sizeof tp->t_init_in.c_cc);
2858 
2859 	/* Make callout the same as callin */
2860 	tp->t_init_out = tp->t_init_in;
2861 
2862 	mtx_lock(&tty_list_mutex);
2863 	TAILQ_INSERT_TAIL(&tty_list, tp, t_list);
2864 	mtx_unlock(&tty_list_mutex);
2865 	knlist_init(&tp->t_rsel.si_note, &tp->t_mtx, NULL, NULL, NULL);
2866 	knlist_init(&tp->t_wsel.si_note, &tp->t_mtx, NULL, NULL, NULL);
2867 	return (tp);
2868 }
2869 
2870 struct tty *
2871 ttyalloc()
2872 {
2873 
2874 	return (ttymalloc(NULL));
2875 }
2876 
2877 static void
2878 ttypurge(struct cdev *dev)
2879 {
2880 
2881 	if (dev->si_tty == NULL)
2882 		return;
2883 	ttygone(dev->si_tty);
2884 }
2885 
2886 /*
2887  * ttycreate()
2888  *
2889  * Create the device entries for this tty thereby opening it for business.
2890  *
2891  * The flags argument controls if "cua" units are created.
2892  *
2893  * The t_sc filed is copied to si_drv1 in the created cdevs.  This
2894  * is particularly important for ->t_cioctl() users.
2895  *
2896  * XXX: implement the init and lock devices by cloning.
2897  */
2898 
2899 int
2900 ttycreate(struct tty *tp, int flags, const char *fmt, ...)
2901 {
2902 	char namebuf[SPECNAMELEN - 3];		/* XXX space for "tty" */
2903 	struct cdevsw *csw = NULL;
2904 	int unit = 0;
2905 	va_list ap;
2906 	struct cdev *cp;
2907 	int i, minor, sminor, sunit;
2908 
2909 	mtx_assert(&Giant, MA_OWNED);
2910 
2911 	if (tty_unit == NULL)
2912 		tty_unit = new_unrhdr(0, 0xffff, NULL);
2913 
2914 	sunit = alloc_unr(tty_unit);
2915 	tp->t_devunit = sunit;
2916 
2917 	if (csw == NULL) {
2918 		csw = &tty_cdevsw;
2919 		unit = sunit;
2920 	}
2921 	KASSERT(csw->d_purge == NULL || csw->d_purge == ttypurge,
2922 	    ("tty should not have d_purge"));
2923 
2924 	csw->d_purge = ttypurge;
2925 
2926 	minor = unit2minor(unit);
2927 	sminor = unit2minor(sunit);
2928 	va_start(ap, fmt);
2929 	i = vsnrprintf(namebuf, sizeof namebuf, 32, fmt, ap);
2930 	va_end(ap);
2931 	KASSERT(i < sizeof namebuf, ("Too long tty name (%s)", namebuf));
2932 
2933 	cp = make_dev(csw, minor,
2934 	    UID_ROOT, GID_WHEEL, 0600, "tty%s", namebuf);
2935 	tp->t_dev = cp;
2936 	tp->t_mdev = cp;
2937 	cp->si_tty = tp;
2938 	cp->si_drv1 = tp->t_sc;
2939 
2940 	cp = make_dev(&ttys_cdevsw, sminor | MINOR_INIT,
2941 	    UID_ROOT, GID_WHEEL, 0600, "tty%s.init", namebuf);
2942 	dev_depends(tp->t_dev, cp);
2943 	cp->si_drv1 = tp->t_sc;
2944 	cp->si_drv2 = &tp->t_init_in;
2945 	cp->si_tty = tp;
2946 
2947 	cp = make_dev(&ttys_cdevsw, sminor | MINOR_LOCK,
2948 	    UID_ROOT, GID_WHEEL, 0600, "tty%s.lock", namebuf);
2949 	dev_depends(tp->t_dev, cp);
2950 	cp->si_drv1 = tp->t_sc;
2951 	cp->si_drv2 = &tp->t_lock_in;
2952 	cp->si_tty = tp;
2953 
2954 	if (flags & TS_CALLOUT) {
2955 		cp = make_dev(csw, minor | MINOR_CALLOUT,
2956 		    UID_UUCP, GID_DIALER, 0660, "cua%s", namebuf);
2957 		dev_depends(tp->t_dev, cp);
2958 		cp->si_drv1 = tp->t_sc;
2959 		cp->si_tty = tp;
2960 
2961 		cp = make_dev(&ttys_cdevsw, sminor | MINOR_CALLOUT | MINOR_INIT,
2962 		    UID_UUCP, GID_DIALER, 0660, "cua%s.init", namebuf);
2963 		dev_depends(tp->t_dev, cp);
2964 		cp->si_drv1 = tp->t_sc;
2965 		cp->si_drv2 = &tp->t_init_out;
2966 		cp->si_tty = tp;
2967 
2968 		cp = make_dev(&ttys_cdevsw, sminor | MINOR_CALLOUT | MINOR_LOCK,
2969 		    UID_UUCP, GID_DIALER, 0660, "cua%s.lock", namebuf);
2970 		dev_depends(tp->t_dev, cp);
2971 		cp->si_drv1 = tp->t_sc;
2972 		cp->si_drv2 = &tp->t_lock_out;
2973 		cp->si_tty = tp;
2974 	}
2975 
2976 	return (0);
2977 }
2978 
2979 /*
2980  * This function is called when the hardware disappears.  We set a flag
2981  * and wake up stuff so all sleeping threads will notice.
2982  */
2983 void
2984 ttygone(struct tty *tp)
2985 {
2986 
2987 	tp->t_state |= TS_GONE;
2988 	wakeup(&tp->t_dtr_wait);
2989 	wakeup(TSA_CARR_ON(tp));
2990 	wakeup(TSA_HUP_OR_INPUT(tp));
2991 	wakeup(TSA_OCOMPLETE(tp));
2992 	wakeup(TSA_OLOWAT(tp));
2993 	tt_purge(tp);
2994 }
2995 
2996 /*
2997  * ttyfree()
2998  *
2999  * Called when the driver is ready to free the tty structure.
3000  *
3001  * XXX: This shall sleep until all threads have left the driver.
3002  */
3003 
3004 void
3005 ttyfree(struct tty *tp)
3006 {
3007 	u_int unit;
3008 
3009 	mtx_assert(&Giant, MA_OWNED);
3010 	ttygone(tp);
3011 	unit = tp->t_devunit;
3012 	destroy_dev(tp->t_mdev);
3013 	free_unr(tty_unit, unit);
3014 }
3015 
3016 static int
3017 sysctl_kern_ttys(SYSCTL_HANDLER_ARGS)
3018 {
3019 	struct tty *tp, *tp2;
3020 	struct xtty xt;
3021 	int error;
3022 
3023 	error = 0;
3024 	mtx_lock(&tty_list_mutex);
3025 	tp = TAILQ_FIRST(&tty_list);
3026 	if (tp != NULL)
3027 		ttyref(tp);
3028 	mtx_unlock(&tty_list_mutex);
3029 	while (tp != NULL) {
3030 		bzero(&xt, sizeof xt);
3031 		xt.xt_size = sizeof xt;
3032 #define XT_COPY(field) xt.xt_##field = tp->t_##field
3033 		xt.xt_rawcc = tp->t_rawq.c_cc;
3034 		xt.xt_cancc = tp->t_canq.c_cc;
3035 		xt.xt_outcc = tp->t_outq.c_cc;
3036 		XT_COPY(line);
3037 		if (tp->t_dev != NULL)
3038 			xt.xt_dev = dev2udev(tp->t_dev);
3039 		XT_COPY(state);
3040 		XT_COPY(flags);
3041 		XT_COPY(timeout);
3042 		if (tp->t_pgrp != NULL)
3043 			xt.xt_pgid = tp->t_pgrp->pg_id;
3044 		if (tp->t_session != NULL)
3045 			xt.xt_sid = tp->t_session->s_sid;
3046 		XT_COPY(termios);
3047 		XT_COPY(winsize);
3048 		XT_COPY(column);
3049 		XT_COPY(rocount);
3050 		XT_COPY(rocol);
3051 		XT_COPY(ififosize);
3052 		XT_COPY(ihiwat);
3053 		XT_COPY(ilowat);
3054 		XT_COPY(ispeedwat);
3055 		XT_COPY(ohiwat);
3056 		XT_COPY(olowat);
3057 		XT_COPY(ospeedwat);
3058 #undef XT_COPY
3059 		error = SYSCTL_OUT(req, &xt, sizeof xt);
3060 		if (error != 0) {
3061 			ttyrel(tp);
3062 			return (error);
3063 		}
3064 		mtx_lock(&tty_list_mutex);
3065 		tp2 = TAILQ_NEXT(tp, t_list);
3066 		if (tp2 != NULL)
3067 			ttyref(tp2);
3068 		mtx_unlock(&tty_list_mutex);
3069 		ttyrel(tp);
3070 		tp = tp2;
3071 	}
3072 	return (0);
3073 }
3074 
3075 SYSCTL_PROC(_kern, OID_AUTO, ttys, CTLTYPE_OPAQUE|CTLFLAG_RD,
3076 	0, 0, sysctl_kern_ttys, "S,xtty", "All ttys");
3077 SYSCTL_LONG(_kern, OID_AUTO, tty_nin, CTLFLAG_RD,
3078 	&tk_nin, 0, "Total TTY in characters");
3079 SYSCTL_LONG(_kern, OID_AUTO, tty_nout, CTLFLAG_RD,
3080 	&tk_nout, 0, "Total TTY out characters");
3081 
3082 void
3083 nottystop(struct tty *tp, int rw)
3084 {
3085 
3086 	return;
3087 }
3088 
3089 int
3090 ttyopen(struct cdev *dev, int flag, int mode, struct thread *td)
3091 {
3092 	int		error;
3093 	int		s;
3094 	struct tty	*tp;
3095 
3096 	tp = dev->si_tty;
3097 	s = spltty();
3098 	/*
3099 	 * We jump to this label after all non-interrupted sleeps to pick
3100 	 * up any changes of the device state.
3101 	 */
3102 open_top:
3103 	if (tp->t_state & TS_GONE)
3104 		return (ENXIO);
3105 	error = ttydtrwaitsleep(tp);
3106 	if (error)
3107 		goto out;
3108 	if (tp->t_state & TS_ISOPEN) {
3109 		/*
3110 		 * The device is open, so everything has been initialized.
3111 		 * Handle conflicts.
3112 		 */
3113 		if (ISCALLOUT(dev) && !tp->t_actout)
3114 			return (EBUSY);
3115 		if (tp->t_actout && !ISCALLOUT(dev)) {
3116 			if (flag & O_NONBLOCK)
3117 				return (EBUSY);
3118 			error =	tsleep(&tp->t_actout,
3119 				       TTIPRI | PCATCH, "ttybi", 0);
3120 			if (error != 0 || (tp->t_flags & TS_GONE))
3121 				goto out;
3122 			goto open_top;
3123 		}
3124 		if (tp->t_state & TS_XCLUDE && suser(td))
3125 			return (EBUSY);
3126 	} else {
3127 		/*
3128 		 * The device isn't open, so there are no conflicts.
3129 		 * Initialize it.  Initialization is done twice in many
3130 		 * cases: to preempt sleeping callin opens if we are
3131 		 * callout, and to complete a callin open after DCD rises.
3132 		 */
3133 		tp->t_termios = ISCALLOUT(dev) ? tp->t_init_out : tp->t_init_in;
3134 		tp->t_cflag = tp->t_termios.c_cflag;
3135 		if (tp->t_modem != NULL)
3136 			tt_modem(tp, SER_DTR | SER_RTS, 0);
3137 		++tp->t_wopeners;
3138 		error = tt_param(tp, &tp->t_termios);
3139 		--tp->t_wopeners;
3140 		if (error == 0)
3141 			error = tt_open(tp, dev);
3142 		if (error != 0)
3143 			goto out;
3144 		if (ISCALLOUT(dev) || (tt_modem(tp, 0, 0) & SER_DCD))
3145 			ttyld_modem(tp, 1);
3146 	}
3147 	/*
3148 	 * Wait for DCD if necessary.
3149 	 */
3150 	if (!(tp->t_state & TS_CARR_ON) && !ISCALLOUT(dev)
3151 	    && !(tp->t_cflag & CLOCAL) && !(flag & O_NONBLOCK)) {
3152 		++tp->t_wopeners;
3153 		error = tsleep(TSA_CARR_ON(tp), TTIPRI | PCATCH, "ttydcd", 0);
3154 		--tp->t_wopeners;
3155 		if (error != 0 || (tp->t_state & TS_GONE))
3156 			goto out;
3157 		goto open_top;
3158 	}
3159 	error =	ttyld_open(tp, dev);
3160 	ttyldoptim(tp);
3161 	if (tp->t_state & TS_ISOPEN && ISCALLOUT(dev))
3162 		tp->t_actout = TRUE;
3163 out:
3164 	splx(s);
3165 	if (!(tp->t_state & TS_ISOPEN) && tp->t_wopeners == 0)
3166 		tt_close(tp);
3167 	return (error);
3168 }
3169 
3170 int
3171 ttyclose(struct cdev *dev, int flag, int mode, struct thread *td)
3172 {
3173 	struct tty *tp;
3174 
3175 	tp = dev->si_tty;
3176 	ttyld_close(tp, flag);
3177 	ttyldoptim(tp);
3178 	tt_close(tp);
3179 	tp->t_do_timestamp = 0;
3180 	if (tp->t_pps != NULL)
3181 		tp->t_pps->ppsparam.mode = 0;
3182 	tty_close(tp);
3183 	return (0);
3184 }
3185 
3186 int
3187 ttyread(struct cdev *dev, struct uio *uio, int flag)
3188 {
3189 	struct tty *tp;
3190 
3191 	tp = tty_gettp(dev);
3192 
3193 	if (tp->t_state & TS_GONE)
3194 		return (ENODEV);
3195 	return (ttyld_read(tp, uio, flag));
3196 }
3197 
3198 int
3199 ttywrite(struct cdev *dev, struct uio *uio, int flag)
3200 {
3201 	struct tty *tp;
3202 
3203 	tp = tty_gettp(dev);
3204 
3205 	if (tp->t_state & TS_GONE)
3206 		return (ENODEV);
3207 	return (ttyld_write(tp, uio, flag));
3208 }
3209 
3210 int
3211 ttyioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
3212 {
3213 	struct	tty *tp;
3214 	int	error;
3215 
3216 	tp = dev->si_tty;
3217 
3218 	if (cmd == TIOCSETA || cmd == TIOCSETAW || cmd == TIOCSETAF) {
3219 		int cc;
3220 		struct termios *dt = (struct termios *)data;
3221 		struct termios *lt =
3222 		    ISCALLOUT(dev) ?  &tp->t_lock_out : &tp->t_lock_in;
3223 
3224 		dt->c_iflag = (tp->t_iflag & lt->c_iflag)
3225 		    | (dt->c_iflag & ~lt->c_iflag);
3226 		dt->c_oflag = (tp->t_oflag & lt->c_oflag)
3227 		    | (dt->c_oflag & ~lt->c_oflag);
3228 		dt->c_cflag = (tp->t_cflag & lt->c_cflag)
3229 		    | (dt->c_cflag & ~lt->c_cflag);
3230 		dt->c_lflag = (tp->t_lflag & lt->c_lflag)
3231 		    | (dt->c_lflag & ~lt->c_lflag);
3232 		for (cc = 0; cc < NCCS; ++cc)
3233 		    if (lt->c_cc[cc] != 0)
3234 		        dt->c_cc[cc] = tp->t_cc[cc];
3235 		if (lt->c_ispeed != 0)
3236 		    dt->c_ispeed = tp->t_ispeed;
3237 		if (lt->c_ospeed != 0)
3238 		    dt->c_ospeed = tp->t_ospeed;
3239 	}
3240 
3241 	error = ttyld_ioctl(tp, cmd, data, flag, td);
3242 	if (error == ENOIOCTL)
3243 		error = ttioctl(tp, cmd, data, flag);
3244 	ttyldoptim(tp);
3245 	if (error != ENOIOCTL)
3246 		return (error);
3247 	return (ENOTTY);
3248 }
3249 
3250 void
3251 ttyldoptim(struct tty *tp)
3252 {
3253 	struct termios	*t;
3254 
3255 	t = &tp->t_termios;
3256 	if (!(t->c_iflag & (ICRNL | IGNCR | IMAXBEL | INLCR | ISTRIP | IXON))
3257 	    && (!(t->c_iflag & BRKINT) || (t->c_iflag & IGNBRK))
3258 	    && (!(t->c_iflag & PARMRK)
3259 		|| (t->c_iflag & (IGNPAR | IGNBRK)) == (IGNPAR | IGNBRK))
3260 	    && !(t->c_lflag & (ECHO | ICANON | IEXTEN | ISIG | PENDIN))
3261 	    && linesw[tp->t_line]->l_rint == ttyinput)
3262 		tp->t_state |= TS_CAN_BYPASS_L_RINT;
3263 	else
3264 		tp->t_state &= ~TS_CAN_BYPASS_L_RINT;
3265 }
3266 
3267 static void
3268 ttydtrwaitwakeup(void *arg)
3269 {
3270 	struct tty *tp;
3271 
3272 	tp = arg;
3273 	tp->t_state &= ~TS_DTR_WAIT;
3274 	wakeup(&tp->t_dtr_wait);
3275 }
3276 
3277 
3278 void
3279 ttydtrwaitstart(struct tty *tp)
3280 {
3281 
3282 	if (tp->t_dtr_wait == 0)
3283 		return;
3284 	if (tp->t_state & TS_DTR_WAIT)
3285 		return;
3286 	timeout(ttydtrwaitwakeup, tp, tp->t_dtr_wait);
3287 	tp->t_state |= TS_DTR_WAIT;
3288 }
3289 
3290 int
3291 ttydtrwaitsleep(struct tty *tp)
3292 {
3293 	int error;
3294 
3295 	error = 0;
3296 	while (error == 0) {
3297 		if (tp->t_state & TS_GONE)
3298 			error = ENXIO;
3299 		else if (!(tp->t_state & TS_DTR_WAIT))
3300 			break;
3301 		else
3302 			error = tsleep(&tp->t_dtr_wait, TTIPRI | PCATCH,
3303 			    "dtrwait", 0);
3304 	}
3305 	return (error);
3306 }
3307 
3308 static int
3309 ttysopen(struct cdev *dev, int flag, int mode, struct thread *td)
3310 {
3311 	struct tty *tp;
3312 
3313 	tp = dev->si_tty;
3314 	KASSERT(tp != NULL,
3315 	    ("ttysopen(): no tty pointer on device (%s)", devtoname(dev)));
3316 	if (tp->t_state & TS_GONE)
3317 		return (ENODEV);
3318 	return (0);
3319 }
3320 
3321 static int
3322 ttysclose(struct cdev *dev, int flag, int mode, struct thread *td)
3323 {
3324 
3325 	return (0);
3326 }
3327 
3328 static int
3329 ttysrdwr(struct cdev *dev, struct uio *uio, int flag)
3330 {
3331 
3332 	return (ENODEV);
3333 }
3334 
3335 static int
3336 ttysioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
3337 {
3338 	struct tty	*tp;
3339 	int		error;
3340 	struct termios	*ct;
3341 
3342 	tp = dev->si_tty;
3343 	KASSERT(tp != NULL,
3344 	    ("ttysopen(): no tty pointer on device (%s)", devtoname(dev)));
3345 	if (tp->t_state & TS_GONE)
3346 		return (ENODEV);
3347 	ct = dev->si_drv2;
3348 	switch (cmd) {
3349 	case TIOCSETA:
3350 		error = suser(td);
3351 		if (error != 0)
3352 			return (error);
3353 		*ct = *(struct termios *)data;
3354 		return (0);
3355 	case TIOCGETA:
3356 		*(struct termios *)data = *ct;
3357 		return (0);
3358 	case TIOCGETD:
3359 		*(int *)data = TTYDISC;
3360 		return (0);
3361 	case TIOCGWINSZ:
3362 		bzero(data, sizeof(struct winsize));
3363 		return (0);
3364 	default:
3365 		if (tp->t_cioctl != NULL)
3366 			return(tp->t_cioctl(dev, cmd, data, flag, td));
3367 		return (ENOTTY);
3368 	}
3369 }
3370 
3371 /*
3372  * Initialize a tty to sane modes.
3373  */
3374 void
3375 ttyinitmode(struct tty *tp, int echo, int speed)
3376 {
3377 
3378 	if (speed == 0)
3379 		speed = TTYDEF_SPEED;
3380 	tp->t_init_in.c_iflag = TTYDEF_IFLAG;
3381 	tp->t_init_in.c_oflag = TTYDEF_OFLAG;
3382 	tp->t_init_in.c_cflag = TTYDEF_CFLAG;
3383 	if (echo)
3384 		tp->t_init_in.c_lflag = TTYDEF_LFLAG_ECHO;
3385 	else
3386 		tp->t_init_in.c_lflag = TTYDEF_LFLAG_NOECHO;
3387 
3388 	tp->t_init_in.c_ispeed = tp->t_init_in.c_ospeed = speed;
3389 	termioschars(&tp->t_init_in);
3390 	tp->t_init_out = tp->t_init_in;
3391 	tp->t_termios = tp->t_init_in;
3392 }
3393 
3394 /*
3395  * Use more "normal" termios paramters for consoles.
3396  */
3397 void
3398 ttyconsolemode(struct tty *tp, int speed)
3399 {
3400 
3401 	if (speed == 0)
3402 		speed = TTYDEF_SPEED;
3403 	ttyinitmode(tp, 1, speed);
3404 	tp->t_init_in.c_cflag |= CLOCAL;
3405 	tp->t_lock_out.c_cflag = tp->t_lock_in.c_cflag = CLOCAL;
3406 	tp->t_lock_out.c_ispeed = tp->t_lock_out.c_ospeed =
3407 	tp->t_lock_in.c_ispeed = tp->t_lock_in.c_ospeed = speed;
3408 	tp->t_init_out = tp->t_init_in;
3409 	tp->t_termios = tp->t_init_in;
3410 	ttsetwater(tp);
3411 }
3412 
3413 /*
3414  * Record the relationship between the serial ports notion of modem control
3415  * signals and the one used in certain ioctls in a way the compiler can enforce
3416  * XXX: We should define TIOCM_* in terms of SER_ if we can limit the
3417  * XXX: consequences of the #include work that would take.
3418  */
3419 CTASSERT(SER_DTR == TIOCM_DTR / 2);
3420 CTASSERT(SER_RTS == TIOCM_RTS / 2);
3421 CTASSERT(SER_STX == TIOCM_ST / 2);
3422 CTASSERT(SER_SRX == TIOCM_SR / 2);
3423 CTASSERT(SER_CTS == TIOCM_CTS / 2);
3424 CTASSERT(SER_DCD == TIOCM_DCD / 2);
3425 CTASSERT(SER_RI == TIOCM_RI / 2);
3426 CTASSERT(SER_DSR == TIOCM_DSR / 2);
3427 
3428