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