]> git.ipfire.org Git - people/ms/linux.git/blame - net/ipv4/tcp_input.c
tcp: annotate data-race around challenge_timestamp
[people/ms/linux.git] / net / ipv4 / tcp_input.c
CommitLineData
b2441318 1// SPDX-License-Identifier: GPL-2.0
1da177e4
LT
2/*
3 * INET An implementation of the TCP/IP protocol suite for the LINUX
4 * operating system. INET is implemented using the BSD Socket
5 * interface as the means of communication with the user level.
6 *
7 * Implementation of the Transmission Control Protocol(TCP).
8 *
02c30a84 9 * Authors: Ross Biro
1da177e4
LT
10 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
11 * Mark Evans, <evansmp@uhura.aston.ac.uk>
12 * Corey Minyard <wf-rch!minyard@relay.EU.net>
13 * Florian La Roche, <flla@stud.uni-sb.de>
14 * Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
15 * Linus Torvalds, <torvalds@cs.helsinki.fi>
16 * Alan Cox, <gw4pts@gw4pts.ampr.org>
17 * Matthew Dillon, <dillon@apollo.west.oic.com>
18 * Arnt Gulbrandsen, <agulbra@nvg.unit.no>
19 * Jorge Cwik, <jorge@laser.satlink.net>
20 */
21
22/*
23 * Changes:
24 * Pedro Roque : Fast Retransmit/Recovery.
25 * Two receive queues.
26 * Retransmit queue handled by TCP.
27 * Better retransmit timer handling.
28 * New congestion avoidance.
29 * Header prediction.
30 * Variable renaming.
31 *
32 * Eric : Fast Retransmit.
33 * Randy Scott : MSS option defines.
34 * Eric Schenk : Fixes to slow start algorithm.
35 * Eric Schenk : Yet another double ACK bug.
36 * Eric Schenk : Delayed ACK bug fixes.
37 * Eric Schenk : Floyd style fast retrans war avoidance.
38 * David S. Miller : Don't allow zero congestion window.
39 * Eric Schenk : Fix retransmitter so that it sends
40 * next packet on ack of previous packet.
41 * Andi Kleen : Moved open_request checking here
42 * and process RSTs for open_requests.
43 * Andi Kleen : Better prune_queue, and other fixes.
caa20d9a 44 * Andrey Savochkin: Fix RTT measurements in the presence of
1da177e4
LT
45 * timestamps.
46 * Andrey Savochkin: Check sequence numbers correctly when
47 * removing SACKs due to in sequence incoming
48 * data segments.
49 * Andi Kleen: Make sure we never ack data there is not
50 * enough room for. Also make this condition
51 * a fatal error if it might still happen.
e905a9ed 52 * Andi Kleen: Add tcp_measure_rcv_mss to make
1da177e4 53 * connections with MSS<min(MTU,ann. MSS)
e905a9ed 54 * work without delayed acks.
1da177e4
LT
55 * Andi Kleen: Process packets with PSH set in the
56 * fast path.
57 * J Hadi Salim: ECN support
58 * Andrei Gurtov,
59 * Pasi Sarolahti,
60 * Panu Kuhlberg: Experimental audit of TCP (re)transmission
61 * engine. Lots of bugs are found.
62 * Pasi Sarolahti: F-RTO for dealing with spurious RTOs
1da177e4
LT
63 */
64
afd46503
JP
65#define pr_fmt(fmt) "TCP: " fmt
66
1da177e4 67#include <linux/mm.h>
5a0e3ad6 68#include <linux/slab.h>
1da177e4
LT
69#include <linux/module.h>
70#include <linux/sysctl.h>
a0bffffc 71#include <linux/kernel.h>
ad971f61 72#include <linux/prefetch.h>
5ffc02a1 73#include <net/dst.h>
1da177e4
LT
74#include <net/tcp.h>
75#include <net/inet_common.h>
76#include <linux/ipsec.h>
77#include <asm/unaligned.h>
e1c8a607 78#include <linux/errqueue.h>
5941521c 79#include <trace/events/tcp.h>
494bc1d2 80#include <linux/jump_label_ratelimit.h>
c6345ce7 81#include <net/busy_poll.h>
eda7acdd 82#include <net/mptcp.h>
1da177e4 83
ab32ea5d 84int sysctl_tcp_max_orphans __read_mostly = NR_FILE;
1da177e4 85
1da177e4
LT
86#define FLAG_DATA 0x01 /* Incoming frame contained data. */
87#define FLAG_WIN_UPDATE 0x02 /* Incoming ACK was a window update. */
88#define FLAG_DATA_ACKED 0x04 /* This ACK acknowledged new data. */
89#define FLAG_RETRANS_DATA_ACKED 0x08 /* "" "" some of which was retransmitted. */
90#define FLAG_SYN_ACKED 0x10 /* This ACK acknowledged SYN. */
91#define FLAG_DATA_SACKED 0x20 /* New SACK. */
92#define FLAG_ECE 0x40 /* ECE in this ACK */
291a00d1 93#define FLAG_LOST_RETRANS 0x80 /* This ACK marks some retransmission lost */
31770e34 94#define FLAG_SLOWPATH 0x100 /* Do not skip RFC checks for window update.*/
e33099f9 95#define FLAG_ORIG_SACK_ACKED 0x200 /* Never retransmitted data are (s)acked */
2e605294 96#define FLAG_SND_UNA_ADVANCED 0x400 /* Snd_una was changed (!= FLAG_DATA_ACKED) */
564262c1 97#define FLAG_DSACKING_ACK 0x800 /* SACK blocks contained D-SACK info */
df92c839 98#define FLAG_SET_XMIT_TIMER 0x1000 /* Set TLP or RTO timer */
cadbd031 99#define FLAG_SACK_RENEGING 0x2000 /* snd_una advanced to a sacked seq */
12fb3dd9 100#define FLAG_UPDATE_TS_RECENT 0x4000 /* tcp_replace_ts_recent() */
d0e1a1b5 101#define FLAG_NO_CHALLENGE_ACK 0x8000 /* do not call tcp_send_challenge_ack() */
eb36be0f 102#define FLAG_ACK_MAYBE_DELAYED 0x10000 /* Likely a delayed ACK */
63f367d9 103#define FLAG_DSACK_TLP 0x20000 /* DSACK for tail loss probe */
1da177e4
LT
104
105#define FLAG_ACKED (FLAG_DATA_ACKED|FLAG_SYN_ACKED)
106#define FLAG_NOT_DUP (FLAG_DATA|FLAG_WIN_UPDATE|FLAG_ACKED)
d09b9e60 107#define FLAG_CA_ALERT (FLAG_DATA_SACKED|FLAG_ECE|FLAG_DSACKING_ACK)
1da177e4
LT
108#define FLAG_FORWARD_PROGRESS (FLAG_ACKED|FLAG_DATA_SACKED)
109
1da177e4 110#define TCP_REMNANT (TCP_FLAG_FIN|TCP_FLAG_URG|TCP_FLAG_SYN|TCP_FLAG_PSH)
bdf1ee5d 111#define TCP_HP_BITS (~(TCP_RESERVED_BITS|TCP_FLAG_PSH))
1da177e4 112
e662ca40
YC
113#define REXMIT_NONE 0 /* no loss recovery to do */
114#define REXMIT_LOST 1 /* retransmit packets marked lost */
115#define REXMIT_NEW 2 /* FRTO-style transmit of unsent/new packets */
116
6dac1523 117#if IS_ENABLED(CONFIG_TLS_DEVICE)
494bc1d2 118static DEFINE_STATIC_KEY_DEFERRED_FALSE(clean_acked_data_enabled, HZ);
6dac1523
IL
119
120void clean_acked_data_enable(struct inet_connection_sock *icsk,
121 void (*cad)(struct sock *sk, u32 ack_seq))
122{
123 icsk->icsk_clean_acked = cad;
7b58139f 124 static_branch_deferred_inc(&clean_acked_data_enabled);
6dac1523
IL
125}
126EXPORT_SYMBOL_GPL(clean_acked_data_enable);
127
128void clean_acked_data_disable(struct inet_connection_sock *icsk)
129{
494bc1d2 130 static_branch_slow_dec_deferred(&clean_acked_data_enabled);
6dac1523
IL
131 icsk->icsk_clean_acked = NULL;
132}
133EXPORT_SYMBOL_GPL(clean_acked_data_disable);
494bc1d2
JK
134
135void clean_acked_data_flush(void)
136{
137 static_key_deferred_flush(&clean_acked_data_enabled);
138}
139EXPORT_SYMBOL_GPL(clean_acked_data_flush);
6dac1523
IL
140#endif
141
72be0fe6 142#ifdef CONFIG_CGROUP_BPF
00d211a4
MKL
143static void bpf_skops_parse_hdr(struct sock *sk, struct sk_buff *skb)
144{
145 bool unknown_opt = tcp_sk(sk)->rx_opt.saw_unknown &&
146 BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk),
147 BPF_SOCK_OPS_PARSE_UNKNOWN_HDR_OPT_CB_FLAG);
148 bool parse_all_opt = BPF_SOCK_OPS_TEST_FLAG(tcp_sk(sk),
149 BPF_SOCK_OPS_PARSE_ALL_HDR_OPT_CB_FLAG);
0813a841 150 struct bpf_sock_ops_kern sock_ops;
00d211a4
MKL
151
152 if (likely(!unknown_opt && !parse_all_opt))
153 return;
154
155 /* The skb will be handled in the
156 * bpf_skops_established() or
157 * bpf_skops_write_hdr_opt().
158 */
159 switch (sk->sk_state) {
160 case TCP_SYN_RECV:
161 case TCP_SYN_SENT:
162 case TCP_LISTEN:
163 return;
164 }
165
0813a841
MKL
166 sock_owned_by_me(sk);
167
168 memset(&sock_ops, 0, offsetof(struct bpf_sock_ops_kern, temp));
169 sock_ops.op = BPF_SOCK_OPS_PARSE_HDR_OPT_CB;
170 sock_ops.is_fullsock = 1;
171 sock_ops.sk = sk;
172 bpf_skops_init_skb(&sock_ops, skb, tcp_hdrlen(skb));
173
174 BPF_CGROUP_RUN_PROG_SOCK_OPS(&sock_ops);
00d211a4
MKL
175}
176
72be0fe6
MKL
177static void bpf_skops_established(struct sock *sk, int bpf_op,
178 struct sk_buff *skb)
179{
180 struct bpf_sock_ops_kern sock_ops;
181
182 sock_owned_by_me(sk);
183
184 memset(&sock_ops, 0, offsetof(struct bpf_sock_ops_kern, temp));
185 sock_ops.op = bpf_op;
186 sock_ops.is_fullsock = 1;
187 sock_ops.sk = sk;
0813a841
MKL
188 /* sk with TCP_REPAIR_ON does not have skb in tcp_finish_connect */
189 if (skb)
190 bpf_skops_init_skb(&sock_ops, skb, tcp_hdrlen(skb));
72be0fe6
MKL
191
192 BPF_CGROUP_RUN_PROG_SOCK_OPS(&sock_ops);
193}
194#else
00d211a4
MKL
195static void bpf_skops_parse_hdr(struct sock *sk, struct sk_buff *skb)
196{
197}
198
72be0fe6
MKL
199static void bpf_skops_established(struct sock *sk, int bpf_op,
200 struct sk_buff *skb)
201{
202}
203#endif
204
0b9aefea
MRL
205static void tcp_gro_dev_warn(struct sock *sk, const struct sk_buff *skb,
206 unsigned int len)
dcb17d22
MRL
207{
208 static bool __once __read_mostly;
209
210 if (!__once) {
211 struct net_device *dev;
212
213 __once = true;
214
215 rcu_read_lock();
216 dev = dev_get_by_index_rcu(sock_net(sk), skb->skb_iif);
0b9aefea
MRL
217 if (!dev || len >= dev->mtu)
218 pr_warn("%s: Driver has suspect GRO implementation, TCP performance may be compromised.\n",
219 dev ? dev->name : "Unknown driver");
dcb17d22
MRL
220 rcu_read_unlock();
221 }
222}
223
e905a9ed 224/* Adapt the MSS value used to make delayed ack decision to the
1da177e4 225 * real world.
e905a9ed 226 */
056834d9 227static void tcp_measure_rcv_mss(struct sock *sk, const struct sk_buff *skb)
1da177e4 228{
463c84b9 229 struct inet_connection_sock *icsk = inet_csk(sk);
e905a9ed 230 const unsigned int lss = icsk->icsk_ack.last_seg_size;
463c84b9 231 unsigned int len;
1da177e4 232
e905a9ed 233 icsk->icsk_ack.last_seg_size = 0;
1da177e4
LT
234
235 /* skb->len may jitter because of SACKs, even if peer
236 * sends good full-sized frames.
237 */
056834d9 238 len = skb_shinfo(skb)->gso_size ? : skb->len;
463c84b9 239 if (len >= icsk->icsk_ack.rcv_mss) {
dcb17d22
MRL
240 icsk->icsk_ack.rcv_mss = min_t(unsigned int, len,
241 tcp_sk(sk)->advmss);
0b9aefea
MRL
242 /* Account for possibly-removed options */
243 if (unlikely(len > icsk->icsk_ack.rcv_mss +
244 MAX_TCP_OPTION_SPACE))
245 tcp_gro_dev_warn(sk, skb, len);
1da177e4
LT
246 } else {
247 /* Otherwise, we make more careful check taking into account,
248 * that SACKs block is variable.
249 *
250 * "len" is invariant segment length, including TCP header.
251 */
9c70220b 252 len += skb->data - skb_transport_header(skb);
bee7ca9e 253 if (len >= TCP_MSS_DEFAULT + sizeof(struct tcphdr) ||
1da177e4
LT
254 /* If PSH is not set, packet should be
255 * full sized, provided peer TCP is not badly broken.
256 * This observation (if it is correct 8)) allows
257 * to handle super-low mtu links fairly.
258 */
259 (len >= TCP_MIN_MSS + sizeof(struct tcphdr) &&
aa8223c7 260 !(tcp_flag_word(tcp_hdr(skb)) & TCP_REMNANT))) {
1da177e4
LT
261 /* Subtract also invariant (if peer is RFC compliant),
262 * tcp header plus fixed timestamp option length.
263 * Resulting "len" is MSS free of SACK jitter.
264 */
463c84b9
ACM
265 len -= tcp_sk(sk)->tcp_header_len;
266 icsk->icsk_ack.last_seg_size = len;
1da177e4 267 if (len == lss) {
463c84b9 268 icsk->icsk_ack.rcv_mss = len;
1da177e4
LT
269 return;
270 }
271 }
1ef9696c
AK
272 if (icsk->icsk_ack.pending & ICSK_ACK_PUSHED)
273 icsk->icsk_ack.pending |= ICSK_ACK_PUSHED2;
463c84b9 274 icsk->icsk_ack.pending |= ICSK_ACK_PUSHED;
1da177e4
LT
275 }
276}
277
9a9c9b51 278static void tcp_incr_quickack(struct sock *sk, unsigned int max_quickacks)
1da177e4 279{
463c84b9 280 struct inet_connection_sock *icsk = inet_csk(sk);
95c96174 281 unsigned int quickacks = tcp_sk(sk)->rcv_wnd / (2 * icsk->icsk_ack.rcv_mss);
1da177e4 282
056834d9
IJ
283 if (quickacks == 0)
284 quickacks = 2;
9a9c9b51 285 quickacks = min(quickacks, max_quickacks);
463c84b9 286 if (quickacks > icsk->icsk_ack.quick)
9a9c9b51 287 icsk->icsk_ack.quick = quickacks;
1da177e4
LT
288}
289
a0496ef2 290void tcp_enter_quickack_mode(struct sock *sk, unsigned int max_quickacks)
1da177e4 291{
463c84b9 292 struct inet_connection_sock *icsk = inet_csk(sk);
9a9c9b51
ED
293
294 tcp_incr_quickack(sk, max_quickacks);
31954cd8 295 inet_csk_exit_pingpong_mode(sk);
463c84b9 296 icsk->icsk_ack.ato = TCP_ATO_MIN;
1da177e4 297}
a0496ef2 298EXPORT_SYMBOL(tcp_enter_quickack_mode);
1da177e4
LT
299
300/* Send ACKs quickly, if "quick" count is not exhausted
301 * and the session is not interactive.
302 */
303
2251ae46 304static bool tcp_in_quickack_mode(struct sock *sk)
1da177e4 305{
463c84b9 306 const struct inet_connection_sock *icsk = inet_csk(sk);
2251ae46 307 const struct dst_entry *dst = __sk_dst_get(sk);
a2a385d6 308
2251ae46 309 return (dst && dst_metric(dst, RTAX_QUICKACK)) ||
31954cd8 310 (icsk->icsk_ack.quick && !inet_csk_in_pingpong_mode(sk));
1da177e4
LT
311}
312
735d3831 313static void tcp_ecn_queue_cwr(struct tcp_sock *tp)
bdf1ee5d 314{
056834d9 315 if (tp->ecn_flags & TCP_ECN_OK)
bdf1ee5d
IJ
316 tp->ecn_flags |= TCP_ECN_QUEUE_CWR;
317}
318
fd2123a3 319static void tcp_ecn_accept_cwr(struct sock *sk, const struct sk_buff *skb)
bdf1ee5d 320{
9aee4000 321 if (tcp_hdr(skb)->cwr) {
fd2123a3 322 tcp_sk(sk)->ecn_flags &= ~TCP_ECN_DEMAND_CWR;
9aee4000
LB
323
324 /* If the sender is telling us it has entered CWR, then its
325 * cwnd may be very low (even just 1 packet), so we should ACK
326 * immediately.
327 */
25702840
DK
328 if (TCP_SKB_CB(skb)->seq != TCP_SKB_CB(skb)->end_seq)
329 inet_csk(sk)->icsk_ack.pending |= ICSK_ACK_NOW;
9aee4000 330 }
bdf1ee5d
IJ
331}
332
735d3831 333static void tcp_ecn_withdraw_cwr(struct tcp_sock *tp)
bdf1ee5d 334{
af38d07e 335 tp->ecn_flags &= ~TCP_ECN_QUEUE_CWR;
bdf1ee5d
IJ
336}
337
f4c9f85f 338static void __tcp_ecn_check_ce(struct sock *sk, const struct sk_buff *skb)
bdf1ee5d 339{
f4c9f85f
YS
340 struct tcp_sock *tp = tcp_sk(sk);
341
b82d1bb4 342 switch (TCP_SKB_CB(skb)->ip_dsfield & INET_ECN_MASK) {
7a269ffa 343 case INET_ECN_NOT_ECT:
bdf1ee5d 344 /* Funny extension: if ECT is not set on a segment,
7a269ffa
ED
345 * and we already seen ECT on a previous segment,
346 * it is probably a retransmit.
347 */
348 if (tp->ecn_flags & TCP_ECN_SEEN)
15ecbe94 349 tcp_enter_quickack_mode(sk, 2);
7a269ffa
ED
350 break;
351 case INET_ECN_CE:
f4c9f85f
YS
352 if (tcp_ca_needs_ecn(sk))
353 tcp_ca_event(sk, CA_EVENT_ECN_IS_CE);
9890092e 354
aae06bf5
ED
355 if (!(tp->ecn_flags & TCP_ECN_DEMAND_CWR)) {
356 /* Better not delay acks, sender can have a very low cwnd */
15ecbe94 357 tcp_enter_quickack_mode(sk, 2);
aae06bf5
ED
358 tp->ecn_flags |= TCP_ECN_DEMAND_CWR;
359 }
9890092e
FW
360 tp->ecn_flags |= TCP_ECN_SEEN;
361 break;
7a269ffa 362 default:
f4c9f85f
YS
363 if (tcp_ca_needs_ecn(sk))
364 tcp_ca_event(sk, CA_EVENT_ECN_NO_CE);
7a269ffa 365 tp->ecn_flags |= TCP_ECN_SEEN;
9890092e 366 break;
bdf1ee5d
IJ
367 }
368}
369
f4c9f85f 370static void tcp_ecn_check_ce(struct sock *sk, const struct sk_buff *skb)
735d3831 371{
f4c9f85f
YS
372 if (tcp_sk(sk)->ecn_flags & TCP_ECN_OK)
373 __tcp_ecn_check_ce(sk, skb);
735d3831
FW
374}
375
376static void tcp_ecn_rcv_synack(struct tcp_sock *tp, const struct tcphdr *th)
bdf1ee5d 377{
056834d9 378 if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || th->cwr))
bdf1ee5d
IJ
379 tp->ecn_flags &= ~TCP_ECN_OK;
380}
381
735d3831 382static void tcp_ecn_rcv_syn(struct tcp_sock *tp, const struct tcphdr *th)
bdf1ee5d 383{
056834d9 384 if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || !th->cwr))
bdf1ee5d
IJ
385 tp->ecn_flags &= ~TCP_ECN_OK;
386}
387
735d3831 388static bool tcp_ecn_rcv_ecn_echo(const struct tcp_sock *tp, const struct tcphdr *th)
bdf1ee5d 389{
056834d9 390 if (th->ece && !th->syn && (tp->ecn_flags & TCP_ECN_OK))
a2a385d6
ED
391 return true;
392 return false;
bdf1ee5d
IJ
393}
394
1da177e4
LT
395/* Buffer size and advertised window tuning.
396 *
397 * 1. Tuning sk->sk_sndbuf, when connection enters established state.
398 */
399
6ae70532 400static void tcp_sndbuf_expand(struct sock *sk)
1da177e4 401{
6ae70532 402 const struct tcp_sock *tp = tcp_sk(sk);
77bfc174 403 const struct tcp_congestion_ops *ca_ops = inet_csk(sk)->icsk_ca_ops;
6ae70532
ED
404 int sndmem, per_mss;
405 u32 nr_segs;
406
407 /* Worst case is non GSO/TSO : each frame consumes one skb
408 * and skb->head is kmalloced using power of two area of memory
409 */
410 per_mss = max_t(u32, tp->rx_opt.mss_clamp, tp->mss_cache) +
411 MAX_TCP_HEADER +
412 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
413
414 per_mss = roundup_pow_of_two(per_mss) +
415 SKB_DATA_ALIGN(sizeof(struct sk_buff));
416
40570375 417 nr_segs = max_t(u32, TCP_INIT_CWND, tcp_snd_cwnd(tp));
6ae70532
ED
418 nr_segs = max_t(u32, nr_segs, tp->reordering + 1);
419
420 /* Fast Recovery (RFC 5681 3.2) :
421 * Cubic needs 1.7 factor, rounded to 2 to include
a9a08845 422 * extra cushion (application might react slowly to EPOLLOUT)
6ae70532 423 */
77bfc174
YC
424 sndmem = ca_ops->sndbuf_expand ? ca_ops->sndbuf_expand(sk) : 2;
425 sndmem *= nr_segs * per_mss;
1da177e4 426
06a59ecb 427 if (sk->sk_sndbuf < sndmem)
e292f05e 428 WRITE_ONCE(sk->sk_sndbuf,
02739545 429 min(sndmem, READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_wmem[2])));
1da177e4
LT
430}
431
432/* 2. Tuning advertised window (window_clamp, rcv_ssthresh)
433 *
434 * All tcp_full_space() is split to two parts: "network" buffer, allocated
435 * forward and advertised in receiver window (tp->rcv_wnd) and
436 * "application buffer", required to isolate scheduling/application
437 * latencies from network.
438 * window_clamp is maximal advertised window. It can be less than
439 * tcp_full_space(), in this case tcp_full_space() - window_clamp
440 * is reserved for "application" buffer. The less window_clamp is
441 * the smoother our behaviour from viewpoint of network, but the lower
442 * throughput and the higher sensitivity of the connection to losses. 8)
443 *
444 * rcv_ssthresh is more strict window_clamp used at "slow start"
445 * phase to predict further behaviour of this connection.
446 * It is used for two goals:
447 * - to enforce header prediction at sender, even when application
448 * requires some significant "application buffer". It is check #1.
449 * - to prevent pruning of receive queue because of misprediction
450 * of receiver window. Check #2.
451 *
452 * The scheme does not work when sender sends good segments opening
caa20d9a 453 * window and then starts to feed us spaghetti. But it should work
1da177e4
LT
454 * in common situations. Otherwise, we have to rely on queue collapsing.
455 */
456
457/* Slow part of check#2. */
240bfd13
ED
458static int __tcp_grow_window(const struct sock *sk, const struct sk_buff *skb,
459 unsigned int skbtruesize)
1da177e4 460{
9e412ba7 461 struct tcp_sock *tp = tcp_sk(sk);
1da177e4 462 /* Optimize this! */
240bfd13 463 int truesize = tcp_win_from_space(sk, skbtruesize) >> 1;
02739545 464 int window = tcp_win_from_space(sk, READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[2])) >> 1;
1da177e4
LT
465
466 while (tp->rcv_ssthresh <= window) {
467 if (truesize <= skb->len)
463c84b9 468 return 2 * inet_csk(sk)->icsk_ack.rcv_mss;
1da177e4
LT
469
470 truesize >>= 1;
471 window >>= 1;
472 }
473 return 0;
474}
475
240bfd13
ED
476/* Even if skb appears to have a bad len/truesize ratio, TCP coalescing
477 * can play nice with us, as sk_buff and skb->head might be either
478 * freed or shared with up to MAX_SKB_FRAGS segments.
479 * Only give a boost to drivers using page frag(s) to hold the frame(s),
480 * and if no payload was pulled in skb->head before reaching us.
481 */
482static u32 truesize_adjust(bool adjust, const struct sk_buff *skb)
483{
484 u32 truesize = skb->truesize;
485
486 if (adjust && !skb_headlen(skb)) {
487 truesize -= SKB_TRUESIZE(skb_end_offset(skb));
488 /* paranoid check, some drivers might be buggy */
489 if (unlikely((int)truesize < (int)skb->len))
490 truesize = skb->truesize;
491 }
492 return truesize;
493}
494
495static void tcp_grow_window(struct sock *sk, const struct sk_buff *skb,
496 bool adjust)
1da177e4 497{
9e412ba7 498 struct tcp_sock *tp = tcp_sk(sk);
50ce163a
ED
499 int room;
500
501 room = min_t(int, tp->window_clamp, tcp_space(sk)) - tp->rcv_ssthresh;
9e412ba7 502
053f3684
WW
503 if (room <= 0)
504 return;
505
1da177e4 506 /* Check #1 */
053f3684 507 if (!tcp_under_memory_pressure(sk)) {
240bfd13 508 unsigned int truesize = truesize_adjust(adjust, skb);
1da177e4
LT
509 int incr;
510
511 /* Check #2. Increase window, if skb with such overhead
512 * will fit to rcvbuf in future.
513 */
240bfd13 514 if (tcp_win_from_space(sk, truesize) <= skb->len)
056834d9 515 incr = 2 * tp->advmss;
1da177e4 516 else
240bfd13 517 incr = __tcp_grow_window(sk, skb, truesize);
1da177e4
LT
518
519 if (incr) {
4d846f02 520 incr = max_t(int, incr, 2 * skb->len);
50ce163a 521 tp->rcv_ssthresh += min(room, incr);
463c84b9 522 inet_csk(sk)->icsk_ack.quick |= 1;
1da177e4 523 }
053f3684
WW
524 } else {
525 /* Under pressure:
526 * Adjust rcv_ssthresh according to reserved mem
527 */
528 tcp_adjust_rcv_ssthresh(sk);
1da177e4
LT
529 }
530}
531
a337531b 532/* 3. Try to fixup all. It is made immediately after connection enters
1da177e4
LT
533 * established state.
534 */
bc183dec 535static void tcp_init_buffer_space(struct sock *sk)
1da177e4 536{
02ca527a 537 int tcp_app_win = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_app_win);
1da177e4
LT
538 struct tcp_sock *tp = tcp_sk(sk);
539 int maxwin;
540
1da177e4 541 if (!(sk->sk_userlocks & SOCK_SNDBUF_LOCK))
6ae70532 542 tcp_sndbuf_expand(sk);
1da177e4 543
9a568de4 544 tcp_mstamp_refresh(tp);
645f4c6f 545 tp->rcvq_space.time = tp->tcp_mstamp;
b0983d3c 546 tp->rcvq_space.seq = tp->copied_seq;
1da177e4
LT
547
548 maxwin = tcp_full_space(sk);
549
550 if (tp->window_clamp >= maxwin) {
551 tp->window_clamp = maxwin;
552
0c12654a 553 if (tcp_app_win && maxwin > 4 * tp->advmss)
1da177e4 554 tp->window_clamp = max(maxwin -
0c12654a 555 (maxwin >> tcp_app_win),
1da177e4
LT
556 4 * tp->advmss);
557 }
558
559 /* Force reservation of one segment. */
0c12654a 560 if (tcp_app_win &&
1da177e4
LT
561 tp->window_clamp > 2 * tp->advmss &&
562 tp->window_clamp + tp->advmss > maxwin)
563 tp->window_clamp = max(2 * tp->advmss, maxwin - tp->advmss);
564
565 tp->rcv_ssthresh = min(tp->rcv_ssthresh, tp->window_clamp);
c2203cf7 566 tp->snd_cwnd_stamp = tcp_jiffies32;
72d05c00
ED
567 tp->rcvq_space.space = min3(tp->rcv_ssthresh, tp->rcv_wnd,
568 (u32)TCP_INIT_CWND * tp->advmss);
1da177e4
LT
569}
570
a337531b 571/* 4. Recalculate window clamp after socket hit its memory bounds. */
9e412ba7 572static void tcp_clamp_window(struct sock *sk)
1da177e4 573{
9e412ba7 574 struct tcp_sock *tp = tcp_sk(sk);
6687e988 575 struct inet_connection_sock *icsk = inet_csk(sk);
356d1833 576 struct net *net = sock_net(sk);
02739545 577 int rmem2;
1da177e4 578
6687e988 579 icsk->icsk_ack.quick = 0;
02739545 580 rmem2 = READ_ONCE(net->ipv4.sysctl_tcp_rmem[2]);
1da177e4 581
02739545 582 if (sk->sk_rcvbuf < rmem2 &&
326f36e9 583 !(sk->sk_userlocks & SOCK_RCVBUF_LOCK) &&
b8da51eb 584 !tcp_under_memory_pressure(sk) &&
180d8cd9 585 sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0)) {
ebb3b78d 586 WRITE_ONCE(sk->sk_rcvbuf,
02739545 587 min(atomic_read(&sk->sk_rmem_alloc), rmem2));
1da177e4 588 }
326f36e9 589 if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf)
056834d9 590 tp->rcv_ssthresh = min(tp->window_clamp, 2U * tp->advmss);
1da177e4
LT
591}
592
40efc6fa
SH
593/* Initialize RCV_MSS value.
594 * RCV_MSS is an our guess about MSS used by the peer.
595 * We haven't any direct information about the MSS.
596 * It's better to underestimate the RCV_MSS rather than overestimate.
597 * Overestimations make us ACKing less frequently than needed.
598 * Underestimations are more easy to detect and fix by tcp_measure_rcv_mss().
599 */
600void tcp_initialize_rcv_mss(struct sock *sk)
601{
cf533ea5 602 const struct tcp_sock *tp = tcp_sk(sk);
40efc6fa
SH
603 unsigned int hint = min_t(unsigned int, tp->advmss, tp->mss_cache);
604
056834d9 605 hint = min(hint, tp->rcv_wnd / 2);
bee7ca9e 606 hint = min(hint, TCP_MSS_DEFAULT);
40efc6fa
SH
607 hint = max(hint, TCP_MIN_MSS);
608
609 inet_csk(sk)->icsk_ack.rcv_mss = hint;
610}
4bc2f18b 611EXPORT_SYMBOL(tcp_initialize_rcv_mss);
40efc6fa 612
1da177e4
LT
613/* Receiver "autotuning" code.
614 *
615 * The algorithm for RTT estimation w/o timestamps is based on
616 * Dynamic Right-Sizing (DRS) by Wu Feng and Mike Fisk of LANL.
7a6498eb 617 * <https://public.lanl.gov/radiant/pubs.html#DRS>
1da177e4
LT
618 *
619 * More detail on this code can be found at
631dd1a8 620 * <http://staff.psc.edu/jheffner/>,
1da177e4
LT
621 * though this reference is out of date. A new paper
622 * is pending.
623 */
624static void tcp_rcv_rtt_update(struct tcp_sock *tp, u32 sample, int win_dep)
625{
645f4c6f 626 u32 new_sample = tp->rcv_rtt_est.rtt_us;
1da177e4
LT
627 long m = sample;
628
1da177e4
LT
629 if (new_sample != 0) {
630 /* If we sample in larger samples in the non-timestamp
631 * case, we could grossly overestimate the RTT especially
632 * with chatty applications or bulk transfer apps which
633 * are stalled on filesystem I/O.
634 *
635 * Also, since we are only going for a minimum in the
31f34269 636 * non-timestamp case, we do not smooth things out
caa20d9a 637 * else with timestamps disabled convergence takes too
1da177e4
LT
638 * long.
639 */
640 if (!win_dep) {
641 m -= (new_sample >> 3);
642 new_sample += m;
18a223e0
NC
643 } else {
644 m <<= 3;
645 if (m < new_sample)
646 new_sample = m;
647 }
1da177e4 648 } else {
caa20d9a 649 /* No previous measure. */
1da177e4
LT
650 new_sample = m << 3;
651 }
652
645f4c6f 653 tp->rcv_rtt_est.rtt_us = new_sample;
1da177e4
LT
654}
655
656static inline void tcp_rcv_rtt_measure(struct tcp_sock *tp)
657{
645f4c6f
ED
658 u32 delta_us;
659
9a568de4 660 if (tp->rcv_rtt_est.time == 0)
1da177e4
LT
661 goto new_measure;
662 if (before(tp->rcv_nxt, tp->rcv_rtt_est.seq))
663 return;
9a568de4 664 delta_us = tcp_stamp_us_delta(tp->tcp_mstamp, tp->rcv_rtt_est.time);
9ee11bd0
WW
665 if (!delta_us)
666 delta_us = 1;
645f4c6f 667 tcp_rcv_rtt_update(tp, delta_us, 1);
1da177e4
LT
668
669new_measure:
670 tp->rcv_rtt_est.seq = tp->rcv_nxt + tp->rcv_wnd;
645f4c6f 671 tp->rcv_rtt_est.time = tp->tcp_mstamp;
1da177e4
LT
672}
673
056834d9
IJ
674static inline void tcp_rcv_rtt_measure_ts(struct sock *sk,
675 const struct sk_buff *skb)
1da177e4 676{
463c84b9 677 struct tcp_sock *tp = tcp_sk(sk);
9a568de4 678
3f6c65d6
WW
679 if (tp->rx_opt.rcv_tsecr == tp->rcv_rtt_last_tsecr)
680 return;
681 tp->rcv_rtt_last_tsecr = tp->rx_opt.rcv_tsecr;
682
683 if (TCP_SKB_CB(skb)->end_seq -
684 TCP_SKB_CB(skb)->seq >= inet_csk(sk)->icsk_ack.rcv_mss) {
9a568de4 685 u32 delta = tcp_time_stamp(tp) - tp->rx_opt.rcv_tsecr;
9ee11bd0 686 u32 delta_us;
9a568de4 687
9efdda4e
ED
688 if (likely(delta < INT_MAX / (USEC_PER_SEC / TCP_TS_HZ))) {
689 if (!delta)
690 delta = 1;
691 delta_us = delta * (USEC_PER_SEC / TCP_TS_HZ);
692 tcp_rcv_rtt_update(tp, delta_us, 0);
693 }
9a568de4 694 }
1da177e4
LT
695}
696
697/*
698 * This function should be called every time data is copied to user space.
699 * It calculates the appropriate TCP receive buffer space.
700 */
701void tcp_rcv_space_adjust(struct sock *sk)
702{
703 struct tcp_sock *tp = tcp_sk(sk);
607065ba 704 u32 copied;
1da177e4 705 int time;
e905a9ed 706
6163849d
YS
707 trace_tcp_rcv_space_adjust(sk);
708
86323850 709 tcp_mstamp_refresh(tp);
9a568de4 710 time = tcp_stamp_us_delta(tp->tcp_mstamp, tp->rcvq_space.time);
645f4c6f 711 if (time < (tp->rcv_rtt_est.rtt_us >> 3) || tp->rcv_rtt_est.rtt_us == 0)
1da177e4 712 return;
e905a9ed 713
b0983d3c
ED
714 /* Number of bytes copied to user in last RTT */
715 copied = tp->copied_seq - tp->rcvq_space.seq;
716 if (copied <= tp->rcvq_space.space)
717 goto new_measure;
718
719 /* A bit of theory :
720 * copied = bytes received in previous RTT, our base window
721 * To cope with packet losses, we need a 2x factor
722 * To cope with slow start, and sender growing its cwin by 100 %
723 * every RTT, we need a 4x factor, because the ACK we are sending
724 * now is for the next RTT, not the current one :
725 * <prev RTT . ><current RTT .. ><next RTT .... >
726 */
727
78047648 728 if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_moderate_rcvbuf) &&
b0983d3c 729 !(sk->sk_userlocks & SOCK_RCVBUF_LOCK)) {
607065ba 730 int rcvmem, rcvbuf;
c3916ad9 731 u64 rcvwin, grow;
1da177e4 732
b0983d3c
ED
733 /* minimal window to cope with packet losses, assuming
734 * steady state. Add some cushion because of small variations.
735 */
607065ba 736 rcvwin = ((u64)copied << 1) + 16 * tp->advmss;
1da177e4 737
c3916ad9
ED
738 /* Accommodate for sender rate increase (eg. slow start) */
739 grow = rcvwin * (copied - tp->rcvq_space.space);
740 do_div(grow, tp->rcvq_space.space);
741 rcvwin += (grow << 1);
1da177e4 742
b0983d3c 743 rcvmem = SKB_TRUESIZE(tp->advmss + MAX_TCP_HEADER);
94f0893e 744 while (tcp_win_from_space(sk, rcvmem) < tp->advmss)
b0983d3c 745 rcvmem += 128;
1da177e4 746
607065ba
ED
747 do_div(rcvwin, tp->advmss);
748 rcvbuf = min_t(u64, rcvwin * rcvmem,
02739545 749 READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_rmem[2]));
b0983d3c 750 if (rcvbuf > sk->sk_rcvbuf) {
ebb3b78d 751 WRITE_ONCE(sk->sk_rcvbuf, rcvbuf);
1da177e4 752
b0983d3c 753 /* Make the window clamp follow along. */
02db5571 754 tp->window_clamp = tcp_win_from_space(sk, rcvbuf);
1da177e4
LT
755 }
756 }
b0983d3c 757 tp->rcvq_space.space = copied;
e905a9ed 758
1da177e4
LT
759new_measure:
760 tp->rcvq_space.seq = tp->copied_seq;
645f4c6f 761 tp->rcvq_space.time = tp->tcp_mstamp;
1da177e4
LT
762}
763
764/* There is something which you must keep in mind when you analyze the
765 * behavior of the tp->ato delayed ack timeout interval. When a
766 * connection starts up, we want to ack as quickly as possible. The
767 * problem is that "good" TCP's do slow start at the beginning of data
768 * transmission. The means that until we send the first few ACK's the
769 * sender will sit on his end and only queue most of his data, because
770 * he can only send snd_cwnd unacked packets at any given time. For
771 * each ACK we send, he increments snd_cwnd and transmits more of his
772 * queue. -DaveM
773 */
9e412ba7 774static void tcp_event_data_recv(struct sock *sk, struct sk_buff *skb)
1da177e4 775{
9e412ba7 776 struct tcp_sock *tp = tcp_sk(sk);
463c84b9 777 struct inet_connection_sock *icsk = inet_csk(sk);
1da177e4
LT
778 u32 now;
779
463c84b9 780 inet_csk_schedule_ack(sk);
1da177e4 781
463c84b9 782 tcp_measure_rcv_mss(sk, skb);
1da177e4
LT
783
784 tcp_rcv_rtt_measure(tp);
e905a9ed 785
70eabf0e 786 now = tcp_jiffies32;
1da177e4 787
463c84b9 788 if (!icsk->icsk_ack.ato) {
1da177e4
LT
789 /* The _first_ data packet received, initialize
790 * delayed ACK engine.
791 */
9a9c9b51 792 tcp_incr_quickack(sk, TCP_MAX_QUICKACKS);
463c84b9 793 icsk->icsk_ack.ato = TCP_ATO_MIN;
1da177e4 794 } else {
463c84b9 795 int m = now - icsk->icsk_ack.lrcvtime;
1da177e4 796
056834d9 797 if (m <= TCP_ATO_MIN / 2) {
1da177e4 798 /* The fastest case is the first. */
463c84b9
ACM
799 icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + TCP_ATO_MIN / 2;
800 } else if (m < icsk->icsk_ack.ato) {
801 icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + m;
802 if (icsk->icsk_ack.ato > icsk->icsk_rto)
803 icsk->icsk_ack.ato = icsk->icsk_rto;
804 } else if (m > icsk->icsk_rto) {
caa20d9a 805 /* Too long gap. Apparently sender failed to
1da177e4
LT
806 * restart window, so that we send ACKs quickly.
807 */
9a9c9b51 808 tcp_incr_quickack(sk, TCP_MAX_QUICKACKS);
1da177e4
LT
809 }
810 }
463c84b9 811 icsk->icsk_ack.lrcvtime = now;
1da177e4 812
f4c9f85f 813 tcp_ecn_check_ce(sk, skb);
1da177e4
LT
814
815 if (skb->len >= 128)
240bfd13 816 tcp_grow_window(sk, skb, true);
1da177e4
LT
817}
818
1da177e4
LT
819/* Called to compute a smoothed rtt estimate. The data fed to this
820 * routine either comes from timestamps, or from segments that were
821 * known _not_ to have been retransmitted [see Karn/Partridge
822 * Proceedings SIGCOMM 87]. The algorithm is from the SIGCOMM 88
823 * piece by Van Jacobson.
824 * NOTE: the next three routines used to be one big routine.
825 * To save cycles in the RFC 1323 implementation it was better to break
826 * it up into three procedures. -- erics
827 */
740b0f18 828static void tcp_rtt_estimator(struct sock *sk, long mrtt_us)
1da177e4 829{
6687e988 830 struct tcp_sock *tp = tcp_sk(sk);
740b0f18
ED
831 long m = mrtt_us; /* RTT */
832 u32 srtt = tp->srtt_us;
1da177e4 833
1da177e4
LT
834 /* The following amusing code comes from Jacobson's
835 * article in SIGCOMM '88. Note that rtt and mdev
836 * are scaled versions of rtt and mean deviation.
e905a9ed 837 * This is designed to be as fast as possible
1da177e4
LT
838 * m stands for "measurement".
839 *
840 * On a 1990 paper the rto value is changed to:
841 * RTO = rtt + 4 * mdev
842 *
843 * Funny. This algorithm seems to be very broken.
844 * These formulae increase RTO, when it should be decreased, increase
31f34269 845 * too slowly, when it should be increased quickly, decrease too quickly
1da177e4
LT
846 * etc. I guess in BSD RTO takes ONE value, so that it is absolutely
847 * does not matter how to _calculate_ it. Seems, it was trap
848 * that VJ failed to avoid. 8)
849 */
4a5ab4e2
ED
850 if (srtt != 0) {
851 m -= (srtt >> 3); /* m is now error in rtt est */
852 srtt += m; /* rtt = 7/8 rtt + 1/8 new */
1da177e4
LT
853 if (m < 0) {
854 m = -m; /* m is now abs(error) */
740b0f18 855 m -= (tp->mdev_us >> 2); /* similar update on mdev */
1da177e4
LT
856 /* This is similar to one of Eifel findings.
857 * Eifel blocks mdev updates when rtt decreases.
858 * This solution is a bit different: we use finer gain
859 * for mdev in this case (alpha*beta).
860 * Like Eifel it also prevents growth of rto,
861 * but also it limits too fast rto decreases,
862 * happening in pure Eifel.
863 */
864 if (m > 0)
865 m >>= 3;
866 } else {
740b0f18 867 m -= (tp->mdev_us >> 2); /* similar update on mdev */
1da177e4 868 }
740b0f18
ED
869 tp->mdev_us += m; /* mdev = 3/4 mdev + 1/4 new */
870 if (tp->mdev_us > tp->mdev_max_us) {
871 tp->mdev_max_us = tp->mdev_us;
872 if (tp->mdev_max_us > tp->rttvar_us)
873 tp->rttvar_us = tp->mdev_max_us;
1da177e4
LT
874 }
875 if (after(tp->snd_una, tp->rtt_seq)) {
740b0f18
ED
876 if (tp->mdev_max_us < tp->rttvar_us)
877 tp->rttvar_us -= (tp->rttvar_us - tp->mdev_max_us) >> 2;
1da177e4 878 tp->rtt_seq = tp->snd_nxt;
740b0f18 879 tp->mdev_max_us = tcp_rto_min_us(sk);
23729ff2
SF
880
881 tcp_bpf_rtt(sk);
1da177e4
LT
882 }
883 } else {
884 /* no previous measure. */
4a5ab4e2 885 srtt = m << 3; /* take the measured time to be rtt */
740b0f18
ED
886 tp->mdev_us = m << 1; /* make sure rto = 3*rtt */
887 tp->rttvar_us = max(tp->mdev_us, tcp_rto_min_us(sk));
888 tp->mdev_max_us = tp->rttvar_us;
1da177e4 889 tp->rtt_seq = tp->snd_nxt;
23729ff2
SF
890
891 tcp_bpf_rtt(sk);
1da177e4 892 }
740b0f18 893 tp->srtt_us = max(1U, srtt);
1da177e4
LT
894}
895
95bd09eb
ED
896static void tcp_update_pacing_rate(struct sock *sk)
897{
898 const struct tcp_sock *tp = tcp_sk(sk);
899 u64 rate;
900
901 /* set sk_pacing_rate to 200 % of current rate (mss * cwnd / srtt) */
43e122b0
ED
902 rate = (u64)tp->mss_cache * ((USEC_PER_SEC / 100) << 3);
903
904 /* current rate is (cwnd * mss) / srtt
905 * In Slow Start [1], set sk_pacing_rate to 200 % the current rate.
906 * In Congestion Avoidance phase, set it to 120 % the current rate.
907 *
908 * [1] : Normal Slow Start condition is (tp->snd_cwnd < tp->snd_ssthresh)
909 * If snd_cwnd >= (tp->snd_ssthresh / 2), we are approaching
910 * end of slow start and should slow down.
911 */
40570375 912 if (tcp_snd_cwnd(tp) < tp->snd_ssthresh / 2)
59bf6c65 913 rate *= READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_pacing_ss_ratio);
43e122b0 914 else
59bf6c65 915 rate *= READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_pacing_ca_ratio);
95bd09eb 916
40570375 917 rate *= max(tcp_snd_cwnd(tp), tp->packets_out);
95bd09eb 918
740b0f18
ED
919 if (likely(tp->srtt_us))
920 do_div(rate, tp->srtt_us);
95bd09eb 921
a9da6f29 922 /* WRITE_ONCE() is needed because sch_fq fetches sk_pacing_rate
ba537427
ED
923 * without any lock. We want to make sure compiler wont store
924 * intermediate values in this location.
925 */
a9da6f29
MR
926 WRITE_ONCE(sk->sk_pacing_rate, min_t(u64, rate,
927 sk->sk_max_pacing_rate));
95bd09eb
ED
928}
929
1da177e4
LT
930/* Calculate rto without backoff. This is the second half of Van Jacobson's
931 * routine referred to above.
932 */
f7e56a76 933static void tcp_set_rto(struct sock *sk)
1da177e4 934{
463c84b9 935 const struct tcp_sock *tp = tcp_sk(sk);
1da177e4
LT
936 /* Old crap is replaced with new one. 8)
937 *
938 * More seriously:
939 * 1. If rtt variance happened to be less 50msec, it is hallucination.
940 * It cannot be less due to utterly erratic ACK generation made
941 * at least by solaris and freebsd. "Erratic ACKs" has _nothing_
942 * to do with delayed acks, because at cwnd>2 true delack timeout
943 * is invisible. Actually, Linux-2.4 also generates erratic
caa20d9a 944 * ACKs in some circumstances.
1da177e4 945 */
f1ecd5d9 946 inet_csk(sk)->icsk_rto = __tcp_set_rto(tp);
1da177e4
LT
947
948 /* 2. Fixups made earlier cannot be right.
949 * If we do not estimate RTO correctly without them,
950 * all the algo is pure shit and should be replaced
caa20d9a 951 * with correct one. It is exactly, which we pretend to do.
1da177e4 952 */
1da177e4 953
ee6aac59
IJ
954 /* NOTE: clamping at TCP_RTO_MIN is not required, current algo
955 * guarantees that rto is higher.
956 */
f1ecd5d9 957 tcp_bound_rto(sk);
1da177e4
LT
958}
959
cf533ea5 960__u32 tcp_init_cwnd(const struct tcp_sock *tp, const struct dst_entry *dst)
1da177e4
LT
961{
962 __u32 cwnd = (dst ? dst_metric(dst, RTAX_INITCWND) : 0);
963
22b71c8f 964 if (!cwnd)
442b9635 965 cwnd = TCP_INIT_CWND;
1da177e4
LT
966 return min_t(__u32, cwnd, tp->snd_cwnd_clamp);
967}
968
a71d77e6
PJ
969struct tcp_sacktag_state {
970 /* Timestamps for earliest and latest never-retransmitted segment
971 * that was SACKed. RTO needs the earliest RTT to stay conservative,
972 * but congestion control should still get an accurate delay signal.
973 */
974 u64 first_sackt;
975 u64 last_sackt;
976 u32 reord;
977 u32 sack_delivered;
978 int flag;
979 unsigned int mss_now;
980 struct rate_sample *rate;
981};
982
ad2b9b0f
PJ
983/* Take a notice that peer is sending D-SACKs. Skip update of data delivery
984 * and spurious retransmission information if this DSACK is unlikely caused by
985 * sender's action:
986 * - DSACKed sequence range is larger than maximum receiver's window.
987 * - Total no. of DSACKed segments exceed the total no. of retransmitted segs.
988 */
a71d77e6
PJ
989static u32 tcp_dsack_seen(struct tcp_sock *tp, u32 start_seq,
990 u32 end_seq, struct tcp_sacktag_state *state)
e60402d0 991{
a71d77e6
PJ
992 u32 seq_len, dup_segs = 1;
993
ad2b9b0f
PJ
994 if (!before(start_seq, end_seq))
995 return 0;
996
997 seq_len = end_seq - start_seq;
998 /* Dubious DSACK: DSACKed range greater than maximum advertised rwnd */
999 if (seq_len > tp->max_window)
1000 return 0;
1001 if (seq_len > tp->mss_cache)
1002 dup_segs = DIV_ROUND_UP(seq_len, tp->mss_cache);
63f367d9
YC
1003 else if (tp->tlp_high_seq && tp->tlp_high_seq == end_seq)
1004 state->flag |= FLAG_DSACK_TLP;
ad2b9b0f
PJ
1005
1006 tp->dsack_dups += dup_segs;
1007 /* Skip the DSACK if dup segs weren't retransmitted by sender */
1008 if (tp->dsack_dups > tp->total_retrans)
1009 return 0;
a71d77e6 1010
ab56222a 1011 tp->rx_opt.sack_ok |= TCP_DSACK_SEEN;
a657db03
NC
1012 /* We increase the RACK ordering window in rounds where we receive
1013 * DSACKs that may have been due to reordering causing RACK to trigger
1014 * a spurious fast recovery. Thus RACK ignores DSACKs that happen
1015 * without having seen reordering, or that match TLP probes (TLP
1016 * is timer-driven, not triggered by RACK).
1017 */
1018 if (tp->reord_seen && !(state->flag & FLAG_DSACK_TLP))
1019 tp->rack.dsack_seen = 1;
a71d77e6
PJ
1020
1021 state->flag |= FLAG_DSACKING_ACK;
1022 /* A spurious retransmission is delivered */
1023 state->sack_delivered += dup_segs;
1024
1025 return dup_segs;
e60402d0
IJ
1026}
1027
737ff314
YC
1028/* It's reordering when higher sequence was delivered (i.e. sacked) before
1029 * some lower never-retransmitted sequence ("low_seq"). The maximum reordering
1030 * distance is approximated in full-mss packet distance ("reordering").
1031 */
1032static void tcp_check_sack_reordering(struct sock *sk, const u32 low_seq,
1033 const int ts)
1da177e4 1034{
6687e988 1035 struct tcp_sock *tp = tcp_sk(sk);
737ff314
YC
1036 const u32 mss = tp->mss_cache;
1037 u32 fack, metric;
40b215e5 1038
737ff314
YC
1039 fack = tcp_highest_sack_seq(tp);
1040 if (!before(low_seq, fack))
6f5b24ee
SHY
1041 return;
1042
737ff314
YC
1043 metric = fack - low_seq;
1044 if ((metric > tp->reordering * mss) && mss) {
1da177e4 1045#if FASTRETRANS_DEBUG > 1
91df42be
JP
1046 pr_debug("Disorder%d %d %u f%u s%u rr%d\n",
1047 tp->rx_opt.sack_ok, inet_csk(sk)->icsk_ca_state,
1048 tp->reordering,
737ff314 1049 0,
91df42be
JP
1050 tp->sacked_out,
1051 tp->undo_marker ? tp->undo_retrans : 0);
1da177e4 1052#endif
737ff314 1053 tp->reordering = min_t(u32, (metric + mss - 1) / mss,
a11e5b3e 1054 READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_max_reordering));
1da177e4 1055 }
eed530b6 1056
2d2517ee 1057 /* This exciting event is worth to be remembered. 8) */
7ec65372 1058 tp->reord_seen++;
737ff314
YC
1059 NET_INC_STATS(sock_net(sk),
1060 ts ? LINUX_MIB_TCPTSREORDER : LINUX_MIB_TCPSACKREORDER);
1da177e4
LT
1061}
1062
68698970
YC
1063 /* This must be called before lost_out or retrans_out are updated
1064 * on a new loss, because we want to know if all skbs previously
1065 * known to be lost have already been retransmitted, indicating
1066 * that this newly lost skb is our next skb to retransmit.
1067 */
c8c213f2
IJ
1068static void tcp_verify_retransmit_hint(struct tcp_sock *tp, struct sk_buff *skb)
1069{
e176b1ba
PY
1070 if ((!tp->retransmit_skb_hint && tp->retrans_out >= tp->lost_out) ||
1071 (tp->retransmit_skb_hint &&
1072 before(TCP_SKB_CB(skb)->seq,
1073 TCP_SKB_CB(tp->retransmit_skb_hint)->seq)))
006f582c 1074 tp->retransmit_skb_hint = skb;
c8c213f2
IJ
1075}
1076
9cd8b6c9
YC
1077/* Sum the number of packets on the wire we have marked as lost, and
1078 * notify the congestion control module that the given skb was marked lost.
1079 */
1080static void tcp_notify_skb_loss_event(struct tcp_sock *tp, const struct sk_buff *skb)
1081{
1082 tp->lost += tcp_skb_pcount(skb);
1083}
1084
fd214674
YC
1085void tcp_mark_skb_lost(struct sock *sk, struct sk_buff *skb)
1086{
68698970 1087 __u8 sacked = TCP_SKB_CB(skb)->sacked;
fd214674
YC
1088 struct tcp_sock *tp = tcp_sk(sk);
1089
68698970
YC
1090 if (sacked & TCPCB_SACKED_ACKED)
1091 return;
0682e690 1092
68698970
YC
1093 tcp_verify_retransmit_hint(tp, skb);
1094 if (sacked & TCPCB_LOST) {
1095 if (sacked & TCPCB_SACKED_RETRANS) {
1096 /* Account for retransmits that are lost again */
1097 TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
1098 tp->retrans_out -= tcp_skb_pcount(skb);
1099 NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPLOSTRETRANSMIT,
1100 tcp_skb_pcount(skb));
9cd8b6c9 1101 tcp_notify_skb_loss_event(tp, skb);
68698970
YC
1102 }
1103 } else {
1104 tp->lost_out += tcp_skb_pcount(skb);
1105 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
9cd8b6c9 1106 tcp_notify_skb_loss_event(tp, skb);
68698970 1107 }
0682e690
NC
1108}
1109
082d4fa9
YS
1110/* Updates the delivered and delivered_ce counts */
1111static void tcp_count_delivered(struct tcp_sock *tp, u32 delivered,
1112 bool ece_ack)
1113{
1114 tp->delivered += delivered;
1115 if (ece_ack)
1116 tp->delivered_ce += delivered;
1117}
1118
1da177e4
LT
1119/* This procedure tags the retransmission queue when SACKs arrive.
1120 *
1121 * We have three tag bits: SACKED(S), RETRANS(R) and LOST(L).
1122 * Packets in queue with these bits set are counted in variables
1123 * sacked_out, retrans_out and lost_out, correspondingly.
1124 *
1125 * Valid combinations are:
1126 * Tag InFlight Description
1127 * 0 1 - orig segment is in flight.
1128 * S 0 - nothing flies, orig reached receiver.
1129 * L 0 - nothing flies, orig lost by net.
1130 * R 2 - both orig and retransmit are in flight.
1131 * L|R 1 - orig is lost, retransmit is in flight.
1132 * S|R 1 - orig reached receiver, retrans is still in flight.
1133 * (L|S|R is logically valid, it could occur when L|R is sacked,
1134 * but it is equivalent to plain S and code short-curcuits it to S.
1135 * L|S is logically invalid, it would mean -1 packet in flight 8))
1136 *
1137 * These 6 states form finite state machine, controlled by the following events:
1138 * 1. New ACK (+SACK) arrives. (tcp_sacktag_write_queue())
1139 * 2. Retransmission. (tcp_retransmit_skb(), tcp_xmit_retransmit_queue())
974c1236 1140 * 3. Loss detection event of two flavors:
1da177e4
LT
1141 * A. Scoreboard estimator decided the packet is lost.
1142 * A'. Reno "three dupacks" marks head of queue lost.
974c1236 1143 * B. SACK arrives sacking SND.NXT at the moment, when the
1da177e4
LT
1144 * segment was retransmitted.
1145 * 4. D-SACK added new rule: D-SACK changes any tag to S.
1146 *
1147 * It is pleasant to note, that state diagram turns out to be commutative,
1148 * so that we are allowed not to be bothered by order of our actions,
1149 * when multiple events arrive simultaneously. (see the function below).
1150 *
1151 * Reordering detection.
1152 * --------------------
1153 * Reordering metric is maximal distance, which a packet can be displaced
1154 * in packet stream. With SACKs we can estimate it:
1155 *
1156 * 1. SACK fills old hole and the corresponding segment was not
1157 * ever retransmitted -> reordering. Alas, we cannot use it
1158 * when segment was retransmitted.
1159 * 2. The last flaw is solved with D-SACK. D-SACK arrives
1160 * for retransmitted and already SACKed segment -> reordering..
1161 * Both of these heuristics are not used in Loss state, when we cannot
1162 * account for retransmits accurately.
5b3c9882
IJ
1163 *
1164 * SACK block validation.
1165 * ----------------------
1166 *
1167 * SACK block range validation checks that the received SACK block fits to
1168 * the expected sequence limits, i.e., it is between SND.UNA and SND.NXT.
1169 * Note that SND.UNA is not included to the range though being valid because
0e835331
IJ
1170 * it means that the receiver is rather inconsistent with itself reporting
1171 * SACK reneging when it should advance SND.UNA. Such SACK block this is
1172 * perfectly valid, however, in light of RFC2018 which explicitly states
1173 * that "SACK block MUST reflect the newest segment. Even if the newest
1174 * segment is going to be discarded ...", not that it looks very clever
1175 * in case of head skb. Due to potentional receiver driven attacks, we
1176 * choose to avoid immediate execution of a walk in write queue due to
1177 * reneging and defer head skb's loss recovery to standard loss recovery
1178 * procedure that will eventually trigger (nothing forbids us doing this).
5b3c9882
IJ
1179 *
1180 * Implements also blockage to start_seq wrap-around. Problem lies in the
1181 * fact that though start_seq (s) is before end_seq (i.e., not reversed),
1182 * there's no guarantee that it will be before snd_nxt (n). The problem
1183 * happens when start_seq resides between end_seq wrap (e_w) and snd_nxt
1184 * wrap (s_w):
1185 *
1186 * <- outs wnd -> <- wrapzone ->
1187 * u e n u_w e_w s n_w
1188 * | | | | | | |
1189 * |<------------+------+----- TCP seqno space --------------+---------->|
1190 * ...-- <2^31 ->| |<--------...
1191 * ...---- >2^31 ------>| |<--------...
1192 *
1193 * Current code wouldn't be vulnerable but it's better still to discard such
1194 * crazy SACK blocks. Doing this check for start_seq alone closes somewhat
1195 * similar case (end_seq after snd_nxt wrap) as earlier reversed check in
1196 * snd_nxt wrap -> snd_una region will then become "well defined", i.e.,
1197 * equal to the ideal case (infinite seqno space without wrap caused issues).
1198 *
1199 * With D-SACK the lower bound is extended to cover sequence space below
1200 * SND.UNA down to undo_marker, which is the last point of interest. Yet
564262c1 1201 * again, D-SACK block must not to go across snd_una (for the same reason as
5b3c9882
IJ
1202 * for the normal SACK blocks, explained above). But there all simplicity
1203 * ends, TCP might receive valid D-SACKs below that. As long as they reside
1204 * fully below undo_marker they do not affect behavior in anyway and can
1205 * therefore be safely ignored. In rare cases (which are more or less
1206 * theoretical ones), the D-SACK will nicely cross that boundary due to skb
1207 * fragmentation and packet reordering past skb's retransmission. To consider
1208 * them correctly, the acceptable range must be extended even more though
1209 * the exact amount is rather hard to quantify. However, tp->max_window can
1210 * be used as an exaggerated estimate.
1da177e4 1211 */
a2a385d6
ED
1212static bool tcp_is_sackblock_valid(struct tcp_sock *tp, bool is_dsack,
1213 u32 start_seq, u32 end_seq)
5b3c9882
IJ
1214{
1215 /* Too far in future, or reversed (interpretation is ambiguous) */
1216 if (after(end_seq, tp->snd_nxt) || !before(start_seq, end_seq))
a2a385d6 1217 return false;
5b3c9882
IJ
1218
1219 /* Nasty start_seq wrap-around check (see comments above) */
1220 if (!before(start_seq, tp->snd_nxt))
a2a385d6 1221 return false;
5b3c9882 1222
564262c1 1223 /* In outstanding window? ...This is valid exit for D-SACKs too.
5b3c9882
IJ
1224 * start_seq == snd_una is non-sensical (see comments above)
1225 */
1226 if (after(start_seq, tp->snd_una))
a2a385d6 1227 return true;
5b3c9882
IJ
1228
1229 if (!is_dsack || !tp->undo_marker)
a2a385d6 1230 return false;
5b3c9882
IJ
1231
1232 /* ...Then it's D-SACK, and must reside below snd_una completely */
f779b2d6 1233 if (after(end_seq, tp->snd_una))
a2a385d6 1234 return false;
5b3c9882
IJ
1235
1236 if (!before(start_seq, tp->undo_marker))
a2a385d6 1237 return true;
5b3c9882
IJ
1238
1239 /* Too old */
1240 if (!after(end_seq, tp->undo_marker))
a2a385d6 1241 return false;
5b3c9882
IJ
1242
1243 /* Undo_marker boundary crossing (overestimates a lot). Known already:
1244 * start_seq < undo_marker and end_seq >= undo_marker.
1245 */
1246 return !before(start_seq, end_seq - tp->max_window);
1247}
1248
a2a385d6
ED
1249static bool tcp_check_dsack(struct sock *sk, const struct sk_buff *ack_skb,
1250 struct tcp_sack_block_wire *sp, int num_sacks,
a71d77e6 1251 u32 prior_snd_una, struct tcp_sacktag_state *state)
d06e021d 1252{
1ed83465 1253 struct tcp_sock *tp = tcp_sk(sk);
d3e2ce3b
HH
1254 u32 start_seq_0 = get_unaligned_be32(&sp[0].start_seq);
1255 u32 end_seq_0 = get_unaligned_be32(&sp[0].end_seq);
a71d77e6 1256 u32 dup_segs;
d06e021d
DM
1257
1258 if (before(start_seq_0, TCP_SKB_CB(ack_skb)->ack_seq)) {
c10d9310 1259 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKRECV);
d06e021d 1260 } else if (num_sacks > 1) {
d3e2ce3b
HH
1261 u32 end_seq_1 = get_unaligned_be32(&sp[1].end_seq);
1262 u32 start_seq_1 = get_unaligned_be32(&sp[1].start_seq);
d06e021d 1263
a71d77e6
PJ
1264 if (after(end_seq_0, end_seq_1) || before(start_seq_0, start_seq_1))
1265 return false;
1266 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKOFORECV);
1267 } else {
1268 return false;
d06e021d
DM
1269 }
1270
a71d77e6 1271 dup_segs = tcp_dsack_seen(tp, start_seq_0, end_seq_0, state);
ad2b9b0f
PJ
1272 if (!dup_segs) { /* Skip dubious DSACK */
1273 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKIGNOREDDUBIOUS);
1274 return false;
1275 }
1276
e3a5a1e8 1277 NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPDSACKRECVSEGS, dup_segs);
a71d77e6 1278
d06e021d 1279 /* D-SACK for already forgotten data... Do dumb counting. */
a71d77e6 1280 if (tp->undo_marker && tp->undo_retrans > 0 &&
d06e021d
DM
1281 !after(end_seq_0, prior_snd_una) &&
1282 after(end_seq_0, tp->undo_marker))
a71d77e6 1283 tp->undo_retrans = max_t(int, 0, tp->undo_retrans - dup_segs);
d06e021d 1284
a71d77e6 1285 return true;
d06e021d
DM
1286}
1287
d1935942
IJ
1288/* Check if skb is fully within the SACK block. In presence of GSO skbs,
1289 * the incoming SACK may not exactly match but we can find smaller MSS
1290 * aligned portion of it that matches. Therefore we might need to fragment
1291 * which may fail and creates some hassle (caller must handle error case
1292 * returns).
832d11c5
IJ
1293 *
1294 * FIXME: this could be merged to shift decision code
d1935942 1295 */
0f79efdc 1296static int tcp_match_skb_to_sack(struct sock *sk, struct sk_buff *skb,
a2a385d6 1297 u32 start_seq, u32 end_seq)
d1935942 1298{
a2a385d6
ED
1299 int err;
1300 bool in_sack;
d1935942 1301 unsigned int pkt_len;
adb92db8 1302 unsigned int mss;
d1935942
IJ
1303
1304 in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
1305 !before(end_seq, TCP_SKB_CB(skb)->end_seq);
1306
1307 if (tcp_skb_pcount(skb) > 1 && !in_sack &&
1308 after(TCP_SKB_CB(skb)->end_seq, start_seq)) {
adb92db8 1309 mss = tcp_skb_mss(skb);
d1935942
IJ
1310 in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq);
1311
adb92db8 1312 if (!in_sack) {
d1935942 1313 pkt_len = start_seq - TCP_SKB_CB(skb)->seq;
adb92db8
IJ
1314 if (pkt_len < mss)
1315 pkt_len = mss;
1316 } else {
d1935942 1317 pkt_len = end_seq - TCP_SKB_CB(skb)->seq;
adb92db8
IJ
1318 if (pkt_len < mss)
1319 return -EINVAL;
1320 }
1321
1322 /* Round if necessary so that SACKs cover only full MSSes
1323 * and/or the remaining small portion (if present)
1324 */
1325 if (pkt_len > mss) {
1326 unsigned int new_len = (pkt_len / mss) * mss;
b451e5d2 1327 if (!in_sack && new_len < pkt_len)
adb92db8 1328 new_len += mss;
adb92db8
IJ
1329 pkt_len = new_len;
1330 }
b451e5d2
YC
1331
1332 if (pkt_len >= skb->len && !in_sack)
1333 return 0;
1334
75c119af
ED
1335 err = tcp_fragment(sk, TCP_FRAG_IN_RTX_QUEUE, skb,
1336 pkt_len, mss, GFP_ATOMIC);
d1935942
IJ
1337 if (err < 0)
1338 return err;
1339 }
1340
1341 return in_sack;
1342}
1343
cc9a672e
NC
1344/* Mark the given newly-SACKed range as such, adjusting counters and hints. */
1345static u8 tcp_sacktag_one(struct sock *sk,
1346 struct tcp_sacktag_state *state, u8 sacked,
1347 u32 start_seq, u32 end_seq,
740b0f18 1348 int dup_sack, int pcount,
9a568de4 1349 u64 xmit_time)
9e10c47c 1350{
6859d494 1351 struct tcp_sock *tp = tcp_sk(sk);
9e10c47c
IJ
1352
1353 /* Account D-SACK for retransmitted packet. */
1354 if (dup_sack && (sacked & TCPCB_RETRANS)) {
6e08d5e3 1355 if (tp->undo_marker && tp->undo_retrans > 0 &&
cc9a672e 1356 after(end_seq, tp->undo_marker))
4f884f39 1357 tp->undo_retrans = max_t(int, 0, tp->undo_retrans - pcount);
737ff314
YC
1358 if ((sacked & TCPCB_SACKED_ACKED) &&
1359 before(start_seq, state->reord))
1360 state->reord = start_seq;
9e10c47c
IJ
1361 }
1362
1363 /* Nothing to do; acked frame is about to be dropped (was ACKed). */
cc9a672e 1364 if (!after(end_seq, tp->snd_una))
a1197f5a 1365 return sacked;
9e10c47c
IJ
1366
1367 if (!(sacked & TCPCB_SACKED_ACKED)) {
d2329f10 1368 tcp_rack_advance(tp, sacked, end_seq, xmit_time);
659a8ad5 1369
9e10c47c
IJ
1370 if (sacked & TCPCB_SACKED_RETRANS) {
1371 /* If the segment is not tagged as lost,
1372 * we do not clear RETRANS, believing
1373 * that retransmission is still in flight.
1374 */
1375 if (sacked & TCPCB_LOST) {
a1197f5a 1376 sacked &= ~(TCPCB_LOST|TCPCB_SACKED_RETRANS);
f58b22fd
IJ
1377 tp->lost_out -= pcount;
1378 tp->retrans_out -= pcount;
9e10c47c
IJ
1379 }
1380 } else {
1381 if (!(sacked & TCPCB_RETRANS)) {
1382 /* New sack for not retransmitted frame,
1383 * which was in hole. It is reordering.
1384 */
cc9a672e 1385 if (before(start_seq,
737ff314
YC
1386 tcp_highest_sack_seq(tp)) &&
1387 before(start_seq, state->reord))
1388 state->reord = start_seq;
1389
e33099f9
YC
1390 if (!after(end_seq, tp->high_seq))
1391 state->flag |= FLAG_ORIG_SACK_ACKED;
9a568de4
ED
1392 if (state->first_sackt == 0)
1393 state->first_sackt = xmit_time;
1394 state->last_sackt = xmit_time;
9e10c47c
IJ
1395 }
1396
1397 if (sacked & TCPCB_LOST) {
a1197f5a 1398 sacked &= ~TCPCB_LOST;
f58b22fd 1399 tp->lost_out -= pcount;
9e10c47c
IJ
1400 }
1401 }
1402
a1197f5a
IJ
1403 sacked |= TCPCB_SACKED_ACKED;
1404 state->flag |= FLAG_DATA_SACKED;
f58b22fd 1405 tp->sacked_out += pcount;
082d4fa9 1406 /* Out-of-order packets delivered */
f00394ce 1407 state->sack_delivered += pcount;
9e10c47c 1408
9e10c47c 1409 /* Lost marker hint past SACKed? Tweak RFC3517 cnt */
713bafea 1410 if (tp->lost_skb_hint &&
cc9a672e 1411 before(start_seq, TCP_SKB_CB(tp->lost_skb_hint)->seq))
f58b22fd 1412 tp->lost_cnt_hint += pcount;
9e10c47c
IJ
1413 }
1414
1415 /* D-SACK. We can detect redundant retransmission in S|R and plain R
1416 * frames and clear it. undo_retrans is decreased above, L|R frames
1417 * are accounted above as well.
1418 */
a1197f5a
IJ
1419 if (dup_sack && (sacked & TCPCB_SACKED_RETRANS)) {
1420 sacked &= ~TCPCB_SACKED_RETRANS;
f58b22fd 1421 tp->retrans_out -= pcount;
9e10c47c
IJ
1422 }
1423
a1197f5a 1424 return sacked;
9e10c47c
IJ
1425}
1426
daef52ba
NC
1427/* Shift newly-SACKed bytes from this skb to the immediately previous
1428 * already-SACKed sk_buff. Mark the newly-SACKed bytes as such.
1429 */
f3319816
ED
1430static bool tcp_shifted_skb(struct sock *sk, struct sk_buff *prev,
1431 struct sk_buff *skb,
a2a385d6
ED
1432 struct tcp_sacktag_state *state,
1433 unsigned int pcount, int shifted, int mss,
1434 bool dup_sack)
832d11c5
IJ
1435{
1436 struct tcp_sock *tp = tcp_sk(sk);
daef52ba
NC
1437 u32 start_seq = TCP_SKB_CB(skb)->seq; /* start of newly-SACKed */
1438 u32 end_seq = start_seq + shifted; /* end of newly-SACKed */
832d11c5
IJ
1439
1440 BUG_ON(!pcount);
1441
4c90d3b3
NC
1442 /* Adjust counters and hints for the newly sacked sequence
1443 * range but discard the return value since prev is already
1444 * marked. We must tag the range first because the seq
1445 * advancement below implicitly advances
1446 * tcp_highest_sack_seq() when skb is highest_sack.
1447 */
1448 tcp_sacktag_one(sk, state, TCP_SKB_CB(skb)->sacked,
59c9af42 1449 start_seq, end_seq, dup_sack, pcount,
2fd66ffb 1450 tcp_skb_timestamp_us(skb));
b9f64820 1451 tcp_rate_skb_delivered(sk, skb, state->rate);
4c90d3b3
NC
1452
1453 if (skb == tp->lost_skb_hint)
0af2a0d0
NC
1454 tp->lost_cnt_hint += pcount;
1455
832d11c5
IJ
1456 TCP_SKB_CB(prev)->end_seq += shifted;
1457 TCP_SKB_CB(skb)->seq += shifted;
1458
cd7d8498 1459 tcp_skb_pcount_add(prev, pcount);
3b4929f6 1460 WARN_ON_ONCE(tcp_skb_pcount(skb) < pcount);
cd7d8498 1461 tcp_skb_pcount_add(skb, -pcount);
832d11c5
IJ
1462
1463 /* When we're adding to gso_segs == 1, gso_size will be zero,
1464 * in theory this shouldn't be necessary but as long as DSACK
1465 * code can come after this skb later on it's better to keep
1466 * setting gso_size to something.
1467 */
f69ad292
ED
1468 if (!TCP_SKB_CB(prev)->tcp_gso_size)
1469 TCP_SKB_CB(prev)->tcp_gso_size = mss;
832d11c5
IJ
1470
1471 /* CHECKME: To clear or not to clear? Mimics normal skb currently */
51466a75 1472 if (tcp_skb_pcount(skb) <= 1)
f69ad292 1473 TCP_SKB_CB(skb)->tcp_gso_size = 0;
832d11c5 1474
832d11c5
IJ
1475 /* Difference in this won't matter, both ACKed by the same cumul. ACK */
1476 TCP_SKB_CB(prev)->sacked |= (TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS);
1477
832d11c5
IJ
1478 if (skb->len > 0) {
1479 BUG_ON(!tcp_skb_pcount(skb));
c10d9310 1480 NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKSHIFTED);
a2a385d6 1481 return false;
832d11c5
IJ
1482 }
1483
1484 /* Whole SKB was eaten :-) */
1485
92ee76b6
IJ
1486 if (skb == tp->retransmit_skb_hint)
1487 tp->retransmit_skb_hint = prev;
92ee76b6
IJ
1488 if (skb == tp->lost_skb_hint) {
1489 tp->lost_skb_hint = prev;
1490 tp->lost_cnt_hint -= tcp_skb_pcount(prev);
1491 }
1492
5e8a402f 1493 TCP_SKB_CB(prev)->tcp_flags |= TCP_SKB_CB(skb)->tcp_flags;
a643b5d4 1494 TCP_SKB_CB(prev)->eor = TCP_SKB_CB(skb)->eor;
5e8a402f
ED
1495 if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
1496 TCP_SKB_CB(prev)->end_seq++;
1497
832d11c5
IJ
1498 if (skb == tcp_highest_sack(sk))
1499 tcp_advance_highest_sack(sk, skb);
1500
cfea5a68 1501 tcp_skb_collapse_tstamp(prev, skb);
9a568de4
ED
1502 if (unlikely(TCP_SKB_CB(prev)->tx.delivered_mstamp))
1503 TCP_SKB_CB(prev)->tx.delivered_mstamp = 0;
b9f64820 1504
75c119af 1505 tcp_rtx_queue_unlink_and_free(skb, sk);
832d11c5 1506
c10d9310 1507 NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKMERGED);
111cc8b9 1508
a2a385d6 1509 return true;
832d11c5
IJ
1510}
1511
1512/* I wish gso_size would have a bit more sane initialization than
1513 * something-or-zero which complicates things
1514 */
cf533ea5 1515static int tcp_skb_seglen(const struct sk_buff *skb)
832d11c5 1516{
775ffabf 1517 return tcp_skb_pcount(skb) == 1 ? skb->len : tcp_skb_mss(skb);
832d11c5
IJ
1518}
1519
1520/* Shifting pages past head area doesn't work */
cf533ea5 1521static int skb_can_shift(const struct sk_buff *skb)
832d11c5
IJ
1522{
1523 return !skb_headlen(skb) && skb_is_nonlinear(skb);
1524}
1525
3b4929f6
ED
1526int tcp_skb_shift(struct sk_buff *to, struct sk_buff *from,
1527 int pcount, int shiftlen)
1528{
1529 /* TCP min gso_size is 8 bytes (TCP_MIN_GSO_SIZE)
1530 * Since TCP_SKB_CB(skb)->tcp_gso_segs is 16 bits, we need
1531 * to make sure not storing more than 65535 * 8 bytes per skb,
1532 * even if current MSS is bigger.
1533 */
1534 if (unlikely(to->len + shiftlen >= 65535 * TCP_MIN_GSO_SIZE))
1535 return 0;
1536 if (unlikely(tcp_skb_pcount(to) + pcount > 65535))
1537 return 0;
1538 return skb_shift(to, from, shiftlen);
1539}
1540
832d11c5
IJ
1541/* Try collapsing SACK blocks spanning across multiple skbs to a single
1542 * skb.
1543 */
1544static struct sk_buff *tcp_shift_skb_data(struct sock *sk, struct sk_buff *skb,
a1197f5a 1545 struct tcp_sacktag_state *state,
832d11c5 1546 u32 start_seq, u32 end_seq,
a2a385d6 1547 bool dup_sack)
832d11c5
IJ
1548{
1549 struct tcp_sock *tp = tcp_sk(sk);
1550 struct sk_buff *prev;
1551 int mss;
1552 int pcount = 0;
1553 int len;
1554 int in_sack;
1555
832d11c5
IJ
1556 /* Normally R but no L won't result in plain S */
1557 if (!dup_sack &&
9969ca5f 1558 (TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_RETRANS)) == TCPCB_SACKED_RETRANS)
832d11c5
IJ
1559 goto fallback;
1560 if (!skb_can_shift(skb))
1561 goto fallback;
1562 /* This frame is about to be dropped (was ACKed). */
1563 if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una))
1564 goto fallback;
1565
1566 /* Can only happen with delayed DSACK + discard craziness */
75c119af
ED
1567 prev = skb_rb_prev(skb);
1568 if (!prev)
832d11c5 1569 goto fallback;
832d11c5
IJ
1570
1571 if ((TCP_SKB_CB(prev)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED)
1572 goto fallback;
1573
85712484 1574 if (!tcp_skb_can_collapse(prev, skb))
a643b5d4
MKL
1575 goto fallback;
1576
832d11c5
IJ
1577 in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
1578 !before(end_seq, TCP_SKB_CB(skb)->end_seq);
1579
1580 if (in_sack) {
1581 len = skb->len;
1582 pcount = tcp_skb_pcount(skb);
775ffabf 1583 mss = tcp_skb_seglen(skb);
832d11c5
IJ
1584
1585 /* TODO: Fix DSACKs to not fragment already SACKed and we can
1586 * drop this restriction as unnecessary
1587 */
775ffabf 1588 if (mss != tcp_skb_seglen(prev))
832d11c5
IJ
1589 goto fallback;
1590 } else {
1591 if (!after(TCP_SKB_CB(skb)->end_seq, start_seq))
1592 goto noop;
1593 /* CHECKME: This is non-MSS split case only?, this will
1594 * cause skipped skbs due to advancing loop btw, original
1595 * has that feature too
1596 */
1597 if (tcp_skb_pcount(skb) <= 1)
1598 goto noop;
1599
1600 in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq);
1601 if (!in_sack) {
1602 /* TODO: head merge to next could be attempted here
1603 * if (!after(TCP_SKB_CB(skb)->end_seq, end_seq)),
1604 * though it might not be worth of the additional hassle
1605 *
1606 * ...we can probably just fallback to what was done
1607 * previously. We could try merging non-SACKed ones
1608 * as well but it probably isn't going to buy off
1609 * because later SACKs might again split them, and
1610 * it would make skb timestamp tracking considerably
1611 * harder problem.
1612 */
1613 goto fallback;
1614 }
1615
1616 len = end_seq - TCP_SKB_CB(skb)->seq;
1617 BUG_ON(len < 0);
1618 BUG_ON(len > skb->len);
1619
1620 /* MSS boundaries should be honoured or else pcount will
1621 * severely break even though it makes things bit trickier.
1622 * Optimize common case to avoid most of the divides
1623 */
1624 mss = tcp_skb_mss(skb);
1625
1626 /* TODO: Fix DSACKs to not fragment already SACKed and we can
1627 * drop this restriction as unnecessary
1628 */
775ffabf 1629 if (mss != tcp_skb_seglen(prev))
832d11c5
IJ
1630 goto fallback;
1631
1632 if (len == mss) {
1633 pcount = 1;
1634 } else if (len < mss) {
1635 goto noop;
1636 } else {
1637 pcount = len / mss;
1638 len = pcount * mss;
1639 }
1640 }
1641
4648dc97
NC
1642 /* tcp_sacktag_one() won't SACK-tag ranges below snd_una */
1643 if (!after(TCP_SKB_CB(skb)->seq + len, tp->snd_una))
1644 goto fallback;
1645
3b4929f6 1646 if (!tcp_skb_shift(prev, skb, pcount, len))
832d11c5 1647 goto fallback;
f3319816 1648 if (!tcp_shifted_skb(sk, prev, skb, state, pcount, len, mss, dup_sack))
832d11c5
IJ
1649 goto out;
1650
1651 /* Hole filled allows collapsing with the next as well, this is very
1652 * useful when hole on every nth skb pattern happens
1653 */
75c119af
ED
1654 skb = skb_rb_next(prev);
1655 if (!skb)
832d11c5 1656 goto out;
832d11c5 1657
f0bc52f3 1658 if (!skb_can_shift(skb) ||
f0bc52f3 1659 ((TCP_SKB_CB(skb)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED) ||
775ffabf 1660 (mss != tcp_skb_seglen(skb)))
832d11c5
IJ
1661 goto out;
1662
b67985be
ED
1663 if (!tcp_skb_can_collapse(prev, skb))
1664 goto out;
832d11c5 1665 len = skb->len;
3b4929f6
ED
1666 pcount = tcp_skb_pcount(skb);
1667 if (tcp_skb_shift(prev, skb, pcount, len))
1668 tcp_shifted_skb(sk, prev, skb, state, pcount,
f3319816 1669 len, mss, 0);
832d11c5
IJ
1670
1671out:
832d11c5
IJ
1672 return prev;
1673
1674noop:
1675 return skb;
1676
1677fallback:
c10d9310 1678 NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKSHIFTFALLBACK);
832d11c5
IJ
1679 return NULL;
1680}
1681
68f8353b
IJ
1682static struct sk_buff *tcp_sacktag_walk(struct sk_buff *skb, struct sock *sk,
1683 struct tcp_sack_block *next_dup,
a1197f5a 1684 struct tcp_sacktag_state *state,
68f8353b 1685 u32 start_seq, u32 end_seq,
a2a385d6 1686 bool dup_sack_in)
68f8353b 1687{
832d11c5
IJ
1688 struct tcp_sock *tp = tcp_sk(sk);
1689 struct sk_buff *tmp;
1690
75c119af 1691 skb_rbtree_walk_from(skb) {
68f8353b 1692 int in_sack = 0;
a2a385d6 1693 bool dup_sack = dup_sack_in;
68f8353b 1694
68f8353b
IJ
1695 /* queue is in-order => we can short-circuit the walk early */
1696 if (!before(TCP_SKB_CB(skb)->seq, end_seq))
1697 break;
1698
00db4124 1699 if (next_dup &&
68f8353b
IJ
1700 before(TCP_SKB_CB(skb)->seq, next_dup->end_seq)) {
1701 in_sack = tcp_match_skb_to_sack(sk, skb,
1702 next_dup->start_seq,
1703 next_dup->end_seq);
1704 if (in_sack > 0)
a2a385d6 1705 dup_sack = true;
68f8353b
IJ
1706 }
1707
832d11c5
IJ
1708 /* skb reference here is a bit tricky to get right, since
1709 * shifting can eat and free both this skb and the next,
1710 * so not even _safe variant of the loop is enough.
1711 */
1712 if (in_sack <= 0) {
a1197f5a
IJ
1713 tmp = tcp_shift_skb_data(sk, skb, state,
1714 start_seq, end_seq, dup_sack);
00db4124 1715 if (tmp) {
832d11c5
IJ
1716 if (tmp != skb) {
1717 skb = tmp;
1718 continue;
1719 }
1720
1721 in_sack = 0;
1722 } else {
1723 in_sack = tcp_match_skb_to_sack(sk, skb,
1724 start_seq,
1725 end_seq);
1726 }
1727 }
1728
68f8353b
IJ
1729 if (unlikely(in_sack < 0))
1730 break;
1731
832d11c5 1732 if (in_sack) {
cc9a672e
NC
1733 TCP_SKB_CB(skb)->sacked =
1734 tcp_sacktag_one(sk,
1735 state,
1736 TCP_SKB_CB(skb)->sacked,
1737 TCP_SKB_CB(skb)->seq,
1738 TCP_SKB_CB(skb)->end_seq,
1739 dup_sack,
59c9af42 1740 tcp_skb_pcount(skb),
2fd66ffb 1741 tcp_skb_timestamp_us(skb));
b9f64820 1742 tcp_rate_skb_delivered(sk, skb, state->rate);
e2080072
ED
1743 if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)
1744 list_del_init(&skb->tcp_tsorted_anchor);
68f8353b 1745
832d11c5
IJ
1746 if (!before(TCP_SKB_CB(skb)->seq,
1747 tcp_highest_sack_seq(tp)))
1748 tcp_advance_highest_sack(sk, skb);
1749 }
68f8353b
IJ
1750 }
1751 return skb;
1752}
1753
4bfabc46 1754static struct sk_buff *tcp_sacktag_bsearch(struct sock *sk, u32 seq)
75c119af
ED
1755{
1756 struct rb_node *parent, **p = &sk->tcp_rtx_queue.rb_node;
1757 struct sk_buff *skb;
75c119af
ED
1758
1759 while (*p) {
1760 parent = *p;
1761 skb = rb_to_skb(parent);
1762 if (before(seq, TCP_SKB_CB(skb)->seq)) {
1763 p = &parent->rb_left;
1764 continue;
1765 }
1766 if (!before(seq, TCP_SKB_CB(skb)->end_seq)) {
1767 p = &parent->rb_right;
1768 continue;
1769 }
75c119af
ED
1770 return skb;
1771 }
1772 return NULL;
1773}
1774
68f8353b 1775static struct sk_buff *tcp_sacktag_skip(struct sk_buff *skb, struct sock *sk,
a1197f5a 1776 u32 skip_to_seq)
68f8353b 1777{
75c119af
ED
1778 if (skb && after(TCP_SKB_CB(skb)->seq, skip_to_seq))
1779 return skb;
d152a7d8 1780
4bfabc46 1781 return tcp_sacktag_bsearch(sk, skip_to_seq);
68f8353b
IJ
1782}
1783
1784static struct sk_buff *tcp_maybe_skipping_dsack(struct sk_buff *skb,
1785 struct sock *sk,
1786 struct tcp_sack_block *next_dup,
a1197f5a
IJ
1787 struct tcp_sacktag_state *state,
1788 u32 skip_to_seq)
68f8353b 1789{
51456b29 1790 if (!next_dup)
68f8353b
IJ
1791 return skb;
1792
1793 if (before(next_dup->start_seq, skip_to_seq)) {
4bfabc46 1794 skb = tcp_sacktag_skip(skb, sk, next_dup->start_seq);
a1197f5a
IJ
1795 skb = tcp_sacktag_walk(skb, sk, NULL, state,
1796 next_dup->start_seq, next_dup->end_seq,
1797 1);
68f8353b
IJ
1798 }
1799
1800 return skb;
1801}
1802
cf533ea5 1803static int tcp_sack_cache_ok(const struct tcp_sock *tp, const struct tcp_sack_block *cache)
68f8353b
IJ
1804{
1805 return cache < tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache);
1806}
1807
1da177e4 1808static int
cf533ea5 1809tcp_sacktag_write_queue(struct sock *sk, const struct sk_buff *ack_skb,
196da974 1810 u32 prior_snd_una, struct tcp_sacktag_state *state)
1da177e4
LT
1811{
1812 struct tcp_sock *tp = tcp_sk(sk);
cf533ea5
ED
1813 const unsigned char *ptr = (skb_transport_header(ack_skb) +
1814 TCP_SKB_CB(ack_skb)->sacked);
fd6dad61 1815 struct tcp_sack_block_wire *sp_wire = (struct tcp_sack_block_wire *)(ptr+2);
4389dded 1816 struct tcp_sack_block sp[TCP_NUM_SACKS];
68f8353b
IJ
1817 struct tcp_sack_block *cache;
1818 struct sk_buff *skb;
4389dded 1819 int num_sacks = min(TCP_NUM_SACKS, (ptr[1] - TCPOLEN_SACK_BASE) >> 3);
fd6dad61 1820 int used_sacks;
a2a385d6 1821 bool found_dup_sack = false;
68f8353b 1822 int i, j;
fda03fbb 1823 int first_sack_index;
1da177e4 1824
196da974 1825 state->flag = 0;
737ff314 1826 state->reord = tp->snd_nxt;
a1197f5a 1827
737ff314 1828 if (!tp->sacked_out)
6859d494 1829 tcp_highest_sack_reset(sk);
1da177e4 1830
1ed83465 1831 found_dup_sack = tcp_check_dsack(sk, ack_skb, sp_wire,
a71d77e6 1832 num_sacks, prior_snd_una, state);
6f74651a
BE
1833
1834 /* Eliminate too old ACKs, but take into
1835 * account more or less fresh ones, they can
1836 * contain valid SACK info.
1837 */
1838 if (before(TCP_SKB_CB(ack_skb)->ack_seq, prior_snd_una - tp->max_window))
1839 return 0;
1840