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