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