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