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.
6 * Implementation of the Transmission Control Protocol(TCP).
8 * Version: $Id: tcp_input.c,v 1.243 2002/02/01 22:01:04 davem Exp $
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>
25 * Pedro Roque : Fast Retransmit/Recovery.
27 * Retransmit queue handled by TCP.
28 * Better retransmit timer handling.
29 * New congestion avoidance.
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.
45 * Andrey Savochkin: Fix RTT measurements in the presence of
47 * Andrey Savochkin: Check sequence numbers correctly when
48 * removing SACKs due to in sequence incoming
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.
53 * Andi Kleen: Add tcp_measure_rcv_mss to make
54 * connections with MSS<min(MTU,ann. MSS)
55 * work without delayed acks.
56 * Andi Kleen: Process packets with PSH set in the
58 * J Hadi Salim: ECN support
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
67 #include <linux/module.h>
68 #include <linux/sysctl.h>
70 #include <net/inet_common.h>
71 #include <linux/ipsec.h>
72 #include <asm/unaligned.h>
73 #include <net/netdma.h>
75 int sysctl_tcp_timestamps __read_mostly = 1;
76 int sysctl_tcp_window_scaling __read_mostly = 1;
77 int sysctl_tcp_sack __read_mostly = 1;
78 int sysctl_tcp_fack __read_mostly = 1;
79 int sysctl_tcp_reordering __read_mostly = TCP_FASTRETRANS_THRESH;
80 int sysctl_tcp_ecn __read_mostly;
81 int sysctl_tcp_dsack __read_mostly = 1;
82 int sysctl_tcp_app_win __read_mostly = 31;
83 int sysctl_tcp_adv_win_scale __read_mostly = 2;
85 int sysctl_tcp_stdurg __read_mostly;
86 int sysctl_tcp_rfc1337 __read_mostly;
87 int sysctl_tcp_max_orphans __read_mostly = NR_FILE;
88 int sysctl_tcp_frto __read_mostly = 2;
89 int sysctl_tcp_frto_response __read_mostly;
90 int sysctl_tcp_nometrics_save __read_mostly;
92 int sysctl_tcp_moderate_rcvbuf __read_mostly = 1;
93 int sysctl_tcp_abc __read_mostly;
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.*/
104 #define FLAG_ONLY_ORIG_SACKED 0x200 /* SACKs only non-rexmit sent before RTO */
105 #define FLAG_SND_UNA_ADVANCED 0x400 /* Snd_una was changed (!= FLAG_DATA_ACKED) */
106 #define FLAG_DSACKING_ACK 0x800 /* SACK blocks contained D-SACK info */
107 #define FLAG_NONHEAD_RETRANS_ACKED 0x1000 /* Non-head rexmitted data was ACKed */
108 #define FLAG_SACK_RENEGING 0x2000 /* snd_una advanced to a sacked seq */
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)
114 #define FLAG_ANY_PROGRESS (FLAG_FORWARD_PROGRESS|FLAG_SND_UNA_ADVANCED)
116 #define IsSackFrto() (sysctl_tcp_frto == 0x2)
118 #define TCP_REMNANT (TCP_FLAG_FIN|TCP_FLAG_URG|TCP_FLAG_SYN|TCP_FLAG_PSH)
119 #define TCP_HP_BITS (~(TCP_RESERVED_BITS|TCP_FLAG_PSH))
121 /* Adapt the MSS value used to make delayed ack decision to the
124 static void tcp_measure_rcv_mss(struct sock *sk, const struct sk_buff *skb)
126 struct inet_connection_sock *icsk = inet_csk(sk);
127 const unsigned int lss = icsk->icsk_ack.last_seg_size;
130 icsk->icsk_ack.last_seg_size = 0;
132 /* skb->len may jitter because of SACKs, even if peer
133 * sends good full-sized frames.
135 len = skb_shinfo(skb)->gso_size ? : skb->len;
136 if (len >= icsk->icsk_ack.rcv_mss) {
137 icsk->icsk_ack.rcv_mss = len;
139 /* Otherwise, we make more careful check taking into account,
140 * that SACKs block is variable.
142 * "len" is invariant segment length, including TCP header.
144 len += skb->data - skb_transport_header(skb);
145 if (len >= TCP_MIN_RCVMSS + sizeof(struct tcphdr) ||
146 /* If PSH is not set, packet should be
147 * full sized, provided peer TCP is not badly broken.
148 * This observation (if it is correct 8)) allows
149 * to handle super-low mtu links fairly.
151 (len >= TCP_MIN_MSS + sizeof(struct tcphdr) &&
152 !(tcp_flag_word(tcp_hdr(skb)) & TCP_REMNANT))) {
153 /* Subtract also invariant (if peer is RFC compliant),
154 * tcp header plus fixed timestamp option length.
155 * Resulting "len" is MSS free of SACK jitter.
157 len -= tcp_sk(sk)->tcp_header_len;
158 icsk->icsk_ack.last_seg_size = len;
160 icsk->icsk_ack.rcv_mss = len;
164 if (icsk->icsk_ack.pending & ICSK_ACK_PUSHED)
165 icsk->icsk_ack.pending |= ICSK_ACK_PUSHED2;
166 icsk->icsk_ack.pending |= ICSK_ACK_PUSHED;
170 static void tcp_incr_quickack(struct sock *sk)
172 struct inet_connection_sock *icsk = inet_csk(sk);
173 unsigned quickacks = tcp_sk(sk)->rcv_wnd / (2 * icsk->icsk_ack.rcv_mss);
177 if (quickacks > icsk->icsk_ack.quick)
178 icsk->icsk_ack.quick = min(quickacks, TCP_MAX_QUICKACKS);
181 void tcp_enter_quickack_mode(struct sock *sk)
183 struct inet_connection_sock *icsk = inet_csk(sk);
184 tcp_incr_quickack(sk);
185 icsk->icsk_ack.pingpong = 0;
186 icsk->icsk_ack.ato = TCP_ATO_MIN;
189 /* Send ACKs quickly, if "quick" count is not exhausted
190 * and the session is not interactive.
193 static inline int tcp_in_quickack_mode(const struct sock *sk)
195 const struct inet_connection_sock *icsk = inet_csk(sk);
196 return icsk->icsk_ack.quick && !icsk->icsk_ack.pingpong;
199 static inline void TCP_ECN_queue_cwr(struct tcp_sock *tp)
201 if (tp->ecn_flags & TCP_ECN_OK)
202 tp->ecn_flags |= TCP_ECN_QUEUE_CWR;
205 static inline void TCP_ECN_accept_cwr(struct tcp_sock *tp, struct sk_buff *skb)
207 if (tcp_hdr(skb)->cwr)
208 tp->ecn_flags &= ~TCP_ECN_DEMAND_CWR;
211 static inline void TCP_ECN_withdraw_cwr(struct tcp_sock *tp)
213 tp->ecn_flags &= ~TCP_ECN_DEMAND_CWR;
216 static inline void TCP_ECN_check_ce(struct tcp_sock *tp, struct sk_buff *skb)
218 if (tp->ecn_flags & TCP_ECN_OK) {
219 if (INET_ECN_is_ce(TCP_SKB_CB(skb)->flags))
220 tp->ecn_flags |= TCP_ECN_DEMAND_CWR;
221 /* Funny extension: if ECT is not set on a segment,
222 * it is surely retransmit. It is not in ECN RFC,
223 * but Linux follows this rule. */
224 else if (INET_ECN_is_not_ect((TCP_SKB_CB(skb)->flags)))
225 tcp_enter_quickack_mode((struct sock *)tp);
229 static inline void TCP_ECN_rcv_synack(struct tcp_sock *tp, struct tcphdr *th)
231 if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || th->cwr))
232 tp->ecn_flags &= ~TCP_ECN_OK;
235 static inline void TCP_ECN_rcv_syn(struct tcp_sock *tp, struct tcphdr *th)
237 if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || !th->cwr))
238 tp->ecn_flags &= ~TCP_ECN_OK;
241 static inline int TCP_ECN_rcv_ecn_echo(struct tcp_sock *tp, struct tcphdr *th)
243 if (th->ece && !th->syn && (tp->ecn_flags & TCP_ECN_OK))
248 /* Buffer size and advertised window tuning.
250 * 1. Tuning sk->sk_sndbuf, when connection enters established state.
253 static void tcp_fixup_sndbuf(struct sock *sk)
255 int sndmem = tcp_sk(sk)->rx_opt.mss_clamp + MAX_TCP_HEADER + 16 +
256 sizeof(struct sk_buff);
258 if (sk->sk_sndbuf < 3 * sndmem)
259 sk->sk_sndbuf = min(3 * sndmem, sysctl_tcp_wmem[2]);
262 /* 2. Tuning advertised window (window_clamp, rcv_ssthresh)
264 * All tcp_full_space() is split to two parts: "network" buffer, allocated
265 * forward and advertised in receiver window (tp->rcv_wnd) and
266 * "application buffer", required to isolate scheduling/application
267 * latencies from network.
268 * window_clamp is maximal advertised window. It can be less than
269 * tcp_full_space(), in this case tcp_full_space() - window_clamp
270 * is reserved for "application" buffer. The less window_clamp is
271 * the smoother our behaviour from viewpoint of network, but the lower
272 * throughput and the higher sensitivity of the connection to losses. 8)
274 * rcv_ssthresh is more strict window_clamp used at "slow start"
275 * phase to predict further behaviour of this connection.
276 * It is used for two goals:
277 * - to enforce header prediction at sender, even when application
278 * requires some significant "application buffer". It is check #1.
279 * - to prevent pruning of receive queue because of misprediction
280 * of receiver window. Check #2.
282 * The scheme does not work when sender sends good segments opening
283 * window and then starts to feed us spaghetti. But it should work
284 * in common situations. Otherwise, we have to rely on queue collapsing.
287 /* Slow part of check#2. */
288 static int __tcp_grow_window(const struct sock *sk, const struct sk_buff *skb)
290 struct tcp_sock *tp = tcp_sk(sk);
292 int truesize = tcp_win_from_space(skb->truesize) >> 1;
293 int window = tcp_win_from_space(sysctl_tcp_rmem[2]) >> 1;
295 while (tp->rcv_ssthresh <= window) {
296 if (truesize <= skb->len)
297 return 2 * inet_csk(sk)->icsk_ack.rcv_mss;
305 static void tcp_grow_window(struct sock *sk, struct sk_buff *skb)
307 struct tcp_sock *tp = tcp_sk(sk);
310 if (tp->rcv_ssthresh < tp->window_clamp &&
311 (int)tp->rcv_ssthresh < tcp_space(sk) &&
312 !tcp_memory_pressure) {
315 /* Check #2. Increase window, if skb with such overhead
316 * will fit to rcvbuf in future.
318 if (tcp_win_from_space(skb->truesize) <= skb->len)
319 incr = 2 * tp->advmss;
321 incr = __tcp_grow_window(sk, skb);
324 tp->rcv_ssthresh = min(tp->rcv_ssthresh + incr,
326 inet_csk(sk)->icsk_ack.quick |= 1;
331 /* 3. Tuning rcvbuf, when connection enters established state. */
333 static void tcp_fixup_rcvbuf(struct sock *sk)
335 struct tcp_sock *tp = tcp_sk(sk);
336 int rcvmem = tp->advmss + MAX_TCP_HEADER + 16 + sizeof(struct sk_buff);
338 /* Try to select rcvbuf so that 4 mss-sized segments
339 * will fit to window and corresponding skbs will fit to our rcvbuf.
340 * (was 3; 4 is minimum to allow fast retransmit to work.)
342 while (tcp_win_from_space(rcvmem) < tp->advmss)
344 if (sk->sk_rcvbuf < 4 * rcvmem)
345 sk->sk_rcvbuf = min(4 * rcvmem, sysctl_tcp_rmem[2]);
348 /* 4. Try to fixup all. It is made immediately after connection enters
351 static void tcp_init_buffer_space(struct sock *sk)
353 struct tcp_sock *tp = tcp_sk(sk);
356 if (!(sk->sk_userlocks & SOCK_RCVBUF_LOCK))
357 tcp_fixup_rcvbuf(sk);
358 if (!(sk->sk_userlocks & SOCK_SNDBUF_LOCK))
359 tcp_fixup_sndbuf(sk);
361 tp->rcvq_space.space = tp->rcv_wnd;
363 maxwin = tcp_full_space(sk);
365 if (tp->window_clamp >= maxwin) {
366 tp->window_clamp = maxwin;
368 if (sysctl_tcp_app_win && maxwin > 4 * tp->advmss)
369 tp->window_clamp = max(maxwin -
370 (maxwin >> sysctl_tcp_app_win),
374 /* Force reservation of one segment. */
375 if (sysctl_tcp_app_win &&
376 tp->window_clamp > 2 * tp->advmss &&
377 tp->window_clamp + tp->advmss > maxwin)
378 tp->window_clamp = max(2 * tp->advmss, maxwin - tp->advmss);
380 tp->rcv_ssthresh = min(tp->rcv_ssthresh, tp->window_clamp);
381 tp->snd_cwnd_stamp = tcp_time_stamp;
384 /* 5. Recalculate window clamp after socket hit its memory bounds. */
385 static void tcp_clamp_window(struct sock *sk)
387 struct tcp_sock *tp = tcp_sk(sk);
388 struct inet_connection_sock *icsk = inet_csk(sk);
390 icsk->icsk_ack.quick = 0;
392 if (sk->sk_rcvbuf < sysctl_tcp_rmem[2] &&
393 !(sk->sk_userlocks & SOCK_RCVBUF_LOCK) &&
394 !tcp_memory_pressure &&
395 atomic_read(&tcp_memory_allocated) < sysctl_tcp_mem[0]) {
396 sk->sk_rcvbuf = min(atomic_read(&sk->sk_rmem_alloc),
399 if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf)
400 tp->rcv_ssthresh = min(tp->window_clamp, 2U * tp->advmss);
403 /* Initialize RCV_MSS value.
404 * RCV_MSS is an our guess about MSS used by the peer.
405 * We haven't any direct information about the MSS.
406 * It's better to underestimate the RCV_MSS rather than overestimate.
407 * Overestimations make us ACKing less frequently than needed.
408 * Underestimations are more easy to detect and fix by tcp_measure_rcv_mss().
410 void tcp_initialize_rcv_mss(struct sock *sk)
412 struct tcp_sock *tp = tcp_sk(sk);
413 unsigned int hint = min_t(unsigned int, tp->advmss, tp->mss_cache);
415 hint = min(hint, tp->rcv_wnd / 2);
416 hint = min(hint, TCP_MIN_RCVMSS);
417 hint = max(hint, TCP_MIN_MSS);
419 inet_csk(sk)->icsk_ack.rcv_mss = hint;
422 /* Receiver "autotuning" code.
424 * The algorithm for RTT estimation w/o timestamps is based on
425 * Dynamic Right-Sizing (DRS) by Wu Feng and Mike Fisk of LANL.
426 * <http://www.lanl.gov/radiant/website/pubs/drs/lacsi2001.ps>
428 * More detail on this code can be found at
429 * <http://www.psc.edu/~jheffner/senior_thesis.ps>,
430 * though this reference is out of date. A new paper
433 static void tcp_rcv_rtt_update(struct tcp_sock *tp, u32 sample, int win_dep)
435 u32 new_sample = tp->rcv_rtt_est.rtt;
441 if (new_sample != 0) {
442 /* If we sample in larger samples in the non-timestamp
443 * case, we could grossly overestimate the RTT especially
444 * with chatty applications or bulk transfer apps which
445 * are stalled on filesystem I/O.
447 * Also, since we are only going for a minimum in the
448 * non-timestamp case, we do not smooth things out
449 * else with timestamps disabled convergence takes too
453 m -= (new_sample >> 3);
455 } else if (m < new_sample)
458 /* No previous measure. */
462 if (tp->rcv_rtt_est.rtt != new_sample)
463 tp->rcv_rtt_est.rtt = new_sample;
466 static inline void tcp_rcv_rtt_measure(struct tcp_sock *tp)
468 if (tp->rcv_rtt_est.time == 0)
470 if (before(tp->rcv_nxt, tp->rcv_rtt_est.seq))
472 tcp_rcv_rtt_update(tp, jiffies - tp->rcv_rtt_est.time, 1);
475 tp->rcv_rtt_est.seq = tp->rcv_nxt + tp->rcv_wnd;
476 tp->rcv_rtt_est.time = tcp_time_stamp;
479 static inline void tcp_rcv_rtt_measure_ts(struct sock *sk,
480 const struct sk_buff *skb)
482 struct tcp_sock *tp = tcp_sk(sk);
483 if (tp->rx_opt.rcv_tsecr &&
484 (TCP_SKB_CB(skb)->end_seq -
485 TCP_SKB_CB(skb)->seq >= inet_csk(sk)->icsk_ack.rcv_mss))
486 tcp_rcv_rtt_update(tp, tcp_time_stamp - tp->rx_opt.rcv_tsecr, 0);
490 * This function should be called every time data is copied to user space.
491 * It calculates the appropriate TCP receive buffer space.
493 void tcp_rcv_space_adjust(struct sock *sk)
495 struct tcp_sock *tp = tcp_sk(sk);
499 if (tp->rcvq_space.time == 0)
502 time = tcp_time_stamp - tp->rcvq_space.time;
503 if (time < (tp->rcv_rtt_est.rtt >> 3) || tp->rcv_rtt_est.rtt == 0)
506 space = 2 * (tp->copied_seq - tp->rcvq_space.seq);
508 space = max(tp->rcvq_space.space, space);
510 if (tp->rcvq_space.space != space) {
513 tp->rcvq_space.space = space;
515 if (sysctl_tcp_moderate_rcvbuf &&
516 !(sk->sk_userlocks & SOCK_RCVBUF_LOCK)) {
517 int new_clamp = space;
519 /* Receive space grows, normalize in order to
520 * take into account packet headers and sk_buff
521 * structure overhead.
526 rcvmem = (tp->advmss + MAX_TCP_HEADER +
527 16 + sizeof(struct sk_buff));
528 while (tcp_win_from_space(rcvmem) < tp->advmss)
531 space = min(space, sysctl_tcp_rmem[2]);
532 if (space > sk->sk_rcvbuf) {
533 sk->sk_rcvbuf = space;
535 /* Make the window clamp follow along. */
536 tp->window_clamp = new_clamp;
542 tp->rcvq_space.seq = tp->copied_seq;
543 tp->rcvq_space.time = tcp_time_stamp;
546 /* There is something which you must keep in mind when you analyze the
547 * behavior of the tp->ato delayed ack timeout interval. When a
548 * connection starts up, we want to ack as quickly as possible. The
549 * problem is that "good" TCP's do slow start at the beginning of data
550 * transmission. The means that until we send the first few ACK's the
551 * sender will sit on his end and only queue most of his data, because
552 * he can only send snd_cwnd unacked packets at any given time. For
553 * each ACK we send, he increments snd_cwnd and transmits more of his
556 static void tcp_event_data_recv(struct sock *sk, struct sk_buff *skb)
558 struct tcp_sock *tp = tcp_sk(sk);
559 struct inet_connection_sock *icsk = inet_csk(sk);
562 inet_csk_schedule_ack(sk);
564 tcp_measure_rcv_mss(sk, skb);
566 tcp_rcv_rtt_measure(tp);
568 now = tcp_time_stamp;
570 if (!icsk->icsk_ack.ato) {
571 /* The _first_ data packet received, initialize
572 * delayed ACK engine.
574 tcp_incr_quickack(sk);
575 icsk->icsk_ack.ato = TCP_ATO_MIN;
577 int m = now - icsk->icsk_ack.lrcvtime;
579 if (m <= TCP_ATO_MIN / 2) {
580 /* The fastest case is the first. */
581 icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + TCP_ATO_MIN / 2;
582 } else if (m < icsk->icsk_ack.ato) {
583 icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + m;
584 if (icsk->icsk_ack.ato > icsk->icsk_rto)
585 icsk->icsk_ack.ato = icsk->icsk_rto;
586 } else if (m > icsk->icsk_rto) {
587 /* Too long gap. Apparently sender failed to
588 * restart window, so that we send ACKs quickly.
590 tcp_incr_quickack(sk);
594 icsk->icsk_ack.lrcvtime = now;
596 TCP_ECN_check_ce(tp, skb);
599 tcp_grow_window(sk, skb);
602 static u32 tcp_rto_min(struct sock *sk)
604 struct dst_entry *dst = __sk_dst_get(sk);
605 u32 rto_min = TCP_RTO_MIN;
607 if (dst && dst_metric_locked(dst, RTAX_RTO_MIN))
608 rto_min = dst->metrics[RTAX_RTO_MIN - 1];
612 /* Called to compute a smoothed rtt estimate. The data fed to this
613 * routine either comes from timestamps, or from segments that were
614 * known _not_ to have been retransmitted [see Karn/Partridge
615 * Proceedings SIGCOMM 87]. The algorithm is from the SIGCOMM 88
616 * piece by Van Jacobson.
617 * NOTE: the next three routines used to be one big routine.
618 * To save cycles in the RFC 1323 implementation it was better to break
619 * it up into three procedures. -- erics
621 static void tcp_rtt_estimator(struct sock *sk, const __u32 mrtt)
623 struct tcp_sock *tp = tcp_sk(sk);
624 long m = mrtt; /* RTT */
626 /* The following amusing code comes from Jacobson's
627 * article in SIGCOMM '88. Note that rtt and mdev
628 * are scaled versions of rtt and mean deviation.
629 * This is designed to be as fast as possible
630 * m stands for "measurement".
632 * On a 1990 paper the rto value is changed to:
633 * RTO = rtt + 4 * mdev
635 * Funny. This algorithm seems to be very broken.
636 * These formulae increase RTO, when it should be decreased, increase
637 * too slowly, when it should be increased quickly, decrease too quickly
638 * etc. I guess in BSD RTO takes ONE value, so that it is absolutely
639 * does not matter how to _calculate_ it. Seems, it was trap
640 * that VJ failed to avoid. 8)
645 m -= (tp->srtt >> 3); /* m is now error in rtt est */
646 tp->srtt += m; /* rtt = 7/8 rtt + 1/8 new */
648 m = -m; /* m is now abs(error) */
649 m -= (tp->mdev >> 2); /* similar update on mdev */
650 /* This is similar to one of Eifel findings.
651 * Eifel blocks mdev updates when rtt decreases.
652 * This solution is a bit different: we use finer gain
653 * for mdev in this case (alpha*beta).
654 * Like Eifel it also prevents growth of rto,
655 * but also it limits too fast rto decreases,
656 * happening in pure Eifel.
661 m -= (tp->mdev >> 2); /* similar update on mdev */
663 tp->mdev += m; /* mdev = 3/4 mdev + 1/4 new */
664 if (tp->mdev > tp->mdev_max) {
665 tp->mdev_max = tp->mdev;
666 if (tp->mdev_max > tp->rttvar)
667 tp->rttvar = tp->mdev_max;
669 if (after(tp->snd_una, tp->rtt_seq)) {
670 if (tp->mdev_max < tp->rttvar)
671 tp->rttvar -= (tp->rttvar - tp->mdev_max) >> 2;
672 tp->rtt_seq = tp->snd_nxt;
673 tp->mdev_max = tcp_rto_min(sk);
676 /* no previous measure. */
677 tp->srtt = m << 3; /* take the measured time to be rtt */
678 tp->mdev = m << 1; /* make sure rto = 3*rtt */
679 tp->mdev_max = tp->rttvar = max(tp->mdev, tcp_rto_min(sk));
680 tp->rtt_seq = tp->snd_nxt;
684 /* Calculate rto without backoff. This is the second half of Van Jacobson's
685 * routine referred to above.
687 static inline void tcp_set_rto(struct sock *sk)
689 const struct tcp_sock *tp = tcp_sk(sk);
690 /* Old crap is replaced with new one. 8)
693 * 1. If rtt variance happened to be less 50msec, it is hallucination.
694 * It cannot be less due to utterly erratic ACK generation made
695 * at least by solaris and freebsd. "Erratic ACKs" has _nothing_
696 * to do with delayed acks, because at cwnd>2 true delack timeout
697 * is invisible. Actually, Linux-2.4 also generates erratic
698 * ACKs in some circumstances.
700 inet_csk(sk)->icsk_rto = (tp->srtt >> 3) + tp->rttvar;
702 /* 2. Fixups made earlier cannot be right.
703 * If we do not estimate RTO correctly without them,
704 * all the algo is pure shit and should be replaced
705 * with correct one. It is exactly, which we pretend to do.
709 /* NOTE: clamping at TCP_RTO_MIN is not required, current algo
710 * guarantees that rto is higher.
712 static inline void tcp_bound_rto(struct sock *sk)
714 if (inet_csk(sk)->icsk_rto > TCP_RTO_MAX)
715 inet_csk(sk)->icsk_rto = TCP_RTO_MAX;
718 /* Save metrics learned by this TCP session.
719 This function is called only, when TCP finishes successfully
720 i.e. when it enters TIME-WAIT or goes from LAST-ACK to CLOSE.
722 void tcp_update_metrics(struct sock *sk)
724 struct tcp_sock *tp = tcp_sk(sk);
725 struct dst_entry *dst = __sk_dst_get(sk);
727 if (sysctl_tcp_nometrics_save)
732 if (dst && (dst->flags & DST_HOST)) {
733 const struct inet_connection_sock *icsk = inet_csk(sk);
736 if (icsk->icsk_backoff || !tp->srtt) {
737 /* This session failed to estimate rtt. Why?
738 * Probably, no packets returned in time.
741 if (!(dst_metric_locked(dst, RTAX_RTT)))
742 dst->metrics[RTAX_RTT - 1] = 0;
746 m = dst_metric(dst, RTAX_RTT) - tp->srtt;
748 /* If newly calculated rtt larger than stored one,
749 * store new one. Otherwise, use EWMA. Remember,
750 * rtt overestimation is always better than underestimation.
752 if (!(dst_metric_locked(dst, RTAX_RTT))) {
754 dst->metrics[RTAX_RTT - 1] = tp->srtt;
756 dst->metrics[RTAX_RTT - 1] -= (m >> 3);
759 if (!(dst_metric_locked(dst, RTAX_RTTVAR))) {
763 /* Scale deviation to rttvar fixed point */
768 if (m >= dst_metric(dst, RTAX_RTTVAR))
769 dst->metrics[RTAX_RTTVAR - 1] = m;
771 dst->metrics[RTAX_RTTVAR-1] -=
772 (dst->metrics[RTAX_RTTVAR-1] - m)>>2;
775 if (tp->snd_ssthresh >= 0xFFFF) {
776 /* Slow start still did not finish. */
777 if (dst_metric(dst, RTAX_SSTHRESH) &&
778 !dst_metric_locked(dst, RTAX_SSTHRESH) &&
779 (tp->snd_cwnd >> 1) > dst_metric(dst, RTAX_SSTHRESH))
780 dst->metrics[RTAX_SSTHRESH-1] = tp->snd_cwnd >> 1;
781 if (!dst_metric_locked(dst, RTAX_CWND) &&
782 tp->snd_cwnd > dst_metric(dst, RTAX_CWND))
783 dst->metrics[RTAX_CWND - 1] = tp->snd_cwnd;
784 } else if (tp->snd_cwnd > tp->snd_ssthresh &&
785 icsk->icsk_ca_state == TCP_CA_Open) {
786 /* Cong. avoidance phase, cwnd is reliable. */
787 if (!dst_metric_locked(dst, RTAX_SSTHRESH))
788 dst->metrics[RTAX_SSTHRESH-1] =
789 max(tp->snd_cwnd >> 1, tp->snd_ssthresh);
790 if (!dst_metric_locked(dst, RTAX_CWND))
791 dst->metrics[RTAX_CWND-1] = (dst->metrics[RTAX_CWND-1] + tp->snd_cwnd) >> 1;
793 /* Else slow start did not finish, cwnd is non-sense,
794 ssthresh may be also invalid.
796 if (!dst_metric_locked(dst, RTAX_CWND))
797 dst->metrics[RTAX_CWND-1] = (dst->metrics[RTAX_CWND-1] + tp->snd_ssthresh) >> 1;
798 if (dst->metrics[RTAX_SSTHRESH-1] &&
799 !dst_metric_locked(dst, RTAX_SSTHRESH) &&
800 tp->snd_ssthresh > dst->metrics[RTAX_SSTHRESH-1])
801 dst->metrics[RTAX_SSTHRESH-1] = tp->snd_ssthresh;
804 if (!dst_metric_locked(dst, RTAX_REORDERING)) {
805 if (dst->metrics[RTAX_REORDERING-1] < tp->reordering &&
806 tp->reordering != sysctl_tcp_reordering)
807 dst->metrics[RTAX_REORDERING-1] = tp->reordering;
812 /* Numbers are taken from RFC3390.
814 * John Heffner states:
816 * The RFC specifies a window of no more than 4380 bytes
817 * unless 2*MSS > 4380. Reading the pseudocode in the RFC
818 * is a bit misleading because they use a clamp at 4380 bytes
819 * rather than use a multiplier in the relevant range.
821 __u32 tcp_init_cwnd(struct tcp_sock *tp, struct dst_entry *dst)
823 __u32 cwnd = (dst ? dst_metric(dst, RTAX_INITCWND) : 0);
826 if (tp->mss_cache > 1460)
829 cwnd = (tp->mss_cache > 1095) ? 3 : 4;
831 return min_t(__u32, cwnd, tp->snd_cwnd_clamp);
834 /* Set slow start threshold and cwnd not falling to slow start */
835 void tcp_enter_cwr(struct sock *sk, const int set_ssthresh)
837 struct tcp_sock *tp = tcp_sk(sk);
838 const struct inet_connection_sock *icsk = inet_csk(sk);
840 tp->prior_ssthresh = 0;
842 if (icsk->icsk_ca_state < TCP_CA_CWR) {
845 tp->snd_ssthresh = icsk->icsk_ca_ops->ssthresh(sk);
846 tp->snd_cwnd = min(tp->snd_cwnd,
847 tcp_packets_in_flight(tp) + 1U);
848 tp->snd_cwnd_cnt = 0;
849 tp->high_seq = tp->snd_nxt;
850 tp->snd_cwnd_stamp = tcp_time_stamp;
851 TCP_ECN_queue_cwr(tp);
853 tcp_set_ca_state(sk, TCP_CA_CWR);
858 * Packet counting of FACK is based on in-order assumptions, therefore TCP
859 * disables it when reordering is detected
861 static void tcp_disable_fack(struct tcp_sock *tp)
863 /* RFC3517 uses different metric in lost marker => reset on change */
865 tp->lost_skb_hint = NULL;
866 tp->rx_opt.sack_ok &= ~2;
869 /* Take a notice that peer is sending D-SACKs */
870 static void tcp_dsack_seen(struct tcp_sock *tp)
872 tp->rx_opt.sack_ok |= 4;
875 /* Initialize metrics on socket. */
877 static void tcp_init_metrics(struct sock *sk)
879 struct tcp_sock *tp = tcp_sk(sk);
880 struct dst_entry *dst = __sk_dst_get(sk);
887 if (dst_metric_locked(dst, RTAX_CWND))
888 tp->snd_cwnd_clamp = dst_metric(dst, RTAX_CWND);
889 if (dst_metric(dst, RTAX_SSTHRESH)) {
890 tp->snd_ssthresh = dst_metric(dst, RTAX_SSTHRESH);
891 if (tp->snd_ssthresh > tp->snd_cwnd_clamp)
892 tp->snd_ssthresh = tp->snd_cwnd_clamp;
894 if (dst_metric(dst, RTAX_REORDERING) &&
895 tp->reordering != dst_metric(dst, RTAX_REORDERING)) {
896 tcp_disable_fack(tp);
897 tp->reordering = dst_metric(dst, RTAX_REORDERING);
900 if (dst_metric(dst, RTAX_RTT) == 0)
903 if (!tp->srtt && dst_metric(dst, RTAX_RTT) < (TCP_TIMEOUT_INIT << 3))
906 /* Initial rtt is determined from SYN,SYN-ACK.
907 * The segment is small and rtt may appear much
908 * less than real one. Use per-dst memory
909 * to make it more realistic.
911 * A bit of theory. RTT is time passed after "normal" sized packet
912 * is sent until it is ACKed. In normal circumstances sending small
913 * packets force peer to delay ACKs and calculation is correct too.
914 * The algorithm is adaptive and, provided we follow specs, it
915 * NEVER underestimate RTT. BUT! If peer tries to make some clever
916 * tricks sort of "quick acks" for time long enough to decrease RTT
917 * to low value, and then abruptly stops to do it and starts to delay
918 * ACKs, wait for troubles.
920 if (dst_metric(dst, RTAX_RTT) > tp->srtt) {
921 tp->srtt = dst_metric(dst, RTAX_RTT);
922 tp->rtt_seq = tp->snd_nxt;
924 if (dst_metric(dst, RTAX_RTTVAR) > tp->mdev) {
925 tp->mdev = dst_metric(dst, RTAX_RTTVAR);
926 tp->mdev_max = tp->rttvar = max(tp->mdev, tcp_rto_min(sk));
930 if (inet_csk(sk)->icsk_rto < TCP_TIMEOUT_INIT && !tp->rx_opt.saw_tstamp)
932 tp->snd_cwnd = tcp_init_cwnd(tp, dst);
933 tp->snd_cwnd_stamp = tcp_time_stamp;
937 /* Play conservative. If timestamps are not
938 * supported, TCP will fail to recalculate correct
939 * rtt, if initial rto is too small. FORGET ALL AND RESET!
941 if (!tp->rx_opt.saw_tstamp && tp->srtt) {
943 tp->mdev = tp->mdev_max = tp->rttvar = TCP_TIMEOUT_INIT;
944 inet_csk(sk)->icsk_rto = TCP_TIMEOUT_INIT;
948 static void tcp_update_reordering(struct sock *sk, const int metric,
951 struct tcp_sock *tp = tcp_sk(sk);
952 if (metric > tp->reordering) {
953 tp->reordering = min(TCP_MAX_REORDERING, metric);
955 /* This exciting event is worth to be remembered. 8) */
957 NET_INC_STATS_BH(LINUX_MIB_TCPTSREORDER);
958 else if (tcp_is_reno(tp))
959 NET_INC_STATS_BH(LINUX_MIB_TCPRENOREORDER);
960 else if (tcp_is_fack(tp))
961 NET_INC_STATS_BH(LINUX_MIB_TCPFACKREORDER);
963 NET_INC_STATS_BH(LINUX_MIB_TCPSACKREORDER);
964 #if FASTRETRANS_DEBUG > 1
965 printk(KERN_DEBUG "Disorder%d %d %u f%u s%u rr%d\n",
966 tp->rx_opt.sack_ok, inet_csk(sk)->icsk_ca_state,
970 tp->undo_marker ? tp->undo_retrans : 0);
972 tcp_disable_fack(tp);
976 /* This procedure tags the retransmission queue when SACKs arrive.
978 * We have three tag bits: SACKED(S), RETRANS(R) and LOST(L).
979 * Packets in queue with these bits set are counted in variables
980 * sacked_out, retrans_out and lost_out, correspondingly.
982 * Valid combinations are:
983 * Tag InFlight Description
984 * 0 1 - orig segment is in flight.
985 * S 0 - nothing flies, orig reached receiver.
986 * L 0 - nothing flies, orig lost by net.
987 * R 2 - both orig and retransmit are in flight.
988 * L|R 1 - orig is lost, retransmit is in flight.
989 * S|R 1 - orig reached receiver, retrans is still in flight.
990 * (L|S|R is logically valid, it could occur when L|R is sacked,
991 * but it is equivalent to plain S and code short-curcuits it to S.
992 * L|S is logically invalid, it would mean -1 packet in flight 8))
994 * These 6 states form finite state machine, controlled by the following events:
995 * 1. New ACK (+SACK) arrives. (tcp_sacktag_write_queue())
996 * 2. Retransmission. (tcp_retransmit_skb(), tcp_xmit_retransmit_queue())
997 * 3. Loss detection event of one of three flavors:
998 * A. Scoreboard estimator decided the packet is lost.
999 * A'. Reno "three dupacks" marks head of queue lost.
1000 * A''. Its FACK modfication, head until snd.fack is lost.
1001 * B. SACK arrives sacking data transmitted after never retransmitted
1002 * hole was sent out.
1003 * C. SACK arrives sacking SND.NXT at the moment, when the
1004 * segment was retransmitted.
1005 * 4. D-SACK added new rule: D-SACK changes any tag to S.
1007 * It is pleasant to note, that state diagram turns out to be commutative,
1008 * so that we are allowed not to be bothered by order of our actions,
1009 * when multiple events arrive simultaneously. (see the function below).
1011 * Reordering detection.
1012 * --------------------
1013 * Reordering metric is maximal distance, which a packet can be displaced
1014 * in packet stream. With SACKs we can estimate it:
1016 * 1. SACK fills old hole and the corresponding segment was not
1017 * ever retransmitted -> reordering. Alas, we cannot use it
1018 * when segment was retransmitted.
1019 * 2. The last flaw is solved with D-SACK. D-SACK arrives
1020 * for retransmitted and already SACKed segment -> reordering..
1021 * Both of these heuristics are not used in Loss state, when we cannot
1022 * account for retransmits accurately.
1024 * SACK block validation.
1025 * ----------------------
1027 * SACK block range validation checks that the received SACK block fits to
1028 * the expected sequence limits, i.e., it is between SND.UNA and SND.NXT.
1029 * Note that SND.UNA is not included to the range though being valid because
1030 * it means that the receiver is rather inconsistent with itself reporting
1031 * SACK reneging when it should advance SND.UNA. Such SACK block this is
1032 * perfectly valid, however, in light of RFC2018 which explicitly states
1033 * that "SACK block MUST reflect the newest segment. Even if the newest
1034 * segment is going to be discarded ...", not that it looks very clever
1035 * in case of head skb. Due to potentional receiver driven attacks, we
1036 * choose to avoid immediate execution of a walk in write queue due to
1037 * reneging and defer head skb's loss recovery to standard loss recovery
1038 * procedure that will eventually trigger (nothing forbids us doing this).
1040 * Implements also blockage to start_seq wrap-around. Problem lies in the
1041 * fact that though start_seq (s) is before end_seq (i.e., not reversed),
1042 * there's no guarantee that it will be before snd_nxt (n). The problem
1043 * happens when start_seq resides between end_seq wrap (e_w) and snd_nxt
1046 * <- outs wnd -> <- wrapzone ->
1047 * u e n u_w e_w s n_w
1049 * |<------------+------+----- TCP seqno space --------------+---------->|
1050 * ...-- <2^31 ->| |<--------...
1051 * ...---- >2^31 ------>| |<--------...
1053 * Current code wouldn't be vulnerable but it's better still to discard such
1054 * crazy SACK blocks. Doing this check for start_seq alone closes somewhat
1055 * similar case (end_seq after snd_nxt wrap) as earlier reversed check in
1056 * snd_nxt wrap -> snd_una region will then become "well defined", i.e.,
1057 * equal to the ideal case (infinite seqno space without wrap caused issues).
1059 * With D-SACK the lower bound is extended to cover sequence space below
1060 * SND.UNA down to undo_marker, which is the last point of interest. Yet
1061 * again, D-SACK block must not to go across snd_una (for the same reason as
1062 * for the normal SACK blocks, explained above). But there all simplicity
1063 * ends, TCP might receive valid D-SACKs below that. As long as they reside
1064 * fully below undo_marker they do not affect behavior in anyway and can
1065 * therefore be safely ignored. In rare cases (which are more or less
1066 * theoretical ones), the D-SACK will nicely cross that boundary due to skb
1067 * fragmentation and packet reordering past skb's retransmission. To consider
1068 * them correctly, the acceptable range must be extended even more though
1069 * the exact amount is rather hard to quantify. However, tp->max_window can
1070 * be used as an exaggerated estimate.
1072 static int tcp_is_sackblock_valid(struct tcp_sock *tp, int is_dsack,
1073 u32 start_seq, u32 end_seq)
1075 /* Too far in future, or reversed (interpretation is ambiguous) */
1076 if (after(end_seq, tp->snd_nxt) || !before(start_seq, end_seq))
1079 /* Nasty start_seq wrap-around check (see comments above) */
1080 if (!before(start_seq, tp->snd_nxt))
1083 /* In outstanding window? ...This is valid exit for D-SACKs too.
1084 * start_seq == snd_una is non-sensical (see comments above)
1086 if (after(start_seq, tp->snd_una))
1089 if (!is_dsack || !tp->undo_marker)
1092 /* ...Then it's D-SACK, and must reside below snd_una completely */
1093 if (!after(end_seq, tp->snd_una))
1096 if (!before(start_seq, tp->undo_marker))
1100 if (!after(end_seq, tp->undo_marker))
1103 /* Undo_marker boundary crossing (overestimates a lot). Known already:
1104 * start_seq < undo_marker and end_seq >= undo_marker.
1106 return !before(start_seq, end_seq - tp->max_window);
1109 /* Check for lost retransmit. This superb idea is borrowed from "ratehalving".
1110 * Event "C". Later note: FACK people cheated me again 8), we have to account
1111 * for reordering! Ugly, but should help.
1113 * Search retransmitted skbs from write_queue that were sent when snd_nxt was
1114 * less than what is now known to be received by the other end (derived from
1115 * highest SACK block). Also calculate the lowest snd_nxt among the remaining
1116 * retransmitted skbs to avoid some costly processing per ACKs.
1118 static void tcp_mark_lost_retrans(struct sock *sk)
1120 const struct inet_connection_sock *icsk = inet_csk(sk);
1121 struct tcp_sock *tp = tcp_sk(sk);
1122 struct sk_buff *skb;
1124 u32 new_low_seq = tp->snd_nxt;
1125 u32 received_upto = tcp_highest_sack_seq(tp);
1127 if (!tcp_is_fack(tp) || !tp->retrans_out ||
1128 !after(received_upto, tp->lost_retrans_low) ||
1129 icsk->icsk_ca_state != TCP_CA_Recovery)
1132 tcp_for_write_queue(skb, sk) {
1133 u32 ack_seq = TCP_SKB_CB(skb)->ack_seq;
1135 if (skb == tcp_send_head(sk))
1137 if (cnt == tp->retrans_out)
1139 if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una))
1142 if (!(TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS))
1145 if (after(received_upto, ack_seq) &&
1147 !before(received_upto,
1148 ack_seq + tp->reordering * tp->mss_cache))) {
1149 TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
1150 tp->retrans_out -= tcp_skb_pcount(skb);
1152 /* clear lost hint */
1153 tp->retransmit_skb_hint = NULL;
1155 if (!(TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_ACKED))) {
1156 tp->lost_out += tcp_skb_pcount(skb);
1157 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1159 NET_INC_STATS_BH(LINUX_MIB_TCPLOSTRETRANSMIT);
1161 if (before(ack_seq, new_low_seq))
1162 new_low_seq = ack_seq;
1163 cnt += tcp_skb_pcount(skb);
1167 if (tp->retrans_out)
1168 tp->lost_retrans_low = new_low_seq;
1171 static int tcp_check_dsack(struct tcp_sock *tp, struct sk_buff *ack_skb,
1172 struct tcp_sack_block_wire *sp, int num_sacks,
1175 u32 start_seq_0 = ntohl(get_unaligned(&sp[0].start_seq));
1176 u32 end_seq_0 = ntohl(get_unaligned(&sp[0].end_seq));
1179 if (before(start_seq_0, TCP_SKB_CB(ack_skb)->ack_seq)) {
1182 NET_INC_STATS_BH(LINUX_MIB_TCPDSACKRECV);
1183 } else if (num_sacks > 1) {
1184 u32 end_seq_1 = ntohl(get_unaligned(&sp[1].end_seq));
1185 u32 start_seq_1 = ntohl(get_unaligned(&sp[1].start_seq));
1187 if (!after(end_seq_0, end_seq_1) &&
1188 !before(start_seq_0, start_seq_1)) {
1191 NET_INC_STATS_BH(LINUX_MIB_TCPDSACKOFORECV);
1195 /* D-SACK for already forgotten data... Do dumb counting. */
1197 !after(end_seq_0, prior_snd_una) &&
1198 after(end_seq_0, tp->undo_marker))
1204 /* Check if skb is fully within the SACK block. In presence of GSO skbs,
1205 * the incoming SACK may not exactly match but we can find smaller MSS
1206 * aligned portion of it that matches. Therefore we might need to fragment
1207 * which may fail and creates some hassle (caller must handle error case
1210 static int tcp_match_skb_to_sack(struct sock *sk, struct sk_buff *skb,
1211 u32 start_seq, u32 end_seq)
1214 unsigned int pkt_len;
1216 in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
1217 !before(end_seq, TCP_SKB_CB(skb)->end_seq);
1219 if (tcp_skb_pcount(skb) > 1 && !in_sack &&
1220 after(TCP_SKB_CB(skb)->end_seq, start_seq)) {
1222 in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq);
1225 pkt_len = start_seq - TCP_SKB_CB(skb)->seq;
1227 pkt_len = end_seq - TCP_SKB_CB(skb)->seq;
1228 err = tcp_fragment(sk, skb, pkt_len, skb_shinfo(skb)->gso_size);
1236 static int tcp_sacktag_one(struct sk_buff *skb, struct sock *sk,
1237 int *reord, int dup_sack, int fack_count)
1239 struct tcp_sock *tp = tcp_sk(sk);
1240 u8 sacked = TCP_SKB_CB(skb)->sacked;
1243 /* Account D-SACK for retransmitted packet. */
1244 if (dup_sack && (sacked & TCPCB_RETRANS)) {
1245 if (after(TCP_SKB_CB(skb)->end_seq, tp->undo_marker))
1247 if (sacked & TCPCB_SACKED_ACKED)
1248 *reord = min(fack_count, *reord);
1251 /* Nothing to do; acked frame is about to be dropped (was ACKed). */
1252 if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una))
1255 if (!(sacked & TCPCB_SACKED_ACKED)) {
1256 if (sacked & TCPCB_SACKED_RETRANS) {
1257 /* If the segment is not tagged as lost,
1258 * we do not clear RETRANS, believing
1259 * that retransmission is still in flight.
1261 if (sacked & TCPCB_LOST) {
1262 TCP_SKB_CB(skb)->sacked &=
1263 ~(TCPCB_LOST|TCPCB_SACKED_RETRANS);
1264 tp->lost_out -= tcp_skb_pcount(skb);
1265 tp->retrans_out -= tcp_skb_pcount(skb);
1267 /* clear lost hint */
1268 tp->retransmit_skb_hint = NULL;
1271 if (!(sacked & TCPCB_RETRANS)) {
1272 /* New sack for not retransmitted frame,
1273 * which was in hole. It is reordering.
1275 if (before(TCP_SKB_CB(skb)->seq,
1276 tcp_highest_sack_seq(tp)))
1277 *reord = min(fack_count, *reord);
1279 /* SACK enhanced F-RTO (RFC4138; Appendix B) */
1280 if (!after(TCP_SKB_CB(skb)->end_seq, tp->frto_highmark))
1281 flag |= FLAG_ONLY_ORIG_SACKED;
1284 if (sacked & TCPCB_LOST) {
1285 TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
1286 tp->lost_out -= tcp_skb_pcount(skb);
1288 /* clear lost hint */
1289 tp->retransmit_skb_hint = NULL;
1293 TCP_SKB_CB(skb)->sacked |= TCPCB_SACKED_ACKED;
1294 flag |= FLAG_DATA_SACKED;
1295 tp->sacked_out += tcp_skb_pcount(skb);
1297 fack_count += tcp_skb_pcount(skb);
1299 /* Lost marker hint past SACKed? Tweak RFC3517 cnt */
1300 if (!tcp_is_fack(tp) && (tp->lost_skb_hint != NULL) &&
1301 before(TCP_SKB_CB(skb)->seq,
1302 TCP_SKB_CB(tp->lost_skb_hint)->seq))
1303 tp->lost_cnt_hint += tcp_skb_pcount(skb);
1305 if (fack_count > tp->fackets_out)
1306 tp->fackets_out = fack_count;
1308 if (!before(TCP_SKB_CB(skb)->seq, tcp_highest_sack_seq(tp)))
1309 tcp_advance_highest_sack(sk, skb);
1312 /* D-SACK. We can detect redundant retransmission in S|R and plain R
1313 * frames and clear it. undo_retrans is decreased above, L|R frames
1314 * are accounted above as well.
1316 if (dup_sack && (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS)) {
1317 TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
1318 tp->retrans_out -= tcp_skb_pcount(skb);
1319 tp->retransmit_skb_hint = NULL;
1325 static struct sk_buff *tcp_sacktag_walk(struct sk_buff *skb, struct sock *sk,
1326 struct tcp_sack_block *next_dup,
1327 u32 start_seq, u32 end_seq,
1328 int dup_sack_in, int *fack_count,
1329 int *reord, int *flag)
1331 tcp_for_write_queue_from(skb, sk) {
1333 int dup_sack = dup_sack_in;
1335 if (skb == tcp_send_head(sk))
1338 /* queue is in-order => we can short-circuit the walk early */
1339 if (!before(TCP_SKB_CB(skb)->seq, end_seq))
1342 if ((next_dup != NULL) &&
1343 before(TCP_SKB_CB(skb)->seq, next_dup->end_seq)) {
1344 in_sack = tcp_match_skb_to_sack(sk, skb,
1345 next_dup->start_seq,
1352 in_sack = tcp_match_skb_to_sack(sk, skb, start_seq,
1354 if (unlikely(in_sack < 0))
1358 *flag |= tcp_sacktag_one(skb, sk, reord, dup_sack,
1361 *fack_count += tcp_skb_pcount(skb);
1366 /* Avoid all extra work that is being done by sacktag while walking in
1369 static struct sk_buff *tcp_sacktag_skip(struct sk_buff *skb, struct sock *sk,
1370 u32 skip_to_seq, int *fack_count)
1372 tcp_for_write_queue_from(skb, sk) {
1373 if (skb == tcp_send_head(sk))
1376 if (!before(TCP_SKB_CB(skb)->end_seq, skip_to_seq))
1379 *fack_count += tcp_skb_pcount(skb);
1384 static struct sk_buff *tcp_maybe_skipping_dsack(struct sk_buff *skb,
1386 struct tcp_sack_block *next_dup,
1388 int *fack_count, int *reord,
1391 if (next_dup == NULL)
1394 if (before(next_dup->start_seq, skip_to_seq)) {
1395 skb = tcp_sacktag_skip(skb, sk, next_dup->start_seq, fack_count);
1396 tcp_sacktag_walk(skb, sk, NULL,
1397 next_dup->start_seq, next_dup->end_seq,
1398 1, fack_count, reord, flag);
1404 static int tcp_sack_cache_ok(struct tcp_sock *tp, struct tcp_sack_block *cache)
1406 return cache < tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache);
1410 tcp_sacktag_write_queue(struct sock *sk, struct sk_buff *ack_skb,
1413 const struct inet_connection_sock *icsk = inet_csk(sk);
1414 struct tcp_sock *tp = tcp_sk(sk);
1415 unsigned char *ptr = (skb_transport_header(ack_skb) +
1416 TCP_SKB_CB(ack_skb)->sacked);
1417 struct tcp_sack_block_wire *sp_wire = (struct tcp_sack_block_wire *)(ptr+2);
1418 struct tcp_sack_block sp[4];
1419 struct tcp_sack_block *cache;
1420 struct sk_buff *skb;
1421 int num_sacks = (ptr[1] - TCPOLEN_SACK_BASE) >> 3;
1423 int reord = tp->packets_out;
1425 int found_dup_sack = 0;
1428 int first_sack_index;
1430 if (!tp->sacked_out) {
1431 if (WARN_ON(tp->fackets_out))
1432 tp->fackets_out = 0;
1433 tcp_highest_sack_reset(sk);
1436 found_dup_sack = tcp_check_dsack(tp, ack_skb, sp_wire,
1437 num_sacks, prior_snd_una);
1439 flag |= FLAG_DSACKING_ACK;
1441 /* Eliminate too old ACKs, but take into
1442 * account more or less fresh ones, they can
1443 * contain valid SACK info.
1445 if (before(TCP_SKB_CB(ack_skb)->ack_seq, prior_snd_una - tp->max_window))
1448 if (!tp->packets_out)
1452 first_sack_index = 0;
1453 for (i = 0; i < num_sacks; i++) {
1454 int dup_sack = !i && found_dup_sack;
1456 sp[used_sacks].start_seq = ntohl(get_unaligned(&sp_wire[i].start_seq));
1457 sp[used_sacks].end_seq = ntohl(get_unaligned(&sp_wire[i].end_seq));
1459 if (!tcp_is_sackblock_valid(tp, dup_sack,
1460 sp[used_sacks].start_seq,
1461 sp[used_sacks].end_seq)) {
1463 if (!tp->undo_marker)
1464 NET_INC_STATS_BH(LINUX_MIB_TCPDSACKIGNOREDNOUNDO);
1466 NET_INC_STATS_BH(LINUX_MIB_TCPDSACKIGNOREDOLD);
1468 /* Don't count olds caused by ACK reordering */
1469 if ((TCP_SKB_CB(ack_skb)->ack_seq != tp->snd_una) &&
1470 !after(sp[used_sacks].end_seq, tp->snd_una))
1472 NET_INC_STATS_BH(LINUX_MIB_TCPSACKDISCARD);
1475 first_sack_index = -1;
1479 /* Ignore very old stuff early */
1480 if (!after(sp[used_sacks].end_seq, prior_snd_una))
1486 /* order SACK blocks to allow in order walk of the retrans queue */
1487 for (i = used_sacks - 1; i > 0; i--) {
1488 for (j = 0; j < i; j++) {
1489 if (after(sp[j].start_seq, sp[j + 1].start_seq)) {
1490 struct tcp_sack_block tmp;
1496 /* Track where the first SACK block goes to */
1497 if (j == first_sack_index)
1498 first_sack_index = j + 1;
1503 skb = tcp_write_queue_head(sk);
1507 if (!tp->sacked_out) {
1508 /* It's already past, so skip checking against it */
1509 cache = tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache);
1511 cache = tp->recv_sack_cache;
1512 /* Skip empty blocks in at head of the cache */
1513 while (tcp_sack_cache_ok(tp, cache) && !cache->start_seq &&
1518 while (i < used_sacks) {
1519 u32 start_seq = sp[i].start_seq;
1520 u32 end_seq = sp[i].end_seq;
1521 int dup_sack = (found_dup_sack && (i == first_sack_index));
1522 struct tcp_sack_block *next_dup = NULL;
1524 if (found_dup_sack && ((i + 1) == first_sack_index))
1525 next_dup = &sp[i + 1];
1527 /* Event "B" in the comment above. */
1528 if (after(end_seq, tp->high_seq))
1529 flag |= FLAG_DATA_LOST;
1531 /* Skip too early cached blocks */
1532 while (tcp_sack_cache_ok(tp, cache) &&
1533 !before(start_seq, cache->end_seq))
1536 /* Can skip some work by looking recv_sack_cache? */
1537 if (tcp_sack_cache_ok(tp, cache) && !dup_sack &&
1538 after(end_seq, cache->start_seq)) {
1541 if (before(start_seq, cache->start_seq)) {
1542 skb = tcp_sacktag_skip(skb, sk, start_seq,
1544 skb = tcp_sacktag_walk(skb, sk, next_dup,
1547 dup_sack, &fack_count,
1551 /* Rest of the block already fully processed? */
1552 if (!after(end_seq, cache->end_seq))
1555 skb = tcp_maybe_skipping_dsack(skb, sk, next_dup,
1557 &fack_count, &reord,
1560 /* ...tail remains todo... */
1561 if (tcp_highest_sack_seq(tp) == cache->end_seq) {
1562 /* ...but better entrypoint exists! */
1563 skb = tcp_highest_sack(sk);
1566 fack_count = tp->fackets_out;
1571 skb = tcp_sacktag_skip(skb, sk, cache->end_seq,
1573 /* Check overlap against next cached too (past this one already) */
1578 if (!before(start_seq, tcp_highest_sack_seq(tp))) {
1579 skb = tcp_highest_sack(sk);
1582 fack_count = tp->fackets_out;
1584 skb = tcp_sacktag_skip(skb, sk, start_seq, &fack_count);
1587 skb = tcp_sacktag_walk(skb, sk, next_dup, start_seq, end_seq,
1588 dup_sack, &fack_count, &reord, &flag);
1591 /* SACK enhanced FRTO (RFC4138, Appendix B): Clearing correct
1592 * due to in-order walk
1594 if (after(end_seq, tp->frto_highmark))
1595 flag &= ~FLAG_ONLY_ORIG_SACKED;
1600 /* Clear the head of the cache sack blocks so we can skip it next time */
1601 for (i = 0; i < ARRAY_SIZE(tp->recv_sack_cache) - used_sacks; i++) {
1602 tp->recv_sack_cache[i].start_seq = 0;
1603 tp->recv_sack_cache[i].end_seq = 0;
1605 for (j = 0; j < used_sacks; j++)
1606 tp->recv_sack_cache[i++] = sp[j];
1608 tcp_mark_lost_retrans(sk);
1610 tcp_verify_left_out(tp);
1612 if ((reord < tp->fackets_out) &&
1613 ((icsk->icsk_ca_state != TCP_CA_Loss) || tp->undo_marker) &&
1614 (!tp->frto_highmark || after(tp->snd_una, tp->frto_highmark)))
1615 tcp_update_reordering(sk, tp->fackets_out - reord, 0);
1619 #if FASTRETRANS_DEBUG > 0
1620 BUG_TRAP((int)tp->sacked_out >= 0);
1621 BUG_TRAP((int)tp->lost_out >= 0);
1622 BUG_TRAP((int)tp->retrans_out >= 0);
1623 BUG_TRAP((int)tcp_packets_in_flight(tp) >= 0);
1628 /* Limits sacked_out so that sum with lost_out isn't ever larger than
1629 * packets_out. Returns zero if sacked_out adjustement wasn't necessary.
1631 int tcp_limit_reno_sacked(struct tcp_sock *tp)
1635 holes = max(tp->lost_out, 1U);
1636 holes = min(holes, tp->packets_out);
1638 if ((tp->sacked_out + holes) > tp->packets_out) {
1639 tp->sacked_out = tp->packets_out - holes;
1645 /* If we receive more dupacks than we expected counting segments
1646 * in assumption of absent reordering, interpret this as reordering.
1647 * The only another reason could be bug in receiver TCP.
1649 static void tcp_check_reno_reordering(struct sock *sk, const int addend)
1651 struct tcp_sock *tp = tcp_sk(sk);
1652 if (tcp_limit_reno_sacked(tp))
1653 tcp_update_reordering(sk, tp->packets_out + addend, 0);
1656 /* Emulate SACKs for SACKless connection: account for a new dupack. */
1658 static void tcp_add_reno_sack(struct sock *sk)
1660 struct tcp_sock *tp = tcp_sk(sk);
1662 tcp_check_reno_reordering(sk, 0);
1663 tcp_verify_left_out(tp);
1666 /* Account for ACK, ACKing some data in Reno Recovery phase. */
1668 static void tcp_remove_reno_sacks(struct sock *sk, int acked)
1670 struct tcp_sock *tp = tcp_sk(sk);
1673 /* One ACK acked hole. The rest eat duplicate ACKs. */
1674 if (acked - 1 >= tp->sacked_out)
1677 tp->sacked_out -= acked - 1;
1679 tcp_check_reno_reordering(sk, acked);
1680 tcp_verify_left_out(tp);
1683 static inline void tcp_reset_reno_sack(struct tcp_sock *tp)
1688 /* F-RTO can only be used if TCP has never retransmitted anything other than
1689 * head (SACK enhanced variant from Appendix B of RFC4138 is more robust here)
1691 int tcp_use_frto(struct sock *sk)
1693 const struct tcp_sock *tp = tcp_sk(sk);
1694 const struct inet_connection_sock *icsk = inet_csk(sk);
1695 struct sk_buff *skb;
1697 if (!sysctl_tcp_frto)
1700 /* MTU probe and F-RTO won't really play nicely along currently */
1701 if (icsk->icsk_mtup.probe_size)
1707 /* Avoid expensive walking of rexmit queue if possible */
1708 if (tp->retrans_out > 1)
1711 skb = tcp_write_queue_head(sk);
1712 skb = tcp_write_queue_next(sk, skb); /* Skips head */
1713 tcp_for_write_queue_from(skb, sk) {
1714 if (skb == tcp_send_head(sk))
1716 if (TCP_SKB_CB(skb)->sacked & TCPCB_RETRANS)
1718 /* Short-circuit when first non-SACKed skb has been checked */
1719 if (!(TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED))
1725 /* RTO occurred, but do not yet enter Loss state. Instead, defer RTO
1726 * recovery a bit and use heuristics in tcp_process_frto() to detect if
1727 * the RTO was spurious. Only clear SACKED_RETRANS of the head here to
1728 * keep retrans_out counting accurate (with SACK F-RTO, other than head
1729 * may still have that bit set); TCPCB_LOST and remaining SACKED_RETRANS
1730 * bits are handled if the Loss state is really to be entered (in
1731 * tcp_enter_frto_loss).
1733 * Do like tcp_enter_loss() would; when RTO expires the second time it
1735 * "Reduce ssthresh if it has not yet been made inside this window."
1737 void tcp_enter_frto(struct sock *sk)
1739 const struct inet_connection_sock *icsk = inet_csk(sk);
1740 struct tcp_sock *tp = tcp_sk(sk);
1741 struct sk_buff *skb;
1743 if ((!tp->frto_counter && icsk->icsk_ca_state <= TCP_CA_Disorder) ||
1744 tp->snd_una == tp->high_seq ||
1745 ((icsk->icsk_ca_state == TCP_CA_Loss || tp->frto_counter) &&
1746 !icsk->icsk_retransmits)) {
1747 tp->prior_ssthresh = tcp_current_ssthresh(sk);
1748 /* Our state is too optimistic in ssthresh() call because cwnd
1749 * is not reduced until tcp_enter_frto_loss() when previous F-RTO
1750 * recovery has not yet completed. Pattern would be this: RTO,
1751 * Cumulative ACK, RTO (2xRTO for the same segment does not end
1753 * RFC4138 should be more specific on what to do, even though
1754 * RTO is quite unlikely to occur after the first Cumulative ACK
1755 * due to back-off and complexity of triggering events ...
1757 if (tp->frto_counter) {
1759 stored_cwnd = tp->snd_cwnd;
1761 tp->snd_ssthresh = icsk->icsk_ca_ops->ssthresh(sk);
1762 tp->snd_cwnd = stored_cwnd;
1764 tp->snd_ssthresh = icsk->icsk_ca_ops->ssthresh(sk);
1766 /* ... in theory, cong.control module could do "any tricks" in
1767 * ssthresh(), which means that ca_state, lost bits and lost_out
1768 * counter would have to be faked before the call occurs. We
1769 * consider that too expensive, unlikely and hacky, so modules
1770 * using these in ssthresh() must deal these incompatibility
1771 * issues if they receives CA_EVENT_FRTO and frto_counter != 0
1773 tcp_ca_event(sk, CA_EVENT_FRTO);
1776 tp->undo_marker = tp->snd_una;
1777 tp->undo_retrans = 0;
1779 skb = tcp_write_queue_head(sk);
1780 if (TCP_SKB_CB(skb)->sacked & TCPCB_RETRANS)
1781 tp->undo_marker = 0;
1782 if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS) {
1783 TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
1784 tp->retrans_out -= tcp_skb_pcount(skb);
1786 tcp_verify_left_out(tp);
1788 /* Too bad if TCP was application limited */
1789 tp->snd_cwnd = min(tp->snd_cwnd, tcp_packets_in_flight(tp) + 1);
1791 /* Earlier loss recovery underway (see RFC4138; Appendix B).
1792 * The last condition is necessary at least in tp->frto_counter case.
1794 if (IsSackFrto() && (tp->frto_counter ||
1795 ((1 << icsk->icsk_ca_state) & (TCPF_CA_Recovery|TCPF_CA_Loss))) &&
1796 after(tp->high_seq, tp->snd_una)) {
1797 tp->frto_highmark = tp->high_seq;
1799 tp->frto_highmark = tp->snd_nxt;
1801 tcp_set_ca_state(sk, TCP_CA_Disorder);
1802 tp->high_seq = tp->snd_nxt;
1803 tp->frto_counter = 1;
1806 /* Enter Loss state after F-RTO was applied. Dupack arrived after RTO,
1807 * which indicates that we should follow the traditional RTO recovery,
1808 * i.e. mark everything lost and do go-back-N retransmission.
1810 static void tcp_enter_frto_loss(struct sock *sk, int allowed_segments, int flag)
1812 struct tcp_sock *tp = tcp_sk(sk);
1813 struct sk_buff *skb;
1816 tp->retrans_out = 0;
1817 if (tcp_is_reno(tp))
1818 tcp_reset_reno_sack(tp);
1820 tcp_for_write_queue(skb, sk) {
1821 if (skb == tcp_send_head(sk))
1824 TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
1826 * Count the retransmission made on RTO correctly (only when
1827 * waiting for the first ACK and did not get it)...
1829 if ((tp->frto_counter == 1) && !(flag & FLAG_DATA_ACKED)) {
1830 /* For some reason this R-bit might get cleared? */
1831 if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS)
1832 tp->retrans_out += tcp_skb_pcount(skb);
1833 /* ...enter this if branch just for the first segment */
1834 flag |= FLAG_DATA_ACKED;
1836 if (TCP_SKB_CB(skb)->sacked & TCPCB_RETRANS)
1837 tp->undo_marker = 0;
1838 TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
1841 /* Don't lost mark skbs that were fwd transmitted after RTO */
1842 if (!(TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED) &&
1843 !after(TCP_SKB_CB(skb)->end_seq, tp->frto_highmark)) {
1844 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1845 tp->lost_out += tcp_skb_pcount(skb);
1848 tcp_verify_left_out(tp);
1850 tp->snd_cwnd = tcp_packets_in_flight(tp) + allowed_segments;
1851 tp->snd_cwnd_cnt = 0;
1852 tp->snd_cwnd_stamp = tcp_time_stamp;
1853 tp->frto_counter = 0;
1854 tp->bytes_acked = 0;
1856 tp->reordering = min_t(unsigned int, tp->reordering,
1857 sysctl_tcp_reordering);
1858 tcp_set_ca_state(sk, TCP_CA_Loss);
1859 tp->high_seq = tp->frto_highmark;
1860 TCP_ECN_queue_cwr(tp);
1862 tcp_clear_retrans_hints_partial(tp);
1865 static void tcp_clear_retrans_partial(struct tcp_sock *tp)
1867 tp->retrans_out = 0;
1870 tp->undo_marker = 0;
1871 tp->undo_retrans = 0;
1874 void tcp_clear_retrans(struct tcp_sock *tp)
1876 tcp_clear_retrans_partial(tp);
1878 tp->fackets_out = 0;
1882 /* Enter Loss state. If "how" is not zero, forget all SACK information
1883 * and reset tags completely, otherwise preserve SACKs. If receiver
1884 * dropped its ofo queue, we will know this due to reneging detection.
1886 void tcp_enter_loss(struct sock *sk, int how)
1888 const struct inet_connection_sock *icsk = inet_csk(sk);
1889 struct tcp_sock *tp = tcp_sk(sk);
1890 struct sk_buff *skb;
1892 /* Reduce ssthresh if it has not yet been made inside this window. */
1893 if (icsk->icsk_ca_state <= TCP_CA_Disorder || tp->snd_una == tp->high_seq ||
1894 (icsk->icsk_ca_state == TCP_CA_Loss && !icsk->icsk_retransmits)) {
1895 tp->prior_ssthresh = tcp_current_ssthresh(sk);
1896 tp->snd_ssthresh = icsk->icsk_ca_ops->ssthresh(sk);
1897 tcp_ca_event(sk, CA_EVENT_LOSS);
1900 tp->snd_cwnd_cnt = 0;
1901 tp->snd_cwnd_stamp = tcp_time_stamp;
1903 tp->bytes_acked = 0;
1904 tcp_clear_retrans_partial(tp);
1906 if (tcp_is_reno(tp))
1907 tcp_reset_reno_sack(tp);
1910 /* Push undo marker, if it was plain RTO and nothing
1911 * was retransmitted. */
1912 tp->undo_marker = tp->snd_una;
1913 tcp_clear_retrans_hints_partial(tp);
1916 tp->fackets_out = 0;
1917 tcp_clear_all_retrans_hints(tp);
1920 tcp_for_write_queue(skb, sk) {
1921 if (skb == tcp_send_head(sk))
1924 if (TCP_SKB_CB(skb)->sacked & TCPCB_RETRANS)
1925 tp->undo_marker = 0;
1926 TCP_SKB_CB(skb)->sacked &= (~TCPCB_TAGBITS)|TCPCB_SACKED_ACKED;
1927 if (!(TCP_SKB_CB(skb)->sacked&TCPCB_SACKED_ACKED) || how) {
1928 TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_ACKED;
1929 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1930 tp->lost_out += tcp_skb_pcount(skb);
1933 tcp_verify_left_out(tp);
1935 tp->reordering = min_t(unsigned int, tp->reordering,
1936 sysctl_tcp_reordering);
1937 tcp_set_ca_state(sk, TCP_CA_Loss);
1938 tp->high_seq = tp->snd_nxt;
1939 TCP_ECN_queue_cwr(tp);
1940 /* Abort F-RTO algorithm if one is in progress */
1941 tp->frto_counter = 0;
1944 /* If ACK arrived pointing to a remembered SACK, it means that our
1945 * remembered SACKs do not reflect real state of receiver i.e.
1946 * receiver _host_ is heavily congested (or buggy).
1948 * Do processing similar to RTO timeout.
1950 static int tcp_check_sack_reneging(struct sock *sk, int flag)
1952 if (flag & FLAG_SACK_RENEGING) {
1953 struct inet_connection_sock *icsk = inet_csk(sk);
1954 NET_INC_STATS_BH(LINUX_MIB_TCPSACKRENEGING);
1956 tcp_enter_loss(sk, 1);
1957 icsk->icsk_retransmits++;
1958 tcp_retransmit_skb(sk, tcp_write_queue_head(sk));
1959 inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
1960 icsk->icsk_rto, TCP_RTO_MAX);
1966 static inline int tcp_fackets_out(struct tcp_sock *tp)
1968 return tcp_is_reno(tp) ? tp->sacked_out + 1 : tp->fackets_out;
1971 /* Heurestics to calculate number of duplicate ACKs. There's no dupACKs
1972 * counter when SACK is enabled (without SACK, sacked_out is used for
1975 * Instead, with FACK TCP uses fackets_out that includes both SACKed
1976 * segments up to the highest received SACK block so far and holes in
1979 * With reordering, holes may still be in flight, so RFC3517 recovery
1980 * uses pure sacked_out (total number of SACKed segments) even though
1981 * it violates the RFC that uses duplicate ACKs, often these are equal
1982 * but when e.g. out-of-window ACKs or packet duplication occurs,
1983 * they differ. Since neither occurs due to loss, TCP should really
1986 static inline int tcp_dupack_heurestics(struct tcp_sock *tp)
1988 return tcp_is_fack(tp) ? tp->fackets_out : tp->sacked_out + 1;
1991 static inline int tcp_skb_timedout(struct sock *sk, struct sk_buff *skb)
1993 return (tcp_time_stamp - TCP_SKB_CB(skb)->when > inet_csk(sk)->icsk_rto);
1996 static inline int tcp_head_timedout(struct sock *sk)
1998 struct tcp_sock *tp = tcp_sk(sk);
2000 return tp->packets_out &&
2001 tcp_skb_timedout(sk, tcp_write_queue_head(sk));
2004 /* Linux NewReno/SACK/FACK/ECN state machine.
2005 * --------------------------------------
2007 * "Open" Normal state, no dubious events, fast path.
2008 * "Disorder" In all the respects it is "Open",
2009 * but requires a bit more attention. It is entered when
2010 * we see some SACKs or dupacks. It is split of "Open"
2011 * mainly to move some processing from fast path to slow one.
2012 * "CWR" CWND was reduced due to some Congestion Notification event.
2013 * It can be ECN, ICMP source quench, local device congestion.
2014 * "Recovery" CWND was reduced, we are fast-retransmitting.
2015 * "Loss" CWND was reduced due to RTO timeout or SACK reneging.
2017 * tcp_fastretrans_alert() is entered:
2018 * - each incoming ACK, if state is not "Open"
2019 * - when arrived ACK is unusual, namely:
2024 * Counting packets in flight is pretty simple.
2026 * in_flight = packets_out - left_out + retrans_out
2028 * packets_out is SND.NXT-SND.UNA counted in packets.
2030 * retrans_out is number of retransmitted segments.
2032 * left_out is number of segments left network, but not ACKed yet.
2034 * left_out = sacked_out + lost_out
2036 * sacked_out: Packets, which arrived to receiver out of order
2037 * and hence not ACKed. With SACKs this number is simply
2038 * amount of SACKed data. Even without SACKs
2039 * it is easy to give pretty reliable estimate of this number,
2040 * counting duplicate ACKs.
2042 * lost_out: Packets lost by network. TCP has no explicit
2043 * "loss notification" feedback from network (for now).
2044 * It means that this number can be only _guessed_.
2045 * Actually, it is the heuristics to predict lossage that
2046 * distinguishes different algorithms.
2048 * F.e. after RTO, when all the queue is considered as lost,
2049 * lost_out = packets_out and in_flight = retrans_out.
2051 * Essentially, we have now two algorithms counting
2054 * FACK: It is the simplest heuristics. As soon as we decided
2055 * that something is lost, we decide that _all_ not SACKed
2056 * packets until the most forward SACK are lost. I.e.
2057 * lost_out = fackets_out - sacked_out and left_out = fackets_out.
2058 * It is absolutely correct estimate, if network does not reorder
2059 * packets. And it loses any connection to reality when reordering
2060 * takes place. We use FACK by default until reordering
2061 * is suspected on the path to this destination.
2063 * NewReno: when Recovery is entered, we assume that one segment
2064 * is lost (classic Reno). While we are in Recovery and
2065 * a partial ACK arrives, we assume that one more packet
2066 * is lost (NewReno). This heuristics are the same in NewReno
2069 * Imagine, that's all! Forget about all this shamanism about CWND inflation
2070 * deflation etc. CWND is real congestion window, never inflated, changes
2071 * only according to classic VJ rules.
2073 * Really tricky (and requiring careful tuning) part of algorithm
2074 * is hidden in functions tcp_time_to_recover() and tcp_xmit_retransmit_queue().
2075 * The first determines the moment _when_ we should reduce CWND and,
2076 * hence, slow down forward transmission. In fact, it determines the moment
2077 * when we decide that hole is caused by loss, rather than by a reorder.
2079 * tcp_xmit_retransmit_queue() decides, _what_ we should retransmit to fill
2080 * holes, caused by lost packets.
2082 * And the most logically complicated part of algorithm is undo
2083 * heuristics. We detect false retransmits due to both too early
2084 * fast retransmit (reordering) and underestimated RTO, analyzing
2085 * timestamps and D-SACKs. When we detect that some segments were
2086 * retransmitted by mistake and CWND reduction was wrong, we undo
2087 * window reduction and abort recovery phase. This logic is hidden
2088 * inside several functions named tcp_try_undo_<something>.
2091 /* This function decides, when we should leave Disordered state
2092 * and enter Recovery phase, reducing congestion window.
2094 * Main question: may we further continue forward transmission
2095 * with the same cwnd?
2097 static int tcp_time_to_recover(struct sock *sk)
2099 struct tcp_sock *tp = tcp_sk(sk);
2102 /* Do not perform any recovery during F-RTO algorithm */
2103 if (tp->frto_counter)
2106 /* Trick#1: The loss is proven. */
2110 /* Not-A-Trick#2 : Classic rule... */
2111 if (tcp_dupack_heurestics(tp) > tp->reordering)
2114 /* Trick#3 : when we use RFC2988 timer restart, fast
2115 * retransmit can be triggered by timeout of queue head.
2117 if (tcp_is_fack(tp) && tcp_head_timedout(sk))
2120 /* Trick#4: It is still not OK... But will it be useful to delay
2123 packets_out = tp->packets_out;
2124 if (packets_out <= tp->reordering &&
2125 tp->sacked_out >= max_t(__u32, packets_out/2, sysctl_tcp_reordering) &&
2126 !tcp_may_send_now(sk)) {
2127 /* We have nothing to send. This connection is limited
2128 * either by receiver window or by application.
2136 /* RFC: This is from the original, I doubt that this is necessary at all:
2137 * clear xmit_retrans hint if seq of this skb is beyond hint. How could we
2138 * retransmitted past LOST markings in the first place? I'm not fully sure
2139 * about undo and end of connection cases, which can cause R without L?
2141 static void tcp_verify_retransmit_hint(struct tcp_sock *tp, struct sk_buff *skb)
2143 if ((tp->retransmit_skb_hint != NULL) &&
2144 before(TCP_SKB_CB(skb)->seq,
2145 TCP_SKB_CB(tp->retransmit_skb_hint)->seq))
2146 tp->retransmit_skb_hint = NULL;
2149 /* Mark head of queue up as lost. With RFC3517 SACK, the packets is
2150 * is against sacked "cnt", otherwise it's against facked "cnt"
2152 static void tcp_mark_head_lost(struct sock *sk, int packets)
2154 struct tcp_sock *tp = tcp_sk(sk);
2155 struct sk_buff *skb;
2160 BUG_TRAP(packets <= tp->packets_out);
2161 if (tp->lost_skb_hint) {
2162 skb = tp->lost_skb_hint;
2163 cnt = tp->lost_cnt_hint;
2165 skb = tcp_write_queue_head(sk);
2169 tcp_for_write_queue_from(skb, sk) {
2170 if (skb == tcp_send_head(sk))
2172 /* TODO: do this better */
2173 /* this is not the most efficient way to do this... */
2174 tp->lost_skb_hint = skb;
2175 tp->lost_cnt_hint = cnt;
2177 if (after(TCP_SKB_CB(skb)->end_seq, tp->high_seq))
2181 if (tcp_is_fack(tp) || tcp_is_reno(tp) ||
2182 (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED))
2183 cnt += tcp_skb_pcount(skb);
2185 if (cnt > packets) {
2186 if (tcp_is_sack(tp) || (oldcnt >= packets))
2189 mss = skb_shinfo(skb)->gso_size;
2190 err = tcp_fragment(sk, skb, (packets - oldcnt) * mss, mss);
2196 if (!(TCP_SKB_CB(skb)->sacked & (TCPCB_SACKED_ACKED|TCPCB_LOST))) {
2197 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
2198 tp->lost_out += tcp_skb_pcount(skb);
2199 tcp_verify_retransmit_hint(tp, skb);
2202 tcp_verify_left_out(tp);
2205 /* Account newly detected lost packet(s) */
2207 static void tcp_update_scoreboard(struct sock *sk, int fast_rexmit)
2209 struct tcp_sock *tp = tcp_sk(sk);
2211 if (tcp_is_reno(tp)) {
2212 tcp_mark_head_lost(sk, 1);
2213 } else if (tcp_is_fack(tp)) {
2214 int lost = tp->fackets_out - tp->reordering;
2217 tcp_mark_head_lost(sk, lost);
2219 int sacked_upto = tp->sacked_out - tp->reordering;
2220 if (sacked_upto < fast_rexmit)
2221 sacked_upto = fast_rexmit;
2222 tcp_mark_head_lost(sk, sacked_upto);
2225 /* New heuristics: it is possible only after we switched
2226 * to restart timer each time when something is ACKed.
2227 * Hence, we can detect timed out packets during fast
2228 * retransmit without falling to slow start.
2230 if (tcp_is_fack(tp) && tcp_head_timedout(sk)) {
2231 struct sk_buff *skb;
2233 skb = tp->scoreboard_skb_hint ? tp->scoreboard_skb_hint
2234 : tcp_write_queue_head(sk);
2236 tcp_for_write_queue_from(skb, sk) {
2237 if (skb == tcp_send_head(sk))
2239 if (!tcp_skb_timedout(sk, skb))
2242 if (!(TCP_SKB_CB(skb)->sacked & (TCPCB_SACKED_ACKED|TCPCB_LOST))) {
2243 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
2244 tp->lost_out += tcp_skb_pcount(skb);
2245 tcp_verify_retransmit_hint(tp, skb);
2249 tp->scoreboard_skb_hint = skb;
2251 tcp_verify_left_out(tp);
2255 /* CWND moderation, preventing bursts due to too big ACKs
2256 * in dubious situations.
2258 static inline void tcp_moderate_cwnd(struct tcp_sock *tp)
2260 tp->snd_cwnd = min(tp->snd_cwnd,
2261 tcp_packets_in_flight(tp) + tcp_max_burst(tp));
2262 tp->snd_cwnd_stamp = tcp_time_stamp;
2265 /* Lower bound on congestion window is slow start threshold
2266 * unless congestion avoidance choice decides to overide it.
2268 static inline u32 tcp_cwnd_min(const struct sock *sk)
2270 const struct tcp_congestion_ops *ca_ops = inet_csk(sk)->icsk_ca_ops;
2272 return ca_ops->min_cwnd ? ca_ops->min_cwnd(sk) : tcp_sk(sk)->snd_ssthresh;
2275 /* Decrease cwnd each second ack. */
2276 static void tcp_cwnd_down(struct sock *sk, int flag)
2278 struct tcp_sock *tp = tcp_sk(sk);
2279 int decr = tp->snd_cwnd_cnt + 1;
2281 if ((flag & (FLAG_ANY_PROGRESS | FLAG_DSACKING_ACK)) ||
2282 (tcp_is_reno(tp) && !(flag & FLAG_NOT_DUP))) {
2283 tp->snd_cwnd_cnt = decr & 1;
2286 if (decr && tp->snd_cwnd > tcp_cwnd_min(sk))
2287 tp->snd_cwnd -= decr;
2289 tp->snd_cwnd = min(tp->snd_cwnd, tcp_packets_in_flight(tp) + 1);
2290 tp->snd_cwnd_stamp = tcp_time_stamp;
2294 /* Nothing was retransmitted or returned timestamp is less
2295 * than timestamp of the first retransmission.
2297 static inline int tcp_packet_delayed(struct tcp_sock *tp)
2299 return !tp->retrans_stamp ||
2300 (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr &&
2301 (__s32)(tp->rx_opt.rcv_tsecr - tp->retrans_stamp) < 0);
2304 /* Undo procedures. */
2306 #if FASTRETRANS_DEBUG > 1
2307 static void DBGUNDO(struct sock *sk, const char *msg)
2309 struct tcp_sock *tp = tcp_sk(sk);
2310 struct inet_sock *inet = inet_sk(sk);
2312 printk(KERN_DEBUG "Undo %s %u.%u.%u.%u/%u c%u l%u ss%u/%u p%u\n",
2314 NIPQUAD(inet->daddr), ntohs(inet->dport),
2315 tp->snd_cwnd, tcp_left_out(tp),
2316 tp->snd_ssthresh, tp->prior_ssthresh,
2320 #define DBGUNDO(x...) do { } while (0)
2323 static void tcp_undo_cwr(struct sock *sk, const int undo)
2325 struct tcp_sock *tp = tcp_sk(sk);
2327 if (tp->prior_ssthresh) {
2328 const struct inet_connection_sock *icsk = inet_csk(sk);
2330 if (icsk->icsk_ca_ops->undo_cwnd)
2331 tp->snd_cwnd = icsk->icsk_ca_ops->undo_cwnd(sk);
2333 tp->snd_cwnd = max(tp->snd_cwnd, tp->snd_ssthresh << 1);
2335 if (undo && tp->prior_ssthresh > tp->snd_ssthresh) {
2336 tp->snd_ssthresh = tp->prior_ssthresh;
2337 TCP_ECN_withdraw_cwr(tp);
2340 tp->snd_cwnd = max(tp->snd_cwnd, tp->snd_ssthresh);
2342 tcp_moderate_cwnd(tp);
2343 tp->snd_cwnd_stamp = tcp_time_stamp;
2345 /* There is something screwy going on with the retrans hints after
2347 tcp_clear_all_retrans_hints(tp);
2350 static inline int tcp_may_undo(struct tcp_sock *tp)
2352 return tp->undo_marker && (!tp->undo_retrans || tcp_packet_delayed(tp));
2355 /* People celebrate: "We love our President!" */
2356 static int tcp_try_undo_recovery(struct sock *sk)
2358 struct tcp_sock *tp = tcp_sk(sk);
2360 if (tcp_may_undo(tp)) {
2361 /* Happy end! We did not retransmit anything
2362 * or our original transmission succeeded.
2364 DBGUNDO(sk, inet_csk(sk)->icsk_ca_state == TCP_CA_Loss ? "loss" : "retrans");
2365 tcp_undo_cwr(sk, 1);
2366 if (inet_csk(sk)->icsk_ca_state == TCP_CA_Loss)
2367 NET_INC_STATS_BH(LINUX_MIB_TCPLOSSUNDO);
2369 NET_INC_STATS_BH(LINUX_MIB_TCPFULLUNDO);
2370 tp->undo_marker = 0;
2372 if (tp->snd_una == tp->high_seq && tcp_is_reno(tp)) {
2373 /* Hold old state until something *above* high_seq
2374 * is ACKed. For Reno it is MUST to prevent false
2375 * fast retransmits (RFC2582). SACK TCP is safe. */
2376 tcp_moderate_cwnd(tp);
2379 tcp_set_ca_state(sk, TCP_CA_Open);
2383 /* Try to undo cwnd reduction, because D-SACKs acked all retransmitted data */
2384 static void tcp_try_undo_dsack(struct sock *sk)
2386 struct tcp_sock *tp = tcp_sk(sk);
2388 if (tp->undo_marker && !tp->undo_retrans) {
2389 DBGUNDO(sk, "D-SACK");
2390 tcp_undo_cwr(sk, 1);
2391 tp->undo_marker = 0;
2392 NET_INC_STATS_BH(LINUX_MIB_TCPDSACKUNDO);
2396 /* Undo during fast recovery after partial ACK. */
2398 static int tcp_try_undo_partial(struct sock *sk, int acked)
2400 struct tcp_sock *tp = tcp_sk(sk);
2401 /* Partial ACK arrived. Force Hoe's retransmit. */
2402 int failed = tcp_is_reno(tp) || (tcp_fackets_out(tp) > tp->reordering);
2404 if (tcp_may_undo(tp)) {
2405 /* Plain luck! Hole if filled with delayed
2406 * packet, rather than with a retransmit.
2408 if (tp->retrans_out == 0)
2409 tp->retrans_stamp = 0;
2411 tcp_update_reordering(sk, tcp_fackets_out(tp) + acked, 1);
2414 tcp_undo_cwr(sk, 0);
2415 NET_INC_STATS_BH(LINUX_MIB_TCPPARTIALUNDO);
2417 /* So... Do not make Hoe's retransmit yet.
2418 * If the first packet was delayed, the rest
2419 * ones are most probably delayed as well.
2426 /* Undo during loss recovery after partial ACK. */
2427 static int tcp_try_undo_loss(struct sock *sk)
2429 struct tcp_sock *tp = tcp_sk(sk);
2431 if (tcp_may_undo(tp)) {
2432 struct sk_buff *skb;
2433 tcp_for_write_queue(skb, sk) {
2434 if (skb == tcp_send_head(sk))
2436 TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
2439 tcp_clear_all_retrans_hints(tp);
2441 DBGUNDO(sk, "partial loss");
2443 tcp_undo_cwr(sk, 1);
2444 NET_INC_STATS_BH(LINUX_MIB_TCPLOSSUNDO);
2445 inet_csk(sk)->icsk_retransmits = 0;
2446 tp->undo_marker = 0;
2447 if (tcp_is_sack(tp))
2448 tcp_set_ca_state(sk, TCP_CA_Open);
2454 static inline void tcp_complete_cwr(struct sock *sk)
2456 struct tcp_sock *tp = tcp_sk(sk);
2457 tp->snd_cwnd = min(tp->snd_cwnd, tp->snd_ssthresh);
2458 tp->snd_cwnd_stamp = tcp_time_stamp;
2459 tcp_ca_event(sk, CA_EVENT_COMPLETE_CWR);
2462 static void tcp_try_to_open(struct sock *sk, int flag)
2464 struct tcp_sock *tp = tcp_sk(sk);
2466 tcp_verify_left_out(tp);
2468 if (tp->retrans_out == 0)
2469 tp->retrans_stamp = 0;
2471 if (flag & FLAG_ECE)
2472 tcp_enter_cwr(sk, 1);
2474 if (inet_csk(sk)->icsk_ca_state != TCP_CA_CWR) {
2475 int state = TCP_CA_Open;
2477 if (tcp_left_out(tp) || tp->retrans_out || tp->undo_marker)
2478 state = TCP_CA_Disorder;
2480 if (inet_csk(sk)->icsk_ca_state != state) {
2481 tcp_set_ca_state(sk, state);
2482 tp->high_seq = tp->snd_nxt;
2484 tcp_moderate_cwnd(tp);
2486 tcp_cwnd_down(sk, flag);
2490 static void tcp_mtup_probe_failed(struct sock *sk)
2492 struct inet_connection_sock *icsk = inet_csk(sk);
2494 icsk->icsk_mtup.search_high = icsk->icsk_mtup.probe_size - 1;
2495 icsk->icsk_mtup.probe_size = 0;
2498 static void tcp_mtup_probe_success(struct sock *sk, struct sk_buff *skb)
2500 struct tcp_sock *tp = tcp_sk(sk);
2501 struct inet_connection_sock *icsk = inet_csk(sk);
2503 /* FIXME: breaks with very large cwnd */
2504 tp->prior_ssthresh = tcp_current_ssthresh(sk);
2505 tp->snd_cwnd = tp->snd_cwnd *
2506 tcp_mss_to_mtu(sk, tp->mss_cache) /
2507 icsk->icsk_mtup.probe_size;
2508 tp->snd_cwnd_cnt = 0;
2509 tp->snd_cwnd_stamp = tcp_time_stamp;
2510 tp->rcv_ssthresh = tcp_current_ssthresh(sk);
2512 icsk->icsk_mtup.search_low = icsk->icsk_mtup.probe_size;
2513 icsk->icsk_mtup.probe_size = 0;
2514 tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
2517 /* Process an event, which can update packets-in-flight not trivially.
2518 * Main goal of this function is to calculate new estimate for left_out,
2519 * taking into account both packets sitting in receiver's buffer and
2520 * packets lost by network.
2522 * Besides that it does CWND reduction, when packet loss is detected
2523 * and changes state of machine.
2525 * It does _not_ decide what to send, it is made in function
2526 * tcp_xmit_retransmit_queue().
2528 static void tcp_fastretrans_alert(struct sock *sk, int pkts_acked, int flag)
2530 struct inet_connection_sock *icsk = inet_csk(sk);
2531 struct tcp_sock *tp = tcp_sk(sk);
2532 int is_dupack = !(flag & (FLAG_SND_UNA_ADVANCED | FLAG_NOT_DUP));
2533 int do_lost = is_dupack || ((flag & FLAG_DATA_SACKED) &&
2534 (tcp_fackets_out(tp) > tp->reordering));
2535 int fast_rexmit = 0;
2537 if (WARN_ON(!tp->packets_out && tp->sacked_out))
2539 if (WARN_ON(!tp->sacked_out && tp->fackets_out))
2540 tp->fackets_out = 0;
2542 /* Now state machine starts.
2543 * A. ECE, hence prohibit cwnd undoing, the reduction is required. */
2544 if (flag & FLAG_ECE)
2545 tp->prior_ssthresh = 0;
2547 /* B. In all the states check for reneging SACKs. */
2548 if (tcp_check_sack_reneging(sk, flag))
2551 /* C. Process data loss notification, provided it is valid. */
2552 if (tcp_is_fack(tp) && (flag & FLAG_DATA_LOST) &&
2553 before(tp->snd_una, tp->high_seq) &&
2554 icsk->icsk_ca_state != TCP_CA_Open &&
2555 tp->fackets_out > tp->reordering) {
2556 tcp_mark_head_lost(sk, tp->fackets_out - tp->reordering);
2557 NET_INC_STATS_BH(LINUX_MIB_TCPLOSS);
2560 /* D. Check consistency of the current state. */
2561 tcp_verify_left_out(tp);
2563 /* E. Check state exit conditions. State can be terminated
2564 * when high_seq is ACKed. */
2565 if (icsk->icsk_ca_state == TCP_CA_Open) {
2566 BUG_TRAP(tp->retrans_out == 0);
2567 tp->retrans_stamp = 0;
2568 } else if (!before(tp->snd_una, tp->high_seq)) {
2569 switch (icsk->icsk_ca_state) {
2571 icsk->icsk_retransmits = 0;
2572 if (tcp_try_undo_recovery(sk))
2577 /* CWR is to be held something *above* high_seq
2578 * is ACKed for CWR bit to reach receiver. */
2579 if (tp->snd_una != tp->high_seq) {
2580 tcp_complete_cwr(sk);
2581 tcp_set_ca_state(sk, TCP_CA_Open);
2585 case TCP_CA_Disorder:
2586 tcp_try_undo_dsack(sk);
2587 if (!tp->undo_marker ||
2588 /* For SACK case do not Open to allow to undo
2589 * catching for all duplicate ACKs. */
2590 tcp_is_reno(tp) || tp->snd_una != tp->high_seq) {
2591 tp->undo_marker = 0;
2592 tcp_set_ca_state(sk, TCP_CA_Open);
2596 case TCP_CA_Recovery:
2597 if (tcp_is_reno(tp))
2598 tcp_reset_reno_sack(tp);
2599 if (tcp_try_undo_recovery(sk))
2601 tcp_complete_cwr(sk);
2606 /* F. Process state. */
2607 switch (icsk->icsk_ca_state) {
2608 case TCP_CA_Recovery:
2609 if (!(flag & FLAG_SND_UNA_ADVANCED)) {
2610 if (tcp_is_reno(tp) && is_dupack)
2611 tcp_add_reno_sack(sk);
2613 do_lost = tcp_try_undo_partial(sk, pkts_acked);
2616 if (flag & FLAG_DATA_ACKED)
2617 icsk->icsk_retransmits = 0;
2618 if (tcp_is_reno(tp) && flag & FLAG_SND_UNA_ADVANCED)
2619 tcp_reset_reno_sack(tp);
2620 if (!tcp_try_undo_loss(sk)) {
2621 tcp_moderate_cwnd(tp);
2622 tcp_xmit_retransmit_queue(sk);
2625 if (icsk->icsk_ca_state != TCP_CA_Open)
2627 /* Loss is undone; fall through to processing in Open state. */
2629 if (tcp_is_reno(tp)) {
2630 if (flag & FLAG_SND_UNA_ADVANCED)
2631 tcp_reset_reno_sack(tp);
2633 tcp_add_reno_sack(sk);
2636 if (icsk->icsk_ca_state == TCP_CA_Disorder)
2637 tcp_try_undo_dsack(sk);
2639 if (!tcp_time_to_recover(sk)) {
2640 tcp_try_to_open(sk, flag);
2644 /* MTU probe failure: don't reduce cwnd */
2645 if (icsk->icsk_ca_state < TCP_CA_CWR &&
2646 icsk->icsk_mtup.probe_size &&
2647 tp->snd_una == tp->mtu_probe.probe_seq_start) {
2648 tcp_mtup_probe_failed(sk);
2649 /* Restores the reduction we did in tcp_mtup_probe() */
2651 tcp_simple_retransmit(sk);
2655 /* Otherwise enter Recovery state */
2657 if (tcp_is_reno(tp))
2658 NET_INC_STATS_BH(LINUX_MIB_TCPRENORECOVERY);
2660 NET_INC_STATS_BH(LINUX_MIB_TCPSACKRECOVERY);
2662 tp->high_seq = tp->snd_nxt;
2663 tp->prior_ssthresh = 0;
2664 tp->undo_marker = tp->snd_una;
2665 tp->undo_retrans = tp->retrans_out;
2667 if (icsk->icsk_ca_state < TCP_CA_CWR) {
2668 if (!(flag & FLAG_ECE))
2669 tp->prior_ssthresh = tcp_current_ssthresh(sk);
2670 tp->snd_ssthresh = icsk->icsk_ca_ops->ssthresh(sk);
2671 TCP_ECN_queue_cwr(tp);
2674 tp->bytes_acked = 0;
2675 tp->snd_cwnd_cnt = 0;
2676 tcp_set_ca_state(sk, TCP_CA_Recovery);
2680 if (do_lost || (tcp_is_fack(tp) && tcp_head_timedout(sk)))
2681 tcp_update_scoreboard(sk, fast_rexmit);
2682 tcp_cwnd_down(sk, flag);
2683 tcp_xmit_retransmit_queue(sk);
2686 /* Read draft-ietf-tcplw-high-performance before mucking
2687 * with this code. (Supersedes RFC1323)
2689 static void tcp_ack_saw_tstamp(struct sock *sk, int flag)
2691 /* RTTM Rule: A TSecr value received in a segment is used to
2692 * update the averaged RTT measurement only if the segment
2693 * acknowledges some new data, i.e., only if it advances the
2694 * left edge of the send window.
2696 * See draft-ietf-tcplw-high-performance-00, section 3.3.
2697 * 1998/04/10 Andrey V. Savochkin <saw@msu.ru>
2699 * Changed: reset backoff as soon as we see the first valid sample.
2700 * If we do not, we get strongly overestimated rto. With timestamps
2701 * samples are accepted even from very old segments: f.e., when rtt=1
2702 * increases to 8, we retransmit 5 times and after 8 seconds delayed
2703 * answer arrives rto becomes 120 seconds! If at least one of segments
2704 * in window is lost... Voila. --ANK (010210)
2706 struct tcp_sock *tp = tcp_sk(sk);
2707 const __u32 seq_rtt = tcp_time_stamp - tp->rx_opt.rcv_tsecr;
2708 tcp_rtt_estimator(sk, seq_rtt);
2710 inet_csk(sk)->icsk_backoff = 0;
2714 static void tcp_ack_no_tstamp(struct sock *sk, u32 seq_rtt, int flag)
2716 /* We don't have a timestamp. Can only use
2717 * packets that are not retransmitted to determine
2718 * rtt estimates. Also, we must not reset the
2719 * backoff for rto until we get a non-retransmitted
2720 * packet. This allows us to deal with a situation
2721 * where the network delay has increased suddenly.
2722 * I.e. Karn's algorithm. (SIGCOMM '87, p5.)
2725 if (flag & FLAG_RETRANS_DATA_ACKED)
2728 tcp_rtt_estimator(sk, seq_rtt);
2730 inet_csk(sk)->icsk_backoff = 0;
2734 static inline void tcp_ack_update_rtt(struct sock *sk, const int flag,
2737 const struct tcp_sock *tp = tcp_sk(sk);
2738 /* Note that peer MAY send zero echo. In this case it is ignored. (rfc1323) */
2739 if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr)
2740 tcp_ack_saw_tstamp(sk, flag);
2741 else if (seq_rtt >= 0)
2742 tcp_ack_no_tstamp(sk, seq_rtt, flag);
2745 static void tcp_cong_avoid(struct sock *sk, u32 ack, u32 in_flight)
2747 const struct inet_connection_sock *icsk = inet_csk(sk);
2748 icsk->icsk_ca_ops->cong_avoid(sk, ack, in_flight);
2749 tcp_sk(sk)->snd_cwnd_stamp = tcp_time_stamp;
2752 /* Restart timer after forward progress on connection.
2753 * RFC2988 recommends to restart timer to now+rto.
2755 static void tcp_rearm_rto(struct sock *sk)
2757 struct tcp_sock *tp = tcp_sk(sk);
2759 if (!tp->packets_out) {
2760 inet_csk_clear_xmit_timer(sk, ICSK_TIME_RETRANS);
2762 inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
2763 inet_csk(sk)->icsk_rto, TCP_RTO_MAX);
2767 /* If we get here, the whole TSO packet has not been acked. */
2768 static u32 tcp_tso_acked(struct sock *sk, struct sk_buff *skb)
2770 struct tcp_sock *tp = tcp_sk(sk);
2773 BUG_ON(!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una));
2775 packets_acked = tcp_skb_pcount(skb);
2776 if (tcp_trim_head(sk, skb, tp->snd_una - TCP_SKB_CB(skb)->seq))
2778 packets_acked -= tcp_skb_pcount(skb);
2780 if (packets_acked) {
2781 BUG_ON(tcp_skb_pcount(skb) == 0);
2782 BUG_ON(!before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq));
2785 return packets_acked;
2788 /* Remove acknowledged frames from the retransmission queue. If our packet
2789 * is before the ack sequence we can discard it as it's confirmed to have
2790 * arrived at the other end.
2792 static int tcp_clean_rtx_queue(struct sock *sk, int prior_fackets)
2794 struct tcp_sock *tp = tcp_sk(sk);
2795 const struct inet_connection_sock *icsk = inet_csk(sk);
2796 struct sk_buff *skb;
2797 u32 now = tcp_time_stamp;
2798 int fully_acked = 1;
2801 u32 reord = tp->packets_out;
2803 s32 ca_seq_rtt = -1;
2804 ktime_t last_ackt = net_invalid_timestamp();
2806 while ((skb = tcp_write_queue_head(sk)) && skb != tcp_send_head(sk)) {
2807 struct tcp_skb_cb *scb = TCP_SKB_CB(skb);
2810 u8 sacked = scb->sacked;
2812 /* Determine how many packets and what bytes were acked, tso and else */
2813 if (after(scb->end_seq, tp->snd_una)) {
2814 if (tcp_skb_pcount(skb) == 1 ||
2815 !after(tp->snd_una, scb->seq))
2818 acked_pcount = tcp_tso_acked(sk, skb);
2823 end_seq = tp->snd_una;
2825 acked_pcount = tcp_skb_pcount(skb);
2826 end_seq = scb->end_seq;
2829 /* MTU probing checks */
2830 if (fully_acked && icsk->icsk_mtup.probe_size &&
2831 !after(tp->mtu_probe.probe_seq_end, scb->end_seq)) {
2832 tcp_mtup_probe_success(sk, skb);
2835 if (sacked & TCPCB_RETRANS) {
2836 if (sacked & TCPCB_SACKED_RETRANS)
2837 tp->retrans_out -= acked_pcount;
2838 flag |= FLAG_RETRANS_DATA_ACKED;
2841 if ((flag & FLAG_DATA_ACKED) || (acked_pcount > 1))
2842 flag |= FLAG_NONHEAD_RETRANS_ACKED;
2844 ca_seq_rtt = now - scb->when;
2845 last_ackt = skb->tstamp;
2847 seq_rtt = ca_seq_rtt;
2849 if (!(sacked & TCPCB_SACKED_ACKED))
2850 reord = min(pkts_acked, reord);
2853 if (sacked & TCPCB_SACKED_ACKED)
2854 tp->sacked_out -= acked_pcount;
2855 if (sacked & TCPCB_LOST)
2856 tp->lost_out -= acked_pcount;
2858 if (unlikely(tp->urg_mode && !before(end_seq, tp->snd_up)))
2861 tp->packets_out -= acked_pcount;
2862 pkts_acked += acked_pcount;
2864 /* Initial outgoing SYN's get put onto the write_queue
2865 * just like anything else we transmit. It is not
2866 * true data, and if we misinform our callers that
2867 * this ACK acks real data, we will erroneously exit
2868 * connection startup slow start one packet too
2869 * quickly. This is severely frowned upon behavior.
2871 if (!(scb->flags & TCPCB_FLAG_SYN)) {
2872 flag |= FLAG_DATA_ACKED;
2874 flag |= FLAG_SYN_ACKED;
2875 tp->retrans_stamp = 0;
2881 tcp_unlink_write_queue(skb, sk);
2882 sk_wmem_free_skb(sk, skb);
2883 tcp_clear_all_retrans_hints(tp);
2886 if (skb && (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED))
2887 flag |= FLAG_SACK_RENEGING;
2889 if (flag & FLAG_ACKED) {
2890 const struct tcp_congestion_ops *ca_ops
2891 = inet_csk(sk)->icsk_ca_ops;
2893 tcp_ack_update_rtt(sk, flag, seq_rtt);
2896 if (tcp_is_reno(tp)) {
2897 tcp_remove_reno_sacks(sk, pkts_acked);
2899 /* Non-retransmitted hole got filled? That's reordering */
2900 if (reord < prior_fackets)
2901 tcp_update_reordering(sk, tp->fackets_out - reord, 0);
2904 tp->fackets_out -= min(pkts_acked, tp->fackets_out);
2906 if (ca_ops->pkts_acked) {
2909 /* Is the ACK triggering packet unambiguous? */
2910 if (!(flag & FLAG_RETRANS_DATA_ACKED)) {
2911 /* High resolution needed and available? */
2912 if (ca_ops->flags & TCP_CONG_RTT_STAMP &&
2913 !ktime_equal(last_ackt,
2914 net_invalid_timestamp()))
2915 rtt_us = ktime_us_delta(ktime_get_real(),
2917 else if (ca_seq_rtt > 0)
2918 rtt_us = jiffies_to_usecs(ca_seq_rtt);
2921 ca_ops->pkts_acked(sk, pkts_acked, rtt_us);
2925 #if FASTRETRANS_DEBUG > 0
2926 BUG_TRAP((int)tp->sacked_out >= 0);
2927 BUG_TRAP((int)tp->lost_out >= 0);
2928 BUG_TRAP((int)tp->retrans_out >= 0);
2929 if (!tp->packets_out && tcp_is_sack(tp)) {
2930 icsk = inet_csk(sk);
2932 printk(KERN_DEBUG "Leak l=%u %d\n",
2933 tp->lost_out, icsk->icsk_ca_state);
2936 if (tp->sacked_out) {
2937 printk(KERN_DEBUG "Leak s=%u %d\n",
2938 tp->sacked_out, icsk->icsk_ca_state);
2941 if (tp->retrans_out) {
2942 printk(KERN_DEBUG "Leak r=%u %d\n",
2943 tp->retrans_out, icsk->icsk_ca_state);
2944 tp->retrans_out = 0;
2951 static void tcp_ack_probe(struct sock *sk)
2953 const struct tcp_sock *tp = tcp_sk(sk);
2954 struct inet_connection_sock *icsk = inet_csk(sk);
2956 /* Was it a usable window open? */
2958 if (!after(TCP_SKB_CB(tcp_send_head(sk))->end_seq, tcp_wnd_end(tp))) {
2959 icsk->icsk_backoff = 0;
2960 inet_csk_clear_xmit_timer(sk, ICSK_TIME_PROBE0);
2961 /* Socket must be waked up by subsequent tcp_data_snd_check().
2962 * This function is not for random using!
2965 inet_csk_reset_xmit_timer(sk, ICSK_TIME_PROBE0,
2966 min(icsk->icsk_rto << icsk->icsk_backoff, TCP_RTO_MAX),
2971 static inline int tcp_ack_is_dubious(const struct sock *sk, const int flag)
2973 return (!(flag & FLAG_NOT_DUP) || (flag & FLAG_CA_ALERT) ||
2974 inet_csk(sk)->icsk_ca_state != TCP_CA_Open);
2977 static inline int tcp_may_raise_cwnd(const struct sock *sk, const int flag)
2979 const struct tcp_sock *tp = tcp_sk(sk);
2980 return (!(flag & FLAG_ECE) || tp->snd_cwnd < tp->snd_ssthresh) &&
2981 !((1 << inet_csk(sk)->icsk_ca_state) & (TCPF_CA_Recovery | TCPF_CA_CWR));
2984 /* Check that window update is acceptable.
2985 * The function assumes that snd_una<=ack<=snd_next.
2987 static inline int tcp_may_update_window(const struct tcp_sock *tp,
2988 const u32 ack, const u32 ack_seq,
2991 return (after(ack, tp->snd_una) ||
2992 after(ack_seq, tp->snd_wl1) ||
2993 (ack_seq == tp->snd_wl1 && nwin > tp->snd_wnd));
2996 /* Update our send window.
2998 * Window update algorithm, described in RFC793/RFC1122 (used in linux-2.2
2999 * and in FreeBSD. NetBSD's one is even worse.) is wrong.
3001 static int tcp_ack_update_window(struct sock *sk, struct sk_buff *skb, u32 ack,
3004 struct tcp_sock *tp = tcp_sk(sk);
3006 u32 nwin = ntohs(tcp_hdr(skb)->window);
3008 if (likely(!tcp_hdr(skb)->syn))
3009 nwin <<= tp->rx_opt.snd_wscale;
3011 if (tcp_may_update_window(tp, ack, ack_seq, nwin)) {
3012 flag |= FLAG_WIN_UPDATE;
3013 tcp_update_wl(tp, ack, ack_seq);
3015 if (tp->snd_wnd != nwin) {
3018 /* Note, it is the only place, where
3019 * fast path is recovered for sending TCP.
3022 tcp_fast_path_check(sk);
3024 if (nwin > tp->max_window) {
3025 tp->max_window = nwin;
3026 tcp_sync_mss(sk, inet_csk(sk)->icsk_pmtu_cookie);
3036 /* A very conservative spurious RTO response algorithm: reduce cwnd and
3037 * continue in congestion avoidance.
3039 static void tcp_conservative_spur_to_response(struct tcp_sock *tp)
3041 tp->snd_cwnd = min(tp->snd_cwnd, tp->snd_ssthresh);
3042 tp->snd_cwnd_cnt = 0;
3043 tp->bytes_acked = 0;
3044 TCP_ECN_queue_cwr(tp);
3045 tcp_moderate_cwnd(tp);
3048 /* A conservative spurious RTO response algorithm: reduce cwnd using
3049 * rate halving and continue in congestion avoidance.
3051 static void tcp_ratehalving_spur_to_response(struct sock *sk)
3053 tcp_enter_cwr(sk, 0);
3056 static void tcp_undo_spur_to_response(struct sock *sk, int flag)
3058 if (flag & FLAG_ECE)
3059 tcp_ratehalving_spur_to_response(sk);
3061 tcp_undo_cwr(sk, 1);
3064 /* F-RTO spurious RTO detection algorithm (RFC4138)
3066 * F-RTO affects during two new ACKs following RTO (well, almost, see inline
3067 * comments). State (ACK number) is kept in frto_counter. When ACK advances
3068 * window (but not to or beyond highest sequence sent before RTO):
3069 * On First ACK, send two new segments out.
3070 * On Second ACK, RTO was likely spurious. Do spurious response (response
3071 * algorithm is not part of the F-RTO detection algorithm
3072 * given in RFC4138 but can be selected separately).
3073 * Otherwise (basically on duplicate ACK), RTO was (likely) caused by a loss
3074 * and TCP falls back to conventional RTO recovery. F-RTO allows overriding
3075 * of Nagle, this is done using frto_counter states 2 and 3, when a new data
3076 * segment of any size sent during F-RTO, state 2 is upgraded to 3.
3078 * Rationale: if the RTO was spurious, new ACKs should arrive from the
3079 * original window even after we transmit two new data segments.
3082 * on first step, wait until first cumulative ACK arrives, then move to
3083 * the second step. In second step, the next ACK decides.
3085 * F-RTO is implemented (mainly) in four functions:
3086 * - tcp_use_frto() is used to determine if TCP is can use F-RTO
3087 * - tcp_enter_frto() prepares TCP state on RTO if F-RTO is used, it is
3088 * called when tcp_use_frto() showed green light
3089 * - tcp_process_frto() handles incoming ACKs during F-RTO algorithm
3090 * - tcp_enter_frto_loss() is called if there is not enough evidence
3091 * to prove that the RTO is indeed spurious. It transfers the control
3092 * from F-RTO to the conventional RTO recovery
3094 static int tcp_process_frto(struct sock *sk, int flag)
3096 struct tcp_sock *tp = tcp_sk(sk);
3098 tcp_verify_left_out(tp);
3100 /* Duplicate the behavior from Loss state (fastretrans_alert) */
3101 if (flag & FLAG_DATA_ACKED)
3102 inet_csk(sk)->icsk_retransmits = 0;
3104 if ((flag & FLAG_NONHEAD_RETRANS_ACKED) ||
3105 ((tp->frto_counter >= 2) && (flag & FLAG_RETRANS_DATA_ACKED)))
3106 tp->undo_marker = 0;
3108 if (!before(tp->snd_una, tp->frto_highmark)) {
3109 tcp_enter_frto_loss(sk, (tp->frto_counter == 1 ? 2 : 3), flag);