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