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