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