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