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