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