net: cleanup unsigned to unsigned int
[GitHub/mt8127/android_kernel_alcatel_ttab.git] / net / ipv4 / tcp_input.c
CommitLineData
1da177e4
LT
1/*
2 * INET An implementation of the TCP/IP protocol suite for the LINUX
3 * operating system. INET is implemented using the BSD Socket
4 * interface as the means of communication with the user level.
5 *
6 * Implementation of the Transmission Control Protocol(TCP).
7 *
02c30a84 8 * Authors: Ross Biro
1da177e4
LT
9 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
10 * Mark Evans, <evansmp@uhura.aston.ac.uk>
11 * Corey Minyard <wf-rch!minyard@relay.EU.net>
12 * Florian La Roche, <flla@stud.uni-sb.de>
13 * Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
14 * Linus Torvalds, <torvalds@cs.helsinki.fi>
15 * Alan Cox, <gw4pts@gw4pts.ampr.org>
16 * Matthew Dillon, <dillon@apollo.west.oic.com>
17 * Arnt Gulbrandsen, <agulbra@nvg.unit.no>
18 * Jorge Cwik, <jorge@laser.satlink.net>
19 */
20
21/*
22 * Changes:
23 * Pedro Roque : Fast Retransmit/Recovery.
24 * Two receive queues.
25 * Retransmit queue handled by TCP.
26 * Better retransmit timer handling.
27 * New congestion avoidance.
28 * Header prediction.
29 * Variable renaming.
30 *
31 * Eric : Fast Retransmit.
32 * Randy Scott : MSS option defines.
33 * Eric Schenk : Fixes to slow start algorithm.
34 * Eric Schenk : Yet another double ACK bug.
35 * Eric Schenk : Delayed ACK bug fixes.
36 * Eric Schenk : Floyd style fast retrans war avoidance.
37 * David S. Miller : Don't allow zero congestion window.
38 * Eric Schenk : Fix retransmitter so that it sends
39 * next packet on ack of previous packet.
40 * Andi Kleen : Moved open_request checking here
41 * and process RSTs for open_requests.
42 * Andi Kleen : Better prune_queue, and other fixes.
caa20d9a 43 * Andrey Savochkin: Fix RTT measurements in the presence of
1da177e4
LT
44 * timestamps.
45 * Andrey Savochkin: Check sequence numbers correctly when
46 * removing SACKs due to in sequence incoming
47 * data segments.
48 * Andi Kleen: Make sure we never ack data there is not
49 * enough room for. Also make this condition
50 * a fatal error if it might still happen.
e905a9ed 51 * Andi Kleen: Add tcp_measure_rcv_mss to make
1da177e4 52 * connections with MSS<min(MTU,ann. MSS)
e905a9ed 53 * work without delayed acks.
1da177e4
LT
54 * Andi Kleen: Process packets with PSH set in the
55 * fast path.
56 * J Hadi Salim: ECN support
57 * Andrei Gurtov,
58 * Pasi Sarolahti,
59 * Panu Kuhlberg: Experimental audit of TCP (re)transmission
60 * engine. Lots of bugs are found.
61 * Pasi Sarolahti: F-RTO for dealing with spurious RTOs
1da177e4
LT
62 */
63
afd46503
JP
64#define pr_fmt(fmt) "TCP: " fmt
65
1da177e4 66#include <linux/mm.h>
5a0e3ad6 67#include <linux/slab.h>
1da177e4
LT
68#include <linux/module.h>
69#include <linux/sysctl.h>
a0bffffc 70#include <linux/kernel.h>
5ffc02a1 71#include <net/dst.h>
1da177e4
LT
72#include <net/tcp.h>
73#include <net/inet_common.h>
74#include <linux/ipsec.h>
75#include <asm/unaligned.h>
1a2449a8 76#include <net/netdma.h>
1da177e4 77
ab32ea5d
BH
78int sysctl_tcp_timestamps __read_mostly = 1;
79int sysctl_tcp_window_scaling __read_mostly = 1;
80int sysctl_tcp_sack __read_mostly = 1;
81int sysctl_tcp_fack __read_mostly = 1;
82int sysctl_tcp_reordering __read_mostly = TCP_FASTRETRANS_THRESH;
4bc2f18b 83EXPORT_SYMBOL(sysctl_tcp_reordering);
255cac91 84int sysctl_tcp_ecn __read_mostly = 2;
4bc2f18b 85EXPORT_SYMBOL(sysctl_tcp_ecn);
ab32ea5d
BH
86int sysctl_tcp_dsack __read_mostly = 1;
87int sysctl_tcp_app_win __read_mostly = 31;
88int sysctl_tcp_adv_win_scale __read_mostly = 2;
4bc2f18b 89EXPORT_SYMBOL(sysctl_tcp_adv_win_scale);
1da177e4 90
ab32ea5d
BH
91int sysctl_tcp_stdurg __read_mostly;
92int sysctl_tcp_rfc1337 __read_mostly;
93int sysctl_tcp_max_orphans __read_mostly = NR_FILE;
c96fd3d4 94int sysctl_tcp_frto __read_mostly = 2;
3cfe3baa 95int sysctl_tcp_frto_response __read_mostly;
ab32ea5d 96int sysctl_tcp_nometrics_save __read_mostly;
1da177e4 97
7e380175
AP
98int sysctl_tcp_thin_dupack __read_mostly;
99
ab32ea5d
BH
100int sysctl_tcp_moderate_rcvbuf __read_mostly = 1;
101int sysctl_tcp_abc __read_mostly;
1da177e4 102
1da177e4
LT
103#define FLAG_DATA 0x01 /* Incoming frame contained data. */
104#define FLAG_WIN_UPDATE 0x02 /* Incoming ACK was a window update. */
105#define FLAG_DATA_ACKED 0x04 /* This ACK acknowledged new data. */
106#define FLAG_RETRANS_DATA_ACKED 0x08 /* "" "" some of which was retransmitted. */
107#define FLAG_SYN_ACKED 0x10 /* This ACK acknowledged SYN. */
108#define FLAG_DATA_SACKED 0x20 /* New SACK. */
109#define FLAG_ECE 0x40 /* ECE in this ACK */
1da177e4 110#define FLAG_SLOWPATH 0x100 /* Do not skip RFC checks for window update.*/
4dc2665e 111#define FLAG_ONLY_ORIG_SACKED 0x200 /* SACKs only non-rexmit sent before RTO */
2e605294 112#define FLAG_SND_UNA_ADVANCED 0x400 /* Snd_una was changed (!= FLAG_DATA_ACKED) */
564262c1 113#define FLAG_DSACKING_ACK 0x800 /* SACK blocks contained D-SACK info */
009a2e3e 114#define FLAG_NONHEAD_RETRANS_ACKED 0x1000 /* Non-head rexmitted data was ACKed */
cadbd031 115#define FLAG_SACK_RENEGING 0x2000 /* snd_una advanced to a sacked seq */
1da177e4
LT
116
117#define FLAG_ACKED (FLAG_DATA_ACKED|FLAG_SYN_ACKED)
118#define FLAG_NOT_DUP (FLAG_DATA|FLAG_WIN_UPDATE|FLAG_ACKED)
119#define FLAG_CA_ALERT (FLAG_DATA_SACKED|FLAG_ECE)
120#define FLAG_FORWARD_PROGRESS (FLAG_ACKED|FLAG_DATA_SACKED)
2e605294 121#define FLAG_ANY_PROGRESS (FLAG_FORWARD_PROGRESS|FLAG_SND_UNA_ADVANCED)
1da177e4 122
1da177e4 123#define TCP_REMNANT (TCP_FLAG_FIN|TCP_FLAG_URG|TCP_FLAG_SYN|TCP_FLAG_PSH)
bdf1ee5d 124#define TCP_HP_BITS (~(TCP_RESERVED_BITS|TCP_FLAG_PSH))
1da177e4 125
e905a9ed 126/* Adapt the MSS value used to make delayed ack decision to the
1da177e4 127 * real world.
e905a9ed 128 */
056834d9 129static void tcp_measure_rcv_mss(struct sock *sk, const struct sk_buff *skb)
1da177e4 130{
463c84b9 131 struct inet_connection_sock *icsk = inet_csk(sk);
e905a9ed 132 const unsigned int lss = icsk->icsk_ack.last_seg_size;
463c84b9 133 unsigned int len;
1da177e4 134
e905a9ed 135 icsk->icsk_ack.last_seg_size = 0;
1da177e4
LT
136
137 /* skb->len may jitter because of SACKs, even if peer
138 * sends good full-sized frames.
139 */
056834d9 140 len = skb_shinfo(skb)->gso_size ? : skb->len;
463c84b9
ACM
141 if (len >= icsk->icsk_ack.rcv_mss) {
142 icsk->icsk_ack.rcv_mss = len;
1da177e4
LT
143 } else {
144 /* Otherwise, we make more careful check taking into account,
145 * that SACKs block is variable.
146 *
147 * "len" is invariant segment length, including TCP header.
148 */
9c70220b 149 len += skb->data - skb_transport_header(skb);
bee7ca9e 150 if (len >= TCP_MSS_DEFAULT + sizeof(struct tcphdr) ||
1da177e4
LT
151 /* If PSH is not set, packet should be
152 * full sized, provided peer TCP is not badly broken.
153 * This observation (if it is correct 8)) allows
154 * to handle super-low mtu links fairly.
155 */
156 (len >= TCP_MIN_MSS + sizeof(struct tcphdr) &&
aa8223c7 157 !(tcp_flag_word(tcp_hdr(skb)) & TCP_REMNANT))) {
1da177e4
LT
158 /* Subtract also invariant (if peer is RFC compliant),
159 * tcp header plus fixed timestamp option length.
160 * Resulting "len" is MSS free of SACK jitter.
161 */
463c84b9
ACM
162 len -= tcp_sk(sk)->tcp_header_len;
163 icsk->icsk_ack.last_seg_size = len;
1da177e4 164 if (len == lss) {
463c84b9 165 icsk->icsk_ack.rcv_mss = len;
1da177e4
LT
166 return;
167 }
168 }
1ef9696c
AK
169 if (icsk->icsk_ack.pending & ICSK_ACK_PUSHED)
170 icsk->icsk_ack.pending |= ICSK_ACK_PUSHED2;
463c84b9 171 icsk->icsk_ack.pending |= ICSK_ACK_PUSHED;
1da177e4
LT
172 }
173}
174
463c84b9 175static void tcp_incr_quickack(struct sock *sk)
1da177e4 176{
463c84b9 177 struct inet_connection_sock *icsk = inet_csk(sk);
95c96174 178 unsigned int quickacks = tcp_sk(sk)->rcv_wnd / (2 * icsk->icsk_ack.rcv_mss);
1da177e4 179
056834d9
IJ
180 if (quickacks == 0)
181 quickacks = 2;
463c84b9
ACM
182 if (quickacks > icsk->icsk_ack.quick)
183 icsk->icsk_ack.quick = min(quickacks, TCP_MAX_QUICKACKS);
1da177e4
LT
184}
185
1b9f4092 186static void tcp_enter_quickack_mode(struct sock *sk)
1da177e4 187{
463c84b9
ACM
188 struct inet_connection_sock *icsk = inet_csk(sk);
189 tcp_incr_quickack(sk);
190 icsk->icsk_ack.pingpong = 0;
191 icsk->icsk_ack.ato = TCP_ATO_MIN;
1da177e4
LT
192}
193
194/* Send ACKs quickly, if "quick" count is not exhausted
195 * and the session is not interactive.
196 */
197
463c84b9 198static inline int tcp_in_quickack_mode(const struct sock *sk)
1da177e4 199{
463c84b9
ACM
200 const struct inet_connection_sock *icsk = inet_csk(sk);
201 return icsk->icsk_ack.quick && !icsk->icsk_ack.pingpong;
1da177e4
LT
202}
203
bdf1ee5d
IJ
204static inline void TCP_ECN_queue_cwr(struct tcp_sock *tp)
205{
056834d9 206 if (tp->ecn_flags & TCP_ECN_OK)
bdf1ee5d
IJ
207 tp->ecn_flags |= TCP_ECN_QUEUE_CWR;
208}
209
cf533ea5 210static inline void TCP_ECN_accept_cwr(struct tcp_sock *tp, const struct sk_buff *skb)
bdf1ee5d
IJ
211{
212 if (tcp_hdr(skb)->cwr)
213 tp->ecn_flags &= ~TCP_ECN_DEMAND_CWR;
214}
215
216static inline void TCP_ECN_withdraw_cwr(struct tcp_sock *tp)
217{
218 tp->ecn_flags &= ~TCP_ECN_DEMAND_CWR;
219}
220
7a269ffa 221static inline void TCP_ECN_check_ce(struct tcp_sock *tp, const struct sk_buff *skb)
bdf1ee5d 222{
7a269ffa
ED
223 if (!(tp->ecn_flags & TCP_ECN_OK))
224 return;
225
b82d1bb4 226 switch (TCP_SKB_CB(skb)->ip_dsfield & INET_ECN_MASK) {
7a269ffa 227 case INET_ECN_NOT_ECT:
bdf1ee5d 228 /* Funny extension: if ECT is not set on a segment,
7a269ffa
ED
229 * and we already seen ECT on a previous segment,
230 * it is probably a retransmit.
231 */
232 if (tp->ecn_flags & TCP_ECN_SEEN)
bdf1ee5d 233 tcp_enter_quickack_mode((struct sock *)tp);
7a269ffa
ED
234 break;
235 case INET_ECN_CE:
236 tp->ecn_flags |= TCP_ECN_DEMAND_CWR;
237 /* fallinto */
238 default:
239 tp->ecn_flags |= TCP_ECN_SEEN;
bdf1ee5d
IJ
240 }
241}
242
cf533ea5 243static inline void TCP_ECN_rcv_synack(struct tcp_sock *tp, const struct tcphdr *th)
bdf1ee5d 244{
056834d9 245 if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || th->cwr))
bdf1ee5d
IJ
246 tp->ecn_flags &= ~TCP_ECN_OK;
247}
248
cf533ea5 249static inline void TCP_ECN_rcv_syn(struct tcp_sock *tp, const struct tcphdr *th)
bdf1ee5d 250{
056834d9 251 if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || !th->cwr))
bdf1ee5d
IJ
252 tp->ecn_flags &= ~TCP_ECN_OK;
253}
254
cf533ea5 255static inline int TCP_ECN_rcv_ecn_echo(const struct tcp_sock *tp, const struct tcphdr *th)
bdf1ee5d 256{
056834d9 257 if (th->ece && !th->syn && (tp->ecn_flags & TCP_ECN_OK))
bdf1ee5d
IJ
258 return 1;
259 return 0;
260}
261
1da177e4
LT
262/* Buffer size and advertised window tuning.
263 *
264 * 1. Tuning sk->sk_sndbuf, when connection enters established state.
265 */
266
267static void tcp_fixup_sndbuf(struct sock *sk)
268{
87fb4b7b 269 int sndmem = SKB_TRUESIZE(tcp_sk(sk)->rx_opt.mss_clamp + MAX_TCP_HEADER);
1da177e4 270
06a59ecb
ED
271 sndmem *= TCP_INIT_CWND;
272 if (sk->sk_sndbuf < sndmem)
273 sk->sk_sndbuf = min(sndmem, sysctl_tcp_wmem[2]);
1da177e4
LT
274}
275
276/* 2. Tuning advertised window (window_clamp, rcv_ssthresh)
277 *
278 * All tcp_full_space() is split to two parts: "network" buffer, allocated
279 * forward and advertised in receiver window (tp->rcv_wnd) and
280 * "application buffer", required to isolate scheduling/application
281 * latencies from network.
282 * window_clamp is maximal advertised window. It can be less than
283 * tcp_full_space(), in this case tcp_full_space() - window_clamp
284 * is reserved for "application" buffer. The less window_clamp is
285 * the smoother our behaviour from viewpoint of network, but the lower
286 * throughput and the higher sensitivity of the connection to losses. 8)
287 *
288 * rcv_ssthresh is more strict window_clamp used at "slow start"
289 * phase to predict further behaviour of this connection.
290 * It is used for two goals:
291 * - to enforce header prediction at sender, even when application
292 * requires some significant "application buffer". It is check #1.
293 * - to prevent pruning of receive queue because of misprediction
294 * of receiver window. Check #2.
295 *
296 * The scheme does not work when sender sends good segments opening
caa20d9a 297 * window and then starts to feed us spaghetti. But it should work
1da177e4
LT
298 * in common situations. Otherwise, we have to rely on queue collapsing.
299 */
300
301/* Slow part of check#2. */
9e412ba7 302static int __tcp_grow_window(const struct sock *sk, const struct sk_buff *skb)
1da177e4 303{
9e412ba7 304 struct tcp_sock *tp = tcp_sk(sk);
1da177e4 305 /* Optimize this! */
dfd4f0ae
ED
306 int truesize = tcp_win_from_space(skb->truesize) >> 1;
307 int window = tcp_win_from_space(sysctl_tcp_rmem[2]) >> 1;
1da177e4
LT
308
309 while (tp->rcv_ssthresh <= window) {
310 if (truesize <= skb->len)
463c84b9 311 return 2 * inet_csk(sk)->icsk_ack.rcv_mss;
1da177e4
LT
312
313 truesize >>= 1;
314 window >>= 1;
315 }
316 return 0;
317}
318
cf533ea5 319static void tcp_grow_window(struct sock *sk, const struct sk_buff *skb)
1da177e4 320{
9e412ba7
IJ
321 struct tcp_sock *tp = tcp_sk(sk);
322
1da177e4
LT
323 /* Check #1 */
324 if (tp->rcv_ssthresh < tp->window_clamp &&
325 (int)tp->rcv_ssthresh < tcp_space(sk) &&
180d8cd9 326 !sk_under_memory_pressure(sk)) {
1da177e4
LT
327 int incr;
328
329 /* Check #2. Increase window, if skb with such overhead
330 * will fit to rcvbuf in future.
331 */
332 if (tcp_win_from_space(skb->truesize) <= skb->len)
056834d9 333 incr = 2 * tp->advmss;
1da177e4 334 else
9e412ba7 335 incr = __tcp_grow_window(sk, skb);
1da177e4
LT
336
337 if (incr) {
056834d9
IJ
338 tp->rcv_ssthresh = min(tp->rcv_ssthresh + incr,
339 tp->window_clamp);
463c84b9 340 inet_csk(sk)->icsk_ack.quick |= 1;
1da177e4
LT
341 }
342 }
343}
344
345/* 3. Tuning rcvbuf, when connection enters established state. */
346
347static void tcp_fixup_rcvbuf(struct sock *sk)
348{
e9266a02
ED
349 u32 mss = tcp_sk(sk)->advmss;
350 u32 icwnd = TCP_DEFAULT_INIT_RCVWND;
351 int rcvmem;
1da177e4 352
e9266a02
ED
353 /* Limit to 10 segments if mss <= 1460,
354 * or 14600/mss segments, with a minimum of two segments.
1da177e4 355 */
e9266a02
ED
356 if (mss > 1460)
357 icwnd = max_t(u32, (1460 * TCP_DEFAULT_INIT_RCVWND) / mss, 2);
358
359 rcvmem = SKB_TRUESIZE(mss + MAX_TCP_HEADER);
360 while (tcp_win_from_space(rcvmem) < mss)
1da177e4 361 rcvmem += 128;
e9266a02
ED
362
363 rcvmem *= icwnd;
364
365 if (sk->sk_rcvbuf < rcvmem)
366 sk->sk_rcvbuf = min(rcvmem, sysctl_tcp_rmem[2]);
1da177e4
LT
367}
368
caa20d9a 369/* 4. Try to fixup all. It is made immediately after connection enters
1da177e4
LT
370 * established state.
371 */
372static void tcp_init_buffer_space(struct sock *sk)
373{
374 struct tcp_sock *tp = tcp_sk(sk);
375 int maxwin;
376
377 if (!(sk->sk_userlocks & SOCK_RCVBUF_LOCK))
378 tcp_fixup_rcvbuf(sk);
379 if (!(sk->sk_userlocks & SOCK_SNDBUF_LOCK))
380 tcp_fixup_sndbuf(sk);
381
382 tp->rcvq_space.space = tp->rcv_wnd;
383
384 maxwin = tcp_full_space(sk);
385
386 if (tp->window_clamp >= maxwin) {
387 tp->window_clamp = maxwin;
388
389 if (sysctl_tcp_app_win && maxwin > 4 * tp->advmss)
390 tp->window_clamp = max(maxwin -
391 (maxwin >> sysctl_tcp_app_win),
392 4 * tp->advmss);
393 }
394
395 /* Force reservation of one segment. */
396 if (sysctl_tcp_app_win &&
397 tp->window_clamp > 2 * tp->advmss &&
398 tp->window_clamp + tp->advmss > maxwin)
399 tp->window_clamp = max(2 * tp->advmss, maxwin - tp->advmss);
400
401 tp->rcv_ssthresh = min(tp->rcv_ssthresh, tp->window_clamp);
402 tp->snd_cwnd_stamp = tcp_time_stamp;
403}
404
1da177e4 405/* 5. Recalculate window clamp after socket hit its memory bounds. */
9e412ba7 406static void tcp_clamp_window(struct sock *sk)
1da177e4 407{
9e412ba7 408 struct tcp_sock *tp = tcp_sk(sk);
6687e988 409 struct inet_connection_sock *icsk = inet_csk(sk);
1da177e4 410
6687e988 411 icsk->icsk_ack.quick = 0;
1da177e4 412
326f36e9
JH
413 if (sk->sk_rcvbuf < sysctl_tcp_rmem[2] &&
414 !(sk->sk_userlocks & SOCK_RCVBUF_LOCK) &&
180d8cd9
GC
415 !sk_under_memory_pressure(sk) &&
416 sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0)) {
326f36e9
JH
417 sk->sk_rcvbuf = min(atomic_read(&sk->sk_rmem_alloc),
418 sysctl_tcp_rmem[2]);
1da177e4 419 }
326f36e9 420 if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf)
056834d9 421 tp->rcv_ssthresh = min(tp->window_clamp, 2U * tp->advmss);
1da177e4
LT
422}
423
40efc6fa
SH
424/* Initialize RCV_MSS value.
425 * RCV_MSS is an our guess about MSS used by the peer.
426 * We haven't any direct information about the MSS.
427 * It's better to underestimate the RCV_MSS rather than overestimate.
428 * Overestimations make us ACKing less frequently than needed.
429 * Underestimations are more easy to detect and fix by tcp_measure_rcv_mss().
430 */
431void tcp_initialize_rcv_mss(struct sock *sk)
432{
cf533ea5 433 const struct tcp_sock *tp = tcp_sk(sk);
40efc6fa
SH
434 unsigned int hint = min_t(unsigned int, tp->advmss, tp->mss_cache);
435
056834d9 436 hint = min(hint, tp->rcv_wnd / 2);
bee7ca9e 437 hint = min(hint, TCP_MSS_DEFAULT);
40efc6fa
SH
438 hint = max(hint, TCP_MIN_MSS);
439
440 inet_csk(sk)->icsk_ack.rcv_mss = hint;
441}
4bc2f18b 442EXPORT_SYMBOL(tcp_initialize_rcv_mss);
40efc6fa 443
1da177e4
LT
444/* Receiver "autotuning" code.
445 *
446 * The algorithm for RTT estimation w/o timestamps is based on
447 * Dynamic Right-Sizing (DRS) by Wu Feng and Mike Fisk of LANL.
631dd1a8 448 * <http://public.lanl.gov/radiant/pubs.html#DRS>
1da177e4
LT
449 *
450 * More detail on this code can be found at
631dd1a8 451 * <http://staff.psc.edu/jheffner/>,
1da177e4
LT
452 * though this reference is out of date. A new paper
453 * is pending.
454 */
455static void tcp_rcv_rtt_update(struct tcp_sock *tp, u32 sample, int win_dep)
456{
457 u32 new_sample = tp->rcv_rtt_est.rtt;
458 long m = sample;
459
460 if (m == 0)
461 m = 1;
462
463 if (new_sample != 0) {
464 /* If we sample in larger samples in the non-timestamp
465 * case, we could grossly overestimate the RTT especially
466 * with chatty applications or bulk transfer apps which
467 * are stalled on filesystem I/O.
468 *
469 * Also, since we are only going for a minimum in the
31f34269 470 * non-timestamp case, we do not smooth things out
caa20d9a 471 * else with timestamps disabled convergence takes too
1da177e4
LT
472 * long.
473 */
474 if (!win_dep) {
475 m -= (new_sample >> 3);
476 new_sample += m;
18a223e0
NC
477 } else {
478 m <<= 3;
479 if (m < new_sample)
480 new_sample = m;
481 }
1da177e4 482 } else {
caa20d9a 483 /* No previous measure. */
1da177e4
LT
484 new_sample = m << 3;
485 }
486
487 if (tp->rcv_rtt_est.rtt != new_sample)
488 tp->rcv_rtt_est.rtt = new_sample;
489}
490
491static inline void tcp_rcv_rtt_measure(struct tcp_sock *tp)
492{
493 if (tp->rcv_rtt_est.time == 0)
494 goto new_measure;
495 if (before(tp->rcv_nxt, tp->rcv_rtt_est.seq))
496 return;
056834d9 497 tcp_rcv_rtt_update(tp, jiffies - tp->rcv_rtt_est.time, 1);
1da177e4
LT
498
499new_measure:
500 tp->rcv_rtt_est.seq = tp->rcv_nxt + tp->rcv_wnd;
501 tp->rcv_rtt_est.time = tcp_time_stamp;
502}
503
056834d9
IJ
504static inline void tcp_rcv_rtt_measure_ts(struct sock *sk,
505 const struct sk_buff *skb)
1da177e4 506{
463c84b9 507 struct tcp_sock *tp = tcp_sk(sk);
1da177e4
LT
508 if (tp->rx_opt.rcv_tsecr &&
509 (TCP_SKB_CB(skb)->end_seq -
463c84b9 510 TCP_SKB_CB(skb)->seq >= inet_csk(sk)->icsk_ack.rcv_mss))
1da177e4
LT
511 tcp_rcv_rtt_update(tp, tcp_time_stamp - tp->rx_opt.rcv_tsecr, 0);
512}
513
514/*
515 * This function should be called every time data is copied to user space.
516 * It calculates the appropriate TCP receive buffer space.
517 */
518void tcp_rcv_space_adjust(struct sock *sk)
519{
520 struct tcp_sock *tp = tcp_sk(sk);
521 int time;
522 int space;
e905a9ed 523
1da177e4
LT
524 if (tp->rcvq_space.time == 0)
525 goto new_measure;
e905a9ed 526
1da177e4 527 time = tcp_time_stamp - tp->rcvq_space.time;
056834d9 528 if (time < (tp->rcv_rtt_est.rtt >> 3) || tp->rcv_rtt_est.rtt == 0)
1da177e4 529 return;
e905a9ed 530
1da177e4
LT
531 space = 2 * (tp->copied_seq - tp->rcvq_space.seq);
532
533 space = max(tp->rcvq_space.space, space);
534
535 if (tp->rcvq_space.space != space) {
536 int rcvmem;
537
538 tp->rcvq_space.space = space;
539
6fcf9412
JH
540 if (sysctl_tcp_moderate_rcvbuf &&
541 !(sk->sk_userlocks & SOCK_RCVBUF_LOCK)) {
1da177e4
LT
542 int new_clamp = space;
543
544 /* Receive space grows, normalize in order to
545 * take into account packet headers and sk_buff
546 * structure overhead.
547 */
548 space /= tp->advmss;
549 if (!space)
550 space = 1;
87fb4b7b 551 rcvmem = SKB_TRUESIZE(tp->advmss + MAX_TCP_HEADER);
1da177e4
LT
552 while (tcp_win_from_space(rcvmem) < tp->advmss)
553 rcvmem += 128;
554 space *= rcvmem;
555 space = min(space, sysctl_tcp_rmem[2]);
556 if (space > sk->sk_rcvbuf) {
557 sk->sk_rcvbuf = space;
558
559 /* Make the window clamp follow along. */
560 tp->window_clamp = new_clamp;
561 }
562 }
563 }
e905a9ed 564
1da177e4
LT
565new_measure:
566 tp->rcvq_space.seq = tp->copied_seq;
567 tp->rcvq_space.time = tcp_time_stamp;
568}
569
570/* There is something which you must keep in mind when you analyze the
571 * behavior of the tp->ato delayed ack timeout interval. When a
572 * connection starts up, we want to ack as quickly as possible. The
573 * problem is that "good" TCP's do slow start at the beginning of data
574 * transmission. The means that until we send the first few ACK's the
575 * sender will sit on his end and only queue most of his data, because
576 * he can only send snd_cwnd unacked packets at any given time. For
577 * each ACK we send, he increments snd_cwnd and transmits more of his
578 * queue. -DaveM
579 */
9e412ba7 580static void tcp_event_data_recv(struct sock *sk, struct sk_buff *skb)
1da177e4 581{
9e412ba7 582 struct tcp_sock *tp = tcp_sk(sk);
463c84b9 583 struct inet_connection_sock *icsk = inet_csk(sk);
1da177e4
LT
584 u32 now;
585
463c84b9 586 inet_csk_schedule_ack(sk);
1da177e4 587
463c84b9 588 tcp_measure_rcv_mss(sk, skb);
1da177e4
LT
589
590 tcp_rcv_rtt_measure(tp);
e905a9ed 591
1da177e4
LT
592 now = tcp_time_stamp;
593
463c84b9 594 if (!icsk->icsk_ack.ato) {
1da177e4
LT
595 /* The _first_ data packet received, initialize
596 * delayed ACK engine.
597 */
463c84b9
ACM
598 tcp_incr_quickack(sk);
599 icsk->icsk_ack.ato = TCP_ATO_MIN;
1da177e4 600 } else {
463c84b9 601 int m = now - icsk->icsk_ack.lrcvtime;
1da177e4 602
056834d9 603 if (m <= TCP_ATO_MIN / 2) {
1da177e4 604 /* The fastest case is the first. */
463c84b9
ACM
605 icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + TCP_ATO_MIN / 2;
606 } else if (m < icsk->icsk_ack.ato) {
607 icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + m;
608 if (icsk->icsk_ack.ato > icsk->icsk_rto)
609 icsk->icsk_ack.ato = icsk->icsk_rto;
610 } else if (m > icsk->icsk_rto) {
caa20d9a 611 /* Too long gap. Apparently sender failed to
1da177e4
LT
612 * restart window, so that we send ACKs quickly.
613 */
463c84b9 614 tcp_incr_quickack(sk);
3ab224be 615 sk_mem_reclaim(sk);
1da177e4
LT
616 }
617 }
463c84b9 618 icsk->icsk_ack.lrcvtime = now;
1da177e4
LT
619
620 TCP_ECN_check_ce(tp, skb);
621
622 if (skb->len >= 128)
9e412ba7 623 tcp_grow_window(sk, skb);
1da177e4
LT
624}
625
1da177e4
LT
626/* Called to compute a smoothed rtt estimate. The data fed to this
627 * routine either comes from timestamps, or from segments that were
628 * known _not_ to have been retransmitted [see Karn/Partridge
629 * Proceedings SIGCOMM 87]. The algorithm is from the SIGCOMM 88
630 * piece by Van Jacobson.
631 * NOTE: the next three routines used to be one big routine.
632 * To save cycles in the RFC 1323 implementation it was better to break
633 * it up into three procedures. -- erics
634 */
2d2abbab 635static void tcp_rtt_estimator(struct sock *sk, const __u32 mrtt)
1da177e4 636{
6687e988 637 struct tcp_sock *tp = tcp_sk(sk);
1da177e4
LT
638 long m = mrtt; /* RTT */
639
1da177e4
LT
640 /* The following amusing code comes from Jacobson's
641 * article in SIGCOMM '88. Note that rtt and mdev
642 * are scaled versions of rtt and mean deviation.
e905a9ed 643 * This is designed to be as fast as possible
1da177e4
LT
644 * m stands for "measurement".
645 *
646 * On a 1990 paper the rto value is changed to:
647 * RTO = rtt + 4 * mdev
648 *
649 * Funny. This algorithm seems to be very broken.
650 * These formulae increase RTO, when it should be decreased, increase
31f34269 651 * too slowly, when it should be increased quickly, decrease too quickly
1da177e4
LT
652 * etc. I guess in BSD RTO takes ONE value, so that it is absolutely
653 * does not matter how to _calculate_ it. Seems, it was trap
654 * that VJ failed to avoid. 8)
655 */
2de979bd 656 if (m == 0)
1da177e4
LT
657 m = 1;
658 if (tp->srtt != 0) {
659 m -= (tp->srtt >> 3); /* m is now error in rtt est */
660 tp->srtt += m; /* rtt = 7/8 rtt + 1/8 new */
661 if (m < 0) {
662 m = -m; /* m is now abs(error) */
663 m -= (tp->mdev >> 2); /* similar update on mdev */
664 /* This is similar to one of Eifel findings.
665 * Eifel blocks mdev updates when rtt decreases.
666 * This solution is a bit different: we use finer gain
667 * for mdev in this case (alpha*beta).
668 * Like Eifel it also prevents growth of rto,
669 * but also it limits too fast rto decreases,
670 * happening in pure Eifel.
671 */
672 if (m > 0)
673 m >>= 3;
674 } else {
675 m -= (tp->mdev >> 2); /* similar update on mdev */
676 }
677 tp->mdev += m; /* mdev = 3/4 mdev + 1/4 new */
678 if (tp->mdev > tp->mdev_max) {
679 tp->mdev_max = tp->mdev;
680 if (tp->mdev_max > tp->rttvar)
681 tp->rttvar = tp->mdev_max;
682 }
683 if (after(tp->snd_una, tp->rtt_seq)) {
684 if (tp->mdev_max < tp->rttvar)
056834d9 685 tp->rttvar -= (tp->rttvar - tp->mdev_max) >> 2;
1da177e4 686 tp->rtt_seq = tp->snd_nxt;
05bb1fad 687 tp->mdev_max = tcp_rto_min(sk);
1da177e4
LT
688 }
689 } else {
690 /* no previous measure. */
056834d9
IJ
691 tp->srtt = m << 3; /* take the measured time to be rtt */
692 tp->mdev = m << 1; /* make sure rto = 3*rtt */
05bb1fad 693 tp->mdev_max = tp->rttvar = max(tp->mdev, tcp_rto_min(sk));
1da177e4
LT
694 tp->rtt_seq = tp->snd_nxt;
695 }
1da177e4
LT
696}
697
698/* Calculate rto without backoff. This is the second half of Van Jacobson's
699 * routine referred to above.
700 */
463c84b9 701static inline void tcp_set_rto(struct sock *sk)
1da177e4 702{
463c84b9 703 const struct tcp_sock *tp = tcp_sk(sk);
1da177e4
LT
704 /* Old crap is replaced with new one. 8)
705 *
706 * More seriously:
707 * 1. If rtt variance happened to be less 50msec, it is hallucination.
708 * It cannot be less due to utterly erratic ACK generation made
709 * at least by solaris and freebsd. "Erratic ACKs" has _nothing_
710 * to do with delayed acks, because at cwnd>2 true delack timeout
711 * is invisible. Actually, Linux-2.4 also generates erratic
caa20d9a 712 * ACKs in some circumstances.
1da177e4 713 */
f1ecd5d9 714 inet_csk(sk)->icsk_rto = __tcp_set_rto(tp);
1da177e4
LT
715
716 /* 2. Fixups made earlier cannot be right.
717 * If we do not estimate RTO correctly without them,
718 * all the algo is pure shit and should be replaced
caa20d9a 719 * with correct one. It is exactly, which we pretend to do.
1da177e4 720 */
1da177e4 721
ee6aac59
IJ
722 /* NOTE: clamping at TCP_RTO_MIN is not required, current algo
723 * guarantees that rto is higher.
724 */
f1ecd5d9 725 tcp_bound_rto(sk);
1da177e4
LT
726}
727
728/* Save metrics learned by this TCP session.
729 This function is called only, when TCP finishes successfully
730 i.e. when it enters TIME-WAIT or goes from LAST-ACK to CLOSE.
731 */
732void tcp_update_metrics(struct sock *sk)
733{
734 struct tcp_sock *tp = tcp_sk(sk);
735 struct dst_entry *dst = __sk_dst_get(sk);
736
737 if (sysctl_tcp_nometrics_save)
738 return;
739
740 dst_confirm(dst);
741
056834d9 742 if (dst && (dst->flags & DST_HOST)) {
6687e988 743 const struct inet_connection_sock *icsk = inet_csk(sk);
1da177e4 744 int m;
c1e20f7c 745 unsigned long rtt;
1da177e4 746
6687e988 747 if (icsk->icsk_backoff || !tp->srtt) {
1da177e4
LT
748 /* This session failed to estimate rtt. Why?
749 * Probably, no packets returned in time.
750 * Reset our results.
751 */
752 if (!(dst_metric_locked(dst, RTAX_RTT)))
defb3519 753 dst_metric_set(dst, RTAX_RTT, 0);
1da177e4
LT
754 return;
755 }
756
c1e20f7c
SH
757 rtt = dst_metric_rtt(dst, RTAX_RTT);
758 m = rtt - tp->srtt;
1da177e4
LT
759
760 /* If newly calculated rtt larger than stored one,
761 * store new one. Otherwise, use EWMA. Remember,
762 * rtt overestimation is always better than underestimation.
763 */
764 if (!(dst_metric_locked(dst, RTAX_RTT))) {
765 if (m <= 0)
c1e20f7c 766 set_dst_metric_rtt(dst, RTAX_RTT, tp->srtt);
1da177e4 767 else
c1e20f7c 768 set_dst_metric_rtt(dst, RTAX_RTT, rtt - (m >> 3));
1da177e4
LT
769 }
770
771 if (!(dst_metric_locked(dst, RTAX_RTTVAR))) {
c1e20f7c 772 unsigned long var;
1da177e4
LT
773 if (m < 0)
774 m = -m;
775
776 /* Scale deviation to rttvar fixed point */
777 m >>= 1;
778 if (m < tp->mdev)
779 m = tp->mdev;
780
c1e20f7c
SH
781 var = dst_metric_rtt(dst, RTAX_RTTVAR);
782 if (m >= var)
783 var = m;
1da177e4 784 else
c1e20f7c
SH
785 var -= (var - m) >> 2;
786
787 set_dst_metric_rtt(dst, RTAX_RTTVAR, var);
1da177e4
LT
788 }
789
0b6a05c1 790 if (tcp_in_initial_slowstart(tp)) {
1da177e4
LT
791 /* Slow start still did not finish. */
792 if (dst_metric(dst, RTAX_SSTHRESH) &&
793 !dst_metric_locked(dst, RTAX_SSTHRESH) &&
794 (tp->snd_cwnd >> 1) > dst_metric(dst, RTAX_SSTHRESH))
defb3519 795 dst_metric_set(dst, RTAX_SSTHRESH, tp->snd_cwnd >> 1);
1da177e4
LT
796 if (!dst_metric_locked(dst, RTAX_CWND) &&
797 tp->snd_cwnd > dst_metric(dst, RTAX_CWND))
defb3519 798 dst_metric_set(dst, RTAX_CWND, tp->snd_cwnd);
1da177e4 799 } else if (tp->snd_cwnd > tp->snd_ssthresh &&
6687e988 800 icsk->icsk_ca_state == TCP_CA_Open) {
1da177e4
LT
801 /* Cong. avoidance phase, cwnd is reliable. */
802 if (!dst_metric_locked(dst, RTAX_SSTHRESH))
defb3519
DM
803 dst_metric_set(dst, RTAX_SSTHRESH,
804 max(tp->snd_cwnd >> 1, tp->snd_ssthresh));
1da177e4 805 if (!dst_metric_locked(dst, RTAX_CWND))
defb3519
DM
806 dst_metric_set(dst, RTAX_CWND,
807 (dst_metric(dst, RTAX_CWND) +
808 tp->snd_cwnd) >> 1);
1da177e4
LT
809 } else {
810 /* Else slow start did not finish, cwnd is non-sense,
811 ssthresh may be also invalid.
812 */
813 if (!dst_metric_locked(dst, RTAX_CWND))
defb3519
DM
814 dst_metric_set(dst, RTAX_CWND,
815 (dst_metric(dst, RTAX_CWND) +
816 tp->snd_ssthresh) >> 1);
5ffc02a1 817 if (dst_metric(dst, RTAX_SSTHRESH) &&
1da177e4 818 !dst_metric_locked(dst, RTAX_SSTHRESH) &&
5ffc02a1 819 tp->snd_ssthresh > dst_metric(dst, RTAX_SSTHRESH))
defb3519 820 dst_metric_set(dst, RTAX_SSTHRESH, tp->snd_ssthresh);
1da177e4
LT
821 }
822
823 if (!dst_metric_locked(dst, RTAX_REORDERING)) {
5ffc02a1 824 if (dst_metric(dst, RTAX_REORDERING) < tp->reordering &&
1da177e4 825 tp->reordering != sysctl_tcp_reordering)
defb3519 826 dst_metric_set(dst, RTAX_REORDERING, tp->reordering);
1da177e4
LT
827 }
828 }
829}
830
cf533ea5 831__u32 tcp_init_cwnd(const struct tcp_sock *tp, const struct dst_entry *dst)
1da177e4
LT
832{
833 __u32 cwnd = (dst ? dst_metric(dst, RTAX_INITCWND) : 0);
834
22b71c8f 835 if (!cwnd)
442b9635 836 cwnd = TCP_INIT_CWND;
1da177e4
LT
837 return min_t(__u32, cwnd, tp->snd_cwnd_clamp);
838}
839
40efc6fa 840/* Set slow start threshold and cwnd not falling to slow start */
3cfe3baa 841void tcp_enter_cwr(struct sock *sk, const int set_ssthresh)
40efc6fa
SH
842{
843 struct tcp_sock *tp = tcp_sk(sk);
3cfe3baa 844 const struct inet_connection_sock *icsk = inet_csk(sk);
40efc6fa
SH
845
846 tp->prior_ssthresh = 0;
847 tp->bytes_acked = 0;
e01f9d77 848 if (icsk->icsk_ca_state < TCP_CA_CWR) {
40efc6fa 849 tp->undo_marker = 0;
3cfe3baa
IJ
850 if (set_ssthresh)
851 tp->snd_ssthresh = icsk->icsk_ca_ops->ssthresh(sk);
40efc6fa
SH
852 tp->snd_cwnd = min(tp->snd_cwnd,
853 tcp_packets_in_flight(tp) + 1U);
854 tp->snd_cwnd_cnt = 0;
855 tp->high_seq = tp->snd_nxt;
856 tp->snd_cwnd_stamp = tcp_time_stamp;
857 TCP_ECN_queue_cwr(tp);
858
859 tcp_set_ca_state(sk, TCP_CA_CWR);
860 }
861}
862
e60402d0
IJ
863/*
864 * Packet counting of FACK is based on in-order assumptions, therefore TCP
865 * disables it when reordering is detected
866 */
867static void tcp_disable_fack(struct tcp_sock *tp)
868{
85cc391c
IJ
869 /* RFC3517 uses different metric in lost marker => reset on change */
870 if (tcp_is_fack(tp))
871 tp->lost_skb_hint = NULL;
ab56222a 872 tp->rx_opt.sack_ok &= ~TCP_FACK_ENABLED;
e60402d0
IJ
873}
874
564262c1 875/* Take a notice that peer is sending D-SACKs */
e60402d0
IJ
876static void tcp_dsack_seen(struct tcp_sock *tp)
877{
ab56222a 878 tp->rx_opt.sack_ok |= TCP_DSACK_SEEN;
e60402d0
IJ
879}
880
1da177e4
LT
881/* Initialize metrics on socket. */
882
883static void tcp_init_metrics(struct sock *sk)
884{
885 struct tcp_sock *tp = tcp_sk(sk);
886 struct dst_entry *dst = __sk_dst_get(sk);
887
888 if (dst == NULL)
889 goto reset;
890
891 dst_confirm(dst);
892
893 if (dst_metric_locked(dst, RTAX_CWND))
894 tp->snd_cwnd_clamp = dst_metric(dst, RTAX_CWND);
895 if (dst_metric(dst, RTAX_SSTHRESH)) {
896 tp->snd_ssthresh = dst_metric(dst, RTAX_SSTHRESH);
897 if (tp->snd_ssthresh > tp->snd_cwnd_clamp)
898 tp->snd_ssthresh = tp->snd_cwnd_clamp;
9ad7c049
JC
899 } else {
900 /* ssthresh may have been reduced unnecessarily during.
901 * 3WHS. Restore it back to its initial default.
902 */
903 tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
1da177e4
LT
904 }
905 if (dst_metric(dst, RTAX_REORDERING) &&
906 tp->reordering != dst_metric(dst, RTAX_REORDERING)) {
e60402d0 907 tcp_disable_fack(tp);
1da177e4
LT
908 tp->reordering = dst_metric(dst, RTAX_REORDERING);
909 }
910
9ad7c049 911 if (dst_metric(dst, RTAX_RTT) == 0 || tp->srtt == 0)
1da177e4
LT
912 goto reset;
913
914 /* Initial rtt is determined from SYN,SYN-ACK.
915 * The segment is small and rtt may appear much
916 * less than real one. Use per-dst memory
917 * to make it more realistic.
918 *
919 * A bit of theory. RTT is time passed after "normal" sized packet
caa20d9a 920 * is sent until it is ACKed. In normal circumstances sending small
1da177e4
LT
921 * packets force peer to delay ACKs and calculation is correct too.
922 * The algorithm is adaptive and, provided we follow specs, it
923 * NEVER underestimate RTT. BUT! If peer tries to make some clever
924 * tricks sort of "quick acks" for time long enough to decrease RTT
925 * to low value, and then abruptly stops to do it and starts to delay
926 * ACKs, wait for troubles.
927 */
c1e20f7c
SH
928 if (dst_metric_rtt(dst, RTAX_RTT) > tp->srtt) {
929 tp->srtt = dst_metric_rtt(dst, RTAX_RTT);
1da177e4
LT
930 tp->rtt_seq = tp->snd_nxt;
931 }
c1e20f7c
SH
932 if (dst_metric_rtt(dst, RTAX_RTTVAR) > tp->mdev) {
933 tp->mdev = dst_metric_rtt(dst, RTAX_RTTVAR);
488faa2a 934 tp->mdev_max = tp->rttvar = max(tp->mdev, tcp_rto_min(sk));
1da177e4 935 }
463c84b9 936 tcp_set_rto(sk);
1da177e4 937reset:
9ad7c049 938 if (tp->srtt == 0) {
fd4f2cea 939 /* RFC6298: 5.7 We've failed to get a valid RTT sample from
9ad7c049
JC
940 * 3WHS. This is most likely due to retransmission,
941 * including spurious one. Reset the RTO back to 3secs
942 * from the more aggressive 1sec to avoid more spurious
943 * retransmission.
d9f4fbaf 944 */
9ad7c049
JC
945 tp->mdev = tp->mdev_max = tp->rttvar = TCP_TIMEOUT_FALLBACK;
946 inet_csk(sk)->icsk_rto = TCP_TIMEOUT_FALLBACK;
1da177e4 947 }
9ad7c049 948 /* Cut cwnd down to 1 per RFC5681 if SYN or SYN-ACK has been
fd4f2cea 949 * retransmitted. In light of RFC6298 more aggressive 1sec
9ad7c049
JC
950 * initRTO, we only reset cwnd when more than 1 SYN/SYN-ACK
951 * retransmission has occurred.
952 */
953 if (tp->total_retrans > 1)
954 tp->snd_cwnd = 1;
955 else
956 tp->snd_cwnd = tcp_init_cwnd(tp, dst);
d9f4fbaf 957 tp->snd_cwnd_stamp = tcp_time_stamp;
1da177e4
LT
958}
959
6687e988
ACM
960static void tcp_update_reordering(struct sock *sk, const int metric,
961 const int ts)
1da177e4 962{
6687e988 963 struct tcp_sock *tp = tcp_sk(sk);
1da177e4 964 if (metric > tp->reordering) {
40b215e5
PE
965 int mib_idx;
966
1da177e4
LT
967 tp->reordering = min(TCP_MAX_REORDERING, metric);
968
969 /* This exciting event is worth to be remembered. 8) */
970 if (ts)
40b215e5 971 mib_idx = LINUX_MIB_TCPTSREORDER;
e60402d0 972 else if (tcp_is_reno(tp))
40b215e5 973 mib_idx = LINUX_MIB_TCPRENOREORDER;
e60402d0 974 else if (tcp_is_fack(tp))
40b215e5 975 mib_idx = LINUX_MIB_TCPFACKREORDER;
1da177e4 976 else
40b215e5
PE
977 mib_idx = LINUX_MIB_TCPSACKREORDER;
978
de0744af 979 NET_INC_STATS_BH(sock_net(sk), mib_idx);
1da177e4
LT
980#if FASTRETRANS_DEBUG > 1
981 printk(KERN_DEBUG "Disorder%d %d %u f%u s%u rr%d\n",
6687e988 982 tp->rx_opt.sack_ok, inet_csk(sk)->icsk_ca_state,
1da177e4
LT
983 tp->reordering,
984 tp->fackets_out,
985 tp->sacked_out,
986 tp->undo_marker ? tp->undo_retrans : 0);
987#endif
e60402d0 988 tcp_disable_fack(tp);
1da177e4
LT
989 }
990}
991
006f582c 992/* This must be called before lost_out is incremented */
c8c213f2
IJ
993static void tcp_verify_retransmit_hint(struct tcp_sock *tp, struct sk_buff *skb)
994{
006f582c 995 if ((tp->retransmit_skb_hint == NULL) ||
c8c213f2
IJ
996 before(TCP_SKB_CB(skb)->seq,
997 TCP_SKB_CB(tp->retransmit_skb_hint)->seq))
006f582c
IJ
998 tp->retransmit_skb_hint = skb;
999
1000 if (!tp->lost_out ||
1001 after(TCP_SKB_CB(skb)->end_seq, tp->retransmit_high))
1002 tp->retransmit_high = TCP_SKB_CB(skb)->end_seq;
c8c213f2
IJ
1003}
1004
41ea36e3
IJ
1005static void tcp_skb_mark_lost(struct tcp_sock *tp, struct sk_buff *skb)
1006{
1007 if (!(TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_ACKED))) {
1008 tcp_verify_retransmit_hint(tp, skb);
1009
1010 tp->lost_out += tcp_skb_pcount(skb);
1011 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1012 }
1013}
1014
e1aa680f
IJ
1015static void tcp_skb_mark_lost_uncond_verify(struct tcp_sock *tp,
1016 struct sk_buff *skb)
006f582c
IJ
1017{
1018 tcp_verify_retransmit_hint(tp, skb);
1019
1020 if (!(TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_ACKED))) {
1021 tp->lost_out += tcp_skb_pcount(skb);
1022 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1023 }
1024}
1025
1da177e4
LT
1026/* This procedure tags the retransmission queue when SACKs arrive.
1027 *
1028 * We have three tag bits: SACKED(S), RETRANS(R) and LOST(L).
1029 * Packets in queue with these bits set are counted in variables
1030 * sacked_out, retrans_out and lost_out, correspondingly.
1031 *
1032 * Valid combinations are:
1033 * Tag InFlight Description
1034 * 0 1 - orig segment is in flight.
1035 * S 0 - nothing flies, orig reached receiver.
1036 * L 0 - nothing flies, orig lost by net.
1037 * R 2 - both orig and retransmit are in flight.
1038 * L|R 1 - orig is lost, retransmit is in flight.
1039 * S|R 1 - orig reached receiver, retrans is still in flight.
1040 * (L|S|R is logically valid, it could occur when L|R is sacked,
1041 * but it is equivalent to plain S and code short-curcuits it to S.
1042 * L|S is logically invalid, it would mean -1 packet in flight 8))
1043 *
1044 * These 6 states form finite state machine, controlled by the following events:
1045 * 1. New ACK (+SACK) arrives. (tcp_sacktag_write_queue())
1046 * 2. Retransmission. (tcp_retransmit_skb(), tcp_xmit_retransmit_queue())
974c1236 1047 * 3. Loss detection event of two flavors:
1da177e4
LT
1048 * A. Scoreboard estimator decided the packet is lost.
1049 * A'. Reno "three dupacks" marks head of queue lost.
974c1236
YC
1050 * A''. Its FACK modification, head until snd.fack is lost.
1051 * B. SACK arrives sacking SND.NXT at the moment, when the
1da177e4
LT
1052 * segment was retransmitted.
1053 * 4. D-SACK added new rule: D-SACK changes any tag to S.
1054 *
1055 * It is pleasant to note, that state diagram turns out to be commutative,
1056 * so that we are allowed not to be bothered by order of our actions,
1057 * when multiple events arrive simultaneously. (see the function below).
1058 *
1059 * Reordering detection.
1060 * --------------------
1061 * Reordering metric is maximal distance, which a packet can be displaced
1062 * in packet stream. With SACKs we can estimate it:
1063 *
1064 * 1. SACK fills old hole and the corresponding segment was not
1065 * ever retransmitted -> reordering. Alas, we cannot use it
1066 * when segment was retransmitted.
1067 * 2. The last flaw is solved with D-SACK. D-SACK arrives
1068 * for retransmitted and already SACKed segment -> reordering..
1069 * Both of these heuristics are not used in Loss state, when we cannot
1070 * account for retransmits accurately.
5b3c9882
IJ
1071 *
1072 * SACK block validation.
1073 * ----------------------
1074 *
1075 * SACK block range validation checks that the received SACK block fits to
1076 * the expected sequence limits, i.e., it is between SND.UNA and SND.NXT.
1077 * Note that SND.UNA is not included to the range though being valid because
0e835331
IJ
1078 * it means that the receiver is rather inconsistent with itself reporting
1079 * SACK reneging when it should advance SND.UNA. Such SACK block this is
1080 * perfectly valid, however, in light of RFC2018 which explicitly states
1081 * that "SACK block MUST reflect the newest segment. Even if the newest
1082 * segment is going to be discarded ...", not that it looks very clever
1083 * in case of head skb. Due to potentional receiver driven attacks, we
1084 * choose to avoid immediate execution of a walk in write queue due to
1085 * reneging and defer head skb's loss recovery to standard loss recovery
1086 * procedure that will eventually trigger (nothing forbids us doing this).
5b3c9882
IJ
1087 *
1088 * Implements also blockage to start_seq wrap-around. Problem lies in the
1089 * fact that though start_seq (s) is before end_seq (i.e., not reversed),
1090 * there's no guarantee that it will be before snd_nxt (n). The problem
1091 * happens when start_seq resides between end_seq wrap (e_w) and snd_nxt
1092 * wrap (s_w):
1093 *
1094 * <- outs wnd -> <- wrapzone ->
1095 * u e n u_w e_w s n_w
1096 * | | | | | | |
1097 * |<------------+------+----- TCP seqno space --------------+---------->|
1098 * ...-- <2^31 ->| |<--------...
1099 * ...---- >2^31 ------>| |<--------...
1100 *
1101 * Current code wouldn't be vulnerable but it's better still to discard such
1102 * crazy SACK blocks. Doing this check for start_seq alone closes somewhat
1103 * similar case (end_seq after snd_nxt wrap) as earlier reversed check in
1104 * snd_nxt wrap -> snd_una region will then become "well defined", i.e.,
1105 * equal to the ideal case (infinite seqno space without wrap caused issues).
1106 *
1107 * With D-SACK the lower bound is extended to cover sequence space below
1108 * SND.UNA down to undo_marker, which is the last point of interest. Yet
564262c1 1109 * again, D-SACK block must not to go across snd_una (for the same reason as
5b3c9882
IJ
1110 * for the normal SACK blocks, explained above). But there all simplicity
1111 * ends, TCP might receive valid D-SACKs below that. As long as they reside
1112 * fully below undo_marker they do not affect behavior in anyway and can
1113 * therefore be safely ignored. In rare cases (which are more or less
1114 * theoretical ones), the D-SACK will nicely cross that boundary due to skb
1115 * fragmentation and packet reordering past skb's retransmission. To consider
1116 * them correctly, the acceptable range must be extended even more though
1117 * the exact amount is rather hard to quantify. However, tp->max_window can
1118 * be used as an exaggerated estimate.
1da177e4 1119 */
5b3c9882
IJ
1120static int tcp_is_sackblock_valid(struct tcp_sock *tp, int is_dsack,
1121 u32 start_seq, u32 end_seq)
1122{
1123 /* Too far in future, or reversed (interpretation is ambiguous) */
1124 if (after(end_seq, tp->snd_nxt) || !before(start_seq, end_seq))
1125 return 0;
1126
1127 /* Nasty start_seq wrap-around check (see comments above) */
1128 if (!before(start_seq, tp->snd_nxt))
1129 return 0;
1130
564262c1 1131 /* In outstanding window? ...This is valid exit for D-SACKs too.
5b3c9882
IJ
1132 * start_seq == snd_una is non-sensical (see comments above)
1133 */
1134 if (after(start_seq, tp->snd_una))
1135 return 1;
1136
1137 if (!is_dsack || !tp->undo_marker)
1138 return 0;
1139
1140 /* ...Then it's D-SACK, and must reside below snd_una completely */
f779b2d6 1141 if (after(end_seq, tp->snd_una))
5b3c9882
IJ
1142 return 0;
1143
1144 if (!before(start_seq, tp->undo_marker))
1145 return 1;
1146
1147 /* Too old */
1148 if (!after(end_seq, tp->undo_marker))
1149 return 0;
1150
1151 /* Undo_marker boundary crossing (overestimates a lot). Known already:
1152 * start_seq < undo_marker and end_seq >= undo_marker.
1153 */
1154 return !before(start_seq, end_seq - tp->max_window);
1155}
1156
1c1e87ed 1157/* Check for lost retransmit. This superb idea is borrowed from "ratehalving".
974c1236 1158 * Event "B". Later note: FACK people cheated me again 8), we have to account
1c1e87ed 1159 * for reordering! Ugly, but should help.
f785a8e2
IJ
1160 *
1161 * Search retransmitted skbs from write_queue that were sent when snd_nxt was
1162 * less than what is now known to be received by the other end (derived from
9f58f3b7
IJ
1163 * highest SACK block). Also calculate the lowest snd_nxt among the remaining
1164 * retransmitted skbs to avoid some costly processing per ACKs.
1c1e87ed 1165 */
407ef1de 1166static void tcp_mark_lost_retrans(struct sock *sk)
1c1e87ed 1167{
9f58f3b7 1168 const struct inet_connection_sock *icsk = inet_csk(sk);
1c1e87ed
IJ
1169 struct tcp_sock *tp = tcp_sk(sk);
1170 struct sk_buff *skb;
f785a8e2 1171 int cnt = 0;
df2e014b 1172 u32 new_low_seq = tp->snd_nxt;
6859d494 1173 u32 received_upto = tcp_highest_sack_seq(tp);
9f58f3b7
IJ
1174
1175 if (!tcp_is_fack(tp) || !tp->retrans_out ||
1176 !after(received_upto, tp->lost_retrans_low) ||
1177 icsk->icsk_ca_state != TCP_CA_Recovery)
407ef1de 1178 return;
1c1e87ed
IJ
1179
1180 tcp_for_write_queue(skb, sk) {
1181 u32 ack_seq = TCP_SKB_CB(skb)->ack_seq;
1182
1183 if (skb == tcp_send_head(sk))
1184 break;
f785a8e2 1185 if (cnt == tp->retrans_out)
1c1e87ed
IJ
1186 break;
1187 if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una))
1188 continue;
1189
f785a8e2
IJ
1190 if (!(TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS))
1191 continue;
1192
d0af4160
IJ
1193 /* TODO: We would like to get rid of tcp_is_fack(tp) only
1194 * constraint here (see above) but figuring out that at
1195 * least tp->reordering SACK blocks reside between ack_seq
1196 * and received_upto is not easy task to do cheaply with
1197 * the available datastructures.
1198 *
1199 * Whether FACK should check here for tp->reordering segs
1200 * in-between one could argue for either way (it would be
1201 * rather simple to implement as we could count fack_count
1202 * during the walk and do tp->fackets_out - fack_count).
1203 */
1204 if (after(received_upto, ack_seq)) {
1c1e87ed
IJ
1205 TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
1206 tp->retrans_out -= tcp_skb_pcount(skb);
1207
006f582c 1208 tcp_skb_mark_lost_uncond_verify(tp, skb);
de0744af 1209 NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPLOSTRETRANSMIT);
f785a8e2 1210 } else {
df2e014b 1211 if (before(ack_seq, new_low_seq))
b08d6cb2 1212 new_low_seq = ack_seq;
f785a8e2 1213 cnt += tcp_skb_pcount(skb);
1c1e87ed
IJ
1214 }
1215 }
b08d6cb2
IJ
1216
1217 if (tp->retrans_out)
1218 tp->lost_retrans_low = new_low_seq;
1c1e87ed 1219}
5b3c9882 1220
cf533ea5 1221static int tcp_check_dsack(struct sock *sk, const struct sk_buff *ack_skb,
d06e021d
DM
1222 struct tcp_sack_block_wire *sp, int num_sacks,
1223 u32 prior_snd_una)
1224{
1ed83465 1225 struct tcp_sock *tp = tcp_sk(sk);
d3e2ce3b
HH
1226 u32 start_seq_0 = get_unaligned_be32(&sp[0].start_seq);
1227 u32 end_seq_0 = get_unaligned_be32(&sp[0].end_seq);
d06e021d
DM
1228 int dup_sack = 0;
1229
1230 if (before(start_seq_0, TCP_SKB_CB(ack_skb)->ack_seq)) {
1231 dup_sack = 1;
e60402d0 1232 tcp_dsack_seen(tp);
de0744af 1233 NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPDSACKRECV);
d06e021d 1234 } else if (num_sacks > 1) {
d3e2ce3b
HH
1235 u32 end_seq_1 = get_unaligned_be32(&sp[1].end_seq);
1236 u32 start_seq_1 = get_unaligned_be32(&sp[1].start_seq);
d06e021d
DM
1237
1238 if (!after(end_seq_0, end_seq_1) &&
1239 !before(start_seq_0, start_seq_1)) {
1240 dup_sack = 1;
e60402d0 1241 tcp_dsack_seen(tp);
de0744af
PE
1242 NET_INC_STATS_BH(sock_net(sk),
1243 LINUX_MIB_TCPDSACKOFORECV);
d06e021d
DM
1244 }
1245 }
1246
1247 /* D-SACK for already forgotten data... Do dumb counting. */
c24f691b 1248 if (dup_sack && tp->undo_marker && tp->undo_retrans &&
d06e021d
DM
1249 !after(end_seq_0, prior_snd_una) &&
1250 after(end_seq_0, tp->undo_marker))
1251 tp->undo_retrans--;
1252
1253 return dup_sack;
1254}
1255
a1197f5a
IJ
1256struct tcp_sacktag_state {
1257 int reord;
1258 int fack_count;
1259 int flag;
1260};
1261
d1935942
IJ
1262/* Check if skb is fully within the SACK block. In presence of GSO skbs,
1263 * the incoming SACK may not exactly match but we can find smaller MSS
1264 * aligned portion of it that matches. Therefore we might need to fragment
1265 * which may fail and creates some hassle (caller must handle error case
1266 * returns).
832d11c5
IJ
1267 *
1268 * FIXME: this could be merged to shift decision code
d1935942 1269 */
0f79efdc
AB
1270static int tcp_match_skb_to_sack(struct sock *sk, struct sk_buff *skb,
1271 u32 start_seq, u32 end_seq)
d1935942
IJ
1272{
1273 int in_sack, err;
1274 unsigned int pkt_len;
adb92db8 1275 unsigned int mss;
d1935942
IJ
1276
1277 in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
1278 !before(end_seq, TCP_SKB_CB(skb)->end_seq);
1279
1280 if (tcp_skb_pcount(skb) > 1 && !in_sack &&
1281 after(TCP_SKB_CB(skb)->end_seq, start_seq)) {
adb92db8 1282 mss = tcp_skb_mss(skb);
d1935942
IJ
1283 in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq);
1284
adb92db8 1285 if (!in_sack) {
d1935942 1286 pkt_len = start_seq - TCP_SKB_CB(skb)->seq;
adb92db8
IJ
1287 if (pkt_len < mss)
1288 pkt_len = mss;
1289 } else {
d1935942 1290 pkt_len = end_seq - TCP_SKB_CB(skb)->seq;
adb92db8
IJ
1291 if (pkt_len < mss)
1292 return -EINVAL;
1293 }
1294
1295 /* Round if necessary so that SACKs cover only full MSSes
1296 * and/or the remaining small portion (if present)
1297 */
1298 if (pkt_len > mss) {
1299 unsigned int new_len = (pkt_len / mss) * mss;
1300 if (!in_sack && new_len < pkt_len) {
1301 new_len += mss;
1302 if (new_len > skb->len)
1303 return 0;
1304 }
1305 pkt_len = new_len;
1306 }
1307 err = tcp_fragment(sk, skb, pkt_len, mss);
d1935942
IJ
1308 if (err < 0)
1309 return err;
1310 }
1311
1312 return in_sack;
1313}
1314
cc9a672e
NC
1315/* Mark the given newly-SACKed range as such, adjusting counters and hints. */
1316static u8 tcp_sacktag_one(struct sock *sk,
1317 struct tcp_sacktag_state *state, u8 sacked,
1318 u32 start_seq, u32 end_seq,
a1197f5a 1319 int dup_sack, int pcount)
9e10c47c 1320{
6859d494 1321 struct tcp_sock *tp = tcp_sk(sk);
a1197f5a 1322 int fack_count = state->fack_count;
9e10c47c
IJ
1323
1324 /* Account D-SACK for retransmitted packet. */
1325 if (dup_sack && (sacked & TCPCB_RETRANS)) {
c24f691b 1326 if (tp->undo_marker && tp->undo_retrans &&
cc9a672e 1327 after(end_seq, tp->undo_marker))
9e10c47c 1328 tp->undo_retrans--;
ede9f3b1 1329 if (sacked & TCPCB_SACKED_ACKED)
a1197f5a 1330 state->reord = min(fack_count, state->reord);
9e10c47c
IJ
1331 }
1332
1333 /* Nothing to do; acked frame is about to be dropped (was ACKed). */
cc9a672e 1334 if (!after(end_seq, tp->snd_una))
a1197f5a 1335 return sacked;
9e10c47c
IJ
1336
1337 if (!(sacked & TCPCB_SACKED_ACKED)) {
1338 if (sacked & TCPCB_SACKED_RETRANS) {
1339 /* If the segment is not tagged as lost,
1340 * we do not clear RETRANS, believing
1341 * that retransmission is still in flight.
1342 */
1343 if (sacked & TCPCB_LOST) {
a1197f5a 1344 sacked &= ~(TCPCB_LOST|TCPCB_SACKED_RETRANS);
f58b22fd
IJ
1345 tp->lost_out -= pcount;
1346 tp->retrans_out -= pcount;
9e10c47c
IJ
1347 }
1348 } else {
1349 if (!(sacked & TCPCB_RETRANS)) {
1350 /* New sack for not retransmitted frame,
1351 * which was in hole. It is reordering.
1352 */
cc9a672e 1353 if (before(start_seq,
9e10c47c 1354 tcp_highest_sack_seq(tp)))
a1197f5a
IJ
1355 state->reord = min(fack_count,
1356 state->reord);
9e10c47c
IJ
1357
1358 /* SACK enhanced F-RTO (RFC4138; Appendix B) */
cc9a672e 1359 if (!after(end_seq, tp->frto_highmark))
a1197f5a 1360 state->flag |= FLAG_ONLY_ORIG_SACKED;
9e10c47c
IJ
1361 }
1362
1363 if (sacked & TCPCB_LOST) {
a1197f5a 1364 sacked &= ~TCPCB_LOST;
f58b22fd 1365 tp->lost_out -= pcount;
9e10c47c
IJ
1366 }
1367 }
1368
a1197f5a
IJ
1369 sacked |= TCPCB_SACKED_ACKED;
1370 state->flag |= FLAG_DATA_SACKED;
f58b22fd 1371 tp->sacked_out += pcount;
9e10c47c 1372
f58b22fd 1373 fack_count += pcount;
9e10c47c
IJ
1374
1375 /* Lost marker hint past SACKed? Tweak RFC3517 cnt */
1376 if (!tcp_is_fack(tp) && (tp->lost_skb_hint != NULL) &&
cc9a672e 1377 before(start_seq, TCP_SKB_CB(tp->lost_skb_hint)->seq))
f58b22fd 1378 tp->lost_cnt_hint += pcount;
9e10c47c
IJ
1379
1380 if (fack_count > tp->fackets_out)
1381 tp->fackets_out = fack_count;
9e10c47c
IJ
1382 }
1383
1384 /* D-SACK. We can detect redundant retransmission in S|R and plain R
1385 * frames and clear it. undo_retrans is decreased above, L|R frames
1386 * are accounted above as well.
1387 */
a1197f5a
IJ
1388 if (dup_sack && (sacked & TCPCB_SACKED_RETRANS)) {
1389 sacked &= ~TCPCB_SACKED_RETRANS;
f58b22fd 1390 tp->retrans_out -= pcount;
9e10c47c
IJ
1391 }
1392
a1197f5a 1393 return sacked;
9e10c47c
IJ
1394}
1395
daef52ba
NC
1396/* Shift newly-SACKed bytes from this skb to the immediately previous
1397 * already-SACKed sk_buff. Mark the newly-SACKed bytes as such.
1398 */
50133161 1399static int tcp_shifted_skb(struct sock *sk, struct sk_buff *skb,
a1197f5a 1400 struct tcp_sacktag_state *state,
9ec06ff5
IJ
1401 unsigned int pcount, int shifted, int mss,
1402 int dup_sack)
832d11c5
IJ
1403{
1404 struct tcp_sock *tp = tcp_sk(sk);
50133161 1405 struct sk_buff *prev = tcp_write_queue_prev(sk, skb);
daef52ba
NC
1406 u32 start_seq = TCP_SKB_CB(skb)->seq; /* start of newly-SACKed */
1407 u32 end_seq = start_seq + shifted; /* end of newly-SACKed */
832d11c5
IJ
1408
1409 BUG_ON(!pcount);
1410
4c90d3b3
NC
1411 /* Adjust counters and hints for the newly sacked sequence
1412 * range but discard the return value since prev is already
1413 * marked. We must tag the range first because the seq
1414 * advancement below implicitly advances
1415 * tcp_highest_sack_seq() when skb is highest_sack.
1416 */
1417 tcp_sacktag_one(sk, state, TCP_SKB_CB(skb)->sacked,
1418 start_seq, end_seq, dup_sack, pcount);
1419
1420 if (skb == tp->lost_skb_hint)
0af2a0d0
NC
1421 tp->lost_cnt_hint += pcount;
1422
832d11c5
IJ
1423 TCP_SKB_CB(prev)->end_seq += shifted;
1424 TCP_SKB_CB(skb)->seq += shifted;
1425
1426 skb_shinfo(prev)->gso_segs += pcount;
1427 BUG_ON(skb_shinfo(skb)->gso_segs < pcount);
1428 skb_shinfo(skb)->gso_segs -= pcount;
1429
1430 /* When we're adding to gso_segs == 1, gso_size will be zero,
1431 * in theory this shouldn't be necessary but as long as DSACK
1432 * code can come after this skb later on it's better to keep
1433 * setting gso_size to something.
1434 */
1435 if (!skb_shinfo(prev)->gso_size) {
1436 skb_shinfo(prev)->gso_size = mss;
1437 skb_shinfo(prev)->gso_type = sk->sk_gso_type;
1438 }
1439
1440 /* CHECKME: To clear or not to clear? Mimics normal skb currently */
1441 if (skb_shinfo(skb)->gso_segs <= 1) {
1442 skb_shinfo(skb)->gso_size = 0;
1443 skb_shinfo(skb)->gso_type = 0;
1444 }
1445
832d11c5
IJ
1446 /* Difference in this won't matter, both ACKed by the same cumul. ACK */
1447 TCP_SKB_CB(prev)->sacked |= (TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS);
1448
832d11c5
IJ
1449 if (skb->len > 0) {
1450 BUG_ON(!tcp_skb_pcount(skb));
111cc8b9 1451 NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SACKSHIFTED);
832d11c5
IJ
1452 return 0;
1453 }
1454
1455 /* Whole SKB was eaten :-) */
1456
92ee76b6
IJ
1457 if (skb == tp->retransmit_skb_hint)
1458 tp->retransmit_skb_hint = prev;
1459 if (skb == tp->scoreboard_skb_hint)
1460 tp->scoreboard_skb_hint = prev;
1461 if (skb == tp->lost_skb_hint) {
1462 tp->lost_skb_hint = prev;
1463 tp->lost_cnt_hint -= tcp_skb_pcount(prev);
1464 }
1465
4de075e0 1466 TCP_SKB_CB(skb)->tcp_flags |= TCP_SKB_CB(prev)->tcp_flags;
832d11c5
IJ
1467 if (skb == tcp_highest_sack(sk))
1468 tcp_advance_highest_sack(sk, skb);
1469
1470 tcp_unlink_write_queue(skb, sk);
1471 sk_wmem_free_skb(sk, skb);
1472
111cc8b9
IJ
1473 NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SACKMERGED);
1474
832d11c5
IJ
1475 return 1;
1476}
1477
1478/* I wish gso_size would have a bit more sane initialization than
1479 * something-or-zero which complicates things
1480 */
cf533ea5 1481static int tcp_skb_seglen(const struct sk_buff *skb)
832d11c5 1482{
775ffabf 1483 return tcp_skb_pcount(skb) == 1 ? skb->len : tcp_skb_mss(skb);
832d11c5
IJ
1484}
1485
1486/* Shifting pages past head area doesn't work */
cf533ea5 1487static int skb_can_shift(const struct sk_buff *skb)
832d11c5
IJ
1488{
1489 return !skb_headlen(skb) && skb_is_nonlinear(skb);
1490}
1491
1492/* Try collapsing SACK blocks spanning across multiple skbs to a single
1493 * skb.
1494 */
1495static struct sk_buff *tcp_shift_skb_data(struct sock *sk, struct sk_buff *skb,
a1197f5a 1496 struct tcp_sacktag_state *state,
832d11c5 1497 u32 start_seq, u32 end_seq,
a1197f5a 1498 int dup_sack)
832d11c5
IJ
1499{
1500 struct tcp_sock *tp = tcp_sk(sk);
1501 struct sk_buff *prev;
1502 int mss;
1503 int pcount = 0;
1504 int len;
1505 int in_sack;
1506
1507 if (!sk_can_gso(sk))
1508 goto fallback;
1509
1510 /* Normally R but no L won't result in plain S */
1511 if (!dup_sack &&
9969ca5f 1512 (TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_RETRANS)) == TCPCB_SACKED_RETRANS)
832d11c5
IJ
1513 goto fallback;
1514 if (!skb_can_shift(skb))
1515 goto fallback;
1516 /* This frame is about to be dropped (was ACKed). */
1517 if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una))
1518 goto fallback;
1519
1520 /* Can only happen with delayed DSACK + discard craziness */
1521 if (unlikely(skb == tcp_write_queue_head(sk)))
1522 goto fallback;
1523 prev = tcp_write_queue_prev(sk, skb);
1524
1525 if ((TCP_SKB_CB(prev)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED)
1526 goto fallback;
1527
1528 in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
1529 !before(end_seq, TCP_SKB_CB(skb)->end_seq);
1530
1531 if (in_sack) {
1532 len = skb->len;
1533 pcount = tcp_skb_pcount(skb);
775ffabf 1534 mss = tcp_skb_seglen(skb);
832d11c5
IJ
1535
1536 /* TODO: Fix DSACKs to not fragment already SACKed and we can
1537 * drop this restriction as unnecessary
1538 */
775ffabf 1539 if (mss != tcp_skb_seglen(prev))
832d11c5
IJ
1540 goto fallback;
1541 } else {
1542 if (!after(TCP_SKB_CB(skb)->end_seq, start_seq))
1543 goto noop;
1544 /* CHECKME: This is non-MSS split case only?, this will
1545 * cause skipped skbs due to advancing loop btw, original
1546 * has that feature too
1547 */
1548 if (tcp_skb_pcount(skb) <= 1)
1549 goto noop;
1550
1551 in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq);
1552 if (!in_sack) {
1553 /* TODO: head merge to next could be attempted here
1554 * if (!after(TCP_SKB_CB(skb)->end_seq, end_seq)),
1555 * though it might not be worth of the additional hassle
1556 *
1557 * ...we can probably just fallback to what was done
1558 * previously. We could try merging non-SACKed ones
1559 * as well but it probably isn't going to buy off
1560 * because later SACKs might again split them, and
1561 * it would make skb timestamp tracking considerably
1562 * harder problem.
1563 */
1564 goto fallback;
1565 }
1566
1567 len = end_seq - TCP_SKB_CB(skb)->seq;
1568 BUG_ON(len < 0);
1569 BUG_ON(len > skb->len);
1570
1571 /* MSS boundaries should be honoured or else pcount will
1572 * severely break even though it makes things bit trickier.
1573 * Optimize common case to avoid most of the divides
1574 */
1575 mss = tcp_skb_mss(skb);
1576
1577 /* TODO: Fix DSACKs to not fragment already SACKed and we can
1578 * drop this restriction as unnecessary
1579 */
775ffabf 1580 if (mss != tcp_skb_seglen(prev))
832d11c5
IJ
1581 goto fallback;
1582
1583 if (len == mss) {
1584 pcount = 1;
1585 } else if (len < mss) {
1586 goto noop;
1587 } else {
1588 pcount = len / mss;
1589 len = pcount * mss;
1590 }
1591 }
1592
4648dc97
NC
1593 /* tcp_sacktag_one() won't SACK-tag ranges below snd_una */
1594 if (!after(TCP_SKB_CB(skb)->seq + len, tp->snd_una))
1595 goto fallback;
1596
832d11c5
IJ
1597 if (!skb_shift(prev, skb, len))
1598 goto fallback;
9ec06ff5 1599 if (!tcp_shifted_skb(sk, skb, state, pcount, len, mss, dup_sack))
832d11c5
IJ
1600 goto out;
1601
1602 /* Hole filled allows collapsing with the next as well, this is very
1603 * useful when hole on every nth skb pattern happens
1604 */
1605 if (prev == tcp_write_queue_tail(sk))
1606 goto out;
1607 skb = tcp_write_queue_next(sk, prev);
1608
f0bc52f3
IJ
1609 if (!skb_can_shift(skb) ||
1610 (skb == tcp_send_head(sk)) ||
1611 ((TCP_SKB_CB(skb)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED) ||
775ffabf 1612 (mss != tcp_skb_seglen(skb)))
832d11c5
IJ
1613 goto out;
1614
1615 len = skb->len;
1616 if (skb_shift(prev, skb, len)) {
1617 pcount += tcp_skb_pcount(skb);
9ec06ff5 1618 tcp_shifted_skb(sk, skb, state, tcp_skb_pcount(skb), len, mss, 0);
832d11c5
IJ
1619 }
1620
1621out:
a1197f5a 1622 state->fack_count += pcount;
832d11c5
IJ
1623 return prev;
1624
1625noop:
1626 return skb;
1627
1628fallback:
111cc8b9 1629 NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SACKSHIFTFALLBACK);
832d11c5
IJ
1630 return NULL;
1631}
1632
68f8353b
IJ
1633static struct sk_buff *tcp_sacktag_walk(struct sk_buff *skb, struct sock *sk,
1634 struct tcp_sack_block *next_dup,
a1197f5a 1635 struct tcp_sacktag_state *state,
68f8353b 1636 u32 start_seq, u32 end_seq,
a1197f5a 1637 int dup_sack_in)
68f8353b 1638{
832d11c5
IJ
1639 struct tcp_sock *tp = tcp_sk(sk);
1640 struct sk_buff *tmp;
1641
68f8353b
IJ
1642 tcp_for_write_queue_from(skb, sk) {
1643 int in_sack = 0;
1644 int dup_sack = dup_sack_in;
1645
1646 if (skb == tcp_send_head(sk))
1647 break;
1648
1649 /* queue is in-order => we can short-circuit the walk early */
1650 if (!before(TCP_SKB_CB(skb)->seq, end_seq))
1651 break;
1652
1653 if ((next_dup != NULL) &&
1654 before(TCP_SKB_CB(skb)->seq, next_dup->end_seq)) {
1655 in_sack = tcp_match_skb_to_sack(sk, skb,
1656 next_dup->start_seq,
1657 next_dup->end_seq);
1658 if (in_sack > 0)
1659 dup_sack = 1;
1660 }
1661
832d11c5
IJ
1662 /* skb reference here is a bit tricky to get right, since
1663 * shifting can eat and free both this skb and the next,
1664 * so not even _safe variant of the loop is enough.
1665 */
1666 if (in_sack <= 0) {
a1197f5a
IJ
1667 tmp = tcp_shift_skb_data(sk, skb, state,
1668 start_seq, end_seq, dup_sack);
832d11c5
IJ
1669 if (tmp != NULL) {
1670 if (tmp != skb) {
1671 skb = tmp;
1672 continue;
1673 }
1674
1675 in_sack = 0;
1676 } else {
1677 in_sack = tcp_match_skb_to_sack(sk, skb,
1678 start_seq,
1679 end_seq);
1680 }
1681 }
1682
68f8353b
IJ
1683 if (unlikely(in_sack < 0))
1684 break;
1685
832d11c5 1686 if (in_sack) {
cc9a672e
NC
1687 TCP_SKB_CB(skb)->sacked =
1688 tcp_sacktag_one(sk,
1689 state,
1690 TCP_SKB_CB(skb)->sacked,
1691 TCP_SKB_CB(skb)->seq,
1692 TCP_SKB_CB(skb)->end_seq,
1693 dup_sack,
1694 tcp_skb_pcount(skb));
68f8353b 1695
832d11c5
IJ
1696 if (!before(TCP_SKB_CB(skb)->seq,
1697 tcp_highest_sack_seq(tp)))
1698 tcp_advance_highest_sack(sk, skb);
1699 }
1700
a1197f5a 1701 state->fack_count += tcp_skb_pcount(skb);
68f8353b
IJ
1702 }
1703 return skb;
1704}
1705
1706/* Avoid all extra work that is being done by sacktag while walking in
1707 * a normal way
1708 */
1709static struct sk_buff *tcp_sacktag_skip(struct sk_buff *skb, struct sock *sk,
a1197f5a
IJ
1710 struct tcp_sacktag_state *state,
1711 u32 skip_to_seq)
68f8353b
IJ
1712{
1713 tcp_for_write_queue_from(skb, sk) {
1714 if (skb == tcp_send_head(sk))
1715 break;
1716
e8bae275 1717 if (after(TCP_SKB_CB(skb)->end_seq, skip_to_seq))
68f8353b 1718 break;
d152a7d8 1719
a1197f5a 1720 state->fack_count += tcp_skb_pcount(skb);
68f8353b
IJ
1721 }
1722 return skb;
1723}
1724
1725static struct sk_buff *tcp_maybe_skipping_dsack(struct sk_buff *skb,
1726 struct sock *sk,
1727 struct tcp_sack_block *next_dup,
a1197f5a
IJ
1728 struct tcp_sacktag_state *state,
1729 u32 skip_to_seq)
68f8353b
IJ
1730{
1731 if (next_dup == NULL)
1732 return skb;
1733
1734 if (before(next_dup->start_seq, skip_to_seq)) {
a1197f5a
IJ
1735 skb = tcp_sacktag_skip(skb, sk, state, next_dup->start_seq);
1736 skb = tcp_sacktag_walk(skb, sk, NULL, state,
1737 next_dup->start_seq, next_dup->end_seq,
1738 1);
68f8353b
IJ
1739 }
1740
1741 return skb;
1742}
1743
cf533ea5 1744static int tcp_sack_cache_ok(const struct tcp_sock *tp, const struct tcp_sack_block *cache)
68f8353b
IJ
1745{
1746 return cache < tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache);
1747}
1748
1da177e4 1749static int
cf533ea5 1750tcp_sacktag_write_queue(struct sock *sk, const struct sk_buff *ack_skb,
056834d9 1751 u32 prior_snd_una)
1da177e4 1752{
6687e988 1753 const struct inet_connection_sock *icsk = inet_csk(sk);
1da177e4 1754 struct tcp_sock *tp = tcp_sk(sk);
cf533ea5
ED
1755 const unsigned char *ptr = (skb_transport_header(ack_skb) +
1756 TCP_SKB_CB(ack_skb)->sacked);
fd6dad61 1757 struct tcp_sack_block_wire *sp_wire = (struct tcp_sack_block_wire *)(ptr+2);
4389dded 1758 struct tcp_sack_block sp[TCP_NUM_SACKS];
68f8353b 1759 struct tcp_sack_block *cache;
a1197f5a 1760 struct tcp_sacktag_state state;
68f8353b 1761 struct sk_buff *skb;
4389dded 1762 int num_sacks = min(TCP_NUM_SACKS, (ptr[1] - TCPOLEN_SACK_BASE) >> 3);
fd6dad61 1763 int used_sacks;
7769f406 1764 int found_dup_sack = 0;
68f8353b 1765 int i, j;
fda03fbb 1766 int first_sack_index;
1da177e4 1767
a1197f5a
IJ
1768 state.flag = 0;
1769 state.reord = tp->packets_out;
1770
d738cd8f 1771 if (!tp->sacked_out) {
de83c058
IJ
1772 if (WARN_ON(tp->fackets_out))
1773 tp->fackets_out = 0;
6859d494 1774 tcp_highest_sack_reset(sk);
d738cd8f 1775 }
1da177e4 1776
1ed83465 1777 found_dup_sack = tcp_check_dsack(sk, ack_skb, sp_wire,
d06e021d
DM
1778 num_sacks, prior_snd_una);
1779 if (found_dup_sack)
a1197f5a 1780 state.flag |= FLAG_DSACKING_ACK;
6f74651a
BE
1781
1782 /* Eliminate too old ACKs, but take into
1783 * account more or less fresh ones, they can
1784 * contain valid SACK info.
1785 */
1786 if (before(TCP_SKB_CB(ack_skb)->ack_seq, prior_snd_una - tp->max_window))
1787 return 0;
1788