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 skb_shinfo(to)->nr_frags = nr_frags; 2714 if (!skb_frags_try_ref(to)) { 2715 skb_shinfo(to)->nr_frags = 0; 2716 return -ENOMEM; 2717 } 2718 2719 to->truesize += probe_size; 2720 to->len += probe_size; 2721 to->data_len += probe_size; 2722 __skb_header_release(to); 2723 return 0; 2724 } 2725 2726 /* tcp_mtu_probe() and tcp_grow_skb() can both eat an skb (src) if 2727 * all its payload was moved to another one (dst). 2728 * Make sure to transfer tcp_flags, eor, and tstamp. 2729 */ 2730 static void tcp_eat_one_skb(struct sock *sk, 2731 struct sk_buff *dst, 2732 struct sk_buff *src) 2733 { 2734 TCP_SKB_CB(dst)->tcp_flags |= TCP_SKB_CB(src)->tcp_flags; 2735 TCP_SKB_CB(dst)->eor = TCP_SKB_CB(src)->eor; 2736 tcp_skb_collapse_tstamp(dst, src); 2737 tcp_unlink_write_queue(src, sk); 2738 tcp_wmem_free_skb(sk, src); 2739 } 2740 2741 /* Create a new MTU probe if we are ready. 2742 * MTU probe is regularly attempting to increase the path MTU by 2743 * deliberately sending larger packets. This discovers routing 2744 * changes resulting in larger path MTUs. 2745 * 2746 * Returns 0 if we should wait to probe (no cwnd available), 2747 * 1 if a probe was sent, 2748 * -1 otherwise 2749 */ 2750 static int tcp_mtu_probe(struct sock *sk) 2751 { 2752 struct inet_connection_sock *icsk = inet_csk(sk); 2753 struct tcp_sock *tp = tcp_sk(sk); 2754 struct sk_buff *skb, *nskb, *next; 2755 struct net *net = sock_net(sk); 2756 int probe_size; 2757 u64 size_needed; 2758 int copy, len; 2759 int mss_now; 2760 int interval; 2761 2762 /* Not currently probing/verifying, 2763 * not in recovery, 2764 * have enough cwnd, and 2765 * not SACKing (the variable headers throw things off) 2766 */ 2767 if (likely(!icsk->icsk_mtup.enabled || 2768 icsk->icsk_mtup.probe_size || 2769 inet_csk(sk)->icsk_ca_state != TCP_CA_Open || 2770 tcp_snd_cwnd(tp) < 11 || 2771 tp->rx_opt.num_sacks || tp->rx_opt.dsack)) 2772 return -1; 2773 2774 /* Use binary search for probe_size between tcp_mss_base, 2775 * and current mss_clamp. if (search_high - search_low) 2776 * smaller than a threshold, backoff from probing. 2777 */ 2778 mss_now = tcp_current_mss(sk); 2779 probe_size = tcp_mtu_to_mss(sk, (icsk->icsk_mtup.search_high + 2780 icsk->icsk_mtup.search_low) >> 1); 2781 size_needed = probe_size + ((u64)tp->reordering + 1) * tp->mss_cache; 2782 interval = icsk->icsk_mtup.search_high - icsk->icsk_mtup.search_low; 2783 /* When misfortune happens, we are reprobing actively, 2784 * and then reprobe timer has expired. We stick with current 2785 * probing process by not resetting search range to its orignal. 2786 */ 2787 if (probe_size > tcp_mtu_to_mss(sk, icsk->icsk_mtup.search_high) || 2788 interval < READ_ONCE(net->ipv4.sysctl_tcp_probe_threshold)) { 2789 /* Check whether enough time has elaplased for 2790 * another round of probing. 2791 */ 2792 tcp_mtu_check_reprobe(sk); 2793 return -1; 2794 } 2795 2796 /* Have enough data in the send queue to probe? */ 2797 if (tp->write_seq - tp->snd_nxt < size_needed) 2798 return -1; 2799 2800 if (tp->snd_wnd < size_needed) 2801 return -1; 2802 if (after(tp->snd_nxt + size_needed, tcp_wnd_end(tp))) 2803 return 0; 2804 2805 /* Do we need to wait to drain cwnd? With none in flight, don't stall */ 2806 if (tcp_packets_in_flight(tp) + 2 > tcp_snd_cwnd(tp)) { 2807 if (!tcp_packets_in_flight(tp)) 2808 return -1; 2809 else 2810 return 0; 2811 } 2812 2813 if (!tcp_can_coalesce_send_queue_head(sk, probe_size)) 2814 return -1; 2815 2816 /* We're allowed to probe. Build it now. */ 2817 nskb = tcp_stream_alloc_skb(sk, GFP_ATOMIC, false); 2818 if (!nskb) 2819 return -1; 2820 2821 /* build the payload, and be prepared to abort if this fails. */ 2822 if (tcp_clone_payload(sk, nskb, probe_size)) { 2823 tcp_skb_tsorted_anchor_cleanup(nskb); 2824 consume_skb(nskb); 2825 return -1; 2826 } 2827 sk_wmem_queued_add(sk, nskb->truesize); 2828 sk_mem_charge(sk, nskb->truesize); 2829 2830 skb = tcp_send_head(sk); 2831 skb_copy_decrypted(nskb, skb); 2832 mptcp_skb_ext_copy(nskb, skb); 2833 2834 TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(skb)->seq; 2835 TCP_SKB_CB(nskb)->end_seq = TCP_SKB_CB(skb)->seq + probe_size; 2836 TCP_SKB_CB(nskb)->tcp_flags = TCPHDR_ACK; 2837 2838 tcp_insert_write_queue_before(nskb, skb, sk); 2839 tcp_highest_sack_replace(sk, skb, nskb); 2840 2841 len = 0; 2842 tcp_for_write_queue_from_safe(skb, next, sk) { 2843 copy = min_t(int, skb->len, probe_size - len); 2844 2845 if (skb->len <= copy) { 2846 tcp_eat_one_skb(sk, nskb, skb); 2847 } else { 2848 TCP_SKB_CB(nskb)->tcp_flags |= TCP_SKB_CB(skb)->tcp_flags & 2849 ~(TCPHDR_FIN|TCPHDR_PSH); 2850 __pskb_trim_head(skb, copy); 2851 tcp_set_skb_tso_segs(skb, mss_now); 2852 TCP_SKB_CB(skb)->seq += copy; 2853 } 2854 2855 len += copy; 2856 2857 if (len >= probe_size) 2858 break; 2859 } 2860 tcp_init_tso_segs(nskb, nskb->len); 2861 2862 /* We're ready to send. If this fails, the probe will 2863 * be resegmented into mss-sized pieces by tcp_write_xmit(). 2864 */ 2865 if (!tcp_transmit_skb(sk, nskb, 1, GFP_ATOMIC)) { 2866 /* Decrement cwnd here because we are sending 2867 * effectively two packets. */ 2868 tcp_snd_cwnd_set(tp, tcp_snd_cwnd(tp) - 1); 2869 tcp_event_new_data_sent(sk, nskb); 2870 2871 icsk->icsk_mtup.probe_size = tcp_mss_to_mtu(sk, nskb->len); 2872 tp->mtu_probe.probe_seq_start = TCP_SKB_CB(nskb)->seq; 2873 tp->mtu_probe.probe_seq_end = TCP_SKB_CB(nskb)->end_seq; 2874 2875 return 1; 2876 } 2877 2878 return -1; 2879 } 2880 2881 static bool tcp_pacing_check(struct sock *sk) 2882 { 2883 struct tcp_sock *tp = tcp_sk(sk); 2884 2885 if (!tcp_needs_internal_pacing(sk)) 2886 return false; 2887 2888 if (tp->tcp_wstamp_ns <= tp->tcp_clock_cache) 2889 return false; 2890 2891 if (!hrtimer_is_queued(&tp->pacing_timer)) { 2892 hrtimer_start(&tp->pacing_timer, 2893 ns_to_ktime(tp->tcp_wstamp_ns), 2894 HRTIMER_MODE_ABS_PINNED_SOFT); 2895 sock_hold(sk); 2896 } 2897 return true; 2898 } 2899 2900 static bool tcp_rtx_queue_empty_or_single_skb(const struct sock *sk) 2901 { 2902 const struct rb_node *node = sk->tcp_rtx_queue.rb_node; 2903 2904 /* No skb in the rtx queue. */ 2905 if (!node) 2906 return true; 2907 2908 /* Only one skb in rtx queue. */ 2909 return !node->rb_left && !node->rb_right; 2910 } 2911 2912 /* TCP Small Queues : 2913 * Control number of packets in qdisc/devices to two packets / or ~1 ms. 2914 * (These limits are doubled for retransmits) 2915 * This allows for : 2916 * - better RTT estimation and ACK scheduling 2917 * - faster recovery 2918 * - high rates 2919 * Alas, some drivers / subsystems require a fair amount 2920 * of queued bytes to ensure line rate. 2921 * One example is wifi aggregation (802.11 AMPDU) 2922 */ 2923 static bool tcp_small_queue_check(struct sock *sk, const struct sk_buff *skb, 2924 unsigned int factor) 2925 { 2926 unsigned long limit; 2927 2928 limit = max_t(unsigned long, 2929 2 * skb->truesize, 2930 READ_ONCE(sk->sk_pacing_rate) >> READ_ONCE(sk->sk_pacing_shift)); 2931 limit = min_t(unsigned long, limit, 2932 READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_limit_output_bytes)); 2933 limit <<= factor; 2934 2935 if (static_branch_unlikely(&tcp_tx_delay_enabled) && 2936 tcp_sk(sk)->tcp_tx_delay) { 2937 u64 extra_bytes = (u64)READ_ONCE(sk->sk_pacing_rate) * 2938 tcp_sk(sk)->tcp_tx_delay; 2939 2940 /* TSQ is based on skb truesize sum (sk_wmem_alloc), so we 2941 * approximate our needs assuming an ~100% skb->truesize overhead. 2942 * USEC_PER_SEC is approximated by 2^20. 2943 * do_div(extra_bytes, USEC_PER_SEC/2) is replaced by a right shift. 2944 */ 2945 extra_bytes >>= (20 - 1); 2946 limit += extra_bytes; 2947 } 2948 if (refcount_read(&sk->sk_wmem_alloc) > limit) { 2949 /* Always send skb if rtx queue is empty or has one skb. 2950 * No need to wait for TX completion to call us back, 2951 * after softirq schedule. 2952 * This helps when TX completions are delayed too much. 2953 */ 2954 if (tcp_rtx_queue_empty_or_single_skb(sk)) 2955 return false; 2956 2957 set_bit(TSQ_THROTTLED, &sk->sk_tsq_flags); 2958 /* It is possible TX completion already happened 2959 * before we set TSQ_THROTTLED, so we must 2960 * test again the condition. 2961 */ 2962 smp_mb__after_atomic(); 2963 if (refcount_read(&sk->sk_wmem_alloc) > limit) 2964 return true; 2965 } 2966 return false; 2967 } 2968 2969 void tcp_chrono_stop(struct sock *sk, const enum tcp_chrono type) 2970 { 2971 struct tcp_sock *tp = tcp_sk(sk); 2972 2973 2974 /* There are multiple conditions worthy of tracking in a 2975 * chronograph, so that the highest priority enum takes 2976 * precedence over the other conditions (see tcp_chrono_start). 2977 * If a condition stops, we only stop chrono tracking if 2978 * it's the "most interesting" or current chrono we are 2979 * tracking and starts busy chrono if we have pending data. 2980 */ 2981 if (tcp_rtx_and_write_queues_empty(sk)) 2982 tcp_chrono_set(tp, TCP_CHRONO_UNSPEC); 2983 else if (type == tp->chrono_type) 2984 tcp_chrono_set(tp, TCP_CHRONO_BUSY); 2985 } 2986 2987 /* First skb in the write queue is smaller than ideal packet size. 2988 * Check if we can move payload from the second skb in the queue. 2989 */ 2990 static void tcp_grow_skb(struct sock *sk, struct sk_buff *skb, int amount) 2991 { 2992 struct sk_buff *next_skb = skb->next; 2993 unsigned int nlen; 2994 2995 if (tcp_skb_is_last(sk, skb)) 2996 return; 2997 2998 if (!tcp_skb_can_collapse(skb, next_skb)) 2999 return; 3000 3001 nlen = min_t(u32, amount, next_skb->len); 3002 if (!nlen || !skb_shift(skb, next_skb, nlen)) 3003 return; 3004 3005 TCP_SKB_CB(skb)->end_seq += nlen; 3006 TCP_SKB_CB(next_skb)->seq += nlen; 3007 3008 if (!next_skb->len) { 3009 /* In case FIN is set, we need to update end_seq */ 3010 TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(next_skb)->end_seq; 3011 3012 tcp_eat_one_skb(sk, skb, next_skb); 3013 } 3014 } 3015 3016 /* This routine writes packets to the network. It advances the 3017 * send_head. This happens as incoming acks open up the remote 3018 * window for us. 3019 * 3020 * LARGESEND note: !tcp_urg_mode is overkill, only frames between 3021 * snd_up-64k-mss .. snd_up cannot be large. However, taking into 3022 * account rare use of URG, this is not a big flaw. 3023 * 3024 * Send at most one packet when push_one > 0. Temporarily ignore 3025 * cwnd limit to force at most one packet out when push_one == 2. 3026 3027 * Returns true, if no segments are in flight and we have queued segments, 3028 * but cannot send anything now because of SWS or another problem. 3029 */ 3030 static bool tcp_write_xmit(struct sock *sk, unsigned int mss_now, int nonagle, 3031 int push_one, gfp_t gfp) 3032 { 3033 struct tcp_sock *tp = tcp_sk(sk); 3034 struct sk_buff *skb; 3035 unsigned int tso_segs, sent_pkts; 3036 u32 cwnd_quota, max_segs; 3037 int result; 3038 bool is_cwnd_limited = false, is_rwnd_limited = false; 3039 3040 sent_pkts = 0; 3041 3042 tcp_mstamp_refresh_inline(tp); 3043 3044 /* AccECN option beacon depends on mstamp, it may change mss */ 3045 if (tcp_ecn_mode_accecn(tp) && tcp_accecn_option_beacon_check(sk)) 3046 mss_now = tcp_current_mss(sk); 3047 3048 if (!push_one) { 3049 /* Do MTU probing. */ 3050 result = tcp_mtu_probe(sk); 3051 if (!result) { 3052 return false; 3053 } else if (result > 0) { 3054 sent_pkts = 1; 3055 } 3056 } 3057 3058 max_segs = tcp_tso_segs(sk, mss_now); 3059 while ((skb = tcp_send_head(sk))) { 3060 unsigned int limit; 3061 int missing_bytes; 3062 3063 if (unlikely(tp->repair) && tp->repair_queue == TCP_SEND_QUEUE) { 3064 /* "skb_mstamp_ns" is used as a start point for the retransmit timer */ 3065 tp->tcp_wstamp_ns = tp->tcp_clock_cache; 3066 skb_set_delivery_time(skb, tp->tcp_wstamp_ns, SKB_CLOCK_MONOTONIC); 3067 list_move_tail(&skb->tcp_tsorted_anchor, &tp->tsorted_sent_queue); 3068 tcp_init_tso_segs(skb, mss_now); 3069 goto repair; /* Skip network transmission */ 3070 } 3071 3072 if (tcp_pacing_check(sk)) 3073 break; 3074 3075 cwnd_quota = tcp_cwnd_test(tp); 3076 if (!cwnd_quota) { 3077 if (push_one == 2) 3078 /* Force out a loss probe pkt. */ 3079 cwnd_quota = 1; 3080 else 3081 break; 3082 } 3083 cwnd_quota = min(cwnd_quota, max_segs); 3084 missing_bytes = cwnd_quota * mss_now - skb->len; 3085 if (missing_bytes > 0) 3086 tcp_grow_skb(sk, skb, missing_bytes); 3087 3088 tso_segs = tcp_set_skb_tso_segs(skb, mss_now); 3089 3090 if (unlikely(!tcp_snd_wnd_test(tp, skb, mss_now))) { 3091 is_rwnd_limited = true; 3092 break; 3093 } 3094 3095 if (tso_segs == 1) { 3096 if (unlikely(!tcp_nagle_test(tp, skb, mss_now, 3097 (tcp_skb_is_last(sk, skb) ? 3098 nonagle : TCP_NAGLE_PUSH)))) 3099 break; 3100 } else { 3101 if (!push_one && 3102 tcp_tso_should_defer(sk, skb, &is_cwnd_limited, 3103 &is_rwnd_limited, max_segs)) 3104 break; 3105 } 3106 3107 limit = mss_now; 3108 if (tso_segs > 1 && !tcp_urg_mode(tp)) 3109 limit = tcp_mss_split_point(sk, skb, mss_now, 3110 cwnd_quota, 3111 nonagle); 3112 3113 if (skb->len > limit && 3114 unlikely(tso_fragment(sk, skb, limit, mss_now, gfp))) 3115 break; 3116 3117 if (tcp_small_queue_check(sk, skb, 0)) 3118 break; 3119 3120 /* Argh, we hit an empty skb(), presumably a thread 3121 * is sleeping in sendmsg()/sk_stream_wait_memory(). 3122 * We do not want to send a pure-ack packet and have 3123 * a strange looking rtx queue with empty packet(s). 3124 */ 3125 if (TCP_SKB_CB(skb)->end_seq == TCP_SKB_CB(skb)->seq) 3126 break; 3127 3128 if (unlikely(tcp_transmit_skb(sk, skb, 1, gfp))) 3129 break; 3130 3131 repair: 3132 /* Advance the send_head. This one is sent out. 3133 * This call will increment packets_out. 3134 */ 3135 tcp_event_new_data_sent(sk, skb); 3136 3137 tcp_minshall_update(tp, mss_now, skb); 3138 sent_pkts += tcp_skb_pcount(skb); 3139 3140 if (push_one) 3141 break; 3142 } 3143 3144 if (is_rwnd_limited) 3145 tcp_chrono_start(sk, TCP_CHRONO_RWND_LIMITED); 3146 else 3147 tcp_chrono_stop(sk, TCP_CHRONO_RWND_LIMITED); 3148 3149 is_cwnd_limited |= (tcp_packets_in_flight(tp) >= tcp_snd_cwnd(tp)); 3150 if (likely(sent_pkts || is_cwnd_limited)) 3151 tcp_cwnd_validate(sk, is_cwnd_limited); 3152 3153 if (likely(sent_pkts)) { 3154 if (tcp_in_cwnd_reduction(sk)) 3155 tp->prr_out += sent_pkts; 3156 3157 /* Send one loss probe per tail loss episode. */ 3158 if (push_one != 2) 3159 tcp_schedule_loss_probe(sk, false); 3160 return false; 3161 } 3162 return !tp->packets_out && !tcp_write_queue_empty(sk); 3163 } 3164 3165 bool tcp_schedule_loss_probe(struct sock *sk, bool advancing_rto) 3166 { 3167 struct inet_connection_sock *icsk = inet_csk(sk); 3168 struct tcp_sock *tp = tcp_sk(sk); 3169 u32 timeout, timeout_us, rto_delta_us; 3170 int early_retrans; 3171 3172 /* Don't do any loss probe on a Fast Open connection before 3WHS 3173 * finishes. 3174 */ 3175 if (rcu_access_pointer(tp->fastopen_rsk)) 3176 return false; 3177 3178 early_retrans = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_early_retrans); 3179 /* Schedule a loss probe in 2*RTT for SACK capable connections 3180 * not in loss recovery, that are either limited by cwnd or application. 3181 */ 3182 if ((early_retrans != 3 && early_retrans != 4) || 3183 !tcp_is_sack(tp) || 3184 (icsk->icsk_ca_state != TCP_CA_Open && 3185 icsk->icsk_ca_state != TCP_CA_CWR)) 3186 return false; 3187 3188 /* Probe timeout is 2*rtt. Add minimum RTO to account 3189 * for delayed ack when there's one outstanding packet. If no RTT 3190 * sample is available then probe after TCP_TIMEOUT_INIT. 3191 */ 3192 if (tp->srtt_us) { 3193 timeout_us = tp->srtt_us >> 2; 3194 if (tp->packets_out == 1) 3195 timeout_us += tcp_rto_min_us(sk); 3196 else 3197 timeout_us += TCP_TIMEOUT_MIN_US; 3198 timeout = usecs_to_jiffies(timeout_us); 3199 } else { 3200 timeout = TCP_TIMEOUT_INIT; 3201 } 3202 3203 /* If the RTO formula yields an earlier time, then use that time. */ 3204 rto_delta_us = advancing_rto ? 3205 jiffies_to_usecs(inet_csk(sk)->icsk_rto) : 3206 tcp_rto_delta_us(sk); /* How far in future is RTO? */ 3207 if (rto_delta_us > 0) 3208 timeout = min_t(u32, timeout, usecs_to_jiffies(rto_delta_us)); 3209 3210 tcp_reset_xmit_timer(sk, ICSK_TIME_LOSS_PROBE, timeout, true); 3211 return true; 3212 } 3213 3214 /* Thanks to skb fast clones, we can detect if a prior transmit of 3215 * a packet is still in a qdisc or driver queue. 3216 * In this case, there is very little point doing a retransmit ! 3217 */ 3218 static bool skb_still_in_host_queue(struct sock *sk, 3219 const struct sk_buff *skb) 3220 { 3221 if (unlikely(skb_fclone_busy(sk, skb))) { 3222 set_bit(TSQ_THROTTLED, &sk->sk_tsq_flags); 3223 smp_mb__after_atomic(); 3224 if (skb_fclone_busy(sk, skb)) { 3225 NET_INC_STATS(sock_net(sk), 3226 LINUX_MIB_TCPSPURIOUS_RTX_HOSTQUEUES); 3227 return true; 3228 } 3229 } 3230 return false; 3231 } 3232 3233 /* When probe timeout (PTO) fires, try send a new segment if possible, else 3234 * retransmit the last segment. 3235 */ 3236 void tcp_send_loss_probe(struct sock *sk) 3237 { 3238 struct tcp_sock *tp = tcp_sk(sk); 3239 struct sk_buff *skb; 3240 int pcount; 3241 int mss = tcp_current_mss(sk); 3242 3243 /* At most one outstanding TLP */ 3244 if (tp->tlp_high_seq) 3245 goto rearm_timer; 3246 3247 tp->tlp_retrans = 0; 3248 skb = tcp_send_head(sk); 3249 if (skb && tcp_snd_wnd_test(tp, skb, mss)) { 3250 pcount = tp->packets_out; 3251 tcp_write_xmit(sk, mss, TCP_NAGLE_OFF, 2, GFP_ATOMIC); 3252 if (tp->packets_out > pcount) 3253 goto probe_sent; 3254 goto rearm_timer; 3255 } 3256 skb = skb_rb_last(&sk->tcp_rtx_queue); 3257 if (unlikely(!skb)) { 3258 tcp_warn_once(sk, tp->packets_out, "invalid inflight: "); 3259 smp_store_release(&inet_csk(sk)->icsk_pending, 0); 3260 return; 3261 } 3262 3263 if (skb_still_in_host_queue(sk, skb)) 3264 goto rearm_timer; 3265 3266 pcount = tcp_skb_pcount(skb); 3267 if (WARN_ON(!pcount)) 3268 goto rearm_timer; 3269 3270 if ((pcount > 1) && (skb->len > (pcount - 1) * mss)) { 3271 if (unlikely(tcp_fragment(sk, TCP_FRAG_IN_RTX_QUEUE, skb, 3272 (pcount - 1) * mss, mss, 3273 GFP_ATOMIC))) 3274 goto rearm_timer; 3275 skb = skb_rb_next(skb); 3276 } 3277 3278 if (WARN_ON(!skb || !tcp_skb_pcount(skb))) 3279 goto rearm_timer; 3280 3281 if (__tcp_retransmit_skb(sk, skb, 1)) 3282 goto rearm_timer; 3283 3284 tp->tlp_retrans = 1; 3285 3286 probe_sent: 3287 /* Record snd_nxt for loss detection. */ 3288 tp->tlp_high_seq = tp->snd_nxt; 3289 3290 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPLOSSPROBES); 3291 /* Reset s.t. tcp_rearm_rto will restart timer from now */ 3292 smp_store_release(&inet_csk(sk)->icsk_pending, 0); 3293 rearm_timer: 3294 tcp_rearm_rto(sk); 3295 } 3296 3297 /* Push out any pending frames which were held back due to 3298 * TCP_CORK or attempt at coalescing tiny packets. 3299 * The socket must be locked by the caller. 3300 */ 3301 void __tcp_push_pending_frames(struct sock *sk, unsigned int cur_mss, 3302 int nonagle) 3303 { 3304 /* If we are closed, the bytes will have to remain here. 3305 * In time closedown will finish, we empty the write queue and 3306 * all will be happy. 3307 */ 3308 if (unlikely(sk->sk_state == TCP_CLOSE)) 3309 return; 3310 3311 if (tcp_write_xmit(sk, cur_mss, nonagle, 0, 3312 sk_gfp_mask(sk, GFP_ATOMIC))) 3313 tcp_check_probe_timer(sk); 3314 } 3315 3316 /* Send _single_ skb sitting at the send head. This function requires 3317 * true push pending frames to setup probe timer etc. 3318 */ 3319 void tcp_push_one(struct sock *sk, unsigned int mss_now) 3320 { 3321 struct sk_buff *skb = tcp_send_head(sk); 3322 3323 BUG_ON(!skb || skb->len < mss_now); 3324 3325 tcp_write_xmit(sk, mss_now, TCP_NAGLE_PUSH, 1, sk->sk_allocation); 3326 } 3327 3328 /* This function returns the amount that we can raise the 3329 * usable window based on the following constraints 3330 * 3331 * 1. The window can never be shrunk once it is offered (RFC 793) 3332 * 2. We limit memory per socket 3333 * 3334 * RFC 1122: 3335 * "the suggested [SWS] avoidance algorithm for the receiver is to keep 3336 * RECV.NEXT + RCV.WIN fixed until: 3337 * RCV.BUFF - RCV.USER - RCV.WINDOW >= min(1/2 RCV.BUFF, MSS)" 3338 * 3339 * i.e. don't raise the right edge of the window until you can raise 3340 * it at least MSS bytes. 3341 * 3342 * Unfortunately, the recommended algorithm breaks header prediction, 3343 * since header prediction assumes th->window stays fixed. 3344 * 3345 * Strictly speaking, keeping th->window fixed violates the receiver 3346 * side SWS prevention criteria. The problem is that under this rule 3347 * a stream of single byte packets will cause the right side of the 3348 * window to always advance by a single byte. 3349 * 3350 * Of course, if the sender implements sender side SWS prevention 3351 * then this will not be a problem. 3352 * 3353 * BSD seems to make the following compromise: 3354 * 3355 * If the free space is less than the 1/4 of the maximum 3356 * space available and the free space is less than 1/2 mss, 3357 * then set the window to 0. 3358 * [ Actually, bsd uses MSS and 1/4 of maximal _window_ ] 3359 * Otherwise, just prevent the window from shrinking 3360 * and from being larger than the largest representable value. 3361 * 3362 * This prevents incremental opening of the window in the regime 3363 * where TCP is limited by the speed of the reader side taking 3364 * data out of the TCP receive queue. It does nothing about 3365 * those cases where the window is constrained on the sender side 3366 * because the pipeline is full. 3367 * 3368 * BSD also seems to "accidentally" limit itself to windows that are a 3369 * multiple of MSS, at least until the free space gets quite small. 3370 * This would appear to be a side effect of the mbuf implementation. 3371 * Combining these two algorithms results in the observed behavior 3372 * of having a fixed window size at almost all times. 3373 * 3374 * Below we obtain similar behavior by forcing the offered window to 3375 * a multiple of the mss when it is feasible to do so. 3376 * 3377 * Note, we don't "adjust" for TIMESTAMP or SACK option bytes. 3378 * Regular options like TIMESTAMP are taken into account. 3379 */ 3380 u32 __tcp_select_window(struct sock *sk) 3381 { 3382 struct inet_connection_sock *icsk = inet_csk(sk); 3383 struct tcp_sock *tp = tcp_sk(sk); 3384 struct net *net = sock_net(sk); 3385 /* MSS for the peer's data. Previous versions used mss_clamp 3386 * here. I don't know if the value based on our guesses 3387 * of peer's MSS is better for the performance. It's more correct 3388 * but may be worse for the performance because of rcv_mss 3389 * fluctuations. --SAW 1998/11/1 3390 */ 3391 int mss = icsk->icsk_ack.rcv_mss; 3392 int free_space = tcp_space(sk); 3393 int allowed_space = tcp_full_space(sk); 3394 int full_space, window; 3395 3396 if (sk_is_mptcp(sk)) 3397 mptcp_space(sk, &free_space, &allowed_space); 3398 3399 full_space = min_t(int, tp->window_clamp, allowed_space); 3400 3401 if (unlikely(mss > full_space)) { 3402 mss = full_space; 3403 if (mss <= 0) 3404 return 0; 3405 } 3406 3407 /* Only allow window shrink if the sysctl is enabled and we have 3408 * a non-zero scaling factor in effect. 3409 */ 3410 if (READ_ONCE(net->ipv4.sysctl_tcp_shrink_window) && tp->rx_opt.rcv_wscale) 3411 goto shrink_window_allowed; 3412 3413 /* do not allow window to shrink */ 3414 3415 if (free_space < (full_space >> 1)) { 3416 icsk->icsk_ack.quick = 0; 3417 3418 if (tcp_under_memory_pressure(sk)) 3419 tcp_adjust_rcv_ssthresh(sk); 3420 3421 /* free_space might become our new window, make sure we don't 3422 * increase it due to wscale. 3423 */ 3424 free_space = round_down(free_space, 1 << tp->rx_opt.rcv_wscale); 3425 3426 /* if free space is less than mss estimate, or is below 1/16th 3427 * of the maximum allowed, try to move to zero-window, else 3428 * tcp_clamp_window() will grow rcv buf up to tcp_rmem[2], and 3429 * new incoming data is dropped due to memory limits. 3430 * With large window, mss test triggers way too late in order 3431 * to announce zero window in time before rmem limit kicks in. 3432 */ 3433 if (free_space < (allowed_space >> 4) || free_space < mss) 3434 return 0; 3435 } 3436 3437 if (free_space > tp->rcv_ssthresh) 3438 free_space = tp->rcv_ssthresh; 3439 3440 /* Don't do rounding if we are using window scaling, since the 3441 * scaled window will not line up with the MSS boundary anyway. 3442 */ 3443 if (tp->rx_opt.rcv_wscale) { 3444 window = free_space; 3445 3446 /* Advertise enough space so that it won't get scaled away. 3447 * Import case: prevent zero window announcement if 3448 * 1<<rcv_wscale > mss. 3449 */ 3450 window = ALIGN(window, (1 << tp->rx_opt.rcv_wscale)); 3451 } else { 3452 window = tp->rcv_wnd; 3453 /* Get the largest window that is a nice multiple of mss. 3454 * Window clamp already applied above. 3455 * If our current window offering is within 1 mss of the 3456 * free space we just keep it. This prevents the divide 3457 * and multiply from happening most of the time. 3458 * We also don't do any window rounding when the free space 3459 * is too small. 3460 */ 3461 if (window <= free_space - mss || window > free_space) 3462 window = rounddown(free_space, mss); 3463 else if (mss == full_space && 3464 free_space > window + (full_space >> 1)) 3465 window = free_space; 3466 } 3467 3468 return window; 3469 3470 shrink_window_allowed: 3471 /* new window should always be an exact multiple of scaling factor */ 3472 free_space = round_down(free_space, 1 << tp->rx_opt.rcv_wscale); 3473 3474 if (free_space < (full_space >> 1)) { 3475 icsk->icsk_ack.quick = 0; 3476 3477 if (tcp_under_memory_pressure(sk)) 3478 tcp_adjust_rcv_ssthresh(sk); 3479 3480 /* if free space is too low, return a zero window */ 3481 if (free_space < (allowed_space >> 4) || free_space < mss || 3482 free_space < (1 << tp->rx_opt.rcv_wscale)) 3483 return 0; 3484 } 3485 3486 if (free_space > tp->rcv_ssthresh) { 3487 free_space = tp->rcv_ssthresh; 3488 /* new window should always be an exact multiple of scaling factor 3489 * 3490 * For this case, we ALIGN "up" (increase free_space) because 3491 * we know free_space is not zero here, it has been reduced from 3492 * the memory-based limit, and rcv_ssthresh is not a hard limit 3493 * (unlike sk_rcvbuf). 3494 */ 3495 free_space = ALIGN(free_space, (1 << tp->rx_opt.rcv_wscale)); 3496 } 3497 3498 return free_space; 3499 } 3500 3501 void tcp_skb_collapse_tstamp(struct sk_buff *skb, 3502 const struct sk_buff *next_skb) 3503 { 3504 if (unlikely(tcp_has_tx_tstamp(next_skb))) { 3505 const struct skb_shared_info *next_shinfo = 3506 skb_shinfo(next_skb); 3507 struct skb_shared_info *shinfo = skb_shinfo(skb); 3508 3509 shinfo->tx_flags |= next_shinfo->tx_flags & SKBTX_ANY_TSTAMP; 3510 shinfo->tskey = next_shinfo->tskey; 3511 TCP_SKB_CB(skb)->txstamp_ack |= 3512 TCP_SKB_CB(next_skb)->txstamp_ack; 3513 } 3514 } 3515 3516 /* Collapses two adjacent SKB's during retransmission. */ 3517 static bool tcp_collapse_retrans(struct sock *sk, struct sk_buff *skb) 3518 { 3519 struct tcp_sock *tp = tcp_sk(sk); 3520 struct sk_buff *next_skb = skb_rb_next(skb); 3521 int next_skb_size; 3522 3523 next_skb_size = next_skb->len; 3524 3525 BUG_ON(tcp_skb_pcount(skb) != 1 || tcp_skb_pcount(next_skb) != 1); 3526 3527 if (next_skb_size && !tcp_skb_shift(skb, next_skb, 1, next_skb_size)) 3528 return false; 3529 3530 tcp_highest_sack_replace(sk, next_skb, skb); 3531 3532 /* Update sequence range on original skb. */ 3533 TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(next_skb)->end_seq; 3534 3535 /* Merge over control information. This moves PSH/FIN etc. over */ 3536 TCP_SKB_CB(skb)->tcp_flags |= TCP_SKB_CB(next_skb)->tcp_flags; 3537 3538 /* All done, get rid of second SKB and account for it so 3539 * packet counting does not break. 3540 */ 3541 TCP_SKB_CB(skb)->sacked |= TCP_SKB_CB(next_skb)->sacked & TCPCB_EVER_RETRANS; 3542 TCP_SKB_CB(skb)->eor = TCP_SKB_CB(next_skb)->eor; 3543 3544 /* changed transmit queue under us so clear hints */ 3545 if (next_skb == tp->retransmit_skb_hint) 3546 tp->retransmit_skb_hint = skb; 3547 3548 tcp_adjust_pcount(sk, next_skb, tcp_skb_pcount(next_skb)); 3549 3550 tcp_skb_collapse_tstamp(skb, next_skb); 3551 3552 tcp_rtx_queue_unlink_and_free(next_skb, sk); 3553 return true; 3554 } 3555 3556 /* Check if coalescing SKBs is legal. */ 3557 static bool tcp_can_collapse(const struct sock *sk, const struct sk_buff *skb) 3558 { 3559 if (tcp_skb_pcount(skb) > 1) 3560 return false; 3561 if (skb_cloned(skb)) 3562 return false; 3563 if (!skb_frags_readable(skb)) 3564 return false; 3565 /* Some heuristics for collapsing over SACK'd could be invented */ 3566 if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED) 3567 return false; 3568 3569 return true; 3570 } 3571 3572 /* Collapse packets in the retransmit queue to make to create 3573 * less packets on the wire. This is only done on retransmission. 3574 */ 3575 static void tcp_retrans_try_collapse(struct sock *sk, struct sk_buff *to, 3576 int space) 3577 { 3578 struct tcp_sock *tp = tcp_sk(sk); 3579 struct sk_buff *skb = to, *tmp; 3580 bool first = true; 3581 3582 if (!READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_retrans_collapse)) 3583 return; 3584 if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN) 3585 return; 3586 3587 skb_rbtree_walk_from_safe(skb, tmp) { 3588 if (!tcp_can_collapse(sk, skb)) 3589 break; 3590 3591 if (!tcp_skb_can_collapse(to, skb)) 3592 break; 3593 3594 space -= skb->len; 3595 3596 if (first) { 3597 first = false; 3598 continue; 3599 } 3600 3601 if (space < 0) 3602 break; 3603 3604 if (after(TCP_SKB_CB(skb)->end_seq, tcp_wnd_end(tp))) 3605 break; 3606 3607 if (!tcp_collapse_retrans(sk, to)) 3608 break; 3609 } 3610 } 3611 3612 /* This retransmits one SKB. Policy decisions and retransmit queue 3613 * state updates are done by the caller. Returns non-zero if an 3614 * error occurred which prevented the send. 3615 */ 3616 int __tcp_retransmit_skb(struct sock *sk, struct sk_buff *skb, int segs) 3617 { 3618 struct inet_connection_sock *icsk = inet_csk(sk); 3619 struct tcp_sock *tp = tcp_sk(sk); 3620 unsigned int cur_mss; 3621 int diff, len, err; 3622 int avail_wnd; 3623 3624 /* Inconclusive MTU probe */ 3625 if (icsk->icsk_mtup.probe_size) 3626 icsk->icsk_mtup.probe_size = 0; 3627 3628 if (skb_still_in_host_queue(sk, skb)) { 3629 err = -EBUSY; 3630 goto out; 3631 } 3632 3633 start: 3634 if (before(TCP_SKB_CB(skb)->seq, tp->snd_una)) { 3635 if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) { 3636 TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_SYN; 3637 TCP_SKB_CB(skb)->seq++; 3638 goto start; 3639 } 3640 if (unlikely(before(TCP_SKB_CB(skb)->end_seq, tp->snd_una))) { 3641 WARN_ON_ONCE(1); 3642 err = -EINVAL; 3643 goto out; 3644 } 3645 if (tcp_trim_head(sk, skb, tp->snd_una - TCP_SKB_CB(skb)->seq)) { 3646 err = -ENOMEM; 3647 goto out; 3648 } 3649 } 3650 3651 if (inet_csk(sk)->icsk_af_ops->rebuild_header(sk)) { 3652 err = -EHOSTUNREACH; /* Routing failure or similar. */ 3653 goto out; 3654 } 3655 3656 cur_mss = tcp_current_mss(sk); 3657 avail_wnd = tcp_wnd_end(tp) - TCP_SKB_CB(skb)->seq; 3658 3659 /* If receiver has shrunk his window, and skb is out of 3660 * new window, do not retransmit it. The exception is the 3661 * case, when window is shrunk to zero. In this case 3662 * our retransmit of one segment serves as a zero window probe. 3663 */ 3664 if (avail_wnd <= 0) { 3665 if (TCP_SKB_CB(skb)->seq != tp->snd_una) { 3666 err = -EAGAIN; 3667 goto out; 3668 } 3669 avail_wnd = cur_mss; 3670 } 3671 3672 len = cur_mss * (tcp_urg_mode(tp) ? 1 : segs); 3673 if (len > avail_wnd) { 3674 len = rounddown(avail_wnd, cur_mss); 3675 if (!len) 3676 len = avail_wnd; 3677 } 3678 if (skb->len > len) { 3679 if (tcp_fragment(sk, TCP_FRAG_IN_RTX_QUEUE, skb, len, 3680 cur_mss, GFP_ATOMIC)) { 3681 err = -ENOMEM; /* We'll try again later. */ 3682 goto out; 3683 } 3684 } else { 3685 if (skb_unclone_keeptruesize(skb, GFP_ATOMIC)) { 3686 err = -ENOMEM; 3687 goto out; 3688 } 3689 3690 diff = tcp_skb_pcount(skb); 3691 tcp_set_skb_tso_segs(skb, cur_mss); 3692 diff -= tcp_skb_pcount(skb); 3693 if (diff) 3694 tcp_adjust_pcount(sk, skb, diff); 3695 avail_wnd = min_t(int, avail_wnd, cur_mss); 3696 if (skb->len < avail_wnd) 3697 tcp_retrans_try_collapse(sk, skb, avail_wnd); 3698 } 3699 3700 if (!tcp_ecn_mode_pending(tp) || icsk->icsk_retransmits > 1) { 3701 /* RFC3168, section 6.1.1.1. ECN fallback 3702 * As AccECN uses the same SYN flags (+ AE), this check 3703 * covers both cases. 3704 */ 3705 if ((TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN_ECN) == 3706 TCPHDR_SYN_ECN) 3707 tcp_ecn_clear_syn(sk, skb); 3708 } 3709 3710 /* Update global and local TCP statistics. */ 3711 segs = tcp_skb_pcount(skb); 3712 TCP_ADD_STATS(sock_net(sk), TCP_MIB_RETRANSSEGS, segs); 3713 if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN) 3714 __NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPSYNRETRANS); 3715 WRITE_ONCE(tp->total_retrans, tp->total_retrans + segs); 3716 WRITE_ONCE(tp->bytes_retrans, tp->bytes_retrans + skb->len); 3717 3718 /* make sure skb->data is aligned on arches that require it 3719 * and check if ack-trimming & collapsing extended the headroom 3720 * beyond what csum_start can cover. 3721 */ 3722 if (unlikely((NET_IP_ALIGN && ((unsigned long)skb->data & 3)) || 3723 skb_headroom(skb) >= 0xFFFF)) { 3724 struct sk_buff *nskb; 3725 3726 tcp_skb_tsorted_save(skb) { 3727 nskb = __pskb_copy(skb, MAX_TCP_HEADER, GFP_ATOMIC); 3728 if (nskb) { 3729 nskb->dev = NULL; 3730 err = tcp_transmit_skb(sk, nskb, 0, GFP_ATOMIC); 3731 } else { 3732 err = -ENOBUFS; 3733 } 3734 } tcp_skb_tsorted_restore(skb); 3735 3736 if (!err) { 3737 tcp_update_skb_after_send(sk, skb, tp->tcp_wstamp_ns); 3738 tcp_rate_skb_sent(sk, skb); 3739 } 3740 } else { 3741 err = tcp_transmit_skb(sk, skb, 1, GFP_ATOMIC); 3742 } 3743 3744 tcp_call_bpf_flag(sk, BPF_SOCK_OPS_RETRANS_CB, 3745 TCP_SKB_CB(skb)->seq, segs, err); 3746 bpf_tcp_ops_call(retrans, sk, skb, err); 3747 3748 if (unlikely(err) && err != -EBUSY) 3749 NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPRETRANSFAIL, segs); 3750 3751 /* To avoid taking spuriously low RTT samples based on a timestamp 3752 * for a transmit that never happened, always mark EVER_RETRANS 3753 */ 3754 TCP_SKB_CB(skb)->sacked |= TCPCB_EVER_RETRANS; 3755 3756 out: 3757 trace_tcp_retransmit_skb(sk, skb, err); 3758 return err; 3759 } 3760 3761 int tcp_retransmit_skb(struct sock *sk, struct sk_buff *skb, int segs) 3762 { 3763 struct tcp_sock *tp = tcp_sk(sk); 3764 int err = __tcp_retransmit_skb(sk, skb, segs); 3765 3766 if (err == 0) { 3767 #if FASTRETRANS_DEBUG > 0 3768 if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS) { 3769 net_dbg_ratelimited("retrans_out leaked\n"); 3770 } 3771 #endif 3772 TCP_SKB_CB(skb)->sacked |= TCPCB_RETRANS; 3773 tp->retrans_out += tcp_skb_pcount(skb); 3774 } 3775 3776 /* Save stamp of the first (attempted) retransmit. */ 3777 if (!tp->retrans_stamp) 3778 tp->retrans_stamp = tcp_skb_timestamp_ts(tp->tcp_usec_ts, skb); 3779 3780 if (tp->undo_retrans < 0) 3781 tp->undo_retrans = 0; 3782 tp->undo_retrans += tcp_skb_pcount(skb); 3783 return err; 3784 } 3785 3786 /* This gets called after a retransmit timeout, and the initially 3787 * retransmitted data is acknowledged. It tries to continue 3788 * resending the rest of the retransmit queue, until either 3789 * we've sent it all or the congestion window limit is reached. 3790 */ 3791 void tcp_xmit_retransmit_queue(struct sock *sk) 3792 { 3793 const struct inet_connection_sock *icsk = inet_csk(sk); 3794 struct sk_buff *skb, *rtx_head, *hole = NULL; 3795 struct tcp_sock *tp = tcp_sk(sk); 3796 bool rearm_timer = false; 3797 u32 max_segs; 3798 int mib_idx; 3799 3800 if (!tp->packets_out) 3801 return; 3802 3803 rtx_head = tcp_rtx_queue_head(sk); 3804 skb = tp->retransmit_skb_hint ?: rtx_head; 3805 max_segs = tcp_tso_segs(sk, tcp_current_mss(sk)); 3806 skb_rbtree_walk_from(skb) { 3807 __u8 sacked; 3808 int segs; 3809 3810 if (tcp_pacing_check(sk)) 3811 break; 3812 3813 /* we could do better than to assign each time */ 3814 if (!hole) 3815 tp->retransmit_skb_hint = skb; 3816 3817 segs = tcp_snd_cwnd(tp) - tcp_packets_in_flight(tp); 3818 if (segs <= 0) 3819 break; 3820 sacked = TCP_SKB_CB(skb)->sacked; 3821 /* In case tcp_shift_skb_data() have aggregated large skbs, 3822 * we need to make sure not sending too bigs TSO packets 3823 */ 3824 segs = min_t(int, segs, max_segs); 3825 3826 if (tp->retrans_out >= tp->lost_out) { 3827 break; 3828 } else if (!(sacked & TCPCB_LOST)) { 3829 if (!hole && !(sacked & (TCPCB_SACKED_RETRANS|TCPCB_SACKED_ACKED))) 3830 hole = skb; 3831 continue; 3832 3833 } else { 3834 if (icsk->icsk_ca_state != TCP_CA_Loss) 3835 mib_idx = LINUX_MIB_TCPFASTRETRANS; 3836 else 3837 mib_idx = LINUX_MIB_TCPSLOWSTARTRETRANS; 3838 } 3839 3840 if (sacked & (TCPCB_SACKED_ACKED|TCPCB_SACKED_RETRANS)) 3841 continue; 3842 3843 if (tcp_small_queue_check(sk, skb, 1)) 3844 break; 3845 3846 if (tcp_retransmit_skb(sk, skb, segs)) 3847 break; 3848 3849 NET_ADD_STATS(sock_net(sk), mib_idx, tcp_skb_pcount(skb)); 3850 3851 if (tcp_in_cwnd_reduction(sk)) 3852 tp->prr_out += tcp_skb_pcount(skb); 3853 3854 if (skb == rtx_head && 3855 icsk->icsk_pending != ICSK_TIME_REO_TIMEOUT) 3856 rearm_timer = true; 3857 3858 } 3859 if (rearm_timer) 3860 tcp_reset_xmit_timer(sk, ICSK_TIME_RETRANS, 3861 inet_csk(sk)->icsk_rto, true); 3862 } 3863 3864 /* Send a FIN. The caller locks the socket for us. 3865 * We should try to send a FIN packet really hard, but eventually give up. 3866 */ 3867 void tcp_send_fin(struct sock *sk) 3868 { 3869 struct sk_buff *skb, *tskb, *tail = tcp_write_queue_tail(sk); 3870 struct tcp_sock *tp = tcp_sk(sk); 3871 3872 /* Optimization, tack on the FIN if we have one skb in write queue and 3873 * this skb was not yet sent, or we are under memory pressure. 3874 * Note: in the latter case, FIN packet will be sent after a timeout, 3875 * as TCP stack thinks it has already been transmitted. 3876 */ 3877 tskb = tail; 3878 if (!tskb && tcp_under_memory_pressure(sk)) 3879 tskb = skb_rb_last(&sk->tcp_rtx_queue); 3880 3881 if (tskb) { 3882 TCP_SKB_CB(tskb)->tcp_flags |= TCPHDR_FIN; 3883 TCP_SKB_CB(tskb)->end_seq++; 3884 tp->write_seq++; 3885 if (!tail) { 3886 /* This means tskb was already sent. 3887 * Pretend we included the FIN on previous transmit. 3888 * We need to set tp->snd_nxt to the value it would have 3889 * if FIN had been sent. This is because retransmit path 3890 * does not change tp->snd_nxt. 3891 */ 3892 WRITE_ONCE(tp->snd_nxt, tp->snd_nxt + 1); 3893 return; 3894 } 3895 } else { 3896 skb = alloc_skb_fclone(MAX_TCP_HEADER, 3897 sk_gfp_mask(sk, GFP_ATOMIC | 3898 __GFP_NOWARN)); 3899 if (unlikely(!skb)) 3900 return; 3901 3902 INIT_LIST_HEAD(&skb->tcp_tsorted_anchor); 3903 skb_reserve(skb, MAX_TCP_HEADER); 3904 sk_forced_mem_schedule(sk, skb->truesize); 3905 /* FIN eats a sequence byte, write_seq advanced by tcp_queue_skb(). */ 3906 tcp_init_nondata_skb(skb, sk, tp->write_seq, 3907 TCPHDR_ACK | TCPHDR_FIN); 3908 tcp_queue_skb(sk, skb); 3909 } 3910 __tcp_push_pending_frames(sk, tcp_current_mss(sk), TCP_NAGLE_OFF); 3911 } 3912 3913 /* We get here when a process closes a file descriptor (either due to 3914 * an explicit close() or as a byproduct of exit()'ing) and there 3915 * was unread data in the receive queue. This behavior is recommended 3916 * by RFC 2525, section 2.17. -DaveM 3917 */ 3918 void tcp_send_active_reset(struct sock *sk, enum sk_rst_reason reason) 3919 { 3920 gfp_t priority = sk_gfp_mask(sk, GFP_ATOMIC | __GFP_NOWARN); 3921 struct sk_buff *skb; 3922 3923 TCP_INC_STATS(sock_net(sk), TCP_MIB_OUTRSTS); 3924 3925 /* NOTE: No TCP options attached and we never retransmit this. */ 3926 skb = alloc_skb(MAX_TCP_HEADER, priority); 3927 if (!skb) { 3928 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTFAILED); 3929 return; 3930 } 3931 3932 /* Reserve space for headers and prepare control bits. */ 3933 skb_reserve(skb, MAX_TCP_HEADER); 3934 tcp_init_nondata_skb(skb, sk, tcp_acceptable_seq(sk), 3935 TCPHDR_ACK | TCPHDR_RST); 3936 tcp_mstamp_refresh(tcp_sk(sk)); 3937 /* Send it off. */ 3938 if (tcp_transmit_skb(sk, skb, 0, priority)) 3939 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTFAILED); 3940 3941 /* skb of trace_tcp_send_reset() keeps the skb that caused RST, 3942 * skb here is different to the troublesome skb, so use NULL 3943 */ 3944 trace_tcp_send_reset(sk, NULL, reason); 3945 } 3946 3947 /* Send a crossed SYN-ACK during socket establishment. 3948 * WARNING: This routine must only be called when we have already sent 3949 * a SYN packet that crossed the incoming SYN that caused this routine 3950 * to get called. If this assumption fails then the initial rcv_wnd 3951 * and rcv_wscale values will not be correct. 3952 */ 3953 int tcp_send_synack(struct sock *sk) 3954 { 3955 struct tcp_sock *tp = tcp_sk(sk); 3956 struct sk_buff *skb; 3957 3958 skb = tcp_rtx_queue_head(sk); 3959 if (!skb || !(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) { 3960 pr_err("%s: wrong queue state\n", __func__); 3961 return -EFAULT; 3962 } 3963 if (!(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_ACK)) { 3964 if (skb_cloned(skb)) { 3965 struct sk_buff *nskb; 3966 3967 tcp_skb_tsorted_save(skb) { 3968 nskb = skb_copy(skb, GFP_ATOMIC); 3969 } tcp_skb_tsorted_restore(skb); 3970 if (!nskb) 3971 return -ENOMEM; 3972 INIT_LIST_HEAD(&nskb->tcp_tsorted_anchor); 3973 if (skb == tp->retransmit_skb_hint) 3974 tp->retransmit_skb_hint = nskb; 3975 tcp_highest_sack_replace(sk, skb, nskb); 3976 tcp_rtx_queue_unlink_and_free(skb, sk); 3977 __skb_header_release(nskb); 3978 tcp_rbtree_insert(&sk->tcp_rtx_queue, nskb); 3979 sk_wmem_queued_add(sk, nskb->truesize); 3980 sk_mem_charge(sk, nskb->truesize); 3981 skb = nskb; 3982 } 3983 3984 TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_ACK; 3985 tcp_ecn_send_synack(sk, skb); 3986 } 3987 return tcp_transmit_skb(sk, skb, 1, GFP_ATOMIC); 3988 } 3989 3990 /** 3991 * tcp_make_synack - Allocate one skb and build a SYNACK packet. 3992 * @sk: listener socket 3993 * @dst: dst entry attached to the SYNACK. It is consumed and caller 3994 * should not use it again. 3995 * @req: request_sock pointer 3996 * @foc: cookie for tcp fast open 3997 * @synack_type: Type of synack to prepare 3998 * @syn_skb: SYN packet just received. It could be NULL for rtx case. 3999 */ 4000 struct sk_buff *tcp_make_synack(const struct sock *sk, struct dst_entry *dst, 4001 struct request_sock *req, 4002 struct tcp_fastopen_cookie *foc, 4003 enum tcp_synack_type synack_type, 4004 struct sk_buff *syn_skb) 4005 { 4006 struct inet_request_sock *ireq = inet_rsk(req); 4007 const struct tcp_sock *tp = tcp_sk(sk); 4008 struct tcp_out_options opts; 4009 struct tcp_key key = {}; 4010 struct sk_buff *skb; 4011 int tcp_header_size; 4012 struct tcphdr *th; 4013 int mss; 4014 u64 now; 4015 4016 skb = alloc_skb(MAX_TCP_HEADER, GFP_ATOMIC); 4017 if (unlikely(!skb)) { 4018 dst_release(dst); 4019 return NULL; 4020 } 4021 /* Reserve space for headers. */ 4022 skb_reserve(skb, MAX_TCP_HEADER); 4023 4024 switch (synack_type) { 4025 case TCP_SYNACK_NORMAL: 4026 case TCP_SYNACK_RETRANS: 4027 skb_set_owner_edemux(skb, req_to_sk(req)); 4028 break; 4029 case TCP_SYNACK_COOKIE: 4030 /* Under synflood, we do not attach skb to a socket, 4031 * to avoid false sharing. 4032 */ 4033 break; 4034 case TCP_SYNACK_FASTOPEN: 4035 /* sk is a const pointer, because we want to express multiple 4036 * cpu might call us concurrently. 4037 * sk->sk_wmem_alloc in an atomic, we can promote to rw. 4038 */ 4039 skb_set_owner_w(skb, (struct sock *)sk); 4040 break; 4041 } 4042 skb_dst_set(skb, dst); 4043 4044 mss = tcp_mss_clamp(tp, tcp_dst_advmss(dst)); 4045 4046 memset(&opts, 0, sizeof(opts)); 4047 now = tcp_clock_ns(); 4048 #ifdef CONFIG_SYN_COOKIES 4049 if (unlikely(synack_type == TCP_SYNACK_COOKIE && ireq->tstamp_ok)) 4050 skb_set_delivery_time(skb, cookie_init_timestamp(req, now), 4051 SKB_CLOCK_MONOTONIC); 4052 else 4053 #endif 4054 { 4055 skb_set_delivery_time(skb, now, SKB_CLOCK_MONOTONIC); 4056 if (!tcp_rsk(req)->snt_synack) /* Timestamp first SYNACK */ 4057 tcp_rsk(req)->snt_synack = tcp_skb_timestamp_us(skb); 4058 } 4059 4060 #if defined(CONFIG_TCP_MD5SIG) || defined(CONFIG_TCP_AO) 4061 rcu_read_lock(); 4062 #endif 4063 if (tcp_rsk_used_ao(req)) { 4064 #ifdef CONFIG_TCP_AO 4065 struct tcp_ao_key *ao_key = NULL; 4066 u8 keyid = tcp_rsk(req)->ao_keyid; 4067 u8 rnext = tcp_rsk(req)->ao_rcv_next; 4068 4069 ao_key = tcp_sk(sk)->af_specific->ao_lookup(sk, req_to_sk(req), 4070 keyid, -1); 4071 /* If there is no matching key - avoid sending anything, 4072 * especially usigned segments. It could try harder and lookup 4073 * for another peer-matching key, but the peer has requested 4074 * ao_keyid (RFC5925 RNextKeyID), so let's keep it simple here. 4075 */ 4076 if (unlikely(!ao_key)) { 4077 trace_tcp_ao_synack_no_key(sk, keyid, rnext); 4078 rcu_read_unlock(); 4079 kfree_skb(skb); 4080 net_warn_ratelimited("TCP-AO: the keyid %u from SYN packet is not present - not sending SYNACK\n", 4081 keyid); 4082 return NULL; 4083 } 4084 key.ao_key = ao_key; 4085 key.type = TCP_KEY_AO; 4086 #endif 4087 } else { 4088 #ifdef CONFIG_TCP_MD5SIG 4089 key.md5_key = tcp_rsk(req)->af_specific->req_md5_lookup(sk, 4090 req_to_sk(req)); 4091 if (key.md5_key) 4092 key.type = TCP_KEY_MD5; 4093 #endif 4094 } 4095 skb_set_hash(skb, READ_ONCE(tcp_rsk(req)->txhash), PKT_HASH_TYPE_L4); 4096 /* bpf program will be interested in the tcp_flags */ 4097 TCP_SKB_CB(skb)->tcp_flags = TCPHDR_SYN | TCPHDR_ACK; 4098 tcp_header_size = tcp_synack_options(sk, req, mss, skb, &opts, 4099 &key, foc, synack_type, syn_skb) 4100 + sizeof(*th); 4101 4102 skb_push(skb, tcp_header_size); 4103 skb_reset_transport_header(skb); 4104 4105 th = (struct tcphdr *)skb->data; 4106 memset(th, 0, sizeof(struct tcphdr)); 4107 th->syn = 1; 4108 th->ack = 1; 4109 tcp_ecn_make_synack(req, th, synack_type); 4110 th->source = htons(ireq->ir_num); 4111 th->dest = ireq->ir_rmt_port; 4112 skb->mark = ireq->ir_mark; 4113 skb->ip_summed = CHECKSUM_PARTIAL; 4114 th->seq = htonl(tcp_rsk(req)->snt_isn); 4115 /* XXX data is queued and acked as is. No buffer/window check */ 4116 th->ack_seq = htonl(tcp_rsk(req)->rcv_nxt); 4117 4118 /* RFC1323: The window in SYN & SYN/ACK segments is never scaled. */ 4119 th->window = htons(min(req->rsk_rcv_wnd, 65535U)); 4120 tcp_options_write(th, NULL, tcp_rsk(req), &opts, &key); 4121 th->doff = (tcp_header_size >> 2); 4122 TCP_INC_STATS(sock_net(sk), TCP_MIB_OUTSEGS); 4123 4124 /* Okay, we have all we need - do the md5 hash if needed */ 4125 if (tcp_key_is_md5(&key)) { 4126 #ifdef CONFIG_TCP_MD5SIG 4127 tcp_rsk(req)->af_specific->calc_md5_hash(opts.hash_location, 4128 key.md5_key, req_to_sk(req), skb); 4129 #endif 4130 } else if (tcp_key_is_ao(&key)) { 4131 #ifdef CONFIG_TCP_AO 4132 tcp_rsk(req)->af_specific->ao_synack_hash(opts.hash_location, 4133 key.ao_key, req, skb, 4134 opts.hash_location - (u8 *)th, 0); 4135 #endif 4136 } 4137 #if defined(CONFIG_TCP_MD5SIG) || defined(CONFIG_TCP_AO) 4138 rcu_read_unlock(); 4139 #endif 4140 4141 bpf_skops_write_hdr_opt((struct sock *)sk, skb, req, syn_skb, 4142 synack_type, &opts); 4143 4144 skb_set_delivery_time(skb, now, SKB_CLOCK_MONOTONIC); 4145 tcp_add_tx_delay(skb, tp); 4146 4147 return skb; 4148 } 4149 4150 static void tcp_ca_dst_init(struct sock *sk, const struct dst_entry *dst) 4151 { 4152 struct inet_connection_sock *icsk = inet_csk(sk); 4153 const struct tcp_congestion_ops *ca; 4154 u32 ca_key = dst_metric(dst, RTAX_CC_ALGO); 4155 4156 if (ca_key == TCP_CA_UNSPEC) 4157 return; 4158 4159 rcu_read_lock(); 4160 ca = tcp_ca_find_key(ca_key); 4161 if (likely(ca && bpf_try_module_get(ca, ca->owner))) { 4162 bpf_module_put(icsk->icsk_ca_ops, icsk->icsk_ca_ops->owner); 4163 icsk->icsk_ca_dst_locked = tcp_ca_dst_locked(dst); 4164 WRITE_ONCE(icsk->icsk_ca_ops, ca); 4165 } 4166 rcu_read_unlock(); 4167 } 4168 4169 /* Do all connect socket setups that can be done AF independent. */ 4170 static void tcp_connect_init(struct sock *sk) 4171 { 4172 const struct dst_entry *dst = __sk_dst_get(sk); 4173 struct tcp_sock *tp = tcp_sk(sk); 4174 __u8 rcv_wscale; 4175 int full_space; 4176 u16 user_mss; 4177 u32 rcv_wnd; 4178 4179 /* We'll fix this up when we get a response from the other end. 4180 * See tcp_input.c:tcp_rcv_state_process case TCP_SYN_SENT. 4181 */ 4182 tp->tcp_header_len = sizeof(struct tcphdr); 4183 if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_timestamps)) 4184 tp->tcp_header_len += TCPOLEN_TSTAMP_ALIGNED; 4185 4186 tcp_ao_connect_init(sk); 4187 4188 /* If user gave his TCP_MAXSEG, record it to clamp */ 4189 user_mss = READ_ONCE(tp->rx_opt.user_mss); 4190 if (user_mss) 4191 tp->rx_opt.mss_clamp = user_mss; 4192 tp->max_window = 0; 4193 tcp_mtup_init(sk); 4194 tcp_sync_mss(sk, dst_mtu(dst)); 4195 4196 tcp_ca_dst_init(sk, dst); 4197 4198 if (!tp->window_clamp) 4199 WRITE_ONCE(tp->window_clamp, dst_metric(dst, RTAX_WINDOW)); 4200 tp->advmss = tcp_mss_clamp(tp, tcp_dst_advmss(dst)); 4201 4202 tcp_initialize_rcv_mss(sk); 4203 4204 /* limit the window selection if the user enforce a smaller rx buffer */ 4205 if (sk->sk_userlocks & SOCK_RCVBUF_LOCK && 4206 (tp->window_clamp > tcp_full_space(sk) || tp->window_clamp == 0)) 4207 WRITE_ONCE(tp->window_clamp, tcp_full_space(sk)); 4208 4209 rcv_wnd = tcp_rwnd_init_bpf(sk); 4210 full_space = tcp_full_space(sk); 4211 if (rcv_wnd == 0) 4212 rcv_wnd = dst_metric(dst, RTAX_INITRWND); 4213 else if (full_space < (u64)rcv_wnd * tp->advmss) 4214 full_space = min_t(u64, (u64)rcv_wnd * tp->advmss, INT_MAX); 4215 4216 tcp_select_initial_window(sk, full_space, 4217 tp->advmss - (tp->rx_opt.ts_recent_stamp ? tp->tcp_header_len - sizeof(struct tcphdr) : 0), 4218 &tp->rcv_wnd, 4219 &tp->window_clamp, 4220 READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_window_scaling), 4221 &rcv_wscale, 4222 rcv_wnd); 4223 4224 tp->rx_opt.rcv_wscale = rcv_wscale; 4225 tp->rcv_ssthresh = tp->rcv_wnd; 4226 4227 WRITE_ONCE(sk->sk_err, 0); 4228 sock_reset_flag(sk, SOCK_DONE); 4229 tp->snd_wnd = 0; 4230 tcp_init_wl(tp, 0); 4231 tcp_write_queue_purge(sk); 4232 WRITE_ONCE(tp->snd_una, tp->write_seq); 4233 tp->snd_sml = tp->write_seq; 4234 tp->snd_up = tp->write_seq; 4235 WRITE_ONCE(tp->snd_nxt, tp->write_seq); 4236 4237 if (likely(!tp->repair)) 4238 tp->rcv_nxt = 0; 4239 else 4240 tp->rcv_tstamp = tcp_jiffies32; 4241 tp->rcv_wup = tp->rcv_nxt; 4242 tp->rcv_mwnd_seq = tp->rcv_nxt + tp->rcv_wnd; 4243 WRITE_ONCE(tp->copied_seq, tp->rcv_nxt); 4244 4245 inet_csk(sk)->icsk_rto = tcp_timeout_init(sk); 4246 WRITE_ONCE(inet_csk(sk)->icsk_retransmits, 0); 4247 tcp_clear_retrans(tp); 4248 } 4249 4250 static void tcp_connect_queue_skb(struct sock *sk, struct sk_buff *skb) 4251 { 4252 struct tcp_sock *tp = tcp_sk(sk); 4253 struct tcp_skb_cb *tcb = TCP_SKB_CB(skb); 4254 4255 tcb->end_seq += skb->len; 4256 __skb_header_release(skb); 4257 sk_wmem_queued_add(sk, skb->truesize); 4258 sk_mem_charge(sk, skb->truesize); 4259 WRITE_ONCE(tp->write_seq, tcb->end_seq); 4260 tp->packets_out += tcp_skb_pcount(skb); 4261 } 4262 4263 /* Build and send a SYN with data and (cached) Fast Open cookie. However, 4264 * queue a data-only packet after the regular SYN, such that regular SYNs 4265 * are retransmitted on timeouts. Also if the remote SYN-ACK acknowledges 4266 * only the SYN sequence, the data are retransmitted in the first ACK. 4267 * If cookie is not cached or other error occurs, falls back to send a 4268 * regular SYN with Fast Open cookie request option. 4269 */ 4270 static int tcp_send_syn_data(struct sock *sk, struct sk_buff *syn) 4271 { 4272 struct inet_connection_sock *icsk = inet_csk(sk); 4273 struct tcp_sock *tp = tcp_sk(sk); 4274 struct tcp_fastopen_request *fo = tp->fastopen_req; 4275 struct page_frag *pfrag = sk_page_frag(sk); 4276 struct sk_buff *syn_data; 4277 int space, err = 0; 4278 4279 tp->rx_opt.mss_clamp = tp->advmss; /* If MSS is not cached */ 4280 if (!tcp_fastopen_cookie_check(sk, &tp->rx_opt.mss_clamp, &fo->cookie)) 4281 goto fallback; 4282 4283 /* MSS for SYN-data is based on cached MSS and bounded by PMTU and 4284 * user-MSS. Reserve maximum option space for middleboxes that add 4285 * private TCP options. The cost is reduced data space in SYN :( 4286 */ 4287 tp->rx_opt.mss_clamp = tcp_mss_clamp(tp, tp->rx_opt.mss_clamp); 4288 /* Sync mss_cache after updating the mss_clamp */ 4289 tcp_sync_mss(sk, icsk->icsk_pmtu_cookie); 4290 4291 space = __tcp_mtu_to_mss(sk, icsk->icsk_pmtu_cookie) - 4292 MAX_TCP_OPTION_SPACE; 4293 4294 space = min_t(size_t, space, fo->size); 4295 4296 if (space && 4297 !skb_page_frag_refill(min_t(size_t, space, PAGE_SIZE), 4298 pfrag, sk->sk_allocation)) 4299 goto fallback; 4300 syn_data = tcp_stream_alloc_skb(sk, sk->sk_allocation, false); 4301 if (!syn_data) 4302 goto fallback; 4303 memcpy(syn_data->cb, syn->cb, sizeof(syn->cb)); 4304 if (space) { 4305 space = min_t(size_t, space, pfrag->size - pfrag->offset); 4306 space = tcp_wmem_schedule(sk, space); 4307 } 4308 if (space) { 4309 space = copy_page_from_iter(pfrag->page, pfrag->offset, 4310 space, &fo->data->msg_iter); 4311 if (unlikely(!space)) { 4312 tcp_skb_tsorted_anchor_cleanup(syn_data); 4313 kfree_skb(syn_data); 4314 goto fallback; 4315 } 4316 skb_fill_page_desc(syn_data, 0, pfrag->page, 4317 pfrag->offset, space); 4318 page_ref_inc(pfrag->page); 4319 pfrag->offset += space; 4320 skb_len_add(syn_data, space); 4321 skb_zcopy_set(syn_data, fo->uarg, NULL); 4322 } 4323 /* No more data pending in inet_wait_for_connect() */ 4324 if (space == fo->size) 4325 fo->data = NULL; 4326 fo->copied = space; 4327 4328 tcp_connect_queue_skb(sk, syn_data); 4329 if (syn_data->len) 4330 tcp_chrono_start(sk, TCP_CHRONO_BUSY); 4331 4332 err = tcp_transmit_skb(sk, syn_data, 1, sk->sk_allocation); 4333 4334 skb_set_delivery_time(syn, syn_data->skb_mstamp_ns, SKB_CLOCK_MONOTONIC); 4335 4336 /* Now full SYN+DATA was cloned and sent (or not), 4337 * remove the SYN from the original skb (syn_data) 4338 * we keep in write queue in case of a retransmit, as we 4339 * also have the SYN packet (with no data) in the same queue. 4340 */ 4341 TCP_SKB_CB(syn_data)->seq++; 4342 TCP_SKB_CB(syn_data)->tcp_flags = TCPHDR_ACK | TCPHDR_PSH; 4343 if (!err) { 4344 tp->syn_data = (fo->copied > 0); 4345 tcp_rbtree_insert(&sk->tcp_rtx_queue, syn_data); 4346 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPORIGDATASENT); 4347 goto done; 4348 } 4349 4350 /* data was not sent, put it in write_queue */ 4351 __skb_queue_tail(&sk->sk_write_queue, syn_data); 4352 tp->packets_out -= tcp_skb_pcount(syn_data); 4353 4354 fallback: 4355 /* Send a regular SYN with Fast Open cookie request option */ 4356 if (fo->cookie.len > 0) 4357 fo->cookie.len = 0; 4358 err = tcp_transmit_skb(sk, syn, 1, sk->sk_allocation); 4359 if (err) 4360 tp->syn_fastopen = 0; 4361 done: 4362 fo->cookie.len = -1; /* Exclude Fast Open option for SYN retries */ 4363 return err; 4364 } 4365 4366 /* Build a SYN and send it off. */ 4367 int tcp_connect(struct sock *sk) 4368 { 4369 struct tcp_sock *tp = tcp_sk(sk); 4370 struct sk_buff *buff; 4371 int err; 4372 4373 tcp_call_bpf(sk, BPF_SOCK_OPS_TCP_CONNECT_CB); 4374 bpf_tcp_ops_call(connect, sk); 4375 4376 #if defined(CONFIG_TCP_MD5SIG) && defined(CONFIG_TCP_AO) 4377 /* Has to be checked late, after setting daddr/saddr/ops. 4378 * Return error if the peer has both a md5 and a tcp-ao key 4379 * configured as this is ambiguous. 4380 */ 4381 if (unlikely(rcu_dereference_protected(tp->md5sig_info, 4382 lockdep_sock_is_held(sk)))) { 4383 bool needs_ao = !!tp->af_specific->ao_lookup(sk, sk, -1, -1); 4384 bool needs_md5 = !!tp->af_specific->md5_lookup(sk, sk); 4385 struct tcp_ao_info *ao_info; 4386 4387 ao_info = rcu_dereference_check(tp->ao_info, 4388 lockdep_sock_is_held(sk)); 4389 if (ao_info) { 4390 /* This is an extra check: tcp_ao_required() in 4391 * tcp_v{4,6}_parse_md5_keys() should prevent adding 4392 * md5 keys on ao_required socket. 4393 */ 4394 needs_ao |= ao_info->ao_required; 4395 WARN_ON_ONCE(ao_info->ao_required && needs_md5); 4396 } 4397 if (needs_md5 && needs_ao) 4398 return -EKEYREJECTED; 4399 4400 /* If we have a matching md5 key and no matching tcp-ao key 4401 * then free up ao_info if allocated. 4402 */ 4403 if (needs_md5) { 4404 tcp_ao_destroy_sock(sk, false); 4405 } else if (needs_ao) { 4406 struct tcp_md5sig_info *md5sig; 4407 4408 tcp_clear_md5_list(sk); 4409 md5sig = rcu_replace_pointer(tp->md5sig_info, NULL, 4410 lockdep_sock_is_held(sk)); 4411 kfree_rcu(md5sig, rcu); 4412 static_branch_slow_dec_deferred(&tcp_md5_needed); 4413 } 4414 } 4415 #endif 4416 #ifdef CONFIG_TCP_AO 4417 if (unlikely(rcu_dereference_protected(tp->ao_info, 4418 lockdep_sock_is_held(sk)))) { 4419 /* Don't allow connecting if ao is configured but no 4420 * matching key is found. 4421 */ 4422 if (!tp->af_specific->ao_lookup(sk, sk, -1, -1)) 4423 return -EKEYREJECTED; 4424 } 4425 #endif 4426 4427 if (inet_csk(sk)->icsk_af_ops->rebuild_header(sk)) 4428 return -EHOSTUNREACH; /* Routing failure or similar. */ 4429 4430 tcp_connect_init(sk); 4431 4432 if (unlikely(tp->repair)) { 4433 tcp_finish_connect(sk, NULL); 4434 return 0; 4435 } 4436 4437 buff = tcp_stream_alloc_skb(sk, sk->sk_allocation, true); 4438 if (unlikely(!buff)) 4439 return -ENOBUFS; 4440 4441 /* SYN eats a sequence byte, write_seq updated by 4442 * tcp_connect_queue_skb(). 4443 */ 4444 tcp_init_nondata_skb(buff, sk, tp->write_seq, TCPHDR_SYN); 4445 tcp_mstamp_refresh(tp); 4446 tp->retrans_stamp = tcp_time_stamp_ts(tp); 4447 tcp_connect_queue_skb(sk, buff); 4448 tcp_ecn_send_syn(sk, buff); 4449 tcp_rbtree_insert(&sk->tcp_rtx_queue, buff); 4450 4451 /* Send off SYN; include data in Fast Open. */ 4452 err = tp->fastopen_req ? tcp_send_syn_data(sk, buff) : 4453 tcp_transmit_skb(sk, buff, 1, sk->sk_allocation); 4454 if (err == -ECONNREFUSED) 4455 return err; 4456 4457 /* We change tp->snd_nxt after the tcp_transmit_skb() call 4458 * in order to make this packet get counted in tcpOutSegs. 4459 */ 4460 WRITE_ONCE(tp->snd_nxt, tp->write_seq); 4461 tp->pushed_seq = tp->write_seq; 4462 buff = tcp_send_head(sk); 4463 if (unlikely(buff)) { 4464 WRITE_ONCE(tp->snd_nxt, TCP_SKB_CB(buff)->seq); 4465 tp->pushed_seq = TCP_SKB_CB(buff)->seq; 4466 } 4467 TCP_INC_STATS(sock_net(sk), TCP_MIB_ACTIVEOPENS); 4468 4469 /* Timer for repeating the SYN until an answer. */ 4470 tcp_reset_xmit_timer(sk, ICSK_TIME_RETRANS, 4471 inet_csk(sk)->icsk_rto, false); 4472 return 0; 4473 } 4474 EXPORT_SYMBOL(tcp_connect); 4475 4476 u32 tcp_delack_max(const struct sock *sk) 4477 { 4478 u32 delack_from_rto_min = max(tcp_rto_min(sk), 2) - 1; 4479 4480 return min(READ_ONCE(inet_csk(sk)->icsk_delack_max), delack_from_rto_min); 4481 } 4482 4483 /* Send out a delayed ack, the caller does the policy checking 4484 * to see if we should even be here. See tcp_input.c:tcp_ack_snd_check() 4485 * for details. 4486 */ 4487 void tcp_send_delayed_ack(struct sock *sk) 4488 { 4489 struct inet_connection_sock *icsk = inet_csk(sk); 4490 int ato = icsk->icsk_ack.ato; 4491 unsigned long timeout; 4492 4493 if (ato > TCP_DELACK_MIN) { 4494 const struct tcp_sock *tp = tcp_sk(sk); 4495 int max_ato = HZ / 2; 4496 4497 if (inet_csk_in_pingpong_mode(sk) || 4498 (icsk->icsk_ack.pending & ICSK_ACK_PUSHED)) 4499 max_ato = TCP_DELACK_MAX; 4500 4501 /* Slow path, intersegment interval is "high". */ 4502 4503 /* If some rtt estimate is known, use it to bound delayed ack. 4504 * Do not use inet_csk(sk)->icsk_rto here, use results of rtt measurements 4505 * directly. 4506 */ 4507 if (tp->srtt_us) { 4508 int rtt = max_t(int, usecs_to_jiffies(tp->srtt_us >> 3), 4509 TCP_DELACK_MIN); 4510 4511 if (rtt < max_ato) 4512 max_ato = rtt; 4513 } 4514 4515 ato = min(ato, max_ato); 4516 } 4517 4518 ato = min_t(u32, ato, tcp_delack_max(sk)); 4519 4520 /* Stay within the limit we were given */ 4521 timeout = jiffies + ato; 4522 4523 /* Use new timeout only if there wasn't a older one earlier. */ 4524 if (icsk->icsk_ack.pending & ICSK_ACK_TIMER) { 4525 /* If delack timer is about to expire, send ACK now. */ 4526 if (time_before_eq(icsk_delack_timeout(icsk), jiffies + (ato >> 2))) { 4527 tcp_send_ack(sk); 4528 return; 4529 } 4530 4531 if (!time_before(timeout, icsk_delack_timeout(icsk))) 4532 timeout = icsk_delack_timeout(icsk); 4533 } 4534 smp_store_release(&icsk->icsk_ack.pending, 4535 icsk->icsk_ack.pending | ICSK_ACK_SCHED | ICSK_ACK_TIMER); 4536 sk_reset_timer(sk, &icsk->icsk_delack_timer, timeout); 4537 } 4538 4539 /* This routine sends an ack and also updates the window. */ 4540 void __tcp_send_ack(struct sock *sk, u32 rcv_nxt, u16 flags) 4541 { 4542 struct sk_buff *buff; 4543 4544 /* If we have been reset, we may not send again. */ 4545 if (sk->sk_state == TCP_CLOSE) 4546 return; 4547 4548 /* We are not putting this on the write queue, so 4549 * tcp_transmit_skb() will set the ownership to this 4550 * sock. 4551 */ 4552 buff = alloc_skb(MAX_TCP_HEADER, 4553 sk_gfp_mask(sk, GFP_ATOMIC | __GFP_NOWARN)); 4554 if (unlikely(!buff)) { 4555 struct inet_connection_sock *icsk = inet_csk(sk); 4556 unsigned long delay; 4557 4558 delay = TCP_DELACK_MAX << icsk->icsk_ack.retry; 4559 if (delay < tcp_rto_max(sk)) 4560 icsk->icsk_ack.retry++; 4561 inet_csk_schedule_ack(sk); 4562 icsk->icsk_ack.ato = TCP_ATO_MIN; 4563 tcp_reset_xmit_timer(sk, ICSK_TIME_DACK, delay, false); 4564 return; 4565 } 4566 4567 /* Reserve space for headers and prepare control bits. */ 4568 skb_reserve(buff, MAX_TCP_HEADER); 4569 tcp_init_nondata_skb(buff, sk, 4570 tcp_acceptable_seq(sk), TCPHDR_ACK | flags); 4571 4572 /* We do not want pure acks influencing TCP Small Queues or fq/pacing 4573 * too much. 4574 * SKB_TRUESIZE(max(1 .. 66, MAX_TCP_HEADER)) is unfortunately ~784 4575 */ 4576 skb_set_tcp_pure_ack(buff); 4577 4578 /* Send it off, this clears delayed acks for us. */ 4579 __tcp_transmit_skb(sk, buff, 0, (__force gfp_t)0, rcv_nxt); 4580 } 4581 EXPORT_SYMBOL_GPL(__tcp_send_ack); 4582 4583 void tcp_send_ack(struct sock *sk) 4584 { 4585 __tcp_send_ack(sk, tcp_sk(sk)->rcv_nxt, 0); 4586 } 4587 4588 /* This routine sends a packet with an out of date sequence 4589 * number. It assumes the other end will try to ack it. 4590 * 4591 * Question: what should we make while urgent mode? 4592 * 4.4BSD forces sending single byte of data. We cannot send 4593 * out of window data, because we have SND.NXT==SND.MAX... 4594 * 4595 * Current solution: to send TWO zero-length segments in urgent mode: 4596 * one is with SEG.SEQ=SND.UNA to deliver urgent pointer, another is 4597 * out-of-date with SND.UNA-1 to probe window. 4598 */ 4599 static int tcp_xmit_probe_skb(struct sock *sk, int urgent, int mib) 4600 { 4601 struct tcp_sock *tp = tcp_sk(sk); 4602 struct sk_buff *skb; 4603 4604 /* We don't queue it, tcp_transmit_skb() sets ownership. */ 4605 skb = alloc_skb(MAX_TCP_HEADER, 4606 sk_gfp_mask(sk, GFP_ATOMIC | __GFP_NOWARN)); 4607 if (!skb) 4608 return -1; 4609 4610 /* Reserve space for headers and set control bits. */ 4611 skb_reserve(skb, MAX_TCP_HEADER); 4612 /* Use a previous sequence. This should cause the other 4613 * end to send an ack. Don't queue or clone SKB, just 4614 * send it. 4615 */ 4616 tcp_init_nondata_skb(skb, sk, tp->snd_una - !urgent, TCPHDR_ACK); 4617 NET_INC_STATS(sock_net(sk), mib); 4618 return tcp_transmit_skb(sk, skb, 0, (__force gfp_t)0); 4619 } 4620 4621 /* Called from setsockopt( ... TCP_REPAIR ) */ 4622 void tcp_send_window_probe(struct sock *sk) 4623 { 4624 if (sk->sk_state == TCP_ESTABLISHED) { 4625 tcp_sk(sk)->snd_wl1 = tcp_sk(sk)->rcv_nxt - 1; 4626 tcp_mstamp_refresh(tcp_sk(sk)); 4627 tcp_xmit_probe_skb(sk, 0, LINUX_MIB_TCPWINPROBE); 4628 } 4629 } 4630 4631 /* Initiate keepalive or window probe from timer. */ 4632 int tcp_write_wakeup(struct sock *sk, int mib) 4633 { 4634 struct tcp_sock *tp = tcp_sk(sk); 4635 struct sk_buff *skb; 4636 4637 if (sk->sk_state == TCP_CLOSE) 4638 return -1; 4639 4640 skb = tcp_send_head(sk); 4641 if (skb && before(TCP_SKB_CB(skb)->seq, tcp_wnd_end(tp))) { 4642 int err; 4643 unsigned int mss = tcp_current_mss(sk); 4644 unsigned int seg_size = tcp_wnd_end(tp) - TCP_SKB_CB(skb)->seq; 4645 4646 if (before(tp->pushed_seq, TCP_SKB_CB(skb)->end_seq)) 4647 tp->pushed_seq = TCP_SKB_CB(skb)->end_seq; 4648 4649 /* We are probing the opening of a window 4650 * but the window size is != 0 4651 * must have been a result SWS avoidance ( sender ) 4652 */ 4653 if (seg_size < TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq || 4654 skb->len > mss) { 4655 seg_size = min(seg_size, mss); 4656 TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH; 4657 if (tcp_fragment(sk, TCP_FRAG_IN_WRITE_QUEUE, 4658 skb, seg_size, mss, GFP_ATOMIC)) 4659 return -1; 4660 } else if (!tcp_skb_pcount(skb)) 4661 tcp_set_skb_tso_segs(skb, mss); 4662 4663 TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH; 4664 err = tcp_transmit_skb(sk, skb, 1, GFP_ATOMIC); 4665 if (!err) 4666 tcp_event_new_data_sent(sk, skb); 4667 return err; 4668 } else { 4669 if (between(tp->snd_up, tp->snd_una + 1, tp->snd_una + 0xFFFF)) 4670 tcp_xmit_probe_skb(sk, 1, mib); 4671 return tcp_xmit_probe_skb(sk, 0, mib); 4672 } 4673 } 4674 4675 /* A window probe timeout has occurred. If window is not closed send 4676 * a partial packet else a zero probe. 4677 */ 4678 void tcp_send_probe0(struct sock *sk) 4679 { 4680 struct inet_connection_sock *icsk = inet_csk(sk); 4681 struct tcp_sock *tp = tcp_sk(sk); 4682 struct net *net = sock_net(sk); 4683 unsigned long timeout; 4684 int err; 4685 4686 err = tcp_write_wakeup(sk, LINUX_MIB_TCPWINPROBE); 4687 4688 if (tp->packets_out || tcp_write_queue_empty(sk)) { 4689 /* Cancel probe timer, if it is not required. */ 4690 WRITE_ONCE(icsk->icsk_probes_out, 0); 4691 icsk->icsk_backoff = 0; 4692 icsk->icsk_probes_tstamp = 0; 4693 return; 4694 } 4695 4696 WRITE_ONCE(icsk->icsk_probes_out, icsk->icsk_probes_out + 1); 4697 if (err <= 0) { 4698 if (icsk->icsk_backoff < READ_ONCE(net->ipv4.sysctl_tcp_retries2)) 4699 icsk->icsk_backoff++; 4700 timeout = tcp_probe0_when(sk, tcp_rto_max(sk)); 4701 } else { 4702 /* If packet was not sent due to local congestion, 4703 * Let senders fight for local resources conservatively. 4704 */ 4705 timeout = TCP_RESOURCE_PROBE_INTERVAL; 4706 } 4707 4708 timeout = tcp_clamp_probe0_to_user_timeout(sk, timeout); 4709 tcp_reset_xmit_timer(sk, ICSK_TIME_PROBE0, timeout, true); 4710 } 4711 4712 int tcp_rtx_synack(const struct sock *sk, struct request_sock *req) 4713 { 4714 const struct tcp_request_sock_ops *af_ops = tcp_rsk(req)->af_specific; 4715 struct flowi fl; 4716 int res; 4717 4718 /* Paired with WRITE_ONCE() in sock_setsockopt() */ 4719 if (READ_ONCE(sk->sk_txrehash) == SOCK_TXREHASH_ENABLED) 4720 WRITE_ONCE(tcp_rsk(req)->txhash, net_tx_rndhash()); 4721 res = af_ops->send_synack(sk, NULL, &fl, req, NULL, TCP_SYNACK_RETRANS, 4722 NULL); 4723 if (!res) { 4724 TCP_INC_STATS(sock_net(sk), TCP_MIB_RETRANSSEGS); 4725 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPSYNRETRANS); 4726 if (unlikely(tcp_passive_fastopen(sk))) { 4727 /* sk has const attribute because listeners are lockless. 4728 * However in this case, we are dealing with a passive fastopen 4729 * socket thus we can change total_retrans value. 4730 */ 4731 WRITE_ONCE(tcp_sk_rw(sk)->total_retrans, 4732 tcp_sk_rw(sk)->total_retrans + 1); 4733 } 4734 trace_tcp_retransmit_synack(sk, req); 4735 WRITE_ONCE(req->num_retrans, req->num_retrans + 1); 4736 } 4737 return res; 4738 } 4739