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 * @(#)tcp_subr.c 8.2 (Berkeley) 5/24/95
32 */
33
34 #include <sys/cdefs.h>
35 #include "opt_inet.h"
36 #include "opt_inet6.h"
37 #include "opt_ipsec.h"
38 #include "opt_kern_tls.h"
39 #include "opt_tcpdebug.h"
40
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/arb.h>
44 #include <sys/callout.h>
45 #include <sys/eventhandler.h>
46 #ifdef TCP_HHOOK
47 #include <sys/hhook.h>
48 #endif
49 #include <sys/kernel.h>
50 #ifdef TCP_HHOOK
51 #include <sys/khelp.h>
52 #endif
53 #ifdef KERN_TLS
54 #include <sys/ktls.h>
55 #endif
56 #include <sys/qmath.h>
57 #include <sys/stats.h>
58 #include <sys/sysctl.h>
59 #include <sys/jail.h>
60 #include <sys/malloc.h>
61 #include <sys/refcount.h>
62 #include <sys/mbuf.h>
63 #ifdef INET6
64 #include <sys/domain.h>
65 #endif
66 #include <sys/priv.h>
67 #include <sys/proc.h>
68 #include <sys/sdt.h>
69 #include <sys/socket.h>
70 #include <sys/socketvar.h>
71 #include <sys/protosw.h>
72 #include <sys/random.h>
73
74 #include <vm/uma.h>
75
76 #include <net/route.h>
77 #include <net/route/nhop.h>
78 #include <net/if.h>
79 #include <net/if_var.h>
80 #include <net/vnet.h>
81
82 #include <netinet/in.h>
83 #include <netinet/in_fib.h>
84 #include <netinet/in_kdtrace.h>
85 #include <netinet/in_pcb.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/in_var.h>
88 #include <netinet/ip.h>
89 #include <netinet/ip_icmp.h>
90 #include <netinet/ip_var.h>
91 #ifdef INET6
92 #include <netinet/icmp6.h>
93 #include <netinet/ip6.h>
94 #include <netinet6/in6_fib.h>
95 #include <netinet6/in6_pcb.h>
96 #include <netinet6/ip6_var.h>
97 #include <netinet6/scope6_var.h>
98 #include <netinet6/nd6.h>
99 #endif
100
101 #include <netinet/tcp.h>
102 #include <netinet/tcp_fsm.h>
103 #include <netinet/tcp_seq.h>
104 #include <netinet/tcp_timer.h>
105 #include <netinet/tcp_var.h>
106 #include <netinet/tcp_log_buf.h>
107 #include <netinet/tcp_syncache.h>
108 #include <netinet/tcp_hpts.h>
109 #include <netinet/cc/cc.h>
110 #ifdef INET6
111 #include <netinet6/tcp6_var.h>
112 #endif
113 #include <netinet/tcpip.h>
114 #include <netinet/tcp_fastopen.h>
115 #ifdef TCPPCAP
116 #include <netinet/tcp_pcap.h>
117 #endif
118 #ifdef TCPDEBUG
119 #include <netinet/tcp_debug.h>
120 #endif
121 #ifdef INET6
122 #include <netinet6/ip6protosw.h>
123 #endif
124 #ifdef TCP_OFFLOAD
125 #include <netinet/tcp_offload.h>
126 #endif
127 #include <netinet/udp.h>
128 #include <netinet/udp_var.h>
129
130 #include <netipsec/ipsec_support.h>
131
132 #include <machine/in_cksum.h>
133 #include <crypto/siphash/siphash.h>
134
135 #include <security/mac/mac_framework.h>
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 NETFLIX_EXP_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_sack_to_ack_thresh = 700; /* 70 % */
153 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, sack_to_ack_thresh,
154 CTLFLAG_RW,
155 &tcp_sack_to_ack_thresh, 700,
156 "Percentage of sacks to acks we must see above (10.1 percent is 101)?");
157 int32_t tcp_sack_to_move_thresh = 600; /* 60 % */
158 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, move_thresh,
159 CTLFLAG_RW,
160 &tcp_sack_to_move_thresh, 600,
161 "Percentage of sack moves we must see above (10.1 percent is 101)");
162 int32_t tcp_restoral_thresh = 650; /* 65 % (sack:2:ack -5%) */
163 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, restore_thresh,
164 CTLFLAG_RW,
165 &tcp_restoral_thresh, 550,
166 "Percentage of sack to ack percentage we must see below to restore(10.1 percent is 101)");
167 int32_t tcp_sad_decay_val = 800;
168 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, decay_per,
169 CTLFLAG_RW,
170 &tcp_sad_decay_val, 800,
171 "The decay percentage (10.1 percent equals 101 )");
172 int32_t tcp_map_minimum = 500;
173 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, nummaps,
174 CTLFLAG_RW,
175 &tcp_map_minimum, 500,
176 "Number of Map enteries before we start detection");
177 int32_t tcp_attack_on_turns_on_logging = 0;
178 SYSCTL_INT(_net_inet_tcp_sack_attack, OID_AUTO, attacks_logged,
179 CTLFLAG_RW,
180 &tcp_attack_on_turns_on_logging, 0,
181 "When we have a positive hit on attack, do we turn on logging?");
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
290 static int tcp_pacing_limit = 10000;
291 SYSCTL_INT(_net_inet_tcp, OID_AUTO, pacing_limit, CTLFLAG_RW,
292 &tcp_pacing_limit, 1000,
293 "If the TCP stack does pacing, is there a limit (-1 = no, 0 = no pacing N = number of connections)");
294
295 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, pacing_count, CTLFLAG_RD,
296 &shadow_num_connections, 0, "Number of TCP connections being paced");
297
298 static int tcp_log_debug = 0;
299 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_debug, CTLFLAG_RW,
300 &tcp_log_debug, 0, "Log errors caused by incoming TCP segments");
301
302 /*
303 * Target size of TCP PCB hash tables. Must be a power of two.
304 *
305 * Note that this can be overridden by the kernel environment
306 * variable net.inet.tcp.tcbhashsize
307 */
308 #ifndef TCBHASHSIZE
309 #define TCBHASHSIZE 0
310 #endif
311 static int tcp_tcbhashsize = TCBHASHSIZE;
312 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcbhashsize, CTLFLAG_RDTUN,
313 &tcp_tcbhashsize, 0, "Size of TCP control-block hashtable");
314
315 static int do_tcpdrain = 1;
316 SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_tcpdrain, CTLFLAG_RW, &do_tcpdrain, 0,
317 "Enable tcp_drain routine for extra help when low on mbufs");
318
319 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, pcbcount, CTLFLAG_VNET | CTLFLAG_RD,
320 &VNET_NAME(tcbinfo.ipi_count), 0, "Number of active PCBs");
321
322 VNET_DEFINE_STATIC(int, icmp_may_rst) = 1;
323 #define V_icmp_may_rst VNET(icmp_may_rst)
324 SYSCTL_INT(_net_inet_tcp, OID_AUTO, icmp_may_rst, CTLFLAG_VNET | CTLFLAG_RW,
325 &VNET_NAME(icmp_may_rst), 0,
326 "Certain ICMP unreachable messages may abort connections in SYN_SENT");
327
328 VNET_DEFINE_STATIC(int, tcp_isn_reseed_interval) = 0;
329 #define V_tcp_isn_reseed_interval VNET(tcp_isn_reseed_interval)
330 SYSCTL_INT(_net_inet_tcp, OID_AUTO, isn_reseed_interval, CTLFLAG_VNET | CTLFLAG_RW,
331 &VNET_NAME(tcp_isn_reseed_interval), 0,
332 "Seconds between reseeding of ISN secret");
333
334 static int tcp_soreceive_stream;
335 SYSCTL_INT(_net_inet_tcp, OID_AUTO, soreceive_stream, CTLFLAG_RDTUN,
336 &tcp_soreceive_stream, 0, "Using soreceive_stream for TCP sockets");
337
338 VNET_DEFINE(uma_zone_t, sack_hole_zone);
339 #define V_sack_hole_zone VNET(sack_hole_zone)
340 VNET_DEFINE(uint32_t, tcp_map_entries_limit) = 0; /* unlimited */
341 static int
sysctl_net_inet_tcp_map_limit_check(SYSCTL_HANDLER_ARGS)342 sysctl_net_inet_tcp_map_limit_check(SYSCTL_HANDLER_ARGS)
343 {
344 int error;
345 uint32_t new;
346
347 new = V_tcp_map_entries_limit;
348 error = sysctl_handle_int(oidp, &new, 0, req);
349 if (error == 0 && req->newptr) {
350 /* only allow "0" and value > minimum */
351 if (new > 0 && new < TCP_MIN_MAP_ENTRIES_LIMIT)
352 error = EINVAL;
353 else
354 V_tcp_map_entries_limit = new;
355 }
356 return (error);
357 }
358 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, map_limit,
359 CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
360 &VNET_NAME(tcp_map_entries_limit), 0,
361 &sysctl_net_inet_tcp_map_limit_check, "IU",
362 "Total sendmap entries limit");
363
364 VNET_DEFINE(uint32_t, tcp_map_split_limit) = 0; /* unlimited */
365 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, split_limit, CTLFLAG_VNET | CTLFLAG_RW,
366 &VNET_NAME(tcp_map_split_limit), 0,
367 "Total sendmap split entries limit");
368
369 #ifdef TCP_HHOOK
370 VNET_DEFINE(struct hhook_head *, tcp_hhh[HHOOK_TCP_LAST+1]);
371 #endif
372
373 #define TS_OFFSET_SECRET_LENGTH SIPHASH_KEY_LENGTH
374 VNET_DEFINE_STATIC(u_char, ts_offset_secret[TS_OFFSET_SECRET_LENGTH]);
375 #define V_ts_offset_secret VNET(ts_offset_secret)
376
377 static int tcp_default_fb_init(struct tcpcb *tp);
378 static void tcp_default_fb_fini(struct tcpcb *tp, int tcb_is_purged);
379 static int tcp_default_handoff_ok(struct tcpcb *tp);
380 static struct inpcb *tcp_notify(struct inpcb *, int);
381 static struct inpcb *tcp_mtudisc_notify(struct inpcb *, int);
382 static void tcp_mtudisc(struct inpcb *, int);
383 static char * tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th,
384 void *ip4hdr, const void *ip6hdr);
385
386 static struct tcp_function_block tcp_def_funcblk = {
387 .tfb_tcp_block_name = "freebsd",
388 .tfb_tcp_output = tcp_output,
389 .tfb_tcp_do_segment = tcp_do_segment,
390 .tfb_tcp_ctloutput = tcp_default_ctloutput,
391 .tfb_tcp_handoff_ok = tcp_default_handoff_ok,
392 .tfb_tcp_fb_init = tcp_default_fb_init,
393 .tfb_tcp_fb_fini = tcp_default_fb_fini,
394 };
395
396 static int tcp_fb_cnt = 0;
397 struct tcp_funchead t_functions;
398 static struct tcp_function_block *tcp_func_set_ptr = &tcp_def_funcblk;
399
400 static struct tcp_function_block *
find_tcp_functions_locked(struct tcp_function_set * fs)401 find_tcp_functions_locked(struct tcp_function_set *fs)
402 {
403 struct tcp_function *f;
404 struct tcp_function_block *blk=NULL;
405
406 TAILQ_FOREACH(f, &t_functions, tf_next) {
407 if (strcmp(f->tf_name, fs->function_set_name) == 0) {
408 blk = f->tf_fb;
409 break;
410 }
411 }
412 return(blk);
413 }
414
415 static struct tcp_function_block *
find_tcp_fb_locked(struct tcp_function_block * blk,struct tcp_function ** s)416 find_tcp_fb_locked(struct tcp_function_block *blk, struct tcp_function **s)
417 {
418 struct tcp_function_block *rblk=NULL;
419 struct tcp_function *f;
420
421 TAILQ_FOREACH(f, &t_functions, tf_next) {
422 if (f->tf_fb == blk) {
423 rblk = blk;
424 if (s) {
425 *s = f;
426 }
427 break;
428 }
429 }
430 return (rblk);
431 }
432
433 struct tcp_function_block *
find_and_ref_tcp_functions(struct tcp_function_set * fs)434 find_and_ref_tcp_functions(struct tcp_function_set *fs)
435 {
436 struct tcp_function_block *blk;
437
438 rw_rlock(&tcp_function_lock);
439 blk = find_tcp_functions_locked(fs);
440 if (blk)
441 refcount_acquire(&blk->tfb_refcnt);
442 rw_runlock(&tcp_function_lock);
443 return(blk);
444 }
445
446 struct tcp_function_block *
find_and_ref_tcp_fb(struct tcp_function_block * blk)447 find_and_ref_tcp_fb(struct tcp_function_block *blk)
448 {
449 struct tcp_function_block *rblk;
450
451 rw_rlock(&tcp_function_lock);
452 rblk = find_tcp_fb_locked(blk, NULL);
453 if (rblk)
454 refcount_acquire(&rblk->tfb_refcnt);
455 rw_runlock(&tcp_function_lock);
456 return(rblk);
457 }
458
459 static struct tcp_function_block *
find_and_ref_tcp_default_fb(void)460 find_and_ref_tcp_default_fb(void)
461 {
462 struct tcp_function_block *rblk;
463
464 rw_rlock(&tcp_function_lock);
465 rblk = tcp_func_set_ptr;
466 refcount_acquire(&rblk->tfb_refcnt);
467 rw_runlock(&tcp_function_lock);
468 return (rblk);
469 }
470
471 void
tcp_switch_back_to_default(struct tcpcb * tp)472 tcp_switch_back_to_default(struct tcpcb *tp)
473 {
474 struct tcp_function_block *tfb;
475
476 KASSERT(tp->t_fb != &tcp_def_funcblk,
477 ("%s: called by the built-in default stack", __func__));
478
479 /*
480 * Release the old stack. This function will either find a new one
481 * or panic.
482 */
483 if (tp->t_fb->tfb_tcp_fb_fini != NULL)
484 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 0);
485 refcount_release(&tp->t_fb->tfb_refcnt);
486
487 /*
488 * Now, we'll find a new function block to use.
489 * Start by trying the current user-selected
490 * default, unless this stack is the user-selected
491 * default.
492 */
493 tfb = find_and_ref_tcp_default_fb();
494 if (tfb == tp->t_fb) {
495 refcount_release(&tfb->tfb_refcnt);
496 tfb = NULL;
497 }
498 /* Does the stack accept this connection? */
499 if (tfb != NULL && tfb->tfb_tcp_handoff_ok != NULL &&
500 (*tfb->tfb_tcp_handoff_ok)(tp)) {
501 refcount_release(&tfb->tfb_refcnt);
502 tfb = NULL;
503 }
504 /* Try to use that stack. */
505 if (tfb != NULL) {
506 /* Initialize the new stack. If it succeeds, we are done. */
507 tp->t_fb = tfb;
508 if (tp->t_fb->tfb_tcp_fb_init == NULL ||
509 (*tp->t_fb->tfb_tcp_fb_init)(tp) == 0)
510 return;
511
512 /*
513 * Initialization failed. Release the reference count on
514 * the stack.
515 */
516 refcount_release(&tfb->tfb_refcnt);
517 }
518
519 /*
520 * If that wasn't feasible, use the built-in default
521 * stack which is not allowed to reject anyone.
522 */
523 tfb = find_and_ref_tcp_fb(&tcp_def_funcblk);
524 if (tfb == NULL) {
525 /* there always should be a default */
526 panic("Can't refer to tcp_def_funcblk");
527 }
528 if (tfb->tfb_tcp_handoff_ok != NULL) {
529 if ((*tfb->tfb_tcp_handoff_ok) (tp)) {
530 /* The default stack cannot say no */
531 panic("Default stack rejects a new session?");
532 }
533 }
534 tp->t_fb = tfb;
535 if (tp->t_fb->tfb_tcp_fb_init != NULL &&
536 (*tp->t_fb->tfb_tcp_fb_init)(tp)) {
537 /* The default stack cannot fail */
538 panic("Default stack initialization failed");
539 }
540 }
541
542 static void
tcp_recv_udp_tunneled_packet(struct mbuf * m,int off,struct inpcb * inp,const struct sockaddr * sa,void * ctx)543 tcp_recv_udp_tunneled_packet(struct mbuf *m, int off, struct inpcb *inp,
544 const struct sockaddr *sa, void *ctx)
545 {
546 struct ip *iph;
547 #ifdef INET6
548 struct ip6_hdr *ip6;
549 #endif
550 struct udphdr *uh;
551 struct tcphdr *th;
552 int thlen;
553 uint16_t port;
554
555 TCPSTAT_INC(tcps_tunneled_pkts);
556 if ((m->m_flags & M_PKTHDR) == 0) {
557 /* Can't handle one that is not a pkt hdr */
558 TCPSTAT_INC(tcps_tunneled_errs);
559 goto out;
560 }
561 thlen = sizeof(struct tcphdr);
562 if (m->m_len < off + sizeof(struct udphdr) + thlen &&
563 (m = m_pullup(m, off + sizeof(struct udphdr) + thlen)) == NULL) {
564 TCPSTAT_INC(tcps_tunneled_errs);
565 goto out;
566 }
567 iph = mtod(m, struct ip *);
568 uh = (struct udphdr *)((caddr_t)iph + off);
569 th = (struct tcphdr *)(uh + 1);
570 thlen = th->th_off << 2;
571 if (m->m_len < off + sizeof(struct udphdr) + thlen) {
572 m = m_pullup(m, off + sizeof(struct udphdr) + thlen);
573 if (m == NULL) {
574 TCPSTAT_INC(tcps_tunneled_errs);
575 goto out;
576 } else {
577 iph = mtod(m, struct ip *);
578 uh = (struct udphdr *)((caddr_t)iph + off);
579 th = (struct tcphdr *)(uh + 1);
580 }
581 }
582 m->m_pkthdr.tcp_tun_port = port = uh->uh_sport;
583 bcopy(th, uh, m->m_len - off);
584 m->m_len -= sizeof(struct udphdr);
585 m->m_pkthdr.len -= sizeof(struct udphdr);
586 /*
587 * We use the same algorithm for
588 * both UDP and TCP for c-sum. So
589 * the code in tcp_input will skip
590 * the checksum. So we do nothing
591 * with the flag (m->m_pkthdr.csum_flags).
592 */
593 switch (iph->ip_v) {
594 #ifdef INET
595 case IPVERSION:
596 iph->ip_len = htons(ntohs(iph->ip_len) - sizeof(struct udphdr));
597 tcp_input_with_port(&m, &off, IPPROTO_TCP, port);
598 break;
599 #endif
600 #ifdef INET6
601 case IPV6_VERSION >> 4:
602 ip6 = mtod(m, struct ip6_hdr *);
603 ip6->ip6_plen = htons(ntohs(ip6->ip6_plen) - sizeof(struct udphdr));
604 tcp6_input_with_port(&m, &off, IPPROTO_TCP, port);
605 break;
606 #endif
607 default:
608 goto out;
609 break;
610 }
611 return;
612 out:
613 m_freem(m);
614 }
615
616 static int
sysctl_net_inet_default_tcp_functions(SYSCTL_HANDLER_ARGS)617 sysctl_net_inet_default_tcp_functions(SYSCTL_HANDLER_ARGS)
618 {
619 int error=ENOENT;
620 struct tcp_function_set fs;
621 struct tcp_function_block *blk;
622
623 memset(&fs, 0, sizeof(fs));
624 rw_rlock(&tcp_function_lock);
625 blk = find_tcp_fb_locked(tcp_func_set_ptr, NULL);
626 if (blk) {
627 /* Found him */
628 strcpy(fs.function_set_name, blk->tfb_tcp_block_name);
629 fs.pcbcnt = blk->tfb_refcnt;
630 }
631 rw_runlock(&tcp_function_lock);
632 error = sysctl_handle_string(oidp, fs.function_set_name,
633 sizeof(fs.function_set_name), req);
634
635 /* Check for error or no change */
636 if (error != 0 || req->newptr == NULL)
637 return(error);
638
639 rw_wlock(&tcp_function_lock);
640 blk = find_tcp_functions_locked(&fs);
641 if ((blk == NULL) ||
642 (blk->tfb_flags & TCP_FUNC_BEING_REMOVED)) {
643 error = ENOENT;
644 goto done;
645 }
646 tcp_func_set_ptr = blk;
647 done:
648 rw_wunlock(&tcp_function_lock);
649 return (error);
650 }
651
652 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, functions_default,
653 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
654 NULL, 0, sysctl_net_inet_default_tcp_functions, "A",
655 "Set/get the default TCP functions");
656
657 static int
sysctl_net_inet_list_available(SYSCTL_HANDLER_ARGS)658 sysctl_net_inet_list_available(SYSCTL_HANDLER_ARGS)
659 {
660 int error, cnt, linesz;
661 struct tcp_function *f;
662 char *buffer, *cp;
663 size_t bufsz, outsz;
664 bool alias;
665
666 cnt = 0;
667 rw_rlock(&tcp_function_lock);
668 TAILQ_FOREACH(f, &t_functions, tf_next) {
669 cnt++;
670 }
671 rw_runlock(&tcp_function_lock);
672
673 bufsz = (cnt+2) * ((TCP_FUNCTION_NAME_LEN_MAX * 2) + 13) + 1;
674 buffer = malloc(bufsz, M_TEMP, M_WAITOK);
675
676 error = 0;
677 cp = buffer;
678
679 linesz = snprintf(cp, bufsz, "\n%-32s%c %-32s %s\n", "Stack", 'D',
680 "Alias", "PCB count");
681 cp += linesz;
682 bufsz -= linesz;
683 outsz = linesz;
684
685 rw_rlock(&tcp_function_lock);
686 TAILQ_FOREACH(f, &t_functions, tf_next) {
687 alias = (f->tf_name != f->tf_fb->tfb_tcp_block_name);
688 linesz = snprintf(cp, bufsz, "%-32s%c %-32s %u\n",
689 f->tf_fb->tfb_tcp_block_name,
690 (f->tf_fb == tcp_func_set_ptr) ? '*' : ' ',
691 alias ? f->tf_name : "-",
692 f->tf_fb->tfb_refcnt);
693 if (linesz >= bufsz) {
694 error = EOVERFLOW;
695 break;
696 }
697 cp += linesz;
698 bufsz -= linesz;
699 outsz += linesz;
700 }
701 rw_runlock(&tcp_function_lock);
702 if (error == 0)
703 error = sysctl_handle_string(oidp, buffer, outsz + 1, req);
704 free(buffer, M_TEMP);
705 return (error);
706 }
707
708 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, functions_available,
709 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
710 NULL, 0, sysctl_net_inet_list_available, "A",
711 "list available TCP Function sets");
712
713 VNET_DEFINE(int, tcp_udp_tunneling_port) = TCP_TUNNELING_PORT_DEFAULT;
714
715 #ifdef INET
716 VNET_DEFINE(struct socket *, udp4_tun_socket) = NULL;
717 #define V_udp4_tun_socket VNET(udp4_tun_socket)
718 #endif
719 #ifdef INET6
720 VNET_DEFINE(struct socket *, udp6_tun_socket) = NULL;
721 #define V_udp6_tun_socket VNET(udp6_tun_socket)
722 #endif
723
724 static void
tcp_over_udp_stop(void)725 tcp_over_udp_stop(void)
726 {
727 /*
728 * This function assumes sysctl caller holds inp_rinfo_lock()
729 * for writing!
730 */
731 #ifdef INET
732 if (V_udp4_tun_socket != NULL) {
733 soclose(V_udp4_tun_socket);
734 V_udp4_tun_socket = NULL;
735 }
736 #endif
737 #ifdef INET6
738 if (V_udp6_tun_socket != NULL) {
739 soclose(V_udp6_tun_socket);
740 V_udp6_tun_socket = NULL;
741 }
742 #endif
743 }
744
745 static int
tcp_over_udp_start(void)746 tcp_over_udp_start(void)
747 {
748 uint16_t port;
749 int ret;
750 #ifdef INET
751 struct sockaddr_in sin;
752 #endif
753 #ifdef INET6
754 struct sockaddr_in6 sin6;
755 #endif
756 /*
757 * This function assumes sysctl caller holds inp_info_rlock()
758 * for writing!
759 */
760 port = V_tcp_udp_tunneling_port;
761 if (ntohs(port) == 0) {
762 /* Must have a port set */
763 return (EINVAL);
764 }
765 #ifdef INET
766 if (V_udp4_tun_socket != NULL) {
767 /* Already running -- must stop first */
768 return (EALREADY);
769 }
770 #endif
771 #ifdef INET6
772 if (V_udp6_tun_socket != NULL) {
773 /* Already running -- must stop first */
774 return (EALREADY);
775 }
776 #endif
777 #ifdef INET
778 if ((ret = socreate(PF_INET, &V_udp4_tun_socket,
779 SOCK_DGRAM, IPPROTO_UDP,
780 curthread->td_ucred, curthread))) {
781 tcp_over_udp_stop();
782 return (ret);
783 }
784 /* Call the special UDP hook. */
785 if ((ret = udp_set_kernel_tunneling(V_udp4_tun_socket,
786 tcp_recv_udp_tunneled_packet,
787 tcp_ctlinput_viaudp,
788 NULL))) {
789 tcp_over_udp_stop();
790 return (ret);
791 }
792 /* Ok, we have a socket, bind it to the port. */
793 memset(&sin, 0, sizeof(struct sockaddr_in));
794 sin.sin_len = sizeof(struct sockaddr_in);
795 sin.sin_family = AF_INET;
796 sin.sin_port = htons(port);
797 if ((ret = sobind(V_udp4_tun_socket,
798 (struct sockaddr *)&sin, curthread))) {
799 tcp_over_udp_stop();
800 return (ret);
801 }
802 #endif
803 #ifdef INET6
804 if ((ret = socreate(PF_INET6, &V_udp6_tun_socket,
805 SOCK_DGRAM, IPPROTO_UDP,
806 curthread->td_ucred, curthread))) {
807 tcp_over_udp_stop();
808 return (ret);
809 }
810 /* Call the special UDP hook. */
811 if ((ret = udp_set_kernel_tunneling(V_udp6_tun_socket,
812 tcp_recv_udp_tunneled_packet,
813 tcp6_ctlinput_viaudp,
814 NULL))) {
815 tcp_over_udp_stop();
816 return (ret);
817 }
818 /* Ok, we have a socket, bind it to the port. */
819 memset(&sin6, 0, sizeof(struct sockaddr_in6));
820 sin6.sin6_len = sizeof(struct sockaddr_in6);
821 sin6.sin6_family = AF_INET6;
822 sin6.sin6_port = htons(port);
823 if ((ret = sobind(V_udp6_tun_socket,
824 (struct sockaddr *)&sin6, curthread))) {
825 tcp_over_udp_stop();
826 return (ret);
827 }
828 #endif
829 return (0);
830 }
831
832 static int
sysctl_net_inet_tcp_udp_tunneling_port_check(SYSCTL_HANDLER_ARGS)833 sysctl_net_inet_tcp_udp_tunneling_port_check(SYSCTL_HANDLER_ARGS)
834 {
835 int error;
836 uint32_t old, new;
837
838 old = V_tcp_udp_tunneling_port;
839 new = old;
840 error = sysctl_handle_int(oidp, &new, 0, req);
841 if ((error == 0) &&
842 (req->newptr != NULL)) {
843 if ((new < TCP_TUNNELING_PORT_MIN) ||
844 (new > TCP_TUNNELING_PORT_MAX)) {
845 error = EINVAL;
846 } else {
847 V_tcp_udp_tunneling_port = new;
848 if (old != 0) {
849 tcp_over_udp_stop();
850 }
851 if (new != 0) {
852 error = tcp_over_udp_start();
853 if (error != 0) {
854 V_tcp_udp_tunneling_port = 0;
855 }
856 }
857 }
858 }
859 return (error);
860 }
861
862 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, udp_tunneling_port,
863 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
864 &VNET_NAME(tcp_udp_tunneling_port),
865 0, &sysctl_net_inet_tcp_udp_tunneling_port_check, "IU",
866 "Tunneling port for tcp over udp");
867
868 VNET_DEFINE(int, tcp_udp_tunneling_overhead) = TCP_TUNNELING_OVERHEAD_DEFAULT;
869
870 static int
sysctl_net_inet_tcp_udp_tunneling_overhead_check(SYSCTL_HANDLER_ARGS)871 sysctl_net_inet_tcp_udp_tunneling_overhead_check(SYSCTL_HANDLER_ARGS)
872 {
873 int error, new;
874
875 new = V_tcp_udp_tunneling_overhead;
876 error = sysctl_handle_int(oidp, &new, 0, req);
877 if (error == 0 && req->newptr) {
878 if ((new < TCP_TUNNELING_OVERHEAD_MIN) ||
879 (new > TCP_TUNNELING_OVERHEAD_MAX))
880 error = EINVAL;
881 else
882 V_tcp_udp_tunneling_overhead = new;
883 }
884 return (error);
885 }
886
887 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, udp_tunneling_overhead,
888 CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
889 &VNET_NAME(tcp_udp_tunneling_overhead),
890 0, &sysctl_net_inet_tcp_udp_tunneling_overhead_check, "IU",
891 "MSS reduction when using tcp over udp");
892
893 /*
894 * Exports one (struct tcp_function_info) for each alias/name.
895 */
896 static int
sysctl_net_inet_list_func_info(SYSCTL_HANDLER_ARGS)897 sysctl_net_inet_list_func_info(SYSCTL_HANDLER_ARGS)
898 {
899 int cnt, error;
900 struct tcp_function *f;
901 struct tcp_function_info tfi;
902
903 /*
904 * We don't allow writes.
905 */
906 if (req->newptr != NULL)
907 return (EINVAL);
908
909 /*
910 * Wire the old buffer so we can directly copy the functions to
911 * user space without dropping the lock.
912 */
913 if (req->oldptr != NULL) {
914 error = sysctl_wire_old_buffer(req, 0);
915 if (error)
916 return (error);
917 }
918
919 /*
920 * Walk the list and copy out matching entries. If INVARIANTS
921 * is compiled in, also walk the list to verify the length of
922 * the list matches what we have recorded.
923 */
924 rw_rlock(&tcp_function_lock);
925
926 cnt = 0;
927 #ifndef INVARIANTS
928 if (req->oldptr == NULL) {
929 cnt = tcp_fb_cnt;
930 goto skip_loop;
931 }
932 #endif
933 TAILQ_FOREACH(f, &t_functions, tf_next) {
934 #ifdef INVARIANTS
935 cnt++;
936 #endif
937 if (req->oldptr != NULL) {
938 bzero(&tfi, sizeof(tfi));
939 tfi.tfi_refcnt = f->tf_fb->tfb_refcnt;
940 tfi.tfi_id = f->tf_fb->tfb_id;
941 (void)strlcpy(tfi.tfi_alias, f->tf_name,
942 sizeof(tfi.tfi_alias));
943 (void)strlcpy(tfi.tfi_name,
944 f->tf_fb->tfb_tcp_block_name, sizeof(tfi.tfi_name));
945 error = SYSCTL_OUT(req, &tfi, sizeof(tfi));
946 /*
947 * Don't stop on error, as that is the
948 * mechanism we use to accumulate length
949 * information if the buffer was too short.
950 */
951 }
952 }
953 KASSERT(cnt == tcp_fb_cnt,
954 ("%s: cnt (%d) != tcp_fb_cnt (%d)", __func__, cnt, tcp_fb_cnt));
955 #ifndef INVARIANTS
956 skip_loop:
957 #endif
958 rw_runlock(&tcp_function_lock);
959 if (req->oldptr == NULL)
960 error = SYSCTL_OUT(req, NULL,
961 (cnt + 1) * sizeof(struct tcp_function_info));
962
963 return (error);
964 }
965
966 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, function_info,
967 CTLTYPE_OPAQUE | CTLFLAG_SKIP | CTLFLAG_RD | CTLFLAG_MPSAFE,
968 NULL, 0, sysctl_net_inet_list_func_info, "S,tcp_function_info",
969 "List TCP function block name-to-ID mappings");
970
971 /*
972 * tfb_tcp_handoff_ok() function for the default stack.
973 * Note that we'll basically try to take all comers.
974 */
975 static int
tcp_default_handoff_ok(struct tcpcb * tp)976 tcp_default_handoff_ok(struct tcpcb *tp)
977 {
978
979 return (0);
980 }
981
982 /*
983 * tfb_tcp_fb_init() function for the default stack.
984 *
985 * This handles making sure we have appropriate timers set if you are
986 * transitioning a socket that has some amount of setup done.
987 *
988 * The init() fuction from the default can *never* return non-zero i.e.
989 * it is required to always succeed since it is the stack of last resort!
990 */
991 static int
tcp_default_fb_init(struct tcpcb * tp)992 tcp_default_fb_init(struct tcpcb *tp)
993 {
994
995 struct socket *so;
996
997 INP_WLOCK_ASSERT(tp->t_inpcb);
998
999 KASSERT(tp->t_state >= 0 && tp->t_state < TCPS_TIME_WAIT,
1000 ("%s: connection %p in unexpected state %d", __func__, tp,
1001 tp->t_state));
1002
1003 /*
1004 * Nothing to do for ESTABLISHED or LISTEN states. And, we don't
1005 * know what to do for unexpected states (which includes TIME_WAIT).
1006 */
1007 if (tp->t_state <= TCPS_LISTEN || tp->t_state >= TCPS_TIME_WAIT)
1008 return (0);
1009
1010 /*
1011 * Make sure some kind of transmission timer is set if there is
1012 * outstanding data.
1013 */
1014 so = tp->t_inpcb->inp_socket;
1015 if ((!TCPS_HAVEESTABLISHED(tp->t_state) || sbavail(&so->so_snd) ||
1016 tp->snd_una != tp->snd_max) && !(tcp_timer_active(tp, TT_REXMT) ||
1017 tcp_timer_active(tp, TT_PERSIST))) {
1018 /*
1019 * If the session has established and it looks like it should
1020 * be in the persist state, set the persist timer. Otherwise,
1021 * set the retransmit timer.
1022 */
1023 if (TCPS_HAVEESTABLISHED(tp->t_state) && tp->snd_wnd == 0 &&
1024 (int32_t)(tp->snd_nxt - tp->snd_una) <
1025 (int32_t)sbavail(&so->so_snd))
1026 tcp_setpersist(tp);
1027 else
1028 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
1029 }
1030
1031 /* All non-embryonic sessions get a keepalive timer. */
1032 if (!tcp_timer_active(tp, TT_KEEP))
1033 tcp_timer_activate(tp, TT_KEEP,
1034 TCPS_HAVEESTABLISHED(tp->t_state) ? TP_KEEPIDLE(tp) :
1035 TP_KEEPINIT(tp));
1036
1037 /*
1038 * Make sure critical variables are initialized
1039 * if transitioning while in Recovery.
1040 */
1041 if IN_FASTRECOVERY(tp->t_flags) {
1042 if (tp->sackhint.recover_fs == 0)
1043 tp->sackhint.recover_fs = max(1,
1044 tp->snd_nxt - tp->snd_una);
1045 }
1046
1047 return (0);
1048 }
1049
1050 /*
1051 * tfb_tcp_fb_fini() function for the default stack.
1052 *
1053 * This changes state as necessary (or prudent) to prepare for another stack
1054 * to assume responsibility for the connection.
1055 */
1056 static void
tcp_default_fb_fini(struct tcpcb * tp,int tcb_is_purged)1057 tcp_default_fb_fini(struct tcpcb *tp, int tcb_is_purged)
1058 {
1059
1060 INP_WLOCK_ASSERT(tp->t_inpcb);
1061 return;
1062 }
1063
1064 /*
1065 * XXX
1066 * Callouts should be moved into struct tcp directly. They are currently
1067 * separate because the tcpcb structure is exported to userland for sysctl
1068 * parsing purposes, which do not know about callouts.
1069 */
1070 struct tcpcb_mem {
1071 struct tcpcb tcb;
1072 struct tcp_timer tt;
1073 struct cc_var ccv;
1074 #ifdef TCP_HHOOK
1075 struct osd osd;
1076 #endif
1077 };
1078
1079 VNET_DEFINE_STATIC(uma_zone_t, tcpcb_zone);
1080 #define V_tcpcb_zone VNET(tcpcb_zone)
1081
1082 MALLOC_DEFINE(M_TCPLOG, "tcplog", "TCP address and flags print buffers");
1083 MALLOC_DEFINE(M_TCPFUNCTIONS, "tcpfunc", "TCP function set memory");
1084
1085 static struct mtx isn_mtx;
1086
1087 #define ISN_LOCK_INIT() mtx_init(&isn_mtx, "isn_mtx", NULL, MTX_DEF)
1088 #define ISN_LOCK() mtx_lock(&isn_mtx)
1089 #define ISN_UNLOCK() mtx_unlock(&isn_mtx)
1090
1091 /*
1092 * TCP initialization.
1093 */
1094 static void
tcp_zone_change(void * tag)1095 tcp_zone_change(void *tag)
1096 {
1097
1098 uma_zone_set_max(V_tcbinfo.ipi_zone, maxsockets);
1099 uma_zone_set_max(V_tcpcb_zone, maxsockets);
1100 tcp_tw_zone_change();
1101 }
1102
1103 static int
tcp_inpcb_init(void * mem,int size,int flags)1104 tcp_inpcb_init(void *mem, int size, int flags)
1105 {
1106 struct inpcb *inp = mem;
1107
1108 INP_LOCK_INIT(inp, "inp", "tcpinp");
1109 return (0);
1110 }
1111
1112 /*
1113 * Take a value and get the next power of 2 that doesn't overflow.
1114 * Used to size the tcp_inpcb hash buckets.
1115 */
1116 static int
maketcp_hashsize(int size)1117 maketcp_hashsize(int size)
1118 {
1119 int hashsize;
1120
1121 /*
1122 * auto tune.
1123 * get the next power of 2 higher than maxsockets.
1124 */
1125 hashsize = 1 << fls(size);
1126 /* catch overflow, and just go one power of 2 smaller */
1127 if (hashsize < size) {
1128 hashsize = 1 << (fls(size) - 1);
1129 }
1130 return (hashsize);
1131 }
1132
1133 static volatile int next_tcp_stack_id = 1;
1134
1135 /*
1136 * Register a TCP function block with the name provided in the names
1137 * array. (Note that this function does NOT automatically register
1138 * blk->tfb_tcp_block_name as a stack name. Therefore, you should
1139 * explicitly include blk->tfb_tcp_block_name in the list of names if
1140 * you wish to register the stack with that name.)
1141 *
1142 * Either all name registrations will succeed or all will fail. If
1143 * a name registration fails, the function will update the num_names
1144 * argument to point to the array index of the name that encountered
1145 * the failure.
1146 *
1147 * Returns 0 on success, or an error code on failure.
1148 */
1149 int
register_tcp_functions_as_names(struct tcp_function_block * blk,int wait,const char * names[],int * num_names)1150 register_tcp_functions_as_names(struct tcp_function_block *blk, int wait,
1151 const char *names[], int *num_names)
1152 {
1153 struct tcp_function *n;
1154 struct tcp_function_set fs;
1155 int error, i;
1156
1157 KASSERT(names != NULL && *num_names > 0,
1158 ("%s: Called with 0-length name list", __func__));
1159 KASSERT(names != NULL, ("%s: Called with NULL name list", __func__));
1160 KASSERT(rw_initialized(&tcp_function_lock),
1161 ("%s: called too early", __func__));
1162
1163 if ((blk->tfb_tcp_output == NULL) ||
1164 (blk->tfb_tcp_do_segment == NULL) ||
1165 (blk->tfb_tcp_ctloutput == NULL) ||
1166 (strlen(blk->tfb_tcp_block_name) == 0)) {
1167 /*
1168 * These functions are required and you
1169 * need a name.
1170 */
1171 *num_names = 0;
1172 return (EINVAL);
1173 }
1174 if (blk->tfb_tcp_timer_stop_all ||
1175 blk->tfb_tcp_timer_activate ||
1176 blk->tfb_tcp_timer_active ||
1177 blk->tfb_tcp_timer_stop) {
1178 /*
1179 * If you define one timer function you
1180 * must have them all.
1181 */
1182 if ((blk->tfb_tcp_timer_stop_all == NULL) ||
1183 (blk->tfb_tcp_timer_activate == NULL) ||
1184 (blk->tfb_tcp_timer_active == NULL) ||
1185 (blk->tfb_tcp_timer_stop == NULL)) {
1186 *num_names = 0;
1187 return (EINVAL);
1188 }
1189 }
1190
1191 if (blk->tfb_flags & TCP_FUNC_BEING_REMOVED) {
1192 *num_names = 0;
1193 return (EINVAL);
1194 }
1195
1196 refcount_init(&blk->tfb_refcnt, 0);
1197 blk->tfb_id = atomic_fetchadd_int(&next_tcp_stack_id, 1);
1198 for (i = 0; i < *num_names; i++) {
1199 n = malloc(sizeof(struct tcp_function), M_TCPFUNCTIONS, wait);
1200 if (n == NULL) {
1201 error = ENOMEM;
1202 goto cleanup;
1203 }
1204 n->tf_fb = blk;
1205
1206 (void)strlcpy(fs.function_set_name, names[i],
1207 sizeof(fs.function_set_name));
1208 rw_wlock(&tcp_function_lock);
1209 if (find_tcp_functions_locked(&fs) != NULL) {
1210 /* Duplicate name space not allowed */
1211 rw_wunlock(&tcp_function_lock);
1212 free(n, M_TCPFUNCTIONS);
1213 error = EALREADY;
1214 goto cleanup;
1215 }
1216 (void)strlcpy(n->tf_name, names[i], sizeof(n->tf_name));
1217 TAILQ_INSERT_TAIL(&t_functions, n, tf_next);
1218 tcp_fb_cnt++;
1219 rw_wunlock(&tcp_function_lock);
1220 }
1221 return(0);
1222
1223 cleanup:
1224 /*
1225 * Deregister the names we just added. Because registration failed
1226 * for names[i], we don't need to deregister that name.
1227 */
1228 *num_names = i;
1229 rw_wlock(&tcp_function_lock);
1230 while (--i >= 0) {
1231 TAILQ_FOREACH(n, &t_functions, tf_next) {
1232 if (!strncmp(n->tf_name, names[i],
1233 TCP_FUNCTION_NAME_LEN_MAX)) {
1234 TAILQ_REMOVE(&t_functions, n, tf_next);
1235 tcp_fb_cnt--;
1236 n->tf_fb = NULL;
1237 free(n, M_TCPFUNCTIONS);
1238 break;
1239 }
1240 }
1241 }
1242 rw_wunlock(&tcp_function_lock);
1243 return (error);
1244 }
1245
1246 /*
1247 * Register a TCP function block using the name provided in the name
1248 * argument.
1249 *
1250 * Returns 0 on success, or an error code on failure.
1251 */
1252 int
register_tcp_functions_as_name(struct tcp_function_block * blk,const char * name,int wait)1253 register_tcp_functions_as_name(struct tcp_function_block *blk, const char *name,
1254 int wait)
1255 {
1256 const char *name_list[1];
1257 int num_names, rv;
1258
1259 num_names = 1;
1260 if (name != NULL)
1261 name_list[0] = name;
1262 else
1263 name_list[0] = blk->tfb_tcp_block_name;
1264 rv = register_tcp_functions_as_names(blk, wait, name_list, &num_names);
1265 return (rv);
1266 }
1267
1268 /*
1269 * Register a TCP function block using the name defined in
1270 * blk->tfb_tcp_block_name.
1271 *
1272 * Returns 0 on success, or an error code on failure.
1273 */
1274 int
register_tcp_functions(struct tcp_function_block * blk,int wait)1275 register_tcp_functions(struct tcp_function_block *blk, int wait)
1276 {
1277
1278 return (register_tcp_functions_as_name(blk, NULL, wait));
1279 }
1280
1281 /*
1282 * Deregister all names associated with a function block. This
1283 * functionally removes the function block from use within the system.
1284 *
1285 * When called with a true quiesce argument, mark the function block
1286 * as being removed so no more stacks will use it and determine
1287 * whether the removal would succeed.
1288 *
1289 * When called with a false quiesce argument, actually attempt the
1290 * removal.
1291 *
1292 * When called with a force argument, attempt to switch all TCBs to
1293 * use the default stack instead of returning EBUSY.
1294 *
1295 * Returns 0 on success (or if the removal would succeed, or an error
1296 * code on failure.
1297 */
1298 int
deregister_tcp_functions(struct tcp_function_block * blk,bool quiesce,bool force)1299 deregister_tcp_functions(struct tcp_function_block *blk, bool quiesce,
1300 bool force)
1301 {
1302 struct tcp_function *f;
1303
1304 if (blk == &tcp_def_funcblk) {
1305 /* You can't un-register the default */
1306 return (EPERM);
1307 }
1308 rw_wlock(&tcp_function_lock);
1309 if (blk == tcp_func_set_ptr) {
1310 /* You can't free the current default */
1311 rw_wunlock(&tcp_function_lock);
1312 return (EBUSY);
1313 }
1314 /* Mark the block so no more stacks can use it. */
1315 blk->tfb_flags |= TCP_FUNC_BEING_REMOVED;
1316 /*
1317 * If TCBs are still attached to the stack, attempt to switch them
1318 * to the default stack.
1319 */
1320 if (force && blk->tfb_refcnt) {
1321 struct inpcb *inp;
1322 struct tcpcb *tp;
1323 VNET_ITERATOR_DECL(vnet_iter);
1324
1325 rw_wunlock(&tcp_function_lock);
1326
1327 VNET_LIST_RLOCK();
1328 VNET_FOREACH(vnet_iter) {
1329 CURVNET_SET(vnet_iter);
1330 INP_INFO_WLOCK(&V_tcbinfo);
1331 CK_LIST_FOREACH(inp, V_tcbinfo.ipi_listhead, inp_list) {
1332 INP_WLOCK(inp);
1333 if (inp->inp_flags & INP_TIMEWAIT) {
1334 INP_WUNLOCK(inp);
1335 continue;
1336 }
1337 tp = intotcpcb(inp);
1338 if (tp == NULL || tp->t_fb != blk) {
1339 INP_WUNLOCK(inp);
1340 continue;
1341 }
1342 tcp_switch_back_to_default(tp);
1343 INP_WUNLOCK(inp);
1344 }
1345 INP_INFO_WUNLOCK(&V_tcbinfo);
1346 CURVNET_RESTORE();
1347 }
1348 VNET_LIST_RUNLOCK();
1349
1350 rw_wlock(&tcp_function_lock);
1351 }
1352 if (blk->tfb_refcnt) {
1353 /* TCBs still attached. */
1354 rw_wunlock(&tcp_function_lock);
1355 return (EBUSY);
1356 }
1357 if (quiesce) {
1358 /* Skip removal. */
1359 rw_wunlock(&tcp_function_lock);
1360 return (0);
1361 }
1362 /* Remove any function names that map to this function block. */
1363 while (find_tcp_fb_locked(blk, &f) != NULL) {
1364 TAILQ_REMOVE(&t_functions, f, tf_next);
1365 tcp_fb_cnt--;
1366 f->tf_fb = NULL;
1367 free(f, M_TCPFUNCTIONS);
1368 }
1369 rw_wunlock(&tcp_function_lock);
1370 return (0);
1371 }
1372
1373 void
tcp_init(void)1374 tcp_init(void)
1375 {
1376 int hashsize;
1377
1378 #ifdef TCP_HHOOK
1379 if (hhook_head_register(HHOOK_TYPE_TCP, HHOOK_TCP_EST_IN,
1380 &V_tcp_hhh[HHOOK_TCP_EST_IN], HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
1381 printf("%s: WARNING: unable to register helper hook\n", __func__);
1382 if (hhook_head_register(HHOOK_TYPE_TCP, HHOOK_TCP_EST_OUT,
1383 &V_tcp_hhh[HHOOK_TCP_EST_OUT], HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
1384 printf("%s: WARNING: unable to register helper hook\n", __func__);
1385 #endif
1386 #ifdef STATS
1387 if (tcp_stats_init())
1388 printf("%s: WARNING: unable to initialise TCP stats\n",
1389 __func__);
1390 #endif
1391 hashsize = tcp_tcbhashsize;
1392 if (hashsize == 0) {
1393 /*
1394 * Auto tune the hash size based on maxsockets.
1395 * A perfect hash would have a 1:1 mapping
1396 * (hashsize = maxsockets) however it's been
1397 * suggested that O(2) average is better.
1398 */
1399 hashsize = maketcp_hashsize(maxsockets / 4);
1400 /*
1401 * Our historical default is 512,
1402 * do not autotune lower than this.
1403 */
1404 if (hashsize < 512)
1405 hashsize = 512;
1406 if (bootverbose && IS_DEFAULT_VNET(curvnet))
1407 printf("%s: %s auto tuned to %d\n", __func__,
1408 "net.inet.tcp.tcbhashsize", hashsize);
1409 }
1410 /*
1411 * We require a hashsize to be a power of two.
1412 * Previously if it was not a power of two we would just reset it
1413 * back to 512, which could be a nasty surprise if you did not notice
1414 * the error message.
1415 * Instead what we do is clip it to the closest power of two lower
1416 * than the specified hash value.
1417 */
1418 if (!powerof2(hashsize)) {
1419 int oldhashsize = hashsize;
1420
1421 hashsize = maketcp_hashsize(hashsize);
1422 /* prevent absurdly low value */
1423 if (hashsize < 16)
1424 hashsize = 16;
1425 printf("%s: WARNING: TCB hash size not a power of 2, "
1426 "clipped from %d to %d.\n", __func__, oldhashsize,
1427 hashsize);
1428 }
1429 in_pcbinfo_init(&V_tcbinfo, "tcp", &V_tcb, hashsize, hashsize,
1430 "tcp_inpcb", tcp_inpcb_init, IPI_HASHFIELDS_4TUPLE);
1431
1432 /*
1433 * These have to be type stable for the benefit of the timers.
1434 */
1435 V_tcpcb_zone = uma_zcreate("tcpcb", sizeof(struct tcpcb_mem),
1436 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1437 uma_zone_set_max(V_tcpcb_zone, maxsockets);
1438 uma_zone_set_warning(V_tcpcb_zone, "kern.ipc.maxsockets limit reached");
1439
1440 tcp_tw_init();
1441 syncache_init();
1442 tcp_hc_init();
1443
1444 TUNABLE_INT_FETCH("net.inet.tcp.sack.enable", &V_tcp_do_sack);
1445 V_sack_hole_zone = uma_zcreate("sackhole", sizeof(struct sackhole),
1446 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1447
1448 tcp_fastopen_init();
1449
1450 V_tcp_msl = TCPTV_MSL;
1451 arc4rand(&V_ts_offset_secret, sizeof(V_ts_offset_secret), 0);
1452
1453 /* Skip initialization of globals for non-default instances. */
1454 if (!IS_DEFAULT_VNET(curvnet))
1455 return;
1456
1457 tcp_reass_global_init();
1458
1459 /* XXX virtualize those below? */
1460 tcp_delacktime = TCPTV_DELACK;
1461 tcp_keepinit = TCPTV_KEEP_INIT;
1462 tcp_keepidle = TCPTV_KEEP_IDLE;
1463 tcp_keepintvl = TCPTV_KEEPINTVL;
1464 tcp_maxpersistidle = TCPTV_KEEP_IDLE;
1465 tcp_rexmit_initial = TCPTV_RTOBASE;
1466 if (tcp_rexmit_initial < 1)
1467 tcp_rexmit_initial = 1;
1468 tcp_rexmit_min = TCPTV_MIN;
1469 if (tcp_rexmit_min < 1)
1470 tcp_rexmit_min = 1;
1471 tcp_persmin = TCPTV_PERSMIN;
1472 tcp_persmax = TCPTV_PERSMAX;
1473 tcp_rexmit_slop = TCPTV_CPU_VAR;
1474 tcp_finwait2_timeout = TCPTV_FINWAIT2_TIMEOUT;
1475 tcp_tcbhashsize = hashsize;
1476
1477 /* Setup the tcp function block list */
1478 TAILQ_INIT(&t_functions);
1479 rw_init(&tcp_function_lock, "tcp_func_lock");
1480 register_tcp_functions(&tcp_def_funcblk, M_WAITOK);
1481 #ifdef TCP_BLACKBOX
1482 /* Initialize the TCP logging data. */
1483 tcp_log_init();
1484 #endif
1485
1486 if (tcp_soreceive_stream) {
1487 #ifdef INET
1488 tcp_usrreqs.pru_soreceive = soreceive_stream;
1489 #endif
1490 #ifdef INET6
1491 tcp6_usrreqs.pru_soreceive = soreceive_stream;
1492 #endif /* INET6 */
1493 }
1494
1495 #ifdef INET6
1496 #define TCP_MINPROTOHDR (sizeof(struct ip6_hdr) + sizeof(struct tcphdr))
1497 #else /* INET6 */
1498 #define TCP_MINPROTOHDR (sizeof(struct tcpiphdr))
1499 #endif /* INET6 */
1500 if (max_protohdr < TCP_MINPROTOHDR)
1501 max_protohdr = TCP_MINPROTOHDR;
1502 if (max_linkhdr + TCP_MINPROTOHDR > MHLEN)
1503 panic("tcp_init");
1504 #undef TCP_MINPROTOHDR
1505
1506 ISN_LOCK_INIT();
1507 EVENTHANDLER_REGISTER(shutdown_pre_sync, tcp_fini, NULL,
1508 SHUTDOWN_PRI_DEFAULT);
1509 EVENTHANDLER_REGISTER(maxsockets_change, tcp_zone_change, NULL,
1510 EVENTHANDLER_PRI_ANY);
1511
1512 tcp_inp_lro_direct_queue = counter_u64_alloc(M_WAITOK);
1513 tcp_inp_lro_wokeup_queue = counter_u64_alloc(M_WAITOK);
1514 tcp_inp_lro_compressed = counter_u64_alloc(M_WAITOK);
1515 tcp_inp_lro_locks_taken = counter_u64_alloc(M_WAITOK);
1516 tcp_extra_mbuf = counter_u64_alloc(M_WAITOK);
1517 tcp_would_have_but = counter_u64_alloc(M_WAITOK);
1518 tcp_comp_total = counter_u64_alloc(M_WAITOK);
1519 tcp_uncomp_total = counter_u64_alloc(M_WAITOK);
1520 #ifdef TCPPCAP
1521 tcp_pcap_init();
1522 #endif
1523 }
1524
1525 #ifdef VIMAGE
1526 static void
tcp_destroy(void * unused __unused)1527 tcp_destroy(void *unused __unused)
1528 {
1529 int n;
1530 #ifdef TCP_HHOOK
1531 int error;
1532 #endif
1533
1534 /*
1535 * All our processes are gone, all our sockets should be cleaned
1536 * up, which means, we should be past the tcp_discardcb() calls.
1537 * Sleep to let all tcpcb timers really disappear and cleanup.
1538 */
1539 for (;;) {
1540 INP_LIST_RLOCK(&V_tcbinfo);
1541 n = V_tcbinfo.ipi_count;
1542 INP_LIST_RUNLOCK(&V_tcbinfo);
1543 if (n == 0)
1544 break;
1545 pause("tcpdes", hz / 10);
1546 }
1547 tcp_hc_destroy();
1548 syncache_destroy();
1549 tcp_tw_destroy();
1550 in_pcbinfo_destroy(&V_tcbinfo);
1551 /* tcp_discardcb() clears the sack_holes up. */
1552 uma_zdestroy(V_sack_hole_zone);
1553 uma_zdestroy(V_tcpcb_zone);
1554
1555 /*
1556 * Cannot free the zone until all tcpcbs are released as we attach
1557 * the allocations to them.
1558 */
1559 tcp_fastopen_destroy();
1560
1561 #ifdef TCP_HHOOK
1562 error = hhook_head_deregister(V_tcp_hhh[HHOOK_TCP_EST_IN]);
1563 if (error != 0) {
1564 printf("%s: WARNING: unable to deregister helper hook "
1565 "type=%d, id=%d: error %d returned\n", __func__,
1566 HHOOK_TYPE_TCP, HHOOK_TCP_EST_IN, error);
1567 }
1568 error = hhook_head_deregister(V_tcp_hhh[HHOOK_TCP_EST_OUT]);
1569 if (error != 0) {
1570 printf("%s: WARNING: unable to deregister helper hook "
1571 "type=%d, id=%d: error %d returned\n", __func__,
1572 HHOOK_TYPE_TCP, HHOOK_TCP_EST_OUT, error);
1573 }
1574 #endif
1575 }
1576 VNET_SYSUNINIT(tcp, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH, tcp_destroy, NULL);
1577 #endif
1578
1579 void
tcp_fini(void * xtp)1580 tcp_fini(void *xtp)
1581 {
1582
1583 }
1584
1585 /*
1586 * Fill in the IP and TCP headers for an outgoing packet, given the tcpcb.
1587 * tcp_template used to store this data in mbufs, but we now recopy it out
1588 * of the tcpcb each time to conserve mbufs.
1589 */
1590 void
tcpip_fillheaders(struct inpcb * inp,uint16_t port,void * ip_ptr,void * tcp_ptr)1591 tcpip_fillheaders(struct inpcb *inp, uint16_t port, void *ip_ptr, void *tcp_ptr)
1592 {
1593 struct tcphdr *th = (struct tcphdr *)tcp_ptr;
1594
1595 INP_WLOCK_ASSERT(inp);
1596
1597 #ifdef INET6
1598 if ((inp->inp_vflag & INP_IPV6) != 0) {
1599 struct ip6_hdr *ip6;
1600
1601 ip6 = (struct ip6_hdr *)ip_ptr;
1602 ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) |
1603 (inp->inp_flow & IPV6_FLOWINFO_MASK);
1604 ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) |
1605 (IPV6_VERSION & IPV6_VERSION_MASK);
1606 if (port == 0)
1607 ip6->ip6_nxt = IPPROTO_TCP;
1608 else
1609 ip6->ip6_nxt = IPPROTO_UDP;
1610 ip6->ip6_plen = htons(sizeof(struct tcphdr));
1611 ip6->ip6_src = inp->in6p_laddr;
1612 ip6->ip6_dst = inp->in6p_faddr;
1613 }
1614 #endif /* INET6 */
1615 #if defined(INET6) && defined(INET)
1616 else
1617 #endif
1618 #ifdef INET
1619 {
1620 struct ip *ip;
1621
1622 ip = (struct ip *)ip_ptr;
1623 ip->ip_v = IPVERSION;
1624 ip->ip_hl = 5;
1625 ip->ip_tos = inp->inp_ip_tos;
1626 ip->ip_len = 0;
1627 ip->ip_id = 0;
1628 ip->ip_off = 0;
1629 ip->ip_ttl = inp->inp_ip_ttl;
1630 ip->ip_sum = 0;
1631 if (port == 0)
1632 ip->ip_p = IPPROTO_TCP;
1633 else
1634 ip->ip_p = IPPROTO_UDP;
1635 ip->ip_src = inp->inp_laddr;
1636 ip->ip_dst = inp->inp_faddr;
1637 }
1638 #endif /* INET */
1639 th->th_sport = inp->inp_lport;
1640 th->th_dport = inp->inp_fport;
1641 th->th_seq = 0;
1642 th->th_ack = 0;
1643 th->th_x2 = 0;
1644 th->th_off = 5;
1645 th->th_flags = 0;
1646 th->th_win = 0;
1647 th->th_urp = 0;
1648 th->th_sum = 0; /* in_pseudo() is called later for ipv4 */
1649 }
1650
1651 /*
1652 * Create template to be used to send tcp packets on a connection.
1653 * Allocates an mbuf and fills in a skeletal tcp/ip header. The only
1654 * use for this function is in keepalives, which use tcp_respond.
1655 */
1656 struct tcptemp *
tcpip_maketemplate(struct inpcb * inp)1657 tcpip_maketemplate(struct inpcb *inp)
1658 {
1659 struct tcptemp *t;
1660
1661 t = malloc(sizeof(*t), M_TEMP, M_NOWAIT);
1662 if (t == NULL)
1663 return (NULL);
1664 tcpip_fillheaders(inp, 0, (void *)&t->tt_ipgen, (void *)&t->tt_t);
1665 return (t);
1666 }
1667
1668 /*
1669 * Send a single message to the TCP at address specified by
1670 * the given TCP/IP header. If m == NULL, then we make a copy
1671 * of the tcpiphdr at th and send directly to the addressed host.
1672 * This is used to force keep alive messages out using the TCP
1673 * template for a connection. If flags are given then we send
1674 * a message back to the TCP which originated the segment th,
1675 * and discard the mbuf containing it and any other attached mbufs.
1676 *
1677 * In any case the ack and sequence number of the transmitted
1678 * segment are as specified by the parameters.
1679 *
1680 * NOTE: If m != NULL, then th must point to *inside* the mbuf.
1681 */
1682 void
tcp_respond(struct tcpcb * tp,void * ipgen,struct tcphdr * th,struct mbuf * m,tcp_seq ack,tcp_seq seq,int flags)1683 tcp_respond(struct tcpcb *tp, void *ipgen, struct tcphdr *th, struct mbuf *m,
1684 tcp_seq ack, tcp_seq seq, int flags)
1685 {
1686 struct tcpopt to;
1687 struct inpcb *inp;
1688 struct ip *ip;
1689 struct mbuf *optm;
1690 struct udphdr *uh = NULL;
1691 struct tcphdr *nth;
1692 u_char *optp;
1693 #ifdef INET6
1694 struct ip6_hdr *ip6;
1695 int isipv6;
1696 #endif /* INET6 */
1697 int optlen, tlen, win, ulen;
1698 bool incl_opts;
1699 uint16_t port;
1700
1701 KASSERT(tp != NULL || m != NULL, ("tcp_respond: tp and m both NULL"));
1702 NET_EPOCH_ASSERT();
1703
1704 #ifdef INET6
1705 isipv6 = ((struct ip *)ipgen)->ip_v == (IPV6_VERSION >> 4);
1706 ip6 = ipgen;
1707 #endif /* INET6 */
1708 ip = ipgen;
1709
1710 if (tp != NULL) {
1711 inp = tp->t_inpcb;
1712 KASSERT(inp != NULL, ("tcp control block w/o inpcb"));
1713 INP_WLOCK_ASSERT(inp);
1714 } else
1715 inp = NULL;
1716
1717 if (m != NULL) {
1718 #ifdef INET6
1719 if (isipv6 && ip6 && (ip6->ip6_nxt == IPPROTO_UDP))
1720 port = m->m_pkthdr.tcp_tun_port;
1721 else
1722 #endif
1723 if (ip && (ip->ip_p == IPPROTO_UDP))
1724 port = m->m_pkthdr.tcp_tun_port;
1725 else
1726 port = 0;
1727 } else
1728 port = tp->t_port;
1729
1730 incl_opts = false;
1731 win = 0;
1732 if (tp != NULL) {
1733 if (!(flags & TH_RST)) {
1734 win = sbspace(&inp->inp_socket->so_rcv);
1735 if (win > TCP_MAXWIN << tp->rcv_scale)
1736 win = TCP_MAXWIN << tp->rcv_scale;
1737 }
1738 if ((tp->t_flags & TF_NOOPT) == 0)
1739 incl_opts = true;
1740 }
1741 if (m == NULL) {
1742 m = m_gethdr(M_NOWAIT, MT_DATA);
1743 if (m == NULL)
1744 return;
1745 m->m_data += max_linkhdr;
1746 #ifdef INET6
1747 if (isipv6) {
1748 bcopy((caddr_t)ip6, mtod(m, caddr_t),
1749 sizeof(struct ip6_hdr));
1750 ip6 = mtod(m, struct ip6_hdr *);
1751 nth = (struct tcphdr *)(ip6 + 1);
1752 if (port) {
1753 /* Insert a UDP header */
1754 uh = (struct udphdr *)nth;
1755 uh->uh_sport = htons(V_tcp_udp_tunneling_port);
1756 uh->uh_dport = port;
1757 nth = (struct tcphdr *)(uh + 1);
1758 }
1759 } else
1760 #endif /* INET6 */
1761 {
1762 bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
1763 ip = mtod(m, struct ip *);
1764 nth = (struct tcphdr *)(ip + 1);
1765 if (port) {
1766 /* Insert a UDP header */
1767 uh = (struct udphdr *)nth;
1768 uh->uh_sport = htons(V_tcp_udp_tunneling_port);
1769 uh->uh_dport = port;
1770 nth = (struct tcphdr *)(uh + 1);
1771 }
1772 }
1773 bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr));
1774 flags = TH_ACK;
1775 } else if ((!M_WRITABLE(m)) || (port != 0)) {
1776 struct mbuf *n;
1777
1778 /* Can't reuse 'm', allocate a new mbuf. */
1779 n = m_gethdr(M_NOWAIT, MT_DATA);
1780 if (n == NULL) {
1781 m_freem(m);
1782 return;
1783 }
1784
1785 if (!m_dup_pkthdr(n, m, M_NOWAIT)) {
1786 m_freem(m);
1787 m_freem(n);
1788 return;
1789 }
1790
1791 n->m_data += max_linkhdr;
1792 /* m_len is set later */
1793 #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
1794 #ifdef INET6
1795 if (isipv6) {
1796 bcopy((caddr_t)ip6, mtod(n, caddr_t),
1797 sizeof(struct ip6_hdr));
1798 ip6 = mtod(n, struct ip6_hdr *);
1799 xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
1800 nth = (struct tcphdr *)(ip6 + 1);
1801 if (port) {
1802 /* Insert a UDP header */
1803 uh = (struct udphdr *)nth;
1804 uh->uh_sport = htons(V_tcp_udp_tunneling_port);
1805 uh->uh_dport = port;
1806 nth = (struct tcphdr *)(uh + 1);
1807 }
1808 } else
1809 #endif /* INET6 */
1810 {
1811 bcopy((caddr_t)ip, mtod(n, caddr_t), sizeof(struct ip));
1812 ip = mtod(n, struct ip *);
1813 xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, uint32_t);
1814 nth = (struct tcphdr *)(ip + 1);
1815 if (port) {
1816 /* Insert a UDP header */
1817 uh = (struct udphdr *)nth;
1818 uh->uh_sport = htons(V_tcp_udp_tunneling_port);
1819 uh->uh_dport = port;
1820 nth = (struct tcphdr *)(uh + 1);
1821 }
1822 }
1823 bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr));
1824 xchg(nth->th_dport, nth->th_sport, uint16_t);
1825 th = nth;
1826 m_freem(m);
1827 m = n;
1828 } else {
1829 /*
1830 * reuse the mbuf.
1831 * XXX MRT We inherit the FIB, which is lucky.
1832 */
1833 m_freem(m->m_next);
1834 m->m_next = NULL;
1835 m->m_data = (caddr_t)ipgen;
1836 /* m_len is set later */
1837 #ifdef INET6
1838 if (isipv6) {
1839 xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
1840 nth = (struct tcphdr *)(ip6 + 1);
1841 } else
1842 #endif /* INET6 */
1843 {
1844 xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, uint32_t);
1845 nth = (struct tcphdr *)(ip + 1);
1846 }
1847 if (th != nth) {
1848 /*
1849 * this is usually a case when an extension header
1850 * exists between the IPv6 header and the
1851 * TCP header.
1852 */
1853 nth->th_sport = th->th_sport;
1854 nth->th_dport = th->th_dport;
1855 }
1856 xchg(nth->th_dport, nth->th_sport, uint16_t);
1857 #undef xchg
1858 }
1859 tlen = 0;
1860 #ifdef INET6
1861 if (isipv6)
1862 tlen = sizeof (struct ip6_hdr) + sizeof (struct tcphdr);
1863 #endif
1864 #if defined(INET) && defined(INET6)
1865 else
1866 #endif
1867 #ifdef INET
1868 tlen = sizeof (struct tcpiphdr);
1869 #endif
1870 if (port)
1871 tlen += sizeof (struct udphdr);
1872 #ifdef INVARIANTS
1873 m->m_len = 0;
1874 KASSERT(M_TRAILINGSPACE(m) >= tlen,
1875 ("Not enough trailing space for message (m=%p, need=%d, have=%ld)",
1876 m, tlen, (long)M_TRAILINGSPACE(m)));
1877 #endif
1878 m->m_len = tlen;
1879 to.to_flags = 0;
1880 if (incl_opts) {
1881 /* Make sure we have room. */
1882 if (M_TRAILINGSPACE(m) < TCP_MAXOLEN) {
1883 m->m_next = m_get(M_NOWAIT, MT_DATA);
1884 if (m->m_next) {
1885 optp = mtod(m->m_next, u_char *);
1886 optm = m->m_next;
1887 } else
1888 incl_opts = false;
1889 } else {
1890 optp = (u_char *) (nth + 1);
1891 optm = m;
1892 }
1893 }
1894 if (incl_opts) {
1895 /* Timestamps. */
1896 if (tp->t_flags & TF_RCVD_TSTMP) {
1897 to.to_tsval = tcp_ts_getticks() + tp->ts_offset;
1898 to.to_tsecr = tp->ts_recent;
1899 to.to_flags |= TOF_TS;
1900 }
1901 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1902 /* TCP-MD5 (RFC2385). */
1903 if (tp->t_flags & TF_SIGNATURE)
1904 to.to_flags |= TOF_SIGNATURE;
1905 #endif
1906 /* Add the options. */
1907 tlen += optlen = tcp_addoptions(&to, optp);
1908
1909 /* Update m_len in the correct mbuf. */
1910 optm->m_len += optlen;
1911 } else
1912 optlen = 0;
1913 #ifdef INET6
1914 if (isipv6) {
1915 if (uh) {
1916 ulen = tlen - sizeof(struct ip6_hdr);
1917 uh->uh_ulen = htons(ulen);
1918 }
1919 ip6->ip6_flow = 0;
1920 ip6->ip6_vfc = IPV6_VERSION;
1921 if (port)
1922 ip6->ip6_nxt = IPPROTO_UDP;
1923 else
1924 ip6->ip6_nxt = IPPROTO_TCP;
1925 ip6->ip6_plen = htons(tlen - sizeof(*ip6));
1926 }
1927 #endif
1928 #if defined(INET) && defined(INET6)
1929 else
1930 #endif
1931 #ifdef INET
1932 {
1933 if (uh) {
1934 ulen = tlen - sizeof(struct ip);
1935 uh->uh_ulen = htons(ulen);
1936 }
1937 ip->ip_len = htons(tlen);
1938 ip->ip_ttl = V_ip_defttl;
1939 if (port) {
1940 ip->ip_p = IPPROTO_UDP;
1941 } else {
1942 ip->ip_p = IPPROTO_TCP;
1943 }
1944 if (V_path_mtu_discovery)
1945 ip->ip_off |= htons(IP_DF);
1946 }
1947 #endif
1948 m->m_pkthdr.len = tlen;
1949 m->m_pkthdr.rcvif = NULL;
1950 #ifdef MAC
1951 if (inp != NULL) {
1952 /*
1953 * Packet is associated with a socket, so allow the
1954 * label of the response to reflect the socket label.
1955 */
1956 INP_WLOCK_ASSERT(inp);
1957 mac_inpcb_create_mbuf(inp, m);
1958 } else {
1959 /*
1960 * Packet is not associated with a socket, so possibly
1961 * update the label in place.
1962 */
1963 mac_netinet_tcp_reply(m);
1964 }
1965 #endif
1966 nth->th_seq = htonl(seq);
1967 nth->th_ack = htonl(ack);
1968 nth->th_x2 = 0;
1969 nth->th_off = (sizeof (struct tcphdr) + optlen) >> 2;
1970 nth->th_flags = flags;
1971 if (tp != NULL)
1972 nth->th_win = htons((u_short) (win >> tp->rcv_scale));
1973 else
1974 nth->th_win = htons((u_short)win);
1975 nth->th_urp = 0;
1976
1977 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1978 if (to.to_flags & TOF_SIGNATURE) {
1979 if (!TCPMD5_ENABLED() ||
1980 TCPMD5_OUTPUT(m, nth, to.to_signature) != 0) {
1981 m_freem(m);
1982 return;
1983 }
1984 }
1985 #endif
1986
1987 #ifdef INET6
1988 if (isipv6) {
1989 if (port) {
1990 m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
1991 m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
1992 uh->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
1993 nth->th_sum = 0;
1994 } else {
1995 m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
1996 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1997 nth->th_sum = in6_cksum_pseudo(ip6,
1998 tlen - sizeof(struct ip6_hdr), IPPROTO_TCP, 0);
1999 }
2000 ip6->ip6_hlim = in6_selecthlim(tp != NULL ? tp->t_inpcb :
2001 NULL, NULL);
2002 }
2003 #endif /* INET6 */
2004 #if defined(INET6) && defined(INET)
2005 else
2006 #endif
2007 #ifdef INET
2008 {
2009 if (port) {
2010 uh->uh_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
2011 htons(ulen + IPPROTO_UDP));
2012 m->m_pkthdr.csum_flags = CSUM_UDP;
2013 m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
2014 nth->th_sum = 0;
2015 } else {
2016 m->m_pkthdr.csum_flags = CSUM_TCP;
2017 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2018 nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
2019 htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p)));
2020 }
2021 }
2022 #endif /* INET */
2023 #ifdef TCPDEBUG
2024 if (tp == NULL || (inp->inp_socket->so_options & SO_DEBUG))
2025 tcp_trace(TA_OUTPUT, 0, tp, mtod(m, void *), th, 0);
2026 #endif
2027 TCP_PROBE3(debug__output, tp, th, m);
2028 if (flags & TH_RST)
2029 TCP_PROBE5(accept__refused, NULL, NULL, m, tp, nth);
2030
2031 #ifdef INET6
2032 if (isipv6) {
2033 TCP_PROBE5(send, NULL, tp, ip6, tp, nth);
2034 (void)ip6_output(m, NULL, NULL, 0, NULL, NULL, inp);
2035 }
2036 #endif /* INET6 */
2037 #if defined(INET) && defined(INET6)
2038 else
2039 #endif
2040 #ifdef INET
2041 {
2042 TCP_PROBE5(send, NULL, tp, ip, tp, nth);
2043 (void)ip_output(m, NULL, NULL, 0, NULL, inp);
2044 }
2045 #endif
2046 }
2047
2048 /*
2049 * Create a new TCP control block, making an
2050 * empty reassembly queue and hooking it to the argument
2051 * protocol control block. The `inp' parameter must have
2052 * come from the zone allocator set up in tcp_init().
2053 */
2054 struct tcpcb *
tcp_newtcpcb(struct inpcb * inp)2055 tcp_newtcpcb(struct inpcb *inp)
2056 {
2057 struct tcpcb_mem *tm;
2058 struct tcpcb *tp;
2059 #ifdef INET6
2060 int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
2061 #endif /* INET6 */
2062
2063 tm = uma_zalloc(V_tcpcb_zone, M_NOWAIT | M_ZERO);
2064 if (tm == NULL)
2065 return (NULL);
2066 tp = &tm->tcb;
2067
2068 /* Initialise cc_var struct for this tcpcb. */
2069 tp->ccv = &tm->ccv;
2070 tp->ccv->type = IPPROTO_TCP;
2071 tp->ccv->ccvc.tcp = tp;
2072 rw_rlock(&tcp_function_lock);
2073 tp->t_fb = tcp_func_set_ptr;
2074 refcount_acquire(&tp->t_fb->tfb_refcnt);
2075 rw_runlock(&tcp_function_lock);
2076 /*
2077 * Use the current system default CC algorithm.
2078 */
2079 CC_LIST_RLOCK();
2080 KASSERT(!STAILQ_EMPTY(&cc_list), ("cc_list is empty!"));
2081 CC_ALGO(tp) = CC_DEFAULT();
2082 CC_LIST_RUNLOCK();
2083 /*
2084 * The tcpcb will hold a reference on its inpcb until tcp_discardcb()
2085 * is called.
2086 */
2087 in_pcbref(inp); /* Reference for tcpcb */
2088 tp->t_inpcb = inp;
2089
2090 if (CC_ALGO(tp)->cb_init != NULL)
2091 if (CC_ALGO(tp)->cb_init(tp->ccv) > 0) {
2092 if (tp->t_fb->tfb_tcp_fb_fini)
2093 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
2094 in_pcbrele_wlocked(inp);
2095 refcount_release(&tp->t_fb->tfb_refcnt);
2096 uma_zfree(V_tcpcb_zone, tm);
2097 return (NULL);
2098 }
2099
2100 #ifdef TCP_HHOOK
2101 tp->osd = &tm->osd;
2102 if (khelp_init_osd(HELPER_CLASS_TCP, tp->osd)) {
2103 if (tp->t_fb->tfb_tcp_fb_fini)
2104 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
2105 in_pcbrele_wlocked(inp);
2106 refcount_release(&tp->t_fb->tfb_refcnt);
2107 uma_zfree(V_tcpcb_zone, tm);
2108 return (NULL);
2109 }
2110 #endif
2111
2112 #ifdef VIMAGE
2113 tp->t_vnet = inp->inp_vnet;
2114 #endif
2115 tp->t_timers = &tm->tt;
2116 TAILQ_INIT(&tp->t_segq);
2117 tp->t_maxseg =
2118 #ifdef INET6
2119 isipv6 ? V_tcp_v6mssdflt :
2120 #endif /* INET6 */
2121 V_tcp_mssdflt;
2122
2123 /* Set up our timeouts. */
2124 callout_init(&tp->t_timers->tt_rexmt, 1);
2125 callout_init(&tp->t_timers->tt_persist, 1);
2126 callout_init(&tp->t_timers->tt_keep, 1);
2127 callout_init(&tp->t_timers->tt_2msl, 1);
2128 callout_init(&tp->t_timers->tt_delack, 1);
2129
2130 if (V_tcp_do_rfc1323)
2131 tp->t_flags = (TF_REQ_SCALE|TF_REQ_TSTMP);
2132 if (V_tcp_do_sack)
2133 tp->t_flags |= TF_SACK_PERMIT;
2134 TAILQ_INIT(&tp->snd_holes);
2135
2136 /*
2137 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
2138 * rtt estimate. Set rttvar so that srtt + 4 * rttvar gives
2139 * reasonable initial retransmit time.
2140 */
2141 tp->t_srtt = TCPTV_SRTTBASE;
2142 tp->t_rttvar = ((tcp_rexmit_initial - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4;
2143 tp->t_rttmin = tcp_rexmit_min;
2144 tp->t_rxtcur = tcp_rexmit_initial;
2145 tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
2146 tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
2147 tp->t_rcvtime = ticks;
2148 /*
2149 * IPv4 TTL initialization is necessary for an IPv6 socket as well,
2150 * because the socket may be bound to an IPv6 wildcard address,
2151 * which may match an IPv4-mapped IPv6 address.
2152 */
2153 inp->inp_ip_ttl = V_ip_defttl;
2154 inp->inp_ppcb = tp;
2155 #ifdef TCPPCAP
2156 /*
2157 * Init the TCP PCAP queues.
2158 */
2159 tcp_pcap_tcpcb_init(tp);
2160 #endif
2161 #ifdef TCP_BLACKBOX
2162 /* Initialize the per-TCPCB log data. */
2163 tcp_log_tcpcbinit(tp);
2164 #endif
2165 tp->t_pacing_rate = -1;
2166 if (tp->t_fb->tfb_tcp_fb_init) {
2167 if ((*tp->t_fb->tfb_tcp_fb_init)(tp)) {
2168 refcount_release(&tp->t_fb->tfb_refcnt);
2169 in_pcbrele_wlocked(inp);
2170 uma_zfree(V_tcpcb_zone, tm);
2171 return (NULL);
2172 }
2173 }
2174 #ifdef STATS
2175 if (V_tcp_perconn_stats_enable == 1)
2176 tp->t_stats = stats_blob_alloc(V_tcp_perconn_stats_dflt_tpl, 0);
2177 #endif
2178 return (tp); /* XXX */
2179 }
2180
2181 /*
2182 * Switch the congestion control algorithm back to NewReno for any active
2183 * control blocks using an algorithm which is about to go away.
2184 * This ensures the CC framework can allow the unload to proceed without leaving
2185 * any dangling pointers which would trigger a panic.
2186 * Returning non-zero would inform the CC framework that something went wrong
2187 * and it would be unsafe to allow the unload to proceed. However, there is no
2188 * way for this to occur with this implementation so we always return zero.
2189 */
2190 int
tcp_ccalgounload(struct cc_algo * unload_algo)2191 tcp_ccalgounload(struct cc_algo *unload_algo)
2192 {
2193 struct cc_algo *tmpalgo;
2194 struct inpcb *inp;
2195 struct tcpcb *tp;
2196 VNET_ITERATOR_DECL(vnet_iter);
2197
2198 /*
2199 * Check all active control blocks across all network stacks and change
2200 * any that are using "unload_algo" back to NewReno. If "unload_algo"
2201 * requires cleanup code to be run, call it.
2202 */
2203 VNET_LIST_RLOCK();
2204 VNET_FOREACH(vnet_iter) {
2205 CURVNET_SET(vnet_iter);
2206 INP_INFO_WLOCK(&V_tcbinfo);
2207 /*
2208 * New connections already part way through being initialised
2209 * with the CC algo we're removing will not race with this code
2210 * because the INP_INFO_WLOCK is held during initialisation. We
2211 * therefore don't enter the loop below until the connection
2212 * list has stabilised.
2213 */
2214 CK_LIST_FOREACH(inp, &V_tcb, inp_list) {
2215 INP_WLOCK(inp);
2216 /* Important to skip tcptw structs. */
2217 if (!(inp->inp_flags & INP_TIMEWAIT) &&
2218 (tp = intotcpcb(inp)) != NULL) {
2219 /*
2220 * By holding INP_WLOCK here, we are assured
2221 * that the connection is not currently
2222 * executing inside the CC module's functions
2223 * i.e. it is safe to make the switch back to
2224 * NewReno.
2225 */
2226 if (CC_ALGO(tp) == unload_algo) {
2227 tmpalgo = CC_ALGO(tp);
2228 if (tmpalgo->cb_destroy != NULL)
2229 tmpalgo->cb_destroy(tp->ccv);
2230 CC_DATA(tp) = NULL;
2231 /*
2232 * NewReno may allocate memory on
2233 * demand for certain stateful
2234 * configuration as needed, but is
2235 * coded to never fail on memory
2236 * allocation failure so it is a safe
2237 * fallback.
2238 */
2239 CC_ALGO(tp) = &newreno_cc_algo;
2240 }
2241 }
2242 INP_WUNLOCK(inp);
2243 }
2244 INP_INFO_WUNLOCK(&V_tcbinfo);
2245 CURVNET_RESTORE();
2246 }
2247 VNET_LIST_RUNLOCK();
2248
2249 return (0);
2250 }
2251
2252 /*
2253 * Drop a TCP connection, reporting
2254 * the specified error. If connection is synchronized,
2255 * then send a RST to peer.
2256 */
2257 struct tcpcb *
tcp_drop(struct tcpcb * tp,int errno)2258 tcp_drop(struct tcpcb *tp, int errno)
2259 {
2260 struct socket *so = tp->t_inpcb->inp_socket;
2261
2262 NET_EPOCH_ASSERT();
2263 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2264 INP_WLOCK_ASSERT(tp->t_inpcb);
2265
2266 if (TCPS_HAVERCVDSYN(tp->t_state)) {
2267 tcp_state_change(tp, TCPS_CLOSED);
2268 (void) tp->t_fb->tfb_tcp_output(tp);
2269 TCPSTAT_INC(tcps_drops);
2270 } else
2271 TCPSTAT_INC(tcps_conndrops);
2272 if (errno == ETIMEDOUT && tp->t_softerror)
2273 errno = tp->t_softerror;
2274 so->so_error = errno;
2275 return (tcp_close(tp));
2276 }
2277
2278 void
tcp_discardcb(struct tcpcb * tp)2279 tcp_discardcb(struct tcpcb *tp)
2280 {
2281 struct inpcb *inp = tp->t_inpcb;
2282 struct socket *so = inp->inp_socket;
2283 #ifdef INET6
2284 int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
2285 #endif /* INET6 */
2286 int released __unused;
2287
2288 INP_WLOCK_ASSERT(inp);
2289
2290 /*
2291 * Make sure that all of our timers are stopped before we delete the
2292 * PCB.
2293 *
2294 * If stopping a timer fails, we schedule a discard function in same
2295 * callout, and the last discard function called will take care of
2296 * deleting the tcpcb.
2297 */
2298 tp->t_timers->tt_draincnt = 0;
2299 tcp_timer_stop(tp, TT_REXMT);
2300 tcp_timer_stop(tp, TT_PERSIST);
2301 tcp_timer_stop(tp, TT_KEEP);
2302 tcp_timer_stop(tp, TT_2MSL);
2303 tcp_timer_stop(tp, TT_DELACK);
2304 if (tp->t_fb->tfb_tcp_timer_stop_all) {
2305 /*
2306 * Call the stop-all function of the methods,
2307 * this function should call the tcp_timer_stop()
2308 * method with each of the function specific timeouts.
2309 * That stop will be called via the tfb_tcp_timer_stop()
2310 * which should use the async drain function of the
2311 * callout system (see tcp_var.h).
2312 */
2313 tp->t_fb->tfb_tcp_timer_stop_all(tp);
2314 }
2315
2316 /* free the reassembly queue, if any */
2317 tcp_reass_flush(tp);
2318
2319 #ifdef TCP_OFFLOAD
2320 /* Disconnect offload device, if any. */
2321 if (tp->t_flags & TF_TOE)
2322 tcp_offload_detach(tp);
2323 #endif
2324
2325 tcp_free_sackholes(tp);
2326
2327 #ifdef TCPPCAP
2328 /* Free the TCP PCAP queues. */
2329 tcp_pcap_drain(&(tp->t_inpkts));
2330 tcp_pcap_drain(&(tp->t_outpkts));
2331 #endif
2332
2333 /* Allow the CC algorithm to clean up after itself. */
2334 if (CC_ALGO(tp)->cb_destroy != NULL)
2335 CC_ALGO(tp)->cb_destroy(tp->ccv);
2336 CC_DATA(tp) = NULL;
2337
2338 #ifdef TCP_HHOOK
2339 khelp_destroy_osd(tp->osd);
2340 #endif
2341 #ifdef STATS
2342 stats_blob_destroy(tp->t_stats);
2343 #endif
2344
2345 CC_ALGO(tp) = NULL;
2346 inp->inp_ppcb = NULL;
2347 if (tp->t_timers->tt_draincnt == 0) {
2348 /* We own the last reference on tcpcb, let's free it. */
2349 #ifdef TCP_BLACKBOX
2350 tcp_log_tcpcbfini(tp);
2351 #endif
2352 TCPSTATES_DEC(tp->t_state);
2353 if (tp->t_fb->tfb_tcp_fb_fini)
2354 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
2355
2356 /*
2357 * If we got enough samples through the srtt filter,
2358 * save the rtt and rttvar in the routing entry.
2359 * 'Enough' is arbitrarily defined as 4 rtt samples.
2360 * 4 samples is enough for the srtt filter to converge
2361 * to within enough % of the correct value; fewer samples
2362 * and we could save a bogus rtt. The danger is not high
2363 * as tcp quickly recovers from everything.
2364 * XXX: Works very well but needs some more statistics!
2365 *
2366 * XXXRRS: Updating must be after the stack fini() since
2367 * that may be converting some internal representation of
2368 * say srtt etc into the general one used by other stacks.
2369 * Lets also at least protect against the so being NULL
2370 * as RW stated below.
2371 */
2372 if ((tp->t_rttupdated >= 4) && (so != NULL)) {
2373 struct hc_metrics_lite metrics;
2374 uint32_t ssthresh;
2375
2376 bzero(&metrics, sizeof(metrics));
2377 /*
2378 * Update the ssthresh always when the conditions below
2379 * are satisfied. This gives us better new start value
2380 * for the congestion avoidance for new connections.
2381 * ssthresh is only set if packet loss occurred on a session.
2382 *
2383 * XXXRW: 'so' may be NULL here, and/or socket buffer may be
2384 * being torn down. Ideally this code would not use 'so'.
2385 */
2386 ssthresh = tp->snd_ssthresh;
2387 if (ssthresh != 0 && ssthresh < so->so_snd.sb_hiwat / 2) {
2388 /*
2389 * convert the limit from user data bytes to
2390 * packets then to packet data bytes.
2391 */
2392 ssthresh = (ssthresh + tp->t_maxseg / 2) / tp->t_maxseg;
2393 if (ssthresh < 2)
2394 ssthresh = 2;
2395 ssthresh *= (tp->t_maxseg +
2396 #ifdef INET6
2397 (isipv6 ? sizeof (struct ip6_hdr) +
2398 sizeof (struct tcphdr) :
2399 #endif
2400 sizeof (struct tcpiphdr)
2401 #ifdef INET6
2402 )
2403 #endif
2404 );
2405 } else
2406 ssthresh = 0;
2407 metrics.rmx_ssthresh = ssthresh;
2408
2409 metrics.rmx_rtt = tp->t_srtt;
2410 metrics.rmx_rttvar = tp->t_rttvar;
2411 metrics.rmx_cwnd = tp->snd_cwnd;
2412 metrics.rmx_sendpipe = 0;
2413 metrics.rmx_recvpipe = 0;
2414
2415 tcp_hc_update(&inp->inp_inc, &metrics);
2416 }
2417 refcount_release(&tp->t_fb->tfb_refcnt);
2418 tp->t_inpcb = NULL;
2419 uma_zfree(V_tcpcb_zone, tp);
2420 released = in_pcbrele_wlocked(inp);
2421 KASSERT(!released, ("%s: inp %p should not have been released "
2422 "here", __func__, inp));
2423 }
2424 }
2425
2426 void
tcp_timer_discard(void * ptp)2427 tcp_timer_discard(void *ptp)
2428 {
2429 struct inpcb *inp;
2430 struct tcpcb *tp;
2431 struct epoch_tracker et;
2432
2433 tp = (struct tcpcb *)ptp;
2434 CURVNET_SET(tp->t_vnet);
2435 NET_EPOCH_ENTER(et);
2436 inp = tp->t_inpcb;
2437 KASSERT(inp != NULL, ("%s: tp %p tp->t_inpcb == NULL",
2438 __func__, tp));
2439 INP_WLOCK(inp);
2440 KASSERT((tp->t_timers->tt_flags & TT_STOPPED) != 0,
2441 ("%s: tcpcb has to be stopped here", __func__));
2442 tp->t_timers->tt_draincnt--;
2443 if (tp->t_timers->tt_draincnt == 0) {
2444 /* We own the last reference on this tcpcb, let's free it. */
2445 #ifdef TCP_BLACKBOX
2446 tcp_log_tcpcbfini(tp);
2447 #endif
2448 TCPSTATES_DEC(tp->t_state);
2449 if (tp->t_fb->tfb_tcp_fb_fini)
2450 (*tp->t_fb->tfb_tcp_fb_fini)(tp, 1);
2451 refcount_release(&tp->t_fb->tfb_refcnt);
2452 tp->t_inpcb = NULL;
2453 uma_zfree(V_tcpcb_zone, tp);
2454 if (in_pcbrele_wlocked(inp)) {
2455 NET_EPOCH_EXIT(et);
2456 CURVNET_RESTORE();
2457 return;
2458 }
2459 }
2460 INP_WUNLOCK(inp);
2461 NET_EPOCH_EXIT(et);
2462 CURVNET_RESTORE();
2463 }
2464
2465 /*
2466 * Attempt to close a TCP control block, marking it as dropped, and freeing
2467 * the socket if we hold the only reference.
2468 */
2469 struct tcpcb *
tcp_close(struct tcpcb * tp)2470 tcp_close(struct tcpcb *tp)
2471 {
2472 struct inpcb *inp = tp->t_inpcb;
2473 struct socket *so;
2474
2475 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2476 INP_WLOCK_ASSERT(inp);
2477
2478 #ifdef TCP_OFFLOAD
2479 if (tp->t_state == TCPS_LISTEN)
2480 tcp_offload_listen_stop(tp);
2481 #endif
2482 /*
2483 * This releases the TFO pending counter resource for TFO listen
2484 * sockets as well as passively-created TFO sockets that transition
2485 * from SYN_RECEIVED to CLOSED.
2486 */
2487 if (tp->t_tfo_pending) {
2488 tcp_fastopen_decrement_counter(tp->t_tfo_pending);
2489 tp->t_tfo_pending = NULL;
2490 }
2491 in_pcbdrop(inp);
2492 TCPSTAT_INC(tcps_closed);
2493 if (tp->t_state != TCPS_CLOSED)
2494 tcp_state_change(tp, TCPS_CLOSED);
2495 KASSERT(inp->inp_socket != NULL, ("tcp_close: inp_socket NULL"));
2496 so = inp->inp_socket;
2497 soisdisconnected(so);
2498 if (inp->inp_flags & INP_SOCKREF) {
2499 KASSERT(so->so_state & SS_PROTOREF,
2500 ("tcp_close: !SS_PROTOREF"));
2501 inp->inp_flags &= ~INP_SOCKREF;
2502 INP_WUNLOCK(inp);
2503 SOCK_LOCK(so);
2504 so->so_state &= ~SS_PROTOREF;
2505 sofree(so);
2506 return (NULL);
2507 }
2508 return (tp);
2509 }
2510
2511 void
tcp_drain(void)2512 tcp_drain(void)
2513 {
2514 VNET_ITERATOR_DECL(vnet_iter);
2515
2516 if (!do_tcpdrain)
2517 return;
2518
2519 VNET_LIST_RLOCK_NOSLEEP();
2520 VNET_FOREACH(vnet_iter) {
2521 CURVNET_SET(vnet_iter);
2522 struct inpcb *inpb;
2523 struct tcpcb *tcpb;
2524
2525 /*
2526 * Walk the tcpbs, if existing, and flush the reassembly queue,
2527 * if there is one...
2528 * XXX: The "Net/3" implementation doesn't imply that the TCP
2529 * reassembly queue should be flushed, but in a situation
2530 * where we're really low on mbufs, this is potentially
2531 * useful.
2532 */
2533 INP_INFO_WLOCK(&V_tcbinfo);
2534 CK_LIST_FOREACH(inpb, V_tcbinfo.ipi_listhead, inp_list) {
2535 INP_WLOCK(inpb);
2536 if (inpb->inp_flags & INP_TIMEWAIT) {
2537 INP_WUNLOCK(inpb);
2538 continue;
2539 }
2540 if ((tcpb = intotcpcb(inpb)) != NULL) {
2541 tcp_reass_flush(tcpb);
2542 tcp_clean_sackreport(tcpb);
2543 #ifdef TCP_BLACKBOX
2544 tcp_log_drain(tcpb);
2545 #endif
2546 #ifdef TCPPCAP
2547 if (tcp_pcap_aggressive_free) {
2548 /* Free the TCP PCAP queues. */
2549 tcp_pcap_drain(&(tcpb->t_inpkts));
2550 tcp_pcap_drain(&(tcpb->t_outpkts));
2551 }
2552 #endif
2553 }
2554 INP_WUNLOCK(inpb);
2555 }
2556 INP_INFO_WUNLOCK(&V_tcbinfo);
2557 CURVNET_RESTORE();
2558 }
2559 VNET_LIST_RUNLOCK_NOSLEEP();
2560 }
2561
2562 /*
2563 * Notify a tcp user of an asynchronous error;
2564 * store error as soft error, but wake up user
2565 * (for now, won't do anything until can select for soft error).
2566 *
2567 * Do not wake up user since there currently is no mechanism for
2568 * reporting soft errors (yet - a kqueue filter may be added).
2569 */
2570 static struct inpcb *
tcp_notify(struct inpcb * inp,int error)2571 tcp_notify(struct inpcb *inp, int error)
2572 {
2573 struct tcpcb *tp;
2574
2575 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2576 INP_WLOCK_ASSERT(inp);
2577
2578 if ((inp->inp_flags & INP_TIMEWAIT) ||
2579 (inp->inp_flags & INP_DROPPED))
2580 return (inp);
2581
2582 tp = intotcpcb(inp);
2583 KASSERT(tp != NULL, ("tcp_notify: tp == NULL"));
2584
2585 /*
2586 * Ignore some errors if we are hooked up.
2587 * If connection hasn't completed, has retransmitted several times,
2588 * and receives a second error, give up now. This is better
2589 * than waiting a long time to establish a connection that
2590 * can never complete.
2591 */
2592 if (tp->t_state == TCPS_ESTABLISHED &&
2593 (error == EHOSTUNREACH || error == ENETUNREACH ||
2594 error == EHOSTDOWN)) {
2595 if (inp->inp_route.ro_nh) {
2596 NH_FREE(inp->inp_route.ro_nh);
2597 inp->inp_route.ro_nh = (struct nhop_object *)NULL;
2598 }
2599 return (inp);
2600 } else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 &&
2601 tp->t_softerror) {
2602 tp = tcp_drop(tp, error);
2603 if (tp != NULL)
2604 return (inp);
2605 else
2606 return (NULL);
2607 } else {
2608 tp->t_softerror = error;
2609 return (inp);
2610 }
2611 #if 0
2612 wakeup( &so->so_timeo);
2613 sorwakeup(so);
2614 sowwakeup(so);
2615 #endif
2616 }
2617
2618 static int
tcp_pcblist(SYSCTL_HANDLER_ARGS)2619 tcp_pcblist(SYSCTL_HANDLER_ARGS)
2620 {
2621 struct epoch_tracker et;
2622 struct inpcb *inp;
2623 struct xinpgen xig;
2624 int error;
2625
2626 if (req->newptr != NULL)
2627 return (EPERM);
2628
2629 if (req->oldptr == NULL) {
2630 int n;
2631
2632 n = V_tcbinfo.ipi_count +
2633 counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
2634 n += imax(n / 8, 10);
2635 req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xtcpcb);
2636 return (0);
2637 }
2638
2639 if ((error = sysctl_wire_old_buffer(req, 0)) != 0)
2640 return (error);
2641
2642 bzero(&xig, sizeof(xig));
2643 xig.xig_len = sizeof xig;
2644 xig.xig_count = V_tcbinfo.ipi_count +
2645 counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
2646 xig.xig_gen = V_tcbinfo.ipi_gencnt;
2647 xig.xig_sogen = so_gencnt;
2648 error = SYSCTL_OUT(req, &xig, sizeof xig);
2649 if (error)
2650 return (error);
2651
2652 error = syncache_pcblist(req);
2653 if (error)
2654 return (error);
2655
2656 NET_EPOCH_ENTER(et);
2657 for (inp = CK_LIST_FIRST(V_tcbinfo.ipi_listhead);
2658 inp != NULL;
2659 inp = CK_LIST_NEXT(inp, inp_list)) {
2660 INP_RLOCK(inp);
2661 if (inp->inp_gencnt <= xig.xig_gen) {
2662 int crerr;
2663
2664 /*
2665 * XXX: This use of cr_cansee(), introduced with
2666 * TCP state changes, is not quite right, but for
2667 * now, better than nothing.
2668 */
2669 if (inp->inp_flags & INP_TIMEWAIT) {
2670 if (intotw(inp) != NULL)
2671 crerr = cr_cansee(req->td->td_ucred,
2672 intotw(inp)->tw_cred);
2673 else
2674 crerr = EINVAL; /* Skip this inp. */
2675 } else
2676 crerr = cr_canseeinpcb(req->td->td_ucred, inp);
2677 if (crerr == 0) {
2678 struct xtcpcb xt;
2679
2680 tcp_inptoxtp(inp, &xt);
2681 INP_RUNLOCK(inp);
2682 error = SYSCTL_OUT(req, &xt, sizeof xt);
2683 if (error)
2684 break;
2685 else
2686 continue;
2687 }
2688 }
2689 INP_RUNLOCK(inp);
2690 }
2691 NET_EPOCH_EXIT(et);
2692
2693 if (!error) {
2694 /*
2695 * Give the user an updated idea of our state.
2696 * If the generation differs from what we told
2697 * her before, she knows that something happened
2698 * while we were processing this request, and it
2699 * might be necessary to retry.
2700 */
2701 xig.xig_gen = V_tcbinfo.ipi_gencnt;
2702 xig.xig_sogen = so_gencnt;
2703 xig.xig_count = V_tcbinfo.ipi_count +
2704 counter_u64_fetch(V_tcps_states[TCPS_SYN_RECEIVED]);
2705 error = SYSCTL_OUT(req, &xig, sizeof xig);
2706 }
2707
2708 return (error);
2709 }
2710
2711 SYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist,
2712 CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
2713 NULL, 0, tcp_pcblist, "S,xtcpcb",
2714 "List of active TCP connections");
2715
2716 #ifdef INET
2717 static int
tcp_getcred(SYSCTL_HANDLER_ARGS)2718 tcp_getcred(SYSCTL_HANDLER_ARGS)
2719 {
2720 struct xucred xuc;
2721 struct sockaddr_in addrs[2];
2722 struct epoch_tracker et;
2723 struct inpcb *inp;
2724 int error;
2725
2726 error = priv_check(req->td, PRIV_NETINET_GETCRED);
2727 if (error)
2728 return (error);
2729 error = SYSCTL_IN(req, addrs, sizeof(addrs));
2730 if (error)
2731 return (error);
2732 NET_EPOCH_ENTER(et);
2733 inp = in_pcblookup(&V_tcbinfo, addrs[1].sin_addr, addrs[1].sin_port,
2734 addrs[0].sin_addr, addrs[0].sin_port, INPLOOKUP_RLOCKPCB, NULL);
2735 NET_EPOCH_EXIT(et);
2736 if (inp != NULL) {
2737 if (inp->inp_socket == NULL)
2738 error = ENOENT;
2739 if (error == 0)
2740 error = cr_canseeinpcb(req->td->td_ucred, inp);
2741 if (error == 0)
2742 cru2x(inp->inp_cred, &xuc);
2743 INP_RUNLOCK(inp);
2744 } else
2745 error = ENOENT;
2746 if (error == 0)
2747 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
2748 return (error);
2749 }
2750
2751 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, getcred,
2752 CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_PRISON | CTLFLAG_NEEDGIANT,
2753 0, 0, tcp_getcred, "S,xucred",
2754 "Get the xucred of a TCP connection");
2755 #endif /* INET */
2756
2757 #ifdef INET6
2758 static int
tcp6_getcred(SYSCTL_HANDLER_ARGS)2759 tcp6_getcred(SYSCTL_HANDLER_ARGS)
2760 {
2761 struct epoch_tracker et;
2762 struct xucred xuc;
2763 struct sockaddr_in6 addrs[2];
2764 struct inpcb *inp;
2765 int error;
2766 #ifdef INET
2767 int mapped = 0;
2768 #endif
2769
2770 error = priv_check(req->td, PRIV_NETINET_GETCRED);
2771 if (error)
2772 return (error);
2773 error = SYSCTL_IN(req, addrs, sizeof(addrs));
2774 if (error)
2775 return (error);
2776 if ((error = sa6_embedscope(&addrs[0], V_ip6_use_defzone)) != 0 ||
2777 (error = sa6_embedscope(&addrs[1], V_ip6_use_defzone)) != 0) {
2778 return (error);
2779 }
2780 if (IN6_IS_ADDR_V4MAPPED(&addrs[0].sin6_addr)) {
2781 #ifdef INET
2782 if (IN6_IS_ADDR_V4MAPPED(&addrs[1].sin6_addr))
2783 mapped = 1;
2784 else
2785 #endif
2786 return (EINVAL);
2787 }
2788
2789 NET_EPOCH_ENTER(et);
2790 #ifdef INET
2791 if (mapped == 1)
2792 inp = in_pcblookup(&V_tcbinfo,
2793 *(struct in_addr *)&addrs[1].sin6_addr.s6_addr[12],
2794 addrs[1].sin6_port,
2795 *(struct in_addr *)&addrs[0].sin6_addr.s6_addr[12],
2796 addrs[0].sin6_port, INPLOOKUP_RLOCKPCB, NULL);
2797 else
2798 #endif
2799 inp = in6_pcblookup(&V_tcbinfo,
2800 &addrs[1].sin6_addr, addrs[1].sin6_port,
2801 &addrs[0].sin6_addr, addrs[0].sin6_port,
2802 INPLOOKUP_RLOCKPCB, NULL);
2803 NET_EPOCH_EXIT(et);
2804 if (inp != NULL) {
2805 if (inp->inp_socket == NULL)
2806 error = ENOENT;
2807 if (error == 0)
2808 error = cr_canseeinpcb(req->td->td_ucred, inp);
2809 if (error == 0)
2810 cru2x(inp->inp_cred, &xuc);
2811 INP_RUNLOCK(inp);
2812 } else
2813 error = ENOENT;
2814 if (error == 0)
2815 error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
2816 return (error);
2817 }
2818
2819 SYSCTL_PROC(_net_inet6_tcp6, OID_AUTO, getcred,
2820 CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_PRISON | CTLFLAG_NEEDGIANT,
2821 0, 0, tcp6_getcred, "S,xucred",
2822 "Get the xucred of a TCP6 connection");
2823 #endif /* INET6 */
2824
2825 #ifdef INET
2826 static void
tcp_ctlinput_with_port(int cmd,struct sockaddr * sa,void * vip,uint16_t port)2827 tcp_ctlinput_with_port(int cmd, struct sockaddr *sa, void *vip, uint16_t port)
2828 {
2829 struct ip *ip = vip;
2830 struct tcphdr *th;
2831 struct in_addr faddr;
2832 struct inpcb *inp;
2833 struct tcpcb *tp;
2834 struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify;
2835 struct icmp *icp;
2836 struct in_conninfo inc;
2837 tcp_seq icmp_tcp_seq;
2838 int mtu;
2839
2840 faddr = ((struct sockaddr_in *)sa)->sin_addr;
2841 if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
2842 return;
2843
2844 if (cmd == PRC_MSGSIZE)
2845 notify = tcp_mtudisc_notify;
2846 else if (V_icmp_may_rst && (cmd == PRC_UNREACH_ADMIN_PROHIB ||
2847 cmd == PRC_UNREACH_PORT || cmd == PRC_UNREACH_PROTOCOL ||
2848 cmd == PRC_TIMXCEED_INTRANS) && ip)
2849 notify = tcp_drop_syn_sent;
2850
2851 /*
2852 * Hostdead is ugly because it goes linearly through all PCBs.
2853 * XXX: We never get this from ICMP, otherwise it makes an
2854 * excellent DoS attack on machines with many connections.
2855 */
2856 else if (cmd == PRC_HOSTDEAD)
2857 ip = NULL;
2858 else if ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0)
2859 return;
2860
2861 if (ip == NULL) {
2862 in_pcbnotifyall(&V_tcbinfo, faddr, inetctlerrmap[cmd], notify);
2863 return;
2864 }
2865
2866 icp = (struct icmp *)((caddr_t)ip - offsetof(struct icmp, icmp_ip));
2867 th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
2868 inp = in_pcblookup(&V_tcbinfo, faddr, th->th_dport, ip->ip_src,
2869 th->th_sport, INPLOOKUP_WLOCKPCB, NULL);
2870 if (inp != NULL && PRC_IS_REDIRECT(cmd)) {
2871 /* signal EHOSTDOWN, as it flushes the cached route */
2872 inp = (*notify)(inp, EHOSTDOWN);
2873 goto out;
2874 }
2875 icmp_tcp_seq = th->th_seq;
2876 if (inp != NULL) {
2877 if (!(inp->inp_flags & INP_TIMEWAIT) &&
2878 !(inp->inp_flags & INP_DROPPED) &&
2879 !(inp->inp_socket == NULL)) {
2880 tp = intotcpcb(inp);
2881 if (tp->t_port != port) {
2882 goto out;
2883 }
2884 if (SEQ_GEQ(ntohl(icmp_tcp_seq), tp->snd_una) &&
2885 SEQ_LT(ntohl(icmp_tcp_seq), tp->snd_max)) {
2886 if (cmd == PRC_MSGSIZE) {
2887 /*
2888 * MTU discovery:
2889 * If we got a needfrag set the MTU
2890 * in the route to the suggested new
2891 * value (if given) and then notify.
2892 */
2893 mtu = ntohs(icp->icmp_nextmtu);
2894 /*
2895 * If no alternative MTU was
2896 * proposed, try the next smaller
2897 * one.
2898 */
2899 if (!mtu)
2900 mtu = ip_next_mtu(
2901 ntohs(ip->ip_len), 1);
2902 if (mtu < V_tcp_minmss +
2903 sizeof(struct tcpiphdr))
2904 mtu = V_tcp_minmss +
2905 sizeof(struct tcpiphdr);
2906 /*
2907 * Only process the offered MTU if it
2908 * is smaller than the current one.
2909 */
2910 if (mtu < tp->t_maxseg +
2911 sizeof(struct tcpiphdr)) {
2912 bzero(&inc, sizeof(inc));
2913 inc.inc_faddr = faddr;
2914 inc.inc_fibnum =
2915 inp->inp_inc.inc_fibnum;
2916 tcp_hc_updatemtu(&inc, mtu);
2917 tcp_mtudisc(inp, mtu);
2918 }
2919 } else
2920 inp = (*notify)(inp,
2921 inetctlerrmap[cmd]);
2922 }
2923 }
2924 } else {
2925 bzero(&inc, sizeof(inc));
2926 inc.inc_fport = th->th_dport;
2927 inc.inc_lport = th->th_sport;
2928 inc.inc_faddr = faddr;
2929 inc.inc_laddr = ip->ip_src;
2930 syncache_unreach(&inc, icmp_tcp_seq, port);
2931 }
2932 out:
2933 if (inp != NULL)
2934 INP_WUNLOCK(inp);
2935 }
2936
2937 void
tcp_ctlinput(int cmd,struct sockaddr * sa,void * vip)2938 tcp_ctlinput(int cmd, struct sockaddr *sa, void *vip)
2939 {
2940 tcp_ctlinput_with_port(cmd, sa, vip, htons(0));
2941 }
2942
2943 void
tcp_ctlinput_viaudp(int cmd,struct sockaddr * sa,void * vip,void * unused)2944 tcp_ctlinput_viaudp(int cmd, struct sockaddr *sa, void *vip, void *unused)
2945 {
2946 /* Its a tunneled TCP over UDP icmp */
2947 struct ip *outer_ip, *inner_ip;
2948 struct icmp *icmp;
2949 struct udphdr *udp;
2950 struct tcphdr *th, ttemp;
2951 int i_hlen, o_len;
2952 uint16_t port;
2953
2954 inner_ip = (struct ip *)vip;
2955 icmp = (struct icmp *)((caddr_t)inner_ip -
2956 (sizeof(struct icmp) - sizeof(struct ip)));
2957 outer_ip = (struct ip *)((caddr_t)icmp - sizeof(struct ip));
2958 i_hlen = inner_ip->ip_hl << 2;
2959 o_len = ntohs(outer_ip->ip_len);
2960 if (o_len <
2961 (sizeof(struct ip) + 8 + i_hlen + sizeof(struct udphdr) + offsetof(struct tcphdr, th_ack))) {
2962 /* Not enough data present */
2963 return;
2964 }
2965 /* Ok lets strip out the inner udphdr header by copying up on top of it the tcp hdr */
2966 udp = (struct udphdr *)(((caddr_t)inner_ip) + i_hlen);
2967 if (ntohs(udp->uh_sport) != V_tcp_udp_tunneling_port) {
2968 return;
2969 }
2970 port = udp->uh_dport;
2971 th = (struct tcphdr *)(udp + 1);
2972 memcpy(&ttemp, th, sizeof(struct tcphdr));
2973 memcpy(udp, &ttemp, sizeof(struct tcphdr));
2974 /* Now adjust down the size of the outer IP header */
2975 o_len -= sizeof(struct udphdr);
2976 outer_ip->ip_len = htons(o_len);
2977 /* Now call in to the normal handling code */
2978 tcp_ctlinput_with_port(cmd, sa, vip, port);
2979 }
2980 #endif /* INET */
2981
2982 #ifdef INET6
2983 static void
tcp6_ctlinput_with_port(int cmd,struct sockaddr * sa,void * d,uint16_t port)2984 tcp6_ctlinput_with_port(int cmd, struct sockaddr *sa, void *d, uint16_t port)
2985 {
2986 struct in6_addr *dst;
2987 struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify;
2988 struct ip6_hdr *ip6;
2989 struct mbuf *m;
2990 struct inpcb *inp;
2991 struct tcpcb *tp;
2992 struct icmp6_hdr *icmp6;
2993 struct ip6ctlparam *ip6cp = NULL;
2994 const struct sockaddr_in6 *sa6_src = NULL;
2995 struct in_conninfo inc;
2996 struct tcp_ports {
2997 uint16_t th_sport;
2998 uint16_t th_dport;
2999 } t_ports;
3000 tcp_seq icmp_tcp_seq;
3001 unsigned int mtu;
3002 unsigned int off;
3003
3004 if (sa->sa_family != AF_INET6 ||
3005 sa->sa_len != sizeof(struct sockaddr_in6))
3006 return;
3007
3008 /* if the parameter is from icmp6, decode it. */
3009 if (d != NULL) {
3010 ip6cp = (struct ip6ctlparam *)d;
3011 icmp6 = ip6cp->ip6c_icmp6;
3012 m = ip6cp->ip6c_m;
3013 ip6 = ip6cp->ip6c_ip6;
3014 off = ip6cp->ip6c_off;
3015 sa6_src = ip6cp->ip6c_src;
3016 dst = ip6cp->ip6c_finaldst;
3017 } else {
3018 m = NULL;
3019 ip6 = NULL;
3020 off = 0; /* fool gcc */
3021 sa6_src = &sa6_any;
3022 dst = NULL;
3023 }
3024
3025 if (cmd == PRC_MSGSIZE)
3026 notify = tcp_mtudisc_notify;
3027 else if (V_icmp_may_rst && (cmd == PRC_UNREACH_ADMIN_PROHIB ||
3028 cmd == PRC_UNREACH_PORT || cmd == PRC_UNREACH_PROTOCOL ||
3029 cmd == PRC_TIMXCEED_INTRANS) && ip6 != NULL)
3030 notify = tcp_drop_syn_sent;
3031
3032 /*
3033 * Hostdead is ugly because it goes linearly through all PCBs.
3034 * XXX: We never get this from ICMP, otherwise it makes an
3035 * excellent DoS attack on machines with many connections.
3036 */
3037 else if (cmd == PRC_HOSTDEAD)
3038 ip6 = NULL;
3039 else if ((unsigned)cmd >= PRC_NCMDS || inet6ctlerrmap[cmd] == 0)
3040 return;
3041
3042 if (ip6 == NULL) {
3043 in6_pcbnotify(&V_tcbinfo, sa, 0,
3044 (const struct sockaddr *)sa6_src,
3045 0, cmd, NULL, notify);
3046 return;
3047 }
3048
3049 /* Check if we can safely get the ports from the tcp hdr */
3050 if (m == NULL ||
3051 (m->m_pkthdr.len <
3052 (int32_t) (off + sizeof(struct tcp_ports)))) {
3053 return;
3054 }
3055 bzero(&t_ports, sizeof(struct tcp_ports));
3056 m_copydata(m, off, sizeof(struct tcp_ports), (caddr_t)&t_ports);
3057 inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_dst, t_ports.th_dport,
3058 &ip6->ip6_src, t_ports.th_sport, INPLOOKUP_WLOCKPCB, NULL);
3059 if (inp != NULL && PRC_IS_REDIRECT(cmd)) {
3060 /* signal EHOSTDOWN, as it flushes the cached route */
3061 inp = (*notify)(inp, EHOSTDOWN);
3062 goto out;
3063 }
3064 off += sizeof(struct tcp_ports);
3065 if (m->m_pkthdr.len < (int32_t) (off + sizeof(tcp_seq))) {
3066 goto out;
3067 }
3068 m_copydata(m, off, sizeof(tcp_seq), (caddr_t)&icmp_tcp_seq);
3069 if (inp != NULL) {
3070 if (!(inp->inp_flags & INP_TIMEWAIT) &&
3071 !(inp->inp_flags & INP_DROPPED) &&
3072 !(inp->inp_socket == NULL)) {
3073 tp = intotcpcb(inp);
3074 if (tp->t_port != port) {
3075 goto out;
3076 }
3077 if (SEQ_GEQ(ntohl(icmp_tcp_seq), tp->snd_una) &&
3078 SEQ_LT(ntohl(icmp_tcp_seq), tp->snd_max)) {
3079 if (cmd == PRC_MSGSIZE) {
3080 /*
3081 * MTU discovery:
3082 * If we got a needfrag set the MTU
3083 * in the route to the suggested new
3084 * value (if given) and then notify.
3085 */
3086 mtu = ntohl(icmp6->icmp6_mtu);
3087 /*
3088 * If no alternative MTU was
3089 * proposed, or the proposed
3090 * MTU was too small, set to
3091 * the min.
3092 */
3093 if (mtu < IPV6_MMTU)
3094 mtu = IPV6_MMTU - 8;
3095 bzero(&inc, sizeof(inc));
3096 inc.inc_fibnum = M_GETFIB(m);
3097 inc.inc_flags |= INC_ISIPV6;
3098 inc.inc6_faddr = *dst;
3099 if (in6_setscope(&inc.inc6_faddr,
3100 m->m_pkthdr.rcvif, NULL))
3101 goto out;
3102 /*
3103 * Only process the offered MTU if it
3104 * is smaller than the current one.
3105 */
3106 if (mtu < tp->t_maxseg +
3107 sizeof (struct tcphdr) +
3108 sizeof (struct ip6_hdr)) {
3109 tcp_hc_updatemtu(&inc, mtu);
3110 tcp_mtudisc(inp, mtu);
3111 ICMP6STAT_INC(icp6s_pmtuchg);
3112 }
3113 } else
3114 inp = (*notify)(inp,
3115 inet6ctlerrmap[cmd]);
3116 }
3117 }
3118 } else {
3119 bzero(&inc, sizeof(inc));
3120 inc.inc_fibnum = M_GETFIB(m);
3121 inc.inc_flags |= INC_ISIPV6;
3122 inc.inc_fport = t_ports.th_dport;
3123 inc.inc_lport = t_ports.th_sport;
3124 inc.inc6_faddr = *dst;
3125 inc.inc6_laddr = ip6->ip6_src;
3126 syncache_unreach(&inc, icmp_tcp_seq, port);
3127 }
3128 out:
3129 if (inp != NULL)
3130 INP_WUNLOCK(inp);
3131 }
3132
3133 void
tcp6_ctlinput(int cmd,struct sockaddr * sa,void * d)3134 tcp6_ctlinput(int cmd, struct sockaddr *sa, void *d)
3135 {
3136 tcp6_ctlinput_with_port(cmd, sa, d, htons(0));
3137 }
3138
3139 void
tcp6_ctlinput_viaudp(int cmd,struct sockaddr * sa,void * d,void * unused)3140 tcp6_ctlinput_viaudp(int cmd, struct sockaddr *sa, void *d, void *unused)
3141 {
3142 struct ip6ctlparam *ip6cp;
3143 struct mbuf *m;
3144 struct udphdr *udp;
3145 uint16_t port;
3146
3147 ip6cp = (struct ip6ctlparam *)d;
3148 m = m_pulldown(ip6cp->ip6c_m, ip6cp->ip6c_off, sizeof(struct udphdr), NULL);
3149 if (m == NULL) {
3150 return;
3151 }
3152 udp = mtod(m, struct udphdr *);
3153 if (ntohs(udp->uh_sport) != V_tcp_udp_tunneling_port) {
3154 return;
3155 }
3156 port = udp->uh_dport;
3157 m_adj(m, sizeof(struct udphdr));
3158 if ((m->m_flags & M_PKTHDR) == 0) {
3159 ip6cp->ip6c_m->m_pkthdr.len -= sizeof(struct udphdr);
3160 }
3161 /* Now call in to the normal handling code */
3162 tcp6_ctlinput_with_port(cmd, sa, d, port);
3163 }
3164
3165 #endif /* INET6 */
3166
3167 static uint32_t
tcp_keyed_hash(struct in_conninfo * inc,u_char * key,u_int len)3168 tcp_keyed_hash(struct in_conninfo *inc, u_char *key, u_int len)
3169 {
3170 SIPHASH_CTX ctx;
3171 uint32_t hash[2];
3172
3173 KASSERT(len >= SIPHASH_KEY_LENGTH,
3174 ("%s: keylen %u too short ", __func__, len));
3175 SipHash24_Init(&ctx);
3176 SipHash_SetKey(&ctx, (uint8_t *)key);
3177 SipHash_Update(&ctx, &inc->inc_fport, sizeof(uint16_t));
3178 SipHash_Update(&ctx, &inc->inc_lport, sizeof(uint16_t));
3179 switch (inc->inc_flags & INC_ISIPV6) {
3180 #ifdef INET
3181 case 0:
3182 SipHash_Update(&ctx, &inc->inc_faddr, sizeof(struct in_addr));
3183 SipHash_Update(&ctx, &inc->inc_laddr, sizeof(struct in_addr));
3184 break;
3185 #endif
3186 #ifdef INET6
3187 case INC_ISIPV6:
3188 SipHash_Update(&ctx, &inc->inc6_faddr, sizeof(struct in6_addr));
3189 SipHash_Update(&ctx, &inc->inc6_laddr, sizeof(struct in6_addr));
3190 break;
3191 #endif
3192 }
3193 SipHash_Final((uint8_t *)hash, &ctx);
3194
3195 return (hash[0] ^ hash[1]);
3196 }
3197
3198 uint32_t
tcp_new_ts_offset(struct in_conninfo * inc)3199 tcp_new_ts_offset(struct in_conninfo *inc)
3200 {
3201 struct in_conninfo inc_store, *local_inc;
3202
3203 if (!V_tcp_ts_offset_per_conn) {
3204 memcpy(&inc_store, inc, sizeof(struct in_conninfo));
3205 inc_store.inc_lport = 0;
3206 inc_store.inc_fport = 0;
3207 local_inc = &inc_store;
3208 } else {
3209 local_inc = inc;
3210 }
3211 return (tcp_keyed_hash(local_inc, V_ts_offset_secret,
3212 sizeof(V_ts_offset_secret)));
3213 }
3214
3215 /*
3216 * Following is where TCP initial sequence number generation occurs.
3217 *
3218 * There are two places where we must use initial sequence numbers:
3219 * 1. In SYN-ACK packets.
3220 * 2. In SYN packets.
3221 *
3222 * All ISNs for SYN-ACK packets are generated by the syncache. See
3223 * tcp_syncache.c for details.
3224 *
3225 * The ISNs in SYN packets must be monotonic; TIME_WAIT recycling
3226 * depends on this property. In addition, these ISNs should be
3227 * unguessable so as to prevent connection hijacking. To satisfy
3228 * the requirements of this situation, the algorithm outlined in
3229 * RFC 1948 is used, with only small modifications.
3230 *
3231 * Implementation details:
3232 *
3233 * Time is based off the system timer, and is corrected so that it
3234 * increases by one megabyte per second. This allows for proper
3235 * recycling on high speed LANs while still leaving over an hour
3236 * before rollover.
3237 *
3238 * As reading the *exact* system time is too expensive to be done
3239 * whenever setting up a TCP connection, we increment the time
3240 * offset in two ways. First, a small random positive increment
3241 * is added to isn_offset for each connection that is set up.
3242 * Second, the function tcp_isn_tick fires once per clock tick
3243 * and increments isn_offset as necessary so that sequence numbers
3244 * are incremented at approximately ISN_BYTES_PER_SECOND. The
3245 * random positive increments serve only to ensure that the same
3246 * exact sequence number is never sent out twice (as could otherwise
3247 * happen when a port is recycled in less than the system tick
3248 * interval.)
3249 *
3250 * net.inet.tcp.isn_reseed_interval controls the number of seconds
3251 * between seeding of isn_secret. This is normally set to zero,
3252 * as reseeding should not be necessary.
3253 *
3254 * Locking of the global variables isn_secret, isn_last_reseed, isn_offset,
3255 * isn_offset_old, and isn_ctx is performed using the ISN lock. In
3256 * general, this means holding an exclusive (write) lock.
3257 */
3258
3259 #define ISN_BYTES_PER_SECOND 1048576
3260 #define ISN_STATIC_INCREMENT 4096
3261 #define ISN_RANDOM_INCREMENT (4096 - 1)
3262 #define ISN_SECRET_LENGTH SIPHASH_KEY_LENGTH
3263
3264 VNET_DEFINE_STATIC(u_char, isn_secret[ISN_SECRET_LENGTH]);
3265 VNET_DEFINE_STATIC(int, isn_last);
3266 VNET_DEFINE_STATIC(int, isn_last_reseed);
3267 VNET_DEFINE_STATIC(u_int32_t, isn_offset);
3268 VNET_DEFINE_STATIC(u_int32_t, isn_offset_old);
3269
3270 #define V_isn_secret VNET(isn_secret)
3271 #define V_isn_last VNET(isn_last)
3272 #define V_isn_last_reseed VNET(isn_last_reseed)
3273 #define V_isn_offset VNET(isn_offset)
3274 #define V_isn_offset_old VNET(isn_offset_old)
3275
3276 tcp_seq
tcp_new_isn(struct in_conninfo * inc)3277 tcp_new_isn(struct in_conninfo *inc)
3278 {
3279 tcp_seq new_isn;
3280 u_int32_t projected_offset;
3281
3282 ISN_LOCK();
3283 /* Seed if this is the first use, reseed if requested. */
3284 if ((V_isn_last_reseed == 0) || ((V_tcp_isn_reseed_interval > 0) &&
3285 (((u_int)V_isn_last_reseed + (u_int)V_tcp_isn_reseed_interval*hz)
3286 < (u_int)ticks))) {
3287 arc4rand(&V_isn_secret, sizeof(V_isn_secret), 0);
3288 V_isn_last_reseed = ticks;
3289 }
3290
3291 /* Compute the hash and return the ISN. */
3292 new_isn = (tcp_seq)tcp_keyed_hash(inc, V_isn_secret,
3293 sizeof(V_isn_secret));
3294 V_isn_offset += ISN_STATIC_INCREMENT +
3295 (arc4random() & ISN_RANDOM_INCREMENT);
3296 if (ticks != V_isn_last) {
3297 projected_offset = V_isn_offset_old +
3298 ISN_BYTES_PER_SECOND / hz * (ticks - V_isn_last);
3299 if (SEQ_GT(projected_offset, V_isn_offset))
3300 V_isn_offset = projected_offset;
3301 V_isn_offset_old = V_isn_offset;
3302 V_isn_last = ticks;
3303 }
3304 new_isn += V_isn_offset;
3305 ISN_UNLOCK();
3306 return (new_isn);
3307 }
3308
3309 /*
3310 * When a specific ICMP unreachable message is received and the
3311 * connection state is SYN-SENT, drop the connection. This behavior
3312 * is controlled by the icmp_may_rst sysctl.
3313 */
3314 struct inpcb *
tcp_drop_syn_sent(struct inpcb * inp,int errno)3315 tcp_drop_syn_sent(struct inpcb *inp, int errno)
3316 {
3317 struct tcpcb *tp;
3318
3319 NET_EPOCH_ASSERT();
3320 INP_WLOCK_ASSERT(inp);
3321
3322 if ((inp->inp_flags & INP_TIMEWAIT) ||
3323 (inp->inp_flags & INP_DROPPED))
3324 return (inp);
3325
3326 tp = intotcpcb(inp);
3327 if (tp->t_state != TCPS_SYN_SENT)
3328 return (inp);
3329
3330 if (IS_FASTOPEN(tp->t_flags))
3331 tcp_fastopen_disable_path(tp);
3332
3333 tp = tcp_drop(tp, errno);
3334 if (tp != NULL)
3335 return (inp);
3336 else
3337 return (NULL);
3338 }
3339
3340 /*
3341 * When `need fragmentation' ICMP is received, update our idea of the MSS
3342 * based on the new value. Also nudge TCP to send something, since we
3343 * know the packet we just sent was dropped.
3344 * This duplicates some code in the tcp_mss() function in tcp_input.c.
3345 */
3346 static struct inpcb *
tcp_mtudisc_notify(struct inpcb * inp,int error)3347 tcp_mtudisc_notify(struct inpcb *inp, int error)
3348 {
3349
3350 tcp_mtudisc(inp, -1);
3351 return (inp);
3352 }
3353
3354 static void
tcp_mtudisc(struct inpcb * inp,int mtuoffer)3355 tcp_mtudisc(struct inpcb *inp, int mtuoffer)
3356 {
3357 struct tcpcb *tp;
3358 struct socket *so;
3359
3360 INP_WLOCK_ASSERT(inp);
3361 if ((inp->inp_flags & INP_TIMEWAIT) ||
3362 (inp->inp_flags & INP_DROPPED))
3363 return;
3364
3365 tp = intotcpcb(inp);
3366 KASSERT(tp != NULL, ("tcp_mtudisc: tp == NULL"));
3367
3368 tcp_mss_update(tp, -1, mtuoffer, NULL, NULL);
3369
3370 so = inp->inp_socket;
3371 SOCKBUF_LOCK(&so->so_snd);
3372 /* If the mss is larger than the socket buffer, decrease the mss. */
3373 if (so->so_snd.sb_hiwat < tp->t_maxseg)
3374 tp->t_maxseg = so->so_snd.sb_hiwat;
3375 SOCKBUF_UNLOCK(&so->so_snd);
3376
3377 TCPSTAT_INC(tcps_mturesent);
3378 tp->t_rtttime = 0;
3379 tp->snd_nxt = tp->snd_una;
3380 tcp_free_sackholes(tp);
3381 tp->snd_recover = tp->snd_max;
3382 if (tp->t_flags & TF_SACK_PERMIT)
3383 EXIT_FASTRECOVERY(tp->t_flags);
3384 if (tp->t_fb->tfb_tcp_mtu_chg != NULL) {
3385 /*
3386 * Conceptually the snd_nxt setting
3387 * and freeing sack holes should
3388 * be done by the default stacks
3389 * own tfb_tcp_mtu_chg().
3390 */
3391 tp->t_fb->tfb_tcp_mtu_chg(tp);
3392 }
3393 tp->t_fb->tfb_tcp_output(tp);
3394 }
3395
3396 #ifdef INET
3397 /*
3398 * Look-up the routing entry to the peer of this inpcb. If no route
3399 * is found and it cannot be allocated, then return 0. This routine
3400 * is called by TCP routines that access the rmx structure and by
3401 * tcp_mss_update to get the peer/interface MTU.
3402 */
3403 uint32_t
tcp_maxmtu(struct in_conninfo * inc,struct tcp_ifcap * cap)3404 tcp_maxmtu(struct in_conninfo *inc, struct tcp_ifcap *cap)
3405 {
3406 struct nhop_object *nh;
3407 struct ifnet *ifp;
3408 uint32_t maxmtu = 0;
3409
3410 KASSERT(inc != NULL, ("tcp_maxmtu with NULL in_conninfo pointer"));
3411
3412 if (inc->inc_faddr.s_addr != INADDR_ANY) {
3413 nh = fib4_lookup(inc->inc_fibnum, inc->inc_faddr, 0, NHR_NONE, 0);
3414 if (nh == NULL)
3415 return (0);
3416
3417 ifp = nh->nh_ifp;
3418 maxmtu = nh->nh_mtu;
3419
3420 /* Report additional interface capabilities. */
3421 if (cap != NULL) {
3422 if (ifp->if_capenable & IFCAP_TSO4 &&
3423 ifp->if_hwassist & CSUM_TSO) {
3424 cap->ifcap |= CSUM_TSO;
3425 cap->tsomax = ifp->if_hw_tsomax;
3426 cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount;
3427 cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize;
3428 }
3429 }
3430 }
3431 return (maxmtu);
3432 }
3433 #endif /* INET */
3434
3435 #ifdef INET6
3436 uint32_t
tcp_maxmtu6(struct in_conninfo * inc,struct tcp_ifcap * cap)3437 tcp_maxmtu6(struct in_conninfo *inc, struct tcp_ifcap *cap)
3438 {
3439 struct nhop_object *nh;
3440 struct in6_addr dst6;
3441 uint32_t scopeid;
3442 struct ifnet *ifp;
3443 uint32_t maxmtu = 0;
3444
3445 KASSERT(inc != NULL, ("tcp_maxmtu6 with NULL in_conninfo pointer"));
3446
3447 if (inc->inc_flags & INC_IPV6MINMTU)
3448 return (IPV6_MMTU);
3449
3450 if (!IN6_IS_ADDR_UNSPECIFIED(&inc->inc6_faddr)) {
3451 in6_splitscope(&inc->inc6_faddr, &dst6, &scopeid);
3452 nh = fib6_lookup(inc->inc_fibnum, &dst6, scopeid, NHR_NONE, 0);
3453 if (nh == NULL)
3454 return (0);
3455
3456 ifp = nh->nh_ifp;
3457 maxmtu = nh->nh_mtu;
3458
3459 /* Report additional interface capabilities. */
3460 if (cap != NULL) {
3461 if (ifp->if_capenable & IFCAP_TSO6 &&
3462 ifp->if_hwassist & CSUM_TSO) {
3463 cap->ifcap |= CSUM_TSO;
3464 cap->tsomax = ifp->if_hw_tsomax;
3465 cap->tsomaxsegcount = ifp->if_hw_tsomaxsegcount;
3466 cap->tsomaxsegsize = ifp->if_hw_tsomaxsegsize;
3467 }
3468 }
3469 }
3470
3471 return (maxmtu);
3472 }
3473 #endif /* INET6 */
3474
3475 /*
3476 * Calculate effective SMSS per RFC5681 definition for a given TCP
3477 * connection at its current state, taking into account SACK and etc.
3478 */
3479 u_int
tcp_maxseg(const struct tcpcb * tp)3480 tcp_maxseg(const struct tcpcb *tp)
3481 {
3482 u_int optlen;
3483
3484 if (tp->t_flags & TF_NOOPT)
3485 return (tp->t_maxseg);
3486
3487 /*
3488 * Here we have a simplified code from tcp_addoptions(),
3489 * without a proper loop, and having most of paddings hardcoded.
3490 * We might make mistakes with padding here in some edge cases,
3491 * but this is harmless, since result of tcp_maxseg() is used
3492 * only in cwnd and ssthresh estimations.
3493 */
3494 if (TCPS_HAVEESTABLISHED(tp->t_state)) {
3495 if (tp->t_flags & TF_RCVD_TSTMP)
3496 optlen = TCPOLEN_TSTAMP_APPA;
3497 else
3498 optlen = 0;
3499 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3500 if (tp->t_flags & TF_SIGNATURE)
3501 optlen += PADTCPOLEN(TCPOLEN_SIGNATURE);
3502 #endif
3503 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks > 0) {
3504 optlen += TCPOLEN_SACKHDR;
3505 optlen += tp->rcv_numsacks * TCPOLEN_SACK;
3506 optlen = PADTCPOLEN(optlen);
3507 }
3508 } else {
3509 if (tp->t_flags & TF_REQ_TSTMP)
3510 optlen = TCPOLEN_TSTAMP_APPA;
3511 else
3512 optlen = PADTCPOLEN(TCPOLEN_MAXSEG);
3513 if (tp->t_flags & TF_REQ_SCALE)
3514 optlen += PADTCPOLEN(TCPOLEN_WINDOW);
3515 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3516 if (tp->t_flags & TF_SIGNATURE)
3517 optlen += PADTCPOLEN(TCPOLEN_SIGNATURE);
3518 #endif
3519 if (tp->t_flags & TF_SACK_PERMIT)
3520 optlen += PADTCPOLEN(TCPOLEN_SACK_PERMITTED);
3521 }
3522 #undef PAD
3523 optlen = min(optlen, TCP_MAXOLEN);
3524 return (tp->t_maxseg - optlen);
3525 }
3526
3527
3528 u_int
tcp_fixed_maxseg(const struct tcpcb * tp)3529 tcp_fixed_maxseg(const struct tcpcb *tp)
3530 {
3531 int optlen;
3532
3533 if (tp->t_flags & TF_NOOPT)
3534 return (tp->t_maxseg);
3535
3536 /*
3537 * Here we have a simplified code from tcp_addoptions(),
3538 * without a proper loop, and having most of paddings hardcoded.
3539 * We only consider fixed options that we would send every
3540 * time I.e. SACK is not considered. This is important
3541 * for cc modules to figure out what the modulo of the
3542 * cwnd should be.
3543 */
3544 #define PAD(len) ((((len) / 4) + !!((len) % 4)) * 4)
3545 if (TCPS_HAVEESTABLISHED(tp->t_state)) {
3546 if (tp->t_flags & TF_RCVD_TSTMP)
3547 optlen = TCPOLEN_TSTAMP_APPA;
3548 else
3549 optlen = 0;
3550 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3551 if (tp->t_flags & TF_SIGNATURE)
3552 optlen += PAD(TCPOLEN_SIGNATURE);
3553 #endif
3554 } else {
3555 if (tp->t_flags & TF_REQ_TSTMP)
3556 optlen = TCPOLEN_TSTAMP_APPA;
3557 else
3558 optlen = PAD(TCPOLEN_MAXSEG);
3559 if (tp->t_flags & TF_REQ_SCALE)
3560 optlen += PAD(TCPOLEN_WINDOW);
3561 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
3562 if (tp->t_flags & TF_SIGNATURE)
3563 optlen += PAD(TCPOLEN_SIGNATURE);
3564 #endif
3565 if (tp->t_flags & TF_SACK_PERMIT)
3566 optlen += PAD(TCPOLEN_SACK_PERMITTED);
3567 }
3568 #undef PAD
3569 optlen = min(optlen, TCP_MAXOLEN);
3570 return (tp->t_maxseg - optlen);
3571 }
3572
3573
3574
3575 static int
sysctl_drop(SYSCTL_HANDLER_ARGS)3576 sysctl_drop(SYSCTL_HANDLER_ARGS)
3577 {
3578 /* addrs[0] is a foreign socket, addrs[1] is a local one. */
3579 struct sockaddr_storage addrs[2];
3580 struct inpcb *inp;
3581 struct tcpcb *tp;
3582 struct tcptw *tw;
3583 struct sockaddr_in *fin, *lin;
3584 struct epoch_tracker et;
3585 #ifdef INET6
3586 struct sockaddr_in6 *fin6, *lin6;
3587 #endif
3588 int error;
3589
3590 inp = NULL;
3591 fin = lin = NULL;
3592 #ifdef INET6
3593 fin6 = lin6 = NULL;
3594 #endif
3595 error = 0;
3596
3597 if (req->oldptr != NULL || req->oldlen != 0)
3598 return (EINVAL);
3599 if (req->newptr == NULL)
3600 return (EPERM);
3601 if (req->newlen < sizeof(addrs))
3602 return (ENOMEM);
3603 error = SYSCTL_IN(req, &addrs, sizeof(addrs));
3604 if (error)
3605 return (error);
3606
3607 switch (addrs[0].ss_family) {
3608 #ifdef INET6
3609 case AF_INET6:
3610 fin6 = (struct sockaddr_in6 *)&addrs[0];
3611 lin6 = (struct sockaddr_in6 *)&addrs[1];
3612 if (fin6->sin6_len != sizeof(struct sockaddr_in6) ||
3613 lin6->sin6_len != sizeof(struct sockaddr_in6))
3614 return (EINVAL);
3615 if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) {
3616 if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr))
3617 return (EINVAL);
3618 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]);
3619 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]);
3620 fin = (struct sockaddr_in *)&addrs[0];
3621 lin = (struct sockaddr_in *)&addrs[1];
3622 break;
3623 }
3624 error = sa6_embedscope(fin6, V_ip6_use_defzone);
3625 if (error)
3626 return (error);
3627 error = sa6_embedscope(lin6, V_ip6_use_defzone);
3628 if (error)
3629 return (error);
3630 break;
3631 #endif
3632 #ifdef INET
3633 case AF_INET:
3634 fin = (struct sockaddr_in *)&addrs[0];
3635 lin = (struct sockaddr_in *)&addrs[1];
3636 if (fin->sin_len != sizeof(struct sockaddr_in) ||
3637 lin->sin_len != sizeof(struct sockaddr_in))
3638 return (EINVAL);
3639 break;
3640 #endif
3641 default:
3642 return (EINVAL);
3643 }
3644 NET_EPOCH_ENTER(et);
3645 switch (addrs[0].ss_family) {
3646 #ifdef INET6
3647 case AF_INET6:
3648 inp = in6_pcblookup(&V_tcbinfo, &fin6->sin6_addr,
3649 fin6->sin6_port, &lin6->sin6_addr, lin6->sin6_port,
3650 INPLOOKUP_WLOCKPCB, NULL);
3651 break;
3652 #endif
3653 #ifdef INET
3654 case AF_INET:
3655 inp = in_pcblookup(&V_tcbinfo, fin->sin_addr, fin->sin_port,
3656 lin->sin_addr, lin->sin_port, INPLOOKUP_WLOCKPCB, NULL);
3657 break;
3658 #endif
3659 }
3660 if (inp != NULL) {
3661 if (inp->inp_flags & INP_TIMEWAIT) {
3662 /*
3663 * XXXRW: There currently exists a state where an
3664 * inpcb is present, but its timewait state has been
3665 * discarded. For now, don't allow dropping of this
3666 * type of inpcb.
3667 */
3668 tw = intotw(inp);
3669 if (tw != NULL)
3670 tcp_twclose(tw, 0);
3671 else
3672 INP_WUNLOCK(inp);
3673 } else if ((inp->inp_flags & INP_DROPPED) == 0 &&
3674 !SOLISTENING(inp->inp_socket)) {
3675 tp = intotcpcb(inp);
3676 tp = tcp_drop(tp, ECONNABORTED);
3677 if (tp != NULL)
3678 INP_WUNLOCK(inp);
3679 } else
3680 INP_WUNLOCK(inp);
3681 } else
3682 error = ESRCH;
3683 NET_EPOCH_EXIT(et);
3684 return (error);
3685 }
3686
3687 SYSCTL_PROC(_net_inet_tcp, TCPCTL_DROP, drop,
3688 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
3689 CTLFLAG_NEEDGIANT, NULL, 0, sysctl_drop, "",
3690 "Drop TCP connection");
3691
3692 #ifdef KERN_TLS
3693 static int
sysctl_switch_tls(SYSCTL_HANDLER_ARGS)3694 sysctl_switch_tls(SYSCTL_HANDLER_ARGS)
3695 {
3696 /* addrs[0] is a foreign socket, addrs[1] is a local one. */
3697 struct sockaddr_storage addrs[2];
3698 struct inpcb *inp;
3699 struct sockaddr_in *fin, *lin;
3700 struct epoch_tracker et;
3701 #ifdef INET6
3702 struct sockaddr_in6 *fin6, *lin6;
3703 #endif
3704 int error;
3705
3706 inp = NULL;
3707 fin = lin = NULL;
3708 #ifdef INET6
3709 fin6 = lin6 = NULL;
3710 #endif
3711 error = 0;
3712
3713 if (req->oldptr != NULL || req->oldlen != 0)
3714 return (EINVAL);
3715 if (req->newptr == NULL)
3716 return (EPERM);
3717 if (req->newlen < sizeof(addrs))
3718 return (ENOMEM);
3719 error = SYSCTL_IN(req, &addrs, sizeof(addrs));
3720 if (error)
3721 return (error);
3722
3723 switch (addrs[0].ss_family) {
3724 #ifdef INET6
3725 case AF_INET6:
3726 fin6 = (struct sockaddr_in6 *)&addrs[0];
3727 lin6 = (struct sockaddr_in6 *)&addrs[1];
3728 if (fin6->sin6_len != sizeof(struct sockaddr_in6) ||
3729 lin6->sin6_len != sizeof(struct sockaddr_in6))
3730 return (EINVAL);
3731 if (IN6_IS_ADDR_V4MAPPED(&fin6->sin6_addr)) {
3732 if (!IN6_IS_ADDR_V4MAPPED(&lin6->sin6_addr))
3733 return (EINVAL);
3734 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[0]);
3735 in6_sin6_2_sin_in_sock((struct sockaddr *)&addrs[1]);
3736 fin = (struct sockaddr_in *)&addrs[0];
3737 lin = (struct sockaddr_in *)&addrs[1];
3738 break;
3739 }
3740 error = sa6_embedscope(fin6, V_ip6_use_defzone);
3741 if (error)
3742 return (error);
3743 error = sa6_embedscope(lin6, V_ip6_use_defzone);
3744 if (error)
3745 return (error);
3746 break;
3747 #endif
3748 #ifdef INET
3749 case AF_INET:
3750 fin = (struct sockaddr_in *)&addrs[0];
3751 lin = (struct sockaddr_in *)&addrs[1];
3752 if (fin->sin_len != sizeof(struct sockaddr_in) ||
3753 lin->sin_len != sizeof(struct sockaddr_in))
3754 return (EINVAL);
3755 break;
3756 #endif
3757 default:
3758 return (EINVAL);
3759 }
3760 NET_EPOCH_ENTER(et);
3761 switch (addrs[0].ss_family) {
3762 #ifdef INET6
3763 case AF_INET6:
3764 inp = in6_pcblookup(&V_tcbinfo, &fin6->sin6_addr,
3765 fin6->sin6_port, &lin6->sin6_addr, lin6->sin6_port,
3766 INPLOOKUP_WLOCKPCB, NULL);
3767 break;
3768 #endif
3769 #ifdef INET
3770 case AF_INET:
3771 inp = in_pcblookup(&V_tcbinfo, fin->sin_addr, fin->sin_port,
3772 lin->sin_addr, lin->sin_port, INPLOOKUP_WLOCKPCB, NULL);
3773 break;
3774 #endif
3775 }
3776 NET_EPOCH_EXIT(et);
3777 if (inp != NULL) {
3778 if ((inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) != 0 ||
3779 inp->inp_socket == NULL) {
3780 error = ECONNRESET;
3781 INP_WUNLOCK(inp);
3782 } else {
3783 struct socket *so;
3784
3785 so = inp->inp_socket;
3786 soref(so);
3787 error = ktls_set_tx_mode(so,
3788 arg2 == 0 ? TCP_TLS_MODE_SW : TCP_TLS_MODE_IFNET);
3789 INP_WUNLOCK(inp);
3790 SOCK_LOCK(so);
3791 sorele(so);
3792 }
3793 } else
3794 error = ESRCH;
3795 return (error);
3796 }
3797
3798 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, switch_to_sw_tls,
3799 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
3800 CTLFLAG_NEEDGIANT, NULL, 0, sysctl_switch_tls, "",
3801 "Switch TCP connection to SW TLS");
3802 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, switch_to_ifnet_tls,
3803 CTLFLAG_VNET | CTLTYPE_STRUCT | CTLFLAG_WR | CTLFLAG_SKIP |
3804 CTLFLAG_NEEDGIANT, NULL, 1, sysctl_switch_tls, "",
3805 "Switch TCP connection to ifnet TLS");
3806 #endif
3807
3808 /*
3809 * Generate a standardized TCP log line for use throughout the
3810 * tcp subsystem. Memory allocation is done with M_NOWAIT to
3811 * allow use in the interrupt context.
3812 *
3813 * NB: The caller MUST free(s, M_TCPLOG) the returned string.
3814 * NB: The function may return NULL if memory allocation failed.
3815 *
3816 * Due to header inclusion and ordering limitations the struct ip
3817 * and ip6_hdr pointers have to be passed as void pointers.
3818 */
3819 char *
tcp_log_vain(struct in_conninfo * inc,struct tcphdr * th,void * ip4hdr,const void * ip6hdr)3820 tcp_log_vain(struct in_conninfo *inc, struct tcphdr *th, void *ip4hdr,
3821 const void *ip6hdr)
3822 {
3823
3824 /* Is logging enabled? */
3825 if (V_tcp_log_in_vain == 0)
3826 return (NULL);
3827
3828 return (tcp_log_addr(inc, th, ip4hdr, ip6hdr));
3829 }
3830
3831 char *
tcp_log_addrs(struct in_conninfo * inc,struct tcphdr * th,void * ip4hdr,const void * ip6hdr)3832 tcp_log_addrs(struct in_conninfo *inc, struct tcphdr *th, void *ip4hdr,
3833 const void *ip6hdr)
3834 {
3835
3836 /* Is logging enabled? */
3837 if (tcp_log_debug == 0)
3838 return (NULL);
3839
3840 return (tcp_log_addr(inc, th, ip4hdr, ip6hdr));
3841 }
3842
3843 static char *
tcp_log_addr(struct in_conninfo * inc,struct tcphdr * th,void * ip4hdr,const void * ip6hdr)3844 tcp_log_addr(struct in_conninfo *inc, struct tcphdr *th, void *ip4hdr,
3845 const void *ip6hdr)
3846 {
3847 char *s, *sp;
3848 size_t size;
3849 struct ip *ip;
3850 #ifdef INET6
3851 const struct ip6_hdr *ip6;
3852
3853 ip6 = (const struct ip6_hdr *)ip6hdr;
3854 #endif /* INET6 */
3855 ip = (struct ip *)ip4hdr;
3856
3857 /*
3858 * The log line looks like this:
3859 * "TCP: [1.2.3.4]:50332 to [1.2.3.4]:80 tcpflags 0x2<SYN>"
3860 */
3861 size = sizeof("TCP: []:12345 to []:12345 tcpflags 0x2<>") +
3862 sizeof(PRINT_TH_FLAGS) + 1 +
3863 #ifdef INET6
3864 2 * INET6_ADDRSTRLEN;
3865 #else
3866 2 * INET_ADDRSTRLEN;
3867 #endif /* INET6 */
3868
3869 s = malloc(size, M_TCPLOG, M_ZERO|M_NOWAIT);
3870 if (s == NULL)
3871 return (NULL);
3872
3873 strcat(s, "TCP: [");
3874 sp = s + strlen(s);
3875
3876 if (inc && ((inc->inc_flags & INC_ISIPV6) == 0)) {
3877 inet_ntoa_r(inc->inc_faddr, sp);
3878 sp = s + strlen(s);
3879 sprintf(sp, "]:%i to [", ntohs(inc->inc_fport));
3880 sp = s + strlen(s);
3881 inet_ntoa_r(inc->inc_laddr, sp);
3882 sp = s + strlen(s);
3883 sprintf(sp, "]:%i", ntohs(inc->inc_lport));
3884 #ifdef INET6
3885 } else if (inc) {
3886 ip6_sprintf(sp, &inc->inc6_faddr);
3887 sp = s + strlen(s);
3888 sprintf(sp, "]:%i to [", ntohs(inc->inc_fport));
3889 sp = s + strlen(s);
3890 ip6_sprintf(sp, &inc->inc6_laddr);
3891 sp = s + strlen(s);
3892 sprintf(sp, "]:%i", ntohs(inc->inc_lport));
3893 } else if (ip6 && th) {
3894 ip6_sprintf(sp, &ip6->ip6_src);
3895 sp = s + strlen(s);
3896 sprintf(sp, "]:%i to [", ntohs(th->th_sport));
3897 sp = s + strlen(s);
3898 ip6_sprintf(sp, &ip6->ip6_dst);
3899 sp = s + strlen(s);
3900 sprintf(sp, "]:%i", ntohs(th->th_dport));
3901 #endif /* INET6 */
3902 #ifdef INET
3903 } else if (ip && th) {
3904 inet_ntoa_r(ip->ip_src, sp);
3905 sp = s + strlen(s);
3906 sprintf(sp, "]:%i to [", ntohs(th->th_sport));
3907 sp = s + strlen(s);
3908 inet_ntoa_r(ip->ip_dst, sp);
3909 sp = s + strlen(s);
3910 sprintf(sp, "]:%i", ntohs(th->th_dport));
3911 #endif /* INET */
3912 } else {
3913 free(s, M_TCPLOG);
3914 return (NULL);
3915 }
3916 sp = s + strlen(s);
3917 if (th)
3918 sprintf(sp, " tcpflags 0x%b", th->th_flags, PRINT_TH_FLAGS);
3919 if (*(s + size - 1) != '\0')
3920 panic("%s: string too long", __func__);
3921 return (s);
3922 }
3923
3924 /*
3925 * A subroutine which makes it easy to track TCP state changes with DTrace.
3926 * This function shouldn't be called for t_state initializations that don't
3927 * correspond to actual TCP state transitions.
3928 */
3929 void
tcp_state_change(struct tcpcb * tp,int newstate)3930 tcp_state_change(struct tcpcb *tp, int newstate)
3931 {
3932 #if defined(KDTRACE_HOOKS)
3933 int pstate = tp->t_state;
3934 #endif
3935
3936 TCPSTATES_DEC(tp->t_state);
3937 TCPSTATES_INC(newstate);
3938 tp->t_state = newstate;
3939 TCP_PROBE6(state__change, NULL, tp, NULL, tp, NULL, pstate);
3940 }
3941
3942 /*
3943 * Create an external-format (``xtcpcb'') structure using the information in
3944 * the kernel-format tcpcb structure pointed to by tp. This is done to
3945 * reduce the spew of irrelevant information over this interface, to isolate
3946 * user code from changes in the kernel structure, and potentially to provide
3947 * information-hiding if we decide that some of this information should be
3948 * hidden from users.
3949 */
3950 void
tcp_inptoxtp(const struct inpcb * inp,struct xtcpcb * xt)3951 tcp_inptoxtp(const struct inpcb *inp, struct xtcpcb *xt)
3952 {
3953 struct tcpcb *tp = intotcpcb(inp);
3954 struct tcptw *tw = intotw(inp);
3955 sbintime_t now;
3956
3957 bzero(xt, sizeof(*xt));
3958 if (inp->inp_flags & INP_TIMEWAIT) {
3959 xt->t_state = TCPS_TIME_WAIT;
3960 xt->xt_encaps_port = tw->t_port;
3961 } else {
3962 xt->t_state = tp->t_state;
3963 xt->t_logstate = tp->t_logstate;
3964 xt->t_flags = tp->t_flags;
3965 xt->t_sndzerowin = tp->t_sndzerowin;
3966 xt->t_sndrexmitpack = tp->t_sndrexmitpack;
3967 xt->t_rcvoopack = tp->t_rcvoopack;
3968 xt->t_rcv_wnd = tp->rcv_wnd;
3969 xt->t_snd_wnd = tp->snd_wnd;
3970 xt->t_snd_cwnd = tp->snd_cwnd;
3971 xt->t_snd_ssthresh = tp->snd_ssthresh;
3972 xt->t_maxseg = tp->t_maxseg;
3973 xt->xt_ecn = (tp->t_flags2 & TF2_ECN_PERMIT) ? 1 : 0 +
3974 (tp->t_flags2 & TF2_ACE_PERMIT) ? 2 : 0;
3975
3976 now = getsbinuptime();
3977 #define COPYTIMER(ttt) do { \
3978 if (callout_active(&tp->t_timers->ttt)) \
3979 xt->ttt = (tp->t_timers->ttt.c_time - now) / \
3980 SBT_1MS; \
3981 else \
3982 xt->ttt = 0; \
3983 } while (0)
3984 COPYTIMER(tt_delack);
3985 COPYTIMER(tt_rexmt);
3986 COPYTIMER(tt_persist);
3987 COPYTIMER(tt_keep);
3988 COPYTIMER(tt_2msl);
3989 #undef COPYTIMER
3990 xt->t_rcvtime = 1000 * (ticks - tp->t_rcvtime) / hz;
3991
3992 xt->xt_encaps_port = tp->t_port;
3993 bcopy(tp->t_fb->tfb_tcp_block_name, xt->xt_stack,
3994 TCP_FUNCTION_NAME_LEN_MAX);
3995 bcopy(CC_ALGO(tp)->name, xt->xt_cc,
3996 TCP_CA_NAME_MAX);
3997 #ifdef TCP_BLACKBOX
3998 (void)tcp_log_get_id(tp, xt->xt_logid);
3999 #endif
4000 }
4001
4002 xt->xt_len = sizeof(struct xtcpcb);
4003 in_pcbtoxinpcb(inp, &xt->xt_inp);
4004 if (inp->inp_socket == NULL)
4005 xt->xt_inp.xi_socket.xso_protocol = IPPROTO_TCP;
4006 }
4007
4008 void
tcp_log_end_status(struct tcpcb * tp,uint8_t status)4009 tcp_log_end_status(struct tcpcb *tp, uint8_t status)
4010 {
4011 uint32_t bit, i;
4012
4013 if ((tp == NULL) ||
4014 (status > TCP_EI_STATUS_MAX_VALUE) ||
4015 (status == 0)) {
4016 /* Invalid */
4017 return;
4018 }
4019 if (status > (sizeof(uint32_t) * 8)) {
4020 /* Should this be a KASSERT? */
4021 return;
4022 }
4023 bit = 1U << (status - 1);
4024 if (bit & tp->t_end_info_status) {
4025 /* already logged */
4026 return;
4027 }
4028 for (i = 0; i < TCP_END_BYTE_INFO; i++) {
4029 if (tp->t_end_info_bytes[i] == TCP_EI_EMPTY_SLOT) {
4030 tp->t_end_info_bytes[i] = status;
4031 tp->t_end_info_status |= bit;
4032 break;
4033 }
4034 }
4035 }
4036
4037 int
tcp_can_enable_pacing(void)4038 tcp_can_enable_pacing(void)
4039 {
4040
4041 if ((tcp_pacing_limit == -1) ||
4042 (tcp_pacing_limit > number_of_tcp_connections_pacing)) {
4043 atomic_fetchadd_int(&number_of_tcp_connections_pacing, 1);
4044 shadow_num_connections = number_of_tcp_connections_pacing;
4045 return (1);
4046 } else {
4047 return (0);
4048 }
4049 }
4050
4051 static uint8_t tcp_pacing_warning = 0;
4052
4053 void
tcp_decrement_paced_conn(void)4054 tcp_decrement_paced_conn(void)
4055 {
4056 uint32_t ret;
4057
4058 ret = atomic_fetchadd_int(&number_of_tcp_connections_pacing, -1);
4059 shadow_num_connections = number_of_tcp_connections_pacing;
4060 KASSERT(ret != 0, ("tcp_paced_connection_exits -1 would cause wrap?"));
4061 if (ret == 0) {
4062 if (tcp_pacing_limit != -1) {
4063 printf("Warning all pacing is now disabled, count decrements invalidly!\n");
4064 tcp_pacing_limit = 0;
4065 } else if (tcp_pacing_warning == 0) {
4066 printf("Warning pacing count is invalid, invalid decrement\n");
4067 tcp_pacing_warning = 1;
4068 }
4069 }
4070 }
4071