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