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