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