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