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