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