2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS TCP/IP protocol driver
4 * FILE: transport/tcp/tcp_input.c
5 * PURPOSE: Transmission Control Protocol
6 * PROGRAMMERS: Casper S. Hornstrup (chorns@users.sourceforge.net)
8 * CSH 15-01-2003 Imported from linux kernel 2.4.20
12 * INET An implementation of the TCP/IP protocol suite for the LINUX
13 * operating system. INET is implemented using the BSD Socket
14 * interface as the means of communication with the user level.
16 * Implementation of the Transmission Control Protocol(TCP).
20 * Authors: Ross Biro, <bir7@leland.Stanford.Edu>
21 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
22 * Mark Evans, <evansmp@uhura.aston.ac.uk>
23 * Corey Minyard <wf-rch!minyard@relay.EU.net>
24 * Florian La Roche, <flla@stud.uni-sb.de>
25 * Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
26 * Linus Torvalds, <torvalds@cs.helsinki.fi>
27 * Alan Cox, <gw4pts@gw4pts.ampr.org>
28 * Matthew Dillon, <dillon@apollo.west.oic.com>
29 * Arnt Gulbrandsen, <agulbra@nvg.unit.no>
30 * Jorge Cwik, <jorge@laser.satlink.net>
35 * Pedro Roque : Fast Retransmit/Recovery.
37 * Retransmit queue handled by TCP.
38 * Better retransmit timer handling.
39 * New congestion avoidance.
43 * Eric : Fast Retransmit.
44 * Randy Scott : MSS option defines.
45 * Eric Schenk : Fixes to slow start algorithm.
46 * Eric Schenk : Yet another double ACK bug.
47 * Eric Schenk : Delayed ACK bug fixes.
48 * Eric Schenk : Floyd style fast retrans war avoidance.
49 * David S. Miller : Don't allow zero congestion window.
50 * Eric Schenk : Fix retransmitter so that it sends
51 * next packet on ack of previous packet.
52 * Andi Kleen : Moved open_request checking here
53 * and process RSTs for open_requests.
54 * Andi Kleen : Better prune_queue, and other fixes.
55 * Andrey Savochkin: Fix RTT measurements in the presnce of
57 * Andrey Savochkin: Check sequence numbers correctly when
58 * removing SACKs due to in sequence incoming
60 * Andi Kleen: Make sure we never ack data there is not
61 * enough room for. Also make this condition
62 * a fatal error if it might still happen.
63 * Andi Kleen: Add tcp_measure_rcv_mss to make
64 * connections with MSS<min(MTU,ann. MSS)
65 * work without delayed acks.
66 * Andi Kleen: Process packets with PSH set in the
68 * J Hadi Salim: ECN support
71 * Panu Kuhlberg: Experimental audit of TCP (re)transmission
72 * engine. Lots of bugs are found.
76 #include <linux/config.h>
78 #include <linux/sysctl.h>
80 #include <net/inet_common.h>
81 #include <linux/ipsec.h>
87 int sysctl_tcp_timestamps = 1;
88 int sysctl_tcp_window_scaling = 1;
89 int sysctl_tcp_sack = 1;
90 int sysctl_tcp_fack = 1;
91 int sysctl_tcp_reordering = TCP_FASTRETRANS_THRESH;
92 #ifdef CONFIG_INET_ECN
93 int sysctl_tcp_ecn = 1;
95 int sysctl_tcp_ecn = 0;
97 int sysctl_tcp_dsack = 1;
98 int sysctl_tcp_app_win = 31;
99 int sysctl_tcp_adv_win_scale = 2;
101 int sysctl_tcp_stdurg = 0;
102 int sysctl_tcp_rfc1337 = 0;
103 //int sysctl_tcp_max_orphans = NR_FILE;
105 #define FLAG_DATA 0x01 /* Incoming frame contained data. */
106 #define FLAG_WIN_UPDATE 0x02 /* Incoming ACK was a window update. */
107 #define FLAG_DATA_ACKED 0x04 /* This ACK acknowledged new data. */
108 #define FLAG_RETRANS_DATA_ACKED 0x08 /* "" "" some of which was retransmitted. */
109 #define FLAG_SYN_ACKED 0x10 /* This ACK acknowledged SYN. */
110 #define FLAG_DATA_SACKED 0x20 /* New SACK. */
111 #define FLAG_ECE 0x40 /* ECE in this ACK */
112 #define FLAG_DATA_LOST 0x80 /* SACK detected data lossage. */
113 #define FLAG_SLOWPATH 0x100 /* Do not skip RFC checks for window update.*/
115 #define FLAG_ACKED (FLAG_DATA_ACKED|FLAG_SYN_ACKED)
116 #define FLAG_NOT_DUP (FLAG_DATA|FLAG_WIN_UPDATE|FLAG_ACKED)
117 #define FLAG_CA_ALERT (FLAG_DATA_SACKED|FLAG_ECE)
118 #define FLAG_FORWARD_PROGRESS (FLAG_ACKED|FLAG_DATA_SACKED)
120 #define IsReno(tp) ((tp)->sack_ok == 0)
121 #define IsFack(tp) ((tp)->sack_ok & 2)
122 #define IsDSack(tp) ((tp)->sack_ok & 4)
124 #define TCP_REMNANT (TCP_FLAG_FIN|TCP_FLAG_URG|TCP_FLAG_SYN|TCP_FLAG_PSH)
126 /* Adapt the MSS value used to make delayed ack decision to the
129 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;
174 static void tcp_incr_quickack(struct tcp_opt *tp)
177 unsigned quickacks = tp->rcv_wnd/(2*tp->ack.rcv_mss);
181 if (quickacks > tp->ack.quick)
182 tp->ack.quick = min(quickacks, TCP_MAX_QUICKACKS);
186 void tcp_enter_quickack_mode(struct tcp_opt *tp)
189 tcp_incr_quickack(tp);
190 tp->ack.pingpong = 0;
191 tp->ack.ato = TCP_ATO_MIN;
195 /* Send ACKs quickly, if "quick" count is not exhausted
196 * and the session is not interactive.
199 static __inline__ int tcp_in_quickack_mode(struct tcp_opt *tp)
202 return (tp->ack.quick && !tp->ack.pingpong);
208 /* Buffer size and advertised window tuning.
210 * 1. Tuning sk->sndbuf, when connection enters established state.
213 static void tcp_fixup_sndbuf(struct sock *sk)
216 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
217 int sndmem = tp->mss_clamp+MAX_TCP_HEADER+16+sizeof(struct sk_buff);
219 if (sk->sndbuf < 3*sndmem)
220 sk->sndbuf = min(3*sndmem, sysctl_tcp_wmem[2]);
224 /* 2. Tuning advertised window (window_clamp, rcv_ssthresh)
226 * All tcp_full_space() is split to two parts: "network" buffer, allocated
227 * forward and advertised in receiver window (tp->rcv_wnd) and
228 * "application buffer", required to isolate scheduling/application
229 * latencies from network.
230 * window_clamp is maximal advertised window. It can be less than
231 * tcp_full_space(), in this case tcp_full_space() - window_clamp
232 * is reserved for "application" buffer. The less window_clamp is
233 * the smoother our behaviour from viewpoint of network, but the lower
234 * throughput and the higher sensitivity of the connection to losses. 8)
236 * rcv_ssthresh is more strict window_clamp used at "slow start"
237 * phase to predict further behaviour of this connection.
238 * It is used for two goals:
239 * - to enforce header prediction at sender, even when application
240 * requires some significant "application buffer". It is check #1.
241 * - to prevent pruning of receive queue because of misprediction
242 * of receiver window. Check #2.
244 * The scheme does not work when sender sends good segments opening
245 * window and then starts to feed us spagetti. But it should work
246 * in common situations. Otherwise, we have to rely on queue collapsing.
249 /* Slow part of check#2. */
251 __tcp_grow_window(struct sock *sk, struct tcp_opt *tp, struct sk_buff *skb)
255 int truesize = tcp_win_from_space(skb->truesize)/2;
256 int window = tcp_full_space(sk)/2;
258 while (tp->rcv_ssthresh <= window) {
259 if (truesize <= skb->len)
260 return 2*tp->ack.rcv_mss;
271 static __inline__ void
272 tcp_grow_window(struct sock *sk, struct tcp_opt *tp, struct sk_buff *skb)
276 if (tp->rcv_ssthresh < tp->window_clamp &&
277 (int)tp->rcv_ssthresh < tcp_space(sk) &&
278 !tcp_memory_pressure) {
281 /* Check #2. Increase window, if skb with such overhead
282 * will fit to rcvbuf in future.
284 if (tcp_win_from_space(skb->truesize) <= skb->len)
287 incr = __tcp_grow_window(sk, tp, skb);
290 tp->rcv_ssthresh = min(tp->rcv_ssthresh + incr, tp->window_clamp);
297 /* 3. Tuning rcvbuf, when connection enters established state. */
299 static void tcp_fixup_rcvbuf(struct sock *sk)
302 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
303 int rcvmem = tp->advmss+MAX_TCP_HEADER+16+sizeof(struct sk_buff);
305 /* Try to select rcvbuf so that 4 mss-sized segments
306 * will fit to window and correspoding skbs will fit to our rcvbuf.
307 * (was 3; 4 is minimum to allow fast retransmit to work.)
309 while (tcp_win_from_space(rcvmem) < tp->advmss)
311 if (sk->rcvbuf < 4*rcvmem)
312 sk->rcvbuf = min(4*rcvmem, sysctl_tcp_rmem[2]);
316 /* 4. Try to fixup all. It is made iimediately after connection enters
319 static void tcp_init_buffer_space(struct sock *sk)
322 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
325 if (!(sk->userlocks&SOCK_RCVBUF_LOCK))
326 tcp_fixup_rcvbuf(sk);
327 if (!(sk->userlocks&SOCK_SNDBUF_LOCK))
328 tcp_fixup_sndbuf(sk);
330 maxwin = tcp_full_space(sk);
332 if (tp->window_clamp >= maxwin) {
333 tp->window_clamp = maxwin;
335 if (sysctl_tcp_app_win && maxwin>4*tp->advmss)
336 tp->window_clamp = max(maxwin-(maxwin>>sysctl_tcp_app_win), 4*tp->advmss);
339 /* Force reservation of one segment. */
340 if (sysctl_tcp_app_win &&
341 tp->window_clamp > 2*tp->advmss &&
342 tp->window_clamp + tp->advmss > maxwin)
343 tp->window_clamp = max(2*tp->advmss, maxwin-tp->advmss);
345 tp->rcv_ssthresh = min(tp->rcv_ssthresh, tp->window_clamp);
346 tp->snd_cwnd_stamp = tcp_time_stamp;
350 /* 5. Recalculate window clamp after socket hit its memory bounds. */
351 static void tcp_clamp_window(struct sock *sk, struct tcp_opt *tp)
355 unsigned int app_win = tp->rcv_nxt - tp->copied_seq;
360 skb_queue_walk(&tp->out_of_order_queue, skb) {
364 /* If overcommit is due to out of order segments,
365 * do not clamp window. Try to expand rcvbuf instead.
368 if (sk->rcvbuf < sysctl_tcp_rmem[2] &&
369 !(sk->userlocks&SOCK_RCVBUF_LOCK) &&
370 !tcp_memory_pressure &&
371 atomic_read(&tcp_memory_allocated) < sysctl_tcp_mem[0])
372 sk->rcvbuf = min(atomic_read(&sk->rmem_alloc), sysctl_tcp_rmem[2]);
374 if (atomic_read(&sk->rmem_alloc) > sk->rcvbuf) {
376 if (atomic_read(&sk->rmem_alloc) >= 2*sk->rcvbuf)
378 if (app_win > tp->ack.rcv_mss)
379 app_win -= tp->ack.rcv_mss;
380 app_win = max(app_win, 2U*tp->advmss);
383 tp->window_clamp = min(tp->window_clamp, app_win);
384 tp->rcv_ssthresh = min(tp->window_clamp, 2U*tp->advmss);
389 /* There is something which you must keep in mind when you analyze the
390 * behavior of the tp->ato delayed ack timeout interval. When a
391 * connection starts up, we want to ack as quickly as possible. The
392 * problem is that "good" TCP's do slow start at the beginning of data
393 * transmission. The means that until we send the first few ACK's the
394 * sender will sit on his end and only queue most of his data, because
395 * he can only send snd_cwnd unacked packets at any given time. For
396 * each ACK we send, he increments snd_cwnd and transmits more of his
399 static void tcp_event_data_recv(struct sock *sk, struct tcp_opt *tp, struct sk_buff *skb)
404 tcp_schedule_ack(tp);
406 tcp_measure_rcv_mss(tp, skb);
408 now = tcp_time_stamp;
411 /* The _first_ data packet received, initialize
412 * delayed ACK engine.
414 tcp_incr_quickack(tp);
415 tp->ack.ato = TCP_ATO_MIN;
417 int m = now - tp->ack.lrcvtime;
419 if (m <= TCP_ATO_MIN/2) {
420 /* The fastest case is the first. */
421 tp->ack.ato = (tp->ack.ato>>1) + TCP_ATO_MIN/2;
422 } else if (m < tp->ack.ato) {
423 tp->ack.ato = (tp->ack.ato>>1) + m;
424 if (tp->ack.ato > tp->rto)
425 tp->ack.ato = tp->rto;
426 } else if (m > tp->rto) {
427 /* Too long gap. Apparently sender falled to
428 * restart window, so that we send ACKs quickly.
430 tcp_incr_quickack(tp);
434 tp->ack.lrcvtime = now;
436 TCP_ECN_check_ce(tp, skb);
439 tcp_grow_window(sk, tp, skb);
443 /* Called to compute a smoothed rtt estimate. The data fed to this
444 * routine either comes from timestamps, or from segments that were
445 * known _not_ to have been retransmitted [see Karn/Partridge
446 * Proceedings SIGCOMM 87]. The algorithm is from the SIGCOMM 88
447 * piece by Van Jacobson.
448 * NOTE: the next three routines used to be one big routine.
449 * To save cycles in the RFC 1323 implementation it was better to break
450 * it up into three procedures. -- erics
452 static __inline__ void tcp_rtt_estimator(struct tcp_opt *tp, __u32 mrtt)
455 long m = mrtt; /* RTT */
457 /* The following amusing code comes from Jacobson's
458 * article in SIGCOMM '88. Note that rtt and mdev
459 * are scaled versions of rtt and mean deviation.
460 * This is designed to be as fast as possible
461 * m stands for "measurement".
463 * On a 1990 paper the rto value is changed to:
464 * RTO = rtt + 4 * mdev
466 * Funny. This algorithm seems to be very broken.
467 * These formulae increase RTO, when it should be decreased, increase
468 * too slowly, when it should be incresed fastly, decrease too fastly
469 * etc. I guess in BSD RTO takes ONE value, so that it is absolutely
470 * does not matter how to _calculate_ it. Seems, it was trap
471 * that VJ failed to avoid. 8)
476 m -= (tp->srtt >> 3); /* m is now error in rtt est */
477 tp->srtt += m; /* rtt = 7/8 rtt + 1/8 new */
479 m = -m; /* m is now abs(error) */
480 m -= (tp->mdev >> 2); /* similar update on mdev */
481 /* This is similar to one of Eifel findings.
482 * Eifel blocks mdev updates when rtt decreases.
483 * This solution is a bit different: we use finer gain
484 * for mdev in this case (alpha*beta).
485 * Like Eifel it also prevents growth of rto,
486 * but also it limits too fast rto decreases,
487 * happening in pure Eifel.
492 m -= (tp->mdev >> 2); /* similar update on mdev */
494 tp->mdev += m; /* mdev = 3/4 mdev + 1/4 new */
495 if (tp->mdev > tp->mdev_max) {
496 tp->mdev_max = tp->mdev;
497 if (tp->mdev_max > tp->rttvar)
498 tp->rttvar = tp->mdev_max;
500 if (after(tp->snd_una, tp->rtt_seq)) {
501 if (tp->mdev_max < tp->rttvar)
502 tp->rttvar -= (tp->rttvar-tp->mdev_max)>>2;
503 tp->rtt_seq = tp->snd_nxt;
504 tp->mdev_max = TCP_RTO_MIN;
507 /* no previous measure. */
508 tp->srtt = m<<3; /* take the measured time to be rtt */
509 tp->mdev = m<<1; /* make sure rto = 3*rtt */
510 tp->mdev_max = tp->rttvar = max(tp->mdev, TCP_RTO_MIN);
511 tp->rtt_seq = tp->snd_nxt;
516 /* Calculate rto without backoff. This is the second half of Van Jacobson's
517 * routine referred to above.
519 static __inline__ void tcp_set_rto(struct tcp_opt *tp)
522 /* Old crap is replaced with new one. 8)
525 * 1. If rtt variance happened to be less 50msec, it is hallucination.
526 * It cannot be less due to utterly erratic ACK generation made
527 * at least by solaris and freebsd. "Erratic ACKs" has _nothing_
528 * to do with delayed acks, because at cwnd>2 true delack timeout
529 * is invisible. Actually, Linux-2.4 also generates erratic
530 * ACKs in some curcumstances.
532 tp->rto = (tp->srtt >> 3) + tp->rttvar;
534 /* 2. Fixups made earlier cannot be right.
535 * If we do not estimate RTO correctly without them,
536 * all the algo is pure shit and should be replaced
537 * with correct one. It is exaclty, which we pretend to do.
542 /* NOTE: clamping at TCP_RTO_MIN is not required, current algo
543 * guarantees that rto is higher.
545 static __inline__ void tcp_bound_rto(struct tcp_opt *tp)
548 if (tp->rto > TCP_RTO_MAX)
549 tp->rto = TCP_RTO_MAX;
553 /* Save metrics learned by this TCP session.
554 This function is called only, when TCP finishes successfully
555 i.e. when it enters TIME-WAIT or goes from LAST-ACK to CLOSE.
557 void tcp_update_metrics(struct sock *sk)
560 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
561 struct dst_entry *dst = __sk_dst_get(sk);
565 if (dst && (dst->flags&DST_HOST)) {
568 if (tp->backoff || !tp->srtt) {
569 /* This session failed to estimate rtt. Why?
570 * Probably, no packets returned in time.
573 if (!(dst->mxlock&(1<<RTAX_RTT)))
578 m = dst->rtt - tp->srtt;
580 /* If newly calculated rtt larger than stored one,
581 * store new one. Otherwise, use EWMA. Remember,
582 * rtt overestimation is always better than underestimation.
584 if (!(dst->mxlock&(1<<RTAX_RTT))) {
591 if (!(dst->mxlock&(1<<RTAX_RTTVAR))) {
595 /* Scale deviation to rttvar fixed point */
600 if (m >= dst->rttvar)
603 dst->rttvar -= (dst->rttvar - m)>>2;
606 if (tp->snd_ssthresh >= 0xFFFF) {
607 /* Slow start still did not finish. */
609 !(dst->mxlock&(1<<RTAX_SSTHRESH)) &&
610 (tp->snd_cwnd>>1) > dst->ssthresh)
611 dst->ssthresh = (tp->snd_cwnd>>1);
612 if (!(dst->mxlock&(1<<RTAX_CWND)) &&
613 tp->snd_cwnd > dst->cwnd)
614 dst->cwnd = tp->snd_cwnd;
615 } else if (tp->snd_cwnd > tp->snd_ssthresh &&
616 tp->ca_state == TCP_CA_Open) {
617 /* Cong. avoidance phase, cwnd is reliable. */
618 if (!(dst->mxlock&(1<<RTAX_SSTHRESH)))
619 dst->ssthresh = max(tp->snd_cwnd>>1, tp->snd_ssthresh);
620 if (!(dst->mxlock&(1<<RTAX_CWND)))
621 dst->cwnd = (dst->cwnd + tp->snd_cwnd)>>1;
623 /* Else slow start did not finish, cwnd is non-sense,
624 ssthresh may be also invalid.
626 if (!(dst->mxlock&(1<<RTAX_CWND)))
627 dst->cwnd = (dst->cwnd + tp->snd_ssthresh)>>1;
629 !(dst->mxlock&(1<<RTAX_SSTHRESH)) &&
630 tp->snd_ssthresh > dst->ssthresh)
631 dst->ssthresh = tp->snd_ssthresh;
634 if (!(dst->mxlock&(1<<RTAX_REORDERING))) {
635 if (dst->reordering < tp->reordering &&
636 tp->reordering != sysctl_tcp_reordering)
637 dst->reordering = tp->reordering;
643 /* Increase initial CWND conservatively: if estimated
644 * RTT is low enough (<20msec) or if we have some preset ssthresh.
646 * Numbers are taken from RFC2414.
648 __u32 tcp_init_cwnd(struct tcp_opt *tp)
653 if (tp->mss_cache > 1460)
656 cwnd = (tp->mss_cache > 1095) ? 3 : 4;
658 if (!tp->srtt || (tp->snd_ssthresh >= 0xFFFF && tp->srtt > ((HZ/50)<<3)))
660 else if (cwnd > tp->snd_ssthresh)
661 cwnd = tp->snd_ssthresh;
663 return min_t(__u32, cwnd, tp->snd_cwnd_clamp);
669 /* Initialize metrics on socket. */
671 static void tcp_init_metrics(struct sock *sk)
674 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
675 struct dst_entry *dst = __sk_dst_get(sk);
682 if (dst->mxlock&(1<<RTAX_CWND))
683 tp->snd_cwnd_clamp = dst->cwnd;
685 tp->snd_ssthresh = dst->ssthresh;
686 if (tp->snd_ssthresh > tp->snd_cwnd_clamp)
687 tp->snd_ssthresh = tp->snd_cwnd_clamp;
689 if (dst->reordering && tp->reordering != dst->reordering) {
691 tp->reordering = dst->reordering;
697 if (!tp->srtt && dst->rtt < (TCP_TIMEOUT_INIT<<3))
700 /* Initial rtt is determined from SYN,SYN-ACK.
701 * The segment is small and rtt may appear much
702 * less than real one. Use per-dst memory
703 * to make it more realistic.
705 * A bit of theory. RTT is time passed after "normal" sized packet
706 * is sent until it is ACKed. In normal curcumstances sending small
707 * packets force peer to delay ACKs and calculation is correct too.
708 * The algorithm is adaptive and, provided we follow specs, it
709 * NEVER underestimate RTT. BUT! If peer tries to make some clever
710 * tricks sort of "quick acks" for time long enough to decrease RTT
711 * to low value, and then abruptly stops to do it and starts to delay
712 * ACKs, wait for troubles.
714 if (dst->rtt > tp->srtt)
716 if (dst->rttvar > tp->mdev) {
717 tp->mdev = dst->rttvar;
718 tp->mdev_max = tp->rttvar = max(tp->mdev, TCP_RTO_MIN);
722 if (tp->rto < TCP_TIMEOUT_INIT && !tp->saw_tstamp)
724 tp->snd_cwnd = tcp_init_cwnd(tp);
725 tp->snd_cwnd_stamp = tcp_time_stamp;
729 /* Play conservative. If timestamps are not
730 * supported, TCP will fail to recalculate correct
731 * rtt, if initial rto is too small. FORGET ALL AND RESET!
733 if (!tp->saw_tstamp && tp->srtt) {
735 tp->mdev = tp->mdev_max = tp->rttvar = TCP_TIMEOUT_INIT;
736 tp->rto = TCP_TIMEOUT_INIT;
741 static void tcp_update_reordering(struct tcp_opt *tp, int metric, int ts)
744 if (metric > tp->reordering) {
745 tp->reordering = min(TCP_MAX_REORDERING, metric);
747 /* This exciting event is worth to be remembered. 8) */
749 NET_INC_STATS_BH(TCPTSReorder);
751 NET_INC_STATS_BH(TCPRenoReorder);
753 NET_INC_STATS_BH(TCPFACKReorder);
755 NET_INC_STATS_BH(TCPSACKReorder);
756 #if FASTRETRANS_DEBUG > 1
757 printk(KERN_DEBUG "Disorder%d %d %u f%u s%u rr%d\n",
758 tp->sack_ok, tp->ca_state,
759 tp->reordering, tp->fackets_out, tp->sacked_out,
760 tp->undo_marker ? tp->undo_retrans : 0);
762 /* Disable FACK yet. */
768 /* This procedure tags the retransmission queue when SACKs arrive.
770 * We have three tag bits: SACKED(S), RETRANS(R) and LOST(L).
771 * Packets in queue with these bits set are counted in variables
772 * sacked_out, retrans_out and lost_out, correspondingly.
774 * Valid combinations are:
775 * Tag InFlight Description
776 * 0 1 - orig segment is in flight.
777 * S 0 - nothing flies, orig reached receiver.
778 * L 0 - nothing flies, orig lost by net.
779 * R 2 - both orig and retransmit are in flight.
780 * L|R 1 - orig is lost, retransmit is in flight.
781 * S|R 1 - orig reached receiver, retrans is still in flight.
782 * (L|S|R is logically valid, it could occur when L|R is sacked,
783 * but it is equivalent to plain S and code short-curcuits it to S.
784 * L|S is logically invalid, it would mean -1 packet in flight 8))
786 * These 6 states form finite state machine, controlled by the following events:
787 * 1. New ACK (+SACK) arrives. (tcp_sacktag_write_queue())
788 * 2. Retransmission. (tcp_retransmit_skb(), tcp_xmit_retransmit_queue())
789 * 3. Loss detection event of one of three flavors:
790 * A. Scoreboard estimator decided the packet is lost.
791 * A'. Reno "three dupacks" marks head of queue lost.
792 * A''. Its FACK modfication, head until snd.fack is lost.
793 * B. SACK arrives sacking data transmitted after never retransmitted
795 * C. SACK arrives sacking SND.NXT at the moment, when the
796 * segment was retransmitted.
797 * 4. D-SACK added new rule: D-SACK changes any tag to S.
799 * It is pleasant to note, that state diagram turns out to be commutative,
800 * so that we are allowed not to be bothered by order of our actions,
801 * when multiple events arrive simultaneously. (see the function below).
803 * Reordering detection.
804 * --------------------
805 * Reordering metric is maximal distance, which a packet can be displaced
806 * in packet stream. With SACKs we can estimate it:
808 * 1. SACK fills old hole and the corresponding segment was not
809 * ever retransmitted -> reordering. Alas, we cannot use it
810 * when segment was retransmitted.
811 * 2. The last flaw is solved with D-SACK. D-SACK arrives
812 * for retransmitted and already SACKed segment -> reordering..
813 * Both of these heuristics are not used in Loss state, when we cannot
814 * account for retransmits accurately.
817 tcp_sacktag_write_queue(struct sock *sk, struct sk_buff *ack_skb, u32 prior_snd_una)
820 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
821 unsigned char *ptr = ack_skb->h.raw + TCP_SKB_CB(ack_skb)->sacked;
822 struct tcp_sack_block *sp = (struct tcp_sack_block *)(ptr+2);
823 int num_sacks = (ptr[1] - TCPOLEN_SACK_BASE)>>3;
824 int reord = tp->packets_out;
826 u32 lost_retrans = 0;
832 prior_fackets = tp->fackets_out;
834 for (i=0; i<num_sacks; i++, sp++) {
836 __u32 start_seq = ntohl(sp->start_seq);
837 __u32 end_seq = ntohl(sp->end_seq);
841 /* Check for D-SACK. */
843 u32 ack = TCP_SKB_CB(ack_skb)->ack_seq;
845 if (before(start_seq, ack)) {
848 NET_INC_STATS_BH(TCPDSACKRecv);
849 } else if (num_sacks > 1 &&
850 !after(end_seq, ntohl(sp[1].end_seq)) &&
851 !before(start_seq, ntohl(sp[1].start_seq))) {
854 NET_INC_STATS_BH(TCPDSACKOfoRecv);
857 /* D-SACK for already forgotten data...
858 * Do dumb counting. */
860 !after(end_seq, prior_snd_una) &&
861 after(end_seq, tp->undo_marker))
864 /* Eliminate too old ACKs, but take into
865 * account more or less fresh ones, they can
866 * contain valid SACK info.
868 if (before(ack, prior_snd_una-tp->max_window))
872 /* Event "B" in the comment above. */
873 if (after(end_seq, tp->high_seq))
874 flag |= FLAG_DATA_LOST;
876 for_retrans_queue(skb, sk, tp) {
877 u8 sacked = TCP_SKB_CB(skb)->sacked;
880 /* The retransmission queue is always in order, so
881 * we can short-circuit the walk early.
883 if(!before(TCP_SKB_CB(skb)->seq, end_seq))
888 in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
889 !before(end_seq, TCP_SKB_CB(skb)->end_seq);
891 /* Account D-SACK for retransmitted packet. */
892 if ((dup_sack && in_sack) &&
893 (sacked & TCPCB_RETRANS) &&
894 after(TCP_SKB_CB(skb)->end_seq, tp->undo_marker))
897 /* The frame is ACKed. */
898 if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una)) {
899 if (sacked&TCPCB_RETRANS) {
900 if ((dup_sack && in_sack) &&
901 (sacked&TCPCB_SACKED_ACKED))
902 reord = min(fack_count, reord);
904 /* If it was in a hole, we detected reordering. */
905 if (fack_count < prior_fackets &&
906 !(sacked&TCPCB_SACKED_ACKED))
907 reord = min(fack_count, reord);
910 /* Nothing to do; acked frame is about to be dropped. */
914 if ((sacked&TCPCB_SACKED_RETRANS) &&
915 after(end_seq, TCP_SKB_CB(skb)->ack_seq) &&
916 (!lost_retrans || after(end_seq, lost_retrans)))
917 lost_retrans = end_seq;
922 if (!(sacked&TCPCB_SACKED_ACKED)) {
923 if (sacked & TCPCB_SACKED_RETRANS) {
924 /* If the segment is not tagged as lost,
925 * we do not clear RETRANS, believing
926 * that retransmission is still in flight.
928 if (sacked & TCPCB_LOST) {
929 TCP_SKB_CB(skb)->sacked &= ~(TCPCB_LOST|TCPCB_SACKED_RETRANS);
934 /* New sack for not retransmitted frame,
935 * which was in hole. It is reordering.
937 if (!(sacked & TCPCB_RETRANS) &&
938 fack_count < prior_fackets)
939 reord = min(fack_count, reord);
941 if (sacked & TCPCB_LOST) {
942 TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
947 TCP_SKB_CB(skb)->sacked |= TCPCB_SACKED_ACKED;
948 flag |= FLAG_DATA_SACKED;
951 if (fack_count > tp->fackets_out)
952 tp->fackets_out = fack_count;
954 if (dup_sack && (sacked&TCPCB_RETRANS))
955 reord = min(fack_count, reord);
958 /* D-SACK. We can detect redundant retransmission
959 * in S|R and plain R frames and clear it.
960 * undo_retrans is decreased above, L|R frames
961 * are accounted above as well.
964 (TCP_SKB_CB(skb)->sacked&TCPCB_SACKED_RETRANS)) {
965 TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
971 /* Check for lost retransmit. This superb idea is
972 * borrowed from "ratehalving". Event "C".
973 * Later note: FACK people cheated me again 8),
974 * we have to account for reordering! Ugly,
977 if (lost_retrans && tp->ca_state == TCP_CA_Recovery) {
980 for_retrans_queue(skb, sk, tp) {
981 if (after(TCP_SKB_CB(skb)->seq, lost_retrans))
983 if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una))
985 if ((TCP_SKB_CB(skb)->sacked&TCPCB_SACKED_RETRANS) &&
986 after(lost_retrans, TCP_SKB_CB(skb)->ack_seq) &&
988 !before(lost_retrans, TCP_SKB_CB(skb)->ack_seq+tp->reordering*tp->mss_cache))) {
989 TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
992 if (!(TCP_SKB_CB(skb)->sacked&(TCPCB_LOST|TCPCB_SACKED_ACKED))) {
994 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
995 flag |= FLAG_DATA_SACKED;
996 NET_INC_STATS_BH(TCPLostRetransmit);
1002 tp->left_out = tp->sacked_out + tp->lost_out;
1004 if (reord < tp->fackets_out && tp->ca_state != TCP_CA_Loss)
1005 tcp_update_reordering(tp, (tp->fackets_out+1)-reord, 0);
1007 #if FASTRETRANS_DEBUG > 0
1008 BUG_TRAP((int)tp->sacked_out >= 0);
1009 BUG_TRAP((int)tp->lost_out >= 0);
1010 BUG_TRAP((int)tp->retrans_out >= 0);
1011 BUG_TRAP((int)tcp_packets_in_flight(tp) >= 0);
1019 void tcp_clear_retrans(struct tcp_opt *tp)
1023 tp->retrans_out = 0;
1025 tp->fackets_out = 0;
1029 tp->undo_marker = 0;
1030 tp->undo_retrans = 0;
1034 /* Enter Loss state. If "how" is not zero, forget all SACK information
1035 * and reset tags completely, otherwise preserve SACKs. If receiver
1036 * dropped its ofo queue, we will know this due to reneging detection.
1038 void tcp_enter_loss(struct sock *sk, int how)
1041 struct tcp_opt *tp = &sk->tp_pinfo.af_tcp;
1042 struct sk_buff *skb;
1045 /* Reduce ssthresh if it has not yet been made inside this window. */
1046 if (tp->ca_state <= TCP_CA_Disorder ||
1047 tp->snd_una == tp->high_seq ||
1048 (tp->ca_state == TCP_CA_Loss && !tp->retransmits)) {
1049 tp->prior_ssthresh = tcp_current_ssthresh(tp);
1050 tp->snd_ssthresh = tcp_recalc_ssthresh(tp);
1053 tp->snd_cwnd_cnt = 0;
1054 tp->snd_cwnd_stamp = tcp_time_stamp;
1056 tcp_clear_retrans(tp);
1058 /* Push undo marker, if it was plain RTO and nothing
1059 * was retransmitted. */
1061 tp->undo_marker = tp->snd_una;
1063 for_retrans_queue(skb, sk, tp) {
1065 if (TCP_SKB_CB(skb)->sacked&TCPCB_RETRANS)
1066 tp->undo_marker = 0;
1067 TCP_SKB_CB(skb)->sacked &= (~TCPCB_TAGBITS)|TCPCB_SACKED_ACKED;
1068 if (!(TCP_SKB_CB(skb)->sacked&TCPCB_SACKED_ACKED) || how) {
1069 TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_ACKED;
1070 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1074 tp->fackets_out = cnt;
1077 tcp_sync_left_out(tp);
1079 tp->reordering = min_t(unsigned int, tp->reordering, sysctl_tcp_reordering);
1080 tp->ca_state = TCP_CA_Loss;
1081 tp->high_seq = tp->snd_nxt;
1082 TCP_ECN_queue_cwr(tp);
1086 static int tcp_check_sack_reneging(struct sock *sk, struct tcp_opt *tp)
1089 struct sk_buff *skb;
1091 /* If ACK arrived pointing to a remembered SACK,
1092 * it means that our remembered SACKs do not reflect
1093 * real state of receiver i.e.
1094 * receiver _host_ is heavily congested (or buggy).
1095 * Do processing similar to RTO timeout.
1097 if ((skb = skb_peek(&sk->write_queue)) != NULL &&
1098 (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)) {
1099 NET_INC_STATS_BH(TCPSACKReneging);
1101 tcp_enter_loss(sk, 1);
1103 tcp_retransmit_skb(sk, skb_peek(&sk->write_queue));
1104 tcp_reset_xmit_timer(sk, TCP_TIME_RETRANS, tp->rto);
1113 static inline int tcp_fackets_out(struct tcp_opt *tp)
1116 return IsReno(tp) ? tp->sacked_out+1 : tp->fackets_out;
1122 static inline int tcp_skb_timedout(struct tcp_opt *tp, struct sk_buff *skb)
1125 return (tcp_time_stamp - TCP_SKB_CB(skb)->when > tp->rto);
1131 static inline int tcp_head_timedout(struct sock *sk, struct tcp_opt *tp)
1134 return tp->packets_out && tcp_skb_timedout(tp, skb_peek(&sk->write_queue));
1140 /* Linux NewReno/SACK/FACK/ECN state machine.
1141 * --------------------------------------
1143 * "Open" Normal state, no dubious events, fast path.
1144 * "Disorder" In all the respects it is "Open",
1145 * but requires a bit more attention. It is entered when
1146 * we see some SACKs or dupacks. It is split of "Open"
1147 * mainly to move some processing from fast path to slow one.
1148 * "CWR" CWND was reduced due to some Congestion Notification event.
1149 * It can be ECN, ICMP source quench, local device congestion.
1150 * "Recovery" CWND was reduced, we are fast-retransmitting.
1151 * "Loss" CWND was reduced due to RTO timeout or SACK reneging.
1153 * tcp_fastretrans_alert() is entered:
1154 * - each incoming ACK, if state is not "Open"
1155 * - when arrived ACK is unusual, namely:
1160 * Counting packets in flight is pretty simple.
1162 * in_flight = packets_out - left_out + retrans_out
1164 * packets_out is SND.NXT-SND.UNA counted in packets.
1166 * retrans_out is number of retransmitted segments.
1168 * left_out is number of segments left network, but not ACKed yet.
1170 * left_out = sacked_out + lost_out
1172 * sacked_out: Packets, which arrived to receiver out of order
1173 * and hence not ACKed. With SACKs this number is simply
1174 * amount of SACKed data. Even without SACKs
1175 * it is easy to give pretty reliable estimate of this number,
1176 * counting duplicate ACKs.
1178 * lost_out: Packets lost by network. TCP has no explicit
1179 * "loss notification" feedback from network (for now).
1180 * It means that this number can be only _guessed_.
1181 * Actually, it is the heuristics to predict lossage that
1182 * distinguishes different algorithms.
1184 * F.e. after RTO, when all the queue is considered as lost,
1185 * lost_out = packets_out and in_flight = retrans_out.
1187 * Essentially, we have now two algorithms counting
1190 * FACK: It is the simplest heuristics. As soon as we decided
1191 * that something is lost, we decide that _all_ not SACKed
1192 * packets until the most forward SACK are lost. I.e.
1193 * lost_out = fackets_out - sacked_out and left_out = fackets_out.
1194 * It is absolutely correct estimate, if network does not reorder
1195 * packets. And it loses any connection to reality when reordering
1196 * takes place. We use FACK by default until reordering
1197 * is suspected on the path to this destination.
1199 * NewReno: when Recovery is entered, we assume that one segment
1200 * is lost (classic Reno). While we are in Recovery and
1201 * a partial ACK arrives, we assume that one more packet
1202 * is lost (NewReno). This heuristics are the same in NewReno
1205 * Imagine, that's all! Forget about all this shamanism about CWND inflation
1206 * deflation etc. CWND is real congestion window, never inflated, changes
1207 * only according to classic VJ rules.
1209 * Really tricky (and requiring careful tuning) part of algorithm
1210 * is hidden in functions tcp_time_to_recover() and tcp_xmit_retransmit_queue().
1211 * The first determines the moment _when_ we should reduce CWND and,
1212 * hence, slow down forward transmission. In fact, it determines the moment
1213 * when we decide that hole is caused by loss, rather than by a reorder.
1215 * tcp_xmit_retransmit_queue() decides, _what_ we should retransmit to fill
1216 * holes, caused by lost packets.
1218 * And the most logically complicated part of algorithm is undo
1219 * heuristics. We detect false retransmits due to both too early
1220 * fast retransmit (reordering) and underestimated RTO, analyzing
1221 * timestamps and D-SACKs. When we detect that some segments were
1222 * retransmitted by mistake and CWND reduction was wrong, we undo
1223 * window reduction and abort recovery phase. This logic is hidden
1224 * inside several functions named tcp_try_undo_<something>.
1227 /* This function decides, when we should leave Disordered state
1228 * and enter Recovery phase, reducing congestion window.
1230 * Main question: may we further continue forward transmission
1231 * with the same cwnd?
1234 tcp_time_to_recover(struct sock *sk, struct tcp_opt *tp)
1237 /* Trick#1: The loss is proven. */
1241 /* Not-A-Trick#2 : Classic rule... */
1242 if (tcp_fackets_out(tp) > tp->reordering)
1245 /* Trick#3 : when we use RFC2988 timer restart, fast
1246 * retransmit can be triggered by timeout of queue head.
1248 if (tcp_head_timedout(sk, tp))
1251 /* Trick#4: It is still not OK... But will it be useful to delay
1254 if (tp->packets_out <= tp->reordering &&
1255 tp->sacked_out >= max_t(__u32, tp->packets_out/2, sysctl_tcp_reordering) &&
1256 !tcp_may_send_now(sk, tp)) {
1257 /* We have nothing to send. This connection is limited
1258 * either by receiver window or by application.
1269 /* If we receive more dupacks than we expected counting segments
1270 * in assumption of absent reordering, interpret this as reordering.
1271 * The only another reason could be bug in receiver TCP.
1273 static void tcp_check_reno_reordering(struct tcp_opt *tp, int addend)
1278 holes = max(tp->lost_out, 1U);
1279 holes = min(holes, tp->packets_out);
1281 if (tp->sacked_out + holes > tp->packets_out) {
1282 tp->sacked_out = tp->packets_out - holes;
1283 tcp_update_reordering(tp, tp->packets_out+addend, 0);
1288 /* Emulate SACKs for SACKless connection: account for a new dupack. */
1290 static void tcp_add_reno_sack(struct tcp_opt *tp)
1294 tcp_check_reno_reordering(tp, 0);
1295 tcp_sync_left_out(tp);
1299 /* Account for ACK, ACKing some data in Reno Recovery phase. */
1301 static void tcp_remove_reno_sacks(struct sock *sk, struct tcp_opt *tp, int acked)
1305 /* One ACK acked hole. The rest eat duplicate ACKs. */
1306 if (acked-1 >= tp->sacked_out)
1309 tp->sacked_out -= acked-1;
1311 tcp_check_reno_reordering(tp, acked);
1312 tcp_sync_left_out(tp);
1316 static inline void tcp_reset_reno_sack(struct tcp_opt *tp)
1320 tp->left_out = tp->lost_out;
1324 /* Mark head of queue up as lost. */
1326 tcp_mark_head_lost(struct sock *sk, struct tcp_opt *tp, int packets, u32 high_seq)
1329 struct sk_buff *skb;
1332 BUG_TRAP(cnt <= tp->packets_out);
1334 for_retrans_queue(skb, sk, tp) {
1335 if (--cnt < 0 || after(TCP_SKB_CB(skb)->end_seq, high_seq))
1337 if (!(TCP_SKB_CB(skb)->sacked&TCPCB_TAGBITS)) {
1338 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1342 tcp_sync_left_out(tp);
1346 /* Account newly detected lost packet(s) */
1348 static void tcp_update_scoreboard(struct sock *sk, struct tcp_opt *tp)
1352 int lost = tp->fackets_out - tp->reordering;
1355 tcp_mark_head_lost(sk, tp, lost, tp->high_seq);
1357 tcp_mark_head_lost(sk, tp, 1, tp->high_seq);
1360 /* New heuristics: it is possible only after we switched
1361 * to restart timer each time when something is ACKed.
1362 * Hence, we can detect timed out packets during fast
1363 * retransmit without falling to slow start.
1365 if (tcp_head_timedout(sk, tp)) {
1366 struct sk_buff *skb;
1368 for_retrans_queue(skb, sk, tp) {
1369 if (tcp_skb_timedout(tp, skb) &&
1370 !(TCP_SKB_CB(skb)->sacked&TCPCB_TAGBITS)) {
1371 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1375 tcp_sync_left_out(tp);
1380 /* CWND moderation, preventing bursts due to too big ACKs
1381 * in dubious situations.
1383 static __inline__ void tcp_moderate_cwnd(struct tcp_opt *tp)
1386 tp->snd_cwnd = min(tp->snd_cwnd,
1387 tcp_packets_in_flight(tp)+tcp_max_burst(tp));
1388 tp->snd_cwnd_stamp = tcp_time_stamp;
1392 /* Decrease cwnd each second ack. */
1394 static void tcp_cwnd_down(struct tcp_opt *tp)
1397 int decr = tp->snd_cwnd_cnt + 1;
1399 tp->snd_cwnd_cnt = decr&1;
1402 if (decr && tp->snd_cwnd > tp->snd_ssthresh/2)
1403 tp->snd_cwnd -= decr;
1405 tp->snd_cwnd = min(tp->snd_cwnd, tcp_packets_in_flight(tp)+1);
1406 tp->snd_cwnd_stamp = tcp_time_stamp;
1410 /* Nothing was retransmitted or returned timestamp is less
1411 * than timestamp of the first retransmission.
1413 static __inline__ int tcp_packet_delayed(struct tcp_opt *tp)
1416 return !tp->retrans_stamp ||
1417 (tp->saw_tstamp && tp->rcv_tsecr &&
1418 (__s32)(tp->rcv_tsecr - tp->retrans_stamp) < 0);
1424 /* Undo procedures. */
1426 #if FASTRETRANS_DEBUG > 1
1427 static void DBGUNDO(struct sock *sk, struct tcp_opt *tp, const char *msg)
1430 printk(KERN_DEBUG "Undo %s %u.%u.%u.%u/%u c%u l%u ss%u/%u p%u\n",
1432 NIPQUAD(sk->daddr), ntohs(sk->dport),
1433 tp->snd_cwnd, tp->left_out,
1434 tp->snd_ssthresh, tp->prior_ssthresh, tp->packets_out);
1438 #define DBGUNDO(x...) do { } while (0)
1441 static void tcp_undo_cwr(struct tcp_opt *tp, int undo)
1444 if (tp->prior_ssthresh) {
1445 tp->snd_cwnd = max(tp->snd_cwnd, tp->snd_ssthresh<<1);
1447 if (undo && tp->prior_ssthresh > tp->snd_ssthresh) {
1448 tp->snd_ssthresh = tp->prior_ssthresh;
1449 TCP_ECN_withdraw_cwr(tp);
1452 tp->snd_cwnd = max(tp->snd_cwnd, tp->snd_ssthresh);
1454 tcp_moderate_cwnd(tp);
1455 tp->snd_cwnd_stamp = tcp_time_stamp;
1459 static inline int tcp_may_undo(struct tcp_opt *tp)
1462 return tp->undo_marker &&
1463 (!tp->undo_retrans || tcp_packet_delayed(tp));
1469 /* People celebrate: "We love our President!" */
1470 static int tcp_try_undo_recovery(struct sock *sk, struct tcp_opt *tp)
1473 if (tcp_may_undo(tp)) {
1474 /* Happy end! We did not retransmit anything
1475 * or our original transmission succeeded.
1477 DBGUNDO(sk, tp, tp->ca_state == TCP_CA_Loss ? "loss" : "retrans");
1478 tcp_undo_cwr(tp, 1);
1479 if (tp->ca_state == TCP_CA_Loss)
1480 NET_INC_STATS_BH(TCPLossUndo);
1482 NET_INC_STATS_BH(TCPFullUndo);
1483 tp->undo_marker = 0;
1485 if (tp->snd_una == tp->high_seq && IsReno(tp)) {
1486 /* Hold old state until something *above* high_seq
1487 * is ACKed. For Reno it is MUST to prevent false
1488 * fast retransmits (RFC2582). SACK TCP is safe. */
1489 tcp_moderate_cwnd(tp);
1492 tp->ca_state = TCP_CA_Open;
1499 /* Try to undo cwnd reduction, because D-SACKs acked all retransmitted data */
1500 static void tcp_try_undo_dsack(struct sock *sk, struct tcp_opt *tp)
1503 if (tp->undo_marker && !tp->undo_retrans) {
1504 DBGUNDO(sk, tp, "D-SACK");
1505 tcp_undo_cwr(tp, 1);
1506 tp->undo_marker = 0;
1507 NET_INC_STATS_BH(TCPDSACKUndo);
1512 /* Undo during fast recovery after partial ACK. */
1514 static int tcp_try_undo_partial(struct sock *sk, struct tcp_opt *tp, int acked)
1517 /* Partial ACK arrived. Force Hoe's retransmit. */
1518 int failed = IsReno(tp) || tp->fackets_out>tp->reordering;
1520 if (tcp_may_undo(tp)) {
1521 /* Plain luck! Hole if filled with delayed
1522 * packet, rather than with a retransmit.
1524 if (tp->retrans_out == 0)
1525 tp->retrans_stamp = 0;
1527 tcp_update_reordering(tp, tcp_fackets_out(tp)+acked, 1);
1529 DBGUNDO(sk, tp, "Hoe");
1530 tcp_undo_cwr(tp, 0);
1531 NET_INC_STATS_BH(TCPPartialUndo);
1533 /* So... Do not make Hoe's retransmit yet.
1534 * If the first packet was delayed, the rest
1535 * ones are most probably delayed as well.
1545 /* Undo during loss recovery after partial ACK. */
1546 static int tcp_try_undo_loss(struct sock *sk, struct tcp_opt *tp)
1549 if (tcp_may_undo(tp)) {
1550 struct sk_buff *skb;
1551 for_retrans_queue(skb, sk, tp) {
1552 TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
1554 DBGUNDO(sk, tp, "partial loss");
1556 tp->left_out = tp->sacked_out;
1557 tcp_undo_cwr(tp, 1);
1558 NET_INC_STATS_BH(TCPLossUndo);
1559 tp->retransmits = 0;
1560 tp->undo_marker = 0;
1562 tp->ca_state = TCP_CA_Open;
1571 static __inline__ void tcp_complete_cwr(struct tcp_opt *tp)
1574 tp->snd_cwnd = min(tp->snd_cwnd, tp->snd_ssthresh);
1575 tp->snd_cwnd_stamp = tcp_time_stamp;
1579 static void tcp_try_to_open(struct sock *sk, struct tcp_opt *tp, int flag)
1582 tp->left_out = tp->sacked_out;
1584 if (tp->retrans_out == 0)
1585 tp->retrans_stamp = 0;
1590 if (tp->ca_state != TCP_CA_CWR) {
1591 int state = TCP_CA_Open;
1596 state = TCP_CA_Disorder;
1598 if (tp->ca_state != state) {
1599 tp->ca_state = state;
1600 tp->high_seq = tp->snd_nxt;
1602 tcp_moderate_cwnd(tp);
1609 /* Process an event, which can update packets-in-flight not trivially.
1610 * Main goal of this function is to calculate new estimate for left_out,
1611 * taking into account both packets sitting in receiver's buffer and
1612 * packets lost by network.
1614 * Besides that it does CWND reduction, when packet loss is detected
1615 * and changes state of machine.
1617 * It does _not_ decide what to send, it is made in function
1618 * tcp_xmit_retransmit_queue().
1621 tcp_fastretrans_alert(struct sock *sk, u32 prior_snd_una,
1622 int prior_packets, int flag)
1625 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
1626 int is_dupack = (tp->snd_una == prior_snd_una && !(flag&FLAG_NOT_DUP));
1628 /* Some technical things:
1629 * 1. Reno does not count dupacks (sacked_out) automatically. */
1630 if (!tp->packets_out)
1632 /* 2. SACK counts snd_fack in packets inaccurately. */
1633 if (tp->sacked_out == 0)
1634 tp->fackets_out = 0;
1636 /* Now state machine starts.
1637 * A. ECE, hence prohibit cwnd undoing, the reduction is required. */
1639 tp->prior_ssthresh = 0;
1641 /* B. In all the states check for reneging SACKs. */
1642 if (tp->sacked_out && tcp_check_sack_reneging(sk, tp))
1645 /* C. Process data loss notification, provided it is valid. */
1646 if ((flag&FLAG_DATA_LOST) &&
1647 before(tp->snd_una, tp->high_seq) &&
1648 tp->ca_state != TCP_CA_Open &&
1649 tp->fackets_out > tp->reordering) {
1650 tcp_mark_head_lost(sk, tp, tp->fackets_out-tp->reordering, tp->high_seq);
1651 NET_INC_STATS_BH(TCPLoss);
1654 /* D. Synchronize left_out to current state. */
1655 tcp_sync_left_out(tp);
1657 /* E. Check state exit conditions. State can be terminated
1658 * when high_seq is ACKed. */
1659 if (tp->ca_state == TCP_CA_Open) {
1660 BUG_TRAP(tp->retrans_out == 0);
1661 tp->retrans_stamp = 0;
1662 } else if (!before(tp->snd_una, tp->high_seq)) {
1663 switch (tp->ca_state) {
1665 tp->retransmits = 0;
1666 if (tcp_try_undo_recovery(sk, tp))
1671 /* CWR is to be held something *above* high_seq
1672 * is ACKed for CWR bit to reach receiver. */
1673 if (tp->snd_una != tp->high_seq) {
1674 tcp_complete_cwr(tp);
1675 tp->ca_state = TCP_CA_Open;
1679 case TCP_CA_Disorder:
1680 tcp_try_undo_dsack(sk, tp);
1681 if (!tp->undo_marker ||
1682 /* For SACK case do not Open to allow to undo
1683 * catching for all duplicate ACKs. */
1684 IsReno(tp) || tp->snd_una != tp->high_seq) {
1685 tp->undo_marker = 0;
1686 tp->ca_state = TCP_CA_Open;
1690 case TCP_CA_Recovery:
1692 tcp_reset_reno_sack(tp);
1693 if (tcp_try_undo_recovery(sk, tp))
1695 tcp_complete_cwr(tp);
1700 /* F. Process state. */
1701 switch (tp->ca_state) {
1702 case TCP_CA_Recovery:
1703 if (prior_snd_una == tp->snd_una) {
1704 if (IsReno(tp) && is_dupack)
1705 tcp_add_reno_sack(tp);
1707 int acked = prior_packets - tp->packets_out;
1709 tcp_remove_reno_sacks(sk, tp, acked);
1710 is_dupack = tcp_try_undo_partial(sk, tp, acked);
1714 if (flag&FLAG_DATA_ACKED)
1715 tp->retransmits = 0;
1716 if (!tcp_try_undo_loss(sk, tp)) {
1717 tcp_moderate_cwnd(tp);
1718 tcp_xmit_retransmit_queue(sk);
1721 if (tp->ca_state != TCP_CA_Open)
1723 /* Loss is undone; fall through to processing in Open state. */
1726 if (tp->snd_una != prior_snd_una)
1727 tcp_reset_reno_sack(tp);
1729 tcp_add_reno_sack(tp);
1732 if (tp->ca_state == TCP_CA_Disorder)
1733 tcp_try_undo_dsack(sk, tp);
1735 if (!tcp_time_to_recover(sk, tp)) {
1736 tcp_try_to_open(sk, tp, flag);
1740 /* Otherwise enter Recovery state */
1743 NET_INC_STATS_BH(TCPRenoRecovery);
1745 NET_INC_STATS_BH(TCPSackRecovery);
1747 tp->high_seq = tp->snd_nxt;
1748 tp->prior_ssthresh = 0;
1749 tp->undo_marker = tp->snd_una;
1750 tp->undo_retrans = tp->retrans_out;
1752 if (tp->ca_state < TCP_CA_CWR) {
1753 if (!(flag&FLAG_ECE))
1754 tp->prior_ssthresh = tcp_current_ssthresh(tp);
1755 tp->snd_ssthresh = tcp_recalc_ssthresh(tp);
1756 TCP_ECN_queue_cwr(tp);
1759 tp->snd_cwnd_cnt = 0;
1760 tp->ca_state = TCP_CA_Recovery;
1763 if (is_dupack || tcp_head_timedout(sk, tp))
1764 tcp_update_scoreboard(sk, tp);
1766 tcp_xmit_retransmit_queue(sk);
1770 /* Read draft-ietf-tcplw-high-performance before mucking
1771 * with this code. (Superceeds RFC1323)
1773 static void tcp_ack_saw_tstamp(struct tcp_opt *tp, int flag)
1778 /* RTTM Rule: A TSecr value received in a segment is used to
1779 * update the averaged RTT measurement only if the segment
1780 * acknowledges some new data, i.e., only if it advances the
1781 * left edge of the send window.
1783 * See draft-ietf-tcplw-high-performance-00, section 3.3.
1784 * 1998/04/10 Andrey V. Savochkin <saw@msu.ru>
1786 * Changed: reset backoff as soon as we see the first valid sample.
1787 * If we do not, we get strongly overstimated rto. With timestamps
1788 * samples are accepted even from very old segments: f.e., when rtt=1
1789 * increases to 8, we retransmit 5 times and after 8 seconds delayed
1790 * answer arrives rto becomes 120 seconds! If at least one of segments
1791 * in window is lost... Voila. --ANK (010210)
1793 seq_rtt = tcp_time_stamp - tp->rcv_tsecr;
1794 tcp_rtt_estimator(tp, seq_rtt);
1801 static void tcp_ack_no_tstamp(struct tcp_opt *tp, u32 seq_rtt, int flag)
1804 /* We don't have a timestamp. Can only use
1805 * packets that are not retransmitted to determine
1806 * rtt estimates. Also, we must not reset the
1807 * backoff for rto until we get a non-retransmitted
1808 * packet. This allows us to deal with a situation
1809 * where the network delay has increased suddenly.
1810 * I.e. Karn's algorithm. (SIGCOMM '87, p5.)
1813 if (flag & FLAG_RETRANS_DATA_ACKED)
1816 tcp_rtt_estimator(tp, seq_rtt);
1823 static __inline__ void
1824 tcp_ack_update_rtt(struct tcp_opt *tp, int flag, s32 seq_rtt)
1827 /* Note that peer MAY send zero echo. In this case it is ignored. (rfc1323) */
1828 if (tp->saw_tstamp && tp->rcv_tsecr)
1829 tcp_ack_saw_tstamp(tp, flag);
1830 else if (seq_rtt >= 0)
1831 tcp_ack_no_tstamp(tp, seq_rtt, flag);
1835 /* This is Jacobson's slow start and congestion avoidance.
1836 * SIGCOMM '88, p. 328.
1838 static __inline__ void tcp_cong_avoid(struct tcp_opt *tp)
1841 if (tp->snd_cwnd <= tp->snd_ssthresh) {
1842 /* In "safe" area, increase. */
1843 if (tp->snd_cwnd < tp->snd_cwnd_clamp)
1846 /* In dangerous area, increase slowly.
1847 * In theory this is tp->snd_cwnd += 1 / tp->snd_cwnd
1849 if (tp->snd_cwnd_cnt >= tp->snd_cwnd) {
1850 if (tp->snd_cwnd < tp->snd_cwnd_clamp)
1856 tp->snd_cwnd_stamp = tcp_time_stamp;
1860 /* Restart timer after forward progress on connection.
1861 * RFC2988 recommends to restart timer to now+rto.
1864 static __inline__ void tcp_ack_packets_out(struct sock *sk, struct tcp_opt *tp)
1867 if (tp->packets_out==0) {
1868 tcp_clear_xmit_timer(sk, TCP_TIME_RETRANS);
1870 tcp_reset_xmit_timer(sk, TCP_TIME_RETRANS, tp->rto);
1875 /* Remove acknowledged frames from the retransmission queue. */
1876 static int tcp_clean_rtx_queue(struct sock *sk)
1879 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
1880 struct sk_buff *skb;
1881 __u32 now = tcp_time_stamp;
1885 while((skb=skb_peek(&sk->write_queue)) && (skb != tp->send_head)) {
1886 struct tcp_skb_cb *scb = TCP_SKB_CB(skb);
1887 __u8 sacked = scb->sacked;
1889 /* If our packet is before the ack sequence we can
1890 * discard it as it's confirmed to have arrived at
1893 if (after(scb->end_seq, tp->snd_una))
1896 /* Initial outgoing SYN's get put onto the write_queue
1897 * just like anything else we transmit. It is not
1898 * true data, and if we misinform our callers that
1899 * this ACK acks real data, we will erroneously exit
1900 * connection startup slow start one packet too
1901 * quickly. This is severely frowned upon behavior.
1903 if(!(scb->flags & TCPCB_FLAG_SYN)) {
1904 acked |= FLAG_DATA_ACKED;
1906 acked |= FLAG_SYN_ACKED;
1907 tp->retrans_stamp = 0;
1911 if(sacked & TCPCB_RETRANS) {
1912 if(sacked & TCPCB_SACKED_RETRANS)
1914 acked |= FLAG_RETRANS_DATA_ACKED;
1916 } else if (seq_rtt < 0)
1917 seq_rtt = now - scb->when;
1918 if(sacked & TCPCB_SACKED_ACKED)
1920 if(sacked & TCPCB_LOST)
1922 if(sacked & TCPCB_URG) {
1924 !before(scb->end_seq, tp->snd_up))
1927 } else if (seq_rtt < 0)
1928 seq_rtt = now - scb->when;
1932 __skb_unlink(skb, skb->list);
1933 tcp_free_skb(sk, skb);
1936 if (acked&FLAG_ACKED) {
1937 tcp_ack_update_rtt(tp, acked, seq_rtt);
1938 tcp_ack_packets_out(sk, tp);
1941 #if FASTRETRANS_DEBUG > 0
1942 BUG_TRAP((int)tp->sacked_out >= 0);
1943 BUG_TRAP((int)tp->lost_out >= 0);
1944 BUG_TRAP((int)tp->retrans_out >= 0);
1945 if (tp->packets_out==0 && tp->sack_ok) {
1947 printk(KERN_DEBUG "Leak l=%u %d\n", tp->lost_out, tp->ca_state);
1950 if (tp->sacked_out) {
1951 printk(KERN_DEBUG "Leak s=%u %d\n", tp->sacked_out, tp->ca_state);
1954 if (tp->retrans_out) {
1955 printk(KERN_DEBUG "Leak r=%u %d\n", tp->retrans_out, tp->ca_state);
1956 tp->retrans_out = 0;
1966 static void tcp_ack_probe(struct sock *sk)
1969 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
1971 /* Was it a usable window open? */
1973 if (!after(TCP_SKB_CB(tp->send_head)->end_seq, tp->snd_una + tp->snd_wnd)) {
1975 tcp_clear_xmit_timer(sk, TCP_TIME_PROBE0);
1976 /* Socket must be waked up by subsequent tcp_data_snd_check().
1977 * This function is not for random using!
1980 tcp_reset_xmit_timer(sk, TCP_TIME_PROBE0,
1981 min(tp->rto << tp->backoff, TCP_RTO_MAX));
1986 static __inline__ int tcp_ack_is_dubious(struct tcp_opt *tp, int flag)
1989 return (!(flag & FLAG_NOT_DUP) || (flag & FLAG_CA_ALERT) ||
1990 tp->ca_state != TCP_CA_Open);
1996 static __inline__ int tcp_may_raise_cwnd(struct tcp_opt *tp, int flag)
1999 return (!(flag & FLAG_ECE) || tp->snd_cwnd < tp->snd_ssthresh) &&
2000 !((1<<tp->ca_state)&(TCPF_CA_Recovery|TCPF_CA_CWR));
2006 /* Check that window update is acceptable.
2007 * The function assumes that snd_una<=ack<=snd_next.
2009 static __inline__ int
2010 tcp_may_update_window(struct tcp_opt *tp, u32 ack, u32 ack_seq, u32 nwin)
2013 return (after(ack, tp->snd_una) ||
2014 after(ack_seq, tp->snd_wl1) ||
2015 (ack_seq == tp->snd_wl1 && nwin > tp->snd_wnd));
2021 /* Update our send window.
2023 * Window update algorithm, described in RFC793/RFC1122 (used in linux-2.2
2024 * and in FreeBSD. NetBSD's one is even worse.) is wrong.
2026 static int tcp_ack_update_window(struct sock *sk, struct tcp_opt *tp,
2027 struct sk_buff *skb, u32 ack, u32 ack_seq)
2031 u32 nwin = ntohs(skb->h.th->window) << tp->snd_wscale;
2033 if (tcp_may_update_window(tp, ack, ack_seq, nwin)) {
2034 flag |= FLAG_WIN_UPDATE;
2035 tcp_update_wl(tp, ack, ack_seq);
2037 if (tp->snd_wnd != nwin) {
2040 /* Note, it is the only place, where
2041 * fast path is recovered for sending TCP.
2043 tcp_fast_path_check(sk, tp);
2045 if (nwin > tp->max_window) {
2046 tp->max_window = nwin;
2047 tcp_sync_mss(sk, tp->pmtu_cookie);
2060 /* This routine deals with incoming acks, but not outgoing ones. */
2061 static int tcp_ack(struct sock *sk, struct sk_buff *skb, int flag)
2064 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
2065 u32 prior_snd_una = tp->snd_una;
2066 u32 ack_seq = TCP_SKB_CB(skb)->seq;
2067 u32 ack = TCP_SKB_CB(skb)->ack_seq;
2068 u32 prior_in_flight;
2071 /* If the ack is newer than sent or older than previous acks
2072 * then we can probably ignore it.
2074 if (after(ack, tp->snd_nxt))
2075 goto uninteresting_ack;
2077 if (before(ack, prior_snd_una))
2080 if (!(flag&FLAG_SLOWPATH) && after(ack, prior_snd_una)) {
2081 /* Window is constant, pure forward advance.
2082 * No more checks are required.
2083 * Note, we use the fact that SND.UNA>=SND.WL2.
2085 tcp_update_wl(tp, ack, ack_seq);
2087 flag |= FLAG_WIN_UPDATE;
2089 NET_INC_STATS_BH(TCPHPAcks);
2091 if (ack_seq != TCP_SKB_CB(skb)->end_seq)
2094 NET_INC_STATS_BH(TCPPureAcks);
2096 flag |= tcp_ack_update_window(sk, tp, skb, ack, ack_seq);
2098 if (TCP_SKB_CB(skb)->sacked)
2099 flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una);
2101 if (TCP_ECN_rcv_ecn_echo(tp, skb->h.th))
2105 /* We passed data and got it acked, remove any soft error
2106 * log. Something worked...
2109 tp->rcv_tstamp = tcp_time_stamp;
2110 if ((prior_packets = tp->packets_out) == 0)
2113 prior_in_flight = tcp_packets_in_flight(tp);
2115 /* See if we can take anything off of the retransmit queue. */
2116 flag |= tcp_clean_rtx_queue(sk);
2118 if (tcp_ack_is_dubious(tp, flag)) {
2119 /* Advanve CWND, if state allows this. */
2120 if ((flag&FLAG_DATA_ACKED) && prior_in_flight >= tp->snd_cwnd &&
2121 tcp_may_raise_cwnd(tp, flag))
2123 tcp_fastretrans_alert(sk, prior_snd_una, prior_packets, flag);
2125 if ((flag&FLAG_DATA_ACKED) && prior_in_flight >= tp->snd_cwnd)
2129 if ((flag & FLAG_FORWARD_PROGRESS) || !(flag&FLAG_NOT_DUP))
2130 dst_confirm(sk->dst_cache);
2137 /* If this ack opens up a zero window, clear backoff. It was
2138 * being used to time the probes, and is probably far higher than
2139 * it needs to be for normal retransmission.
2146 if (TCP_SKB_CB(skb)->sacked)
2147 tcp_sacktag_write_queue(sk, skb, prior_snd_una);
2150 SOCK_DEBUG(sk, "Ack %u out of %u:%u\n", ack, tp->snd_una, tp->snd_nxt);
2158 /* Look for tcp options. Normally only called on SYN and SYNACK packets.
2159 * But, this can also be called on packets in the established flow when
2160 * the fast version below fails.
2162 void tcp_parse_options(struct sk_buff *skb, struct tcp_opt *tp, int estab)
2166 struct tcphdr *th = skb->h.th;
2167 int length=(th->doff*4)-sizeof(struct tcphdr);
2169 ptr = (unsigned char *)(th + 1);
2179 case TCPOPT_NOP: /* Ref: RFC 793 section 3.1 */
2184 if (opsize < 2) /* "silly options" */
2186 if (opsize > length)
2187 return; /* don't parse partial options */
2190 if(opsize==TCPOLEN_MSS && th->syn && !estab) {
2191 u16 in_mss = ntohs(*(__u16 *)ptr);
2193 if (tp->user_mss && tp->user_mss < in_mss)
2194 in_mss = tp->user_mss;
2195 tp->mss_clamp = in_mss;
2200 if(opsize==TCPOLEN_WINDOW && th->syn && !estab)
2201 if (sysctl_tcp_window_scaling) {
2203 tp->snd_wscale = *(__u8 *)ptr;
2204 if(tp->snd_wscale > 14) {
2206 printk("tcp_parse_options: Illegal window "
2207 "scaling value %d >14 received.",
2209 tp->snd_wscale = 14;
2213 case TCPOPT_TIMESTAMP:
2214 if(opsize==TCPOLEN_TIMESTAMP) {
2215 if ((estab && tp->tstamp_ok) ||
2216 (!estab && sysctl_tcp_timestamps)) {
2218 tp->rcv_tsval = ntohl(*(__u32 *)ptr);
2219 tp->rcv_tsecr = ntohl(*(__u32 *)(ptr+4));
2223 case TCPOPT_SACK_PERM:
2224 if(opsize==TCPOLEN_SACK_PERM && th->syn && !estab) {
2225 if (sysctl_tcp_sack) {
2233 if((opsize >= (TCPOLEN_SACK_BASE + TCPOLEN_SACK_PERBLOCK)) &&
2234 !((opsize - TCPOLEN_SACK_BASE) % TCPOLEN_SACK_PERBLOCK) &&
2236 TCP_SKB_CB(skb)->sacked = (ptr - 2) - (unsigned char *)th;
2246 /* Fast parse options. This hopes to only see timestamps.
2247 * If it is wrong it falls back on tcp_parse_options().
2249 static __inline__ int tcp_fast_parse_options(struct sk_buff *skb, struct tcphdr *th, struct tcp_opt *tp)
2252 if (th->doff == sizeof(struct tcphdr)>>2) {
2255 } else if (tp->tstamp_ok &&
2256 th->doff == (sizeof(struct tcphdr)>>2)+(TCPOLEN_TSTAMP_ALIGNED>>2)) {
2257 __u32 *ptr = (__u32 *)(th + 1);
2258 if (*ptr == ntohl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16)
2259 | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP)) {
2262 tp->rcv_tsval = ntohl(*ptr);
2264 tp->rcv_tsecr = ntohl(*ptr);
2268 tcp_parse_options(skb, tp, 1);
2275 extern __inline__ void
2276 tcp_store_ts_recent(struct tcp_opt *tp)
2279 tp->ts_recent = tp->rcv_tsval;
2280 tp->ts_recent_stamp = xtime.tv_sec;
2284 extern __inline__ void
2285 tcp_replace_ts_recent(struct tcp_opt *tp, u32 seq)
2288 if (tp->saw_tstamp && !after(seq, tp->rcv_wup)) {
2289 /* PAWS bug workaround wrt. ACK frames, the PAWS discard
2290 * extra check below makes sure this can only happen
2291 * for pure ACK frames. -DaveM
2293 * Not only, also it occurs for expired timestamps.
2296 if((s32)(tp->rcv_tsval - tp->ts_recent) >= 0 ||
2297 xtime.tv_sec >= tp->ts_recent_stamp + TCP_PAWS_24DAYS)
2298 tcp_store_ts_recent(tp);
2303 /* Sorry, PAWS as specified is broken wrt. pure-ACKs -DaveM
2305 * It is not fatal. If this ACK does _not_ change critical state (seqs, window)
2306 * it can pass through stack. So, the following predicate verifies that
2307 * this segment is not used for anything but congestion avoidance or
2308 * fast retransmit. Moreover, we even are able to eliminate most of such
2309 * second order effects, if we apply some small "replay" window (~RTO)
2310 * to timestamp space.
2312 * All these measures still do not guarantee that we reject wrapped ACKs
2313 * on networks with high bandwidth, when sequence space is recycled fastly,
2314 * but it guarantees that such events will be very rare and do not affect
2315 * connection seriously. This doesn't look nice, but alas, PAWS is really
2318 * [ Later note. Even worse! It is buggy for segments _with_ data. RFC
2319 * states that events when retransmit arrives after original data are rare.
2320 * It is a blatant lie. VJ forgot about fast retransmit! 8)8) It is
2321 * the biggest problem on large power networks even with minor reordering.
2322 * OK, let's give it small replay window. If peer clock is even 1hz, it is safe
2323 * up to bandwidth of 18Gigabit/sec. 8) ]
2326 static int tcp_disordered_ack(struct tcp_opt *tp, struct sk_buff *skb)
2329 struct tcphdr *th = skb->h.th;
2330 u32 seq = TCP_SKB_CB(skb)->seq;
2331 u32 ack = TCP_SKB_CB(skb)->ack_seq;
2333 return (/* 1. Pure ACK with correct sequence number. */
2334 (th->ack && seq == TCP_SKB_CB(skb)->end_seq && seq == tp->rcv_nxt) &&
2336 /* 2. ... and duplicate ACK. */
2337 ack == tp->snd_una &&
2339 /* 3. ... and does not update window. */
2340 !tcp_may_update_window(tp, ack, seq, ntohs(th->window)<<tp->snd_wscale) &&
2342 /* 4. ... and sits in replay window. */
2343 (s32)(tp->ts_recent - tp->rcv_tsval) <= (tp->rto*1024)/HZ);
2347 extern __inline__ int tcp_paws_discard(struct tcp_opt *tp, struct sk_buff *skb)
2350 return ((s32)(tp->ts_recent - tp->rcv_tsval) > TCP_PAWS_WINDOW &&
2351 xtime.tv_sec < tp->ts_recent_stamp + TCP_PAWS_24DAYS &&
2352 !tcp_disordered_ack(tp, skb));
2358 /* Check segment sequence number for validity.
2360 * Segment controls are considered valid, if the segment
2361 * fits to the window after truncation to the window. Acceptability
2362 * of data (and SYN, FIN, of course) is checked separately.
2363 * See tcp_data_queue(), for example.
2365 * Also, controls (RST is main one) are accepted using RCV.WUP instead
2366 * of RCV.NXT. Peer still did not advance his SND.UNA when we
2367 * delayed ACK, so that hisSND.UNA<=ourRCV.WUP.
2368 * (borrowed from freebsd)
2371 static inline int tcp_sequence(struct tcp_opt *tp, u32 seq, u32 end_seq)
2374 return !before(end_seq, tp->rcv_wup) &&
2375 !after(seq, tp->rcv_nxt + tcp_receive_window(tp));
2381 /* When we get a reset we do this. */
2382 static void tcp_reset(struct sock *sk)
2385 /* We want the right error as BSD sees it (and indeed as we do). */
2386 switch (sk->state) {
2388 sk->err = ECONNREFUSED;
2390 case TCP_CLOSE_WAIT:
2396 sk->err = ECONNRESET;
2400 sk->error_report(sk);
2407 * Process the FIN bit. This now behaves as it is supposed to work
2408 * and the FIN takes effect when it is validly part of sequence
2409 * space. Not before when we get holes.
2411 * If we are ESTABLISHED, a received fin moves us to CLOSE-WAIT
2412 * (and thence onto LAST-ACK and finally, CLOSE, we never enter
2415 * If we are in FINWAIT-1, a received FIN indicates simultaneous
2416 * close and we go into CLOSING (and later onto TIME-WAIT)
2418 * If we are in FINWAIT-2, a received FIN moves us to TIME-WAIT.
2420 static void tcp_fin(struct sk_buff *skb, struct sock *sk, struct tcphdr *th)
2423 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
2425 tcp_schedule_ack(tp);
2427 sk->shutdown |= RCV_SHUTDOWN;
2432 case TCP_ESTABLISHED:
2433 /* Move to CLOSE_WAIT */
2434 tcp_set_state(sk, TCP_CLOSE_WAIT);
2435 tp->ack.pingpong = 1;
2438 case TCP_CLOSE_WAIT:
2440 /* Received a retransmission of the FIN, do
2445 /* RFC793: Remain in the LAST-ACK state. */
2449 /* This case occurs when a simultaneous close
2450 * happens, we must ack the received FIN and
2451 * enter the CLOSING state.
2454 tcp_set_state(sk, TCP_CLOSING);
2457 /* Received a FIN -- send ACK and enter TIME_WAIT. */
2459 tcp_time_wait(sk, TCP_TIME_WAIT, 0);
2462 /* Only TCP_LISTEN and TCP_CLOSE are left, in these
2463 * cases we should never reach this piece of code.
2465 printk("tcp_fin: Impossible, sk->state=%d\n", sk->state);
2469 /* It _is_ possible, that we have something out-of-order _after_ FIN.
2470 * Probably, we should reset in this case. For now drop them.
2472 __skb_queue_purge(&tp->out_of_order_queue);
2475 tcp_mem_reclaim(sk);
2478 sk->state_change(sk);
2480 /* Do not send POLL_HUP for half duplex close. */
2481 if (sk->shutdown == SHUTDOWN_MASK || sk->state == TCP_CLOSE)
2482 sk_wake_async(sk, 1, POLL_HUP);
2484 sk_wake_async(sk, 1, POLL_IN);
2489 static __inline__ int
2490 tcp_sack_extend(struct tcp_sack_block *sp, u32 seq, u32 end_seq)
2493 if (!after(seq, sp->end_seq) && !after(sp->start_seq, end_seq)) {
2494 if (before(seq, sp->start_seq))
2495 sp->start_seq = seq;
2496 if (after(end_seq, sp->end_seq))
2497 sp->end_seq = end_seq;
2506 static __inline__ void tcp_dsack_set(struct tcp_opt *tp, u32 seq, u32 end_seq)
2509 if (tp->sack_ok && sysctl_tcp_dsack) {
2510 if (before(seq, tp->rcv_nxt))
2511 NET_INC_STATS_BH(TCPDSACKOldSent);
2513 NET_INC_STATS_BH(TCPDSACKOfoSent);
2516 tp->duplicate_sack[0].start_seq = seq;
2517 tp->duplicate_sack[0].end_seq = end_seq;
2518 tp->eff_sacks = min(tp->num_sacks+1, 4-tp->tstamp_ok);
2523 static __inline__ void tcp_dsack_extend(struct tcp_opt *tp, u32 seq, u32 end_seq)
2527 tcp_dsack_set(tp, seq, end_seq);
2529 tcp_sack_extend(tp->duplicate_sack, seq, end_seq);
2533 static void tcp_send_dupack(struct sock *sk, struct sk_buff *skb)
2536 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
2538 if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
2539 before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
2540 NET_INC_STATS_BH(DelayedACKLost);
2541 tcp_enter_quickack_mode(tp);
2543 if (tp->sack_ok && sysctl_tcp_dsack) {
2544 u32 end_seq = TCP_SKB_CB(skb)->end_seq;
2546 if (after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt))
2547 end_seq = tp->rcv_nxt;
2548 tcp_dsack_set(tp, TCP_SKB_CB(skb)->seq, end_seq);
2556 /* These routines update the SACK block as out-of-order packets arrive or
2557 * in-order packets close up the sequence space.
2559 static void tcp_sack_maybe_coalesce(struct tcp_opt *tp)
2563 struct tcp_sack_block *sp = &tp->selective_acks[0];
2564 struct tcp_sack_block *swalk = sp+1;
2566 /* See if the recent change to the first SACK eats into
2567 * or hits the sequence space of other SACK blocks, if so coalesce.
2569 for (this_sack = 1; this_sack < tp->num_sacks; ) {
2570 if (tcp_sack_extend(sp, swalk->start_seq, swalk->end_seq)) {
2573 /* Zap SWALK, by moving every further SACK up by one slot.
2574 * Decrease num_sacks.
2577 tp->eff_sacks = min(tp->num_sacks+tp->dsack, 4-tp->tstamp_ok);
2578 for(i=this_sack; i < tp->num_sacks; i++)
2582 this_sack++, swalk++;
2587 static __inline__ void tcp_sack_swap(struct tcp_sack_block *sack1, struct tcp_sack_block *sack2)
2592 tmp = sack1->start_seq;
2593 sack1->start_seq = sack2->start_seq;
2594 sack2->start_seq = tmp;
2596 tmp = sack1->end_seq;
2597 sack1->end_seq = sack2->end_seq;
2598 sack2->end_seq = tmp;
2602 static void tcp_sack_new_ofo_skb(struct sock *sk, u32 seq, u32 end_seq)
2605 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
2606 struct tcp_sack_block *sp = &tp->selective_acks[0];
2607 int cur_sacks = tp->num_sacks;
2613 for (this_sack=0; this_sack<cur_sacks; this_sack++, sp++) {
2614 if (tcp_sack_extend(sp, seq, end_seq)) {
2615 /* Rotate this_sack to the first one. */
2616 for (; this_sack>0; this_sack--, sp--)
2617 tcp_sack_swap(sp, sp-1);
2619 tcp_sack_maybe_coalesce(tp);
2624 /* Could not find an adjacent existing SACK, build a new one,
2625 * put it at the front, and shift everyone else down. We
2626 * always know there is at least one SACK present already here.
2628 * If the sack array is full, forget about the last one.
2630 if (this_sack >= 4) {
2635 for(; this_sack > 0; this_sack--, sp--)
2639 /* Build the new head SACK, and we're done. */
2640 sp->start_seq = seq;
2641 sp->end_seq = end_seq;
2643 tp->eff_sacks = min(tp->num_sacks+tp->dsack, 4-tp->tstamp_ok);
2647 /* RCV.NXT advances, some SACKs should be eaten. */
2649 static void tcp_sack_remove(struct tcp_opt *tp)
2652 struct tcp_sack_block *sp = &tp->selective_acks[0];
2653 int num_sacks = tp->num_sacks;
2656 /* Empty ofo queue, hence, all the SACKs are eaten. Clear. */
2657 if (skb_queue_len(&tp->out_of_order_queue) == 0) {
2659 tp->eff_sacks = tp->dsack;
2663 for(this_sack = 0; this_sack < num_sacks; ) {
2664 /* Check if the start of the sack is covered by RCV.NXT. */
2665 if (!before(tp->rcv_nxt, sp->start_seq)) {
2668 /* RCV.NXT must cover all the block! */
2669 BUG_TRAP(!before(tp->rcv_nxt, sp->end_seq));
2671 /* Zap this SACK, by moving forward any other SACKS. */
2672 for (i=this_sack+1; i < num_sacks; i++)
2673 tp->selective_acks[i-1] = tp->selective_acks[i];
2680 if (num_sacks != tp->num_sacks) {
2681 tp->num_sacks = num_sacks;
2682 tp->eff_sacks = min(tp->num_sacks+tp->dsack, 4-tp->tstamp_ok);
2687 /* This one checks to see if we can put data from the
2688 * out_of_order queue into the receive_queue.
2690 static void tcp_ofo_queue(struct sock *sk)
2693 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
2694 __u32 dsack_high = tp->rcv_nxt;
2695 struct sk_buff *skb;
2697 while ((skb = skb_peek(&tp->out_of_order_queue)) != NULL) {
2698 if (after(TCP_SKB_CB(skb)->seq, tp->rcv_nxt))
2701 if (before(TCP_SKB_CB(skb)->seq, dsack_high)) {
2702 __u32 dsack = dsack_high;
2703 if (before(TCP_SKB_CB(skb)->end_seq, dsack_high))
2704 dsack_high = TCP_SKB_CB(skb)->end_seq;
2705 tcp_dsack_extend(tp, TCP_SKB_CB(skb)->seq, dsack);
2708 if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) {
2709 SOCK_DEBUG(sk, "ofo packet was already received \n");
2710 __skb_unlink(skb, skb->list);
2714 SOCK_DEBUG(sk, "ofo requeuing : rcv_next %X seq %X - %X\n",
2715 tp->rcv_nxt, TCP_SKB_CB(skb)->seq,
2716 TCP_SKB_CB(skb)->end_seq);
2718 __skb_unlink(skb, skb->list);
2719 __skb_queue_tail(&sk->receive_queue, skb);
2720 tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
2722 tcp_fin(skb, sk, skb->h.th);
2727 static inline int tcp_rmem_schedule(struct sock *sk, struct sk_buff *skb)
2730 return (int)skb->truesize <= sk->forward_alloc ||
2731 tcp_mem_schedule(sk, skb->truesize, 1);
2737 static int tcp_prune_queue(struct sock *sk);
2739 static void tcp_data_queue(struct sock *sk, struct sk_buff *skb)
2742 struct tcphdr *th = skb->h.th;
2743 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
2746 if (TCP_SKB_CB(skb)->seq == TCP_SKB_CB(skb)->end_seq)
2750 __skb_pull(skb, th->doff*4);
2752 TCP_ECN_accept_cwr(tp, skb);
2756 tp->eff_sacks = min_t(unsigned int, tp->num_sacks, 4-tp->tstamp_ok);
2759 /* Queue data for delivery to the user.
2760 * Packets in sequence go to the receive queue.
2761 * Out of sequence packets to the out_of_order_queue.
2763 if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt) {
2764 if (tcp_receive_window(tp) == 0)
2767 /* Ok. In sequence. In window. */
2768 if (tp->ucopy.task == current &&
2769 tp->copied_seq == tp->rcv_nxt &&
2773 int chunk = min_t(unsigned int, skb->len, tp->ucopy.len);
2775 __set_current_state(TASK_RUNNING);
2778 if (!skb_copy_datagram_iovec(skb, 0, tp->ucopy.iov, chunk)) {
2779 tp->ucopy.len -= chunk;
2780 tp->copied_seq += chunk;
2781 eaten = (chunk == skb->len && !th->fin);
2789 (atomic_read(&sk->rmem_alloc) > sk->rcvbuf ||
2790 !tcp_rmem_schedule(sk, skb))) {
2791 if (tcp_prune_queue(sk) < 0 || !tcp_rmem_schedule(sk, skb))
2794 tcp_set_owner_r(skb, sk);
2795 __skb_queue_tail(&sk->receive_queue, skb);
2797 tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
2799 tcp_event_data_recv(sk, tp, skb);
2801 tcp_fin(skb, sk, th);
2803 if (skb_queue_len(&tp->out_of_order_queue)) {
2806 /* RFC2581. 4.2. SHOULD send immediate ACK, when
2807 * gap in queue is filled.
2809 if (skb_queue_len(&tp->out_of_order_queue) == 0)
2810 tp->ack.pingpong = 0;
2814 tcp_sack_remove(tp);
2816 tcp_fast_path_check(sk, tp);
2820 } else if (!sk->dead)
2821 sk->data_ready(sk, 0);
2825 if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) {
2826 /* A retransmit, 2nd most common case. Force an immediate ack. */
2827 NET_INC_STATS_BH(DelayedACKLost);
2828 tcp_dsack_set(tp, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq);
2831 tcp_enter_quickack_mode(tp);
2832 tcp_schedule_ack(tp);
2838 /* Out of window. F.e. zero window probe. */
2839 if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt+tcp_receive_window(tp)))
2842 tcp_enter_quickack_mode(tp);
2844 if (before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
2845 /* Partial packet, seq < rcv_next < end_seq */
2846 SOCK_DEBUG(sk, "partial packet: rcv_next %X seq %X - %X\n",
2847 tp->rcv_nxt, TCP_SKB_CB(skb)->seq,
2848 TCP_SKB_CB(skb)->end_seq);
2850 tcp_dsack_set(tp, TCP_SKB_CB(skb)->seq, tp->rcv_nxt);
2852 /* If window is closed, drop tail of packet. But after
2853 * remembering D-SACK for its head made in previous line.
2855 if (!tcp_receive_window(tp))
2860 TCP_ECN_check_ce(tp, skb);
2862 if (atomic_read(&sk->rmem_alloc) > sk->rcvbuf ||
2863 !tcp_rmem_schedule(sk, skb)) {
2864 if (tcp_prune_queue(sk) < 0 || !tcp_rmem_schedule(sk, skb))
2868 /* Disable header prediction. */
2870 tcp_schedule_ack(tp);
2872 SOCK_DEBUG(sk, "out of order segment: rcv_next %X seq %X - %X\n",
2873 tp->rcv_nxt, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq);
2875 tcp_set_owner_r(skb, sk);
2877 if (skb_peek(&tp->out_of_order_queue) == NULL) {
2878 /* Initial out of order segment, build 1 SACK. */
2883 tp->selective_acks[0].start_seq = TCP_SKB_CB(skb)->seq;
2884 tp->selective_acks[0].end_seq = TCP_SKB_CB(skb)->end_seq;
2886 __skb_queue_head(&tp->out_of_order_queue,skb);
2888 struct sk_buff *skb1=tp->out_of_order_queue.prev;
2889 u32 seq = TCP_SKB_CB(skb)->seq;
2890 u32 end_seq = TCP_SKB_CB(skb)->end_seq;
2892 if (seq == TCP_SKB_CB(skb1)->end_seq) {
2893 __skb_append(skb1, skb);
2895 if (tp->num_sacks == 0 ||
2896 tp->selective_acks[0].end_seq != seq)
2899 /* Common case: data arrive in order after hole. */
2900 tp->selective_acks[0].end_seq = end_seq;
2904 /* Find place to insert this segment. */
2906 if (!after(TCP_SKB_CB(skb1)->seq, seq))
2908 } while ((skb1=skb1->prev) != (struct sk_buff*)&tp->out_of_order_queue);
2910 /* Do skb overlap to previous one? */
2911 if (skb1 != (struct sk_buff*)&tp->out_of_order_queue &&
2912 before(seq, TCP_SKB_CB(skb1)->end_seq)) {
2913 if (!after(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
2914 /* All the bits are present. Drop. */
2916 tcp_dsack_set(tp, seq, end_seq);
2919 if (after(seq, TCP_SKB_CB(skb1)->seq)) {
2920 /* Partial overlap. */
2921 tcp_dsack_set(tp, seq, TCP_SKB_CB(skb1)->end_seq);
2926 __skb_insert(skb, skb1, skb1->next, &tp->out_of_order_queue);
2928 /* And clean segments covered by new one as whole. */
2929 while ((skb1 = skb->next) != (struct sk_buff*)&tp->out_of_order_queue &&
2930 after(end_seq, TCP_SKB_CB(skb1)->seq)) {
2931 if (before(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
2932 tcp_dsack_extend(tp, TCP_SKB_CB(skb1)->seq, end_seq);
2935 __skb_unlink(skb1, skb1->list);
2936 tcp_dsack_extend(tp, TCP_SKB_CB(skb1)->seq, TCP_SKB_CB(skb1)->end_seq);
2942 tcp_sack_new_ofo_skb(sk, seq, end_seq);
2947 /* Collapse contiguous sequence of skbs head..tail with
2948 * sequence numbers start..end.
2949 * Segments with FIN/SYN are not collapsed (only because this
2953 tcp_collapse(struct sock *sk, struct sk_buff *head,
2954 struct sk_buff *tail, u32 start, u32 end)
2957 struct sk_buff *skb;
2959 /* First, check that queue is collapsable and find
2960 * the point where collapsing can be useful. */
2961 for (skb = head; skb != tail; ) {
2962 /* No new bits? It is possible on ofo queue. */
2963 if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
2964 struct sk_buff *next = skb->next;
2965 __skb_unlink(skb, skb->list);
2967 NET_INC_STATS_BH(TCPRcvCollapsed);
2972 /* The first skb to collapse is:
2974 * - bloated or contains data before "start" or
2975 * overlaps to the next one.
2977 if (!skb->h.th->syn && !skb->h.th->fin &&
2978 (tcp_win_from_space(skb->truesize) > skb->len ||
2979 before(TCP_SKB_CB(skb)->seq, start) ||
2980 (skb->next != tail &&
2981 TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb->next)->seq)))
2984 /* Decided to skip this, advance start seq. */
2985 start = TCP_SKB_CB(skb)->end_seq;
2988 if (skb == tail || skb->h.th->syn || skb->h.th->fin)
2991 while (before(start, end)) {
2992 struct sk_buff *nskb;
2993 int header = skb_headroom(skb);
2994 int copy = (PAGE_SIZE - sizeof(struct sk_buff) -
2995 sizeof(struct skb_shared_info) - header - 31)&~15;
2997 /* Too big header? This can happen with IPv6. */
3000 if (end-start < copy)
3002 nskb = alloc_skb(copy+header, GFP_ATOMIC);
3005 skb_reserve(nskb, header);
3006 memcpy(nskb->head, skb->head, header);
3007 nskb->nh.raw = nskb->head + (skb->nh.raw-skb->head);
3008 nskb->h.raw = nskb->head + (skb->h.raw-skb->head);
3009 nskb->mac.raw = nskb->head + (skb->mac.raw-skb->head);
3010 memcpy(nskb->cb, skb->cb, sizeof(skb->cb));
3011 TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(nskb)->end_seq = start;
3012 __skb_insert(nskb, skb->prev, skb, skb->list);
3013 tcp_set_owner_r(nskb, sk);
3015 /* Copy data, releasing collapsed skbs. */
3017 int offset = start - TCP_SKB_CB(skb)->seq;
3018 int size = TCP_SKB_CB(skb)->end_seq - start;
3020 if (offset < 0) BUG();
3022 size = min(copy, size);
3023 if (skb_copy_bits(skb, offset, skb_put(nskb, size), size))
3025 TCP_SKB_CB(nskb)->end_seq += size;
3029 if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
3030 struct sk_buff *next = skb->next;
3031 __skb_unlink(skb, skb->list);
3033 NET_INC_STATS_BH(TCPRcvCollapsed);
3035 if (skb == tail || skb->h.th->syn || skb->h.th->fin)
3043 /* Collapse ofo queue. Algorithm: select contiguous sequence of skbs
3044 * and tcp_collapse() them until all the queue is collapsed.
3046 static void tcp_collapse_ofo_queue(struct sock *sk)
3049 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
3050 struct sk_buff *skb = skb_peek(&tp->out_of_order_queue);
3051 struct sk_buff *head;
3057 start = TCP_SKB_CB(skb)->seq;
3058 end = TCP_SKB_CB(skb)->end_seq;
3064 /* Segment is terminated when we see gap or when
3065 * we are at the end of all the queue. */
3066 if (skb == (struct sk_buff *)&tp->out_of_order_queue ||
3067 after(TCP_SKB_CB(skb)->seq, end) ||
3068 before(TCP_SKB_CB(skb)->end_seq, start)) {
3069 tcp_collapse(sk, head, skb, start, end);
3071 if (skb == (struct sk_buff *)&tp->out_of_order_queue)
3073 /* Start new segment */
3074 start = TCP_SKB_CB(skb)->seq;
3075 end = TCP_SKB_CB(skb)->end_seq;
3077 if (before(TCP_SKB_CB(skb)->seq, start))
3078 start = TCP_SKB_CB(skb)->seq;
3079 if (after(TCP_SKB_CB(skb)->end_seq, end))
3080 end = TCP_SKB_CB(skb)->end_seq;
3086 /* Reduce allocated memory if we can, trying to get
3087 * the socket within its memory limits again.
3089 * Return less than zero if we should start dropping frames
3090 * until the socket owning process reads some of the data
3091 * to stabilize the situation.
3093 static int tcp_prune_queue(struct sock *sk)
3096 struct tcp_opt *tp = &sk->tp_pinfo.af_tcp;
3098 SOCK_DEBUG(sk, "prune_queue: c=%x\n", tp->copied_seq);
3100 NET_INC_STATS_BH(PruneCalled);
3102 if (atomic_read(&sk->rmem_alloc) >= sk->rcvbuf)
3103 tcp_clamp_window(sk, tp);
3104 else if (tcp_memory_pressure)
3105 tp->rcv_ssthresh = min(tp->rcv_ssthresh, 4U*tp->advmss);
3107 tcp_collapse_ofo_queue(sk);
3108 tcp_collapse(sk, sk->receive_queue.next,
3109 (struct sk_buff*)&sk->receive_queue,
3110 tp->copied_seq, tp->rcv_nxt);
3111 tcp_mem_reclaim(sk);
3113 if (atomic_read(&sk->rmem_alloc) <= sk->rcvbuf)
3116 /* Collapsing did not help, destructive actions follow.
3117 * This must not ever occur. */
3119 /* First, purge the out_of_order queue. */
3120 if (skb_queue_len(&tp->out_of_order_queue)) {
3121 net_statistics[smp_processor_id()*2].OfoPruned += skb_queue_len(&tp->out_of_order_queue);
3122 __skb_queue_purge(&tp->out_of_order_queue);
3124 /* Reset SACK state. A conforming SACK implementation will
3125 * do the same at a timeout based retransmit. When a connection
3126 * is in a sad state like this, we care only about integrity
3127 * of the connection not performance.
3131 tcp_mem_reclaim(sk);
3134 if(atomic_read(&sk->rmem_alloc) <= sk->rcvbuf)
3137 /* If we are really being abused, tell the caller to silently
3138 * drop receive data on the floor. It will get retransmitted
3139 * and hopefully then we'll have sufficient space.
3141 NET_INC_STATS_BH(RcvPruned);
3143 /* Massive buffer overcommit. */
3152 /* RFC2861, slow part. Adjust cwnd, after it was not full during one rto.
3153 * As additional protections, we do not touch cwnd in retransmission phases,
3154 * and if application hit its sndbuf limit recently.
3156 void tcp_cwnd_application_limited(struct sock *sk)
3159 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
3161 if (tp->ca_state == TCP_CA_Open &&
3162 sk->socket && !test_bit(SOCK_NOSPACE, &sk->socket->flags)) {
3163 /* Limited by application or receiver window. */
3164 u32 win_used = max(tp->snd_cwnd_used, 2U);
3165 if (win_used < tp->snd_cwnd) {
3166 tp->snd_ssthresh = tcp_current_ssthresh(tp);
3167 tp->snd_cwnd = (tp->snd_cwnd+win_used)>>1;
3169 tp->snd_cwnd_used = 0;
3171 tp->snd_cwnd_stamp = tcp_time_stamp;
3176 /* When incoming ACK allowed to free some skb from write_queue,
3177 * we remember this event in flag tp->queue_shrunk and wake up socket
3178 * on the exit from tcp input handler.
3180 static void tcp_new_space(struct sock *sk)
3183 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
3185 if (tp->packets_out < tp->snd_cwnd &&
3186 !(sk->userlocks&SOCK_SNDBUF_LOCK) &&
3187 !tcp_memory_pressure &&
3188 atomic_read(&tcp_memory_allocated) < sysctl_tcp_mem[0]) {
3189 int sndmem, demanded;
3191 sndmem = tp->mss_clamp+MAX_TCP_HEADER+16+sizeof(struct sk_buff);
3192 demanded = max_t(unsigned int, tp->snd_cwnd, tp->reordering+1);
3193 sndmem *= 2*demanded;
3194 if (sndmem > sk->sndbuf)
3195 sk->sndbuf = min(sndmem, sysctl_tcp_wmem[2]);
3196 tp->snd_cwnd_stamp = tcp_time_stamp;
3199 sk->write_space(sk);
3203 static inline void tcp_check_space(struct sock *sk)
3206 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
3208 if (tp->queue_shrunk) {
3209 tp->queue_shrunk = 0;
3210 if (sk->socket && test_bit(SOCK_NOSPACE, &sk->socket->flags))
3216 static void __tcp_data_snd_check(struct sock *sk, struct sk_buff *skb)
3219 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
3221 if (after(TCP_SKB_CB(skb)->end_seq, tp->snd_una + tp->snd_wnd) ||
3222 tcp_packets_in_flight(tp) >= tp->snd_cwnd ||
3223 tcp_write_xmit(sk, tp->nonagle))
3224 tcp_check_probe_timer(sk, tp);
3228 static __inline__ void tcp_data_snd_check(struct sock *sk)
3231 struct sk_buff *skb = sk->tp_pinfo.af_tcp.send_head;
3234 __tcp_data_snd_check(sk, skb);
3235 tcp_check_space(sk);
3240 * Check if sending an ack is needed.
3242 static __inline__ void __tcp_ack_snd_check(struct sock *sk, int ofo_possible)
3245 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
3247 /* More than one full frame received... */
3248 if (((tp->rcv_nxt - tp->rcv_wup) > tp->ack.rcv_mss
3249 /* ... and right edge of window advances far enough.
3250 * (tcp_recvmsg() will send ACK otherwise). Or...
3252 && __tcp_select_window(sk) >= tp->rcv_wnd) ||
3253 /* We ACK each frame or... */
3254 tcp_in_quickack_mode(tp) ||
3255 /* We have out of order data. */
3257 skb_peek(&tp->out_of_order_queue) != NULL)) {
3258 /* Then ack it now */
3261 /* Else, send delayed ack. */
3262 tcp_send_delayed_ack(sk);
3267 static __inline__ void tcp_ack_snd_check(struct sock *sk)
3270 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
3271 if (!tcp_ack_scheduled(tp)) {
3272 /* We sent a data segment already. */
3275 __tcp_ack_snd_check(sk, 1);
3280 * This routine is only called when we have urgent data
3281 * signalled. Its the 'slow' part of tcp_urg. It could be
3282 * moved inline now as tcp_urg is only called from one
3283 * place. We handle URGent data wrong. We have to - as
3284 * BSD still doesn't use the correction from RFC961.
3285 * For 1003.1g we should support a new option TCP_STDURG to permit
3286 * either form (or just set the sysctl tcp_stdurg).
3289 static void tcp_check_urg(struct sock * sk, struct tcphdr * th)
3292 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
3293 u32 ptr = ntohs(th->urg_ptr);
3295 if (ptr && !sysctl_tcp_stdurg)
3297 ptr += ntohl(th->seq);
3299 /* Ignore urgent data that we've already seen and read. */
3300 if (after(tp->copied_seq, ptr))
3303 /* Do not replay urg ptr.
3305 * NOTE: interesting situation not covered by specs.
3306 * Misbehaving sender may send urg ptr, pointing to segment,
3307 * which we already have in ofo queue. We are not able to fetch
3308 * such data and will stay in TCP_URG_NOTYET until will be eaten
3309 * by recvmsg(). Seems, we are not obliged to handle such wicked
3310 * situations. But it is worth to think about possibility of some
3311 * DoSes using some hypothetical application level deadlock.
3313 if (before(ptr, tp->rcv_nxt))
3316 /* Do we already have a newer (or duplicate) urgent pointer? */
3317 if (tp->urg_data && !after(ptr, tp->urg_seq))
3320 /* Tell the world about our new urgent pointer. */
3321 if (sk->proc != 0) {
3323 kill_proc(sk->proc, SIGURG, 1);
3325 kill_pg(-sk->proc, SIGURG, 1);
3326 sk_wake_async(sk, 3, POLL_PRI);
3329 /* We may be adding urgent data when the last byte read was
3330 * urgent. To do this requires some care. We cannot just ignore
3331 * tp->copied_seq since we would read the last urgent byte again
3332 * as data, nor can we alter copied_seq until this data arrives
3333 * or we break the sematics of SIOCATMARK (and thus sockatmark())
3335 * NOTE. Double Dutch. Rendering to plain English: author of comment
3336 * above did something sort of send("A", MSG_OOB); send("B", MSG_OOB);
3337 * and expect that both A and B disappear from stream. This is _wrong_.
3338 * Though this happens in BSD with high probability, this is occasional.
3339 * Any application relying on this is buggy. Note also, that fix "works"
3340 * only in this artificial test. Insert some normal data between A and B and we will
3341 * decline of BSD again. Verdict: it is better to remove to trap
3344 if (tp->urg_seq == tp->copied_seq && tp->urg_data &&
3346 tp->copied_seq != tp->rcv_nxt) {
3347 struct sk_buff *skb = skb_peek(&sk->receive_queue);
3349 if (skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq)) {
3350 __skb_unlink(skb, skb->list);
3355 tp->urg_data = TCP_URG_NOTYET;
3358 /* Disable header prediction. */
3363 /* This is the 'fast' part of urgent handling. */
3364 static inline void tcp_urg(struct sock *sk, struct sk_buff *skb, struct tcphdr *th)
3367 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
3369 /* Check if we get a new urgent pointer - normally not. */
3371 tcp_check_urg(sk,th);
3373 /* Do we wait for any urgent data? - normally not... */
3374 if (tp->urg_data == TCP_URG_NOTYET) {
3375 u32 ptr = tp->urg_seq - ntohl(th->seq) + (th->doff*4) - th->syn;
3377 /* Is the urgent pointer pointing into this packet? */
3378 if (ptr < skb->len) {
3380 if (skb_copy_bits(skb, ptr, &tmp, 1))
3382 tp->urg_data = TCP_URG_VALID | tmp;
3384 sk->data_ready(sk,0);
3390 static int tcp_copy_to_iovec(struct sock *sk, struct sk_buff *skb, int hlen)
3393 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
3394 int chunk = skb->len - hlen;
3398 if (skb->ip_summed==CHECKSUM_UNNECESSARY)
3399 err = skb_copy_datagram_iovec(skb, hlen, tp->ucopy.iov, chunk);
3401 err = skb_copy_and_csum_datagram_iovec(skb, hlen, tp->ucopy.iov);
3404 tp->ucopy.len -= chunk;
3405 tp->copied_seq += chunk;
3415 static int __tcp_checksum_complete_user(struct sock *sk, struct sk_buff *skb)
3420 if (sk->lock.users) {
3422 result = __tcp_checksum_complete(skb);
3425 result = __tcp_checksum_complete(skb);
3433 static __inline__ int
3434 tcp_checksum_complete_user(struct sock *sk, struct sk_buff *skb)
3437 return skb->ip_summed != CHECKSUM_UNNECESSARY &&
3438 __tcp_checksum_complete_user(sk, skb);
3445 * TCP receive function for the ESTABLISHED state.
3447 * It is split into a fast path and a slow path. The fast path is
3449 * - A zero window was announced from us - zero window probing
3450 * is only handled properly in the slow path.
3451 * - Out of order segments arrived.
3452 * - Urgent data is expected.
3453 * - There is no buffer space left
3454 * - Unexpected TCP flags/window values/header lengths are received
3455 * (detected by checking the TCP header against pred_flags)
3456 * - Data is sent in both directions. Fast path only supports pure senders
3457 * or pure receivers (this means either the sequence number or the ack
3458 * value must stay constant)
3459 * - Unexpected TCP option.
3461 * When these conditions are not satisfied it drops into a standard
3462 * receive procedure patterned after RFC793 to handle all cases.
3463 * The first three cases are guaranteed by proper pred_flags setting,
3464 * the rest is checked inline. Fast processing is turned on in
3465 * tcp_data_queue when everything is OK.
3467 int tcp_rcv_established(struct sock *sk, struct sk_buff *skb,
3468 struct tcphdr *th, unsigned len)
3471 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
3474 * Header prediction.
3475 * The code losely follows the one in the famous
3476 * "30 instruction TCP receive" Van Jacobson mail.
3478 * Van's trick is to deposit buffers into socket queue
3479 * on a device interrupt, to call tcp_recv function
3480 * on the receive process context and checksum and copy
3481 * the buffer to user space. smart...
3483 * Our current scheme is not silly either but we take the
3484 * extra cost of the net_bh soft interrupt processing...
3485 * We do checksum and copy also but from device to kernel.
3490 /* pred_flags is 0xS?10 << 16 + snd_wnd
3491 * if header_predition is to be made
3492 * 'S' will always be tp->tcp_header_len >> 2
3493 * '?' will be 0 for the fast path, otherwise pred_flags is 0 to
3494 * turn it off (when there are holes in the receive
3495 * space for instance)
3496 * PSH flag is ignored.
3499 if ((tcp_flag_word(th) & TCP_HP_BITS) == tp->pred_flags &&
3500 TCP_SKB_CB(skb)->seq == tp->rcv_nxt) {
3501 int tcp_header_len = tp->tcp_header_len;
3503 /* Timestamp header prediction: tcp_header_len
3504 * is automatically equal to th->doff*4 due to pred_flags
3508 /* Check timestamp */
3509 if (tcp_header_len == sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) {
3510 __u32 *ptr = (__u32 *)(th + 1);
3512 /* No? Slow path! */
3513 if (*ptr != ntohl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16)
3514 | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP))
3519 tp->rcv_tsval = ntohl(*ptr);
3521 tp->rcv_tsecr = ntohl(*ptr);
3523 /* If PAWS failed, check it more carefully in slow path */
3524 if ((s32)(tp->rcv_tsval - tp->ts_recent) < 0)
3527 /* DO NOT update ts_recent here, if checksum fails
3528 * and timestamp was corrupted part, it will result
3529 * in a hung connection since we will drop all
3530 * future packets due to the PAWS test.
3534 if (len <= tcp_header_len) {
3535 /* Bulk data transfer: sender */
3536 if (len == tcp_header_len) {
3537 /* Predicted packet is in window by definition.
3538 * seq == rcv_nxt and rcv_wup <= rcv_nxt.
3539 * Hence, check seq<=rcv_wup reduces to:
3541 if (tcp_header_len ==
3542 (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) &&
3543 tp->rcv_nxt == tp->rcv_wup)
3544 tcp_store_ts_recent(tp);
3545 /* We know that such packets are checksummed
3548 tcp_ack(sk, skb, 0);
3550 tcp_data_snd_check(sk);
3552 } else { /* Header too small */
3553 TCP_INC_STATS_BH(TcpInErrs);
3559 if (tp->ucopy.task == current &&
3560 tp->copied_seq == tp->rcv_nxt &&
3561 len - tcp_header_len <= tp->ucopy.len &&
3563 __set_current_state(TASK_RUNNING);
3565 if (!tcp_copy_to_iovec(sk, skb, tcp_header_len)) {
3566 /* Predicted packet is in window by definition.
3567 * seq == rcv_nxt and rcv_wup <= rcv_nxt.
3568 * Hence, check seq<=rcv_wup reduces to:
3570 if (tcp_header_len ==
3571 (sizeof(struct tcphdr) +
3572 TCPOLEN_TSTAMP_ALIGNED) &&
3573 tp->rcv_nxt == tp->rcv_wup)
3574 tcp_store_ts_recent(tp);
3576 __skb_pull(skb, tcp_header_len);
3577 tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
3578 NET_INC_STATS_BH(TCPHPHitsToUser);
3583 if (tcp_checksum_complete_user(sk, skb))
3586 /* Predicted packet is in window by definition.
3587 * seq == rcv_nxt and rcv_wup <= rcv_nxt.
3588 * Hence, check seq<=rcv_wup reduces to:
3590 if (tcp_header_len ==
3591 (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) &&
3592 tp->rcv_nxt == tp->rcv_wup)
3593 tcp_store_ts_recent(tp);
3595 if ((int)skb->truesize > sk->forward_alloc)
3598 NET_INC_STATS_BH(TCPHPHits);
3600 /* Bulk data transfer: receiver */
3601 __skb_pull(skb,tcp_header_len);
3602 __skb_queue_tail(&sk->receive_queue, skb);
3603 tcp_set_owner_r(skb, sk);
3604 tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
3607 tcp_event_data_recv(sk, tp, skb);
3609 if (TCP_SKB_CB(skb)->ack_seq != tp->snd_una) {
3610 /* Well, only one small jumplet in fast path... */
3611 tcp_ack(sk, skb, FLAG_DATA);
3612 tcp_data_snd_check(sk);
3613 if (!tcp_ack_scheduled(tp))
3618 if (tcp_in_quickack_mode(tp)) {
3621 tcp_send_delayed_ack(sk);
3624 __tcp_ack_snd_check(sk, 0);
3631 sk->data_ready(sk, 0);
3637 if (len < (th->doff<<2) || tcp_checksum_complete_user(sk, skb))
3641 * RFC1323: H1. Apply PAWS check first.
3643 if (tcp_fast_parse_options(skb, th, tp) && tp->saw_tstamp &&
3644 tcp_paws_discard(tp, skb)) {
3646 NET_INC_STATS_BH(PAWSEstabRejected);
3647 tcp_send_dupack(sk, skb);
3650 /* Resets are accepted even if PAWS failed.
3652 ts_recent update must be made after we are sure
3653 that the packet is in window.
3658 * Standard slow path.
3661 if (!tcp_sequence(tp, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq)) {
3662 /* RFC793, page 37: "In all states except SYN-SENT, all reset
3663 * (RST) segments are validated by checking their SEQ-fields."
3664 * And page 69: "If an incoming segment is not acceptable,
3665 * an acknowledgment should be sent in reply (unless the RST bit
3666 * is set, if so drop the segment and return)".
3669 tcp_send_dupack(sk, skb);
3678 tcp_replace_ts_recent(tp, TCP_SKB_CB(skb)->seq);
3680 if (th->syn && !before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
3681 TCP_INC_STATS_BH(TcpInErrs);
3682 NET_INC_STATS_BH(TCPAbortOnSyn);
3689 tcp_ack(sk, skb, FLAG_SLOWPATH);
3691 /* Process urgent data. */
3692 tcp_urg(sk, skb, th);
3694 /* step 7: process the segment text */
3695 tcp_data_queue(sk, skb);
3697 tcp_data_snd_check(sk);
3698 tcp_ack_snd_check(sk);
3702 TCP_INC_STATS_BH(TcpInErrs);
3712 static int tcp_rcv_synsent_state_process(struct sock *sk, struct sk_buff *skb,
3713 struct tcphdr *th, unsigned len)
3716 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
3717 int saved_clamp = tp->mss_clamp;
3719 tcp_parse_options(skb, tp, 0);
3723 * "If the state is SYN-SENT then
3724 * first check the ACK bit
3725 * If the ACK bit is set
3726 * If SEG.ACK =< ISS, or SEG.ACK > SND.NXT, send
3727 * a reset (unless the RST bit is set, if so drop
3728 * the segment and return)"
3730 * We do not send data with SYN, so that RFC-correct
3733 if (TCP_SKB_CB(skb)->ack_seq != tp->snd_nxt)
3734 goto reset_and_undo;
3736 if (tp->saw_tstamp && tp->rcv_tsecr &&
3737 !between(tp->rcv_tsecr, tp->retrans_stamp, tcp_time_stamp)) {
3738 NET_INC_STATS_BH(PAWSActiveRejected);
3739 goto reset_and_undo;
3742 /* Now ACK is acceptable.
3744 * "If the RST bit is set
3745 * If the ACK was acceptable then signal the user "error:
3746 * connection reset", drop the segment, enter CLOSED state,
3747 * delete TCB, and return."
3756 * "fifth, if neither of the SYN or RST bits is set then
3757 * drop the segment and return."
3763 goto discard_and_undo;
3766 * "If the SYN bit is on ...
3767 * are acceptable then ...
3768 * (our SYN has been ACKed), change the connection
3769 * state to ESTABLISHED..."
3772 TCP_ECN_rcv_synack(tp, th);
3774 tp->snd_wl1 = TCP_SKB_CB(skb)->seq;
3775 tcp_ack(sk, skb, FLAG_SLOWPATH);
3777 /* Ok.. it's good. Set up sequence numbers and
3778 * move to established.
3780 tp->rcv_nxt = TCP_SKB_CB(skb)->seq+1;
3781 tp->rcv_wup = TCP_SKB_CB(skb)->seq+1;
3783 /* RFC1323: The window in SYN & SYN/ACK segments is
3786 tp->snd_wnd = ntohs(th->window);
3787 tcp_init_wl(tp, TCP_SKB_CB(skb)->ack_seq, TCP_SKB_CB(skb)->seq);
3789 if (tp->wscale_ok == 0) {
3790 tp->snd_wscale = tp->rcv_wscale = 0;
3791 tp->window_clamp = min(tp->window_clamp, 65535U);
3794 if (tp->saw_tstamp) {
3796 tp->tcp_header_len =
3797 sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
3798 tp->advmss -= TCPOLEN_TSTAMP_ALIGNED;
3799 tcp_store_ts_recent(tp);
3801 tp->tcp_header_len = sizeof(struct tcphdr);
3804 if (tp->sack_ok && sysctl_tcp_fack)
3807 tcp_sync_mss(sk, tp->pmtu_cookie);
3808 tcp_initialize_rcv_mss(sk);
3809 tcp_init_metrics(sk);
3810 tcp_init_buffer_space(sk);
3813 tcp_reset_keepalive_timer(sk, keepalive_time_when(tp));
3815 if (tp->snd_wscale == 0)
3816 __tcp_fast_path_on(tp, tp->snd_wnd);
3820 /* Remember, tcp_poll() does not lock socket!
3821 * Change state from SYN-SENT only after copied_seq
3822 * is initialized. */
3823 tp->copied_seq = tp->rcv_nxt;
3825 tcp_set_state(sk, TCP_ESTABLISHED);
3828 sk->state_change(sk);
3829 sk_wake_async(sk, 0, POLL_OUT);
3832 if (tp->write_pending || tp->defer_accept || tp->ack.pingpong) {
3833 /* Save one ACK. Data will be ready after
3834 * several ticks, if write_pending is set.
3836 * It may be deleted, but with this feature tcpdumps
3837 * look so _wonderfully_ clever, that I was not able
3838 * to stand against the temptation 8) --ANK
3840 tcp_schedule_ack(tp);
3841 tp->ack.lrcvtime = tcp_time_stamp;
3842 tp->ack.ato = TCP_ATO_MIN;
3843 tcp_incr_quickack(tp);
3844 tcp_enter_quickack_mode(tp);
3845 tcp_reset_xmit_timer(sk, TCP_TIME_DACK, TCP_DELACK_MAX);
3856 /* No ACK in the segment */
3860 * "If the RST bit is set
3862 * Otherwise (no ACK) drop the segment and return."
3865 goto discard_and_undo;
3869 if (tp->ts_recent_stamp && tp->saw_tstamp && tcp_paws_check(tp, 0))
3870 goto discard_and_undo;
3873 /* We see SYN without ACK. It is attempt of
3874 * simultaneous connect with crossed SYNs.
3875 * Particularly, it can be connect to self.
3877 tcp_set_state(sk, TCP_SYN_RECV);
3879 if (tp->saw_tstamp) {
3881 tcp_store_ts_recent(tp);
3882 tp->tcp_header_len =
3883 sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
3885 tp->tcp_header_len = sizeof(struct tcphdr);
3888 tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1;
3889 tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
3891 /* RFC1323: The window in SYN & SYN/ACK segments is
3894 tp->snd_wnd = ntohs(th->window);
3895 tp->snd_wl1 = TCP_SKB_CB(skb)->seq;
3896 tp->max_window = tp->snd_wnd;
3898 tcp_sync_mss(sk, tp->pmtu_cookie);
3899 tcp_initialize_rcv_mss(sk);
3901 TCP_ECN_rcv_syn(tp, th);
3903 tcp_send_synack(sk);
3905 /* Note, we could accept data and URG from this segment.
3906 * There are no obstacles to make this.
3908 * However, if we ignore data in ACKless segments sometimes,
3909 * we have no reasons to accept it sometimes.
3910 * Also, seems the code doing it in step6 of tcp_rcv_state_process
3911 * is not flawless. So, discard packet for sanity.
3912 * Uncomment this return to process the data.
3919 /* "fifth, if neither of the SYN or RST bits is set then
3920 * drop the segment and return."
3924 tcp_clear_options(tp);
3925 tp->mss_clamp = saved_clamp;
3929 tcp_clear_options(tp);
3930 tp->mss_clamp = saved_clamp;
3939 * This function implements the receiving procedure of RFC 793 for
3940 * all states except ESTABLISHED and TIME_WAIT.
3941 * It's called from both tcp_v4_rcv and tcp_v6_rcv and should be
3942 * address independent.
3945 int tcp_rcv_state_process(struct sock *sk, struct sk_buff *skb,
3946 struct tcphdr *th, unsigned len)
3949 struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
3954 switch (sk->state) {
3966 if(tp->af_specific->conn_request(sk, skb) < 0)
3969 /* Now we have several options: In theory there is
3970 * nothing else in the frame. KA9Q has an option to
3971 * send data with the syn, BSD accepts data with the
3972 * syn up to the [to be] advertised window and
3973 * Solaris 2.1 gives you a protocol error. For now
3974 * we just ignore it, that fits the spec precisely
3975 * and avoids incompatibilities. It would be nice in
3976 * future to drop through and process the data.
3978 * Now that TTCP is starting to be used we ought to
3980 * But, this leaves one open to an easy denial of
3981 * service attack, and SYN cookies can't defend
3982 * against this problem. So, we drop the data
3983 * in the interest of security over speed.
3990 queued = tcp_rcv_synsent_state_process(sk, skb, th, len);
3994 /* Do step6 onward by hand. */
3995 tcp_urg(sk, skb, th);
3997 tcp_data_snd_check(sk);
4001 if (tcp_fast_parse_options(skb, th, tp) && tp->saw_tstamp &&
4002 tcp_paws_discard(tp, skb)) {
4004 NET_INC_STATS_BH(PAWSEstabRejected);
4005 tcp_send_dupack(sk, skb);
4008 /* Reset is accepted even if it did not pass PAWS. */
4011 /* step 1: check sequence number */
4012 if (!tcp_sequence(tp, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq)) {
4014 tcp_send_dupack(sk, skb);
4018 /* step 2: check RST bit */
4024 tcp_replace_ts_recent(tp, TCP_SKB_CB(skb)->seq);
4026 /* step 3: check security and precedence [ignored] */
4030 * Check for a SYN in window.
4032 if (th->syn && !before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
4033 NET_INC_STATS_BH(TCPAbortOnSyn);
4038 /* step 5: check the ACK field */
4040 int acceptable = tcp_ack(sk, skb, FLAG_SLOWPATH);
4045 tp->copied_seq = tp->rcv_nxt;
4047 tcp_set_state(sk, TCP_ESTABLISHED);
4048 sk->state_change(sk);
4050 /* Note, that this wakeup is only for marginal
4051 * crossed SYN case. Passively open sockets
4052 * are not waked up, because sk->sleep == NULL
4053 * and sk->socket == NULL.
4056 sk_wake_async(sk,0,POLL_OUT);
4059 tp->snd_una = TCP_SKB_CB(skb)->ack_seq;
4060 tp->snd_wnd = ntohs(th->window) << tp->snd_wscale;
4061 tcp_init_wl(tp, TCP_SKB_CB(skb)->ack_seq, TCP_SKB_CB(skb)->seq);
4063 /* tcp_ack considers this ACK as duplicate
4064 * and does not calculate rtt.
4065 * Fix it at least with timestamps.
4067 if (tp->saw_tstamp && tp->rcv_tsecr && !tp->srtt)
4068 tcp_ack_saw_tstamp(tp, 0);
4071 tp->advmss -= TCPOLEN_TSTAMP_ALIGNED;
4073 tcp_init_metrics(sk);
4074 tcp_initialize_rcv_mss(sk);
4075 tcp_init_buffer_space(sk);
4076 tcp_fast_path_on(tp);
4083 if (tp->snd_una == tp->write_seq) {
4084 tcp_set_state(sk, TCP_FIN_WAIT2);
4085 sk->shutdown |= SEND_SHUTDOWN;
4086 dst_confirm(sk->dst_cache);
4089 /* Wake up lingering close() */
4090 sk->state_change(sk);
4094 if (tp->linger2 < 0 ||
4095 (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
4096 after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt))) {
4098 NET_INC_STATS_BH(TCPAbortOnData);
4102 tmo = tcp_fin_time(tp);
4103 if (tmo > TCP_TIMEWAIT_LEN) {
4104 tcp_reset_keepalive_timer(sk, tmo - TCP_TIMEWAIT_LEN);
4105 } else if (th->fin || sk->lock.users) {
4106 /* Bad case. We could lose such FIN otherwise.
4107 * It is not a big problem, but it looks confusing
4108 * and not so rare event. We still can lose it now,
4109 * if it spins in bh_lock_sock(), but it is really
4112 tcp_reset_keepalive_timer(sk, tmo);
4114 tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
4122 if (tp->snd_una == tp->write_seq) {
4123 tcp_time_wait(sk, TCP_TIME_WAIT, 0);
4129 if (tp->snd_una == tp->write_seq) {
4130 tcp_update_metrics(sk);
4139 /* step 6: check the URG bit */
4140 tcp_urg(sk, skb, th);
4142 /* step 7: process the segment text */
4143 switch (sk->state) {
4144 case TCP_CLOSE_WAIT:
4147 if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt))
4151 /* RFC 793 says to queue data in these states,
4152 * RFC 1122 says we MUST send a reset.
4153 * BSD 4.4 also does reset.
4155 if (sk->shutdown & RCV_SHUTDOWN) {
4156 if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
4157 after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt)) {
4158 NET_INC_STATS_BH(TCPAbortOnData);
4164 case TCP_ESTABLISHED:
4165 tcp_data_queue(sk, skb);
4170 /* tcp_data could move socket to TIME-WAIT */
4171 if (sk->state != TCP_CLOSE) {
4172 tcp_data_snd_check(sk);
4173 tcp_ack_snd_check(sk);