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