1 // SPDX-License-Identifier: GPL-2.0-only 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: Pedro Roque : Retransmit queue handled by TCP. 24 * : Fragmentation on mtu decrease 25 * : Segment collapse on retransmit 26 * : AF independence 27 * 28 * Linus Torvalds : send_delayed_ack 29 * David S. Miller : Charge memory using the right skb 30 * during syn/ack processing. 31 * David S. Miller : Output engine completely rewritten. 32 * Andrea Arcangeli: SYNACK carry ts_recent in tsecr. 33 * Cacophonix Gaul : draft-minshall-nagle-01 34 * J Hadi Salim : ECN support 35 * 36 */ 37 38 #define pr_fmt(fmt) "TCP: " fmt 39 40 #include <net/tcp.h> 41 #include <net/tcp_ecn.h> 42 #include <net/mptcp.h> 43 #include <net/proto_memory.h> 44 #include <net/psp.h> 45 46 #include <linux/compiler.h> 47 #include <linux/gfp.h> 48 #include <linux/module.h> 49 #include <linux/static_key.h> 50 #include <linux/skbuff_ref.h> 51 52 #include <trace/events/tcp.h> 53 54 /* Refresh clocks of a TCP socket, 55 * ensuring monotically increasing values. 56 */ 57 void tcp_mstamp_refresh(struct tcp_sock *tp) 58 { 59 u64 val = tcp_clock_ns(); 60 61 tp->tcp_clock_cache = val; 62 tp->tcp_mstamp = div_u64(val, NSEC_PER_USEC); 63 } 64 65 static bool tcp_write_xmit(struct sock *sk, unsigned int mss_now, int nonagle, 66 int push_one, gfp_t gfp); 67 68 /* Account for new data that has been sent to the network. */ 69 static void tcp_event_new_data_sent(struct sock *sk, struct sk_buff *skb) 70 { 71 struct inet_connection_sock *icsk = inet_csk(sk); 72 struct tcp_sock *tp = tcp_sk(sk); 73 unsigned int prior_packets = tp->packets_out; 74 75 WRITE_ONCE(tp->snd_nxt, TCP_SKB_CB(skb)->end_seq); 76 77 __skb_unlink(skb, &sk->sk_write_queue); 78 tcp_rbtree_insert(&sk->tcp_rtx_queue, skb); 79 80 if (tp->highest_sack == NULL) 81 tp->highest_sack = skb; 82 83 tp->packets_out += tcp_skb_pcount(skb); 84 if (!prior_packets || icsk->icsk_pending == ICSK_TIME_LOSS_PROBE) 85 tcp_rearm_rto(sk); 86 87 NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPORIGDATASENT, 88 tcp_skb_pcount(skb)); 89 tcp_check_space(sk); 90 } 91 92 /* SND.NXT, if window was not shrunk or the amount of shrunk was less than one 93 * window scaling factor due to loss of precision. 94 * If window has been shrunk, what should we make? It is not clear at all. 95 * Using SND.UNA we will fail to open window, SND.NXT is out of window. :-( 96 * Anything in between SND.UNA...SND.UNA+SND.WND also can be already 97 * invalid. OK, let's make this for now: 98 */ 99 static inline __u32 tcp_acceptable_seq(const struct sock *sk) 100 { 101 const struct tcp_sock *tp = tcp_sk(sk); 102 103 if (!before(tcp_wnd_end(tp), tp->snd_nxt) || 104 (tp->rx_opt.wscale_ok && 105 ((tp->snd_nxt - tcp_wnd_end(tp)) < (1 << tp->rx_opt.rcv_wscale)))) 106 return tp->snd_nxt; 107 else 108 return tcp_wnd_end(tp); 109 } 110 111 /* Calculate mss to advertise in SYN segment. 112 * RFC1122, RFC1063, draft-ietf-tcpimpl-pmtud-01 state that: 113 * 114 * 1. It is independent of path mtu. 115 * 2. Ideally, it is maximal possible segment size i.e. 65535-40. 116 * 3. For IPv4 it is reasonable to calculate it from maximal MTU of 117 * attached devices, because some buggy hosts are confused by 118 * large MSS. 119 * 4. We do not make 3, we advertise MSS, calculated from first 120 * hop device mtu, but allow to raise it to ip_rt_min_advmss. 121 * This may be overridden via information stored in routing table. 122 * 5. Value 65535 for MSS is valid in IPv6 and means "as large as possible, 123 * probably even Jumbo". 124 */ 125 static __u16 tcp_advertise_mss(struct sock *sk) 126 { 127 struct tcp_sock *tp = tcp_sk(sk); 128 const struct dst_entry *dst = __sk_dst_get(sk); 129 int mss = tp->advmss; 130 131 if (dst) { 132 unsigned int metric = dst_metric_advmss(dst); 133 134 if (metric < mss) { 135 mss = metric; 136 tp->advmss = mss; 137 } 138 } 139 140 return (__u16)mss; 141 } 142 143 /* RFC2861. Reset CWND after idle period longer RTO to "restart window". 144 * This is the first part of cwnd validation mechanism. 145 */ 146 void tcp_cwnd_restart(struct sock *sk, s32 delta) 147 { 148 struct tcp_sock *tp = tcp_sk(sk); 149 u32 restart_cwnd = tcp_init_cwnd(tp, __sk_dst_get(sk)); 150 u32 cwnd = tcp_snd_cwnd(tp); 151 152 tcp_ca_event(sk, CA_EVENT_CWND_RESTART); 153 154 tp->snd_ssthresh = tcp_current_ssthresh(sk); 155 restart_cwnd = min(restart_cwnd, cwnd); 156 157 while ((delta -= inet_csk(sk)->icsk_rto) > 0 && cwnd > restart_cwnd) 158 cwnd >>= 1; 159 tcp_snd_cwnd_set(tp, max(cwnd, restart_cwnd)); 160 tp->snd_cwnd_stamp = tcp_jiffies32; 161 tp->snd_cwnd_used = 0; 162 } 163 164 /* Congestion state accounting after a packet has been sent. */ 165 static void tcp_event_data_sent(struct tcp_sock *tp, 166 struct sock *sk) 167 { 168 struct inet_connection_sock *icsk = inet_csk(sk); 169 const u32 now = tcp_jiffies32; 170 171 if (tcp_packets_in_flight(tp) == 0) 172 tcp_ca_event(sk, CA_EVENT_TX_START); 173 174 tp->lsndtime = now; 175 176 /* If it is a reply for ato after last received 177 * packet, increase pingpong count. 178 */ 179 if ((u32)(now - icsk->icsk_ack.lrcvtime) < icsk->icsk_ack.ato) 180 inet_csk_inc_pingpong_cnt(sk); 181 } 182 183 /* Account for an ACK we sent. */ 184 static inline void tcp_event_ack_sent(struct sock *sk, u32 rcv_nxt) 185 { 186 struct tcp_sock *tp = tcp_sk(sk); 187 188 if (unlikely(tp->compressed_ack)) { 189 NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPACKCOMPRESSED, 190 tp->compressed_ack); 191 tp->compressed_ack = 0; 192 if (hrtimer_try_to_cancel(&tp->compressed_ack_timer) == 1) 193 __sock_put(sk); 194 } 195 196 if (unlikely(rcv_nxt != tp->rcv_nxt)) 197 return; /* Special ACK sent by DCTCP to reflect ECN */ 198 tcp_dec_quickack_mode(sk); 199 inet_csk_clear_xmit_timer(sk, ICSK_TIME_DACK); 200 } 201 202 /* Determine a window scaling and initial window to offer. 203 * Based on the assumption that the given amount of space 204 * will be offered. Store the results in the tp structure. 205 * NOTE: for smooth operation initial space offering should 206 * be a multiple of mss if possible. We assume here that mss >= 1. 207 * This MUST be enforced by all callers. 208 */ 209 void tcp_select_initial_window(const struct sock *sk, int __space, __u32 mss, 210 __u32 *rcv_wnd, __u32 *__window_clamp, 211 int wscale_ok, __u8 *rcv_wscale, 212 __u32 init_rcv_wnd) 213 { 214 unsigned int space = (__space < 0 ? 0 : __space); 215 u32 window_clamp = READ_ONCE(*__window_clamp); 216 217 /* If no clamp set the clamp to the max possible scaled window */ 218 if (window_clamp == 0) 219 window_clamp = (U16_MAX << TCP_MAX_WSCALE); 220 space = min(window_clamp, space); 221 222 /* Quantize space offering to a multiple of mss if possible. */ 223 if (space > mss) 224 space = rounddown(space, mss); 225 226 /* NOTE: offering an initial window larger than 32767 227 * will break some buggy TCP stacks. If the admin tells us 228 * it is likely we could be speaking with such a buggy stack 229 * we will truncate our initial window offering to 32K-1 230 * unless the remote has sent us a window scaling option, 231 * which we interpret as a sign the remote TCP is not 232 * misinterpreting the window field as a signed quantity. 233 */ 234 if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_workaround_signed_windows)) 235 (*rcv_wnd) = min(space, MAX_TCP_WINDOW); 236 else 237 (*rcv_wnd) = space; 238 239 if (init_rcv_wnd) 240 *rcv_wnd = min(*rcv_wnd, init_rcv_wnd * mss); 241 242 *rcv_wscale = 0; 243 if (wscale_ok) { 244 /* Set window scaling on max possible window */ 245 space = max_t(u32, space, READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[2])); 246 space = max_t(u32, space, READ_ONCE(sysctl_rmem_max)); 247 space = min_t(u32, space, window_clamp); 248 *rcv_wscale = clamp_t(int, ilog2(space) - 15, 249 0, TCP_MAX_WSCALE); 250 } 251 /* Set the clamp no higher than max representable value */ 252 WRITE_ONCE(*__window_clamp, 253 min_t(__u32, U16_MAX << (*rcv_wscale), window_clamp)); 254 } 255 EXPORT_IPV6_MOD(tcp_select_initial_window); 256 257 /* Chose a new window to advertise, update state in tcp_sock for the 258 * socket, and return result with RFC1323 scaling applied. The return 259 * value can be stuffed directly into th->window for an outgoing 260 * frame. 261 */ 262 static u16 tcp_select_window(struct sock *sk) 263 { 264 struct tcp_sock *tp = tcp_sk(sk); 265 struct net *net = sock_net(sk); 266 u32 old_win = tp->rcv_wnd; 267 u32 cur_win, new_win; 268 269 /* Make the window 0 if we failed to queue the data because we 270 * are out of memory. 271 */ 272 if (unlikely(inet_csk(sk)->icsk_ack.pending & ICSK_ACK_NOMEM)) { 273 tp->pred_flags = 0; 274 tp->rcv_wnd = 0; 275 tp->rcv_wup = tp->rcv_nxt; 276 return 0; 277 } 278 279 cur_win = tcp_receive_window(tp); 280 new_win = __tcp_select_window(sk); 281 if (new_win < cur_win) { 282 /* Danger Will Robinson! 283 * Don't update rcv_wup/rcv_wnd here or else 284 * we will not be able to advertise a zero 285 * window in time. --DaveM 286 * 287 * Relax Will Robinson. 288 */ 289 if (!READ_ONCE(net->ipv4.sysctl_tcp_shrink_window) || !tp->rx_opt.rcv_wscale) { 290 /* Never shrink the offered window */ 291 if (new_win == 0) 292 NET_INC_STATS(net, LINUX_MIB_TCPWANTZEROWINDOWADV); 293 new_win = ALIGN(cur_win, 1 << tp->rx_opt.rcv_wscale); 294 } 295 } 296 297 tp->rcv_wnd = new_win; 298 tp->rcv_wup = tp->rcv_nxt; 299 300 /* Make sure we do not exceed the maximum possible 301 * scaled window. 302 */ 303 if (!tp->rx_opt.rcv_wscale && 304 READ_ONCE(net->ipv4.sysctl_tcp_workaround_signed_windows)) 305 new_win = min(new_win, MAX_TCP_WINDOW); 306 else 307 new_win = min(new_win, (65535U << tp->rx_opt.rcv_wscale)); 308 309 /* RFC1323 scaling applied */ 310 new_win >>= tp->rx_opt.rcv_wscale; 311 312 /* If we advertise zero window, disable fast path. */ 313 if (new_win == 0) { 314 tp->pred_flags = 0; 315 if (old_win) 316 NET_INC_STATS(net, LINUX_MIB_TCPTOZEROWINDOWADV); 317 } else if (old_win == 0) { 318 NET_INC_STATS(net, LINUX_MIB_TCPFROMZEROWINDOWADV); 319 } 320 321 return new_win; 322 } 323 324 /* Set up ECN state for a packet on a ESTABLISHED socket that is about to 325 * be sent. 326 */ 327 static void tcp_ecn_send(struct sock *sk, struct sk_buff *skb, 328 struct tcphdr *th, int tcp_header_len) 329 { 330 struct tcp_sock *tp = tcp_sk(sk); 331 332 if (!tcp_ecn_mode_any(tp)) 333 return; 334 335 if (tcp_ecn_mode_accecn(tp)) { 336 if (!tcp_accecn_ace_fail_recv(tp)) 337 INET_ECN_xmit(sk); 338 tcp_accecn_set_ace(tp, skb, th); 339 skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ACCECN; 340 } else { 341 /* Not-retransmitted data segment: set ECT and inject CWR. */ 342 if (skb->len != tcp_header_len && 343 !before(TCP_SKB_CB(skb)->seq, tp->snd_nxt)) { 344 INET_ECN_xmit(sk); 345 if (tp->ecn_flags & TCP_ECN_QUEUE_CWR) { 346 tp->ecn_flags &= ~TCP_ECN_QUEUE_CWR; 347 th->cwr = 1; 348 skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN; 349 } 350 } else if (!tcp_ca_needs_ecn(sk)) { 351 /* ACK or retransmitted segment: clear ECT|CE */ 352 INET_ECN_dontxmit(sk); 353 } 354 if (tp->ecn_flags & TCP_ECN_DEMAND_CWR) 355 th->ece = 1; 356 } 357 } 358 359 /* Constructs common control bits of non-data skb. If SYN/FIN is present, 360 * auto increment end seqno. 361 */ 362 static void tcp_init_nondata_skb(struct sk_buff *skb, struct sock *sk, 363 u32 seq, u16 flags) 364 { 365 skb->ip_summed = CHECKSUM_PARTIAL; 366 367 TCP_SKB_CB(skb)->tcp_flags = flags; 368 369 tcp_skb_pcount_set(skb, 1); 370 psp_enqueue_set_decrypted(sk, skb); 371 372 TCP_SKB_CB(skb)->seq = seq; 373 if (flags & (TCPHDR_SYN | TCPHDR_FIN)) 374 seq++; 375 TCP_SKB_CB(skb)->end_seq = seq; 376 } 377 378 static inline bool tcp_urg_mode(const struct tcp_sock *tp) 379 { 380 return tp->snd_una != tp->snd_up; 381 } 382 383 #define OPTION_SACK_ADVERTISE BIT(0) 384 #define OPTION_TS BIT(1) 385 #define OPTION_MD5 BIT(2) 386 #define OPTION_WSCALE BIT(3) 387 #define OPTION_FAST_OPEN_COOKIE BIT(8) 388 #define OPTION_SMC BIT(9) 389 #define OPTION_MPTCP BIT(10) 390 #define OPTION_AO BIT(11) 391 #define OPTION_ACCECN BIT(12) 392 393 static void smc_options_write(__be32 *ptr, u16 *options) 394 { 395 #if IS_ENABLED(CONFIG_SMC) 396 if (static_branch_unlikely(&tcp_have_smc)) { 397 if (unlikely(OPTION_SMC & *options)) { 398 *ptr++ = htonl((TCPOPT_NOP << 24) | 399 (TCPOPT_NOP << 16) | 400 (TCPOPT_EXP << 8) | 401 (TCPOLEN_EXP_SMC_BASE)); 402 *ptr++ = htonl(TCPOPT_SMC_MAGIC); 403 } 404 } 405 #endif 406 } 407 408 struct tcp_out_options { 409 u16 options; /* bit field of OPTION_* */ 410 u16 mss; /* 0 to disable */ 411 u8 ws; /* window scale, 0 to disable */ 412 u8 num_sack_blocks; /* number of SACK blocks to include */ 413 u8 num_accecn_fields:7, /* number of AccECN fields needed */ 414 use_synack_ecn_bytes:1; /* Use synack_ecn_bytes or not */ 415 u8 hash_size; /* bytes in hash_location */ 416 u8 bpf_opt_len; /* length of BPF hdr option */ 417 __u8 *hash_location; /* temporary pointer, overloaded */ 418 __u32 tsval, tsecr; /* need to include OPTION_TS */ 419 struct tcp_fastopen_cookie *fastopen_cookie; /* Fast open cookie */ 420 struct mptcp_out_options mptcp; 421 }; 422 423 static void mptcp_options_write(struct tcphdr *th, __be32 *ptr, 424 struct tcp_sock *tp, 425 struct tcp_out_options *opts) 426 { 427 #if IS_ENABLED(CONFIG_MPTCP) 428 if (unlikely(OPTION_MPTCP & opts->options)) 429 mptcp_write_options(th, ptr, tp, &opts->mptcp); 430 #endif 431 } 432 433 #ifdef CONFIG_CGROUP_BPF 434 static int bpf_skops_write_hdr_opt_arg0(struct sk_buff *skb, 435 enum tcp_synack_type synack_type) 436 { 437 if (unlikely(!skb)) 438 return BPF_WRITE_HDR_TCP_CURRENT_MSS; 439 440 if (unlikely(synack_type == TCP_SYNACK_COOKIE)) 441 return BPF_WRITE_HDR_TCP_SYNACK_COOKIE; 442 443 return 0; 444 } 445 446 /* req, syn_skb and synack_type are used when writing synack */ 447 static void bpf_skops_hdr_opt_len(struct sock *sk, struct sk_buff *skb, 448 struct request_sock *req, 449 struct sk_buff *syn_skb, 450 enum tcp_synack_type synack_type, 451 struct tcp_out_options *opts, 452 unsigned int *remaining) 453 { 454 struct bpf_sock_ops_kern sock_ops; 455 int err; 456 457 if (likely(!BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk), 458 BPF_SOCK_OPS_WRITE_HDR_OPT_CB_FLAG)) || 459 !*remaining) 460 return; 461 462 /* *remaining has already been aligned to 4 bytes, so *remaining >= 4 */ 463 464 /* init sock_ops */ 465 memset(&sock_ops, 0, offsetof(struct bpf_sock_ops_kern, temp)); 466 467 sock_ops.op = BPF_SOCK_OPS_HDR_OPT_LEN_CB; 468 469 if (req) { 470 /* The listen "sk" cannot be passed here because 471 * it is not locked. It would not make too much 472 * sense to do bpf_setsockopt(listen_sk) based 473 * on individual connection request also. 474 * 475 * Thus, "req" is passed here and the cgroup-bpf-progs 476 * of the listen "sk" will be run. 477 * 478 * "req" is also used here for fastopen even the "sk" here is 479 * a fullsock "child" sk. It is to keep the behavior 480 * consistent between fastopen and non-fastopen on 481 * the bpf programming side. 482 */ 483 sock_ops.sk = (struct sock *)req; 484 sock_ops.syn_skb = syn_skb; 485 } else { 486 sock_owned_by_me(sk); 487 488 sock_ops.is_fullsock = 1; 489 sock_ops.is_locked_tcp_sock = 1; 490 sock_ops.sk = sk; 491 } 492 493 sock_ops.args[0] = bpf_skops_write_hdr_opt_arg0(skb, synack_type); 494 sock_ops.remaining_opt_len = *remaining; 495 /* tcp_current_mss() does not pass a skb */ 496 if (skb) 497 bpf_skops_init_skb(&sock_ops, skb, 0); 498 499 err = BPF_CGROUP_RUN_PROG_SOCK_OPS_SK(&sock_ops, sk); 500 501 if (err || sock_ops.remaining_opt_len == *remaining) 502 return; 503 504 opts->bpf_opt_len = *remaining - sock_ops.remaining_opt_len; 505 /* round up to 4 bytes */ 506 opts->bpf_opt_len = (opts->bpf_opt_len + 3) & ~3; 507 508 *remaining -= opts->bpf_opt_len; 509 } 510 511 static void bpf_skops_write_hdr_opt(struct sock *sk, struct sk_buff *skb, 512 struct request_sock *req, 513 struct sk_buff *syn_skb, 514 enum tcp_synack_type synack_type, 515 struct tcp_out_options *opts) 516 { 517 u8 first_opt_off, nr_written, max_opt_len = opts->bpf_opt_len; 518 struct bpf_sock_ops_kern sock_ops; 519 int err; 520 521 if (likely(!max_opt_len)) 522 return; 523 524 memset(&sock_ops, 0, offsetof(struct bpf_sock_ops_kern, temp)); 525 526 sock_ops.op = BPF_SOCK_OPS_WRITE_HDR_OPT_CB; 527 528 if (req) { 529 sock_ops.sk = (struct sock *)req; 530 sock_ops.syn_skb = syn_skb; 531 } else { 532 sock_owned_by_me(sk); 533 534 sock_ops.is_fullsock = 1; 535 sock_ops.is_locked_tcp_sock = 1; 536 sock_ops.sk = sk; 537 } 538 539 sock_ops.args[0] = bpf_skops_write_hdr_opt_arg0(skb, synack_type); 540 sock_ops.remaining_opt_len = max_opt_len; 541 first_opt_off = tcp_hdrlen(skb) - max_opt_len; 542 bpf_skops_init_skb(&sock_ops, skb, first_opt_off); 543 544 err = BPF_CGROUP_RUN_PROG_SOCK_OPS_SK(&sock_ops, sk); 545 546 if (err) 547 nr_written = 0; 548 else 549 nr_written = max_opt_len - sock_ops.remaining_opt_len; 550 551 if (nr_written < max_opt_len) 552 memset(skb->data + first_opt_off + nr_written, TCPOPT_NOP, 553 max_opt_len - nr_written); 554 } 555 #else 556 static void bpf_skops_hdr_opt_len(struct sock *sk, struct sk_buff *skb, 557 struct request_sock *req, 558 struct sk_buff *syn_skb, 559 enum tcp_synack_type synack_type, 560 struct tcp_out_options *opts, 561 unsigned int *remaining) 562 { 563 } 564 565 static void bpf_skops_write_hdr_opt(struct sock *sk, struct sk_buff *skb, 566 struct request_sock *req, 567 struct sk_buff *syn_skb, 568 enum tcp_synack_type synack_type, 569 struct tcp_out_options *opts) 570 { 571 } 572 #endif 573 574 static __be32 *process_tcp_ao_options(struct tcp_sock *tp, 575 const struct tcp_request_sock *tcprsk, 576 struct tcp_out_options *opts, 577 struct tcp_key *key, __be32 *ptr) 578 { 579 #ifdef CONFIG_TCP_AO 580 u8 maclen = tcp_ao_maclen(key->ao_key); 581 582 if (tcprsk) { 583 u8 aolen = maclen + sizeof(struct tcp_ao_hdr); 584 585 *ptr++ = htonl((TCPOPT_AO << 24) | (aolen << 16) | 586 (tcprsk->ao_keyid << 8) | 587 (tcprsk->ao_rcv_next)); 588 } else { 589 struct tcp_ao_key *rnext_key; 590 struct tcp_ao_info *ao_info; 591 592 ao_info = rcu_dereference_check(tp->ao_info, 593 lockdep_sock_is_held(&tp->inet_conn.icsk_inet.sk)); 594 rnext_key = READ_ONCE(ao_info->rnext_key); 595 if (WARN_ON_ONCE(!rnext_key)) 596 return ptr; 597 *ptr++ = htonl((TCPOPT_AO << 24) | 598 (tcp_ao_len(key->ao_key) << 16) | 599 (key->ao_key->sndid << 8) | 600 (rnext_key->rcvid)); 601 } 602 opts->hash_location = (__u8 *)ptr; 603 ptr += maclen / sizeof(*ptr); 604 if (unlikely(maclen % sizeof(*ptr))) { 605 memset(ptr, TCPOPT_NOP, sizeof(*ptr)); 606 ptr++; 607 } 608 #endif 609 return ptr; 610 } 611 612 /* Initial values for AccECN option, ordered is based on ECN field bits 613 * similar to received_ecn_bytes. Used for SYN/ACK AccECN option. 614 */ 615 static const u32 synack_ecn_bytes[3] = { 0, 0, 0 }; 616 617 /* Write previously computed TCP options to the packet. 618 * 619 * Beware: Something in the Internet is very sensitive to the ordering of 620 * TCP options, we learned this through the hard way, so be careful here. 621 * Luckily we can at least blame others for their non-compliance but from 622 * inter-operability perspective it seems that we're somewhat stuck with 623 * the ordering which we have been using if we want to keep working with 624 * those broken things (not that it currently hurts anybody as there isn't 625 * particular reason why the ordering would need to be changed). 626 * 627 * At least SACK_PERM as the first option is known to lead to a disaster 628 * (but it may well be that other scenarios fail similarly). 629 */ 630 static void tcp_options_write(struct tcphdr *th, struct tcp_sock *tp, 631 const struct tcp_request_sock *tcprsk, 632 struct tcp_out_options *opts, 633 struct tcp_key *key) 634 { 635 u8 leftover_highbyte = TCPOPT_NOP; /* replace 1st NOP if avail */ 636 u8 leftover_lowbyte = TCPOPT_NOP; /* replace 2nd NOP in succession */ 637 __be32 *ptr = (__be32 *)(th + 1); 638 u16 options = opts->options; /* mungable copy */ 639 640 if (tcp_key_is_md5(key)) { 641 *ptr++ = htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | 642 (TCPOPT_MD5SIG << 8) | TCPOLEN_MD5SIG); 643 /* overload cookie hash location */ 644 opts->hash_location = (__u8 *)ptr; 645 ptr += 4; 646 } else if (tcp_key_is_ao(key)) { 647 ptr = process_tcp_ao_options(tp, tcprsk, opts, key, ptr); 648 } 649 if (unlikely(opts->mss)) { 650 *ptr++ = htonl((TCPOPT_MSS << 24) | 651 (TCPOLEN_MSS << 16) | 652 opts->mss); 653 } 654 655 if (likely(OPTION_TS & options)) { 656 if (unlikely(OPTION_SACK_ADVERTISE & options)) { 657 *ptr++ = htonl((TCPOPT_SACK_PERM << 24) | 658 (TCPOLEN_SACK_PERM << 16) | 659 (TCPOPT_TIMESTAMP << 8) | 660 TCPOLEN_TIMESTAMP); 661 options &= ~OPTION_SACK_ADVERTISE; 662 } else { 663 *ptr++ = htonl((TCPOPT_NOP << 24) | 664 (TCPOPT_NOP << 16) | 665 (TCPOPT_TIMESTAMP << 8) | 666 TCPOLEN_TIMESTAMP); 667 } 668 *ptr++ = htonl(opts->tsval); 669 *ptr++ = htonl(opts->tsecr); 670 } 671 672 if (OPTION_ACCECN & options) { 673 const u32 *ecn_bytes = opts->use_synack_ecn_bytes ? 674 synack_ecn_bytes : 675 tp->received_ecn_bytes; 676 const u8 ect0_idx = INET_ECN_ECT_0 - 1; 677 const u8 ect1_idx = INET_ECN_ECT_1 - 1; 678 const u8 ce_idx = INET_ECN_CE - 1; 679 u32 e0b; 680 u32 e1b; 681 u32 ceb; 682 u8 len; 683 684 e0b = ecn_bytes[ect0_idx] + TCP_ACCECN_E0B_INIT_OFFSET; 685 e1b = ecn_bytes[ect1_idx] + TCP_ACCECN_E1B_INIT_OFFSET; 686 ceb = ecn_bytes[ce_idx] + TCP_ACCECN_CEB_INIT_OFFSET; 687 len = TCPOLEN_ACCECN_BASE + 688 opts->num_accecn_fields * TCPOLEN_ACCECN_PERFIELD; 689 690 if (opts->num_accecn_fields == 2) { 691 *ptr++ = htonl((TCPOPT_ACCECN1 << 24) | (len << 16) | 692 ((e1b >> 8) & 0xffff)); 693 *ptr++ = htonl(((e1b & 0xff) << 24) | 694 (ceb & 0xffffff)); 695 } else if (opts->num_accecn_fields == 1) { 696 *ptr++ = htonl((TCPOPT_ACCECN1 << 24) | (len << 16) | 697 ((e1b >> 8) & 0xffff)); 698 leftover_highbyte = e1b & 0xff; 699 leftover_lowbyte = TCPOPT_NOP; 700 } else if (opts->num_accecn_fields == 0) { 701 leftover_highbyte = TCPOPT_ACCECN1; 702 leftover_lowbyte = len; 703 } else if (opts->num_accecn_fields == 3) { 704 *ptr++ = htonl((TCPOPT_ACCECN1 << 24) | (len << 16) | 705 ((e1b >> 8) & 0xffff)); 706 *ptr++ = htonl(((e1b & 0xff) << 24) | 707 (ceb & 0xffffff)); 708 *ptr++ = htonl(((e0b & 0xffffff) << 8) | 709 TCPOPT_NOP); 710 } 711 if (tp) { 712 tp->accecn_minlen = 0; 713 tp->accecn_opt_tstamp = tp->tcp_mstamp; 714 if (tp->accecn_opt_demand) 715 tp->accecn_opt_demand--; 716 } 717 } 718 719 if (unlikely(OPTION_SACK_ADVERTISE & options)) { 720 *ptr++ = htonl((leftover_highbyte << 24) | 721 (leftover_lowbyte << 16) | 722 (TCPOPT_SACK_PERM << 8) | 723 TCPOLEN_SACK_PERM); 724 leftover_highbyte = TCPOPT_NOP; 725 leftover_lowbyte = TCPOPT_NOP; 726 } 727 728 if (unlikely(OPTION_WSCALE & options)) { 729 u8 highbyte = TCPOPT_NOP; 730 731 /* Do not split the leftover 2-byte to fit into a single 732 * NOP, i.e., replace this NOP only when 1 byte is leftover 733 * within leftover_highbyte. 734 */ 735 if (unlikely(leftover_highbyte != TCPOPT_NOP && 736 leftover_lowbyte == TCPOPT_NOP)) { 737 highbyte = leftover_highbyte; 738 leftover_highbyte = TCPOPT_NOP; 739 } 740 *ptr++ = htonl((highbyte << 24) | 741 (TCPOPT_WINDOW << 16) | 742 (TCPOLEN_WINDOW << 8) | 743 opts->ws); 744 } 745 746 if (unlikely(opts->num_sack_blocks)) { 747 struct tcp_sack_block *sp = tp->rx_opt.dsack ? 748 tp->duplicate_sack : tp->selective_acks; 749 int this_sack; 750 751 *ptr++ = htonl((leftover_highbyte << 24) | 752 (leftover_lowbyte << 16) | 753 (TCPOPT_SACK << 8) | 754 (TCPOLEN_SACK_BASE + (opts->num_sack_blocks * 755 TCPOLEN_SACK_PERBLOCK))); 756 leftover_highbyte = TCPOPT_NOP; 757 leftover_lowbyte = TCPOPT_NOP; 758 759 for (this_sack = 0; this_sack < opts->num_sack_blocks; 760 ++this_sack) { 761 *ptr++ = htonl(sp[this_sack].start_seq); 762 *ptr++ = htonl(sp[this_sack].end_seq); 763 } 764 765 tp->rx_opt.dsack = 0; 766 } else if (unlikely(leftover_highbyte != TCPOPT_NOP || 767 leftover_lowbyte != TCPOPT_NOP)) { 768 *ptr++ = htonl((leftover_highbyte << 24) | 769 (leftover_lowbyte << 16) | 770 (TCPOPT_NOP << 8) | 771 TCPOPT_NOP); 772 leftover_highbyte = TCPOPT_NOP; 773 leftover_lowbyte = TCPOPT_NOP; 774 } 775 776 if (unlikely(OPTION_FAST_OPEN_COOKIE & options)) { 777 struct tcp_fastopen_cookie *foc = opts->fastopen_cookie; 778 u8 *p = (u8 *)ptr; 779 u32 len; /* Fast Open option length */ 780 781 if (foc->exp) { 782 len = TCPOLEN_EXP_FASTOPEN_BASE + foc->len; 783 *ptr = htonl((TCPOPT_EXP << 24) | (len << 16) | 784 TCPOPT_FASTOPEN_MAGIC); 785 p += TCPOLEN_EXP_FASTOPEN_BASE; 786 } else { 787 len = TCPOLEN_FASTOPEN_BASE + foc->len; 788 *p++ = TCPOPT_FASTOPEN; 789 *p++ = len; 790 } 791 792 memcpy(p, foc->val, foc->len); 793 if ((len & 3) == 2) { 794 p[foc->len] = TCPOPT_NOP; 795 p[foc->len + 1] = TCPOPT_NOP; 796 } 797 ptr += (len + 3) >> 2; 798 } 799 800 smc_options_write(ptr, &options); 801 802 mptcp_options_write(th, ptr, tp, opts); 803 } 804 805 static void smc_set_option(const struct tcp_sock *tp, 806 struct tcp_out_options *opts, 807 unsigned int *remaining) 808 { 809 #if IS_ENABLED(CONFIG_SMC) 810 if (static_branch_unlikely(&tcp_have_smc)) { 811 if (tp->syn_smc) { 812 if (*remaining >= TCPOLEN_EXP_SMC_BASE_ALIGNED) { 813 opts->options |= OPTION_SMC; 814 *remaining -= TCPOLEN_EXP_SMC_BASE_ALIGNED; 815 } 816 } 817 } 818 #endif 819 } 820 821 static void smc_set_option_cond(const struct tcp_sock *tp, 822 const struct inet_request_sock *ireq, 823 struct tcp_out_options *opts, 824 unsigned int *remaining) 825 { 826 #if IS_ENABLED(CONFIG_SMC) 827 if (static_branch_unlikely(&tcp_have_smc)) { 828 if (tp->syn_smc && ireq->smc_ok) { 829 if (*remaining >= TCPOLEN_EXP_SMC_BASE_ALIGNED) { 830 opts->options |= OPTION_SMC; 831 *remaining -= TCPOLEN_EXP_SMC_BASE_ALIGNED; 832 } 833 } 834 } 835 #endif 836 } 837 838 static void mptcp_set_option_cond(const struct request_sock *req, 839 struct tcp_out_options *opts, 840 unsigned int *remaining) 841 { 842 if (rsk_is_mptcp(req)) { 843 unsigned int size; 844 845 if (mptcp_synack_options(req, &size, &opts->mptcp)) { 846 if (*remaining >= size) { 847 opts->options |= OPTION_MPTCP; 848 *remaining -= size; 849 } 850 } 851 } 852 } 853 854 static u32 tcp_synack_options_combine_saving(struct tcp_out_options *opts) 855 { 856 /* How much there's room for combining with the alignment padding? */ 857 if ((opts->options & (OPTION_SACK_ADVERTISE | OPTION_TS)) == 858 OPTION_SACK_ADVERTISE) 859 return 2; 860 else if (opts->options & OPTION_WSCALE) 861 return 1; 862 return 0; 863 } 864 865 /* Calculates how long AccECN option will fit to @remaining option space. 866 * 867 * AccECN option can sometimes replace NOPs used for alignment of other 868 * TCP options (up to @max_combine_saving available). 869 * 870 * Only solutions with at least @required AccECN fields are accepted. 871 * 872 * Returns: The size of the AccECN option excluding space repurposed from 873 * the alignment of the other options. 874 */ 875 static int tcp_options_fit_accecn(struct tcp_out_options *opts, int required, 876 int remaining) 877 { 878 int size = TCP_ACCECN_MAXSIZE; 879 int sack_blocks_reduce = 0; 880 int max_combine_saving; 881 int rem = remaining; 882 int align_size; 883 884 if (opts->use_synack_ecn_bytes) 885 max_combine_saving = tcp_synack_options_combine_saving(opts); 886 else 887 max_combine_saving = opts->num_sack_blocks > 0 ? 2 : 0; 888 opts->num_accecn_fields = TCP_ACCECN_NUMFIELDS; 889 while (opts->num_accecn_fields >= required) { 890 /* Pad to dword if cannot combine */ 891 if ((size & 0x3) > max_combine_saving) 892 align_size = ALIGN(size, 4); 893 else 894 align_size = ALIGN_DOWN(size, 4); 895 896 if (rem >= align_size) { 897 size = align_size; 898 break; 899 } else if (opts->num_accecn_fields == required && 900 opts->num_sack_blocks > 2 && 901 required > 0) { 902 /* Try to fit the option by removing one SACK block */ 903 opts->num_sack_blocks--; 904 sack_blocks_reduce++; 905 rem = rem + TCPOLEN_SACK_PERBLOCK; 906 907 opts->num_accecn_fields = TCP_ACCECN_NUMFIELDS; 908 size = TCP_ACCECN_MAXSIZE; 909 continue; 910 } 911 912 opts->num_accecn_fields--; 913 size -= TCPOLEN_ACCECN_PERFIELD; 914 } 915 if (sack_blocks_reduce > 0) { 916 if (opts->num_accecn_fields >= required) 917 size -= sack_blocks_reduce * TCPOLEN_SACK_PERBLOCK; 918 else 919 opts->num_sack_blocks += sack_blocks_reduce; 920 } 921 if (opts->num_accecn_fields < required) 922 return 0; 923 924 opts->options |= OPTION_ACCECN; 925 return size; 926 } 927 928 /* Compute TCP options for SYN packets. This is not the final 929 * network wire format yet. 930 */ 931 static unsigned int tcp_syn_options(struct sock *sk, struct sk_buff *skb, 932 struct tcp_out_options *opts, 933 struct tcp_key *key) 934 { 935 struct tcp_sock *tp = tcp_sk(sk); 936 unsigned int remaining = MAX_TCP_OPTION_SPACE; 937 struct tcp_fastopen_request *fastopen = tp->fastopen_req; 938 bool timestamps; 939 940 /* Better than switch (key.type) as it has static branches */ 941 if (tcp_key_is_md5(key)) { 942 timestamps = false; 943 opts->options |= OPTION_MD5; 944 remaining -= TCPOLEN_MD5SIG_ALIGNED; 945 } else { 946 timestamps = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_timestamps); 947 if (tcp_key_is_ao(key)) { 948 opts->options |= OPTION_AO; 949 remaining -= tcp_ao_len_aligned(key->ao_key); 950 } 951 } 952 953 /* We always get an MSS option. The option bytes which will be seen in 954 * normal data packets should timestamps be used, must be in the MSS 955 * advertised. But we subtract them from tp->mss_cache so that 956 * calculations in tcp_sendmsg are simpler etc. So account for this 957 * fact here if necessary. If we don't do this correctly, as a 958 * receiver we won't recognize data packets as being full sized when we 959 * should, and thus we won't abide by the delayed ACK rules correctly. 960 * SACKs don't matter, we never delay an ACK when we have any of those 961 * going out. */ 962 opts->mss = tcp_advertise_mss(sk); 963 remaining -= TCPOLEN_MSS_ALIGNED; 964 965 if (likely(timestamps)) { 966 opts->options |= OPTION_TS; 967 opts->tsval = tcp_skb_timestamp_ts(tp->tcp_usec_ts, skb) + tp->tsoffset; 968 opts->tsecr = tp->rx_opt.ts_recent; 969 remaining -= TCPOLEN_TSTAMP_ALIGNED; 970 } 971 if (likely(READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_window_scaling))) { 972 opts->ws = tp->rx_opt.rcv_wscale; 973 opts->options |= OPTION_WSCALE; 974 remaining -= TCPOLEN_WSCALE_ALIGNED; 975 } 976 if (likely(READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_sack))) { 977 opts->options |= OPTION_SACK_ADVERTISE; 978 if (unlikely(!(OPTION_TS & opts->options))) 979 remaining -= TCPOLEN_SACKPERM_ALIGNED; 980 } 981 982 if (fastopen && fastopen->cookie.len >= 0) { 983 u32 need = fastopen->cookie.len; 984 985 need += fastopen->cookie.exp ? TCPOLEN_EXP_FASTOPEN_BASE : 986 TCPOLEN_FASTOPEN_BASE; 987 need = (need + 3) & ~3U; /* Align to 32 bits */ 988 if (remaining >= need) { 989 opts->options |= OPTION_FAST_OPEN_COOKIE; 990 opts->fastopen_cookie = &fastopen->cookie; 991 remaining -= need; 992 tp->syn_fastopen = 1; 993 tp->syn_fastopen_exp = fastopen->cookie.exp ? 1 : 0; 994 } 995 } 996 997 smc_set_option(tp, opts, &remaining); 998 999 if (sk_is_mptcp(sk)) { 1000 unsigned int size; 1001 1002 if (mptcp_syn_options(sk, skb, &size, &opts->mptcp)) { 1003 if (remaining >= size) { 1004 opts->options |= OPTION_MPTCP; 1005 remaining -= size; 1006 } 1007 } 1008 } 1009 1010 /* Simultaneous open SYN/ACK needs AccECN option but not SYN. 1011 * It is attempted to negotiate the use of AccECN also on the first 1012 * retransmitted SYN, as mentioned in "3.1.4.1. Retransmitted SYNs" 1013 * of AccECN draft. 1014 */ 1015 if (unlikely((TCP_SKB_CB(skb)->tcp_flags & TCPHDR_ACK) && 1016 tcp_ecn_mode_accecn(tp) && 1017 inet_csk(sk)->icsk_retransmits < 2 && 1018 READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_ecn_option) && 1019 remaining >= TCPOLEN_ACCECN_BASE)) { 1020 opts->use_synack_ecn_bytes = 1; 1021 remaining -= tcp_options_fit_accecn(opts, 0, remaining); 1022 } 1023 1024 bpf_skops_hdr_opt_len(sk, skb, NULL, NULL, 0, opts, &remaining); 1025 1026 return MAX_TCP_OPTION_SPACE - remaining; 1027 } 1028 1029 /* Set up TCP options for SYN-ACKs. */ 1030 static unsigned int tcp_synack_options(const struct sock *sk, 1031 struct request_sock *req, 1032 unsigned int mss, struct sk_buff *skb, 1033 struct tcp_out_options *opts, 1034 const struct tcp_key *key, 1035 struct tcp_fastopen_cookie *foc, 1036 enum tcp_synack_type synack_type, 1037 struct sk_buff *syn_skb) 1038 { 1039 struct inet_request_sock *ireq = inet_rsk(req); 1040 unsigned int remaining = MAX_TCP_OPTION_SPACE; 1041 struct tcp_request_sock *treq = tcp_rsk(req); 1042 1043 if (tcp_key_is_md5(key)) { 1044 opts->options |= OPTION_MD5; 1045 remaining -= TCPOLEN_MD5SIG_ALIGNED; 1046 1047 /* We can't fit any SACK blocks in a packet with MD5 + TS 1048 * options. There was discussion about disabling SACK 1049 * rather than TS in order to fit in better with old, 1050 * buggy kernels, but that was deemed to be unnecessary. 1051 */ 1052 if (synack_type != TCP_SYNACK_COOKIE) 1053 ireq->tstamp_ok &= !ireq->sack_ok; 1054 } else if (tcp_key_is_ao(key)) { 1055 opts->options |= OPTION_AO; 1056 remaining -= tcp_ao_len_aligned(key->ao_key); 1057 ireq->tstamp_ok &= !ireq->sack_ok; 1058 } 1059 1060 /* We always send an MSS option. */ 1061 opts->mss = mss; 1062 remaining -= TCPOLEN_MSS_ALIGNED; 1063 1064 if (likely(ireq->wscale_ok)) { 1065 opts->ws = ireq->rcv_wscale; 1066 opts->options |= OPTION_WSCALE; 1067 remaining -= TCPOLEN_WSCALE_ALIGNED; 1068 } 1069 if (likely(ireq->tstamp_ok)) { 1070 opts->options |= OPTION_TS; 1071 opts->tsval = tcp_skb_timestamp_ts(tcp_rsk(req)->req_usec_ts, skb) + 1072 tcp_rsk(req)->ts_off; 1073 if (!tcp_rsk(req)->snt_tsval_first) { 1074 if (!opts->tsval) 1075 opts->tsval = ~0U; 1076 tcp_rsk(req)->snt_tsval_first = opts->tsval; 1077 } 1078 WRITE_ONCE(tcp_rsk(req)->snt_tsval_last, opts->tsval); 1079 opts->tsecr = req->ts_recent; 1080 remaining -= TCPOLEN_TSTAMP_ALIGNED; 1081 } 1082 if (likely(ireq->sack_ok)) { 1083 opts->options |= OPTION_SACK_ADVERTISE; 1084 if (unlikely(!ireq->tstamp_ok)) 1085 remaining -= TCPOLEN_SACKPERM_ALIGNED; 1086 } 1087 if (foc != NULL && foc->len >= 0) { 1088 u32 need = foc->len; 1089 1090 need += foc->exp ? TCPOLEN_EXP_FASTOPEN_BASE : 1091 TCPOLEN_FASTOPEN_BASE; 1092 need = (need + 3) & ~3U; /* Align to 32 bits */ 1093 if (remaining >= need) { 1094 opts->options |= OPTION_FAST_OPEN_COOKIE; 1095 opts->fastopen_cookie = foc; 1096 remaining -= need; 1097 } 1098 } 1099 1100 mptcp_set_option_cond(req, opts, &remaining); 1101 1102 smc_set_option_cond(tcp_sk(sk), ireq, opts, &remaining); 1103 1104 if (treq->accecn_ok && 1105 READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_ecn_option) && 1106 req->num_timeout < 1 && remaining >= TCPOLEN_ACCECN_BASE) { 1107 opts->use_synack_ecn_bytes = 1; 1108 remaining -= tcp_options_fit_accecn(opts, 0, remaining); 1109 } 1110 1111 bpf_skops_hdr_opt_len((struct sock *)sk, skb, req, syn_skb, 1112 synack_type, opts, &remaining); 1113 1114 return MAX_TCP_OPTION_SPACE - remaining; 1115 } 1116 1117 /* Compute TCP options for ESTABLISHED sockets. This is not the 1118 * final wire format yet. 1119 */ 1120 static unsigned int tcp_established_options(struct sock *sk, struct sk_buff *skb, 1121 struct tcp_out_options *opts, 1122 struct tcp_key *key) 1123 { 1124 struct tcp_sock *tp = tcp_sk(sk); 1125 unsigned int size = 0; 1126 unsigned int eff_sacks; 1127 1128 opts->options = 0; 1129 1130 /* Better than switch (key.type) as it has static branches */ 1131 if (tcp_key_is_md5(key)) { 1132 opts->options |= OPTION_MD5; 1133 size += TCPOLEN_MD5SIG_ALIGNED; 1134 } else if (tcp_key_is_ao(key)) { 1135 opts->options |= OPTION_AO; 1136 size += tcp_ao_len_aligned(key->ao_key); 1137 } 1138 1139 if (likely(tp->rx_opt.tstamp_ok)) { 1140 opts->options |= OPTION_TS; 1141 opts->tsval = skb ? tcp_skb_timestamp_ts(tp->tcp_usec_ts, skb) + 1142 tp->tsoffset : 0; 1143 opts->tsecr = tp->rx_opt.ts_recent; 1144 size += TCPOLEN_TSTAMP_ALIGNED; 1145 } 1146 1147 /* MPTCP options have precedence over SACK for the limited TCP 1148 * option space because a MPTCP connection would be forced to 1149 * fall back to regular TCP if a required multipath option is 1150 * missing. SACK still gets a chance to use whatever space is 1151 * left. 1152 */ 1153 if (sk_is_mptcp(sk)) { 1154 unsigned int remaining = MAX_TCP_OPTION_SPACE - size; 1155 unsigned int opt_size = 0; 1156 1157 if (mptcp_established_options(sk, skb, &opt_size, remaining, 1158 &opts->mptcp)) { 1159 opts->options |= OPTION_MPTCP; 1160 size += opt_size; 1161 } 1162 } 1163 1164 eff_sacks = tp->rx_opt.num_sacks + tp->rx_opt.dsack; 1165 if (unlikely(eff_sacks)) { 1166 const unsigned int remaining = MAX_TCP_OPTION_SPACE - size; 1167 if (likely(remaining >= TCPOLEN_SACK_BASE_ALIGNED + 1168 TCPOLEN_SACK_PERBLOCK)) { 1169 opts->num_sack_blocks = 1170 min_t(unsigned int, eff_sacks, 1171 (remaining - TCPOLEN_SACK_BASE_ALIGNED) / 1172 TCPOLEN_SACK_PERBLOCK); 1173 1174 size += TCPOLEN_SACK_BASE_ALIGNED + 1175 opts->num_sack_blocks * TCPOLEN_SACK_PERBLOCK; 1176 } else { 1177 opts->num_sack_blocks = 0; 1178 } 1179 } else { 1180 opts->num_sack_blocks = 0; 1181 } 1182 1183 if (tcp_ecn_mode_accecn(tp)) { 1184 int ecn_opt = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_ecn_option); 1185 1186 if (ecn_opt && tp->saw_accecn_opt && !tcp_accecn_opt_fail_send(tp) && 1187 (ecn_opt >= TCP_ACCECN_OPTION_FULL || tp->accecn_opt_demand || 1188 tcp_accecn_option_beacon_check(sk))) { 1189 opts->use_synack_ecn_bytes = 0; 1190 size += tcp_options_fit_accecn(opts, tp->accecn_minlen, 1191 MAX_TCP_OPTION_SPACE - size); 1192 } 1193 } 1194 1195 if (unlikely(BPF_SOCK_OPS_TEST_FLAG(tp, 1196 BPF_SOCK_OPS_WRITE_HDR_OPT_CB_FLAG))) { 1197 unsigned int remaining = MAX_TCP_OPTION_SPACE - size; 1198 1199 bpf_skops_hdr_opt_len(sk, skb, NULL, NULL, 0, opts, &remaining); 1200 1201 size = MAX_TCP_OPTION_SPACE - remaining; 1202 } 1203 1204 return size; 1205 } 1206 1207 1208 /* TCP SMALL QUEUES (TSQ) 1209 * 1210 * TSQ goal is to keep small amount of skbs per tcp flow in tx queues (qdisc+dev) 1211 * to reduce RTT and bufferbloat. 1212 * We do this using a special skb destructor (tcp_wfree). 1213 * 1214 * Its important tcp_wfree() can be replaced by sock_wfree() in the event skb 1215 * needs to be reallocated in a driver. 1216 * The invariant being skb->truesize subtracted from sk->sk_wmem_alloc 1217 * 1218 * Since transmit from skb destructor is forbidden, we use a BH work item 1219 * to process all sockets that eventually need to send more skbs. 1220 * We use one work item per cpu, with its own queue of sockets. 1221 */ 1222 struct tsq_work { 1223 struct work_struct work; 1224 struct list_head head; /* queue of tcp sockets */ 1225 }; 1226 static DEFINE_PER_CPU(struct tsq_work, tsq_work); 1227 1228 static void tcp_tsq_write(struct sock *sk) 1229 { 1230 if ((1 << sk->sk_state) & 1231 (TCPF_ESTABLISHED | TCPF_FIN_WAIT1 | TCPF_CLOSING | 1232 TCPF_CLOSE_WAIT | TCPF_LAST_ACK)) { 1233 struct tcp_sock *tp = tcp_sk(sk); 1234 1235 if (tp->lost_out > tp->retrans_out && 1236 tcp_snd_cwnd(tp) > tcp_packets_in_flight(tp)) { 1237 tcp_mstamp_refresh(tp); 1238 tcp_xmit_retransmit_queue(sk); 1239 } 1240 1241 tcp_write_xmit(sk, tcp_current_mss(sk), tp->nonagle, 1242 0, GFP_ATOMIC); 1243 } 1244 } 1245 1246 static void tcp_tsq_handler(struct sock *sk) 1247 { 1248 bh_lock_sock(sk); 1249 if (!sock_owned_by_user(sk)) 1250 tcp_tsq_write(sk); 1251 else if (!test_and_set_bit(TCP_TSQ_DEFERRED, &sk->sk_tsq_flags)) 1252 sock_hold(sk); 1253 bh_unlock_sock(sk); 1254 } 1255 /* 1256 * One work item per cpu tries to send more skbs. 1257 * We run in BH context but need to disable irqs when 1258 * transferring tsq->head because tcp_wfree() might 1259 * interrupt us (non NAPI drivers) 1260 */ 1261 static void tcp_tsq_workfn(struct work_struct *work) 1262 { 1263 struct tsq_work *tsq = container_of(work, struct tsq_work, work); 1264 LIST_HEAD(list); 1265 unsigned long flags; 1266 struct list_head *q, *n; 1267 struct tcp_sock *tp; 1268 struct sock *sk; 1269 1270 local_irq_save(flags); 1271 list_splice_init(&tsq->head, &list); 1272 local_irq_restore(flags); 1273 1274 list_for_each_safe(q, n, &list) { 1275 tp = list_entry(q, struct tcp_sock, tsq_node); 1276 list_del(&tp->tsq_node); 1277 1278 sk = (struct sock *)tp; 1279 smp_mb__before_atomic(); 1280 clear_bit(TSQ_QUEUED, &sk->sk_tsq_flags); 1281 1282 tcp_tsq_handler(sk); 1283 sk_free(sk); 1284 } 1285 } 1286 1287 #define TCP_DEFERRED_ALL (TCPF_TSQ_DEFERRED | \ 1288 TCPF_WRITE_TIMER_DEFERRED | \ 1289 TCPF_DELACK_TIMER_DEFERRED | \ 1290 TCPF_MTU_REDUCED_DEFERRED | \ 1291 TCPF_ACK_DEFERRED) 1292 /** 1293 * tcp_release_cb - tcp release_sock() callback 1294 * @sk: socket 1295 * 1296 * called from release_sock() to perform protocol dependent 1297 * actions before socket release. 1298 */ 1299 void tcp_release_cb(struct sock *sk) 1300 { 1301 unsigned long flags = smp_load_acquire(&sk->sk_tsq_flags); 1302 unsigned long nflags; 1303 1304 /* perform an atomic operation only if at least one flag is set */ 1305 do { 1306 if (!(flags & TCP_DEFERRED_ALL)) 1307 return; 1308 nflags = flags & ~TCP_DEFERRED_ALL; 1309 } while (!try_cmpxchg(&sk->sk_tsq_flags, &flags, nflags)); 1310 1311 if (flags & TCPF_TSQ_DEFERRED) { 1312 tcp_tsq_write(sk); 1313 __sock_put(sk); 1314 } 1315 1316 if (flags & TCPF_WRITE_TIMER_DEFERRED) { 1317 tcp_write_timer_handler(sk); 1318 __sock_put(sk); 1319 } 1320 if (flags & TCPF_DELACK_TIMER_DEFERRED) { 1321 tcp_delack_timer_handler(sk); 1322 __sock_put(sk); 1323 } 1324 if (flags & TCPF_MTU_REDUCED_DEFERRED) { 1325 inet_csk(sk)->icsk_af_ops->mtu_reduced(sk); 1326 __sock_put(sk); 1327 } 1328 if ((flags & TCPF_ACK_DEFERRED) && inet_csk_ack_scheduled(sk)) 1329 tcp_send_ack(sk); 1330 } 1331 EXPORT_IPV6_MOD(tcp_release_cb); 1332 1333 void __init tcp_tsq_work_init(void) 1334 { 1335 int i; 1336 1337 for_each_possible_cpu(i) { 1338 struct tsq_work *tsq = &per_cpu(tsq_work, i); 1339 1340 INIT_LIST_HEAD(&tsq->head); 1341 INIT_WORK(&tsq->work, tcp_tsq_workfn); 1342 } 1343 } 1344 1345 /* 1346 * Write buffer destructor automatically called from kfree_skb. 1347 * We can't xmit new skbs from this context, as we might already 1348 * hold qdisc lock. 1349 */ 1350 void tcp_wfree(struct sk_buff *skb) 1351 { 1352 struct sock *sk = skb->sk; 1353 struct tcp_sock *tp = tcp_sk(sk); 1354 unsigned long flags, nval, oval; 1355 struct tsq_work *tsq; 1356 bool empty; 1357 1358 /* Keep one reference on sk_wmem_alloc. 1359 * Will be released by sk_free() from here or tcp_tsq_workfn() 1360 */ 1361 WARN_ON(refcount_sub_and_test(skb->truesize - 1, &sk->sk_wmem_alloc)); 1362 1363 /* If this softirq is serviced by ksoftirqd, we are likely under stress. 1364 * Wait until our queues (qdisc + devices) are drained. 1365 * This gives : 1366 * - less callbacks to tcp_write_xmit(), reducing stress (batches) 1367 * - chance for incoming ACK (processed by another cpu maybe) 1368 * to migrate this flow (skb->ooo_okay will be eventually set) 1369 */ 1370 if (refcount_read(&sk->sk_wmem_alloc) >= SKB_TRUESIZE(1) && this_cpu_ksoftirqd() == current) 1371 goto out; 1372 1373 oval = smp_load_acquire(&sk->sk_tsq_flags); 1374 do { 1375 if (!(oval & TSQF_THROTTLED) || (oval & TSQF_QUEUED)) 1376 goto out; 1377 1378 nval = (oval & ~TSQF_THROTTLED) | TSQF_QUEUED; 1379 } while (!try_cmpxchg(&sk->sk_tsq_flags, &oval, nval)); 1380 1381 /* queue this socket to BH workqueue */ 1382 local_irq_save(flags); 1383 tsq = this_cpu_ptr(&tsq_work); 1384 empty = list_empty(&tsq->head); 1385 list_add(&tp->tsq_node, &tsq->head); 1386 if (empty) 1387 queue_work(system_bh_wq, &tsq->work); 1388 local_irq_restore(flags); 1389 return; 1390 out: 1391 sk_free(sk); 1392 } 1393 1394 /* Note: Called under soft irq. 1395 * We can call TCP stack right away, unless socket is owned by user. 1396 */ 1397 enum hrtimer_restart tcp_pace_kick(struct hrtimer *timer) 1398 { 1399 struct tcp_sock *tp = container_of(timer, struct tcp_sock, pacing_timer); 1400 struct sock *sk = (struct sock *)tp; 1401 1402 tcp_tsq_handler(sk); 1403 sock_put(sk); 1404 1405 return HRTIMER_NORESTART; 1406 } 1407 1408 static void tcp_update_skb_after_send(struct sock *sk, struct sk_buff *skb, 1409 u64 prior_wstamp) 1410 { 1411 struct tcp_sock *tp = tcp_sk(sk); 1412 1413 if (sk->sk_pacing_status != SK_PACING_NONE) { 1414 unsigned long rate = READ_ONCE(sk->sk_pacing_rate); 1415 1416 /* Original sch_fq does not pace first 10 MSS 1417 * Note that tp->data_segs_out overflows after 2^32 packets, 1418 * this is a minor annoyance. 1419 */ 1420 if (rate != ~0UL && rate && tp->data_segs_out >= 10) { 1421 u64 len_ns = div64_ul((u64)skb->len * NSEC_PER_SEC, rate); 1422 u64 credit = tp->tcp_wstamp_ns - prior_wstamp; 1423 1424 /* take into account OS jitter */ 1425 len_ns -= min_t(u64, len_ns / 2, credit); 1426 tp->tcp_wstamp_ns += len_ns; 1427 } 1428 } 1429 list_move_tail(&skb->tcp_tsorted_anchor, &tp->tsorted_sent_queue); 1430 } 1431 1432 INDIRECT_CALLABLE_DECLARE(int ip_queue_xmit(struct sock *sk, struct sk_buff *skb, struct flowi *fl)); 1433 INDIRECT_CALLABLE_DECLARE(int inet6_csk_xmit(struct sock *sk, struct sk_buff *skb, struct flowi *fl)); 1434 INDIRECT_CALLABLE_DECLARE(void tcp_v4_send_check(struct sock *sk, struct sk_buff *skb)); 1435 1436 /* This routine actually transmits TCP packets queued in by 1437 * tcp_do_sendmsg(). This is used by both the initial 1438 * transmission and possible later retransmissions. 1439 * All SKB's seen here are completely headerless. It is our 1440 * job to build the TCP header, and pass the packet down to 1441 * IP so it can do the same plus pass the packet off to the 1442 * device. 1443 * 1444 * We are working here with either a clone of the original 1445 * SKB, or a fresh unique copy made by the retransmit engine. 1446 */ 1447 static int __tcp_transmit_skb(struct sock *sk, struct sk_buff *skb, 1448 int clone_it, gfp_t gfp_mask, u32 rcv_nxt) 1449 { 1450 const struct inet_connection_sock *icsk = inet_csk(sk); 1451 struct inet_sock *inet; 1452 struct tcp_sock *tp; 1453 struct tcp_skb_cb *tcb; 1454 struct tcp_out_options opts; 1455 unsigned int tcp_options_size, tcp_header_size; 1456 struct sk_buff *oskb = NULL; 1457 struct tcp_key key; 1458 struct tcphdr *th; 1459 u64 prior_wstamp; 1460 int err; 1461 1462 BUG_ON(!skb || !tcp_skb_pcount(skb)); 1463 tp = tcp_sk(sk); 1464 prior_wstamp = tp->tcp_wstamp_ns; 1465 tp->tcp_wstamp_ns = max(tp->tcp_wstamp_ns, tp->tcp_clock_cache); 1466 skb_set_delivery_time(skb, tp->tcp_wstamp_ns, SKB_CLOCK_MONOTONIC); 1467 if (clone_it) { 1468 oskb = skb; 1469 1470 tcp_skb_tsorted_save(oskb) { 1471 if (unlikely(skb_cloned(oskb))) 1472 skb = pskb_copy(oskb, gfp_mask); 1473 else 1474 skb = skb_clone(oskb, gfp_mask); 1475 } tcp_skb_tsorted_restore(oskb); 1476 1477 if (unlikely(!skb)) 1478 return -ENOBUFS; 1479 /* retransmit skbs might have a non zero value in skb->dev 1480 * because skb->dev is aliased with skb->rbnode.rb_left 1481 */ 1482 skb->dev = NULL; 1483 } 1484 1485 inet = inet_sk(sk); 1486 tcb = TCP_SKB_CB(skb); 1487 memset(&opts, 0, sizeof(opts)); 1488 1489 tcp_get_current_key(sk, &key); 1490 if (unlikely(tcb->tcp_flags & TCPHDR_SYN)) { 1491 tcp_options_size = tcp_syn_options(sk, skb, &opts, &key); 1492 } else { 1493 tcp_options_size = tcp_established_options(sk, skb, &opts, &key); 1494 /* Force a PSH flag on all (GSO) packets to expedite GRO flush 1495 * at receiver : This slightly improve GRO performance. 1496 * Note that we do not force the PSH flag for non GSO packets, 1497 * because they might be sent under high congestion events, 1498 * and in this case it is better to delay the delivery of 1-MSS 1499 * packets and thus the corresponding ACK packet that would 1500 * release the following packet. 1501 */ 1502 if (tcp_skb_pcount(skb) > 1) 1503 tcb->tcp_flags |= TCPHDR_PSH; 1504 } 1505 tcp_header_size = tcp_options_size + sizeof(struct tcphdr); 1506 1507 /* We set skb->ooo_okay to one if this packet can select 1508 * a different TX queue than prior packets of this flow, 1509 * to avoid self inflicted reorders. 1510 * The 'other' queue decision is based on current cpu number 1511 * if XPS is enabled, or sk->sk_txhash otherwise. 1512 * We can switch to another (and better) queue if: 1513 * 1) No packet with payload is in qdisc/device queues. 1514 * Delays in TX completion can defeat the test 1515 * even if packets were already sent. 1516 * 2) Or rtx queue is empty. 1517 * This mitigates above case if ACK packets for 1518 * all prior packets were already processed. 1519 */ 1520 skb->ooo_okay = sk_wmem_alloc_get(sk) < SKB_TRUESIZE(1) || 1521 tcp_rtx_queue_empty(sk); 1522 1523 /* If we had to use memory reserve to allocate this skb, 1524 * this might cause drops if packet is looped back : 1525 * Other socket might not have SOCK_MEMALLOC. 1526 * Packets not looped back do not care about pfmemalloc. 1527 */ 1528 skb->pfmemalloc = 0; 1529 1530 skb_push(skb, tcp_header_size); 1531 skb_reset_transport_header(skb); 1532 1533 skb_orphan(skb); 1534 skb->sk = sk; 1535 skb->destructor = skb_is_tcp_pure_ack(skb) ? __sock_wfree : tcp_wfree; 1536 refcount_add(skb->truesize, &sk->sk_wmem_alloc); 1537 1538 skb_set_dst_pending_confirm(skb, READ_ONCE(sk->sk_dst_pending_confirm)); 1539 1540 /* Build TCP header and checksum it. */ 1541 th = (struct tcphdr *)skb->data; 1542 th->source = inet->inet_sport; 1543 th->dest = inet->inet_dport; 1544 th->seq = htonl(tcb->seq); 1545 th->ack_seq = htonl(rcv_nxt); 1546 *(((__be16 *)th) + 6) = htons(((tcp_header_size >> 2) << 12) | 1547 (tcb->tcp_flags & TCPHDR_FLAGS_MASK)); 1548 1549 th->check = 0; 1550 th->urg_ptr = 0; 1551 1552 /* The urg_mode check is necessary during a below snd_una win probe */ 1553 if (unlikely(tcp_urg_mode(tp) && before(tcb->seq, tp->snd_up))) { 1554 if (before(tp->snd_up, tcb->seq + 0x10000)) { 1555 th->urg_ptr = htons(tp->snd_up - tcb->seq); 1556 th->urg = 1; 1557 } else if (after(tcb->seq + 0xFFFF, tp->snd_nxt)) { 1558 th->urg_ptr = htons(0xFFFF); 1559 th->urg = 1; 1560 } 1561 } 1562 1563 skb_shinfo(skb)->gso_type = sk->sk_gso_type; 1564 if (likely(!(tcb->tcp_flags & TCPHDR_SYN))) { 1565 th->window = htons(tcp_select_window(sk)); 1566 tcp_ecn_send(sk, skb, th, tcp_header_size); 1567 } else { 1568 /* RFC1323: The window in SYN & SYN/ACK segments 1569 * is never scaled. 1570 */ 1571 th->window = htons(min(tp->rcv_wnd, 65535U)); 1572 } 1573 1574 tcp_options_write(th, tp, NULL, &opts, &key); 1575 1576 if (tcp_key_is_md5(&key)) { 1577 #ifdef CONFIG_TCP_MD5SIG 1578 /* Calculate the MD5 hash, as we have all we need now */ 1579 sk_gso_disable(sk); 1580 tp->af_specific->calc_md5_hash(opts.hash_location, 1581 key.md5_key, sk, skb); 1582 #endif 1583 } else if (tcp_key_is_ao(&key)) { 1584 int err; 1585 1586 err = tcp_ao_transmit_skb(sk, skb, key.ao_key, th, 1587 opts.hash_location); 1588 if (err) { 1589 sk_skb_reason_drop(sk, skb, SKB_DROP_REASON_NOT_SPECIFIED); 1590 return -ENOMEM; 1591 } 1592 } 1593 1594 /* BPF prog is the last one writing header option */ 1595 bpf_skops_write_hdr_opt(sk, skb, NULL, NULL, 0, &opts); 1596 1597 INDIRECT_CALL_INET(icsk->icsk_af_ops->send_check, 1598 tcp_v6_send_check, tcp_v4_send_check, 1599 sk, skb); 1600 1601 if (likely(tcb->tcp_flags & TCPHDR_ACK)) 1602 tcp_event_ack_sent(sk, rcv_nxt); 1603 1604 if (skb->len != tcp_header_size) { 1605 tcp_event_data_sent(tp, sk); 1606 tp->data_segs_out += tcp_skb_pcount(skb); 1607 tp->bytes_sent += skb->len - tcp_header_size; 1608 } 1609 1610 if (after(tcb->end_seq, tp->snd_nxt) || tcb->seq == tcb->end_seq) 1611 TCP_ADD_STATS(sock_net(sk), TCP_MIB_OUTSEGS, 1612 tcp_skb_pcount(skb)); 1613 1614 tp->segs_out += tcp_skb_pcount(skb); 1615 skb_set_hash_from_sk(skb, sk); 1616 /* OK, its time to fill skb_shinfo(skb)->gso_{segs|size} */ 1617 skb_shinfo(skb)->gso_segs = tcp_skb_pcount(skb); 1618 skb_shinfo(skb)->gso_size = tcp_skb_mss(skb); 1619 1620 /* Leave earliest departure time in skb->tstamp (skb->skb_mstamp_ns) */ 1621 1622 /* Cleanup our debris for IP stacks */ 1623 memset(skb->cb, 0, max(sizeof(struct inet_skb_parm), 1624 sizeof(struct inet6_skb_parm))); 1625 1626 tcp_add_tx_delay(skb, tp); 1627 1628 err = INDIRECT_CALL_INET(icsk->icsk_af_ops->queue_xmit, 1629 inet6_csk_xmit, ip_queue_xmit, 1630 sk, skb, &inet->cork.fl); 1631 1632 if (unlikely(err > 0)) { 1633 tcp_enter_cwr(sk); 1634 err = net_xmit_eval(err); 1635 } 1636 if (!err && oskb) { 1637 tcp_update_skb_after_send(sk, oskb, prior_wstamp); 1638 tcp_rate_skb_sent(sk, oskb); 1639 } 1640 return err; 1641 } 1642 1643 static int tcp_transmit_skb(struct sock *sk, struct sk_buff *skb, int clone_it, 1644 gfp_t gfp_mask) 1645 { 1646 return __tcp_transmit_skb(sk, skb, clone_it, gfp_mask, 1647 tcp_sk(sk)->rcv_nxt); 1648 } 1649 1650 /* This routine just queues the buffer for sending. 1651 * 1652 * NOTE: probe0 timer is not checked, do not forget tcp_push_pending_frames, 1653 * otherwise socket can stall. 1654 */ 1655 static void tcp_queue_skb(struct sock *sk, struct sk_buff *skb) 1656 { 1657 struct tcp_sock *tp = tcp_sk(sk); 1658 1659 /* Advance write_seq and place onto the write_queue. */ 1660 WRITE_ONCE(tp->write_seq, TCP_SKB_CB(skb)->end_seq); 1661 __skb_header_release(skb); 1662 psp_enqueue_set_decrypted(sk, skb); 1663 tcp_add_write_queue_tail(sk, skb); 1664 sk_wmem_queued_add(sk, skb->truesize); 1665 sk_mem_charge(sk, skb->truesize); 1666 } 1667 1668 /* Initialize TSO segments for a packet. */ 1669 static int tcp_set_skb_tso_segs(struct sk_buff *skb, unsigned int mss_now) 1670 { 1671 int tso_segs; 1672 1673 if (skb->len <= mss_now) { 1674 /* Avoid the costly divide in the normal 1675 * non-TSO case. 1676 */ 1677 TCP_SKB_CB(skb)->tcp_gso_size = 0; 1678 tcp_skb_pcount_set(skb, 1); 1679 return 1; 1680 } 1681 TCP_SKB_CB(skb)->tcp_gso_size = mss_now; 1682 tso_segs = DIV_ROUND_UP(skb->len, mss_now); 1683 tcp_skb_pcount_set(skb, tso_segs); 1684 return tso_segs; 1685 } 1686 1687 /* Pcount in the middle of the write queue got changed, we need to do various 1688 * tweaks to fix counters 1689 */ 1690 static void tcp_adjust_pcount(struct sock *sk, const struct sk_buff *skb, int decr) 1691 { 1692 struct tcp_sock *tp = tcp_sk(sk); 1693 1694 tp->packets_out -= decr; 1695 1696 if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED) 1697 tp->sacked_out -= decr; 1698 if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS) 1699 tp->retrans_out -= decr; 1700 if (TCP_SKB_CB(skb)->sacked & TCPCB_LOST) 1701 tp->lost_out -= decr; 1702 1703 /* Reno case is special. Sigh... */ 1704 if (tcp_is_reno(tp) && decr > 0) 1705 tp->sacked_out -= min_t(u32, tp->sacked_out, decr); 1706 1707 tcp_verify_left_out(tp); 1708 } 1709 1710 static bool tcp_has_tx_tstamp(const struct sk_buff *skb) 1711 { 1712 return TCP_SKB_CB(skb)->txstamp_ack || 1713 (skb_shinfo(skb)->tx_flags & SKBTX_ANY_TSTAMP); 1714 } 1715 1716 static void tcp_fragment_tstamp(struct sk_buff *skb, struct sk_buff *skb2) 1717 { 1718 struct skb_shared_info *shinfo = skb_shinfo(skb); 1719 1720 if (unlikely(tcp_has_tx_tstamp(skb)) && 1721 !before(shinfo->tskey, TCP_SKB_CB(skb2)->seq)) { 1722 struct skb_shared_info *shinfo2 = skb_shinfo(skb2); 1723 u8 tsflags = shinfo->tx_flags & SKBTX_ANY_TSTAMP; 1724 1725 shinfo->tx_flags &= ~tsflags; 1726 shinfo2->tx_flags |= tsflags; 1727 swap(shinfo->tskey, shinfo2->tskey); 1728 TCP_SKB_CB(skb2)->txstamp_ack = TCP_SKB_CB(skb)->txstamp_ack; 1729 TCP_SKB_CB(skb)->txstamp_ack = 0; 1730 } 1731 } 1732 1733 static void tcp_skb_fragment_eor(struct sk_buff *skb, struct sk_buff *skb2) 1734 { 1735 TCP_SKB_CB(skb2)->eor = TCP_SKB_CB(skb)->eor; 1736 TCP_SKB_CB(skb)->eor = 0; 1737 } 1738 1739 /* Insert buff after skb on the write or rtx queue of sk. */ 1740 static void tcp_insert_write_queue_after(struct sk_buff *skb, 1741 struct sk_buff *buff, 1742 struct sock *sk, 1743 enum tcp_queue tcp_queue) 1744 { 1745 if (tcp_queue == TCP_FRAG_IN_WRITE_QUEUE) 1746 __skb_queue_after(&sk->sk_write_queue, skb, buff); 1747 else 1748 tcp_rbtree_insert(&sk->tcp_rtx_queue, buff); 1749 } 1750 1751 /* Function to create two new TCP segments. Shrinks the given segment 1752 * to the specified size and appends a new segment with the rest of the 1753 * packet to the list. This won't be called frequently, I hope. 1754 * Remember, these are still headerless SKBs at this point. 1755 */ 1756 int tcp_fragment(struct sock *sk, enum tcp_queue tcp_queue, 1757 struct sk_buff *skb, u32 len, 1758 unsigned int mss_now, gfp_t gfp) 1759 { 1760 struct tcp_sock *tp = tcp_sk(sk); 1761 struct sk_buff *buff; 1762 int old_factor; 1763 long limit; 1764 u16 flags; 1765 int nlen; 1766 1767 if (WARN_ON(len > skb->len)) 1768 return -EINVAL; 1769 1770 DEBUG_NET_WARN_ON_ONCE(skb_headlen(skb)); 1771 1772 /* tcp_sendmsg() can overshoot sk_wmem_queued by one full size skb. 1773 * We need some allowance to not penalize applications setting small 1774 * SO_SNDBUF values. 1775 * Also allow first and last skb in retransmit queue to be split. 1776 */ 1777 limit = sk->sk_sndbuf + 2 * SKB_TRUESIZE(GSO_LEGACY_MAX_SIZE); 1778 if (unlikely((sk->sk_wmem_queued >> 1) > limit && 1779 tcp_queue != TCP_FRAG_IN_WRITE_QUEUE && 1780 skb != tcp_rtx_queue_head(sk) && 1781 skb != tcp_rtx_queue_tail(sk))) { 1782 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPWQUEUETOOBIG); 1783 return -ENOMEM; 1784 } 1785 1786 if (skb_unclone_keeptruesize(skb, gfp)) 1787 return -ENOMEM; 1788 1789 /* Get a new skb... force flag on. */ 1790 buff = tcp_stream_alloc_skb(sk, gfp, true); 1791 if (!buff) 1792 return -ENOMEM; /* We'll just try again later. */ 1793 skb_copy_decrypted(buff, skb); 1794 mptcp_skb_ext_copy(buff, skb); 1795 1796 sk_wmem_queued_add(sk, buff->truesize); 1797 sk_mem_charge(sk, buff->truesize); 1798 nlen = skb->len - len; 1799 buff->truesize += nlen; 1800 skb->truesize -= nlen; 1801 1802 /* Correct the sequence numbers. */ 1803 TCP_SKB_CB(buff)->seq = TCP_SKB_CB(skb)->seq + len; 1804 TCP_SKB_CB(buff)->end_seq = TCP_SKB_CB(skb)->end_seq; 1805 TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(buff)->seq; 1806 1807 /* PSH and FIN should only be set in the second packet. */ 1808 flags = TCP_SKB_CB(skb)->tcp_flags; 1809 TCP_SKB_CB(skb)->tcp_flags = flags & ~(TCPHDR_FIN | TCPHDR_PSH); 1810 TCP_SKB_CB(buff)->tcp_flags = flags; 1811 TCP_SKB_CB(buff)->sacked = TCP_SKB_CB(skb)->sacked; 1812 tcp_skb_fragment_eor(skb, buff); 1813 1814 skb_split(skb, buff, len); 1815 1816 skb_set_delivery_time(buff, skb->tstamp, SKB_CLOCK_MONOTONIC); 1817 tcp_fragment_tstamp(skb, buff); 1818 1819 old_factor = tcp_skb_pcount(skb); 1820 1821 /* Fix up tso_factor for both original and new SKB. */ 1822 tcp_set_skb_tso_segs(skb, mss_now); 1823 tcp_set_skb_tso_segs(buff, mss_now); 1824 1825 /* Update delivered info for the new segment */ 1826 TCP_SKB_CB(buff)->tx = TCP_SKB_CB(skb)->tx; 1827 1828 /* If this packet has been sent out already, we must 1829 * adjust the various packet counters. 1830 */ 1831 if (!before(tp->snd_nxt, TCP_SKB_CB(buff)->end_seq)) { 1832 int diff = old_factor - tcp_skb_pcount(skb) - 1833 tcp_skb_pcount(buff); 1834 1835 if (diff) 1836 tcp_adjust_pcount(sk, skb, diff); 1837 } 1838 1839 /* Link BUFF into the send queue. */ 1840 __skb_header_release(buff); 1841 tcp_insert_write_queue_after(skb, buff, sk, tcp_queue); 1842 if (tcp_queue == TCP_FRAG_IN_RTX_QUEUE) 1843 list_add(&buff->tcp_tsorted_anchor, &skb->tcp_tsorted_anchor); 1844 1845 return 0; 1846 } 1847 1848 /* This is similar to __pskb_pull_tail(). The difference is that pulled 1849 * data is not copied, but immediately discarded. 1850 */ 1851 static int __pskb_trim_head(struct sk_buff *skb, int len) 1852 { 1853 struct skb_shared_info *shinfo; 1854 int i, k, eat; 1855 1856 DEBUG_NET_WARN_ON_ONCE(skb_headlen(skb)); 1857 eat = len; 1858 k = 0; 1859 shinfo = skb_shinfo(skb); 1860 for (i = 0; i < shinfo->nr_frags; i++) { 1861 int size = skb_frag_size(&shinfo->frags[i]); 1862 1863 if (size <= eat) { 1864 skb_frag_unref(skb, i); 1865 eat -= size; 1866 } else { 1867 shinfo->frags[k] = shinfo->frags[i]; 1868 if (eat) { 1869 skb_frag_off_add(&shinfo->frags[k], eat); 1870 skb_frag_size_sub(&shinfo->frags[k], eat); 1871 eat = 0; 1872 } 1873 k++; 1874 } 1875 } 1876 shinfo->nr_frags = k; 1877 1878 skb->data_len -= len; 1879 skb->len = skb->data_len; 1880 return len; 1881 } 1882 1883 /* Remove acked data from a packet in the transmit queue. */ 1884 int tcp_trim_head(struct sock *sk, struct sk_buff *skb, u32 len) 1885 { 1886 u32 delta_truesize; 1887 1888 if (skb_unclone_keeptruesize(skb, GFP_ATOMIC)) 1889 return -ENOMEM; 1890 1891 delta_truesize = __pskb_trim_head(skb, len); 1892 1893 TCP_SKB_CB(skb)->seq += len; 1894 1895 skb->truesize -= delta_truesize; 1896 sk_wmem_queued_add(sk, -delta_truesize); 1897 if (!skb_zcopy_pure(skb)) 1898 sk_mem_uncharge(sk, delta_truesize); 1899 1900 /* Any change of skb->len requires recalculation of tso factor. */ 1901 if (tcp_skb_pcount(skb) > 1) 1902 tcp_set_skb_tso_segs(skb, tcp_skb_mss(skb)); 1903 1904 return 0; 1905 } 1906 1907 /* Calculate MSS not accounting any TCP options. */ 1908 static inline int __tcp_mtu_to_mss(struct sock *sk, int pmtu) 1909 { 1910 const struct tcp_sock *tp = tcp_sk(sk); 1911 const struct inet_connection_sock *icsk = inet_csk(sk); 1912 int mss_now; 1913 1914 /* Calculate base mss without TCP options: 1915 It is MMS_S - sizeof(tcphdr) of rfc1122 1916 */ 1917 mss_now = pmtu - icsk->icsk_af_ops->net_header_len - sizeof(struct tcphdr); 1918 1919 /* Clamp it (mss_clamp does not include tcp options) */ 1920 if (mss_now > tp->rx_opt.mss_clamp) 1921 mss_now = tp->rx_opt.mss_clamp; 1922 1923 /* Now subtract optional transport overhead */ 1924 mss_now -= icsk->icsk_ext_hdr_len; 1925 1926 /* Then reserve room for full set of TCP options and 8 bytes of data */ 1927 mss_now = max(mss_now, 1928 READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_min_snd_mss)); 1929 return mss_now; 1930 } 1931 1932 /* Calculate MSS. Not accounting for SACKs here. */ 1933 int tcp_mtu_to_mss(struct sock *sk, int pmtu) 1934 { 1935 /* Subtract TCP options size, not including SACKs */ 1936 return __tcp_mtu_to_mss(sk, pmtu) - 1937 (tcp_sk(sk)->tcp_header_len - sizeof(struct tcphdr)); 1938 } 1939 EXPORT_IPV6_MOD(tcp_mtu_to_mss); 1940 1941 /* Inverse of above */ 1942 int tcp_mss_to_mtu(struct sock *sk, int mss) 1943 { 1944 const struct tcp_sock *tp = tcp_sk(sk); 1945 const struct inet_connection_sock *icsk = inet_csk(sk); 1946 1947 return mss + 1948 tp->tcp_header_len + 1949 icsk->icsk_ext_hdr_len + 1950 icsk->icsk_af_ops->net_header_len; 1951 } 1952 EXPORT_SYMBOL(tcp_mss_to_mtu); 1953 1954 /* MTU probing init per socket */ 1955 void tcp_mtup_init(struct sock *sk) 1956 { 1957 struct tcp_sock *tp = tcp_sk(sk); 1958 struct inet_connection_sock *icsk = inet_csk(sk); 1959 struct net *net = sock_net(sk); 1960 1961 icsk->icsk_mtup.enabled = READ_ONCE(net->ipv4.sysctl_tcp_mtu_probing) > 1; 1962 icsk->icsk_mtup.search_high = tp->rx_opt.mss_clamp + sizeof(struct tcphdr) + 1963 icsk->icsk_af_ops->net_header_len; 1964 icsk->icsk_mtup.search_low = tcp_mss_to_mtu(sk, READ_ONCE(net->ipv4.sysctl_tcp_base_mss)); 1965 icsk->icsk_mtup.probe_size = 0; 1966 if (icsk->icsk_mtup.enabled) 1967 icsk->icsk_mtup.probe_timestamp = tcp_jiffies32; 1968 } 1969 1970 /* This function synchronize snd mss to current pmtu/exthdr set. 1971 1972 tp->rx_opt.user_mss is mss set by user by TCP_MAXSEG. It does NOT counts 1973 for TCP options, but includes only bare TCP header. 1974 1975 tp->rx_opt.mss_clamp is mss negotiated at connection setup. 1976 It is minimum of user_mss and mss received with SYN. 1977 It also does not include TCP options. 1978 1979 inet_csk(sk)->icsk_pmtu_cookie is last pmtu, seen by this function. 1980 1981 tp->mss_cache is current effective sending mss, including 1982 all tcp options except for SACKs. It is evaluated, 1983 taking into account current pmtu, but never exceeds 1984 tp->rx_opt.mss_clamp. 1985 1986 NOTE1. rfc1122 clearly states that advertised MSS 1987 DOES NOT include either tcp or ip options. 1988 1989 NOTE2. inet_csk(sk)->icsk_pmtu_cookie and tp->mss_cache 1990 are READ ONLY outside this function. --ANK (980731) 1991 */ 1992 unsigned int tcp_sync_mss(struct sock *sk, u32 pmtu) 1993 { 1994 struct tcp_sock *tp = tcp_sk(sk); 1995 struct inet_connection_sock *icsk = inet_csk(sk); 1996 int mss_now; 1997 1998 if (icsk->icsk_mtup.search_high > pmtu) 1999 icsk->icsk_mtup.search_high = pmtu; 2000 2001 mss_now = tcp_mtu_to_mss(sk, pmtu); 2002 mss_now = tcp_bound_to_half_wnd(tp, mss_now); 2003 2004 /* And store cached results */ 2005 icsk->icsk_pmtu_cookie = pmtu; 2006 if (icsk->icsk_mtup.enabled) 2007 mss_now = min(mss_now, tcp_mtu_to_mss(sk, icsk->icsk_mtup.search_low)); 2008 tp->mss_cache = mss_now; 2009 2010 return mss_now; 2011 } 2012 EXPORT_IPV6_MOD(tcp_sync_mss); 2013 2014 /* Compute the current effective MSS, taking SACKs and IP options, 2015 * and even PMTU discovery events into account. 2016 */ 2017 unsigned int tcp_current_mss(struct sock *sk) 2018 { 2019 const struct tcp_sock *tp = tcp_sk(sk); 2020 const struct dst_entry *dst = __sk_dst_get(sk); 2021 u32 mss_now; 2022 unsigned int header_len; 2023 struct tcp_out_options opts; 2024 struct tcp_key key; 2025 2026 mss_now = tp->mss_cache; 2027 2028 if (dst) { 2029 u32 mtu = dst_mtu(dst); 2030 if (mtu != inet_csk(sk)->icsk_pmtu_cookie) 2031 mss_now = tcp_sync_mss(sk, mtu); 2032 } 2033 tcp_get_current_key(sk, &key); 2034 header_len = tcp_established_options(sk, NULL, &opts, &key) + 2035 sizeof(struct tcphdr); 2036 /* The mss_cache is sized based on tp->tcp_header_len, which assumes 2037 * some common options. If this is an odd packet (because we have SACK 2038 * blocks etc) then our calculated header_len will be different, and 2039 * we have to adjust mss_now correspondingly */ 2040 if (header_len != tp->tcp_header_len) { 2041 int delta = (int) header_len - tp->tcp_header_len; 2042 mss_now -= delta; 2043 } 2044 2045 return mss_now; 2046 } 2047 2048 /* RFC2861, slow part. Adjust cwnd, after it was not full during one rto. 2049 * As additional protections, we do not touch cwnd in retransmission phases, 2050 * and if application hit its sndbuf limit recently. 2051 */ 2052 static void tcp_cwnd_application_limited(struct sock *sk) 2053 { 2054 struct tcp_sock *tp = tcp_sk(sk); 2055 2056 if (inet_csk(sk)->icsk_ca_state == TCP_CA_Open && 2057 sk->sk_socket && !test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) { 2058 /* Limited by application or receiver window. */ 2059 u32 init_win = tcp_init_cwnd(tp, __sk_dst_get(sk)); 2060 u32 win_used = max(tp->snd_cwnd_used, init_win); 2061 if (win_used < tcp_snd_cwnd(tp)) { 2062 tp->snd_ssthresh = tcp_current_ssthresh(sk); 2063 tcp_snd_cwnd_set(tp, (tcp_snd_cwnd(tp) + win_used) >> 1); 2064 } 2065 tp->snd_cwnd_used = 0; 2066 } 2067 tp->snd_cwnd_stamp = tcp_jiffies32; 2068 } 2069 2070 static void tcp_cwnd_validate(struct sock *sk, bool is_cwnd_limited) 2071 { 2072 const struct tcp_congestion_ops *ca_ops = inet_csk(sk)->icsk_ca_ops; 2073 struct tcp_sock *tp = tcp_sk(sk); 2074 2075 /* Track the strongest available signal of the degree to which the cwnd 2076 * is fully utilized. If cwnd-limited then remember that fact for the 2077 * current window. If not cwnd-limited then track the maximum number of 2078 * outstanding packets in the current window. (If cwnd-limited then we 2079 * chose to not update tp->max_packets_out to avoid an extra else 2080 * clause with no functional impact.) 2081 */ 2082 if (!before(tp->snd_una, tp->cwnd_usage_seq) || 2083 is_cwnd_limited || 2084 (!tp->is_cwnd_limited && 2085 tp->packets_out > tp->max_packets_out)) { 2086 tp->is_cwnd_limited = is_cwnd_limited; 2087 tp->max_packets_out = tp->packets_out; 2088 tp->cwnd_usage_seq = tp->snd_nxt; 2089 } 2090 2091 if (tcp_is_cwnd_limited(sk)) { 2092 /* Network is feed fully. */ 2093 tp->snd_cwnd_used = 0; 2094 tp->snd_cwnd_stamp = tcp_jiffies32; 2095 } else { 2096 /* Network starves. */ 2097 if (tp->packets_out > tp->snd_cwnd_used) 2098 tp->snd_cwnd_used = tp->packets_out; 2099 2100 if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_slow_start_after_idle) && 2101 (s32)(tcp_jiffies32 - tp->snd_cwnd_stamp) >= inet_csk(sk)->icsk_rto && 2102 !ca_ops->cong_control) 2103 tcp_cwnd_application_limited(sk); 2104 2105 /* The following conditions together indicate the starvation 2106 * is caused by insufficient sender buffer: 2107 * 1) just sent some data (see tcp_write_xmit) 2108 * 2) not cwnd limited (this else condition) 2109 * 3) no more data to send (tcp_write_queue_empty()) 2110 * 4) application is hitting buffer limit (SOCK_NOSPACE) 2111 */ 2112 if (tcp_write_queue_empty(sk) && sk->sk_socket && 2113 test_bit(SOCK_NOSPACE, &sk->sk_socket->flags) && 2114 (1 << sk->sk_state) & (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) 2115 tcp_chrono_start(sk, TCP_CHRONO_SNDBUF_LIMITED); 2116 } 2117 } 2118 2119 /* Minshall's variant of the Nagle send check. */ 2120 static bool tcp_minshall_check(const struct tcp_sock *tp) 2121 { 2122 return after(tp->snd_sml, tp->snd_una) && 2123 !after(tp->snd_sml, tp->snd_nxt); 2124 } 2125 2126 /* Update snd_sml if this skb is under mss 2127 * Note that a TSO packet might end with a sub-mss segment 2128 * The test is really : 2129 * if ((skb->len % mss) != 0) 2130 * tp->snd_sml = TCP_SKB_CB(skb)->end_seq; 2131 * But we can avoid doing the divide again given we already have 2132 * skb_pcount = skb->len / mss_now 2133 */ 2134 static void tcp_minshall_update(struct tcp_sock *tp, unsigned int mss_now, 2135 const struct sk_buff *skb) 2136 { 2137 if (skb->len < tcp_skb_pcount(skb) * mss_now) 2138 tp->snd_sml = TCP_SKB_CB(skb)->end_seq; 2139 } 2140 2141 /* Return false, if packet can be sent now without violation Nagle's rules: 2142 * 1. It is full sized. (provided by caller in %partial bool) 2143 * 2. Or it contains FIN. (already checked by caller) 2144 * 3. Or TCP_CORK is not set, and TCP_NODELAY is set. 2145 * 4. Or TCP_CORK is not set, and all sent packets are ACKed. 2146 * With Minshall's modification: all sent small packets are ACKed. 2147 */ 2148 static bool tcp_nagle_check(bool partial, const struct tcp_sock *tp, 2149 int nonagle) 2150 { 2151 return partial && 2152 ((nonagle & TCP_NAGLE_CORK) || 2153 (!nonagle && tp->packets_out && tcp_minshall_check(tp))); 2154 } 2155 2156 /* Return how many segs we'd like on a TSO packet, 2157 * depending on current pacing rate, and how close the peer is. 2158 * 2159 * Rationale is: 2160 * - For close peers, we rather send bigger packets to reduce 2161 * cpu costs, because occasional losses will be repaired fast. 2162 * - For long distance/rtt flows, we would like to get ACK clocking 2163 * with 1 ACK per ms. 2164 * 2165 * Use min_rtt to help adapt TSO burst size, with smaller min_rtt resulting 2166 * in bigger TSO bursts. We we cut the RTT-based allowance in half 2167 * for every 2^9 usec (aka 512 us) of RTT, so that the RTT-based allowance 2168 * is below 1500 bytes after 6 * ~500 usec = 3ms. 2169 */ 2170 static u32 tcp_tso_autosize(const struct sock *sk, unsigned int mss_now, 2171 int min_tso_segs) 2172 { 2173 unsigned long bytes; 2174 u32 r; 2175 2176 bytes = READ_ONCE(sk->sk_pacing_rate) >> READ_ONCE(sk->sk_pacing_shift); 2177 2178 r = tcp_min_rtt(tcp_sk(sk)) >> READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_tso_rtt_log); 2179 if (r < BITS_PER_TYPE(sk->sk_gso_max_size)) 2180 bytes += sk->sk_gso_max_size >> r; 2181 2182 bytes = min_t(unsigned long, bytes, sk->sk_gso_max_size); 2183 2184 return max_t(u32, bytes / mss_now, min_tso_segs); 2185 } 2186 2187 /* Return the number of segments we want in the skb we are transmitting. 2188 * See if congestion control module wants to decide; otherwise, autosize. 2189 */ 2190 static u32 tcp_tso_segs(struct sock *sk, unsigned int mss_now) 2191 { 2192 const struct tcp_congestion_ops *ca_ops = inet_csk(sk)->icsk_ca_ops; 2193 u32 min_tso, tso_segs; 2194 2195 min_tso = ca_ops->min_tso_segs ? 2196 ca_ops->min_tso_segs(sk) : 2197 READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_min_tso_segs); 2198 2199 tso_segs = tcp_tso_autosize(sk, mss_now, min_tso); 2200 return min_t(u32, tso_segs, sk->sk_gso_max_segs); 2201 } 2202 2203 /* Returns the portion of skb which can be sent right away */ 2204 static unsigned int tcp_mss_split_point(const struct sock *sk, 2205 const struct sk_buff *skb, 2206 unsigned int mss_now, 2207 unsigned int max_segs, 2208 int nonagle) 2209 { 2210 const struct tcp_sock *tp = tcp_sk(sk); 2211 u32 partial, needed, window, max_len; 2212 2213 window = tcp_wnd_end(tp) - TCP_SKB_CB(skb)->seq; 2214 max_len = mss_now * max_segs; 2215 2216 if (likely(max_len <= window && skb != tcp_write_queue_tail(sk))) 2217 return max_len; 2218 2219 needed = min(skb->len, window); 2220 2221 if (max_len <= needed) 2222 return max_len; 2223 2224 partial = needed % mss_now; 2225 /* If last segment is not a full MSS, check if Nagle rules allow us 2226 * to include this last segment in this skb. 2227 * Otherwise, we'll split the skb at last MSS boundary 2228 */ 2229 if (tcp_nagle_check(partial != 0, tp, nonagle)) 2230 return needed - partial; 2231 2232 return needed; 2233 } 2234 2235 /* Can at least one segment of SKB be sent right now, according to the 2236 * congestion window rules? If so, return how many segments are allowed. 2237 */ 2238 static u32 tcp_cwnd_test(const struct tcp_sock *tp) 2239 { 2240 u32 in_flight, cwnd, halfcwnd; 2241 2242 in_flight = tcp_packets_in_flight(tp); 2243 cwnd = tcp_snd_cwnd(tp); 2244 if (in_flight >= cwnd) 2245 return 0; 2246 2247 /* For better scheduling, ensure we have at least 2248 * 2 GSO packets in flight. 2249 */ 2250 halfcwnd = max(cwnd >> 1, 1U); 2251 return min(halfcwnd, cwnd - in_flight); 2252 } 2253 2254 /* Initialize TSO state of a skb. 2255 * This must be invoked the first time we consider transmitting 2256 * SKB onto the wire. 2257 */ 2258 static int tcp_init_tso_segs(struct sk_buff *skb, unsigned int mss_now) 2259 { 2260 int tso_segs = tcp_skb_pcount(skb); 2261 2262 if (!tso_segs || (tso_segs > 1 && tcp_skb_mss(skb) != mss_now)) 2263 return tcp_set_skb_tso_segs(skb, mss_now); 2264 2265 return tso_segs; 2266 } 2267 2268 2269 /* Return true if the Nagle test allows this packet to be 2270 * sent now. 2271 */ 2272 static inline bool tcp_nagle_test(const struct tcp_sock *tp, const struct sk_buff *skb, 2273 unsigned int cur_mss, int nonagle) 2274 { 2275 /* Nagle rule does not apply to frames, which sit in the middle of the 2276 * write_queue (they have no chances to get new data). 2277 * 2278 * This is implemented in the callers, where they modify the 'nonagle' 2279 * argument based upon the location of SKB in the send queue. 2280 */ 2281 if (nonagle & TCP_NAGLE_PUSH) 2282 return true; 2283 2284 /* Don't use the nagle rule for urgent data (or for the final FIN). */ 2285 if (tcp_urg_mode(tp) || (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)) 2286 return true; 2287 2288 if (!tcp_nagle_check(skb->len < cur_mss, tp, nonagle)) 2289 return true; 2290 2291 return false; 2292 } 2293 2294 /* Does at least the first segment of SKB fit into the send window? */ 2295 static bool tcp_snd_wnd_test(const struct tcp_sock *tp, 2296 const struct sk_buff *skb, 2297 unsigned int cur_mss) 2298 { 2299 u32 end_seq = TCP_SKB_CB(skb)->end_seq; 2300 2301 if (skb->len > cur_mss) 2302 end_seq = TCP_SKB_CB(skb)->seq + cur_mss; 2303 2304 return !after(end_seq, tcp_wnd_end(tp)); 2305 } 2306 2307 /* Trim TSO SKB to LEN bytes, put the remaining data into a new packet 2308 * which is put after SKB on the list. It is very much like 2309 * tcp_fragment() except that it may make several kinds of assumptions 2310 * in order to speed up the splitting operation. In particular, we 2311 * know that all the data is in scatter-gather pages, and that the 2312 * packet has never been sent out before (and thus is not cloned). 2313 */ 2314 static int tso_fragment(struct sock *sk, struct sk_buff *skb, unsigned int len, 2315 unsigned int mss_now, gfp_t gfp) 2316 { 2317 int nlen = skb->len - len; 2318 struct sk_buff *buff; 2319 u16 flags; 2320 2321 /* All of a TSO frame must be composed of paged data. */ 2322 DEBUG_NET_WARN_ON_ONCE(skb->len != skb->data_len); 2323 2324 buff = tcp_stream_alloc_skb(sk, gfp, true); 2325 if (unlikely(!buff)) 2326 return -ENOMEM; 2327 skb_copy_decrypted(buff, skb); 2328 mptcp_skb_ext_copy(buff, skb); 2329 2330 sk_wmem_queued_add(sk, buff->truesize); 2331 sk_mem_charge(sk, buff->truesize); 2332 buff->truesize += nlen; 2333 skb->truesize -= nlen; 2334 2335 /* Correct the sequence numbers. */ 2336 TCP_SKB_CB(buff)->seq = TCP_SKB_CB(skb)->seq + len; 2337 TCP_SKB_CB(buff)->end_seq = TCP_SKB_CB(skb)->end_seq; 2338 TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(buff)->seq; 2339 2340 /* PSH and FIN should only be set in the second packet. */ 2341 flags = TCP_SKB_CB(skb)->tcp_flags; 2342 TCP_SKB_CB(skb)->tcp_flags = flags & ~(TCPHDR_FIN | TCPHDR_PSH); 2343 TCP_SKB_CB(buff)->tcp_flags = flags; 2344 2345 tcp_skb_fragment_eor(skb, buff); 2346 2347 skb_split(skb, buff, len); 2348 tcp_fragment_tstamp(skb, buff); 2349 2350 /* Fix up tso_factor for both original and new SKB. */ 2351 tcp_set_skb_tso_segs(skb, mss_now); 2352 tcp_set_skb_tso_segs(buff, mss_now); 2353 2354 /* Link BUFF into the send queue. */ 2355 __skb_header_release(buff); 2356 tcp_insert_write_queue_after(skb, buff, sk, TCP_FRAG_IN_WRITE_QUEUE); 2357 2358 return 0; 2359 } 2360 2361 /* Try to defer sending, if possible, in order to minimize the amount 2362 * of TSO splitting we do. View it as a kind of TSO Nagle test. 2363 * 2364 * This algorithm is from John Heffner. 2365 */ 2366 static bool tcp_tso_should_defer(struct sock *sk, struct sk_buff *skb, 2367 bool *is_cwnd_limited, 2368 bool *is_rwnd_limited, 2369 u32 max_segs) 2370 { 2371 const struct inet_connection_sock *icsk = inet_csk(sk); 2372 u32 send_win, cong_win, limit, in_flight, threshold; 2373 u64 srtt_in_ns, expected_ack, how_far_is_the_ack; 2374 struct tcp_sock *tp = tcp_sk(sk); 2375 struct sk_buff *head; 2376 int win_divisor; 2377 s64 delta; 2378 2379 if (icsk->icsk_ca_state >= TCP_CA_Recovery) 2380 goto send_now; 2381 2382 /* Avoid bursty behavior by allowing defer 2383 * only if the last write was recent (1 ms). 2384 * Note that tp->tcp_wstamp_ns can be in the future if we have 2385 * packets waiting in a qdisc or device for EDT delivery. 2386 */ 2387 delta = tp->tcp_clock_cache - tp->tcp_wstamp_ns - NSEC_PER_MSEC; 2388 if (delta > 0) 2389 goto send_now; 2390 2391 in_flight = tcp_packets_in_flight(tp); 2392 2393 BUG_ON(tcp_skb_pcount(skb) <= 1); 2394 BUG_ON(tcp_snd_cwnd(tp) <= in_flight); 2395 2396 send_win = tcp_wnd_end(tp) - TCP_SKB_CB(skb)->seq; 2397 2398 /* From in_flight test above, we know that cwnd > in_flight. */ 2399 cong_win = (tcp_snd_cwnd(tp) - in_flight) * tp->mss_cache; 2400 2401 limit = min(send_win, cong_win); 2402 2403 /* If a full-sized TSO skb can be sent, do it. */ 2404 if (limit >= max_segs * tp->mss_cache) 2405 goto send_now; 2406 2407 /* Middle in queue won't get any more data, full sendable already? */ 2408 if ((skb != tcp_write_queue_tail(sk)) && (limit >= skb->len)) 2409 goto send_now; 2410 2411 win_divisor = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_tso_win_divisor); 2412 if (win_divisor) { 2413 u32 chunk = min(tp->snd_wnd, tcp_snd_cwnd(tp) * tp->mss_cache); 2414 2415 /* If at least some fraction of a window is available, 2416 * just use it. 2417 */ 2418 chunk /= win_divisor; 2419 if (limit >= chunk) 2420 goto send_now; 2421 } else { 2422 /* Different approach, try not to defer past a single 2423 * ACK. Receiver should ACK every other full sized 2424 * frame, so if we have space for more than 3 frames 2425 * then send now. 2426 */ 2427 if (limit > tcp_max_tso_deferred_mss(tp) * tp->mss_cache) 2428 goto send_now; 2429 } 2430 2431 /* TODO : use tsorted_sent_queue ? */ 2432 head = tcp_rtx_queue_head(sk); 2433 if (!head) 2434 goto send_now; 2435 2436 srtt_in_ns = (u64)(NSEC_PER_USEC >> 3) * tp->srtt_us; 2437 /* When is the ACK expected ? */ 2438 expected_ack = head->tstamp + srtt_in_ns; 2439 /* How far from now is the ACK expected ? */ 2440 how_far_is_the_ack = expected_ack - tp->tcp_clock_cache; 2441 2442 /* If next ACK is likely to come too late, 2443 * ie in more than min(1ms, half srtt), do not defer. 2444 */ 2445 threshold = min(srtt_in_ns >> 1, NSEC_PER_MSEC); 2446 2447 if ((s64)(how_far_is_the_ack - threshold) > 0) 2448 goto send_now; 2449 2450 /* Ok, it looks like it is advisable to defer. 2451 * Three cases are tracked : 2452 * 1) We are cwnd-limited 2453 * 2) We are rwnd-limited 2454 * 3) We are application limited. 2455 */ 2456 if (cong_win < send_win) { 2457 if (cong_win <= skb->len) { 2458 *is_cwnd_limited = true; 2459 return true; 2460 } 2461 } else { 2462 if (send_win <= skb->len) { 2463 *is_rwnd_limited = true; 2464 return true; 2465 } 2466 } 2467 2468 /* If this packet won't get more data, do not wait. */ 2469 if ((TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) || 2470 TCP_SKB_CB(skb)->eor) 2471 goto send_now; 2472 2473 return true; 2474 2475 send_now: 2476 return false; 2477 } 2478 2479 static inline void tcp_mtu_check_reprobe(struct sock *sk) 2480 { 2481 struct inet_connection_sock *icsk = inet_csk(sk); 2482 struct tcp_sock *tp = tcp_sk(sk); 2483 struct net *net = sock_net(sk); 2484 u32 interval; 2485 s32 delta; 2486 2487 interval = READ_ONCE(net->ipv4.sysctl_tcp_probe_interval); 2488 delta = tcp_jiffies32 - icsk->icsk_mtup.probe_timestamp; 2489 if (unlikely(delta >= interval * HZ)) { 2490 int mss = tcp_current_mss(sk); 2491 2492 /* Update current search range */ 2493 icsk->icsk_mtup.probe_size = 0; 2494 icsk->icsk_mtup.search_high = tp->rx_opt.mss_clamp + 2495 sizeof(struct tcphdr) + 2496 icsk->icsk_af_ops->net_header_len; 2497 icsk->icsk_mtup.search_low = tcp_mss_to_mtu(sk, mss); 2498 2499 /* Update probe time stamp */ 2500 icsk->icsk_mtup.probe_timestamp = tcp_jiffies32; 2501 } 2502 } 2503 2504 static bool tcp_can_coalesce_send_queue_head(struct sock *sk, int len) 2505 { 2506 struct sk_buff *skb, *next; 2507 2508 skb = tcp_send_head(sk); 2509 tcp_for_write_queue_from_safe(skb, next, sk) { 2510 if (len <= skb->len) 2511 break; 2512 2513 if (tcp_has_tx_tstamp(skb) || !tcp_skb_can_collapse(skb, next)) 2514 return false; 2515 2516 len -= skb->len; 2517 } 2518 2519 return true; 2520 } 2521 2522 static int tcp_clone_payload(struct sock *sk, struct sk_buff *to, 2523 int probe_size) 2524 { 2525 skb_frag_t *lastfrag = NULL, *fragto = skb_shinfo(to)->frags; 2526 int i, todo, len = 0, nr_frags = 0; 2527 const struct sk_buff *skb; 2528 2529 if (!sk_wmem_schedule(sk, to->truesize + probe_size)) 2530 return -ENOMEM; 2531 2532 skb_queue_walk(&sk->sk_write_queue, skb) { 2533 const skb_frag_t *fragfrom = skb_shinfo(skb)->frags; 2534 2535 if (skb_headlen(skb)) 2536 return -EINVAL; 2537 2538 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++, fragfrom++) { 2539 if (len >= probe_size) 2540 goto commit; 2541 todo = min_t(int, skb_frag_size(fragfrom), 2542 probe_size - len); 2543 len += todo; 2544 if (lastfrag && 2545 skb_frag_page(fragfrom) == skb_frag_page(lastfrag) && 2546 skb_frag_off(fragfrom) == skb_frag_off(lastfrag) + 2547 skb_frag_size(lastfrag)) { 2548 skb_frag_size_add(lastfrag, todo); 2549 continue; 2550 } 2551 if (unlikely(nr_frags == MAX_SKB_FRAGS)) 2552 return -E2BIG; 2553 skb_frag_page_copy(fragto, fragfrom); 2554 skb_frag_off_copy(fragto, fragfrom); 2555 skb_frag_size_set(fragto, todo); 2556 nr_frags++; 2557 lastfrag = fragto++; 2558 } 2559 } 2560 commit: 2561 WARN_ON_ONCE(len != probe_size); 2562 for (i = 0; i < nr_frags; i++) 2563 skb_frag_ref(to, i); 2564 2565 skb_shinfo(to)->nr_frags = nr_frags; 2566 to->truesize += probe_size; 2567 to->len += probe_size; 2568 to->data_len += probe_size; 2569 __skb_header_release(to); 2570 return 0; 2571 } 2572 2573 /* tcp_mtu_probe() and tcp_grow_skb() can both eat an skb (src) if 2574 * all its payload was moved to another one (dst). 2575 * Make sure to transfer tcp_flags, eor, and tstamp. 2576 */ 2577 static void tcp_eat_one_skb(struct sock *sk, 2578 struct sk_buff *dst, 2579 struct sk_buff *src) 2580 { 2581 TCP_SKB_CB(dst)->tcp_flags |= TCP_SKB_CB(src)->tcp_flags; 2582 TCP_SKB_CB(dst)->eor = TCP_SKB_CB(src)->eor; 2583 tcp_skb_collapse_tstamp(dst, src); 2584 tcp_unlink_write_queue(src, sk); 2585 tcp_wmem_free_skb(sk, src); 2586 } 2587 2588 /* Create a new MTU probe if we are ready. 2589 * MTU probe is regularly attempting to increase the path MTU by 2590 * deliberately sending larger packets. This discovers routing 2591 * changes resulting in larger path MTUs. 2592 * 2593 * Returns 0 if we should wait to probe (no cwnd available), 2594 * 1 if a probe was sent, 2595 * -1 otherwise 2596 */ 2597 static int tcp_mtu_probe(struct sock *sk) 2598 { 2599 struct inet_connection_sock *icsk = inet_csk(sk); 2600 struct tcp_sock *tp = tcp_sk(sk); 2601 struct sk_buff *skb, *nskb, *next; 2602 struct net *net = sock_net(sk); 2603 int probe_size; 2604 int size_needed; 2605 int copy, len; 2606 int mss_now; 2607 int interval; 2608 2609 /* Not currently probing/verifying, 2610 * not in recovery, 2611 * have enough cwnd, and 2612 * not SACKing (the variable headers throw things off) 2613 */ 2614 if (likely(!icsk->icsk_mtup.enabled || 2615 icsk->icsk_mtup.probe_size || 2616 inet_csk(sk)->icsk_ca_state != TCP_CA_Open || 2617 tcp_snd_cwnd(tp) < 11 || 2618 tp->rx_opt.num_sacks || tp->rx_opt.dsack)) 2619 return -1; 2620 2621 /* Use binary search for probe_size between tcp_mss_base, 2622 * and current mss_clamp. if (search_high - search_low) 2623 * smaller than a threshold, backoff from probing. 2624 */ 2625 mss_now = tcp_current_mss(sk); 2626 probe_size = tcp_mtu_to_mss(sk, (icsk->icsk_mtup.search_high + 2627 icsk->icsk_mtup.search_low) >> 1); 2628 size_needed = probe_size + (tp->reordering + 1) * tp->mss_cache; 2629 interval = icsk->icsk_mtup.search_high - icsk->icsk_mtup.search_low; 2630 /* When misfortune happens, we are reprobing actively, 2631 * and then reprobe timer has expired. We stick with current 2632 * probing process by not resetting search range to its orignal. 2633 */ 2634 if (probe_size > tcp_mtu_to_mss(sk, icsk->icsk_mtup.search_high) || 2635 interval < READ_ONCE(net->ipv4.sysctl_tcp_probe_threshold)) { 2636 /* Check whether enough time has elaplased for 2637 * another round of probing. 2638 */ 2639 tcp_mtu_check_reprobe(sk); 2640 return -1; 2641 } 2642 2643 /* Have enough data in the send queue to probe? */ 2644 if (tp->write_seq - tp->snd_nxt < size_needed) 2645 return -1; 2646 2647 if (tp->snd_wnd < size_needed) 2648 return -1; 2649 if (after(tp->snd_nxt + size_needed, tcp_wnd_end(tp))) 2650 return 0; 2651 2652 /* Do we need to wait to drain cwnd? With none in flight, don't stall */ 2653 if (tcp_packets_in_flight(tp) + 2 > tcp_snd_cwnd(tp)) { 2654 if (!tcp_packets_in_flight(tp)) 2655 return -1; 2656 else 2657 return 0; 2658 } 2659 2660 if (!tcp_can_coalesce_send_queue_head(sk, probe_size)) 2661 return -1; 2662 2663 /* We're allowed to probe. Build it now. */ 2664 nskb = tcp_stream_alloc_skb(sk, GFP_ATOMIC, false); 2665 if (!nskb) 2666 return -1; 2667 2668 /* build the payload, and be prepared to abort if this fails. */ 2669 if (tcp_clone_payload(sk, nskb, probe_size)) { 2670 tcp_skb_tsorted_anchor_cleanup(nskb); 2671 consume_skb(nskb); 2672 return -1; 2673 } 2674 sk_wmem_queued_add(sk, nskb->truesize); 2675 sk_mem_charge(sk, nskb->truesize); 2676 2677 skb = tcp_send_head(sk); 2678 skb_copy_decrypted(nskb, skb); 2679 mptcp_skb_ext_copy(nskb, skb); 2680 2681 TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(skb)->seq; 2682 TCP_SKB_CB(nskb)->end_seq = TCP_SKB_CB(skb)->seq + probe_size; 2683 TCP_SKB_CB(nskb)->tcp_flags = TCPHDR_ACK; 2684 2685 tcp_insert_write_queue_before(nskb, skb, sk); 2686 tcp_highest_sack_replace(sk, skb, nskb); 2687 2688 len = 0; 2689 tcp_for_write_queue_from_safe(skb, next, sk) { 2690 copy = min_t(int, skb->len, probe_size - len); 2691 2692 if (skb->len <= copy) { 2693 tcp_eat_one_skb(sk, nskb, skb); 2694 } else { 2695 TCP_SKB_CB(nskb)->tcp_flags |= TCP_SKB_CB(skb)->tcp_flags & 2696 ~(TCPHDR_FIN|TCPHDR_PSH); 2697 __pskb_trim_head(skb, copy); 2698 tcp_set_skb_tso_segs(skb, mss_now); 2699 TCP_SKB_CB(skb)->seq += copy; 2700 } 2701 2702 len += copy; 2703 2704 if (len >= probe_size) 2705 break; 2706 } 2707 tcp_init_tso_segs(nskb, nskb->len); 2708 2709 /* We're ready to send. If this fails, the probe will 2710 * be resegmented into mss-sized pieces by tcp_write_xmit(). 2711 */ 2712 if (!tcp_transmit_skb(sk, nskb, 1, GFP_ATOMIC)) { 2713 /* Decrement cwnd here because we are sending 2714 * effectively two packets. */ 2715 tcp_snd_cwnd_set(tp, tcp_snd_cwnd(tp) - 1); 2716 tcp_event_new_data_sent(sk, nskb); 2717 2718 icsk->icsk_mtup.probe_size = tcp_mss_to_mtu(sk, nskb->len); 2719 tp->mtu_probe.probe_seq_start = TCP_SKB_CB(nskb)->seq; 2720 tp->mtu_probe.probe_seq_end = TCP_SKB_CB(nskb)->end_seq; 2721 2722 return 1; 2723 } 2724 2725 return -1; 2726 } 2727 2728 static bool tcp_pacing_check(struct sock *sk) 2729 { 2730 struct tcp_sock *tp = tcp_sk(sk); 2731 2732 if (!tcp_needs_internal_pacing(sk)) 2733 return false; 2734 2735 if (tp->tcp_wstamp_ns <= tp->tcp_clock_cache) 2736 return false; 2737 2738 if (!hrtimer_is_queued(&tp->pacing_timer)) { 2739 hrtimer_start(&tp->pacing_timer, 2740 ns_to_ktime(tp->tcp_wstamp_ns), 2741 HRTIMER_MODE_ABS_PINNED_SOFT); 2742 sock_hold(sk); 2743 } 2744 return true; 2745 } 2746 2747 static bool tcp_rtx_queue_empty_or_single_skb(const struct sock *sk) 2748 { 2749 const struct rb_node *node = sk->tcp_rtx_queue.rb_node; 2750 2751 /* No skb in the rtx queue. */ 2752 if (!node) 2753 return true; 2754 2755 /* Only one skb in rtx queue. */ 2756 return !node->rb_left && !node->rb_right; 2757 } 2758 2759 /* TCP Small Queues : 2760 * Control number of packets in qdisc/devices to two packets / or ~1 ms. 2761 * (These limits are doubled for retransmits) 2762 * This allows for : 2763 * - better RTT estimation and ACK scheduling 2764 * - faster recovery 2765 * - high rates 2766 * Alas, some drivers / subsystems require a fair amount 2767 * of queued bytes to ensure line rate. 2768 * One example is wifi aggregation (802.11 AMPDU) 2769 */ 2770 static bool tcp_small_queue_check(struct sock *sk, const struct sk_buff *skb, 2771 unsigned int factor) 2772 { 2773 unsigned long limit; 2774 2775 limit = max_t(unsigned long, 2776 2 * skb->truesize, 2777 READ_ONCE(sk->sk_pacing_rate) >> READ_ONCE(sk->sk_pacing_shift)); 2778 limit = min_t(unsigned long, limit, 2779 READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_limit_output_bytes)); 2780 limit <<= factor; 2781 2782 if (static_branch_unlikely(&tcp_tx_delay_enabled) && 2783 tcp_sk(sk)->tcp_tx_delay) { 2784 u64 extra_bytes = (u64)READ_ONCE(sk->sk_pacing_rate) * 2785 tcp_sk(sk)->tcp_tx_delay; 2786 2787 /* TSQ is based on skb truesize sum (sk_wmem_alloc), so we 2788 * approximate our needs assuming an ~100% skb->truesize overhead. 2789 * USEC_PER_SEC is approximated by 2^20. 2790 * do_div(extra_bytes, USEC_PER_SEC/2) is replaced by a right shift. 2791 */ 2792 extra_bytes >>= (20 - 1); 2793 limit += extra_bytes; 2794 } 2795 if (refcount_read(&sk->sk_wmem_alloc) > limit) { 2796 /* Always send skb if rtx queue is empty or has one skb. 2797 * No need to wait for TX completion to call us back, 2798 * after softirq schedule. 2799 * This helps when TX completions are delayed too much. 2800 */ 2801 if (tcp_rtx_queue_empty_or_single_skb(sk)) 2802 return false; 2803 2804 set_bit(TSQ_THROTTLED, &sk->sk_tsq_flags); 2805 /* It is possible TX completion already happened 2806 * before we set TSQ_THROTTLED, so we must 2807 * test again the condition. 2808 */ 2809 smp_mb__after_atomic(); 2810 if (refcount_read(&sk->sk_wmem_alloc) > limit) 2811 return true; 2812 } 2813 return false; 2814 } 2815 2816 static void tcp_chrono_set(struct tcp_sock *tp, const enum tcp_chrono new) 2817 { 2818 const u32 now = tcp_jiffies32; 2819 enum tcp_chrono old = tp->chrono_type; 2820 2821 if (old > TCP_CHRONO_UNSPEC) 2822 tp->chrono_stat[old - 1] += now - tp->chrono_start; 2823 tp->chrono_start = now; 2824 tp->chrono_type = new; 2825 } 2826 2827 void tcp_chrono_start(struct sock *sk, const enum tcp_chrono type) 2828 { 2829 struct tcp_sock *tp = tcp_sk(sk); 2830 2831 /* If there are multiple conditions worthy of tracking in a 2832 * chronograph then the highest priority enum takes precedence 2833 * over the other conditions. So that if something "more interesting" 2834 * starts happening, stop the previous chrono and start a new one. 2835 */ 2836 if (type > tp->chrono_type) 2837 tcp_chrono_set(tp, type); 2838 } 2839 2840 void tcp_chrono_stop(struct sock *sk, const enum tcp_chrono type) 2841 { 2842 struct tcp_sock *tp = tcp_sk(sk); 2843 2844 2845 /* There are multiple conditions worthy of tracking in a 2846 * chronograph, so that the highest priority enum takes 2847 * precedence over the other conditions (see tcp_chrono_start). 2848 * If a condition stops, we only stop chrono tracking if 2849 * it's the "most interesting" or current chrono we are 2850 * tracking and starts busy chrono if we have pending data. 2851 */ 2852 if (tcp_rtx_and_write_queues_empty(sk)) 2853 tcp_chrono_set(tp, TCP_CHRONO_UNSPEC); 2854 else if (type == tp->chrono_type) 2855 tcp_chrono_set(tp, TCP_CHRONO_BUSY); 2856 } 2857 2858 /* First skb in the write queue is smaller than ideal packet size. 2859 * Check if we can move payload from the second skb in the queue. 2860 */ 2861 static void tcp_grow_skb(struct sock *sk, struct sk_buff *skb, int amount) 2862 { 2863 struct sk_buff *next_skb = skb->next; 2864 unsigned int nlen; 2865 2866 if (tcp_skb_is_last(sk, skb)) 2867 return; 2868 2869 if (!tcp_skb_can_collapse(skb, next_skb)) 2870 return; 2871 2872 nlen = min_t(u32, amount, next_skb->len); 2873 if (!nlen || !skb_shift(skb, next_skb, nlen)) 2874 return; 2875 2876 TCP_SKB_CB(skb)->end_seq += nlen; 2877 TCP_SKB_CB(next_skb)->seq += nlen; 2878 2879 if (!next_skb->len) { 2880 /* In case FIN is set, we need to update end_seq */ 2881 TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(next_skb)->end_seq; 2882 2883 tcp_eat_one_skb(sk, skb, next_skb); 2884 } 2885 } 2886 2887 /* This routine writes packets to the network. It advances the 2888 * send_head. This happens as incoming acks open up the remote 2889 * window for us. 2890 * 2891 * LARGESEND note: !tcp_urg_mode is overkill, only frames between 2892 * snd_up-64k-mss .. snd_up cannot be large. However, taking into 2893 * account rare use of URG, this is not a big flaw. 2894 * 2895 * Send at most one packet when push_one > 0. Temporarily ignore 2896 * cwnd limit to force at most one packet out when push_one == 2. 2897 2898 * Returns true, if no segments are in flight and we have queued segments, 2899 * but cannot send anything now because of SWS or another problem. 2900 */ 2901 static bool tcp_write_xmit(struct sock *sk, unsigned int mss_now, int nonagle, 2902 int push_one, gfp_t gfp) 2903 { 2904 struct tcp_sock *tp = tcp_sk(sk); 2905 struct sk_buff *skb; 2906 unsigned int tso_segs, sent_pkts; 2907 u32 cwnd_quota, max_segs; 2908 int result; 2909 bool is_cwnd_limited = false, is_rwnd_limited = false; 2910 2911 sent_pkts = 0; 2912 2913 tcp_mstamp_refresh(tp); 2914 2915 /* AccECN option beacon depends on mstamp, it may change mss */ 2916 if (tcp_ecn_mode_accecn(tp) && tcp_accecn_option_beacon_check(sk)) 2917 mss_now = tcp_current_mss(sk); 2918 2919 if (!push_one) { 2920 /* Do MTU probing. */ 2921 result = tcp_mtu_probe(sk); 2922 if (!result) { 2923 return false; 2924 } else if (result > 0) { 2925 sent_pkts = 1; 2926 } 2927 } 2928 2929 max_segs = tcp_tso_segs(sk, mss_now); 2930 while ((skb = tcp_send_head(sk))) { 2931 unsigned int limit; 2932 int missing_bytes; 2933 2934 if (unlikely(tp->repair) && tp->repair_queue == TCP_SEND_QUEUE) { 2935 /* "skb_mstamp_ns" is used as a start point for the retransmit timer */ 2936 tp->tcp_wstamp_ns = tp->tcp_clock_cache; 2937 skb_set_delivery_time(skb, tp->tcp_wstamp_ns, SKB_CLOCK_MONOTONIC); 2938 list_move_tail(&skb->tcp_tsorted_anchor, &tp->tsorted_sent_queue); 2939 tcp_init_tso_segs(skb, mss_now); 2940 goto repair; /* Skip network transmission */ 2941 } 2942 2943 if (tcp_pacing_check(sk)) 2944 break; 2945 2946 cwnd_quota = tcp_cwnd_test(tp); 2947 if (!cwnd_quota) { 2948 if (push_one == 2) 2949 /* Force out a loss probe pkt. */ 2950 cwnd_quota = 1; 2951 else 2952 break; 2953 } 2954 cwnd_quota = min(cwnd_quota, max_segs); 2955 missing_bytes = cwnd_quota * mss_now - skb->len; 2956 if (missing_bytes > 0) 2957 tcp_grow_skb(sk, skb, missing_bytes); 2958 2959 tso_segs = tcp_set_skb_tso_segs(skb, mss_now); 2960 2961 if (unlikely(!tcp_snd_wnd_test(tp, skb, mss_now))) { 2962 is_rwnd_limited = true; 2963 break; 2964 } 2965 2966 if (tso_segs == 1) { 2967 if (unlikely(!tcp_nagle_test(tp, skb, mss_now, 2968 (tcp_skb_is_last(sk, skb) ? 2969 nonagle : TCP_NAGLE_PUSH)))) 2970 break; 2971 } else { 2972 if (!push_one && 2973 tcp_tso_should_defer(sk, skb, &is_cwnd_limited, 2974 &is_rwnd_limited, max_segs)) 2975 break; 2976 } 2977 2978 limit = mss_now; 2979 if (tso_segs > 1 && !tcp_urg_mode(tp)) 2980 limit = tcp_mss_split_point(sk, skb, mss_now, 2981 cwnd_quota, 2982 nonagle); 2983 2984 if (skb->len > limit && 2985 unlikely(tso_fragment(sk, skb, limit, mss_now, gfp))) 2986 break; 2987 2988 if (tcp_small_queue_check(sk, skb, 0)) 2989 break; 2990 2991 /* Argh, we hit an empty skb(), presumably a thread 2992 * is sleeping in sendmsg()/sk_stream_wait_memory(). 2993 * We do not want to send a pure-ack packet and have 2994 * a strange looking rtx queue with empty packet(s). 2995 */ 2996 if (TCP_SKB_CB(skb)->end_seq == TCP_SKB_CB(skb)->seq) 2997 break; 2998 2999 if (unlikely(tcp_transmit_skb(sk, skb, 1, gfp))) 3000 break; 3001 3002 repair: 3003 /* Advance the send_head. This one is sent out. 3004 * This call will increment packets_out. 3005 */ 3006 tcp_event_new_data_sent(sk, skb); 3007 3008 tcp_minshall_update(tp, mss_now, skb); 3009 sent_pkts += tcp_skb_pcount(skb); 3010 3011 if (push_one) 3012 break; 3013 } 3014 3015 if (is_rwnd_limited) 3016 tcp_chrono_start(sk, TCP_CHRONO_RWND_LIMITED); 3017 else 3018 tcp_chrono_stop(sk, TCP_CHRONO_RWND_LIMITED); 3019 3020 is_cwnd_limited |= (tcp_packets_in_flight(tp) >= tcp_snd_cwnd(tp)); 3021 if (likely(sent_pkts || is_cwnd_limited)) 3022 tcp_cwnd_validate(sk, is_cwnd_limited); 3023 3024 if (likely(sent_pkts)) { 3025 if (tcp_in_cwnd_reduction(sk)) 3026 tp->prr_out += sent_pkts; 3027 3028 /* Send one loss probe per tail loss episode. */ 3029 if (push_one != 2) 3030 tcp_schedule_loss_probe(sk, false); 3031 return false; 3032 } 3033 return !tp->packets_out && !tcp_write_queue_empty(sk); 3034 } 3035 3036 bool tcp_schedule_loss_probe(struct sock *sk, bool advancing_rto) 3037 { 3038 struct inet_connection_sock *icsk = inet_csk(sk); 3039 struct tcp_sock *tp = tcp_sk(sk); 3040 u32 timeout, timeout_us, rto_delta_us; 3041 int early_retrans; 3042 3043 /* Don't do any loss probe on a Fast Open connection before 3WHS 3044 * finishes. 3045 */ 3046 if (rcu_access_pointer(tp->fastopen_rsk)) 3047 return false; 3048 3049 early_retrans = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_early_retrans); 3050 /* Schedule a loss probe in 2*RTT for SACK capable connections 3051 * not in loss recovery, that are either limited by cwnd or application. 3052 */ 3053 if ((early_retrans != 3 && early_retrans != 4) || 3054 !tp->packets_out || !tcp_is_sack(tp) || 3055 (icsk->icsk_ca_state != TCP_CA_Open && 3056 icsk->icsk_ca_state != TCP_CA_CWR)) 3057 return false; 3058 3059 /* Probe timeout is 2*rtt. Add minimum RTO to account 3060 * for delayed ack when there's one outstanding packet. If no RTT 3061 * sample is available then probe after TCP_TIMEOUT_INIT. 3062 */ 3063 if (tp->srtt_us) { 3064 timeout_us = tp->srtt_us >> 2; 3065 if (tp->packets_out == 1) 3066 timeout_us += tcp_rto_min_us(sk); 3067 else 3068 timeout_us += TCP_TIMEOUT_MIN_US; 3069 timeout = usecs_to_jiffies(timeout_us); 3070 } else { 3071 timeout = TCP_TIMEOUT_INIT; 3072 } 3073 3074 /* If the RTO formula yields an earlier time, then use that time. */ 3075 rto_delta_us = advancing_rto ? 3076 jiffies_to_usecs(inet_csk(sk)->icsk_rto) : 3077 tcp_rto_delta_us(sk); /* How far in future is RTO? */ 3078 if (rto_delta_us > 0) 3079 timeout = min_t(u32, timeout, usecs_to_jiffies(rto_delta_us)); 3080 3081 tcp_reset_xmit_timer(sk, ICSK_TIME_LOSS_PROBE, timeout, true); 3082 return true; 3083 } 3084 3085 /* Thanks to skb fast clones, we can detect if a prior transmit of 3086 * a packet is still in a qdisc or driver queue. 3087 * In this case, there is very little point doing a retransmit ! 3088 */ 3089 static bool skb_still_in_host_queue(struct sock *sk, 3090 const struct sk_buff *skb) 3091 { 3092 if (unlikely(skb_fclone_busy(sk, skb))) { 3093 set_bit(TSQ_THROTTLED, &sk->sk_tsq_flags); 3094 smp_mb__after_atomic(); 3095 if (skb_fclone_busy(sk, skb)) { 3096 NET_INC_STATS(sock_net(sk), 3097 LINUX_MIB_TCPSPURIOUS_RTX_HOSTQUEUES); 3098 return true; 3099 } 3100 } 3101 return false; 3102 } 3103 3104 /* When probe timeout (PTO) fires, try send a new segment if possible, else 3105 * retransmit the last segment. 3106 */ 3107 void tcp_send_loss_probe(struct sock *sk) 3108 { 3109 struct tcp_sock *tp = tcp_sk(sk); 3110 struct sk_buff *skb; 3111 int pcount; 3112 int mss = tcp_current_mss(sk); 3113 3114 /* At most one outstanding TLP */ 3115 if (tp->tlp_high_seq) 3116 goto rearm_timer; 3117 3118 tp->tlp_retrans = 0; 3119 skb = tcp_send_head(sk); 3120 if (skb && tcp_snd_wnd_test(tp, skb, mss)) { 3121 pcount = tp->packets_out; 3122 tcp_write_xmit(sk, mss, TCP_NAGLE_OFF, 2, GFP_ATOMIC); 3123 if (tp->packets_out > pcount) 3124 goto probe_sent; 3125 goto rearm_timer; 3126 } 3127 skb = skb_rb_last(&sk->tcp_rtx_queue); 3128 if (unlikely(!skb)) { 3129 tcp_warn_once(sk, tp->packets_out, "invalid inflight: "); 3130 smp_store_release(&inet_csk(sk)->icsk_pending, 0); 3131 return; 3132 } 3133 3134 if (skb_still_in_host_queue(sk, skb)) 3135 goto rearm_timer; 3136 3137 pcount = tcp_skb_pcount(skb); 3138 if (WARN_ON(!pcount)) 3139 goto rearm_timer; 3140 3141 if ((pcount > 1) && (skb->len > (pcount - 1) * mss)) { 3142 if (unlikely(tcp_fragment(sk, TCP_FRAG_IN_RTX_QUEUE, skb, 3143 (pcount - 1) * mss, mss, 3144 GFP_ATOMIC))) 3145 goto rearm_timer; 3146 skb = skb_rb_next(skb); 3147 } 3148 3149 if (WARN_ON(!skb || !tcp_skb_pcount(skb))) 3150 goto rearm_timer; 3151 3152 if (__tcp_retransmit_skb(sk, skb, 1)) 3153 goto rearm_timer; 3154 3155 tp->tlp_retrans = 1; 3156 3157 probe_sent: 3158 /* Record snd_nxt for loss detection. */ 3159 tp->tlp_high_seq = tp->snd_nxt; 3160 3161 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPLOSSPROBES); 3162 /* Reset s.t. tcp_rearm_rto will restart timer from now */ 3163 smp_store_release(&inet_csk(sk)->icsk_pending, 0); 3164 rearm_timer: 3165 tcp_rearm_rto(sk); 3166 } 3167 3168 /* Push out any pending frames which were held back due to 3169 * TCP_CORK or attempt at coalescing tiny packets. 3170 * The socket must be locked by the caller. 3171 */ 3172 void __tcp_push_pending_frames(struct sock *sk, unsigned int cur_mss, 3173 int nonagle) 3174 { 3175 /* If we are closed, the bytes will have to remain here. 3176 * In time closedown will finish, we empty the write queue and 3177 * all will be happy. 3178 */ 3179 if (unlikely(sk->sk_state == TCP_CLOSE)) 3180 return; 3181 3182 if (tcp_write_xmit(sk, cur_mss, nonagle, 0, 3183 sk_gfp_mask(sk, GFP_ATOMIC))) 3184 tcp_check_probe_timer(sk); 3185 } 3186 3187 /* Send _single_ skb sitting at the send head. This function requires 3188 * true push pending frames to setup probe timer etc. 3189 */ 3190 void tcp_push_one(struct sock *sk, unsigned int mss_now) 3191 { 3192 struct sk_buff *skb = tcp_send_head(sk); 3193 3194 BUG_ON(!skb || skb->len < mss_now); 3195 3196 tcp_write_xmit(sk, mss_now, TCP_NAGLE_PUSH, 1, sk->sk_allocation); 3197 } 3198 3199 /* This function returns the amount that we can raise the 3200 * usable window based on the following constraints 3201 * 3202 * 1. The window can never be shrunk once it is offered (RFC 793) 3203 * 2. We limit memory per socket 3204 * 3205 * RFC 1122: 3206 * "the suggested [SWS] avoidance algorithm for the receiver is to keep 3207 * RECV.NEXT + RCV.WIN fixed until: 3208 * RCV.BUFF - RCV.USER - RCV.WINDOW >= min(1/2 RCV.BUFF, MSS)" 3209 * 3210 * i.e. don't raise the right edge of the window until you can raise 3211 * it at least MSS bytes. 3212 * 3213 * Unfortunately, the recommended algorithm breaks header prediction, 3214 * since header prediction assumes th->window stays fixed. 3215 * 3216 * Strictly speaking, keeping th->window fixed violates the receiver 3217 * side SWS prevention criteria. The problem is that under this rule 3218 * a stream of single byte packets will cause the right side of the 3219 * window to always advance by a single byte. 3220 * 3221 * Of course, if the sender implements sender side SWS prevention 3222 * then this will not be a problem. 3223 * 3224 * BSD seems to make the following compromise: 3225 * 3226 * If the free space is less than the 1/4 of the maximum 3227 * space available and the free space is less than 1/2 mss, 3228 * then set the window to 0. 3229 * [ Actually, bsd uses MSS and 1/4 of maximal _window_ ] 3230 * Otherwise, just prevent the window from shrinking 3231 * and from being larger than the largest representable value. 3232 * 3233 * This prevents incremental opening of the window in the regime 3234 * where TCP is limited by the speed of the reader side taking 3235 * data out of the TCP receive queue. It does nothing about 3236 * those cases where the window is constrained on the sender side 3237 * because the pipeline is full. 3238 * 3239 * BSD also seems to "accidentally" limit itself to windows that are a 3240 * multiple of MSS, at least until the free space gets quite small. 3241 * This would appear to be a side effect of the mbuf implementation. 3242 * Combining these two algorithms results in the observed behavior 3243 * of having a fixed window size at almost all times. 3244 * 3245 * Below we obtain similar behavior by forcing the offered window to 3246 * a multiple of the mss when it is feasible to do so. 3247 * 3248 * Note, we don't "adjust" for TIMESTAMP or SACK option bytes. 3249 * Regular options like TIMESTAMP are taken into account. 3250 */ 3251 u32 __tcp_select_window(struct sock *sk) 3252 { 3253 struct inet_connection_sock *icsk = inet_csk(sk); 3254 struct tcp_sock *tp = tcp_sk(sk); 3255 struct net *net = sock_net(sk); 3256 /* MSS for the peer's data. Previous versions used mss_clamp 3257 * here. I don't know if the value based on our guesses 3258 * of peer's MSS is better for the performance. It's more correct 3259 * but may be worse for the performance because of rcv_mss 3260 * fluctuations. --SAW 1998/11/1 3261 */ 3262 int mss = icsk->icsk_ack.rcv_mss; 3263 int free_space = tcp_space(sk); 3264 int allowed_space = tcp_full_space(sk); 3265 int full_space, window; 3266 3267 if (sk_is_mptcp(sk)) 3268 mptcp_space(sk, &free_space, &allowed_space); 3269 3270 full_space = min_t(int, tp->window_clamp, allowed_space); 3271 3272 if (unlikely(mss > full_space)) { 3273 mss = full_space; 3274 if (mss <= 0) 3275 return 0; 3276 } 3277 3278 /* Only allow window shrink if the sysctl is enabled and we have 3279 * a non-zero scaling factor in effect. 3280 */ 3281 if (READ_ONCE(net->ipv4.sysctl_tcp_shrink_window) && tp->rx_opt.rcv_wscale) 3282 goto shrink_window_allowed; 3283 3284 /* do not allow window to shrink */ 3285 3286 if (free_space < (full_space >> 1)) { 3287 icsk->icsk_ack.quick = 0; 3288 3289 if (tcp_under_memory_pressure(sk)) 3290 tcp_adjust_rcv_ssthresh(sk); 3291 3292 /* free_space might become our new window, make sure we don't 3293 * increase it due to wscale. 3294 */ 3295 free_space = round_down(free_space, 1 << tp->rx_opt.rcv_wscale); 3296 3297 /* if free space is less than mss estimate, or is below 1/16th 3298 * of the maximum allowed, try to move to zero-window, else 3299 * tcp_clamp_window() will grow rcv buf up to tcp_rmem[2], and 3300 * new incoming data is dropped due to memory limits. 3301 * With large window, mss test triggers way too late in order 3302 * to announce zero window in time before rmem limit kicks in. 3303 */ 3304 if (free_space < (allowed_space >> 4) || free_space < mss) 3305 return 0; 3306 } 3307 3308 if (free_space > tp->rcv_ssthresh) 3309 free_space = tp->rcv_ssthresh; 3310 3311 /* Don't do rounding if we are using window scaling, since the 3312 * scaled window will not line up with the MSS boundary anyway. 3313 */ 3314 if (tp->rx_opt.rcv_wscale) { 3315 window = free_space; 3316 3317 /* Advertise enough space so that it won't get scaled away. 3318 * Import case: prevent zero window announcement if 3319 * 1<<rcv_wscale > mss. 3320 */ 3321 window = ALIGN(window, (1 << tp->rx_opt.rcv_wscale)); 3322 } else { 3323 window = tp->rcv_wnd; 3324 /* Get the largest window that is a nice multiple of mss. 3325 * Window clamp already applied above. 3326 * If our current window offering is within 1 mss of the 3327 * free space we just keep it. This prevents the divide 3328 * and multiply from happening most of the time. 3329 * We also don't do any window rounding when the free space 3330 * is too small. 3331 */ 3332 if (window <= free_space - mss || window > free_space) 3333 window = rounddown(free_space, mss); 3334 else if (mss == full_space && 3335 free_space > window + (full_space >> 1)) 3336 window = free_space; 3337 } 3338 3339 return window; 3340 3341 shrink_window_allowed: 3342 /* new window should always be an exact multiple of scaling factor */ 3343 free_space = round_down(free_space, 1 << tp->rx_opt.rcv_wscale); 3344 3345 if (free_space < (full_space >> 1)) { 3346 icsk->icsk_ack.quick = 0; 3347 3348 if (tcp_under_memory_pressure(sk)) 3349 tcp_adjust_rcv_ssthresh(sk); 3350 3351 /* if free space is too low, return a zero window */ 3352 if (free_space < (allowed_space >> 4) || free_space < mss || 3353 free_space < (1 << tp->rx_opt.rcv_wscale)) 3354 return 0; 3355 } 3356 3357 if (free_space > tp->rcv_ssthresh) { 3358 free_space = tp->rcv_ssthresh; 3359 /* new window should always be an exact multiple of scaling factor 3360 * 3361 * For this case, we ALIGN "up" (increase free_space) because 3362 * we know free_space is not zero here, it has been reduced from 3363 * the memory-based limit, and rcv_ssthresh is not a hard limit 3364 * (unlike sk_rcvbuf). 3365 */ 3366 free_space = ALIGN(free_space, (1 << tp->rx_opt.rcv_wscale)); 3367 } 3368 3369 return free_space; 3370 } 3371 3372 void tcp_skb_collapse_tstamp(struct sk_buff *skb, 3373 const struct sk_buff *next_skb) 3374 { 3375 if (unlikely(tcp_has_tx_tstamp(next_skb))) { 3376 const struct skb_shared_info *next_shinfo = 3377 skb_shinfo(next_skb); 3378 struct skb_shared_info *shinfo = skb_shinfo(skb); 3379 3380 shinfo->tx_flags |= next_shinfo->tx_flags & SKBTX_ANY_TSTAMP; 3381 shinfo->tskey = next_shinfo->tskey; 3382 TCP_SKB_CB(skb)->txstamp_ack |= 3383 TCP_SKB_CB(next_skb)->txstamp_ack; 3384 } 3385 } 3386 3387 /* Collapses two adjacent SKB's during retransmission. */ 3388 static bool tcp_collapse_retrans(struct sock *sk, struct sk_buff *skb) 3389 { 3390 struct tcp_sock *tp = tcp_sk(sk); 3391 struct sk_buff *next_skb = skb_rb_next(skb); 3392 int next_skb_size; 3393 3394 next_skb_size = next_skb->len; 3395 3396 BUG_ON(tcp_skb_pcount(skb) != 1 || tcp_skb_pcount(next_skb) != 1); 3397 3398 if (next_skb_size && !tcp_skb_shift(skb, next_skb, 1, next_skb_size)) 3399 return false; 3400 3401 tcp_highest_sack_replace(sk, next_skb, skb); 3402 3403 /* Update sequence range on original skb. */ 3404 TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(next_skb)->end_seq; 3405 3406 /* Merge over control information. This moves PSH/FIN etc. over */ 3407 TCP_SKB_CB(skb)->tcp_flags |= TCP_SKB_CB(next_skb)->tcp_flags; 3408 3409 /* All done, get rid of second SKB and account for it so 3410 * packet counting does not break. 3411 */ 3412 TCP_SKB_CB(skb)->sacked |= TCP_SKB_CB(next_skb)->sacked & TCPCB_EVER_RETRANS; 3413 TCP_SKB_CB(skb)->eor = TCP_SKB_CB(next_skb)->eor; 3414 3415 /* changed transmit queue under us so clear hints */ 3416 if (next_skb == tp->retransmit_skb_hint) 3417 tp->retransmit_skb_hint = skb; 3418 3419 tcp_adjust_pcount(sk, next_skb, tcp_skb_pcount(next_skb)); 3420 3421 tcp_skb_collapse_tstamp(skb, next_skb); 3422 3423 tcp_rtx_queue_unlink_and_free(next_skb, sk); 3424 return true; 3425 } 3426 3427 /* Check if coalescing SKBs is legal. */ 3428 static bool tcp_can_collapse(const struct sock *sk, const struct sk_buff *skb) 3429 { 3430 if (tcp_skb_pcount(skb) > 1) 3431 return false; 3432 if (skb_cloned(skb)) 3433 return false; 3434 if (!skb_frags_readable(skb)) 3435 return false; 3436 /* Some heuristics for collapsing over SACK'd could be invented */ 3437 if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED) 3438 return false; 3439 3440 return true; 3441 } 3442 3443 /* Collapse packets in the retransmit queue to make to create 3444 * less packets on the wire. This is only done on retransmission. 3445 */ 3446 static void tcp_retrans_try_collapse(struct sock *sk, struct sk_buff *to, 3447 int space) 3448 { 3449 struct tcp_sock *tp = tcp_sk(sk); 3450 struct sk_buff *skb = to, *tmp; 3451 bool first = true; 3452 3453 if (!READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_retrans_collapse)) 3454 return; 3455 if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN) 3456 return; 3457 3458 skb_rbtree_walk_from_safe(skb, tmp) { 3459 if (!tcp_can_collapse(sk, skb)) 3460 break; 3461 3462 if (!tcp_skb_can_collapse(to, skb)) 3463 break; 3464 3465 space -= skb->len; 3466 3467 if (first) { 3468 first = false; 3469 continue; 3470 } 3471 3472 if (space < 0) 3473 break; 3474 3475 if (after(TCP_SKB_CB(skb)->end_seq, tcp_wnd_end(tp))) 3476 break; 3477 3478 if (!tcp_collapse_retrans(sk, to)) 3479 break; 3480 } 3481 } 3482 3483 /* This retransmits one SKB. Policy decisions and retransmit queue 3484 * state updates are done by the caller. Returns non-zero if an 3485 * error occurred which prevented the send. 3486 */ 3487 int __tcp_retransmit_skb(struct sock *sk, struct sk_buff *skb, int segs) 3488 { 3489 struct inet_connection_sock *icsk = inet_csk(sk); 3490 struct tcp_sock *tp = tcp_sk(sk); 3491 unsigned int cur_mss; 3492 int diff, len, err; 3493 int avail_wnd; 3494 3495 /* Inconclusive MTU probe */ 3496 if (icsk->icsk_mtup.probe_size) 3497 icsk->icsk_mtup.probe_size = 0; 3498 3499 if (skb_still_in_host_queue(sk, skb)) { 3500 err = -EBUSY; 3501 goto out; 3502 } 3503 3504 start: 3505 if (before(TCP_SKB_CB(skb)->seq, tp->snd_una)) { 3506 if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) { 3507 TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_SYN; 3508 TCP_SKB_CB(skb)->seq++; 3509 goto start; 3510 } 3511 if (unlikely(before(TCP_SKB_CB(skb)->end_seq, tp->snd_una))) { 3512 WARN_ON_ONCE(1); 3513 err = -EINVAL; 3514 goto out; 3515 } 3516 if (tcp_trim_head(sk, skb, tp->snd_una - TCP_SKB_CB(skb)->seq)) { 3517 err = -ENOMEM; 3518 goto out; 3519 } 3520 } 3521 3522 if (inet_csk(sk)->icsk_af_ops->rebuild_header(sk)) { 3523 err = -EHOSTUNREACH; /* Routing failure or similar. */ 3524 goto out; 3525 } 3526 3527 cur_mss = tcp_current_mss(sk); 3528 avail_wnd = tcp_wnd_end(tp) - TCP_SKB_CB(skb)->seq; 3529 3530 /* If receiver has shrunk his window, and skb is out of 3531 * new window, do not retransmit it. The exception is the 3532 * case, when window is shrunk to zero. In this case 3533 * our retransmit of one segment serves as a zero window probe. 3534 */ 3535 if (avail_wnd <= 0) { 3536 if (TCP_SKB_CB(skb)->seq != tp->snd_una) { 3537 err = -EAGAIN; 3538 goto out; 3539 } 3540 avail_wnd = cur_mss; 3541 } 3542 3543 len = cur_mss * segs; 3544 if (len > avail_wnd) { 3545 len = rounddown(avail_wnd, cur_mss); 3546 if (!len) 3547 len = avail_wnd; 3548 } 3549 if (skb->len > len) { 3550 if (tcp_fragment(sk, TCP_FRAG_IN_RTX_QUEUE, skb, len, 3551 cur_mss, GFP_ATOMIC)) { 3552 err = -ENOMEM; /* We'll try again later. */ 3553 goto out; 3554 } 3555 } else { 3556 if (skb_unclone_keeptruesize(skb, GFP_ATOMIC)) { 3557 err = -ENOMEM; 3558 goto out; 3559 } 3560 3561 diff = tcp_skb_pcount(skb); 3562 tcp_set_skb_tso_segs(skb, cur_mss); 3563 diff -= tcp_skb_pcount(skb); 3564 if (diff) 3565 tcp_adjust_pcount(sk, skb, diff); 3566 avail_wnd = min_t(int, avail_wnd, cur_mss); 3567 if (skb->len < avail_wnd) 3568 tcp_retrans_try_collapse(sk, skb, avail_wnd); 3569 } 3570 3571 /* RFC3168, section 6.1.1.1. ECN fallback 3572 * As AccECN uses the same SYN flags (+ AE), this check covers both 3573 * cases. 3574 */ 3575 if ((TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN_ECN) == TCPHDR_SYN_ECN) 3576 tcp_ecn_clear_syn(sk, skb); 3577 3578 /* Update global and local TCP statistics. */ 3579 segs = tcp_skb_pcount(skb); 3580 TCP_ADD_STATS(sock_net(sk), TCP_MIB_RETRANSSEGS, segs); 3581 if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN) 3582 __NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPSYNRETRANS); 3583 tp->total_retrans += segs; 3584 tp->bytes_retrans += skb->len; 3585 3586 /* make sure skb->data is aligned on arches that require it 3587 * and check if ack-trimming & collapsing extended the headroom 3588 * beyond what csum_start can cover. 3589 */ 3590 if (unlikely((NET_IP_ALIGN && ((unsigned long)skb->data & 3)) || 3591 skb_headroom(skb) >= 0xFFFF)) { 3592 struct sk_buff *nskb; 3593 3594 tcp_skb_tsorted_save(skb) { 3595 nskb = __pskb_copy(skb, MAX_TCP_HEADER, GFP_ATOMIC); 3596 if (nskb) { 3597 nskb->dev = NULL; 3598 err = tcp_transmit_skb(sk, nskb, 0, GFP_ATOMIC); 3599 } else { 3600 err = -ENOBUFS; 3601 } 3602 } tcp_skb_tsorted_restore(skb); 3603 3604 if (!err) { 3605 tcp_update_skb_after_send(sk, skb, tp->tcp_wstamp_ns); 3606 tcp_rate_skb_sent(sk, skb); 3607 } 3608 } else { 3609 err = tcp_transmit_skb(sk, skb, 1, GFP_ATOMIC); 3610 } 3611 3612 if (BPF_SOCK_OPS_TEST_FLAG(tp, BPF_SOCK_OPS_RETRANS_CB_FLAG)) 3613 tcp_call_bpf_3arg(sk, BPF_SOCK_OPS_RETRANS_CB, 3614 TCP_SKB_CB(skb)->seq, segs, err); 3615 3616 if (unlikely(err) && err != -EBUSY) 3617 NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPRETRANSFAIL, segs); 3618 3619 /* To avoid taking spuriously low RTT samples based on a timestamp 3620 * for a transmit that never happened, always mark EVER_RETRANS 3621 */ 3622 TCP_SKB_CB(skb)->sacked |= TCPCB_EVER_RETRANS; 3623 3624 out: 3625 trace_tcp_retransmit_skb(sk, skb, err); 3626 return err; 3627 } 3628 3629 int tcp_retransmit_skb(struct sock *sk, struct sk_buff *skb, int segs) 3630 { 3631 struct tcp_sock *tp = tcp_sk(sk); 3632 int err = __tcp_retransmit_skb(sk, skb, segs); 3633 3634 if (err == 0) { 3635 #if FASTRETRANS_DEBUG > 0 3636 if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS) { 3637 net_dbg_ratelimited("retrans_out leaked\n"); 3638 } 3639 #endif 3640 TCP_SKB_CB(skb)->sacked |= TCPCB_RETRANS; 3641 tp->retrans_out += tcp_skb_pcount(skb); 3642 } 3643 3644 /* Save stamp of the first (attempted) retransmit. */ 3645 if (!tp->retrans_stamp) 3646 tp->retrans_stamp = tcp_skb_timestamp_ts(tp->tcp_usec_ts, skb); 3647 3648 if (tp->undo_retrans < 0) 3649 tp->undo_retrans = 0; 3650 tp->undo_retrans += tcp_skb_pcount(skb); 3651 return err; 3652 } 3653 3654 /* This gets called after a retransmit timeout, and the initially 3655 * retransmitted data is acknowledged. It tries to continue 3656 * resending the rest of the retransmit queue, until either 3657 * we've sent it all or the congestion window limit is reached. 3658 */ 3659 void tcp_xmit_retransmit_queue(struct sock *sk) 3660 { 3661 const struct inet_connection_sock *icsk = inet_csk(sk); 3662 struct sk_buff *skb, *rtx_head, *hole = NULL; 3663 struct tcp_sock *tp = tcp_sk(sk); 3664 bool rearm_timer = false; 3665 u32 max_segs; 3666 int mib_idx; 3667 3668 if (!tp->packets_out) 3669 return; 3670 3671 rtx_head = tcp_rtx_queue_head(sk); 3672 skb = tp->retransmit_skb_hint ?: rtx_head; 3673 max_segs = tcp_tso_segs(sk, tcp_current_mss(sk)); 3674 skb_rbtree_walk_from(skb) { 3675 __u8 sacked; 3676 int segs; 3677 3678 if (tcp_pacing_check(sk)) 3679 break; 3680 3681 /* we could do better than to assign each time */ 3682 if (!hole) 3683 tp->retransmit_skb_hint = skb; 3684 3685 segs = tcp_snd_cwnd(tp) - tcp_packets_in_flight(tp); 3686 if (segs <= 0) 3687 break; 3688 sacked = TCP_SKB_CB(skb)->sacked; 3689 /* In case tcp_shift_skb_data() have aggregated large skbs, 3690 * we need to make sure not sending too bigs TSO packets 3691 */ 3692 segs = min_t(int, segs, max_segs); 3693 3694 if (tp->retrans_out >= tp->lost_out) { 3695 break; 3696 } else if (!(sacked & TCPCB_LOST)) { 3697 if (!hole && !(sacked & (TCPCB_SACKED_RETRANS|TCPCB_SACKED_ACKED))) 3698 hole = skb; 3699 continue; 3700 3701 } else { 3702 if (icsk->icsk_ca_state != TCP_CA_Loss) 3703 mib_idx = LINUX_MIB_TCPFASTRETRANS; 3704 else 3705 mib_idx = LINUX_MIB_TCPSLOWSTARTRETRANS; 3706 } 3707 3708 if (sacked & (TCPCB_SACKED_ACKED|TCPCB_SACKED_RETRANS)) 3709 continue; 3710 3711 if (tcp_small_queue_check(sk, skb, 1)) 3712 break; 3713 3714 if (tcp_retransmit_skb(sk, skb, segs)) 3715 break; 3716 3717 NET_ADD_STATS(sock_net(sk), mib_idx, tcp_skb_pcount(skb)); 3718 3719 if (tcp_in_cwnd_reduction(sk)) 3720 tp->prr_out += tcp_skb_pcount(skb); 3721 3722 if (skb == rtx_head && 3723 icsk->icsk_pending != ICSK_TIME_REO_TIMEOUT) 3724 rearm_timer = true; 3725 3726 } 3727 if (rearm_timer) 3728 tcp_reset_xmit_timer(sk, ICSK_TIME_RETRANS, 3729 inet_csk(sk)->icsk_rto, true); 3730 } 3731 3732 /* We allow to exceed memory limits for FIN packets to expedite 3733 * connection tear down and (memory) recovery. 3734 * Otherwise tcp_send_fin() could be tempted to either delay FIN 3735 * or even be forced to close flow without any FIN. 3736 * In general, we want to allow one skb per socket to avoid hangs 3737 * with edge trigger epoll() 3738 */ 3739 void sk_forced_mem_schedule(struct sock *sk, int size) 3740 { 3741 int delta, amt; 3742 3743 delta = size - sk->sk_forward_alloc; 3744 if (delta <= 0) 3745 return; 3746 amt = sk_mem_pages(delta); 3747 sk_forward_alloc_add(sk, amt << PAGE_SHIFT); 3748 sk_memory_allocated_add(sk, amt); 3749 3750 if (mem_cgroup_sk_enabled(sk)) 3751 mem_cgroup_sk_charge(sk, amt, gfp_memcg_charge() | __GFP_NOFAIL); 3752 } 3753 3754 /* Send a FIN. The caller locks the socket for us. 3755 * We should try to send a FIN packet really hard, but eventually give up. 3756 */ 3757 void tcp_send_fin(struct sock *sk) 3758 { 3759 struct sk_buff *skb, *tskb, *tail = tcp_write_queue_tail(sk); 3760 struct tcp_sock *tp = tcp_sk(sk); 3761 3762 /* Optimization, tack on the FIN if we have one skb in write queue and 3763 * this skb was not yet sent, or we are under memory pressure. 3764 * Note: in the latter case, FIN packet will be sent after a timeout, 3765 * as TCP stack thinks it has already been transmitted. 3766 */ 3767 tskb = tail; 3768 if (!tskb && tcp_under_memory_pressure(sk)) 3769 tskb = skb_rb_last(&sk->tcp_rtx_queue); 3770 3771 if (tskb) { 3772 TCP_SKB_CB(tskb)->tcp_flags |= TCPHDR_FIN; 3773 TCP_SKB_CB(tskb)->end_seq++; 3774 tp->write_seq++; 3775 if (!tail) { 3776 /* This means tskb was already sent. 3777 * Pretend we included the FIN on previous transmit. 3778 * We need to set tp->snd_nxt to the value it would have 3779 * if FIN had been sent. This is because retransmit path 3780 * does not change tp->snd_nxt. 3781 */ 3782 WRITE_ONCE(tp->snd_nxt, tp->snd_nxt + 1); 3783 return; 3784 } 3785 } else { 3786 skb = alloc_skb_fclone(MAX_TCP_HEADER, 3787 sk_gfp_mask(sk, GFP_ATOMIC | 3788 __GFP_NOWARN)); 3789 if (unlikely(!skb)) 3790 return; 3791 3792 INIT_LIST_HEAD(&skb->tcp_tsorted_anchor); 3793 skb_reserve(skb, MAX_TCP_HEADER); 3794 sk_forced_mem_schedule(sk, skb->truesize); 3795 /* FIN eats a sequence byte, write_seq advanced by tcp_queue_skb(). */ 3796 tcp_init_nondata_skb(skb, sk, tp->write_seq, 3797 TCPHDR_ACK | TCPHDR_FIN); 3798 tcp_queue_skb(sk, skb); 3799 } 3800 __tcp_push_pending_frames(sk, tcp_current_mss(sk), TCP_NAGLE_OFF); 3801 } 3802 3803 /* We get here when a process closes a file descriptor (either due to 3804 * an explicit close() or as a byproduct of exit()'ing) and there 3805 * was unread data in the receive queue. This behavior is recommended 3806 * by RFC 2525, section 2.17. -DaveM 3807 */ 3808 void tcp_send_active_reset(struct sock *sk, gfp_t priority, 3809 enum sk_rst_reason reason) 3810 { 3811 struct sk_buff *skb; 3812 3813 TCP_INC_STATS(sock_net(sk), TCP_MIB_OUTRSTS); 3814 3815 /* NOTE: No TCP options attached and we never retransmit this. */ 3816 skb = alloc_skb(MAX_TCP_HEADER, priority); 3817 if (!skb) { 3818 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTFAILED); 3819 return; 3820 } 3821 3822 /* Reserve space for headers and prepare control bits. */ 3823 skb_reserve(skb, MAX_TCP_HEADER); 3824 tcp_init_nondata_skb(skb, sk, tcp_acceptable_seq(sk), 3825 TCPHDR_ACK | TCPHDR_RST); 3826 tcp_mstamp_refresh(tcp_sk(sk)); 3827 /* Send it off. */ 3828 if (tcp_transmit_skb(sk, skb, 0, priority)) 3829 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTFAILED); 3830 3831 /* skb of trace_tcp_send_reset() keeps the skb that caused RST, 3832 * skb here is different to the troublesome skb, so use NULL 3833 */ 3834 trace_tcp_send_reset(sk, NULL, reason); 3835 } 3836 3837 /* Send a crossed SYN-ACK during socket establishment. 3838 * WARNING: This routine must only be called when we have already sent 3839 * a SYN packet that crossed the incoming SYN that caused this routine 3840 * to get called. If this assumption fails then the initial rcv_wnd 3841 * and rcv_wscale values will not be correct. 3842 */ 3843 int tcp_send_synack(struct sock *sk) 3844 { 3845 struct sk_buff *skb; 3846 3847 skb = tcp_rtx_queue_head(sk); 3848 if (!skb || !(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) { 3849 pr_err("%s: wrong queue state\n", __func__); 3850 return -EFAULT; 3851 } 3852 if (!(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_ACK)) { 3853 if (skb_cloned(skb)) { 3854 struct sk_buff *nskb; 3855 3856 tcp_skb_tsorted_save(skb) { 3857 nskb = skb_copy(skb, GFP_ATOMIC); 3858 } tcp_skb_tsorted_restore(skb); 3859 if (!nskb) 3860 return -ENOMEM; 3861 INIT_LIST_HEAD(&nskb->tcp_tsorted_anchor); 3862 tcp_highest_sack_replace(sk, skb, nskb); 3863 tcp_rtx_queue_unlink_and_free(skb, sk); 3864 __skb_header_release(nskb); 3865 tcp_rbtree_insert(&sk->tcp_rtx_queue, nskb); 3866 sk_wmem_queued_add(sk, nskb->truesize); 3867 sk_mem_charge(sk, nskb->truesize); 3868 skb = nskb; 3869 } 3870 3871 TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_ACK; 3872 tcp_ecn_send_synack(sk, skb); 3873 } 3874 return tcp_transmit_skb(sk, skb, 1, GFP_ATOMIC); 3875 } 3876 3877 /** 3878 * tcp_make_synack - Allocate one skb and build a SYNACK packet. 3879 * @sk: listener socket 3880 * @dst: dst entry attached to the SYNACK. It is consumed and caller 3881 * should not use it again. 3882 * @req: request_sock pointer 3883 * @foc: cookie for tcp fast open 3884 * @synack_type: Type of synack to prepare 3885 * @syn_skb: SYN packet just received. It could be NULL for rtx case. 3886 */ 3887 struct sk_buff *tcp_make_synack(const struct sock *sk, struct dst_entry *dst, 3888 struct request_sock *req, 3889 struct tcp_fastopen_cookie *foc, 3890 enum tcp_synack_type synack_type, 3891 struct sk_buff *syn_skb) 3892 { 3893 struct inet_request_sock *ireq = inet_rsk(req); 3894 const struct tcp_sock *tp = tcp_sk(sk); 3895 struct tcp_out_options opts; 3896 struct tcp_key key = {}; 3897 struct sk_buff *skb; 3898 int tcp_header_size; 3899 struct tcphdr *th; 3900 int mss; 3901 u64 now; 3902 3903 skb = alloc_skb(MAX_TCP_HEADER, GFP_ATOMIC); 3904 if (unlikely(!skb)) { 3905 dst_release(dst); 3906 return NULL; 3907 } 3908 /* Reserve space for headers. */ 3909 skb_reserve(skb, MAX_TCP_HEADER); 3910 3911 switch (synack_type) { 3912 case TCP_SYNACK_NORMAL: 3913 skb_set_owner_edemux(skb, req_to_sk(req)); 3914 break; 3915 case TCP_SYNACK_COOKIE: 3916 /* Under synflood, we do not attach skb to a socket, 3917 * to avoid false sharing. 3918 */ 3919 break; 3920 case TCP_SYNACK_FASTOPEN: 3921 /* sk is a const pointer, because we want to express multiple 3922 * cpu might call us concurrently. 3923 * sk->sk_wmem_alloc in an atomic, we can promote to rw. 3924 */ 3925 skb_set_owner_w(skb, (struct sock *)sk); 3926 break; 3927 } 3928 skb_dst_set(skb, dst); 3929 3930 mss = tcp_mss_clamp(tp, dst_metric_advmss(dst)); 3931 3932 memset(&opts, 0, sizeof(opts)); 3933 now = tcp_clock_ns(); 3934 #ifdef CONFIG_SYN_COOKIES 3935 if (unlikely(synack_type == TCP_SYNACK_COOKIE && ireq->tstamp_ok)) 3936 skb_set_delivery_time(skb, cookie_init_timestamp(req, now), 3937 SKB_CLOCK_MONOTONIC); 3938 else 3939 #endif 3940 { 3941 skb_set_delivery_time(skb, now, SKB_CLOCK_MONOTONIC); 3942 if (!tcp_rsk(req)->snt_synack) /* Timestamp first SYNACK */ 3943 tcp_rsk(req)->snt_synack = tcp_skb_timestamp_us(skb); 3944 } 3945 3946 #if defined(CONFIG_TCP_MD5SIG) || defined(CONFIG_TCP_AO) 3947 rcu_read_lock(); 3948 #endif 3949 if (tcp_rsk_used_ao(req)) { 3950 #ifdef CONFIG_TCP_AO 3951 struct tcp_ao_key *ao_key = NULL; 3952 u8 keyid = tcp_rsk(req)->ao_keyid; 3953 u8 rnext = tcp_rsk(req)->ao_rcv_next; 3954 3955 ao_key = tcp_sk(sk)->af_specific->ao_lookup(sk, req_to_sk(req), 3956 keyid, -1); 3957 /* If there is no matching key - avoid sending anything, 3958 * especially usigned segments. It could try harder and lookup 3959 * for another peer-matching key, but the peer has requested 3960 * ao_keyid (RFC5925 RNextKeyID), so let's keep it simple here. 3961 */ 3962 if (unlikely(!ao_key)) { 3963 trace_tcp_ao_synack_no_key(sk, keyid, rnext); 3964 rcu_read_unlock(); 3965 kfree_skb(skb); 3966 net_warn_ratelimited("TCP-AO: the keyid %u from SYN packet is not present - not sending SYNACK\n", 3967 keyid); 3968 return NULL; 3969 } 3970 key.ao_key = ao_key; 3971 key.type = TCP_KEY_AO; 3972 #endif 3973 } else { 3974 #ifdef CONFIG_TCP_MD5SIG 3975 key.md5_key = tcp_rsk(req)->af_specific->req_md5_lookup(sk, 3976 req_to_sk(req)); 3977 if (key.md5_key) 3978 key.type = TCP_KEY_MD5; 3979 #endif 3980 } 3981 skb_set_hash(skb, READ_ONCE(tcp_rsk(req)->txhash), PKT_HASH_TYPE_L4); 3982 /* bpf program will be interested in the tcp_flags */ 3983 TCP_SKB_CB(skb)->tcp_flags = TCPHDR_SYN | TCPHDR_ACK; 3984 tcp_header_size = tcp_synack_options(sk, req, mss, skb, &opts, 3985 &key, foc, synack_type, syn_skb) 3986 + sizeof(*th); 3987 3988 skb_push(skb, tcp_header_size); 3989 skb_reset_transport_header(skb); 3990 3991 th = (struct tcphdr *)skb->data; 3992 memset(th, 0, sizeof(struct tcphdr)); 3993 th->syn = 1; 3994 th->ack = 1; 3995 tcp_ecn_make_synack(req, th); 3996 th->source = htons(ireq->ir_num); 3997 th->dest = ireq->ir_rmt_port; 3998 skb->mark = ireq->ir_mark; 3999 skb->ip_summed = CHECKSUM_PARTIAL; 4000 th->seq = htonl(tcp_rsk(req)->snt_isn); 4001 /* XXX data is queued and acked as is. No buffer/window check */ 4002 th->ack_seq = htonl(tcp_rsk(req)->rcv_nxt); 4003 4004 /* RFC1323: The window in SYN & SYN/ACK segments is never scaled. */ 4005 th->window = htons(min(req->rsk_rcv_wnd, 65535U)); 4006 tcp_options_write(th, NULL, tcp_rsk(req), &opts, &key); 4007 th->doff = (tcp_header_size >> 2); 4008 TCP_INC_STATS(sock_net(sk), TCP_MIB_OUTSEGS); 4009 4010 /* Okay, we have all we need - do the md5 hash if needed */ 4011 if (tcp_key_is_md5(&key)) { 4012 #ifdef CONFIG_TCP_MD5SIG 4013 tcp_rsk(req)->af_specific->calc_md5_hash(opts.hash_location, 4014 key.md5_key, req_to_sk(req), skb); 4015 #endif 4016 } else if (tcp_key_is_ao(&key)) { 4017 #ifdef CONFIG_TCP_AO 4018 tcp_rsk(req)->af_specific->ao_synack_hash(opts.hash_location, 4019 key.ao_key, req, skb, 4020 opts.hash_location - (u8 *)th, 0); 4021 #endif 4022 } 4023 #if defined(CONFIG_TCP_MD5SIG) || defined(CONFIG_TCP_AO) 4024 rcu_read_unlock(); 4025 #endif 4026 4027 bpf_skops_write_hdr_opt((struct sock *)sk, skb, req, syn_skb, 4028 synack_type, &opts); 4029 4030 skb_set_delivery_time(skb, now, SKB_CLOCK_MONOTONIC); 4031 tcp_add_tx_delay(skb, tp); 4032 4033 return skb; 4034 } 4035 EXPORT_IPV6_MOD(tcp_make_synack); 4036 4037 static void tcp_ca_dst_init(struct sock *sk, const struct dst_entry *dst) 4038 { 4039 struct inet_connection_sock *icsk = inet_csk(sk); 4040 const struct tcp_congestion_ops *ca; 4041 u32 ca_key = dst_metric(dst, RTAX_CC_ALGO); 4042 4043 if (ca_key == TCP_CA_UNSPEC) 4044 return; 4045 4046 rcu_read_lock(); 4047 ca = tcp_ca_find_key(ca_key); 4048 if (likely(ca && bpf_try_module_get(ca, ca->owner))) { 4049 bpf_module_put(icsk->icsk_ca_ops, icsk->icsk_ca_ops->owner); 4050 icsk->icsk_ca_dst_locked = tcp_ca_dst_locked(dst); 4051 icsk->icsk_ca_ops = ca; 4052 } 4053 rcu_read_unlock(); 4054 } 4055 4056 /* Do all connect socket setups that can be done AF independent. */ 4057 static void tcp_connect_init(struct sock *sk) 4058 { 4059 const struct dst_entry *dst = __sk_dst_get(sk); 4060 struct tcp_sock *tp = tcp_sk(sk); 4061 __u8 rcv_wscale; 4062 u16 user_mss; 4063 u32 rcv_wnd; 4064 4065 /* We'll fix this up when we get a response from the other end. 4066 * See tcp_input.c:tcp_rcv_state_process case TCP_SYN_SENT. 4067 */ 4068 tp->tcp_header_len = sizeof(struct tcphdr); 4069 if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_timestamps)) 4070 tp->tcp_header_len += TCPOLEN_TSTAMP_ALIGNED; 4071 4072 tcp_ao_connect_init(sk); 4073 4074 /* If user gave his TCP_MAXSEG, record it to clamp */ 4075 user_mss = READ_ONCE(tp->rx_opt.user_mss); 4076 if (user_mss) 4077 tp->rx_opt.mss_clamp = user_mss; 4078 tp->max_window = 0; 4079 tcp_mtup_init(sk); 4080 tcp_sync_mss(sk, dst_mtu(dst)); 4081 4082 tcp_ca_dst_init(sk, dst); 4083 4084 if (!tp->window_clamp) 4085 WRITE_ONCE(tp->window_clamp, dst_metric(dst, RTAX_WINDOW)); 4086 tp->advmss = tcp_mss_clamp(tp, dst_metric_advmss(dst)); 4087 4088 tcp_initialize_rcv_mss(sk); 4089 4090 /* limit the window selection if the user enforce a smaller rx buffer */ 4091 if (sk->sk_userlocks & SOCK_RCVBUF_LOCK && 4092 (tp->window_clamp > tcp_full_space(sk) || tp->window_clamp == 0)) 4093 WRITE_ONCE(tp->window_clamp, tcp_full_space(sk)); 4094 4095 rcv_wnd = tcp_rwnd_init_bpf(sk); 4096 if (rcv_wnd == 0) 4097 rcv_wnd = dst_metric(dst, RTAX_INITRWND); 4098 4099 tcp_select_initial_window(sk, tcp_full_space(sk), 4100 tp->advmss - (tp->rx_opt.ts_recent_stamp ? tp->tcp_header_len - sizeof(struct tcphdr) : 0), 4101 &tp->rcv_wnd, 4102 &tp->window_clamp, 4103 READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_window_scaling), 4104 &rcv_wscale, 4105 rcv_wnd); 4106 4107 tp->rx_opt.rcv_wscale = rcv_wscale; 4108 tp->rcv_ssthresh = tp->rcv_wnd; 4109 4110 WRITE_ONCE(sk->sk_err, 0); 4111 sock_reset_flag(sk, SOCK_DONE); 4112 tp->snd_wnd = 0; 4113 tcp_init_wl(tp, 0); 4114 tcp_write_queue_purge(sk); 4115 tp->snd_una = tp->write_seq; 4116 tp->snd_sml = tp->write_seq; 4117 tp->snd_up = tp->write_seq; 4118 WRITE_ONCE(tp->snd_nxt, tp->write_seq); 4119 4120 if (likely(!tp->repair)) 4121 tp->rcv_nxt = 0; 4122 else 4123 tp->rcv_tstamp = tcp_jiffies32; 4124 tp->rcv_wup = tp->rcv_nxt; 4125 WRITE_ONCE(tp->copied_seq, tp->rcv_nxt); 4126 4127 inet_csk(sk)->icsk_rto = tcp_timeout_init(sk); 4128 WRITE_ONCE(inet_csk(sk)->icsk_retransmits, 0); 4129 tcp_clear_retrans(tp); 4130 } 4131 4132 static void tcp_connect_queue_skb(struct sock *sk, struct sk_buff *skb) 4133 { 4134 struct tcp_sock *tp = tcp_sk(sk); 4135 struct tcp_skb_cb *tcb = TCP_SKB_CB(skb); 4136 4137 tcb->end_seq += skb->len; 4138 __skb_header_release(skb); 4139 sk_wmem_queued_add(sk, skb->truesize); 4140 sk_mem_charge(sk, skb->truesize); 4141 WRITE_ONCE(tp->write_seq, tcb->end_seq); 4142 tp->packets_out += tcp_skb_pcount(skb); 4143 } 4144 4145 /* Build and send a SYN with data and (cached) Fast Open cookie. However, 4146 * queue a data-only packet after the regular SYN, such that regular SYNs 4147 * are retransmitted on timeouts. Also if the remote SYN-ACK acknowledges 4148 * only the SYN sequence, the data are retransmitted in the first ACK. 4149 * If cookie is not cached or other error occurs, falls back to send a 4150 * regular SYN with Fast Open cookie request option. 4151 */ 4152 static int tcp_send_syn_data(struct sock *sk, struct sk_buff *syn) 4153 { 4154 struct inet_connection_sock *icsk = inet_csk(sk); 4155 struct tcp_sock *tp = tcp_sk(sk); 4156 struct tcp_fastopen_request *fo = tp->fastopen_req; 4157 struct page_frag *pfrag = sk_page_frag(sk); 4158 struct sk_buff *syn_data; 4159 int space, err = 0; 4160 4161 tp->rx_opt.mss_clamp = tp->advmss; /* If MSS is not cached */ 4162 if (!tcp_fastopen_cookie_check(sk, &tp->rx_opt.mss_clamp, &fo->cookie)) 4163 goto fallback; 4164 4165 /* MSS for SYN-data is based on cached MSS and bounded by PMTU and 4166 * user-MSS. Reserve maximum option space for middleboxes that add 4167 * private TCP options. The cost is reduced data space in SYN :( 4168 */ 4169 tp->rx_opt.mss_clamp = tcp_mss_clamp(tp, tp->rx_opt.mss_clamp); 4170 /* Sync mss_cache after updating the mss_clamp */ 4171 tcp_sync_mss(sk, icsk->icsk_pmtu_cookie); 4172 4173 space = __tcp_mtu_to_mss(sk, icsk->icsk_pmtu_cookie) - 4174 MAX_TCP_OPTION_SPACE; 4175 4176 space = min_t(size_t, space, fo->size); 4177 4178 if (space && 4179 !skb_page_frag_refill(min_t(size_t, space, PAGE_SIZE), 4180 pfrag, sk->sk_allocation)) 4181 goto fallback; 4182 syn_data = tcp_stream_alloc_skb(sk, sk->sk_allocation, false); 4183 if (!syn_data) 4184 goto fallback; 4185 memcpy(syn_data->cb, syn->cb, sizeof(syn->cb)); 4186 if (space) { 4187 space = min_t(size_t, space, pfrag->size - pfrag->offset); 4188 space = tcp_wmem_schedule(sk, space); 4189 } 4190 if (space) { 4191 space = copy_page_from_iter(pfrag->page, pfrag->offset, 4192 space, &fo->data->msg_iter); 4193 if (unlikely(!space)) { 4194 tcp_skb_tsorted_anchor_cleanup(syn_data); 4195 kfree_skb(syn_data); 4196 goto fallback; 4197 } 4198 skb_fill_page_desc(syn_data, 0, pfrag->page, 4199 pfrag->offset, space); 4200 page_ref_inc(pfrag->page); 4201 pfrag->offset += space; 4202 skb_len_add(syn_data, space); 4203 skb_zcopy_set(syn_data, fo->uarg, NULL); 4204 } 4205 /* No more data pending in inet_wait_for_connect() */ 4206 if (space == fo->size) 4207 fo->data = NULL; 4208 fo->copied = space; 4209 4210 tcp_connect_queue_skb(sk, syn_data); 4211 if (syn_data->len) 4212 tcp_chrono_start(sk, TCP_CHRONO_BUSY); 4213 4214 err = tcp_transmit_skb(sk, syn_data, 1, sk->sk_allocation); 4215 4216 skb_set_delivery_time(syn, syn_data->skb_mstamp_ns, SKB_CLOCK_MONOTONIC); 4217 4218 /* Now full SYN+DATA was cloned and sent (or not), 4219 * remove the SYN from the original skb (syn_data) 4220 * we keep in write queue in case of a retransmit, as we 4221 * also have the SYN packet (with no data) in the same queue. 4222 */ 4223 TCP_SKB_CB(syn_data)->seq++; 4224 TCP_SKB_CB(syn_data)->tcp_flags = TCPHDR_ACK | TCPHDR_PSH; 4225 if (!err) { 4226 tp->syn_data = (fo->copied > 0); 4227 tcp_rbtree_insert(&sk->tcp_rtx_queue, syn_data); 4228 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPORIGDATASENT); 4229 goto done; 4230 } 4231 4232 /* data was not sent, put it in write_queue */ 4233 __skb_queue_tail(&sk->sk_write_queue, syn_data); 4234 tp->packets_out -= tcp_skb_pcount(syn_data); 4235 4236 fallback: 4237 /* Send a regular SYN with Fast Open cookie request option */ 4238 if (fo->cookie.len > 0) 4239 fo->cookie.len = 0; 4240 err = tcp_transmit_skb(sk, syn, 1, sk->sk_allocation); 4241 if (err) 4242 tp->syn_fastopen = 0; 4243 done: 4244 fo->cookie.len = -1; /* Exclude Fast Open option for SYN retries */ 4245 return err; 4246 } 4247 4248 /* Build a SYN and send it off. */ 4249 int tcp_connect(struct sock *sk) 4250 { 4251 struct tcp_sock *tp = tcp_sk(sk); 4252 struct sk_buff *buff; 4253 int err; 4254 4255 tcp_call_bpf(sk, BPF_SOCK_OPS_TCP_CONNECT_CB, 0, NULL); 4256 4257 #if defined(CONFIG_TCP_MD5SIG) && defined(CONFIG_TCP_AO) 4258 /* Has to be checked late, after setting daddr/saddr/ops. 4259 * Return error if the peer has both a md5 and a tcp-ao key 4260 * configured as this is ambiguous. 4261 */ 4262 if (unlikely(rcu_dereference_protected(tp->md5sig_info, 4263 lockdep_sock_is_held(sk)))) { 4264 bool needs_ao = !!tp->af_specific->ao_lookup(sk, sk, -1, -1); 4265 bool needs_md5 = !!tp->af_specific->md5_lookup(sk, sk); 4266 struct tcp_ao_info *ao_info; 4267 4268 ao_info = rcu_dereference_check(tp->ao_info, 4269 lockdep_sock_is_held(sk)); 4270 if (ao_info) { 4271 /* This is an extra check: tcp_ao_required() in 4272 * tcp_v{4,6}_parse_md5_keys() should prevent adding 4273 * md5 keys on ao_required socket. 4274 */ 4275 needs_ao |= ao_info->ao_required; 4276 WARN_ON_ONCE(ao_info->ao_required && needs_md5); 4277 } 4278 if (needs_md5 && needs_ao) 4279 return -EKEYREJECTED; 4280 4281 /* If we have a matching md5 key and no matching tcp-ao key 4282 * then free up ao_info if allocated. 4283 */ 4284 if (needs_md5) { 4285 tcp_ao_destroy_sock(sk, false); 4286 } else if (needs_ao) { 4287 tcp_clear_md5_list(sk); 4288 kfree(rcu_replace_pointer(tp->md5sig_info, NULL, 4289 lockdep_sock_is_held(sk))); 4290 } 4291 } 4292 #endif 4293 #ifdef CONFIG_TCP_AO 4294 if (unlikely(rcu_dereference_protected(tp->ao_info, 4295 lockdep_sock_is_held(sk)))) { 4296 /* Don't allow connecting if ao is configured but no 4297 * matching key is found. 4298 */ 4299 if (!tp->af_specific->ao_lookup(sk, sk, -1, -1)) 4300 return -EKEYREJECTED; 4301 } 4302 #endif 4303 4304 if (inet_csk(sk)->icsk_af_ops->rebuild_header(sk)) 4305 return -EHOSTUNREACH; /* Routing failure or similar. */ 4306 4307 tcp_connect_init(sk); 4308 4309 if (unlikely(tp->repair)) { 4310 tcp_finish_connect(sk, NULL); 4311 return 0; 4312 } 4313 4314 buff = tcp_stream_alloc_skb(sk, sk->sk_allocation, true); 4315 if (unlikely(!buff)) 4316 return -ENOBUFS; 4317 4318 /* SYN eats a sequence byte, write_seq updated by 4319 * tcp_connect_queue_skb(). 4320 */ 4321 tcp_init_nondata_skb(buff, sk, tp->write_seq, TCPHDR_SYN); 4322 tcp_mstamp_refresh(tp); 4323 tp->retrans_stamp = tcp_time_stamp_ts(tp); 4324 tcp_connect_queue_skb(sk, buff); 4325 tcp_ecn_send_syn(sk, buff); 4326 tcp_rbtree_insert(&sk->tcp_rtx_queue, buff); 4327 4328 /* Send off SYN; include data in Fast Open. */ 4329 err = tp->fastopen_req ? tcp_send_syn_data(sk, buff) : 4330 tcp_transmit_skb(sk, buff, 1, sk->sk_allocation); 4331 if (err == -ECONNREFUSED) 4332 return err; 4333 4334 /* We change tp->snd_nxt after the tcp_transmit_skb() call 4335 * in order to make this packet get counted in tcpOutSegs. 4336 */ 4337 WRITE_ONCE(tp->snd_nxt, tp->write_seq); 4338 tp->pushed_seq = tp->write_seq; 4339 buff = tcp_send_head(sk); 4340 if (unlikely(buff)) { 4341 WRITE_ONCE(tp->snd_nxt, TCP_SKB_CB(buff)->seq); 4342 tp->pushed_seq = TCP_SKB_CB(buff)->seq; 4343 } 4344 TCP_INC_STATS(sock_net(sk), TCP_MIB_ACTIVEOPENS); 4345 4346 /* Timer for repeating the SYN until an answer. */ 4347 tcp_reset_xmit_timer(sk, ICSK_TIME_RETRANS, 4348 inet_csk(sk)->icsk_rto, false); 4349 return 0; 4350 } 4351 EXPORT_SYMBOL(tcp_connect); 4352 4353 u32 tcp_delack_max(const struct sock *sk) 4354 { 4355 u32 delack_from_rto_min = max(tcp_rto_min(sk), 2) - 1; 4356 4357 return min(READ_ONCE(inet_csk(sk)->icsk_delack_max), delack_from_rto_min); 4358 } 4359 4360 /* Send out a delayed ack, the caller does the policy checking 4361 * to see if we should even be here. See tcp_input.c:tcp_ack_snd_check() 4362 * for details. 4363 */ 4364 void tcp_send_delayed_ack(struct sock *sk) 4365 { 4366 struct inet_connection_sock *icsk = inet_csk(sk); 4367 int ato = icsk->icsk_ack.ato; 4368 unsigned long timeout; 4369 4370 if (ato > TCP_DELACK_MIN) { 4371 const struct tcp_sock *tp = tcp_sk(sk); 4372 int max_ato = HZ / 2; 4373 4374 if (inet_csk_in_pingpong_mode(sk) || 4375 (icsk->icsk_ack.pending & ICSK_ACK_PUSHED)) 4376 max_ato = TCP_DELACK_MAX; 4377 4378 /* Slow path, intersegment interval is "high". */ 4379 4380 /* If some rtt estimate is known, use it to bound delayed ack. 4381 * Do not use inet_csk(sk)->icsk_rto here, use results of rtt measurements 4382 * directly. 4383 */ 4384 if (tp->srtt_us) { 4385 int rtt = max_t(int, usecs_to_jiffies(tp->srtt_us >> 3), 4386 TCP_DELACK_MIN); 4387 4388 if (rtt < max_ato) 4389 max_ato = rtt; 4390 } 4391 4392 ato = min(ato, max_ato); 4393 } 4394 4395 ato = min_t(u32, ato, tcp_delack_max(sk)); 4396 4397 /* Stay within the limit we were given */ 4398 timeout = jiffies + ato; 4399 4400 /* Use new timeout only if there wasn't a older one earlier. */ 4401 if (icsk->icsk_ack.pending & ICSK_ACK_TIMER) { 4402 /* If delack timer is about to expire, send ACK now. */ 4403 if (time_before_eq(icsk_delack_timeout(icsk), jiffies + (ato >> 2))) { 4404 tcp_send_ack(sk); 4405 return; 4406 } 4407 4408 if (!time_before(timeout, icsk_delack_timeout(icsk))) 4409 timeout = icsk_delack_timeout(icsk); 4410 } 4411 smp_store_release(&icsk->icsk_ack.pending, 4412 icsk->icsk_ack.pending | ICSK_ACK_SCHED | ICSK_ACK_TIMER); 4413 sk_reset_timer(sk, &icsk->icsk_delack_timer, timeout); 4414 } 4415 4416 /* This routine sends an ack and also updates the window. */ 4417 void __tcp_send_ack(struct sock *sk, u32 rcv_nxt, u16 flags) 4418 { 4419 struct sk_buff *buff; 4420 4421 /* If we have been reset, we may not send again. */ 4422 if (sk->sk_state == TCP_CLOSE) 4423 return; 4424 4425 /* We are not putting this on the write queue, so 4426 * tcp_transmit_skb() will set the ownership to this 4427 * sock. 4428 */ 4429 buff = alloc_skb(MAX_TCP_HEADER, 4430 sk_gfp_mask(sk, GFP_ATOMIC | __GFP_NOWARN)); 4431 if (unlikely(!buff)) { 4432 struct inet_connection_sock *icsk = inet_csk(sk); 4433 unsigned long delay; 4434 4435 delay = TCP_DELACK_MAX << icsk->icsk_ack.retry; 4436 if (delay < tcp_rto_max(sk)) 4437 icsk->icsk_ack.retry++; 4438 inet_csk_schedule_ack(sk); 4439 icsk->icsk_ack.ato = TCP_ATO_MIN; 4440 tcp_reset_xmit_timer(sk, ICSK_TIME_DACK, delay, false); 4441 return; 4442 } 4443 4444 /* Reserve space for headers and prepare control bits. */ 4445 skb_reserve(buff, MAX_TCP_HEADER); 4446 tcp_init_nondata_skb(buff, sk, 4447 tcp_acceptable_seq(sk), TCPHDR_ACK | flags); 4448 4449 /* We do not want pure acks influencing TCP Small Queues or fq/pacing 4450 * too much. 4451 * SKB_TRUESIZE(max(1 .. 66, MAX_TCP_HEADER)) is unfortunately ~784 4452 */ 4453 skb_set_tcp_pure_ack(buff); 4454 4455 /* Send it off, this clears delayed acks for us. */ 4456 __tcp_transmit_skb(sk, buff, 0, (__force gfp_t)0, rcv_nxt); 4457 } 4458 EXPORT_SYMBOL_GPL(__tcp_send_ack); 4459 4460 void tcp_send_ack(struct sock *sk) 4461 { 4462 __tcp_send_ack(sk, tcp_sk(sk)->rcv_nxt, 0); 4463 } 4464 4465 /* This routine sends a packet with an out of date sequence 4466 * number. It assumes the other end will try to ack it. 4467 * 4468 * Question: what should we make while urgent mode? 4469 * 4.4BSD forces sending single byte of data. We cannot send 4470 * out of window data, because we have SND.NXT==SND.MAX... 4471 * 4472 * Current solution: to send TWO zero-length segments in urgent mode: 4473 * one is with SEG.SEQ=SND.UNA to deliver urgent pointer, another is 4474 * out-of-date with SND.UNA-1 to probe window. 4475 */ 4476 static int tcp_xmit_probe_skb(struct sock *sk, int urgent, int mib) 4477 { 4478 struct tcp_sock *tp = tcp_sk(sk); 4479 struct sk_buff *skb; 4480 4481 /* We don't queue it, tcp_transmit_skb() sets ownership. */ 4482 skb = alloc_skb(MAX_TCP_HEADER, 4483 sk_gfp_mask(sk, GFP_ATOMIC | __GFP_NOWARN)); 4484 if (!skb) 4485 return -1; 4486 4487 /* Reserve space for headers and set control bits. */ 4488 skb_reserve(skb, MAX_TCP_HEADER); 4489 /* Use a previous sequence. This should cause the other 4490 * end to send an ack. Don't queue or clone SKB, just 4491 * send it. 4492 */ 4493 tcp_init_nondata_skb(skb, sk, tp->snd_una - !urgent, TCPHDR_ACK); 4494 NET_INC_STATS(sock_net(sk), mib); 4495 return tcp_transmit_skb(sk, skb, 0, (__force gfp_t)0); 4496 } 4497 4498 /* Called from setsockopt( ... TCP_REPAIR ) */ 4499 void tcp_send_window_probe(struct sock *sk) 4500 { 4501 if (sk->sk_state == TCP_ESTABLISHED) { 4502 tcp_sk(sk)->snd_wl1 = tcp_sk(sk)->rcv_nxt - 1; 4503 tcp_mstamp_refresh(tcp_sk(sk)); 4504 tcp_xmit_probe_skb(sk, 0, LINUX_MIB_TCPWINPROBE); 4505 } 4506 } 4507 4508 /* Initiate keepalive or window probe from timer. */ 4509 int tcp_write_wakeup(struct sock *sk, int mib) 4510 { 4511 struct tcp_sock *tp = tcp_sk(sk); 4512 struct sk_buff *skb; 4513 4514 if (sk->sk_state == TCP_CLOSE) 4515 return -1; 4516 4517 skb = tcp_send_head(sk); 4518 if (skb && before(TCP_SKB_CB(skb)->seq, tcp_wnd_end(tp))) { 4519 int err; 4520 unsigned int mss = tcp_current_mss(sk); 4521 unsigned int seg_size = tcp_wnd_end(tp) - TCP_SKB_CB(skb)->seq; 4522 4523 if (before(tp->pushed_seq, TCP_SKB_CB(skb)->end_seq)) 4524 tp->pushed_seq = TCP_SKB_CB(skb)->end_seq; 4525 4526 /* We are probing the opening of a window 4527 * but the window size is != 0 4528 * must have been a result SWS avoidance ( sender ) 4529 */ 4530 if (seg_size < TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq || 4531 skb->len > mss) { 4532 seg_size = min(seg_size, mss); 4533 TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH; 4534 if (tcp_fragment(sk, TCP_FRAG_IN_WRITE_QUEUE, 4535 skb, seg_size, mss, GFP_ATOMIC)) 4536 return -1; 4537 } else if (!tcp_skb_pcount(skb)) 4538 tcp_set_skb_tso_segs(skb, mss); 4539 4540 TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH; 4541 err = tcp_transmit_skb(sk, skb, 1, GFP_ATOMIC); 4542 if (!err) 4543 tcp_event_new_data_sent(sk, skb); 4544 return err; 4545 } else { 4546 if (between(tp->snd_up, tp->snd_una + 1, tp->snd_una + 0xFFFF)) 4547 tcp_xmit_probe_skb(sk, 1, mib); 4548 return tcp_xmit_probe_skb(sk, 0, mib); 4549 } 4550 } 4551 4552 /* A window probe timeout has occurred. If window is not closed send 4553 * a partial packet else a zero probe. 4554 */ 4555 void tcp_send_probe0(struct sock *sk) 4556 { 4557 struct inet_connection_sock *icsk = inet_csk(sk); 4558 struct tcp_sock *tp = tcp_sk(sk); 4559 struct net *net = sock_net(sk); 4560 unsigned long timeout; 4561 int err; 4562 4563 err = tcp_write_wakeup(sk, LINUX_MIB_TCPWINPROBE); 4564 4565 if (tp->packets_out || tcp_write_queue_empty(sk)) { 4566 /* Cancel probe timer, if it is not required. */ 4567 WRITE_ONCE(icsk->icsk_probes_out, 0); 4568 icsk->icsk_backoff = 0; 4569 icsk->icsk_probes_tstamp = 0; 4570 return; 4571 } 4572 4573 WRITE_ONCE(icsk->icsk_probes_out, icsk->icsk_probes_out + 1); 4574 if (err <= 0) { 4575 if (icsk->icsk_backoff < READ_ONCE(net->ipv4.sysctl_tcp_retries2)) 4576 icsk->icsk_backoff++; 4577 timeout = tcp_probe0_when(sk, tcp_rto_max(sk)); 4578 } else { 4579 /* If packet was not sent due to local congestion, 4580 * Let senders fight for local resources conservatively. 4581 */ 4582 timeout = TCP_RESOURCE_PROBE_INTERVAL; 4583 } 4584 4585 timeout = tcp_clamp_probe0_to_user_timeout(sk, timeout); 4586 tcp_reset_xmit_timer(sk, ICSK_TIME_PROBE0, timeout, true); 4587 } 4588 4589 int tcp_rtx_synack(const struct sock *sk, struct request_sock *req) 4590 { 4591 const struct tcp_request_sock_ops *af_ops = tcp_rsk(req)->af_specific; 4592 struct flowi fl; 4593 int res; 4594 4595 /* Paired with WRITE_ONCE() in sock_setsockopt() */ 4596 if (READ_ONCE(sk->sk_txrehash) == SOCK_TXREHASH_ENABLED) 4597 WRITE_ONCE(tcp_rsk(req)->txhash, net_tx_rndhash()); 4598 res = af_ops->send_synack(sk, NULL, &fl, req, NULL, TCP_SYNACK_NORMAL, 4599 NULL); 4600 if (!res) { 4601 TCP_INC_STATS(sock_net(sk), TCP_MIB_RETRANSSEGS); 4602 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPSYNRETRANS); 4603 if (unlikely(tcp_passive_fastopen(sk))) { 4604 /* sk has const attribute because listeners are lockless. 4605 * However in this case, we are dealing with a passive fastopen 4606 * socket thus we can change total_retrans value. 4607 */ 4608 tcp_sk_rw(sk)->total_retrans++; 4609 } 4610 trace_tcp_retransmit_synack(sk, req); 4611 WRITE_ONCE(req->num_retrans, req->num_retrans + 1); 4612 } 4613 return res; 4614 } 4615 EXPORT_IPV6_MOD(tcp_rtx_synack); 4616