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