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