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