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