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