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