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 "opt_kern_tls.h"
41 #include <sys/param.h>
42 #include <sys/arb.h>
43 #include <sys/module.h>
44 #include <sys/kernel.h>
45 #ifdef TCP_HHOOK
46 #include <sys/hhook.h>
47 #endif
48 #include <sys/malloc.h>
49 #include <sys/mbuf.h>
50 #include <sys/proc.h>
51 #include <sys/qmath.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
54 #ifdef KERN_TLS
55 #include <sys/ktls.h>
56 #endif
57 #include <sys/sysctl.h>
58 #include <sys/systm.h>
59 #include <sys/tree.h>
60 #ifdef NETFLIX_STATS
61 #include <sys/stats.h> /* Must come after qmath.h and tree.h */
62 #endif
63 #include <sys/refcount.h>
64 #include <sys/queue.h>
65 #include <sys/smp.h>
66 #include <sys/kthread.h>
67 #include <sys/lock.h>
68 #include <sys/mutex.h>
69 #include <sys/tim_filter.h>
70 #include <sys/time.h>
71 #include <vm/uma.h>
72 #include <sys/kern_prefetch.h>
73 
74 #include <net/route.h>
75 #include <net/vnet.h>
76 #include <net/ethernet.h>
77 #include <net/bpf.h>
78 
79 #define TCPSTATES		/* for logging */
80 
81 #include <netinet/in.h>
82 #include <netinet/in_kdtrace.h>
83 #include <netinet/in_pcb.h>
84 #include <netinet/ip.h>
85 #include <netinet/ip_icmp.h>	/* required for icmp_var.h */
86 #include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
87 #include <netinet/ip_var.h>
88 #include <netinet/ip6.h>
89 #include <netinet6/in6_pcb.h>
90 #include <netinet6/ip6_var.h>
91 #include <netinet/tcp.h>
92 #include <netinet/tcp_fsm.h>
93 #include <netinet/tcp_seq.h>
94 #include <netinet/tcp_timer.h>
95 #include <netinet/tcp_var.h>
96 #include <netinet/tcpip.h>
97 #include <netinet/tcp_ecn.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 TCP_OFFLOAD
103 #include <netinet/tcp_offload.h>
104 #endif
105 #ifdef INET6
106 #include <netinet6/tcp6_var.h>
107 #endif
108 #include <netinet/tcp_fastopen.h>
109 
110 #include <netipsec/ipsec_support.h>
111 #include <net/if.h>
112 #include <net/if_var.h>
113 #include <net/if_private.h>
114 
115 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
116 #include <netipsec/ipsec.h>
117 #include <netipsec/ipsec6.h>
118 #endif				/* IPSEC */
119 
120 #include <netinet/udp.h>
121 #include <netinet/udp_var.h>
122 #include <machine/in_cksum.h>
123 
124 #ifdef MAC
125 #include <security/mac/mac_framework.h>
126 #endif
127 #include "rack_bbr_common.h"
128 
129 /*
130  * Common TCP Functions - These are shared by borth
131  * rack and BBR.
132  */
133 #ifdef KERN_TLS
134 uint32_t
135 ctf_get_opt_tls_size(struct socket *so, uint32_t rwnd)
136 {
137 	struct ktls_session *tls;
138 	uint32_t len;
139 
140 again:
141 	tls = so->so_snd.sb_tls_info;
142 	len = tls->params.max_frame_len;         /* max tls payload */
143 	len += tls->params.tls_hlen;      /* tls header len  */
144 	len += tls->params.tls_tlen;      /* tls trailer len */
145 	if ((len * 4) > rwnd) {
146 		/*
147 		 * Stroke this will suck counter and what
148 		 * else should we do Drew? From the
149 		 * TCP perspective I am not sure
150 		 * what should be done...
151 		 */
152 		if (tls->params.max_frame_len > 4096) {
153 			tls->params.max_frame_len -= 4096;
154 			if (tls->params.max_frame_len < 4096)
155 				tls->params.max_frame_len = 4096;
156 			goto again;
157 		}
158 	}
159 	return (len);
160 }
161 #endif
162 
163 static int
164 ctf_get_enet_type(struct ifnet *ifp, struct mbuf *m)
165 {
166 	struct ether_header *eh;
167 #ifdef INET6
168 	struct ip6_hdr *ip6 = NULL;	/* Keep compiler happy. */
169 #endif
170 #ifdef INET
171 	struct ip *ip = NULL;		/* Keep compiler happy. */
172 #endif
173 #if defined(INET) || defined(INET6)
174 	struct tcphdr *th;
175 	int32_t tlen;
176 	uint16_t drop_hdrlen;
177 #endif
178 	uint16_t etype;
179 #ifdef INET
180 	uint8_t iptos;
181 #endif
182 
183 	/* Is it the easy way? */
184 	if (m->m_flags & M_LRO_EHDRSTRP)
185 		return (m->m_pkthdr.lro_etype);
186 	/*
187 	 * Ok this is the old style call, the ethernet header is here.
188 	 * This also means no checksum or BPF were done. This
189 	 * can happen if the race to setup the inp fails and
190 	 * LRO sees no INP at packet input, but by the time
191 	 * we queue the packets an INP gets there. Its rare
192 	 * but it can occur so we will handle it. Note that
193 	 * this means duplicated work but with the rarity of it
194 	 * its not worth worrying about.
195 	 */
196 	/* Let the BPF see the packet */
197 	if (bpf_peers_present(ifp->if_bpf))
198 		ETHER_BPF_MTAP(ifp, m);
199 	/* Now the csum */
200 	eh = mtod(m, struct ether_header *);
201 	etype = ntohs(eh->ether_type);
202 	m_adj(m,  sizeof(*eh));
203 	switch (etype) {
204 #ifdef INET6
205 		case ETHERTYPE_IPV6:
206 		{
207 			if (m->m_len < (sizeof(*ip6) + sizeof(*th))) {
208 				m = m_pullup(m, sizeof(*ip6) + sizeof(*th));
209 				if (m == NULL) {
210 					KMOD_TCPSTAT_INC(tcps_rcvshort);
211 					return (-1);
212 				}
213 			}
214 			ip6 = (struct ip6_hdr *)(eh + 1);
215 			th = (struct tcphdr *)(ip6 + 1);
216 			drop_hdrlen = sizeof(*ip6);
217 			tlen = ntohs(ip6->ip6_plen);
218 			if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID_IPV6) {
219 				if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
220 					th->th_sum = m->m_pkthdr.csum_data;
221 				else
222 					th->th_sum = in6_cksum_pseudo(ip6, tlen,
223 								      IPPROTO_TCP,
224 								      m->m_pkthdr.csum_data);
225 				th->th_sum ^= 0xffff;
226 			} else
227 				th->th_sum = in6_cksum(m, IPPROTO_TCP, drop_hdrlen, tlen);
228 			if (th->th_sum) {
229 				KMOD_TCPSTAT_INC(tcps_rcvbadsum);
230 				m_freem(m);
231 				return (-1);
232 			}
233 			return (etype);
234 		}
235 #endif
236 #ifdef INET
237 		case ETHERTYPE_IP:
238 		{
239 			if (m->m_len < sizeof (struct tcpiphdr)) {
240 				m = m_pullup(m, sizeof (struct tcpiphdr));
241 				if (m == NULL) {
242 					KMOD_TCPSTAT_INC(tcps_rcvshort);
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 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 __diagused;
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 	inp = tptoinpcb(tp);
404 	INP_WLOCK_ASSERT(inp);
405 	NET_EPOCH_ASSERT();
406 
407 	if (m)
408 		ifp = m_rcvif(m);
409 	else
410 		ifp = NULL;
411 	if (ifp == NULL) {
412 		/*
413 		 * We probably should not work around
414 		 * but kassert, since lro alwasy sets rcvif.
415 		 */
416 		no_vn = 1;
417 		goto skip_vnet;
418 	}
419 	CURVNET_SET(ifp->if_vnet);
420 skip_vnet:
421 	tcp_get_usecs(&tv);
422 	while (m) {
423 		m_save = m->m_nextpkt;
424 		m->m_nextpkt = NULL;
425 		if ((m->m_flags & M_ACKCMP) == 0) {
426 			/* Now lets get the ether header */
427 			etype = ctf_get_enet_type(ifp, m);
428 			if (etype == -1) {
429 				/* Skip this packet it was freed by checksum */
430 				goto skipped_pkt;
431 			}
432 			KASSERT(((etype == ETHERTYPE_IPV6) || (etype == ETHERTYPE_IP)),
433 				("tp:%p m:%p etype:0x%x -- not IP or IPv6", tp, m, etype));
434 			/* Trim off the ethernet header */
435 			switch (etype) {
436 #ifdef INET6
437 			case ETHERTYPE_IPV6:
438 				ip6 = mtod(m, struct ip6_hdr *);
439 				th = (struct tcphdr *)(ip6 + 1);
440 				tlen = ntohs(ip6->ip6_plen);
441 				drop_hdrlen = sizeof(*ip6);
442 				iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
443 				break;
444 #endif
445 #ifdef INET
446 			case ETHERTYPE_IP:
447 				ip = mtod(m, struct ip *);
448 				th = (struct tcphdr *)(ip + 1);
449 				drop_hdrlen = sizeof(*ip);
450 				iptos = ip->ip_tos;
451 				tlen = ntohs(ip->ip_len) - sizeof(struct ip);
452 				break;
453 #endif
454 			} /* end switch */
455 			/*
456 			 * Convert TCP protocol specific fields to host format.
457 			 */
458 			tcp_fields_to_host(th);
459 			off = th->th_off << 2;
460 			if (off < sizeof (struct tcphdr) || off > tlen) {
461 				printf("off:%d < hdrlen:%zu || > tlen:%u -- dump\n",
462 				       off,
463 				       sizeof(struct tcphdr),
464 				       tlen);
465 				KMOD_TCPSTAT_INC(tcps_rcvbadoff);
466 				m_freem(m);
467 				goto skipped_pkt;
468 			}
469 			tlen -= off;
470 			drop_hdrlen += off;
471 			/*
472 			 * Now lets setup the timeval to be when we should
473 			 * have been called (if we can).
474 			 */
475 			m->m_pkthdr.lro_nsegs = 1;
476 			/* Now what about next packet? */
477 		} else {
478 			/*
479 			 * This mbuf is an array of acks that have
480 			 * been compressed. We assert the inp has
481 			 * the flag set to enable this!
482 			 */
483 			KASSERT((inp->inp_flags2 & INP_MBUF_ACKCMP),
484 			    ("tp:%p inp:%p no INP_MBUF_ACKCMP flags?", tp, inp));
485 			tlen = 0;
486 			drop_hdrlen = 0;
487 			th = NULL;
488 			iptos = 0;
489 		}
490 		tcp_get_usecs(&tv);
491 		if (m_save || has_pkt)
492 			nxt_pkt = 1;
493 		else
494 			nxt_pkt = 0;
495 		if ((m->m_flags & M_ACKCMP) == 0)
496 			KMOD_TCPSTAT_INC(tcps_rcvtotal);
497 		else
498 			KMOD_TCPSTAT_ADD(tcps_rcvtotal, (m->m_len / sizeof(struct tcp_ackent)));
499 		retval = (*tp->t_fb->tfb_do_segment_nounlock)(m, th, so, tp, drop_hdrlen, tlen,
500 							      iptos, nxt_pkt, &tv);
501 		if (retval) {
502 			/* We lost the lock and tcb probably */
503 			m = m_save;
504 			while(m) {
505 				m_save = m->m_nextpkt;
506 				m->m_nextpkt = NULL;
507 				m_freem(m);
508 				m = m_save;
509 			}
510 			if (no_vn == 0) {
511 				CURVNET_RESTORE();
512 			}
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 	}
522 	return(retval);
523 }
524 
525 int
526 ctf_do_queued_segments(struct socket *so, struct tcpcb *tp, int have_pkt)
527 {
528 	struct mbuf *m;
529 
530 	/* First lets see if we have old packets */
531 	if (tp->t_in_pkt) {
532 		m = tp->t_in_pkt;
533 		tp->t_in_pkt = NULL;
534 		tp->t_tail_pkt = NULL;
535 		if (ctf_process_inbound_raw(tp, so, m, have_pkt)) {
536 			/* We lost the tcpcb (maybe a RST came in)? */
537 			return(1);
538 		}
539 	}
540 	return (0);
541 }
542 
543 uint32_t
544 ctf_outstanding(struct tcpcb *tp)
545 {
546 	uint32_t bytes_out;
547 
548 	bytes_out = tp->snd_max - tp->snd_una;
549 	if (tp->t_state < TCPS_ESTABLISHED)
550 		bytes_out++;
551 	if (tp->t_flags & TF_SENTFIN)
552 		bytes_out++;
553 	return (bytes_out);
554 }
555 
556 uint32_t
557 ctf_flight_size(struct tcpcb *tp, uint32_t rc_sacked)
558 {
559 	if (rc_sacked <= ctf_outstanding(tp))
560 		return(ctf_outstanding(tp) - rc_sacked);
561 	else {
562 		return (0);
563 	}
564 }
565 
566 void
567 ctf_do_dropwithreset(struct mbuf *m, struct tcpcb *tp, struct tcphdr *th,
568     int32_t rstreason, int32_t tlen)
569 {
570 	if (tp != NULL) {
571 		tcp_dropwithreset(m, th, tp, tlen, rstreason);
572 		INP_WUNLOCK(tptoinpcb(tp));
573 	} else
574 		tcp_dropwithreset(m, th, NULL, tlen, rstreason);
575 }
576 
577 void
578 ctf_ack_war_checks(struct tcpcb *tp, uint32_t *ts, uint32_t *cnt)
579 {
580 	if ((ts != NULL) && (cnt != NULL) &&
581 	    (tcp_ack_war_time_window > 0) &&
582 	    (tcp_ack_war_cnt > 0)) {
583 		/* We are possibly doing ack war prevention */
584 		uint32_t cts;
585 
586 		/*
587 		 * We use a msec tick here which gives us
588 		 * roughly 49 days. We don't need the
589 		 * precision of a microsecond timestamp which
590 		 * would only give us hours.
591 		 */
592 		cts = tcp_ts_getticks();
593 		if (TSTMP_LT((*ts), cts)) {
594 			/* Timestamp is in the past */
595 			*cnt = 0;
596 			*ts = (cts + tcp_ack_war_time_window);
597 		}
598 		if (*cnt < tcp_ack_war_cnt) {
599 			*cnt = (*cnt + 1);
600 			tp->t_flags |= TF_ACKNOW;
601 		} else
602 			tp->t_flags &= ~TF_ACKNOW;
603 	} else
604 		tp->t_flags |= TF_ACKNOW;
605 }
606 
607 /*
608  * ctf_drop_checks returns 1 for you should not proceed. It places
609  * in ret_val what should be returned 1/0 by the caller. The 1 indicates
610  * that the TCB is unlocked and probably dropped. The 0 indicates the
611  * TCB is still valid and locked.
612  */
613 int
614 _ctf_drop_checks(struct tcpopt *to, struct mbuf *m, struct tcphdr *th,
615 		 struct tcpcb *tp, int32_t *tlenp,
616 		 int32_t *thf, int32_t *drop_hdrlen, int32_t *ret_val,
617 		 uint32_t *ts, uint32_t *cnt)
618 {
619 	int32_t todrop;
620 	int32_t thflags;
621 	int32_t tlen;
622 
623 	thflags = *thf;
624 	tlen = *tlenp;
625 	todrop = tp->rcv_nxt - th->th_seq;
626 	if (todrop > 0) {
627 		if (thflags & TH_SYN) {
628 			thflags &= ~TH_SYN;
629 			th->th_seq++;
630 			if (th->th_urp > 1)
631 				th->th_urp--;
632 			else
633 				thflags &= ~TH_URG;
634 			todrop--;
635 		}
636 		/*
637 		 * Following if statement from Stevens, vol. 2, p. 960.
638 		 */
639 		if (todrop > tlen
640 		    || (todrop == tlen && (thflags & TH_FIN) == 0)) {
641 			/*
642 			 * Any valid FIN must be to the left of the window.
643 			 * At this point the FIN must be a duplicate or out
644 			 * of sequence; drop it.
645 			 */
646 			thflags &= ~TH_FIN;
647 			/*
648 			 * Send an ACK to resynchronize and drop any data.
649 			 * But keep on processing for RST or ACK.
650 			 */
651 			ctf_ack_war_checks(tp, ts, cnt);
652 			todrop = tlen;
653 			KMOD_TCPSTAT_INC(tcps_rcvduppack);
654 			KMOD_TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
655 		} else {
656 			KMOD_TCPSTAT_INC(tcps_rcvpartduppack);
657 			KMOD_TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
658 		}
659 		/*
660 		 * DSACK - add SACK block for dropped range
661 		 */
662 		if ((todrop > 0) && (tp->t_flags & TF_SACK_PERMIT)) {
663 			/*
664 			 * ACK now, as the next in-sequence segment
665 			 * will clear the DSACK block again
666 			 */
667 			ctf_ack_war_checks(tp, ts, cnt);
668 			if (tp->t_flags & TF_ACKNOW)
669 				tcp_update_sack_list(tp, th->th_seq,
670 						     th->th_seq + todrop);
671 		}
672 		*drop_hdrlen += todrop;	/* drop from the top afterwards */
673 		th->th_seq += todrop;
674 		tlen -= todrop;
675 		if (th->th_urp > todrop)
676 			th->th_urp -= todrop;
677 		else {
678 			thflags &= ~TH_URG;
679 			th->th_urp = 0;
680 		}
681 	}
682 	/*
683 	 * If segment ends after window, drop trailing data (and PUSH and
684 	 * FIN); if nothing left, just ACK.
685 	 */
686 	todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
687 	if (todrop > 0) {
688 		KMOD_TCPSTAT_INC(tcps_rcvpackafterwin);
689 		if (todrop >= tlen) {
690 			KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
691 			/*
692 			 * If window is closed can only take segments at
693 			 * window edge, and have to drop data and PUSH from
694 			 * incoming segments.  Continue processing, but
695 			 * remember to ack.  Otherwise, drop segment and
696 			 * ack.
697 			 */
698 			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
699 				ctf_ack_war_checks(tp, ts, cnt);
700 				KMOD_TCPSTAT_INC(tcps_rcvwinprobe);
701 			} else {
702 				__ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val, ts, cnt);
703 				return (1);
704 			}
705 		} else
706 			KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
707 		m_adj(m, -todrop);
708 		tlen -= todrop;
709 		thflags &= ~(TH_PUSH | TH_FIN);
710 	}
711 	*thf = thflags;
712 	*tlenp = tlen;
713 	return (0);
714 }
715 
716 /*
717  * The value in ret_val informs the caller
718  * if we dropped the tcb (and lock) or not.
719  * 1 = we dropped it, 0 = the TCB is still locked
720  * and valid.
721  */
722 void
723 __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)
724 {
725 	/*
726 	 * Generate an ACK dropping incoming segment if it occupies sequence
727 	 * space, where the ACK reflects our state.
728 	 *
729 	 * We can now skip the test for the RST flag since all paths to this
730 	 * code happen after packets containing RST have been dropped.
731 	 *
732 	 * In the SYN-RECEIVED state, don't send an ACK unless the segment
733 	 * we received passes the SYN-RECEIVED ACK test. If it fails send a
734 	 * RST.  This breaks the loop in the "LAND" DoS attack, and also
735 	 * prevents an ACK storm between two listening ports that have been
736 	 * sent forged SYN segments, each with the source address of the
737 	 * other.
738 	 */
739 	if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
740 	    (SEQ_GT(tp->snd_una, th->th_ack) ||
741 	    SEQ_GT(th->th_ack, tp->snd_max))) {
742 		*ret_val = 1;
743 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
744 		return;
745 	} else
746 		*ret_val = 0;
747 	ctf_ack_war_checks(tp, ts, cnt);
748 	if (m)
749 		m_freem(m);
750 }
751 
752 void
753 ctf_do_drop(struct mbuf *m, struct tcpcb *tp)
754 {
755 
756 	/*
757 	 * Drop space held by incoming segment and return.
758 	 */
759 	if (tp != NULL)
760 		INP_WUNLOCK(tptoinpcb(tp));
761 	if (m)
762 		m_freem(m);
763 }
764 
765 int
766 __ctf_process_rst(struct mbuf *m, struct tcphdr *th, struct socket *so,
767 		struct tcpcb *tp, uint32_t *ts, uint32_t *cnt)
768 {
769 	/*
770 	 * RFC5961 Section 3.2
771 	 *
772 	 * - RST drops connection only if SEG.SEQ == RCV.NXT. - If RST is in
773 	 * window, we send challenge ACK.
774 	 *
775 	 * Note: to take into account delayed ACKs, we should test against
776 	 * last_ack_sent instead of rcv_nxt. Note 2: we handle special case
777 	 * of closed window, not covered by the RFC.
778 	 */
779 	int dropped = 0;
780 
781 	if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
782 	    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
783 	    (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
784 		KASSERT(tp->t_state != TCPS_SYN_SENT,
785 		    ("%s: TH_RST for TCPS_SYN_SENT th %p tp %p",
786 		    __func__, th, tp));
787 
788 		if (V_tcp_insecure_rst ||
789 		    (tp->last_ack_sent == th->th_seq) ||
790 		    (tp->rcv_nxt == th->th_seq)) {
791 			KMOD_TCPSTAT_INC(tcps_drops);
792 			/* Drop the connection. */
793 			switch (tp->t_state) {
794 			case TCPS_SYN_RECEIVED:
795 				so->so_error = ECONNREFUSED;
796 				goto close;
797 			case TCPS_ESTABLISHED:
798 			case TCPS_FIN_WAIT_1:
799 			case TCPS_FIN_WAIT_2:
800 			case TCPS_CLOSE_WAIT:
801 			case TCPS_CLOSING:
802 			case TCPS_LAST_ACK:
803 				so->so_error = ECONNRESET;
804 		close:
805 				tcp_state_change(tp, TCPS_CLOSED);
806 				/* FALLTHROUGH */
807 			default:
808 				tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_RST);
809 				tp = tcp_close(tp);
810 			}
811 			dropped = 1;
812 			ctf_do_drop(m, tp);
813 		} else {
814 			int send_challenge;
815 
816 			KMOD_TCPSTAT_INC(tcps_badrst);
817 			if ((ts != NULL) && (cnt != NULL) &&
818 			    (tcp_ack_war_time_window > 0) &&
819 			    (tcp_ack_war_cnt > 0)) {
820 				/* We are possibly preventing an  ack-rst  war prevention */
821 				uint32_t cts;
822 
823 				/*
824 				 * We use a msec tick here which gives us
825 				 * roughly 49 days. We don't need the
826 				 * precision of a microsecond timestamp which
827 				 * would only give us hours.
828 				 */
829 				cts = tcp_ts_getticks();
830 				if (TSTMP_LT((*ts), cts)) {
831 					/* Timestamp is in the past */
832 					*cnt = 0;
833 					*ts = (cts + tcp_ack_war_time_window);
834 				}
835 				if (*cnt < tcp_ack_war_cnt) {
836 					*cnt = (*cnt + 1);
837 					send_challenge = 1;
838 				} else
839 					send_challenge = 0;
840 			} else
841 				send_challenge = 1;
842 			if (send_challenge) {
843 				/* Send challenge ACK. */
844 				tcp_respond(tp, mtod(m, void *), th, m,
845 					    tp->rcv_nxt, tp->snd_nxt, TH_ACK);
846 				tp->last_ack_sent = tp->rcv_nxt;
847 			}
848 		}
849 	} else {
850 		m_freem(m);
851 	}
852 	return (dropped);
853 }
854 
855 /*
856  * The value in ret_val informs the caller
857  * if we dropped the tcb (and lock) or not.
858  * 1 = we dropped it, 0 = the TCB is still locked
859  * and valid.
860  */
861 void
862 ctf_challenge_ack(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp, uint8_t iptos, int32_t * ret_val)
863 {
864 
865 	NET_EPOCH_ASSERT();
866 
867 	KMOD_TCPSTAT_INC(tcps_badsyn);
868 	if (V_tcp_insecure_syn &&
869 	    SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
870 	    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
871 		tp = tcp_drop(tp, ECONNRESET);
872 		*ret_val = 1;
873 		ctf_do_drop(m, tp);
874 	} else {
875 		tcp_ecn_input_syn_sent(tp, tcp_get_flags(th), iptos);
876 		/* Send challenge ACK. */
877 		tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt,
878 		    tp->snd_nxt, TH_ACK);
879 		tp->last_ack_sent = tp->rcv_nxt;
880 		m = NULL;
881 		*ret_val = 0;
882 		ctf_do_drop(m, NULL);
883 	}
884 }
885 
886 /*
887  * ctf_ts_check returns 1 for you should not proceed, the state
888  * machine should return. It places in ret_val what should
889  * be returned 1/0 by the caller (hpts_do_segment). The 1 indicates
890  * that the TCB is unlocked and probably dropped. The 0 indicates the
891  * TCB is still valid and locked.
892  */
893 int
894 ctf_ts_check(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
895     int32_t tlen, int32_t thflags, int32_t * ret_val)
896 {
897 
898 	if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
899 		/*
900 		 * Invalidate ts_recent.  If this segment updates ts_recent,
901 		 * the age will be reset later and ts_recent will get a
902 		 * valid value.  If it does not, setting ts_recent to zero
903 		 * will at least satisfy the requirement that zero be placed
904 		 * in the timestamp echo reply when ts_recent isn't valid.
905 		 * The age isn't reset until we get a valid ts_recent
906 		 * because we don't want out-of-order segments to be dropped
907 		 * when ts_recent is old.
908 		 */
909 		tp->ts_recent = 0;
910 	} else {
911 		KMOD_TCPSTAT_INC(tcps_rcvduppack);
912 		KMOD_TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
913 		KMOD_TCPSTAT_INC(tcps_pawsdrop);
914 		*ret_val = 0;
915 		if (tlen) {
916 			ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
917 		} else {
918 			ctf_do_drop(m, NULL);
919 		}
920 		return (1);
921 	}
922 	return (0);
923 }
924 
925 int
926 ctf_ts_check_ac(struct tcpcb *tp, int32_t thflags)
927 {
928 
929 	if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
930 		/*
931 		 * Invalidate ts_recent.  If this segment updates ts_recent,
932 		 * the age will be reset later and ts_recent will get a
933 		 * valid value.  If it does not, setting ts_recent to zero
934 		 * will at least satisfy the requirement that zero be placed
935 		 * in the timestamp echo reply when ts_recent isn't valid.
936 		 * The age isn't reset until we get a valid ts_recent
937 		 * because we don't want out-of-order segments to be dropped
938 		 * when ts_recent is old.
939 		 */
940 		tp->ts_recent = 0;
941 	} else {
942 		KMOD_TCPSTAT_INC(tcps_rcvduppack);
943 		KMOD_TCPSTAT_INC(tcps_pawsdrop);
944 		return (1);
945 	}
946 	return (0);
947 }
948 
949 
950 
951 void
952 ctf_calc_rwin(struct socket *so, struct tcpcb *tp)
953 {
954 	int32_t win;
955 
956 	/*
957 	 * Calculate amount of space in receive window, and then do TCP
958 	 * input processing. Receive window is amount of space in rcv queue,
959 	 * but not less than advertised window.
960 	 */
961 	win = sbspace(&so->so_rcv);
962 	if (win < 0)
963 		win = 0;
964 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
965 }
966 
967 void
968 ctf_do_dropwithreset_conn(struct mbuf *m, struct tcpcb *tp, struct tcphdr *th,
969     int32_t rstreason, int32_t tlen)
970 {
971 
972 	tcp_dropwithreset(m, th, tp, tlen, rstreason);
973 	tp = tcp_drop(tp, ETIMEDOUT);
974 	if (tp)
975 		INP_WUNLOCK(tptoinpcb(tp));
976 }
977 
978 uint32_t
979 ctf_fixed_maxseg(struct tcpcb *tp)
980 {
981 	return (tcp_fixed_maxseg(tp));
982 }
983 
984 void
985 ctf_log_sack_filter(struct tcpcb *tp, int num_sack_blks, struct sackblk *sack_blocks)
986 {
987 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
988 		union tcp_log_stackspecific log;
989 		struct timeval tv;
990 
991 		memset(&log, 0, sizeof(log));
992 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
993 		log.u_bbr.flex8 = num_sack_blks;
994 		if (num_sack_blks > 0) {
995 			log.u_bbr.flex1 = sack_blocks[0].start;
996 			log.u_bbr.flex2 = sack_blocks[0].end;
997 		}
998 		if (num_sack_blks > 1) {
999 			log.u_bbr.flex3 = sack_blocks[1].start;
1000 			log.u_bbr.flex4 = sack_blocks[1].end;
1001 		}
1002 		if (num_sack_blks > 2) {
1003 			log.u_bbr.flex5 = sack_blocks[2].start;
1004 			log.u_bbr.flex6 = sack_blocks[2].end;
1005 		}
1006 		if (num_sack_blks > 3) {
1007 			log.u_bbr.applimited = sack_blocks[3].start;
1008 			log.u_bbr.pkts_out = sack_blocks[3].end;
1009 		}
1010 		TCP_LOG_EVENTP(tp, NULL,
1011 		    &tptosocket(tp)->so_rcv,
1012 		    &tptosocket(tp)->so_snd,
1013 		    TCP_SACK_FILTER_RES, 0,
1014 		    0, &log, false, &tv);
1015 	}
1016 }
1017 
1018 uint32_t
1019 ctf_decay_count(uint32_t count, uint32_t decay)
1020 {
1021 	/*
1022 	 * Given a count, decay it by a set percentage. The
1023 	 * percentage is in thousands i.e. 100% = 1000,
1024 	 * 19.3% = 193.
1025 	 */
1026 	uint64_t perc_count, decay_per;
1027 	uint32_t decayed_count;
1028 	if (decay > 1000) {
1029 		/* We don't raise it */
1030 		return (count);
1031 	}
1032 	perc_count = count;
1033 	decay_per = decay;
1034 	perc_count *= decay_per;
1035 	perc_count /= 1000;
1036 	/*
1037 	 * So now perc_count holds the
1038 	 * count decay value.
1039 	 */
1040 	decayed_count = count - (uint32_t)perc_count;
1041 	return(decayed_count);
1042 }
1043 
1044 int32_t
1045 ctf_progress_timeout_check(struct tcpcb *tp, bool log)
1046 {
1047 	if (tp->t_maxunacktime && tp->t_acktime && TSTMP_GT(ticks, tp->t_acktime)) {
1048 		if ((ticks - tp->t_acktime) >= tp->t_maxunacktime) {
1049 			/*
1050 			 * There is an assumption that the caller
1051 			 * will drop the connection so we will
1052 			 * increment the counters here.
1053 			 */
1054 			if (log)
1055 				tcp_log_end_status(tp, TCP_EI_STATUS_PROGRESS);
1056 #ifdef NETFLIX_STATS
1057 			KMOD_TCPSTAT_INC(tcps_progdrops);
1058 #endif
1059 			return (1);
1060 		}
1061 	}
1062 	return (0);
1063 }
1064