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