xref: /openbmc/linux/net/ipv4/tcp_input.c (revision d37cf9b63113f13d742713881ce691fc615d8b3b)
1b2441318SGreg Kroah-Hartman // SPDX-License-Identifier: GPL-2.0
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  * INET		An implementation of the TCP/IP protocol suite for the LINUX
41da177e4SLinus Torvalds  *		operating system.  INET is implemented using the  BSD Socket
51da177e4SLinus Torvalds  *		interface as the means of communication with the user level.
61da177e4SLinus Torvalds  *
71da177e4SLinus Torvalds  *		Implementation of the Transmission Control Protocol(TCP).
81da177e4SLinus Torvalds  *
902c30a84SJesper Juhl  * Authors:	Ross Biro
101da177e4SLinus Torvalds  *		Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
111da177e4SLinus Torvalds  *		Mark Evans, <evansmp@uhura.aston.ac.uk>
121da177e4SLinus Torvalds  *		Corey Minyard <wf-rch!minyard@relay.EU.net>
131da177e4SLinus Torvalds  *		Florian La Roche, <flla@stud.uni-sb.de>
141da177e4SLinus Torvalds  *		Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
151da177e4SLinus Torvalds  *		Linus Torvalds, <torvalds@cs.helsinki.fi>
161da177e4SLinus Torvalds  *		Alan Cox, <gw4pts@gw4pts.ampr.org>
171da177e4SLinus Torvalds  *		Matthew Dillon, <dillon@apollo.west.oic.com>
181da177e4SLinus Torvalds  *		Arnt Gulbrandsen, <agulbra@nvg.unit.no>
191da177e4SLinus Torvalds  *		Jorge Cwik, <jorge@laser.satlink.net>
201da177e4SLinus Torvalds  */
211da177e4SLinus Torvalds 
221da177e4SLinus Torvalds /*
231da177e4SLinus Torvalds  * Changes:
241da177e4SLinus Torvalds  *		Pedro Roque	:	Fast Retransmit/Recovery.
251da177e4SLinus Torvalds  *					Two receive queues.
261da177e4SLinus Torvalds  *					Retransmit queue handled by TCP.
271da177e4SLinus Torvalds  *					Better retransmit timer handling.
281da177e4SLinus Torvalds  *					New congestion avoidance.
291da177e4SLinus Torvalds  *					Header prediction.
301da177e4SLinus Torvalds  *					Variable renaming.
311da177e4SLinus Torvalds  *
321da177e4SLinus Torvalds  *		Eric		:	Fast Retransmit.
331da177e4SLinus Torvalds  *		Randy Scott	:	MSS option defines.
341da177e4SLinus Torvalds  *		Eric Schenk	:	Fixes to slow start algorithm.
351da177e4SLinus Torvalds  *		Eric Schenk	:	Yet another double ACK bug.
361da177e4SLinus Torvalds  *		Eric Schenk	:	Delayed ACK bug fixes.
371da177e4SLinus Torvalds  *		Eric Schenk	:	Floyd style fast retrans war avoidance.
381da177e4SLinus Torvalds  *		David S. Miller	:	Don't allow zero congestion window.
391da177e4SLinus Torvalds  *		Eric Schenk	:	Fix retransmitter so that it sends
401da177e4SLinus Torvalds  *					next packet on ack of previous packet.
411da177e4SLinus Torvalds  *		Andi Kleen	:	Moved open_request checking here
421da177e4SLinus Torvalds  *					and process RSTs for open_requests.
431da177e4SLinus Torvalds  *		Andi Kleen	:	Better prune_queue, and other fixes.
44caa20d9aSStephen Hemminger  *		Andrey Savochkin:	Fix RTT measurements in the presence of
451da177e4SLinus Torvalds  *					timestamps.
461da177e4SLinus Torvalds  *		Andrey Savochkin:	Check sequence numbers correctly when
471da177e4SLinus Torvalds  *					removing SACKs due to in sequence incoming
481da177e4SLinus Torvalds  *					data segments.
491da177e4SLinus Torvalds  *		Andi Kleen:		Make sure we never ack data there is not
501da177e4SLinus Torvalds  *					enough room for. Also make this condition
511da177e4SLinus Torvalds  *					a fatal error if it might still happen.
521da177e4SLinus Torvalds  *		Andi Kleen:		Add tcp_measure_rcv_mss to make
531da177e4SLinus Torvalds  *					connections with MSS<min(MTU,ann. MSS)
541da177e4SLinus Torvalds  *					work without delayed acks.
551da177e4SLinus Torvalds  *		Andi Kleen:		Process packets with PSH set in the
561da177e4SLinus Torvalds  *					fast path.
571da177e4SLinus Torvalds  *		J Hadi Salim:		ECN support
581da177e4SLinus Torvalds  *	 	Andrei Gurtov,
591da177e4SLinus Torvalds  *		Pasi Sarolahti,
601da177e4SLinus Torvalds  *		Panu Kuhlberg:		Experimental audit of TCP (re)transmission
611da177e4SLinus Torvalds  *					engine. Lots of bugs are found.
621da177e4SLinus Torvalds  *		Pasi Sarolahti:		F-RTO for dealing with spurious RTOs
631da177e4SLinus Torvalds  */
641da177e4SLinus Torvalds 
65afd46503SJoe Perches #define pr_fmt(fmt) "TCP: " fmt
66afd46503SJoe Perches 
671da177e4SLinus Torvalds #include <linux/mm.h>
685a0e3ad6STejun Heo #include <linux/slab.h>
691da177e4SLinus Torvalds #include <linux/module.h>
701da177e4SLinus Torvalds #include <linux/sysctl.h>
71a0bffffcSIlpo Järvinen #include <linux/kernel.h>
72ad971f61SEric Dumazet #include <linux/prefetch.h>
735ffc02a1SSatoru SATOH #include <net/dst.h>
741da177e4SLinus Torvalds #include <net/tcp.h>
751da177e4SLinus Torvalds #include <net/inet_common.h>
761da177e4SLinus Torvalds #include <linux/ipsec.h>
771da177e4SLinus Torvalds #include <asm/unaligned.h>
78e1c8a607SWillem de Bruijn #include <linux/errqueue.h>
795941521cSSong Liu #include <trace/events/tcp.h>
80494bc1d2SJakub Kicinski #include <linux/jump_label_ratelimit.h>
81c6345ce7SAmritha Nambiar #include <net/busy_poll.h>
82eda7acddSPeter Krystad #include <net/mptcp.h>
831da177e4SLinus Torvalds 
84ab32ea5dSBrian Haley int sysctl_tcp_max_orphans __read_mostly = NR_FILE;
851da177e4SLinus Torvalds 
861da177e4SLinus Torvalds #define FLAG_DATA		0x01 /* Incoming frame contained data.		*/
871da177e4SLinus Torvalds #define FLAG_WIN_UPDATE		0x02 /* Incoming ACK was a window update.	*/
881da177e4SLinus Torvalds #define FLAG_DATA_ACKED		0x04 /* This ACK acknowledged new data.		*/
891da177e4SLinus Torvalds #define FLAG_RETRANS_DATA_ACKED	0x08 /* "" "" some of which was retransmitted.	*/
901da177e4SLinus Torvalds #define FLAG_SYN_ACKED		0x10 /* This ACK acknowledged SYN.		*/
911da177e4SLinus Torvalds #define FLAG_DATA_SACKED	0x20 /* New SACK.				*/
921da177e4SLinus Torvalds #define FLAG_ECE		0x40 /* ECE in this ACK				*/
93291a00d1SYuchung Cheng #define FLAG_LOST_RETRANS	0x80 /* This ACK marks some retransmission lost */
9431770e34SFlorian Westphal #define FLAG_SLOWPATH		0x100 /* Do not skip RFC checks for window update.*/
95e33099f9SYuchung Cheng #define FLAG_ORIG_SACK_ACKED	0x200 /* Never retransmitted data are (s)acked	*/
962e605294SIlpo Järvinen #define FLAG_SND_UNA_ADVANCED	0x400 /* Snd_una was changed (!= FLAG_DATA_ACKED) */
97564262c1SRyousei Takano #define FLAG_DSACKING_ACK	0x800 /* SACK blocks contained D-SACK info */
98df92c839SNeal Cardwell #define FLAG_SET_XMIT_TIMER	0x1000 /* Set TLP or RTO timer */
99cadbd031SIlpo Järvinen #define FLAG_SACK_RENEGING	0x2000 /* snd_una advanced to a sacked seq */
10012fb3dd9SEric Dumazet #define FLAG_UPDATE_TS_RECENT	0x4000 /* tcp_replace_ts_recent() */
101d0e1a1b5SEric Dumazet #define FLAG_NO_CHALLENGE_ACK	0x8000 /* do not call tcp_send_challenge_ack()	*/
102eb36be0fSYuchung Cheng #define FLAG_ACK_MAYBE_DELAYED	0x10000 /* Likely a delayed ACK */
10363f367d9SYuchung Cheng #define FLAG_DSACK_TLP		0x20000 /* DSACK for tail loss probe */
1041da177e4SLinus Torvalds 
1051da177e4SLinus Torvalds #define FLAG_ACKED		(FLAG_DATA_ACKED|FLAG_SYN_ACKED)
1061da177e4SLinus Torvalds #define FLAG_NOT_DUP		(FLAG_DATA|FLAG_WIN_UPDATE|FLAG_ACKED)
107d09b9e60SPriyaranjan Jha #define FLAG_CA_ALERT		(FLAG_DATA_SACKED|FLAG_ECE|FLAG_DSACKING_ACK)
1081da177e4SLinus Torvalds #define FLAG_FORWARD_PROGRESS	(FLAG_ACKED|FLAG_DATA_SACKED)
1091da177e4SLinus Torvalds 
1101da177e4SLinus Torvalds #define TCP_REMNANT (TCP_FLAG_FIN|TCP_FLAG_URG|TCP_FLAG_SYN|TCP_FLAG_PSH)
111bdf1ee5dSIlpo Järvinen #define TCP_HP_BITS (~(TCP_RESERVED_BITS|TCP_FLAG_PSH))
1121da177e4SLinus Torvalds 
113e662ca40SYuchung Cheng #define REXMIT_NONE	0 /* no loss recovery to do */
114e662ca40SYuchung Cheng #define REXMIT_LOST	1 /* retransmit packets marked lost */
115e662ca40SYuchung Cheng #define REXMIT_NEW	2 /* FRTO-style transmit of unsent/new packets */
116e662ca40SYuchung Cheng 
1176dac1523SIlya Lesokhin #if IS_ENABLED(CONFIG_TLS_DEVICE)
118494bc1d2SJakub Kicinski static DEFINE_STATIC_KEY_DEFERRED_FALSE(clean_acked_data_enabled, HZ);
1196dac1523SIlya Lesokhin 
clean_acked_data_enable(struct inet_connection_sock * icsk,void (* cad)(struct sock * sk,u32 ack_seq))1206dac1523SIlya Lesokhin void clean_acked_data_enable(struct inet_connection_sock *icsk,
1216dac1523SIlya Lesokhin 			     void (*cad)(struct sock *sk, u32 ack_seq))
1226dac1523SIlya Lesokhin {
1236dac1523SIlya Lesokhin 	icsk->icsk_clean_acked = cad;
1247b58139fSWillem de Bruijn 	static_branch_deferred_inc(&clean_acked_data_enabled);
1256dac1523SIlya Lesokhin }
1266dac1523SIlya Lesokhin EXPORT_SYMBOL_GPL(clean_acked_data_enable);
1276dac1523SIlya Lesokhin 
clean_acked_data_disable(struct inet_connection_sock * icsk)1286dac1523SIlya Lesokhin void clean_acked_data_disable(struct inet_connection_sock *icsk)
1296dac1523SIlya Lesokhin {
130494bc1d2SJakub Kicinski 	static_branch_slow_dec_deferred(&clean_acked_data_enabled);
1316dac1523SIlya Lesokhin 	icsk->icsk_clean_acked = NULL;
1326dac1523SIlya Lesokhin }
1336dac1523SIlya Lesokhin EXPORT_SYMBOL_GPL(clean_acked_data_disable);
134494bc1d2SJakub Kicinski 
clean_acked_data_flush(void)135494bc1d2SJakub Kicinski void clean_acked_data_flush(void)
136494bc1d2SJakub Kicinski {
137494bc1d2SJakub Kicinski 	static_key_deferred_flush(&clean_acked_data_enabled);
138494bc1d2SJakub Kicinski }
139494bc1d2SJakub Kicinski EXPORT_SYMBOL_GPL(clean_acked_data_flush);
1406dac1523SIlya Lesokhin #endif
1416dac1523SIlya Lesokhin 
14272be0fe6SMartin KaFai Lau #ifdef CONFIG_CGROUP_BPF
bpf_skops_parse_hdr(struct sock * sk,struct sk_buff * skb)14300d211a4SMartin KaFai Lau static void bpf_skops_parse_hdr(struct sock *sk, struct sk_buff *skb)
14400d211a4SMartin KaFai Lau {
14500d211a4SMartin KaFai Lau 	bool unknown_opt = tcp_sk(sk)->rx_opt.saw_unknown &&
14600d211a4SMartin KaFai Lau 		BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk),
14700d211a4SMartin KaFai Lau 				       BPF_SOCK_OPS_PARSE_UNKNOWN_HDR_OPT_CB_FLAG);
14800d211a4SMartin KaFai Lau 	bool parse_all_opt = BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk),
14900d211a4SMartin KaFai Lau 						    BPF_SOCK_OPS_PARSE_ALL_HDR_OPT_CB_FLAG);
1500813a841SMartin KaFai Lau 	struct bpf_sock_ops_kern sock_ops;
15100d211a4SMartin KaFai Lau 
15200d211a4SMartin KaFai Lau 	if (likely(!unknown_opt && !parse_all_opt))
15300d211a4SMartin KaFai Lau 		return;
15400d211a4SMartin KaFai Lau 
15500d211a4SMartin KaFai Lau 	/* The skb will be handled in the
15600d211a4SMartin KaFai Lau 	 * bpf_skops_established() or
15700d211a4SMartin KaFai Lau 	 * bpf_skops_write_hdr_opt().
15800d211a4SMartin KaFai Lau 	 */
15900d211a4SMartin KaFai Lau 	switch (sk->sk_state) {
16000d211a4SMartin KaFai Lau 	case TCP_SYN_RECV:
16100d211a4SMartin KaFai Lau 	case TCP_SYN_SENT:
16200d211a4SMartin KaFai Lau 	case TCP_LISTEN:
16300d211a4SMartin KaFai Lau 		return;
16400d211a4SMartin KaFai Lau 	}
16500d211a4SMartin KaFai Lau 
1660813a841SMartin KaFai Lau 	sock_owned_by_me(sk);
1670813a841SMartin KaFai Lau 
1680813a841SMartin KaFai Lau 	memset(&sock_ops, 0, offsetof(struct bpf_sock_ops_kern, temp));
1690813a841SMartin KaFai Lau 	sock_ops.op = BPF_SOCK_OPS_PARSE_HDR_OPT_CB;
1700813a841SMartin KaFai Lau 	sock_ops.is_fullsock = 1;
1710813a841SMartin KaFai Lau 	sock_ops.sk = sk;
1720813a841SMartin KaFai Lau 	bpf_skops_init_skb(&sock_ops, skb, tcp_hdrlen(skb));
1730813a841SMartin KaFai Lau 
1740813a841SMartin KaFai Lau 	BPF_CGROUP_RUN_PROG_SOCK_OPS(&sock_ops);
17500d211a4SMartin KaFai Lau }
17600d211a4SMartin KaFai Lau 
bpf_skops_established(struct sock * sk,int bpf_op,struct sk_buff * skb)17772be0fe6SMartin KaFai Lau static void bpf_skops_established(struct sock *sk, int bpf_op,
17872be0fe6SMartin KaFai Lau 				  struct sk_buff *skb)
17972be0fe6SMartin KaFai Lau {
18072be0fe6SMartin KaFai Lau 	struct bpf_sock_ops_kern sock_ops;
18172be0fe6SMartin KaFai Lau 
18272be0fe6SMartin KaFai Lau 	sock_owned_by_me(sk);
18372be0fe6SMartin KaFai Lau 
18472be0fe6SMartin KaFai Lau 	memset(&sock_ops, 0, offsetof(struct bpf_sock_ops_kern, temp));
18572be0fe6SMartin KaFai Lau 	sock_ops.op = bpf_op;
18672be0fe6SMartin KaFai Lau 	sock_ops.is_fullsock = 1;
18772be0fe6SMartin KaFai Lau 	sock_ops.sk = sk;
1880813a841SMartin KaFai Lau 	/* sk with TCP_REPAIR_ON does not have skb in tcp_finish_connect */
1890813a841SMartin KaFai Lau 	if (skb)
1900813a841SMartin KaFai Lau 		bpf_skops_init_skb(&sock_ops, skb, tcp_hdrlen(skb));
19172be0fe6SMartin KaFai Lau 
19272be0fe6SMartin KaFai Lau 	BPF_CGROUP_RUN_PROG_SOCK_OPS(&sock_ops);
19372be0fe6SMartin KaFai Lau }
19472be0fe6SMartin KaFai Lau #else
bpf_skops_parse_hdr(struct sock * sk,struct sk_buff * skb)19500d211a4SMartin KaFai Lau static void bpf_skops_parse_hdr(struct sock *sk, struct sk_buff *skb)
19600d211a4SMartin KaFai Lau {
19700d211a4SMartin KaFai Lau }
19800d211a4SMartin KaFai Lau 
bpf_skops_established(struct sock * sk,int bpf_op,struct sk_buff * skb)19972be0fe6SMartin KaFai Lau static void bpf_skops_established(struct sock *sk, int bpf_op,
20072be0fe6SMartin KaFai Lau 				  struct sk_buff *skb)
20172be0fe6SMartin KaFai Lau {
20272be0fe6SMartin KaFai Lau }
20372be0fe6SMartin KaFai Lau #endif
20472be0fe6SMartin KaFai Lau 
tcp_gro_dev_warn(struct sock * sk,const struct sk_buff * skb,unsigned int len)2050b9aefeaSMarcelo Ricardo Leitner static void tcp_gro_dev_warn(struct sock *sk, const struct sk_buff *skb,
2060b9aefeaSMarcelo Ricardo Leitner 			     unsigned int len)
207dcb17d22SMarcelo Ricardo Leitner {
208dcb17d22SMarcelo Ricardo Leitner 	static bool __once __read_mostly;
209dcb17d22SMarcelo Ricardo Leitner 
210dcb17d22SMarcelo Ricardo Leitner 	if (!__once) {
211dcb17d22SMarcelo Ricardo Leitner 		struct net_device *dev;
212dcb17d22SMarcelo Ricardo Leitner 
213dcb17d22SMarcelo Ricardo Leitner 		__once = true;
214dcb17d22SMarcelo Ricardo Leitner 
215dcb17d22SMarcelo Ricardo Leitner 		rcu_read_lock();
216dcb17d22SMarcelo Ricardo Leitner 		dev = dev_get_by_index_rcu(sock_net(sk), skb->skb_iif);
2170b9aefeaSMarcelo Ricardo Leitner 		if (!dev || len >= dev->mtu)
218dcb17d22SMarcelo Ricardo Leitner 			pr_warn("%s: Driver has suspect GRO implementation, TCP performance may be compromised.\n",
219dcb17d22SMarcelo Ricardo Leitner 				dev ? dev->name : "Unknown driver");
220dcb17d22SMarcelo Ricardo Leitner 		rcu_read_unlock();
221dcb17d22SMarcelo Ricardo Leitner 	}
222dcb17d22SMarcelo Ricardo Leitner }
223dcb17d22SMarcelo Ricardo Leitner 
2241da177e4SLinus Torvalds /* Adapt the MSS value used to make delayed ack decision to the
2251da177e4SLinus Torvalds  * real world.
2261da177e4SLinus Torvalds  */
tcp_measure_rcv_mss(struct sock * sk,const struct sk_buff * skb)227056834d9SIlpo Järvinen static void tcp_measure_rcv_mss(struct sock *sk, const struct sk_buff *skb)
2281da177e4SLinus Torvalds {
229463c84b9SArnaldo Carvalho de Melo 	struct inet_connection_sock *icsk = inet_csk(sk);
230463c84b9SArnaldo Carvalho de Melo 	const unsigned int lss = icsk->icsk_ack.last_seg_size;
231463c84b9SArnaldo Carvalho de Melo 	unsigned int len;
2321da177e4SLinus Torvalds 
233463c84b9SArnaldo Carvalho de Melo 	icsk->icsk_ack.last_seg_size = 0;
2341da177e4SLinus Torvalds 
2351da177e4SLinus Torvalds 	/* skb->len may jitter because of SACKs, even if peer
2361da177e4SLinus Torvalds 	 * sends good full-sized frames.
2371da177e4SLinus Torvalds 	 */
238ff9b5e0fSHerbert Xu 	len = skb_shinfo(skb)->gso_size ? : skb->len;
239463c84b9SArnaldo Carvalho de Melo 	if (len >= icsk->icsk_ack.rcv_mss) {
240dfa2f048SEric Dumazet 		/* Note: divides are still a bit expensive.
241dfa2f048SEric Dumazet 		 * For the moment, only adjust scaling_ratio
242dfa2f048SEric Dumazet 		 * when we update icsk_ack.rcv_mss.
243dfa2f048SEric Dumazet 		 */
244dfa2f048SEric Dumazet 		if (unlikely(len != icsk->icsk_ack.rcv_mss)) {
245dfa2f048SEric Dumazet 			u64 val = (u64)skb->len << TCP_RMEM_TO_WIN_SCALE;
246227355adSSubash Abhinov Kasiviswanathan 			u8 old_ratio = tcp_sk(sk)->scaling_ratio;
247dfa2f048SEric Dumazet 
248dfa2f048SEric Dumazet 			do_div(val, skb->truesize);
249dfa2f048SEric Dumazet 			tcp_sk(sk)->scaling_ratio = val ? val : 1;
250227355adSSubash Abhinov Kasiviswanathan 
25149076867SJakub Kicinski 			if (old_ratio != tcp_sk(sk)->scaling_ratio) {
25249076867SJakub Kicinski 				struct tcp_sock *tp = tcp_sk(sk);
25349076867SJakub Kicinski 
25449076867SJakub Kicinski 				val = tcp_win_from_space(sk, sk->sk_rcvbuf);
25549076867SJakub Kicinski 				tcp_set_window_clamp(sk, val);
25649076867SJakub Kicinski 
25749076867SJakub Kicinski 				if (tp->window_clamp < tp->rcvq_space.space)
25849076867SJakub Kicinski 					tp->rcvq_space.space = tp->window_clamp;
25949076867SJakub Kicinski 			}
260dfa2f048SEric Dumazet 		}
261dcb17d22SMarcelo Ricardo Leitner 		icsk->icsk_ack.rcv_mss = min_t(unsigned int, len,
262dcb17d22SMarcelo Ricardo Leitner 					       tcp_sk(sk)->advmss);
2630b9aefeaSMarcelo Ricardo Leitner 		/* Account for possibly-removed options */
2640b9aefeaSMarcelo Ricardo Leitner 		if (unlikely(len > icsk->icsk_ack.rcv_mss +
2650b9aefeaSMarcelo Ricardo Leitner 				   MAX_TCP_OPTION_SPACE))
2660b9aefeaSMarcelo Ricardo Leitner 			tcp_gro_dev_warn(sk, skb, len);
2674720852eSNeal Cardwell 		/* If the skb has a len of exactly 1*MSS and has the PSH bit
2684720852eSNeal Cardwell 		 * set then it is likely the end of an application write. So
2694720852eSNeal Cardwell 		 * more data may not be arriving soon, and yet the data sender
2704720852eSNeal Cardwell 		 * may be waiting for an ACK if cwnd-bound or using TX zero
2714720852eSNeal Cardwell 		 * copy. So we set ICSK_ACK_PUSHED here so that
2724720852eSNeal Cardwell 		 * tcp_cleanup_rbuf() will send an ACK immediately if the app
2734720852eSNeal Cardwell 		 * reads all of the data and is not ping-pong. If len > MSS
2744720852eSNeal Cardwell 		 * then this logic does not matter (and does not hurt) because
2754720852eSNeal Cardwell 		 * tcp_cleanup_rbuf() will always ACK immediately if the app
2764720852eSNeal Cardwell 		 * reads data and there is more than an MSS of unACKed data.
2774720852eSNeal Cardwell 		 */
2784720852eSNeal Cardwell 		if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_PSH)
2794720852eSNeal Cardwell 			icsk->icsk_ack.pending |= ICSK_ACK_PUSHED;
2801da177e4SLinus Torvalds 	} else {
2811da177e4SLinus Torvalds 		/* Otherwise, we make more careful check taking into account,
2821da177e4SLinus Torvalds 		 * that SACKs block is variable.
2831da177e4SLinus Torvalds 		 *
2841da177e4SLinus Torvalds 		 * "len" is invariant segment length, including TCP header.
2851da177e4SLinus Torvalds 		 */
2869c70220bSArnaldo Carvalho de Melo 		len += skb->data - skb_transport_header(skb);
287bee7ca9eSWilliam Allen Simpson 		if (len >= TCP_MSS_DEFAULT + sizeof(struct tcphdr) ||
2881da177e4SLinus Torvalds 		    /* If PSH is not set, packet should be
2891da177e4SLinus Torvalds 		     * full sized, provided peer TCP is not badly broken.
2901da177e4SLinus Torvalds 		     * This observation (if it is correct 8)) allows
2911da177e4SLinus Torvalds 		     * to handle super-low mtu links fairly.
2921da177e4SLinus Torvalds 		     */
2931da177e4SLinus Torvalds 		    (len >= TCP_MIN_MSS + sizeof(struct tcphdr) &&
294aa8223c7SArnaldo Carvalho de Melo 		     !(tcp_flag_word(tcp_hdr(skb)) & TCP_REMNANT))) {
2951da177e4SLinus Torvalds 			/* Subtract also invariant (if peer is RFC compliant),
2961da177e4SLinus Torvalds 			 * tcp header plus fixed timestamp option length.
2971da177e4SLinus Torvalds 			 * Resulting "len" is MSS free of SACK jitter.
2981da177e4SLinus Torvalds 			 */
299463c84b9SArnaldo Carvalho de Melo 			len -= tcp_sk(sk)->tcp_header_len;
300463c84b9SArnaldo Carvalho de Melo 			icsk->icsk_ack.last_seg_size = len;
3011da177e4SLinus Torvalds 			if (len == lss) {
302463c84b9SArnaldo Carvalho de Melo 				icsk->icsk_ack.rcv_mss = len;
3031da177e4SLinus Torvalds 				return;
3041da177e4SLinus Torvalds 			}
3051da177e4SLinus Torvalds 		}
3061ef9696cSAlexey Kuznetsov 		if (icsk->icsk_ack.pending & ICSK_ACK_PUSHED)
3071ef9696cSAlexey Kuznetsov 			icsk->icsk_ack.pending |= ICSK_ACK_PUSHED2;
308463c84b9SArnaldo Carvalho de Melo 		icsk->icsk_ack.pending |= ICSK_ACK_PUSHED;
3091da177e4SLinus Torvalds 	}
3101da177e4SLinus Torvalds }
3111da177e4SLinus Torvalds 
tcp_incr_quickack(struct sock * sk,unsigned int max_quickacks)3129a9c9b51SEric Dumazet static void tcp_incr_quickack(struct sock *sk, unsigned int max_quickacks)
3131da177e4SLinus Torvalds {
314463c84b9SArnaldo Carvalho de Melo 	struct inet_connection_sock *icsk = inet_csk(sk);
31595c96174SEric Dumazet 	unsigned int quickacks = tcp_sk(sk)->rcv_wnd / (2 * icsk->icsk_ack.rcv_mss);
3161da177e4SLinus Torvalds 
3171da177e4SLinus Torvalds 	if (quickacks == 0)
3181da177e4SLinus Torvalds 		quickacks = 2;
3199a9c9b51SEric Dumazet 	quickacks = min(quickacks, max_quickacks);
320463c84b9SArnaldo Carvalho de Melo 	if (quickacks > icsk->icsk_ack.quick)
3219a9c9b51SEric Dumazet 		icsk->icsk_ack.quick = quickacks;
3221da177e4SLinus Torvalds }
3231da177e4SLinus Torvalds 
tcp_enter_quickack_mode(struct sock * sk,unsigned int max_quickacks)32403b123deSEric Dumazet static void tcp_enter_quickack_mode(struct sock *sk, unsigned int max_quickacks)
3251da177e4SLinus Torvalds {
326463c84b9SArnaldo Carvalho de Melo 	struct inet_connection_sock *icsk = inet_csk(sk);
3279a9c9b51SEric Dumazet 
3289a9c9b51SEric Dumazet 	tcp_incr_quickack(sk, max_quickacks);
32931954cd8SWei Wang 	inet_csk_exit_pingpong_mode(sk);
330463c84b9SArnaldo Carvalho de Melo 	icsk->icsk_ack.ato = TCP_ATO_MIN;
3311da177e4SLinus Torvalds }
3321da177e4SLinus Torvalds 
3331da177e4SLinus Torvalds /* Send ACKs quickly, if "quick" count is not exhausted
3341da177e4SLinus Torvalds  * and the session is not interactive.
3351da177e4SLinus Torvalds  */
3361da177e4SLinus Torvalds 
tcp_in_quickack_mode(struct sock * sk)3372251ae46SJon Maxwell static bool tcp_in_quickack_mode(struct sock *sk)
3381da177e4SLinus Torvalds {
339463c84b9SArnaldo Carvalho de Melo 	const struct inet_connection_sock *icsk = inet_csk(sk);
3402251ae46SJon Maxwell 	const struct dst_entry *dst = __sk_dst_get(sk);
341a2a385d6SEric Dumazet 
3422251ae46SJon Maxwell 	return (dst && dst_metric(dst, RTAX_QUICKACK)) ||
34331954cd8SWei Wang 		(icsk->icsk_ack.quick && !inet_csk_in_pingpong_mode(sk));
3441da177e4SLinus Torvalds }
3451da177e4SLinus Torvalds 
tcp_ecn_queue_cwr(struct tcp_sock * tp)346735d3831SFlorian Westphal static void tcp_ecn_queue_cwr(struct tcp_sock *tp)
347bdf1ee5dSIlpo Järvinen {
348bdf1ee5dSIlpo Järvinen 	if (tp->ecn_flags & TCP_ECN_OK)
349bdf1ee5dSIlpo Järvinen 		tp->ecn_flags |= TCP_ECN_QUEUE_CWR;
350bdf1ee5dSIlpo Järvinen }
351bdf1ee5dSIlpo Järvinen 
tcp_ecn_accept_cwr(struct sock * sk,const struct sk_buff * skb)352fd2123a3SYuchung Cheng static void tcp_ecn_accept_cwr(struct sock *sk, const struct sk_buff *skb)
353bdf1ee5dSIlpo Järvinen {
3549aee4000SLawrence Brakmo 	if (tcp_hdr(skb)->cwr) {
355fd2123a3SYuchung Cheng 		tcp_sk(sk)->ecn_flags &= ~TCP_ECN_DEMAND_CWR;
3569aee4000SLawrence Brakmo 
3579aee4000SLawrence Brakmo 		/* If the sender is telling us it has entered CWR, then its
3589aee4000SLawrence Brakmo 		 * cwnd may be very low (even just 1 packet), so we should ACK
3599aee4000SLawrence Brakmo 		 * immediately.
3609aee4000SLawrence Brakmo 		 */
36125702840SDenis Kirjanov 		if (TCP_SKB_CB(skb)->seq != TCP_SKB_CB(skb)->end_seq)
362fd2123a3SYuchung Cheng 			inet_csk(sk)->icsk_ack.pending |= ICSK_ACK_NOW;
3639aee4000SLawrence Brakmo 	}
364bdf1ee5dSIlpo Järvinen }
365bdf1ee5dSIlpo Järvinen 
tcp_ecn_withdraw_cwr(struct tcp_sock * tp)366735d3831SFlorian Westphal static void tcp_ecn_withdraw_cwr(struct tcp_sock *tp)
367bdf1ee5dSIlpo Järvinen {
368af38d07eSNeal Cardwell 	tp->ecn_flags &= ~TCP_ECN_QUEUE_CWR;
369bdf1ee5dSIlpo Järvinen }
370bdf1ee5dSIlpo Järvinen 
__tcp_ecn_check_ce(struct sock * sk,const struct sk_buff * skb)371f4c9f85fSYousuk Seung static void __tcp_ecn_check_ce(struct sock *sk, const struct sk_buff *skb)
372bdf1ee5dSIlpo Järvinen {
373f4c9f85fSYousuk Seung 	struct tcp_sock *tp = tcp_sk(sk);
374f4c9f85fSYousuk Seung 
375b82d1bb4SEric Dumazet 	switch (TCP_SKB_CB(skb)->ip_dsfield & INET_ECN_MASK) {
3767a269ffaSEric Dumazet 	case INET_ECN_NOT_ECT:
377bdf1ee5dSIlpo Järvinen 		/* Funny extension: if ECT is not set on a segment,
3787a269ffaSEric Dumazet 		 * and we already seen ECT on a previous segment,
3797a269ffaSEric Dumazet 		 * it is probably a retransmit.
3807a269ffaSEric Dumazet 		 */
3817a269ffaSEric Dumazet 		if (tp->ecn_flags & TCP_ECN_SEEN)
38215ecbe94SEric Dumazet 			tcp_enter_quickack_mode(sk, 2);
3837a269ffaSEric Dumazet 		break;
3847a269ffaSEric Dumazet 	case INET_ECN_CE:
385f4c9f85fSYousuk Seung 		if (tcp_ca_needs_ecn(sk))
386f4c9f85fSYousuk Seung 			tcp_ca_event(sk, CA_EVENT_ECN_IS_CE);
3879890092eSFlorian Westphal 
388aae06bf5SEric Dumazet 		if (!(tp->ecn_flags & TCP_ECN_DEMAND_CWR)) {
389aae06bf5SEric Dumazet 			/* Better not delay acks, sender can have a very low cwnd */
39015ecbe94SEric Dumazet 			tcp_enter_quickack_mode(sk, 2);
3917a269ffaSEric Dumazet 			tp->ecn_flags |= TCP_ECN_DEMAND_CWR;
392aae06bf5SEric Dumazet 		}
3937a269ffaSEric Dumazet 		tp->ecn_flags |= TCP_ECN_SEEN;
3949890092eSFlorian Westphal 		break;
3959890092eSFlorian Westphal 	default:
396f4c9f85fSYousuk Seung 		if (tcp_ca_needs_ecn(sk))
397f4c9f85fSYousuk Seung 			tcp_ca_event(sk, CA_EVENT_ECN_NO_CE);
3989890092eSFlorian Westphal 		tp->ecn_flags |= TCP_ECN_SEEN;
3999890092eSFlorian Westphal 		break;
400bdf1ee5dSIlpo Järvinen 	}
401bdf1ee5dSIlpo Järvinen }
402bdf1ee5dSIlpo Järvinen 
tcp_ecn_check_ce(struct sock * sk,const struct sk_buff * skb)403f4c9f85fSYousuk Seung static void tcp_ecn_check_ce(struct sock *sk, const struct sk_buff *skb)
404735d3831SFlorian Westphal {
405f4c9f85fSYousuk Seung 	if (tcp_sk(sk)->ecn_flags & TCP_ECN_OK)
406f4c9f85fSYousuk Seung 		__tcp_ecn_check_ce(sk, skb);
407735d3831SFlorian Westphal }
408735d3831SFlorian Westphal 
tcp_ecn_rcv_synack(struct tcp_sock * tp,const struct tcphdr * th)409735d3831SFlorian Westphal static void tcp_ecn_rcv_synack(struct tcp_sock *tp, const struct tcphdr *th)
410bdf1ee5dSIlpo Järvinen {
411bdf1ee5dSIlpo Järvinen 	if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || th->cwr))
412bdf1ee5dSIlpo Järvinen 		tp->ecn_flags &= ~TCP_ECN_OK;
413bdf1ee5dSIlpo Järvinen }
414bdf1ee5dSIlpo Järvinen 
tcp_ecn_rcv_syn(struct tcp_sock * tp,const struct tcphdr * th)415735d3831SFlorian Westphal static void tcp_ecn_rcv_syn(struct tcp_sock *tp, const struct tcphdr *th)
416bdf1ee5dSIlpo Järvinen {
417bdf1ee5dSIlpo Järvinen 	if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || !th->cwr))
418bdf1ee5dSIlpo Järvinen 		tp->ecn_flags &= ~TCP_ECN_OK;
419bdf1ee5dSIlpo Järvinen }
420bdf1ee5dSIlpo Järvinen 
tcp_ecn_rcv_ecn_echo(const struct tcp_sock * tp,const struct tcphdr * th)421735d3831SFlorian Westphal static bool tcp_ecn_rcv_ecn_echo(const struct tcp_sock *tp, const struct tcphdr *th)
422bdf1ee5dSIlpo Järvinen {
423bdf1ee5dSIlpo Järvinen 	if (th->ece && !th->syn && (tp->ecn_flags & TCP_ECN_OK))
424a2a385d6SEric Dumazet 		return true;
425a2a385d6SEric Dumazet 	return false;
426bdf1ee5dSIlpo Järvinen }
427bdf1ee5dSIlpo Järvinen 
4281da177e4SLinus Torvalds /* Buffer size and advertised window tuning.
4291da177e4SLinus Torvalds  *
4301da177e4SLinus Torvalds  * 1. Tuning sk->sk_sndbuf, when connection enters established state.
4311da177e4SLinus Torvalds  */
4321da177e4SLinus Torvalds 
tcp_sndbuf_expand(struct sock * sk)4336ae70532SEric Dumazet static void tcp_sndbuf_expand(struct sock *sk)
4341da177e4SLinus Torvalds {
4356ae70532SEric Dumazet 	const struct tcp_sock *tp = tcp_sk(sk);
43677bfc174SYuchung Cheng 	const struct tcp_congestion_ops *ca_ops = inet_csk(sk)->icsk_ca_ops;
4376ae70532SEric Dumazet 	int sndmem, per_mss;
4386ae70532SEric Dumazet 	u32 nr_segs;
4391da177e4SLinus Torvalds 
4406ae70532SEric Dumazet 	/* Worst case is non GSO/TSO : each frame consumes one skb
4416ae70532SEric Dumazet 	 * and skb->head is kmalloced using power of two area of memory
4426ae70532SEric Dumazet 	 */
4436ae70532SEric Dumazet 	per_mss = max_t(u32, tp->rx_opt.mss_clamp, tp->mss_cache) +
4446ae70532SEric Dumazet 		  MAX_TCP_HEADER +
4456ae70532SEric Dumazet 		  SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
4466ae70532SEric Dumazet 
4476ae70532SEric Dumazet 	per_mss = roundup_pow_of_two(per_mss) +
4486ae70532SEric Dumazet 		  SKB_DATA_ALIGN(sizeof(struct sk_buff));
4496ae70532SEric Dumazet 
45040570375SEric Dumazet 	nr_segs = max_t(u32, TCP_INIT_CWND, tcp_snd_cwnd(tp));
4516ae70532SEric Dumazet 	nr_segs = max_t(u32, nr_segs, tp->reordering + 1);
4526ae70532SEric Dumazet 
4536ae70532SEric Dumazet 	/* Fast Recovery (RFC 5681 3.2) :
4546ae70532SEric Dumazet 	 * Cubic needs 1.7 factor, rounded to 2 to include
455a9a08845SLinus Torvalds 	 * extra cushion (application might react slowly to EPOLLOUT)
4566ae70532SEric Dumazet 	 */
45777bfc174SYuchung Cheng 	sndmem = ca_ops->sndbuf_expand ? ca_ops->sndbuf_expand(sk) : 2;
45877bfc174SYuchung Cheng 	sndmem *= nr_segs * per_mss;
4596ae70532SEric Dumazet 
46006a59ecbSEric Dumazet 	if (sk->sk_sndbuf < sndmem)
461e292f05eSEric Dumazet 		WRITE_ONCE(sk->sk_sndbuf,
46202739545SKuniyuki Iwashima 			   min(sndmem, READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_wmem[2])));
4631da177e4SLinus Torvalds }
4641da177e4SLinus Torvalds 
4651da177e4SLinus Torvalds /* 2. Tuning advertised window (window_clamp, rcv_ssthresh)
4661da177e4SLinus Torvalds  *
4671da177e4SLinus Torvalds  * All tcp_full_space() is split to two parts: "network" buffer, allocated
4681da177e4SLinus Torvalds  * forward and advertised in receiver window (tp->rcv_wnd) and
4691da177e4SLinus Torvalds  * "application buffer", required to isolate scheduling/application
4701da177e4SLinus Torvalds  * latencies from network.
4711da177e4SLinus Torvalds  * window_clamp is maximal advertised window. It can be less than
4721da177e4SLinus Torvalds  * tcp_full_space(), in this case tcp_full_space() - window_clamp
4731da177e4SLinus Torvalds  * is reserved for "application" buffer. The less window_clamp is
4741da177e4SLinus Torvalds  * the smoother our behaviour from viewpoint of network, but the lower
4751da177e4SLinus Torvalds  * throughput and the higher sensitivity of the connection to losses. 8)
4761da177e4SLinus Torvalds  *
4771da177e4SLinus Torvalds  * rcv_ssthresh is more strict window_clamp used at "slow start"
4781da177e4SLinus Torvalds  * phase to predict further behaviour of this connection.
4791da177e4SLinus Torvalds  * It is used for two goals:
4801da177e4SLinus Torvalds  * - to enforce header prediction at sender, even when application
4811da177e4SLinus Torvalds  *   requires some significant "application buffer". It is check #1.
4821da177e4SLinus Torvalds  * - to prevent pruning of receive queue because of misprediction
4831da177e4SLinus Torvalds  *   of receiver window. Check #2.
4841da177e4SLinus Torvalds  *
4851da177e4SLinus Torvalds  * The scheme does not work when sender sends good segments opening
486caa20d9aSStephen Hemminger  * window and then starts to feed us spaghetti. But it should work
4871da177e4SLinus Torvalds  * in common situations. Otherwise, we have to rely on queue collapsing.
4881da177e4SLinus Torvalds  */
4891da177e4SLinus Torvalds 
4901da177e4SLinus Torvalds /* Slow part of check#2. */
__tcp_grow_window(const struct sock * sk,const struct sk_buff * skb,unsigned int skbtruesize)491240bfd13SEric Dumazet static int __tcp_grow_window(const struct sock *sk, const struct sk_buff *skb,
492240bfd13SEric Dumazet 			     unsigned int skbtruesize)
4931da177e4SLinus Torvalds {
494e9d9da91SEric Dumazet 	const struct tcp_sock *tp = tcp_sk(sk);
4951da177e4SLinus Torvalds 	/* Optimize this! */
496240bfd13SEric Dumazet 	int truesize = tcp_win_from_space(sk, skbtruesize) >> 1;
49702739545SKuniyuki Iwashima 	int window = tcp_win_from_space(sk, READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[2])) >> 1;
4981da177e4SLinus Torvalds 
4991da177e4SLinus Torvalds 	while (tp->rcv_ssthresh <= window) {
5001da177e4SLinus Torvalds 		if (truesize <= skb->len)
501463c84b9SArnaldo Carvalho de Melo 			return 2 * inet_csk(sk)->icsk_ack.rcv_mss;
5021da177e4SLinus Torvalds 
5031da177e4SLinus Torvalds 		truesize >>= 1;
5041da177e4SLinus Torvalds 		window >>= 1;
5051da177e4SLinus Torvalds 	}
5061da177e4SLinus Torvalds 	return 0;
5071da177e4SLinus Torvalds }
5081da177e4SLinus Torvalds 
509240bfd13SEric Dumazet /* Even if skb appears to have a bad len/truesize ratio, TCP coalescing
510240bfd13SEric Dumazet  * can play nice with us, as sk_buff and skb->head might be either
511240bfd13SEric Dumazet  * freed or shared with up to MAX_SKB_FRAGS segments.
512240bfd13SEric Dumazet  * Only give a boost to drivers using page frag(s) to hold the frame(s),
513240bfd13SEric Dumazet  * and if no payload was pulled in skb->head before reaching us.
514240bfd13SEric Dumazet  */
truesize_adjust(bool adjust,const struct sk_buff * skb)515240bfd13SEric Dumazet static u32 truesize_adjust(bool adjust, const struct sk_buff *skb)
516240bfd13SEric Dumazet {
517240bfd13SEric Dumazet 	u32 truesize = skb->truesize;
518240bfd13SEric Dumazet 
519240bfd13SEric Dumazet 	if (adjust && !skb_headlen(skb)) {
520240bfd13SEric Dumazet 		truesize -= SKB_TRUESIZE(skb_end_offset(skb));
521240bfd13SEric Dumazet 		/* paranoid check, some drivers might be buggy */
522240bfd13SEric Dumazet 		if (unlikely((int)truesize < (int)skb->len))
523240bfd13SEric Dumazet 			truesize = skb->truesize;
524240bfd13SEric Dumazet 	}
525240bfd13SEric Dumazet 	return truesize;
526240bfd13SEric Dumazet }
527240bfd13SEric Dumazet 
tcp_grow_window(struct sock * sk,const struct sk_buff * skb,bool adjust)528240bfd13SEric Dumazet static void tcp_grow_window(struct sock *sk, const struct sk_buff *skb,
529240bfd13SEric Dumazet 			    bool adjust)
5301da177e4SLinus Torvalds {
5319e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
53250ce163aSEric Dumazet 	int room;
53350ce163aSEric Dumazet 
53450ce163aSEric Dumazet 	room = min_t(int, tp->window_clamp, tcp_space(sk)) - tp->rcv_ssthresh;
5359e412ba7SIlpo Järvinen 
536053f3684SWei Wang 	if (room <= 0)
537053f3684SWei Wang 		return;
538053f3684SWei Wang 
5391da177e4SLinus Torvalds 	/* Check #1 */
540053f3684SWei Wang 	if (!tcp_under_memory_pressure(sk)) {
541240bfd13SEric Dumazet 		unsigned int truesize = truesize_adjust(adjust, skb);
5421da177e4SLinus Torvalds 		int incr;
5431da177e4SLinus Torvalds 
5441da177e4SLinus Torvalds 		/* Check #2. Increase window, if skb with such overhead
5451da177e4SLinus Torvalds 		 * will fit to rcvbuf in future.
5461da177e4SLinus Torvalds 		 */
547240bfd13SEric Dumazet 		if (tcp_win_from_space(sk, truesize) <= skb->len)
5481da177e4SLinus Torvalds 			incr = 2 * tp->advmss;
5491da177e4SLinus Torvalds 		else
550240bfd13SEric Dumazet 			incr = __tcp_grow_window(sk, skb, truesize);
5511da177e4SLinus Torvalds 
5521da177e4SLinus Torvalds 		if (incr) {
5534d846f02SEric Dumazet 			incr = max_t(int, incr, 2 * skb->len);
55450ce163aSEric Dumazet 			tp->rcv_ssthresh += min(room, incr);
555463c84b9SArnaldo Carvalho de Melo 			inet_csk(sk)->icsk_ack.quick |= 1;
5561da177e4SLinus Torvalds 		}
557053f3684SWei Wang 	} else {
558053f3684SWei Wang 		/* Under pressure:
559053f3684SWei Wang 		 * Adjust rcv_ssthresh according to reserved mem
560053f3684SWei Wang 		 */
561053f3684SWei Wang 		tcp_adjust_rcv_ssthresh(sk);
5621da177e4SLinus Torvalds 	}
5631da177e4SLinus Torvalds }
5641da177e4SLinus Torvalds 
565a337531bSYuchung Cheng /* 3. Try to fixup all. It is made immediately after connection enters
5661da177e4SLinus Torvalds  *    established state.
5671da177e4SLinus Torvalds  */
tcp_init_buffer_space(struct sock * sk)568bc183decSFlorian Westphal static void tcp_init_buffer_space(struct sock *sk)
5691da177e4SLinus Torvalds {
57002ca527aSKuniyuki Iwashima 	int tcp_app_win = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_app_win);
5711da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
5721da177e4SLinus Torvalds 	int maxwin;
5731da177e4SLinus Torvalds 
5741da177e4SLinus Torvalds 	if (!(sk->sk_userlocks & SOCK_SNDBUF_LOCK))
5756ae70532SEric Dumazet 		tcp_sndbuf_expand(sk);
5761da177e4SLinus Torvalds 
5779a568de4SEric Dumazet 	tcp_mstamp_refresh(tp);
578645f4c6fSEric Dumazet 	tp->rcvq_space.time = tp->tcp_mstamp;
579b0983d3cSEric Dumazet 	tp->rcvq_space.seq = tp->copied_seq;
5801da177e4SLinus Torvalds 
5811da177e4SLinus Torvalds 	maxwin = tcp_full_space(sk);
5821da177e4SLinus Torvalds 
5831da177e4SLinus Torvalds 	if (tp->window_clamp >= maxwin) {
584f9fef23aSEric Dumazet 		WRITE_ONCE(tp->window_clamp, maxwin);
5851da177e4SLinus Torvalds 
5860c12654aSEric Dumazet 		if (tcp_app_win && maxwin > 4 * tp->advmss)
587f9fef23aSEric Dumazet 			WRITE_ONCE(tp->window_clamp,
588f9fef23aSEric Dumazet 				   max(maxwin - (maxwin >> tcp_app_win),
589f9fef23aSEric Dumazet 				       4 * tp->advmss));
5901da177e4SLinus Torvalds 	}
5911da177e4SLinus Torvalds 
5921da177e4SLinus Torvalds 	/* Force reservation of one segment. */
5930c12654aSEric Dumazet 	if (tcp_app_win &&
5941da177e4SLinus Torvalds 	    tp->window_clamp > 2 * tp->advmss &&
5951da177e4SLinus Torvalds 	    tp->window_clamp + tp->advmss > maxwin)
596f9fef23aSEric Dumazet 		WRITE_ONCE(tp->window_clamp,
597f9fef23aSEric Dumazet 			   max(2 * tp->advmss, maxwin - tp->advmss));
5981da177e4SLinus Torvalds 
5991da177e4SLinus Torvalds 	tp->rcv_ssthresh = min(tp->rcv_ssthresh, tp->window_clamp);
600c2203cf7SEric Dumazet 	tp->snd_cwnd_stamp = tcp_jiffies32;
60172d05c00SEric Dumazet 	tp->rcvq_space.space = min3(tp->rcv_ssthresh, tp->rcv_wnd,
60272d05c00SEric Dumazet 				    (u32)TCP_INIT_CWND * tp->advmss);
6031da177e4SLinus Torvalds }
6041da177e4SLinus Torvalds 
605a337531bSYuchung Cheng /* 4. Recalculate window clamp after socket hit its memory bounds. */
tcp_clamp_window(struct sock * sk)6069e412ba7SIlpo Järvinen static void tcp_clamp_window(struct sock *sk)
6071da177e4SLinus Torvalds {
6089e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
6096687e988SArnaldo Carvalho de Melo 	struct inet_connection_sock *icsk = inet_csk(sk);
610356d1833SEric Dumazet 	struct net *net = sock_net(sk);
61102739545SKuniyuki Iwashima 	int rmem2;
6121da177e4SLinus Torvalds 
6136687e988SArnaldo Carvalho de Melo 	icsk->icsk_ack.quick = 0;
61402739545SKuniyuki Iwashima 	rmem2 = READ_ONCE(net->ipv4.sysctl_tcp_rmem[2]);
6151da177e4SLinus Torvalds 
61602739545SKuniyuki Iwashima 	if (sk->sk_rcvbuf < rmem2 &&
6171da177e4SLinus Torvalds 	    !(sk->sk_userlocks & SOCK_RCVBUF_LOCK) &&
618b8da51ebSEric Dumazet 	    !tcp_under_memory_pressure(sk) &&
619180d8cd9SGlauber Costa 	    sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0)) {
620ebb3b78dSEric Dumazet 		WRITE_ONCE(sk->sk_rcvbuf,
62102739545SKuniyuki Iwashima 			   min(atomic_read(&sk->sk_rmem_alloc), rmem2));
6221da177e4SLinus Torvalds 	}
623326f36e9SJohn Heffner 	if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf)
6241da177e4SLinus Torvalds 		tp->rcv_ssthresh = min(tp->window_clamp, 2U * tp->advmss);
6251da177e4SLinus Torvalds }
6261da177e4SLinus Torvalds 
62740efc6faSStephen Hemminger /* Initialize RCV_MSS value.
62840efc6faSStephen Hemminger  * RCV_MSS is an our guess about MSS used by the peer.
62940efc6faSStephen Hemminger  * We haven't any direct information about the MSS.
63040efc6faSStephen Hemminger  * It's better to underestimate the RCV_MSS rather than overestimate.
63140efc6faSStephen Hemminger  * Overestimations make us ACKing less frequently than needed.
63240efc6faSStephen Hemminger  * Underestimations are more easy to detect and fix by tcp_measure_rcv_mss().
63340efc6faSStephen Hemminger  */
tcp_initialize_rcv_mss(struct sock * sk)63440efc6faSStephen Hemminger void tcp_initialize_rcv_mss(struct sock *sk)
63540efc6faSStephen Hemminger {
636cf533ea5SEric Dumazet 	const struct tcp_sock *tp = tcp_sk(sk);
63740efc6faSStephen Hemminger 	unsigned int hint = min_t(unsigned int, tp->advmss, tp->mss_cache);
63840efc6faSStephen Hemminger 
63940efc6faSStephen Hemminger 	hint = min(hint, tp->rcv_wnd / 2);
640bee7ca9eSWilliam Allen Simpson 	hint = min(hint, TCP_MSS_DEFAULT);
64140efc6faSStephen Hemminger 	hint = max(hint, TCP_MIN_MSS);
64240efc6faSStephen Hemminger 
64340efc6faSStephen Hemminger 	inet_csk(sk)->icsk_ack.rcv_mss = hint;
64440efc6faSStephen Hemminger }
6454bc2f18bSEric Dumazet EXPORT_SYMBOL(tcp_initialize_rcv_mss);
64640efc6faSStephen Hemminger 
6471da177e4SLinus Torvalds /* Receiver "autotuning" code.
6481da177e4SLinus Torvalds  *
6491da177e4SLinus Torvalds  * The algorithm for RTT estimation w/o timestamps is based on
6501da177e4SLinus Torvalds  * Dynamic Right-Sizing (DRS) by Wu Feng and Mike Fisk of LANL.
6517a6498ebSAlexander A. Klimov  * <https://public.lanl.gov/radiant/pubs.html#DRS>
6521da177e4SLinus Torvalds  *
6531da177e4SLinus Torvalds  * More detail on this code can be found at
654631dd1a8SJustin P. Mattock  * <http://staff.psc.edu/jheffner/>,
6551da177e4SLinus Torvalds  * though this reference is out of date.  A new paper
6561da177e4SLinus Torvalds  * is pending.
6571da177e4SLinus Torvalds  */
tcp_rcv_rtt_update(struct tcp_sock * tp,u32 sample,int win_dep)6581da177e4SLinus Torvalds static void tcp_rcv_rtt_update(struct tcp_sock *tp, u32 sample, int win_dep)
6591da177e4SLinus Torvalds {
660645f4c6fSEric Dumazet 	u32 new_sample = tp->rcv_rtt_est.rtt_us;
6611da177e4SLinus Torvalds 	long m = sample;
6621da177e4SLinus Torvalds 
6631da177e4SLinus Torvalds 	if (new_sample != 0) {
6641da177e4SLinus Torvalds 		/* If we sample in larger samples in the non-timestamp
6651da177e4SLinus Torvalds 		 * case, we could grossly overestimate the RTT especially
6661da177e4SLinus Torvalds 		 * with chatty applications or bulk transfer apps which
6671da177e4SLinus Torvalds 		 * are stalled on filesystem I/O.
6681da177e4SLinus Torvalds 		 *
6691da177e4SLinus Torvalds 		 * Also, since we are only going for a minimum in the
67031f34269SStephen Hemminger 		 * non-timestamp case, we do not smooth things out
671caa20d9aSStephen Hemminger 		 * else with timestamps disabled convergence takes too
6721da177e4SLinus Torvalds 		 * long.
6731da177e4SLinus Torvalds 		 */
6741da177e4SLinus Torvalds 		if (!win_dep) {
6751da177e4SLinus Torvalds 			m -= (new_sample >> 3);
6761da177e4SLinus Torvalds 			new_sample += m;
67718a223e0SNeal Cardwell 		} else {
67818a223e0SNeal Cardwell 			m <<= 3;
67918a223e0SNeal Cardwell 			if (m < new_sample)
68018a223e0SNeal Cardwell 				new_sample = m;
68118a223e0SNeal Cardwell 		}
6821da177e4SLinus Torvalds 	} else {
683caa20d9aSStephen Hemminger 		/* No previous measure. */
6841da177e4SLinus Torvalds 		new_sample = m << 3;
6851da177e4SLinus Torvalds 	}
6861da177e4SLinus Torvalds 
687645f4c6fSEric Dumazet 	tp->rcv_rtt_est.rtt_us = new_sample;
6881da177e4SLinus Torvalds }
6891da177e4SLinus Torvalds 
tcp_rcv_rtt_measure(struct tcp_sock * tp)6901da177e4SLinus Torvalds static inline void tcp_rcv_rtt_measure(struct tcp_sock *tp)
6911da177e4SLinus Torvalds {
692645f4c6fSEric Dumazet 	u32 delta_us;
693645f4c6fSEric Dumazet 
6949a568de4SEric Dumazet 	if (tp->rcv_rtt_est.time == 0)
6951da177e4SLinus Torvalds 		goto new_measure;
6961da177e4SLinus Torvalds 	if (before(tp->rcv_nxt, tp->rcv_rtt_est.seq))
6971da177e4SLinus Torvalds 		return;
6989a568de4SEric Dumazet 	delta_us = tcp_stamp_us_delta(tp->tcp_mstamp, tp->rcv_rtt_est.time);
6999ee11bd0SWei Wang 	if (!delta_us)
7009ee11bd0SWei Wang 		delta_us = 1;
701645f4c6fSEric Dumazet 	tcp_rcv_rtt_update(tp, delta_us, 1);
7021da177e4SLinus Torvalds 
7031da177e4SLinus Torvalds new_measure:
7041da177e4SLinus Torvalds 	tp->rcv_rtt_est.seq = tp->rcv_nxt + tp->rcv_wnd;
705645f4c6fSEric Dumazet 	tp->rcv_rtt_est.time = tp->tcp_mstamp;
7061da177e4SLinus Torvalds }
7071da177e4SLinus Torvalds 
tcp_rcv_rtt_measure_ts(struct sock * sk,const struct sk_buff * skb)708056834d9SIlpo Järvinen static inline void tcp_rcv_rtt_measure_ts(struct sock *sk,
709056834d9SIlpo Järvinen 					  const struct sk_buff *skb)
7101da177e4SLinus Torvalds {
711463c84b9SArnaldo Carvalho de Melo 	struct tcp_sock *tp = tcp_sk(sk);
7129a568de4SEric Dumazet 
7133f6c65d6SWei Wang 	if (tp->rx_opt.rcv_tsecr == tp->rcv_rtt_last_tsecr)
7143f6c65d6SWei Wang 		return;
7153f6c65d6SWei Wang 	tp->rcv_rtt_last_tsecr = tp->rx_opt.rcv_tsecr;
7163f6c65d6SWei Wang 
7173f6c65d6SWei Wang 	if (TCP_SKB_CB(skb)->end_seq -
7183f6c65d6SWei Wang 	    TCP_SKB_CB(skb)->seq >= inet_csk(sk)->icsk_ack.rcv_mss) {
7199a568de4SEric Dumazet 		u32 delta = tcp_time_stamp(tp) - tp->rx_opt.rcv_tsecr;
7209ee11bd0SWei Wang 		u32 delta_us;
7219a568de4SEric Dumazet 
7229efdda4eSEric Dumazet 		if (likely(delta < INT_MAX / (USEC_PER_SEC / TCP_TS_HZ))) {
7239ee11bd0SWei Wang 			if (!delta)
7249ee11bd0SWei Wang 				delta = 1;
7259ee11bd0SWei Wang 			delta_us = delta * (USEC_PER_SEC / TCP_TS_HZ);
7269a568de4SEric Dumazet 			tcp_rcv_rtt_update(tp, delta_us, 0);
7279a568de4SEric Dumazet 		}
7281da177e4SLinus Torvalds 	}
7299efdda4eSEric Dumazet }
7301da177e4SLinus Torvalds 
7311da177e4SLinus Torvalds /*
7321da177e4SLinus Torvalds  * This function should be called every time data is copied to user space.
7331da177e4SLinus Torvalds  * It calculates the appropriate TCP receive buffer space.
7341da177e4SLinus Torvalds  */
tcp_rcv_space_adjust(struct sock * sk)7351da177e4SLinus Torvalds void tcp_rcv_space_adjust(struct sock *sk)
7361da177e4SLinus Torvalds {
7371da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
738607065baSEric Dumazet 	u32 copied;
7391da177e4SLinus Torvalds 	int time;
7401da177e4SLinus Torvalds 
7416163849dSYafang Shao 	trace_tcp_rcv_space_adjust(sk);
7426163849dSYafang Shao 
74386323850SEric Dumazet 	tcp_mstamp_refresh(tp);
7449a568de4SEric Dumazet 	time = tcp_stamp_us_delta(tp->tcp_mstamp, tp->rcvq_space.time);
745645f4c6fSEric Dumazet 	if (time < (tp->rcv_rtt_est.rtt_us >> 3) || tp->rcv_rtt_est.rtt_us == 0)
7461da177e4SLinus Torvalds 		return;
7471da177e4SLinus Torvalds 
748b0983d3cSEric Dumazet 	/* Number of bytes copied to user in last RTT */
749b0983d3cSEric Dumazet 	copied = tp->copied_seq - tp->rcvq_space.seq;
750b0983d3cSEric Dumazet 	if (copied <= tp->rcvq_space.space)
751b0983d3cSEric Dumazet 		goto new_measure;
7521da177e4SLinus Torvalds 
753b0983d3cSEric Dumazet 	/* A bit of theory :
754b0983d3cSEric Dumazet 	 * copied = bytes received in previous RTT, our base window
755b0983d3cSEric Dumazet 	 * To cope with packet losses, we need a 2x factor
756b0983d3cSEric Dumazet 	 * To cope with slow start, and sender growing its cwin by 100 %
757b0983d3cSEric Dumazet 	 * every RTT, we need a 4x factor, because the ACK we are sending
758b0983d3cSEric Dumazet 	 * now is for the next RTT, not the current one :
759b0983d3cSEric Dumazet 	 * <prev RTT . ><current RTT .. ><next RTT .... >
760b0983d3cSEric Dumazet 	 */
7611da177e4SLinus Torvalds 
762227355adSSubash Abhinov Kasiviswanathan 	if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_moderate_rcvbuf) &&
763227355adSSubash Abhinov Kasiviswanathan 	    !(sk->sk_userlocks & SOCK_RCVBUF_LOCK)) {
764c3916ad9SEric Dumazet 		u64 rcvwin, grow;
765dfa2f048SEric Dumazet 		int rcvbuf;
7661da177e4SLinus Torvalds 
767b0983d3cSEric Dumazet 		/* minimal window to cope with packet losses, assuming
768b0983d3cSEric Dumazet 		 * steady state. Add some cushion because of small variations.
7691da177e4SLinus Torvalds 		 */
770607065baSEric Dumazet 		rcvwin = ((u64)copied << 1) + 16 * tp->advmss;
771b0983d3cSEric Dumazet 
772c3916ad9SEric Dumazet 		/* Accommodate for sender rate increase (eg. slow start) */
773c3916ad9SEric Dumazet 		grow = rcvwin * (copied - tp->rcvq_space.space);
774c3916ad9SEric Dumazet 		do_div(grow, tp->rcvq_space.space);
775c3916ad9SEric Dumazet 		rcvwin += (grow << 1);
776b0983d3cSEric Dumazet 
777dfa2f048SEric Dumazet 		rcvbuf = min_t(u64, tcp_space_from_win(sk, rcvwin),
77802739545SKuniyuki Iwashima 			       READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[2]));
779b0983d3cSEric Dumazet 		if (rcvbuf > sk->sk_rcvbuf) {
780ebb3b78dSEric Dumazet 			WRITE_ONCE(sk->sk_rcvbuf, rcvbuf);
7811da177e4SLinus Torvalds 
7821da177e4SLinus Torvalds 			/* Make the window clamp follow along.  */
783f9fef23aSEric Dumazet 			WRITE_ONCE(tp->window_clamp,
784f9fef23aSEric Dumazet 				   tcp_win_from_space(sk, rcvbuf));
7851da177e4SLinus Torvalds 		}
7861da177e4SLinus Torvalds 	}
787b0983d3cSEric Dumazet 	tp->rcvq_space.space = copied;
7881da177e4SLinus Torvalds 
7891da177e4SLinus Torvalds new_measure:
7901da177e4SLinus Torvalds 	tp->rcvq_space.seq = tp->copied_seq;
791645f4c6fSEric Dumazet 	tp->rcvq_space.time = tp->tcp_mstamp;
7921da177e4SLinus Torvalds }
7931da177e4SLinus Torvalds 
7941da177e4SLinus Torvalds /* There is something which you must keep in mind when you analyze the
7951da177e4SLinus Torvalds  * behavior of the tp->ato delayed ack timeout interval.  When a
7961da177e4SLinus Torvalds  * connection starts up, we want to ack as quickly as possible.  The
7971da177e4SLinus Torvalds  * problem is that "good" TCP's do slow start at the beginning of data
7981da177e4SLinus Torvalds  * transmission.  The means that until we send the first few ACK's the
7991da177e4SLinus Torvalds  * sender will sit on his end and only queue most of his data, because
8001da177e4SLinus Torvalds  * he can only send snd_cwnd unacked packets at any given time.  For
8011da177e4SLinus Torvalds  * each ACK we send, he increments snd_cwnd and transmits more of his
8021da177e4SLinus Torvalds  * queue.  -DaveM
8031da177e4SLinus Torvalds  */
tcp_event_data_recv(struct sock * sk,struct sk_buff * skb)8049e412ba7SIlpo Järvinen static void tcp_event_data_recv(struct sock *sk, struct sk_buff *skb)
8051da177e4SLinus Torvalds {
8069e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
807463c84b9SArnaldo Carvalho de Melo 	struct inet_connection_sock *icsk = inet_csk(sk);
8081da177e4SLinus Torvalds 	u32 now;
8091da177e4SLinus Torvalds 
810463c84b9SArnaldo Carvalho de Melo 	inet_csk_schedule_ack(sk);
8111da177e4SLinus Torvalds 
812463c84b9SArnaldo Carvalho de Melo 	tcp_measure_rcv_mss(sk, skb);
8131da177e4SLinus Torvalds 
8141da177e4SLinus Torvalds 	tcp_rcv_rtt_measure(tp);
8151da177e4SLinus Torvalds 
81670eabf0eSEric Dumazet 	now = tcp_jiffies32;
8171da177e4SLinus Torvalds 
818463c84b9SArnaldo Carvalho de Melo 	if (!icsk->icsk_ack.ato) {
8191da177e4SLinus Torvalds 		/* The _first_ data packet received, initialize
8201da177e4SLinus Torvalds 		 * delayed ACK engine.
8211da177e4SLinus Torvalds 		 */
8229a9c9b51SEric Dumazet 		tcp_incr_quickack(sk, TCP_MAX_QUICKACKS);
823463c84b9SArnaldo Carvalho de Melo 		icsk->icsk_ack.ato = TCP_ATO_MIN;
8241da177e4SLinus Torvalds 	} else {
825463c84b9SArnaldo Carvalho de Melo 		int m = now - icsk->icsk_ack.lrcvtime;
8261da177e4SLinus Torvalds 
8271da177e4SLinus Torvalds 		if (m <= TCP_ATO_MIN / 2) {
8281da177e4SLinus Torvalds 			/* The fastest case is the first. */
829463c84b9SArnaldo Carvalho de Melo 			icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + TCP_ATO_MIN / 2;
830463c84b9SArnaldo Carvalho de Melo 		} else if (m < icsk->icsk_ack.ato) {
831463c84b9SArnaldo Carvalho de Melo 			icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + m;
832463c84b9SArnaldo Carvalho de Melo 			if (icsk->icsk_ack.ato > icsk->icsk_rto)
833463c84b9SArnaldo Carvalho de Melo 				icsk->icsk_ack.ato = icsk->icsk_rto;
834463c84b9SArnaldo Carvalho de Melo 		} else if (m > icsk->icsk_rto) {
835caa20d9aSStephen Hemminger 			/* Too long gap. Apparently sender failed to
8361da177e4SLinus Torvalds 			 * restart window, so that we send ACKs quickly.
8371da177e4SLinus Torvalds 			 */
8389a9c9b51SEric Dumazet 			tcp_incr_quickack(sk, TCP_MAX_QUICKACKS);
8391da177e4SLinus Torvalds 		}
8401da177e4SLinus Torvalds 	}
841463c84b9SArnaldo Carvalho de Melo 	icsk->icsk_ack.lrcvtime = now;
8421da177e4SLinus Torvalds 
843f4c9f85fSYousuk Seung 	tcp_ecn_check_ce(sk, skb);
8441da177e4SLinus Torvalds 
8451da177e4SLinus Torvalds 	if (skb->len >= 128)
846240bfd13SEric Dumazet 		tcp_grow_window(sk, skb, true);
8471da177e4SLinus Torvalds }
8481da177e4SLinus Torvalds 
8491da177e4SLinus Torvalds /* Called to compute a smoothed rtt estimate. The data fed to this
8501da177e4SLinus Torvalds  * routine either comes from timestamps, or from segments that were
8511da177e4SLinus Torvalds  * known _not_ to have been retransmitted [see Karn/Partridge
8521da177e4SLinus Torvalds  * Proceedings SIGCOMM 87]. The algorithm is from the SIGCOMM 88
8531da177e4SLinus Torvalds  * piece by Van Jacobson.
8541da177e4SLinus Torvalds  * NOTE: the next three routines used to be one big routine.
8551da177e4SLinus Torvalds  * To save cycles in the RFC 1323 implementation it was better to break
8561da177e4SLinus Torvalds  * it up into three procedures. -- erics
8571da177e4SLinus Torvalds  */
tcp_rtt_estimator(struct sock * sk,long mrtt_us)858740b0f18SEric Dumazet static void tcp_rtt_estimator(struct sock *sk, long mrtt_us)
8591da177e4SLinus Torvalds {
8606687e988SArnaldo Carvalho de Melo 	struct tcp_sock *tp = tcp_sk(sk);
861740b0f18SEric Dumazet 	long m = mrtt_us; /* RTT */
862740b0f18SEric Dumazet 	u32 srtt = tp->srtt_us;
8631da177e4SLinus Torvalds 
8641da177e4SLinus Torvalds 	/*	The following amusing code comes from Jacobson's
8651da177e4SLinus Torvalds 	 *	article in SIGCOMM '88.  Note that rtt and mdev
8661da177e4SLinus Torvalds 	 *	are scaled versions of rtt and mean deviation.
8671da177e4SLinus Torvalds 	 *	This is designed to be as fast as possible
8681da177e4SLinus Torvalds 	 *	m stands for "measurement".
8691da177e4SLinus Torvalds 	 *
8701da177e4SLinus Torvalds 	 *	On a 1990 paper the rto value is changed to:
8711da177e4SLinus Torvalds 	 *	RTO = rtt + 4 * mdev
8721da177e4SLinus Torvalds 	 *
8731da177e4SLinus Torvalds 	 * Funny. This algorithm seems to be very broken.
8741da177e4SLinus Torvalds 	 * These formulae increase RTO, when it should be decreased, increase
87531f34269SStephen Hemminger 	 * too slowly, when it should be increased quickly, decrease too quickly
8761da177e4SLinus Torvalds 	 * etc. I guess in BSD RTO takes ONE value, so that it is absolutely
8771da177e4SLinus Torvalds 	 * does not matter how to _calculate_ it. Seems, it was trap
8781da177e4SLinus Torvalds 	 * that VJ failed to avoid. 8)
8791da177e4SLinus Torvalds 	 */
8804a5ab4e2SEric Dumazet 	if (srtt != 0) {
8814a5ab4e2SEric Dumazet 		m -= (srtt >> 3);	/* m is now error in rtt est */
8824a5ab4e2SEric Dumazet 		srtt += m;		/* rtt = 7/8 rtt + 1/8 new */
8831da177e4SLinus Torvalds 		if (m < 0) {
8841da177e4SLinus Torvalds 			m = -m;		/* m is now abs(error) */
885740b0f18SEric Dumazet 			m -= (tp->mdev_us >> 2);   /* similar update on mdev */
8861da177e4SLinus Torvalds 			/* This is similar to one of Eifel findings.
8871da177e4SLinus Torvalds 			 * Eifel blocks mdev updates when rtt decreases.
8881da177e4SLinus Torvalds 			 * This solution is a bit different: we use finer gain
8891da177e4SLinus Torvalds 			 * for mdev in this case (alpha*beta).
8901da177e4SLinus Torvalds 			 * Like Eifel it also prevents growth of rto,
8911da177e4SLinus Torvalds 			 * but also it limits too fast rto decreases,
8921da177e4SLinus Torvalds 			 * happening in pure Eifel.
8931da177e4SLinus Torvalds 			 */
8941da177e4SLinus Torvalds 			if (m > 0)
8951da177e4SLinus Torvalds 				m >>= 3;
8961da177e4SLinus Torvalds 		} else {
897740b0f18SEric Dumazet 			m -= (tp->mdev_us >> 2);   /* similar update on mdev */
8981da177e4SLinus Torvalds 		}
899740b0f18SEric Dumazet 		tp->mdev_us += m;		/* mdev = 3/4 mdev + 1/4 new */
900740b0f18SEric Dumazet 		if (tp->mdev_us > tp->mdev_max_us) {
901740b0f18SEric Dumazet 			tp->mdev_max_us = tp->mdev_us;
902740b0f18SEric Dumazet 			if (tp->mdev_max_us > tp->rttvar_us)
903740b0f18SEric Dumazet 				tp->rttvar_us = tp->mdev_max_us;
9041da177e4SLinus Torvalds 		}
9051da177e4SLinus Torvalds 		if (after(tp->snd_una, tp->rtt_seq)) {
906740b0f18SEric Dumazet 			if (tp->mdev_max_us < tp->rttvar_us)
907740b0f18SEric Dumazet 				tp->rttvar_us -= (tp->rttvar_us - tp->mdev_max_us) >> 2;
9081da177e4SLinus Torvalds 			tp->rtt_seq = tp->snd_nxt;
909740b0f18SEric Dumazet 			tp->mdev_max_us = tcp_rto_min_us(sk);
91023729ff2SStanislav Fomichev 
91123729ff2SStanislav Fomichev 			tcp_bpf_rtt(sk);
9121da177e4SLinus Torvalds 		}
9131da177e4SLinus Torvalds 	} else {
9141da177e4SLinus Torvalds 		/* no previous measure. */
9154a5ab4e2SEric Dumazet 		srtt = m << 3;		/* take the measured time to be rtt */
916740b0f18SEric Dumazet 		tp->mdev_us = m << 1;	/* make sure rto = 3*rtt */
917740b0f18SEric Dumazet 		tp->rttvar_us = max(tp->mdev_us, tcp_rto_min_us(sk));
918740b0f18SEric Dumazet 		tp->mdev_max_us = tp->rttvar_us;
9191da177e4SLinus Torvalds 		tp->rtt_seq = tp->snd_nxt;
92023729ff2SStanislav Fomichev 
92123729ff2SStanislav Fomichev 		tcp_bpf_rtt(sk);
9221da177e4SLinus Torvalds 	}
923740b0f18SEric Dumazet 	tp->srtt_us = max(1U, srtt);
9241da177e4SLinus Torvalds }
9251da177e4SLinus Torvalds 
tcp_update_pacing_rate(struct sock * sk)92695bd09ebSEric Dumazet static void tcp_update_pacing_rate(struct sock *sk)
92795bd09ebSEric Dumazet {
92895bd09ebSEric Dumazet 	const struct tcp_sock *tp = tcp_sk(sk);
92995bd09ebSEric Dumazet 	u64 rate;
93095bd09ebSEric Dumazet 
93195bd09ebSEric Dumazet 	/* set sk_pacing_rate to 200 % of current rate (mss * cwnd / srtt) */
93243e122b0SEric Dumazet 	rate = (u64)tp->mss_cache * ((USEC_PER_SEC / 100) << 3);
93343e122b0SEric Dumazet 
93443e122b0SEric Dumazet 	/* current rate is (cwnd * mss) / srtt
93543e122b0SEric Dumazet 	 * In Slow Start [1], set sk_pacing_rate to 200 % the current rate.
93643e122b0SEric Dumazet 	 * In Congestion Avoidance phase, set it to 120 % the current rate.
93743e122b0SEric Dumazet 	 *
93843e122b0SEric Dumazet 	 * [1] : Normal Slow Start condition is (tp->snd_cwnd < tp->snd_ssthresh)
93943e122b0SEric Dumazet 	 *	 If snd_cwnd >= (tp->snd_ssthresh / 2), we are approaching
94043e122b0SEric Dumazet 	 *	 end of slow start and should slow down.
94143e122b0SEric Dumazet 	 */
94240570375SEric Dumazet 	if (tcp_snd_cwnd(tp) < tp->snd_ssthresh / 2)
94359bf6c65SKuniyuki Iwashima 		rate *= READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_pacing_ss_ratio);
94443e122b0SEric Dumazet 	else
94559bf6c65SKuniyuki Iwashima 		rate *= READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_pacing_ca_ratio);
94695bd09ebSEric Dumazet 
94740570375SEric Dumazet 	rate *= max(tcp_snd_cwnd(tp), tp->packets_out);
94895bd09ebSEric Dumazet 
949740b0f18SEric Dumazet 	if (likely(tp->srtt_us))
950740b0f18SEric Dumazet 		do_div(rate, tp->srtt_us);
95195bd09ebSEric Dumazet 
952a9da6f29SMark Rutland 	/* WRITE_ONCE() is needed because sch_fq fetches sk_pacing_rate
953ba537427SEric Dumazet 	 * without any lock. We want to make sure compiler wont store
954ba537427SEric Dumazet 	 * intermediate values in this location.
955ba537427SEric Dumazet 	 */
956a9da6f29SMark Rutland 	WRITE_ONCE(sk->sk_pacing_rate, min_t(u64, rate,
957a9da6f29SMark Rutland 					     sk->sk_max_pacing_rate));
95895bd09ebSEric Dumazet }
95995bd09ebSEric Dumazet 
9601da177e4SLinus Torvalds /* Calculate rto without backoff.  This is the second half of Van Jacobson's
9611da177e4SLinus Torvalds  * routine referred to above.
9621da177e4SLinus Torvalds  */
tcp_set_rto(struct sock * sk)963f7e56a76Sstephen hemminger static void tcp_set_rto(struct sock *sk)
9641da177e4SLinus Torvalds {
965463c84b9SArnaldo Carvalho de Melo 	const struct tcp_sock *tp = tcp_sk(sk);
9661da177e4SLinus Torvalds 	/* Old crap is replaced with new one. 8)
9671da177e4SLinus Torvalds 	 *
9681da177e4SLinus Torvalds 	 * More seriously:
9691da177e4SLinus Torvalds 	 * 1. If rtt variance happened to be less 50msec, it is hallucination.
9701da177e4SLinus Torvalds 	 *    It cannot be less due to utterly erratic ACK generation made
9711da177e4SLinus Torvalds 	 *    at least by solaris and freebsd. "Erratic ACKs" has _nothing_
9721da177e4SLinus Torvalds 	 *    to do with delayed acks, because at cwnd>2 true delack timeout
9731da177e4SLinus Torvalds 	 *    is invisible. Actually, Linux-2.4 also generates erratic
974caa20d9aSStephen Hemminger 	 *    ACKs in some circumstances.
9751da177e4SLinus Torvalds 	 */
976f1ecd5d9SDamian Lukowski 	inet_csk(sk)->icsk_rto = __tcp_set_rto(tp);
9771da177e4SLinus Torvalds 
9781da177e4SLinus Torvalds 	/* 2. Fixups made earlier cannot be right.
9791da177e4SLinus Torvalds 	 *    If we do not estimate RTO correctly without them,
9801da177e4SLinus Torvalds 	 *    all the algo is pure shit and should be replaced
981caa20d9aSStephen Hemminger 	 *    with correct one. It is exactly, which we pretend to do.
9821da177e4SLinus Torvalds 	 */
9831da177e4SLinus Torvalds 
9841da177e4SLinus Torvalds 	/* NOTE: clamping at TCP_RTO_MIN is not required, current algo
9851da177e4SLinus Torvalds 	 * guarantees that rto is higher.
9861da177e4SLinus Torvalds 	 */
987f1ecd5d9SDamian Lukowski 	tcp_bound_rto(sk);
9881da177e4SLinus Torvalds }
9891da177e4SLinus Torvalds 
tcp_init_cwnd(const struct tcp_sock * tp,const struct dst_entry * dst)990cf533ea5SEric Dumazet __u32 tcp_init_cwnd(const struct tcp_sock *tp, const struct dst_entry *dst)
9911da177e4SLinus Torvalds {
9921da177e4SLinus Torvalds 	__u32 cwnd = (dst ? dst_metric(dst, RTAX_INITCWND) : 0);
9931da177e4SLinus Torvalds 
99422b71c8fSGerrit Renker 	if (!cwnd)
995442b9635SDavid S. Miller 		cwnd = TCP_INIT_CWND;
9961da177e4SLinus Torvalds 	return min_t(__u32, cwnd, tp->snd_cwnd_clamp);
9971da177e4SLinus Torvalds }
9981da177e4SLinus Torvalds 
999a71d77e6SPriyaranjan Jha struct tcp_sacktag_state {
1000a71d77e6SPriyaranjan Jha 	/* Timestamps for earliest and latest never-retransmitted segment
1001a71d77e6SPriyaranjan Jha 	 * that was SACKed. RTO needs the earliest RTT to stay conservative,
1002a71d77e6SPriyaranjan Jha 	 * but congestion control should still get an accurate delay signal.
1003a71d77e6SPriyaranjan Jha 	 */
1004a71d77e6SPriyaranjan Jha 	u64	first_sackt;
1005a71d77e6SPriyaranjan Jha 	u64	last_sackt;
1006a71d77e6SPriyaranjan Jha 	u32	reord;
1007a71d77e6SPriyaranjan Jha 	u32	sack_delivered;
1008a71d77e6SPriyaranjan Jha 	int	flag;
1009a71d77e6SPriyaranjan Jha 	unsigned int mss_now;
1010a71d77e6SPriyaranjan Jha 	struct rate_sample *rate;
1011a71d77e6SPriyaranjan Jha };
1012a71d77e6SPriyaranjan Jha 
1013ad2b9b0fSPriyaranjan Jha /* Take a notice that peer is sending D-SACKs. Skip update of data delivery
1014ad2b9b0fSPriyaranjan Jha  * and spurious retransmission information if this DSACK is unlikely caused by
1015ad2b9b0fSPriyaranjan Jha  * sender's action:
1016ad2b9b0fSPriyaranjan Jha  * - DSACKed sequence range is larger than maximum receiver's window.
1017ad2b9b0fSPriyaranjan Jha  * - Total no. of DSACKed segments exceed the total no. of retransmitted segs.
1018ad2b9b0fSPriyaranjan Jha  */
tcp_dsack_seen(struct tcp_sock * tp,u32 start_seq,u32 end_seq,struct tcp_sacktag_state * state)1019a71d77e6SPriyaranjan Jha static u32 tcp_dsack_seen(struct tcp_sock *tp, u32 start_seq,
1020a71d77e6SPriyaranjan Jha 			  u32 end_seq, struct tcp_sacktag_state *state)
1021e60402d0SIlpo Järvinen {
1022a71d77e6SPriyaranjan Jha 	u32 seq_len, dup_segs = 1;
1023a71d77e6SPriyaranjan Jha 
1024ad2b9b0fSPriyaranjan Jha 	if (!before(start_seq, end_seq))
1025ad2b9b0fSPriyaranjan Jha 		return 0;
1026ad2b9b0fSPriyaranjan Jha 
1027a71d77e6SPriyaranjan Jha 	seq_len = end_seq - start_seq;
1028ad2b9b0fSPriyaranjan Jha 	/* Dubious DSACK: DSACKed range greater than maximum advertised rwnd */
1029ad2b9b0fSPriyaranjan Jha 	if (seq_len > tp->max_window)
1030ad2b9b0fSPriyaranjan Jha 		return 0;
1031a71d77e6SPriyaranjan Jha 	if (seq_len > tp->mss_cache)
1032a71d77e6SPriyaranjan Jha 		dup_segs = DIV_ROUND_UP(seq_len, tp->mss_cache);
103363f367d9SYuchung Cheng 	else if (tp->tlp_high_seq && tp->tlp_high_seq == end_seq)
103463f367d9SYuchung Cheng 		state->flag |= FLAG_DSACK_TLP;
1035ad2b9b0fSPriyaranjan Jha 
1036ad2b9b0fSPriyaranjan Jha 	tp->dsack_dups += dup_segs;
1037ad2b9b0fSPriyaranjan Jha 	/* Skip the DSACK if dup segs weren't retransmitted by sender */
1038ad2b9b0fSPriyaranjan Jha 	if (tp->dsack_dups > tp->total_retrans)
1039ad2b9b0fSPriyaranjan Jha 		return 0;
1040a71d77e6SPriyaranjan Jha 
1041ab56222aSVijay Subramanian 	tp->rx_opt.sack_ok |= TCP_DSACK_SEEN;
1042a657db03SNeal Cardwell 	/* We increase the RACK ordering window in rounds where we receive
1043a657db03SNeal Cardwell 	 * DSACKs that may have been due to reordering causing RACK to trigger
1044a657db03SNeal Cardwell 	 * a spurious fast recovery. Thus RACK ignores DSACKs that happen
1045a657db03SNeal Cardwell 	 * without having seen reordering, or that match TLP probes (TLP
1046a657db03SNeal Cardwell 	 * is timer-driven, not triggered by RACK).
1047a657db03SNeal Cardwell 	 */
1048a657db03SNeal Cardwell 	if (tp->reord_seen && !(state->flag & FLAG_DSACK_TLP))
10491f255691SPriyaranjan Jha 		tp->rack.dsack_seen = 1;
1050a71d77e6SPriyaranjan Jha 
1051a71d77e6SPriyaranjan Jha 	state->flag |= FLAG_DSACKING_ACK;
1052a71d77e6SPriyaranjan Jha 	/* A spurious retransmission is delivered */
1053a71d77e6SPriyaranjan Jha 	state->sack_delivered += dup_segs;
1054a71d77e6SPriyaranjan Jha 
1055a71d77e6SPriyaranjan Jha 	return dup_segs;
1056e60402d0SIlpo Järvinen }
1057e60402d0SIlpo Järvinen 
1058737ff314SYuchung Cheng /* It's reordering when higher sequence was delivered (i.e. sacked) before
1059737ff314SYuchung Cheng  * some lower never-retransmitted sequence ("low_seq"). The maximum reordering
1060737ff314SYuchung Cheng  * distance is approximated in full-mss packet distance ("reordering").
1061737ff314SYuchung Cheng  */
tcp_check_sack_reordering(struct sock * sk,const u32 low_seq,const int ts)1062737ff314SYuchung Cheng static void tcp_check_sack_reordering(struct sock *sk, const u32 low_seq,
10636687e988SArnaldo Carvalho de Melo 				      const int ts)
10641da177e4SLinus Torvalds {
10656687e988SArnaldo Carvalho de Melo 	struct tcp_sock *tp = tcp_sk(sk);
1066737ff314SYuchung Cheng 	const u32 mss = tp->mss_cache;
1067737ff314SYuchung Cheng 	u32 fack, metric;
106840b215e5SPavel Emelyanov 
1069737ff314SYuchung Cheng 	fack = tcp_highest_sack_seq(tp);
1070737ff314SYuchung Cheng 	if (!before(low_seq, fack))
10716f5b24eeSSoheil Hassas Yeganeh 		return;
10726f5b24eeSSoheil Hassas Yeganeh 
1073737ff314SYuchung Cheng 	metric = fack - low_seq;
1074737ff314SYuchung Cheng 	if ((metric > tp->reordering * mss) && mss) {
10751da177e4SLinus Torvalds #if FASTRETRANS_DEBUG > 1
107691df42beSJoe Perches 		pr_debug("Disorder%d %d %u f%u s%u rr%d\n",
10776687e988SArnaldo Carvalho de Melo 			 tp->rx_opt.sack_ok, inet_csk(sk)->icsk_ca_state,
10781da177e4SLinus Torvalds 			 tp->reordering,
1079737ff314SYuchung Cheng 			 0,
10801da177e4SLinus Torvalds 			 tp->sacked_out,
10811da177e4SLinus Torvalds 			 tp->undo_marker ? tp->undo_retrans : 0);
10821da177e4SLinus Torvalds #endif
1083737ff314SYuchung Cheng 		tp->reordering = min_t(u32, (metric + mss - 1) / mss,
1084a11e5b3eSKuniyuki Iwashima 				       READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_max_reordering));
10851da177e4SLinus Torvalds 	}
1086eed530b6SYuchung Cheng 
10872d2517eeSYuchung Cheng 	/* This exciting event is worth to be remembered. 8) */
10887ec65372SWei Wang 	tp->reord_seen++;
1089737ff314SYuchung Cheng 	NET_INC_STATS(sock_net(sk),
1090737ff314SYuchung Cheng 		      ts ? LINUX_MIB_TCPTSREORDER : LINUX_MIB_TCPSACKREORDER);
10911da177e4SLinus Torvalds }
10921da177e4SLinus Torvalds 
109368698970SYuchung Cheng  /* This must be called before lost_out or retrans_out are updated
109468698970SYuchung Cheng   * on a new loss, because we want to know if all skbs previously
109568698970SYuchung Cheng   * known to be lost have already been retransmitted, indicating
109668698970SYuchung Cheng   * that this newly lost skb is our next skb to retransmit.
109768698970SYuchung Cheng   */
tcp_verify_retransmit_hint(struct tcp_sock * tp,struct sk_buff * skb)1098c8c213f2SIlpo Järvinen static void tcp_verify_retransmit_hint(struct tcp_sock *tp, struct sk_buff *skb)
1099c8c213f2SIlpo Järvinen {
1100e176b1baSPengcheng Yang 	if ((!tp->retransmit_skb_hint && tp->retrans_out >= tp->lost_out) ||
1101e176b1baSPengcheng Yang 	    (tp->retransmit_skb_hint &&
1102c8c213f2SIlpo Järvinen 	     before(TCP_SKB_CB(skb)->seq,
1103e176b1baSPengcheng Yang 		    TCP_SKB_CB(tp->retransmit_skb_hint)->seq)))
1104006f582cSIlpo Järvinen 		tp->retransmit_skb_hint = skb;
1105c8c213f2SIlpo Järvinen }
1106c8c213f2SIlpo Järvinen 
11079cd8b6c9SYuchung Cheng /* Sum the number of packets on the wire we have marked as lost, and
11089cd8b6c9SYuchung Cheng  * notify the congestion control module that the given skb was marked lost.
11099cd8b6c9SYuchung Cheng  */
tcp_notify_skb_loss_event(struct tcp_sock * tp,const struct sk_buff * skb)11109cd8b6c9SYuchung Cheng static void tcp_notify_skb_loss_event(struct tcp_sock *tp, const struct sk_buff *skb)
11119cd8b6c9SYuchung Cheng {
11129cd8b6c9SYuchung Cheng 	tp->lost += tcp_skb_pcount(skb);
11139cd8b6c9SYuchung Cheng }
11149cd8b6c9SYuchung Cheng 
tcp_mark_skb_lost(struct sock * sk,struct sk_buff * skb)1115fd214674SYuchung Cheng void tcp_mark_skb_lost(struct sock *sk, struct sk_buff *skb)
1116fd214674SYuchung Cheng {
111768698970SYuchung Cheng 	__u8 sacked = TCP_SKB_CB(skb)->sacked;
1118fd214674SYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
1119fd214674SYuchung Cheng 
112068698970SYuchung Cheng 	if (sacked & TCPCB_SACKED_ACKED)
112168698970SYuchung Cheng 		return;
112268698970SYuchung Cheng 
112368698970SYuchung Cheng 	tcp_verify_retransmit_hint(tp, skb);
112468698970SYuchung Cheng 	if (sacked & TCPCB_LOST) {
112568698970SYuchung Cheng 		if (sacked & TCPCB_SACKED_RETRANS) {
1126fd214674SYuchung Cheng 			/* Account for retransmits that are lost again */
1127fd214674SYuchung Cheng 			TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
1128fd214674SYuchung Cheng 			tp->retrans_out -= tcp_skb_pcount(skb);
1129fd214674SYuchung Cheng 			NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPLOSTRETRANSMIT,
1130fd214674SYuchung Cheng 				      tcp_skb_pcount(skb));
11319cd8b6c9SYuchung Cheng 			tcp_notify_skb_loss_event(tp, skb);
1132fd214674SYuchung Cheng 		}
113368698970SYuchung Cheng 	} else {
113468698970SYuchung Cheng 		tp->lost_out += tcp_skb_pcount(skb);
113568698970SYuchung Cheng 		TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
11369cd8b6c9SYuchung Cheng 		tcp_notify_skb_loss_event(tp, skb);
1137fd214674SYuchung Cheng 	}
11380682e690SNeal Cardwell }
11390682e690SNeal Cardwell 
1140082d4fa9SYousuk Seung /* Updates the delivered and delivered_ce counts */
tcp_count_delivered(struct tcp_sock * tp,u32 delivered,bool ece_ack)1141082d4fa9SYousuk Seung static void tcp_count_delivered(struct tcp_sock *tp, u32 delivered,
1142082d4fa9SYousuk Seung 				bool ece_ack)
1143082d4fa9SYousuk Seung {
1144082d4fa9SYousuk Seung 	tp->delivered += delivered;
1145082d4fa9SYousuk Seung 	if (ece_ack)
1146082d4fa9SYousuk Seung 		tp->delivered_ce += delivered;
1147082d4fa9SYousuk Seung }
1148082d4fa9SYousuk Seung 
11491da177e4SLinus Torvalds /* This procedure tags the retransmission queue when SACKs arrive.
11501da177e4SLinus Torvalds  *
11511da177e4SLinus Torvalds  * We have three tag bits: SACKED(S), RETRANS(R) and LOST(L).
11521da177e4SLinus Torvalds  * Packets in queue with these bits set are counted in variables
11531da177e4SLinus Torvalds  * sacked_out, retrans_out and lost_out, correspondingly.
11541da177e4SLinus Torvalds  *
11551da177e4SLinus Torvalds  * Valid combinations are:
11561da177e4SLinus Torvalds  * Tag  InFlight	Description
11571da177e4SLinus Torvalds  * 0	1		- orig segment is in flight.
11581da177e4SLinus Torvalds  * S	0		- nothing flies, orig reached receiver.
11591da177e4SLinus Torvalds  * L	0		- nothing flies, orig lost by net.
11601da177e4SLinus Torvalds  * R	2		- both orig and retransmit are in flight.
11611da177e4SLinus Torvalds  * L|R	1		- orig is lost, retransmit is in flight.
11621da177e4SLinus Torvalds  * S|R  1		- orig reached receiver, retrans is still in flight.
11631da177e4SLinus Torvalds  * (L|S|R is logically valid, it could occur when L|R is sacked,
11641da177e4SLinus Torvalds  *  but it is equivalent to plain S and code short-curcuits it to S.
11651da177e4SLinus Torvalds  *  L|S is logically invalid, it would mean -1 packet in flight 8))
11661da177e4SLinus Torvalds  *
11671da177e4SLinus Torvalds  * These 6 states form finite state machine, controlled by the following events:
11681da177e4SLinus Torvalds  * 1. New ACK (+SACK) arrives. (tcp_sacktag_write_queue())
11691da177e4SLinus Torvalds  * 2. Retransmission. (tcp_retransmit_skb(), tcp_xmit_retransmit_queue())
1170974c1236SYuchung Cheng  * 3. Loss detection event of two flavors:
11711da177e4SLinus Torvalds  *	A. Scoreboard estimator decided the packet is lost.
11721da177e4SLinus Torvalds  *	   A'. Reno "three dupacks" marks head of queue lost.
1173974c1236SYuchung Cheng  *	B. SACK arrives sacking SND.NXT at the moment, when the
11741da177e4SLinus Torvalds  *	   segment was retransmitted.
11751da177e4SLinus Torvalds  * 4. D-SACK added new rule: D-SACK changes any tag to S.
11761da177e4SLinus Torvalds  *
11771da177e4SLinus Torvalds  * It is pleasant to note, that state diagram turns out to be commutative,
11781da177e4SLinus Torvalds  * so that we are allowed not to be bothered by order of our actions,
11791da177e4SLinus Torvalds  * when multiple events arrive simultaneously. (see the function below).
11801da177e4SLinus Torvalds  *
11811da177e4SLinus Torvalds  * Reordering detection.
11821da177e4SLinus Torvalds  * --------------------
11831da177e4SLinus Torvalds  * Reordering metric is maximal distance, which a packet can be displaced
11841da177e4SLinus Torvalds  * in packet stream. With SACKs we can estimate it:
11851da177e4SLinus Torvalds  *
11861da177e4SLinus Torvalds  * 1. SACK fills old hole and the corresponding segment was not
11871da177e4SLinus Torvalds  *    ever retransmitted -> reordering. Alas, we cannot use it
11881da177e4SLinus Torvalds  *    when segment was retransmitted.
11891da177e4SLinus Torvalds  * 2. The last flaw is solved with D-SACK. D-SACK arrives
11901da177e4SLinus Torvalds  *    for retransmitted and already SACKed segment -> reordering..
11911da177e4SLinus Torvalds  * Both of these heuristics are not used in Loss state, when we cannot
11921da177e4SLinus Torvalds  * account for retransmits accurately.
11935b3c9882SIlpo Järvinen  *
11945b3c9882SIlpo Järvinen  * SACK block validation.
11955b3c9882SIlpo Järvinen  * ----------------------
11965b3c9882SIlpo Järvinen  *
11975b3c9882SIlpo Järvinen  * SACK block range validation checks that the received SACK block fits to
11985b3c9882SIlpo Järvinen  * the expected sequence limits, i.e., it is between SND.UNA and SND.NXT.
11995b3c9882SIlpo Järvinen  * Note that SND.UNA is not included to the range though being valid because
12000e835331SIlpo Järvinen  * it means that the receiver is rather inconsistent with itself reporting
12010e835331SIlpo Järvinen  * SACK reneging when it should advance SND.UNA. Such SACK block this is
12020e835331SIlpo Järvinen  * perfectly valid, however, in light of RFC2018 which explicitly states
12030e835331SIlpo Järvinen  * that "SACK block MUST reflect the newest segment.  Even if the newest
12040e835331SIlpo Järvinen  * segment is going to be discarded ...", not that it looks very clever
12050e835331SIlpo Järvinen  * in case of head skb. Due to potentional receiver driven attacks, we
12060e835331SIlpo Järvinen  * choose to avoid immediate execution of a walk in write queue due to
12070e835331SIlpo Järvinen  * reneging and defer head skb's loss recovery to standard loss recovery
12080e835331SIlpo Järvinen  * procedure that will eventually trigger (nothing forbids us doing this).
12095b3c9882SIlpo Järvinen  *
12105b3c9882SIlpo Järvinen  * Implements also blockage to start_seq wrap-around. Problem lies in the
12115b3c9882SIlpo Järvinen  * fact that though start_seq (s) is before end_seq (i.e., not reversed),
12125b3c9882SIlpo Järvinen  * there's no guarantee that it will be before snd_nxt (n). The problem
12135b3c9882SIlpo Järvinen  * happens when start_seq resides between end_seq wrap (e_w) and snd_nxt
12145b3c9882SIlpo Järvinen  * wrap (s_w):
12155b3c9882SIlpo Järvinen  *
12165b3c9882SIlpo Järvinen  *         <- outs wnd ->                          <- wrapzone ->
12175b3c9882SIlpo Järvinen  *         u     e      n                         u_w   e_w  s n_w
12185b3c9882SIlpo Järvinen  *         |     |      |                          |     |   |  |
12195b3c9882SIlpo Järvinen  * |<------------+------+----- TCP seqno space --------------+---------->|
12205b3c9882SIlpo Järvinen  * ...-- <2^31 ->|                                           |<--------...
12215b3c9882SIlpo Järvinen  * ...---- >2^31 ------>|                                    |<--------...
12225b3c9882SIlpo Järvinen  *
12235b3c9882SIlpo Järvinen  * Current code wouldn't be vulnerable but it's better still to discard such
12245b3c9882SIlpo Järvinen  * crazy SACK blocks. Doing this check for start_seq alone closes somewhat
12255b3c9882SIlpo Järvinen  * similar case (end_seq after snd_nxt wrap) as earlier reversed check in
12265b3c9882SIlpo Järvinen  * snd_nxt wrap -> snd_una region will then become "well defined", i.e.,
12275b3c9882SIlpo Järvinen  * equal to the ideal case (infinite seqno space without wrap caused issues).
12285b3c9882SIlpo Järvinen  *
12295b3c9882SIlpo Järvinen  * With D-SACK the lower bound is extended to cover sequence space below
12305b3c9882SIlpo Järvinen  * SND.UNA down to undo_marker, which is the last point of interest. Yet
1231564262c1SRyousei Takano  * again, D-SACK block must not to go across snd_una (for the same reason as
12325b3c9882SIlpo Järvinen  * for the normal SACK blocks, explained above). But there all simplicity
12335b3c9882SIlpo Järvinen  * ends, TCP might receive valid D-SACKs below that. As long as they reside
12345b3c9882SIlpo Järvinen  * fully below undo_marker they do not affect behavior in anyway and can
12355b3c9882SIlpo Järvinen  * therefore be safely ignored. In rare cases (which are more or less
12365b3c9882SIlpo Järvinen  * theoretical ones), the D-SACK will nicely cross that boundary due to skb
12375b3c9882SIlpo Järvinen  * fragmentation and packet reordering past skb's retransmission. To consider
12385b3c9882SIlpo Järvinen  * them correctly, the acceptable range must be extended even more though
12395b3c9882SIlpo Järvinen  * the exact amount is rather hard to quantify. However, tp->max_window can
12405b3c9882SIlpo Järvinen  * be used as an exaggerated estimate.
12411da177e4SLinus Torvalds  */
tcp_is_sackblock_valid(struct tcp_sock * tp,bool is_dsack,u32 start_seq,u32 end_seq)1242a2a385d6SEric Dumazet static bool tcp_is_sackblock_valid(struct tcp_sock *tp, bool is_dsack,
12435b3c9882SIlpo Järvinen 				   u32 start_seq, u32 end_seq)
12445b3c9882SIlpo Järvinen {
12455b3c9882SIlpo Järvinen 	/* Too far in future, or reversed (interpretation is ambiguous) */
12465b3c9882SIlpo Järvinen 	if (after(end_seq, tp->snd_nxt) || !before(start_seq, end_seq))
1247a2a385d6SEric Dumazet 		return false;
12485b3c9882SIlpo Järvinen 
12495b3c9882SIlpo Järvinen 	/* Nasty start_seq wrap-around check (see comments above) */
12505b3c9882SIlpo Järvinen 	if (!before(start_seq, tp->snd_nxt))
1251a2a385d6SEric Dumazet 		return false;
12525b3c9882SIlpo Järvinen 
1253564262c1SRyousei Takano 	/* In outstanding window? ...This is valid exit for D-SACKs too.
12545b3c9882SIlpo Järvinen 	 * start_seq == snd_una is non-sensical (see comments above)
12555b3c9882SIlpo Järvinen 	 */
12565b3c9882SIlpo Järvinen 	if (after(start_seq, tp->snd_una))
1257a2a385d6SEric Dumazet 		return true;
12585b3c9882SIlpo Järvinen 
12595b3c9882SIlpo Järvinen 	if (!is_dsack || !tp->undo_marker)
1260a2a385d6SEric Dumazet 		return false;
12615b3c9882SIlpo Järvinen 
12625b3c9882SIlpo Järvinen 	/* ...Then it's D-SACK, and must reside below snd_una completely */
1263f779b2d6SZheng Yan 	if (after(end_seq, tp->snd_una))
1264a2a385d6SEric Dumazet 		return false;
12655b3c9882SIlpo Järvinen 
12665b3c9882SIlpo Järvinen 	if (!before(start_seq, tp->undo_marker))
1267a2a385d6SEric Dumazet 		return true;
12685b3c9882SIlpo Järvinen 
12695b3c9882SIlpo Järvinen 	/* Too old */
12705b3c9882SIlpo Järvinen 	if (!after(end_seq, tp->undo_marker))
1271a2a385d6SEric Dumazet 		return false;
12725b3c9882SIlpo Järvinen 
12735b3c9882SIlpo Järvinen 	/* Undo_marker boundary crossing (overestimates a lot). Known already:
12745b3c9882SIlpo Järvinen 	 *   start_seq < undo_marker and end_seq >= undo_marker.
12755b3c9882SIlpo Järvinen 	 */
12765b3c9882SIlpo Järvinen 	return !before(start_seq, end_seq - tp->max_window);
12775b3c9882SIlpo Järvinen }
12785b3c9882SIlpo Järvinen 
tcp_check_dsack(struct sock * sk,const struct sk_buff * ack_skb,struct tcp_sack_block_wire * sp,int num_sacks,u32 prior_snd_una,struct tcp_sacktag_state * state)1279a2a385d6SEric Dumazet static bool tcp_check_dsack(struct sock *sk, const struct sk_buff *ack_skb,
1280d06e021dSDavid S. Miller 			    struct tcp_sack_block_wire *sp, int num_sacks,
1281a71d77e6SPriyaranjan Jha 			    u32 prior_snd_una, struct tcp_sacktag_state *state)
1282d06e021dSDavid S. Miller {
12831ed83465SPavel Emelyanov 	struct tcp_sock *tp = tcp_sk(sk);
1284d3e2ce3bSHarvey Harrison 	u32 start_seq_0 = get_unaligned_be32(&sp[0].start_seq);
1285d3e2ce3bSHarvey Harrison 	u32 end_seq_0 = get_unaligned_be32(&sp[0].end_seq);
1286a71d77e6SPriyaranjan Jha 	u32 dup_segs;
1287d06e021dSDavid S. Miller 
1288d06e021dSDavid S. Miller 	if (before(start_seq_0, TCP_SKB_CB(ack_skb)->ack_seq)) {
1289c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKRECV);
1290d06e021dSDavid S. Miller 	} else if (num_sacks > 1) {
1291d3e2ce3bSHarvey Harrison 		u32 end_seq_1 = get_unaligned_be32(&sp[1].end_seq);
1292d3e2ce3bSHarvey Harrison 		u32 start_seq_1 = get_unaligned_be32(&sp[1].start_seq);
1293d06e021dSDavid S. Miller 
1294a71d77e6SPriyaranjan Jha 		if (after(end_seq_0, end_seq_1) || before(start_seq_0, start_seq_1))
1295a71d77e6SPriyaranjan Jha 			return false;
1296a71d77e6SPriyaranjan Jha 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKOFORECV);
1297a71d77e6SPriyaranjan Jha 	} else {
1298a71d77e6SPriyaranjan Jha 		return false;
1299d06e021dSDavid S. Miller 	}
1300a71d77e6SPriyaranjan Jha 
1301a71d77e6SPriyaranjan Jha 	dup_segs = tcp_dsack_seen(tp, start_seq_0, end_seq_0, state);
1302ad2b9b0fSPriyaranjan Jha 	if (!dup_segs) {	/* Skip dubious DSACK */
1303ad2b9b0fSPriyaranjan Jha 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKIGNOREDDUBIOUS);
1304ad2b9b0fSPriyaranjan Jha 		return false;
1305ad2b9b0fSPriyaranjan Jha 	}
1306ad2b9b0fSPriyaranjan Jha 
1307e3a5a1e8SPriyaranjan Jha 	NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPDSACKRECVSEGS, dup_segs);
1308d06e021dSDavid S. Miller 
1309d06e021dSDavid S. Miller 	/* D-SACK for already forgotten data... Do dumb counting. */
1310a71d77e6SPriyaranjan Jha 	if (tp->undo_marker && tp->undo_retrans > 0 &&
1311d06e021dSDavid S. Miller 	    !after(end_seq_0, prior_snd_una) &&
1312d06e021dSDavid S. Miller 	    after(end_seq_0, tp->undo_marker))
1313a71d77e6SPriyaranjan Jha 		tp->undo_retrans = max_t(int, 0, tp->undo_retrans - dup_segs);
1314d06e021dSDavid S. Miller 
1315a71d77e6SPriyaranjan Jha 	return true;
1316d06e021dSDavid S. Miller }
1317d06e021dSDavid S. Miller 
1318d1935942SIlpo Järvinen /* Check if skb is fully within the SACK block. In presence of GSO skbs,
1319d1935942SIlpo Järvinen  * the incoming SACK may not exactly match but we can find smaller MSS
1320d1935942SIlpo Järvinen  * aligned portion of it that matches. Therefore we might need to fragment
1321d1935942SIlpo Järvinen  * which may fail and creates some hassle (caller must handle error case
1322d1935942SIlpo Järvinen  * returns).
1323832d11c5SIlpo Järvinen  *
1324832d11c5SIlpo Järvinen  * FIXME: this could be merged to shift decision code
1325d1935942SIlpo Järvinen  */
tcp_match_skb_to_sack(struct sock * sk,struct sk_buff * skb,u32 start_seq,u32 end_seq)13260f79efdcSAdrian Bunk static int tcp_match_skb_to_sack(struct sock *sk, struct sk_buff *skb,
1327d1935942SIlpo Järvinen 				  u32 start_seq, u32 end_seq)
1328d1935942SIlpo Järvinen {
1329a2a385d6SEric Dumazet 	int err;
1330a2a385d6SEric Dumazet 	bool in_sack;
1331d1935942SIlpo Järvinen 	unsigned int pkt_len;
1332adb92db8SIlpo Järvinen 	unsigned int mss;
1333d1935942SIlpo Järvinen 
1334d1935942SIlpo Järvinen 	in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
1335d1935942SIlpo Järvinen 		  !before(end_seq, TCP_SKB_CB(skb)->end_seq);
1336d1935942SIlpo Järvinen 
1337d1935942SIlpo Järvinen 	if (tcp_skb_pcount(skb) > 1 && !in_sack &&
1338d1935942SIlpo Järvinen 	    after(TCP_SKB_CB(skb)->end_seq, start_seq)) {
1339adb92db8SIlpo Järvinen 		mss = tcp_skb_mss(skb);
1340d1935942SIlpo Järvinen 		in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq);
1341d1935942SIlpo Järvinen 
1342adb92db8SIlpo Järvinen 		if (!in_sack) {
1343d1935942SIlpo Järvinen 			pkt_len = start_seq - TCP_SKB_CB(skb)->seq;
1344adb92db8SIlpo Järvinen 			if (pkt_len < mss)
1345adb92db8SIlpo Järvinen 				pkt_len = mss;
1346adb92db8SIlpo Järvinen 		} else {
1347d1935942SIlpo Järvinen 			pkt_len = end_seq - TCP_SKB_CB(skb)->seq;
1348adb92db8SIlpo Järvinen 			if (pkt_len < mss)
1349adb92db8SIlpo Järvinen 				return -EINVAL;
1350adb92db8SIlpo Järvinen 		}
1351adb92db8SIlpo Järvinen 
1352adb92db8SIlpo Järvinen 		/* Round if necessary so that SACKs cover only full MSSes
1353adb92db8SIlpo Järvinen 		 * and/or the remaining small portion (if present)
1354adb92db8SIlpo Järvinen 		 */
1355adb92db8SIlpo Järvinen 		if (pkt_len > mss) {
1356adb92db8SIlpo Järvinen 			unsigned int new_len = (pkt_len / mss) * mss;
1357b451e5d2SYuchung Cheng 			if (!in_sack && new_len < pkt_len)
1358adb92db8SIlpo Järvinen 				new_len += mss;
1359adb92db8SIlpo Järvinen 			pkt_len = new_len;
1360adb92db8SIlpo Järvinen 		}
1361b451e5d2SYuchung Cheng 
1362b451e5d2SYuchung Cheng 		if (pkt_len >= skb->len && !in_sack)
1363b451e5d2SYuchung Cheng 			return 0;
1364b451e5d2SYuchung Cheng 
136575c119afSEric Dumazet 		err = tcp_fragment(sk, TCP_FRAG_IN_RTX_QUEUE, skb,
136675c119afSEric Dumazet 				   pkt_len, mss, GFP_ATOMIC);
1367d1935942SIlpo Järvinen 		if (err < 0)
1368d1935942SIlpo Järvinen 			return err;
1369d1935942SIlpo Järvinen 	}
1370d1935942SIlpo Järvinen 
1371d1935942SIlpo Järvinen 	return in_sack;
1372d1935942SIlpo Järvinen }
1373d1935942SIlpo Järvinen 
1374cc9a672eSNeal Cardwell /* Mark the given newly-SACKed range as such, adjusting counters and hints. */
tcp_sacktag_one(struct sock * sk,struct tcp_sacktag_state * state,u8 sacked,u32 start_seq,u32 end_seq,int dup_sack,int pcount,u64 xmit_time)1375cc9a672eSNeal Cardwell static u8 tcp_sacktag_one(struct sock *sk,
1376cc9a672eSNeal Cardwell 			  struct tcp_sacktag_state *state, u8 sacked,
1377cc9a672eSNeal Cardwell 			  u32 start_seq, u32 end_seq,
1378740b0f18SEric Dumazet 			  int dup_sack, int pcount,
13799a568de4SEric Dumazet 			  u64 xmit_time)
13809e10c47cSIlpo Järvinen {
13816859d494SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
13829e10c47cSIlpo Järvinen 
13839e10c47cSIlpo Järvinen 	/* Account D-SACK for retransmitted packet. */
13849e10c47cSIlpo Järvinen 	if (dup_sack && (sacked & TCPCB_RETRANS)) {
13856e08d5e3SYuchung Cheng 		if (tp->undo_marker && tp->undo_retrans > 0 &&
1386cc9a672eSNeal Cardwell 		    after(end_seq, tp->undo_marker))
13874f884f39Szhenggy 			tp->undo_retrans = max_t(int, 0, tp->undo_retrans - pcount);
1388737ff314SYuchung Cheng 		if ((sacked & TCPCB_SACKED_ACKED) &&
1389737ff314SYuchung Cheng 		    before(start_seq, state->reord))
1390737ff314SYuchung Cheng 				state->reord = start_seq;
13919e10c47cSIlpo Järvinen 	}
13929e10c47cSIlpo Järvinen 
13939e10c47cSIlpo Järvinen 	/* Nothing to do; acked frame is about to be dropped (was ACKed). */
1394cc9a672eSNeal Cardwell 	if (!after(end_seq, tp->snd_una))
1395a1197f5aSIlpo Järvinen 		return sacked;
13969e10c47cSIlpo Järvinen 
13979e10c47cSIlpo Järvinen 	if (!(sacked & TCPCB_SACKED_ACKED)) {
1398d2329f10SEric Dumazet 		tcp_rack_advance(tp, sacked, end_seq, xmit_time);
1399659a8ad5SYuchung Cheng 
14009e10c47cSIlpo Järvinen 		if (sacked & TCPCB_SACKED_RETRANS) {
14019e10c47cSIlpo Järvinen 			/* If the segment is not tagged as lost,
14029e10c47cSIlpo Järvinen 			 * we do not clear RETRANS, believing
14039e10c47cSIlpo Järvinen 			 * that retransmission is still in flight.
14049e10c47cSIlpo Järvinen 			 */
14059e10c47cSIlpo Järvinen 			if (sacked & TCPCB_LOST) {
1406a1197f5aSIlpo Järvinen 				sacked &= ~(TCPCB_LOST|TCPCB_SACKED_RETRANS);
1407f58b22fdSIlpo Järvinen 				tp->lost_out -= pcount;
1408f58b22fdSIlpo Järvinen 				tp->retrans_out -= pcount;
14099e10c47cSIlpo Järvinen 			}
14109e10c47cSIlpo Järvinen 		} else {
14119e10c47cSIlpo Järvinen 			if (!(sacked & TCPCB_RETRANS)) {
14129e10c47cSIlpo Järvinen 				/* New sack for not retransmitted frame,
14139e10c47cSIlpo Järvinen 				 * which was in hole. It is reordering.
14149e10c47cSIlpo Järvinen 				 */
1415cc9a672eSNeal Cardwell 				if (before(start_seq,
1416737ff314SYuchung Cheng 					   tcp_highest_sack_seq(tp)) &&
1417737ff314SYuchung Cheng 				    before(start_seq, state->reord))
1418737ff314SYuchung Cheng 					state->reord = start_seq;
1419737ff314SYuchung Cheng 
1420e33099f9SYuchung Cheng 				if (!after(end_seq, tp->high_seq))
1421e33099f9SYuchung Cheng 					state->flag |= FLAG_ORIG_SACK_ACKED;
14229a568de4SEric Dumazet 				if (state->first_sackt == 0)
14239a568de4SEric Dumazet 					state->first_sackt = xmit_time;
14249a568de4SEric Dumazet 				state->last_sackt = xmit_time;
14259e10c47cSIlpo Järvinen 			}
14269e10c47cSIlpo Järvinen 
14279e10c47cSIlpo Järvinen 			if (sacked & TCPCB_LOST) {
1428a1197f5aSIlpo Järvinen 				sacked &= ~TCPCB_LOST;
1429f58b22fdSIlpo Järvinen 				tp->lost_out -= pcount;
14309e10c47cSIlpo Järvinen 			}
14319e10c47cSIlpo Järvinen 		}
14329e10c47cSIlpo Järvinen 
1433a1197f5aSIlpo Järvinen 		sacked |= TCPCB_SACKED_ACKED;
1434a1197f5aSIlpo Järvinen 		state->flag |= FLAG_DATA_SACKED;
1435f58b22fdSIlpo Järvinen 		tp->sacked_out += pcount;
1436082d4fa9SYousuk Seung 		/* Out-of-order packets delivered */
1437f00394ceSYousuk Seung 		state->sack_delivered += pcount;
14389e10c47cSIlpo Järvinen 
14399e10c47cSIlpo Järvinen 		/* Lost marker hint past SACKed? Tweak RFC3517 cnt */
1440713bafeaSYuchung Cheng 		if (tp->lost_skb_hint &&
1441cc9a672eSNeal Cardwell 		    before(start_seq, TCP_SKB_CB(tp->lost_skb_hint)->seq))
1442f58b22fdSIlpo Järvinen 			tp->lost_cnt_hint += pcount;
14439e10c47cSIlpo Järvinen 	}
14449e10c47cSIlpo Järvinen 
14459e10c47cSIlpo Järvinen 	/* D-SACK. We can detect redundant retransmission in S|R and plain R
14469e10c47cSIlpo Järvinen 	 * frames and clear it. undo_retrans is decreased above, L|R frames
14479e10c47cSIlpo Järvinen 	 * are accounted above as well.
14489e10c47cSIlpo Järvinen 	 */
1449a1197f5aSIlpo Järvinen 	if (dup_sack && (sacked & TCPCB_SACKED_RETRANS)) {
1450a1197f5aSIlpo Järvinen 		sacked &= ~TCPCB_SACKED_RETRANS;
1451f58b22fdSIlpo Järvinen 		tp->retrans_out -= pcount;
14529e10c47cSIlpo Järvinen 	}
14539e10c47cSIlpo Järvinen 
1454a1197f5aSIlpo Järvinen 	return sacked;
14559e10c47cSIlpo Järvinen }
14569e10c47cSIlpo Järvinen 
1457daef52baSNeal Cardwell /* Shift newly-SACKed bytes from this skb to the immediately previous
1458daef52baSNeal Cardwell  * already-SACKed sk_buff. Mark the newly-SACKed bytes as such.
1459daef52baSNeal Cardwell  */
tcp_shifted_skb(struct sock * sk,struct sk_buff * prev,struct sk_buff * skb,struct tcp_sacktag_state * state,unsigned int pcount,int shifted,int mss,bool dup_sack)1460f3319816SEric Dumazet static bool tcp_shifted_skb(struct sock *sk, struct sk_buff *prev,
1461f3319816SEric Dumazet 			    struct sk_buff *skb,
1462a1197f5aSIlpo Järvinen 			    struct tcp_sacktag_state *state,
14639ec06ff5SIlpo Järvinen 			    unsigned int pcount, int shifted, int mss,
1464a2a385d6SEric Dumazet 			    bool dup_sack)
1465832d11c5SIlpo Järvinen {
1466832d11c5SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
1467daef52baSNeal Cardwell 	u32 start_seq = TCP_SKB_CB(skb)->seq;	/* start of newly-SACKed */
1468daef52baSNeal Cardwell 	u32 end_seq = start_seq + shifted;	/* end of newly-SACKed */
1469832d11c5SIlpo Järvinen 
1470832d11c5SIlpo Järvinen 	BUG_ON(!pcount);
1471832d11c5SIlpo Järvinen 
14724c90d3b3SNeal Cardwell 	/* Adjust counters and hints for the newly sacked sequence
14734c90d3b3SNeal Cardwell 	 * range but discard the return value since prev is already
14744c90d3b3SNeal Cardwell 	 * marked. We must tag the range first because the seq
14754c90d3b3SNeal Cardwell 	 * advancement below implicitly advances
14764c90d3b3SNeal Cardwell 	 * tcp_highest_sack_seq() when skb is highest_sack.
14774c90d3b3SNeal Cardwell 	 */
14784c90d3b3SNeal Cardwell 	tcp_sacktag_one(sk, state, TCP_SKB_CB(skb)->sacked,
147959c9af42SYuchung Cheng 			start_seq, end_seq, dup_sack, pcount,
14802fd66ffbSEric Dumazet 			tcp_skb_timestamp_us(skb));
1481b9f64820SYuchung Cheng 	tcp_rate_skb_delivered(sk, skb, state->rate);
14824c90d3b3SNeal Cardwell 
14834c90d3b3SNeal Cardwell 	if (skb == tp->lost_skb_hint)
14840af2a0d0SNeal Cardwell 		tp->lost_cnt_hint += pcount;
14850af2a0d0SNeal Cardwell 
1486832d11c5SIlpo Järvinen 	TCP_SKB_CB(prev)->end_seq += shifted;
1487832d11c5SIlpo Järvinen 	TCP_SKB_CB(skb)->seq += shifted;
1488832d11c5SIlpo Järvinen 
1489cd7d8498SEric Dumazet 	tcp_skb_pcount_add(prev, pcount);
14903b4929f6SEric Dumazet 	WARN_ON_ONCE(tcp_skb_pcount(skb) < pcount);
1491cd7d8498SEric Dumazet 	tcp_skb_pcount_add(skb, -pcount);
1492832d11c5SIlpo Järvinen 
1493832d11c5SIlpo Järvinen 	/* When we're adding to gso_segs == 1, gso_size will be zero,
1494832d11c5SIlpo Järvinen 	 * in theory this shouldn't be necessary but as long as DSACK
1495832d11c5SIlpo Järvinen 	 * code can come after this skb later on it's better to keep
1496832d11c5SIlpo Järvinen 	 * setting gso_size to something.
1497832d11c5SIlpo Järvinen 	 */
1498f69ad292SEric Dumazet 	if (!TCP_SKB_CB(prev)->tcp_gso_size)
1499f69ad292SEric Dumazet 		TCP_SKB_CB(prev)->tcp_gso_size = mss;
1500832d11c5SIlpo Järvinen 
1501832d11c5SIlpo Järvinen 	/* CHECKME: To clear or not to clear? Mimics normal skb currently */
150251466a75SEric Dumazet 	if (tcp_skb_pcount(skb) <= 1)
1503f69ad292SEric Dumazet 		TCP_SKB_CB(skb)->tcp_gso_size = 0;
1504832d11c5SIlpo Järvinen 
1505832d11c5SIlpo Järvinen 	/* Difference in this won't matter, both ACKed by the same cumul. ACK */
1506832d11c5SIlpo Järvinen 	TCP_SKB_CB(prev)->sacked |= (TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS);
1507832d11c5SIlpo Järvinen 
1508832d11c5SIlpo Järvinen 	if (skb->len > 0) {
1509832d11c5SIlpo Järvinen 		BUG_ON(!tcp_skb_pcount(skb));
1510c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKSHIFTED);
1511a2a385d6SEric Dumazet 		return false;
1512832d11c5SIlpo Järvinen 	}
1513832d11c5SIlpo Järvinen 
1514832d11c5SIlpo Järvinen 	/* Whole SKB was eaten :-) */
1515832d11c5SIlpo Järvinen 
151692ee76b6SIlpo Järvinen 	if (skb == tp->retransmit_skb_hint)
151792ee76b6SIlpo Järvinen 		tp->retransmit_skb_hint = prev;
151892ee76b6SIlpo Järvinen 	if (skb == tp->lost_skb_hint) {
151992ee76b6SIlpo Järvinen 		tp->lost_skb_hint = prev;
152092ee76b6SIlpo Järvinen 		tp->lost_cnt_hint -= tcp_skb_pcount(prev);
152192ee76b6SIlpo Järvinen 	}
152292ee76b6SIlpo Järvinen 
15235e8a402fSEric Dumazet 	TCP_SKB_CB(prev)->tcp_flags |= TCP_SKB_CB(skb)->tcp_flags;
1524a643b5d4SMartin KaFai Lau 	TCP_SKB_CB(prev)->eor = TCP_SKB_CB(skb)->eor;
15255e8a402fSEric Dumazet 	if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
15265e8a402fSEric Dumazet 		TCP_SKB_CB(prev)->end_seq++;
15275e8a402fSEric Dumazet 
1528832d11c5SIlpo Järvinen 	if (skb == tcp_highest_sack(sk))
1529832d11c5SIlpo Järvinen 		tcp_advance_highest_sack(sk, skb);
1530832d11c5SIlpo Järvinen 
1531cfea5a68SMartin KaFai Lau 	tcp_skb_collapse_tstamp(prev, skb);
15329a568de4SEric Dumazet 	if (unlikely(TCP_SKB_CB(prev)->tx.delivered_mstamp))
15339a568de4SEric Dumazet 		TCP_SKB_CB(prev)->tx.delivered_mstamp = 0;
1534b9f64820SYuchung Cheng 
153575c119afSEric Dumazet 	tcp_rtx_queue_unlink_and_free(skb, sk);
1536832d11c5SIlpo Järvinen 
1537c10d9310SEric Dumazet 	NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKMERGED);
1538111cc8b9SIlpo Järvinen 
1539a2a385d6SEric Dumazet 	return true;
1540832d11c5SIlpo Järvinen }
1541832d11c5SIlpo Järvinen 
1542832d11c5SIlpo Järvinen /* I wish gso_size would have a bit more sane initialization than
1543832d11c5SIlpo Järvinen  * something-or-zero which complicates things
1544832d11c5SIlpo Järvinen  */
tcp_skb_seglen(const struct sk_buff * skb)1545cf533ea5SEric Dumazet static int tcp_skb_seglen(const struct sk_buff *skb)
1546832d11c5SIlpo Järvinen {
1547775ffabfSIlpo Järvinen 	return tcp_skb_pcount(skb) == 1 ? skb->len : tcp_skb_mss(skb);
1548832d11c5SIlpo Järvinen }
1549832d11c5SIlpo Järvinen 
1550832d11c5SIlpo Järvinen /* Shifting pages past head area doesn't work */
skb_can_shift(const struct sk_buff * skb)1551cf533ea5SEric Dumazet static int skb_can_shift(const struct sk_buff *skb)
1552832d11c5SIlpo Järvinen {
1553832d11c5SIlpo Järvinen 	return !skb_headlen(skb) && skb_is_nonlinear(skb);
1554832d11c5SIlpo Järvinen }
1555832d11c5SIlpo Järvinen 
tcp_skb_shift(struct sk_buff * to,struct sk_buff * from,int pcount,int shiftlen)15563b4929f6SEric Dumazet int tcp_skb_shift(struct sk_buff *to, struct sk_buff *from,
15573b4929f6SEric Dumazet 		  int pcount, int shiftlen)
15583b4929f6SEric Dumazet {
15593b4929f6SEric Dumazet 	/* TCP min gso_size is 8 bytes (TCP_MIN_GSO_SIZE)
15603b4929f6SEric Dumazet 	 * Since TCP_SKB_CB(skb)->tcp_gso_segs is 16 bits, we need
15613b4929f6SEric Dumazet 	 * to make sure not storing more than 65535 * 8 bytes per skb,
15623b4929f6SEric Dumazet 	 * even if current MSS is bigger.
15633b4929f6SEric Dumazet 	 */
15643b4929f6SEric Dumazet 	if (unlikely(to->len + shiftlen >= 65535 * TCP_MIN_GSO_SIZE))
15653b4929f6SEric Dumazet 		return 0;
15663b4929f6SEric Dumazet 	if (unlikely(tcp_skb_pcount(to) + pcount > 65535))
15673b4929f6SEric Dumazet 		return 0;
15683b4929f6SEric Dumazet 	return skb_shift(to, from, shiftlen);
15693b4929f6SEric Dumazet }
15703b4929f6SEric Dumazet 
1571832d11c5SIlpo Järvinen /* Try collapsing SACK blocks spanning across multiple skbs to a single
1572832d11c5SIlpo Järvinen  * skb.
1573832d11c5SIlpo Järvinen  */
tcp_shift_skb_data(struct sock * sk,struct sk_buff * skb,struct tcp_sacktag_state * state,u32 start_seq,u32 end_seq,bool dup_sack)1574832d11c5SIlpo Järvinen static struct sk_buff *tcp_shift_skb_data(struct sock *sk, struct sk_buff *skb,
1575a1197f5aSIlpo Järvinen 					  struct tcp_sacktag_state *state,
1576832d11c5SIlpo Järvinen 					  u32 start_seq, u32 end_seq,
1577a2a385d6SEric Dumazet 					  bool dup_sack)
1578832d11c5SIlpo Järvinen {
1579832d11c5SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
1580832d11c5SIlpo Järvinen 	struct sk_buff *prev;
1581832d11c5SIlpo Järvinen 	int mss;
1582832d11c5SIlpo Järvinen 	int pcount = 0;
1583832d11c5SIlpo Järvinen 	int len;
1584832d11c5SIlpo Järvinen 	int in_sack;
1585832d11c5SIlpo Järvinen 
1586832d11c5SIlpo Järvinen 	/* Normally R but no L won't result in plain S */
1587832d11c5SIlpo Järvinen 	if (!dup_sack &&
15889969ca5fSIlpo Järvinen 	    (TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_RETRANS)) == TCPCB_SACKED_RETRANS)
1589832d11c5SIlpo Järvinen 		goto fallback;
1590832d11c5SIlpo Järvinen 	if (!skb_can_shift(skb))
1591832d11c5SIlpo Järvinen 		goto fallback;
1592832d11c5SIlpo Järvinen 	/* This frame is about to be dropped (was ACKed). */
1593832d11c5SIlpo Järvinen 	if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una))
1594832d11c5SIlpo Järvinen 		goto fallback;
1595832d11c5SIlpo Järvinen 
1596832d11c5SIlpo Järvinen 	/* Can only happen with delayed DSACK + discard craziness */
159775c119afSEric Dumazet 	prev = skb_rb_prev(skb);
159875c119afSEric Dumazet 	if (!prev)
1599832d11c5SIlpo Järvinen 		goto fallback;
1600832d11c5SIlpo Järvinen 
1601832d11c5SIlpo Järvinen 	if ((TCP_SKB_CB(prev)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED)
1602832d11c5SIlpo Järvinen 		goto fallback;
1603832d11c5SIlpo Järvinen 
160485712484SMat Martineau 	if (!tcp_skb_can_collapse(prev, skb))
1605a643b5d4SMartin KaFai Lau 		goto fallback;
1606a643b5d4SMartin KaFai Lau 
1607832d11c5SIlpo Järvinen 	in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
1608832d11c5SIlpo Järvinen 		  !before(end_seq, TCP_SKB_CB(skb)->end_seq);
1609832d11c5SIlpo Järvinen 
1610832d11c5SIlpo Järvinen 	if (in_sack) {
1611832d11c5SIlpo Järvinen 		len = skb->len;
1612832d11c5SIlpo Järvinen 		pcount = tcp_skb_pcount(skb);
1613775ffabfSIlpo Järvinen 		mss = tcp_skb_seglen(skb);
1614832d11c5SIlpo Järvinen 
1615832d11c5SIlpo Järvinen 		/* TODO: Fix DSACKs to not fragment already SACKed and we can
1616832d11c5SIlpo Järvinen 		 * drop this restriction as unnecessary
1617832d11c5SIlpo Järvinen 		 */
1618775ffabfSIlpo Järvinen 		if (mss != tcp_skb_seglen(prev))
1619832d11c5SIlpo Järvinen 			goto fallback;
1620832d11c5SIlpo Järvinen 	} else {
1621832d11c5SIlpo Järvinen 		if (!after(TCP_SKB_CB(skb)->end_seq, start_seq))
1622832d11c5SIlpo Järvinen 			goto noop;
1623832d11c5SIlpo Järvinen 		/* CHECKME: This is non-MSS split case only?, this will
1624832d11c5SIlpo Järvinen 		 * cause skipped skbs due to advancing loop btw, original
1625832d11c5SIlpo Järvinen 		 * has that feature too
1626832d11c5SIlpo Järvinen 		 */
1627832d11c5SIlpo Järvinen 		if (tcp_skb_pcount(skb) <= 1)
1628832d11c5SIlpo Järvinen 			goto noop;
1629832d11c5SIlpo Järvinen 
1630832d11c5SIlpo Järvinen 		in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq);
1631832d11c5SIlpo Järvinen 		if (!in_sack) {
1632832d11c5SIlpo Järvinen 			/* TODO: head merge to next could be attempted here
1633832d11c5SIlpo Järvinen 			 * if (!after(TCP_SKB_CB(skb)->end_seq, end_seq)),
1634832d11c5SIlpo Järvinen 			 * though it might not be worth of the additional hassle
1635832d11c5SIlpo Järvinen 			 *
1636832d11c5SIlpo Järvinen 			 * ...we can probably just fallback to what was done
1637832d11c5SIlpo Järvinen 			 * previously. We could try merging non-SACKed ones
1638832d11c5SIlpo Järvinen 			 * as well but it probably isn't going to buy off
1639832d11c5SIlpo Järvinen 			 * because later SACKs might again split them, and
1640832d11c5SIlpo Järvinen 			 * it would make skb timestamp tracking considerably
1641832d11c5SIlpo Järvinen 			 * harder problem.
1642832d11c5SIlpo Järvinen 			 */
1643832d11c5SIlpo Järvinen 			goto fallback;
1644832d11c5SIlpo Järvinen 		}
1645832d11c5SIlpo Järvinen 
1646832d11c5SIlpo Järvinen 		len = end_seq - TCP_SKB_CB(skb)->seq;
1647832d11c5SIlpo Järvinen 		BUG_ON(len < 0);
1648832d11c5SIlpo Järvinen 		BUG_ON(len > skb->len);
1649832d11c5SIlpo Järvinen 
1650832d11c5SIlpo Järvinen 		/* MSS boundaries should be honoured or else pcount will
1651832d11c5SIlpo Järvinen 		 * severely break even though it makes things bit trickier.
1652832d11c5SIlpo Järvinen 		 * Optimize common case to avoid most of the divides
1653832d11c5SIlpo Järvinen 		 */
1654832d11c5SIlpo Järvinen 		mss = tcp_skb_mss(skb);
1655832d11c5SIlpo Järvinen 
1656832d11c5SIlpo Järvinen 		/* TODO: Fix DSACKs to not fragment already SACKed and we can
1657832d11c5SIlpo Järvinen 		 * drop this restriction as unnecessary
1658832d11c5SIlpo Järvinen 		 */
1659775ffabfSIlpo Järvinen 		if (mss != tcp_skb_seglen(prev))
1660832d11c5SIlpo Järvinen 			goto fallback;
1661832d11c5SIlpo Järvinen 
1662832d11c5SIlpo Järvinen 		if (len == mss) {
1663832d11c5SIlpo Järvinen 			pcount = 1;
1664832d11c5SIlpo Järvinen 		} else if (len < mss) {
1665832d11c5SIlpo Järvinen 			goto noop;
1666832d11c5SIlpo Järvinen 		} else {
1667832d11c5SIlpo Järvinen 			pcount = len / mss;
1668832d11c5SIlpo Järvinen 			len = pcount * mss;
1669832d11c5SIlpo Järvinen 		}
1670832d11c5SIlpo Järvinen 	}
1671832d11c5SIlpo Järvinen 
16724648dc97SNeal Cardwell 	/* tcp_sacktag_one() won't SACK-tag ranges below snd_una */
16734648dc97SNeal Cardwell 	if (!after(TCP_SKB_CB(skb)->seq + len, tp->snd_una))
16744648dc97SNeal Cardwell 		goto fallback;
16754648dc97SNeal Cardwell 
16763b4929f6SEric Dumazet 	if (!tcp_skb_shift(prev, skb, pcount, len))
1677832d11c5SIlpo Järvinen 		goto fallback;
1678f3319816SEric Dumazet 	if (!tcp_shifted_skb(sk, prev, skb, state, pcount, len, mss, dup_sack))
1679832d11c5SIlpo Järvinen 		goto out;
1680832d11c5SIlpo Järvinen 
1681832d11c5SIlpo Järvinen 	/* Hole filled allows collapsing with the next as well, this is very
1682832d11c5SIlpo Järvinen 	 * useful when hole on every nth skb pattern happens
1683832d11c5SIlpo Järvinen 	 */
168475c119afSEric Dumazet 	skb = skb_rb_next(prev);
168575c119afSEric Dumazet 	if (!skb)
1686832d11c5SIlpo Järvinen 		goto out;
1687832d11c5SIlpo Järvinen 
1688f0bc52f3SIlpo Järvinen 	if (!skb_can_shift(skb) ||
1689f0bc52f3SIlpo Järvinen 	    ((TCP_SKB_CB(skb)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED) ||
1690775ffabfSIlpo Järvinen 	    (mss != tcp_skb_seglen(skb)))
1691832d11c5SIlpo Järvinen 		goto out;
1692832d11c5SIlpo Järvinen 
1693b67985beSEric Dumazet 	if (!tcp_skb_can_collapse(prev, skb))
1694b67985beSEric Dumazet 		goto out;
1695832d11c5SIlpo Järvinen 	len = skb->len;
16963b4929f6SEric Dumazet 	pcount = tcp_skb_pcount(skb);
16973b4929f6SEric Dumazet 	if (tcp_skb_shift(prev, skb, pcount, len))
16983b4929f6SEric Dumazet 		tcp_shifted_skb(sk, prev, skb, state, pcount,
1699f3319816SEric Dumazet 				len, mss, 0);
1700832d11c5SIlpo Järvinen 
1701832d11c5SIlpo Järvinen out:
1702832d11c5SIlpo Järvinen 	return prev;
1703832d11c5SIlpo Järvinen 
1704832d11c5SIlpo Järvinen noop:
1705832d11c5SIlpo Järvinen 	return skb;
1706832d11c5SIlpo Järvinen 
1707832d11c5SIlpo Järvinen fallback:
1708c10d9310SEric Dumazet 	NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKSHIFTFALLBACK);
1709832d11c5SIlpo Järvinen 	return NULL;
1710832d11c5SIlpo Järvinen }
1711832d11c5SIlpo Järvinen 
tcp_sacktag_walk(struct sk_buff * skb,struct sock * sk,struct tcp_sack_block * next_dup,struct tcp_sacktag_state * state,u32 start_seq,u32 end_seq,bool dup_sack_in)171268f8353bSIlpo Järvinen static struct sk_buff *tcp_sacktag_walk(struct sk_buff *skb, struct sock *sk,
171368f8353bSIlpo Järvinen 					struct tcp_sack_block *next_dup,
1714a1197f5aSIlpo Järvinen 					struct tcp_sacktag_state *state,
171568f8353bSIlpo Järvinen 					u32 start_seq, u32 end_seq,
1716a2a385d6SEric Dumazet 					bool dup_sack_in)
171768f8353bSIlpo Järvinen {
1718832d11c5SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
1719832d11c5SIlpo Järvinen 	struct sk_buff *tmp;
1720832d11c5SIlpo Järvinen 
172175c119afSEric Dumazet 	skb_rbtree_walk_from(skb) {
172268f8353bSIlpo Järvinen 		int in_sack = 0;
1723a2a385d6SEric Dumazet 		bool dup_sack = dup_sack_in;
172468f8353bSIlpo Järvinen 
172568f8353bSIlpo Järvinen 		/* queue is in-order => we can short-circuit the walk early */
172668f8353bSIlpo Järvinen 		if (!before(TCP_SKB_CB(skb)->seq, end_seq))
172768f8353bSIlpo Järvinen 			break;
172868f8353bSIlpo Järvinen 
172900db4124SIan Morris 		if (next_dup  &&
173068f8353bSIlpo Järvinen 		    before(TCP_SKB_CB(skb)->seq, next_dup->end_seq)) {
173168f8353bSIlpo Järvinen 			in_sack = tcp_match_skb_to_sack(sk, skb,
173268f8353bSIlpo Järvinen 							next_dup->start_seq,
173368f8353bSIlpo Järvinen 							next_dup->end_seq);
173468f8353bSIlpo Järvinen 			if (in_sack > 0)
1735a2a385d6SEric Dumazet 				dup_sack = true;
173668f8353bSIlpo Järvinen 		}
173768f8353bSIlpo Järvinen 
1738832d11c5SIlpo Järvinen 		/* skb reference here is a bit tricky to get right, since
1739832d11c5SIlpo Järvinen 		 * shifting can eat and free both this skb and the next,
1740832d11c5SIlpo Järvinen 		 * so not even _safe variant of the loop is enough.
1741832d11c5SIlpo Järvinen 		 */
1742832d11c5SIlpo Järvinen 		if (in_sack <= 0) {
1743a1197f5aSIlpo Järvinen 			tmp = tcp_shift_skb_data(sk, skb, state,
1744a1197f5aSIlpo Järvinen 						 start_seq, end_seq, dup_sack);
174500db4124SIan Morris 			if (tmp) {
1746832d11c5SIlpo Järvinen 				if (tmp != skb) {
1747832d11c5SIlpo Järvinen 					skb = tmp;
1748832d11c5SIlpo Järvinen 					continue;
1749832d11c5SIlpo Järvinen 				}
1750832d11c5SIlpo Järvinen 
1751832d11c5SIlpo Järvinen 				in_sack = 0;
1752832d11c5SIlpo Järvinen 			} else {
1753832d11c5SIlpo Järvinen 				in_sack = tcp_match_skb_to_sack(sk, skb,
1754832d11c5SIlpo Järvinen 								start_seq,
1755056834d9SIlpo Järvinen 								end_seq);
1756832d11c5SIlpo Järvinen 			}
1757832d11c5SIlpo Järvinen 		}
1758832d11c5SIlpo Järvinen 
175968f8353bSIlpo Järvinen 		if (unlikely(in_sack < 0))
176068f8353bSIlpo Järvinen 			break;
176168f8353bSIlpo Järvinen 
1762832d11c5SIlpo Järvinen 		if (in_sack) {
1763cc9a672eSNeal Cardwell 			TCP_SKB_CB(skb)->sacked =
1764cc9a672eSNeal Cardwell 				tcp_sacktag_one(sk,
1765a1197f5aSIlpo Järvinen 						state,
1766cc9a672eSNeal Cardwell 						TCP_SKB_CB(skb)->sacked,
1767cc9a672eSNeal Cardwell 						TCP_SKB_CB(skb)->seq,
1768cc9a672eSNeal Cardwell 						TCP_SKB_CB(skb)->end_seq,
1769a1197f5aSIlpo Järvinen 						dup_sack,
177059c9af42SYuchung Cheng 						tcp_skb_pcount(skb),
17712fd66ffbSEric Dumazet 						tcp_skb_timestamp_us(skb));
1772b9f64820SYuchung Cheng 			tcp_rate_skb_delivered(sk, skb, state->rate);
1773e2080072SEric Dumazet 			if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)
1774e2080072SEric Dumazet 				list_del_init(&skb->tcp_tsorted_anchor);
177568f8353bSIlpo Järvinen 
1776832d11c5SIlpo Järvinen 			if (!before(TCP_SKB_CB(skb)->seq,
1777832d11c5SIlpo Järvinen 				    tcp_highest_sack_seq(tp)))
1778832d11c5SIlpo Järvinen 				tcp_advance_highest_sack(sk, skb);
1779832d11c5SIlpo Järvinen 		}
178068f8353bSIlpo Järvinen 	}
178168f8353bSIlpo Järvinen 	return skb;
178268f8353bSIlpo Järvinen }
178368f8353bSIlpo Järvinen 
tcp_sacktag_bsearch(struct sock * sk,u32 seq)17844bfabc46STaehee Yoo static struct sk_buff *tcp_sacktag_bsearch(struct sock *sk, u32 seq)
178575c119afSEric Dumazet {
178675c119afSEric Dumazet 	struct rb_node *parent, **p = &sk->tcp_rtx_queue.rb_node;
178775c119afSEric Dumazet 	struct sk_buff *skb;
178875c119afSEric Dumazet 
178975c119afSEric Dumazet 	while (*p) {
179075c119afSEric Dumazet 		parent = *p;
179175c119afSEric Dumazet 		skb = rb_to_skb(parent);
179275c119afSEric Dumazet 		if (before(seq, TCP_SKB_CB(skb)->seq)) {
179375c119afSEric Dumazet 			p = &parent->rb_left;
179475c119afSEric Dumazet 			continue;
179575c119afSEric Dumazet 		}
179675c119afSEric Dumazet 		if (!before(seq, TCP_SKB_CB(skb)->end_seq)) {
179775c119afSEric Dumazet 			p = &parent->rb_right;
179875c119afSEric Dumazet 			continue;
179975c119afSEric Dumazet 		}
180075c119afSEric Dumazet 		return skb;
180175c119afSEric Dumazet 	}
180275c119afSEric Dumazet 	return NULL;
180375c119afSEric Dumazet }
180475c119afSEric Dumazet 
tcp_sacktag_skip(struct sk_buff * skb,struct sock * sk,u32 skip_to_seq)180568f8353bSIlpo Järvinen static struct sk_buff *tcp_sacktag_skip(struct sk_buff *skb, struct sock *sk,
1806a1197f5aSIlpo Järvinen 					u32 skip_to_seq)
180768f8353bSIlpo Järvinen {
180875c119afSEric Dumazet 	if (skb && after(TCP_SKB_CB(skb)->seq, skip_to_seq))
180968f8353bSIlpo Järvinen 		return skb;
181075c119afSEric Dumazet 
18114bfabc46STaehee Yoo 	return tcp_sacktag_bsearch(sk, skip_to_seq);
181268f8353bSIlpo Järvinen }
181368f8353bSIlpo Järvinen 
tcp_maybe_skipping_dsack(struct sk_buff * skb,struct sock * sk,struct tcp_sack_block * next_dup,struct tcp_sacktag_state * state,u32 skip_to_seq)181468f8353bSIlpo Järvinen static struct sk_buff *tcp_maybe_skipping_dsack(struct sk_buff *skb,
181568f8353bSIlpo Järvinen 						struct sock *sk,
181668f8353bSIlpo Järvinen 						struct tcp_sack_block *next_dup,
1817a1197f5aSIlpo Järvinen 						struct tcp_sacktag_state *state,
1818a1197f5aSIlpo Järvinen 						u32 skip_to_seq)
181968f8353bSIlpo Järvinen {
182051456b29SIan Morris 	if (!next_dup)
182168f8353bSIlpo Järvinen 		return skb;
182268f8353bSIlpo Järvinen 
182368f8353bSIlpo Järvinen 	if (before(next_dup->start_seq, skip_to_seq)) {
18244bfabc46STaehee Yoo 		skb = tcp_sacktag_skip(skb, sk, next_dup->start_seq);
1825a1197f5aSIlpo Järvinen 		skb = tcp_sacktag_walk(skb, sk, NULL, state,
182668f8353bSIlpo Järvinen 				       next_dup->start_seq, next_dup->end_seq,
1827a1197f5aSIlpo Järvinen 				       1);
182868f8353bSIlpo Järvinen 	}
182968f8353bSIlpo Järvinen 
183068f8353bSIlpo Järvinen 	return skb;
183168f8353bSIlpo Järvinen }
183268f8353bSIlpo Järvinen 
tcp_sack_cache_ok(const struct tcp_sock * tp,const struct tcp_sack_block * cache)1833cf533ea5SEric Dumazet static int tcp_sack_cache_ok(const struct tcp_sock *tp, const struct tcp_sack_block *cache)
183468f8353bSIlpo Järvinen {
183568f8353bSIlpo Järvinen 	return cache < tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache);
183668f8353bSIlpo Järvinen }
183768f8353bSIlpo Järvinen 
18381da177e4SLinus Torvalds static int
tcp_sacktag_write_queue(struct sock * sk,const struct sk_buff * ack_skb,u32 prior_snd_una,struct tcp_sacktag_state * state)1839cf533ea5SEric Dumazet tcp_sacktag_write_queue(struct sock *sk, const struct sk_buff *ack_skb,
1840196da974SKenneth Klette Jonassen 			u32 prior_snd_una, struct tcp_sacktag_state *state)
18411da177e4SLinus Torvalds {
18421da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
1843cf533ea5SEric Dumazet 	const unsigned char *ptr = (skb_transport_header(ack_skb) +
18449c70220bSArnaldo Carvalho de Melo 				    TCP_SKB_CB(ack_skb)->sacked);
1845fd6dad61SIlpo Järvinen 	struct tcp_sack_block_wire *sp_wire = (struct tcp_sack_block_wire *)(ptr+2);
18464389ddedSAdam Langley 	struct tcp_sack_block sp[TCP_NUM_SACKS];
184768f8353bSIlpo Järvinen 	struct tcp_sack_block *cache;
184868f8353bSIlpo Järvinen 	struct sk_buff *skb;
18494389ddedSAdam Langley 	int num_sacks = min(TCP_NUM_SACKS, (ptr[1] - TCPOLEN_SACK_BASE) >> 3);
1850fd6dad61SIlpo Järvinen 	int used_sacks;
1851a2a385d6SEric Dumazet 	bool found_dup_sack = false;
185268f8353bSIlpo Järvinen 	int i, j;
1853fda03fbbSBaruch Even 	int first_sack_index;
18541da177e4SLinus Torvalds 
1855196da974SKenneth Klette Jonassen 	state->flag = 0;
1856737ff314SYuchung Cheng 	state->reord = tp->snd_nxt;
1857a1197f5aSIlpo Järvinen 
1858737ff314SYuchung Cheng 	if (!tp->sacked_out)
18596859d494SIlpo Järvinen 		tcp_highest_sack_reset(sk);
18601da177e4SLinus Torvalds 
18611ed83465SPavel Emelyanov 	found_dup_sack = tcp_check_dsack(sk, ack_skb, sp_wire,
1862a71d77e6SPriyaranjan Jha 					 num_sacks, prior_snd_una, state);
18636f74651aSBaruch Even 
18646f74651aSBaruch Even 	/* Eliminate too old ACKs, but take into
18656f74651aSBaruch Even 	 * account more or less fresh ones, they can
18666f74651aSBaruch Even 	 * contain valid SACK info.
18676f74651aSBaruch Even 	 */
18686f74651aSBaruch Even 	if (before(TCP_SKB_CB(ack_skb)->ack_seq, prior_snd_una - tp->max_window))
18696f74651aSBaruch Even 		return 0;
18706f74651aSBaruch Even 
187196a2d41aSIlpo Järvinen 	if (!tp->packets_out)
187296a2d41aSIlpo Järvinen 		goto out;
187396a2d41aSIlpo Järvinen 
1874fd6dad61SIlpo Järvinen 	used_sacks = 0;
1875fd6dad61SIlpo Järvinen 	first_sack_index = 0;
1876fd6dad61SIlpo Järvinen 	for (i = 0; i < num_sacks; i++) {
1877a2a385d6SEric Dumazet 		bool dup_sack = !i && found_dup_sack;
1878fd6dad61SIlpo Järvinen 
1879d3e2ce3bSHarvey Harrison 		sp[used_sacks].start_seq = get_unaligned_be32(&sp_wire[i].start_seq);
1880d3e2ce3bSHarvey Harrison 		sp[used_sacks].end_seq = get_unaligned_be32(&sp_wire[i].end_seq);
1881fd6dad61SIlpo Järvinen 
1882fd6dad61SIlpo Järvinen 		if (!tcp_is_sackblock_valid(tp, dup_sack,
1883fd6dad61SIlpo Järvinen 					    sp[used_sacks].start_seq,
1884fd6dad61SIlpo Järvinen 					    sp[used_sacks].end_seq)) {
188540b215e5SPavel Emelyanov 			int mib_idx;
188640b215e5SPavel Emelyanov 
1887fd6dad61SIlpo Järvinen 			if (dup_sack) {
1888fd6dad61SIlpo Järvinen 				if (!tp->undo_marker)
188940b215e5SPavel Emelyanov 					mib_idx = LINUX_MIB_TCPDSACKIGNOREDNOUNDO;
1890fd6dad61SIlpo Järvinen 				else
189140b215e5SPavel Emelyanov 					mib_idx = LINUX_MIB_TCPDSACKIGNOREDOLD;
1892fd6dad61SIlpo Järvinen 			} else {
1893fd6dad61SIlpo Järvinen 				/* Don't count olds caused by ACK reordering */
1894fd6dad61SIlpo Järvinen 				if ((TCP_SKB_CB(ack_skb)->ack_seq != tp->snd_una) &&
1895fd6dad61SIlpo Järvinen 				    !after(sp[used_sacks].end_seq, tp->snd_una))
1896fd6dad61SIlpo Järvinen 					continue;
189740b215e5SPavel Emelyanov 				mib_idx = LINUX_MIB_TCPSACKDISCARD;
1898fd6dad61SIlpo Järvinen 			}
189940b215e5SPavel Emelyanov 
1900c10d9310SEric Dumazet 			NET_INC_STATS(sock_net(sk), mib_idx);
1901fd6dad61SIlpo Järvinen 			if (i == 0)
1902fd6dad61SIlpo Järvinen 				first_sack_index = -1;
1903fd6dad61SIlpo Järvinen 			continue;
1904fd6dad61SIlpo Järvinen 		}
1905fd6dad61SIlpo Järvinen 
1906fd6dad61SIlpo Järvinen 		/* Ignore very old stuff early */
1907c9655008SPengcheng Yang 		if (!after(sp[used_sacks].end_seq, prior_snd_una)) {
1908c9655008SPengcheng Yang 			if (i == 0)
1909c9655008SPengcheng Yang 				first_sack_index = -1;
1910fd6dad61SIlpo Järvinen 			continue;
1911c9655008SPengcheng Yang 		}
1912fd6dad61SIlpo Järvinen 
1913fd6dad61SIlpo Järvinen 		used_sacks++;
1914fd6dad61SIlpo Järvinen 	}
1915fd6dad61SIlpo Järvinen 
19166a438bbeSStephen Hemminger 	/* order SACK blocks to allow in order walk of the retrans queue */
1917fd6dad61SIlpo Järvinen 	for (i = used_sacks - 1; i > 0; i--) {
19186a438bbeSStephen Hemminger 		for (j = 0; j < i; j++) {
1919fd6dad61SIlpo Järvinen 			if (after(sp[j].start_seq, sp[j + 1].start_seq)) {
1920a0bffffcSIlpo Järvinen 				swap(sp[j], sp[j + 1]);
1921fda03fbbSBaruch Even 
1922fda03fbbSBaruch Even 				/* Track where the first SACK block goes to */
1923fda03fbbSBaruch Even 				if (j == first_sack_index)
1924fda03fbbSBaruch Even 					first_sack_index = j + 1;
19256a438bbeSStephen Hemminger 			}
19266a438bbeSStephen Hemminger 		}
19276a438bbeSStephen Hemminger 	}
19286a438bbeSStephen Hemminger 
192975c119afSEric Dumazet 	state->mss_now = tcp_current_mss(sk);
193075c119afSEric Dumazet 	skb = NULL;
193168f8353bSIlpo Järvinen 	i = 0;
193268f8353bSIlpo Järvinen 
193368f8353bSIlpo Järvinen 	if (!tp->sacked_out) {
193468f8353bSIlpo Järvinen 		/* It's already past, so skip checking against it */
193568f8353bSIlpo Järvinen 		cache = tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache);
193668f8353bSIlpo Järvinen 	} else {
193768f8353bSIlpo Järvinen 		cache = tp->recv_sack_cache;
193868f8353bSIlpo Järvinen 		/* Skip empty blocks in at head of the cache */
193968f8353bSIlpo Järvinen 		while (tcp_sack_cache_ok(tp, cache) && !cache->start_seq &&
194068f8353bSIlpo Järvinen 		       !cache->end_seq)
194168f8353bSIlpo Järvinen 			cache++;
1942fda03fbbSBaruch Even 	}
1943fda03fbbSBaruch Even 
194468f8353bSIlpo Järvinen 	while (i < used_sacks) {
1945fd6dad61SIlpo Järvinen 		u32 start_seq = sp[i].start_seq;
1946fd6dad61SIlpo Järvinen 		u32 end_seq = sp[i].end_seq;
1947a2a385d6SEric Dumazet 		bool dup_sack = (found_dup_sack && (i == first_sack_index));
194868f8353bSIlpo Järvinen 		struct tcp_sack_block *next_dup = NULL;
1949e56d6cd6SIlpo Järvinen 
195068f8353bSIlpo Järvinen 		if (found_dup_sack && ((i + 1) == first_sack_index))
195168f8353bSIlpo Järvinen 			next_dup = &sp[i + 1];
19521da177e4SLinus Torvalds 
195368f8353bSIlpo Järvinen 		/* Skip too early cached blocks */
195468f8353bSIlpo Järvinen 		while (tcp_sack_cache_ok(tp, cache) &&
195568f8353bSIlpo Järvinen 		       !before(start_seq, cache->end_seq))
195668f8353bSIlpo Järvinen 			cache++;
19571da177e4SLinus Torvalds 
195868f8353bSIlpo Järvinen 		/* Can skip some work by looking recv_sack_cache? */
195968f8353bSIlpo Järvinen 		if (tcp_sack_cache_ok(tp, cache) && !dup_sack &&
196068f8353bSIlpo Järvinen 		    after(end_seq, cache->start_seq)) {
1961fe067e8aSDavid S. Miller 
196268f8353bSIlpo Järvinen 			/* Head todo? */
196368f8353bSIlpo Järvinen 			if (before(start_seq, cache->start_seq)) {
19644bfabc46STaehee Yoo 				skb = tcp_sacktag_skip(skb, sk, start_seq);
1965056834d9SIlpo Järvinen 				skb = tcp_sacktag_walk(skb, sk, next_dup,
1966196da974SKenneth Klette Jonassen 						       state,
1967056834d9SIlpo Järvinen 						       start_seq,
1968056834d9SIlpo Järvinen 						       cache->start_seq,
1969a1197f5aSIlpo Järvinen 						       dup_sack);
1970fda03fbbSBaruch Even 			}
19716a438bbeSStephen Hemminger 
197268f8353bSIlpo Järvinen 			/* Rest of the block already fully processed? */
197320de20beSIlpo Järvinen 			if (!after(end_seq, cache->end_seq))
197420de20beSIlpo Järvinen 				goto advance_sp;
197520de20beSIlpo Järvinen 
1976056834d9SIlpo Järvinen 			skb = tcp_maybe_skipping_dsack(skb, sk, next_dup,
1977196da974SKenneth Klette Jonassen 						       state,
1978a1197f5aSIlpo Järvinen 						       cache->end_seq);
197968f8353bSIlpo Järvinen 
198068f8353bSIlpo Järvinen 			/* ...tail remains todo... */
19816859d494SIlpo Järvinen 			if (tcp_highest_sack_seq(tp) == cache->end_seq) {
198220de20beSIlpo Järvinen 				/* ...but better entrypoint exists! */
19836859d494SIlpo Järvinen 				skb = tcp_highest_sack(sk);
198451456b29SIan Morris 				if (!skb)
19856859d494SIlpo Järvinen 					break;
198668f8353bSIlpo Järvinen 				cache++;
198768f8353bSIlpo Järvinen 				goto walk;
1988e56d6cd6SIlpo Järvinen 			}
1989e56d6cd6SIlpo Järvinen 
19904bfabc46STaehee Yoo 			skb = tcp_sacktag_skip(skb, sk, cache->end_seq);
199168f8353bSIlpo Järvinen 			/* Check overlap against next cached too (past this one already) */
199268f8353bSIlpo Järvinen 			cache++;
199368f8353bSIlpo Järvinen 			continue;
19941da177e4SLinus Torvalds 		}
1995fbd52eb2SIlpo Järvinen 
19966859d494SIlpo Järvinen 		if (!before(start_seq, tcp_highest_sack_seq(tp))) {
19976859d494SIlpo Järvinen 			skb = tcp_highest_sack(sk);
199851456b29SIan Morris 			if (!skb)
19996859d494SIlpo Järvinen 				break;
200068f8353bSIlpo Järvinen 		}
20014bfabc46STaehee Yoo 		skb = tcp_sacktag_skip(skb, sk, start_seq);
200268f8353bSIlpo Järvinen 
200368f8353bSIlpo Järvinen walk:
2004196da974SKenneth Klette Jonassen 		skb = tcp_sacktag_walk(skb, sk, next_dup, state,
2005a1197f5aSIlpo Järvinen 				       start_seq, end_seq, dup_sack);
200668f8353bSIlpo Järvinen 
200768f8353bSIlpo Järvinen advance_sp:
200868f8353bSIlpo Järvinen 		i++;
20091da177e4SLinus Torvalds 	}
20101da177e4SLinus Torvalds 
201168f8353bSIlpo Järvinen 	/* Clear the head of the cache sack blocks so we can skip it next time */
201268f8353bSIlpo Järvinen 	for (i = 0; i < ARRAY_SIZE(tp->recv_sack_cache) - used_sacks; i++) {
201368f8353bSIlpo Järvinen 		tp->recv_sack_cache[i].start_seq = 0;
201468f8353bSIlpo Järvinen 		tp->recv_sack_cache[i].end_seq = 0;
201568f8353bSIlpo Järvinen 	}
201668f8353bSIlpo Järvinen 	for (j = 0; j < used_sacks; j++)
201768f8353bSIlpo Järvinen 		tp->recv_sack_cache[i++] = sp[j];
201868f8353bSIlpo Järvinen 
2019737ff314SYuchung Cheng 	if (inet_csk(sk)->icsk_ca_state != TCP_CA_Loss || tp->undo_marker)
2020737ff314SYuchung Cheng 		tcp_check_sack_reordering(sk, state->reord, 0);
20211da177e4SLinus Torvalds 
20229dac8835SYuchung Cheng 	tcp_verify_left_out(tp);
202396a2d41aSIlpo Järvinen out:
202496a2d41aSIlpo Järvinen 
20251da177e4SLinus Torvalds #if FASTRETRANS_DEBUG > 0
2026547b792cSIlpo Järvinen 	WARN_ON((int)tp->sacked_out < 0);
2027547b792cSIlpo Järvinen 	WARN_ON((int)tp->lost_out < 0);
2028547b792cSIlpo Järvinen 	WARN_ON((int)tp->retrans_out < 0);
2029547b792cSIlpo Järvinen 	WARN_ON((int)tcp_packets_in_flight(tp) < 0);
20301da177e4SLinus Torvalds #endif
2031196da974SKenneth Klette Jonassen 	return state->flag;
20321da177e4SLinus Torvalds }
20331da177e4SLinus Torvalds 
2034882bebaaSIlpo Järvinen /* Limits sacked_out so that sum with lost_out isn't ever larger than
2035a2a385d6SEric Dumazet  * packets_out. Returns false if sacked_out adjustement wasn't necessary.
203630935cf4SIlpo Järvinen  */
tcp_limit_reno_sacked(struct tcp_sock * tp)2037a2a385d6SEric Dumazet static bool tcp_limit_reno_sacked(struct tcp_sock *tp)
20384ddf6676SIlpo Järvinen {
20394ddf6676SIlpo Järvinen 	u32 holes;
20404ddf6676SIlpo Järvinen 
20414ddf6676SIlpo Järvinen 	holes = max(tp->lost_out, 1U);
20424ddf6676SIlpo Järvinen 	holes = min(holes, tp->packets_out);
20434ddf6676SIlpo Järvinen 
20444ddf6676SIlpo Järvinen 	if ((tp->sacked_out + holes) > tp->packets_out) {
20454ddf6676SIlpo Järvinen 		tp->sacked_out = tp->packets_out - holes;
2046a2a385d6SEric Dumazet 		return true;
20474ddf6676SIlpo Järvinen 	}
2048a2a385d6SEric Dumazet 	return false;
2049882bebaaSIlpo Järvinen }
2050882bebaaSIlpo Järvinen 
2051882bebaaSIlpo Järvinen /* If we receive more dupacks than we expected counting segments
2052882bebaaSIlpo Järvinen  * in assumption of absent reordering, interpret this as reordering.
2053882bebaaSIlpo Järvinen  * The only another reason could be bug in receiver TCP.
2054882bebaaSIlpo Järvinen  */
tcp_check_reno_reordering(struct sock * sk,const int addend)2055882bebaaSIlpo Järvinen static void tcp_check_reno_reordering(struct sock *sk, const int addend)
2056882bebaaSIlpo Järvinen {
2057882bebaaSIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
2058737ff314SYuchung Cheng 
2059737ff314SYuchung Cheng 	if (!tcp_limit_reno_sacked(tp))
2060737ff314SYuchung Cheng 		return;
2061737ff314SYuchung Cheng 
2062737ff314SYuchung Cheng 	tp->reordering = min_t(u32, tp->packets_out + addend,
2063a11e5b3eSKuniyuki Iwashima 			       READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_max_reordering));
20647ec65372SWei Wang 	tp->reord_seen++;
2065737ff314SYuchung Cheng 	NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPRENOREORDER);
20664ddf6676SIlpo Järvinen }
20674ddf6676SIlpo Järvinen 
20684ddf6676SIlpo Järvinen /* Emulate SACKs for SACKless connection: account for a new dupack. */
20694ddf6676SIlpo Järvinen 
tcp_add_reno_sack(struct sock * sk,int num_dupack,bool ece_ack)2070c634e34fSYousuk Seung static void tcp_add_reno_sack(struct sock *sk, int num_dupack, bool ece_ack)
20714ddf6676SIlpo Järvinen {
207219119f29SEric Dumazet 	if (num_dupack) {
20734ddf6676SIlpo Järvinen 		struct tcp_sock *tp = tcp_sk(sk);
2074ddf1af6fSYuchung Cheng 		u32 prior_sacked = tp->sacked_out;
207519119f29SEric Dumazet 		s32 delivered;
2076ddf1af6fSYuchung Cheng 
207719119f29SEric Dumazet 		tp->sacked_out += num_dupack;
20784ddf6676SIlpo Järvinen 		tcp_check_reno_reordering(sk, 0);
207919119f29SEric Dumazet 		delivered = tp->sacked_out - prior_sacked;
208019119f29SEric Dumazet 		if (delivered > 0)
2081082d4fa9SYousuk Seung 			tcp_count_delivered(tp, delivered, ece_ack);
2082005903bcSIlpo Järvinen 		tcp_verify_left_out(tp);
20834ddf6676SIlpo Järvinen 	}
208419119f29SEric Dumazet }
20854ddf6676SIlpo Järvinen 
20864ddf6676SIlpo Järvinen /* Account for ACK, ACKing some data in Reno Recovery phase. */
20874ddf6676SIlpo Järvinen 
tcp_remove_reno_sacks(struct sock * sk,int acked,bool ece_ack)2088c634e34fSYousuk Seung static void tcp_remove_reno_sacks(struct sock *sk, int acked, bool ece_ack)
20894ddf6676SIlpo Järvinen {
20904ddf6676SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
20914ddf6676SIlpo Järvinen 
20924ddf6676SIlpo Järvinen 	if (acked > 0) {
20934ddf6676SIlpo Järvinen 		/* One ACK acked hole. The rest eat duplicate ACKs. */
2094082d4fa9SYousuk Seung 		tcp_count_delivered(tp, max_t(int, acked - tp->sacked_out, 1),
2095082d4fa9SYousuk Seung 				    ece_ack);
20964ddf6676SIlpo Järvinen 		if (acked - 1 >= tp->sacked_out)
20974ddf6676SIlpo Järvinen 			tp->sacked_out = 0;
20984ddf6676SIlpo Järvinen 		else
20994ddf6676SIlpo Järvinen 			tp->sacked_out -= acked - 1;
21004ddf6676SIlpo Järvinen 	}
21014ddf6676SIlpo Järvinen 	tcp_check_reno_reordering(sk, acked);
2102005903bcSIlpo Järvinen 	tcp_verify_left_out(tp);
21034ddf6676SIlpo Järvinen }
21044ddf6676SIlpo Järvinen 
tcp_reset_reno_sack(struct tcp_sock * tp)21054ddf6676SIlpo Järvinen static inline void tcp_reset_reno_sack(struct tcp_sock *tp)
21064ddf6676SIlpo Järvinen {
21074ddf6676SIlpo Järvinen 	tp->sacked_out = 0;
21084ddf6676SIlpo Järvinen }
21094ddf6676SIlpo Järvinen 
tcp_clear_retrans(struct tcp_sock * tp)2110989e04c5SYuchung Cheng void tcp_clear_retrans(struct tcp_sock *tp)
21111da177e4SLinus Torvalds {
21121da177e4SLinus Torvalds 	tp->retrans_out = 0;
21131da177e4SLinus Torvalds 	tp->lost_out = 0;
21141da177e4SLinus Torvalds 	tp->undo_marker = 0;
21156e08d5e3SYuchung Cheng 	tp->undo_retrans = -1;
21164cd82999SIlpo Järvinen 	tp->sacked_out = 0;
2117718c49f8SAananth V 	tp->rto_stamp = 0;
2118718c49f8SAananth V 	tp->total_rto = 0;
2119718c49f8SAananth V 	tp->total_rto_recoveries = 0;
2120718c49f8SAananth V 	tp->total_rto_time = 0;
21214cd82999SIlpo Järvinen }
21224cd82999SIlpo Järvinen 
tcp_init_undo(struct tcp_sock * tp)2123989e04c5SYuchung Cheng static inline void tcp_init_undo(struct tcp_sock *tp)
2124989e04c5SYuchung Cheng {
2125989e04c5SYuchung Cheng 	tp->undo_marker = tp->snd_una;
2126124886cfSNeal Cardwell 
2127989e04c5SYuchung Cheng 	/* Retransmission still in flight may cause DSACKs later. */
2128124886cfSNeal Cardwell 	/* First, account for regular retransmits in flight: */
2129124886cfSNeal Cardwell 	tp->undo_retrans = tp->retrans_out;
2130124886cfSNeal Cardwell 	/* Next, account for TLP retransmits in flight: */
2131124886cfSNeal Cardwell 	if (tp->tlp_high_seq && tp->tlp_retrans)
2132124886cfSNeal Cardwell 		tp->undo_retrans++;
2133124886cfSNeal Cardwell 	/* Finally, avoid 0, because undo_retrans==0 means "can undo now": */
2134124886cfSNeal Cardwell 	if (!tp->undo_retrans)
2135124886cfSNeal Cardwell 		tp->undo_retrans = -1;
2136989e04c5SYuchung Cheng }
2137989e04c5SYuchung Cheng 
tcp_is_rack(const struct sock * sk)2138b8fef65aSYuchung Cheng static bool tcp_is_rack(const struct sock *sk)
2139b8fef65aSYuchung Cheng {
2140e7d2ef83SKuniyuki Iwashima 	return READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_recovery) &
2141e7d2ef83SKuniyuki Iwashima 		TCP_RACK_LOSS_DETECTION;
2142b8fef65aSYuchung Cheng }
2143b8fef65aSYuchung Cheng 
21442ad55f56SYuchung Cheng /* If we detect SACK reneging, forget all SACK information
21451da177e4SLinus Torvalds  * and reset tags completely, otherwise preserve SACKs. If receiver
21461da177e4SLinus Torvalds  * dropped its ofo queue, we will know this due to reneging detection.
21471da177e4SLinus Torvalds  */
tcp_timeout_mark_lost(struct sock * sk)21482ad55f56SYuchung Cheng static void tcp_timeout_mark_lost(struct sock *sk)
21492ad55f56SYuchung Cheng {
21502ad55f56SYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
215156f8c5d7SYuchung Cheng 	struct sk_buff *skb, *head;
21522ad55f56SYuchung Cheng 	bool is_reneg;			/* is receiver reneging on SACKs? */
21532ad55f56SYuchung Cheng 
215456f8c5d7SYuchung Cheng 	head = tcp_rtx_queue_head(sk);
215556f8c5d7SYuchung Cheng 	is_reneg = head && (TCP_SKB_CB(head)->sacked & TCPCB_SACKED_ACKED);
21562ad55f56SYuchung Cheng 	if (is_reneg) {
21572ad55f56SYuchung Cheng 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPSACKRENEGING);
21582ad55f56SYuchung Cheng 		tp->sacked_out = 0;
21592ad55f56SYuchung Cheng 		/* Mark SACK reneging until we recover from this loss event. */
21602ad55f56SYuchung Cheng 		tp->is_sack_reneg = 1;
21612ad55f56SYuchung Cheng 	} else if (tcp_is_reno(tp)) {
21622ad55f56SYuchung Cheng 		tcp_reset_reno_sack(tp);
21632ad55f56SYuchung Cheng 	}
21642ad55f56SYuchung Cheng 
216556f8c5d7SYuchung Cheng 	skb = head;
21662ad55f56SYuchung Cheng 	skb_rbtree_walk_from(skb) {
21672ad55f56SYuchung Cheng 		if (is_reneg)
21682ad55f56SYuchung Cheng 			TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_ACKED;
216956f8c5d7SYuchung Cheng 		else if (tcp_is_rack(sk) && skb != head &&
217056f8c5d7SYuchung Cheng 			 tcp_rack_skb_timeout(tp, skb, 0) > 0)
217156f8c5d7SYuchung Cheng 			continue; /* Don't mark recently sent ones lost yet */
21722ad55f56SYuchung Cheng 		tcp_mark_skb_lost(sk, skb);
21732ad55f56SYuchung Cheng 	}
21742ad55f56SYuchung Cheng 	tcp_verify_left_out(tp);
21752ad55f56SYuchung Cheng 	tcp_clear_all_retrans_hints(tp);
21762ad55f56SYuchung Cheng }
21772ad55f56SYuchung Cheng 
21782ad55f56SYuchung Cheng /* Enter Loss state. */
tcp_enter_loss(struct sock * sk)21795ae344c9SNeal Cardwell void tcp_enter_loss(struct sock *sk)
21801da177e4SLinus Torvalds {
21816687e988SArnaldo Carvalho de Melo 	const struct inet_connection_sock *icsk = inet_csk(sk);
21821da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
21831043e25fSNikolay Borisov 	struct net *net = sock_net(sk);
2184cc663f4dSYuchung Cheng 	bool new_recovery = icsk->icsk_ca_state < TCP_CA_Recovery;
218546778cd1SKuniyuki Iwashima 	u8 reordering;
21861da177e4SLinus Torvalds 
2187c77d62ffSYuchung Cheng 	tcp_timeout_mark_lost(sk);
2188c77d62ffSYuchung Cheng 
21891da177e4SLinus Torvalds 	/* Reduce ssthresh if it has not yet been made inside this window. */
2190e33099f9SYuchung Cheng 	if (icsk->icsk_ca_state <= TCP_CA_Disorder ||
2191e33099f9SYuchung Cheng 	    !after(tp->high_seq, tp->snd_una) ||
21926687e988SArnaldo Carvalho de Melo 	    (icsk->icsk_ca_state == TCP_CA_Loss && !icsk->icsk_retransmits)) {
21936687e988SArnaldo Carvalho de Melo 		tp->prior_ssthresh = tcp_current_ssthresh(sk);
219440570375SEric Dumazet 		tp->prior_cwnd = tcp_snd_cwnd(tp);
21956687e988SArnaldo Carvalho de Melo 		tp->snd_ssthresh = icsk->icsk_ca_ops->ssthresh(sk);
21966687e988SArnaldo Carvalho de Melo 		tcp_ca_event(sk, CA_EVENT_LOSS);
2197989e04c5SYuchung Cheng 		tcp_init_undo(tp);
21981da177e4SLinus Torvalds 	}
219940570375SEric Dumazet 	tcp_snd_cwnd_set(tp, tcp_packets_in_flight(tp) + 1);
22001da177e4SLinus Torvalds 	tp->snd_cwnd_cnt   = 0;
2201c2203cf7SEric Dumazet 	tp->snd_cwnd_stamp = tcp_jiffies32;
22021da177e4SLinus Torvalds 
220374c181d5SYuchung Cheng 	/* Timeout in disordered state after receiving substantial DUPACKs
220474c181d5SYuchung Cheng 	 * suggests that the degree of reordering is over-estimated.
220574c181d5SYuchung Cheng 	 */
220646778cd1SKuniyuki Iwashima 	reordering = READ_ONCE(net->ipv4.sysctl_tcp_reordering);
220774c181d5SYuchung Cheng 	if (icsk->icsk_ca_state <= TCP_CA_Disorder &&
220846778cd1SKuniyuki Iwashima 	    tp->sacked_out >= reordering)
22091da177e4SLinus Torvalds 		tp->reordering = min_t(unsigned int, tp->reordering,
221046778cd1SKuniyuki Iwashima 				       reordering);
221146778cd1SKuniyuki Iwashima 
22126687e988SArnaldo Carvalho de Melo 	tcp_set_ca_state(sk, TCP_CA_Loss);
22131da177e4SLinus Torvalds 	tp->high_seq = tp->snd_nxt;
2214124886cfSNeal Cardwell 	tp->tlp_high_seq = 0;
2215735d3831SFlorian Westphal 	tcp_ecn_queue_cwr(tp);
2216e33099f9SYuchung Cheng 
2217cc663f4dSYuchung Cheng 	/* F-RTO RFC5682 sec 3.1 step 1: retransmit SND.UNA if no previous
2218cc663f4dSYuchung Cheng 	 * loss recovery is underway except recurring timeout(s) on
2219cc663f4dSYuchung Cheng 	 * the same SND.UNA (sec 3.2). Disable F-RTO on path MTU probing
2220e33099f9SYuchung Cheng 	 */
2221706c6202SKuniyuki Iwashima 	tp->frto = READ_ONCE(net->ipv4.sysctl_tcp_frto) &&
2222cc663f4dSYuchung Cheng 		   (new_recovery || icsk->icsk_retransmits) &&
2223cc663f4dSYuchung Cheng 		   !inet_csk(sk)->icsk_mtup.probe_size;
22241da177e4SLinus Torvalds }
22251da177e4SLinus Torvalds 
2226cadbd031SIlpo Järvinen /* If ACK arrived pointing to a remembered SACK, it means that our
2227cadbd031SIlpo Järvinen  * remembered SACKs do not reflect real state of receiver i.e.
22281da177e4SLinus Torvalds  * receiver _host_ is heavily congested (or buggy).
2229cadbd031SIlpo Järvinen  *
22305ae344c9SNeal Cardwell  * To avoid big spurious retransmission bursts due to transient SACK
22315ae344c9SNeal Cardwell  * scoreboard oddities that look like reneging, we give the receiver a
22325ae344c9SNeal Cardwell  * little time (max(RTT/2, 10ms)) to send us some more ACKs that will
22335ae344c9SNeal Cardwell  * restore sanity to the SACK scoreboard. If the apparent reneging
22345ae344c9SNeal Cardwell  * persists until this RTO then we'll clear the SACK scoreboard.
22351da177e4SLinus Torvalds  */
tcp_check_sack_reneging(struct sock * sk,int * ack_flag)2236d2a0fc37SFred Chen static bool tcp_check_sack_reneging(struct sock *sk, int *ack_flag)
2237cadbd031SIlpo Järvinen {
2238d2a0fc37SFred Chen 	if (*ack_flag & FLAG_SACK_RENEGING &&
2239d2a0fc37SFred Chen 	    *ack_flag & FLAG_SND_UNA_ADVANCED) {
22405ae344c9SNeal Cardwell 		struct tcp_sock *tp = tcp_sk(sk);
22415ae344c9SNeal Cardwell 		unsigned long delay = max(usecs_to_jiffies(tp->srtt_us >> 4),
22425ae344c9SNeal Cardwell 					  msecs_to_jiffies(10));
22431da177e4SLinus Torvalds 
2244463c84b9SArnaldo Carvalho de Melo 		inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
22455ae344c9SNeal Cardwell 					  delay, TCP_RTO_MAX);
2246d2a0fc37SFred Chen 		*ack_flag &= ~FLAG_SET_XMIT_TIMER;
2247a2a385d6SEric Dumazet 		return true;
22481da177e4SLinus Torvalds 	}
2249a2a385d6SEric Dumazet 	return false;
22501da177e4SLinus Torvalds }
22511da177e4SLinus Torvalds 
225285cc391cSIlpo Järvinen /* Heurestics to calculate number of duplicate ACKs. There's no dupACKs
225385cc391cSIlpo Järvinen  * counter when SACK is enabled (without SACK, sacked_out is used for
225485cc391cSIlpo Järvinen  * that purpose).
225585cc391cSIlpo Järvinen  *
225685cc391cSIlpo Järvinen  * With reordering, holes may still be in flight, so RFC3517 recovery
225785cc391cSIlpo Järvinen  * uses pure sacked_out (total number of SACKed segments) even though
225885cc391cSIlpo Järvinen  * it violates the RFC that uses duplicate ACKs, often these are equal
225985cc391cSIlpo Järvinen  * but when e.g. out-of-window ACKs or packet duplication occurs,
226085cc391cSIlpo Järvinen  * they differ. Since neither occurs due to loss, TCP should really
226185cc391cSIlpo Järvinen  * ignore them.
226285cc391cSIlpo Järvinen  */
tcp_dupack_heuristics(const struct tcp_sock * tp)2263cf533ea5SEric Dumazet static inline int tcp_dupack_heuristics(const struct tcp_sock *tp)
226485cc391cSIlpo Järvinen {
2265713bafeaSYuchung Cheng 	return tp->sacked_out + 1;
226685cc391cSIlpo Järvinen }
226785cc391cSIlpo Järvinen 
2268713bafeaSYuchung Cheng /* Linux NewReno/SACK/ECN state machine.
22691da177e4SLinus Torvalds  * --------------------------------------
22701da177e4SLinus Torvalds  *
22711da177e4SLinus Torvalds  * "Open"	Normal state, no dubious events, fast path.
22721da177e4SLinus Torvalds  * "Disorder"   In all the respects it is "Open",
22731da177e4SLinus Torvalds  *		but requires a bit more attention. It is entered when
22741da177e4SLinus Torvalds  *		we see some SACKs or dupacks. It is split of "Open"
22751da177e4SLinus Torvalds  *		mainly to move some processing from fast path to slow one.
22761da177e4SLinus Torvalds  * "CWR"	CWND was reduced due to some Congestion Notification event.
22771da177e4SLinus Torvalds  *		It can be ECN, ICMP source quench, local device congestion.
22781da177e4SLinus Torvalds  * "Recovery"	CWND was reduced, we are fast-retransmitting.
22791da177e4SLinus Torvalds  * "Loss"	CWND was reduced due to RTO timeout or SACK reneging.
22801da177e4SLinus Torvalds  *
22811da177e4SLinus Torvalds  * tcp_fastretrans_alert() is entered:
22821da177e4SLinus Torvalds  * - each incoming ACK, if state is not "Open"
22831da177e4SLinus Torvalds  * - when arrived ACK is unusual, namely:
22841da177e4SLinus Torvalds  *	* SACK
22851da177e4SLinus Torvalds  *	* Duplicate ACK.
22861da177e4SLinus Torvalds  *	* ECN ECE.
22871da177e4SLinus Torvalds  *
22881da177e4SLinus Torvalds  * Counting packets in flight is pretty simple.
22891da177e4SLinus Torvalds  *
22901da177e4SLinus Torvalds  *	in_flight = packets_out - left_out + retrans_out
22911da177e4SLinus Torvalds  *
22921da177e4SLinus Torvalds  *	packets_out is SND.NXT-SND.UNA counted in packets.
22931da177e4SLinus Torvalds  *
22941da177e4SLinus Torvalds  *	retrans_out is number of retransmitted segments.
22951da177e4SLinus Torvalds  *
22961da177e4SLinus Torvalds  *	left_out is number of segments left network, but not ACKed yet.
22971da177e4SLinus Torvalds  *
22981da177e4SLinus Torvalds  *		left_out = sacked_out + lost_out
22991da177e4SLinus Torvalds  *
23001da177e4SLinus Torvalds  *     sacked_out: Packets, which arrived to receiver out of order
23011da177e4SLinus Torvalds  *		   and hence not ACKed. With SACKs this number is simply
23021da177e4SLinus Torvalds  *		   amount of SACKed data. Even without SACKs
23031da177e4SLinus Torvalds  *		   it is easy to give pretty reliable estimate of this number,
23041da177e4SLinus Torvalds  *		   counting duplicate ACKs.
23051da177e4SLinus Torvalds  *
23061da177e4SLinus Torvalds  *       lost_out: Packets lost by network. TCP has no explicit
23071da177e4SLinus Torvalds  *		   "loss notification" feedback from network (for now).
23081da177e4SLinus Torvalds  *		   It means that this number can be only _guessed_.
23091da177e4SLinus Torvalds  *		   Actually, it is the heuristics to predict lossage that
23101da177e4SLinus Torvalds  *		   distinguishes different algorithms.
23111da177e4SLinus Torvalds  *
23121da177e4SLinus Torvalds  *	F.e. after RTO, when all the queue is considered as lost,
23131da177e4SLinus Torvalds  *	lost_out = packets_out and in_flight = retrans_out.
23141da177e4SLinus Torvalds  *
2315a0370b3fSYuchung Cheng  *		Essentially, we have now a few algorithms detecting
23161da177e4SLinus Torvalds  *		lost packets.
23171da177e4SLinus Torvalds  *
2318a0370b3fSYuchung Cheng  *		If the receiver supports SACK:
2319a0370b3fSYuchung Cheng  *
2320a0370b3fSYuchung Cheng  *		RFC6675/3517: It is the conventional algorithm. A packet is
2321a0370b3fSYuchung Cheng  *		considered lost if the number of higher sequence packets
2322a0370b3fSYuchung Cheng  *		SACKed is greater than or equal the DUPACK thoreshold
2323a0370b3fSYuchung Cheng  *		(reordering). This is implemented in tcp_mark_head_lost and
2324a0370b3fSYuchung Cheng  *		tcp_update_scoreboard.
2325a0370b3fSYuchung Cheng  *
2326a0370b3fSYuchung Cheng  *		RACK (draft-ietf-tcpm-rack-01): it is a newer algorithm
2327a0370b3fSYuchung Cheng  *		(2017-) that checks timing instead of counting DUPACKs.
2328a0370b3fSYuchung Cheng  *		Essentially a packet is considered lost if it's not S/ACKed
2329a0370b3fSYuchung Cheng  *		after RTT + reordering_window, where both metrics are
2330a0370b3fSYuchung Cheng  *		dynamically measured and adjusted. This is implemented in
2331a0370b3fSYuchung Cheng  *		tcp_rack_mark_lost.
2332a0370b3fSYuchung Cheng  *
2333a0370b3fSYuchung Cheng  *		If the receiver does not support SACK:
2334a0370b3fSYuchung Cheng  *
2335a0370b3fSYuchung Cheng  *		NewReno (RFC6582): in Recovery we assume that one segment
23361da177e4SLinus Torvalds  *		is lost (classic Reno). While we are in Recovery and
23371da177e4SLinus Torvalds  *		a partial ACK arrives, we assume that one more packet
23381da177e4SLinus Torvalds  *		is lost (NewReno). This heuristics are the same in NewReno
23391da177e4SLinus Torvalds  *		and SACK.
23401da177e4SLinus Torvalds  *
23411da177e4SLinus Torvalds  * Really tricky (and requiring careful tuning) part of algorithm
23421da177e4SLinus Torvalds  * is hidden in functions tcp_time_to_recover() and tcp_xmit_retransmit_queue().
23431da177e4SLinus Torvalds  * The first determines the moment _when_ we should reduce CWND and,
23441da177e4SLinus Torvalds  * hence, slow down forward transmission. In fact, it determines the moment
23451da177e4SLinus Torvalds  * when we decide that hole is caused by loss, rather than by a reorder.
23461da177e4SLinus Torvalds  *
23471da177e4SLinus Torvalds  * tcp_xmit_retransmit_queue() decides, _what_ we should retransmit to fill
23481da177e4SLinus Torvalds  * holes, caused by lost packets.
23491da177e4SLinus Torvalds  *
23501da177e4SLinus Torvalds  * And the most logically complicated part of algorithm is undo
23511da177e4SLinus Torvalds  * heuristics. We detect false retransmits due to both too early
23521da177e4SLinus Torvalds  * fast retransmit (reordering) and underestimated RTO, analyzing
23531da177e4SLinus Torvalds  * timestamps and D-SACKs. When we detect that some segments were
23541da177e4SLinus Torvalds  * retransmitted by mistake and CWND reduction was wrong, we undo
23551da177e4SLinus Torvalds  * window reduction and abort recovery phase. This logic is hidden
23561da177e4SLinus Torvalds  * inside several functions named tcp_try_undo_<something>.
23571da177e4SLinus Torvalds  */
23581da177e4SLinus Torvalds 
23591da177e4SLinus Torvalds /* This function decides, when we should leave Disordered state
23601da177e4SLinus Torvalds  * and enter Recovery phase, reducing congestion window.
23611da177e4SLinus Torvalds  *
23621da177e4SLinus Torvalds  * Main question: may we further continue forward transmission
23631da177e4SLinus Torvalds  * with the same cwnd?
23641da177e4SLinus Torvalds  */
tcp_time_to_recover(struct sock * sk,int flag)2365a2a385d6SEric Dumazet static bool tcp_time_to_recover(struct sock *sk, int flag)
23661da177e4SLinus Torvalds {
23679e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
23681da177e4SLinus Torvalds 
23691da177e4SLinus Torvalds 	/* Trick#1: The loss is proven. */
23701da177e4SLinus Torvalds 	if (tp->lost_out)
2371a2a385d6SEric Dumazet 		return true;
23721da177e4SLinus Torvalds 
23731da177e4SLinus Torvalds 	/* Not-A-Trick#2 : Classic rule... */
2374b38a51feSYuchung Cheng 	if (!tcp_is_rack(sk) && tcp_dupack_heuristics(tp) > tp->reordering)
2375a2a385d6SEric Dumazet 		return true;
23761da177e4SLinus Torvalds 
2377a2a385d6SEric Dumazet 	return false;
23781da177e4SLinus Torvalds }
23791da177e4SLinus Torvalds 
2380974c1236SYuchung Cheng /* Detect loss in event "A" above by marking head of queue up as lost.
2381636ef28dSzhang kai  * For RFC3517 SACK, a segment is considered lost if it
2382974c1236SYuchung Cheng  * has at least tp->reordering SACKed seqments above it; "packets" refers to
2383974c1236SYuchung Cheng  * the maximum SACKed segments to pass before reaching this limit.
238485cc391cSIlpo Järvinen  */
tcp_mark_head_lost(struct sock * sk,int packets,int mark_head)23851fdb9361SIlpo Järvinen static void tcp_mark_head_lost(struct sock *sk, int packets, int mark_head)
23861da177e4SLinus Torvalds {
23879e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
23881da177e4SLinus Torvalds 	struct sk_buff *skb;
2389636ef28dSzhang kai 	int cnt;
2390974c1236SYuchung Cheng 	/* Use SACK to deduce losses of new sequences sent during recovery */
2391636ef28dSzhang kai 	const u32 loss_high = tp->snd_nxt;
23921da177e4SLinus Torvalds 
2393547b792cSIlpo Järvinen 	WARN_ON(packets > tp->packets_out);
23946a438bbeSStephen Hemminger 	skb = tp->lost_skb_hint;
23955e76ee4bSEric Dumazet 	if (skb) {
23961fdb9361SIlpo Järvinen 		/* Head already handled? */
23975e76ee4bSEric Dumazet 		if (mark_head && after(TCP_SKB_CB(skb)->seq, tp->snd_una))
23981fdb9361SIlpo Järvinen 			return;
23995e76ee4bSEric Dumazet 		cnt = tp->lost_cnt_hint;
24006a438bbeSStephen Hemminger 	} else {
240175c119afSEric Dumazet 		skb = tcp_rtx_queue_head(sk);
24026a438bbeSStephen Hemminger 		cnt = 0;
24036a438bbeSStephen Hemminger 	}
24041da177e4SLinus Torvalds 
240575c119afSEric Dumazet 	skb_rbtree_walk_from(skb) {
24066a438bbeSStephen Hemminger 		/* TODO: do this better */
24076a438bbeSStephen Hemminger 		/* this is not the most efficient way to do this... */
24086a438bbeSStephen Hemminger 		tp->lost_skb_hint = skb;
24096a438bbeSStephen Hemminger 		tp->lost_cnt_hint = cnt;
241085cc391cSIlpo Järvinen 
2411974c1236SYuchung Cheng 		if (after(TCP_SKB_CB(skb)->end_seq, loss_high))
2412c137f3ddSIlpo Järvinen 			break;
2413c137f3ddSIlpo Järvinen 
2414636ef28dSzhang kai 		if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)
24156a438bbeSStephen Hemminger 			cnt += tcp_skb_pcount(skb);
241685cc391cSIlpo Järvinen 
2417636ef28dSzhang kai 		if (cnt > packets)
24181da177e4SLinus Torvalds 			break;
2419c137f3ddSIlpo Järvinen 
2420534a2109SYuchung Cheng 		if (!(TCP_SKB_CB(skb)->sacked & TCPCB_LOST))
2421534a2109SYuchung Cheng 			tcp_mark_skb_lost(sk, skb);
24221fdb9361SIlpo Järvinen 
24231fdb9361SIlpo Järvinen 		if (mark_head)
24241fdb9361SIlpo Järvinen 			break;
24251da177e4SLinus Torvalds 	}
2426005903bcSIlpo Järvinen 	tcp_verify_left_out(tp);
24271da177e4SLinus Torvalds }
24281da177e4SLinus Torvalds 
24291da177e4SLinus Torvalds /* Account newly detected lost packet(s) */
24301da177e4SLinus Torvalds 
tcp_update_scoreboard(struct sock * sk,int fast_rexmit)243185cc391cSIlpo Järvinen static void tcp_update_scoreboard(struct sock *sk, int fast_rexmit)
24321da177e4SLinus Torvalds {
24339e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
24349e412ba7SIlpo Järvinen 
24356ac06ecdSYuchung Cheng 	if (tcp_is_sack(tp)) {
243685cc391cSIlpo Järvinen 		int sacked_upto = tp->sacked_out - tp->reordering;
24371fdb9361SIlpo Järvinen 		if (sacked_upto >= 0)
24381fdb9361SIlpo Järvinen 			tcp_mark_head_lost(sk, sacked_upto, 0);
24391fdb9361SIlpo Järvinen 		else if (fast_rexmit)
24401fdb9361SIlpo Järvinen 			tcp_mark_head_lost(sk, 1, 1);
24411da177e4SLinus Torvalds 	}
24421da177e4SLinus Torvalds }
24431da177e4SLinus Torvalds 
tcp_tsopt_ecr_before(const struct tcp_sock * tp,u32 when)244477c63127SYuchung Cheng static bool tcp_tsopt_ecr_before(const struct tcp_sock *tp, u32 when)
244577c63127SYuchung Cheng {
244677c63127SYuchung Cheng 	return tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr &&
244777c63127SYuchung Cheng 	       before(tp->rx_opt.rcv_tsecr, when);
244877c63127SYuchung Cheng }
244977c63127SYuchung Cheng 
2450659a8ad5SYuchung Cheng /* skb is spurious retransmitted if the returned timestamp echo
2451659a8ad5SYuchung Cheng  * reply is prior to the skb transmission time
2452659a8ad5SYuchung Cheng  */
tcp_skb_spurious_retrans(const struct tcp_sock * tp,const struct sk_buff * skb)2453659a8ad5SYuchung Cheng static bool tcp_skb_spurious_retrans(const struct tcp_sock *tp,
2454659a8ad5SYuchung Cheng 				     const struct sk_buff *skb)
2455659a8ad5SYuchung Cheng {
2456659a8ad5SYuchung Cheng 	return (TCP_SKB_CB(skb)->sacked & TCPCB_RETRANS) &&
2457659a8ad5SYuchung Cheng 	       tcp_tsopt_ecr_before(tp, tcp_skb_timestamp(skb));
2458659a8ad5SYuchung Cheng }
2459659a8ad5SYuchung Cheng 
24601da177e4SLinus Torvalds /* Nothing was retransmitted or returned timestamp is less
24611da177e4SLinus Torvalds  * than timestamp of the first retransmission.
24621da177e4SLinus Torvalds  */
tcp_packet_delayed(const struct tcp_sock * tp)246367b95bd7SVijay Subramanian static inline bool tcp_packet_delayed(const struct tcp_sock *tp)
24641da177e4SLinus Torvalds {
2465e676ca60SNeal Cardwell 	const struct sock *sk = (const struct sock *)tp;
2466e676ca60SNeal Cardwell 
2467e676ca60SNeal Cardwell 	if (tp->retrans_stamp &&
2468e676ca60SNeal Cardwell 	    tcp_tsopt_ecr_before(tp, tp->retrans_stamp))
2469e676ca60SNeal Cardwell 		return true;  /* got echoed TS before first retransmission */
2470e676ca60SNeal Cardwell 
2471e676ca60SNeal Cardwell 	/* Check if nothing was retransmitted (retrans_stamp==0), which may
2472e676ca60SNeal Cardwell 	 * happen in fast recovery due to TSQ. But we ignore zero retrans_stamp
2473e676ca60SNeal Cardwell 	 * in TCP_SYN_SENT, since when we set FLAG_SYN_ACKED we also clear
2474e676ca60SNeal Cardwell 	 * retrans_stamp even if we had retransmitted the SYN.
2475e676ca60SNeal Cardwell 	 */
2476e676ca60SNeal Cardwell 	if (!tp->retrans_stamp &&	   /* no record of a retransmit/SYN? */
2477e676ca60SNeal Cardwell 	    sk->sk_state != TCP_SYN_SENT)  /* not the FLAG_SYN_ACKED case? */
2478e676ca60SNeal Cardwell 		return true;  /* nothing was retransmitted */
2479e676ca60SNeal Cardwell 
2480e676ca60SNeal Cardwell 	return false;
24811da177e4SLinus Torvalds }
24821da177e4SLinus Torvalds 
24831da177e4SLinus Torvalds /* Undo procedures. */
24841da177e4SLinus Torvalds 
24851f37bf87SMarcelo Leitner /* We can clear retrans_stamp when there are no retransmissions in the
24861f37bf87SMarcelo Leitner  * window. It would seem that it is trivially available for us in
24871f37bf87SMarcelo Leitner  * tp->retrans_out, however, that kind of assumptions doesn't consider
24881f37bf87SMarcelo Leitner  * what will happen if errors occur when sending retransmission for the
24891f37bf87SMarcelo Leitner  * second time. ...It could the that such segment has only
24901f37bf87SMarcelo Leitner  * TCPCB_EVER_RETRANS set at the present time. It seems that checking
24911f37bf87SMarcelo Leitner  * the head skb is enough except for some reneging corner cases that
24921f37bf87SMarcelo Leitner  * are not worth the effort.
24931f37bf87SMarcelo Leitner  *
24941f37bf87SMarcelo Leitner  * Main reason for all this complexity is the fact that connection dying
24951f37bf87SMarcelo Leitner  * time now depends on the validity of the retrans_stamp, in particular,
24961f37bf87SMarcelo Leitner  * that successive retransmissions of a segment must not advance
24971f37bf87SMarcelo Leitner  * retrans_stamp under any conditions.
24981f37bf87SMarcelo Leitner  */
tcp_any_retrans_done(const struct sock * sk)24991f37bf87SMarcelo Leitner static bool tcp_any_retrans_done(const struct sock *sk)
25001f37bf87SMarcelo Leitner {
25011f37bf87SMarcelo Leitner 	const struct tcp_sock *tp = tcp_sk(sk);
25021f37bf87SMarcelo Leitner 	struct sk_buff *skb;
25031f37bf87SMarcelo Leitner 
25041f37bf87SMarcelo Leitner 	if (tp->retrans_out)
25051f37bf87SMarcelo Leitner 		return true;
25061f37bf87SMarcelo Leitner 
250775c119afSEric Dumazet 	skb = tcp_rtx_queue_head(sk);
25081f37bf87SMarcelo Leitner 	if (unlikely(skb && TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS))
25091f37bf87SMarcelo Leitner 		return true;
25101f37bf87SMarcelo Leitner 
25111f37bf87SMarcelo Leitner 	return false;
25121f37bf87SMarcelo Leitner }
25131f37bf87SMarcelo Leitner 
251404dce9a1SNeal Cardwell /* If loss recovery is finished and there are no retransmits out in the
251504dce9a1SNeal Cardwell  * network, then we clear retrans_stamp so that upon the next loss recovery
251604dce9a1SNeal Cardwell  * retransmits_timed_out() and timestamp-undo are using the correct value.
251704dce9a1SNeal Cardwell  */
tcp_retrans_stamp_cleanup(struct sock * sk)251804dce9a1SNeal Cardwell static void tcp_retrans_stamp_cleanup(struct sock *sk)
251904dce9a1SNeal Cardwell {
252004dce9a1SNeal Cardwell 	if (!tcp_any_retrans_done(sk))
252104dce9a1SNeal Cardwell 		tcp_sk(sk)->retrans_stamp = 0;
252204dce9a1SNeal Cardwell }
252304dce9a1SNeal Cardwell 
DBGUNDO(struct sock * sk,const char * msg)25249e412ba7SIlpo Järvinen static void DBGUNDO(struct sock *sk, const char *msg)
25251da177e4SLinus Torvalds {
25263934788aSJoe Perches #if FASTRETRANS_DEBUG > 1
25279e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
25281da177e4SLinus Torvalds 	struct inet_sock *inet = inet_sk(sk);
25299e412ba7SIlpo Järvinen 
2530569508c9SYOSHIFUJI Hideaki 	if (sk->sk_family == AF_INET) {
253191df42beSJoe Perches 		pr_debug("Undo %s %pI4/%u c%u l%u ss%u/%u p%u\n",
25321da177e4SLinus Torvalds 			 msg,
2533288fcee8SJoe Perches 			 &inet->inet_daddr, ntohs(inet->inet_dport),
253440570375SEric Dumazet 			 tcp_snd_cwnd(tp), tcp_left_out(tp),
25351da177e4SLinus Torvalds 			 tp->snd_ssthresh, tp->prior_ssthresh,
25361da177e4SLinus Torvalds 			 tp->packets_out);
25371da177e4SLinus Torvalds 	}
2538dfd56b8bSEric Dumazet #if IS_ENABLED(CONFIG_IPV6)
2539569508c9SYOSHIFUJI Hideaki 	else if (sk->sk_family == AF_INET6) {
254091df42beSJoe Perches 		pr_debug("Undo %s %pI6/%u c%u l%u ss%u/%u p%u\n",
2541569508c9SYOSHIFUJI Hideaki 			 msg,
2542019b1c9fSEric Dumazet 			 &sk->sk_v6_daddr, ntohs(inet->inet_dport),
254340570375SEric Dumazet 			 tcp_snd_cwnd(tp), tcp_left_out(tp),
2544569508c9SYOSHIFUJI Hideaki 			 tp->snd_ssthresh, tp->prior_ssthresh,
2545569508c9SYOSHIFUJI Hideaki 			 tp->packets_out);
2546569508c9SYOSHIFUJI Hideaki 	}
2547569508c9SYOSHIFUJI Hideaki #endif
25481da177e4SLinus Torvalds #endif
25493934788aSJoe Perches }
25501da177e4SLinus Torvalds 
tcp_undo_cwnd_reduction(struct sock * sk,bool unmark_loss)25517026b912SYuchung Cheng static void tcp_undo_cwnd_reduction(struct sock *sk, bool unmark_loss)
25521da177e4SLinus Torvalds {
25536687e988SArnaldo Carvalho de Melo 	struct tcp_sock *tp = tcp_sk(sk);
25546687e988SArnaldo Carvalho de Melo 
25556a63df46SYuchung Cheng 	if (unmark_loss) {
25566a63df46SYuchung Cheng 		struct sk_buff *skb;
25576a63df46SYuchung Cheng 
255875c119afSEric Dumazet 		skb_rbtree_walk(skb, &sk->tcp_rtx_queue) {
25596a63df46SYuchung Cheng 			TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
25606a63df46SYuchung Cheng 		}
25616a63df46SYuchung Cheng 		tp->lost_out = 0;
25626a63df46SYuchung Cheng 		tcp_clear_all_retrans_hints(tp);
25636a63df46SYuchung Cheng 	}
25646a63df46SYuchung Cheng 
25651da177e4SLinus Torvalds 	if (tp->prior_ssthresh) {
25666687e988SArnaldo Carvalho de Melo 		const struct inet_connection_sock *icsk = inet_csk(sk);
25676687e988SArnaldo Carvalho de Melo 
256840570375SEric Dumazet 		tcp_snd_cwnd_set(tp, icsk->icsk_ca_ops->undo_cwnd(sk));
25691da177e4SLinus Torvalds 
25707026b912SYuchung Cheng 		if (tp->prior_ssthresh > tp->snd_ssthresh) {
25711da177e4SLinus Torvalds 			tp->snd_ssthresh = tp->prior_ssthresh;
2572735d3831SFlorian Westphal 			tcp_ecn_withdraw_cwr(tp);
25731da177e4SLinus Torvalds 		}
25741da177e4SLinus Torvalds 	}
2575c2203cf7SEric Dumazet 	tp->snd_cwnd_stamp = tcp_jiffies32;
25766a63df46SYuchung Cheng 	tp->undo_marker = 0;
2577cd1fc85bSYuchung Cheng 	tp->rack.advanced = 1; /* Force RACK to re-exam losses */
25781da177e4SLinus Torvalds }
25791da177e4SLinus Torvalds 
tcp_may_undo(const struct tcp_sock * tp)258067b95bd7SVijay Subramanian static inline bool tcp_may_undo(const struct tcp_sock *tp)
25811da177e4SLinus Torvalds {
2582056834d9SIlpo Järvinen 	return tp->undo_marker && (!tp->undo_retrans || tcp_packet_delayed(tp));
25831da177e4SLinus Torvalds }
25841da177e4SLinus Torvalds 
tcp_is_non_sack_preventing_reopen(struct sock * sk)2585686dc2dbSNeal Cardwell static bool tcp_is_non_sack_preventing_reopen(struct sock *sk)
2586686dc2dbSNeal Cardwell {
2587686dc2dbSNeal Cardwell 	struct tcp_sock *tp = tcp_sk(sk);
2588686dc2dbSNeal Cardwell 
2589686dc2dbSNeal Cardwell 	if (tp->snd_una == tp->high_seq && tcp_is_reno(tp)) {
2590686dc2dbSNeal Cardwell 		/* Hold old state until something *above* high_seq
2591686dc2dbSNeal Cardwell 		 * is ACKed. For Reno it is MUST to prevent false
2592686dc2dbSNeal Cardwell 		 * fast retransmits (RFC2582). SACK TCP is safe. */
2593686dc2dbSNeal Cardwell 		if (!tcp_any_retrans_done(sk))
2594686dc2dbSNeal Cardwell 			tp->retrans_stamp = 0;
2595686dc2dbSNeal Cardwell 		return true;
2596686dc2dbSNeal Cardwell 	}
2597686dc2dbSNeal Cardwell 	return false;
2598686dc2dbSNeal Cardwell }
2599686dc2dbSNeal Cardwell 
26001da177e4SLinus Torvalds /* People celebrate: "We love our President!" */
tcp_try_undo_recovery(struct sock * sk)2601a2a385d6SEric Dumazet static bool tcp_try_undo_recovery(struct sock *sk)
26021da177e4SLinus Torvalds {
26039e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
26049e412ba7SIlpo Järvinen 
26051da177e4SLinus Torvalds 	if (tcp_may_undo(tp)) {
260640b215e5SPavel Emelyanov 		int mib_idx;
260740b215e5SPavel Emelyanov 
26081da177e4SLinus Torvalds 		/* Happy end! We did not retransmit anything
26091da177e4SLinus Torvalds 		 * or our original transmission succeeded.
26101da177e4SLinus Torvalds 		 */
26119e412ba7SIlpo Järvinen 		DBGUNDO(sk, inet_csk(sk)->icsk_ca_state == TCP_CA_Loss ? "loss" : "retrans");
26127026b912SYuchung Cheng 		tcp_undo_cwnd_reduction(sk, false);
26136687e988SArnaldo Carvalho de Melo 		if (inet_csk(sk)->icsk_ca_state == TCP_CA_Loss)
261440b215e5SPavel Emelyanov 			mib_idx = LINUX_MIB_TCPLOSSUNDO;
26151da177e4SLinus Torvalds 		else
261640b215e5SPavel Emelyanov 			mib_idx = LINUX_MIB_TCPFULLUNDO;
261740b215e5SPavel Emelyanov 
2618c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), mib_idx);
26191f255691SPriyaranjan Jha 	} else if (tp->rack.reo_wnd_persist) {
26201f255691SPriyaranjan Jha 		tp->rack.reo_wnd_persist--;
26211da177e4SLinus Torvalds 	}
2622686dc2dbSNeal Cardwell 	if (tcp_is_non_sack_preventing_reopen(sk))
2623a2a385d6SEric Dumazet 		return true;
26246687e988SArnaldo Carvalho de Melo 	tcp_set_ca_state(sk, TCP_CA_Open);
2625d4761754SYousuk Seung 	tp->is_sack_reneg = 0;
2626a2a385d6SEric Dumazet 	return false;
26271da177e4SLinus Torvalds }
26281da177e4SLinus Torvalds 
26291da177e4SLinus Torvalds /* Try to undo cwnd reduction, because D-SACKs acked all retransmitted data */
tcp_try_undo_dsack(struct sock * sk)2630c7d9d6a1SYuchung Cheng static bool tcp_try_undo_dsack(struct sock *sk)
26311da177e4SLinus Torvalds {
26329e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
26339e412ba7SIlpo Järvinen 
26341da177e4SLinus Torvalds 	if (tp->undo_marker && !tp->undo_retrans) {
26351f255691SPriyaranjan Jha 		tp->rack.reo_wnd_persist = min(TCP_RACK_RECOVERY_THRESH,
26361f255691SPriyaranjan Jha 					       tp->rack.reo_wnd_persist + 1);
26379e412ba7SIlpo Järvinen 		DBGUNDO(sk, "D-SACK");
26387026b912SYuchung Cheng 		tcp_undo_cwnd_reduction(sk, false);
2639c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKUNDO);
2640c7d9d6a1SYuchung Cheng 		return true;
26411da177e4SLinus Torvalds 	}
2642c7d9d6a1SYuchung Cheng 	return false;
26431da177e4SLinus Torvalds }
26441da177e4SLinus Torvalds 
2645e33099f9SYuchung Cheng /* Undo during loss recovery after partial ACK or using F-RTO. */
tcp_try_undo_loss(struct sock * sk,bool frto_undo)2646e33099f9SYuchung Cheng static bool tcp_try_undo_loss(struct sock *sk, bool frto_undo)
26471da177e4SLinus Torvalds {
26489e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
26499e412ba7SIlpo Järvinen 
2650e33099f9SYuchung Cheng 	if (frto_undo || tcp_may_undo(tp)) {
26517026b912SYuchung Cheng 		tcp_undo_cwnd_reduction(sk, true);
26526a438bbeSStephen Hemminger 
26539e412ba7SIlpo Järvinen 		DBGUNDO(sk, "partial loss");
2654c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPLOSSUNDO);
2655e33099f9SYuchung Cheng 		if (frto_undo)
2656c10d9310SEric Dumazet 			NET_INC_STATS(sock_net(sk),
2657e33099f9SYuchung Cheng 					LINUX_MIB_TCPSPURIOUSRTOS);
2658463c84b9SArnaldo Carvalho de Melo 		inet_csk(sk)->icsk_retransmits = 0;
2659686dc2dbSNeal Cardwell 		if (tcp_is_non_sack_preventing_reopen(sk))
2660686dc2dbSNeal Cardwell 			return true;
2661d4761754SYousuk Seung 		if (frto_undo || tcp_is_sack(tp)) {
26626687e988SArnaldo Carvalho de Melo 			tcp_set_ca_state(sk, TCP_CA_Open);
2663d4761754SYousuk Seung 			tp->is_sack_reneg = 0;
2664d4761754SYousuk Seung 		}
2665a2a385d6SEric Dumazet 		return true;
26661da177e4SLinus Torvalds 	}
2667a2a385d6SEric Dumazet 	return false;
26681da177e4SLinus Torvalds }
26691da177e4SLinus Torvalds 
26703759824dSYuchung Cheng /* The cwnd reduction in CWR and Recovery uses the PRR algorithm in RFC 6937.
2671fb4d3d1dSYuchung Cheng  * It computes the number of packets to send (sndcnt) based on packets newly
2672fb4d3d1dSYuchung Cheng  * delivered:
2673fb4d3d1dSYuchung Cheng  *   1) If the packets in flight is larger than ssthresh, PRR spreads the
2674fb4d3d1dSYuchung Cheng  *	cwnd reductions across a full RTT.
26753759824dSYuchung Cheng  *   2) Otherwise PRR uses packet conservation to send as much as delivered.
26767e901ee7SYuchung Cheng  *      But when SND_UNA is acked without further losses,
26773759824dSYuchung Cheng  *      slow starts cwnd up to ssthresh to speed up the recovery.
2678fb4d3d1dSYuchung Cheng  */
tcp_init_cwnd_reduction(struct sock * sk)26795ee2c941SChristoph Paasch static void tcp_init_cwnd_reduction(struct sock *sk)
2680684bad11SYuchung Cheng {
2681684bad11SYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
2682684bad11SYuchung Cheng 
2683684bad11SYuchung Cheng 	tp->high_seq = tp->snd_nxt;
26849b717a8dSNandita Dukkipati 	tp->tlp_high_seq = 0;
2685684bad11SYuchung Cheng 	tp->snd_cwnd_cnt = 0;
268640570375SEric Dumazet 	tp->prior_cwnd = tcp_snd_cwnd(tp);
2687684bad11SYuchung Cheng 	tp->prr_delivered = 0;
2688684bad11SYuchung Cheng 	tp->prr_out = 0;
2689684bad11SYuchung Cheng 	tp->snd_ssthresh = inet_csk(sk)->icsk_ca_ops->ssthresh(sk);
2690735d3831SFlorian Westphal 	tcp_ecn_queue_cwr(tp);
2691684bad11SYuchung Cheng }
2692684bad11SYuchung Cheng 
tcp_cwnd_reduction(struct sock * sk,int newly_acked_sacked,int newly_lost,int flag)26937e901ee7SYuchung Cheng void tcp_cwnd_reduction(struct sock *sk, int newly_acked_sacked, int newly_lost, int flag)
2694fb4d3d1dSYuchung Cheng {
2695fb4d3d1dSYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
2696fb4d3d1dSYuchung Cheng 	int sndcnt = 0;
2697fb4d3d1dSYuchung Cheng 	int delta = tp->snd_ssthresh - tcp_packets_in_flight(tp);
2698fb4d3d1dSYuchung Cheng 
26998b8a321fSYuchung Cheng 	if (newly_acked_sacked <= 0 || WARN_ON_ONCE(!tp->prior_cwnd))
27008b8a321fSYuchung Cheng 		return;
27018b8a321fSYuchung Cheng 
2702684bad11SYuchung Cheng 	tp->prr_delivered += newly_acked_sacked;
27033759824dSYuchung Cheng 	if (delta < 0) {
2704fb4d3d1dSYuchung Cheng 		u64 dividend = (u64)tp->snd_ssthresh * tp->prr_delivered +
2705fb4d3d1dSYuchung Cheng 			       tp->prior_cwnd - 1;
2706fb4d3d1dSYuchung Cheng 		sndcnt = div_u64(dividend, tp->prior_cwnd) - tp->prr_out;
27073759824dSYuchung Cheng 	} else {
27089ad084d6SYuchung Cheng 		sndcnt = max_t(int, tp->prr_delivered - tp->prr_out,
27099ad084d6SYuchung Cheng 			       newly_acked_sacked);
27109ad084d6SYuchung Cheng 		if (flag & FLAG_SND_UNA_ADVANCED && !newly_lost)
27119ad084d6SYuchung Cheng 			sndcnt++;
27129ad084d6SYuchung Cheng 		sndcnt = min(delta, sndcnt);
2713fb4d3d1dSYuchung Cheng 	}
271431ba0c10SYuchung Cheng 	/* Force a fast retransmit upon entering fast recovery */
271531ba0c10SYuchung Cheng 	sndcnt = max(sndcnt, (tp->prr_out ? 0 : 1));
271640570375SEric Dumazet 	tcp_snd_cwnd_set(tp, tcp_packets_in_flight(tp) + sndcnt);
2717fb4d3d1dSYuchung Cheng }
2718fb4d3d1dSYuchung Cheng 
tcp_end_cwnd_reduction(struct sock * sk)2719684bad11SYuchung Cheng static inline void tcp_end_cwnd_reduction(struct sock *sk)
27201da177e4SLinus Torvalds {
27216687e988SArnaldo Carvalho de Melo 	struct tcp_sock *tp = tcp_sk(sk);
2722a262f0cdSNandita Dukkipati 
2723c0402760SYuchung Cheng 	if (inet_csk(sk)->icsk_ca_ops->cong_control)
2724c0402760SYuchung Cheng 		return;
2725c0402760SYuchung Cheng 
2726684bad11SYuchung Cheng 	/* Reset cwnd to ssthresh in CWR or Recovery (unless it's undone) */
2727ed254971SYuchung Cheng 	if (tp->snd_ssthresh < TCP_INFINITE_SSTHRESH &&
2728ed254971SYuchung Cheng 	    (inet_csk(sk)->icsk_ca_state == TCP_CA_CWR || tp->undo_marker)) {
272940570375SEric Dumazet 		tcp_snd_cwnd_set(tp, tp->snd_ssthresh);
2730c2203cf7SEric Dumazet 		tp->snd_cwnd_stamp = tcp_jiffies32;
273167d4120aSYuchung Cheng 	}
27326687e988SArnaldo Carvalho de Melo 	tcp_ca_event(sk, CA_EVENT_COMPLETE_CWR);
27331da177e4SLinus Torvalds }
27341da177e4SLinus Torvalds 
2735684bad11SYuchung Cheng /* Enter CWR state. Disable cwnd undo since congestion is proven with ECN */
tcp_enter_cwr(struct sock * sk)27365ee2c941SChristoph Paasch void tcp_enter_cwr(struct sock *sk)
273709484d1fSYuchung Cheng {
273809484d1fSYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
273909484d1fSYuchung Cheng 
274009484d1fSYuchung Cheng 	tp->prior_ssthresh = 0;
2741684bad11SYuchung Cheng 	if (inet_csk(sk)->icsk_ca_state < TCP_CA_CWR) {
274209484d1fSYuchung Cheng 		tp->undo_marker = 0;
27435ee2c941SChristoph Paasch 		tcp_init_cwnd_reduction(sk);
274409484d1fSYuchung Cheng 		tcp_set_ca_state(sk, TCP_CA_CWR);
274509484d1fSYuchung Cheng 	}
274609484d1fSYuchung Cheng }
27477782ad8bSKenneth Klette Jonassen EXPORT_SYMBOL(tcp_enter_cwr);
274809484d1fSYuchung Cheng 
tcp_try_keep_open(struct sock * sk)27498aca6cb1SIlpo Järvinen static void tcp_try_keep_open(struct sock *sk)
27508aca6cb1SIlpo Järvinen {
27518aca6cb1SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
27528aca6cb1SIlpo Järvinen 	int state = TCP_CA_Open;
27538aca6cb1SIlpo Järvinen 
2754f698204bSNeal Cardwell 	if (tcp_left_out(tp) || tcp_any_retrans_done(sk))
27558aca6cb1SIlpo Järvinen 		state = TCP_CA_Disorder;
27568aca6cb1SIlpo Järvinen 
27578aca6cb1SIlpo Järvinen 	if (inet_csk(sk)->icsk_ca_state != state) {
27588aca6cb1SIlpo Järvinen 		tcp_set_ca_state(sk, state);
27598aca6cb1SIlpo Järvinen 		tp->high_seq = tp->snd_nxt;
27608aca6cb1SIlpo Järvinen 	}
27618aca6cb1SIlpo Järvinen }
27628aca6cb1SIlpo Järvinen 
tcp_try_to_open(struct sock * sk,int flag)276331ba0c10SYuchung Cheng static void tcp_try_to_open(struct sock *sk, int flag)
27641da177e4SLinus Torvalds {
27659e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
27669e412ba7SIlpo Järvinen 
276786426c22SIlpo Järvinen 	tcp_verify_left_out(tp);
276886426c22SIlpo Järvinen 
27699b44190dSYuchung Cheng 	if (!tcp_any_retrans_done(sk))
27701da177e4SLinus Torvalds 		tp->retrans_stamp = 0;
27711da177e4SLinus Torvalds 
27721da177e4SLinus Torvalds 	if (flag & FLAG_ECE)
27735ee2c941SChristoph Paasch 		tcp_enter_cwr(sk);
27741da177e4SLinus Torvalds 
27756687e988SArnaldo Carvalho de Melo 	if (inet_csk(sk)->icsk_ca_state != TCP_CA_CWR) {
27768aca6cb1SIlpo Järvinen 		tcp_try_keep_open(sk);
27771da177e4SLinus Torvalds 	}
27781da177e4SLinus Torvalds }
27791da177e4SLinus Torvalds 
tcp_mtup_probe_failed(struct sock * sk)27805d424d5aSJohn Heffner static void tcp_mtup_probe_failed(struct sock *sk)
27815d424d5aSJohn Heffner {
27825d424d5aSJohn Heffner 	struct inet_connection_sock *icsk = inet_csk(sk);
27835d424d5aSJohn Heffner 
27845d424d5aSJohn Heffner 	icsk->icsk_mtup.search_high = icsk->icsk_mtup.probe_size - 1;
27855d424d5aSJohn Heffner 	icsk->icsk_mtup.probe_size = 0;
2786c10d9310SEric Dumazet 	NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMTUPFAIL);
27875d424d5aSJohn Heffner }
27885d424d5aSJohn Heffner 
tcp_mtup_probe_success(struct sock * sk)278972211e90SIlpo Järvinen static void tcp_mtup_probe_success(struct sock *sk)
27905d424d5aSJohn Heffner {
27915d424d5aSJohn Heffner 	struct tcp_sock *tp = tcp_sk(sk);
27925d424d5aSJohn Heffner 	struct inet_connection_sock *icsk = inet_csk(sk);
279311825765SEric Dumazet 	u64 val;
27945d424d5aSJohn Heffner 
27955d424d5aSJohn Heffner 	tp->prior_ssthresh = tcp_current_ssthresh(sk);
279611825765SEric Dumazet 
279711825765SEric Dumazet 	val = (u64)tcp_snd_cwnd(tp) * tcp_mss_to_mtu(sk, tp->mss_cache);
279811825765SEric Dumazet 	do_div(val, icsk->icsk_mtup.probe_size);
279911825765SEric Dumazet 	DEBUG_NET_WARN_ON_ONCE((u32)val != val);
280011825765SEric Dumazet 	tcp_snd_cwnd_set(tp, max_t(u32, 1U, val));
280111825765SEric Dumazet 
28025d424d5aSJohn Heffner 	tp->snd_cwnd_cnt = 0;
2803c2203cf7SEric Dumazet 	tp->snd_cwnd_stamp = tcp_jiffies32;
28049c6d5e55SJohn Heffner 	tp->snd_ssthresh = tcp_current_ssthresh(sk);
28055d424d5aSJohn Heffner 
28065d424d5aSJohn Heffner 	icsk->icsk_mtup.search_low = icsk->icsk_mtup.probe_size;
28075d424d5aSJohn Heffner 	icsk->icsk_mtup.probe_size = 0;
28085d424d5aSJohn Heffner 	tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
2809c10d9310SEric Dumazet 	NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMTUPSUCCESS);
28105d424d5aSJohn Heffner }
28115d424d5aSJohn Heffner 
2812b4b26d23SNeal Cardwell /* Sometimes we deduce that packets have been dropped due to reasons other than
2813b4b26d23SNeal Cardwell  * congestion, like path MTU reductions or failed client TFO attempts. In these
2814b4b26d23SNeal Cardwell  * cases we call this function to retransmit as many packets as cwnd allows,
2815b4b26d23SNeal Cardwell  * without reducing cwnd. Given that retransmits will set retrans_stamp to a
2816b4b26d23SNeal Cardwell  * non-zero value (and may do so in a later calling context due to TSQ), we
2817b4b26d23SNeal Cardwell  * also enter CA_Loss so that we track when all retransmitted packets are ACKed
2818b4b26d23SNeal Cardwell  * and clear retrans_stamp when that happens (to ensure later recurring RTOs
2819b4b26d23SNeal Cardwell  * are using the correct retrans_stamp and don't declare ETIMEDOUT
2820b4b26d23SNeal Cardwell  * prematurely).
2821b4b26d23SNeal Cardwell  */
tcp_non_congestion_loss_retransmit(struct sock * sk)2822b4b26d23SNeal Cardwell static void tcp_non_congestion_loss_retransmit(struct sock *sk)
2823b4b26d23SNeal Cardwell {
2824b4b26d23SNeal Cardwell 	const struct inet_connection_sock *icsk = inet_csk(sk);
2825b4b26d23SNeal Cardwell 	struct tcp_sock *tp = tcp_sk(sk);
2826b4b26d23SNeal Cardwell 
2827b4b26d23SNeal Cardwell 	if (icsk->icsk_ca_state != TCP_CA_Loss) {
2828b4b26d23SNeal Cardwell 		tp->high_seq = tp->snd_nxt;
2829b4b26d23SNeal Cardwell 		tp->snd_ssthresh = tcp_current_ssthresh(sk);
2830b4b26d23SNeal Cardwell 		tp->prior_ssthresh = 0;
2831b4b26d23SNeal Cardwell 		tp->undo_marker = 0;
2832b4b26d23SNeal Cardwell 		tcp_set_ca_state(sk, TCP_CA_Loss);
2833b4b26d23SNeal Cardwell 	}
2834b4b26d23SNeal Cardwell 	tcp_xmit_retransmit_queue(sk);
2835b4b26d23SNeal Cardwell }
2836b4b26d23SNeal Cardwell 
2837e1aa680fSIlpo Järvinen /* Do a simple retransmit without using the backoff mechanisms in
2838e1aa680fSIlpo Järvinen  * tcp_timer. This is used for path mtu discovery.
2839e1aa680fSIlpo Järvinen  * The socket is already locked here.
2840e1aa680fSIlpo Järvinen  */
tcp_simple_retransmit(struct sock * sk)2841e1aa680fSIlpo Järvinen void tcp_simple_retransmit(struct sock *sk)
2842e1aa680fSIlpo Järvinen {
2843e1aa680fSIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
2844e1aa680fSIlpo Järvinen 	struct sk_buff *skb;
2845c31b70c9SAlexander Duyck 	int mss;
2846c31b70c9SAlexander Duyck 
2847c31b70c9SAlexander Duyck 	/* A fastopen SYN request is stored as two separate packets within
2848c31b70c9SAlexander Duyck 	 * the retransmit queue, this is done by tcp_send_syn_data().
2849c31b70c9SAlexander Duyck 	 * As a result simply checking the MSS of the frames in the queue
2850c31b70c9SAlexander Duyck 	 * will not work for the SYN packet.
2851c31b70c9SAlexander Duyck 	 *
2852c31b70c9SAlexander Duyck 	 * Us being here is an indication of a path MTU issue so we can
2853c31b70c9SAlexander Duyck 	 * assume that the fastopen SYN was lost and just mark all the
2854c31b70c9SAlexander Duyck 	 * frames in the retransmit queue as lost. We will use an MSS of
2855c31b70c9SAlexander Duyck 	 * -1 to mark all frames as lost, otherwise compute the current MSS.
2856c31b70c9SAlexander Duyck 	 */
2857c31b70c9SAlexander Duyck 	if (tp->syn_data && sk->sk_state == TCP_SYN_SENT)
2858c31b70c9SAlexander Duyck 		mss = -1;
2859c31b70c9SAlexander Duyck 	else
2860c31b70c9SAlexander Duyck 		mss = tcp_current_mss(sk);
2861e1aa680fSIlpo Järvinen 
286275c119afSEric Dumazet 	skb_rbtree_walk(skb, &sk->tcp_rtx_queue) {
286368698970SYuchung Cheng 		if (tcp_skb_seglen(skb) > mss)
2864179ac35fSYuchung Cheng 			tcp_mark_skb_lost(sk, skb);
2865e1aa680fSIlpo Järvinen 	}
2866e1aa680fSIlpo Järvinen 
2867e1aa680fSIlpo Järvinen 	tcp_clear_retrans_hints_partial(tp);
2868e1aa680fSIlpo Järvinen 
28690eb96bf7SYuchung Cheng 	if (!tp->lost_out)
2870e1aa680fSIlpo Järvinen 		return;
2871e1aa680fSIlpo Järvinen 
2872e1aa680fSIlpo Järvinen 	if (tcp_is_reno(tp))
2873e1aa680fSIlpo Järvinen 		tcp_limit_reno_sacked(tp);
2874e1aa680fSIlpo Järvinen 
2875e1aa680fSIlpo Järvinen 	tcp_verify_left_out(tp);
2876e1aa680fSIlpo Järvinen 
2877e1aa680fSIlpo Järvinen 	/* Don't muck with the congestion window here.
2878e1aa680fSIlpo Järvinen 	 * Reason is that we do not increase amount of _data_
2879e1aa680fSIlpo Järvinen 	 * in network, but units changed and effective
2880e1aa680fSIlpo Järvinen 	 * cwnd/ssthresh really reduced now.
2881e1aa680fSIlpo Järvinen 	 */
2882b4b26d23SNeal Cardwell 	tcp_non_congestion_loss_retransmit(sk);
2883e1aa680fSIlpo Järvinen }
28844bc2f18bSEric Dumazet EXPORT_SYMBOL(tcp_simple_retransmit);
2885e1aa680fSIlpo Järvinen 
tcp_enter_recovery(struct sock * sk,bool ece_ack)288657dde7f7SYuchung Cheng void tcp_enter_recovery(struct sock *sk, bool ece_ack)
28871fbc3405SYuchung Cheng {
28881fbc3405SYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
28891fbc3405SYuchung Cheng 	int mib_idx;
28901fbc3405SYuchung Cheng 
289104dce9a1SNeal Cardwell 	/* Start the clock with our fast retransmit, for undo and ETIMEDOUT. */
289204dce9a1SNeal Cardwell 	tcp_retrans_stamp_cleanup(sk);
289304dce9a1SNeal Cardwell 
28941fbc3405SYuchung Cheng 	if (tcp_is_reno(tp))
28951fbc3405SYuchung Cheng 		mib_idx = LINUX_MIB_TCPRENORECOVERY;
28961fbc3405SYuchung Cheng 	else
28971fbc3405SYuchung Cheng 		mib_idx = LINUX_MIB_TCPSACKRECOVERY;
28981fbc3405SYuchung Cheng 
2899c10d9310SEric Dumazet 	NET_INC_STATS(sock_net(sk), mib_idx);
29001fbc3405SYuchung Cheng 
29011fbc3405SYuchung Cheng 	tp->prior_ssthresh = 0;
2902989e04c5SYuchung Cheng 	tcp_init_undo(tp);
29031fbc3405SYuchung Cheng 
2904291a00d1SYuchung Cheng 	if (!tcp_in_cwnd_reduction(sk)) {
29051fbc3405SYuchung Cheng 		if (!ece_ack)
29061fbc3405SYuchung Cheng 			tp->prior_ssthresh = tcp_current_ssthresh(sk);
29075ee2c941SChristoph Paasch 		tcp_init_cwnd_reduction(sk);
29081fbc3405SYuchung Cheng 	}
29091fbc3405SYuchung Cheng 	tcp_set_ca_state(sk, TCP_CA_Recovery);
29101fbc3405SYuchung Cheng }
29111fbc3405SYuchung Cheng 
tcp_update_rto_time(struct tcp_sock * tp)2912718c49f8SAananth V static void tcp_update_rto_time(struct tcp_sock *tp)
2913718c49f8SAananth V {
2914718c49f8SAananth V 	if (tp->rto_stamp) {
2915718c49f8SAananth V 		tp->total_rto_time += tcp_time_stamp(tp) - tp->rto_stamp;
2916718c49f8SAananth V 		tp->rto_stamp = 0;
2917718c49f8SAananth V 	}
2918718c49f8SAananth V }
2919718c49f8SAananth V 
2920ab42d9eeSYuchung Cheng /* Process an ACK in CA_Loss state. Move to CA_Open if lost data are
2921ab42d9eeSYuchung Cheng  * recovered or spurious. Otherwise retransmits more on partial ACKs.
2922ab42d9eeSYuchung Cheng  */
tcp_process_loss(struct sock * sk,int flag,int num_dupack,int * rexmit)292319119f29SEric Dumazet static void tcp_process_loss(struct sock *sk, int flag, int num_dupack,
2924e662ca40SYuchung Cheng 			     int *rexmit)
2925ab42d9eeSYuchung Cheng {
2926ab42d9eeSYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
2927e33099f9SYuchung Cheng 	bool recovered = !before(tp->snd_una, tp->high_seq);
2928ab42d9eeSYuchung Cheng 
2929d983ea6fSEric Dumazet 	if ((flag & FLAG_SND_UNA_ADVANCED || rcu_access_pointer(tp->fastopen_rsk)) &&
2930da34ac76SYuchung Cheng 	    tcp_try_undo_loss(sk, false))
2931da34ac76SYuchung Cheng 		return;
2932da34ac76SYuchung Cheng 
2933fc68e171SYuchung Cheng 	if (tp->frto) { /* F-RTO RFC5682 sec 3.1 (sack enhanced version). */
2934fc68e171SYuchung Cheng 		/* Step 3.b. A timeout is spurious if not all data are
2935fc68e171SYuchung Cheng 		 * lost, i.e., never-retransmitted data are (s)acked.
2936e33099f9SYuchung Cheng 		 */
2937da34ac76SYuchung Cheng 		if ((flag & FLAG_ORIG_SACK_ACKED) &&
2938fc68e171SYuchung Cheng 		    tcp_try_undo_loss(sk, true))
2939e33099f9SYuchung Cheng 			return;
29400cfa5c07SYuchung Cheng 
2941b7b0ed91SYuchung Cheng 		if (after(tp->snd_nxt, tp->high_seq)) {
294219119f29SEric Dumazet 			if (flag & FLAG_DATA_SACKED || num_dupack)
2943b7b0ed91SYuchung Cheng 				tp->frto = 0; /* Step 3.a. loss was real */
2944e33099f9SYuchung Cheng 		} else if (flag & FLAG_SND_UNA_ADVANCED && !recovered) {
2945e33099f9SYuchung Cheng 			tp->high_seq = tp->snd_nxt;
2946e662ca40SYuchung Cheng 			/* Step 2.b. Try send new data (but deferred until cwnd
2947e662ca40SYuchung Cheng 			 * is updated in tcp_ack()). Otherwise fall back to
2948e662ca40SYuchung Cheng 			 * the conventional recovery.
2949e662ca40SYuchung Cheng 			 */
295075c119afSEric Dumazet 			if (!tcp_write_queue_empty(sk) &&
2951e662ca40SYuchung Cheng 			    after(tcp_wnd_end(tp), tp->snd_nxt)) {
2952e662ca40SYuchung Cheng 				*rexmit = REXMIT_NEW;
2953e662ca40SYuchung Cheng 				return;
2954e662ca40SYuchung Cheng 			}
2955e33099f9SYuchung Cheng 			tp->frto = 0;
2956e33099f9SYuchung Cheng 		}
2957e33099f9SYuchung Cheng 	}
2958e33099f9SYuchung Cheng 
2959e33099f9SYuchung Cheng 	if (recovered) {
2960e33099f9SYuchung Cheng 		/* F-RTO RFC5682 sec 3.1 step 2.a and 1st part of step 3.a */
2961ab42d9eeSYuchung Cheng 		tcp_try_undo_recovery(sk);
2962ab42d9eeSYuchung Cheng 		return;
2963ab42d9eeSYuchung Cheng 	}
2964e33099f9SYuchung Cheng 	if (tcp_is_reno(tp)) {
2965e33099f9SYuchung Cheng 		/* A Reno DUPACK means new data in F-RTO step 2.b above are
2966304b1875SYueh-Shun Li 		 * delivered. Lower inflight to clock out (re)transmissions.
2967e33099f9SYuchung Cheng 		 */
296819119f29SEric Dumazet 		if (after(tp->snd_nxt, tp->high_seq) && num_dupack)
2969c634e34fSYousuk Seung 			tcp_add_reno_sack(sk, num_dupack, flag & FLAG_ECE);
2970e33099f9SYuchung Cheng 		else if (flag & FLAG_SND_UNA_ADVANCED)
2971ab42d9eeSYuchung Cheng 			tcp_reset_reno_sack(tp);
2972e33099f9SYuchung Cheng 	}
2973e662ca40SYuchung Cheng 	*rexmit = REXMIT_LOST;
2974ab42d9eeSYuchung Cheng }
2975ab42d9eeSYuchung Cheng 
tcp_force_fast_retransmit(struct sock * sk)2976a29cb691SYuchung Cheng static bool tcp_force_fast_retransmit(struct sock *sk)
2977a29cb691SYuchung Cheng {
2978a29cb691SYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
2979a29cb691SYuchung Cheng 
2980a29cb691SYuchung Cheng 	return after(tcp_highest_sack_seq(tp),
2981a29cb691SYuchung Cheng 		     tp->snd_una + tp->reordering * tp->mss_cache);
2982a29cb691SYuchung Cheng }
2983a29cb691SYuchung Cheng 
29846a63df46SYuchung Cheng /* Undo during fast recovery after partial ACK. */
tcp_try_undo_partial(struct sock * sk,u32 prior_snd_una,bool * do_lost)2985a29cb691SYuchung Cheng static bool tcp_try_undo_partial(struct sock *sk, u32 prior_snd_una,
2986a29cb691SYuchung Cheng 				 bool *do_lost)
29876a63df46SYuchung Cheng {
29886a63df46SYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
29896a63df46SYuchung Cheng 
29907026b912SYuchung Cheng 	if (tp->undo_marker && tcp_packet_delayed(tp)) {
29916a63df46SYuchung Cheng 		/* Plain luck! Hole if filled with delayed
2992737ff314SYuchung Cheng 		 * packet, rather than with a retransmit. Check reordering.
29936a63df46SYuchung Cheng 		 */
2994737ff314SYuchung Cheng 		tcp_check_sack_reordering(sk, prior_snd_una, 1);
29957026b912SYuchung Cheng 
29967026b912SYuchung Cheng 		/* We are getting evidence that the reordering degree is higher
29977026b912SYuchung Cheng 		 * than we realized. If there are no retransmits out then we
29987026b912SYuchung Cheng 		 * can undo. Otherwise we clock out new packets but do not
29997026b912SYuchung Cheng 		 * mark more packets lost or retransmit more.
30007026b912SYuchung Cheng 		 */
300131ba0c10SYuchung Cheng 		if (tp->retrans_out)
30027026b912SYuchung Cheng 			return true;
30037026b912SYuchung Cheng 
30046a63df46SYuchung Cheng 		if (!tcp_any_retrans_done(sk))
30056a63df46SYuchung Cheng 			tp->retrans_stamp = 0;
30066a63df46SYuchung Cheng 
30077026b912SYuchung Cheng 		DBGUNDO(sk, "partial recovery");
30087026b912SYuchung Cheng 		tcp_undo_cwnd_reduction(sk, true);
3009c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPPARTIALUNDO);
30107026b912SYuchung Cheng 		tcp_try_keep_open(sk);
3011a29cb691SYuchung Cheng 	} else {
3012a29cb691SYuchung Cheng 		/* Partial ACK arrived. Force fast retransmit. */
3013a29cb691SYuchung Cheng 		*do_lost = tcp_force_fast_retransmit(sk);
30146a63df46SYuchung Cheng 	}
30157026b912SYuchung Cheng 	return false;
30166a63df46SYuchung Cheng }
30176a63df46SYuchung Cheng 
tcp_identify_packet_loss(struct sock * sk,int * ack_flag)30186ac06ecdSYuchung Cheng static void tcp_identify_packet_loss(struct sock *sk, int *ack_flag)
301998e36d44SYuchung Cheng {
302098e36d44SYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
302198e36d44SYuchung Cheng 
30226ac06ecdSYuchung Cheng 	if (tcp_rtx_queue_empty(sk))
30236ac06ecdSYuchung Cheng 		return;
30246ac06ecdSYuchung Cheng 
30256ac06ecdSYuchung Cheng 	if (unlikely(tcp_is_reno(tp))) {
30266ac06ecdSYuchung Cheng 		tcp_newreno_mark_lost(sk, *ack_flag & FLAG_SND_UNA_ADVANCED);
30276ac06ecdSYuchung Cheng 	} else if (tcp_is_rack(sk)) {
302898e36d44SYuchung Cheng 		u32 prior_retrans = tp->retrans_out;
302998e36d44SYuchung Cheng 
303062d9f1a6SPengcheng Yang 		if (tcp_rack_mark_lost(sk))
303162d9f1a6SPengcheng Yang 			*ack_flag &= ~FLAG_SET_XMIT_TIMER;
303298e36d44SYuchung Cheng 		if (prior_retrans > tp->retrans_out)
303398e36d44SYuchung Cheng 			*ack_flag |= FLAG_LOST_RETRANS;
303498e36d44SYuchung Cheng 	}
303598e36d44SYuchung Cheng }
303698e36d44SYuchung Cheng 
30371da177e4SLinus Torvalds /* Process an event, which can update packets-in-flight not trivially.
30381da177e4SLinus Torvalds  * Main goal of this function is to calculate new estimate for left_out,
30391da177e4SLinus Torvalds  * taking into account both packets sitting in receiver's buffer and
30401da177e4SLinus Torvalds  * packets lost by network.
30411da177e4SLinus Torvalds  *
304231ba0c10SYuchung Cheng  * Besides that it updates the congestion state when packet loss or ECN
304331ba0c10SYuchung Cheng  * is detected. But it does not reduce the cwnd, it is done by the
304431ba0c10SYuchung Cheng  * congestion control later.
30451da177e4SLinus Torvalds  *
30461da177e4SLinus Torvalds  * It does _not_ decide what to send, it is made in function
30471da177e4SLinus Torvalds  * tcp_xmit_retransmit_queue().
30481da177e4SLinus Torvalds  */
tcp_fastretrans_alert(struct sock * sk,const u32 prior_snd_una,int num_dupack,int * ack_flag,int * rexmit)3049737ff314SYuchung Cheng static void tcp_fastretrans_alert(struct sock *sk, const u32 prior_snd_una,
305019119f29SEric Dumazet 				  int num_dupack, int *ack_flag, int *rexmit)
30511da177e4SLinus Torvalds {
30526687e988SArnaldo Carvalho de Melo 	struct inet_connection_sock *icsk = inet_csk(sk);
30531da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
305431ba0c10SYuchung Cheng 	int fast_rexmit = 0, flag = *ack_flag;
3055c634e34fSYousuk Seung 	bool ece_ack = flag & FLAG_ECE;
305619119f29SEric Dumazet 	bool do_lost = num_dupack || ((flag & FLAG_DATA_SACKED) &&
3057737ff314SYuchung Cheng 				      tcp_force_fast_retransmit(sk));
30581da177e4SLinus Torvalds 
30598ba6ddaaSEric Dumazet 	if (!tp->packets_out && tp->sacked_out)
30601da177e4SLinus Torvalds 		tp->sacked_out = 0;
30611da177e4SLinus Torvalds 
30621da177e4SLinus Torvalds 	/* Now state machine starts.
30631da177e4SLinus Torvalds 	 * A. ECE, hence prohibit cwnd undoing, the reduction is required. */
3064c634e34fSYousuk Seung 	if (ece_ack)
30651da177e4SLinus Torvalds 		tp->prior_ssthresh = 0;
30661da177e4SLinus Torvalds 
30671da177e4SLinus Torvalds 	/* B. In all the states check for reneging SACKs. */
3068d2a0fc37SFred Chen 	if (tcp_check_sack_reneging(sk, ack_flag))
30691da177e4SLinus Torvalds 		return;
30701da177e4SLinus Torvalds 
3071974c1236SYuchung Cheng 	/* C. Check consistency of the current state. */
3072005903bcSIlpo Järvinen 	tcp_verify_left_out(tp);
30731da177e4SLinus Torvalds 
3074974c1236SYuchung Cheng 	/* D. Check state exit conditions. State can be terminated
30751da177e4SLinus Torvalds 	 *    when high_seq is ACKed. */
30766687e988SArnaldo Carvalho de Melo 	if (icsk->icsk_ca_state == TCP_CA_Open) {
3077a7abf3cdSEric Dumazet 		WARN_ON(tp->retrans_out != 0 && !tp->syn_data);
30781da177e4SLinus Torvalds 		tp->retrans_stamp = 0;
30791da177e4SLinus Torvalds 	} else if (!before(tp->snd_una, tp->high_seq)) {
30806687e988SArnaldo Carvalho de Melo 		switch (icsk->icsk_ca_state) {
30811da177e4SLinus Torvalds 		case TCP_CA_CWR:
30821da177e4SLinus Torvalds 			/* CWR is to be held something *above* high_seq
30831da177e4SLinus Torvalds 			 * is ACKed for CWR bit to reach receiver. */
30841da177e4SLinus Torvalds 			if (tp->snd_una != tp->high_seq) {
3085684bad11SYuchung Cheng 				tcp_end_cwnd_reduction(sk);
30866687e988SArnaldo Carvalho de Melo 				tcp_set_ca_state(sk, TCP_CA_Open);
30871da177e4SLinus Torvalds 			}
30881da177e4SLinus Torvalds 			break;
30891da177e4SLinus Torvalds 
30901da177e4SLinus Torvalds 		case TCP_CA_Recovery:
3091e60402d0SIlpo Järvinen 			if (tcp_is_reno(tp))
30921da177e4SLinus Torvalds 				tcp_reset_reno_sack(tp);
30939e412ba7SIlpo Järvinen 			if (tcp_try_undo_recovery(sk))
30941da177e4SLinus Torvalds 				return;
3095684bad11SYuchung Cheng 			tcp_end_cwnd_reduction(sk);
30961da177e4SLinus Torvalds 			break;
30971da177e4SLinus Torvalds 		}
30981da177e4SLinus Torvalds 	}
30991da177e4SLinus Torvalds 
3100974c1236SYuchung Cheng 	/* E. Process state. */
31016687e988SArnaldo Carvalho de Melo 	switch (icsk->icsk_ca_state) {
31021da177e4SLinus Torvalds 	case TCP_CA_Recovery:
31032e605294SIlpo Järvinen 		if (!(flag & FLAG_SND_UNA_ADVANCED)) {
310419119f29SEric Dumazet 			if (tcp_is_reno(tp))
3105c634e34fSYousuk Seung 				tcp_add_reno_sack(sk, num_dupack, ece_ack);
3106a29cb691SYuchung Cheng 		} else if (tcp_try_undo_partial(sk, prior_snd_una, &do_lost))
31077026b912SYuchung Cheng 			return;
3108a29cb691SYuchung Cheng 
3109a29cb691SYuchung Cheng 		if (tcp_try_undo_dsack(sk))
31108a7fc236SNeal Cardwell 			tcp_try_to_open(sk, flag);
3111a29cb691SYuchung Cheng 
31126ac06ecdSYuchung Cheng 		tcp_identify_packet_loss(sk, ack_flag);
3113a29cb691SYuchung Cheng 		if (icsk->icsk_ca_state != TCP_CA_Recovery) {
3114a29cb691SYuchung Cheng 			if (!tcp_time_to_recover(sk, flag))
3115a29cb691SYuchung Cheng 				return;
3116a29cb691SYuchung Cheng 			/* Undo reverts the recovery state. If loss is evident,
3117a29cb691SYuchung Cheng 			 * starts a new recovery (e.g. reordering then loss);
3118a29cb691SYuchung Cheng 			 */
3119a29cb691SYuchung Cheng 			tcp_enter_recovery(sk, ece_ack);
3120a29cb691SYuchung Cheng 		}
31211da177e4SLinus Torvalds 		break;
31221da177e4SLinus Torvalds 	case TCP_CA_Loss:
312319119f29SEric Dumazet 		tcp_process_loss(sk, flag, num_dupack, rexmit);
3124718c49f8SAananth V 		if (icsk->icsk_ca_state != TCP_CA_Loss)
3125718c49f8SAananth V 			tcp_update_rto_time(tp);
31266ac06ecdSYuchung Cheng 		tcp_identify_packet_loss(sk, ack_flag);
312798e36d44SYuchung Cheng 		if (!(icsk->icsk_ca_state == TCP_CA_Open ||
312898e36d44SYuchung Cheng 		      (*ack_flag & FLAG_LOST_RETRANS)))
31291da177e4SLinus Torvalds 			return;
3130291a00d1SYuchung Cheng 		/* Change state if cwnd is undone or retransmits are lost */
3131a8eceea8SJoe Perches 		fallthrough;
31321da177e4SLinus Torvalds 	default:
3133e60402d0SIlpo Järvinen 		if (tcp_is_reno(tp)) {
31342e605294SIlpo Järvinen 			if (flag & FLAG_SND_UNA_ADVANCED)
31351da177e4SLinus Torvalds 				tcp_reset_reno_sack(tp);
3136c634e34fSYousuk Seung 			tcp_add_reno_sack(sk, num_dupack, ece_ack);
31371da177e4SLinus Torvalds 		}
31381da177e4SLinus Torvalds 
3139f698204bSNeal Cardwell 		if (icsk->icsk_ca_state <= TCP_CA_Disorder)
31409e412ba7SIlpo Järvinen 			tcp_try_undo_dsack(sk);
31411da177e4SLinus Torvalds 
31426ac06ecdSYuchung Cheng 		tcp_identify_packet_loss(sk, ack_flag);
3143750ea2baSYuchung Cheng 		if (!tcp_time_to_recover(sk, flag)) {
314431ba0c10SYuchung Cheng 			tcp_try_to_open(sk, flag);
31451da177e4SLinus Torvalds 			return;
31461da177e4SLinus Torvalds 		}
31471da177e4SLinus Torvalds 
31485d424d5aSJohn Heffner 		/* MTU probe failure: don't reduce cwnd */
31495d424d5aSJohn Heffner 		if (icsk->icsk_ca_state < TCP_CA_CWR &&
31505d424d5aSJohn Heffner 		    icsk->icsk_mtup.probe_size &&
31510e7b1368SJohn Heffner 		    tp->snd_una == tp->mtu_probe.probe_seq_start) {
31525d424d5aSJohn Heffner 			tcp_mtup_probe_failed(sk);
31535d424d5aSJohn Heffner 			/* Restores the reduction we did in tcp_mtup_probe() */
315440570375SEric Dumazet 			tcp_snd_cwnd_set(tp, tcp_snd_cwnd(tp) + 1);
31555d424d5aSJohn Heffner 			tcp_simple_retransmit(sk);
31565d424d5aSJohn Heffner 			return;
31575d424d5aSJohn Heffner 		}
31585d424d5aSJohn Heffner 
31591da177e4SLinus Torvalds 		/* Otherwise enter Recovery state */
3160c634e34fSYousuk Seung 		tcp_enter_recovery(sk, ece_ack);
316185cc391cSIlpo Järvinen 		fast_rexmit = 1;
31621da177e4SLinus Torvalds 	}
31631da177e4SLinus Torvalds 
3164b38a51feSYuchung Cheng 	if (!tcp_is_rack(sk) && do_lost)
316585cc391cSIlpo Järvinen 		tcp_update_scoreboard(sk, fast_rexmit);
3166e662ca40SYuchung Cheng 	*rexmit = REXMIT_LOST;
31671da177e4SLinus Torvalds }
31681da177e4SLinus Torvalds 
tcp_update_rtt_min(struct sock * sk,u32 rtt_us,const int flag)3169eb36be0fSYuchung Cheng static void tcp_update_rtt_min(struct sock *sk, u32 rtt_us, const int flag)
3170f6722583SYuchung Cheng {
31711330ffacSKuniyuki Iwashima 	u32 wlen = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_min_rtt_wlen) * HZ;
317264033892SNeal Cardwell 	struct tcp_sock *tp = tcp_sk(sk);
3173f6722583SYuchung Cheng 
3174eb36be0fSYuchung Cheng 	if ((flag & FLAG_ACK_MAYBE_DELAYED) && rtt_us > tcp_min_rtt(tp)) {
3175eb36be0fSYuchung Cheng 		/* If the remote keeps returning delayed ACKs, eventually
3176eb36be0fSYuchung Cheng 		 * the min filter would pick it up and overestimate the
3177eb36be0fSYuchung Cheng 		 * prop. delay when it expires. Skip suspected delayed ACKs.
3178eb36be0fSYuchung Cheng 		 */
3179eb36be0fSYuchung Cheng 		return;
3180eb36be0fSYuchung Cheng 	}
3181ac9517fcSEric Dumazet 	minmax_running_min(&tp->rtt_min, wlen, tcp_jiffies32,
318264033892SNeal Cardwell 			   rtt_us ? : jiffies_to_usecs(1));
3183f6722583SYuchung Cheng }
3184f6722583SYuchung Cheng 
tcp_ack_update_rtt(struct sock * sk,const int flag,long seq_rtt_us,long sack_rtt_us,long ca_rtt_us,struct rate_sample * rs)3185775e68a9SYuchung Cheng static bool tcp_ack_update_rtt(struct sock *sk, const int flag,
3186f6722583SYuchung Cheng 			       long seq_rtt_us, long sack_rtt_us,
3187775e68a9SYuchung Cheng 			       long ca_rtt_us, struct rate_sample *rs)
318841834b73SIlpo Järvinen {
31895b08e47cSYuchung Cheng 	const struct tcp_sock *tp = tcp_sk(sk);
319041834b73SIlpo Järvinen 
31915b08e47cSYuchung Cheng 	/* Prefer RTT measured from ACK's timing to TS-ECR. This is because
31925b08e47cSYuchung Cheng 	 * broken middle-boxes or peers may corrupt TS-ECR fields. But
31935b08e47cSYuchung Cheng 	 * Karn's algorithm forbids taking RTT if some retransmitted data
31945b08e47cSYuchung Cheng 	 * is acked (RFC6298).
31951da177e4SLinus Torvalds 	 */
3196740b0f18SEric Dumazet 	if (seq_rtt_us < 0)
3197740b0f18SEric Dumazet 		seq_rtt_us = sack_rtt_us;
3198ed08495cSYuchung Cheng 
31991da177e4SLinus Torvalds 	/* RTTM Rule: A TSecr value received in a segment is used to
32001da177e4SLinus Torvalds 	 * update the averaged RTT measurement only if the segment
32011da177e4SLinus Torvalds 	 * acknowledges some new data, i.e., only if it advances the
32021da177e4SLinus Torvalds 	 * left edge of the send window.
32031da177e4SLinus Torvalds 	 * See draft-ietf-tcplw-high-performance-00, section 3.3.
32041da177e4SLinus Torvalds 	 */
3205740b0f18SEric Dumazet 	if (seq_rtt_us < 0 && tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr &&
32069a568de4SEric Dumazet 	    flag & FLAG_ACKED) {
32079a568de4SEric Dumazet 		u32 delta = tcp_time_stamp(tp) - tp->rx_opt.rcv_tsecr;
32089a568de4SEric Dumazet 
32099efdda4eSEric Dumazet 		if (likely(delta < INT_MAX / (USEC_PER_SEC / TCP_TS_HZ))) {
3210730e700eSJianfeng Wang 			if (!delta)
3211730e700eSJianfeng Wang 				delta = 1;
32129efdda4eSEric Dumazet 			seq_rtt_us = delta * (USEC_PER_SEC / TCP_TS_HZ);
32139efdda4eSEric Dumazet 			ca_rtt_us = seq_rtt_us;
32149efdda4eSEric Dumazet 		}
32159a568de4SEric Dumazet 	}
3216775e68a9SYuchung Cheng 	rs->rtt_us = ca_rtt_us; /* RTT of last (S)ACKed packet (or -1) */
3217740b0f18SEric Dumazet 	if (seq_rtt_us < 0)
3218ed08495cSYuchung Cheng 		return false;
32191da177e4SLinus Torvalds 
3220f6722583SYuchung Cheng 	/* ca_rtt_us >= 0 is counting on the invariant that ca_rtt_us is
3221f6722583SYuchung Cheng 	 * always taken together with ACK, SACK, or TS-opts. Any negative
3222f6722583SYuchung Cheng 	 * values will be skipped with the seq_rtt_us < 0 check above.
3223f6722583SYuchung Cheng 	 */
3224eb36be0fSYuchung Cheng 	tcp_update_rtt_min(sk, ca_rtt_us, flag);
3225740b0f18SEric Dumazet 	tcp_rtt_estimator(sk, seq_rtt_us);
32265b08e47cSYuchung Cheng 	tcp_set_rto(sk);
32271da177e4SLinus Torvalds 
32285b08e47cSYuchung Cheng 	/* RFC6298: only reset backoff on valid RTT measurement. */
32295b08e47cSYuchung Cheng 	inet_csk(sk)->icsk_backoff = 0;
3230ed08495cSYuchung Cheng 	return true;
32311da177e4SLinus Torvalds }
32321da177e4SLinus Torvalds 
3233375fe02cSYuchung Cheng /* Compute time elapsed between (last) SYNACK and the ACK completing 3WHS. */
tcp_synack_rtt_meas(struct sock * sk,struct request_sock * req)32340f1c28aeSYuchung Cheng void tcp_synack_rtt_meas(struct sock *sk, struct request_sock *req)
3235375fe02cSYuchung Cheng {
3236775e68a9SYuchung Cheng 	struct rate_sample rs;
32370f1c28aeSYuchung Cheng 	long rtt_us = -1L;
3238375fe02cSYuchung Cheng 
32399a568de4SEric Dumazet 	if (req && !req->num_retrans && tcp_rsk(req)->snt_synack)
32409a568de4SEric Dumazet 		rtt_us = tcp_stamp_us_delta(tcp_clock_us(), tcp_rsk(req)->snt_synack);
3241375fe02cSYuchung Cheng 
3242775e68a9SYuchung Cheng 	tcp_ack_update_rtt(sk, FLAG_SYN_ACKED, rtt_us, -1L, rtt_us, &rs);
32430f1c28aeSYuchung Cheng }
32440f1c28aeSYuchung Cheng 
32450f1c28aeSYuchung Cheng 
tcp_cong_avoid(struct sock * sk,u32 ack,u32 acked)324624901551SEric Dumazet static void tcp_cong_avoid(struct sock *sk, u32 ack, u32 acked)
32471da177e4SLinus Torvalds {
32486687e988SArnaldo Carvalho de Melo 	const struct inet_connection_sock *icsk = inet_csk(sk);
324924901551SEric Dumazet 
325024901551SEric Dumazet 	icsk->icsk_ca_ops->cong_avoid(sk, ack, acked);
3251c2203cf7SEric Dumazet 	tcp_sk(sk)->snd_cwnd_stamp = tcp_jiffies32;
32521da177e4SLinus Torvalds }
32531da177e4SLinus Torvalds 
32541da177e4SLinus Torvalds /* Restart timer after forward progress on connection.
32551da177e4SLinus Torvalds  * RFC2988 recommends to restart timer to now+rto.
32561da177e4SLinus Torvalds  */
tcp_rearm_rto(struct sock * sk)3257750ea2baSYuchung Cheng void tcp_rearm_rto(struct sock *sk)
32581da177e4SLinus Torvalds {
32596ba8a3b1SNandita Dukkipati 	const struct inet_connection_sock *icsk = inet_csk(sk);
3260750ea2baSYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
32619e412ba7SIlpo Järvinen 
3262168a8f58SJerry Chu 	/* If the retrans timer is currently being used by Fast Open
3263168a8f58SJerry Chu 	 * for SYN-ACK retrans purpose, stay put.
3264168a8f58SJerry Chu 	 */
3265d983ea6fSEric Dumazet 	if (rcu_access_pointer(tp->fastopen_rsk))
3266168a8f58SJerry Chu 		return;
3267168a8f58SJerry Chu 
32681da177e4SLinus Torvalds 	if (!tp->packets_out) {
3269463c84b9SArnaldo Carvalho de Melo 		inet_csk_clear_xmit_timer(sk, ICSK_TIME_RETRANS);
32701da177e4SLinus Torvalds 	} else {
3271750ea2baSYuchung Cheng 		u32 rto = inet_csk(sk)->icsk_rto;
3272750ea2baSYuchung Cheng 		/* Offset the time elapsed after installing regular RTO */
3273bec41a11SYuchung Cheng 		if (icsk->icsk_pending == ICSK_TIME_REO_TIMEOUT ||
32746ba8a3b1SNandita Dukkipati 		    icsk->icsk_pending == ICSK_TIME_LOSS_PROBE) {
3275e1a10ef7SNeal Cardwell 			s64 delta_us = tcp_rto_delta_us(sk);
3276b17b8a20SEric Dumazet 			/* delta_us may not be positive if the socket is locked
32776ba8a3b1SNandita Dukkipati 			 * when the retrans timer fires and is rescheduled.
3278750ea2baSYuchung Cheng 			 */
3279cdbeb633SNeal Cardwell 			rto = usecs_to_jiffies(max_t(int, delta_us, 1));
32801da177e4SLinus Torvalds 		}
32813f80e08fSEric Dumazet 		tcp_reset_xmit_timer(sk, ICSK_TIME_RETRANS, rto,
32828dc242adSEric Dumazet 				     TCP_RTO_MAX);
3283750ea2baSYuchung Cheng 	}
3284750ea2baSYuchung Cheng }
3285750ea2baSYuchung Cheng 
3286df92c839SNeal Cardwell /* Try to schedule a loss probe; if that doesn't work, then schedule an RTO. */
tcp_set_xmit_timer(struct sock * sk)3287df92c839SNeal Cardwell static void tcp_set_xmit_timer(struct sock *sk)
3288df92c839SNeal Cardwell {
3289ed66dfafSNeal Cardwell 	if (!tcp_schedule_loss_probe(sk, true))
3290df92c839SNeal Cardwell 		tcp_rearm_rto(sk);
3291df92c839SNeal Cardwell }
3292df92c839SNeal Cardwell 
32937c46a03eSIlpo Järvinen /* If we get here, the whole TSO packet has not been acked. */
tcp_tso_acked(struct sock * sk,struct sk_buff * skb)329413fcf850SIlpo Järvinen static u32 tcp_tso_acked(struct sock *sk, struct sk_buff *skb)
32951da177e4SLinus Torvalds {
32961da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
32977c46a03eSIlpo Järvinen 	u32 packets_acked;
32981da177e4SLinus Torvalds 
32997c46a03eSIlpo Järvinen 	BUG_ON(!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una));
33001da177e4SLinus Torvalds 
33011da177e4SLinus Torvalds 	packets_acked = tcp_skb_pcount(skb);
33027c46a03eSIlpo Järvinen 	if (tcp_trim_head(sk, skb, tp->snd_una - TCP_SKB_CB(skb)->seq))
33031da177e4SLinus Torvalds 		return 0;
33041da177e4SLinus Torvalds 	packets_acked -= tcp_skb_pcount(skb);
33051da177e4SLinus Torvalds 
33061da177e4SLinus Torvalds 	if (packets_acked) {
33071da177e4SLinus Torvalds 		BUG_ON(tcp_skb_pcount(skb) == 0);
33087c46a03eSIlpo Järvinen 		BUG_ON(!before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq));
33091da177e4SLinus Torvalds 	}
33101da177e4SLinus Torvalds 
331113fcf850SIlpo Järvinen 	return packets_acked;
33121da177e4SLinus Torvalds }
33131da177e4SLinus Torvalds 
tcp_ack_tstamp(struct sock * sk,struct sk_buff * skb,const struct sk_buff * ack_skb,u32 prior_snd_una)3314ad971f61SEric Dumazet static void tcp_ack_tstamp(struct sock *sk, struct sk_buff *skb,
3315e7ed11eeSYousuk Seung 			   const struct sk_buff *ack_skb, u32 prior_snd_una)
3316ad971f61SEric Dumazet {
3317ad971f61SEric Dumazet 	const struct skb_shared_info *shinfo;
3318ad971f61SEric Dumazet 
3319ad971f61SEric Dumazet 	/* Avoid cache line misses to get skb_shinfo() and shinfo->tx_flags */
33206b084928SSoheil Hassas Yeganeh 	if (likely(!TCP_SKB_CB(skb)->txstamp_ack))
3321ad971f61SEric Dumazet 		return;
3322ad971f61SEric Dumazet 
3323ad971f61SEric Dumazet 	shinfo = skb_shinfo(skb);
33240a2cf20cSSoheil Hassas Yeganeh 	if (!before(shinfo->tskey, prior_snd_una) &&
3325e2080072SEric Dumazet 	    before(shinfo->tskey, tcp_sk(sk)->snd_una)) {
3326e2080072SEric Dumazet 		tcp_skb_tsorted_save(skb) {
3327e7ed11eeSYousuk Seung 			__skb_tstamp_tx(skb, ack_skb, NULL, sk, SCM_TSTAMP_ACK);
3328e2080072SEric Dumazet 		} tcp_skb_tsorted_restore(skb);
3329e2080072SEric Dumazet 	}
3330ad971f61SEric Dumazet }
3331ad971f61SEric Dumazet 
33327c46a03eSIlpo Järvinen /* Remove acknowledged frames from the retransmission queue. If our packet
33337c46a03eSIlpo Järvinen  * is before the ack sequence we can discard it as it's confirmed to have
33347c46a03eSIlpo Järvinen  * arrived at the other end.
33357c46a03eSIlpo Järvinen  */
tcp_clean_rtx_queue(struct sock * sk,const struct sk_buff * ack_skb,u32 prior_fack,u32 prior_snd_una,struct tcp_sacktag_state * sack,bool ece_ack)3336e7ed11eeSYousuk Seung static int tcp_clean_rtx_queue(struct sock *sk, const struct sk_buff *ack_skb,
3337e7ed11eeSYousuk Seung 			       u32 prior_fack, u32 prior_snd_una,
3338c634e34fSYousuk Seung 			       struct tcp_sacktag_state *sack, bool ece_ack)
33391da177e4SLinus Torvalds {
33402d2abbabSStephen Hemminger 	const struct inet_connection_sock *icsk = inet_csk(sk);
33419a568de4SEric Dumazet 	u64 first_ackt, last_ackt;
3342740b0f18SEric Dumazet 	struct tcp_sock *tp = tcp_sk(sk);
334390638a04SIlpo Järvinen 	u32 prior_sacked = tp->sacked_out;
3344737ff314SYuchung Cheng 	u32 reord = tp->snd_nxt; /* lowest acked un-retx un-sacked seq */
334575c119afSEric Dumazet 	struct sk_buff *skb, *next;
3346740b0f18SEric Dumazet 	bool fully_acked = true;
334731231a8aSKenneth Klette Jonassen 	long sack_rtt_us = -1L;
3348740b0f18SEric Dumazet 	long seq_rtt_us = -1L;
334931231a8aSKenneth Klette Jonassen 	long ca_rtt_us = -1L;
3350740b0f18SEric Dumazet 	u32 pkts_acked = 0;
33512f715c1dSYuchung Cheng 	bool rtt_update;
3352740b0f18SEric Dumazet 	int flag = 0;
3353740b0f18SEric Dumazet 
33549a568de4SEric Dumazet 	first_ackt = 0;
33551da177e4SLinus Torvalds 
335675c119afSEric Dumazet 	for (skb = skb_rb_first(&sk->tcp_rtx_queue); skb; skb = next) {
33571da177e4SLinus Torvalds 		struct tcp_skb_cb *scb = TCP_SKB_CB(skb);
3358737ff314SYuchung Cheng 		const u32 start_seq = scb->seq;
33597c46a03eSIlpo Järvinen 		u8 sacked = scb->sacked;
3360740b0f18SEric Dumazet 		u32 acked_pcount;
33611da177e4SLinus Torvalds 
33622072c228SGavin McCullagh 		/* Determine how many packets and what bytes were acked, tso and else */
33631da177e4SLinus Torvalds 		if (after(scb->end_seq, tp->snd_una)) {
336413fcf850SIlpo Järvinen 			if (tcp_skb_pcount(skb) == 1 ||
336513fcf850SIlpo Järvinen 			    !after(tp->snd_una, scb->seq))
33661da177e4SLinus Torvalds 				break;
336713fcf850SIlpo Järvinen 
336872018835SIlpo Järvinen 			acked_pcount = tcp_tso_acked(sk, skb);
336972018835SIlpo Järvinen 			if (!acked_pcount)
337013fcf850SIlpo Järvinen 				break;
3371a2a385d6SEric Dumazet 			fully_acked = false;
337213fcf850SIlpo Järvinen 		} else {
337372018835SIlpo Järvinen 			acked_pcount = tcp_skb_pcount(skb);
33741da177e4SLinus Torvalds 		}
33751da177e4SLinus Torvalds 
3376ad971f61SEric Dumazet 		if (unlikely(sacked & TCPCB_RETRANS)) {
33771da177e4SLinus Torvalds 			if (sacked & TCPCB_SACKED_RETRANS)
337872018835SIlpo Järvinen 				tp->retrans_out -= acked_pcount;
33797c46a03eSIlpo Järvinen 			flag |= FLAG_RETRANS_DATA_ACKED;
33803d0d26c7SKenneth Klette Jonassen 		} else if (!(sacked & TCPCB_SACKED_ACKED)) {
33812fd66ffbSEric Dumazet 			last_ackt = tcp_skb_timestamp_us(skb);
33829a568de4SEric Dumazet 			WARN_ON_ONCE(last_ackt == 0);
33839a568de4SEric Dumazet 			if (!first_ackt)
3384740b0f18SEric Dumazet 				first_ackt = last_ackt;
3385740b0f18SEric Dumazet 
3386737ff314SYuchung Cheng 			if (before(start_seq, reord))
3387737ff314SYuchung Cheng 				reord = start_seq;
3388e33099f9SYuchung Cheng 			if (!after(scb->end_seq, tp->high_seq))
3389e33099f9SYuchung Cheng 				flag |= FLAG_ORIG_SACK_ACKED;
3390c7caf8d3SIlpo Järvinen 		}
33917c46a03eSIlpo Järvinen 
3392ddf1af6fSYuchung Cheng 		if (sacked & TCPCB_SACKED_ACKED) {
339372018835SIlpo Järvinen 			tp->sacked_out -= acked_pcount;
3394ddf1af6fSYuchung Cheng 		} else if (tcp_is_sack(tp)) {
3395082d4fa9SYousuk Seung 			tcp_count_delivered(tp, acked_pcount, ece_ack);
3396ddf1af6fSYuchung Cheng 			if (!tcp_skb_spurious_retrans(tp, skb))
33971d0833dfSYuchung Cheng 				tcp_rack_advance(tp, sacked, scb->end_seq,
33982fd66ffbSEric Dumazet 						 tcp_skb_timestamp_us(skb));
3399ddf1af6fSYuchung Cheng 		}
34001da177e4SLinus Torvalds 		if (sacked & TCPCB_LOST)
340172018835SIlpo Järvinen 			tp->lost_out -= acked_pcount;
34027c46a03eSIlpo Järvinen 
340372018835SIlpo Järvinen 		tp->packets_out -= acked_pcount;
340472018835SIlpo Järvinen 		pkts_acked += acked_pcount;
3405b9f64820SYuchung Cheng 		tcp_rate_skb_delivered(sk, skb, sack->rate);
340613fcf850SIlpo Järvinen 
3407009a2e3eSIlpo Järvinen 		/* Initial outgoing SYN's get put onto the write_queue
3408009a2e3eSIlpo Järvinen 		 * just like anything else we transmit.  It is not
3409009a2e3eSIlpo Järvinen 		 * true data, and if we misinform our callers that
3410009a2e3eSIlpo Järvinen 		 * this ACK acks real data, we will erroneously exit
3411009a2e3eSIlpo Järvinen 		 * connection startup slow start one packet too
3412009a2e3eSIlpo Järvinen 		 * quickly.  This is severely frowned upon behavior.
3413009a2e3eSIlpo Järvinen 		 */
3414ad971f61SEric Dumazet 		if (likely(!(scb->tcp_flags & TCPHDR_SYN))) {
3415009a2e3eSIlpo Järvinen 			flag |= FLAG_DATA_ACKED;
3416009a2e3eSIlpo Järvinen 		} else {
3417009a2e3eSIlpo Järvinen 			flag |= FLAG_SYN_ACKED;
3418009a2e3eSIlpo Järvinen 			tp->retrans_stamp = 0;
3419009a2e3eSIlpo Järvinen 		}
3420009a2e3eSIlpo Järvinen 
342113fcf850SIlpo Järvinen 		if (!fully_acked)
342213fcf850SIlpo Järvinen 			break;
342313fcf850SIlpo Järvinen 
3424e7ed11eeSYousuk Seung 		tcp_ack_tstamp(sk, skb, ack_skb, prior_snd_una);
3425fdb7eb21SYousuk Seung 
342675c119afSEric Dumazet 		next = skb_rb_next(skb);
3427ad971f61SEric Dumazet 		if (unlikely(skb == tp->retransmit_skb_hint))
3428ef9da47cSIlpo Järvinen 			tp->retransmit_skb_hint = NULL;
3429ad971f61SEric Dumazet 		if (unlikely(skb == tp->lost_skb_hint))
343090638a04SIlpo Järvinen 			tp->lost_skb_hint = NULL;
34312bec445fSEric Dumazet 		tcp_highest_sack_replace(sk, skb, next);
343275c119afSEric Dumazet 		tcp_rtx_queue_unlink_and_free(skb, sk);
34331da177e4SLinus Torvalds 	}
34341da177e4SLinus Torvalds 
34350f87230dSFrancis Yan 	if (!skb)
34360f87230dSFrancis Yan 		tcp_chrono_stop(sk, TCP_CHRONO_BUSY);
34370f87230dSFrancis Yan 
343833f5f57eSIlpo Järvinen 	if (likely(between(tp->snd_up, prior_snd_una, tp->snd_una)))
343933f5f57eSIlpo Järvinen 		tp->snd_up = tp->snd_una;
344033f5f57eSIlpo Järvinen 
3441ff91e929SYousuk Seung 	if (skb) {
3442e7ed11eeSYousuk Seung 		tcp_ack_tstamp(sk, skb, ack_skb, prior_snd_una);
3443ff91e929SYousuk Seung 		if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)
3444cadbd031SIlpo Järvinen 			flag |= FLAG_SACK_RENEGING;
3445ff91e929SYousuk Seung 	}
3446cadbd031SIlpo Järvinen 
34479a568de4SEric Dumazet 	if (likely(first_ackt) && !(flag & FLAG_RETRANS_DATA_ACKED)) {
34489a568de4SEric Dumazet 		seq_rtt_us = tcp_stamp_us_delta(tp->tcp_mstamp, first_ackt);
34499a568de4SEric Dumazet 		ca_rtt_us = tcp_stamp_us_delta(tp->tcp_mstamp, last_ackt);
3450eb36be0fSYuchung Cheng 
345140bc6063SYuchung Cheng 		if (pkts_acked == 1 && fully_acked && !prior_sacked &&
345240bc6063SYuchung Cheng 		    (tp->snd_una - prior_snd_una) < tp->mss_cache &&
3453eb36be0fSYuchung Cheng 		    sack->rate->prior_delivered + 1 == tp->delivered &&
3454eb36be0fSYuchung Cheng 		    !(flag & (FLAG_CA_ALERT | FLAG_SYN_ACKED))) {
3455eb36be0fSYuchung Cheng 			/* Conservatively mark a delayed ACK. It's typically
3456eb36be0fSYuchung Cheng 			 * from a lone runt packet over the round trip to
3457eb36be0fSYuchung Cheng 			 * a receiver w/o out-of-order or CE events.
3458eb36be0fSYuchung Cheng 			 */
3459eb36be0fSYuchung Cheng 			flag |= FLAG_ACK_MAYBE_DELAYED;
3460eb36be0fSYuchung Cheng 		}
346131231a8aSKenneth Klette Jonassen 	}
34629a568de4SEric Dumazet 	if (sack->first_sackt) {
34639a568de4SEric Dumazet 		sack_rtt_us = tcp_stamp_us_delta(tp->tcp_mstamp, sack->first_sackt);
34649a568de4SEric Dumazet 		ca_rtt_us = tcp_stamp_us_delta(tp->tcp_mstamp, sack->last_sackt);
3465740b0f18SEric Dumazet 	}
3466f6722583SYuchung Cheng 	rtt_update = tcp_ack_update_rtt(sk, flag, seq_rtt_us, sack_rtt_us,
3467775e68a9SYuchung Cheng 					ca_rtt_us, sack->rate);
3468ed08495cSYuchung Cheng 
34697c46a03eSIlpo Järvinen 	if (flag & FLAG_ACKED) {
3470df92c839SNeal Cardwell 		flag |= FLAG_SET_XMIT_TIMER;  /* set TLP or RTO timer */
347172211e90SIlpo Järvinen 		if (unlikely(icsk->icsk_mtup.probe_size &&
347272211e90SIlpo Järvinen 			     !after(tp->mtu_probe.probe_seq_end, tp->snd_una))) {
347372211e90SIlpo Järvinen 			tcp_mtup_probe_success(sk);
347472211e90SIlpo Järvinen 		}
347572211e90SIlpo Järvinen 
3476c7caf8d3SIlpo Järvinen 		if (tcp_is_reno(tp)) {
3477c634e34fSYousuk Seung 			tcp_remove_reno_sacks(sk, pkts_acked, ece_ack);
34781236f22fSIlpo Järvinen 
34791236f22fSIlpo Järvinen 			/* If any of the cumulatively ACKed segments was
34801236f22fSIlpo Järvinen 			 * retransmitted, non-SACK case cannot confirm that
34811236f22fSIlpo Järvinen 			 * progress was due to original transmission due to
34821236f22fSIlpo Järvinen 			 * lack of TCPCB_SACKED_ACKED bits even if some of
34831236f22fSIlpo Järvinen 			 * the packets may have been never retransmitted.
34841236f22fSIlpo Järvinen 			 */
34851236f22fSIlpo Järvinen 			if (flag & FLAG_RETRANS_DATA_ACKED)
34861236f22fSIlpo Järvinen 				flag &= ~FLAG_ORIG_SACK_ACKED;
3487c7caf8d3SIlpo Järvinen 		} else {
348859a08cbaSIlpo Järvinen 			int delta;
348959a08cbaSIlpo Järvinen 
3490c7caf8d3SIlpo Järvinen 			/* Non-retransmitted hole got filled? That's reordering */
3491737ff314SYuchung Cheng 			if (before(reord, prior_fack))
3492737ff314SYuchung Cheng 				tcp_check_sack_reordering(sk, reord, 0);
349390638a04SIlpo Järvinen 
3494713bafeaSYuchung Cheng 			delta = prior_sacked - tp->sacked_out;
349559a08cbaSIlpo Järvinen 			tp->lost_cnt_hint -= min(tp->lost_cnt_hint, delta);
3496c7caf8d3SIlpo Järvinen 		}
3497740b0f18SEric Dumazet 	} else if (skb && rtt_update && sack_rtt_us >= 0 &&
34982fd66ffbSEric Dumazet 		   sack_rtt_us > tcp_stamp_us_delta(tp->tcp_mstamp,
34992fd66ffbSEric Dumazet 						    tcp_skb_timestamp_us(skb))) {
35002f715c1dSYuchung Cheng 		/* Do not re-arm RTO if the sack RTT is measured from data sent
35012f715c1dSYuchung Cheng 		 * after when the head was last (re)transmitted. Otherwise the
35022f715c1dSYuchung Cheng 		 * timeout may continue to extend in loss recovery.
35032f715c1dSYuchung Cheng 		 */
3504df92c839SNeal Cardwell 		flag |= FLAG_SET_XMIT_TIMER;  /* set TLP or RTO timer */
35051da177e4SLinus Torvalds 	}
35061da177e4SLinus Torvalds 
3507756ee172SLawrence Brakmo 	if (icsk->icsk_ca_ops->pkts_acked) {
3508756ee172SLawrence Brakmo 		struct ack_sample sample = { .pkts_acked = pkts_acked,
350940bc6063SYuchung Cheng 					     .rtt_us = sack->rate->rtt_us };
3510756ee172SLawrence Brakmo 
351140bc6063SYuchung Cheng 		sample.in_flight = tp->mss_cache *
351240bc6063SYuchung Cheng 			(tp->delivered - sack->rate->prior_delivered);
3513756ee172SLawrence Brakmo 		icsk->icsk_ca_ops->pkts_acked(sk, &sample);
3514756ee172SLawrence Brakmo 	}
3515138998fdSKenneth Klette Jonassen 
35161da177e4SLinus Torvalds #if FASTRETRANS_DEBUG > 0
3517547b792cSIlpo Järvinen 	WARN_ON((int)tp->sacked_out < 0);
3518547b792cSIlpo Järvinen 	WARN_ON((int)tp->lost_out < 0);
3519547b792cSIlpo Järvinen 	WARN_ON((int)tp->retrans_out < 0);
3520e60402d0SIlpo Järvinen 	if (!tp->packets_out && tcp_is_sack(tp)) {
3521cfcabdccSStephen Hemminger 		icsk = inet_csk(sk);
35221da177e4SLinus Torvalds 		if (tp->lost_out) {
352391df42beSJoe Perches 			pr_debug("Leak l=%u %d\n",
35246687e988SArnaldo Carvalho de Melo 				 tp->lost_out, icsk->icsk_ca_state);
35251da177e4SLinus Torvalds 			tp->lost_out = 0;
35261da177e4SLinus Torvalds 		}
35271da177e4SLinus Torvalds 		if (tp->sacked_out) {
352891df42beSJoe Perches 			pr_debug("Leak s=%u %d\n",
35296687e988SArnaldo Carvalho de Melo 				 tp->sacked_out, icsk->icsk_ca_state);
35301da177e4SLinus Torvalds 			tp->sacked_out = 0;
35311da177e4SLinus Torvalds 		}
35321da177e4SLinus Torvalds 		if (tp->retrans_out) {
353391df42beSJoe Perches 			pr_debug("Leak r=%u %d\n",
35346687e988SArnaldo Carvalho de Melo 				 tp->retrans_out, icsk->icsk_ca_state);
35351da177e4SLinus Torvalds 			tp->retrans_out = 0;
35361da177e4SLinus Torvalds 		}
35371da177e4SLinus Torvalds 	}
35381da177e4SLinus Torvalds #endif
35397c46a03eSIlpo Järvinen 	return flag;
35401da177e4SLinus Torvalds }
35411da177e4SLinus Torvalds 
tcp_ack_probe(struct sock * sk)35421da177e4SLinus Torvalds static void tcp_ack_probe(struct sock *sk)
35431da177e4SLinus Torvalds {
3544463c84b9SArnaldo Carvalho de Melo 	struct inet_connection_sock *icsk = inet_csk(sk);
354575c119afSEric Dumazet 	struct sk_buff *head = tcp_send_head(sk);
354675c119afSEric Dumazet 	const struct tcp_sock *tp = tcp_sk(sk);
35471da177e4SLinus Torvalds 
35481da177e4SLinus Torvalds 	/* Was it a usable window open? */
354975c119afSEric Dumazet 	if (!head)
355075c119afSEric Dumazet 		return;
355175c119afSEric Dumazet 	if (!after(TCP_SKB_CB(head)->end_seq, tcp_wnd_end(tp))) {
3552463c84b9SArnaldo Carvalho de Melo 		icsk->icsk_backoff = 0;
35539d9b1ee0SEnke Chen 		icsk->icsk_probes_tstamp = 0;
3554463c84b9SArnaldo Carvalho de Melo 		inet_csk_clear_xmit_timer(sk, ICSK_TIME_PROBE0);
35551da177e4SLinus Torvalds 		/* Socket must be waked up by subsequent tcp_data_snd_check().
35561da177e4SLinus Torvalds 		 * This function is not for random using!
35571da177e4SLinus Torvalds 		 */
35581da177e4SLinus Torvalds 	} else {
355921c8fe99SEric Dumazet 		unsigned long when = tcp_probe0_when(sk, TCP_RTO_MAX);
3560fcdd1cf4SEric Dumazet 
3561344db93aSEnke Chen 		when = tcp_clamp_probe0_to_user_timeout(sk, when);
3562344db93aSEnke Chen 		tcp_reset_xmit_timer(sk, ICSK_TIME_PROBE0, when, TCP_RTO_MAX);
35631da177e4SLinus Torvalds 	}
35641da177e4SLinus Torvalds }
35651da177e4SLinus Torvalds 
tcp_ack_is_dubious(const struct sock * sk,const int flag)356667b95bd7SVijay Subramanian static inline bool tcp_ack_is_dubious(const struct sock *sk, const int flag)
35671da177e4SLinus Torvalds {
3568a02cec21SEric Dumazet 	return !(flag & FLAG_NOT_DUP) || (flag & FLAG_CA_ALERT) ||
3569a02cec21SEric Dumazet 		inet_csk(sk)->icsk_ca_state != TCP_CA_Open;
35701da177e4SLinus Torvalds }
35711da177e4SLinus Torvalds 
35720f7cc9a3SYuchung Cheng /* Decide wheather to run the increase function of congestion control. */
tcp_may_raise_cwnd(const struct sock * sk,const int flag)357367b95bd7SVijay Subramanian static inline bool tcp_may_raise_cwnd(const struct sock *sk, const int flag)
35741da177e4SLinus Torvalds {
35750f7cc9a3SYuchung Cheng 	/* If reordering is high then always grow cwnd whenever data is
35760f7cc9a3SYuchung Cheng 	 * delivered regardless of its ordering. Otherwise stay conservative
357716edfe7eSYuchung Cheng 	 * and only grow cwnd on in-order delivery (RFC5681). A stretched ACK w/
35780f7cc9a3SYuchung Cheng 	 * new SACK or ECE mark may first advance cwnd here and later reduce
35790f7cc9a3SYuchung Cheng 	 * cwnd in tcp_fastretrans_alert() based on more states.
35800f7cc9a3SYuchung Cheng 	 */
358146778cd1SKuniyuki Iwashima 	if (tcp_sk(sk)->reordering >
358246778cd1SKuniyuki Iwashima 	    READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_reordering))
35830f7cc9a3SYuchung Cheng 		return flag & FLAG_FORWARD_PROGRESS;
35840f7cc9a3SYuchung Cheng 
358516edfe7eSYuchung Cheng 	return flag & FLAG_DATA_ACKED;
35861da177e4SLinus Torvalds }
35871da177e4SLinus Torvalds 
3588d452e6caSYuchung Cheng /* The "ultimate" congestion control function that aims to replace the rigid
3589d452e6caSYuchung Cheng  * cwnd increase and decrease control (tcp_cong_avoid,tcp_*cwnd_reduction).
3590d452e6caSYuchung Cheng  * It's called toward the end of processing an ACK with precise rate
3591d452e6caSYuchung Cheng  * information. All transmission or retransmission are delayed afterwards.
3592d452e6caSYuchung Cheng  */
tcp_cong_control(struct sock * sk,u32 ack,u32 acked_sacked,int flag,const struct rate_sample * rs)3593d452e6caSYuchung Cheng static void tcp_cong_control(struct sock *sk, u32 ack, u32 acked_sacked,
3594c0402760SYuchung Cheng 			     int flag, const struct rate_sample *rs)
3595d452e6caSYuchung Cheng {
3596c0402760SYuchung Cheng 	const struct inet_connection_sock *icsk = inet_csk(sk);
3597c0402760SYuchung Cheng 
3598c0402760SYuchung Cheng 	if (icsk->icsk_ca_ops->cong_control) {
3599c0402760SYuchung Cheng 		icsk->icsk_ca_ops->cong_control(sk, rs);
3600c0402760SYuchung Cheng 		return;
3601c0402760SYuchung Cheng 	}
3602c0402760SYuchung Cheng 
3603d452e6caSYuchung Cheng 	if (tcp_in_cwnd_reduction(sk)) {
3604d452e6caSYuchung Cheng 		/* Reduce cwnd if state mandates */
36057e901ee7SYuchung Cheng 		tcp_cwnd_reduction(sk, acked_sacked, rs->losses, flag);
3606d452e6caSYuchung Cheng 	} else if (tcp_may_raise_cwnd(sk, flag)) {
3607d452e6caSYuchung Cheng 		/* Advance cwnd if state allows */
3608d452e6caSYuchung Cheng 		tcp_cong_avoid(sk, ack, acked_sacked);
3609d452e6caSYuchung Cheng 	}
3610d452e6caSYuchung Cheng 	tcp_update_pacing_rate(sk);
3611d452e6caSYuchung Cheng }
3612d452e6caSYuchung Cheng 
36131da177e4SLinus Torvalds /* Check that window update is acceptable.
36141da177e4SLinus Torvalds  * The function assumes that snd_una<=ack<=snd_next.
36151da177e4SLinus Torvalds  */
tcp_may_update_window(const struct tcp_sock * tp,const u32 ack,const u32 ack_seq,const u32 nwin)361667b95bd7SVijay Subramanian static inline bool tcp_may_update_window(const struct tcp_sock *tp,
3617056834d9SIlpo Järvinen 					const u32 ack, const u32 ack_seq,
3618056834d9SIlpo Järvinen 					const u32 nwin)
36191da177e4SLinus Torvalds {
3620a02cec21SEric Dumazet 	return	after(ack, tp->snd_una) ||
36211da177e4SLinus Torvalds 		after(ack_seq, tp->snd_wl1) ||
3622800a6661SMenglong Dong 		(ack_seq == tp->snd_wl1 && (nwin > tp->snd_wnd || !nwin));
36231da177e4SLinus Torvalds }
36241da177e4SLinus Torvalds 
36250df48c26SEric Dumazet /* If we update tp->snd_una, also update tp->bytes_acked */
tcp_snd_una_update(struct tcp_sock * tp,u32 ack)36260df48c26SEric Dumazet static void tcp_snd_una_update(struct tcp_sock *tp, u32 ack)
36270df48c26SEric Dumazet {
36280df48c26SEric Dumazet 	u32 delta = ack - tp->snd_una;
36290df48c26SEric Dumazet 
363046cc6e49SEric Dumazet 	sock_owned_by_me((struct sock *)tp);
36310df48c26SEric Dumazet 	tp->bytes_acked += delta;
36320df48c26SEric Dumazet 	tp->snd_una = ack;
36330df48c26SEric Dumazet }
36340df48c26SEric Dumazet 
3635bdd1f9edSEric Dumazet /* If we update tp->rcv_nxt, also update tp->bytes_received */
tcp_rcv_nxt_update(struct tcp_sock * tp,u32 seq)3636bdd1f9edSEric Dumazet static void tcp_rcv_nxt_update(struct tcp_sock *tp, u32 seq)
3637bdd1f9edSEric Dumazet {
3638bdd1f9edSEric Dumazet 	u32 delta = seq - tp->rcv_nxt;
3639bdd1f9edSEric Dumazet 
364046cc6e49SEric Dumazet 	sock_owned_by_me((struct sock *)tp);
3641bdd1f9edSEric Dumazet 	tp->bytes_received += delta;
3642dba7d9b8SEric Dumazet 	WRITE_ONCE(tp->rcv_nxt, seq);
3643bdd1f9edSEric Dumazet }
3644bdd1f9edSEric Dumazet 
36451da177e4SLinus Torvalds /* Update our send window.
36461da177e4SLinus Torvalds  *
36471da177e4SLinus Torvalds  * Window update algorithm, described in RFC793/RFC1122 (used in linux-2.2
36481da177e4SLinus Torvalds  * and in FreeBSD. NetBSD's one is even worse.) is wrong.
36491da177e4SLinus Torvalds  */
tcp_ack_update_window(struct sock * sk,const struct sk_buff * skb,u32 ack,u32 ack_seq)3650cf533ea5SEric Dumazet static int tcp_ack_update_window(struct sock *sk, const struct sk_buff *skb, u32 ack,
36519e412ba7SIlpo Järvinen 				 u32 ack_seq)
36521da177e4SLinus Torvalds {
36539e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
36541da177e4SLinus Torvalds 	int flag = 0;
3655aa8223c7SArnaldo Carvalho de Melo 	u32 nwin = ntohs(tcp_hdr(skb)->window);
36561da177e4SLinus Torvalds 
3657aa8223c7SArnaldo Carvalho de Melo 	if (likely(!tcp_hdr(skb)->syn))
36581da177e4SLinus Torvalds 		nwin <<= tp->rx_opt.snd_wscale;
36591da177e4SLinus Torvalds 
36601da177e4SLinus Torvalds 	if (tcp_may_update_window(tp, ack, ack_seq, nwin)) {
36611da177e4SLinus Torvalds 		flag |= FLAG_WIN_UPDATE;
3662ee7537b6SHantzis Fotis 		tcp_update_wl(tp, ack_seq);
36631da177e4SLinus Torvalds 
36641da177e4SLinus Torvalds 		if (tp->snd_wnd != nwin) {
36651da177e4SLinus Torvalds 			tp->snd_wnd = nwin;
36661da177e4SLinus Torvalds 
366731770e34SFlorian Westphal 			/* Note, it is the only place, where
366831770e34SFlorian Westphal 			 * fast path is recovered for sending TCP.
366931770e34SFlorian Westphal 			 */
367031770e34SFlorian Westphal 			tp->pred_flags = 0;
367131770e34SFlorian Westphal 			tcp_fast_path_check(sk);
367231770e34SFlorian Westphal 
367375c119afSEric Dumazet 			if (!tcp_write_queue_empty(sk))
36746f021c62SEric Dumazet 				tcp_slow_start_after_idle_check(sk);
36756f021c62SEric Dumazet 
36761da177e4SLinus Torvalds 			if (nwin > tp->max_window) {
36771da177e4SLinus Torvalds 				tp->max_window = nwin;
3678d83d8461SArnaldo Carvalho de Melo 				tcp_sync_mss(sk, inet_csk(sk)->icsk_pmtu_cookie);
36791da177e4SLinus Torvalds 			}
36801da177e4SLinus Torvalds 		}
36811da177e4SLinus Torvalds 	}
36821da177e4SLinus Torvalds 
36830df48c26SEric Dumazet 	tcp_snd_una_update(tp, ack);
36841da177e4SLinus Torvalds 
36851da177e4SLinus Torvalds 	return flag;
36861da177e4SLinus Torvalds }
36871da177e4SLinus Torvalds 
__tcp_oow_rate_limited(struct net * net,int mib_idx,u32 * last_oow_ack_time)3688083ae308SJason Baron static bool __tcp_oow_rate_limited(struct net *net, int mib_idx,
3689083ae308SJason Baron 				   u32 *last_oow_ack_time)
3690083ae308SJason Baron {
3691998127cdSEric Dumazet 	/* Paired with the WRITE_ONCE() in this function. */
3692998127cdSEric Dumazet 	u32 val = READ_ONCE(*last_oow_ack_time);
3693998127cdSEric Dumazet 
3694998127cdSEric Dumazet 	if (val) {
3695998127cdSEric Dumazet 		s32 elapsed = (s32)(tcp_jiffies32 - val);
3696083ae308SJason Baron 
36972afdbe7bSKuniyuki Iwashima 		if (0 <= elapsed &&
36982afdbe7bSKuniyuki Iwashima 		    elapsed < READ_ONCE(net->ipv4.sysctl_tcp_invalid_ratelimit)) {
3699083ae308SJason Baron 			NET_INC_STATS(net, mib_idx);
3700083ae308SJason Baron 			return true;	/* rate-limited: don't send yet! */
3701083ae308SJason Baron 		}
3702083ae308SJason Baron 	}
3703083ae308SJason Baron 
3704998127cdSEric Dumazet 	/* Paired with the prior READ_ONCE() and with itself,
3705998127cdSEric Dumazet 	 * as we might be lockless.
3706998127cdSEric Dumazet 	 */
3707998127cdSEric Dumazet 	WRITE_ONCE(*last_oow_ack_time, tcp_jiffies32);
3708083ae308SJason Baron 
3709083ae308SJason Baron 	return false;	/* not rate-limited: go ahead, send dupack now! */
3710083ae308SJason Baron }
3711083ae308SJason Baron 
37127970ddc8SEric Dumazet /* Return true if we're currently rate-limiting out-of-window ACKs and
37137970ddc8SEric Dumazet  * thus shouldn't send a dupack right now. We rate-limit dupacks in
37147970ddc8SEric Dumazet  * response to out-of-window SYNs or ACKs to mitigate ACK loops or DoS
37157970ddc8SEric Dumazet  * attacks that send repeated SYNs or ACKs for the same connection. To
37167970ddc8SEric Dumazet  * do this, we do not send a duplicate SYNACK or ACK if the remote
37177970ddc8SEric Dumazet  * endpoint is sending out-of-window SYNs or pure ACKs at a high rate.
37187970ddc8SEric Dumazet  */
tcp_oow_rate_limited(struct net * net,const struct sk_buff * skb,int mib_idx,u32 * last_oow_ack_time)37197970ddc8SEric Dumazet bool tcp_oow_rate_limited(struct net *net, const struct sk_buff *skb,
37207970ddc8SEric Dumazet 			  int mib_idx, u32 *last_oow_ack_time)
37217970ddc8SEric Dumazet {
37227970ddc8SEric Dumazet 	/* Data packets without SYNs are not likely part of an ACK loop. */
37237970ddc8SEric Dumazet 	if ((TCP_SKB_CB(skb)->seq != TCP_SKB_CB(skb)->end_seq) &&
37247970ddc8SEric Dumazet 	    !tcp_hdr(skb)->syn)
3725083ae308SJason Baron 		return false;
37267970ddc8SEric Dumazet 
3727083ae308SJason Baron 	return __tcp_oow_rate_limited(net, mib_idx, last_oow_ack_time);
37287970ddc8SEric Dumazet }
37297970ddc8SEric Dumazet 
3730354e4aa3SEric Dumazet /* RFC 5961 7 [ACK Throttling] */
tcp_send_challenge_ack(struct sock * sk)3731208dd45dSBenjamin Yim static void tcp_send_challenge_ack(struct sock *sk)
3732354e4aa3SEric Dumazet {
3733f2b2c582SNeal Cardwell 	struct tcp_sock *tp = tcp_sk(sk);
3734b530b681SEric Dumazet 	struct net *net = sock_net(sk);
373579e3602cSEric Dumazet 	u32 count, now, ack_limit;
3736354e4aa3SEric Dumazet 
3737f2b2c582SNeal Cardwell 	/* First check our per-socket dupack rate limit. */
3738b530b681SEric Dumazet 	if (__tcp_oow_rate_limited(net,
3739f2b2c582SNeal Cardwell 				   LINUX_MIB_TCPACKSKIPPEDCHALLENGE,
3740f2b2c582SNeal Cardwell 				   &tp->last_oow_ack_time))
3741f2b2c582SNeal Cardwell 		return;
3742f2b2c582SNeal Cardwell 
374379e3602cSEric Dumazet 	ack_limit = READ_ONCE(net->ipv4.sysctl_tcp_challenge_ack_limit);
374479e3602cSEric Dumazet 	if (ack_limit == INT_MAX)
374579e3602cSEric Dumazet 		goto send_ack;
374679e3602cSEric Dumazet 
374775ff39ccSEric Dumazet 	/* Then check host-wide RFC 5961 rate limit. */
3748f2b2c582SNeal Cardwell 	now = jiffies / HZ;
374979e3602cSEric Dumazet 	if (now != READ_ONCE(net->ipv4.tcp_challenge_timestamp)) {
3750b530b681SEric Dumazet 		u32 half = (ack_limit + 1) >> 1;
375175ff39ccSEric Dumazet 
375279e3602cSEric Dumazet 		WRITE_ONCE(net->ipv4.tcp_challenge_timestamp, now);
37538032bf12SJason A. Donenfeld 		WRITE_ONCE(net->ipv4.tcp_challenge_count,
3754e8a533cbSJason A. Donenfeld 			   get_random_u32_inclusive(half, ack_limit + half - 1));
3755354e4aa3SEric Dumazet 	}
375679e3602cSEric Dumazet 	count = READ_ONCE(net->ipv4.tcp_challenge_count);
375775ff39ccSEric Dumazet 	if (count > 0) {
375879e3602cSEric Dumazet 		WRITE_ONCE(net->ipv4.tcp_challenge_count, count - 1);
375979e3602cSEric Dumazet send_ack:
3760b530b681SEric Dumazet 		NET_INC_STATS(net, LINUX_MIB_TCPCHALLENGEACK);
3761354e4aa3SEric Dumazet 		tcp_send_ack(sk);
3762354e4aa3SEric Dumazet 	}
3763354e4aa3SEric Dumazet }
3764354e4aa3SEric Dumazet 
tcp_store_ts_recent(struct tcp_sock * tp)376512fb3dd9SEric Dumazet static void tcp_store_ts_recent(struct tcp_sock *tp)
376612fb3dd9SEric Dumazet {
376712fb3dd9SEric Dumazet 	tp->rx_opt.ts_recent = tp->rx_opt.rcv_tsval;
3768cca9bab1SArnd Bergmann 	tp->rx_opt.ts_recent_stamp = ktime_get_seconds();
376912fb3dd9SEric Dumazet }
377012fb3dd9SEric Dumazet 
tcp_replace_ts_recent(struct tcp_sock * tp,u32 seq)377112fb3dd9SEric Dumazet static void tcp_replace_ts_recent(struct tcp_sock *tp, u32 seq)
377212fb3dd9SEric Dumazet {
377312fb3dd9SEric Dumazet 	if (tp->rx_opt.saw_tstamp && !after(seq, tp->rcv_wup)) {
377412fb3dd9SEric Dumazet 		/* PAWS bug workaround wrt. ACK frames, the PAWS discard
377512fb3dd9SEric Dumazet 		 * extra check below makes sure this can only happen
377612fb3dd9SEric Dumazet 		 * for pure ACK frames.  -DaveM
377712fb3dd9SEric Dumazet 		 *
377812fb3dd9SEric Dumazet 		 * Not only, also it occurs for expired timestamps.
377912fb3dd9SEric Dumazet 		 */
378012fb3dd9SEric Dumazet 
378112fb3dd9SEric Dumazet 		if (tcp_paws_check(&tp->rx_opt, 0))
378212fb3dd9SEric Dumazet 			tcp_store_ts_recent(tp);
378312fb3dd9SEric Dumazet 	}
378412fb3dd9SEric Dumazet }
378512fb3dd9SEric Dumazet 
378676be93fcSYuchung Cheng /* This routine deals with acks during a TLP episode and ends an episode by
378776be93fcSYuchung Cheng  * resetting tlp_high_seq. Ref: TLP algorithm in draft-ietf-tcpm-rack
37889b717a8dSNandita Dukkipati  */
tcp_process_tlp_ack(struct sock * sk,u32 ack,int flag)37899b717a8dSNandita Dukkipati static void tcp_process_tlp_ack(struct sock *sk, u32 ack, int flag)
37909b717a8dSNandita Dukkipati {
37919b717a8dSNandita Dukkipati 	struct tcp_sock *tp = tcp_sk(sk);
37929b717a8dSNandita Dukkipati 
379308abdffaSSébastien Barré 	if (before(ack, tp->tlp_high_seq))
37949b717a8dSNandita Dukkipati 		return;
37959b717a8dSNandita Dukkipati 
379676be93fcSYuchung Cheng 	if (!tp->tlp_retrans) {
379776be93fcSYuchung Cheng 		/* TLP of new data has been acknowledged */
379876be93fcSYuchung Cheng 		tp->tlp_high_seq = 0;
379963f367d9SYuchung Cheng 	} else if (flag & FLAG_DSACK_TLP) {
380008abdffaSSébastien Barré 		/* This DSACK means original and TLP probe arrived; no loss */
38019b717a8dSNandita Dukkipati 		tp->tlp_high_seq = 0;
380208abdffaSSébastien Barré 	} else if (after(ack, tp->tlp_high_seq)) {
380308abdffaSSébastien Barré 		/* ACK advances: there was a loss, so reduce cwnd. Reset
380408abdffaSSébastien Barré 		 * tlp_high_seq in tcp_init_cwnd_reduction()
380508abdffaSSébastien Barré 		 */
38065ee2c941SChristoph Paasch 		tcp_init_cwnd_reduction(sk);
38079b717a8dSNandita Dukkipati 		tcp_set_ca_state(sk, TCP_CA_CWR);
38089b717a8dSNandita Dukkipati 		tcp_end_cwnd_reduction(sk);
3809031afe49SYuchung Cheng 		tcp_try_keep_open(sk);
3810c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk),
38119b717a8dSNandita Dukkipati 				LINUX_MIB_TCPLOSSPROBERECOVERY);
381208abdffaSSébastien Barré 	} else if (!(flag & (FLAG_SND_UNA_ADVANCED |
381308abdffaSSébastien Barré 			     FLAG_NOT_DUP | FLAG_DATA_SACKED))) {
381408abdffaSSébastien Barré 		/* Pure dupack: original and TLP probe arrived; no loss */
381508abdffaSSébastien Barré 		tp->tlp_high_seq = 0;
38169b717a8dSNandita Dukkipati 	}
38179b717a8dSNandita Dukkipati }
38189b717a8dSNandita Dukkipati 
tcp_in_ack_event(struct sock * sk,u32 flags)38197354c8c3SFlorian Westphal static inline void tcp_in_ack_event(struct sock *sk, u32 flags)
38207354c8c3SFlorian Westphal {
38217354c8c3SFlorian Westphal 	const struct inet_connection_sock *icsk = inet_csk(sk);
38227354c8c3SFlorian Westphal 
38237354c8c3SFlorian Westphal 	if (icsk->icsk_ca_ops->in_ack_event)
38247354c8c3SFlorian Westphal 		icsk->icsk_ca_ops->in_ack_event(sk, flags);
38257354c8c3SFlorian Westphal }
38267354c8c3SFlorian Westphal 
3827e662ca40SYuchung Cheng /* Congestion control has updated the cwnd already. So if we're in
3828e662ca40SYuchung Cheng  * loss recovery then now we do any new sends (for FRTO) or
3829e662ca40SYuchung Cheng  * retransmits (for CA_Loss or CA_recovery) that make sense.
3830e662ca40SYuchung Cheng  */
tcp_xmit_recovery(struct sock * sk,int rexmit)3831e662ca40SYuchung Cheng static void tcp_xmit_recovery(struct sock *sk, int rexmit)
3832e662ca40SYuchung Cheng {
3833e662ca40SYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
3834e662ca40SYuchung Cheng 
3835bc9f38c8SYuchung Cheng 	if (rexmit == REXMIT_NONE || sk->sk_state == TCP_SYN_SENT)
3836e662ca40SYuchung Cheng 		return;
3837e662ca40SYuchung Cheng 
3838d0e8bcafSMao Wenan 	if (unlikely(rexmit == REXMIT_NEW)) {
3839e662ca40SYuchung Cheng 		__tcp_push_pending_frames(sk, tcp_current_mss(sk),
3840e662ca40SYuchung Cheng 					  TCP_NAGLE_OFF);
3841e662ca40SYuchung Cheng 		if (after(tp->snd_nxt, tp->high_seq))
3842e662ca40SYuchung Cheng 			return;
3843e662ca40SYuchung Cheng 		tp->frto = 0;
3844e662ca40SYuchung Cheng 	}
3845e662ca40SYuchung Cheng 	tcp_xmit_retransmit_queue(sk);
3846e662ca40SYuchung Cheng }
3847e662ca40SYuchung Cheng 
3848a77fa010SYuchung Cheng /* Returns the number of packets newly acked or sacked by the current ACK */
tcp_newly_delivered(struct sock * sk,u32 prior_delivered,int flag)3849a77fa010SYuchung Cheng static u32 tcp_newly_delivered(struct sock *sk, u32 prior_delivered, int flag)
3850a77fa010SYuchung Cheng {
3851feb5f2ecSYuchung Cheng 	const struct net *net = sock_net(sk);
3852a77fa010SYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
3853a77fa010SYuchung Cheng 	u32 delivered;
3854a77fa010SYuchung Cheng 
3855a77fa010SYuchung Cheng 	delivered = tp->delivered - prior_delivered;
3856feb5f2ecSYuchung Cheng 	NET_ADD_STATS(net, LINUX_MIB_TCPDELIVERED, delivered);
3857082d4fa9SYousuk Seung 	if (flag & FLAG_ECE)
3858feb5f2ecSYuchung Cheng 		NET_ADD_STATS(net, LINUX_MIB_TCPDELIVEREDCE, delivered);
3859082d4fa9SYousuk Seung 
3860a77fa010SYuchung Cheng 	return delivered;
3861a77fa010SYuchung Cheng }
3862a77fa010SYuchung Cheng 
38631da177e4SLinus Torvalds /* This routine deals with incoming acks, but not outgoing ones. */
tcp_ack(struct sock * sk,const struct sk_buff * skb,int flag)3864cf533ea5SEric Dumazet static int tcp_ack(struct sock *sk, const struct sk_buff *skb, int flag)
38651da177e4SLinus Torvalds {
38666687e988SArnaldo Carvalho de Melo 	struct inet_connection_sock *icsk = inet_csk(sk);
38671da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
3868196da974SKenneth Klette Jonassen 	struct tcp_sacktag_state sack_state;
3869b9f64820SYuchung Cheng 	struct rate_sample rs = { .prior_delivered = 0 };
38701da177e4SLinus Torvalds 	u32 prior_snd_una = tp->snd_una;
3871d4761754SYousuk Seung 	bool is_sack_reneg = tp->is_sack_reneg;
38721da177e4SLinus Torvalds 	u32 ack_seq = TCP_SKB_CB(skb)->seq;
38731da177e4SLinus Torvalds 	u32 ack = TCP_SKB_CB(skb)->ack_seq;
387419119f29SEric Dumazet 	int num_dupack = 0;
387535f079ebSNandita Dukkipati 	int prior_packets = tp->packets_out;
3876b9f64820SYuchung Cheng 	u32 delivered = tp->delivered;
3877b9f64820SYuchung Cheng 	u32 lost = tp->lost;
3878e662ca40SYuchung Cheng 	int rexmit = REXMIT_NONE; /* Flag to (re)transmit to recover losses */
3879737ff314SYuchung Cheng 	u32 prior_fack;
3880196da974SKenneth Klette Jonassen 
38819a568de4SEric Dumazet 	sack_state.first_sackt = 0;
3882b9f64820SYuchung Cheng 	sack_state.rate = &rs;
3883f00394ceSYousuk Seung 	sack_state.sack_delivered = 0;
38841da177e4SLinus Torvalds 
388575c119afSEric Dumazet 	/* We very likely will need to access rtx queue. */
388675c119afSEric Dumazet 	prefetch(sk->tcp_rtx_queue.rb_node);
3887ad971f61SEric Dumazet 
388896e0bf4bSJohn Dykstra 	/* If the ack is older than previous acks
38891da177e4SLinus Torvalds 	 * then we can probably ignore it.
38901da177e4SLinus Torvalds 	 */
3891354e4aa3SEric Dumazet 	if (before(ack, prior_snd_una)) {
38922087d53aSEric Dumazet 		u32 max_window;
38932087d53aSEric Dumazet 
38942087d53aSEric Dumazet 		/* do not accept ACK for bytes we never sent. */
38952087d53aSEric Dumazet 		max_window = min_t(u64, tp->max_window, tp->bytes_acked);
3896354e4aa3SEric Dumazet 		/* RFC 5961 5.2 [Blind Data Injection Attack].[Mitigation] */
38972087d53aSEric Dumazet 		if (before(ack, prior_snd_una - max_window)) {
3898d0e1a1b5SEric Dumazet 			if (!(flag & FLAG_NO_CHALLENGE_ACK))
3899208dd45dSBenjamin Yim 				tcp_send_challenge_ack(sk);
39004b506af9SEric Dumazet 			return -SKB_DROP_REASON_TCP_TOO_OLD_ACK;
3901354e4aa3SEric Dumazet 		}
39021da177e4SLinus Torvalds 		goto old_ack;
3903354e4aa3SEric Dumazet 	}
39041da177e4SLinus Torvalds 
390596e0bf4bSJohn Dykstra 	/* If the ack includes data we haven't sent yet, discard
390696e0bf4bSJohn Dykstra 	 * this segment (RFC793 Section 3.9).
390796e0bf4bSJohn Dykstra 	 */
390896e0bf4bSJohn Dykstra 	if (after(ack, tp->snd_nxt))
39094b506af9SEric Dumazet 		return -SKB_DROP_REASON_TCP_ACK_UNSENT_DATA;
391096e0bf4bSJohn Dykstra 
39110c9ab092SNeal Cardwell 	if (after(ack, prior_snd_una)) {
39122e605294SIlpo Järvinen 		flag |= FLAG_SND_UNA_ADVANCED;
39130c9ab092SNeal Cardwell 		icsk->icsk_retransmits = 0;
39146dac1523SIlya Lesokhin 
39156dac1523SIlya Lesokhin #if IS_ENABLED(CONFIG_TLS_DEVICE)
3916494bc1d2SJakub Kicinski 		if (static_branch_unlikely(&clean_acked_data_enabled.key))
39176dac1523SIlya Lesokhin 			if (icsk->icsk_clean_acked)
39186dac1523SIlya Lesokhin 				icsk->icsk_clean_acked(sk, ack);
39196dac1523SIlya Lesokhin #endif
39200c9ab092SNeal Cardwell 	}
39212e605294SIlpo Järvinen 
392250895b9dSEric Dumazet 	prior_fack = tcp_is_sack(tp) ? tcp_highest_sack_seq(tp) : tp->snd_una;
3923b9f64820SYuchung Cheng 	rs.prior_in_flight = tcp_packets_in_flight(tp);
3924c7caf8d3SIlpo Järvinen 
392512fb3dd9SEric Dumazet 	/* ts_recent update must be made after we are sure that the packet
392612fb3dd9SEric Dumazet 	 * is in window.
392712fb3dd9SEric Dumazet 	 */
392812fb3dd9SEric Dumazet 	if (flag & FLAG_UPDATE_TS_RECENT)
392912fb3dd9SEric Dumazet 		tcp_replace_ts_recent(tp, TCP_SKB_CB(skb)->seq);
393012fb3dd9SEric Dumazet 
39315e13a0d3SYafang Shao 	if ((flag & (FLAG_SLOWPATH | FLAG_SND_UNA_ADVANCED)) ==
39325e13a0d3SYafang Shao 	    FLAG_SND_UNA_ADVANCED) {
393331770e34SFlorian Westphal 		/* Window is constant, pure forward advance.
393431770e34SFlorian Westphal 		 * No more checks are required.
393531770e34SFlorian Westphal 		 * Note, we use the fact that SND.UNA>=SND.WL2.
393631770e34SFlorian Westphal 		 */
393731770e34SFlorian Westphal 		tcp_update_wl(tp, ack_seq);
393831770e34SFlorian Westphal 		tcp_snd_una_update(tp, ack);
393931770e34SFlorian Westphal 		flag |= FLAG_WIN_UPDATE;
394031770e34SFlorian Westphal 
394131770e34SFlorian Westphal 		tcp_in_ack_event(sk, CA_ACK_WIN_UPDATE);
394231770e34SFlorian Westphal 
394331770e34SFlorian Westphal 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPHPACKS);
394431770e34SFlorian Westphal 	} else {
3945c1d2b4c3SFlorian Westphal 		u32 ack_ev_flags = CA_ACK_SLOWPATH;
3946c1d2b4c3SFlorian Westphal 
39471da177e4SLinus Torvalds 		if (ack_seq != TCP_SKB_CB(skb)->end_seq)
39481da177e4SLinus Torvalds 			flag |= FLAG_DATA;
39491da177e4SLinus Torvalds 		else
3950c10d9310SEric Dumazet 			NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPPUREACKS);
39511da177e4SLinus Torvalds 
39529e412ba7SIlpo Järvinen 		flag |= tcp_ack_update_window(sk, skb, ack, ack_seq);
39531da177e4SLinus Torvalds 
39541da177e4SLinus Torvalds 		if (TCP_SKB_CB(skb)->sacked)
395559c9af42SYuchung Cheng 			flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una,
3956196da974SKenneth Klette Jonassen 							&sack_state);
39571da177e4SLinus Torvalds 
3958735d3831SFlorian Westphal 		if (tcp_ecn_rcv_ecn_echo(tp, tcp_hdr(skb))) {
39591da177e4SLinus Torvalds 			flag |= FLAG_ECE;
3960c1d2b4c3SFlorian Westphal 			ack_ev_flags |= CA_ACK_ECE;
39619890092eSFlorian Westphal 		}
39621da177e4SLinus Torvalds 
3963082d4fa9SYousuk Seung 		if (sack_state.sack_delivered)
3964082d4fa9SYousuk Seung 			tcp_count_delivered(tp, sack_state.sack_delivered,
3965082d4fa9SYousuk Seung 					    flag & FLAG_ECE);
3966082d4fa9SYousuk Seung 
39679890092eSFlorian Westphal 		if (flag & FLAG_WIN_UPDATE)
39689890092eSFlorian Westphal 			ack_ev_flags |= CA_ACK_WIN_UPDATE;
39699890092eSFlorian Westphal 
39709890092eSFlorian Westphal 		tcp_in_ack_event(sk, ack_ev_flags);
3971c1d2b4c3SFlorian Westphal 	}
39721da177e4SLinus Torvalds 
397325702840SDenis Kirjanov 	/* This is a deviation from RFC3168 since it states that:
397425702840SDenis Kirjanov 	 * "When the TCP data sender is ready to set the CWR bit after reducing
397525702840SDenis Kirjanov 	 * the congestion window, it SHOULD set the CWR bit only on the first
397625702840SDenis Kirjanov 	 * new data packet that it transmits."
397725702840SDenis Kirjanov 	 * We accept CWR on pure ACKs to be more robust
397825702840SDenis Kirjanov 	 * with widely-deployed TCP implementations that do this.
397925702840SDenis Kirjanov 	 */
398025702840SDenis Kirjanov 	tcp_ecn_accept_cwr(sk, skb);
398125702840SDenis Kirjanov 
39821da177e4SLinus Torvalds 	/* We passed data and got it acked, remove any soft error
39831da177e4SLinus Torvalds 	 * log. Something worked...
39841da177e4SLinus Torvalds 	 */
3985cee1af82SEric Dumazet 	WRITE_ONCE(sk->sk_err_soft, 0);
39864b53fb67SDavid S. Miller 	icsk->icsk_probes_out = 0;
398770eabf0eSEric Dumazet 	tp->rcv_tstamp = tcp_jiffies32;
39881da177e4SLinus Torvalds 	if (!prior_packets)
39891da177e4SLinus Torvalds 		goto no_queue;
39901da177e4SLinus Torvalds 
39911da177e4SLinus Torvalds 	/* See if we can take anything off of the retransmit queue. */
3992e7ed11eeSYousuk Seung 	flag |= tcp_clean_rtx_queue(sk, skb, prior_fack, prior_snd_una,
3993e7ed11eeSYousuk Seung 				    &sack_state, flag & FLAG_ECE);
3994a262f0cdSNandita Dukkipati 
39951f255691SPriyaranjan Jha 	tcp_rack_update_reo_wnd(sk, &rs);
39961da177e4SLinus Torvalds 
3997df92c839SNeal Cardwell 	if (tp->tlp_high_seq)
3998df92c839SNeal Cardwell 		tcp_process_tlp_ack(sk, ack, flag);
3999df92c839SNeal Cardwell 
40000f7cc9a3SYuchung Cheng 	if (tcp_ack_is_dubious(sk, flag)) {
4001d9157f68SPengcheng Yang 		if (!(flag & (FLAG_SND_UNA_ADVANCED |
4002d9157f68SPengcheng Yang 			      FLAG_NOT_DUP | FLAG_DSACKING_ACK))) {
400319119f29SEric Dumazet 			num_dupack = 1;
400419119f29SEric Dumazet 			/* Consider if pure acks were aggregated in tcp_add_backlog() */
400519119f29SEric Dumazet 			if (!(flag & FLAG_DATA))
400619119f29SEric Dumazet 				num_dupack = max_t(u16, 1, skb_shinfo(skb)->gso_segs);
400719119f29SEric Dumazet 		}
400819119f29SEric Dumazet 		tcp_fastretrans_alert(sk, prior_snd_una, num_dupack, &flag,
4009737ff314SYuchung Cheng 				      &rexmit);
40101da177e4SLinus Torvalds 	}
40119b717a8dSNandita Dukkipati 
401262d9f1a6SPengcheng Yang 	/* If needed, reset TLP/RTO timer when RACK doesn't set. */
401362d9f1a6SPengcheng Yang 	if (flag & FLAG_SET_XMIT_TIMER)
401462d9f1a6SPengcheng Yang 		tcp_set_xmit_timer(sk);
401562d9f1a6SPengcheng Yang 
4016c3a2e837SJulian Anastasov 	if ((flag & FLAG_FORWARD_PROGRESS) || !(flag & FLAG_NOT_DUP))
4017c3a2e837SJulian Anastasov 		sk_dst_confirm(sk);
40186ba8a3b1SNandita Dukkipati 
4019a77fa010SYuchung Cheng 	delivered = tcp_newly_delivered(sk, delivered, flag);
4020b9f64820SYuchung Cheng 	lost = tp->lost - lost;			/* freshly marked lost */
4021e4286603SYuchung Cheng 	rs.is_ack_delayed = !!(flag & FLAG_ACK_MAYBE_DELAYED);
4022d4761754SYousuk Seung 	tcp_rate_gen(sk, delivered, lost, is_sack_reneg, sack_state.rate);
4023deed7be7SYuchung Cheng 	tcp_cong_control(sk, ack, delivered, flag, sack_state.rate);
4024e662ca40SYuchung Cheng 	tcp_xmit_recovery(sk, rexmit);
40251da177e4SLinus Torvalds 	return 1;
40261da177e4SLinus Torvalds 
40271da177e4SLinus Torvalds no_queue:
40285628adf1SNeal Cardwell 	/* If data was DSACKed, see if we can undo a cwnd reduction. */
4029a77fa010SYuchung Cheng 	if (flag & FLAG_DSACKING_ACK) {
403019119f29SEric Dumazet 		tcp_fastretrans_alert(sk, prior_snd_una, num_dupack, &flag,
4031737ff314SYuchung Cheng 				      &rexmit);
4032a77fa010SYuchung Cheng 		tcp_newly_delivered(sk, delivered, flag);
4033a77fa010SYuchung Cheng 	}
40341da177e4SLinus Torvalds 	/* If this ack opens up a zero window, clear backoff.  It was
40351da177e4SLinus Torvalds 	 * being used to time the probes, and is probably far higher than
40361da177e4SLinus Torvalds 	 * it needs to be for normal retransmission.
40371da177e4SLinus Torvalds 	 */
40381da177e4SLinus Torvalds 	tcp_ack_probe(sk);
40399b717a8dSNandita Dukkipati 
40409b717a8dSNandita Dukkipati 	if (tp->tlp_high_seq)
40419b717a8dSNandita Dukkipati 		tcp_process_tlp_ack(sk, ack, flag);
40421da177e4SLinus Torvalds 	return 1;
40431da177e4SLinus Torvalds 
40441da177e4SLinus Torvalds old_ack:
4045e95ae2f2SNeal Cardwell 	/* If data was SACKed, tag it and see if we should send more data.
4046e95ae2f2SNeal Cardwell 	 * If data was DSACKed, see if we can undo a cwnd reduction.
4047e95ae2f2SNeal Cardwell 	 */
40488aca6cb1SIlpo Järvinen 	if (TCP_SKB_CB(skb)->sacked) {
404959c9af42SYuchung Cheng 		flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una,
4050196da974SKenneth Klette Jonassen 						&sack_state);
405119119f29SEric Dumazet 		tcp_fastretrans_alert(sk, prior_snd_una, num_dupack, &flag,
4052737ff314SYuchung Cheng 				      &rexmit);
4053a77fa010SYuchung Cheng 		tcp_newly_delivered(sk, delivered, flag);
4054e662ca40SYuchung Cheng 		tcp_xmit_recovery(sk, rexmit);
40558aca6cb1SIlpo Järvinen 	}
40561da177e4SLinus Torvalds 
40571da177e4SLinus Torvalds 	return 0;
40581da177e4SLinus Torvalds }
40591da177e4SLinus Torvalds 
tcp_parse_fastopen_option(int len,const unsigned char * cookie,bool syn,struct tcp_fastopen_cookie * foc,bool exp_opt)40607f9b838bSDaniel Lee static void tcp_parse_fastopen_option(int len, const unsigned char *cookie,
40617f9b838bSDaniel Lee 				      bool syn, struct tcp_fastopen_cookie *foc,
40627f9b838bSDaniel Lee 				      bool exp_opt)
40637f9b838bSDaniel Lee {
40647f9b838bSDaniel Lee 	/* Valid only in SYN or SYN-ACK with an even length.  */
40657f9b838bSDaniel Lee 	if (!foc || !syn || len < 0 || (len & 1))
40667f9b838bSDaniel Lee 		return;
40677f9b838bSDaniel Lee 
40687f9b838bSDaniel Lee 	if (len >= TCP_FASTOPEN_COOKIE_MIN &&
40697f9b838bSDaniel Lee 	    len <= TCP_FASTOPEN_COOKIE_MAX)
40707f9b838bSDaniel Lee 		memcpy(foc->val, cookie, len);
40717f9b838bSDaniel Lee 	else if (len != 0)
40727f9b838bSDaniel Lee 		len = -1;
40737f9b838bSDaniel Lee 	foc->len = len;
40747f9b838bSDaniel Lee 	foc->exp = exp_opt;
40757f9b838bSDaniel Lee }
40767f9b838bSDaniel Lee 
smc_parse_options(const struct tcphdr * th,struct tcp_options_received * opt_rx,const unsigned char * ptr,int opsize)40777656d684SMartin KaFai Lau static bool smc_parse_options(const struct tcphdr *th,
407860e2a778SUrsula Braun 			      struct tcp_options_received *opt_rx,
407960e2a778SUrsula Braun 			      const unsigned char *ptr,
408060e2a778SUrsula Braun 			      int opsize)
408160e2a778SUrsula Braun {
408260e2a778SUrsula Braun #if IS_ENABLED(CONFIG_SMC)
408360e2a778SUrsula Braun 	if (static_branch_unlikely(&tcp_have_smc)) {
408460e2a778SUrsula Braun 		if (th->syn && !(opsize & 1) &&
408560e2a778SUrsula Braun 		    opsize >= TCPOLEN_EXP_SMC_BASE &&
40867656d684SMartin KaFai Lau 		    get_unaligned_be32(ptr) == TCPOPT_SMC_MAGIC) {
408760e2a778SUrsula Braun 			opt_rx->smc_ok = 1;
40887656d684SMartin KaFai Lau 			return true;
40897656d684SMartin KaFai Lau 		}
409060e2a778SUrsula Braun 	}
409160e2a778SUrsula Braun #endif
40927656d684SMartin KaFai Lau 	return false;
409360e2a778SUrsula Braun }
409460e2a778SUrsula Braun 
40959349d600SPetar Penkov /* Try to parse the MSS option from the TCP header. Return 0 on failure, clamped
40969349d600SPetar Penkov  * value on success.
40979349d600SPetar Penkov  */
tcp_parse_mss_option(const struct tcphdr * th,u16 user_mss)409833bf9885SMaxim Mikityanskiy u16 tcp_parse_mss_option(const struct tcphdr *th, u16 user_mss)
40999349d600SPetar Penkov {
41009349d600SPetar Penkov 	const unsigned char *ptr = (const unsigned char *)(th + 1);
41019349d600SPetar Penkov 	int length = (th->doff * 4) - sizeof(struct tcphdr);
41029349d600SPetar Penkov 	u16 mss = 0;
41039349d600SPetar Penkov 
41049349d600SPetar Penkov 	while (length > 0) {
41059349d600SPetar Penkov 		int opcode = *ptr++;
41069349d600SPetar Penkov 		int opsize;
41079349d600SPetar Penkov 
41089349d600SPetar Penkov 		switch (opcode) {
41099349d600SPetar Penkov 		case TCPOPT_EOL:
41109349d600SPetar Penkov 			return mss;
41119349d600SPetar Penkov 		case TCPOPT_NOP:	/* Ref: RFC 793 section 3.1 */
41129349d600SPetar Penkov 			length--;
41139349d600SPetar Penkov 			continue;
41149349d600SPetar Penkov 		default:
41159349d600SPetar Penkov 			if (length < 2)
41169349d600SPetar Penkov 				return mss;
41179349d600SPetar Penkov 			opsize = *ptr++;
41189349d600SPetar Penkov 			if (opsize < 2) /* "silly options" */
41199349d600SPetar Penkov 				return mss;
41209349d600SPetar Penkov 			if (opsize > length)
41219349d600SPetar Penkov 				return mss;	/* fail on partial options */
41229349d600SPetar Penkov 			if (opcode == TCPOPT_MSS && opsize == TCPOLEN_MSS) {
41239349d600SPetar Penkov 				u16 in_mss = get_unaligned_be16(ptr);
41249349d600SPetar Penkov 
41259349d600SPetar Penkov 				if (in_mss) {
41269349d600SPetar Penkov 					if (user_mss && user_mss < in_mss)
41279349d600SPetar Penkov 						in_mss = user_mss;
41289349d600SPetar Penkov 					mss = in_mss;
41299349d600SPetar Penkov 				}
41309349d600SPetar Penkov 			}
41319349d600SPetar Penkov 			ptr += opsize - 2;
41329349d600SPetar Penkov 			length -= opsize;
41339349d600SPetar Penkov 		}
41349349d600SPetar Penkov 	}
41359349d600SPetar Penkov 	return mss;
41369349d600SPetar Penkov }
413733bf9885SMaxim Mikityanskiy EXPORT_SYMBOL_GPL(tcp_parse_mss_option);
41389349d600SPetar Penkov 
41391da177e4SLinus Torvalds /* Look for tcp options. Normally only called on SYN and SYNACK packets.
41401da177e4SLinus Torvalds  * But, this can also be called on packets in the established flow when
41411da177e4SLinus Torvalds  * the fast version below fails.
41421da177e4SLinus Torvalds  */
tcp_parse_options(const struct net * net,const struct sk_buff * skb,struct tcp_options_received * opt_rx,int estab,struct tcp_fastopen_cookie * foc)4143eed29f17SEric Dumazet void tcp_parse_options(const struct net *net,
4144eed29f17SEric Dumazet 		       const struct sk_buff *skb,
41451a2c6181SChristoph Paasch 		       struct tcp_options_received *opt_rx, int estab,
41462100c8d2SYuchung Cheng 		       struct tcp_fastopen_cookie *foc)
41471da177e4SLinus Torvalds {
4148cf533ea5SEric Dumazet 	const unsigned char *ptr;
4149cf533ea5SEric Dumazet 	const struct tcphdr *th = tcp_hdr(skb);
41501da177e4SLinus Torvalds 	int length = (th->doff * 4) - sizeof(struct tcphdr);
41511da177e4SLinus Torvalds 
4152cf533ea5SEric Dumazet 	ptr = (const unsigned char *)(th + 1);
41531da177e4SLinus Torvalds 	opt_rx->saw_tstamp = 0;
41547656d684SMartin KaFai Lau 	opt_rx->saw_unknown = 0;
41551da177e4SLinus Torvalds 
41561da177e4SLinus Torvalds 	while (length > 0) {
41571da177e4SLinus Torvalds 		int opcode = *ptr++;
41581da177e4SLinus Torvalds 		int opsize;
41591da177e4SLinus Torvalds 
41601da177e4SLinus Torvalds 		switch (opcode) {
41611da177e4SLinus Torvalds 		case TCPOPT_EOL:
41621da177e4SLinus Torvalds 			return;
41631da177e4SLinus Torvalds 		case TCPOPT_NOP:	/* Ref: RFC 793 section 3.1 */
41641da177e4SLinus Torvalds 			length--;
41651da177e4SLinus Torvalds 			continue;
41661da177e4SLinus Torvalds 		default:
41679609dad2SYoung Xiao 			if (length < 2)
41689609dad2SYoung Xiao 				return;
41691da177e4SLinus Torvalds 			opsize = *ptr++;
41701da177e4SLinus Torvalds 			if (opsize < 2) /* "silly options" */
41711da177e4SLinus Torvalds 				return;
41721da177e4SLinus Torvalds 			if (opsize > length)
41731da177e4SLinus Torvalds 				return;	/* don't parse partial options */
41741da177e4SLinus Torvalds 			switch (opcode) {
41751da177e4SLinus Torvalds 			case TCPOPT_MSS:
41761da177e4SLinus Torvalds 				if (opsize == TCPOLEN_MSS && th->syn && !estab) {
4177d3e2ce3bSHarvey Harrison 					u16 in_mss = get_unaligned_be16(ptr);
41781da177e4SLinus Torvalds 					if (in_mss) {
4179f038ac8fSIlpo Järvinen 						if (opt_rx->user_mss &&
4180f038ac8fSIlpo Järvinen 						    opt_rx->user_mss < in_mss)
41811da177e4SLinus Torvalds 							in_mss = opt_rx->user_mss;
41821da177e4SLinus Torvalds 						opt_rx->mss_clamp = in_mss;
41831da177e4SLinus Torvalds 					}
41841da177e4SLinus Torvalds 				}
41851da177e4SLinus Torvalds 				break;
41861da177e4SLinus Torvalds 			case TCPOPT_WINDOW:
4187f038ac8fSIlpo Järvinen 				if (opsize == TCPOLEN_WINDOW && th->syn &&
41883666f666SKuniyuki Iwashima 				    !estab && READ_ONCE(net->ipv4.sysctl_tcp_window_scaling)) {
41891da177e4SLinus Torvalds 					__u8 snd_wscale = *(__u8 *)ptr;
41901da177e4SLinus Torvalds 					opt_rx->wscale_ok = 1;
4191589c49cbSGao Feng 					if (snd_wscale > TCP_MAX_WSCALE) {
4192589c49cbSGao Feng 						net_info_ratelimited("%s: Illegal window scaling value %d > %u received\n",
4193058bd4d2SJoe Perches 								     __func__,
4194589c49cbSGao Feng 								     snd_wscale,
4195589c49cbSGao Feng 								     TCP_MAX_WSCALE);
4196589c49cbSGao Feng 						snd_wscale = TCP_MAX_WSCALE;
41971da177e4SLinus Torvalds 					}
41981da177e4SLinus Torvalds 					opt_rx->snd_wscale = snd_wscale;
41991da177e4SLinus Torvalds 				}
42001da177e4SLinus Torvalds 				break;
42011da177e4SLinus Torvalds 			case TCPOPT_TIMESTAMP:
4202f038ac8fSIlpo Järvinen 				if ((opsize == TCPOLEN_TIMESTAMP) &&
4203f038ac8fSIlpo Järvinen 				    ((estab && opt_rx->tstamp_ok) ||
42043666f666SKuniyuki Iwashima 				     (!estab && READ_ONCE(net->ipv4.sysctl_tcp_timestamps)))) {
42051da177e4SLinus Torvalds 					opt_rx->saw_tstamp = 1;
4206d3e2ce3bSHarvey Harrison 					opt_rx->rcv_tsval = get_unaligned_be32(ptr);
4207d3e2ce3bSHarvey Harrison 					opt_rx->rcv_tsecr = get_unaligned_be32(ptr + 4);
42081da177e4SLinus Torvalds 				}
42091da177e4SLinus Torvalds 				break;
42101da177e4SLinus Torvalds 			case TCPOPT_SACK_PERM:
4211f038ac8fSIlpo Järvinen 				if (opsize == TCPOLEN_SACK_PERM && th->syn &&
42123666f666SKuniyuki Iwashima 				    !estab && READ_ONCE(net->ipv4.sysctl_tcp_sack)) {
4213ab56222aSVijay Subramanian 					opt_rx->sack_ok = TCP_SACK_SEEN;
42141da177e4SLinus Torvalds 					tcp_sack_reset(opt_rx);
42151da177e4SLinus Torvalds 				}
42161da177e4SLinus Torvalds 				break;
42171da177e4SLinus Torvalds 
42181da177e4SLinus Torvalds 			case TCPOPT_SACK:
42191da177e4SLinus Torvalds 				if ((opsize >= (TCPOLEN_SACK_BASE + TCPOLEN_SACK_PERBLOCK)) &&
42201da177e4SLinus Torvalds 				   !((opsize - TCPOLEN_SACK_BASE) % TCPOLEN_SACK_PERBLOCK) &&
42211da177e4SLinus Torvalds 				   opt_rx->sack_ok) {
42221da177e4SLinus Torvalds 					TCP_SKB_CB(skb)->sacked = (ptr - 2) - (unsigned char *)th;
42231da177e4SLinus Torvalds 				}
4224d7ea5b91SIlpo Järvinen 				break;
4225cfb6eeb4SYOSHIFUJI Hideaki #ifdef CONFIG_TCP_MD5SIG
4226cfb6eeb4SYOSHIFUJI Hideaki 			case TCPOPT_MD5SIG:
4227b2051536SKuniyuki Iwashima 				/* The MD5 Hash has already been
4228b2051536SKuniyuki Iwashima 				 * checked (see tcp_v{4,6}_rcv()).
4229cfb6eeb4SYOSHIFUJI Hideaki 				 */
4230cfb6eeb4SYOSHIFUJI Hideaki 				break;
4231cfb6eeb4SYOSHIFUJI Hideaki #endif
42327f9b838bSDaniel Lee 			case TCPOPT_FASTOPEN:
42337f9b838bSDaniel Lee 				tcp_parse_fastopen_option(
42347f9b838bSDaniel Lee 					opsize - TCPOLEN_FASTOPEN_BASE,
42357f9b838bSDaniel Lee 					ptr, th->syn, foc, false);
42367f9b838bSDaniel Lee 				break;
42377f9b838bSDaniel Lee 
42382100c8d2SYuchung Cheng 			case TCPOPT_EXP:
42392100c8d2SYuchung Cheng 				/* Fast Open option shares code 254 using a
42407f9b838bSDaniel Lee 				 * 16 bits magic number.
42412100c8d2SYuchung Cheng 				 */
42427f9b838bSDaniel Lee 				if (opsize >= TCPOLEN_EXP_FASTOPEN_BASE &&
42437f9b838bSDaniel Lee 				    get_unaligned_be16(ptr) ==
42447656d684SMartin KaFai Lau 				    TCPOPT_FASTOPEN_MAGIC) {
42457f9b838bSDaniel Lee 					tcp_parse_fastopen_option(opsize -
42467f9b838bSDaniel Lee 						TCPOLEN_EXP_FASTOPEN_BASE,
42477f9b838bSDaniel Lee 						ptr + 2, th->syn, foc, true);
42487656d684SMartin KaFai Lau 					break;
42497656d684SMartin KaFai Lau 				}
42507656d684SMartin KaFai Lau 
42517656d684SMartin KaFai Lau 				if (smc_parse_options(th, opt_rx, ptr, opsize))
42522100c8d2SYuchung Cheng 					break;
42532100c8d2SYuchung Cheng 
42547656d684SMartin KaFai Lau 				opt_rx->saw_unknown = 1;
42557656d684SMartin KaFai Lau 				break;
42567656d684SMartin KaFai Lau 
42577656d684SMartin KaFai Lau 			default:
42587656d684SMartin KaFai Lau 				opt_rx->saw_unknown = 1;
42592100c8d2SYuchung Cheng 			}
42601da177e4SLinus Torvalds 			ptr += opsize-2;
42611da177e4SLinus Torvalds 			length -= opsize;
42623ff50b79SStephen Hemminger 		}
42631da177e4SLinus Torvalds 	}
42641da177e4SLinus Torvalds }
42654bc2f18bSEric Dumazet EXPORT_SYMBOL(tcp_parse_options);
42661da177e4SLinus Torvalds 
tcp_parse_aligned_timestamp(struct tcp_sock * tp,const struct tcphdr * th)4267a2a385d6SEric Dumazet static bool tcp_parse_aligned_timestamp(struct tcp_sock *tp, const struct tcphdr *th)
4268a4356b29SIlpo Järvinen {
4269cf533ea5SEric Dumazet 	const __be32 *ptr = (const __be32 *)(th + 1);
4270a4356b29SIlpo Järvinen 
4271a4356b29SIlpo Järvinen 	if (*ptr == htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16)
4272a4356b29SIlpo Järvinen 			  | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP)) {
4273a4356b29SIlpo Järvinen 		tp->rx_opt.saw_tstamp = 1;
4274a4356b29SIlpo Järvinen 		++ptr;
4275a4356b29SIlpo Järvinen 		tp->rx_opt.rcv_tsval = ntohl(*ptr);
4276a4356b29SIlpo Järvinen 		++ptr;
4277e3e12028SAndrew Vagin 		if (*ptr)
4278ee684b6fSAndrey Vagin 			tp->rx_opt.rcv_tsecr = ntohl(*ptr) - tp->tsoffset;
4279e3e12028SAndrew Vagin 		else
4280e3e12028SAndrew Vagin 			tp->rx_opt.rcv_tsecr = 0;
4281a2a385d6SEric Dumazet 		return true;
4282a4356b29SIlpo Järvinen 	}
4283a2a385d6SEric Dumazet 	return false;
4284a4356b29SIlpo Järvinen }
4285a4356b29SIlpo Järvinen 
42861da177e4SLinus Torvalds /* Fast parse options. This hopes to only see timestamps.
42871da177e4SLinus Torvalds  * If it is wrong it falls back on tcp_parse_options().
42881da177e4SLinus Torvalds  */
tcp_fast_parse_options(const struct net * net,const struct sk_buff * skb,const struct tcphdr * th,struct tcp_sock * tp)4289eed29f17SEric Dumazet static bool tcp_fast_parse_options(const struct net *net,
4290eed29f17SEric Dumazet 				   const struct sk_buff *skb,
42911a2c6181SChristoph Paasch 				   const struct tcphdr *th, struct tcp_sock *tp)
42921da177e4SLinus Torvalds {
42934957faadSWilliam Allen Simpson 	/* In the spirit of fast parsing, compare doff directly to constant
42944957faadSWilliam Allen Simpson 	 * values.  Because equality is used, short doff can be ignored here.
42954957faadSWilliam Allen Simpson 	 */
42964957faadSWilliam Allen Simpson 	if (th->doff == (sizeof(*th) / 4)) {
42971da177e4SLinus Torvalds 		tp->rx_opt.saw_tstamp = 0;
4298a2a385d6SEric Dumazet 		return false;
42991da177e4SLinus Torvalds 	} else if (tp->rx_opt.tstamp_ok &&
43004957faadSWilliam Allen Simpson 		   th->doff == ((sizeof(*th) + TCPOLEN_TSTAMP_ALIGNED) / 4)) {
4301a4356b29SIlpo Järvinen 		if (tcp_parse_aligned_timestamp(tp, th))
4302a2a385d6SEric Dumazet 			return true;
43031da177e4SLinus Torvalds 	}
4304ee684b6fSAndrey Vagin 
4305eed29f17SEric Dumazet 	tcp_parse_options(net, skb, &tp->rx_opt, 1, NULL);
4306e3e12028SAndrew Vagin 	if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr)
4307ee684b6fSAndrey Vagin 		tp->rx_opt.rcv_tsecr -= tp->tsoffset;
4308ee684b6fSAndrey Vagin 
4309a2a385d6SEric Dumazet 	return true;
43101da177e4SLinus Torvalds }
43111da177e4SLinus Torvalds 
43127d5d5525SYOSHIFUJI Hideaki #ifdef CONFIG_TCP_MD5SIG
43137d5d5525SYOSHIFUJI Hideaki /*
43147d5d5525SYOSHIFUJI Hideaki  * Parse MD5 Signature option
43157d5d5525SYOSHIFUJI Hideaki  */
tcp_parse_md5sig_option(const struct tcphdr * th)4316cf533ea5SEric Dumazet const u8 *tcp_parse_md5sig_option(const struct tcphdr *th)
43177d5d5525SYOSHIFUJI Hideaki {
43187d5d5525SYOSHIFUJI Hideaki 	int length = (th->doff << 2) - sizeof(*th);
4319cf533ea5SEric Dumazet 	const u8 *ptr = (const u8 *)(th + 1);
43207d5d5525SYOSHIFUJI Hideaki 
43217e5a206aSJann Horn 	/* If not enough data remaining, we can short cut */
43227e5a206aSJann Horn 	while (length >= TCPOLEN_MD5SIG) {
43237d5d5525SYOSHIFUJI Hideaki 		int opcode = *ptr++;
43247d5d5525SYOSHIFUJI Hideaki 		int opsize;
43257d5d5525SYOSHIFUJI Hideaki 
43267d5d5525SYOSHIFUJI Hideaki 		switch (opcode) {
43277d5d5525SYOSHIFUJI Hideaki 		case TCPOPT_EOL:
43287d5d5525SYOSHIFUJI Hideaki 			return NULL;
43297d5d5525SYOSHIFUJI Hideaki 		case TCPOPT_NOP:
43307d5d5525SYOSHIFUJI Hideaki 			length--;
43317d5d5525SYOSHIFUJI Hideaki 			continue;
43327d5d5525SYOSHIFUJI Hideaki 		default:
43337d5d5525SYOSHIFUJI Hideaki 			opsize = *ptr++;
43347d5d5525SYOSHIFUJI Hideaki 			if (opsize < 2 || opsize > length)
43357d5d5525SYOSHIFUJI Hideaki 				return NULL;
43367d5d5525SYOSHIFUJI Hideaki 			if (opcode == TCPOPT_MD5SIG)
4337ba78e2ddSDmitry Popov 				return opsize == TCPOLEN_MD5SIG ? ptr : NULL;
43387d5d5525SYOSHIFUJI Hideaki 		}
43397d5d5525SYOSHIFUJI Hideaki 		ptr += opsize - 2;
43407d5d5525SYOSHIFUJI Hideaki 		length -= opsize;
43417d5d5525SYOSHIFUJI Hideaki 	}
43427d5d5525SYOSHIFUJI Hideaki 	return NULL;
43437d5d5525SYOSHIFUJI Hideaki }
43444bc2f18bSEric Dumazet EXPORT_SYMBOL(tcp_parse_md5sig_option);
43457d5d5525SYOSHIFUJI Hideaki #endif
43467d5d5525SYOSHIFUJI Hideaki 
43471da177e4SLinus Torvalds /* Sorry, PAWS as specified is broken wrt. pure-ACKs -DaveM
43481da177e4SLinus Torvalds  *
43491da177e4SLinus Torvalds  * It is not fatal. If this ACK does _not_ change critical state (seqs, window)
43501da177e4SLinus Torvalds  * it can pass through stack. So, the following predicate verifies that
43511da177e4SLinus Torvalds  * this segment is not used for anything but congestion avoidance or
43521da177e4SLinus Torvalds  * fast retransmit. Moreover, we even are able to eliminate most of such
43531da177e4SLinus Torvalds  * second order effects, if we apply some small "replay" window (~RTO)
43541da177e4SLinus Torvalds  * to timestamp space.
43551da177e4SLinus Torvalds  *
43561da177e4SLinus Torvalds  * All these measures still do not guarantee that we reject wrapped ACKs
43571da177e4SLinus Torvalds  * on networks with high bandwidth, when sequence space is recycled fastly,
43581da177e4SLinus Torvalds  * but it guarantees that such events will be very rare and do not affect
43591da177e4SLinus Torvalds  * connection seriously. This doesn't look nice, but alas, PAWS is really
43601da177e4SLinus Torvalds  * buggy extension.
43611da177e4SLinus Torvalds  *
43621da177e4SLinus Torvalds  * [ Later note. Even worse! It is buggy for segments _with_ data. RFC
43631da177e4SLinus Torvalds  * states that events when retransmit arrives after original data are rare.
43641da177e4SLinus Torvalds  * It is a blatant lie. VJ forgot about fast retransmit! 8)8) It is
43651da177e4SLinus Torvalds  * the biggest problem on large power networks even with minor reordering.
43661da177e4SLinus Torvalds  * OK, let's give it small replay window. If peer clock is even 1hz, it is safe
43671da177e4SLinus Torvalds  * up to bandwidth of 18Gigabit/sec. 8) ]
43681da177e4SLinus Torvalds  */
43691da177e4SLinus Torvalds 
tcp_disordered_ack(const struct sock * sk,const struct sk_buff * skb)4370463c84b9SArnaldo Carvalho de Melo static int tcp_disordered_ack(const struct sock *sk, const struct sk_buff *skb)
43711da177e4SLinus Torvalds {
4372cf533ea5SEric Dumazet 	const struct tcp_sock *tp = tcp_sk(sk);
4373cf533ea5SEric Dumazet 	const struct tcphdr *th = tcp_hdr(skb);
43741da177e4SLinus Torvalds 	u32 seq = TCP_SKB_CB(skb)->seq;
43751da177e4SLinus Torvalds 	u32 ack = TCP_SKB_CB(skb)->ack_seq;
43761da177e4SLinus Torvalds 
43771da177e4SLinus Torvalds 	return (/* 1. Pure ACK with correct sequence number. */
43781da177e4SLinus Torvalds 		(th->ack && seq == TCP_SKB_CB(skb)->end_seq && seq == tp->rcv_nxt) &&
43791da177e4SLinus Torvalds 
43801da177e4SLinus Torvalds 		/* 2. ... and duplicate ACK. */
43811da177e4SLinus Torvalds 		ack == tp->snd_una &&
43821da177e4SLinus Torvalds 
43831da177e4SLinus Torvalds 		/* 3. ... and does not update window. */
43841da177e4SLinus Torvalds 		!tcp_may_update_window(tp, ack, seq, ntohs(th->window) << tp->rx_opt.snd_wscale) &&
43851da177e4SLinus Torvalds 
43861da177e4SLinus Torvalds 		/* 4. ... and sits in replay window. */
4387463c84b9SArnaldo Carvalho de Melo 		(s32)(tp->rx_opt.ts_recent - tp->rx_opt.rcv_tsval) <= (inet_csk(sk)->icsk_rto * 1024) / HZ);
43881da177e4SLinus Torvalds }
43891da177e4SLinus Torvalds 
tcp_paws_discard(const struct sock * sk,const struct sk_buff * skb)439067b95bd7SVijay Subramanian static inline bool tcp_paws_discard(const struct sock *sk,
4391056834d9SIlpo Järvinen 				   const struct sk_buff *skb)
43921da177e4SLinus Torvalds {
4393463c84b9SArnaldo Carvalho de Melo 	const struct tcp_sock *tp = tcp_sk(sk);
4394c887e6d2SIlpo Järvinen 
4395c887e6d2SIlpo Järvinen 	return !tcp_paws_check(&tp->rx_opt, TCP_PAWS_WINDOW) &&
4396c887e6d2SIlpo Järvinen 	       !tcp_disordered_ack(sk, skb);
43971da177e4SLinus Torvalds }
43981da177e4SLinus Torvalds 
43991da177e4SLinus Torvalds /* Check segment sequence number for validity.
44001da177e4SLinus Torvalds  *
44011da177e4SLinus Torvalds  * Segment controls are considered valid, if the segment
44021da177e4SLinus Torvalds  * fits to the window after truncation to the window. Acceptability
44031da177e4SLinus Torvalds  * of data (and SYN, FIN, of course) is checked separately.
44041da177e4SLinus Torvalds  * See tcp_data_queue(), for example.
44051da177e4SLinus Torvalds  *
44061da177e4SLinus Torvalds  * Also, controls (RST is main one) are accepted using RCV.WUP instead
44071da177e4SLinus Torvalds  * of RCV.NXT. Peer still did not advance his SND.UNA when we
44081da177e4SLinus Torvalds  * delayed ACK, so that hisSND.UNA<=ourRCV.WUP.
44091da177e4SLinus Torvalds  * (borrowed from freebsd)
44101da177e4SLinus Torvalds  */
44111da177e4SLinus Torvalds 
tcp_sequence(const struct tcp_sock * tp,u32 seq,u32 end_seq)4412b4469349SEric Dumazet static enum skb_drop_reason tcp_sequence(const struct tcp_sock *tp,
4413b4469349SEric Dumazet 					 u32 seq, u32 end_seq)
44141da177e4SLinus Torvalds {
4415b4469349SEric Dumazet 	if (before(end_seq, tp->rcv_wup))
4416b4469349SEric Dumazet 		return SKB_DROP_REASON_TCP_OLD_SEQUENCE;
4417b4469349SEric Dumazet 
4418b4469349SEric Dumazet 	if (after(seq, tp->rcv_nxt + tcp_receive_window(tp)))
4419b4469349SEric Dumazet 		return SKB_DROP_REASON_TCP_INVALID_SEQUENCE;
4420b4469349SEric Dumazet 
4421b4469349SEric Dumazet 	return SKB_NOT_DROPPED_YET;
44221da177e4SLinus Torvalds }
44231da177e4SLinus Torvalds 
4424ecc6836dSEric Dumazet 
tcp_done_with_error(struct sock * sk,int err)4425ecc6836dSEric Dumazet void tcp_done_with_error(struct sock *sk, int err)
4426ecc6836dSEric Dumazet {
4427ecc6836dSEric Dumazet 	/* This barrier is coupled with smp_rmb() in tcp_poll() */
4428ecc6836dSEric Dumazet 	WRITE_ONCE(sk->sk_err, err);
4429ecc6836dSEric Dumazet 	smp_wmb();
4430ecc6836dSEric Dumazet 
4431ecc6836dSEric Dumazet 	tcp_write_queue_purge(sk);
4432ecc6836dSEric Dumazet 	tcp_done(sk);
4433ecc6836dSEric Dumazet 
4434ecc6836dSEric Dumazet 	if (!sock_flag(sk, SOCK_DEAD))
4435ecc6836dSEric Dumazet 		sk_error_report(sk);
4436ecc6836dSEric Dumazet }
4437ecc6836dSEric Dumazet EXPORT_SYMBOL(tcp_done_with_error);
4438ecc6836dSEric Dumazet 
44391da177e4SLinus Torvalds /* When we get a reset we do this. */
tcp_reset(struct sock * sk,struct sk_buff * skb)4440049fe386SFlorian Westphal void tcp_reset(struct sock *sk, struct sk_buff *skb)
44411da177e4SLinus Torvalds {
4442ecc6836dSEric Dumazet 	int err;
4443ecc6836dSEric Dumazet 
44445941521cSSong Liu 	trace_tcp_receive_reset(sk);
44455941521cSSong Liu 
44466787b7e3SJianguo Wu 	/* mptcp can't tell us to ignore reset pkts,
44476787b7e3SJianguo Wu 	 * so just ignore the return value of mptcp_incoming_options().
44486787b7e3SJianguo Wu 	 */
4449049fe386SFlorian Westphal 	if (sk_is_mptcp(sk))
4450049fe386SFlorian Westphal 		mptcp_incoming_options(sk, skb);
4451049fe386SFlorian Westphal 
44521da177e4SLinus Torvalds 	/* We want the right error as BSD sees it (and indeed as we do). */
44531da177e4SLinus Torvalds 	switch (sk->sk_state) {
44541da177e4SLinus Torvalds 	case TCP_SYN_SENT:
4455ecc6836dSEric Dumazet 		err = ECONNREFUSED;
44561da177e4SLinus Torvalds 		break;
44571da177e4SLinus Torvalds 	case TCP_CLOSE_WAIT:
4458ecc6836dSEric Dumazet 		err = EPIPE;
44591da177e4SLinus Torvalds 		break;
44601da177e4SLinus Torvalds 	case TCP_CLOSE:
44611da177e4SLinus Torvalds 		return;
44621da177e4SLinus Torvalds 	default:
4463ecc6836dSEric Dumazet 		err = ECONNRESET;
44641da177e4SLinus Torvalds 	}
4465ecc6836dSEric Dumazet 	tcp_done_with_error(sk, err);
44661da177e4SLinus Torvalds }
44671da177e4SLinus Torvalds 
44681da177e4SLinus Torvalds /*
44691da177e4SLinus Torvalds  * 	Process the FIN bit. This now behaves as it is supposed to work
44701da177e4SLinus Torvalds  *	and the FIN takes effect when it is validly part of sequence
44711da177e4SLinus Torvalds  *	space. Not before when we get holes.
44721da177e4SLinus Torvalds  *
44731da177e4SLinus Torvalds  *	If we are ESTABLISHED, a received fin moves us to CLOSE-WAIT
44741da177e4SLinus Torvalds  *	(and thence onto LAST-ACK and finally, CLOSE, we never enter
44751da177e4SLinus Torvalds  *	TIME-WAIT)
44761da177e4SLinus Torvalds  *
44771da177e4SLinus Torvalds  *	If we are in FINWAIT-1, a received FIN indicates simultaneous
44781da177e4SLinus Torvalds  *	close and we go into CLOSING (and later onto TIME-WAIT)
44791da177e4SLinus Torvalds  *
44801da177e4SLinus Torvalds  *	If we are in FINWAIT-2, a received FIN moves us to TIME-WAIT.
44811da177e4SLinus Torvalds  */
tcp_fin(struct sock * sk)4482e3e17b77SEric Dumazet void tcp_fin(struct sock *sk)
44831da177e4SLinus Torvalds {
44841da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
44851da177e4SLinus Torvalds 
4486463c84b9SArnaldo Carvalho de Melo 	inet_csk_schedule_ack(sk);
44871da177e4SLinus Torvalds 
4488e14cadfdSEric Dumazet 	WRITE_ONCE(sk->sk_shutdown, sk->sk_shutdown | RCV_SHUTDOWN);
44891da177e4SLinus Torvalds 	sock_set_flag(sk, SOCK_DONE);
44901da177e4SLinus Torvalds 
44911da177e4SLinus Torvalds 	switch (sk->sk_state) {
44921da177e4SLinus Torvalds 	case TCP_SYN_RECV:
44931da177e4SLinus Torvalds 	case TCP_ESTABLISHED:
44941da177e4SLinus Torvalds 		/* Move to CLOSE_WAIT */
44951da177e4SLinus Torvalds 		tcp_set_state(sk, TCP_CLOSE_WAIT);
449631954cd8SWei Wang 		inet_csk_enter_pingpong_mode(sk);
44971da177e4SLinus Torvalds 		break;
44981da177e4SLinus Torvalds 
44991da177e4SLinus Torvalds 	case TCP_CLOSE_WAIT:
45001da177e4SLinus Torvalds 	case TCP_CLOSING:
45011da177e4SLinus Torvalds 		/* Received a retransmission of the FIN, do
45021da177e4SLinus Torvalds 		 * nothing.
45031da177e4SLinus Torvalds 		 */
45041da177e4SLinus Torvalds 		break;
45051da177e4SLinus Torvalds 	case TCP_LAST_ACK:
45061da177e4SLinus Torvalds 		/* RFC793: Remain in the LAST-ACK state. */
45071da177e4SLinus Torvalds 		break;
45081da177e4SLinus Torvalds 
45091da177e4SLinus Torvalds 	case TCP_FIN_WAIT1:
45101da177e4SLinus Torvalds 		/* This case occurs when a simultaneous close
45111da177e4SLinus Torvalds 		 * happens, we must ack the received FIN and
45121da177e4SLinus Torvalds 		 * enter the CLOSING state.
45131da177e4SLinus Torvalds 		 */
45141da177e4SLinus Torvalds 		tcp_send_ack(sk);
45151da177e4SLinus Torvalds 		tcp_set_state(sk, TCP_CLOSING);
45161da177e4SLinus Torvalds 		break;
45171da177e4SLinus Torvalds 	case TCP_FIN_WAIT2:
45181da177e4SLinus Torvalds 		/* Received a FIN -- send ACK and enter TIME_WAIT. */
45191da177e4SLinus Torvalds 		tcp_send_ack(sk);
45201da177e4SLinus Torvalds 		tcp_time_wait(sk, TCP_TIME_WAIT, 0);
45211da177e4SLinus Torvalds 		break;
45221da177e4SLinus Torvalds 	default:
45231da177e4SLinus Torvalds 		/* Only TCP_LISTEN and TCP_CLOSE are left, in these
45241da177e4SLinus Torvalds 		 * cases we should never reach this piece of code.
45251da177e4SLinus Torvalds 		 */
4526058bd4d2SJoe Perches 		pr_err("%s: Impossible, sk->sk_state=%d\n",
45270dc47877SHarvey Harrison 		       __func__, sk->sk_state);
45281da177e4SLinus Torvalds 		break;
45293ff50b79SStephen Hemminger 	}
45301da177e4SLinus Torvalds 
45311da177e4SLinus Torvalds 	/* It _is_ possible, that we have something out-of-order _after_ FIN.
45321da177e4SLinus Torvalds 	 * Probably, we should reset in this case. For now drop them.
45331da177e4SLinus Torvalds 	 */
45349f5afeaeSYaogong Wang 	skb_rbtree_purge(&tp->out_of_order_queue);
4535e60402d0SIlpo Järvinen 	if (tcp_is_sack(tp))
45361da177e4SLinus Torvalds 		tcp_sack_reset(&tp->rx_opt);
45371da177e4SLinus Torvalds 
45381da177e4SLinus Torvalds 	if (!sock_flag(sk, SOCK_DEAD)) {
45391da177e4SLinus Torvalds 		sk->sk_state_change(sk);
45401da177e4SLinus Torvalds 
45411da177e4SLinus Torvalds 		/* Do not send POLL_HUP for half duplex close. */
45421da177e4SLinus Torvalds 		if (sk->sk_shutdown == SHUTDOWN_MASK ||
45431da177e4SLinus Torvalds 		    sk->sk_state == TCP_CLOSE)
45448d8ad9d7SPavel Emelyanov 			sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP);
45451da177e4SLinus Torvalds 		else
45468d8ad9d7SPavel Emelyanov 			sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
45471da177e4SLinus Torvalds 	}
45481da177e4SLinus Torvalds }
45491da177e4SLinus Torvalds 
tcp_sack_extend(struct tcp_sack_block * sp,u32 seq,u32 end_seq)4550a2a385d6SEric Dumazet static inline bool tcp_sack_extend(struct tcp_sack_block *sp, u32 seq,
4551056834d9SIlpo Järvinen 				  u32 end_seq)
45521da177e4SLinus Torvalds {
45531da177e4SLinus Torvalds 	if (!after(seq, sp->end_seq) && !after(sp->start_seq, end_seq)) {
45541da177e4SLinus Torvalds 		if (before(seq, sp->start_seq))
45551da177e4SLinus Torvalds 			sp->start_seq = seq;
45561da177e4SLinus Torvalds 		if (after(end_seq, sp->end_seq))
45571da177e4SLinus Torvalds 			sp->end_seq = end_seq;
4558a2a385d6SEric Dumazet 		return true;
45591da177e4SLinus Torvalds 	}
4560a2a385d6SEric Dumazet 	return false;
45611da177e4SLinus Torvalds }
45621da177e4SLinus Torvalds 
tcp_dsack_set(struct sock * sk,u32 seq,u32 end_seq)45631ed83465SPavel Emelyanov static void tcp_dsack_set(struct sock *sk, u32 seq, u32 end_seq)
45641da177e4SLinus Torvalds {
45651ed83465SPavel Emelyanov 	struct tcp_sock *tp = tcp_sk(sk);
45661ed83465SPavel Emelyanov 
456758ebb1c8SKuniyuki Iwashima 	if (tcp_is_sack(tp) && READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_dsack)) {
456840b215e5SPavel Emelyanov 		int mib_idx;
456940b215e5SPavel Emelyanov 
45701da177e4SLinus Torvalds 		if (before(seq, tp->rcv_nxt))
457140b215e5SPavel Emelyanov 			mib_idx = LINUX_MIB_TCPDSACKOLDSENT;
45721da177e4SLinus Torvalds 		else
457340b215e5SPavel Emelyanov 			mib_idx = LINUX_MIB_TCPDSACKOFOSENT;
457440b215e5SPavel Emelyanov 
4575c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), mib_idx);
45761da177e4SLinus Torvalds 
45771da177e4SLinus Torvalds 		tp->rx_opt.dsack = 1;
45781da177e4SLinus Torvalds 		tp->duplicate_sack[0].start_seq = seq;
45791da177e4SLinus Torvalds 		tp->duplicate_sack[0].end_seq = end_seq;
45801da177e4SLinus Torvalds 	}
45811da177e4SLinus Torvalds }
45821da177e4SLinus Torvalds 
tcp_dsack_extend(struct sock * sk,u32 seq,u32 end_seq)45831ed83465SPavel Emelyanov static void tcp_dsack_extend(struct sock *sk, u32 seq, u32 end_seq)
45841da177e4SLinus Torvalds {
45851ed83465SPavel Emelyanov 	struct tcp_sock *tp = tcp_sk(sk);
45861ed83465SPavel Emelyanov 
45871da177e4SLinus Torvalds 	if (!tp->rx_opt.dsack)
45881ed83465SPavel Emelyanov 		tcp_dsack_set(sk, seq, end_seq);
45891da177e4SLinus Torvalds 	else
45901da177e4SLinus Torvalds 		tcp_sack_extend(tp->duplicate_sack, seq, end_seq);
45911da177e4SLinus Torvalds }
45921da177e4SLinus Torvalds 
tcp_rcv_spurious_retrans(struct sock * sk,const struct sk_buff * skb)45937788174eSYuchung Cheng static void tcp_rcv_spurious_retrans(struct sock *sk, const struct sk_buff *skb)
45947788174eSYuchung Cheng {
45957788174eSYuchung Cheng 	/* When the ACK path fails or drops most ACKs, the sender would
45967788174eSYuchung Cheng 	 * timeout and spuriously retransmit the same segment repeatedly.
45977788174eSYuchung Cheng 	 * The receiver remembers and reflects via DSACKs. Leverage the
45987788174eSYuchung Cheng 	 * DSACK state and change the txhash to re-route speculatively.
45997788174eSYuchung Cheng 	 */
46009c30ae83SYuchung Cheng 	if (TCP_SKB_CB(skb)->seq == tcp_sk(sk)->duplicate_sack[0].start_seq &&
46019c30ae83SYuchung Cheng 	    sk_rethink_txhash(sk))
460232efcc06SAbdul Kabbani 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDUPLICATEDATAREHASH);
460332efcc06SAbdul Kabbani }
46047788174eSYuchung Cheng 
tcp_send_dupack(struct sock * sk,const struct sk_buff * skb)4605cf533ea5SEric Dumazet static void tcp_send_dupack(struct sock *sk, const struct sk_buff *skb)
46061da177e4SLinus Torvalds {
46071da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
46081da177e4SLinus Torvalds 
46091da177e4SLinus Torvalds 	if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
46101da177e4SLinus Torvalds 	    before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
4611c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_DELAYEDACKLOST);
46129a9c9b51SEric Dumazet 		tcp_enter_quickack_mode(sk, TCP_MAX_QUICKACKS);
46131da177e4SLinus Torvalds 
461458ebb1c8SKuniyuki Iwashima 		if (tcp_is_sack(tp) && READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_dsack)) {
46151da177e4SLinus Torvalds 			u32 end_seq = TCP_SKB_CB(skb)->end_seq;
46161da177e4SLinus Torvalds 
46177788174eSYuchung Cheng 			tcp_rcv_spurious_retrans(sk, skb);
46181da177e4SLinus Torvalds 			if (after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt))
46191da177e4SLinus Torvalds 				end_seq = tp->rcv_nxt;
46201ed83465SPavel Emelyanov 			tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, end_seq);
46211da177e4SLinus Torvalds 		}
46221da177e4SLinus Torvalds 	}
46231da177e4SLinus Torvalds 
46241da177e4SLinus Torvalds 	tcp_send_ack(sk);
46251da177e4SLinus Torvalds }
46261da177e4SLinus Torvalds 
46271da177e4SLinus Torvalds /* These routines update the SACK block as out-of-order packets arrive or
46281da177e4SLinus Torvalds  * in-order packets close up the sequence space.
46291da177e4SLinus Torvalds  */
tcp_sack_maybe_coalesce(struct tcp_sock * tp)46301da177e4SLinus Torvalds static void tcp_sack_maybe_coalesce(struct tcp_sock *tp)
46311da177e4SLinus Torvalds {
46321da177e4SLinus Torvalds 	int this_sack;
46331da177e4SLinus Torvalds 	struct tcp_sack_block *sp = &tp->selective_acks[0];
46341da177e4SLinus Torvalds 	struct tcp_sack_block *swalk = sp + 1;
46351da177e4SLinus Torvalds 
46361da177e4SLinus Torvalds 	/* See if the recent change to the first SACK eats into
46371da177e4SLinus Torvalds 	 * or hits the sequence space of other SACK blocks, if so coalesce.
46381da177e4SLinus Torvalds 	 */
46391da177e4SLinus Torvalds 	for (this_sack = 1; this_sack < tp->rx_opt.num_sacks;) {
46401da177e4SLinus Torvalds 		if (tcp_sack_extend(sp, swalk->start_seq, swalk->end_seq)) {
46411da177e4SLinus Torvalds 			int i;
46421da177e4SLinus Torvalds 
46431da177e4SLinus Torvalds 			/* Zap SWALK, by moving every further SACK up by one slot.
46441da177e4SLinus Torvalds 			 * Decrease num_sacks.
46451da177e4SLinus Torvalds 			 */
46461da177e4SLinus Torvalds 			tp->rx_opt.num_sacks--;
46471da177e4SLinus Torvalds 			for (i = this_sack; i < tp->rx_opt.num_sacks; i++)
46481da177e4SLinus Torvalds 				sp[i] = sp[i + 1];
46491da177e4SLinus Torvalds 			continue;
46501da177e4SLinus Torvalds 		}
465144797589SJulia Lawall 		this_sack++;
465244797589SJulia Lawall 		swalk++;
46531da177e4SLinus Torvalds 	}
46541da177e4SLinus Torvalds }
46551da177e4SLinus Torvalds 
tcp_sack_compress_send_ack(struct sock * sk)465630c6f0bfSfuyuanli void tcp_sack_compress_send_ack(struct sock *sk)
46572b195850SEric Dumazet {
46582b195850SEric Dumazet 	struct tcp_sock *tp = tcp_sk(sk);
46592b195850SEric Dumazet 
46602b195850SEric Dumazet 	if (!tp->compressed_ack)
46612b195850SEric Dumazet 		return;
46622b195850SEric Dumazet 
46632b195850SEric Dumazet 	if (hrtimer_try_to_cancel(&tp->compressed_ack_timer) == 1)
46642b195850SEric Dumazet 		__sock_put(sk);
46652b195850SEric Dumazet 
46662b195850SEric Dumazet 	/* Since we have to send one ack finally,
46672b195850SEric Dumazet 	 * substract one from tp->compressed_ack to keep
46682b195850SEric Dumazet 	 * LINUX_MIB_TCPACKCOMPRESSED accurate.
46692b195850SEric Dumazet 	 */
46702b195850SEric Dumazet 	NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPACKCOMPRESSED,
46712b195850SEric Dumazet 		      tp->compressed_ack - 1);
46722b195850SEric Dumazet 
46732b195850SEric Dumazet 	tp->compressed_ack = 0;
46742b195850SEric Dumazet 	tcp_send_ack(sk);
46752b195850SEric Dumazet }
46762b195850SEric Dumazet 
4677ccd0628fSEric Dumazet /* Reasonable amount of sack blocks included in TCP SACK option
4678ccd0628fSEric Dumazet  * The max is 4, but this becomes 3 if TCP timestamps are there.
4679ccd0628fSEric Dumazet  * Given that SACK packets might be lost, be conservative and use 2.
4680ccd0628fSEric Dumazet  */
4681ccd0628fSEric Dumazet #define TCP_SACK_BLOCKS_EXPECTED 2
4682ccd0628fSEric Dumazet 
tcp_sack_new_ofo_skb(struct sock * sk,u32 seq,u32 end_seq)46831da177e4SLinus Torvalds static void tcp_sack_new_ofo_skb(struct sock *sk, u32 seq, u32 end_seq)
46841da177e4SLinus Torvalds {
46851da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
46861da177e4SLinus Torvalds 	struct tcp_sack_block *sp = &tp->selective_acks[0];
46871da177e4SLinus Torvalds 	int cur_sacks = tp->rx_opt.num_sacks;
46881da177e4SLinus Torvalds 	int this_sack;
46891da177e4SLinus Torvalds 
46901da177e4SLinus Torvalds 	if (!cur_sacks)
46911da177e4SLinus Torvalds 		goto new_sack;
46921da177e4SLinus Torvalds 
46931da177e4SLinus Torvalds 	for (this_sack = 0; this_sack < cur_sacks; this_sack++, sp++) {
46941da177e4SLinus Torvalds 		if (tcp_sack_extend(sp, seq, end_seq)) {
4695ccd0628fSEric Dumazet 			if (this_sack >= TCP_SACK_BLOCKS_EXPECTED)
4696ccd0628fSEric Dumazet 				tcp_sack_compress_send_ack(sk);
46971da177e4SLinus Torvalds 			/* Rotate this_sack to the first one. */
46981da177e4SLinus Torvalds 			for (; this_sack > 0; this_sack--, sp--)
4699a0bffffcSIlpo Järvinen 				swap(*sp, *(sp - 1));
47001da177e4SLinus Torvalds 			if (cur_sacks > 1)
47011da177e4SLinus Torvalds 				tcp_sack_maybe_coalesce(tp);
47021da177e4SLinus Torvalds 			return;
47031da177e4SLinus Torvalds 		}
47041da177e4SLinus Torvalds 	}
47051da177e4SLinus Torvalds 
4706ccd0628fSEric Dumazet 	if (this_sack >= TCP_SACK_BLOCKS_EXPECTED)
4707ccd0628fSEric Dumazet 		tcp_sack_compress_send_ack(sk);
4708ccd0628fSEric Dumazet 
47091da177e4SLinus Torvalds 	/* Could not find an adjacent existing SACK, build a new one,
47101da177e4SLinus Torvalds 	 * put it at the front, and shift everyone else down.  We
47111da177e4SLinus Torvalds 	 * always know there is at least one SACK present already here.
47121da177e4SLinus Torvalds 	 *
47131da177e4SLinus Torvalds 	 * If the sack array is full, forget about the last one.
47141da177e4SLinus Torvalds 	 */
47154389ddedSAdam Langley 	if (this_sack >= TCP_NUM_SACKS) {
47161da177e4SLinus Torvalds 		this_sack--;
47171da177e4SLinus Torvalds 		tp->rx_opt.num_sacks--;
47181da177e4SLinus Torvalds 		sp--;
47191da177e4SLinus Torvalds 	}
47201da177e4SLinus Torvalds 	for (; this_sack > 0; this_sack--, sp--)
47211da177e4SLinus Torvalds 		*sp = *(sp - 1);
47221da177e4SLinus Torvalds 
47231da177e4SLinus Torvalds new_sack:
47241da177e4SLinus Torvalds 	/* Build the new head SACK, and we're done. */
47251da177e4SLinus Torvalds 	sp->start_seq = seq;
47261da177e4SLinus Torvalds 	sp->end_seq = end_seq;
47271da177e4SLinus Torvalds 	tp->rx_opt.num_sacks++;
47281da177e4SLinus Torvalds }
47291da177e4SLinus Torvalds 
47301da177e4SLinus Torvalds /* RCV.NXT advances, some SACKs should be eaten. */
47311da177e4SLinus Torvalds 
tcp_sack_remove(struct tcp_sock * tp)47321da177e4SLinus Torvalds static void tcp_sack_remove(struct tcp_sock *tp)
47331da177e4SLinus Torvalds {
47341da177e4SLinus Torvalds 	struct tcp_sack_block *sp = &tp->selective_acks[0];
47351da177e4SLinus Torvalds 	int num_sacks = tp->rx_opt.num_sacks;
47361da177e4SLinus Torvalds 	int this_sack;
47371da177e4SLinus Torvalds 
47381da177e4SLinus Torvalds 	/* Empty ofo queue, hence, all the SACKs are eaten. Clear. */
47399f5afeaeSYaogong Wang 	if (RB_EMPTY_ROOT(&tp->out_of_order_queue)) {
47401da177e4SLinus Torvalds 		tp->rx_opt.num_sacks = 0;
47411da177e4SLinus Torvalds 		return;
47421da177e4SLinus Torvalds 	}
47431da177e4SLinus Torvalds 
47441da177e4SLinus Torvalds 	for (this_sack = 0; this_sack < num_sacks;) {
47451da177e4SLinus Torvalds 		/* Check if the start of the sack is covered by RCV.NXT. */
47461da177e4SLinus Torvalds 		if (!before(tp->rcv_nxt, sp->start_seq)) {
47471da177e4SLinus Torvalds 			int i;
47481da177e4SLinus Torvalds 
47491da177e4SLinus Torvalds 			/* RCV.NXT must cover all the block! */
4750547b792cSIlpo Järvinen 			WARN_ON(before(tp->rcv_nxt, sp->end_seq));
47511da177e4SLinus Torvalds 
47521da177e4SLinus Torvalds 			/* Zap this SACK, by moving forward any other SACKS. */
47531da177e4SLinus Torvalds 			for (i = this_sack+1; i < num_sacks; i++)
47541da177e4SLinus Torvalds 				tp->selective_acks[i-1] = tp->selective_acks[i];
47551da177e4SLinus Torvalds 			num_sacks--;
47561da177e4SLinus Torvalds 			continue;
47571da177e4SLinus Torvalds 		}
47581da177e4SLinus Torvalds 		this_sack++;
47591da177e4SLinus Torvalds 		sp++;
47601da177e4SLinus Torvalds 	}
47611da177e4SLinus Torvalds 	tp->rx_opt.num_sacks = num_sacks;
47621da177e4SLinus Torvalds }
47631da177e4SLinus Torvalds 
47641402d366SEric Dumazet /**
47651402d366SEric Dumazet  * tcp_try_coalesce - try to merge skb to prior one
47661402d366SEric Dumazet  * @sk: socket
47671402d366SEric Dumazet  * @to: prior buffer
47681402d366SEric Dumazet  * @from: buffer to add in queue
4769923dd347SEric Dumazet  * @fragstolen: pointer to boolean
47701402d366SEric Dumazet  *
47711402d366SEric Dumazet  * Before queueing skb @from after @to, try to merge them
47721402d366SEric Dumazet  * to reduce overall memory use and queue lengths, if cost is small.
47731402d366SEric Dumazet  * Packets in ofo or receive queues can stay a long time.
47741402d366SEric Dumazet  * Better try to coalesce them right now to avoid future collapses.
4775783c175fSEric Dumazet  * Returns true if caller should free @from instead of queueing it
47761402d366SEric Dumazet  */
tcp_try_coalesce(struct sock * sk,struct sk_buff * to,struct sk_buff * from,bool * fragstolen)4777783c175fSEric Dumazet static bool tcp_try_coalesce(struct sock *sk,
47781402d366SEric Dumazet 			     struct sk_buff *to,
4779329033f6SEric Dumazet 			     struct sk_buff *from,
4780329033f6SEric Dumazet 			     bool *fragstolen)
47811402d366SEric Dumazet {
4782bad43ca8SEric Dumazet 	int delta;
47831402d366SEric Dumazet 
4784329033f6SEric Dumazet 	*fragstolen = false;
478534a802a5SAlexander Duyck 
47861ca7ee30SEric Dumazet 	/* Its possible this segment overlaps with prior segment in queue */
47871ca7ee30SEric Dumazet 	if (TCP_SKB_CB(from)->seq != TCP_SKB_CB(to)->end_seq)
47881ca7ee30SEric Dumazet 		return false;
47891ca7ee30SEric Dumazet 
479085712484SMat Martineau 	if (!mptcp_skb_can_collapse(to, from))
479185712484SMat Martineau 		return false;
479285712484SMat Martineau 
479341ed9c04SBoris Pismenny #ifdef CONFIG_TLS_DEVICE
479441ed9c04SBoris Pismenny 	if (from->decrypted != to->decrypted)
479541ed9c04SBoris Pismenny 		return false;
479641ed9c04SBoris Pismenny #endif
479741ed9c04SBoris Pismenny 
4798bad43ca8SEric Dumazet 	if (!skb_try_coalesce(to, from, fragstolen, &delta))
4799783c175fSEric Dumazet 		return false;
480034a802a5SAlexander Duyck 
48011402d366SEric Dumazet 	atomic_add(delta, &sk->sk_rmem_alloc);
48021402d366SEric Dumazet 	sk_mem_charge(sk, delta);
4803c10d9310SEric Dumazet 	NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPRCVCOALESCE);
480434a802a5SAlexander Duyck 	TCP_SKB_CB(to)->end_seq = TCP_SKB_CB(from)->end_seq;
480534a802a5SAlexander Duyck 	TCP_SKB_CB(to)->ack_seq = TCP_SKB_CB(from)->ack_seq;
4806e93a0435SEric Dumazet 	TCP_SKB_CB(to)->tcp_flags |= TCP_SKB_CB(from)->tcp_flags;
480798aaa913SMike Maloney 
480898aaa913SMike Maloney 	if (TCP_SKB_CB(from)->has_rxtstamp) {
480998aaa913SMike Maloney 		TCP_SKB_CB(to)->has_rxtstamp = true;
481098aaa913SMike Maloney 		to->tstamp = from->tstamp;
4811cadf9df2SStephen Mallon 		skb_hwtstamps(to)->hwtstamp = skb_hwtstamps(from)->hwtstamp;
481298aaa913SMike Maloney 	}
481398aaa913SMike Maloney 
481434a802a5SAlexander Duyck 	return true;
48151402d366SEric Dumazet }
48161402d366SEric Dumazet 
tcp_ooo_try_coalesce(struct sock * sk,struct sk_buff * to,struct sk_buff * from,bool * fragstolen)481758152ecbSEric Dumazet static bool tcp_ooo_try_coalesce(struct sock *sk,
481858152ecbSEric Dumazet 			     struct sk_buff *to,
481958152ecbSEric Dumazet 			     struct sk_buff *from,
482058152ecbSEric Dumazet 			     bool *fragstolen)
482158152ecbSEric Dumazet {
482258152ecbSEric Dumazet 	bool res = tcp_try_coalesce(sk, to, from, fragstolen);
482358152ecbSEric Dumazet 
48248fbf1957SEric Dumazet 	/* In case tcp_drop_reason() is called later, update to->gso_segs */
482558152ecbSEric Dumazet 	if (res) {
482658152ecbSEric Dumazet 		u32 gso_segs = max_t(u16, 1, skb_shinfo(to)->gso_segs) +
482758152ecbSEric Dumazet 			       max_t(u16, 1, skb_shinfo(from)->gso_segs);
482858152ecbSEric Dumazet 
482958152ecbSEric Dumazet 		skb_shinfo(to)->gso_segs = min_t(u32, gso_segs, 0xFFFF);
483058152ecbSEric Dumazet 	}
483158152ecbSEric Dumazet 	return res;
483258152ecbSEric Dumazet }
483358152ecbSEric Dumazet 
tcp_drop_reason(struct sock * sk,struct sk_buff * skb,enum skb_drop_reason reason)4834082116ffSMenglong Dong static void tcp_drop_reason(struct sock *sk, struct sk_buff *skb,
4835082116ffSMenglong Dong 			    enum skb_drop_reason reason)
4836532182cdSEric Dumazet {
4837532182cdSEric Dumazet 	sk_drops_add(sk, skb);
4838082116ffSMenglong Dong 	kfree_skb_reason(skb, reason);
4839082116ffSMenglong Dong }
4840082116ffSMenglong Dong 
48411da177e4SLinus Torvalds /* This one checks to see if we can put data from the
48421da177e4SLinus Torvalds  * out_of_order queue into the receive_queue.
48431da177e4SLinus Torvalds  */
tcp_ofo_queue(struct sock * sk)48441da177e4SLinus Torvalds static void tcp_ofo_queue(struct sock *sk)
48451da177e4SLinus Torvalds {
48461da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
48471da177e4SLinus Torvalds 	__u32 dsack_high = tp->rcv_nxt;
48489f5afeaeSYaogong Wang 	bool fin, fragstolen, eaten;
4849bd1e75abSEric Dumazet 	struct sk_buff *skb, *tail;
48509f5afeaeSYaogong Wang 	struct rb_node *p;
48511da177e4SLinus Torvalds 
48529f5afeaeSYaogong Wang 	p = rb_first(&tp->out_of_order_queue);
48539f5afeaeSYaogong Wang 	while (p) {
485418a4c0eaSEric Dumazet 		skb = rb_to_skb(p);
48551da177e4SLinus Torvalds 		if (after(TCP_SKB_CB(skb)->seq, tp->rcv_nxt))
48561da177e4SLinus Torvalds 			break;
48571da177e4SLinus Torvalds 
48581da177e4SLinus Torvalds 		if (before(TCP_SKB_CB(skb)->seq, dsack_high)) {
48591da177e4SLinus Torvalds 			__u32 dsack = dsack_high;
48601da177e4SLinus Torvalds 			if (before(TCP_SKB_CB(skb)->end_seq, dsack_high))
48611da177e4SLinus Torvalds 				dsack_high = TCP_SKB_CB(skb)->end_seq;
48621da177e4SLinus Torvalds 			tcp_dsack_extend(sk, TCP_SKB_CB(skb)->seq, dsack);
48631da177e4SLinus Torvalds 		}
48649f5afeaeSYaogong Wang 		p = rb_next(p);
48659f5afeaeSYaogong Wang 		rb_erase(&skb->rbnode, &tp->out_of_order_queue);
48661da177e4SLinus Torvalds 
48679f5afeaeSYaogong Wang 		if (unlikely(!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt))) {
48688fbf1957SEric Dumazet 			tcp_drop_reason(sk, skb, SKB_DROP_REASON_TCP_OFO_DROP);
48691da177e4SLinus Torvalds 			continue;
48701da177e4SLinus Torvalds 		}
48711da177e4SLinus Torvalds 
4872bd1e75abSEric Dumazet 		tail = skb_peek_tail(&sk->sk_receive_queue);
4873bffa72cfSEric Dumazet 		eaten = tail && tcp_try_coalesce(sk, tail, skb, &fragstolen);
4874bdd1f9edSEric Dumazet 		tcp_rcv_nxt_update(tp, TCP_SKB_CB(skb)->end_seq);
48759f5afeaeSYaogong Wang 		fin = TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN;
4876bd1e75abSEric Dumazet 		if (!eaten)
4877*f1d5e6a5SSabrina Dubroca 			tcp_add_receive_queue(sk, skb);
48789f5afeaeSYaogong Wang 		else
4879bd1e75abSEric Dumazet 			kfree_skb_partial(skb, fragstolen);
48809f5afeaeSYaogong Wang 
48819f5afeaeSYaogong Wang 		if (unlikely(fin)) {
48829f5afeaeSYaogong Wang 			tcp_fin(sk);
48839f5afeaeSYaogong Wang 			/* tcp_fin() purges tp->out_of_order_queue,
48849f5afeaeSYaogong Wang 			 * so we must end this loop right now.
48859f5afeaeSYaogong Wang 			 */
48869f5afeaeSYaogong Wang 			break;
48879f5afeaeSYaogong Wang 		}
48881da177e4SLinus Torvalds 	}
48891da177e4SLinus Torvalds }
48901da177e4SLinus Torvalds 
4891b0e01253SEric Dumazet static bool tcp_prune_ofo_queue(struct sock *sk, const struct sk_buff *in_skb);
4892b0e01253SEric Dumazet static int tcp_prune_queue(struct sock *sk, const struct sk_buff *in_skb);
48931da177e4SLinus Torvalds 
tcp_try_rmem_schedule(struct sock * sk,struct sk_buff * skb,unsigned int size)48941da177e4SLinus Torvalds static int tcp_try_rmem_schedule(struct sock *sk, struct sk_buff *skb,
48951da177e4SLinus Torvalds 				 unsigned int size)
48961da177e4SLinus Torvalds {
48971da177e4SLinus Torvalds 	if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
48981da177e4SLinus Torvalds 	    !sk_rmem_schedule(sk, skb, size)) {
48991da177e4SLinus Torvalds 
4900b0e01253SEric Dumazet 		if (tcp_prune_queue(sk, skb) < 0)
49011da177e4SLinus Torvalds 			return -1;
49021ed83465SPavel Emelyanov 
490336a6503fSEric Dumazet 		while (!sk_rmem_schedule(sk, skb, size)) {
4904b0e01253SEric Dumazet 			if (!tcp_prune_ofo_queue(sk, skb))
49051da177e4SLinus Torvalds 				return -1;
49061da177e4SLinus Torvalds 		}
49071da177e4SLinus Torvalds 	}
49081da177e4SLinus Torvalds 	return 0;
49091da177e4SLinus Torvalds }
49101da177e4SLinus Torvalds 
tcp_data_queue_ofo(struct sock * sk,struct sk_buff * skb)4911e86b2919SEric Dumazet static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb)
4912e86b2919SEric Dumazet {
4913e86b2919SEric Dumazet 	struct tcp_sock *tp = tcp_sk(sk);
491418a4c0eaSEric Dumazet 	struct rb_node **p, *parent;
4915e86b2919SEric Dumazet 	struct sk_buff *skb1;
4916e86b2919SEric Dumazet 	u32 seq, end_seq;
49179f5afeaeSYaogong Wang 	bool fragstolen;
4918e86b2919SEric Dumazet 
4919f4c9f85fSYousuk Seung 	tcp_ecn_check_ce(sk, skb);
4920e86b2919SEric Dumazet 
4921c76562b6SMel Gorman 	if (unlikely(tcp_try_rmem_schedule(sk, skb, skb->truesize))) {
4922c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPOFODROP);
4923ba3bb0e7SEric Dumazet 		sk->sk_data_ready(sk);
4924d25e481bSMenglong Dong 		tcp_drop_reason(sk, skb, SKB_DROP_REASON_PROTO_MEM);
4925e86b2919SEric Dumazet 		return;
4926e86b2919SEric Dumazet 	}
4927e86b2919SEric Dumazet 
492831770e34SFlorian Westphal 	/* Disable header prediction. */
492931770e34SFlorian Westphal 	tp->pred_flags = 0;
4930e86b2919SEric Dumazet 	inet_csk_schedule_ack(sk);
4931e86b2919SEric Dumazet 
4932f9af2dbbSThomas Higdon 	tp->rcv_ooopack += max_t(u16, 1, skb_shinfo(skb)->gso_segs);
4933c10d9310SEric Dumazet 	NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPOFOQUEUE);
49349f5afeaeSYaogong Wang 	seq = TCP_SKB_CB(skb)->seq;
49359f5afeaeSYaogong Wang 	end_seq = TCP_SKB_CB(skb)->end_seq;
4936e86b2919SEric Dumazet 
49379f5afeaeSYaogong Wang 	p = &tp->out_of_order_queue.rb_node;
49389f5afeaeSYaogong Wang 	if (RB_EMPTY_ROOT(&tp->out_of_order_queue)) {
4939e86b2919SEric Dumazet 		/* Initial out of order segment, build 1 SACK. */
4940e86b2919SEric Dumazet 		if (tcp_is_sack(tp)) {
4941e86b2919SEric Dumazet 			tp->rx_opt.num_sacks = 1;
49429f5afeaeSYaogong Wang 			tp->selective_acks[0].start_seq = seq;
49439f5afeaeSYaogong Wang 			tp->selective_acks[0].end_seq = end_seq;
4944e86b2919SEric Dumazet 		}
49459f5afeaeSYaogong Wang 		rb_link_node(&skb->rbnode, NULL, p);
49469f5afeaeSYaogong Wang 		rb_insert_color(&skb->rbnode, &tp->out_of_order_queue);
49479f5afeaeSYaogong Wang 		tp->ooo_last_skb = skb;
4948e86b2919SEric Dumazet 		goto end;
4949e86b2919SEric Dumazet 	}
4950e86b2919SEric Dumazet 
49519f5afeaeSYaogong Wang 	/* In the typical case, we are adding an skb to the end of the list.
49529f5afeaeSYaogong Wang 	 * Use of ooo_last_skb avoids the O(Log(N)) rbtree lookup.
49539f5afeaeSYaogong Wang 	 */
495458152ecbSEric Dumazet 	if (tcp_ooo_try_coalesce(sk, tp->ooo_last_skb,
495598aaa913SMike Maloney 				 skb, &fragstolen)) {
49569f5afeaeSYaogong Wang coalesce_done:
495766205121SEric Dumazet 		/* For non sack flows, do not grow window to force DUPACK
495866205121SEric Dumazet 		 * and trigger fast retransmit.
495966205121SEric Dumazet 		 */
496066205121SEric Dumazet 		if (tcp_is_sack(tp))
4961240bfd13SEric Dumazet 			tcp_grow_window(sk, skb, true);
4962923dd347SEric Dumazet 		kfree_skb_partial(skb, fragstolen);
4963c8628155SEric Dumazet 		skb = NULL;
4964e86b2919SEric Dumazet 		goto add_sack;
4965e86b2919SEric Dumazet 	}
49662594a2a9SEric Dumazet 	/* Can avoid an rbtree lookup if we are adding skb after ooo_last_skb */
49672594a2a9SEric Dumazet 	if (!before(seq, TCP_SKB_CB(tp->ooo_last_skb)->end_seq)) {
49682594a2a9SEric Dumazet 		parent = &tp->ooo_last_skb->rbnode;
49692594a2a9SEric Dumazet 		p = &parent->rb_right;
49702594a2a9SEric Dumazet 		goto insert;
4971e86b2919SEric Dumazet 	}
4972e86b2919SEric Dumazet 
49739f5afeaeSYaogong Wang 	/* Find place to insert this segment. Handle overlaps on the way. */
49749f5afeaeSYaogong Wang 	parent = NULL;
49759f5afeaeSYaogong Wang 	while (*p) {
49769f5afeaeSYaogong Wang 		parent = *p;
497718a4c0eaSEric Dumazet 		skb1 = rb_to_skb(parent);
49789f5afeaeSYaogong Wang 		if (before(seq, TCP_SKB_CB(skb1)->seq)) {
49799f5afeaeSYaogong Wang 			p = &parent->rb_left;
49809f5afeaeSYaogong Wang 			continue;
4981e86b2919SEric Dumazet 		}
49829f5afeaeSYaogong Wang 		if (before(seq, TCP_SKB_CB(skb1)->end_seq)) {
4983e86b2919SEric Dumazet 			if (!after(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
4984e86b2919SEric Dumazet 				/* All the bits are present. Drop. */
49859f5afeaeSYaogong Wang 				NET_INC_STATS(sock_net(sk),
49869f5afeaeSYaogong Wang 					      LINUX_MIB_TCPOFOMERGE);
4987d25e481bSMenglong Dong 				tcp_drop_reason(sk, skb,
4988d25e481bSMenglong Dong 						SKB_DROP_REASON_TCP_OFOMERGE);
4989e86b2919SEric Dumazet 				skb = NULL;
4990e86b2919SEric Dumazet 				tcp_dsack_set(sk, seq, end_seq);
4991e86b2919SEric Dumazet 				goto add_sack;
4992e86b2919SEric Dumazet 			}
4993e86b2919SEric Dumazet 			if (after(seq, TCP_SKB_CB(skb1)->seq)) {
4994e86b2919SEric Dumazet 				/* Partial overlap. */
49959f5afeaeSYaogong Wang 				tcp_dsack_set(sk, seq, TCP_SKB_CB(skb1)->end_seq);
4996e86b2919SEric Dumazet 			} else {
49979f5afeaeSYaogong Wang 				/* skb's seq == skb1's seq and skb covers skb1.
49989f5afeaeSYaogong Wang 				 * Replace skb1 with skb.
49999f5afeaeSYaogong Wang 				 */
50009f5afeaeSYaogong Wang 				rb_replace_node(&skb1->rbnode, &skb->rbnode,
50019f5afeaeSYaogong Wang 						&tp->out_of_order_queue);
50029f5afeaeSYaogong Wang 				tcp_dsack_extend(sk,
50039f5afeaeSYaogong Wang 						 TCP_SKB_CB(skb1)->seq,
50049f5afeaeSYaogong Wang 						 TCP_SKB_CB(skb1)->end_seq);
50059f5afeaeSYaogong Wang 				NET_INC_STATS(sock_net(sk),
50069f5afeaeSYaogong Wang 					      LINUX_MIB_TCPOFOMERGE);
5007d25e481bSMenglong Dong 				tcp_drop_reason(sk, skb1,
5008d25e481bSMenglong Dong 						SKB_DROP_REASON_TCP_OFOMERGE);
500976f0dcbbSEric Dumazet 				goto merge_right;
5010e86b2919SEric Dumazet 			}
501158152ecbSEric Dumazet 		} else if (tcp_ooo_try_coalesce(sk, skb1,
501298aaa913SMike Maloney 						skb, &fragstolen)) {
50139f5afeaeSYaogong Wang 			goto coalesce_done;
5014e86b2919SEric Dumazet 		}
50159f5afeaeSYaogong Wang 		p = &parent->rb_right;
50169f5afeaeSYaogong Wang 	}
50172594a2a9SEric Dumazet insert:
50189f5afeaeSYaogong Wang 	/* Insert segment into RB tree. */
50199f5afeaeSYaogong Wang 	rb_link_node(&skb->rbnode, parent, p);
50209f5afeaeSYaogong Wang 	rb_insert_color(&skb->rbnode, &tp->out_of_order_queue);
5021e86b2919SEric Dumazet 
502276f0dcbbSEric Dumazet merge_right:
50239f5afeaeSYaogong Wang 	/* Remove other segments covered by skb. */
502418a4c0eaSEric Dumazet 	while ((skb1 = skb_rb_next(skb)) != NULL) {
5025e86b2919SEric Dumazet 		if (!after(end_seq, TCP_SKB_CB(skb1)->seq))
5026e86b2919SEric Dumazet 			break;
5027e86b2919SEric Dumazet 		if (before(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
5028e86b2919SEric Dumazet 			tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq,
5029e86b2919SEric Dumazet 					 end_seq);
5030e86b2919SEric Dumazet 			break;
5031e86b2919SEric Dumazet 		}
50329f5afeaeSYaogong Wang 		rb_erase(&skb1->rbnode, &tp->out_of_order_queue);
5033e86b2919SEric Dumazet 		tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq,
5034e86b2919SEric Dumazet 				 TCP_SKB_CB(skb1)->end_seq);
5035c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPOFOMERGE);
5036d25e481bSMenglong Dong 		tcp_drop_reason(sk, skb1, SKB_DROP_REASON_TCP_OFOMERGE);
5037e86b2919SEric Dumazet 	}
50389f5afeaeSYaogong Wang 	/* If there is no skb after us, we are the last_skb ! */
503918a4c0eaSEric Dumazet 	if (!skb1)
50409f5afeaeSYaogong Wang 		tp->ooo_last_skb = skb;
5041e86b2919SEric Dumazet 
5042e86b2919SEric Dumazet add_sack:
5043e86b2919SEric Dumazet 	if (tcp_is_sack(tp))
5044e86b2919SEric Dumazet 		tcp_sack_new_ofo_skb(sk, seq, end_seq);
5045e86b2919SEric Dumazet end:
50464e4f1fc2SEric Dumazet 	if (skb) {
504766205121SEric Dumazet 		/* For non sack flows, do not grow window to force DUPACK
504866205121SEric Dumazet 		 * and trigger fast retransmit.
504966205121SEric Dumazet 		 */
505066205121SEric Dumazet 		if (tcp_is_sack(tp))
5051240bfd13SEric Dumazet 			tcp_grow_window(sk, skb, false);
505260b1af33SEric Dumazet 		skb_condense(skb);
5053e86b2919SEric Dumazet 		skb_set_owner_r(skb, sk);
5054e86b2919SEric Dumazet 	}
50554e4f1fc2SEric Dumazet }
5056e86b2919SEric Dumazet 
tcp_queue_rcv(struct sock * sk,struct sk_buff * skb,bool * fragstolen)5057e7395f1fSEric Dumazet static int __must_check tcp_queue_rcv(struct sock *sk, struct sk_buff *skb,
5058b081f85cSEric Dumazet 				      bool *fragstolen)
5059b081f85cSEric Dumazet {
5060b081f85cSEric Dumazet 	int eaten;
5061b081f85cSEric Dumazet 	struct sk_buff *tail = skb_peek_tail(&sk->sk_receive_queue);
5062b081f85cSEric Dumazet 
5063b081f85cSEric Dumazet 	eaten = (tail &&
5064bffa72cfSEric Dumazet 		 tcp_try_coalesce(sk, tail,
506598aaa913SMike Maloney 				  skb, fragstolen)) ? 1 : 0;
5066bdd1f9edSEric Dumazet 	tcp_rcv_nxt_update(tcp_sk(sk), TCP_SKB_CB(skb)->end_seq);
5067b081f85cSEric Dumazet 	if (!eaten) {
5068*f1d5e6a5SSabrina Dubroca 		tcp_add_receive_queue(sk, skb);
5069b081f85cSEric Dumazet 		skb_set_owner_r(skb, sk);
5070b081f85cSEric Dumazet 	}
5071b081f85cSEric Dumazet 	return eaten;
5072b081f85cSEric Dumazet }
5073e86b2919SEric Dumazet 
tcp_send_rcvq(struct sock * sk,struct msghdr * msg,size_t size)5074292e8d8cSPavel Emelyanov int tcp_send_rcvq(struct sock *sk, struct msghdr *msg, size_t size)
5075292e8d8cSPavel Emelyanov {
5076cb93471aSEric Dumazet 	struct sk_buff *skb;
50775d4c9bfbSEric Dumazet 	int err = -ENOMEM;
50785d4c9bfbSEric Dumazet 	int data_len = 0;
5079292e8d8cSPavel Emelyanov 	bool fragstolen;
5080292e8d8cSPavel Emelyanov 
5081c454e611SPavel Emelyanov 	if (size == 0)
5082c454e611SPavel Emelyanov 		return 0;
5083c454e611SPavel Emelyanov 
50845d4c9bfbSEric Dumazet 	if (size > PAGE_SIZE) {
50855d4c9bfbSEric Dumazet 		int npages = min_t(size_t, size >> PAGE_SHIFT, MAX_SKB_FRAGS);
50865d4c9bfbSEric Dumazet 
50875d4c9bfbSEric Dumazet 		data_len = npages << PAGE_SHIFT;
50885d4c9bfbSEric Dumazet 		size = data_len + (size & ~PAGE_MASK);
50895d4c9bfbSEric Dumazet 	}
50905d4c9bfbSEric Dumazet 	skb = alloc_skb_with_frags(size - data_len, data_len,
50915d4c9bfbSEric Dumazet 				   PAGE_ALLOC_COSTLY_ORDER,
50925d4c9bfbSEric Dumazet 				   &err, sk->sk_allocation);
5093292e8d8cSPavel Emelyanov 	if (!skb)
5094292e8d8cSPavel Emelyanov 		goto err;
5095292e8d8cSPavel Emelyanov 
50965d4c9bfbSEric Dumazet 	skb_put(skb, size - data_len);
50975d4c9bfbSEric Dumazet 	skb->data_len = data_len;
50985d4c9bfbSEric Dumazet 	skb->len = size;
50995d4c9bfbSEric Dumazet 
5100ea5d0c32SYafang Shao 	if (tcp_try_rmem_schedule(sk, skb, skb->truesize)) {
5101ea5d0c32SYafang Shao 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPRCVQDROP);
5102c76562b6SMel Gorman 		goto err_free;
5103ea5d0c32SYafang Shao 	}
5104c76562b6SMel Gorman 
51055d4c9bfbSEric Dumazet 	err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, size);
51065d4c9bfbSEric Dumazet 	if (err)
5107292e8d8cSPavel Emelyanov 		goto err_free;
5108292e8d8cSPavel Emelyanov 
5109292e8d8cSPavel Emelyanov 	TCP_SKB_CB(skb)->seq = tcp_sk(sk)->rcv_nxt;
5110292e8d8cSPavel Emelyanov 	TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(skb)->seq + size;
5111292e8d8cSPavel Emelyanov 	TCP_SKB_CB(skb)->ack_seq = tcp_sk(sk)->snd_una - 1;
5112292e8d8cSPavel Emelyanov 
5113e7395f1fSEric Dumazet 	if (tcp_queue_rcv(sk, skb, &fragstolen)) {
5114292e8d8cSPavel Emelyanov 		WARN_ON_ONCE(fragstolen); /* should not happen */
5115292e8d8cSPavel Emelyanov 		__kfree_skb(skb);
5116292e8d8cSPavel Emelyanov 	}
5117292e8d8cSPavel Emelyanov 	return size;
5118292e8d8cSPavel Emelyanov 
5119292e8d8cSPavel Emelyanov err_free:
5120292e8d8cSPavel Emelyanov 	kfree_skb(skb);
5121292e8d8cSPavel Emelyanov err:
51225d4c9bfbSEric Dumazet 	return err;
51235d4c9bfbSEric Dumazet 
5124292e8d8cSPavel Emelyanov }
5125292e8d8cSPavel Emelyanov 
tcp_data_ready(struct sock * sk)512603f45c88SEric Dumazet void tcp_data_ready(struct sock *sk)
512703f45c88SEric Dumazet {
512839354eb2SEric Dumazet 	if (tcp_epollin_ready(sk, sk->sk_rcvlowat) || sock_flag(sk, SOCK_DONE))
512903f45c88SEric Dumazet 		sk->sk_data_ready(sk);
513003f45c88SEric Dumazet }
513103f45c88SEric Dumazet 
tcp_data_queue(struct sock * sk,struct sk_buff * skb)51321da177e4SLinus Torvalds static void tcp_data_queue(struct sock *sk, struct sk_buff *skb)
51331da177e4SLinus Torvalds {
51341da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
5135a7ec3810SMenglong Dong 	enum skb_drop_reason reason;
51365357f0bdSEric Dumazet 	bool fragstolen;
51375357f0bdSEric Dumazet 	int eaten;
51381da177e4SLinus Torvalds 
51396787b7e3SJianguo Wu 	/* If a subflow has been reset, the packet should not continue
51406787b7e3SJianguo Wu 	 * to be processed, drop the packet.
51416787b7e3SJianguo Wu 	 */
51426787b7e3SJianguo Wu 	if (sk_is_mptcp(sk) && !mptcp_incoming_options(sk, skb)) {
51436787b7e3SJianguo Wu 		__kfree_skb(skb);
51446787b7e3SJianguo Wu 		return;
51456787b7e3SJianguo Wu 	}
5146648ef4b8SMat Martineau 
5147532182cdSEric Dumazet 	if (TCP_SKB_CB(skb)->seq == TCP_SKB_CB(skb)->end_seq) {
5148532182cdSEric Dumazet 		__kfree_skb(skb);
5149532182cdSEric Dumazet 		return;
5150532182cdSEric Dumazet 	}
5151*f1d5e6a5SSabrina Dubroca 	tcp_cleanup_skb(skb);
5152155c6e1aSPeter Pan(潘卫平) 	__skb_pull(skb, tcp_hdr(skb)->doff * 4);
51531da177e4SLinus Torvalds 
5154a7ec3810SMenglong Dong 	reason = SKB_DROP_REASON_NOT_SPECIFIED;
51551da177e4SLinus Torvalds 	tp->rx_opt.dsack = 0;
51561da177e4SLinus Torvalds 
51571da177e4SLinus Torvalds 	/*  Queue data for delivery to the user.
51581da177e4SLinus Torvalds 	 *  Packets in sequence go to the receive queue.
51591da177e4SLinus Torvalds 	 *  Out of sequence packets to the out_of_order_queue.
51601da177e4SLinus Torvalds 	 */
51611da177e4SLinus Torvalds 	if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt) {
5162fb223502SYafang Shao 		if (tcp_receive_window(tp) == 0) {
5163a7ec3810SMenglong Dong 			reason = SKB_DROP_REASON_TCP_ZEROWINDOW;
5164fb223502SYafang Shao 			NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPZEROWINDOWDROP);
51651da177e4SLinus Torvalds 			goto out_of_window;
5166fb223502SYafang Shao 		}
51671da177e4SLinus Torvalds 
51681da177e4SLinus Torvalds 		/* Ok. In sequence. In window. */
51691da177e4SLinus Torvalds queue_and_out:
5170e2142825SMenglong Dong 		if (tcp_try_rmem_schedule(sk, skb, skb->truesize)) {
5171e2142825SMenglong Dong 			/* TODO: maybe ratelimit these WIN 0 ACK ? */
5172e2142825SMenglong Dong 			inet_csk(sk)->icsk_ack.pending |=
5173e2142825SMenglong Dong 					(ICSK_ACK_NOMEM | ICSK_ACK_NOW);
5174e2142825SMenglong Dong 			inet_csk_schedule_ack(sk);
5175e2142825SMenglong Dong 			sk->sk_data_ready(sk);
5176e2142825SMenglong Dong 
5177e2142825SMenglong Dong 			if (skb_queue_len(&sk->sk_receive_queue)) {
5178a7ec3810SMenglong Dong 				reason = SKB_DROP_REASON_PROTO_MEM;
5179ea5d0c32SYafang Shao 				NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPRCVQDROP);
51801da177e4SLinus Torvalds 				goto drop;
5181ea5d0c32SYafang Shao 			}
5182e2142825SMenglong Dong 			sk_forced_mem_schedule(sk, skb->truesize);
5183e2142825SMenglong Dong 		}
51845357f0bdSEric Dumazet 
5185e7395f1fSEric Dumazet 		eaten = tcp_queue_rcv(sk, skb, &fragstolen);
51861da177e4SLinus Torvalds 		if (skb->len)
51879e412ba7SIlpo Järvinen 			tcp_event_data_recv(sk, skb);
5188155c6e1aSPeter Pan(潘卫平) 		if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
518920c4cb79SEric Dumazet 			tcp_fin(sk);
51901da177e4SLinus Torvalds 
51919f5afeaeSYaogong Wang 		if (!RB_EMPTY_ROOT(&tp->out_of_order_queue)) {
51921da177e4SLinus Torvalds 			tcp_ofo_queue(sk);
51931da177e4SLinus Torvalds 
519415bdd568SYuchung Cheng 			/* RFC5681. 4.2. SHOULD send immediate ACK, when
51951da177e4SLinus Torvalds 			 * gap in queue is filled.
51961da177e4SLinus Torvalds 			 */
51979f5afeaeSYaogong Wang 			if (RB_EMPTY_ROOT(&tp->out_of_order_queue))
519815bdd568SYuchung Cheng 				inet_csk(sk)->icsk_ack.pending |= ICSK_ACK_NOW;
51991da177e4SLinus Torvalds 		}
52001da177e4SLinus Torvalds 
52011da177e4SLinus Torvalds 		if (tp->rx_opt.num_sacks)
52021da177e4SLinus Torvalds 			tcp_sack_remove(tp);
52031da177e4SLinus Torvalds 
520431770e34SFlorian Westphal 		tcp_fast_path_check(sk);
520531770e34SFlorian Westphal 
5206923dd347SEric Dumazet 		if (eaten > 0)
5207923dd347SEric Dumazet 			kfree_skb_partial(skb, fragstolen);
52081d57f195SEric Dumazet 		if (!sock_flag(sk, SOCK_DEAD))
520903f45c88SEric Dumazet 			tcp_data_ready(sk);
52101da177e4SLinus Torvalds 		return;
52111da177e4SLinus Torvalds 	}
52121da177e4SLinus Torvalds 
52131da177e4SLinus Torvalds 	if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) {
52147788174eSYuchung Cheng 		tcp_rcv_spurious_retrans(sk, skb);
52151da177e4SLinus Torvalds 		/* A retransmit, 2nd most common case.  Force an immediate ack. */
5216a7ec3810SMenglong Dong 		reason = SKB_DROP_REASON_TCP_OLD_DATA;
5217c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_DELAYEDACKLOST);
52181ed83465SPavel Emelyanov 		tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq);
52191da177e4SLinus Torvalds 
52201da177e4SLinus Torvalds out_of_window:
52219a9c9b51SEric Dumazet 		tcp_enter_quickack_mode(sk, TCP_MAX_QUICKACKS);
5222463c84b9SArnaldo Carvalho de Melo 		inet_csk_schedule_ack(sk);
52231da177e4SLinus Torvalds drop:
5224a7ec3810SMenglong Dong 		tcp_drop_reason(sk, skb, reason);
52251da177e4SLinus Torvalds 		return;
52261da177e4SLinus Torvalds 	}
52271da177e4SLinus Torvalds 
52281da177e4SLinus Torvalds 	/* Out of window. F.e. zero window probe. */
5229a7ec3810SMenglong Dong 	if (!before(TCP_SKB_CB(skb)->seq,
5230a7ec3810SMenglong Dong 		    tp->rcv_nxt + tcp_receive_window(tp))) {
5231a7ec3810SMenglong Dong 		reason = SKB_DROP_REASON_TCP_OVERWINDOW;
52321da177e4SLinus Torvalds 		goto out_of_window;
5233a7ec3810SMenglong Dong 	}
52341da177e4SLinus Torvalds 
52351da177e4SLinus Torvalds 	if (before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
52361da177e4SLinus Torvalds 		/* Partial packet, seq < rcv_next < end_seq */
52371ed83465SPavel Emelyanov 		tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, tp->rcv_nxt);
52381da177e4SLinus Torvalds 
52391da177e4SLinus Torvalds 		/* If window is closed, drop tail of packet. But after
52401da177e4SLinus Torvalds 		 * remembering D-SACK for its head made in previous line.
52411da177e4SLinus Torvalds 		 */
5242fb223502SYafang Shao 		if (!tcp_receive_window(tp)) {
5243a7ec3810SMenglong Dong 			reason = SKB_DROP_REASON_TCP_ZEROWINDOW;
5244fb223502SYafang Shao 			NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPZEROWINDOWDROP);
52451da177e4SLinus Torvalds 			goto out_of_window;
5246fb223502SYafang Shao 		}
52471da177e4SLinus Torvalds 		goto queue_and_out;
52481da177e4SLinus Torvalds 	}
52491da177e4SLinus Torvalds 
5250e86b2919SEric Dumazet 	tcp_data_queue_ofo(sk, skb);
52511da177e4SLinus Torvalds }
52521da177e4SLinus Torvalds 
tcp_skb_next(struct sk_buff * skb,struct sk_buff_head * list)52539f5afeaeSYaogong Wang static struct sk_buff *tcp_skb_next(struct sk_buff *skb, struct sk_buff_head *list)
52542cf46637SIlpo Järvinen {
52559f5afeaeSYaogong Wang 	if (list)
52569f5afeaeSYaogong Wang 		return !skb_queue_is_last(list, skb) ? skb->next : NULL;
525791521944SDavid S. Miller 
525818a4c0eaSEric Dumazet 	return skb_rb_next(skb);
52599f5afeaeSYaogong Wang }
52602cf46637SIlpo Järvinen 
tcp_collapse_one(struct sock * sk,struct sk_buff * skb,struct sk_buff_head * list,struct rb_root * root)52619f5afeaeSYaogong Wang static struct sk_buff *tcp_collapse_one(struct sock *sk, struct sk_buff *skb,
52629f5afeaeSYaogong Wang 					struct sk_buff_head *list,
52639f5afeaeSYaogong Wang 					struct rb_root *root)
52649f5afeaeSYaogong Wang {
52659f5afeaeSYaogong Wang 	struct sk_buff *next = tcp_skb_next(skb, list);
52669f5afeaeSYaogong Wang 
52679f5afeaeSYaogong Wang 	if (list)
52682cf46637SIlpo Järvinen 		__skb_unlink(skb, list);
52699f5afeaeSYaogong Wang 	else
52709f5afeaeSYaogong Wang 		rb_erase(&skb->rbnode, root);
52719f5afeaeSYaogong Wang 
52722cf46637SIlpo Järvinen 	__kfree_skb(skb);
5273c10d9310SEric Dumazet 	NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPRCVCOLLAPSED);
52742cf46637SIlpo Järvinen 
52752cf46637SIlpo Järvinen 	return next;
52762cf46637SIlpo Järvinen }
52772cf46637SIlpo Järvinen 
52789f5afeaeSYaogong Wang /* Insert skb into rb tree, ordered by TCP_SKB_CB(skb)->seq */
tcp_rbtree_insert(struct rb_root * root,struct sk_buff * skb)527975c119afSEric Dumazet void tcp_rbtree_insert(struct rb_root *root, struct sk_buff *skb)
52809f5afeaeSYaogong Wang {
52819f5afeaeSYaogong Wang 	struct rb_node **p = &root->rb_node;
52829f5afeaeSYaogong Wang 	struct rb_node *parent = NULL;
52839f5afeaeSYaogong Wang 	struct sk_buff *skb1;
52849f5afeaeSYaogong Wang 
52859f5afeaeSYaogong Wang 	while (*p) {
52869f5afeaeSYaogong Wang 		parent = *p;
528718a4c0eaSEric Dumazet 		skb1 = rb_to_skb(parent);
52889f5afeaeSYaogong Wang 		if (before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb1)->seq))
52899f5afeaeSYaogong Wang 			p = &parent->rb_left;
52909f5afeaeSYaogong Wang 		else
52919f5afeaeSYaogong Wang 			p = &parent->rb_right;
52929f5afeaeSYaogong Wang 	}
52939f5afeaeSYaogong Wang 	rb_link_node(&skb->rbnode, parent, p);
52949f5afeaeSYaogong Wang 	rb_insert_color(&skb->rbnode, root);
52959f5afeaeSYaogong Wang }
52969f5afeaeSYaogong Wang 
52971da177e4SLinus Torvalds /* Collapse contiguous sequence of skbs head..tail with
52981da177e4SLinus Torvalds  * sequence numbers start..end.
529991521944SDavid S. Miller  *
53009f5afeaeSYaogong Wang  * If tail is NULL, this means until the end of the queue.
530191521944SDavid S. Miller  *
53021da177e4SLinus Torvalds  * Segments with FIN/SYN are not collapsed (only because this
53031da177e4SLinus Torvalds  * simplifies code)
53041da177e4SLinus Torvalds  */
53051da177e4SLinus Torvalds static void
tcp_collapse(struct sock * sk,struct sk_buff_head * list,struct rb_root * root,struct sk_buff * head,struct sk_buff * tail,u32 start,u32 end)53069f5afeaeSYaogong Wang tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root,
53079f5afeaeSYaogong Wang 	     struct sk_buff *head, struct sk_buff *tail, u32 start, u32 end)
53081da177e4SLinus Torvalds {
53099f5afeaeSYaogong Wang 	struct sk_buff *skb = head, *n;
53109f5afeaeSYaogong Wang 	struct sk_buff_head tmp;
531191521944SDavid S. Miller 	bool end_of_skbs;
53121da177e4SLinus Torvalds 
5313caa20d9aSStephen Hemminger 	/* First, check that queue is collapsible and find
53149f5afeaeSYaogong Wang 	 * the point where collapsing can be useful.
53159f5afeaeSYaogong Wang 	 */
531691521944SDavid S. Miller restart:
53179f5afeaeSYaogong Wang 	for (end_of_skbs = true; skb != NULL && skb != tail; skb = n) {
53189f5afeaeSYaogong Wang 		n = tcp_skb_next(skb, list);
53199f5afeaeSYaogong Wang 
53201da177e4SLinus Torvalds 		/* No new bits? It is possible on ofo queue. */
53211da177e4SLinus Torvalds 		if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
53229f5afeaeSYaogong Wang 			skb = tcp_collapse_one(sk, skb, list, root);
532391521944SDavid S. Miller 			if (!skb)
532491521944SDavid S. Miller 				break;
532591521944SDavid S. Miller 			goto restart;
53261da177e4SLinus Torvalds 		}
53271da177e4SLinus Torvalds 
53281da177e4SLinus Torvalds 		/* The first skb to collapse is:
53291da177e4SLinus Torvalds 		 * - not SYN/FIN and
53301da177e4SLinus Torvalds 		 * - bloated or contains data before "start" or
533185712484SMat Martineau 		 *   overlaps to the next one and mptcp allow collapsing.
53321da177e4SLinus Torvalds 		 */
5333e11ecddfSEric Dumazet 		if (!(TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN)) &&
533494f0893eSEric Dumazet 		    (tcp_win_from_space(sk, skb->truesize) > skb->len ||
533591521944SDavid S. Miller 		     before(TCP_SKB_CB(skb)->seq, start))) {
533691521944SDavid S. Miller 			end_of_skbs = false;
53371da177e4SLinus Torvalds 			break;
533891521944SDavid S. Miller 		}
533991521944SDavid S. Miller 
534085712484SMat Martineau 		if (n && n != tail && mptcp_skb_can_collapse(skb, n) &&
53419f5afeaeSYaogong Wang 		    TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(n)->seq) {
534291521944SDavid S. Miller 			end_of_skbs = false;
534391521944SDavid S. Miller 			break;
534491521944SDavid S. Miller 		}
53451da177e4SLinus Torvalds 
53461da177e4SLinus Torvalds 		/* Decided to skip this, advance start seq. */
53471da177e4SLinus Torvalds 		start = TCP_SKB_CB(skb)->end_seq;
53481da177e4SLinus Torvalds 	}
5349e11ecddfSEric Dumazet 	if (end_of_skbs ||
5350e11ecddfSEric Dumazet 	    (TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN)))
53511da177e4SLinus Torvalds 		return;
53521da177e4SLinus Torvalds 
53539f5afeaeSYaogong Wang 	__skb_queue_head_init(&tmp);
53549f5afeaeSYaogong Wang 
53551da177e4SLinus Torvalds 	while (before(start, end)) {
5356b3d6cb92SEric Dumazet 		int copy = min_t(int, SKB_MAX_ORDER(0, 0), end - start);
53571da177e4SLinus Torvalds 		struct sk_buff *nskb;
53581da177e4SLinus Torvalds 
5359b3d6cb92SEric Dumazet 		nskb = alloc_skb(copy, GFP_ATOMIC);
53601da177e4SLinus Torvalds 		if (!nskb)
53619f5afeaeSYaogong Wang 			break;
5362c51957daSArnaldo Carvalho de Melo 
53631da177e4SLinus Torvalds 		memcpy(nskb->cb, skb->cb, sizeof(skb->cb));
536441ed9c04SBoris Pismenny #ifdef CONFIG_TLS_DEVICE
536541ed9c04SBoris Pismenny 		nskb->decrypted = skb->decrypted;
536641ed9c04SBoris Pismenny #endif
53671da177e4SLinus Torvalds 		TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(nskb)->end_seq = start;
53689f5afeaeSYaogong Wang 		if (list)
536943f59c89SDavid S. Miller 			__skb_queue_before(list, skb, nskb);
53709f5afeaeSYaogong Wang 		else
53719f5afeaeSYaogong Wang 			__skb_queue_tail(&tmp, nskb); /* defer rbtree insertion */
53723ab224beSHideo Aoki 		skb_set_owner_r(nskb, sk);
537385712484SMat Martineau 		mptcp_skb_ext_move(nskb, skb);
53741da177e4SLinus Torvalds 
53751da177e4SLinus Torvalds 		/* Copy data, releasing collapsed skbs. */
53761da177e4SLinus Torvalds 		while (copy > 0) {
53771da177e4SLinus Torvalds 			int offset = start - TCP_SKB_CB(skb)->seq;
53781da177e4SLinus Torvalds 			int size = TCP_SKB_CB(skb)->end_seq - start;
53791da177e4SLinus Torvalds 
538009a62660SKris Katterjohn 			BUG_ON(offset < 0);
53811da177e4SLinus Torvalds 			if (size > 0) {
53821da177e4SLinus Torvalds 				size = min(copy, size);
53831da177e4SLinus Torvalds 				if (skb_copy_bits(skb, offset, skb_put(nskb, size), size))
53841da177e4SLinus Torvalds 					BUG();
53851da177e4SLinus Torvalds 				TCP_SKB_CB(nskb)->end_seq += size;
53861da177e4SLinus Torvalds 				copy -= size;
53871da177e4SLinus Torvalds 				start += size;
53881da177e4SLinus Torvalds 			}
53891da177e4SLinus Torvalds 			if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
53909f5afeaeSYaogong Wang 				skb = tcp_collapse_one(sk, skb, list, root);
539191521944SDavid S. Miller 				if (!skb ||
539291521944SDavid S. Miller 				    skb == tail ||
539385712484SMat Martineau 				    !mptcp_skb_can_collapse(nskb, skb) ||
5394e11ecddfSEric Dumazet 				    (TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN)))
53959f5afeaeSYaogong Wang 					goto end;
539641ed9c04SBoris Pismenny #ifdef CONFIG_TLS_DEVICE
539741ed9c04SBoris Pismenny 				if (skb->decrypted != nskb->decrypted)
539841ed9c04SBoris Pismenny 					goto end;
539941ed9c04SBoris Pismenny #endif
54001da177e4SLinus Torvalds 			}
54011da177e4SLinus Torvalds 		}
54021da177e4SLinus Torvalds 	}
54039f5afeaeSYaogong Wang end:
54049f5afeaeSYaogong Wang 	skb_queue_walk_safe(&tmp, skb, n)
54059f5afeaeSYaogong Wang 		tcp_rbtree_insert(root, skb);
54061da177e4SLinus Torvalds }
54071da177e4SLinus Torvalds 
54081da177e4SLinus Torvalds /* Collapse ofo queue. Algorithm: select contiguous sequence of skbs
54091da177e4SLinus Torvalds  * and tcp_collapse() them until all the queue is collapsed.
54101da177e4SLinus Torvalds  */
tcp_collapse_ofo_queue(struct sock * sk)54111da177e4SLinus Torvalds static void tcp_collapse_ofo_queue(struct sock *sk)
54121da177e4SLinus Torvalds {
54131da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
54143d4bf93aSEric Dumazet 	u32 range_truesize, sum_tiny = 0;
54159f5afeaeSYaogong Wang 	struct sk_buff *skb, *head;
54161da177e4SLinus Torvalds 	u32 start, end;
54171da177e4SLinus Torvalds 
541818a4c0eaSEric Dumazet 	skb = skb_rb_first(&tp->out_of_order_queue);
54199f5afeaeSYaogong Wang new_range:
54209f5afeaeSYaogong Wang 	if (!skb) {
542118a4c0eaSEric Dumazet 		tp->ooo_last_skb = skb_rb_last(&tp->out_of_order_queue);
54221da177e4SLinus Torvalds 		return;
54239f5afeaeSYaogong Wang 	}
54241da177e4SLinus Torvalds 	start = TCP_SKB_CB(skb)->seq;
54251da177e4SLinus Torvalds 	end = TCP_SKB_CB(skb)->end_seq;
54263d4bf93aSEric Dumazet 	range_truesize = skb->truesize;
54271da177e4SLinus Torvalds 
54289f5afeaeSYaogong Wang 	for (head = skb;;) {
542918a4c0eaSEric Dumazet 		skb = skb_rb_next(skb);
543091521944SDavid S. Miller 
54319f5afeaeSYaogong Wang 		/* Range is terminated when we see a gap or when
54329f5afeaeSYaogong Wang 		 * we are at the queue end.
54339f5afeaeSYaogong Wang 		 */
543491521944SDavid S. Miller 		if (!skb ||
54351da177e4SLinus Torvalds 		    after(TCP_SKB_CB(skb)->seq, end) ||
54361da177e4SLinus Torvalds 		    before(TCP_SKB_CB(skb)->end_seq, start)) {
54373d4bf93aSEric Dumazet 			/* Do not attempt collapsing tiny skbs */
54383d4bf93aSEric Dumazet 			if (range_truesize != head->truesize ||
5439100fdd1fSEric Dumazet 			    end - start >= SKB_WITH_OVERHEAD(PAGE_SIZE)) {
54409f5afeaeSYaogong Wang 				tcp_collapse(sk, NULL, &tp->out_of_order_queue,
54418728b834SDavid S. Miller 					     head, skb, start, end);
54423d4bf93aSEric Dumazet 			} else {
54433d4bf93aSEric Dumazet 				sum_tiny += range_truesize;
54443d4bf93aSEric Dumazet 				if (sum_tiny > sk->sk_rcvbuf >> 3)
54453d4bf93aSEric Dumazet 					return;
54463d4bf93aSEric Dumazet 			}
54479f5afeaeSYaogong Wang 			goto new_range;
54489f5afeaeSYaogong Wang 		}
54499f5afeaeSYaogong Wang 
54503d4bf93aSEric Dumazet 		range_truesize += skb->truesize;
54519f5afeaeSYaogong Wang 		if (unlikely(before(TCP_SKB_CB(skb)->seq, start)))
54521da177e4SLinus Torvalds 			start = TCP_SKB_CB(skb)->seq;
54531da177e4SLinus Torvalds 		if (after(TCP_SKB_CB(skb)->end_seq, end))
54541da177e4SLinus Torvalds 			end = TCP_SKB_CB(skb)->end_seq;
54551da177e4SLinus Torvalds 	}
54561da177e4SLinus Torvalds }
54571da177e4SLinus Torvalds 
5458b000cd37SVitaliy Gusev /*
545936a6503fSEric Dumazet  * Clean the out-of-order queue to make room.
546036a6503fSEric Dumazet  * We drop high sequences packets to :
546136a6503fSEric Dumazet  * 1) Let a chance for holes to be filled.
5462b0e01253SEric Dumazet  *    This means we do not drop packets from ooo queue if their sequence
5463b0e01253SEric Dumazet  *    is before incoming packet sequence.
546436a6503fSEric Dumazet  * 2) not add too big latencies if thousands of packets sit there.
546536a6503fSEric Dumazet  *    (But if application shrinks SO_RCVBUF, we could still end up
546636a6503fSEric Dumazet  *     freeing whole queue here)
546772cd43baSEric Dumazet  * 3) Drop at least 12.5 % of sk_rcvbuf to avoid malicious attacks.
546836a6503fSEric Dumazet  *
546936a6503fSEric Dumazet  * Return true if queue has shrunk.
5470b000cd37SVitaliy Gusev  */
tcp_prune_ofo_queue(struct sock * sk,const struct sk_buff * in_skb)5471b0e01253SEric Dumazet static bool tcp_prune_ofo_queue(struct sock *sk, const struct sk_buff *in_skb)
5472b000cd37SVitaliy Gusev {
5473b000cd37SVitaliy Gusev 	struct tcp_sock *tp = tcp_sk(sk);
54749f5afeaeSYaogong Wang 	struct rb_node *node, *prev;
5475b0e01253SEric Dumazet 	bool pruned = false;
547672cd43baSEric Dumazet 	int goal;
5477b000cd37SVitaliy Gusev 
54789f5afeaeSYaogong Wang 	if (RB_EMPTY_ROOT(&tp->out_of_order_queue))
547936a6503fSEric Dumazet 		return false;
548036a6503fSEric Dumazet 
548172cd43baSEric Dumazet 	goal = sk->sk_rcvbuf >> 3;
54829f5afeaeSYaogong Wang 	node = &tp->ooo_last_skb->rbnode;
5483b0e01253SEric Dumazet 
54849f5afeaeSYaogong Wang 	do {
5485b0e01253SEric Dumazet 		struct sk_buff *skb = rb_to_skb(node);
5486b0e01253SEric Dumazet 
5487b0e01253SEric Dumazet 		/* If incoming skb would land last in ofo queue, stop pruning. */
5488b0e01253SEric Dumazet 		if (after(TCP_SKB_CB(in_skb)->seq, TCP_SKB_CB(skb)->seq))
5489b0e01253SEric Dumazet 			break;
5490b0e01253SEric Dumazet 		pruned = true;
54919f5afeaeSYaogong Wang 		prev = rb_prev(node);
54929f5afeaeSYaogong Wang 		rb_erase(node, &tp->out_of_order_queue);
5493b0e01253SEric Dumazet 		goal -= skb->truesize;
5494b0e01253SEric Dumazet 		tcp_drop_reason(sk, skb, SKB_DROP_REASON_TCP_OFO_QUEUE_PRUNE);
5495b0e01253SEric Dumazet 		tp->ooo_last_skb = rb_to_skb(prev);
549672cd43baSEric Dumazet 		if (!prev || goal <= 0) {
549736a6503fSEric Dumazet 			if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf &&
549836a6503fSEric Dumazet 			    !tcp_under_memory_pressure(sk))
549936a6503fSEric Dumazet 				break;
550072cd43baSEric Dumazet 			goal = sk->sk_rcvbuf >> 3;
550172cd43baSEric Dumazet 		}
55029f5afeaeSYaogong Wang 		node = prev;
55039f5afeaeSYaogong Wang 	} while (node);
5504b000cd37SVitaliy Gusev 
5505b0e01253SEric Dumazet 	if (pruned) {
5506b0e01253SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_OFOPRUNED);
5507b000cd37SVitaliy Gusev 		/* Reset SACK state.  A conforming SACK implementation will
5508b000cd37SVitaliy Gusev 		 * do the same at a timeout based retransmit.  When a connection
5509b000cd37SVitaliy Gusev 		 * is in a sad state like this, we care only about integrity
5510b000cd37SVitaliy Gusev 		 * of the connection not performance.
5511b000cd37SVitaliy Gusev 		 */
5512b000cd37SVitaliy Gusev 		if (tp->rx_opt.sack_ok)
5513b000cd37SVitaliy Gusev 			tcp_sack_reset(&tp->rx_opt);
5514b0e01253SEric Dumazet 	}
5515b0e01253SEric Dumazet 	return pruned;
5516b000cd37SVitaliy Gusev }
5517b000cd37SVitaliy Gusev 
55181da177e4SLinus Torvalds /* Reduce allocated memory if we can, trying to get
55191da177e4SLinus Torvalds  * the socket within its memory limits again.
55201da177e4SLinus Torvalds  *
55211da177e4SLinus Torvalds  * Return less than zero if we should start dropping frames
55221da177e4SLinus Torvalds  * until the socket owning process reads some of the data
55231da177e4SLinus Torvalds  * to stabilize the situation.
55241da177e4SLinus Torvalds  */
tcp_prune_queue(struct sock * sk,const struct sk_buff * in_skb)5525b0e01253SEric Dumazet static int tcp_prune_queue(struct sock *sk, const struct sk_buff *in_skb)
55261da177e4SLinus Torvalds {
55271da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
55281da177e4SLinus Torvalds 
5529c10d9310SEric Dumazet 	NET_INC_STATS(sock_net(sk), LINUX_MIB_PRUNECALLED);
55301da177e4SLinus Torvalds 
55311da177e4SLinus Torvalds 	if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
55329e412ba7SIlpo Järvinen 		tcp_clamp_window(sk);
5533b8da51ebSEric Dumazet 	else if (tcp_under_memory_pressure(sk))
5534053f3684SWei Wang 		tcp_adjust_rcv_ssthresh(sk);
55351da177e4SLinus Torvalds 
5536f4a3313dSEric Dumazet 	if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf)
5537f4a3313dSEric Dumazet 		return 0;
5538f4a3313dSEric Dumazet 
55391da177e4SLinus Torvalds 	tcp_collapse_ofo_queue(sk);
554091521944SDavid S. Miller 	if (!skb_queue_empty(&sk->sk_receive_queue))
55419f5afeaeSYaogong Wang 		tcp_collapse(sk, &sk->sk_receive_queue, NULL,
554291521944SDavid S. Miller 			     skb_peek(&sk->sk_receive_queue),
554391521944SDavid S. Miller 			     NULL,
55441da177e4SLinus Torvalds 			     tp->copied_seq, tp->rcv_nxt);
55451da177e4SLinus Torvalds 
55461da177e4SLinus Torvalds 	if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf)
55471da177e4SLinus Torvalds 		return 0;
55481da177e4SLinus Torvalds 
55491da177e4SLinus Torvalds 	/* Collapsing did not help, destructive actions follow.
55501da177e4SLinus Torvalds 	 * This must not ever occur. */
55511da177e4SLinus Torvalds 
5552b0e01253SEric Dumazet 	tcp_prune_ofo_queue(sk, in_skb);
55531da177e4SLinus Torvalds 
55541da177e4SLinus Torvalds 	if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf)
55551da177e4SLinus Torvalds 		return 0;
55561da177e4SLinus Torvalds 
55571da177e4SLinus Torvalds 	/* If we are really being abused, tell the caller to silently
55581da177e4SLinus Torvalds 	 * drop receive data on the floor.  It will get retransmitted
55591da177e4SLinus Torvalds 	 * and hopefully then we'll have sufficient space.
55601da177e4SLinus Torvalds 	 */
5561c10d9310SEric Dumazet 	NET_INC_STATS(sock_net(sk), LINUX_MIB_RCVPRUNED);
55621da177e4SLinus Torvalds 
55631da177e4SLinus Torvalds 	/* Massive buffer overcommit. */
556431770e34SFlorian Westphal 	tp->pred_flags = 0;
55651da177e4SLinus Torvalds 	return -1;
55661da177e4SLinus Torvalds }
55671da177e4SLinus Torvalds 
tcp_should_expand_sndbuf(struct sock * sk)5568ca057051SWei Wang static bool tcp_should_expand_sndbuf(struct sock *sk)
55690d9901dfSDavid S. Miller {
5570cf533ea5SEric Dumazet 	const struct tcp_sock *tp = tcp_sk(sk);
55719e412ba7SIlpo Järvinen 
55720d9901dfSDavid S. Miller 	/* If the user specified a specific send buffer setting, do
55730d9901dfSDavid S. Miller 	 * not modify it.
55740d9901dfSDavid S. Miller 	 */
55750d9901dfSDavid S. Miller 	if (sk->sk_userlocks & SOCK_SNDBUF_LOCK)
5576a2a385d6SEric Dumazet 		return false;
55770d9901dfSDavid S. Miller 
55780d9901dfSDavid S. Miller 	/* If we are under global TCP memory pressure, do not expand.  */
5579ca057051SWei Wang 	if (tcp_under_memory_pressure(sk)) {
5580ca057051SWei Wang 		int unused_mem = sk_unused_reserved_mem(sk);
5581ca057051SWei Wang 
5582ca057051SWei Wang 		/* Adjust sndbuf according to reserved mem. But make sure
5583ca057051SWei Wang 		 * it never goes below SOCK_MIN_SNDBUF.
5584ca057051SWei Wang 		 * See sk_stream_moderate_sndbuf() for more details.
5585ca057051SWei Wang 		 */
5586ca057051SWei Wang 		if (unused_mem > SOCK_MIN_SNDBUF)
5587ca057051SWei Wang 			WRITE_ONCE(sk->sk_sndbuf, unused_mem);
5588ca057051SWei Wang 
5589a2a385d6SEric Dumazet 		return false;
5590ca057051SWei Wang 	}
55910d9901dfSDavid S. Miller 
55920d9901dfSDavid S. Miller 	/* If we are under soft global TCP memory pressure, do not expand.  */
5593180d8cd9SGlauber Costa 	if (sk_memory_allocated(sk) >= sk_prot_mem_limits(sk, 0))
5594a2a385d6SEric Dumazet 		return false;
55950d9901dfSDavid S. Miller 
55960d9901dfSDavid S. Miller 	/* If we filled the congestion window, do not expand.  */
559740570375SEric Dumazet 	if (tcp_packets_in_flight(tp) >= tcp_snd_cwnd(tp))
5598a2a385d6SEric Dumazet 		return false;
55990d9901dfSDavid S. Miller 
5600a2a385d6SEric Dumazet 	return true;
56010d9901dfSDavid S. Miller }
56021da177e4SLinus Torvalds 
tcp_new_space(struct sock * sk)56031da177e4SLinus Torvalds static void tcp_new_space(struct sock *sk)
56041da177e4SLinus Torvalds {
56051da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
56061da177e4SLinus Torvalds 
56079e412ba7SIlpo Järvinen 	if (tcp_should_expand_sndbuf(sk)) {
56086ae70532SEric Dumazet 		tcp_sndbuf_expand(sk);
5609c2203cf7SEric Dumazet 		tp->snd_cwnd_stamp = tcp_jiffies32;
56101da177e4SLinus Torvalds 	}
56111da177e4SLinus Torvalds 
5612739b2adfSEric Dumazet 	INDIRECT_CALL_1(sk->sk_write_space, sk_stream_write_space, sk);
56131da177e4SLinus Torvalds }
56141da177e4SLinus Torvalds 
56154bfe744fSEric Dumazet /* Caller made space either from:
56164bfe744fSEric Dumazet  * 1) Freeing skbs in rtx queues (after tp->snd_una has advanced)
56174bfe744fSEric Dumazet  * 2) Sent skbs from output queue (and thus advancing tp->snd_nxt)
56184bfe744fSEric Dumazet  *
56194bfe744fSEric Dumazet  * We might be able to generate EPOLLOUT to the application if:
56204bfe744fSEric Dumazet  * 1) Space consumed in output/rtx queues is below sk->sk_sndbuf/2
56214bfe744fSEric Dumazet  * 2) notsent amount (tp->write_seq - tp->snd_nxt) became
56224bfe744fSEric Dumazet  *    small enough that tcp_stream_memory_free() decides it
56234bfe744fSEric Dumazet  *    is time to generate EPOLLOUT.
56244bfe744fSEric Dumazet  */
tcp_check_space(struct sock * sk)56254bfe744fSEric Dumazet void tcp_check_space(struct sock *sk)
56261da177e4SLinus Torvalds {
56273c715127Sjbaron@akamai.com 	/* pairs with tcp_poll() */
562856d80622SJason Baron 	smp_mb();
56291da177e4SLinus Torvalds 	if (sk->sk_socket &&
5630b0f71bd3SFrancis Yan 	    test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
56311da177e4SLinus Torvalds 		tcp_new_space(sk);
5632b0f71bd3SFrancis Yan 		if (!test_bit(SOCK_NOSPACE, &sk->sk_socket->flags))
5633b0f71bd3SFrancis Yan 			tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED);
5634b0f71bd3SFrancis Yan 	}
56351da177e4SLinus Torvalds }
56361da177e4SLinus Torvalds 
tcp_data_snd_check(struct sock * sk)56379e412ba7SIlpo Järvinen static inline void tcp_data_snd_check(struct sock *sk)
56381da177e4SLinus Torvalds {
56399e412ba7SIlpo Järvinen 	tcp_push_pending_frames(sk);
56401da177e4SLinus Torvalds 	tcp_check_space(sk);
56411da177e4SLinus Torvalds }
56421da177e4SLinus Torvalds 
56431da177e4SLinus Torvalds /*
56441da177e4SLinus Torvalds  * Check if sending an ack is needed.
56451da177e4SLinus Torvalds  */
__tcp_ack_snd_check(struct sock * sk,int ofo_possible)56461da177e4SLinus Torvalds static void __tcp_ack_snd_check(struct sock *sk, int ofo_possible)
56471da177e4SLinus Torvalds {
56481da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
56495d9f4262SEric Dumazet 	unsigned long rtt, delay;
56501da177e4SLinus Torvalds 
56511da177e4SLinus Torvalds 	    /* More than one full frame received... */
56529d4fb27dSJoe Perches 	if (((tp->rcv_nxt - tp->rcv_wup) > inet_csk(sk)->icsk_ack.rcv_mss &&
56531da177e4SLinus Torvalds 	     /* ... and right edge of window advances far enough.
5654796f82eaSEric Dumazet 	      * (tcp_recvmsg() will send ACK otherwise).
5655796f82eaSEric Dumazet 	      * If application uses SO_RCVLOWAT, we want send ack now if
5656796f82eaSEric Dumazet 	      * we have not received enough bytes to satisfy the condition.
56571da177e4SLinus Torvalds 	      */
5658796f82eaSEric Dumazet 	    (tp->rcv_nxt - tp->copied_seq < sk->sk_rcvlowat ||
5659796f82eaSEric Dumazet 	     __tcp_select_window(sk) >= tp->rcv_wnd)) ||
56601da177e4SLinus Torvalds 	    /* We ACK each frame or... */
5661466466dcSYuchung Cheng 	    tcp_in_quickack_mode(sk) ||
5662466466dcSYuchung Cheng 	    /* Protocol state mandates a one-time immediate ACK */
5663466466dcSYuchung Cheng 	    inet_csk(sk)->icsk_ack.pending & ICSK_ACK_NOW) {
56645d9f4262SEric Dumazet send_now:
56651da177e4SLinus Torvalds 		tcp_send_ack(sk);
56665d9f4262SEric Dumazet 		return;
56671da177e4SLinus Torvalds 	}
56685d9f4262SEric Dumazet 
56695d9f4262SEric Dumazet 	if (!ofo_possible || RB_EMPTY_ROOT(&tp->out_of_order_queue)) {
56705d9f4262SEric Dumazet 		tcp_send_delayed_ack(sk);
56715d9f4262SEric Dumazet 		return;
56725d9f4262SEric Dumazet 	}
56735d9f4262SEric Dumazet 
56749c21d2fcSEric Dumazet 	if (!tcp_is_sack(tp) ||
567579f55473SKuniyuki Iwashima 	    tp->compressed_ack >= READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_comp_sack_nr))
56765d9f4262SEric Dumazet 		goto send_now;
567786de5921SEric Dumazet 
567886de5921SEric Dumazet 	if (tp->compressed_ack_rcv_nxt != tp->rcv_nxt) {
567986de5921SEric Dumazet 		tp->compressed_ack_rcv_nxt = tp->rcv_nxt;
56802b195850SEric Dumazet 		tp->dup_ack_counter = 0;
568186de5921SEric Dumazet 	}
56822b195850SEric Dumazet 	if (tp->dup_ack_counter < TCP_FASTRETRANS_THRESH) {
56832b195850SEric Dumazet 		tp->dup_ack_counter++;
568486de5921SEric Dumazet 		goto send_now;
56852b195850SEric Dumazet 	}
56862b195850SEric Dumazet 	tp->compressed_ack++;
56875d9f4262SEric Dumazet 	if (hrtimer_is_queued(&tp->compressed_ack_timer))
56885d9f4262SEric Dumazet 		return;
56895d9f4262SEric Dumazet 
56906d82aa24SEric Dumazet 	/* compress ack timer : 5 % of rtt, but no more than tcp_comp_sack_delay_ns */
56915d9f4262SEric Dumazet 
56925d9f4262SEric Dumazet 	rtt = tp->rcv_rtt_est.rtt_us;
56935d9f4262SEric Dumazet 	if (tp->srtt_us && tp->srtt_us < rtt)
56945d9f4262SEric Dumazet 		rtt = tp->srtt_us;
56955d9f4262SEric Dumazet 
56964866b2b0SKuniyuki Iwashima 	delay = min_t(unsigned long,
56974866b2b0SKuniyuki Iwashima 		      READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_comp_sack_delay_ns),
56985d9f4262SEric Dumazet 		      rtt * (NSEC_PER_USEC >> 3)/20);
56995d9f4262SEric Dumazet 	sock_hold(sk);
5700a70437ccSEric Dumazet 	hrtimer_start_range_ns(&tp->compressed_ack_timer, ns_to_ktime(delay),
570122396941SKuniyuki Iwashima 			       READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_comp_sack_slack_ns),
57025d9f4262SEric Dumazet 			       HRTIMER_MODE_REL_PINNED_SOFT);
57031da177e4SLinus Torvalds }
57041da177e4SLinus Torvalds 
tcp_ack_snd_check(struct sock * sk)570540efc6faSStephen Hemminger static inline void tcp_ack_snd_check(struct sock *sk)
57061da177e4SLinus Torvalds {
5707463c84b9SArnaldo Carvalho de Melo 	if (!inet_csk_ack_scheduled(sk)) {
57081da177e4SLinus Torvalds 		/* We sent a data segment already. */
57091da177e4SLinus Torvalds 		return;
57101da177e4SLinus Torvalds 	}
57111da177e4SLinus Torvalds 	__tcp_ack_snd_check(sk, 1);
57121da177e4SLinus Torvalds }
57131da177e4SLinus Torvalds 
57141da177e4SLinus Torvalds /*
57151da177e4SLinus Torvalds  *	This routine is only called when we have urgent data
5716caa20d9aSStephen Hemminger  *	signaled. Its the 'slow' part of tcp_urg. It could be
57171da177e4SLinus Torvalds  *	moved inline now as tcp_urg is only called from one
57181da177e4SLinus Torvalds  *	place. We handle URGent data wrong. We have to - as
57191da177e4SLinus Torvalds  *	BSD still doesn't use the correction from RFC961.
57201da177e4SLinus Torvalds  *	For 1003.1g we should support a new option TCP_STDURG to permit
57211da177e4SLinus Torvalds  *	either form (or just set the sysctl tcp_stdurg).
57221da177e4SLinus Torvalds  */
57231da177e4SLinus Torvalds 
tcp_check_urg(struct sock * sk,const struct tcphdr * th)5724cf533ea5SEric Dumazet static void tcp_check_urg(struct sock *sk, const struct tcphdr *th)
57251da177e4SLinus Torvalds {
57261da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
57271da177e4SLinus Torvalds 	u32 ptr = ntohs(th->urg_ptr);
57281da177e4SLinus Torvalds 
57294e08ed41SKuniyuki Iwashima 	if (ptr && !READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_stdurg))
57301da177e4SLinus Torvalds 		ptr--;
57311da177e4SLinus Torvalds 	ptr += ntohl(th->seq);
57321da177e4SLinus Torvalds 
57331da177e4SLinus Torvalds 	/* Ignore urgent data that we've already seen and read. */
57341da177e4SLinus Torvalds 	if (after(tp->copied_seq, ptr))
57351da177e4SLinus Torvalds 		return;
57361da177e4SLinus Torvalds 
57371da177e4SLinus Torvalds 	/* Do not replay urg ptr.
57381da177e4SLinus Torvalds 	 *
57391da177e4SLinus Torvalds 	 * NOTE: interesting situation not covered by specs.
57401da177e4SLinus Torvalds 	 * Misbehaving sender may send urg ptr, pointing to segment,
57411da177e4SLinus Torvalds 	 * which we already have in ofo queue. We are not able to fetch
57421da177e4SLinus Torvalds 	 * such data and will stay in TCP_URG_NOTYET until will be eaten
57431da177e4SLinus Torvalds 	 * by recvmsg(). Seems, we are not obliged to handle such wicked
57441da177e4SLinus Torvalds 	 * situations. But it is worth to think about possibility of some
57451da177e4SLinus Torvalds 	 * DoSes using some hypothetical application level deadlock.
57461da177e4SLinus Torvalds 	 */
57471da177e4SLinus Torvalds 	if (before(ptr, tp->rcv_nxt))
57481da177e4SLinus Torvalds 		return;
57491da177e4SLinus Torvalds 
57501da177e4SLinus Torvalds 	/* Do we already have a newer (or duplicate) urgent pointer? */
57511da177e4SLinus Torvalds 	if (tp->urg_data && !after(ptr, tp->urg_seq))
57521da177e4SLinus Torvalds 		return;
57531da177e4SLinus Torvalds 
57541da177e4SLinus Torvalds 	/* Tell the world about our new urgent pointer. */
57551da177e4SLinus Torvalds 	sk_send_sigurg(sk);
57561da177e4SLinus Torvalds 
57571da177e4SLinus Torvalds 	/* We may be adding urgent data when the last byte read was
57581da177e4SLinus Torvalds 	 * urgent. To do this requires some care. We cannot just ignore
57591da177e4SLinus Torvalds 	 * tp->copied_seq since we would read the last urgent byte again
57601da177e4SLinus Torvalds 	 * as data, nor can we alter copied_seq until this data arrives
5761caa20d9aSStephen Hemminger 	 * or we break the semantics of SIOCATMARK (and thus sockatmark())
57621da177e4SLinus Torvalds 	 *
57631da177e4SLinus Torvalds 	 * NOTE. Double Dutch. Rendering to plain English: author of comment
57641da177e4SLinus Torvalds 	 * above did something sort of 	send("A", MSG_OOB); send("B", MSG_OOB);
57651da177e4SLinus Torvalds 	 * and expect that both A and B disappear from stream. This is _wrong_.
57661da177e4SLinus Torvalds 	 * Though this happens in BSD with high probability, this is occasional.
57671da177e4SLinus Torvalds 	 * Any application relying on this is buggy. Note also, that fix "works"
57681da177e4SLinus Torvalds 	 * only in this artificial test. Insert some normal data between A and B and we will
57691da177e4SLinus Torvalds 	 * decline of BSD again. Verdict: it is better to remove to trap
57701da177e4SLinus Torvalds 	 * buggy users.
57711da177e4SLinus Torvalds 	 */
57721da177e4SLinus Torvalds 	if (tp->urg_seq == tp->copied_seq && tp->urg_data &&
5773056834d9SIlpo Järvinen 	    !sock_flag(sk, SOCK_URGINLINE) && tp->copied_seq != tp->rcv_nxt) {
57741da177e4SLinus Torvalds 		struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
57751da177e4SLinus Torvalds 		tp->copied_seq++;
57761da177e4SLinus Torvalds 		if (skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq)) {
57778728b834SDavid S. Miller 			__skb_unlink(skb, &sk->sk_receive_queue);
57781da177e4SLinus Torvalds 			__kfree_skb(skb);
57791da177e4SLinus Torvalds 		}
57801da177e4SLinus Torvalds 	}
57811da177e4SLinus Torvalds 
57827b6a893aSEric Dumazet 	WRITE_ONCE(tp->urg_data, TCP_URG_NOTYET);
5783d9b55bf7SEric Dumazet 	WRITE_ONCE(tp->urg_seq, ptr);
578431770e34SFlorian Westphal 
578531770e34SFlorian Westphal 	/* Disable header prediction. */
578631770e34SFlorian Westphal 	tp->pred_flags = 0;
57871da177e4SLinus Torvalds }
57881da177e4SLinus Torvalds 
57891da177e4SLinus Torvalds /* This is the 'fast' part of urgent handling. */
tcp_urg(struct sock * sk,struct sk_buff * skb,const struct tcphdr * th)5790cf533ea5SEric Dumazet static void tcp_urg(struct sock *sk, struct sk_buff *skb, const struct tcphdr *th)
57911da177e4SLinus Torvalds {
57921da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
57931da177e4SLinus Torvalds 
57941da177e4SLinus Torvalds 	/* Check if we get a new urgent pointer - normally not. */
5795b96c51bdSEric Dumazet 	if (unlikely(th->urg))
57961da177e4SLinus Torvalds 		tcp_check_urg(sk, th);
57971da177e4SLinus Torvalds 
57981da177e4SLinus Torvalds 	/* Do we wait for any urgent data? - normally not... */
5799b96c51bdSEric Dumazet 	if (unlikely(tp->urg_data == TCP_URG_NOTYET)) {
58001da177e4SLinus Torvalds 		u32 ptr = tp->urg_seq - ntohl(th->seq) + (th->doff * 4) -
58011da177e4SLinus Torvalds 			  th->syn;
58021da177e4SLinus Torvalds 
58031da177e4SLinus Torvalds 		/* Is the urgent pointer pointing into this packet? */
58041da177e4SLinus Torvalds 		if (ptr < skb->len) {
58051da177e4SLinus Torvalds 			u8 tmp;
58061da177e4SLinus Torvalds 			if (skb_copy_bits(skb, ptr, &tmp, 1))
58071da177e4SLinus Torvalds 				BUG();
58087b6a893aSEric Dumazet 			WRITE_ONCE(tp->urg_data, TCP_URG_VALID | tmp);
58091da177e4SLinus Torvalds 			if (!sock_flag(sk, SOCK_DEAD))
5810676d2369SDavid S. Miller 				sk->sk_data_ready(sk);
58111da177e4SLinus Torvalds 		}
58121da177e4SLinus Torvalds 	}
58131da177e4SLinus Torvalds }
58141da177e4SLinus Torvalds 
58150e40f4c9SJason Baron /* Accept RST for rcv_nxt - 1 after a FIN.
58160e40f4c9SJason Baron  * When tcp connections are abruptly terminated from Mac OSX (via ^C), a
58170e40f4c9SJason Baron  * FIN is sent followed by a RST packet. The RST is sent with the same
58180e40f4c9SJason Baron  * sequence number as the FIN, and thus according to RFC 5961 a challenge
58190e40f4c9SJason Baron  * ACK should be sent. However, Mac OSX rate limits replies to challenge
58200e40f4c9SJason Baron  * ACKs on the closed socket. In addition middleboxes can drop either the
58210e40f4c9SJason Baron  * challenge ACK or a subsequent RST.
58220e40f4c9SJason Baron  */
tcp_reset_check(const struct sock * sk,const struct sk_buff * skb)58230e40f4c9SJason Baron static bool tcp_reset_check(const struct sock *sk, const struct sk_buff *skb)
58240e40f4c9SJason Baron {
5825e9d9da91SEric Dumazet 	const struct tcp_sock *tp = tcp_sk(sk);
58260e40f4c9SJason Baron 
58270e40f4c9SJason Baron 	return unlikely(TCP_SKB_CB(skb)->seq == (tp->rcv_nxt - 1) &&
58280e40f4c9SJason Baron 			(1 << sk->sk_state) & (TCPF_CLOSE_WAIT | TCPF_LAST_ACK |
58290e40f4c9SJason Baron 					       TCPF_CLOSING));
58300e40f4c9SJason Baron }
58310e40f4c9SJason Baron 
5832cbe2d128SIlpo Järvinen /* Does PAWS and seqno based validation of an incoming segment, flags will
5833cbe2d128SIlpo Järvinen  * play significant role here.
5834cbe2d128SIlpo Järvinen  */
tcp_validate_incoming(struct sock * sk,struct sk_buff * skb,const struct tcphdr * th,int syn_inerr)58350c24604bSEric Dumazet static bool tcp_validate_incoming(struct sock *sk, struct sk_buff *skb,
5836cf533ea5SEric Dumazet 				  const struct tcphdr *th, int syn_inerr)
5837cbe2d128SIlpo Järvinen {
5838cbe2d128SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
5839da40b613SEric Dumazet 	SKB_DR(reason);
5840cbe2d128SIlpo Järvinen 
5841cbe2d128SIlpo Järvinen 	/* RFC1323: H1. Apply PAWS check first. */
5842eed29f17SEric Dumazet 	if (tcp_fast_parse_options(sock_net(sk), skb, th, tp) &&
5843eed29f17SEric Dumazet 	    tp->rx_opt.saw_tstamp &&
5844cbe2d128SIlpo Järvinen 	    tcp_paws_discard(sk, skb)) {
5845cbe2d128SIlpo Järvinen 		if (!th->rst) {
5846ee05d90dSKuniyuki Iwashima 			if (unlikely(th->syn))
5847ee05d90dSKuniyuki Iwashima 				goto syn_challenge;
5848c10d9310SEric Dumazet 			NET_INC_STATS(sock_net(sk), LINUX_MIB_PAWSESTABREJECTED);
5849f2b2c582SNeal Cardwell 			if (!tcp_oow_rate_limited(sock_net(sk), skb,
5850f2b2c582SNeal Cardwell 						  LINUX_MIB_TCPACKSKIPPEDPAWS,
5851f2b2c582SNeal Cardwell 						  &tp->last_oow_ack_time))
5852cbe2d128SIlpo Järvinen 				tcp_send_dupack(sk, skb);
5853da40b613SEric Dumazet 			SKB_DR_SET(reason, TCP_RFC7323_PAWS);
5854cbe2d128SIlpo Järvinen 			goto discard;
5855cbe2d128SIlpo Järvinen 		}
5856cbe2d128SIlpo Järvinen 		/* Reset is accepted even if it did not pass PAWS. */
5857cbe2d128SIlpo Järvinen 	}
5858cbe2d128SIlpo Järvinen 
5859cbe2d128SIlpo Järvinen 	/* Step 1: check sequence number */
5860b4469349SEric Dumazet 	reason = tcp_sequence(tp, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq);
5861b4469349SEric Dumazet 	if (reason) {
5862cbe2d128SIlpo Järvinen 		/* RFC793, page 37: "In all states except SYN-SENT, all reset
5863cbe2d128SIlpo Järvinen 		 * (RST) segments are validated by checking their SEQ-fields."
5864cbe2d128SIlpo Järvinen 		 * And page 69: "If an incoming segment is not acceptable,
5865cbe2d128SIlpo Järvinen 		 * an acknowledgment should be sent in reply (unless the RST
5866cbe2d128SIlpo Järvinen 		 * bit is set, if so drop the segment and return)".
5867cbe2d128SIlpo Järvinen 		 */
5868e3715899SEric Dumazet 		if (!th->rst) {
5869e3715899SEric Dumazet 			if (th->syn)
5870e3715899SEric Dumazet 				goto syn_challenge;
5871f2b2c582SNeal Cardwell 			if (!tcp_oow_rate_limited(sock_net(sk), skb,
5872f2b2c582SNeal Cardwell 						  LINUX_MIB_TCPACKSKIPPEDSEQ,
5873f2b2c582SNeal Cardwell 						  &tp->last_oow_ack_time))
5874cbe2d128SIlpo Järvinen 				tcp_send_dupack(sk, skb);
58750e40f4c9SJason Baron 		} else if (tcp_reset_check(sk, skb)) {
5876d9d024f9SEric Dumazet 			goto reset;
5877e3715899SEric Dumazet 		}
5878cbe2d128SIlpo Järvinen 		goto discard;
5879cbe2d128SIlpo Järvinen 	}
5880cbe2d128SIlpo Järvinen 
5881cbe2d128SIlpo Järvinen 	/* Step 2: check RST bit */
5882cbe2d128SIlpo Järvinen 	if (th->rst) {
58830e40f4c9SJason Baron 		/* RFC 5961 3.2 (extend to match against (RCV.NXT - 1) after a
58840e40f4c9SJason Baron 		 * FIN and SACK too if available):
58850e40f4c9SJason Baron 		 * If seq num matches RCV.NXT or (RCV.NXT - 1) after a FIN, or
58860e40f4c9SJason Baron 		 * the right-most SACK block,
5887e00431bcSPau Espin Pedrol 		 * then
5888282f23c6SEric Dumazet 		 *     RESET the connection
5889282f23c6SEric Dumazet 		 * else
5890282f23c6SEric Dumazet 		 *     Send a challenge ACK
5891282f23c6SEric Dumazet 		 */
58920e40f4c9SJason Baron 		if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt ||
5893b5ec1e62SEric Dumazet 		    tcp_reset_check(sk, skb))
5894b5ec1e62SEric Dumazet 			goto reset;
5895b5ec1e62SEric Dumazet 
5896b5ec1e62SEric Dumazet 		if (tcp_is_sack(tp) && tp->rx_opt.num_sacks > 0) {
5897e00431bcSPau Espin Pedrol 			struct tcp_sack_block *sp = &tp->selective_acks[0];
5898e00431bcSPau Espin Pedrol 			int max_sack = sp[0].end_seq;
5899e00431bcSPau Espin Pedrol 			int this_sack;
5900e00431bcSPau Espin Pedrol 
5901e00431bcSPau Espin Pedrol 			for (this_sack = 1; this_sack < tp->rx_opt.num_sacks;
5902e00431bcSPau Espin Pedrol 			     ++this_sack) {
5903e00431bcSPau Espin Pedrol 				max_sack = after(sp[this_sack].end_seq,
5904e00431bcSPau Espin Pedrol 						 max_sack) ?
5905e00431bcSPau Espin Pedrol 					sp[this_sack].end_seq : max_sack;
5906e00431bcSPau Espin Pedrol 			}
5907e00431bcSPau Espin Pedrol 
5908e00431bcSPau Espin Pedrol 			if (TCP_SKB_CB(skb)->seq == max_sack)
5909d9d024f9SEric Dumazet 				goto reset;
5910b5ec1e62SEric Dumazet 		}
5911d9d024f9SEric Dumazet 
5912cf1ef3f0SWei Wang 		/* Disable TFO if RST is out-of-order
5913cf1ef3f0SWei Wang 		 * and no data has been received
5914cf1ef3f0SWei Wang 		 * for current active TFO socket
5915cf1ef3f0SWei Wang 		 */
5916cf1ef3f0SWei Wang 		if (tp->syn_fastopen && !tp->data_segs_in &&
5917cf1ef3f0SWei Wang 		    sk->sk_state == TCP_ESTABLISHED)
591846c2fa39SWei Wang 			tcp_fastopen_active_disable(sk);
5919208dd45dSBenjamin Yim 		tcp_send_challenge_ack(sk);
5920da40b613SEric Dumazet 		SKB_DR_SET(reason, TCP_RESET);
5921cbe2d128SIlpo Järvinen 		goto discard;
5922cbe2d128SIlpo Järvinen 	}
5923cbe2d128SIlpo Järvinen 
5924cbe2d128SIlpo Järvinen 	/* step 3: check security and precedence [ignored] */
5925cbe2d128SIlpo Järvinen 
59260c24604bSEric Dumazet 	/* step 4: Check for a SYN
5927cd214535SSowmini Varadhan 	 * RFC 5961 4.2 : Send a challenge ack
59280c24604bSEric Dumazet 	 */
59290c24604bSEric Dumazet 	if (th->syn) {
59309fd29738SKuniyuki Iwashima 		if (sk->sk_state == TCP_SYN_RECV && sk->sk_socket && th->ack &&
59319fd29738SKuniyuki Iwashima 		    TCP_SKB_CB(skb)->seq + 1 == TCP_SKB_CB(skb)->end_seq &&
59329fd29738SKuniyuki Iwashima 		    TCP_SKB_CB(skb)->seq + 1 == tp->rcv_nxt &&
59339fd29738SKuniyuki Iwashima 		    TCP_SKB_CB(skb)->ack_seq == tp->snd_nxt)
59349fd29738SKuniyuki Iwashima 			goto pass;
5935e3715899SEric Dumazet syn_challenge:
5936cbe2d128SIlpo Järvinen 		if (syn_inerr)
5937c10d9310SEric Dumazet 			TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS);
5938c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPSYNCHALLENGE);
5939208dd45dSBenjamin Yim 		tcp_send_challenge_ack(sk);
5940da40b613SEric Dumazet 		SKB_DR_SET(reason, TCP_INVALID_SYN);
59410c24604bSEric Dumazet 		goto discard;
5942cbe2d128SIlpo Järvinen 	}
5943cbe2d128SIlpo Järvinen 
59449fd29738SKuniyuki Iwashima pass:
594500d211a4SMartin KaFai Lau 	bpf_skops_parse_hdr(sk, skb);
594600d211a4SMartin KaFai Lau 
59470c24604bSEric Dumazet 	return true;
5948cbe2d128SIlpo Järvinen 
5949cbe2d128SIlpo Järvinen discard:
5950da40b613SEric Dumazet 	tcp_drop_reason(sk, skb, reason);
59510c24604bSEric Dumazet 	return false;
5952d9d024f9SEric Dumazet 
5953d9d024f9SEric Dumazet reset:
5954d9d024f9SEric Dumazet 	tcp_reset(sk, skb);
5955d9d024f9SEric Dumazet 	__kfree_skb(skb);
5956d9d024f9SEric Dumazet 	return false;
5957cbe2d128SIlpo Järvinen }
5958cbe2d128SIlpo Järvinen 
59591da177e4SLinus Torvalds /*
59601da177e4SLinus Torvalds  *	TCP receive function for the ESTABLISHED state.
596131770e34SFlorian Westphal  *
596231770e34SFlorian Westphal  *	It is split into a fast path and a slow path. The fast path is
596331770e34SFlorian Westphal  * 	disabled when:
596431770e34SFlorian Westphal  *	- A zero window was announced from us - zero window probing
596531770e34SFlorian Westphal  *        is only handled properly in the slow path.
596631770e34SFlorian Westphal  *	- Out of order segments arrived.
596731770e34SFlorian Westphal  *	- Urgent data is expected.
596831770e34SFlorian Westphal  *	- There is no buffer space left
596931770e34SFlorian Westphal  *	- Unexpected TCP flags/window values/header lengths are received
597031770e34SFlorian Westphal  *	  (detected by checking the TCP header against pred_flags)
597131770e34SFlorian Westphal  *	- Data is sent in both directions. Fast path only supports pure senders
597231770e34SFlorian Westphal  *	  or pure receivers (this means either the sequence number or the ack
597331770e34SFlorian Westphal  *	  value must stay constant)
597431770e34SFlorian Westphal  *	- Unexpected TCP option.
597531770e34SFlorian Westphal  *
597631770e34SFlorian Westphal  *	When these conditions are not satisfied it drops into a standard
597731770e34SFlorian Westphal  *	receive procedure patterned after RFC793 to handle all cases.
597831770e34SFlorian Westphal  *	The first three cases are guaranteed by proper pred_flags setting,
597931770e34SFlorian Westphal  *	the rest is checked inline. Fast processing is turned on in
598031770e34SFlorian Westphal  *	tcp_data_queue when everything is OK.
59811da177e4SLinus Torvalds  */
tcp_rcv_established(struct sock * sk,struct sk_buff * skb)59823d97d88eSYafang Shao void tcp_rcv_established(struct sock *sk, struct sk_buff *skb)
59831da177e4SLinus Torvalds {
59842a968ef6SMenglong Dong 	enum skb_drop_reason reason = SKB_DROP_REASON_NOT_SPECIFIED;
59853d97d88eSYafang Shao 	const struct tcphdr *th = (const struct tcphdr *)skb->data;
59861da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
59873d97d88eSYafang Shao 	unsigned int len = skb->len;
59881da177e4SLinus Torvalds 
5989c3fde1bdSMasami Hiramatsu 	/* TCP congestion window tracking */
5990c3fde1bdSMasami Hiramatsu 	trace_tcp_probe(sk, skb);
5991c3fde1bdSMasami Hiramatsu 
59929a568de4SEric Dumazet 	tcp_mstamp_refresh(tp);
59938f905c0eSEric Dumazet 	if (unlikely(!rcu_access_pointer(sk->sk_rx_dst)))
59945d299f3dSEric Dumazet 		inet_csk(sk)->icsk_af_ops->sk_rx_dst_set(sk, skb);
599531770e34SFlorian Westphal 	/*
599631770e34SFlorian Westphal 	 *	Header prediction.
599731770e34SFlorian Westphal 	 *	The code loosely follows the one in the famous
599831770e34SFlorian Westphal 	 *	"30 instruction TCP receive" Van Jacobson mail.
599931770e34SFlorian Westphal 	 *
600031770e34SFlorian Westphal 	 *	Van's trick is to deposit buffers into socket queue
600131770e34SFlorian Westphal 	 *	on a device interrupt, to call tcp_recv function
600231770e34SFlorian Westphal 	 *	on the receive process context and checksum and copy
600331770e34SFlorian Westphal 	 *	the buffer to user space. smart...
600431770e34SFlorian Westphal 	 *
600531770e34SFlorian Westphal 	 *	Our current scheme is not silly either but we take the
600631770e34SFlorian Westphal 	 *	extra cost of the net_bh soft interrupt processing...
600731770e34SFlorian Westphal 	 *	We do checksum and copy also but from device to kernel.
600831770e34SFlorian Westphal 	 */
60091da177e4SLinus Torvalds 
60101da177e4SLinus Torvalds 	tp->rx_opt.saw_tstamp = 0;
60111da177e4SLinus Torvalds 
601231770e34SFlorian Westphal 	/*	pred_flags is 0xS?10 << 16 + snd_wnd
601331770e34SFlorian Westphal 	 *	if header_prediction is to be made
601431770e34SFlorian Westphal 	 *	'S' will always be tp->tcp_header_len >> 2
601531770e34SFlorian Westphal 	 *	'?' will be 0 for the fast path, otherwise pred_flags is 0 to
601631770e34SFlorian Westphal 	 *  turn it off	(when there are holes in the receive
601731770e34SFlorian Westphal 	 *	 space for instance)
601831770e34SFlorian Westphal 	 *	PSH flag is ignored.
601931770e34SFlorian Westphal 	 */
602031770e34SFlorian Westphal 
602131770e34SFlorian Westphal 	if ((tcp_flag_word(th) & TCP_HP_BITS) == tp->pred_flags &&
602231770e34SFlorian Westphal 	    TCP_SKB_CB(skb)->seq == tp->rcv_nxt &&
602331770e34SFlorian Westphal 	    !after(TCP_SKB_CB(skb)->ack_seq, tp->snd_nxt)) {
602431770e34SFlorian Westphal 		int tcp_header_len = tp->tcp_header_len;
602531770e34SFlorian Westphal 
602631770e34SFlorian Westphal 		/* Timestamp header prediction: tcp_header_len
602731770e34SFlorian Westphal 		 * is automatically equal to th->doff*4 due to pred_flags
602831770e34SFlorian Westphal 		 * match.
602931770e34SFlorian Westphal 		 */
603031770e34SFlorian Westphal 
603131770e34SFlorian Westphal 		/* Check timestamp */
603231770e34SFlorian Westphal 		if (tcp_header_len == sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) {
603331770e34SFlorian Westphal 			/* No? Slow path! */
603431770e34SFlorian Westphal 			if (!tcp_parse_aligned_timestamp(tp, th))
603531770e34SFlorian Westphal 				goto slow_path;
603631770e34SFlorian Westphal 
603731770e34SFlorian Westphal 			/* If PAWS failed, check it more carefully in slow path */
603831770e34SFlorian Westphal 			if ((s32)(tp->rx_opt.rcv_tsval - tp->rx_opt.ts_recent) < 0)
603931770e34SFlorian Westphal 				goto slow_path;
604031770e34SFlorian Westphal 
604131770e34SFlorian Westphal 			/* DO NOT update ts_recent here, if checksum fails
604231770e34SFlorian Westphal 			 * and timestamp was corrupted part, it will result
604331770e34SFlorian Westphal 			 * in a hung connection since we will drop all
604431770e34SFlorian Westphal 			 * future packets due to the PAWS test.
604531770e34SFlorian Westphal 			 */
604631770e34SFlorian Westphal 		}
604731770e34SFlorian Westphal 
604831770e34SFlorian Westphal 		if (len <= tcp_header_len) {
604931770e34SFlorian Westphal 			/* Bulk data transfer: sender */
605031770e34SFlorian Westphal 			if (len == tcp_header_len) {
605131770e34SFlorian Westphal 				/* Predicted packet is in window by definition.
605231770e34SFlorian Westphal 				 * seq == rcv_nxt and rcv_wup <= rcv_nxt.
605331770e34SFlorian Westphal 				 * Hence, check seq<=rcv_wup reduces to:
605431770e34SFlorian Westphal 				 */
605531770e34SFlorian Westphal 				if (tcp_header_len ==
605631770e34SFlorian Westphal 				    (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) &&
605731770e34SFlorian Westphal 				    tp->rcv_nxt == tp->rcv_wup)
605831770e34SFlorian Westphal 					tcp_store_ts_recent(tp);
605931770e34SFlorian Westphal 
606031770e34SFlorian Westphal 				/* We know that such packets are checksummed
606131770e34SFlorian Westphal 				 * on entry.
606231770e34SFlorian Westphal 				 */
606331770e34SFlorian Westphal 				tcp_ack(sk, skb, 0);
606431770e34SFlorian Westphal 				__kfree_skb(skb);
606531770e34SFlorian Westphal 				tcp_data_snd_check(sk);
60663f6c65d6SWei Wang 				/* When receiving pure ack in fast path, update
60673f6c65d6SWei Wang 				 * last ts ecr directly instead of calling
60683f6c65d6SWei Wang 				 * tcp_rcv_rtt_measure_ts()
60693f6c65d6SWei Wang 				 */
60703f6c65d6SWei Wang 				tp->rcv_rtt_last_tsecr = tp->rx_opt.rcv_tsecr;
607131770e34SFlorian Westphal 				return;
607231770e34SFlorian Westphal 			} else { /* Header too small */
60732a968ef6SMenglong Dong 				reason = SKB_DROP_REASON_PKT_TOO_SMALL;
607431770e34SFlorian Westphal 				TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS);
607531770e34SFlorian Westphal 				goto discard;
607631770e34SFlorian Westphal 			}
607731770e34SFlorian Westphal 		} else {
607831770e34SFlorian Westphal 			int eaten = 0;
607931770e34SFlorian Westphal 			bool fragstolen = false;
608031770e34SFlorian Westphal 
608131770e34SFlorian Westphal 			if (tcp_checksum_complete(skb))
608231770e34SFlorian Westphal 				goto csum_error;
608331770e34SFlorian Westphal 
608431770e34SFlorian Westphal 			if ((int)skb->truesize > sk->sk_forward_alloc)
608531770e34SFlorian Westphal 				goto step5;
608631770e34SFlorian Westphal 
608731770e34SFlorian Westphal 			/* Predicted packet is in window by definition.
608831770e34SFlorian Westphal 			 * seq == rcv_nxt and rcv_wup <= rcv_nxt.
608931770e34SFlorian Westphal 			 * Hence, check seq<=rcv_wup reduces to:
609031770e34SFlorian Westphal 			 */
609131770e34SFlorian Westphal 			if (tcp_header_len ==
609231770e34SFlorian Westphal 			    (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) &&
609331770e34SFlorian Westphal 			    tp->rcv_nxt == tp->rcv_wup)
609431770e34SFlorian Westphal 				tcp_store_ts_recent(tp);
609531770e34SFlorian Westphal 
609631770e34SFlorian Westphal 			tcp_rcv_rtt_measure_ts(sk, skb);
609731770e34SFlorian Westphal 
609831770e34SFlorian Westphal 			NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPHPHITS);
609931770e34SFlorian Westphal 
610031770e34SFlorian Westphal 			/* Bulk data transfer: receiver */
6101*f1d5e6a5SSabrina Dubroca 			tcp_cleanup_skb(skb);
6102e7395f1fSEric Dumazet 			__skb_pull(skb, tcp_header_len);
6103e7395f1fSEric Dumazet 			eaten = tcp_queue_rcv(sk, skb, &fragstolen);
610431770e34SFlorian Westphal 
610531770e34SFlorian Westphal 			tcp_event_data_recv(sk, skb);
610631770e34SFlorian Westphal 
610731770e34SFlorian Westphal 			if (TCP_SKB_CB(skb)->ack_seq != tp->snd_una) {
610831770e34SFlorian Westphal 				/* Well, only one small jumplet in fast path... */
610931770e34SFlorian Westphal 				tcp_ack(sk, skb, FLAG_DATA);
611031770e34SFlorian Westphal 				tcp_data_snd_check(sk);
611131770e34SFlorian Westphal 				if (!inet_csk_ack_scheduled(sk))
611231770e34SFlorian Westphal 					goto no_ack;
611318ded910SNeal Cardwell 			} else {
611418ded910SNeal Cardwell 				tcp_update_wl(tp, TCP_SKB_CB(skb)->seq);
611531770e34SFlorian Westphal 			}
611631770e34SFlorian Westphal 
611731770e34SFlorian Westphal 			__tcp_ack_snd_check(sk, 0);
611831770e34SFlorian Westphal no_ack:
611931770e34SFlorian Westphal 			if (eaten)
612031770e34SFlorian Westphal 				kfree_skb_partial(skb, fragstolen);
612103f45c88SEric Dumazet 			tcp_data_ready(sk);
612231770e34SFlorian Westphal 			return;
612331770e34SFlorian Westphal 		}
612431770e34SFlorian Westphal 	}
612531770e34SFlorian Westphal 
612631770e34SFlorian Westphal slow_path:
6127fb3477c0SEric Dumazet 	if (len < (th->doff << 2) || tcp_checksum_complete(skb))
61281da177e4SLinus Torvalds 		goto csum_error;
61291da177e4SLinus Torvalds 
61302a968ef6SMenglong Dong 	if (!th->ack && !th->rst && !th->syn) {
61312a968ef6SMenglong Dong 		reason = SKB_DROP_REASON_TCP_FLAGS;
6132c3ae62afSEric Dumazet 		goto discard;
61332a968ef6SMenglong Dong 	}
6134c3ae62afSEric Dumazet 
613531770e34SFlorian Westphal 	/*
613631770e34SFlorian Westphal 	 *	Standard slow path.
613731770e34SFlorian Westphal 	 */
613831770e34SFlorian Westphal 
61390c24604bSEric Dumazet 	if (!tcp_validate_incoming(sk, skb, th, 1))
6140c995ae22SVijay Subramanian 		return;
61411da177e4SLinus Torvalds 
614231770e34SFlorian Westphal step5:
61434b506af9SEric Dumazet 	reason = tcp_ack(sk, skb, FLAG_SLOWPATH | FLAG_UPDATE_TS_RECENT);
6144843f7740SEric Dumazet 	if ((int)reason < 0) {
6145843f7740SEric Dumazet 		reason = -reason;
614696e0bf4bSJohn Dykstra 		goto discard;
6147843f7740SEric Dumazet 	}
6148463c84b9SArnaldo Carvalho de Melo 	tcp_rcv_rtt_measure_ts(sk, skb);
61491da177e4SLinus Torvalds 
61501da177e4SLinus Torvalds 	/* Process urgent data. */
61511da177e4SLinus Torvalds 	tcp_urg(sk, skb, th);
61521da177e4SLinus Torvalds 
61531da177e4SLinus Torvalds 	/* step 7: process the segment text */
61541da177e4SLinus Torvalds 	tcp_data_queue(sk, skb);
61551da177e4SLinus Torvalds 
61569e412ba7SIlpo Järvinen 	tcp_data_snd_check(sk);
61571da177e4SLinus Torvalds 	tcp_ack_snd_check(sk);
6158c995ae22SVijay Subramanian 	return;
61591da177e4SLinus Torvalds 
61601da177e4SLinus Torvalds csum_error:
61612a968ef6SMenglong Dong 	reason = SKB_DROP_REASON_TCP_CSUM;
6162709c0314SJakub Kicinski 	trace_tcp_bad_csum(skb);
6163c10d9310SEric Dumazet 	TCP_INC_STATS(sock_net(sk), TCP_MIB_CSUMERRORS);
6164c10d9310SEric Dumazet 	TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS);
61651da177e4SLinus Torvalds 
61661da177e4SLinus Torvalds discard:
61672a968ef6SMenglong Dong 	tcp_drop_reason(sk, skb, reason);
61681da177e4SLinus Torvalds }
61694bc2f18bSEric Dumazet EXPORT_SYMBOL(tcp_rcv_established);
61701da177e4SLinus Torvalds 
tcp_init_transfer(struct sock * sk,int bpf_op,struct sk_buff * skb)617172be0fe6SMartin KaFai Lau void tcp_init_transfer(struct sock *sk, int bpf_op, struct sk_buff *skb)
617298fa6271SYuchung Cheng {
617398fa6271SYuchung Cheng 	struct inet_connection_sock *icsk = inet_csk(sk);
617498fa6271SYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
617598fa6271SYuchung Cheng 
617698fa6271SYuchung Cheng 	tcp_mtup_init(sk);
617798fa6271SYuchung Cheng 	icsk->icsk_af_ops->rebuild_header(sk);
617898fa6271SYuchung Cheng 	tcp_init_metrics(sk);
617998fa6271SYuchung Cheng 
618098fa6271SYuchung Cheng 	/* Initialize the congestion window to start the transfer.
618198fa6271SYuchung Cheng 	 * Cut cwnd down to 1 per RFC5681 if SYN or SYN-ACK has been
618298fa6271SYuchung Cheng 	 * retransmitted. In light of RFC6298 more aggressive 1sec
618398fa6271SYuchung Cheng 	 * initRTO, we only reset cwnd when more than 1 SYN/SYN-ACK
618498fa6271SYuchung Cheng 	 * retransmission has occurred.
618598fa6271SYuchung Cheng 	 */
618698fa6271SYuchung Cheng 	if (tp->total_retrans > 1 && tp->undo_marker)
618740570375SEric Dumazet 		tcp_snd_cwnd_set(tp, 1);
618898fa6271SYuchung Cheng 	else
618940570375SEric Dumazet 		tcp_snd_cwnd_set(tp, tcp_init_cwnd(tp, __sk_dst_get(sk)));
619098fa6271SYuchung Cheng 	tp->snd_cwnd_stamp = tcp_jiffies32;
619198fa6271SYuchung Cheng 
619272be0fe6SMartin KaFai Lau 	bpf_skops_established(sk, bpf_op, skb);
6193be5d1b61SNguyen Dinh Phi 	/* Initialize congestion control unless BPF initialized it already: */
61948919a9b3SNeal Cardwell 	if (!icsk->icsk_ca_initialized)
619598fa6271SYuchung Cheng 		tcp_init_congestion_control(sk);
619698fa6271SYuchung Cheng 	tcp_init_buffer_space(sk);
619798fa6271SYuchung Cheng }
619898fa6271SYuchung Cheng 
tcp_finish_connect(struct sock * sk,struct sk_buff * skb)6199370816aeSPavel Emelyanov void tcp_finish_connect(struct sock *sk, struct sk_buff *skb)
6200370816aeSPavel Emelyanov {
6201370816aeSPavel Emelyanov 	struct tcp_sock *tp = tcp_sk(sk);
6202370816aeSPavel Emelyanov 	struct inet_connection_sock *icsk = inet_csk(sk);
6203370816aeSPavel Emelyanov 
6204370816aeSPavel Emelyanov 	tcp_set_state(sk, TCP_ESTABLISHED);
620570eabf0eSEric Dumazet 	icsk->icsk_ack.lrcvtime = tcp_jiffies32;
6206370816aeSPavel Emelyanov 
620700db4124SIan Morris 	if (skb) {
62085d299f3dSEric Dumazet 		icsk->icsk_af_ops->sk_rx_dst_set(sk, skb);
6209370816aeSPavel Emelyanov 		security_inet_conn_established(sk, skb);
6210c6345ce7SAmritha Nambiar 		sk_mark_napi_id(sk, skb);
621141063e9dSDavid S. Miller 	}
6212370816aeSPavel Emelyanov 
621372be0fe6SMartin KaFai Lau 	tcp_init_transfer(sk, BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB, skb);
6214370816aeSPavel Emelyanov 
6215370816aeSPavel Emelyanov 	/* Prevent spurious tcp_cwnd_restart() on first data
6216370816aeSPavel Emelyanov 	 * packet.
6217370816aeSPavel Emelyanov 	 */
6218d635fbe2SEric Dumazet 	tp->lsndtime = tcp_jiffies32;
6219370816aeSPavel Emelyanov 
6220370816aeSPavel Emelyanov 	if (sock_flag(sk, SOCK_KEEPOPEN))
6221370816aeSPavel Emelyanov 		inet_csk_reset_keepalive_timer(sk, keepalive_time_when(tp));
622231770e34SFlorian Westphal 
622331770e34SFlorian Westphal 	if (!tp->rx_opt.snd_wscale)
622431770e34SFlorian Westphal 		__tcp_fast_path_on(tp, tp->snd_wnd);
622531770e34SFlorian Westphal 	else
622631770e34SFlorian Westphal 		tp->pred_flags = 0;
6227370816aeSPavel Emelyanov }
6228370816aeSPavel Emelyanov 
tcp_rcv_fastopen_synack(struct sock * sk,struct sk_buff * synack,struct tcp_fastopen_cookie * cookie)62298e4178c1SYuchung Cheng static bool tcp_rcv_fastopen_synack(struct sock *sk, struct sk_buff *synack,
62308e4178c1SYuchung Cheng 				    struct tcp_fastopen_cookie *cookie)
62318e4178c1SYuchung Cheng {
62328e4178c1SYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
623375c119afSEric Dumazet 	struct sk_buff *data = tp->syn_data ? tcp_rtx_queue_head(sk) : NULL;
62342646c831SDaniel Lee 	u16 mss = tp->rx_opt.mss_clamp, try_exp = 0;
62352646c831SDaniel Lee 	bool syn_drop = false;
62368e4178c1SYuchung Cheng 
62378e4178c1SYuchung Cheng 	if (mss == tp->rx_opt.user_mss) {
62388e4178c1SYuchung Cheng 		struct tcp_options_received opt;
62398e4178c1SYuchung Cheng 
62408e4178c1SYuchung Cheng 		/* Get original SYNACK MSS value if user MSS sets mss_clamp */
62418e4178c1SYuchung Cheng 		tcp_clear_options(&opt);
62428e4178c1SYuchung Cheng 		opt.user_mss = opt.mss_clamp = 0;
6243eed29f17SEric Dumazet 		tcp_parse_options(sock_net(sk), synack, &opt, 0, NULL);
62448e4178c1SYuchung Cheng 		mss = opt.mss_clamp;
62458e4178c1SYuchung Cheng 	}
62468e4178c1SYuchung Cheng 
62472646c831SDaniel Lee 	if (!tp->syn_fastopen) {
62482646c831SDaniel Lee 		/* Ignore an unsolicited cookie */
624967da22d2SYuchung Cheng 		cookie->len = -1;
62502646c831SDaniel Lee 	} else if (tp->total_retrans) {
62512646c831SDaniel Lee 		/* SYN timed out and the SYN-ACK neither has a cookie nor
62522646c831SDaniel Lee 		 * acknowledges data. Presumably the remote received only
62532646c831SDaniel Lee 		 * the retransmitted (regular) SYNs: either the original
62542646c831SDaniel Lee 		 * SYN-data or the corresponding SYN-ACK was dropped.
6255aab48743SYuchung Cheng 		 */
62562646c831SDaniel Lee 		syn_drop = (cookie->len < 0 && data);
62572646c831SDaniel Lee 	} else if (cookie->len < 0 && !tp->syn_data) {
62582646c831SDaniel Lee 		/* We requested a cookie but didn't get it. If we did not use
62592646c831SDaniel Lee 		 * the (old) exp opt format then try so next time (try_exp=1).
62602646c831SDaniel Lee 		 * Otherwise we go back to use the RFC7413 opt (try_exp=2).
62612646c831SDaniel Lee 		 */
62622646c831SDaniel Lee 		try_exp = tp->syn_fastopen_exp ? 2 : 1;
62632646c831SDaniel Lee 	}
6264aab48743SYuchung Cheng 
62652646c831SDaniel Lee 	tcp_fastopen_cache_set(sk, mss, cookie, syn_drop, try_exp);
62668e4178c1SYuchung Cheng 
62678e4178c1SYuchung Cheng 	if (data) { /* Retransmit unacked data in SYN */
626848027478SJason Baron 		if (tp->total_retrans)
626948027478SJason Baron 			tp->fastopen_client_fail = TFO_SYN_RETRANSMITTED;
627048027478SJason Baron 		else
627148027478SJason Baron 			tp->fastopen_client_fail = TFO_DATA_NOT_ACKED;
6272a7abf3cdSEric Dumazet 		skb_rbtree_walk_from(data)
6273a7abf3cdSEric Dumazet 			 tcp_mark_skb_lost(sk, data);
6274b4b26d23SNeal Cardwell 		tcp_non_congestion_loss_retransmit(sk);
6275c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk),
627602a1d6e7SEric Dumazet 				LINUX_MIB_TCPFASTOPENACTIVEFAIL);
62778e4178c1SYuchung Cheng 		return true;
62788e4178c1SYuchung Cheng 	}
62796f73601eSYuchung Cheng 	tp->syn_data_acked = tp->syn_data;
6280bef5767fSYuchung Cheng 	if (tp->syn_data_acked) {
6281bef5767fSYuchung Cheng 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPFASTOPENACTIVE);
6282bef5767fSYuchung Cheng 		/* SYN-data is counted as two separate packets in tcp_ack() */
6283bef5767fSYuchung Cheng 		if (tp->delivered > 1)
6284bef5767fSYuchung Cheng 			--tp->delivered;
6285bef5767fSYuchung Cheng 	}
628661d2bcaeSEric Dumazet 
628761d2bcaeSEric Dumazet 	tcp_fastopen_add_skb(sk, synack);
628861d2bcaeSEric Dumazet 
62898e4178c1SYuchung Cheng 	return false;
62908e4178c1SYuchung Cheng }
62918e4178c1SYuchung Cheng 
smc_check_reset_syn(struct tcp_sock * tp)629260e2a778SUrsula Braun static void smc_check_reset_syn(struct tcp_sock *tp)
629360e2a778SUrsula Braun {
629460e2a778SUrsula Braun #if IS_ENABLED(CONFIG_SMC)
629560e2a778SUrsula Braun 	if (static_branch_unlikely(&tcp_have_smc)) {
629660e2a778SUrsula Braun 		if (tp->syn_smc && !tp->rx_opt.smc_ok)
629760e2a778SUrsula Braun 			tp->syn_smc = 0;
629860e2a778SUrsula Braun 	}
629960e2a778SUrsula Braun #endif
630060e2a778SUrsula Braun }
630160e2a778SUrsula Braun 
tcp_try_undo_spurious_syn(struct sock * sk)63027c1f0815SYuchung Cheng static void tcp_try_undo_spurious_syn(struct sock *sk)
63037c1f0815SYuchung Cheng {
63047c1f0815SYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
63057c1f0815SYuchung Cheng 	u32 syn_stamp;
63067c1f0815SYuchung Cheng 
63077c1f0815SYuchung Cheng 	/* undo_marker is set when SYN or SYNACK times out. The timeout is
63087c1f0815SYuchung Cheng 	 * spurious if the ACK's timestamp option echo value matches the
63097c1f0815SYuchung Cheng 	 * original SYN timestamp.
63107c1f0815SYuchung Cheng 	 */
63117c1f0815SYuchung Cheng 	syn_stamp = tp->retrans_stamp;
63127c1f0815SYuchung Cheng 	if (tp->undo_marker && syn_stamp && tp->rx_opt.saw_tstamp &&
63137c1f0815SYuchung Cheng 	    syn_stamp == tp->rx_opt.rcv_tsecr)
63147c1f0815SYuchung Cheng 		tp->undo_marker = 0;
63157c1f0815SYuchung Cheng }
63167c1f0815SYuchung Cheng 
tcp_rcv_synsent_state_process(struct sock * sk,struct sk_buff * skb,const struct tcphdr * th)63171da177e4SLinus Torvalds static int tcp_rcv_synsent_state_process(struct sock *sk, struct sk_buff *skb,
6318bda07a64SEric Dumazet 					 const struct tcphdr *th)
63191da177e4SLinus Torvalds {
6320d83d8461SArnaldo Carvalho de Melo 	struct inet_connection_sock *icsk = inet_csk(sk);
63214957faadSWilliam Allen Simpson 	struct tcp_sock *tp = tcp_sk(sk);
63228e4178c1SYuchung Cheng 	struct tcp_fastopen_cookie foc = { .len = -1 };
63234957faadSWilliam Allen Simpson 	int saved_clamp = tp->rx_opt.mss_clamp;
63240f9fa831SEric Dumazet 	bool fastopen_fail;
6325659affdbSEric Dumazet 	SKB_DR(reason);
63261da177e4SLinus Torvalds 
6327eed29f17SEric Dumazet 	tcp_parse_options(sock_net(sk), skb, &tp->rx_opt, 0, &foc);
6328e3e12028SAndrew Vagin 	if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr)
6329ee684b6fSAndrey Vagin 		tp->rx_opt.rcv_tsecr -= tp->tsoffset;
63301da177e4SLinus Torvalds 
63311da177e4SLinus Torvalds 	if (th->ack) {
63321da177e4SLinus Torvalds 		/* rfc793:
63331da177e4SLinus Torvalds 		 * "If the state is SYN-SENT then
63341da177e4SLinus Torvalds 		 *    first check the ACK bit
63351da177e4SLinus Torvalds 		 *      If the ACK bit is set
63361da177e4SLinus Torvalds 		 *	  If SEG.ACK =< ISS, or SEG.ACK > SND.NXT, send
63371da177e4SLinus Torvalds 		 *        a reset (unless the RST bit is set, if so drop
63381da177e4SLinus Torvalds 		 *        the segment and return)"
63391da177e4SLinus Torvalds 		 */
63408e4178c1SYuchung Cheng 		if (!after(TCP_SKB_CB(skb)->ack_seq, tp->snd_una) ||
63419603d47bSSeongJae Park 		    after(TCP_SKB_CB(skb)->ack_seq, tp->snd_nxt)) {
63429603d47bSSeongJae Park 			/* Previous FIN/ACK or RST/ACK might be ignored. */
63439603d47bSSeongJae Park 			if (icsk->icsk_retransmits == 0)
63449603d47bSSeongJae Park 				inet_csk_reset_xmit_timer(sk,
63459603d47bSSeongJae Park 						ICSK_TIME_RETRANS,
63469603d47bSSeongJae Park 						TCP_TIMEOUT_MIN, TCP_RTO_MAX);
63471da177e4SLinus Torvalds 			goto reset_and_undo;
63489603d47bSSeongJae Park 		}
63491da177e4SLinus Torvalds 
63501da177e4SLinus Torvalds 		if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr &&
63511da177e4SLinus Torvalds 		    !between(tp->rx_opt.rcv_tsecr, tp->retrans_stamp,
63529a568de4SEric Dumazet 			     tcp_time_stamp(tp))) {
6353c10d9310SEric Dumazet 			NET_INC_STATS(sock_net(sk),
635402a1d6e7SEric Dumazet 					LINUX_MIB_PAWSACTIVEREJECTED);
63551da177e4SLinus Torvalds 			goto reset_and_undo;
63561da177e4SLinus Torvalds 		}
63571da177e4SLinus Torvalds 
63581da177e4SLinus Torvalds 		/* Now ACK is acceptable.
63591da177e4SLinus Torvalds 		 *
63601da177e4SLinus Torvalds 		 * "If the RST bit is set
63611da177e4SLinus Torvalds 		 *    If the ACK was acceptable then signal the user "error:
63621da177e4SLinus Torvalds 		 *    connection reset", drop the segment, enter CLOSED state,
63631da177e4SLinus Torvalds 		 *    delete TCB, and return."
63641da177e4SLinus Torvalds 		 */
63651da177e4SLinus Torvalds 
63661da177e4SLinus Torvalds 		if (th->rst) {
6367049fe386SFlorian Westphal 			tcp_reset(sk, skb);
6368c337578aSEric Dumazet consume:
6369c337578aSEric Dumazet 			__kfree_skb(skb);
6370c337578aSEric Dumazet 			return 0;
63711da177e4SLinus Torvalds 		}
63721da177e4SLinus Torvalds 
63731da177e4SLinus Torvalds 		/* rfc793:
63741da177e4SLinus Torvalds 		 *   "fifth, if neither of the SYN or RST bits is set then
63751da177e4SLinus Torvalds 		 *    drop the segment and return."
63761da177e4SLinus Torvalds 		 *
63771da177e4SLinus Torvalds 		 *    See note below!
63781da177e4SLinus Torvalds 		 *                                        --ANK(990513)
63791da177e4SLinus Torvalds 		 */
6380659affdbSEric Dumazet 		if (!th->syn) {
6381659affdbSEric Dumazet 			SKB_DR_SET(reason, TCP_FLAGS);
63821da177e4SLinus Torvalds 			goto discard_and_undo;
6383659affdbSEric Dumazet 		}
63841da177e4SLinus Torvalds 		/* rfc793:
63851da177e4SLinus Torvalds 		 *   "If the SYN bit is on ...
63861da177e4SLinus Torvalds 		 *    are acceptable then ...
63871da177e4SLinus Torvalds 		 *    (our SYN has been ACKed), change the connection
63881da177e4SLinus Torvalds 		 *    state to ESTABLISHED..."
63891da177e4SLinus Torvalds 		 */
63901da177e4SLinus Torvalds 
6391735d3831SFlorian Westphal 		tcp_ecn_rcv_synack(tp, th);
63921da177e4SLinus Torvalds 
63931b3a6926SRazvan Ghitulete 		tcp_init_wl(tp, TCP_SKB_CB(skb)->seq);
63947c1f0815SYuchung Cheng 		tcp_try_undo_spurious_syn(sk);
639531770e34SFlorian Westphal 		tcp_ack(sk, skb, FLAG_SLOWPATH);
63961da177e4SLinus Torvalds 
63971da177e4SLinus Torvalds 		/* Ok.. it's good. Set up sequence numbers and
63981da177e4SLinus Torvalds 		 * move to established.
63991da177e4SLinus Torvalds 		 */
6400dba7d9b8SEric Dumazet 		WRITE_ONCE(tp->rcv_nxt, TCP_SKB_CB(skb)->seq + 1);
64011da177e4SLinus Torvalds 		tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
64021da177e4SLinus Torvalds 
64031da177e4SLinus Torvalds 		/* RFC1323: The window in SYN & SYN/ACK segments is
64041da177e4SLinus Torvalds 		 * never scaled.
64051da177e4SLinus Torvalds 		 */
64061da177e4SLinus Torvalds 		tp->snd_wnd = ntohs(th->window);
64071da177e4SLinus Torvalds 
64081da177e4SLinus Torvalds 		if (!tp->rx_opt.wscale_ok) {
64091da177e4SLinus Torvalds 			tp->rx_opt.snd_wscale = tp->rx_opt.rcv_wscale = 0;
6410f9fef23aSEric Dumazet 			WRITE_ONCE(tp->window_clamp,
6411f9fef23aSEric Dumazet 				   min(tp->window_clamp, 65535U));
64121da177e4SLinus Torvalds 		}
64131da177e4SLinus Torvalds 
64141da177e4SLinus Torvalds 		if (tp->rx_opt.saw_tstamp) {
64151da177e4SLinus Torvalds 			tp->rx_opt.tstamp_ok	   = 1;
64161da177e4SLinus Torvalds 			tp->tcp_header_len =
64171da177e4SLinus Torvalds 				sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
64181da177e4SLinus Torvalds 			tp->advmss	    -= TCPOLEN_TSTAMP_ALIGNED;
64191da177e4SLinus Torvalds 			tcp_store_ts_recent(tp);
64201da177e4SLinus Torvalds 		} else {
64211da177e4SLinus Torvalds 			tp->tcp_header_len = sizeof(struct tcphdr);
64221da177e4SLinus Torvalds 		}
64231da177e4SLinus Torvalds 
6424d83d8461SArnaldo Carvalho de Melo 		tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
64251da177e4SLinus Torvalds 		tcp_initialize_rcv_mss(sk);
64261da177e4SLinus Torvalds 
64271da177e4SLinus Torvalds 		/* Remember, tcp_poll() does not lock socket!
64281da177e4SLinus Torvalds 		 * Change state from SYN-SENT only after copied_seq
64291da177e4SLinus Torvalds 		 * is initialized. */
64307db48e98SEric Dumazet 		WRITE_ONCE(tp->copied_seq, tp->rcv_nxt);
64314957faadSWilliam Allen Simpson 
643260e2a778SUrsula Braun 		smc_check_reset_syn(tp);
643360e2a778SUrsula Braun 
6434e16aa207SRalf Baechle 		smp_mb();
64351da177e4SLinus Torvalds 
6436370816aeSPavel Emelyanov 		tcp_finish_connect(sk, skb);
64371da177e4SLinus Torvalds 
64380f9fa831SEric Dumazet 		fastopen_fail = (tp->syn_fastopen || tp->syn_data) &&
64390f9fa831SEric Dumazet 				tcp_rcv_fastopen_synack(sk, skb, &foc);
64408e4178c1SYuchung Cheng 
64410f9fa831SEric Dumazet 		if (!sock_flag(sk, SOCK_DEAD)) {
64420f9fa831SEric Dumazet 			sk->sk_state_change(sk);
64430f9fa831SEric Dumazet 			sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT);
64440f9fa831SEric Dumazet 		}
64450f9fa831SEric Dumazet 		if (fastopen_fail)
64460f9fa831SEric Dumazet 			return -1;
6447295f7324SArnaldo Carvalho de Melo 		if (sk->sk_write_pending ||
64486e97ba55SEric Dumazet 		    READ_ONCE(icsk->icsk_accept_queue.rskq_defer_accept) ||
644931954cd8SWei Wang 		    inet_csk_in_pingpong_mode(sk)) {
64501da177e4SLinus Torvalds 			/* Save one ACK. Data will be ready after
64511da177e4SLinus Torvalds 			 * several ticks, if write_pending is set.
64521da177e4SLinus Torvalds 			 *
64531da177e4SLinus Torvalds 			 * It may be deleted, but with this feature tcpdumps
64541da177e4SLinus Torvalds 			 * look so _wonderfully_ clever, that I was not able
64551da177e4SLinus Torvalds 			 * to stand against the temptation 8)     --ANK
64561da177e4SLinus Torvalds 			 */
6457463c84b9SArnaldo Carvalho de Melo 			inet_csk_schedule_ack(sk);
64589a9c9b51SEric Dumazet 			tcp_enter_quickack_mode(sk, TCP_MAX_QUICKACKS);
64593f421baaSArnaldo Carvalho de Melo 			inet_csk_reset_xmit_timer(sk, ICSK_TIME_DACK,
64603f421baaSArnaldo Carvalho de Melo 						  TCP_DELACK_MAX, TCP_RTO_MAX);
6461c337578aSEric Dumazet 			goto consume;
64621da177e4SLinus Torvalds 		}
6463c337578aSEric Dumazet 		tcp_send_ack(sk);
64641da177e4SLinus Torvalds 		return -1;
64651da177e4SLinus Torvalds 	}
64661da177e4SLinus Torvalds 
64671da177e4SLinus Torvalds 	/* No ACK in the segment */
64681da177e4SLinus Torvalds 
64691da177e4SLinus Torvalds 	if (th->rst) {
64701da177e4SLinus Torvalds 		/* rfc793:
64711da177e4SLinus Torvalds 		 * "If the RST bit is set
64721da177e4SLinus Torvalds 		 *
64731da177e4SLinus Torvalds 		 *      Otherwise (no ACK) drop the segment and return."
64741da177e4SLinus Torvalds 		 */
6475659affdbSEric Dumazet 		SKB_DR_SET(reason, TCP_RESET);
64761da177e4SLinus Torvalds 		goto discard_and_undo;
64771da177e4SLinus Torvalds 	}
64781da177e4SLinus Torvalds 
64791da177e4SLinus Torvalds 	/* PAWS check. */
6480056834d9SIlpo Järvinen 	if (tp->rx_opt.ts_recent_stamp && tp->rx_opt.saw_tstamp &&
6481659affdbSEric Dumazet 	    tcp_paws_reject(&tp->rx_opt, 0)) {
6482659affdbSEric Dumazet 		SKB_DR_SET(reason, TCP_RFC7323_PAWS);
64831da177e4SLinus Torvalds 		goto discard_and_undo;
6484659affdbSEric Dumazet 	}
64851da177e4SLinus Torvalds 	if (th->syn) {
64861da177e4SLinus Torvalds 		/* We see SYN without ACK. It is attempt of
64871da177e4SLinus Torvalds 		 * simultaneous connect with crossed SYNs.
64881da177e4SLinus Torvalds 		 * Particularly, it can be connect to self.
64891da177e4SLinus Torvalds 		 */
64901da177e4SLinus Torvalds 		tcp_set_state(sk, TCP_SYN_RECV);
64911da177e4SLinus Torvalds 
64921da177e4SLinus Torvalds 		if (tp->rx_opt.saw_tstamp) {
64931da177e4SLinus Torvalds 			tp->rx_opt.tstamp_ok = 1;
64941da177e4SLinus Torvalds 			tcp_store_ts_recent(tp);
64951da177e4SLinus Torvalds 			tp->tcp_header_len =
64961da177e4SLinus Torvalds 				sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
64971da177e4SLinus Torvalds 		} else {
64981da177e4SLinus Torvalds 			tp->tcp_header_len = sizeof(struct tcphdr);
64991da177e4SLinus Torvalds 		}
65001da177e4SLinus Torvalds 
6501dba7d9b8SEric Dumazet 		WRITE_ONCE(tp->rcv_nxt, TCP_SKB_CB(skb)->seq + 1);
65027db48e98SEric Dumazet 		WRITE_ONCE(tp->copied_seq, tp->rcv_nxt);
65031da177e4SLinus Torvalds 		tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
65041da177e4SLinus Torvalds 
65051da177e4SLinus Torvalds 		/* RFC1323: The window in SYN & SYN/ACK segments is
65061da177e4SLinus Torvalds 		 * never scaled.
65071da177e4SLinus Torvalds 		 */
65081da177e4SLinus Torvalds 		tp->snd_wnd    = ntohs(th->window);
65091da177e4SLinus Torvalds 		tp->snd_wl1    = TCP_SKB_CB(skb)->seq;
65101da177e4SLinus Torvalds 		tp->max_window = tp->snd_wnd;
65111da177e4SLinus Torvalds 
6512735d3831SFlorian Westphal 		tcp_ecn_rcv_syn(tp, th);
65131da177e4SLinus Torvalds 
65145d424d5aSJohn Heffner 		tcp_mtup_init(sk);
6515d83d8461SArnaldo Carvalho de Melo 		tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
65161da177e4SLinus Torvalds 		tcp_initialize_rcv_mss(sk);
65171da177e4SLinus Torvalds 
65181da177e4SLinus Torvalds 		tcp_send_synack(sk);
65191da177e4SLinus Torvalds #if 0
65201da177e4SLinus Torvalds 		/* Note, we could accept data and URG from this segment.
6521168a8f58SJerry Chu 		 * There are no obstacles to make this (except that we must
6522168a8f58SJerry Chu 		 * either change tcp_recvmsg() to prevent it from returning data
6523168a8f58SJerry Chu 		 * before 3WHS completes per RFC793, or employ TCP Fast Open).
65241da177e4SLinus Torvalds 		 *
65251da177e4SLinus Torvalds 		 * However, if we ignore data in ACKless segments sometimes,
65261da177e4SLinus Torvalds 		 * we have no reasons to accept it sometimes.
65271da177e4SLinus Torvalds 		 * Also, seems the code doing it in step6 of tcp_rcv_state_process
65281da177e4SLinus Torvalds 		 * is not flawless. So, discard packet for sanity.
65291da177e4SLinus Torvalds 		 * Uncomment this return to process the data.
65301da177e4SLinus Torvalds 		 */
65311da177e4SLinus Torvalds 		return -1;
65321da177e4SLinus Torvalds #else
6533c337578aSEric Dumazet 		goto consume;
65341da177e4SLinus Torvalds #endif
65351da177e4SLinus Torvalds 	}
65361da177e4SLinus Torvalds 	/* "fifth, if neither of the SYN or RST bits is set then
65371da177e4SLinus Torvalds 	 * drop the segment and return."
65381da177e4SLinus Torvalds 	 */
65391da177e4SLinus Torvalds 
65401da177e4SLinus Torvalds discard_and_undo:
65411da177e4SLinus Torvalds 	tcp_clear_options(&tp->rx_opt);
65421da177e4SLinus Torvalds 	tp->rx_opt.mss_clamp = saved_clamp;
6543659affdbSEric Dumazet 	tcp_drop_reason(sk, skb, reason);
6544c337578aSEric Dumazet 	return 0;
65451da177e4SLinus Torvalds 
65461da177e4SLinus Torvalds reset_and_undo:
65471da177e4SLinus Torvalds 	tcp_clear_options(&tp->rx_opt);
65481da177e4SLinus Torvalds 	tp->rx_opt.mss_clamp = saved_clamp;
65491da177e4SLinus Torvalds 	return 1;
65501da177e4SLinus Torvalds }
65511da177e4SLinus Torvalds 
tcp_rcv_synrecv_state_fastopen(struct sock * sk)65526b94b1c8SYuchung Cheng static void tcp_rcv_synrecv_state_fastopen(struct sock *sk)
65536b94b1c8SYuchung Cheng {
65547cfb0246SAananth V 	struct tcp_sock *tp = tcp_sk(sk);
6555d983ea6fSEric Dumazet 	struct request_sock *req;
6556d983ea6fSEric Dumazet 
6557dad8cea7SNeal Cardwell 	/* If we are still handling the SYNACK RTO, see if timestamp ECR allows
6558dad8cea7SNeal Cardwell 	 * undo. If peer SACKs triggered fast recovery, we can't undo here.
6559dad8cea7SNeal Cardwell 	 */
65607cfb0246SAananth V 	if (inet_csk(sk)->icsk_ca_state == TCP_CA_Loss && !tp->packets_out)
65617cfb0246SAananth V 		tcp_try_undo_recovery(sk);
6562cd736d8bSYuchung Cheng 
6563718c49f8SAananth V 	tcp_update_rto_time(tp);
65646b94b1c8SYuchung Cheng 	inet_csk(sk)->icsk_retransmits = 0;
65652daffbd8SNeal Cardwell 	/* In tcp_fastopen_synack_timer() on the first SYNACK RTO we set
65662daffbd8SNeal Cardwell 	 * retrans_stamp but don't enter CA_Loss, so in case that happened we
65672daffbd8SNeal Cardwell 	 * need to zero retrans_stamp here to prevent spurious
65682daffbd8SNeal Cardwell 	 * retransmits_timed_out(). However, if the ACK of our SYNACK caused us
65692daffbd8SNeal Cardwell 	 * to enter CA_Recovery then we need to leave retrans_stamp as it was
65702daffbd8SNeal Cardwell 	 * set entering CA_Recovery, for correct retransmits_timed_out() and
65712daffbd8SNeal Cardwell 	 * undo behavior.
65722daffbd8SNeal Cardwell 	 */
65732daffbd8SNeal Cardwell 	tcp_retrans_stamp_cleanup(sk);
65746b94b1c8SYuchung Cheng 
65756b94b1c8SYuchung Cheng 	/* Once we leave TCP_SYN_RECV or TCP_FIN_WAIT_1,
65766b94b1c8SYuchung Cheng 	 * we no longer need req so release it.
65776b94b1c8SYuchung Cheng 	 */
65787cfb0246SAananth V 	req = rcu_dereference_protected(tp->fastopen_rsk,
6579d983ea6fSEric Dumazet 					lockdep_sock_is_held(sk));
6580d983ea6fSEric Dumazet 	reqsk_fastopen_remove(sk, req, false);
65816b94b1c8SYuchung Cheng 
65826b94b1c8SYuchung Cheng 	/* Re-arm the timer because data may have been sent out.
65836b94b1c8SYuchung Cheng 	 * This is similar to the regular data transmission case
65846b94b1c8SYuchung Cheng 	 * when new data has just been ack'ed.
65856b94b1c8SYuchung Cheng 	 *
65866b94b1c8SYuchung Cheng 	 * (TFO) - we could try to be more aggressive and
65876b94b1c8SYuchung Cheng 	 * retransmitting any data sooner based on when they
65886b94b1c8SYuchung Cheng 	 * are sent out.
65896b94b1c8SYuchung Cheng 	 */
65906b94b1c8SYuchung Cheng 	tcp_rearm_rto(sk);
65916b94b1c8SYuchung Cheng }
65926b94b1c8SYuchung Cheng 
65931da177e4SLinus Torvalds /*
65941da177e4SLinus Torvalds  *	This function implements the receiving procedure of RFC 793 for
65951da177e4SLinus Torvalds  *	all states except ESTABLISHED and TIME_WAIT.
65961da177e4SLinus Torvalds  *	It's called from both tcp_v4_rcv and tcp_v6_rcv and should be
65971da177e4SLinus Torvalds  *	address independent.
65981da177e4SLinus Torvalds  */
65991da177e4SLinus Torvalds 
tcp_rcv_state_process(struct sock * sk,struct sk_buff * skb)660072ab4a86SEric Dumazet int tcp_rcv_state_process(struct sock *sk, struct sk_buff *skb)
66011da177e4SLinus Torvalds {
66021da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
66038292a17aSArnaldo Carvalho de Melo 	struct inet_connection_sock *icsk = inet_csk(sk);
660472ab4a86SEric Dumazet 	const struct tcphdr *th = tcp_hdr(skb);
6605168a8f58SJerry Chu 	struct request_sock *req;
66061da177e4SLinus Torvalds 	int queued = 0;
66071f6afc81SEric Dumazet 	bool acceptable;
6608669da7a7SEric Dumazet 	SKB_DR(reason);
66091da177e4SLinus Torvalds 
66101da177e4SLinus Torvalds 	switch (sk->sk_state) {
66111da177e4SLinus Torvalds 	case TCP_CLOSE:
6612669da7a7SEric Dumazet 		SKB_DR_SET(reason, TCP_CLOSE);
66131da177e4SLinus Torvalds 		goto discard;
66141da177e4SLinus Torvalds 
66151da177e4SLinus Torvalds 	case TCP_LISTEN:
66161da177e4SLinus Torvalds 		if (th->ack)
66171da177e4SLinus Torvalds 			return 1;
66181da177e4SLinus Torvalds 
6619669da7a7SEric Dumazet 		if (th->rst) {
6620669da7a7SEric Dumazet 			SKB_DR_SET(reason, TCP_RESET);
66211da177e4SLinus Torvalds 			goto discard;
6622669da7a7SEric Dumazet 		}
66231da177e4SLinus Torvalds 		if (th->syn) {
6624669da7a7SEric Dumazet 			if (th->fin) {
6625669da7a7SEric Dumazet 				SKB_DR_SET(reason, TCP_FLAGS);
6626fdf5af0dSEric Dumazet 				goto discard;
6627669da7a7SEric Dumazet 			}
6628449809a6SEric Dumazet 			/* It is possible that we process SYN packets from backlog,
66291ad98e9dSEric Dumazet 			 * so we need to make sure to disable BH and RCU right there.
6630449809a6SEric Dumazet 			 */
66311ad98e9dSEric Dumazet 			rcu_read_lock();
6632449809a6SEric Dumazet 			local_bh_disable();
6633449809a6SEric Dumazet 			acceptable = icsk->icsk_af_ops->conn_request(sk, skb) >= 0;
6634449809a6SEric Dumazet 			local_bh_enable();
66351ad98e9dSEric Dumazet 			rcu_read_unlock();
66361da177e4SLinus Torvalds 
6637449809a6SEric Dumazet 			if (!acceptable)
6638449809a6SEric Dumazet 				return 1;
66390aea76d3SEric Dumazet 			consume_skb(skb);
6640fb7e2399SMasayuki Nakagawa 			return 0;
66411da177e4SLinus Torvalds 		}
6642669da7a7SEric Dumazet 		SKB_DR_SET(reason, TCP_FLAGS);
66431da177e4SLinus Torvalds 		goto discard;
66441da177e4SLinus Torvalds 
66451da177e4SLinus Torvalds 	case TCP_SYN_SENT:
66468804b272SEric Dumazet 		tp->rx_opt.saw_tstamp = 0;
66479a568de4SEric Dumazet 		tcp_mstamp_refresh(tp);
6648bda07a64SEric Dumazet 		queued = tcp_rcv_synsent_state_process(sk, skb, th);
66491da177e4SLinus Torvalds 		if (queued >= 0)
66501da177e4SLinus Torvalds 			return queued;
66511da177e4SLinus Torvalds 
66521da177e4SLinus Torvalds 		/* Do step6 onward by hand. */
66531da177e4SLinus Torvalds 		tcp_urg(sk, skb, th);
66541da177e4SLinus Torvalds 		__kfree_skb(skb);
66559e412ba7SIlpo Järvinen 		tcp_data_snd_check(sk);
66561da177e4SLinus Torvalds 		return 0;
66571da177e4SLinus Torvalds 	}
66581da177e4SLinus Torvalds 
66599a568de4SEric Dumazet 	tcp_mstamp_refresh(tp);
66608804b272SEric Dumazet 	tp->rx_opt.saw_tstamp = 0;
6661d983ea6fSEric Dumazet 	req = rcu_dereference_protected(tp->fastopen_rsk,
6662d983ea6fSEric Dumazet 					lockdep_sock_is_held(sk));
666300db4124SIan Morris 	if (req) {
6664e0f9759fSEric Dumazet 		bool req_stolen;
6665e0f9759fSEric Dumazet 
666637561f68SJerry Chu 		WARN_ON_ONCE(sk->sk_state != TCP_SYN_RECV &&
6667168a8f58SJerry Chu 		    sk->sk_state != TCP_FIN_WAIT1);
6668168a8f58SJerry Chu 
6669669da7a7SEric Dumazet 		if (!tcp_check_req(sk, skb, req, true, &req_stolen)) {
6670669da7a7SEric Dumazet 			SKB_DR_SET(reason, TCP_FASTOPEN);
6671168a8f58SJerry Chu 			goto discard;
6672e69bebdeSNeal Cardwell 		}
6673669da7a7SEric Dumazet 	}
6674c3ae62afSEric Dumazet 
6675669da7a7SEric Dumazet 	if (!th->ack && !th->rst && !th->syn) {
6676669da7a7SEric Dumazet 		SKB_DR_SET(reason, TCP_FLAGS);
6677c3ae62afSEric Dumazet 		goto discard;
6678669da7a7SEric Dumazet 	}
6679e69bebdeSNeal Cardwell 	if (!tcp_validate_incoming(sk, skb, th, 0))
66800c24604bSEric Dumazet 		return 0;
66811da177e4SLinus Torvalds 
66821da177e4SLinus Torvalds 	/* step 5: check the ACK field */
668331770e34SFlorian Westphal 	acceptable = tcp_ack(sk, skb, FLAG_SLOWPATH |
668431770e34SFlorian Westphal 				      FLAG_UPDATE_TS_RECENT |
6685d0e1a1b5SEric Dumazet 				      FLAG_NO_CHALLENGE_ACK) > 0;
66861da177e4SLinus Torvalds 
6687d0e1a1b5SEric Dumazet 	if (!acceptable) {
6688d0e1a1b5SEric Dumazet 		if (sk->sk_state == TCP_SYN_RECV)
6689d0e1a1b5SEric Dumazet 			return 1;	/* send one RST */
6690208dd45dSBenjamin Yim 		tcp_send_challenge_ack(sk);
6691669da7a7SEric Dumazet 		SKB_DR_SET(reason, TCP_OLD_ACK);
6692d0e1a1b5SEric Dumazet 		goto discard;
6693d0e1a1b5SEric Dumazet 	}
66941da177e4SLinus Torvalds 	switch (sk->sk_state) {
66951da177e4SLinus Torvalds 	case TCP_SYN_RECV:
6696bef5767fSYuchung Cheng 		tp->delivered++; /* SYN-ACK delivery isn't tracked in tcp_ack */
66970f1c28aeSYuchung Cheng 		if (!tp->srtt_us)
66980f1c28aeSYuchung Cheng 			tcp_synack_rtt_meas(sk, req);
66990f1c28aeSYuchung Cheng 
6700168a8f58SJerry Chu 		if (req) {
67016b94b1c8SYuchung Cheng 			tcp_rcv_synrecv_state_fastopen(sk);
6702168a8f58SJerry Chu 		} else {
6703336c39a0SYuchung Cheng 			tcp_try_undo_spurious_syn(sk);
6704336c39a0SYuchung Cheng 			tp->retrans_stamp = 0;
670572be0fe6SMartin KaFai Lau 			tcp_init_transfer(sk, BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB,
670672be0fe6SMartin KaFai Lau 					  skb);
67077db48e98SEric Dumazet 			WRITE_ONCE(tp->copied_seq, tp->rcv_nxt);
6708168a8f58SJerry Chu 		}
6709e16aa207SRalf Baechle 		smp_mb();
67101da177e4SLinus Torvalds 		tcp_set_state(sk, TCP_ESTABLISHED);
67111da177e4SLinus Torvalds 		sk->sk_state_change(sk);
67121da177e4SLinus Torvalds 
671361eb9003SJoe Perches 		/* Note, that this wakeup is only for marginal crossed SYN case.
671461eb9003SJoe Perches 		 * Passively open sockets are not waked up, because
671561eb9003SJoe Perches 		 * sk->sk_sleep == NULL and sk->sk_socket == NULL.
67161da177e4SLinus Torvalds 		 */
67178d8ad9d7SPavel Emelyanov 		if (sk->sk_socket)
67181f6afc81SEric Dumazet 			sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT);
67191da177e4SLinus Torvalds 
67201da177e4SLinus Torvalds 		tp->snd_una = TCP_SKB_CB(skb)->ack_seq;
672161eb9003SJoe Perches 		tp->snd_wnd = ntohs(th->window) << tp->rx_opt.snd_wscale;
6722ee7537b6SHantzis Fotis 		tcp_init_wl(tp, TCP_SKB_CB(skb)->seq);
67231da177e4SLinus Torvalds 
67241da177e4SLinus Torvalds 		if (tp->rx_opt.tstamp_ok)
67251da177e4SLinus Torvalds 			tp->advmss -= TCPOLEN_TSTAMP_ALIGNED;
67261da177e4SLinus Torvalds 
6727c0402760SYuchung Cheng 		if (!inet_csk(sk)->icsk_ca_ops->cong_control)
672802cf4ebdSNeal Cardwell 			tcp_update_pacing_rate(sk);
672902cf4ebdSNeal Cardwell 
673061eb9003SJoe Perches 		/* Prevent spurious tcp_cwnd_restart() on first data packet */
6731d635fbe2SEric Dumazet 		tp->lsndtime = tcp_jiffies32;
67321da177e4SLinus Torvalds 
67331da177e4SLinus Torvalds 		tcp_initialize_rcv_mss(sk);
673431770e34SFlorian Westphal 		tcp_fast_path_on(tp);
6735f47d0d32SEric Dumazet 		if (sk->sk_shutdown & SEND_SHUTDOWN)
6736f47d0d32SEric Dumazet 			tcp_shutdown(sk, SEND_SHUTDOWN);
67371da177e4SLinus Torvalds 		break;
67381da177e4SLinus Torvalds 
6739c48b22daSJoe Perches 	case TCP_FIN_WAIT1: {
6740c48b22daSJoe Perches 		int tmo;
6741c48b22daSJoe Perches 
67426b94b1c8SYuchung Cheng 		if (req)
67436b94b1c8SYuchung Cheng 			tcp_rcv_synrecv_state_fastopen(sk);
67446b94b1c8SYuchung Cheng 
6745c48b22daSJoe Perches 		if (tp->snd_una != tp->write_seq)
6746c48b22daSJoe Perches 			break;
67475110effeSDavid S. Miller 
67481da177e4SLinus Torvalds 		tcp_set_state(sk, TCP_FIN_WAIT2);
6749e14cadfdSEric Dumazet 		WRITE_ONCE(sk->sk_shutdown, sk->sk_shutdown | SEND_SHUTDOWN);
67505110effeSDavid S. Miller 
6751c3a2e837SJulian Anastasov 		sk_dst_confirm(sk);
67521da177e4SLinus Torvalds 
67531f6afc81SEric Dumazet 		if (!sock_flag(sk, SOCK_DEAD)) {
67541da177e4SLinus Torvalds 			/* Wake up lingering close() */
67551da177e4SLinus Torvalds 			sk->sk_state_change(sk);
6756c48b22daSJoe Perches 			break;
6757c48b22daSJoe Perches 		}
67581da177e4SLinus Torvalds 
6759a81722ddSEric Dumazet 		if (READ_ONCE(tp->linger2) < 0) {
6760cf1ef3f0SWei Wang 			tcp_done(sk);
6761cf1ef3f0SWei Wang 			NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
6762cf1ef3f0SWei Wang 			return 1;
6763cf1ef3f0SWei Wang 		}
6764cf1ef3f0SWei Wang 		if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
6765cf1ef3f0SWei Wang 		    after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt)) {
6766cf1ef3f0SWei Wang 			/* Receive out of order FIN after close() */
6767cf1ef3f0SWei Wang 			if (tp->syn_fastopen && th->fin)
676846c2fa39SWei Wang 				tcp_fastopen_active_disable(sk);
67691da177e4SLinus Torvalds 			tcp_done(sk);
6770c10d9310SEric Dumazet 			NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
67711da177e4SLinus Torvalds 			return 1;
67721da177e4SLinus Torvalds 		}
67731da177e4SLinus Torvalds 
6774463c84b9SArnaldo Carvalho de Melo 		tmo = tcp_fin_time(sk);
67751da177e4SLinus Torvalds 		if (tmo > TCP_TIMEWAIT_LEN) {
6776463c84b9SArnaldo Carvalho de Melo 			inet_csk_reset_keepalive_timer(sk, tmo - TCP_TIMEWAIT_LEN);
67771da177e4SLinus Torvalds 		} else if (th->fin || sock_owned_by_user(sk)) {
67781da177e4SLinus Torvalds 			/* Bad case. We could lose such FIN otherwise.
67791da177e4SLinus Torvalds 			 * It is not a big problem, but it looks confusing
67801da177e4SLinus Torvalds 			 * and not so rare event. We still can lose it now,
67811da177e4SLinus Torvalds 			 * if it spins in bh_lock_sock(), but it is really
67821da177e4SLinus Torvalds 			 * marginal case.
67831da177e4SLinus Torvalds 			 */
6784463c84b9SArnaldo Carvalho de Melo 			inet_csk_reset_keepalive_timer(sk, tmo);
67851da177e4SLinus Torvalds 		} else {
67861da177e4SLinus Torvalds 			tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
678737fd4e84SEric Dumazet 			goto consume;
67881da177e4SLinus Torvalds 		}
67891da177e4SLinus Torvalds 		break;
6790c48b22daSJoe Perches 	}
67911da177e4SLinus Torvalds 
67921da177e4SLinus Torvalds 	case TCP_CLOSING:
67931da177e4SLinus Torvalds 		if (tp->snd_una == tp->write_seq) {
67941da177e4SLinus Torvalds 			tcp_time_wait(sk, TCP_TIME_WAIT, 0);
679537fd4e84SEric Dumazet 			goto consume;
67961da177e4SLinus Torvalds 		}
67971da177e4SLinus Torvalds 		break;
67981da177e4SLinus Torvalds 
67991da177e4SLinus Torvalds 	case TCP_LAST_ACK:
68001da177e4SLinus Torvalds 		if (tp->snd_una == tp->write_seq) {
68011da177e4SLinus Torvalds 			tcp_update_metrics(sk);
68021da177e4SLinus Torvalds 			tcp_done(sk);
680337fd4e84SEric Dumazet 			goto consume;
68041da177e4SLinus Torvalds 		}
68051da177e4SLinus Torvalds 		break;
68061da177e4SLinus Torvalds 	}
68071da177e4SLinus Torvalds 
68081da177e4SLinus Torvalds 	/* step 6: check the URG bit */
68091da177e4SLinus Torvalds 	tcp_urg(sk, skb, th);
68101da177e4SLinus Torvalds 
68111da177e4SLinus Torvalds 	/* step 7: process the segment text */
68121da177e4SLinus Torvalds 	switch (sk->sk_state) {
68131da177e4SLinus Torvalds 	case TCP_CLOSE_WAIT:
68141da177e4SLinus Torvalds 	case TCP_CLOSING:
68151da177e4SLinus Torvalds 	case TCP_LAST_ACK:
6816648ef4b8SMat Martineau 		if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
68176787b7e3SJianguo Wu 			/* If a subflow has been reset, the packet should not
68186787b7e3SJianguo Wu 			 * continue to be processed, drop the packet.
68196787b7e3SJianguo Wu 			 */
68206787b7e3SJianguo Wu 			if (sk_is_mptcp(sk) && !mptcp_incoming_options(sk, skb))
68216787b7e3SJianguo Wu 				goto discard;
68221da177e4SLinus Torvalds 			break;
6823648ef4b8SMat Martineau 		}
6824a8eceea8SJoe Perches 		fallthrough;
68251da177e4SLinus Torvalds 	case TCP_FIN_WAIT1:
68261da177e4SLinus Torvalds 	case TCP_FIN_WAIT2:
68271da177e4SLinus Torvalds 		/* RFC 793 says to queue data in these states,
68281da177e4SLinus Torvalds 		 * RFC 1122 says we MUST send a reset.
68291da177e4SLinus Torvalds 		 * BSD 4.4 also does reset.
68301da177e4SLinus Torvalds 		 */
68311da177e4SLinus Torvalds 		if (sk->sk_shutdown & RCV_SHUTDOWN) {
68321da177e4SLinus Torvalds 			if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
68331da177e4SLinus Torvalds 			    after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt)) {
6834c10d9310SEric Dumazet 				NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
6835049fe386SFlorian Westphal 				tcp_reset(sk, skb);
68361da177e4SLinus Torvalds 				return 1;
68371da177e4SLinus Torvalds 			}
68381da177e4SLinus Torvalds 		}
6839a8eceea8SJoe Perches 		fallthrough;
68401da177e4SLinus Torvalds 	case TCP_ESTABLISHED:
68411da177e4SLinus Torvalds 		tcp_data_queue(sk, skb);
68421da177e4SLinus Torvalds 		queued = 1;
68431da177e4SLinus Torvalds 		break;
68441da177e4SLinus Torvalds 	}
68451da177e4SLinus Torvalds 
68461da177e4SLinus Torvalds 	/* tcp_data could move socket to TIME-WAIT */
68471da177e4SLinus Torvalds 	if (sk->sk_state != TCP_CLOSE) {
68489e412ba7SIlpo Järvinen 		tcp_data_snd_check(sk);
68491da177e4SLinus Torvalds 		tcp_ack_snd_check(sk);
68501da177e4SLinus Torvalds 	}
68511da177e4SLinus Torvalds 
68521da177e4SLinus Torvalds 	if (!queued) {
68531da177e4SLinus Torvalds discard:
6854669da7a7SEric Dumazet 		tcp_drop_reason(sk, skb, reason);
68551da177e4SLinus Torvalds 	}
68561da177e4SLinus Torvalds 	return 0;
685737fd4e84SEric Dumazet 
685837fd4e84SEric Dumazet consume:
685937fd4e84SEric Dumazet 	__kfree_skb(skb);
686037fd4e84SEric Dumazet 	return 0;
68611da177e4SLinus Torvalds }
68621da177e4SLinus Torvalds EXPORT_SYMBOL(tcp_rcv_state_process);
68631fb6f159SOctavian Purdila 
pr_drop_req(struct request_sock * req,__u16 port,int family)68641fb6f159SOctavian Purdila static inline void pr_drop_req(struct request_sock *req, __u16 port, int family)
68651fb6f159SOctavian Purdila {
68661fb6f159SOctavian Purdila 	struct inet_request_sock *ireq = inet_rsk(req);
68671fb6f159SOctavian Purdila 
68681fb6f159SOctavian Purdila 	if (family == AF_INET)
6869ba7a46f1SJoe Perches 		net_dbg_ratelimited("drop open request from %pI4/%u\n",
68701fb6f159SOctavian Purdila 				    &ireq->ir_rmt_addr, port);
68714135ab82SOctavian Purdila #if IS_ENABLED(CONFIG_IPV6)
68724135ab82SOctavian Purdila 	else if (family == AF_INET6)
6873ba7a46f1SJoe Perches 		net_dbg_ratelimited("drop open request from %pI6/%u\n",
68741fb6f159SOctavian Purdila 				    &ireq->ir_v6_rmt_addr, port);
68754135ab82SOctavian Purdila #endif
68761fb6f159SOctavian Purdila }
68771fb6f159SOctavian Purdila 
6878d82bd122SFlorian Westphal /* RFC3168 : 6.1.1 SYN packets must not have ECT/ECN bits set
6879d82bd122SFlorian Westphal  *
6880d82bd122SFlorian Westphal  * If we receive a SYN packet with these bits set, it means a
6881d82bd122SFlorian Westphal  * network is playing bad games with TOS bits. In order to
6882d82bd122SFlorian Westphal  * avoid possible false congestion notifications, we disable
6883f4e715c3Sstephen hemminger  * TCP ECN negotiation.
6884d82bd122SFlorian Westphal  *
6885d82bd122SFlorian Westphal  * Exception: tcp_ca wants ECN. This is required for DCTCP
6886843c2fdfSFlorian Westphal  * congestion control: Linux DCTCP asserts ECT on all packets,
6887843c2fdfSFlorian Westphal  * including SYN, which is most optimal solution; however,
6888843c2fdfSFlorian Westphal  * others, such as FreeBSD do not.
6889f6fee16dSTilmans, Olivier (Nokia - BE/Antwerp)  *
6890f6fee16dSTilmans, Olivier (Nokia - BE/Antwerp)  * Exception: At least one of the reserved bits of the TCP header (th->res1) is
6891f6fee16dSTilmans, Olivier (Nokia - BE/Antwerp)  * set, indicating the use of a future TCP extension (such as AccECN). See
6892f6fee16dSTilmans, Olivier (Nokia - BE/Antwerp)  * RFC8311 §4.3 which updates RFC3168 to allow the development of such
6893f6fee16dSTilmans, Olivier (Nokia - BE/Antwerp)  * extensions.
6894d82bd122SFlorian Westphal  */
tcp_ecn_create_request(struct request_sock * req,const struct sk_buff * skb,const struct sock * listen_sk,const struct dst_entry * dst)6895d82bd122SFlorian Westphal static void tcp_ecn_create_request(struct request_sock *req,
6896d82bd122SFlorian Westphal 				   const struct sk_buff *skb,
6897f7b3bec6SFlorian Westphal 				   const struct sock *listen_sk,
6898f7b3bec6SFlorian Westphal 				   const struct dst_entry *dst)
6899d82bd122SFlorian Westphal {
6900d82bd122SFlorian Westphal 	const struct tcphdr *th = tcp_hdr(skb);
6901d82bd122SFlorian Westphal 	const struct net *net = sock_net(listen_sk);
6902d82bd122SFlorian Westphal 	bool th_ecn = th->ece && th->cwr;
6903843c2fdfSFlorian Westphal 	bool ect, ecn_ok;
6904c3a8d947SDaniel Borkmann 	u32 ecn_ok_dst;
6905d82bd122SFlorian Westphal 
6906d82bd122SFlorian Westphal 	if (!th_ecn)
6907d82bd122SFlorian Westphal 		return;
6908d82bd122SFlorian Westphal 
6909d82bd122SFlorian Westphal 	ect = !INET_ECN_is_not_ect(TCP_SKB_CB(skb)->ip_dsfield);
6910c3a8d947SDaniel Borkmann 	ecn_ok_dst = dst_feature(dst, DST_FEATURE_ECN_MASK);
69114785a667SKuniyuki Iwashima 	ecn_ok = READ_ONCE(net->ipv4.sysctl_tcp_ecn) || ecn_ok_dst;
6912d82bd122SFlorian Westphal 
6913f6fee16dSTilmans, Olivier (Nokia - BE/Antwerp) 	if (((!ect || th->res1) && ecn_ok) || tcp_ca_needs_ecn(listen_sk) ||
691491b5b21cSLawrence Brakmo 	    (ecn_ok_dst & DST_FEATURE_ECN_CA) ||
691591b5b21cSLawrence Brakmo 	    tcp_bpf_ca_needs_ecn((struct sock *)req))
6916d82bd122SFlorian Westphal 		inet_rsk(req)->ecn_ok = 1;
6917d82bd122SFlorian Westphal }
6918d82bd122SFlorian Westphal 
tcp_openreq_init(struct request_sock * req,const struct tcp_options_received * rx_opt,struct sk_buff * skb,const struct sock * sk)69191bfc4438SEric Dumazet static void tcp_openreq_init(struct request_sock *req,
69201bfc4438SEric Dumazet 			     const struct tcp_options_received *rx_opt,
69211bfc4438SEric Dumazet 			     struct sk_buff *skb, const struct sock *sk)
69221bfc4438SEric Dumazet {
69231bfc4438SEric Dumazet 	struct inet_request_sock *ireq = inet_rsk(req);
69241bfc4438SEric Dumazet 
6925ed53d0abSEric Dumazet 	req->rsk_rcv_wnd = 0;		/* So that tcp_send_synack() knows! */
69261bfc4438SEric Dumazet 	tcp_rsk(req)->rcv_isn = TCP_SKB_CB(skb)->seq;
69271bfc4438SEric Dumazet 	tcp_rsk(req)->rcv_nxt = TCP_SKB_CB(skb)->seq + 1;
69289e450c1eSYuchung Cheng 	tcp_rsk(req)->snt_synack = 0;
69291bfc4438SEric Dumazet 	tcp_rsk(req)->last_oow_ack_time = 0;
69301bfc4438SEric Dumazet 	req->mss = rx_opt->mss_clamp;
69311bfc4438SEric Dumazet 	req->ts_recent = rx_opt->saw_tstamp ? rx_opt->rcv_tsval : 0;
69321bfc4438SEric Dumazet 	ireq->tstamp_ok = rx_opt->tstamp_ok;
69331bfc4438SEric Dumazet 	ireq->sack_ok = rx_opt->sack_ok;
69341bfc4438SEric Dumazet 	ireq->snd_wscale = rx_opt->snd_wscale;
69351bfc4438SEric Dumazet 	ireq->wscale_ok = rx_opt->wscale_ok;
69361bfc4438SEric Dumazet 	ireq->acked = 0;
69371bfc4438SEric Dumazet 	ireq->ecn_ok = 0;
69381bfc4438SEric Dumazet 	ireq->ir_rmt_port = tcp_hdr(skb)->source;
69391bfc4438SEric Dumazet 	ireq->ir_num = ntohs(tcp_hdr(skb)->dest);
69401bfc4438SEric Dumazet 	ireq->ir_mark = inet_request_mark(sk, skb);
694160e2a778SUrsula Braun #if IS_ENABLED(CONFIG_SMC)
694248b6190aSD. Wythe 	ireq->smc_ok = rx_opt->smc_ok && !(tcp_sk(sk)->smc_hs_congested &&
694348b6190aSD. Wythe 			tcp_sk(sk)->smc_hs_congested(sk));
694460e2a778SUrsula Braun #endif
69451bfc4438SEric Dumazet }
69461bfc4438SEric Dumazet 
inet_reqsk_alloc(const struct request_sock_ops * ops,struct sock * sk_listener,bool attach_listener)6947e49bb337SEric Dumazet struct request_sock *inet_reqsk_alloc(const struct request_sock_ops *ops,
6948a1a5344dSEric Dumazet 				      struct sock *sk_listener,
6949a1a5344dSEric Dumazet 				      bool attach_listener)
6950e49bb337SEric Dumazet {
6951a1a5344dSEric Dumazet 	struct request_sock *req = reqsk_alloc(ops, sk_listener,
6952a1a5344dSEric Dumazet 					       attach_listener);
6953e49bb337SEric Dumazet 
6954e49bb337SEric Dumazet 	if (req) {
6955e49bb337SEric Dumazet 		struct inet_request_sock *ireq = inet_rsk(req);
6956e49bb337SEric Dumazet 
6957c92e8c02SEric Dumazet 		ireq->ireq_opt = NULL;
695856ac42bcSHuw Davies #if IS_ENABLED(CONFIG_IPV6)
695956ac42bcSHuw Davies 		ireq->pktopts = NULL;
696056ac42bcSHuw Davies #endif
6961a06ac0d6SYafang Shao 		atomic64_set(&ireq->ir_cookie, 0);
6962e49bb337SEric Dumazet 		ireq->ireq_state = TCP_NEW_SYN_RECV;
6963e49bb337SEric Dumazet 		write_pnet(&ireq->ireq_net, sock_net(sk_listener));
69640144a81cSEric Dumazet 		ireq->ireq_family = sk_listener->sk_family;
69655903123fSAkhmat Karakotov 		req->timeout = TCP_TIMEOUT_INIT;
6966e49bb337SEric Dumazet 	}
6967e49bb337SEric Dumazet 
6968e49bb337SEric Dumazet 	return req;
6969e49bb337SEric Dumazet }
6970e49bb337SEric Dumazet EXPORT_SYMBOL(inet_reqsk_alloc);
6971e49bb337SEric Dumazet 
697241d25fe0SEric Dumazet /*
697341d25fe0SEric Dumazet  * Return true if a syncookie should be sent
697441d25fe0SEric Dumazet  */
tcp_syn_flood_action(const struct sock * sk,const char * proto)697596511278SPetar Penkov static bool tcp_syn_flood_action(const struct sock *sk, const char *proto)
697641d25fe0SEric Dumazet {
69778d2675f1SEric Dumazet 	struct request_sock_queue *queue = &inet_csk(sk)->icsk_accept_queue;
697841d25fe0SEric Dumazet 	const char *msg = "Dropping request";
697912ed8244SNikolay Borisov 	struct net *net = sock_net(sk);
6980f2e383b5SKuniyuki Iwashima 	bool want_cookie = false;
6981f2e383b5SKuniyuki Iwashima 	u8 syncookies;
6982f2e383b5SKuniyuki Iwashima 
6983f2e383b5SKuniyuki Iwashima 	syncookies = READ_ONCE(net->ipv4.sysctl_tcp_syncookies);
698441d25fe0SEric Dumazet 
698541d25fe0SEric Dumazet #ifdef CONFIG_SYN_COOKIES
6986f2e383b5SKuniyuki Iwashima 	if (syncookies) {
698741d25fe0SEric Dumazet 		msg = "Sending cookies";
698841d25fe0SEric Dumazet 		want_cookie = true;
698902a1d6e7SEric Dumazet 		__NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPREQQFULLDOCOOKIES);
699041d25fe0SEric Dumazet 	} else
699141d25fe0SEric Dumazet #endif
699202a1d6e7SEric Dumazet 		__NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPREQQFULLDROP);
699341d25fe0SEric Dumazet 
6994bf36267eSEric Dumazet 	if (!READ_ONCE(queue->synflood_warned) && syncookies != 2 &&
6995d9282e48SJamie Bainbridge 	    xchg(&queue->synflood_warned, 1) == 0) {
6996d9282e48SJamie Bainbridge 		if (IS_ENABLED(CONFIG_IPV6) && sk->sk_family == AF_INET6) {
6997d9282e48SJamie Bainbridge 			net_info_ratelimited("%s: Possible SYN flooding on port [%pI6c]:%u. %s.\n",
6998c90b6b10SSaeed Mahameed 					proto, inet6_rcv_saddr(sk),
6999d9282e48SJamie Bainbridge 					sk->sk_num, msg);
7000d9282e48SJamie Bainbridge 		} else {
7001d9282e48SJamie Bainbridge 			net_info_ratelimited("%s: Possible SYN flooding on port %pI4:%u. %s.\n",
7002d9282e48SJamie Bainbridge 					proto, &sk->sk_rcv_saddr,
7003d9282e48SJamie Bainbridge 					sk->sk_num, msg);
7004d9282e48SJamie Bainbridge 		}
7005d9282e48SJamie Bainbridge 	}
70062985aaacSEric Dumazet 
700741d25fe0SEric Dumazet 	return want_cookie;
700841d25fe0SEric Dumazet }
700941d25fe0SEric Dumazet 
tcp_reqsk_record_syn(const struct sock * sk,struct request_sock * req,const struct sk_buff * skb)7010cd8ae852SEric Dumazet static void tcp_reqsk_record_syn(const struct sock *sk,
7011cd8ae852SEric Dumazet 				 struct request_sock *req,
7012cd8ae852SEric Dumazet 				 const struct sk_buff *skb)
7013cd8ae852SEric Dumazet {
7014cd8ae852SEric Dumazet 	if (tcp_sk(sk)->save_syn) {
7015cd8ae852SEric Dumazet 		u32 len = skb_network_header_len(skb) + tcp_hdrlen(skb);
701670a217f1SMartin KaFai Lau 		struct saved_syn *saved_syn;
7017267cf9faSMartin KaFai Lau 		u32 mac_hdrlen;
7018267cf9faSMartin KaFai Lau 		void *base;
7019267cf9faSMartin KaFai Lau 
7020267cf9faSMartin KaFai Lau 		if (tcp_sk(sk)->save_syn == 2) {  /* Save full header. */
7021267cf9faSMartin KaFai Lau 			base = skb_mac_header(skb);
7022267cf9faSMartin KaFai Lau 			mac_hdrlen = skb_mac_header_len(skb);
7023267cf9faSMartin KaFai Lau 			len += mac_hdrlen;
7024267cf9faSMartin KaFai Lau 		} else {
7025267cf9faSMartin KaFai Lau 			base = skb_network_header(skb);
7026267cf9faSMartin KaFai Lau 			mac_hdrlen = 0;
7027267cf9faSMartin KaFai Lau 		}
7028cd8ae852SEric Dumazet 
702970a217f1SMartin KaFai Lau 		saved_syn = kmalloc(struct_size(saved_syn, data, len),
703070a217f1SMartin KaFai Lau 				    GFP_ATOMIC);
703170a217f1SMartin KaFai Lau 		if (saved_syn) {
7032267cf9faSMartin KaFai Lau 			saved_syn->mac_hdrlen = mac_hdrlen;
703370a217f1SMartin KaFai Lau 			saved_syn->network_hdrlen = skb_network_header_len(skb);
703470a217f1SMartin KaFai Lau 			saved_syn->tcp_hdrlen = tcp_hdrlen(skb);
7035267cf9faSMartin KaFai Lau 			memcpy(saved_syn->data, base, len);
703670a217f1SMartin KaFai Lau 			req->saved_syn = saved_syn;
7037cd8ae852SEric Dumazet 		}
7038cd8ae852SEric Dumazet 	}
7039cd8ae852SEric Dumazet }
7040cd8ae852SEric Dumazet 
70419349d600SPetar Penkov /* If a SYN cookie is required and supported, returns a clamped MSS value to be
70429349d600SPetar Penkov  * used for SYN cookie generation.
70439349d600SPetar Penkov  */
tcp_get_syncookie_mss(struct request_sock_ops * rsk_ops,const struct tcp_request_sock_ops * af_ops,struct sock * sk,struct tcphdr * th)70449349d600SPetar Penkov u16 tcp_get_syncookie_mss(struct request_sock_ops *rsk_ops,
70459349d600SPetar Penkov 			  const struct tcp_request_sock_ops *af_ops,
70469349d600SPetar Penkov 			  struct sock *sk, struct tcphdr *th)
70479349d600SPetar Penkov {
70489349d600SPetar Penkov 	struct tcp_sock *tp = tcp_sk(sk);
70499349d600SPetar Penkov 	u16 mss;
70509349d600SPetar Penkov 
7051f2e383b5SKuniyuki Iwashima 	if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_syncookies) != 2 &&
70529349d600SPetar Penkov 	    !inet_csk_reqsk_queue_is_full(sk))
70539349d600SPetar Penkov 		return 0;
70549349d600SPetar Penkov 
70559349d600SPetar Penkov 	if (!tcp_syn_flood_action(sk, rsk_ops->slab_name))
70569349d600SPetar Penkov 		return 0;
70579349d600SPetar Penkov 
70589349d600SPetar Penkov 	if (sk_acceptq_is_full(sk)) {
70599349d600SPetar Penkov 		NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
70609349d600SPetar Penkov 		return 0;
70619349d600SPetar Penkov 	}
70629349d600SPetar Penkov 
70639349d600SPetar Penkov 	mss = tcp_parse_mss_option(th, tp->rx_opt.user_mss);
70649349d600SPetar Penkov 	if (!mss)
70659349d600SPetar Penkov 		mss = af_ops->mss_clamp;
70669349d600SPetar Penkov 
70679349d600SPetar Penkov 	return mss;
70689349d600SPetar Penkov }
70699349d600SPetar Penkov EXPORT_SYMBOL_GPL(tcp_get_syncookie_mss);
70709349d600SPetar Penkov 
tcp_conn_request(struct request_sock_ops * rsk_ops,const struct tcp_request_sock_ops * af_ops,struct sock * sk,struct sk_buff * skb)70711fb6f159SOctavian Purdila int tcp_conn_request(struct request_sock_ops *rsk_ops,
70721fb6f159SOctavian Purdila 		     const struct tcp_request_sock_ops *af_ops,
70731fb6f159SOctavian Purdila 		     struct sock *sk, struct sk_buff *skb)
70741fb6f159SOctavian Purdila {
70751fb6f159SOctavian Purdila 	struct tcp_fastopen_cookie foc = { .len = -1 };
70767c85af88SEric Dumazet 	__u32 isn = TCP_SKB_CB(skb)->tcp_tw_isn;
70777c85af88SEric Dumazet 	struct tcp_options_received tmp_opt;
70787c85af88SEric Dumazet 	struct tcp_sock *tp = tcp_sk(sk);
707912ed8244SNikolay Borisov 	struct net *net = sock_net(sk);
70807c85af88SEric Dumazet 	struct sock *fastopen_sk = NULL;
70817c85af88SEric Dumazet 	struct request_sock *req;
70827c85af88SEric Dumazet 	bool want_cookie = false;
7083eaa72dc4SEric Dumazet 	struct dst_entry *dst;
70847c85af88SEric Dumazet 	struct flowi fl;
7085f2e383b5SKuniyuki Iwashima 	u8 syncookies;
7086f2e383b5SKuniyuki Iwashima 
7087f2e383b5SKuniyuki Iwashima 	syncookies = READ_ONCE(net->ipv4.sysctl_tcp_syncookies);
70881fb6f159SOctavian Purdila 
70891fb6f159SOctavian Purdila 	/* TW buckets are converted to open requests without
70901fb6f159SOctavian Purdila 	 * limitations, they conserve resources and peer is
70911fb6f159SOctavian Purdila 	 * evidently real one.
70921fb6f159SOctavian Purdila 	 */
7093f2e383b5SKuniyuki Iwashima 	if ((syncookies == 2 || inet_csk_reqsk_queue_is_full(sk)) && !isn) {
709496511278SPetar Penkov 		want_cookie = tcp_syn_flood_action(sk, rsk_ops->slab_name);
70951fb6f159SOctavian Purdila 		if (!want_cookie)
70961fb6f159SOctavian Purdila 			goto drop;
70971fb6f159SOctavian Purdila 	}
70981fb6f159SOctavian Purdila 
70995ea8ea2cSEric Dumazet 	if (sk_acceptq_is_full(sk)) {
7100c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
71011fb6f159SOctavian Purdila 		goto drop;
71021fb6f159SOctavian Purdila 	}
71031fb6f159SOctavian Purdila 
7104a1a5344dSEric Dumazet 	req = inet_reqsk_alloc(rsk_ops, sk, !want_cookie);
71051fb6f159SOctavian Purdila 	if (!req)
71061fb6f159SOctavian Purdila 		goto drop;
71071fb6f159SOctavian Purdila 
7108f8ace8d9SFlorian Westphal 	req->syncookie = want_cookie;
71091fb6f159SOctavian Purdila 	tcp_rsk(req)->af_specific = af_ops;
711095a22caeSFlorian Westphal 	tcp_rsk(req)->ts_off = 0;
7111cec37a6eSPeter Krystad #if IS_ENABLED(CONFIG_MPTCP)
7112cec37a6eSPeter Krystad 	tcp_rsk(req)->is_mptcp = 0;
7113cec37a6eSPeter Krystad #endif
71141fb6f159SOctavian Purdila 
71151fb6f159SOctavian Purdila 	tcp_clear_options(&tmp_opt);
71161fb6f159SOctavian Purdila 	tmp_opt.mss_clamp = af_ops->mss_clamp;
71171fb6f159SOctavian Purdila 	tmp_opt.user_mss  = tp->rx_opt.user_mss;
7118eed29f17SEric Dumazet 	tcp_parse_options(sock_net(sk), skb, &tmp_opt, 0,
7119eed29f17SEric Dumazet 			  want_cookie ? NULL : &foc);
71201fb6f159SOctavian Purdila 
71211fb6f159SOctavian Purdila 	if (want_cookie && !tmp_opt.saw_tstamp)
71221fb6f159SOctavian Purdila 		tcp_clear_options(&tmp_opt);
71231fb6f159SOctavian Purdila 
7124bc58a1baSHans Wippel 	if (IS_ENABLED(CONFIG_SMC) && want_cookie)
7125bc58a1baSHans Wippel 		tmp_opt.smc_ok = 0;
7126bc58a1baSHans Wippel 
71271fb6f159SOctavian Purdila 	tmp_opt.tstamp_ok = tmp_opt.saw_tstamp;
71281fb6f159SOctavian Purdila 	tcp_openreq_init(req, &tmp_opt, skb, sk);
71294bd0623fSEric Dumazet 	inet_rsk(req)->no_srccheck = inet_test_bit(TRANSPARENT, sk);
71301fb6f159SOctavian Purdila 
713116f86165SEric Dumazet 	/* Note: tcp_v6_init_req() might override ir_iif for link locals */
71326dd9a14eSDavid Ahern 	inet_rsk(req)->ir_iif = inet_request_bound_dev_if(sk, skb);
713316f86165SEric Dumazet 
71347ea851d1SFlorian Westphal 	dst = af_ops->route_req(sk, skb, &fl, req);
71357ea851d1SFlorian Westphal 	if (!dst)
71361fb6f159SOctavian Purdila 		goto drop_and_free;
71371fb6f159SOctavian Purdila 
713884b114b9SEric Dumazet 	if (tmp_opt.tstamp_ok)
71395d2ed052SEric Dumazet 		tcp_rsk(req)->ts_off = af_ops->init_ts_off(net, skb);
714095a22caeSFlorian Westphal 
7141f7b3bec6SFlorian Westphal 	if (!want_cookie && !isn) {
714279539f34SKuniyuki Iwashima 		int max_syn_backlog = READ_ONCE(net->ipv4.sysctl_max_syn_backlog);
714379539f34SKuniyuki Iwashima 
71441fb6f159SOctavian Purdila 		/* Kill the following clause, if you dislike this way. */
7145f2e383b5SKuniyuki Iwashima 		if (!syncookies &&
714679539f34SKuniyuki Iwashima 		    (max_syn_backlog - inet_csk_reqsk_queue_len(sk) <
714779539f34SKuniyuki Iwashima 		     (max_syn_backlog >> 2)) &&
7148d82bae12SSoheil Hassas Yeganeh 		    !tcp_peer_is_proven(req, dst)) {
71491fb6f159SOctavian Purdila 			/* Without syncookies last quarter of
71501fb6f159SOctavian Purdila 			 * backlog is filled with destinations,
71511fb6f159SOctavian Purdila 			 * proven to be alive.
71521fb6f159SOctavian Purdila 			 * It means that we continue to communicate
71531fb6f159SOctavian Purdila 			 * to destinations, already remembered
71541fb6f159SOctavian Purdila 			 * to the moment of synflood.
71551fb6f159SOctavian Purdila 			 */
71561fb6f159SOctavian Purdila 			pr_drop_req(req, ntohs(tcp_hdr(skb)->source),
71571fb6f159SOctavian Purdila 				    rsk_ops->family);
71581fb6f159SOctavian Purdila 			goto drop_and_release;
71591fb6f159SOctavian Purdila 		}
71601fb6f159SOctavian Purdila 
716184b114b9SEric Dumazet 		isn = af_ops->init_seq(skb);
71621fb6f159SOctavian Purdila 	}
71631fb6f159SOctavian Purdila 
7164f7b3bec6SFlorian Westphal 	tcp_ecn_create_request(req, skb, sk, dst);
7165f7b3bec6SFlorian Westphal 
7166f7b3bec6SFlorian Westphal 	if (want_cookie) {
7167f7b3bec6SFlorian Westphal 		isn = cookie_init_sequence(af_ops, sk, skb, &req->mss);
7168f7b3bec6SFlorian Westphal 		if (!tmp_opt.tstamp_ok)
7169f7b3bec6SFlorian Westphal 			inet_rsk(req)->ecn_ok = 0;
7170f7b3bec6SFlorian Westphal 	}
7171f7b3bec6SFlorian Westphal 
71721fb6f159SOctavian Purdila 	tcp_rsk(req)->snt_isn = isn;
717358d607d3SEric Dumazet 	tcp_rsk(req)->txhash = net_tx_rndhash();
7174e9b12edcSWei Wang 	tcp_rsk(req)->syn_tos = TCP_SKB_CB(skb)->ip_dsfield;
71751fb6f159SOctavian Purdila 	tcp_openreq_init_rwin(req, sk, dst);
7176c6345ce7SAmritha Nambiar 	sk_rx_queue_set(req_to_sk(req), skb);
7177ca6fb065SEric Dumazet 	if (!want_cookie) {
7178ca6fb065SEric Dumazet 		tcp_reqsk_record_syn(sk, req, skb);
717971c02379SChristoph Paasch 		fastopen_sk = tcp_try_fastopen(sk, skb, req, &foc, dst);
7180ca6fb065SEric Dumazet 	}
71817c85af88SEric Dumazet 	if (fastopen_sk) {
7182ca6fb065SEric Dumazet 		af_ops->send_synack(fastopen_sk, dst, &fl, req,
7183331fca43SMartin KaFai Lau 				    &foc, TCP_SYNACK_FASTOPEN, skb);
71847656d842SEric Dumazet 		/* Add the child socket directly into the accept queue */
71859d3e1368SGuillaume Nault 		if (!inet_csk_reqsk_queue_add(sk, req, fastopen_sk)) {
71869d3e1368SGuillaume Nault 			reqsk_fastopen_remove(fastopen_sk, req, false);
71879d3e1368SGuillaume Nault 			bh_unlock_sock(fastopen_sk);
71889d3e1368SGuillaume Nault 			sock_put(fastopen_sk);
71899403cf23SGuillaume Nault 			goto drop_and_free;
71909d3e1368SGuillaume Nault 		}
71917656d842SEric Dumazet 		sk->sk_data_ready(sk);
71927656d842SEric Dumazet 		bh_unlock_sock(fastopen_sk);
71937c85af88SEric Dumazet 		sock_put(fastopen_sk);
71947c85af88SEric Dumazet 	} else {
71959439ce00SEric Dumazet 		tcp_rsk(req)->tfo_listener = false;
71965903123fSAkhmat Karakotov 		if (!want_cookie) {
71975903123fSAkhmat Karakotov 			req->timeout = tcp_timeout_init((struct sock *)req);
7198fdae4d13Sluoxuanqiang 			if (unlikely(!inet_csk_reqsk_queue_hash_add(sk, req,
7199fdae4d13Sluoxuanqiang 								    req->timeout))) {
7200fdae4d13Sluoxuanqiang 				reqsk_free(req);
72012af69905SWang Liang 				dst_release(dst);
7202fdae4d13Sluoxuanqiang 				return 0;
7203fdae4d13Sluoxuanqiang 			}
7204fdae4d13Sluoxuanqiang 
72055903123fSAkhmat Karakotov 		}
7206b3d05147SEric Dumazet 		af_ops->send_synack(sk, dst, &fl, req, &foc,
7207b3d05147SEric Dumazet 				    !want_cookie ? TCP_SYNACK_NORMAL :
7208331fca43SMartin KaFai Lau 						   TCP_SYNACK_COOKIE,
7209331fca43SMartin KaFai Lau 				    skb);
72109caad864SEric Dumazet 		if (want_cookie) {
72119caad864SEric Dumazet 			reqsk_free(req);
72129caad864SEric Dumazet 			return 0;
72139caad864SEric Dumazet 		}
72141fb6f159SOctavian Purdila 	}
7215ca6fb065SEric Dumazet 	reqsk_put(req);
72161fb6f159SOctavian Purdila 	return 0;
72171fb6f159SOctavian Purdila 
72181fb6f159SOctavian Purdila drop_and_release:
72191fb6f159SOctavian Purdila 	dst_release(dst);
72201fb6f159SOctavian Purdila drop_and_free:
72219403cf23SGuillaume Nault 	__reqsk_free(req);
72221fb6f159SOctavian Purdila drop:
72239caad864SEric Dumazet 	tcp_listendrop(sk);
72241fb6f159SOctavian Purdila 	return 0;
72251fb6f159SOctavian Purdila }
72261fb6f159SOctavian Purdila EXPORT_SYMBOL(tcp_conn_request);
7227