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