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