xref: /freebsd/sys/netinet/tcp_stacks/rack_bbr_common.c (revision dbaad75f2834f40bfe74ebe393d2101967052036)
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 tfb_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;
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 			INP_UNLOCK_ASSERT(inp);
514 			return(retval);
515 		}
516 skipped_pkt:
517 		m = m_save;
518 	}
519 	if (no_vn == 0)
520 		CURVNET_RESTORE();
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(tp->t_inpcb);
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(tp->t_inpcb);
760 	if (m)
761 		m_freem(m);
762 }
763 
764 int
765 ctf_process_rst(struct mbuf *m, struct tcphdr *th, struct socket *so, struct tcpcb *tp)
766 {
767 	/*
768 	 * RFC5961 Section 3.2
769 	 *
770 	 * - RST drops connection only if SEG.SEQ == RCV.NXT. - If RST is in
771 	 * window, we send challenge ACK.
772 	 *
773 	 * Note: to take into account delayed ACKs, we should test against
774 	 * last_ack_sent instead of rcv_nxt. Note 2: we handle special case
775 	 * of closed window, not covered by the RFC.
776 	 */
777 	int dropped = 0;
778 
779 	if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
780 	    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
781 	    (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
782 		KASSERT(tp->t_state != TCPS_SYN_SENT,
783 		    ("%s: TH_RST for TCPS_SYN_SENT th %p tp %p",
784 		    __func__, th, tp));
785 
786 		if (V_tcp_insecure_rst ||
787 		    (tp->last_ack_sent == th->th_seq) ||
788 		    (tp->rcv_nxt == th->th_seq)) {
789 			KMOD_TCPSTAT_INC(tcps_drops);
790 			/* Drop the connection. */
791 			switch (tp->t_state) {
792 			case TCPS_SYN_RECEIVED:
793 				so->so_error = ECONNREFUSED;
794 				goto close;
795 			case TCPS_ESTABLISHED:
796 			case TCPS_FIN_WAIT_1:
797 			case TCPS_FIN_WAIT_2:
798 			case TCPS_CLOSE_WAIT:
799 			case TCPS_CLOSING:
800 			case TCPS_LAST_ACK:
801 				so->so_error = ECONNRESET;
802 		close:
803 				tcp_state_change(tp, TCPS_CLOSED);
804 				/* FALLTHROUGH */
805 			default:
806 				tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_RST);
807 				tp = tcp_close(tp);
808 			}
809 			dropped = 1;
810 			ctf_do_drop(m, tp);
811 		} else {
812 			KMOD_TCPSTAT_INC(tcps_badrst);
813 			/* Send challenge ACK. */
814 			tcp_respond(tp, mtod(m, void *), th, m,
815 			    tp->rcv_nxt, tp->snd_nxt, TH_ACK);
816 			tp->last_ack_sent = tp->rcv_nxt;
817 		}
818 	} else {
819 		m_freem(m);
820 	}
821 	return (dropped);
822 }
823 
824 /*
825  * The value in ret_val informs the caller
826  * if we dropped the tcb (and lock) or not.
827  * 1 = we dropped it, 0 = the TCB is still locked
828  * and valid.
829  */
830 void
831 ctf_challenge_ack(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp, int32_t * ret_val)
832 {
833 
834 	NET_EPOCH_ASSERT();
835 
836 	KMOD_TCPSTAT_INC(tcps_badsyn);
837 	if (V_tcp_insecure_syn &&
838 	    SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
839 	    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
840 		tp = tcp_drop(tp, ECONNRESET);
841 		*ret_val = 1;
842 		ctf_do_drop(m, tp);
843 	} else {
844 		/* Send challenge ACK. */
845 		tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt,
846 		    tp->snd_nxt, TH_ACK);
847 		tp->last_ack_sent = tp->rcv_nxt;
848 		m = NULL;
849 		*ret_val = 0;
850 		ctf_do_drop(m, NULL);
851 	}
852 }
853 
854 /*
855  * ctf_ts_check returns 1 for you should not proceed, the state
856  * machine should return. It places in ret_val what should
857  * be returned 1/0 by the caller (hpts_do_segment). The 1 indicates
858  * that the TCB is unlocked and probably dropped. The 0 indicates the
859  * TCB is still valid and locked.
860  */
861 int
862 ctf_ts_check(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
863     int32_t tlen, int32_t thflags, int32_t * ret_val)
864 {
865 
866 	if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
867 		/*
868 		 * Invalidate ts_recent.  If this segment updates ts_recent,
869 		 * the age will be reset later and ts_recent will get a
870 		 * valid value.  If it does not, setting ts_recent to zero
871 		 * will at least satisfy the requirement that zero be placed
872 		 * in the timestamp echo reply when ts_recent isn't valid.
873 		 * The age isn't reset until we get a valid ts_recent
874 		 * because we don't want out-of-order segments to be dropped
875 		 * when ts_recent is old.
876 		 */
877 		tp->ts_recent = 0;
878 	} else {
879 		KMOD_TCPSTAT_INC(tcps_rcvduppack);
880 		KMOD_TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
881 		KMOD_TCPSTAT_INC(tcps_pawsdrop);
882 		*ret_val = 0;
883 		if (tlen) {
884 			ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
885 		} else {
886 			ctf_do_drop(m, NULL);
887 		}
888 		return (1);
889 	}
890 	return (0);
891 }
892 
893 int
894 ctf_ts_check_ac(struct tcpcb *tp, int32_t thflags)
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_INC(tcps_pawsdrop);
912 		return (1);
913 	}
914 	return (0);
915 }
916 
917 
918 
919 void
920 ctf_calc_rwin(struct socket *so, struct tcpcb *tp)
921 {
922 	int32_t win;
923 
924 	/*
925 	 * Calculate amount of space in receive window, and then do TCP
926 	 * input processing. Receive window is amount of space in rcv queue,
927 	 * but not less than advertised window.
928 	 */
929 	win = sbspace(&so->so_rcv);
930 	if (win < 0)
931 		win = 0;
932 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
933 }
934 
935 void
936 ctf_do_dropwithreset_conn(struct mbuf *m, struct tcpcb *tp, struct tcphdr *th,
937     int32_t rstreason, int32_t tlen)
938 {
939 
940 	if (tp->t_inpcb) {
941 		tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
942 	}
943 	tcp_dropwithreset(m, th, tp, tlen, rstreason);
944 	INP_WUNLOCK(tp->t_inpcb);
945 }
946 
947 uint32_t
948 ctf_fixed_maxseg(struct tcpcb *tp)
949 {
950 	return (tcp_fixed_maxseg(tp));
951 }
952 
953 void
954 ctf_log_sack_filter(struct tcpcb *tp, int num_sack_blks, struct sackblk *sack_blocks)
955 {
956 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
957 		union tcp_log_stackspecific log;
958 		struct timeval tv;
959 
960 		memset(&log, 0, sizeof(log));
961 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
962 		log.u_bbr.flex8 = num_sack_blks;
963 		if (num_sack_blks > 0) {
964 			log.u_bbr.flex1 = sack_blocks[0].start;
965 			log.u_bbr.flex2 = sack_blocks[0].end;
966 		}
967 		if (num_sack_blks > 1) {
968 			log.u_bbr.flex3 = sack_blocks[1].start;
969 			log.u_bbr.flex4 = sack_blocks[1].end;
970 		}
971 		if (num_sack_blks > 2) {
972 			log.u_bbr.flex5 = sack_blocks[2].start;
973 			log.u_bbr.flex6 = sack_blocks[2].end;
974 		}
975 		if (num_sack_blks > 3) {
976 			log.u_bbr.applimited = sack_blocks[3].start;
977 			log.u_bbr.pkts_out = sack_blocks[3].end;
978 		}
979 		TCP_LOG_EVENTP(tp, NULL,
980 		    &tp->t_inpcb->inp_socket->so_rcv,
981 		    &tp->t_inpcb->inp_socket->so_snd,
982 		    TCP_SACK_FILTER_RES, 0,
983 		    0, &log, false, &tv);
984 	}
985 }
986 
987 uint32_t
988 ctf_decay_count(uint32_t count, uint32_t decay)
989 {
990 	/*
991 	 * Given a count, decay it by a set percentage. The
992 	 * percentage is in thousands i.e. 100% = 1000,
993 	 * 19.3% = 193.
994 	 */
995 	uint64_t perc_count, decay_per;
996 	uint32_t decayed_count;
997 	if (decay > 1000) {
998 		/* We don't raise it */
999 		return (count);
1000 	}
1001 	perc_count = count;
1002 	decay_per = decay;
1003 	perc_count *= decay_per;
1004 	perc_count /= 1000;
1005 	/*
1006 	 * So now perc_count holds the
1007 	 * count decay value.
1008 	 */
1009 	decayed_count = count - (uint32_t)perc_count;
1010 	return(decayed_count);
1011 }
1012 
1013 int32_t
1014 ctf_progress_timeout_check(struct tcpcb *tp, bool log)
1015 {
1016 	if (tp->t_maxunacktime && tp->t_acktime && TSTMP_GT(ticks, tp->t_acktime)) {
1017 		if ((ticks - tp->t_acktime) >= tp->t_maxunacktime) {
1018 			/*
1019 			 * There is an assumption that the caller
1020 			 * will drop the connection so we will
1021 			 * increment the counters here.
1022 			 */
1023 			if (log)
1024 				tcp_log_end_status(tp, TCP_EI_STATUS_PROGRESS);
1025 #ifdef NETFLIX_STATS
1026 			KMOD_TCPSTAT_INC(tcps_progdrops);
1027 #endif
1028 			return (1);
1029 		}
1030 	}
1031 	return (0);
1032 }
1033