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