xref: /freebsd/sys/netinet/tcp_subr.c (revision 41356c80179c708b6a49eabf1be9cedd6bca4444)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include "opt_inet.h"
33 #include "opt_inet6.h"
34 #include "opt_ipsec.h"
35 #include "opt_kern_tls.h"
36 
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/arb.h>
40 #include <sys/callout.h>
41 #include <sys/eventhandler.h>
42 #ifdef TCP_HHOOK
43 #include <sys/hhook.h>
44 #endif
45 #include <sys/kernel.h>
46 #ifdef TCP_HHOOK
47 #include <sys/khelp.h>
48 #endif
49 #ifdef KERN_TLS
50 #include <sys/ktls.h>
51 #endif
52 #include <sys/qmath.h>
53 #include <sys/stats.h>
54 #include <sys/sysctl.h>
55 #include <sys/jail.h>
56 #include <sys/malloc.h>
57 #include <sys/refcount.h>
58 #include <sys/mbuf.h>
59 #include <sys/priv.h>
60 #include <sys/sdt.h>
61 #include <sys/socket.h>
62 #include <sys/socketvar.h>
63 #include <sys/protosw.h>
64 #include <sys/random.h>
65 
66 #include <vm/uma.h>
67 
68 #include <net/route.h>
69 #include <net/route/nhop.h>
70 #include <net/if.h>
71 #include <net/if_var.h>
72 #include <net/if_private.h>
73 #include <net/vnet.h>
74 
75 #include <netinet/in.h>
76 #include <netinet/in_fib.h>
77 #include <netinet/in_kdtrace.h>
78 #include <netinet/in_pcb.h>
79 #include <netinet/in_systm.h>
80 #include <netinet/in_var.h>
81 #include <netinet/ip.h>
82 #include <netinet/ip_icmp.h>
83 #include <netinet/ip_var.h>
84 #include <netinet/icmp_var.h>
85 #ifdef INET6
86 #include <netinet/icmp6.h>
87 #include <netinet/ip6.h>
88 #include <netinet6/in6_fib.h>
89 #include <netinet6/in6_pcb.h>
90 #include <netinet6/ip6_var.h>
91 #include <netinet6/scope6_var.h>
92 #include <netinet6/nd6.h>
93 #endif
94 
95 #include <netinet/tcp.h>
96 #ifdef INVARIANTS
97 #define TCPSTATES
98 #endif
99 #include <netinet/tcp_fsm.h>
100 #include <netinet/tcp_seq.h>
101 #include <netinet/tcp_timer.h>
102 #include <netinet/tcp_var.h>
103 #include <netinet/tcp_ecn.h>
104 #include <netinet/tcp_log_buf.h>
105 #include <netinet/tcp_syncache.h>
106 #include <netinet/tcp_hpts.h>
107 #include <netinet/tcp_lro.h>
108 #include <netinet/cc/cc.h>
109 #include <netinet/tcpip.h>
110 #include <netinet/tcp_fastopen.h>
111 #include <netinet/tcp_accounting.h>
112 #ifdef TCP_OFFLOAD
113 #include <netinet/tcp_offload.h>
114 #endif
115 #include <netinet/udp.h>
116 #include <netinet/udp_var.h>
117 #ifdef INET6
118 #include <netinet6/tcp6_var.h>
119 #endif
120 
121 #include <netipsec/ipsec_support.h>
122 
123 #include <machine/in_cksum.h>
124 #include <crypto/siphash/siphash.h>
125 
126 #include <security/mac/mac_framework.h>
127 
128 #ifdef INET6
129 static ip6proto_ctlinput_t tcp6_ctlinput;
130 static udp_tun_icmp_t tcp6_ctlinput_viaudp;
131 #endif
132 
133 VNET_DEFINE(int, tcp_mssdflt) = TCP_MSS;
134 #ifdef INET6
135 VNET_DEFINE(int, tcp_v6mssdflt) = TCP6_MSS;
136 #endif
137 
138 VNET_DEFINE(uint32_t, tcp_ack_war_time_window) = 1000;
139 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, ack_war_timewindow,
140     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(tcp_ack_war_time_window), 0,
141    "Time interval in ms used to limit the number (ack_war_cnt) of challenge ACKs sent per TCP connection");
142 VNET_DEFINE(uint32_t, tcp_ack_war_cnt) = 5;
143 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, ack_war_cnt, CTLFLAG_VNET | CTLFLAG_RW,
144     &VNET_NAME(tcp_ack_war_cnt), 0,
145    "Maximum number of challenge ACKs sent per TCP connection during the time interval (ack_war_timewindow)");
146 
147 struct rwlock tcp_function_lock;
148 
149 static int
sysctl_net_inet_tcp_mss_check(SYSCTL_HANDLER_ARGS)150 sysctl_net_inet_tcp_mss_check(SYSCTL_HANDLER_ARGS)
151 {
152 	int error, new;
153 
154 	new = V_tcp_mssdflt;
155 	error = sysctl_handle_int(oidp, &new, 0, req);
156 	if (error == 0 && req->newptr) {
157 		if (new < TCP_MINMSS)
158 			error = EINVAL;
159 		else
160 			V_tcp_mssdflt = new;
161 	}
162 	return (error);
163 }
164 
165 SYSCTL_PROC(_net_inet_tcp, TCPCTL_MSSDFLT, mssdflt,
166     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
167     &VNET_NAME(tcp_mssdflt), 0, &sysctl_net_inet_tcp_mss_check, "I",
168     "Default TCP Maximum Segment Size");
169 
170 #ifdef INET6
171 static int
sysctl_net_inet_tcp_mss_v6_check(SYSCTL_HANDLER_ARGS)172 sysctl_net_inet_tcp_mss_v6_check(SYSCTL_HANDLER_ARGS)
173 {
174 	int error, new;
175 
176 	new = V_tcp_v6mssdflt;
177 	error = sysctl_handle_int(oidp, &new, 0, req);
178 	if (error == 0 && req->newptr) {
179 		if (new < TCP_MINMSS)
180 			error = EINVAL;
181 		else
182 			V_tcp_v6mssdflt = new;
183 	}
184 	return (error);
185 }
186 
187 SYSCTL_PROC(_net_inet_tcp, TCPCTL_V6MSSDFLT, v6mssdflt,
188     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
189     &VNET_NAME(tcp_v6mssdflt), 0, &sysctl_net_inet_tcp_mss_v6_check, "I",
190    "Default TCP Maximum Segment Size for IPv6");
191 #endif /* INET6 */
192 
193 /*
194  * Minimum MSS we accept and use. This prevents DoS attacks where
195  * we are forced to a ridiculous low MSS like 20 and send hundreds
196  * of packets instead of one. The effect scales with the available
197  * bandwidth and quickly saturates the CPU and network interface
198  * with packet generation and sending. Set to zero to disable MINMSS
199  * checking. This setting prevents us from sending too small packets.
200  */
201 VNET_DEFINE(int, tcp_minmss) = TCP_MINMSS;
202 SYSCTL_INT(_net_inet_tcp, OID_AUTO, minmss, CTLFLAG_VNET | CTLFLAG_RW,
203      &VNET_NAME(tcp_minmss), 0,
204     "Minimum TCP Maximum Segment Size");
205 
206 VNET_DEFINE(int, tcp_do_rfc1323) = 1;
207 SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1323, rfc1323, CTLFLAG_VNET | CTLFLAG_RW,
208     &VNET_NAME(tcp_do_rfc1323), 0,
209     "Enable rfc1323 (high performance TCP) extensions");
210 
211 /*
212  * As of June 2021, several TCP stacks violate RFC 7323 from September 2014.
213  * Some stacks negotiate TS, but never send them after connection setup. Some
214  * stacks negotiate TS, but don't send them when sending keep-alive segments.
215  * These include modern widely deployed TCP stacks.
216  * Therefore tolerating violations for now...
217  */
218 VNET_DEFINE(int, tcp_tolerate_missing_ts) = 1;
219 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tolerate_missing_ts, CTLFLAG_VNET | CTLFLAG_RW,
220     &VNET_NAME(tcp_tolerate_missing_ts), 0,
221     "Tolerate missing TCP timestamps");
222 
223 VNET_DEFINE(int, tcp_ts_offset_per_conn) = 1;
224 SYSCTL_INT(_net_inet_tcp, OID_AUTO, ts_offset_per_conn, CTLFLAG_VNET | CTLFLAG_RW,
225     &VNET_NAME(tcp_ts_offset_per_conn), 0,
226     "Initialize TCP timestamps per connection instead of per host pair");
227 
228 /* How many connections are pacing */
229 static volatile uint32_t number_of_tcp_connections_pacing = 0;
230 static uint32_t shadow_num_connections = 0;
231 static counter_u64_t tcp_pacing_failures;
232 static counter_u64_t tcp_dgp_failures;
233 static uint32_t shadow_tcp_pacing_dgp = 0;
234 static volatile uint32_t number_of_dgp_connections = 0;
235 
236 static int tcp_pacing_limit = 10000;
237 SYSCTL_INT(_net_inet_tcp, OID_AUTO, pacing_limit, CTLFLAG_RW,
238     &tcp_pacing_limit, 1000,
239     "If the TCP stack does pacing, is there a limit (-1 = no, 0 = no pacing N = number of connections)");
240 
241 static int tcp_dgp_limit = -1;
242 SYSCTL_INT(_net_inet_tcp, OID_AUTO, dgp_limit, CTLFLAG_RW,
243     &tcp_dgp_limit, -1,
244     "If the TCP stack does DGP, is there a limit (-1 = no, 0 = no dgp N = number of connections)");
245 
246 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, pacing_count, CTLFLAG_RD,
247     &shadow_num_connections, 0, "Number of TCP connections being paced");
248 
249 SYSCTL_COUNTER_U64(_net_inet_tcp, OID_AUTO, pacing_failures, CTLFLAG_RD,
250     &tcp_pacing_failures, "Number of times we failed to enable pacing to avoid exceeding the limit");
251 
252 SYSCTL_COUNTER_U64(_net_inet_tcp, OID_AUTO, dgp_failures, CTLFLAG_RD,
253     &tcp_dgp_failures, "Number of times we failed to enable dgp to avoid exceeding the limit");
254 
255 static int	tcp_log_debug = 0;
256 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_debug, CTLFLAG_RW,
257     &tcp_log_debug, 0, "Log errors caused by incoming TCP segments");
258 
259 /*
260  * Target size of TCP PCB hash tables. Must be a power of two.
261  *
262  * Note that this can be overridden by the kernel environment
263  * variable net.inet.tcp.tcbhashsize
264  */
265 #ifndef TCBHASHSIZE
266 #define TCBHASHSIZE	0
267 #endif
268 static int	tcp_tcbhashsize = TCBHASHSIZE;
269 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcbhashsize, CTLFLAG_RDTUN,
270     &tcp_tcbhashsize, 0, "Size of TCP control-block hashtable");
271 
272 static int	do_tcpdrain = 1;
273 SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_tcpdrain, CTLFLAG_RW, &do_tcpdrain, 0,
274     "Enable tcp_drain routine for extra help when low on mbufs");
275 
276 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, pcbcount, CTLFLAG_VNET | CTLFLAG_RD,
277     &VNET_NAME(tcbinfo.ipi_count), 0, "Number of active PCBs");
278 
279 VNET_DEFINE_STATIC(int, icmp_may_rst) = 1;
280 #define	V_icmp_may_rst			VNET(icmp_may_rst)
281 SYSCTL_INT(_net_inet_tcp, OID_AUTO, icmp_may_rst, CTLFLAG_VNET | CTLFLAG_RW,
282     &VNET_NAME(icmp_may_rst), 0,
283     "Certain ICMP unreachable messages may abort connections in SYN_SENT");
284 
285 VNET_DEFINE_STATIC(int, tcp_isn_reseed_interval) = 0;
286 #define	V_tcp_isn_reseed_interval	VNET(tcp_isn_reseed_interval)
287 SYSCTL_INT(_net_inet_tcp, OID_AUTO, isn_reseed_interval, CTLFLAG_VNET | CTLFLAG_RW,
288     &VNET_NAME(tcp_isn_reseed_interval), 0,
289     "Seconds between reseeding of ISN secret");
290 
291 static int	tcp_soreceive_stream;
292 SYSCTL_INT(_net_inet_tcp, OID_AUTO, soreceive_stream, CTLFLAG_RDTUN,
293     &tcp_soreceive_stream, 0, "Using soreceive_stream for TCP sockets");
294 
295 uma_zone_t tcp_sack_hole_zone;
296 
297 VNET_DEFINE(uint32_t, tcp_map_entries_limit) = 0;	/* unlimited */
298 static int
sysctl_net_inet_tcp_map_limit_check(SYSCTL_HANDLER_ARGS)299 sysctl_net_inet_tcp_map_limit_check(SYSCTL_HANDLER_ARGS)
300 {
301 	int error;
302 	uint32_t new;
303 
304 	new = V_tcp_map_entries_limit;
305 	error = sysctl_handle_int(oidp, &new, 0, req);
306 	if (error == 0 && req->newptr) {
307 		/* only allow "0" and value > minimum */
308 		if (new > 0 && new < TCP_MIN_MAP_ENTRIES_LIMIT)
309 			error = EINVAL;
310 		else
311 			V_tcp_map_entries_limit = new;
312 	}
313 	return (error);
314 }
315 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, map_limit,
316     CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
317     &VNET_NAME(tcp_map_entries_limit), 0,
318     &sysctl_net_inet_tcp_map_limit_check, "IU",
319     "Total sendmap entries limit");
320 
321 VNET_DEFINE(uint32_t, tcp_map_split_limit) = 0;	/* unlimited */
322 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, split_limit, CTLFLAG_VNET | CTLFLAG_RW,
323      &VNET_NAME(tcp_map_split_limit), 0,
324     "Total sendmap split entries limit");
325 
326 #ifdef TCP_HHOOK
327 VNET_DEFINE(struct hhook_head *, tcp_hhh[HHOOK_TCP_LAST+1]);
328 #endif
329 
330 #define TS_OFFSET_SECRET_LENGTH SIPHASH_KEY_LENGTH
331 VNET_DEFINE_STATIC(u_char, ts_offset_secret[TS_OFFSET_SECRET_LENGTH]);
332 #define	V_ts_offset_secret	VNET(ts_offset_secret)
333 
334 static int	tcp_default_fb_init(struct tcpcb *tp, void **ptr);
335 static void	tcp_default_fb_fini(struct tcpcb *tp, int tcb_is_purged);
336 static int	tcp_default_handoff_ok(struct tcpcb *tp);
337 static struct inpcb *tcp_notify(struct inpcb *, int);
338 static struct inpcb *tcp_mtudisc_notify(struct inpcb *, int);
339 static struct inpcb *tcp_mtudisc(struct inpcb *, int);
340 static struct inpcb *tcp_drop_syn_sent(struct inpcb *, int);
341 static char *	tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th,
342 		    const void *ip4hdr, const void *ip6hdr);
343 static void	tcp_default_switch_failed(struct tcpcb *tp);
344 
345 #ifdef INET
346 static ipproto_ctlinput_t	tcp_ctlinput;
347 static udp_tun_icmp_t		tcp_ctlinput_viaudp;
348 #endif
349 
350 static struct tcp_function_block tcp_def_funcblk = {
351 	.tfb_tcp_block_name = "freebsd",
352 	.tfb_tcp_output = tcp_default_output,
353 	.tfb_tcp_do_segment = tcp_do_segment,
354 	.tfb_tcp_ctloutput = tcp_default_ctloutput,
355 	.tfb_tcp_handoff_ok = tcp_default_handoff_ok,
356 	.tfb_tcp_fb_init = tcp_default_fb_init,
357 	.tfb_tcp_fb_fini = tcp_default_fb_fini,
358 	.tfb_switch_failed = tcp_default_switch_failed,
359 	.tfb_flags = TCP_FUNC_DEFAULT_OK,
360 };
361 
362 static int tcp_fb_cnt = 0;
363 struct tcp_funchead t_functions;
364 VNET_DEFINE_STATIC(struct tcp_function_block *, tcp_func_set_ptr) = &tcp_def_funcblk;
365 #define	V_tcp_func_set_ptr VNET(tcp_func_set_ptr)
366 
367 void
tcp_record_dsack(struct tcpcb * tp,tcp_seq start,tcp_seq end,int tlp)368 tcp_record_dsack(struct tcpcb *tp, tcp_seq start, tcp_seq end, int tlp)
369 {
370 	TCPSTAT_INC(tcps_dsack_count);
371 	tp->t_dsack_pack++;
372 	if (tlp == 0) {
373 		if (SEQ_GT(end, start)) {
374 			tp->t_dsack_bytes += (end - start);
375 			TCPSTAT_ADD(tcps_dsack_bytes, (end - start));
376 		} else {
377 			tp->t_dsack_tlp_bytes += (start - end);
378 			TCPSTAT_ADD(tcps_dsack_bytes, (start - end));
379 		}
380 	} else {
381 		if (SEQ_GT(end, start)) {
382 			tp->t_dsack_bytes += (end - start);
383 			TCPSTAT_ADD(tcps_dsack_tlp_bytes, (end - start));
384 		} else {
385 			tp->t_dsack_tlp_bytes += (start - end);
386 			TCPSTAT_ADD(tcps_dsack_tlp_bytes, (start - end));
387 		}
388 	}
389 }
390 
391 static struct tcp_function_block *
find_tcp_functions_locked(struct tcp_function_set * fs)392 find_tcp_functions_locked(struct tcp_function_set *fs)
393 {
394 	struct tcp_function *f;
395 	struct tcp_function_block *blk = NULL;
396 
397 	rw_assert(&tcp_function_lock, RA_LOCKED);
398 	TAILQ_FOREACH(f, &t_functions, tf_next) {
399 		if (strcmp(f->tf_name, fs->function_set_name) == 0) {
400 			blk = f->tf_fb;
401 			break;
402 		}
403 	}
404 	return (blk);
405 }
406 
407 static struct tcp_function_block *
find_tcp_fb_locked(struct tcp_function_block * blk,struct tcp_function ** s)408 find_tcp_fb_locked(struct tcp_function_block *blk, struct tcp_function **s)
409 {
410 	struct tcp_function_block *rblk = NULL;
411 	struct tcp_function *f;
412 
413 	rw_assert(&tcp_function_lock, RA_LOCKED);
414 	TAILQ_FOREACH(f, &t_functions, tf_next) {
415 		if (f->tf_fb == blk) {
416 			rblk = blk;
417 			if (s) {
418 				*s = f;
419 			}
420 			break;
421 		}
422 	}
423 	return (rblk);
424 }
425 
426 struct tcp_function_block *
find_and_ref_tcp_functions(struct tcp_function_set * fs)427 find_and_ref_tcp_functions(struct tcp_function_set *fs)
428 {
429 	struct tcp_function_block *blk;
430 
431 	rw_rlock(&tcp_function_lock);
432 	blk = find_tcp_functions_locked(fs);
433 	if (blk)
434 		refcount_acquire(&blk->tfb_refcnt);
435 	rw_runlock(&tcp_function_lock);
436 	return (blk);
437 }
438 
439 struct tcp_function_block *
find_and_ref_tcp_fb(struct tcp_function_block * blk)440 find_and_ref_tcp_fb(struct tcp_function_block *blk)
441 {
442 	struct tcp_function_block *rblk;
443 
444 	rw_rlock(&tcp_function_lock);
445 	rblk = find_tcp_fb_locked(blk, NULL);
446 	if (rblk)
447 		refcount_acquire(&rblk->tfb_refcnt);
448 	rw_runlock(&tcp_function_lock);
449 	return (rblk);
450 }
451 
452 /* Find a matching alias for the given tcp_function_block. */
453 int
find_tcp_function_alias(struct tcp_function_block * blk,struct tcp_function_set * fs)454 find_tcp_function_alias(struct tcp_function_block *blk,
455     struct tcp_function_set *fs)
456 {
457 	struct tcp_function *f;
458 	int found;
459 
460 	found = 0;
461 	rw_rlock(&tcp_function_lock);
462 	TAILQ_FOREACH(f, &t_functions, tf_next) {
463 		if ((f->tf_fb == blk) &&
464 		    (strncmp(f->tf_name, blk->tfb_tcp_block_name,
465 		        TCP_FUNCTION_NAME_LEN_MAX) != 0)) {
466 			/* Matching function block with different name. */
467 			strncpy(fs->function_set_name, f->tf_name,
468 			    TCP_FUNCTION_NAME_LEN_MAX);
469 			found = 1;
470 			break;
471 		}
472 	}
473 	/* Null terminate the string appropriately. */
474 	if (found) {
475 		fs->function_set_name[TCP_FUNCTION_NAME_LEN_MAX - 1] = '\0';
476 	} else {
477 		fs->function_set_name[0] = '\0';
478 	}
479 	rw_runlock(&tcp_function_lock);
480 	return (found);
481 }
482 
483 static struct tcp_function_block *
find_and_ref_tcp_default_fb(void)484 find_and_ref_tcp_default_fb(void)
485 {
486 	struct tcp_function_block *rblk;
487 
488 	rw_rlock(&tcp_function_lock);
489 	rblk = V_tcp_func_set_ptr;
490 	refcount_acquire(&rblk->tfb_refcnt);
491 	rw_runlock(&tcp_function_lock);
492 	return (rblk);
493 }
494 
495 void
tcp_switch_back_to_default(struct tcpcb * tp)496 tcp_switch_back_to_default(struct tcpcb *tp)
497 {
498 	struct tcp_function_block *tfb;
499 	void *ptr = NULL;
500 
501 	KASSERT(tp->t_fb != &tcp_def_funcblk,
502 	    ("%s: called by the built-in default stack", __func__));
503 
504 	if (tp->t_fb->tfb_tcp_timer_stop_all != NULL)
505 		tp->t_fb->tfb_tcp_timer_stop_all(tp);
506 
507 	/*
508 	 * Now, we'll find a new function block to use.
509 	 * Start by trying the current user-selected
510 	 * default, unless this stack is the user-selected
511 	 * default.
512 	 */
513 	tfb = find_and_ref_tcp_default_fb();
514 	if (tfb == tp->t_fb) {
515 		refcount_release(&tfb->tfb_refcnt);
516 		tfb = NULL;
517 	}
518 	/* Does the stack accept this connection? */
519 	if (tfb != NULL && (*tfb->tfb_tcp_handoff_ok)(tp)) {
520 		refcount_release(&tfb->tfb_refcnt);
521 		tfb = NULL;
522 	}
523 	/* Try to use that stack. */
524 	if (tfb != NULL) {
525 		/* Initialize the new stack. If it succeeds, we are done. */
526 		if (tfb->tfb_tcp_fb_init == NULL ||
527 		    (*tfb->tfb_tcp_fb_init)(tp, &ptr) == 0) {
528 			/* Release the old stack */
529 			if (tp->t_fb->tfb_tcp_fb_fini != NULL)
530 				(*tp->t_fb->tfb_tcp_fb_fini)(tp, 0);
531 			refcount_release(&tp->t_fb->tfb_refcnt);
532 			/* Now set in all the pointers */
533 			tp->t_fb = tfb;
534 			tp->t_fb_ptr = ptr;
535 			return;
536 		}
537 		/*
538 		 * Initialization failed. Release the reference count on
539 		 * the looked up default stack.
540 		 */
541 		refcount_release(&tfb->tfb_refcnt);
542 	}
543 
544 	/*
545 	 * If that wasn't feasible, use the built-in default
546 	 * stack which is not allowed to reject anyone.
547 	 */
548 	tfb = find_and_ref_tcp_fb(&tcp_def_funcblk);
549 	if (tfb == NULL) {
550 		/* there always should be a default */
551 		panic("Can't refer to tcp_def_funcblk");
552 	}
553 	if ((*tfb->tfb_tcp_handoff_ok)(tp)) {
554 		/* The default stack cannot say no */
555 		panic("Default stack rejects a new session?");
556 	}
557 	if (tfb->tfb_tcp_fb_init != NULL &&
558 	    (*tfb->tfb_tcp_fb_init)(tp, &ptr)) {
559 		/* The default stack cannot fail */
560 		panic("Default stack initialization failed");
561 	}
562 	/* Now release the old stack */
563 	if (tp->t_fb->tfb_tcp_fb_fini != NULL)
564 		(*tp->t_fb->tfb_tcp_fb_fini)(tp, 0);
565 	refcount_release(&tp->t_fb->tfb_refcnt);
566 	/* And set in the pointers to the new */
567 	tp->t_fb = tfb;
568 	tp->t_fb_ptr = ptr;
569 }
570 
571 static bool
tcp_recv_udp_tunneled_packet(struct mbuf * m,int off,struct inpcb * inp,const struct sockaddr * sa,void * ctx)572 tcp_recv_udp_tunneled_packet(struct mbuf *m, int off, struct inpcb *inp,
573     const struct sockaddr *sa, void *ctx)
574 {
575 	struct ip *iph;
576 #ifdef INET6
577 	struct ip6_hdr *ip6;
578 #endif
579 	struct udphdr *uh;
580 	struct tcphdr *th;
581 	int len;
582 	uint16_t port;
583 
584 	TCPSTAT_INC(tcps_tunneled_pkts);
585 	if ((m->m_flags & M_PKTHDR) == 0) {
586 		/* Can't handle one that is not a pkt hdr */
587 		TCPSTAT_INC(tcps_tunneled_errs);
588 		m_freem(m);
589 		return (true);
590 	}
591 	if ((m = m_pullup(m, off + sizeof(struct udphdr) +
592 	    sizeof(struct tcphdr))) == NULL) {
593 		TCPSTAT_INC(tcps_tunneled_errs);
594 		return (true);
595 	}
596 	iph = mtod(m, struct ip *);
597 	uh = (struct udphdr *)((char *)iph + off);
598 	th = (struct tcphdr *)(uh + 1);
599 	if ((m = m_pullup(m, off + sizeof(struct udphdr) +
600 	    (th->th_off << 2))) == NULL) {
601 		TCPSTAT_INC(tcps_tunneled_errs);
602 		return (true);
603 	}
604 	iph = mtod(m, struct ip *);
605 	uh = (struct udphdr *)((char *)iph + off);
606 	th = (struct tcphdr *)(uh + 1);
607 
608 	m->m_pkthdr.tcp_tun_port = port = uh->uh_sport;
609 	bcopy(th, uh, m->m_len - off - sizeof(struct udphdr));
610 	m->m_len -= sizeof(struct udphdr);
611 	m->m_pkthdr.len -= sizeof(struct udphdr);
612 	/*
613 	 * We use the same algorithm for
614 	 * both UDP and TCP for c-sum. So
615 	 * the code in tcp_input will skip
616 	 * the checksum. So we do nothing
617 	 * with the flag (m->m_pkthdr.csum_flags).
618 	 */
619 	switch (iph->ip_v) {
620 #ifdef INET
621 	case IPVERSION:
622 		len = ntohs(iph->ip_len) - sizeof(struct udphdr);
623 		if (__predict_false(len != m->m_pkthdr.len)) {
624 			TCPSTAT_INC(tcps_tunneled_errs);
625 			m_freem(m);
626 			return (true);
627 		} else {
628 			iph->ip_len = htons(len);
629 			tcp_input_with_port(&m, &off, IPPROTO_TCP, port);
630 		}
631 		break;
632 #endif
633 #ifdef INET6
634 	case IPV6_VERSION >> 4:
635 		ip6 = mtod(m, struct ip6_hdr *);
636 		len = ntohs(ip6->ip6_plen) - sizeof(struct udphdr);
637 		if (__predict_false(len + sizeof(struct ip6_hdr) !=
638 		    m->m_pkthdr.len)) {
639 			TCPSTAT_INC(tcps_tunneled_errs);
640 			m_freem(m);
641 			return (true);
642 		} else {
643 			ip6->ip6_plen = htons(len);
644 			tcp6_input_with_port(&m, &off, IPPROTO_TCP, port);
645 		}
646 		break;
647 #endif
648 	default:
649 		m_freem(m);
650 		break;
651 	}
652 	return (true);
653 }
654 
655 static int
sysctl_net_inet_default_tcp_functions(SYSCTL_HANDLER_ARGS)656 sysctl_net_inet_default_tcp_functions(SYSCTL_HANDLER_ARGS)
657 {
658 	struct tcp_function_set fs;
659 	struct tcp_function_block *blk;
660 	int error;
661 
662 	memset(&fs, 0, sizeof(struct tcp_function_set));
663 	rw_rlock(&tcp_function_lock);
664 	blk = find_tcp_fb_locked(V_tcp_func_set_ptr, NULL);
665 	if (blk != NULL) {
666 		/* Found him */
667 		strcpy(fs.function_set_name, blk->tfb_tcp_block_name);
668 		fs.pcbcnt = blk->tfb_refcnt;
669 	}
670 	rw_runlock(&tcp_function_lock);
671 	error = sysctl_handle_string(oidp, fs.function_set_name,
672 				     sizeof(fs.function_set_name), req);
673 
674 	/* Check for error or no change */
675 	if (error != 0 || req->newptr == NULL)
676 		return (error);
677 
678 	rw_wlock(&tcp_function_lock);
679 	blk = find_tcp_functions_locked(&fs);
680 	if ((blk == NULL) ||
681 	    (blk->tfb_flags & TCP_FUNC_BEING_REMOVED)) {
682 		error = ENOENT;
683 		goto done;
684 	}
685 	if ((blk->tfb_flags & TCP_FUNC_DEFAULT_OK) == 0) {
686 		error = EINVAL;
687 		goto done;
688 	}
689 	V_tcp_func_set_ptr = blk;
690 done:
691 	rw_wunlock(&tcp_function_lock);
692 	return (error);
693 }
694 
695 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, functions_default,
696     CTLFLAG_VNET | CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
697     NULL, 0, sysctl_net_inet_default_tcp_functions, "A",
698     "Set/get the default TCP functions");
699 
700 static int
sysctl_net_inet_list_available(SYSCTL_HANDLER_ARGS)701 sysctl_net_inet_list_available(SYSCTL_HANDLER_ARGS)
702 {
703 	int error, cnt, linesz;
704 	struct tcp_function *f;
705 	char *buffer, *cp;
706 	size_t bufsz, outsz;
707 	bool alias;
708 
709 	cnt = 0;
710 	rw_rlock(&tcp_function_lock);
711 	TAILQ_FOREACH(f, &t_functions, tf_next) {
712 		cnt++;
713 	}
714 	rw_runlock(&tcp_function_lock);
715 
716 	bufsz = (cnt+2) * ((TCP_FUNCTION_NAME_LEN_MAX * 2) + 13) + 1;
717 	buffer = malloc(bufsz, M_TEMP, M_WAITOK);
718 
719 	error = 0;
720 	cp = buffer;
721 
722 	linesz = snprintf(cp, bufsz, "\n%-32s%c %-32s %s\n", "Stack", 'D',
723 	    "Alias", "PCB count");
724 	cp += linesz;
725 	bufsz -= linesz;
726 	outsz = linesz;
727 
728 	rw_rlock(&tcp_function_lock);
729 	TAILQ_FOREACH(f, &t_functions, tf_next) {
730 		alias = (f->tf_name != f->tf_fb->tfb_tcp_block_name);
731 		linesz = snprintf(cp, bufsz, "%-32s%c %-32s %u\n",
732 		    f->tf_fb->tfb_tcp_block_name,
733 		    (f->tf_fb == V_tcp_func_set_ptr) ? '*' : ' ',
734 		    alias ? f->tf_name : "-",
735 		    f->tf_fb->tfb_refcnt);
736 		if (linesz >= bufsz) {
737 			error = EOVERFLOW;
738 			break;
739 		}
740 		cp += linesz;
741 		bufsz -= linesz;
742 		outsz += linesz;
743 	}
744 	rw_runlock(&tcp_function_lock);
745 	if (error == 0)
746 		error = sysctl_handle_string(oidp, buffer, outsz + 1, req);
747 	free(buffer, M_TEMP);
748 	return (error);
749 }
750 
751 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, functions_available,
752     CTLFLAG_VNET | CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
753     NULL, 0, sysctl_net_inet_list_available, "A",
754     "list available TCP Function sets");
755 
756 VNET_DEFINE(int, tcp_udp_tunneling_port) = TCP_TUNNELING_PORT_DEFAULT;
757 
758 #ifdef INET
759 VNET_DEFINE(struct socket *, udp4_tun_socket) = NULL;
760 #define	V_udp4_tun_socket	VNET(udp4_tun_socket)
761 #endif
762 #ifdef INET6
763 VNET_DEFINE(struct socket *, udp6_tun_socket) = NULL;
764 #define	V_udp6_tun_socket	VNET(udp6_tun_socket)
765 #endif
766 
767 static struct sx tcpoudp_lock;
768 
769 static void
tcp_over_udp_stop(void)770 tcp_over_udp_stop(void)
771 {
772 
773 	sx_assert(&tcpoudp_lock, SA_XLOCKED);
774 
775 #ifdef INET
776 	if (V_udp4_tun_socket != NULL) {
777 		soclose(V_udp4_tun_socket);
778 		V_udp4_tun_socket = NULL;
779 	}
780 #endif
781 #ifdef INET6
782 	if (V_udp6_tun_socket != NULL) {
783 		soclose(V_udp6_tun_socket);
784 		V_udp6_tun_socket = NULL;
785 	}
786 #endif
787 }
788 
789 static int
tcp_over_udp_start(void)790 tcp_over_udp_start(void)
791 {
792 	uint16_t port;
793 	int ret;
794 #ifdef INET
795 	struct sockaddr_in sin;
796 #endif
797 #ifdef INET6
798 	struct sockaddr_in6 sin6;
799 #endif
800 
801 	sx_assert(&tcpoudp_lock, SA_XLOCKED);
802 
803 	port = V_tcp_udp_tunneling_port;
804 	if (ntohs(port) == 0) {
805 		/* Must have a port set */
806 		return (EINVAL);
807 	}
808 #ifdef INET
809 	if (V_udp4_tun_socket != NULL) {
810 		/* Already running -- must stop first */
811 		return (EALREADY);
812 	}
813 #endif
814 #ifdef INET6
815 	if (V_udp6_tun_socket != NULL) {
816 		/* Already running -- must stop first */
817 		return (EALREADY);
818 	}
819 #endif
820 #ifdef INET
821 	if ((ret = socreate(PF_INET, &V_udp4_tun_socket,
822 	    SOCK_DGRAM, IPPROTO_UDP,
823 	    curthread->td_ucred, curthread))) {
824 		tcp_over_udp_stop();
825 		return (ret);
826 	}
827 	/* Call the special UDP hook. */
828 	if ((ret = udp_set_kernel_tunneling(V_udp4_tun_socket,
829 	    tcp_recv_udp_tunneled_packet,
830 	    tcp_ctlinput_viaudp,
831 	    NULL))) {
832 		tcp_over_udp_stop();
833 		return (ret);
834 	}
835 	/* Ok, we have a socket, bind it to the port. */
836 	memset(&sin, 0, sizeof(struct sockaddr_in));
837 	sin.sin_len = sizeof(struct sockaddr_in);
838 	sin.sin_family = AF_INET;
839 	sin.sin_port = htons(port);
840 	if ((ret = sobind(V_udp4_tun_socket,
841 	    (struct sockaddr *)&sin, curthread))) {
842 		tcp_over_udp_stop();
843 		return (ret);
844 	}
845 #endif
846 #ifdef INET6
847 	if ((ret = socreate(PF_INET6, &V_udp6_tun_socket,
848 	    SOCK_DGRAM, IPPROTO_UDP,
849 	    curthread->td_ucred, curthread))) {
850 		tcp_over_udp_stop();
851 		return (ret);
852 	}
853 	/* Call the special UDP hook. */
854 	if ((ret = udp_set_kernel_tunneling(V_udp6_tun_socket,
855 	    tcp_recv_udp_tunneled_packet,
856 	    tcp6_ctlinput_viaudp,
857 	    NULL))) {
858 		tcp_over_udp_stop();
859 		return (ret);
860 	}
861 	/* Ok, we have a socket, bind it to the port. */
862 	memset(&sin6, 0, sizeof(struct sockaddr_in6));
863 	sin6.sin6_len = sizeof(struct sockaddr_in6);
864 	sin6.sin6_family = AF_INET6;
865 	sin6.sin6_port = htons(port);
866 	if ((ret = sobind(V_udp6_tun_socket,
867 	    (struct sockaddr *)&sin6, curthread))) {
868 		tcp_over_udp_stop();
869 		return (ret);
870 	}
871 #endif
872 	return (0);
873 }
874 
875 static int
sysctl_net_inet_tcp_udp_tunneling_port_check(SYSCTL_HANDLER_ARGS)876 sysctl_net_inet_tcp_udp_tunneling_port_check(SYSCTL_HANDLER_ARGS)
877 {
878 	int error;
879 	uint32_t old, new;
880 
881 	old = V_tcp_udp_tunneling_port;
882 	new = old;
883 	error = sysctl_handle_int(oidp, &new, 0, req);
884 	if ((error == 0) &&
885 	    (req->newptr != NULL)) {
886 		if ((new < TCP_TUNNELING_PORT_MIN) ||
887 		    (new > TCP_TUNNELING_PORT_MAX)) {
888 			error = EINVAL;
889 		} else {
890 			sx_xlock(&tcpoudp_lock);
891 			V_tcp_udp_tunneling_port = new;
892 			if (old != 0) {
893 				tcp_over_udp_stop();
894 			}
895 			if (new != 0) {
896 				error = tcp_over_udp_start();
897 				if (error != 0) {
898 					V_tcp_udp_tunneling_port = 0;
899 				}
900 			}
901 			sx_xunlock(&tcpoudp_lock);
902 		}
903 	}
904 	return (error);
905 }
906 
907 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, udp_tunneling_port,
908     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
909     &VNET_NAME(tcp_udp_tunneling_port),
910     0, &sysctl_net_inet_tcp_udp_tunneling_port_check, "IU",
911     "Tunneling port for tcp over udp");
912 
913 VNET_DEFINE(int, tcp_udp_tunneling_overhead) = TCP_TUNNELING_OVERHEAD_DEFAULT;
914 
915 static int
sysctl_net_inet_tcp_udp_tunneling_overhead_check(SYSCTL_HANDLER_ARGS)916 sysctl_net_inet_tcp_udp_tunneling_overhead_check(SYSCTL_HANDLER_ARGS)
917 {
918 	int error, new;
919 
920 	new = V_tcp_udp_tunneling_overhead;
921 	error = sysctl_handle_int(oidp, &new, 0, req);
922 	if (error == 0 && req->newptr) {
923 		if ((new < TCP_TUNNELING_OVERHEAD_MIN) ||
924 		    (new > TCP_TUNNELING_OVERHEAD_MAX))
925 			error = EINVAL;
926 		else
927 			V_tcp_udp_tunneling_overhead = new;
928 	}
929 	return (error);
930 }
931 
932 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, udp_tunneling_overhead,
933     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
934     &VNET_NAME(tcp_udp_tunneling_overhead),
935     0, &sysctl_net_inet_tcp_udp_tunneling_overhead_check, "IU",
936     "MSS reduction when using tcp over udp");
937 
938 /*
939  * Exports one (struct tcp_function_info) for each alias/name.
940  */
941 static int
sysctl_net_inet_list_func_info(SYSCTL_HANDLER_ARGS)942 sysctl_net_inet_list_func_info(SYSCTL_HANDLER_ARGS)
943 {
944 	int cnt, error;
945 	struct tcp_function *f;
946 	struct tcp_function_info tfi;
947 
948 	/*
949 	 * We don't allow writes.
950 	 */
951 	if (req->newptr != NULL)
952 		return (EINVAL);
953 
954 	/*
955 	 * Wire the old buffer so we can directly copy the functions to
956 	 * user space without dropping the lock.
957 	 */
958 	if (req->oldptr != NULL) {
959 		error = sysctl_wire_old_buffer(req, 0);
960 		if (error)
961 			return (error);
962 	}
963 
964 	/*
965 	 * Walk the list and copy out matching entries. If INVARIANTS
966 	 * is compiled in, also walk the list to verify the length of
967 	 * the list matches what we have recorded.
968 	 */
969 	rw_rlock(&tcp_function_lock);
970 
971 	cnt = 0;
972 #ifndef INVARIANTS
973 	if (req->oldptr == NULL) {
974 		cnt = tcp_fb_cnt;
975 		goto skip_loop;
976 	}
977 #endif
978 	TAILQ_FOREACH(f, &t_functions, tf_next) {
979 #ifdef INVARIANTS
980 		cnt++;
981 #endif
982 		if (req->oldptr != NULL) {
983 			bzero(&tfi, sizeof(tfi));
984 			tfi.tfi_refcnt = f->tf_fb->tfb_refcnt;
985 			tfi.tfi_id = f->tf_fb->tfb_id;
986 			(void)strlcpy(tfi.tfi_alias, f->tf_name,
987 			    sizeof(tfi.tfi_alias));
988 			(void)strlcpy(tfi.tfi_name,
989 			    f->tf_fb->tfb_tcp_block_name, sizeof(tfi.tfi_name));
990 			error = SYSCTL_OUT(req, &tfi, sizeof(tfi));
991 			/*
992 			 * Don't stop on error, as that is the
993 			 * mechanism we use to accumulate length
994 			 * information if the buffer was too short.
995 			 */
996 		}
997 	}
998 	KASSERT(cnt == tcp_fb_cnt,
999 	    ("%s: cnt (%d) != tcp_fb_cnt (%d)", __func__, cnt, tcp_fb_cnt));
1000 #ifndef INVARIANTS
1001 skip_loop:
1002 #endif
1003 	rw_runlock(&tcp_function_lock);
1004 	if (req->oldptr == NULL)
1005 		error = SYSCTL_OUT(req, NULL,
1006 		    (cnt + 1) * sizeof(struct tcp_function_info));
1007 
1008 	return (error);
1009 }
1010 
1011 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, function_info,
1012 	    CTLTYPE_OPAQUE | CTLFLAG_SKIP | CTLFLAG_RD | CTLFLAG_MPSAFE,
1013 	    NULL, 0, sysctl_net_inet_list_func_info, "S,tcp_function_info",
1014 	    "List TCP function block name-to-ID mappings");
1015 
1016 /*
1017  * tfb_tcp_handoff_ok() function for the default stack.
1018  * Note that we'll basically try to take all comers.
1019  */
1020 static int
tcp_default_handoff_ok(struct tcpcb * tp)1021 tcp_default_handoff_ok(struct tcpcb *tp)
1022 {
1023 
1024 	return (0);
1025 }
1026 
1027 /*
1028  * tfb_tcp_fb_init() function for the default stack.
1029  *
1030  * This handles making sure we have appropriate timers set if you are
1031  * transitioning a socket that has some amount of setup done.
1032  *
1033  * The init() fuction from the default can *never* return non-zero i.e.
1034  * it is required to always succeed since it is the stack of last resort!
1035  */
1036 static int
tcp_default_fb_init(struct tcpcb * tp,void ** ptr)1037 tcp_default_fb_init(struct tcpcb *tp, void **ptr)
1038 {
1039 	struct socket *so = tptosocket(tp);
1040 	int rexmt;
1041 
1042 	INP_WLOCK_ASSERT(tptoinpcb(tp));
1043 	/* We don't use the pointer */
1044 	*ptr = NULL;
1045 
1046 	/* Make sure we get no interesting mbuf queuing behavior */
1047 	/* All mbuf queue/ack compress flags should be off */
1048 	tcp_lro_features_off(tp);
1049 
1050 	/* Cancel the GP measurement in progress */
1051 	tp->t_flags &= ~TF_GPUTINPROG;
1052 	/* Validate the timers are not in usec, if they are convert */
1053 	tcp_change_time_units(tp, TCP_TMR_GRANULARITY_TICKS);
1054 	if ((tp->t_state == TCPS_SYN_SENT) ||
1055 	    (tp->t_state == TCPS_SYN_RECEIVED))
1056 		rexmt = tcp_rexmit_initial * tcp_backoff[tp->t_rxtshift];
1057 	else
1058 		rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
1059 	if (tp->t_rxtshift == 0)
1060 		tp->t_rxtcur = rexmt;
1061 	else
1062 		TCPT_RANGESET(tp->t_rxtcur, rexmt, tp->t_rttmin,
1063 		    tcp_rexmit_max);
1064 
1065 	/*
1066 	 * Nothing to do for ESTABLISHED or LISTEN states. And, we don't
1067 	 * know what to do for unexpected states (which includes TIME_WAIT).
1068 	 */
1069 	if (tp->t_state <= TCPS_LISTEN || tp->t_state >= TCPS_TIME_WAIT)
1070 		return (0);
1071 
1072 	/*
1073 	 * Make sure some kind of transmission timer is set if there is
1074 	 * outstanding data.
1075 	 */
1076 	if ((!TCPS_HAVEESTABLISHED(tp->t_state) || sbavail(&so->so_snd) ||
1077 	    tp->snd_una != tp->snd_max) && !(tcp_timer_active(tp, TT_REXMT) ||
1078 	    tcp_timer_active(tp, TT_PERSIST))) {
1079 		/*
1080 		 * If the session has established and it looks like it should
1081 		 * be in the persist state, set the persist timer. Otherwise,
1082 		 * set the retransmit timer.
1083 		 */
1084 		if (TCPS_HAVEESTABLISHED(tp->t_state) && tp->snd_wnd == 0 &&
1085 		    (int32_t)(tp->snd_nxt - tp->snd_una) <
1086 		    (int32_t)sbavail(&so->so_snd))
1087 			tcp_setpersist(tp);
1088 		else
1089 			tcp_timer_activate(tp, TT_REXMT, TP_RXTCUR(tp));
1090 	}
1091 
1092 	/* All non-embryonic sessions get a keepalive timer. */
1093 	if (!tcp_timer_active(tp, TT_KEEP))
1094 		tcp_timer_activate(tp, TT_KEEP,
1095 		    TCPS_HAVEESTABLISHED(tp->t_state) ? TP_KEEPIDLE(tp) :
1096 		    TP_KEEPINIT(tp));
1097 
1098 	/*
1099 	 * Make sure critical variables are initialized
1100 	 * if transitioning while in Recovery.
1101 	 */
1102 	if IN_FASTRECOVERY(tp->t_flags) {
1103 		if (tp->sackhint.recover_fs == 0)
1104 			tp->sackhint.recover_fs = max(1,
1105 			    tp->snd_nxt - tp->snd_una);
1106 	}
1107 
1108 	return (0);
1109 }
1110 
1111 /*
1112  * tfb_tcp_fb_fini() function for the default stack.
1113  *
1114  * This changes state as necessary (or prudent) to prepare for another stack
1115  * to assume responsibility for the connection.
1116  */
1117 static void
tcp_default_fb_fini(struct tcpcb * tp,int tcb_is_purged)1118 tcp_default_fb_fini(struct tcpcb *tp, int tcb_is_purged)
1119 {
1120 
1121 	INP_WLOCK_ASSERT(tptoinpcb(tp));
1122 
1123 #ifdef TCP_BLACKBOX
1124 	tcp_log_flowend(tp);
1125 #endif
1126 	tp->t_acktime = 0;
1127 	return;
1128 }
1129 
1130 MALLOC_DEFINE(M_TCPLOG, "tcplog", "TCP address and flags print buffers");
1131 MALLOC_DEFINE(M_TCPFUNCTIONS, "tcpfunc", "TCP function set memory");
1132 #ifdef TCP_REQUEST_TRK
1133 MALLOC_DEFINE(M_TCPREQTRK, "tcpreqtrk", "TCP request tracking");
1134 #endif
1135 
1136 static struct mtx isn_mtx;
1137 
1138 #define	ISN_LOCK_INIT()	mtx_init(&isn_mtx, "isn_mtx", NULL, MTX_DEF)
1139 #define	ISN_LOCK()	mtx_lock(&isn_mtx)
1140 #define	ISN_UNLOCK()	mtx_unlock(&isn_mtx)
1141 
1142 INPCBSTORAGE_DEFINE(tcpcbstor, tcpcb, "tcpinp", "tcp_inpcb", "tcphash");
1143 
1144 /*
1145  * Take a value and get the next power of 2 that doesn't overflow.
1146  * Used to size the tcp_inpcb hash buckets.
1147  */
1148 static int
maketcp_hashsize(int size)1149 maketcp_hashsize(int size)
1150 {
1151 	int hashsize;
1152 
1153 	/*
1154 	 * auto tune.
1155 	 * get the next power of 2 higher than maxsockets.
1156 	 */
1157 	hashsize = 1 << fls(size);
1158 	/* catch overflow, and just go one power of 2 smaller */
1159 	if (hashsize < size) {
1160 		hashsize = 1 << (fls(size) - 1);
1161 	}
1162 	return (hashsize);
1163 }
1164 
1165 static volatile int next_tcp_stack_id = 1;
1166 
1167 /*
1168  * Register a TCP function block with the name provided in the names
1169  * array.  (Note that this function does NOT automatically register
1170  * blk->tfb_tcp_block_name as a stack name.  Therefore, you should
1171  * explicitly include blk->tfb_tcp_block_name in the list of names if
1172  * you wish to register the stack with that name.)
1173  *
1174  * Either all name registrations will succeed or all will fail.  If
1175  * a name registration fails, the function will update the num_names
1176  * argument to point to the array index of the name that encountered
1177  * the failure.
1178  *
1179  * Returns 0 on success, or an error code on failure.
1180  */
1181 int
register_tcp_functions_as_names(struct tcp_function_block * blk,int wait,const char * names[],int * num_names)1182 register_tcp_functions_as_names(struct tcp_function_block *blk, int wait,
1183     const char *names[], int *num_names)
1184 {
1185 	struct tcp_function *f[TCP_FUNCTION_NAME_NUM_MAX];
1186 	struct tcp_function_set fs;
1187 	int error, i, num_registered;
1188 
1189 	KASSERT(names != NULL, ("%s: Called with NULL name list", __func__));
1190 	KASSERT(*num_names > 0,
1191 	    ("%s: Called with non-positive length of name list", __func__));
1192 	KASSERT(rw_initialized(&tcp_function_lock),
1193 	    ("%s: called too early", __func__));
1194 
1195 	if (*num_names > TCP_FUNCTION_NAME_NUM_MAX) {
1196 		/* Too many names. */
1197 		*num_names = 0;
1198 		return (E2BIG);
1199 	}
1200 	if ((blk->tfb_tcp_output == NULL) ||
1201 	    (blk->tfb_tcp_do_segment == NULL) ||
1202 	    (blk->tfb_tcp_ctloutput == NULL) ||
1203 	    (blk->tfb_tcp_handoff_ok == NULL) ||
1204 	    (strlen(blk->tfb_tcp_block_name) == 0)) {
1205 		/* These functions are required and a name is needed. */
1206 		*num_names = 0;
1207 		return (EINVAL);
1208 	}
1209 
1210 	for (i = 0; i < *num_names; i++) {
1211 		f[i] = malloc(sizeof(struct tcp_function), M_TCPFUNCTIONS, wait);
1212 		if (f[i] == NULL) {
1213 			while (--i >= 0)
1214 				free(f[i], M_TCPFUNCTIONS);
1215 			*num_names = 0;
1216 			return (ENOMEM);
1217 		}
1218 	}
1219 
1220 	num_registered = 0;
1221 	rw_wlock(&tcp_function_lock);
1222 	if (find_tcp_fb_locked(blk, NULL) != NULL) {
1223 		/* A TCP function block can only be registered once. */
1224 		error = EALREADY;
1225 		goto cleanup;
1226 	}
1227 	if (blk->tfb_flags & TCP_FUNC_BEING_REMOVED) {
1228 		error = EINVAL;
1229 		goto cleanup;
1230 	}
1231 	refcount_init(&blk->tfb_refcnt, 0);
1232 	blk->tfb_id = atomic_fetchadd_int(&next_tcp_stack_id, 1);
1233 	for (i = 0; i < *num_names; i++) {
1234 		(void)strlcpy(fs.function_set_name, names[i],
1235 		    sizeof(fs.function_set_name));
1236 		if (find_tcp_functions_locked(&fs) != NULL) {
1237 			/* Duplicate name space not allowed */
1238 			error = EALREADY;
1239 			goto cleanup;
1240 		}
1241 		f[i]->tf_fb = blk;
1242 		(void)strlcpy(f[i]->tf_name, names[i], sizeof(f[i]->tf_name));
1243 		TAILQ_INSERT_TAIL(&t_functions, f[i], tf_next);
1244 		tcp_fb_cnt++;
1245 		num_registered++;
1246 	}
1247 	rw_wunlock(&tcp_function_lock);
1248 	return (0);
1249 
1250 cleanup:
1251 	/* Remove the entries just added. */
1252 	for (i = 0; i < *num_names; i++) {
1253 		if (i < num_registered) {
1254 			TAILQ_REMOVE(&t_functions, f[i], tf_next);
1255 			tcp_fb_cnt--;
1256 		}
1257 		f[i]->tf_fb = NULL;
1258 		free(f[i], M_TCPFUNCTIONS);
1259 	}
1260 	rw_wunlock(&tcp_function_lock);
1261 	*num_names = num_registered;
1262 	return (error);
1263 }
1264 
1265 /*
1266  * Register a TCP function block using the name provided in the name
1267  * argument.
1268  *
1269  * Returns 0 on success, or an error code on failure.
1270  */
1271 int
register_tcp_functions_as_name(struct tcp_function_block * blk,const char * name,int wait)1272 register_tcp_functions_as_name(struct tcp_function_block *blk, const char *name,
1273     int wait)
1274 {
1275 	const char *name_list[1];
1276 	int num_names, rv;
1277 
1278 	num_names = 1;
1279 	if (name != NULL)
1280 		name_list[0] = name;
1281 	else
1282 		name_list[0] = blk->tfb_tcp_block_name;
1283 	rv = register_tcp_functions_as_names(blk, wait, name_list, &num_names);
1284 	return (rv);
1285 }
1286 
1287 /*
1288  * Register a TCP function block using the name defined in
1289  * blk->tfb_tcp_block_name.
1290  *
1291  * Returns 0 on success, or an error code on failure.
1292  */
1293 int
register_tcp_functions(struct tcp_function_block * blk,int wait)1294 register_tcp_functions(struct tcp_function_block *blk, int wait)
1295 {
1296 
1297 	return (register_tcp_functions_as_name(blk, NULL, wait));
1298 }
1299 
1300 /*
1301  * Deregister all names associated with a function block. This
1302  * functionally removes the function block from use within the system.
1303  *
1304  * When called with a true quiesce argument, mark the function block
1305  * as being removed so no more stacks will use it and determine
1306  * whether the removal would succeed.
1307  *
1308  * When called with a false quiesce argument, actually attempt the
1309  * removal.
1310  *
1311  * When called with a force argument, attempt to switch all TCBs to
1312  * use the default stack instead of returning EBUSY.
1313  *
1314  * Returns 0 on success (or if the removal would succeed), or an error
1315  * code on failure.
1316  */
1317 int
deregister_tcp_functions(struct tcp_function_block * blk,bool quiesce,bool force)1318 deregister_tcp_functions(struct tcp_function_block *blk, bool quiesce,
1319     bool force)
1320 {
1321 	struct tcp_function *f;
1322 	VNET_ITERATOR_DECL(vnet_iter);
1323 
1324 	if (blk == &tcp_def_funcblk) {
1325 		/* You can't un-register the default */
1326 		return (EPERM);
1327 	}
1328 	rw_wlock(&tcp_function_lock);
1329 	VNET_LIST_RLOCK_NOSLEEP();
1330 	VNET_FOREACH(vnet_iter) {
1331 		CURVNET_SET(vnet_iter);
1332 		if (blk == V_tcp_func_set_ptr) {
1333 			/* You can't free the current default in some vnet. */
1334 			CURVNET_RESTORE();
1335 			VNET_LIST_RUNLOCK_NOSLEEP();
1336 			rw_wunlock(&tcp_function_lock);
1337 			return (EBUSY);
1338 		}
1339 		CURVNET_RESTORE();
1340 	}
1341 	VNET_LIST_RUNLOCK_NOSLEEP();
1342 	/* Mark the block so no more stacks can use it. */
1343 	blk->tfb_flags |= TCP_FUNC_BEING_REMOVED;
1344 	/*
1345 	 * If TCBs are still attached to the stack, attempt to switch them
1346 	 * to the default stack.
1347 	 */
1348 	if (force && blk->tfb_refcnt) {
1349 		struct inpcb *inp;
1350 		struct tcpcb *tp;
1351 		VNET_ITERATOR_DECL(vnet_iter);
1352 
1353 		rw_wunlock(&tcp_function_lock);
1354 
1355 		VNET_LIST_RLOCK();
1356 		VNET_FOREACH(vnet_iter) {
1357 			CURVNET_SET(vnet_iter);
1358 			struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_tcbinfo,
1359 			    INPLOOKUP_WLOCKPCB);
1360 
1361 			while ((inp = inp_next(&inpi)) != NULL) {
1362 				tp = intotcpcb(inp);
1363 				if (tp == NULL || tp->t_fb != blk)
1364 					continue;
1365 				tcp_switch_back_to_default(tp);
1366 			}
1367 			CURVNET_RESTORE();
1368 		}
1369 		VNET_LIST_RUNLOCK();
1370 
1371 		rw_wlock(&tcp_function_lock);
1372 	}
1373 	if (blk->tfb_refcnt) {
1374 		/* TCBs still attached. */
1375 		rw_wunlock(&tcp_function_lock);
1376 		return (EBUSY);
1377 	}
1378 	if (quiesce) {
1379 		/* Skip removal. */
1380 		rw_wunlock(&tcp_function_lock);
1381 		return (0);
1382 	}
1383 	/* Remove any function names that map to this function block. */
1384 	while (find_tcp_fb_locked(blk, &f) != NULL) {
1385 		TAILQ_REMOVE(&t_functions, f, tf_next);
1386 		tcp_fb_cnt--;
1387 		f->tf_fb = NULL;
1388 		free(f, M_TCPFUNCTIONS);
1389 	}
1390 	rw_wunlock(&tcp_function_lock);
1391 	return (0);
1392 }
1393 
1394 static void
tcp_drain(void * ctx __unused,int flags __unused)1395 tcp_drain(void *ctx __unused, int flags __unused)
1396 {
1397 	struct epoch_tracker et;
1398 	VNET_ITERATOR_DECL(vnet_iter);
1399 
1400 	if (!do_tcpdrain)
1401 		return;
1402 
1403 	NET_EPOCH_ENTER(et);
1404 	VNET_LIST_RLOCK_NOSLEEP();
1405 	VNET_FOREACH(vnet_iter) {
1406 		CURVNET_SET(vnet_iter);
1407 		struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_tcbinfo,
1408 		    INPLOOKUP_WLOCKPCB);
1409 		struct inpcb *inpb;
1410 		struct tcpcb *tcpb;
1411 
1412 	/*
1413 	 * Walk the tcpbs, if existing, and flush the reassembly queue,
1414 	 * if there is one...
1415 	 * XXX: The "Net/3" implementation doesn't imply that the TCP
1416 	 *      reassembly queue should be flushed, but in a situation
1417 	 *	where we're really low on mbufs, this is potentially
1418 	 *	useful.
1419 	 */
1420 		while ((inpb = inp_next(&inpi)) != NULL) {
1421 			if ((tcpb = intotcpcb(inpb)) != NULL) {
1422 				tcp_reass_flush(tcpb);
1423 				tcp_clean_sackreport(tcpb);
1424 #ifdef TCP_BLACKBOX
1425 				tcp_log_drain(tcpb);
1426 #endif
1427 			}
1428 		}
1429 		CURVNET_RESTORE();
1430 	}
1431 	VNET_LIST_RUNLOCK_NOSLEEP();
1432 	NET_EPOCH_EXIT(et);
1433 }
1434 
1435 static void
tcp_vnet_init(void * arg __unused)1436 tcp_vnet_init(void *arg __unused)
1437 {
1438 
1439 #ifdef TCP_HHOOK
1440 	if (hhook_head_register(HHOOK_TYPE_TCP, HHOOK_TCP_EST_IN,
1441 	    &V_tcp_hhh[HHOOK_TCP_EST_IN], HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
1442 		printf("%s: WARNING: unable to register helper hook\n", __func__);
1443 	if (hhook_head_register(HHOOK_TYPE_TCP, HHOOK_TCP_EST_OUT,
1444 	    &V_tcp_hhh[HHOOK_TCP_EST_OUT], HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
1445 		printf("%s: WARNING: unable to register helper hook\n", __func__);
1446 #endif
1447 #ifdef STATS
1448 	if (tcp_stats_init())
1449 		printf("%s: WARNING: unable to initialise TCP stats\n",
1450 		    __func__);
1451 #endif
1452 	in_pcbinfo_init(&V_tcbinfo, &tcpcbstor, tcp_tcbhashsize,
1453 	    tcp_tcbhashsize, tcp_tcbhashsize);
1454 
1455 	syncache_init();
1456 	tcp_hc_init();
1457 
1458 	TUNABLE_INT_FETCH("net.inet.tcp.sack.enable", &V_tcp_do_sack);
1459 
1460 	tcp_fastopen_vnet_init();
1461 
1462 	COUNTER_ARRAY_ALLOC(V_tcps_states, TCP_NSTATES, M_WAITOK);
1463 	VNET_PCPUSTAT_ALLOC(tcpstat, M_WAITOK);
1464 
1465 	V_tcp_msl = TCPTV_MSL;
1466 	V_tcp_msl_local = TCPTV_MSL_LOCAL;
1467 	arc4rand(&V_ts_offset_secret, sizeof(V_ts_offset_secret), 0);
1468 }
1469 VNET_SYSINIT(tcp_vnet_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH,
1470     tcp_vnet_init, NULL);
1471 
1472 static void
tcp_init(void * arg __unused)1473 tcp_init(void *arg __unused)
1474 {
1475 	int hashsize;
1476 
1477 	tcp_reass_global_init();
1478 
1479 	/* XXX virtualize those below? */
1480 	tcp_delacktime = TCPTV_DELACK;
1481 	tcp_keepinit = TCPTV_KEEP_INIT;
1482 	tcp_keepidle = TCPTV_KEEP_IDLE;
1483 	tcp_keepintvl = TCPTV_KEEPINTVL;
1484 	tcp_maxpersistidle = TCPTV_KEEP_IDLE;
1485 	tcp_rexmit_initial = TCPTV_RTOBASE;
1486 	tcp_rexmit_min = TCPTV_MIN;
1487 	tcp_rexmit_max = TCPTV_REXMTMAX;
1488 	tcp_persmin = TCPTV_PERSMIN;
1489 	tcp_persmax = TCPTV_PERSMAX;
1490 	tcp_rexmit_slop = TCPTV_CPU_VAR;
1491 	tcp_finwait2_timeout = TCPTV_FINWAIT2_TIMEOUT;
1492 
1493 	/* Setup the tcp function block list */
1494 	TAILQ_INIT(&t_functions);
1495 	rw_init(&tcp_function_lock, "tcp_func_lock");
1496 	register_tcp_functions(&tcp_def_funcblk, M_WAITOK);
1497 	sx_init(&tcpoudp_lock, "TCP over UDP configuration");
1498 #ifdef TCP_BLACKBOX
1499 	/* Initialize the TCP logging data. */
1500 	tcp_log_init();
1501 #endif
1502 
1503 	if (tcp_soreceive_stream) {
1504 #ifdef INET
1505 		tcp_protosw.pr_soreceive = soreceive_stream;
1506 #endif
1507 #ifdef INET6
1508 		tcp6_protosw.pr_soreceive = soreceive_stream;
1509 #endif /* INET6 */
1510 	}
1511 
1512 #ifdef INET6
1513 	max_protohdr_grow(sizeof(struct ip6_hdr) + sizeof(struct tcphdr));
1514 #else /* INET6 */
1515 	max_protohdr_grow(sizeof(struct tcpiphdr));
1516 #endif /* INET6 */
1517 
1518 	ISN_LOCK_INIT();
1519 	EVENTHANDLER_REGISTER(vm_lowmem, tcp_drain, NULL, LOWMEM_PRI_DEFAULT);
1520 	EVENTHANDLER_REGISTER(mbuf_lowmem, tcp_drain, NULL, LOWMEM_PRI_DEFAULT);
1521 
1522 	tcp_inp_lro_direct_queue = counter_u64_alloc(M_WAITOK);
1523 	tcp_inp_lro_wokeup_queue = counter_u64_alloc(M_WAITOK);
1524 	tcp_inp_lro_compressed = counter_u64_alloc(M_WAITOK);
1525 	tcp_inp_lro_locks_taken = counter_u64_alloc(M_WAITOK);
1526 	tcp_extra_mbuf = counter_u64_alloc(M_WAITOK);
1527 	tcp_would_have_but = counter_u64_alloc(M_WAITOK);
1528 	tcp_comp_total = counter_u64_alloc(M_WAITOK);
1529 	tcp_uncomp_total = counter_u64_alloc(M_WAITOK);
1530 	tcp_bad_csums = counter_u64_alloc(M_WAITOK);
1531 	tcp_pacing_failures = counter_u64_alloc(M_WAITOK);
1532 	tcp_dgp_failures = counter_u64_alloc(M_WAITOK);
1533 
1534 	hashsize = tcp_tcbhashsize;
1535 	if (hashsize == 0) {
1536 		/*
1537 		 * Auto tune the hash size based on maxsockets.
1538 		 * A perfect hash would have a 1:1 mapping
1539 		 * (hashsize = maxsockets) however it's been
1540 		 * suggested that O(2) average is better.
1541 		 */
1542 		hashsize = maketcp_hashsize(maxsockets / 4);
1543 		/*
1544 		 * Our historical default is 512,
1545 		 * do not autotune lower than this.
1546 		 */
1547 		if (hashsize < 512)
1548 			hashsize = 512;
1549 		if (bootverbose)
1550 			printf("%s: %s auto tuned to %d\n", __func__,
1551 			    "net.inet.tcp.tcbhashsize", hashsize);
1552 	}
1553 	/*
1554 	 * We require a hashsize to be a power of two.
1555 	 * Previously if it was not a power of two we would just reset it
1556 	 * back to 512, which could be a nasty surprise if you did not notice
1557 	 * the error message.
1558 	 * Instead what we do is clip it to the closest power of two lower
1559 	 * than the specified hash value.
1560 	 */
1561 	if (!powerof2(hashsize)) {
1562 		int oldhashsize = hashsize;
1563 
1564 		hashsize = maketcp_hashsize(hashsize);
1565 		/* prevent absurdly low value */
1566 		if (hashsize < 16)
1567 			hashsize = 16;
1568 		printf("%s: WARNING: TCB hash size not a power of 2, "
1569 		    "clipped from %d to %d.\n", __func__, oldhashsize,
1570 		    hashsize);
1571 	}
1572 	tcp_tcbhashsize = hashsize;
1573 
1574 #ifdef INET
1575 	IPPROTO_REGISTER(IPPROTO_TCP, tcp_input, tcp_ctlinput);
1576 #endif
1577 #ifdef INET6
1578 	IP6PROTO_REGISTER(IPPROTO_TCP, tcp6_input, tcp6_ctlinput);
1579 #endif
1580 
1581 	tcp_fastopen_init();
1582 	tcp_sack_hole_zone = uma_zcreate("sackhole", sizeof(struct sackhole),
1583 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1584 }
1585 SYSINIT(tcp_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, tcp_init, NULL);
1586 
1587 #ifdef VIMAGE
1588 static void
tcp_vnet_destroy(void * unused __unused)1589 tcp_vnet_destroy(void *unused __unused)
1590 {
1591 #ifdef TCP_HHOOK
1592 	int error;
1593 #endif
1594 
1595 	tcp_hc_destroy();
1596 	syncache_destroy();
1597 	in_pcbinfo_destroy(&V_tcbinfo);
1598 
1599 	/*
1600 	 * Cannot free the zone until all tcpcbs are released as we attach
1601 	 * the allocations to them.
1602 	 */
1603 	tcp_fastopen_vnet_destroy();
1604 
1605 	COUNTER_ARRAY_FREE(V_tcps_states, TCP_NSTATES);
1606 	VNET_PCPUSTAT_FREE(tcpstat);
1607 
1608 #ifdef TCP_HHOOK
1609 	error = hhook_head_deregister(V_tcp_hhh[HHOOK_TCP_EST_IN]);
1610 	if (error != 0) {
1611 		printf("%s: WARNING: unable to deregister helper hook "
1612 		    "type=%d, id=%d: error %d returned\n", __func__,
1613 		    HHOOK_TYPE_TCP, HHOOK_TCP_EST_IN, error);
1614 	}
1615 	error = hhook_head_deregister(V_tcp_hhh[HHOOK_TCP_EST_OUT]);
1616 	if (error != 0) {
1617 		printf("%s: WARNING: unable to deregister helper hook "
1618 		    "type=%d, id=%d: error %d returned\n", __func__,
1619 		    HHOOK_TYPE_TCP, HHOOK_TCP_EST_OUT, error);
1620 	}
1621 #endif
1622 }
1623 VNET_SYSUNINIT(tcp, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH, tcp_vnet_destroy,
1624     NULL);
1625 #endif
1626 
1627 /*
1628  * Fill in the IP and TCP headers for an outgoing packet, given the tcpcb.
1629  * tcp_template used to store this data in mbufs, but we now recopy it out
1630  * of the tcpcb each time to conserve mbufs.
1631  */
1632 void
tcpip_fillheaders(struct inpcb * inp,uint16_t port,void * ip_ptr,void * tcp_ptr)1633 tcpip_fillheaders(struct inpcb *inp, uint16_t port, void *ip_ptr, void *tcp_ptr)
1634 {
1635 	struct tcphdr *th = (struct tcphdr *)tcp_ptr;
1636 
1637 	INP_WLOCK_ASSERT(inp);
1638 
1639 #ifdef INET6
1640 	if ((inp->inp_vflag & INP_IPV6) != 0) {
1641 		struct ip6_hdr *ip6;
1642 
1643 		ip6 = (struct ip6_hdr *)ip_ptr;
1644 		ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) |
1645 			(inp->inp_flow & IPV6_FLOWINFO_MASK);
1646 		ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) |
1647 			(IPV6_VERSION & IPV6_VERSION_MASK);
1648 		if (port == 0)
1649 			ip6->ip6_nxt = IPPROTO_TCP;
1650 		else
1651 			ip6->ip6_nxt = IPPROTO_UDP;
1652 		ip6->ip6_plen = htons(sizeof(struct tcphdr));
1653 		ip6->ip6_src = inp->in6p_laddr;
1654 		ip6->ip6_dst = inp->in6p_faddr;
1655 	}
1656 #endif /* INET6 */
1657 #if defined(INET6) && defined(INET)
1658 	else
1659 #endif
1660 #ifdef INET
1661 	{
1662 		struct ip *ip;
1663 
1664 		ip = (struct ip *)ip_ptr;
1665 		ip->ip_v = IPVERSION;
1666 		ip->ip_hl = 5;
1667 		ip->ip_tos = inp->inp_ip_tos;
1668 		ip->ip_len = 0;
1669 		ip->ip_id = 0;
1670 		ip->ip_off = 0;
1671 		ip->ip_ttl = inp->inp_ip_ttl;
1672 		ip->ip_sum = 0;
1673 		if (port == 0)
1674 			ip->ip_p = IPPROTO_TCP;
1675 		else
1676 			ip->ip_p = IPPROTO_UDP;
1677 		ip->ip_src = inp->inp_laddr;
1678 		ip->ip_dst = inp->inp_faddr;
1679 	}
1680 #endif /* INET */
1681 	th->th_sport = inp->inp_lport;
1682 	th->th_dport = inp->inp_fport;
1683 	th->th_seq = 0;
1684 	th->th_ack = 0;
1685 	th->th_off = 5;
1686 	tcp_set_flags(th, 0);
1687 	th->th_win = 0;
1688 	th->th_urp = 0;
1689 	th->th_sum = 0;		/* in_pseudo() is called later for ipv4 */
1690 }
1691 
1692 /*
1693  * Create template to be used to send tcp packets on a connection.
1694  * Allocates an mbuf and fills in a skeletal tcp/ip header.  The only
1695  * use for this function is in keepalives, which use tcp_respond.
1696  */
1697 struct tcptemp *
tcpip_maketemplate(struct inpcb * inp)1698 tcpip_maketemplate(struct inpcb *inp)
1699 {
1700 	struct tcptemp *t;
1701 
1702 	t = malloc(sizeof(*t), M_TEMP, M_NOWAIT);
1703 	if (t == NULL)
1704 		return (NULL);
1705 	tcpip_fillheaders(inp, 0, (void *)&t->tt_ipgen, (void *)&t->tt_t);
1706 	return (t);
1707 }
1708 
1709 /*
1710  * Send a single message to the TCP at address specified by
1711  * the given TCP/IP header.  If m == NULL, then we make a copy
1712  * of the tcpiphdr at th and send directly to the addressed host.
1713  * This is used to force keep alive messages out using the TCP
1714  * template for a connection.  If flags are given then we send
1715  * a message back to the TCP which originated the segment th,
1716  * and discard the mbuf containing it and any other attached mbufs.
1717  *
1718  * In any case the ack and sequence number of the transmitted
1719  * segment are as specified by the parameters.
1720  *
1721  * NOTE: If m != NULL, then th must point to *inside* the mbuf.
1722  */
1723 
1724 void
tcp_respond(struct tcpcb * tp,void * ipgen,struct tcphdr * th,struct mbuf * m,tcp_seq ack,tcp_seq seq,uint16_t flags)1725 tcp_respond(struct tcpcb *tp, void *ipgen, struct tcphdr *th, struct mbuf *m,
1726     tcp_seq ack, tcp_seq seq, uint16_t flags)
1727 {
1728 	struct tcpopt to;
1729 	struct inpcb *inp;
1730 	struct ip *ip;
1731 	struct mbuf *optm;
1732 	struct udphdr *uh = NULL;
1733 	struct tcphdr *nth;
1734 	struct tcp_log_buffer *lgb;
1735 	u_char *optp;
1736 #ifdef INET6
1737 	struct ip6_hdr *ip6;
1738 	int isipv6;
1739 #endif /* INET6 */
1740 	int optlen, tlen, win, ulen;
1741 	int ect = 0;
1742 	bool incl_opts;
1743 	uint16_t port;
1744 	int output_ret;
1745 #ifdef INVARIANTS
1746 	int thflags = tcp_get_flags(th);
1747 #endif
1748 
1749 	KASSERT(tp != NULL || m != NULL, ("tcp_respond: tp and m both NULL"));
1750 	NET_EPOCH_ASSERT();
1751 
1752 #ifdef INET6
1753 	isipv6 = ((struct ip *)ipgen)->ip_v == (IPV6_VERSION >> 4);
1754 	ip6 = ipgen;
1755 #endif /* INET6 */
1756 	ip = ipgen;
1757 
1758 	if (tp != NULL) {
1759 		inp = tptoinpcb(tp);
1760 		INP_LOCK_ASSERT(inp);
1761 	} else
1762 		inp = NULL;
1763 
1764 	if (m != NULL) {
1765 #ifdef INET6
1766 		if (isipv6 && ip6 && (ip6->ip6_nxt == IPPROTO_UDP))
1767 			port = m->m_pkthdr.tcp_tun_port;
1768 		else
1769 #endif
1770 		if (ip && (ip->ip_p == IPPROTO_UDP))
1771 			port = m->m_pkthdr.tcp_tun_port;
1772 		else
1773 			port = 0;
1774 	} else
1775 		port = tp->t_port;
1776 
1777 	incl_opts = false;
1778 	win = 0;
1779 	if (tp != NULL) {
1780 		if (!(flags & TH_RST)) {
1781 			win = sbspace(&inp->inp_socket->so_rcv);
1782 			if (win > TCP_MAXWIN << tp->rcv_scale)
1783 				win = TCP_MAXWIN << tp->rcv_scale;
1784 		}
1785 		if ((tp->t_flags & TF_NOOPT) == 0)
1786 			incl_opts = true;
1787 	}
1788 	if (m == NULL) {
1789 		m = m_gethdr(M_NOWAIT, MT_DATA);
1790 		if (m == NULL)
1791 			return;
1792 		m->m_data += max_linkhdr;
1793 #ifdef INET6
1794 		if (isipv6) {
1795 			bcopy(ip6, mtod(m, char *), sizeof(struct ip6_hdr));
1796 			ip6 = mtod(m, struct ip6_hdr *);
1797 			nth = (struct tcphdr *)(ip6 + 1);
1798 			if (port) {
1799 				/* Insert a UDP header */
1800 				uh = (struct udphdr *)nth;
1801 				uh->uh_sport = htons(V_tcp_udp_tunneling_port);
1802 				uh->uh_dport = port;
1803 				nth = (struct tcphdr *)(uh + 1);
1804 			}
1805 		} else
1806 #endif /* INET6 */
1807 		{
1808 			bcopy(ip, mtod(m, char *), sizeof(struct ip));
1809 			ip = mtod(m, struct ip *);
1810 			nth = (struct tcphdr *)(ip + 1);
1811 			if (port) {
1812 				/* Insert a UDP header */
1813 				uh = (struct udphdr *)nth;
1814 				uh->uh_sport = htons(V_tcp_udp_tunneling_port);
1815 				uh->uh_dport = port;
1816 				nth = (struct tcphdr *)(uh + 1);
1817 			}
1818 		}
1819 		bcopy(th, nth, sizeof(struct tcphdr));
1820 		flags = TH_ACK;
1821 	} else if ((!M_WRITABLE(m)) || (port != 0)) {
1822 		struct mbuf *n;
1823 
1824 		/* Can't reuse 'm', allocate a new mbuf. */
1825 		n = m_gethdr(M_NOWAIT, MT_DATA);
1826 		if (n == NULL) {
1827 			m_freem(m);
1828 			return;
1829 		}
1830 
1831 		if (!m_dup_pkthdr(n, m, M_NOWAIT)) {
1832 			m_freem(m);
1833 			m_freem(n);
1834 			return;
1835 		}
1836 
1837 		n->m_data += max_linkhdr;
1838 		/* m_len is set later */
1839 #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
1840 #ifdef INET6
1841 		if (isipv6) {
1842 			bcopy(ip6, mtod(n, char *), sizeof(struct ip6_hdr));
1843 			ip6 = mtod(n, struct ip6_hdr *);
1844 			xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
1845 			nth = (struct tcphdr *)(ip6 + 1);
1846 			if (port) {
1847 				/* Insert a UDP header */
1848 				uh = (struct udphdr *)nth;
1849 				uh->uh_sport = htons(V_tcp_udp_tunneling_port);
1850 				uh->uh_dport = port;
1851 				nth = (struct tcphdr *)(uh + 1);
1852 			}
1853 		} else
1854 #endif /* INET6 */
1855 		{
1856 			bcopy(ip, mtod(n, char *), sizeof(struct ip));
1857 			ip = mtod(n, struct ip *);
1858 			xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, uint32_t);
1859 			nth = (struct tcphdr *)(ip + 1);
1860 			if (port) {
1861 				/* Insert a UDP header */
1862 				uh = (struct udphdr *)nth;
1863 				uh->uh_sport = htons(V_tcp_udp_tunneling_port);
1864 				uh->uh_dport = port;
1865 				nth = (struct tcphdr *)(uh + 1);
1866 			}
1867 		}
1868 		bcopy(th, nth, sizeof(struct tcphdr));
1869 		xchg(nth->th_dport, nth->th_sport, uint16_t);
1870 		th = nth;
1871 		m_freem(m);
1872 		m = n;
1873 	} else {
1874 		/*
1875 		 *  reuse the mbuf.
1876 		 * XXX MRT We inherit the FIB, which is lucky.
1877 		 */
1878 		m_freem(m->m_next);
1879 		m->m_next = NULL;
1880 		m->m_data = ipgen;
1881 		/* clear any receive flags for proper bpf timestamping */
1882 		m->m_flags &= ~(M_TSTMP | M_TSTMP_LRO);
1883 		/* m_len is set later */
1884 #ifdef INET6
1885 		if (isipv6) {
1886 			xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
1887 			nth = (struct tcphdr *)(ip6 + 1);
1888 		} else
1889 #endif /* INET6 */
1890 		{
1891 			xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, uint32_t);
1892 			nth = (struct tcphdr *)(ip + 1);
1893 		}
1894 		if (th != nth) {
1895 			/*
1896 			 * this is usually a case when an extension header
1897 			 * exists between the IPv6 header and the
1898 			 * TCP header.
1899 			 */
1900 			nth->th_sport = th->th_sport;
1901 			nth->th_dport = th->th_dport;
1902 		}
1903 		xchg(nth->th_dport, nth->th_sport, uint16_t);
1904 #undef xchg
1905 	}
1906 	tlen = 0;
1907 #ifdef INET6
1908 	if (isipv6)
1909 		tlen = sizeof (struct ip6_hdr) + sizeof (struct tcphdr);
1910 #endif
1911 #if defined(INET) && defined(INET6)
1912 	else
1913 #endif
1914 #ifdef INET
1915 		tlen = sizeof (struct tcpiphdr);
1916 #endif
1917 	if (port)
1918 		tlen += sizeof (struct udphdr);
1919 #ifdef INVARIANTS
1920 	m->m_len = 0;
1921 	KASSERT(M_TRAILINGSPACE(m) >= tlen,
1922 	    ("Not enough trailing space for message (m=%p, need=%d, have=%ld)",
1923 	    m, tlen, (long)M_TRAILINGSPACE(m)));
1924 #endif
1925 	m->m_len = tlen;
1926 	to.to_flags = 0;
1927 	if (incl_opts) {
1928 		ect = tcp_ecn_output_established(tp, &flags, 0, false);
1929 		/* Make sure we have room. */
1930 		if (M_TRAILINGSPACE(m) < TCP_MAXOLEN) {
1931 			m->m_next = m_get(M_NOWAIT, MT_DATA);
1932 			if (m->m_next) {
1933 				optp = mtod(m->m_next, u_char *);
1934 				optm = m->m_next;
1935 			} else
1936 				incl_opts = false;
1937 		} else {
1938 			optp = (u_char *) (nth + 1);
1939 			optm = m;
1940 		}
1941 	}
1942 	if (incl_opts) {
1943 		/* Timestamps. */
1944 		if (tp->t_flags & TF_RCVD_TSTMP) {
1945 			to.to_tsval = tcp_ts_getticks() + tp->ts_offset;
1946 			to.to_tsecr = tp->ts_recent;
1947 			to.to_flags |= TOF_TS;
1948 		}
1949 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1950 		/* TCP-MD5 (RFC2385). */
1951 		if (tp->t_flags & TF_SIGNATURE)
1952 			to.to_flags |= TOF_SIGNATURE;
1953 #endif
1954 		/* Add the options. */
1955 		tlen += optlen = tcp_addoptions(&to, optp);
1956 
1957 		/* Update m_len in the correct mbuf. */
1958 		optm->m_len += optlen;
1959 	} else
1960 		optlen = 0;
1961 #ifdef INET6
1962 	if (isipv6) {
1963 		if (uh) {
1964 			ulen = tlen - sizeof(struct ip6_hdr);
1965 			uh->uh_ulen = htons(ulen);
1966 		}
1967 		ip6->ip6_flow = htonl(ect << IPV6_FLOWLABEL_LEN);
1968 		ip6->ip6_vfc = IPV6_VERSION;
1969 		if (port)
1970 			ip6->ip6_nxt = IPPROTO_UDP;
1971 		else
1972 			ip6->ip6_nxt = IPPROTO_TCP;
1973 		ip6->ip6_plen = htons(tlen - sizeof(*ip6));
1974 	}
1975 #endif
1976 #if defined(INET) && defined(INET6)
1977 	else
1978 #endif
1979 #ifdef INET
1980 	{
1981 		if (uh) {
1982 			ulen = tlen - sizeof(struct ip);
1983 			uh->uh_ulen = htons(ulen);
1984 		}
1985 		ip->ip_len = htons(tlen);
1986 		if (inp != NULL) {
1987 			ip->ip_tos = inp->inp_ip_tos & ~IPTOS_ECN_MASK;
1988 			ip->ip_ttl = inp->inp_ip_ttl;
1989 		} else {
1990 			ip->ip_tos = 0;
1991 			ip->ip_ttl = V_ip_defttl;
1992 		}
1993 		ip->ip_tos |= ect;
1994 		if (port) {
1995 			ip->ip_p = IPPROTO_UDP;
1996 		} else {
1997 			ip->ip_p = IPPROTO_TCP;
1998 		}
1999 		if (V_path_mtu_discovery)
2000 			ip->ip_off |= htons(IP_DF);
2001 	}
2002 #endif
2003 	m->m_pkthdr.len = tlen;
2004 	m->m_pkthdr.rcvif = NULL;
2005 #ifdef MAC
2006 	if (inp != NULL) {
2007 		/*
2008 		 * Packet is associated with a socket, so allow the
2009 		 * label of the response to reflect the socket label.
2010 		 */
2011 		INP_LOCK_ASSERT(inp);
2012 		mac_inpcb_create_mbuf(inp, m);
2013 	} else {
2014 		/*
2015 		 * Packet is not associated with a socket, so possibly
2016 		 * update the label in place.
2017 		 */
2018 		mac_netinet_tcp_reply(m);
2019 	}
2020 #endif
2021 	nth->th_seq = htonl(seq);
2022 	nth->th_ack = htonl(ack);
2023 	nth->th_off = (sizeof (struct tcphdr) + optlen) >> 2;
2024 	tcp_set_flags(nth, flags);
2025 	if (tp && (flags & TH_RST)) {
2026 		/* Log the reset */
2027 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
2028 	}
2029 	if (tp != NULL)
2030 		nth->th_win = htons((u_short) (win >> tp->rcv_scale));
2031 	else
2032 		nth->th_win = htons((u_short)win);
2033 	nth->th_urp = 0;
2034 
2035 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
2036 	if (to.to_flags & TOF_SIGNATURE) {
2037 		if (!TCPMD5_ENABLED() ||
2038 		    TCPMD5_OUTPUT(m, nth, to.to_signature) != 0) {
2039 			m_freem(m);
2040 			return;
2041 		}
2042 	}
2043 #endif
2044 
2045 #ifdef INET6
2046 	if (isipv6) {
2047 		if (port) {
2048 			m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
2049 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
2050 			uh->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
2051 			nth->th_sum = 0;
2052 		} else {
2053 			m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
2054 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2055 			nth->th_sum = in6_cksum_pseudo(ip6,
2056 			    tlen - sizeof(struct ip6_hdr), IPPROTO_TCP, 0);
2057 		}
2058 		ip6->ip6_hlim = in6_selecthlim(inp, NULL);
2059 	}
2060 #endif /* INET6 */
2061 #if defined(INET6) && defined(INET)
2062 	else
2063 #endif
2064 #ifdef INET
2065 	{
2066 		if (port) {
2067 			uh->uh_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
2068 			    htons(ulen + IPPROTO_UDP));
2069 			m->m_pkthdr.csum_flags = CSUM_UDP;
2070 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
2071 			nth->th_sum = 0;
2072 		} else {
2073 			m->m_pkthdr.csum_flags = CSUM_TCP;
2074 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2075 			nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
2076 			    htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p)));
2077 		}
2078 	}
2079 #endif /* INET */
2080 	TCP_PROBE3(debug__output, tp, th, m);
2081 	if (flags & TH_RST)
2082 		TCP_PROBE5(accept__refused, NULL, NULL, m, tp, nth);
2083 	lgb = NULL;
2084 	if ((tp != NULL) && tcp_bblogging_on(tp)) {
2085 		if (INP_WLOCKED(inp)) {
2086 			union tcp_log_stackspecific log;
2087 			struct timeval tv;
2088 
2089 			memset(&log, 0, sizeof(log));
2090 			log.u_bbr.inhpts = tcp_in_hpts(tp);
2091 			log.u_bbr.flex8 = 4;
2092 			log.u_bbr.pkts_out = tp->t_maxseg;
2093 			log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2094 			log.u_bbr.delivered = 0;
2095 			lgb = tcp_log_event(tp, nth, NULL, NULL, TCP_LOG_OUT,
2096 			    ERRNO_UNK, 0, &log, false, NULL, NULL, 0, &tv);
2097 		} else {
2098 			/*
2099 			 * We can not log the packet, since we only own the
2100 			 * read lock, but a write lock is needed. The read lock
2101 			 * is not upgraded to a write lock, since only getting
2102 			 * the read lock was done intentionally to improve the
2103 			 * handling of SYN flooding attacks.
2104 			 * This happens only for pure SYN segments received in
2105 			 * the initial CLOSED state, or received in a more
2106 			 * advanced state than listen and the UDP encapsulation
2107 			 * port is unexpected.
2108 			 * The incoming SYN segments do not really belong to
2109 			 * the TCP connection and the handling does not change
2110 			 * the state of the TCP connection. Therefore, the
2111 			 * sending of the RST segments is not logged. Please
2112 			 * note that also the incoming SYN segments are not
2113 			 * logged.
2114 			 *
2115 			 * The following code ensures that the above description
2116 			 * is and stays correct.
2117 			 */
2118 			KASSERT((thflags & (TH_ACK|TH_SYN)) == TH_SYN &&
2119 			    (tp->t_state == TCPS_CLOSED ||
2120 			    (tp->t_state > TCPS_LISTEN && tp->t_port != port)),
2121 			    ("%s: Logging of TCP segment with flags 0x%b and "
2122 			    "UDP encapsulation port %u skipped in state %s",
2123 			    __func__, thflags, PRINT_TH_FLAGS,
2124 			    ntohs(port), tcpstates[tp->t_state]));
2125 		}
2126 	}
2127 
2128 	if (flags & TH_ACK)
2129 		TCPSTAT_INC(tcps_sndacks);
2130 	else if (flags & (TH_SYN|TH_FIN|TH_RST))
2131 		TCPSTAT_INC(tcps_sndctrl);
2132 	TCPSTAT_INC(tcps_sndtotal);
2133 
2134 #ifdef INET6
2135 	if (isipv6) {
2136 		TCP_PROBE5(send, NULL, tp, ip6, tp, nth);
2137 		output_ret = ip6_output(m, inp ? inp->in6p_outputopts : NULL,
2138 		    NULL, 0, NULL, NULL, inp);
2139 	}
2140 #endif /* INET6 */
2141 #if defined(INET) && defined(INET6)
2142 	else
2143 #endif
2144 #ifdef INET
2145 	{
2146 		TCP_PROBE5(send, NULL, tp, ip, tp, nth);
2147 		output_ret = ip_output(m, NULL, NULL, 0, NULL, inp);
2148 	}
2149 #endif
2150 	if (lgb != NULL)
2151 		lgb->tlb_errno = output_ret;
2152 }
2153 
2154 /*
2155  * Check that no more than V_tcp_ack_war_cnt per V_tcp_ack_war_time_window
2156  * are sent. *epoch_end is the end of the current epoch and is updated, if the
2157  * current epoch ended in the past. *ack_cnt is the counter used during the
2158  * current epoch. It might be reset and incremented.
2159  * The function returns true if a challenge ACK should be sent.
2160  */
2161 bool
tcp_challenge_ack_check(sbintime_t * epoch_end,uint32_t * ack_cnt)2162 tcp_challenge_ack_check(sbintime_t *epoch_end, uint32_t *ack_cnt)
2163 {
2164 	sbintime_t now;
2165 
2166 	/*
2167 	 * The sending of a challenge ACK could be triggered by a blind attacker
2168 	 * to detect an existing TCP connection. To mitigate that, increment
2169 	 * also the global counter which would be incremented if the attacker
2170 	 * would have guessed wrongly.
2171 	 */
2172 	(void)badport_bandlim(BANDLIM_TCP_RST);
2173 
2174 	if (V_tcp_ack_war_time_window == 0 || V_tcp_ack_war_cnt == 0) {
2175 		/* ACK war protection is disabled. */
2176 		return (true);
2177 	} else {
2178 		/* Start new epoch, if the previous one is already over. */
2179 		now = getsbinuptime();
2180 		if (*epoch_end < now) {
2181 			*ack_cnt = 0;
2182 			*epoch_end = now + V_tcp_ack_war_time_window * SBT_1MS;
2183 		}
2184 		/*
2185 		 * Send a challenge ACK, if less than tcp_ack_war_cnt have been
2186 		 * sent in the current epoch.
2187 		 */
2188 		if (*ack_cnt < V_tcp_ack_war_cnt) {
2189 			(*ack_cnt)++;
2190 			return (true);
2191 		} else {
2192 			return (false);
2193 		}
2194 	}
2195 }
2196 
2197 /*
2198  * Send a challenge ack (no data, no SACK option), but not more than
2199  * V_tcp_ack_war_cnt per V_tcp_ack_war_time_window (per TCP connection).
2200  */
2201 void
tcp_send_challenge_ack(struct tcpcb * tp,struct tcphdr * th,struct mbuf * m)2202 tcp_send_challenge_ack(struct tcpcb *tp, struct tcphdr *th, struct mbuf *m)
2203 {
2204 	if (tcp_challenge_ack_check(&tp->t_challenge_ack_end,
2205 	    &tp->t_challenge_ack_cnt)) {
2206 		tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt,
2207 		    tp->snd_nxt, TH_ACK);
2208 		tp->last_ack_sent = tp->rcv_nxt;
2209 	} else {
2210 		m_freem(m);
2211 	}
2212 }
2213 
2214 /*
2215  * Create a new TCP control block, making an empty reassembly queue and hooking
2216  * it to the argument protocol control block.  The `inp' parameter must have
2217  * come from the zone allocator set up by tcpcbstor declaration.
2218  * The caller can provide a pointer to a tcpcb of the listener to inherit the
2219  * TCP function block from the listener.
2220  */
2221 struct tcpcb *
tcp_newtcpcb(struct inpcb * inp,struct tcpcb * listening_tcb)2222 tcp_newtcpcb(struct inpcb *inp, struct tcpcb *listening_tcb)
2223 {
2224 	struct tcpcb *tp = intotcpcb(inp);
2225 #ifdef INET6
2226 	int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
2227 #endif /* INET6 */
2228 
2229 	/*
2230 	 * Historically allocation was done with M_ZERO.  There is a lot of
2231 	 * code that rely on that.  For now take safe approach and zero whole
2232 	 * tcpcb.  This definitely can be optimized.
2233 	 */
2234 	bzero(&tp->t_start_zero, t_zero_size);
2235 
2236 	/* Initialise cc_var struct for this tcpcb. */
2237 	tp->t_ccv.tp = tp;
2238 	rw_rlock(&tcp_function_lock);
2239 	if (listening_tcb != NULL) {
2240 		INP_LOCK_ASSERT(tptoinpcb(listening_tcb));
2241 		KASSERT(listening_tcb->t_fb != NULL,
2242 		    ("tcp_newtcpcb: listening_tcb->t_fb is NULL"));
2243 		if (listening_tcb->t_fb->tfb_flags & TCP_FUNC_BEING_REMOVED) {
2244 			rw_runlock(&tcp_function_lock);
2245 			return (NULL);
2246 		}
2247 		tp->t_fb = listening_tcb->t_fb;
2248 	} else {
2249 		tp->t_fb = V_tcp_func_set_ptr;
2250 	}
2251 	refcount_acquire(&tp->t_fb->tfb_refcnt);
2252 	KASSERT((tp->t_fb->tfb_flags & TCP_FUNC_BEING_REMOVED) == 0,
2253 	    ("tcp_newtcpcb: using TFB being removed"));
2254 	rw_runlock(&tcp_function_lock);
2255 	CC_LIST_RLOCK();
2256 	if (listening_tcb != NULL) {
2257 		if (CC_ALGO(listening_tcb)->flags & CC_MODULE_BEING_REMOVED) {
2258 			CC_LIST_RUNLOCK();
2259 			if (tp->t_fb->tfb_tcp_fb_fini)
2260 				(*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
2261 			refcount_release(&tp->t_fb->tfb_refcnt);
2262 			return (NULL);
2263 		}
2264 		CC_ALGO(tp) = CC_ALGO(listening_tcb);
2265 	} else
2266 		CC_ALGO(tp) = CC_DEFAULT_ALGO();
2267 	cc_refer(CC_ALGO(tp));
2268 	CC_LIST_RUNLOCK();
2269 	if (CC_ALGO(tp)->cb_init != NULL)
2270 		if (CC_ALGO(tp)->cb_init(&tp->t_ccv, NULL) > 0) {
2271 			cc_detach(tp);
2272 			if (tp->t_fb->tfb_tcp_fb_fini)
2273 				(*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
2274 			refcount_release(&tp->t_fb->tfb_refcnt);
2275 			return (NULL);
2276 		}
2277 
2278 #ifdef TCP_HHOOK
2279 	if (khelp_init_osd(HELPER_CLASS_TCP, &tp->t_osd)) {
2280 		if (CC_ALGO(tp)->cb_destroy != NULL)
2281 			CC_ALGO(tp)->cb_destroy(&tp->t_ccv);
2282 		CC_DATA(tp) = NULL;
2283 		cc_detach(tp);
2284 		if (tp->t_fb->tfb_tcp_fb_fini)
2285 			(*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
2286 		refcount_release(&tp->t_fb->tfb_refcnt);
2287 		return (NULL);
2288 	}
2289 #endif
2290 
2291 	TAILQ_INIT(&tp->t_segq);
2292 	STAILQ_INIT(&tp->t_inqueue);
2293 	tp->t_maxseg =
2294 #ifdef INET6
2295 		isipv6 ? V_tcp_v6mssdflt :
2296 #endif /* INET6 */
2297 		V_tcp_mssdflt;
2298 
2299 	/* All mbuf queue/ack compress flags should be off */
2300 	tcp_lro_features_off(tp);
2301 
2302 	tp->t_hpts_cpu = HPTS_CPU_NONE;
2303 	tp->t_lro_cpu = HPTS_CPU_NONE;
2304 
2305 	callout_init_rw(&tp->t_callout, &inp->inp_lock,
2306 	    CALLOUT_TRYLOCK | CALLOUT_RETURNUNLOCKED);
2307 	for (int i = 0; i < TT_N; i++)
2308 		tp->t_timers[i] = SBT_MAX;
2309 
2310 	switch (V_tcp_do_rfc1323) {
2311 		case 0:
2312 			break;
2313 		default:
2314 		case 1:
2315 			tp->t_flags = (TF_REQ_SCALE|TF_REQ_TSTMP);
2316 			break;
2317 		case 2:
2318 			tp->t_flags = TF_REQ_SCALE;
2319 			break;
2320 		case 3:
2321 			tp->t_flags = TF_REQ_TSTMP;
2322 			break;
2323 	}
2324 	if (V_tcp_do_sack)
2325 		tp->t_flags |= TF_SACK_PERMIT;
2326 	TAILQ_INIT(&tp->snd_holes);
2327 
2328 	/*
2329 	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
2330 	 * rtt estimate.  Set rttvar so that srtt + 4 * rttvar gives
2331 	 * reasonable initial retransmit time.
2332 	 */
2333 	tp->t_srtt = TCPTV_SRTTBASE;
2334 	tp->t_rttvar = ((tcp_rexmit_initial - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4;
2335 	tp->t_rttmin = tcp_rexmit_min;
2336 	tp->t_rxtcur = tcp_rexmit_initial;
2337 	tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
2338 	tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
2339 	tp->t_rcvtime = ticks;
2340 	/* We always start with ticks granularity */
2341 	tp->t_tmr_granularity = TCP_TMR_GRANULARITY_TICKS;
2342 	/*
2343 	 * IPv4 TTL initialization is necessary for an IPv6 socket as well,
2344 	 * because the socket may be bound to an IPv6 wildcard address,
2345 	 * which may match an IPv4-mapped IPv6 address.
2346 	 */
2347 	inp->inp_ip_ttl = V_ip_defttl;
2348 #ifdef TCP_BLACKBOX
2349 	/* Initialize the per-TCPCB log data. */
2350 	tcp_log_tcpcbinit(tp);
2351 #endif
2352 	tp->t_pacing_rate = -1;
2353 	if (tp->t_fb->tfb_tcp_fb_init) {
2354 		if ((*tp->t_fb->tfb_tcp_fb_init)(tp, &tp->t_fb_ptr)) {
2355 			if (CC_ALGO(tp)->cb_destroy != NULL)
2356 				CC_ALGO(tp)->cb_destroy(&tp->t_ccv);
2357 			CC_DATA(tp) = NULL;
2358 			cc_detach(tp);
2359 #ifdef TCP_HHOOK
2360 			khelp_destroy_osd(&tp->t_osd);
2361 #endif
2362 			refcount_release(&tp->t_fb->tfb_refcnt);
2363 			return (NULL);
2364 		}
2365 	}
2366 #ifdef STATS
2367 	if (V_tcp_perconn_stats_enable == 1)
2368 		tp->t_stats = stats_blob_alloc(V_tcp_perconn_stats_dflt_tpl, 0);
2369 #endif
2370 	if (V_tcp_do_lrd)
2371 		tp->t_flags |= TF_LRD;
2372 
2373 	return (tp);
2374 }
2375 
2376 /*
2377  * Drop a TCP connection, reporting
2378  * the specified error.  If connection is synchronized,
2379  * then send a RST to peer.
2380  */
2381 struct tcpcb *
tcp_drop(struct tcpcb * tp,int errno)2382 tcp_drop(struct tcpcb *tp, int errno)
2383 {
2384 	struct socket *so = tptosocket(tp);
2385 
2386 	NET_EPOCH_ASSERT();
2387 	INP_WLOCK_ASSERT(tptoinpcb(tp));
2388 
2389 	if (TCPS_HAVERCVDSYN(tp->t_state)) {
2390 		tcp_state_change(tp, TCPS_CLOSED);
2391 		/* Don't use tcp_output() here due to possible recursion. */
2392 		(void)tcp_output_nodrop(tp);
2393 		TCPSTAT_INC(tcps_drops);
2394 	} else
2395 		TCPSTAT_INC(tcps_conndrops);
2396 	if (errno == ETIMEDOUT && tp->t_softerror)
2397 		errno = tp->t_softerror;
2398 	so->so_error = errno;
2399 	return (tcp_close(tp));
2400 }
2401 
2402 void
tcp_discardcb(struct tcpcb * tp)2403 tcp_discardcb(struct tcpcb *tp)
2404 {
2405 	struct inpcb *inp = tptoinpcb(tp);
2406 	struct socket *so = tptosocket(tp);
2407 	struct mbuf *m;
2408 #ifdef INET6
2409 	bool isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
2410 #endif
2411 
2412 	INP_WLOCK_ASSERT(inp);
2413 	MPASS(!callout_active(&tp->t_callout));
2414 	MPASS(TAILQ_EMPTY(&tp->snd_holes));
2415 
2416 	/* free the reassembly queue, if any */
2417 	tcp_reass_flush(tp);
2418 
2419 #ifdef TCP_OFFLOAD
2420 	/* Disconnect offload device, if any. */
2421 	if (tp->t_flags & TF_TOE)
2422 		tcp_offload_detach(tp);
2423 #endif
2424 
2425 	/* Allow the CC algorithm to clean up after itself. */
2426 	if (CC_ALGO(tp)->cb_destroy != NULL)
2427 		CC_ALGO(tp)->cb_destroy(&tp->t_ccv);
2428 	CC_DATA(tp) = NULL;
2429 	/* Detach from the CC algorithm */
2430 	cc_detach(tp);
2431 
2432 #ifdef TCP_HHOOK
2433 	khelp_destroy_osd(&tp->t_osd);
2434 #endif
2435 #ifdef STATS
2436 	stats_blob_destroy(tp->t_stats);
2437 #endif
2438 #ifdef TCP_REQUEST_TRK
2439 	if (tp->t_tcpreq_info != NULL) {
2440 		free(tp->t_tcpreq_info, M_TCPREQTRK);
2441 		tp->t_tcpreq_info = NULL;
2442 	}
2443 #endif
2444 
2445 	CC_ALGO(tp) = NULL;
2446 	if ((m = STAILQ_FIRST(&tp->t_inqueue)) != NULL) {
2447 		struct mbuf *prev;
2448 
2449 		STAILQ_INIT(&tp->t_inqueue);
2450 		STAILQ_FOREACH_FROM_SAFE(m, &tp->t_inqueue, m_stailqpkt, prev)
2451 			m_freem(m);
2452 	}
2453 
2454 	if (tp->t_fb->tfb_tcp_fb_fini)
2455 		(*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
2456 	MPASS(!tcp_in_hpts(tp));
2457 #ifdef TCP_BLACKBOX
2458 	tcp_log_tcpcbfini(tp);
2459 #endif
2460 
2461 	/*
2462 	 * If we got enough samples through the srtt filter,
2463 	 * save the rtt and rttvar in the routing entry.
2464 	 * 'Enough' is arbitrarily defined as 4 rtt samples.
2465 	 * 4 samples is enough for the srtt filter to converge
2466 	 * to within enough % of the correct value; fewer samples
2467 	 * and we could save a bogus rtt. The danger is not high
2468 	 * as tcp quickly recovers from everything.
2469 	 * XXX: Works very well but needs some more statistics!
2470 	 *
2471 	 * XXXRRS: Updating must be after the stack fini() since
2472 	 * that may be converting some internal representation of
2473 	 * say srtt etc into the general one used by other stacks.
2474 	 */
2475 	if (tp->t_rttupdated >= 4) {
2476 		uint32_t ssthresh;
2477 
2478 		/*
2479 		 * Update the ssthresh always when the conditions below
2480 		 * are satisfied. This gives us better new start value
2481 		 * for the congestion avoidance for new connections.
2482 		 * ssthresh is only set if packet loss occurred on a session.
2483 		 */
2484 		ssthresh = tp->snd_ssthresh;
2485 		if (ssthresh != 0 && ssthresh < so->so_snd.sb_hiwat / 2) {
2486 			/*
2487 			 * convert the limit from user data bytes to
2488 			 * packets then to packet data bytes.
2489 			 */
2490 			ssthresh = (ssthresh + tp->t_maxseg / 2) / tp->t_maxseg;
2491 			if (ssthresh < 2)
2492 				ssthresh = 2;
2493 			ssthresh *= (tp->t_maxseg +
2494 #ifdef INET6
2495 			    (isipv6 ? sizeof (struct ip6_hdr) +
2496 			    sizeof (struct tcphdr) :
2497 #endif
2498 			    sizeof (struct tcpiphdr)
2499 #ifdef INET6
2500 			    )
2501 #endif
2502 			    );
2503 		} else
2504 			ssthresh = 0;
2505 		tcp_hc_update(&inp->inp_inc, &(struct tcp_hc_metrics){
2506 		    .hc_ssthresh = ssthresh,
2507 		    .hc_rtt = tp->t_srtt,
2508 		    .hc_rttvar = tp->t_rttvar,
2509 		    .hc_cwnd = tp->snd_cwnd,
2510 		    .hc_sendpipe = so->so_snd.sb_hiwat,
2511 		    .hc_recvpipe = so->so_rcv.sb_hiwat,
2512 		    });
2513 	}
2514 
2515 	refcount_release(&tp->t_fb->tfb_refcnt);
2516 }
2517 
2518 /*
2519  * Attempt to close a TCP control block, marking it as dropped, and freeing
2520  * the socket if we hold the only reference.
2521  */
2522 struct tcpcb *
tcp_close(struct tcpcb * tp)2523 tcp_close(struct tcpcb *tp)
2524 {
2525 	struct inpcb *inp = tptoinpcb(tp);
2526 	struct socket *so = tptosocket(tp);
2527 
2528 	INP_WLOCK_ASSERT(inp);
2529 
2530 #ifdef TCP_OFFLOAD
2531 	if (tp->t_state == TCPS_LISTEN)
2532 		tcp_offload_listen_stop(tp);
2533 #endif
2534 	/*
2535 	 * This releases the TFO pending counter resource for TFO listen
2536 	 * sockets as well as passively-created TFO sockets that transition
2537 	 * from SYN_RECEIVED to CLOSED.
2538 	 */
2539 	if (tp->t_tfo_pending) {
2540 		tcp_fastopen_decrement_counter(tp->t_tfo_pending);
2541 		tp->t_tfo_pending = NULL;
2542 	}
2543 	tcp_timer_stop(tp);
2544 	if (tp->t_fb->tfb_tcp_timer_stop_all != NULL)
2545 		tp->t_fb->tfb_tcp_timer_stop_all(tp);
2546 #if defined(INET) && defined(INET6)
2547 	if ((inp->inp_vflag & INP_IPV6) != 0)
2548 		in6_pcbdisconnect(inp);
2549 	else
2550 		in_pcbdisconnect(inp);
2551 #elif defined(INET6)
2552 	in6_pcbdisconnect(inp);
2553 #else
2554 	in_pcbdisconnect(inp);
2555 #endif
2556 	TCPSTAT_INC(tcps_closed);
2557 	if (tp->t_state != TCPS_CLOSED)
2558 		tcp_state_change(tp, TCPS_CLOSED);
2559 	tp->t_flags |= TF_DISCONNECTED;
2560 	KASSERT(inp->inp_socket != NULL, ("tcp_close: inp_socket NULL"));
2561 	tcp_free_sackholes(tp);
2562 	soisdisconnected(so);
2563 	if (inp->inp_flags & INP_SOCKREF) {
2564 		inp->inp_flags &= ~INP_SOCKREF;
2565 		INP_WUNLOCK(inp);
2566 		sorele(so);
2567 		return (NULL);
2568 	}
2569 	return (tp);
2570 }
2571 
2572 /*
2573  * Notify a tcp user of an asynchronous error;
2574  * store error as soft error, but wake up user
2575  * (for now, won't do anything until can select for soft error).
2576  *
2577  * Do not wake up user since there currently is no mechanism for
2578  * reporting soft errors (yet - a kqueue filter may be added).
2579  */
2580 static struct inpcb *
tcp_notify(struct inpcb * inp,int error)2581 tcp_notify(struct inpcb *inp, int error)
2582 {
2583 	struct tcpcb *tp;
2584 
2585 	INP_WLOCK_ASSERT(inp);
2586 
2587 	tp = intotcpcb(inp);
2588 	KASSERT(tp != NULL, ("tcp_notify: tp == NULL"));
2589 
2590 	/*
2591 	 * Ignore some errors if we are hooked up.
2592 	 * If connection hasn't completed, has retransmitted several times,
2593 	 * and receives a second error, give up now.  This is better
2594 	 * than waiting a long time to establish a connection that
2595 	 * can never complete.
2596 	 */
2597 	if (tp->t_state == TCPS_ESTABLISHED &&
2598 	    (error == EHOSTUNREACH || error == ENETUNREACH ||
2599 	     error == EHOSTDOWN)) {
2600 		if (inp->inp_route.ro_nh) {
2601 			NH_FREE(inp->inp_route.ro_nh);
2602 			inp->inp_route.ro_nh = (struct nhop_object *)NULL;
2603 		}
2604 		return (inp);
2605 	} else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 &&
2606 	    tp->t_softerror) {
2607 		tp = tcp_drop(tp, error);
2608 		if (tp != NULL)
2609 			return (inp);
2610 		else
2611 			return (NULL);
2612 	} else {
2613 		tp->t_softerror = error;
2614 		return (inp);
2615 	}
2616 #if 0
2617 	wakeup( &so->so_timeo);
2618 	sorwakeup(so);
2619 	sowwakeup(so);
2620 #endif
2621 }
2622 
2623 static int
tcp_pcblist(SYSCTL_HANDLER_ARGS)2624 tcp_pcblist(SYSCTL_HANDLER_ARGS)
2625 {
2626 	struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_tcbinfo,
2627 	    INPLOOKUP_RLOCKPCB);
2628 	struct xinpgen xig;
2629 	struct inpcb *inp;
2630 	int error;
2631 
2632 	if (req->newptr != NULL)
2633 		return (EPERM);
2634 
2635 	if (req->oldptr == NULL) {
2636 		int n;
2637 
2638 		n = V_tcbinfo.ipi_count +
2639 		    counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
2640 		n += imax(n / 8, 10);
2641 		req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xtcpcb);
2642 		return (0);
2643 	}
2644 
2645 	if ((error = sysctl_wire_old_buffer(req, 0)) != 0)
2646 		return (error);
2647 
2648 	bzero(&xig, sizeof(xig));
2649 	xig.xig_len = sizeof xig;
2650 	xig.xig_count = V_tcbinfo.ipi_count +
2651 	    counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
2652 	xig.xig_gen = V_tcbinfo.ipi_gencnt;
2653 	xig.xig_sogen = so_gencnt;
2654 	error = SYSCTL_OUT(req, &xig, sizeof xig);
2655 	if (error)
2656 		return (error);
2657 
2658 	error = syncache_pcblist(req);
2659 	if (error)
2660 		return (error);
2661 
2662 	while ((inp = inp_next(&inpi)) != NULL) {
2663 		if (inp->inp_gencnt <= xig.xig_gen &&
2664 		    cr_canseeinpcb(req->td->td_ucred, inp) == 0) {
2665 			struct xtcpcb xt;
2666 
2667 			tcp_inptoxtp(inp, &xt);
2668 			error = SYSCTL_OUT(req, &xt, sizeof xt);
2669 			if (error) {
2670 				INP_RUNLOCK(inp);
2671 				break;
2672 			} else
2673 				continue;
2674 		}
2675 	}
2676 
2677 	if (!error) {
2678 		/*
2679 		 * Give the user an updated idea of our state.
2680 		 * If the generation differs from what we told
2681 		 * her before, she knows that something happened
2682 		 * while we were processing this request, and it
2683 		 * might be necessary to retry.
2684 		 */
2685 		xig.xig_gen = V_tcbinfo.ipi_gencnt;
2686 		xig.xig_sogen = so_gencnt;
2687 		xig.xig_count = V_tcbinfo.ipi_count +
2688 		    counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
2689 		error = SYSCTL_OUT(req, &xig, sizeof xig);
2690 	}
2691 
2692 	return (error);
2693 }
2694 
2695 SYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist,
2696     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
2697     NULL, 0, tcp_pcblist, "S,xtcpcb",
2698     "List of active TCP connections");
2699 
2700 #define SND_TAG_STATUS_MAXLEN	128
2701 
2702 #ifdef KERN_TLS
2703 
2704 static struct sx ktlslist_lock;
2705 SX_SYSINIT(ktlslistlock, &ktlslist_lock, "ktlslist");
2706 static uint64_t ktls_glob_gen = 1;
2707 
2708 static int
tcp_ktlslist_locked(SYSCTL_HANDLER_ARGS,bool export_keys)2709 tcp_ktlslist_locked(SYSCTL_HANDLER_ARGS, bool export_keys)
2710 {
2711 	struct xinpgen xig;
2712 	struct inpcb *inp;
2713 	struct socket *so;
2714 	struct ktls_session *ksr, *kss;
2715 	char *buf;
2716 	struct xktls_session *xktls;
2717 	uint64_t ipi_gencnt;
2718 	size_t buflen, len, sz;
2719 	u_int cnt;
2720 	int error;
2721 	bool ek, p;
2722 
2723 	sx_assert(&ktlslist_lock, SA_XLOCKED);
2724 	if (req->newptr != NULL)
2725 		return (EPERM);
2726 
2727 	len = 0;
2728 	cnt = 0;
2729 	ipi_gencnt = V_tcbinfo.ipi_gencnt;
2730 	bzero(&xig, sizeof(xig));
2731 	xig.xig_len = sizeof(xig);
2732 	xig.xig_gen = ktls_glob_gen++;
2733 	xig.xig_sogen = so_gencnt;
2734 
2735 	struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_tcbinfo,
2736 	    INPLOOKUP_RLOCKPCB);
2737 	while ((inp = inp_next(&inpi)) != NULL) {
2738 		if (inp->inp_gencnt > ipi_gencnt ||
2739 		    cr_canseeinpcb(req->td->td_ucred, inp) != 0)
2740 			continue;
2741 
2742 		so = inp->inp_socket;
2743 		if (so != NULL && so->so_gencnt <= xig.xig_sogen) {
2744 			p = false;
2745 			ek = export_keys && cr_canexport_ktlskeys(
2746 			    req->td, inp);
2747 			ksr = so->so_rcv.sb_tls_info;
2748 			if (ksr != NULL) {
2749 				ksr->gen = xig.xig_gen;
2750 				p = true;
2751 				if (ek) {
2752 					sz = SIZE_T_MAX;
2753 					ktls_session_copy_keys(ksr,
2754 					    NULL, &sz);
2755 					len += sz;
2756 				}
2757 				if (ksr->snd_tag != NULL &&
2758 				    ksr->snd_tag->sw->snd_tag_status_str !=
2759 				    NULL) {
2760 					sz = SND_TAG_STATUS_MAXLEN;
2761 					in_pcbref(inp);
2762 					INP_RUNLOCK(inp);
2763 					error = ksr->snd_tag->sw->
2764 					    snd_tag_status_str(
2765 					    ksr->snd_tag, NULL, &sz);
2766 					if (in_pcbrele_rlock(inp))
2767 						return (EDEADLK);
2768 					if (error == 0)
2769 						len += sz;
2770 				}
2771 			}
2772 			kss = so->so_snd.sb_tls_info;
2773 			if (kss != NULL) {
2774 				kss->gen = xig.xig_gen;
2775 				p = true;
2776 				if (ek) {
2777 					sz = SIZE_T_MAX;
2778 					ktls_session_copy_keys(kss,
2779 					    NULL, &sz);
2780 					len += sz;
2781 				}
2782 				if (kss->snd_tag != NULL &&
2783 				    kss->snd_tag->sw->snd_tag_status_str !=
2784 				    NULL) {
2785 					sz = SND_TAG_STATUS_MAXLEN;
2786 					in_pcbref(inp);
2787 					INP_RUNLOCK(inp);
2788 					error = kss->snd_tag->sw->
2789 					    snd_tag_status_str(
2790 					    kss->snd_tag, NULL, &sz);
2791 					if (in_pcbrele_rlock(inp))
2792 						return (EDEADLK);
2793 					if (error == 0)
2794 						len += sz;
2795 				}
2796 			}
2797 			if (p) {
2798 				len += sizeof(*xktls);
2799 				len = roundup2(len, __alignof(struct
2800 				    xktls_session));
2801 			}
2802 		}
2803 	}
2804 	if (req->oldptr == NULL) {
2805 		len += 2 * sizeof(xig);
2806 		len += 3 * len / 4;
2807 		req->oldidx = len;
2808 		return (0);
2809 	}
2810 
2811 	if ((error = sysctl_wire_old_buffer(req, 0)) != 0)
2812 		return (error);
2813 
2814 	error = SYSCTL_OUT(req, &xig, sizeof xig);
2815 	if (error != 0)
2816 		return (error);
2817 
2818 	buflen = roundup2(sizeof(*xktls) + 2 * TLS_MAX_PARAM_SIZE +
2819 	    2 * SND_TAG_STATUS_MAXLEN, __alignof(struct xktls_session));
2820 	buf = malloc(buflen, M_TEMP, M_WAITOK | M_ZERO);
2821 	struct inpcb_iterator inpi1 = INP_ALL_ITERATOR(&V_tcbinfo,
2822 	    INPLOOKUP_RLOCKPCB);
2823 	while ((inp = inp_next(&inpi1)) != NULL) {
2824 		if (inp->inp_gencnt > ipi_gencnt ||
2825 		    cr_canseeinpcb(req->td->td_ucred, inp) != 0)
2826 			continue;
2827 
2828 		so = inp->inp_socket;
2829 		if (so == NULL)
2830 			continue;
2831 
2832 		p = false;
2833 		ek = export_keys && cr_canexport_ktlskeys(req->td, inp);
2834 		ksr = so->so_rcv.sb_tls_info;
2835 		kss = so->so_snd.sb_tls_info;
2836 		xktls = (struct xktls_session *)buf;
2837 		if (ksr != NULL && ksr->gen == xig.xig_gen) {
2838 			p = true;
2839 			ktls_session_to_xktls_onedir(ksr, ek, &xktls->rcv);
2840 		}
2841 		if (kss != NULL && kss->gen == xig.xig_gen) {
2842 			p = true;
2843 			ktls_session_to_xktls_onedir(kss, ek, &xktls->snd);
2844 		}
2845 		if (!p)
2846 			continue;
2847 
2848 		xktls->inp_gencnt = inp->inp_gencnt;
2849 		xktls->so_pcb = (kvaddr_t)inp;
2850 		memcpy(&xktls->coninf, &inp->inp_inc, sizeof(xktls->coninf));
2851 		len = sizeof(*xktls);
2852 		if (ksr != NULL && ksr->gen == xig.xig_gen) {
2853 			if (ek) {
2854 				sz = buflen - len;
2855 				ktls_session_copy_keys(ksr, buf + len, &sz);
2856 				len += sz;
2857 			} else {
2858 				xktls->rcv.cipher_key_len = 0;
2859 				xktls->rcv.auth_key_len = 0;
2860 			}
2861 			if (ksr->snd_tag != NULL &&
2862 			    ksr->snd_tag->sw->snd_tag_status_str != NULL) {
2863 				sz = SND_TAG_STATUS_MAXLEN;
2864 				in_pcbref(inp);
2865 				INP_RUNLOCK(inp);
2866 				error = ksr->snd_tag->sw->snd_tag_status_str(
2867 				    ksr->snd_tag, buf + len, &sz);
2868 				if (in_pcbrele_rlock(inp))
2869 					return (EDEADLK);
2870 				if (error == 0) {
2871 					xktls->rcv.drv_st_len = sz;
2872 					len += sz;
2873 				}
2874 			}
2875 		}
2876 		if (kss != NULL && kss->gen == xig.xig_gen) {
2877 			if (ek) {
2878 				sz = buflen - len;
2879 				ktls_session_copy_keys(kss, buf + len, &sz);
2880 				len += sz;
2881 			} else {
2882 				xktls->snd.cipher_key_len = 0;
2883 				xktls->snd.auth_key_len = 0;
2884 			}
2885 			if (kss->snd_tag != NULL &&
2886 			    kss->snd_tag->sw->snd_tag_status_str != NULL) {
2887 				sz = SND_TAG_STATUS_MAXLEN;
2888 				in_pcbref(inp);
2889 				INP_RUNLOCK(inp);
2890 				error = kss->snd_tag->sw->snd_tag_status_str(
2891 				    kss->snd_tag, buf + len, &sz);
2892 				if (in_pcbrele_rlock(inp))
2893 					return (EDEADLK);
2894 				if (error == 0) {
2895 					xktls->snd.drv_st_len = sz;
2896 					len += sz;
2897 				}
2898 			}
2899 		}
2900 		len = roundup2(len, __alignof(*xktls));
2901 		xktls->tsz = len;
2902 		xktls->fsz = sizeof(*xktls);
2903 
2904 		error = SYSCTL_OUT(req, xktls, len);
2905 		if (error != 0) {
2906 			INP_RUNLOCK(inp);
2907 			break;
2908 		}
2909 		cnt++;
2910 	}
2911 
2912 	if (error == 0) {
2913 		xig.xig_sogen = so_gencnt;
2914 		xig.xig_count = cnt;
2915 		error = SYSCTL_OUT(req, &xig, sizeof(xig));
2916 	}
2917 
2918 	zfree(buf, M_TEMP);
2919 	return (error);
2920 }
2921 
2922 static int
tcp_ktlslist1(SYSCTL_HANDLER_ARGS,bool export_keys)2923 tcp_ktlslist1(SYSCTL_HANDLER_ARGS, bool export_keys)
2924 {
2925 	int repeats, error;
2926 
2927 	for (repeats = 0; repeats < 100; repeats++) {
2928 		if (sx_xlock_sig(&ktlslist_lock))
2929 			return (EINTR);
2930 		error = tcp_ktlslist_locked(oidp, arg1, arg2, req,
2931 		    export_keys);
2932 		sx_xunlock(&ktlslist_lock);
2933 		if (error != EDEADLK)
2934 			break;
2935 		if (sig_intr() != 0) {
2936 			error = EINTR;
2937 			break;
2938 		}
2939 		req->oldidx = 0;
2940 	}
2941 	return (error);
2942 }
2943 
2944 static int
tcp_ktlslist_nokeys(SYSCTL_HANDLER_ARGS)2945 tcp_ktlslist_nokeys(SYSCTL_HANDLER_ARGS)
2946 {
2947 	return (tcp_ktlslist1(oidp, arg1, arg2, req, false));
2948 }
2949 
2950 static int
tcp_ktlslist_wkeys(SYSCTL_HANDLER_ARGS)2951 tcp_ktlslist_wkeys(SYSCTL_HANDLER_ARGS)
2952 {
2953 	return (tcp_ktlslist1(oidp, arg1, arg2, req, true));
2954 }
2955 
2956 SYSCTL_PROC(_net_inet_tcp, TCPCTL_KTLSLIST, ktlslist,
2957     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2958     NULL, 0, tcp_ktlslist_nokeys, "S,xktls_session",
2959     "List of active kTLS sessions for TCP connections");
2960 SYSCTL_PROC(_net_inet_tcp, TCPCTL_KTLSLIST_WKEYS, ktlslist_wkeys,
2961     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2962     NULL, 0, tcp_ktlslist_wkeys, "S,xktls_session",
2963     "List of active kTLS sessions for TCP connections with keys");
2964 #endif /* KERN_TLS */
2965 
2966 #ifdef INET
2967 static int
tcp_getcred(SYSCTL_HANDLER_ARGS)2968 tcp_getcred(SYSCTL_HANDLER_ARGS)
2969 {
2970 	struct xucred xuc;
2971 	struct sockaddr_in addrs[2];
2972 	struct epoch_tracker et;
2973 	struct inpcb *inp;
2974 	int error;
2975 
2976 	if (req->newptr == NULL)
2977 		return (EINVAL);
2978 	error = priv_check(req->td, PRIV_NETINET_GETCRED);
2979 	if (error)
2980 		return (error);
2981 	error = SYSCTL_IN(req, addrs, sizeof(addrs));
2982 	if (error)
2983 		return (error);
2984 	NET_EPOCH_ENTER(et);
2985 	inp = in_pcblookup(&V_tcbinfo, addrs[1].sin_addr, addrs[1].sin_port,
2986 	    addrs[0].sin_addr, addrs[0].sin_port, INPLOOKUP_RLOCKPCB, NULL);
2987 	NET_EPOCH_EXIT(et);
2988 	if (inp != NULL) {
2989 		if (error == 0)
2990 			error = cr_canseeinpcb(req->td->td_ucred, inp);
2991 		if (error == 0)
2992 			cru2x(inp->inp_cred, &xuc);
2993 		INP_RUNLOCK(inp);
2994 	} else
2995 		error = ENOENT;
2996 	if (error == 0)
2997 		error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
2998 	return (error);
2999 }
3000 
3001 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, getcred,
3002     CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_PRISON | CTLFLAG_NEEDGIANT,
3003     0, 0, tcp_getcred, "S,xucred",
3004     "Get the xucred of a TCP connection");
3005 #endif /* INET */
3006 
3007 #ifdef INET6
3008 static int
tcp6_getcred(SYSCTL_HANDLER_ARGS)3009 tcp6_getcred(SYSCTL_HANDLER_ARGS)
3010 {
3011 	struct epoch_tracker et;
3012 	struct xucred xuc;
3013 	struct sockaddr_in6 addrs[2];
3014 	struct inpcb *inp;
3015 	int error;
3016 #ifdef INET
3017 	int mapped = 0;
3018 #endif
3019 
3020 	if (req->newptr == NULL)
3021 		return (EINVAL);
3022 	error = priv_check(req->td, PRIV_NETINET_GETCRED);
3023 	if (error)
3024 		return (error);
3025 	error = SYSCTL_IN(req, addrs, sizeof(addrs));
3026 	if (error)
3027 		return (error);
3028 	if ((error = sa6_embedscope(&addrs[0], V_ip6_use_defzone)) != 0 ||
3029 	    (error = sa6_embedscope(&addrs[1], V_ip6_use_defzone)) != 0) {
3030 		return (error);
3031 	}
3032 	if (IN6_IS_ADDR_V4MAPPED(&addrs[0].sin6_addr)) {
3033 #ifdef INET
3034 		if (IN6_IS_ADDR_V4MAPPED(&addrs[1].sin6_addr))
3035 			mapped = 1;
3036 		else
3037 #endif
3038 			return (EINVAL);
3039 	}
3040 
3041 	NET_EPOCH_ENTER(et);
3042 #ifdef INET
3043 	if (mapped == 1)
3044 		inp = in_pcblookup(&V_tcbinfo,
3045 			*(struct in_addr *)&addrs[1].sin6_addr.s6_addr[12],
3046 			addrs[1].sin6_port,
3047 			*(struct in_addr *)&addrs[0].sin6_addr.s6_addr[12],
3048 			addrs[0].sin6_port, INPLOOKUP_RLOCKPCB, NULL);
3049 	else
3050 #endif
3051 		inp = in6_pcblookup(&V_tcbinfo,
3052 			&addrs[1].sin6_addr, addrs[1].sin6_port,
3053 			&addrs[0].sin6_addr, addrs[0].sin6_port,
3054 			INPLOOKUP_RLOCKPCB, NULL);
3055 	NET_EPOCH_EXIT(et);
3056 	if (inp != NULL) {
3057 		if (error == 0)
3058 			error = cr_canseeinpcb(req->td->td_ucred, inp);
3059 		if (error == 0)
3060 			cru2x(inp->inp_cred, &xuc);
3061 		INP_RUNLOCK(inp);
3062 	} else
3063 		error = ENOENT;
3064 	if (error == 0)
3065 		error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
3066 	return (error);
3067 }
3068 
3069 SYSCTL_PROC(_net_inet6_tcp6, OID_AUTO, getcred,
3070     CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_PRISON | CTLFLAG_NEEDGIANT,
3071     0, 0, tcp6_getcred, "S,xucred",
3072     "Get the xucred of a TCP6 connection");
3073 #endif /* INET6 */
3074 
3075 #ifdef INET
3076 /* Path MTU to try next when a fragmentation-needed message is received. */
3077 static inline int
tcp_next_pmtu(const struct icmp * icp,const struct ip * ip)3078 tcp_next_pmtu(const struct icmp *icp, const struct ip *ip)
3079 {
3080 	int mtu = ntohs(icp->icmp_nextmtu);
3081 
3082 	/* If no alternative MTU was proposed, try the next smaller one. */
3083 	if (!mtu)
3084 		mtu = ip_next_mtu(ntohs(ip->ip_len), 1);
3085 	if (mtu < V_tcp_minmss + sizeof(struct tcpiphdr))
3086 		mtu = V_tcp_minmss + sizeof(struct tcpiphdr);
3087 
3088 	return (mtu);
3089 }
3090 
3091 static void
tcp_ctlinput_with_port(struct icmp * icp,uint16_t port)3092 tcp_ctlinput_with_port(struct icmp *icp, uint16_t port)
3093 {
3094 	struct ip *ip;
3095 	struct tcphdr *th;
3096 	struct inpcb *inp;
3097 	struct tcpcb *tp;
3098 	struct inpcb *(*notify)(struct inpcb *, int);
3099 	struct in_conninfo inc;
3100 	tcp_seq icmp_tcp_seq;
3101 	int errno, mtu;
3102 
3103 	errno = icmp_errmap(icp);
3104 	switch (errno) {
3105 	case 0:
3106 		return;
3107 	case EMSGSIZE:
3108 		notify = tcp_mtudisc_notify;
3109 		break;
3110 	case ECONNREFUSED:
3111 		if (V_icmp_may_rst)
3112 			notify = tcp_drop_syn_sent;
3113 		else
3114 			notify = tcp_notify;
3115 		break;
3116 	case EHOSTUNREACH:
3117 		if (V_icmp_may_rst && icp->icmp_type == ICMP_TIMXCEED)
3118 			notify = tcp_drop_syn_sent;
3119 		else
3120 			notify = tcp_notify;
3121 		break;
3122 	default:
3123 		notify = tcp_notify;
3124 	}
3125 
3126 	ip = &icp->icmp_ip;
3127 	th = (struct tcphdr *)((char *)ip + (ip->ip_hl << 2));
3128 	icmp_tcp_seq = th->th_seq;
3129 	inp = in_pcblookup(&V_tcbinfo, ip->ip_dst, th->th_dport, ip->ip_src,
3130 	    th->th_sport, INPLOOKUP_WLOCKPCB, NULL);
3131 	if (inp != NULL)  {
3132 		tp = intotcpcb(inp);
3133 #ifdef TCP_OFFLOAD
3134 		if (tp->t_flags & TF_TOE && errno == EMSGSIZE) {
3135 			/*
3136 			 * MTU discovery for offloaded connections.  Let
3137 			 * the TOE driver verify seq# and process it.
3138 			 */
3139 			mtu = tcp_next_pmtu(icp, ip);
3140 			tcp_offload_pmtu_update(tp, icmp_tcp_seq, mtu);
3141 			goto out;
3142 		}
3143 #endif
3144 		if (tp->t_port != port)
3145 			goto out;
3146 		if (SEQ_GEQ(ntohl(icmp_tcp_seq), tp->snd_una) &&
3147 		    SEQ_LT(ntohl(icmp_tcp_seq), tp->snd_max)) {
3148 			if (errno == EMSGSIZE) {
3149 				/*
3150 				 * MTU discovery: we got a needfrag and
3151 				 * will potentially try a lower MTU.
3152 				 */
3153 				mtu = tcp_next_pmtu(icp, ip);
3154 
3155 				/*
3156 				 * Only process the offered MTU if it
3157 				 * is smaller than the current one.
3158 				 */
3159 				if (mtu < tp->t_maxseg +
3160 				    sizeof(struct tcpiphdr)) {
3161 					bzero(&inc, sizeof(inc));
3162 					inc.inc_faddr = ip->ip_dst;
3163 					inc.inc_fibnum =
3164 					    inp->inp_inc.inc_fibnum;
3165 					tcp_hc_updatemtu(&inc, mtu);
3166 					inp = tcp_mtudisc(inp, mtu);
3167 				}
3168 			} else
3169 				inp = (*notify)(inp, errno);
3170 		}
3171 	} else {
3172 		bzero(&inc, sizeof(inc));
3173 		inc.inc_fport = th->th_dport;
3174 		inc.inc_lport = th->th_sport;
3175 		inc.inc_faddr = ip->ip_dst;
3176 		inc.inc_laddr = ip->ip_src;
3177 		syncache_unreach(&inc, icmp_tcp_seq, port);
3178 	}
3179 out:
3180 	if (inp != NULL)
3181 		INP_WUNLOCK(inp);
3182 }
3183 
3184 static void
tcp_ctlinput(struct icmp * icmp)3185 tcp_ctlinput(struct icmp *icmp)
3186 {
3187 	tcp_ctlinput_with_port(icmp, htons(0));
3188 }
3189 
3190 static void
tcp_ctlinput_viaudp(udp_tun_icmp_param_t param)3191 tcp_ctlinput_viaudp(udp_tun_icmp_param_t param)
3192 {
3193 	/* Its a tunneled TCP over UDP icmp */
3194 	struct icmp *icmp = param.icmp;
3195 	struct ip *outer_ip, *inner_ip;
3196 	struct udphdr *udp;
3197 	struct tcphdr *th, ttemp;
3198 	int i_hlen, o_len;
3199 	uint16_t port;
3200 
3201 	outer_ip = (struct ip *)((char *)icmp - sizeof(struct ip));
3202 	inner_ip = &icmp->icmp_ip;
3203 	i_hlen = inner_ip->ip_hl << 2;
3204 	o_len = ntohs(outer_ip->ip_len);
3205 	if (o_len <
3206 	    (sizeof(struct ip) + 8 + i_hlen + sizeof(struct udphdr) + offsetof(struct tcphdr, th_ack))) {
3207 		/* Not enough data present */
3208 		return;
3209 	}
3210 	/* Ok lets strip out the inner udphdr header by copying up on top of it the tcp hdr */
3211 	udp = (struct udphdr *)(((char *)inner_ip) + i_hlen);
3212 	if (ntohs(udp->uh_sport) != V_tcp_udp_tunneling_port) {
3213 		return;
3214 	}
3215 	port = udp->uh_dport;
3216 	th = (struct tcphdr *)(udp + 1);
3217 	memcpy(&ttemp, th, sizeof(struct tcphdr));
3218 	memcpy(udp, &ttemp, sizeof(struct tcphdr));
3219 	/* Now adjust down the size of the outer IP header */
3220 	o_len -= sizeof(struct udphdr);
3221 	outer_ip->ip_len = htons(o_len);
3222 	/* Now call in to the normal handling code */
3223 	tcp_ctlinput_with_port(icmp, port);
3224 }
3225 #endif /* INET */
3226 
3227 #ifdef INET6
3228 static inline int
tcp6_next_pmtu(const struct icmp6_hdr * icmp6)3229 tcp6_next_pmtu(const struct icmp6_hdr *icmp6)
3230 {
3231 	int mtu = ntohl(icmp6->icmp6_mtu);
3232 
3233 	/*
3234 	 * If no alternative MTU was proposed, or the proposed MTU was too
3235 	 * small, set to the min.
3236 	 */
3237 	if (mtu < IPV6_MMTU)
3238 		mtu = IPV6_MMTU;
3239 	return (mtu);
3240 }
3241 
3242 static void
tcp6_ctlinput_with_port(struct ip6ctlparam * ip6cp,uint16_t port)3243 tcp6_ctlinput_with_port(struct ip6ctlparam *ip6cp, uint16_t port)
3244 {
3245 	struct in6_addr *dst;
3246 	struct inpcb *(*notify)(struct inpcb *, int);
3247 	struct ip6_hdr *ip6;
3248 	struct mbuf *m;
3249 	struct inpcb *inp;
3250 	struct tcpcb *tp;
3251 	struct icmp6_hdr *icmp6;
3252 	struct in_conninfo inc;
3253 	struct tcp_ports {
3254 		uint16_t th_sport;
3255 		uint16_t th_dport;
3256 	} t_ports;
3257 	tcp_seq icmp_tcp_seq;
3258 	unsigned int mtu;
3259 	unsigned int off;
3260 	int errno;
3261 
3262 	icmp6 = ip6cp->ip6c_icmp6;
3263 	m = ip6cp->ip6c_m;
3264 	ip6 = ip6cp->ip6c_ip6;
3265 	off = ip6cp->ip6c_off;
3266 	dst = &ip6cp->ip6c_finaldst->sin6_addr;
3267 
3268 	errno = icmp6_errmap(icmp6);
3269 	switch (errno) {
3270 	case 0:
3271 		return;
3272 	case EMSGSIZE:
3273 		notify = tcp_mtudisc_notify;
3274 		break;
3275 	case ECONNREFUSED:
3276 		if (V_icmp_may_rst)
3277 			notify = tcp_drop_syn_sent;
3278 		else
3279 			notify = tcp_notify;
3280 		break;
3281 	case EHOSTUNREACH:
3282 		/*
3283 		 * There are only four ICMPs that may reset connection:
3284 		 * - administratively prohibited
3285 		 * - port unreachable
3286 		 * - time exceeded in transit
3287 		 * - unknown next header
3288 		 */
3289 		if (V_icmp_may_rst &&
3290 		    ((icmp6->icmp6_type == ICMP6_DST_UNREACH &&
3291 		     (icmp6->icmp6_code == ICMP6_DST_UNREACH_ADMIN ||
3292 		      icmp6->icmp6_code == ICMP6_DST_UNREACH_NOPORT)) ||
3293 		    (icmp6->icmp6_type == ICMP6_TIME_EXCEEDED &&
3294 		      icmp6->icmp6_code == ICMP6_TIME_EXCEED_TRANSIT) ||
3295 		    (icmp6->icmp6_type == ICMP6_PARAM_PROB &&
3296 		      icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER)))
3297 			notify = tcp_drop_syn_sent;
3298 		else
3299 			notify = tcp_notify;
3300 		break;
3301 	default:
3302 		notify = tcp_notify;
3303 	}
3304 
3305 	/* Check if we can safely get the ports from the tcp hdr */
3306 	if (m == NULL ||
3307 	    (m->m_pkthdr.len <
3308 		(int32_t) (off + sizeof(struct tcp_ports)))) {
3309 		return;
3310 	}
3311 	bzero(&t_ports, sizeof(struct tcp_ports));
3312 	m_copydata(m, off, sizeof(struct tcp_ports), &t_ports);
3313 	inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_dst, t_ports.th_dport,
3314 	    &ip6->ip6_src, t_ports.th_sport, INPLOOKUP_WLOCKPCB, NULL);
3315 	off += sizeof(struct tcp_ports);
3316 	if (m->m_pkthdr.len < (int32_t) (off + sizeof(tcp_seq))) {
3317 		goto out;
3318 	}
3319 	m_copydata(m, off, sizeof(tcp_seq), &icmp_tcp_seq);
3320 	if (inp != NULL)  {
3321 		tp = intotcpcb(inp);
3322 #ifdef TCP_OFFLOAD
3323 		if (tp->t_flags & TF_TOE && errno == EMSGSIZE) {
3324 			/* MTU discovery for offloaded connections. */
3325 			mtu = tcp6_next_pmtu(icmp6);
3326 			tcp_offload_pmtu_update(tp, icmp_tcp_seq, mtu);
3327 			goto out;
3328 		}
3329 #endif
3330 		if (tp->t_port != port)
3331 			goto out;
3332 		if (SEQ_GEQ(ntohl(icmp_tcp_seq), tp->snd_una) &&
3333 		    SEQ_LT(ntohl(icmp_tcp_seq), tp->snd_max)) {
3334 			if (errno == EMSGSIZE) {
3335 				/*
3336 				 * MTU discovery:
3337 				 * If we got a needfrag set the MTU
3338 				 * in the route to the suggested new
3339 				 * value (if given) and then notify.
3340 				 */
3341 				mtu = tcp6_next_pmtu(icmp6);
3342 
3343 				bzero(&inc, sizeof(inc));
3344 				inc.inc_fibnum = M_GETFIB(m);
3345 				inc.inc_flags |= INC_ISIPV6;
3346 				inc.inc6_faddr = *dst;
3347 				if (in6_setscope(&inc.inc6_faddr,
3348 					m->m_pkthdr.rcvif, NULL))
3349 					goto out;
3350 				/*
3351 				 * Only process the offered MTU if it
3352 				 * is smaller than the current one.
3353 				 */
3354 				if (mtu < tp->t_maxseg +
3355 				    sizeof (struct tcphdr) +
3356 				    sizeof (struct ip6_hdr)) {
3357 					tcp_hc_updatemtu(&inc, mtu);
3358 					tcp_mtudisc(inp, mtu);
3359 					ICMP6STAT_INC(icp6s_pmtuchg);
3360 				}
3361 			} else
3362 				inp = (*notify)(inp, errno);
3363 		}
3364 	} else {
3365 		bzero(&inc, sizeof(inc));
3366 		inc.inc_fibnum = M_GETFIB(m);
3367 		inc.inc_flags |= INC_ISIPV6;
3368 		inc.inc_fport = t_ports.th_dport;
3369 		inc.inc_lport = t_ports.th_sport;
3370 		inc.inc6_faddr = *dst;
3371 		inc.inc6_laddr = ip6->ip6_src;
3372 		syncache_unreach(&inc, icmp_tcp_seq, port);
3373 	}
3374 out:
3375 	if (inp != NULL)
3376 		INP_WUNLOCK(inp);
3377 }
3378 
3379 static void
tcp6_ctlinput(struct ip6ctlparam * ctl)3380 tcp6_ctlinput(struct ip6ctlparam *ctl)
3381 {
3382 	tcp6_ctlinput_with_port(ctl, htons(0));
3383 }
3384 
3385 static void
tcp6_ctlinput_viaudp(udp_tun_icmp_param_t param)3386 tcp6_ctlinput_viaudp(udp_tun_icmp_param_t param)
3387 {
3388 	struct ip6ctlparam *ip6cp = param.ip6cp;
3389 	struct udphdr udp;
3390 	uint16_t port;
3391 
3392 	if (ip6cp->ip6c_m->m_pkthdr.len <
3393 	    ip6cp->ip6c_off + sizeof(struct udphdr))
3394 		return;
3395 	m_copydata(ip6cp->ip6c_m, ip6cp->ip6c_off, sizeof(udp), &udp);
3396 	if (ntohs(udp.uh_sport) != V_tcp_udp_tunneling_port)
3397 		return;
3398 	port = udp.uh_dport;
3399 	ip6cp->ip6c_off += sizeof(struct udphdr);
3400 	/* Now call in to the normal handling code */
3401 	tcp6_ctlinput_with_port(ip6cp, port);
3402 	ip6cp->ip6c_off -= sizeof(struct udphdr);
3403 }
3404 
3405 #endif /* INET6 */
3406 
3407 static uint32_t
tcp_keyed_hash(struct in_conninfo * inc,u_char * key,u_int len)3408 tcp_keyed_hash(struct in_conninfo *inc, u_char *key, u_int len)
3409 {
3410 	SIPHASH_CTX ctx;
3411 	uint32_t hash[2];
3412 
3413 	KASSERT(len >= SIPHASH_KEY_LENGTH,
3414 	    ("%s: keylen %u too short ", __func__, len));
3415 	SipHash24_Init(&ctx);
3416 	SipHash_SetKey(&ctx, (uint8_t *)key);
3417 	SipHash_Update(&ctx, &inc->inc_fport, sizeof(uint16_t));
3418 	SipHash_Update(&ctx, &inc->inc_lport, sizeof(uint16_t));
3419 	switch (inc->inc_flags & INC_ISIPV6) {
3420 #ifdef INET
3421 	case 0:
3422 		SipHash_Update(&ctx, &inc->inc_faddr, sizeof(struct in_addr));
3423 		SipHash_Update(&ctx, &inc->inc_laddr, sizeof(struct in_addr));
3424 		break;
3425 #endif
3426 #ifdef INET6
3427 	case INC_ISIPV6:
3428 		SipHash_Update(&ctx, &inc->inc6_faddr, sizeof(struct in6_addr));
3429 		SipHash_Update(&ctx, &inc->inc6_laddr, sizeof(struct in6_addr));
3430 		break;
3431 #endif
3432 	}
3433 	SipHash_Final((uint8_t *)hash, &ctx);
3434 
3435 	return (hash[0] ^ hash[1]);
3436 }
3437 
3438 uint32_t
tcp_new_ts_offset(struct in_conninfo * inc)3439 tcp_new_ts_offset(struct in_conninfo *inc)
3440 {
3441 	struct in_conninfo inc_store, *local_inc;
3442 
3443 	if (!V_tcp_ts_offset_per_conn) {
3444 		memcpy(&inc_store, inc, sizeof(struct in_conninfo));
3445 		inc_store.inc_lport = 0;
3446 		inc_store.inc_fport = 0;
3447 		local_inc = &inc_store;
3448 	} else {
3449 		local_inc = inc;
3450 	}
3451 	return (tcp_keyed_hash(local_inc, V_ts_offset_secret,
3452 	    sizeof(V_ts_offset_secret)));
3453 }
3454 
3455 /*
3456  * Following is where TCP initial sequence number generation occurs.
3457  *
3458  * There are two places where we must use initial sequence numbers:
3459  * 1.  In SYN-ACK packets.
3460  * 2.  In SYN packets.
3461  *
3462  * All ISNs for SYN-ACK packets are generated by the syncache.  See
3463  * tcp_syncache.c for details.
3464  *
3465  * The ISNs in SYN packets must be monotonic; TIME_WAIT recycling
3466  * depends on this property.  In addition, these ISNs should be
3467  * unguessable so as to prevent connection hijacking.  To satisfy
3468  * the requirements of this situation, the algorithm outlined in
3469  * RFC 1948 is used, with only small modifications.
3470  *
3471  * Implementation details:
3472  *
3473  * Time is based off the system timer, and is corrected so that it
3474  * increases by one megabyte per second.  This allows for proper
3475  * recycling on high speed LANs while still leaving over an hour
3476  * before rollover.
3477  *
3478  * As reading the *exact* system time is too expensive to be done
3479  * whenever setting up a TCP connection, we increment the time
3480  * offset in two ways.  First, a small random positive increment
3481  * is added to isn_offset for each connection that is set up.
3482  * Second, the function tcp_isn_tick fires once per clock tick
3483  * and increments isn_offset as necessary so that sequence numbers
3484  * are incremented at approximately ISN_BYTES_PER_SECOND.  The
3485  * random positive increments serve only to ensure that the same
3486  * exact sequence number is never sent out twice (as could otherwise
3487  * happen when a port is recycled in less than the system tick
3488  * interval.)
3489  *
3490  * net.inet.tcp.isn_reseed_interval controls the number of seconds
3491  * between seeding of isn_secret.  This is normally set to zero,
3492  * as reseeding should not be necessary.
3493  *
3494  * Locking of the global variables isn_secret, isn_last_reseed, isn_offset,
3495  * isn_offset_old, and isn_ctx is performed using the ISN lock.  In
3496  * general, this means holding an exclusive (write) lock.
3497  */
3498 
3499 #define ISN_BYTES_PER_SECOND 1048576
3500 #define ISN_STATIC_INCREMENT 4096
3501 #define ISN_RANDOM_INCREMENT (4096 - 1)
3502 #define ISN_SECRET_LENGTH    SIPHASH_KEY_LENGTH
3503 
3504 VNET_DEFINE_STATIC(u_char, isn_secret[ISN_SECRET_LENGTH]);
3505 VNET_DEFINE_STATIC(int, isn_last);
3506 VNET_DEFINE_STATIC(int, isn_last_reseed);
3507 VNET_DEFINE_STATIC(u_int32_t, isn_offset);
3508 VNET_DEFINE_STATIC(u_int32_t, isn_offset_old);
3509 
3510 #define	V_isn_secret			VNET(isn_secret)
3511 #define	V_isn_last			VNET(isn_last)
3512 #define	V_isn_last_reseed		VNET(isn_last_reseed)
3513 #define	V_isn_offset			VNET(isn_offset)
3514 #define	V_isn_offset_old		VNET(isn_offset_old)
3515 
3516 tcp_seq
tcp_new_isn(struct in_conninfo * inc)3517 tcp_new_isn(struct in_conninfo *inc)
3518 {
3519 	tcp_seq new_isn;
3520 	u_int32_t projected_offset;
3521 
3522 	ISN_LOCK();
3523 	/* Seed if this is the first use, reseed if requested. */
3524 	if ((V_isn_last_reseed == 0) || ((V_tcp_isn_reseed_interval > 0) &&
3525 	     (((u_int)V_isn_last_reseed + (u_int)V_tcp_isn_reseed_interval*hz)
3526 		< (u_int)ticks))) {
3527 		arc4rand(&V_isn_secret, sizeof(V_isn_secret), 0);
3528 		V_isn_last_reseed = ticks;
3529 	}
3530 
3531 	/* Compute the hash and return the ISN. */
3532 	new_isn = (tcp_seq)tcp_keyed_hash(inc, V_isn_secret,
3533 	    sizeof(V_isn_secret));
3534 	V_isn_offset += ISN_STATIC_INCREMENT +
3535 		(arc4random() & ISN_RANDOM_INCREMENT);
3536 	if (ticks != V_isn_last) {
3537 		projected_offset = V_isn_offset_old +
3538 		    ISN_BYTES_PER_SECOND / hz * (ticks - V_isn_last);
3539 		if (SEQ_GT(projected_offset, V_isn_offset))
3540 			V_isn_offset = projected_offset;
3541 		V_isn_offset_old = V_isn_offset;
3542 		V_isn_last = ticks;
3543 	}
3544 	new_isn += V_isn_offset;
3545 	ISN_UNLOCK();
3546 	return (new_isn);
3547 }
3548 
3549 /*
3550  * When a specific ICMP unreachable message is received and the
3551  * connection state is SYN-SENT, drop the connection.  This behavior
3552  * is controlled by the icmp_may_rst sysctl.
3553  */
3554 static struct inpcb *
tcp_drop_syn_sent(struct inpcb * inp,int errno)3555 tcp_drop_syn_sent(struct inpcb *inp, int errno)
3556 {
3557 	struct tcpcb *tp;
3558 
3559 	NET_EPOCH_ASSERT();
3560 	INP_WLOCK_ASSERT(inp);
3561 
3562 	tp = intotcpcb(inp);
3563 	if (tp->t_state != TCPS_SYN_SENT)
3564 		return (inp);
3565 
3566 	if (tp->t_flags & TF_FASTOPEN)
3567 		tcp_fastopen_disable_path(tp);
3568 
3569 	tp = tcp_drop(tp, errno);
3570 	if (tp != NULL)
3571 		return (inp);
3572 	else
3573 		return (NULL);
3574 }
3575 
3576 /*
3577  * When `need fragmentation' ICMP is received, update our idea of the MSS
3578  * based on the new value. Also nudge TCP to send something, since we
3579  * know the packet we just sent was dropped.
3580  * This duplicates some code in the tcp_mss() function in tcp_input.c.
3581  */
3582 static struct inpcb *
tcp_mtudisc_notify(struct inpcb * inp,int error)3583 tcp_mtudisc_notify(struct inpcb *inp, int error)
3584 {
3585 
3586 	return (tcp_mtudisc(inp, -1));
3587 }
3588 
3589 static struct inpcb *
tcp_mtudisc(struct inpcb * inp,int mtuoffer)3590 tcp_mtudisc(struct inpcb *inp, int mtuoffer)
3591 {
3592 	struct tcpcb *tp;
3593 	struct socket *so;
3594 
3595 	INP_WLOCK_ASSERT(inp);
3596 
3597 	tp = intotcpcb(inp);
3598 	KASSERT(tp != NULL, ("tcp_mtudisc: tp == NULL"));
3599 
3600 	tcp_mss_update(tp, -1, mtuoffer, NULL, NULL);
3601 
3602 	so = inp->inp_socket;
3603 	SOCK_SENDBUF_LOCK(so);
3604 	/* If the mss is larger than the socket buffer, decrease the mss. */
3605 	if (so->so_snd.sb_hiwat < tp->t_maxseg) {
3606 		tp->t_maxseg = so->so_snd.sb_hiwat;
3607 		if (tp->t_maxseg < V_tcp_mssdflt) {
3608 			/*
3609 			 * The MSS is so small we should not process incoming
3610 			 * SACK's since we are subject to attack in such a
3611 			 * case.
3612 			 */
3613 			tp->t_flags2 |= TF2_PROC_SACK_PROHIBIT;
3614 		} else {
3615 			tp->t_flags2 &= ~TF2_PROC_SACK_PROHIBIT;
3616 		}
3617 	}
3618 	SOCK_SENDBUF_UNLOCK(so);
3619 
3620 	TCPSTAT_INC(tcps_mturesent);
3621 	tp->t_rtttime = 0;
3622 	tp->snd_nxt = tp->snd_una;
3623 	tcp_free_sackholes(tp);
3624 	tp->snd_recover = tp->snd_max;
3625 	if (tp->t_flags & TF_SACK_PERMIT)
3626 		EXIT_FASTRECOVERY(tp->t_flags);
3627 	if (tp->t_fb->tfb_tcp_mtu_chg != NULL) {
3628 		/*
3629 		 * Conceptually the snd_nxt setting
3630 		 * and freeing sack holes should
3631 		 * be done by the default stacks
3632 		 * own tfb_tcp_mtu_chg().
3633 		 */
3634 		tp->t_fb->tfb_tcp_mtu_chg(tp);
3635 	}
3636 	if (tcp_output(tp) < 0)
3637 		return (NULL);
3638 	else
3639 		return (inp);
3640 }
3641 
3642 #ifdef INET
3643 /*
3644  * Look-up the routing entry to the peer of this inpcb.  If no route
3645  * is found and it cannot be allocated, then return 0.  This routine
3646  * is called by TCP routines that access the rmx structure and by
3647  * tcp_mss_update to get the peer/interface MTU.
3648  */
3649 uint32_t
tcp_maxmtu(struct in_conninfo * inc,struct tcp_ifcap * cap)3650 tcp_maxmtu(struct in_conninfo *inc, struct tcp_ifcap *cap)
3651 {
3652 	struct nhop_object *nh;
3653 	struct ifnet *ifp;
3654 	uint32_t maxmtu = 0;
3655 
3656 	KASSERT(inc != NULL, ("tcp_maxmtu with NULL in_conninfo pointer"));
3657 
3658 	if (inc->inc_faddr.s_addr != INADDR_ANY) {
3659 		nh = fib4_lookup(inc->inc_fibnum, inc->inc_faddr, 0, NHR_NONE, 0);
3660 		if (nh == NULL)
3661 			return (0);
3662 
3663 		ifp = nh->nh_ifp;
3664 		maxmtu = nh->nh_mtu;
3665 
3666 		/* Report additional interface capabilities. */
3667 		if (cap != NULL) {
3668 			if (ifp->if_capenable & IFCAP_TSO4 &&
3669 			    ifp->if_hwassist & CSUM_TSO) {
3670 				cap->ifcap |= CSUM_TSO;
3671 				cap->tsomax = ifp->if_hw_tsomax;
3672 				cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount;
3673 				cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize;
3674 				/* XXXKIB IFCAP2_IPSEC_OFFLOAD_TSO */
3675 				cap->ipsec_tso =  (ifp->if_capenable2 &
3676 				    IFCAP2_BIT(IFCAP2_IPSEC_OFFLOAD)) != 0;
3677 			}
3678 		}
3679 	}
3680 	return (maxmtu);
3681 }
3682 #endif /* INET */
3683 
3684 #ifdef INET6
3685 uint32_t
tcp_maxmtu6(struct in_conninfo * inc,struct tcp_ifcap * cap)3686 tcp_maxmtu6(struct in_conninfo *inc, struct tcp_ifcap *cap)
3687 {
3688 	struct nhop_object *nh;
3689 	struct in6_addr dst6;
3690 	uint32_t scopeid;
3691 	struct ifnet *ifp;
3692 	uint32_t maxmtu = 0;
3693 
3694 	KASSERT(inc != NULL, ("tcp_maxmtu6 with NULL in_conninfo pointer"));
3695 
3696 	if (inc->inc_flags & INC_IPV6MINMTU)
3697 		return (IPV6_MMTU);
3698 
3699 	if (!IN6_IS_ADDR_UNSPECIFIED(&inc->inc6_faddr)) {
3700 		in6_splitscope(&inc->inc6_faddr, &dst6, &scopeid);
3701 		nh = fib6_lookup(inc->inc_fibnum, &dst6, scopeid, NHR_NONE, 0);
3702 		if (nh == NULL)
3703 			return (0);
3704 
3705 		ifp = nh->nh_ifp;
3706 		maxmtu = nh->nh_mtu;
3707 
3708 		/* Report additional interface capabilities. */
3709 		if (cap != NULL) {
3710 			if (ifp->if_capenable & IFCAP_TSO6 &&
3711 			    ifp->if_hwassist & CSUM_TSO) {
3712 				cap->ifcap |= CSUM_TSO;
3713 				cap->tsomax = ifp->if_hw_tsomax;
3714 				cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount;
3715 				cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize;
3716 				cap->ipsec_tso = false; /* XXXKIB */
3717 			}
3718 		}
3719 	}
3720 
3721 	return (maxmtu);
3722 }
3723 
3724 /*
3725  * Handle setsockopt(IPV6_USE_MIN_MTU) by a TCP stack.
3726  *
3727  * XXXGL: we are updating inpcb here with INC_IPV6MINMTU flag.
3728  * The right place to do that is ip6_setpktopt() that has just been
3729  * executed.  By the way it just filled ip6po_minmtu for us.
3730  */
3731 void
tcp6_use_min_mtu(struct tcpcb * tp)3732 tcp6_use_min_mtu(struct tcpcb *tp)
3733 {
3734 	struct inpcb *inp = tptoinpcb(tp);
3735 
3736 	INP_WLOCK_ASSERT(inp);
3737 	/*
3738 	 * In case of the IPV6_USE_MIN_MTU socket
3739 	 * option, the INC_IPV6MINMTU flag to announce
3740 	 * a corresponding MSS during the initial
3741 	 * handshake.  If the TCP connection is not in
3742 	 * the front states, just reduce the MSS being
3743 	 * used.  This avoids the sending of TCP
3744 	 * segments which will be fragmented at the
3745 	 * IPv6 layer.
3746 	 */
3747 	inp->inp_inc.inc_flags |= INC_IPV6MINMTU;
3748 	if ((tp->t_state >= TCPS_SYN_SENT) &&
3749 	    (inp->inp_inc.inc_flags & INC_ISIPV6)) {
3750 		struct ip6_pktopts *opt;
3751 
3752 		opt = inp->in6p_outputopts;
3753 		if (opt != NULL && opt->ip6po_minmtu == IP6PO_MINMTU_ALL &&
3754 		    tp->t_maxseg > TCP6_MSS) {
3755 			tp->t_maxseg = TCP6_MSS;
3756 			if (tp->t_maxseg < V_tcp_mssdflt) {
3757 				/*
3758 				 * The MSS is so small we should not process incoming
3759 				 * SACK's since we are subject to attack in such a
3760 				 * case.
3761 				 */
3762 				tp->t_flags2 |= TF2_PROC_SACK_PROHIBIT;
3763 			} else {
3764 				tp->t_flags2 &= ~TF2_PROC_SACK_PROHIBIT;
3765 			}
3766 		}
3767 	}
3768 }
3769 #endif /* INET6 */
3770 
3771 /*
3772  * Calculate effective SMSS per RFC5681 definition for a given TCP
3773  * connection at its current state, taking into account SACK and etc.
3774  */
3775 u_int
tcp_maxseg(const struct tcpcb * tp)3776 tcp_maxseg(const struct tcpcb *tp)
3777 {
3778 	u_int optlen;
3779 
3780 	if (tp->t_flags & TF_NOOPT)
3781 		return (tp->t_maxseg);
3782 
3783 	/*
3784 	 * Here we have a simplified code from tcp_addoptions(),
3785 	 * without a proper loop, and having most of paddings hardcoded.
3786 	 * We might make mistakes with padding here in some edge cases,
3787 	 * but this is harmless, since result of tcp_maxseg() is used
3788 	 * only in cwnd and ssthresh estimations.
3789 	 */
3790 	if (TCPS_HAVEESTABLISHED(tp->t_state)) {
3791 		if (tp->t_flags & TF_RCVD_TSTMP)
3792 			optlen = TCPOLEN_TSTAMP_APPA;
3793 		else
3794 			optlen = 0;
3795 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3796 		if (tp->t_flags & TF_SIGNATURE)
3797 			optlen += PADTCPOLEN(TCPOLEN_SIGNATURE);
3798 #endif
3799 		if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks > 0) {
3800 			optlen += TCPOLEN_SACKHDR;
3801 			optlen += tp->rcv_numsacks * TCPOLEN_SACK;
3802 			optlen = PADTCPOLEN(optlen);
3803 		}
3804 	} else {
3805 		if (tp->t_flags & TF_REQ_TSTMP)
3806 			optlen = TCPOLEN_TSTAMP_APPA;
3807 		else
3808 			optlen = PADTCPOLEN(TCPOLEN_MAXSEG);
3809 		if (tp->t_flags & TF_REQ_SCALE)
3810 			optlen += PADTCPOLEN(TCPOLEN_WINDOW);
3811 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3812 		if (tp->t_flags & TF_SIGNATURE)
3813 			optlen += PADTCPOLEN(TCPOLEN_SIGNATURE);
3814 #endif
3815 		if (tp->t_flags & TF_SACK_PERMIT)
3816 			optlen += PADTCPOLEN(TCPOLEN_SACK_PERMITTED);
3817 	}
3818 	optlen = min(optlen, TCP_MAXOLEN);
3819 	return (tp->t_maxseg - optlen);
3820 }
3821 
3822 
3823 u_int
tcp_fixed_maxseg(const struct tcpcb * tp)3824 tcp_fixed_maxseg(const struct tcpcb *tp)
3825 {
3826 	int optlen;
3827 
3828 	if (tp->t_flags & TF_NOOPT)
3829 		return (tp->t_maxseg);
3830 
3831 	/*
3832 	 * Here we have a simplified code from tcp_addoptions(),
3833 	 * without a proper loop, and having most of paddings hardcoded.
3834 	 * We only consider fixed options that we would send every
3835 	 * time I.e. SACK is not considered. This is important
3836 	 * for cc modules to figure out what the modulo of the
3837 	 * cwnd should be.
3838 	 */
3839 	if (TCPS_HAVEESTABLISHED(tp->t_state)) {
3840 		if (tp->t_flags & TF_RCVD_TSTMP)
3841 			optlen = TCPOLEN_TSTAMP_APPA;
3842 		else
3843 			optlen = 0;
3844 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3845 		if (tp->t_flags & TF_SIGNATURE)
3846 			optlen += PADTCPOLEN(TCPOLEN_SIGNATURE);
3847 #endif
3848 	} else {
3849 		if (tp->t_flags & TF_REQ_TSTMP)
3850 			optlen = TCPOLEN_TSTAMP_APPA;
3851 		else
3852 			optlen = PADTCPOLEN(TCPOLEN_MAXSEG);
3853 		if (tp->t_flags & TF_REQ_SCALE)
3854 			optlen += PADTCPOLEN(TCPOLEN_WINDOW);
3855 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3856 		if (tp->t_flags & TF_SIGNATURE)
3857 			optlen += PADTCPOLEN(TCPOLEN_SIGNATURE);
3858 #endif
3859 		if (tp->t_flags & TF_SACK_PERMIT)
3860 			optlen += PADTCPOLEN(TCPOLEN_SACK_PERMITTED);
3861 	}
3862 	optlen = min(optlen, TCP_MAXOLEN);
3863 	return (tp->t_maxseg - optlen);
3864 }
3865 
3866 
3867 
3868 static int
sysctl_drop(SYSCTL_HANDLER_ARGS)3869 sysctl_drop(SYSCTL_HANDLER_ARGS)
3870 {
3871 	/* addrs[0] is a foreign socket, addrs[1] is a local one. */
3872 	struct sockaddr_storage addrs[2];
3873 	struct inpcb *inp;
3874 	struct tcpcb *tp;
3875 #ifdef INET
3876 	struct sockaddr_in *fin = NULL, *lin = NULL;
3877 #endif
3878 	struct epoch_tracker et;
3879 #ifdef INET6
3880 	struct sockaddr_in6 *fin6, *lin6;
3881 #endif
3882 	int error;
3883 
3884 	inp = NULL;
3885 #ifdef INET6
3886 	fin6 = lin6 = NULL;
3887 #endif
3888 	error = 0;
3889 
3890 	if (req->oldptr != NULL || req->oldlen != 0)
3891 		return (EINVAL);
3892 	if (req->newptr == NULL)
3893 		return (EPERM);
3894 	if (req->newlen < sizeof(addrs))
3895 		return (ENOMEM);
3896 	error = SYSCTL_IN(req, &addrs, sizeof(addrs));
3897 	if (error)
3898 		return (error);
3899 
3900 	switch (addrs[0].ss_family) {
3901 #ifdef INET6
3902 	case AF_INET6:
3903 		fin6 = (struct sockaddr_in6 *)&addrs[0];
3904 		lin6 = (struct sockaddr_in6 *)&addrs[1];
3905 		if (fin6->sin6_len != sizeof(struct sockaddr_in6) ||
3906 		    lin6->sin6_len != sizeof(struct sockaddr_in6))
3907 			return (EINVAL);
3908 		if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) {
3909 			if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr))
3910 				return (EINVAL);
3911 			in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]);
3912 			in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]);
3913 #ifdef INET
3914 			fin = (struct sockaddr_in *)&addrs[0];
3915 			lin = (struct sockaddr_in *)&addrs[1];
3916 #endif
3917 			break;
3918 		}
3919 		error = sa6_embedscope(fin6, V_ip6_use_defzone);
3920 		if (error)
3921 			return (error);
3922 		error = sa6_embedscope(lin6, V_ip6_use_defzone);
3923 		if (error)
3924 			return (error);
3925 		break;
3926 #endif
3927 #ifdef INET
3928 	case AF_INET:
3929 		fin = (struct sockaddr_in *)&addrs[0];
3930 		lin = (struct sockaddr_in *)&addrs[1];
3931 		if (fin->sin_len != sizeof(struct sockaddr_in) ||
3932 		    lin->sin_len != sizeof(struct sockaddr_in))
3933 			return (EINVAL);
3934 		break;
3935 #endif
3936 	default:
3937 		return (EINVAL);
3938 	}
3939 	NET_EPOCH_ENTER(et);
3940 	switch (addrs[0].ss_family) {
3941 #ifdef INET6
3942 	case AF_INET6:
3943 		inp = in6_pcblookup(&V_tcbinfo, &fin6->sin6_addr,
3944 		    fin6->sin6_port, &lin6->sin6_addr, lin6->sin6_port,
3945 		    INPLOOKUP_WLOCKPCB, NULL);
3946 		break;
3947 #endif
3948 #ifdef INET
3949 	case AF_INET:
3950 		inp = in_pcblookup(&V_tcbinfo, fin->sin_addr, fin->sin_port,
3951 		    lin->sin_addr, lin->sin_port, INPLOOKUP_WLOCKPCB, NULL);
3952 		break;
3953 #endif
3954 	}
3955 	if (inp != NULL) {
3956 		if (!SOLISTENING(inp->inp_socket)) {
3957 			tp = intotcpcb(inp);
3958 			tp = tcp_drop(tp, ECONNABORTED);
3959 			if (tp != NULL)
3960 				INP_WUNLOCK(inp);
3961 		} else
3962 			INP_WUNLOCK(inp);
3963 	} else
3964 		error = ESRCH;
3965 	NET_EPOCH_EXIT(et);
3966 	return (error);
3967 }
3968 
3969 SYSCTL_PROC(_net_inet_tcp, TCPCTL_DROP, drop,
3970     CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
3971     CTLFLAG_NEEDGIANT, NULL, 0, sysctl_drop, "",
3972     "Drop TCP connection");
3973 
3974 static int
tcp_sysctl_setsockopt(SYSCTL_HANDLER_ARGS)3975 tcp_sysctl_setsockopt(SYSCTL_HANDLER_ARGS)
3976 {
3977 	return (sysctl_setsockopt(oidp, arg1, arg2, req, &V_tcbinfo,
3978 	    &tcp_ctloutput_set));
3979 }
3980 
3981 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, setsockopt,
3982     CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
3983     CTLFLAG_MPSAFE, NULL, 0, tcp_sysctl_setsockopt, "",
3984     "Set socket option for TCP endpoint");
3985 
3986 #ifdef KERN_TLS
3987 static int
sysctl_switch_tls(SYSCTL_HANDLER_ARGS)3988 sysctl_switch_tls(SYSCTL_HANDLER_ARGS)
3989 {
3990 	/* addrs[0] is a foreign socket, addrs[1] is a local one. */
3991 	struct sockaddr_storage addrs[2];
3992 	struct inpcb *inp;
3993 #ifdef INET
3994 	struct sockaddr_in *fin = NULL, *lin = NULL;
3995 #endif
3996 	struct epoch_tracker et;
3997 #ifdef INET6
3998 	struct sockaddr_in6 *fin6, *lin6;
3999 #endif
4000 	int error;
4001 
4002 	inp = NULL;
4003 #ifdef INET6
4004 	fin6 = lin6 = NULL;
4005 #endif
4006 	error = 0;
4007 
4008 	if (req->oldptr != NULL || req->oldlen != 0)
4009 		return (EINVAL);
4010 	if (req->newptr == NULL)
4011 		return (EPERM);
4012 	if (req->newlen < sizeof(addrs))
4013 		return (ENOMEM);
4014 	error = SYSCTL_IN(req, &addrs, sizeof(addrs));
4015 	if (error)
4016 		return (error);
4017 
4018 	switch (addrs[0].ss_family) {
4019 #ifdef INET6
4020 	case AF_INET6:
4021 		fin6 = (struct sockaddr_in6 *)&addrs[0];
4022 		lin6 = (struct sockaddr_in6 *)&addrs[1];
4023 		if (fin6->sin6_len != sizeof(struct sockaddr_in6) ||
4024 		    lin6->sin6_len != sizeof(struct sockaddr_in6))
4025 			return (EINVAL);
4026 		if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) {
4027 			if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr))
4028 				return (EINVAL);
4029 			in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]);
4030 			in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]);
4031 #ifdef INET
4032 			fin = (struct sockaddr_in *)&addrs[0];
4033 			lin = (struct sockaddr_in *)&addrs[1];
4034 #endif
4035 			break;
4036 		}
4037 		error = sa6_embedscope(fin6, V_ip6_use_defzone);
4038 		if (error)
4039 			return (error);
4040 		error = sa6_embedscope(lin6, V_ip6_use_defzone);
4041 		if (error)
4042 			return (error);
4043 		break;
4044 #endif
4045 #ifdef INET
4046 	case AF_INET:
4047 		fin = (struct sockaddr_in *)&addrs[0];
4048 		lin = (struct sockaddr_in *)&addrs[1];
4049 		if (fin->sin_len != sizeof(struct sockaddr_in) ||
4050 		    lin->sin_len != sizeof(struct sockaddr_in))
4051 			return (EINVAL);
4052 		break;
4053 #endif
4054 	default:
4055 		return (EINVAL);
4056 	}
4057 	NET_EPOCH_ENTER(et);
4058 	switch (addrs[0].ss_family) {
4059 #ifdef INET6
4060 	case AF_INET6:
4061 		inp = in6_pcblookup(&V_tcbinfo, &fin6->sin6_addr,
4062 		    fin6->sin6_port, &lin6->sin6_addr, lin6->sin6_port,
4063 		    INPLOOKUP_WLOCKPCB, NULL);
4064 		break;
4065 #endif
4066 #ifdef INET
4067 	case AF_INET:
4068 		inp = in_pcblookup(&V_tcbinfo, fin->sin_addr, fin->sin_port,
4069 		    lin->sin_addr, lin->sin_port, INPLOOKUP_WLOCKPCB, NULL);
4070 		break;
4071 #endif
4072 	}
4073 	NET_EPOCH_EXIT(et);
4074 	if (inp != NULL) {
4075 		struct socket *so;
4076 
4077 		so = inp->inp_socket;
4078 		soref(so);
4079 		error = ktls_set_tx_mode(so,
4080 		    arg2 == 0 ? TCP_TLS_MODE_SW : TCP_TLS_MODE_IFNET);
4081 		INP_WUNLOCK(inp);
4082 		sorele(so);
4083 	} else
4084 		error = ESRCH;
4085 	return (error);
4086 }
4087 
4088 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, switch_to_sw_tls,
4089     CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
4090     CTLFLAG_NEEDGIANT, NULL, 0, sysctl_switch_tls, "",
4091     "Switch TCP connection to SW TLS");
4092 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, switch_to_ifnet_tls,
4093     CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
4094     CTLFLAG_NEEDGIANT, NULL, 1, sysctl_switch_tls, "",
4095     "Switch TCP connection to ifnet TLS");
4096 #endif
4097 
4098 /*
4099  * Generate a standardized TCP log line for use throughout the
4100  * tcp subsystem.  Memory allocation is done with M_NOWAIT to
4101  * allow use in the interrupt context.
4102  *
4103  * NB: The caller MUST free(s, M_TCPLOG) the returned string.
4104  * NB: The function may return NULL if memory allocation failed.
4105  *
4106  * Due to header inclusion and ordering limitations the struct ip
4107  * and ip6_hdr pointers have to be passed as void pointers.
4108  */
4109 char *
tcp_log_vain(struct in_conninfo * inc,struct tcphdr * th,const void * ip4hdr,const void * ip6hdr)4110 tcp_log_vain(struct in_conninfo *inc, struct tcphdr *th, const void *ip4hdr,
4111     const void *ip6hdr)
4112 {
4113 
4114 	/* Is logging enabled? */
4115 	if (V_tcp_log_in_vain == 0)
4116 		return (NULL);
4117 
4118 	return (tcp_log_addr(inc, th, ip4hdr, ip6hdr));
4119 }
4120 
4121 char *
tcp_log_addrs(struct in_conninfo * inc,struct tcphdr * th,const void * ip4hdr,const void * ip6hdr)4122 tcp_log_addrs(struct in_conninfo *inc, struct tcphdr *th, const void *ip4hdr,
4123     const void *ip6hdr)
4124 {
4125 
4126 	/* Is logging enabled? */
4127 	if (tcp_log_debug == 0)
4128 		return (NULL);
4129 
4130 	return (tcp_log_addr(inc, th, ip4hdr, ip6hdr));
4131 }
4132 
4133 static char *
tcp_log_addr(struct in_conninfo * inc,struct tcphdr * th,const void * ip4hdr,const void * ip6hdr)4134 tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th, const void *ip4hdr,
4135     const void *ip6hdr)
4136 {
4137 	char *s, *sp;
4138 	size_t size;
4139 #ifdef INET
4140 	const struct ip *ip = (const struct ip *)ip4hdr;
4141 #endif
4142 #ifdef INET6
4143 	const struct ip6_hdr *ip6 = (const struct ip6_hdr *)ip6hdr;
4144 #endif /* INET6 */
4145 
4146 	/*
4147 	 * The log line looks like this:
4148 	 * "TCP: [1.2.3.4]:50332 to [1.2.3.4]:80 tcpflags 0x2<SYN>"
4149 	 */
4150 	size = sizeof("TCP: []:12345 to []:12345 tcpflags 0x2<>") +
4151 	    sizeof(PRINT_TH_FLAGS) + 1 +
4152 #ifdef INET6
4153 	    2 * INET6_ADDRSTRLEN;
4154 #else
4155 	    2 * INET_ADDRSTRLEN;
4156 #endif /* INET6 */
4157 
4158 	s = malloc(size, M_TCPLOG, M_ZERO|M_NOWAIT);
4159 	if (s == NULL)
4160 		return (NULL);
4161 
4162 	strcat(s, "TCP: [");
4163 	sp = s + strlen(s);
4164 
4165 	if (inc && ((inc->inc_flags & INC_ISIPV6) == 0)) {
4166 		inet_ntoa_r(inc->inc_faddr, sp);
4167 		sp = s + strlen(s);
4168 		sprintf(sp, "]:%i to [", ntohs(inc->inc_fport));
4169 		sp = s + strlen(s);
4170 		inet_ntoa_r(inc->inc_laddr, sp);
4171 		sp = s + strlen(s);
4172 		sprintf(sp, "]:%i", ntohs(inc->inc_lport));
4173 #ifdef INET6
4174 	} else if (inc) {
4175 		ip6_sprintf(sp, &inc->inc6_faddr);
4176 		sp = s + strlen(s);
4177 		sprintf(sp, "]:%i to [", ntohs(inc->inc_fport));
4178 		sp = s + strlen(s);
4179 		ip6_sprintf(sp, &inc->inc6_laddr);
4180 		sp = s + strlen(s);
4181 		sprintf(sp, "]:%i", ntohs(inc->inc_lport));
4182 	} else if (ip6 && th) {
4183 		ip6_sprintf(sp, &ip6->ip6_src);
4184 		sp = s + strlen(s);
4185 		sprintf(sp, "]:%i to [", ntohs(th->th_sport));
4186 		sp = s + strlen(s);
4187 		ip6_sprintf(sp, &ip6->ip6_dst);
4188 		sp = s + strlen(s);
4189 		sprintf(sp, "]:%i", ntohs(th->th_dport));
4190 #endif /* INET6 */
4191 #ifdef INET
4192 	} else if (ip && th) {
4193 		inet_ntoa_r(ip->ip_src, sp);
4194 		sp = s + strlen(s);
4195 		sprintf(sp, "]:%i to [", ntohs(th->th_sport));
4196 		sp = s + strlen(s);
4197 		inet_ntoa_r(ip->ip_dst, sp);
4198 		sp = s + strlen(s);
4199 		sprintf(sp, "]:%i", ntohs(th->th_dport));
4200 #endif /* INET */
4201 	} else {
4202 		free(s, M_TCPLOG);
4203 		return (NULL);
4204 	}
4205 	sp = s + strlen(s);
4206 	if (th)
4207 		sprintf(sp, " tcpflags 0x%b", tcp_get_flags(th), PRINT_TH_FLAGS);
4208 	if (*(s + size - 1) != '\0')
4209 		panic("%s: string too long", __func__);
4210 	return (s);
4211 }
4212 
4213 /*
4214  * A subroutine which makes it easy to track TCP state changes with DTrace.
4215  * This function shouldn't be called for t_state initializations that don't
4216  * correspond to actual TCP state transitions.
4217  */
4218 void
tcp_state_change(struct tcpcb * tp,int newstate)4219 tcp_state_change(struct tcpcb *tp, int newstate)
4220 {
4221 #if defined(KDTRACE_HOOKS)
4222 	int pstate = tp->t_state;
4223 #endif
4224 
4225 	TCPSTATES_DEC(tp->t_state);
4226 	TCPSTATES_INC(newstate);
4227 	tp->t_state = newstate;
4228 	TCP_PROBE6(state__change, NULL, tp, NULL, tp, NULL, pstate);
4229 }
4230 
4231 /*
4232  * Create an external-format (``xtcpcb'') structure using the information in
4233  * the kernel-format tcpcb structure pointed to by tp.  This is done to
4234  * reduce the spew of irrelevant information over this interface, to isolate
4235  * user code from changes in the kernel structure, and potentially to provide
4236  * information-hiding if we decide that some of this information should be
4237  * hidden from users.
4238  */
4239 void
tcp_inptoxtp(const struct inpcb * inp,struct xtcpcb * xt)4240 tcp_inptoxtp(const struct inpcb *inp, struct xtcpcb *xt)
4241 {
4242 	struct tcpcb *tp = intotcpcb(inp);
4243 	sbintime_t now;
4244 
4245 	bzero(xt, sizeof(*xt));
4246 	xt->t_state = tp->t_state;
4247 	xt->t_logstate = tcp_get_bblog_state(tp);
4248 	xt->t_flags = tp->t_flags;
4249 	xt->t_sndzerowin = tp->t_sndzerowin;
4250 	xt->t_sndrexmitpack = tp->t_sndrexmitpack;
4251 	xt->t_rcvoopack = tp->t_rcvoopack;
4252 	xt->t_rcv_wnd = tp->rcv_wnd;
4253 	xt->t_snd_wnd = tp->snd_wnd;
4254 	xt->t_snd_cwnd = tp->snd_cwnd;
4255 	xt->t_snd_ssthresh = tp->snd_ssthresh;
4256 	xt->t_dsack_bytes = tp->t_dsack_bytes;
4257 	xt->t_dsack_tlp_bytes = tp->t_dsack_tlp_bytes;
4258 	xt->t_dsack_pack = tp->t_dsack_pack;
4259 	xt->t_maxseg = tp->t_maxseg;
4260 	xt->xt_ecn = (tp->t_flags2 & TF2_ECN_PERMIT) ? 1 : 0 +
4261 		     (tp->t_flags2 & TF2_ACE_PERMIT) ? 2 : 0;
4262 
4263 	now = getsbinuptime();
4264 #define	COPYTIMER(which,where)	do {					\
4265 	if (tp->t_timers[which] != SBT_MAX)				\
4266 		xt->where = (tp->t_timers[which] - now) / SBT_1MS;	\
4267 	else								\
4268 		xt->where = 0;						\
4269 } while (0)
4270 	COPYTIMER(TT_DELACK, tt_delack);
4271 	COPYTIMER(TT_REXMT, tt_rexmt);
4272 	COPYTIMER(TT_PERSIST, tt_persist);
4273 	COPYTIMER(TT_KEEP, tt_keep);
4274 	COPYTIMER(TT_2MSL, tt_2msl);
4275 #undef COPYTIMER
4276 	xt->t_rcvtime = 1000 * (ticks - tp->t_rcvtime) / hz;
4277 
4278 	xt->xt_encaps_port = tp->t_port;
4279 	bcopy(tp->t_fb->tfb_tcp_block_name, xt->xt_stack,
4280 	    TCP_FUNCTION_NAME_LEN_MAX);
4281 	bcopy(CC_ALGO(tp)->name, xt->xt_cc, TCP_CA_NAME_MAX);
4282 #ifdef TCP_BLACKBOX
4283 	(void)tcp_log_get_id(tp, xt->xt_logid);
4284 	xt->t_lognum = tp->t_lognum;
4285 	xt->t_loglimit = tp->t_loglimit;
4286 	xt->t_logsn = tp->t_logsn;
4287 #endif
4288 
4289 	xt->xt_len = sizeof(struct xtcpcb);
4290 	in_pcbtoxinpcb(inp, &xt->xt_inp);
4291 }
4292 
4293 void
tcp_log_end_status(struct tcpcb * tp,uint8_t status)4294 tcp_log_end_status(struct tcpcb *tp, uint8_t status)
4295 {
4296 	uint32_t bit, i;
4297 
4298 	if ((tp == NULL) ||
4299 	    (status > TCP_EI_STATUS_MAX_VALUE) ||
4300 	    (status == 0)) {
4301 		/* Invalid */
4302 		return;
4303 	}
4304 	if (status > (sizeof(uint32_t) * 8)) {
4305 		/* Should this be a KASSERT? */
4306 		return;
4307 	}
4308 	bit = 1U << (status - 1);
4309 	if (bit & tp->t_end_info_status) {
4310 		/* already logged */
4311 		return;
4312 	}
4313 	for (i = 0; i < TCP_END_BYTE_INFO; i++) {
4314 		if (tp->t_end_info_bytes[i] == TCP_EI_EMPTY_SLOT) {
4315 			tp->t_end_info_bytes[i] = status;
4316 			tp->t_end_info_status |= bit;
4317 			break;
4318 		}
4319 	}
4320 }
4321 
4322 int
tcp_can_enable_pacing(void)4323 tcp_can_enable_pacing(void)
4324 {
4325 
4326 	if ((tcp_pacing_limit == -1) ||
4327 	    (tcp_pacing_limit > number_of_tcp_connections_pacing)) {
4328 		atomic_fetchadd_int(&number_of_tcp_connections_pacing, 1);
4329 		shadow_num_connections = number_of_tcp_connections_pacing;
4330 		return (1);
4331 	} else {
4332 		counter_u64_add(tcp_pacing_failures, 1);
4333 		return (0);
4334 	}
4335 }
4336 
4337 int
tcp_incr_dgp_pacing_cnt(void)4338 tcp_incr_dgp_pacing_cnt(void)
4339 {
4340 	if ((tcp_dgp_limit == -1) ||
4341 	    (tcp_dgp_limit > number_of_dgp_connections)) {
4342 		atomic_fetchadd_int(&number_of_dgp_connections, 1);
4343 		shadow_tcp_pacing_dgp = number_of_dgp_connections;
4344 		return (1);
4345 	} else {
4346 		counter_u64_add(tcp_dgp_failures, 1);
4347 		return (0);
4348 	}
4349 }
4350 
4351 static uint8_t tcp_dgp_warning = 0;
4352 
4353 void
tcp_dec_dgp_pacing_cnt(void)4354 tcp_dec_dgp_pacing_cnt(void)
4355 {
4356 	uint32_t ret;
4357 
4358 	ret = atomic_fetchadd_int(&number_of_dgp_connections, -1);
4359 	shadow_tcp_pacing_dgp = number_of_dgp_connections;
4360 	KASSERT(ret != 0, ("number_of_dgp_connections -1 would cause wrap?"));
4361 	if (ret == 0) {
4362 		if (tcp_dgp_limit != -1) {
4363 			printf("Warning all DGP is now disabled, count decrements invalidly!\n");
4364 			tcp_dgp_limit = 0;
4365 			tcp_dgp_warning = 1;
4366 		} else if (tcp_dgp_warning == 0) {
4367 			printf("Warning DGP pacing is invalid, invalid decrement\n");
4368 			tcp_dgp_warning = 1;
4369 		}
4370 	}
4371 
4372 }
4373 
4374 static uint8_t tcp_pacing_warning = 0;
4375 
4376 void
tcp_decrement_paced_conn(void)4377 tcp_decrement_paced_conn(void)
4378 {
4379 	uint32_t ret;
4380 
4381 	ret = atomic_fetchadd_int(&number_of_tcp_connections_pacing, -1);
4382 	shadow_num_connections = number_of_tcp_connections_pacing;
4383 	KASSERT(ret != 0, ("tcp_paced_connection_exits -1 would cause wrap?"));
4384 	if (ret == 0) {
4385 		if (tcp_pacing_limit != -1) {
4386 			printf("Warning all pacing is now disabled, count decrements invalidly!\n");
4387 			tcp_pacing_limit = 0;
4388 		} else if (tcp_pacing_warning == 0) {
4389 			printf("Warning pacing count is invalid, invalid decrement\n");
4390 			tcp_pacing_warning = 1;
4391 		}
4392 	}
4393 }
4394 
4395 static void
tcp_default_switch_failed(struct tcpcb * tp)4396 tcp_default_switch_failed(struct tcpcb *tp)
4397 {
4398 	/*
4399 	 * If a switch fails we only need to
4400 	 * care about two things:
4401 	 * a) The t_flags2
4402 	 * and
4403 	 * b) The timer granularity.
4404 	 * Timeouts, at least for now, don't use the
4405 	 * old callout system in the other stacks so
4406 	 * those are hopefully safe.
4407 	 */
4408 	tcp_lro_features_off(tp);
4409 	tcp_change_time_units(tp, TCP_TMR_GRANULARITY_TICKS);
4410 }
4411 
4412 #ifdef TCP_ACCOUNTING
4413 int
tcp_do_ack_accounting(struct tcpcb * tp,struct tcphdr * th,struct tcpopt * to,uint32_t tiwin,int mss)4414 tcp_do_ack_accounting(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to, uint32_t tiwin, int mss)
4415 {
4416 	if (SEQ_LT(th->th_ack, tp->snd_una)) {
4417 		/* Do we have a SACK? */
4418 		if (to->to_flags & TOF_SACK) {
4419 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4420 				tp->tcp_cnt_counters[ACK_SACK]++;
4421 			}
4422 			return (ACK_SACK);
4423 		} else {
4424 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4425 				tp->tcp_cnt_counters[ACK_BEHIND]++;
4426 			}
4427 			return (ACK_BEHIND);
4428 		}
4429 	} else if (th->th_ack == tp->snd_una) {
4430 		/* Do we have a SACK? */
4431 		if (to->to_flags & TOF_SACK) {
4432 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4433 				tp->tcp_cnt_counters[ACK_SACK]++;
4434 			}
4435 			return (ACK_SACK);
4436 		} else if (tiwin != tp->snd_wnd) {
4437 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4438 				tp->tcp_cnt_counters[ACK_RWND]++;
4439 			}
4440 			return (ACK_RWND);
4441 		} else {
4442 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4443 				tp->tcp_cnt_counters[ACK_DUPACK]++;
4444 			}
4445 			return (ACK_DUPACK);
4446 		}
4447 	} else {
4448 		if (!SEQ_GT(th->th_ack, tp->snd_max)) {
4449 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4450 				tp->tcp_cnt_counters[CNT_OF_ACKS_IN] += (((th->th_ack - tp->snd_una) + mss - 1)/mss);
4451 			}
4452 		}
4453 		if (to->to_flags & TOF_SACK) {
4454 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4455 				tp->tcp_cnt_counters[ACK_CUMACK_SACK]++;
4456 			}
4457 			return (ACK_CUMACK_SACK);
4458 		} else {
4459 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
4460 				tp->tcp_cnt_counters[ACK_CUMACK]++;
4461 			}
4462 			return (ACK_CUMACK);
4463 		}
4464 	}
4465 }
4466 #endif
4467 
4468 void
tcp_change_time_units(struct tcpcb * tp,int granularity)4469 tcp_change_time_units(struct tcpcb *tp, int granularity)
4470 {
4471 	if (tp->t_tmr_granularity == granularity) {
4472 		/* We are there */
4473 		return;
4474 	}
4475 	if (granularity == TCP_TMR_GRANULARITY_USEC) {
4476 		KASSERT((tp->t_tmr_granularity == TCP_TMR_GRANULARITY_TICKS),
4477 			("Granularity is not TICKS its %u in tp:%p",
4478 			 tp->t_tmr_granularity, tp));
4479 		tp->t_rttlow = TICKS_2_USEC(tp->t_rttlow);
4480 		if (tp->t_srtt > 1) {
4481 			uint32_t val, frac;
4482 
4483 			val = tp->t_srtt >> TCP_RTT_SHIFT;
4484 			frac = tp->t_srtt & 0x1f;
4485 			tp->t_srtt = TICKS_2_USEC(val);
4486 			/*
4487 			 * frac is the fractional part of the srtt (if any)
4488 			 * but its in ticks and every bit represents
4489 			 * 1/32nd of a hz.
4490 			 */
4491 			if (frac) {
4492 				if (hz == 1000) {
4493 					frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_MSEC) / (uint64_t)TCP_RTT_SCALE);
4494 				} else {
4495 					frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_SEC) / ((uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE));
4496 				}
4497 				tp->t_srtt += frac;
4498 			}
4499 		}
4500 		if (tp->t_rttvar) {
4501 			uint32_t val, frac;
4502 
4503 			val = tp->t_rttvar >> TCP_RTTVAR_SHIFT;
4504 			frac = tp->t_rttvar & 0x1f;
4505 			tp->t_rttvar = TICKS_2_USEC(val);
4506 			/*
4507 			 * frac is the fractional part of the srtt (if any)
4508 			 * but its in ticks and every bit represents
4509 			 * 1/32nd of a hz.
4510 			 */
4511 			if (frac) {
4512 				if (hz == 1000) {
4513 					frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_MSEC) / (uint64_t)TCP_RTT_SCALE);
4514 				} else {
4515 					frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_SEC) / ((uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE));
4516 				}
4517 				tp->t_rttvar += frac;
4518 			}
4519 		}
4520 		tp->t_tmr_granularity = TCP_TMR_GRANULARITY_USEC;
4521 	} else if (granularity == TCP_TMR_GRANULARITY_TICKS) {
4522 		/* Convert back to ticks, with  */
4523 		KASSERT((tp->t_tmr_granularity == TCP_TMR_GRANULARITY_USEC),
4524 			("Granularity is not USEC its %u in tp:%p",
4525 			 tp->t_tmr_granularity, tp));
4526 		if (tp->t_srtt > 1) {
4527 			uint32_t val, frac;
4528 
4529 			val = USEC_2_TICKS(tp->t_srtt);
4530 			frac = tp->t_srtt % (HPTS_USEC_IN_SEC / hz);
4531 			tp->t_srtt = val << TCP_RTT_SHIFT;
4532 			/*
4533 			 * frac is the fractional part here is left
4534 			 * over from converting to hz and shifting.
4535 			 * We need to convert this to the 5 bit
4536 			 * remainder.
4537 			 */
4538 			if (frac) {
4539 				if (hz == 1000) {
4540 					frac = (((uint64_t)frac *  (uint64_t)TCP_RTT_SCALE) / (uint64_t)HPTS_USEC_IN_MSEC);
4541 				} else {
4542 					frac = (((uint64_t)frac * (uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE) /(uint64_t)HPTS_USEC_IN_SEC);
4543 				}
4544 				tp->t_srtt += frac;
4545 			}
4546 		}
4547 		if (tp->t_rttvar) {
4548 			uint32_t val, frac;
4549 
4550 			val = USEC_2_TICKS(tp->t_rttvar);
4551 			frac = tp->t_rttvar % (HPTS_USEC_IN_SEC / hz);
4552 			tp->t_rttvar = val <<  TCP_RTTVAR_SHIFT;
4553 			/*
4554 			 * frac is the fractional part here is left
4555 			 * over from converting to hz and shifting.
4556 			 * We need to convert this to the 4 bit
4557 			 * remainder.
4558 			 */
4559 			if (frac) {
4560 				if (hz == 1000) {
4561 					frac = (((uint64_t)frac *  (uint64_t)TCP_RTTVAR_SCALE) / (uint64_t)HPTS_USEC_IN_MSEC);
4562 				} else {
4563 					frac = (((uint64_t)frac * (uint64_t)(hz) * (uint64_t)TCP_RTTVAR_SCALE) /(uint64_t)HPTS_USEC_IN_SEC);
4564 				}
4565 				tp->t_rttvar += frac;
4566 			}
4567 		}
4568 		tp->t_rttlow = USEC_2_TICKS(tp->t_rttlow);
4569 		tp->t_tmr_granularity = TCP_TMR_GRANULARITY_TICKS;
4570 	}
4571 #ifdef INVARIANTS
4572 	else {
4573 		panic("Unknown granularity:%d tp:%p",
4574 		      granularity, tp);
4575 	}
4576 #endif
4577 }
4578 
4579 void
tcp_handle_orphaned_packets(struct tcpcb * tp)4580 tcp_handle_orphaned_packets(struct tcpcb *tp)
4581 {
4582 	struct mbuf *save, *m, *prev;
4583 	/*
4584 	 * Called when a stack switch is occuring from the fini()
4585 	 * of the old stack. We assue the init() as already been
4586 	 * run of the new stack and it has set the t_flags2 to
4587 	 * what it supports. This function will then deal with any
4588 	 * differences i.e. cleanup packets that maybe queued that
4589 	 * the newstack does not support.
4590 	 */
4591 
4592 	if (tp->t_flags2 & TF2_MBUF_L_ACKS)
4593 		return;
4594 	if ((tp->t_flags2 & TF2_SUPPORTS_MBUFQ) == 0 &&
4595 	    !STAILQ_EMPTY(&tp->t_inqueue)) {
4596 		/*
4597 		 * It is unsafe to process the packets since a
4598 		 * reset may be lurking in them (its rare but it
4599 		 * can occur). If we were to find a RST, then we
4600 		 * would end up dropping the connection and the
4601 		 * INP lock, so when we return the caller (tcp_usrreq)
4602 		 * will blow up when it trys to unlock the inp.
4603 		 * This new stack does not do any fancy LRO features
4604 		 * so all we can do is toss the packets.
4605 		 */
4606 		m = STAILQ_FIRST(&tp->t_inqueue);
4607 		STAILQ_INIT(&tp->t_inqueue);
4608 		STAILQ_FOREACH_FROM_SAFE(m, &tp->t_inqueue, m_stailqpkt, save)
4609 			m_freem(m);
4610 	} else {
4611 		/*
4612 		 * Here we have a stack that does mbuf queuing but
4613 		 * does not support compressed ack's. We must
4614 		 * walk all the mbufs and discard any compressed acks.
4615 		 */
4616 		STAILQ_FOREACH_SAFE(m, &tp->t_inqueue, m_stailqpkt, save) {
4617 			if (m->m_flags & M_ACKCMP) {
4618 				if (m == STAILQ_FIRST(&tp->t_inqueue))
4619 					STAILQ_REMOVE_HEAD(&tp->t_inqueue,
4620 					    m_stailqpkt);
4621 				else
4622 					STAILQ_REMOVE_AFTER(&tp->t_inqueue,
4623 					    prev, m_stailqpkt);
4624 				m_freem(m);
4625 			} else
4626 				prev = m;
4627 		}
4628 	}
4629 }
4630 
4631 #ifdef TCP_REQUEST_TRK
4632 uint32_t
tcp_estimate_tls_overhead(struct socket * so,uint64_t tls_usr_bytes)4633 tcp_estimate_tls_overhead(struct socket *so, uint64_t tls_usr_bytes)
4634 {
4635 #ifdef KERN_TLS
4636 	struct ktls_session *tls;
4637 	uint32_t rec_oh, records;
4638 
4639 	tls = so->so_snd.sb_tls_info;
4640 	if (tls == NULL)
4641 	    return (0);
4642 
4643 	rec_oh = tls->params.tls_hlen + tls->params.tls_tlen;
4644 	records = ((tls_usr_bytes + tls->params.max_frame_len - 1)/tls->params.max_frame_len);
4645 	return (records * rec_oh);
4646 #else
4647 	return (0);
4648 #endif
4649 }
4650 
4651 extern uint32_t tcp_stale_entry_time;
4652 uint32_t tcp_stale_entry_time = 250000;
4653 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, usrlog_stale, CTLFLAG_RW,
4654     &tcp_stale_entry_time, 250000, "Time that a tcpreq entry without a sendfile ages out");
4655 
4656 void
tcp_req_log_req_info(struct tcpcb * tp,struct tcp_sendfile_track * req,uint16_t slot,uint8_t val,uint64_t offset,uint64_t nbytes)4657 tcp_req_log_req_info(struct tcpcb *tp, struct tcp_sendfile_track *req,
4658     uint16_t slot, uint8_t val, uint64_t offset, uint64_t nbytes)
4659 {
4660 	if (tcp_bblogging_on(tp)) {
4661 		union tcp_log_stackspecific log;
4662 		struct timeval tv;
4663 
4664 		memset(&log, 0, sizeof(log));
4665 		log.u_bbr.inhpts = tcp_in_hpts(tp);
4666 		log.u_bbr.flex8 = val;
4667 		log.u_bbr.rttProp = req->timestamp;
4668 		log.u_bbr.delRate = req->start;
4669 		log.u_bbr.cur_del_rate = req->end;
4670 		log.u_bbr.flex1 = req->start_seq;
4671 		log.u_bbr.flex2 = req->end_seq;
4672 		log.u_bbr.flex3 = req->flags;
4673 		log.u_bbr.flex4 = ((req->localtime >> 32) & 0x00000000ffffffff);
4674 		log.u_bbr.flex5 = (req->localtime & 0x00000000ffffffff);
4675 		log.u_bbr.flex7 = slot;
4676 		log.u_bbr.bw_inuse = offset;
4677 		/* nbytes = flex6 | epoch */
4678 		log.u_bbr.flex6 = ((nbytes >> 32) & 0x00000000ffffffff);
4679 		log.u_bbr.epoch = (nbytes & 0x00000000ffffffff);
4680 		/* cspr =  lt_epoch | pkts_out */
4681 		log.u_bbr.lt_epoch = ((req->cspr >> 32) & 0x00000000ffffffff);
4682 		log.u_bbr.pkts_out |= (req->cspr & 0x00000000ffffffff);
4683 		log.u_bbr.applimited = tp->t_tcpreq_closed;
4684 		log.u_bbr.applimited <<= 8;
4685 		log.u_bbr.applimited |= tp->t_tcpreq_open;
4686 		log.u_bbr.applimited <<= 8;
4687 		log.u_bbr.applimited |= tp->t_tcpreq_req;
4688 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
4689 		TCP_LOG_EVENTP(tp, NULL,
4690 		    &tptosocket(tp)->so_rcv,
4691 		    &tptosocket(tp)->so_snd,
4692 		    TCP_LOG_REQ_T, 0,
4693 		    0, &log, false, &tv);
4694 	}
4695 }
4696 
4697 void
tcp_req_free_a_slot(struct tcpcb * tp,struct tcp_sendfile_track * ent)4698 tcp_req_free_a_slot(struct tcpcb *tp, struct tcp_sendfile_track *ent)
4699 {
4700 	if (tp->t_tcpreq_req > 0)
4701 		tp->t_tcpreq_req--;
4702 	if (ent->flags & TCP_TRK_TRACK_FLG_OPEN) {
4703 		if (tp->t_tcpreq_open > 0)
4704 			tp->t_tcpreq_open--;
4705 	} else {
4706 		if (tp->t_tcpreq_closed > 0)
4707 			tp->t_tcpreq_closed--;
4708 	}
4709 	ent->flags = TCP_TRK_TRACK_FLG_EMPTY;
4710 }
4711 
4712 static void
tcp_req_check_for_stale_entries(struct tcpcb * tp,uint64_t ts,int rm_oldest)4713 tcp_req_check_for_stale_entries(struct tcpcb *tp, uint64_t ts, int rm_oldest)
4714 {
4715 	struct tcp_sendfile_track *ent;
4716 	uint64_t time_delta, oldest_delta;
4717 	int i, oldest, oldest_set = 0, cnt_rm = 0;
4718 
4719 	for (i = 0; i < MAX_TCP_TRK_REQ; i++) {
4720 		ent = &tp->t_tcpreq_info[i];
4721 		if (ent->flags != TCP_TRK_TRACK_FLG_USED) {
4722 			/*
4723 			 * We only care about closed end ranges
4724 			 * that are allocated and have no sendfile
4725 			 * ever touching them. They would be in
4726 			 * state USED.
4727 			 */
4728 			continue;
4729 		}
4730 		if (ts >= ent->localtime)
4731 			time_delta = ts - ent->localtime;
4732 		else
4733 			time_delta = 0;
4734 		if (time_delta &&
4735 		    ((oldest_delta < time_delta) || (oldest_set == 0))) {
4736 			oldest_set = 1;
4737 			oldest = i;
4738 			oldest_delta = time_delta;
4739 		}
4740 		if (tcp_stale_entry_time && (time_delta >= tcp_stale_entry_time)) {
4741 			/*
4742 			 * No sendfile in a our time-limit
4743 			 * time to purge it.
4744 			 */
4745 			cnt_rm++;
4746 			tcp_req_log_req_info(tp, &tp->t_tcpreq_info[i], i, TCP_TRK_REQ_LOG_STALE,
4747 					      time_delta, 0);
4748 			tcp_req_free_a_slot(tp, ent);
4749 		}
4750 	}
4751 	if ((cnt_rm == 0) && rm_oldest && oldest_set) {
4752 		ent = &tp->t_tcpreq_info[oldest];
4753 		tcp_req_log_req_info(tp, &tp->t_tcpreq_info[i], i, TCP_TRK_REQ_LOG_STALE,
4754 				      oldest_delta, 1);
4755 		tcp_req_free_a_slot(tp, ent);
4756 	}
4757 }
4758 
4759 int
tcp_req_check_for_comp(struct tcpcb * tp,tcp_seq ack_point)4760 tcp_req_check_for_comp(struct tcpcb *tp, tcp_seq ack_point)
4761 {
4762 	int i, ret = 0;
4763 	struct tcp_sendfile_track *ent;
4764 
4765 	/* Clean up any old closed end requests that are now completed */
4766 	if (tp->t_tcpreq_req == 0)
4767 		return (0);
4768 	if (tp->t_tcpreq_closed == 0)
4769 		return (0);
4770 	for (i = 0; i < MAX_TCP_TRK_REQ; i++) {
4771 		ent = &tp->t_tcpreq_info[i];
4772 		/* Skip empty ones */
4773 		if (ent->flags == TCP_TRK_TRACK_FLG_EMPTY)
4774 			continue;
4775 		/* Skip open ones */
4776 		if (ent->flags & TCP_TRK_TRACK_FLG_OPEN)
4777 			continue;
4778 		if (SEQ_GEQ(ack_point, ent->end_seq)) {
4779 			/* We are past it -- free it */
4780 			tcp_req_log_req_info(tp, ent,
4781 					      i, TCP_TRK_REQ_LOG_FREED, 0, 0);
4782 			tcp_req_free_a_slot(tp, ent);
4783 			ret++;
4784 		}
4785 	}
4786 	return (ret);
4787 }
4788 
4789 int
tcp_req_is_entry_comp(struct tcpcb * tp,struct tcp_sendfile_track * ent,tcp_seq ack_point)4790 tcp_req_is_entry_comp(struct tcpcb *tp, struct tcp_sendfile_track *ent, tcp_seq ack_point)
4791 {
4792 	if (tp->t_tcpreq_req == 0)
4793 		return (-1);
4794 	if (tp->t_tcpreq_closed == 0)
4795 		return (-1);
4796 	if (ent->flags == TCP_TRK_TRACK_FLG_EMPTY)
4797 		return (-1);
4798 	if (SEQ_GEQ(ack_point, ent->end_seq)) {
4799 		return (1);
4800 	}
4801 	return (0);
4802 }
4803 
4804 struct tcp_sendfile_track *
tcp_req_find_a_req_that_is_completed_by(struct tcpcb * tp,tcp_seq th_ack,int * ip)4805 tcp_req_find_a_req_that_is_completed_by(struct tcpcb *tp, tcp_seq th_ack, int *ip)
4806 {
4807 	/*
4808 	 * Given an ack point (th_ack) walk through our entries and
4809 	 * return the first one found that th_ack goes past the
4810 	 * end_seq.
4811 	 */
4812 	struct tcp_sendfile_track *ent;
4813 	int i;
4814 
4815 	if (tp->t_tcpreq_req == 0) {
4816 		/* none open */
4817 		return (NULL);
4818 	}
4819 	for (i = 0; i < MAX_TCP_TRK_REQ; i++) {
4820 		ent = &tp->t_tcpreq_info[i];
4821 		if (ent->flags == TCP_TRK_TRACK_FLG_EMPTY)
4822 			continue;
4823 		if ((ent->flags & TCP_TRK_TRACK_FLG_OPEN) == 0) {
4824 			if (SEQ_GEQ(th_ack, ent->end_seq)) {
4825 				*ip = i;
4826 				return (ent);
4827 			}
4828 		}
4829 	}
4830 	return (NULL);
4831 }
4832 
4833 struct tcp_sendfile_track *
tcp_req_find_req_for_seq(struct tcpcb * tp,tcp_seq seq)4834 tcp_req_find_req_for_seq(struct tcpcb *tp, tcp_seq seq)
4835 {
4836 	struct tcp_sendfile_track *ent;
4837 	int i;
4838 
4839 	if (tp->t_tcpreq_req == 0) {
4840 		/* none open */
4841 		return (NULL);
4842 	}
4843 	for (i = 0; i < MAX_TCP_TRK_REQ; i++) {
4844 		ent = &tp->t_tcpreq_info[i];
4845 		tcp_req_log_req_info(tp, ent, i, TCP_TRK_REQ_LOG_SEARCH,
4846 				      (uint64_t)seq, 0);
4847 		if (ent->flags == TCP_TRK_TRACK_FLG_EMPTY) {
4848 			continue;
4849 		}
4850 		if (ent->flags & TCP_TRK_TRACK_FLG_OPEN) {
4851 			/*
4852 			 * An open end request only needs to
4853 			 * match the beginning seq or be
4854 			 * all we have (once we keep going on
4855 			 * a open end request we may have a seq
4856 			 * wrap).
4857 			 */
4858 			if ((SEQ_GEQ(seq, ent->start_seq)) ||
4859 			    (tp->t_tcpreq_closed == 0))
4860 				return (ent);
4861 		} else {
4862 			/*
4863 			 * For this one we need to
4864 			 * be a bit more careful if its
4865 			 * completed at least.
4866 			 */
4867 			if ((SEQ_GEQ(seq, ent->start_seq)) &&
4868 			    (SEQ_LT(seq, ent->end_seq))) {
4869 				return (ent);
4870 			}
4871 		}
4872 	}
4873 	return (NULL);
4874 }
4875 
4876 /* Should this be in its own file tcp_req.c ? */
4877 struct tcp_sendfile_track *
tcp_req_alloc_req_full(struct tcpcb * tp,struct tcp_snd_req * req,uint64_t ts,int rec_dups)4878 tcp_req_alloc_req_full(struct tcpcb *tp, struct tcp_snd_req *req, uint64_t ts, int rec_dups)
4879 {
4880 	struct tcp_sendfile_track *fil;
4881 	int i, allocated;
4882 
4883 	/* Allocate the request tracking array on demand */
4884 	if (tp->t_tcpreq_info == NULL) {
4885 		tp->t_tcpreq_info = malloc(
4886 		    sizeof(*tp->t_tcpreq_info) * MAX_TCP_TRK_REQ,
4887 		    M_TCPREQTRK, M_NOWAIT | M_ZERO);
4888 		if (tp->t_tcpreq_info == NULL)
4889 			return (NULL);
4890 	}
4891 	/* In case the stack does not check for completions do so now */
4892 	tcp_req_check_for_comp(tp, tp->snd_una);
4893 	/* Check for stale entries */
4894 	if (tp->t_tcpreq_req)
4895 		tcp_req_check_for_stale_entries(tp, ts,
4896 		    (tp->t_tcpreq_req >= MAX_TCP_TRK_REQ));
4897 	/* Check to see if this is a duplicate of one not started */
4898 	if (tp->t_tcpreq_req) {
4899 		for (i = 0, allocated = 0; i < MAX_TCP_TRK_REQ; i++) {
4900 			fil = &tp->t_tcpreq_info[i];
4901 			if ((fil->flags & TCP_TRK_TRACK_FLG_USED) == 0)
4902 				continue;
4903 			if ((fil->timestamp == req->timestamp) &&
4904 			    (fil->start == req->start) &&
4905 			    ((fil->flags & TCP_TRK_TRACK_FLG_OPEN) ||
4906 			     (fil->end == req->end))) {
4907 				/*
4908 				 * We already have this request
4909 				 * and it has not been started with sendfile.
4910 				 * This probably means the user was returned
4911 				 * a 4xx of some sort and its going to age
4912 				 * out, lets not duplicate it.
4913 				 */
4914 				return (fil);
4915 			}
4916 		}
4917 	}
4918 	/* Ok if there is no room at the inn we are in trouble */
4919 	if (tp->t_tcpreq_req >= MAX_TCP_TRK_REQ) {
4920 		tcp_trace_point(tp, TCP_TP_REQ_LOG_FAIL);
4921 		for (i = 0; i < MAX_TCP_TRK_REQ; i++) {
4922 			tcp_req_log_req_info(tp, &tp->t_tcpreq_info[i],
4923 			    i, TCP_TRK_REQ_LOG_ALLOCFAIL, 0, 0);
4924 		}
4925 		return (NULL);
4926 	}
4927 	for (i = 0, allocated = 0; i < MAX_TCP_TRK_REQ; i++) {
4928 		fil = &tp->t_tcpreq_info[i];
4929 		if (fil->flags == TCP_TRK_TRACK_FLG_EMPTY) {
4930 			allocated = 1;
4931 			fil->flags = TCP_TRK_TRACK_FLG_USED;
4932 			fil->timestamp = req->timestamp;
4933 			fil->playout_ms = req->playout_ms;
4934 			fil->localtime = ts;
4935 			fil->start = req->start;
4936 			if (req->flags & TCP_LOG_HTTPD_RANGE_END) {
4937 				fil->end = req->end;
4938 			} else {
4939 				fil->end = 0;
4940 				fil->flags |= TCP_TRK_TRACK_FLG_OPEN;
4941 			}
4942 			/*
4943 			 * We can set the min boundaries to the TCP Sequence space,
4944 			 * but it might be found to be further up when sendfile
4945 			 * actually runs on this range (if it ever does).
4946 			 */
4947 			fil->sbcc_at_s = tptosocket(tp)->so_snd.sb_ccc;
4948 			fil->start_seq = tp->snd_una +
4949 			    tptosocket(tp)->so_snd.sb_ccc;
4950 			if (req->flags & TCP_LOG_HTTPD_RANGE_END)
4951 				fil->end_seq = (fil->start_seq + ((uint32_t)(fil->end - fil->start)));
4952 			else
4953 				fil->end_seq = 0;
4954 			if (tptosocket(tp)->so_snd.sb_tls_info) {
4955 				/*
4956 				 * This session is doing TLS. Take a swag guess
4957 				 * at the overhead.
4958 				 */
4959 				fil->end_seq += tcp_estimate_tls_overhead(
4960 				    tptosocket(tp), (fil->end - fil->start));
4961 			}
4962 			tp->t_tcpreq_req++;
4963 			if (fil->flags & TCP_TRK_TRACK_FLG_OPEN)
4964 				tp->t_tcpreq_open++;
4965 			else
4966 				tp->t_tcpreq_closed++;
4967 			tcp_req_log_req_info(tp, fil, i,
4968 			    TCP_TRK_REQ_LOG_NEW, 0, 0);
4969 			break;
4970 		} else
4971 			fil = NULL;
4972 	}
4973 	return (fil);
4974 }
4975 
4976 void
tcp_req_alloc_req(struct tcpcb * tp,union tcp_log_userdata * user,uint64_t ts)4977 tcp_req_alloc_req(struct tcpcb *tp, union tcp_log_userdata *user, uint64_t ts)
4978 {
4979 	(void)tcp_req_alloc_req_full(tp, &user->tcp_req, ts, 1);
4980 }
4981 #endif
4982 
4983 void
tcp_log_socket_option(struct tcpcb * tp,uint32_t option_num,uint32_t option_val,int err)4984 tcp_log_socket_option(struct tcpcb *tp, uint32_t option_num, uint32_t option_val, int err)
4985 {
4986 	if (tcp_bblogging_on(tp)) {
4987 		struct tcp_log_buffer *l;
4988 
4989 		l = tcp_log_event(tp, NULL,
4990 		        &tptosocket(tp)->so_rcv,
4991 		        &tptosocket(tp)->so_snd,
4992 		        TCP_LOG_SOCKET_OPT,
4993 		        err, 0, NULL, 1,
4994 		        NULL, NULL, 0, NULL);
4995 		if (l) {
4996 			l->tlb_flex1 = option_num;
4997 			l->tlb_flex2 = option_val;
4998 		}
4999 	}
5000 }
5001 
5002 uint32_t
tcp_get_srtt(struct tcpcb * tp,int granularity)5003 tcp_get_srtt(struct tcpcb *tp, int granularity)
5004 {
5005 	uint32_t srtt;
5006 
5007 	KASSERT(granularity == TCP_TMR_GRANULARITY_USEC ||
5008 	    granularity == TCP_TMR_GRANULARITY_TICKS,
5009 	    ("%s: called with unexpected granularity %d", __func__,
5010 	    granularity));
5011 
5012 	srtt = tp->t_srtt;
5013 
5014 	/*
5015 	 * We only support two granularities. If the stored granularity
5016 	 * does not match the granularity requested by the caller,
5017 	 * convert the stored value to the requested unit of granularity.
5018 	 */
5019 	if (tp->t_tmr_granularity != granularity) {
5020 		if (granularity == TCP_TMR_GRANULARITY_USEC)
5021 			srtt = TICKS_2_USEC(srtt);
5022 		else
5023 			srtt = USEC_2_TICKS(srtt);
5024 	}
5025 
5026 	/*
5027 	 * If the srtt is stored with ticks granularity, we need to
5028 	 * unshift to get the actual value. We do this after the
5029 	 * conversion above (if one was necessary) in order to maximize
5030 	 * precision.
5031 	 */
5032 	if (tp->t_tmr_granularity == TCP_TMR_GRANULARITY_TICKS)
5033 		srtt = srtt >> TCP_RTT_SHIFT;
5034 
5035 	return (srtt);
5036 }
5037 
5038 void
tcp_account_for_send(struct tcpcb * tp,uint32_t len,uint8_t is_rxt,uint8_t is_tlp,bool hw_tls)5039 tcp_account_for_send(struct tcpcb *tp, uint32_t len, uint8_t is_rxt,
5040     uint8_t is_tlp, bool hw_tls)
5041 {
5042 
5043 	if (is_tlp) {
5044 		tp->t_sndtlppack++;
5045 		tp->t_sndtlpbyte += len;
5046 	}
5047 	/* To get total bytes sent you must add t_snd_rxt_bytes to t_sndbytes */
5048 	if (is_rxt)
5049 		tp->t_snd_rxt_bytes += len;
5050 	else
5051 		tp->t_sndbytes += len;
5052 
5053 #ifdef KERN_TLS
5054 	if (hw_tls && is_rxt && len != 0) {
5055 		uint64_t rexmit_percent;
5056 
5057 		rexmit_percent = (1000ULL * tp->t_snd_rxt_bytes) /
5058 		    (10ULL * (tp->t_snd_rxt_bytes + tp->t_sndbytes));
5059 		if (rexmit_percent > ktls_ifnet_max_rexmit_pct)
5060 			ktls_disable_ifnet(tp);
5061 	}
5062 #endif
5063 }
5064