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