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