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