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