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