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