]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/tcp_stacks/rack_bbr_common.c
Retain only mutually supported TCP options after simultaneous SYN
[FreeBSD/FreeBSD.git] / sys / netinet / tcp_stacks / rack_bbr_common.c
1 /*-
2  * Copyright (c) 2016-2020 Netflix, Inc.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  *
25  */
26 /*
27  * Author: Randall Stewart <rrs@netflix.com>
28  * This work is based on the ACM Queue paper
29  * BBR - Congestion Based Congestion Control
30  * and also numerous discussions with Neal, Yuchung and Van.
31  */
32
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35
36 #include "opt_inet.h"
37 #include "opt_inet6.h"
38 #include "opt_ipsec.h"
39 #include "opt_tcpdebug.h"
40 #include "opt_ratelimit.h"
41 #include "opt_kern_tls.h"
42 #include <sys/param.h>
43 #include <sys/arb.h>
44 #include <sys/module.h>
45 #include <sys/kernel.h>
46 #ifdef TCP_HHOOK
47 #include <sys/hhook.h>
48 #endif
49 #include <sys/malloc.h>
50 #include <sys/mbuf.h>
51 #include <sys/proc.h>
52 #include <sys/qmath.h>
53 #include <sys/socket.h>
54 #include <sys/socketvar.h>
55 #ifdef KERN_TLS
56 #include <sys/ktls.h>
57 #endif
58 #include <sys/sysctl.h>
59 #include <sys/systm.h>
60 #include <sys/tree.h>
61 #ifdef NETFLIX_STATS
62 #include <sys/stats.h> /* Must come after qmath.h and tree.h */
63 #endif
64 #include <sys/refcount.h>
65 #include <sys/queue.h>
66 #include <sys/smp.h>
67 #include <sys/kthread.h>
68 #include <sys/lock.h>
69 #include <sys/mutex.h>
70 #include <sys/tim_filter.h>
71 #include <sys/time.h>
72 #include <vm/uma.h>
73 #include <sys/kern_prefetch.h>
74
75 #include <net/route.h>
76 #include <net/vnet.h>
77 #include <net/ethernet.h>
78 #include <net/bpf.h>
79
80 #define TCPSTATES               /* for logging */
81
82 #include <netinet/in.h>
83 #include <netinet/in_kdtrace.h>
84 #include <netinet/in_pcb.h>
85 #include <netinet/ip.h>
86 #include <netinet/ip_icmp.h>    /* required for icmp_var.h */
87 #include <netinet/icmp_var.h>   /* for ICMP_BANDLIM */
88 #include <netinet/ip_var.h>
89 #include <netinet/ip6.h>
90 #include <netinet6/in6_pcb.h>
91 #include <netinet6/ip6_var.h>
92 #include <netinet/tcp.h>
93 #include <netinet/tcp_fsm.h>
94 #include <netinet/tcp_seq.h>
95 #include <netinet/tcp_timer.h>
96 #include <netinet/tcp_var.h>
97 #include <netinet/tcpip.h>
98 #include <netinet/tcp_hpts.h>
99 #include <netinet/cc/cc.h>
100 #include <netinet/tcp_log_buf.h>
101 #ifdef TCPDEBUG
102 #include <netinet/tcp_debug.h>
103 #endif                          /* TCPDEBUG */
104 #ifdef TCP_OFFLOAD
105 #include <netinet/tcp_offload.h>
106 #endif
107 #ifdef INET6
108 #include <netinet6/tcp6_var.h>
109 #endif
110 #include <netinet/tcp_fastopen.h>
111
112 #include <netipsec/ipsec_support.h>
113 #include <net/if.h>
114 #include <net/if_var.h>
115
116 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
117 #include <netipsec/ipsec.h>
118 #include <netipsec/ipsec6.h>
119 #endif                          /* IPSEC */
120
121 #include <netinet/udp.h>
122 #include <netinet/udp_var.h>
123 #include <machine/in_cksum.h>
124
125 #ifdef MAC
126 #include <security/mac/mac_framework.h>
127 #endif
128 #include "rack_bbr_common.h"
129
130 /*
131  * Common TCP Functions - These are shared by borth
132  * rack and BBR.
133  */
134 #ifdef KERN_TLS
135 uint32_t
136 ctf_get_opt_tls_size(struct socket *so, uint32_t rwnd)
137 {
138         struct ktls_session *tls;
139         uint32_t len;
140
141 again:
142         tls = so->so_snd.sb_tls_info;
143         len = tls->params.max_frame_len;         /* max tls payload */
144         len += tls->params.tls_hlen;      /* tls header len  */
145         len += tls->params.tls_tlen;      /* tls trailer len */
146         if ((len * 4) > rwnd) {
147                 /*
148                  * Stroke this will suck counter and what
149                  * else should we do Drew? From the
150                  * TCP perspective I am not sure
151                  * what should be done...
152                  */
153                 if (tls->params.max_frame_len > 4096) {
154                         tls->params.max_frame_len -= 4096;
155                         if (tls->params.max_frame_len < 4096)
156                                 tls->params.max_frame_len = 4096;
157                         goto again;
158                 }
159         }
160         return (len);
161 }
162 #endif
163
164
165 /*
166  * The function ctf_process_inbound_raw() is used by
167  * transport developers to do the steps needed to
168  * support MBUF Queuing i.e. the flags in
169  * inp->inp_flags2:
170  *
171  * - INP_SUPPORTS_MBUFQ
172  * - INP_MBUF_QUEUE_READY
173  * - INP_DONT_SACK_QUEUE
174  *
175  * These flags help control how LRO will deliver
176  * packets to the transport. You first set in inp_flags2
177  * the INP_SUPPORTS_MBUFQ to tell the LRO code that you
178  * will gladly take a queue of packets instead of a compressed
179  * single packet. You also set in your t_fb pointer the
180  * tfb_do_queued_segments to point to ctf_process_inbound_raw.
181  *
182  * This then gets you lists of inbound ACK's/Data instead
183  * of a condensed compressed ACK/DATA packet. Why would you
184  * want that? This will get you access to all the arrival
185  * times of at least LRO and possibly at the Hardware (if
186  * the interface card supports that) of the actual ACK/DATA.
187  * In some transport designs this is important since knowing
188  * the actual time we got the packet is useful information.
189  *
190  * Now there are some interesting Caveats that the transport
191  * designer needs to take into account when using this feature.
192  *
193  * 1) It is used with HPTS and pacing, when the pacing timer
194  *    for output calls it will first call the input.
195  * 2) When you set INP_MBUF_QUEUE_READY this tells LRO
196  *    queue normal packets, I am busy pacing out data and
197  *    will process the queued packets before my tfb_tcp_output
198  *    call from pacing. If a non-normal packet arrives, (e.g. sack)
199  *    you will be awoken immediately.
200  * 3) Finally you can add the INP_DONT_SACK_QUEUE to not even
201  *    be awoken if a SACK has arrived. You would do this when
202  *    you were not only running a pacing for output timer
203  *    but a Rack timer as well i.e. you know you are in recovery
204  *    and are in the process (via the timers) of dealing with
205  *    the loss.
206  *
207  * Now a critical thing you must be aware of here is that the
208  * use of the flags has a far greater scope then just your
209  * typical LRO. Why? Well thats because in the normal compressed
210  * LRO case at the end of a driver interupt all packets are going
211  * to get presented to the transport no matter if there is one
212  * or 100. With the MBUF_QUEUE model, this is not true. You will
213  * only be awoken to process the queue of packets when:
214  *     a) The flags discussed above allow it.
215  *          <or>
216  *     b) You exceed a ack or data limit (by default the
217  *        ack limit is infinity (64k acks) and the data
218  *        limit is 64k of new TCP data)
219  *         <or>
220  *     c) The push bit has been set by the peer
221  */
222
223 int
224 ctf_process_inbound_raw(struct tcpcb *tp, struct socket *so, struct mbuf *m, int has_pkt)
225 {
226         /*
227          * We are passed a raw change of mbuf packets
228          * that arrived in LRO. They are linked via
229          * the m_nextpkt link in the pkt-headers.
230          *
231          * We process each one by:
232          * a) saving off the next
233          * b) stripping off the ether-header
234          * c) formulating the arguments for
235          *    the tfb_tcp_hpts_do_segment
236          * d) calling each mbuf to tfb_tcp_hpts_do_segment
237          *    after adjusting the time to match the arrival time.
238          * Note that the LRO code assures no IP options are present.
239          *
240          * The symantics for calling tfb_tcp_hpts_do_segment are the
241          * following:
242          * 1) It returns 0 if all went well and you (the caller) need
243          *    to release the lock.
244          * 2) If nxt_pkt is set, then the function will surpress calls
245          *    to tfb_tcp_output() since you are promising to call again
246          *    with another packet.
247          * 3) If it returns 1, then you must free all the packets being
248          *    shipped in, the tcb has been destroyed (or about to be destroyed).
249          */
250         struct mbuf *m_save;
251         struct ether_header *eh;
252         struct tcphdr *th;
253 #ifdef INET6
254         struct ip6_hdr *ip6 = NULL;     /* Keep compiler happy. */
255 #endif
256 #ifdef INET
257         struct ip *ip = NULL;           /* Keep compiler happy. */
258 #endif
259         struct ifnet *ifp;
260         struct timeval tv;
261         int32_t retval, nxt_pkt, tlen, off;
262         uint16_t etype;
263         uint16_t drop_hdrlen;
264         uint8_t iptos, no_vn=0, bpf_req=0;
265
266         NET_EPOCH_ASSERT();
267
268         if (m && m->m_pkthdr.rcvif)
269                 ifp = m->m_pkthdr.rcvif;
270         else
271                 ifp = NULL;
272         if (ifp) {
273                 bpf_req = bpf_peers_present(ifp->if_bpf);
274         } else  {
275                 /*
276                  * We probably should not work around
277                  * but kassert, since lro alwasy sets rcvif.
278                  */
279                 no_vn = 1;
280                 goto skip_vnet;
281         }
282         CURVNET_SET(ifp->if_vnet);
283 skip_vnet:
284         while (m) {
285                 m_save = m->m_nextpkt;
286                 m->m_nextpkt = NULL;
287                 /* Now lets get the ether header */
288                 eh = mtod(m, struct ether_header *);
289                 etype = ntohs(eh->ether_type);
290                 /* Let the BPF see the packet */
291                 if (bpf_req && ifp)
292                         ETHER_BPF_MTAP(ifp, m);
293                 m_adj(m,  sizeof(*eh));
294                 /* Trim off the ethernet header */
295                 switch (etype) {
296 #ifdef INET6
297                 case ETHERTYPE_IPV6:
298                 {
299                         if (m->m_len < (sizeof(*ip6) + sizeof(*th))) {
300                                 m = m_pullup(m, sizeof(*ip6) + sizeof(*th));
301                                 if (m == NULL) {
302                                         KMOD_TCPSTAT_INC(tcps_rcvshort);
303                                         m_freem(m);
304                                         goto skipped_pkt;
305                                 }
306                         }
307                         ip6 = (struct ip6_hdr *)(eh + 1);
308                         th = (struct tcphdr *)(ip6 + 1);
309                         tlen = ntohs(ip6->ip6_plen);
310                         drop_hdrlen = sizeof(*ip6);
311                         if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID_IPV6) {
312                                 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
313                                         th->th_sum = m->m_pkthdr.csum_data;
314                                 else
315                                         th->th_sum = in6_cksum_pseudo(ip6, tlen,
316                                                                       IPPROTO_TCP, m->m_pkthdr.csum_data);
317                                 th->th_sum ^= 0xffff;
318                         } else
319                                 th->th_sum = in6_cksum(m, IPPROTO_TCP, drop_hdrlen, tlen);
320                         if (th->th_sum) {
321                                 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
322                                 m_freem(m);
323                                 goto skipped_pkt;
324                         }
325                         /*
326                          * Be proactive about unspecified IPv6 address in source.
327                          * As we use all-zero to indicate unbounded/unconnected pcb,
328                          * unspecified IPv6 address can be used to confuse us.
329                          *
330                          * Note that packets with unspecified IPv6 destination is
331                          * already dropped in ip6_input.
332                          */
333                         if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
334                                 /* XXX stat */
335                                 m_freem(m);
336                                 goto skipped_pkt;
337                         }
338                         iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
339                         break;
340                 }
341 #endif
342 #ifdef INET
343                 case ETHERTYPE_IP:
344                 {
345                         if (m->m_len < sizeof (struct tcpiphdr)) {
346                                 if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
347                                     == NULL) {
348                                         KMOD_TCPSTAT_INC(tcps_rcvshort);
349                                         m_freem(m);
350                                         goto skipped_pkt;
351                                 }
352                         }
353                         ip = (struct ip *)(eh + 1);
354                         th = (struct tcphdr *)(ip + 1);
355                         drop_hdrlen = sizeof(*ip);
356                         iptos = ip->ip_tos;
357                         tlen = ntohs(ip->ip_len) - sizeof(struct ip);
358                         if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
359                                 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
360                                         th->th_sum = m->m_pkthdr.csum_data;
361                                 else
362                                         th->th_sum = in_pseudo(ip->ip_src.s_addr,
363                                                                ip->ip_dst.s_addr,
364                                                                htonl(m->m_pkthdr.csum_data + tlen +
365                                                                      IPPROTO_TCP));
366                                 th->th_sum ^= 0xffff;
367                         } else {
368                                 int len;
369                                 struct ipovly *ipov = (struct ipovly *)ip;
370                                 /*
371                                  * Checksum extended TCP header and data.
372                                  */
373                                 len = drop_hdrlen + tlen;
374                                 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
375                                 ipov->ih_len = htons(tlen);
376                                 th->th_sum = in_cksum(m, len);
377                                 /* Reset length for SDT probes. */
378                                 ip->ip_len = htons(len);
379                                 /* Reset TOS bits */
380                                 ip->ip_tos = iptos;
381                                 /* Re-initialization for later version check */
382                                 ip->ip_v = IPVERSION;
383                                 ip->ip_hl = sizeof(*ip) >> 2;
384                         }
385                         if (th->th_sum) {
386                                 KMOD_TCPSTAT_INC(tcps_rcvbadsum);
387                                 m_freem(m);
388                                 goto skipped_pkt;
389                         }
390                         break;
391                 }
392 #endif
393                 }
394                 /*
395                  * Convert TCP protocol specific fields to host format.
396                  */
397                 tcp_fields_to_host(th);
398
399                 off = th->th_off << 2;
400                 if (off < sizeof (struct tcphdr) || off > tlen) {
401                         KMOD_TCPSTAT_INC(tcps_rcvbadoff);
402                                 m_freem(m);
403                                 goto skipped_pkt;
404                 }
405                 tlen -= off;
406                 drop_hdrlen += off;
407                 /*
408                  * Now lets setup the timeval to be when we should
409                  * have been called (if we can).
410                  */
411                 m->m_pkthdr.lro_nsegs = 1;
412                 if (m->m_flags & M_TSTMP_LRO) {
413                         tv.tv_sec = m->m_pkthdr.rcv_tstmp /1000000000;
414                         tv.tv_usec = (m->m_pkthdr.rcv_tstmp % 1000000000)/1000;
415                 } else {
416                         /* Should not be should we kassert instead? */
417                         tcp_get_usecs(&tv);
418                 }
419                 /* Now what about next packet? */
420                 if (m_save || has_pkt)
421                         nxt_pkt = 1;
422                 else
423                         nxt_pkt = 0;
424                 KMOD_TCPSTAT_INC(tcps_rcvtotal);
425                 retval = (*tp->t_fb->tfb_do_segment_nounlock)(m, th, so, tp, drop_hdrlen, tlen,
426                                                               iptos, nxt_pkt, &tv);
427                 if (retval) {
428                         /* We lost the lock and tcb probably */
429                         m = m_save;
430                         while(m) {
431                                 m_save = m->m_nextpkt;
432                                 m->m_nextpkt = NULL;
433                                 m_freem(m);
434                                 m = m_save;
435                         }
436                         if (no_vn == 0)
437                                 CURVNET_RESTORE();
438                         return(retval);
439                 }
440 skipped_pkt:
441                 m = m_save;
442         }
443         if (no_vn == 0)
444                 CURVNET_RESTORE();
445         return(retval);
446 }
447
448 int
449 ctf_do_queued_segments(struct socket *so, struct tcpcb *tp, int have_pkt)
450 {
451         struct mbuf *m;
452
453         /* First lets see if we have old packets */
454         if (tp->t_in_pkt) {
455                 m = tp->t_in_pkt;
456                 tp->t_in_pkt = NULL;
457                 tp->t_tail_pkt = NULL;
458                 if (ctf_process_inbound_raw(tp, so, m, have_pkt)) {
459                         /* We lost the tcpcb (maybe a RST came in)? */
460                         return(1);
461                 }
462         }
463         return (0);
464 }
465
466 uint32_t
467 ctf_outstanding(struct tcpcb *tp)
468 {
469         uint32_t bytes_out;
470
471         bytes_out = tp->snd_max - tp->snd_una;
472         if (tp->t_state < TCPS_ESTABLISHED)
473                 bytes_out++;
474         if (tp->t_flags & TF_SENTFIN)
475                 bytes_out++;
476         return (bytes_out);
477 }
478
479 uint32_t
480 ctf_flight_size(struct tcpcb *tp, uint32_t rc_sacked)
481 {
482         if (rc_sacked <= ctf_outstanding(tp))
483                 return(ctf_outstanding(tp) - rc_sacked);
484         else {
485                 /* TSNH */
486 #ifdef INVARIANTS
487                 panic("tp:%p rc_sacked:%d > out:%d",
488                       tp, rc_sacked, ctf_outstanding(tp));
489 #endif
490                 return (0);
491         }
492 }
493
494 void
495 ctf_do_dropwithreset(struct mbuf *m, struct tcpcb *tp, struct tcphdr *th,
496     int32_t rstreason, int32_t tlen)
497 {
498         if (tp != NULL) {
499                 tcp_dropwithreset(m, th, tp, tlen, rstreason);
500                 INP_WUNLOCK(tp->t_inpcb);
501         } else
502                 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
503 }
504
505 /*
506  * ctf_drop_checks returns 1 for you should not proceed. It places
507  * in ret_val what should be returned 1/0 by the caller. The 1 indicates
508  * that the TCB is unlocked and probably dropped. The 0 indicates the
509  * TCB is still valid and locked.
510  */
511 int
512 ctf_drop_checks(struct tcpopt *to, struct mbuf *m, struct tcphdr *th, struct tcpcb *tp, int32_t * tlenp,  int32_t * thf, int32_t * drop_hdrlen, int32_t * ret_val)
513 {
514         int32_t todrop;
515         int32_t thflags;
516         int32_t tlen;
517
518         thflags = *thf;
519         tlen = *tlenp;
520         todrop = tp->rcv_nxt - th->th_seq;
521         if (todrop > 0) {
522                 if (thflags & TH_SYN) {
523                         thflags &= ~TH_SYN;
524                         th->th_seq++;
525                         if (th->th_urp > 1)
526                                 th->th_urp--;
527                         else
528                                 thflags &= ~TH_URG;
529                         todrop--;
530                 }
531                 /*
532                  * Following if statement from Stevens, vol. 2, p. 960.
533                  */
534                 if (todrop > tlen
535                     || (todrop == tlen && (thflags & TH_FIN) == 0)) {
536                         /*
537                          * Any valid FIN must be to the left of the window.
538                          * At this point the FIN must be a duplicate or out
539                          * of sequence; drop it.
540                          */
541                         thflags &= ~TH_FIN;
542                         /*
543                          * Send an ACK to resynchronize and drop any data.
544                          * But keep on processing for RST or ACK.
545                          */
546                         tp->t_flags |= TF_ACKNOW;
547                         todrop = tlen;
548                         KMOD_TCPSTAT_INC(tcps_rcvduppack);
549                         KMOD_TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
550                 } else {
551                         KMOD_TCPSTAT_INC(tcps_rcvpartduppack);
552                         KMOD_TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
553                 }
554                 /*
555                  * DSACK - add SACK block for dropped range
556                  */
557                 if ((todrop > 0) && (tp->t_flags & TF_SACK_PERMIT)) {
558                         tcp_update_sack_list(tp, th->th_seq,
559                             th->th_seq + todrop);
560                         /*
561                          * ACK now, as the next in-sequence segment
562                          * will clear the DSACK block again
563                          */
564                         tp->t_flags |= TF_ACKNOW;
565                 }
566                 *drop_hdrlen += todrop; /* drop from the top afterwards */
567                 th->th_seq += todrop;
568                 tlen -= todrop;
569                 if (th->th_urp > todrop)
570                         th->th_urp -= todrop;
571                 else {
572                         thflags &= ~TH_URG;
573                         th->th_urp = 0;
574                 }
575         }
576         /*
577          * If segment ends after window, drop trailing data (and PUSH and
578          * FIN); if nothing left, just ACK.
579          */
580         todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
581         if (todrop > 0) {
582                 KMOD_TCPSTAT_INC(tcps_rcvpackafterwin);
583                 if (todrop >= tlen) {
584                         KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
585                         /*
586                          * If window is closed can only take segments at
587                          * window edge, and have to drop data and PUSH from
588                          * incoming segments.  Continue processing, but
589                          * remember to ack.  Otherwise, drop segment and
590                          * ack.
591                          */
592                         if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
593                                 tp->t_flags |= TF_ACKNOW;
594                                 KMOD_TCPSTAT_INC(tcps_rcvwinprobe);
595                         } else {
596                                 ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
597                                 return (1);
598                         }
599                 } else
600                         KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
601                 m_adj(m, -todrop);
602                 tlen -= todrop;
603                 thflags &= ~(TH_PUSH | TH_FIN);
604         }
605         *thf = thflags;
606         *tlenp = tlen;
607         return (0);
608 }
609
610 /*
611  * The value in ret_val informs the caller
612  * if we dropped the tcb (and lock) or not.
613  * 1 = we dropped it, 0 = the TCB is still locked
614  * and valid.
615  */
616 void
617 ctf_do_dropafterack(struct mbuf *m, struct tcpcb *tp, struct tcphdr *th, int32_t thflags, int32_t tlen, int32_t * ret_val)
618 {
619         /*
620          * Generate an ACK dropping incoming segment if it occupies sequence
621          * space, where the ACK reflects our state.
622          *
623          * We can now skip the test for the RST flag since all paths to this
624          * code happen after packets containing RST have been dropped.
625          *
626          * In the SYN-RECEIVED state, don't send an ACK unless the segment
627          * we received passes the SYN-RECEIVED ACK test. If it fails send a
628          * RST.  This breaks the loop in the "LAND" DoS attack, and also
629          * prevents an ACK storm between two listening ports that have been
630          * sent forged SYN segments, each with the source address of the
631          * other.
632          */
633         if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
634             (SEQ_GT(tp->snd_una, th->th_ack) ||
635             SEQ_GT(th->th_ack, tp->snd_max))) {
636                 *ret_val = 1;
637                 ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
638                 return;
639         } else
640                 *ret_val = 0;
641         tp->t_flags |= TF_ACKNOW;
642         if (m)
643                 m_freem(m);
644 }
645
646 void
647 ctf_do_drop(struct mbuf *m, struct tcpcb *tp)
648 {
649
650         /*
651          * Drop space held by incoming segment and return.
652          */
653         if (tp != NULL)
654                 INP_WUNLOCK(tp->t_inpcb);
655         if (m)
656                 m_freem(m);
657 }
658
659 int
660 ctf_process_rst(struct mbuf *m, struct tcphdr *th, struct socket *so, struct tcpcb *tp)
661 {
662         /*
663          * RFC5961 Section 3.2
664          *
665          * - RST drops connection only if SEG.SEQ == RCV.NXT. - If RST is in
666          * window, we send challenge ACK.
667          *
668          * Note: to take into account delayed ACKs, we should test against
669          * last_ack_sent instead of rcv_nxt. Note 2: we handle special case
670          * of closed window, not covered by the RFC.
671          */
672         int dropped = 0;
673
674         if ((SEQ_GEQ(th->th_seq, (tp->last_ack_sent - 1)) &&
675             SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
676             (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
677
678                 KASSERT(tp->t_state != TCPS_SYN_SENT,
679                     ("%s: TH_RST for TCPS_SYN_SENT th %p tp %p",
680                     __func__, th, tp));
681
682                 if (V_tcp_insecure_rst ||
683                     (tp->last_ack_sent == th->th_seq) ||
684                     (tp->rcv_nxt == th->th_seq) ||
685                     ((tp->last_ack_sent - 1) == th->th_seq)) {
686                         KMOD_TCPSTAT_INC(tcps_drops);
687                         /* Drop the connection. */
688                         switch (tp->t_state) {
689                         case TCPS_SYN_RECEIVED:
690                                 so->so_error = ECONNREFUSED;
691                                 goto close;
692                         case TCPS_ESTABLISHED:
693                         case TCPS_FIN_WAIT_1:
694                         case TCPS_FIN_WAIT_2:
695                         case TCPS_CLOSE_WAIT:
696                         case TCPS_CLOSING:
697                         case TCPS_LAST_ACK:
698                                 so->so_error = ECONNRESET;
699                 close:
700                                 tcp_state_change(tp, TCPS_CLOSED);
701                                 /* FALLTHROUGH */
702                         default:
703                                 tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_RST);
704                                 tp = tcp_close(tp);
705                         }
706                         dropped = 1;
707                         ctf_do_drop(m, tp);
708                 } else {
709                         KMOD_TCPSTAT_INC(tcps_badrst);
710                         /* Send challenge ACK. */
711                         tcp_respond(tp, mtod(m, void *), th, m,
712                             tp->rcv_nxt, tp->snd_nxt, TH_ACK);
713                         tp->last_ack_sent = tp->rcv_nxt;
714                 }
715         } else {
716                 m_freem(m);
717         }
718         return (dropped);
719 }
720
721 /*
722  * The value in ret_val informs the caller
723  * if we dropped the tcb (and lock) or not.
724  * 1 = we dropped it, 0 = the TCB is still locked
725  * and valid.
726  */
727 void
728 ctf_challenge_ack(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp, int32_t * ret_val)
729 {
730
731         NET_EPOCH_ASSERT();
732
733         KMOD_TCPSTAT_INC(tcps_badsyn);
734         if (V_tcp_insecure_syn &&
735             SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
736             SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
737                 tp = tcp_drop(tp, ECONNRESET);
738                 *ret_val = 1;
739                 ctf_do_drop(m, tp);
740         } else {
741                 /* Send challenge ACK. */
742                 tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt,
743                     tp->snd_nxt, TH_ACK);
744                 tp->last_ack_sent = tp->rcv_nxt;
745                 m = NULL;
746                 *ret_val = 0;
747                 ctf_do_drop(m, NULL);
748         }
749 }
750
751 /*
752  * bbr_ts_check returns 1 for you should not proceed, the state
753  * machine should return. It places in ret_val what should
754  * be returned 1/0 by the caller (hpts_do_segment). The 1 indicates
755  * that the TCB is unlocked and probably dropped. The 0 indicates the
756  * TCB is still valid and locked.
757  */
758 int
759 ctf_ts_check(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
760     int32_t tlen, int32_t thflags, int32_t * ret_val)
761 {
762
763         if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
764                 /*
765                  * Invalidate ts_recent.  If this segment updates ts_recent,
766                  * the age will be reset later and ts_recent will get a
767                  * valid value.  If it does not, setting ts_recent to zero
768                  * will at least satisfy the requirement that zero be placed
769                  * in the timestamp echo reply when ts_recent isn't valid.
770                  * The age isn't reset until we get a valid ts_recent
771                  * because we don't want out-of-order segments to be dropped
772                  * when ts_recent is old.
773                  */
774                 tp->ts_recent = 0;
775         } else {
776                 KMOD_TCPSTAT_INC(tcps_rcvduppack);
777                 KMOD_TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
778                 KMOD_TCPSTAT_INC(tcps_pawsdrop);
779                 *ret_val = 0;
780                 if (tlen) {
781                         ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
782                 } else {
783                         ctf_do_drop(m, NULL);
784                 }
785                 return (1);
786         }
787         return (0);
788 }
789
790 void
791 ctf_calc_rwin(struct socket *so, struct tcpcb *tp)
792 {
793         int32_t win;
794
795         /*
796          * Calculate amount of space in receive window, and then do TCP
797          * input processing. Receive window is amount of space in rcv queue,
798          * but not less than advertised window.
799          */
800         win = sbspace(&so->so_rcv);
801         if (win < 0)
802                 win = 0;
803         tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
804 }
805
806 void
807 ctf_do_dropwithreset_conn(struct mbuf *m, struct tcpcb *tp, struct tcphdr *th,
808     int32_t rstreason, int32_t tlen)
809 {
810
811         if (tp->t_inpcb) {
812                 tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
813         }
814         tcp_dropwithreset(m, th, tp, tlen, rstreason);
815         INP_WUNLOCK(tp->t_inpcb);
816 }
817
818 uint32_t
819 ctf_fixed_maxseg(struct tcpcb *tp)
820 {
821         int optlen;
822
823         if (tp->t_flags & TF_NOOPT)
824                 return (tp->t_maxseg);
825
826         /*
827          * Here we have a simplified code from tcp_addoptions(),
828          * without a proper loop, and having most of paddings hardcoded.
829          * We only consider fixed options that we would send every
830          * time I.e. SACK is not considered.
831          *
832          */
833 #define PAD(len)        ((((len) / 4) + !!((len) % 4)) * 4)
834         if (TCPS_HAVEESTABLISHED(tp->t_state)) {
835                 if (tp->t_flags & TF_RCVD_TSTMP)
836                         optlen = TCPOLEN_TSTAMP_APPA;
837                 else
838                         optlen = 0;
839 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
840                 if (tp->t_flags & TF_SIGNATURE)
841                         optlen += PAD(TCPOLEN_SIGNATURE);
842 #endif
843         } else {
844                 if (tp->t_flags & TF_REQ_TSTMP)
845                         optlen = TCPOLEN_TSTAMP_APPA;
846                 else
847                         optlen = PAD(TCPOLEN_MAXSEG);
848                 if (tp->t_flags & TF_REQ_SCALE)
849                         optlen += PAD(TCPOLEN_WINDOW);
850 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
851                 if (tp->t_flags & TF_SIGNATURE)
852                         optlen += PAD(TCPOLEN_SIGNATURE);
853 #endif
854                 if (tp->t_flags & TF_SACK_PERMIT)
855                         optlen += PAD(TCPOLEN_SACK_PERMITTED);
856         }
857 #undef PAD
858         optlen = min(optlen, TCP_MAXOLEN);
859         return (tp->t_maxseg - optlen);
860 }
861
862 void
863 ctf_log_sack_filter(struct tcpcb *tp, int num_sack_blks, struct sackblk *sack_blocks)
864 {
865         if (tp->t_logstate != TCP_LOG_STATE_OFF) {
866                 union tcp_log_stackspecific log;
867                 struct timeval tv;
868
869                 memset(&log, 0, sizeof(log));
870                 log.u_bbr.timeStamp = tcp_get_usecs(&tv);
871                 log.u_bbr.flex8 = num_sack_blks;
872                 if (num_sack_blks > 0) {
873                         log.u_bbr.flex1 = sack_blocks[0].start;
874                         log.u_bbr.flex2 = sack_blocks[0].end;
875                 }
876                 if (num_sack_blks > 1) {
877                         log.u_bbr.flex3 = sack_blocks[1].start;
878                         log.u_bbr.flex4 = sack_blocks[1].end;
879                 }
880                 if (num_sack_blks > 2) {
881                         log.u_bbr.flex5 = sack_blocks[2].start;
882                         log.u_bbr.flex6 = sack_blocks[2].end;
883                 }
884                 if (num_sack_blks > 3) {
885                         log.u_bbr.applimited = sack_blocks[3].start;
886                         log.u_bbr.pkts_out = sack_blocks[3].end;
887                 }
888                 TCP_LOG_EVENTP(tp, NULL,
889                     &tp->t_inpcb->inp_socket->so_rcv,
890                     &tp->t_inpcb->inp_socket->so_snd,
891                     TCP_SACK_FILTER_RES, 0,
892                     0, &log, false, &tv);
893         }
894 }
895
896 uint32_t
897 ctf_decay_count(uint32_t count, uint32_t decay)
898 {
899         /*
900          * Given a count, decay it by a set percentage. The
901          * percentage is in thousands i.e. 100% = 1000,
902          * 19.3% = 193.
903          */
904         uint64_t perc_count, decay_per;
905         uint32_t decayed_count;
906         if (decay > 1000) {
907                 /* We don't raise it */
908                 return (count);
909         }
910         perc_count = count;
911         decay_per = decay;
912         perc_count *= decay_per;
913         perc_count /= 1000;
914         /*
915          * So now perc_count holds the
916          * count decay value.
917          */
918         decayed_count = count - (uint32_t)perc_count;
919         return(decayed_count);
920 }
921
922 int32_t
923 ctf_progress_timeout_check(struct tcpcb *tp, bool log)
924 {
925         if (tp->t_maxunacktime && tp->t_acktime && TSTMP_GT(ticks, tp->t_acktime)) {
926                 if ((ticks - tp->t_acktime) >= tp->t_maxunacktime) {
927                         /*
928                          * There is an assumption that the caller
929                          * will drop the connection so we will
930                          * increment the counters here.
931                          */
932                         if (log)
933                                 tcp_log_end_status(tp, TCP_EI_STATUS_PROGRESS);
934 #ifdef NETFLIX_STATS
935                         KMOD_TCPSTAT_INC(tcps_progdrops);
936 #endif
937                         return (1);
938                 }
939         }
940         return (0);
941 }