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