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