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