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 $
10 * Authors: Ross Biro, <bir7@leland.Stanford.Edu>
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 presnce 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
64 * Angelo Dell'Aera: TCP Westwood+ support
67 #include <linux/config.h>
69 #include <linux/module.h>
70 #include <linux/sysctl.h>
72 #include <net/inet_common.h>
73 #include <linux/ipsec.h>
75 int sysctl_tcp_timestamps = 1;
76 int sysctl_tcp_window_scaling = 1;
77 int sysctl_tcp_sack = 1;
78 int sysctl_tcp_fack = 1;
79 int sysctl_tcp_reordering = TCP_FASTRETRANS_THRESH;
81 int sysctl_tcp_dsack = 1;
82 int sysctl_tcp_app_win = 31;
83 int sysctl_tcp_adv_win_scale = 2;
85 int sysctl_tcp_stdurg;
86 int sysctl_tcp_rfc1337;
87 int sysctl_tcp_max_orphans = NR_FILE;
89 int sysctl_tcp_nometrics_save;
90 int sysctl_tcp_westwood;
91 int sysctl_tcp_vegas_cong_avoid;
93 int sysctl_tcp_moderate_rcvbuf;
95 /* Default values of the Vegas variables, in fixed-point representation
96 * with V_PARAM_SHIFT bits to the right of the binary point.
98 #define V_PARAM_SHIFT 1
99 int sysctl_tcp_vegas_alpha = 1<<V_PARAM_SHIFT;
100 int sysctl_tcp_vegas_beta = 3<<V_PARAM_SHIFT;
101 int sysctl_tcp_vegas_gamma = 1<<V_PARAM_SHIFT;
103 int sysctl_tcp_bic_fast_convergence = 1;
104 int sysctl_tcp_bic_low_window = 14;
106 #define FLAG_DATA 0x01 /* Incoming frame contained data. */
107 #define FLAG_WIN_UPDATE 0x02 /* Incoming ACK was a window update. */
108 #define FLAG_DATA_ACKED 0x04 /* This ACK acknowledged new data. */
109 #define FLAG_RETRANS_DATA_ACKED 0x08 /* "" "" some of which was retransmitted. */
110 #define FLAG_SYN_ACKED 0x10 /* This ACK acknowledged SYN. */
111 #define FLAG_DATA_SACKED 0x20 /* New SACK. */
112 #define FLAG_ECE 0x40 /* ECE in this ACK */
113 #define FLAG_DATA_LOST 0x80 /* SACK detected data lossage. */
114 #define FLAG_SLOWPATH 0x100 /* Do not skip RFC checks for window update.*/
116 #define FLAG_ACKED (FLAG_DATA_ACKED|FLAG_SYN_ACKED)
117 #define FLAG_NOT_DUP (FLAG_DATA|FLAG_WIN_UPDATE|FLAG_ACKED)
118 #define FLAG_CA_ALERT (FLAG_DATA_SACKED|FLAG_ECE)
119 #define FLAG_FORWARD_PROGRESS (FLAG_ACKED|FLAG_DATA_SACKED)
121 #define IsReno(tp) ((tp)->sack_ok == 0)
122 #define IsFack(tp) ((tp)->sack_ok & 2)
123 #define IsDSack(tp) ((tp)->sack_ok & 4)
125 #define TCP_REMNANT (TCP_FLAG_FIN|TCP_FLAG_URG|TCP_FLAG_SYN|TCP_FLAG_PSH)
127 /* Adapt the MSS value used to make delayed ack decision to the
130 static __inline__ void tcp_measure_rcv_mss(struct tcp_opt *tp, struct sk_buff *skb)
132 unsigned int len, lss;
134 lss = tp->ack.last_seg_size;
135 tp->ack.last_seg_size = 0;
137 /* skb->len may jitter because of SACKs, even if peer
138 * sends good full-sized frames.
141 if (len >= tp->ack.rcv_mss) {
142 tp->ack.rcv_mss = len;
144 /* Otherwise, we make more careful check taking into account,
145 * that SACKs block is variable.
147 * "len" is invariant segment length, including TCP header.
149 len += skb->data - skb->h.raw;
150 if (len >= TCP_MIN_RCVMSS + sizeof(struct tcphdr) ||
151 /* If PSH is not set, packet should be
152 * full sized, provided peer TCP is not badly broken.
153 * This observation (if it is correct 8)) allows
154 * to handle super-low mtu links fairly.
156 (len >= TCP_MIN_MSS + sizeof(struct tcphdr) &&
157 !(tcp_flag_word(skb->h.th)&TCP_REMNANT))) {
158 /* Subtract also invariant (if peer is RFC compliant),
159 * tcp header plus fixed timestamp option length.
160 * Resulting "len" is MSS free of SACK jitter.
162 len -= tp->tcp_header_len;
163 tp->ack.last_seg_size = len;
165 tp->ack.rcv_mss = len;
169 tp->ack.pending |= TCP_ACK_PUSHED;
173 static void tcp_incr_quickack(struct tcp_opt *tp)
175 unsigned quickacks = tp->rcv_wnd/(2*tp->ack.rcv_mss);
179 if (quickacks > tp->ack.quick)
180 tp->ack.quick = min(quickacks, TCP_MAX_QUICKACKS);
183 void tcp_enter_quickack_mode(struct tcp_opt *tp)
185 tcp_incr_quickack(tp);
186 tp->ack.pingpong = 0;
187 tp->ack.ato = TCP_ATO_MIN;
190 /* Send ACKs quickly, if "quick" count is not exhausted
191 * and the session is not interactive.
194 static __inline__ int tcp_in_quickack_mode(struct tcp_opt *tp)
196 return (tp->ack.quick && !tp->ack.pingpong);
199 /* Buffer size and advertised window tuning.
201 * 1. Tuning sk->sk_sndbuf, when connection enters established state.
204 static void tcp_fixup_sndbuf(struct sock *sk)
206 int sndmem = tcp_sk(sk)->mss_clamp + MAX_TCP_HEADER + 16 +
207 sizeof(struct sk_buff);
209 if (sk->sk_sndbuf < 3 * sndmem)
210 sk->sk_sndbuf = min(3 * sndmem, sysctl_tcp_wmem[2]);
213 /* 2. Tuning advertised window (window_clamp, rcv_ssthresh)
215 * All tcp_full_space() is split to two parts: "network" buffer, allocated
216 * forward and advertised in receiver window (tp->rcv_wnd) and
217 * "application buffer", required to isolate scheduling/application
218 * latencies from network.
219 * window_clamp is maximal advertised window. It can be less than
220 * tcp_full_space(), in this case tcp_full_space() - window_clamp
221 * is reserved for "application" buffer. The less window_clamp is
222 * the smoother our behaviour from viewpoint of network, but the lower
223 * throughput and the higher sensitivity of the connection to losses. 8)
225 * rcv_ssthresh is more strict window_clamp used at "slow start"
226 * phase to predict further behaviour of this connection.
227 * It is used for two goals:
228 * - to enforce header prediction at sender, even when application
229 * requires some significant "application buffer". It is check #1.
230 * - to prevent pruning of receive queue because of misprediction
231 * of receiver window. Check #2.
233 * The scheme does not work when sender sends good segments opening
234 * window and then starts to feed us spagetti. But it should work
235 * in common situations. Otherwise, we have to rely on queue collapsing.
238 /* Slow part of check#2. */
240 __tcp_grow_window(struct sock *sk, struct tcp_opt *tp, struct sk_buff *skb)
243 int truesize = tcp_win_from_space(skb->truesize)/2;
244 int window = tcp_full_space(sk)/2;
246 while (tp->rcv_ssthresh <= window) {
247 if (truesize <= skb->len)
248 return 2*tp->ack.rcv_mss;
256 static __inline__ void
257 tcp_grow_window(struct sock *sk, struct tcp_opt *tp, struct sk_buff *skb)
260 if (tp->rcv_ssthresh < tp->window_clamp &&
261 (int)tp->rcv_ssthresh < tcp_space(sk) &&
262 !tcp_memory_pressure) {
265 /* Check #2. Increase window, if skb with such overhead
266 * will fit to rcvbuf in future.
268 if (tcp_win_from_space(skb->truesize) <= skb->len)
271 incr = __tcp_grow_window(sk, tp, skb);
274 tp->rcv_ssthresh = min(tp->rcv_ssthresh + incr, tp->window_clamp);
280 /* 3. Tuning rcvbuf, when connection enters established state. */
282 static void tcp_fixup_rcvbuf(struct sock *sk)
284 struct tcp_opt *tp = tcp_sk(sk);
285 int rcvmem = tp->advmss + MAX_TCP_HEADER + 16 + sizeof(struct sk_buff);
287 /* Try to select rcvbuf so that 4 mss-sized segments
288 * will fit to window and correspoding skbs will fit to our rcvbuf.
289 * (was 3; 4 is minimum to allow fast retransmit to work.)
291 while (tcp_win_from_space(rcvmem) < tp->advmss)
293 if (sk->sk_rcvbuf < 4 * rcvmem)
294 sk->sk_rcvbuf = min(4 * rcvmem, sysctl_tcp_rmem[2]);
297 /* 4. Try to fixup all. It is made iimediately after connection enters
300 static void tcp_init_buffer_space(struct sock *sk)
302 struct tcp_opt *tp = tcp_sk(sk);
305 if (!(sk->sk_userlocks & SOCK_RCVBUF_LOCK))
306 tcp_fixup_rcvbuf(sk);
307 if (!(sk->sk_userlocks & SOCK_SNDBUF_LOCK))
308 tcp_fixup_sndbuf(sk);
310 tp->rcvq_space.space = tp->rcv_wnd;
312 maxwin = tcp_full_space(sk);
314 if (tp->window_clamp >= maxwin) {
315 tp->window_clamp = maxwin;
317 if (sysctl_tcp_app_win && maxwin > 4 * tp->advmss)
318 tp->window_clamp = max(maxwin -
319 (maxwin >> sysctl_tcp_app_win),
323 /* Force reservation of one segment. */
324 if (sysctl_tcp_app_win &&
325 tp->window_clamp > 2 * tp->advmss &&
326 tp->window_clamp + tp->advmss > maxwin)
327 tp->window_clamp = max(2 * tp->advmss, maxwin - tp->advmss);
329 tp->rcv_ssthresh = min(tp->rcv_ssthresh, tp->window_clamp);
330 tp->snd_cwnd_stamp = tcp_time_stamp;
333 /* 5. Recalculate window clamp after socket hit its memory bounds. */
334 static void tcp_clamp_window(struct sock *sk, struct tcp_opt *tp)
337 unsigned int app_win = tp->rcv_nxt - tp->copied_seq;
342 skb_queue_walk(&tp->out_of_order_queue, skb) {
346 /* If overcommit is due to out of order segments,
347 * do not clamp window. Try to expand rcvbuf instead.
350 if (sk->sk_rcvbuf < sysctl_tcp_rmem[2] &&
351 !(sk->sk_userlocks & SOCK_RCVBUF_LOCK) &&
352 !tcp_memory_pressure &&
353 atomic_read(&tcp_memory_allocated) < sysctl_tcp_mem[0])
354 sk->sk_rcvbuf = min(atomic_read(&sk->sk_rmem_alloc),
357 if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf) {
359 if (atomic_read(&sk->sk_rmem_alloc) >= 2 * sk->sk_rcvbuf)
361 if (app_win > tp->ack.rcv_mss)
362 app_win -= tp->ack.rcv_mss;
363 app_win = max(app_win, 2U*tp->advmss);
366 tp->window_clamp = min(tp->window_clamp, app_win);
367 tp->rcv_ssthresh = min(tp->window_clamp, 2U*tp->advmss);
371 /* Receiver "autotuning" code.
373 * The algorithm for RTT estimation w/o timestamps is based on
374 * Dynamic Right-Sizing (DRS) by Wu Feng and Mike Fisk of LANL.
375 * <http://www.lanl.gov/radiant/website/pubs/drs/lacsi2001.ps>
377 * More detail on this code can be found at
378 * <http://www.psc.edu/~jheffner/senior_thesis.ps>,
379 * though this reference is out of date. A new paper
382 static void tcp_rcv_rtt_update(struct tcp_opt *tp, u32 sample, int win_dep)
384 u32 new_sample = tp->rcv_rtt_est.rtt;
390 if (new_sample != 0) {
391 /* If we sample in larger samples in the non-timestamp
392 * case, we could grossly overestimate the RTT especially
393 * with chatty applications or bulk transfer apps which
394 * are stalled on filesystem I/O.
396 * Also, since we are only going for a minimum in the
397 * non-timestamp case, we do not smoothe things out
398 * else with timestamps disabled convergance takes too
402 m -= (new_sample >> 3);
404 } else if (m < new_sample)
407 /* No previous mesaure. */
411 if (tp->rcv_rtt_est.rtt != new_sample)
412 tp->rcv_rtt_est.rtt = new_sample;
415 static inline void tcp_rcv_rtt_measure(struct tcp_opt *tp)
417 if (tp->rcv_rtt_est.time == 0)
419 if (before(tp->rcv_nxt, tp->rcv_rtt_est.seq))
421 tcp_rcv_rtt_update(tp,
422 jiffies - tp->rcv_rtt_est.time,
426 tp->rcv_rtt_est.seq = tp->rcv_nxt + tp->rcv_wnd;
427 tp->rcv_rtt_est.time = tcp_time_stamp;
430 static inline void tcp_rcv_rtt_measure_ts(struct tcp_opt *tp, struct sk_buff *skb)
433 (TCP_SKB_CB(skb)->end_seq -
434 TCP_SKB_CB(skb)->seq >= tp->ack.rcv_mss))
435 tcp_rcv_rtt_update(tp, tcp_time_stamp - tp->rcv_tsecr, 0);
439 * This function should be called every time data is copied to user space.
440 * It calculates the appropriate TCP receive buffer space.
442 void tcp_rcv_space_adjust(struct sock *sk)
444 struct tcp_opt *tp = tcp_sk(sk);
448 if (tp->rcvq_space.time == 0)
451 time = tcp_time_stamp - tp->rcvq_space.time;
452 if (time < (tp->rcv_rtt_est.rtt >> 3) ||
453 tp->rcv_rtt_est.rtt == 0)
456 space = 2 * (tp->copied_seq - tp->rcvq_space.seq);
458 space = max(tp->rcvq_space.space, space);
460 if (tp->rcvq_space.space != space) {
463 tp->rcvq_space.space = space;
465 if (sysctl_tcp_moderate_rcvbuf) {
466 /* Receive space grows, normalize in order to
467 * take into account packet headers and sk_buff
468 * structure overhead.
473 rcvmem = (tp->advmss + MAX_TCP_HEADER +
474 16 + sizeof(struct sk_buff));
476 space = min(space, sysctl_tcp_rmem[2]);
477 if (space > sk->sk_rcvbuf)
478 sk->sk_rcvbuf = space;
483 tp->rcvq_space.seq = tp->copied_seq;
484 tp->rcvq_space.time = tcp_time_stamp;
487 /* There is something which you must keep in mind when you analyze the
488 * behavior of the tp->ato delayed ack timeout interval. When a
489 * connection starts up, we want to ack as quickly as possible. The
490 * problem is that "good" TCP's do slow start at the beginning of data
491 * transmission. The means that until we send the first few ACK's the
492 * sender will sit on his end and only queue most of his data, because
493 * he can only send snd_cwnd unacked packets at any given time. For
494 * each ACK we send, he increments snd_cwnd and transmits more of his
497 static void tcp_event_data_recv(struct sock *sk, struct tcp_opt *tp, struct sk_buff *skb)
501 tcp_schedule_ack(tp);
503 tcp_measure_rcv_mss(tp, skb);
505 tcp_rcv_rtt_measure(tp);
507 now = tcp_time_stamp;
510 /* The _first_ data packet received, initialize
511 * delayed ACK engine.
513 tcp_incr_quickack(tp);
514 tp->ack.ato = TCP_ATO_MIN;
516 int m = now - tp->ack.lrcvtime;
518 if (m <= TCP_ATO_MIN/2) {
519 /* The fastest case is the first. */
520 tp->ack.ato = (tp->ack.ato>>1) + TCP_ATO_MIN/2;
521 } else if (m < tp->ack.ato) {
522 tp->ack.ato = (tp->ack.ato>>1) + m;
523 if (tp->ack.ato > tp->rto)
524 tp->ack.ato = tp->rto;
525 } else if (m > tp->rto) {
526 /* Too long gap. Apparently sender falled to
527 * restart window, so that we send ACKs quickly.
529 tcp_incr_quickack(tp);
533 tp->ack.lrcvtime = now;
535 TCP_ECN_check_ce(tp, skb);
538 tcp_grow_window(sk, tp, skb);
541 /* Set up a new TCP connection, depending on whether it should be
542 * using Vegas or not.
544 void tcp_vegas_init(struct tcp_opt *tp)
546 if (sysctl_tcp_vegas_cong_avoid) {
547 tp->vegas.do_vegas = 1;
548 tp->vegas.baseRTT = 0x7fffffff;
549 tcp_vegas_enable(tp);
551 tcp_vegas_disable(tp);
554 /* Do RTT sampling needed for Vegas.
556 * o min-filter RTT samples from within an RTT to get the current
557 * propagation delay + queuing delay (we are min-filtering to try to
558 * avoid the effects of delayed ACKs)
559 * o min-filter RTT samples from a much longer window (forever for now)
560 * to find the propagation delay (baseRTT)
562 static inline void vegas_rtt_calc(struct tcp_opt *tp, __u32 rtt)
564 __u32 vrtt = rtt + 1; /* Never allow zero rtt or baseRTT */
566 /* Filter to find propagation delay: */
567 if (vrtt < tp->vegas.baseRTT)
568 tp->vegas.baseRTT = vrtt;
570 /* Find the min RTT during the last RTT to find
571 * the current prop. delay + queuing delay:
573 tp->vegas.minRTT = min(tp->vegas.minRTT, vrtt);
577 /* Called to compute a smoothed rtt estimate. The data fed to this
578 * routine either comes from timestamps, or from segments that were
579 * known _not_ to have been retransmitted [see Karn/Partridge
580 * Proceedings SIGCOMM 87]. The algorithm is from the SIGCOMM 88
581 * piece by Van Jacobson.
582 * NOTE: the next three routines used to be one big routine.
583 * To save cycles in the RFC 1323 implementation it was better to break
584 * it up into three procedures. -- erics
586 static void tcp_rtt_estimator(struct tcp_opt *tp, __u32 mrtt)
588 long m = mrtt; /* RTT */
590 if (tcp_vegas_enabled(tp))
591 vegas_rtt_calc(tp, mrtt);
593 /* The following amusing code comes from Jacobson's
594 * article in SIGCOMM '88. Note that rtt and mdev
595 * are scaled versions of rtt and mean deviation.
596 * This is designed to be as fast as possible
597 * m stands for "measurement".
599 * On a 1990 paper the rto value is changed to:
600 * RTO = rtt + 4 * mdev
602 * Funny. This algorithm seems to be very broken.
603 * These formulae increase RTO, when it should be decreased, increase
604 * too slowly, when it should be incresed fastly, decrease too fastly
605 * etc. I guess in BSD RTO takes ONE value, so that it is absolutely
606 * does not matter how to _calculate_ it. Seems, it was trap
607 * that VJ failed to avoid. 8)
612 m -= (tp->srtt >> 3); /* m is now error in rtt est */
613 tp->srtt += m; /* rtt = 7/8 rtt + 1/8 new */
615 m = -m; /* m is now abs(error) */
616 m -= (tp->mdev >> 2); /* similar update on mdev */
617 /* This is similar to one of Eifel findings.
618 * Eifel blocks mdev updates when rtt decreases.
619 * This solution is a bit different: we use finer gain
620 * for mdev in this case (alpha*beta).
621 * Like Eifel it also prevents growth of rto,
622 * but also it limits too fast rto decreases,
623 * happening in pure Eifel.
628 m -= (tp->mdev >> 2); /* similar update on mdev */
630 tp->mdev += m; /* mdev = 3/4 mdev + 1/4 new */
631 if (tp->mdev > tp->mdev_max) {
632 tp->mdev_max = tp->mdev;
633 if (tp->mdev_max > tp->rttvar)
634 tp->rttvar = tp->mdev_max;
636 if (after(tp->snd_una, tp->rtt_seq)) {
637 if (tp->mdev_max < tp->rttvar)
638 tp->rttvar -= (tp->rttvar-tp->mdev_max)>>2;
639 tp->rtt_seq = tp->snd_nxt;
640 tp->mdev_max = TCP_RTO_MIN;
643 /* no previous measure. */
644 tp->srtt = m<<3; /* take the measured time to be rtt */
645 tp->mdev = m<<1; /* make sure rto = 3*rtt */
646 tp->mdev_max = tp->rttvar = max(tp->mdev, TCP_RTO_MIN);
647 tp->rtt_seq = tp->snd_nxt;
650 tcp_westwood_update_rtt(tp, tp->srtt >> 3);
653 /* Calculate rto without backoff. This is the second half of Van Jacobson's
654 * routine referred to above.
656 static __inline__ void tcp_set_rto(struct tcp_opt *tp)
658 /* Old crap is replaced with new one. 8)
661 * 1. If rtt variance happened to be less 50msec, it is hallucination.
662 * It cannot be less due to utterly erratic ACK generation made
663 * at least by solaris and freebsd. "Erratic ACKs" has _nothing_
664 * to do with delayed acks, because at cwnd>2 true delack timeout
665 * is invisible. Actually, Linux-2.4 also generates erratic
666 * ACKs in some curcumstances.
668 tp->rto = (tp->srtt >> 3) + tp->rttvar;
670 /* 2. Fixups made earlier cannot be right.
671 * If we do not estimate RTO correctly without them,
672 * all the algo is pure shit and should be replaced
673 * with correct one. It is exaclty, which we pretend to do.
677 /* NOTE: clamping at TCP_RTO_MIN is not required, current algo
678 * guarantees that rto is higher.
680 static __inline__ void tcp_bound_rto(struct tcp_opt *tp)
682 if (tp->rto > TCP_RTO_MAX)
683 tp->rto = TCP_RTO_MAX;
686 /* Save metrics learned by this TCP session.
687 This function is called only, when TCP finishes successfully
688 i.e. when it enters TIME-WAIT or goes from LAST-ACK to CLOSE.
690 void tcp_update_metrics(struct sock *sk)
692 struct tcp_opt *tp = tcp_sk(sk);
693 struct dst_entry *dst = __sk_dst_get(sk);
695 if (sysctl_tcp_nometrics_save)
700 if (dst && (dst->flags&DST_HOST)) {
703 if (tp->backoff || !tp->srtt) {
704 /* This session failed to estimate rtt. Why?
705 * Probably, no packets returned in time.
708 if (!(dst_metric_locked(dst, RTAX_RTT)))
709 dst->metrics[RTAX_RTT-1] = 0;
713 m = dst_metric(dst, RTAX_RTT) - tp->srtt;
715 /* If newly calculated rtt larger than stored one,
716 * store new one. Otherwise, use EWMA. Remember,
717 * rtt overestimation is always better than underestimation.
719 if (!(dst_metric_locked(dst, RTAX_RTT))) {
721 dst->metrics[RTAX_RTT-1] = tp->srtt;
723 dst->metrics[RTAX_RTT-1] -= (m>>3);
726 if (!(dst_metric_locked(dst, RTAX_RTTVAR))) {
730 /* Scale deviation to rttvar fixed point */
735 if (m >= dst_metric(dst, RTAX_RTTVAR))
736 dst->metrics[RTAX_RTTVAR-1] = m;
738 dst->metrics[RTAX_RTTVAR-1] -=
739 (dst->metrics[RTAX_RTTVAR-1] - m)>>2;
742 if (tp->snd_ssthresh >= 0xFFFF) {
743 /* Slow start still did not finish. */
744 if (dst_metric(dst, RTAX_SSTHRESH) &&
745 !dst_metric_locked(dst, RTAX_SSTHRESH) &&
746 (tp->snd_cwnd >> 1) > dst_metric(dst, RTAX_SSTHRESH))
747 dst->metrics[RTAX_SSTHRESH-1] = tp->snd_cwnd >> 1;
748 if (!dst_metric_locked(dst, RTAX_CWND) &&
749 tp->snd_cwnd > dst_metric(dst, RTAX_CWND))
750 dst->metrics[RTAX_CWND-1] = tp->snd_cwnd;
751 } else if (tp->snd_cwnd > tp->snd_ssthresh &&
752 tp->ca_state == TCP_CA_Open) {
753 /* Cong. avoidance phase, cwnd is reliable. */
754 if (!dst_metric_locked(dst, RTAX_SSTHRESH))
755 dst->metrics[RTAX_SSTHRESH-1] =
756 max(tp->snd_cwnd >> 1, tp->snd_ssthresh);
757 if (!dst_metric_locked(dst, RTAX_CWND))
758 dst->metrics[RTAX_CWND-1] = (dst->metrics[RTAX_CWND-1] + tp->snd_cwnd) >> 1;
760 /* Else slow start did not finish, cwnd is non-sense,
761 ssthresh may be also invalid.
763 if (!dst_metric_locked(dst, RTAX_CWND))
764 dst->metrics[RTAX_CWND-1] = (dst->metrics[RTAX_CWND-1] + tp->snd_ssthresh) >> 1;
765 if (dst->metrics[RTAX_SSTHRESH-1] &&
766 !dst_metric_locked(dst, RTAX_SSTHRESH) &&
767 tp->snd_ssthresh > dst->metrics[RTAX_SSTHRESH-1])
768 dst->metrics[RTAX_SSTHRESH-1] = tp->snd_ssthresh;
771 if (!dst_metric_locked(dst, RTAX_REORDERING)) {
772 if (dst->metrics[RTAX_REORDERING-1] < tp->reordering &&
773 tp->reordering != sysctl_tcp_reordering)
774 dst->metrics[RTAX_REORDERING-1] = tp->reordering;
779 /* Numbers are taken from RFC2414. */
780 __u32 tcp_init_cwnd(struct tcp_opt *tp, struct dst_entry *dst)
782 __u32 cwnd = (dst ? dst_metric(dst, RTAX_INITCWND) : 0);
785 if (tp->mss_cache > 1460)
788 cwnd = (tp->mss_cache > 1095) ? 3 : 4;
790 return min_t(__u32, cwnd, tp->snd_cwnd_clamp);
793 /* Initialize metrics on socket. */
795 static void tcp_init_metrics(struct sock *sk)
797 struct tcp_opt *tp = tcp_sk(sk);
798 struct dst_entry *dst = __sk_dst_get(sk);
805 if (dst_metric_locked(dst, RTAX_CWND))
806 tp->snd_cwnd_clamp = dst_metric(dst, RTAX_CWND);
807 if (dst_metric(dst, RTAX_SSTHRESH)) {
808 tp->snd_ssthresh = dst_metric(dst, RTAX_SSTHRESH);
809 if (tp->snd_ssthresh > tp->snd_cwnd_clamp)
810 tp->snd_ssthresh = tp->snd_cwnd_clamp;
812 if (dst_metric(dst, RTAX_REORDERING) &&
813 tp->reordering != dst_metric(dst, RTAX_REORDERING)) {
815 tp->reordering = dst_metric(dst, RTAX_REORDERING);
818 if (dst_metric(dst, RTAX_RTT) == 0)
821 if (!tp->srtt && dst_metric(dst, RTAX_RTT) < (TCP_TIMEOUT_INIT << 3))
824 /* Initial rtt is determined from SYN,SYN-ACK.
825 * The segment is small and rtt may appear much
826 * less than real one. Use per-dst memory
827 * to make it more realistic.
829 * A bit of theory. RTT is time passed after "normal" sized packet
830 * is sent until it is ACKed. In normal curcumstances sending small
831 * packets force peer to delay ACKs and calculation is correct too.
832 * The algorithm is adaptive and, provided we follow specs, it
833 * NEVER underestimate RTT. BUT! If peer tries to make some clever
834 * tricks sort of "quick acks" for time long enough to decrease RTT
835 * to low value, and then abruptly stops to do it and starts to delay
836 * ACKs, wait for troubles.
838 if (dst_metric(dst, RTAX_RTT) > tp->srtt)
839 tp->srtt = dst_metric(dst, RTAX_RTT);
840 if (dst_metric(dst, RTAX_RTTVAR) > tp->mdev) {
841 tp->mdev = dst_metric(dst, RTAX_RTTVAR);
842 tp->mdev_max = tp->rttvar = max(tp->mdev, TCP_RTO_MIN);
846 if (tp->rto < TCP_TIMEOUT_INIT && !tp->saw_tstamp)
848 tp->snd_cwnd = tcp_init_cwnd(tp, dst);
849 tp->snd_cwnd_stamp = tcp_time_stamp;
853 /* Play conservative. If timestamps are not
854 * supported, TCP will fail to recalculate correct
855 * rtt, if initial rto is too small. FORGET ALL AND RESET!
857 if (!tp->saw_tstamp && tp->srtt) {
859 tp->mdev = tp->mdev_max = tp->rttvar = TCP_TIMEOUT_INIT;
860 tp->rto = TCP_TIMEOUT_INIT;
864 static void tcp_update_reordering(struct tcp_opt *tp, int metric, int ts)
866 if (metric > tp->reordering) {
867 tp->reordering = min(TCP_MAX_REORDERING, metric);
869 /* This exciting event is worth to be remembered. 8) */
871 NET_INC_STATS_BH(TCPTSReorder);
873 NET_INC_STATS_BH(TCPRenoReorder);
875 NET_INC_STATS_BH(TCPFACKReorder);
877 NET_INC_STATS_BH(TCPSACKReorder);
878 #if FASTRETRANS_DEBUG > 1
879 printk(KERN_DEBUG "Disorder%d %d %u f%u s%u rr%d\n",
880 tp->sack_ok, tp->ca_state,
881 tp->reordering, tp->fackets_out, tp->sacked_out,
882 tp->undo_marker ? tp->undo_retrans : 0);
884 /* Disable FACK yet. */
889 /* This procedure tags the retransmission queue when SACKs arrive.
891 * We have three tag bits: SACKED(S), RETRANS(R) and LOST(L).
892 * Packets in queue with these bits set are counted in variables
893 * sacked_out, retrans_out and lost_out, correspondingly.
895 * Valid combinations are:
896 * Tag InFlight Description
897 * 0 1 - orig segment is in flight.
898 * S 0 - nothing flies, orig reached receiver.
899 * L 0 - nothing flies, orig lost by net.
900 * R 2 - both orig and retransmit are in flight.
901 * L|R 1 - orig is lost, retransmit is in flight.
902 * S|R 1 - orig reached receiver, retrans is still in flight.
903 * (L|S|R is logically valid, it could occur when L|R is sacked,
904 * but it is equivalent to plain S and code short-curcuits it to S.
905 * L|S is logically invalid, it would mean -1 packet in flight 8))
907 * These 6 states form finite state machine, controlled by the following events:
908 * 1. New ACK (+SACK) arrives. (tcp_sacktag_write_queue())
909 * 2. Retransmission. (tcp_retransmit_skb(), tcp_xmit_retransmit_queue())
910 * 3. Loss detection event of one of three flavors:
911 * A. Scoreboard estimator decided the packet is lost.
912 * A'. Reno "three dupacks" marks head of queue lost.
913 * A''. Its FACK modfication, head until snd.fack is lost.
914 * B. SACK arrives sacking data transmitted after never retransmitted
916 * C. SACK arrives sacking SND.NXT at the moment, when the
917 * segment was retransmitted.
918 * 4. D-SACK added new rule: D-SACK changes any tag to S.
920 * It is pleasant to note, that state diagram turns out to be commutative,
921 * so that we are allowed not to be bothered by order of our actions,
922 * when multiple events arrive simultaneously. (see the function below).
924 * Reordering detection.
925 * --------------------
926 * Reordering metric is maximal distance, which a packet can be displaced
927 * in packet stream. With SACKs we can estimate it:
929 * 1. SACK fills old hole and the corresponding segment was not
930 * ever retransmitted -> reordering. Alas, we cannot use it
931 * when segment was retransmitted.
932 * 2. The last flaw is solved with D-SACK. D-SACK arrives
933 * for retransmitted and already SACKed segment -> reordering..
934 * Both of these heuristics are not used in Loss state, when we cannot
935 * account for retransmits accurately.
938 tcp_sacktag_write_queue(struct sock *sk, struct sk_buff *ack_skb, u32 prior_snd_una)
940 struct tcp_opt *tp = tcp_sk(sk);
941 unsigned char *ptr = ack_skb->h.raw + TCP_SKB_CB(ack_skb)->sacked;
942 struct tcp_sack_block *sp = (struct tcp_sack_block *)(ptr+2);
943 int num_sacks = (ptr[1] - TCPOLEN_SACK_BASE)>>3;
944 int reord = tp->packets_out;
946 u32 lost_retrans = 0;
950 /* So, SACKs for already sent large segments will be lost.
951 * Not good, but alternative is to resegment the queue. */
952 if (sk->sk_route_caps & NETIF_F_TSO) {
953 sk->sk_route_caps &= ~NETIF_F_TSO;
954 sk->sk_no_largesend = 1;
955 tp->mss_cache = tp->mss_cache_std;
960 prior_fackets = tp->fackets_out;
962 for (i=0; i<num_sacks; i++, sp++) {
964 __u32 start_seq = ntohl(sp->start_seq);
965 __u32 end_seq = ntohl(sp->end_seq);
969 /* Check for D-SACK. */
971 u32 ack = TCP_SKB_CB(ack_skb)->ack_seq;
973 if (before(start_seq, ack)) {
976 NET_INC_STATS_BH(TCPDSACKRecv);
977 } else if (num_sacks > 1 &&
978 !after(end_seq, ntohl(sp[1].end_seq)) &&
979 !before(start_seq, ntohl(sp[1].start_seq))) {
982 NET_INC_STATS_BH(TCPDSACKOfoRecv);
985 /* D-SACK for already forgotten data...
986 * Do dumb counting. */
988 !after(end_seq, prior_snd_una) &&
989 after(end_seq, tp->undo_marker))
992 /* Eliminate too old ACKs, but take into
993 * account more or less fresh ones, they can
994 * contain valid SACK info.
996 if (before(ack, prior_snd_una - tp->max_window))
1000 /* Event "B" in the comment above. */
1001 if (after(end_seq, tp->high_seq))
1002 flag |= FLAG_DATA_LOST;
1004 for_retrans_queue(skb, sk, tp) {
1005 u8 sacked = TCP_SKB_CB(skb)->sacked;
1008 /* The retransmission queue is always in order, so
1009 * we can short-circuit the walk early.
1011 if(!before(TCP_SKB_CB(skb)->seq, end_seq))
1016 in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
1017 !before(end_seq, TCP_SKB_CB(skb)->end_seq);
1019 /* Account D-SACK for retransmitted packet. */
1020 if ((dup_sack && in_sack) &&
1021 (sacked & TCPCB_RETRANS) &&
1022 after(TCP_SKB_CB(skb)->end_seq, tp->undo_marker))
1025 /* The frame is ACKed. */
1026 if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una)) {
1027 if (sacked&TCPCB_RETRANS) {
1028 if ((dup_sack && in_sack) &&
1029 (sacked&TCPCB_SACKED_ACKED))
1030 reord = min(fack_count, reord);
1032 /* If it was in a hole, we detected reordering. */
1033 if (fack_count < prior_fackets &&
1034 !(sacked&TCPCB_SACKED_ACKED))
1035 reord = min(fack_count, reord);
1038 /* Nothing to do; acked frame is about to be dropped. */
1042 if ((sacked&TCPCB_SACKED_RETRANS) &&
1043 after(end_seq, TCP_SKB_CB(skb)->ack_seq) &&
1044 (!lost_retrans || after(end_seq, lost_retrans)))
1045 lost_retrans = end_seq;
1050 if (!(sacked&TCPCB_SACKED_ACKED)) {
1051 if (sacked & TCPCB_SACKED_RETRANS) {
1052 /* If the segment is not tagged as lost,
1053 * we do not clear RETRANS, believing
1054 * that retransmission is still in flight.
1056 if (sacked & TCPCB_LOST) {
1057 TCP_SKB_CB(skb)->sacked &= ~(TCPCB_LOST|TCPCB_SACKED_RETRANS);
1062 /* New sack for not retransmitted frame,
1063 * which was in hole. It is reordering.
1065 if (!(sacked & TCPCB_RETRANS) &&
1066 fack_count < prior_fackets)
1067 reord = min(fack_count, reord);
1069 if (sacked & TCPCB_LOST) {
1070 TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
1075 TCP_SKB_CB(skb)->sacked |= TCPCB_SACKED_ACKED;
1076 flag |= FLAG_DATA_SACKED;
1079 if (fack_count > tp->fackets_out)
1080 tp->fackets_out = fack_count;
1082 if (dup_sack && (sacked&TCPCB_RETRANS))
1083 reord = min(fack_count, reord);
1086 /* D-SACK. We can detect redundant retransmission
1087 * in S|R and plain R frames and clear it.
1088 * undo_retrans is decreased above, L|R frames
1089 * are accounted above as well.
1092 (TCP_SKB_CB(skb)->sacked&TCPCB_SACKED_RETRANS)) {
1093 TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
1099 /* Check for lost retransmit. This superb idea is
1100 * borrowed from "ratehalving". Event "C".
1101 * Later note: FACK people cheated me again 8),
1102 * we have to account for reordering! Ugly,
1105 if (lost_retrans && tp->ca_state == TCP_CA_Recovery) {
1106 struct sk_buff *skb;
1108 for_retrans_queue(skb, sk, tp) {
1109 if (after(TCP_SKB_CB(skb)->seq, lost_retrans))
1111 if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una))
1113 if ((TCP_SKB_CB(skb)->sacked&TCPCB_SACKED_RETRANS) &&
1114 after(lost_retrans, TCP_SKB_CB(skb)->ack_seq) &&
1116 !before(lost_retrans,
1117 TCP_SKB_CB(skb)->ack_seq + tp->reordering *
1119 TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
1122 if (!(TCP_SKB_CB(skb)->sacked&(TCPCB_LOST|TCPCB_SACKED_ACKED))) {
1124 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1125 flag |= FLAG_DATA_SACKED;
1126 NET_INC_STATS_BH(TCPLostRetransmit);
1132 tp->left_out = tp->sacked_out + tp->lost_out;
1134 if (reord < tp->fackets_out && tp->ca_state != TCP_CA_Loss)
1135 tcp_update_reordering(tp, (tp->fackets_out + 1) - reord, 0);
1137 #if FASTRETRANS_DEBUG > 0
1138 BUG_TRAP((int)tp->sacked_out >= 0);
1139 BUG_TRAP((int)tp->lost_out >= 0);
1140 BUG_TRAP((int)tp->retrans_out >= 0);
1141 BUG_TRAP((int)tcp_packets_in_flight(tp) >= 0);
1146 /* RTO occurred, but do not yet enter loss state. Instead, transmit two new
1147 * segments to see from the next ACKs whether any data was really missing.
1148 * If the RTO was spurious, new ACKs should arrive.
1150 void tcp_enter_frto(struct sock *sk)
1152 struct tcp_opt *tp = tcp_sk(sk);
1153 struct sk_buff *skb;
1155 tp->frto_counter = 1;
1157 if (tp->ca_state <= TCP_CA_Disorder ||
1158 tp->snd_una == tp->high_seq ||
1159 (tp->ca_state == TCP_CA_Loss && !tp->retransmits)) {
1160 tp->prior_ssthresh = tcp_current_ssthresh(tp);
1161 if (!tcp_westwood_ssthresh(tp))
1162 tp->snd_ssthresh = tcp_recalc_ssthresh(tp);
1165 /* Have to clear retransmission markers here to keep the bookkeeping
1166 * in shape, even though we are not yet in Loss state.
1167 * If something was really lost, it is eventually caught up
1168 * in tcp_enter_frto_loss.
1170 tp->retrans_out = 0;
1171 tp->undo_marker = tp->snd_una;
1172 tp->undo_retrans = 0;
1174 for_retrans_queue(skb, sk, tp) {
1175 TCP_SKB_CB(skb)->sacked &= ~TCPCB_RETRANS;
1177 tcp_sync_left_out(tp);
1179 tcp_set_ca_state(tp, TCP_CA_Open);
1180 tp->frto_highmark = tp->snd_nxt;
1183 /* Enter Loss state after F-RTO was applied. Dupack arrived after RTO,
1184 * which indicates that we should follow the traditional RTO recovery,
1185 * i.e. mark everything lost and do go-back-N retransmission.
1187 static void tcp_enter_frto_loss(struct sock *sk)
1189 struct tcp_opt *tp = tcp_sk(sk);
1190 struct sk_buff *skb;
1195 tp->fackets_out = 0;
1197 for_retrans_queue(skb, sk, tp) {
1199 TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
1200 if (!(TCP_SKB_CB(skb)->sacked&TCPCB_SACKED_ACKED)) {
1202 /* Do not mark those segments lost that were
1203 * forward transmitted after RTO
1205 if(!after(TCP_SKB_CB(skb)->end_seq,
1206 tp->frto_highmark)) {
1207 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1212 tp->fackets_out = cnt;
1215 tcp_sync_left_out(tp);
1217 tp->snd_cwnd = tp->frto_counter + tcp_packets_in_flight(tp)+1;
1218 tp->snd_cwnd_cnt = 0;
1219 tp->snd_cwnd_stamp = tcp_time_stamp;
1220 tp->undo_marker = 0;
1221 tp->frto_counter = 0;
1223 tp->reordering = min_t(unsigned int, tp->reordering,
1224 sysctl_tcp_reordering);
1225 tcp_set_ca_state(tp, TCP_CA_Loss);
1226 tp->high_seq = tp->frto_highmark;
1227 TCP_ECN_queue_cwr(tp);
1230 void tcp_clear_retrans(struct tcp_opt *tp)
1233 tp->retrans_out = 0;
1235 tp->fackets_out = 0;
1239 tp->undo_marker = 0;
1240 tp->undo_retrans = 0;
1243 /* Enter Loss state. If "how" is not zero, forget all SACK information
1244 * and reset tags completely, otherwise preserve SACKs. If receiver
1245 * dropped its ofo queue, we will know this due to reneging detection.
1247 void tcp_enter_loss(struct sock *sk, int how)
1249 struct tcp_opt *tp = tcp_sk(sk);
1250 struct sk_buff *skb;
1253 /* Reduce ssthresh if it has not yet been made inside this window. */
1254 if (tp->ca_state <= TCP_CA_Disorder || tp->snd_una == tp->high_seq ||
1255 (tp->ca_state == TCP_CA_Loss && !tp->retransmits)) {
1256 tp->prior_ssthresh = tcp_current_ssthresh(tp);
1257 tp->snd_ssthresh = tcp_recalc_ssthresh(tp);
1260 tp->snd_cwnd_cnt = 0;
1261 tp->snd_cwnd_stamp = tcp_time_stamp;
1263 tcp_clear_retrans(tp);
1265 /* Push undo marker, if it was plain RTO and nothing
1266 * was retransmitted. */
1268 tp->undo_marker = tp->snd_una;
1270 for_retrans_queue(skb, sk, tp) {
1272 if (TCP_SKB_CB(skb)->sacked&TCPCB_RETRANS)
1273 tp->undo_marker = 0;
1274 TCP_SKB_CB(skb)->sacked &= (~TCPCB_TAGBITS)|TCPCB_SACKED_ACKED;
1275 if (!(TCP_SKB_CB(skb)->sacked&TCPCB_SACKED_ACKED) || how) {
1276 TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_ACKED;
1277 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1281 tp->fackets_out = cnt;
1284 tcp_sync_left_out(tp);
1286 tp->reordering = min_t(unsigned int, tp->reordering,
1287 sysctl_tcp_reordering);
1288 tcp_set_ca_state(tp, TCP_CA_Loss);
1289 tp->high_seq = tp->snd_nxt;
1290 TCP_ECN_queue_cwr(tp);
1293 static int tcp_check_sack_reneging(struct sock *sk, struct tcp_opt *tp)
1295 struct sk_buff *skb;
1297 /* If ACK arrived pointing to a remembered SACK,
1298 * it means that our remembered SACKs do not reflect
1299 * real state of receiver i.e.
1300 * receiver _host_ is heavily congested (or buggy).
1301 * Do processing similar to RTO timeout.
1303 if ((skb = skb_peek(&sk->sk_write_queue)) != NULL &&
1304 (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)) {
1305 NET_INC_STATS_BH(TCPSACKReneging);
1307 tcp_enter_loss(sk, 1);
1309 tcp_retransmit_skb(sk, skb_peek(&sk->sk_write_queue));
1310 tcp_reset_xmit_timer(sk, TCP_TIME_RETRANS, tp->rto);
1316 static inline int tcp_fackets_out(struct tcp_opt *tp)
1318 return IsReno(tp) ? tp->sacked_out+1 : tp->fackets_out;
1321 static inline int tcp_skb_timedout(struct tcp_opt *tp, struct sk_buff *skb)
1323 return (tcp_time_stamp - TCP_SKB_CB(skb)->when > tp->rto);
1326 static inline int tcp_head_timedout(struct sock *sk, struct tcp_opt *tp)
1328 return tp->packets_out &&
1329 tcp_skb_timedout(tp, skb_peek(&sk->sk_write_queue));
1332 /* Linux NewReno/SACK/FACK/ECN state machine.
1333 * --------------------------------------
1335 * "Open" Normal state, no dubious events, fast path.
1336 * "Disorder" In all the respects it is "Open",
1337 * but requires a bit more attention. It is entered when
1338 * we see some SACKs or dupacks. It is split of "Open"
1339 * mainly to move some processing from fast path to slow one.
1340 * "CWR" CWND was reduced due to some Congestion Notification event.
1341 * It can be ECN, ICMP source quench, local device congestion.
1342 * "Recovery" CWND was reduced, we are fast-retransmitting.
1343 * "Loss" CWND was reduced due to RTO timeout or SACK reneging.
1345 * tcp_fastretrans_alert() is entered:
1346 * - each incoming ACK, if state is not "Open"
1347 * - when arrived ACK is unusual, namely:
1352 * Counting packets in flight is pretty simple.
1354 * in_flight = packets_out - left_out + retrans_out
1356 * packets_out is SND.NXT-SND.UNA counted in packets.
1358 * retrans_out is number of retransmitted segments.
1360 * left_out is number of segments left network, but not ACKed yet.
1362 * left_out = sacked_out + lost_out
1364 * sacked_out: Packets, which arrived to receiver out of order
1365 * and hence not ACKed. With SACKs this number is simply
1366 * amount of SACKed data. Even without SACKs
1367 * it is easy to give pretty reliable estimate of this number,
1368 * counting duplicate ACKs.
1370 * lost_out: Packets lost by network. TCP has no explicit
1371 * "loss notification" feedback from network (for now).
1372 * It means that this number can be only _guessed_.
1373 * Actually, it is the heuristics to predict lossage that
1374 * distinguishes different algorithms.
1376 * F.e. after RTO, when all the queue is considered as lost,
1377 * lost_out = packets_out and in_flight = retrans_out.
1379 * Essentially, we have now two algorithms counting
1382 * FACK: It is the simplest heuristics. As soon as we decided
1383 * that something is lost, we decide that _all_ not SACKed
1384 * packets until the most forward SACK are lost. I.e.
1385 * lost_out = fackets_out - sacked_out and left_out = fackets_out.
1386 * It is absolutely correct estimate, if network does not reorder
1387 * packets. And it loses any connection to reality when reordering
1388 * takes place. We use FACK by default until reordering
1389 * is suspected on the path to this destination.
1391 * NewReno: when Recovery is entered, we assume that one segment
1392 * is lost (classic Reno). While we are in Recovery and
1393 * a partial ACK arrives, we assume that one more packet
1394 * is lost (NewReno). This heuristics are the same in NewReno
1397 * Imagine, that's all! Forget about all this shamanism about CWND inflation
1398 * deflation etc. CWND is real congestion window, never inflated, changes
1399 * only according to classic VJ rules.
1401 * Really tricky (and requiring careful tuning) part of algorithm
1402 * is hidden in functions tcp_time_to_recover() and tcp_xmit_retransmit_queue().
1403 * The first determines the moment _when_ we should reduce CWND and,
1404 * hence, slow down forward transmission. In fact, it determines the moment
1405 * when we decide that hole is caused by loss, rather than by a reorder.
1407 * tcp_xmit_retransmit_queue() decides, _what_ we should retransmit to fill
1408 * holes, caused by lost packets.
1410 * And the most logically complicated part of algorithm is undo
1411 * heuristics. We detect false retransmits due to both too early
1412 * fast retransmit (reordering) and underestimated RTO, analyzing
1413 * timestamps and D-SACKs. When we detect that some segments were
1414 * retransmitted by mistake and CWND reduction was wrong, we undo
1415 * window reduction and abort recovery phase. This logic is hidden
1416 * inside several functions named tcp_try_undo_<something>.
1419 /* This function decides, when we should leave Disordered state
1420 * and enter Recovery phase, reducing congestion window.
1422 * Main question: may we further continue forward transmission
1423 * with the same cwnd?
1426 tcp_time_to_recover(struct sock *sk, struct tcp_opt *tp)
1428 /* Trick#1: The loss is proven. */
1432 /* Not-A-Trick#2 : Classic rule... */
1433 if (tcp_fackets_out(tp) > tp->reordering)
1436 /* Trick#3 : when we use RFC2988 timer restart, fast
1437 * retransmit can be triggered by timeout of queue head.
1439 if (tcp_head_timedout(sk, tp))
1442 /* Trick#4: It is still not OK... But will it be useful to delay
1445 if (tp->packets_out <= tp->reordering &&
1446 tp->sacked_out >= max_t(__u32, tp->packets_out/2, sysctl_tcp_reordering) &&
1447 !tcp_may_send_now(sk, tp)) {
1448 /* We have nothing to send. This connection is limited
1449 * either by receiver window or by application.
1457 /* If we receive more dupacks than we expected counting segments
1458 * in assumption of absent reordering, interpret this as reordering.
1459 * The only another reason could be bug in receiver TCP.
1461 static void tcp_check_reno_reordering(struct tcp_opt *tp, int addend)
1465 holes = max(tp->lost_out, 1U);
1466 holes = min(holes, tp->packets_out);
1468 if (tp->sacked_out + holes > tp->packets_out) {
1469 tp->sacked_out = tp->packets_out - holes;
1470 tcp_update_reordering(tp, tp->packets_out+addend, 0);
1474 /* Emulate SACKs for SACKless connection: account for a new dupack. */
1476 static void tcp_add_reno_sack(struct tcp_opt *tp)
1479 tcp_check_reno_reordering(tp, 0);
1480 tcp_sync_left_out(tp);
1483 /* Account for ACK, ACKing some data in Reno Recovery phase. */
1485 static void tcp_remove_reno_sacks(struct sock *sk, struct tcp_opt *tp, int acked)
1488 /* One ACK acked hole. The rest eat duplicate ACKs. */
1489 if (acked-1 >= tp->sacked_out)
1492 tp->sacked_out -= acked-1;
1494 tcp_check_reno_reordering(tp, acked);
1495 tcp_sync_left_out(tp);
1498 static inline void tcp_reset_reno_sack(struct tcp_opt *tp)
1501 tp->left_out = tp->lost_out;
1504 /* Mark head of queue up as lost. */
1506 tcp_mark_head_lost(struct sock *sk, struct tcp_opt *tp, int packets, u32 high_seq)
1508 struct sk_buff *skb;
1511 BUG_TRAP(cnt <= tp->packets_out);
1513 for_retrans_queue(skb, sk, tp) {
1514 if (--cnt < 0 || after(TCP_SKB_CB(skb)->end_seq, high_seq))
1516 if (!(TCP_SKB_CB(skb)->sacked&TCPCB_TAGBITS)) {
1517 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1521 tcp_sync_left_out(tp);
1524 /* Account newly detected lost packet(s) */
1526 static void tcp_update_scoreboard(struct sock *sk, struct tcp_opt *tp)
1529 int lost = tp->fackets_out - tp->reordering;
1532 tcp_mark_head_lost(sk, tp, lost, tp->high_seq);
1534 tcp_mark_head_lost(sk, tp, 1, tp->high_seq);
1537 /* New heuristics: it is possible only after we switched
1538 * to restart timer each time when something is ACKed.
1539 * Hence, we can detect timed out packets during fast
1540 * retransmit without falling to slow start.
1542 if (tcp_head_timedout(sk, tp)) {
1543 struct sk_buff *skb;
1545 for_retrans_queue(skb, sk, tp) {
1546 if (tcp_skb_timedout(tp, skb) &&
1547 !(TCP_SKB_CB(skb)->sacked&TCPCB_TAGBITS)) {
1548 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1552 tcp_sync_left_out(tp);
1556 /* CWND moderation, preventing bursts due to too big ACKs
1557 * in dubious situations.
1559 static __inline__ void tcp_moderate_cwnd(struct tcp_opt *tp)
1561 tp->snd_cwnd = min(tp->snd_cwnd,
1562 tcp_packets_in_flight(tp)+tcp_max_burst(tp));
1563 tp->snd_cwnd_stamp = tcp_time_stamp;
1566 /* Decrease cwnd each second ack. */
1568 static void tcp_cwnd_down(struct tcp_opt *tp)
1570 int decr = tp->snd_cwnd_cnt + 1;
1575 * Here limit is evaluated as BWestimation*RTTmin (for obtaining it
1576 * in packets we use mss_cache). If sysctl_tcp_westwood is off
1577 * tcp_westwood_bw_rttmin() returns 0. In such case snd_ssthresh is
1578 * still used as usual. It prevents other strange cases in which
1579 * BWE*RTTmin could assume value 0. It should not happen but...
1582 if (!(limit = tcp_westwood_bw_rttmin(tp)))
1583 limit = tp->snd_ssthresh/2;
1585 tp->snd_cwnd_cnt = decr&1;
1588 if (decr && tp->snd_cwnd > limit)
1589 tp->snd_cwnd -= decr;
1591 tp->snd_cwnd = min(tp->snd_cwnd, tcp_packets_in_flight(tp)+1);
1592 tp->snd_cwnd_stamp = tcp_time_stamp;
1595 /* Nothing was retransmitted or returned timestamp is less
1596 * than timestamp of the first retransmission.
1598 static __inline__ int tcp_packet_delayed(struct tcp_opt *tp)
1600 return !tp->retrans_stamp ||
1601 (tp->saw_tstamp && tp->rcv_tsecr &&
1602 (__s32)(tp->rcv_tsecr - tp->retrans_stamp) < 0);
1605 /* Undo procedures. */
1607 #if FASTRETRANS_DEBUG > 1
1608 static void DBGUNDO(struct sock *sk, struct tcp_opt *tp, const char *msg)
1610 struct inet_opt *inet = inet_sk(sk);
1611 printk(KERN_DEBUG "Undo %s %u.%u.%u.%u/%u c%u l%u ss%u/%u p%u\n",
1613 NIPQUAD(inet->daddr), ntohs(inet->dport),
1614 tp->snd_cwnd, tp->left_out,
1615 tp->snd_ssthresh, tp->prior_ssthresh, tp->packets_out);
1618 #define DBGUNDO(x...) do { } while (0)
1621 static void tcp_undo_cwr(struct tcp_opt *tp, int undo)
1623 if (tp->prior_ssthresh) {
1624 tp->snd_cwnd = max(tp->snd_cwnd, tp->snd_ssthresh<<1);
1626 if (undo && tp->prior_ssthresh > tp->snd_ssthresh) {
1627 tp->snd_ssthresh = tp->prior_ssthresh;
1628 TCP_ECN_withdraw_cwr(tp);
1631 tp->snd_cwnd = max(tp->snd_cwnd, tp->snd_ssthresh);
1633 tcp_moderate_cwnd(tp);
1634 tp->snd_cwnd_stamp = tcp_time_stamp;
1637 static inline int tcp_may_undo(struct tcp_opt *tp)
1639 return tp->undo_marker &&
1640 (!tp->undo_retrans || tcp_packet_delayed(tp));
1643 /* People celebrate: "We love our President!" */
1644 static int tcp_try_undo_recovery(struct sock *sk, struct tcp_opt *tp)
1646 if (tcp_may_undo(tp)) {
1647 /* Happy end! We did not retransmit anything
1648 * or our original transmission succeeded.
1650 DBGUNDO(sk, tp, tp->ca_state == TCP_CA_Loss ? "loss" : "retrans");
1651 tcp_undo_cwr(tp, 1);
1652 if (tp->ca_state == TCP_CA_Loss)
1653 NET_INC_STATS_BH(TCPLossUndo);
1655 NET_INC_STATS_BH(TCPFullUndo);
1656 tp->undo_marker = 0;
1658 if (tp->snd_una == tp->high_seq && IsReno(tp)) {
1659 /* Hold old state until something *above* high_seq
1660 * is ACKed. For Reno it is MUST to prevent false
1661 * fast retransmits (RFC2582). SACK TCP is safe. */
1662 tcp_moderate_cwnd(tp);
1665 tcp_set_ca_state(tp, TCP_CA_Open);
1669 /* Try to undo cwnd reduction, because D-SACKs acked all retransmitted data */
1670 static void tcp_try_undo_dsack(struct sock *sk, struct tcp_opt *tp)
1672 if (tp->undo_marker && !tp->undo_retrans) {
1673 DBGUNDO(sk, tp, "D-SACK");
1674 tcp_undo_cwr(tp, 1);
1675 tp->undo_marker = 0;
1676 NET_INC_STATS_BH(TCPDSACKUndo);
1680 /* Undo during fast recovery after partial ACK. */
1682 static int tcp_try_undo_partial(struct sock *sk, struct tcp_opt *tp, int acked)
1684 /* Partial ACK arrived. Force Hoe's retransmit. */
1685 int failed = IsReno(tp) || tp->fackets_out>tp->reordering;
1687 if (tcp_may_undo(tp)) {
1688 /* Plain luck! Hole if filled with delayed
1689 * packet, rather than with a retransmit.
1691 if (tp->retrans_out == 0)
1692 tp->retrans_stamp = 0;
1694 tcp_update_reordering(tp, tcp_fackets_out(tp)+acked, 1);
1696 DBGUNDO(sk, tp, "Hoe");
1697 tcp_undo_cwr(tp, 0);
1698 NET_INC_STATS_BH(TCPPartialUndo);
1700 /* So... Do not make Hoe's retransmit yet.
1701 * If the first packet was delayed, the rest
1702 * ones are most probably delayed as well.
1709 /* Undo during loss recovery after partial ACK. */
1710 static int tcp_try_undo_loss(struct sock *sk, struct tcp_opt *tp)
1712 if (tcp_may_undo(tp)) {
1713 struct sk_buff *skb;
1714 for_retrans_queue(skb, sk, tp) {
1715 TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
1717 DBGUNDO(sk, tp, "partial loss");
1719 tp->left_out = tp->sacked_out;
1720 tcp_undo_cwr(tp, 1);
1721 NET_INC_STATS_BH(TCPLossUndo);
1722 tp->retransmits = 0;
1723 tp->undo_marker = 0;
1725 tcp_set_ca_state(tp, TCP_CA_Open);
1731 static __inline__ void tcp_complete_cwr(struct tcp_opt *tp)
1733 if (tcp_westwood_cwnd(tp))
1734 tp->snd_ssthresh = tp->snd_cwnd;
1736 tp->snd_cwnd = min(tp->snd_cwnd, tp->snd_ssthresh);
1737 tp->snd_cwnd_stamp = tcp_time_stamp;
1740 static void tcp_try_to_open(struct sock *sk, struct tcp_opt *tp, int flag)
1742 tp->left_out = tp->sacked_out;
1744 if (tp->retrans_out == 0)
1745 tp->retrans_stamp = 0;
1750 if (tp->ca_state != TCP_CA_CWR) {
1751 int state = TCP_CA_Open;
1756 state = TCP_CA_Disorder;
1758 if (tp->ca_state != state) {
1759 tcp_set_ca_state(tp, state);
1760 tp->high_seq = tp->snd_nxt;
1762 tcp_moderate_cwnd(tp);
1768 /* Process an event, which can update packets-in-flight not trivially.
1769 * Main goal of this function is to calculate new estimate for left_out,
1770 * taking into account both packets sitting in receiver's buffer and
1771 * packets lost by network.
1773 * Besides that it does CWND reduction, when packet loss is detected
1774 * and changes state of machine.
1776 * It does _not_ decide what to send, it is made in function
1777 * tcp_xmit_retransmit_queue().
1780 tcp_fastretrans_alert(struct sock *sk, u32 prior_snd_una,
1781 int prior_packets, int flag)
1783 struct tcp_opt *tp = tcp_sk(sk);
1784 int is_dupack = (tp->snd_una == prior_snd_una && !(flag&FLAG_NOT_DUP));
1786 /* Some technical things:
1787 * 1. Reno does not count dupacks (sacked_out) automatically. */
1788 if (!tp->packets_out)
1790 /* 2. SACK counts snd_fack in packets inaccurately. */
1791 if (tp->sacked_out == 0)
1792 tp->fackets_out = 0;
1794 /* Now state machine starts.
1795 * A. ECE, hence prohibit cwnd undoing, the reduction is required. */
1797 tp->prior_ssthresh = 0;
1799 /* B. In all the states check for reneging SACKs. */
1800 if (tp->sacked_out && tcp_check_sack_reneging(sk, tp))
1803 /* C. Process data loss notification, provided it is valid. */
1804 if ((flag&FLAG_DATA_LOST) &&
1805 before(tp->snd_una, tp->high_seq) &&
1806 tp->ca_state != TCP_CA_Open &&
1807 tp->fackets_out > tp->reordering) {
1808 tcp_mark_head_lost(sk, tp, tp->fackets_out-tp->reordering, tp->high_seq);
1809 NET_INC_STATS_BH(TCPLoss);
1812 /* D. Synchronize left_out to current state. */
1813 tcp_sync_left_out(tp);
1815 /* E. Check state exit conditions. State can be terminated
1816 * when high_seq is ACKed. */
1817 if (tp->ca_state == TCP_CA_Open) {
1818 if (!sysctl_tcp_frto)
1819 BUG_TRAP(tp->retrans_out == 0);
1820 tp->retrans_stamp = 0;
1821 } else if (!before(tp->snd_una, tp->high_seq)) {
1822 switch (tp->ca_state) {
1824 tp->retransmits = 0;
1825 if (tcp_try_undo_recovery(sk, tp))
1830 /* CWR is to be held something *above* high_seq
1831 * is ACKed for CWR bit to reach receiver. */
1832 if (tp->snd_una != tp->high_seq) {
1833 tcp_complete_cwr(tp);
1834 tcp_set_ca_state(tp, TCP_CA_Open);
1838 case TCP_CA_Disorder:
1839 tcp_try_undo_dsack(sk, tp);
1840 if (!tp->undo_marker ||
1841 /* For SACK case do not Open to allow to undo
1842 * catching for all duplicate ACKs. */
1843 IsReno(tp) || tp->snd_una != tp->high_seq) {
1844 tp->undo_marker = 0;
1845 tcp_set_ca_state(tp, TCP_CA_Open);
1849 case TCP_CA_Recovery:
1851 tcp_reset_reno_sack(tp);
1852 if (tcp_try_undo_recovery(sk, tp))
1854 tcp_complete_cwr(tp);
1859 /* F. Process state. */
1860 switch (tp->ca_state) {
1861 case TCP_CA_Recovery:
1862 if (prior_snd_una == tp->snd_una) {
1863 if (IsReno(tp) && is_dupack)
1864 tcp_add_reno_sack(tp);
1866 int acked = prior_packets - tp->packets_out;
1868 tcp_remove_reno_sacks(sk, tp, acked);
1869 is_dupack = tcp_try_undo_partial(sk, tp, acked);
1873 if (flag&FLAG_DATA_ACKED)
1874 tp->retransmits = 0;
1875 if (!tcp_try_undo_loss(sk, tp)) {
1876 tcp_moderate_cwnd(tp);
1877 tcp_xmit_retransmit_queue(sk);
1880 if (tp->ca_state != TCP_CA_Open)
1882 /* Loss is undone; fall through to processing in Open state. */
1885 if (tp->snd_una != prior_snd_una)
1886 tcp_reset_reno_sack(tp);
1888 tcp_add_reno_sack(tp);
1891 if (tp->ca_state == TCP_CA_Disorder)
1892 tcp_try_undo_dsack(sk, tp);
1894 if (!tcp_time_to_recover(sk, tp)) {
1895 tcp_try_to_open(sk, tp, flag);
1899 /* Otherwise enter Recovery state */
1902 NET_INC_STATS_BH(TCPRenoRecovery);
1904 NET_INC_STATS_BH(TCPSackRecovery);
1906 tp->high_seq = tp->snd_nxt;
1907 tp->prior_ssthresh = 0;
1908 tp->undo_marker = tp->snd_una;
1909 tp->undo_retrans = tp->retrans_out;
1911 if (tp->ca_state < TCP_CA_CWR) {
1912 if (!(flag&FLAG_ECE))
1913 tp->prior_ssthresh = tcp_current_ssthresh(tp);
1914 tp->snd_ssthresh = tcp_recalc_ssthresh(tp);
1915 TCP_ECN_queue_cwr(tp);
1918 tp->snd_cwnd_cnt = 0;
1919 tcp_set_ca_state(tp, TCP_CA_Recovery);
1922 if (is_dupack || tcp_head_timedout(sk, tp))
1923 tcp_update_scoreboard(sk, tp);
1925 tcp_xmit_retransmit_queue(sk);
1928 /* Read draft-ietf-tcplw-high-performance before mucking
1929 * with this code. (Superceeds RFC1323)
1931 static void tcp_ack_saw_tstamp(struct tcp_opt *tp, int flag)
1935 /* RTTM Rule: A TSecr value received in a segment is used to
1936 * update the averaged RTT measurement only if the segment
1937 * acknowledges some new data, i.e., only if it advances the
1938 * left edge of the send window.
1940 * See draft-ietf-tcplw-high-performance-00, section 3.3.
1941 * 1998/04/10 Andrey V. Savochkin <saw@msu.ru>
1943 * Changed: reset backoff as soon as we see the first valid sample.
1944 * If we do not, we get strongly overstimated rto. With timestamps
1945 * samples are accepted even from very old segments: f.e., when rtt=1
1946 * increases to 8, we retransmit 5 times and after 8 seconds delayed
1947 * answer arrives rto becomes 120 seconds! If at least one of segments
1948 * in window is lost... Voila. --ANK (010210)
1950 seq_rtt = tcp_time_stamp - tp->rcv_tsecr;
1951 tcp_rtt_estimator(tp, seq_rtt);
1957 static void tcp_ack_no_tstamp(struct tcp_opt *tp, u32 seq_rtt, int flag)
1959 /* We don't have a timestamp. Can only use
1960 * packets that are not retransmitted to determine
1961 * rtt estimates. Also, we must not reset the
1962 * backoff for rto until we get a non-retransmitted
1963 * packet. This allows us to deal with a situation
1964 * where the network delay has increased suddenly.
1965 * I.e. Karn's algorithm. (SIGCOMM '87, p5.)
1968 if (flag & FLAG_RETRANS_DATA_ACKED)
1971 tcp_rtt_estimator(tp, seq_rtt);
1977 static __inline__ void
1978 tcp_ack_update_rtt(struct tcp_opt *tp, int flag, s32 seq_rtt)
1980 /* Note that peer MAY send zero echo. In this case it is ignored. (rfc1323) */
1981 if (tp->saw_tstamp && tp->rcv_tsecr)
1982 tcp_ack_saw_tstamp(tp, flag);
1983 else if (seq_rtt >= 0)
1984 tcp_ack_no_tstamp(tp, seq_rtt, flag);
1988 * Compute congestion window to use.
1990 * This is from the implementation of BICTCP in
1991 * Lison-Xu, Kahaled Harfoush, and Injog Rhee.
1992 * "Binary Increase Congestion Control for Fast, Long Distance
1993 * Networks" in InfoComm 2004
1995 * http://www.csc.ncsu.edu/faculty/rhee/export/bitcp.pdf
1997 * Unless BIC is enabled and congestion window is large
1998 * this behaves the same as the original Reno.
2000 static inline __u32 bictcp_cwnd(struct tcp_opt *tp)
2002 /* orignal Reno behaviour */
2003 if (!sysctl_tcp_bic)
2004 return tp->snd_cwnd;
2006 if (tp->bictcp.last_cwnd == tp->snd_cwnd)
2007 return tp->bictcp.cnt; /* same cwnd, no update */
2009 tp->bictcp.last_cwnd = tp->snd_cwnd;
2011 /* start off normal */
2012 if (tp->snd_cwnd <= sysctl_tcp_bic_low_window)
2013 tp->bictcp.cnt = tp->snd_cwnd;
2015 /* binary increase */
2016 else if (tp->snd_cwnd < tp->bictcp.last_max_cwnd) {
2017 __u32 dist = (tp->bictcp.last_max_cwnd - tp->snd_cwnd)
2020 if (dist > BICTCP_MAX_INCREMENT)
2021 /* linear increase */
2022 tp->bictcp.cnt = tp->snd_cwnd / BICTCP_MAX_INCREMENT;
2023 else if (dist <= 1U)
2024 /* binary search increase */
2025 tp->bictcp.cnt = tp->snd_cwnd * BICTCP_FUNC_OF_MIN_INCR
2028 /* binary search increase */
2029 tp->bictcp.cnt = tp->snd_cwnd / dist;
2031 /* slow start amd linear increase */
2032 if (tp->snd_cwnd < tp->bictcp.last_max_cwnd + BICTCP_B)
2034 tp->bictcp.cnt = tp->snd_cwnd * BICTCP_FUNC_OF_MIN_INCR
2036 else if (tp->snd_cwnd < tp->bictcp.last_max_cwnd
2037 + BICTCP_MAX_INCREMENT*(BICTCP_B-1))
2039 tp->bictcp.cnt = tp->snd_cwnd * (BICTCP_B-1)
2040 / (tp->snd_cwnd-tp->bictcp.last_max_cwnd);
2042 /* linear increase */
2043 tp->bictcp.cnt = tp->snd_cwnd / BICTCP_MAX_INCREMENT;
2045 return tp->bictcp.cnt;
2048 /* This is Jacobson's slow start and congestion avoidance.
2049 * SIGCOMM '88, p. 328.
2051 static __inline__ void reno_cong_avoid(struct tcp_opt *tp)
2053 if (tp->snd_cwnd <= tp->snd_ssthresh) {
2054 /* In "safe" area, increase. */
2055 if (tp->snd_cwnd < tp->snd_cwnd_clamp)
2058 /* In dangerous area, increase slowly.
2059 * In theory this is tp->snd_cwnd += 1 / tp->snd_cwnd
2061 if (tp->snd_cwnd_cnt >= bictcp_cwnd(tp)) {
2062 if (tp->snd_cwnd < tp->snd_cwnd_clamp)
2068 tp->snd_cwnd_stamp = tcp_time_stamp;
2071 /* This is based on the congestion detection/avoidance scheme described in
2072 * Lawrence S. Brakmo and Larry L. Peterson.
2073 * "TCP Vegas: End to end congestion avoidance on a global internet."
2074 * IEEE Journal on Selected Areas in Communication, 13(8):1465--1480,
2075 * October 1995. Available from:
2076 * ftp://ftp.cs.arizona.edu/xkernel/Papers/jsac.ps
2078 * See http://www.cs.arizona.edu/xkernel/ for their implementation.
2079 * The main aspects that distinguish this implementation from the
2080 * Arizona Vegas implementation are:
2081 * o We do not change the loss detection or recovery mechanisms of
2082 * Linux in any way. Linux already recovers from losses quite well,
2083 * using fine-grained timers, NewReno, and FACK.
2084 * o To avoid the performance penalty imposed by increasing cwnd
2085 * only every-other RTT during slow start, we increase during
2086 * every RTT during slow start, just like Reno.
2087 * o Largely to allow continuous cwnd growth during slow start,
2088 * we use the rate at which ACKs come back as the "actual"
2089 * rate, rather than the rate at which data is sent.
2090 * o To speed convergence to the right rate, we set the cwnd
2091 * to achieve the right ("actual") rate when we exit slow start.
2092 * o To filter out the noise caused by delayed ACKs, we use the
2093 * minimum RTT sample observed during the last RTT to calculate
2095 * o When the sender re-starts from idle, it waits until it has
2096 * received ACKs for an entire flight of new data before making
2097 * a cwnd adjustment decision. The original Vegas implementation
2098 * assumed senders never went idle.
2100 static void vegas_cong_avoid(struct tcp_opt *tp, u32 ack, u32 seq_rtt)
2102 /* The key players are v_beg_snd_una and v_beg_snd_nxt.
2104 * These are so named because they represent the approximate values
2105 * of snd_una and snd_nxt at the beginning of the current RTT. More
2106 * precisely, they represent the amount of data sent during the RTT.
2107 * At the end of the RTT, when we receive an ACK for v_beg_snd_nxt,
2108 * we will calculate that (v_beg_snd_nxt - v_beg_snd_una) outstanding
2109 * bytes of data have been ACKed during the course of the RTT, giving
2110 * an "actual" rate of:
2112 * (v_beg_snd_nxt - v_beg_snd_una) / (rtt duration)
2114 * Unfortunately, v_beg_snd_una is not exactly equal to snd_una,
2115 * because delayed ACKs can cover more than one segment, so they
2116 * don't line up nicely with the boundaries of RTTs.
2118 * Another unfortunate fact of life is that delayed ACKs delay the
2119 * advance of the left edge of our send window, so that the number
2120 * of bytes we send in an RTT is often less than our cwnd will allow.
2121 * So we keep track of our cwnd separately, in v_beg_snd_cwnd.
2124 if (after(ack, tp->vegas.beg_snd_nxt)) {
2125 /* Do the Vegas once-per-RTT cwnd adjustment. */
2126 u32 old_wnd, old_snd_cwnd;
2129 /* Here old_wnd is essentially the window of data that was
2130 * sent during the previous RTT, and has all
2131 * been acknowledged in the course of the RTT that ended
2132 * with the ACK we just received. Likewise, old_snd_cwnd
2133 * is the cwnd during the previous RTT.
2135 old_wnd = (tp->vegas.beg_snd_nxt - tp->vegas.beg_snd_una) /
2137 old_snd_cwnd = tp->vegas.beg_snd_cwnd;
2139 /* Save the extent of the current window so we can use this
2140 * at the end of the next RTT.
2142 tp->vegas.beg_snd_una = tp->vegas.beg_snd_nxt;
2143 tp->vegas.beg_snd_nxt = tp->snd_nxt;
2144 tp->vegas.beg_snd_cwnd = tp->snd_cwnd;
2146 /* Take into account the current RTT sample too, to
2147 * decrease the impact of delayed acks. This double counts
2148 * this sample since we count it for the next window as well,
2149 * but that's not too awful, since we're taking the min,
2150 * rather than averaging.
2152 vegas_rtt_calc(tp, seq_rtt);
2154 /* We do the Vegas calculations only if we got enough RTT
2155 * samples that we can be reasonably sure that we got
2156 * at least one RTT sample that wasn't from a delayed ACK.
2157 * If we only had 2 samples total,
2158 * then that means we're getting only 1 ACK per RTT, which
2159 * means they're almost certainly delayed ACKs.
2160 * If we have 3 samples, we should be OK.
2163 if (tp->vegas.cntRTT <= 2) {
2164 /* We don't have enough RTT samples to do the Vegas
2165 * calculation, so we'll behave like Reno.
2167 if (tp->snd_cwnd > tp->snd_ssthresh)
2170 u32 rtt, target_cwnd, diff;
2172 /* We have enough RTT samples, so, using the Vegas
2173 * algorithm, we determine if we should increase or
2174 * decrease cwnd, and by how much.
2177 /* Pluck out the RTT we are using for the Vegas
2178 * calculations. This is the min RTT seen during the
2179 * last RTT. Taking the min filters out the effects
2180 * of delayed ACKs, at the cost of noticing congestion
2183 rtt = tp->vegas.minRTT;
2185 /* Calculate the cwnd we should have, if we weren't
2189 * (actual rate in segments) * baseRTT
2190 * We keep it as a fixed point number with
2191 * V_PARAM_SHIFT bits to the right of the binary point.
2193 target_cwnd = ((old_wnd * tp->vegas.baseRTT)
2194 << V_PARAM_SHIFT) / rtt;
2196 /* Calculate the difference between the window we had,
2197 * and the window we would like to have. This quantity
2198 * is the "Diff" from the Arizona Vegas papers.
2200 * Again, this is a fixed point number with
2201 * V_PARAM_SHIFT bits to the right of the binary
2204 diff = (old_wnd << V_PARAM_SHIFT) - target_cwnd;
2206 if (tp->snd_cwnd < tp->snd_ssthresh) {
2208 if (diff > sysctl_tcp_vegas_gamma) {
2209 /* Going too fast. Time to slow down
2210 * and switch to congestion avoidance.
2212 tp->snd_ssthresh = 2;
2214 /* Set cwnd to match the actual rate
2216 * cwnd = (actual rate) * baseRTT
2217 * Then we add 1 because the integer
2218 * truncation robs us of full link
2221 tp->snd_cwnd = min(tp->snd_cwnd,
2227 /* Congestion avoidance. */
2230 /* Figure out where we would like cwnd
2233 if (diff > sysctl_tcp_vegas_beta) {
2234 /* The old window was too fast, so
2237 next_snd_cwnd = old_snd_cwnd - 1;
2238 } else if (diff < sysctl_tcp_vegas_alpha) {
2239 /* We don't have enough extra packets
2240 * in the network, so speed up.
2242 next_snd_cwnd = old_snd_cwnd + 1;
2244 /* Sending just as fast as we
2247 next_snd_cwnd = old_snd_cwnd;
2250 /* Adjust cwnd upward or downward, toward the
2253 if (next_snd_cwnd > tp->snd_cwnd)
2255 else if (next_snd_cwnd < tp->snd_cwnd)
2260 /* Wipe the slate clean for the next RTT. */
2261 tp->vegas.cntRTT = 0;
2262 tp->vegas.minRTT = 0x7fffffff;
2265 /* The following code is executed for every ack we receive,
2266 * except for conditions checked in should_advance_cwnd()
2267 * before the call to tcp_cong_avoid(). Mainly this means that
2268 * we only execute this code if the ack actually acked some
2272 /* If we are in slow start, increase our cwnd in response to this ACK.
2273 * (If we are not in slow start then we are in congestion avoidance,
2274 * and adjust our congestion window only once per RTT. See the code
2277 if (tp->snd_cwnd <= tp->snd_ssthresh)
2280 /* to keep cwnd from growing without bound */
2281 tp->snd_cwnd = min_t(u32, tp->snd_cwnd, tp->snd_cwnd_clamp);
2283 /* Make sure that we are never so timid as to reduce our cwnd below
2286 * Going below 2 MSS would risk huge delayed ACKs from our receiver.
2288 tp->snd_cwnd = max(tp->snd_cwnd, 2U);
2290 tp->snd_cwnd_stamp = tcp_time_stamp;
2293 static inline void tcp_cong_avoid(struct tcp_opt *tp, u32 ack, u32 seq_rtt)
2295 if (tcp_vegas_enabled(tp))
2296 vegas_cong_avoid(tp, ack, seq_rtt);
2298 reno_cong_avoid(tp);
2301 /* Restart timer after forward progress on connection.
2302 * RFC2988 recommends to restart timer to now+rto.
2305 static __inline__ void tcp_ack_packets_out(struct sock *sk, struct tcp_opt *tp)
2307 if (tp->packets_out==0) {
2308 tcp_clear_xmit_timer(sk, TCP_TIME_RETRANS);
2310 tcp_reset_xmit_timer(sk, TCP_TIME_RETRANS, tp->rto);
2314 /* Remove acknowledged frames from the retransmission queue. */
2315 static int tcp_clean_rtx_queue(struct sock *sk, __s32 *seq_rtt_p)
2317 struct tcp_opt *tp = tcp_sk(sk);
2318 struct sk_buff *skb;
2319 __u32 now = tcp_time_stamp;
2323 while ((skb = skb_peek(&sk->sk_write_queue)) && skb != tp->send_head) {
2324 struct tcp_skb_cb *scb = TCP_SKB_CB(skb);
2325 __u8 sacked = scb->sacked;
2327 /* If our packet is before the ack sequence we can
2328 * discard it as it's confirmed to have arrived at
2331 if (after(scb->end_seq, tp->snd_una))
2334 /* Initial outgoing SYN's get put onto the write_queue
2335 * just like anything else we transmit. It is not
2336 * true data, and if we misinform our callers that
2337 * this ACK acks real data, we will erroneously exit
2338 * connection startup slow start one packet too
2339 * quickly. This is severely frowned upon behavior.
2341 if(!(scb->flags & TCPCB_FLAG_SYN)) {
2342 acked |= FLAG_DATA_ACKED;
2344 acked |= FLAG_SYN_ACKED;
2345 tp->retrans_stamp = 0;
2349 if(sacked & TCPCB_RETRANS) {
2350 if(sacked & TCPCB_SACKED_RETRANS)
2352 acked |= FLAG_RETRANS_DATA_ACKED;
2354 } else if (seq_rtt < 0)
2355 seq_rtt = now - scb->when;
2356 if(sacked & TCPCB_SACKED_ACKED)
2358 if(sacked & TCPCB_LOST)
2360 if(sacked & TCPCB_URG) {
2362 !before(scb->end_seq, tp->snd_up))
2365 } else if (seq_rtt < 0)
2366 seq_rtt = now - scb->when;
2367 if (tp->fackets_out)
2370 __skb_unlink(skb, skb->list);
2371 tcp_free_skb(sk, skb);
2374 if (acked&FLAG_ACKED) {
2375 tcp_ack_update_rtt(tp, acked, seq_rtt);
2376 tcp_ack_packets_out(sk, tp);
2379 #if FASTRETRANS_DEBUG > 0
2380 BUG_TRAP((int)tp->sacked_out >= 0);
2381 BUG_TRAP((int)tp->lost_out >= 0);
2382 BUG_TRAP((int)tp->retrans_out >= 0);
2383 if (!tp->packets_out && tp->sack_ok) {
2385 printk(KERN_DEBUG "Leak l=%u %d\n", tp->lost_out,
2389 if (tp->sacked_out) {
2390 printk(KERN_DEBUG "Leak s=%u %d\n", tp->sacked_out,
2394 if (tp->retrans_out) {
2395 printk(KERN_DEBUG "Leak r=%u %d\n", tp->retrans_out,
2397 tp->retrans_out = 0;
2401 *seq_rtt_p = seq_rtt;
2405 static void tcp_ack_probe(struct sock *sk)
2407 struct tcp_opt *tp = tcp_sk(sk);
2409 /* Was it a usable window open? */
2411 if (!after(TCP_SKB_CB(tp->send_head)->end_seq,
2412 tp->snd_una + tp->snd_wnd)) {
2414 tcp_clear_xmit_timer(sk, TCP_TIME_PROBE0);
2415 /* Socket must be waked up by subsequent tcp_data_snd_check().
2416 * This function is not for random using!
2419 tcp_reset_xmit_timer(sk, TCP_TIME_PROBE0,
2420 min(tp->rto << tp->backoff, TCP_RTO_MAX));
2424 static __inline__ int tcp_ack_is_dubious(struct tcp_opt *tp, int flag)
2426 return (!(flag & FLAG_NOT_DUP) || (flag & FLAG_CA_ALERT) ||
2427 tp->ca_state != TCP_CA_Open);
2430 static __inline__ int tcp_may_raise_cwnd(struct tcp_opt *tp, int flag)
2432 return (!(flag & FLAG_ECE) || tp->snd_cwnd < tp->snd_ssthresh) &&
2433 !((1<<tp->ca_state)&(TCPF_CA_Recovery|TCPF_CA_CWR));
2436 /* Check that window update is acceptable.
2437 * The function assumes that snd_una<=ack<=snd_next.
2439 static __inline__ int
2440 tcp_may_update_window(struct tcp_opt *tp, u32 ack, u32 ack_seq, u32 nwin)
2442 return (after(ack, tp->snd_una) ||
2443 after(ack_seq, tp->snd_wl1) ||
2444 (ack_seq == tp->snd_wl1 && nwin > tp->snd_wnd));
2447 /* Update our send window.
2449 * Window update algorithm, described in RFC793/RFC1122 (used in linux-2.2
2450 * and in FreeBSD. NetBSD's one is even worse.) is wrong.
2452 static int tcp_ack_update_window(struct sock *sk, struct tcp_opt *tp,
2453 struct sk_buff *skb, u32 ack, u32 ack_seq)
2456 u32 nwin = ntohs(skb->h.th->window);
2458 if (likely(!skb->h.th->syn))
2459 nwin <<= tp->snd_wscale;
2461 if (tcp_may_update_window(tp, ack, ack_seq, nwin)) {
2462 flag |= FLAG_WIN_UPDATE;
2463 tcp_update_wl(tp, ack, ack_seq);
2465 if (tp->snd_wnd != nwin) {
2468 /* Note, it is the only place, where
2469 * fast path is recovered for sending TCP.
2471 tcp_fast_path_check(sk, tp);
2473 if (nwin > tp->max_window) {
2474 tp->max_window = nwin;
2475 tcp_sync_mss(sk, tp->pmtu_cookie);
2485 static void tcp_process_frto(struct sock *sk, u32 prior_snd_una)
2487 struct tcp_opt *tp = tcp_sk(sk);
2489 tcp_sync_left_out(tp);
2491 if (tp->snd_una == prior_snd_una ||
2492 !before(tp->snd_una, tp->frto_highmark)) {
2493 /* RTO was caused by loss, start retransmitting in
2494 * go-back-N slow start
2496 tcp_enter_frto_loss(sk);
2500 if (tp->frto_counter == 1) {
2501 /* First ACK after RTO advances the window: allow two new
2504 tp->snd_cwnd = tcp_packets_in_flight(tp) + 2;
2506 /* Also the second ACK after RTO advances the window.
2507 * The RTO was likely spurious. Reduce cwnd and continue
2508 * in congestion avoidance
2510 tp->snd_cwnd = min(tp->snd_cwnd, tp->snd_ssthresh);
2511 tcp_moderate_cwnd(tp);
2514 /* F-RTO affects on two new ACKs following RTO.
2515 * At latest on third ACK the TCP behavor is back to normal.
2517 tp->frto_counter = (tp->frto_counter + 1) % 3;
2526 * This function initializes fields used in TCP Westwood+. We can't
2527 * get no information about RTTmin at this time so we simply set it to
2528 * TCP_WESTWOOD_INIT_RTT. This value was chosen to be too conservative
2529 * since in this way we're sure it will be updated in a consistent
2530 * way as soon as possible. It will reasonably happen within the first
2531 * RTT period of the connection lifetime.
2534 static void init_westwood(struct sock *sk)
2536 struct tcp_opt *tp = tcp_sk(sk);
2538 tp->westwood.bw_ns_est = 0;
2539 tp->westwood.bw_est = 0;
2540 tp->westwood.accounted = 0;
2541 tp->westwood.cumul_ack = 0;
2542 tp->westwood.rtt_win_sx = tcp_time_stamp;
2543 tp->westwood.rtt = TCP_WESTWOOD_INIT_RTT;
2544 tp->westwood.rtt_min = TCP_WESTWOOD_INIT_RTT;
2545 tp->westwood.snd_una = tp->snd_una;
2549 * @westwood_do_filter
2550 * Low-pass filter. Implemented using constant coeffients.
2553 static inline __u32 westwood_do_filter(__u32 a, __u32 b)
2555 return (((7 * a) + b) >> 3);
2558 static void westwood_filter(struct sock *sk, __u32 delta)
2560 struct tcp_opt *tp = tcp_sk(sk);
2562 tp->westwood.bw_ns_est =
2563 westwood_do_filter(tp->westwood.bw_ns_est,
2564 tp->westwood.bk / delta);
2565 tp->westwood.bw_est =
2566 westwood_do_filter(tp->westwood.bw_est,
2567 tp->westwood.bw_ns_est);
2571 * @westwood_update_rttmin
2572 * It is used to update RTTmin. In this case we MUST NOT use
2573 * WESTWOOD_RTT_MIN minimum bound since we could be on a LAN!
2576 static inline __u32 westwood_update_rttmin(struct sock *sk)
2578 struct tcp_opt *tp = tcp_sk(sk);
2579 __u32 rttmin = tp->westwood.rtt_min;
2581 if (tp->westwood.rtt == 0)
2584 if (tp->westwood.rtt < tp->westwood.rtt_min || !rttmin)
2585 rttmin = tp->westwood.rtt;
2592 * Evaluate increases for dk.
2595 static inline __u32 westwood_acked(struct sock *sk)
2597 struct tcp_opt *tp = tcp_sk(sk);
2599 return ((tp->snd_una) - (tp->westwood.snd_una));
2603 * @westwood_new_window
2604 * It evaluates if we are receiving data inside the same RTT window as
2607 * It returns 0 if we are still evaluating samples in the same RTT
2608 * window, 1 if the sample has to be considered in the next window.
2611 static int westwood_new_window(struct sock *sk)
2613 struct tcp_opt *tp = tcp_sk(sk);
2618 left_bound = tp->westwood.rtt_win_sx;
2619 rtt = max(tp->westwood.rtt, (u32) TCP_WESTWOOD_RTT_MIN);
2622 * A RTT-window has passed. Be careful since if RTT is less than
2623 * 50ms we don't filter but we continue 'building the sample'.
2624 * This minimum limit was choosen since an estimation on small
2625 * time intervals is better to avoid...
2626 * Obvioulsy on a LAN we reasonably will always have
2627 * right_bound = left_bound + WESTWOOD_RTT_MIN
2630 if ((left_bound + rtt) < tcp_time_stamp)
2637 * @westwood_update_window
2638 * It updates RTT evaluation window if it is the right moment to do
2639 * it. If so it calls filter for evaluating bandwidth.
2642 static void __westwood_update_window(struct sock *sk, __u32 now)
2644 struct tcp_opt *tp = tcp_sk(sk);
2645 __u32 delta = now - tp->westwood.rtt_win_sx;
2650 if (tp->westwood.rtt)
2651 westwood_filter(sk, delta);
2653 tp->westwood.bk = 0;
2654 tp->westwood.rtt_win_sx = tcp_time_stamp;
2658 static void westwood_update_window(struct sock *sk, __u32 now)
2660 if (westwood_new_window(sk))
2661 __westwood_update_window(sk, now);
2665 * @__tcp_westwood_fast_bw
2666 * It is called when we are in fast path. In particular it is called when
2667 * header prediction is successfull. In such case infact update is
2668 * straight forward and doesn't need any particular care.
2671 void __tcp_westwood_fast_bw(struct sock *sk, struct sk_buff *skb)
2673 struct tcp_opt *tp = tcp_sk(sk);
2675 westwood_update_window(sk, tcp_time_stamp);
2677 tp->westwood.bk += westwood_acked(sk);
2678 tp->westwood.snd_una = tp->snd_una;
2679 tp->westwood.rtt_min = westwood_update_rttmin(sk);
2684 * @westwood_dupack_update
2685 * It updates accounted and cumul_ack when receiving a dupack.
2688 static void westwood_dupack_update(struct sock *sk)
2690 struct tcp_opt *tp = tcp_sk(sk);
2692 tp->westwood.accounted += tp->mss_cache;
2693 tp->westwood.cumul_ack = tp->mss_cache;
2696 static inline int westwood_may_change_cumul(struct tcp_opt *tp)
2698 return ((tp->westwood.cumul_ack) > tp->mss_cache);
2701 static inline void westwood_partial_update(struct tcp_opt *tp)
2703 tp->westwood.accounted -= tp->westwood.cumul_ack;
2704 tp->westwood.cumul_ack = tp->mss_cache;
2707 static inline void westwood_complete_update(struct tcp_opt *tp)
2709 tp->westwood.cumul_ack -= tp->westwood.accounted;
2710 tp->westwood.accounted = 0;
2714 * @westwood_acked_count
2715 * This function evaluates cumul_ack for evaluating dk in case of
2716 * delayed or partial acks.
2719 static __u32 westwood_acked_count(struct sock *sk)
2721 struct tcp_opt *tp = tcp_sk(sk);
2723 tp->westwood.cumul_ack = westwood_acked(sk);
2725 /* If cumul_ack is 0 this is a dupack since it's not moving
2728 if (!(tp->westwood.cumul_ack))
2729 westwood_dupack_update(sk);
2731 if (westwood_may_change_cumul(tp)) {
2732 /* Partial or delayed ack */
2733 if ((tp->westwood.accounted) >= (tp->westwood.cumul_ack))
2734 westwood_partial_update(tp);
2736 westwood_complete_update(tp);
2739 tp->westwood.snd_una = tp->snd_una;
2741 return tp->westwood.cumul_ack;
2746 * @__tcp_westwood_slow_bw
2747 * It is called when something is going wrong..even if there could
2748 * be no problems! Infact a simple delayed packet may trigger a
2749 * dupack. But we need to be careful in such case.
2752 void __tcp_westwood_slow_bw(struct sock *sk, struct sk_buff *skb)
2754 struct tcp_opt *tp = tcp_sk(sk);
2756 westwood_update_window(sk, tcp_time_stamp);
2758 tp->westwood.bk += westwood_acked_count(sk);
2759 tp->westwood.rtt_min = westwood_update_rttmin(sk);
2762 /* This routine deals with incoming acks, but not outgoing ones. */
2763 static int tcp_ack(struct sock *sk, struct sk_buff *skb, int flag)
2765 struct tcp_opt *tp = tcp_sk(sk);
2766 u32 prior_snd_una = tp->snd_una;
2767 u32 ack_seq = TCP_SKB_CB(skb)->seq;
2768 u32 ack = TCP_SKB_CB(skb)->ack_seq;
2769 u32 prior_in_flight;
2773 /* If the ack is newer than sent or older than previous acks
2774 * then we can probably ignore it.
2776 if (after(ack, tp->snd_nxt))
2777 goto uninteresting_ack;
2779 if (before(ack, prior_snd_una))
2782 if (!(flag&FLAG_SLOWPATH) && after(ack, prior_snd_una)) {
2783 /* Window is constant, pure forward advance.
2784 * No more checks are required.
2785 * Note, we use the fact that SND.UNA>=SND.WL2.
2787 tcp_update_wl(tp, ack, ack_seq);
2789 tcp_westwood_fast_bw(sk, skb);
2790 flag |= FLAG_WIN_UPDATE;
2792 NET_INC_STATS_BH(TCPHPAcks);
2794 if (ack_seq != TCP_SKB_CB(skb)->end_seq)
2797 NET_INC_STATS_BH(TCPPureAcks);
2799 flag |= tcp_ack_update_window(sk, tp, skb, ack, ack_seq);
2801 if (TCP_SKB_CB(skb)->sacked)
2802 flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una);
2804 if (TCP_ECN_rcv_ecn_echo(tp, skb->h.th))
2807 tcp_westwood_slow_bw(sk,skb);
2810 /* We passed data and got it acked, remove any soft error
2811 * log. Something worked...
2813 sk->sk_err_soft = 0;
2814 tp->rcv_tstamp = tcp_time_stamp;
2815 prior_packets = tp->packets_out;
2819 prior_in_flight = tcp_packets_in_flight(tp);
2821 /* See if we can take anything off of the retransmit queue. */
2822 flag |= tcp_clean_rtx_queue(sk, &seq_rtt);
2824 if (tp->frto_counter)
2825 tcp_process_frto(sk, prior_snd_una);
2827 if (tcp_ack_is_dubious(tp, flag)) {
2828 /* Advanve CWND, if state allows this. */
2829 if ((flag & FLAG_DATA_ACKED) &&
2830 (tcp_vegas_enabled(tp) || prior_in_flight >= tp->snd_cwnd) &&
2831 tcp_may_raise_cwnd(tp, flag))
2832 tcp_cong_avoid(tp, ack, seq_rtt);
2833 tcp_fastretrans_alert(sk, prior_snd_una, prior_packets, flag);
2835 if ((flag & FLAG_DATA_ACKED) &&
2836 (tcp_vegas_enabled(tp) || prior_in_flight >= tp->snd_cwnd))
2837 tcp_cong_avoid(tp, ack, seq_rtt);
2840 if ((flag & FLAG_FORWARD_PROGRESS) || !(flag&FLAG_NOT_DUP))
2841 dst_confirm(sk->sk_dst_cache);
2848 /* If this ack opens up a zero window, clear backoff. It was
2849 * being used to time the probes, and is probably far higher than
2850 * it needs to be for normal retransmission.
2857 if (TCP_SKB_CB(skb)->sacked)
2858 tcp_sacktag_write_queue(sk, skb, prior_snd_una);
2861 SOCK_DEBUG(sk, "Ack %u out of %u:%u\n", ack, tp->snd_una, tp->snd_nxt);
2866 /* Look for tcp options. Normally only called on SYN and SYNACK packets.
2867 * But, this can also be called on packets in the established flow when
2868 * the fast version below fails.
2870 void tcp_parse_options(struct sk_buff *skb, struct tcp_opt *tp, int estab)
2873 struct tcphdr *th = skb->h.th;
2874 int length=(th->doff*4)-sizeof(struct tcphdr);
2876 ptr = (unsigned char *)(th + 1);
2886 case TCPOPT_NOP: /* Ref: RFC 793 section 3.1 */
2891 if (opsize < 2) /* "silly options" */
2893 if (opsize > length)
2894 return; /* don't parse partial options */
2897 if(opsize==TCPOLEN_MSS && th->syn && !estab) {
2898 u16 in_mss = ntohs(*(__u16 *)ptr);
2900 if (tp->user_mss && tp->user_mss < in_mss)
2901 in_mss = tp->user_mss;
2902 tp->mss_clamp = in_mss;
2907 if(opsize==TCPOLEN_WINDOW && th->syn && !estab)
2908 if (sysctl_tcp_window_scaling) {
2910 tp->snd_wscale = *(__u8 *)ptr;
2911 if(tp->snd_wscale > 14) {
2913 printk("tcp_parse_options: Illegal window "
2914 "scaling value %d >14 received.",
2916 tp->snd_wscale = 14;
2920 case TCPOPT_TIMESTAMP:
2921 if(opsize==TCPOLEN_TIMESTAMP) {
2922 if ((estab && tp->tstamp_ok) ||
2923 (!estab && sysctl_tcp_timestamps)) {
2925 tp->rcv_tsval = ntohl(*(__u32 *)ptr);
2926 tp->rcv_tsecr = ntohl(*(__u32 *)(ptr+4));
2930 case TCPOPT_SACK_PERM:
2931 if(opsize==TCPOLEN_SACK_PERM && th->syn && !estab) {
2932 if (sysctl_tcp_sack) {
2940 if((opsize >= (TCPOLEN_SACK_BASE + TCPOLEN_SACK_PERBLOCK)) &&
2941 !((opsize - TCPOLEN_SACK_BASE) % TCPOLEN_SACK_PERBLOCK) &&
2943 TCP_SKB_CB(skb)->sacked = (ptr - 2) - (unsigned char *)th;
2952 /* Fast parse options. This hopes to only see timestamps.
2953 * If it is wrong it falls back on tcp_parse_options().
2955 static __inline__ int tcp_fast_parse_options(struct sk_buff *skb, struct tcphdr *th, struct tcp_opt *tp)
2957 if (th->doff == sizeof(struct tcphdr)>>2) {
2960 } else if (tp->tstamp_ok &&
2961 th->doff == (sizeof(struct tcphdr)>>2)+(TCPOLEN_TSTAMP_ALIGNED>>2)) {
2962 __u32 *ptr = (__u32 *)(th + 1);
2963 if (*ptr == ntohl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16)
2964 | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP)) {
2967 tp->rcv_tsval = ntohl(*ptr);
2969 tp->rcv_tsecr = ntohl(*ptr);
2973 tcp_parse_options(skb, tp, 1);
2977 static __inline__ void
2978 tcp_store_ts_recent(struct tcp_opt *tp)
2980 tp->ts_recent = tp->rcv_tsval;
2981 tp->ts_recent_stamp = xtime.tv_sec;
2984 static __inline__ void
2985 tcp_replace_ts_recent(struct tcp_opt *tp, u32 seq)
2987 if (tp->saw_tstamp && !after(seq, tp->rcv_wup)) {
2988 /* PAWS bug workaround wrt. ACK frames, the PAWS discard
2989 * extra check below makes sure this can only happen
2990 * for pure ACK frames. -DaveM
2992 * Not only, also it occurs for expired timestamps.
2995 if((s32)(tp->rcv_tsval - tp->ts_recent) >= 0 ||
2996 xtime.tv_sec >= tp->ts_recent_stamp + TCP_PAWS_24DAYS)
2997 tcp_store_ts_recent(tp);
3001 /* Sorry, PAWS as specified is broken wrt. pure-ACKs -DaveM
3003 * It is not fatal. If this ACK does _not_ change critical state (seqs, window)
3004 * it can pass through stack. So, the following predicate verifies that
3005 * this segment is not used for anything but congestion avoidance or
3006 * fast retransmit. Moreover, we even are able to eliminate most of such
3007 * second order effects, if we apply some small "replay" window (~RTO)
3008 * to timestamp space.
3010 * All these measures still do not guarantee that we reject wrapped ACKs
3011 * on networks with high bandwidth, when sequence space is recycled fastly,
3012 * but it guarantees that such events will be very rare and do not affect
3013 * connection seriously. This doesn't look nice, but alas, PAWS is really
3016 * [ Later note. Even worse! It is buggy for segments _with_ data. RFC
3017 * states that events when retransmit arrives after original data are rare.
3018 * It is a blatant lie. VJ forgot about fast retransmit! 8)8) It is
3019 * the biggest problem on large power networks even with minor reordering.
3020 * OK, let's give it small replay window. If peer clock is even 1hz, it is safe
3021 * up to bandwidth of 18Gigabit/sec. 8) ]
3024 static int tcp_disordered_ack(struct tcp_opt *tp, struct sk_buff *skb)
3026 struct tcphdr *th = skb->h.th;
3027 u32 seq = TCP_SKB_CB(skb)->seq;
3028 u32 ack = TCP_SKB_CB(skb)->ack_seq;
3030 return (/* 1. Pure ACK with correct sequence number. */
3031 (th->ack && seq == TCP_SKB_CB(skb)->end_seq && seq == tp->rcv_nxt) &&
3033 /* 2. ... and duplicate ACK. */
3034 ack == tp->snd_una &&
3036 /* 3. ... and does not update window. */
3037 !tcp_may_update_window(tp, ack, seq, ntohs(th->window)<<tp->snd_wscale) &&
3039 /* 4. ... and sits in replay window. */
3040 (s32)(tp->ts_recent - tp->rcv_tsval) <= (tp->rto*1024)/HZ);
3043 static __inline__ int tcp_paws_discard(struct tcp_opt *tp, struct sk_buff *skb)
3045 return ((s32)(tp->ts_recent - tp->rcv_tsval) > TCP_PAWS_WINDOW &&
3046 xtime.tv_sec < tp->ts_recent_stamp + TCP_PAWS_24DAYS &&
3047 !tcp_disordered_ack(tp, skb));
3050 /* Check segment sequence number for validity.
3052 * Segment controls are considered valid, if the segment
3053 * fits to the window after truncation to the window. Acceptability
3054 * of data (and SYN, FIN, of course) is checked separately.
3055 * See tcp_data_queue(), for example.
3057 * Also, controls (RST is main one) are accepted using RCV.WUP instead
3058 * of RCV.NXT. Peer still did not advance his SND.UNA when we
3059 * delayed ACK, so that hisSND.UNA<=ourRCV.WUP.
3060 * (borrowed from freebsd)
3063 static inline int tcp_sequence(struct tcp_opt *tp, u32 seq, u32 end_seq)
3065 return !before(end_seq, tp->rcv_wup) &&
3066 !after(seq, tp->rcv_nxt + tcp_receive_window(tp));
3069 /* When we get a reset we do this. */
3070 static void tcp_reset(struct sock *sk)
3072 /* We want the right error as BSD sees it (and indeed as we do). */
3073 switch (sk->sk_state) {
3075 sk->sk_err = ECONNREFUSED;
3077 case TCP_CLOSE_WAIT:
3083 sk->sk_err = ECONNRESET;
3086 if (!sock_flag(sk, SOCK_DEAD))
3087 sk->sk_error_report(sk);
3093 * Process the FIN bit. This now behaves as it is supposed to work
3094 * and the FIN takes effect when it is validly part of sequence
3095 * space. Not before when we get holes.
3097 * If we are ESTABLISHED, a received fin moves us to CLOSE-WAIT
3098 * (and thence onto LAST-ACK and finally, CLOSE, we never enter
3101 * If we are in FINWAIT-1, a received FIN indicates simultaneous
3102 * close and we go into CLOSING (and later onto TIME-WAIT)
3104 * If we are in FINWAIT-2, a received FIN moves us to TIME-WAIT.
3106 static void tcp_fin(struct sk_buff *skb, struct sock *sk, struct tcphdr *th)
3108 struct tcp_opt *tp = tcp_sk(sk);
3110 tcp_schedule_ack(tp);
3112 sk->sk_shutdown |= RCV_SHUTDOWN;
3113 sock_set_flag(sk, SOCK_DONE);
3115 switch (sk->sk_state) {
3117 case TCP_ESTABLISHED:
3118 /* Move to CLOSE_WAIT */
3119 tcp_set_state(sk, TCP_CLOSE_WAIT);
3120 tp->ack.pingpong = 1;
3123 case TCP_CLOSE_WAIT:
3125 /* Received a retransmission of the FIN, do
3130 /* RFC793: Remain in the LAST-ACK state. */
3134 /* This case occurs when a simultaneous close
3135 * happens, we must ack the received FIN and
3136 * enter the CLOSING state.
3139 tcp_set_state(sk, TCP_CLOSING);
3142 /* Received a FIN -- send ACK and enter TIME_WAIT. */
3144 tcp_time_wait(sk, TCP_TIME_WAIT, 0);
3147 /* Only TCP_LISTEN and TCP_CLOSE are left, in these
3148 * cases we should never reach this piece of code.
3150 printk(KERN_ERR "%s: Impossible, sk->sk_state=%d\n",
3151 __FUNCTION__, sk->sk_state);
3155 /* It _is_ possible, that we have something out-of-order _after_ FIN.
3156 * Probably, we should reset in this case. For now drop them.
3158 __skb_queue_purge(&tp->out_of_order_queue);
3161 tcp_mem_reclaim(sk);
3163 if (!sock_flag(sk, SOCK_DEAD)) {
3164 sk->sk_state_change(sk);
3166 /* Do not send POLL_HUP for half duplex close. */
3167 if (sk->sk_shutdown == SHUTDOWN_MASK ||
3168 sk->sk_state == TCP_CLOSE)
3169 sk_wake_async(sk, 1, POLL_HUP);
3171 sk_wake_async(sk, 1, POLL_IN);
3175 static __inline__ int
3176 tcp_sack_extend(struct tcp_sack_block *sp, u32 seq, u32 end_seq)
3178 if (!after(seq, sp->end_seq) && !after(sp->start_seq, end_seq)) {
3179 if (before(seq, sp->start_seq))
3180 sp->start_seq = seq;
3181 if (after(end_seq, sp->end_seq))
3182 sp->end_seq = end_seq;
3188 static __inline__ void tcp_dsack_set(struct tcp_opt *tp, u32 seq, u32 end_seq)
3190 if (tp->sack_ok && sysctl_tcp_dsack) {
3191 if (before(seq, tp->rcv_nxt))
3192 NET_INC_STATS_BH(TCPDSACKOldSent);
3194 NET_INC_STATS_BH(TCPDSACKOfoSent);
3197 tp->duplicate_sack[0].start_seq = seq;
3198 tp->duplicate_sack[0].end_seq = end_seq;
3199 tp->eff_sacks = min(tp->num_sacks+1, 4-tp->tstamp_ok);
3203 static __inline__ void tcp_dsack_extend(struct tcp_opt *tp, u32 seq, u32 end_seq)
3206 tcp_dsack_set(tp, seq, end_seq);
3208 tcp_sack_extend(tp->duplicate_sack, seq, end_seq);
3211 static void tcp_send_dupack(struct sock *sk, struct sk_buff *skb)
3213 struct tcp_opt *tp = tcp_sk(sk);
3215 if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
3216 before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
3217 NET_INC_STATS_BH(DelayedACKLost);
3218 tcp_enter_quickack_mode(tp);
3220 if (tp->sack_ok && sysctl_tcp_dsack) {
3221 u32 end_seq = TCP_SKB_CB(skb)->end_seq;
3223 if (after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt))
3224 end_seq = tp->rcv_nxt;
3225 tcp_dsack_set(tp, TCP_SKB_CB(skb)->seq, end_seq);
3232 /* These routines update the SACK block as out-of-order packets arrive or
3233 * in-order packets close up the sequence space.
3235 static void tcp_sack_maybe_coalesce(struct tcp_opt *tp)
3238 struct tcp_sack_block *sp = &tp->selective_acks[0];
3239 struct tcp_sack_block *swalk = sp+1;
3241 /* See if the recent change to the first SACK eats into
3242 * or hits the sequence space of other SACK blocks, if so coalesce.
3244 for (this_sack = 1; this_sack < tp->num_sacks; ) {
3245 if (tcp_sack_extend(sp, swalk->start_seq, swalk->end_seq)) {
3248 /* Zap SWALK, by moving every further SACK up by one slot.
3249 * Decrease num_sacks.
3252 tp->eff_sacks = min(tp->num_sacks+tp->dsack, 4-tp->tstamp_ok);
3253 for(i=this_sack; i < tp->num_sacks; i++)
3257 this_sack++, swalk++;
3261 static __inline__ void tcp_sack_swap(struct tcp_sack_block *sack1, struct tcp_sack_block *sack2)
3265 tmp = sack1->start_seq;
3266 sack1->start_seq = sack2->start_seq;
3267 sack2->start_seq = tmp;
3269 tmp = sack1->end_seq;
3270 sack1->end_seq = sack2->end_seq;
3271 sack2->end_seq = tmp;
3274 static void tcp_sack_new_ofo_skb(struct sock *sk, u32 seq, u32 end_seq)
3276 struct tcp_opt *tp = tcp_sk(sk);
3277 struct tcp_sack_block *sp = &tp->selective_acks[0];
3278 int cur_sacks = tp->num_sacks;
3284 for (this_sack=0; this_sack<cur_sacks; this_sack++, sp++) {
3285 if (tcp_sack_extend(sp, seq, end_seq)) {
3286 /* Rotate this_sack to the first one. */
3287 for (; this_sack>0; this_sack--, sp--)
3288 tcp_sack_swap(sp, sp-1);
3290 tcp_sack_maybe_coalesce(tp);
3295 /* Could not find an adjacent existing SACK, build a new one,
3296 * put it at the front, and shift everyone else down. We
3297 * always know there is at least one SACK present already here.
3299 * If the sack array is full, forget about the last one.
3301 if (this_sack >= 4) {
3306 for(; this_sack > 0; this_sack--, sp--)
3310 /* Build the new head SACK, and we're done. */
3311 sp->start_seq = seq;
3312 sp->end_seq = end_seq;
3314 tp->eff_sacks = min(tp->num_sacks + tp->dsack, 4 - tp->tstamp_ok);
3317 /* RCV.NXT advances, some SACKs should be eaten. */
3319 static void tcp_sack_remove(struct tcp_opt *tp)
3321 struct tcp_sack_block *sp = &tp->selective_acks[0];
3322 int num_sacks = tp->num_sacks;
3325 /* Empty ofo queue, hence, all the SACKs are eaten. Clear. */
3326 if (skb_queue_len(&tp->out_of_order_queue) == 0) {
3328 tp->eff_sacks = tp->dsack;
3332 for(this_sack = 0; this_sack < num_sacks; ) {
3333 /* Check if the start of the sack is covered by RCV.NXT. */
3334 if (!before(tp->rcv_nxt, sp->start_seq)) {
3337 /* RCV.NXT must cover all the block! */
3338 BUG_TRAP(!before(tp->rcv_nxt, sp->end_seq));
3340 /* Zap this SACK, by moving forward any other SACKS. */
3341 for (i=this_sack+1; i < num_sacks; i++)
3342 tp->selective_acks[i-1] = tp->selective_acks[i];
3349 if (num_sacks != tp->num_sacks) {
3350 tp->num_sacks = num_sacks;
3351 tp->eff_sacks = min(tp->num_sacks+tp->dsack, 4-tp->tstamp_ok);
3355 /* This one checks to see if we can put data from the
3356 * out_of_order queue into the receive_queue.
3358 static void tcp_ofo_queue(struct sock *sk)
3360 struct tcp_opt *tp = tcp_sk(sk);
3361 __u32 dsack_high = tp->rcv_nxt;
3362 struct sk_buff *skb;
3364 while ((skb = skb_peek(&tp->out_of_order_queue)) != NULL) {
3365 if (after(TCP_SKB_CB(skb)->seq, tp->rcv_nxt))
3368 if (before(TCP_SKB_CB(skb)->seq, dsack_high)) {
3369 __u32 dsack = dsack_high;
3370 if (before(TCP_SKB_CB(skb)->end_seq, dsack_high))
3371 dsack_high = TCP_SKB_CB(skb)->end_seq;
3372 tcp_dsack_extend(tp, TCP_SKB_CB(skb)->seq, dsack);
3375 if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) {
3376 SOCK_DEBUG(sk, "ofo packet was already received \n");
3377 __skb_unlink(skb, skb->list);
3381 SOCK_DEBUG(sk, "ofo requeuing : rcv_next %X seq %X - %X\n",
3382 tp->rcv_nxt, TCP_SKB_CB(skb)->seq,
3383 TCP_SKB_CB(skb)->end_seq);
3385 __skb_unlink(skb, skb->list);
3386 __skb_queue_tail(&sk->sk_receive_queue, skb);
3387 tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
3389 tcp_fin(skb, sk, skb->h.th);
3393 static inline int tcp_rmem_schedule(struct sock *sk, struct sk_buff *skb)
3395 return (int)skb->truesize <= sk->sk_forward_alloc ||
3396 tcp_mem_schedule(sk, skb->truesize, 1);
3399 static int tcp_prune_queue(struct sock *sk);
3401 static void tcp_data_queue(struct sock *sk, struct sk_buff *skb)
3403 struct tcphdr *th = skb->h.th;
3404 struct tcp_opt *tp = tcp_sk(sk);
3407 if (TCP_SKB_CB(skb)->seq == TCP_SKB_CB(skb)->end_seq)
3411 __skb_pull(skb, th->doff*4);
3413 TCP_ECN_accept_cwr(tp, skb);
3417 tp->eff_sacks = min_t(unsigned int, tp->num_sacks,
3421 /* Queue data for delivery to the user.
3422 * Packets in sequence go to the receive queue.
3423 * Out of sequence packets to the out_of_order_queue.
3425 if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt) {
3426 if (tcp_receive_window(tp) == 0)
3429 /* Ok. In sequence. In window. */
3430 if (tp->ucopy.task == current &&
3431 tp->copied_seq == tp->rcv_nxt && tp->ucopy.len &&
3432 sock_owned_by_user(sk) && !tp->urg_data) {
3433 int chunk = min_t(unsigned int, skb->len,
3436 __set_current_state(TASK_RUNNING);
3439 if (!skb_copy_datagram_iovec(skb, 0, tp->ucopy.iov, chunk)) {
3440 tp->ucopy.len -= chunk;
3441 tp->copied_seq += chunk;
3442 eaten = (chunk == skb->len && !th->fin);
3443 tcp_rcv_space_adjust(sk);
3451 (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
3452 !tcp_rmem_schedule(sk, skb))) {
3453 if (tcp_prune_queue(sk) < 0 || !tcp_rmem_schedule(sk, skb))
3456 tcp_set_owner_r(skb, sk);
3457 __skb_queue_tail(&sk->sk_receive_queue, skb);
3459 tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
3461 tcp_event_data_recv(sk, tp, skb);
3463 tcp_fin(skb, sk, th);
3465 if (skb_queue_len(&tp->out_of_order_queue)) {
3468 /* RFC2581. 4.2. SHOULD send immediate ACK, when
3469 * gap in queue is filled.
3471 if (!skb_queue_len(&tp->out_of_order_queue))
3472 tp->ack.pingpong = 0;
3476 tcp_sack_remove(tp);
3478 tcp_fast_path_check(sk, tp);
3482 else if (!sock_flag(sk, SOCK_DEAD))
3483 sk->sk_data_ready(sk, 0);
3487 if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) {
3488 /* A retransmit, 2nd most common case. Force an immediate ack. */
3489 NET_INC_STATS_BH(DelayedACKLost);
3490 tcp_dsack_set(tp, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq);
3493 tcp_enter_quickack_mode(tp);
3494 tcp_schedule_ack(tp);
3500 /* Out of window. F.e. zero window probe. */
3501 if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt + tcp_receive_window(tp)))
3504 tcp_enter_quickack_mode(tp);
3506 if (before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
3507 /* Partial packet, seq < rcv_next < end_seq */
3508 SOCK_DEBUG(sk, "partial packet: rcv_next %X seq %X - %X\n",
3509 tp->rcv_nxt, TCP_SKB_CB(skb)->seq,
3510 TCP_SKB_CB(skb)->end_seq);
3512 tcp_dsack_set(tp, TCP_SKB_CB(skb)->seq, tp->rcv_nxt);
3514 /* If window is closed, drop tail of packet. But after
3515 * remembering D-SACK for its head made in previous line.
3517 if (!tcp_receive_window(tp))
3522 TCP_ECN_check_ce(tp, skb);
3524 if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
3525 !tcp_rmem_schedule(sk, skb)) {
3526 if (tcp_prune_queue(sk) < 0 || !tcp_rmem_schedule(sk, skb))
3530 /* Disable header prediction. */
3532 tcp_schedule_ack(tp);
3534 SOCK_DEBUG(sk, "out of order segment: rcv_next %X seq %X - %X\n",
3535 tp->rcv_nxt, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq);
3537 tcp_set_owner_r(skb, sk);
3539 if (!skb_peek(&tp->out_of_order_queue)) {
3540 /* Initial out of order segment, build 1 SACK. */
3545 tp->selective_acks[0].start_seq = TCP_SKB_CB(skb)->seq;
3546 tp->selective_acks[0].end_seq =
3547 TCP_SKB_CB(skb)->end_seq;
3549 __skb_queue_head(&tp->out_of_order_queue,skb);
3551 struct sk_buff *skb1 = tp->out_of_order_queue.prev;
3552 u32 seq = TCP_SKB_CB(skb)->seq;
3553 u32 end_seq = TCP_SKB_CB(skb)->end_seq;
3555 if (seq == TCP_SKB_CB(skb1)->end_seq) {
3556 __skb_append(skb1, skb);
3558 if (!tp->num_sacks ||
3559 tp->selective_acks[0].end_seq != seq)
3562 /* Common case: data arrive in order after hole. */
3563 tp->selective_acks[0].end_seq = end_seq;
3567 /* Find place to insert this segment. */
3569 if (!after(TCP_SKB_CB(skb1)->seq, seq))
3571 } while ((skb1 = skb1->prev) !=
3572 (struct sk_buff*)&tp->out_of_order_queue);
3574 /* Do skb overlap to previous one? */
3575 if (skb1 != (struct sk_buff*)&tp->out_of_order_queue &&
3576 before(seq, TCP_SKB_CB(skb1)->end_seq)) {
3577 if (!after(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
3578 /* All the bits are present. Drop. */
3580 tcp_dsack_set(tp, seq, end_seq);
3583 if (after(seq, TCP_SKB_CB(skb1)->seq)) {
3584 /* Partial overlap. */
3585 tcp_dsack_set(tp, seq, TCP_SKB_CB(skb1)->end_seq);
3590 __skb_insert(skb, skb1, skb1->next, &tp->out_of_order_queue);
3592 /* And clean segments covered by new one as whole. */
3593 while ((skb1 = skb->next) !=
3594 (struct sk_buff*)&tp->out_of_order_queue &&
3595 after(end_seq, TCP_SKB_CB(skb1)->seq)) {
3596 if (before(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
3597 tcp_dsack_extend(tp, TCP_SKB_CB(skb1)->seq, end_seq);
3600 __skb_unlink(skb1, skb1->list);
3601 tcp_dsack_extend(tp, TCP_SKB_CB(skb1)->seq, TCP_SKB_CB(skb1)->end_seq);
3607 tcp_sack_new_ofo_skb(sk, seq, end_seq);
3611 /* Collapse contiguous sequence of skbs head..tail with
3612 * sequence numbers start..end.
3613 * Segments with FIN/SYN are not collapsed (only because this
3617 tcp_collapse(struct sock *sk, struct sk_buff *head,
3618 struct sk_buff *tail, u32 start, u32 end)
3620 struct sk_buff *skb;
3622 /* First, check that queue is collapsable and find
3623 * the point where collapsing can be useful. */
3624 for (skb = head; skb != tail; ) {
3625 /* No new bits? It is possible on ofo queue. */
3626 if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
3627 struct sk_buff *next = skb->next;
3628 __skb_unlink(skb, skb->list);
3630 NET_INC_STATS_BH(TCPRcvCollapsed);
3635 /* The first skb to collapse is:
3637 * - bloated or contains data before "start" or
3638 * overlaps to the next one.
3640 if (!skb->h.th->syn && !skb->h.th->fin &&
3641 (tcp_win_from_space(skb->truesize) > skb->len ||
3642 before(TCP_SKB_CB(skb)->seq, start) ||
3643 (skb->next != tail &&
3644 TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb->next)->seq)))
3647 /* Decided to skip this, advance start seq. */
3648 start = TCP_SKB_CB(skb)->end_seq;
3651 if (skb == tail || skb->h.th->syn || skb->h.th->fin)
3654 while (before(start, end)) {
3655 struct sk_buff *nskb;
3656 int header = skb_headroom(skb);
3657 int copy = (PAGE_SIZE - sizeof(struct sk_buff) -
3658 sizeof(struct skb_shared_info) - header - 31)&~15;
3660 /* Too big header? This can happen with IPv6. */
3663 if (end-start < copy)
3665 nskb = alloc_skb(copy+header, GFP_ATOMIC);
3668 skb_reserve(nskb, header);
3669 memcpy(nskb->head, skb->head, header);
3670 nskb->nh.raw = nskb->head + (skb->nh.raw-skb->head);
3671 nskb->h.raw = nskb->head + (skb->h.raw-skb->head);
3672 nskb->mac.raw = nskb->head + (skb->mac.raw-skb->head);
3673 memcpy(nskb->cb, skb->cb, sizeof(skb->cb));
3674 TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(nskb)->end_seq = start;
3675 __skb_insert(nskb, skb->prev, skb, skb->list);
3676 tcp_set_owner_r(nskb, sk);
3678 /* Copy data, releasing collapsed skbs. */
3680 int offset = start - TCP_SKB_CB(skb)->seq;
3681 int size = TCP_SKB_CB(skb)->end_seq - start;
3683 if (offset < 0) BUG();
3685 size = min(copy, size);
3686 if (skb_copy_bits(skb, offset, skb_put(nskb, size), size))
3688 TCP_SKB_CB(nskb)->end_seq += size;
3692 if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
3693 struct sk_buff *next = skb->next;
3694 __skb_unlink(skb, skb->list);
3696 NET_INC_STATS_BH(TCPRcvCollapsed);
3698 if (skb == tail || skb->h.th->syn || skb->h.th->fin)
3705 /* Collapse ofo queue. Algorithm: select contiguous sequence of skbs
3706 * and tcp_collapse() them until all the queue is collapsed.
3708 static void tcp_collapse_ofo_queue(struct sock *sk)
3710 struct tcp_opt *tp = tcp_sk(sk);
3711 struct sk_buff *skb = skb_peek(&tp->out_of_order_queue);
3712 struct sk_buff *head;
3718 start = TCP_SKB_CB(skb)->seq;
3719 end = TCP_SKB_CB(skb)->end_seq;
3725 /* Segment is terminated when we see gap or when
3726 * we are at the end of all the queue. */
3727 if (skb == (struct sk_buff *)&tp->out_of_order_queue ||
3728 after(TCP_SKB_CB(skb)->seq, end) ||
3729 before(TCP_SKB_CB(skb)->end_seq, start)) {
3730 tcp_collapse(sk, head, skb, start, end);
3732 if (skb == (struct sk_buff *)&tp->out_of_order_queue)
3734 /* Start new segment */
3735 start = TCP_SKB_CB(skb)->seq;
3736 end = TCP_SKB_CB(skb)->end_seq;
3738 if (before(TCP_SKB_CB(skb)->seq, start))
3739 start = TCP_SKB_CB(skb)->seq;
3740 if (after(TCP_SKB_CB(skb)->end_seq, end))
3741 end = TCP_SKB_CB(skb)->end_seq;
3746 /* Reduce allocated memory if we can, trying to get
3747 * the socket within its memory limits again.
3749 * Return less than zero if we should start dropping frames
3750 * until the socket owning process reads some of the data
3751 * to stabilize the situation.
3753 static int tcp_prune_queue(struct sock *sk)
3755 struct tcp_opt *tp = tcp_sk(sk);
3757 SOCK_DEBUG(sk, "prune_queue: c=%x\n", tp->copied_seq);
3759 NET_INC_STATS_BH(PruneCalled);
3761 if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
3762 tcp_clamp_window(sk, tp);
3763 else if (tcp_memory_pressure)
3764 tp->rcv_ssthresh = min(tp->rcv_ssthresh, 4U * tp->advmss);
3766 tcp_collapse_ofo_queue(sk);
3767 tcp_collapse(sk, sk->sk_receive_queue.next,
3768 (struct sk_buff*)&sk->sk_receive_queue,
3769 tp->copied_seq, tp->rcv_nxt);
3770 tcp_mem_reclaim(sk);
3772 if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf)
3775 /* Collapsing did not help, destructive actions follow.
3776 * This must not ever occur. */
3778 /* First, purge the out_of_order queue. */
3779 if (skb_queue_len(&tp->out_of_order_queue)) {
3780 NET_ADD_STATS_BH(OfoPruned,
3781 skb_queue_len(&tp->out_of_order_queue));
3782 __skb_queue_purge(&tp->out_of_order_queue);
3784 /* Reset SACK state. A conforming SACK implementation will
3785 * do the same at a timeout based retransmit. When a connection
3786 * is in a sad state like this, we care only about integrity
3787 * of the connection not performance.
3791 tcp_mem_reclaim(sk);
3794 if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf)
3797 /* If we are really being abused, tell the caller to silently
3798 * drop receive data on the floor. It will get retransmitted
3799 * and hopefully then we'll have sufficient space.
3801 NET_INC_STATS_BH(RcvPruned);
3803 /* Massive buffer overcommit. */
3809 /* RFC2861, slow part. Adjust cwnd, after it was not full during one rto.
3810 * As additional protections, we do not touch cwnd in retransmission phases,
3811 * and if application hit its sndbuf limit recently.
3813 void tcp_cwnd_application_limited(struct sock *sk)
3815 struct tcp_opt *tp = tcp_sk(sk);
3817 if (tp->ca_state == TCP_CA_Open &&
3818 sk->sk_socket && !test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
3819 /* Limited by application or receiver window. */
3820 u32 win_used = max(tp->snd_cwnd_used, 2U);
3821 if (win_used < tp->snd_cwnd) {
3822 tp->snd_ssthresh = tcp_current_ssthresh(tp);
3823 tp->snd_cwnd = (tp->snd_cwnd + win_used) >> 1;
3825 tp->snd_cwnd_used = 0;
3827 tp->snd_cwnd_stamp = tcp_time_stamp;
3831 /* When incoming ACK allowed to free some skb from write_queue,
3832 * we remember this event in flag tp->queue_shrunk and wake up socket
3833 * on the exit from tcp input handler.
3835 * PROBLEM: sndbuf expansion does not work well with largesend.
3837 static void tcp_new_space(struct sock *sk)
3839 struct tcp_opt *tp = tcp_sk(sk);
3841 if (tp->packets_out < tp->snd_cwnd &&
3842 !(sk->sk_userlocks & SOCK_SNDBUF_LOCK) &&
3843 !tcp_memory_pressure &&
3844 atomic_read(&tcp_memory_allocated) < sysctl_tcp_mem[0]) {
3845 int sndmem = max_t(u32, tp->mss_clamp, tp->mss_cache) +
3846 MAX_TCP_HEADER + 16 + sizeof(struct sk_buff),
3847 demanded = max_t(unsigned int, tp->snd_cwnd,
3848 tp->reordering + 1);
3849 sndmem *= 2*demanded;
3850 if (sndmem > sk->sk_sndbuf)
3851 sk->sk_sndbuf = min(sndmem, sysctl_tcp_wmem[2]);
3852 tp->snd_cwnd_stamp = tcp_time_stamp;
3855 sk->sk_write_space(sk);
3858 static inline void tcp_check_space(struct sock *sk)
3860 struct tcp_opt *tp = tcp_sk(sk);
3862 if (tp->queue_shrunk) {
3863 tp->queue_shrunk = 0;
3864 if (sk->sk_socket &&
3865 test_bit(SOCK_NOSPACE, &sk->sk_socket->flags))
3870 static void __tcp_data_snd_check(struct sock *sk, struct sk_buff *skb)
3872 struct tcp_opt *tp = tcp_sk(sk);
3874 if (after(TCP_SKB_CB(skb)->end_seq, tp->snd_una + tp->snd_wnd) ||
3875 tcp_packets_in_flight(tp) >= tp->snd_cwnd ||
3876 tcp_write_xmit(sk, tp->nonagle))
3877 tcp_check_probe_timer(sk, tp);
3880 static __inline__ void tcp_data_snd_check(struct sock *sk)
3882 struct tcp_opt *tp = tcp_sk(sk);
3883 struct sk_buff *skb = tp->send_head;
3886 __tcp_data_snd_check(sk, skb);
3887 tcp_check_space(sk);
3891 * Check if sending an ack is needed.
3893 static void __tcp_ack_snd_check(struct sock *sk, int ofo_possible)
3895 struct tcp_opt *tp = tcp_sk(sk);
3897 /* More than one full frame received... */
3898 if (((tp->rcv_nxt - tp->rcv_wup) > tp->ack.rcv_mss
3899 /* ... and right edge of window advances far enough.
3900 * (tcp_recvmsg() will send ACK otherwise). Or...
3902 && __tcp_select_window(sk) >= tp->rcv_wnd) ||
3903 /* We ACK each frame or... */
3904 tcp_in_quickack_mode(tp) ||
3905 /* We have out of order data. */
3907 skb_peek(&tp->out_of_order_queue))) {
3908 /* Then ack it now */
3911 /* Else, send delayed ack. */
3912 tcp_send_delayed_ack(sk);
3916 static __inline__ void tcp_ack_snd_check(struct sock *sk)
3918 struct tcp_opt *tp = tcp_sk(sk);
3919 if (!tcp_ack_scheduled(tp)) {
3920 /* We sent a data segment already. */
3923 __tcp_ack_snd_check(sk, 1);
3927 * This routine is only called when we have urgent data
3928 * signalled. Its the 'slow' part of tcp_urg. It could be
3929 * moved inline now as tcp_urg is only called from one
3930 * place. We handle URGent data wrong. We have to - as
3931 * BSD still doesn't use the correction from RFC961.
3932 * For 1003.1g we should support a new option TCP_STDURG to permit
3933 * either form (or just set the sysctl tcp_stdurg).
3936 static void tcp_check_urg(struct sock * sk, struct tcphdr * th)
3938 struct tcp_opt *tp = tcp_sk(sk);
3939 u32 ptr = ntohs(th->urg_ptr);
3941 if (ptr && !sysctl_tcp_stdurg)
3943 ptr += ntohl(th->seq);
3945 /* Ignore urgent data that we've already seen and read. */
3946 if (after(tp->copied_seq, ptr))
3949 /* Do not replay urg ptr.
3951 * NOTE: interesting situation not covered by specs.
3952 * Misbehaving sender may send urg ptr, pointing to segment,
3953 * which we already have in ofo queue. We are not able to fetch
3954 * such data and will stay in TCP_URG_NOTYET until will be eaten
3955 * by recvmsg(). Seems, we are not obliged to handle such wicked
3956 * situations. But it is worth to think about possibility of some
3957 * DoSes using some hypothetical application level deadlock.
3959 if (before(ptr, tp->rcv_nxt))
3962 /* Do we already have a newer (or duplicate) urgent pointer? */
3963 if (tp->urg_data && !after(ptr, tp->urg_seq))
3966 /* Tell the world about our new urgent pointer. */
3969 /* We may be adding urgent data when the last byte read was
3970 * urgent. To do this requires some care. We cannot just ignore
3971 * tp->copied_seq since we would read the last urgent byte again
3972 * as data, nor can we alter copied_seq until this data arrives
3973 * or we break the sematics of SIOCATMARK (and thus sockatmark())
3975 * NOTE. Double Dutch. Rendering to plain English: author of comment
3976 * above did something sort of send("A", MSG_OOB); send("B", MSG_OOB);
3977 * and expect that both A and B disappear from stream. This is _wrong_.
3978 * Though this happens in BSD with high probability, this is occasional.
3979 * Any application relying on this is buggy. Note also, that fix "works"
3980 * only in this artificial test. Insert some normal data between A and B and we will
3981 * decline of BSD again. Verdict: it is better to remove to trap
3984 if (tp->urg_seq == tp->copied_seq && tp->urg_data &&
3985 !sock_flag(sk, SOCK_URGINLINE) &&
3986 tp->copied_seq != tp->rcv_nxt) {
3987 struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
3989 if (skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq)) {
3990 __skb_unlink(skb, skb->list);
3995 tp->urg_data = TCP_URG_NOTYET;
3998 /* Disable header prediction. */
4002 /* This is the 'fast' part of urgent handling. */
4003 static void tcp_urg(struct sock *sk, struct sk_buff *skb, struct tcphdr *th)
4005 struct tcp_opt *tp = tcp_sk(sk);
4007 /* Check if we get a new urgent pointer - normally not. */
4009 tcp_check_urg(sk,th);
4011 /* Do we wait for any urgent data? - normally not... */
4012 if (tp->urg_data == TCP_URG_NOTYET) {
4013 u32 ptr = tp->urg_seq - ntohl(th->seq) + (th->doff * 4) -
4016 /* Is the urgent pointer pointing into this packet? */
4017 if (ptr < skb->len) {
4019 if (skb_copy_bits(skb, ptr, &tmp, 1))
4021 tp->urg_data = TCP_URG_VALID | tmp;
4022 if (!sock_flag(sk, SOCK_DEAD))
4023 sk->sk_data_ready(sk, 0);
4028 static int tcp_copy_to_iovec(struct sock *sk, struct sk_buff *skb, int hlen)
4030 struct tcp_opt *tp = tcp_sk(sk);
4031 int chunk = skb->len - hlen;
4035 if (skb->ip_summed==CHECKSUM_UNNECESSARY)
4036 err = skb_copy_datagram_iovec(skb, hlen, tp->ucopy.iov, chunk);
4038 err = skb_copy_and_csum_datagram_iovec(skb, hlen,
4042 tp->ucopy.len -= chunk;
4043 tp->copied_seq += chunk;
4044 tcp_rcv_space_adjust(sk);
4051 static int __tcp_checksum_complete_user(struct sock *sk, struct sk_buff *skb)
4055 if (sock_owned_by_user(sk)) {
4057 result = __tcp_checksum_complete(skb);
4060 result = __tcp_checksum_complete(skb);
4065 static __inline__ int
4066 tcp_checksum_complete_user(struct sock *sk, struct sk_buff *skb)
4068 return skb->ip_summed != CHECKSUM_UNNECESSARY &&
4069 __tcp_checksum_complete_user(sk, skb);
4073 * TCP receive function for the ESTABLISHED state.
4075 * It is split into a fast path and a slow path. The fast path is
4077 * - A zero window was announced from us - zero window probing
4078 * is only handled properly in the slow path.
4079 * - Out of order segments arrived.
4080 * - Urgent data is expected.
4081 * - There is no buffer space left
4082 * - Unexpected TCP flags/window values/header lengths are received
4083 * (detected by checking the TCP header against pred_flags)
4084 * - Data is sent in both directions. Fast path only supports pure senders
4085 * or pure receivers (this means either the sequence number or the ack
4086 * value must stay constant)
4087 * - Unexpected TCP option.
4089 * When these conditions are not satisfied it drops into a standard
4090 * receive procedure patterned after RFC793 to handle all cases.
4091 * The first three cases are guaranteed by proper pred_flags setting,
4092 * the rest is checked inline. Fast processing is turned on in
4093 * tcp_data_queue when everything is OK.
4095 int tcp_rcv_established(struct sock *sk, struct sk_buff *skb,
4096 struct tcphdr *th, unsigned len)
4098 struct tcp_opt *tp = tcp_sk(sk);
4101 * Header prediction.
4102 * The code loosely follows the one in the famous
4103 * "30 instruction TCP receive" Van Jacobson mail.
4105 * Van's trick is to deposit buffers into socket queue
4106 * on a device interrupt, to call tcp_recv function
4107 * on the receive process context and checksum and copy
4108 * the buffer to user space. smart...
4110 * Our current scheme is not silly either but we take the
4111 * extra cost of the net_bh soft interrupt processing...
4112 * We do checksum and copy also but from device to kernel.
4117 /* pred_flags is 0xS?10 << 16 + snd_wnd
4118 * if header_predition is to be made
4119 * 'S' will always be tp->tcp_header_len >> 2
4120 * '?' will be 0 for the fast path, otherwise pred_flags is 0 to
4121 * turn it off (when there are holes in the receive
4122 * space for instance)
4123 * PSH flag is ignored.
4126 if ((tcp_flag_word(th) & TCP_HP_BITS) == tp->pred_flags &&
4127 TCP_SKB_CB(skb)->seq == tp->rcv_nxt) {
4128 int tcp_header_len = tp->tcp_header_len;
4130 /* Timestamp header prediction: tcp_header_len
4131 * is automatically equal to th->doff*4 due to pred_flags
4135 /* Check timestamp */
4136 if (tcp_header_len == sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) {
4137 __u32 *ptr = (__u32 *)(th + 1);
4139 /* No? Slow path! */
4140 if (*ptr != ntohl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16)
4141 | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP))
4146 tp->rcv_tsval = ntohl(*ptr);
4148 tp->rcv_tsecr = ntohl(*ptr);
4150 /* If PAWS failed, check it more carefully in slow path */
4151 if ((s32)(tp->rcv_tsval - tp->ts_recent) < 0)
4154 /* DO NOT update ts_recent here, if checksum fails
4155 * and timestamp was corrupted part, it will result
4156 * in a hung connection since we will drop all
4157 * future packets due to the PAWS test.
4161 if (len <= tcp_header_len) {
4162 /* Bulk data transfer: sender */
4163 if (len == tcp_header_len) {
4164 /* Predicted packet is in window by definition.
4165 * seq == rcv_nxt and rcv_wup <= rcv_nxt.
4166 * Hence, check seq<=rcv_wup reduces to:
4168 if (tcp_header_len ==
4169 (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) &&
4170 tp->rcv_nxt == tp->rcv_wup)
4171 tcp_store_ts_recent(tp);
4173 tcp_rcv_rtt_measure_ts(tp, skb);
4175 /* We know that such packets are checksummed
4178 tcp_ack(sk, skb, 0);
4180 tcp_data_snd_check(sk);
4182 } else { /* Header too small */
4183 TCP_INC_STATS_BH(TcpInErrs);
4189 if (tp->ucopy.task == current &&
4190 tp->copied_seq == tp->rcv_nxt &&
4191 len - tcp_header_len <= tp->ucopy.len &&
4192 sock_owned_by_user(sk)) {
4193 __set_current_state(TASK_RUNNING);
4195 if (!tcp_copy_to_iovec(sk, skb, tcp_header_len)) {
4196 /* Predicted packet is in window by definition.
4197 * seq == rcv_nxt and rcv_wup <= rcv_nxt.
4198 * Hence, check seq<=rcv_wup reduces to:
4200 if (tcp_header_len ==
4201 (sizeof(struct tcphdr) +
4202 TCPOLEN_TSTAMP_ALIGNED) &&
4203 tp->rcv_nxt == tp->rcv_wup)
4204 tcp_store_ts_recent(tp);
4206 tcp_rcv_rtt_measure_ts(tp, skb);
4208 __skb_pull(skb, tcp_header_len);
4209 tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
4210 NET_INC_STATS_BH(TCPHPHitsToUser);
4215 if (tcp_checksum_complete_user(sk, skb))
4218 /* Predicted packet is in window by definition.
4219 * seq == rcv_nxt and rcv_wup <= rcv_nxt.
4220 * Hence, check seq<=rcv_wup reduces to:
4222 if (tcp_header_len ==
4223 (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) &&
4224 tp->rcv_nxt == tp->rcv_wup)
4225 tcp_store_ts_recent(tp);
4227 tcp_rcv_rtt_measure_ts(tp, skb);
4229 if ((int)skb->truesize > sk->sk_forward_alloc)
4232 NET_INC_STATS_BH(TCPHPHits);
4234 /* Bulk data transfer: receiver */
4235 __skb_pull(skb,tcp_header_len);
4236 __skb_queue_tail(&sk->sk_receive_queue, skb);
4237 tcp_set_owner_r(skb, sk);
4238 tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
4241 tcp_event_data_recv(sk, tp, skb);
4243 if (TCP_SKB_CB(skb)->ack_seq != tp->snd_una) {
4244 /* Well, only one small jumplet in fast path... */
4245 tcp_ack(sk, skb, FLAG_DATA);
4246 tcp_data_snd_check(sk);
4247 if (!tcp_ack_scheduled(tp))
4252 if (tcp_in_quickack_mode(tp)) {
4255 tcp_send_delayed_ack(sk);
4258 __tcp_ack_snd_check(sk, 0);
4265 sk->sk_data_ready(sk, 0);
4271 if (len < (th->doff<<2) || tcp_checksum_complete_user(sk, skb))
4275 * RFC1323: H1. Apply PAWS check first.
4277 if (tcp_fast_parse_options(skb, th, tp) && tp->saw_tstamp &&
4278 tcp_paws_discard(tp, skb)) {
4280 NET_INC_STATS_BH(PAWSEstabRejected);
4281 tcp_send_dupack(sk, skb);
4284 /* Resets are accepted even if PAWS failed.
4286 ts_recent update must be made after we are sure
4287 that the packet is in window.
4292 * Standard slow path.
4295 if (!tcp_sequence(tp, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq)) {
4296 /* RFC793, page 37: "In all states except SYN-SENT, all reset
4297 * (RST) segments are validated by checking their SEQ-fields."
4298 * And page 69: "If an incoming segment is not acceptable,
4299 * an acknowledgment should be sent in reply (unless the RST bit
4300 * is set, if so drop the segment and return)".
4303 tcp_send_dupack(sk, skb);
4312 tcp_replace_ts_recent(tp, TCP_SKB_CB(skb)->seq);
4314 if (th->syn && !before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
4315 TCP_INC_STATS_BH(TcpInErrs);
4316 NET_INC_STATS_BH(TCPAbortOnSyn);
4323 tcp_ack(sk, skb, FLAG_SLOWPATH);
4325 tcp_rcv_rtt_measure_ts(tp, skb);
4327 /* Process urgent data. */
4328 tcp_urg(sk, skb, th);
4330 /* step 7: process the segment text */
4331 tcp_data_queue(sk, skb);
4333 tcp_data_snd_check(sk);
4334 tcp_ack_snd_check(sk);
4338 TCP_INC_STATS_BH(TcpInErrs);
4345 static int tcp_rcv_synsent_state_process(struct sock *sk, struct sk_buff *skb,
4346 struct tcphdr *th, unsigned len)
4348 struct tcp_opt *tp = tcp_sk(sk);
4349 int saved_clamp = tp->mss_clamp;
4351 tcp_parse_options(skb, tp, 0);
4355 * "If the state is SYN-SENT then
4356 * first check the ACK bit
4357 * If the ACK bit is set
4358 * If SEG.ACK =< ISS, or SEG.ACK > SND.NXT, send
4359 * a reset (unless the RST bit is set, if so drop
4360 * the segment and return)"
4362 * We do not send data with SYN, so that RFC-correct
4365 if (TCP_SKB_CB(skb)->ack_seq != tp->snd_nxt)
4366 goto reset_and_undo;
4368 if (tp->saw_tstamp && tp->rcv_tsecr &&
4369 !between(tp->rcv_tsecr, tp->retrans_stamp,
4371 NET_INC_STATS_BH(PAWSActiveRejected);
4372 goto reset_and_undo;
4375 /* Now ACK is acceptable.
4377 * "If the RST bit is set
4378 * If the ACK was acceptable then signal the user "error:
4379 * connection reset", drop the segment, enter CLOSED state,
4380 * delete TCB, and return."
4389 * "fifth, if neither of the SYN or RST bits is set then
4390 * drop the segment and return."
4396 goto discard_and_undo;
4399 * "If the SYN bit is on ...
4400 * are acceptable then ...
4401 * (our SYN has been ACKed), change the connection
4402 * state to ESTABLISHED..."
4405 TCP_ECN_rcv_synack(tp, th);
4406 if (tp->ecn_flags&TCP_ECN_OK)
4407 sk->sk_no_largesend = 1;
4409 tp->snd_wl1 = TCP_SKB_CB(skb)->seq;
4410 tcp_ack(sk, skb, FLAG_SLOWPATH);
4412 /* Ok.. it's good. Set up sequence numbers and
4413 * move to established.
4415 tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1;
4416 tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
4418 /* RFC1323: The window in SYN & SYN/ACK segments is
4421 tp->snd_wnd = ntohs(th->window);
4422 tcp_init_wl(tp, TCP_SKB_CB(skb)->ack_seq, TCP_SKB_CB(skb)->seq);
4424 if (!tp->wscale_ok) {
4425 tp->snd_wscale = tp->rcv_wscale = 0;
4426 tp->window_clamp = min(tp->window_clamp, 65535U);
4429 if (tp->saw_tstamp) {
4431 tp->tcp_header_len =
4432 sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
4433 tp->advmss -= TCPOLEN_TSTAMP_ALIGNED;
4434 tcp_store_ts_recent(tp);
4436 tp->tcp_header_len = sizeof(struct tcphdr);
4439 if (tp->sack_ok && sysctl_tcp_fack)
4442 tcp_sync_mss(sk, tp->pmtu_cookie);
4443 tcp_initialize_rcv_mss(sk);
4445 /* Remember, tcp_poll() does not lock socket!
4446 * Change state from SYN-SENT only after copied_seq
4447 * is initialized. */
4448 tp->copied_seq = tp->rcv_nxt;
4450 tcp_set_state(sk, TCP_ESTABLISHED);
4452 /* Make sure socket is routed, for correct metrics. */
4453 tp->af_specific->rebuild_header(sk);
4455 tcp_init_metrics(sk);
4457 /* Prevent spurious tcp_cwnd_restart() on first data
4460 tp->lsndtime = tcp_time_stamp;
4462 tcp_init_buffer_space(sk);
4464 if (sock_flag(sk, SOCK_KEEPOPEN))
4465 tcp_reset_keepalive_timer(sk, keepalive_time_when(tp));
4467 if (!tp->snd_wscale)
4468 __tcp_fast_path_on(tp, tp->snd_wnd);
4472 if (!sock_flag(sk, SOCK_DEAD)) {
4473 sk->sk_state_change(sk);
4474 sk_wake_async(sk, 0, POLL_OUT);
4477 if (tp->write_pending || tp->defer_accept || tp->ack.pingpong) {
4478 /* Save one ACK. Data will be ready after
4479 * several ticks, if write_pending is set.
4481 * It may be deleted, but with this feature tcpdumps
4482 * look so _wonderfully_ clever, that I was not able
4483 * to stand against the temptation 8) --ANK
4485 tcp_schedule_ack(tp);
4486 tp->ack.lrcvtime = tcp_time_stamp;
4487 tp->ack.ato = TCP_ATO_MIN;
4488 tcp_incr_quickack(tp);
4489 tcp_enter_quickack_mode(tp);
4490 tcp_reset_xmit_timer(sk, TCP_TIME_DACK, TCP_DELACK_MAX);
4501 /* No ACK in the segment */
4505 * "If the RST bit is set
4507 * Otherwise (no ACK) drop the segment and return."
4510 goto discard_and_undo;
4514 if (tp->ts_recent_stamp && tp->saw_tstamp && tcp_paws_check(tp, 0))
4515 goto discard_and_undo;
4518 /* We see SYN without ACK. It is attempt of
4519 * simultaneous connect with crossed SYNs.
4520 * Particularly, it can be connect to self.
4522 tcp_set_state(sk, TCP_SYN_RECV);
4524 if (tp->saw_tstamp) {
4526 tcp_store_ts_recent(tp);
4527 tp->tcp_header_len =
4528 sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
4530 tp->tcp_header_len = sizeof(struct tcphdr);
4533 tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1;
4534 tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
4536 /* RFC1323: The window in SYN & SYN/ACK segments is
4539 tp->snd_wnd = ntohs(th->window);
4540 tp->snd_wl1 = TCP_SKB_CB(skb)->seq;
4541 tp->max_window = tp->snd_wnd;
4543 TCP_ECN_rcv_syn(tp, th);
4544 if (tp->ecn_flags&TCP_ECN_OK)
4545 sk->sk_no_largesend = 1;
4547 tcp_sync_mss(sk, tp->pmtu_cookie);
4548 tcp_initialize_rcv_mss(sk);
4551 tcp_send_synack(sk);
4553 /* Note, we could accept data and URG from this segment.
4554 * There are no obstacles to make this.
4556 * However, if we ignore data in ACKless segments sometimes,
4557 * we have no reasons to accept it sometimes.
4558 * Also, seems the code doing it in step6 of tcp_rcv_state_process
4559 * is not flawless. So, discard packet for sanity.
4560 * Uncomment this return to process the data.
4567 /* "fifth, if neither of the SYN or RST bits is set then
4568 * drop the segment and return."
4572 tcp_clear_options(tp);
4573 tp->mss_clamp = saved_clamp;
4577 tcp_clear_options(tp);
4578 tp->mss_clamp = saved_clamp;
4584 * This function implements the receiving procedure of RFC 793 for
4585 * all states except ESTABLISHED and TIME_WAIT.
4586 * It's called from both tcp_v4_rcv and tcp_v6_rcv and should be
4587 * address independent.
4590 int tcp_rcv_state_process(struct sock *sk, struct sk_buff *skb,
4591 struct tcphdr *th, unsigned len)
4593 struct tcp_opt *tp = tcp_sk(sk);
4598 switch (sk->sk_state) {
4610 if(tp->af_specific->conn_request(sk, skb) < 0)
4615 /* Now we have several options: In theory there is
4616 * nothing else in the frame. KA9Q has an option to
4617 * send data with the syn, BSD accepts data with the
4618 * syn up to the [to be] advertised window and
4619 * Solaris 2.1 gives you a protocol error. For now
4620 * we just ignore it, that fits the spec precisely
4621 * and avoids incompatibilities. It would be nice in
4622 * future to drop through and process the data.
4624 * Now that TTCP is starting to be used we ought to
4626 * But, this leaves one open to an easy denial of
4627 * service attack, and SYN cookies can't defend
4628 * against this problem. So, we drop the data
4629 * in the interest of security over speed.
4638 queued = tcp_rcv_synsent_state_process(sk, skb, th, len);
4642 /* Do step6 onward by hand. */
4643 tcp_urg(sk, skb, th);
4645 tcp_data_snd_check(sk);
4649 if (tcp_fast_parse_options(skb, th, tp) && tp->saw_tstamp &&
4650 tcp_paws_discard(tp, skb)) {
4652 NET_INC_STATS_BH(PAWSEstabRejected);
4653 tcp_send_dupack(sk, skb);
4656 /* Reset is accepted even if it did not pass PAWS. */
4659 /* step 1: check sequence number */
4660 if (!tcp_sequence(tp, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq)) {
4662 tcp_send_dupack(sk, skb);
4666 /* step 2: check RST bit */
4672 tcp_replace_ts_recent(tp, TCP_SKB_CB(skb)->seq);
4674 /* step 3: check security and precedence [ignored] */
4678 * Check for a SYN in window.
4680 if (th->syn && !before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
4681 NET_INC_STATS_BH(TCPAbortOnSyn);
4686 /* step 5: check the ACK field */
4688 int acceptable = tcp_ack(sk, skb, FLAG_SLOWPATH);
4690 switch(sk->sk_state) {
4693 tp->copied_seq = tp->rcv_nxt;
4695 tcp_set_state(sk, TCP_ESTABLISHED);
4696 sk->sk_state_change(sk);
4698 /* Note, that this wakeup is only for marginal
4699 * crossed SYN case. Passively open sockets
4700 * are not waked up, because sk->sk_sleep ==
4701 * NULL and sk->sk_socket == NULL.
4703 if (sk->sk_socket) {
4704 sk_wake_async(sk,0,POLL_OUT);
4707 tp->snd_una = TCP_SKB_CB(skb)->ack_seq;
4708 tp->snd_wnd = ntohs(th->window) <<
4710 tcp_init_wl(tp, TCP_SKB_CB(skb)->ack_seq,
4711 TCP_SKB_CB(skb)->seq);
4713 /* tcp_ack considers this ACK as duplicate
4714 * and does not calculate rtt.
4715 * Fix it at least with timestamps.
4717 if (tp->saw_tstamp && tp->rcv_tsecr &&
4719 tcp_ack_saw_tstamp(tp, 0);
4722 tp->advmss -= TCPOLEN_TSTAMP_ALIGNED;
4724 /* Make sure socket is routed, for
4727 tp->af_specific->rebuild_header(sk);
4729 tcp_init_metrics(sk);
4731 /* Prevent spurious tcp_cwnd_restart() on
4732 * first data packet.
4734 tp->lsndtime = tcp_time_stamp;
4736 tcp_initialize_rcv_mss(sk);
4737 tcp_init_buffer_space(sk);
4738 tcp_fast_path_on(tp);
4745 if (tp->snd_una == tp->write_seq) {
4746 tcp_set_state(sk, TCP_FIN_WAIT2);
4747 sk->sk_shutdown |= SEND_SHUTDOWN;
4748 dst_confirm(sk->sk_dst_cache);
4750 if (!sock_flag(sk, SOCK_DEAD))
4751 /* Wake up lingering close() */
4752 sk->sk_state_change(sk);
4756 if (tp->linger2 < 0 ||
4757 (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
4758 after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt))) {
4760 NET_INC_STATS_BH(TCPAbortOnData);
4764 tmo = tcp_fin_time(tp);
4765 if (tmo > TCP_TIMEWAIT_LEN) {
4766 tcp_reset_keepalive_timer(sk, tmo - TCP_TIMEWAIT_LEN);
4767 } else if (th->fin || sock_owned_by_user(sk)) {
4768 /* Bad case. We could lose such FIN otherwise.
4769 * It is not a big problem, but it looks confusing
4770 * and not so rare event. We still can lose it now,
4771 * if it spins in bh_lock_sock(), but it is really
4774 tcp_reset_keepalive_timer(sk, tmo);
4776 tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
4784 if (tp->snd_una == tp->write_seq) {
4785 tcp_time_wait(sk, TCP_TIME_WAIT, 0);
4791 if (tp->snd_una == tp->write_seq) {
4792 tcp_update_metrics(sk);
4801 /* step 6: check the URG bit */
4802 tcp_urg(sk, skb, th);
4804 /* step 7: process the segment text */
4805 switch (sk->sk_state) {
4806 case TCP_CLOSE_WAIT:
4809 if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt))
4813 /* RFC 793 says to queue data in these states,
4814 * RFC 1122 says we MUST send a reset.
4815 * BSD 4.4 also does reset.
4817 if (sk->sk_shutdown & RCV_SHUTDOWN) {
4818 if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
4819 after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt)) {
4820 NET_INC_STATS_BH(TCPAbortOnData);
4826 case TCP_ESTABLISHED:
4827 tcp_data_queue(sk, skb);
4832 /* tcp_data could move socket to TIME-WAIT */
4833 if (sk->sk_state != TCP_CLOSE) {
4834 tcp_data_snd_check(sk);
4835 tcp_ack_snd_check(sk);
4845 EXPORT_SYMBOL(sysctl_tcp_ecn);
4846 EXPORT_SYMBOL(sysctl_tcp_reordering);
4847 EXPORT_SYMBOL(tcp_cwnd_application_limited);
4848 EXPORT_SYMBOL(tcp_parse_options);
4849 EXPORT_SYMBOL(tcp_rcv_established);
4850 EXPORT_SYMBOL(tcp_rcv_state_process);