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