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