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