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