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