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