xref: /freebsd/sys/netinet/tcp_stacks/rack_bbr_common.c (revision 090e9752d7291db0c251a5576892e3bbbaea2479)
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_ratelimit.h"
40 #include <sys/param.h>
41 #include <sys/arb.h>
42 #include <sys/module.h>
43 #include <sys/kernel.h>
44 #ifdef TCP_HHOOK
45 #include <sys/hhook.h>
46 #endif
47 #include <sys/malloc.h>
48 #include <sys/mbuf.h>
49 #include <sys/proc.h>
50 #include <sys/qmath.h>
51 #include <sys/socket.h>
52 #include <sys/socketvar.h>
53 #include <sys/sysctl.h>
54 #include <sys/systm.h>
55 #include <sys/tree.h>
56 #ifdef NETFLIX_STATS
57 #include <sys/stats.h> /* Must come after qmath.h and tree.h */
58 #endif
59 #include <sys/refcount.h>
60 #include <sys/queue.h>
61 #include <sys/smp.h>
62 #include <sys/kthread.h>
63 #include <sys/lock.h>
64 #include <sys/mutex.h>
65 #include <sys/tim_filter.h>
66 #include <sys/time.h>
67 #include <vm/uma.h>
68 #include <sys/kern_prefetch.h>
69 
70 #include <net/route.h>
71 #include <net/vnet.h>
72 #include <net/ethernet.h>
73 #include <net/bpf.h>
74 
75 #define TCPSTATES		/* for logging */
76 
77 #include <netinet/in.h>
78 #include <netinet/in_kdtrace.h>
79 #include <netinet/in_pcb.h>
80 #include <netinet/ip.h>
81 #include <netinet/ip_icmp.h>	/* required for icmp_var.h */
82 #include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
83 #include <netinet/ip_var.h>
84 #include <netinet/ip6.h>
85 #include <netinet6/in6_pcb.h>
86 #include <netinet6/ip6_var.h>
87 #include <netinet/tcp.h>
88 #include <netinet/tcp_fsm.h>
89 #include <netinet/tcp_seq.h>
90 #include <netinet/tcp_timer.h>
91 #include <netinet/tcp_var.h>
92 #include <netinet/tcpip.h>
93 #include <netinet/tcp_ecn.h>
94 #include <netinet/tcp_hpts.h>
95 #include <netinet/tcp_lro.h>
96 #include <netinet/cc/cc.h>
97 #include <netinet/tcp_log_buf.h>
98 #ifdef TCP_OFFLOAD
99 #include <netinet/tcp_offload.h>
100 #endif
101 #ifdef INET6
102 #include <netinet6/tcp6_var.h>
103 #endif
104 #include <netinet/tcp_fastopen.h>
105 
106 #include <netipsec/ipsec_support.h>
107 #include <net/if.h>
108 #include <net/if_var.h>
109 #include <net/if_private.h>
110 
111 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
112 #include <netipsec/ipsec.h>
113 #include <netipsec/ipsec6.h>
114 #endif				/* IPSEC */
115 
116 #include <netinet/udp.h>
117 #include <netinet/udp_var.h>
118 #include <machine/in_cksum.h>
119 
120 #ifdef MAC
121 #include <security/mac/mac_framework.h>
122 #endif
123 #include "rack_bbr_common.h"
124 
125 /*
126  * Common TCP Functions - These are shared by borth
127  * rack and BBR.
128  */
129 static int
130 ctf_get_enet_type(struct ifnet *ifp, struct mbuf *m)
131 {
132 	struct ether_header *eh;
133 #ifdef INET6
134 	struct ip6_hdr *ip6 = NULL;	/* Keep compiler happy. */
135 #endif
136 #ifdef INET
137 	struct ip *ip = NULL;		/* Keep compiler happy. */
138 #endif
139 #if defined(INET) || defined(INET6)
140 	struct tcphdr *th;
141 	int32_t tlen;
142 	uint16_t drop_hdrlen;
143 #endif
144 	uint16_t etype;
145 #ifdef INET
146 	uint8_t iptos;
147 #endif
148 
149 	/* Is it the easy way? */
150 	if (m->m_flags & M_LRO_EHDRSTRP)
151 		return (m->m_pkthdr.lro_etype);
152 	/*
153 	 * Ok this is the old style call, the ethernet header is here.
154 	 * This also means no checksum or BPF were done. This
155 	 * can happen if the race to setup the inp fails and
156 	 * LRO sees no INP at packet input, but by the time
157 	 * we queue the packets an INP gets there. Its rare
158 	 * but it can occur so we will handle it. Note that
159 	 * this means duplicated work but with the rarity of it
160 	 * its not worth worrying about.
161 	 */
162 	/* Let the BPF see the packet */
163 	if (bpf_peers_present(ifp->if_bpf))
164 		ETHER_BPF_MTAP(ifp, m);
165 	/* Now the csum */
166 	eh = mtod(m, struct ether_header *);
167 	etype = ntohs(eh->ether_type);
168 	m_adj(m,  sizeof(*eh));
169 	switch (etype) {
170 #ifdef INET6
171 		case ETHERTYPE_IPV6:
172 		{
173 			if (m->m_len < (sizeof(*ip6) + sizeof(*th))) {
174 				m = m_pullup(m, sizeof(*ip6) + sizeof(*th));
175 				if (m == NULL) {
176 					KMOD_TCPSTAT_INC(tcps_rcvshort);
177 					return (-1);
178 				}
179 			}
180 			ip6 = (struct ip6_hdr *)(eh + 1);
181 			th = (struct tcphdr *)(ip6 + 1);
182 			drop_hdrlen = sizeof(*ip6);
183 			tlen = ntohs(ip6->ip6_plen);
184 			if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID_IPV6) {
185 				if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
186 					th->th_sum = m->m_pkthdr.csum_data;
187 				else
188 					th->th_sum = in6_cksum_pseudo(ip6, tlen,
189 								      IPPROTO_TCP,
190 								      m->m_pkthdr.csum_data);
191 				th->th_sum ^= 0xffff;
192 			} else
193 				th->th_sum = in6_cksum(m, IPPROTO_TCP, drop_hdrlen, tlen);
194 			if (th->th_sum) {
195 				KMOD_TCPSTAT_INC(tcps_rcvbadsum);
196 				m_freem(m);
197 				return (-1);
198 			}
199 			return (etype);
200 		}
201 #endif
202 #ifdef INET
203 		case ETHERTYPE_IP:
204 		{
205 			if (m->m_len < sizeof (struct tcpiphdr)) {
206 				m = m_pullup(m, sizeof (struct tcpiphdr));
207 				if (m == NULL) {
208 					KMOD_TCPSTAT_INC(tcps_rcvshort);
209 					return (-1);
210 				}
211 			}
212 			ip = (struct ip *)(eh + 1);
213 			th = (struct tcphdr *)(ip + 1);
214 			drop_hdrlen = sizeof(*ip);
215 			iptos = ip->ip_tos;
216 			tlen = ntohs(ip->ip_len) - sizeof(struct ip);
217 			if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
218 				if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
219 					th->th_sum = m->m_pkthdr.csum_data;
220 				else
221 					th->th_sum = in_pseudo(ip->ip_src.s_addr,
222 							       ip->ip_dst.s_addr,
223 							       htonl(m->m_pkthdr.csum_data + tlen + IPPROTO_TCP));
224 				th->th_sum ^= 0xffff;
225 			} else {
226 				int len;
227 				struct ipovly *ipov = (struct ipovly *)ip;
228 				/*
229 				 * Checksum extended TCP header and data.
230 				 */
231 				len = drop_hdrlen + tlen;
232 				bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
233 				ipov->ih_len = htons(tlen);
234 				th->th_sum = in_cksum(m, len);
235 				/* Reset length for SDT probes. */
236 				ip->ip_len = htons(len);
237 				/* Reset TOS bits */
238 				ip->ip_tos = iptos;
239 				/* Re-initialization for later version check */
240 				ip->ip_v = IPVERSION;
241 				ip->ip_hl = sizeof(*ip) >> 2;
242 			}
243 			if (th->th_sum) {
244 				KMOD_TCPSTAT_INC(tcps_rcvbadsum);
245 				m_freem(m);
246 				return (-1);
247 			}
248 			break;
249 		}
250 #endif
251 	};
252 	return (etype);
253 }
254 
255 /*
256  * The function ctf_process_inbound_raw() is used by
257  * transport developers to do the steps needed to
258  * support MBUF Queuing i.e. the flags in
259  * inp->inp_flags2:
260  *
261  * - INP_SUPPORTS_MBUFQ
262  * - INP_MBUF_QUEUE_READY
263  * - INP_DONT_SACK_QUEUE
264  * - INP_MBUF_ACKCMP
265  *
266  * These flags help control how LRO will deliver
267  * packets to the transport. You first set in inp_flags2
268  * the INP_SUPPORTS_MBUFQ to tell the LRO code that you
269  * will gladly take a queue of packets instead of a compressed
270  * single packet. You also set in your t_fb pointer the
271  * tfb_do_queued_segments to point to ctf_process_inbound_raw.
272  *
273  * This then gets you lists of inbound ACK's/Data instead
274  * of a condensed compressed ACK/DATA packet. Why would you
275  * want that? This will get you access to all the arrival
276  * times of at least LRO and possibly at the Hardware (if
277  * the interface card supports that) of the actual ACK/DATA.
278  * In some transport designs this is important since knowing
279  * the actual time we got the packet is useful information.
280  *
281  * A new special type of mbuf may also be supported by the transport
282  * if it has set the INP_MBUF_ACKCMP flag. If its set, LRO will
283  * possibly create a M_ACKCMP type mbuf. This is a mbuf with
284  * an array of "acks". One thing also to note is that when this
285  * occurs a subsequent LRO may find at the back of the untouched
286  * mbuf queue chain a M_ACKCMP and append on to it. This means
287  * that until the transport pulls in the mbuf chain queued
288  * for it more ack's may get on the mbufs that were already
289  * delivered. There currently is a limit of 6 acks condensed
290  * into 1 mbuf which means often when this is occuring, we
291  * don't get that effect but it does happen.
292  *
293  * Now there are some interesting Caveats that the transport
294  * designer needs to take into account when using this feature.
295  *
296  * 1) It is used with HPTS and pacing, when the pacing timer
297  *    for output calls it will first call the input.
298  * 2) When you set INP_MBUF_QUEUE_READY this tells LRO
299  *    queue normal packets, I am busy pacing out data and
300  *    will process the queued packets before my tfb_tcp_output
301  *    call from pacing. If a non-normal packet arrives, (e.g. sack)
302  *    you will be awoken immediately.
303  * 3) Finally you can add the INP_DONT_SACK_QUEUE to not even
304  *    be awoken if a SACK has arrived. You would do this when
305  *    you were not only running a pacing for output timer
306  *    but a Rack timer as well i.e. you know you are in recovery
307  *    and are in the process (via the timers) of dealing with
308  *    the loss.
309  *
310  * Now a critical thing you must be aware of here is that the
311  * use of the flags has a far greater scope then just your
312  * typical LRO. Why? Well thats because in the normal compressed
313  * LRO case at the end of a driver interupt all packets are going
314  * to get presented to the transport no matter if there is one
315  * or 100. With the MBUF_QUEUE model, this is not true. You will
316  * only be awoken to process the queue of packets when:
317  *     a) The flags discussed above allow it.
318  *          <or>
319  *     b) You exceed a ack or data limit (by default the
320  *        ack limit is infinity (64k acks) and the data
321  *        limit is 64k of new TCP data)
322  *         <or>
323  *     c) The push bit has been set by the peer
324  */
325 
326 static int
327 ctf_process_inbound_raw(struct tcpcb *tp, struct mbuf *m, int has_pkt)
328 {
329 	/*
330 	 * We are passed a raw change of mbuf packets
331 	 * that arrived in LRO. They are linked via
332 	 * the m_nextpkt link in the pkt-headers.
333 	 *
334 	 * We process each one by:
335 	 * a) saving off the next
336 	 * b) stripping off the ether-header
337 	 * c) formulating the arguments for tfb_do_segment_nounlock()
338 	 * d) calling each mbuf to tfb_do_segment_nounlock()
339 	 *    after adjusting the time to match the arrival time.
340 	 * Note that the LRO code assures no IP options are present.
341 	 *
342 	 * The symantics for calling tfb_do_segment_nounlock() are the
343 	 * following:
344 	 * 1) It returns 0 if all went well and you (the caller) need
345 	 *    to release the lock.
346 	 * 2) If nxt_pkt is set, then the function will surpress calls
347 	 *    to tcp_output() since you are promising to call again
348 	 *    with another packet.
349 	 * 3) If it returns 1, then you must free all the packets being
350 	 *    shipped in, the tcb has been destroyed (or about to be destroyed).
351 	 */
352 	struct mbuf *m_save;
353 	struct tcphdr *th;
354 #ifdef INET6
355 	struct ip6_hdr *ip6 = NULL;	/* Keep compiler happy. */
356 #endif
357 #ifdef INET
358 	struct ip *ip = NULL;		/* Keep compiler happy. */
359 #endif
360 	struct ifnet *ifp;
361 	struct timeval tv;
362 	struct inpcb *inp __diagused;
363 	int32_t retval, nxt_pkt, tlen, off;
364 	int etype = 0;
365 	uint16_t drop_hdrlen;
366 	uint8_t iptos, no_vn=0;
367 
368 	inp = tptoinpcb(tp);
369 	INP_WLOCK_ASSERT(inp);
370 	NET_EPOCH_ASSERT();
371 
372 	if (m)
373 		ifp = m_rcvif(m);
374 	else
375 		ifp = NULL;
376 	if (ifp == NULL) {
377 		/*
378 		 * We probably should not work around
379 		 * but kassert, since lro alwasy sets rcvif.
380 		 */
381 		no_vn = 1;
382 		goto skip_vnet;
383 	}
384 	CURVNET_SET(ifp->if_vnet);
385 skip_vnet:
386 	tcp_get_usecs(&tv);
387 	while (m) {
388 		m_save = m->m_nextpkt;
389 		m->m_nextpkt = NULL;
390 		if ((m->m_flags & M_ACKCMP) == 0) {
391 			/* Now lets get the ether header */
392 			etype = ctf_get_enet_type(ifp, m);
393 			if (etype == -1) {
394 				/* Skip this packet it was freed by checksum */
395 				goto skipped_pkt;
396 			}
397 			KASSERT(((etype == ETHERTYPE_IPV6) || (etype == ETHERTYPE_IP)),
398 				("tp:%p m:%p etype:0x%x -- not IP or IPv6", tp, m, etype));
399 			/* Trim off the ethernet header */
400 			switch (etype) {
401 #ifdef INET6
402 			case ETHERTYPE_IPV6:
403 				ip6 = mtod(m, struct ip6_hdr *);
404 				th = (struct tcphdr *)(ip6 + 1);
405 				tlen = ntohs(ip6->ip6_plen);
406 				drop_hdrlen = sizeof(*ip6);
407 				iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
408 				break;
409 #endif
410 #ifdef INET
411 			case ETHERTYPE_IP:
412 				ip = mtod(m, struct ip *);
413 				th = (struct tcphdr *)(ip + 1);
414 				drop_hdrlen = sizeof(*ip);
415 				iptos = ip->ip_tos;
416 				tlen = ntohs(ip->ip_len) - sizeof(struct ip);
417 				break;
418 #endif
419 			} /* end switch */
420 			/*
421 			 * Convert TCP protocol specific fields to host format.
422 			 */
423 			tcp_fields_to_host(th);
424 			off = th->th_off << 2;
425 			if (off < sizeof (struct tcphdr) || off > tlen) {
426 				printf("off:%d < hdrlen:%zu || > tlen:%u -- dump\n",
427 				       off,
428 				       sizeof(struct tcphdr),
429 				       tlen);
430 				KMOD_TCPSTAT_INC(tcps_rcvbadoff);
431 				m_freem(m);
432 				goto skipped_pkt;
433 			}
434 			tlen -= off;
435 			drop_hdrlen += off;
436 			/*
437 			 * Now lets setup the timeval to be when we should
438 			 * have been called (if we can).
439 			 */
440 			m->m_pkthdr.lro_nsegs = 1;
441 			/* Now what about next packet? */
442 		} else {
443 			/*
444 			 * This mbuf is an array of acks that have
445 			 * been compressed. We assert the inp has
446 			 * the flag set to enable this!
447 			 */
448 			KASSERT((tp->t_flags2 & TF2_MBUF_ACKCMP),
449 			    ("tp:%p no TF2_MBUF_ACKCMP flags?", tp));
450 			tlen = 0;
451 			drop_hdrlen = 0;
452 			th = NULL;
453 			iptos = 0;
454 		}
455 		tcp_get_usecs(&tv);
456 		if (m_save || has_pkt)
457 			nxt_pkt = 1;
458 		else
459 			nxt_pkt = 0;
460 		if ((m->m_flags & M_ACKCMP) == 0)
461 			KMOD_TCPSTAT_INC(tcps_rcvtotal);
462 		else
463 			KMOD_TCPSTAT_ADD(tcps_rcvtotal, (m->m_len / sizeof(struct tcp_ackent)));
464 		retval = (*tp->t_fb->tfb_do_segment_nounlock)(tp, m, th,
465 		    drop_hdrlen, tlen, iptos, nxt_pkt, &tv);
466 		if (retval) {
467 			/* We lost the lock and tcb probably */
468 			m = m_save;
469 			while(m) {
470 				m_save = m->m_nextpkt;
471 				m->m_nextpkt = NULL;
472 				m_freem(m);
473 				m = m_save;
474 			}
475 			if (no_vn == 0) {
476 				CURVNET_RESTORE();
477 			}
478 			INP_UNLOCK_ASSERT(inp);
479 			return(retval);
480 		}
481 skipped_pkt:
482 		m = m_save;
483 	}
484 	if (no_vn == 0) {
485 		CURVNET_RESTORE();
486 	}
487 	return(retval);
488 }
489 
490 int
491 ctf_do_queued_segments(struct tcpcb *tp, int have_pkt)
492 {
493 	struct mbuf *m;
494 
495 	/* First lets see if we have old packets */
496 	if ((m = STAILQ_FIRST(&tp->t_inqueue)) != NULL) {
497 		STAILQ_INIT(&tp->t_inqueue);
498 		if (ctf_process_inbound_raw(tp, m, have_pkt)) {
499 			/* We lost the tcpcb (maybe a RST came in)? */
500 			return(1);
501 		}
502 	}
503 	return (0);
504 }
505 
506 uint32_t
507 ctf_outstanding(struct tcpcb *tp)
508 {
509 	uint32_t bytes_out;
510 
511 	bytes_out = tp->snd_max - tp->snd_una;
512 	if (tp->t_state < TCPS_ESTABLISHED)
513 		bytes_out++;
514 	if (tp->t_flags & TF_SENTFIN)
515 		bytes_out++;
516 	return (bytes_out);
517 }
518 
519 uint32_t
520 ctf_flight_size(struct tcpcb *tp, uint32_t rc_sacked)
521 {
522 	if (rc_sacked <= ctf_outstanding(tp))
523 		return(ctf_outstanding(tp) - rc_sacked);
524 	else {
525 		return (0);
526 	}
527 }
528 
529 void
530 ctf_do_dropwithreset(struct mbuf *m, struct tcpcb *tp, struct tcphdr *th,
531     int32_t rstreason, int32_t tlen)
532 {
533 	if (tp != NULL) {
534 		tcp_dropwithreset(m, th, tp, tlen, rstreason);
535 		INP_WUNLOCK(tptoinpcb(tp));
536 	} else
537 		tcp_dropwithreset(m, th, NULL, tlen, rstreason);
538 }
539 
540 void
541 ctf_ack_war_checks(struct tcpcb *tp, uint32_t *ts, uint32_t *cnt)
542 {
543 	if ((ts != NULL) && (cnt != NULL) &&
544 	    (tcp_ack_war_time_window > 0) &&
545 	    (tcp_ack_war_cnt > 0)) {
546 		/* We are possibly doing ack war prevention */
547 		uint32_t cts;
548 
549 		/*
550 		 * We use a msec tick here which gives us
551 		 * roughly 49 days. We don't need the
552 		 * precision of a microsecond timestamp which
553 		 * would only give us hours.
554 		 */
555 		cts = tcp_ts_getticks();
556 		if (TSTMP_LT((*ts), cts)) {
557 			/* Timestamp is in the past */
558 			*cnt = 0;
559 			*ts = (cts + tcp_ack_war_time_window);
560 		}
561 		if (*cnt < tcp_ack_war_cnt) {
562 			*cnt = (*cnt + 1);
563 			tp->t_flags |= TF_ACKNOW;
564 		} else
565 			tp->t_flags &= ~TF_ACKNOW;
566 	} else
567 		tp->t_flags |= TF_ACKNOW;
568 }
569 
570 /*
571  * ctf_drop_checks returns 1 for you should not proceed. It places
572  * in ret_val what should be returned 1/0 by the caller. The 1 indicates
573  * that the TCB is unlocked and probably dropped. The 0 indicates the
574  * TCB is still valid and locked.
575  */
576 int
577 _ctf_drop_checks(struct tcpopt *to, struct mbuf *m, struct tcphdr *th,
578 		 struct tcpcb *tp, int32_t *tlenp,
579 		 int32_t *thf, int32_t *drop_hdrlen, int32_t *ret_val,
580 		 uint32_t *ts, uint32_t *cnt)
581 {
582 	int32_t todrop;
583 	int32_t thflags;
584 	int32_t tlen;
585 
586 	thflags = *thf;
587 	tlen = *tlenp;
588 	todrop = tp->rcv_nxt - th->th_seq;
589 	if (todrop > 0) {
590 		if (thflags & TH_SYN) {
591 			thflags &= ~TH_SYN;
592 			th->th_seq++;
593 			if (th->th_urp > 1)
594 				th->th_urp--;
595 			else
596 				thflags &= ~TH_URG;
597 			todrop--;
598 		}
599 		/*
600 		 * Following if statement from Stevens, vol. 2, p. 960.
601 		 */
602 		if (todrop > tlen
603 		    || (todrop == tlen && (thflags & TH_FIN) == 0)) {
604 			/*
605 			 * Any valid FIN must be to the left of the window.
606 			 * At this point the FIN must be a duplicate or out
607 			 * of sequence; drop it.
608 			 */
609 			thflags &= ~TH_FIN;
610 			/*
611 			 * Send an ACK to resynchronize and drop any data.
612 			 * But keep on processing for RST or ACK.
613 			 */
614 			ctf_ack_war_checks(tp, ts, cnt);
615 			todrop = tlen;
616 			KMOD_TCPSTAT_INC(tcps_rcvduppack);
617 			KMOD_TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
618 		} else {
619 			KMOD_TCPSTAT_INC(tcps_rcvpartduppack);
620 			KMOD_TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
621 		}
622 		/*
623 		 * DSACK - add SACK block for dropped range
624 		 */
625 		if ((todrop > 0) && (tp->t_flags & TF_SACK_PERMIT)) {
626 			/*
627 			 * ACK now, as the next in-sequence segment
628 			 * will clear the DSACK block again
629 			 */
630 			ctf_ack_war_checks(tp, ts, cnt);
631 			if (tp->t_flags & TF_ACKNOW)
632 				tcp_update_sack_list(tp, th->th_seq,
633 						     th->th_seq + todrop);
634 		}
635 		*drop_hdrlen += todrop;	/* drop from the top afterwards */
636 		th->th_seq += todrop;
637 		tlen -= todrop;
638 		if (th->th_urp > todrop)
639 			th->th_urp -= todrop;
640 		else {
641 			thflags &= ~TH_URG;
642 			th->th_urp = 0;
643 		}
644 	}
645 	/*
646 	 * If segment ends after window, drop trailing data (and PUSH and
647 	 * FIN); if nothing left, just ACK.
648 	 */
649 	todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
650 	if (todrop > 0) {
651 		KMOD_TCPSTAT_INC(tcps_rcvpackafterwin);
652 		if (todrop >= tlen) {
653 			KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
654 			/*
655 			 * If window is closed can only take segments at
656 			 * window edge, and have to drop data and PUSH from
657 			 * incoming segments.  Continue processing, but
658 			 * remember to ack.  Otherwise, drop segment and
659 			 * ack.
660 			 */
661 			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
662 				ctf_ack_war_checks(tp, ts, cnt);
663 				KMOD_TCPSTAT_INC(tcps_rcvwinprobe);
664 			} else {
665 				__ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val, ts, cnt);
666 				return (1);
667 			}
668 		} else
669 			KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
670 		m_adj(m, -todrop);
671 		tlen -= todrop;
672 		thflags &= ~(TH_PUSH | TH_FIN);
673 	}
674 	*thf = thflags;
675 	*tlenp = tlen;
676 	return (0);
677 }
678 
679 /*
680  * The value in ret_val informs the caller
681  * if we dropped the tcb (and lock) or not.
682  * 1 = we dropped it, 0 = the TCB is still locked
683  * and valid.
684  */
685 void
686 __ctf_do_dropafterack(struct mbuf *m, struct tcpcb *tp, struct tcphdr *th, int32_t thflags, int32_t tlen, int32_t *ret_val, uint32_t *ts, uint32_t *cnt)
687 {
688 	/*
689 	 * Generate an ACK dropping incoming segment if it occupies sequence
690 	 * space, where the ACK reflects our state.
691 	 *
692 	 * We can now skip the test for the RST flag since all paths to this
693 	 * code happen after packets containing RST have been dropped.
694 	 *
695 	 * In the SYN-RECEIVED state, don't send an ACK unless the segment
696 	 * we received passes the SYN-RECEIVED ACK test. If it fails send a
697 	 * RST.  This breaks the loop in the "LAND" DoS attack, and also
698 	 * prevents an ACK storm between two listening ports that have been
699 	 * sent forged SYN segments, each with the source address of the
700 	 * other.
701 	 */
702 	if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
703 	    (SEQ_GT(tp->snd_una, th->th_ack) ||
704 	    SEQ_GT(th->th_ack, tp->snd_max))) {
705 		*ret_val = 1;
706 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
707 		return;
708 	} else
709 		*ret_val = 0;
710 	ctf_ack_war_checks(tp, ts, cnt);
711 	if (m)
712 		m_freem(m);
713 }
714 
715 void
716 ctf_do_drop(struct mbuf *m, struct tcpcb *tp)
717 {
718 
719 	/*
720 	 * Drop space held by incoming segment and return.
721 	 */
722 	if (tp != NULL)
723 		INP_WUNLOCK(tptoinpcb(tp));
724 	if (m)
725 		m_freem(m);
726 }
727 
728 int
729 __ctf_process_rst(struct mbuf *m, struct tcphdr *th, struct socket *so,
730 		struct tcpcb *tp, uint32_t *ts, uint32_t *cnt)
731 {
732 	/*
733 	 * RFC5961 Section 3.2
734 	 *
735 	 * - RST drops connection only if SEG.SEQ == RCV.NXT. - If RST is in
736 	 * window, we send challenge ACK.
737 	 *
738 	 * Note: to take into account delayed ACKs, we should test against
739 	 * last_ack_sent instead of rcv_nxt. Note 2: we handle special case
740 	 * of closed window, not covered by the RFC.
741 	 */
742 	int dropped = 0;
743 
744 	if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
745 	    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
746 	    (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
747 		KASSERT(tp->t_state != TCPS_SYN_SENT,
748 		    ("%s: TH_RST for TCPS_SYN_SENT th %p tp %p",
749 		    __func__, th, tp));
750 
751 		if (V_tcp_insecure_rst ||
752 		    (tp->last_ack_sent == th->th_seq) ||
753 		    (tp->rcv_nxt == th->th_seq)) {
754 			KMOD_TCPSTAT_INC(tcps_drops);
755 			/* Drop the connection. */
756 			switch (tp->t_state) {
757 			case TCPS_SYN_RECEIVED:
758 				so->so_error = ECONNREFUSED;
759 				goto close;
760 			case TCPS_ESTABLISHED:
761 			case TCPS_FIN_WAIT_1:
762 			case TCPS_FIN_WAIT_2:
763 			case TCPS_CLOSE_WAIT:
764 			case TCPS_CLOSING:
765 			case TCPS_LAST_ACK:
766 				so->so_error = ECONNRESET;
767 		close:
768 				tcp_state_change(tp, TCPS_CLOSED);
769 				/* FALLTHROUGH */
770 			default:
771 				tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_RST);
772 				tp = tcp_close(tp);
773 			}
774 			dropped = 1;
775 			ctf_do_drop(m, tp);
776 		} else {
777 			int send_challenge;
778 
779 			KMOD_TCPSTAT_INC(tcps_badrst);
780 			if ((ts != NULL) && (cnt != NULL) &&
781 			    (tcp_ack_war_time_window > 0) &&
782 			    (tcp_ack_war_cnt > 0)) {
783 				/* We are possibly preventing an  ack-rst  war prevention */
784 				uint32_t cts;
785 
786 				/*
787 				 * We use a msec tick here which gives us
788 				 * roughly 49 days. We don't need the
789 				 * precision of a microsecond timestamp which
790 				 * would only give us hours.
791 				 */
792 				cts = tcp_ts_getticks();
793 				if (TSTMP_LT((*ts), cts)) {
794 					/* Timestamp is in the past */
795 					*cnt = 0;
796 					*ts = (cts + tcp_ack_war_time_window);
797 				}
798 				if (*cnt < tcp_ack_war_cnt) {
799 					*cnt = (*cnt + 1);
800 					send_challenge = 1;
801 				} else
802 					send_challenge = 0;
803 			} else
804 				send_challenge = 1;
805 			if (send_challenge) {
806 				/* Send challenge ACK. */
807 				tcp_respond(tp, mtod(m, void *), th, m,
808 					    tp->rcv_nxt, tp->snd_nxt, TH_ACK);
809 				tp->last_ack_sent = tp->rcv_nxt;
810 			}
811 		}
812 	} else {
813 		m_freem(m);
814 	}
815 	return (dropped);
816 }
817 
818 /*
819  * The value in ret_val informs the caller
820  * if we dropped the tcb (and lock) or not.
821  * 1 = we dropped it, 0 = the TCB is still locked
822  * and valid.
823  */
824 void
825 ctf_challenge_ack(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp, uint8_t iptos, int32_t * ret_val)
826 {
827 
828 	NET_EPOCH_ASSERT();
829 
830 	KMOD_TCPSTAT_INC(tcps_badsyn);
831 	if (V_tcp_insecure_syn &&
832 	    SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
833 	    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
834 		tp = tcp_drop(tp, ECONNRESET);
835 		*ret_val = 1;
836 		ctf_do_drop(m, tp);
837 	} else {
838 		tcp_ecn_input_syn_sent(tp, tcp_get_flags(th), iptos);
839 		/* Send challenge ACK. */
840 		tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt,
841 		    tp->snd_nxt, TH_ACK);
842 		tp->last_ack_sent = tp->rcv_nxt;
843 		m = NULL;
844 		*ret_val = 0;
845 		ctf_do_drop(m, NULL);
846 	}
847 }
848 
849 /*
850  * ctf_ts_check returns 1 for you should not proceed, the state
851  * machine should return. It places in ret_val what should
852  * be returned 1/0 by the caller (hpts_do_segment). The 1 indicates
853  * that the TCB is unlocked and probably dropped. The 0 indicates the
854  * TCB is still valid and locked.
855  */
856 int
857 ctf_ts_check(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
858     int32_t tlen, int32_t thflags, int32_t * ret_val)
859 {
860 
861 	if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
862 		/*
863 		 * Invalidate ts_recent.  If this segment updates ts_recent,
864 		 * the age will be reset later and ts_recent will get a
865 		 * valid value.  If it does not, setting ts_recent to zero
866 		 * will at least satisfy the requirement that zero be placed
867 		 * in the timestamp echo reply when ts_recent isn't valid.
868 		 * The age isn't reset until we get a valid ts_recent
869 		 * because we don't want out-of-order segments to be dropped
870 		 * when ts_recent is old.
871 		 */
872 		tp->ts_recent = 0;
873 	} else {
874 		KMOD_TCPSTAT_INC(tcps_rcvduppack);
875 		KMOD_TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
876 		KMOD_TCPSTAT_INC(tcps_pawsdrop);
877 		*ret_val = 0;
878 		if (tlen) {
879 			ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
880 		} else {
881 			ctf_do_drop(m, NULL);
882 		}
883 		return (1);
884 	}
885 	return (0);
886 }
887 
888 int
889 ctf_ts_check_ac(struct tcpcb *tp, int32_t thflags)
890 {
891 
892 	if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
893 		/*
894 		 * Invalidate ts_recent.  If this segment updates ts_recent,
895 		 * the age will be reset later and ts_recent will get a
896 		 * valid value.  If it does not, setting ts_recent to zero
897 		 * will at least satisfy the requirement that zero be placed
898 		 * in the timestamp echo reply when ts_recent isn't valid.
899 		 * The age isn't reset until we get a valid ts_recent
900 		 * because we don't want out-of-order segments to be dropped
901 		 * when ts_recent is old.
902 		 */
903 		tp->ts_recent = 0;
904 	} else {
905 		KMOD_TCPSTAT_INC(tcps_rcvduppack);
906 		KMOD_TCPSTAT_INC(tcps_pawsdrop);
907 		return (1);
908 	}
909 	return (0);
910 }
911 
912 
913 
914 void
915 ctf_calc_rwin(struct socket *so, struct tcpcb *tp)
916 {
917 	int32_t win;
918 
919 	/*
920 	 * Calculate amount of space in receive window, and then do TCP
921 	 * input processing. Receive window is amount of space in rcv queue,
922 	 * but not less than advertised window.
923 	 */
924 	win = sbspace(&so->so_rcv);
925 	if (win < 0)
926 		win = 0;
927 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
928 }
929 
930 void
931 ctf_do_dropwithreset_conn(struct mbuf *m, struct tcpcb *tp, struct tcphdr *th,
932     int32_t rstreason, int32_t tlen)
933 {
934 
935 	tcp_dropwithreset(m, th, tp, tlen, rstreason);
936 	tp = tcp_drop(tp, ETIMEDOUT);
937 	if (tp)
938 		INP_WUNLOCK(tptoinpcb(tp));
939 }
940 
941 uint32_t
942 ctf_fixed_maxseg(struct tcpcb *tp)
943 {
944 	return (tcp_fixed_maxseg(tp));
945 }
946 
947 void
948 ctf_log_sack_filter(struct tcpcb *tp, int num_sack_blks, struct sackblk *sack_blocks)
949 {
950 	if (tcp_bblogging_on(tp)) {
951 		union tcp_log_stackspecific log;
952 		struct timeval tv;
953 
954 		memset(&log, 0, sizeof(log));
955 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
956 		log.u_bbr.flex8 = num_sack_blks;
957 		if (num_sack_blks > 0) {
958 			log.u_bbr.flex1 = sack_blocks[0].start;
959 			log.u_bbr.flex2 = sack_blocks[0].end;
960 		}
961 		if (num_sack_blks > 1) {
962 			log.u_bbr.flex3 = sack_blocks[1].start;
963 			log.u_bbr.flex4 = sack_blocks[1].end;
964 		}
965 		if (num_sack_blks > 2) {
966 			log.u_bbr.flex5 = sack_blocks[2].start;
967 			log.u_bbr.flex6 = sack_blocks[2].end;
968 		}
969 		if (num_sack_blks > 3) {
970 			log.u_bbr.applimited = sack_blocks[3].start;
971 			log.u_bbr.pkts_out = sack_blocks[3].end;
972 		}
973 		TCP_LOG_EVENTP(tp, NULL,
974 		    &tptosocket(tp)->so_rcv,
975 		    &tptosocket(tp)->so_snd,
976 		    TCP_SACK_FILTER_RES, 0,
977 		    0, &log, false, &tv);
978 	}
979 }
980 
981 uint32_t
982 ctf_decay_count(uint32_t count, uint32_t decay)
983 {
984 	/*
985 	 * Given a count, decay it by a set percentage. The
986 	 * percentage is in thousands i.e. 100% = 1000,
987 	 * 19.3% = 193.
988 	 */
989 	uint64_t perc_count, decay_per;
990 	uint32_t decayed_count;
991 	if (decay > 1000) {
992 		/* We don't raise it */
993 		return (count);
994 	}
995 	perc_count = count;
996 	decay_per = decay;
997 	perc_count *= decay_per;
998 	perc_count /= 1000;
999 	/*
1000 	 * So now perc_count holds the
1001 	 * count decay value.
1002 	 */
1003 	decayed_count = count - (uint32_t)perc_count;
1004 	return(decayed_count);
1005 }
1006 
1007 int32_t
1008 ctf_progress_timeout_check(struct tcpcb *tp, bool log)
1009 {
1010 	if (tp->t_maxunacktime && tp->t_acktime && TSTMP_GT(ticks, tp->t_acktime)) {
1011 		if ((ticks - tp->t_acktime) >= tp->t_maxunacktime) {
1012 			/*
1013 			 * There is an assumption that the caller
1014 			 * will drop the connection so we will
1015 			 * increment the counters here.
1016 			 */
1017 			if (log)
1018 				tcp_log_end_status(tp, TCP_EI_STATUS_PROGRESS);
1019 #ifdef NETFLIX_STATS
1020 			KMOD_TCPSTAT_INC(tcps_progdrops);
1021 #endif
1022 			return (1);
1023 		}
1024 	}
1025 	return (0);
1026 }
1027