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