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