]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blame - net/ipv4/tcp_input.c
tcp: Fix data-races around sysctl_tcp_dsack.
[mirror_ubuntu-jammy-kernel.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
0d24ea1d 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
ED
428 WRITE_ONCE(sk->sk_sndbuf,
429 min(sndmem, 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;
356d1833 464 int window = tcp_win_from_space(sk, 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
1da177e4 503 /* Check #1 */
50ce163a 504 if (room > 0 && !tcp_under_memory_pressure(sk)) {
240bfd13 505 unsigned int truesize = truesize_adjust(adjust, skb);
1da177e4
LT
506 int incr;
507
508 /* Check #2. Increase window, if skb with such overhead
509 * will fit to rcvbuf in future.
510 */
240bfd13 511 if (tcp_win_from_space(sk, truesize) <= skb->len)
056834d9 512 incr = 2 * tp->advmss;
1da177e4 513 else
240bfd13 514 incr = __tcp_grow_window(sk, skb, truesize);
1da177e4
LT
515
516 if (incr) {
4d846f02 517 incr = max_t(int, incr, 2 * skb->len);
50ce163a 518 tp->rcv_ssthresh += min(room, incr);
463c84b9 519 inet_csk(sk)->icsk_ack.quick |= 1;
1da177e4
LT
520 }
521 }
522}
523
a337531b 524/* 3. Try to fixup all. It is made immediately after connection enters
1da177e4
LT
525 * established state.
526 */
bc183dec 527static void tcp_init_buffer_space(struct sock *sk)
1da177e4 528{
0c12654a 529 int tcp_app_win = sock_net(sk)->ipv4.sysctl_tcp_app_win;
1da177e4
LT
530 struct tcp_sock *tp = tcp_sk(sk);
531 int maxwin;
532
1da177e4 533 if (!(sk->sk_userlocks & SOCK_SNDBUF_LOCK))
6ae70532 534 tcp_sndbuf_expand(sk);
1da177e4 535
9a568de4 536 tcp_mstamp_refresh(tp);
645f4c6f 537 tp->rcvq_space.time = tp->tcp_mstamp;
b0983d3c 538 tp->rcvq_space.seq = tp->copied_seq;
1da177e4
LT
539
540 maxwin = tcp_full_space(sk);
541
542 if (tp->window_clamp >= maxwin) {
543 tp->window_clamp = maxwin;
544
0c12654a 545 if (tcp_app_win && maxwin > 4 * tp->advmss)
1da177e4 546 tp->window_clamp = max(maxwin -
0c12654a 547 (maxwin >> tcp_app_win),
1da177e4
LT
548 4 * tp->advmss);
549 }
550
551 /* Force reservation of one segment. */
0c12654a 552 if (tcp_app_win &&
1da177e4
LT
553 tp->window_clamp > 2 * tp->advmss &&
554 tp->window_clamp + tp->advmss > maxwin)
555 tp->window_clamp = max(2 * tp->advmss, maxwin - tp->advmss);
556
557 tp->rcv_ssthresh = min(tp->rcv_ssthresh, tp->window_clamp);
c2203cf7 558 tp->snd_cwnd_stamp = tcp_jiffies32;
72d05c00
ED
559 tp->rcvq_space.space = min3(tp->rcv_ssthresh, tp->rcv_wnd,
560 (u32)TCP_INIT_CWND * tp->advmss);
1da177e4
LT
561}
562
a337531b 563/* 4. Recalculate window clamp after socket hit its memory bounds. */
9e412ba7 564static void tcp_clamp_window(struct sock *sk)
1da177e4 565{
9e412ba7 566 struct tcp_sock *tp = tcp_sk(sk);
6687e988 567 struct inet_connection_sock *icsk = inet_csk(sk);
356d1833 568 struct net *net = sock_net(sk);
1da177e4 569
6687e988 570 icsk->icsk_ack.quick = 0;
1da177e4 571
356d1833 572 if (sk->sk_rcvbuf < net->ipv4.sysctl_tcp_rmem[2] &&
326f36e9 573 !(sk->sk_userlocks & SOCK_RCVBUF_LOCK) &&
b8da51eb 574 !tcp_under_memory_pressure(sk) &&
180d8cd9 575 sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0)) {
ebb3b78d
ED
576 WRITE_ONCE(sk->sk_rcvbuf,
577 min(atomic_read(&sk->sk_rmem_alloc),
578 net->ipv4.sysctl_tcp_rmem[2]));
1da177e4 579 }
326f36e9 580 if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf)
056834d9 581 tp->rcv_ssthresh = min(tp->window_clamp, 2U * tp->advmss);
1da177e4
LT
582}
583
40efc6fa
SH
584/* Initialize RCV_MSS value.
585 * RCV_MSS is an our guess about MSS used by the peer.
586 * We haven't any direct information about the MSS.
587 * It's better to underestimate the RCV_MSS rather than overestimate.
588 * Overestimations make us ACKing less frequently than needed.
589 * Underestimations are more easy to detect and fix by tcp_measure_rcv_mss().
590 */
591void tcp_initialize_rcv_mss(struct sock *sk)
592{
cf533ea5 593 const struct tcp_sock *tp = tcp_sk(sk);
40efc6fa
SH
594 unsigned int hint = min_t(unsigned int, tp->advmss, tp->mss_cache);
595
056834d9 596 hint = min(hint, tp->rcv_wnd / 2);
bee7ca9e 597 hint = min(hint, TCP_MSS_DEFAULT);
40efc6fa
SH
598 hint = max(hint, TCP_MIN_MSS);
599
600 inet_csk(sk)->icsk_ack.rcv_mss = hint;
601}
4bc2f18b 602EXPORT_SYMBOL(tcp_initialize_rcv_mss);
40efc6fa 603
1da177e4
LT
604/* Receiver "autotuning" code.
605 *
606 * The algorithm for RTT estimation w/o timestamps is based on
607 * Dynamic Right-Sizing (DRS) by Wu Feng and Mike Fisk of LANL.
7a6498eb 608 * <https://public.lanl.gov/radiant/pubs.html#DRS>
1da177e4
LT
609 *
610 * More detail on this code can be found at
631dd1a8 611 * <http://staff.psc.edu/jheffner/>,
1da177e4
LT
612 * though this reference is out of date. A new paper
613 * is pending.
614 */
615static void tcp_rcv_rtt_update(struct tcp_sock *tp, u32 sample, int win_dep)
616{
645f4c6f 617 u32 new_sample = tp->rcv_rtt_est.rtt_us;
1da177e4
LT
618 long m = sample;
619
1da177e4
LT
620 if (new_sample != 0) {
621 /* If we sample in larger samples in the non-timestamp
622 * case, we could grossly overestimate the RTT especially
623 * with chatty applications or bulk transfer apps which
624 * are stalled on filesystem I/O.
625 *
626 * Also, since we are only going for a minimum in the
31f34269 627 * non-timestamp case, we do not smooth things out
caa20d9a 628 * else with timestamps disabled convergence takes too
1da177e4
LT
629 * long.
630 */
631 if (!win_dep) {
632 m -= (new_sample >> 3);
633 new_sample += m;
18a223e0
NC
634 } else {
635 m <<= 3;
636 if (m < new_sample)
637 new_sample = m;
638 }
1da177e4 639 } else {
caa20d9a 640 /* No previous measure. */
1da177e4
LT
641 new_sample = m << 3;
642 }
643
645f4c6f 644 tp->rcv_rtt_est.rtt_us = new_sample;
1da177e4
LT
645}
646
647static inline void tcp_rcv_rtt_measure(struct tcp_sock *tp)
648{
645f4c6f
ED
649 u32 delta_us;
650
9a568de4 651 if (tp->rcv_rtt_est.time == 0)
1da177e4
LT
652 goto new_measure;
653 if (before(tp->rcv_nxt, tp->rcv_rtt_est.seq))
654 return;
9a568de4 655 delta_us = tcp_stamp_us_delta(tp->tcp_mstamp, tp->rcv_rtt_est.time);
9ee11bd0
WW
656 if (!delta_us)
657 delta_us = 1;
645f4c6f 658 tcp_rcv_rtt_update(tp, delta_us, 1);
1da177e4
LT
659
660new_measure:
661 tp->rcv_rtt_est.seq = tp->rcv_nxt + tp->rcv_wnd;
645f4c6f 662 tp->rcv_rtt_est.time = tp->tcp_mstamp;
1da177e4
LT
663}
664
056834d9
IJ
665static inline void tcp_rcv_rtt_measure_ts(struct sock *sk,
666 const struct sk_buff *skb)
1da177e4 667{
463c84b9 668 struct tcp_sock *tp = tcp_sk(sk);
9a568de4 669
3f6c65d6
WW
670 if (tp->rx_opt.rcv_tsecr == tp->rcv_rtt_last_tsecr)
671 return;
672 tp->rcv_rtt_last_tsecr = tp->rx_opt.rcv_tsecr;
673
674 if (TCP_SKB_CB(skb)->end_seq -
675 TCP_SKB_CB(skb)->seq >= inet_csk(sk)->icsk_ack.rcv_mss) {
9a568de4 676 u32 delta = tcp_time_stamp(tp) - tp->rx_opt.rcv_tsecr;
9ee11bd0 677 u32 delta_us;
9a568de4 678
9efdda4e
ED
679 if (likely(delta < INT_MAX / (USEC_PER_SEC / TCP_TS_HZ))) {
680 if (!delta)
681 delta = 1;
682 delta_us = delta * (USEC_PER_SEC / TCP_TS_HZ);
683 tcp_rcv_rtt_update(tp, delta_us, 0);
684 }
9a568de4 685 }
1da177e4
LT
686}
687
688/*
689 * This function should be called every time data is copied to user space.
690 * It calculates the appropriate TCP receive buffer space.
691 */
692void tcp_rcv_space_adjust(struct sock *sk)
693{
694 struct tcp_sock *tp = tcp_sk(sk);
607065ba 695 u32 copied;
1da177e4 696 int time;
e905a9ed 697
6163849d
YS
698 trace_tcp_rcv_space_adjust(sk);
699
86323850 700 tcp_mstamp_refresh(tp);
9a568de4 701 time = tcp_stamp_us_delta(tp->tcp_mstamp, tp->rcvq_space.time);
645f4c6f 702 if (time < (tp->rcv_rtt_est.rtt_us >> 3) || tp->rcv_rtt_est.rtt_us == 0)
1da177e4 703 return;
e905a9ed 704
b0983d3c
ED
705 /* Number of bytes copied to user in last RTT */
706 copied = tp->copied_seq - tp->rcvq_space.seq;
707 if (copied <= tp->rcvq_space.space)
708 goto new_measure;
709
710 /* A bit of theory :
711 * copied = bytes received in previous RTT, our base window
712 * To cope with packet losses, we need a 2x factor
713 * To cope with slow start, and sender growing its cwin by 100 %
714 * every RTT, we need a 4x factor, because the ACK we are sending
715 * now is for the next RTT, not the current one :
716 * <prev RTT . ><current RTT .. ><next RTT .... >
717 */
718
4540c0cf 719 if (sock_net(sk)->ipv4.sysctl_tcp_moderate_rcvbuf &&
b0983d3c 720 !(sk->sk_userlocks & SOCK_RCVBUF_LOCK)) {
607065ba 721 int rcvmem, rcvbuf;
c3916ad9 722 u64 rcvwin, grow;
1da177e4 723
b0983d3c
ED
724 /* minimal window to cope with packet losses, assuming
725 * steady state. Add some cushion because of small variations.
726 */
607065ba 727 rcvwin = ((u64)copied << 1) + 16 * tp->advmss;
1da177e4 728
c3916ad9
ED
729 /* Accommodate for sender rate increase (eg. slow start) */
730 grow = rcvwin * (copied - tp->rcvq_space.space);
731 do_div(grow, tp->rcvq_space.space);
732 rcvwin += (grow << 1);
1da177e4 733
b0983d3c 734 rcvmem = SKB_TRUESIZE(tp->advmss + MAX_TCP_HEADER);
94f0893e 735 while (tcp_win_from_space(sk, rcvmem) < tp->advmss)
b0983d3c 736 rcvmem += 128;
1da177e4 737
607065ba
ED
738 do_div(rcvwin, tp->advmss);
739 rcvbuf = min_t(u64, rcvwin * rcvmem,
740 sock_net(sk)->ipv4.sysctl_tcp_rmem[2]);
b0983d3c 741 if (rcvbuf > sk->sk_rcvbuf) {
ebb3b78d 742 WRITE_ONCE(sk->sk_rcvbuf, rcvbuf);
1da177e4 743
b0983d3c 744 /* Make the window clamp follow along. */
02db5571 745 tp->window_clamp = tcp_win_from_space(sk, rcvbuf);
1da177e4
LT
746 }
747 }
b0983d3c 748 tp->rcvq_space.space = copied;
e905a9ed 749
1da177e4
LT
750new_measure:
751 tp->rcvq_space.seq = tp->copied_seq;
645f4c6f 752 tp->rcvq_space.time = tp->tcp_mstamp;
1da177e4
LT
753}
754
755/* There is something which you must keep in mind when you analyze the
756 * behavior of the tp->ato delayed ack timeout interval. When a
757 * connection starts up, we want to ack as quickly as possible. The
758 * problem is that "good" TCP's do slow start at the beginning of data
759 * transmission. The means that until we send the first few ACK's the
760 * sender will sit on his end and only queue most of his data, because
761 * he can only send snd_cwnd unacked packets at any given time. For
762 * each ACK we send, he increments snd_cwnd and transmits more of his
763 * queue. -DaveM
764 */
9e412ba7 765static void tcp_event_data_recv(struct sock *sk, struct sk_buff *skb)
1da177e4 766{
9e412ba7 767 struct tcp_sock *tp = tcp_sk(sk);
463c84b9 768 struct inet_connection_sock *icsk = inet_csk(sk);
1da177e4
LT
769 u32 now;
770
463c84b9 771 inet_csk_schedule_ack(sk);
1da177e4 772
463c84b9 773 tcp_measure_rcv_mss(sk, skb);
1da177e4
LT
774
775 tcp_rcv_rtt_measure(tp);
e905a9ed 776
70eabf0e 777 now = tcp_jiffies32;
1da177e4 778
463c84b9 779 if (!icsk->icsk_ack.ato) {
1da177e4
LT
780 /* The _first_ data packet received, initialize
781 * delayed ACK engine.
782 */
9a9c9b51 783 tcp_incr_quickack(sk, TCP_MAX_QUICKACKS);
463c84b9 784 icsk->icsk_ack.ato = TCP_ATO_MIN;
1da177e4 785 } else {
463c84b9 786 int m = now - icsk->icsk_ack.lrcvtime;
1da177e4 787
056834d9 788 if (m <= TCP_ATO_MIN / 2) {
1da177e4 789 /* The fastest case is the first. */
463c84b9
ACM
790 icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + TCP_ATO_MIN / 2;
791 } else if (m < icsk->icsk_ack.ato) {
792 icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + m;
793 if (icsk->icsk_ack.ato > icsk->icsk_rto)
794 icsk->icsk_ack.ato = icsk->icsk_rto;
795 } else if (m > icsk->icsk_rto) {
caa20d9a 796 /* Too long gap. Apparently sender failed to
1da177e4
LT
797 * restart window, so that we send ACKs quickly.
798 */
9a9c9b51 799 tcp_incr_quickack(sk, TCP_MAX_QUICKACKS);
3ab224be 800 sk_mem_reclaim(sk);
1da177e4
LT
801 }
802 }
463c84b9 803 icsk->icsk_ack.lrcvtime = now;
1da177e4 804
f4c9f85f 805 tcp_ecn_check_ce(sk, skb);
1da177e4
LT
806
807 if (skb->len >= 128)
240bfd13 808 tcp_grow_window(sk, skb, true);
1da177e4
LT
809}
810
1da177e4
LT
811/* Called to compute a smoothed rtt estimate. The data fed to this
812 * routine either comes from timestamps, or from segments that were
813 * known _not_ to have been retransmitted [see Karn/Partridge
814 * Proceedings SIGCOMM 87]. The algorithm is from the SIGCOMM 88
815 * piece by Van Jacobson.
816 * NOTE: the next three routines used to be one big routine.
817 * To save cycles in the RFC 1323 implementation it was better to break
818 * it up into three procedures. -- erics
819 */
740b0f18 820static void tcp_rtt_estimator(struct sock *sk, long mrtt_us)
1da177e4 821{
6687e988 822 struct tcp_sock *tp = tcp_sk(sk);
740b0f18
ED
823 long m = mrtt_us; /* RTT */
824 u32 srtt = tp->srtt_us;
1da177e4 825
1da177e4
LT
826 /* The following amusing code comes from Jacobson's
827 * article in SIGCOMM '88. Note that rtt and mdev
828 * are scaled versions of rtt and mean deviation.
e905a9ed 829 * This is designed to be as fast as possible
1da177e4
LT
830 * m stands for "measurement".
831 *
832 * On a 1990 paper the rto value is changed to:
833 * RTO = rtt + 4 * mdev
834 *
835 * Funny. This algorithm seems to be very broken.
836 * These formulae increase RTO, when it should be decreased, increase
31f34269 837 * too slowly, when it should be increased quickly, decrease too quickly
1da177e4
LT
838 * etc. I guess in BSD RTO takes ONE value, so that it is absolutely
839 * does not matter how to _calculate_ it. Seems, it was trap
840 * that VJ failed to avoid. 8)
841 */
4a5ab4e2
ED
842 if (srtt != 0) {
843 m -= (srtt >> 3); /* m is now error in rtt est */
844 srtt += m; /* rtt = 7/8 rtt + 1/8 new */
1da177e4
LT
845 if (m < 0) {
846 m = -m; /* m is now abs(error) */
740b0f18 847 m -= (tp->mdev_us >> 2); /* similar update on mdev */
1da177e4
LT
848 /* This is similar to one of Eifel findings.
849 * Eifel blocks mdev updates when rtt decreases.
850 * This solution is a bit different: we use finer gain
851 * for mdev in this case (alpha*beta).
852 * Like Eifel it also prevents growth of rto,
853 * but also it limits too fast rto decreases,
854 * happening in pure Eifel.
855 */
856 if (m > 0)
857 m >>= 3;
858 } else {
740b0f18 859 m -= (tp->mdev_us >> 2); /* similar update on mdev */
1da177e4 860 }
740b0f18
ED
861 tp->mdev_us += m; /* mdev = 3/4 mdev + 1/4 new */
862 if (tp->mdev_us > tp->mdev_max_us) {
863 tp->mdev_max_us = tp->mdev_us;
864 if (tp->mdev_max_us > tp->rttvar_us)
865 tp->rttvar_us = tp->mdev_max_us;
1da177e4
LT
866 }
867 if (after(tp->snd_una, tp->rtt_seq)) {
740b0f18
ED
868 if (tp->mdev_max_us < tp->rttvar_us)
869 tp->rttvar_us -= (tp->rttvar_us - tp->mdev_max_us) >> 2;
1da177e4 870 tp->rtt_seq = tp->snd_nxt;
740b0f18 871 tp->mdev_max_us = tcp_rto_min_us(sk);
23729ff2
SF
872
873 tcp_bpf_rtt(sk);
1da177e4
LT
874 }
875 } else {
876 /* no previous measure. */
4a5ab4e2 877 srtt = m << 3; /* take the measured time to be rtt */
740b0f18
ED
878 tp->mdev_us = m << 1; /* make sure rto = 3*rtt */
879 tp->rttvar_us = max(tp->mdev_us, tcp_rto_min_us(sk));
880 tp->mdev_max_us = tp->rttvar_us;
1da177e4 881 tp->rtt_seq = tp->snd_nxt;
23729ff2
SF
882
883 tcp_bpf_rtt(sk);
1da177e4 884 }
740b0f18 885 tp->srtt_us = max(1U, srtt);
1da177e4
LT
886}
887
95bd09eb
ED
888static void tcp_update_pacing_rate(struct sock *sk)
889{
890 const struct tcp_sock *tp = tcp_sk(sk);
891 u64 rate;
892
893 /* set sk_pacing_rate to 200 % of current rate (mss * cwnd / srtt) */
43e122b0
ED
894 rate = (u64)tp->mss_cache * ((USEC_PER_SEC / 100) << 3);
895
896 /* current rate is (cwnd * mss) / srtt
897 * In Slow Start [1], set sk_pacing_rate to 200 % the current rate.
898 * In Congestion Avoidance phase, set it to 120 % the current rate.
899 *
900 * [1] : Normal Slow Start condition is (tp->snd_cwnd < tp->snd_ssthresh)
901 * If snd_cwnd >= (tp->snd_ssthresh / 2), we are approaching
902 * end of slow start and should slow down.
903 */
0d24ea1d 904 if (tcp_snd_cwnd(tp) < tp->snd_ssthresh / 2)
23a7102a 905 rate *= sock_net(sk)->ipv4.sysctl_tcp_pacing_ss_ratio;
43e122b0 906 else
c26e91f8 907 rate *= sock_net(sk)->ipv4.sysctl_tcp_pacing_ca_ratio;
95bd09eb 908
0d24ea1d 909 rate *= max(tcp_snd_cwnd(tp), tp->packets_out);
95bd09eb 910
740b0f18
ED
911 if (likely(tp->srtt_us))
912 do_div(rate, tp->srtt_us);
95bd09eb 913
a9da6f29 914 /* WRITE_ONCE() is needed because sch_fq fetches sk_pacing_rate
ba537427
ED
915 * without any lock. We want to make sure compiler wont store
916 * intermediate values in this location.
917 */
a9da6f29
MR
918 WRITE_ONCE(sk->sk_pacing_rate, min_t(u64, rate,
919 sk->sk_max_pacing_rate));
95bd09eb
ED
920}
921
1da177e4
LT
922/* Calculate rto without backoff. This is the second half of Van Jacobson's
923 * routine referred to above.
924 */
f7e56a76 925static void tcp_set_rto(struct sock *sk)
1da177e4 926{
463c84b9 927 const struct tcp_sock *tp = tcp_sk(sk);
1da177e4
LT
928 /* Old crap is replaced with new one. 8)
929 *
930 * More seriously:
931 * 1. If rtt variance happened to be less 50msec, it is hallucination.
932 * It cannot be less due to utterly erratic ACK generation made
933 * at least by solaris and freebsd. "Erratic ACKs" has _nothing_
934 * to do with delayed acks, because at cwnd>2 true delack timeout
935 * is invisible. Actually, Linux-2.4 also generates erratic
caa20d9a 936 * ACKs in some circumstances.
1da177e4 937 */
f1ecd5d9 938 inet_csk(sk)->icsk_rto = __tcp_set_rto(tp);
1da177e4
LT
939
940 /* 2. Fixups made earlier cannot be right.
941 * If we do not estimate RTO correctly without them,
942 * all the algo is pure shit and should be replaced
caa20d9a 943 * with correct one. It is exactly, which we pretend to do.
1da177e4 944 */
1da177e4 945
ee6aac59
IJ
946 /* NOTE: clamping at TCP_RTO_MIN is not required, current algo
947 * guarantees that rto is higher.
948 */
f1ecd5d9 949 tcp_bound_rto(sk);
1da177e4
LT
950}
951
cf533ea5 952__u32 tcp_init_cwnd(const struct tcp_sock *tp, const struct dst_entry *dst)
1da177e4
LT
953{
954 __u32 cwnd = (dst ? dst_metric(dst, RTAX_INITCWND) : 0);
955
22b71c8f 956 if (!cwnd)
442b9635 957 cwnd = TCP_INIT_CWND;
1da177e4
LT
958 return min_t(__u32, cwnd, tp->snd_cwnd_clamp);
959}
960
a71d77e6
PJ
961struct tcp_sacktag_state {
962 /* Timestamps for earliest and latest never-retransmitted segment
963 * that was SACKed. RTO needs the earliest RTT to stay conservative,
964 * but congestion control should still get an accurate delay signal.
965 */
966 u64 first_sackt;
967 u64 last_sackt;
968 u32 reord;
969 u32 sack_delivered;
970 int flag;
971 unsigned int mss_now;
972 struct rate_sample *rate;
973};
974
ad2b9b0f
PJ
975/* Take a notice that peer is sending D-SACKs. Skip update of data delivery
976 * and spurious retransmission information if this DSACK is unlikely caused by
977 * sender's action:
978 * - DSACKed sequence range is larger than maximum receiver's window.
979 * - Total no. of DSACKed segments exceed the total no. of retransmitted segs.
980 */
a71d77e6
PJ
981static u32 tcp_dsack_seen(struct tcp_sock *tp, u32 start_seq,
982 u32 end_seq, struct tcp_sacktag_state *state)
e60402d0 983{
a71d77e6
PJ
984 u32 seq_len, dup_segs = 1;
985
ad2b9b0f
PJ
986 if (!before(start_seq, end_seq))
987 return 0;
988
989 seq_len = end_seq - start_seq;
990 /* Dubious DSACK: DSACKed range greater than maximum advertised rwnd */
991 if (seq_len > tp->max_window)
992 return 0;
993 if (seq_len > tp->mss_cache)
994 dup_segs = DIV_ROUND_UP(seq_len, tp->mss_cache);
63f367d9
YC
995 else if (tp->tlp_high_seq && tp->tlp_high_seq == end_seq)
996 state->flag |= FLAG_DSACK_TLP;
ad2b9b0f
PJ
997
998 tp->dsack_dups += dup_segs;
999 /* Skip the DSACK if dup segs weren't retransmitted by sender */
1000 if (tp->dsack_dups > tp->total_retrans)
1001 return 0;
a71d77e6 1002
ab56222a 1003 tp->rx_opt.sack_ok |= TCP_DSACK_SEEN;
a657db03
NC
1004 /* We increase the RACK ordering window in rounds where we receive
1005 * DSACKs that may have been due to reordering causing RACK to trigger
1006 * a spurious fast recovery. Thus RACK ignores DSACKs that happen
1007 * without having seen reordering, or that match TLP probes (TLP
1008 * is timer-driven, not triggered by RACK).
1009 */
1010 if (tp->reord_seen && !(state->flag & FLAG_DSACK_TLP))
1011 tp->rack.dsack_seen = 1;
a71d77e6
PJ
1012
1013 state->flag |= FLAG_DSACKING_ACK;
1014 /* A spurious retransmission is delivered */
1015 state->sack_delivered += dup_segs;
1016
1017 return dup_segs;
e60402d0
IJ
1018}
1019
737ff314
YC
1020/* It's reordering when higher sequence was delivered (i.e. sacked) before
1021 * some lower never-retransmitted sequence ("low_seq"). The maximum reordering
1022 * distance is approximated in full-mss packet distance ("reordering").
1023 */
1024static void tcp_check_sack_reordering(struct sock *sk, const u32 low_seq,
1025 const int ts)
1da177e4 1026{
6687e988 1027 struct tcp_sock *tp = tcp_sk(sk);
737ff314
YC
1028 const u32 mss = tp->mss_cache;
1029 u32 fack, metric;
40b215e5 1030
737ff314
YC
1031 fack = tcp_highest_sack_seq(tp);
1032 if (!before(low_seq, fack))
6f5b24ee
SHY
1033 return;
1034
737ff314
YC
1035 metric = fack - low_seq;
1036 if ((metric > tp->reordering * mss) && mss) {
1da177e4 1037#if FASTRETRANS_DEBUG > 1
91df42be
JP
1038 pr_debug("Disorder%d %d %u f%u s%u rr%d\n",
1039 tp->rx_opt.sack_ok, inet_csk(sk)->icsk_ca_state,
1040 tp->reordering,
737ff314 1041 0,
91df42be
JP
1042 tp->sacked_out,
1043 tp->undo_marker ? tp->undo_retrans : 0);
1da177e4 1044#endif
737ff314 1045 tp->reordering = min_t(u32, (metric + mss - 1) / mss,
f230184b 1046 READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_max_reordering));
1da177e4 1047 }
eed530b6 1048
2d2517ee 1049 /* This exciting event is worth to be remembered. 8) */
7ec65372 1050 tp->reord_seen++;
737ff314
YC
1051 NET_INC_STATS(sock_net(sk),
1052 ts ? LINUX_MIB_TCPTSREORDER : LINUX_MIB_TCPSACKREORDER);
1da177e4
LT
1053}
1054
68698970
YC
1055 /* This must be called before lost_out or retrans_out are updated
1056 * on a new loss, because we want to know if all skbs previously
1057 * known to be lost have already been retransmitted, indicating
1058 * that this newly lost skb is our next skb to retransmit.
1059 */
c8c213f2
IJ
1060static void tcp_verify_retransmit_hint(struct tcp_sock *tp, struct sk_buff *skb)
1061{
e176b1ba
PY
1062 if ((!tp->retransmit_skb_hint && tp->retrans_out >= tp->lost_out) ||
1063 (tp->retransmit_skb_hint &&
1064 before(TCP_SKB_CB(skb)->seq,
1065 TCP_SKB_CB(tp->retransmit_skb_hint)->seq)))
006f582c 1066 tp->retransmit_skb_hint = skb;
c8c213f2
IJ
1067}
1068
9cd8b6c9
YC
1069/* Sum the number of packets on the wire we have marked as lost, and
1070 * notify the congestion control module that the given skb was marked lost.
1071 */
1072static void tcp_notify_skb_loss_event(struct tcp_sock *tp, const struct sk_buff *skb)
1073{
1074 tp->lost += tcp_skb_pcount(skb);
1075}
1076
fd214674
YC
1077void tcp_mark_skb_lost(struct sock *sk, struct sk_buff *skb)
1078{
68698970 1079 __u8 sacked = TCP_SKB_CB(skb)->sacked;
fd214674
YC
1080 struct tcp_sock *tp = tcp_sk(sk);
1081
68698970
YC
1082 if (sacked & TCPCB_SACKED_ACKED)
1083 return;
0682e690 1084
68698970
YC
1085 tcp_verify_retransmit_hint(tp, skb);
1086 if (sacked & TCPCB_LOST) {
1087 if (sacked & TCPCB_SACKED_RETRANS) {
1088 /* Account for retransmits that are lost again */
1089 TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
1090 tp->retrans_out -= tcp_skb_pcount(skb);
1091 NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPLOSTRETRANSMIT,
1092 tcp_skb_pcount(skb));
9cd8b6c9 1093 tcp_notify_skb_loss_event(tp, skb);
68698970
YC
1094 }
1095 } else {
1096 tp->lost_out += tcp_skb_pcount(skb);
1097 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
9cd8b6c9 1098 tcp_notify_skb_loss_event(tp, skb);
68698970 1099 }
0682e690
NC
1100}
1101
082d4fa9
YS
1102/* Updates the delivered and delivered_ce counts */
1103static void tcp_count_delivered(struct tcp_sock *tp, u32 delivered,
1104 bool ece_ack)
1105{
1106 tp->delivered += delivered;
1107 if (ece_ack)
1108 tp->delivered_ce += delivered;
1109}
1110
1da177e4
LT
1111/* This procedure tags the retransmission queue when SACKs arrive.
1112 *
1113 * We have three tag bits: SACKED(S), RETRANS(R) and LOST(L).
1114 * Packets in queue with these bits set are counted in variables
1115 * sacked_out, retrans_out and lost_out, correspondingly.
1116 *
1117 * Valid combinations are:
1118 * Tag InFlight Description
1119 * 0 1 - orig segment is in flight.
1120 * S 0 - nothing flies, orig reached receiver.
1121 * L 0 - nothing flies, orig lost by net.
1122 * R 2 - both orig and retransmit are in flight.
1123 * L|R 1 - orig is lost, retransmit is in flight.
1124 * S|R 1 - orig reached receiver, retrans is still in flight.
1125 * (L|S|R is logically valid, it could occur when L|R is sacked,
1126 * but it is equivalent to plain S and code short-curcuits it to S.
1127 * L|S is logically invalid, it would mean -1 packet in flight 8))
1128 *
1129 * These 6 states form finite state machine, controlled by the following events:
1130 * 1. New ACK (+SACK) arrives. (tcp_sacktag_write_queue())
1131 * 2. Retransmission. (tcp_retransmit_skb(), tcp_xmit_retransmit_queue())
974c1236 1132 * 3. Loss detection event of two flavors:
1da177e4
LT
1133 * A. Scoreboard estimator decided the packet is lost.
1134 * A'. Reno "three dupacks" marks head of queue lost.
974c1236 1135 * B. SACK arrives sacking SND.NXT at the moment, when the
1da177e4
LT
1136 * segment was retransmitted.
1137 * 4. D-SACK added new rule: D-SACK changes any tag to S.
1138 *
1139 * It is pleasant to note, that state diagram turns out to be commutative,
1140 * so that we are allowed not to be bothered by order of our actions,
1141 * when multiple events arrive simultaneously. (see the function below).
1142 *
1143 * Reordering detection.
1144 * --------------------
1145 * Reordering metric is maximal distance, which a packet can be displaced
1146 * in packet stream. With SACKs we can estimate it:
1147 *
1148 * 1. SACK fills old hole and the corresponding segment was not
1149 * ever retransmitted -> reordering. Alas, we cannot use it
1150 * when segment was retransmitted.
1151 * 2. The last flaw is solved with D-SACK. D-SACK arrives
1152 * for retransmitted and already SACKed segment -> reordering..
1153 * Both of these heuristics are not used in Loss state, when we cannot
1154 * account for retransmits accurately.
5b3c9882
IJ
1155 *
1156 * SACK block validation.
1157 * ----------------------
1158 *
1159 * SACK block range validation checks that the received SACK block fits to
1160 * the expected sequence limits, i.e., it is between SND.UNA and SND.NXT.
1161 * Note that SND.UNA is not included to the range though being valid because
0e835331
IJ
1162 * it means that the receiver is rather inconsistent with itself reporting
1163 * SACK reneging when it should advance SND.UNA. Such SACK block this is
1164 * perfectly valid, however, in light of RFC2018 which explicitly states
1165 * that "SACK block MUST reflect the newest segment. Even if the newest
1166 * segment is going to be discarded ...", not that it looks very clever
1167 * in case of head skb. Due to potentional receiver driven attacks, we
1168 * choose to avoid immediate execution of a walk in write queue due to
1169 * reneging and defer head skb's loss recovery to standard loss recovery
1170 * procedure that will eventually trigger (nothing forbids us doing this).
5b3c9882
IJ
1171 *
1172 * Implements also blockage to start_seq wrap-around. Problem lies in the
1173 * fact that though start_seq (s) is before end_seq (i.e., not reversed),
1174 * there's no guarantee that it will be before snd_nxt (n). The problem
1175 * happens when start_seq resides between end_seq wrap (e_w) and snd_nxt
1176 * wrap (s_w):
1177 *
1178 * <- outs wnd -> <- wrapzone ->
1179 * u e n u_w e_w s n_w
1180 * | | | | | | |
1181 * |<------------+------+----- TCP seqno space --------------+---------->|
1182 * ...-- <2^31 ->| |<--------...
1183 * ...---- >2^31 ------>| |<--------...
1184 *
1185 * Current code wouldn't be vulnerable but it's better still to discard such
1186 * crazy SACK blocks. Doing this check for start_seq alone closes somewhat
1187 * similar case (end_seq after snd_nxt wrap) as earlier reversed check in
1188 * snd_nxt wrap -> snd_una region will then become "well defined", i.e.,
1189 * equal to the ideal case (infinite seqno space without wrap caused issues).
1190 *
1191 * With D-SACK the lower bound is extended to cover sequence space below
1192 * SND.UNA down to undo_marker, which is the last point of interest. Yet
564262c1 1193 * again, D-SACK block must not to go across snd_una (for the same reason as
5b3c9882
IJ
1194 * for the normal SACK blocks, explained above). But there all simplicity
1195 * ends, TCP might receive valid D-SACKs below that. As long as they reside
1196 * fully below undo_marker they do not affect behavior in anyway and can
1197 * therefore be safely ignored. In rare cases (which are more or less
1198 * theoretical ones), the D-SACK will nicely cross that boundary due to skb
1199 * fragmentation and packet reordering past skb's retransmission. To consider
1200 * them correctly, the acceptable range must be extended even more though
1201 * the exact amount is rather hard to quantify. However, tp->max_window can
1202 * be used as an exaggerated estimate.
1da177e4 1203 */
a2a385d6
ED
1204static bool tcp_is_sackblock_valid(struct tcp_sock *tp, bool is_dsack,
1205 u32 start_seq, u32 end_seq)
5b3c9882
IJ
1206{
1207 /* Too far in future, or reversed (interpretation is ambiguous) */
1208 if (after(end_seq, tp->snd_nxt) || !before(start_seq, end_seq))
a2a385d6 1209 return false;
5b3c9882
IJ
1210
1211 /* Nasty start_seq wrap-around check (see comments above) */
1212 if (!before(start_seq, tp->snd_nxt))
a2a385d6 1213 return false;
5b3c9882 1214
564262c1 1215 /* In outstanding window? ...This is valid exit for D-SACKs too.
5b3c9882
IJ
1216 * start_seq == snd_una is non-sensical (see comments above)
1217 */
1218 if (after(start_seq, tp->snd_una))
a2a385d6 1219 return true;
5b3c9882
IJ
1220
1221 if (!is_dsack || !tp->undo_marker)
a2a385d6 1222 return false;
5b3c9882
IJ
1223
1224 /* ...Then it's D-SACK, and must reside below snd_una completely */
f779b2d6 1225 if (after(end_seq, tp->snd_una))
a2a385d6 1226 return false;
5b3c9882
IJ
1227
1228 if (!before(start_seq, tp->undo_marker))
a2a385d6 1229 return true;
5b3c9882
IJ
1230
1231 /* Too old */
1232 if (!after(end_seq, tp->undo_marker))
a2a385d6 1233 return false;
5b3c9882
IJ
1234
1235 /* Undo_marker boundary crossing (overestimates a lot). Known already:
1236 * start_seq < undo_marker and end_seq >= undo_marker.
1237 */
1238 return !before(start_seq, end_seq - tp->max_window);
1239}
1240
a2a385d6
ED
1241static bool tcp_check_dsack(struct sock *sk, const struct sk_buff *ack_skb,
1242 struct tcp_sack_block_wire *sp, int num_sacks,
a71d77e6 1243 u32 prior_snd_una, struct tcp_sacktag_state *state)
d06e021d 1244{
1ed83465 1245 struct tcp_sock *tp = tcp_sk(sk);
d3e2ce3b
HH
1246 u32 start_seq_0 = get_unaligned_be32(&sp[0].start_seq);
1247 u32 end_seq_0 = get_unaligned_be32(&sp[0].end_seq);
a71d77e6 1248 u32 dup_segs;
d06e021d
DM
1249
1250 if (before(start_seq_0, TCP_SKB_CB(ack_skb)->ack_seq)) {
c10d9310 1251 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKRECV);
d06e021d 1252 } else if (num_sacks > 1) {
d3e2ce3b
HH
1253 u32 end_seq_1 = get_unaligned_be32(&sp[1].end_seq);
1254 u32 start_seq_1 = get_unaligned_be32(&sp[1].start_seq);
d06e021d 1255
a71d77e6
PJ
1256 if (after(end_seq_0, end_seq_1) || before(start_seq_0, start_seq_1))
1257 return false;
1258 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKOFORECV);
1259 } else {
1260 return false;
d06e021d
DM
1261 }
1262
a71d77e6 1263 dup_segs = tcp_dsack_seen(tp, start_seq_0, end_seq_0, state);
ad2b9b0f
PJ
1264 if (!dup_segs) { /* Skip dubious DSACK */
1265 NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKIGNOREDDUBIOUS);
1266 return false;
1267 }
1268
e3a5a1e8 1269 NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPDSACKRECVSEGS, dup_segs);
a71d77e6 1270
d06e021d 1271 /* D-SACK for already forgotten data... Do dumb counting. */
a71d77e6 1272 if (tp->undo_marker && tp->undo_retrans > 0 &&
d06e021d
DM
1273 !after(end_seq_0, prior_snd_una) &&
1274 after(end_seq_0, tp->undo_marker))
a71d77e6 1275 tp->undo_retrans = max_t(int, 0, tp->undo_retrans - dup_segs);
d06e021d 1276
a71d77e6 1277 return true;
d06e021d
DM
1278}
1279
d1935942
IJ
1280/* Check if skb is fully within the SACK block. In presence of GSO skbs,
1281 * the incoming SACK may not exactly match but we can find smaller MSS
1282 * aligned portion of it that matches. Therefore we might need to fragment
1283 * which may fail and creates some hassle (caller must handle error case
1284 * returns).
832d11c5
IJ
1285 *
1286 * FIXME: this could be merged to shift decision code
d1935942 1287 */
0f79efdc 1288static int tcp_match_skb_to_sack(struct sock *sk, struct sk_buff *skb,
a2a385d6 1289 u32 start_seq, u32 end_seq)
d1935942 1290{
a2a385d6
ED
1291 int err;
1292 bool in_sack;
d1935942 1293 unsigned int pkt_len;
adb92db8 1294 unsigned int mss;
d1935942
IJ
1295
1296 in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
1297 !before(end_seq, TCP_SKB_CB(skb)->end_seq);
1298
1299 if (tcp_skb_pcount(skb) > 1 && !in_sack &&
1300 after(TCP_SKB_CB(skb)->end_seq, start_seq)) {
adb92db8 1301 mss = tcp_skb_mss(skb);
d1935942
IJ
1302 in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq);
1303
adb92db8 1304 if (!in_sack) {
d1935942 1305 pkt_len = start_seq - TCP_SKB_CB(skb)->seq;
adb92db8
IJ
1306 if (pkt_len < mss)
1307 pkt_len = mss;
1308 } else {
d1935942 1309 pkt_len = end_seq - TCP_SKB_CB(skb)->seq;
adb92db8
IJ
1310 if (pkt_len < mss)
1311 return -EINVAL;
1312 }
1313
1314 /* Round if necessary so that SACKs cover only full MSSes
1315 * and/or the remaining small portion (if present)
1316 */
1317 if (pkt_len > mss) {
1318 unsigned int new_len = (pkt_len / mss) * mss;
b451e5d2 1319 if (!in_sack && new_len < pkt_len)
adb92db8 1320 new_len += mss;
adb92db8
IJ
1321 pkt_len = new_len;
1322 }
b451e5d2
YC
1323
1324 if (pkt_len >= skb->len && !in_sack)
1325 return 0;
1326
75c119af
ED
1327 err = tcp_fragment(sk, TCP_FRAG_IN_RTX_QUEUE, skb,
1328 pkt_len, mss, GFP_ATOMIC);
d1935942
IJ
1329 if (err < 0)
1330 return err;
1331 }
1332
1333 return in_sack;
1334}
1335
cc9a672e
NC
1336/* Mark the given newly-SACKed range as such, adjusting counters and hints. */
1337static u8 tcp_sacktag_one(struct sock *sk,
1338 struct tcp_sacktag_state *state, u8 sacked,
1339 u32 start_seq, u32 end_seq,
740b0f18 1340 int dup_sack, int pcount,
9a568de4 1341 u64 xmit_time)
9e10c47c 1342{
6859d494 1343 struct tcp_sock *tp = tcp_sk(sk);
9e10c47c
IJ
1344
1345 /* Account D-SACK for retransmitted packet. */
1346 if (dup_sack && (sacked & TCPCB_RETRANS)) {
6e08d5e3 1347 if (tp->undo_marker && tp->undo_retrans > 0 &&
cc9a672e 1348 after(end_seq, tp->undo_marker))
4f884f39 1349 tp->undo_retrans = max_t(int, 0, tp->undo_retrans - pcount);
737ff314
YC
1350 if ((sacked & TCPCB_SACKED_ACKED) &&
1351 before(start_seq, state->reord))
1352 state->reord = start_seq;
9e10c47c
IJ
1353 }
1354
1355 /* Nothing to do; acked frame is about to be dropped (was ACKed). */
cc9a672e 1356 if (!after(end_seq, tp->snd_una))
a1197f5a 1357 return sacked;
9e10c47c
IJ
1358
1359 if (!(sacked & TCPCB_SACKED_ACKED)) {
d2329f10 1360 tcp_rack_advance(tp, sacked, end_seq, xmit_time);
659a8ad5 1361
9e10c47c
IJ
1362 if (sacked & TCPCB_SACKED_RETRANS) {
1363 /* If the segment is not tagged as lost,
1364 * we do not clear RETRANS, believing
1365 * that retransmission is still in flight.
1366 */
1367 if (sacked & TCPCB_LOST) {
a1197f5a 1368 sacked &= ~(TCPCB_LOST|TCPCB_SACKED_RETRANS);
f58b22fd
IJ
1369 tp->lost_out -= pcount;
1370 tp->retrans_out -= pcount;
9e10c47c
IJ
1371 }
1372 } else {
1373 if (!(sacked & TCPCB_RETRANS)) {
1374 /* New sack for not retransmitted frame,
1375 * which was in hole. It is reordering.
1376 */
cc9a672e 1377 if (before(start_seq,
737ff314
YC
1378 tcp_highest_sack_seq(tp)) &&
1379 before(start_seq, state->reord))
1380 state->reord = start_seq;
1381
e33099f9
YC
1382 if (!after(end_seq, tp->high_seq))
1383 state->flag |= FLAG_ORIG_SACK_ACKED;
9a568de4
ED
1384 if (state->first_sackt == 0)
1385 state->first_sackt = xmit_time;
1386 state->last_sackt = xmit_time;
9e10c47c
IJ
1387 }
1388
1389 if (sacked & TCPCB_LOST) {
a1197f5a 1390 sacked &= ~TCPCB_LOST;
f58b22fd 1391 tp->lost_out -= pcount;
9e10c47c
IJ
1392 }
1393 }
1394
a1197f5a
IJ
1395 sacked |= TCPCB_SACKED_ACKED;
1396 state->flag |= FLAG_DATA_SACKED;
f58b22fd 1397 tp->sacked_out += pcount;
082d4fa9 1398 /* Out-of-order packets delivered */
f00394ce 1399 state->sack_delivered += pcount;
9e10c47c 1400
9e10c47c 1401 /* Lost marker hint past SACKed? Tweak RFC3517 cnt */
713bafea 1402 if (tp->lost_skb_hint &&
cc9a672e 1403 before(start_seq, TCP_SKB_CB(tp->lost_skb_hint)->seq))
f58b22fd 1404 tp->lost_cnt_hint += pcount;
9e10c47c
IJ
1405 }
1406
1407 /* D-SACK. We can detect redundant retransmission in S|R and plain R
1408 * frames and clear it. undo_retrans is decreased above, L|R frames
1409 * are accounted above as well.
1410 */
a1197f5a
IJ
1411 if (dup_sack && (sacked & TCPCB_SACKED_RETRANS)) {
1412 sacked &= ~TCPCB_SACKED_RETRANS;
f58b22fd 1413 tp->retrans_out -= pcount;
9e10c47c
IJ
1414 }
1415
a1197f5a 1416 return sacked;
9e10c47c
IJ
1417}
1418
daef52ba
NC
1419/* Shift newly-SACKed bytes from this skb to the immediately previous
1420 * already-SACKed sk_buff. Mark the newly-SACKed bytes as such.
1421 */
f3319816
ED
1422static bool tcp_shifted_skb(struct sock *sk, struct sk_buff *prev,
1423 struct sk_buff *skb,
a2a385d6
ED
1424 struct tcp_sacktag_state *state,
1425 unsigned int pcount, int shifted, int mss,
1426 bool dup_sack)
832d11c5
IJ
1427{
1428 struct tcp_sock *tp = tcp_sk(sk);
daef52ba
NC
1429 u32 start_seq = TCP_SKB_CB(skb)->seq; /* start of newly-SACKed */
1430 u32 end_seq = start_seq + shifted; /* end of newly-SACKed */
832d11c5
IJ
1431
1432 BUG_ON(!pcount);
1433
4c90d3b3
NC
1434 /* Adjust counters and hints for the newly sacked sequence
1435 * range but discard the return value since prev is already
1436 * marked. We must tag the range first because the seq
1437 * advancement below implicitly advances
1438 * tcp_highest_sack_seq() when skb is highest_sack.
1439 */
1440 tcp_sacktag_one(sk, state, TCP_SKB_CB(skb)->sacked,
59c9af42 1441 start_seq, end_seq, dup_sack, pcount,
2fd66ffb 1442 tcp_skb_timestamp_us(skb));
b9f64820 1443 tcp_rate_skb_delivered(sk, skb, state->rate);
4c90d3b3
NC
1444
1445 if (skb == tp->lost_skb_hint)
0af2a0d0
NC
1446 tp->lost_cnt_hint += pcount;
1447
832d11c5
IJ
1448 TCP_SKB_CB(prev)->end_seq += shifted;
1449 TCP_SKB_CB(skb)->seq += shifted;
1450
cd7d8498 1451 tcp_skb_pcount_add(prev, pcount);
3b4929f6 1452 WARN_ON_ONCE(tcp_skb_pcount(skb) < pcount);
cd7d8498 1453 tcp_skb_pcount_add(skb, -pcount);
832d11c5
IJ
1454
1455 /* When we're adding to gso_segs == 1, gso_size will be zero,
1456 * in theory this shouldn't be necessary but as long as DSACK
1457 * code can come after this skb later on it's better to keep
1458 * setting gso_size to something.
1459 */
f69ad292
ED
1460 if (!TCP_SKB_CB(prev)->tcp_gso_size)
1461 TCP_SKB_CB(prev)->tcp_gso_size = mss;
832d11c5
IJ
1462
1463 /* CHECKME: To clear or not to clear? Mimics normal skb currently */
51466a75 1464 if (tcp_skb_pcount(skb) <= 1)
f69ad292 1465 TCP_SKB_CB(skb)->tcp_gso_size = 0;
832d11c5 1466
832d11c5
IJ
1467 /* Difference in this won't matter, both ACKed by the same cumul. ACK */
1468 TCP_SKB_CB(prev)->sacked |= (TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS);
1469
832d11c5
IJ
1470 if (skb->len > 0) {
1471 BUG_ON(!tcp_skb_pcount(skb));
c10d9310 1472 NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKSHIFTED);
a2a385d6 1473 return false;
832d11c5
IJ
1474 }
1475
1476 /* Whole SKB was eaten :-) */
1477
92ee76b6
IJ
1478 if (skb == tp->retransmit_skb_hint)
1479 tp->retransmit_skb_hint = prev;
92ee76b6
IJ
1480 if (skb == tp->lost_skb_hint) {
1481 tp->lost_skb_hint = prev;
1482 tp->lost_cnt_hint -= tcp_skb_pcount(prev);
1483 }
1484
5e8a402f 1485 TCP_SKB_CB(prev)->tcp_flags |= TCP_SKB_CB(skb)->tcp_flags;
a643b5d4 1486 TCP_SKB_CB(prev)->eor = TCP_SKB_CB(skb)->eor;
5e8a402f
ED
1487 if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
1488 TCP_SKB_CB(prev)->end_seq++;
1489
832d11c5
IJ
1490 if (skb == tcp_highest_sack(sk))
1491 tcp_advance_highest_sack(sk, skb);
1492
cfea5a68 1493 tcp_skb_collapse_tstamp(prev, skb);
9a568de4
ED
1494 if (unlikely(TCP_SKB_CB(prev)->tx.delivered_mstamp))
1495 TCP_SKB_CB(prev)->tx.delivered_mstamp = 0;
b9f64820 1496
75c119af 1497 tcp_rtx_queue_unlink_and_free(skb, sk);
832d11c5 1498
c10d9310 1499 NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKMERGED);
111cc8b9 1500
a2a385d6 1501 return true;
832d11c5
IJ
1502}
1503
1504/* I wish gso_size would have a bit more sane initialization than
1505 * something-or-zero which complicates things
1506 */
cf533ea5 1507static int tcp_skb_seglen(const struct sk_buff *skb)
832d11c5 1508{
775ffabf 1509 return tcp_skb_pcount(skb) == 1 ? skb->len : tcp_skb_mss(skb);
832d11c5
IJ
1510}
1511
1512/* Shifting pages past head area doesn't work */
cf533ea5 1513static int skb_can_shift(const struct sk_buff *skb)
832d11c5
IJ
1514{
1515 return !skb_headlen(skb) && skb_is_nonlinear(skb);
1516}
1517
3b4929f6
ED
1518int tcp_skb_shift(struct sk_buff *to, struct sk_buff *from,
1519 int pcount, int shiftlen)
1520{
1521 /* TCP min gso_size is 8 bytes (TCP_MIN_GSO_SIZE)
1522 * Since TCP_SKB_CB(skb)->tcp_gso_segs is 16 bits, we need
1523 * to make sure not storing more than 65535 * 8 bytes per skb,
1524 * even if current MSS is bigger.
1525 */
1526 if (unlikely(to->len + shiftlen >= 65535 * TCP_MIN_GSO_SIZE))
1527 return 0;
1528 if (unlikely(tcp_skb_pcount(to) + pcount > 65535))
1529 return 0;
1530 return skb_shift(to, from, shiftlen);
1531}
1532
832d11c5
IJ
1533/* Try collapsing SACK blocks spanning across multiple skbs to a single
1534 * skb.
1535 */
1536static struct sk_buff *tcp_shift_skb_data(struct sock *sk, struct sk_buff *skb,
a1197f5a 1537 struct tcp_sacktag_state *state,
832d11c5 1538 u32 start_seq, u32 end_seq,
a2a385d6 1539 bool dup_sack)
832d11c5
IJ
1540{
1541 struct tcp_sock *tp = tcp_sk(sk);
1542 struct sk_buff *prev;
1543 int mss;
1544 int pcount = 0;
1545 int len;
1546 int in_sack;
1547
832d11c5
IJ
1548 /* Normally R but no L won't result in plain S */
1549 if (!dup_sack &&
9969ca5f 1550 (TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_RETRANS)) == TCPCB_SACKED_RETRANS)
832d11c5
IJ
1551 goto fallback;
1552 if (!skb_can_shift(skb))
1553 goto fallback;
1554 /* This frame is about to be dropped (was ACKed). */
1555 if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una))
1556 goto fallback;
1557
1558 /* Can only happen with delayed DSACK + discard craziness */
75c119af
ED
1559 prev = skb_rb_prev(skb);
1560 if (!prev)
832d11c5 1561 goto fallback;
832d11c5
IJ
1562
1563 if ((TCP_SKB_CB(prev)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED)
1564 goto fallback;
1565
85712484 1566 if (!tcp_skb_can_collapse(prev, skb))
a643b5d4
MKL
1567 goto fallback;
1568
832d11c5
IJ
1569 in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
1570 !before(end_seq, TCP_SKB_CB(skb)->end_seq);
1571
1572 if (in_sack) {
1573 len = skb->len;
1574 pcount = tcp_skb_pcount(skb);
775ffabf 1575 mss = tcp_skb_seglen(skb);
832d11c5
IJ
1576
1577 /* TODO: Fix DSACKs to not fragment already SACKed and we can
1578 * drop this restriction as unnecessary
1579 */
775ffabf 1580 if (mss != tcp_skb_seglen(prev))
832d11c5
IJ
1581 goto fallback;
1582 } else {
1583 if (!after(TCP_SKB_CB(skb)->end_seq, start_seq))
1584 goto noop;
1585 /* CHECKME: This is non-MSS split case only?, this will
1586 * cause skipped skbs due to advancing loop btw, original
1587 * has that feature too
1588 */
1589 if (tcp_skb_pcount(skb) <= 1)
1590 goto noop;
1591
1592 in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq);
1593 if (!in_sack) {
1594 /* TODO: head merge to next could be attempted here
1595 * if (!after(TCP_SKB_CB(skb)->end_seq, end_seq)),
1596 * though it might not be worth of the additional hassle
1597 *
1598 * ...we can probably just fallback to what was done
1599 * previously. We could try merging non-SACKed ones
1600 * as well but it probably isn't going to buy off
1601 * because later SACKs might again split them, and
1602 * it would make skb timestamp tracking considerably
1603 * harder problem.
1604 */
1605 goto fallback;
1606 }
1607
1608 len = end_seq - TCP_SKB_CB(skb)->seq;
1609 BUG_ON(len < 0);
1610 BUG_ON(len > skb->len);
1611
1612 /* MSS boundaries should be honoured or else pcount will
1613 * severely break even though it makes things bit trickier.
1614 * Optimize common case to avoid most of the divides
1615 */
1616 mss = tcp_skb_mss(skb);
1617
1618 /* TODO: Fix DSACKs to not fragment already SACKed and we can
1619 * drop this restriction as unnecessary
1620 */
775ffabf 1621 if (mss != tcp_skb_seglen(prev))
832d11c5
IJ
1622 goto fallback;
1623
1624 if (len == mss) {
1625 pcount = 1;
1626 } else if (len < mss) {
1627 goto noop;
1628 } else {
1629 pcount = len / mss;
1630 len = pcount * mss;
1631 }
1632 }
1633
4648dc97
NC
1634 /* tcp_sacktag_one() won't SACK-tag ranges below snd_una */
1635 if (!after(TCP_SKB_CB(skb)->seq + len, tp->snd_una))
1636 goto fallback;
1637
3b4929f6 1638 if (!tcp_skb_shift(prev, skb, pcount, len))
832d11c5 1639 goto fallback;
f3319816 1640 if (!tcp_shifted_skb(sk, prev, skb, state, pcount, len, mss, dup_sack))
832d11c5
IJ
1641 goto out;
1642
1643 /* Hole filled allows collapsing with the next as well, this is very
1644 * useful when hole on every nth skb pattern happens
1645 */
75c119af
ED
1646 skb = skb_rb_next(prev);
1647 if (!skb)
832d11c5 1648 goto out;
832d11c5 1649
f0bc52f3 1650 if (!skb_can_shift(skb) ||
f0bc52f3 1651 ((TCP_SKB_CB(skb)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED) ||
775ffabf 1652 (mss != tcp_skb_seglen(skb)))
832d11c5
IJ
1653 goto out;
1654
f142cf86
ED
1655 if (!tcp_skb_can_collapse(prev, skb))
1656 goto out;
832d11c5 1657 len = skb->len;
3b4929f6
ED
1658 pcount = tcp_skb_pcount(skb);
1659 if (tcp_skb_shift(prev, skb, pcount, len))
1660 tcp_shifted_skb(sk, prev, skb, state, pcount,
f3319816 1661 len, mss, 0);
832d11c5
IJ
1662
1663out:
832d11c5
IJ
1664 return prev;
1665
1666noop:
1667 return skb;
1668
1669fallback:
c10d9310 1670 NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKSHIFTFALLBACK);
832d11c5
IJ
1671 return NULL;
1672}
1673
68f8353b
IJ
1674static struct sk_buff *tcp_sacktag_walk(struct sk_buff *skb, struct sock *sk,
1675 struct tcp_sack_block *next_dup,
a1197f5a 1676 struct tcp_sacktag_state *state,
68f8353b 1677 u32 start_seq, u32 end_seq,
a2a385d6 1678 bool dup_sack_in)
68f8353b 1679{
832d11c5
IJ
1680 struct tcp_sock *tp = tcp_sk(sk);
1681 struct sk_buff *tmp;
1682
75c119af 1683 skb_rbtree_walk_from(skb) {
68f8353b 1684 int in_sack = 0;
a2a385d6 1685 bool dup_sack = dup_sack_in;
68f8353b 1686
68f8353b
IJ
1687 /* queue is in-order => we can short-circuit the walk early */
1688 if (!before(TCP_SKB_CB(skb)->seq, end_seq))
1689 break;
1690
00db4124 1691 if (next_dup &&
68f8353b
IJ
1692 before(TCP_SKB_CB(skb)->seq, next_dup->end_seq)) {
1693 in_sack = tcp_match_skb_to_sack(sk, skb,
1694 next_dup->start_seq,
1695 next_dup->end_seq);
1696 if (in_sack > 0)
a2a385d6 1697 dup_sack = true;
68f8353b
IJ
1698 }
1699
832d11c5
IJ
1700 /* skb reference here is a bit tricky to get right, since
1701 * shifting can eat and free both this skb and the next,
1702 * so not even _safe variant of the loop is enough.
1703 */
1704 if (in_sack <= 0) {
a1197f5a
IJ
1705 tmp = tcp_shift_skb_data(sk, skb, state,
1706 start_seq, end_seq, dup_sack);
00db4124 1707 if (tmp) {
832d11c5
IJ
1708 if (tmp != skb) {
1709 skb = tmp;
1710 continue;
1711 }
1712
1713 in_sack = 0;
1714 } else {
1715 in_sack = tcp_match_skb_to_sack(sk, skb,
1716 start_seq,
1717 end_seq);
1718 }
1719 }
1720
68f8353b
IJ
1721 if (unlikely(in_sack < 0))
1722 break;
1723
832d11c5 1724 if (in_sack) {
cc9a672e
NC
1725 TCP_SKB_CB(skb)->sacked =
1726 tcp_sacktag_one(sk,
1727 state,
1728 TCP_SKB_CB(skb)->sacked,
1729 TCP_SKB_CB(skb)->seq,
1730 TCP_SKB_CB(skb)->end_seq,
1731 dup_sack,
59c9af42 1732 tcp_skb_pcount(skb),
2fd66ffb 1733 tcp_skb_timestamp_us(skb));
b9f64820 1734 tcp_rate_skb_delivered(sk, skb, state->rate);
e2080072
ED
1735 if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)
1736 list_del_init(&skb->tcp_tsorted_anchor);
68f8353b 1737
832d11c5
IJ
1738 if (!before(TCP_SKB_CB(skb)->seq,
1739 tcp_highest_sack_seq(tp)))
1740 tcp_advance_highest_sack(sk, skb);
1741 }
68f8353b
IJ
1742 }
1743 return skb;
1744}
1745
4bfabc46 1746static struct sk_buff *tcp_sacktag_bsearch(struct sock *sk, u32 seq)
75c119af
ED
1747{
1748 struct rb_node *parent, **p = &sk->tcp_rtx_queue.rb_node;
1749 struct sk_buff *skb;
75c119af
ED
1750
1751 while (*p) {
1752 parent = *p;
1753 skb = rb_to_skb(parent);
1754 if (before(seq, TCP_SKB_CB(skb)->seq)) {
1755 p = &parent->rb_left;
1756 continue;
1757 }
1758 if (!before(seq, TCP_SKB_CB(skb)->end_seq)) {
1759 p = &parent->rb_right;
1760 continue;
1761 }
75c119af
ED
1762 return skb;
1763 }
1764 return NULL;
1765}
1766
68f8353b 1767static struct sk_buff *tcp_sacktag_skip(struct sk_buff *skb, struct sock *sk,
a1197f5a 1768 u32 skip_to_seq)
68f8353b 1769{
75c119af
ED
1770 if (skb && after(TCP_SKB_CB(skb)->seq, skip_to_seq))
1771 return skb;
d152a7d8 1772
4bfabc46 1773 return tcp_sacktag_bsearch(sk, skip_to_seq);
68f8353b
IJ
1774}
1775
1776static struct sk_buff *tcp_maybe_skipping_dsack(struct sk_buff *skb,
1777 struct sock *sk,
1778 struct tcp_sack_block *next_dup,
a1197f5a
IJ
1779 struct tcp_sacktag_state *state,
1780 u32 skip_to_seq)
68f8353b 1781{
51456b29 1782 if (!next_dup)
68f8353b
IJ
1783 return skb;
1784
1785 if (before(next_dup->start_seq, skip_to_seq)) {
4bfabc46 1786 skb = tcp_sacktag_skip(skb, sk, next_dup->start_seq);
a1197f5a
IJ
1787 skb = tcp_sacktag_walk(skb, sk, NULL, state,
1788 next_dup->start_seq, next_dup->end_seq,
1789 1);
68f8353b
IJ
1790 }
1791
1792 return skb;
1793}
1794
cf533ea5 1795static int tcp_sack_cache_ok(const struct tcp_sock *tp, const struct tcp_sack_block *cache)
68f8353b
IJ
1796{
1797 return cache < tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache);
1798}
1799
1da177e4 1800static int
cf533ea5 1801tcp_sacktag_write_queue(struct sock *sk, const struct sk_buff *ack_skb,
196da974 1802 u32 prior_snd_una, struct tcp_sacktag_state *state)
1da177e4
LT
1803{
1804 struct tcp_sock *tp = tcp_sk(sk);
cf533ea5
ED
1805 const unsigned char *ptr = (skb_transport_header(ack_skb) +
1806 TCP_SKB_CB(ack_skb)->sacked);
fd6dad61 1807 struct tcp_sack_block_wire *sp_wire = (struct tcp_sack_block_wire *)(ptr+2);
4389dded 1808 struct tcp_sack_block sp[TCP_NUM_SACKS];
68f8353b
IJ
1809 struct tcp_sack_block *cache;
1810 struct sk_buff *skb;
4389dded 1811 int num_sacks = min(TCP_NUM_SACKS, (ptr[1] - TCPOLEN_SACK_BASE) >> 3);
fd6dad61 1812 int used_sacks;
a2a385d6 1813 bool found_dup_sack = false;
68f8353b 1814 int i, j;
fda03fbb 1815 int first_sack_index;
1da177e4 1816
196da974 1817 state->flag = 0;
737ff314 1818 state->reord = tp->snd_nxt;
a1197f5a 1819
737ff314 1820 if (!tp->sacked_out)
6859d494 1821 tcp_highest_sack_reset(sk);
1da177e4 1822
1ed83465 1823 found_dup_sack = tcp_check_dsack(sk, ack_skb, sp_wire,
a71d77e6 1824 num_sacks, prior_snd_una, state);
6f74651a
BE
1825
1826 /* Eliminate too old ACKs, but take into
1827 * account more or less fresh ones, they can
1828 * contain valid SACK info.
1829 */
1830 if (before(TCP_SKB_CB(ack_skb)->ack_seq, prior_snd_una - tp->max_window))
1831 return 0;
1832