xref: /linux/net/ipv4/tcp_input.c (revision d0e1a1b5a833b625c93d3d49847609350ebd79db)
11da177e4SLinus Torvalds /*
21da177e4SLinus Torvalds  * INET		An implementation of the TCP/IP protocol suite for the LINUX
31da177e4SLinus Torvalds  *		operating system.  INET is implemented using the  BSD Socket
41da177e4SLinus Torvalds  *		interface as the means of communication with the user level.
51da177e4SLinus Torvalds  *
61da177e4SLinus Torvalds  *		Implementation of the Transmission Control Protocol(TCP).
71da177e4SLinus Torvalds  *
802c30a84SJesper Juhl  * Authors:	Ross Biro
91da177e4SLinus Torvalds  *		Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
101da177e4SLinus Torvalds  *		Mark Evans, <evansmp@uhura.aston.ac.uk>
111da177e4SLinus Torvalds  *		Corey Minyard <wf-rch!minyard@relay.EU.net>
121da177e4SLinus Torvalds  *		Florian La Roche, <flla@stud.uni-sb.de>
131da177e4SLinus Torvalds  *		Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
141da177e4SLinus Torvalds  *		Linus Torvalds, <torvalds@cs.helsinki.fi>
151da177e4SLinus Torvalds  *		Alan Cox, <gw4pts@gw4pts.ampr.org>
161da177e4SLinus Torvalds  *		Matthew Dillon, <dillon@apollo.west.oic.com>
171da177e4SLinus Torvalds  *		Arnt Gulbrandsen, <agulbra@nvg.unit.no>
181da177e4SLinus Torvalds  *		Jorge Cwik, <jorge@laser.satlink.net>
191da177e4SLinus Torvalds  */
201da177e4SLinus Torvalds 
211da177e4SLinus Torvalds /*
221da177e4SLinus Torvalds  * Changes:
231da177e4SLinus Torvalds  *		Pedro Roque	:	Fast Retransmit/Recovery.
241da177e4SLinus Torvalds  *					Two receive queues.
251da177e4SLinus Torvalds  *					Retransmit queue handled by TCP.
261da177e4SLinus Torvalds  *					Better retransmit timer handling.
271da177e4SLinus Torvalds  *					New congestion avoidance.
281da177e4SLinus Torvalds  *					Header prediction.
291da177e4SLinus Torvalds  *					Variable renaming.
301da177e4SLinus Torvalds  *
311da177e4SLinus Torvalds  *		Eric		:	Fast Retransmit.
321da177e4SLinus Torvalds  *		Randy Scott	:	MSS option defines.
331da177e4SLinus Torvalds  *		Eric Schenk	:	Fixes to slow start algorithm.
341da177e4SLinus Torvalds  *		Eric Schenk	:	Yet another double ACK bug.
351da177e4SLinus Torvalds  *		Eric Schenk	:	Delayed ACK bug fixes.
361da177e4SLinus Torvalds  *		Eric Schenk	:	Floyd style fast retrans war avoidance.
371da177e4SLinus Torvalds  *		David S. Miller	:	Don't allow zero congestion window.
381da177e4SLinus Torvalds  *		Eric Schenk	:	Fix retransmitter so that it sends
391da177e4SLinus Torvalds  *					next packet on ack of previous packet.
401da177e4SLinus Torvalds  *		Andi Kleen	:	Moved open_request checking here
411da177e4SLinus Torvalds  *					and process RSTs for open_requests.
421da177e4SLinus Torvalds  *		Andi Kleen	:	Better prune_queue, and other fixes.
43caa20d9aSStephen Hemminger  *		Andrey Savochkin:	Fix RTT measurements in the presence of
441da177e4SLinus Torvalds  *					timestamps.
451da177e4SLinus Torvalds  *		Andrey Savochkin:	Check sequence numbers correctly when
461da177e4SLinus Torvalds  *					removing SACKs due to in sequence incoming
471da177e4SLinus Torvalds  *					data segments.
481da177e4SLinus Torvalds  *		Andi Kleen:		Make sure we never ack data there is not
491da177e4SLinus Torvalds  *					enough room for. Also make this condition
501da177e4SLinus Torvalds  *					a fatal error if it might still happen.
511da177e4SLinus Torvalds  *		Andi Kleen:		Add tcp_measure_rcv_mss to make
521da177e4SLinus Torvalds  *					connections with MSS<min(MTU,ann. MSS)
531da177e4SLinus Torvalds  *					work without delayed acks.
541da177e4SLinus Torvalds  *		Andi Kleen:		Process packets with PSH set in the
551da177e4SLinus Torvalds  *					fast path.
561da177e4SLinus Torvalds  *		J Hadi Salim:		ECN support
571da177e4SLinus Torvalds  *	 	Andrei Gurtov,
581da177e4SLinus Torvalds  *		Pasi Sarolahti,
591da177e4SLinus Torvalds  *		Panu Kuhlberg:		Experimental audit of TCP (re)transmission
601da177e4SLinus Torvalds  *					engine. Lots of bugs are found.
611da177e4SLinus Torvalds  *		Pasi Sarolahti:		F-RTO for dealing with spurious RTOs
621da177e4SLinus Torvalds  */
631da177e4SLinus Torvalds 
64afd46503SJoe Perches #define pr_fmt(fmt) "TCP: " fmt
65afd46503SJoe Perches 
661da177e4SLinus Torvalds #include <linux/mm.h>
675a0e3ad6STejun Heo #include <linux/slab.h>
681da177e4SLinus Torvalds #include <linux/module.h>
691da177e4SLinus Torvalds #include <linux/sysctl.h>
70a0bffffcSIlpo Järvinen #include <linux/kernel.h>
71ad971f61SEric Dumazet #include <linux/prefetch.h>
725ffc02a1SSatoru SATOH #include <net/dst.h>
731da177e4SLinus Torvalds #include <net/tcp.h>
741da177e4SLinus Torvalds #include <net/inet_common.h>
751da177e4SLinus Torvalds #include <linux/ipsec.h>
761da177e4SLinus Torvalds #include <asm/unaligned.h>
77e1c8a607SWillem de Bruijn #include <linux/errqueue.h>
781da177e4SLinus Torvalds 
79ab32ea5dSBrian Haley int sysctl_tcp_timestamps __read_mostly = 1;
80ab32ea5dSBrian Haley int sysctl_tcp_window_scaling __read_mostly = 1;
81ab32ea5dSBrian Haley int sysctl_tcp_sack __read_mostly = 1;
8294bdc978SYuchung Cheng int sysctl_tcp_fack __read_mostly;
83dca145ffSEric Dumazet int sysctl_tcp_max_reordering __read_mostly = 300;
84ab32ea5dSBrian Haley int sysctl_tcp_dsack __read_mostly = 1;
85ab32ea5dSBrian Haley int sysctl_tcp_app_win __read_mostly = 31;
86b49960a0SEric Dumazet int sysctl_tcp_adv_win_scale __read_mostly = 1;
874bc2f18bSEric Dumazet EXPORT_SYMBOL(sysctl_tcp_adv_win_scale);
881da177e4SLinus Torvalds 
89282f23c6SEric Dumazet /* rfc5961 challenge ack rate limiting */
9075ff39ccSEric Dumazet int sysctl_tcp_challenge_ack_limit = 1000;
91282f23c6SEric Dumazet 
92ab32ea5dSBrian Haley int sysctl_tcp_stdurg __read_mostly;
93ab32ea5dSBrian Haley int sysctl_tcp_rfc1337 __read_mostly;
94ab32ea5dSBrian Haley int sysctl_tcp_max_orphans __read_mostly = NR_FILE;
95c96fd3d4SIlpo Järvinen int sysctl_tcp_frto __read_mostly = 2;
96f6722583SYuchung Cheng int sysctl_tcp_min_rtt_wlen __read_mostly = 300;
97ab32ea5dSBrian Haley int sysctl_tcp_moderate_rcvbuf __read_mostly = 1;
986ba8a3b1SNandita Dukkipati int sysctl_tcp_early_retrans __read_mostly = 3;
99032ee423SNeal Cardwell int sysctl_tcp_invalid_ratelimit __read_mostly = HZ/2;
1001da177e4SLinus Torvalds 
1011da177e4SLinus Torvalds #define FLAG_DATA		0x01 /* Incoming frame contained data.		*/
1021da177e4SLinus Torvalds #define FLAG_WIN_UPDATE		0x02 /* Incoming ACK was a window update.	*/
1031da177e4SLinus Torvalds #define FLAG_DATA_ACKED		0x04 /* This ACK acknowledged new data.		*/
1041da177e4SLinus Torvalds #define FLAG_RETRANS_DATA_ACKED	0x08 /* "" "" some of which was retransmitted.	*/
1051da177e4SLinus Torvalds #define FLAG_SYN_ACKED		0x10 /* This ACK acknowledged SYN.		*/
1061da177e4SLinus Torvalds #define FLAG_DATA_SACKED	0x20 /* New SACK.				*/
1071da177e4SLinus Torvalds #define FLAG_ECE		0x40 /* ECE in this ACK				*/
108291a00d1SYuchung Cheng #define FLAG_LOST_RETRANS	0x80 /* This ACK marks some retransmission lost */
1091da177e4SLinus Torvalds #define FLAG_SLOWPATH		0x100 /* Do not skip RFC checks for window update.*/
110e33099f9SYuchung Cheng #define FLAG_ORIG_SACK_ACKED	0x200 /* Never retransmitted data are (s)acked	*/
1112e605294SIlpo Järvinen #define FLAG_SND_UNA_ADVANCED	0x400 /* Snd_una was changed (!= FLAG_DATA_ACKED) */
112564262c1SRyousei Takano #define FLAG_DSACKING_ACK	0x800 /* SACK blocks contained D-SACK info */
113cadbd031SIlpo Järvinen #define FLAG_SACK_RENEGING	0x2000 /* snd_una advanced to a sacked seq */
11412fb3dd9SEric Dumazet #define FLAG_UPDATE_TS_RECENT	0x4000 /* tcp_replace_ts_recent() */
115*d0e1a1b5SEric Dumazet #define FLAG_NO_CHALLENGE_ACK	0x8000 /* do not call tcp_send_challenge_ack()	*/
1161da177e4SLinus Torvalds 
1171da177e4SLinus Torvalds #define FLAG_ACKED		(FLAG_DATA_ACKED|FLAG_SYN_ACKED)
1181da177e4SLinus Torvalds #define FLAG_NOT_DUP		(FLAG_DATA|FLAG_WIN_UPDATE|FLAG_ACKED)
1191da177e4SLinus Torvalds #define FLAG_CA_ALERT		(FLAG_DATA_SACKED|FLAG_ECE)
1201da177e4SLinus Torvalds #define FLAG_FORWARD_PROGRESS	(FLAG_ACKED|FLAG_DATA_SACKED)
1211da177e4SLinus Torvalds 
1221da177e4SLinus Torvalds #define TCP_REMNANT (TCP_FLAG_FIN|TCP_FLAG_URG|TCP_FLAG_SYN|TCP_FLAG_PSH)
123bdf1ee5dSIlpo Järvinen #define TCP_HP_BITS (~(TCP_RESERVED_BITS|TCP_FLAG_PSH))
1241da177e4SLinus Torvalds 
125e662ca40SYuchung Cheng #define REXMIT_NONE	0 /* no loss recovery to do */
126e662ca40SYuchung Cheng #define REXMIT_LOST	1 /* retransmit packets marked lost */
127e662ca40SYuchung Cheng #define REXMIT_NEW	2 /* FRTO-style transmit of unsent/new packets */
128e662ca40SYuchung Cheng 
1290b9aefeaSMarcelo Ricardo Leitner static void tcp_gro_dev_warn(struct sock *sk, const struct sk_buff *skb,
1300b9aefeaSMarcelo Ricardo Leitner 			     unsigned int len)
131dcb17d22SMarcelo Ricardo Leitner {
132dcb17d22SMarcelo Ricardo Leitner 	static bool __once __read_mostly;
133dcb17d22SMarcelo Ricardo Leitner 
134dcb17d22SMarcelo Ricardo Leitner 	if (!__once) {
135dcb17d22SMarcelo Ricardo Leitner 		struct net_device *dev;
136dcb17d22SMarcelo Ricardo Leitner 
137dcb17d22SMarcelo Ricardo Leitner 		__once = true;
138dcb17d22SMarcelo Ricardo Leitner 
139dcb17d22SMarcelo Ricardo Leitner 		rcu_read_lock();
140dcb17d22SMarcelo Ricardo Leitner 		dev = dev_get_by_index_rcu(sock_net(sk), skb->skb_iif);
1410b9aefeaSMarcelo Ricardo Leitner 		if (!dev || len >= dev->mtu)
142dcb17d22SMarcelo Ricardo Leitner 			pr_warn("%s: Driver has suspect GRO implementation, TCP performance may be compromised.\n",
143dcb17d22SMarcelo Ricardo Leitner 				dev ? dev->name : "Unknown driver");
144dcb17d22SMarcelo Ricardo Leitner 		rcu_read_unlock();
145dcb17d22SMarcelo Ricardo Leitner 	}
146dcb17d22SMarcelo Ricardo Leitner }
147dcb17d22SMarcelo Ricardo Leitner 
1481da177e4SLinus Torvalds /* Adapt the MSS value used to make delayed ack decision to the
1491da177e4SLinus Torvalds  * real world.
1501da177e4SLinus Torvalds  */
151056834d9SIlpo Järvinen static void tcp_measure_rcv_mss(struct sock *sk, const struct sk_buff *skb)
1521da177e4SLinus Torvalds {
153463c84b9SArnaldo Carvalho de Melo 	struct inet_connection_sock *icsk = inet_csk(sk);
154463c84b9SArnaldo Carvalho de Melo 	const unsigned int lss = icsk->icsk_ack.last_seg_size;
155463c84b9SArnaldo Carvalho de Melo 	unsigned int len;
1561da177e4SLinus Torvalds 
157463c84b9SArnaldo Carvalho de Melo 	icsk->icsk_ack.last_seg_size = 0;
1581da177e4SLinus Torvalds 
1591da177e4SLinus Torvalds 	/* skb->len may jitter because of SACKs, even if peer
1601da177e4SLinus Torvalds 	 * sends good full-sized frames.
1611da177e4SLinus Torvalds 	 */
162ff9b5e0fSHerbert Xu 	len = skb_shinfo(skb)->gso_size ? : skb->len;
163463c84b9SArnaldo Carvalho de Melo 	if (len >= icsk->icsk_ack.rcv_mss) {
164dcb17d22SMarcelo Ricardo Leitner 		icsk->icsk_ack.rcv_mss = min_t(unsigned int, len,
165dcb17d22SMarcelo Ricardo Leitner 					       tcp_sk(sk)->advmss);
1660b9aefeaSMarcelo Ricardo Leitner 		/* Account for possibly-removed options */
1670b9aefeaSMarcelo Ricardo Leitner 		if (unlikely(len > icsk->icsk_ack.rcv_mss +
1680b9aefeaSMarcelo Ricardo Leitner 				   MAX_TCP_OPTION_SPACE))
1690b9aefeaSMarcelo Ricardo Leitner 			tcp_gro_dev_warn(sk, skb, len);
1701da177e4SLinus Torvalds 	} else {
1711da177e4SLinus Torvalds 		/* Otherwise, we make more careful check taking into account,
1721da177e4SLinus Torvalds 		 * that SACKs block is variable.
1731da177e4SLinus Torvalds 		 *
1741da177e4SLinus Torvalds 		 * "len" is invariant segment length, including TCP header.
1751da177e4SLinus Torvalds 		 */
1769c70220bSArnaldo Carvalho de Melo 		len += skb->data - skb_transport_header(skb);
177bee7ca9eSWilliam Allen Simpson 		if (len >= TCP_MSS_DEFAULT + sizeof(struct tcphdr) ||
1781da177e4SLinus Torvalds 		    /* If PSH is not set, packet should be
1791da177e4SLinus Torvalds 		     * full sized, provided peer TCP is not badly broken.
1801da177e4SLinus Torvalds 		     * This observation (if it is correct 8)) allows
1811da177e4SLinus Torvalds 		     * to handle super-low mtu links fairly.
1821da177e4SLinus Torvalds 		     */
1831da177e4SLinus Torvalds 		    (len >= TCP_MIN_MSS + sizeof(struct tcphdr) &&
184aa8223c7SArnaldo Carvalho de Melo 		     !(tcp_flag_word(tcp_hdr(skb)) & TCP_REMNANT))) {
1851da177e4SLinus Torvalds 			/* Subtract also invariant (if peer is RFC compliant),
1861da177e4SLinus Torvalds 			 * tcp header plus fixed timestamp option length.
1871da177e4SLinus Torvalds 			 * Resulting "len" is MSS free of SACK jitter.
1881da177e4SLinus Torvalds 			 */
189463c84b9SArnaldo Carvalho de Melo 			len -= tcp_sk(sk)->tcp_header_len;
190463c84b9SArnaldo Carvalho de Melo 			icsk->icsk_ack.last_seg_size = len;
1911da177e4SLinus Torvalds 			if (len == lss) {
192463c84b9SArnaldo Carvalho de Melo 				icsk->icsk_ack.rcv_mss = len;
1931da177e4SLinus Torvalds 				return;
1941da177e4SLinus Torvalds 			}
1951da177e4SLinus Torvalds 		}
1961ef9696cSAlexey Kuznetsov 		if (icsk->icsk_ack.pending & ICSK_ACK_PUSHED)
1971ef9696cSAlexey Kuznetsov 			icsk->icsk_ack.pending |= ICSK_ACK_PUSHED2;
198463c84b9SArnaldo Carvalho de Melo 		icsk->icsk_ack.pending |= ICSK_ACK_PUSHED;
1991da177e4SLinus Torvalds 	}
2001da177e4SLinus Torvalds }
2011da177e4SLinus Torvalds 
202463c84b9SArnaldo Carvalho de Melo static void tcp_incr_quickack(struct sock *sk)
2031da177e4SLinus Torvalds {
204463c84b9SArnaldo Carvalho de Melo 	struct inet_connection_sock *icsk = inet_csk(sk);
20595c96174SEric Dumazet 	unsigned int quickacks = tcp_sk(sk)->rcv_wnd / (2 * icsk->icsk_ack.rcv_mss);
2061da177e4SLinus Torvalds 
2071da177e4SLinus Torvalds 	if (quickacks == 0)
2081da177e4SLinus Torvalds 		quickacks = 2;
209463c84b9SArnaldo Carvalho de Melo 	if (quickacks > icsk->icsk_ack.quick)
210463c84b9SArnaldo Carvalho de Melo 		icsk->icsk_ack.quick = min(quickacks, TCP_MAX_QUICKACKS);
2111da177e4SLinus Torvalds }
2121da177e4SLinus Torvalds 
2131b9f4092Sstephen hemminger static void tcp_enter_quickack_mode(struct sock *sk)
2141da177e4SLinus Torvalds {
215463c84b9SArnaldo Carvalho de Melo 	struct inet_connection_sock *icsk = inet_csk(sk);
216463c84b9SArnaldo Carvalho de Melo 	tcp_incr_quickack(sk);
217463c84b9SArnaldo Carvalho de Melo 	icsk->icsk_ack.pingpong = 0;
218463c84b9SArnaldo Carvalho de Melo 	icsk->icsk_ack.ato = TCP_ATO_MIN;
2191da177e4SLinus Torvalds }
2201da177e4SLinus Torvalds 
2211da177e4SLinus Torvalds /* Send ACKs quickly, if "quick" count is not exhausted
2221da177e4SLinus Torvalds  * and the session is not interactive.
2231da177e4SLinus Torvalds  */
2241da177e4SLinus Torvalds 
2252251ae46SJon Maxwell static bool tcp_in_quickack_mode(struct sock *sk)
2261da177e4SLinus Torvalds {
227463c84b9SArnaldo Carvalho de Melo 	const struct inet_connection_sock *icsk = inet_csk(sk);
2282251ae46SJon Maxwell 	const struct dst_entry *dst = __sk_dst_get(sk);
229a2a385d6SEric Dumazet 
2302251ae46SJon Maxwell 	return (dst && dst_metric(dst, RTAX_QUICKACK)) ||
2312251ae46SJon Maxwell 		(icsk->icsk_ack.quick && !icsk->icsk_ack.pingpong);
2321da177e4SLinus Torvalds }
2331da177e4SLinus Torvalds 
234735d3831SFlorian Westphal static void tcp_ecn_queue_cwr(struct tcp_sock *tp)
235bdf1ee5dSIlpo Järvinen {
236bdf1ee5dSIlpo Järvinen 	if (tp->ecn_flags & TCP_ECN_OK)
237bdf1ee5dSIlpo Järvinen 		tp->ecn_flags |= TCP_ECN_QUEUE_CWR;
238bdf1ee5dSIlpo Järvinen }
239bdf1ee5dSIlpo Järvinen 
240735d3831SFlorian Westphal static void tcp_ecn_accept_cwr(struct tcp_sock *tp, const struct sk_buff *skb)
241bdf1ee5dSIlpo Järvinen {
242bdf1ee5dSIlpo Järvinen 	if (tcp_hdr(skb)->cwr)
243bdf1ee5dSIlpo Järvinen 		tp->ecn_flags &= ~TCP_ECN_DEMAND_CWR;
244bdf1ee5dSIlpo Järvinen }
245bdf1ee5dSIlpo Järvinen 
246735d3831SFlorian Westphal static void tcp_ecn_withdraw_cwr(struct tcp_sock *tp)
247bdf1ee5dSIlpo Järvinen {
248bdf1ee5dSIlpo Järvinen 	tp->ecn_flags &= ~TCP_ECN_DEMAND_CWR;
249bdf1ee5dSIlpo Järvinen }
250bdf1ee5dSIlpo Järvinen 
251735d3831SFlorian Westphal static void __tcp_ecn_check_ce(struct tcp_sock *tp, const struct sk_buff *skb)
252bdf1ee5dSIlpo Järvinen {
253b82d1bb4SEric Dumazet 	switch (TCP_SKB_CB(skb)->ip_dsfield & INET_ECN_MASK) {
2547a269ffaSEric Dumazet 	case INET_ECN_NOT_ECT:
255bdf1ee5dSIlpo Järvinen 		/* Funny extension: if ECT is not set on a segment,
2567a269ffaSEric Dumazet 		 * and we already seen ECT on a previous segment,
2577a269ffaSEric Dumazet 		 * it is probably a retransmit.
2587a269ffaSEric Dumazet 		 */
2597a269ffaSEric Dumazet 		if (tp->ecn_flags & TCP_ECN_SEEN)
260bdf1ee5dSIlpo Järvinen 			tcp_enter_quickack_mode((struct sock *)tp);
2617a269ffaSEric Dumazet 		break;
2627a269ffaSEric Dumazet 	case INET_ECN_CE:
2639890092eSFlorian Westphal 		if (tcp_ca_needs_ecn((struct sock *)tp))
2649890092eSFlorian Westphal 			tcp_ca_event((struct sock *)tp, CA_EVENT_ECN_IS_CE);
2659890092eSFlorian Westphal 
266aae06bf5SEric Dumazet 		if (!(tp->ecn_flags & TCP_ECN_DEMAND_CWR)) {
267aae06bf5SEric Dumazet 			/* Better not delay acks, sender can have a very low cwnd */
268aae06bf5SEric Dumazet 			tcp_enter_quickack_mode((struct sock *)tp);
2697a269ffaSEric Dumazet 			tp->ecn_flags |= TCP_ECN_DEMAND_CWR;
270aae06bf5SEric Dumazet 		}
2717a269ffaSEric Dumazet 		tp->ecn_flags |= TCP_ECN_SEEN;
2729890092eSFlorian Westphal 		break;
2739890092eSFlorian Westphal 	default:
2749890092eSFlorian Westphal 		if (tcp_ca_needs_ecn((struct sock *)tp))
2759890092eSFlorian Westphal 			tcp_ca_event((struct sock *)tp, CA_EVENT_ECN_NO_CE);
2769890092eSFlorian Westphal 		tp->ecn_flags |= TCP_ECN_SEEN;
2779890092eSFlorian Westphal 		break;
278bdf1ee5dSIlpo Järvinen 	}
279bdf1ee5dSIlpo Järvinen }
280bdf1ee5dSIlpo Järvinen 
281735d3831SFlorian Westphal static void tcp_ecn_check_ce(struct tcp_sock *tp, const struct sk_buff *skb)
282735d3831SFlorian Westphal {
283735d3831SFlorian Westphal 	if (tp->ecn_flags & TCP_ECN_OK)
284735d3831SFlorian Westphal 		__tcp_ecn_check_ce(tp, skb);
285735d3831SFlorian Westphal }
286735d3831SFlorian Westphal 
287735d3831SFlorian Westphal static void tcp_ecn_rcv_synack(struct tcp_sock *tp, const struct tcphdr *th)
288bdf1ee5dSIlpo Järvinen {
289bdf1ee5dSIlpo Järvinen 	if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || th->cwr))
290bdf1ee5dSIlpo Järvinen 		tp->ecn_flags &= ~TCP_ECN_OK;
291bdf1ee5dSIlpo Järvinen }
292bdf1ee5dSIlpo Järvinen 
293735d3831SFlorian Westphal static void tcp_ecn_rcv_syn(struct tcp_sock *tp, const struct tcphdr *th)
294bdf1ee5dSIlpo Järvinen {
295bdf1ee5dSIlpo Järvinen 	if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || !th->cwr))
296bdf1ee5dSIlpo Järvinen 		tp->ecn_flags &= ~TCP_ECN_OK;
297bdf1ee5dSIlpo Järvinen }
298bdf1ee5dSIlpo Järvinen 
299735d3831SFlorian Westphal static bool tcp_ecn_rcv_ecn_echo(const struct tcp_sock *tp, const struct tcphdr *th)
300bdf1ee5dSIlpo Järvinen {
301bdf1ee5dSIlpo Järvinen 	if (th->ece && !th->syn && (tp->ecn_flags & TCP_ECN_OK))
302a2a385d6SEric Dumazet 		return true;
303a2a385d6SEric Dumazet 	return false;
304bdf1ee5dSIlpo Järvinen }
305bdf1ee5dSIlpo Järvinen 
3061da177e4SLinus Torvalds /* Buffer size and advertised window tuning.
3071da177e4SLinus Torvalds  *
3081da177e4SLinus Torvalds  * 1. Tuning sk->sk_sndbuf, when connection enters established state.
3091da177e4SLinus Torvalds  */
3101da177e4SLinus Torvalds 
3116ae70532SEric Dumazet static void tcp_sndbuf_expand(struct sock *sk)
3121da177e4SLinus Torvalds {
3136ae70532SEric Dumazet 	const struct tcp_sock *tp = tcp_sk(sk);
31477bfc174SYuchung Cheng 	const struct tcp_congestion_ops *ca_ops = inet_csk(sk)->icsk_ca_ops;
3156ae70532SEric Dumazet 	int sndmem, per_mss;
3166ae70532SEric Dumazet 	u32 nr_segs;
3171da177e4SLinus Torvalds 
3186ae70532SEric Dumazet 	/* Worst case is non GSO/TSO : each frame consumes one skb
3196ae70532SEric Dumazet 	 * and skb->head is kmalloced using power of two area of memory
3206ae70532SEric Dumazet 	 */
3216ae70532SEric Dumazet 	per_mss = max_t(u32, tp->rx_opt.mss_clamp, tp->mss_cache) +
3226ae70532SEric Dumazet 		  MAX_TCP_HEADER +
3236ae70532SEric Dumazet 		  SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
3246ae70532SEric Dumazet 
3256ae70532SEric Dumazet 	per_mss = roundup_pow_of_two(per_mss) +
3266ae70532SEric Dumazet 		  SKB_DATA_ALIGN(sizeof(struct sk_buff));
3276ae70532SEric Dumazet 
3286ae70532SEric Dumazet 	nr_segs = max_t(u32, TCP_INIT_CWND, tp->snd_cwnd);
3296ae70532SEric Dumazet 	nr_segs = max_t(u32, nr_segs, tp->reordering + 1);
3306ae70532SEric Dumazet 
3316ae70532SEric Dumazet 	/* Fast Recovery (RFC 5681 3.2) :
3326ae70532SEric Dumazet 	 * Cubic needs 1.7 factor, rounded to 2 to include
3336ae70532SEric Dumazet 	 * extra cushion (application might react slowly to POLLOUT)
3346ae70532SEric Dumazet 	 */
33577bfc174SYuchung Cheng 	sndmem = ca_ops->sndbuf_expand ? ca_ops->sndbuf_expand(sk) : 2;
33677bfc174SYuchung Cheng 	sndmem *= nr_segs * per_mss;
3376ae70532SEric Dumazet 
33806a59ecbSEric Dumazet 	if (sk->sk_sndbuf < sndmem)
33906a59ecbSEric Dumazet 		sk->sk_sndbuf = min(sndmem, sysctl_tcp_wmem[2]);
3401da177e4SLinus Torvalds }
3411da177e4SLinus Torvalds 
3421da177e4SLinus Torvalds /* 2. Tuning advertised window (window_clamp, rcv_ssthresh)
3431da177e4SLinus Torvalds  *
3441da177e4SLinus Torvalds  * All tcp_full_space() is split to two parts: "network" buffer, allocated
3451da177e4SLinus Torvalds  * forward and advertised in receiver window (tp->rcv_wnd) and
3461da177e4SLinus Torvalds  * "application buffer", required to isolate scheduling/application
3471da177e4SLinus Torvalds  * latencies from network.
3481da177e4SLinus Torvalds  * window_clamp is maximal advertised window. It can be less than
3491da177e4SLinus Torvalds  * tcp_full_space(), in this case tcp_full_space() - window_clamp
3501da177e4SLinus Torvalds  * is reserved for "application" buffer. The less window_clamp is
3511da177e4SLinus Torvalds  * the smoother our behaviour from viewpoint of network, but the lower
3521da177e4SLinus Torvalds  * throughput and the higher sensitivity of the connection to losses. 8)
3531da177e4SLinus Torvalds  *
3541da177e4SLinus Torvalds  * rcv_ssthresh is more strict window_clamp used at "slow start"
3551da177e4SLinus Torvalds  * phase to predict further behaviour of this connection.
3561da177e4SLinus Torvalds  * It is used for two goals:
3571da177e4SLinus Torvalds  * - to enforce header prediction at sender, even when application
3581da177e4SLinus Torvalds  *   requires some significant "application buffer". It is check #1.
3591da177e4SLinus Torvalds  * - to prevent pruning of receive queue because of misprediction
3601da177e4SLinus Torvalds  *   of receiver window. Check #2.
3611da177e4SLinus Torvalds  *
3621da177e4SLinus Torvalds  * The scheme does not work when sender sends good segments opening
363caa20d9aSStephen Hemminger  * window and then starts to feed us spaghetti. But it should work
3641da177e4SLinus Torvalds  * in common situations. Otherwise, we have to rely on queue collapsing.
3651da177e4SLinus Torvalds  */
3661da177e4SLinus Torvalds 
3671da177e4SLinus Torvalds /* Slow part of check#2. */
3689e412ba7SIlpo Järvinen static int __tcp_grow_window(const struct sock *sk, const struct sk_buff *skb)
3691da177e4SLinus Torvalds {
3709e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
3711da177e4SLinus Torvalds 	/* Optimize this! */
372dfd4f0aeSEric Dumazet 	int truesize = tcp_win_from_space(skb->truesize) >> 1;
373dfd4f0aeSEric Dumazet 	int window = tcp_win_from_space(sysctl_tcp_rmem[2]) >> 1;
3741da177e4SLinus Torvalds 
3751da177e4SLinus Torvalds 	while (tp->rcv_ssthresh <= window) {
3761da177e4SLinus Torvalds 		if (truesize <= skb->len)
377463c84b9SArnaldo Carvalho de Melo 			return 2 * inet_csk(sk)->icsk_ack.rcv_mss;
3781da177e4SLinus Torvalds 
3791da177e4SLinus Torvalds 		truesize >>= 1;
3801da177e4SLinus Torvalds 		window >>= 1;
3811da177e4SLinus Torvalds 	}
3821da177e4SLinus Torvalds 	return 0;
3831da177e4SLinus Torvalds }
3841da177e4SLinus Torvalds 
385cf533ea5SEric Dumazet static void tcp_grow_window(struct sock *sk, const struct sk_buff *skb)
3861da177e4SLinus Torvalds {
3879e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
3889e412ba7SIlpo Järvinen 
3891da177e4SLinus Torvalds 	/* Check #1 */
3901da177e4SLinus Torvalds 	if (tp->rcv_ssthresh < tp->window_clamp &&
3911da177e4SLinus Torvalds 	    (int)tp->rcv_ssthresh < tcp_space(sk) &&
392b8da51ebSEric Dumazet 	    !tcp_under_memory_pressure(sk)) {
3931da177e4SLinus Torvalds 		int incr;
3941da177e4SLinus Torvalds 
3951da177e4SLinus Torvalds 		/* Check #2. Increase window, if skb with such overhead
3961da177e4SLinus Torvalds 		 * will fit to rcvbuf in future.
3971da177e4SLinus Torvalds 		 */
3981da177e4SLinus Torvalds 		if (tcp_win_from_space(skb->truesize) <= skb->len)
3991da177e4SLinus Torvalds 			incr = 2 * tp->advmss;
4001da177e4SLinus Torvalds 		else
4019e412ba7SIlpo Järvinen 			incr = __tcp_grow_window(sk, skb);
4021da177e4SLinus Torvalds 
4031da177e4SLinus Torvalds 		if (incr) {
4044d846f02SEric Dumazet 			incr = max_t(int, incr, 2 * skb->len);
405056834d9SIlpo Järvinen 			tp->rcv_ssthresh = min(tp->rcv_ssthresh + incr,
406056834d9SIlpo Järvinen 					       tp->window_clamp);
407463c84b9SArnaldo Carvalho de Melo 			inet_csk(sk)->icsk_ack.quick |= 1;
4081da177e4SLinus Torvalds 		}
4091da177e4SLinus Torvalds 	}
4101da177e4SLinus Torvalds }
4111da177e4SLinus Torvalds 
4121da177e4SLinus Torvalds /* 3. Tuning rcvbuf, when connection enters established state. */
4131da177e4SLinus Torvalds static void tcp_fixup_rcvbuf(struct sock *sk)
4141da177e4SLinus Torvalds {
415e9266a02SEric Dumazet 	u32 mss = tcp_sk(sk)->advmss;
416e9266a02SEric Dumazet 	int rcvmem;
4171da177e4SLinus Torvalds 
41885f16525SYuchung Cheng 	rcvmem = 2 * SKB_TRUESIZE(mss + MAX_TCP_HEADER) *
41985f16525SYuchung Cheng 		 tcp_default_init_rwnd(mss);
420e9266a02SEric Dumazet 
421b0983d3cSEric Dumazet 	/* Dynamic Right Sizing (DRS) has 2 to 3 RTT latency
422b0983d3cSEric Dumazet 	 * Allow enough cushion so that sender is not limited by our window
423b0983d3cSEric Dumazet 	 */
424b0983d3cSEric Dumazet 	if (sysctl_tcp_moderate_rcvbuf)
425b0983d3cSEric Dumazet 		rcvmem <<= 2;
426b0983d3cSEric Dumazet 
427e9266a02SEric Dumazet 	if (sk->sk_rcvbuf < rcvmem)
428e9266a02SEric Dumazet 		sk->sk_rcvbuf = min(rcvmem, sysctl_tcp_rmem[2]);
4291da177e4SLinus Torvalds }
4301da177e4SLinus Torvalds 
431caa20d9aSStephen Hemminger /* 4. Try to fixup all. It is made immediately after connection enters
4321da177e4SLinus Torvalds  *    established state.
4331da177e4SLinus Torvalds  */
43410467163SJerry Chu void tcp_init_buffer_space(struct sock *sk)
4351da177e4SLinus Torvalds {
4361da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
4371da177e4SLinus Torvalds 	int maxwin;
4381da177e4SLinus Torvalds 
4391da177e4SLinus Torvalds 	if (!(sk->sk_userlocks & SOCK_RCVBUF_LOCK))
4401da177e4SLinus Torvalds 		tcp_fixup_rcvbuf(sk);
4411da177e4SLinus Torvalds 	if (!(sk->sk_userlocks & SOCK_SNDBUF_LOCK))
4426ae70532SEric Dumazet 		tcp_sndbuf_expand(sk);
4431da177e4SLinus Torvalds 
4441da177e4SLinus Torvalds 	tp->rcvq_space.space = tp->rcv_wnd;
4459a568de4SEric Dumazet 	tcp_mstamp_refresh(tp);
446645f4c6fSEric Dumazet 	tp->rcvq_space.time = tp->tcp_mstamp;
447b0983d3cSEric Dumazet 	tp->rcvq_space.seq = tp->copied_seq;
4481da177e4SLinus Torvalds 
4491da177e4SLinus Torvalds 	maxwin = tcp_full_space(sk);
4501da177e4SLinus Torvalds 
4511da177e4SLinus Torvalds 	if (tp->window_clamp >= maxwin) {
4521da177e4SLinus Torvalds 		tp->window_clamp = maxwin;
4531da177e4SLinus Torvalds 
4541da177e4SLinus Torvalds 		if (sysctl_tcp_app_win && maxwin > 4 * tp->advmss)
4551da177e4SLinus Torvalds 			tp->window_clamp = max(maxwin -
4561da177e4SLinus Torvalds 					       (maxwin >> sysctl_tcp_app_win),
4571da177e4SLinus Torvalds 					       4 * tp->advmss);
4581da177e4SLinus Torvalds 	}
4591da177e4SLinus Torvalds 
4601da177e4SLinus Torvalds 	/* Force reservation of one segment. */
4611da177e4SLinus Torvalds 	if (sysctl_tcp_app_win &&
4621da177e4SLinus Torvalds 	    tp->window_clamp > 2 * tp->advmss &&
4631da177e4SLinus Torvalds 	    tp->window_clamp + tp->advmss > maxwin)
4641da177e4SLinus Torvalds 		tp->window_clamp = max(2 * tp->advmss, maxwin - tp->advmss);
4651da177e4SLinus Torvalds 
4661da177e4SLinus Torvalds 	tp->rcv_ssthresh = min(tp->rcv_ssthresh, tp->window_clamp);
467c2203cf7SEric Dumazet 	tp->snd_cwnd_stamp = tcp_jiffies32;
4681da177e4SLinus Torvalds }
4691da177e4SLinus Torvalds 
4701da177e4SLinus Torvalds /* 5. Recalculate window clamp after socket hit its memory bounds. */
4719e412ba7SIlpo Järvinen static void tcp_clamp_window(struct sock *sk)
4721da177e4SLinus Torvalds {
4739e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
4746687e988SArnaldo Carvalho de Melo 	struct inet_connection_sock *icsk = inet_csk(sk);
4751da177e4SLinus Torvalds 
4766687e988SArnaldo Carvalho de Melo 	icsk->icsk_ack.quick = 0;
4771da177e4SLinus Torvalds 
4781da177e4SLinus Torvalds 	if (sk->sk_rcvbuf < sysctl_tcp_rmem[2] &&
4791da177e4SLinus Torvalds 	    !(sk->sk_userlocks & SOCK_RCVBUF_LOCK) &&
480b8da51ebSEric Dumazet 	    !tcp_under_memory_pressure(sk) &&
481180d8cd9SGlauber Costa 	    sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0)) {
4821da177e4SLinus Torvalds 		sk->sk_rcvbuf = min(atomic_read(&sk->sk_rmem_alloc),
4831da177e4SLinus Torvalds 				    sysctl_tcp_rmem[2]);
4841da177e4SLinus Torvalds 	}
485326f36e9SJohn Heffner 	if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf)
4861da177e4SLinus Torvalds 		tp->rcv_ssthresh = min(tp->window_clamp, 2U * tp->advmss);
4871da177e4SLinus Torvalds }
4881da177e4SLinus Torvalds 
48940efc6faSStephen Hemminger /* Initialize RCV_MSS value.
49040efc6faSStephen Hemminger  * RCV_MSS is an our guess about MSS used by the peer.
49140efc6faSStephen Hemminger  * We haven't any direct information about the MSS.
49240efc6faSStephen Hemminger  * It's better to underestimate the RCV_MSS rather than overestimate.
49340efc6faSStephen Hemminger  * Overestimations make us ACKing less frequently than needed.
49440efc6faSStephen Hemminger  * Underestimations are more easy to detect and fix by tcp_measure_rcv_mss().
49540efc6faSStephen Hemminger  */
49640efc6faSStephen Hemminger void tcp_initialize_rcv_mss(struct sock *sk)
49740efc6faSStephen Hemminger {
498cf533ea5SEric Dumazet 	const struct tcp_sock *tp = tcp_sk(sk);
49940efc6faSStephen Hemminger 	unsigned int hint = min_t(unsigned int, tp->advmss, tp->mss_cache);
50040efc6faSStephen Hemminger 
50140efc6faSStephen Hemminger 	hint = min(hint, tp->rcv_wnd / 2);
502bee7ca9eSWilliam Allen Simpson 	hint = min(hint, TCP_MSS_DEFAULT);
50340efc6faSStephen Hemminger 	hint = max(hint, TCP_MIN_MSS);
50440efc6faSStephen Hemminger 
50540efc6faSStephen Hemminger 	inet_csk(sk)->icsk_ack.rcv_mss = hint;
50640efc6faSStephen Hemminger }
5074bc2f18bSEric Dumazet EXPORT_SYMBOL(tcp_initialize_rcv_mss);
50840efc6faSStephen Hemminger 
5091da177e4SLinus Torvalds /* Receiver "autotuning" code.
5101da177e4SLinus Torvalds  *
5111da177e4SLinus Torvalds  * The algorithm for RTT estimation w/o timestamps is based on
5121da177e4SLinus Torvalds  * Dynamic Right-Sizing (DRS) by Wu Feng and Mike Fisk of LANL.
513631dd1a8SJustin P. Mattock  * <http://public.lanl.gov/radiant/pubs.html#DRS>
5141da177e4SLinus Torvalds  *
5151da177e4SLinus Torvalds  * More detail on this code can be found at
516631dd1a8SJustin P. Mattock  * <http://staff.psc.edu/jheffner/>,
5171da177e4SLinus Torvalds  * though this reference is out of date.  A new paper
5181da177e4SLinus Torvalds  * is pending.
5191da177e4SLinus Torvalds  */
5201da177e4SLinus Torvalds static void tcp_rcv_rtt_update(struct tcp_sock *tp, u32 sample, int win_dep)
5211da177e4SLinus Torvalds {
522645f4c6fSEric Dumazet 	u32 new_sample = tp->rcv_rtt_est.rtt_us;
5231da177e4SLinus Torvalds 	long m = sample;
5241da177e4SLinus Torvalds 
5251da177e4SLinus Torvalds 	if (m == 0)
5261da177e4SLinus Torvalds 		m = 1;
5271da177e4SLinus Torvalds 
5281da177e4SLinus Torvalds 	if (new_sample != 0) {
5291da177e4SLinus Torvalds 		/* If we sample in larger samples in the non-timestamp
5301da177e4SLinus Torvalds 		 * case, we could grossly overestimate the RTT especially
5311da177e4SLinus Torvalds 		 * with chatty applications or bulk transfer apps which
5321da177e4SLinus Torvalds 		 * are stalled on filesystem I/O.
5331da177e4SLinus Torvalds 		 *
5341da177e4SLinus Torvalds 		 * Also, since we are only going for a minimum in the
53531f34269SStephen Hemminger 		 * non-timestamp case, we do not smooth things out
536caa20d9aSStephen Hemminger 		 * else with timestamps disabled convergence takes too
5371da177e4SLinus Torvalds 		 * long.
5381da177e4SLinus Torvalds 		 */
5391da177e4SLinus Torvalds 		if (!win_dep) {
5401da177e4SLinus Torvalds 			m -= (new_sample >> 3);
5411da177e4SLinus Torvalds 			new_sample += m;
54218a223e0SNeal Cardwell 		} else {
54318a223e0SNeal Cardwell 			m <<= 3;
54418a223e0SNeal Cardwell 			if (m < new_sample)
54518a223e0SNeal Cardwell 				new_sample = m;
54618a223e0SNeal Cardwell 		}
5471da177e4SLinus Torvalds 	} else {
548caa20d9aSStephen Hemminger 		/* No previous measure. */
5491da177e4SLinus Torvalds 		new_sample = m << 3;
5501da177e4SLinus Torvalds 	}
5511da177e4SLinus Torvalds 
552645f4c6fSEric Dumazet 	tp->rcv_rtt_est.rtt_us = new_sample;
5531da177e4SLinus Torvalds }
5541da177e4SLinus Torvalds 
5551da177e4SLinus Torvalds static inline void tcp_rcv_rtt_measure(struct tcp_sock *tp)
5561da177e4SLinus Torvalds {
557645f4c6fSEric Dumazet 	u32 delta_us;
558645f4c6fSEric Dumazet 
5599a568de4SEric Dumazet 	if (tp->rcv_rtt_est.time == 0)
5601da177e4SLinus Torvalds 		goto new_measure;
5611da177e4SLinus Torvalds 	if (before(tp->rcv_nxt, tp->rcv_rtt_est.seq))
5621da177e4SLinus Torvalds 		return;
5639a568de4SEric Dumazet 	delta_us = tcp_stamp_us_delta(tp->tcp_mstamp, tp->rcv_rtt_est.time);
564645f4c6fSEric Dumazet 	tcp_rcv_rtt_update(tp, delta_us, 1);
5651da177e4SLinus Torvalds 
5661da177e4SLinus Torvalds new_measure:
5671da177e4SLinus Torvalds 	tp->rcv_rtt_est.seq = tp->rcv_nxt + tp->rcv_wnd;
568645f4c6fSEric Dumazet 	tp->rcv_rtt_est.time = tp->tcp_mstamp;
5691da177e4SLinus Torvalds }
5701da177e4SLinus Torvalds 
571056834d9SIlpo Järvinen static inline void tcp_rcv_rtt_measure_ts(struct sock *sk,
572056834d9SIlpo Järvinen 					  const struct sk_buff *skb)
5731da177e4SLinus Torvalds {
574463c84b9SArnaldo Carvalho de Melo 	struct tcp_sock *tp = tcp_sk(sk);
5759a568de4SEric Dumazet 
5761da177e4SLinus Torvalds 	if (tp->rx_opt.rcv_tsecr &&
5771da177e4SLinus Torvalds 	    (TCP_SKB_CB(skb)->end_seq -
5789a568de4SEric Dumazet 	     TCP_SKB_CB(skb)->seq >= inet_csk(sk)->icsk_ack.rcv_mss)) {
5799a568de4SEric Dumazet 		u32 delta = tcp_time_stamp(tp) - tp->rx_opt.rcv_tsecr;
5809a568de4SEric Dumazet 		u32 delta_us = delta * (USEC_PER_SEC / TCP_TS_HZ);
5819a568de4SEric Dumazet 
5829a568de4SEric Dumazet 		tcp_rcv_rtt_update(tp, delta_us, 0);
5839a568de4SEric Dumazet 	}
5841da177e4SLinus Torvalds }
5851da177e4SLinus Torvalds 
5861da177e4SLinus Torvalds /*
5871da177e4SLinus Torvalds  * This function should be called every time data is copied to user space.
5881da177e4SLinus Torvalds  * It calculates the appropriate TCP receive buffer space.
5891da177e4SLinus Torvalds  */
5901da177e4SLinus Torvalds void tcp_rcv_space_adjust(struct sock *sk)
5911da177e4SLinus Torvalds {
5921da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
5931da177e4SLinus Torvalds 	int time;
594b0983d3cSEric Dumazet 	int copied;
5951da177e4SLinus Torvalds 
5969a568de4SEric Dumazet 	time = tcp_stamp_us_delta(tp->tcp_mstamp, tp->rcvq_space.time);
597645f4c6fSEric Dumazet 	if (time < (tp->rcv_rtt_est.rtt_us >> 3) || tp->rcv_rtt_est.rtt_us == 0)
5981da177e4SLinus Torvalds 		return;
5991da177e4SLinus Torvalds 
600b0983d3cSEric Dumazet 	/* Number of bytes copied to user in last RTT */
601b0983d3cSEric Dumazet 	copied = tp->copied_seq - tp->rcvq_space.seq;
602b0983d3cSEric Dumazet 	if (copied <= tp->rcvq_space.space)
603b0983d3cSEric Dumazet 		goto new_measure;
6041da177e4SLinus Torvalds 
605b0983d3cSEric Dumazet 	/* A bit of theory :
606b0983d3cSEric Dumazet 	 * copied = bytes received in previous RTT, our base window
607b0983d3cSEric Dumazet 	 * To cope with packet losses, we need a 2x factor
608b0983d3cSEric Dumazet 	 * To cope with slow start, and sender growing its cwin by 100 %
609b0983d3cSEric Dumazet 	 * every RTT, we need a 4x factor, because the ACK we are sending
610b0983d3cSEric Dumazet 	 * now is for the next RTT, not the current one :
611b0983d3cSEric Dumazet 	 * <prev RTT . ><current RTT .. ><next RTT .... >
612b0983d3cSEric Dumazet 	 */
6131da177e4SLinus Torvalds 
6146fcf9412SJohn Heffner 	if (sysctl_tcp_moderate_rcvbuf &&
6156fcf9412SJohn Heffner 	    !(sk->sk_userlocks & SOCK_RCVBUF_LOCK)) {
616b0983d3cSEric Dumazet 		int rcvwin, rcvmem, rcvbuf;
6171da177e4SLinus Torvalds 
618b0983d3cSEric Dumazet 		/* minimal window to cope with packet losses, assuming
619b0983d3cSEric Dumazet 		 * steady state. Add some cushion because of small variations.
6201da177e4SLinus Torvalds 		 */
621b0983d3cSEric Dumazet 		rcvwin = (copied << 1) + 16 * tp->advmss;
622b0983d3cSEric Dumazet 
623b0983d3cSEric Dumazet 		/* If rate increased by 25%,
624b0983d3cSEric Dumazet 		 *	assume slow start, rcvwin = 3 * copied
625b0983d3cSEric Dumazet 		 * If rate increased by 50%,
626b0983d3cSEric Dumazet 		 *	assume sender can use 2x growth, rcvwin = 4 * copied
627b0983d3cSEric Dumazet 		 */
628b0983d3cSEric Dumazet 		if (copied >=
629b0983d3cSEric Dumazet 		    tp->rcvq_space.space + (tp->rcvq_space.space >> 2)) {
630b0983d3cSEric Dumazet 			if (copied >=
631b0983d3cSEric Dumazet 			    tp->rcvq_space.space + (tp->rcvq_space.space >> 1))
632b0983d3cSEric Dumazet 				rcvwin <<= 1;
633b0983d3cSEric Dumazet 			else
634b0983d3cSEric Dumazet 				rcvwin += (rcvwin >> 1);
635b0983d3cSEric Dumazet 		}
636b0983d3cSEric Dumazet 
63787fb4b7bSEric Dumazet 		rcvmem = SKB_TRUESIZE(tp->advmss + MAX_TCP_HEADER);
6381da177e4SLinus Torvalds 		while (tcp_win_from_space(rcvmem) < tp->advmss)
6391da177e4SLinus Torvalds 			rcvmem += 128;
640b0983d3cSEric Dumazet 
641b0983d3cSEric Dumazet 		rcvbuf = min(rcvwin / tp->advmss * rcvmem, sysctl_tcp_rmem[2]);
642b0983d3cSEric Dumazet 		if (rcvbuf > sk->sk_rcvbuf) {
643b0983d3cSEric Dumazet 			sk->sk_rcvbuf = rcvbuf;
6441da177e4SLinus Torvalds 
6451da177e4SLinus Torvalds 			/* Make the window clamp follow along.  */
646b0983d3cSEric Dumazet 			tp->window_clamp = rcvwin;
6471da177e4SLinus Torvalds 		}
6481da177e4SLinus Torvalds 	}
649b0983d3cSEric Dumazet 	tp->rcvq_space.space = copied;
6501da177e4SLinus Torvalds 
6511da177e4SLinus Torvalds new_measure:
6521da177e4SLinus Torvalds 	tp->rcvq_space.seq = tp->copied_seq;
653645f4c6fSEric Dumazet 	tp->rcvq_space.time = tp->tcp_mstamp;
6541da177e4SLinus Torvalds }
6551da177e4SLinus Torvalds 
6561da177e4SLinus Torvalds /* There is something which you must keep in mind when you analyze the
6571da177e4SLinus Torvalds  * behavior of the tp->ato delayed ack timeout interval.  When a
6581da177e4SLinus Torvalds  * connection starts up, we want to ack as quickly as possible.  The
6591da177e4SLinus Torvalds  * problem is that "good" TCP's do slow start at the beginning of data
6601da177e4SLinus Torvalds  * transmission.  The means that until we send the first few ACK's the
6611da177e4SLinus Torvalds  * sender will sit on his end and only queue most of his data, because
6621da177e4SLinus Torvalds  * he can only send snd_cwnd unacked packets at any given time.  For
6631da177e4SLinus Torvalds  * each ACK we send, he increments snd_cwnd and transmits more of his
6641da177e4SLinus Torvalds  * queue.  -DaveM
6651da177e4SLinus Torvalds  */
6669e412ba7SIlpo Järvinen static void tcp_event_data_recv(struct sock *sk, struct sk_buff *skb)
6671da177e4SLinus Torvalds {
6689e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
669463c84b9SArnaldo Carvalho de Melo 	struct inet_connection_sock *icsk = inet_csk(sk);
6701da177e4SLinus Torvalds 	u32 now;
6711da177e4SLinus Torvalds 
672463c84b9SArnaldo Carvalho de Melo 	inet_csk_schedule_ack(sk);
6731da177e4SLinus Torvalds 
674463c84b9SArnaldo Carvalho de Melo 	tcp_measure_rcv_mss(sk, skb);
6751da177e4SLinus Torvalds 
6761da177e4SLinus Torvalds 	tcp_rcv_rtt_measure(tp);
6771da177e4SLinus Torvalds 
67870eabf0eSEric Dumazet 	now = tcp_jiffies32;
6791da177e4SLinus Torvalds 
680463c84b9SArnaldo Carvalho de Melo 	if (!icsk->icsk_ack.ato) {
6811da177e4SLinus Torvalds 		/* The _first_ data packet received, initialize
6821da177e4SLinus Torvalds 		 * delayed ACK engine.
6831da177e4SLinus Torvalds 		 */
684463c84b9SArnaldo Carvalho de Melo 		tcp_incr_quickack(sk);
685463c84b9SArnaldo Carvalho de Melo 		icsk->icsk_ack.ato = TCP_ATO_MIN;
6861da177e4SLinus Torvalds 	} else {
687463c84b9SArnaldo Carvalho de Melo 		int m = now - icsk->icsk_ack.lrcvtime;
6881da177e4SLinus Torvalds 
6891da177e4SLinus Torvalds 		if (m <= TCP_ATO_MIN / 2) {
6901da177e4SLinus Torvalds 			/* The fastest case is the first. */
691463c84b9SArnaldo Carvalho de Melo 			icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + TCP_ATO_MIN / 2;
692463c84b9SArnaldo Carvalho de Melo 		} else if (m < icsk->icsk_ack.ato) {
693463c84b9SArnaldo Carvalho de Melo 			icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + m;
694463c84b9SArnaldo Carvalho de Melo 			if (icsk->icsk_ack.ato > icsk->icsk_rto)
695463c84b9SArnaldo Carvalho de Melo 				icsk->icsk_ack.ato = icsk->icsk_rto;
696463c84b9SArnaldo Carvalho de Melo 		} else if (m > icsk->icsk_rto) {
697caa20d9aSStephen Hemminger 			/* Too long gap. Apparently sender failed to
6981da177e4SLinus Torvalds 			 * restart window, so that we send ACKs quickly.
6991da177e4SLinus Torvalds 			 */
700463c84b9SArnaldo Carvalho de Melo 			tcp_incr_quickack(sk);
7013ab224beSHideo Aoki 			sk_mem_reclaim(sk);
7021da177e4SLinus Torvalds 		}
7031da177e4SLinus Torvalds 	}
704463c84b9SArnaldo Carvalho de Melo 	icsk->icsk_ack.lrcvtime = now;
7051da177e4SLinus Torvalds 
706735d3831SFlorian Westphal 	tcp_ecn_check_ce(tp, skb);
7071da177e4SLinus Torvalds 
7081da177e4SLinus Torvalds 	if (skb->len >= 128)
7099e412ba7SIlpo Järvinen 		tcp_grow_window(sk, skb);
7101da177e4SLinus Torvalds }
7111da177e4SLinus Torvalds 
7121da177e4SLinus Torvalds /* Called to compute a smoothed rtt estimate. The data fed to this
7131da177e4SLinus Torvalds  * routine either comes from timestamps, or from segments that were
7141da177e4SLinus Torvalds  * known _not_ to have been retransmitted [see Karn/Partridge
7151da177e4SLinus Torvalds  * Proceedings SIGCOMM 87]. The algorithm is from the SIGCOMM 88
7161da177e4SLinus Torvalds  * piece by Van Jacobson.
7171da177e4SLinus Torvalds  * NOTE: the next three routines used to be one big routine.
7181da177e4SLinus Torvalds  * To save cycles in the RFC 1323 implementation it was better to break
7191da177e4SLinus Torvalds  * it up into three procedures. -- erics
7201da177e4SLinus Torvalds  */
721740b0f18SEric Dumazet static void tcp_rtt_estimator(struct sock *sk, long mrtt_us)
7221da177e4SLinus Torvalds {
7236687e988SArnaldo Carvalho de Melo 	struct tcp_sock *tp = tcp_sk(sk);
724740b0f18SEric Dumazet 	long m = mrtt_us; /* RTT */
725740b0f18SEric Dumazet 	u32 srtt = tp->srtt_us;
7261da177e4SLinus Torvalds 
7271da177e4SLinus Torvalds 	/*	The following amusing code comes from Jacobson's
7281da177e4SLinus Torvalds 	 *	article in SIGCOMM '88.  Note that rtt and mdev
7291da177e4SLinus Torvalds 	 *	are scaled versions of rtt and mean deviation.
7301da177e4SLinus Torvalds 	 *	This is designed to be as fast as possible
7311da177e4SLinus Torvalds 	 *	m stands for "measurement".
7321da177e4SLinus Torvalds 	 *
7331da177e4SLinus Torvalds 	 *	On a 1990 paper the rto value is changed to:
7341da177e4SLinus Torvalds 	 *	RTO = rtt + 4 * mdev
7351da177e4SLinus Torvalds 	 *
7361da177e4SLinus Torvalds 	 * Funny. This algorithm seems to be very broken.
7371da177e4SLinus Torvalds 	 * These formulae increase RTO, when it should be decreased, increase
73831f34269SStephen Hemminger 	 * too slowly, when it should be increased quickly, decrease too quickly
7391da177e4SLinus Torvalds 	 * etc. I guess in BSD RTO takes ONE value, so that it is absolutely
7401da177e4SLinus Torvalds 	 * does not matter how to _calculate_ it. Seems, it was trap
7411da177e4SLinus Torvalds 	 * that VJ failed to avoid. 8)
7421da177e4SLinus Torvalds 	 */
7434a5ab4e2SEric Dumazet 	if (srtt != 0) {
7444a5ab4e2SEric Dumazet 		m -= (srtt >> 3);	/* m is now error in rtt est */
7454a5ab4e2SEric Dumazet 		srtt += m;		/* rtt = 7/8 rtt + 1/8 new */
7461da177e4SLinus Torvalds 		if (m < 0) {
7471da177e4SLinus Torvalds 			m = -m;		/* m is now abs(error) */
748740b0f18SEric Dumazet 			m -= (tp->mdev_us >> 2);   /* similar update on mdev */
7491da177e4SLinus Torvalds 			/* This is similar to one of Eifel findings.
7501da177e4SLinus Torvalds 			 * Eifel blocks mdev updates when rtt decreases.
7511da177e4SLinus Torvalds 			 * This solution is a bit different: we use finer gain
7521da177e4SLinus Torvalds 			 * for mdev in this case (alpha*beta).
7531da177e4SLinus Torvalds 			 * Like Eifel it also prevents growth of rto,
7541da177e4SLinus Torvalds 			 * but also it limits too fast rto decreases,
7551da177e4SLinus Torvalds 			 * happening in pure Eifel.
7561da177e4SLinus Torvalds 			 */
7571da177e4SLinus Torvalds 			if (m > 0)
7581da177e4SLinus Torvalds 				m >>= 3;
7591da177e4SLinus Torvalds 		} else {
760740b0f18SEric Dumazet 			m -= (tp->mdev_us >> 2);   /* similar update on mdev */
7611da177e4SLinus Torvalds 		}
762740b0f18SEric Dumazet 		tp->mdev_us += m;		/* mdev = 3/4 mdev + 1/4 new */
763740b0f18SEric Dumazet 		if (tp->mdev_us > tp->mdev_max_us) {
764740b0f18SEric Dumazet 			tp->mdev_max_us = tp->mdev_us;
765740b0f18SEric Dumazet 			if (tp->mdev_max_us > tp->rttvar_us)
766740b0f18SEric Dumazet 				tp->rttvar_us = tp->mdev_max_us;
7671da177e4SLinus Torvalds 		}
7681da177e4SLinus Torvalds 		if (after(tp->snd_una, tp->rtt_seq)) {
769740b0f18SEric Dumazet 			if (tp->mdev_max_us < tp->rttvar_us)
770740b0f18SEric Dumazet 				tp->rttvar_us -= (tp->rttvar_us - tp->mdev_max_us) >> 2;
7711da177e4SLinus Torvalds 			tp->rtt_seq = tp->snd_nxt;
772740b0f18SEric Dumazet 			tp->mdev_max_us = tcp_rto_min_us(sk);
7731da177e4SLinus Torvalds 		}
7741da177e4SLinus Torvalds 	} else {
7751da177e4SLinus Torvalds 		/* no previous measure. */
7764a5ab4e2SEric Dumazet 		srtt = m << 3;		/* take the measured time to be rtt */
777740b0f18SEric Dumazet 		tp->mdev_us = m << 1;	/* make sure rto = 3*rtt */
778740b0f18SEric Dumazet 		tp->rttvar_us = max(tp->mdev_us, tcp_rto_min_us(sk));
779740b0f18SEric Dumazet 		tp->mdev_max_us = tp->rttvar_us;
7801da177e4SLinus Torvalds 		tp->rtt_seq = tp->snd_nxt;
7811da177e4SLinus Torvalds 	}
782740b0f18SEric Dumazet 	tp->srtt_us = max(1U, srtt);
7831da177e4SLinus Torvalds }
7841da177e4SLinus Torvalds 
78595bd09ebSEric Dumazet /* Set the sk_pacing_rate to allow proper sizing of TSO packets.
78695bd09ebSEric Dumazet  * Note: TCP stack does not yet implement pacing.
78795bd09ebSEric Dumazet  * FQ packet scheduler can be used to implement cheap but effective
78895bd09ebSEric Dumazet  * TCP pacing, to smooth the burst on large writes when packets
78995bd09ebSEric Dumazet  * in flight is significantly lower than cwnd (or rwin)
79095bd09ebSEric Dumazet  */
79143e122b0SEric Dumazet int sysctl_tcp_pacing_ss_ratio __read_mostly = 200;
79243e122b0SEric Dumazet int sysctl_tcp_pacing_ca_ratio __read_mostly = 120;
79343e122b0SEric Dumazet 
79495bd09ebSEric Dumazet static void tcp_update_pacing_rate(struct sock *sk)
79595bd09ebSEric Dumazet {
79695bd09ebSEric Dumazet 	const struct tcp_sock *tp = tcp_sk(sk);
79795bd09ebSEric Dumazet 	u64 rate;
79895bd09ebSEric Dumazet 
79995bd09ebSEric Dumazet 	/* set sk_pacing_rate to 200 % of current rate (mss * cwnd / srtt) */
80043e122b0SEric Dumazet 	rate = (u64)tp->mss_cache * ((USEC_PER_SEC / 100) << 3);
80143e122b0SEric Dumazet 
80243e122b0SEric Dumazet 	/* current rate is (cwnd * mss) / srtt
80343e122b0SEric Dumazet 	 * In Slow Start [1], set sk_pacing_rate to 200 % the current rate.
80443e122b0SEric Dumazet 	 * In Congestion Avoidance phase, set it to 120 % the current rate.
80543e122b0SEric Dumazet 	 *
80643e122b0SEric Dumazet 	 * [1] : Normal Slow Start condition is (tp->snd_cwnd < tp->snd_ssthresh)
80743e122b0SEric Dumazet 	 *	 If snd_cwnd >= (tp->snd_ssthresh / 2), we are approaching
80843e122b0SEric Dumazet 	 *	 end of slow start and should slow down.
80943e122b0SEric Dumazet 	 */
81043e122b0SEric Dumazet 	if (tp->snd_cwnd < tp->snd_ssthresh / 2)
81143e122b0SEric Dumazet 		rate *= sysctl_tcp_pacing_ss_ratio;
81243e122b0SEric Dumazet 	else
81343e122b0SEric Dumazet 		rate *= sysctl_tcp_pacing_ca_ratio;
81495bd09ebSEric Dumazet 
81595bd09ebSEric Dumazet 	rate *= max(tp->snd_cwnd, tp->packets_out);
81695bd09ebSEric Dumazet 
817740b0f18SEric Dumazet 	if (likely(tp->srtt_us))
818740b0f18SEric Dumazet 		do_div(rate, tp->srtt_us);
81995bd09ebSEric Dumazet 
820ba537427SEric Dumazet 	/* ACCESS_ONCE() is needed because sch_fq fetches sk_pacing_rate
821ba537427SEric Dumazet 	 * without any lock. We want to make sure compiler wont store
822ba537427SEric Dumazet 	 * intermediate values in this location.
823ba537427SEric Dumazet 	 */
824ba537427SEric Dumazet 	ACCESS_ONCE(sk->sk_pacing_rate) = min_t(u64, rate,
825ba537427SEric Dumazet 						sk->sk_max_pacing_rate);
82695bd09ebSEric Dumazet }
82795bd09ebSEric Dumazet 
8281da177e4SLinus Torvalds /* Calculate rto without backoff.  This is the second half of Van Jacobson's
8291da177e4SLinus Torvalds  * routine referred to above.
8301da177e4SLinus Torvalds  */
831f7e56a76Sstephen hemminger static void tcp_set_rto(struct sock *sk)
8321da177e4SLinus Torvalds {
833463c84b9SArnaldo Carvalho de Melo 	const struct tcp_sock *tp = tcp_sk(sk);
8341da177e4SLinus Torvalds 	/* Old crap is replaced with new one. 8)
8351da177e4SLinus Torvalds 	 *
8361da177e4SLinus Torvalds 	 * More seriously:
8371da177e4SLinus Torvalds 	 * 1. If rtt variance happened to be less 50msec, it is hallucination.
8381da177e4SLinus Torvalds 	 *    It cannot be less due to utterly erratic ACK generation made
8391da177e4SLinus Torvalds 	 *    at least by solaris and freebsd. "Erratic ACKs" has _nothing_
8401da177e4SLinus Torvalds 	 *    to do with delayed acks, because at cwnd>2 true delack timeout
8411da177e4SLinus Torvalds 	 *    is invisible. Actually, Linux-2.4 also generates erratic
842caa20d9aSStephen Hemminger 	 *    ACKs in some circumstances.
8431da177e4SLinus Torvalds 	 */
844f1ecd5d9SDamian Lukowski 	inet_csk(sk)->icsk_rto = __tcp_set_rto(tp);
8451da177e4SLinus Torvalds 
8461da177e4SLinus Torvalds 	/* 2. Fixups made earlier cannot be right.
8471da177e4SLinus Torvalds 	 *    If we do not estimate RTO correctly without them,
8481da177e4SLinus Torvalds 	 *    all the algo is pure shit and should be replaced
849caa20d9aSStephen Hemminger 	 *    with correct one. It is exactly, which we pretend to do.
8501da177e4SLinus Torvalds 	 */
8511da177e4SLinus Torvalds 
8521da177e4SLinus Torvalds 	/* NOTE: clamping at TCP_RTO_MIN is not required, current algo
8531da177e4SLinus Torvalds 	 * guarantees that rto is higher.
8541da177e4SLinus Torvalds 	 */
855f1ecd5d9SDamian Lukowski 	tcp_bound_rto(sk);
8561da177e4SLinus Torvalds }
8571da177e4SLinus Torvalds 
858cf533ea5SEric Dumazet __u32 tcp_init_cwnd(const struct tcp_sock *tp, const struct dst_entry *dst)
8591da177e4SLinus Torvalds {
8601da177e4SLinus Torvalds 	__u32 cwnd = (dst ? dst_metric(dst, RTAX_INITCWND) : 0);
8611da177e4SLinus Torvalds 
86222b71c8fSGerrit Renker 	if (!cwnd)
863442b9635SDavid S. Miller 		cwnd = TCP_INIT_CWND;
8641da177e4SLinus Torvalds 	return min_t(__u32, cwnd, tp->snd_cwnd_clamp);
8651da177e4SLinus Torvalds }
8661da177e4SLinus Torvalds 
867e60402d0SIlpo Järvinen /*
868e60402d0SIlpo Järvinen  * Packet counting of FACK is based on in-order assumptions, therefore TCP
869e60402d0SIlpo Järvinen  * disables it when reordering is detected
870e60402d0SIlpo Järvinen  */
8714aabd8efSDavid S. Miller void tcp_disable_fack(struct tcp_sock *tp)
872e60402d0SIlpo Järvinen {
87385cc391cSIlpo Järvinen 	/* RFC3517 uses different metric in lost marker => reset on change */
87485cc391cSIlpo Järvinen 	if (tcp_is_fack(tp))
87585cc391cSIlpo Järvinen 		tp->lost_skb_hint = NULL;
876ab56222aSVijay Subramanian 	tp->rx_opt.sack_ok &= ~TCP_FACK_ENABLED;
877e60402d0SIlpo Järvinen }
878e60402d0SIlpo Järvinen 
879564262c1SRyousei Takano /* Take a notice that peer is sending D-SACKs */
880e60402d0SIlpo Järvinen static void tcp_dsack_seen(struct tcp_sock *tp)
881e60402d0SIlpo Järvinen {
882ab56222aSVijay Subramanian 	tp->rx_opt.sack_ok |= TCP_DSACK_SEEN;
883e60402d0SIlpo Järvinen }
884e60402d0SIlpo Järvinen 
8856687e988SArnaldo Carvalho de Melo static void tcp_update_reordering(struct sock *sk, const int metric,
8866687e988SArnaldo Carvalho de Melo 				  const int ts)
8871da177e4SLinus Torvalds {
8886687e988SArnaldo Carvalho de Melo 	struct tcp_sock *tp = tcp_sk(sk);
88940b215e5SPavel Emelyanov 	int mib_idx;
89040b215e5SPavel Emelyanov 
8916f5b24eeSSoheil Hassas Yeganeh 	if (WARN_ON_ONCE(metric < 0))
8926f5b24eeSSoheil Hassas Yeganeh 		return;
8936f5b24eeSSoheil Hassas Yeganeh 
8942d2517eeSYuchung Cheng 	if (metric > tp->reordering) {
895dca145ffSEric Dumazet 		tp->reordering = min(sysctl_tcp_max_reordering, metric);
8961da177e4SLinus Torvalds 
8971da177e4SLinus Torvalds #if FASTRETRANS_DEBUG > 1
89891df42beSJoe Perches 		pr_debug("Disorder%d %d %u f%u s%u rr%d\n",
8996687e988SArnaldo Carvalho de Melo 			 tp->rx_opt.sack_ok, inet_csk(sk)->icsk_ca_state,
9001da177e4SLinus Torvalds 			 tp->reordering,
9011da177e4SLinus Torvalds 			 tp->fackets_out,
9021da177e4SLinus Torvalds 			 tp->sacked_out,
9031da177e4SLinus Torvalds 			 tp->undo_marker ? tp->undo_retrans : 0);
9041da177e4SLinus Torvalds #endif
905e60402d0SIlpo Järvinen 		tcp_disable_fack(tp);
9061da177e4SLinus Torvalds 	}
907eed530b6SYuchung Cheng 
9084f41b1c5SYuchung Cheng 	tp->rack.reord = 1;
9092d2517eeSYuchung Cheng 
9102d2517eeSYuchung Cheng 	/* This exciting event is worth to be remembered. 8) */
9112d2517eeSYuchung Cheng 	if (ts)
9122d2517eeSYuchung Cheng 		mib_idx = LINUX_MIB_TCPTSREORDER;
9132d2517eeSYuchung Cheng 	else if (tcp_is_reno(tp))
9142d2517eeSYuchung Cheng 		mib_idx = LINUX_MIB_TCPRENOREORDER;
9152d2517eeSYuchung Cheng 	else if (tcp_is_fack(tp))
9162d2517eeSYuchung Cheng 		mib_idx = LINUX_MIB_TCPFACKREORDER;
9172d2517eeSYuchung Cheng 	else
9182d2517eeSYuchung Cheng 		mib_idx = LINUX_MIB_TCPSACKREORDER;
9192d2517eeSYuchung Cheng 
9202d2517eeSYuchung Cheng 	NET_INC_STATS(sock_net(sk), mib_idx);
9211da177e4SLinus Torvalds }
9221da177e4SLinus Torvalds 
923006f582cSIlpo Järvinen /* This must be called before lost_out is incremented */
924c8c213f2SIlpo Järvinen static void tcp_verify_retransmit_hint(struct tcp_sock *tp, struct sk_buff *skb)
925c8c213f2SIlpo Järvinen {
92651456b29SIan Morris 	if (!tp->retransmit_skb_hint ||
927c8c213f2SIlpo Järvinen 	    before(TCP_SKB_CB(skb)->seq,
928c8c213f2SIlpo Järvinen 		   TCP_SKB_CB(tp->retransmit_skb_hint)->seq))
929006f582cSIlpo Järvinen 		tp->retransmit_skb_hint = skb;
930c8c213f2SIlpo Järvinen }
931c8c213f2SIlpo Järvinen 
9320682e690SNeal Cardwell /* Sum the number of packets on the wire we have marked as lost.
9330682e690SNeal Cardwell  * There are two cases we care about here:
9340682e690SNeal Cardwell  * a) Packet hasn't been marked lost (nor retransmitted),
9350682e690SNeal Cardwell  *    and this is the first loss.
9360682e690SNeal Cardwell  * b) Packet has been marked both lost and retransmitted,
9370682e690SNeal Cardwell  *    and this means we think it was lost again.
9380682e690SNeal Cardwell  */
9390682e690SNeal Cardwell static void tcp_sum_lost(struct tcp_sock *tp, struct sk_buff *skb)
9400682e690SNeal Cardwell {
9410682e690SNeal Cardwell 	__u8 sacked = TCP_SKB_CB(skb)->sacked;
9420682e690SNeal Cardwell 
9430682e690SNeal Cardwell 	if (!(sacked & TCPCB_LOST) ||
9440682e690SNeal Cardwell 	    ((sacked & TCPCB_LOST) && (sacked & TCPCB_SACKED_RETRANS)))
9450682e690SNeal Cardwell 		tp->lost += tcp_skb_pcount(skb);
9460682e690SNeal Cardwell }
9470682e690SNeal Cardwell 
94841ea36e3SIlpo Järvinen static void tcp_skb_mark_lost(struct tcp_sock *tp, struct sk_buff *skb)
94941ea36e3SIlpo Järvinen {
95041ea36e3SIlpo Järvinen 	if (!(TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_ACKED))) {
95141ea36e3SIlpo Järvinen 		tcp_verify_retransmit_hint(tp, skb);
95241ea36e3SIlpo Järvinen 
95341ea36e3SIlpo Järvinen 		tp->lost_out += tcp_skb_pcount(skb);
9540682e690SNeal Cardwell 		tcp_sum_lost(tp, skb);
95541ea36e3SIlpo Järvinen 		TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
95641ea36e3SIlpo Järvinen 	}
95741ea36e3SIlpo Järvinen }
95841ea36e3SIlpo Järvinen 
9594f41b1c5SYuchung Cheng void tcp_skb_mark_lost_uncond_verify(struct tcp_sock *tp, struct sk_buff *skb)
960006f582cSIlpo Järvinen {
961006f582cSIlpo Järvinen 	tcp_verify_retransmit_hint(tp, skb);
962006f582cSIlpo Järvinen 
9630682e690SNeal Cardwell 	tcp_sum_lost(tp, skb);
964006f582cSIlpo Järvinen 	if (!(TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_ACKED))) {
965006f582cSIlpo Järvinen 		tp->lost_out += tcp_skb_pcount(skb);
966006f582cSIlpo Järvinen 		TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
967006f582cSIlpo Järvinen 	}
968006f582cSIlpo Järvinen }
969006f582cSIlpo Järvinen 
9701da177e4SLinus Torvalds /* This procedure tags the retransmission queue when SACKs arrive.
9711da177e4SLinus Torvalds  *
9721da177e4SLinus Torvalds  * We have three tag bits: SACKED(S), RETRANS(R) and LOST(L).
9731da177e4SLinus Torvalds  * Packets in queue with these bits set are counted in variables
9741da177e4SLinus Torvalds  * sacked_out, retrans_out and lost_out, correspondingly.
9751da177e4SLinus Torvalds  *
9761da177e4SLinus Torvalds  * Valid combinations are:
9771da177e4SLinus Torvalds  * Tag  InFlight	Description
9781da177e4SLinus Torvalds  * 0	1		- orig segment is in flight.
9791da177e4SLinus Torvalds  * S	0		- nothing flies, orig reached receiver.
9801da177e4SLinus Torvalds  * L	0		- nothing flies, orig lost by net.
9811da177e4SLinus Torvalds  * R	2		- both orig and retransmit are in flight.
9821da177e4SLinus Torvalds  * L|R	1		- orig is lost, retransmit is in flight.
9831da177e4SLinus Torvalds  * S|R  1		- orig reached receiver, retrans is still in flight.
9841da177e4SLinus Torvalds  * (L|S|R is logically valid, it could occur when L|R is sacked,
9851da177e4SLinus Torvalds  *  but it is equivalent to plain S and code short-curcuits it to S.
9861da177e4SLinus Torvalds  *  L|S is logically invalid, it would mean -1 packet in flight 8))
9871da177e4SLinus Torvalds  *
9881da177e4SLinus Torvalds  * These 6 states form finite state machine, controlled by the following events:
9891da177e4SLinus Torvalds  * 1. New ACK (+SACK) arrives. (tcp_sacktag_write_queue())
9901da177e4SLinus Torvalds  * 2. Retransmission. (tcp_retransmit_skb(), tcp_xmit_retransmit_queue())
991974c1236SYuchung Cheng  * 3. Loss detection event of two flavors:
9921da177e4SLinus Torvalds  *	A. Scoreboard estimator decided the packet is lost.
9931da177e4SLinus Torvalds  *	   A'. Reno "three dupacks" marks head of queue lost.
994974c1236SYuchung Cheng  *	   A''. Its FACK modification, head until snd.fack is lost.
995974c1236SYuchung Cheng  *	B. SACK arrives sacking SND.NXT at the moment, when the
9961da177e4SLinus Torvalds  *	   segment was retransmitted.
9971da177e4SLinus Torvalds  * 4. D-SACK added new rule: D-SACK changes any tag to S.
9981da177e4SLinus Torvalds  *
9991da177e4SLinus Torvalds  * It is pleasant to note, that state diagram turns out to be commutative,
10001da177e4SLinus Torvalds  * so that we are allowed not to be bothered by order of our actions,
10011da177e4SLinus Torvalds  * when multiple events arrive simultaneously. (see the function below).
10021da177e4SLinus Torvalds  *
10031da177e4SLinus Torvalds  * Reordering detection.
10041da177e4SLinus Torvalds  * --------------------
10051da177e4SLinus Torvalds  * Reordering metric is maximal distance, which a packet can be displaced
10061da177e4SLinus Torvalds  * in packet stream. With SACKs we can estimate it:
10071da177e4SLinus Torvalds  *
10081da177e4SLinus Torvalds  * 1. SACK fills old hole and the corresponding segment was not
10091da177e4SLinus Torvalds  *    ever retransmitted -> reordering. Alas, we cannot use it
10101da177e4SLinus Torvalds  *    when segment was retransmitted.
10111da177e4SLinus Torvalds  * 2. The last flaw is solved with D-SACK. D-SACK arrives
10121da177e4SLinus Torvalds  *    for retransmitted and already SACKed segment -> reordering..
10131da177e4SLinus Torvalds  * Both of these heuristics are not used in Loss state, when we cannot
10141da177e4SLinus Torvalds  * account for retransmits accurately.
10155b3c9882SIlpo Järvinen  *
10165b3c9882SIlpo Järvinen  * SACK block validation.
10175b3c9882SIlpo Järvinen  * ----------------------
10185b3c9882SIlpo Järvinen  *
10195b3c9882SIlpo Järvinen  * SACK block range validation checks that the received SACK block fits to
10205b3c9882SIlpo Järvinen  * the expected sequence limits, i.e., it is between SND.UNA and SND.NXT.
10215b3c9882SIlpo Järvinen  * Note that SND.UNA is not included to the range though being valid because
10220e835331SIlpo Järvinen  * it means that the receiver is rather inconsistent with itself reporting
10230e835331SIlpo Järvinen  * SACK reneging when it should advance SND.UNA. Such SACK block this is
10240e835331SIlpo Järvinen  * perfectly valid, however, in light of RFC2018 which explicitly states
10250e835331SIlpo Järvinen  * that "SACK block MUST reflect the newest segment.  Even if the newest
10260e835331SIlpo Järvinen  * segment is going to be discarded ...", not that it looks very clever
10270e835331SIlpo Järvinen  * in case of head skb. Due to potentional receiver driven attacks, we
10280e835331SIlpo Järvinen  * choose to avoid immediate execution of a walk in write queue due to
10290e835331SIlpo Järvinen  * reneging and defer head skb's loss recovery to standard loss recovery
10300e835331SIlpo Järvinen  * procedure that will eventually trigger (nothing forbids us doing this).
10315b3c9882SIlpo Järvinen  *
10325b3c9882SIlpo Järvinen  * Implements also blockage to start_seq wrap-around. Problem lies in the
10335b3c9882SIlpo Järvinen  * fact that though start_seq (s) is before end_seq (i.e., not reversed),
10345b3c9882SIlpo Järvinen  * there's no guarantee that it will be before snd_nxt (n). The problem
10355b3c9882SIlpo Järvinen  * happens when start_seq resides between end_seq wrap (e_w) and snd_nxt
10365b3c9882SIlpo Järvinen  * wrap (s_w):
10375b3c9882SIlpo Järvinen  *
10385b3c9882SIlpo Järvinen  *         <- outs wnd ->                          <- wrapzone ->
10395b3c9882SIlpo Järvinen  *         u     e      n                         u_w   e_w  s n_w
10405b3c9882SIlpo Järvinen  *         |     |      |                          |     |   |  |
10415b3c9882SIlpo Järvinen  * |<------------+------+----- TCP seqno space --------------+---------->|
10425b3c9882SIlpo Järvinen  * ...-- <2^31 ->|                                           |<--------...
10435b3c9882SIlpo Järvinen  * ...---- >2^31 ------>|                                    |<--------...
10445b3c9882SIlpo Järvinen  *
10455b3c9882SIlpo Järvinen  * Current code wouldn't be vulnerable but it's better still to discard such
10465b3c9882SIlpo Järvinen  * crazy SACK blocks. Doing this check for start_seq alone closes somewhat
10475b3c9882SIlpo Järvinen  * similar case (end_seq after snd_nxt wrap) as earlier reversed check in
10485b3c9882SIlpo Järvinen  * snd_nxt wrap -> snd_una region will then become "well defined", i.e.,
10495b3c9882SIlpo Järvinen  * equal to the ideal case (infinite seqno space without wrap caused issues).
10505b3c9882SIlpo Järvinen  *
10515b3c9882SIlpo Järvinen  * With D-SACK the lower bound is extended to cover sequence space below
10525b3c9882SIlpo Järvinen  * SND.UNA down to undo_marker, which is the last point of interest. Yet
1053564262c1SRyousei Takano  * again, D-SACK block must not to go across snd_una (for the same reason as
10545b3c9882SIlpo Järvinen  * for the normal SACK blocks, explained above). But there all simplicity
10555b3c9882SIlpo Järvinen  * ends, TCP might receive valid D-SACKs below that. As long as they reside
10565b3c9882SIlpo Järvinen  * fully below undo_marker they do not affect behavior in anyway and can
10575b3c9882SIlpo Järvinen  * therefore be safely ignored. In rare cases (which are more or less
10585b3c9882SIlpo Järvinen  * theoretical ones), the D-SACK will nicely cross that boundary due to skb
10595b3c9882SIlpo Järvinen  * fragmentation and packet reordering past skb's retransmission. To consider
10605b3c9882SIlpo Järvinen  * them correctly, the acceptable range must be extended even more though
10615b3c9882SIlpo Järvinen  * the exact amount is rather hard to quantify. However, tp->max_window can
10625b3c9882SIlpo Järvinen  * be used as an exaggerated estimate.
10631da177e4SLinus Torvalds  */
1064a2a385d6SEric Dumazet static bool tcp_is_sackblock_valid(struct tcp_sock *tp, bool is_dsack,
10655b3c9882SIlpo Järvinen 				   u32 start_seq, u32 end_seq)
10665b3c9882SIlpo Järvinen {
10675b3c9882SIlpo Järvinen 	/* Too far in future, or reversed (interpretation is ambiguous) */
10685b3c9882SIlpo Järvinen 	if (after(end_seq, tp->snd_nxt) || !before(start_seq, end_seq))
1069a2a385d6SEric Dumazet 		return false;
10705b3c9882SIlpo Järvinen 
10715b3c9882SIlpo Järvinen 	/* Nasty start_seq wrap-around check (see comments above) */
10725b3c9882SIlpo Järvinen 	if (!before(start_seq, tp->snd_nxt))
1073a2a385d6SEric Dumazet 		return false;
10745b3c9882SIlpo Järvinen 
1075564262c1SRyousei Takano 	/* In outstanding window? ...This is valid exit for D-SACKs too.
10765b3c9882SIlpo Järvinen 	 * start_seq == snd_una is non-sensical (see comments above)
10775b3c9882SIlpo Järvinen 	 */
10785b3c9882SIlpo Järvinen 	if (after(start_seq, tp->snd_una))
1079a2a385d6SEric Dumazet 		return true;
10805b3c9882SIlpo Järvinen 
10815b3c9882SIlpo Järvinen 	if (!is_dsack || !tp->undo_marker)
1082a2a385d6SEric Dumazet 		return false;
10835b3c9882SIlpo Järvinen 
10845b3c9882SIlpo Järvinen 	/* ...Then it's D-SACK, and must reside below snd_una completely */
1085f779b2d6SZheng Yan 	if (after(end_seq, tp->snd_una))
1086a2a385d6SEric Dumazet 		return false;
10875b3c9882SIlpo Järvinen 
10885b3c9882SIlpo Järvinen 	if (!before(start_seq, tp->undo_marker))
1089a2a385d6SEric Dumazet 		return true;
10905b3c9882SIlpo Järvinen 
10915b3c9882SIlpo Järvinen 	/* Too old */
10925b3c9882SIlpo Järvinen 	if (!after(end_seq, tp->undo_marker))
1093a2a385d6SEric Dumazet 		return false;
10945b3c9882SIlpo Järvinen 
10955b3c9882SIlpo Järvinen 	/* Undo_marker boundary crossing (overestimates a lot). Known already:
10965b3c9882SIlpo Järvinen 	 *   start_seq < undo_marker and end_seq >= undo_marker.
10975b3c9882SIlpo Järvinen 	 */
10985b3c9882SIlpo Järvinen 	return !before(start_seq, end_seq - tp->max_window);
10995b3c9882SIlpo Järvinen }
11005b3c9882SIlpo Järvinen 
1101a2a385d6SEric Dumazet static bool tcp_check_dsack(struct sock *sk, const struct sk_buff *ack_skb,
1102d06e021dSDavid S. Miller 			    struct tcp_sack_block_wire *sp, int num_sacks,
1103d06e021dSDavid S. Miller 			    u32 prior_snd_una)
1104d06e021dSDavid S. Miller {
11051ed83465SPavel Emelyanov 	struct tcp_sock *tp = tcp_sk(sk);
1106d3e2ce3bSHarvey Harrison 	u32 start_seq_0 = get_unaligned_be32(&sp[0].start_seq);
1107d3e2ce3bSHarvey Harrison 	u32 end_seq_0 = get_unaligned_be32(&sp[0].end_seq);
1108a2a385d6SEric Dumazet 	bool dup_sack = false;
1109d06e021dSDavid S. Miller 
1110d06e021dSDavid S. Miller 	if (before(start_seq_0, TCP_SKB_CB(ack_skb)->ack_seq)) {
1111a2a385d6SEric Dumazet 		dup_sack = true;
1112e60402d0SIlpo Järvinen 		tcp_dsack_seen(tp);
1113c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKRECV);
1114d06e021dSDavid S. Miller 	} else if (num_sacks > 1) {
1115d3e2ce3bSHarvey Harrison 		u32 end_seq_1 = get_unaligned_be32(&sp[1].end_seq);
1116d3e2ce3bSHarvey Harrison 		u32 start_seq_1 = get_unaligned_be32(&sp[1].start_seq);
1117d06e021dSDavid S. Miller 
1118d06e021dSDavid S. Miller 		if (!after(end_seq_0, end_seq_1) &&
1119d06e021dSDavid S. Miller 		    !before(start_seq_0, start_seq_1)) {
1120a2a385d6SEric Dumazet 			dup_sack = true;
1121e60402d0SIlpo Järvinen 			tcp_dsack_seen(tp);
1122c10d9310SEric Dumazet 			NET_INC_STATS(sock_net(sk),
1123de0744afSPavel Emelyanov 					LINUX_MIB_TCPDSACKOFORECV);
1124d06e021dSDavid S. Miller 		}
1125d06e021dSDavid S. Miller 	}
1126d06e021dSDavid S. Miller 
1127d06e021dSDavid S. Miller 	/* D-SACK for already forgotten data... Do dumb counting. */
11286e08d5e3SYuchung Cheng 	if (dup_sack && tp->undo_marker && tp->undo_retrans > 0 &&
1129d06e021dSDavid S. Miller 	    !after(end_seq_0, prior_snd_una) &&
1130d06e021dSDavid S. Miller 	    after(end_seq_0, tp->undo_marker))
1131d06e021dSDavid S. Miller 		tp->undo_retrans--;
1132d06e021dSDavid S. Miller 
1133d06e021dSDavid S. Miller 	return dup_sack;
1134d06e021dSDavid S. Miller }
1135d06e021dSDavid S. Miller 
1136a1197f5aSIlpo Järvinen struct tcp_sacktag_state {
1137a1197f5aSIlpo Järvinen 	int	reord;
1138a1197f5aSIlpo Järvinen 	int	fack_count;
113931231a8aSKenneth Klette Jonassen 	/* Timestamps for earliest and latest never-retransmitted segment
114031231a8aSKenneth Klette Jonassen 	 * that was SACKed. RTO needs the earliest RTT to stay conservative,
114131231a8aSKenneth Klette Jonassen 	 * but congestion control should still get an accurate delay signal.
114231231a8aSKenneth Klette Jonassen 	 */
11439a568de4SEric Dumazet 	u64	first_sackt;
11449a568de4SEric Dumazet 	u64	last_sackt;
1145b9f64820SYuchung Cheng 	struct rate_sample *rate;
1146a1197f5aSIlpo Järvinen 	int	flag;
1147a1197f5aSIlpo Järvinen };
1148a1197f5aSIlpo Järvinen 
1149d1935942SIlpo Järvinen /* Check if skb is fully within the SACK block. In presence of GSO skbs,
1150d1935942SIlpo Järvinen  * the incoming SACK may not exactly match but we can find smaller MSS
1151d1935942SIlpo Järvinen  * aligned portion of it that matches. Therefore we might need to fragment
1152d1935942SIlpo Järvinen  * which may fail and creates some hassle (caller must handle error case
1153d1935942SIlpo Järvinen  * returns).
1154832d11c5SIlpo Järvinen  *
1155832d11c5SIlpo Järvinen  * FIXME: this could be merged to shift decision code
1156d1935942SIlpo Järvinen  */
11570f79efdcSAdrian Bunk static int tcp_match_skb_to_sack(struct sock *sk, struct sk_buff *skb,
1158d1935942SIlpo Järvinen 				  u32 start_seq, u32 end_seq)
1159d1935942SIlpo Järvinen {
1160a2a385d6SEric Dumazet 	int err;
1161a2a385d6SEric Dumazet 	bool in_sack;
1162d1935942SIlpo Järvinen 	unsigned int pkt_len;
1163adb92db8SIlpo Järvinen 	unsigned int mss;
1164d1935942SIlpo Järvinen 
1165d1935942SIlpo Järvinen 	in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
1166d1935942SIlpo Järvinen 		  !before(end_seq, TCP_SKB_CB(skb)->end_seq);
1167d1935942SIlpo Järvinen 
1168d1935942SIlpo Järvinen 	if (tcp_skb_pcount(skb) > 1 && !in_sack &&
1169d1935942SIlpo Järvinen 	    after(TCP_SKB_CB(skb)->end_seq, start_seq)) {
1170adb92db8SIlpo Järvinen 		mss = tcp_skb_mss(skb);
1171d1935942SIlpo Järvinen 		in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq);
1172d1935942SIlpo Järvinen 
1173adb92db8SIlpo Järvinen 		if (!in_sack) {
1174d1935942SIlpo Järvinen 			pkt_len = start_seq - TCP_SKB_CB(skb)->seq;
1175adb92db8SIlpo Järvinen 			if (pkt_len < mss)
1176adb92db8SIlpo Järvinen 				pkt_len = mss;
1177adb92db8SIlpo Järvinen 		} else {
1178d1935942SIlpo Järvinen 			pkt_len = end_seq - TCP_SKB_CB(skb)->seq;
1179adb92db8SIlpo Järvinen 			if (pkt_len < mss)
1180adb92db8SIlpo Järvinen 				return -EINVAL;
1181adb92db8SIlpo Järvinen 		}
1182adb92db8SIlpo Järvinen 
1183adb92db8SIlpo Järvinen 		/* Round if necessary so that SACKs cover only full MSSes
1184adb92db8SIlpo Järvinen 		 * and/or the remaining small portion (if present)
1185adb92db8SIlpo Järvinen 		 */
1186adb92db8SIlpo Järvinen 		if (pkt_len > mss) {
1187adb92db8SIlpo Järvinen 			unsigned int new_len = (pkt_len / mss) * mss;
1188b451e5d2SYuchung Cheng 			if (!in_sack && new_len < pkt_len)
1189adb92db8SIlpo Järvinen 				new_len += mss;
1190adb92db8SIlpo Järvinen 			pkt_len = new_len;
1191adb92db8SIlpo Järvinen 		}
1192b451e5d2SYuchung Cheng 
1193b451e5d2SYuchung Cheng 		if (pkt_len >= skb->len && !in_sack)
1194b451e5d2SYuchung Cheng 			return 0;
1195b451e5d2SYuchung Cheng 
11966cc55e09SOctavian Purdila 		err = tcp_fragment(sk, skb, pkt_len, mss, GFP_ATOMIC);
1197d1935942SIlpo Järvinen 		if (err < 0)
1198d1935942SIlpo Järvinen 			return err;
1199d1935942SIlpo Järvinen 	}
1200d1935942SIlpo Järvinen 
1201d1935942SIlpo Järvinen 	return in_sack;
1202d1935942SIlpo Järvinen }
1203d1935942SIlpo Järvinen 
1204cc9a672eSNeal Cardwell /* Mark the given newly-SACKed range as such, adjusting counters and hints. */
1205cc9a672eSNeal Cardwell static u8 tcp_sacktag_one(struct sock *sk,
1206cc9a672eSNeal Cardwell 			  struct tcp_sacktag_state *state, u8 sacked,
1207cc9a672eSNeal Cardwell 			  u32 start_seq, u32 end_seq,
1208740b0f18SEric Dumazet 			  int dup_sack, int pcount,
12099a568de4SEric Dumazet 			  u64 xmit_time)
12109e10c47cSIlpo Järvinen {
12116859d494SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
1212a1197f5aSIlpo Järvinen 	int fack_count = state->fack_count;
12139e10c47cSIlpo Järvinen 
12149e10c47cSIlpo Järvinen 	/* Account D-SACK for retransmitted packet. */
12159e10c47cSIlpo Järvinen 	if (dup_sack && (sacked & TCPCB_RETRANS)) {
12166e08d5e3SYuchung Cheng 		if (tp->undo_marker && tp->undo_retrans > 0 &&
1217cc9a672eSNeal Cardwell 		    after(end_seq, tp->undo_marker))
12189e10c47cSIlpo Järvinen 			tp->undo_retrans--;
1219ede9f3b1SIlpo Järvinen 		if (sacked & TCPCB_SACKED_ACKED)
1220a1197f5aSIlpo Järvinen 			state->reord = min(fack_count, state->reord);
12219e10c47cSIlpo Järvinen 	}
12229e10c47cSIlpo Järvinen 
12239e10c47cSIlpo Järvinen 	/* Nothing to do; acked frame is about to be dropped (was ACKed). */
1224cc9a672eSNeal Cardwell 	if (!after(end_seq, tp->snd_una))
1225a1197f5aSIlpo Järvinen 		return sacked;
12269e10c47cSIlpo Järvinen 
12279e10c47cSIlpo Järvinen 	if (!(sacked & TCPCB_SACKED_ACKED)) {
1228d2329f10SEric Dumazet 		tcp_rack_advance(tp, sacked, end_seq, xmit_time);
1229659a8ad5SYuchung Cheng 
12309e10c47cSIlpo Järvinen 		if (sacked & TCPCB_SACKED_RETRANS) {
12319e10c47cSIlpo Järvinen 			/* If the segment is not tagged as lost,
12329e10c47cSIlpo Järvinen 			 * we do not clear RETRANS, believing
12339e10c47cSIlpo Järvinen 			 * that retransmission is still in flight.
12349e10c47cSIlpo Järvinen 			 */
12359e10c47cSIlpo Järvinen 			if (sacked & TCPCB_LOST) {
1236a1197f5aSIlpo Järvinen 				sacked &= ~(TCPCB_LOST|TCPCB_SACKED_RETRANS);
1237f58b22fdSIlpo Järvinen 				tp->lost_out -= pcount;
1238f58b22fdSIlpo Järvinen 				tp->retrans_out -= pcount;
12399e10c47cSIlpo Järvinen 			}
12409e10c47cSIlpo Järvinen 		} else {
12419e10c47cSIlpo Järvinen 			if (!(sacked & TCPCB_RETRANS)) {
12429e10c47cSIlpo Järvinen 				/* New sack for not retransmitted frame,
12439e10c47cSIlpo Järvinen 				 * which was in hole. It is reordering.
12449e10c47cSIlpo Järvinen 				 */
1245cc9a672eSNeal Cardwell 				if (before(start_seq,
12469e10c47cSIlpo Järvinen 					   tcp_highest_sack_seq(tp)))
1247a1197f5aSIlpo Järvinen 					state->reord = min(fack_count,
1248a1197f5aSIlpo Järvinen 							   state->reord);
1249e33099f9SYuchung Cheng 				if (!after(end_seq, tp->high_seq))
1250e33099f9SYuchung Cheng 					state->flag |= FLAG_ORIG_SACK_ACKED;
12519a568de4SEric Dumazet 				if (state->first_sackt == 0)
12529a568de4SEric Dumazet 					state->first_sackt = xmit_time;
12539a568de4SEric Dumazet 				state->last_sackt = xmit_time;
12549e10c47cSIlpo Järvinen 			}
12559e10c47cSIlpo Järvinen 
12569e10c47cSIlpo Järvinen 			if (sacked & TCPCB_LOST) {
1257a1197f5aSIlpo Järvinen 				sacked &= ~TCPCB_LOST;
1258f58b22fdSIlpo Järvinen 				tp->lost_out -= pcount;
12599e10c47cSIlpo Järvinen 			}
12609e10c47cSIlpo Järvinen 		}
12619e10c47cSIlpo Järvinen 
1262a1197f5aSIlpo Järvinen 		sacked |= TCPCB_SACKED_ACKED;
1263a1197f5aSIlpo Järvinen 		state->flag |= FLAG_DATA_SACKED;
1264f58b22fdSIlpo Järvinen 		tp->sacked_out += pcount;
1265ddf1af6fSYuchung Cheng 		tp->delivered += pcount;  /* Out-of-order packets delivered */
12669e10c47cSIlpo Järvinen 
1267f58b22fdSIlpo Järvinen 		fack_count += pcount;
12689e10c47cSIlpo Järvinen 
12699e10c47cSIlpo Järvinen 		/* Lost marker hint past SACKed? Tweak RFC3517 cnt */
127000db4124SIan Morris 		if (!tcp_is_fack(tp) && tp->lost_skb_hint &&
1271cc9a672eSNeal Cardwell 		    before(start_seq, TCP_SKB_CB(tp->lost_skb_hint)->seq))
1272f58b22fdSIlpo Järvinen 			tp->lost_cnt_hint += pcount;
12739e10c47cSIlpo Järvinen 
12749e10c47cSIlpo Järvinen 		if (fack_count > tp->fackets_out)
12759e10c47cSIlpo Järvinen 			tp->fackets_out = fack_count;
12769e10c47cSIlpo Järvinen 	}
12779e10c47cSIlpo Järvinen 
12789e10c47cSIlpo Järvinen 	/* D-SACK. We can detect redundant retransmission in S|R and plain R
12799e10c47cSIlpo Järvinen 	 * frames and clear it. undo_retrans is decreased above, L|R frames
12809e10c47cSIlpo Järvinen 	 * are accounted above as well.
12819e10c47cSIlpo Järvinen 	 */
1282a1197f5aSIlpo Järvinen 	if (dup_sack && (sacked & TCPCB_SACKED_RETRANS)) {
1283a1197f5aSIlpo Järvinen 		sacked &= ~TCPCB_SACKED_RETRANS;
1284f58b22fdSIlpo Järvinen 		tp->retrans_out -= pcount;
12859e10c47cSIlpo Järvinen 	}
12869e10c47cSIlpo Järvinen 
1287a1197f5aSIlpo Järvinen 	return sacked;
12889e10c47cSIlpo Järvinen }
12899e10c47cSIlpo Järvinen 
1290daef52baSNeal Cardwell /* Shift newly-SACKed bytes from this skb to the immediately previous
1291daef52baSNeal Cardwell  * already-SACKed sk_buff. Mark the newly-SACKed bytes as such.
1292daef52baSNeal Cardwell  */
1293a2a385d6SEric Dumazet static bool tcp_shifted_skb(struct sock *sk, struct sk_buff *skb,
1294a1197f5aSIlpo Järvinen 			    struct tcp_sacktag_state *state,
12959ec06ff5SIlpo Järvinen 			    unsigned int pcount, int shifted, int mss,
1296a2a385d6SEric Dumazet 			    bool dup_sack)
1297832d11c5SIlpo Järvinen {
1298832d11c5SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
129950133161SIlpo Järvinen 	struct sk_buff *prev = tcp_write_queue_prev(sk, skb);
1300daef52baSNeal Cardwell 	u32 start_seq = TCP_SKB_CB(skb)->seq;	/* start of newly-SACKed */
1301daef52baSNeal Cardwell 	u32 end_seq = start_seq + shifted;	/* end of newly-SACKed */
1302832d11c5SIlpo Järvinen 
1303832d11c5SIlpo Järvinen 	BUG_ON(!pcount);
1304832d11c5SIlpo Järvinen 
13054c90d3b3SNeal Cardwell 	/* Adjust counters and hints for the newly sacked sequence
13064c90d3b3SNeal Cardwell 	 * range but discard the return value since prev is already
13074c90d3b3SNeal Cardwell 	 * marked. We must tag the range first because the seq
13084c90d3b3SNeal Cardwell 	 * advancement below implicitly advances
13094c90d3b3SNeal Cardwell 	 * tcp_highest_sack_seq() when skb is highest_sack.
13104c90d3b3SNeal Cardwell 	 */
13114c90d3b3SNeal Cardwell 	tcp_sacktag_one(sk, state, TCP_SKB_CB(skb)->sacked,
131259c9af42SYuchung Cheng 			start_seq, end_seq, dup_sack, pcount,
13139a568de4SEric Dumazet 			skb->skb_mstamp);
1314b9f64820SYuchung Cheng 	tcp_rate_skb_delivered(sk, skb, state->rate);
13154c90d3b3SNeal Cardwell 
13164c90d3b3SNeal Cardwell 	if (skb == tp->lost_skb_hint)
13170af2a0d0SNeal Cardwell 		tp->lost_cnt_hint += pcount;
13180af2a0d0SNeal Cardwell 
1319832d11c5SIlpo Järvinen 	TCP_SKB_CB(prev)->end_seq += shifted;
1320832d11c5SIlpo Järvinen 	TCP_SKB_CB(skb)->seq += shifted;
1321832d11c5SIlpo Järvinen 
1322cd7d8498SEric Dumazet 	tcp_skb_pcount_add(prev, pcount);
1323cd7d8498SEric Dumazet 	BUG_ON(tcp_skb_pcount(skb) < pcount);
1324cd7d8498SEric Dumazet 	tcp_skb_pcount_add(skb, -pcount);
1325832d11c5SIlpo Järvinen 
1326832d11c5SIlpo Järvinen 	/* When we're adding to gso_segs == 1, gso_size will be zero,
1327832d11c5SIlpo Järvinen 	 * in theory this shouldn't be necessary but as long as DSACK
1328832d11c5SIlpo Järvinen 	 * code can come after this skb later on it's better to keep
1329832d11c5SIlpo Järvinen 	 * setting gso_size to something.
1330832d11c5SIlpo Järvinen 	 */
1331f69ad292SEric Dumazet 	if (!TCP_SKB_CB(prev)->tcp_gso_size)
1332f69ad292SEric Dumazet 		TCP_SKB_CB(prev)->tcp_gso_size = mss;
1333832d11c5SIlpo Järvinen 
1334832d11c5SIlpo Järvinen 	/* CHECKME: To clear or not to clear? Mimics normal skb currently */
133551466a75SEric Dumazet 	if (tcp_skb_pcount(skb) <= 1)
1336f69ad292SEric Dumazet 		TCP_SKB_CB(skb)->tcp_gso_size = 0;
1337832d11c5SIlpo Järvinen 
1338832d11c5SIlpo Järvinen 	/* Difference in this won't matter, both ACKed by the same cumul. ACK */
1339832d11c5SIlpo Järvinen 	TCP_SKB_CB(prev)->sacked |= (TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS);
1340832d11c5SIlpo Järvinen 
1341832d11c5SIlpo Järvinen 	if (skb->len > 0) {
1342832d11c5SIlpo Järvinen 		BUG_ON(!tcp_skb_pcount(skb));
1343c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKSHIFTED);
1344a2a385d6SEric Dumazet 		return false;
1345832d11c5SIlpo Järvinen 	}
1346832d11c5SIlpo Järvinen 
1347832d11c5SIlpo Järvinen 	/* Whole SKB was eaten :-) */
1348832d11c5SIlpo Järvinen 
134992ee76b6SIlpo Järvinen 	if (skb == tp->retransmit_skb_hint)
135092ee76b6SIlpo Järvinen 		tp->retransmit_skb_hint = prev;
135192ee76b6SIlpo Järvinen 	if (skb == tp->lost_skb_hint) {
135292ee76b6SIlpo Järvinen 		tp->lost_skb_hint = prev;
135392ee76b6SIlpo Järvinen 		tp->lost_cnt_hint -= tcp_skb_pcount(prev);
135492ee76b6SIlpo Järvinen 	}
135592ee76b6SIlpo Järvinen 
13565e8a402fSEric Dumazet 	TCP_SKB_CB(prev)->tcp_flags |= TCP_SKB_CB(skb)->tcp_flags;
1357a643b5d4SMartin KaFai Lau 	TCP_SKB_CB(prev)->eor = TCP_SKB_CB(skb)->eor;
13585e8a402fSEric Dumazet 	if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
13595e8a402fSEric Dumazet 		TCP_SKB_CB(prev)->end_seq++;
13605e8a402fSEric Dumazet 
1361832d11c5SIlpo Järvinen 	if (skb == tcp_highest_sack(sk))
1362832d11c5SIlpo Järvinen 		tcp_advance_highest_sack(sk, skb);
1363832d11c5SIlpo Järvinen 
1364cfea5a68SMartin KaFai Lau 	tcp_skb_collapse_tstamp(prev, skb);
13659a568de4SEric Dumazet 	if (unlikely(TCP_SKB_CB(prev)->tx.delivered_mstamp))
13669a568de4SEric Dumazet 		TCP_SKB_CB(prev)->tx.delivered_mstamp = 0;
1367b9f64820SYuchung Cheng 
1368832d11c5SIlpo Järvinen 	tcp_unlink_write_queue(skb, sk);
1369832d11c5SIlpo Järvinen 	sk_wmem_free_skb(sk, skb);
1370832d11c5SIlpo Järvinen 
1371c10d9310SEric Dumazet 	NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKMERGED);
1372111cc8b9SIlpo Järvinen 
1373a2a385d6SEric Dumazet 	return true;
1374832d11c5SIlpo Järvinen }
1375832d11c5SIlpo Järvinen 
1376832d11c5SIlpo Järvinen /* I wish gso_size would have a bit more sane initialization than
1377832d11c5SIlpo Järvinen  * something-or-zero which complicates things
1378832d11c5SIlpo Järvinen  */
1379cf533ea5SEric Dumazet static int tcp_skb_seglen(const struct sk_buff *skb)
1380832d11c5SIlpo Järvinen {
1381775ffabfSIlpo Järvinen 	return tcp_skb_pcount(skb) == 1 ? skb->len : tcp_skb_mss(skb);
1382832d11c5SIlpo Järvinen }
1383832d11c5SIlpo Järvinen 
1384832d11c5SIlpo Järvinen /* Shifting pages past head area doesn't work */
1385cf533ea5SEric Dumazet static int skb_can_shift(const struct sk_buff *skb)
1386832d11c5SIlpo Järvinen {
1387832d11c5SIlpo Järvinen 	return !skb_headlen(skb) && skb_is_nonlinear(skb);
1388832d11c5SIlpo Järvinen }
1389832d11c5SIlpo Järvinen 
1390832d11c5SIlpo Järvinen /* Try collapsing SACK blocks spanning across multiple skbs to a single
1391832d11c5SIlpo Järvinen  * skb.
1392832d11c5SIlpo Järvinen  */
1393832d11c5SIlpo Järvinen static struct sk_buff *tcp_shift_skb_data(struct sock *sk, struct sk_buff *skb,
1394a1197f5aSIlpo Järvinen 					  struct tcp_sacktag_state *state,
1395832d11c5SIlpo Järvinen 					  u32 start_seq, u32 end_seq,
1396a2a385d6SEric Dumazet 					  bool dup_sack)
1397832d11c5SIlpo Järvinen {
1398832d11c5SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
1399832d11c5SIlpo Järvinen 	struct sk_buff *prev;
1400832d11c5SIlpo Järvinen 	int mss;
1401832d11c5SIlpo Järvinen 	int pcount = 0;
1402832d11c5SIlpo Järvinen 	int len;
1403832d11c5SIlpo Järvinen 	int in_sack;
1404832d11c5SIlpo Järvinen 
1405832d11c5SIlpo Järvinen 	if (!sk_can_gso(sk))
1406832d11c5SIlpo Järvinen 		goto fallback;
1407832d11c5SIlpo Järvinen 
1408832d11c5SIlpo Järvinen 	/* Normally R but no L won't result in plain S */
1409832d11c5SIlpo Järvinen 	if (!dup_sack &&
14109969ca5fSIlpo Järvinen 	    (TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_RETRANS)) == TCPCB_SACKED_RETRANS)
1411832d11c5SIlpo Järvinen 		goto fallback;
1412832d11c5SIlpo Järvinen 	if (!skb_can_shift(skb))
1413832d11c5SIlpo Järvinen 		goto fallback;
1414832d11c5SIlpo Järvinen 	/* This frame is about to be dropped (was ACKed). */
1415832d11c5SIlpo Järvinen 	if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una))
1416832d11c5SIlpo Järvinen 		goto fallback;
1417832d11c5SIlpo Järvinen 
1418832d11c5SIlpo Järvinen 	/* Can only happen with delayed DSACK + discard craziness */
1419832d11c5SIlpo Järvinen 	if (unlikely(skb == tcp_write_queue_head(sk)))
1420832d11c5SIlpo Järvinen 		goto fallback;
1421832d11c5SIlpo Järvinen 	prev = tcp_write_queue_prev(sk, skb);
1422832d11c5SIlpo Järvinen 
1423832d11c5SIlpo Järvinen 	if ((TCP_SKB_CB(prev)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED)
1424832d11c5SIlpo Järvinen 		goto fallback;
1425832d11c5SIlpo Järvinen 
1426a643b5d4SMartin KaFai Lau 	if (!tcp_skb_can_collapse_to(prev))
1427a643b5d4SMartin KaFai Lau 		goto fallback;
1428a643b5d4SMartin KaFai Lau 
1429832d11c5SIlpo Järvinen 	in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
1430832d11c5SIlpo Järvinen 		  !before(end_seq, TCP_SKB_CB(skb)->end_seq);
1431832d11c5SIlpo Järvinen 
1432832d11c5SIlpo Järvinen 	if (in_sack) {
1433832d11c5SIlpo Järvinen 		len = skb->len;
1434832d11c5SIlpo Järvinen 		pcount = tcp_skb_pcount(skb);
1435775ffabfSIlpo Järvinen 		mss = tcp_skb_seglen(skb);
1436832d11c5SIlpo Järvinen 
1437832d11c5SIlpo Järvinen 		/* TODO: Fix DSACKs to not fragment already SACKed and we can
1438832d11c5SIlpo Järvinen 		 * drop this restriction as unnecessary
1439832d11c5SIlpo Järvinen 		 */
1440775ffabfSIlpo Järvinen 		if (mss != tcp_skb_seglen(prev))
1441832d11c5SIlpo Järvinen 			goto fallback;
1442832d11c5SIlpo Järvinen 	} else {
1443832d11c5SIlpo Järvinen 		if (!after(TCP_SKB_CB(skb)->end_seq, start_seq))
1444832d11c5SIlpo Järvinen 			goto noop;
1445832d11c5SIlpo Järvinen 		/* CHECKME: This is non-MSS split case only?, this will
1446832d11c5SIlpo Järvinen 		 * cause skipped skbs due to advancing loop btw, original
1447832d11c5SIlpo Järvinen 		 * has that feature too
1448832d11c5SIlpo Järvinen 		 */
1449832d11c5SIlpo Järvinen 		if (tcp_skb_pcount(skb) <= 1)
1450832d11c5SIlpo Järvinen 			goto noop;
1451832d11c5SIlpo Järvinen 
1452832d11c5SIlpo Järvinen 		in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq);
1453832d11c5SIlpo Järvinen 		if (!in_sack) {
1454832d11c5SIlpo Järvinen 			/* TODO: head merge to next could be attempted here
1455832d11c5SIlpo Järvinen 			 * if (!after(TCP_SKB_CB(skb)->end_seq, end_seq)),
1456832d11c5SIlpo Järvinen 			 * though it might not be worth of the additional hassle
1457832d11c5SIlpo Järvinen 			 *
1458832d11c5SIlpo Järvinen 			 * ...we can probably just fallback to what was done
1459832d11c5SIlpo Järvinen 			 * previously. We could try merging non-SACKed ones
1460832d11c5SIlpo Järvinen 			 * as well but it probably isn't going to buy off
1461832d11c5SIlpo Järvinen 			 * because later SACKs might again split them, and
1462832d11c5SIlpo Järvinen 			 * it would make skb timestamp tracking considerably
1463832d11c5SIlpo Järvinen 			 * harder problem.
1464832d11c5SIlpo Järvinen 			 */
1465832d11c5SIlpo Järvinen 			goto fallback;
1466832d11c5SIlpo Järvinen 		}
1467832d11c5SIlpo Järvinen 
1468832d11c5SIlpo Järvinen 		len = end_seq - TCP_SKB_CB(skb)->seq;
1469832d11c5SIlpo Järvinen 		BUG_ON(len < 0);
1470832d11c5SIlpo Järvinen 		BUG_ON(len > skb->len);
1471832d11c5SIlpo Järvinen 
1472832d11c5SIlpo Järvinen 		/* MSS boundaries should be honoured or else pcount will
1473832d11c5SIlpo Järvinen 		 * severely break even though it makes things bit trickier.
1474832d11c5SIlpo Järvinen 		 * Optimize common case to avoid most of the divides
1475832d11c5SIlpo Järvinen 		 */
1476832d11c5SIlpo Järvinen 		mss = tcp_skb_mss(skb);
1477832d11c5SIlpo Järvinen 
1478832d11c5SIlpo Järvinen 		/* TODO: Fix DSACKs to not fragment already SACKed and we can
1479832d11c5SIlpo Järvinen 		 * drop this restriction as unnecessary
1480832d11c5SIlpo Järvinen 		 */
1481775ffabfSIlpo Järvinen 		if (mss != tcp_skb_seglen(prev))
1482832d11c5SIlpo Järvinen 			goto fallback;
1483832d11c5SIlpo Järvinen 
1484832d11c5SIlpo Järvinen 		if (len == mss) {
1485832d11c5SIlpo Järvinen 			pcount = 1;
1486832d11c5SIlpo Järvinen 		} else if (len < mss) {
1487832d11c5SIlpo Järvinen 			goto noop;
1488832d11c5SIlpo Järvinen 		} else {
1489832d11c5SIlpo Järvinen 			pcount = len / mss;
1490832d11c5SIlpo Järvinen 			len = pcount * mss;
1491832d11c5SIlpo Järvinen 		}
1492832d11c5SIlpo Järvinen 	}
1493832d11c5SIlpo Järvinen 
14944648dc97SNeal Cardwell 	/* tcp_sacktag_one() won't SACK-tag ranges below snd_una */
14954648dc97SNeal Cardwell 	if (!after(TCP_SKB_CB(skb)->seq + len, tp->snd_una))
14964648dc97SNeal Cardwell 		goto fallback;
14974648dc97SNeal Cardwell 
1498832d11c5SIlpo Järvinen 	if (!skb_shift(prev, skb, len))
1499832d11c5SIlpo Järvinen 		goto fallback;
15009ec06ff5SIlpo Järvinen 	if (!tcp_shifted_skb(sk, skb, state, pcount, len, mss, dup_sack))
1501832d11c5SIlpo Järvinen 		goto out;
1502832d11c5SIlpo Järvinen 
1503832d11c5SIlpo Järvinen 	/* Hole filled allows collapsing with the next as well, this is very
1504832d11c5SIlpo Järvinen 	 * useful when hole on every nth skb pattern happens
1505832d11c5SIlpo Järvinen 	 */
1506832d11c5SIlpo Järvinen 	if (prev == tcp_write_queue_tail(sk))
1507832d11c5SIlpo Järvinen 		goto out;
1508832d11c5SIlpo Järvinen 	skb = tcp_write_queue_next(sk, prev);
1509832d11c5SIlpo Järvinen 
1510f0bc52f3SIlpo Järvinen 	if (!skb_can_shift(skb) ||
1511f0bc52f3SIlpo Järvinen 	    (skb == tcp_send_head(sk)) ||
1512f0bc52f3SIlpo Järvinen 	    ((TCP_SKB_CB(skb)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED) ||
1513775ffabfSIlpo Järvinen 	    (mss != tcp_skb_seglen(skb)))
1514832d11c5SIlpo Järvinen 		goto out;
1515832d11c5SIlpo Järvinen 
1516832d11c5SIlpo Järvinen 	len = skb->len;
1517832d11c5SIlpo Järvinen 	if (skb_shift(prev, skb, len)) {
1518832d11c5SIlpo Järvinen 		pcount += tcp_skb_pcount(skb);
15199ec06ff5SIlpo Järvinen 		tcp_shifted_skb(sk, skb, state, tcp_skb_pcount(skb), len, mss, 0);
1520832d11c5SIlpo Järvinen 	}
1521832d11c5SIlpo Järvinen 
1522832d11c5SIlpo Järvinen out:
1523a1197f5aSIlpo Järvinen 	state->fack_count += pcount;
1524832d11c5SIlpo Järvinen 	return prev;
1525832d11c5SIlpo Järvinen 
1526832d11c5SIlpo Järvinen noop:
1527832d11c5SIlpo Järvinen 	return skb;
1528832d11c5SIlpo Järvinen 
1529832d11c5SIlpo Järvinen fallback:
1530c10d9310SEric Dumazet 	NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKSHIFTFALLBACK);
1531832d11c5SIlpo Järvinen 	return NULL;
1532832d11c5SIlpo Järvinen }
1533832d11c5SIlpo Järvinen 
153468f8353bSIlpo Järvinen static struct sk_buff *tcp_sacktag_walk(struct sk_buff *skb, struct sock *sk,
153568f8353bSIlpo Järvinen 					struct tcp_sack_block *next_dup,
1536a1197f5aSIlpo Järvinen 					struct tcp_sacktag_state *state,
153768f8353bSIlpo Järvinen 					u32 start_seq, u32 end_seq,
1538a2a385d6SEric Dumazet 					bool dup_sack_in)
153968f8353bSIlpo Järvinen {
1540832d11c5SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
1541832d11c5SIlpo Järvinen 	struct sk_buff *tmp;
1542832d11c5SIlpo Järvinen 
154368f8353bSIlpo Järvinen 	tcp_for_write_queue_from(skb, sk) {
154468f8353bSIlpo Järvinen 		int in_sack = 0;
1545a2a385d6SEric Dumazet 		bool dup_sack = dup_sack_in;
154668f8353bSIlpo Järvinen 
154768f8353bSIlpo Järvinen 		if (skb == tcp_send_head(sk))
154868f8353bSIlpo Järvinen 			break;
154968f8353bSIlpo Järvinen 
155068f8353bSIlpo Järvinen 		/* queue is in-order => we can short-circuit the walk early */
155168f8353bSIlpo Järvinen 		if (!before(TCP_SKB_CB(skb)->seq, end_seq))
155268f8353bSIlpo Järvinen 			break;
155368f8353bSIlpo Järvinen 
155400db4124SIan Morris 		if (next_dup  &&
155568f8353bSIlpo Järvinen 		    before(TCP_SKB_CB(skb)->seq, next_dup->end_seq)) {
155668f8353bSIlpo Järvinen 			in_sack = tcp_match_skb_to_sack(sk, skb,
155768f8353bSIlpo Järvinen 							next_dup->start_seq,
155868f8353bSIlpo Järvinen 							next_dup->end_seq);
155968f8353bSIlpo Järvinen 			if (in_sack > 0)
1560a2a385d6SEric Dumazet 				dup_sack = true;
156168f8353bSIlpo Järvinen 		}
156268f8353bSIlpo Järvinen 
1563832d11c5SIlpo Järvinen 		/* skb reference here is a bit tricky to get right, since
1564832d11c5SIlpo Järvinen 		 * shifting can eat and free both this skb and the next,
1565832d11c5SIlpo Järvinen 		 * so not even _safe variant of the loop is enough.
1566832d11c5SIlpo Järvinen 		 */
1567832d11c5SIlpo Järvinen 		if (in_sack <= 0) {
1568a1197f5aSIlpo Järvinen 			tmp = tcp_shift_skb_data(sk, skb, state,
1569a1197f5aSIlpo Järvinen 						 start_seq, end_seq, dup_sack);
157000db4124SIan Morris 			if (tmp) {
1571832d11c5SIlpo Järvinen 				if (tmp != skb) {
1572832d11c5SIlpo Järvinen 					skb = tmp;
1573832d11c5SIlpo Järvinen 					continue;
1574832d11c5SIlpo Järvinen 				}
1575832d11c5SIlpo Järvinen 
1576832d11c5SIlpo Järvinen 				in_sack = 0;
1577832d11c5SIlpo Järvinen 			} else {
1578832d11c5SIlpo Järvinen 				in_sack = tcp_match_skb_to_sack(sk, skb,
1579832d11c5SIlpo Järvinen 								start_seq,
1580056834d9SIlpo Järvinen 								end_seq);
1581832d11c5SIlpo Järvinen 			}
1582832d11c5SIlpo Järvinen 		}
1583832d11c5SIlpo Järvinen 
158468f8353bSIlpo Järvinen 		if (unlikely(in_sack < 0))
158568f8353bSIlpo Järvinen 			break;
158668f8353bSIlpo Järvinen 
1587832d11c5SIlpo Järvinen 		if (in_sack) {
1588cc9a672eSNeal Cardwell 			TCP_SKB_CB(skb)->sacked =
1589cc9a672eSNeal Cardwell 				tcp_sacktag_one(sk,
1590a1197f5aSIlpo Järvinen 						state,
1591cc9a672eSNeal Cardwell 						TCP_SKB_CB(skb)->sacked,
1592cc9a672eSNeal Cardwell 						TCP_SKB_CB(skb)->seq,
1593cc9a672eSNeal Cardwell 						TCP_SKB_CB(skb)->end_seq,
1594a1197f5aSIlpo Järvinen 						dup_sack,
159559c9af42SYuchung Cheng 						tcp_skb_pcount(skb),
15969a568de4SEric Dumazet 						skb->skb_mstamp);
1597b9f64820SYuchung Cheng 			tcp_rate_skb_delivered(sk, skb, state->rate);
159868f8353bSIlpo Järvinen 
1599832d11c5SIlpo Järvinen 			if (!before(TCP_SKB_CB(skb)->seq,
1600832d11c5SIlpo Järvinen 				    tcp_highest_sack_seq(tp)))
1601832d11c5SIlpo Järvinen 				tcp_advance_highest_sack(sk, skb);
1602832d11c5SIlpo Järvinen 		}
1603832d11c5SIlpo Järvinen 
1604a1197f5aSIlpo Järvinen 		state->fack_count += tcp_skb_pcount(skb);
160568f8353bSIlpo Järvinen 	}
160668f8353bSIlpo Järvinen 	return skb;
160768f8353bSIlpo Järvinen }
160868f8353bSIlpo Järvinen 
160968f8353bSIlpo Järvinen /* Avoid all extra work that is being done by sacktag while walking in
161068f8353bSIlpo Järvinen  * a normal way
161168f8353bSIlpo Järvinen  */
161268f8353bSIlpo Järvinen static struct sk_buff *tcp_sacktag_skip(struct sk_buff *skb, struct sock *sk,
1613a1197f5aSIlpo Järvinen 					struct tcp_sacktag_state *state,
1614a1197f5aSIlpo Järvinen 					u32 skip_to_seq)
161568f8353bSIlpo Järvinen {
161668f8353bSIlpo Järvinen 	tcp_for_write_queue_from(skb, sk) {
161768f8353bSIlpo Järvinen 		if (skb == tcp_send_head(sk))
161868f8353bSIlpo Järvinen 			break;
161968f8353bSIlpo Järvinen 
1620e8bae275SIlpo Järvinen 		if (after(TCP_SKB_CB(skb)->end_seq, skip_to_seq))
162168f8353bSIlpo Järvinen 			break;
1622d152a7d8SIlpo Järvinen 
1623a1197f5aSIlpo Järvinen 		state->fack_count += tcp_skb_pcount(skb);
162468f8353bSIlpo Järvinen 	}
162568f8353bSIlpo Järvinen 	return skb;
162668f8353bSIlpo Järvinen }
162768f8353bSIlpo Järvinen 
162868f8353bSIlpo Järvinen static struct sk_buff *tcp_maybe_skipping_dsack(struct sk_buff *skb,
162968f8353bSIlpo Järvinen 						struct sock *sk,
163068f8353bSIlpo Järvinen 						struct tcp_sack_block *next_dup,
1631a1197f5aSIlpo Järvinen 						struct tcp_sacktag_state *state,
1632a1197f5aSIlpo Järvinen 						u32 skip_to_seq)
163368f8353bSIlpo Järvinen {
163451456b29SIan Morris 	if (!next_dup)
163568f8353bSIlpo Järvinen 		return skb;
163668f8353bSIlpo Järvinen 
163768f8353bSIlpo Järvinen 	if (before(next_dup->start_seq, skip_to_seq)) {
1638a1197f5aSIlpo Järvinen 		skb = tcp_sacktag_skip(skb, sk, state, next_dup->start_seq);
1639a1197f5aSIlpo Järvinen 		skb = tcp_sacktag_walk(skb, sk, NULL, state,
164068f8353bSIlpo Järvinen 				       next_dup->start_seq, next_dup->end_seq,
1641a1197f5aSIlpo Järvinen 				       1);
164268f8353bSIlpo Järvinen 	}
164368f8353bSIlpo Järvinen 
164468f8353bSIlpo Järvinen 	return skb;
164568f8353bSIlpo Järvinen }
164668f8353bSIlpo Järvinen 
1647cf533ea5SEric Dumazet static int tcp_sack_cache_ok(const struct tcp_sock *tp, const struct tcp_sack_block *cache)
164868f8353bSIlpo Järvinen {
164968f8353bSIlpo Järvinen 	return cache < tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache);
165068f8353bSIlpo Järvinen }
165168f8353bSIlpo Järvinen 
16521da177e4SLinus Torvalds static int
1653cf533ea5SEric Dumazet tcp_sacktag_write_queue(struct sock *sk, const struct sk_buff *ack_skb,
1654196da974SKenneth Klette Jonassen 			u32 prior_snd_una, struct tcp_sacktag_state *state)
16551da177e4SLinus Torvalds {
16561da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
1657cf533ea5SEric Dumazet 	const unsigned char *ptr = (skb_transport_header(ack_skb) +
16589c70220bSArnaldo Carvalho de Melo 				    TCP_SKB_CB(ack_skb)->sacked);
1659fd6dad61SIlpo Järvinen 	struct tcp_sack_block_wire *sp_wire = (struct tcp_sack_block_wire *)(ptr+2);
16604389ddedSAdam Langley 	struct tcp_sack_block sp[TCP_NUM_SACKS];
166168f8353bSIlpo Järvinen 	struct tcp_sack_block *cache;
166268f8353bSIlpo Järvinen 	struct sk_buff *skb;
16634389ddedSAdam Langley 	int num_sacks = min(TCP_NUM_SACKS, (ptr[1] - TCPOLEN_SACK_BASE) >> 3);
1664fd6dad61SIlpo Järvinen 	int used_sacks;
1665a2a385d6SEric Dumazet 	bool found_dup_sack = false;
166668f8353bSIlpo Järvinen 	int i, j;
1667fda03fbbSBaruch Even 	int first_sack_index;
16681da177e4SLinus Torvalds 
1669196da974SKenneth Klette Jonassen 	state->flag = 0;
1670196da974SKenneth Klette Jonassen 	state->reord = tp->packets_out;
1671a1197f5aSIlpo Järvinen 
1672d738cd8fSIlpo Järvinen 	if (!tp->sacked_out) {
1673de83c058SIlpo Järvinen 		if (WARN_ON(tp->fackets_out))
16741da177e4SLinus Torvalds 			tp->fackets_out = 0;
16756859d494SIlpo Järvinen 		tcp_highest_sack_reset(sk);
1676d738cd8fSIlpo Järvinen 	}
16771da177e4SLinus Torvalds 
16781ed83465SPavel Emelyanov 	found_dup_sack = tcp_check_dsack(sk, ack_skb, sp_wire,
1679d06e021dSDavid S. Miller 					 num_sacks, prior_snd_una);
1680b9f64820SYuchung Cheng 	if (found_dup_sack) {
1681196da974SKenneth Klette Jonassen 		state->flag |= FLAG_DSACKING_ACK;
1682b9f64820SYuchung Cheng 		tp->delivered++; /* A spurious retransmission is delivered */
1683b9f64820SYuchung Cheng 	}
16846f74651aSBaruch Even 
16856f74651aSBaruch Even 	/* Eliminate too old ACKs, but take into
16866f74651aSBaruch Even 	 * account more or less fresh ones, they can
16876f74651aSBaruch Even 	 * contain valid SACK info.
16886f74651aSBaruch Even 	 */
16896f74651aSBaruch Even 	if (before(TCP_SKB_CB(ack_skb)->ack_seq, prior_snd_una - tp->max_window))
16906f74651aSBaruch Even 		return 0;
16916f74651aSBaruch Even 
169296a2d41aSIlpo Järvinen 	if (!tp->packets_out)
169396a2d41aSIlpo Järvinen 		goto out;
169496a2d41aSIlpo Järvinen 
1695fd6dad61SIlpo Järvinen 	used_sacks = 0;
1696fd6dad61SIlpo Järvinen 	first_sack_index = 0;
1697fd6dad61SIlpo Järvinen 	for (i = 0; i < num_sacks; i++) {
1698a2a385d6SEric Dumazet 		bool dup_sack = !i && found_dup_sack;
1699fd6dad61SIlpo Järvinen 
1700d3e2ce3bSHarvey Harrison 		sp[used_sacks].start_seq = get_unaligned_be32(&sp_wire[i].start_seq);
1701d3e2ce3bSHarvey Harrison 		sp[used_sacks].end_seq = get_unaligned_be32(&sp_wire[i].end_seq);
1702fd6dad61SIlpo Järvinen 
1703fd6dad61SIlpo Järvinen 		if (!tcp_is_sackblock_valid(tp, dup_sack,
1704fd6dad61SIlpo Järvinen 					    sp[used_sacks].start_seq,
1705fd6dad61SIlpo Järvinen 					    sp[used_sacks].end_seq)) {
170640b215e5SPavel Emelyanov 			int mib_idx;
170740b215e5SPavel Emelyanov 
1708fd6dad61SIlpo Järvinen 			if (dup_sack) {
1709fd6dad61SIlpo Järvinen 				if (!tp->undo_marker)
171040b215e5SPavel Emelyanov 					mib_idx = LINUX_MIB_TCPDSACKIGNOREDNOUNDO;
1711fd6dad61SIlpo Järvinen 				else
171240b215e5SPavel Emelyanov 					mib_idx = LINUX_MIB_TCPDSACKIGNOREDOLD;
1713fd6dad61SIlpo Järvinen 			} else {
1714fd6dad61SIlpo Järvinen 				/* Don't count olds caused by ACK reordering */
1715fd6dad61SIlpo Järvinen 				if ((TCP_SKB_CB(ack_skb)->ack_seq != tp->snd_una) &&
1716fd6dad61SIlpo Järvinen 				    !after(sp[used_sacks].end_seq, tp->snd_una))
1717fd6dad61SIlpo Järvinen 					continue;
171840b215e5SPavel Emelyanov 				mib_idx = LINUX_MIB_TCPSACKDISCARD;
1719fd6dad61SIlpo Järvinen 			}
172040b215e5SPavel Emelyanov 
1721c10d9310SEric Dumazet 			NET_INC_STATS(sock_net(sk), mib_idx);
1722fd6dad61SIlpo Järvinen 			if (i == 0)
1723fd6dad61SIlpo Järvinen 				first_sack_index = -1;
1724fd6dad61SIlpo Järvinen 			continue;
1725fd6dad61SIlpo Järvinen 		}
1726fd6dad61SIlpo Järvinen 
1727fd6dad61SIlpo Järvinen 		/* Ignore very old stuff early */
1728fd6dad61SIlpo Järvinen 		if (!after(sp[used_sacks].end_seq, prior_snd_una))
1729fd6dad61SIlpo Järvinen 			continue;
1730fd6dad61SIlpo Järvinen 
1731fd6dad61SIlpo Järvinen 		used_sacks++;
1732fd6dad61SIlpo Järvinen 	}
1733fd6dad61SIlpo Järvinen 
17346a438bbeSStephen Hemminger 	/* order SACK blocks to allow in order walk of the retrans queue */
1735fd6dad61SIlpo Järvinen 	for (i = used_sacks - 1; i > 0; i--) {
17366a438bbeSStephen Hemminger 		for (j = 0; j < i; j++) {
1737fd6dad61SIlpo Järvinen 			if (after(sp[j].start_seq, sp[j + 1].start_seq)) {
1738a0bffffcSIlpo Järvinen 				swap(sp[j], sp[j + 1]);
1739fda03fbbSBaruch Even 
1740fda03fbbSBaruch Even 				/* Track where the first SACK block goes to */
1741fda03fbbSBaruch Even 				if (j == first_sack_index)
1742fda03fbbSBaruch Even 					first_sack_index = j + 1;
17436a438bbeSStephen Hemminger 			}
17446a438bbeSStephen Hemminger 		}
17456a438bbeSStephen Hemminger 	}
17466a438bbeSStephen Hemminger 
174768f8353bSIlpo Järvinen 	skb = tcp_write_queue_head(sk);
1748196da974SKenneth Klette Jonassen 	state->fack_count = 0;
174968f8353bSIlpo Järvinen 	i = 0;
175068f8353bSIlpo Järvinen 
175168f8353bSIlpo Järvinen 	if (!tp->sacked_out) {
175268f8353bSIlpo Järvinen 		/* It's already past, so skip checking against it */
175368f8353bSIlpo Järvinen 		cache = tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache);
175468f8353bSIlpo Järvinen 	} else {
175568f8353bSIlpo Järvinen 		cache = tp->recv_sack_cache;
175668f8353bSIlpo Järvinen 		/* Skip empty blocks in at head of the cache */
175768f8353bSIlpo Järvinen 		while (tcp_sack_cache_ok(tp, cache) && !cache->start_seq &&
175868f8353bSIlpo Järvinen 		       !cache->end_seq)
175968f8353bSIlpo Järvinen 			cache++;
1760fda03fbbSBaruch Even 	}
1761fda03fbbSBaruch Even 
176268f8353bSIlpo Järvinen 	while (i < used_sacks) {
1763fd6dad61SIlpo Järvinen 		u32 start_seq = sp[i].start_seq;
1764fd6dad61SIlpo Järvinen 		u32 end_seq = sp[i].end_seq;
1765a2a385d6SEric Dumazet 		bool dup_sack = (found_dup_sack && (i == first_sack_index));
176668f8353bSIlpo Järvinen 		struct tcp_sack_block *next_dup = NULL;
1767e56d6cd6SIlpo Järvinen 
176868f8353bSIlpo Järvinen 		if (found_dup_sack && ((i + 1) == first_sack_index))
176968f8353bSIlpo Järvinen 			next_dup = &sp[i + 1];
17701da177e4SLinus Torvalds 
177168f8353bSIlpo Järvinen 		/* Skip too early cached blocks */
177268f8353bSIlpo Järvinen 		while (tcp_sack_cache_ok(tp, cache) &&
177368f8353bSIlpo Järvinen 		       !before(start_seq, cache->end_seq))
177468f8353bSIlpo Järvinen 			cache++;
17751da177e4SLinus Torvalds 
177668f8353bSIlpo Järvinen 		/* Can skip some work by looking recv_sack_cache? */
177768f8353bSIlpo Järvinen 		if (tcp_sack_cache_ok(tp, cache) && !dup_sack &&
177868f8353bSIlpo Järvinen 		    after(end_seq, cache->start_seq)) {
1779fe067e8aSDavid S. Miller 
178068f8353bSIlpo Järvinen 			/* Head todo? */
178168f8353bSIlpo Järvinen 			if (before(start_seq, cache->start_seq)) {
1782196da974SKenneth Klette Jonassen 				skb = tcp_sacktag_skip(skb, sk, state,
1783a1197f5aSIlpo Järvinen 						       start_seq);
1784056834d9SIlpo Järvinen 				skb = tcp_sacktag_walk(skb, sk, next_dup,
1785196da974SKenneth Klette Jonassen 						       state,
1786056834d9SIlpo Järvinen 						       start_seq,
1787056834d9SIlpo Järvinen 						       cache->start_seq,
1788a1197f5aSIlpo Järvinen 						       dup_sack);
1789fda03fbbSBaruch Even 			}
17906a438bbeSStephen Hemminger 
179168f8353bSIlpo Järvinen 			/* Rest of the block already fully processed? */
179220de20beSIlpo Järvinen 			if (!after(end_seq, cache->end_seq))
179320de20beSIlpo Järvinen 				goto advance_sp;
179420de20beSIlpo Järvinen 
1795056834d9SIlpo Järvinen 			skb = tcp_maybe_skipping_dsack(skb, sk, next_dup,
1796196da974SKenneth Klette Jonassen 						       state,
1797a1197f5aSIlpo Järvinen 						       cache->end_seq);
179868f8353bSIlpo Järvinen 
179968f8353bSIlpo Järvinen 			/* ...tail remains todo... */
18006859d494SIlpo Järvinen 			if (tcp_highest_sack_seq(tp) == cache->end_seq) {
180120de20beSIlpo Järvinen 				/* ...but better entrypoint exists! */
18026859d494SIlpo Järvinen 				skb = tcp_highest_sack(sk);
180351456b29SIan Morris 				if (!skb)
18046859d494SIlpo Järvinen 					break;
1805196da974SKenneth Klette Jonassen 				state->fack_count = tp->fackets_out;
180668f8353bSIlpo Järvinen 				cache++;
180768f8353bSIlpo Järvinen 				goto walk;
1808e56d6cd6SIlpo Järvinen 			}
1809e56d6cd6SIlpo Järvinen 
1810196da974SKenneth Klette Jonassen 			skb = tcp_sacktag_skip(skb, sk, state, cache->end_seq);
181168f8353bSIlpo Järvinen 			/* Check overlap against next cached too (past this one already) */
181268f8353bSIlpo Järvinen 			cache++;
181368f8353bSIlpo Järvinen 			continue;
18141da177e4SLinus Torvalds 		}
1815fbd52eb2SIlpo Järvinen 
18166859d494SIlpo Järvinen 		if (!before(start_seq, tcp_highest_sack_seq(tp))) {
18176859d494SIlpo Järvinen 			skb = tcp_highest_sack(sk);
181851456b29SIan Morris 			if (!skb)
18196859d494SIlpo Järvinen 				break;
1820196da974SKenneth Klette Jonassen 			state->fack_count = tp->fackets_out;
182168f8353bSIlpo Järvinen 		}
1822196da974SKenneth Klette Jonassen 		skb = tcp_sacktag_skip(skb, sk, state, start_seq);
182368f8353bSIlpo Järvinen 
182468f8353bSIlpo Järvinen walk:
1825196da974SKenneth Klette Jonassen 		skb = tcp_sacktag_walk(skb, sk, next_dup, state,
1826a1197f5aSIlpo Järvinen 				       start_seq, end_seq, dup_sack);
182768f8353bSIlpo Järvinen 
182868f8353bSIlpo Järvinen advance_sp:
182968f8353bSIlpo Järvinen 		i++;
18301da177e4SLinus Torvalds 	}
18311da177e4SLinus Torvalds 
183268f8353bSIlpo Järvinen 	/* Clear the head of the cache sack blocks so we can skip it next time */
183368f8353bSIlpo Järvinen 	for (i = 0; i < ARRAY_SIZE(tp->recv_sack_cache) - used_sacks; i++) {
183468f8353bSIlpo Järvinen 		tp->recv_sack_cache[i].start_seq = 0;
183568f8353bSIlpo Järvinen 		tp->recv_sack_cache[i].end_seq = 0;
183668f8353bSIlpo Järvinen 	}
183768f8353bSIlpo Järvinen 	for (j = 0; j < used_sacks; j++)
183868f8353bSIlpo Järvinen 		tp->recv_sack_cache[i++] = sp[j];
183968f8353bSIlpo Järvinen 
1840196da974SKenneth Klette Jonassen 	if ((state->reord < tp->fackets_out) &&
18419b44190dSYuchung Cheng 	    ((inet_csk(sk)->icsk_ca_state != TCP_CA_Loss) || tp->undo_marker))
1842196da974SKenneth Klette Jonassen 		tcp_update_reordering(sk, tp->fackets_out - state->reord, 0);
18431da177e4SLinus Torvalds 
18449dac8835SYuchung Cheng 	tcp_verify_left_out(tp);
184596a2d41aSIlpo Järvinen out:
184696a2d41aSIlpo Järvinen 
18471da177e4SLinus Torvalds #if FASTRETRANS_DEBUG > 0
1848547b792cSIlpo Järvinen 	WARN_ON((int)tp->sacked_out < 0);
1849547b792cSIlpo Järvinen 	WARN_ON((int)tp->lost_out < 0);
1850547b792cSIlpo Järvinen 	WARN_ON((int)tp->retrans_out < 0);
1851547b792cSIlpo Järvinen 	WARN_ON((int)tcp_packets_in_flight(tp) < 0);
18521da177e4SLinus Torvalds #endif
1853196da974SKenneth Klette Jonassen 	return state->flag;
18541da177e4SLinus Torvalds }
18551da177e4SLinus Torvalds 
1856882bebaaSIlpo Järvinen /* Limits sacked_out so that sum with lost_out isn't ever larger than
1857a2a385d6SEric Dumazet  * packets_out. Returns false if sacked_out adjustement wasn't necessary.
185830935cf4SIlpo Järvinen  */
1859a2a385d6SEric Dumazet static bool tcp_limit_reno_sacked(struct tcp_sock *tp)
18604ddf6676SIlpo Järvinen {
18614ddf6676SIlpo Järvinen 	u32 holes;
18624ddf6676SIlpo Järvinen 
18634ddf6676SIlpo Järvinen 	holes = max(tp->lost_out, 1U);
18644ddf6676SIlpo Järvinen 	holes = min(holes, tp->packets_out);
18654ddf6676SIlpo Järvinen 
18664ddf6676SIlpo Järvinen 	if ((tp->sacked_out + holes) > tp->packets_out) {
18674ddf6676SIlpo Järvinen 		tp->sacked_out = tp->packets_out - holes;
1868a2a385d6SEric Dumazet 		return true;
18694ddf6676SIlpo Järvinen 	}
1870a2a385d6SEric Dumazet 	return false;
1871882bebaaSIlpo Järvinen }
1872882bebaaSIlpo Järvinen 
1873882bebaaSIlpo Järvinen /* If we receive more dupacks than we expected counting segments
1874882bebaaSIlpo Järvinen  * in assumption of absent reordering, interpret this as reordering.
1875882bebaaSIlpo Järvinen  * The only another reason could be bug in receiver TCP.
1876882bebaaSIlpo Järvinen  */
1877882bebaaSIlpo Järvinen static void tcp_check_reno_reordering(struct sock *sk, const int addend)
1878882bebaaSIlpo Järvinen {
1879882bebaaSIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
1880882bebaaSIlpo Järvinen 	if (tcp_limit_reno_sacked(tp))
1881882bebaaSIlpo Järvinen 		tcp_update_reordering(sk, tp->packets_out + addend, 0);
18824ddf6676SIlpo Järvinen }
18834ddf6676SIlpo Järvinen 
18844ddf6676SIlpo Järvinen /* Emulate SACKs for SACKless connection: account for a new dupack. */
18854ddf6676SIlpo Järvinen 
18864ddf6676SIlpo Järvinen static void tcp_add_reno_sack(struct sock *sk)
18874ddf6676SIlpo Järvinen {
18884ddf6676SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
1889ddf1af6fSYuchung Cheng 	u32 prior_sacked = tp->sacked_out;
1890ddf1af6fSYuchung Cheng 
18914ddf6676SIlpo Järvinen 	tp->sacked_out++;
18924ddf6676SIlpo Järvinen 	tcp_check_reno_reordering(sk, 0);
1893ddf1af6fSYuchung Cheng 	if (tp->sacked_out > prior_sacked)
1894ddf1af6fSYuchung Cheng 		tp->delivered++; /* Some out-of-order packet is delivered */
1895005903bcSIlpo Järvinen 	tcp_verify_left_out(tp);
18964ddf6676SIlpo Järvinen }
18974ddf6676SIlpo Järvinen 
18984ddf6676SIlpo Järvinen /* Account for ACK, ACKing some data in Reno Recovery phase. */
18994ddf6676SIlpo Järvinen 
19004ddf6676SIlpo Järvinen static void tcp_remove_reno_sacks(struct sock *sk, int acked)
19014ddf6676SIlpo Järvinen {
19024ddf6676SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
19034ddf6676SIlpo Järvinen 
19044ddf6676SIlpo Järvinen 	if (acked > 0) {
19054ddf6676SIlpo Järvinen 		/* One ACK acked hole. The rest eat duplicate ACKs. */
1906ddf1af6fSYuchung Cheng 		tp->delivered += max_t(int, acked - tp->sacked_out, 1);
19074ddf6676SIlpo Järvinen 		if (acked - 1 >= tp->sacked_out)
19084ddf6676SIlpo Järvinen 			tp->sacked_out = 0;
19094ddf6676SIlpo Järvinen 		else
19104ddf6676SIlpo Järvinen 			tp->sacked_out -= acked - 1;
19114ddf6676SIlpo Järvinen 	}
19124ddf6676SIlpo Järvinen 	tcp_check_reno_reordering(sk, acked);
1913005903bcSIlpo Järvinen 	tcp_verify_left_out(tp);
19144ddf6676SIlpo Järvinen }
19154ddf6676SIlpo Järvinen 
19164ddf6676SIlpo Järvinen static inline void tcp_reset_reno_sack(struct tcp_sock *tp)
19174ddf6676SIlpo Järvinen {
19184ddf6676SIlpo Järvinen 	tp->sacked_out = 0;
19194ddf6676SIlpo Järvinen }
19204ddf6676SIlpo Järvinen 
1921989e04c5SYuchung Cheng void tcp_clear_retrans(struct tcp_sock *tp)
19221da177e4SLinus Torvalds {
19231da177e4SLinus Torvalds 	tp->retrans_out = 0;
19241da177e4SLinus Torvalds 	tp->lost_out = 0;
19251da177e4SLinus Torvalds 	tp->undo_marker = 0;
19266e08d5e3SYuchung Cheng 	tp->undo_retrans = -1;
19274cd82999SIlpo Järvinen 	tp->fackets_out = 0;
19284cd82999SIlpo Järvinen 	tp->sacked_out = 0;
19294cd82999SIlpo Järvinen }
19304cd82999SIlpo Järvinen 
1931989e04c5SYuchung Cheng static inline void tcp_init_undo(struct tcp_sock *tp)
1932989e04c5SYuchung Cheng {
1933989e04c5SYuchung Cheng 	tp->undo_marker = tp->snd_una;
1934989e04c5SYuchung Cheng 	/* Retransmission still in flight may cause DSACKs later. */
1935989e04c5SYuchung Cheng 	tp->undo_retrans = tp->retrans_out ? : -1;
1936989e04c5SYuchung Cheng }
1937989e04c5SYuchung Cheng 
19385ae344c9SNeal Cardwell /* Enter Loss state. If we detect SACK reneging, forget all SACK information
19391da177e4SLinus Torvalds  * and reset tags completely, otherwise preserve SACKs. If receiver
19401da177e4SLinus Torvalds  * dropped its ofo queue, we will know this due to reneging detection.
19411da177e4SLinus Torvalds  */
19425ae344c9SNeal Cardwell void tcp_enter_loss(struct sock *sk)
19431da177e4SLinus Torvalds {
19446687e988SArnaldo Carvalho de Melo 	const struct inet_connection_sock *icsk = inet_csk(sk);
19451da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
19461043e25fSNikolay Borisov 	struct net *net = sock_net(sk);
19471da177e4SLinus Torvalds 	struct sk_buff *skb;
1948cc663f4dSYuchung Cheng 	bool new_recovery = icsk->icsk_ca_state < TCP_CA_Recovery;
19495ae344c9SNeal Cardwell 	bool is_reneg;			/* is receiver reneging on SACKs? */
19500682e690SNeal Cardwell 	bool mark_lost;
19511da177e4SLinus Torvalds 
19521da177e4SLinus Torvalds 	/* Reduce ssthresh if it has not yet been made inside this window. */
1953e33099f9SYuchung Cheng 	if (icsk->icsk_ca_state <= TCP_CA_Disorder ||
1954e33099f9SYuchung Cheng 	    !after(tp->high_seq, tp->snd_una) ||
19556687e988SArnaldo Carvalho de Melo 	    (icsk->icsk_ca_state == TCP_CA_Loss && !icsk->icsk_retransmits)) {
19566687e988SArnaldo Carvalho de Melo 		tp->prior_ssthresh = tcp_current_ssthresh(sk);
19576687e988SArnaldo Carvalho de Melo 		tp->snd_ssthresh = icsk->icsk_ca_ops->ssthresh(sk);
19586687e988SArnaldo Carvalho de Melo 		tcp_ca_event(sk, CA_EVENT_LOSS);
1959989e04c5SYuchung Cheng 		tcp_init_undo(tp);
19601da177e4SLinus Torvalds 	}
19611da177e4SLinus Torvalds 	tp->snd_cwnd	   = 1;
19621da177e4SLinus Torvalds 	tp->snd_cwnd_cnt   = 0;
1963c2203cf7SEric Dumazet 	tp->snd_cwnd_stamp = tcp_jiffies32;
19641da177e4SLinus Torvalds 
1965989e04c5SYuchung Cheng 	tp->retrans_out = 0;
1966989e04c5SYuchung Cheng 	tp->lost_out = 0;
19674cd82999SIlpo Järvinen 
19684cd82999SIlpo Järvinen 	if (tcp_is_reno(tp))
19694cd82999SIlpo Järvinen 		tcp_reset_reno_sack(tp);
19701da177e4SLinus Torvalds 
19715ae344c9SNeal Cardwell 	skb = tcp_write_queue_head(sk);
19725ae344c9SNeal Cardwell 	is_reneg = skb && (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED);
19735ae344c9SNeal Cardwell 	if (is_reneg) {
1974c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPSACKRENEGING);
19754cd82999SIlpo Järvinen 		tp->sacked_out = 0;
19764cd82999SIlpo Järvinen 		tp->fackets_out = 0;
1977b7689205SIlpo Järvinen 	}
197864edc273SIlpo Järvinen 	tcp_clear_all_retrans_hints(tp);
19791da177e4SLinus Torvalds 
1980fe067e8aSDavid S. Miller 	tcp_for_write_queue(skb, sk) {
1981fe067e8aSDavid S. Miller 		if (skb == tcp_send_head(sk))
1982fe067e8aSDavid S. Miller 			break;
19834cd82999SIlpo Järvinen 
19840682e690SNeal Cardwell 		mark_lost = (!(TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED) ||
19850682e690SNeal Cardwell 			     is_reneg);
19860682e690SNeal Cardwell 		if (mark_lost)
19870682e690SNeal Cardwell 			tcp_sum_lost(tp, skb);
19881da177e4SLinus Torvalds 		TCP_SKB_CB(skb)->sacked &= (~TCPCB_TAGBITS)|TCPCB_SACKED_ACKED;
19890682e690SNeal Cardwell 		if (mark_lost) {
19901da177e4SLinus Torvalds 			TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_ACKED;
19911da177e4SLinus Torvalds 			TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
19921da177e4SLinus Torvalds 			tp->lost_out += tcp_skb_pcount(skb);
19931da177e4SLinus Torvalds 		}
19941da177e4SLinus Torvalds 	}
1995005903bcSIlpo Järvinen 	tcp_verify_left_out(tp);
19961da177e4SLinus Torvalds 
199774c181d5SYuchung Cheng 	/* Timeout in disordered state after receiving substantial DUPACKs
199874c181d5SYuchung Cheng 	 * suggests that the degree of reordering is over-estimated.
199974c181d5SYuchung Cheng 	 */
200074c181d5SYuchung Cheng 	if (icsk->icsk_ca_state <= TCP_CA_Disorder &&
20011043e25fSNikolay Borisov 	    tp->sacked_out >= net->ipv4.sysctl_tcp_reordering)
20021da177e4SLinus Torvalds 		tp->reordering = min_t(unsigned int, tp->reordering,
20031043e25fSNikolay Borisov 				       net->ipv4.sysctl_tcp_reordering);
20046687e988SArnaldo Carvalho de Melo 	tcp_set_ca_state(sk, TCP_CA_Loss);
20051da177e4SLinus Torvalds 	tp->high_seq = tp->snd_nxt;
2006735d3831SFlorian Westphal 	tcp_ecn_queue_cwr(tp);
2007e33099f9SYuchung Cheng 
2008cc663f4dSYuchung Cheng 	/* F-RTO RFC5682 sec 3.1 step 1: retransmit SND.UNA if no previous
2009cc663f4dSYuchung Cheng 	 * loss recovery is underway except recurring timeout(s) on
2010cc663f4dSYuchung Cheng 	 * the same SND.UNA (sec 3.2). Disable F-RTO on path MTU probing
2011cc663f4dSYuchung Cheng 	 *
2012cc663f4dSYuchung Cheng 	 * In theory F-RTO can be used repeatedly during loss recovery.
2013cc663f4dSYuchung Cheng 	 * In practice this interacts badly with broken middle-boxes that
2014cc663f4dSYuchung Cheng 	 * falsely raise the receive window, which results in repeated
2015cc663f4dSYuchung Cheng 	 * timeouts and stop-and-go behavior.
2016e33099f9SYuchung Cheng 	 */
2017cc663f4dSYuchung Cheng 	tp->frto = sysctl_tcp_frto &&
2018cc663f4dSYuchung Cheng 		   (new_recovery || icsk->icsk_retransmits) &&
2019cc663f4dSYuchung Cheng 		   !inet_csk(sk)->icsk_mtup.probe_size;
20201da177e4SLinus Torvalds }
20211da177e4SLinus Torvalds 
2022cadbd031SIlpo Järvinen /* If ACK arrived pointing to a remembered SACK, it means that our
2023cadbd031SIlpo Järvinen  * remembered SACKs do not reflect real state of receiver i.e.
20241da177e4SLinus Torvalds  * receiver _host_ is heavily congested (or buggy).
2025cadbd031SIlpo Järvinen  *
20265ae344c9SNeal Cardwell  * To avoid big spurious retransmission bursts due to transient SACK
20275ae344c9SNeal Cardwell  * scoreboard oddities that look like reneging, we give the receiver a
20285ae344c9SNeal Cardwell  * little time (max(RTT/2, 10ms)) to send us some more ACKs that will
20295ae344c9SNeal Cardwell  * restore sanity to the SACK scoreboard. If the apparent reneging
20305ae344c9SNeal Cardwell  * persists until this RTO then we'll clear the SACK scoreboard.
20311da177e4SLinus Torvalds  */
2032a2a385d6SEric Dumazet static bool tcp_check_sack_reneging(struct sock *sk, int flag)
2033cadbd031SIlpo Järvinen {
2034cadbd031SIlpo Järvinen 	if (flag & FLAG_SACK_RENEGING) {
20355ae344c9SNeal Cardwell 		struct tcp_sock *tp = tcp_sk(sk);
20365ae344c9SNeal Cardwell 		unsigned long delay = max(usecs_to_jiffies(tp->srtt_us >> 4),
20375ae344c9SNeal Cardwell 					  msecs_to_jiffies(10));
20381da177e4SLinus Torvalds 
2039463c84b9SArnaldo Carvalho de Melo 		inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
20405ae344c9SNeal Cardwell 					  delay, TCP_RTO_MAX);
2041a2a385d6SEric Dumazet 		return true;
20421da177e4SLinus Torvalds 	}
2043a2a385d6SEric Dumazet 	return false;
20441da177e4SLinus Torvalds }
20451da177e4SLinus Torvalds 
2046cf533ea5SEric Dumazet static inline int tcp_fackets_out(const struct tcp_sock *tp)
20471da177e4SLinus Torvalds {
2048e60402d0SIlpo Järvinen 	return tcp_is_reno(tp) ? tp->sacked_out + 1 : tp->fackets_out;
20491da177e4SLinus Torvalds }
20501da177e4SLinus Torvalds 
205185cc391cSIlpo Järvinen /* Heurestics to calculate number of duplicate ACKs. There's no dupACKs
205285cc391cSIlpo Järvinen  * counter when SACK is enabled (without SACK, sacked_out is used for
205385cc391cSIlpo Järvinen  * that purpose).
205485cc391cSIlpo Järvinen  *
205585cc391cSIlpo Järvinen  * Instead, with FACK TCP uses fackets_out that includes both SACKed
205685cc391cSIlpo Järvinen  * segments up to the highest received SACK block so far and holes in
205785cc391cSIlpo Järvinen  * between them.
205885cc391cSIlpo Järvinen  *
205985cc391cSIlpo Järvinen  * With reordering, holes may still be in flight, so RFC3517 recovery
206085cc391cSIlpo Järvinen  * uses pure sacked_out (total number of SACKed segments) even though
206185cc391cSIlpo Järvinen  * it violates the RFC that uses duplicate ACKs, often these are equal
206285cc391cSIlpo Järvinen  * but when e.g. out-of-window ACKs or packet duplication occurs,
206385cc391cSIlpo Järvinen  * they differ. Since neither occurs due to loss, TCP should really
206485cc391cSIlpo Järvinen  * ignore them.
206585cc391cSIlpo Järvinen  */
2066cf533ea5SEric Dumazet static inline int tcp_dupack_heuristics(const struct tcp_sock *tp)
206785cc391cSIlpo Järvinen {
206885cc391cSIlpo Järvinen 	return tcp_is_fack(tp) ? tp->fackets_out : tp->sacked_out + 1;
206985cc391cSIlpo Järvinen }
207085cc391cSIlpo Järvinen 
20711da177e4SLinus Torvalds /* Linux NewReno/SACK/FACK/ECN state machine.
20721da177e4SLinus Torvalds  * --------------------------------------
20731da177e4SLinus Torvalds  *
20741da177e4SLinus Torvalds  * "Open"	Normal state, no dubious events, fast path.
20751da177e4SLinus Torvalds  * "Disorder"   In all the respects it is "Open",
20761da177e4SLinus Torvalds  *		but requires a bit more attention. It is entered when
20771da177e4SLinus Torvalds  *		we see some SACKs or dupacks. It is split of "Open"
20781da177e4SLinus Torvalds  *		mainly to move some processing from fast path to slow one.
20791da177e4SLinus Torvalds  * "CWR"	CWND was reduced due to some Congestion Notification event.
20801da177e4SLinus Torvalds  *		It can be ECN, ICMP source quench, local device congestion.
20811da177e4SLinus Torvalds  * "Recovery"	CWND was reduced, we are fast-retransmitting.
20821da177e4SLinus Torvalds  * "Loss"	CWND was reduced due to RTO timeout or SACK reneging.
20831da177e4SLinus Torvalds  *
20841da177e4SLinus Torvalds  * tcp_fastretrans_alert() is entered:
20851da177e4SLinus Torvalds  * - each incoming ACK, if state is not "Open"
20861da177e4SLinus Torvalds  * - when arrived ACK is unusual, namely:
20871da177e4SLinus Torvalds  *	* SACK
20881da177e4SLinus Torvalds  *	* Duplicate ACK.
20891da177e4SLinus Torvalds  *	* ECN ECE.
20901da177e4SLinus Torvalds  *
20911da177e4SLinus Torvalds  * Counting packets in flight is pretty simple.
20921da177e4SLinus Torvalds  *
20931da177e4SLinus Torvalds  *	in_flight = packets_out - left_out + retrans_out
20941da177e4SLinus Torvalds  *
20951da177e4SLinus Torvalds  *	packets_out is SND.NXT-SND.UNA counted in packets.
20961da177e4SLinus Torvalds  *
20971da177e4SLinus Torvalds  *	retrans_out is number of retransmitted segments.
20981da177e4SLinus Torvalds  *
20991da177e4SLinus Torvalds  *	left_out is number of segments left network, but not ACKed yet.
21001da177e4SLinus Torvalds  *
21011da177e4SLinus Torvalds  *		left_out = sacked_out + lost_out
21021da177e4SLinus Torvalds  *
21031da177e4SLinus Torvalds  *     sacked_out: Packets, which arrived to receiver out of order
21041da177e4SLinus Torvalds  *		   and hence not ACKed. With SACKs this number is simply
21051da177e4SLinus Torvalds  *		   amount of SACKed data. Even without SACKs
21061da177e4SLinus Torvalds  *		   it is easy to give pretty reliable estimate of this number,
21071da177e4SLinus Torvalds  *		   counting duplicate ACKs.
21081da177e4SLinus Torvalds  *
21091da177e4SLinus Torvalds  *       lost_out: Packets lost by network. TCP has no explicit
21101da177e4SLinus Torvalds  *		   "loss notification" feedback from network (for now).
21111da177e4SLinus Torvalds  *		   It means that this number can be only _guessed_.
21121da177e4SLinus Torvalds  *		   Actually, it is the heuristics to predict lossage that
21131da177e4SLinus Torvalds  *		   distinguishes different algorithms.
21141da177e4SLinus Torvalds  *
21151da177e4SLinus Torvalds  *	F.e. after RTO, when all the queue is considered as lost,
21161da177e4SLinus Torvalds  *	lost_out = packets_out and in_flight = retrans_out.
21171da177e4SLinus Torvalds  *
2118a0370b3fSYuchung Cheng  *		Essentially, we have now a few algorithms detecting
21191da177e4SLinus Torvalds  *		lost packets.
21201da177e4SLinus Torvalds  *
2121a0370b3fSYuchung Cheng  *		If the receiver supports SACK:
2122a0370b3fSYuchung Cheng  *
2123a0370b3fSYuchung Cheng  *		RFC6675/3517: It is the conventional algorithm. A packet is
2124a0370b3fSYuchung Cheng  *		considered lost if the number of higher sequence packets
2125a0370b3fSYuchung Cheng  *		SACKed is greater than or equal the DUPACK thoreshold
2126a0370b3fSYuchung Cheng  *		(reordering). This is implemented in tcp_mark_head_lost and
2127a0370b3fSYuchung Cheng  *		tcp_update_scoreboard.
2128a0370b3fSYuchung Cheng  *
2129a0370b3fSYuchung Cheng  *		RACK (draft-ietf-tcpm-rack-01): it is a newer algorithm
2130a0370b3fSYuchung Cheng  *		(2017-) that checks timing instead of counting DUPACKs.
2131a0370b3fSYuchung Cheng  *		Essentially a packet is considered lost if it's not S/ACKed
2132a0370b3fSYuchung Cheng  *		after RTT + reordering_window, where both metrics are
2133a0370b3fSYuchung Cheng  *		dynamically measured and adjusted. This is implemented in
2134a0370b3fSYuchung Cheng  *		tcp_rack_mark_lost.
2135a0370b3fSYuchung Cheng  *
213694bdc978SYuchung Cheng  *		FACK (Disabled by default. Subsumbed by RACK):
213794bdc978SYuchung Cheng  *		It is the simplest heuristics. As soon as we decided
21381da177e4SLinus Torvalds  *		that something is lost, we decide that _all_ not SACKed
21391da177e4SLinus Torvalds  *		packets until the most forward SACK are lost. I.e.
21401da177e4SLinus Torvalds  *		lost_out = fackets_out - sacked_out and left_out = fackets_out.
21411da177e4SLinus Torvalds  *		It is absolutely correct estimate, if network does not reorder
21421da177e4SLinus Torvalds  *		packets. And it loses any connection to reality when reordering
21431da177e4SLinus Torvalds  *		takes place. We use FACK by default until reordering
21441da177e4SLinus Torvalds  *		is suspected on the path to this destination.
21451da177e4SLinus Torvalds  *
2146a0370b3fSYuchung Cheng  *		If the receiver does not support SACK:
2147a0370b3fSYuchung Cheng  *
2148a0370b3fSYuchung Cheng  *		NewReno (RFC6582): in Recovery we assume that one segment
21491da177e4SLinus Torvalds  *		is lost (classic Reno). While we are in Recovery and
21501da177e4SLinus Torvalds  *		a partial ACK arrives, we assume that one more packet
21511da177e4SLinus Torvalds  *		is lost (NewReno). This heuristics are the same in NewReno
21521da177e4SLinus Torvalds  *		and SACK.
21531da177e4SLinus Torvalds  *
21541da177e4SLinus Torvalds  * Really tricky (and requiring careful tuning) part of algorithm
21551da177e4SLinus Torvalds  * is hidden in functions tcp_time_to_recover() and tcp_xmit_retransmit_queue().
21561da177e4SLinus Torvalds  * The first determines the moment _when_ we should reduce CWND and,
21571da177e4SLinus Torvalds  * hence, slow down forward transmission. In fact, it determines the moment
21581da177e4SLinus Torvalds  * when we decide that hole is caused by loss, rather than by a reorder.
21591da177e4SLinus Torvalds  *
21601da177e4SLinus Torvalds  * tcp_xmit_retransmit_queue() decides, _what_ we should retransmit to fill
21611da177e4SLinus Torvalds  * holes, caused by lost packets.
21621da177e4SLinus Torvalds  *
21631da177e4SLinus Torvalds  * And the most logically complicated part of algorithm is undo
21641da177e4SLinus Torvalds  * heuristics. We detect false retransmits due to both too early
21651da177e4SLinus Torvalds  * fast retransmit (reordering) and underestimated RTO, analyzing
21661da177e4SLinus Torvalds  * timestamps and D-SACKs. When we detect that some segments were
21671da177e4SLinus Torvalds  * retransmitted by mistake and CWND reduction was wrong, we undo
21681da177e4SLinus Torvalds  * window reduction and abort recovery phase. This logic is hidden
21691da177e4SLinus Torvalds  * inside several functions named tcp_try_undo_<something>.
21701da177e4SLinus Torvalds  */
21711da177e4SLinus Torvalds 
21721da177e4SLinus Torvalds /* This function decides, when we should leave Disordered state
21731da177e4SLinus Torvalds  * and enter Recovery phase, reducing congestion window.
21741da177e4SLinus Torvalds  *
21751da177e4SLinus Torvalds  * Main question: may we further continue forward transmission
21761da177e4SLinus Torvalds  * with the same cwnd?
21771da177e4SLinus Torvalds  */
2178a2a385d6SEric Dumazet static bool tcp_time_to_recover(struct sock *sk, int flag)
21791da177e4SLinus Torvalds {
21809e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
21811da177e4SLinus Torvalds 
21821da177e4SLinus Torvalds 	/* Trick#1: The loss is proven. */
21831da177e4SLinus Torvalds 	if (tp->lost_out)
2184a2a385d6SEric Dumazet 		return true;
21851da177e4SLinus Torvalds 
21861da177e4SLinus Torvalds 	/* Not-A-Trick#2 : Classic rule... */
2187ea84e555SAndreas Petlund 	if (tcp_dupack_heuristics(tp) > tp->reordering)
2188a2a385d6SEric Dumazet 		return true;
21891da177e4SLinus Torvalds 
2190a2a385d6SEric Dumazet 	return false;
21911da177e4SLinus Torvalds }
21921da177e4SLinus Torvalds 
2193974c1236SYuchung Cheng /* Detect loss in event "A" above by marking head of queue up as lost.
2194974c1236SYuchung Cheng  * For FACK or non-SACK(Reno) senders, the first "packets" number of segments
2195974c1236SYuchung Cheng  * are considered lost. For RFC3517 SACK, a segment is considered lost if it
2196974c1236SYuchung Cheng  * has at least tp->reordering SACKed seqments above it; "packets" refers to
2197974c1236SYuchung Cheng  * the maximum SACKed segments to pass before reaching this limit.
219885cc391cSIlpo Järvinen  */
21991fdb9361SIlpo Järvinen static void tcp_mark_head_lost(struct sock *sk, int packets, int mark_head)
22001da177e4SLinus Torvalds {
22019e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
22021da177e4SLinus Torvalds 	struct sk_buff *skb;
2203d88270eeSNeal Cardwell 	int cnt, oldcnt, lost;
2204c137f3ddSIlpo Järvinen 	unsigned int mss;
2205974c1236SYuchung Cheng 	/* Use SACK to deduce losses of new sequences sent during recovery */
2206974c1236SYuchung Cheng 	const u32 loss_high = tcp_is_sack(tp) ?  tp->snd_nxt : tp->high_seq;
22071da177e4SLinus Torvalds 
2208547b792cSIlpo Järvinen 	WARN_ON(packets > tp->packets_out);
22096a438bbeSStephen Hemminger 	if (tp->lost_skb_hint) {
22106a438bbeSStephen Hemminger 		skb = tp->lost_skb_hint;
22116a438bbeSStephen Hemminger 		cnt = tp->lost_cnt_hint;
22121fdb9361SIlpo Järvinen 		/* Head already handled? */
22131fdb9361SIlpo Järvinen 		if (mark_head && skb != tcp_write_queue_head(sk))
22141fdb9361SIlpo Järvinen 			return;
22156a438bbeSStephen Hemminger 	} else {
2216fe067e8aSDavid S. Miller 		skb = tcp_write_queue_head(sk);
22176a438bbeSStephen Hemminger 		cnt = 0;
22186a438bbeSStephen Hemminger 	}
22191da177e4SLinus Torvalds 
2220fe067e8aSDavid S. Miller 	tcp_for_write_queue_from(skb, sk) {
2221fe067e8aSDavid S. Miller 		if (skb == tcp_send_head(sk))
2222fe067e8aSDavid S. Miller 			break;
22236a438bbeSStephen Hemminger 		/* TODO: do this better */
22246a438bbeSStephen Hemminger 		/* this is not the most efficient way to do this... */
22256a438bbeSStephen Hemminger 		tp->lost_skb_hint = skb;
22266a438bbeSStephen Hemminger 		tp->lost_cnt_hint = cnt;
222785cc391cSIlpo Järvinen 
2228974c1236SYuchung Cheng 		if (after(TCP_SKB_CB(skb)->end_seq, loss_high))
2229c137f3ddSIlpo Järvinen 			break;
2230c137f3ddSIlpo Järvinen 
2231c137f3ddSIlpo Järvinen 		oldcnt = cnt;
2232ad1984e8SIlpo Järvinen 		if (tcp_is_fack(tp) || tcp_is_reno(tp) ||
223385cc391cSIlpo Järvinen 		    (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED))
22346a438bbeSStephen Hemminger 			cnt += tcp_skb_pcount(skb);
223585cc391cSIlpo Järvinen 
2236c137f3ddSIlpo Järvinen 		if (cnt > packets) {
2237b3de7559SYuchung Cheng 			if ((tcp_is_sack(tp) && !tcp_is_fack(tp)) ||
2238c0638c24SNeal Cardwell 			    (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED) ||
2239b3de7559SYuchung Cheng 			    (oldcnt >= packets))
22401da177e4SLinus Torvalds 				break;
2241c137f3ddSIlpo Järvinen 
2242f69ad292SEric Dumazet 			mss = tcp_skb_mss(skb);
2243d88270eeSNeal Cardwell 			/* If needed, chop off the prefix to mark as lost. */
2244d88270eeSNeal Cardwell 			lost = (packets - oldcnt) * mss;
2245d88270eeSNeal Cardwell 			if (lost < skb->len &&
2246d88270eeSNeal Cardwell 			    tcp_fragment(sk, skb, lost, mss, GFP_ATOMIC) < 0)
2247c137f3ddSIlpo Järvinen 				break;
2248c137f3ddSIlpo Järvinen 			cnt = packets;
2249c137f3ddSIlpo Järvinen 		}
2250c137f3ddSIlpo Järvinen 
225141ea36e3SIlpo Järvinen 		tcp_skb_mark_lost(tp, skb);
22521fdb9361SIlpo Järvinen 
22531fdb9361SIlpo Järvinen 		if (mark_head)
22541fdb9361SIlpo Järvinen 			break;
22551da177e4SLinus Torvalds 	}
2256005903bcSIlpo Järvinen 	tcp_verify_left_out(tp);
22571da177e4SLinus Torvalds }
22581da177e4SLinus Torvalds 
22591da177e4SLinus Torvalds /* Account newly detected lost packet(s) */
22601da177e4SLinus Torvalds 
226185cc391cSIlpo Järvinen static void tcp_update_scoreboard(struct sock *sk, int fast_rexmit)
22621da177e4SLinus Torvalds {
22639e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
22649e412ba7SIlpo Järvinen 
226585cc391cSIlpo Järvinen 	if (tcp_is_reno(tp)) {
22661fdb9361SIlpo Järvinen 		tcp_mark_head_lost(sk, 1, 1);
226785cc391cSIlpo Järvinen 	} else if (tcp_is_fack(tp)) {
22681da177e4SLinus Torvalds 		int lost = tp->fackets_out - tp->reordering;
22691da177e4SLinus Torvalds 		if (lost <= 0)
22701da177e4SLinus Torvalds 			lost = 1;
22711fdb9361SIlpo Järvinen 		tcp_mark_head_lost(sk, lost, 0);
22721da177e4SLinus Torvalds 	} else {
227385cc391cSIlpo Järvinen 		int sacked_upto = tp->sacked_out - tp->reordering;
22741fdb9361SIlpo Järvinen 		if (sacked_upto >= 0)
22751fdb9361SIlpo Järvinen 			tcp_mark_head_lost(sk, sacked_upto, 0);
22761fdb9361SIlpo Järvinen 		else if (fast_rexmit)
22771fdb9361SIlpo Järvinen 			tcp_mark_head_lost(sk, 1, 1);
22781da177e4SLinus Torvalds 	}
22791da177e4SLinus Torvalds }
22801da177e4SLinus Torvalds 
228177c63127SYuchung Cheng static bool tcp_tsopt_ecr_before(const struct tcp_sock *tp, u32 when)
228277c63127SYuchung Cheng {
228377c63127SYuchung Cheng 	return tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr &&
228477c63127SYuchung Cheng 	       before(tp->rx_opt.rcv_tsecr, when);
228577c63127SYuchung Cheng }
228677c63127SYuchung Cheng 
2287659a8ad5SYuchung Cheng /* skb is spurious retransmitted if the returned timestamp echo
2288659a8ad5SYuchung Cheng  * reply is prior to the skb transmission time
2289659a8ad5SYuchung Cheng  */
2290659a8ad5SYuchung Cheng static bool tcp_skb_spurious_retrans(const struct tcp_sock *tp,
2291659a8ad5SYuchung Cheng 				     const struct sk_buff *skb)
2292659a8ad5SYuchung Cheng {
2293659a8ad5SYuchung Cheng 	return (TCP_SKB_CB(skb)->sacked & TCPCB_RETRANS) &&
2294659a8ad5SYuchung Cheng 	       tcp_tsopt_ecr_before(tp, tcp_skb_timestamp(skb));
2295659a8ad5SYuchung Cheng }
2296659a8ad5SYuchung Cheng 
22971da177e4SLinus Torvalds /* Nothing was retransmitted or returned timestamp is less
22981da177e4SLinus Torvalds  * than timestamp of the first retransmission.
22991da177e4SLinus Torvalds  */
230067b95bd7SVijay Subramanian static inline bool tcp_packet_delayed(const struct tcp_sock *tp)
23011da177e4SLinus Torvalds {
23021da177e4SLinus Torvalds 	return !tp->retrans_stamp ||
230377c63127SYuchung Cheng 	       tcp_tsopt_ecr_before(tp, tp->retrans_stamp);
23041da177e4SLinus Torvalds }
23051da177e4SLinus Torvalds 
23061da177e4SLinus Torvalds /* Undo procedures. */
23071da177e4SLinus Torvalds 
23081f37bf87SMarcelo Leitner /* We can clear retrans_stamp when there are no retransmissions in the
23091f37bf87SMarcelo Leitner  * window. It would seem that it is trivially available for us in
23101f37bf87SMarcelo Leitner  * tp->retrans_out, however, that kind of assumptions doesn't consider
23111f37bf87SMarcelo Leitner  * what will happen if errors occur when sending retransmission for the
23121f37bf87SMarcelo Leitner  * second time. ...It could the that such segment has only
23131f37bf87SMarcelo Leitner  * TCPCB_EVER_RETRANS set at the present time. It seems that checking
23141f37bf87SMarcelo Leitner  * the head skb is enough except for some reneging corner cases that
23151f37bf87SMarcelo Leitner  * are not worth the effort.
23161f37bf87SMarcelo Leitner  *
23171f37bf87SMarcelo Leitner  * Main reason for all this complexity is the fact that connection dying
23181f37bf87SMarcelo Leitner  * time now depends on the validity of the retrans_stamp, in particular,
23191f37bf87SMarcelo Leitner  * that successive retransmissions of a segment must not advance
23201f37bf87SMarcelo Leitner  * retrans_stamp under any conditions.
23211f37bf87SMarcelo Leitner  */
23221f37bf87SMarcelo Leitner static bool tcp_any_retrans_done(const struct sock *sk)
23231f37bf87SMarcelo Leitner {
23241f37bf87SMarcelo Leitner 	const struct tcp_sock *tp = tcp_sk(sk);
23251f37bf87SMarcelo Leitner 	struct sk_buff *skb;
23261f37bf87SMarcelo Leitner 
23271f37bf87SMarcelo Leitner 	if (tp->retrans_out)
23281f37bf87SMarcelo Leitner 		return true;
23291f37bf87SMarcelo Leitner 
23301f37bf87SMarcelo Leitner 	skb = tcp_write_queue_head(sk);
23311f37bf87SMarcelo Leitner 	if (unlikely(skb && TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS))
23321f37bf87SMarcelo Leitner 		return true;
23331f37bf87SMarcelo Leitner 
23341f37bf87SMarcelo Leitner 	return false;
23351f37bf87SMarcelo Leitner }
23361f37bf87SMarcelo Leitner 
23371da177e4SLinus Torvalds #if FASTRETRANS_DEBUG > 1
23389e412ba7SIlpo Järvinen static void DBGUNDO(struct sock *sk, const char *msg)
23391da177e4SLinus Torvalds {
23409e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
23411da177e4SLinus Torvalds 	struct inet_sock *inet = inet_sk(sk);
23429e412ba7SIlpo Järvinen 
2343569508c9SYOSHIFUJI Hideaki 	if (sk->sk_family == AF_INET) {
234491df42beSJoe Perches 		pr_debug("Undo %s %pI4/%u c%u l%u ss%u/%u p%u\n",
23451da177e4SLinus Torvalds 			 msg,
2346288fcee8SJoe Perches 			 &inet->inet_daddr, ntohs(inet->inet_dport),
234783ae4088SIlpo Järvinen 			 tp->snd_cwnd, tcp_left_out(tp),
23481da177e4SLinus Torvalds 			 tp->snd_ssthresh, tp->prior_ssthresh,
23491da177e4SLinus Torvalds 			 tp->packets_out);
23501da177e4SLinus Torvalds 	}
2351dfd56b8bSEric Dumazet #if IS_ENABLED(CONFIG_IPV6)
2352569508c9SYOSHIFUJI Hideaki 	else if (sk->sk_family == AF_INET6) {
235391df42beSJoe Perches 		pr_debug("Undo %s %pI6/%u c%u l%u ss%u/%u p%u\n",
2354569508c9SYOSHIFUJI Hideaki 			 msg,
2355019b1c9fSEric Dumazet 			 &sk->sk_v6_daddr, ntohs(inet->inet_dport),
2356569508c9SYOSHIFUJI Hideaki 			 tp->snd_cwnd, tcp_left_out(tp),
2357569508c9SYOSHIFUJI Hideaki 			 tp->snd_ssthresh, tp->prior_ssthresh,
2358569508c9SYOSHIFUJI Hideaki 			 tp->packets_out);
2359569508c9SYOSHIFUJI Hideaki 	}
2360569508c9SYOSHIFUJI Hideaki #endif
2361569508c9SYOSHIFUJI Hideaki }
23621da177e4SLinus Torvalds #else
23631da177e4SLinus Torvalds #define DBGUNDO(x...) do { } while (0)
23641da177e4SLinus Torvalds #endif
23651da177e4SLinus Torvalds 
23667026b912SYuchung Cheng static void tcp_undo_cwnd_reduction(struct sock *sk, bool unmark_loss)
23671da177e4SLinus Torvalds {
23686687e988SArnaldo Carvalho de Melo 	struct tcp_sock *tp = tcp_sk(sk);
23696687e988SArnaldo Carvalho de Melo 
23706a63df46SYuchung Cheng 	if (unmark_loss) {
23716a63df46SYuchung Cheng 		struct sk_buff *skb;
23726a63df46SYuchung Cheng 
23736a63df46SYuchung Cheng 		tcp_for_write_queue(skb, sk) {
23746a63df46SYuchung Cheng 			if (skb == tcp_send_head(sk))
23756a63df46SYuchung Cheng 				break;
23766a63df46SYuchung Cheng 			TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
23776a63df46SYuchung Cheng 		}
23786a63df46SYuchung Cheng 		tp->lost_out = 0;
23796a63df46SYuchung Cheng 		tcp_clear_all_retrans_hints(tp);
23806a63df46SYuchung Cheng 	}
23816a63df46SYuchung Cheng 
23821da177e4SLinus Torvalds 	if (tp->prior_ssthresh) {
23836687e988SArnaldo Carvalho de Melo 		const struct inet_connection_sock *icsk = inet_csk(sk);
23846687e988SArnaldo Carvalho de Melo 
23856687e988SArnaldo Carvalho de Melo 		tp->snd_cwnd = icsk->icsk_ca_ops->undo_cwnd(sk);
23861da177e4SLinus Torvalds 
23877026b912SYuchung Cheng 		if (tp->prior_ssthresh > tp->snd_ssthresh) {
23881da177e4SLinus Torvalds 			tp->snd_ssthresh = tp->prior_ssthresh;
2389735d3831SFlorian Westphal 			tcp_ecn_withdraw_cwr(tp);
23901da177e4SLinus Torvalds 		}
23911da177e4SLinus Torvalds 	}
2392c2203cf7SEric Dumazet 	tp->snd_cwnd_stamp = tcp_jiffies32;
23936a63df46SYuchung Cheng 	tp->undo_marker = 0;
23941da177e4SLinus Torvalds }
23951da177e4SLinus Torvalds 
239667b95bd7SVijay Subramanian static inline bool tcp_may_undo(const struct tcp_sock *tp)
23971da177e4SLinus Torvalds {
2398056834d9SIlpo Järvinen 	return tp->undo_marker && (!tp->undo_retrans || tcp_packet_delayed(tp));
23991da177e4SLinus Torvalds }
24001da177e4SLinus Torvalds 
24011da177e4SLinus Torvalds /* People celebrate: "We love our President!" */
2402a2a385d6SEric Dumazet static bool tcp_try_undo_recovery(struct sock *sk)
24031da177e4SLinus Torvalds {
24049e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
24059e412ba7SIlpo Järvinen 
24061da177e4SLinus Torvalds 	if (tcp_may_undo(tp)) {
240740b215e5SPavel Emelyanov 		int mib_idx;
240840b215e5SPavel Emelyanov 
24091da177e4SLinus Torvalds 		/* Happy end! We did not retransmit anything
24101da177e4SLinus Torvalds 		 * or our original transmission succeeded.
24111da177e4SLinus Torvalds 		 */
24129e412ba7SIlpo Järvinen 		DBGUNDO(sk, inet_csk(sk)->icsk_ca_state == TCP_CA_Loss ? "loss" : "retrans");
24137026b912SYuchung Cheng 		tcp_undo_cwnd_reduction(sk, false);
24146687e988SArnaldo Carvalho de Melo 		if (inet_csk(sk)->icsk_ca_state == TCP_CA_Loss)
241540b215e5SPavel Emelyanov 			mib_idx = LINUX_MIB_TCPLOSSUNDO;
24161da177e4SLinus Torvalds 		else
241740b215e5SPavel Emelyanov 			mib_idx = LINUX_MIB_TCPFULLUNDO;
241840b215e5SPavel Emelyanov 
2419c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), mib_idx);
24201da177e4SLinus Torvalds 	}
2421e60402d0SIlpo Järvinen 	if (tp->snd_una == tp->high_seq && tcp_is_reno(tp)) {
24221da177e4SLinus Torvalds 		/* Hold old state until something *above* high_seq
24231da177e4SLinus Torvalds 		 * is ACKed. For Reno it is MUST to prevent false
24241da177e4SLinus Torvalds 		 * fast retransmits (RFC2582). SACK TCP is safe. */
24251f37bf87SMarcelo Leitner 		if (!tcp_any_retrans_done(sk))
24261f37bf87SMarcelo Leitner 			tp->retrans_stamp = 0;
2427a2a385d6SEric Dumazet 		return true;
24281da177e4SLinus Torvalds 	}
24296687e988SArnaldo Carvalho de Melo 	tcp_set_ca_state(sk, TCP_CA_Open);
2430a2a385d6SEric Dumazet 	return false;
24311da177e4SLinus Torvalds }
24321da177e4SLinus Torvalds 
24331da177e4SLinus Torvalds /* Try to undo cwnd reduction, because D-SACKs acked all retransmitted data */
2434c7d9d6a1SYuchung Cheng static bool tcp_try_undo_dsack(struct sock *sk)
24351da177e4SLinus Torvalds {
24369e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
24379e412ba7SIlpo Järvinen 
24381da177e4SLinus Torvalds 	if (tp->undo_marker && !tp->undo_retrans) {
24399e412ba7SIlpo Järvinen 		DBGUNDO(sk, "D-SACK");
24407026b912SYuchung Cheng 		tcp_undo_cwnd_reduction(sk, false);
2441c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKUNDO);
2442c7d9d6a1SYuchung Cheng 		return true;
24431da177e4SLinus Torvalds 	}
2444c7d9d6a1SYuchung Cheng 	return false;
24451da177e4SLinus Torvalds }
24461da177e4SLinus Torvalds 
2447e33099f9SYuchung Cheng /* Undo during loss recovery after partial ACK or using F-RTO. */
2448e33099f9SYuchung Cheng static bool tcp_try_undo_loss(struct sock *sk, bool frto_undo)
24491da177e4SLinus Torvalds {
24509e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
24519e412ba7SIlpo Järvinen 
2452e33099f9SYuchung Cheng 	if (frto_undo || tcp_may_undo(tp)) {
24537026b912SYuchung Cheng 		tcp_undo_cwnd_reduction(sk, true);
24546a438bbeSStephen Hemminger 
24559e412ba7SIlpo Järvinen 		DBGUNDO(sk, "partial loss");
2456c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPLOSSUNDO);
2457e33099f9SYuchung Cheng 		if (frto_undo)
2458c10d9310SEric Dumazet 			NET_INC_STATS(sock_net(sk),
2459e33099f9SYuchung Cheng 					LINUX_MIB_TCPSPURIOUSRTOS);
2460463c84b9SArnaldo Carvalho de Melo 		inet_csk(sk)->icsk_retransmits = 0;
2461e33099f9SYuchung Cheng 		if (frto_undo || tcp_is_sack(tp))
24626687e988SArnaldo Carvalho de Melo 			tcp_set_ca_state(sk, TCP_CA_Open);
2463a2a385d6SEric Dumazet 		return true;
24641da177e4SLinus Torvalds 	}
2465a2a385d6SEric Dumazet 	return false;
24661da177e4SLinus Torvalds }
24671da177e4SLinus Torvalds 
24683759824dSYuchung Cheng /* The cwnd reduction in CWR and Recovery uses the PRR algorithm in RFC 6937.
2469fb4d3d1dSYuchung Cheng  * It computes the number of packets to send (sndcnt) based on packets newly
2470fb4d3d1dSYuchung Cheng  * delivered:
2471fb4d3d1dSYuchung Cheng  *   1) If the packets in flight is larger than ssthresh, PRR spreads the
2472fb4d3d1dSYuchung Cheng  *	cwnd reductions across a full RTT.
24733759824dSYuchung Cheng  *   2) Otherwise PRR uses packet conservation to send as much as delivered.
24743759824dSYuchung Cheng  *      But when the retransmits are acked without further losses, PRR
24753759824dSYuchung Cheng  *      slow starts cwnd up to ssthresh to speed up the recovery.
2476fb4d3d1dSYuchung Cheng  */
24775ee2c941SChristoph Paasch static void tcp_init_cwnd_reduction(struct sock *sk)
2478684bad11SYuchung Cheng {
2479684bad11SYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
2480684bad11SYuchung Cheng 
2481684bad11SYuchung Cheng 	tp->high_seq = tp->snd_nxt;
24829b717a8dSNandita Dukkipati 	tp->tlp_high_seq = 0;
2483684bad11SYuchung Cheng 	tp->snd_cwnd_cnt = 0;
2484684bad11SYuchung Cheng 	tp->prior_cwnd = tp->snd_cwnd;
2485684bad11SYuchung Cheng 	tp->prr_delivered = 0;
2486684bad11SYuchung Cheng 	tp->prr_out = 0;
2487684bad11SYuchung Cheng 	tp->snd_ssthresh = inet_csk(sk)->icsk_ca_ops->ssthresh(sk);
2488735d3831SFlorian Westphal 	tcp_ecn_queue_cwr(tp);
2489684bad11SYuchung Cheng }
2490684bad11SYuchung Cheng 
249157dde7f7SYuchung Cheng void tcp_cwnd_reduction(struct sock *sk, int newly_acked_sacked, int flag)
2492fb4d3d1dSYuchung Cheng {
2493fb4d3d1dSYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
2494fb4d3d1dSYuchung Cheng 	int sndcnt = 0;
2495fb4d3d1dSYuchung Cheng 	int delta = tp->snd_ssthresh - tcp_packets_in_flight(tp);
2496fb4d3d1dSYuchung Cheng 
24978b8a321fSYuchung Cheng 	if (newly_acked_sacked <= 0 || WARN_ON_ONCE(!tp->prior_cwnd))
24988b8a321fSYuchung Cheng 		return;
24998b8a321fSYuchung Cheng 
2500684bad11SYuchung Cheng 	tp->prr_delivered += newly_acked_sacked;
25013759824dSYuchung Cheng 	if (delta < 0) {
2502fb4d3d1dSYuchung Cheng 		u64 dividend = (u64)tp->snd_ssthresh * tp->prr_delivered +
2503fb4d3d1dSYuchung Cheng 			       tp->prior_cwnd - 1;
2504fb4d3d1dSYuchung Cheng 		sndcnt = div_u64(dividend, tp->prior_cwnd) - tp->prr_out;
25053759824dSYuchung Cheng 	} else if ((flag & FLAG_RETRANS_DATA_ACKED) &&
25063759824dSYuchung Cheng 		   !(flag & FLAG_LOST_RETRANS)) {
2507fb4d3d1dSYuchung Cheng 		sndcnt = min_t(int, delta,
2508fb4d3d1dSYuchung Cheng 			       max_t(int, tp->prr_delivered - tp->prr_out,
2509fb4d3d1dSYuchung Cheng 				     newly_acked_sacked) + 1);
25103759824dSYuchung Cheng 	} else {
25113759824dSYuchung Cheng 		sndcnt = min(delta, newly_acked_sacked);
2512fb4d3d1dSYuchung Cheng 	}
251331ba0c10SYuchung Cheng 	/* Force a fast retransmit upon entering fast recovery */
251431ba0c10SYuchung Cheng 	sndcnt = max(sndcnt, (tp->prr_out ? 0 : 1));
2515fb4d3d1dSYuchung Cheng 	tp->snd_cwnd = tcp_packets_in_flight(tp) + sndcnt;
2516fb4d3d1dSYuchung Cheng }
2517fb4d3d1dSYuchung Cheng 
2518684bad11SYuchung Cheng static inline void tcp_end_cwnd_reduction(struct sock *sk)
25191da177e4SLinus Torvalds {
25206687e988SArnaldo Carvalho de Melo 	struct tcp_sock *tp = tcp_sk(sk);
2521a262f0cdSNandita Dukkipati 
2522c0402760SYuchung Cheng 	if (inet_csk(sk)->icsk_ca_ops->cong_control)
2523c0402760SYuchung Cheng 		return;
2524c0402760SYuchung Cheng 
2525684bad11SYuchung Cheng 	/* Reset cwnd to ssthresh in CWR or Recovery (unless it's undone) */
2526684bad11SYuchung Cheng 	if (inet_csk(sk)->icsk_ca_state == TCP_CA_CWR ||
2527684bad11SYuchung Cheng 	    (tp->undo_marker && tp->snd_ssthresh < TCP_INFINITE_SSTHRESH)) {
252867d4120aSYuchung Cheng 		tp->snd_cwnd = tp->snd_ssthresh;
2529c2203cf7SEric Dumazet 		tp->snd_cwnd_stamp = tcp_jiffies32;
253067d4120aSYuchung Cheng 	}
25316687e988SArnaldo Carvalho de Melo 	tcp_ca_event(sk, CA_EVENT_COMPLETE_CWR);
25321da177e4SLinus Torvalds }
25331da177e4SLinus Torvalds 
2534684bad11SYuchung Cheng /* Enter CWR state. Disable cwnd undo since congestion is proven with ECN */
25355ee2c941SChristoph Paasch void tcp_enter_cwr(struct sock *sk)
253609484d1fSYuchung Cheng {
253709484d1fSYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
253809484d1fSYuchung Cheng 
253909484d1fSYuchung Cheng 	tp->prior_ssthresh = 0;
2540684bad11SYuchung Cheng 	if (inet_csk(sk)->icsk_ca_state < TCP_CA_CWR) {
254109484d1fSYuchung Cheng 		tp->undo_marker = 0;
25425ee2c941SChristoph Paasch 		tcp_init_cwnd_reduction(sk);
254309484d1fSYuchung Cheng 		tcp_set_ca_state(sk, TCP_CA_CWR);
254409484d1fSYuchung Cheng 	}
254509484d1fSYuchung Cheng }
25467782ad8bSKenneth Klette Jonassen EXPORT_SYMBOL(tcp_enter_cwr);
254709484d1fSYuchung Cheng 
25488aca6cb1SIlpo Järvinen static void tcp_try_keep_open(struct sock *sk)
25498aca6cb1SIlpo Järvinen {
25508aca6cb1SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
25518aca6cb1SIlpo Järvinen 	int state = TCP_CA_Open;
25528aca6cb1SIlpo Järvinen 
2553f698204bSNeal Cardwell 	if (tcp_left_out(tp) || tcp_any_retrans_done(sk))
25548aca6cb1SIlpo Järvinen 		state = TCP_CA_Disorder;
25558aca6cb1SIlpo Järvinen 
25568aca6cb1SIlpo Järvinen 	if (inet_csk(sk)->icsk_ca_state != state) {
25578aca6cb1SIlpo Järvinen 		tcp_set_ca_state(sk, state);
25588aca6cb1SIlpo Järvinen 		tp->high_seq = tp->snd_nxt;
25598aca6cb1SIlpo Järvinen 	}
25608aca6cb1SIlpo Järvinen }
25618aca6cb1SIlpo Järvinen 
256231ba0c10SYuchung Cheng static void tcp_try_to_open(struct sock *sk, int flag)
25631da177e4SLinus Torvalds {
25649e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
25659e412ba7SIlpo Järvinen 
256686426c22SIlpo Järvinen 	tcp_verify_left_out(tp);
256786426c22SIlpo Järvinen 
25689b44190dSYuchung Cheng 	if (!tcp_any_retrans_done(sk))
25691da177e4SLinus Torvalds 		tp->retrans_stamp = 0;
25701da177e4SLinus Torvalds 
25711da177e4SLinus Torvalds 	if (flag & FLAG_ECE)
25725ee2c941SChristoph Paasch 		tcp_enter_cwr(sk);
25731da177e4SLinus Torvalds 
25746687e988SArnaldo Carvalho de Melo 	if (inet_csk(sk)->icsk_ca_state != TCP_CA_CWR) {
25758aca6cb1SIlpo Järvinen 		tcp_try_keep_open(sk);
25761da177e4SLinus Torvalds 	}
25771da177e4SLinus Torvalds }
25781da177e4SLinus Torvalds 
25795d424d5aSJohn Heffner static void tcp_mtup_probe_failed(struct sock *sk)
25805d424d5aSJohn Heffner {
25815d424d5aSJohn Heffner 	struct inet_connection_sock *icsk = inet_csk(sk);
25825d424d5aSJohn Heffner 
25835d424d5aSJohn Heffner 	icsk->icsk_mtup.search_high = icsk->icsk_mtup.probe_size - 1;
25845d424d5aSJohn Heffner 	icsk->icsk_mtup.probe_size = 0;
2585c10d9310SEric Dumazet 	NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMTUPFAIL);
25865d424d5aSJohn Heffner }
25875d424d5aSJohn Heffner 
258872211e90SIlpo Järvinen static void tcp_mtup_probe_success(struct sock *sk)
25895d424d5aSJohn Heffner {
25905d424d5aSJohn Heffner 	struct tcp_sock *tp = tcp_sk(sk);
25915d424d5aSJohn Heffner 	struct inet_connection_sock *icsk = inet_csk(sk);
25925d424d5aSJohn Heffner 
25935d424d5aSJohn Heffner 	/* FIXME: breaks with very large cwnd */
25945d424d5aSJohn Heffner 	tp->prior_ssthresh = tcp_current_ssthresh(sk);
25955d424d5aSJohn Heffner 	tp->snd_cwnd = tp->snd_cwnd *
25965d424d5aSJohn Heffner 		       tcp_mss_to_mtu(sk, tp->mss_cache) /
25975d424d5aSJohn Heffner 		       icsk->icsk_mtup.probe_size;
25985d424d5aSJohn Heffner 	tp->snd_cwnd_cnt = 0;
2599c2203cf7SEric Dumazet 	tp->snd_cwnd_stamp = tcp_jiffies32;
26009c6d5e55SJohn Heffner 	tp->snd_ssthresh = tcp_current_ssthresh(sk);
26015d424d5aSJohn Heffner 
26025d424d5aSJohn Heffner 	icsk->icsk_mtup.search_low = icsk->icsk_mtup.probe_size;
26035d424d5aSJohn Heffner 	icsk->icsk_mtup.probe_size = 0;
26045d424d5aSJohn Heffner 	tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
2605c10d9310SEric Dumazet 	NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMTUPSUCCESS);
26065d424d5aSJohn Heffner }
26075d424d5aSJohn Heffner 
2608e1aa680fSIlpo Järvinen /* Do a simple retransmit without using the backoff mechanisms in
2609e1aa680fSIlpo Järvinen  * tcp_timer. This is used for path mtu discovery.
2610e1aa680fSIlpo Järvinen  * The socket is already locked here.
2611e1aa680fSIlpo Järvinen  */
2612e1aa680fSIlpo Järvinen void tcp_simple_retransmit(struct sock *sk)
2613e1aa680fSIlpo Järvinen {
2614e1aa680fSIlpo Järvinen 	const struct inet_connection_sock *icsk = inet_csk(sk);
2615e1aa680fSIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
2616e1aa680fSIlpo Järvinen 	struct sk_buff *skb;
26170c54b85fSIlpo Järvinen 	unsigned int mss = tcp_current_mss(sk);
2618e1aa680fSIlpo Järvinen 	u32 prior_lost = tp->lost_out;
2619e1aa680fSIlpo Järvinen 
2620e1aa680fSIlpo Järvinen 	tcp_for_write_queue(skb, sk) {
2621e1aa680fSIlpo Järvinen 		if (skb == tcp_send_head(sk))
2622e1aa680fSIlpo Järvinen 			break;
2623775ffabfSIlpo Järvinen 		if (tcp_skb_seglen(skb) > mss &&
2624e1aa680fSIlpo Järvinen 		    !(TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)) {
2625e1aa680fSIlpo Järvinen 			if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS) {
2626e1aa680fSIlpo Järvinen 				TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
2627e1aa680fSIlpo Järvinen 				tp->retrans_out -= tcp_skb_pcount(skb);
2628e1aa680fSIlpo Järvinen 			}
2629e1aa680fSIlpo Järvinen 			tcp_skb_mark_lost_uncond_verify(tp, skb);
2630e1aa680fSIlpo Järvinen 		}
2631e1aa680fSIlpo Järvinen 	}
2632e1aa680fSIlpo Järvinen 
2633e1aa680fSIlpo Järvinen 	tcp_clear_retrans_hints_partial(tp);
2634e1aa680fSIlpo Järvinen 
2635e1aa680fSIlpo Järvinen 	if (prior_lost == tp->lost_out)
2636e1aa680fSIlpo Järvinen 		return;
2637e1aa680fSIlpo Järvinen 
2638e1aa680fSIlpo Järvinen 	if (tcp_is_reno(tp))
2639e1aa680fSIlpo Järvinen 		tcp_limit_reno_sacked(tp);
2640e1aa680fSIlpo Järvinen 
2641e1aa680fSIlpo Järvinen 	tcp_verify_left_out(tp);
2642e1aa680fSIlpo Järvinen 
2643e1aa680fSIlpo Järvinen 	/* Don't muck with the congestion window here.
2644e1aa680fSIlpo Järvinen 	 * Reason is that we do not increase amount of _data_
2645e1aa680fSIlpo Järvinen 	 * in network, but units changed and effective
2646e1aa680fSIlpo Järvinen 	 * cwnd/ssthresh really reduced now.
2647e1aa680fSIlpo Järvinen 	 */
2648e1aa680fSIlpo Järvinen 	if (icsk->icsk_ca_state != TCP_CA_Loss) {
2649e1aa680fSIlpo Järvinen 		tp->high_seq = tp->snd_nxt;
2650e1aa680fSIlpo Järvinen 		tp->snd_ssthresh = tcp_current_ssthresh(sk);
2651e1aa680fSIlpo Järvinen 		tp->prior_ssthresh = 0;
2652e1aa680fSIlpo Järvinen 		tp->undo_marker = 0;
2653e1aa680fSIlpo Järvinen 		tcp_set_ca_state(sk, TCP_CA_Loss);
2654e1aa680fSIlpo Järvinen 	}
2655e1aa680fSIlpo Järvinen 	tcp_xmit_retransmit_queue(sk);
2656e1aa680fSIlpo Järvinen }
26574bc2f18bSEric Dumazet EXPORT_SYMBOL(tcp_simple_retransmit);
2658e1aa680fSIlpo Järvinen 
265957dde7f7SYuchung Cheng void tcp_enter_recovery(struct sock *sk, bool ece_ack)
26601fbc3405SYuchung Cheng {
26611fbc3405SYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
26621fbc3405SYuchung Cheng 	int mib_idx;
26631fbc3405SYuchung Cheng 
26641fbc3405SYuchung Cheng 	if (tcp_is_reno(tp))
26651fbc3405SYuchung Cheng 		mib_idx = LINUX_MIB_TCPRENORECOVERY;
26661fbc3405SYuchung Cheng 	else
26671fbc3405SYuchung Cheng 		mib_idx = LINUX_MIB_TCPSACKRECOVERY;
26681fbc3405SYuchung Cheng 
2669c10d9310SEric Dumazet 	NET_INC_STATS(sock_net(sk), mib_idx);
26701fbc3405SYuchung Cheng 
26711fbc3405SYuchung Cheng 	tp->prior_ssthresh = 0;
2672989e04c5SYuchung Cheng 	tcp_init_undo(tp);
26731fbc3405SYuchung Cheng 
2674291a00d1SYuchung Cheng 	if (!tcp_in_cwnd_reduction(sk)) {
26751fbc3405SYuchung Cheng 		if (!ece_ack)
26761fbc3405SYuchung Cheng 			tp->prior_ssthresh = tcp_current_ssthresh(sk);
26775ee2c941SChristoph Paasch 		tcp_init_cwnd_reduction(sk);
26781fbc3405SYuchung Cheng 	}
26791fbc3405SYuchung Cheng 	tcp_set_ca_state(sk, TCP_CA_Recovery);
26801fbc3405SYuchung Cheng }
26811fbc3405SYuchung Cheng 
2682ab42d9eeSYuchung Cheng /* Process an ACK in CA_Loss state. Move to CA_Open if lost data are
2683ab42d9eeSYuchung Cheng  * recovered or spurious. Otherwise retransmits more on partial ACKs.
2684ab42d9eeSYuchung Cheng  */
2685e662ca40SYuchung Cheng static void tcp_process_loss(struct sock *sk, int flag, bool is_dupack,
2686e662ca40SYuchung Cheng 			     int *rexmit)
2687ab42d9eeSYuchung Cheng {
2688ab42d9eeSYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
2689e33099f9SYuchung Cheng 	bool recovered = !before(tp->snd_una, tp->high_seq);
2690ab42d9eeSYuchung Cheng 
2691da34ac76SYuchung Cheng 	if ((flag & FLAG_SND_UNA_ADVANCED) &&
2692da34ac76SYuchung Cheng 	    tcp_try_undo_loss(sk, false))
2693da34ac76SYuchung Cheng 		return;
2694da34ac76SYuchung Cheng 
269589fe18e4SYuchung Cheng 	/* The ACK (s)acks some never-retransmitted data meaning not all
269689fe18e4SYuchung Cheng 	 * the data packets before the timeout were lost. Therefore we
269789fe18e4SYuchung Cheng 	 * undo the congestion window and state. This is essentially
269889fe18e4SYuchung Cheng 	 * the operation in F-RTO (RFC5682 section 3.1 step 3.b). Since
269989fe18e4SYuchung Cheng 	 * a retransmitted skb is permantly marked, we can apply such an
270089fe18e4SYuchung Cheng 	 * operation even if F-RTO was not used.
2701e33099f9SYuchung Cheng 	 */
2702da34ac76SYuchung Cheng 	if ((flag & FLAG_ORIG_SACK_ACKED) &&
270389fe18e4SYuchung Cheng 	    tcp_try_undo_loss(sk, tp->undo_marker))
2704e33099f9SYuchung Cheng 		return;
27050cfa5c07SYuchung Cheng 
270689fe18e4SYuchung Cheng 	if (tp->frto) { /* F-RTO RFC5682 sec 3.1 (sack enhanced version). */
2707b7b0ed91SYuchung Cheng 		if (after(tp->snd_nxt, tp->high_seq)) {
2708b7b0ed91SYuchung Cheng 			if (flag & FLAG_DATA_SACKED || is_dupack)
2709b7b0ed91SYuchung Cheng 				tp->frto = 0; /* Step 3.a. loss was real */
2710e33099f9SYuchung Cheng 		} else if (flag & FLAG_SND_UNA_ADVANCED && !recovered) {
2711e33099f9SYuchung Cheng 			tp->high_seq = tp->snd_nxt;
2712e662ca40SYuchung Cheng 			/* Step 2.b. Try send new data (but deferred until cwnd
2713e662ca40SYuchung Cheng 			 * is updated in tcp_ack()). Otherwise fall back to
2714e662ca40SYuchung Cheng 			 * the conventional recovery.
2715e662ca40SYuchung Cheng 			 */
2716e662ca40SYuchung Cheng 			if (tcp_send_head(sk) &&
2717e662ca40SYuchung Cheng 			    after(tcp_wnd_end(tp), tp->snd_nxt)) {
2718e662ca40SYuchung Cheng 				*rexmit = REXMIT_NEW;
2719e662ca40SYuchung Cheng 				return;
2720e662ca40SYuchung Cheng 			}
2721e33099f9SYuchung Cheng 			tp->frto = 0;
2722e33099f9SYuchung Cheng 		}
2723e33099f9SYuchung Cheng 	}
2724e33099f9SYuchung Cheng 
2725e33099f9SYuchung Cheng 	if (recovered) {
2726e33099f9SYuchung Cheng 		/* F-RTO RFC5682 sec 3.1 step 2.a and 1st part of step 3.a */
2727ab42d9eeSYuchung Cheng 		tcp_try_undo_recovery(sk);
2728ab42d9eeSYuchung Cheng 		return;
2729ab42d9eeSYuchung Cheng 	}
2730e33099f9SYuchung Cheng 	if (tcp_is_reno(tp)) {
2731e33099f9SYuchung Cheng 		/* A Reno DUPACK means new data in F-RTO step 2.b above are
2732e33099f9SYuchung Cheng 		 * delivered. Lower inflight to clock out (re)tranmissions.
2733e33099f9SYuchung Cheng 		 */
2734e33099f9SYuchung Cheng 		if (after(tp->snd_nxt, tp->high_seq) && is_dupack)
2735e33099f9SYuchung Cheng 			tcp_add_reno_sack(sk);
2736e33099f9SYuchung Cheng 		else if (flag & FLAG_SND_UNA_ADVANCED)
2737ab42d9eeSYuchung Cheng 			tcp_reset_reno_sack(tp);
2738e33099f9SYuchung Cheng 	}
2739e662ca40SYuchung Cheng 	*rexmit = REXMIT_LOST;
2740ab42d9eeSYuchung Cheng }
2741ab42d9eeSYuchung Cheng 
27426a63df46SYuchung Cheng /* Undo during fast recovery after partial ACK. */
274331ba0c10SYuchung Cheng static bool tcp_try_undo_partial(struct sock *sk, const int acked)
27446a63df46SYuchung Cheng {
27456a63df46SYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
27466a63df46SYuchung Cheng 
27477026b912SYuchung Cheng 	if (tp->undo_marker && tcp_packet_delayed(tp)) {
27486a63df46SYuchung Cheng 		/* Plain luck! Hole if filled with delayed
27496a63df46SYuchung Cheng 		 * packet, rather than with a retransmit.
27506a63df46SYuchung Cheng 		 */
27517026b912SYuchung Cheng 		tcp_update_reordering(sk, tcp_fackets_out(tp) + acked, 1);
27527026b912SYuchung Cheng 
27537026b912SYuchung Cheng 		/* We are getting evidence that the reordering degree is higher
27547026b912SYuchung Cheng 		 * than we realized. If there are no retransmits out then we
27557026b912SYuchung Cheng 		 * can undo. Otherwise we clock out new packets but do not
27567026b912SYuchung Cheng 		 * mark more packets lost or retransmit more.
27577026b912SYuchung Cheng 		 */
275831ba0c10SYuchung Cheng 		if (tp->retrans_out)
27597026b912SYuchung Cheng 			return true;
27607026b912SYuchung Cheng 
27616a63df46SYuchung Cheng 		if (!tcp_any_retrans_done(sk))
27626a63df46SYuchung Cheng 			tp->retrans_stamp = 0;
27636a63df46SYuchung Cheng 
27647026b912SYuchung Cheng 		DBGUNDO(sk, "partial recovery");
27657026b912SYuchung Cheng 		tcp_undo_cwnd_reduction(sk, true);
2766c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPPARTIALUNDO);
27677026b912SYuchung Cheng 		tcp_try_keep_open(sk);
27687026b912SYuchung Cheng 		return true;
27696a63df46SYuchung Cheng 	}
27707026b912SYuchung Cheng 	return false;
27716a63df46SYuchung Cheng }
27726a63df46SYuchung Cheng 
2773efab8f85SEric Dumazet static void tcp_rack_identify_loss(struct sock *sk, int *ack_flag)
277498e36d44SYuchung Cheng {
277598e36d44SYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
277698e36d44SYuchung Cheng 
277798e36d44SYuchung Cheng 	/* Use RACK to detect loss */
2778a0370b3fSYuchung Cheng 	if (sysctl_tcp_recovery & TCP_RACK_LOSS_DETECTION) {
277998e36d44SYuchung Cheng 		u32 prior_retrans = tp->retrans_out;
278098e36d44SYuchung Cheng 
2781128eda86SEric Dumazet 		tcp_rack_mark_lost(sk);
278298e36d44SYuchung Cheng 		if (prior_retrans > tp->retrans_out)
278398e36d44SYuchung Cheng 			*ack_flag |= FLAG_LOST_RETRANS;
278498e36d44SYuchung Cheng 	}
278598e36d44SYuchung Cheng }
278698e36d44SYuchung Cheng 
27871da177e4SLinus Torvalds /* Process an event, which can update packets-in-flight not trivially.
27881da177e4SLinus Torvalds  * Main goal of this function is to calculate new estimate for left_out,
27891da177e4SLinus Torvalds  * taking into account both packets sitting in receiver's buffer and
27901da177e4SLinus Torvalds  * packets lost by network.
27911da177e4SLinus Torvalds  *
279231ba0c10SYuchung Cheng  * Besides that it updates the congestion state when packet loss or ECN
279331ba0c10SYuchung Cheng  * is detected. But it does not reduce the cwnd, it is done by the
279431ba0c10SYuchung Cheng  * congestion control later.
27951da177e4SLinus Torvalds  *
27961da177e4SLinus Torvalds  * It does _not_ decide what to send, it is made in function
27971da177e4SLinus Torvalds  * tcp_xmit_retransmit_queue().
27981da177e4SLinus Torvalds  */
27996804973fSYuchung Cheng static void tcp_fastretrans_alert(struct sock *sk, const int acked,
28001317a9d6SEric Dumazet 				  bool is_dupack, int *ack_flag, int *rexmit)
28011da177e4SLinus Torvalds {
28026687e988SArnaldo Carvalho de Melo 	struct inet_connection_sock *icsk = inet_csk(sk);
28031da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
280431ba0c10SYuchung Cheng 	int fast_rexmit = 0, flag = *ack_flag;
28056a63df46SYuchung Cheng 	bool do_lost = is_dupack || ((flag & FLAG_DATA_SACKED) &&
280685cc391cSIlpo Järvinen 				    (tcp_fackets_out(tp) > tp->reordering));
28071da177e4SLinus Torvalds 
28083ccd3130SIlpo Järvinen 	if (WARN_ON(!tp->packets_out && tp->sacked_out))
28091da177e4SLinus Torvalds 		tp->sacked_out = 0;
281091fed7a1SIlpo Järvinen 	if (WARN_ON(!tp->sacked_out && tp->fackets_out))
28111da177e4SLinus Torvalds 		tp->fackets_out = 0;
28121da177e4SLinus Torvalds 
28131da177e4SLinus Torvalds 	/* Now state machine starts.
28141da177e4SLinus Torvalds 	 * A. ECE, hence prohibit cwnd undoing, the reduction is required. */
28151da177e4SLinus Torvalds 	if (flag & FLAG_ECE)
28161da177e4SLinus Torvalds 		tp->prior_ssthresh = 0;
28171da177e4SLinus Torvalds 
28181da177e4SLinus Torvalds 	/* B. In all the states check for reneging SACKs. */
2819cadbd031SIlpo Järvinen 	if (tcp_check_sack_reneging(sk, flag))
28201da177e4SLinus Torvalds 		return;
28211da177e4SLinus Torvalds 
2822974c1236SYuchung Cheng 	/* C. Check consistency of the current state. */
2823005903bcSIlpo Järvinen 	tcp_verify_left_out(tp);
28241da177e4SLinus Torvalds 
2825974c1236SYuchung Cheng 	/* D. Check state exit conditions. State can be terminated
28261da177e4SLinus Torvalds 	 *    when high_seq is ACKed. */
28276687e988SArnaldo Carvalho de Melo 	if (icsk->icsk_ca_state == TCP_CA_Open) {
2828547b792cSIlpo Järvinen 		WARN_ON(tp->retrans_out != 0);
28291da177e4SLinus Torvalds 		tp->retrans_stamp = 0;
28301da177e4SLinus Torvalds 	} else if (!before(tp->snd_una, tp->high_seq)) {
28316687e988SArnaldo Carvalho de Melo 		switch (icsk->icsk_ca_state) {
28321da177e4SLinus Torvalds 		case TCP_CA_CWR:
28331da177e4SLinus Torvalds 			/* CWR is to be held something *above* high_seq
28341da177e4SLinus Torvalds 			 * is ACKed for CWR bit to reach receiver. */
28351da177e4SLinus Torvalds 			if (tp->snd_una != tp->high_seq) {
2836684bad11SYuchung Cheng 				tcp_end_cwnd_reduction(sk);
28376687e988SArnaldo Carvalho de Melo 				tcp_set_ca_state(sk, TCP_CA_Open);
28381da177e4SLinus Torvalds 			}
28391da177e4SLinus Torvalds 			break;
28401da177e4SLinus Torvalds 
28411da177e4SLinus Torvalds 		case TCP_CA_Recovery:
2842e60402d0SIlpo Järvinen 			if (tcp_is_reno(tp))
28431da177e4SLinus Torvalds 				tcp_reset_reno_sack(tp);
28449e412ba7SIlpo Järvinen 			if (tcp_try_undo_recovery(sk))
28451da177e4SLinus Torvalds 				return;
2846684bad11SYuchung Cheng 			tcp_end_cwnd_reduction(sk);
28471da177e4SLinus Torvalds 			break;
28481da177e4SLinus Torvalds 		}
28491da177e4SLinus Torvalds 	}
28501da177e4SLinus Torvalds 
2851974c1236SYuchung Cheng 	/* E. Process state. */
28526687e988SArnaldo Carvalho de Melo 	switch (icsk->icsk_ca_state) {
28531da177e4SLinus Torvalds 	case TCP_CA_Recovery:
28542e605294SIlpo Järvinen 		if (!(flag & FLAG_SND_UNA_ADVANCED)) {
2855e60402d0SIlpo Järvinen 			if (tcp_is_reno(tp) && is_dupack)
28566687e988SArnaldo Carvalho de Melo 				tcp_add_reno_sack(sk);
28577026b912SYuchung Cheng 		} else {
285831ba0c10SYuchung Cheng 			if (tcp_try_undo_partial(sk, acked))
28597026b912SYuchung Cheng 				return;
28607026b912SYuchung Cheng 			/* Partial ACK arrived. Force fast retransmit. */
28617026b912SYuchung Cheng 			do_lost = tcp_is_reno(tp) ||
28627026b912SYuchung Cheng 				  tcp_fackets_out(tp) > tp->reordering;
28637026b912SYuchung Cheng 		}
2864c7d9d6a1SYuchung Cheng 		if (tcp_try_undo_dsack(sk)) {
2865c7d9d6a1SYuchung Cheng 			tcp_try_keep_open(sk);
2866c7d9d6a1SYuchung Cheng 			return;
2867c7d9d6a1SYuchung Cheng 		}
2868efab8f85SEric Dumazet 		tcp_rack_identify_loss(sk, ack_flag);
28691da177e4SLinus Torvalds 		break;
28701da177e4SLinus Torvalds 	case TCP_CA_Loss:
2871e662ca40SYuchung Cheng 		tcp_process_loss(sk, flag, is_dupack, rexmit);
2872efab8f85SEric Dumazet 		tcp_rack_identify_loss(sk, ack_flag);
287398e36d44SYuchung Cheng 		if (!(icsk->icsk_ca_state == TCP_CA_Open ||
287498e36d44SYuchung Cheng 		      (*ack_flag & FLAG_LOST_RETRANS)))
28751da177e4SLinus Torvalds 			return;
2876291a00d1SYuchung Cheng 		/* Change state if cwnd is undone or retransmits are lost */
28771da177e4SLinus Torvalds 	default:
2878e60402d0SIlpo Järvinen 		if (tcp_is_reno(tp)) {
28792e605294SIlpo Järvinen 			if (flag & FLAG_SND_UNA_ADVANCED)
28801da177e4SLinus Torvalds 				tcp_reset_reno_sack(tp);
28811da177e4SLinus Torvalds 			if (is_dupack)
28826687e988SArnaldo Carvalho de Melo 				tcp_add_reno_sack(sk);
28831da177e4SLinus Torvalds 		}
28841da177e4SLinus Torvalds 
2885f698204bSNeal Cardwell 		if (icsk->icsk_ca_state <= TCP_CA_Disorder)
28869e412ba7SIlpo Järvinen 			tcp_try_undo_dsack(sk);
28871da177e4SLinus Torvalds 
2888efab8f85SEric Dumazet 		tcp_rack_identify_loss(sk, ack_flag);
2889750ea2baSYuchung Cheng 		if (!tcp_time_to_recover(sk, flag)) {
289031ba0c10SYuchung Cheng 			tcp_try_to_open(sk, flag);
28911da177e4SLinus Torvalds 			return;
28921da177e4SLinus Torvalds 		}
28931da177e4SLinus Torvalds 
28945d424d5aSJohn Heffner 		/* MTU probe failure: don't reduce cwnd */
28955d424d5aSJohn Heffner 		if (icsk->icsk_ca_state < TCP_CA_CWR &&
28965d424d5aSJohn Heffner 		    icsk->icsk_mtup.probe_size &&
28970e7b1368SJohn Heffner 		    tp->snd_una == tp->mtu_probe.probe_seq_start) {
28985d424d5aSJohn Heffner 			tcp_mtup_probe_failed(sk);
28995d424d5aSJohn Heffner 			/* Restores the reduction we did in tcp_mtup_probe() */
29005d424d5aSJohn Heffner 			tp->snd_cwnd++;
29015d424d5aSJohn Heffner 			tcp_simple_retransmit(sk);
29025d424d5aSJohn Heffner 			return;
29035d424d5aSJohn Heffner 		}
29045d424d5aSJohn Heffner 
29051da177e4SLinus Torvalds 		/* Otherwise enter Recovery state */
29061fbc3405SYuchung Cheng 		tcp_enter_recovery(sk, (flag & FLAG_ECE));
290785cc391cSIlpo Järvinen 		fast_rexmit = 1;
29081da177e4SLinus Torvalds 	}
29091da177e4SLinus Torvalds 
29103e59cb0dSYuchung Cheng 	if (do_lost)
291185cc391cSIlpo Järvinen 		tcp_update_scoreboard(sk, fast_rexmit);
2912e662ca40SYuchung Cheng 	*rexmit = REXMIT_LOST;
29131da177e4SLinus Torvalds }
29141da177e4SLinus Torvalds 
2915f6722583SYuchung Cheng static void tcp_update_rtt_min(struct sock *sk, u32 rtt_us)
2916f6722583SYuchung Cheng {
291764033892SNeal Cardwell 	struct tcp_sock *tp = tcp_sk(sk);
291864033892SNeal Cardwell 	u32 wlen = sysctl_tcp_min_rtt_wlen * HZ;
2919f6722583SYuchung Cheng 
2920ac9517fcSEric Dumazet 	minmax_running_min(&tp->rtt_min, wlen, tcp_jiffies32,
292164033892SNeal Cardwell 			   rtt_us ? : jiffies_to_usecs(1));
2922f6722583SYuchung Cheng }
2923f6722583SYuchung Cheng 
2924ed08495cSYuchung Cheng static inline bool tcp_ack_update_rtt(struct sock *sk, const int flag,
2925f6722583SYuchung Cheng 				      long seq_rtt_us, long sack_rtt_us,
2926f6722583SYuchung Cheng 				      long ca_rtt_us)
292741834b73SIlpo Järvinen {
29285b08e47cSYuchung Cheng 	const struct tcp_sock *tp = tcp_sk(sk);
292941834b73SIlpo Järvinen 
29305b08e47cSYuchung Cheng 	/* Prefer RTT measured from ACK's timing to TS-ECR. This is because
29315b08e47cSYuchung Cheng 	 * broken middle-boxes or peers may corrupt TS-ECR fields. But
29325b08e47cSYuchung Cheng 	 * Karn's algorithm forbids taking RTT if some retransmitted data
29335b08e47cSYuchung Cheng 	 * is acked (RFC6298).
29341da177e4SLinus Torvalds 	 */
2935740b0f18SEric Dumazet 	if (seq_rtt_us < 0)
2936740b0f18SEric Dumazet 		seq_rtt_us = sack_rtt_us;
2937ed08495cSYuchung Cheng 
29381da177e4SLinus Torvalds 	/* RTTM Rule: A TSecr value received in a segment is used to
29391da177e4SLinus Torvalds 	 * update the averaged RTT measurement only if the segment
29401da177e4SLinus Torvalds 	 * acknowledges some new data, i.e., only if it advances the
29411da177e4SLinus Torvalds 	 * left edge of the send window.
29421da177e4SLinus Torvalds 	 * See draft-ietf-tcplw-high-performance-00, section 3.3.
29431da177e4SLinus Torvalds 	 */
2944740b0f18SEric Dumazet 	if (seq_rtt_us < 0 && tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr &&
29459a568de4SEric Dumazet 	    flag & FLAG_ACKED) {
29469a568de4SEric Dumazet 		u32 delta = tcp_time_stamp(tp) - tp->rx_opt.rcv_tsecr;
29479a568de4SEric Dumazet 		u32 delta_us = delta * (USEC_PER_SEC / TCP_TS_HZ);
29489a568de4SEric Dumazet 
29499a568de4SEric Dumazet 		seq_rtt_us = ca_rtt_us = delta_us;
29509a568de4SEric Dumazet 	}
2951740b0f18SEric Dumazet 	if (seq_rtt_us < 0)
2952ed08495cSYuchung Cheng 		return false;
29531da177e4SLinus Torvalds 
2954f6722583SYuchung Cheng 	/* ca_rtt_us >= 0 is counting on the invariant that ca_rtt_us is
2955f6722583SYuchung Cheng 	 * always taken together with ACK, SACK, or TS-opts. Any negative
2956f6722583SYuchung Cheng 	 * values will be skipped with the seq_rtt_us < 0 check above.
2957f6722583SYuchung Cheng 	 */
2958f6722583SYuchung Cheng 	tcp_update_rtt_min(sk, ca_rtt_us);
2959740b0f18SEric Dumazet 	tcp_rtt_estimator(sk, seq_rtt_us);
29605b08e47cSYuchung Cheng 	tcp_set_rto(sk);
29611da177e4SLinus Torvalds 
29625b08e47cSYuchung Cheng 	/* RFC6298: only reset backoff on valid RTT measurement. */
29635b08e47cSYuchung Cheng 	inet_csk(sk)->icsk_backoff = 0;
2964ed08495cSYuchung Cheng 	return true;
29651da177e4SLinus Torvalds }
29661da177e4SLinus Torvalds 
2967375fe02cSYuchung Cheng /* Compute time elapsed between (last) SYNACK and the ACK completing 3WHS. */
29680f1c28aeSYuchung Cheng void tcp_synack_rtt_meas(struct sock *sk, struct request_sock *req)
2969375fe02cSYuchung Cheng {
29700f1c28aeSYuchung Cheng 	long rtt_us = -1L;
2971375fe02cSYuchung Cheng 
29729a568de4SEric Dumazet 	if (req && !req->num_retrans && tcp_rsk(req)->snt_synack)
29739a568de4SEric Dumazet 		rtt_us = tcp_stamp_us_delta(tcp_clock_us(), tcp_rsk(req)->snt_synack);
2974375fe02cSYuchung Cheng 
2975f6722583SYuchung Cheng 	tcp_ack_update_rtt(sk, FLAG_SYN_ACKED, rtt_us, -1L, rtt_us);
29760f1c28aeSYuchung Cheng }
29770f1c28aeSYuchung Cheng 
29780f1c28aeSYuchung Cheng 
297924901551SEric Dumazet static void tcp_cong_avoid(struct sock *sk, u32 ack, u32 acked)
29801da177e4SLinus Torvalds {
29816687e988SArnaldo Carvalho de Melo 	const struct inet_connection_sock *icsk = inet_csk(sk);
298224901551SEric Dumazet 
298324901551SEric Dumazet 	icsk->icsk_ca_ops->cong_avoid(sk, ack, acked);
2984c2203cf7SEric Dumazet 	tcp_sk(sk)->snd_cwnd_stamp = tcp_jiffies32;
29851da177e4SLinus Torvalds }
29861da177e4SLinus Torvalds 
29871da177e4SLinus Torvalds /* Restart timer after forward progress on connection.
29881da177e4SLinus Torvalds  * RFC2988 recommends to restart timer to now+rto.
29891da177e4SLinus Torvalds  */
2990750ea2baSYuchung Cheng void tcp_rearm_rto(struct sock *sk)
29911da177e4SLinus Torvalds {
29926ba8a3b1SNandita Dukkipati 	const struct inet_connection_sock *icsk = inet_csk(sk);
2993750ea2baSYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
29949e412ba7SIlpo Järvinen 
2995168a8f58SJerry Chu 	/* If the retrans timer is currently being used by Fast Open
2996168a8f58SJerry Chu 	 * for SYN-ACK retrans purpose, stay put.
2997168a8f58SJerry Chu 	 */
2998168a8f58SJerry Chu 	if (tp->fastopen_rsk)
2999168a8f58SJerry Chu 		return;
3000168a8f58SJerry Chu 
30011da177e4SLinus Torvalds 	if (!tp->packets_out) {
3002463c84b9SArnaldo Carvalho de Melo 		inet_csk_clear_xmit_timer(sk, ICSK_TIME_RETRANS);
30031da177e4SLinus Torvalds 	} else {
3004750ea2baSYuchung Cheng 		u32 rto = inet_csk(sk)->icsk_rto;
3005750ea2baSYuchung Cheng 		/* Offset the time elapsed after installing regular RTO */
3006bec41a11SYuchung Cheng 		if (icsk->icsk_pending == ICSK_TIME_REO_TIMEOUT ||
30076ba8a3b1SNandita Dukkipati 		    icsk->icsk_pending == ICSK_TIME_LOSS_PROBE) {
3008750ea2baSYuchung Cheng 			struct sk_buff *skb = tcp_write_queue_head(sk);
3009b17b8a20SEric Dumazet 			u64 rto_time_stamp = skb->skb_mstamp +
3010b17b8a20SEric Dumazet 					     jiffies_to_usecs(rto);
3011b17b8a20SEric Dumazet 			s64 delta_us = rto_time_stamp - tp->tcp_mstamp;
3012b17b8a20SEric Dumazet 			/* delta_us may not be positive if the socket is locked
30136ba8a3b1SNandita Dukkipati 			 * when the retrans timer fires and is rescheduled.
3014750ea2baSYuchung Cheng 			 */
3015b17b8a20SEric Dumazet 			if (delta_us > 0)
3016b17b8a20SEric Dumazet 				rto = usecs_to_jiffies(delta_us);
30171da177e4SLinus Torvalds 		}
3018750ea2baSYuchung Cheng 		inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS, rto,
3019750ea2baSYuchung Cheng 					  TCP_RTO_MAX);
3020750ea2baSYuchung Cheng 	}
3021750ea2baSYuchung Cheng }
3022750ea2baSYuchung Cheng 
30237c46a03eSIlpo Järvinen /* If we get here, the whole TSO packet has not been acked. */
302413fcf850SIlpo Järvinen static u32 tcp_tso_acked(struct sock *sk, struct sk_buff *skb)
30251da177e4SLinus Torvalds {
30261da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
30277c46a03eSIlpo Järvinen 	u32 packets_acked;
30281da177e4SLinus Torvalds 
30297c46a03eSIlpo Järvinen 	BUG_ON(!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una));
30301da177e4SLinus Torvalds 
30311da177e4SLinus Torvalds 	packets_acked = tcp_skb_pcount(skb);
30327c46a03eSIlpo Järvinen 	if (tcp_trim_head(sk, skb, tp->snd_una - TCP_SKB_CB(skb)->seq))
30331da177e4SLinus Torvalds 		return 0;
30341da177e4SLinus Torvalds 	packets_acked -= tcp_skb_pcount(skb);
30351da177e4SLinus Torvalds 
30361da177e4SLinus Torvalds 	if (packets_acked) {
30371da177e4SLinus Torvalds 		BUG_ON(tcp_skb_pcount(skb) == 0);
30387c46a03eSIlpo Järvinen 		BUG_ON(!before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq));
30391da177e4SLinus Torvalds 	}
30401da177e4SLinus Torvalds 
304113fcf850SIlpo Järvinen 	return packets_acked;
30421da177e4SLinus Torvalds }
30431da177e4SLinus Torvalds 
3044ad971f61SEric Dumazet static void tcp_ack_tstamp(struct sock *sk, struct sk_buff *skb,
3045ad971f61SEric Dumazet 			   u32 prior_snd_una)
3046ad971f61SEric Dumazet {
3047ad971f61SEric Dumazet 	const struct skb_shared_info *shinfo;
3048ad971f61SEric Dumazet 
3049ad971f61SEric Dumazet 	/* Avoid cache line misses to get skb_shinfo() and shinfo->tx_flags */
30506b084928SSoheil Hassas Yeganeh 	if (likely(!TCP_SKB_CB(skb)->txstamp_ack))
3051ad971f61SEric Dumazet 		return;
3052ad971f61SEric Dumazet 
3053ad971f61SEric Dumazet 	shinfo = skb_shinfo(skb);
30540a2cf20cSSoheil Hassas Yeganeh 	if (!before(shinfo->tskey, prior_snd_una) &&
3055479f85c3SMartin KaFai Lau 	    before(shinfo->tskey, tcp_sk(sk)->snd_una))
3056ad971f61SEric Dumazet 		__skb_tstamp_tx(skb, NULL, sk, SCM_TSTAMP_ACK);
3057ad971f61SEric Dumazet }
3058ad971f61SEric Dumazet 
30597c46a03eSIlpo Järvinen /* Remove acknowledged frames from the retransmission queue. If our packet
30607c46a03eSIlpo Järvinen  * is before the ack sequence we can discard it as it's confirmed to have
30617c46a03eSIlpo Järvinen  * arrived at the other end.
30627c46a03eSIlpo Järvinen  */
306333f5f57eSIlpo Järvinen static int tcp_clean_rtx_queue(struct sock *sk, int prior_fackets,
30643ebd8871SYuchung Cheng 			       u32 prior_snd_una, int *acked,
3065deed7be7SYuchung Cheng 			       struct tcp_sacktag_state *sack)
30661da177e4SLinus Torvalds {
30672d2abbabSStephen Hemminger 	const struct inet_connection_sock *icsk = inet_csk(sk);
30689a568de4SEric Dumazet 	u64 first_ackt, last_ackt;
3069740b0f18SEric Dumazet 	struct tcp_sock *tp = tcp_sk(sk);
307090638a04SIlpo Järvinen 	u32 prior_sacked = tp->sacked_out;
3071740b0f18SEric Dumazet 	u32 reord = tp->packets_out;
3072740b0f18SEric Dumazet 	bool fully_acked = true;
307331231a8aSKenneth Klette Jonassen 	long sack_rtt_us = -1L;
3074740b0f18SEric Dumazet 	long seq_rtt_us = -1L;
307531231a8aSKenneth Klette Jonassen 	long ca_rtt_us = -1L;
3076740b0f18SEric Dumazet 	struct sk_buff *skb;
3077740b0f18SEric Dumazet 	u32 pkts_acked = 0;
30786f094b9eSLawrence Brakmo 	u32 last_in_flight = 0;
30792f715c1dSYuchung Cheng 	bool rtt_update;
3080740b0f18SEric Dumazet 	int flag = 0;
3081740b0f18SEric Dumazet 
30829a568de4SEric Dumazet 	first_ackt = 0;
30831da177e4SLinus Torvalds 
30847c46a03eSIlpo Järvinen 	while ((skb = tcp_write_queue_head(sk)) && skb != tcp_send_head(sk)) {
30851da177e4SLinus Torvalds 		struct tcp_skb_cb *scb = TCP_SKB_CB(skb);
30867c46a03eSIlpo Järvinen 		u8 sacked = scb->sacked;
3087740b0f18SEric Dumazet 		u32 acked_pcount;
30881da177e4SLinus Torvalds 
3089ad971f61SEric Dumazet 		tcp_ack_tstamp(sk, skb, prior_snd_una);
3090712a7221SWillem de Bruijn 
30912072c228SGavin McCullagh 		/* Determine how many packets and what bytes were acked, tso and else */
30921da177e4SLinus Torvalds 		if (after(scb->end_seq, tp->snd_una)) {
309313fcf850SIlpo Järvinen 			if (tcp_skb_pcount(skb) == 1 ||
309413fcf850SIlpo Järvinen 			    !after(tp->snd_una, scb->seq))
30951da177e4SLinus Torvalds 				break;
309613fcf850SIlpo Järvinen 
309772018835SIlpo Järvinen 			acked_pcount = tcp_tso_acked(sk, skb);
309872018835SIlpo Järvinen 			if (!acked_pcount)
309913fcf850SIlpo Järvinen 				break;
3100a2a385d6SEric Dumazet 			fully_acked = false;
310113fcf850SIlpo Järvinen 		} else {
3102ad971f61SEric Dumazet 			/* Speedup tcp_unlink_write_queue() and next loop */
3103ad971f61SEric Dumazet 			prefetchw(skb->next);
310472018835SIlpo Järvinen 			acked_pcount = tcp_skb_pcount(skb);
31051da177e4SLinus Torvalds 		}
31061da177e4SLinus Torvalds 
3107ad971f61SEric Dumazet 		if (unlikely(sacked & TCPCB_RETRANS)) {
31081da177e4SLinus Torvalds 			if (sacked & TCPCB_SACKED_RETRANS)
310972018835SIlpo Järvinen 				tp->retrans_out -= acked_pcount;
31107c46a03eSIlpo Järvinen 			flag |= FLAG_RETRANS_DATA_ACKED;
31113d0d26c7SKenneth Klette Jonassen 		} else if (!(sacked & TCPCB_SACKED_ACKED)) {
3112740b0f18SEric Dumazet 			last_ackt = skb->skb_mstamp;
31139a568de4SEric Dumazet 			WARN_ON_ONCE(last_ackt == 0);
31149a568de4SEric Dumazet 			if (!first_ackt)
3115740b0f18SEric Dumazet 				first_ackt = last_ackt;
3116740b0f18SEric Dumazet 
31176f094b9eSLawrence Brakmo 			last_in_flight = TCP_SKB_CB(skb)->tx.in_flight;
311872018835SIlpo Järvinen 			reord = min(pkts_acked, reord);
3119e33099f9SYuchung Cheng 			if (!after(scb->end_seq, tp->high_seq))
3120e33099f9SYuchung Cheng 				flag |= FLAG_ORIG_SACK_ACKED;
3121c7caf8d3SIlpo Järvinen 		}
31227c46a03eSIlpo Järvinen 
3123ddf1af6fSYuchung Cheng 		if (sacked & TCPCB_SACKED_ACKED) {
312472018835SIlpo Järvinen 			tp->sacked_out -= acked_pcount;
3125ddf1af6fSYuchung Cheng 		} else if (tcp_is_sack(tp)) {
3126ddf1af6fSYuchung Cheng 			tp->delivered += acked_pcount;
3127ddf1af6fSYuchung Cheng 			if (!tcp_skb_spurious_retrans(tp, skb))
31281d0833dfSYuchung Cheng 				tcp_rack_advance(tp, sacked, scb->end_seq,
31299a568de4SEric Dumazet 						 skb->skb_mstamp);
3130ddf1af6fSYuchung Cheng 		}
31311da177e4SLinus Torvalds 		if (sacked & TCPCB_LOST)
313272018835SIlpo Järvinen 			tp->lost_out -= acked_pcount;
31337c46a03eSIlpo Järvinen 
313472018835SIlpo Järvinen 		tp->packets_out -= acked_pcount;
313572018835SIlpo Järvinen 		pkts_acked += acked_pcount;
3136b9f64820SYuchung Cheng 		tcp_rate_skb_delivered(sk, skb, sack->rate);
313713fcf850SIlpo Järvinen 
3138009a2e3eSIlpo Järvinen 		/* Initial outgoing SYN's get put onto the write_queue
3139009a2e3eSIlpo Järvinen 		 * just like anything else we transmit.  It is not
3140009a2e3eSIlpo Järvinen 		 * true data, and if we misinform our callers that
3141009a2e3eSIlpo Järvinen 		 * this ACK acks real data, we will erroneously exit
3142009a2e3eSIlpo Järvinen 		 * connection startup slow start one packet too
3143009a2e3eSIlpo Järvinen 		 * quickly.  This is severely frowned upon behavior.
3144009a2e3eSIlpo Järvinen 		 */
3145ad971f61SEric Dumazet 		if (likely(!(scb->tcp_flags & TCPHDR_SYN))) {
3146009a2e3eSIlpo Järvinen 			flag |= FLAG_DATA_ACKED;
3147009a2e3eSIlpo Järvinen 		} else {
3148009a2e3eSIlpo Järvinen 			flag |= FLAG_SYN_ACKED;
3149009a2e3eSIlpo Järvinen 			tp->retrans_stamp = 0;
3150009a2e3eSIlpo Järvinen 		}
3151009a2e3eSIlpo Järvinen 
315213fcf850SIlpo Järvinen 		if (!fully_acked)
315313fcf850SIlpo Järvinen 			break;
315413fcf850SIlpo Järvinen 
3155fe067e8aSDavid S. Miller 		tcp_unlink_write_queue(skb, sk);
31563ab224beSHideo Aoki 		sk_wmem_free_skb(sk, skb);
3157ad971f61SEric Dumazet 		if (unlikely(skb == tp->retransmit_skb_hint))
3158ef9da47cSIlpo Järvinen 			tp->retransmit_skb_hint = NULL;
3159ad971f61SEric Dumazet 		if (unlikely(skb == tp->lost_skb_hint))
316090638a04SIlpo Järvinen 			tp->lost_skb_hint = NULL;
31611da177e4SLinus Torvalds 	}
31621da177e4SLinus Torvalds 
31630f87230dSFrancis Yan 	if (!skb)
31640f87230dSFrancis Yan 		tcp_chrono_stop(sk, TCP_CHRONO_BUSY);
31650f87230dSFrancis Yan 
316633f5f57eSIlpo Järvinen 	if (likely(between(tp->snd_up, prior_snd_una, tp->snd_una)))
316733f5f57eSIlpo Järvinen 		tp->snd_up = tp->snd_una;
316833f5f57eSIlpo Järvinen 
3169cadbd031SIlpo Järvinen 	if (skb && (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED))
3170cadbd031SIlpo Järvinen 		flag |= FLAG_SACK_RENEGING;
3171cadbd031SIlpo Järvinen 
31729a568de4SEric Dumazet 	if (likely(first_ackt) && !(flag & FLAG_RETRANS_DATA_ACKED)) {
31739a568de4SEric Dumazet 		seq_rtt_us = tcp_stamp_us_delta(tp->tcp_mstamp, first_ackt);
31749a568de4SEric Dumazet 		ca_rtt_us = tcp_stamp_us_delta(tp->tcp_mstamp, last_ackt);
317531231a8aSKenneth Klette Jonassen 	}
31769a568de4SEric Dumazet 	if (sack->first_sackt) {
31779a568de4SEric Dumazet 		sack_rtt_us = tcp_stamp_us_delta(tp->tcp_mstamp, sack->first_sackt);
31789a568de4SEric Dumazet 		ca_rtt_us = tcp_stamp_us_delta(tp->tcp_mstamp, sack->last_sackt);
3179740b0f18SEric Dumazet 	}
3180b9f64820SYuchung Cheng 	sack->rate->rtt_us = ca_rtt_us; /* RTT of last (S)ACKed packet, or -1 */
3181f6722583SYuchung Cheng 	rtt_update = tcp_ack_update_rtt(sk, flag, seq_rtt_us, sack_rtt_us,
3182f6722583SYuchung Cheng 					ca_rtt_us);
3183ed08495cSYuchung Cheng 
31847c46a03eSIlpo Järvinen 	if (flag & FLAG_ACKED) {
31852f715c1dSYuchung Cheng 		tcp_rearm_rto(sk);
318672211e90SIlpo Järvinen 		if (unlikely(icsk->icsk_mtup.probe_size &&
318772211e90SIlpo Järvinen 			     !after(tp->mtu_probe.probe_seq_end, tp->snd_una))) {
318872211e90SIlpo Järvinen 			tcp_mtup_probe_success(sk);
318972211e90SIlpo Järvinen 		}
319072211e90SIlpo Järvinen 
3191c7caf8d3SIlpo Järvinen 		if (tcp_is_reno(tp)) {
3192c7caf8d3SIlpo Järvinen 			tcp_remove_reno_sacks(sk, pkts_acked);
3193c7caf8d3SIlpo Järvinen 		} else {
319459a08cbaSIlpo Järvinen 			int delta;
319559a08cbaSIlpo Järvinen 
3196c7caf8d3SIlpo Järvinen 			/* Non-retransmitted hole got filled? That's reordering */
3197bafbb9c7SSoheil Hassas Yeganeh 			if (reord < prior_fackets && reord <= tp->fackets_out)
3198c7caf8d3SIlpo Järvinen 				tcp_update_reordering(sk, tp->fackets_out - reord, 0);
319990638a04SIlpo Järvinen 
320059a08cbaSIlpo Järvinen 			delta = tcp_is_fack(tp) ? pkts_acked :
320159a08cbaSIlpo Järvinen 						  prior_sacked - tp->sacked_out;
320259a08cbaSIlpo Järvinen 			tp->lost_cnt_hint -= min(tp->lost_cnt_hint, delta);
3203c7caf8d3SIlpo Järvinen 		}
3204c7caf8d3SIlpo Järvinen 
320591fed7a1SIlpo Järvinen 		tp->fackets_out -= min(pkts_acked, tp->fackets_out);
320668f8353bSIlpo Järvinen 
3207740b0f18SEric Dumazet 	} else if (skb && rtt_update && sack_rtt_us >= 0 &&
32089a568de4SEric Dumazet 		   sack_rtt_us > tcp_stamp_us_delta(tp->tcp_mstamp, skb->skb_mstamp)) {
32092f715c1dSYuchung Cheng 		/* Do not re-arm RTO if the sack RTT is measured from data sent
32102f715c1dSYuchung Cheng 		 * after when the head was last (re)transmitted. Otherwise the
32112f715c1dSYuchung Cheng 		 * timeout may continue to extend in loss recovery.
32122f715c1dSYuchung Cheng 		 */
32132f715c1dSYuchung Cheng 		tcp_rearm_rto(sk);
32141da177e4SLinus Torvalds 	}
32151da177e4SLinus Torvalds 
3216756ee172SLawrence Brakmo 	if (icsk->icsk_ca_ops->pkts_acked) {
3217756ee172SLawrence Brakmo 		struct ack_sample sample = { .pkts_acked = pkts_acked,
32186f094b9eSLawrence Brakmo 					     .rtt_us = ca_rtt_us,
32196f094b9eSLawrence Brakmo 					     .in_flight = last_in_flight };
3220756ee172SLawrence Brakmo 
3221756ee172SLawrence Brakmo 		icsk->icsk_ca_ops->pkts_acked(sk, &sample);
3222756ee172SLawrence Brakmo 	}
3223138998fdSKenneth Klette Jonassen 
32241da177e4SLinus Torvalds #if FASTRETRANS_DEBUG > 0
3225547b792cSIlpo Järvinen 	WARN_ON((int)tp->sacked_out < 0);
3226547b792cSIlpo Järvinen 	WARN_ON((int)tp->lost_out < 0);
3227547b792cSIlpo Järvinen 	WARN_ON((int)tp->retrans_out < 0);
3228e60402d0SIlpo Järvinen 	if (!tp->packets_out && tcp_is_sack(tp)) {
3229cfcabdccSStephen Hemminger 		icsk = inet_csk(sk);
32301da177e4SLinus Torvalds 		if (tp->lost_out) {
323191df42beSJoe Perches 			pr_debug("Leak l=%u %d\n",
32326687e988SArnaldo Carvalho de Melo 				 tp->lost_out, icsk->icsk_ca_state);
32331da177e4SLinus Torvalds 			tp->lost_out = 0;
32341da177e4SLinus Torvalds 		}
32351da177e4SLinus Torvalds 		if (tp->sacked_out) {
323691df42beSJoe Perches 			pr_debug("Leak s=%u %d\n",
32376687e988SArnaldo Carvalho de Melo 				 tp->sacked_out, icsk->icsk_ca_state);
32381da177e4SLinus Torvalds 			tp->sacked_out = 0;
32391da177e4SLinus Torvalds 		}
32401da177e4SLinus Torvalds 		if (tp->retrans_out) {
324191df42beSJoe Perches 			pr_debug("Leak r=%u %d\n",
32426687e988SArnaldo Carvalho de Melo 				 tp->retrans_out, icsk->icsk_ca_state);
32431da177e4SLinus Torvalds 			tp->retrans_out = 0;
32441da177e4SLinus Torvalds 		}
32451da177e4SLinus Torvalds 	}
32461da177e4SLinus Torvalds #endif
32473ebd8871SYuchung Cheng 	*acked = pkts_acked;
32487c46a03eSIlpo Järvinen 	return flag;
32491da177e4SLinus Torvalds }
32501da177e4SLinus Torvalds 
32511da177e4SLinus Torvalds static void tcp_ack_probe(struct sock *sk)
32521da177e4SLinus Torvalds {
3253463c84b9SArnaldo Carvalho de Melo 	const struct tcp_sock *tp = tcp_sk(sk);
3254463c84b9SArnaldo Carvalho de Melo 	struct inet_connection_sock *icsk = inet_csk(sk);
32551da177e4SLinus Torvalds 
32561da177e4SLinus Torvalds 	/* Was it a usable window open? */
32571da177e4SLinus Torvalds 
325890840defSIlpo Järvinen 	if (!after(TCP_SKB_CB(tcp_send_head(sk))->end_seq, tcp_wnd_end(tp))) {
3259463c84b9SArnaldo Carvalho de Melo 		icsk->icsk_backoff = 0;
3260463c84b9SArnaldo Carvalho de Melo 		inet_csk_clear_xmit_timer(sk, ICSK_TIME_PROBE0);
32611da177e4SLinus Torvalds 		/* Socket must be waked up by subsequent tcp_data_snd_check().
32621da177e4SLinus Torvalds 		 * This function is not for random using!
32631da177e4SLinus Torvalds 		 */
32641da177e4SLinus Torvalds 	} else {
326521c8fe99SEric Dumazet 		unsigned long when = tcp_probe0_when(sk, TCP_RTO_MAX);
3266fcdd1cf4SEric Dumazet 
3267463c84b9SArnaldo Carvalho de Melo 		inet_csk_reset_xmit_timer(sk, ICSK_TIME_PROBE0,
3268fcdd1cf4SEric Dumazet 					  when, TCP_RTO_MAX);
32691da177e4SLinus Torvalds 	}
32701da177e4SLinus Torvalds }
32711da177e4SLinus Torvalds 
327267b95bd7SVijay Subramanian static inline bool tcp_ack_is_dubious(const struct sock *sk, const int flag)
32731da177e4SLinus Torvalds {
3274a02cec21SEric Dumazet 	return !(flag & FLAG_NOT_DUP) || (flag & FLAG_CA_ALERT) ||
3275a02cec21SEric Dumazet 		inet_csk(sk)->icsk_ca_state != TCP_CA_Open;
32761da177e4SLinus Torvalds }
32771da177e4SLinus Torvalds 
32780f7cc9a3SYuchung Cheng /* Decide wheather to run the increase function of congestion control. */
327967b95bd7SVijay Subramanian static inline bool tcp_may_raise_cwnd(const struct sock *sk, const int flag)
32801da177e4SLinus Torvalds {
32810f7cc9a3SYuchung Cheng 	/* If reordering is high then always grow cwnd whenever data is
32820f7cc9a3SYuchung Cheng 	 * delivered regardless of its ordering. Otherwise stay conservative
328316edfe7eSYuchung Cheng 	 * and only grow cwnd on in-order delivery (RFC5681). A stretched ACK w/
32840f7cc9a3SYuchung Cheng 	 * new SACK or ECE mark may first advance cwnd here and later reduce
32850f7cc9a3SYuchung Cheng 	 * cwnd in tcp_fastretrans_alert() based on more states.
32860f7cc9a3SYuchung Cheng 	 */
32871043e25fSNikolay Borisov 	if (tcp_sk(sk)->reordering > sock_net(sk)->ipv4.sysctl_tcp_reordering)
32880f7cc9a3SYuchung Cheng 		return flag & FLAG_FORWARD_PROGRESS;
32890f7cc9a3SYuchung Cheng 
329016edfe7eSYuchung Cheng 	return flag & FLAG_DATA_ACKED;
32911da177e4SLinus Torvalds }
32921da177e4SLinus Torvalds 
3293d452e6caSYuchung Cheng /* The "ultimate" congestion control function that aims to replace the rigid
3294d452e6caSYuchung Cheng  * cwnd increase and decrease control (tcp_cong_avoid,tcp_*cwnd_reduction).
3295d452e6caSYuchung Cheng  * It's called toward the end of processing an ACK with precise rate
3296d452e6caSYuchung Cheng  * information. All transmission or retransmission are delayed afterwards.
3297d452e6caSYuchung Cheng  */
3298d452e6caSYuchung Cheng static void tcp_cong_control(struct sock *sk, u32 ack, u32 acked_sacked,
3299c0402760SYuchung Cheng 			     int flag, const struct rate_sample *rs)
3300d452e6caSYuchung Cheng {
3301c0402760SYuchung Cheng 	const struct inet_connection_sock *icsk = inet_csk(sk);
3302c0402760SYuchung Cheng 
3303c0402760SYuchung Cheng 	if (icsk->icsk_ca_ops->cong_control) {
3304c0402760SYuchung Cheng 		icsk->icsk_ca_ops->cong_control(sk, rs);
3305c0402760SYuchung Cheng 		return;
3306c0402760SYuchung Cheng 	}
3307c0402760SYuchung Cheng 
3308d452e6caSYuchung Cheng 	if (tcp_in_cwnd_reduction(sk)) {
3309d452e6caSYuchung Cheng 		/* Reduce cwnd if state mandates */
3310d452e6caSYuchung Cheng 		tcp_cwnd_reduction(sk, acked_sacked, flag);
3311d452e6caSYuchung Cheng 	} else if (tcp_may_raise_cwnd(sk, flag)) {
3312d452e6caSYuchung Cheng 		/* Advance cwnd if state allows */
3313d452e6caSYuchung Cheng 		tcp_cong_avoid(sk, ack, acked_sacked);
3314d452e6caSYuchung Cheng 	}
3315d452e6caSYuchung Cheng 	tcp_update_pacing_rate(sk);
3316d452e6caSYuchung Cheng }
3317d452e6caSYuchung Cheng 
33181da177e4SLinus Torvalds /* Check that window update is acceptable.
33191da177e4SLinus Torvalds  * The function assumes that snd_una<=ack<=snd_next.
33201da177e4SLinus Torvalds  */
332167b95bd7SVijay Subramanian static inline bool tcp_may_update_window(const struct tcp_sock *tp,
3322056834d9SIlpo Järvinen 					const u32 ack, const u32 ack_seq,
3323056834d9SIlpo Järvinen 					const u32 nwin)
33241da177e4SLinus Torvalds {
3325a02cec21SEric Dumazet 	return	after(ack, tp->snd_una) ||
33261da177e4SLinus Torvalds 		after(ack_seq, tp->snd_wl1) ||
3327a02cec21SEric Dumazet 		(ack_seq == tp->snd_wl1 && nwin > tp->snd_wnd);
33281da177e4SLinus Torvalds }
33291da177e4SLinus Torvalds 
33300df48c26SEric Dumazet /* If we update tp->snd_una, also update tp->bytes_acked */
33310df48c26SEric Dumazet static void tcp_snd_una_update(struct tcp_sock *tp, u32 ack)
33320df48c26SEric Dumazet {
33330df48c26SEric Dumazet 	u32 delta = ack - tp->snd_una;
33340df48c26SEric Dumazet 
333546cc6e49SEric Dumazet 	sock_owned_by_me((struct sock *)tp);
33360df48c26SEric Dumazet 	tp->bytes_acked += delta;
33370df48c26SEric Dumazet 	tp->snd_una = ack;
33380df48c26SEric Dumazet }
33390df48c26SEric Dumazet 
3340bdd1f9edSEric Dumazet /* If we update tp->rcv_nxt, also update tp->bytes_received */
3341bdd1f9edSEric Dumazet static void tcp_rcv_nxt_update(struct tcp_sock *tp, u32 seq)
3342bdd1f9edSEric Dumazet {
3343bdd1f9edSEric Dumazet 	u32 delta = seq - tp->rcv_nxt;
3344bdd1f9edSEric Dumazet 
334546cc6e49SEric Dumazet 	sock_owned_by_me((struct sock *)tp);
3346bdd1f9edSEric Dumazet 	tp->bytes_received += delta;
3347bdd1f9edSEric Dumazet 	tp->rcv_nxt = seq;
3348bdd1f9edSEric Dumazet }
3349bdd1f9edSEric Dumazet 
33501da177e4SLinus Torvalds /* Update our send window.
33511da177e4SLinus Torvalds  *
33521da177e4SLinus Torvalds  * Window update algorithm, described in RFC793/RFC1122 (used in linux-2.2
33531da177e4SLinus Torvalds  * and in FreeBSD. NetBSD's one is even worse.) is wrong.
33541da177e4SLinus Torvalds  */
3355cf533ea5SEric Dumazet static int tcp_ack_update_window(struct sock *sk, const struct sk_buff *skb, u32 ack,
33569e412ba7SIlpo Järvinen 				 u32 ack_seq)
33571da177e4SLinus Torvalds {
33589e412ba7SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
33591da177e4SLinus Torvalds 	int flag = 0;
3360aa8223c7SArnaldo Carvalho de Melo 	u32 nwin = ntohs(tcp_hdr(skb)->window);
33611da177e4SLinus Torvalds 
3362aa8223c7SArnaldo Carvalho de Melo 	if (likely(!tcp_hdr(skb)->syn))
33631da177e4SLinus Torvalds 		nwin <<= tp->rx_opt.snd_wscale;
33641da177e4SLinus Torvalds 
33651da177e4SLinus Torvalds 	if (tcp_may_update_window(tp, ack, ack_seq, nwin)) {
33661da177e4SLinus Torvalds 		flag |= FLAG_WIN_UPDATE;
3367ee7537b6SHantzis Fotis 		tcp_update_wl(tp, ack_seq);
33681da177e4SLinus Torvalds 
33691da177e4SLinus Torvalds 		if (tp->snd_wnd != nwin) {
33701da177e4SLinus Torvalds 			tp->snd_wnd = nwin;
33711da177e4SLinus Torvalds 
33721da177e4SLinus Torvalds 			/* Note, it is the only place, where
33731da177e4SLinus Torvalds 			 * fast path is recovered for sending TCP.
33741da177e4SLinus Torvalds 			 */
33752ad41065SHerbert Xu 			tp->pred_flags = 0;
33769e412ba7SIlpo Järvinen 			tcp_fast_path_check(sk);
33771da177e4SLinus Torvalds 
33786f021c62SEric Dumazet 			if (tcp_send_head(sk))
33796f021c62SEric Dumazet 				tcp_slow_start_after_idle_check(sk);
33806f021c62SEric Dumazet 
33811da177e4SLinus Torvalds 			if (nwin > tp->max_window) {
33821da177e4SLinus Torvalds 				tp->max_window = nwin;
3383d83d8461SArnaldo Carvalho de Melo 				tcp_sync_mss(sk, inet_csk(sk)->icsk_pmtu_cookie);
33841da177e4SLinus Torvalds 			}
33851da177e4SLinus Torvalds 		}
33861da177e4SLinus Torvalds 	}
33871da177e4SLinus Torvalds 
33880df48c26SEric Dumazet 	tcp_snd_una_update(tp, ack);
33891da177e4SLinus Torvalds 
33901da177e4SLinus Torvalds 	return flag;
33911da177e4SLinus Torvalds }
33921da177e4SLinus Torvalds 
3393083ae308SJason Baron static bool __tcp_oow_rate_limited(struct net *net, int mib_idx,
3394083ae308SJason Baron 				   u32 *last_oow_ack_time)
3395083ae308SJason Baron {
3396083ae308SJason Baron 	if (*last_oow_ack_time) {
3397594208afSEric Dumazet 		s32 elapsed = (s32)(tcp_jiffies32 - *last_oow_ack_time);
3398083ae308SJason Baron 
3399083ae308SJason Baron 		if (0 <= elapsed && elapsed < sysctl_tcp_invalid_ratelimit) {
3400083ae308SJason Baron 			NET_INC_STATS(net, mib_idx);
3401083ae308SJason Baron 			return true;	/* rate-limited: don't send yet! */
3402083ae308SJason Baron 		}
3403083ae308SJason Baron 	}
3404083ae308SJason Baron 
3405594208afSEric Dumazet 	*last_oow_ack_time = tcp_jiffies32;
3406083ae308SJason Baron 
3407083ae308SJason Baron 	return false;	/* not rate-limited: go ahead, send dupack now! */
3408083ae308SJason Baron }
3409083ae308SJason Baron 
34107970ddc8SEric Dumazet /* Return true if we're currently rate-limiting out-of-window ACKs and
34117970ddc8SEric Dumazet  * thus shouldn't send a dupack right now. We rate-limit dupacks in
34127970ddc8SEric Dumazet  * response to out-of-window SYNs or ACKs to mitigate ACK loops or DoS
34137970ddc8SEric Dumazet  * attacks that send repeated SYNs or ACKs for the same connection. To
34147970ddc8SEric Dumazet  * do this, we do not send a duplicate SYNACK or ACK if the remote
34157970ddc8SEric Dumazet  * endpoint is sending out-of-window SYNs or pure ACKs at a high rate.
34167970ddc8SEric Dumazet  */
34177970ddc8SEric Dumazet bool tcp_oow_rate_limited(struct net *net, const struct sk_buff *skb,
34187970ddc8SEric Dumazet 			  int mib_idx, u32 *last_oow_ack_time)
34197970ddc8SEric Dumazet {
34207970ddc8SEric Dumazet 	/* Data packets without SYNs are not likely part of an ACK loop. */
34217970ddc8SEric Dumazet 	if ((TCP_SKB_CB(skb)->seq != TCP_SKB_CB(skb)->end_seq) &&
34227970ddc8SEric Dumazet 	    !tcp_hdr(skb)->syn)
3423083ae308SJason Baron 		return false;
34247970ddc8SEric Dumazet 
3425083ae308SJason Baron 	return __tcp_oow_rate_limited(net, mib_idx, last_oow_ack_time);
34267970ddc8SEric Dumazet }
34277970ddc8SEric Dumazet 
3428354e4aa3SEric Dumazet /* RFC 5961 7 [ACK Throttling] */
3429f2b2c582SNeal Cardwell static void tcp_send_challenge_ack(struct sock *sk, const struct sk_buff *skb)
3430354e4aa3SEric Dumazet {
3431354e4aa3SEric Dumazet 	/* unprotected vars, we dont care of overwrites */
3432354e4aa3SEric Dumazet 	static u32 challenge_timestamp;
3433354e4aa3SEric Dumazet 	static unsigned int challenge_count;
3434f2b2c582SNeal Cardwell 	struct tcp_sock *tp = tcp_sk(sk);
343575ff39ccSEric Dumazet 	u32 count, now;
3436354e4aa3SEric Dumazet 
3437f2b2c582SNeal Cardwell 	/* First check our per-socket dupack rate limit. */
3438083ae308SJason Baron 	if (__tcp_oow_rate_limited(sock_net(sk),
3439f2b2c582SNeal Cardwell 				   LINUX_MIB_TCPACKSKIPPEDCHALLENGE,
3440f2b2c582SNeal Cardwell 				   &tp->last_oow_ack_time))
3441f2b2c582SNeal Cardwell 		return;
3442f2b2c582SNeal Cardwell 
344375ff39ccSEric Dumazet 	/* Then check host-wide RFC 5961 rate limit. */
3444f2b2c582SNeal Cardwell 	now = jiffies / HZ;
3445354e4aa3SEric Dumazet 	if (now != challenge_timestamp) {
344675ff39ccSEric Dumazet 		u32 half = (sysctl_tcp_challenge_ack_limit + 1) >> 1;
344775ff39ccSEric Dumazet 
3448354e4aa3SEric Dumazet 		challenge_timestamp = now;
344975ff39ccSEric Dumazet 		WRITE_ONCE(challenge_count, half +
345075ff39ccSEric Dumazet 			   prandom_u32_max(sysctl_tcp_challenge_ack_limit));
3451354e4aa3SEric Dumazet 	}
345275ff39ccSEric Dumazet 	count = READ_ONCE(challenge_count);
345375ff39ccSEric Dumazet 	if (count > 0) {
345475ff39ccSEric Dumazet 		WRITE_ONCE(challenge_count, count - 1);
3455c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPCHALLENGEACK);
3456354e4aa3SEric Dumazet 		tcp_send_ack(sk);
3457354e4aa3SEric Dumazet 	}
3458354e4aa3SEric Dumazet }
3459354e4aa3SEric Dumazet 
346012fb3dd9SEric Dumazet static void tcp_store_ts_recent(struct tcp_sock *tp)
346112fb3dd9SEric Dumazet {
346212fb3dd9SEric Dumazet 	tp->rx_opt.ts_recent = tp->rx_opt.rcv_tsval;
346312fb3dd9SEric Dumazet 	tp->rx_opt.ts_recent_stamp = get_seconds();
346412fb3dd9SEric Dumazet }
346512fb3dd9SEric Dumazet 
346612fb3dd9SEric Dumazet static void tcp_replace_ts_recent(struct tcp_sock *tp, u32 seq)
346712fb3dd9SEric Dumazet {
346812fb3dd9SEric Dumazet 	if (tp->rx_opt.saw_tstamp && !after(seq, tp->rcv_wup)) {
346912fb3dd9SEric Dumazet 		/* PAWS bug workaround wrt. ACK frames, the PAWS discard
347012fb3dd9SEric Dumazet 		 * extra check below makes sure this can only happen
347112fb3dd9SEric Dumazet 		 * for pure ACK frames.  -DaveM
347212fb3dd9SEric Dumazet 		 *
347312fb3dd9SEric Dumazet 		 * Not only, also it occurs for expired timestamps.
347412fb3dd9SEric Dumazet 		 */
347512fb3dd9SEric Dumazet 
347612fb3dd9SEric Dumazet 		if (tcp_paws_check(&tp->rx_opt, 0))
347712fb3dd9SEric Dumazet 			tcp_store_ts_recent(tp);
347812fb3dd9SEric Dumazet 	}
347912fb3dd9SEric Dumazet }
348012fb3dd9SEric Dumazet 
34819b717a8dSNandita Dukkipati /* This routine deals with acks during a TLP episode.
348208abdffaSSébastien Barré  * We mark the end of a TLP episode on receiving TLP dupack or when
348308abdffaSSébastien Barré  * ack is after tlp_high_seq.
34849b717a8dSNandita Dukkipati  * Ref: loss detection algorithm in draft-dukkipati-tcpm-tcp-loss-probe.
34859b717a8dSNandita Dukkipati  */
34869b717a8dSNandita Dukkipati static void tcp_process_tlp_ack(struct sock *sk, u32 ack, int flag)
34879b717a8dSNandita Dukkipati {
34889b717a8dSNandita Dukkipati 	struct tcp_sock *tp = tcp_sk(sk);
34899b717a8dSNandita Dukkipati 
349008abdffaSSébastien Barré 	if (before(ack, tp->tlp_high_seq))
34919b717a8dSNandita Dukkipati 		return;
34929b717a8dSNandita Dukkipati 
349308abdffaSSébastien Barré 	if (flag & FLAG_DSACKING_ACK) {
349408abdffaSSébastien Barré 		/* This DSACK means original and TLP probe arrived; no loss */
34959b717a8dSNandita Dukkipati 		tp->tlp_high_seq = 0;
349608abdffaSSébastien Barré 	} else if (after(ack, tp->tlp_high_seq)) {
349708abdffaSSébastien Barré 		/* ACK advances: there was a loss, so reduce cwnd. Reset
349808abdffaSSébastien Barré 		 * tlp_high_seq in tcp_init_cwnd_reduction()
349908abdffaSSébastien Barré 		 */
35005ee2c941SChristoph Paasch 		tcp_init_cwnd_reduction(sk);
35019b717a8dSNandita Dukkipati 		tcp_set_ca_state(sk, TCP_CA_CWR);
35029b717a8dSNandita Dukkipati 		tcp_end_cwnd_reduction(sk);
3503031afe49SYuchung Cheng 		tcp_try_keep_open(sk);
3504c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk),
35059b717a8dSNandita Dukkipati 				LINUX_MIB_TCPLOSSPROBERECOVERY);
350608abdffaSSébastien Barré 	} else if (!(flag & (FLAG_SND_UNA_ADVANCED |
350708abdffaSSébastien Barré 			     FLAG_NOT_DUP | FLAG_DATA_SACKED))) {
350808abdffaSSébastien Barré 		/* Pure dupack: original and TLP probe arrived; no loss */
350908abdffaSSébastien Barré 		tp->tlp_high_seq = 0;
35109b717a8dSNandita Dukkipati 	}
35119b717a8dSNandita Dukkipati }
35129b717a8dSNandita Dukkipati 
35137354c8c3SFlorian Westphal static inline void tcp_in_ack_event(struct sock *sk, u32 flags)
35147354c8c3SFlorian Westphal {
35157354c8c3SFlorian Westphal 	const struct inet_connection_sock *icsk = inet_csk(sk);
35167354c8c3SFlorian Westphal 
35177354c8c3SFlorian Westphal 	if (icsk->icsk_ca_ops->in_ack_event)
35187354c8c3SFlorian Westphal 		icsk->icsk_ca_ops->in_ack_event(sk, flags);
35197354c8c3SFlorian Westphal }
35207354c8c3SFlorian Westphal 
3521e662ca40SYuchung Cheng /* Congestion control has updated the cwnd already. So if we're in
3522e662ca40SYuchung Cheng  * loss recovery then now we do any new sends (for FRTO) or
3523e662ca40SYuchung Cheng  * retransmits (for CA_Loss or CA_recovery) that make sense.
3524e662ca40SYuchung Cheng  */
3525e662ca40SYuchung Cheng static void tcp_xmit_recovery(struct sock *sk, int rexmit)
3526e662ca40SYuchung Cheng {
3527e662ca40SYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
3528e662ca40SYuchung Cheng 
3529e662ca40SYuchung Cheng 	if (rexmit == REXMIT_NONE)
3530e662ca40SYuchung Cheng 		return;
3531e662ca40SYuchung Cheng 
3532e662ca40SYuchung Cheng 	if (unlikely(rexmit == 2)) {
3533e662ca40SYuchung Cheng 		__tcp_push_pending_frames(sk, tcp_current_mss(sk),
3534e662ca40SYuchung Cheng 					  TCP_NAGLE_OFF);
3535e662ca40SYuchung Cheng 		if (after(tp->snd_nxt, tp->high_seq))
3536e662ca40SYuchung Cheng 			return;
3537e662ca40SYuchung Cheng 		tp->frto = 0;
3538e662ca40SYuchung Cheng 	}
3539e662ca40SYuchung Cheng 	tcp_xmit_retransmit_queue(sk);
3540e662ca40SYuchung Cheng }
3541e662ca40SYuchung Cheng 
35421da177e4SLinus Torvalds /* This routine deals with incoming acks, but not outgoing ones. */
3543cf533ea5SEric Dumazet static int tcp_ack(struct sock *sk, const struct sk_buff *skb, int flag)
35441da177e4SLinus Torvalds {
35456687e988SArnaldo Carvalho de Melo 	struct inet_connection_sock *icsk = inet_csk(sk);
35461da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
3547196da974SKenneth Klette Jonassen 	struct tcp_sacktag_state sack_state;
3548b9f64820SYuchung Cheng 	struct rate_sample rs = { .prior_delivered = 0 };
35491da177e4SLinus Torvalds 	u32 prior_snd_una = tp->snd_una;
35501da177e4SLinus Torvalds 	u32 ack_seq = TCP_SKB_CB(skb)->seq;
35511da177e4SLinus Torvalds 	u32 ack = TCP_SKB_CB(skb)->ack_seq;
35527d2b55f8SNeal Cardwell 	bool is_dupack = false;
3553c7caf8d3SIlpo Järvinen 	u32 prior_fackets;
355435f079ebSNandita Dukkipati 	int prior_packets = tp->packets_out;
3555b9f64820SYuchung Cheng 	u32 delivered = tp->delivered;
3556b9f64820SYuchung Cheng 	u32 lost = tp->lost;
35576804973fSYuchung Cheng 	int acked = 0; /* Number of packets newly acked */
3558e662ca40SYuchung Cheng 	int rexmit = REXMIT_NONE; /* Flag to (re)transmit to recover losses */
3559196da974SKenneth Klette Jonassen 
35609a568de4SEric Dumazet 	sack_state.first_sackt = 0;
3561b9f64820SYuchung Cheng 	sack_state.rate = &rs;
35621da177e4SLinus Torvalds 
3563ad971f61SEric Dumazet 	/* We very likely will need to access write queue head. */
3564ad971f61SEric Dumazet 	prefetchw(sk->sk_write_queue.next);
3565ad971f61SEric Dumazet 
356696e0bf4bSJohn Dykstra 	/* If the ack is older than previous acks
35671da177e4SLinus Torvalds 	 * then we can probably ignore it.
35681da177e4SLinus Torvalds 	 */
3569354e4aa3SEric Dumazet 	if (before(ack, prior_snd_una)) {
3570354e4aa3SEric Dumazet 		/* RFC 5961 5.2 [Blind Data Injection Attack].[Mitigation] */
3571354e4aa3SEric Dumazet 		if (before(ack, prior_snd_una - tp->max_window)) {
3572*d0e1a1b5SEric Dumazet 			if (!(flag & FLAG_NO_CHALLENGE_ACK))
3573f2b2c582SNeal Cardwell 				tcp_send_challenge_ack(sk, skb);
3574354e4aa3SEric Dumazet 			return -1;
3575354e4aa3SEric Dumazet 		}
35761da177e4SLinus Torvalds 		goto old_ack;
3577354e4aa3SEric Dumazet 	}
35781da177e4SLinus Torvalds 
357996e0bf4bSJohn Dykstra 	/* If the ack includes data we haven't sent yet, discard
358096e0bf4bSJohn Dykstra 	 * this segment (RFC793 Section 3.9).
358196e0bf4bSJohn Dykstra 	 */
358296e0bf4bSJohn Dykstra 	if (after(ack, tp->snd_nxt))
358396e0bf4bSJohn Dykstra 		goto invalid_ack;
358496e0bf4bSJohn Dykstra 
3585bec41a11SYuchung Cheng 	if (icsk->icsk_pending == ICSK_TIME_LOSS_PROBE)
3586750ea2baSYuchung Cheng 		tcp_rearm_rto(sk);
3587750ea2baSYuchung Cheng 
35880c9ab092SNeal Cardwell 	if (after(ack, prior_snd_una)) {
35892e605294SIlpo Järvinen 		flag |= FLAG_SND_UNA_ADVANCED;
35900c9ab092SNeal Cardwell 		icsk->icsk_retransmits = 0;
35910c9ab092SNeal Cardwell 	}
35922e605294SIlpo Järvinen 
3593c7caf8d3SIlpo Järvinen 	prior_fackets = tp->fackets_out;
3594b9f64820SYuchung Cheng 	rs.prior_in_flight = tcp_packets_in_flight(tp);
3595c7caf8d3SIlpo Järvinen 
359612fb3dd9SEric Dumazet 	/* ts_recent update must be made after we are sure that the packet
359712fb3dd9SEric Dumazet 	 * is in window.
359812fb3dd9SEric Dumazet 	 */
359912fb3dd9SEric Dumazet 	if (flag & FLAG_UPDATE_TS_RECENT)
360012fb3dd9SEric Dumazet 		tcp_replace_ts_recent(tp, TCP_SKB_CB(skb)->seq);
360112fb3dd9SEric Dumazet 
36021da177e4SLinus Torvalds 	if (!(flag & FLAG_SLOWPATH) && after(ack, prior_snd_una)) {
36031da177e4SLinus Torvalds 		/* Window is constant, pure forward advance.
36041da177e4SLinus Torvalds 		 * No more checks are required.
36051da177e4SLinus Torvalds 		 * Note, we use the fact that SND.UNA>=SND.WL2.
36061da177e4SLinus Torvalds 		 */
3607ee7537b6SHantzis Fotis 		tcp_update_wl(tp, ack_seq);
36080df48c26SEric Dumazet 		tcp_snd_una_update(tp, ack);
36091da177e4SLinus Torvalds 		flag |= FLAG_WIN_UPDATE;
36101da177e4SLinus Torvalds 
36119890092eSFlorian Westphal 		tcp_in_ack_event(sk, CA_ACK_WIN_UPDATE);
3612317a76f9SStephen Hemminger 
3613c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPHPACKS);
36141da177e4SLinus Torvalds 	} else {
36159890092eSFlorian Westphal 		u32 ack_ev_flags = CA_ACK_SLOWPATH;
36169890092eSFlorian Westphal 
36171da177e4SLinus Torvalds 		if (ack_seq != TCP_SKB_CB(skb)->end_seq)
36181da177e4SLinus Torvalds 			flag |= FLAG_DATA;
36191da177e4SLinus Torvalds 		else
3620c10d9310SEric Dumazet 			NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPPUREACKS);
36211da177e4SLinus Torvalds 
36229e412ba7SIlpo Järvinen 		flag |= tcp_ack_update_window(sk, skb, ack, ack_seq);
36231da177e4SLinus Torvalds 
36241da177e4SLinus Torvalds 		if (TCP_SKB_CB(skb)->sacked)
362559c9af42SYuchung Cheng 			flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una,
3626196da974SKenneth Klette Jonassen 							&sack_state);
36271da177e4SLinus Torvalds 
3628735d3831SFlorian Westphal 		if (tcp_ecn_rcv_ecn_echo(tp, tcp_hdr(skb))) {
36291da177e4SLinus Torvalds 			flag |= FLAG_ECE;
36309890092eSFlorian Westphal 			ack_ev_flags |= CA_ACK_ECE;
36319890092eSFlorian Westphal 		}
36321da177e4SLinus Torvalds 
36339890092eSFlorian Westphal 		if (flag & FLAG_WIN_UPDATE)
36349890092eSFlorian Westphal 			ack_ev_flags |= CA_ACK_WIN_UPDATE;
36359890092eSFlorian Westphal 
36369890092eSFlorian Westphal 		tcp_in_ack_event(sk, ack_ev_flags);
36371da177e4SLinus Torvalds 	}
36381da177e4SLinus Torvalds 
36391da177e4SLinus Torvalds 	/* We passed data and got it acked, remove any soft error
36401da177e4SLinus Torvalds 	 * log. Something worked...
36411da177e4SLinus Torvalds 	 */
36421da177e4SLinus Torvalds 	sk->sk_err_soft = 0;
36434b53fb67SDavid S. Miller 	icsk->icsk_probes_out = 0;
364470eabf0eSEric Dumazet 	tp->rcv_tstamp = tcp_jiffies32;
36451da177e4SLinus Torvalds 	if (!prior_packets)
36461da177e4SLinus Torvalds 		goto no_queue;
36471da177e4SLinus Torvalds 
36481da177e4SLinus Torvalds 	/* See if we can take anything off of the retransmit queue. */
36493ebd8871SYuchung Cheng 	flag |= tcp_clean_rtx_queue(sk, prior_fackets, prior_snd_una, &acked,
3650deed7be7SYuchung Cheng 				    &sack_state);
3651a262f0cdSNandita Dukkipati 
36520f7cc9a3SYuchung Cheng 	if (tcp_ack_is_dubious(sk, flag)) {
36537d2b55f8SNeal Cardwell 		is_dupack = !(flag & (FLAG_SND_UNA_ADVANCED | FLAG_NOT_DUP));
36541317a9d6SEric Dumazet 		tcp_fastretrans_alert(sk, acked, is_dupack, &flag, &rexmit);
36551da177e4SLinus Torvalds 	}
36569b717a8dSNandita Dukkipati 	if (tp->tlp_high_seq)
36579b717a8dSNandita Dukkipati 		tcp_process_tlp_ack(sk, ack, flag);
36589b717a8dSNandita Dukkipati 
3659c3a2e837SJulian Anastasov 	if ((flag & FLAG_FORWARD_PROGRESS) || !(flag & FLAG_NOT_DUP))
3660c3a2e837SJulian Anastasov 		sk_dst_confirm(sk);
36616ba8a3b1SNandita Dukkipati 
36626ba8a3b1SNandita Dukkipati 	if (icsk->icsk_pending == ICSK_TIME_RETRANS)
36636ba8a3b1SNandita Dukkipati 		tcp_schedule_loss_probe(sk);
3664b9f64820SYuchung Cheng 	delivered = tp->delivered - delivered;	/* freshly ACKed or SACKed */
3665b9f64820SYuchung Cheng 	lost = tp->lost - lost;			/* freshly marked lost */
366688d5c650SEric Dumazet 	tcp_rate_gen(sk, delivered, lost, sack_state.rate);
3667deed7be7SYuchung Cheng 	tcp_cong_control(sk, ack, delivered, flag, sack_state.rate);
3668e662ca40SYuchung Cheng 	tcp_xmit_recovery(sk, rexmit);
36691da177e4SLinus Torvalds 	return 1;
36701da177e4SLinus Torvalds 
36711da177e4SLinus Torvalds no_queue:
36725628adf1SNeal Cardwell 	/* If data was DSACKed, see if we can undo a cwnd reduction. */
36735628adf1SNeal Cardwell 	if (flag & FLAG_DSACKING_ACK)
36741317a9d6SEric Dumazet 		tcp_fastretrans_alert(sk, acked, is_dupack, &flag, &rexmit);
36751da177e4SLinus Torvalds 	/* If this ack opens up a zero window, clear backoff.  It was
36761da177e4SLinus Torvalds 	 * being used to time the probes, and is probably far higher than
36771da177e4SLinus Torvalds 	 * it needs to be for normal retransmission.
36781da177e4SLinus Torvalds 	 */
3679fe067e8aSDavid S. Miller 	if (tcp_send_head(sk))
36801da177e4SLinus Torvalds 		tcp_ack_probe(sk);
36819b717a8dSNandita Dukkipati 
36829b717a8dSNandita Dukkipati 	if (tp->tlp_high_seq)
36839b717a8dSNandita Dukkipati 		tcp_process_tlp_ack(sk, ack, flag);
36841da177e4SLinus Torvalds 	return 1;
36851da177e4SLinus Torvalds 
368696e0bf4bSJohn Dykstra invalid_ack:
368796e0bf4bSJohn Dykstra 	SOCK_DEBUG(sk, "Ack %u after %u:%u\n", ack, tp->snd_una, tp->snd_nxt);
368896e0bf4bSJohn Dykstra 	return -1;
368996e0bf4bSJohn Dykstra 
36901da177e4SLinus Torvalds old_ack:
3691e95ae2f2SNeal Cardwell 	/* If data was SACKed, tag it and see if we should send more data.
3692e95ae2f2SNeal Cardwell 	 * If data was DSACKed, see if we can undo a cwnd reduction.
3693e95ae2f2SNeal Cardwell 	 */
36948aca6cb1SIlpo Järvinen 	if (TCP_SKB_CB(skb)->sacked) {
369559c9af42SYuchung Cheng 		flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una,
3696196da974SKenneth Klette Jonassen 						&sack_state);
36971317a9d6SEric Dumazet 		tcp_fastretrans_alert(sk, acked, is_dupack, &flag, &rexmit);
3698e662ca40SYuchung Cheng 		tcp_xmit_recovery(sk, rexmit);
36998aca6cb1SIlpo Järvinen 	}
37001da177e4SLinus Torvalds 
370196e0bf4bSJohn Dykstra 	SOCK_DEBUG(sk, "Ack %u before %u:%u\n", ack, tp->snd_una, tp->snd_nxt);
37021da177e4SLinus Torvalds 	return 0;
37031da177e4SLinus Torvalds }
37041da177e4SLinus Torvalds 
37057f9b838bSDaniel Lee static void tcp_parse_fastopen_option(int len, const unsigned char *cookie,
37067f9b838bSDaniel Lee 				      bool syn, struct tcp_fastopen_cookie *foc,
37077f9b838bSDaniel Lee 				      bool exp_opt)
37087f9b838bSDaniel Lee {
37097f9b838bSDaniel Lee 	/* Valid only in SYN or SYN-ACK with an even length.  */
37107f9b838bSDaniel Lee 	if (!foc || !syn || len < 0 || (len & 1))
37117f9b838bSDaniel Lee 		return;
37127f9b838bSDaniel Lee 
37137f9b838bSDaniel Lee 	if (len >= TCP_FASTOPEN_COOKIE_MIN &&
37147f9b838bSDaniel Lee 	    len <= TCP_FASTOPEN_COOKIE_MAX)
37157f9b838bSDaniel Lee 		memcpy(foc->val, cookie, len);
37167f9b838bSDaniel Lee 	else if (len != 0)
37177f9b838bSDaniel Lee 		len = -1;
37187f9b838bSDaniel Lee 	foc->len = len;
37197f9b838bSDaniel Lee 	foc->exp = exp_opt;
37207f9b838bSDaniel Lee }
37217f9b838bSDaniel Lee 
37221da177e4SLinus Torvalds /* Look for tcp options. Normally only called on SYN and SYNACK packets.
37231da177e4SLinus Torvalds  * But, this can also be called on packets in the established flow when
37241da177e4SLinus Torvalds  * the fast version below fails.
37251da177e4SLinus Torvalds  */
37261a2c6181SChristoph Paasch void tcp_parse_options(const struct sk_buff *skb,
37271a2c6181SChristoph Paasch 		       struct tcp_options_received *opt_rx, int estab,
37282100c8d2SYuchung Cheng 		       struct tcp_fastopen_cookie *foc)
37291da177e4SLinus Torvalds {
3730cf533ea5SEric Dumazet 	const unsigned char *ptr;
3731cf533ea5SEric Dumazet 	const struct tcphdr *th = tcp_hdr(skb);
37321da177e4SLinus Torvalds 	int length = (th->doff * 4) - sizeof(struct tcphdr);
37331da177e4SLinus Torvalds 
3734cf533ea5SEric Dumazet 	ptr = (const unsigned char *)(th + 1);
37351da177e4SLinus Torvalds 	opt_rx->saw_tstamp = 0;
37361da177e4SLinus Torvalds 
37371da177e4SLinus Torvalds 	while (length > 0) {
37381da177e4SLinus Torvalds 		int opcode = *ptr++;
37391da177e4SLinus Torvalds 		int opsize;
37401da177e4SLinus Torvalds 
37411da177e4SLinus Torvalds 		switch (opcode) {
37421da177e4SLinus Torvalds 		case TCPOPT_EOL:
37431da177e4SLinus Torvalds 			return;
37441da177e4SLinus Torvalds 		case TCPOPT_NOP:	/* Ref: RFC 793 section 3.1 */
37451da177e4SLinus Torvalds 			length--;
37461da177e4SLinus Torvalds 			continue;
37471da177e4SLinus Torvalds 		default:
37481da177e4SLinus Torvalds 			opsize = *ptr++;
37491da177e4SLinus Torvalds 			if (opsize < 2) /* "silly options" */
37501da177e4SLinus Torvalds 				return;
37511da177e4SLinus Torvalds 			if (opsize > length)
37521da177e4SLinus Torvalds 				return;	/* don't parse partial options */
37531da177e4SLinus Torvalds 			switch (opcode) {
37541da177e4SLinus Torvalds 			case TCPOPT_MSS:
37551da177e4SLinus Torvalds 				if (opsize == TCPOLEN_MSS && th->syn && !estab) {
3756d3e2ce3bSHarvey Harrison 					u16 in_mss = get_unaligned_be16(ptr);
37571da177e4SLinus Torvalds 					if (in_mss) {
3758f038ac8fSIlpo Järvinen 						if (opt_rx->user_mss &&
3759f038ac8fSIlpo Järvinen 						    opt_rx->user_mss < in_mss)
37601da177e4SLinus Torvalds 							in_mss = opt_rx->user_mss;
37611da177e4SLinus Torvalds 						opt_rx->mss_clamp = in_mss;
37621da177e4SLinus Torvalds 					}
37631da177e4SLinus Torvalds 				}
37641da177e4SLinus Torvalds 				break;
37651da177e4SLinus Torvalds 			case TCPOPT_WINDOW:
3766f038ac8fSIlpo Järvinen 				if (opsize == TCPOLEN_WINDOW && th->syn &&
3767bb5b7c11SDavid S. Miller 				    !estab && sysctl_tcp_window_scaling) {
37681da177e4SLinus Torvalds 					__u8 snd_wscale = *(__u8 *)ptr;
37691da177e4SLinus Torvalds 					opt_rx->wscale_ok = 1;
3770589c49cbSGao Feng 					if (snd_wscale > TCP_MAX_WSCALE) {
3771589c49cbSGao Feng 						net_info_ratelimited("%s: Illegal window scaling value %d > %u received\n",
3772058bd4d2SJoe Perches 								     __func__,
3773589c49cbSGao Feng 								     snd_wscale,
3774589c49cbSGao Feng 								     TCP_MAX_WSCALE);
3775589c49cbSGao Feng 						snd_wscale = TCP_MAX_WSCALE;
37761da177e4SLinus Torvalds 					}
37771da177e4SLinus Torvalds 					opt_rx->snd_wscale = snd_wscale;
37781da177e4SLinus Torvalds 				}
37791da177e4SLinus Torvalds 				break;
37801da177e4SLinus Torvalds 			case TCPOPT_TIMESTAMP:
3781f038ac8fSIlpo Järvinen 				if ((opsize == TCPOLEN_TIMESTAMP) &&
3782f038ac8fSIlpo Järvinen 				    ((estab && opt_rx->tstamp_ok) ||
3783bb5b7c11SDavid S. Miller 				     (!estab && sysctl_tcp_timestamps))) {
37841da177e4SLinus Torvalds 					opt_rx->saw_tstamp = 1;
3785d3e2ce3bSHarvey Harrison 					opt_rx->rcv_tsval = get_unaligned_be32(ptr);
3786d3e2ce3bSHarvey Harrison 					opt_rx->rcv_tsecr = get_unaligned_be32(ptr + 4);
37871da177e4SLinus Torvalds 				}
37881da177e4SLinus Torvalds 				break;
37891da177e4SLinus Torvalds 			case TCPOPT_SACK_PERM:
3790f038ac8fSIlpo Järvinen 				if (opsize == TCPOLEN_SACK_PERM && th->syn &&
3791bb5b7c11SDavid S. Miller 				    !estab && sysctl_tcp_sack) {
3792ab56222aSVijay Subramanian 					opt_rx->sack_ok = TCP_SACK_SEEN;
37931da177e4SLinus Torvalds 					tcp_sack_reset(opt_rx);
37941da177e4SLinus Torvalds 				}
37951da177e4SLinus Torvalds 				break;
37961da177e4SLinus Torvalds 
37971da177e4SLinus Torvalds 			case TCPOPT_SACK:
37981da177e4SLinus Torvalds 				if ((opsize >= (TCPOLEN_SACK_BASE + TCPOLEN_SACK_PERBLOCK)) &&
37991da177e4SLinus Torvalds 				   !((opsize - TCPOLEN_SACK_BASE) % TCPOLEN_SACK_PERBLOCK) &&
38001da177e4SLinus Torvalds 				   opt_rx->sack_ok) {
38011da177e4SLinus Torvalds 					TCP_SKB_CB(skb)->sacked = (ptr - 2) - (unsigned char *)th;
38021da177e4SLinus Torvalds 				}
3803d7ea5b91SIlpo Järvinen 				break;
3804cfb6eeb4SYOSHIFUJI Hideaki #ifdef CONFIG_TCP_MD5SIG
3805cfb6eeb4SYOSHIFUJI Hideaki 			case TCPOPT_MD5SIG:
3806cfb6eeb4SYOSHIFUJI Hideaki 				/*
3807cfb6eeb4SYOSHIFUJI Hideaki 				 * The MD5 Hash has already been
3808cfb6eeb4SYOSHIFUJI Hideaki 				 * checked (see tcp_v{4,6}_do_rcv()).
3809cfb6eeb4SYOSHIFUJI Hideaki 				 */
3810cfb6eeb4SYOSHIFUJI Hideaki 				break;
3811cfb6eeb4SYOSHIFUJI Hideaki #endif
38127f9b838bSDaniel Lee 			case TCPOPT_FASTOPEN:
38137f9b838bSDaniel Lee 				tcp_parse_fastopen_option(
38147f9b838bSDaniel Lee 					opsize - TCPOLEN_FASTOPEN_BASE,
38157f9b838bSDaniel Lee 					ptr, th->syn, foc, false);
38167f9b838bSDaniel Lee 				break;
38177f9b838bSDaniel Lee 
38182100c8d2SYuchung Cheng 			case TCPOPT_EXP:
38192100c8d2SYuchung Cheng 				/* Fast Open option shares code 254 using a
38207f9b838bSDaniel Lee 				 * 16 bits magic number.
38212100c8d2SYuchung Cheng 				 */
38227f9b838bSDaniel Lee 				if (opsize >= TCPOLEN_EXP_FASTOPEN_BASE &&
38237f9b838bSDaniel Lee 				    get_unaligned_be16(ptr) ==
38247f9b838bSDaniel Lee 				    TCPOPT_FASTOPEN_MAGIC)
38257f9b838bSDaniel Lee 					tcp_parse_fastopen_option(opsize -
38267f9b838bSDaniel Lee 						TCPOLEN_EXP_FASTOPEN_BASE,
38277f9b838bSDaniel Lee 						ptr + 2, th->syn, foc, true);
38282100c8d2SYuchung Cheng 				break;
38292100c8d2SYuchung Cheng 
38302100c8d2SYuchung Cheng 			}
38311da177e4SLinus Torvalds 			ptr += opsize-2;
38321da177e4SLinus Torvalds 			length -= opsize;
38333ff50b79SStephen Hemminger 		}
38341da177e4SLinus Torvalds 	}
38351da177e4SLinus Torvalds }
38364bc2f18bSEric Dumazet EXPORT_SYMBOL(tcp_parse_options);
38371da177e4SLinus Torvalds 
3838a2a385d6SEric Dumazet static bool tcp_parse_aligned_timestamp(struct tcp_sock *tp, const struct tcphdr *th)
3839a4356b29SIlpo Järvinen {
3840cf533ea5SEric Dumazet 	const __be32 *ptr = (const __be32 *)(th + 1);
3841a4356b29SIlpo Järvinen 
3842a4356b29SIlpo Järvinen 	if (*ptr == htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16)
3843a4356b29SIlpo Järvinen 			  | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP)) {
3844a4356b29SIlpo Järvinen 		tp->rx_opt.saw_tstamp = 1;
3845a4356b29SIlpo Järvinen 		++ptr;
3846a4356b29SIlpo Järvinen 		tp->rx_opt.rcv_tsval = ntohl(*ptr);
3847a4356b29SIlpo Järvinen 		++ptr;
3848e3e12028SAndrew Vagin 		if (*ptr)
3849ee684b6fSAndrey Vagin 			tp->rx_opt.rcv_tsecr = ntohl(*ptr) - tp->tsoffset;
3850e3e12028SAndrew Vagin 		else
3851e3e12028SAndrew Vagin 			tp->rx_opt.rcv_tsecr = 0;
3852a2a385d6SEric Dumazet 		return true;
3853a4356b29SIlpo Järvinen 	}
3854a2a385d6SEric Dumazet 	return false;
3855a4356b29SIlpo Järvinen }
3856a4356b29SIlpo Järvinen 
38571da177e4SLinus Torvalds /* Fast parse options. This hopes to only see timestamps.
38581da177e4SLinus Torvalds  * If it is wrong it falls back on tcp_parse_options().
38591da177e4SLinus Torvalds  */
3860a2a385d6SEric Dumazet static bool tcp_fast_parse_options(const struct sk_buff *skb,
38611a2c6181SChristoph Paasch 				   const struct tcphdr *th, struct tcp_sock *tp)
38621da177e4SLinus Torvalds {
38634957faadSWilliam Allen Simpson 	/* In the spirit of fast parsing, compare doff directly to constant
38644957faadSWilliam Allen Simpson 	 * values.  Because equality is used, short doff can be ignored here.
38654957faadSWilliam Allen Simpson 	 */
38664957faadSWilliam Allen Simpson 	if (th->doff == (sizeof(*th) / 4)) {
38671da177e4SLinus Torvalds 		tp->rx_opt.saw_tstamp = 0;
3868a2a385d6SEric Dumazet 		return false;
38691da177e4SLinus Torvalds 	} else if (tp->rx_opt.tstamp_ok &&
38704957faadSWilliam Allen Simpson 		   th->doff == ((sizeof(*th) + TCPOLEN_TSTAMP_ALIGNED) / 4)) {
3871a4356b29SIlpo Järvinen 		if (tcp_parse_aligned_timestamp(tp, th))
3872a2a385d6SEric Dumazet 			return true;
38731da177e4SLinus Torvalds 	}
3874ee684b6fSAndrey Vagin 
38751a2c6181SChristoph Paasch 	tcp_parse_options(skb, &tp->rx_opt, 1, NULL);
3876e3e12028SAndrew Vagin 	if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr)
3877ee684b6fSAndrey Vagin 		tp->rx_opt.rcv_tsecr -= tp->tsoffset;
3878ee684b6fSAndrey Vagin 
3879a2a385d6SEric Dumazet 	return true;
38801da177e4SLinus Torvalds }
38811da177e4SLinus Torvalds 
38827d5d5525SYOSHIFUJI Hideaki #ifdef CONFIG_TCP_MD5SIG
38837d5d5525SYOSHIFUJI Hideaki /*
38847d5d5525SYOSHIFUJI Hideaki  * Parse MD5 Signature option
38857d5d5525SYOSHIFUJI Hideaki  */
3886cf533ea5SEric Dumazet const u8 *tcp_parse_md5sig_option(const struct tcphdr *th)
38877d5d5525SYOSHIFUJI Hideaki {
38887d5d5525SYOSHIFUJI Hideaki 	int length = (th->doff << 2) - sizeof(*th);
3889cf533ea5SEric Dumazet 	const u8 *ptr = (const u8 *)(th + 1);
38907d5d5525SYOSHIFUJI Hideaki 
38917d5d5525SYOSHIFUJI Hideaki 	/* If the TCP option is too short, we can short cut */
38927d5d5525SYOSHIFUJI Hideaki 	if (length < TCPOLEN_MD5SIG)
38937d5d5525SYOSHIFUJI Hideaki 		return NULL;
38947d5d5525SYOSHIFUJI Hideaki 
38957d5d5525SYOSHIFUJI Hideaki 	while (length > 0) {
38967d5d5525SYOSHIFUJI Hideaki 		int opcode = *ptr++;
38977d5d5525SYOSHIFUJI Hideaki 		int opsize;
38987d5d5525SYOSHIFUJI Hideaki 
38997d5d5525SYOSHIFUJI Hideaki 		switch (opcode) {
39007d5d5525SYOSHIFUJI Hideaki 		case TCPOPT_EOL:
39017d5d5525SYOSHIFUJI Hideaki 			return NULL;
39027d5d5525SYOSHIFUJI Hideaki 		case TCPOPT_NOP:
39037d5d5525SYOSHIFUJI Hideaki 			length--;
39047d5d5525SYOSHIFUJI Hideaki 			continue;
39057d5d5525SYOSHIFUJI Hideaki 		default:
39067d5d5525SYOSHIFUJI Hideaki 			opsize = *ptr++;
39077d5d5525SYOSHIFUJI Hideaki 			if (opsize < 2 || opsize > length)
39087d5d5525SYOSHIFUJI Hideaki 				return NULL;
39097d5d5525SYOSHIFUJI Hideaki 			if (opcode == TCPOPT_MD5SIG)
3910ba78e2ddSDmitry Popov 				return opsize == TCPOLEN_MD5SIG ? ptr : NULL;
39117d5d5525SYOSHIFUJI Hideaki 		}
39127d5d5525SYOSHIFUJI Hideaki 		ptr += opsize - 2;
39137d5d5525SYOSHIFUJI Hideaki 		length -= opsize;
39147d5d5525SYOSHIFUJI Hideaki 	}
39157d5d5525SYOSHIFUJI Hideaki 	return NULL;
39167d5d5525SYOSHIFUJI Hideaki }
39174bc2f18bSEric Dumazet EXPORT_SYMBOL(tcp_parse_md5sig_option);
39187d5d5525SYOSHIFUJI Hideaki #endif
39197d5d5525SYOSHIFUJI Hideaki 
39201da177e4SLinus Torvalds /* Sorry, PAWS as specified is broken wrt. pure-ACKs -DaveM
39211da177e4SLinus Torvalds  *
39221da177e4SLinus Torvalds  * It is not fatal. If this ACK does _not_ change critical state (seqs, window)
39231da177e4SLinus Torvalds  * it can pass through stack. So, the following predicate verifies that
39241da177e4SLinus Torvalds  * this segment is not used for anything but congestion avoidance or
39251da177e4SLinus Torvalds  * fast retransmit. Moreover, we even are able to eliminate most of such
39261da177e4SLinus Torvalds  * second order effects, if we apply some small "replay" window (~RTO)
39271da177e4SLinus Torvalds  * to timestamp space.
39281da177e4SLinus Torvalds  *
39291da177e4SLinus Torvalds  * All these measures still do not guarantee that we reject wrapped ACKs
39301da177e4SLinus Torvalds  * on networks with high bandwidth, when sequence space is recycled fastly,
39311da177e4SLinus Torvalds  * but it guarantees that such events will be very rare and do not affect
39321da177e4SLinus Torvalds  * connection seriously. This doesn't look nice, but alas, PAWS is really
39331da177e4SLinus Torvalds  * buggy extension.
39341da177e4SLinus Torvalds  *
39351da177e4SLinus Torvalds  * [ Later note. Even worse! It is buggy for segments _with_ data. RFC
39361da177e4SLinus Torvalds  * states that events when retransmit arrives after original data are rare.
39371da177e4SLinus Torvalds  * It is a blatant lie. VJ forgot about fast retransmit! 8)8) It is
39381da177e4SLinus Torvalds  * the biggest problem on large power networks even with minor reordering.
39391da177e4SLinus Torvalds  * OK, let's give it small replay window. If peer clock is even 1hz, it is safe
39401da177e4SLinus Torvalds  * up to bandwidth of 18Gigabit/sec. 8) ]
39411da177e4SLinus Torvalds  */
39421da177e4SLinus Torvalds 
3943463c84b9SArnaldo Carvalho de Melo static int tcp_disordered_ack(const struct sock *sk, const struct sk_buff *skb)
39441da177e4SLinus Torvalds {
3945cf533ea5SEric Dumazet 	const struct tcp_sock *tp = tcp_sk(sk);
3946cf533ea5SEric Dumazet 	const struct tcphdr *th = tcp_hdr(skb);
39471da177e4SLinus Torvalds 	u32 seq = TCP_SKB_CB(skb)->seq;
39481da177e4SLinus Torvalds 	u32 ack = TCP_SKB_CB(skb)->ack_seq;
39491da177e4SLinus Torvalds 
39501da177e4SLinus Torvalds 	return (/* 1. Pure ACK with correct sequence number. */
39511da177e4SLinus Torvalds 		(th->ack && seq == TCP_SKB_CB(skb)->end_seq && seq == tp->rcv_nxt) &&
39521da177e4SLinus Torvalds 
39531da177e4SLinus Torvalds 		/* 2. ... and duplicate ACK. */
39541da177e4SLinus Torvalds 		ack == tp->snd_una &&
39551da177e4SLinus Torvalds 
39561da177e4SLinus Torvalds 		/* 3. ... and does not update window. */
39571da177e4SLinus Torvalds 		!tcp_may_update_window(tp, ack, seq, ntohs(th->window) << tp->rx_opt.snd_wscale) &&
39581da177e4SLinus Torvalds 
39591da177e4SLinus Torvalds 		/* 4. ... and sits in replay window. */
3960463c84b9SArnaldo Carvalho de Melo 		(s32)(tp->rx_opt.ts_recent - tp->rx_opt.rcv_tsval) <= (inet_csk(sk)->icsk_rto * 1024) / HZ);
39611da177e4SLinus Torvalds }
39621da177e4SLinus Torvalds 
396367b95bd7SVijay Subramanian static inline bool tcp_paws_discard(const struct sock *sk,
3964056834d9SIlpo Järvinen 				   const struct sk_buff *skb)
39651da177e4SLinus Torvalds {
3966463c84b9SArnaldo Carvalho de Melo 	const struct tcp_sock *tp = tcp_sk(sk);
3967c887e6d2SIlpo Järvinen 
3968c887e6d2SIlpo Järvinen 	return !tcp_paws_check(&tp->rx_opt, TCP_PAWS_WINDOW) &&
3969c887e6d2SIlpo Järvinen 	       !tcp_disordered_ack(sk, skb);
39701da177e4SLinus Torvalds }
39711da177e4SLinus Torvalds 
39721da177e4SLinus Torvalds /* Check segment sequence number for validity.
39731da177e4SLinus Torvalds  *
39741da177e4SLinus Torvalds  * Segment controls are considered valid, if the segment
39751da177e4SLinus Torvalds  * fits to the window after truncation to the window. Acceptability
39761da177e4SLinus Torvalds  * of data (and SYN, FIN, of course) is checked separately.
39771da177e4SLinus Torvalds  * See tcp_data_queue(), for example.
39781da177e4SLinus Torvalds  *
39791da177e4SLinus Torvalds  * Also, controls (RST is main one) are accepted using RCV.WUP instead
39801da177e4SLinus Torvalds  * of RCV.NXT. Peer still did not advance his SND.UNA when we
39811da177e4SLinus Torvalds  * delayed ACK, so that hisSND.UNA<=ourRCV.WUP.
39821da177e4SLinus Torvalds  * (borrowed from freebsd)
39831da177e4SLinus Torvalds  */
39841da177e4SLinus Torvalds 
398567b95bd7SVijay Subramanian static inline bool tcp_sequence(const struct tcp_sock *tp, u32 seq, u32 end_seq)
39861da177e4SLinus Torvalds {
39871da177e4SLinus Torvalds 	return	!before(end_seq, tp->rcv_wup) &&
39881da177e4SLinus Torvalds 		!after(seq, tp->rcv_nxt + tcp_receive_window(tp));
39891da177e4SLinus Torvalds }
39901da177e4SLinus Torvalds 
39911da177e4SLinus Torvalds /* When we get a reset we do this. */
399210467163SJerry Chu void tcp_reset(struct sock *sk)
39931da177e4SLinus Torvalds {
39941da177e4SLinus Torvalds 	/* We want the right error as BSD sees it (and indeed as we do). */
39951da177e4SLinus Torvalds 	switch (sk->sk_state) {
39961da177e4SLinus Torvalds 	case TCP_SYN_SENT:
39971da177e4SLinus Torvalds 		sk->sk_err = ECONNREFUSED;
39981da177e4SLinus Torvalds 		break;
39991da177e4SLinus Torvalds 	case TCP_CLOSE_WAIT:
40001da177e4SLinus Torvalds 		sk->sk_err = EPIPE;
40011da177e4SLinus Torvalds 		break;
40021da177e4SLinus Torvalds 	case TCP_CLOSE:
40031da177e4SLinus Torvalds 		return;
40041da177e4SLinus Torvalds 	default:
40051da177e4SLinus Torvalds 		sk->sk_err = ECONNRESET;
40061da177e4SLinus Torvalds 	}
4007a4d25803STom Marshall 	/* This barrier is coupled with smp_rmb() in tcp_poll() */
4008a4d25803STom Marshall 	smp_wmb();
40091da177e4SLinus Torvalds 
40103d476263SEric Dumazet 	tcp_done(sk);
40113d476263SEric Dumazet 
40121da177e4SLinus Torvalds 	if (!sock_flag(sk, SOCK_DEAD))
40131da177e4SLinus Torvalds 		sk->sk_error_report(sk);
40141da177e4SLinus Torvalds }
40151da177e4SLinus Torvalds 
40161da177e4SLinus Torvalds /*
40171da177e4SLinus Torvalds  * 	Process the FIN bit. This now behaves as it is supposed to work
40181da177e4SLinus Torvalds  *	and the FIN takes effect when it is validly part of sequence
40191da177e4SLinus Torvalds  *	space. Not before when we get holes.
40201da177e4SLinus Torvalds  *
40211da177e4SLinus Torvalds  *	If we are ESTABLISHED, a received fin moves us to CLOSE-WAIT
40221da177e4SLinus Torvalds  *	(and thence onto LAST-ACK and finally, CLOSE, we never enter
40231da177e4SLinus Torvalds  *	TIME-WAIT)
40241da177e4SLinus Torvalds  *
40251da177e4SLinus Torvalds  *	If we are in FINWAIT-1, a received FIN indicates simultaneous
40261da177e4SLinus Torvalds  *	close and we go into CLOSING (and later onto TIME-WAIT)
40271da177e4SLinus Torvalds  *
40281da177e4SLinus Torvalds  *	If we are in FINWAIT-2, a received FIN moves us to TIME-WAIT.
40291da177e4SLinus Torvalds  */
4030e3e17b77SEric Dumazet void tcp_fin(struct sock *sk)
40311da177e4SLinus Torvalds {
40321da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
40331da177e4SLinus Torvalds 
4034463c84b9SArnaldo Carvalho de Melo 	inet_csk_schedule_ack(sk);
40351da177e4SLinus Torvalds 
40361da177e4SLinus Torvalds 	sk->sk_shutdown |= RCV_SHUTDOWN;
40371da177e4SLinus Torvalds 	sock_set_flag(sk, SOCK_DONE);
40381da177e4SLinus Torvalds 
40391da177e4SLinus Torvalds 	switch (sk->sk_state) {
40401da177e4SLinus Torvalds 	case TCP_SYN_RECV:
40411da177e4SLinus Torvalds 	case TCP_ESTABLISHED:
40421da177e4SLinus Torvalds 		/* Move to CLOSE_WAIT */
40431da177e4SLinus Torvalds 		tcp_set_state(sk, TCP_CLOSE_WAIT);
4044463c84b9SArnaldo Carvalho de Melo 		inet_csk(sk)->icsk_ack.pingpong = 1;
40451da177e4SLinus Torvalds 		break;
40461da177e4SLinus Torvalds 
40471da177e4SLinus Torvalds 	case TCP_CLOSE_WAIT:
40481da177e4SLinus Torvalds 	case TCP_CLOSING:
40491da177e4SLinus Torvalds 		/* Received a retransmission of the FIN, do
40501da177e4SLinus Torvalds 		 * nothing.
40511da177e4SLinus Torvalds 		 */
40521da177e4SLinus Torvalds 		break;
40531da177e4SLinus Torvalds 	case TCP_LAST_ACK:
40541da177e4SLinus Torvalds 		/* RFC793: Remain in the LAST-ACK state. */
40551da177e4SLinus Torvalds 		break;
40561da177e4SLinus Torvalds 
40571da177e4SLinus Torvalds 	case TCP_FIN_WAIT1:
40581da177e4SLinus Torvalds 		/* This case occurs when a simultaneous close
40591da177e4SLinus Torvalds 		 * happens, we must ack the received FIN and
40601da177e4SLinus Torvalds 		 * enter the CLOSING state.
40611da177e4SLinus Torvalds 		 */
40621da177e4SLinus Torvalds 		tcp_send_ack(sk);
40631da177e4SLinus Torvalds 		tcp_set_state(sk, TCP_CLOSING);
40641da177e4SLinus Torvalds 		break;
40651da177e4SLinus Torvalds 	case TCP_FIN_WAIT2:
40661da177e4SLinus Torvalds 		/* Received a FIN -- send ACK and enter TIME_WAIT. */
40671da177e4SLinus Torvalds 		tcp_send_ack(sk);
40681da177e4SLinus Torvalds 		tcp_time_wait(sk, TCP_TIME_WAIT, 0);
40691da177e4SLinus Torvalds 		break;
40701da177e4SLinus Torvalds 	default:
40711da177e4SLinus Torvalds 		/* Only TCP_LISTEN and TCP_CLOSE are left, in these
40721da177e4SLinus Torvalds 		 * cases we should never reach this piece of code.
40731da177e4SLinus Torvalds 		 */
4074058bd4d2SJoe Perches 		pr_err("%s: Impossible, sk->sk_state=%d\n",
40750dc47877SHarvey Harrison 		       __func__, sk->sk_state);
40761da177e4SLinus Torvalds 		break;
40773ff50b79SStephen Hemminger 	}
40781da177e4SLinus Torvalds 
40791da177e4SLinus Torvalds 	/* It _is_ possible, that we have something out-of-order _after_ FIN.
40801da177e4SLinus Torvalds 	 * Probably, we should reset in this case. For now drop them.
40811da177e4SLinus Torvalds 	 */
40829f5afeaeSYaogong Wang 	skb_rbtree_purge(&tp->out_of_order_queue);
4083e60402d0SIlpo Järvinen 	if (tcp_is_sack(tp))
40841da177e4SLinus Torvalds 		tcp_sack_reset(&tp->rx_opt);
40853ab224beSHideo Aoki 	sk_mem_reclaim(sk);
40861da177e4SLinus Torvalds 
40871da177e4SLinus Torvalds 	if (!sock_flag(sk, SOCK_DEAD)) {
40881da177e4SLinus Torvalds 		sk->sk_state_change(sk);
40891da177e4SLinus Torvalds 
40901da177e4SLinus Torvalds 		/* Do not send POLL_HUP for half duplex close. */
40911da177e4SLinus Torvalds 		if (sk->sk_shutdown == SHUTDOWN_MASK ||
40921da177e4SLinus Torvalds 		    sk->sk_state == TCP_CLOSE)
40938d8ad9d7SPavel Emelyanov 			sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP);
40941da177e4SLinus Torvalds 		else
40958d8ad9d7SPavel Emelyanov 			sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
40961da177e4SLinus Torvalds 	}
40971da177e4SLinus Torvalds }
40981da177e4SLinus Torvalds 
4099a2a385d6SEric Dumazet static inline bool tcp_sack_extend(struct tcp_sack_block *sp, u32 seq,
4100056834d9SIlpo Järvinen 				  u32 end_seq)
41011da177e4SLinus Torvalds {
41021da177e4SLinus Torvalds 	if (!after(seq, sp->end_seq) && !after(sp->start_seq, end_seq)) {
41031da177e4SLinus Torvalds 		if (before(seq, sp->start_seq))
41041da177e4SLinus Torvalds 			sp->start_seq = seq;
41051da177e4SLinus Torvalds 		if (after(end_seq, sp->end_seq))
41061da177e4SLinus Torvalds 			sp->end_seq = end_seq;
4107a2a385d6SEric Dumazet 		return true;
41081da177e4SLinus Torvalds 	}
4109a2a385d6SEric Dumazet 	return false;
41101da177e4SLinus Torvalds }
41111da177e4SLinus Torvalds 
41121ed83465SPavel Emelyanov static void tcp_dsack_set(struct sock *sk, u32 seq, u32 end_seq)
41131da177e4SLinus Torvalds {
41141ed83465SPavel Emelyanov 	struct tcp_sock *tp = tcp_sk(sk);
41151ed83465SPavel Emelyanov 
4116bb5b7c11SDavid S. Miller 	if (tcp_is_sack(tp) && sysctl_tcp_dsack) {
411740b215e5SPavel Emelyanov 		int mib_idx;
411840b215e5SPavel Emelyanov 
41191da177e4SLinus Torvalds 		if (before(seq, tp->rcv_nxt))
412040b215e5SPavel Emelyanov 			mib_idx = LINUX_MIB_TCPDSACKOLDSENT;
41211da177e4SLinus Torvalds 		else
412240b215e5SPavel Emelyanov 			mib_idx = LINUX_MIB_TCPDSACKOFOSENT;
412340b215e5SPavel Emelyanov 
4124c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), mib_idx);
41251da177e4SLinus Torvalds 
41261da177e4SLinus Torvalds 		tp->rx_opt.dsack = 1;
41271da177e4SLinus Torvalds 		tp->duplicate_sack[0].start_seq = seq;
41281da177e4SLinus Torvalds 		tp->duplicate_sack[0].end_seq = end_seq;
41291da177e4SLinus Torvalds 	}
41301da177e4SLinus Torvalds }
41311da177e4SLinus Torvalds 
41321ed83465SPavel Emelyanov static void tcp_dsack_extend(struct sock *sk, u32 seq, u32 end_seq)
41331da177e4SLinus Torvalds {
41341ed83465SPavel Emelyanov 	struct tcp_sock *tp = tcp_sk(sk);
41351ed83465SPavel Emelyanov 
41361da177e4SLinus Torvalds 	if (!tp->rx_opt.dsack)
41371ed83465SPavel Emelyanov 		tcp_dsack_set(sk, seq, end_seq);
41381da177e4SLinus Torvalds 	else
41391da177e4SLinus Torvalds 		tcp_sack_extend(tp->duplicate_sack, seq, end_seq);
41401da177e4SLinus Torvalds }
41411da177e4SLinus Torvalds 
4142cf533ea5SEric Dumazet static void tcp_send_dupack(struct sock *sk, const struct sk_buff *skb)
41431da177e4SLinus Torvalds {
41441da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
41451da177e4SLinus Torvalds 
41461da177e4SLinus Torvalds 	if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
41471da177e4SLinus Torvalds 	    before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
4148c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_DELAYEDACKLOST);
4149463c84b9SArnaldo Carvalho de Melo 		tcp_enter_quickack_mode(sk);
41501da177e4SLinus Torvalds 
4151bb5b7c11SDavid S. Miller 		if (tcp_is_sack(tp) && sysctl_tcp_dsack) {
41521da177e4SLinus Torvalds 			u32 end_seq = TCP_SKB_CB(skb)->end_seq;
41531da177e4SLinus Torvalds 
41541da177e4SLinus Torvalds 			if (after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt))
41551da177e4SLinus Torvalds 				end_seq = tp->rcv_nxt;
41561ed83465SPavel Emelyanov 			tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, end_seq);
41571da177e4SLinus Torvalds 		}
41581da177e4SLinus Torvalds 	}
41591da177e4SLinus Torvalds 
41601da177e4SLinus Torvalds 	tcp_send_ack(sk);
41611da177e4SLinus Torvalds }
41621da177e4SLinus Torvalds 
41631da177e4SLinus Torvalds /* These routines update the SACK block as out-of-order packets arrive or
41641da177e4SLinus Torvalds  * in-order packets close up the sequence space.
41651da177e4SLinus Torvalds  */
41661da177e4SLinus Torvalds static void tcp_sack_maybe_coalesce(struct tcp_sock *tp)
41671da177e4SLinus Torvalds {
41681da177e4SLinus Torvalds 	int this_sack;
41691da177e4SLinus Torvalds 	struct tcp_sack_block *sp = &tp->selective_acks[0];
41701da177e4SLinus Torvalds 	struct tcp_sack_block *swalk = sp + 1;
41711da177e4SLinus Torvalds 
41721da177e4SLinus Torvalds 	/* See if the recent change to the first SACK eats into
41731da177e4SLinus Torvalds 	 * or hits the sequence space of other SACK blocks, if so coalesce.
41741da177e4SLinus Torvalds 	 */
41751da177e4SLinus Torvalds 	for (this_sack = 1; this_sack < tp->rx_opt.num_sacks;) {
41761da177e4SLinus Torvalds 		if (tcp_sack_extend(sp, swalk->start_seq, swalk->end_seq)) {
41771da177e4SLinus Torvalds 			int i;
41781da177e4SLinus Torvalds 
41791da177e4SLinus Torvalds 			/* Zap SWALK, by moving every further SACK up by one slot.
41801da177e4SLinus Torvalds 			 * Decrease num_sacks.
41811da177e4SLinus Torvalds 			 */
41821da177e4SLinus Torvalds 			tp->rx_opt.num_sacks--;
41831da177e4SLinus Torvalds 			for (i = this_sack; i < tp->rx_opt.num_sacks; i++)
41841da177e4SLinus Torvalds 				sp[i] = sp[i + 1];
41851da177e4SLinus Torvalds 			continue;
41861da177e4SLinus Torvalds 		}
41871da177e4SLinus Torvalds 		this_sack++, swalk++;
41881da177e4SLinus Torvalds 	}
41891da177e4SLinus Torvalds }
41901da177e4SLinus Torvalds 
41911da177e4SLinus Torvalds static void tcp_sack_new_ofo_skb(struct sock *sk, u32 seq, u32 end_seq)
41921da177e4SLinus Torvalds {
41931da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
41941da177e4SLinus Torvalds 	struct tcp_sack_block *sp = &tp->selective_acks[0];
41951da177e4SLinus Torvalds 	int cur_sacks = tp->rx_opt.num_sacks;
41961da177e4SLinus Torvalds 	int this_sack;
41971da177e4SLinus Torvalds 
41981da177e4SLinus Torvalds 	if (!cur_sacks)
41991da177e4SLinus Torvalds 		goto new_sack;
42001da177e4SLinus Torvalds 
42011da177e4SLinus Torvalds 	for (this_sack = 0; this_sack < cur_sacks; this_sack++, sp++) {
42021da177e4SLinus Torvalds 		if (tcp_sack_extend(sp, seq, end_seq)) {
42031da177e4SLinus Torvalds 			/* Rotate this_sack to the first one. */
42041da177e4SLinus Torvalds 			for (; this_sack > 0; this_sack--, sp--)
4205a0bffffcSIlpo Järvinen 				swap(*sp, *(sp - 1));
42061da177e4SLinus Torvalds 			if (cur_sacks > 1)
42071da177e4SLinus Torvalds 				tcp_sack_maybe_coalesce(tp);
42081da177e4SLinus Torvalds 			return;
42091da177e4SLinus Torvalds 		}
42101da177e4SLinus Torvalds 	}
42111da177e4SLinus Torvalds 
42121da177e4SLinus Torvalds 	/* Could not find an adjacent existing SACK, build a new one,
42131da177e4SLinus Torvalds 	 * put it at the front, and shift everyone else down.  We
42141da177e4SLinus Torvalds 	 * always know there is at least one SACK present already here.
42151da177e4SLinus Torvalds 	 *
42161da177e4SLinus Torvalds 	 * If the sack array is full, forget about the last one.
42171da177e4SLinus Torvalds 	 */
42184389ddedSAdam Langley 	if (this_sack >= TCP_NUM_SACKS) {
42191da177e4SLinus Torvalds 		this_sack--;
42201da177e4SLinus Torvalds 		tp->rx_opt.num_sacks--;
42211da177e4SLinus Torvalds 		sp--;
42221da177e4SLinus Torvalds 	}
42231da177e4SLinus Torvalds 	for (; this_sack > 0; this_sack--, sp--)
42241da177e4SLinus Torvalds 		*sp = *(sp - 1);
42251da177e4SLinus Torvalds 
42261da177e4SLinus Torvalds new_sack:
42271da177e4SLinus Torvalds 	/* Build the new head SACK, and we're done. */
42281da177e4SLinus Torvalds 	sp->start_seq = seq;
42291da177e4SLinus Torvalds 	sp->end_seq = end_seq;
42301da177e4SLinus Torvalds 	tp->rx_opt.num_sacks++;
42311da177e4SLinus Torvalds }
42321da177e4SLinus Torvalds 
42331da177e4SLinus Torvalds /* RCV.NXT advances, some SACKs should be eaten. */
42341da177e4SLinus Torvalds 
42351da177e4SLinus Torvalds static void tcp_sack_remove(struct tcp_sock *tp)
42361da177e4SLinus Torvalds {
42371da177e4SLinus Torvalds 	struct tcp_sack_block *sp = &tp->selective_acks[0];
42381da177e4SLinus Torvalds 	int num_sacks = tp->rx_opt.num_sacks;
42391da177e4SLinus Torvalds 	int this_sack;
42401da177e4SLinus Torvalds 
42411da177e4SLinus Torvalds 	/* Empty ofo queue, hence, all the SACKs are eaten. Clear. */
42429f5afeaeSYaogong Wang 	if (RB_EMPTY_ROOT(&tp->out_of_order_queue)) {
42431da177e4SLinus Torvalds 		tp->rx_opt.num_sacks = 0;
42441da177e4SLinus Torvalds 		return;
42451da177e4SLinus Torvalds 	}
42461da177e4SLinus Torvalds 
42471da177e4SLinus Torvalds 	for (this_sack = 0; this_sack < num_sacks;) {
42481da177e4SLinus Torvalds 		/* Check if the start of the sack is covered by RCV.NXT. */
42491da177e4SLinus Torvalds 		if (!before(tp->rcv_nxt, sp->start_seq)) {
42501da177e4SLinus Torvalds 			int i;
42511da177e4SLinus Torvalds 
42521da177e4SLinus Torvalds 			/* RCV.NXT must cover all the block! */
4253547b792cSIlpo Järvinen 			WARN_ON(before(tp->rcv_nxt, sp->end_seq));
42541da177e4SLinus Torvalds 
42551da177e4SLinus Torvalds 			/* Zap this SACK, by moving forward any other SACKS. */
42561da177e4SLinus Torvalds 			for (i = this_sack+1; i < num_sacks; i++)
42571da177e4SLinus Torvalds 				tp->selective_acks[i-1] = tp->selective_acks[i];
42581da177e4SLinus Torvalds 			num_sacks--;
42591da177e4SLinus Torvalds 			continue;
42601da177e4SLinus Torvalds 		}
42611da177e4SLinus Torvalds 		this_sack++;
42621da177e4SLinus Torvalds 		sp++;
42631da177e4SLinus Torvalds 	}
42641da177e4SLinus Torvalds 	tp->rx_opt.num_sacks = num_sacks;
42651da177e4SLinus Torvalds }
42661da177e4SLinus Torvalds 
42671402d366SEric Dumazet /**
42681402d366SEric Dumazet  * tcp_try_coalesce - try to merge skb to prior one
42691402d366SEric Dumazet  * @sk: socket
42701402d366SEric Dumazet  * @to: prior buffer
42711402d366SEric Dumazet  * @from: buffer to add in queue
4272923dd347SEric Dumazet  * @fragstolen: pointer to boolean
42731402d366SEric Dumazet  *
42741402d366SEric Dumazet  * Before queueing skb @from after @to, try to merge them
42751402d366SEric Dumazet  * to reduce overall memory use and queue lengths, if cost is small.
42761402d366SEric Dumazet  * Packets in ofo or receive queues can stay a long time.
42771402d366SEric Dumazet  * Better try to coalesce them right now to avoid future collapses.
4278783c175fSEric Dumazet  * Returns true if caller should free @from instead of queueing it
42791402d366SEric Dumazet  */
4280783c175fSEric Dumazet static bool tcp_try_coalesce(struct sock *sk,
42811402d366SEric Dumazet 			     struct sk_buff *to,
4282329033f6SEric Dumazet 			     struct sk_buff *from,
4283329033f6SEric Dumazet 			     bool *fragstolen)
42841402d366SEric Dumazet {
4285bad43ca8SEric Dumazet 	int delta;
42861402d366SEric Dumazet 
4287329033f6SEric Dumazet 	*fragstolen = false;
428834a802a5SAlexander Duyck 
42891ca7ee30SEric Dumazet 	/* Its possible this segment overlaps with prior segment in queue */
42901ca7ee30SEric Dumazet 	if (TCP_SKB_CB(from)->seq != TCP_SKB_CB(to)->end_seq)
42911ca7ee30SEric Dumazet 		return false;
42921ca7ee30SEric Dumazet 
4293bad43ca8SEric Dumazet 	if (!skb_try_coalesce(to, from, fragstolen, &delta))
4294783c175fSEric Dumazet 		return false;
429534a802a5SAlexander Duyck 
42961402d366SEric Dumazet 	atomic_add(delta, &sk->sk_rmem_alloc);
42971402d366SEric Dumazet 	sk_mem_charge(sk, delta);
4298c10d9310SEric Dumazet 	NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPRCVCOALESCE);
429934a802a5SAlexander Duyck 	TCP_SKB_CB(to)->end_seq = TCP_SKB_CB(from)->end_seq;
430034a802a5SAlexander Duyck 	TCP_SKB_CB(to)->ack_seq = TCP_SKB_CB(from)->ack_seq;
4301e93a0435SEric Dumazet 	TCP_SKB_CB(to)->tcp_flags |= TCP_SKB_CB(from)->tcp_flags;
430234a802a5SAlexander Duyck 	return true;
43031402d366SEric Dumazet }
43041402d366SEric Dumazet 
4305532182cdSEric Dumazet static void tcp_drop(struct sock *sk, struct sk_buff *skb)
4306532182cdSEric Dumazet {
4307532182cdSEric Dumazet 	sk_drops_add(sk, skb);
4308532182cdSEric Dumazet 	__kfree_skb(skb);
4309532182cdSEric Dumazet }
4310532182cdSEric Dumazet 
43111da177e4SLinus Torvalds /* This one checks to see if we can put data from the
43121da177e4SLinus Torvalds  * out_of_order queue into the receive_queue.
43131da177e4SLinus Torvalds  */
43141da177e4SLinus Torvalds static void tcp_ofo_queue(struct sock *sk)
43151da177e4SLinus Torvalds {
43161da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
43171da177e4SLinus Torvalds 	__u32 dsack_high = tp->rcv_nxt;
43189f5afeaeSYaogong Wang 	bool fin, fragstolen, eaten;
4319bd1e75abSEric Dumazet 	struct sk_buff *skb, *tail;
43209f5afeaeSYaogong Wang 	struct rb_node *p;
43211da177e4SLinus Torvalds 
43229f5afeaeSYaogong Wang 	p = rb_first(&tp->out_of_order_queue);
43239f5afeaeSYaogong Wang 	while (p) {
43249f5afeaeSYaogong Wang 		skb = rb_entry(p, struct sk_buff, rbnode);
43251da177e4SLinus Torvalds 		if (after(TCP_SKB_CB(skb)->seq, tp->rcv_nxt))
43261da177e4SLinus Torvalds 			break;
43271da177e4SLinus Torvalds 
43281da177e4SLinus Torvalds 		if (before(TCP_SKB_CB(skb)->seq, dsack_high)) {
43291da177e4SLinus Torvalds 			__u32 dsack = dsack_high;
43301da177e4SLinus Torvalds 			if (before(TCP_SKB_CB(skb)->end_seq, dsack_high))
43311da177e4SLinus Torvalds 				dsack_high = TCP_SKB_CB(skb)->end_seq;
43321da177e4SLinus Torvalds 			tcp_dsack_extend(sk, TCP_SKB_CB(skb)->seq, dsack);
43331da177e4SLinus Torvalds 		}
43349f5afeaeSYaogong Wang 		p = rb_next(p);
43359f5afeaeSYaogong Wang 		rb_erase(&skb->rbnode, &tp->out_of_order_queue);
43361da177e4SLinus Torvalds 
43379f5afeaeSYaogong Wang 		if (unlikely(!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt))) {
43381da177e4SLinus Torvalds 			SOCK_DEBUG(sk, "ofo packet was already received\n");
4339532182cdSEric Dumazet 			tcp_drop(sk, skb);
43401da177e4SLinus Torvalds 			continue;
43411da177e4SLinus Torvalds 		}
43421da177e4SLinus Torvalds 		SOCK_DEBUG(sk, "ofo requeuing : rcv_next %X seq %X - %X\n",
43431da177e4SLinus Torvalds 			   tp->rcv_nxt, TCP_SKB_CB(skb)->seq,
43441da177e4SLinus Torvalds 			   TCP_SKB_CB(skb)->end_seq);
43451da177e4SLinus Torvalds 
4346bd1e75abSEric Dumazet 		tail = skb_peek_tail(&sk->sk_receive_queue);
4347bd1e75abSEric Dumazet 		eaten = tail && tcp_try_coalesce(sk, tail, skb, &fragstolen);
4348bdd1f9edSEric Dumazet 		tcp_rcv_nxt_update(tp, TCP_SKB_CB(skb)->end_seq);
43499f5afeaeSYaogong Wang 		fin = TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN;
4350bd1e75abSEric Dumazet 		if (!eaten)
4351bd1e75abSEric Dumazet 			__skb_queue_tail(&sk->sk_receive_queue, skb);
43529f5afeaeSYaogong Wang 		else
4353bd1e75abSEric Dumazet 			kfree_skb_partial(skb, fragstolen);
43549f5afeaeSYaogong Wang 
43559f5afeaeSYaogong Wang 		if (unlikely(fin)) {
43569f5afeaeSYaogong Wang 			tcp_fin(sk);
43579f5afeaeSYaogong Wang 			/* tcp_fin() purges tp->out_of_order_queue,
43589f5afeaeSYaogong Wang 			 * so we must end this loop right now.
43599f5afeaeSYaogong Wang 			 */
43609f5afeaeSYaogong Wang 			break;
43619f5afeaeSYaogong Wang 		}
43621da177e4SLinus Torvalds 	}
43631da177e4SLinus Torvalds }
43641da177e4SLinus Torvalds 
43651da177e4SLinus Torvalds static bool tcp_prune_ofo_queue(struct sock *sk);
43661da177e4SLinus Torvalds static int tcp_prune_queue(struct sock *sk);
43671da177e4SLinus Torvalds 
43681da177e4SLinus Torvalds static int tcp_try_rmem_schedule(struct sock *sk, struct sk_buff *skb,
43691da177e4SLinus Torvalds 				 unsigned int size)
43701da177e4SLinus Torvalds {
43711da177e4SLinus Torvalds 	if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
43721da177e4SLinus Torvalds 	    !sk_rmem_schedule(sk, skb, size)) {
43731da177e4SLinus Torvalds 
43741da177e4SLinus Torvalds 		if (tcp_prune_queue(sk) < 0)
43751da177e4SLinus Torvalds 			return -1;
43761ed83465SPavel Emelyanov 
437736a6503fSEric Dumazet 		while (!sk_rmem_schedule(sk, skb, size)) {
43781da177e4SLinus Torvalds 			if (!tcp_prune_ofo_queue(sk))
43791da177e4SLinus Torvalds 				return -1;
43801da177e4SLinus Torvalds 		}
43811da177e4SLinus Torvalds 	}
43821da177e4SLinus Torvalds 	return 0;
43831da177e4SLinus Torvalds }
43841da177e4SLinus Torvalds 
4385e86b2919SEric Dumazet static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb)
4386e86b2919SEric Dumazet {
4387e86b2919SEric Dumazet 	struct tcp_sock *tp = tcp_sk(sk);
43889f5afeaeSYaogong Wang 	struct rb_node **p, *q, *parent;
4389e86b2919SEric Dumazet 	struct sk_buff *skb1;
4390e86b2919SEric Dumazet 	u32 seq, end_seq;
43919f5afeaeSYaogong Wang 	bool fragstolen;
4392e86b2919SEric Dumazet 
4393735d3831SFlorian Westphal 	tcp_ecn_check_ce(tp, skb);
4394e86b2919SEric Dumazet 
4395c76562b6SMel Gorman 	if (unlikely(tcp_try_rmem_schedule(sk, skb, skb->truesize))) {
4396c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPOFODROP);
4397532182cdSEric Dumazet 		tcp_drop(sk, skb);
4398e86b2919SEric Dumazet 		return;
4399e86b2919SEric Dumazet 	}
4400e86b2919SEric Dumazet 
4401e86b2919SEric Dumazet 	/* Disable header prediction. */
4402e86b2919SEric Dumazet 	tp->pred_flags = 0;
4403e86b2919SEric Dumazet 	inet_csk_schedule_ack(sk);
4404e86b2919SEric Dumazet 
4405c10d9310SEric Dumazet 	NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPOFOQUEUE);
44069f5afeaeSYaogong Wang 	seq = TCP_SKB_CB(skb)->seq;
44079f5afeaeSYaogong Wang 	end_seq = TCP_SKB_CB(skb)->end_seq;
4408e86b2919SEric Dumazet 	SOCK_DEBUG(sk, "out of order segment: rcv_next %X seq %X - %X\n",
44099f5afeaeSYaogong Wang 		   tp->rcv_nxt, seq, end_seq);
4410e86b2919SEric Dumazet 
44119f5afeaeSYaogong Wang 	p = &tp->out_of_order_queue.rb_node;
44129f5afeaeSYaogong Wang 	if (RB_EMPTY_ROOT(&tp->out_of_order_queue)) {
4413e86b2919SEric Dumazet 		/* Initial out of order segment, build 1 SACK. */
4414e86b2919SEric Dumazet 		if (tcp_is_sack(tp)) {
4415e86b2919SEric Dumazet 			tp->rx_opt.num_sacks = 1;
44169f5afeaeSYaogong Wang 			tp->selective_acks[0].start_seq = seq;
44179f5afeaeSYaogong Wang 			tp->selective_acks[0].end_seq = end_seq;
4418e86b2919SEric Dumazet 		}
44199f5afeaeSYaogong Wang 		rb_link_node(&skb->rbnode, NULL, p);
44209f5afeaeSYaogong Wang 		rb_insert_color(&skb->rbnode, &tp->out_of_order_queue);
44219f5afeaeSYaogong Wang 		tp->ooo_last_skb = skb;
4422e86b2919SEric Dumazet 		goto end;
4423e86b2919SEric Dumazet 	}
4424e86b2919SEric Dumazet 
44259f5afeaeSYaogong Wang 	/* In the typical case, we are adding an skb to the end of the list.
44269f5afeaeSYaogong Wang 	 * Use of ooo_last_skb avoids the O(Log(N)) rbtree lookup.
44279f5afeaeSYaogong Wang 	 */
44289f5afeaeSYaogong Wang 	if (tcp_try_coalesce(sk, tp->ooo_last_skb, skb, &fragstolen)) {
44299f5afeaeSYaogong Wang coalesce_done:
44304e4f1fc2SEric Dumazet 		tcp_grow_window(sk, skb);
4431923dd347SEric Dumazet 		kfree_skb_partial(skb, fragstolen);
4432c8628155SEric Dumazet 		skb = NULL;
4433e86b2919SEric Dumazet 		goto add_sack;
4434e86b2919SEric Dumazet 	}
44352594a2a9SEric Dumazet 	/* Can avoid an rbtree lookup if we are adding skb after ooo_last_skb */
44362594a2a9SEric Dumazet 	if (!before(seq, TCP_SKB_CB(tp->ooo_last_skb)->end_seq)) {
44372594a2a9SEric Dumazet 		parent = &tp->ooo_last_skb->rbnode;
44382594a2a9SEric Dumazet 		p = &parent->rb_right;
44392594a2a9SEric Dumazet 		goto insert;
4440e86b2919SEric Dumazet 	}
4441e86b2919SEric Dumazet 
44429f5afeaeSYaogong Wang 	/* Find place to insert this segment. Handle overlaps on the way. */
44439f5afeaeSYaogong Wang 	parent = NULL;
44449f5afeaeSYaogong Wang 	while (*p) {
44459f5afeaeSYaogong Wang 		parent = *p;
44469f5afeaeSYaogong Wang 		skb1 = rb_entry(parent, struct sk_buff, rbnode);
44479f5afeaeSYaogong Wang 		if (before(seq, TCP_SKB_CB(skb1)->seq)) {
44489f5afeaeSYaogong Wang 			p = &parent->rb_left;
44499f5afeaeSYaogong Wang 			continue;
4450e86b2919SEric Dumazet 		}
44519f5afeaeSYaogong Wang 		if (before(seq, TCP_SKB_CB(skb1)->end_seq)) {
4452e86b2919SEric Dumazet 			if (!after(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
4453e86b2919SEric Dumazet 				/* All the bits are present. Drop. */
44549f5afeaeSYaogong Wang 				NET_INC_STATS(sock_net(sk),
44559f5afeaeSYaogong Wang 					      LINUX_MIB_TCPOFOMERGE);
44569f5afeaeSYaogong Wang 				__kfree_skb(skb);
4457e86b2919SEric Dumazet 				skb = NULL;
4458e86b2919SEric Dumazet 				tcp_dsack_set(sk, seq, end_seq);
4459e86b2919SEric Dumazet 				goto add_sack;
4460e86b2919SEric Dumazet 			}
4461e86b2919SEric Dumazet 			if (after(seq, TCP_SKB_CB(skb1)->seq)) {
4462e86b2919SEric Dumazet 				/* Partial overlap. */
44639f5afeaeSYaogong Wang 				tcp_dsack_set(sk, seq, TCP_SKB_CB(skb1)->end_seq);
4464e86b2919SEric Dumazet 			} else {
44659f5afeaeSYaogong Wang 				/* skb's seq == skb1's seq and skb covers skb1.
44669f5afeaeSYaogong Wang 				 * Replace skb1 with skb.
44679f5afeaeSYaogong Wang 				 */
44689f5afeaeSYaogong Wang 				rb_replace_node(&skb1->rbnode, &skb->rbnode,
44699f5afeaeSYaogong Wang 						&tp->out_of_order_queue);
44709f5afeaeSYaogong Wang 				tcp_dsack_extend(sk,
44719f5afeaeSYaogong Wang 						 TCP_SKB_CB(skb1)->seq,
44729f5afeaeSYaogong Wang 						 TCP_SKB_CB(skb1)->end_seq);
44739f5afeaeSYaogong Wang 				NET_INC_STATS(sock_net(sk),
44749f5afeaeSYaogong Wang 					      LINUX_MIB_TCPOFOMERGE);
44759f5afeaeSYaogong Wang 				__kfree_skb(skb1);
447676f0dcbbSEric Dumazet 				goto merge_right;
4477e86b2919SEric Dumazet 			}
44789f5afeaeSYaogong Wang 		} else if (tcp_try_coalesce(sk, skb1, skb, &fragstolen)) {
44799f5afeaeSYaogong Wang 			goto coalesce_done;
4480e86b2919SEric Dumazet 		}
44819f5afeaeSYaogong Wang 		p = &parent->rb_right;
44829f5afeaeSYaogong Wang 	}
44832594a2a9SEric Dumazet insert:
44849f5afeaeSYaogong Wang 	/* Insert segment into RB tree. */
44859f5afeaeSYaogong Wang 	rb_link_node(&skb->rbnode, parent, p);
44869f5afeaeSYaogong Wang 	rb_insert_color(&skb->rbnode, &tp->out_of_order_queue);
4487e86b2919SEric Dumazet 
448876f0dcbbSEric Dumazet merge_right:
44899f5afeaeSYaogong Wang 	/* Remove other segments covered by skb. */
44909f5afeaeSYaogong Wang 	while ((q = rb_next(&skb->rbnode)) != NULL) {
44919f5afeaeSYaogong Wang 		skb1 = rb_entry(q, struct sk_buff, rbnode);
4492e86b2919SEric Dumazet 
4493e86b2919SEric Dumazet 		if (!after(end_seq, TCP_SKB_CB(skb1)->seq))
4494e86b2919SEric Dumazet 			break;
4495e86b2919SEric Dumazet 		if (before(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
4496e86b2919SEric Dumazet 			tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq,
4497e86b2919SEric Dumazet 					 end_seq);
4498e86b2919SEric Dumazet 			break;
4499e86b2919SEric Dumazet 		}
45009f5afeaeSYaogong Wang 		rb_erase(&skb1->rbnode, &tp->out_of_order_queue);
4501e86b2919SEric Dumazet 		tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq,
4502e86b2919SEric Dumazet 				 TCP_SKB_CB(skb1)->end_seq);
4503c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPOFOMERGE);
4504532182cdSEric Dumazet 		tcp_drop(sk, skb1);
4505e86b2919SEric Dumazet 	}
45069f5afeaeSYaogong Wang 	/* If there is no skb after us, we are the last_skb ! */
45079f5afeaeSYaogong Wang 	if (!q)
45089f5afeaeSYaogong Wang 		tp->ooo_last_skb = skb;
4509e86b2919SEric Dumazet 
4510e86b2919SEric Dumazet add_sack:
4511e86b2919SEric Dumazet 	if (tcp_is_sack(tp))
4512e86b2919SEric Dumazet 		tcp_sack_new_ofo_skb(sk, seq, end_seq);
4513e86b2919SEric Dumazet end:
45144e4f1fc2SEric Dumazet 	if (skb) {
45154e4f1fc2SEric Dumazet 		tcp_grow_window(sk, skb);
451660b1af33SEric Dumazet 		skb_condense(skb);
4517e86b2919SEric Dumazet 		skb_set_owner_r(skb, sk);
4518e86b2919SEric Dumazet 	}
45194e4f1fc2SEric Dumazet }
4520e86b2919SEric Dumazet 
4521292e8d8cSPavel Emelyanov static int __must_check tcp_queue_rcv(struct sock *sk, struct sk_buff *skb, int hdrlen,
4522b081f85cSEric Dumazet 		  bool *fragstolen)
4523b081f85cSEric Dumazet {
4524b081f85cSEric Dumazet 	int eaten;
4525b081f85cSEric Dumazet 	struct sk_buff *tail = skb_peek_tail(&sk->sk_receive_queue);
4526b081f85cSEric Dumazet 
4527b081f85cSEric Dumazet 	__skb_pull(skb, hdrlen);
4528b081f85cSEric Dumazet 	eaten = (tail &&
4529b081f85cSEric Dumazet 		 tcp_try_coalesce(sk, tail, skb, fragstolen)) ? 1 : 0;
4530bdd1f9edSEric Dumazet 	tcp_rcv_nxt_update(tcp_sk(sk), TCP_SKB_CB(skb)->end_seq);
4531b081f85cSEric Dumazet 	if (!eaten) {
4532b081f85cSEric Dumazet 		__skb_queue_tail(&sk->sk_receive_queue, skb);
4533b081f85cSEric Dumazet 		skb_set_owner_r(skb, sk);
4534b081f85cSEric Dumazet 	}
4535b081f85cSEric Dumazet 	return eaten;
4536b081f85cSEric Dumazet }
4537e86b2919SEric Dumazet 
4538292e8d8cSPavel Emelyanov int tcp_send_rcvq(struct sock *sk, struct msghdr *msg, size_t size)
4539292e8d8cSPavel Emelyanov {
4540cb93471aSEric Dumazet 	struct sk_buff *skb;
45415d4c9bfbSEric Dumazet 	int err = -ENOMEM;
45425d4c9bfbSEric Dumazet 	int data_len = 0;
4543292e8d8cSPavel Emelyanov 	bool fragstolen;
4544292e8d8cSPavel Emelyanov 
4545c454e611SPavel Emelyanov 	if (size == 0)
4546c454e611SPavel Emelyanov 		return 0;
4547c454e611SPavel Emelyanov 
45485d4c9bfbSEric Dumazet 	if (size > PAGE_SIZE) {
45495d4c9bfbSEric Dumazet 		int npages = min_t(size_t, size >> PAGE_SHIFT, MAX_SKB_FRAGS);
45505d4c9bfbSEric Dumazet 
45515d4c9bfbSEric Dumazet 		data_len = npages << PAGE_SHIFT;
45525d4c9bfbSEric Dumazet 		size = data_len + (size & ~PAGE_MASK);
45535d4c9bfbSEric Dumazet 	}
45545d4c9bfbSEric Dumazet 	skb = alloc_skb_with_frags(size - data_len, data_len,
45555d4c9bfbSEric Dumazet 				   PAGE_ALLOC_COSTLY_ORDER,
45565d4c9bfbSEric Dumazet 				   &err, sk->sk_allocation);
4557292e8d8cSPavel Emelyanov 	if (!skb)
4558292e8d8cSPavel Emelyanov 		goto err;
4559292e8d8cSPavel Emelyanov 
45605d4c9bfbSEric Dumazet 	skb_put(skb, size - data_len);
45615d4c9bfbSEric Dumazet 	skb->data_len = data_len;
45625d4c9bfbSEric Dumazet 	skb->len = size;
45635d4c9bfbSEric Dumazet 
4564cb93471aSEric Dumazet 	if (tcp_try_rmem_schedule(sk, skb, skb->truesize))
4565c76562b6SMel Gorman 		goto err_free;
4566c76562b6SMel Gorman 
45675d4c9bfbSEric Dumazet 	err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, size);
45685d4c9bfbSEric Dumazet 	if (err)
4569292e8d8cSPavel Emelyanov 		goto err_free;
4570292e8d8cSPavel Emelyanov 
4571292e8d8cSPavel Emelyanov 	TCP_SKB_CB(skb)->seq = tcp_sk(sk)->rcv_nxt;
4572292e8d8cSPavel Emelyanov 	TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(skb)->seq + size;
4573292e8d8cSPavel Emelyanov 	TCP_SKB_CB(skb)->ack_seq = tcp_sk(sk)->snd_una - 1;
4574292e8d8cSPavel Emelyanov 
4575cb93471aSEric Dumazet 	if (tcp_queue_rcv(sk, skb, 0, &fragstolen)) {
4576292e8d8cSPavel Emelyanov 		WARN_ON_ONCE(fragstolen); /* should not happen */
4577292e8d8cSPavel Emelyanov 		__kfree_skb(skb);
4578292e8d8cSPavel Emelyanov 	}
4579292e8d8cSPavel Emelyanov 	return size;
4580292e8d8cSPavel Emelyanov 
4581292e8d8cSPavel Emelyanov err_free:
4582292e8d8cSPavel Emelyanov 	kfree_skb(skb);
4583292e8d8cSPavel Emelyanov err:
45845d4c9bfbSEric Dumazet 	return err;
45855d4c9bfbSEric Dumazet 
4586292e8d8cSPavel Emelyanov }
4587292e8d8cSPavel Emelyanov 
45881da177e4SLinus Torvalds static void tcp_data_queue(struct sock *sk, struct sk_buff *skb)
45891da177e4SLinus Torvalds {
45901da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
4591329033f6SEric Dumazet 	bool fragstolen = false;
4592532182cdSEric Dumazet 	int eaten = -1;
45931da177e4SLinus Torvalds 
4594532182cdSEric Dumazet 	if (TCP_SKB_CB(skb)->seq == TCP_SKB_CB(skb)->end_seq) {
4595532182cdSEric Dumazet 		__kfree_skb(skb);
4596532182cdSEric Dumazet 		return;
4597532182cdSEric Dumazet 	}
4598f84af32cSEric Dumazet 	skb_dst_drop(skb);
4599155c6e1aSPeter Pan(潘卫平) 	__skb_pull(skb, tcp_hdr(skb)->doff * 4);
46001da177e4SLinus Torvalds 
4601735d3831SFlorian Westphal 	tcp_ecn_accept_cwr(tp, skb);
46021da177e4SLinus Torvalds 
46031da177e4SLinus Torvalds 	tp->rx_opt.dsack = 0;
46041da177e4SLinus Torvalds 
46051da177e4SLinus Torvalds 	/*  Queue data for delivery to the user.
46061da177e4SLinus Torvalds 	 *  Packets in sequence go to the receive queue.
46071da177e4SLinus Torvalds 	 *  Out of sequence packets to the out_of_order_queue.
46081da177e4SLinus Torvalds 	 */
46091da177e4SLinus Torvalds 	if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt) {
46101da177e4SLinus Torvalds 		if (tcp_receive_window(tp) == 0)
46111da177e4SLinus Torvalds 			goto out_of_window;
46121da177e4SLinus Torvalds 
46131da177e4SLinus Torvalds 		/* Ok. In sequence. In window. */
46141da177e4SLinus Torvalds 		if (tp->ucopy.task == current &&
46151da177e4SLinus Torvalds 		    tp->copied_seq == tp->rcv_nxt && tp->ucopy.len &&
46161da177e4SLinus Torvalds 		    sock_owned_by_user(sk) && !tp->urg_data) {
46171da177e4SLinus Torvalds 			int chunk = min_t(unsigned int, skb->len,
46181da177e4SLinus Torvalds 					  tp->ucopy.len);
46191da177e4SLinus Torvalds 
46201da177e4SLinus Torvalds 			__set_current_state(TASK_RUNNING);
46211da177e4SLinus Torvalds 
4622f4362a2cSAl Viro 			if (!skb_copy_datagram_msg(skb, 0, tp->ucopy.msg, chunk)) {
46231da177e4SLinus Torvalds 				tp->ucopy.len -= chunk;
46241da177e4SLinus Torvalds 				tp->copied_seq += chunk;
462544f5324bSJerry Chu 				eaten = (chunk == skb->len);
46261da177e4SLinus Torvalds 				tcp_rcv_space_adjust(sk);
46271da177e4SLinus Torvalds 			}
46281da177e4SLinus Torvalds 		}
46291da177e4SLinus Torvalds 
46301da177e4SLinus Torvalds 		if (eaten <= 0) {
46311da177e4SLinus Torvalds queue_and_out:
463276dfa608SEric Dumazet 			if (eaten < 0) {
463376dfa608SEric Dumazet 				if (skb_queue_len(&sk->sk_receive_queue) == 0)
463476dfa608SEric Dumazet 					sk_forced_mem_schedule(sk, skb->truesize);
463576dfa608SEric Dumazet 				else if (tcp_try_rmem_schedule(sk, skb, skb->truesize))
46361da177e4SLinus Torvalds 					goto drop;
463776dfa608SEric Dumazet 			}
4638b081f85cSEric Dumazet 			eaten = tcp_queue_rcv(sk, skb, 0, &fragstolen);
46391402d366SEric Dumazet 		}
4640bdd1f9edSEric Dumazet 		tcp_rcv_nxt_update(tp, TCP_SKB_CB(skb)->end_seq);
46411da177e4SLinus Torvalds 		if (skb->len)
46429e412ba7SIlpo Järvinen 			tcp_event_data_recv(sk, skb);
4643155c6e1aSPeter Pan(潘卫平) 		if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
464420c4cb79SEric Dumazet 			tcp_fin(sk);
46451da177e4SLinus Torvalds 
46469f5afeaeSYaogong Wang 		if (!RB_EMPTY_ROOT(&tp->out_of_order_queue)) {
46471da177e4SLinus Torvalds 			tcp_ofo_queue(sk);
46481da177e4SLinus Torvalds 
46491da177e4SLinus Torvalds 			/* RFC2581. 4.2. SHOULD send immediate ACK, when
46501da177e4SLinus Torvalds 			 * gap in queue is filled.
46511da177e4SLinus Torvalds 			 */
46529f5afeaeSYaogong Wang 			if (RB_EMPTY_ROOT(&tp->out_of_order_queue))
4653463c84b9SArnaldo Carvalho de Melo 				inet_csk(sk)->icsk_ack.pingpong = 0;
46541da177e4SLinus Torvalds 		}
46551da177e4SLinus Torvalds 
46561da177e4SLinus Torvalds 		if (tp->rx_opt.num_sacks)
46571da177e4SLinus Torvalds 			tcp_sack_remove(tp);
46581da177e4SLinus Torvalds 
46599e412ba7SIlpo Järvinen 		tcp_fast_path_check(sk);
46601da177e4SLinus Torvalds 
4661923dd347SEric Dumazet 		if (eaten > 0)
4662923dd347SEric Dumazet 			kfree_skb_partial(skb, fragstolen);
46631d57f195SEric Dumazet 		if (!sock_flag(sk, SOCK_DEAD))
4664676d2369SDavid S. Miller 			sk->sk_data_ready(sk);
46651da177e4SLinus Torvalds 		return;
46661da177e4SLinus Torvalds 	}
46671da177e4SLinus Torvalds 
46681da177e4SLinus Torvalds 	if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) {
46691da177e4SLinus Torvalds 		/* A retransmit, 2nd most common case.  Force an immediate ack. */
4670c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_DELAYEDACKLOST);
46711ed83465SPavel Emelyanov 		tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq);
46721da177e4SLinus Torvalds 
46731da177e4SLinus Torvalds out_of_window:
4674463c84b9SArnaldo Carvalho de Melo 		tcp_enter_quickack_mode(sk);
4675463c84b9SArnaldo Carvalho de Melo 		inet_csk_schedule_ack(sk);
46761da177e4SLinus Torvalds drop:
4677532182cdSEric Dumazet 		tcp_drop(sk, skb);
46781da177e4SLinus Torvalds 		return;
46791da177e4SLinus Torvalds 	}
46801da177e4SLinus Torvalds 
46811da177e4SLinus Torvalds 	/* Out of window. F.e. zero window probe. */
46821da177e4SLinus Torvalds 	if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt + tcp_receive_window(tp)))
46831da177e4SLinus Torvalds 		goto out_of_window;
46841da177e4SLinus Torvalds 
4685463c84b9SArnaldo Carvalho de Melo 	tcp_enter_quickack_mode(sk);
46861da177e4SLinus Torvalds 
46871da177e4SLinus Torvalds 	if (before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
46881da177e4SLinus Torvalds 		/* Partial packet, seq < rcv_next < end_seq */
46891da177e4SLinus Torvalds 		SOCK_DEBUG(sk, "partial packet: rcv_next %X seq %X - %X\n",
46901da177e4SLinus Torvalds 			   tp->rcv_nxt, TCP_SKB_CB(skb)->seq,
46911da177e4SLinus Torvalds 			   TCP_SKB_CB(skb)->end_seq);
46921da177e4SLinus Torvalds 
46931ed83465SPavel Emelyanov 		tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, tp->rcv_nxt);
46941da177e4SLinus Torvalds 
46951da177e4SLinus Torvalds 		/* If window is closed, drop tail of packet. But after
46961da177e4SLinus Torvalds 		 * remembering D-SACK for its head made in previous line.
46971da177e4SLinus Torvalds 		 */
46981da177e4SLinus Torvalds 		if (!tcp_receive_window(tp))
46991da177e4SLinus Torvalds 			goto out_of_window;
47001da177e4SLinus Torvalds 		goto queue_and_out;
47011da177e4SLinus Torvalds 	}
47021da177e4SLinus Torvalds 
4703e86b2919SEric Dumazet 	tcp_data_queue_ofo(sk, skb);
47041da177e4SLinus Torvalds }
47051da177e4SLinus Torvalds 
47069f5afeaeSYaogong Wang static struct sk_buff *tcp_skb_next(struct sk_buff *skb, struct sk_buff_head *list)
47072cf46637SIlpo Järvinen {
47089f5afeaeSYaogong Wang 	if (list)
47099f5afeaeSYaogong Wang 		return !skb_queue_is_last(list, skb) ? skb->next : NULL;
471091521944SDavid S. Miller 
47119f5afeaeSYaogong Wang 	return rb_entry_safe(rb_next(&skb->rbnode), struct sk_buff, rbnode);
47129f5afeaeSYaogong Wang }
47132cf46637SIlpo Järvinen 
47149f5afeaeSYaogong Wang static struct sk_buff *tcp_collapse_one(struct sock *sk, struct sk_buff *skb,
47159f5afeaeSYaogong Wang 					struct sk_buff_head *list,
47169f5afeaeSYaogong Wang 					struct rb_root *root)
47179f5afeaeSYaogong Wang {
47189f5afeaeSYaogong Wang 	struct sk_buff *next = tcp_skb_next(skb, list);
47199f5afeaeSYaogong Wang 
47209f5afeaeSYaogong Wang 	if (list)
47212cf46637SIlpo Järvinen 		__skb_unlink(skb, list);
47229f5afeaeSYaogong Wang 	else
47239f5afeaeSYaogong Wang 		rb_erase(&skb->rbnode, root);
47249f5afeaeSYaogong Wang 
47252cf46637SIlpo Järvinen 	__kfree_skb(skb);
4726c10d9310SEric Dumazet 	NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPRCVCOLLAPSED);
47272cf46637SIlpo Järvinen 
47282cf46637SIlpo Järvinen 	return next;
47292cf46637SIlpo Järvinen }
47302cf46637SIlpo Järvinen 
47319f5afeaeSYaogong Wang /* Insert skb into rb tree, ordered by TCP_SKB_CB(skb)->seq */
47329f5afeaeSYaogong Wang static void tcp_rbtree_insert(struct rb_root *root, struct sk_buff *skb)
47339f5afeaeSYaogong Wang {
47349f5afeaeSYaogong Wang 	struct rb_node **p = &root->rb_node;
47359f5afeaeSYaogong Wang 	struct rb_node *parent = NULL;
47369f5afeaeSYaogong Wang 	struct sk_buff *skb1;
47379f5afeaeSYaogong Wang 
47389f5afeaeSYaogong Wang 	while (*p) {
47399f5afeaeSYaogong Wang 		parent = *p;
47409f5afeaeSYaogong Wang 		skb1 = rb_entry(parent, struct sk_buff, rbnode);
47419f5afeaeSYaogong Wang 		if (before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb1)->seq))
47429f5afeaeSYaogong Wang 			p = &parent->rb_left;
47439f5afeaeSYaogong Wang 		else
47449f5afeaeSYaogong Wang 			p = &parent->rb_right;
47459f5afeaeSYaogong Wang 	}
47469f5afeaeSYaogong Wang 	rb_link_node(&skb->rbnode, parent, p);
47479f5afeaeSYaogong Wang 	rb_insert_color(&skb->rbnode, root);
47489f5afeaeSYaogong Wang }
47499f5afeaeSYaogong Wang 
47501da177e4SLinus Torvalds /* Collapse contiguous sequence of skbs head..tail with
47511da177e4SLinus Torvalds  * sequence numbers start..end.
475291521944SDavid S. Miller  *
47539f5afeaeSYaogong Wang  * If tail is NULL, this means until the end of the queue.
475491521944SDavid S. Miller  *
47551da177e4SLinus Torvalds  * Segments with FIN/SYN are not collapsed (only because this
47561da177e4SLinus Torvalds  * simplifies code)
47571da177e4SLinus Torvalds  */
47581da177e4SLinus Torvalds static void
47599f5afeaeSYaogong Wang tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root,
47609f5afeaeSYaogong Wang 	     struct sk_buff *head, struct sk_buff *tail, u32 start, u32 end)
47611da177e4SLinus Torvalds {
47629f5afeaeSYaogong Wang 	struct sk_buff *skb = head, *n;
47639f5afeaeSYaogong Wang 	struct sk_buff_head tmp;
476491521944SDavid S. Miller 	bool end_of_skbs;
47651da177e4SLinus Torvalds 
4766caa20d9aSStephen Hemminger 	/* First, check that queue is collapsible and find
47679f5afeaeSYaogong Wang 	 * the point where collapsing can be useful.
47689f5afeaeSYaogong Wang 	 */
476991521944SDavid S. Miller restart:
47709f5afeaeSYaogong Wang 	for (end_of_skbs = true; skb != NULL && skb != tail; skb = n) {
47719f5afeaeSYaogong Wang 		n = tcp_skb_next(skb, list);
47729f5afeaeSYaogong Wang 
47731da177e4SLinus Torvalds 		/* No new bits? It is possible on ofo queue. */
47741da177e4SLinus Torvalds 		if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
47759f5afeaeSYaogong Wang 			skb = tcp_collapse_one(sk, skb, list, root);
477691521944SDavid S. Miller 			if (!skb)
477791521944SDavid S. Miller 				break;
477891521944SDavid S. Miller 			goto restart;
47791da177e4SLinus Torvalds 		}
47801da177e4SLinus Torvalds 
47811da177e4SLinus Torvalds 		/* The first skb to collapse is:
47821da177e4SLinus Torvalds 		 * - not SYN/FIN and
47831da177e4SLinus Torvalds 		 * - bloated or contains data before "start" or
47841da177e4SLinus Torvalds 		 *   overlaps to the next one.
47851da177e4SLinus Torvalds 		 */
4786e11ecddfSEric Dumazet 		if (!(TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN)) &&
47871da177e4SLinus Torvalds 		    (tcp_win_from_space(skb->truesize) > skb->len ||
478891521944SDavid S. Miller 		     before(TCP_SKB_CB(skb)->seq, start))) {
478991521944SDavid S. Miller 			end_of_skbs = false;
47901da177e4SLinus Torvalds 			break;
479191521944SDavid S. Miller 		}
479291521944SDavid S. Miller 
47939f5afeaeSYaogong Wang 		if (n && n != tail &&
47949f5afeaeSYaogong Wang 		    TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(n)->seq) {
479591521944SDavid S. Miller 			end_of_skbs = false;
479691521944SDavid S. Miller 			break;
479791521944SDavid S. Miller 		}
47981da177e4SLinus Torvalds 
47991da177e4SLinus Torvalds 		/* Decided to skip this, advance start seq. */
48001da177e4SLinus Torvalds 		start = TCP_SKB_CB(skb)->end_seq;
48011da177e4SLinus Torvalds 	}
4802e11ecddfSEric Dumazet 	if (end_of_skbs ||
4803e11ecddfSEric Dumazet 	    (TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN)))
48041da177e4SLinus Torvalds 		return;
48051da177e4SLinus Torvalds 
48069f5afeaeSYaogong Wang 	__skb_queue_head_init(&tmp);
48079f5afeaeSYaogong Wang 
48081da177e4SLinus Torvalds 	while (before(start, end)) {
4809b3d6cb92SEric Dumazet 		int copy = min_t(int, SKB_MAX_ORDER(0, 0), end - start);
48101da177e4SLinus Torvalds 		struct sk_buff *nskb;
48111da177e4SLinus Torvalds 
4812b3d6cb92SEric Dumazet 		nskb = alloc_skb(copy, GFP_ATOMIC);
48131da177e4SLinus Torvalds 		if (!nskb)
48149f5afeaeSYaogong Wang 			break;
4815c51957daSArnaldo Carvalho de Melo 
48161da177e4SLinus Torvalds 		memcpy(nskb->cb, skb->cb, sizeof(skb->cb));
48171da177e4SLinus Torvalds 		TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(nskb)->end_seq = start;
48189f5afeaeSYaogong Wang 		if (list)
481943f59c89SDavid S. Miller 			__skb_queue_before(list, skb, nskb);
48209f5afeaeSYaogong Wang 		else
48219f5afeaeSYaogong Wang 			__skb_queue_tail(&tmp, nskb); /* defer rbtree insertion */
48223ab224beSHideo Aoki 		skb_set_owner_r(nskb, sk);
48231da177e4SLinus Torvalds 
48241da177e4SLinus Torvalds 		/* Copy data, releasing collapsed skbs. */
48251da177e4SLinus Torvalds 		while (copy > 0) {
48261da177e4SLinus Torvalds 			int offset = start - TCP_SKB_CB(skb)->seq;
48271da177e4SLinus Torvalds 			int size = TCP_SKB_CB(skb)->end_seq - start;
48281da177e4SLinus Torvalds 
482909a62660SKris Katterjohn 			BUG_ON(offset < 0);
48301da177e4SLinus Torvalds 			if (size > 0) {
48311da177e4SLinus Torvalds 				size = min(copy, size);
48321da177e4SLinus Torvalds 				if (skb_copy_bits(skb, offset, skb_put(nskb, size), size))
48331da177e4SLinus Torvalds 					BUG();
48341da177e4SLinus Torvalds 				TCP_SKB_CB(nskb)->end_seq += size;
48351da177e4SLinus Torvalds 				copy -= size;
48361da177e4SLinus Torvalds 				start += size;
48371da177e4SLinus Torvalds 			}
48381da177e4SLinus Torvalds 			if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
48399f5afeaeSYaogong Wang 				skb = tcp_collapse_one(sk, skb, list, root);
484091521944SDavid S. Miller 				if (!skb ||
484191521944SDavid S. Miller 				    skb == tail ||
4842e11ecddfSEric Dumazet 				    (TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN)))
48439f5afeaeSYaogong Wang 					goto end;
48441da177e4SLinus Torvalds 			}
48451da177e4SLinus Torvalds 		}
48461da177e4SLinus Torvalds 	}
48479f5afeaeSYaogong Wang end:
48489f5afeaeSYaogong Wang 	skb_queue_walk_safe(&tmp, skb, n)
48499f5afeaeSYaogong Wang 		tcp_rbtree_insert(root, skb);
48501da177e4SLinus Torvalds }
48511da177e4SLinus Torvalds 
48521da177e4SLinus Torvalds /* Collapse ofo queue. Algorithm: select contiguous sequence of skbs
48531da177e4SLinus Torvalds  * and tcp_collapse() them until all the queue is collapsed.
48541da177e4SLinus Torvalds  */
48551da177e4SLinus Torvalds static void tcp_collapse_ofo_queue(struct sock *sk)
48561da177e4SLinus Torvalds {
48571da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
48589f5afeaeSYaogong Wang 	struct sk_buff *skb, *head;
48599f5afeaeSYaogong Wang 	struct rb_node *p;
48601da177e4SLinus Torvalds 	u32 start, end;
48611da177e4SLinus Torvalds 
48629f5afeaeSYaogong Wang 	p = rb_first(&tp->out_of_order_queue);
48639f5afeaeSYaogong Wang 	skb = rb_entry_safe(p, struct sk_buff, rbnode);
48649f5afeaeSYaogong Wang new_range:
48659f5afeaeSYaogong Wang 	if (!skb) {
48669f5afeaeSYaogong Wang 		p = rb_last(&tp->out_of_order_queue);
48679f5afeaeSYaogong Wang 		/* Note: This is possible p is NULL here. We do not
48689f5afeaeSYaogong Wang 		 * use rb_entry_safe(), as ooo_last_skb is valid only
48699f5afeaeSYaogong Wang 		 * if rbtree is not empty.
48709f5afeaeSYaogong Wang 		 */
48719f5afeaeSYaogong Wang 		tp->ooo_last_skb = rb_entry(p, struct sk_buff, rbnode);
48721da177e4SLinus Torvalds 		return;
48739f5afeaeSYaogong Wang 	}
48741da177e4SLinus Torvalds 	start = TCP_SKB_CB(skb)->seq;
48751da177e4SLinus Torvalds 	end = TCP_SKB_CB(skb)->end_seq;
48761da177e4SLinus Torvalds 
48779f5afeaeSYaogong Wang 	for (head = skb;;) {
48789f5afeaeSYaogong Wang 		skb = tcp_skb_next(skb, NULL);
487991521944SDavid S. Miller 
48809f5afeaeSYaogong Wang 		/* Range is terminated when we see a gap or when
48819f5afeaeSYaogong Wang 		 * we are at the queue end.
48829f5afeaeSYaogong Wang 		 */
488391521944SDavid S. Miller 		if (!skb ||
48841da177e4SLinus Torvalds 		    after(TCP_SKB_CB(skb)->seq, end) ||
48851da177e4SLinus Torvalds 		    before(TCP_SKB_CB(skb)->end_seq, start)) {
48869f5afeaeSYaogong Wang 			tcp_collapse(sk, NULL, &tp->out_of_order_queue,
48878728b834SDavid S. Miller 				     head, skb, start, end);
48889f5afeaeSYaogong Wang 			goto new_range;
48899f5afeaeSYaogong Wang 		}
48909f5afeaeSYaogong Wang 
48919f5afeaeSYaogong Wang 		if (unlikely(before(TCP_SKB_CB(skb)->seq, start)))
48921da177e4SLinus Torvalds 			start = TCP_SKB_CB(skb)->seq;
48931da177e4SLinus Torvalds 		if (after(TCP_SKB_CB(skb)->end_seq, end))
48941da177e4SLinus Torvalds 			end = TCP_SKB_CB(skb)->end_seq;
48951da177e4SLinus Torvalds 	}
48961da177e4SLinus Torvalds }
48971da177e4SLinus Torvalds 
4898b000cd37SVitaliy Gusev /*
489936a6503fSEric Dumazet  * Clean the out-of-order queue to make room.
490036a6503fSEric Dumazet  * We drop high sequences packets to :
490136a6503fSEric Dumazet  * 1) Let a chance for holes to be filled.
490236a6503fSEric Dumazet  * 2) not add too big latencies if thousands of packets sit there.
490336a6503fSEric Dumazet  *    (But if application shrinks SO_RCVBUF, we could still end up
490436a6503fSEric Dumazet  *     freeing whole queue here)
490536a6503fSEric Dumazet  *
490636a6503fSEric Dumazet  * Return true if queue has shrunk.
4907b000cd37SVitaliy Gusev  */
4908a2a385d6SEric Dumazet static bool tcp_prune_ofo_queue(struct sock *sk)
4909b000cd37SVitaliy Gusev {
4910b000cd37SVitaliy Gusev 	struct tcp_sock *tp = tcp_sk(sk);
49119f5afeaeSYaogong Wang 	struct rb_node *node, *prev;
4912b000cd37SVitaliy Gusev 
49139f5afeaeSYaogong Wang 	if (RB_EMPTY_ROOT(&tp->out_of_order_queue))
491436a6503fSEric Dumazet 		return false;
491536a6503fSEric Dumazet 
4916c10d9310SEric Dumazet 	NET_INC_STATS(sock_net(sk), LINUX_MIB_OFOPRUNED);
49179f5afeaeSYaogong Wang 	node = &tp->ooo_last_skb->rbnode;
49189f5afeaeSYaogong Wang 	do {
49199f5afeaeSYaogong Wang 		prev = rb_prev(node);
49209f5afeaeSYaogong Wang 		rb_erase(node, &tp->out_of_order_queue);
49219f5afeaeSYaogong Wang 		tcp_drop(sk, rb_entry(node, struct sk_buff, rbnode));
492236a6503fSEric Dumazet 		sk_mem_reclaim(sk);
492336a6503fSEric Dumazet 		if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf &&
492436a6503fSEric Dumazet 		    !tcp_under_memory_pressure(sk))
492536a6503fSEric Dumazet 			break;
49269f5afeaeSYaogong Wang 		node = prev;
49279f5afeaeSYaogong Wang 	} while (node);
49289f5afeaeSYaogong Wang 	tp->ooo_last_skb = rb_entry(prev, struct sk_buff, rbnode);
4929b000cd37SVitaliy Gusev 
4930b000cd37SVitaliy Gusev 	/* Reset SACK state.  A conforming SACK implementation will
4931b000cd37SVitaliy Gusev 	 * do the same at a timeout based retransmit.  When a connection
4932b000cd37SVitaliy Gusev 	 * is in a sad state like this, we care only about integrity
4933b000cd37SVitaliy Gusev 	 * of the connection not performance.
4934b000cd37SVitaliy Gusev 	 */
4935b000cd37SVitaliy Gusev 	if (tp->rx_opt.sack_ok)
4936b000cd37SVitaliy Gusev 		tcp_sack_reset(&tp->rx_opt);
493736a6503fSEric Dumazet 	return true;
4938b000cd37SVitaliy Gusev }
4939b000cd37SVitaliy Gusev 
49401da177e4SLinus Torvalds /* Reduce allocated memory if we can, trying to get
49411da177e4SLinus Torvalds  * the socket within its memory limits again.
49421da177e4SLinus Torvalds  *
49431da177e4SLinus Torvalds  * Return less than zero if we should start dropping frames
49441da177e4SLinus Torvalds  * until the socket owning process reads some of the data
49451da177e4SLinus Torvalds  * to stabilize the situation.
49461da177e4SLinus Torvalds  */
49471da177e4SLinus Torvalds static int tcp_prune_queue(struct sock *sk)
49481da177e4SLinus Torvalds {
49491da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
49501da177e4SLinus Torvalds 
49511da177e4SLinus Torvalds 	SOCK_DEBUG(sk, "prune_queue: c=%x\n", tp->copied_seq);
49521da177e4SLinus Torvalds 
4953c10d9310SEric Dumazet 	NET_INC_STATS(sock_net(sk), LINUX_MIB_PRUNECALLED);
49541da177e4SLinus Torvalds 
49551da177e4SLinus Torvalds 	if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
49569e412ba7SIlpo Järvinen 		tcp_clamp_window(sk);
4957b8da51ebSEric Dumazet 	else if (tcp_under_memory_pressure(sk))
49581da177e4SLinus Torvalds 		tp->rcv_ssthresh = min(tp->rcv_ssthresh, 4U * tp->advmss);
49591da177e4SLinus Torvalds 
49601da177e4SLinus Torvalds 	tcp_collapse_ofo_queue(sk);
496191521944SDavid S. Miller 	if (!skb_queue_empty(&sk->sk_receive_queue))
49629f5afeaeSYaogong Wang 		tcp_collapse(sk, &sk->sk_receive_queue, NULL,
496391521944SDavid S. Miller 			     skb_peek(&sk->sk_receive_queue),
496491521944SDavid S. Miller 			     NULL,
49651da177e4SLinus Torvalds 			     tp->copied_seq, tp->rcv_nxt);
49663ab224beSHideo Aoki 	sk_mem_reclaim(sk);
49671da177e4SLinus Torvalds 
49681da177e4SLinus Torvalds 	if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf)
49691da177e4SLinus Torvalds 		return 0;
49701da177e4SLinus Torvalds 
49711da177e4SLinus Torvalds 	/* Collapsing did not help, destructive actions follow.
49721da177e4SLinus Torvalds 	 * This must not ever occur. */
49731da177e4SLinus Torvalds 
4974b000cd37SVitaliy Gusev 	tcp_prune_ofo_queue(sk);
49751da177e4SLinus Torvalds 
49761da177e4SLinus Torvalds 	if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf)
49771da177e4SLinus Torvalds 		return 0;
49781da177e4SLinus Torvalds 
49791da177e4SLinus Torvalds 	/* If we are really being abused, tell the caller to silently
49801da177e4SLinus Torvalds 	 * drop receive data on the floor.  It will get retransmitted
49811da177e4SLinus Torvalds 	 * and hopefully then we'll have sufficient space.
49821da177e4SLinus Torvalds 	 */
4983c10d9310SEric Dumazet 	NET_INC_STATS(sock_net(sk), LINUX_MIB_RCVPRUNED);
49841da177e4SLinus Torvalds 
49851da177e4SLinus Torvalds 	/* Massive buffer overcommit. */
49861da177e4SLinus Torvalds 	tp->pred_flags = 0;
49871da177e4SLinus Torvalds 	return -1;
49881da177e4SLinus Torvalds }
49891da177e4SLinus Torvalds 
4990a2a385d6SEric Dumazet static bool tcp_should_expand_sndbuf(const struct sock *sk)
49910d9901dfSDavid S. Miller {
4992cf533ea5SEric Dumazet 	const struct tcp_sock *tp = tcp_sk(sk);
49939e412ba7SIlpo Järvinen 
49940d9901dfSDavid S. Miller 	/* If the user specified a specific send buffer setting, do
49950d9901dfSDavid S. Miller 	 * not modify it.
49960d9901dfSDavid S. Miller 	 */
49970d9901dfSDavid S. Miller 	if (sk->sk_userlocks & SOCK_SNDBUF_LOCK)
4998a2a385d6SEric Dumazet 		return false;
49990d9901dfSDavid S. Miller 
50000d9901dfSDavid S. Miller 	/* If we are under global TCP memory pressure, do not expand.  */
5001b8da51ebSEric Dumazet 	if (tcp_under_memory_pressure(sk))
5002a2a385d6SEric Dumazet 		return false;
50030d9901dfSDavid S. Miller 
50040d9901dfSDavid S. Miller 	/* If we are under soft global TCP memory pressure, do not expand.  */
5005180d8cd9SGlauber Costa 	if (sk_memory_allocated(sk) >= sk_prot_mem_limits(sk, 0))
5006a2a385d6SEric Dumazet 		return false;
50070d9901dfSDavid S. Miller 
50080d9901dfSDavid S. Miller 	/* If we filled the congestion window, do not expand.  */
50096514890fSNeal Cardwell 	if (tcp_packets_in_flight(tp) >= tp->snd_cwnd)
5010a2a385d6SEric Dumazet 		return false;
50110d9901dfSDavid S. Miller 
5012a2a385d6SEric Dumazet 	return true;
50130d9901dfSDavid S. Miller }
50141da177e4SLinus Torvalds 
50151da177e4SLinus Torvalds /* When incoming ACK allowed to free some skb from write_queue,
50161da177e4SLinus Torvalds  * we remember this event in flag SOCK_QUEUE_SHRUNK and wake up socket
50171da177e4SLinus Torvalds  * on the exit from tcp input handler.
50181da177e4SLinus Torvalds  *
50191da177e4SLinus Torvalds  * PROBLEM: sndbuf expansion does not work well with largesend.
50201da177e4SLinus Torvalds  */
50211da177e4SLinus Torvalds static void tcp_new_space(struct sock *sk)
50221da177e4SLinus Torvalds {
50231da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
50241da177e4SLinus Torvalds 
50259e412ba7SIlpo Järvinen 	if (tcp_should_expand_sndbuf(sk)) {
50266ae70532SEric Dumazet 		tcp_sndbuf_expand(sk);
5027c2203cf7SEric Dumazet 		tp->snd_cwnd_stamp = tcp_jiffies32;
50281da177e4SLinus Torvalds 	}
50291da177e4SLinus Torvalds 
50301da177e4SLinus Torvalds 	sk->sk_write_space(sk);
50311da177e4SLinus Torvalds }
50321da177e4SLinus Torvalds 
503340efc6faSStephen Hemminger static void tcp_check_space(struct sock *sk)
50341da177e4SLinus Torvalds {
50351da177e4SLinus Torvalds 	if (sock_flag(sk, SOCK_QUEUE_SHRUNK)) {
50361da177e4SLinus Torvalds 		sock_reset_flag(sk, SOCK_QUEUE_SHRUNK);
50373c715127Sjbaron@akamai.com 		/* pairs with tcp_poll() */
503856d80622SJason Baron 		smp_mb();
50391da177e4SLinus Torvalds 		if (sk->sk_socket &&
5040b0f71bd3SFrancis Yan 		    test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
50411da177e4SLinus Torvalds 			tcp_new_space(sk);
5042b0f71bd3SFrancis Yan 			if (!test_bit(SOCK_NOSPACE, &sk->sk_socket->flags))
5043b0f71bd3SFrancis Yan 				tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED);
5044b0f71bd3SFrancis Yan 		}
50451da177e4SLinus Torvalds 	}
50461da177e4SLinus Torvalds }
50471da177e4SLinus Torvalds 
50489e412ba7SIlpo Järvinen static inline void tcp_data_snd_check(struct sock *sk)
50491da177e4SLinus Torvalds {
50509e412ba7SIlpo Järvinen 	tcp_push_pending_frames(sk);
50511da177e4SLinus Torvalds 	tcp_check_space(sk);
50521da177e4SLinus Torvalds }
50531da177e4SLinus Torvalds 
50541da177e4SLinus Torvalds /*
50551da177e4SLinus Torvalds  * Check if sending an ack is needed.
50561da177e4SLinus Torvalds  */
50571da177e4SLinus Torvalds static void __tcp_ack_snd_check(struct sock *sk, int ofo_possible)
50581da177e4SLinus Torvalds {
50591da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
50601da177e4SLinus Torvalds 
50611da177e4SLinus Torvalds 	    /* More than one full frame received... */
50629d4fb27dSJoe Perches 	if (((tp->rcv_nxt - tp->rcv_wup) > inet_csk(sk)->icsk_ack.rcv_mss &&
50631da177e4SLinus Torvalds 	     /* ... and right edge of window advances far enough.
50641da177e4SLinus Torvalds 	      * (tcp_recvmsg() will send ACK otherwise). Or...
50651da177e4SLinus Torvalds 	      */
50669d4fb27dSJoe Perches 	     __tcp_select_window(sk) >= tp->rcv_wnd) ||
50671da177e4SLinus Torvalds 	    /* We ACK each frame or... */
5068463c84b9SArnaldo Carvalho de Melo 	    tcp_in_quickack_mode(sk) ||
50691da177e4SLinus Torvalds 	    /* We have out of order data. */
50709f5afeaeSYaogong Wang 	    (ofo_possible && !RB_EMPTY_ROOT(&tp->out_of_order_queue))) {
50711da177e4SLinus Torvalds 		/* Then ack it now */
50721da177e4SLinus Torvalds 		tcp_send_ack(sk);
50731da177e4SLinus Torvalds 	} else {
50741da177e4SLinus Torvalds 		/* Else, send delayed ack. */
50751da177e4SLinus Torvalds 		tcp_send_delayed_ack(sk);
50761da177e4SLinus Torvalds 	}
50771da177e4SLinus Torvalds }
50781da177e4SLinus Torvalds 
507940efc6faSStephen Hemminger static inline void tcp_ack_snd_check(struct sock *sk)
50801da177e4SLinus Torvalds {
5081463c84b9SArnaldo Carvalho de Melo 	if (!inet_csk_ack_scheduled(sk)) {
50821da177e4SLinus Torvalds 		/* We sent a data segment already. */
50831da177e4SLinus Torvalds 		return;
50841da177e4SLinus Torvalds 	}
50851da177e4SLinus Torvalds 	__tcp_ack_snd_check(sk, 1);
50861da177e4SLinus Torvalds }
50871da177e4SLinus Torvalds 
50881da177e4SLinus Torvalds /*
50891da177e4SLinus Torvalds  *	This routine is only called when we have urgent data
5090caa20d9aSStephen Hemminger  *	signaled. Its the 'slow' part of tcp_urg. It could be
50911da177e4SLinus Torvalds  *	moved inline now as tcp_urg is only called from one
50921da177e4SLinus Torvalds  *	place. We handle URGent data wrong. We have to - as
50931da177e4SLinus Torvalds  *	BSD still doesn't use the correction from RFC961.
50941da177e4SLinus Torvalds  *	For 1003.1g we should support a new option TCP_STDURG to permit
50951da177e4SLinus Torvalds  *	either form (or just set the sysctl tcp_stdurg).
50961da177e4SLinus Torvalds  */
50971da177e4SLinus Torvalds 
5098cf533ea5SEric Dumazet static void tcp_check_urg(struct sock *sk, const struct tcphdr *th)
50991da177e4SLinus Torvalds {
51001da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
51011da177e4SLinus Torvalds 	u32 ptr = ntohs(th->urg_ptr);
51021da177e4SLinus Torvalds 
51031da177e4SLinus Torvalds 	if (ptr && !sysctl_tcp_stdurg)
51041da177e4SLinus Torvalds 		ptr--;
51051da177e4SLinus Torvalds 	ptr += ntohl(th->seq);
51061da177e4SLinus Torvalds 
51071da177e4SLinus Torvalds 	/* Ignore urgent data that we've already seen and read. */
51081da177e4SLinus Torvalds 	if (after(tp->copied_seq, ptr))
51091da177e4SLinus Torvalds 		return;
51101da177e4SLinus Torvalds 
51111da177e4SLinus Torvalds 	/* Do not replay urg ptr.
51121da177e4SLinus Torvalds 	 *
51131da177e4SLinus Torvalds 	 * NOTE: interesting situation not covered by specs.
51141da177e4SLinus Torvalds 	 * Misbehaving sender may send urg ptr, pointing to segment,
51151da177e4SLinus Torvalds 	 * which we already have in ofo queue. We are not able to fetch
51161da177e4SLinus Torvalds 	 * such data and will stay in TCP_URG_NOTYET until will be eaten
51171da177e4SLinus Torvalds 	 * by recvmsg(). Seems, we are not obliged to handle such wicked
51181da177e4SLinus Torvalds 	 * situations. But it is worth to think about possibility of some
51191da177e4SLinus Torvalds 	 * DoSes using some hypothetical application level deadlock.
51201da177e4SLinus Torvalds 	 */
51211da177e4SLinus Torvalds 	if (before(ptr, tp->rcv_nxt))
51221da177e4SLinus Torvalds 		return;
51231da177e4SLinus Torvalds 
51241da177e4SLinus Torvalds 	/* Do we already have a newer (or duplicate) urgent pointer? */
51251da177e4SLinus Torvalds 	if (tp->urg_data && !after(ptr, tp->urg_seq))
51261da177e4SLinus Torvalds 		return;
51271da177e4SLinus Torvalds 
51281da177e4SLinus Torvalds 	/* Tell the world about our new urgent pointer. */
51291da177e4SLinus Torvalds 	sk_send_sigurg(sk);
51301da177e4SLinus Torvalds 
51311da177e4SLinus Torvalds 	/* We may be adding urgent data when the last byte read was
51321da177e4SLinus Torvalds 	 * urgent. To do this requires some care. We cannot just ignore
51331da177e4SLinus Torvalds 	 * tp->copied_seq since we would read the last urgent byte again
51341da177e4SLinus Torvalds 	 * as data, nor can we alter copied_seq until this data arrives
5135caa20d9aSStephen Hemminger 	 * or we break the semantics of SIOCATMARK (and thus sockatmark())
51361da177e4SLinus Torvalds 	 *
51371da177e4SLinus Torvalds 	 * NOTE. Double Dutch. Rendering to plain English: author of comment
51381da177e4SLinus Torvalds 	 * above did something sort of 	send("A", MSG_OOB); send("B", MSG_OOB);
51391da177e4SLinus Torvalds 	 * and expect that both A and B disappear from stream. This is _wrong_.
51401da177e4SLinus Torvalds 	 * Though this happens in BSD with high probability, this is occasional.
51411da177e4SLinus Torvalds 	 * Any application relying on this is buggy. Note also, that fix "works"
51421da177e4SLinus Torvalds 	 * only in this artificial test. Insert some normal data between A and B and we will
51431da177e4SLinus Torvalds 	 * decline of BSD again. Verdict: it is better to remove to trap
51441da177e4SLinus Torvalds 	 * buggy users.
51451da177e4SLinus Torvalds 	 */
51461da177e4SLinus Torvalds 	if (tp->urg_seq == tp->copied_seq && tp->urg_data &&
5147056834d9SIlpo Järvinen 	    !sock_flag(sk, SOCK_URGINLINE) && tp->copied_seq != tp->rcv_nxt) {
51481da177e4SLinus Torvalds 		struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
51491da177e4SLinus Torvalds 		tp->copied_seq++;
51501da177e4SLinus Torvalds 		if (skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq)) {
51518728b834SDavid S. Miller 			__skb_unlink(skb, &sk->sk_receive_queue);
51521da177e4SLinus Torvalds 			__kfree_skb(skb);
51531da177e4SLinus Torvalds 		}
51541da177e4SLinus Torvalds 	}
51551da177e4SLinus Torvalds 
51561da177e4SLinus Torvalds 	tp->urg_data = TCP_URG_NOTYET;
51571da177e4SLinus Torvalds 	tp->urg_seq = ptr;
51581da177e4SLinus Torvalds 
51591da177e4SLinus Torvalds 	/* Disable header prediction. */
51601da177e4SLinus Torvalds 	tp->pred_flags = 0;
51611da177e4SLinus Torvalds }
51621da177e4SLinus Torvalds 
51631da177e4SLinus Torvalds /* This is the 'fast' part of urgent handling. */
5164cf533ea5SEric Dumazet static void tcp_urg(struct sock *sk, struct sk_buff *skb, const struct tcphdr *th)
51651da177e4SLinus Torvalds {
51661da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
51671da177e4SLinus Torvalds 
51681da177e4SLinus Torvalds 	/* Check if we get a new urgent pointer - normally not. */
51691da177e4SLinus Torvalds 	if (th->urg)
51701da177e4SLinus Torvalds 		tcp_check_urg(sk, th);
51711da177e4SLinus Torvalds 
51721da177e4SLinus Torvalds 	/* Do we wait for any urgent data? - normally not... */
51731da177e4SLinus Torvalds 	if (tp->urg_data == TCP_URG_NOTYET) {
51741da177e4SLinus Torvalds 		u32 ptr = tp->urg_seq - ntohl(th->seq) + (th->doff * 4) -
51751da177e4SLinus Torvalds 			  th->syn;
51761da177e4SLinus Torvalds 
51771da177e4SLinus Torvalds 		/* Is the urgent pointer pointing into this packet? */
51781da177e4SLinus Torvalds 		if (ptr < skb->len) {
51791da177e4SLinus Torvalds 			u8 tmp;
51801da177e4SLinus Torvalds 			if (skb_copy_bits(skb, ptr, &tmp, 1))
51811da177e4SLinus Torvalds 				BUG();
51821da177e4SLinus Torvalds 			tp->urg_data = TCP_URG_VALID | tmp;
51831da177e4SLinus Torvalds 			if (!sock_flag(sk, SOCK_DEAD))
5184676d2369SDavid S. Miller 				sk->sk_data_ready(sk);
51851da177e4SLinus Torvalds 		}
51861da177e4SLinus Torvalds 	}
51871da177e4SLinus Torvalds }
51881da177e4SLinus Torvalds 
51891da177e4SLinus Torvalds static int tcp_copy_to_iovec(struct sock *sk, struct sk_buff *skb, int hlen)
51901da177e4SLinus Torvalds {
51911da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
51921da177e4SLinus Torvalds 	int chunk = skb->len - hlen;
51931da177e4SLinus Torvalds 	int err;
51941da177e4SLinus Torvalds 
519560476372SHerbert Xu 	if (skb_csum_unnecessary(skb))
5196f4362a2cSAl Viro 		err = skb_copy_datagram_msg(skb, hlen, tp->ucopy.msg, chunk);
51971da177e4SLinus Torvalds 	else
5198f4362a2cSAl Viro 		err = skb_copy_and_csum_datagram_msg(skb, hlen, tp->ucopy.msg);
51991da177e4SLinus Torvalds 
52001da177e4SLinus Torvalds 	if (!err) {
52011da177e4SLinus Torvalds 		tp->ucopy.len -= chunk;
52021da177e4SLinus Torvalds 		tp->copied_seq += chunk;
52031da177e4SLinus Torvalds 		tcp_rcv_space_adjust(sk);
52041da177e4SLinus Torvalds 	}
52051da177e4SLinus Torvalds 
52061da177e4SLinus Torvalds 	return err;
52071da177e4SLinus Torvalds }
52081da177e4SLinus Torvalds 
52090e40f4c9SJason Baron /* Accept RST for rcv_nxt - 1 after a FIN.
52100e40f4c9SJason Baron  * When tcp connections are abruptly terminated from Mac OSX (via ^C), a
52110e40f4c9SJason Baron  * FIN is sent followed by a RST packet. The RST is sent with the same
52120e40f4c9SJason Baron  * sequence number as the FIN, and thus according to RFC 5961 a challenge
52130e40f4c9SJason Baron  * ACK should be sent. However, Mac OSX rate limits replies to challenge
52140e40f4c9SJason Baron  * ACKs on the closed socket. In addition middleboxes can drop either the
52150e40f4c9SJason Baron  * challenge ACK or a subsequent RST.
52160e40f4c9SJason Baron  */
52170e40f4c9SJason Baron static bool tcp_reset_check(const struct sock *sk, const struct sk_buff *skb)
52180e40f4c9SJason Baron {
52190e40f4c9SJason Baron 	struct tcp_sock *tp = tcp_sk(sk);
52200e40f4c9SJason Baron 
52210e40f4c9SJason Baron 	return unlikely(TCP_SKB_CB(skb)->seq == (tp->rcv_nxt - 1) &&
52220e40f4c9SJason Baron 			(1 << sk->sk_state) & (TCPF_CLOSE_WAIT | TCPF_LAST_ACK |
52230e40f4c9SJason Baron 					       TCPF_CLOSING));
52240e40f4c9SJason Baron }
52250e40f4c9SJason Baron 
5226cbe2d128SIlpo Järvinen /* Does PAWS and seqno based validation of an incoming segment, flags will
5227cbe2d128SIlpo Järvinen  * play significant role here.
5228cbe2d128SIlpo Järvinen  */
52290c24604bSEric Dumazet static bool tcp_validate_incoming(struct sock *sk, struct sk_buff *skb,
5230cf533ea5SEric Dumazet 				  const struct tcphdr *th, int syn_inerr)
5231cbe2d128SIlpo Järvinen {
5232cbe2d128SIlpo Järvinen 	struct tcp_sock *tp = tcp_sk(sk);
5233e00431bcSPau Espin Pedrol 	bool rst_seq_match = false;
5234cbe2d128SIlpo Järvinen 
5235cbe2d128SIlpo Järvinen 	/* RFC1323: H1. Apply PAWS check first. */
52361a2c6181SChristoph Paasch 	if (tcp_fast_parse_options(skb, th, tp) && tp->rx_opt.saw_tstamp &&
5237cbe2d128SIlpo Järvinen 	    tcp_paws_discard(sk, skb)) {
5238cbe2d128SIlpo Järvinen 		if (!th->rst) {
5239c10d9310SEric Dumazet 			NET_INC_STATS(sock_net(sk), LINUX_MIB_PAWSESTABREJECTED);
5240f2b2c582SNeal Cardwell 			if (!tcp_oow_rate_limited(sock_net(sk), skb,
5241f2b2c582SNeal Cardwell 						  LINUX_MIB_TCPACKSKIPPEDPAWS,
5242f2b2c582SNeal Cardwell 						  &tp->last_oow_ack_time))
5243cbe2d128SIlpo Järvinen 				tcp_send_dupack(sk, skb);
5244cbe2d128SIlpo Järvinen 			goto discard;
5245cbe2d128SIlpo Järvinen 		}
5246cbe2d128SIlpo Järvinen 		/* Reset is accepted even if it did not pass PAWS. */
5247cbe2d128SIlpo Järvinen 	}
5248cbe2d128SIlpo Järvinen 
5249cbe2d128SIlpo Järvinen 	/* Step 1: check sequence number */
5250cbe2d128SIlpo Järvinen 	if (!tcp_sequence(tp, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq)) {
5251cbe2d128SIlpo Järvinen 		/* RFC793, page 37: "In all states except SYN-SENT, all reset
5252cbe2d128SIlpo Järvinen 		 * (RST) segments are validated by checking their SEQ-fields."
5253cbe2d128SIlpo Järvinen 		 * And page 69: "If an incoming segment is not acceptable,
5254cbe2d128SIlpo Järvinen 		 * an acknowledgment should be sent in reply (unless the RST
5255cbe2d128SIlpo Järvinen 		 * bit is set, if so drop the segment and return)".
5256cbe2d128SIlpo Järvinen 		 */
5257e3715899SEric Dumazet 		if (!th->rst) {
5258e3715899SEric Dumazet 			if (th->syn)
5259e3715899SEric Dumazet 				goto syn_challenge;
5260f2b2c582SNeal Cardwell 			if (!tcp_oow_rate_limited(sock_net(sk), skb,
5261f2b2c582SNeal Cardwell 						  LINUX_MIB_TCPACKSKIPPEDSEQ,
5262f2b2c582SNeal Cardwell 						  &tp->last_oow_ack_time))
5263cbe2d128SIlpo Järvinen 				tcp_send_dupack(sk, skb);
52640e40f4c9SJason Baron 		} else if (tcp_reset_check(sk, skb)) {
52650e40f4c9SJason Baron 			tcp_reset(sk);
5266e3715899SEric Dumazet 		}
5267cbe2d128SIlpo Järvinen 		goto discard;
5268cbe2d128SIlpo Järvinen 	}
5269cbe2d128SIlpo Järvinen 
5270cbe2d128SIlpo Järvinen 	/* Step 2: check RST bit */
5271cbe2d128SIlpo Järvinen 	if (th->rst) {
52720e40f4c9SJason Baron 		/* RFC 5961 3.2 (extend to match against (RCV.NXT - 1) after a
52730e40f4c9SJason Baron 		 * FIN and SACK too if available):
52740e40f4c9SJason Baron 		 * If seq num matches RCV.NXT or (RCV.NXT - 1) after a FIN, or
52750e40f4c9SJason Baron 		 * the right-most SACK block,
5276e00431bcSPau Espin Pedrol 		 * then
5277282f23c6SEric Dumazet 		 *     RESET the connection
5278282f23c6SEric Dumazet 		 * else
5279282f23c6SEric Dumazet 		 *     Send a challenge ACK
5280282f23c6SEric Dumazet 		 */
52810e40f4c9SJason Baron 		if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt ||
52820e40f4c9SJason Baron 		    tcp_reset_check(sk, skb)) {
5283e00431bcSPau Espin Pedrol 			rst_seq_match = true;
5284e00431bcSPau Espin Pedrol 		} else if (tcp_is_sack(tp) && tp->rx_opt.num_sacks > 0) {
5285e00431bcSPau Espin Pedrol 			struct tcp_sack_block *sp = &tp->selective_acks[0];
5286e00431bcSPau Espin Pedrol 			int max_sack = sp[0].end_seq;
5287e00431bcSPau Espin Pedrol 			int this_sack;
5288e00431bcSPau Espin Pedrol 
5289e00431bcSPau Espin Pedrol 			for (this_sack = 1; this_sack < tp->rx_opt.num_sacks;
5290e00431bcSPau Espin Pedrol 			     ++this_sack) {
5291e00431bcSPau Espin Pedrol 				max_sack = after(sp[this_sack].end_seq,
5292e00431bcSPau Espin Pedrol 						 max_sack) ?
5293e00431bcSPau Espin Pedrol 					sp[this_sack].end_seq : max_sack;
5294e00431bcSPau Espin Pedrol 			}
5295e00431bcSPau Espin Pedrol 
5296e00431bcSPau Espin Pedrol 			if (TCP_SKB_CB(skb)->seq == max_sack)
5297e00431bcSPau Espin Pedrol 				rst_seq_match = true;
5298e00431bcSPau Espin Pedrol 		}
5299e00431bcSPau Espin Pedrol 
5300e00431bcSPau Espin Pedrol 		if (rst_seq_match)
5301cbe2d128SIlpo Järvinen 			tcp_reset(sk);
5302cf1ef3f0SWei Wang 		else {
5303cf1ef3f0SWei Wang 			/* Disable TFO if RST is out-of-order
5304cf1ef3f0SWei Wang 			 * and no data has been received
5305cf1ef3f0SWei Wang 			 * for current active TFO socket
5306cf1ef3f0SWei Wang 			 */
5307cf1ef3f0SWei Wang 			if (tp->syn_fastopen && !tp->data_segs_in &&
5308cf1ef3f0SWei Wang 			    sk->sk_state == TCP_ESTABLISHED)
530946c2fa39SWei Wang 				tcp_fastopen_active_disable(sk);
5310f2b2c582SNeal Cardwell 			tcp_send_challenge_ack(sk, skb);
5311cf1ef3f0SWei Wang 		}
5312cbe2d128SIlpo Järvinen 		goto discard;
5313cbe2d128SIlpo Järvinen 	}
5314cbe2d128SIlpo Järvinen 
5315cbe2d128SIlpo Järvinen 	/* step 3: check security and precedence [ignored] */
5316cbe2d128SIlpo Järvinen 
53170c24604bSEric Dumazet 	/* step 4: Check for a SYN
5318cd214535SSowmini Varadhan 	 * RFC 5961 4.2 : Send a challenge ack
53190c24604bSEric Dumazet 	 */
53200c24604bSEric Dumazet 	if (th->syn) {
5321e3715899SEric Dumazet syn_challenge:
5322cbe2d128SIlpo Järvinen 		if (syn_inerr)
5323c10d9310SEric Dumazet 			TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS);
5324c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPSYNCHALLENGE);
5325f2b2c582SNeal Cardwell 		tcp_send_challenge_ack(sk, skb);
53260c24604bSEric Dumazet 		goto discard;
5327cbe2d128SIlpo Järvinen 	}
5328cbe2d128SIlpo Järvinen 
53290c24604bSEric Dumazet 	return true;
5330cbe2d128SIlpo Järvinen 
5331cbe2d128SIlpo Järvinen discard:
5332532182cdSEric Dumazet 	tcp_drop(sk, skb);
53330c24604bSEric Dumazet 	return false;
5334cbe2d128SIlpo Järvinen }
5335cbe2d128SIlpo Järvinen 
53361da177e4SLinus Torvalds /*
53371da177e4SLinus Torvalds  *	TCP receive function for the ESTABLISHED state.
53381da177e4SLinus Torvalds  *
53391da177e4SLinus Torvalds  *	It is split into a fast path and a slow path. The fast path is
53401da177e4SLinus Torvalds  * 	disabled when:
53411da177e4SLinus Torvalds  *	- A zero window was announced from us - zero window probing
53421da177e4SLinus Torvalds  *        is only handled properly in the slow path.
53431da177e4SLinus Torvalds  *	- Out of order segments arrived.
53441da177e4SLinus Torvalds  *	- Urgent data is expected.
53451da177e4SLinus Torvalds  *	- There is no buffer space left
53461da177e4SLinus Torvalds  *	- Unexpected TCP flags/window values/header lengths are received
53471da177e4SLinus Torvalds  *	  (detected by checking the TCP header against pred_flags)
53481da177e4SLinus Torvalds  *	- Data is sent in both directions. Fast path only supports pure senders
53491da177e4SLinus Torvalds  *	  or pure receivers (this means either the sequence number or the ack
53501da177e4SLinus Torvalds  *	  value must stay constant)
53511da177e4SLinus Torvalds  *	- Unexpected TCP option.
53521da177e4SLinus Torvalds  *
53531da177e4SLinus Torvalds  *	When these conditions are not satisfied it drops into a standard
53541da177e4SLinus Torvalds  *	receive procedure patterned after RFC793 to handle all cases.
53551da177e4SLinus Torvalds  *	The first three cases are guaranteed by proper pred_flags setting,
53561da177e4SLinus Torvalds  *	the rest is checked inline. Fast processing is turned on in
53571da177e4SLinus Torvalds  *	tcp_data_queue when everything is OK.
53581da177e4SLinus Torvalds  */
5359c995ae22SVijay Subramanian void tcp_rcv_established(struct sock *sk, struct sk_buff *skb,
5360cf533ea5SEric Dumazet 			 const struct tcphdr *th, unsigned int len)
53611da177e4SLinus Torvalds {
53621da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
53631da177e4SLinus Torvalds 
53649a568de4SEric Dumazet 	tcp_mstamp_refresh(tp);
536551456b29SIan Morris 	if (unlikely(!sk->sk_rx_dst))
53665d299f3dSEric Dumazet 		inet_csk(sk)->icsk_af_ops->sk_rx_dst_set(sk, skb);
53671da177e4SLinus Torvalds 	/*
53681da177e4SLinus Torvalds 	 *	Header prediction.
53691da177e4SLinus Torvalds 	 *	The code loosely follows the one in the famous
53701da177e4SLinus Torvalds 	 *	"30 instruction TCP receive" Van Jacobson mail.
53711da177e4SLinus Torvalds 	 *
53721da177e4SLinus Torvalds 	 *	Van's trick is to deposit buffers into socket queue
53731da177e4SLinus Torvalds 	 *	on a device interrupt, to call tcp_recv function
53741da177e4SLinus Torvalds 	 *	on the receive process context and checksum and copy
53751da177e4SLinus Torvalds 	 *	the buffer to user space. smart...
53761da177e4SLinus Torvalds 	 *
53771da177e4SLinus Torvalds 	 *	Our current scheme is not silly either but we take the
53781da177e4SLinus Torvalds 	 *	extra cost of the net_bh soft interrupt processing...
53791da177e4SLinus Torvalds 	 *	We do checksum and copy also but from device to kernel.
53801da177e4SLinus Torvalds 	 */
53811da177e4SLinus Torvalds 
53821da177e4SLinus Torvalds 	tp->rx_opt.saw_tstamp = 0;
53831da177e4SLinus Torvalds 
53841da177e4SLinus Torvalds 	/*	pred_flags is 0xS?10 << 16 + snd_wnd
5385caa20d9aSStephen Hemminger 	 *	if header_prediction is to be made
53861da177e4SLinus Torvalds 	 *	'S' will always be tp->tcp_header_len >> 2
53871da177e4SLinus Torvalds 	 *	'?' will be 0 for the fast path, otherwise pred_flags is 0 to
53881da177e4SLinus Torvalds 	 *  turn it off	(when there are holes in the receive
53891da177e4SLinus Torvalds 	 *	 space for instance)
53901da177e4SLinus Torvalds 	 *	PSH flag is ignored.
53911da177e4SLinus Torvalds 	 */
53921da177e4SLinus Torvalds 
53931da177e4SLinus Torvalds 	if ((tcp_flag_word(th) & TCP_HP_BITS) == tp->pred_flags &&
539496e0bf4bSJohn Dykstra 	    TCP_SKB_CB(skb)->seq == tp->rcv_nxt &&
539596e0bf4bSJohn Dykstra 	    !after(TCP_SKB_CB(skb)->ack_seq, tp->snd_nxt)) {
53961da177e4SLinus Torvalds 		int tcp_header_len = tp->tcp_header_len;
53971da177e4SLinus Torvalds 
53981da177e4SLinus Torvalds 		/* Timestamp header prediction: tcp_header_len
53991da177e4SLinus Torvalds 		 * is automatically equal to th->doff*4 due to pred_flags
54001da177e4SLinus Torvalds 		 * match.
54011da177e4SLinus Torvalds 		 */
54021da177e4SLinus Torvalds 
54031da177e4SLinus Torvalds 		/* Check timestamp */
54041da177e4SLinus Torvalds 		if (tcp_header_len == sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) {
54051da177e4SLinus Torvalds 			/* No? Slow path! */
5406a4356b29SIlpo Järvinen 			if (!tcp_parse_aligned_timestamp(tp, th))
54071da177e4SLinus Torvalds 				goto slow_path;
54081da177e4SLinus Torvalds 
54091da177e4SLinus Torvalds 			/* If PAWS failed, check it more carefully in slow path */
54101da177e4SLinus Torvalds 			if ((s32)(tp->rx_opt.rcv_tsval - tp->rx_opt.ts_recent) < 0)
54111da177e4SLinus Torvalds 				goto slow_path;
54121da177e4SLinus Torvalds 
54131da177e4SLinus Torvalds 			/* DO NOT update ts_recent here, if checksum fails
54141da177e4SLinus Torvalds 			 * and timestamp was corrupted part, it will result
54151da177e4SLinus Torvalds 			 * in a hung connection since we will drop all
54161da177e4SLinus Torvalds 			 * future packets due to the PAWS test.
54171da177e4SLinus Torvalds 			 */
54181da177e4SLinus Torvalds 		}
54191da177e4SLinus Torvalds 
54201da177e4SLinus Torvalds 		if (len <= tcp_header_len) {
54211da177e4SLinus Torvalds 			/* Bulk data transfer: sender */
54221da177e4SLinus Torvalds 			if (len == tcp_header_len) {
54231da177e4SLinus Torvalds 				/* Predicted packet is in window by definition.
54241da177e4SLinus Torvalds 				 * seq == rcv_nxt and rcv_wup <= rcv_nxt.
54251da177e4SLinus Torvalds 				 * Hence, check seq<=rcv_wup reduces to:
54261da177e4SLinus Torvalds 				 */
54271da177e4SLinus Torvalds 				if (tcp_header_len ==
54281da177e4SLinus Torvalds 				    (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) &&
54291da177e4SLinus Torvalds 				    tp->rcv_nxt == tp->rcv_wup)
54301da177e4SLinus Torvalds 					tcp_store_ts_recent(tp);
54311da177e4SLinus Torvalds 
54321da177e4SLinus Torvalds 				/* We know that such packets are checksummed
54331da177e4SLinus Torvalds 				 * on entry.
54341da177e4SLinus Torvalds 				 */
54351da177e4SLinus Torvalds 				tcp_ack(sk, skb, 0);
54361da177e4SLinus Torvalds 				__kfree_skb(skb);
54379e412ba7SIlpo Järvinen 				tcp_data_snd_check(sk);
5438c995ae22SVijay Subramanian 				return;
54391da177e4SLinus Torvalds 			} else { /* Header too small */
5440c10d9310SEric Dumazet 				TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS);
54411da177e4SLinus Torvalds 				goto discard;
54421da177e4SLinus Torvalds 			}
54431da177e4SLinus Torvalds 		} else {
54441da177e4SLinus Torvalds 			int eaten = 0;
5445b081f85cSEric Dumazet 			bool fragstolen = false;
54461da177e4SLinus Torvalds 
544759ea33a6SJiri Kosina 			if (tp->ucopy.task == current &&
5448d27f9bc1SDan Williams 			    tp->copied_seq == tp->rcv_nxt &&
5449d27f9bc1SDan Williams 			    len - tcp_header_len <= tp->ucopy.len &&
5450d27f9bc1SDan Williams 			    sock_owned_by_user(sk)) {
54511da177e4SLinus Torvalds 				__set_current_state(TASK_RUNNING);
54521da177e4SLinus Torvalds 
5453d27f9bc1SDan Williams 				if (!tcp_copy_to_iovec(sk, skb, tcp_header_len)) {
54541da177e4SLinus Torvalds 					/* Predicted packet is in window by definition.
54551da177e4SLinus Torvalds 					 * seq == rcv_nxt and rcv_wup <= rcv_nxt.
54561da177e4SLinus Torvalds 					 * Hence, check seq<=rcv_wup reduces to:
54571da177e4SLinus Torvalds 					 */
54581da177e4SLinus Torvalds 					if (tcp_header_len ==
54591da177e4SLinus Torvalds 					    (sizeof(struct tcphdr) +
54601da177e4SLinus Torvalds 					     TCPOLEN_TSTAMP_ALIGNED) &&
54611da177e4SLinus Torvalds 					    tp->rcv_nxt == tp->rcv_wup)
54621da177e4SLinus Torvalds 						tcp_store_ts_recent(tp);
54631da177e4SLinus Torvalds 
5464463c84b9SArnaldo Carvalho de Melo 					tcp_rcv_rtt_measure_ts(sk, skb);
54651da177e4SLinus Torvalds 
54661da177e4SLinus Torvalds 					__skb_pull(skb, tcp_header_len);
5467bdd1f9edSEric Dumazet 					tcp_rcv_nxt_update(tp, TCP_SKB_CB(skb)->end_seq);
5468c10d9310SEric Dumazet 					NET_INC_STATS(sock_net(sk),
546902a1d6e7SEric Dumazet 							LINUX_MIB_TCPHPHITSTOUSER);
5470d27f9bc1SDan Williams 					eaten = 1;
54711da177e4SLinus Torvalds 				}
54721da177e4SLinus Torvalds 			}
54731da177e4SLinus Torvalds 			if (!eaten) {
5474fb3477c0SEric Dumazet 				if (tcp_checksum_complete(skb))
54751da177e4SLinus Torvalds 					goto csum_error;
54761da177e4SLinus Torvalds 
5477aab2b4bfSNeal Cardwell 				if ((int)skb->truesize > sk->sk_forward_alloc)
5478aab2b4bfSNeal Cardwell 					goto step5;
5479aab2b4bfSNeal Cardwell 
54801da177e4SLinus Torvalds 				/* Predicted packet is in window by definition.
54811da177e4SLinus Torvalds 				 * seq == rcv_nxt and rcv_wup <= rcv_nxt.
54821da177e4SLinus Torvalds 				 * Hence, check seq<=rcv_wup reduces to:
54831da177e4SLinus Torvalds 				 */
54841da177e4SLinus Torvalds 				if (tcp_header_len ==
54851da177e4SLinus Torvalds 				    (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) &&
54861da177e4SLinus Torvalds 				    tp->rcv_nxt == tp->rcv_wup)
54871da177e4SLinus Torvalds 					tcp_store_ts_recent(tp);
54881da177e4SLinus Torvalds 
5489463c84b9SArnaldo Carvalho de Melo 				tcp_rcv_rtt_measure_ts(sk, skb);
54901da177e4SLinus Torvalds 
5491c10d9310SEric Dumazet 				NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPHPHITS);
54921da177e4SLinus Torvalds 
54931da177e4SLinus Torvalds 				/* Bulk data transfer: receiver */
5494b081f85cSEric Dumazet 				eaten = tcp_queue_rcv(sk, skb, tcp_header_len,
5495b081f85cSEric Dumazet 						      &fragstolen);
54961da177e4SLinus Torvalds 			}
54971da177e4SLinus Torvalds 
54989e412ba7SIlpo Järvinen 			tcp_event_data_recv(sk, skb);
54991da177e4SLinus Torvalds 
55001da177e4SLinus Torvalds 			if (TCP_SKB_CB(skb)->ack_seq != tp->snd_una) {
55011da177e4SLinus Torvalds 				/* Well, only one small jumplet in fast path... */
55021da177e4SLinus Torvalds 				tcp_ack(sk, skb, FLAG_DATA);
55039e412ba7SIlpo Järvinen 				tcp_data_snd_check(sk);
5504463c84b9SArnaldo Carvalho de Melo 				if (!inet_csk_ack_scheduled(sk))
55051da177e4SLinus Torvalds 					goto no_ack;
55061da177e4SLinus Torvalds 			}
55071da177e4SLinus Torvalds 
55081da177e4SLinus Torvalds 			__tcp_ack_snd_check(sk, 0);
55091da177e4SLinus Torvalds no_ack:
55101da177e4SLinus Torvalds 			if (eaten)
5511b081f85cSEric Dumazet 				kfree_skb_partial(skb, fragstolen);
5512676d2369SDavid S. Miller 			sk->sk_data_ready(sk);
5513c995ae22SVijay Subramanian 			return;
55141da177e4SLinus Torvalds 		}
55151da177e4SLinus Torvalds 	}
55161da177e4SLinus Torvalds 
55171da177e4SLinus Torvalds slow_path:
5518fb3477c0SEric Dumazet 	if (len < (th->doff << 2) || tcp_checksum_complete(skb))
55191da177e4SLinus Torvalds 		goto csum_error;
55201da177e4SLinus Torvalds 
55210c228e83SCalvin Owens 	if (!th->ack && !th->rst && !th->syn)
5522c3ae62afSEric Dumazet 		goto discard;
5523c3ae62afSEric Dumazet 
55241da177e4SLinus Torvalds 	/*
55251da177e4SLinus Torvalds 	 *	Standard slow path.
55261da177e4SLinus Torvalds 	 */
55271da177e4SLinus Torvalds 
55280c24604bSEric Dumazet 	if (!tcp_validate_incoming(sk, skb, th, 1))
5529c995ae22SVijay Subramanian 		return;
55301da177e4SLinus Torvalds 
55311da177e4SLinus Torvalds step5:
553212fb3dd9SEric Dumazet 	if (tcp_ack(sk, skb, FLAG_SLOWPATH | FLAG_UPDATE_TS_RECENT) < 0)
553396e0bf4bSJohn Dykstra 		goto discard;
55341da177e4SLinus Torvalds 
5535463c84b9SArnaldo Carvalho de Melo 	tcp_rcv_rtt_measure_ts(sk, skb);
55361da177e4SLinus Torvalds 
55371da177e4SLinus Torvalds 	/* Process urgent data. */
55381da177e4SLinus Torvalds 	tcp_urg(sk, skb, th);
55391da177e4SLinus Torvalds 
55401da177e4SLinus Torvalds 	/* step 7: process the segment text */
55411da177e4SLinus Torvalds 	tcp_data_queue(sk, skb);
55421da177e4SLinus Torvalds 
55439e412ba7SIlpo Järvinen 	tcp_data_snd_check(sk);
55441da177e4SLinus Torvalds 	tcp_ack_snd_check(sk);
5545c995ae22SVijay Subramanian 	return;
55461da177e4SLinus Torvalds 
55471da177e4SLinus Torvalds csum_error:
5548c10d9310SEric Dumazet 	TCP_INC_STATS(sock_net(sk), TCP_MIB_CSUMERRORS);
5549c10d9310SEric Dumazet 	TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS);
55501da177e4SLinus Torvalds 
55511da177e4SLinus Torvalds discard:
5552532182cdSEric Dumazet 	tcp_drop(sk, skb);
55531da177e4SLinus Torvalds }
55544bc2f18bSEric Dumazet EXPORT_SYMBOL(tcp_rcv_established);
55551da177e4SLinus Torvalds 
5556370816aeSPavel Emelyanov void tcp_finish_connect(struct sock *sk, struct sk_buff *skb)
5557370816aeSPavel Emelyanov {
5558370816aeSPavel Emelyanov 	struct tcp_sock *tp = tcp_sk(sk);
5559370816aeSPavel Emelyanov 	struct inet_connection_sock *icsk = inet_csk(sk);
5560370816aeSPavel Emelyanov 
5561370816aeSPavel Emelyanov 	tcp_set_state(sk, TCP_ESTABLISHED);
556270eabf0eSEric Dumazet 	icsk->icsk_ack.lrcvtime = tcp_jiffies32;
5563370816aeSPavel Emelyanov 
556400db4124SIan Morris 	if (skb) {
55655d299f3dSEric Dumazet 		icsk->icsk_af_ops->sk_rx_dst_set(sk, skb);
5566370816aeSPavel Emelyanov 		security_inet_conn_established(sk, skb);
556741063e9dSDavid S. Miller 	}
5568370816aeSPavel Emelyanov 
5569370816aeSPavel Emelyanov 	/* Make sure socket is routed, for correct metrics.  */
5570370816aeSPavel Emelyanov 	icsk->icsk_af_ops->rebuild_header(sk);
5571370816aeSPavel Emelyanov 
5572370816aeSPavel Emelyanov 	tcp_init_metrics(sk);
5573370816aeSPavel Emelyanov 
5574370816aeSPavel Emelyanov 	tcp_init_congestion_control(sk);
5575370816aeSPavel Emelyanov 
5576370816aeSPavel Emelyanov 	/* Prevent spurious tcp_cwnd_restart() on first data
5577370816aeSPavel Emelyanov 	 * packet.
5578370816aeSPavel Emelyanov 	 */
5579d635fbe2SEric Dumazet 	tp->lsndtime = tcp_jiffies32;
5580370816aeSPavel Emelyanov 
5581370816aeSPavel Emelyanov 	tcp_init_buffer_space(sk);
5582370816aeSPavel Emelyanov 
5583370816aeSPavel Emelyanov 	if (sock_flag(sk, SOCK_KEEPOPEN))
5584370816aeSPavel Emelyanov 		inet_csk_reset_keepalive_timer(sk, keepalive_time_when(tp));
5585370816aeSPavel Emelyanov 
5586370816aeSPavel Emelyanov 	if (!tp->rx_opt.snd_wscale)
5587370816aeSPavel Emelyanov 		__tcp_fast_path_on(tp, tp->snd_wnd);
5588370816aeSPavel Emelyanov 	else
5589370816aeSPavel Emelyanov 		tp->pred_flags = 0;
5590370816aeSPavel Emelyanov 
5591370816aeSPavel Emelyanov }
5592370816aeSPavel Emelyanov 
55938e4178c1SYuchung Cheng static bool tcp_rcv_fastopen_synack(struct sock *sk, struct sk_buff *synack,
55948e4178c1SYuchung Cheng 				    struct tcp_fastopen_cookie *cookie)
55958e4178c1SYuchung Cheng {
55968e4178c1SYuchung Cheng 	struct tcp_sock *tp = tcp_sk(sk);
559767da22d2SYuchung Cheng 	struct sk_buff *data = tp->syn_data ? tcp_write_queue_head(sk) : NULL;
55982646c831SDaniel Lee 	u16 mss = tp->rx_opt.mss_clamp, try_exp = 0;
55992646c831SDaniel Lee 	bool syn_drop = false;
56008e4178c1SYuchung Cheng 
56018e4178c1SYuchung Cheng 	if (mss == tp->rx_opt.user_mss) {
56028e4178c1SYuchung Cheng 		struct tcp_options_received opt;
56038e4178c1SYuchung Cheng 
56048e4178c1SYuchung Cheng 		/* Get original SYNACK MSS value if user MSS sets mss_clamp */
56058e4178c1SYuchung Cheng 		tcp_clear_options(&opt);
56068e4178c1SYuchung Cheng 		opt.user_mss = opt.mss_clamp = 0;
56071a2c6181SChristoph Paasch 		tcp_parse_options(synack, &opt, 0, NULL);
56088e4178c1SYuchung Cheng 		mss = opt.mss_clamp;
56098e4178c1SYuchung Cheng 	}
56108e4178c1SYuchung Cheng 
56112646c831SDaniel Lee 	if (!tp->syn_fastopen) {
56122646c831SDaniel Lee 		/* Ignore an unsolicited cookie */
561367da22d2SYuchung Cheng 		cookie->len = -1;
56142646c831SDaniel Lee 	} else if (tp->total_retrans) {
56152646c831SDaniel Lee 		/* SYN timed out and the SYN-ACK neither has a cookie nor
56162646c831SDaniel Lee 		 * acknowledges data. Presumably the remote received only
56172646c831SDaniel Lee 		 * the retransmitted (regular) SYNs: either the original
56182646c831SDaniel Lee 		 * SYN-data or the corresponding SYN-ACK was dropped.
5619aab48743SYuchung Cheng 		 */
56202646c831SDaniel Lee 		syn_drop = (cookie->len < 0 && data);
56212646c831SDaniel Lee 	} else if (cookie->len < 0 && !tp->syn_data) {
56222646c831SDaniel Lee 		/* We requested a cookie but didn't get it. If we did not use
56232646c831SDaniel Lee 		 * the (old) exp opt format then try so next time (try_exp=1).
56242646c831SDaniel Lee 		 * Otherwise we go back to use the RFC7413 opt (try_exp=2).
56252646c831SDaniel Lee 		 */
56262646c831SDaniel Lee 		try_exp = tp->syn_fastopen_exp ? 2 : 1;
56272646c831SDaniel Lee 	}
5628aab48743SYuchung Cheng 
56292646c831SDaniel Lee 	tcp_fastopen_cache_set(sk, mss, cookie, syn_drop, try_exp);
56308e4178c1SYuchung Cheng 
56318e4178c1SYuchung Cheng 	if (data) { /* Retransmit unacked data in SYN */
563293b174adSYuchung Cheng 		tcp_for_write_queue_from(data, sk) {
563393b174adSYuchung Cheng 			if (data == tcp_send_head(sk) ||
563410d3be56SEric Dumazet 			    __tcp_retransmit_skb(sk, data, 1))
563593b174adSYuchung Cheng 				break;
563693b174adSYuchung Cheng 		}
56378e4178c1SYuchung Cheng 		tcp_rearm_rto(sk);
5638c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk),
563902a1d6e7SEric Dumazet 				LINUX_MIB_TCPFASTOPENACTIVEFAIL);
56408e4178c1SYuchung Cheng 		return true;
56418e4178c1SYuchung Cheng 	}
56426f73601eSYuchung Cheng 	tp->syn_data_acked = tp->syn_data;
5643f19c29e3SYuchung Cheng 	if (tp->syn_data_acked)
5644c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk),
564502a1d6e7SEric Dumazet 				LINUX_MIB_TCPFASTOPENACTIVE);
564661d2bcaeSEric Dumazet 
564761d2bcaeSEric Dumazet 	tcp_fastopen_add_skb(sk, synack);
564861d2bcaeSEric Dumazet 
56498e4178c1SYuchung Cheng 	return false;
56508e4178c1SYuchung Cheng }
56518e4178c1SYuchung Cheng 
56521da177e4SLinus Torvalds static int tcp_rcv_synsent_state_process(struct sock *sk, struct sk_buff *skb,
5653bda07a64SEric Dumazet 					 const struct tcphdr *th)
56541da177e4SLinus Torvalds {
5655d83d8461SArnaldo Carvalho de Melo 	struct inet_connection_sock *icsk = inet_csk(sk);
56564957faadSWilliam Allen Simpson 	struct tcp_sock *tp = tcp_sk(sk);
56578e4178c1SYuchung Cheng 	struct tcp_fastopen_cookie foc = { .len = -1 };
56584957faadSWilliam Allen Simpson 	int saved_clamp = tp->rx_opt.mss_clamp;
56590f9fa831SEric Dumazet 	bool fastopen_fail;
56601da177e4SLinus Torvalds 
56611a2c6181SChristoph Paasch 	tcp_parse_options(skb, &tp->rx_opt, 0, &foc);
5662e3e12028SAndrew Vagin 	if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr)
5663ee684b6fSAndrey Vagin 		tp->rx_opt.rcv_tsecr -= tp->tsoffset;
56641da177e4SLinus Torvalds 
56651da177e4SLinus Torvalds 	if (th->ack) {
56661da177e4SLinus Torvalds 		/* rfc793:
56671da177e4SLinus Torvalds 		 * "If the state is SYN-SENT then
56681da177e4SLinus Torvalds 		 *    first check the ACK bit
56691da177e4SLinus Torvalds 		 *      If the ACK bit is set
56701da177e4SLinus Torvalds 		 *	  If SEG.ACK =< ISS, or SEG.ACK > SND.NXT, send
56711da177e4SLinus Torvalds 		 *        a reset (unless the RST bit is set, if so drop
56721da177e4SLinus Torvalds 		 *        the segment and return)"
56731da177e4SLinus Torvalds 		 */
56748e4178c1SYuchung Cheng 		if (!after(TCP_SKB_CB(skb)->ack_seq, tp->snd_una) ||
56758e4178c1SYuchung Cheng 		    after(TCP_SKB_CB(skb)->ack_seq, tp->snd_nxt))
56761da177e4SLinus Torvalds 			goto reset_and_undo;
56771da177e4SLinus Torvalds 
56781da177e4SLinus Torvalds 		if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr &&
56791da177e4SLinus Torvalds 		    !between(tp->rx_opt.rcv_tsecr, tp->retrans_stamp,
56809a568de4SEric Dumazet 			     tcp_time_stamp(tp))) {
5681c10d9310SEric Dumazet 			NET_INC_STATS(sock_net(sk),
568202a1d6e7SEric Dumazet 					LINUX_MIB_PAWSACTIVEREJECTED);
56831da177e4SLinus Torvalds 			goto reset_and_undo;
56841da177e4SLinus Torvalds 		}
56851da177e4SLinus Torvalds 
56861da177e4SLinus Torvalds 		/* Now ACK is acceptable.
56871da177e4SLinus Torvalds 		 *
56881da177e4SLinus Torvalds 		 * "If the RST bit is set
56891da177e4SLinus Torvalds 		 *    If the ACK was acceptable then signal the user "error:
56901da177e4SLinus Torvalds 		 *    connection reset", drop the segment, enter CLOSED state,
56911da177e4SLinus Torvalds 		 *    delete TCB, and return."
56921da177e4SLinus Torvalds 		 */
56931da177e4SLinus Torvalds 
56941da177e4SLinus Torvalds 		if (th->rst) {
56951da177e4SLinus Torvalds 			tcp_reset(sk);
56961da177e4SLinus Torvalds 			goto discard;
56971da177e4SLinus Torvalds 		}
56981da177e4SLinus Torvalds 
56991da177e4SLinus Torvalds 		/* rfc793:
57001da177e4SLinus Torvalds 		 *   "fifth, if neither of the SYN or RST bits is set then
57011da177e4SLinus Torvalds 		 *    drop the segment and return."
57021da177e4SLinus Torvalds 		 *
57031da177e4SLinus Torvalds 		 *    See note below!
57041da177e4SLinus Torvalds 		 *                                        --ANK(990513)
57051da177e4SLinus Torvalds 		 */
57061da177e4SLinus Torvalds 		if (!th->syn)
57071da177e4SLinus Torvalds 			goto discard_and_undo;
57081da177e4SLinus Torvalds 
57091da177e4SLinus Torvalds 		/* rfc793:
57101da177e4SLinus Torvalds 		 *   "If the SYN bit is on ...
57111da177e4SLinus Torvalds 		 *    are acceptable then ...
57121da177e4SLinus Torvalds 		 *    (our SYN has been ACKed), change the connection
57131da177e4SLinus Torvalds 		 *    state to ESTABLISHED..."
57141da177e4SLinus Torvalds 		 */
57151da177e4SLinus Torvalds 
5716735d3831SFlorian Westphal 		tcp_ecn_rcv_synack(tp, th);
57171da177e4SLinus Torvalds 
57181b3a6926SRazvan Ghitulete 		tcp_init_wl(tp, TCP_SKB_CB(skb)->seq);
57191da177e4SLinus Torvalds 		tcp_ack(sk, skb, FLAG_SLOWPATH);
57201da177e4SLinus Torvalds 
57211da177e4SLinus Torvalds 		/* Ok.. it's good. Set up sequence numbers and
57221da177e4SLinus Torvalds 		 * move to established.
57231da177e4SLinus Torvalds 		 */
57241da177e4SLinus Torvalds 		tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1;
57251da177e4SLinus Torvalds 		tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
57261da177e4SLinus Torvalds 
57271da177e4SLinus Torvalds 		/* RFC1323: The window in SYN & SYN/ACK segments is
57281da177e4SLinus Torvalds 		 * never scaled.
57291da177e4SLinus Torvalds 		 */
57301da177e4SLinus Torvalds 		tp->snd_wnd = ntohs(th->window);
57311da177e4SLinus Torvalds 
57321da177e4SLinus Torvalds 		if (!tp->rx_opt.wscale_ok) {
57331da177e4SLinus Torvalds 			tp->rx_opt.snd_wscale = tp->rx_opt.rcv_wscale = 0;
57341da177e4SLinus Torvalds 			tp->window_clamp = min(tp->window_clamp, 65535U);
57351da177e4SLinus Torvalds 		}
57361da177e4SLinus Torvalds 
57371da177e4SLinus Torvalds 		if (tp->rx_opt.saw_tstamp) {
57381da177e4SLinus Torvalds 			tp->rx_opt.tstamp_ok	   = 1;
57391da177e4SLinus Torvalds 			tp->tcp_header_len =
57401da177e4SLinus Torvalds 				sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
57411da177e4SLinus Torvalds 			tp->advmss	    -= TCPOLEN_TSTAMP_ALIGNED;
57421da177e4SLinus Torvalds 			tcp_store_ts_recent(tp);
57431da177e4SLinus Torvalds 		} else {
57441da177e4SLinus Torvalds 			tp->tcp_header_len = sizeof(struct tcphdr);
57451da177e4SLinus Torvalds 		}
57461da177e4SLinus Torvalds 
5747e60402d0SIlpo Järvinen 		if (tcp_is_sack(tp) && sysctl_tcp_fack)
5748e60402d0SIlpo Järvinen 			tcp_enable_fack(tp);
57491da177e4SLinus Torvalds 
57505d424d5aSJohn Heffner 		tcp_mtup_init(sk);
5751d83d8461SArnaldo Carvalho de Melo 		tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
57521da177e4SLinus Torvalds 		tcp_initialize_rcv_mss(sk);
57531da177e4SLinus Torvalds 
57541da177e4SLinus Torvalds 		/* Remember, tcp_poll() does not lock socket!
57551da177e4SLinus Torvalds 		 * Change state from SYN-SENT only after copied_seq
57561da177e4SLinus Torvalds 		 * is initialized. */
57571da177e4SLinus Torvalds 		tp->copied_seq = tp->rcv_nxt;
57584957faadSWilliam Allen Simpson 
5759e16aa207SRalf Baechle 		smp_mb();
57601da177e4SLinus Torvalds 
5761370816aeSPavel Emelyanov 		tcp_finish_connect(sk, skb);
57621da177e4SLinus Torvalds 
57630f9fa831SEric Dumazet 		fastopen_fail = (tp->syn_fastopen || tp->syn_data) &&
57640f9fa831SEric Dumazet 				tcp_rcv_fastopen_synack(sk, skb, &foc);
57658e4178c1SYuchung Cheng 
57660f9fa831SEric Dumazet 		if (!sock_flag(sk, SOCK_DEAD)) {
57670f9fa831SEric Dumazet 			sk->sk_state_change(sk);
57680f9fa831SEric Dumazet 			sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT);
57690f9fa831SEric Dumazet 		}
57700f9fa831SEric Dumazet 		if (fastopen_fail)
57710f9fa831SEric Dumazet 			return -1;
5772295f7324SArnaldo Carvalho de Melo 		if (sk->sk_write_pending ||
5773295f7324SArnaldo Carvalho de Melo 		    icsk->icsk_accept_queue.rskq_defer_accept ||
5774295f7324SArnaldo Carvalho de Melo 		    icsk->icsk_ack.pingpong) {
57751da177e4SLinus Torvalds 			/* Save one ACK. Data will be ready after
57761da177e4SLinus Torvalds 			 * several ticks, if write_pending is set.
57771da177e4SLinus Torvalds 			 *
57781da177e4SLinus Torvalds 			 * It may be deleted, but with this feature tcpdumps
57791da177e4SLinus Torvalds 			 * look so _wonderfully_ clever, that I was not able
57801da177e4SLinus Torvalds 			 * to stand against the temptation 8)     --ANK
57811da177e4SLinus Torvalds 			 */
5782463c84b9SArnaldo Carvalho de Melo 			inet_csk_schedule_ack(sk);
5783463c84b9SArnaldo Carvalho de Melo 			tcp_enter_quickack_mode(sk);
57843f421baaSArnaldo Carvalho de Melo 			inet_csk_reset_xmit_timer(sk, ICSK_TIME_DACK,
57853f421baaSArnaldo Carvalho de Melo 						  TCP_DELACK_MAX, TCP_RTO_MAX);
57861da177e4SLinus Torvalds 
57871da177e4SLinus Torvalds discard:
5788532182cdSEric Dumazet 			tcp_drop(sk, skb);
57891da177e4SLinus Torvalds 			return 0;
57901da177e4SLinus Torvalds 		} else {
57911da177e4SLinus Torvalds 			tcp_send_ack(sk);
57921da177e4SLinus Torvalds 		}
57931da177e4SLinus Torvalds 		return -1;
57941da177e4SLinus Torvalds 	}
57951da177e4SLinus Torvalds 
57961da177e4SLinus Torvalds 	/* No ACK in the segment */
57971da177e4SLinus Torvalds 
57981da177e4SLinus Torvalds 	if (th->rst) {
57991da177e4SLinus Torvalds 		/* rfc793:
58001da177e4SLinus Torvalds 		 * "If the RST bit is set
58011da177e4SLinus Torvalds 		 *
58021da177e4SLinus Torvalds 		 *      Otherwise (no ACK) drop the segment and return."
58031da177e4SLinus Torvalds 		 */
58041da177e4SLinus Torvalds 
58051da177e4SLinus Torvalds 		goto discard_and_undo;
58061da177e4SLinus Torvalds 	}
58071da177e4SLinus Torvalds 
58081da177e4SLinus Torvalds 	/* PAWS check. */
5809056834d9SIlpo Järvinen 	if (tp->rx_opt.ts_recent_stamp && tp->rx_opt.saw_tstamp &&
5810c887e6d2SIlpo Järvinen 	    tcp_paws_reject(&tp->rx_opt, 0))
58111da177e4SLinus Torvalds 		goto discard_and_undo;
58121da177e4SLinus Torvalds 
58131da177e4SLinus Torvalds 	if (th->syn) {
58141da177e4SLinus Torvalds 		/* We see SYN without ACK. It is attempt of
58151da177e4SLinus Torvalds 		 * simultaneous connect with crossed SYNs.
58161da177e4SLinus Torvalds 		 * Particularly, it can be connect to self.
58171da177e4SLinus Torvalds 		 */
58181da177e4SLinus Torvalds 		tcp_set_state(sk, TCP_SYN_RECV);
58191da177e4SLinus Torvalds 
58201da177e4SLinus Torvalds 		if (tp->rx_opt.saw_tstamp) {
58211da177e4SLinus Torvalds 			tp->rx_opt.tstamp_ok = 1;
58221da177e4SLinus Torvalds 			tcp_store_ts_recent(tp);
58231da177e4SLinus Torvalds 			tp->tcp_header_len =
58241da177e4SLinus Torvalds 				sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
58251da177e4SLinus Torvalds 		} else {
58261da177e4SLinus Torvalds 			tp->tcp_header_len = sizeof(struct tcphdr);
58271da177e4SLinus Torvalds 		}
58281da177e4SLinus Torvalds 
58291da177e4SLinus Torvalds 		tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1;
5830142a2e7eSEric Dumazet 		tp->copied_seq = tp->rcv_nxt;
58311da177e4SLinus Torvalds 		tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
58321da177e4SLinus Torvalds 
58331da177e4SLinus Torvalds 		/* RFC1323: The window in SYN & SYN/ACK segments is
58341da177e4SLinus Torvalds 		 * never scaled.
58351da177e4SLinus Torvalds 		 */
58361da177e4SLinus Torvalds 		tp->snd_wnd    = ntohs(th->window);
58371da177e4SLinus Torvalds 		tp->snd_wl1    = TCP_SKB_CB(skb)->seq;
58381da177e4SLinus Torvalds 		tp->max_window = tp->snd_wnd;
58391da177e4SLinus Torvalds 
5840735d3831SFlorian Westphal 		tcp_ecn_rcv_syn(tp, th);
58411da177e4SLinus Torvalds 
58425d424d5aSJohn Heffner 		tcp_mtup_init(sk);
5843d83d8461SArnaldo Carvalho de Melo 		tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
58441da177e4SLinus Torvalds 		tcp_initialize_rcv_mss(sk);
58451da177e4SLinus Torvalds 
58461da177e4SLinus Torvalds 		tcp_send_synack(sk);
58471da177e4SLinus Torvalds #if 0
58481da177e4SLinus Torvalds 		/* Note, we could accept data and URG from this segment.
5849168a8f58SJerry Chu 		 * There are no obstacles to make this (except that we must
5850168a8f58SJerry Chu 		 * either change tcp_recvmsg() to prevent it from returning data
5851168a8f58SJerry Chu 		 * before 3WHS completes per RFC793, or employ TCP Fast Open).
58521da177e4SLinus Torvalds 		 *
58531da177e4SLinus Torvalds 		 * However, if we ignore data in ACKless segments sometimes,
58541da177e4SLinus Torvalds 		 * we have no reasons to accept it sometimes.
58551da177e4SLinus Torvalds 		 * Also, seems the code doing it in step6 of tcp_rcv_state_process
58561da177e4SLinus Torvalds 		 * is not flawless. So, discard packet for sanity.
58571da177e4SLinus Torvalds 		 * Uncomment this return to process the data.
58581da177e4SLinus Torvalds 		 */
58591da177e4SLinus Torvalds 		return -1;
58601da177e4SLinus Torvalds #else
58611da177e4SLinus Torvalds 		goto discard;
58621da177e4SLinus Torvalds #endif
58631da177e4SLinus Torvalds 	}
58641da177e4SLinus Torvalds 	/* "fifth, if neither of the SYN or RST bits is set then
58651da177e4SLinus Torvalds 	 * drop the segment and return."
58661da177e4SLinus Torvalds 	 */
58671da177e4SLinus Torvalds 
58681da177e4SLinus Torvalds discard_and_undo:
58691da177e4SLinus Torvalds 	tcp_clear_options(&tp->rx_opt);
58701da177e4SLinus Torvalds 	tp->rx_opt.mss_clamp = saved_clamp;
58711da177e4SLinus Torvalds 	goto discard;
58721da177e4SLinus Torvalds 
58731da177e4SLinus Torvalds reset_and_undo:
58741da177e4SLinus Torvalds 	tcp_clear_options(&tp->rx_opt);
58751da177e4SLinus Torvalds 	tp->rx_opt.mss_clamp = saved_clamp;
58761da177e4SLinus Torvalds 	return 1;
58771da177e4SLinus Torvalds }
58781da177e4SLinus Torvalds 
58791da177e4SLinus Torvalds /*
58801da177e4SLinus Torvalds  *	This function implements the receiving procedure of RFC 793 for
58811da177e4SLinus Torvalds  *	all states except ESTABLISHED and TIME_WAIT.
58821da177e4SLinus Torvalds  *	It's called from both tcp_v4_rcv and tcp_v6_rcv and should be
58831da177e4SLinus Torvalds  *	address independent.
58841da177e4SLinus Torvalds  */
58851da177e4SLinus Torvalds 
588672ab4a86SEric Dumazet int tcp_rcv_state_process(struct sock *sk, struct sk_buff *skb)
58871da177e4SLinus Torvalds {
58881da177e4SLinus Torvalds 	struct tcp_sock *tp = tcp_sk(sk);
58898292a17aSArnaldo Carvalho de Melo 	struct inet_connection_sock *icsk = inet_csk(sk);
589072ab4a86SEric Dumazet 	const struct tcphdr *th = tcp_hdr(skb);
5891168a8f58SJerry Chu 	struct request_sock *req;
58921da177e4SLinus Torvalds 	int queued = 0;
58931f6afc81SEric Dumazet 	bool acceptable;
58941da177e4SLinus Torvalds 
58951da177e4SLinus Torvalds 	switch (sk->sk_state) {
58961da177e4SLinus Torvalds 	case TCP_CLOSE:
58971da177e4SLinus Torvalds 		goto discard;
58981da177e4SLinus Torvalds 
58991da177e4SLinus Torvalds 	case TCP_LISTEN:
59001da177e4SLinus Torvalds 		if (th->ack)
59011da177e4SLinus Torvalds 			return 1;
59021da177e4SLinus Torvalds 
59031da177e4SLinus Torvalds 		if (th->rst)
59041da177e4SLinus Torvalds 			goto discard;
59051da177e4SLinus Torvalds 
59061da177e4SLinus Torvalds 		if (th->syn) {
5907fdf5af0dSEric Dumazet 			if (th->fin)
5908fdf5af0dSEric Dumazet 				goto discard;
5909449809a6SEric Dumazet 			/* It is possible that we process SYN packets from backlog,
5910449809a6SEric Dumazet 			 * so we need to make sure to disable BH right there.
5911449809a6SEric Dumazet 			 */
5912449809a6SEric Dumazet 			local_bh_disable();
5913449809a6SEric Dumazet 			acceptable = icsk->icsk_af_ops->conn_request(sk, skb) >= 0;
5914449809a6SEric Dumazet 			local_bh_enable();
59151da177e4SLinus Torvalds 
5916449809a6SEric Dumazet 			if (!acceptable)
5917449809a6SEric Dumazet 				return 1;
59180aea76d3SEric Dumazet 			consume_skb(skb);
5919fb7e2399SMasayuki Nakagawa 			return 0;
59201da177e4SLinus Torvalds 		}
59211da177e4SLinus Torvalds 		goto discard;
59221da177e4SLinus Torvalds 
59231da177e4SLinus Torvalds 	case TCP_SYN_SENT:
59248804b272SEric Dumazet 		tp->rx_opt.saw_tstamp = 0;
59259a568de4SEric Dumazet 		tcp_mstamp_refresh(tp);
5926bda07a64SEric Dumazet 		queued = tcp_rcv_synsent_state_process(sk, skb, th);
59271da177e4SLinus Torvalds 		if (queued >= 0)
59281da177e4SLinus Torvalds 			return queued;
59291da177e4SLinus Torvalds 
59301da177e4SLinus Torvalds 		/* Do step6 onward by hand. */
59311da177e4SLinus Torvalds 		tcp_urg(sk, skb, th);
59321da177e4SLinus Torvalds 		__kfree_skb(skb);
59339e412ba7SIlpo Järvinen 		tcp_data_snd_check(sk);
59341da177e4SLinus Torvalds 		return 0;
59351da177e4SLinus Torvalds 	}
59361da177e4SLinus Torvalds 
59379a568de4SEric Dumazet 	tcp_mstamp_refresh(tp);
59388804b272SEric Dumazet 	tp->rx_opt.saw_tstamp = 0;
5939168a8f58SJerry Chu 	req = tp->fastopen_rsk;
594000db4124SIan Morris 	if (req) {
594137561f68SJerry Chu 		WARN_ON_ONCE(sk->sk_state != TCP_SYN_RECV &&
5942168a8f58SJerry Chu 		    sk->sk_state != TCP_FIN_WAIT1);
5943168a8f58SJerry Chu 
594451456b29SIan Morris 		if (!tcp_check_req(sk, skb, req, true))
5945168a8f58SJerry Chu 			goto discard;
5946e69bebdeSNeal Cardwell 	}
5947c3ae62afSEric Dumazet 
59480c228e83SCalvin Owens 	if (!th->ack && !th->rst && !th->syn)
5949c3ae62afSEric Dumazet 		goto discard;
5950c3ae62afSEric Dumazet 
5951e69bebdeSNeal Cardwell 	if (!tcp_validate_incoming(sk, skb, th, 0))
59520c24604bSEric Dumazet 		return 0;
59531da177e4SLinus Torvalds 
59541da177e4SLinus Torvalds 	/* step 5: check the ACK field */
59551f6afc81SEric Dumazet 	acceptable = tcp_ack(sk, skb, FLAG_SLOWPATH |
5956*d0e1a1b5SEric Dumazet 				      FLAG_UPDATE_TS_RECENT |
5957*d0e1a1b5SEric Dumazet 				      FLAG_NO_CHALLENGE_ACK) > 0;
59581da177e4SLinus Torvalds 
5959*d0e1a1b5SEric Dumazet 	if (!acceptable) {
5960*d0e1a1b5SEric Dumazet 		if (sk->sk_state == TCP_SYN_RECV)
5961*d0e1a1b5SEric Dumazet 			return 1;	/* send one RST */
5962*d0e1a1b5SEric Dumazet 		tcp_send_challenge_ack(sk, skb);
5963*d0e1a1b5SEric Dumazet 		goto discard;
5964*d0e1a1b5SEric Dumazet 	}
59651da177e4SLinus Torvalds 	switch (sk->sk_state) {
59661da177e4SLinus Torvalds 	case TCP_SYN_RECV:
59670f1c28aeSYuchung Cheng 		if (!tp->srtt_us)
59680f1c28aeSYuchung Cheng 			tcp_synack_rtt_meas(sk, req);
59690f1c28aeSYuchung Cheng 
597061eb9003SJoe Perches 		/* Once we leave TCP_SYN_RECV, we no longer need req
597161eb9003SJoe Perches 		 * so release it.
5972168a8f58SJerry Chu 		 */
5973168a8f58SJerry Chu 		if (req) {
59747e32b443SYuchung Cheng 			inet_csk(sk)->icsk_retransmits = 0;
5975168a8f58SJerry Chu 			reqsk_fastopen_remove(sk, req, false);
5976168a8f58SJerry Chu 		} else {
597761eb9003SJoe Perches 			/* Make sure socket is routed, for correct metrics. */
5978168a8f58SJerry Chu 			icsk->icsk_af_ops->rebuild_header(sk);
5979168a8f58SJerry Chu 			tcp_init_congestion_control(sk);
5980168a8f58SJerry Chu 
5981168a8f58SJerry Chu 			tcp_mtup_init(sk);
59821da177e4SLinus Torvalds 			tp->copied_seq = tp->rcv_nxt;
5983b0983d3cSEric Dumazet 			tcp_init_buffer_space(sk);
5984168a8f58SJerry Chu 		}
5985e16aa207SRalf Baechle 		smp_mb();
59861da177e4SLinus Torvalds 		tcp_set_state(sk, TCP_ESTABLISHED);
59871da177e4SLinus Torvalds 		sk->sk_state_change(sk);
59881da177e4SLinus Torvalds 
598961eb9003SJoe Perches 		/* Note, that this wakeup is only for marginal crossed SYN case.
599061eb9003SJoe Perches 		 * Passively open sockets are not waked up, because
599161eb9003SJoe Perches 		 * sk->sk_sleep == NULL and sk->sk_socket == NULL.
59921da177e4SLinus Torvalds 		 */
59938d8ad9d7SPavel Emelyanov 		if (sk->sk_socket)
59941f6afc81SEric Dumazet 			sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT);
59951da177e4SLinus Torvalds 
59961da177e4SLinus Torvalds 		tp->snd_una = TCP_SKB_CB(skb)->ack_seq;
599761eb9003SJoe Perches 		tp->snd_wnd = ntohs(th->window) << tp->rx_opt.snd_wscale;
5998ee7537b6SHantzis Fotis 		tcp_init_wl(tp, TCP_SKB_CB(skb)->seq);
59991da177e4SLinus Torvalds 
60001da177e4SLinus Torvalds 		if (tp->rx_opt.tstamp_ok)
60011da177e4SLinus Torvalds 			tp->advmss -= TCPOLEN_TSTAMP_ALIGNED;
60021da177e4SLinus Torvalds 
6003168a8f58SJerry Chu 		if (req) {
600461eb9003SJoe Perches 			/* Re-arm the timer because data may have been sent out.
600561eb9003SJoe Perches 			 * This is similar to the regular data transmission case
6006168a8f58SJerry Chu 			 * when new data has just been ack'ed.
6007168a8f58SJerry Chu 			 *
600861eb9003SJoe Perches 			 * (TFO) - we could try to be more aggressive and
600961eb9003SJoe Perches 			 * retransmitting any data sooner based on when they
601061eb9003SJoe Perches 			 * are sent out.
60111da177e4SLinus Torvalds 			 */
6012168a8f58SJerry Chu 			tcp_rearm_rto(sk);
6013168a8f58SJerry Chu 		} else
60141da177e4SLinus Torvalds 			tcp_init_metrics(sk);
60151da177e4SLinus Torvalds 
6016c0402760SYuchung Cheng 		if (!inet_csk(sk)->icsk_ca_ops->cong_control)
601702cf4ebdSNeal Cardwell 			tcp_update_pacing_rate(sk);
601802cf4ebdSNeal Cardwell 
601961eb9003SJoe Perches 		/* Prevent spurious tcp_cwnd_restart() on first data packet */
6020d635fbe2SEric Dumazet 		tp->lsndtime = tcp_jiffies32;
60211da177e4SLinus Torvalds 
60221da177e4SLinus Torvalds 		tcp_initialize_rcv_mss(sk);
60231da177e4SLinus Torvalds 		tcp_fast_path_on(tp);
60241da177e4SLinus Torvalds 		break;
60251da177e4SLinus Torvalds 
6026c48b22daSJoe Perches 	case TCP_FIN_WAIT1: {
6027c48b22daSJoe Perches 		int tmo;
6028c48b22daSJoe Perches 
6029168a8f58SJerry Chu 		/* If we enter the TCP_FIN_WAIT1 state and we are a
6030168a8f58SJerry Chu 		 * Fast Open socket and this is the first acceptable
6031168a8f58SJerry Chu 		 * ACK we have received, this would have acknowledged
6032168a8f58SJerry Chu 		 * our SYNACK so stop the SYNACK timer.
6033168a8f58SJerry Chu 		 */
603400db4124SIan Morris 		if (req) {
6035168a8f58SJerry Chu 			/* We no longer need the request sock. */
6036168a8f58SJerry Chu 			reqsk_fastopen_remove(sk, req, false);
6037168a8f58SJerry Chu 			tcp_rearm_rto(sk);
6038168a8f58SJerry Chu 		}
6039c48b22daSJoe Perches 		if (tp->snd_una != tp->write_seq)
6040c48b22daSJoe Perches 			break;
60415110effeSDavid S. Miller 
60421da177e4SLinus Torvalds 		tcp_set_state(sk, TCP_FIN_WAIT2);
60431da177e4SLinus Torvalds 		sk->sk_shutdown |= SEND_SHUTDOWN;
60445110effeSDavid S. Miller 
6045c3a2e837SJulian Anastasov 		sk_dst_confirm(sk);
60461da177e4SLinus Torvalds 
60471f6afc81SEric Dumazet 		if (!sock_flag(sk, SOCK_DEAD)) {
60481da177e4SLinus Torvalds 			/* Wake up lingering close() */
60491da177e4SLinus Torvalds 			sk->sk_state_change(sk);
6050c48b22daSJoe Perches 			break;
6051c48b22daSJoe Perches 		}
60521da177e4SLinus Torvalds 
6053cf1ef3f0SWei Wang 		if (tp->linger2 < 0) {
6054cf1ef3f0SWei Wang 			tcp_done(sk);
6055cf1ef3f0SWei Wang 			NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
6056cf1ef3f0SWei Wang 			return 1;
6057cf1ef3f0SWei Wang 		}
6058cf1ef3f0SWei Wang 		if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
6059cf1ef3f0SWei Wang 		    after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt)) {
6060cf1ef3f0SWei Wang 			/* Receive out of order FIN after close() */
6061cf1ef3f0SWei Wang 			if (tp->syn_fastopen && th->fin)
606246c2fa39SWei Wang 				tcp_fastopen_active_disable(sk);
60631da177e4SLinus Torvalds 			tcp_done(sk);
6064c10d9310SEric Dumazet 			NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
60651da177e4SLinus Torvalds 			return 1;
60661da177e4SLinus Torvalds 		}
60671da177e4SLinus Torvalds 
6068463c84b9SArnaldo Carvalho de Melo 		tmo = tcp_fin_time(sk);
60691da177e4SLinus Torvalds 		if (tmo > TCP_TIMEWAIT_LEN) {
6070463c84b9SArnaldo Carvalho de Melo 			inet_csk_reset_keepalive_timer(sk, tmo - TCP_TIMEWAIT_LEN);
60711da177e4SLinus Torvalds 		} else if (th->fin || sock_owned_by_user(sk)) {
60721da177e4SLinus Torvalds 			/* Bad case. We could lose such FIN otherwise.
60731da177e4SLinus Torvalds 			 * It is not a big problem, but it looks confusing
60741da177e4SLinus Torvalds 			 * and not so rare event. We still can lose it now,
60751da177e4SLinus Torvalds 			 * if it spins in bh_lock_sock(), but it is really
60761da177e4SLinus Torvalds 			 * marginal case.
60771da177e4SLinus Torvalds 			 */
6078463c84b9SArnaldo Carvalho de Melo 			inet_csk_reset_keepalive_timer(sk, tmo);
60791da177e4SLinus Torvalds 		} else {
60801da177e4SLinus Torvalds 			tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
60811da177e4SLinus Torvalds 			goto discard;
60821da177e4SLinus Torvalds 		}
60831da177e4SLinus Torvalds 		break;
6084c48b22daSJoe Perches 	}
60851da177e4SLinus Torvalds 
60861da177e4SLinus Torvalds 	case TCP_CLOSING:
60871da177e4SLinus Torvalds 		if (tp->snd_una == tp->write_seq) {
60881da177e4SLinus Torvalds 			tcp_time_wait(sk, TCP_TIME_WAIT, 0);
60891da177e4SLinus Torvalds 			goto discard;
60901da177e4SLinus Torvalds 		}
60911da177e4SLinus Torvalds 		break;
60921da177e4SLinus Torvalds 
60931da177e4SLinus Torvalds 	case TCP_LAST_ACK:
60941da177e4SLinus Torvalds 		if (tp->snd_una == tp->write_seq) {
60951da177e4SLinus Torvalds 			tcp_update_metrics(sk);
60961da177e4SLinus Torvalds 			tcp_done(sk);
60971da177e4SLinus Torvalds 			goto discard;
60981da177e4SLinus Torvalds 		}
60991da177e4SLinus Torvalds 		break;
61001da177e4SLinus Torvalds 	}
61011da177e4SLinus Torvalds 
61021da177e4SLinus Torvalds 	/* step 6: check the URG bit */
61031da177e4SLinus Torvalds 	tcp_urg(sk, skb, th);
61041da177e4SLinus Torvalds 
61051da177e4SLinus Torvalds 	/* step 7: process the segment text */
61061da177e4SLinus Torvalds 	switch (sk->sk_state) {
61071da177e4SLinus Torvalds 	case TCP_CLOSE_WAIT:
61081da177e4SLinus Torvalds 	case TCP_CLOSING:
61091da177e4SLinus Torvalds 	case TCP_LAST_ACK:
61101da177e4SLinus Torvalds 		if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt))
61111da177e4SLinus Torvalds 			break;
61121da177e4SLinus Torvalds 	case TCP_FIN_WAIT1:
61131da177e4SLinus Torvalds 	case TCP_FIN_WAIT2:
61141da177e4SLinus Torvalds 		/* RFC 793 says to queue data in these states,
61151da177e4SLinus Torvalds 		 * RFC 1122 says we MUST send a reset.
61161da177e4SLinus Torvalds 		 * BSD 4.4 also does reset.
61171da177e4SLinus Torvalds 		 */
61181da177e4SLinus Torvalds 		if (sk->sk_shutdown & RCV_SHUTDOWN) {
61191da177e4SLinus Torvalds 			if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
61201da177e4SLinus Torvalds 			    after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt)) {
6121c10d9310SEric Dumazet 				NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
61221da177e4SLinus Torvalds 				tcp_reset(sk);
61231da177e4SLinus Torvalds 				return 1;
61241da177e4SLinus Torvalds 			}
61251da177e4SLinus Torvalds 		}
61261da177e4SLinus Torvalds 		/* Fall through */
61271da177e4SLinus Torvalds 	case TCP_ESTABLISHED:
61281da177e4SLinus Torvalds 		tcp_data_queue(sk, skb);
61291da177e4SLinus Torvalds 		queued = 1;
61301da177e4SLinus Torvalds 		break;
61311da177e4SLinus Torvalds 	}
61321da177e4SLinus Torvalds 
61331da177e4SLinus Torvalds 	/* tcp_data could move socket to TIME-WAIT */
61341da177e4SLinus Torvalds 	if (sk->sk_state != TCP_CLOSE) {
61359e412ba7SIlpo Järvinen 		tcp_data_snd_check(sk);
61361da177e4SLinus Torvalds 		tcp_ack_snd_check(sk);
61371da177e4SLinus Torvalds 	}
61381da177e4SLinus Torvalds 
61391da177e4SLinus Torvalds 	if (!queued) {
61401da177e4SLinus Torvalds discard:
6141532182cdSEric Dumazet 		tcp_drop(sk, skb);
61421da177e4SLinus Torvalds 	}
61431da177e4SLinus Torvalds 	return 0;
61441da177e4SLinus Torvalds }
61451da177e4SLinus Torvalds EXPORT_SYMBOL(tcp_rcv_state_process);
61461fb6f159SOctavian Purdila 
61471fb6f159SOctavian Purdila static inline void pr_drop_req(struct request_sock *req, __u16 port, int family)
61481fb6f159SOctavian Purdila {
61491fb6f159SOctavian Purdila 	struct inet_request_sock *ireq = inet_rsk(req);
61501fb6f159SOctavian Purdila 
61511fb6f159SOctavian Purdila 	if (family == AF_INET)
6152ba7a46f1SJoe Perches 		net_dbg_ratelimited("drop open request from %pI4/%u\n",
61531fb6f159SOctavian Purdila 				    &ireq->ir_rmt_addr, port);
61544135ab82SOctavian Purdila #if IS_ENABLED(CONFIG_IPV6)
61554135ab82SOctavian Purdila 	else if (family == AF_INET6)
6156ba7a46f1SJoe Perches 		net_dbg_ratelimited("drop open request from %pI6/%u\n",
61571fb6f159SOctavian Purdila 				    &ireq->ir_v6_rmt_addr, port);
61584135ab82SOctavian Purdila #endif
61591fb6f159SOctavian Purdila }
61601fb6f159SOctavian Purdila 
6161d82bd122SFlorian Westphal /* RFC3168 : 6.1.1 SYN packets must not have ECT/ECN bits set
6162d82bd122SFlorian Westphal  *
6163d82bd122SFlorian Westphal  * If we receive a SYN packet with these bits set, it means a
6164d82bd122SFlorian Westphal  * network is playing bad games with TOS bits. In order to
6165d82bd122SFlorian Westphal  * avoid possible false congestion notifications, we disable
6166f4e715c3Sstephen hemminger  * TCP ECN negotiation.
6167d82bd122SFlorian Westphal  *
6168d82bd122SFlorian Westphal  * Exception: tcp_ca wants ECN. This is required for DCTCP
6169843c2fdfSFlorian Westphal  * congestion control: Linux DCTCP asserts ECT on all packets,
6170843c2fdfSFlorian Westphal  * including SYN, which is most optimal solution; however,
6171843c2fdfSFlorian Westphal  * others, such as FreeBSD do not.
6172d82bd122SFlorian Westphal  */
6173d82bd122SFlorian Westphal static void tcp_ecn_create_request(struct request_sock *req,
6174d82bd122SFlorian Westphal 				   const struct sk_buff *skb,
6175f7b3bec6SFlorian Westphal 				   const struct sock *listen_sk,
6176f7b3bec6SFlorian Westphal 				   const struct dst_entry *dst)
6177d82bd122SFlorian Westphal {
6178d82bd122SFlorian Westphal 	const struct tcphdr *th = tcp_hdr(skb);
6179d82bd122SFlorian Westphal 	const struct net *net = sock_net(listen_sk);
6180d82bd122SFlorian Westphal 	bool th_ecn = th->ece && th->cwr;
6181843c2fdfSFlorian Westphal 	bool ect, ecn_ok;
6182c3a8d947SDaniel Borkmann 	u32 ecn_ok_dst;
6183d82bd122SFlorian Westphal 
6184d82bd122SFlorian Westphal 	if (!th_ecn)
6185d82bd122SFlorian Westphal 		return;
6186d82bd122SFlorian Westphal 
6187d82bd122SFlorian Westphal 	ect = !INET_ECN_is_not_ect(TCP_SKB_CB(skb)->ip_dsfield);
6188c3a8d947SDaniel Borkmann 	ecn_ok_dst = dst_feature(dst, DST_FEATURE_ECN_MASK);
6189c3a8d947SDaniel Borkmann 	ecn_ok = net->ipv4.sysctl_tcp_ecn || ecn_ok_dst;
6190d82bd122SFlorian Westphal 
6191c3a8d947SDaniel Borkmann 	if ((!ect && ecn_ok) || tcp_ca_needs_ecn(listen_sk) ||
6192c3a8d947SDaniel Borkmann 	    (ecn_ok_dst & DST_FEATURE_ECN_CA))
6193d82bd122SFlorian Westphal 		inet_rsk(req)->ecn_ok = 1;
6194d82bd122SFlorian Westphal }
6195d82bd122SFlorian Westphal 
61961bfc4438SEric Dumazet static void tcp_openreq_init(struct request_sock *req,
61971bfc4438SEric Dumazet 			     const struct tcp_options_received *rx_opt,
61981bfc4438SEric Dumazet 			     struct sk_buff *skb, const struct sock *sk)
61991bfc4438SEric Dumazet {
62001bfc4438SEric Dumazet 	struct inet_request_sock *ireq = inet_rsk(req);
62011bfc4438SEric Dumazet 
6202ed53d0abSEric Dumazet 	req->rsk_rcv_wnd = 0;		/* So that tcp_send_synack() knows! */
62031bfc4438SEric Dumazet 	req->cookie_ts = 0;
62041bfc4438SEric Dumazet 	tcp_rsk(req)->rcv_isn = TCP_SKB_CB(skb)->seq;
62051bfc4438SEric Dumazet 	tcp_rsk(req)->rcv_nxt = TCP_SKB_CB(skb)->seq + 1;
62069a568de4SEric Dumazet 	tcp_rsk(req)->snt_synack = tcp_clock_us();
62071bfc4438SEric Dumazet 	tcp_rsk(req)->last_oow_ack_time = 0;
62081bfc4438SEric Dumazet 	req->mss = rx_opt->mss_clamp;
62091bfc4438SEric Dumazet 	req->ts_recent = rx_opt->saw_tstamp ? rx_opt->rcv_tsval : 0;
62101bfc4438SEric Dumazet 	ireq->tstamp_ok = rx_opt->tstamp_ok;
62111bfc4438SEric Dumazet 	ireq->sack_ok = rx_opt->sack_ok;
62121bfc4438SEric Dumazet 	ireq->snd_wscale = rx_opt->snd_wscale;
62131bfc4438SEric Dumazet 	ireq->wscale_ok = rx_opt->wscale_ok;
62141bfc4438SEric Dumazet 	ireq->acked = 0;
62151bfc4438SEric Dumazet 	ireq->ecn_ok = 0;
62161bfc4438SEric Dumazet 	ireq->ir_rmt_port = tcp_hdr(skb)->source;
62171bfc4438SEric Dumazet 	ireq->ir_num = ntohs(tcp_hdr(skb)->dest);
62181bfc4438SEric Dumazet 	ireq->ir_mark = inet_request_mark(sk, skb);
62191bfc4438SEric Dumazet }
62201bfc4438SEric Dumazet 
6221e49bb337SEric Dumazet struct request_sock *inet_reqsk_alloc(const struct request_sock_ops *ops,
6222a1a5344dSEric Dumazet 				      struct sock *sk_listener,
6223a1a5344dSEric Dumazet 				      bool attach_listener)
6224e49bb337SEric Dumazet {
6225a1a5344dSEric Dumazet 	struct request_sock *req = reqsk_alloc(ops, sk_listener,
6226a1a5344dSEric Dumazet 					       attach_listener);
6227e49bb337SEric Dumazet 
6228e49bb337SEric Dumazet 	if (req) {
6229e49bb337SEric Dumazet 		struct inet_request_sock *ireq = inet_rsk(req);
6230e49bb337SEric Dumazet 
6231e49bb337SEric Dumazet 		kmemcheck_annotate_bitfield(ireq, flags);
6232e49bb337SEric Dumazet 		ireq->opt = NULL;
623356ac42bcSHuw Davies #if IS_ENABLED(CONFIG_IPV6)
623456ac42bcSHuw Davies 		ireq->pktopts = NULL;
623556ac42bcSHuw Davies #endif
6236e49bb337SEric Dumazet 		atomic64_set(&ireq->ir_cookie, 0);
6237e49bb337SEric Dumazet 		ireq->ireq_state = TCP_NEW_SYN_RECV;
6238e49bb337SEric Dumazet 		write_pnet(&ireq->ireq_net, sock_net(sk_listener));
62390144a81cSEric Dumazet 		ireq->ireq_family = sk_listener->sk_family;
6240e49bb337SEric Dumazet 	}
6241e49bb337SEric Dumazet 
6242e49bb337SEric Dumazet 	return req;
6243e49bb337SEric Dumazet }
6244e49bb337SEric Dumazet EXPORT_SYMBOL(inet_reqsk_alloc);
6245e49bb337SEric Dumazet 
624641d25fe0SEric Dumazet /*
624741d25fe0SEric Dumazet  * Return true if a syncookie should be sent
624841d25fe0SEric Dumazet  */
62492985aaacSEric Dumazet static bool tcp_syn_flood_action(const struct sock *sk,
625041d25fe0SEric Dumazet 				 const struct sk_buff *skb,
625141d25fe0SEric Dumazet 				 const char *proto)
625241d25fe0SEric Dumazet {
62538d2675f1SEric Dumazet 	struct request_sock_queue *queue = &inet_csk(sk)->icsk_accept_queue;
625441d25fe0SEric Dumazet 	const char *msg = "Dropping request";
625541d25fe0SEric Dumazet 	bool want_cookie = false;
625612ed8244SNikolay Borisov 	struct net *net = sock_net(sk);
625741d25fe0SEric Dumazet 
625841d25fe0SEric Dumazet #ifdef CONFIG_SYN_COOKIES
625912ed8244SNikolay Borisov 	if (net->ipv4.sysctl_tcp_syncookies) {
626041d25fe0SEric Dumazet 		msg = "Sending cookies";
626141d25fe0SEric Dumazet 		want_cookie = true;
626202a1d6e7SEric Dumazet 		__NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPREQQFULLDOCOOKIES);
626341d25fe0SEric Dumazet 	} else
626441d25fe0SEric Dumazet #endif
626502a1d6e7SEric Dumazet 		__NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPREQQFULLDROP);
626641d25fe0SEric Dumazet 
62678d2675f1SEric Dumazet 	if (!queue->synflood_warned &&
626812ed8244SNikolay Borisov 	    net->ipv4.sysctl_tcp_syncookies != 2 &&
62698d2675f1SEric Dumazet 	    xchg(&queue->synflood_warned, 1) == 0)
627041d25fe0SEric Dumazet 		pr_info("%s: Possible SYN flooding on port %d. %s.  Check SNMP counters.\n",
627141d25fe0SEric Dumazet 			proto, ntohs(tcp_hdr(skb)->dest), msg);
62722985aaacSEric Dumazet 
627341d25fe0SEric Dumazet 	return want_cookie;
627441d25fe0SEric Dumazet }
627541d25fe0SEric Dumazet 
6276cd8ae852SEric Dumazet static void tcp_reqsk_record_syn(const struct sock *sk,
6277cd8ae852SEric Dumazet 				 struct request_sock *req,
6278cd8ae852SEric Dumazet 				 const struct sk_buff *skb)
6279cd8ae852SEric Dumazet {
6280cd8ae852SEric Dumazet 	if (tcp_sk(sk)->save_syn) {
6281cd8ae852SEric Dumazet 		u32 len = skb_network_header_len(skb) + tcp_hdrlen(skb);
6282cd8ae852SEric Dumazet 		u32 *copy;
6283cd8ae852SEric Dumazet 
6284cd8ae852SEric Dumazet 		copy = kmalloc(len + sizeof(u32), GFP_ATOMIC);
6285cd8ae852SEric Dumazet 		if (copy) {
6286cd8ae852SEric Dumazet 			copy[0] = len;
6287cd8ae852SEric Dumazet 			memcpy(&copy[1], skb_network_header(skb), len);
6288cd8ae852SEric Dumazet 			req->saved_syn = copy;
6289cd8ae852SEric Dumazet 		}
6290cd8ae852SEric Dumazet 	}
6291cd8ae852SEric Dumazet }
6292cd8ae852SEric Dumazet 
62931fb6f159SOctavian Purdila int tcp_conn_request(struct request_sock_ops *rsk_ops,
62941fb6f159SOctavian Purdila 		     const struct tcp_request_sock_ops *af_ops,
62951fb6f159SOctavian Purdila 		     struct sock *sk, struct sk_buff *skb)
62961fb6f159SOctavian Purdila {
62971fb6f159SOctavian Purdila 	struct tcp_fastopen_cookie foc = { .len = -1 };
62987c85af88SEric Dumazet 	__u32 isn = TCP_SKB_CB(skb)->tcp_tw_isn;
62997c85af88SEric Dumazet 	struct tcp_options_received tmp_opt;
63007c85af88SEric Dumazet 	struct tcp_sock *tp = tcp_sk(sk);
630112ed8244SNikolay Borisov 	struct net *net = sock_net(sk);
63027c85af88SEric Dumazet 	struct sock *fastopen_sk = NULL;
63037c85af88SEric Dumazet 	struct dst_entry *dst = NULL;
63047c85af88SEric Dumazet 	struct request_sock *req;
63057c85af88SEric Dumazet 	bool want_cookie = false;
63067c85af88SEric Dumazet 	struct flowi fl;
63071fb6f159SOctavian Purdila 
63081fb6f159SOctavian Purdila 	/* TW buckets are converted to open requests without
63091fb6f159SOctavian Purdila 	 * limitations, they conserve resources and peer is
63101fb6f159SOctavian Purdila 	 * evidently real one.
63111fb6f159SOctavian Purdila 	 */
631212ed8244SNikolay Borisov 	if ((net->ipv4.sysctl_tcp_syncookies == 2 ||
63131fb6f159SOctavian Purdila 	     inet_csk_reqsk_queue_is_full(sk)) && !isn) {
63141fb6f159SOctavian Purdila 		want_cookie = tcp_syn_flood_action(sk, skb, rsk_ops->slab_name);
63151fb6f159SOctavian Purdila 		if (!want_cookie)
63161fb6f159SOctavian Purdila 			goto drop;
63171fb6f159SOctavian Purdila 	}
63181fb6f159SOctavian Purdila 
63195ea8ea2cSEric Dumazet 	if (sk_acceptq_is_full(sk)) {
6320c10d9310SEric Dumazet 		NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
63211fb6f159SOctavian Purdila 		goto drop;
63221fb6f159SOctavian Purdila 	}
63231fb6f159SOctavian Purdila 
6324a1a5344dSEric Dumazet 	req = inet_reqsk_alloc(rsk_ops, sk, !want_cookie);
63251fb6f159SOctavian Purdila 	if (!req)
63261fb6f159SOctavian Purdila 		goto drop;
63271fb6f159SOctavian Purdila 
63281fb6f159SOctavian Purdila 	tcp_rsk(req)->af_specific = af_ops;
632995a22caeSFlorian Westphal 	tcp_rsk(req)->ts_off = 0;
63301fb6f159SOctavian Purdila 
63311fb6f159SOctavian Purdila 	tcp_clear_options(&tmp_opt);
63321fb6f159SOctavian Purdila 	tmp_opt.mss_clamp = af_ops->mss_clamp;
63331fb6f159SOctavian Purdila 	tmp_opt.user_mss  = tp->rx_opt.user_mss;
63341fb6f159SOctavian Purdila 	tcp_parse_options(skb, &tmp_opt, 0, want_cookie ? NULL : &foc);
63351fb6f159SOctavian Purdila 
63361fb6f159SOctavian Purdila 	if (want_cookie && !tmp_opt.saw_tstamp)
63371fb6f159SOctavian Purdila 		tcp_clear_options(&tmp_opt);
63381fb6f159SOctavian Purdila 
63391fb6f159SOctavian Purdila 	tmp_opt.tstamp_ok = tmp_opt.saw_tstamp;
63401fb6f159SOctavian Purdila 	tcp_openreq_init(req, &tmp_opt, skb, sk);
63417a682575SKOVACS Krisztian 	inet_rsk(req)->no_srccheck = inet_sk(sk)->transparent;
63421fb6f159SOctavian Purdila 
634316f86165SEric Dumazet 	/* Note: tcp_v6_init_req() might override ir_iif for link locals */
63446dd9a14eSDavid Ahern 	inet_rsk(req)->ir_iif = inet_request_bound_dev_if(sk, skb);
634516f86165SEric Dumazet 
63461fb6f159SOctavian Purdila 	af_ops->init_req(req, sk, skb);
63471fb6f159SOctavian Purdila 
63481fb6f159SOctavian Purdila 	if (security_inet_conn_request(sk, skb, req))
63491fb6f159SOctavian Purdila 		goto drop_and_free;
63501fb6f159SOctavian Purdila 
635184b114b9SEric Dumazet 	if (tmp_opt.tstamp_ok)
635284b114b9SEric Dumazet 		tcp_rsk(req)->ts_off = af_ops->init_ts_off(skb);
635395a22caeSFlorian Westphal 
6354f7b3bec6SFlorian Westphal 	if (!want_cookie && !isn) {
63551fb6f159SOctavian Purdila 		/* Kill the following clause, if you dislike this way. */
63564396e461SSoheil Hassas Yeganeh 		if (!net->ipv4.sysctl_tcp_syncookies &&
6357fee83d09SHaishuang Yan 		    (net->ipv4.sysctl_max_syn_backlog - inet_csk_reqsk_queue_len(sk) <
6358fee83d09SHaishuang Yan 		     (net->ipv4.sysctl_max_syn_backlog >> 2)) &&
6359d82bae12SSoheil Hassas Yeganeh 		    !tcp_peer_is_proven(req, dst)) {
63601fb6f159SOctavian Purdila 			/* Without syncookies last quarter of
63611fb6f159SOctavian Purdila 			 * backlog is filled with destinations,
63621fb6f159SOctavian Purdila 			 * proven to be alive.
63631fb6f159SOctavian Purdila 			 * It means that we continue to communicate
63641fb6f159SOctavian Purdila 			 * to destinations, already remembered
63651fb6f159SOctavian Purdila 			 * to the moment of synflood.
63661fb6f159SOctavian Purdila 			 */
63671fb6f159SOctavian Purdila 			pr_drop_req(req, ntohs(tcp_hdr(skb)->source),
63681fb6f159SOctavian Purdila 				    rsk_ops->family);
63691fb6f159SOctavian Purdila 			goto drop_and_release;
63701fb6f159SOctavian Purdila 		}
63711fb6f159SOctavian Purdila 
637284b114b9SEric Dumazet 		isn = af_ops->init_seq(skb);
63731fb6f159SOctavian Purdila 	}
63741fb6f159SOctavian Purdila 	if (!dst) {
63754396e461SSoheil Hassas Yeganeh 		dst = af_ops->route_req(sk, &fl, req);
63761fb6f159SOctavian Purdila 		if (!dst)
63771fb6f159SOctavian Purdila 			goto drop_and_free;
63781fb6f159SOctavian Purdila 	}
63791fb6f159SOctavian Purdila 
6380f7b3bec6SFlorian Westphal 	tcp_ecn_create_request(req, skb, sk, dst);
6381f7b3bec6SFlorian Westphal 
6382f7b3bec6SFlorian Westphal 	if (want_cookie) {
6383f7b3bec6SFlorian Westphal 		isn = cookie_init_sequence(af_ops, sk, skb, &req->mss);
6384f7b3bec6SFlorian Westphal 		req->cookie_ts = tmp_opt.tstamp_ok;
6385f7b3bec6SFlorian Westphal 		if (!tmp_opt.tstamp_ok)
6386f7b3bec6SFlorian Westphal 			inet_rsk(req)->ecn_ok = 0;
6387f7b3bec6SFlorian Westphal 	}
6388f7b3bec6SFlorian Westphal 
63891fb6f159SOctavian Purdila 	tcp_rsk(req)->snt_isn = isn;
639058d607d3SEric Dumazet 	tcp_rsk(req)->txhash = net_tx_rndhash();
63911fb6f159SOctavian Purdila 	tcp_openreq_init_rwin(req, sk, dst);
6392ca6fb065SEric Dumazet 	if (!want_cookie) {
6393ca6fb065SEric Dumazet 		tcp_reqsk_record_syn(sk, req, skb);
63947656d842SEric Dumazet 		fastopen_sk = tcp_try_fastopen(sk, skb, req, &foc, dst);
6395ca6fb065SEric Dumazet 	}
63967c85af88SEric Dumazet 	if (fastopen_sk) {
6397ca6fb065SEric Dumazet 		af_ops->send_synack(fastopen_sk, dst, &fl, req,
6398b3d05147SEric Dumazet 				    &foc, TCP_SYNACK_FASTOPEN);
63997656d842SEric Dumazet 		/* Add the child socket directly into the accept queue */
64007656d842SEric Dumazet 		inet_csk_reqsk_queue_add(sk, req, fastopen_sk);
64017656d842SEric Dumazet 		sk->sk_data_ready(sk);
64027656d842SEric Dumazet 		bh_unlock_sock(fastopen_sk);
64037c85af88SEric Dumazet 		sock_put(fastopen_sk);
64047c85af88SEric Dumazet 	} else {
64059439ce00SEric Dumazet 		tcp_rsk(req)->tfo_listener = false;
6406ca6fb065SEric Dumazet 		if (!want_cookie)
6407079096f1SEric Dumazet 			inet_csk_reqsk_queue_hash_add(sk, req, TCP_TIMEOUT_INIT);
6408b3d05147SEric Dumazet 		af_ops->send_synack(sk, dst, &fl, req, &foc,
6409b3d05147SEric Dumazet 				    !want_cookie ? TCP_SYNACK_NORMAL :
6410b3d05147SEric Dumazet 						   TCP_SYNACK_COOKIE);
64119caad864SEric Dumazet 		if (want_cookie) {
64129caad864SEric Dumazet 			reqsk_free(req);
64139caad864SEric Dumazet 			return 0;
64149caad864SEric Dumazet 		}
64151fb6f159SOctavian Purdila 	}
6416ca6fb065SEric Dumazet 	reqsk_put(req);
64171fb6f159SOctavian Purdila 	return 0;
64181fb6f159SOctavian Purdila 
64191fb6f159SOctavian Purdila drop_and_release:
64201fb6f159SOctavian Purdila 	dst_release(dst);
64211fb6f159SOctavian Purdila drop_and_free:
64221fb6f159SOctavian Purdila 	reqsk_free(req);
64231fb6f159SOctavian Purdila drop:
64249caad864SEric Dumazet 	tcp_listendrop(sk);
64251fb6f159SOctavian Purdila 	return 0;
64261fb6f159SOctavian Purdila }
64271fb6f159SOctavian Purdila EXPORT_SYMBOL(tcp_conn_request);
6428