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