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