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