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