xref: /openbsd-src/sys/netinet/tcp_usrreq.c (revision 68dd5bb1859285b71cb62a10bf107b8ad54064d9)
1 /*	$OpenBSD: tcp_usrreq.c,v 1.229 2024/01/19 02:24:07 bluhm Exp $	*/
2 /*	$NetBSD: tcp_usrreq.c,v 1.20 1996/02/13 23:44:16 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1988, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)COPYRIGHT	1.1 (NRL) 17 January 1995
33  *
34  * NRL grants permission for redistribution and use in source and binary
35  * forms, with or without modification, of the software and documentation
36  * created at NRL provided that the following conditions are met:
37  *
38  * 1. Redistributions of source code must retain the above copyright
39  *    notice, this list of conditions and the following disclaimer.
40  * 2. Redistributions in binary form must reproduce the above copyright
41  *    notice, this list of conditions and the following disclaimer in the
42  *    documentation and/or other materials provided with the distribution.
43  * 3. All advertising materials mentioning features or use of this software
44  *    must display the following acknowledgements:
45  *	This product includes software developed by the University of
46  *	California, Berkeley and its contributors.
47  *	This product includes software developed at the Information
48  *	Technology Division, US Naval Research Laboratory.
49  * 4. Neither the name of the NRL nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THE SOFTWARE PROVIDED BY NRL IS PROVIDED BY NRL AND CONTRIBUTORS ``AS
54  * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
55  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
56  * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL NRL OR
57  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
58  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
59  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
60  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
61  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
62  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
63  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
64  *
65  * The views and conclusions contained in the software and documentation
66  * are those of the authors and should not be interpreted as representing
67  * official policies, either expressed or implied, of the US Naval
68  * Research Laboratory (NRL).
69  */
70 
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/mbuf.h>
74 #include <sys/socket.h>
75 #include <sys/socketvar.h>
76 #include <sys/protosw.h>
77 #include <sys/stat.h>
78 #include <sys/sysctl.h>
79 #include <sys/domain.h>
80 #include <sys/kernel.h>
81 #include <sys/pool.h>
82 #include <sys/proc.h>
83 
84 #include <net/if.h>
85 #include <net/if_var.h>
86 #include <net/route.h>
87 
88 #include <netinet/in.h>
89 #include <netinet/in_var.h>
90 #include <netinet/ip.h>
91 #include <netinet/in_pcb.h>
92 #include <netinet/ip_var.h>
93 #include <netinet/tcp.h>
94 #include <netinet/tcp_fsm.h>
95 #include <netinet/tcp_seq.h>
96 #include <netinet/tcp_timer.h>
97 #include <netinet/tcp_var.h>
98 #include <netinet/tcp_debug.h>
99 
100 #ifdef INET6
101 #include <netinet6/in6_var.h>
102 #endif
103 
104 #ifndef TCP_SENDSPACE
105 #define	TCP_SENDSPACE	1024*16
106 #endif
107 u_int	tcp_sendspace = TCP_SENDSPACE;
108 #ifndef TCP_RECVSPACE
109 #define	TCP_RECVSPACE	1024*16
110 #endif
111 u_int	tcp_recvspace = TCP_RECVSPACE;
112 u_int	tcp_autorcvbuf_inc = 16 * 1024;
113 
114 const struct pr_usrreqs tcp_usrreqs = {
115 	.pru_attach	= tcp_attach,
116 	.pru_detach	= tcp_detach,
117 	.pru_bind	= tcp_bind,
118 	.pru_listen	= tcp_listen,
119 	.pru_connect	= tcp_connect,
120 	.pru_accept	= tcp_accept,
121 	.pru_disconnect	= tcp_disconnect,
122 	.pru_shutdown	= tcp_shutdown,
123 	.pru_rcvd	= tcp_rcvd,
124 	.pru_send	= tcp_send,
125 	.pru_abort	= tcp_abort,
126 	.pru_sense	= tcp_sense,
127 	.pru_rcvoob	= tcp_rcvoob,
128 	.pru_sendoob	= tcp_sendoob,
129 	.pru_control	= in_control,
130 	.pru_sockaddr	= tcp_sockaddr,
131 	.pru_peeraddr	= tcp_peeraddr,
132 };
133 
134 #ifdef INET6
135 const struct pr_usrreqs tcp6_usrreqs = {
136 	.pru_attach	= tcp_attach,
137 	.pru_detach	= tcp_detach,
138 	.pru_bind	= tcp_bind,
139 	.pru_listen	= tcp_listen,
140 	.pru_connect	= tcp_connect,
141 	.pru_accept	= tcp_accept,
142 	.pru_disconnect	= tcp_disconnect,
143 	.pru_shutdown	= tcp_shutdown,
144 	.pru_rcvd	= tcp_rcvd,
145 	.pru_send	= tcp_send,
146 	.pru_abort	= tcp_abort,
147 	.pru_sense	= tcp_sense,
148 	.pru_rcvoob	= tcp_rcvoob,
149 	.pru_sendoob	= tcp_sendoob,
150 	.pru_control	= in6_control,
151 	.pru_sockaddr	= tcp_sockaddr,
152 	.pru_peeraddr	= tcp_peeraddr,
153 };
154 #endif
155 
156 const struct sysctl_bounded_args tcpctl_vars[] = {
157 	{ TCPCTL_RFC1323, &tcp_do_rfc1323, 0, 1 },
158 	{ TCPCTL_SACK, &tcp_do_sack, 0, 1 },
159 	{ TCPCTL_MSSDFLT, &tcp_mssdflt, TCP_MSS, 65535 },
160 	{ TCPCTL_RSTPPSLIMIT, &tcp_rst_ppslim, 1, 1000 * 1000 },
161 	{ TCPCTL_ACK_ON_PUSH, &tcp_ack_on_push, 0, 1 },
162 #ifdef TCP_ECN
163 	{ TCPCTL_ECN, &tcp_do_ecn, 0, 1 },
164 #endif
165 	{ TCPCTL_SYN_CACHE_LIMIT, &tcp_syn_cache_limit, 1, 1000 * 1000 },
166 	{ TCPCTL_SYN_BUCKET_LIMIT, &tcp_syn_bucket_limit, 1, INT_MAX },
167 	{ TCPCTL_RFC3390, &tcp_do_rfc3390, 0, 2 },
168 	{ TCPCTL_ALWAYS_KEEPALIVE, &tcp_always_keepalive, 0, 1 },
169 	{ TCPCTL_TSO, &tcp_do_tso, 0, 1 },
170 };
171 
172 struct	inpcbtable tcbtable;
173 
174 int	tcp_fill_info(struct tcpcb *, struct socket *, struct mbuf *);
175 int	tcp_ident(void *, size_t *, void *, size_t, int);
176 
177 static inline int tcp_sogetpcb(struct socket *, struct inpcb **,
178 		    struct tcpcb **);
179 
180 static inline int
181 tcp_sogetpcb(struct socket *so, struct inpcb **rinp, struct tcpcb **rtp)
182 {
183 	struct inpcb *inp;
184 	struct tcpcb *tp;
185 
186 	/*
187 	 * When a TCP is attached to a socket, then there will be
188 	 * a (struct inpcb) pointed at by the socket, and this
189 	 * structure will point at a subsidiary (struct tcpcb).
190 	 */
191 	if ((inp = sotoinpcb(so)) == NULL || (tp = intotcpcb(inp)) == NULL) {
192 		if (so->so_error)
193 			return so->so_error;
194 		return EINVAL;
195 	}
196 
197 	*rinp = inp;
198 	*rtp = tp;
199 
200 	return 0;
201 }
202 
203 /*
204  * Export internal TCP state information via a struct tcp_info without
205  * leaking any sensitive information. Sequence numbers are reported
206  * relative to the initial sequence number.
207  */
208 int
209 tcp_fill_info(struct tcpcb *tp, struct socket *so, struct mbuf *m)
210 {
211 	struct proc *p = curproc;
212 	struct tcp_info *ti;
213 	u_int t = 1000;		/* msec => usec */
214 	uint64_t now;
215 
216 	if (sizeof(*ti) > MLEN) {
217 		MCLGETL(m, M_WAITOK, sizeof(*ti));
218 		if (!ISSET(m->m_flags, M_EXT))
219 			return ENOMEM;
220 	}
221 	ti = mtod(m, struct tcp_info *);
222 	m->m_len = sizeof(*ti);
223 	memset(ti, 0, sizeof(*ti));
224 	now = tcp_now();
225 
226 	ti->tcpi_state = tp->t_state;
227 	if ((tp->t_flags & TF_REQ_TSTMP) && (tp->t_flags & TF_RCVD_TSTMP))
228 		ti->tcpi_options |= TCPI_OPT_TIMESTAMPS;
229 	if (tp->t_flags & TF_SACK_PERMIT)
230 		ti->tcpi_options |= TCPI_OPT_SACK;
231 	if ((tp->t_flags & TF_REQ_SCALE) && (tp->t_flags & TF_RCVD_SCALE)) {
232 		ti->tcpi_options |= TCPI_OPT_WSCALE;
233 		ti->tcpi_snd_wscale = tp->snd_scale;
234 		ti->tcpi_rcv_wscale = tp->rcv_scale;
235 	}
236 #ifdef TCP_ECN
237 	if (tp->t_flags & TF_ECN_PERMIT)
238 		ti->tcpi_options |= TCPI_OPT_ECN;
239 #endif
240 
241 	ti->tcpi_rto = tp->t_rxtcur * t;
242 	ti->tcpi_snd_mss = tp->t_maxseg;
243 	ti->tcpi_rcv_mss = tp->t_peermss;
244 
245 	ti->tcpi_last_data_sent = (now - tp->t_sndtime) * t;
246 	ti->tcpi_last_ack_sent = (now - tp->t_sndacktime) * t;
247 	ti->tcpi_last_data_recv = (now - tp->t_rcvtime) * t;
248 	ti->tcpi_last_ack_recv = (now - tp->t_rcvacktime) * t;
249 
250 	ti->tcpi_rtt = ((uint64_t)tp->t_srtt * t) >>
251 	    (TCP_RTT_SHIFT + TCP_RTT_BASE_SHIFT);
252 	ti->tcpi_rttvar = ((uint64_t)tp->t_rttvar * t) >>
253 	    (TCP_RTTVAR_SHIFT + TCP_RTT_BASE_SHIFT);
254 	ti->tcpi_snd_ssthresh = tp->snd_ssthresh;
255 	ti->tcpi_snd_cwnd = tp->snd_cwnd;
256 
257 	ti->tcpi_rcv_space = tp->rcv_wnd;
258 
259 	/*
260 	 * Provide only minimal information for unprivileged processes.
261 	 */
262 	if (suser(p) != 0)
263 		return 0;
264 
265 	/* FreeBSD-specific extension fields for tcp_info.  */
266 	ti->tcpi_snd_wnd = tp->snd_wnd;
267 	ti->tcpi_snd_nxt = tp->snd_nxt - tp->iss;
268 	ti->tcpi_rcv_nxt = tp->rcv_nxt - tp->irs;
269 	/* missing tcpi_toe_tid */
270 	ti->tcpi_snd_rexmitpack = tp->t_sndrexmitpack;
271 	ti->tcpi_rcv_ooopack = tp->t_rcvoopack;
272 	ti->tcpi_snd_zerowin = tp->t_sndzerowin;
273 
274 	/* OpenBSD extensions */
275 	ti->tcpi_rttmin = tp->t_rttmin * t;
276 	ti->tcpi_max_sndwnd = tp->max_sndwnd;
277 	ti->tcpi_rcv_adv = tp->rcv_adv - tp->irs;
278 	ti->tcpi_rcv_up = tp->rcv_up - tp->irs;
279 	ti->tcpi_snd_una = tp->snd_una - tp->iss;
280 	ti->tcpi_snd_up = tp->snd_up - tp->iss;
281 	ti->tcpi_snd_wl1 = tp->snd_wl1 - tp->iss;
282 	ti->tcpi_snd_wl2 = tp->snd_wl2 - tp->iss;
283 	ti->tcpi_snd_max = tp->snd_max - tp->iss;
284 
285 	ti->tcpi_ts_recent = tp->ts_recent; /* XXX value from the wire */
286 	ti->tcpi_ts_recent_age = (now - tp->ts_recent_age) * t;
287 	ti->tcpi_rfbuf_cnt = tp->rfbuf_cnt;
288 	ti->tcpi_rfbuf_ts = (now - tp->rfbuf_ts) * t;
289 
290 	ti->tcpi_so_rcv_sb_cc = so->so_rcv.sb_cc;
291 	ti->tcpi_so_rcv_sb_hiwat = so->so_rcv.sb_hiwat;
292 	ti->tcpi_so_rcv_sb_lowat = so->so_rcv.sb_lowat;
293 	ti->tcpi_so_rcv_sb_wat = so->so_rcv.sb_wat;
294 	ti->tcpi_so_snd_sb_cc = so->so_snd.sb_cc;
295 	ti->tcpi_so_snd_sb_hiwat = so->so_snd.sb_hiwat;
296 	ti->tcpi_so_snd_sb_lowat = so->so_snd.sb_lowat;
297 	ti->tcpi_so_snd_sb_wat = so->so_snd.sb_wat;
298 
299 	return 0;
300 }
301 
302 int
303 tcp_ctloutput(int op, struct socket *so, int level, int optname,
304     struct mbuf *m)
305 {
306 	int error = 0;
307 	struct inpcb *inp;
308 	struct tcpcb *tp;
309 	int i;
310 
311 	inp = sotoinpcb(so);
312 	if (inp == NULL)
313 		return (ECONNRESET);
314 	if (level != IPPROTO_TCP) {
315 #ifdef INET6
316 		if (ISSET(inp->inp_flags, INP_IPV6))
317 			error = ip6_ctloutput(op, so, level, optname, m);
318 		else
319 #endif /* INET6 */
320 			error = ip_ctloutput(op, so, level, optname, m);
321 		return (error);
322 	}
323 	tp = intotcpcb(inp);
324 
325 	switch (op) {
326 
327 	case PRCO_SETOPT:
328 		switch (optname) {
329 
330 		case TCP_NODELAY:
331 			if (m == NULL || m->m_len < sizeof (int))
332 				error = EINVAL;
333 			else if (*mtod(m, int *))
334 				tp->t_flags |= TF_NODELAY;
335 			else
336 				tp->t_flags &= ~TF_NODELAY;
337 			break;
338 
339 		case TCP_NOPUSH:
340 			if (m == NULL || m->m_len < sizeof (int))
341 				error = EINVAL;
342 			else if (*mtod(m, int *))
343 				tp->t_flags |= TF_NOPUSH;
344 			else if (tp->t_flags & TF_NOPUSH) {
345 				tp->t_flags &= ~TF_NOPUSH;
346 				if (TCPS_HAVEESTABLISHED(tp->t_state))
347 					error = tcp_output(tp);
348 			}
349 			break;
350 
351 		case TCP_MAXSEG:
352 			if (m == NULL || m->m_len < sizeof (int)) {
353 				error = EINVAL;
354 				break;
355 			}
356 
357 			i = *mtod(m, int *);
358 			if (i > 0 && i <= tp->t_maxseg)
359 				tp->t_maxseg = i;
360 			else
361 				error = EINVAL;
362 			break;
363 
364 		case TCP_SACK_ENABLE:
365 			if (m == NULL || m->m_len < sizeof (int)) {
366 				error = EINVAL;
367 				break;
368 			}
369 
370 			if (TCPS_HAVEESTABLISHED(tp->t_state)) {
371 				error = EPERM;
372 				break;
373 			}
374 
375 			if (tp->t_flags & TF_SIGNATURE) {
376 				error = EPERM;
377 				break;
378 			}
379 
380 			if (*mtod(m, int *))
381 				tp->sack_enable = 1;
382 			else
383 				tp->sack_enable = 0;
384 			break;
385 #ifdef TCP_SIGNATURE
386 		case TCP_MD5SIG:
387 			if (m == NULL || m->m_len < sizeof (int)) {
388 				error = EINVAL;
389 				break;
390 			}
391 
392 			if (TCPS_HAVEESTABLISHED(tp->t_state)) {
393 				error = EPERM;
394 				break;
395 			}
396 
397 			if (*mtod(m, int *)) {
398 				tp->t_flags |= TF_SIGNATURE;
399 				tp->sack_enable = 0;
400 			} else
401 				tp->t_flags &= ~TF_SIGNATURE;
402 			break;
403 #endif /* TCP_SIGNATURE */
404 		default:
405 			error = ENOPROTOOPT;
406 			break;
407 		}
408 		break;
409 
410 	case PRCO_GETOPT:
411 		switch (optname) {
412 		case TCP_NODELAY:
413 			m->m_len = sizeof(int);
414 			*mtod(m, int *) = tp->t_flags & TF_NODELAY;
415 			break;
416 		case TCP_NOPUSH:
417 			m->m_len = sizeof(int);
418 			*mtod(m, int *) = tp->t_flags & TF_NOPUSH;
419 			break;
420 		case TCP_MAXSEG:
421 			m->m_len = sizeof(int);
422 			*mtod(m, int *) = tp->t_maxseg;
423 			break;
424 		case TCP_SACK_ENABLE:
425 			m->m_len = sizeof(int);
426 			*mtod(m, int *) = tp->sack_enable;
427 			break;
428 		case TCP_INFO:
429 			error = tcp_fill_info(tp, so, m);
430 			break;
431 #ifdef TCP_SIGNATURE
432 		case TCP_MD5SIG:
433 			m->m_len = sizeof(int);
434 			*mtod(m, int *) = tp->t_flags & TF_SIGNATURE;
435 			break;
436 #endif
437 		default:
438 			error = ENOPROTOOPT;
439 			break;
440 		}
441 		break;
442 	}
443 	return (error);
444 }
445 
446 /*
447  * Attach TCP protocol to socket, allocating
448  * internet protocol control block, tcp control block,
449  * buffer space, and entering LISTEN state to accept connections.
450  */
451 int
452 tcp_attach(struct socket *so, int proto, int wait)
453 {
454 	struct tcpcb *tp;
455 	struct inpcb *inp;
456 	int error;
457 
458 	if (so->so_pcb)
459 		return EISCONN;
460 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0 ||
461 	    sbcheckreserve(so->so_snd.sb_wat, tcp_sendspace) ||
462 	    sbcheckreserve(so->so_rcv.sb_wat, tcp_recvspace)) {
463 		error = soreserve(so, tcp_sendspace, tcp_recvspace);
464 		if (error)
465 			return (error);
466 	}
467 
468 	NET_ASSERT_LOCKED();
469 	error = in_pcballoc(so, &tcbtable, wait);
470 	if (error)
471 		return (error);
472 	inp = sotoinpcb(so);
473 	tp = tcp_newtcpcb(inp, wait);
474 	if (tp == NULL) {
475 		unsigned int nofd = so->so_state & SS_NOFDREF;	/* XXX */
476 
477 		so->so_state &= ~SS_NOFDREF;	/* don't free the socket yet */
478 		in_pcbdetach(inp);
479 		so->so_state |= nofd;
480 		return (ENOBUFS);
481 	}
482 	tp->t_state = TCPS_CLOSED;
483 #ifdef INET6
484 	/* we disallow IPv4 mapped address completely. */
485 	if (inp->inp_flags & INP_IPV6)
486 		tp->pf = PF_INET6;
487 	else
488 		tp->pf = PF_INET;
489 #else
490 	tp->pf = PF_INET;
491 #endif
492 	if ((so->so_options & SO_LINGER) && so->so_linger == 0)
493 		so->so_linger = TCP_LINGERTIME;
494 
495 	if (so->so_options & SO_DEBUG)
496 		tcp_trace(TA_USER, TCPS_CLOSED, tp, tp, NULL, PRU_ATTACH, 0);
497 	return (0);
498 }
499 
500 int
501 tcp_detach(struct socket *so)
502 {
503 	struct inpcb *inp;
504 	struct tcpcb *otp = NULL, *tp;
505 	int error;
506 	short ostate;
507 
508 	soassertlocked(so);
509 
510 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
511 		return (error);
512 
513 	if (so->so_options & SO_DEBUG) {
514 		otp = tp;
515 		ostate = tp->t_state;
516 	}
517 
518 	/*
519 	 * Detach the TCP protocol from the socket.
520 	 * If the protocol state is non-embryonic, then can't
521 	 * do this directly: have to initiate a PRU_DISCONNECT,
522 	 * which may finish later; embryonic TCB's can just
523 	 * be discarded here.
524 	 */
525 	tp = tcp_dodisconnect(tp);
526 
527 	if (otp)
528 		tcp_trace(TA_USER, ostate, tp, otp, NULL, PRU_DETACH, 0);
529 	return (0);
530 }
531 
532 /*
533  * Give the socket an address.
534  */
535 int
536 tcp_bind(struct socket *so, struct mbuf *nam, struct proc *p)
537 {
538 	struct inpcb *inp;
539 	struct tcpcb *tp;
540 	int error;
541 	short ostate;
542 
543 	soassertlocked(so);
544 
545 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
546 		return (error);
547 
548 	if (so->so_options & SO_DEBUG)
549 		ostate = tp->t_state;
550 
551 	error = in_pcbbind(inp, nam, p);
552 
553 	if (so->so_options & SO_DEBUG)
554 		tcp_trace(TA_USER, ostate, tp, tp, NULL, PRU_BIND, 0);
555 	return (error);
556 }
557 
558 /*
559  * Prepare to accept connections.
560  */
561 int
562 tcp_listen(struct socket *so)
563 {
564 	struct inpcb *inp;
565 	struct tcpcb *tp, *otp = NULL;
566 	int error;
567 	short ostate;
568 
569 	soassertlocked(so);
570 
571 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
572 		return (error);
573 
574 	if (so->so_options & SO_DEBUG) {
575 		otp = tp;
576 		ostate = tp->t_state;
577 	}
578 
579 	if (inp->inp_lport == 0)
580 		if ((error = in_pcbbind(inp, NULL, curproc)))
581 			goto out;
582 
583 	/*
584 	 * If the in_pcbbind() above is called, the tp->pf
585 	 * should still be whatever it was before.
586 	 */
587 	tp->t_state = TCPS_LISTEN;
588 
589 out:
590 	if (otp)
591 		tcp_trace(TA_USER, ostate, tp, otp, NULL, PRU_LISTEN, 0);
592 	return (error);
593 }
594 
595 /*
596  * Initiate connection to peer.
597  * Create a template for use in transmissions on this connection.
598  * Enter SYN_SENT state, and mark socket as connecting.
599  * Start keep-alive timer, and seed output sequence space.
600  * Send initial segment on connection.
601  */
602 int
603 tcp_connect(struct socket *so, struct mbuf *nam)
604 {
605 	struct inpcb *inp;
606 	struct tcpcb *tp, *otp = NULL;
607 	int error;
608 	short ostate;
609 
610 	soassertlocked(so);
611 
612 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
613 		return (error);
614 
615 	if (so->so_options & SO_DEBUG) {
616 		otp = tp;
617 		ostate = tp->t_state;
618 	}
619 
620 #ifdef INET6
621 	if (inp->inp_flags & INP_IPV6) {
622 		struct sockaddr_in6 *sin6;
623 
624 		if ((error = in6_nam2sin6(nam, &sin6)))
625 			goto out;
626 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr) ||
627 		    IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) {
628 			error = EINVAL;
629 			goto out;
630 		}
631 	} else
632 #endif /* INET6 */
633 	{
634 		struct sockaddr_in *sin;
635 
636 		if ((error = in_nam2sin(nam, &sin)))
637 			goto out;
638 		if ((sin->sin_addr.s_addr == INADDR_ANY) ||
639 		    (sin->sin_addr.s_addr == INADDR_BROADCAST) ||
640 		    IN_MULTICAST(sin->sin_addr.s_addr) ||
641 		    in_broadcast(sin->sin_addr, inp->inp_rtableid)) {
642 			error = EINVAL;
643 			goto out;
644 		}
645 	}
646 	error = in_pcbconnect(inp, nam);
647 	if (error)
648 		goto out;
649 
650 	tp->t_template = tcp_template(tp);
651 	if (tp->t_template == 0) {
652 		in_pcbunset_faddr(inp);
653 		in_pcbdisconnect(inp);
654 		error = ENOBUFS;
655 		goto out;
656 	}
657 
658 	so->so_state |= SS_CONNECTOUT;
659 
660 	/* Compute window scaling to request.  */
661 	tcp_rscale(tp, sb_max);
662 
663 	soisconnecting(so);
664 	tcpstat_inc(tcps_connattempt);
665 	tp->t_state = TCPS_SYN_SENT;
666 	TCP_TIMER_ARM(tp, TCPT_KEEP, tcptv_keep_init);
667 	tcp_set_iss_tsm(tp);
668 	tcp_sendseqinit(tp);
669 	tp->snd_last = tp->snd_una;
670 	error = tcp_output(tp);
671 
672 out:
673 	if (otp)
674 		tcp_trace(TA_USER, ostate, tp, otp, NULL, PRU_CONNECT, 0);
675 	return (error);
676 }
677 
678 /*
679  * Accept a connection.  Essentially all the work is done at higher
680  * levels; just return the address of the peer, storing through addr.
681  */
682 int
683 tcp_accept(struct socket *so, struct mbuf *nam)
684 {
685 	struct inpcb *inp;
686 	struct tcpcb *tp;
687 	int error;
688 
689 	soassertlocked(so);
690 
691 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
692 		return (error);
693 
694 	in_setpeeraddr(inp, nam);
695 
696 	if (so->so_options & SO_DEBUG)
697 		tcp_trace(TA_USER, tp->t_state, tp, tp, NULL, PRU_ACCEPT, 0);
698 	return (0);
699 }
700 
701 /*
702  * Initiate disconnect from peer.
703  * If connection never passed embryonic stage, just drop;
704  * else if don't need to let data drain, then can just drop anyways,
705  * else have to begin TCP shutdown process: mark socket disconnecting,
706  * drain unread data, state switch to reflect user close, and
707  * send segment (e.g. FIN) to peer.  Socket will be really disconnected
708  * when peer sends FIN and acks ours.
709  *
710  * SHOULD IMPLEMENT LATER PRU_CONNECT VIA REALLOC TCPCB.
711  */
712 int
713 tcp_disconnect(struct socket *so)
714 {
715 	struct inpcb *inp;
716 	struct tcpcb *tp, *otp = NULL;
717 	int error;
718 	short ostate;
719 
720 	soassertlocked(so);
721 
722 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
723 		return (error);
724 
725 	if (so->so_options & SO_DEBUG) {
726 		otp = tp;
727 		ostate = tp->t_state;
728 	}
729 
730 	tp = tcp_dodisconnect(tp);
731 
732 	if (otp)
733 		tcp_trace(TA_USER, ostate, tp, otp, NULL, PRU_DISCONNECT, 0);
734 	return (0);
735 }
736 
737 /*
738  * Mark the connection as being incapable of further output.
739  */
740 int
741 tcp_shutdown(struct socket *so)
742 {
743 	struct inpcb *inp;
744 	struct tcpcb *tp, *otp = NULL;
745 	int error;
746 	short ostate;
747 
748 	soassertlocked(so);
749 
750 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
751 		return (error);
752 
753 	if (so->so_options & SO_DEBUG) {
754 		otp = tp;
755 		ostate = tp->t_state;
756 	}
757 
758 	if (so->so_snd.sb_state & SS_CANTSENDMORE)
759 		goto out;
760 
761 	socantsendmore(so);
762 	tp = tcp_usrclosed(tp);
763 	if (tp)
764 		error = tcp_output(tp);
765 
766 out:
767 	if (otp)
768 		tcp_trace(TA_USER, ostate, tp, otp, NULL, PRU_SHUTDOWN, 0);
769 	return (error);
770 }
771 
772 /*
773  * After a receive, possibly send window update to peer.
774  */
775 void
776 tcp_rcvd(struct socket *so)
777 {
778 	struct inpcb *inp;
779 	struct tcpcb *tp;
780 	short ostate;
781 
782 	soassertlocked(so);
783 
784 	if (tcp_sogetpcb(so, &inp, &tp))
785 		return;
786 
787 	if (so->so_options & SO_DEBUG)
788 		ostate = tp->t_state;
789 
790 	/*
791 	 * soreceive() calls this function when a user receives
792 	 * ancillary data on a listening socket. We don't call
793 	 * tcp_output in such a case, since there is no header
794 	 * template for a listening socket and hence the kernel
795 	 * will panic.
796 	 */
797 	if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) != 0)
798 		(void) tcp_output(tp);
799 
800 	if (so->so_options & SO_DEBUG)
801 		tcp_trace(TA_USER, ostate, tp, tp, NULL, PRU_RCVD, 0);
802 }
803 
804 /*
805  * Do a send by putting data in output queue and updating urgent
806  * marker if URG set.  Possibly send more data.
807  */
808 int
809 tcp_send(struct socket *so, struct mbuf *m, struct mbuf *nam,
810     struct mbuf *control)
811 {
812 	struct inpcb *inp;
813 	struct tcpcb *tp;
814 	int error;
815 	short ostate;
816 
817 	soassertlocked(so);
818 
819 	if (control && control->m_len) {
820 		error = EINVAL;
821 		goto out;
822 	}
823 
824 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
825 		goto out;
826 
827 	if (so->so_options & SO_DEBUG)
828 		ostate = tp->t_state;
829 
830 	sbappendstream(so, &so->so_snd, m);
831 	m = NULL;
832 
833 	error = tcp_output(tp);
834 
835 	if (so->so_options & SO_DEBUG)
836 		tcp_trace(TA_USER, ostate, tp, tp, NULL, PRU_SEND, 0);
837 
838 out:
839 	m_freem(control);
840 	m_freem(m);
841 
842 	return (error);
843 }
844 
845 /*
846  * Abort the TCP.
847  */
848 void
849 tcp_abort(struct socket *so)
850 {
851 	struct inpcb *inp;
852 	struct tcpcb *tp, *otp = NULL;
853 	short ostate;
854 
855 	soassertlocked(so);
856 
857 	if (tcp_sogetpcb(so, &inp, &tp))
858 		return;
859 
860 	if (so->so_options & SO_DEBUG) {
861 		otp = tp;
862 		ostate = tp->t_state;
863 	}
864 
865 	tp = tcp_drop(tp, ECONNABORTED);
866 
867 	if (otp)
868 		tcp_trace(TA_USER, ostate, tp, otp, NULL, PRU_ABORT, 0);
869 }
870 
871 int
872 tcp_sense(struct socket *so, struct stat *ub)
873 {
874 	struct inpcb *inp;
875 	struct tcpcb *tp;
876 	int error;
877 
878 	soassertlocked(so);
879 
880 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
881 		return (error);
882 
883 	ub->st_blksize = so->so_snd.sb_hiwat;
884 
885 	if (so->so_options & SO_DEBUG)
886 		tcp_trace(TA_USER, tp->t_state, tp, tp, NULL, PRU_SENSE, 0);
887 	return (0);
888 }
889 
890 int
891 tcp_rcvoob(struct socket *so, struct mbuf *m, int flags)
892 {
893 	struct inpcb *inp;
894 	struct tcpcb *tp;
895 	int error;
896 
897 	soassertlocked(so);
898 
899 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
900 		return (error);
901 
902 	if ((so->so_oobmark == 0 &&
903 	    (so->so_rcv.sb_state & SS_RCVATMARK) == 0) ||
904 	    so->so_options & SO_OOBINLINE ||
905 	    tp->t_oobflags & TCPOOB_HADDATA) {
906 		error = EINVAL;
907 		goto out;
908 	}
909 	if ((tp->t_oobflags & TCPOOB_HAVEDATA) == 0) {
910 		error = EWOULDBLOCK;
911 		goto out;
912 	}
913 	m->m_len = 1;
914 	*mtod(m, caddr_t) = tp->t_iobc;
915 	if ((flags & MSG_PEEK) == 0)
916 		tp->t_oobflags ^= (TCPOOB_HAVEDATA | TCPOOB_HADDATA);
917 out:
918 	if (so->so_options & SO_DEBUG)
919 		tcp_trace(TA_USER, tp->t_state, tp, tp, NULL, PRU_RCVOOB, 0);
920 	return (error);
921 }
922 
923 int
924 tcp_sendoob(struct socket *so, struct mbuf *m, struct mbuf *nam,
925     struct mbuf *control)
926 {
927 	struct inpcb *inp;
928 	struct tcpcb *tp;
929 	int error;
930 	short ostate;
931 
932 	soassertlocked(so);
933 
934 	if (control && control->m_len) {
935 		error = EINVAL;
936 		goto release;
937 	}
938 
939 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
940 		goto release;
941 
942 	if (so->so_options & SO_DEBUG)
943 		ostate = tp->t_state;
944 
945 	if (sbspace(so, &so->so_snd) < -512) {
946 		error = ENOBUFS;
947 		goto out;
948 	}
949 
950 	/*
951 	 * According to RFC961 (Assigned Protocols),
952 	 * the urgent pointer points to the last octet
953 	 * of urgent data.  We continue, however,
954 	 * to consider it to indicate the first octet
955 	 * of data past the urgent section.
956 	 * Otherwise, snd_up should be one lower.
957 	 */
958 	sbappendstream(so, &so->so_snd, m);
959 	m = NULL;
960 	tp->snd_up = tp->snd_una + so->so_snd.sb_cc;
961 	tp->t_force = 1;
962 	error = tcp_output(tp);
963 	tp->t_force = 0;
964 
965 out:
966 	if (so->so_options & SO_DEBUG)
967 		tcp_trace(TA_USER, ostate, tp, tp, NULL, PRU_SENDOOB, 0);
968 
969 release:
970 	m_freem(control);
971 	m_freem(m);
972 
973 	return (error);
974 }
975 
976 int
977 tcp_sockaddr(struct socket *so, struct mbuf *nam)
978 {
979 	struct inpcb *inp;
980 	struct tcpcb *tp;
981 	int error;
982 
983 	soassertlocked(so);
984 
985 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
986 		return (error);
987 
988 	in_setsockaddr(inp, nam);
989 
990 	if (so->so_options & SO_DEBUG)
991 		tcp_trace(TA_USER, tp->t_state, tp, tp, NULL,
992 		    PRU_SOCKADDR, 0);
993 	return (0);
994 }
995 
996 int
997 tcp_peeraddr(struct socket *so, struct mbuf *nam)
998 {
999 	struct inpcb *inp;
1000 	struct tcpcb *tp;
1001 	int error;
1002 
1003 	soassertlocked(so);
1004 
1005 	if ((error = tcp_sogetpcb(so, &inp, &tp)))
1006 		return (error);
1007 
1008 	in_setpeeraddr(inp, nam);
1009 
1010 	if (so->so_options & SO_DEBUG)
1011 		tcp_trace(TA_USER, tp->t_state, tp, tp, NULL, PRU_PEERADDR, 0);
1012 	return (0);
1013 }
1014 
1015 /*
1016  * Initiate (or continue) disconnect.
1017  * If embryonic state, just send reset (once).
1018  * If in ``let data drain'' option and linger null, just drop.
1019  * Otherwise (hard), mark socket disconnecting and drop
1020  * current input data; switch states based on user close, and
1021  * send segment to peer (with FIN).
1022  */
1023 struct tcpcb *
1024 tcp_dodisconnect(struct tcpcb *tp)
1025 {
1026 	struct socket *so = tp->t_inpcb->inp_socket;
1027 
1028 	if (TCPS_HAVEESTABLISHED(tp->t_state) == 0)
1029 		tp = tcp_close(tp);
1030 	else if ((so->so_options & SO_LINGER) && so->so_linger == 0)
1031 		tp = tcp_drop(tp, 0);
1032 	else {
1033 		soisdisconnecting(so);
1034 		sbflush(so, &so->so_rcv);
1035 		tp = tcp_usrclosed(tp);
1036 		if (tp)
1037 			(void) tcp_output(tp);
1038 	}
1039 	return (tp);
1040 }
1041 
1042 /*
1043  * User issued close, and wish to trail through shutdown states:
1044  * if never received SYN, just forget it.  If got a SYN from peer,
1045  * but haven't sent FIN, then go to FIN_WAIT_1 state to send peer a FIN.
1046  * If already got a FIN from peer, then almost done; go to LAST_ACK
1047  * state.  In all other cases, have already sent FIN to peer (e.g.
1048  * after PRU_SHUTDOWN), and just have to play tedious game waiting
1049  * for peer to send FIN or not respond to keep-alives, etc.
1050  * We can let the user exit from the close as soon as the FIN is acked.
1051  */
1052 struct tcpcb *
1053 tcp_usrclosed(struct tcpcb *tp)
1054 {
1055 
1056 	switch (tp->t_state) {
1057 
1058 	case TCPS_CLOSED:
1059 	case TCPS_LISTEN:
1060 	case TCPS_SYN_SENT:
1061 		tp->t_state = TCPS_CLOSED;
1062 		tp = tcp_close(tp);
1063 		break;
1064 
1065 	case TCPS_SYN_RECEIVED:
1066 	case TCPS_ESTABLISHED:
1067 		tp->t_state = TCPS_FIN_WAIT_1;
1068 		break;
1069 
1070 	case TCPS_CLOSE_WAIT:
1071 		tp->t_state = TCPS_LAST_ACK;
1072 		break;
1073 	}
1074 	if (tp && tp->t_state >= TCPS_FIN_WAIT_2) {
1075 		soisdisconnected(tp->t_inpcb->inp_socket);
1076 		/*
1077 		 * If we are in FIN_WAIT_2, we arrived here because the
1078 		 * application did a shutdown of the send side.  Like the
1079 		 * case of a transition from FIN_WAIT_1 to FIN_WAIT_2 after
1080 		 * a full close, we start a timer to make sure sockets are
1081 		 * not left in FIN_WAIT_2 forever.
1082 		 */
1083 		if (tp->t_state == TCPS_FIN_WAIT_2)
1084 			TCP_TIMER_ARM(tp, TCPT_2MSL, tcp_maxidle);
1085 	}
1086 	return (tp);
1087 }
1088 
1089 /*
1090  * Look up a socket for ident or tcpdrop, ...
1091  */
1092 int
1093 tcp_ident(void *oldp, size_t *oldlenp, void *newp, size_t newlen, int dodrop)
1094 {
1095 	int error = 0;
1096 	struct tcp_ident_mapping tir;
1097 	struct inpcb *inp;
1098 	struct tcpcb *tp = NULL;
1099 	struct sockaddr_in *fin, *lin;
1100 #ifdef INET6
1101 	struct sockaddr_in6 *fin6, *lin6;
1102 	struct in6_addr f6, l6;
1103 #endif
1104 
1105 	NET_ASSERT_LOCKED();
1106 
1107 	if (dodrop) {
1108 		if (oldp != NULL || *oldlenp != 0)
1109 			return (EINVAL);
1110 		if (newp == NULL)
1111 			return (EPERM);
1112 		if (newlen < sizeof(tir))
1113 			return (ENOMEM);
1114 		if ((error = copyin(newp, &tir, sizeof (tir))) != 0 )
1115 			return (error);
1116 	} else {
1117 		if (oldp == NULL)
1118 			return (EINVAL);
1119 		if (*oldlenp < sizeof(tir))
1120 			return (ENOMEM);
1121 		if (newp != NULL || newlen != 0)
1122 			return (EINVAL);
1123 		if ((error = copyin(oldp, &tir, sizeof (tir))) != 0 )
1124 			return (error);
1125 	}
1126 	switch (tir.faddr.ss_family) {
1127 #ifdef INET6
1128 	case AF_INET6:
1129 		fin6 = (struct sockaddr_in6 *)&tir.faddr;
1130 		error = in6_embedscope(&f6, fin6, NULL, NULL);
1131 		if (error)
1132 			return EINVAL;	/*?*/
1133 		lin6 = (struct sockaddr_in6 *)&tir.laddr;
1134 		error = in6_embedscope(&l6, lin6, NULL, NULL);
1135 		if (error)
1136 			return EINVAL;	/*?*/
1137 		break;
1138 #endif
1139 	case AF_INET:
1140 		fin = (struct sockaddr_in *)&tir.faddr;
1141 		lin = (struct sockaddr_in *)&tir.laddr;
1142 		break;
1143 	default:
1144 		return (EINVAL);
1145 	}
1146 
1147 	switch (tir.faddr.ss_family) {
1148 #ifdef INET6
1149 	case AF_INET6:
1150 		inp = in6_pcblookup(&tcbtable, &f6,
1151 		    fin6->sin6_port, &l6, lin6->sin6_port, tir.rdomain);
1152 		break;
1153 #endif
1154 	case AF_INET:
1155 		inp = in_pcblookup(&tcbtable, fin->sin_addr,
1156 		    fin->sin_port, lin->sin_addr, lin->sin_port, tir.rdomain);
1157 		break;
1158 	default:
1159 		unhandled_af(tir.faddr.ss_family);
1160 	}
1161 
1162 	if (dodrop) {
1163 		if (inp && (tp = intotcpcb(inp)) &&
1164 		    ((inp->inp_socket->so_options & SO_ACCEPTCONN) == 0))
1165 			tp = tcp_drop(tp, ECONNABORTED);
1166 		else
1167 			error = ESRCH;
1168 		in_pcbunref(inp);
1169 		return (error);
1170 	}
1171 
1172 	if (inp == NULL) {
1173 		tcpstat_inc(tcps_pcbhashmiss);
1174 		switch (tir.faddr.ss_family) {
1175 #ifdef INET6
1176 		case AF_INET6:
1177 			inp = in6_pcblookup_listen(&tcbtable,
1178 			    &l6, lin6->sin6_port, NULL, tir.rdomain);
1179 			break;
1180 #endif
1181 		case AF_INET:
1182 			inp = in_pcblookup_listen(&tcbtable,
1183 			    lin->sin_addr, lin->sin_port, NULL, tir.rdomain);
1184 			break;
1185 		}
1186 	}
1187 
1188 	if (inp != NULL && (inp->inp_socket->so_state & SS_CONNECTOUT)) {
1189 		tir.ruid = inp->inp_socket->so_ruid;
1190 		tir.euid = inp->inp_socket->so_euid;
1191 	} else {
1192 		tir.ruid = -1;
1193 		tir.euid = -1;
1194 	}
1195 
1196 	*oldlenp = sizeof (tir);
1197 	error = copyout((void *)&tir, oldp, sizeof (tir));
1198 	in_pcbunref(inp);
1199 	return (error);
1200 }
1201 
1202 int
1203 tcp_sysctl_tcpstat(void *oldp, size_t *oldlenp, void *newp)
1204 {
1205 	uint64_t counters[tcps_ncounters];
1206 	struct tcpstat tcpstat;
1207 	struct syn_cache_set *set;
1208 	int i = 0;
1209 
1210 #define ASSIGN(field)	do { tcpstat.field = counters[i++]; } while (0)
1211 
1212 	memset(&tcpstat, 0, sizeof tcpstat);
1213 	counters_read(tcpcounters, counters, nitems(counters), NULL);
1214 	ASSIGN(tcps_connattempt);
1215 	ASSIGN(tcps_accepts);
1216 	ASSIGN(tcps_connects);
1217 	ASSIGN(tcps_drops);
1218 	ASSIGN(tcps_conndrops);
1219 	ASSIGN(tcps_closed);
1220 	ASSIGN(tcps_segstimed);
1221 	ASSIGN(tcps_rttupdated);
1222 	ASSIGN(tcps_delack);
1223 	ASSIGN(tcps_timeoutdrop);
1224 	ASSIGN(tcps_rexmttimeo);
1225 	ASSIGN(tcps_persisttimeo);
1226 	ASSIGN(tcps_persistdrop);
1227 	ASSIGN(tcps_keeptimeo);
1228 	ASSIGN(tcps_keepprobe);
1229 	ASSIGN(tcps_keepdrops);
1230 	ASSIGN(tcps_sndtotal);
1231 	ASSIGN(tcps_sndpack);
1232 	ASSIGN(tcps_sndbyte);
1233 	ASSIGN(tcps_sndrexmitpack);
1234 	ASSIGN(tcps_sndrexmitbyte);
1235 	ASSIGN(tcps_sndrexmitfast);
1236 	ASSIGN(tcps_sndacks);
1237 	ASSIGN(tcps_sndprobe);
1238 	ASSIGN(tcps_sndurg);
1239 	ASSIGN(tcps_sndwinup);
1240 	ASSIGN(tcps_sndctrl);
1241 	ASSIGN(tcps_rcvtotal);
1242 	ASSIGN(tcps_rcvpack);
1243 	ASSIGN(tcps_rcvbyte);
1244 	ASSIGN(tcps_rcvbadsum);
1245 	ASSIGN(tcps_rcvbadoff);
1246 	ASSIGN(tcps_rcvmemdrop);
1247 	ASSIGN(tcps_rcvnosec);
1248 	ASSIGN(tcps_rcvshort);
1249 	ASSIGN(tcps_rcvduppack);
1250 	ASSIGN(tcps_rcvdupbyte);
1251 	ASSIGN(tcps_rcvpartduppack);
1252 	ASSIGN(tcps_rcvpartdupbyte);
1253 	ASSIGN(tcps_rcvoopack);
1254 	ASSIGN(tcps_rcvoobyte);
1255 	ASSIGN(tcps_rcvpackafterwin);
1256 	ASSIGN(tcps_rcvbyteafterwin);
1257 	ASSIGN(tcps_rcvafterclose);
1258 	ASSIGN(tcps_rcvwinprobe);
1259 	ASSIGN(tcps_rcvdupack);
1260 	ASSIGN(tcps_rcvacktoomuch);
1261 	ASSIGN(tcps_rcvacktooold);
1262 	ASSIGN(tcps_rcvackpack);
1263 	ASSIGN(tcps_rcvackbyte);
1264 	ASSIGN(tcps_rcvwinupd);
1265 	ASSIGN(tcps_pawsdrop);
1266 	ASSIGN(tcps_predack);
1267 	ASSIGN(tcps_preddat);
1268 	ASSIGN(tcps_pcbhashmiss);
1269 	ASSIGN(tcps_noport);
1270 	ASSIGN(tcps_badsyn);
1271 	ASSIGN(tcps_dropsyn);
1272 	ASSIGN(tcps_rcvbadsig);
1273 	ASSIGN(tcps_rcvgoodsig);
1274 	ASSIGN(tcps_inswcsum);
1275 	ASSIGN(tcps_outswcsum);
1276 	ASSIGN(tcps_ecn_accepts);
1277 	ASSIGN(tcps_ecn_rcvece);
1278 	ASSIGN(tcps_ecn_rcvcwr);
1279 	ASSIGN(tcps_ecn_rcvce);
1280 	ASSIGN(tcps_ecn_sndect);
1281 	ASSIGN(tcps_ecn_sndece);
1282 	ASSIGN(tcps_ecn_sndcwr);
1283 	ASSIGN(tcps_cwr_ecn);
1284 	ASSIGN(tcps_cwr_frecovery);
1285 	ASSIGN(tcps_cwr_timeout);
1286 	ASSIGN(tcps_sc_added);
1287 	ASSIGN(tcps_sc_completed);
1288 	ASSIGN(tcps_sc_timed_out);
1289 	ASSIGN(tcps_sc_overflowed);
1290 	ASSIGN(tcps_sc_reset);
1291 	ASSIGN(tcps_sc_unreach);
1292 	ASSIGN(tcps_sc_bucketoverflow);
1293 	ASSIGN(tcps_sc_aborted);
1294 	ASSIGN(tcps_sc_dupesyn);
1295 	ASSIGN(tcps_sc_dropped);
1296 	ASSIGN(tcps_sc_collisions);
1297 	ASSIGN(tcps_sc_retransmitted);
1298 	ASSIGN(tcps_sc_seedrandom);
1299 	ASSIGN(tcps_sc_hash_size);
1300 	ASSIGN(tcps_sc_entry_count);
1301 	ASSIGN(tcps_sc_entry_limit);
1302 	ASSIGN(tcps_sc_bucket_maxlen);
1303 	ASSIGN(tcps_sc_bucket_limit);
1304 	ASSIGN(tcps_sc_uses_left);
1305 	ASSIGN(tcps_conndrained);
1306 	ASSIGN(tcps_sack_recovery_episode);
1307 	ASSIGN(tcps_sack_rexmits);
1308 	ASSIGN(tcps_sack_rexmit_bytes);
1309 	ASSIGN(tcps_sack_rcv_opts);
1310 	ASSIGN(tcps_sack_snd_opts);
1311 	ASSIGN(tcps_sack_drop_opts);
1312 	ASSIGN(tcps_outswtso);
1313 	ASSIGN(tcps_outhwtso);
1314 	ASSIGN(tcps_outpkttso);
1315 	ASSIGN(tcps_outbadtso);
1316 	ASSIGN(tcps_inswlro);
1317 	ASSIGN(tcps_inhwlro);
1318 	ASSIGN(tcps_inpktlro);
1319 	ASSIGN(tcps_inbadlro);
1320 
1321 #undef ASSIGN
1322 
1323 	mtx_enter(&syn_cache_mtx);
1324 	set = &tcp_syn_cache[tcp_syn_cache_active];
1325 	tcpstat.tcps_sc_hash_size = set->scs_size;
1326 	tcpstat.tcps_sc_entry_count = set->scs_count;
1327 	tcpstat.tcps_sc_entry_limit = tcp_syn_cache_limit;
1328 	tcpstat.tcps_sc_bucket_maxlen = 0;
1329 	for (i = 0; i < set->scs_size; i++) {
1330 		if (tcpstat.tcps_sc_bucket_maxlen <
1331 		    set->scs_buckethead[i].sch_length)
1332 			tcpstat.tcps_sc_bucket_maxlen =
1333 				set->scs_buckethead[i].sch_length;
1334 	}
1335 	tcpstat.tcps_sc_bucket_limit = tcp_syn_bucket_limit;
1336 	tcpstat.tcps_sc_uses_left = set->scs_use;
1337 	mtx_leave(&syn_cache_mtx);
1338 
1339 	return (sysctl_rdstruct(oldp, oldlenp, newp,
1340 	    &tcpstat, sizeof(tcpstat)));
1341 }
1342 
1343 /*
1344  * Sysctl for tcp variables.
1345  */
1346 int
1347 tcp_sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
1348     size_t newlen)
1349 {
1350 	int error, nval;
1351 
1352 	/* All sysctl names at this level are terminal. */
1353 	if (namelen != 1)
1354 		return (ENOTDIR);
1355 
1356 	switch (name[0]) {
1357 	case TCPCTL_KEEPINITTIME:
1358 		NET_LOCK();
1359 		nval = tcptv_keep_init / TCP_TIME(1);
1360 		error = sysctl_int_bounded(oldp, oldlenp, newp, newlen, &nval,
1361 		    1, 3 * (TCPTV_KEEP_INIT / TCP_TIME(1)));
1362 		if (!error)
1363 			tcptv_keep_init = TCP_TIME(nval);
1364 		NET_UNLOCK();
1365 		return (error);
1366 
1367 	case TCPCTL_KEEPIDLE:
1368 		NET_LOCK();
1369 		nval = tcp_keepidle / TCP_TIME(1);
1370 		error = sysctl_int_bounded(oldp, oldlenp, newp, newlen, &nval,
1371 		    1, 5 * (TCPTV_KEEP_IDLE / TCP_TIME(1)));
1372 		if (!error)
1373 			tcp_keepidle = TCP_TIME(nval);
1374 		NET_UNLOCK();
1375 		return (error);
1376 
1377 	case TCPCTL_KEEPINTVL:
1378 		NET_LOCK();
1379 		nval = tcp_keepintvl / TCP_TIME(1);
1380 		error = sysctl_int_bounded(oldp, oldlenp, newp, newlen, &nval,
1381 		    1, 3 * (TCPTV_KEEPINTVL / TCP_TIME(1)));
1382 		if (!error)
1383 			tcp_keepintvl = TCP_TIME(nval);
1384 		NET_UNLOCK();
1385 		return (error);
1386 
1387 	case TCPCTL_BADDYNAMIC:
1388 		NET_LOCK();
1389 		error = sysctl_struct(oldp, oldlenp, newp, newlen,
1390 		    baddynamicports.tcp, sizeof(baddynamicports.tcp));
1391 		NET_UNLOCK();
1392 		return (error);
1393 
1394 	case TCPCTL_ROOTONLY:
1395 		if (newp && securelevel > 0)
1396 			return (EPERM);
1397 		NET_LOCK();
1398 		error = sysctl_struct(oldp, oldlenp, newp, newlen,
1399 		    rootonlyports.tcp, sizeof(rootonlyports.tcp));
1400 		NET_UNLOCK();
1401 		return (error);
1402 
1403 	case TCPCTL_IDENT:
1404 		NET_LOCK();
1405 		error = tcp_ident(oldp, oldlenp, newp, newlen, 0);
1406 		NET_UNLOCK();
1407 		return (error);
1408 
1409 	case TCPCTL_DROP:
1410 		NET_LOCK();
1411 		error = tcp_ident(oldp, oldlenp, newp, newlen, 1);
1412 		NET_UNLOCK();
1413 		return (error);
1414 
1415 	case TCPCTL_REASS_LIMIT:
1416 		NET_LOCK();
1417 		nval = tcp_reass_limit;
1418 		error = sysctl_int(oldp, oldlenp, newp, newlen, &nval);
1419 		if (!error && nval != tcp_reass_limit) {
1420 			error = pool_sethardlimit(&tcpqe_pool, nval, NULL, 0);
1421 			if (!error)
1422 				tcp_reass_limit = nval;
1423 		}
1424 		NET_UNLOCK();
1425 		return (error);
1426 
1427 	case TCPCTL_SACKHOLE_LIMIT:
1428 		NET_LOCK();
1429 		nval = tcp_sackhole_limit;
1430 		error = sysctl_int(oldp, oldlenp, newp, newlen, &nval);
1431 		if (!error && nval != tcp_sackhole_limit) {
1432 			error = pool_sethardlimit(&sackhl_pool, nval, NULL, 0);
1433 			if (!error)
1434 				tcp_sackhole_limit = nval;
1435 		}
1436 		NET_UNLOCK();
1437 		return (error);
1438 
1439 	case TCPCTL_STATS:
1440 		return (tcp_sysctl_tcpstat(oldp, oldlenp, newp));
1441 
1442 	case TCPCTL_SYN_USE_LIMIT:
1443 		NET_LOCK();
1444 		error = sysctl_int_bounded(oldp, oldlenp, newp, newlen,
1445 		    &tcp_syn_use_limit, 0, INT_MAX);
1446 		if (!error && newp != NULL) {
1447 			/*
1448 			 * Global tcp_syn_use_limit is used when reseeding a
1449 			 * new cache.  Also update the value in active cache.
1450 			 */
1451 			mtx_enter(&syn_cache_mtx);
1452 			if (tcp_syn_cache[0].scs_use > tcp_syn_use_limit)
1453 				tcp_syn_cache[0].scs_use = tcp_syn_use_limit;
1454 			if (tcp_syn_cache[1].scs_use > tcp_syn_use_limit)
1455 				tcp_syn_cache[1].scs_use = tcp_syn_use_limit;
1456 			mtx_leave(&syn_cache_mtx);
1457 		}
1458 		NET_UNLOCK();
1459 		return (error);
1460 
1461 	case TCPCTL_SYN_HASH_SIZE:
1462 		NET_LOCK();
1463 		nval = tcp_syn_hash_size;
1464 		error = sysctl_int_bounded(oldp, oldlenp, newp, newlen,
1465 		    &nval, 1, 100000);
1466 		if (!error && nval != tcp_syn_hash_size) {
1467 			/*
1468 			 * If global hash size has been changed,
1469 			 * switch sets as soon as possible.  Then
1470 			 * the actual hash array will be reallocated.
1471 			 */
1472 			mtx_enter(&syn_cache_mtx);
1473 			if (tcp_syn_cache[0].scs_size != nval)
1474 				tcp_syn_cache[0].scs_use = 0;
1475 			if (tcp_syn_cache[1].scs_size != nval)
1476 				tcp_syn_cache[1].scs_use = 0;
1477 			tcp_syn_hash_size = nval;
1478 			mtx_leave(&syn_cache_mtx);
1479 		}
1480 		NET_UNLOCK();
1481 		return (error);
1482 
1483 	default:
1484 		NET_LOCK();
1485 		error = sysctl_bounded_arr(tcpctl_vars, nitems(tcpctl_vars),
1486 		    name, namelen, oldp, oldlenp, newp, newlen);
1487 		NET_UNLOCK();
1488 		return (error);
1489 	}
1490 	/* NOTREACHED */
1491 }
1492 
1493 /*
1494  * Scale the send buffer so that inflight data is not accounted against
1495  * the limit. The buffer will scale with the congestion window, if the
1496  * the receiver stops acking data the window will shrink and therefore
1497  * the buffer size will shrink as well.
1498  * In low memory situation try to shrink the buffer to the initial size
1499  * disabling the send buffer scaling as long as the situation persists.
1500  */
1501 void
1502 tcp_update_sndspace(struct tcpcb *tp)
1503 {
1504 	struct socket *so = tp->t_inpcb->inp_socket;
1505 	u_long nmax = so->so_snd.sb_hiwat;
1506 
1507 	if (sbchecklowmem()) {
1508 		/* low on memory try to get rid of some */
1509 		if (tcp_sendspace < nmax)
1510 			nmax = tcp_sendspace;
1511 	} else if (so->so_snd.sb_wat != tcp_sendspace)
1512 		/* user requested buffer size, auto-scaling disabled */
1513 		nmax = so->so_snd.sb_wat;
1514 	else
1515 		/* automatic buffer scaling */
1516 		nmax = MIN(sb_max, so->so_snd.sb_wat + tp->snd_max -
1517 		    tp->snd_una);
1518 
1519 	/* a writable socket must be preserved because of poll(2) semantics */
1520 	if (sbspace(so, &so->so_snd) >= so->so_snd.sb_lowat) {
1521 		if (nmax < so->so_snd.sb_cc + so->so_snd.sb_lowat)
1522 			nmax = so->so_snd.sb_cc + so->so_snd.sb_lowat;
1523 		/* keep in sync with sbreserve() calculation */
1524 		if (nmax * 8 < so->so_snd.sb_mbcnt + so->so_snd.sb_lowat)
1525 			nmax = (so->so_snd.sb_mbcnt+so->so_snd.sb_lowat+7) / 8;
1526 	}
1527 
1528 	/* round to MSS boundary */
1529 	nmax = roundup(nmax, tp->t_maxseg);
1530 
1531 	if (nmax != so->so_snd.sb_hiwat)
1532 		sbreserve(so, &so->so_snd, nmax);
1533 }
1534 
1535 /*
1536  * Scale the recv buffer by looking at how much data was transferred in
1537  * one approximated RTT. If more than a big part of the recv buffer was
1538  * transferred during that time we increase the buffer by a constant.
1539  * In low memory situation try to shrink the buffer to the initial size.
1540  */
1541 void
1542 tcp_update_rcvspace(struct tcpcb *tp)
1543 {
1544 	struct socket *so = tp->t_inpcb->inp_socket;
1545 	u_long nmax = so->so_rcv.sb_hiwat;
1546 
1547 	if (sbchecklowmem()) {
1548 		/* low on memory try to get rid of some */
1549 		if (tcp_recvspace < nmax)
1550 			nmax = tcp_recvspace;
1551 	} else if (so->so_rcv.sb_wat != tcp_recvspace)
1552 		/* user requested buffer size, auto-scaling disabled */
1553 		nmax = so->so_rcv.sb_wat;
1554 	else {
1555 		/* automatic buffer scaling */
1556 		if (tp->rfbuf_cnt > so->so_rcv.sb_hiwat / 8 * 7)
1557 			nmax = MIN(sb_max, so->so_rcv.sb_hiwat +
1558 			    tcp_autorcvbuf_inc);
1559 	}
1560 
1561 	/* a readable socket must be preserved because of poll(2) semantics */
1562 	if (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat &&
1563 	    nmax < so->so_snd.sb_lowat)
1564 		nmax = so->so_snd.sb_lowat;
1565 
1566 	if (nmax == so->so_rcv.sb_hiwat)
1567 		return;
1568 
1569 	/* round to MSS boundary */
1570 	nmax = roundup(nmax, tp->t_maxseg);
1571 	sbreserve(so, &so->so_rcv, nmax);
1572 }
1573