File Index
Files and directories
Sign in
FILE

tcp_input.c

File preview with syntax highlighting.

linux-6.19.14/net/ipv4/tcp_input.c C
   1// SPDX-License-Identifier: GPL-2.0
   2/*
   3 * INET		An implementation of the TCP/IP protocol suite for the LINUX
   4 *		operating system.  INET is implemented using the  BSD Socket
   5 *		interface as the means of communication with the user level.
   6 *
   7 *		Implementation of the Transmission Control Protocol(TCP).
   8 *
   9 * Authors:	Ross Biro
  10 *		Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
  11 *		Mark Evans, <evansmp@uhura.aston.ac.uk>
  12 *		Corey Minyard <wf-rch!minyard@relay.EU.net>
  13 *		Florian La Roche, <flla@stud.uni-sb.de>
  14 *		Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
  15 *		Linus Torvalds, <torvalds@cs.helsinki.fi>
  16 *		Alan Cox, <gw4pts@gw4pts.ampr.org>
  17 *		Matthew Dillon, <dillon@apollo.west.oic.com>
  18 *		Arnt Gulbrandsen, <agulbra@nvg.unit.no>
  19 *		Jorge Cwik, <jorge@laser.satlink.net>
  20 */
  21
  22/*
  23 * Changes:
  24 *		Pedro Roque	:	Fast Retransmit/Recovery.
  25 *					Two receive queues.
  26 *					Retransmit queue handled by TCP.
  27 *					Better retransmit timer handling.
  28 *					New congestion avoidance.
  29 *					Header prediction.
  30 *					Variable renaming.
  31 *
  32 *		Eric		:	Fast Retransmit.
  33 *		Randy Scott	:	MSS option defines.
  34 *		Eric Schenk	:	Fixes to slow start algorithm.
  35 *		Eric Schenk	:	Yet another double ACK bug.
  36 *		Eric Schenk	:	Delayed ACK bug fixes.
  37 *		Eric Schenk	:	Floyd style fast retrans war avoidance.
  38 *		David S. Miller	:	Don't allow zero congestion window.
  39 *		Eric Schenk	:	Fix retransmitter so that it sends
  40 *					next packet on ack of previous packet.
  41 *		Andi Kleen	:	Moved open_request checking here
  42 *					and process RSTs for open_requests.
  43 *		Andi Kleen	:	Better prune_queue, and other fixes.
  44 *		Andrey Savochkin:	Fix RTT measurements in the presence of
  45 *					timestamps.
  46 *		Andrey Savochkin:	Check sequence numbers correctly when
  47 *					removing SACKs due to in sequence incoming
  48 *					data segments.
  49 *		Andi Kleen:		Make sure we never ack data there is not
  50 *					enough room for. Also make this condition
  51 *					a fatal error if it might still happen.
  52 *		Andi Kleen:		Add tcp_measure_rcv_mss to make
  53 *					connections with MSS<min(MTU,ann. MSS)
  54 *					work without delayed acks.
  55 *		Andi Kleen:		Process packets with PSH set in the
  56 *					fast path.
  57 *		J Hadi Salim:		ECN support
  58 *	 	Andrei Gurtov,
  59 *		Pasi Sarolahti,
  60 *		Panu Kuhlberg:		Experimental audit of TCP (re)transmission
  61 *					engine. Lots of bugs are found.
  62 *		Pasi Sarolahti:		F-RTO for dealing with spurious RTOs
  63 */
  64
  65#define pr_fmt(fmt) "TCP: " fmt
  66
  67#include <linux/mm.h>
  68#include <linux/slab.h>
  69#include <linux/module.h>
  70#include <linux/sysctl.h>
  71#include <linux/kernel.h>
  72#include <linux/prefetch.h>
  73#include <linux/bitops.h>
  74#include <net/dst.h>
  75#include <net/tcp.h>
  76#include <net/tcp_ecn.h>
  77#include <net/proto_memory.h>
  78#include <net/inet_common.h>
  79#include <linux/ipsec.h>
  80#include <linux/unaligned.h>
  81#include <linux/errqueue.h>
  82#include <trace/events/tcp.h>
  83#include <linux/jump_label_ratelimit.h>
  84#include <net/busy_poll.h>
  85#include <net/mptcp.h>
  86
  87int sysctl_tcp_max_orphans __read_mostly = NR_FILE;
  88
  89#define FLAG_DATA		0x01 /* Incoming frame contained data.		*/
  90#define FLAG_WIN_UPDATE		0x02 /* Incoming ACK was a window update.	*/
  91#define FLAG_DATA_ACKED		0x04 /* This ACK acknowledged new data.		*/
  92#define FLAG_RETRANS_DATA_ACKED	0x08 /* "" "" some of which was retransmitted.	*/
  93#define FLAG_SYN_ACKED		0x10 /* This ACK acknowledged SYN.		*/
  94#define FLAG_DATA_SACKED	0x20 /* New SACK.				*/
  95#define FLAG_ECE		0x40 /* ECE in this ACK				*/
  96#define FLAG_LOST_RETRANS	0x80 /* This ACK marks some retransmission lost */
  97#define FLAG_SLOWPATH		0x100 /* Do not skip RFC checks for window update.*/
  98#define FLAG_ORIG_SACK_ACKED	0x200 /* Never retransmitted data are (s)acked	*/
  99#define FLAG_SND_UNA_ADVANCED	0x400 /* Snd_una was changed (!= FLAG_DATA_ACKED) */
 100#define FLAG_DSACKING_ACK	0x800 /* SACK blocks contained D-SACK info */
 101#define FLAG_SET_XMIT_TIMER	0x1000 /* Set TLP or RTO timer */
 102#define FLAG_SACK_RENEGING	0x2000 /* snd_una advanced to a sacked seq */
 103#define FLAG_UPDATE_TS_RECENT	0x4000 /* tcp_replace_ts_recent() */
 104#define FLAG_NO_CHALLENGE_ACK	0x8000 /* do not call tcp_send_challenge_ack()	*/
 105#define FLAG_ACK_MAYBE_DELAYED	0x10000 /* Likely a delayed ACK */
 106#define FLAG_DSACK_TLP		0x20000 /* DSACK for tail loss probe */
 107#define FLAG_TS_PROGRESS	0x40000 /* Positive timestamp delta */
 108
 109#define FLAG_ACKED		(FLAG_DATA_ACKED|FLAG_SYN_ACKED)
 110#define FLAG_NOT_DUP		(FLAG_DATA|FLAG_WIN_UPDATE|FLAG_ACKED)
 111#define FLAG_CA_ALERT		(FLAG_DATA_SACKED|FLAG_ECE|FLAG_DSACKING_ACK)
 112#define FLAG_FORWARD_PROGRESS	(FLAG_ACKED|FLAG_DATA_SACKED)
 113
 114#define TCP_REMNANT (TCP_FLAG_FIN|TCP_FLAG_URG|TCP_FLAG_SYN|TCP_FLAG_PSH)
 115#define TCP_HP_BITS (~(TCP_RESERVED_BITS|TCP_FLAG_PSH))
 116
 117#define REXMIT_NONE	0 /* no loss recovery to do */
 118#define REXMIT_LOST	1 /* retransmit packets marked lost */
 119#define REXMIT_NEW	2 /* FRTO-style transmit of unsent/new packets */
 120
 121#if IS_ENABLED(CONFIG_TLS_DEVICE)
 122static DEFINE_STATIC_KEY_DEFERRED_FALSE(clean_acked_data_enabled, HZ);
 123
 124void clean_acked_data_enable(struct tcp_sock *tp,
 125			     void (*cad)(struct sock *sk, u32 ack_seq))
 126{
 127	tp->tcp_clean_acked = cad;
 128	static_branch_deferred_inc(&clean_acked_data_enabled);
 129}
 130EXPORT_SYMBOL_GPL(clean_acked_data_enable);
 131
 132void clean_acked_data_disable(struct tcp_sock *tp)
 133{
 134	static_branch_slow_dec_deferred(&clean_acked_data_enabled);
 135	tp->tcp_clean_acked = NULL;
 136}
 137EXPORT_SYMBOL_GPL(clean_acked_data_disable);
 138
 139void clean_acked_data_flush(void)
 140{
 141	static_key_deferred_flush(&clean_acked_data_enabled);
 142}
 143EXPORT_SYMBOL_GPL(clean_acked_data_flush);
 144#endif
 145
 146#ifdef CONFIG_CGROUP_BPF
 147static void bpf_skops_parse_hdr(struct sock *sk, struct sk_buff *skb)
 148{
 149	bool unknown_opt = tcp_sk(sk)->rx_opt.saw_unknown &&
 150		BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk),
 151				       BPF_SOCK_OPS_PARSE_UNKNOWN_HDR_OPT_CB_FLAG);
 152	bool parse_all_opt = BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk),
 153						    BPF_SOCK_OPS_PARSE_ALL_HDR_OPT_CB_FLAG);
 154	struct bpf_sock_ops_kern sock_ops;
 155
 156	if (likely(!unknown_opt && !parse_all_opt))
 157		return;
 158
 159	/* The skb will be handled in the
 160	 * bpf_skops_established() or
 161	 * bpf_skops_write_hdr_opt().
 162	 */
 163	switch (sk->sk_state) {
 164	case TCP_SYN_RECV:
 165	case TCP_SYN_SENT:
 166	case TCP_LISTEN:
 167		return;
 168	}
 169
 170	sock_owned_by_me(sk);
 171
 172	memset(&sock_ops, 0, offsetof(struct bpf_sock_ops_kern, temp));
 173	sock_ops.op = BPF_SOCK_OPS_PARSE_HDR_OPT_CB;
 174	sock_ops.is_fullsock = 1;
 175	sock_ops.is_locked_tcp_sock = 1;
 176	sock_ops.sk = sk;
 177	bpf_skops_init_skb(&sock_ops, skb, tcp_hdrlen(skb));
 178
 179	BPF_CGROUP_RUN_PROG_SOCK_OPS(&sock_ops);
 180}
 181
 182static void bpf_skops_established(struct sock *sk, int bpf_op,
 183				  struct sk_buff *skb)
 184{
 185	struct bpf_sock_ops_kern sock_ops;
 186
 187	sock_owned_by_me(sk);
 188
 189	memset(&sock_ops, 0, offsetof(struct bpf_sock_ops_kern, temp));
 190	sock_ops.op = bpf_op;
 191	sock_ops.is_fullsock = 1;
 192	sock_ops.is_locked_tcp_sock = 1;
 193	sock_ops.sk = sk;
 194	/* sk with TCP_REPAIR_ON does not have skb in tcp_finish_connect */
 195	if (skb)
 196		bpf_skops_init_skb(&sock_ops, skb, tcp_hdrlen(skb));
 197
 198	BPF_CGROUP_RUN_PROG_SOCK_OPS(&sock_ops);
 199}
 200#else
 201static void bpf_skops_parse_hdr(struct sock *sk, struct sk_buff *skb)
 202{
 203}
 204
 205static void bpf_skops_established(struct sock *sk, int bpf_op,
 206				  struct sk_buff *skb)
 207{
 208}
 209#endif
 210
 211static __cold void tcp_gro_dev_warn(const struct sock *sk, const struct sk_buff *skb,
 212				    unsigned int len)
 213{
 214	struct net_device *dev;
 215
 216	rcu_read_lock();
 217	dev = dev_get_by_index_rcu(sock_net(sk), skb->skb_iif);
 218	if (!dev || len >= READ_ONCE(dev->mtu))
 219		pr_warn("%s: Driver has suspect GRO implementation, TCP performance may be compromised.\n",
 220			dev ? dev->name : "Unknown driver");
 221	rcu_read_unlock();
 222}
 223
 224/* Adapt the MSS value used to make delayed ack decision to the
 225 * real world.
 226 */
 227static void tcp_measure_rcv_mss(struct sock *sk, const struct sk_buff *skb)
 228{
 229	struct inet_connection_sock *icsk = inet_csk(sk);
 230	const unsigned int lss = icsk->icsk_ack.last_seg_size;
 231	unsigned int len;
 232
 233	icsk->icsk_ack.last_seg_size = 0;
 234
 235	/* skb->len may jitter because of SACKs, even if peer
 236	 * sends good full-sized frames.
 237	 */
 238	len = skb_shinfo(skb)->gso_size ? : skb->len;
 239	if (len >= icsk->icsk_ack.rcv_mss) {
 240		/* Note: divides are still a bit expensive.
 241		 * For the moment, only adjust scaling_ratio
 242		 * when we update icsk_ack.rcv_mss.
 243		 */
 244		if (unlikely(len != icsk->icsk_ack.rcv_mss)) {
 245			u64 val = (u64)skb->len << TCP_RMEM_TO_WIN_SCALE;
 246			u8 old_ratio = tcp_sk(sk)->scaling_ratio;
 247
 248			do_div(val, skb->truesize);
 249			tcp_sk(sk)->scaling_ratio = val ? val : 1;
 250
 251			if (old_ratio != tcp_sk(sk)->scaling_ratio) {
 252				struct tcp_sock *tp = tcp_sk(sk);
 253
 254				val = tcp_win_from_space(sk, sk->sk_rcvbuf);
 255				tcp_set_window_clamp(sk, val);
 256
 257				if (tp->window_clamp < tp->rcvq_space.space)
 258					tp->rcvq_space.space = tp->window_clamp;
 259			}
 260		}
 261		icsk->icsk_ack.rcv_mss = min_t(unsigned int, len,
 262					       tcp_sk(sk)->advmss);
 263		/* Account for possibly-removed options */
 264		DO_ONCE_LITE_IF(len > icsk->icsk_ack.rcv_mss + MAX_TCP_OPTION_SPACE,
 265				tcp_gro_dev_warn, sk, skb, len);
 266		/* If the skb has a len of exactly 1*MSS and has the PSH bit
 267		 * set then it is likely the end of an application write. So
 268		 * more data may not be arriving soon, and yet the data sender
 269		 * may be waiting for an ACK if cwnd-bound or using TX zero
 270		 * copy. So we set ICSK_ACK_PUSHED here so that
 271		 * tcp_cleanup_rbuf() will send an ACK immediately if the app
 272		 * reads all of the data and is not ping-pong. If len > MSS
 273		 * then this logic does not matter (and does not hurt) because
 274		 * tcp_cleanup_rbuf() will always ACK immediately if the app
 275		 * reads data and there is more than an MSS of unACKed data.
 276		 */
 277		if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_PSH)
 278			icsk->icsk_ack.pending |= ICSK_ACK_PUSHED;
 279	} else {
 280		/* Otherwise, we make more careful check taking into account,
 281		 * that SACKs block is variable.
 282		 *
 283		 * "len" is invariant segment length, including TCP header.
 284		 */
 285		len += skb->data - skb_transport_header(skb);
 286		if (len >= TCP_MSS_DEFAULT + sizeof(struct tcphdr) ||
 287		    /* If PSH is not set, packet should be
 288		     * full sized, provided peer TCP is not badly broken.
 289		     * This observation (if it is correct 8)) allows
 290		     * to handle super-low mtu links fairly.
 291		     */
 292		    (len >= TCP_MIN_MSS + sizeof(struct tcphdr) &&
 293		     !(tcp_flag_word(tcp_hdr(skb)) & TCP_REMNANT))) {
 294			/* Subtract also invariant (if peer is RFC compliant),
 295			 * tcp header plus fixed timestamp option length.
 296			 * Resulting "len" is MSS free of SACK jitter.
 297			 */
 298			len -= tcp_sk(sk)->tcp_header_len;
 299			icsk->icsk_ack.last_seg_size = len;
 300			if (len == lss) {
 301				icsk->icsk_ack.rcv_mss = len;
 302				return;
 303			}
 304		}
 305		if (icsk->icsk_ack.pending & ICSK_ACK_PUSHED)
 306			icsk->icsk_ack.pending |= ICSK_ACK_PUSHED2;
 307		icsk->icsk_ack.pending |= ICSK_ACK_PUSHED;
 308	}
 309}
 310
 311static void tcp_incr_quickack(struct sock *sk, unsigned int max_quickacks)
 312{
 313	struct inet_connection_sock *icsk = inet_csk(sk);
 314	unsigned int quickacks = tcp_sk(sk)->rcv_wnd / (2 * icsk->icsk_ack.rcv_mss);
 315
 316	if (quickacks == 0)
 317		quickacks = 2;
 318	quickacks = min(quickacks, max_quickacks);
 319	if (quickacks > icsk->icsk_ack.quick)
 320		icsk->icsk_ack.quick = quickacks;
 321}
 322
 323static void tcp_enter_quickack_mode(struct sock *sk, unsigned int max_quickacks)
 324{
 325	struct inet_connection_sock *icsk = inet_csk(sk);
 326
 327	tcp_incr_quickack(sk, max_quickacks);
 328	inet_csk_exit_pingpong_mode(sk);
 329	icsk->icsk_ack.ato = TCP_ATO_MIN;
 330}
 331
 332/* Send ACKs quickly, if "quick" count is not exhausted
 333 * and the session is not interactive.
 334 */
 335
 336static bool tcp_in_quickack_mode(struct sock *sk)
 337{
 338	const struct inet_connection_sock *icsk = inet_csk(sk);
 339
 340	return icsk->icsk_ack.dst_quick_ack ||
 341		(icsk->icsk_ack.quick && !inet_csk_in_pingpong_mode(sk));
 342}
 343
 344static void tcp_data_ecn_check(struct sock *sk, const struct sk_buff *skb)
 345{
 346	struct tcp_sock *tp = tcp_sk(sk);
 347
 348	if (tcp_ecn_disabled(tp))
 349		return;
 350
 351	switch (TCP_SKB_CB(skb)->ip_dsfield & INET_ECN_MASK) {
 352	case INET_ECN_NOT_ECT:
 353		/* Funny extension: if ECT is not set on a segment,
 354		 * and we already seen ECT on a previous segment,
 355		 * it is probably a retransmit.
 356		 */
 357		if (tp->ecn_flags & TCP_ECN_SEEN)
 358			tcp_enter_quickack_mode(sk, 2);
 359		break;
 360	case INET_ECN_CE:
 361		if (tcp_ca_needs_ecn(sk))
 362			tcp_ca_event(sk, CA_EVENT_ECN_IS_CE);
 363
 364		if (!(tp->ecn_flags & TCP_ECN_DEMAND_CWR) &&
 365		    tcp_ecn_mode_rfc3168(tp)) {
 366			/* Better not delay acks, sender can have a very low cwnd */
 367			tcp_enter_quickack_mode(sk, 2);
 368			tp->ecn_flags |= TCP_ECN_DEMAND_CWR;
 369		}
 370		/* As for RFC3168 ECN, the TCP_ECN_SEEN flag is set by
 371		 * tcp_data_ecn_check() when the ECN codepoint of
 372		 * received TCP data contains ECT(0), ECT(1), or CE.
 373		 */
 374		if (!tcp_ecn_mode_rfc3168(tp))
 375			break;
 376		tp->ecn_flags |= TCP_ECN_SEEN;
 377		break;
 378	default:
 379		if (tcp_ca_needs_ecn(sk))
 380			tcp_ca_event(sk, CA_EVENT_ECN_NO_CE);
 381		if (!tcp_ecn_mode_rfc3168(tp))
 382			break;
 383		tp->ecn_flags |= TCP_ECN_SEEN;
 384		break;
 385	}
 386}
 387
 388/* Returns true if the byte counters can be used */
 389static bool tcp_accecn_process_option(struct tcp_sock *tp,
 390				      const struct sk_buff *skb,
 391				      u32 delivered_bytes, int flag)
 392{
 393	u8 estimate_ecnfield = tp->est_ecnfield;
 394	bool ambiguous_ecn_bytes_incr = false;
 395	bool first_changed = false;
 396	unsigned int optlen;
 397	bool order1, res;
 398	unsigned int i;
 399	u8 *ptr;
 400
 401	if (tcp_accecn_opt_fail_recv(tp))
 402		return false;
 403
 404	if (!(flag & FLAG_SLOWPATH) || !tp->rx_opt.accecn) {
 405		if (!tp->saw_accecn_opt) {
 406			/* Too late to enable after this point due to
 407			 * potential counter wraps
 408			 */
 409			if (tp->bytes_sent >= (1 << 23) - 1) {
 410				u8 saw_opt = TCP_ACCECN_OPT_FAIL_SEEN;
 411
 412				tcp_accecn_saw_opt_fail_recv(tp, saw_opt);
 413			}
 414			return false;
 415		}
 416
 417		if (estimate_ecnfield) {
 418			u8 ecnfield = estimate_ecnfield - 1;
 419
 420			tp->delivered_ecn_bytes[ecnfield] += delivered_bytes;
 421			return true;
 422		}
 423		return false;
 424	}
 425
 426	ptr = skb_transport_header(skb) + tp->rx_opt.accecn;
 427	optlen = ptr[1] - 2;
 428	if (WARN_ON_ONCE(ptr[0] != TCPOPT_ACCECN0 && ptr[0] != TCPOPT_ACCECN1))
 429		return false;
 430	order1 = (ptr[0] == TCPOPT_ACCECN1);
 431	ptr += 2;
 432
 433	if (tp->saw_accecn_opt < TCP_ACCECN_OPT_COUNTER_SEEN) {
 434		tp->saw_accecn_opt = tcp_accecn_option_init(skb,
 435							    tp->rx_opt.accecn);
 436		if (tp->saw_accecn_opt == TCP_ACCECN_OPT_FAIL_SEEN)
 437			tcp_accecn_fail_mode_set(tp, TCP_ACCECN_OPT_FAIL_RECV);
 438	}
 439
 440	res = !!estimate_ecnfield;
 441	for (i = 0; i < 3; i++) {
 442		u32 init_offset;
 443		u8 ecnfield;
 444		s32 delta;
 445		u32 *cnt;
 446
 447		if (optlen < TCPOLEN_ACCECN_PERFIELD)
 448			break;
 449
 450		ecnfield = tcp_accecn_optfield_to_ecnfield(i, order1);
 451		init_offset = tcp_accecn_field_init_offset(ecnfield);
 452		cnt = &tp->delivered_ecn_bytes[ecnfield - 1];
 453		delta = tcp_update_ecn_bytes(cnt, ptr, init_offset);
 454		if (delta && delta < 0) {
 455			res = false;
 456			ambiguous_ecn_bytes_incr = true;
 457		}
 458		if (delta && ecnfield != estimate_ecnfield) {
 459			if (!first_changed) {
 460				tp->est_ecnfield = ecnfield;
 461				first_changed = true;
 462			} else {
 463				res = false;
 464				ambiguous_ecn_bytes_incr = true;
 465			}
 466		}
 467
 468		optlen -= TCPOLEN_ACCECN_PERFIELD;
 469		ptr += TCPOLEN_ACCECN_PERFIELD;
 470	}
 471	if (ambiguous_ecn_bytes_incr)
 472		tp->est_ecnfield = 0;
 473
 474	return res;
 475}
 476
 477static void tcp_count_delivered_ce(struct tcp_sock *tp, u32 ecn_count)
 478{
 479	tp->delivered_ce += ecn_count;
 480}
 481
 482/* Updates the delivered and delivered_ce counts */
 483static void tcp_count_delivered(struct tcp_sock *tp, u32 delivered,
 484				bool ece_ack)
 485{
 486	tp->delivered += delivered;
 487	if (tcp_ecn_mode_rfc3168(tp) && ece_ack)
 488		tcp_count_delivered_ce(tp, delivered);
 489}
 490
 491/* Returns the ECN CE delta */
 492static u32 __tcp_accecn_process(struct sock *sk, const struct sk_buff *skb,
 493				u32 delivered_pkts, u32 delivered_bytes,
 494				int flag)
 495{
 496	u32 old_ceb = tcp_sk(sk)->delivered_ecn_bytes[INET_ECN_CE - 1];
 497	const struct tcphdr *th = tcp_hdr(skb);
 498	struct tcp_sock *tp = tcp_sk(sk);
 499	u32 delta, safe_delta, d_ceb;
 500	bool opt_deltas_valid;
 501	u32 corrected_ace;
 502
 503	/* Reordered ACK or uncertain due to lack of data to send and ts */
 504	if (!(flag & (FLAG_FORWARD_PROGRESS | FLAG_TS_PROGRESS)))
 505		return 0;
 506
 507	opt_deltas_valid = tcp_accecn_process_option(tp, skb,
 508						     delivered_bytes, flag);
 509
 510	if (!(flag & FLAG_SLOWPATH)) {
 511		/* AccECN counter might overflow on large ACKs */
 512		if (delivered_pkts <= TCP_ACCECN_CEP_ACE_MASK)
 513			return 0;
 514	}
 515
 516	/* ACE field is not available during handshake */
 517	if (flag & FLAG_SYN_ACKED)
 518		return 0;
 519
 520	if (tp->received_ce_pending >= TCP_ACCECN_ACE_MAX_DELTA)
 521		inet_csk(sk)->icsk_ack.pending |= ICSK_ACK_NOW;
 522
 523	corrected_ace = tcp_accecn_ace(th) - TCP_ACCECN_CEP_INIT_OFFSET;
 524	delta = (corrected_ace - tp->delivered_ce) & TCP_ACCECN_CEP_ACE_MASK;
 525	if (delivered_pkts <= TCP_ACCECN_CEP_ACE_MASK)
 526		return delta;
 527
 528	safe_delta = delivered_pkts -
 529		     ((delivered_pkts - delta) & TCP_ACCECN_CEP_ACE_MASK);
 530
 531	if (opt_deltas_valid) {
 532		d_ceb = tp->delivered_ecn_bytes[INET_ECN_CE - 1] - old_ceb;
 533		if (!d_ceb)
 534			return delta;
 535
 536		if ((delivered_pkts >= (TCP_ACCECN_CEP_ACE_MASK + 1) * 2) &&
 537		    (tcp_is_sack(tp) ||
 538		     ((1 << inet_csk(sk)->icsk_ca_state) &
 539		      (TCPF_CA_Open | TCPF_CA_CWR)))) {
 540			u32 est_d_cep;
 541
 542			if (delivered_bytes <= d_ceb)
 543				return safe_delta;
 544
 545			est_d_cep = DIV_ROUND_UP_ULL((u64)d_ceb *
 546						     delivered_pkts,
 547						     delivered_bytes);
 548			return min(safe_delta,
 549				   delta +
 550				   (est_d_cep & ~TCP_ACCECN_CEP_ACE_MASK));
 551		}
 552
 553		if (d_ceb > delta * tp->mss_cache)
 554			return safe_delta;
 555		if (d_ceb <
 556		    safe_delta * tp->mss_cache >> TCP_ACCECN_SAFETY_SHIFT)
 557			return delta;
 558	}
 559
 560	return safe_delta;
 561}
 562
 563static u32 tcp_accecn_process(struct sock *sk, const struct sk_buff *skb,
 564			      u32 delivered_pkts, u32 delivered_bytes,
 565			      int *flag)
 566{
 567	struct tcp_sock *tp = tcp_sk(sk);
 568	u32 delta;
 569
 570	delta = __tcp_accecn_process(sk, skb, delivered_pkts,
 571				     delivered_bytes, *flag);
 572	if (delta > 0) {
 573		tcp_count_delivered_ce(tp, delta);
 574		*flag |= FLAG_ECE;
 575		/* Recalculate header predictor */
 576		if (tp->pred_flags)
 577			tcp_fast_path_on(tp);
 578	}
 579	return delta;
 580}
 581
 582/* Buffer size and advertised window tuning.
 583 *
 584 * 1. Tuning sk->sk_sndbuf, when connection enters established state.
 585 */
 586
 587static void tcp_sndbuf_expand(struct sock *sk)
 588{
 589	const struct tcp_sock *tp = tcp_sk(sk);
 590	const struct tcp_congestion_ops *ca_ops = inet_csk(sk)->icsk_ca_ops;
 591	int sndmem, per_mss;
 592	u32 nr_segs;
 593
 594	/* Worst case is non GSO/TSO : each frame consumes one skb
 595	 * and skb->head is kmalloced using power of two area of memory
 596	 */
 597	per_mss = max_t(u32, tp->rx_opt.mss_clamp, tp->mss_cache) +
 598		  MAX_TCP_HEADER +
 599		  SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
 600
 601	per_mss = roundup_pow_of_two(per_mss) +
 602		  SKB_DATA_ALIGN(sizeof(struct sk_buff));
 603
 604	nr_segs = max_t(u32, TCP_INIT_CWND, tcp_snd_cwnd(tp));
 605	nr_segs = max_t(u32, nr_segs, tp->reordering + 1);
 606
 607	/* Fast Recovery (RFC 5681 3.2) :
 608	 * Cubic needs 1.7 factor, rounded to 2 to include
 609	 * extra cushion (application might react slowly to EPOLLOUT)
 610	 */
 611	sndmem = ca_ops->sndbuf_expand ? ca_ops->sndbuf_expand(sk) : 2;
 612	sndmem *= nr_segs * per_mss;
 613
 614	if (sk->sk_sndbuf < sndmem)
 615		WRITE_ONCE(sk->sk_sndbuf,
 616			   min(sndmem, READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_wmem[2])));
 617}
 618
 619/* 2. Tuning advertised window (window_clamp, rcv_ssthresh)
 620 *
 621 * All tcp_full_space() is split to two parts: "network" buffer, allocated
 622 * forward and advertised in receiver window (tp->rcv_wnd) and
 623 * "application buffer", required to isolate scheduling/application
 624 * latencies from network.
 625 * window_clamp is maximal advertised window. It can be less than
 626 * tcp_full_space(), in this case tcp_full_space() - window_clamp
 627 * is reserved for "application" buffer. The less window_clamp is
 628 * the smoother our behaviour from viewpoint of network, but the lower
 629 * throughput and the higher sensitivity of the connection to losses. 8)
 630 *
 631 * rcv_ssthresh is more strict window_clamp used at "slow start"
 632 * phase to predict further behaviour of this connection.
 633 * It is used for two goals:
 634 * - to enforce header prediction at sender, even when application
 635 *   requires some significant "application buffer". It is check #1.
 636 * - to prevent pruning of receive queue because of misprediction
 637 *   of receiver window. Check #2.
 638 *
 639 * The scheme does not work when sender sends good segments opening
 640 * window and then starts to feed us spaghetti. But it should work
 641 * in common situations. Otherwise, we have to rely on queue collapsing.
 642 */
 643
 644/* Slow part of check#2. */
 645static int __tcp_grow_window(const struct sock *sk, const struct sk_buff *skb,
 646			     unsigned int skbtruesize)
 647{
 648	const struct tcp_sock *tp = tcp_sk(sk);
 649	/* Optimize this! */
 650	int truesize = tcp_win_from_space(sk, skbtruesize) >> 1;
 651	int window = tcp_win_from_space(sk, READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[2])) >> 1;
 652
 653	while (tp->rcv_ssthresh <= window) {
 654		if (truesize <= skb->len)
 655			return 2 * inet_csk(sk)->icsk_ack.rcv_mss;
 656
 657		truesize >>= 1;
 658		window >>= 1;
 659	}
 660	return 0;
 661}
 662
 663/* Even if skb appears to have a bad len/truesize ratio, TCP coalescing
 664 * can play nice with us, as sk_buff and skb->head might be either
 665 * freed or shared with up to MAX_SKB_FRAGS segments.
 666 * Only give a boost to drivers using page frag(s) to hold the frame(s),
 667 * and if no payload was pulled in skb->head before reaching us.
 668 */
 669static u32 truesize_adjust(bool adjust, const struct sk_buff *skb)
 670{
 671	u32 truesize = skb->truesize;
 672
 673	if (adjust && !skb_headlen(skb)) {
 674		truesize -= SKB_TRUESIZE(skb_end_offset(skb));
 675		/* paranoid check, some drivers might be buggy */
 676		if (unlikely((int)truesize < (int)skb->len))
 677			truesize = skb->truesize;
 678	}
 679	return truesize;
 680}
 681
 682static void tcp_grow_window(struct sock *sk, const struct sk_buff *skb,
 683			    bool adjust)
 684{
 685	struct tcp_sock *tp = tcp_sk(sk);
 686	int room;
 687
 688	room = min_t(int, tp->window_clamp, tcp_space(sk)) - tp->rcv_ssthresh;
 689
 690	if (room <= 0)
 691		return;
 692
 693	/* Check #1 */
 694	if (!tcp_under_memory_pressure(sk)) {
 695		unsigned int truesize = truesize_adjust(adjust, skb);
 696		int incr;
 697
 698		/* Check #2. Increase window, if skb with such overhead
 699		 * will fit to rcvbuf in future.
 700		 */
 701		if (tcp_win_from_space(sk, truesize) <= skb->len)
 702			incr = 2 * tp->advmss;
 703		else
 704			incr = __tcp_grow_window(sk, skb, truesize);
 705
 706		if (incr) {
 707			incr = max_t(int, incr, 2 * skb->len);
 708			tp->rcv_ssthresh += min(room, incr);
 709			inet_csk(sk)->icsk_ack.quick |= 1;
 710		}
 711	} else {
 712		/* Under pressure:
 713		 * Adjust rcv_ssthresh according to reserved mem
 714		 */
 715		tcp_adjust_rcv_ssthresh(sk);
 716	}
 717}
 718
 719/* 3. Try to fixup all. It is made immediately after connection enters
 720 *    established state.
 721 */
 722static void tcp_init_buffer_space(struct sock *sk)
 723{
 724	int tcp_app_win = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_app_win);
 725	struct tcp_sock *tp = tcp_sk(sk);
 726	int maxwin;
 727
 728	if (!(sk->sk_userlocks & SOCK_SNDBUF_LOCK))
 729		tcp_sndbuf_expand(sk);
 730
 731	tcp_mstamp_refresh(tp);
 732	tp->rcvq_space.time = tp->tcp_mstamp;
 733	tp->rcvq_space.seq = tp->copied_seq;
 734
 735	maxwin = tcp_full_space(sk);
 736
 737	if (tp->window_clamp >= maxwin) {
 738		WRITE_ONCE(tp->window_clamp, maxwin);
 739
 740		if (tcp_app_win && maxwin > 4 * tp->advmss)
 741			WRITE_ONCE(tp->window_clamp,
 742				   max(maxwin - (maxwin >> tcp_app_win),
 743				       4 * tp->advmss));
 744	}
 745
 746	/* Force reservation of one segment. */
 747	if (tcp_app_win &&
 748	    tp->window_clamp > 2 * tp->advmss &&
 749	    tp->window_clamp + tp->advmss > maxwin)
 750		WRITE_ONCE(tp->window_clamp,
 751			   max(2 * tp->advmss, maxwin - tp->advmss));
 752
 753	tp->rcv_ssthresh = min(tp->rcv_ssthresh, tp->window_clamp);
 754	tp->snd_cwnd_stamp = tcp_jiffies32;
 755	tp->rcvq_space.space = min3(tp->rcv_ssthresh, tp->rcv_wnd,
 756				    (u32)TCP_INIT_CWND * tp->advmss);
 757}
 758
 759/* 4. Recalculate window clamp after socket hit its memory bounds. */
 760static void tcp_clamp_window(struct sock *sk)
 761{
 762	struct tcp_sock *tp = tcp_sk(sk);
 763	struct inet_connection_sock *icsk = inet_csk(sk);
 764	struct net *net = sock_net(sk);
 765	int rmem2;
 766
 767	icsk->icsk_ack.quick = 0;
 768	rmem2 = READ_ONCE(net->ipv4.sysctl_tcp_rmem[2]);
 769
 770	if (sk->sk_rcvbuf < rmem2 &&
 771	    !(sk->sk_userlocks & SOCK_RCVBUF_LOCK) &&
 772	    !tcp_under_memory_pressure(sk) &&
 773	    sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0)) {
 774		WRITE_ONCE(sk->sk_rcvbuf,
 775			   min(atomic_read(&sk->sk_rmem_alloc), rmem2));
 776	}
 777	if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf)
 778		tp->rcv_ssthresh = min(tp->window_clamp, 2U * tp->advmss);
 779}
 780
 781/* Initialize RCV_MSS value.
 782 * RCV_MSS is an our guess about MSS used by the peer.
 783 * We haven't any direct information about the MSS.
 784 * It's better to underestimate the RCV_MSS rather than overestimate.
 785 * Overestimations make us ACKing less frequently than needed.
 786 * Underestimations are more easy to detect and fix by tcp_measure_rcv_mss().
 787 */
 788void tcp_initialize_rcv_mss(struct sock *sk)
 789{
 790	const struct tcp_sock *tp = tcp_sk(sk);
 791	unsigned int hint = min_t(unsigned int, tp->advmss, tp->mss_cache);
 792
 793	hint = min(hint, tp->rcv_wnd / 2);
 794	hint = min(hint, TCP_MSS_DEFAULT);
 795	hint = max(hint, TCP_MIN_MSS);
 796
 797	inet_csk(sk)->icsk_ack.rcv_mss = hint;
 798}
 799EXPORT_IPV6_MOD(tcp_initialize_rcv_mss);
 800
 801/* Receiver "autotuning" code.
 802 *
 803 * The algorithm for RTT estimation w/o timestamps is based on
 804 * Dynamic Right-Sizing (DRS) by Wu Feng and Mike Fisk of LANL.
 805 * <https://public.lanl.gov/radiant/pubs.html#DRS>
 806 *
 807 * More detail on this code can be found at
 808 * <http://staff.psc.edu/jheffner/>,
 809 * though this reference is out of date.  A new paper
 810 * is pending.
 811 */
 812static void tcp_rcv_rtt_update(struct tcp_sock *tp, u32 sample, int win_dep)
 813{
 814	u32 new_sample, old_sample = tp->rcv_rtt_est.rtt_us;
 815	long m = sample << 3;
 816
 817	if (old_sample == 0 || m < old_sample) {
 818		new_sample = m;
 819	} else {
 820		/* If we sample in larger samples in the non-timestamp
 821		 * case, we could grossly overestimate the RTT especially
 822		 * with chatty applications or bulk transfer apps which
 823		 * are stalled on filesystem I/O.
 824		 *
 825		 * Also, since we are only going for a minimum in the
 826		 * non-timestamp case, we do not smooth things out
 827		 * else with timestamps disabled convergence takes too
 828		 * long.
 829		 */
 830		if (win_dep)
 831			return;
 832		/* Do not use this sample if receive queue is not empty. */
 833		if (tp->rcv_nxt != tp->copied_seq)
 834			return;
 835		new_sample = old_sample - (old_sample >> 3) + sample;
 836	}
 837
 838	tp->rcv_rtt_est.rtt_us = new_sample;
 839}
 840
 841static inline void tcp_rcv_rtt_measure(struct tcp_sock *tp)
 842{
 843	u32 delta_us;
 844
 845	if (tp->rcv_rtt_est.time == 0)
 846		goto new_measure;
 847	if (before(tp->rcv_nxt, tp->rcv_rtt_est.seq))
 848		return;
 849	delta_us = tcp_stamp_us_delta(tp->tcp_mstamp, tp->rcv_rtt_est.time);
 850	if (!delta_us)
 851		delta_us = 1;
 852	tcp_rcv_rtt_update(tp, delta_us, 1);
 853
 854new_measure:
 855	tp->rcv_rtt_est.seq = tp->rcv_nxt + tp->rcv_wnd;
 856	tp->rcv_rtt_est.time = tp->tcp_mstamp;
 857}
 858
 859static s32 tcp_rtt_tsopt_us(const struct tcp_sock *tp, u32 min_delta)
 860{
 861	u32 delta, delta_us;
 862
 863	delta = tcp_time_stamp_ts(tp) - tp->rx_opt.rcv_tsecr;
 864	if (tp->tcp_usec_ts)
 865		return delta;
 866
 867	if (likely(delta < INT_MAX / (USEC_PER_SEC / TCP_TS_HZ))) {
 868		if (!delta)
 869			delta = min_delta;
 870		delta_us = delta * (USEC_PER_SEC / TCP_TS_HZ);
 871		return delta_us;
 872	}
 873	return -1;
 874}
 875
 876static inline void tcp_rcv_rtt_measure_ts(struct sock *sk,
 877					  const struct sk_buff *skb)
 878{
 879	struct tcp_sock *tp = tcp_sk(sk);
 880
 881	if (tp->rx_opt.rcv_tsecr == tp->rcv_rtt_last_tsecr)
 882		return;
 883	tp->rcv_rtt_last_tsecr = tp->rx_opt.rcv_tsecr;
 884
 885	if (TCP_SKB_CB(skb)->end_seq -
 886	    TCP_SKB_CB(skb)->seq >= inet_csk(sk)->icsk_ack.rcv_mss) {
 887		s32 delta = tcp_rtt_tsopt_us(tp, 0);
 888
 889		if (delta > 0)
 890			tcp_rcv_rtt_update(tp, delta, 0);
 891	}
 892}
 893
 894void tcp_rcvbuf_grow(struct sock *sk, u32 newval)
 895{
 896	const struct net *net = sock_net(sk);
 897	struct tcp_sock *tp = tcp_sk(sk);
 898	u32 rcvwin, rcvbuf, cap, oldval;
 899	u32 rtt_threshold, rtt_us;
 900	u64 grow;
 901
 902	oldval = tp->rcvq_space.space;
 903	tp->rcvq_space.space = newval;
 904
 905	if (!READ_ONCE(net->ipv4.sysctl_tcp_moderate_rcvbuf) ||
 906	    (sk->sk_userlocks & SOCK_RCVBUF_LOCK))
 907		return;
 908
 909	/* DRS is always one RTT late. */
 910	rcvwin = newval << 1;
 911
 912	rtt_us = tp->rcv_rtt_est.rtt_us >> 3;
 913	rtt_threshold = READ_ONCE(net->ipv4.sysctl_tcp_rcvbuf_low_rtt);
 914	if (rtt_us < rtt_threshold) {
 915		/* For small RTT, we set @grow to rcvwin * rtt_us/rtt_threshold.
 916		 * It might take few additional ms to reach 'line rate',
 917		 * but will avoid sk_rcvbuf inflation and poor cache use.
 918		 */
 919		grow = div_u64((u64)rcvwin * rtt_us, rtt_threshold);
 920	} else {
 921		/* slow start: allow the sender to double its rate. */
 922		grow = div_u64(((u64)rcvwin << 1) * (newval - oldval), oldval);
 923	}
 924	rcvwin += grow;
 925
 926	if (!RB_EMPTY_ROOT(&tp->out_of_order_queue))
 927		rcvwin += TCP_SKB_CB(tp->ooo_last_skb)->end_seq - tp->rcv_nxt;
 928
 929	cap = READ_ONCE(net->ipv4.sysctl_tcp_rmem[2]);
 930
 931	rcvbuf = min_t(u32, tcp_space_from_win(sk, rcvwin), cap);
 932	if (rcvbuf > sk->sk_rcvbuf) {
 933		WRITE_ONCE(sk->sk_rcvbuf, rcvbuf);
 934		/* Make the window clamp follow along.  */
 935		WRITE_ONCE(tp->window_clamp,
 936			   tcp_win_from_space(sk, rcvbuf));
 937	}
 938}
 939/*
 940 * This function should be called every time data is copied to user space.
 941 * It calculates the appropriate TCP receive buffer space.
 942 */
 943void tcp_rcv_space_adjust(struct sock *sk)
 944{
 945	struct tcp_sock *tp = tcp_sk(sk);
 946	int time, inq, copied;
 947
 948	trace_tcp_rcv_space_adjust(sk);
 949
 950	if (unlikely(!tp->rcv_rtt_est.rtt_us))
 951		return;
 952
 953	/* We do not refresh tp->tcp_mstamp here.
 954	 * Some platforms have expensive ktime_get() implementations.
 955	 * Using the last cached value is enough for DRS.
 956	 */
 957	time = tcp_stamp_us_delta(tp->tcp_mstamp, tp->rcvq_space.time);
 958	if (time < (tp->rcv_rtt_est.rtt_us >> 3))
 959		return;
 960
 961	/* Number of bytes copied to user in last RTT */
 962	copied = tp->copied_seq - tp->rcvq_space.seq;
 963	/* Number of bytes in receive queue. */
 964	inq = tp->rcv_nxt - tp->copied_seq;
 965	copied -= inq;
 966	if (copied <= tp->rcvq_space.space)
 967		goto new_measure;
 968
 969	trace_tcp_rcvbuf_grow(sk, time);
 970
 971	tcp_rcvbuf_grow(sk, copied);
 972
 973new_measure:
 974	tp->rcvq_space.seq = tp->copied_seq;
 975	tp->rcvq_space.time = tp->tcp_mstamp;
 976}
 977
 978static void tcp_save_lrcv_flowlabel(struct sock *sk, const struct sk_buff *skb)
 979{
 980#if IS_ENABLED(CONFIG_IPV6)
 981	struct inet_connection_sock *icsk = inet_csk(sk);
 982
 983	if (skb->protocol == htons(ETH_P_IPV6))
 984		icsk->icsk_ack.lrcv_flowlabel = ntohl(ip6_flowlabel(ipv6_hdr(skb)));
 985#endif
 986}
 987
 988/* There is something which you must keep in mind when you analyze the
 989 * behavior of the tp->ato delayed ack timeout interval.  When a
 990 * connection starts up, we want to ack as quickly as possible.  The
 991 * problem is that "good" TCP's do slow start at the beginning of data
 992 * transmission.  The means that until we send the first few ACK's the
 993 * sender will sit on his end and only queue most of his data, because
 994 * he can only send snd_cwnd unacked packets at any given time.  For
 995 * each ACK we send, he increments snd_cwnd and transmits more of his
 996 * queue.  -DaveM
 997 */
 998static void tcp_event_data_recv(struct sock *sk, struct sk_buff *skb)
 999{
1000	struct tcp_sock *tp = tcp_sk(sk);
1001	struct inet_connection_sock *icsk = inet_csk(sk);
1002	u32 now;
1003
1004	inet_csk_schedule_ack(sk);
1005
1006	tcp_measure_rcv_mss(sk, skb);
1007
1008	tcp_rcv_rtt_measure(tp);
1009
1010	now = tcp_jiffies32;
1011
1012	if (!icsk->icsk_ack.ato) {
1013		/* The _first_ data packet received, initialize
1014		 * delayed ACK engine.
1015		 */
1016		tcp_incr_quickack(sk, TCP_MAX_QUICKACKS);
1017		icsk->icsk_ack.ato = TCP_ATO_MIN;
1018	} else {
1019		int m = now - icsk->icsk_ack.lrcvtime;
1020
1021		if (m <= TCP_ATO_MIN / 2) {
1022			/* The fastest case is the first. */
1023			icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + TCP_ATO_MIN / 2;
1024		} else if (m < icsk->icsk_ack.ato) {
1025			icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + m;
1026			if (icsk->icsk_ack.ato > icsk->icsk_rto)
1027				icsk->icsk_ack.ato = icsk->icsk_rto;
1028		} else if (m > icsk->icsk_rto) {
1029			/* Too long gap. Apparently sender failed to
1030			 * restart window, so that we send ACKs quickly.
1031			 */
1032			tcp_incr_quickack(sk, TCP_MAX_QUICKACKS);
1033		}
1034	}
1035	icsk->icsk_ack.lrcvtime = now;
1036	tcp_save_lrcv_flowlabel(sk, skb);
1037
1038	tcp_data_ecn_check(sk, skb);
1039
1040	if (skb->len >= 128)
1041		tcp_grow_window(sk, skb, true);
1042}
1043
1044/* Called to compute a smoothed rtt estimate. The data fed to this
1045 * routine either comes from timestamps, or from segments that were
1046 * known _not_ to have been retransmitted [see Karn/Partridge
1047 * Proceedings SIGCOMM 87]. The algorithm is from the SIGCOMM 88
1048 * piece by Van Jacobson.
1049 * NOTE: the next three routines used to be one big routine.
1050 * To save cycles in the RFC 1323 implementation it was better to break
1051 * it up into three procedures. -- erics
1052 */
1053static void tcp_rtt_estimator(struct sock *sk, long mrtt_us)
1054{
1055	struct tcp_sock *tp = tcp_sk(sk);
1056	long m = mrtt_us; /* RTT */
1057	u32 srtt = tp->srtt_us;
1058
1059	/*	The following amusing code comes from Jacobson's
1060	 *	article in SIGCOMM '88.  Note that rtt and mdev
1061	 *	are scaled versions of rtt and mean deviation.
1062	 *	This is designed to be as fast as possible
1063	 *	m stands for "measurement".
1064	 *
1065	 *	On a 1990 paper the rto value is changed to:
1066	 *	RTO = rtt + 4 * mdev
1067	 *
1068	 * Funny. This algorithm seems to be very broken.
1069	 * These formulae increase RTO, when it should be decreased, increase
1070	 * too slowly, when it should be increased quickly, decrease too quickly
1071	 * etc. I guess in BSD RTO takes ONE value, so that it is absolutely
1072	 * does not matter how to _calculate_ it. Seems, it was trap
1073	 * that VJ failed to avoid. 8)
1074	 */
1075	if (srtt != 0) {
1076		m -= (srtt >> 3);	/* m is now error in rtt est */
1077		srtt += m;		/* rtt = 7/8 rtt + 1/8 new */
1078		if (m < 0) {
1079			m = -m;		/* m is now abs(error) */
1080			m -= (tp->mdev_us >> 2);   /* similar update on mdev */
1081			/* This is similar to one of Eifel findings.
1082			 * Eifel blocks mdev updates when rtt decreases.
1083			 * This solution is a bit different: we use finer gain
1084			 * for mdev in this case (alpha*beta).
1085			 * Like Eifel it also prevents growth of rto,
1086			 * but also it limits too fast rto decreases,
1087			 * happening in pure Eifel.
1088			 */
1089			if (m > 0)
1090				m >>= 3;
1091		} else {
1092			m -= (tp->mdev_us >> 2);   /* similar update on mdev */
1093		}
1094		tp->mdev_us += m;		/* mdev = 3/4 mdev + 1/4 new */
1095		if (tp->mdev_us > tp->mdev_max_us) {
1096			tp->mdev_max_us = tp->mdev_us;
1097			if (tp->mdev_max_us > tp->rttvar_us)
1098				tp->rttvar_us = tp->mdev_max_us;
1099		}
1100		if (after(tp->snd_una, tp->rtt_seq)) {
1101			if (tp->mdev_max_us < tp->rttvar_us)
1102				tp->rttvar_us -= (tp->rttvar_us - tp->mdev_max_us) >> 2;
1103			tp->rtt_seq = tp->snd_nxt;
1104			tp->mdev_max_us = tcp_rto_min_us(sk);
1105
1106			tcp_bpf_rtt(sk, mrtt_us, srtt);
1107		}
1108	} else {
1109		/* no previous measure. */
1110		srtt = m << 3;		/* take the measured time to be rtt */
1111		tp->mdev_us = m << 1;	/* make sure rto = 3*rtt */
1112		tp->rttvar_us = max(tp->mdev_us, tcp_rto_min_us(sk));
1113		tp->mdev_max_us = tp->rttvar_us;
1114		tp->rtt_seq = tp->snd_nxt;
1115
1116		tcp_bpf_rtt(sk, mrtt_us, srtt);
1117	}
1118	tp->srtt_us = max(1U, srtt);
1119}
1120
1121void tcp_update_pacing_rate(struct sock *sk)
1122{
1123	const struct tcp_sock *tp = tcp_sk(sk);
1124	u64 rate;
1125
1126	/* set sk_pacing_rate to 200 % of current rate (mss * cwnd / srtt) */
1127	rate = (u64)tp->mss_cache * ((USEC_PER_SEC / 100) << 3);
1128
1129	/* current rate is (cwnd * mss) / srtt
1130	 * In Slow Start [1], set sk_pacing_rate to 200 % the current rate.
1131	 * In Congestion Avoidance phase, set it to 120 % the current rate.
1132	 *
1133	 * [1] : Normal Slow Start condition is (tp->snd_cwnd < tp->snd_ssthresh)
1134	 *	 If snd_cwnd >= (tp->snd_ssthresh / 2), we are approaching
1135	 *	 end of slow start and should slow down.
1136	 */
1137	if (tcp_snd_cwnd(tp) < tp->snd_ssthresh / 2)
1138		rate *= READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_pacing_ss_ratio);
1139	else
1140		rate *= READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_pacing_ca_ratio);
1141
1142	rate *= max(tcp_snd_cwnd(tp), tp->packets_out);
1143
1144	if (likely(tp->srtt_us))
1145		do_div(rate, tp->srtt_us);
1146
1147	/* WRITE_ONCE() is needed because sch_fq fetches sk_pacing_rate
1148	 * without any lock. We want to make sure compiler wont store
1149	 * intermediate values in this location.
1150	 */
1151	WRITE_ONCE(sk->sk_pacing_rate,
1152		   min_t(u64, rate, READ_ONCE(sk->sk_max_pacing_rate)));
1153}
1154
1155/* Calculate rto without backoff.  This is the second half of Van Jacobson's
1156 * routine referred to above.
1157 */
1158void tcp_set_rto(struct sock *sk)
1159{
1160	const struct tcp_sock *tp = tcp_sk(sk);
1161	/* Old crap is replaced with new one. 8)
1162	 *
1163	 * More seriously:
1164	 * 1. If rtt variance happened to be less 50msec, it is hallucination.
1165	 *    It cannot be less due to utterly erratic ACK generation made
1166	 *    at least by solaris and freebsd. "Erratic ACKs" has _nothing_
1167	 *    to do with delayed acks, because at cwnd>2 true delack timeout
1168	 *    is invisible. Actually, Linux-2.4 also generates erratic
1169	 *    ACKs in some circumstances.
1170	 */
1171	inet_csk(sk)->icsk_rto = __tcp_set_rto(tp);
1172
1173	/* 2. Fixups made earlier cannot be right.
1174	 *    If we do not estimate RTO correctly without them,
1175	 *    all the algo is pure shit and should be replaced
1176	 *    with correct one. It is exactly, which we pretend to do.
1177	 */
1178
1179	/* NOTE: clamping at TCP_RTO_MIN is not required, current algo
1180	 * guarantees that rto is higher.
1181	 */
1182	tcp_bound_rto(sk);
1183}
1184
1185__u32 tcp_init_cwnd(const struct tcp_sock *tp, const struct dst_entry *dst)
1186{
1187	__u32 cwnd = (dst ? dst_metric(dst, RTAX_INITCWND) : 0);
1188
1189	if (!cwnd)
1190		cwnd = TCP_INIT_CWND;
1191	return min_t(__u32, cwnd, tp->snd_cwnd_clamp);
1192}
1193
1194struct tcp_sacktag_state {
1195	/* Timestamps for earliest and latest never-retransmitted segment
1196	 * that was SACKed. RTO needs the earliest RTT to stay conservative,
1197	 * but congestion control should still get an accurate delay signal.
1198	 */
1199	u64	first_sackt;
1200	u64	last_sackt;
1201	u32	reord;
1202	u32	sack_delivered;
1203	u32	delivered_bytes;
1204	int	flag;
1205	unsigned int mss_now;
1206	struct rate_sample *rate;
1207};
1208
1209/* Take a notice that peer is sending D-SACKs. Skip update of data delivery
1210 * and spurious retransmission information if this DSACK is unlikely caused by
1211 * sender's action:
1212 * - DSACKed sequence range is larger than maximum receiver's window.
1213 * - Total no. of DSACKed segments exceed the total no. of retransmitted segs.
1214 */
1215static u32 tcp_dsack_seen(struct tcp_sock *tp, u32 start_seq,
1216			  u32 end_seq, struct tcp_sacktag_state *state)
1217{
1218	u32 seq_len, dup_segs = 1;
1219
1220	if (!before(start_seq, end_seq))
1221		return 0;
1222
1223	seq_len = end_seq - start_seq;
1224	/* Dubious DSACK: DSACKed range greater than maximum advertised rwnd */
1225	if (seq_len > tp->max_window)
1226		return 0;
1227	if (seq_len > tp->mss_cache)
1228		dup_segs = DIV_ROUND_UP(seq_len, tp->mss_cache);
1229	else if (tp->tlp_high_seq && tp->tlp_high_seq == end_seq)
1230		state->flag |= FLAG_DSACK_TLP;
1231
1232	tp->dsack_dups += dup_segs;
1233	/* Skip the DSACK if dup segs weren't retransmitted by sender */
1234	if (tp->dsack_dups > tp->total_retrans)
1235		return 0;
1236
1237	tp->rx_opt.sack_ok |= TCP_DSACK_SEEN;
1238	/* We increase the RACK ordering window in rounds where we receive
1239	 * DSACKs that may have been due to reordering causing RACK to trigger
1240	 * a spurious fast recovery. Thus RACK ignores DSACKs that happen
1241	 * without having seen reordering, or that match TLP probes (TLP
1242	 * is timer-driven, not triggered by RACK).
1243	 */
1244	if (tp->reord_seen && !(state->flag & FLAG_DSACK_TLP))
1245		tp->rack.dsack_seen = 1;
1246
1247	state->flag |= FLAG_DSACKING_ACK;
1248	/* A spurious retransmission is delivered */
1249	state->sack_delivered += dup_segs;
1250
1251	return dup_segs;
1252}
1253
1254/* It's reordering when higher sequence was delivered (i.e. sacked) before
1255 * some lower never-retransmitted sequence ("low_seq"). The maximum reordering
1256 * distance is approximated in full-mss packet distance ("reordering").
1257 */
1258static void tcp_check_sack_reordering(struct sock *sk, const u32 low_seq,
1259				      const int ts)
1260{
1261	struct tcp_sock *tp = tcp_sk(sk);
1262	const u32 mss = tp->mss_cache;
1263	u32 fack, metric;
1264
1265	fack = tcp_highest_sack_seq(tp);
1266	if (!before(low_seq, fack))
1267		return;
1268
1269	metric = fack - low_seq;
1270	if ((metric > tp->reordering * mss) && mss) {
1271#if FASTRETRANS_DEBUG > 1
1272		pr_debug("Disorder%d %d %u f%u s%u rr%d\n",
1273			 tp->rx_opt.sack_ok, inet_csk(sk)->icsk_ca_state,
1274			 tp->reordering,
1275			 0,
1276			 tp->sacked_out,
1277			 tp->undo_marker ? tp->undo_retrans : 0);
1278#endif
1279		tp->reordering = min_t(u32, (metric + mss - 1) / mss,
1280				       READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_max_reordering));
1281	}
1282
1283	/* This exciting event is worth to be remembered. 8) */
1284	tp->reord_seen++;
1285	NET_INC_STATS(sock_net(sk),
1286		      ts ? LINUX_MIB_TCPTSREORDER : LINUX_MIB_TCPSACKREORDER);
1287}
1288
1289 /* This must be called before lost_out or retrans_out are updated
1290  * on a new loss, because we want to know if all skbs previously
1291  * known to be lost have already been retransmitted, indicating
1292  * that this newly lost skb is our next skb to retransmit.
1293  */
1294static void tcp_verify_retransmit_hint(struct tcp_sock *tp, struct sk_buff *skb)
1295{
1296	if ((!tp->retransmit_skb_hint && tp->retrans_out >= tp->lost_out) ||
1297	    (tp->retransmit_skb_hint &&
1298	     before(TCP_SKB_CB(skb)->seq,
1299		    TCP_SKB_CB(tp->retransmit_skb_hint)->seq)))
1300		tp->retransmit_skb_hint = skb;
1301}
1302
1303/* Sum the number of packets on the wire we have marked as lost, and
1304 * notify the congestion control module that the given skb was marked lost.
1305 */
1306static void tcp_notify_skb_loss_event(struct tcp_sock *tp, const struct sk_buff *skb)
1307{
1308	tp->lost += tcp_skb_pcount(skb);
1309}
1310
1311void tcp_mark_skb_lost(struct sock *sk, struct sk_buff *skb)
1312{
1313	__u8 sacked = TCP_SKB_CB(skb)->sacked;
1314	struct tcp_sock *tp = tcp_sk(sk);
1315
1316	if (sacked & TCPCB_SACKED_ACKED)
1317		return;
1318
1319	tcp_verify_retransmit_hint(tp, skb);
1320	if (sacked & TCPCB_LOST) {
1321		if (sacked & TCPCB_SACKED_RETRANS) {
1322			/* Account for retransmits that are lost again */
1323			TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
1324			tp->retrans_out -= tcp_skb_pcount(skb);
1325			NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPLOSTRETRANSMIT,
1326				      tcp_skb_pcount(skb));
1327			tcp_notify_skb_loss_event(tp, skb);
1328		}
1329	} else {
1330		tp->lost_out += tcp_skb_pcount(skb);
1331		TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1332		tcp_notify_skb_loss_event(tp, skb);
1333	}
1334}
1335
1336/* This procedure tags the retransmission queue when SACKs arrive.
1337 *
1338 * We have three tag bits: SACKED(S), RETRANS(R) and LOST(L).
1339 * Packets in queue with these bits set are counted in variables
1340 * sacked_out, retrans_out and lost_out, correspondingly.
1341 *
1342 * Valid combinations are:
1343 * Tag  InFlight	Description
1344 * 0	1		- orig segment is in flight.
1345 * S	0		- nothing flies, orig reached receiver.
1346 * L	0		- nothing flies, orig lost by net.
1347 * R	2		- both orig and retransmit are in flight.
1348 * L|R	1		- orig is lost, retransmit is in flight.
1349 * S|R  1		- orig reached receiver, retrans is still in flight.
1350 * (L|S|R is logically valid, it could occur when L|R is sacked,
1351 *  but it is equivalent to plain S and code short-circuits it to S.
1352 *  L|S is logically invalid, it would mean -1 packet in flight 8))
1353 *
1354 * These 6 states form finite state machine, controlled by the following events:
1355 * 1. New ACK (+SACK) arrives. (tcp_sacktag_write_queue())
1356 * 2. Retransmission. (tcp_retransmit_skb(), tcp_xmit_retransmit_queue())
1357 * 3. Loss detection event of two flavors:
1358 *	A. Scoreboard estimator decided the packet is lost.
1359 *	   A'. Reno "three dupacks" marks head of queue lost.
1360 *	B. SACK arrives sacking SND.NXT at the moment, when the
1361 *	   segment was retransmitted.
1362 * 4. D-SACK added new rule: D-SACK changes any tag to S.
1363 *
1364 * It is pleasant to note, that state diagram turns out to be commutative,
1365 * so that we are allowed not to be bothered by order of our actions,
1366 * when multiple events arrive simultaneously. (see the function below).
1367 *
1368 * Reordering detection.
1369 * --------------------
1370 * Reordering metric is maximal distance, which a packet can be displaced
1371 * in packet stream. With SACKs we can estimate it:
1372 *
1373 * 1. SACK fills old hole and the corresponding segment was not
1374 *    ever retransmitted -> reordering. Alas, we cannot use it
1375 *    when segment was retransmitted.
1376 * 2. The last flaw is solved with D-SACK. D-SACK arrives
1377 *    for retransmitted and already SACKed segment -> reordering..
1378 * Both of these heuristics are not used in Loss state, when we cannot
1379 * account for retransmits accurately.
1380 *
1381 * SACK block validation.
1382 * ----------------------
1383 *
1384 * SACK block range validation checks that the received SACK block fits to
1385 * the expected sequence limits, i.e., it is between SND.UNA and SND.NXT.
1386 * Note that SND.UNA is not included to the range though being valid because
1387 * it means that the receiver is rather inconsistent with itself reporting
1388 * SACK reneging when it should advance SND.UNA. Such SACK block this is
1389 * perfectly valid, however, in light of RFC2018 which explicitly states
1390 * that "SACK block MUST reflect the newest segment.  Even if the newest
1391 * segment is going to be discarded ...", not that it looks very clever
1392 * in case of head skb. Due to potentional receiver driven attacks, we
1393 * choose to avoid immediate execution of a walk in write queue due to
1394 * reneging and defer head skb's loss recovery to standard loss recovery
1395 * procedure that will eventually trigger (nothing forbids us doing this).
1396 *
1397 * Implements also blockage to start_seq wrap-around. Problem lies in the
1398 * fact that though start_seq (s) is before end_seq (i.e., not reversed),
1399 * there's no guarantee that it will be before snd_nxt (n). The problem
1400 * happens when start_seq resides between end_seq wrap (e_w) and snd_nxt
1401 * wrap (s_w):
1402 *
1403 *         <- outs wnd ->                          <- wrapzone ->
1404 *         u     e      n                         u_w   e_w  s n_w
1405 *         |     |      |                          |     |   |  |
1406 * |<------------+------+----- TCP seqno space --------------+---------->|
1407 * ...-- <2^31 ->|                                           |<--------...
1408 * ...---- >2^31 ------>|                                    |<--------...
1409 *
1410 * Current code wouldn't be vulnerable but it's better still to discard such
1411 * crazy SACK blocks. Doing this check for start_seq alone closes somewhat
1412 * similar case (end_seq after snd_nxt wrap) as earlier reversed check in
1413 * snd_nxt wrap -> snd_una region will then become "well defined", i.e.,
1414 * equal to the ideal case (infinite seqno space without wrap caused issues).
1415 *
1416 * With D-SACK the lower bound is extended to cover sequence space below
1417 * SND.UNA down to undo_marker, which is the last point of interest. Yet
1418 * again, D-SACK block must not to go across snd_una (for the same reason as
1419 * for the normal SACK blocks, explained above). But there all simplicity
1420 * ends, TCP might receive valid D-SACKs below that. As long as they reside
1421 * fully below undo_marker they do not affect behavior in anyway and can
1422 * therefore be safely ignored. In rare cases (which are more or less
1423 * theoretical ones), the D-SACK will nicely cross that boundary due to skb
1424 * fragmentation and packet reordering past skb's retransmission. To consider
1425 * them correctly, the acceptable range must be extended even more though
1426 * the exact amount is rather hard to quantify. However, tp->max_window can
1427 * be used as an exaggerated estimate.
1428 */
1429static bool tcp_is_sackblock_valid(struct tcp_sock *tp, bool is_dsack,
1430				   u32 start_seq, u32 end_seq)
1431{
1432	/* Too far in future, or reversed (interpretation is ambiguous) */
1433	if (after(end_seq, tp->snd_nxt) || !before(start_seq, end_seq))
1434		return false;
1435
1436	/* Nasty start_seq wrap-around check (see comments above) */
1437	if (!before(start_seq, tp->snd_nxt))
1438		return false;
1439
1440	/* In outstanding window? ...This is valid exit for D-SACKs too.
1441	 * start_seq == snd_una is non-sensical (see comments above)
1442	 */
1443	if (after(start_seq, tp->snd_una))
1444		return true;
1445
1446	if (!is_dsack || !tp->undo_marker)
1447		return false;
1448
1449	/* ...Then it's D-SACK, and must reside below snd_una completely */
1450	if (after(end_seq, tp->snd_una))
1451		return false;
1452
1453	if (!before(start_seq, tp->undo_marker))
1454		return true;
1455
1456	/* Too old */
1457	if (!after(end_seq, tp->undo_marker))
1458		return false;
1459
1460	/* Undo_marker boundary crossing (overestimates a lot). Known already:
1461	 *   start_seq < undo_marker and end_seq >= undo_marker.
1462	 */
1463	return !before(start_seq, end_seq - tp->max_window);
1464}
1465
1466static bool tcp_check_dsack(struct sock *sk, const struct sk_buff *ack_skb,
1467			    struct tcp_sack_block_wire *sp, int num_sacks,
1468			    u32 prior_snd_una, struct tcp_sacktag_state *state)
1469{
1470	struct tcp_sock *tp = tcp_sk(sk);
1471	u32 start_seq_0 = get_unaligned_be32(&sp[0].start_seq);
1472	u32 end_seq_0 = get_unaligned_be32(&sp[0].end_seq);
1473	u32 dup_segs;
1474
1475	if (before(start_seq_0, TCP_SKB_CB(ack_skb)->ack_seq)) {
1476		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKRECV);
1477	} else if (num_sacks > 1) {
1478		u32 end_seq_1 = get_unaligned_be32(&sp[1].end_seq);
1479		u32 start_seq_1 = get_unaligned_be32(&sp[1].start_seq);
1480
1481		if (after(end_seq_0, end_seq_1) || before(start_seq_0, start_seq_1))
1482			return false;
1483		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKOFORECV);
1484	} else {
1485		return false;
1486	}
1487
1488	dup_segs = tcp_dsack_seen(tp, start_seq_0, end_seq_0, state);
1489	if (!dup_segs) {	/* Skip dubious DSACK */
1490		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKIGNOREDDUBIOUS);
1491		return false;
1492	}
1493
1494	NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPDSACKRECVSEGS, dup_segs);
1495
1496	/* D-SACK for already forgotten data... Do dumb counting. */
1497	if (tp->undo_marker && tp->undo_retrans > 0 &&
1498	    !after(end_seq_0, prior_snd_una) &&
1499	    after(end_seq_0, tp->undo_marker))
1500		tp->undo_retrans = max_t(int, 0, tp->undo_retrans - dup_segs);
1501
1502	return true;
1503}
1504
1505/* Check if skb is fully within the SACK block. In presence of GSO skbs,
1506 * the incoming SACK may not exactly match but we can find smaller MSS
1507 * aligned portion of it that matches. Therefore we might need to fragment
1508 * which may fail and creates some hassle (caller must handle error case
1509 * returns).
1510 *
1511 * FIXME: this could be merged to shift decision code
1512 */
1513static int tcp_match_skb_to_sack(struct sock *sk, struct sk_buff *skb,
1514				  u32 start_seq, u32 end_seq)
1515{
1516	int err;
1517	bool in_sack;
1518	unsigned int pkt_len;
1519	unsigned int mss;
1520
1521	in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
1522		  !before(end_seq, TCP_SKB_CB(skb)->end_seq);
1523
1524	if (tcp_skb_pcount(skb) > 1 && !in_sack &&
1525	    after(TCP_SKB_CB(skb)->end_seq, start_seq)) {
1526		mss = tcp_skb_mss(skb);
1527		in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq);
1528
1529		if (!in_sack) {
1530			pkt_len = start_seq - TCP_SKB_CB(skb)->seq;
1531			if (pkt_len < mss)
1532				pkt_len = mss;
1533		} else {
1534			pkt_len = end_seq - TCP_SKB_CB(skb)->seq;
1535			if (pkt_len < mss)
1536				return -EINVAL;
1537		}
1538
1539		/* Round if necessary so that SACKs cover only full MSSes
1540		 * and/or the remaining small portion (if present)
1541		 */
1542		if (pkt_len > mss) {
1543			unsigned int new_len = (pkt_len / mss) * mss;
1544			if (!in_sack && new_len < pkt_len)
1545				new_len += mss;
1546			pkt_len = new_len;
1547		}
1548
1549		if (pkt_len >= skb->len && !in_sack)
1550			return 0;
1551
1552		err = tcp_fragment(sk, TCP_FRAG_IN_RTX_QUEUE, skb,
1553				   pkt_len, mss, GFP_ATOMIC);
1554		if (err < 0)
1555			return err;
1556	}
1557
1558	return in_sack;
1559}
1560
1561/* Mark the given newly-SACKed range as such, adjusting counters and hints. */
1562static u8 tcp_sacktag_one(struct sock *sk,
1563			  struct tcp_sacktag_state *state, u8 sacked,
1564			  u32 start_seq, u32 end_seq,
1565			  int dup_sack, int pcount, u32 plen,
1566			  u64 xmit_time)
1567{
1568	struct tcp_sock *tp = tcp_sk(sk);
1569
1570	/* Account D-SACK for retransmitted packet. */
1571	if (dup_sack && (sacked & TCPCB_RETRANS)) {
1572		if (tp->undo_marker && tp->undo_retrans > 0 &&
1573		    after(end_seq, tp->undo_marker))
1574			tp->undo_retrans = max_t(int, 0, tp->undo_retrans - pcount);
1575		if ((sacked & TCPCB_SACKED_ACKED) &&
1576		    before(start_seq, state->reord))
1577				state->reord = start_seq;
1578	}
1579
1580	/* Nothing to do; acked frame is about to be dropped (was ACKed). */
1581	if (!after(end_seq, tp->snd_una))
1582		return sacked;
1583
1584	if (!(sacked & TCPCB_SACKED_ACKED)) {
1585		tcp_rack_advance(tp, sacked, end_seq, xmit_time);
1586
1587		if (sacked & TCPCB_SACKED_RETRANS) {
1588			/* If the segment is not tagged as lost,
1589			 * we do not clear RETRANS, believing
1590			 * that retransmission is still in flight.
1591			 */
1592			if (sacked & TCPCB_LOST) {
1593				sacked &= ~(TCPCB_LOST|TCPCB_SACKED_RETRANS);
1594				tp->lost_out -= pcount;
1595				tp->retrans_out -= pcount;
1596			}
1597		} else {
1598			if (!(sacked & TCPCB_RETRANS)) {
1599				/* New sack for not retransmitted frame,
1600				 * which was in hole. It is reordering.
1601				 */
1602				if (before(start_seq,
1603					   tcp_highest_sack_seq(tp)) &&
1604				    before(start_seq, state->reord))
1605					state->reord = start_seq;
1606
1607				if (!after(end_seq, tp->high_seq))
1608					state->flag |= FLAG_ORIG_SACK_ACKED;
1609				if (state->first_sackt == 0)
1610					state->first_sackt = xmit_time;
1611				state->last_sackt = xmit_time;
1612			}
1613
1614			if (sacked & TCPCB_LOST) {
1615				sacked &= ~TCPCB_LOST;
1616				tp->lost_out -= pcount;
1617			}
1618		}
1619
1620		sacked |= TCPCB_SACKED_ACKED;
1621		state->flag |= FLAG_DATA_SACKED;
1622		tp->sacked_out += pcount;
1623		/* Out-of-order packets delivered */
1624		state->sack_delivered += pcount;
1625		state->delivered_bytes += plen;
1626	}
1627
1628	/* D-SACK. We can detect redundant retransmission in S|R and plain R
1629	 * frames and clear it. undo_retrans is decreased above, L|R frames
1630	 * are accounted above as well.
1631	 */
1632	if (dup_sack && (sacked & TCPCB_SACKED_RETRANS)) {
1633		sacked &= ~TCPCB_SACKED_RETRANS;
1634		tp->retrans_out -= pcount;
1635	}
1636
1637	return sacked;
1638}
1639
1640/* Shift newly-SACKed bytes from this skb to the immediately previous
1641 * already-SACKed sk_buff. Mark the newly-SACKed bytes as such.
1642 */
1643static bool tcp_shifted_skb(struct sock *sk, struct sk_buff *prev,
1644			    struct sk_buff *skb,
1645			    struct tcp_sacktag_state *state,
1646			    unsigned int pcount, int shifted, int mss,
1647			    bool dup_sack)
1648{
1649	struct tcp_sock *tp = tcp_sk(sk);
1650	u32 start_seq = TCP_SKB_CB(skb)->seq;	/* start of newly-SACKed */
1651	u32 end_seq = start_seq + shifted;	/* end of newly-SACKed */
1652
1653	BUG_ON(!pcount);
1654
1655	/* Adjust counters and hints for the newly sacked sequence
1656	 * range but discard the return value since prev is already
1657	 * marked. We must tag the range first because the seq
1658	 * advancement below implicitly advances
1659	 * tcp_highest_sack_seq() when skb is highest_sack.
1660	 */
1661	tcp_sacktag_one(sk, state, TCP_SKB_CB(skb)->sacked,
1662			start_seq, end_seq, dup_sack, pcount, skb->len,
1663			tcp_skb_timestamp_us(skb));
1664	tcp_rate_skb_delivered(sk, skb, state->rate);
1665
1666	TCP_SKB_CB(prev)->end_seq += shifted;
1667	TCP_SKB_CB(skb)->seq += shifted;
1668
1669	tcp_skb_pcount_add(prev, pcount);
1670	WARN_ON_ONCE(tcp_skb_pcount(skb) < pcount);
1671	tcp_skb_pcount_add(skb, -pcount);
1672
1673	/* When we're adding to gso_segs == 1, gso_size will be zero,
1674	 * in theory this shouldn't be necessary but as long as DSACK
1675	 * code can come after this skb later on it's better to keep
1676	 * setting gso_size to something.
1677	 */
1678	if (!TCP_SKB_CB(prev)->tcp_gso_size)
1679		TCP_SKB_CB(prev)->tcp_gso_size = mss;
1680
1681	/* CHECKME: To clear or not to clear? Mimics normal skb currently */
1682	if (tcp_skb_pcount(skb) <= 1)
1683		TCP_SKB_CB(skb)->tcp_gso_size = 0;
1684
1685	/* Difference in this won't matter, both ACKed by the same cumul. ACK */
1686	TCP_SKB_CB(prev)->sacked |= (TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS);
1687
1688	if (skb->len > 0) {
1689		BUG_ON(!tcp_skb_pcount(skb));
1690		NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKSHIFTED);
1691		return false;
1692	}
1693
1694	/* Whole SKB was eaten :-) */
1695
1696	if (skb == tp->retransmit_skb_hint)
1697		tp->retransmit_skb_hint = prev;
1698
1699	TCP_SKB_CB(prev)->tcp_flags |= TCP_SKB_CB(skb)->tcp_flags;
1700	TCP_SKB_CB(prev)->eor = TCP_SKB_CB(skb)->eor;
1701	if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
1702		TCP_SKB_CB(prev)->end_seq++;
1703
1704	if (skb == tcp_highest_sack(sk))
1705		tcp_advance_highest_sack(sk, skb);
1706
1707	tcp_skb_collapse_tstamp(prev, skb);
1708	if (unlikely(TCP_SKB_CB(prev)->tx.delivered_mstamp))
1709		TCP_SKB_CB(prev)->tx.delivered_mstamp = 0;
1710
1711	tcp_rtx_queue_unlink_and_free(skb, sk);
1712
1713	NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKMERGED);
1714
1715	return true;
1716}
1717
1718/* I wish gso_size would have a bit more sane initialization than
1719 * something-or-zero which complicates things
1720 */
1721static int tcp_skb_seglen(const struct sk_buff *skb)
1722{
1723	return tcp_skb_pcount(skb) == 1 ? skb->len : tcp_skb_mss(skb);
1724}
1725
1726/* Shifting pages past head area doesn't work */
1727static int skb_can_shift(const struct sk_buff *skb)
1728{
1729	return !skb_headlen(skb) && skb_is_nonlinear(skb);
1730}
1731
1732int tcp_skb_shift(struct sk_buff *to, struct sk_buff *from,
1733		  int pcount, int shiftlen)
1734{
1735	/* TCP min gso_size is 8 bytes (TCP_MIN_GSO_SIZE)
1736	 * Since TCP_SKB_CB(skb)->tcp_gso_segs is 16 bits, we need
1737	 * to make sure not storing more than 65535 * 8 bytes per skb,
1738	 * even if current MSS is bigger.
1739	 */
1740	if (unlikely(to->len + shiftlen >= 65535 * TCP_MIN_GSO_SIZE))
1741		return 0;
1742	if (unlikely(tcp_skb_pcount(to) + pcount > 65535))
1743		return 0;
1744	return skb_shift(to, from, shiftlen);
1745}
1746
1747/* Try collapsing SACK blocks spanning across multiple skbs to a single
1748 * skb.
1749 */
1750static struct sk_buff *tcp_shift_skb_data(struct sock *sk, struct sk_buff *skb,
1751					  struct tcp_sacktag_state *state,
1752					  u32 start_seq, u32 end_seq,
1753					  bool dup_sack)
1754{
1755	struct tcp_sock *tp = tcp_sk(sk);
1756	struct sk_buff *prev;
1757	int mss;
1758	int pcount = 0;
1759	int len;
1760	int in_sack;
1761
1762	/* Normally R but no L won't result in plain S */
1763	if (!dup_sack &&
1764	    (TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_RETRANS)) == TCPCB_SACKED_RETRANS)
1765		goto fallback;
1766	if (!skb_can_shift(skb))
1767		goto fallback;
1768	/* This frame is about to be dropped (was ACKed). */
1769	if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una))
1770		goto fallback;
1771
1772	/* Can only happen with delayed DSACK + discard craziness */
1773	prev = skb_rb_prev(skb);
1774	if (!prev)
1775		goto fallback;
1776
1777	if ((TCP_SKB_CB(prev)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED)
1778		goto fallback;
1779
1780	if (!tcp_skb_can_collapse(prev, skb))
1781		goto fallback;
1782
1783	in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
1784		  !before(end_seq, TCP_SKB_CB(skb)->end_seq);
1785
1786	if (in_sack) {
1787		len = skb->len;
1788		pcount = tcp_skb_pcount(skb);
1789		mss = tcp_skb_seglen(skb);
1790
1791		/* TODO: Fix DSACKs to not fragment already SACKed and we can
1792		 * drop this restriction as unnecessary
1793		 */
1794		if (mss != tcp_skb_seglen(prev))
1795			goto fallback;
1796	} else {
1797		if (!after(TCP_SKB_CB(skb)->end_seq, start_seq))
1798			goto noop;
1799		/* CHECKME: This is non-MSS split case only?, this will
1800		 * cause skipped skbs due to advancing loop btw, original
1801		 * has that feature too
1802		 */
1803		if (tcp_skb_pcount(skb) <= 1)
1804			goto noop;
1805
1806		in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq);
1807		if (!in_sack) {
1808			/* TODO: head merge to next could be attempted here
1809			 * if (!after(TCP_SKB_CB(skb)->end_seq, end_seq)),
1810			 * though it might not be worth of the additional hassle
1811			 *
1812			 * ...we can probably just fallback to what was done
1813			 * previously. We could try merging non-SACKed ones
1814			 * as well but it probably isn't going to buy off
1815			 * because later SACKs might again split them, and
1816			 * it would make skb timestamp tracking considerably
1817			 * harder problem.
1818			 */
1819			goto fallback;
1820		}
1821
1822		len = end_seq - TCP_SKB_CB(skb)->seq;
1823		BUG_ON(len < 0);
1824		BUG_ON(len > skb->len);
1825
1826		/* MSS boundaries should be honoured or else pcount will
1827		 * severely break even though it makes things bit trickier.
1828		 * Optimize common case to avoid most of the divides
1829		 */
1830		mss = tcp_skb_mss(skb);
1831
1832		/* TODO: Fix DSACKs to not fragment already SACKed and we can
1833		 * drop this restriction as unnecessary
1834		 */
1835		if (mss != tcp_skb_seglen(prev))
1836			goto fallback;
1837
1838		if (len == mss) {
1839			pcount = 1;
1840		} else if (len < mss) {
1841			goto noop;
1842		} else {
1843			pcount = len / mss;
1844			len = pcount * mss;
1845		}
1846	}
1847
1848	/* tcp_sacktag_one() won't SACK-tag ranges below snd_una */
1849	if (!after(TCP_SKB_CB(skb)->seq + len, tp->snd_una))
1850		goto fallback;
1851
1852	if (!tcp_skb_shift(prev, skb, pcount, len))
1853		goto fallback;
1854	if (!tcp_shifted_skb(sk, prev, skb, state, pcount, len, mss, dup_sack))
1855		goto out;
1856
1857	/* Hole filled allows collapsing with the next as well, this is very
1858	 * useful when hole on every nth skb pattern happens
1859	 */
1860	skb = skb_rb_next(prev);
1861	if (!skb)
1862		goto out;
1863
1864	if (!skb_can_shift(skb) ||
1865	    ((TCP_SKB_CB(skb)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED) ||
1866	    (mss != tcp_skb_seglen(skb)))
1867		goto out;
1868
1869	if (!tcp_skb_can_collapse(prev, skb))
1870		goto out;
1871	len = skb->len;
1872	pcount = tcp_skb_pcount(skb);
1873	if (tcp_skb_shift(prev, skb, pcount, len))
1874		tcp_shifted_skb(sk, prev, skb, state, pcount,
1875				len, mss, 0);
1876
1877out:
1878	return prev;
1879
1880noop:
1881	return skb;
1882
1883fallback:
1884	NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKSHIFTFALLBACK);
1885	return NULL;
1886}
1887
1888static struct sk_buff *tcp_sacktag_walk(struct sk_buff *skb, struct sock *sk,
1889					struct tcp_sack_block *next_dup,
1890					struct tcp_sacktag_state *state,
1891					u32 start_seq, u32 end_seq,
1892					bool dup_sack_in)
1893{
1894	struct tcp_sock *tp = tcp_sk(sk);
1895	struct sk_buff *tmp;
1896
1897	skb_rbtree_walk_from(skb) {
1898		int in_sack = 0;
1899		bool dup_sack = dup_sack_in;
1900
1901		/* queue is in-order => we can short-circuit the walk early */
1902		if (!before(TCP_SKB_CB(skb)->seq, end_seq))
1903			break;
1904
1905		if (next_dup  &&
1906		    before(TCP_SKB_CB(skb)->seq, next_dup->end_seq)) {
1907			in_sack = tcp_match_skb_to_sack(sk, skb,
1908							next_dup->start_seq,
1909							next_dup->end_seq);
1910			if (in_sack > 0)
1911				dup_sack = true;
1912		}
1913
1914		/* skb reference here is a bit tricky to get right, since
1915		 * shifting can eat and free both this skb and the next,
1916		 * so not even _safe variant of the loop is enough.
1917		 */
1918		if (in_sack <= 0) {
1919			tmp = tcp_shift_skb_data(sk, skb, state,
1920						 start_seq, end_seq, dup_sack);
1921			if (tmp) {
1922				if (tmp != skb) {
1923					skb = tmp;
1924					continue;
1925				}
1926
1927				in_sack = 0;
1928			} else {
1929				in_sack = tcp_match_skb_to_sack(sk, skb,
1930								start_seq,
1931								end_seq);
1932			}
1933		}
1934
1935		if (unlikely(in_sack < 0))
1936			break;
1937
1938		if (in_sack) {
1939			TCP_SKB_CB(skb)->sacked =
1940				tcp_sacktag_one(sk,
1941						state,
1942						TCP_SKB_CB(skb)->sacked,
1943						TCP_SKB_CB(skb)->seq,
1944						TCP_SKB_CB(skb)->end_seq,
1945						dup_sack,
1946						tcp_skb_pcount(skb),
1947						skb->len,
1948						tcp_skb_timestamp_us(skb));
1949			tcp_rate_skb_delivered(sk, skb, state->rate);
1950			if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)
1951				list_del_init(&skb->tcp_tsorted_anchor);
1952
1953			if (!before(TCP_SKB_CB(skb)->seq,
1954				    tcp_highest_sack_seq(tp)))
1955				tcp_advance_highest_sack(sk, skb);
1956		}
1957	}
1958	return skb;
1959}
1960
1961static struct sk_buff *tcp_sacktag_bsearch(struct sock *sk, u32 seq)
1962{
1963	struct rb_node *parent, **p = &sk->tcp_rtx_queue.rb_node;
1964	struct sk_buff *skb;
1965
1966	while (*p) {
1967		parent = *p;
1968		skb = rb_to_skb(parent);
1969		if (before(seq, TCP_SKB_CB(skb)->seq)) {
1970			p = &parent->rb_left;
1971			continue;
1972		}
1973		if (!before(seq, TCP_SKB_CB(skb)->end_seq)) {
1974			p = &parent->rb_right;
1975			continue;
1976		}
1977		return skb;
1978	}
1979	return NULL;
1980}
1981
1982static struct sk_buff *tcp_sacktag_skip(struct sk_buff *skb, struct sock *sk,
1983					u32 skip_to_seq)
1984{
1985	if (skb && after(TCP_SKB_CB(skb)->seq, skip_to_seq))
1986		return skb;
1987
1988	return tcp_sacktag_bsearch(sk, skip_to_seq);
1989}
1990
1991static struct sk_buff *tcp_maybe_skipping_dsack(struct sk_buff *skb,
1992						struct sock *sk,
1993						struct tcp_sack_block *next_dup,
1994						struct tcp_sacktag_state *state,
1995						u32 skip_to_seq)
1996{
1997	if (!next_dup)
1998		return skb;
1999
2000	if (before(next_dup->start_seq, skip_to_seq)) {
2001		skb = tcp_sacktag_skip(skb, sk, next_dup->start_seq);
2002		skb = tcp_sacktag_walk(skb, sk, NULL, state,
2003				       next_dup->start_seq, next_dup->end_seq,
2004				       1);
2005	}
2006
2007	return skb;
2008}
2009
2010static int tcp_sack_cache_ok(const struct tcp_sock *tp, const struct tcp_sack_block *cache)
2011{
2012	return cache < tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache);
2013}
2014
2015static int
2016tcp_sacktag_write_queue(struct sock *sk, const struct sk_buff *ack_skb,
2017			u32 prior_snd_una, struct tcp_sacktag_state *state)
2018{
2019	struct tcp_sock *tp = tcp_sk(sk);
2020	const unsigned char *ptr = (skb_transport_header(ack_skb) +
2021				    TCP_SKB_CB(ack_skb)->sacked);
2022	struct tcp_sack_block_wire *sp_wire = (struct tcp_sack_block_wire *)(ptr+2);
2023	struct tcp_sack_block sp[TCP_NUM_SACKS];
2024	struct tcp_sack_block *cache;
2025	struct sk_buff *skb;
2026	int num_sacks = min(TCP_NUM_SACKS, (ptr[1] - TCPOLEN_SACK_BASE) >> 3);
2027	int used_sacks;
2028	bool found_dup_sack = false;
2029	int i, j;
2030	int first_sack_index;
2031
2032	state->flag = 0;
2033	state->reord = tp->snd_nxt;
2034
2035	if (!tp->sacked_out)
2036		tcp_highest_sack_reset(sk);
2037
2038	found_dup_sack = tcp_check_dsack(sk, ack_skb, sp_wire,
2039					 num_sacks, prior_snd_una, state);
2040
2041	/* Eliminate too old ACKs, but take into
2042	 * account more or less fresh ones, they can
2043	 * contain valid SACK info.
2044	 */
2045	if (before(TCP_SKB_CB(ack_skb)->ack_seq, prior_snd_una - tp->max_window))
2046		return 0;
2047
2048	if (!tp->packets_out)
2049		goto out;
2050
2051	used_sacks = 0;
2052	first_sack_index = 0;
2053	for (i = 0; i < num_sacks; i++) {
2054		bool dup_sack = !i && found_dup_sack;
2055
2056		sp[used_sacks].start_seq = get_unaligned_be32(&sp_wire[i].start_seq);
2057		sp[used_sacks].end_seq = get_unaligned_be32(&sp_wire[i].end_seq);
2058
2059		if (!tcp_is_sackblock_valid(tp, dup_sack,
2060					    sp[used_sacks].start_seq,
2061					    sp[used_sacks].end_seq)) {
2062			int mib_idx;
2063
2064			if (dup_sack) {
2065				if (!tp->undo_marker)
2066					mib_idx = LINUX_MIB_TCPDSACKIGNOREDNOUNDO;
2067				else
2068					mib_idx = LINUX_MIB_TCPDSACKIGNOREDOLD;
2069			} else {
2070				/* Don't count olds caused by ACK reordering */
2071				if ((TCP_SKB_CB(ack_skb)->ack_seq != tp->snd_una) &&
2072				    !after(sp[used_sacks].end_seq, tp->snd_una))
2073					continue;
2074				mib_idx = LINUX_MIB_TCPSACKDISCARD;
2075			}
2076
2077			NET_INC_STATS(sock_net(sk), mib_idx);
2078			if (i == 0)
2079				first_sack_index = -1;
2080			continue;
2081		}
2082
2083		/* Ignore very old stuff early */
2084		if (!after(sp[used_sacks].end_seq, prior_snd_una)) {
2085			if (i == 0)
2086				first_sack_index = -1;
2087			continue;
2088		}
2089
2090		used_sacks++;
2091	}
2092
2093	/* order SACK blocks to allow in order walk of the retrans queue */
2094	for (i = used_sacks - 1; i > 0; i--) {
2095		for (j = 0; j < i; j++) {
2096			if (after(sp[j].start_seq, sp[j + 1].start_seq)) {
2097				swap(sp[j], sp[j + 1]);
2098
2099				/* Track where the first SACK block goes to */
2100				if (j == first_sack_index)
2101					first_sack_index = j + 1;
2102			}
2103		}
2104	}
2105
2106	state->mss_now = tcp_current_mss(sk);
2107	skb = NULL;
2108	i = 0;
2109
2110	if (!tp->sacked_out) {
2111		/* It's already past, so skip checking against it */
2112		cache = tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache);
2113	} else {
2114		cache = tp->recv_sack_cache;
2115		/* Skip empty blocks in at head of the cache */
2116		while (tcp_sack_cache_ok(tp, cache) && !cache->start_seq &&
2117		       !cache->end_seq)
2118			cache++;
2119	}
2120
2121	while (i < used_sacks) {
2122		u32 start_seq = sp[i].start_seq;
2123		u32 end_seq = sp[i].end_seq;
2124		bool dup_sack = (found_dup_sack && (i == first_sack_index));
2125		struct tcp_sack_block *next_dup = NULL;
2126
2127		if (found_dup_sack && ((i + 1) == first_sack_index))
2128			next_dup = &sp[i + 1];
2129
2130		/* Skip too early cached blocks */
2131		while (tcp_sack_cache_ok(tp, cache) &&
2132		       !before(start_seq, cache->end_seq))
2133			cache++;
2134
2135		/* Can skip some work by looking recv_sack_cache? */
2136		if (tcp_sack_cache_ok(tp, cache) && !dup_sack &&
2137		    after(end_seq, cache->start_seq)) {
2138
2139			/* Head todo? */
2140			if (before(start_seq, cache->start_seq)) {
2141				skb = tcp_sacktag_skip(skb, sk, start_seq);
2142				skb = tcp_sacktag_walk(skb, sk, next_dup,
2143						       state,
2144						       start_seq,
2145						       cache->start_seq,
2146						       dup_sack);
2147			}
2148
2149			/* Rest of the block already fully processed? */
2150			if (!after(end_seq, cache->end_seq))
2151				goto advance_sp;
2152
2153			skb = tcp_maybe_skipping_dsack(skb, sk, next_dup,
2154						       state,
2155						       cache->end_seq);
2156
2157			/* ...tail remains todo... */
2158			if (tcp_highest_sack_seq(tp) == cache->end_seq) {
2159				/* ...but better entrypoint exists! */
2160				skb = tcp_highest_sack(sk);
2161				if (!skb)
2162					break;
2163				cache++;
2164				goto walk;
2165			}
2166
2167			skb = tcp_sacktag_skip(skb, sk, cache->end_seq);
2168			/* Check overlap against next cached too (past this one already) */
2169			cache++;
2170			continue;
2171		}
2172
2173		if (!before(start_seq, tcp_highest_sack_seq(tp))) {
2174			skb = tcp_highest_sack(sk);
2175			if (!skb)
2176				break;
2177		}
2178		skb = tcp_sacktag_skip(skb, sk, start_seq);
2179
2180walk:
2181		skb = tcp_sacktag_walk(skb, sk, next_dup, state,
2182				       start_seq, end_seq, dup_sack);
2183
2184advance_sp:
2185		i++;
2186	}
2187
2188	/* Clear the head of the cache sack blocks so we can skip it next time */
2189	for (i = 0; i < ARRAY_SIZE(tp->recv_sack_cache) - used_sacks; i++) {
2190		tp->recv_sack_cache[i].start_seq = 0;
2191		tp->recv_sack_cache[i].end_seq = 0;
2192	}
2193	for (j = 0; j < used_sacks; j++)
2194		tp->recv_sack_cache[i++] = sp[j];
2195
2196	if (inet_csk(sk)->icsk_ca_state != TCP_CA_Loss || tp->undo_marker)
2197		tcp_check_sack_reordering(sk, state->reord, 0);
2198
2199	tcp_verify_left_out(tp);
2200out:
2201
2202#if FASTRETRANS_DEBUG > 0
2203	WARN_ON((int)tp->sacked_out < 0);
2204	WARN_ON((int)tp->lost_out < 0);
2205	WARN_ON((int)tp->retrans_out < 0);
2206	WARN_ON((int)tcp_packets_in_flight(tp) < 0);
2207#endif
2208	return state->flag;
2209}
2210
2211/* Limits sacked_out so that sum with lost_out isn't ever larger than
2212 * packets_out. Returns false if sacked_out adjustement wasn't necessary.
2213 */
2214static bool tcp_limit_reno_sacked(struct tcp_sock *tp)
2215{
2216	u32 holes;
2217
2218	holes = max(tp->lost_out, 1U);
2219	holes = min(holes, tp->packets_out);
2220
2221	if ((tp->sacked_out + holes) > tp->packets_out) {
2222		tp->sacked_out = tp->packets_out - holes;
2223		return true;
2224	}
2225	return false;
2226}
2227
2228/* If we receive more dupacks than we expected counting segments
2229 * in assumption of absent reordering, interpret this as reordering.
2230 * The only another reason could be bug in receiver TCP.
2231 */
2232static void tcp_check_reno_reordering(struct sock *sk, const int addend)
2233{
2234	struct tcp_sock *tp = tcp_sk(sk);
2235
2236	if (!tcp_limit_reno_sacked(tp))
2237		return;
2238
2239	tp->reordering = min_t(u32, tp->packets_out + addend,
2240			       READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_max_reordering));
2241	tp->reord_seen++;
2242	NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPRENOREORDER);
2243}
2244
2245/* Emulate SACKs for SACKless connection: account for a new dupack. */
2246
2247static void tcp_add_reno_sack(struct sock *sk, int num_dupack, bool ece_ack)
2248{
2249	if (num_dupack) {
2250		struct tcp_sock *tp = tcp_sk(sk);
2251		u32 prior_sacked = tp->sacked_out;
2252		s32 delivered;
2253
2254		tp->sacked_out += num_dupack;
2255		tcp_check_reno_reordering(sk, 0);
2256		delivered = tp->sacked_out - prior_sacked;
2257		if (delivered > 0)
2258			tcp_count_delivered(tp, delivered, ece_ack);
2259		tcp_verify_left_out(tp);
2260	}
2261}
2262
2263/* Account for ACK, ACKing some data in Reno Recovery phase. */
2264
2265static void tcp_remove_reno_sacks(struct sock *sk, int acked, bool ece_ack)
2266{
2267	struct tcp_sock *tp = tcp_sk(sk);
2268
2269	if (acked > 0) {
2270		/* One ACK acked hole. The rest eat duplicate ACKs. */
2271		tcp_count_delivered(tp, max_t(int, acked - tp->sacked_out, 1),
2272				    ece_ack);
2273		if (acked - 1 >= tp->sacked_out)
2274			tp->sacked_out = 0;
2275		else
2276			tp->sacked_out -= acked - 1;
2277	}
2278	tcp_check_reno_reordering(sk, acked);
2279	tcp_verify_left_out(tp);
2280}
2281
2282static inline void tcp_reset_reno_sack(struct tcp_sock *tp)
2283{
2284	tp->sacked_out = 0;
2285}
2286
2287void tcp_clear_retrans(struct tcp_sock *tp)
2288{
2289	tp->retrans_out = 0;
2290	tp->lost_out = 0;
2291	tp->undo_marker = 0;
2292	tp->undo_retrans = -1;
2293	tp->sacked_out = 0;
2294	tp->rto_stamp = 0;
2295	tp->total_rto = 0;
2296	tp->total_rto_recoveries = 0;
2297	tp->total_rto_time = 0;
2298}
2299
2300static inline void tcp_init_undo(struct tcp_sock *tp)
2301{
2302	tp->undo_marker = tp->snd_una;
2303
2304	/* Retransmission still in flight may cause DSACKs later. */
2305	/* First, account for regular retransmits in flight: */
2306	tp->undo_retrans = tp->retrans_out;
2307	/* Next, account for TLP retransmits in flight: */
2308	if (tp->tlp_high_seq && tp->tlp_retrans)
2309		tp->undo_retrans++;
2310	/* Finally, avoid 0, because undo_retrans==0 means "can undo now": */
2311	if (!tp->undo_retrans)
2312		tp->undo_retrans = -1;
2313}
2314
2315/* If we detect SACK reneging, forget all SACK information
2316 * and reset tags completely, otherwise preserve SACKs. If receiver
2317 * dropped its ofo queue, we will know this due to reneging detection.
2318 */
2319static void tcp_timeout_mark_lost(struct sock *sk)
2320{
2321	struct tcp_sock *tp = tcp_sk(sk);
2322	struct sk_buff *skb, *head;
2323	bool is_reneg;			/* is receiver reneging on SACKs? */
2324
2325	head = tcp_rtx_queue_head(sk);
2326	is_reneg = head && (TCP_SKB_CB(head)->sacked & TCPCB_SACKED_ACKED);
2327	if (is_reneg) {
2328		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPSACKRENEGING);
2329		tp->sacked_out = 0;
2330		/* Mark SACK reneging until we recover from this loss event. */
2331		tp->is_sack_reneg = 1;
2332	} else if (tcp_is_reno(tp)) {
2333		tcp_reset_reno_sack(tp);
2334	}
2335
2336	skb = head;
2337	skb_rbtree_walk_from(skb) {
2338		if (is_reneg)
2339			TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_ACKED;
2340		else if (skb != head && tcp_rack_skb_timeout(tp, skb, 0) > 0)
2341			continue; /* Don't mark recently sent ones lost yet */
2342		tcp_mark_skb_lost(sk, skb);
2343	}
2344	tcp_verify_left_out(tp);
2345	tcp_clear_all_retrans_hints(tp);
2346}
2347
2348/* Enter Loss state. */
2349void tcp_enter_loss(struct sock *sk)
2350{
2351	const struct inet_connection_sock *icsk = inet_csk(sk);
2352	struct tcp_sock *tp = tcp_sk(sk);
2353	struct net *net = sock_net(sk);
2354	bool new_recovery = icsk->icsk_ca_state < TCP_CA_Recovery;
2355	u8 reordering;
2356
2357	tcp_timeout_mark_lost(sk);
2358
2359	/* Reduce ssthresh if it has not yet been made inside this window. */
2360	if (icsk->icsk_ca_state <= TCP_CA_Disorder ||
2361	    !after(tp->high_seq, tp->snd_una) ||
2362	    (icsk->icsk_ca_state == TCP_CA_Loss && !icsk->icsk_retransmits)) {
2363		tp->prior_ssthresh = tcp_current_ssthresh(sk);
2364		tp->prior_cwnd = tcp_snd_cwnd(tp);
2365		tp->snd_ssthresh = icsk->icsk_ca_ops->ssthresh(sk);
2366		tcp_ca_event(sk, CA_EVENT_LOSS);
2367		tcp_init_undo(tp);
2368	}
2369	tcp_snd_cwnd_set(tp, tcp_packets_in_flight(tp) + 1);
2370	tp->snd_cwnd_cnt   = 0;
2371	tp->snd_cwnd_stamp = tcp_jiffies32;
2372
2373	/* Timeout in disordered state after receiving substantial DUPACKs
2374	 * suggests that the degree of reordering is over-estimated.
2375	 */
2376	reordering = READ_ONCE(net->ipv4.sysctl_tcp_reordering);
2377	if (icsk->icsk_ca_state <= TCP_CA_Disorder &&
2378	    tp->sacked_out >= reordering)
2379		tp->reordering = min_t(unsigned int, tp->reordering,
2380				       reordering);
2381
2382	tcp_set_ca_state(sk, TCP_CA_Loss);
2383	tp->high_seq = tp->snd_nxt;
2384	tp->tlp_high_seq = 0;
2385	tcp_ecn_queue_cwr(tp);
2386
2387	/* F-RTO RFC5682 sec 3.1 step 1: retransmit SND.UNA if no previous
2388	 * loss recovery is underway except recurring timeout(s) on
2389	 * the same SND.UNA (sec 3.2). Disable F-RTO on path MTU probing
2390	 */
2391	tp->frto = READ_ONCE(net->ipv4.sysctl_tcp_frto) &&
2392		   (new_recovery || icsk->icsk_retransmits) &&
2393		   !inet_csk(sk)->icsk_mtup.probe_size;
2394}
2395
2396/* If ACK arrived pointing to a remembered SACK, it means that our
2397 * remembered SACKs do not reflect real state of receiver i.e.
2398 * receiver _host_ is heavily congested (or buggy).
2399 *
2400 * To avoid big spurious retransmission bursts due to transient SACK
2401 * scoreboard oddities that look like reneging, we give the receiver a
2402 * little time (max(RTT/2, 10ms)) to send us some more ACKs that will
2403 * restore sanity to the SACK scoreboard. If the apparent reneging
2404 * persists until this RTO then we'll clear the SACK scoreboard.
2405 */
2406static bool tcp_check_sack_reneging(struct sock *sk, int *ack_flag)
2407{
2408	if (*ack_flag & FLAG_SACK_RENEGING &&
2409	    *ack_flag & FLAG_SND_UNA_ADVANCED) {
2410		struct tcp_sock *tp = tcp_sk(sk);
2411		unsigned long delay = max(usecs_to_jiffies(tp->srtt_us >> 4),
2412					  msecs_to_jiffies(10));
2413
2414		tcp_reset_xmit_timer(sk, ICSK_TIME_RETRANS, delay, false);
2415		*ack_flag &= ~FLAG_SET_XMIT_TIMER;
2416		return true;
2417	}
2418	return false;
2419}
2420
2421/* Linux NewReno/SACK/ECN state machine.
2422 * --------------------------------------
2423 *
2424 * "Open"	Normal state, no dubious events, fast path.
2425 * "Disorder"   In all the respects it is "Open",
2426 *		but requires a bit more attention. It is entered when
2427 *		we see some SACKs or dupacks. It is split of "Open"
2428 *		mainly to move some processing from fast path to slow one.
2429 * "CWR"	CWND was reduced due to some Congestion Notification event.
2430 *		It can be ECN, ICMP source quench, local device congestion.
2431 * "Recovery"	CWND was reduced, we are fast-retransmitting.
2432 * "Loss"	CWND was reduced due to RTO timeout or SACK reneging.
2433 *
2434 * tcp_fastretrans_alert() is entered:
2435 * - each incoming ACK, if state is not "Open"
2436 * - when arrived ACK is unusual, namely:
2437 *	* SACK
2438 *	* Duplicate ACK.
2439 *	* ECN ECE.
2440 *
2441 * Counting packets in flight is pretty simple.
2442 *
2443 *	in_flight = packets_out - left_out + retrans_out
2444 *
2445 *	packets_out is SND.NXT-SND.UNA counted in packets.
2446 *
2447 *	retrans_out is number of retransmitted segments.
2448 *
2449 *	left_out is number of segments left network, but not ACKed yet.
2450 *
2451 *		left_out = sacked_out + lost_out
2452 *
2453 *     sacked_out: Packets, which arrived to receiver out of order
2454 *		   and hence not ACKed. With SACKs this number is simply
2455 *		   amount of SACKed data. Even without SACKs
2456 *		   it is easy to give pretty reliable estimate of this number,
2457 *		   counting duplicate ACKs.
2458 *
2459 *       lost_out: Packets lost by network. TCP has no explicit
2460 *		   "loss notification" feedback from network (for now).
2461 *		   It means that this number can be only _guessed_.
2462 *		   Actually, it is the heuristics to predict lossage that
2463 *		   distinguishes different algorithms.
2464 *
2465 *	F.e. after RTO, when all the queue is considered as lost,
2466 *	lost_out = packets_out and in_flight = retrans_out.
2467 *
2468 *		Essentially, we have now a few algorithms detecting
2469 *		lost packets.
2470 *
2471 *		If the receiver supports SACK:
2472 *
2473 *		RACK (RFC8985): RACK is a newer loss detection algorithm
2474 *		(2017-) that checks timing instead of counting DUPACKs.
2475 *		Essentially a packet is considered lost if it's not S/ACKed
2476 *		after RTT + reordering_window, where both metrics are
2477 *		dynamically measured and adjusted. This is implemented in
2478 *		tcp_rack_mark_lost.
2479 *
2480 *		If the receiver does not support SACK:
2481 *
2482 *		NewReno (RFC6582): in Recovery we assume that one segment
2483 *		is lost (classic Reno). While we are in Recovery and
2484 *		a partial ACK arrives, we assume that one more packet
2485 *		is lost (NewReno). This heuristics are the same in NewReno
2486 *		and SACK.
2487 *
2488 * The really tricky (and requiring careful tuning) part of the algorithm
2489 * is hidden in the RACK code in tcp_recovery.c and tcp_xmit_retransmit_queue().
2490 * The first determines the moment _when_ we should reduce CWND and,
2491 * hence, slow down forward transmission. In fact, it determines the moment
2492 * when we decide that hole is caused by loss, rather than by a reorder.
2493 *
2494 * tcp_xmit_retransmit_queue() decides, _what_ we should retransmit to fill
2495 * holes, caused by lost packets.
2496 *
2497 * And the most logically complicated part of algorithm is undo
2498 * heuristics. We detect false retransmits due to both too early
2499 * fast retransmit (reordering) and underestimated RTO, analyzing
2500 * timestamps and D-SACKs. When we detect that some segments were
2501 * retransmitted by mistake and CWND reduction was wrong, we undo
2502 * window reduction and abort recovery phase. This logic is hidden
2503 * inside several functions named tcp_try_undo_<something>.
2504 */
2505
2506/* This function decides, when we should leave Disordered state
2507 * and enter Recovery phase, reducing congestion window.
2508 *
2509 * Main question: may we further continue forward transmission
2510 * with the same cwnd?
2511 */
2512static bool tcp_time_to_recover(const struct tcp_sock *tp)
2513{
2514	/* Has loss detection marked at least one packet lost? */
2515	return tp->lost_out != 0;
2516}
2517
2518static bool tcp_tsopt_ecr_before(const struct tcp_sock *tp, u32 when)
2519{
2520	return tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr &&
2521	       before(tp->rx_opt.rcv_tsecr, when);
2522}
2523
2524/* skb is spurious retransmitted if the returned timestamp echo
2525 * reply is prior to the skb transmission time
2526 */
2527static bool tcp_skb_spurious_retrans(const struct tcp_sock *tp,
2528				     const struct sk_buff *skb)
2529{
2530	return (TCP_SKB_CB(skb)->sacked & TCPCB_RETRANS) &&
2531	       tcp_tsopt_ecr_before(tp, tcp_skb_timestamp_ts(tp->tcp_usec_ts, skb));
2532}
2533
2534/* Nothing was retransmitted or returned timestamp is less
2535 * than timestamp of the first retransmission.
2536 */
2537static inline bool tcp_packet_delayed(const struct tcp_sock *tp)
2538{
2539	const struct sock *sk = (const struct sock *)tp;
2540
2541	/* Received an echoed timestamp before the first retransmission? */
2542	if (tp->retrans_stamp)
2543		return tcp_tsopt_ecr_before(tp, tp->retrans_stamp);
2544
2545	/* We set tp->retrans_stamp upon the first retransmission of a loss
2546	 * recovery episode, so normally if tp->retrans_stamp is 0 then no
2547	 * retransmission has happened yet (likely due to TSQ, which can cause
2548	 * fast retransmits to be delayed). So if snd_una advanced while
2549	 * (tp->retrans_stamp is 0 then apparently a packet was merely delayed,
2550	 * not lost. But there are exceptions where we retransmit but then
2551	 * clear tp->retrans_stamp, so we check for those exceptions.
2552	 */
2553
2554	/* (1) For non-SACK connections, tcp_is_non_sack_preventing_reopen()
2555	 * clears tp->retrans_stamp when snd_una == high_seq.
2556	 */
2557	if (!tcp_is_sack(tp) && !before(tp->snd_una, tp->high_seq))
2558		return false;
2559
2560	/* (2) In TCP_SYN_SENT tcp_clean_rtx_queue() clears tp->retrans_stamp
2561	 * when setting FLAG_SYN_ACKED is set, even if the SYN was
2562	 * retransmitted.
2563	 */
2564	if (sk->sk_state == TCP_SYN_SENT)
2565		return false;
2566
2567	return true;	/* tp->retrans_stamp is zero; no retransmit yet */
2568}
2569
2570/* Undo procedures. */
2571
2572/* We can clear retrans_stamp when there are no retransmissions in the
2573 * window. It would seem that it is trivially available for us in
2574 * tp->retrans_out, however, that kind of assumptions doesn't consider
2575 * what will happen if errors occur when sending retransmission for the
2576 * second time. ...It could the that such segment has only
2577 * TCPCB_EVER_RETRANS set at the present time. It seems that checking
2578 * the head skb is enough except for some reneging corner cases that
2579 * are not worth the effort.
2580 *
2581 * Main reason for all this complexity is the fact that connection dying
2582 * time now depends on the validity of the retrans_stamp, in particular,
2583 * that successive retransmissions of a segment must not advance
2584 * retrans_stamp under any conditions.
2585 */
2586static bool tcp_any_retrans_done(const struct sock *sk)
2587{
2588	const struct tcp_sock *tp = tcp_sk(sk);
2589	struct sk_buff *skb;
2590
2591	if (tp->retrans_out)
2592		return true;
2593
2594	skb = tcp_rtx_queue_head(sk);
2595	if (unlikely(skb && TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS))
2596		return true;
2597
2598	return false;
2599}
2600
2601/* If loss recovery is finished and there are no retransmits out in the
2602 * network, then we clear retrans_stamp so that upon the next loss recovery
2603 * retransmits_timed_out() and timestamp-undo are using the correct value.
2604 */
2605static void tcp_retrans_stamp_cleanup(struct sock *sk)
2606{
2607	if (!tcp_any_retrans_done(sk))
2608		tcp_sk(sk)->retrans_stamp = 0;
2609}
2610
2611static void DBGUNDO(struct sock *sk, const char *msg)
2612{
2613#if FASTRETRANS_DEBUG > 1
2614	struct tcp_sock *tp = tcp_sk(sk);
2615	struct inet_sock *inet = inet_sk(sk);
2616
2617	if (sk->sk_family == AF_INET) {
2618		pr_debug("Undo %s %pI4/%u c%u l%u ss%u/%u p%u\n",
2619			 msg,
2620			 &inet->inet_daddr, ntohs(inet->inet_dport),
2621			 tcp_snd_cwnd(tp), tcp_left_out(tp),
2622			 tp->snd_ssthresh, tp->prior_ssthresh,
2623			 tp->packets_out);
2624	}
2625#if IS_ENABLED(CONFIG_IPV6)
2626	else if (sk->sk_family == AF_INET6) {
2627		pr_debug("Undo %s %pI6/%u c%u l%u ss%u/%u p%u\n",
2628			 msg,
2629			 &sk->sk_v6_daddr, ntohs(inet->inet_dport),
2630			 tcp_snd_cwnd(tp), tcp_left_out(tp),
2631			 tp->snd_ssthresh, tp->prior_ssthresh,
2632			 tp->packets_out);
2633	}
2634#endif
2635#endif
2636}
2637
2638static void tcp_undo_cwnd_reduction(struct sock *sk, bool unmark_loss)
2639{
2640	struct tcp_sock *tp = tcp_sk(sk);
2641
2642	if (unmark_loss) {
2643		struct sk_buff *skb;
2644
2645		skb_rbtree_walk(skb, &sk->tcp_rtx_queue) {
2646			TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
2647		}
2648		tp->lost_out = 0;
2649		tcp_clear_all_retrans_hints(tp);
2650	}
2651
2652	if (tp->prior_ssthresh) {
2653		const struct inet_connection_sock *icsk = inet_csk(sk);
2654
2655		tcp_snd_cwnd_set(tp, icsk->icsk_ca_ops->undo_cwnd(sk));
2656
2657		if (tp->prior_ssthresh > tp->snd_ssthresh) {
2658			tp->snd_ssthresh = tp->prior_ssthresh;
2659			tcp_ecn_withdraw_cwr(tp);
2660		}
2661	}
2662	tp->snd_cwnd_stamp = tcp_jiffies32;
2663	tp->undo_marker = 0;
2664	tp->rack.advanced = 1; /* Force RACK to re-exam losses */
2665}
2666
2667static inline bool tcp_may_undo(const struct tcp_sock *tp)
2668{
2669	return tp->undo_marker && (!tp->undo_retrans || tcp_packet_delayed(tp));
2670}
2671
2672static bool tcp_is_non_sack_preventing_reopen(struct sock *sk)
2673{
2674	struct tcp_sock *tp = tcp_sk(sk);
2675
2676	if (tp->snd_una == tp->high_seq && tcp_is_reno(tp)) {
2677		/* Hold old state until something *above* high_seq
2678		 * is ACKed. For Reno it is MUST to prevent false
2679		 * fast retransmits (RFC2582). SACK TCP is safe. */
2680		if (!tcp_any_retrans_done(sk))
2681			tp->retrans_stamp = 0;
2682		return true;
2683	}
2684	return false;
2685}
2686
2687/* People celebrate: "We love our President!" */
2688static bool tcp_try_undo_recovery(struct sock *sk)
2689{
2690	struct tcp_sock *tp = tcp_sk(sk);
2691
2692	if (tcp_may_undo(tp)) {
2693		int mib_idx;
2694
2695		/* Happy end! We did not retransmit anything
2696		 * or our original transmission succeeded.
2697		 */
2698		DBGUNDO(sk, inet_csk(sk)->icsk_ca_state == TCP_CA_Loss ? "loss" : "retrans");
2699		tcp_undo_cwnd_reduction(sk, false);
2700		if (inet_csk(sk)->icsk_ca_state == TCP_CA_Loss)
2701			mib_idx = LINUX_MIB_TCPLOSSUNDO;
2702		else
2703			mib_idx = LINUX_MIB_TCPFULLUNDO;
2704
2705		NET_INC_STATS(sock_net(sk), mib_idx);
2706	} else if (tp->rack.reo_wnd_persist) {
2707		tp->rack.reo_wnd_persist--;
2708	}
2709	if (tcp_is_non_sack_preventing_reopen(sk))
2710		return true;
2711	tcp_set_ca_state(sk, TCP_CA_Open);
2712	tp->is_sack_reneg = 0;
2713	return false;
2714}
2715
2716/* Try to undo cwnd reduction, because D-SACKs acked all retransmitted data */
2717static bool tcp_try_undo_dsack(struct sock *sk)
2718{
2719	struct tcp_sock *tp = tcp_sk(sk);
2720
2721	if (tp->undo_marker && !tp->undo_retrans) {
2722		tp->rack.reo_wnd_persist = min(TCP_RACK_RECOVERY_THRESH,
2723					       tp->rack.reo_wnd_persist + 1);
2724		DBGUNDO(sk, "D-SACK");
2725		tcp_undo_cwnd_reduction(sk, false);
2726		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKUNDO);
2727		return true;
2728	}
2729	return false;
2730}
2731
2732/* Undo during loss recovery after partial ACK or using F-RTO. */
2733static bool tcp_try_undo_loss(struct sock *sk, bool frto_undo)
2734{
2735	struct tcp_sock *tp = tcp_sk(sk);
2736
2737	if (frto_undo || tcp_may_undo(tp)) {
2738		tcp_undo_cwnd_reduction(sk, true);
2739
2740		DBGUNDO(sk, "partial loss");
2741		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPLOSSUNDO);
2742		if (frto_undo)
2743			NET_INC_STATS(sock_net(sk),
2744					LINUX_MIB_TCPSPURIOUSRTOS);
2745		WRITE_ONCE(inet_csk(sk)->icsk_retransmits, 0);
2746		if (tcp_is_non_sack_preventing_reopen(sk))
2747			return true;
2748		if (frto_undo || tcp_is_sack(tp)) {
2749			tcp_set_ca_state(sk, TCP_CA_Open);
2750			tp->is_sack_reneg = 0;
2751		}
2752		return true;
2753	}
2754	return false;
2755}
2756
2757/* The cwnd reduction in CWR and Recovery uses the PRR algorithm in RFC 6937.
2758 * It computes the number of packets to send (sndcnt) based on packets newly
2759 * delivered:
2760 *   1) If the packets in flight is larger than ssthresh, PRR spreads the
2761 *	cwnd reductions across a full RTT.
2762 *   2) Otherwise PRR uses packet conservation to send as much as delivered.
2763 *      But when SND_UNA is acked without further losses,
2764 *      slow starts cwnd up to ssthresh to speed up the recovery.
2765 */
2766static void tcp_init_cwnd_reduction(struct sock *sk)
2767{
2768	struct tcp_sock *tp = tcp_sk(sk);
2769
2770	tp->high_seq = tp->snd_nxt;
2771	tp->tlp_high_seq = 0;
2772	tp->snd_cwnd_cnt = 0;
2773	tp->prior_cwnd = tcp_snd_cwnd(tp);
2774	tp->prr_delivered = 0;
2775	tp->prr_out = 0;
2776	tp->snd_ssthresh = inet_csk(sk)->icsk_ca_ops->ssthresh(sk);
2777	tcp_ecn_queue_cwr(tp);
2778}
2779
2780void tcp_cwnd_reduction(struct sock *sk, int newly_acked_sacked, int newly_lost, int flag)
2781{
2782	struct tcp_sock *tp = tcp_sk(sk);
2783	int sndcnt = 0;
2784	int delta = tp->snd_ssthresh - tcp_packets_in_flight(tp);
2785
2786	if (newly_acked_sacked <= 0 || WARN_ON_ONCE(!tp->prior_cwnd))
2787		return;
2788
2789	trace_tcp_cwnd_reduction_tp(sk, newly_acked_sacked, newly_lost, flag);
2790
2791	tp->prr_delivered += newly_acked_sacked;
2792	if (delta < 0) {
2793		u64 dividend = (u64)tp->snd_ssthresh * tp->prr_delivered +
2794			       tp->prior_cwnd - 1;
2795		sndcnt = div_u64(dividend, tp->prior_cwnd) - tp->prr_out;
2796	} else {
2797		sndcnt = max_t(int, tp->prr_delivered - tp->prr_out,
2798			       newly_acked_sacked);
2799		if (flag & FLAG_SND_UNA_ADVANCED && !newly_lost)
2800			sndcnt++;
2801		sndcnt = min(delta, sndcnt);
2802	}
2803	/* Force a fast retransmit upon entering fast recovery */
2804	sndcnt = max(sndcnt, (tp->prr_out ? 0 : 1));
2805	tcp_snd_cwnd_set(tp, tcp_packets_in_flight(tp) + sndcnt);
2806}
2807
2808static inline void tcp_end_cwnd_reduction(struct sock *sk)
2809{
2810	struct tcp_sock *tp = tcp_sk(sk);
2811
2812	if (inet_csk(sk)->icsk_ca_ops->cong_control)
2813		return;
2814
2815	/* Reset cwnd to ssthresh in CWR or Recovery (unless it's undone) */
2816	if (tp->snd_ssthresh < TCP_INFINITE_SSTHRESH &&
2817	    (inet_csk(sk)->icsk_ca_state == TCP_CA_CWR || tp->undo_marker)) {
2818		tcp_snd_cwnd_set(tp, tp->snd_ssthresh);
2819		tp->snd_cwnd_stamp = tcp_jiffies32;
2820	}
2821	tcp_ca_event(sk, CA_EVENT_COMPLETE_CWR);
2822}
2823
2824/* Enter CWR state. Disable cwnd undo since congestion is proven with ECN */
2825void tcp_enter_cwr(struct sock *sk)
2826{
2827	struct tcp_sock *tp = tcp_sk(sk);
2828
2829	tp->prior_ssthresh = 0;
2830	if (inet_csk(sk)->icsk_ca_state < TCP_CA_CWR) {
2831		tp->undo_marker = 0;
2832		tcp_init_cwnd_reduction(sk);
2833		tcp_set_ca_state(sk, TCP_CA_CWR);
2834	}
2835}
2836EXPORT_SYMBOL(tcp_enter_cwr);
2837
2838static void tcp_try_keep_open(struct sock *sk)
2839{
2840	struct tcp_sock *tp = tcp_sk(sk);
2841	int state = TCP_CA_Open;
2842
2843	if (tcp_left_out(tp) || tcp_any_retrans_done(sk))
2844		state = TCP_CA_Disorder;
2845
2846	if (inet_csk(sk)->icsk_ca_state != state) {
2847		tcp_set_ca_state(sk, state);
2848		tp->high_seq = tp->snd_nxt;
2849	}
2850}
2851
2852static void tcp_try_to_open(struct sock *sk, int flag)
2853{
2854	struct tcp_sock *tp = tcp_sk(sk);
2855
2856	tcp_verify_left_out(tp);
2857
2858	if (!tcp_any_retrans_done(sk))
2859		tp->retrans_stamp = 0;
2860
2861	if (flag & FLAG_ECE)
2862		tcp_enter_cwr(sk);
2863
2864	if (inet_csk(sk)->icsk_ca_state != TCP_CA_CWR) {
2865		tcp_try_keep_open(sk);
2866	}
2867}
2868
2869static void tcp_mtup_probe_failed(struct sock *sk)
2870{
2871	struct inet_connection_sock *icsk = inet_csk(sk);
2872
2873	icsk->icsk_mtup.search_high = icsk->icsk_mtup.probe_size - 1;
2874	icsk->icsk_mtup.probe_size = 0;
2875	NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMTUPFAIL);
2876}
2877
2878static void tcp_mtup_probe_success(struct sock *sk)
2879{
2880	struct tcp_sock *tp = tcp_sk(sk);
2881	struct inet_connection_sock *icsk = inet_csk(sk);
2882	u64 val;
2883
2884	tp->prior_ssthresh = tcp_current_ssthresh(sk);
2885
2886	val = (u64)tcp_snd_cwnd(tp) * tcp_mss_to_mtu(sk, tp->mss_cache);
2887	do_div(val, icsk->icsk_mtup.probe_size);
2888	DEBUG_NET_WARN_ON_ONCE((u32)val != val);
2889	tcp_snd_cwnd_set(tp, max_t(u32, 1U, val));
2890
2891	tp->snd_cwnd_cnt = 0;
2892	tp->snd_cwnd_stamp = tcp_jiffies32;
2893	tp->snd_ssthresh = tcp_current_ssthresh(sk);
2894
2895	icsk->icsk_mtup.search_low = icsk->icsk_mtup.probe_size;
2896	icsk->icsk_mtup.probe_size = 0;
2897	tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
2898	NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMTUPSUCCESS);
2899}
2900
2901/* Sometimes we deduce that packets have been dropped due to reasons other than
2902 * congestion, like path MTU reductions or failed client TFO attempts. In these
2903 * cases we call this function to retransmit as many packets as cwnd allows,
2904 * without reducing cwnd. Given that retransmits will set retrans_stamp to a
2905 * non-zero value (and may do so in a later calling context due to TSQ), we
2906 * also enter CA_Loss so that we track when all retransmitted packets are ACKed
2907 * and clear retrans_stamp when that happens (to ensure later recurring RTOs
2908 * are using the correct retrans_stamp and don't declare ETIMEDOUT
2909 * prematurely).
2910 */
2911static void tcp_non_congestion_loss_retransmit(struct sock *sk)
2912{
2913	const struct inet_connection_sock *icsk = inet_csk(sk);
2914	struct tcp_sock *tp = tcp_sk(sk);
2915
2916	if (icsk->icsk_ca_state != TCP_CA_Loss) {
2917		tp->high_seq = tp->snd_nxt;
2918		tp->snd_ssthresh = tcp_current_ssthresh(sk);
2919		tp->prior_ssthresh = 0;
2920		tp->undo_marker = 0;
2921		tcp_set_ca_state(sk, TCP_CA_Loss);
2922	}
2923	tcp_xmit_retransmit_queue(sk);
2924}
2925
2926/* Do a simple retransmit without using the backoff mechanisms in
2927 * tcp_timer. This is used for path mtu discovery.
2928 * The socket is already locked here.
2929 */
2930void tcp_simple_retransmit(struct sock *sk)
2931{
2932	struct tcp_sock *tp = tcp_sk(sk);
2933	struct sk_buff *skb;
2934	int mss;
2935
2936	/* A fastopen SYN request is stored as two separate packets within
2937	 * the retransmit queue, this is done by tcp_send_syn_data().
2938	 * As a result simply checking the MSS of the frames in the queue
2939	 * will not work for the SYN packet.
2940	 *
2941	 * Us being here is an indication of a path MTU issue so we can
2942	 * assume that the fastopen SYN was lost and just mark all the
2943	 * frames in the retransmit queue as lost. We will use an MSS of
2944	 * -1 to mark all frames as lost, otherwise compute the current MSS.
2945	 */
2946	if (tp->syn_data && sk->sk_state == TCP_SYN_SENT)
2947		mss = -1;
2948	else
2949		mss = tcp_current_mss(sk);
2950
2951	skb_rbtree_walk(skb, &sk->tcp_rtx_queue) {
2952		if (tcp_skb_seglen(skb) > mss)
2953			tcp_mark_skb_lost(sk, skb);
2954	}
2955
2956	if (!tp->lost_out)
2957		return;
2958
2959	if (tcp_is_reno(tp))
2960		tcp_limit_reno_sacked(tp);
2961
2962	tcp_verify_left_out(tp);
2963
2964	/* Don't muck with the congestion window here.
2965	 * Reason is that we do not increase amount of _data_
2966	 * in network, but units changed and effective
2967	 * cwnd/ssthresh really reduced now.
2968	 */
2969	tcp_non_congestion_loss_retransmit(sk);
2970}
2971EXPORT_IPV6_MOD(tcp_simple_retransmit);
2972
2973void tcp_enter_recovery(struct sock *sk, bool ece_ack)
2974{
2975	struct tcp_sock *tp = tcp_sk(sk);
2976	int mib_idx;
2977
2978	/* Start the clock with our fast retransmit, for undo and ETIMEDOUT. */
2979	tcp_retrans_stamp_cleanup(sk);
2980
2981	if (tcp_is_reno(tp))
2982		mib_idx = LINUX_MIB_TCPRENORECOVERY;
2983	else
2984		mib_idx = LINUX_MIB_TCPSACKRECOVERY;
2985
2986	NET_INC_STATS(sock_net(sk), mib_idx);
2987
2988	tp->prior_ssthresh = 0;
2989	tcp_init_undo(tp);
2990
2991	if (!tcp_in_cwnd_reduction(sk)) {
2992		if (!ece_ack)
2993			tp->prior_ssthresh = tcp_current_ssthresh(sk);
2994		tcp_init_cwnd_reduction(sk);
2995	}
2996	tcp_set_ca_state(sk, TCP_CA_Recovery);
2997}
2998
2999static void tcp_update_rto_time(struct tcp_sock *tp)
3000{
3001	if (tp->rto_stamp) {
3002		tp->total_rto_time += tcp_time_stamp_ms(tp) - tp->rto_stamp;
3003		tp->rto_stamp = 0;
3004	}
3005}
3006
3007/* Process an ACK in CA_Loss state. Move to CA_Open if lost data are
3008 * recovered or spurious. Otherwise retransmits more on partial ACKs.
3009 */
3010static void tcp_process_loss(struct sock *sk, int flag, int num_dupack,
3011			     int *rexmit)
3012{
3013	struct tcp_sock *tp = tcp_sk(sk);
3014	bool recovered = !before(tp->snd_una, tp->high_seq);
3015
3016	if ((flag & FLAG_SND_UNA_ADVANCED || rcu_access_pointer(tp->fastopen_rsk)) &&
3017	    tcp_try_undo_loss(sk, false))
3018		return;
3019
3020	if (tp->frto) { /* F-RTO RFC5682 sec 3.1 (sack enhanced version). */
3021		/* Step 3.b. A timeout is spurious if not all data are
3022		 * lost, i.e., never-retransmitted data are (s)acked.
3023		 */
3024		if ((flag & FLAG_ORIG_SACK_ACKED) &&
3025		    tcp_try_undo_loss(sk, true))
3026			return;
3027
3028		if (after(tp->snd_nxt, tp->high_seq)) {
3029			if (flag & FLAG_DATA_SACKED || num_dupack)
3030				tp->frto = 0; /* Step 3.a. loss was real */
3031		} else if (flag & FLAG_SND_UNA_ADVANCED && !recovered) {
3032			tp->high_seq = tp->snd_nxt;
3033			/* Step 2.b. Try send new data (but deferred until cwnd
3034			 * is updated in tcp_ack()). Otherwise fall back to
3035			 * the conventional recovery.
3036			 */
3037			if (!tcp_write_queue_empty(sk) &&
3038			    after(tcp_wnd_end(tp), tp->snd_nxt)) {
3039				*rexmit = REXMIT_NEW;
3040				return;
3041			}
3042			tp->frto = 0;
3043		}
3044	}
3045
3046	if (recovered) {
3047		/* F-RTO RFC5682 sec 3.1 step 2.a and 1st part of step 3.a */
3048		tcp_try_undo_recovery(sk);
3049		return;
3050	}
3051	if (tcp_is_reno(tp)) {
3052		/* A Reno DUPACK means new data in F-RTO step 2.b above are
3053		 * delivered. Lower inflight to clock out (re)transmissions.
3054		 */
3055		if (after(tp->snd_nxt, tp->high_seq) && num_dupack)
3056			tcp_add_reno_sack(sk, num_dupack, flag & FLAG_ECE);
3057		else if (flag & FLAG_SND_UNA_ADVANCED)
3058			tcp_reset_reno_sack(tp);
3059	}
3060	*rexmit = REXMIT_LOST;
3061}
3062
3063/* Undo during fast recovery after partial ACK. */
3064static bool tcp_try_undo_partial(struct sock *sk, u32 prior_snd_una)
3065{
3066	struct tcp_sock *tp = tcp_sk(sk);
3067
3068	if (tp->undo_marker && tcp_packet_delayed(tp)) {
3069		/* Plain luck! Hole if filled with delayed
3070		 * packet, rather than with a retransmit. Check reordering.
3071		 */
3072		tcp_check_sack_reordering(sk, prior_snd_una, 1);
3073
3074		/* We are getting evidence that the reordering degree is higher
3075		 * than we realized. If there are no retransmits out then we
3076		 * can undo. Otherwise we clock out new packets but do not
3077		 * mark more packets lost or retransmit more.
3078		 */
3079		if (tp->retrans_out)
3080			return true;
3081
3082		if (!tcp_any_retrans_done(sk))
3083			tp->retrans_stamp = 0;
3084
3085		DBGUNDO(sk, "partial recovery");
3086		tcp_undo_cwnd_reduction(sk, true);
3087		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPPARTIALUNDO);
3088		tcp_try_keep_open(sk);
3089	}
3090	return false;
3091}
3092
3093static void tcp_identify_packet_loss(struct sock *sk, int *ack_flag)
3094{
3095	struct tcp_sock *tp = tcp_sk(sk);
3096
3097	if (tcp_rtx_queue_empty(sk))
3098		return;
3099
3100	if (unlikely(tcp_is_reno(tp))) {
3101		tcp_newreno_mark_lost(sk, *ack_flag & FLAG_SND_UNA_ADVANCED);
3102	} else {
3103		u32 prior_retrans = tp->retrans_out;
3104
3105		if (tcp_rack_mark_lost(sk))
3106			*ack_flag &= ~FLAG_SET_XMIT_TIMER;
3107		if (prior_retrans > tp->retrans_out)
3108			*ack_flag |= FLAG_LOST_RETRANS;
3109	}
3110}
3111
3112/* Process an event, which can update packets-in-flight not trivially.
3113 * Main goal of this function is to calculate new estimate for left_out,
3114 * taking into account both packets sitting in receiver's buffer and
3115 * packets lost by network.
3116 *
3117 * Besides that it updates the congestion state when packet loss or ECN
3118 * is detected. But it does not reduce the cwnd, it is done by the
3119 * congestion control later.
3120 *
3121 * It does _not_ decide what to send, it is made in function
3122 * tcp_xmit_retransmit_queue().
3123 */
3124static void tcp_fastretrans_alert(struct sock *sk, const u32 prior_snd_una,
3125				  int num_dupack, int *ack_flag, int *rexmit)
3126{
3127	struct inet_connection_sock *icsk = inet_csk(sk);
3128	struct tcp_sock *tp = tcp_sk(sk);
3129	int flag = *ack_flag;
3130	bool ece_ack = flag & FLAG_ECE;
3131
3132	if (!tp->packets_out && tp->sacked_out)
3133		tp->sacked_out = 0;
3134
3135	/* Now state machine starts.
3136	 * A. ECE, hence prohibit cwnd undoing, the reduction is required. */
3137	if (ece_ack)
3138		tp->prior_ssthresh = 0;
3139
3140	/* B. In all the states check for reneging SACKs. */
3141	if (tcp_check_sack_reneging(sk, ack_flag))
3142		return;
3143
3144	/* C. Check consistency of the current state. */
3145	tcp_verify_left_out(tp);
3146
3147	/* D. Check state exit conditions. State can be terminated
3148	 *    when high_seq is ACKed. */
3149	if (icsk->icsk_ca_state == TCP_CA_Open) {
3150		WARN_ON(tp->retrans_out != 0 && !tp->syn_data);
3151		tp->retrans_stamp = 0;
3152	} else if (!before(tp->snd_una, tp->high_seq)) {
3153		switch (icsk->icsk_ca_state) {
3154		case TCP_CA_CWR:
3155			/* CWR is to be held something *above* high_seq
3156			 * is ACKed for CWR bit to reach receiver. */
3157			if (tp->snd_una != tp->high_seq) {
3158				tcp_end_cwnd_reduction(sk);
3159				tcp_set_ca_state(sk, TCP_CA_Open);
3160			}
3161			break;
3162
3163		case TCP_CA_Recovery:
3164			if (tcp_is_reno(tp))
3165				tcp_reset_reno_sack(tp);
3166			if (tcp_try_undo_recovery(sk))
3167				return;
3168			tcp_end_cwnd_reduction(sk);
3169			break;
3170		}
3171	}
3172
3173	/* E. Process state. */
3174	switch (icsk->icsk_ca_state) {
3175	case TCP_CA_Recovery:
3176		if (!(flag & FLAG_SND_UNA_ADVANCED)) {
3177			if (tcp_is_reno(tp))
3178				tcp_add_reno_sack(sk, num_dupack, ece_ack);
3179		} else if (tcp_try_undo_partial(sk, prior_snd_una))
3180			return;
3181
3182		if (tcp_try_undo_dsack(sk))
3183			tcp_try_to_open(sk, flag);
3184
3185		tcp_identify_packet_loss(sk, ack_flag);
3186		if (icsk->icsk_ca_state != TCP_CA_Recovery) {
3187			if (!tcp_time_to_recover(tp))
3188				return;
3189			/* Undo reverts the recovery state. If loss is evident,
3190			 * starts a new recovery (e.g. reordering then loss);
3191			 */
3192			tcp_enter_recovery(sk, ece_ack);
3193		}
3194		break;
3195	case TCP_CA_Loss:
3196		tcp_process_loss(sk, flag, num_dupack, rexmit);
3197		if (icsk->icsk_ca_state != TCP_CA_Loss)
3198			tcp_update_rto_time(tp);
3199		tcp_identify_packet_loss(sk, ack_flag);
3200		if (!(icsk->icsk_ca_state == TCP_CA_Open ||
3201		      (*ack_flag & FLAG_LOST_RETRANS)))
3202			return;
3203		/* Change state if cwnd is undone or retransmits are lost */
3204		fallthrough;
3205	default:
3206		if (tcp_is_reno(tp)) {
3207			if (flag & FLAG_SND_UNA_ADVANCED)
3208				tcp_reset_reno_sack(tp);
3209			tcp_add_reno_sack(sk, num_dupack, ece_ack);
3210		}
3211
3212		if (icsk->icsk_ca_state <= TCP_CA_Disorder)
3213			tcp_try_undo_dsack(sk);
3214
3215		tcp_identify_packet_loss(sk, ack_flag);
3216		if (!tcp_time_to_recover(tp)) {
3217			tcp_try_to_open(sk, flag);
3218			return;
3219		}
3220
3221		/* MTU probe failure: don't reduce cwnd */
3222		if (icsk->icsk_ca_state < TCP_CA_CWR &&
3223		    icsk->icsk_mtup.probe_size &&
3224		    tp->snd_una == tp->mtu_probe.probe_seq_start) {
3225			tcp_mtup_probe_failed(sk);
3226			/* Restores the reduction we did in tcp_mtup_probe() */
3227			tcp_snd_cwnd_set(tp, tcp_snd_cwnd(tp) + 1);
3228			tcp_simple_retransmit(sk);
3229			return;
3230		}
3231
3232		/* Otherwise enter Recovery state */
3233		tcp_enter_recovery(sk, ece_ack);
3234	}
3235
3236	*rexmit = REXMIT_LOST;
3237}
3238
3239static void tcp_update_rtt_min(struct sock *sk, u32 rtt_us, const int flag)
3240{
3241	u32 wlen = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_min_rtt_wlen) * HZ;
3242	struct tcp_sock *tp = tcp_sk(sk);
3243
3244	if ((flag & FLAG_ACK_MAYBE_DELAYED) && rtt_us > tcp_min_rtt(tp)) {
3245		/* If the remote keeps returning delayed ACKs, eventually
3246		 * the min filter would pick it up and overestimate the
3247		 * prop. delay when it expires. Skip suspected delayed ACKs.
3248		 */
3249		return;
3250	}
3251	minmax_running_min(&tp->rtt_min, wlen, tcp_jiffies32,
3252			   rtt_us ? : jiffies_to_usecs(1));
3253}
3254
3255static bool tcp_ack_update_rtt(struct sock *sk, const int flag,
3256			       long seq_rtt_us, long sack_rtt_us,
3257			       long ca_rtt_us, struct rate_sample *rs)
3258{
3259	const struct tcp_sock *tp = tcp_sk(sk);
3260
3261	/* Prefer RTT measured from ACK's timing to TS-ECR. This is because
3262	 * broken middle-boxes or peers may corrupt TS-ECR fields. But
3263	 * Karn's algorithm forbids taking RTT if some retransmitted data
3264	 * is acked (RFC6298).
3265	 */
3266	if (seq_rtt_us < 0)
3267		seq_rtt_us = sack_rtt_us;
3268
3269	/* RTTM Rule: A TSecr value received in a segment is used to
3270	 * update the averaged RTT measurement only if the segment
3271	 * acknowledges some new data, i.e., only if it advances the
3272	 * left edge of the send window.
3273	 * See draft-ietf-tcplw-high-performance-00, section 3.3.
3274	 */
3275	if (seq_rtt_us < 0 && tp->rx_opt.saw_tstamp &&
3276	    tp->rx_opt.rcv_tsecr && flag & FLAG_ACKED)
3277		seq_rtt_us = ca_rtt_us = tcp_rtt_tsopt_us(tp, 1);
3278
3279	rs->rtt_us = ca_rtt_us; /* RTT of last (S)ACKed packet (or -1) */
3280	if (seq_rtt_us < 0)
3281		return false;
3282
3283	/* ca_rtt_us >= 0 is counting on the invariant that ca_rtt_us is
3284	 * always taken together with ACK, SACK, or TS-opts. Any negative
3285	 * values will be skipped with the seq_rtt_us < 0 check above.
3286	 */
3287	tcp_update_rtt_min(sk, ca_rtt_us, flag);
3288	tcp_rtt_estimator(sk, seq_rtt_us);
3289	tcp_set_rto(sk);
3290
3291	/* RFC6298: only reset backoff on valid RTT measurement. */
3292	inet_csk(sk)->icsk_backoff = 0;
3293	return true;
3294}
3295
3296/* Compute time elapsed between (last) SYNACK and the ACK completing 3WHS. */
3297void tcp_synack_rtt_meas(struct sock *sk, struct request_sock *req)
3298{
3299	struct rate_sample rs;
3300	long rtt_us = -1L;
3301
3302	if (req && !req->num_retrans && tcp_rsk(req)->snt_synack)
3303		rtt_us = tcp_stamp_us_delta(tcp_clock_us(), tcp_rsk(req)->snt_synack);
3304
3305	tcp_ack_update_rtt(sk, FLAG_SYN_ACKED, rtt_us, -1L, rtt_us, &rs);
3306}
3307
3308
3309static void tcp_cong_avoid(struct sock *sk, u32 ack, u32 acked)
3310{
3311	const struct inet_connection_sock *icsk = inet_csk(sk);
3312
3313	icsk->icsk_ca_ops->cong_avoid(sk, ack, acked);
3314	tcp_sk(sk)->snd_cwnd_stamp = tcp_jiffies32;
3315}
3316
3317/* Restart timer after forward progress on connection.
3318 * RFC2988 recommends to restart timer to now+rto.
3319 */
3320void tcp_rearm_rto(struct sock *sk)
3321{
3322	const struct inet_connection_sock *icsk = inet_csk(sk);
3323	struct tcp_sock *tp = tcp_sk(sk);
3324
3325	/* If the retrans timer is currently being used by Fast Open
3326	 * for SYN-ACK retrans purpose, stay put.
3327	 */
3328	if (rcu_access_pointer(tp->fastopen_rsk))
3329		return;
3330
3331	if (!tp->packets_out) {
3332		inet_csk_clear_xmit_timer(sk, ICSK_TIME_RETRANS);
3333	} else {
3334		u32 rto = inet_csk(sk)->icsk_rto;
3335		/* Offset the time elapsed after installing regular RTO */
3336		if (icsk->icsk_pending == ICSK_TIME_REO_TIMEOUT ||
3337		    icsk->icsk_pending == ICSK_TIME_LOSS_PROBE) {
3338			s64 delta_us = tcp_rto_delta_us(sk);
3339			/* delta_us may not be positive if the socket is locked
3340			 * when the retrans timer fires and is rescheduled.
3341			 */
3342			rto = usecs_to_jiffies(max_t(int, delta_us, 1));
3343		}
3344		tcp_reset_xmit_timer(sk, ICSK_TIME_RETRANS, rto, true);
3345	}
3346}
3347
3348/* Try to schedule a loss probe; if that doesn't work, then schedule an RTO. */
3349static void tcp_set_xmit_timer(struct sock *sk)
3350{
3351	if (!tcp_schedule_loss_probe(sk, true))
3352		tcp_rearm_rto(sk);
3353}
3354
3355/* If we get here, the whole TSO packet has not been acked. */
3356static u32 tcp_tso_acked(struct sock *sk, struct sk_buff *skb)
3357{
3358	struct tcp_sock *tp = tcp_sk(sk);
3359	u32 packets_acked;
3360
3361	BUG_ON(!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una));
3362
3363	packets_acked = tcp_skb_pcount(skb);
3364	if (tcp_trim_head(sk, skb, tp->snd_una - TCP_SKB_CB(skb)->seq))
3365		return 0;
3366	packets_acked -= tcp_skb_pcount(skb);
3367
3368	if (packets_acked) {
3369		BUG_ON(tcp_skb_pcount(skb) == 0);
3370		BUG_ON(!before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq));
3371	}
3372
3373	return packets_acked;
3374}
3375
3376static void tcp_ack_tstamp(struct sock *sk, struct sk_buff *skb,
3377			   const struct sk_buff *ack_skb, u32 prior_snd_una)
3378{
3379	const struct skb_shared_info *shinfo;
3380
3381	/* Avoid cache line misses to get skb_shinfo() and shinfo->tx_flags */
3382	if (likely(!TCP_SKB_CB(skb)->txstamp_ack))
3383		return;
3384
3385	shinfo = skb_shinfo(skb);
3386	if (!before(shinfo->tskey, prior_snd_una) &&
3387	    before(shinfo->tskey, tcp_sk(sk)->snd_una)) {
3388		tcp_skb_tsorted_save(skb) {
3389			__skb_tstamp_tx(skb, ack_skb, NULL, sk, SCM_TSTAMP_ACK);
3390		} tcp_skb_tsorted_restore(skb);
3391	}
3392}
3393
3394/* Remove acknowledged frames from the retransmission queue. If our packet
3395 * is before the ack sequence we can discard it as it's confirmed to have
3396 * arrived at the other end.
3397 */
3398static int tcp_clean_rtx_queue(struct sock *sk, const struct sk_buff *ack_skb,
3399			       u32 prior_fack, u32 prior_snd_una,
3400			       struct tcp_sacktag_state *sack, bool ece_ack)
3401{
3402	const struct inet_connection_sock *icsk = inet_csk(sk);
3403	u64 first_ackt, last_ackt;
3404	struct tcp_sock *tp = tcp_sk(sk);
3405	u32 prior_sacked = tp->sacked_out;
3406	u32 reord = tp->snd_nxt; /* lowest acked un-retx un-sacked seq */
3407	struct sk_buff *skb, *next;
3408	bool fully_acked = true;
3409	long sack_rtt_us = -1L;
3410	long seq_rtt_us = -1L;
3411	long ca_rtt_us = -1L;
3412	u32 pkts_acked = 0;
3413	bool rtt_update;
3414	int flag = 0;
3415
3416	first_ackt = 0;
3417
3418	for (skb = skb_rb_first(&sk->tcp_rtx_queue); skb; skb = next) {
3419		struct tcp_skb_cb *scb = TCP_SKB_CB(skb);
3420		const u32 start_seq = scb->seq;
3421		u8 sacked = scb->sacked;
3422		u32 acked_pcount;
3423
3424		/* Determine how many packets and what bytes were acked, tso and else */
3425		if (after(scb->end_seq, tp->snd_una)) {
3426			if (tcp_skb_pcount(skb) == 1 ||
3427			    !after(tp->snd_una, scb->seq))
3428				break;
3429
3430			acked_pcount = tcp_tso_acked(sk, skb);
3431			if (!acked_pcount)
3432				break;
3433			fully_acked = false;
3434		} else {
3435			acked_pcount = tcp_skb_pcount(skb);
3436		}
3437
3438		if (unlikely(sacked & TCPCB_RETRANS)) {
3439			if (sacked & TCPCB_SACKED_RETRANS)
3440				tp->retrans_out -= acked_pcount;
3441			flag |= FLAG_RETRANS_DATA_ACKED;
3442		} else if (!(sacked & TCPCB_SACKED_ACKED)) {
3443			last_ackt = tcp_skb_timestamp_us(skb);
3444			WARN_ON_ONCE(last_ackt == 0);
3445			if (!first_ackt)
3446				first_ackt = last_ackt;
3447
3448			if (before(start_seq, reord))
3449				reord = start_seq;
3450			if (!after(scb->end_seq, tp->high_seq))
3451				flag |= FLAG_ORIG_SACK_ACKED;
3452		}
3453
3454		if (sacked & TCPCB_SACKED_ACKED) {
3455			tp->sacked_out -= acked_pcount;
3456			/* snd_una delta covers these skbs */
3457			sack->delivered_bytes -= skb->len;
3458		} else if (tcp_is_sack(tp)) {
3459			tcp_count_delivered(tp, acked_pcount, ece_ack);
3460			if (!tcp_skb_spurious_retrans(tp, skb))
3461				tcp_rack_advance(tp, sacked, scb->end_seq,
3462						 tcp_skb_timestamp_us(skb));
3463		}
3464		if (sacked & TCPCB_LOST)
3465			tp->lost_out -= acked_pcount;
3466
3467		tp->packets_out -= acked_pcount;
3468		pkts_acked += acked_pcount;
3469		tcp_rate_skb_delivered(sk, skb, sack->rate);
3470
3471		/* Initial outgoing SYN's get put onto the write_queue
3472		 * just like anything else we transmit.  It is not
3473		 * true data, and if we misinform our callers that
3474		 * this ACK acks real data, we will erroneously exit
3475		 * connection startup slow start one packet too
3476		 * quickly.  This is severely frowned upon behavior.
3477		 */
3478		if (likely(!(scb->tcp_flags & TCPHDR_SYN))) {
3479			flag |= FLAG_DATA_ACKED;
3480		} else {
3481			flag |= FLAG_SYN_ACKED;
3482			tp->retrans_stamp = 0;
3483		}
3484
3485		if (!fully_acked)
3486			break;
3487
3488		tcp_ack_tstamp(sk, skb, ack_skb, prior_snd_una);
3489
3490		next = skb_rb_next(skb);
3491		if (unlikely(skb == tp->retransmit_skb_hint))
3492			tp->retransmit_skb_hint = NULL;
3493		tcp_highest_sack_replace(sk, skb, next);
3494		tcp_rtx_queue_unlink_and_free(skb, sk);
3495	}
3496
3497	if (!skb)
3498		tcp_chrono_stop(sk, TCP_CHRONO_BUSY);
3499
3500	if (likely(between(tp->snd_up, prior_snd_una, tp->snd_una)))
3501		tp->snd_up = tp->snd_una;
3502
3503	if (skb) {
3504		tcp_ack_tstamp(sk, skb, ack_skb, prior_snd_una);
3505		if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)
3506			flag |= FLAG_SACK_RENEGING;
3507	}
3508
3509	if (likely(first_ackt) && !(flag & FLAG_RETRANS_DATA_ACKED)) {
3510		seq_rtt_us = tcp_stamp_us_delta(tp->tcp_mstamp, first_ackt);
3511		ca_rtt_us = tcp_stamp_us_delta(tp->tcp_mstamp, last_ackt);
3512
3513		if (pkts_acked == 1 && fully_acked && !prior_sacked &&
3514		    (tp->snd_una - prior_snd_una) < tp->mss_cache &&
3515		    sack->rate->prior_delivered + 1 == tp->delivered &&
3516		    !(flag & (FLAG_CA_ALERT | FLAG_SYN_ACKED))) {
3517			/* Conservatively mark a delayed ACK. It's typically
3518			 * from a lone runt packet over the round trip to
3519			 * a receiver w/o out-of-order or CE events.
3520			 */
3521			flag |= FLAG_ACK_MAYBE_DELAYED;
3522		}
3523	}
3524	if (sack->first_sackt) {
3525		sack_rtt_us = tcp_stamp_us_delta(tp->tcp_mstamp, sack->first_sackt);
3526		ca_rtt_us = tcp_stamp_us_delta(tp->tcp_mstamp, sack->last_sackt);
3527	}
3528	rtt_update = tcp_ack_update_rtt(sk, flag, seq_rtt_us, sack_rtt_us,
3529					ca_rtt_us, sack->rate);
3530
3531	if (flag & FLAG_ACKED) {
3532		flag |= FLAG_SET_XMIT_TIMER;  /* set TLP or RTO timer */
3533		if (unlikely(icsk->icsk_mtup.probe_size &&
3534			     !after(tp->mtu_probe.probe_seq_end, tp->snd_una))) {
3535			tcp_mtup_probe_success(sk);
3536		}
3537
3538		if (tcp_is_reno(tp)) {
3539			tcp_remove_reno_sacks(sk, pkts_acked, ece_ack);
3540
3541			/* If any of the cumulatively ACKed segments was
3542			 * retransmitted, non-SACK case cannot confirm that
3543			 * progress was due to original transmission due to
3544			 * lack of TCPCB_SACKED_ACKED bits even if some of
3545			 * the packets may have been never retransmitted.
3546			 */
3547			if (flag & FLAG_RETRANS_DATA_ACKED)
3548				flag &= ~FLAG_ORIG_SACK_ACKED;
3549		} else {
3550			/* Non-retransmitted hole got filled? That's reordering */
3551			if (before(reord, prior_fack))
3552				tcp_check_sack_reordering(sk, reord, 0);
3553		}
3554
3555		sack->delivered_bytes = (skb ?
3556					 TCP_SKB_CB(skb)->seq : tp->snd_una) -
3557					 prior_snd_una;
3558	} else if (skb && rtt_update && sack_rtt_us >= 0 &&
3559		   sack_rtt_us > tcp_stamp_us_delta(tp->tcp_mstamp,
3560						    tcp_skb_timestamp_us(skb))) {
3561		/* Do not re-arm RTO if the sack RTT is measured from data sent
3562		 * after when the head was last (re)transmitted. Otherwise the
3563		 * timeout may continue to extend in loss recovery.
3564		 */
3565		flag |= FLAG_SET_XMIT_TIMER;  /* set TLP or RTO timer */
3566	}
3567
3568	if (icsk->icsk_ca_ops->pkts_acked) {
3569		struct ack_sample sample = { .pkts_acked = pkts_acked,
3570					     .rtt_us = sack->rate->rtt_us };
3571
3572		sample.in_flight = tp->mss_cache *
3573			(tp->delivered - sack->rate->prior_delivered);
3574		icsk->icsk_ca_ops->pkts_acked(sk, &sample);
3575	}
3576
3577#if FASTRETRANS_DEBUG > 0
3578	WARN_ON((int)tp->sacked_out < 0);
3579	WARN_ON((int)tp->lost_out < 0);
3580	WARN_ON((int)tp->retrans_out < 0);
3581	if (!tp->packets_out && tcp_is_sack(tp)) {
3582		icsk = inet_csk(sk);
3583		if (tp->lost_out) {
3584			pr_debug("Leak l=%u %d\n",
3585				 tp->lost_out, icsk->icsk_ca_state);
3586			tp->lost_out = 0;
3587		}
3588		if (tp->sacked_out) {
3589			pr_debug("Leak s=%u %d\n",
3590				 tp->sacked_out, icsk->icsk_ca_state);
3591			tp->sacked_out = 0;
3592		}
3593		if (tp->retrans_out) {
3594			pr_debug("Leak r=%u %d\n",
3595				 tp->retrans_out, icsk->icsk_ca_state);
3596			tp->retrans_out = 0;
3597		}
3598	}
3599#endif
3600	return flag;
3601}
3602
3603static void tcp_ack_probe(struct sock *sk)
3604{
3605	struct inet_connection_sock *icsk = inet_csk(sk);
3606	struct sk_buff *head = tcp_send_head(sk);
3607	const struct tcp_sock *tp = tcp_sk(sk);
3608
3609	/* Was it a usable window open? */
3610	if (!head)
3611		return;
3612	if (!after(TCP_SKB_CB(head)->end_seq, tcp_wnd_end(tp))) {
3613		icsk->icsk_backoff = 0;
3614		icsk->icsk_probes_tstamp = 0;
3615		inet_csk_clear_xmit_timer(sk, ICSK_TIME_PROBE0);
3616		/* Socket must be waked up by subsequent tcp_data_snd_check().
3617		 * This function is not for random using!
3618		 */
3619	} else {
3620		unsigned long when = tcp_probe0_when(sk, tcp_rto_max(sk));
3621
3622		when = tcp_clamp_probe0_to_user_timeout(sk, when);
3623		tcp_reset_xmit_timer(sk, ICSK_TIME_PROBE0, when, true);
3624	}
3625}
3626
3627static inline bool tcp_ack_is_dubious(const struct sock *sk, const int flag)
3628{
3629	return !(flag & FLAG_NOT_DUP) || (flag & FLAG_CA_ALERT) ||
3630		inet_csk(sk)->icsk_ca_state != TCP_CA_Open;
3631}
3632
3633/* Decide wheather to run the increase function of congestion control. */
3634static inline bool tcp_may_raise_cwnd(const struct sock *sk, const int flag)
3635{
3636	/* If reordering is high then always grow cwnd whenever data is
3637	 * delivered regardless of its ordering. Otherwise stay conservative
3638	 * and only grow cwnd on in-order delivery (RFC5681). A stretched ACK w/
3639	 * new SACK or ECE mark may first advance cwnd here and later reduce
3640	 * cwnd in tcp_fastretrans_alert() based on more states.
3641	 */
3642	if (tcp_sk(sk)->reordering >
3643	    READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_reordering))
3644		return flag & FLAG_FORWARD_PROGRESS;
3645
3646	return flag & FLAG_DATA_ACKED;
3647}
3648
3649/* The "ultimate" congestion control function that aims to replace the rigid
3650 * cwnd increase and decrease control (tcp_cong_avoid,tcp_*cwnd_reduction).
3651 * It's called toward the end of processing an ACK with precise rate
3652 * information. All transmission or retransmission are delayed afterwards.
3653 */
3654static void tcp_cong_control(struct sock *sk, u32 ack, u32 acked_sacked,
3655			     int flag, const struct rate_sample *rs)
3656{
3657	const struct inet_connection_sock *icsk = inet_csk(sk);
3658
3659	if (icsk->icsk_ca_ops->cong_control) {
3660		icsk->icsk_ca_ops->cong_control(sk, ack, flag, rs);
3661		return;
3662	}
3663
3664	if (tcp_in_cwnd_reduction(sk)) {
3665		/* Reduce cwnd if state mandates */
3666		tcp_cwnd_reduction(sk, acked_sacked, rs->losses, flag);
3667	} else if (tcp_may_raise_cwnd(sk, flag)) {
3668		/* Advance cwnd if state allows */
3669		tcp_cong_avoid(sk, ack, acked_sacked);
3670	}
3671	tcp_update_pacing_rate(sk);
3672}
3673
3674/* Check that window update is acceptable.
3675 * The function assumes that snd_una<=ack<=snd_next.
3676 */
3677static inline bool tcp_may_update_window(const struct tcp_sock *tp,
3678					const u32 ack, const u32 ack_seq,
3679					const u32 nwin)
3680{
3681	return	after(ack, tp->snd_una) ||
3682		after(ack_seq, tp->snd_wl1) ||
3683		(ack_seq == tp->snd_wl1 && (nwin > tp->snd_wnd || !nwin));
3684}
3685
3686static void tcp_snd_sne_update(struct tcp_sock *tp, u32 ack)
3687{
3688#ifdef CONFIG_TCP_AO
3689	struct tcp_ao_info *ao;
3690
3691	if (!static_branch_unlikely(&tcp_ao_needed.key))
3692		return;
3693
3694	ao = rcu_dereference_protected(tp->ao_info,
3695				       lockdep_sock_is_held((struct sock *)tp));
3696	if (ao && ack < tp->snd_una) {
3697		ao->snd_sne++;
3698		trace_tcp_ao_snd_sne_update((struct sock *)tp, ao->snd_sne);
3699	}
3700#endif
3701}
3702
3703/* If we update tp->snd_una, also update tp->bytes_acked */
3704static void tcp_snd_una_update(struct tcp_sock *tp, u32 ack)
3705{
3706	u32 delta = ack - tp->snd_una;
3707
3708	sock_owned_by_me((struct sock *)tp);
3709	tp->bytes_acked += delta;
3710	tcp_snd_sne_update(tp, ack);
3711	tp->snd_una = ack;
3712}
3713
3714static void tcp_rcv_sne_update(struct tcp_sock *tp, u32 seq)
3715{
3716#ifdef CONFIG_TCP_AO
3717	struct tcp_ao_info *ao;
3718
3719	if (!static_branch_unlikely(&tcp_ao_needed.key))
3720		return;
3721
3722	ao = rcu_dereference_protected(tp->ao_info,
3723				       lockdep_sock_is_held((struct sock *)tp));
3724	if (ao && seq < tp->rcv_nxt) {
3725		ao->rcv_sne++;
3726		trace_tcp_ao_rcv_sne_update((struct sock *)tp, ao->rcv_sne);
3727	}
3728#endif
3729}
3730
3731/* If we update tp->rcv_nxt, also update tp->bytes_received */
3732static void tcp_rcv_nxt_update(struct tcp_sock *tp, u32 seq)
3733{
3734	u32 delta = seq - tp->rcv_nxt;
3735
3736	sock_owned_by_me((struct sock *)tp);
3737	tp->bytes_received += delta;
3738	tcp_rcv_sne_update(tp, seq);
3739	WRITE_ONCE(tp->rcv_nxt, seq);
3740}
3741
3742/* Update our send window.
3743 *
3744 * Window update algorithm, described in RFC793/RFC1122 (used in linux-2.2
3745 * and in FreeBSD. NetBSD's one is even worse.) is wrong.
3746 */
3747static int tcp_ack_update_window(struct sock *sk, const struct sk_buff *skb, u32 ack,
3748				 u32 ack_seq)
3749{
3750	struct tcp_sock *tp = tcp_sk(sk);
3751	int flag = 0;
3752	u32 nwin = ntohs(tcp_hdr(skb)->window);
3753
3754	if (likely(!tcp_hdr(skb)->syn))
3755		nwin <<= tp->rx_opt.snd_wscale;
3756
3757	if (tcp_may_update_window(tp, ack, ack_seq, nwin)) {
3758		flag |= FLAG_WIN_UPDATE;
3759		tcp_update_wl(tp, ack_seq);
3760
3761		if (tp->snd_wnd != nwin) {
3762			tp->snd_wnd = nwin;
3763
3764			/* Note, it is the only place, where
3765			 * fast path is recovered for sending TCP.
3766			 */
3767			tp->pred_flags = 0;
3768			tcp_fast_path_check(sk);
3769
3770			if (!tcp_write_queue_empty(sk))
3771				tcp_slow_start_after_idle_check(sk);
3772
3773			if (nwin > tp->max_window) {
3774				tp->max_window = nwin;
3775				tcp_sync_mss(sk, inet_csk(sk)->icsk_pmtu_cookie);
3776			}
3777		}
3778	}
3779
3780	tcp_snd_una_update(tp, ack);
3781
3782	return flag;
3783}
3784
3785static bool __tcp_oow_rate_limited(struct net *net, int mib_idx,
3786				   u32 *last_oow_ack_time)
3787{
3788	/* Paired with the WRITE_ONCE() in this function. */
3789	u32 val = READ_ONCE(*last_oow_ack_time);
3790
3791	if (val) {
3792		s32 elapsed = (s32)(tcp_jiffies32 - val);
3793
3794		if (0 <= elapsed &&
3795		    elapsed < READ_ONCE(net->ipv4.sysctl_tcp_invalid_ratelimit)) {
3796			NET_INC_STATS(net, mib_idx);
3797			return true;	/* rate-limited: don't send yet! */
3798		}
3799	}
3800
3801	/* Paired with the prior READ_ONCE() and with itself,
3802	 * as we might be lockless.
3803	 */
3804	WRITE_ONCE(*last_oow_ack_time, tcp_jiffies32);
3805
3806	return false;	/* not rate-limited: go ahead, send dupack now! */
3807}
3808
3809/* Return true if we're currently rate-limiting out-of-window ACKs and
3810 * thus shouldn't send a dupack right now. We rate-limit dupacks in
3811 * response to out-of-window SYNs or ACKs to mitigate ACK loops or DoS
3812 * attacks that send repeated SYNs or ACKs for the same connection. To
3813 * do this, we do not send a duplicate SYNACK or ACK if the remote
3814 * endpoint is sending out-of-window SYNs or pure ACKs at a high rate.
3815 */
3816bool tcp_oow_rate_limited(struct net *net, const struct sk_buff *skb,
3817			  int mib_idx, u32 *last_oow_ack_time)
3818{
3819	/* Data packets without SYNs are not likely part of an ACK loop. */
3820	if ((TCP_SKB_CB(skb)->seq != TCP_SKB_CB(skb)->end_seq) &&
3821	    !tcp_hdr(skb)->syn)
3822		return false;
3823
3824	return __tcp_oow_rate_limited(net, mib_idx, last_oow_ack_time);
3825}
3826
3827static void tcp_send_ack_reflect_ect(struct sock *sk, bool accecn_reflector)
3828{
3829	struct tcp_sock *tp = tcp_sk(sk);
3830	u16 flags = 0;
3831
3832	if (accecn_reflector)
3833		flags = tcp_accecn_reflector_flags(tp->syn_ect_rcv);
3834	__tcp_send_ack(sk, tp->rcv_nxt, flags);
3835}
3836
3837/* RFC 5961 7 [ACK Throttling] */
3838static void tcp_send_challenge_ack(struct sock *sk, bool accecn_reflector)
3839{
3840	struct tcp_sock *tp = tcp_sk(sk);
3841	struct net *net = sock_net(sk);
3842	u32 count, now, ack_limit;
3843
3844	/* First check our per-socket dupack rate limit. */
3845	if (__tcp_oow_rate_limited(net,
3846				   LINUX_MIB_TCPACKSKIPPEDCHALLENGE,
3847				   &tp->last_oow_ack_time))
3848		return;
3849
3850	ack_limit = READ_ONCE(net->ipv4.sysctl_tcp_challenge_ack_limit);
3851	if (ack_limit == INT_MAX)
3852		goto send_ack;
3853
3854	/* Then check host-wide RFC 5961 rate limit. */
3855	now = jiffies / HZ;
3856	if (now != READ_ONCE(net->ipv4.tcp_challenge_timestamp)) {
3857		u32 half = (ack_limit + 1) >> 1;
3858
3859		WRITE_ONCE(net->ipv4.tcp_challenge_timestamp, now);
3860		WRITE_ONCE(net->ipv4.tcp_challenge_count,
3861			   get_random_u32_inclusive(half, ack_limit + half - 1));
3862	}
3863	count = READ_ONCE(net->ipv4.tcp_challenge_count);
3864	if (count > 0) {
3865		WRITE_ONCE(net->ipv4.tcp_challenge_count, count - 1);
3866send_ack:
3867		NET_INC_STATS(net, LINUX_MIB_TCPCHALLENGEACK);
3868		tcp_send_ack_reflect_ect(sk, accecn_reflector);
3869	}
3870}
3871
3872static void tcp_store_ts_recent(struct tcp_sock *tp)
3873{
3874	tp->rx_opt.ts_recent = tp->rx_opt.rcv_tsval;
3875	tp->rx_opt.ts_recent_stamp = ktime_get_seconds();
3876}
3877
3878static int __tcp_replace_ts_recent(struct tcp_sock *tp, s32 tstamp_delta)
3879{
3880	tcp_store_ts_recent(tp);
3881	return tstamp_delta > 0 ? FLAG_TS_PROGRESS : 0;
3882}
3883
3884static int tcp_replace_ts_recent(struct tcp_sock *tp, u32 seq)
3885{
3886	s32 delta;
3887
3888	if (tp->rx_opt.saw_tstamp && !after(seq, tp->rcv_wup)) {
3889		/* PAWS bug workaround wrt. ACK frames, the PAWS discard
3890		 * extra check below makes sure this can only happen
3891		 * for pure ACK frames.  -DaveM
3892		 *
3893		 * Not only, also it occurs for expired timestamps.
3894		 */
3895
3896		if (tcp_paws_check(&tp->rx_opt, 0)) {
3897			delta = tp->rx_opt.rcv_tsval - tp->rx_opt.ts_recent;
3898			return __tcp_replace_ts_recent(tp, delta);
3899		}
3900	}
3901
3902	return 0;
3903}
3904
3905/* This routine deals with acks during a TLP episode and ends an episode by
3906 * resetting tlp_high_seq. Ref: TLP algorithm in RFC8985
3907 */
3908static void tcp_process_tlp_ack(struct sock *sk, u32 ack, int flag)
3909{
3910	struct tcp_sock *tp = tcp_sk(sk);
3911
3912	if (before(ack, tp->tlp_high_seq))
3913		return;
3914
3915	if (!tp->tlp_retrans) {
3916		/* TLP of new data has been acknowledged */
3917		tp->tlp_high_seq = 0;
3918	} else if (flag & FLAG_DSACK_TLP) {
3919		/* This DSACK means original and TLP probe arrived; no loss */
3920		tp->tlp_high_seq = 0;
3921	} else if (after(ack, tp->tlp_high_seq)) {
3922		/* ACK advances: there was a loss, so reduce cwnd. Reset
3923		 * tlp_high_seq in tcp_init_cwnd_reduction()
3924		 */
3925		tcp_init_cwnd_reduction(sk);
3926		tcp_set_ca_state(sk, TCP_CA_CWR);
3927		tcp_end_cwnd_reduction(sk);
3928		tcp_try_keep_open(sk);
3929		NET_INC_STATS(sock_net(sk),
3930				LINUX_MIB_TCPLOSSPROBERECOVERY);
3931	} else if (!(flag & (FLAG_SND_UNA_ADVANCED |
3932			     FLAG_NOT_DUP | FLAG_DATA_SACKED))) {
3933		/* Pure dupack: original and TLP probe arrived; no loss */
3934		tp->tlp_high_seq = 0;
3935	}
3936}
3937
3938static void tcp_in_ack_event(struct sock *sk, int flag)
3939{
3940	const struct inet_connection_sock *icsk = inet_csk(sk);
3941
3942	if (icsk->icsk_ca_ops->in_ack_event) {
3943		u32 ack_ev_flags = 0;
3944
3945		if (flag & FLAG_WIN_UPDATE)
3946			ack_ev_flags |= CA_ACK_WIN_UPDATE;
3947		if (flag & FLAG_SLOWPATH) {
3948			ack_ev_flags |= CA_ACK_SLOWPATH;
3949			if (flag & FLAG_ECE)
3950				ack_ev_flags |= CA_ACK_ECE;
3951		}
3952
3953		icsk->icsk_ca_ops->in_ack_event(sk, ack_ev_flags);
3954	}
3955}
3956
3957/* Congestion control has updated the cwnd already. So if we're in
3958 * loss recovery then now we do any new sends (for FRTO) or
3959 * retransmits (for CA_Loss or CA_recovery) that make sense.
3960 */
3961static void tcp_xmit_recovery(struct sock *sk, int rexmit)
3962{
3963	struct tcp_sock *tp = tcp_sk(sk);
3964
3965	if (rexmit == REXMIT_NONE || sk->sk_state == TCP_SYN_SENT)
3966		return;
3967
3968	if (unlikely(rexmit == REXMIT_NEW)) {
3969		__tcp_push_pending_frames(sk, tcp_current_mss(sk),
3970					  TCP_NAGLE_OFF);
3971		if (after(tp->snd_nxt, tp->high_seq))
3972			return;
3973		tp->frto = 0;
3974	}
3975	tcp_xmit_retransmit_queue(sk);
3976}
3977
3978/* Returns the number of packets newly acked or sacked by the current ACK */
3979static u32 tcp_newly_delivered(struct sock *sk, u32 prior_delivered,
3980			       u32 ecn_count, int flag)
3981{
3982	const struct net *net = sock_net(sk);
3983	struct tcp_sock *tp = tcp_sk(sk);
3984	u32 delivered;
3985
3986	delivered = tp->delivered - prior_delivered;
3987	NET_ADD_STATS(net, LINUX_MIB_TCPDELIVERED, delivered);
3988
3989	if (flag & FLAG_ECE) {
3990		if (tcp_ecn_mode_rfc3168(tp))
3991			ecn_count = delivered;
3992		NET_ADD_STATS(net, LINUX_MIB_TCPDELIVEREDCE, ecn_count);
3993	}
3994
3995	return delivered;
3996}
3997
3998/* This routine deals with incoming acks, but not outgoing ones. */
3999static int tcp_ack(struct sock *sk, const struct sk_buff *skb, int flag)
4000{
4001	struct inet_connection_sock *icsk = inet_csk(sk);
4002	struct tcp_sock *tp = tcp_sk(sk);
4003	struct tcp_sacktag_state sack_state;
4004	struct rate_sample rs = { .prior_delivered = 0 };
4005	u32 prior_snd_una = tp->snd_una;
4006	bool is_sack_reneg = tp->is_sack_reneg;
4007	u32 ack_seq = TCP_SKB_CB(skb)->seq;
4008	u32 ack = TCP_SKB_CB(skb)->ack_seq;
4009	int num_dupack = 0;
4010	int prior_packets = tp->packets_out;
4011	u32 delivered = tp->delivered;
4012	u32 lost = tp->lost;
4013	int rexmit = REXMIT_NONE; /* Flag to (re)transmit to recover losses */
4014	u32 ecn_count = 0;	  /* Did we receive ECE/an AccECN ACE update? */
4015	u32 prior_fack;
4016
4017	sack_state.first_sackt = 0;
4018	sack_state.rate = &rs;
4019	sack_state.sack_delivered = 0;
4020	sack_state.delivered_bytes = 0;
4021
4022	/* We very likely will need to access rtx queue. */
4023	prefetch(sk->tcp_rtx_queue.rb_node);
4024
4025	/* If the ack is older than previous acks
4026	 * then we can probably ignore it.
4027	 */
4028	if (before(ack, prior_snd_una)) {
4029		u32 max_window;
4030
4031		/* do not accept ACK for bytes we never sent. */
4032		max_window = min_t(u64, tp->max_window, tp->bytes_acked);
4033		/* RFC 5961 5.2 [Blind Data Injection Attack].[Mitigation] */
4034		if (before(ack, prior_snd_una - max_window)) {
4035			if (!(flag & FLAG_NO_CHALLENGE_ACK))
4036				tcp_send_challenge_ack(sk, false);
4037			return -SKB_DROP_REASON_TCP_TOO_OLD_ACK;
4038		}
4039		goto old_ack;
4040	}
4041
4042	/* If the ack includes data we haven't sent yet, discard
4043	 * this segment (RFC793 Section 3.9).
4044	 */
4045	if (after(ack, tp->snd_nxt))
4046		return -SKB_DROP_REASON_TCP_ACK_UNSENT_DATA;
4047
4048	if (after(ack, prior_snd_una)) {
4049		flag |= FLAG_SND_UNA_ADVANCED;
4050		WRITE_ONCE(icsk->icsk_retransmits, 0);
4051
4052#if IS_ENABLED(CONFIG_TLS_DEVICE)
4053		if (static_branch_unlikely(&clean_acked_data_enabled.key))
4054			if (tp->tcp_clean_acked)
4055				tp->tcp_clean_acked(sk, ack);
4056#endif
4057	}
4058
4059	prior_fack = tcp_is_sack(tp) ? tcp_highest_sack_seq(tp) : tp->snd_una;
4060	rs.prior_in_flight = tcp_packets_in_flight(tp);
4061
4062	/* ts_recent update must be made after we are sure that the packet
4063	 * is in window.
4064	 */
4065	if (flag & FLAG_UPDATE_TS_RECENT)
4066		flag |= tcp_replace_ts_recent(tp, TCP_SKB_CB(skb)->seq);
4067
4068	if ((flag & (FLAG_SLOWPATH | FLAG_SND_UNA_ADVANCED)) ==
4069	    FLAG_SND_UNA_ADVANCED) {
4070		/* Window is constant, pure forward advance.
4071		 * No more checks are required.
4072		 * Note, we use the fact that SND.UNA>=SND.WL2.
4073		 */
4074		tcp_update_wl(tp, ack_seq);
4075		tcp_snd_una_update(tp, ack);
4076		flag |= FLAG_WIN_UPDATE;
4077
4078		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPHPACKS);
4079	} else {
4080		if (ack_seq != TCP_SKB_CB(skb)->end_seq)
4081			flag |= FLAG_DATA;
4082		else
4083			NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPPUREACKS);
4084
4085		flag |= tcp_ack_update_window(sk, skb, ack, ack_seq);
4086
4087		if (TCP_SKB_CB(skb)->sacked)
4088			flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una,
4089							&sack_state);
4090
4091		if (tcp_ecn_rcv_ecn_echo(tp, tcp_hdr(skb)))
4092			flag |= FLAG_ECE;
4093
4094		if (sack_state.sack_delivered)
4095			tcp_count_delivered(tp, sack_state.sack_delivered,
4096					    flag & FLAG_ECE);
4097	}
4098
4099	/* This is a deviation from RFC3168 since it states that:
4100	 * "When the TCP data sender is ready to set the CWR bit after reducing
4101	 * the congestion window, it SHOULD set the CWR bit only on the first
4102	 * new data packet that it transmits."
4103	 * We accept CWR on pure ACKs to be more robust
4104	 * with widely-deployed TCP implementations that do this.
4105	 */
4106	tcp_ecn_accept_cwr(sk, skb);
4107
4108	/* We passed data and got it acked, remove any soft error
4109	 * log. Something worked...
4110	 */
4111	if (READ_ONCE(sk->sk_err_soft))
4112		WRITE_ONCE(sk->sk_err_soft, 0);
4113	WRITE_ONCE(icsk->icsk_probes_out, 0);
4114	tp->rcv_tstamp = tcp_jiffies32;
4115	if (!prior_packets)
4116		goto no_queue;
4117
4118	/* See if we can take anything off of the retransmit queue. */
4119	flag |= tcp_clean_rtx_queue(sk, skb, prior_fack, prior_snd_una,
4120				    &sack_state, flag & FLAG_ECE);
4121
4122	tcp_rack_update_reo_wnd(sk, &rs);
4123
4124	if (tcp_ecn_mode_accecn(tp))
4125		ecn_count = tcp_accecn_process(sk, skb,
4126					       tp->delivered - delivered,
4127					       sack_state.delivered_bytes,
4128					       &flag);
4129
4130	tcp_in_ack_event(sk, flag);
4131
4132	if (tp->tlp_high_seq)
4133		tcp_process_tlp_ack(sk, ack, flag);
4134
4135	if (tcp_ack_is_dubious(sk, flag)) {
4136		if (!(flag & (FLAG_SND_UNA_ADVANCED |
4137			      FLAG_NOT_DUP | FLAG_DSACKING_ACK))) {
4138			num_dupack = 1;
4139			/* Consider if pure acks were aggregated in tcp_add_backlog() */
4140			if (!(flag & FLAG_DATA))
4141				num_dupack = max_t(u16, 1, skb_shinfo(skb)->gso_segs);
4142		}
4143		tcp_fastretrans_alert(sk, prior_snd_una, num_dupack, &flag,
4144				      &rexmit);
4145	}
4146
4147	/* If needed, reset TLP/RTO timer when RACK doesn't set. */
4148	if (flag & FLAG_SET_XMIT_TIMER)
4149		tcp_set_xmit_timer(sk);
4150
4151	if ((flag & FLAG_FORWARD_PROGRESS) || !(flag & FLAG_NOT_DUP))
4152		sk_dst_confirm(sk);
4153
4154	delivered = tcp_newly_delivered(sk, delivered, ecn_count, flag);
4155
4156	lost = tp->lost - lost;			/* freshly marked lost */
4157	rs.is_ack_delayed = !!(flag & FLAG_ACK_MAYBE_DELAYED);
4158	tcp_rate_gen(sk, delivered, lost, is_sack_reneg, sack_state.rate);
4159	tcp_cong_control(sk, ack, delivered, flag, sack_state.rate);
4160	tcp_xmit_recovery(sk, rexmit);
4161	return 1;
4162
4163no_queue:
4164	if (tcp_ecn_mode_accecn(tp))
4165		ecn_count = tcp_accecn_process(sk, skb,
4166					       tp->delivered - delivered,
4167					       sack_state.delivered_bytes,
4168					       &flag);
4169	tcp_in_ack_event(sk, flag);
4170	/* If data was DSACKed, see if we can undo a cwnd reduction. */
4171	if (flag & FLAG_DSACKING_ACK) {
4172		tcp_fastretrans_alert(sk, prior_snd_una, num_dupack, &flag,
4173				      &rexmit);
4174		tcp_newly_delivered(sk, delivered, ecn_count, flag);
4175	}
4176	/* If this ack opens up a zero window, clear backoff.  It was
4177	 * being used to time the probes, and is probably far higher than
4178	 * it needs to be for normal retransmission.
4179	 */
4180	tcp_ack_probe(sk);
4181
4182	if (tp->tlp_high_seq)
4183		tcp_process_tlp_ack(sk, ack, flag);
4184	return 1;
4185
4186old_ack:
4187	/* If data was SACKed, tag it and see if we should send more data.
4188	 * If data was DSACKed, see if we can undo a cwnd reduction.
4189	 */
4190	if (TCP_SKB_CB(skb)->sacked) {
4191		flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una,
4192						&sack_state);
4193		tcp_fastretrans_alert(sk, prior_snd_una, num_dupack, &flag,
4194				      &rexmit);
4195		tcp_newly_delivered(sk, delivered, ecn_count, flag);
4196		tcp_xmit_recovery(sk, rexmit);
4197	}
4198
4199	return 0;
4200}
4201
4202static void tcp_parse_fastopen_option(int len, const unsigned char *cookie,
4203				      bool syn, struct tcp_fastopen_cookie *foc,
4204				      bool exp_opt)
4205{
4206	/* Valid only in SYN or SYN-ACK with an even length.  */
4207	if (!foc || !syn || len < 0 || (len & 1))
4208		return;
4209
4210	if (len >= TCP_FASTOPEN_COOKIE_MIN &&
4211	    len <= TCP_FASTOPEN_COOKIE_MAX)
4212		memcpy(foc->val, cookie, len);
4213	else if (len != 0)
4214		len = -1;
4215	foc->len = len;
4216	foc->exp = exp_opt;
4217}
4218
4219static bool smc_parse_options(const struct tcphdr *th,
4220			      struct tcp_options_received *opt_rx,
4221			      const unsigned char *ptr,
4222			      int opsize)
4223{
4224#if IS_ENABLED(CONFIG_SMC)
4225	if (static_branch_unlikely(&tcp_have_smc)) {
4226		if (th->syn && !(opsize & 1) &&
4227		    opsize >= TCPOLEN_EXP_SMC_BASE &&
4228		    get_unaligned_be32(ptr) == TCPOPT_SMC_MAGIC) {
4229			opt_rx->smc_ok = 1;
4230			return true;
4231		}
4232	}
4233#endif
4234	return false;
4235}
4236
4237/* Try to parse the MSS option from the TCP header. Return 0 on failure, clamped
4238 * value on success.
4239 */
4240u16 tcp_parse_mss_option(const struct tcphdr *th, u16 user_mss)
4241{
4242	const unsigned char *ptr = (const unsigned char *)(th + 1);
4243	int length = (th->doff * 4) - sizeof(struct tcphdr);
4244	u16 mss = 0;
4245
4246	while (length > 0) {
4247		int opcode = *ptr++;
4248		int opsize;
4249
4250		switch (opcode) {
4251		case TCPOPT_EOL:
4252			return mss;
4253		case TCPOPT_NOP:	/* Ref: RFC 793 section 3.1 */
4254			length--;
4255			continue;
4256		default:
4257			if (length < 2)
4258				return mss;
4259			opsize = *ptr++;
4260			if (opsize < 2) /* "silly options" */
4261				return mss;
4262			if (opsize > length)
4263				return mss;	/* fail on partial options */
4264			if (opcode == TCPOPT_MSS && opsize == TCPOLEN_MSS) {
4265				u16 in_mss = get_unaligned_be16(ptr);
4266
4267				if (in_mss) {
4268					if (user_mss && user_mss < in_mss)
4269						in_mss = user_mss;
4270					mss = in_mss;
4271				}
4272			}
4273			ptr += opsize - 2;
4274			length -= opsize;
4275		}
4276	}
4277	return mss;
4278}
4279
4280/* Look for tcp options. Normally only called on SYN and SYNACK packets.
4281 * But, this can also be called on packets in the established flow when
4282 * the fast version below fails.
4283 */
4284void tcp_parse_options(const struct net *net,
4285		       const struct sk_buff *skb,
4286		       struct tcp_options_received *opt_rx, int estab,
4287		       struct tcp_fastopen_cookie *foc)
4288{
4289	const unsigned char *ptr;
4290	const struct tcphdr *th = tcp_hdr(skb);
4291	int length = (th->doff * 4) - sizeof(struct tcphdr);
4292
4293	ptr = (const unsigned char *)(th + 1);
4294	opt_rx->saw_tstamp = 0;
4295	opt_rx->accecn = 0;
4296	opt_rx->saw_unknown = 0;
4297
4298	while (length > 0) {
4299		int opcode = *ptr++;
4300		int opsize;
4301
4302		switch (opcode) {
4303		case TCPOPT_EOL:
4304			return;
4305		case TCPOPT_NOP:	/* Ref: RFC 793 section 3.1 */
4306			length--;
4307			continue;
4308		default:
4309			if (length < 2)
4310				return;
4311			opsize = *ptr++;
4312			if (opsize < 2) /* "silly options" */
4313				return;
4314			if (opsize > length)
4315				return;	/* don't parse partial options */
4316			switch (opcode) {
4317			case TCPOPT_MSS:
4318				if (opsize == TCPOLEN_MSS && th->syn && !estab) {
4319					u16 in_mss = get_unaligned_be16(ptr);
4320					if (in_mss) {
4321						if (opt_rx->user_mss &&
4322						    opt_rx->user_mss < in_mss)
4323							in_mss = opt_rx->user_mss;
4324						opt_rx->mss_clamp = in_mss;
4325					}
4326				}
4327				break;
4328			case TCPOPT_WINDOW:
4329				if (opsize == TCPOLEN_WINDOW && th->syn &&
4330				    !estab && READ_ONCE(net->ipv4.sysctl_tcp_window_scaling)) {
4331					__u8 snd_wscale = *(__u8 *)ptr;
4332					opt_rx->wscale_ok = 1;
4333					if (snd_wscale > TCP_MAX_WSCALE) {
4334						net_info_ratelimited("%s: Illegal window scaling value %d > %u received\n",
4335								     __func__,
4336								     snd_wscale,
4337								     TCP_MAX_WSCALE);
4338						snd_wscale = TCP_MAX_WSCALE;
4339					}
4340					opt_rx->snd_wscale = snd_wscale;
4341				}
4342				break;
4343			case TCPOPT_TIMESTAMP:
4344				if ((opsize == TCPOLEN_TIMESTAMP) &&
4345				    ((estab && opt_rx->tstamp_ok) ||
4346				     (!estab && READ_ONCE(net->ipv4.sysctl_tcp_timestamps)))) {
4347					opt_rx->saw_tstamp = 1;
4348					opt_rx->rcv_tsval = get_unaligned_be32(ptr);
4349					opt_rx->rcv_tsecr = get_unaligned_be32(ptr + 4);
4350				}
4351				break;
4352			case TCPOPT_SACK_PERM:
4353				if (opsize == TCPOLEN_SACK_PERM && th->syn &&
4354				    !estab && READ_ONCE(net->ipv4.sysctl_tcp_sack)) {
4355					opt_rx->sack_ok = TCP_SACK_SEEN;
4356					tcp_sack_reset(opt_rx);
4357				}
4358				break;
4359
4360			case TCPOPT_SACK:
4361				if ((opsize >= (TCPOLEN_SACK_BASE + TCPOLEN_SACK_PERBLOCK)) &&
4362				   !((opsize - TCPOLEN_SACK_BASE) % TCPOLEN_SACK_PERBLOCK) &&
4363				   opt_rx->sack_ok) {
4364					TCP_SKB_CB(skb)->sacked = (ptr - 2) - (unsigned char *)th;
4365				}
4366				break;
4367#ifdef CONFIG_TCP_MD5SIG
4368			case TCPOPT_MD5SIG:
4369				/* The MD5 Hash has already been
4370				 * checked (see tcp_v{4,6}_rcv()).
4371				 */
4372				break;
4373#endif
4374#ifdef CONFIG_TCP_AO
4375			case TCPOPT_AO:
4376				/* TCP AO has already been checked
4377				 * (see tcp_inbound_ao_hash()).
4378				 */
4379				break;
4380#endif
4381			case TCPOPT_FASTOPEN:
4382				tcp_parse_fastopen_option(
4383					opsize - TCPOLEN_FASTOPEN_BASE,
4384					ptr, th->syn, foc, false);
4385				break;
4386
4387			case TCPOPT_ACCECN0:
4388			case TCPOPT_ACCECN1:
4389				/* Save offset of AccECN option in TCP header */
4390				opt_rx->accecn = (ptr - 2) - (__u8 *)th;
4391				break;
4392
4393			case TCPOPT_EXP:
4394				/* Fast Open option shares code 254 using a
4395				 * 16 bits magic number.
4396				 */
4397				if (opsize >= TCPOLEN_EXP_FASTOPEN_BASE &&
4398				    get_unaligned_be16(ptr) ==
4399				    TCPOPT_FASTOPEN_MAGIC) {
4400					tcp_parse_fastopen_option(opsize -
4401						TCPOLEN_EXP_FASTOPEN_BASE,
4402						ptr + 2, th->syn, foc, true);
4403					break;
4404				}
4405
4406				if (smc_parse_options(th, opt_rx, ptr, opsize))
4407					break;
4408
4409				opt_rx->saw_unknown = 1;
4410				break;
4411
4412			default:
4413				opt_rx->saw_unknown = 1;
4414			}
4415			ptr += opsize-2;
4416			length -= opsize;
4417		}
4418	}
4419}
4420EXPORT_SYMBOL(tcp_parse_options);
4421
4422static bool tcp_parse_aligned_timestamp(struct tcp_sock *tp, const struct tcphdr *th)
4423{
4424	const __be32 *ptr = (const __be32 *)(th + 1);
4425
4426	if (*ptr == htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16)
4427			  | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP)) {
4428		tp->rx_opt.saw_tstamp = 1;
4429		++ptr;
4430		tp->rx_opt.rcv_tsval = ntohl(*ptr);
4431		++ptr;
4432		if (*ptr)
4433			tp->rx_opt.rcv_tsecr = ntohl(*ptr) - tp->tsoffset;
4434		else
4435			tp->rx_opt.rcv_tsecr = 0;
4436		return true;
4437	}
4438	return false;
4439}
4440
4441/* Fast parse options. This hopes to only see timestamps.
4442 * If it is wrong it falls back on tcp_parse_options().
4443 */
4444static bool tcp_fast_parse_options(const struct net *net,
4445				   const struct sk_buff *skb,
4446				   const struct tcphdr *th, struct tcp_sock *tp)
4447{
4448	/* In the spirit of fast parsing, compare doff directly to constant
4449	 * values.  Because equality is used, short doff can be ignored here.
4450	 */
4451	if (th->doff == (sizeof(*th) / 4)) {
4452		tp->rx_opt.saw_tstamp = 0;
4453		tp->rx_opt.accecn = 0;
4454		return false;
4455	} else if (tp->rx_opt.tstamp_ok &&
4456		   th->doff == ((sizeof(*th) + TCPOLEN_TSTAMP_ALIGNED) / 4)) {
4457		if (tcp_parse_aligned_timestamp(tp, th)) {
4458			tp->rx_opt.accecn = 0;
4459			return true;
4460		}
4461	}
4462
4463	tcp_parse_options(net, skb, &tp->rx_opt, 1, NULL);
4464	if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr)
4465		tp->rx_opt.rcv_tsecr -= tp->tsoffset;
4466
4467	return true;
4468}
4469
4470#if defined(CONFIG_TCP_MD5SIG) || defined(CONFIG_TCP_AO)
4471/*
4472 * Parse Signature options
4473 */
4474int tcp_do_parse_auth_options(const struct tcphdr *th,
4475			      const u8 **md5_hash, const u8 **ao_hash)
4476{
4477	int length = (th->doff << 2) - sizeof(*th);
4478	const u8 *ptr = (const u8 *)(th + 1);
4479	unsigned int minlen = TCPOLEN_MD5SIG;
4480
4481	if (IS_ENABLED(CONFIG_TCP_AO))
4482		minlen = sizeof(struct tcp_ao_hdr) + 1;
4483
4484	*md5_hash = NULL;
4485	*ao_hash = NULL;
4486
4487	/* If not enough data remaining, we can short cut */
4488	while (length >= minlen) {
4489		int opcode = *ptr++;
4490		int opsize;
4491
4492		switch (opcode) {
4493		case TCPOPT_EOL:
4494			return 0;
4495		case TCPOPT_NOP:
4496			length--;
4497			continue;
4498		default:
4499			opsize = *ptr++;
4500			if (opsize < 2 || opsize > length)
4501				return -EINVAL;
4502			if (opcode == TCPOPT_MD5SIG) {
4503				if (opsize != TCPOLEN_MD5SIG)
4504					return -EINVAL;
4505				if (unlikely(*md5_hash || *ao_hash))
4506					return -EEXIST;
4507				*md5_hash = ptr;
4508			} else if (opcode == TCPOPT_AO) {
4509				if (opsize <= sizeof(struct tcp_ao_hdr))
4510					return -EINVAL;
4511				if (unlikely(*md5_hash || *ao_hash))
4512					return -EEXIST;
4513				*ao_hash = ptr;
4514			}
4515		}
4516		ptr += opsize - 2;
4517		length -= opsize;
4518	}
4519	return 0;
4520}
4521EXPORT_SYMBOL(tcp_do_parse_auth_options);
4522#endif
4523
4524/* Sorry, PAWS as specified is broken wrt. pure-ACKs -DaveM
4525 *
4526 * It is not fatal. If this ACK does _not_ change critical state (seqs, window)
4527 * it can pass through stack. So, the following predicate verifies that
4528 * this segment is not used for anything but congestion avoidance or
4529 * fast retransmit. Moreover, we even are able to eliminate most of such
4530 * second order effects, if we apply some small "replay" window (~RTO)
4531 * to timestamp space.
4532 *
4533 * All these measures still do not guarantee that we reject wrapped ACKs
4534 * on networks with high bandwidth, when sequence space is recycled fastly,
4535 * but it guarantees that such events will be very rare and do not affect
4536 * connection seriously. This doesn't look nice, but alas, PAWS is really
4537 * buggy extension.
4538 *
4539 * [ Later note. Even worse! It is buggy for segments _with_ data. RFC
4540 * states that events when retransmit arrives after original data are rare.
4541 * It is a blatant lie. VJ forgot about fast retransmit! 8)8) It is
4542 * the biggest problem on large power networks even with minor reordering.
4543 * OK, let's give it small replay window. If peer clock is even 1hz, it is safe
4544 * up to bandwidth of 18Gigabit/sec. 8) ]
4545 */
4546
4547/* Estimates max number of increments of remote peer TSval in
4548 * a replay window (based on our current RTO estimation).
4549 */
4550static u32 tcp_tsval_replay(const struct sock *sk)
4551{
4552	/* If we use usec TS resolution,
4553	 * then expect the remote peer to use the same resolution.
4554	 */
4555	if (tcp_sk(sk)->tcp_usec_ts)
4556		return inet_csk(sk)->icsk_rto * (USEC_PER_SEC / HZ);
4557
4558	/* RFC 7323 recommends a TSval clock between 1ms and 1sec.
4559	 * We know that some OS (including old linux) can use 1200 Hz.
4560	 */
4561	return inet_csk(sk)->icsk_rto * 1200 / HZ;
4562}
4563
4564static enum skb_drop_reason tcp_disordered_ack_check(const struct sock *sk,
4565						     const struct sk_buff *skb)
4566{
4567	const struct tcp_sock *tp = tcp_sk(sk);
4568	const struct tcphdr *th = tcp_hdr(skb);
4569	SKB_DR_INIT(reason, TCP_RFC7323_PAWS);
4570	u32 ack = TCP_SKB_CB(skb)->ack_seq;
4571	u32 seq = TCP_SKB_CB(skb)->seq;
4572
4573	/* 1. Is this not a pure ACK ? */
4574	if (!th->ack || seq != TCP_SKB_CB(skb)->end_seq)
4575		return reason;
4576
4577	/* 2. Is its sequence not the expected one ? */
4578	if (seq != tp->rcv_nxt)
4579		return before(seq, tp->rcv_nxt) ?
4580			SKB_DROP_REASON_TCP_RFC7323_PAWS_ACK :
4581			reason;
4582
4583	/* 3. Is this not a duplicate ACK ? */
4584	if (ack != tp->snd_una)
4585		return reason;
4586
4587	/* 4. Is this updating the window ? */
4588	if (tcp_may_update_window(tp, ack, seq, ntohs(th->window) <<
4589						tp->rx_opt.snd_wscale))
4590		return reason;
4591
4592	/* 5. Is this not in the replay window ? */
4593	if ((s32)(tp->rx_opt.ts_recent - tp->rx_opt.rcv_tsval) >
4594	    tcp_tsval_replay(sk))
4595		return reason;
4596
4597	return 0;
4598}
4599
4600/* Check segment sequence number for validity.
4601 *
4602 * Segment controls are considered valid, if the segment
4603 * fits to the window after truncation to the window. Acceptability
4604 * of data (and SYN, FIN, of course) is checked separately.
4605 * See tcp_data_queue(), for example.
4606 *
4607 * Also, controls (RST is main one) are accepted using RCV.WUP instead
4608 * of RCV.NXT. Peer still did not advance his SND.UNA when we
4609 * delayed ACK, so that hisSND.UNA<=ourRCV.WUP.
4610 * (borrowed from freebsd)
4611 */
4612
4613static enum skb_drop_reason tcp_sequence(const struct sock *sk,
4614					 u32 seq, u32 end_seq,
4615					 const struct tcphdr *th)
4616{
4617	const struct tcp_sock *tp = tcp_sk(sk);
4618	u32 seq_limit;
4619
4620	if (before(end_seq, tp->rcv_wup))
4621		return SKB_DROP_REASON_TCP_OLD_SEQUENCE;
4622
4623	seq_limit = tp->rcv_nxt + tcp_receive_window(tp);
4624	if (unlikely(after(end_seq, seq_limit))) {
4625		/* Some stacks are known to handle FIN incorrectly; allow the
4626		 * FIN to extend beyond the window and check it in detail later.
4627		 */
4628		if (!after(end_seq - th->fin, seq_limit))
4629			return SKB_NOT_DROPPED_YET;
4630
4631		if (after(seq, seq_limit))
4632			return SKB_DROP_REASON_TCP_INVALID_SEQUENCE;
4633
4634		/* Only accept this packet if receive queue is empty. */
4635		if (skb_queue_len(&sk->sk_receive_queue))
4636			return SKB_DROP_REASON_TCP_INVALID_END_SEQUENCE;
4637	}
4638
4639	return SKB_NOT_DROPPED_YET;
4640}
4641
4642
4643void tcp_done_with_error(struct sock *sk, int err)
4644{
4645	/* This barrier is coupled with smp_rmb() in tcp_poll() */
4646	WRITE_ONCE(sk->sk_err, err);
4647	smp_wmb();
4648
4649	tcp_write_queue_purge(sk);
4650	tcp_done(sk);
4651
4652	if (!sock_flag(sk, SOCK_DEAD))
4653		sk_error_report(sk);
4654}
4655EXPORT_IPV6_MOD(tcp_done_with_error);
4656
4657/* When we get a reset we do this. */
4658void tcp_reset(struct sock *sk, struct sk_buff *skb)
4659{
4660	int err;
4661
4662	trace_tcp_receive_reset(sk);
4663
4664	/* mptcp can't tell us to ignore reset pkts,
4665	 * so just ignore the return value of mptcp_incoming_options().
4666	 */
4667	if (sk_is_mptcp(sk))
4668		mptcp_incoming_options(sk, skb);
4669
4670	/* We want the right error as BSD sees it (and indeed as we do). */
4671	switch (sk->sk_state) {
4672	case TCP_SYN_SENT:
4673		err = ECONNREFUSED;
4674		break;
4675	case TCP_CLOSE_WAIT:
4676		err = EPIPE;
4677		break;
4678	case TCP_CLOSE:
4679		return;
4680	default:
4681		err = ECONNRESET;
4682	}
4683	tcp_done_with_error(sk, err);
4684}
4685
4686/*
4687 * 	Process the FIN bit. This now behaves as it is supposed to work
4688 *	and the FIN takes effect when it is validly part of sequence
4689 *	space. Not before when we get holes.
4690 *
4691 *	If we are ESTABLISHED, a received fin moves us to CLOSE-WAIT
4692 *	(and thence onto LAST-ACK and finally, CLOSE, we never enter
4693 *	TIME-WAIT)
4694 *
4695 *	If we are in FINWAIT-1, a received FIN indicates simultaneous
4696 *	close and we go into CLOSING (and later onto TIME-WAIT)
4697 *
4698 *	If we are in FINWAIT-2, a received FIN moves us to TIME-WAIT.
4699 */
4700void tcp_fin(struct sock *sk)
4701{
4702	struct tcp_sock *tp = tcp_sk(sk);
4703
4704	inet_csk_schedule_ack(sk);
4705
4706	WRITE_ONCE(sk->sk_shutdown, sk->sk_shutdown | RCV_SHUTDOWN);
4707	sock_set_flag(sk, SOCK_DONE);
4708
4709	switch (sk->sk_state) {
4710	case TCP_SYN_RECV:
4711	case TCP_ESTABLISHED:
4712		/* Move to CLOSE_WAIT */
4713		tcp_set_state(sk, TCP_CLOSE_WAIT);
4714		inet_csk_enter_pingpong_mode(sk);
4715		break;
4716
4717	case TCP_CLOSE_WAIT:
4718	case TCP_CLOSING:
4719		/* Received a retransmission of the FIN, do
4720		 * nothing.
4721		 */
4722		break;
4723	case TCP_LAST_ACK:
4724		/* RFC793: Remain in the LAST-ACK state. */
4725		break;
4726
4727	case TCP_FIN_WAIT1:
4728		/* This case occurs when a simultaneous close
4729		 * happens, we must ack the received FIN and
4730		 * enter the CLOSING state.
4731		 */
4732		tcp_send_ack(sk);
4733		tcp_set_state(sk, TCP_CLOSING);
4734		break;
4735	case TCP_FIN_WAIT2:
4736		/* Received a FIN -- send ACK and enter TIME_WAIT. */
4737		tcp_send_ack(sk);
4738		tcp_time_wait(sk, TCP_TIME_WAIT, 0);
4739		break;
4740	default:
4741		/* Only TCP_LISTEN and TCP_CLOSE are left, in these
4742		 * cases we should never reach this piece of code.
4743		 */
4744		pr_err("%s: Impossible, sk->sk_state=%d\n",
4745		       __func__, sk->sk_state);
4746		break;
4747	}
4748
4749	/* It _is_ possible, that we have something out-of-order _after_ FIN.
4750	 * Probably, we should reset in this case. For now drop them.
4751	 */
4752	skb_rbtree_purge(&tp->out_of_order_queue);
4753	if (tcp_is_sack(tp))
4754		tcp_sack_reset(&tp->rx_opt);
4755
4756	if (!sock_flag(sk, SOCK_DEAD)) {
4757		sk->sk_state_change(sk);
4758
4759		/* Do not send POLL_HUP for half duplex close. */
4760		if (sk->sk_shutdown == SHUTDOWN_MASK ||
4761		    sk->sk_state == TCP_CLOSE)
4762			sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP);
4763		else
4764			sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
4765	}
4766}
4767
4768static inline bool tcp_sack_extend(struct tcp_sack_block *sp, u32 seq,
4769				  u32 end_seq)
4770{
4771	if (!after(seq, sp->end_seq) && !after(sp->start_seq, end_seq)) {
4772		if (before(seq, sp->start_seq))
4773			sp->start_seq = seq;
4774		if (after(end_seq, sp->end_seq))
4775			sp->end_seq = end_seq;
4776		return true;
4777	}
4778	return false;
4779}
4780
4781static void tcp_dsack_set(struct sock *sk, u32 seq, u32 end_seq)
4782{
4783	struct tcp_sock *tp = tcp_sk(sk);
4784
4785	if (tcp_is_sack(tp) && READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_dsack)) {
4786		int mib_idx;
4787
4788		if (before(seq, tp->rcv_nxt))
4789			mib_idx = LINUX_MIB_TCPDSACKOLDSENT;
4790		else
4791			mib_idx = LINUX_MIB_TCPDSACKOFOSENT;
4792
4793		NET_INC_STATS(sock_net(sk), mib_idx);
4794
4795		tp->rx_opt.dsack = 1;
4796		tp->duplicate_sack[0].start_seq = seq;
4797		tp->duplicate_sack[0].end_seq = end_seq;
4798	}
4799}
4800
4801static void tcp_dsack_extend(struct sock *sk, u32 seq, u32 end_seq)
4802{
4803	struct tcp_sock *tp = tcp_sk(sk);
4804
4805	if (!tp->rx_opt.dsack)
4806		tcp_dsack_set(sk, seq, end_seq);
4807	else
4808		tcp_sack_extend(tp->duplicate_sack, seq, end_seq);
4809}
4810
4811static void tcp_rcv_spurious_retrans(struct sock *sk, const struct sk_buff *skb)
4812{
4813	/* When the ACK path fails or drops most ACKs, the sender would
4814	 * timeout and spuriously retransmit the same segment repeatedly.
4815	 * If it seems our ACKs are not reaching the other side,
4816	 * based on receiving a duplicate data segment with new flowlabel
4817	 * (suggesting the sender suffered an RTO), and we are not already
4818	 * repathing due to our own RTO, then rehash the socket to repath our
4819	 * packets.
4820	 */
4821#if IS_ENABLED(CONFIG_IPV6)
4822	if (inet_csk(sk)->icsk_ca_state != TCP_CA_Loss &&
4823	    skb->protocol == htons(ETH_P_IPV6) &&
4824	    (tcp_sk(sk)->inet_conn.icsk_ack.lrcv_flowlabel !=
4825	     ntohl(ip6_flowlabel(ipv6_hdr(skb)))) &&
4826	    sk_rethink_txhash(sk))
4827		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDUPLICATEDATAREHASH);
4828
4829	/* Save last flowlabel after a spurious retrans. */
4830	tcp_save_lrcv_flowlabel(sk, skb);
4831#endif
4832}
4833
4834static void tcp_send_dupack(struct sock *sk, const struct sk_buff *skb)
4835{
4836	struct tcp_sock *tp = tcp_sk(sk);
4837
4838	if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
4839	    before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
4840		NET_INC_STATS(sock_net(sk), LINUX_MIB_DELAYEDACKLOST);
4841		tcp_enter_quickack_mode(sk, TCP_MAX_QUICKACKS);
4842
4843		if (tcp_is_sack(tp) && READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_dsack)) {
4844			u32 end_seq = TCP_SKB_CB(skb)->end_seq;
4845
4846			tcp_rcv_spurious_retrans(sk, skb);
4847			if (after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt))
4848				end_seq = tp->rcv_nxt;
4849			tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, end_seq);
4850		}
4851	}
4852
4853	tcp_send_ack(sk);
4854}
4855
4856/* These routines update the SACK block as out-of-order packets arrive or
4857 * in-order packets close up the sequence space.
4858 */
4859static void tcp_sack_maybe_coalesce(struct tcp_sock *tp)
4860{
4861	int this_sack;
4862	struct tcp_sack_block *sp = &tp->selective_acks[0];
4863	struct tcp_sack_block *swalk = sp + 1;
4864
4865	/* See if the recent change to the first SACK eats into
4866	 * or hits the sequence space of other SACK blocks, if so coalesce.
4867	 */
4868	for (this_sack = 1; this_sack < tp->rx_opt.num_sacks;) {
4869		if (tcp_sack_extend(sp, swalk->start_seq, swalk->end_seq)) {
4870			int i;
4871
4872			/* Zap SWALK, by moving every further SACK up by one slot.
4873			 * Decrease num_sacks.
4874			 */
4875			tp->rx_opt.num_sacks--;
4876			for (i = this_sack; i < tp->rx_opt.num_sacks; i++)
4877				sp[i] = sp[i + 1];
4878			continue;
4879		}
4880		this_sack++;
4881		swalk++;
4882	}
4883}
4884
4885void tcp_sack_compress_send_ack(struct sock *sk)
4886{
4887	struct tcp_sock *tp = tcp_sk(sk);
4888
4889	if (!tp->compressed_ack)
4890		return;
4891
4892	if (hrtimer_try_to_cancel(&tp->compressed_ack_timer) == 1)
4893		__sock_put(sk);
4894
4895	/* Since we have to send one ack finally,
4896	 * substract one from tp->compressed_ack to keep
4897	 * LINUX_MIB_TCPACKCOMPRESSED accurate.
4898	 */
4899	NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPACKCOMPRESSED,
4900		      tp->compressed_ack - 1);
4901
4902	tp->compressed_ack = 0;
4903	tcp_send_ack(sk);
4904}
4905
4906/* Reasonable amount of sack blocks included in TCP SACK option
4907 * The max is 4, but this becomes 3 if TCP timestamps are there.
4908 * Given that SACK packets might be lost, be conservative and use 2.
4909 */
4910#define TCP_SACK_BLOCKS_EXPECTED 2
4911
4912static void tcp_sack_new_ofo_skb(struct sock *sk, u32 seq, u32 end_seq)
4913{
4914	struct tcp_sock *tp = tcp_sk(sk);
4915	struct tcp_sack_block *sp = &tp->selective_acks[0];
4916	int cur_sacks = tp->rx_opt.num_sacks;
4917	int this_sack;
4918
4919	if (!cur_sacks)
4920		goto new_sack;
4921
4922	for (this_sack = 0; this_sack < cur_sacks; this_sack++, sp++) {
4923		if (tcp_sack_extend(sp, seq, end_seq)) {
4924			if (this_sack >= TCP_SACK_BLOCKS_EXPECTED)
4925				tcp_sack_compress_send_ack(sk);
4926			/* Rotate this_sack to the first one. */
4927			for (; this_sack > 0; this_sack--, sp--)
4928				swap(*sp, *(sp - 1));
4929			if (cur_sacks > 1)
4930				tcp_sack_maybe_coalesce(tp);
4931			return;
4932		}
4933	}
4934
4935	if (this_sack >= TCP_SACK_BLOCKS_EXPECTED)
4936		tcp_sack_compress_send_ack(sk);
4937
4938	/* Could not find an adjacent existing SACK, build a new one,
4939	 * put it at the front, and shift everyone else down.  We
4940	 * always know there is at least one SACK present already here.
4941	 *
4942	 * If the sack array is full, forget about the last one.
4943	 */
4944	if (this_sack >= TCP_NUM_SACKS) {
4945		this_sack--;
4946		tp->rx_opt.num_sacks--;
4947		sp--;
4948	}
4949	for (; this_sack > 0; this_sack--, sp--)
4950		*sp = *(sp - 1);
4951
4952new_sack:
4953	/* Build the new head SACK, and we're done. */
4954	sp->start_seq = seq;
4955	sp->end_seq = end_seq;
4956	tp->rx_opt.num_sacks++;
4957}
4958
4959/* RCV.NXT advances, some SACKs should be eaten. */
4960
4961static void tcp_sack_remove(struct tcp_sock *tp)
4962{
4963	struct tcp_sack_block *sp = &tp->selective_acks[0];
4964	int num_sacks = tp->rx_opt.num_sacks;
4965	int this_sack;
4966
4967	/* Empty ofo queue, hence, all the SACKs are eaten. Clear. */
4968	if (RB_EMPTY_ROOT(&tp->out_of_order_queue)) {
4969		tp->rx_opt.num_sacks = 0;
4970		return;
4971	}
4972
4973	for (this_sack = 0; this_sack < num_sacks;) {
4974		/* Check if the start of the sack is covered by RCV.NXT. */
4975		if (!before(tp->rcv_nxt, sp->start_seq)) {
4976			int i;
4977
4978			/* RCV.NXT must cover all the block! */
4979			WARN_ON(before(tp->rcv_nxt, sp->end_seq));
4980
4981			/* Zap this SACK, by moving forward any other SACKS. */
4982			for (i = this_sack+1; i < num_sacks; i++)
4983				tp->selective_acks[i-1] = tp->selective_acks[i];
4984			num_sacks--;
4985			continue;
4986		}
4987		this_sack++;
4988		sp++;
4989	}
4990	tp->rx_opt.num_sacks = num_sacks;
4991}
4992
4993/**
4994 * tcp_try_coalesce - try to merge skb to prior one
4995 * @sk: socket
4996 * @to: prior buffer
4997 * @from: buffer to add in queue
4998 * @fragstolen: pointer to boolean
4999 *
5000 * Before queueing skb @from after @to, try to merge them
5001 * to reduce overall memory use and queue lengths, if cost is small.
5002 * Packets in ofo or receive queues can stay a long time.
5003 * Better try to coalesce them right now to avoid future collapses.
5004 * Returns true if caller should free @from instead of queueing it
5005 */
5006static bool tcp_try_coalesce(struct sock *sk,
5007			     struct sk_buff *to,
5008			     struct sk_buff *from,
5009			     bool *fragstolen)
5010{
5011	int delta;
5012
5013	*fragstolen = false;
5014
5015	/* Its possible this segment overlaps with prior segment in queue */
5016	if (TCP_SKB_CB(from)->seq != TCP_SKB_CB(to)->end_seq)
5017		return false;
5018
5019	if (!tcp_skb_can_collapse_rx(to, from))
5020		return false;
5021
5022	if (!skb_try_coalesce(to, from, fragstolen, &delta))
5023		return false;
5024
5025	atomic_add(delta, &sk->sk_rmem_alloc);
5026	sk_mem_charge(sk, delta);
5027	NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPRCVCOALESCE);
5028	TCP_SKB_CB(to)->end_seq = TCP_SKB_CB(from)->end_seq;
5029	TCP_SKB_CB(to)->ack_seq = TCP_SKB_CB(from)->ack_seq;
5030	TCP_SKB_CB(to)->tcp_flags |= TCP_SKB_CB(from)->tcp_flags;
5031
5032	if (TCP_SKB_CB(from)->has_rxtstamp) {
5033		TCP_SKB_CB(to)->has_rxtstamp = true;
5034		to->tstamp = from->tstamp;
5035		skb_hwtstamps(to)->hwtstamp = skb_hwtstamps(from)->hwtstamp;
5036	}
5037
5038	return true;
5039}
5040
5041static bool tcp_ooo_try_coalesce(struct sock *sk,
5042			     struct sk_buff *to,
5043			     struct sk_buff *from,
5044			     bool *fragstolen)
5045{
5046	bool res = tcp_try_coalesce(sk, to, from, fragstolen);
5047
5048	/* In case tcp_drop_reason() is called later, update to->gso_segs */
5049	if (res) {
5050		u32 gso_segs = max_t(u16, 1, skb_shinfo(to)->gso_segs) +
5051			       max_t(u16, 1, skb_shinfo(from)->gso_segs);
5052
5053		skb_shinfo(to)->gso_segs = min_t(u32, gso_segs, 0xFFFF);
5054	}
5055	return res;
5056}
5057
5058noinline_for_tracing static void
5059tcp_drop_reason(struct sock *sk, struct sk_buff *skb, enum skb_drop_reason reason)
5060{
5061	sk_drops_skbadd(sk, skb);
5062	sk_skb_reason_drop(sk, skb, reason);
5063}
5064
5065/* This one checks to see if we can put data from the
5066 * out_of_order queue into the receive_queue.
5067 */
5068static void tcp_ofo_queue(struct sock *sk)
5069{
5070	struct tcp_sock *tp = tcp_sk(sk);
5071	__u32 dsack_high = tp->rcv_nxt;
5072	bool fin, fragstolen, eaten;
5073	struct sk_buff *skb, *tail;
5074	struct rb_node *p;
5075
5076	p = rb_first(&tp->out_of_order_queue);
5077	while (p) {
5078		skb = rb_to_skb(p);
5079		if (after(TCP_SKB_CB(skb)->seq, tp->rcv_nxt))
5080			break;
5081
5082		if (before(TCP_SKB_CB(skb)->seq, dsack_high)) {
5083			__u32 dsack = dsack_high;
5084
5085			if (before(TCP_SKB_CB(skb)->end_seq, dsack_high))
5086				dsack = TCP_SKB_CB(skb)->end_seq;
5087			tcp_dsack_extend(sk, TCP_SKB_CB(skb)->seq, dsack);
5088		}
5089		p = rb_next(p);
5090		rb_erase(&skb->rbnode, &tp->out_of_order_queue);
5091
5092		if (unlikely(!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt))) {
5093			tcp_drop_reason(sk, skb, SKB_DROP_REASON_TCP_OFO_DROP);
5094			continue;
5095		}
5096
5097		tail = skb_peek_tail(&sk->sk_receive_queue);
5098		eaten = tail && tcp_try_coalesce(sk, tail, skb, &fragstolen);
5099		tcp_rcv_nxt_update(tp, TCP_SKB_CB(skb)->end_seq);
5100		fin = TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN;
5101		if (!eaten)
5102			tcp_add_receive_queue(sk, skb);
5103		else
5104			kfree_skb_partial(skb, fragstolen);
5105
5106		if (unlikely(fin)) {
5107			tcp_fin(sk);
5108			/* tcp_fin() purges tp->out_of_order_queue,
5109			 * so we must end this loop right now.
5110			 */
5111			break;
5112		}
5113	}
5114}
5115
5116static bool tcp_prune_ofo_queue(struct sock *sk, const struct sk_buff *in_skb);
5117static int tcp_prune_queue(struct sock *sk, const struct sk_buff *in_skb);
5118
5119static bool tcp_can_ingest(const struct sock *sk, const struct sk_buff *skb)
5120{
5121	unsigned int rmem = atomic_read(&sk->sk_rmem_alloc);
5122
5123	return rmem <= sk->sk_rcvbuf;
5124}
5125
5126static int tcp_try_rmem_schedule(struct sock *sk, const struct sk_buff *skb,
5127				 unsigned int size)
5128{
5129	if (!tcp_can_ingest(sk, skb) ||
5130	    !sk_rmem_schedule(sk, skb, size)) {
5131
5132		if (tcp_prune_queue(sk, skb) < 0)
5133			return -1;
5134
5135		while (!sk_rmem_schedule(sk, skb, size)) {
5136			if (!tcp_prune_ofo_queue(sk, skb))
5137				return -1;
5138		}
5139	}
5140	return 0;
5141}
5142
5143static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb)
5144{
5145	struct tcp_sock *tp = tcp_sk(sk);
5146	struct rb_node **p, *parent;
5147	struct sk_buff *skb1;
5148	u32 seq, end_seq;
5149	bool fragstolen;
5150
5151	tcp_save_lrcv_flowlabel(sk, skb);
5152	tcp_data_ecn_check(sk, skb);
5153
5154	if (unlikely(tcp_try_rmem_schedule(sk, skb, skb->truesize))) {
5155		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPOFODROP);
5156		READ_ONCE(sk->sk_data_ready)(sk);
5157		tcp_drop_reason(sk, skb, SKB_DROP_REASON_PROTO_MEM);
5158		return;
5159	}
5160
5161	tcp_measure_rcv_mss(sk, skb);
5162	/* Disable header prediction. */
5163	tp->pred_flags = 0;
5164	inet_csk_schedule_ack(sk);
5165
5166	tp->rcv_ooopack += max_t(u16, 1, skb_shinfo(skb)->gso_segs);
5167	NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPOFOQUEUE);
5168	seq = TCP_SKB_CB(skb)->seq;
5169	end_seq = TCP_SKB_CB(skb)->end_seq;
5170
5171	p = &tp->out_of_order_queue.rb_node;
5172	if (RB_EMPTY_ROOT(&tp->out_of_order_queue)) {
5173		/* Initial out of order segment, build 1 SACK. */
5174		if (tcp_is_sack(tp)) {
5175			tp->rx_opt.num_sacks = 1;
5176			tp->selective_acks[0].start_seq = seq;
5177			tp->selective_acks[0].end_seq = end_seq;
5178		}
5179		rb_link_node(&skb->rbnode, NULL, p);
5180		rb_insert_color(&skb->rbnode, &tp->out_of_order_queue);
5181		tp->ooo_last_skb = skb;
5182		goto end;
5183	}
5184
5185	/* In the typical case, we are adding an skb to the end of the list.
5186	 * Use of ooo_last_skb avoids the O(Log(N)) rbtree lookup.
5187	 */
5188	if (tcp_ooo_try_coalesce(sk, tp->ooo_last_skb,
5189				 skb, &fragstolen)) {
5190coalesce_done:
5191		/* For non sack flows, do not grow window to force DUPACK
5192		 * and trigger fast retransmit.
5193		 */
5194		if (tcp_is_sack(tp))
5195			tcp_grow_window(sk, skb, true);
5196		kfree_skb_partial(skb, fragstolen);
5197		skb = NULL;
5198		goto add_sack;
5199	}
5200	/* Can avoid an rbtree lookup if we are adding skb after ooo_last_skb */
5201	if (!before(seq, TCP_SKB_CB(tp->ooo_last_skb)->end_seq)) {
5202		parent = &tp->ooo_last_skb->rbnode;
5203		p = &parent->rb_right;
5204		goto insert;
5205	}
5206
5207	/* Find place to insert this segment. Handle overlaps on the way. */
5208	parent = NULL;
5209	while (*p) {
5210		parent = *p;
5211		skb1 = rb_to_skb(parent);
5212		if (before(seq, TCP_SKB_CB(skb1)->seq)) {
5213			p = &parent->rb_left;
5214			continue;
5215		}
5216		if (before(seq, TCP_SKB_CB(skb1)->end_seq)) {
5217			if (!after(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
5218				/* All the bits are present. Drop. */
5219				NET_INC_STATS(sock_net(sk),
5220					      LINUX_MIB_TCPOFOMERGE);
5221				tcp_drop_reason(sk, skb,
5222						SKB_DROP_REASON_TCP_OFOMERGE);
5223				skb = NULL;
5224				tcp_dsack_set(sk, seq, end_seq);
5225				goto add_sack;
5226			}
5227			if (after(seq, TCP_SKB_CB(skb1)->seq)) {
5228				/* Partial overlap. */
5229				tcp_dsack_set(sk, seq, TCP_SKB_CB(skb1)->end_seq);
5230			} else {
5231				/* skb's seq == skb1's seq and skb covers skb1.
5232				 * Replace skb1 with skb.
5233				 */
5234				rb_replace_node(&skb1->rbnode, &skb->rbnode,
5235						&tp->out_of_order_queue);
5236				tcp_dsack_extend(sk,
5237						 TCP_SKB_CB(skb1)->seq,
5238						 TCP_SKB_CB(skb1)->end_seq);
5239				NET_INC_STATS(sock_net(sk),
5240					      LINUX_MIB_TCPOFOMERGE);
5241				tcp_drop_reason(sk, skb1,
5242						SKB_DROP_REASON_TCP_OFOMERGE);
5243				goto merge_right;
5244			}
5245		} else if (tcp_ooo_try_coalesce(sk, skb1,
5246						skb, &fragstolen)) {
5247			goto coalesce_done;
5248		}
5249		p = &parent->rb_right;
5250	}
5251insert:
5252	/* Insert segment into RB tree. */
5253	rb_link_node(&skb->rbnode, parent, p);
5254	rb_insert_color(&skb->rbnode, &tp->out_of_order_queue);
5255
5256merge_right:
5257	/* Remove other segments covered by skb. */
5258	while ((skb1 = skb_rb_next(skb)) != NULL) {
5259		if (!after(end_seq, TCP_SKB_CB(skb1)->seq))
5260			break;
5261		if (before(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
5262			tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq,
5263					 end_seq);
5264			break;
5265		}
5266		rb_erase(&skb1->rbnode, &tp->out_of_order_queue);
5267		tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq,
5268				 TCP_SKB_CB(skb1)->end_seq);
5269		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPOFOMERGE);
5270		tcp_drop_reason(sk, skb1, SKB_DROP_REASON_TCP_OFOMERGE);
5271	}
5272	/* If there is no skb after us, we are the last_skb ! */
5273	if (!skb1)
5274		tp->ooo_last_skb = skb;
5275
5276add_sack:
5277	if (tcp_is_sack(tp))
5278		tcp_sack_new_ofo_skb(sk, seq, end_seq);
5279end:
5280	if (skb) {
5281		/* For non sack flows, do not grow window to force DUPACK
5282		 * and trigger fast retransmit.
5283		 */
5284		if (tcp_is_sack(tp))
5285			tcp_grow_window(sk, skb, false);
5286		skb_condense(skb);
5287		skb_set_owner_r(skb, sk);
5288	}
5289	/* do not grow rcvbuf for not-yet-accepted or orphaned sockets. */
5290	if (sk->sk_socket)
5291		tcp_rcvbuf_grow(sk, tp->rcvq_space.space);
5292}
5293
5294static int __must_check tcp_queue_rcv(struct sock *sk, struct sk_buff *skb,
5295				      bool *fragstolen)
5296{
5297	int eaten;
5298	struct sk_buff *tail = skb_peek_tail(&sk->sk_receive_queue);
5299
5300	eaten = (tail &&
5301		 tcp_try_coalesce(sk, tail,
5302				  skb, fragstolen)) ? 1 : 0;
5303	tcp_rcv_nxt_update(tcp_sk(sk), TCP_SKB_CB(skb)->end_seq);
5304	if (!eaten) {
5305		tcp_add_receive_queue(sk, skb);
5306		skb_set_owner_r(skb, sk);
5307	}
5308	return eaten;
5309}
5310
5311int tcp_send_rcvq(struct sock *sk, struct msghdr *msg, size_t size)
5312{
5313	struct sk_buff *skb;
5314	int err = -ENOMEM;
5315	int data_len = 0;
5316	bool fragstolen;
5317
5318	if (size == 0)
5319		return 0;
5320
5321	if (size > PAGE_SIZE) {
5322		int npages = min_t(size_t, size >> PAGE_SHIFT, MAX_SKB_FRAGS);
5323
5324		data_len = npages << PAGE_SHIFT;
5325		size = data_len + (size & ~PAGE_MASK);
5326	}
5327	skb = alloc_skb_with_frags(size - data_len, data_len,
5328				   PAGE_ALLOC_COSTLY_ORDER,
5329				   &err, sk->sk_allocation);
5330	if (!skb)
5331		goto err;
5332
5333	skb_put(skb, size - data_len);
5334	skb->data_len = data_len;
5335	skb->len = size;
5336
5337	if (tcp_try_rmem_schedule(sk, skb, skb->truesize)) {
5338		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPRCVQDROP);
5339		goto err_free;
5340	}
5341
5342	err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, size);
5343	if (err)
5344		goto err_free;
5345
5346	TCP_SKB_CB(skb)->seq = tcp_sk(sk)->rcv_nxt;
5347	TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(skb)->seq + size;
5348	TCP_SKB_CB(skb)->ack_seq = tcp_sk(sk)->snd_una - 1;
5349
5350	if (tcp_queue_rcv(sk, skb, &fragstolen)) {
5351		WARN_ON_ONCE(fragstolen); /* should not happen */
5352		__kfree_skb(skb);
5353	}
5354	return size;
5355
5356err_free:
5357	kfree_skb(skb);
5358err:
5359	return err;
5360
5361}
5362
5363void tcp_data_ready(struct sock *sk)
5364{
5365	if (tcp_epollin_ready(sk, sk->sk_rcvlowat) || sock_flag(sk, SOCK_DONE))
5366		READ_ONCE(sk->sk_data_ready)(sk);
5367}
5368
5369static void tcp_data_queue(struct sock *sk, struct sk_buff *skb)
5370{
5371	struct tcp_sock *tp = tcp_sk(sk);
5372	enum skb_drop_reason reason;
5373	bool fragstolen;
5374	int eaten;
5375
5376	/* If a subflow has been reset, the packet should not continue
5377	 * to be processed, drop the packet.
5378	 */
5379	if (sk_is_mptcp(sk) && !mptcp_incoming_options(sk, skb)) {
5380		__kfree_skb(skb);
5381		return;
5382	}
5383
5384	if (TCP_SKB_CB(skb)->seq == TCP_SKB_CB(skb)->end_seq) {
5385		__kfree_skb(skb);
5386		return;
5387	}
5388	tcp_cleanup_skb(skb);
5389	__skb_pull(skb, tcp_hdr(skb)->doff * 4);
5390
5391	reason = SKB_DROP_REASON_NOT_SPECIFIED;
5392	tp->rx_opt.dsack = 0;
5393
5394	/*  Queue data for delivery to the user.
5395	 *  Packets in sequence go to the receive queue.
5396	 *  Out of sequence packets to the out_of_order_queue.
5397	 */
5398	if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt) {
5399		if (tcp_receive_window(tp) == 0) {
5400			/* Some stacks are known to send bare FIN packets
5401			 * in a loop even if we send RWIN 0 in our ACK.
5402			 * Accepting this FIN does not hurt memory pressure
5403			 * because the FIN flag will simply be merged to the
5404			 * receive queue tail skb in most cases.
5405			 */
5406			if (!skb->len &&
5407			    (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN))
5408				goto queue_and_out;
5409
5410			reason = SKB_DROP_REASON_TCP_ZEROWINDOW;
5411			NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPZEROWINDOWDROP);
5412			goto out_of_window;
5413		}
5414
5415		/* Ok. In sequence. In window. */
5416queue_and_out:
5417		if (tcp_try_rmem_schedule(sk, skb, skb->truesize)) {
5418			/* TODO: maybe ratelimit these WIN 0 ACK ? */
5419			inet_csk(sk)->icsk_ack.pending |=
5420					(ICSK_ACK_NOMEM | ICSK_ACK_NOW);
5421			inet_csk_schedule_ack(sk);
5422			READ_ONCE(sk->sk_data_ready)(sk);
5423
5424			if (skb_queue_len(&sk->sk_receive_queue) && skb->len) {
5425				reason = SKB_DROP_REASON_PROTO_MEM;
5426				NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPRCVQDROP);
5427				goto drop;
5428			}
5429			sk_forced_mem_schedule(sk, skb->truesize);
5430		}
5431
5432		eaten = tcp_queue_rcv(sk, skb, &fragstolen);
5433		if (skb->len)
5434			tcp_event_data_recv(sk, skb);
5435		if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
5436			tcp_fin(sk);
5437
5438		if (!RB_EMPTY_ROOT(&tp->out_of_order_queue)) {
5439			tcp_ofo_queue(sk);
5440
5441			/* RFC5681. 4.2. SHOULD send immediate ACK, when
5442			 * gap in queue is filled.
5443			 */
5444			if (RB_EMPTY_ROOT(&tp->out_of_order_queue))
5445				inet_csk(sk)->icsk_ack.pending |= ICSK_ACK_NOW;
5446		}
5447
5448		if (tp->rx_opt.num_sacks)
5449			tcp_sack_remove(tp);
5450
5451		tcp_fast_path_check(sk);
5452
5453		if (eaten > 0)
5454			kfree_skb_partial(skb, fragstolen);
5455		if (!sock_flag(sk, SOCK_DEAD))
5456			tcp_data_ready(sk);
5457		return;
5458	}
5459
5460	if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) {
5461		tcp_rcv_spurious_retrans(sk, skb);
5462		/* A retransmit, 2nd most common case.  Force an immediate ack. */
5463		reason = SKB_DROP_REASON_TCP_OLD_DATA;
5464		NET_INC_STATS(sock_net(sk), LINUX_MIB_DELAYEDACKLOST);
5465		tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq);
5466
5467out_of_window:
5468		tcp_enter_quickack_mode(sk, TCP_MAX_QUICKACKS);
5469		inet_csk_schedule_ack(sk);
5470drop:
5471		tcp_drop_reason(sk, skb, reason);
5472		return;
5473	}
5474
5475	/* Out of window. F.e. zero window probe. */
5476	if (!before(TCP_SKB_CB(skb)->seq,
5477		    tp->rcv_nxt + tcp_receive_window(tp))) {
5478		reason = SKB_DROP_REASON_TCP_OVERWINDOW;
5479		goto out_of_window;
5480	}
5481
5482	if (before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
5483		/* Partial packet, seq < rcv_next < end_seq */
5484		tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, tp->rcv_nxt);
5485
5486		/* If window is closed, drop tail of packet. But after
5487		 * remembering D-SACK for its head made in previous line.
5488		 */
5489		if (!tcp_receive_window(tp)) {
5490			reason = SKB_DROP_REASON_TCP_ZEROWINDOW;
5491			NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPZEROWINDOWDROP);
5492			goto out_of_window;
5493		}
5494		goto queue_and_out;
5495	}
5496
5497	tcp_data_queue_ofo(sk, skb);
5498}
5499
5500static struct sk_buff *tcp_skb_next(struct sk_buff *skb, struct sk_buff_head *list)
5501{
5502	if (list)
5503		return !skb_queue_is_last(list, skb) ? skb->next : NULL;
5504
5505	return skb_rb_next(skb);
5506}
5507
5508static struct sk_buff *tcp_collapse_one(struct sock *sk, struct sk_buff *skb,
5509					struct sk_buff_head *list,
5510					struct rb_root *root)
5511{
5512	struct sk_buff *next = tcp_skb_next(skb, list);
5513
5514	if (list)
5515		__skb_unlink(skb, list);
5516	else
5517		rb_erase(&skb->rbnode, root);
5518
5519	__kfree_skb(skb);
5520	NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPRCVCOLLAPSED);
5521
5522	return next;
5523}
5524
5525/* Insert skb into rb tree, ordered by TCP_SKB_CB(skb)->seq */
5526void tcp_rbtree_insert(struct rb_root *root, struct sk_buff *skb)
5527{
5528	struct rb_node **p = &root->rb_node;
5529	struct rb_node *parent = NULL;
5530	struct sk_buff *skb1;
5531
5532	while (*p) {
5533		parent = *p;
5534		skb1 = rb_to_skb(parent);
5535		if (before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb1)->seq))
5536			p = &parent->rb_left;
5537		else
5538			p = &parent->rb_right;
5539	}
5540	rb_link_node(&skb->rbnode, parent, p);
5541	rb_insert_color(&skb->rbnode, root);
5542}
5543
5544/* Collapse contiguous sequence of skbs head..tail with
5545 * sequence numbers start..end.
5546 *
5547 * If tail is NULL, this means until the end of the queue.
5548 *
5549 * Segments with FIN/SYN are not collapsed (only because this
5550 * simplifies code)
5551 */
5552static void
5553tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root,
5554	     struct sk_buff *head, struct sk_buff *tail, u32 start, u32 end)
5555{
5556	struct sk_buff *skb = head, *n;
5557	struct sk_buff_head tmp;
5558	bool end_of_skbs;
5559
5560	/* First, check that queue is collapsible and find
5561	 * the point where collapsing can be useful.
5562	 */
5563restart:
5564	for (end_of_skbs = true; skb != NULL && skb != tail; skb = n) {
5565		n = tcp_skb_next(skb, list);
5566
5567		if (!skb_frags_readable(skb))
5568			goto skip_this;
5569
5570		/* No new bits? It is possible on ofo queue. */
5571		if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
5572			skb = tcp_collapse_one(sk, skb, list, root);
5573			if (!skb)
5574				break;
5575			goto restart;
5576		}
5577
5578		/* The first skb to collapse is:
5579		 * - not SYN/FIN and
5580		 * - bloated or contains data before "start" or
5581		 *   overlaps to the next one and mptcp allow collapsing.
5582		 */
5583		if (!(TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN)) &&
5584		    (tcp_win_from_space(sk, skb->truesize) > skb->len ||
5585		     before(TCP_SKB_CB(skb)->seq, start))) {
5586			end_of_skbs = false;
5587			break;
5588		}
5589
5590		if (n && n != tail && skb_frags_readable(n) &&
5591		    tcp_skb_can_collapse_rx(skb, n) &&
5592		    TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(n)->seq) {
5593			end_of_skbs = false;
5594			break;
5595		}
5596
5597skip_this:
5598		/* Decided to skip this, advance start seq. */
5599		start = TCP_SKB_CB(skb)->end_seq;
5600	}
5601	if (end_of_skbs ||
5602	    (TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN)) ||
5603	    !skb_frags_readable(skb))
5604		return;
5605
5606	__skb_queue_head_init(&tmp);
5607
5608	while (before(start, end)) {
5609		int copy = min_t(int, SKB_MAX_ORDER(0, 0), end - start);
5610		struct sk_buff *nskb;
5611
5612		nskb = alloc_skb(copy, GFP_ATOMIC);
5613		if (!nskb)
5614			break;
5615
5616		memcpy(nskb->cb, skb->cb, sizeof(skb->cb));
5617		skb_copy_decrypted(nskb, skb);
5618		TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(nskb)->end_seq = start;
5619		if (list)
5620			__skb_queue_before(list, skb, nskb);
5621		else
5622			__skb_queue_tail(&tmp, nskb); /* defer rbtree insertion */
5623		skb_set_owner_r(nskb, sk);
5624		mptcp_skb_ext_move(nskb, skb);
5625
5626		/* Copy data, releasing collapsed skbs. */
5627		while (copy > 0) {
5628			int offset = start - TCP_SKB_CB(skb)->seq;
5629			int size = TCP_SKB_CB(skb)->end_seq - start;
5630
5631			BUG_ON(offset < 0);
5632			if (size > 0) {
5633				size = min(copy, size);
5634				if (skb_copy_bits(skb, offset, skb_put(nskb, size), size))
5635					BUG();
5636				TCP_SKB_CB(nskb)->end_seq += size;
5637				copy -= size;
5638				start += size;
5639			}
5640			if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
5641				skb = tcp_collapse_one(sk, skb, list, root);
5642				if (!skb ||
5643				    skb == tail ||
5644				    !tcp_skb_can_collapse_rx(nskb, skb) ||
5645				    (TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN)) ||
5646				    !skb_frags_readable(skb))
5647					goto end;
5648			}
5649		}
5650	}
5651end:
5652	skb_queue_walk_safe(&tmp, skb, n)
5653		tcp_rbtree_insert(root, skb);
5654}
5655
5656/* Collapse ofo queue. Algorithm: select contiguous sequence of skbs
5657 * and tcp_collapse() them until all the queue is collapsed.
5658 */
5659static void tcp_collapse_ofo_queue(struct sock *sk)
5660{
5661	struct tcp_sock *tp = tcp_sk(sk);
5662	u32 range_truesize, sum_tiny = 0;
5663	struct sk_buff *skb, *head;
5664	u32 start, end;
5665
5666	skb = skb_rb_first(&tp->out_of_order_queue);
5667new_range:
5668	if (!skb) {
5669		tp->ooo_last_skb = skb_rb_last(&tp->out_of_order_queue);
5670		return;
5671	}
5672	start = TCP_SKB_CB(skb)->seq;
5673	end = TCP_SKB_CB(skb)->end_seq;
5674	range_truesize = skb->truesize;
5675
5676	for (head = skb;;) {
5677		skb = skb_rb_next(skb);
5678
5679		/* Range is terminated when we see a gap or when
5680		 * we are at the queue end.
5681		 */
5682		if (!skb ||
5683		    after(TCP_SKB_CB(skb)->seq, end) ||
5684		    before(TCP_SKB_CB(skb)->end_seq, start)) {
5685			/* Do not attempt collapsing tiny skbs */
5686			if (range_truesize != head->truesize ||
5687			    end - start >= SKB_WITH_OVERHEAD(PAGE_SIZE)) {
5688				tcp_collapse(sk, NULL, &tp->out_of_order_queue,
5689					     head, skb, start, end);
5690			} else {
5691				sum_tiny += range_truesize;
5692				if (sum_tiny > sk->sk_rcvbuf >> 3)
5693					return;
5694			}
5695			goto new_range;
5696		}
5697
5698		range_truesize += skb->truesize;
5699		if (unlikely(before(TCP_SKB_CB(skb)->seq, start)))
5700			start = TCP_SKB_CB(skb)->seq;
5701		if (after(TCP_SKB_CB(skb)->end_seq, end))
5702			end = TCP_SKB_CB(skb)->end_seq;
5703	}
5704}
5705
5706/*
5707 * Clean the out-of-order queue to make room.
5708 * We drop high sequences packets to :
5709 * 1) Let a chance for holes to be filled.
5710 *    This means we do not drop packets from ooo queue if their sequence
5711 *    is before incoming packet sequence.
5712 * 2) not add too big latencies if thousands of packets sit there.
5713 *    (But if application shrinks SO_RCVBUF, we could still end up
5714 *     freeing whole queue here)
5715 * 3) Drop at least 12.5 % of sk_rcvbuf to avoid malicious attacks.
5716 *
5717 * Return true if queue has shrunk.
5718 */
5719static bool tcp_prune_ofo_queue(struct sock *sk, const struct sk_buff *in_skb)
5720{
5721	struct tcp_sock *tp = tcp_sk(sk);
5722	struct rb_node *node, *prev;
5723	bool pruned = false;
5724	int goal;
5725
5726	if (RB_EMPTY_ROOT(&tp->out_of_order_queue))
5727		return false;
5728
5729	goal = sk->sk_rcvbuf >> 3;
5730	node = &tp->ooo_last_skb->rbnode;
5731
5732	do {
5733		struct sk_buff *skb = rb_to_skb(node);
5734
5735		/* If incoming skb would land last in ofo queue, stop pruning. */
5736		if (after(TCP_SKB_CB(in_skb)->seq, TCP_SKB_CB(skb)->seq))
5737			break;
5738		pruned = true;
5739		prev = rb_prev(node);
5740		rb_erase(node, &tp->out_of_order_queue);
5741		goal -= skb->truesize;
5742		tcp_drop_reason(sk, skb, SKB_DROP_REASON_TCP_OFO_QUEUE_PRUNE);
5743		tp->ooo_last_skb = rb_to_skb(prev);
5744		if (!prev || goal <= 0) {
5745			if (tcp_can_ingest(sk, in_skb) &&
5746			    !tcp_under_memory_pressure(sk))
5747				break;
5748			goal = sk->sk_rcvbuf >> 3;
5749		}
5750		node = prev;
5751	} while (node);
5752
5753	if (pruned) {
5754		NET_INC_STATS(sock_net(sk), LINUX_MIB_OFOPRUNED);
5755		/* Reset SACK state.  A conforming SACK implementation will
5756		 * do the same at a timeout based retransmit.  When a connection
5757		 * is in a sad state like this, we care only about integrity
5758		 * of the connection not performance.
5759		 */
5760		if (tp->rx_opt.sack_ok)
5761			tcp_sack_reset(&tp->rx_opt);
5762	}
5763	return pruned;
5764}
5765
5766/* Reduce allocated memory if we can, trying to get
5767 * the socket within its memory limits again.
5768 *
5769 * Return less than zero if we should start dropping frames
5770 * until the socket owning process reads some of the data
5771 * to stabilize the situation.
5772 */
5773static int tcp_prune_queue(struct sock *sk, const struct sk_buff *in_skb)
5774{
5775	struct tcp_sock *tp = tcp_sk(sk);
5776
5777	/* Do nothing if our queues are empty. */
5778	if (!atomic_read(&sk->sk_rmem_alloc))
5779		return -1;
5780
5781	NET_INC_STATS(sock_net(sk), LINUX_MIB_PRUNECALLED);
5782
5783	if (!tcp_can_ingest(sk, in_skb))
5784		tcp_clamp_window(sk);
5785	else if (tcp_under_memory_pressure(sk))
5786		tcp_adjust_rcv_ssthresh(sk);
5787
5788	if (tcp_can_ingest(sk, in_skb))
5789		return 0;
5790
5791	tcp_collapse_ofo_queue(sk);
5792	if (!skb_queue_empty(&sk->sk_receive_queue))
5793		tcp_collapse(sk, &sk->sk_receive_queue, NULL,
5794			     skb_peek(&sk->sk_receive_queue),
5795			     NULL,
5796			     tp->copied_seq, tp->rcv_nxt);
5797
5798	if (tcp_can_ingest(sk, in_skb))
5799		return 0;
5800
5801	/* Collapsing did not help, destructive actions follow.
5802	 * This must not ever occur. */
5803
5804	tcp_prune_ofo_queue(sk, in_skb);
5805
5806	if (tcp_can_ingest(sk, in_skb))
5807		return 0;
5808
5809	/* If we are really being abused, tell the caller to silently
5810	 * drop receive data on the floor.  It will get retransmitted
5811	 * and hopefully then we'll have sufficient space.
5812	 */
5813	NET_INC_STATS(sock_net(sk), LINUX_MIB_RCVPRUNED);
5814
5815	/* Massive buffer overcommit. */
5816	tp->pred_flags = 0;
5817	return -1;
5818}
5819
5820static bool tcp_should_expand_sndbuf(struct sock *sk)
5821{
5822	const struct tcp_sock *tp = tcp_sk(sk);
5823
5824	/* If the user specified a specific send buffer setting, do
5825	 * not modify it.
5826	 */
5827	if (sk->sk_userlocks & SOCK_SNDBUF_LOCK)
5828		return false;
5829
5830	/* If we are under global TCP memory pressure, do not expand.  */
5831	if (tcp_under_memory_pressure(sk)) {
5832		int unused_mem = sk_unused_reserved_mem(sk);
5833
5834		/* Adjust sndbuf according to reserved mem. But make sure
5835		 * it never goes below SOCK_MIN_SNDBUF.
5836		 * See sk_stream_moderate_sndbuf() for more details.
5837		 */
5838		if (unused_mem > SOCK_MIN_SNDBUF)
5839			WRITE_ONCE(sk->sk_sndbuf, unused_mem);
5840
5841		return false;
5842	}
5843
5844	/* If we are under soft global TCP memory pressure, do not expand.  */
5845	if (sk_memory_allocated(sk) >= sk_prot_mem_limits(sk, 0))
5846		return false;
5847
5848	/* If we filled the congestion window, do not expand.  */
5849	if (tcp_packets_in_flight(tp) >= tcp_snd_cwnd(tp))
5850		return false;
5851
5852	return true;
5853}
5854
5855static void tcp_new_space(struct sock *sk)
5856{
5857	struct tcp_sock *tp = tcp_sk(sk);
5858
5859	if (tcp_should_expand_sndbuf(sk)) {
5860		tcp_sndbuf_expand(sk);
5861		tp->snd_cwnd_stamp = tcp_jiffies32;
5862	}
5863
5864	INDIRECT_CALL_1(READ_ONCE(sk->sk_write_space),
5865			sk_stream_write_space,
5866			sk);
5867}
5868
5869/* Caller made space either from:
5870 * 1) Freeing skbs in rtx queues (after tp->snd_una has advanced)
5871 * 2) Sent skbs from output queue (and thus advancing tp->snd_nxt)
5872 *
5873 * We might be able to generate EPOLLOUT to the application if:
5874 * 1) Space consumed in output/rtx queues is below sk->sk_sndbuf/2
5875 * 2) notsent amount (tp->write_seq - tp->snd_nxt) became
5876 *    small enough that tcp_stream_memory_free() decides it
5877 *    is time to generate EPOLLOUT.
5878 */
5879void tcp_check_space(struct sock *sk)
5880{
5881	/* pairs with tcp_poll() */
5882	smp_mb();
5883	if (sk->sk_socket &&
5884	    test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
5885		tcp_new_space(sk);
5886		if (!test_bit(SOCK_NOSPACE, &sk->sk_socket->flags))
5887			tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED);
5888	}
5889}
5890
5891static inline void tcp_data_snd_check(struct sock *sk)
5892{
5893	tcp_push_pending_frames(sk);
5894	tcp_check_space(sk);
5895}
5896
5897/*
5898 * Check if sending an ack is needed.
5899 */
5900static void __tcp_ack_snd_check(struct sock *sk, int ofo_possible)
5901{
5902	struct tcp_sock *tp = tcp_sk(sk);
5903	struct net *net = sock_net(sk);
5904	unsigned long rtt;
5905	u64 delay;
5906
5907	    /* More than one full frame received... */
5908	if (((tp->rcv_nxt - tp->rcv_wup) > inet_csk(sk)->icsk_ack.rcv_mss &&
5909	     /* ... and right edge of window advances far enough.
5910	      * (tcp_recvmsg() will send ACK otherwise).
5911	      * If application uses SO_RCVLOWAT, we want send ack now if
5912	      * we have not received enough bytes to satisfy the condition.
5913	      */
5914	    (tp->rcv_nxt - tp->copied_seq < sk->sk_rcvlowat ||
5915	     __tcp_select_window(sk) >= tp->rcv_wnd)) ||
5916	    /* We ACK each frame or... */
5917	    tcp_in_quickack_mode(sk) ||
5918	    /* Protocol state mandates a one-time immediate ACK */
5919	    inet_csk(sk)->icsk_ack.pending & ICSK_ACK_NOW) {
5920		/* If we are running from __release_sock() in user context,
5921		 * Defer the ack until tcp_release_cb().
5922		 */
5923		if (sock_owned_by_user_nocheck(sk) &&
5924		    READ_ONCE(net->ipv4.sysctl_tcp_backlog_ack_defer)) {
5925			set_bit(TCP_ACK_DEFERRED, &sk->sk_tsq_flags);
5926			return;
5927		}
5928send_now:
5929		tcp_send_ack(sk);
5930		return;
5931	}
5932
5933	if (!ofo_possible || RB_EMPTY_ROOT(&tp->out_of_order_queue)) {
5934		tcp_send_delayed_ack(sk);
5935		return;
5936	}
5937
5938	if (!tcp_is_sack(tp) ||
5939	    tp->compressed_ack >= READ_ONCE(net->ipv4.sysctl_tcp_comp_sack_nr))
5940		goto send_now;
5941
5942	if (tp->compressed_ack_rcv_nxt != tp->rcv_nxt) {
5943		tp->compressed_ack_rcv_nxt = tp->rcv_nxt;
5944		tp->dup_ack_counter = 0;
5945	}
5946	if (tp->dup_ack_counter < TCP_FASTRETRANS_THRESH) {
5947		tp->dup_ack_counter++;
5948		goto send_now;
5949	}
5950	tp->compressed_ack++;
5951	if (hrtimer_is_queued(&tp->compressed_ack_timer))
5952		return;
5953
5954	/* compress ack timer : comp_sack_rtt_percent of rtt,
5955	 * but no more than tcp_comp_sack_delay_ns.
5956	 */
5957
5958	rtt = tp->rcv_rtt_est.rtt_us;
5959	if (tp->srtt_us && tp->srtt_us < rtt)
5960		rtt = tp->srtt_us;
5961
5962	/* delay = (rtt >> 3) * NSEC_PER_USEC * comp_sack_rtt_percent / 100
5963	 * ->
5964	 * delay = rtt * 1.25 * comp_sack_rtt_percent
5965	 */
5966	delay = (u64)(rtt + (rtt >> 2)) *
5967		READ_ONCE(net->ipv4.sysctl_tcp_comp_sack_rtt_percent);
5968
5969	delay = min(delay, READ_ONCE(net->ipv4.sysctl_tcp_comp_sack_delay_ns));
5970
5971	sock_hold(sk);
5972	hrtimer_start_range_ns(&tp->compressed_ack_timer, ns_to_ktime(delay),
5973			       READ_ONCE(net->ipv4.sysctl_tcp_comp_sack_slack_ns),
5974			       HRTIMER_MODE_REL_PINNED_SOFT);
5975}
5976
5977static inline void tcp_ack_snd_check(struct sock *sk)
5978{
5979	if (!inet_csk_ack_scheduled(sk)) {
5980		/* We sent a data segment already. */
5981		return;
5982	}
5983	__tcp_ack_snd_check(sk, 1);
5984}
5985
5986/*
5987 *	This routine is only called when we have urgent data
5988 *	signaled. Its the 'slow' part of tcp_urg. It could be
5989 *	moved inline now as tcp_urg is only called from one
5990 *	place. We handle URGent data wrong. We have to - as
5991 *	BSD still doesn't use the correction from RFC961.
5992 *	For 1003.1g we should support a new option TCP_STDURG to permit
5993 *	either form (or just set the sysctl tcp_stdurg).
5994 */
5995
5996static void tcp_check_urg(struct sock *sk, const struct tcphdr *th)
5997{
5998	struct tcp_sock *tp = tcp_sk(sk);
5999	u32 ptr = ntohs(th->urg_ptr);
6000
6001	if (ptr && !READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_stdurg))
6002		ptr--;
6003	ptr += ntohl(th->seq);
6004
6005	/* Ignore urgent data that we've already seen and read. */
6006	if (after(tp->copied_seq, ptr))
6007		return;
6008
6009	/* Do not replay urg ptr.
6010	 *
6011	 * NOTE: interesting situation not covered by specs.
6012	 * Misbehaving sender may send urg ptr, pointing to segment,
6013	 * which we already have in ofo queue. We are not able to fetch
6014	 * such data and will stay in TCP_URG_NOTYET until will be eaten
6015	 * by recvmsg(). Seems, we are not obliged to handle such wicked
6016	 * situations. But it is worth to think about possibility of some
6017	 * DoSes using some hypothetical application level deadlock.
6018	 */
6019	if (before(ptr, tp->rcv_nxt))
6020		return;
6021
6022	/* Do we already have a newer (or duplicate) urgent pointer? */
6023	if (tp->urg_data && !after(ptr, tp->urg_seq))
6024		return;
6025
6026	/* Tell the world about our new urgent pointer. */
6027	sk_send_sigurg(sk);
6028
6029	/* We may be adding urgent data when the last byte read was
6030	 * urgent. To do this requires some care. We cannot just ignore
6031	 * tp->copied_seq since we would read the last urgent byte again
6032	 * as data, nor can we alter copied_seq until this data arrives
6033	 * or we break the semantics of SIOCATMARK (and thus sockatmark())
6034	 *
6035	 * NOTE. Double Dutch. Rendering to plain English: author of comment
6036	 * above did something sort of 	send("A", MSG_OOB); send("B", MSG_OOB);
6037	 * and expect that both A and B disappear from stream. This is _wrong_.
6038	 * Though this happens in BSD with high probability, this is occasional.
6039	 * Any application relying on this is buggy. Note also, that fix "works"
6040	 * only in this artificial test. Insert some normal data between A and B and we will
6041	 * decline of BSD again. Verdict: it is better to remove to trap
6042	 * buggy users.
6043	 */
6044	if (tp->urg_seq == tp->copied_seq && tp->urg_data &&
6045	    !sock_flag(sk, SOCK_URGINLINE) && tp->copied_seq != tp->rcv_nxt) {
6046		struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
6047		tp->copied_seq++;
6048		if (skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq)) {
6049			__skb_unlink(skb, &sk->sk_receive_queue);
6050			__kfree_skb(skb);
6051		}
6052	}
6053
6054	WRITE_ONCE(tp->urg_data, TCP_URG_NOTYET);
6055	WRITE_ONCE(tp->urg_seq, ptr);
6056
6057	/* Disable header prediction. */
6058	tp->pred_flags = 0;
6059}
6060
6061/* This is the 'fast' part of urgent handling. */
6062static void tcp_urg(struct sock *sk, struct sk_buff *skb, const struct tcphdr *th)
6063{
6064	struct tcp_sock *tp = tcp_sk(sk);
6065
6066	/* Check if we get a new urgent pointer - normally not. */
6067	if (unlikely(th->urg))
6068		tcp_check_urg(sk, th);
6069
6070	/* Do we wait for any urgent data? - normally not... */
6071	if (unlikely(tp->urg_data == TCP_URG_NOTYET)) {
6072		u32 ptr = tp->urg_seq - ntohl(th->seq) + (th->doff * 4) -
6073			  th->syn;
6074
6075		/* Is the urgent pointer pointing into this packet? */
6076		if (ptr < skb->len) {
6077			u8 tmp;
6078			if (skb_copy_bits(skb, ptr, &tmp, 1))
6079				BUG();
6080			WRITE_ONCE(tp->urg_data, TCP_URG_VALID | tmp);
6081			if (!sock_flag(sk, SOCK_DEAD))
6082				READ_ONCE(sk->sk_data_ready)(sk);
6083		}
6084	}
6085}
6086
6087/* Accept RST for rcv_nxt - 1 after a FIN.
6088 * When tcp connections are abruptly terminated from Mac OSX (via ^C), a
6089 * FIN is sent followed by a RST packet. The RST is sent with the same
6090 * sequence number as the FIN, and thus according to RFC 5961 a challenge
6091 * ACK should be sent. However, Mac OSX rate limits replies to challenge
6092 * ACKs on the closed socket. In addition middleboxes can drop either the
6093 * challenge ACK or a subsequent RST.
6094 */
6095static bool tcp_reset_check(const struct sock *sk, const struct sk_buff *skb)
6096{
6097	const struct tcp_sock *tp = tcp_sk(sk);
6098
6099	return unlikely(TCP_SKB_CB(skb)->seq == (tp->rcv_nxt - 1) &&
6100			(1 << sk->sk_state) & (TCPF_CLOSE_WAIT | TCPF_LAST_ACK |
6101					       TCPF_CLOSING));
6102}
6103
6104/* Does PAWS and seqno based validation of an incoming segment, flags will
6105 * play significant role here.
6106 */
6107static bool tcp_validate_incoming(struct sock *sk, struct sk_buff *skb,
6108				  const struct tcphdr *th, int syn_inerr)
6109{
6110	struct tcp_sock *tp = tcp_sk(sk);
6111	bool accecn_reflector = false;
6112	SKB_DR(reason);
6113
6114	/* RFC1323: H1. Apply PAWS check first. */
6115	if (!tcp_fast_parse_options(sock_net(sk), skb, th, tp) ||
6116	    !tp->rx_opt.saw_tstamp ||
6117	    tcp_paws_check(&tp->rx_opt, TCP_PAWS_WINDOW))
6118		goto step1;
6119
6120	reason = tcp_disordered_ack_check(sk, skb);
6121	if (!reason)
6122		goto step1;
6123	/* Reset is accepted even if it did not pass PAWS. */
6124	if (th->rst)
6125		goto step1;
6126	if (unlikely(th->syn))
6127		goto syn_challenge;
6128
6129	/* Old ACK are common, increment PAWS_OLD_ACK
6130	 * and do not send a dupack.
6131	 */
6132	if (reason == SKB_DROP_REASON_TCP_RFC7323_PAWS_ACK) {
6133		NET_INC_STATS(sock_net(sk), LINUX_MIB_PAWS_OLD_ACK);
6134		goto discard;
6135	}
6136	NET_INC_STATS(sock_net(sk), LINUX_MIB_PAWSESTABREJECTED);
6137	if (!tcp_oow_rate_limited(sock_net(sk), skb,
6138				  LINUX_MIB_TCPACKSKIPPEDPAWS,
6139				  &tp->last_oow_ack_time))
6140		tcp_send_dupack(sk, skb);
6141	goto discard;
6142
6143step1:
6144	/* Step 1: check sequence number */
6145	reason = tcp_sequence(sk, TCP_SKB_CB(skb)->seq,
6146			      TCP_SKB_CB(skb)->end_seq, th);
6147	if (reason) {
6148		/* RFC793, page 37: "In all states except SYN-SENT, all reset
6149		 * (RST) segments are validated by checking their SEQ-fields."
6150		 * And page 69: "If an incoming segment is not acceptable,
6151		 * an acknowledgment should be sent in reply (unless the RST
6152		 * bit is set, if so drop the segment and return)".
6153		 */
6154		if (!th->rst) {
6155			if (th->syn)
6156				goto syn_challenge;
6157
6158			if (reason == SKB_DROP_REASON_TCP_INVALID_SEQUENCE ||
6159			    reason == SKB_DROP_REASON_TCP_INVALID_END_SEQUENCE)
6160				NET_INC_STATS(sock_net(sk),
6161					      LINUX_MIB_BEYOND_WINDOW);
6162			if (!tcp_oow_rate_limited(sock_net(sk), skb,
6163						  LINUX_MIB_TCPACKSKIPPEDSEQ,
6164						  &tp->last_oow_ack_time))
6165				tcp_send_dupack(sk, skb);
6166		} else if (tcp_reset_check(sk, skb)) {
6167			goto reset;
6168		}
6169		goto discard;
6170	}
6171
6172	/* Step 2: check RST bit */
6173	if (th->rst) {
6174		/* RFC 5961 3.2 (extend to match against (RCV.NXT - 1) after a
6175		 * FIN and SACK too if available):
6176		 * If seq num matches RCV.NXT or (RCV.NXT - 1) after a FIN, or
6177		 * the right-most SACK block,
6178		 * then
6179		 *     RESET the connection
6180		 * else
6181		 *     Send a challenge ACK
6182		 */
6183		if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt ||
6184		    tcp_reset_check(sk, skb))
6185			goto reset;
6186
6187		if (tcp_is_sack(tp) && tp->rx_opt.num_sacks > 0) {
6188			struct tcp_sack_block *sp = &tp->selective_acks[0];
6189			int max_sack = sp[0].end_seq;
6190			int this_sack;
6191
6192			for (this_sack = 1; this_sack < tp->rx_opt.num_sacks;
6193			     ++this_sack) {
6194				max_sack = after(sp[this_sack].end_seq,
6195						 max_sack) ?
6196					sp[this_sack].end_seq : max_sack;
6197			}
6198
6199			if (TCP_SKB_CB(skb)->seq == max_sack)
6200				goto reset;
6201		}
6202
6203		/* Disable TFO if RST is out-of-order
6204		 * and no data has been received
6205		 * for current active TFO socket
6206		 */
6207		if (tp->syn_fastopen && !tp->data_segs_in &&
6208		    sk->sk_state == TCP_ESTABLISHED)
6209			tcp_fastopen_active_disable(sk);
6210		tcp_send_challenge_ack(sk, false);
6211		SKB_DR_SET(reason, TCP_RESET);
6212		goto discard;
6213	}
6214
6215	/* step 3: check security and precedence [ignored] */
6216
6217	/* step 4: Check for a SYN
6218	 * RFC 5961 4.2 : Send a challenge ack
6219	 */
6220	if (th->syn) {
6221		if (tcp_ecn_mode_accecn(tp)) {
6222			accecn_reflector = true;
6223			if (tp->rx_opt.accecn &&
6224			    tp->saw_accecn_opt < TCP_ACCECN_OPT_COUNTER_SEEN) {
6225				u8 saw_opt = tcp_accecn_option_init(skb, tp->rx_opt.accecn);
6226
6227				tcp_accecn_saw_opt_fail_recv(tp, saw_opt);
6228				tcp_accecn_opt_demand_min(sk, 1);
6229			}
6230		}
6231		if (sk->sk_state == TCP_SYN_RECV && sk->sk_socket && th->ack &&
6232		    TCP_SKB_CB(skb)->seq + 1 == TCP_SKB_CB(skb)->end_seq &&
6233		    TCP_SKB_CB(skb)->seq + 1 == tp->rcv_nxt &&
6234		    TCP_SKB_CB(skb)->ack_seq == tp->snd_nxt)
6235			goto pass;
6236syn_challenge:
6237		if (syn_inerr)
6238			TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS);
6239		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPSYNCHALLENGE);
6240		tcp_send_challenge_ack(sk, accecn_reflector);
6241		SKB_DR_SET(reason, TCP_INVALID_SYN);
6242		goto discard;
6243	}
6244
6245pass:
6246	bpf_skops_parse_hdr(sk, skb);
6247
6248	return true;
6249
6250discard:
6251	tcp_drop_reason(sk, skb, reason);
6252	return false;
6253
6254reset:
6255	tcp_reset(sk, skb);
6256	__kfree_skb(skb);
6257	return false;
6258}
6259
6260/*
6261 *	TCP receive function for the ESTABLISHED state.
6262 *
6263 *	It is split into a fast path and a slow path. The fast path is
6264 * 	disabled when:
6265 *	- A zero window was announced from us - zero window probing
6266 *        is only handled properly in the slow path.
6267 *	- Out of order segments arrived.
6268 *	- Urgent data is expected.
6269 *	- There is no buffer space left
6270 *	- Unexpected TCP flags/window values/header lengths are received
6271 *	  (detected by checking the TCP header against pred_flags)
6272 *	- Data is sent in both directions. Fast path only supports pure senders
6273 *	  or pure receivers (this means either the sequence number or the ack
6274 *	  value must stay constant)
6275 *	- Unexpected TCP option.
6276 *
6277 *	When these conditions are not satisfied it drops into a standard
6278 *	receive procedure patterned after RFC793 to handle all cases.
6279 *	The first three cases are guaranteed by proper pred_flags setting,
6280 *	the rest is checked inline. Fast processing is turned on in
6281 *	tcp_data_queue when everything is OK.
6282 */
6283void tcp_rcv_established(struct sock *sk, struct sk_buff *skb)
6284{
6285	enum skb_drop_reason reason = SKB_DROP_REASON_NOT_SPECIFIED;
6286	const struct tcphdr *th = (const struct tcphdr *)skb->data;
6287	struct tcp_sock *tp = tcp_sk(sk);
6288	unsigned int len = skb->len;
6289
6290	/* TCP congestion window tracking */
6291	trace_tcp_probe(sk, skb);
6292
6293	tcp_mstamp_refresh(tp);
6294	if (unlikely(!rcu_access_pointer(sk->sk_rx_dst)))
6295		inet_csk(sk)->icsk_af_ops->sk_rx_dst_set(sk, skb);
6296	/*
6297	 *	Header prediction.
6298	 *	The code loosely follows the one in the famous
6299	 *	"30 instruction TCP receive" Van Jacobson mail.
6300	 *
6301	 *	Van's trick is to deposit buffers into socket queue
6302	 *	on a device interrupt, to call tcp_recv function
6303	 *	on the receive process context and checksum and copy
6304	 *	the buffer to user space. smart...
6305	 *
6306	 *	Our current scheme is not silly either but we take the
6307	 *	extra cost of the net_bh soft interrupt processing...
6308	 *	We do checksum and copy also but from device to kernel.
6309	 */
6310
6311	tp->rx_opt.saw_tstamp = 0;
6312	tp->rx_opt.accecn = 0;
6313
6314	/*	pred_flags is 0xS?10 << 16 + snd_wnd
6315	 *	if header_prediction is to be made
6316	 *	'S' will always be tp->tcp_header_len >> 2
6317	 *	'?' will be 0 for the fast path, otherwise pred_flags is 0 to
6318	 *  turn it off	(when there are holes in the receive
6319	 *	 space for instance)
6320	 *	PSH flag is ignored.
6321	 */
6322
6323	if ((tcp_flag_word(th) & TCP_HP_BITS) == tp->pred_flags &&
6324	    TCP_SKB_CB(skb)->seq == tp->rcv_nxt &&
6325	    !after(TCP_SKB_CB(skb)->ack_seq, tp->snd_nxt)) {
6326		int tcp_header_len = tp->tcp_header_len;
6327		s32 delta = 0;
6328		int flag = 0;
6329
6330		/* Timestamp header prediction: tcp_header_len
6331		 * is automatically equal to th->doff*4 due to pred_flags
6332		 * match.
6333		 */
6334
6335		/* Check timestamp */
6336		if (tcp_header_len == sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) {
6337			/* No? Slow path! */
6338			if (!tcp_parse_aligned_timestamp(tp, th))
6339				goto slow_path;
6340
6341			delta = tp->rx_opt.rcv_tsval -
6342				tp->rx_opt.ts_recent;
6343			/* If PAWS failed, check it more carefully in slow path */
6344			if (delta < 0)
6345				goto slow_path;
6346
6347			/* DO NOT update ts_recent here, if checksum fails
6348			 * and timestamp was corrupted part, it will result
6349			 * in a hung connection since we will drop all
6350			 * future packets due to the PAWS test.
6351			 */
6352		}
6353
6354		if (len <= tcp_header_len) {
6355			/* Bulk data transfer: sender */
6356			if (len == tcp_header_len) {
6357				/* Predicted packet is in window by definition.
6358				 * seq == rcv_nxt and rcv_wup <= rcv_nxt.
6359				 * Hence, check seq<=rcv_wup reduces to:
6360				 */
6361				if (tcp_header_len ==
6362				    (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) &&
6363				    tp->rcv_nxt == tp->rcv_wup)
6364					flag |= __tcp_replace_ts_recent(tp,
6365									delta);
6366
6367				tcp_ecn_received_counters(sk, skb, 0);
6368
6369				/* We know that such packets are checksummed
6370				 * on entry.
6371				 */
6372				tcp_ack(sk, skb, flag);
6373				__kfree_skb(skb);
6374				tcp_data_snd_check(sk);
6375				/* When receiving pure ack in fast path, update
6376				 * last ts ecr directly instead of calling
6377				 * tcp_rcv_rtt_measure_ts()
6378				 */
6379				tp->rcv_rtt_last_tsecr = tp->rx_opt.rcv_tsecr;
6380				return;
6381			} else { /* Header too small */
6382				reason = SKB_DROP_REASON_PKT_TOO_SMALL;
6383				TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS);
6384				goto discard;
6385			}
6386		} else {
6387			int eaten = 0;
6388			bool fragstolen = false;
6389
6390			if (tcp_checksum_complete(skb))
6391				goto csum_error;
6392
6393			if (after(TCP_SKB_CB(skb)->end_seq,
6394				  tp->rcv_nxt + tcp_receive_window(tp)))
6395				goto validate;
6396
6397			if ((int)skb->truesize > sk->sk_forward_alloc)
6398				goto step5;
6399
6400			/* Predicted packet is in window by definition.
6401			 * seq == rcv_nxt and rcv_wup <= rcv_nxt.
6402			 * Hence, check seq<=rcv_wup reduces to:
6403			 */
6404			if (tcp_header_len ==
6405			    (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) &&
6406			    tp->rcv_nxt == tp->rcv_wup)
6407				flag |= __tcp_replace_ts_recent(tp,
6408								delta);
6409
6410			tcp_rcv_rtt_measure_ts(sk, skb);
6411
6412			NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPHPHITS);
6413
6414			/* Bulk data transfer: receiver */
6415			tcp_cleanup_skb(skb);
6416			__skb_pull(skb, tcp_header_len);
6417			tcp_ecn_received_counters(sk, skb,
6418						  len - tcp_header_len);
6419			eaten = tcp_queue_rcv(sk, skb, &fragstolen);
6420
6421			tcp_event_data_recv(sk, skb);
6422
6423			if (TCP_SKB_CB(skb)->ack_seq != tp->snd_una) {
6424				/* Well, only one small jumplet in fast path... */
6425				tcp_ack(sk, skb, flag | FLAG_DATA);
6426				tcp_data_snd_check(sk);
6427				if (!inet_csk_ack_scheduled(sk))
6428					goto no_ack;
6429			} else {
6430				tcp_update_wl(tp, TCP_SKB_CB(skb)->seq);
6431			}
6432
6433			__tcp_ack_snd_check(sk, 0);
6434no_ack:
6435			if (eaten)
6436				kfree_skb_partial(skb, fragstolen);
6437			tcp_data_ready(sk);
6438			return;
6439		}
6440	}
6441
6442slow_path:
6443	if (len < (th->doff << 2) || tcp_checksum_complete(skb))
6444		goto csum_error;
6445
6446	if (!th->ack && !th->rst && !th->syn) {
6447		reason = SKB_DROP_REASON_TCP_FLAGS;
6448		goto discard;
6449	}
6450
6451	/*
6452	 *	Standard slow path.
6453	 */
6454validate:
6455	if (!tcp_validate_incoming(sk, skb, th, 1))
6456		return;
6457
6458step5:
6459	tcp_ecn_received_counters_payload(sk, skb);
6460
6461	reason = tcp_ack(sk, skb, FLAG_SLOWPATH | FLAG_UPDATE_TS_RECENT);
6462	if ((int)reason < 0) {
6463		reason = -reason;
6464		goto discard;
6465	}
6466	tcp_rcv_rtt_measure_ts(sk, skb);
6467
6468	/* Process urgent data. */
6469	tcp_urg(sk, skb, th);
6470
6471	/* step 7: process the segment text */
6472	tcp_data_queue(sk, skb);
6473
6474	tcp_data_snd_check(sk);
6475	tcp_ack_snd_check(sk);
6476	return;
6477
6478csum_error:
6479	reason = SKB_DROP_REASON_TCP_CSUM;
6480	trace_tcp_bad_csum(skb);
6481	TCP_INC_STATS(sock_net(sk), TCP_MIB_CSUMERRORS);
6482	TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS);
6483
6484discard:
6485	tcp_drop_reason(sk, skb, reason);
6486}
6487EXPORT_IPV6_MOD(tcp_rcv_established);
6488
6489void tcp_init_transfer(struct sock *sk, int bpf_op, struct sk_buff *skb)
6490{
6491	struct inet_connection_sock *icsk = inet_csk(sk);
6492	struct tcp_sock *tp = tcp_sk(sk);
6493
6494	tcp_mtup_init(sk);
6495	icsk->icsk_af_ops->rebuild_header(sk);
6496	tcp_init_metrics(sk);
6497
6498	/* Initialize the congestion window to start the transfer.
6499	 * Cut cwnd down to 1 per RFC5681 if SYN or SYN-ACK has been
6500	 * retransmitted. In light of RFC6298 more aggressive 1sec
6501	 * initRTO, we only reset cwnd when more than 1 SYN/SYN-ACK
6502	 * retransmission has occurred.
6503	 */
6504	if (tp->total_retrans > 1 && tp->undo_marker)
6505		tcp_snd_cwnd_set(tp, 1);
6506	else
6507		tcp_snd_cwnd_set(tp, tcp_init_cwnd(tp, __sk_dst_get(sk)));
6508	tp->snd_cwnd_stamp = tcp_jiffies32;
6509
6510	bpf_skops_established(sk, bpf_op, skb);
6511	/* Initialize congestion control unless BPF initialized it already: */
6512	if (!icsk->icsk_ca_initialized)
6513		tcp_init_congestion_control(sk);
6514	tcp_init_buffer_space(sk);
6515}
6516
6517void tcp_finish_connect(struct sock *sk, struct sk_buff *skb)
6518{
6519	struct tcp_sock *tp = tcp_sk(sk);
6520	struct inet_connection_sock *icsk = inet_csk(sk);
6521
6522	tcp_ao_finish_connect(sk, skb);
6523	tcp_set_state(sk, TCP_ESTABLISHED);
6524	icsk->icsk_ack.lrcvtime = tcp_jiffies32;
6525
6526	if (skb) {
6527		icsk->icsk_af_ops->sk_rx_dst_set(sk, skb);
6528		security_inet_conn_established(sk, skb);
6529		sk_mark_napi_id(sk, skb);
6530	}
6531
6532	tcp_init_transfer(sk, BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB, skb);
6533
6534	/* Prevent spurious tcp_cwnd_restart() on first data
6535	 * packet.
6536	 */
6537	tp->lsndtime = tcp_jiffies32;
6538
6539	if (sock_flag(sk, SOCK_KEEPOPEN))
6540		tcp_reset_keepalive_timer(sk, keepalive_time_when(tp));
6541
6542	if (!tp->rx_opt.snd_wscale)
6543		__tcp_fast_path_on(tp, tp->snd_wnd);
6544	else
6545		tp->pred_flags = 0;
6546}
6547
6548static bool tcp_rcv_fastopen_synack(struct sock *sk, struct sk_buff *synack,
6549				    struct tcp_fastopen_cookie *cookie)
6550{
6551	struct tcp_sock *tp = tcp_sk(sk);
6552	struct sk_buff *data = tp->syn_data ? tcp_rtx_queue_head(sk) : NULL;
6553	u16 mss = tp->rx_opt.mss_clamp, try_exp = 0;
6554	bool syn_drop = false;
6555
6556	if (mss == READ_ONCE(tp->rx_opt.user_mss)) {
6557		struct tcp_options_received opt;
6558
6559		/* Get original SYNACK MSS value if user MSS sets mss_clamp */
6560		tcp_clear_options(&opt);
6561		opt.user_mss = opt.mss_clamp = 0;
6562		tcp_parse_options(sock_net(sk), synack, &opt, 0, NULL);
6563		mss = opt.mss_clamp;
6564	}
6565
6566	if (!tp->syn_fastopen) {
6567		/* Ignore an unsolicited cookie */
6568		cookie->len = -1;
6569	} else if (tp->total_retrans) {
6570		/* SYN timed out and the SYN-ACK neither has a cookie nor
6571		 * acknowledges data. Presumably the remote received only
6572		 * the retransmitted (regular) SYNs: either the original
6573		 * SYN-data or the corresponding SYN-ACK was dropped.
6574		 */
6575		syn_drop = (cookie->len < 0 && data);
6576	} else if (cookie->len < 0 && !tp->syn_data) {
6577		/* We requested a cookie but didn't get it. If we did not use
6578		 * the (old) exp opt format then try so next time (try_exp=1).
6579		 * Otherwise we go back to use the RFC7413 opt (try_exp=2).
6580		 */
6581		try_exp = tp->syn_fastopen_exp ? 2 : 1;
6582	}
6583
6584	tcp_fastopen_cache_set(sk, mss, cookie, syn_drop, try_exp);
6585
6586	if (data) { /* Retransmit unacked data in SYN */
6587		if (tp->total_retrans)
6588			tp->fastopen_client_fail = TFO_SYN_RETRANSMITTED;
6589		else
6590			tp->fastopen_client_fail = TFO_DATA_NOT_ACKED;
6591		skb_rbtree_walk_from(data)
6592			 tcp_mark_skb_lost(sk, data);
6593		tcp_non_congestion_loss_retransmit(sk);
6594		NET_INC_STATS(sock_net(sk),
6595				LINUX_MIB_TCPFASTOPENACTIVEFAIL);
6596		return true;
6597	}
6598	tp->syn_data_acked = tp->syn_data;
6599	if (tp->syn_data_acked) {
6600		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPFASTOPENACTIVE);
6601		/* SYN-data is counted as two separate packets in tcp_ack() */
6602		if (tp->delivered > 1)
6603			--tp->delivered;
6604	}
6605
6606	tcp_fastopen_add_skb(sk, synack);
6607
6608	return false;
6609}
6610
6611static void smc_check_reset_syn(struct tcp_sock *tp)
6612{
6613#if IS_ENABLED(CONFIG_SMC)
6614	if (static_branch_unlikely(&tcp_have_smc)) {
6615		if (tp->syn_smc && !tp->rx_opt.smc_ok)
6616			tp->syn_smc = 0;
6617	}
6618#endif
6619}
6620
6621static void tcp_try_undo_spurious_syn(struct sock *sk)
6622{
6623	struct tcp_sock *tp = tcp_sk(sk);
6624	u32 syn_stamp;
6625
6626	/* undo_marker is set when SYN or SYNACK times out. The timeout is
6627	 * spurious if the ACK's timestamp option echo value matches the
6628	 * original SYN timestamp.
6629	 */
6630	syn_stamp = tp->retrans_stamp;
6631	if (tp->undo_marker && syn_stamp && tp->rx_opt.saw_tstamp &&
6632	    syn_stamp == tp->rx_opt.rcv_tsecr)
6633		tp->undo_marker = 0;
6634}
6635
6636static int tcp_rcv_synsent_state_process(struct sock *sk, struct sk_buff *skb,
6637					 const struct tcphdr *th)
6638{
6639	struct inet_connection_sock *icsk = inet_csk(sk);
6640	struct tcp_sock *tp = tcp_sk(sk);
6641	struct tcp_fastopen_cookie foc = { .len = -1 };
6642	int saved_clamp = tp->rx_opt.mss_clamp;
6643	bool fastopen_fail;
6644	SKB_DR(reason);
6645
6646	tcp_parse_options(sock_net(sk), skb, &tp->rx_opt, 0, &foc);
6647	if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr)
6648		tp->rx_opt.rcv_tsecr -= tp->tsoffset;
6649
6650	if (th->ack) {
6651		/* rfc793:
6652		 * "If the state is SYN-SENT then
6653		 *    first check the ACK bit
6654		 *      If the ACK bit is set
6655		 *	  If SEG.ACK =< ISS, or SEG.ACK > SND.NXT, send
6656		 *        a reset (unless the RST bit is set, if so drop
6657		 *        the segment and return)"
6658		 */
6659		if (!after(TCP_SKB_CB(skb)->ack_seq, tp->snd_una) ||
6660		    after(TCP_SKB_CB(skb)->ack_seq, tp->snd_nxt)) {
6661			/* Previous FIN/ACK or RST/ACK might be ignored. */
6662			if (icsk->icsk_retransmits == 0)
6663				tcp_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
6664						     TCP_TIMEOUT_MIN, false);
6665			SKB_DR_SET(reason, TCP_INVALID_ACK_SEQUENCE);
6666			goto reset_and_undo;
6667		}
6668
6669		if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr &&
6670		    !between(tp->rx_opt.rcv_tsecr, tp->retrans_stamp,
6671			     tcp_time_stamp_ts(tp))) {
6672			NET_INC_STATS(sock_net(sk),
6673					LINUX_MIB_PAWSACTIVEREJECTED);
6674			SKB_DR_SET(reason, TCP_RFC7323_PAWS);
6675			goto reset_and_undo;
6676		}
6677
6678		/* Now ACK is acceptable.
6679		 *
6680		 * "If the RST bit is set
6681		 *    If the ACK was acceptable then signal the user "error:
6682		 *    connection reset", drop the segment, enter CLOSED state,
6683		 *    delete TCB, and return."
6684		 */
6685
6686		if (th->rst) {
6687			tcp_reset(sk, skb);
6688consume:
6689			__kfree_skb(skb);
6690			return 0;
6691		}
6692
6693		/* rfc793:
6694		 *   "fifth, if neither of the SYN or RST bits is set then
6695		 *    drop the segment and return."
6696		 *
6697		 *    See note below!
6698		 *                                        --ANK(990513)
6699		 */
6700		if (!th->syn) {
6701			SKB_DR_SET(reason, TCP_FLAGS);
6702			goto discard_and_undo;
6703		}
6704		/* rfc793:
6705		 *   "If the SYN bit is on ...
6706		 *    are acceptable then ...
6707		 *    (our SYN has been ACKed), change the connection
6708		 *    state to ESTABLISHED..."
6709		 */
6710
6711		if (tcp_ecn_mode_any(tp))
6712			tcp_ecn_rcv_synack(sk, skb, th,
6713					   TCP_SKB_CB(skb)->ip_dsfield);
6714
6715		tcp_init_wl(tp, TCP_SKB_CB(skb)->seq);
6716		tcp_try_undo_spurious_syn(sk);
6717		tcp_ack(sk, skb, FLAG_SLOWPATH);
6718
6719		/* Ok.. it's good. Set up sequence numbers and
6720		 * move to established.
6721		 */
6722		WRITE_ONCE(tp->rcv_nxt, TCP_SKB_CB(skb)->seq + 1);
6723		tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
6724
6725		/* RFC1323: The window in SYN & SYN/ACK segments is
6726		 * never scaled.
6727		 */
6728		tp->snd_wnd = ntohs(th->window);
6729
6730		if (!tp->rx_opt.wscale_ok) {
6731			tp->rx_opt.snd_wscale = tp->rx_opt.rcv_wscale = 0;
6732			WRITE_ONCE(tp->window_clamp,
6733				   min(tp->window_clamp, 65535U));
6734		}
6735
6736		if (tp->rx_opt.saw_tstamp) {
6737			tp->rx_opt.tstamp_ok	   = 1;
6738			tp->tcp_header_len =
6739				sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
6740			tp->advmss	    -= TCPOLEN_TSTAMP_ALIGNED;
6741			tcp_store_ts_recent(tp);
6742		} else {
6743			tp->tcp_header_len = sizeof(struct tcphdr);
6744		}
6745
6746		tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
6747		tcp_initialize_rcv_mss(sk);
6748
6749		/* Remember, tcp_poll() does not lock socket!
6750		 * Change state from SYN-SENT only after copied_seq
6751		 * is initialized. */
6752		WRITE_ONCE(tp->copied_seq, tp->rcv_nxt);
6753
6754		smc_check_reset_syn(tp);
6755
6756		smp_mb();
6757
6758		tcp_finish_connect(sk, skb);
6759
6760		fastopen_fail = (tp->syn_fastopen || tp->syn_data) &&
6761				tcp_rcv_fastopen_synack(sk, skb, &foc);
6762
6763		if (!sock_flag(sk, SOCK_DEAD)) {
6764			sk->sk_state_change(sk);
6765			sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT);
6766		}
6767		if (fastopen_fail)
6768			return -1;
6769		if (sk->sk_write_pending ||
6770		    READ_ONCE(icsk->icsk_accept_queue.rskq_defer_accept) ||
6771		    inet_csk_in_pingpong_mode(sk)) {
6772			/* Save one ACK. Data will be ready after
6773			 * several ticks, if write_pending is set.
6774			 *
6775			 * It may be deleted, but with this feature tcpdumps
6776			 * look so _wonderfully_ clever, that I was not able
6777			 * to stand against the temptation 8)     --ANK
6778			 */
6779			inet_csk_schedule_ack(sk);
6780			tcp_enter_quickack_mode(sk, TCP_MAX_QUICKACKS);
6781			tcp_reset_xmit_timer(sk, ICSK_TIME_DACK,
6782					     TCP_DELACK_MAX, false);
6783			goto consume;
6784		}
6785		tcp_send_ack_reflect_ect(sk, tcp_ecn_mode_accecn(tp));
6786		return -1;
6787	}
6788
6789	/* No ACK in the segment */
6790
6791	if (th->rst) {
6792		/* rfc793:
6793		 * "If the RST bit is set
6794		 *
6795		 *      Otherwise (no ACK) drop the segment and return."
6796		 */
6797		SKB_DR_SET(reason, TCP_RESET);
6798		goto discard_and_undo;
6799	}
6800
6801	/* PAWS check. */
6802	if (tp->rx_opt.ts_recent_stamp && tp->rx_opt.saw_tstamp &&
6803	    tcp_paws_reject(&tp->rx_opt, 0)) {
6804		SKB_DR_SET(reason, TCP_RFC7323_PAWS);
6805		goto discard_and_undo;
6806	}
6807	if (th->syn) {
6808		/* We see SYN without ACK. It is attempt of
6809		 * simultaneous connect with crossed SYNs.
6810		 * Particularly, it can be connect to self.
6811		 */
6812#ifdef CONFIG_TCP_AO
6813		struct tcp_ao_info *ao;
6814
6815		ao = rcu_dereference_protected(tp->ao_info,
6816					       lockdep_sock_is_held(sk));
6817		if (ao) {
6818			WRITE_ONCE(ao->risn, th->seq);
6819			ao->rcv_sne = 0;
6820		}
6821#endif
6822		tcp_set_state(sk, TCP_SYN_RECV);
6823
6824		if (tp->rx_opt.saw_tstamp) {
6825			tp->rx_opt.tstamp_ok = 1;
6826			tcp_store_ts_recent(tp);
6827			tp->tcp_header_len =
6828				sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
6829		} else {
6830			tp->tcp_header_len = sizeof(struct tcphdr);
6831		}
6832
6833		WRITE_ONCE(tp->rcv_nxt, TCP_SKB_CB(skb)->seq + 1);
6834		WRITE_ONCE(tp->copied_seq, tp->rcv_nxt);
6835		tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
6836
6837		/* RFC1323: The window in SYN & SYN/ACK segments is
6838		 * never scaled.
6839		 */
6840		tp->snd_wnd    = ntohs(th->window);
6841		tp->snd_wl1    = TCP_SKB_CB(skb)->seq;
6842		tp->max_window = tp->snd_wnd;
6843
6844		tcp_ecn_rcv_syn(sk, th, skb);
6845
6846		tcp_mtup_init(sk);
6847		tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
6848		tcp_initialize_rcv_mss(sk);
6849
6850		tcp_send_synack(sk);
6851#if 0
6852		/* Note, we could accept data and URG from this segment.
6853		 * There are no obstacles to make this (except that we must
6854		 * either change tcp_recvmsg() to prevent it from returning data
6855		 * before 3WHS completes per RFC793, or employ TCP Fast Open).
6856		 *
6857		 * However, if we ignore data in ACKless segments sometimes,
6858		 * we have no reasons to accept it sometimes.
6859		 * Also, seems the code doing it in step6 of tcp_rcv_state_process
6860		 * is not flawless. So, discard packet for sanity.
6861		 * Uncomment this return to process the data.
6862		 */
6863		return -1;
6864#else
6865		goto consume;
6866#endif
6867	}
6868	/* "fifth, if neither of the SYN or RST bits is set then
6869	 * drop the segment and return."
6870	 */
6871
6872discard_and_undo:
6873	tcp_clear_options(&tp->rx_opt);
6874	tp->rx_opt.mss_clamp = saved_clamp;
6875	tcp_drop_reason(sk, skb, reason);
6876	return 0;
6877
6878reset_and_undo:
6879	tcp_clear_options(&tp->rx_opt);
6880	tp->rx_opt.mss_clamp = saved_clamp;
6881	/* we can reuse/return @reason to its caller to handle the exception */
6882	return reason;
6883}
6884
6885static void tcp_rcv_synrecv_state_fastopen(struct sock *sk)
6886{
6887	struct tcp_sock *tp = tcp_sk(sk);
6888	struct request_sock *req;
6889
6890	/* If we are still handling the SYNACK RTO, see if timestamp ECR allows
6891	 * undo. If peer SACKs triggered fast recovery, we can't undo here.
6892	 */
6893	if (inet_csk(sk)->icsk_ca_state == TCP_CA_Loss && !tp->packets_out)
6894		tcp_try_undo_recovery(sk);
6895
6896	tcp_update_rto_time(tp);
6897	WRITE_ONCE(inet_csk(sk)->icsk_retransmits, 0);
6898	/* In tcp_fastopen_synack_timer() on the first SYNACK RTO we set
6899	 * retrans_stamp but don't enter CA_Loss, so in case that happened we
6900	 * need to zero retrans_stamp here to prevent spurious
6901	 * retransmits_timed_out(). However, if the ACK of our SYNACK caused us
6902	 * to enter CA_Recovery then we need to leave retrans_stamp as it was
6903	 * set entering CA_Recovery, for correct retransmits_timed_out() and
6904	 * undo behavior.
6905	 */
6906	tcp_retrans_stamp_cleanup(sk);
6907
6908	/* Once we leave TCP_SYN_RECV or TCP_FIN_WAIT_1,
6909	 * we no longer need req so release it.
6910	 */
6911	req = rcu_dereference_protected(tp->fastopen_rsk,
6912					lockdep_sock_is_held(sk));
6913	reqsk_fastopen_remove(sk, req, false);
6914
6915	/* Re-arm the timer because data may have been sent out.
6916	 * This is similar to the regular data transmission case
6917	 * when new data has just been ack'ed.
6918	 *
6919	 * (TFO) - we could try to be more aggressive and
6920	 * retransmitting any data sooner based on when they
6921	 * are sent out.
6922	 */
6923	tcp_rearm_rto(sk);
6924}
6925
6926/*
6927 *	This function implements the receiving procedure of RFC 793 for
6928 *	all states except ESTABLISHED and TIME_WAIT.
6929 *	It's called from both tcp_v4_rcv and tcp_v6_rcv and should be
6930 *	address independent.
6931 */
6932
6933enum skb_drop_reason
6934tcp_rcv_state_process(struct sock *sk, struct sk_buff *skb)
6935{
6936	struct tcp_sock *tp = tcp_sk(sk);
6937	struct inet_connection_sock *icsk = inet_csk(sk);
6938	const struct tcphdr *th = tcp_hdr(skb);
6939	struct request_sock *req;
6940	int queued = 0;
6941	SKB_DR(reason);
6942
6943	switch (sk->sk_state) {
6944	case TCP_CLOSE:
6945		SKB_DR_SET(reason, TCP_CLOSE);
6946		goto discard;
6947
6948	case TCP_LISTEN:
6949		if (th->ack)
6950			return SKB_DROP_REASON_TCP_FLAGS;
6951
6952		if (th->rst) {
6953			SKB_DR_SET(reason, TCP_RESET);
6954			goto discard;
6955		}
6956		if (th->syn) {
6957			if (th->fin) {
6958				SKB_DR_SET(reason, TCP_FLAGS);
6959				goto discard;
6960			}
6961			/* It is possible that we process SYN packets from backlog,
6962			 * so we need to make sure to disable BH and RCU right there.
6963			 */
6964			rcu_read_lock();
6965			local_bh_disable();
6966			icsk->icsk_af_ops->conn_request(sk, skb);
6967			local_bh_enable();
6968			rcu_read_unlock();
6969
6970			consume_skb(skb);
6971			return 0;
6972		}
6973		SKB_DR_SET(reason, TCP_FLAGS);
6974		goto discard;
6975
6976	case TCP_SYN_SENT:
6977		tp->rx_opt.saw_tstamp = 0;
6978		tcp_mstamp_refresh(tp);
6979		queued = tcp_rcv_synsent_state_process(sk, skb, th);
6980		if (queued >= 0)
6981			return queued;
6982
6983		/* Do step6 onward by hand. */
6984		tcp_urg(sk, skb, th);
6985		__kfree_skb(skb);
6986		tcp_data_snd_check(sk);
6987		return 0;
6988	}
6989
6990	tcp_mstamp_refresh(tp);
6991	tp->rx_opt.saw_tstamp = 0;
6992	req = rcu_dereference_protected(tp->fastopen_rsk,
6993					lockdep_sock_is_held(sk));
6994	if (req) {
6995		bool req_stolen;
6996
6997		WARN_ON_ONCE(sk->sk_state != TCP_SYN_RECV &&
6998		    sk->sk_state != TCP_FIN_WAIT1);
6999
7000		SKB_DR_SET(reason, TCP_FASTOPEN);
7001		if (!tcp_check_req(sk, skb, req, true, &req_stolen, &reason))
7002			goto discard;
7003	}
7004
7005	if (!th->ack && !th->rst && !th->syn) {
7006		SKB_DR_SET(reason, TCP_FLAGS);
7007		goto discard;
7008	}
7009	if (!tcp_validate_incoming(sk, skb, th, 0))
7010		return 0;
7011
7012	/* step 5: check the ACK field */
7013	reason = tcp_ack(sk, skb, FLAG_SLOWPATH |
7014				  FLAG_UPDATE_TS_RECENT |
7015				  FLAG_NO_CHALLENGE_ACK);
7016
7017	if ((int)reason <= 0) {
7018		if (sk->sk_state == TCP_SYN_RECV) {
7019			/* send one RST */
7020			if (!reason)
7021				return SKB_DROP_REASON_TCP_OLD_ACK;
7022			return -reason;
7023		}
7024		/* accept old ack during closing */
7025		if ((int)reason < 0) {
7026			tcp_send_challenge_ack(sk, false);
7027			reason = -reason;
7028			goto discard;
7029		}
7030	}
7031	SKB_DR_SET(reason, NOT_SPECIFIED);
7032	switch (sk->sk_state) {
7033	case TCP_SYN_RECV:
7034		tp->delivered++; /* SYN-ACK delivery isn't tracked in tcp_ack */
7035		if (!tp->srtt_us)
7036			tcp_synack_rtt_meas(sk, req);
7037
7038		if (tp->rx_opt.tstamp_ok)
7039			tp->advmss -= TCPOLEN_TSTAMP_ALIGNED;
7040
7041		if (req) {
7042			tcp_rcv_synrecv_state_fastopen(sk);
7043		} else {
7044			tcp_try_undo_spurious_syn(sk);
7045			tp->retrans_stamp = 0;
7046			tcp_init_transfer(sk, BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB,
7047					  skb);
7048			WRITE_ONCE(tp->copied_seq, tp->rcv_nxt);
7049		}
7050		tcp_ao_established(sk);
7051		smp_mb();
7052		tcp_set_state(sk, TCP_ESTABLISHED);
7053		sk->sk_state_change(sk);
7054
7055		/* Note, that this wakeup is only for marginal crossed SYN case.
7056		 * Passively open sockets are not waked up, because
7057		 * sk->sk_sleep == NULL and sk->sk_socket == NULL.
7058		 */
7059		if (sk->sk_socket)
7060			sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT);
7061
7062		tp->snd_una = TCP_SKB_CB(skb)->ack_seq;
7063		tp->snd_wnd = ntohs(th->window) << tp->rx_opt.snd_wscale;
7064		tcp_init_wl(tp, TCP_SKB_CB(skb)->seq);
7065
7066		if (!inet_csk(sk)->icsk_ca_ops->cong_control)
7067			tcp_update_pacing_rate(sk);
7068
7069		/* Prevent spurious tcp_cwnd_restart() on first data packet */
7070		tp->lsndtime = tcp_jiffies32;
7071
7072		tcp_initialize_rcv_mss(sk);
7073		if (tcp_ecn_mode_accecn(tp))
7074			tcp_accecn_third_ack(sk, skb, tp->syn_ect_snt);
7075		tcp_fast_path_on(tp);
7076		if (sk->sk_shutdown & SEND_SHUTDOWN)
7077			tcp_shutdown(sk, SEND_SHUTDOWN);
7078
7079		break;
7080
7081	case TCP_FIN_WAIT1: {
7082		int tmo;
7083
7084		if (req)
7085			tcp_rcv_synrecv_state_fastopen(sk);
7086
7087		if (tp->snd_una != tp->write_seq)
7088			break;
7089
7090		tcp_set_state(sk, TCP_FIN_WAIT2);
7091		WRITE_ONCE(sk->sk_shutdown, sk->sk_shutdown | SEND_SHUTDOWN);
7092
7093		sk_dst_confirm(sk);
7094
7095		if (!sock_flag(sk, SOCK_DEAD)) {
7096			/* Wake up lingering close() */
7097			sk->sk_state_change(sk);
7098			break;
7099		}
7100
7101		if (READ_ONCE(tp->linger2) < 0) {
7102			tcp_done(sk);
7103			NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
7104			return SKB_DROP_REASON_TCP_ABORT_ON_DATA;
7105		}
7106		if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
7107		    after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt)) {
7108			/* Receive out of order FIN after close() */
7109			if (tp->syn_fastopen && th->fin)
7110				tcp_fastopen_active_disable(sk);
7111			tcp_done(sk);
7112			NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
7113			return SKB_DROP_REASON_TCP_ABORT_ON_DATA;
7114		}
7115
7116		tmo = tcp_fin_time(sk);
7117		if (tmo > TCP_TIMEWAIT_LEN) {
7118			tcp_reset_keepalive_timer(sk, tmo - TCP_TIMEWAIT_LEN);
7119		} else if (th->fin || sock_owned_by_user(sk)) {
7120			/* Bad case. We could lose such FIN otherwise.
7121			 * It is not a big problem, but it looks confusing
7122			 * and not so rare event. We still can lose it now,
7123			 * if it spins in bh_lock_sock(), but it is really
7124			 * marginal case.
7125			 */
7126			tcp_reset_keepalive_timer(sk, tmo);
7127		} else {
7128			tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
7129			goto consume;
7130		}
7131		break;
7132	}
7133
7134	case TCP_CLOSING:
7135		if (tp->snd_una == tp->write_seq) {
7136			tcp_time_wait(sk, TCP_TIME_WAIT, 0);
7137			goto consume;
7138		}
7139		break;
7140
7141	case TCP_LAST_ACK:
7142		if (tp->snd_una == tp->write_seq) {
7143			tcp_update_metrics(sk);
7144			tcp_done(sk);
7145			goto consume;
7146		}
7147		break;
7148	}
7149
7150	/* step 6: check the URG bit */
7151	tcp_urg(sk, skb, th);
7152
7153	/* step 7: process the segment text */
7154	switch (sk->sk_state) {
7155	case TCP_CLOSE_WAIT:
7156	case TCP_CLOSING:
7157	case TCP_LAST_ACK:
7158		if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
7159			/* If a subflow has been reset, the packet should not
7160			 * continue to be processed, drop the packet.
7161			 */
7162			if (sk_is_mptcp(sk) && !mptcp_incoming_options(sk, skb))
7163				goto discard;
7164			break;
7165		}
7166		fallthrough;
7167	case TCP_FIN_WAIT1:
7168	case TCP_FIN_WAIT2:
7169		/* RFC 793 says to queue data in these states,
7170		 * RFC 1122 says we MUST send a reset.
7171		 * BSD 4.4 also does reset.
7172		 */
7173		if (sk->sk_shutdown & RCV_SHUTDOWN) {
7174			if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
7175			    after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt)) {
7176				NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
7177				tcp_reset(sk, skb);
7178				return SKB_DROP_REASON_TCP_ABORT_ON_DATA;
7179			}
7180		}
7181		fallthrough;
7182	case TCP_ESTABLISHED:
7183		tcp_data_queue(sk, skb);
7184		queued = 1;
7185		break;
7186	}
7187
7188	/* tcp_data could move socket to TIME-WAIT */
7189	if (sk->sk_state != TCP_CLOSE) {
7190		tcp_data_snd_check(sk);
7191		tcp_ack_snd_check(sk);
7192	}
7193
7194	if (!queued) {
7195discard:
7196		tcp_drop_reason(sk, skb, reason);
7197	}
7198	return 0;
7199
7200consume:
7201	__kfree_skb(skb);
7202	return 0;
7203}
7204EXPORT_IPV6_MOD(tcp_rcv_state_process);
7205
7206static inline void pr_drop_req(struct request_sock *req, __u16 port, int family)
7207{
7208	struct inet_request_sock *ireq = inet_rsk(req);
7209
7210	if (family == AF_INET)
7211		net_dbg_ratelimited("drop open request from %pI4/%u\n",
7212				    &ireq->ir_rmt_addr, port);
7213#if IS_ENABLED(CONFIG_IPV6)
7214	else if (family == AF_INET6)
7215		net_dbg_ratelimited("drop open request from %pI6/%u\n",
7216				    &ireq->ir_v6_rmt_addr, port);
7217#endif
7218}
7219
7220/* RFC3168 : 6.1.1 SYN packets must not have ECT/ECN bits set
7221 *
7222 * If we receive a SYN packet with these bits set, it means a
7223 * network is playing bad games with TOS bits. In order to
7224 * avoid possible false congestion notifications, we disable
7225 * TCP ECN negotiation.
7226 *
7227 * Exception: tcp_ca wants ECN. This is required for DCTCP
7228 * congestion control: Linux DCTCP asserts ECT on all packets,
7229 * including SYN, which is most optimal solution; however,
7230 * others, such as FreeBSD do not.
7231 *
7232 * Exception: At least one of the reserved bits of the TCP header (th->res1) is
7233 * set, indicating the use of a future TCP extension (such as AccECN). See
7234 * RFC8311 §4.3 which updates RFC3168 to allow the development of such
7235 * extensions.
7236 */
7237static void tcp_ecn_create_request(struct request_sock *req,
7238				   const struct sk_buff *skb,
7239				   const struct sock *listen_sk,
7240				   const struct dst_entry *dst)
7241{
7242	const struct tcphdr *th = tcp_hdr(skb);
7243	const struct net *net = sock_net(listen_sk);
7244	bool th_ecn = th->ece && th->cwr;
7245	bool ect, ecn_ok;
7246	u32 ecn_ok_dst;
7247
7248	if (tcp_accecn_syn_requested(th) &&
7249	    (READ_ONCE(net->ipv4.sysctl_tcp_ecn) >= 3 ||
7250	     tcp_ca_needs_accecn(listen_sk))) {
7251		inet_rsk(req)->ecn_ok = 1;
7252		tcp_rsk(req)->accecn_ok = 1;
7253		tcp_rsk(req)->syn_ect_rcv = TCP_SKB_CB(skb)->ip_dsfield &
7254					    INET_ECN_MASK;
7255		return;
7256	}
7257
7258	if (!th_ecn)
7259		return;
7260
7261	ect = !INET_ECN_is_not_ect(TCP_SKB_CB(skb)->ip_dsfield);
7262	ecn_ok_dst = dst_feature(dst, DST_FEATURE_ECN_MASK);
7263	ecn_ok = READ_ONCE(net->ipv4.sysctl_tcp_ecn) || ecn_ok_dst;
7264
7265	if (((!ect || th->res1 || th->ae) && ecn_ok) ||
7266	    tcp_ca_needs_ecn(listen_sk) ||
7267	    (ecn_ok_dst & DST_FEATURE_ECN_CA) ||
7268	    tcp_bpf_ca_needs_ecn((struct sock *)req))
7269		inet_rsk(req)->ecn_ok = 1;
7270}
7271
7272static void tcp_openreq_init(struct request_sock *req,
7273			     const struct tcp_options_received *rx_opt,
7274			     struct sk_buff *skb, const struct sock *sk)
7275{
7276	struct inet_request_sock *ireq = inet_rsk(req);
7277
7278	req->rsk_rcv_wnd = 0;		/* So that tcp_send_synack() knows! */
7279	tcp_rsk(req)->rcv_isn = TCP_SKB_CB(skb)->seq;
7280	tcp_rsk(req)->rcv_nxt = TCP_SKB_CB(skb)->seq + 1;
7281	tcp_rsk(req)->snt_synack = 0;
7282	tcp_rsk(req)->snt_tsval_first = 0;
7283	tcp_rsk(req)->last_oow_ack_time = 0;
7284	tcp_rsk(req)->accecn_ok = 0;
7285	tcp_rsk(req)->saw_accecn_opt = TCP_ACCECN_OPT_NOT_SEEN;
7286	tcp_rsk(req)->accecn_fail_mode = 0;
7287	tcp_rsk(req)->syn_ect_rcv = 0;
7288	tcp_rsk(req)->syn_ect_snt = 0;
7289	req->mss = rx_opt->mss_clamp;
7290	req->ts_recent = rx_opt->saw_tstamp ? rx_opt->rcv_tsval : 0;
7291	ireq->tstamp_ok = rx_opt->tstamp_ok;
7292	ireq->sack_ok = rx_opt->sack_ok;
7293	ireq->snd_wscale = rx_opt->snd_wscale;
7294	ireq->wscale_ok = rx_opt->wscale_ok;
7295	ireq->acked = 0;
7296	ireq->ecn_ok = 0;
7297	ireq->ir_rmt_port = tcp_hdr(skb)->source;
7298	ireq->ir_num = ntohs(tcp_hdr(skb)->dest);
7299	ireq->ir_mark = inet_request_mark(sk, skb);
7300#if IS_ENABLED(CONFIG_SMC)
7301	ireq->smc_ok = rx_opt->smc_ok && !(tcp_sk(sk)->smc_hs_congested &&
7302			tcp_sk(sk)->smc_hs_congested(sk));
7303#endif
7304}
7305
7306/*
7307 * Return true if a syncookie should be sent
7308 */
7309static bool tcp_syn_flood_action(struct sock *sk, const char *proto)
7310{
7311	struct request_sock_queue *queue = &inet_csk(sk)->icsk_accept_queue;
7312	const char *msg = "Dropping request";
7313	struct net *net = sock_net(sk);
7314	bool want_cookie = false;
7315	u8 syncookies;
7316
7317	syncookies = READ_ONCE(net->ipv4.sysctl_tcp_syncookies);
7318
7319#ifdef CONFIG_SYN_COOKIES
7320	if (syncookies) {
7321		msg = "Sending cookies";
7322		want_cookie = true;
7323		__NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPREQQFULLDOCOOKIES);
7324	} else
7325#endif
7326		__NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPREQQFULLDROP);
7327
7328	if (syncookies != 2 && !READ_ONCE(queue->synflood_warned)) {
7329		WRITE_ONCE(queue->synflood_warned, 1);
7330		if (IS_ENABLED(CONFIG_IPV6) && sk->sk_family == AF_INET6) {
7331			net_info_ratelimited("%s: Possible SYN flooding on port [%pI6c]:%u. %s.\n",
7332					proto, inet6_rcv_saddr(sk),
7333					sk->sk_num, msg);
7334		} else {
7335			net_info_ratelimited("%s: Possible SYN flooding on port %pI4:%u. %s.\n",
7336					proto, &sk->sk_rcv_saddr,
7337					sk->sk_num, msg);
7338		}
7339	}
7340
7341	return want_cookie;
7342}
7343
7344static void tcp_reqsk_record_syn(const struct sock *sk,
7345				 struct request_sock *req,
7346				 const struct sk_buff *skb)
7347{
7348	if (tcp_sk(sk)->save_syn) {
7349		u32 len = skb_network_header_len(skb) + tcp_hdrlen(skb);
7350		struct saved_syn *saved_syn;
7351		u32 mac_hdrlen;
7352		void *base;
7353
7354		if (tcp_sk(sk)->save_syn == 2) {  /* Save full header. */
7355			base = skb_mac_header(skb);
7356			mac_hdrlen = skb_mac_header_len(skb);
7357			len += mac_hdrlen;
7358		} else {
7359			base = skb_network_header(skb);
7360			mac_hdrlen = 0;
7361		}
7362
7363		saved_syn = kmalloc(struct_size(saved_syn, data, len),
7364				    GFP_ATOMIC);
7365		if (saved_syn) {
7366			saved_syn->mac_hdrlen = mac_hdrlen;
7367			saved_syn->network_hdrlen = skb_network_header_len(skb);
7368			saved_syn->tcp_hdrlen = tcp_hdrlen(skb);
7369			memcpy(saved_syn->data, base, len);
7370			req->saved_syn = saved_syn;
7371		}
7372	}
7373}
7374
7375/* If a SYN cookie is required and supported, returns a clamped MSS value to be
7376 * used for SYN cookie generation.
7377 */
7378u16 tcp_get_syncookie_mss(struct request_sock_ops *rsk_ops,
7379			  const struct tcp_request_sock_ops *af_ops,
7380			  struct sock *sk, struct tcphdr *th)
7381{
7382	struct tcp_sock *tp = tcp_sk(sk);
7383	u16 mss;
7384
7385	if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_syncookies) != 2 &&
7386	    !inet_csk_reqsk_queue_is_full(sk))
7387		return 0;
7388
7389	if (!tcp_syn_flood_action(sk, rsk_ops->slab_name))
7390		return 0;
7391
7392	if (sk_acceptq_is_full(sk)) {
7393		NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
7394		return 0;
7395	}
7396
7397	mss = tcp_parse_mss_option(th, READ_ONCE(tp->rx_opt.user_mss));
7398	if (!mss)
7399		mss = af_ops->mss_clamp;
7400
7401	return mss;
7402}
7403EXPORT_IPV6_MOD_GPL(tcp_get_syncookie_mss);
7404
7405int tcp_conn_request(struct request_sock_ops *rsk_ops,
7406		     const struct tcp_request_sock_ops *af_ops,
7407		     struct sock *sk, struct sk_buff *skb)
7408{
7409	struct tcp_fastopen_cookie foc = { .len = -1 };
7410	struct tcp_options_received tmp_opt;
7411	const struct tcp_sock *tp = tcp_sk(sk);
7412	struct net *net = sock_net(sk);
7413	struct sock *fastopen_sk = NULL;
7414	union tcp_seq_and_ts_off st;
7415	struct request_sock *req;
7416	bool want_cookie = false;
7417	struct dst_entry *dst;
7418	struct flowi fl;
7419	u8 syncookies;
7420	u32 isn;
7421
7422#ifdef CONFIG_TCP_AO
7423	const struct tcp_ao_hdr *aoh;
7424#endif
7425
7426	isn = __this_cpu_read(tcp_tw_isn);
7427	if (isn) {
7428		/* TW buckets are converted to open requests without
7429		 * limitations, they conserve resources and peer is
7430		 * evidently real one.
7431		 */
7432		__this_cpu_write(tcp_tw_isn, 0);
7433	} else {
7434		syncookies = READ_ONCE(net->ipv4.sysctl_tcp_syncookies);
7435
7436		if (syncookies == 2 || inet_csk_reqsk_queue_is_full(sk)) {
7437			want_cookie = tcp_syn_flood_action(sk,
7438							   rsk_ops->slab_name);
7439			if (!want_cookie)
7440				goto drop;
7441		}
7442	}
7443
7444	if (sk_acceptq_is_full(sk)) {
7445		NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
7446		goto drop;
7447	}
7448
7449	req = inet_reqsk_alloc(rsk_ops, sk, !want_cookie);
7450	if (!req)
7451		goto drop;
7452
7453	req->syncookie = want_cookie;
7454	tcp_rsk(req)->af_specific = af_ops;
7455	tcp_rsk(req)->ts_off = 0;
7456	tcp_rsk(req)->req_usec_ts = false;
7457#if IS_ENABLED(CONFIG_MPTCP)
7458	tcp_rsk(req)->is_mptcp = 0;
7459#endif
7460
7461	tcp_clear_options(&tmp_opt);
7462	tmp_opt.mss_clamp = af_ops->mss_clamp;
7463	tmp_opt.user_mss  = READ_ONCE(tp->rx_opt.user_mss);
7464	tcp_parse_options(sock_net(sk), skb, &tmp_opt, 0,
7465			  want_cookie ? NULL : &foc);
7466
7467	if (want_cookie && !tmp_opt.saw_tstamp)
7468		tcp_clear_options(&tmp_opt);
7469
7470	if (IS_ENABLED(CONFIG_SMC) && want_cookie)
7471		tmp_opt.smc_ok = 0;
7472
7473	tmp_opt.tstamp_ok = tmp_opt.saw_tstamp;
7474	tcp_openreq_init(req, &tmp_opt, skb, sk);
7475	inet_rsk(req)->no_srccheck = inet_test_bit(TRANSPARENT, sk);
7476
7477	/* Note: tcp_v6_init_req() might override ir_iif for link locals */
7478	inet_rsk(req)->ir_iif = inet_request_bound_dev_if(sk, skb);
7479
7480	dst = af_ops->route_req(sk, skb, &fl, req, isn);
7481	if (!dst)
7482		goto drop_and_free;
7483
7484	if (tmp_opt.tstamp_ok || (!want_cookie && !isn))
7485		st = af_ops->init_seq_and_ts_off(net, skb);
7486
7487	if (tmp_opt.tstamp_ok) {
7488		tcp_rsk(req)->req_usec_ts = dst_tcp_usec_ts(dst);
7489		tcp_rsk(req)->ts_off = st.ts_off;
7490	}
7491	if (!want_cookie && !isn) {
7492		int max_syn_backlog = READ_ONCE(net->ipv4.sysctl_max_syn_backlog);
7493
7494		/* Kill the following clause, if you dislike this way. */
7495		if (!syncookies &&
7496		    (max_syn_backlog - inet_csk_reqsk_queue_len(sk) <
7497		     (max_syn_backlog >> 2)) &&
7498		    !tcp_peer_is_proven(req, dst)) {
7499			/* Without syncookies last quarter of
7500			 * backlog is filled with destinations,
7501			 * proven to be alive.
7502			 * It means that we continue to communicate
7503			 * to destinations, already remembered
7504			 * to the moment of synflood.
7505			 */
7506			pr_drop_req(req, ntohs(tcp_hdr(skb)->source),
7507				    rsk_ops->family);
7508			goto drop_and_release;
7509		}
7510
7511		isn = st.seq;
7512	}
7513
7514	tcp_ecn_create_request(req, skb, sk, dst);
7515
7516	if (want_cookie) {
7517		isn = cookie_init_sequence(af_ops, sk, skb, &req->mss);
7518		if (!tmp_opt.tstamp_ok)
7519			inet_rsk(req)->ecn_ok = 0;
7520	}
7521
7522#ifdef CONFIG_TCP_AO
7523	if (tcp_parse_auth_options(tcp_hdr(skb), NULL, &aoh))
7524		goto drop_and_release; /* Invalid TCP options */
7525	if (aoh) {
7526		tcp_rsk(req)->used_tcp_ao = true;
7527		tcp_rsk(req)->ao_rcv_next = aoh->keyid;
7528		tcp_rsk(req)->ao_keyid = aoh->rnext_keyid;
7529
7530	} else {
7531		tcp_rsk(req)->used_tcp_ao = false;
7532	}
7533#endif
7534	tcp_rsk(req)->snt_isn = isn;
7535	tcp_rsk(req)->txhash = net_tx_rndhash();
7536	tcp_rsk(req)->syn_tos = TCP_SKB_CB(skb)->ip_dsfield;
7537	tcp_openreq_init_rwin(req, sk, dst);
7538	sk_rx_queue_set(req_to_sk(req), skb);
7539	if (!want_cookie) {
7540		tcp_reqsk_record_syn(sk, req, skb);
7541		fastopen_sk = tcp_try_fastopen(sk, skb, req, &foc, dst);
7542	}
7543	if (fastopen_sk) {
7544		af_ops->send_synack(fastopen_sk, dst, &fl, req,
7545				    &foc, TCP_SYNACK_FASTOPEN, skb);
7546		/* Add the child socket directly into the accept queue */
7547		if (!inet_csk_reqsk_queue_add(sk, req, fastopen_sk)) {
7548			bh_unlock_sock(fastopen_sk);
7549			sock_put(fastopen_sk);
7550			goto drop_and_free;
7551		}
7552		READ_ONCE(sk->sk_data_ready)(sk);
7553		bh_unlock_sock(fastopen_sk);
7554		sock_put(fastopen_sk);
7555	} else {
7556		tcp_rsk(req)->tfo_listener = false;
7557		if (!want_cookie &&
7558		    unlikely(!inet_csk_reqsk_queue_hash_add(sk, req))) {
7559			reqsk_free(req);
7560			dst_release(dst);
7561			return 0;
7562		}
7563		af_ops->send_synack(sk, dst, &fl, req, &foc,
7564				    !want_cookie ? TCP_SYNACK_NORMAL :
7565						   TCP_SYNACK_COOKIE,
7566				    skb);
7567		if (want_cookie) {
7568			reqsk_free(req);
7569			return 0;
7570		}
7571	}
7572	reqsk_put(req);
7573	return 0;
7574
7575drop_and_release:
7576	dst_release(dst);
7577drop_and_free:
7578	__reqsk_free(req);
7579drop:
7580	tcp_listendrop(sk);
7581	return 0;
7582}
7583EXPORT_IPV6_MOD(tcp_conn_request);
~/ Read-only file preview.