ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / net / ipv4 / tcp_input.c
1 /*
2  * INET         An implementation of the TCP/IP protocol suite for the LINUX
3  *              operating system.  INET is implemented using the  BSD Socket
4  *              interface as the means of communication with the user level.
5  *
6  *              Implementation of the Transmission Control Protocol(TCP).
7  *
8  * Version:     $Id: tcp_input.c,v 1.243 2002/02/01 22:01:04 davem Exp $
9  *
10  * Authors:     Ross Biro, <bir7@leland.Stanford.Edu>
11  *              Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
12  *              Mark Evans, <evansmp@uhura.aston.ac.uk>
13  *              Corey Minyard <wf-rch!minyard@relay.EU.net>
14  *              Florian La Roche, <flla@stud.uni-sb.de>
15  *              Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
16  *              Linus Torvalds, <torvalds@cs.helsinki.fi>
17  *              Alan Cox, <gw4pts@gw4pts.ampr.org>
18  *              Matthew Dillon, <dillon@apollo.west.oic.com>
19  *              Arnt Gulbrandsen, <agulbra@nvg.unit.no>
20  *              Jorge Cwik, <jorge@laser.satlink.net>
21  */
22
23 /*
24  * Changes:
25  *              Pedro Roque     :       Fast Retransmit/Recovery.
26  *                                      Two receive queues.
27  *                                      Retransmit queue handled by TCP.
28  *                                      Better retransmit timer handling.
29  *                                      New congestion avoidance.
30  *                                      Header prediction.
31  *                                      Variable renaming.
32  *
33  *              Eric            :       Fast Retransmit.
34  *              Randy Scott     :       MSS option defines.
35  *              Eric Schenk     :       Fixes to slow start algorithm.
36  *              Eric Schenk     :       Yet another double ACK bug.
37  *              Eric Schenk     :       Delayed ACK bug fixes.
38  *              Eric Schenk     :       Floyd style fast retrans war avoidance.
39  *              David S. Miller :       Don't allow zero congestion window.
40  *              Eric Schenk     :       Fix retransmitter so that it sends
41  *                                      next packet on ack of previous packet.
42  *              Andi Kleen      :       Moved open_request checking here
43  *                                      and process RSTs for open_requests.
44  *              Andi Kleen      :       Better prune_queue, and other fixes.
45  *              Andrey Savochkin:       Fix RTT measurements in the presnce of
46  *                                      timestamps.
47  *              Andrey Savochkin:       Check sequence numbers correctly when
48  *                                      removing SACKs due to in sequence incoming
49  *                                      data segments.
50  *              Andi Kleen:             Make sure we never ack data there is not
51  *                                      enough room for. Also make this condition
52  *                                      a fatal error if it might still happen.
53  *              Andi Kleen:             Add tcp_measure_rcv_mss to make 
54  *                                      connections with MSS<min(MTU,ann. MSS)
55  *                                      work without delayed acks. 
56  *              Andi Kleen:             Process packets with PSH set in the
57  *                                      fast path.
58  *              J Hadi Salim:           ECN support
59  *              Andrei Gurtov,
60  *              Pasi Sarolahti,
61  *              Panu Kuhlberg:          Experimental audit of TCP (re)transmission
62  *                                      engine. Lots of bugs are found.
63  *              Pasi Sarolahti:         F-RTO for dealing with spurious RTOs
64  *              Angelo Dell'Aera:       TCP Westwood+ support
65  */
66
67 #include <linux/config.h>
68 #include <linux/mm.h>
69 #include <linux/module.h>
70 #include <linux/sysctl.h>
71 #include <net/tcp.h>
72 #include <net/inet_common.h>
73 #include <linux/ipsec.h>
74
75 int sysctl_tcp_timestamps = 1;
76 int sysctl_tcp_window_scaling = 1;
77 int sysctl_tcp_sack = 1;
78 int sysctl_tcp_fack = 1;
79 int sysctl_tcp_reordering = TCP_FASTRETRANS_THRESH;
80 int sysctl_tcp_ecn;
81 int sysctl_tcp_dsack = 1;
82 int sysctl_tcp_app_win = 31;
83 int sysctl_tcp_adv_win_scale = 2;
84
85 int sysctl_tcp_stdurg;
86 int sysctl_tcp_rfc1337;
87 int sysctl_tcp_max_orphans = NR_FILE;
88 int sysctl_tcp_frto;
89 int sysctl_tcp_nometrics_save;
90 int sysctl_tcp_westwood;
91 int sysctl_tcp_vegas_cong_avoid;
92
93 /* Default values of the Vegas variables, in fixed-point representation
94  * with V_PARAM_SHIFT bits to the right of the binary point.
95  */
96 #define V_PARAM_SHIFT 1
97 int sysctl_tcp_vegas_alpha = 1<<V_PARAM_SHIFT;
98 int sysctl_tcp_vegas_beta  = 3<<V_PARAM_SHIFT;
99 int sysctl_tcp_vegas_gamma = 1<<V_PARAM_SHIFT;
100 int sysctl_tcp_bic;
101 int sysctl_tcp_bic_fast_convergence = 1;
102 int sysctl_tcp_bic_low_window = 14;
103
104 #define FLAG_DATA               0x01 /* Incoming frame contained data.          */
105 #define FLAG_WIN_UPDATE         0x02 /* Incoming ACK was a window update.       */
106 #define FLAG_DATA_ACKED         0x04 /* This ACK acknowledged new data.         */
107 #define FLAG_RETRANS_DATA_ACKED 0x08 /* "" "" some of which was retransmitted.  */
108 #define FLAG_SYN_ACKED          0x10 /* This ACK acknowledged SYN.              */
109 #define FLAG_DATA_SACKED        0x20 /* New SACK.                               */
110 #define FLAG_ECE                0x40 /* ECE in this ACK                         */
111 #define FLAG_DATA_LOST          0x80 /* SACK detected data lossage.             */
112 #define FLAG_SLOWPATH           0x100 /* Do not skip RFC checks for window update.*/
113
114 #define FLAG_ACKED              (FLAG_DATA_ACKED|FLAG_SYN_ACKED)
115 #define FLAG_NOT_DUP            (FLAG_DATA|FLAG_WIN_UPDATE|FLAG_ACKED)
116 #define FLAG_CA_ALERT           (FLAG_DATA_SACKED|FLAG_ECE)
117 #define FLAG_FORWARD_PROGRESS   (FLAG_ACKED|FLAG_DATA_SACKED)
118
119 #define IsReno(tp) ((tp)->sack_ok == 0)
120 #define IsFack(tp) ((tp)->sack_ok & 2)
121 #define IsDSack(tp) ((tp)->sack_ok & 4)
122
123 #define TCP_REMNANT (TCP_FLAG_FIN|TCP_FLAG_URG|TCP_FLAG_SYN|TCP_FLAG_PSH)
124
125 /* Adapt the MSS value used to make delayed ack decision to the 
126  * real world.
127  */ 
128 static __inline__ void tcp_measure_rcv_mss(struct tcp_opt *tp, struct sk_buff *skb)
129 {
130         unsigned int len, lss;
131
132         lss = tp->ack.last_seg_size; 
133         tp->ack.last_seg_size = 0; 
134
135         /* skb->len may jitter because of SACKs, even if peer
136          * sends good full-sized frames.
137          */
138         len = skb->len;
139         if (len >= tp->ack.rcv_mss) {
140                 tp->ack.rcv_mss = len;
141         } else {
142                 /* Otherwise, we make more careful check taking into account,
143                  * that SACKs block is variable.
144                  *
145                  * "len" is invariant segment length, including TCP header.
146                  */
147                 len += skb->data - skb->h.raw;
148                 if (len >= TCP_MIN_RCVMSS + sizeof(struct tcphdr) ||
149                     /* If PSH is not set, packet should be
150                      * full sized, provided peer TCP is not badly broken.
151                      * This observation (if it is correct 8)) allows
152                      * to handle super-low mtu links fairly.
153                      */
154                     (len >= TCP_MIN_MSS + sizeof(struct tcphdr) &&
155                      !(tcp_flag_word(skb->h.th)&TCP_REMNANT))) {
156                         /* Subtract also invariant (if peer is RFC compliant),
157                          * tcp header plus fixed timestamp option length.
158                          * Resulting "len" is MSS free of SACK jitter.
159                          */
160                         len -= tp->tcp_header_len;
161                         tp->ack.last_seg_size = len;
162                         if (len == lss) {
163                                 tp->ack.rcv_mss = len;
164                                 return;
165                         }
166                 }
167                 tp->ack.pending |= TCP_ACK_PUSHED;
168         }
169 }
170
171 static void tcp_incr_quickack(struct tcp_opt *tp)
172 {
173         unsigned quickacks = tp->rcv_wnd/(2*tp->ack.rcv_mss);
174
175         if (quickacks==0)
176                 quickacks=2;
177         if (quickacks > tp->ack.quick)
178                 tp->ack.quick = min(quickacks, TCP_MAX_QUICKACKS);
179 }
180
181 void tcp_enter_quickack_mode(struct tcp_opt *tp)
182 {
183         tcp_incr_quickack(tp);
184         tp->ack.pingpong = 0;
185         tp->ack.ato = TCP_ATO_MIN;
186 }
187
188 /* Send ACKs quickly, if "quick" count is not exhausted
189  * and the session is not interactive.
190  */
191
192 static __inline__ int tcp_in_quickack_mode(struct tcp_opt *tp)
193 {
194         return (tp->ack.quick && !tp->ack.pingpong);
195 }
196
197 /* Buffer size and advertised window tuning.
198  *
199  * 1. Tuning sk->sk_sndbuf, when connection enters established state.
200  */
201
202 static void tcp_fixup_sndbuf(struct sock *sk)
203 {
204         int sndmem = tcp_sk(sk)->mss_clamp + MAX_TCP_HEADER + 16 +
205                      sizeof(struct sk_buff);
206
207         if (sk->sk_sndbuf < 3 * sndmem)
208                 sk->sk_sndbuf = min(3 * sndmem, sysctl_tcp_wmem[2]);
209 }
210
211 /* 2. Tuning advertised window (window_clamp, rcv_ssthresh)
212  *
213  * All tcp_full_space() is split to two parts: "network" buffer, allocated
214  * forward and advertised in receiver window (tp->rcv_wnd) and
215  * "application buffer", required to isolate scheduling/application
216  * latencies from network.
217  * window_clamp is maximal advertised window. It can be less than
218  * tcp_full_space(), in this case tcp_full_space() - window_clamp
219  * is reserved for "application" buffer. The less window_clamp is
220  * the smoother our behaviour from viewpoint of network, but the lower
221  * throughput and the higher sensitivity of the connection to losses. 8)
222  *
223  * rcv_ssthresh is more strict window_clamp used at "slow start"
224  * phase to predict further behaviour of this connection.
225  * It is used for two goals:
226  * - to enforce header prediction at sender, even when application
227  *   requires some significant "application buffer". It is check #1.
228  * - to prevent pruning of receive queue because of misprediction
229  *   of receiver window. Check #2.
230  *
231  * The scheme does not work when sender sends good segments opening
232  * window and then starts to feed us spagetti. But it should work
233  * in common situations. Otherwise, we have to rely on queue collapsing.
234  */
235
236 /* Slow part of check#2. */
237 static int
238 __tcp_grow_window(struct sock *sk, struct tcp_opt *tp, struct sk_buff *skb)
239 {
240         /* Optimize this! */
241         int truesize = tcp_win_from_space(skb->truesize)/2;
242         int window = tcp_full_space(sk)/2;
243
244         while (tp->rcv_ssthresh <= window) {
245                 if (truesize <= skb->len)
246                         return 2*tp->ack.rcv_mss;
247
248                 truesize >>= 1;
249                 window >>= 1;
250         }
251         return 0;
252 }
253
254 static __inline__ void
255 tcp_grow_window(struct sock *sk, struct tcp_opt *tp, struct sk_buff *skb)
256 {
257         /* Check #1 */
258         if (tp->rcv_ssthresh < tp->window_clamp &&
259             (int)tp->rcv_ssthresh < tcp_space(sk) &&
260             !tcp_memory_pressure) {
261                 int incr;
262
263                 /* Check #2. Increase window, if skb with such overhead
264                  * will fit to rcvbuf in future.
265                  */
266                 if (tcp_win_from_space(skb->truesize) <= skb->len)
267                         incr = 2*tp->advmss;
268                 else
269                         incr = __tcp_grow_window(sk, tp, skb);
270
271                 if (incr) {
272                         tp->rcv_ssthresh = min(tp->rcv_ssthresh + incr, tp->window_clamp);
273                         tp->ack.quick |= 1;
274                 }
275         }
276 }
277
278 /* 3. Tuning rcvbuf, when connection enters established state. */
279
280 static void tcp_fixup_rcvbuf(struct sock *sk)
281 {
282         struct tcp_opt *tp = tcp_sk(sk);
283         int rcvmem = tp->advmss + MAX_TCP_HEADER + 16 + sizeof(struct sk_buff);
284
285         /* Try to select rcvbuf so that 4 mss-sized segments
286          * will fit to window and correspoding skbs will fit to our rcvbuf.
287          * (was 3; 4 is minimum to allow fast retransmit to work.)
288          */
289         while (tcp_win_from_space(rcvmem) < tp->advmss)
290                 rcvmem += 128;
291         if (sk->sk_rcvbuf < 4 * rcvmem)
292                 sk->sk_rcvbuf = min(4 * rcvmem, sysctl_tcp_rmem[2]);
293 }
294
295 /* 4. Try to fixup all. It is made iimediately after connection enters
296  *    established state.
297  */
298 static void tcp_init_buffer_space(struct sock *sk)
299 {
300         struct tcp_opt *tp = tcp_sk(sk);
301         int maxwin;
302
303         if (!(sk->sk_userlocks & SOCK_RCVBUF_LOCK))
304                 tcp_fixup_rcvbuf(sk);
305         if (!(sk->sk_userlocks & SOCK_SNDBUF_LOCK))
306                 tcp_fixup_sndbuf(sk);
307
308         maxwin = tcp_full_space(sk);
309
310         if (tp->window_clamp >= maxwin) {
311                 tp->window_clamp = maxwin;
312
313                 if (sysctl_tcp_app_win && maxwin > 4 * tp->advmss)
314                         tp->window_clamp = max(maxwin -
315                                                (maxwin >> sysctl_tcp_app_win),
316                                                4 * tp->advmss);
317         }
318
319         /* Force reservation of one segment. */
320         if (sysctl_tcp_app_win &&
321             tp->window_clamp > 2 * tp->advmss &&
322             tp->window_clamp + tp->advmss > maxwin)
323                 tp->window_clamp = max(2 * tp->advmss, maxwin - tp->advmss);
324
325         tp->rcv_ssthresh = min(tp->rcv_ssthresh, tp->window_clamp);
326         tp->snd_cwnd_stamp = tcp_time_stamp;
327 }
328
329 /* 5. Recalculate window clamp after socket hit its memory bounds. */
330 static void tcp_clamp_window(struct sock *sk, struct tcp_opt *tp)
331 {
332         struct sk_buff *skb;
333         unsigned int app_win = tp->rcv_nxt - tp->copied_seq;
334         int ofo_win = 0;
335
336         tp->ack.quick = 0;
337
338         skb_queue_walk(&tp->out_of_order_queue, skb) {
339                 ofo_win += skb->len;
340         }
341
342         /* If overcommit is due to out of order segments,
343          * do not clamp window. Try to expand rcvbuf instead.
344          */
345         if (ofo_win) {
346                 if (sk->sk_rcvbuf < sysctl_tcp_rmem[2] &&
347                     !(sk->sk_userlocks & SOCK_RCVBUF_LOCK) &&
348                     !tcp_memory_pressure &&
349                     atomic_read(&tcp_memory_allocated) < sysctl_tcp_mem[0])
350                         sk->sk_rcvbuf = min(atomic_read(&sk->sk_rmem_alloc),
351                                             sysctl_tcp_rmem[2]);
352         }
353         if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf) {
354                 app_win += ofo_win;
355                 if (atomic_read(&sk->sk_rmem_alloc) >= 2 * sk->sk_rcvbuf)
356                         app_win >>= 1;
357                 if (app_win > tp->ack.rcv_mss)
358                         app_win -= tp->ack.rcv_mss;
359                 app_win = max(app_win, 2U*tp->advmss);
360
361                 if (!ofo_win)
362                         tp->window_clamp = min(tp->window_clamp, app_win);
363                 tp->rcv_ssthresh = min(tp->window_clamp, 2U*tp->advmss);
364         }
365 }
366
367 /* There is something which you must keep in mind when you analyze the
368  * behavior of the tp->ato delayed ack timeout interval.  When a
369  * connection starts up, we want to ack as quickly as possible.  The
370  * problem is that "good" TCP's do slow start at the beginning of data
371  * transmission.  The means that until we send the first few ACK's the
372  * sender will sit on his end and only queue most of his data, because
373  * he can only send snd_cwnd unacked packets at any given time.  For
374  * each ACK we send, he increments snd_cwnd and transmits more of his
375  * queue.  -DaveM
376  */
377 static void tcp_event_data_recv(struct sock *sk, struct tcp_opt *tp, struct sk_buff *skb)
378 {
379         u32 now;
380
381         tcp_schedule_ack(tp);
382
383         tcp_measure_rcv_mss(tp, skb);
384
385         now = tcp_time_stamp;
386
387         if (!tp->ack.ato) {
388                 /* The _first_ data packet received, initialize
389                  * delayed ACK engine.
390                  */
391                 tcp_incr_quickack(tp);
392                 tp->ack.ato = TCP_ATO_MIN;
393         } else {
394                 int m = now - tp->ack.lrcvtime;
395
396                 if (m <= TCP_ATO_MIN/2) {
397                         /* The fastest case is the first. */
398                         tp->ack.ato = (tp->ack.ato>>1) + TCP_ATO_MIN/2;
399                 } else if (m < tp->ack.ato) {
400                         tp->ack.ato = (tp->ack.ato>>1) + m;
401                         if (tp->ack.ato > tp->rto)
402                                 tp->ack.ato = tp->rto;
403                 } else if (m > tp->rto) {
404                         /* Too long gap. Apparently sender falled to
405                          * restart window, so that we send ACKs quickly.
406                          */
407                         tcp_incr_quickack(tp);
408                         tcp_mem_reclaim(sk);
409                 }
410         }
411         tp->ack.lrcvtime = now;
412
413         TCP_ECN_check_ce(tp, skb);
414
415         if (skb->len >= 128)
416                 tcp_grow_window(sk, tp, skb);
417 }
418
419 /* Set up a new TCP connection, depending on whether it should be
420  * using Vegas or not.
421  */    
422 void tcp_vegas_init(struct tcp_opt *tp)
423 {
424         if (sysctl_tcp_vegas_cong_avoid) {
425                 tp->vegas.do_vegas = 1;
426                 tp->vegas.baseRTT = 0x7fffffff;
427                 tcp_vegas_enable(tp);
428         } else 
429                 tcp_vegas_disable(tp);
430 }
431
432 /* Do RTT sampling needed for Vegas.
433  * Basically we:
434  *   o min-filter RTT samples from within an RTT to get the current
435  *     propagation delay + queuing delay (we are min-filtering to try to
436  *     avoid the effects of delayed ACKs)
437  *   o min-filter RTT samples from a much longer window (forever for now)
438  *     to find the propagation delay (baseRTT)
439  */
440 static inline void vegas_rtt_calc(struct tcp_opt *tp, __u32 rtt)
441 {
442         __u32 vrtt = rtt + 1; /* Never allow zero rtt or baseRTT */
443
444         /* Filter to find propagation delay: */
445         if (vrtt < tp->vegas.baseRTT) 
446                 tp->vegas.baseRTT = vrtt;
447
448         /* Find the min RTT during the last RTT to find
449          * the current prop. delay + queuing delay:
450          */
451         tp->vegas.minRTT = min(tp->vegas.minRTT, vrtt);
452         tp->vegas.cntRTT++;
453 }
454
455 /* Called to compute a smoothed rtt estimate. The data fed to this
456  * routine either comes from timestamps, or from segments that were
457  * known _not_ to have been retransmitted [see Karn/Partridge
458  * Proceedings SIGCOMM 87]. The algorithm is from the SIGCOMM 88
459  * piece by Van Jacobson.
460  * NOTE: the next three routines used to be one big routine.
461  * To save cycles in the RFC 1323 implementation it was better to break
462  * it up into three procedures. -- erics
463  */
464 static void tcp_rtt_estimator(struct tcp_opt *tp, __u32 mrtt)
465 {
466         long m = mrtt; /* RTT */
467
468         if (tcp_vegas_enabled(tp))
469                 vegas_rtt_calc(tp, mrtt);
470
471         /*      The following amusing code comes from Jacobson's
472          *      article in SIGCOMM '88.  Note that rtt and mdev
473          *      are scaled versions of rtt and mean deviation.
474          *      This is designed to be as fast as possible 
475          *      m stands for "measurement".
476          *
477          *      On a 1990 paper the rto value is changed to:
478          *      RTO = rtt + 4 * mdev
479          *
480          * Funny. This algorithm seems to be very broken.
481          * These formulae increase RTO, when it should be decreased, increase
482          * too slowly, when it should be incresed fastly, decrease too fastly
483          * etc. I guess in BSD RTO takes ONE value, so that it is absolutely
484          * does not matter how to _calculate_ it. Seems, it was trap
485          * that VJ failed to avoid. 8)
486          */
487         if(m == 0)
488                 m = 1;
489         if (tp->srtt != 0) {
490                 m -= (tp->srtt >> 3);   /* m is now error in rtt est */
491                 tp->srtt += m;          /* rtt = 7/8 rtt + 1/8 new */
492                 if (m < 0) {
493                         m = -m;         /* m is now abs(error) */
494                         m -= (tp->mdev >> 2);   /* similar update on mdev */
495                         /* This is similar to one of Eifel findings.
496                          * Eifel blocks mdev updates when rtt decreases.
497                          * This solution is a bit different: we use finer gain
498                          * for mdev in this case (alpha*beta).
499                          * Like Eifel it also prevents growth of rto,
500                          * but also it limits too fast rto decreases,
501                          * happening in pure Eifel.
502                          */
503                         if (m > 0)
504                                 m >>= 3;
505                 } else {
506                         m -= (tp->mdev >> 2);   /* similar update on mdev */
507                 }
508                 tp->mdev += m;          /* mdev = 3/4 mdev + 1/4 new */
509                 if (tp->mdev > tp->mdev_max) {
510                         tp->mdev_max = tp->mdev;
511                         if (tp->mdev_max > tp->rttvar)
512                                 tp->rttvar = tp->mdev_max;
513                 }
514                 if (after(tp->snd_una, tp->rtt_seq)) {
515                         if (tp->mdev_max < tp->rttvar)
516                                 tp->rttvar -= (tp->rttvar-tp->mdev_max)>>2;
517                         tp->rtt_seq = tp->snd_nxt;
518                         tp->mdev_max = TCP_RTO_MIN;
519                 }
520         } else {
521                 /* no previous measure. */
522                 tp->srtt = m<<3;        /* take the measured time to be rtt */
523                 tp->mdev = m<<1;        /* make sure rto = 3*rtt */
524                 tp->mdev_max = tp->rttvar = max(tp->mdev, TCP_RTO_MIN);
525                 tp->rtt_seq = tp->snd_nxt;
526         }
527
528         tcp_westwood_update_rtt(tp, tp->srtt >> 3);
529 }
530
531 /* Calculate rto without backoff.  This is the second half of Van Jacobson's
532  * routine referred to above.
533  */
534 static __inline__ void tcp_set_rto(struct tcp_opt *tp)
535 {
536         /* Old crap is replaced with new one. 8)
537          *
538          * More seriously:
539          * 1. If rtt variance happened to be less 50msec, it is hallucination.
540          *    It cannot be less due to utterly erratic ACK generation made
541          *    at least by solaris and freebsd. "Erratic ACKs" has _nothing_
542          *    to do with delayed acks, because at cwnd>2 true delack timeout
543          *    is invisible. Actually, Linux-2.4 also generates erratic
544          *    ACKs in some curcumstances.
545          */
546         tp->rto = (tp->srtt >> 3) + tp->rttvar;
547
548         /* 2. Fixups made earlier cannot be right.
549          *    If we do not estimate RTO correctly without them,
550          *    all the algo is pure shit and should be replaced
551          *    with correct one. It is exaclty, which we pretend to do.
552          */
553 }
554
555 /* NOTE: clamping at TCP_RTO_MIN is not required, current algo
556  * guarantees that rto is higher.
557  */
558 static __inline__ void tcp_bound_rto(struct tcp_opt *tp)
559 {
560         if (tp->rto > TCP_RTO_MAX)
561                 tp->rto = TCP_RTO_MAX;
562 }
563
564 /* Save metrics learned by this TCP session.
565    This function is called only, when TCP finishes successfully
566    i.e. when it enters TIME-WAIT or goes from LAST-ACK to CLOSE.
567  */
568 void tcp_update_metrics(struct sock *sk)
569 {
570         struct tcp_opt *tp = tcp_sk(sk);
571         struct dst_entry *dst = __sk_dst_get(sk);
572
573         if (sysctl_tcp_nometrics_save)
574                 return;
575
576         dst_confirm(dst);
577
578         if (dst && (dst->flags&DST_HOST)) {
579                 int m;
580
581                 if (tp->backoff || !tp->srtt) {
582                         /* This session failed to estimate rtt. Why?
583                          * Probably, no packets returned in time.
584                          * Reset our results.
585                          */
586                         if (!(dst_metric_locked(dst, RTAX_RTT)))
587                                 dst->metrics[RTAX_RTT-1] = 0;
588                         return;
589                 }
590
591                 m = dst_metric(dst, RTAX_RTT) - tp->srtt;
592
593                 /* If newly calculated rtt larger than stored one,
594                  * store new one. Otherwise, use EWMA. Remember,
595                  * rtt overestimation is always better than underestimation.
596                  */
597                 if (!(dst_metric_locked(dst, RTAX_RTT))) {
598                         if (m <= 0)
599                                 dst->metrics[RTAX_RTT-1] = tp->srtt;
600                         else
601                                 dst->metrics[RTAX_RTT-1] -= (m>>3);
602                 }
603
604                 if (!(dst_metric_locked(dst, RTAX_RTTVAR))) {
605                         if (m < 0)
606                                 m = -m;
607
608                         /* Scale deviation to rttvar fixed point */
609                         m >>= 1;
610                         if (m < tp->mdev)
611                                 m = tp->mdev;
612
613                         if (m >= dst_metric(dst, RTAX_RTTVAR))
614                                 dst->metrics[RTAX_RTTVAR-1] = m;
615                         else
616                                 dst->metrics[RTAX_RTTVAR-1] -=
617                                         (dst->metrics[RTAX_RTTVAR-1] - m)>>2;
618                 }
619
620                 if (tp->snd_ssthresh >= 0xFFFF) {
621                         /* Slow start still did not finish. */
622                         if (dst_metric(dst, RTAX_SSTHRESH) &&
623                             !dst_metric_locked(dst, RTAX_SSTHRESH) &&
624                             (tp->snd_cwnd >> 1) > dst_metric(dst, RTAX_SSTHRESH))
625                                 dst->metrics[RTAX_SSTHRESH-1] = tp->snd_cwnd >> 1;
626                         if (!dst_metric_locked(dst, RTAX_CWND) &&
627                             tp->snd_cwnd > dst_metric(dst, RTAX_CWND))
628                                 dst->metrics[RTAX_CWND-1] = tp->snd_cwnd;
629                 } else if (tp->snd_cwnd > tp->snd_ssthresh &&
630                            tp->ca_state == TCP_CA_Open) {
631                         /* Cong. avoidance phase, cwnd is reliable. */
632                         if (!dst_metric_locked(dst, RTAX_SSTHRESH))
633                                 dst->metrics[RTAX_SSTHRESH-1] =
634                                         max(tp->snd_cwnd >> 1, tp->snd_ssthresh);
635                         if (!dst_metric_locked(dst, RTAX_CWND))
636                                 dst->metrics[RTAX_CWND-1] = (dst->metrics[RTAX_CWND-1] + tp->snd_cwnd) >> 1;
637                 } else {
638                         /* Else slow start did not finish, cwnd is non-sense,
639                            ssthresh may be also invalid.
640                          */
641                         if (!dst_metric_locked(dst, RTAX_CWND))
642                                 dst->metrics[RTAX_CWND-1] = (dst->metrics[RTAX_CWND-1] + tp->snd_ssthresh) >> 1;
643                         if (dst->metrics[RTAX_SSTHRESH-1] &&
644                             !dst_metric_locked(dst, RTAX_SSTHRESH) &&
645                             tp->snd_ssthresh > dst->metrics[RTAX_SSTHRESH-1])
646                                 dst->metrics[RTAX_SSTHRESH-1] = tp->snd_ssthresh;
647                 }
648
649                 if (!dst_metric_locked(dst, RTAX_REORDERING)) {
650                         if (dst->metrics[RTAX_REORDERING-1] < tp->reordering &&
651                             tp->reordering != sysctl_tcp_reordering)
652                                 dst->metrics[RTAX_REORDERING-1] = tp->reordering;
653                 }
654         }
655 }
656
657 /* Numbers are taken from RFC2414.  */
658 __u32 tcp_init_cwnd(struct tcp_opt *tp, struct dst_entry *dst)
659 {
660         __u32 cwnd = (dst ? dst_metric(dst, RTAX_INITCWND) : 0);
661
662         if (!cwnd) {
663                 if (tp->mss_cache > 1460)
664                         cwnd = 2;
665                 else
666                         cwnd = (tp->mss_cache > 1095) ? 3 : 4;
667         }
668         return min_t(__u32, cwnd, tp->snd_cwnd_clamp);
669 }
670
671 /* Initialize metrics on socket. */
672
673 static void tcp_init_metrics(struct sock *sk)
674 {
675         struct tcp_opt *tp = tcp_sk(sk);
676         struct dst_entry *dst = __sk_dst_get(sk);
677
678         if (dst == NULL)
679                 goto reset;
680
681         dst_confirm(dst);
682
683         if (dst_metric_locked(dst, RTAX_CWND))
684                 tp->snd_cwnd_clamp = dst_metric(dst, RTAX_CWND);
685         if (dst_metric(dst, RTAX_SSTHRESH)) {
686                 tp->snd_ssthresh = dst_metric(dst, RTAX_SSTHRESH);
687                 if (tp->snd_ssthresh > tp->snd_cwnd_clamp)
688                         tp->snd_ssthresh = tp->snd_cwnd_clamp;
689         }
690         if (dst_metric(dst, RTAX_REORDERING) &&
691             tp->reordering != dst_metric(dst, RTAX_REORDERING)) {
692                 tp->sack_ok &= ~2;
693                 tp->reordering = dst_metric(dst, RTAX_REORDERING);
694         }
695
696         if (dst_metric(dst, RTAX_RTT) == 0)
697                 goto reset;
698
699         if (!tp->srtt && dst_metric(dst, RTAX_RTT) < (TCP_TIMEOUT_INIT << 3))
700                 goto reset;
701
702         /* Initial rtt is determined from SYN,SYN-ACK.
703          * The segment is small and rtt may appear much
704          * less than real one. Use per-dst memory
705          * to make it more realistic.
706          *
707          * A bit of theory. RTT is time passed after "normal" sized packet
708          * is sent until it is ACKed. In normal curcumstances sending small
709          * packets force peer to delay ACKs and calculation is correct too.
710          * The algorithm is adaptive and, provided we follow specs, it
711          * NEVER underestimate RTT. BUT! If peer tries to make some clever
712          * tricks sort of "quick acks" for time long enough to decrease RTT
713          * to low value, and then abruptly stops to do it and starts to delay
714          * ACKs, wait for troubles.
715          */
716         if (dst_metric(dst, RTAX_RTT) > tp->srtt)
717                 tp->srtt = dst_metric(dst, RTAX_RTT);
718         if (dst_metric(dst, RTAX_RTTVAR) > tp->mdev) {
719                 tp->mdev = dst_metric(dst, RTAX_RTTVAR);
720                 tp->mdev_max = tp->rttvar = max(tp->mdev, TCP_RTO_MIN);
721         }
722         tcp_set_rto(tp);
723         tcp_bound_rto(tp);
724         if (tp->rto < TCP_TIMEOUT_INIT && !tp->saw_tstamp)
725                 goto reset;
726         tp->snd_cwnd = tcp_init_cwnd(tp, dst);
727         tp->snd_cwnd_stamp = tcp_time_stamp;
728         return;
729
730 reset:
731         /* Play conservative. If timestamps are not
732          * supported, TCP will fail to recalculate correct
733          * rtt, if initial rto is too small. FORGET ALL AND RESET!
734          */
735         if (!tp->saw_tstamp && tp->srtt) {
736                 tp->srtt = 0;
737                 tp->mdev = tp->mdev_max = tp->rttvar = TCP_TIMEOUT_INIT;
738                 tp->rto = TCP_TIMEOUT_INIT;
739         }
740 }
741
742 static void tcp_update_reordering(struct tcp_opt *tp, int metric, int ts)
743 {
744         if (metric > tp->reordering) {
745                 tp->reordering = min(TCP_MAX_REORDERING, metric);
746
747                 /* This exciting event is worth to be remembered. 8) */
748                 if (ts)
749                         NET_INC_STATS_BH(TCPTSReorder);
750                 else if (IsReno(tp))
751                         NET_INC_STATS_BH(TCPRenoReorder);
752                 else if (IsFack(tp))
753                         NET_INC_STATS_BH(TCPFACKReorder);
754                 else
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);
761 #endif
762                 /* Disable FACK yet. */
763                 tp->sack_ok &= ~2;
764         }
765 }
766
767 /* This procedure tags the retransmission queue when SACKs arrive.
768  *
769  * We have three tag bits: SACKED(S), RETRANS(R) and LOST(L).
770  * Packets in queue with these bits set are counted in variables
771  * sacked_out, retrans_out and lost_out, correspondingly.
772  *
773  * Valid combinations are:
774  * Tag  InFlight        Description
775  * 0    1               - orig segment is in flight.
776  * S    0               - nothing flies, orig reached receiver.
777  * L    0               - nothing flies, orig lost by net.
778  * R    2               - both orig and retransmit are in flight.
779  * L|R  1               - orig is lost, retransmit is in flight.
780  * S|R  1               - orig reached receiver, retrans is still in flight.
781  * (L|S|R is logically valid, it could occur when L|R is sacked,
782  *  but it is equivalent to plain S and code short-curcuits it to S.
783  *  L|S is logically invalid, it would mean -1 packet in flight 8))
784  *
785  * These 6 states form finite state machine, controlled by the following events:
786  * 1. New ACK (+SACK) arrives. (tcp_sacktag_write_queue())
787  * 2. Retransmission. (tcp_retransmit_skb(), tcp_xmit_retransmit_queue())
788  * 3. Loss detection event of one of three flavors:
789  *      A. Scoreboard estimator decided the packet is lost.
790  *         A'. Reno "three dupacks" marks head of queue lost.
791  *         A''. Its FACK modfication, head until snd.fack is lost.
792  *      B. SACK arrives sacking data transmitted after never retransmitted
793  *         hole was sent out.
794  *      C. SACK arrives sacking SND.NXT at the moment, when the
795  *         segment was retransmitted.
796  * 4. D-SACK added new rule: D-SACK changes any tag to S.
797  *
798  * It is pleasant to note, that state diagram turns out to be commutative,
799  * so that we are allowed not to be bothered by order of our actions,
800  * when multiple events arrive simultaneously. (see the function below).
801  *
802  * Reordering detection.
803  * --------------------
804  * Reordering metric is maximal distance, which a packet can be displaced
805  * in packet stream. With SACKs we can estimate it:
806  *
807  * 1. SACK fills old hole and the corresponding segment was not
808  *    ever retransmitted -> reordering. Alas, we cannot use it
809  *    when segment was retransmitted.
810  * 2. The last flaw is solved with D-SACK. D-SACK arrives
811  *    for retransmitted and already SACKed segment -> reordering..
812  * Both of these heuristics are not used in Loss state, when we cannot
813  * account for retransmits accurately.
814  */
815 static int
816 tcp_sacktag_write_queue(struct sock *sk, struct sk_buff *ack_skb, u32 prior_snd_una)
817 {
818         struct tcp_opt *tp = tcp_sk(sk);
819         unsigned char *ptr = ack_skb->h.raw + TCP_SKB_CB(ack_skb)->sacked;
820         struct tcp_sack_block *sp = (struct tcp_sack_block *)(ptr+2);
821         int num_sacks = (ptr[1] - TCPOLEN_SACK_BASE)>>3;
822         int reord = tp->packets_out;
823         int prior_fackets;
824         u32 lost_retrans = 0;
825         int flag = 0;
826         int i;
827
828         /* So, SACKs for already sent large segments will be lost.
829          * Not good, but alternative is to resegment the queue. */
830         if (sk->sk_route_caps & NETIF_F_TSO) {
831                 sk->sk_route_caps &= ~NETIF_F_TSO;
832                 sk->sk_no_largesend = 1;
833                 tp->mss_cache = tp->mss_cache_std;
834         }
835
836         if (!tp->sacked_out)
837                 tp->fackets_out = 0;
838         prior_fackets = tp->fackets_out;
839
840         for (i=0; i<num_sacks; i++, sp++) {
841                 struct sk_buff *skb;
842                 __u32 start_seq = ntohl(sp->start_seq);
843                 __u32 end_seq = ntohl(sp->end_seq);
844                 int fack_count = 0;
845                 int dup_sack = 0;
846
847                 /* Check for D-SACK. */
848                 if (i == 0) {
849                         u32 ack = TCP_SKB_CB(ack_skb)->ack_seq;
850
851                         if (before(start_seq, ack)) {
852                                 dup_sack = 1;
853                                 tp->sack_ok |= 4;
854                                 NET_INC_STATS_BH(TCPDSACKRecv);
855                         } else if (num_sacks > 1 &&
856                                    !after(end_seq, ntohl(sp[1].end_seq)) &&
857                                    !before(start_seq, ntohl(sp[1].start_seq))) {
858                                 dup_sack = 1;
859                                 tp->sack_ok |= 4;
860                                 NET_INC_STATS_BH(TCPDSACKOfoRecv);
861                         }
862
863                         /* D-SACK for already forgotten data...
864                          * Do dumb counting. */
865                         if (dup_sack &&
866                             !after(end_seq, prior_snd_una) &&
867                             after(end_seq, tp->undo_marker))
868                                 tp->undo_retrans--;
869
870                         /* Eliminate too old ACKs, but take into
871                          * account more or less fresh ones, they can
872                          * contain valid SACK info.
873                          */
874                         if (before(ack, prior_snd_una - tp->max_window))
875                                 return 0;
876                 }
877
878                 /* Event "B" in the comment above. */
879                 if (after(end_seq, tp->high_seq))
880                         flag |= FLAG_DATA_LOST;
881
882                 for_retrans_queue(skb, sk, tp) {
883                         u8 sacked = TCP_SKB_CB(skb)->sacked;
884                         int in_sack;
885
886                         /* The retransmission queue is always in order, so
887                          * we can short-circuit the walk early.
888                          */
889                         if(!before(TCP_SKB_CB(skb)->seq, end_seq))
890                                 break;
891
892                         fack_count++;
893
894                         in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
895                                 !before(end_seq, TCP_SKB_CB(skb)->end_seq);
896
897                         /* Account D-SACK for retransmitted packet. */
898                         if ((dup_sack && in_sack) &&
899                             (sacked & TCPCB_RETRANS) &&
900                             after(TCP_SKB_CB(skb)->end_seq, tp->undo_marker))
901                                 tp->undo_retrans--;
902
903                         /* The frame is ACKed. */
904                         if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una)) {
905                                 if (sacked&TCPCB_RETRANS) {
906                                         if ((dup_sack && in_sack) &&
907                                             (sacked&TCPCB_SACKED_ACKED))
908                                                 reord = min(fack_count, reord);
909                                 } else {
910                                         /* If it was in a hole, we detected reordering. */
911                                         if (fack_count < prior_fackets &&
912                                             !(sacked&TCPCB_SACKED_ACKED))
913                                                 reord = min(fack_count, reord);
914                                 }
915
916                                 /* Nothing to do; acked frame is about to be dropped. */
917                                 continue;
918                         }
919
920                         if ((sacked&TCPCB_SACKED_RETRANS) &&
921                             after(end_seq, TCP_SKB_CB(skb)->ack_seq) &&
922                             (!lost_retrans || after(end_seq, lost_retrans)))
923                                 lost_retrans = end_seq;
924
925                         if (!in_sack)
926                                 continue;
927
928                         if (!(sacked&TCPCB_SACKED_ACKED)) {
929                                 if (sacked & TCPCB_SACKED_RETRANS) {
930                                         /* If the segment is not tagged as lost,
931                                          * we do not clear RETRANS, believing
932                                          * that retransmission is still in flight.
933                                          */
934                                         if (sacked & TCPCB_LOST) {
935                                                 TCP_SKB_CB(skb)->sacked &= ~(TCPCB_LOST|TCPCB_SACKED_RETRANS);
936                                                 tp->lost_out--;
937                                                 tp->retrans_out--;
938                                         }
939                                 } else {
940                                         /* New sack for not retransmitted frame,
941                                          * which was in hole. It is reordering.
942                                          */
943                                         if (!(sacked & TCPCB_RETRANS) &&
944                                             fack_count < prior_fackets)
945                                                 reord = min(fack_count, reord);
946
947                                         if (sacked & TCPCB_LOST) {
948                                                 TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
949                                                 tp->lost_out--;
950                                         }
951                                 }
952
953                                 TCP_SKB_CB(skb)->sacked |= TCPCB_SACKED_ACKED;
954                                 flag |= FLAG_DATA_SACKED;
955                                 tp->sacked_out++;
956
957                                 if (fack_count > tp->fackets_out)
958                                         tp->fackets_out = fack_count;
959                         } else {
960                                 if (dup_sack && (sacked&TCPCB_RETRANS))
961                                         reord = min(fack_count, reord);
962                         }
963
964                         /* D-SACK. We can detect redundant retransmission
965                          * in S|R and plain R frames and clear it.
966                          * undo_retrans is decreased above, L|R frames
967                          * are accounted above as well.
968                          */
969                         if (dup_sack &&
970                             (TCP_SKB_CB(skb)->sacked&TCPCB_SACKED_RETRANS)) {
971                                 TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
972                                 tp->retrans_out--;
973                         }
974                 }
975         }
976
977         /* Check for lost retransmit. This superb idea is
978          * borrowed from "ratehalving". Event "C".
979          * Later note: FACK people cheated me again 8),
980          * we have to account for reordering! Ugly,
981          * but should help.
982          */
983         if (lost_retrans && tp->ca_state == TCP_CA_Recovery) {
984                 struct sk_buff *skb;
985
986                 for_retrans_queue(skb, sk, tp) {
987                         if (after(TCP_SKB_CB(skb)->seq, lost_retrans))
988                                 break;
989                         if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una))
990                                 continue;
991                         if ((TCP_SKB_CB(skb)->sacked&TCPCB_SACKED_RETRANS) &&
992                             after(lost_retrans, TCP_SKB_CB(skb)->ack_seq) &&
993                             (IsFack(tp) ||
994                              !before(lost_retrans,
995                                      TCP_SKB_CB(skb)->ack_seq + tp->reordering *
996                                      tp->mss_cache))) {
997                                 TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
998                                 tp->retrans_out--;
999
1000                                 if (!(TCP_SKB_CB(skb)->sacked&(TCPCB_LOST|TCPCB_SACKED_ACKED))) {
1001                                         tp->lost_out++;
1002                                         TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1003                                         flag |= FLAG_DATA_SACKED;
1004                                         NET_INC_STATS_BH(TCPLostRetransmit);
1005                                 }
1006                         }
1007                 }
1008         }
1009
1010         tp->left_out = tp->sacked_out + tp->lost_out;
1011
1012         if (reord < tp->fackets_out && tp->ca_state != TCP_CA_Loss)
1013                 tcp_update_reordering(tp, (tp->fackets_out + 1) - reord, 0);
1014
1015 #if FASTRETRANS_DEBUG > 0
1016         BUG_TRAP((int)tp->sacked_out >= 0);
1017         BUG_TRAP((int)tp->lost_out >= 0);
1018         BUG_TRAP((int)tp->retrans_out >= 0);
1019         BUG_TRAP((int)tcp_packets_in_flight(tp) >= 0);
1020 #endif
1021         return flag;
1022 }
1023
1024 /* RTO occurred, but do not yet enter loss state. Instead, transmit two new
1025  * segments to see from the next ACKs whether any data was really missing.
1026  * If the RTO was spurious, new ACKs should arrive.
1027  */
1028 void tcp_enter_frto(struct sock *sk)
1029 {
1030         struct tcp_opt *tp = tcp_sk(sk);
1031         struct sk_buff *skb;
1032
1033         tp->frto_counter = 1;
1034
1035         if (tp->ca_state <= TCP_CA_Disorder ||
1036             tp->snd_una == tp->high_seq ||
1037             (tp->ca_state == TCP_CA_Loss && !tp->retransmits)) {
1038                 tp->prior_ssthresh = tcp_current_ssthresh(tp);
1039                 if (!tcp_westwood_ssthresh(tp))
1040                         tp->snd_ssthresh = tcp_recalc_ssthresh(tp);
1041         }
1042
1043         /* Have to clear retransmission markers here to keep the bookkeeping
1044          * in shape, even though we are not yet in Loss state.
1045          * If something was really lost, it is eventually caught up
1046          * in tcp_enter_frto_loss.
1047          */
1048         tp->retrans_out = 0;
1049         tp->undo_marker = tp->snd_una;
1050         tp->undo_retrans = 0;
1051
1052         for_retrans_queue(skb, sk, tp) {
1053                 TCP_SKB_CB(skb)->sacked &= ~TCPCB_RETRANS;
1054         }
1055         tcp_sync_left_out(tp);
1056
1057         tcp_set_ca_state(tp, TCP_CA_Open);
1058         tp->frto_highmark = tp->snd_nxt;
1059 }
1060
1061 /* Enter Loss state after F-RTO was applied. Dupack arrived after RTO,
1062  * which indicates that we should follow the traditional RTO recovery,
1063  * i.e. mark everything lost and do go-back-N retransmission.
1064  */
1065 static void tcp_enter_frto_loss(struct sock *sk)
1066 {
1067         struct tcp_opt *tp = tcp_sk(sk);
1068         struct sk_buff *skb;
1069         int cnt = 0;
1070
1071         tp->sacked_out = 0;
1072         tp->lost_out = 0;
1073         tp->fackets_out = 0;
1074
1075         for_retrans_queue(skb, sk, tp) {
1076                 cnt++;
1077                 TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
1078                 if (!(TCP_SKB_CB(skb)->sacked&TCPCB_SACKED_ACKED)) {
1079
1080                         /* Do not mark those segments lost that were
1081                          * forward transmitted after RTO
1082                          */
1083                         if(!after(TCP_SKB_CB(skb)->end_seq,
1084                                    tp->frto_highmark)) {
1085                                 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1086                                 tp->lost_out++;
1087                         }
1088                 } else {
1089                         tp->sacked_out++;
1090                         tp->fackets_out = cnt;
1091                 }
1092         }
1093         tcp_sync_left_out(tp);
1094
1095         tp->snd_cwnd = tp->frto_counter + tcp_packets_in_flight(tp)+1;
1096         tp->snd_cwnd_cnt = 0;
1097         tp->snd_cwnd_stamp = tcp_time_stamp;
1098         tp->undo_marker = 0;
1099         tp->frto_counter = 0;
1100
1101         tp->reordering = min_t(unsigned int, tp->reordering,
1102                                              sysctl_tcp_reordering);
1103         tcp_set_ca_state(tp, TCP_CA_Loss);
1104         tp->high_seq = tp->frto_highmark;
1105         TCP_ECN_queue_cwr(tp);
1106 }
1107
1108 void tcp_clear_retrans(struct tcp_opt *tp)
1109 {
1110         tp->left_out = 0;
1111         tp->retrans_out = 0;
1112
1113         tp->fackets_out = 0;
1114         tp->sacked_out = 0;
1115         tp->lost_out = 0;
1116
1117         tp->undo_marker = 0;
1118         tp->undo_retrans = 0;
1119 }
1120
1121 /* Enter Loss state. If "how" is not zero, forget all SACK information
1122  * and reset tags completely, otherwise preserve SACKs. If receiver
1123  * dropped its ofo queue, we will know this due to reneging detection.
1124  */
1125 void tcp_enter_loss(struct sock *sk, int how)
1126 {
1127         struct tcp_opt *tp = tcp_sk(sk);
1128         struct sk_buff *skb;
1129         int cnt = 0;
1130
1131         /* Reduce ssthresh if it has not yet been made inside this window. */
1132         if (tp->ca_state <= TCP_CA_Disorder || tp->snd_una == tp->high_seq ||
1133             (tp->ca_state == TCP_CA_Loss && !tp->retransmits)) {
1134                 tp->prior_ssthresh = tcp_current_ssthresh(tp);
1135                 tp->snd_ssthresh = tcp_recalc_ssthresh(tp);
1136         }
1137         tp->snd_cwnd       = 1;
1138         tp->snd_cwnd_cnt   = 0;
1139         tp->snd_cwnd_stamp = tcp_time_stamp;
1140
1141         tcp_clear_retrans(tp);
1142
1143         /* Push undo marker, if it was plain RTO and nothing
1144          * was retransmitted. */
1145         if (!how)
1146                 tp->undo_marker = tp->snd_una;
1147
1148         for_retrans_queue(skb, sk, tp) {
1149                 cnt++;
1150                 if (TCP_SKB_CB(skb)->sacked&TCPCB_RETRANS)
1151                         tp->undo_marker = 0;
1152                 TCP_SKB_CB(skb)->sacked &= (~TCPCB_TAGBITS)|TCPCB_SACKED_ACKED;
1153                 if (!(TCP_SKB_CB(skb)->sacked&TCPCB_SACKED_ACKED) || how) {
1154                         TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_ACKED;
1155                         TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1156                         tp->lost_out++;
1157                 } else {
1158                         tp->sacked_out++;
1159                         tp->fackets_out = cnt;
1160                 }
1161         }
1162         tcp_sync_left_out(tp);
1163
1164         tp->reordering = min_t(unsigned int, tp->reordering,
1165                                              sysctl_tcp_reordering);
1166         tcp_set_ca_state(tp, TCP_CA_Loss);
1167         tp->high_seq = tp->snd_nxt;
1168         TCP_ECN_queue_cwr(tp);
1169 }
1170
1171 static int tcp_check_sack_reneging(struct sock *sk, struct tcp_opt *tp)
1172 {
1173         struct sk_buff *skb;
1174
1175         /* If ACK arrived pointing to a remembered SACK,
1176          * it means that our remembered SACKs do not reflect
1177          * real state of receiver i.e.
1178          * receiver _host_ is heavily congested (or buggy).
1179          * Do processing similar to RTO timeout.
1180          */
1181         if ((skb = skb_peek(&sk->sk_write_queue)) != NULL &&
1182             (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)) {
1183                 NET_INC_STATS_BH(TCPSACKReneging);
1184
1185                 tcp_enter_loss(sk, 1);
1186                 tp->retransmits++;
1187                 tcp_retransmit_skb(sk, skb_peek(&sk->sk_write_queue));
1188                 tcp_reset_xmit_timer(sk, TCP_TIME_RETRANS, tp->rto);
1189                 return 1;
1190         }
1191         return 0;
1192 }
1193
1194 static inline int tcp_fackets_out(struct tcp_opt *tp)
1195 {
1196         return IsReno(tp) ? tp->sacked_out+1 : tp->fackets_out;
1197 }
1198
1199 static inline int tcp_skb_timedout(struct tcp_opt *tp, struct sk_buff *skb)
1200 {
1201         return (tcp_time_stamp - TCP_SKB_CB(skb)->when > tp->rto);
1202 }
1203
1204 static inline int tcp_head_timedout(struct sock *sk, struct tcp_opt *tp)
1205 {
1206         return tp->packets_out &&
1207                tcp_skb_timedout(tp, skb_peek(&sk->sk_write_queue));
1208 }
1209
1210 /* Linux NewReno/SACK/FACK/ECN state machine.
1211  * --------------------------------------
1212  *
1213  * "Open"       Normal state, no dubious events, fast path.
1214  * "Disorder"   In all the respects it is "Open",
1215  *              but requires a bit more attention. It is entered when
1216  *              we see some SACKs or dupacks. It is split of "Open"
1217  *              mainly to move some processing from fast path to slow one.
1218  * "CWR"        CWND was reduced due to some Congestion Notification event.
1219  *              It can be ECN, ICMP source quench, local device congestion.
1220  * "Recovery"   CWND was reduced, we are fast-retransmitting.
1221  * "Loss"       CWND was reduced due to RTO timeout or SACK reneging.
1222  *
1223  * tcp_fastretrans_alert() is entered:
1224  * - each incoming ACK, if state is not "Open"
1225  * - when arrived ACK is unusual, namely:
1226  *      * SACK
1227  *      * Duplicate ACK.
1228  *      * ECN ECE.
1229  *
1230  * Counting packets in flight is pretty simple.
1231  *
1232  *      in_flight = packets_out - left_out + retrans_out
1233  *
1234  *      packets_out is SND.NXT-SND.UNA counted in packets.
1235  *
1236  *      retrans_out is number of retransmitted segments.
1237  *
1238  *      left_out is number of segments left network, but not ACKed yet.
1239  *
1240  *              left_out = sacked_out + lost_out
1241  *
1242  *     sacked_out: Packets, which arrived to receiver out of order
1243  *                 and hence not ACKed. With SACKs this number is simply
1244  *                 amount of SACKed data. Even without SACKs
1245  *                 it is easy to give pretty reliable estimate of this number,
1246  *                 counting duplicate ACKs.
1247  *
1248  *       lost_out: Packets lost by network. TCP has no explicit
1249  *                 "loss notification" feedback from network (for now).
1250  *                 It means that this number can be only _guessed_.
1251  *                 Actually, it is the heuristics to predict lossage that
1252  *                 distinguishes different algorithms.
1253  *
1254  *      F.e. after RTO, when all the queue is considered as lost,
1255  *      lost_out = packets_out and in_flight = retrans_out.
1256  *
1257  *              Essentially, we have now two algorithms counting
1258  *              lost packets.
1259  *
1260  *              FACK: It is the simplest heuristics. As soon as we decided
1261  *              that something is lost, we decide that _all_ not SACKed
1262  *              packets until the most forward SACK are lost. I.e.
1263  *              lost_out = fackets_out - sacked_out and left_out = fackets_out.
1264  *              It is absolutely correct estimate, if network does not reorder
1265  *              packets. And it loses any connection to reality when reordering
1266  *              takes place. We use FACK by default until reordering
1267  *              is suspected on the path to this destination.
1268  *
1269  *              NewReno: when Recovery is entered, we assume that one segment
1270  *              is lost (classic Reno). While we are in Recovery and
1271  *              a partial ACK arrives, we assume that one more packet
1272  *              is lost (NewReno). This heuristics are the same in NewReno
1273  *              and SACK.
1274  *
1275  *  Imagine, that's all! Forget about all this shamanism about CWND inflation
1276  *  deflation etc. CWND is real congestion window, never inflated, changes
1277  *  only according to classic VJ rules.
1278  *
1279  * Really tricky (and requiring careful tuning) part of algorithm
1280  * is hidden in functions tcp_time_to_recover() and tcp_xmit_retransmit_queue().
1281  * The first determines the moment _when_ we should reduce CWND and,
1282  * hence, slow down forward transmission. In fact, it determines the moment
1283  * when we decide that hole is caused by loss, rather than by a reorder.
1284  *
1285  * tcp_xmit_retransmit_queue() decides, _what_ we should retransmit to fill
1286  * holes, caused by lost packets.
1287  *
1288  * And the most logically complicated part of algorithm is undo
1289  * heuristics. We detect false retransmits due to both too early
1290  * fast retransmit (reordering) and underestimated RTO, analyzing
1291  * timestamps and D-SACKs. When we detect that some segments were
1292  * retransmitted by mistake and CWND reduction was wrong, we undo
1293  * window reduction and abort recovery phase. This logic is hidden
1294  * inside several functions named tcp_try_undo_<something>.
1295  */
1296
1297 /* This function decides, when we should leave Disordered state
1298  * and enter Recovery phase, reducing congestion window.
1299  *
1300  * Main question: may we further continue forward transmission
1301  * with the same cwnd?
1302  */
1303 static int
1304 tcp_time_to_recover(struct sock *sk, struct tcp_opt *tp)
1305 {
1306         /* Trick#1: The loss is proven. */
1307         if (tp->lost_out)
1308                 return 1;
1309
1310         /* Not-A-Trick#2 : Classic rule... */
1311         if (tcp_fackets_out(tp) > tp->reordering)
1312                 return 1;
1313
1314         /* Trick#3 : when we use RFC2988 timer restart, fast
1315          * retransmit can be triggered by timeout of queue head.
1316          */
1317         if (tcp_head_timedout(sk, tp))
1318                 return 1;
1319
1320         /* Trick#4: It is still not OK... But will it be useful to delay
1321          * recovery more?
1322          */
1323         if (tp->packets_out <= tp->reordering &&
1324             tp->sacked_out >= max_t(__u32, tp->packets_out/2, sysctl_tcp_reordering) &&
1325             !tcp_may_send_now(sk, tp)) {
1326                 /* We have nothing to send. This connection is limited
1327                  * either by receiver window or by application.
1328                  */
1329                 return 1;
1330         }
1331
1332         return 0;
1333 }
1334
1335 /* If we receive more dupacks than we expected counting segments
1336  * in assumption of absent reordering, interpret this as reordering.
1337  * The only another reason could be bug in receiver TCP.
1338  */
1339 static void tcp_check_reno_reordering(struct tcp_opt *tp, int addend)
1340 {
1341         u32 holes;
1342
1343         holes = max(tp->lost_out, 1U);
1344         holes = min(holes, tp->packets_out);
1345
1346         if (tp->sacked_out + holes > tp->packets_out) {
1347                 tp->sacked_out = tp->packets_out - holes;
1348                 tcp_update_reordering(tp, tp->packets_out+addend, 0);
1349         }
1350 }
1351
1352 /* Emulate SACKs for SACKless connection: account for a new dupack. */
1353
1354 static void tcp_add_reno_sack(struct tcp_opt *tp)
1355 {
1356         ++tp->sacked_out;
1357         tcp_check_reno_reordering(tp, 0);
1358         tcp_sync_left_out(tp);
1359 }
1360
1361 /* Account for ACK, ACKing some data in Reno Recovery phase. */
1362
1363 static void tcp_remove_reno_sacks(struct sock *sk, struct tcp_opt *tp, int acked)
1364 {
1365         if (acked > 0) {
1366                 /* One ACK acked hole. The rest eat duplicate ACKs. */
1367                 if (acked-1 >= tp->sacked_out)
1368                         tp->sacked_out = 0;
1369                 else
1370                         tp->sacked_out -= acked-1;
1371         }
1372         tcp_check_reno_reordering(tp, acked);
1373         tcp_sync_left_out(tp);
1374 }
1375
1376 static inline void tcp_reset_reno_sack(struct tcp_opt *tp)
1377 {
1378         tp->sacked_out = 0;
1379         tp->left_out = tp->lost_out;
1380 }
1381
1382 /* Mark head of queue up as lost. */
1383 static void
1384 tcp_mark_head_lost(struct sock *sk, struct tcp_opt *tp, int packets, u32 high_seq)
1385 {
1386         struct sk_buff *skb;
1387         int cnt = packets;
1388
1389         BUG_TRAP(cnt <= tp->packets_out);
1390
1391         for_retrans_queue(skb, sk, tp) {
1392                 if (--cnt < 0 || after(TCP_SKB_CB(skb)->end_seq, high_seq))
1393                         break;
1394                 if (!(TCP_SKB_CB(skb)->sacked&TCPCB_TAGBITS)) {
1395                         TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1396                         tp->lost_out++;
1397                 }
1398         }
1399         tcp_sync_left_out(tp);
1400 }
1401
1402 /* Account newly detected lost packet(s) */
1403
1404 static void tcp_update_scoreboard(struct sock *sk, struct tcp_opt *tp)
1405 {
1406         if (IsFack(tp)) {
1407                 int lost = tp->fackets_out - tp->reordering;
1408                 if (lost <= 0)
1409                         lost = 1;
1410                 tcp_mark_head_lost(sk, tp, lost, tp->high_seq);
1411         } else {
1412                 tcp_mark_head_lost(sk, tp, 1, tp->high_seq);
1413         }
1414
1415         /* New heuristics: it is possible only after we switched
1416          * to restart timer each time when something is ACKed.
1417          * Hence, we can detect timed out packets during fast
1418          * retransmit without falling to slow start.
1419          */
1420         if (tcp_head_timedout(sk, tp)) {
1421                 struct sk_buff *skb;
1422
1423                 for_retrans_queue(skb, sk, tp) {
1424                         if (tcp_skb_timedout(tp, skb) &&
1425                             !(TCP_SKB_CB(skb)->sacked&TCPCB_TAGBITS)) {
1426                                 TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1427                                 tp->lost_out++;
1428                         }
1429                 }
1430                 tcp_sync_left_out(tp);
1431         }
1432 }
1433
1434 /* CWND moderation, preventing bursts due to too big ACKs
1435  * in dubious situations.
1436  */
1437 static __inline__ void tcp_moderate_cwnd(struct tcp_opt *tp)
1438 {
1439         tp->snd_cwnd = min(tp->snd_cwnd,
1440                            tcp_packets_in_flight(tp)+tcp_max_burst(tp));
1441         tp->snd_cwnd_stamp = tcp_time_stamp;
1442 }
1443
1444 /* Decrease cwnd each second ack. */
1445
1446 static void tcp_cwnd_down(struct tcp_opt *tp)
1447 {
1448         int decr = tp->snd_cwnd_cnt + 1;
1449         __u32 limit;
1450
1451         /*
1452          * TCP Westwood
1453          * Here limit is evaluated as BWestimation*RTTmin (for obtaining it
1454          * in packets we use mss_cache). If sysctl_tcp_westwood is off
1455          * tcp_westwood_bw_rttmin() returns 0. In such case snd_ssthresh is
1456          * still used as usual. It prevents other strange cases in which
1457          * BWE*RTTmin could assume value 0. It should not happen but...
1458          */
1459
1460         if (!(limit = tcp_westwood_bw_rttmin(tp)))
1461                 limit = tp->snd_ssthresh/2;
1462
1463         tp->snd_cwnd_cnt = decr&1;
1464         decr >>= 1;
1465
1466         if (decr && tp->snd_cwnd > limit)
1467                 tp->snd_cwnd -= decr;
1468
1469         tp->snd_cwnd = min(tp->snd_cwnd, tcp_packets_in_flight(tp)+1);
1470         tp->snd_cwnd_stamp = tcp_time_stamp;
1471 }
1472
1473 /* Nothing was retransmitted or returned timestamp is less
1474  * than timestamp of the first retransmission.
1475  */
1476 static __inline__ int tcp_packet_delayed(struct tcp_opt *tp)
1477 {
1478         return !tp->retrans_stamp ||
1479                 (tp->saw_tstamp && tp->rcv_tsecr &&
1480                  (__s32)(tp->rcv_tsecr - tp->retrans_stamp) < 0);
1481 }
1482
1483 /* Undo procedures. */
1484
1485 #if FASTRETRANS_DEBUG > 1
1486 static void DBGUNDO(struct sock *sk, struct tcp_opt *tp, const char *msg)
1487 {
1488         struct inet_opt *inet = inet_sk(sk);
1489         printk(KERN_DEBUG "Undo %s %u.%u.%u.%u/%u c%u l%u ss%u/%u p%u\n",
1490                msg,
1491                NIPQUAD(inet->daddr), ntohs(inet->dport),
1492                tp->snd_cwnd, tp->left_out,
1493                tp->snd_ssthresh, tp->prior_ssthresh, tp->packets_out);
1494 }
1495 #else
1496 #define DBGUNDO(x...) do { } while (0)
1497 #endif
1498
1499 static void tcp_undo_cwr(struct tcp_opt *tp, int undo)
1500 {
1501         if (tp->prior_ssthresh) {
1502                 tp->snd_cwnd = max(tp->snd_cwnd, tp->snd_ssthresh<<1);
1503
1504                 if (undo && tp->prior_ssthresh > tp->snd_ssthresh) {
1505                         tp->snd_ssthresh = tp->prior_ssthresh;
1506                         TCP_ECN_withdraw_cwr(tp);
1507                 }
1508         } else {
1509                 tp->snd_cwnd = max(tp->snd_cwnd, tp->snd_ssthresh);
1510         }
1511         tcp_moderate_cwnd(tp);
1512         tp->snd_cwnd_stamp = tcp_time_stamp;
1513 }
1514
1515 static inline int tcp_may_undo(struct tcp_opt *tp)
1516 {
1517         return tp->undo_marker &&
1518                 (!tp->undo_retrans || tcp_packet_delayed(tp));
1519 }
1520
1521 /* People celebrate: "We love our President!" */
1522 static int tcp_try_undo_recovery(struct sock *sk, struct tcp_opt *tp)
1523 {
1524         if (tcp_may_undo(tp)) {
1525                 /* Happy end! We did not retransmit anything
1526                  * or our original transmission succeeded.
1527                  */
1528                 DBGUNDO(sk, tp, tp->ca_state == TCP_CA_Loss ? "loss" : "retrans");
1529                 tcp_undo_cwr(tp, 1);
1530                 if (tp->ca_state == TCP_CA_Loss)
1531                         NET_INC_STATS_BH(TCPLossUndo);
1532                 else
1533                         NET_INC_STATS_BH(TCPFullUndo);
1534                 tp->undo_marker = 0;
1535         }
1536         if (tp->snd_una == tp->high_seq && IsReno(tp)) {
1537                 /* Hold old state until something *above* high_seq
1538                  * is ACKed. For Reno it is MUST to prevent false
1539                  * fast retransmits (RFC2582). SACK TCP is safe. */
1540                 tcp_moderate_cwnd(tp);
1541                 return 1;
1542         }
1543         tcp_set_ca_state(tp, TCP_CA_Open);
1544         return 0;
1545 }
1546
1547 /* Try to undo cwnd reduction, because D-SACKs acked all retransmitted data */
1548 static void tcp_try_undo_dsack(struct sock *sk, struct tcp_opt *tp)
1549 {
1550         if (tp->undo_marker && !tp->undo_retrans) {
1551                 DBGUNDO(sk, tp, "D-SACK");
1552                 tcp_undo_cwr(tp, 1);
1553                 tp->undo_marker = 0;
1554                 NET_INC_STATS_BH(TCPDSACKUndo);
1555         }
1556 }
1557
1558 /* Undo during fast recovery after partial ACK. */
1559
1560 static int tcp_try_undo_partial(struct sock *sk, struct tcp_opt *tp, int acked)
1561 {
1562         /* Partial ACK arrived. Force Hoe's retransmit. */
1563         int failed = IsReno(tp) || tp->fackets_out>tp->reordering;
1564
1565         if (tcp_may_undo(tp)) {
1566                 /* Plain luck! Hole if filled with delayed
1567                  * packet, rather than with a retransmit.
1568                  */
1569                 if (tp->retrans_out == 0)
1570                         tp->retrans_stamp = 0;
1571
1572                 tcp_update_reordering(tp, tcp_fackets_out(tp)+acked, 1);
1573
1574                 DBGUNDO(sk, tp, "Hoe");
1575                 tcp_undo_cwr(tp, 0);
1576                 NET_INC_STATS_BH(TCPPartialUndo);
1577
1578                 /* So... Do not make Hoe's retransmit yet.
1579                  * If the first packet was delayed, the rest
1580                  * ones are most probably delayed as well.
1581                  */
1582                 failed = 0;
1583         }
1584         return failed;
1585 }
1586
1587 /* Undo during loss recovery after partial ACK. */
1588 static int tcp_try_undo_loss(struct sock *sk, struct tcp_opt *tp)
1589 {
1590         if (tcp_may_undo(tp)) {
1591                 struct sk_buff *skb;
1592                 for_retrans_queue(skb, sk, tp) {
1593                         TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
1594                 }
1595                 DBGUNDO(sk, tp, "partial loss");
1596                 tp->lost_out = 0;
1597                 tp->left_out = tp->sacked_out;
1598                 tcp_undo_cwr(tp, 1);
1599                 NET_INC_STATS_BH(TCPLossUndo);
1600                 tp->retransmits = 0;
1601                 tp->undo_marker = 0;
1602                 if (!IsReno(tp))
1603                         tcp_set_ca_state(tp, TCP_CA_Open);
1604                 return 1;
1605         }
1606         return 0;
1607 }
1608
1609 static __inline__ void tcp_complete_cwr(struct tcp_opt *tp)
1610 {
1611         if (tcp_westwood_cwnd(tp)) 
1612                 tp->snd_ssthresh = tp->snd_cwnd;
1613         else
1614                 tp->snd_cwnd = min(tp->snd_cwnd, tp->snd_ssthresh);
1615         tp->snd_cwnd_stamp = tcp_time_stamp;
1616 }
1617
1618 static void tcp_try_to_open(struct sock *sk, struct tcp_opt *tp, int flag)
1619 {
1620         tp->left_out = tp->sacked_out;
1621
1622         if (tp->retrans_out == 0)
1623                 tp->retrans_stamp = 0;
1624
1625         if (flag&FLAG_ECE)
1626                 tcp_enter_cwr(tp);
1627
1628         if (tp->ca_state != TCP_CA_CWR) {
1629                 int state = TCP_CA_Open;
1630
1631                 if (tp->left_out ||
1632                     tp->retrans_out ||
1633                     tp->undo_marker)
1634                         state = TCP_CA_Disorder;
1635
1636                 if (tp->ca_state != state) {
1637                         tcp_set_ca_state(tp, state);
1638                         tp->high_seq = tp->snd_nxt;
1639                 }
1640                 tcp_moderate_cwnd(tp);
1641         } else {
1642                 tcp_cwnd_down(tp);
1643         }
1644 }
1645
1646 /* Process an event, which can update packets-in-flight not trivially.
1647  * Main goal of this function is to calculate new estimate for left_out,
1648  * taking into account both packets sitting in receiver's buffer and
1649  * packets lost by network.
1650  *
1651  * Besides that it does CWND reduction, when packet loss is detected
1652  * and changes state of machine.
1653  *
1654  * It does _not_ decide what to send, it is made in function
1655  * tcp_xmit_retransmit_queue().
1656  */
1657 static void
1658 tcp_fastretrans_alert(struct sock *sk, u32 prior_snd_una,
1659                       int prior_packets, int flag)
1660 {
1661         struct tcp_opt *tp = tcp_sk(sk);
1662         int is_dupack = (tp->snd_una == prior_snd_una && !(flag&FLAG_NOT_DUP));
1663
1664         /* Some technical things:
1665          * 1. Reno does not count dupacks (sacked_out) automatically. */
1666         if (!tp->packets_out)
1667                 tp->sacked_out = 0;
1668         /* 2. SACK counts snd_fack in packets inaccurately. */
1669         if (tp->sacked_out == 0)
1670                 tp->fackets_out = 0;
1671
1672         /* Now state machine starts.
1673          * A. ECE, hence prohibit cwnd undoing, the reduction is required. */
1674         if (flag&FLAG_ECE)
1675                 tp->prior_ssthresh = 0;
1676
1677         /* B. In all the states check for reneging SACKs. */
1678         if (tp->sacked_out && tcp_check_sack_reneging(sk, tp))
1679                 return;
1680
1681         /* C. Process data loss notification, provided it is valid. */
1682         if ((flag&FLAG_DATA_LOST) &&
1683             before(tp->snd_una, tp->high_seq) &&
1684             tp->ca_state != TCP_CA_Open &&
1685             tp->fackets_out > tp->reordering) {
1686                 tcp_mark_head_lost(sk, tp, tp->fackets_out-tp->reordering, tp->high_seq);
1687                 NET_INC_STATS_BH(TCPLoss);
1688         }
1689
1690         /* D. Synchronize left_out to current state. */
1691         tcp_sync_left_out(tp);
1692
1693         /* E. Check state exit conditions. State can be terminated
1694          *    when high_seq is ACKed. */
1695         if (tp->ca_state == TCP_CA_Open) {
1696                 if (!sysctl_tcp_frto)
1697                         BUG_TRAP(tp->retrans_out == 0);
1698                 tp->retrans_stamp = 0;
1699         } else if (!before(tp->snd_una, tp->high_seq)) {
1700                 switch (tp->ca_state) {
1701                 case TCP_CA_Loss:
1702                         tp->retransmits = 0;
1703                         if (tcp_try_undo_recovery(sk, tp))
1704                                 return;
1705                         break;
1706
1707                 case TCP_CA_CWR:
1708                         /* CWR is to be held something *above* high_seq
1709                          * is ACKed for CWR bit to reach receiver. */
1710                         if (tp->snd_una != tp->high_seq) {
1711                                 tcp_complete_cwr(tp);
1712                                 tcp_set_ca_state(tp, TCP_CA_Open);
1713                         }
1714                         break;
1715
1716                 case TCP_CA_Disorder:
1717                         tcp_try_undo_dsack(sk, tp);
1718                         if (!tp->undo_marker ||
1719                             /* For SACK case do not Open to allow to undo
1720                              * catching for all duplicate ACKs. */
1721                             IsReno(tp) || tp->snd_una != tp->high_seq) {
1722                                 tp->undo_marker = 0;
1723                                 tcp_set_ca_state(tp, TCP_CA_Open);
1724                         }
1725                         break;
1726
1727                 case TCP_CA_Recovery:
1728                         if (IsReno(tp))
1729                                 tcp_reset_reno_sack(tp);
1730                         if (tcp_try_undo_recovery(sk, tp))
1731                                 return;
1732                         tcp_complete_cwr(tp);
1733                         break;
1734                 }
1735         }
1736
1737         /* F. Process state. */
1738         switch (tp->ca_state) {
1739         case TCP_CA_Recovery:
1740                 if (prior_snd_una == tp->snd_una) {
1741                         if (IsReno(tp) && is_dupack)
1742                                 tcp_add_reno_sack(tp);
1743                 } else {
1744                         int acked = prior_packets - tp->packets_out;
1745                         if (IsReno(tp))
1746                                 tcp_remove_reno_sacks(sk, tp, acked);
1747                         is_dupack = tcp_try_undo_partial(sk, tp, acked);
1748                 }
1749                 break;
1750         case TCP_CA_Loss:
1751                 if (flag&FLAG_DATA_ACKED)
1752                         tp->retransmits = 0;
1753                 if (!tcp_try_undo_loss(sk, tp)) {
1754                         tcp_moderate_cwnd(tp);
1755                         tcp_xmit_retransmit_queue(sk);
1756                         return;
1757                 }
1758                 if (tp->ca_state != TCP_CA_Open)
1759                         return;
1760                 /* Loss is undone; fall through to processing in Open state. */
1761         default:
1762                 if (IsReno(tp)) {
1763                         if (tp->snd_una != prior_snd_una)
1764                                 tcp_reset_reno_sack(tp);
1765                         if (is_dupack)
1766                                 tcp_add_reno_sack(tp);
1767                 }
1768
1769                 if (tp->ca_state == TCP_CA_Disorder)
1770                         tcp_try_undo_dsack(sk, tp);
1771
1772                 if (!tcp_time_to_recover(sk, tp)) {
1773                         tcp_try_to_open(sk, tp, flag);
1774                         return;
1775                 }
1776
1777                 /* Otherwise enter Recovery state */
1778
1779                 if (IsReno(tp))
1780                         NET_INC_STATS_BH(TCPRenoRecovery);
1781                 else
1782                         NET_INC_STATS_BH(TCPSackRecovery);
1783
1784                 tp->high_seq = tp->snd_nxt;
1785                 tp->prior_ssthresh = 0;
1786                 tp->undo_marker = tp->snd_una;
1787                 tp->undo_retrans = tp->retrans_out;
1788
1789                 if (tp->ca_state < TCP_CA_CWR) {
1790                         if (!(flag&FLAG_ECE))
1791                                 tp->prior_ssthresh = tcp_current_ssthresh(tp);
1792                         tp->snd_ssthresh = tcp_recalc_ssthresh(tp);
1793                         TCP_ECN_queue_cwr(tp);
1794                 }
1795
1796                 tp->snd_cwnd_cnt = 0;
1797                 tcp_set_ca_state(tp, TCP_CA_Recovery);
1798         }
1799
1800         if (is_dupack || tcp_head_timedout(sk, tp))
1801                 tcp_update_scoreboard(sk, tp);
1802         tcp_cwnd_down(tp);
1803         tcp_xmit_retransmit_queue(sk);
1804 }
1805
1806 /* Read draft-ietf-tcplw-high-performance before mucking
1807  * with this code. (Superceeds RFC1323)
1808  */
1809 static void tcp_ack_saw_tstamp(struct tcp_opt *tp, int flag)
1810 {
1811         __u32 seq_rtt;
1812
1813         /* RTTM Rule: A TSecr value received in a segment is used to
1814          * update the averaged RTT measurement only if the segment
1815          * acknowledges some new data, i.e., only if it advances the
1816          * left edge of the send window.
1817          *
1818          * See draft-ietf-tcplw-high-performance-00, section 3.3.
1819          * 1998/04/10 Andrey V. Savochkin <saw@msu.ru>
1820          *
1821          * Changed: reset backoff as soon as we see the first valid sample.
1822          * If we do not, we get strongly overstimated rto. With timestamps
1823          * samples are accepted even from very old segments: f.e., when rtt=1
1824          * increases to 8, we retransmit 5 times and after 8 seconds delayed
1825          * answer arrives rto becomes 120 seconds! If at least one of segments
1826          * in window is lost... Voila.                          --ANK (010210)
1827          */
1828         seq_rtt = tcp_time_stamp - tp->rcv_tsecr;
1829         tcp_rtt_estimator(tp, seq_rtt);
1830         tcp_set_rto(tp);
1831         tp->backoff = 0;
1832         tcp_bound_rto(tp);
1833 }
1834
1835 static void tcp_ack_no_tstamp(struct tcp_opt *tp, u32 seq_rtt, int flag)
1836 {
1837         /* We don't have a timestamp. Can only use
1838          * packets that are not retransmitted to determine
1839          * rtt estimates. Also, we must not reset the
1840          * backoff for rto until we get a non-retransmitted
1841          * packet. This allows us to deal with a situation
1842          * where the network delay has increased suddenly.
1843          * I.e. Karn's algorithm. (SIGCOMM '87, p5.)
1844          */
1845
1846         if (flag & FLAG_RETRANS_DATA_ACKED)
1847                 return;
1848
1849         tcp_rtt_estimator(tp, seq_rtt);
1850         tcp_set_rto(tp);
1851         tp->backoff = 0;
1852         tcp_bound_rto(tp);
1853 }
1854
1855 static __inline__ void
1856 tcp_ack_update_rtt(struct tcp_opt *tp, int flag, s32 seq_rtt)
1857 {
1858         /* Note that peer MAY send zero echo. In this case it is ignored. (rfc1323) */
1859         if (tp->saw_tstamp && tp->rcv_tsecr)
1860                 tcp_ack_saw_tstamp(tp, flag);
1861         else if (seq_rtt >= 0)
1862                 tcp_ack_no_tstamp(tp, seq_rtt, flag);
1863 }
1864
1865 /*
1866  * Compute congestion window to use.
1867  *
1868  * This is from the implementation of BICTCP in
1869  * Lison-Xu, Kahaled Harfoush, and Injog Rhee.
1870  *  "Binary Increase Congestion Control for Fast, Long Distance
1871  *  Networks" in InfoComm 2004
1872  * Available from:
1873  *  http://www.csc.ncsu.edu/faculty/rhee/export/bitcp.pdf
1874  *
1875  * Unless BIC is enabled and congestion window is large
1876  * this behaves the same as the original Reno.
1877  */
1878 static inline __u32 bictcp_cwnd(struct tcp_opt *tp)
1879 {
1880         /* orignal Reno behaviour */
1881         if (!sysctl_tcp_bic)
1882                 return tp->snd_cwnd;
1883
1884         if (tp->bictcp.last_cwnd == tp->snd_cwnd)
1885                 return tp->bictcp.cnt; /*  same cwnd, no update */
1886       
1887         tp->bictcp.last_cwnd = tp->snd_cwnd;
1888       
1889         /* start off normal */
1890         if (tp->snd_cwnd <= sysctl_tcp_bic_low_window)
1891                 tp->bictcp.cnt = tp->snd_cwnd;
1892
1893         /* binary increase */
1894         else if (tp->snd_cwnd < tp->bictcp.last_max_cwnd) {
1895                 __u32   dist = (tp->bictcp.last_max_cwnd - tp->snd_cwnd)
1896                         / BICTCP_B;
1897
1898                 if (dist > BICTCP_MAX_INCREMENT)
1899                         /* linear increase */
1900                         tp->bictcp.cnt = tp->snd_cwnd / BICTCP_MAX_INCREMENT;
1901                 else if (dist <= 1U)
1902                         /* binary search increase */
1903                         tp->bictcp.cnt = tp->snd_cwnd * BICTCP_FUNC_OF_MIN_INCR
1904                                 / BICTCP_B;
1905                 else
1906                         /* binary search increase */
1907                         tp->bictcp.cnt = tp->snd_cwnd / dist;
1908         } else {
1909                 /* slow start amd linear increase */
1910                 if (tp->snd_cwnd < tp->bictcp.last_max_cwnd + BICTCP_B)
1911                         /* slow start */
1912                         tp->bictcp.cnt = tp->snd_cwnd * BICTCP_FUNC_OF_MIN_INCR
1913                                 / BICTCP_B;
1914                 else if (tp->snd_cwnd < tp->bictcp.last_max_cwnd
1915                                         + BICTCP_MAX_INCREMENT*(BICTCP_B-1))
1916                         /* slow start */
1917                         tp->bictcp.cnt = tp->snd_cwnd * (BICTCP_B-1)
1918                                 / (tp->snd_cwnd-tp->bictcp.last_max_cwnd);
1919                 else
1920                         /* linear increase */
1921                         tp->bictcp.cnt = tp->snd_cwnd / BICTCP_MAX_INCREMENT;
1922         }
1923         return tp->bictcp.cnt;
1924 }
1925
1926 /* This is Jacobson's slow start and congestion avoidance. 
1927  * SIGCOMM '88, p. 328.
1928  */
1929 static __inline__ void reno_cong_avoid(struct tcp_opt *tp)
1930 {
1931         if (tp->snd_cwnd <= tp->snd_ssthresh) {
1932                 /* In "safe" area, increase. */
1933                 if (tp->snd_cwnd < tp->snd_cwnd_clamp)
1934                         tp->snd_cwnd++;
1935         } else {
1936                 /* In dangerous area, increase slowly.
1937                  * In theory this is tp->snd_cwnd += 1 / tp->snd_cwnd
1938                  */
1939                 if (tp->snd_cwnd_cnt >= bictcp_cwnd(tp)) {
1940                         if (tp->snd_cwnd < tp->snd_cwnd_clamp)
1941                                 tp->snd_cwnd++;
1942                         tp->snd_cwnd_cnt=0;
1943                 } else
1944                         tp->snd_cwnd_cnt++;
1945         }
1946         tp->snd_cwnd_stamp = tcp_time_stamp;
1947 }
1948
1949 /* This is based on the congestion detection/avoidance scheme described in
1950  *    Lawrence S. Brakmo and Larry L. Peterson.
1951  *    "TCP Vegas: End to end congestion avoidance on a global internet."
1952  *    IEEE Journal on Selected Areas in Communication, 13(8):1465--1480,
1953  *    October 1995. Available from:
1954  *      ftp://ftp.cs.arizona.edu/xkernel/Papers/jsac.ps
1955  *
1956  * See http://www.cs.arizona.edu/xkernel/ for their implementation.
1957  * The main aspects that distinguish this implementation from the
1958  * Arizona Vegas implementation are:
1959  *   o We do not change the loss detection or recovery mechanisms of
1960  *     Linux in any way. Linux already recovers from losses quite well,
1961  *     using fine-grained timers, NewReno, and FACK.
1962  *   o To avoid the performance penalty imposed by increasing cwnd
1963  *     only every-other RTT during slow start, we increase during
1964  *     every RTT during slow start, just like Reno.
1965  *   o Largely to allow continuous cwnd growth during slow start,
1966  *     we use the rate at which ACKs come back as the "actual"
1967  *     rate, rather than the rate at which data is sent.
1968  *   o To speed convergence to the right rate, we set the cwnd
1969  *     to achieve the right ("actual") rate when we exit slow start.
1970  *   o To filter out the noise caused by delayed ACKs, we use the
1971  *     minimum RTT sample observed during the last RTT to calculate
1972  *     the actual rate.
1973  *   o When the sender re-starts from idle, it waits until it has
1974  *     received ACKs for an entire flight of new data before making
1975  *     a cwnd adjustment decision. The original Vegas implementation
1976  *     assumed senders never went idle.
1977  */
1978 static void vegas_cong_avoid(struct tcp_opt *tp, u32 ack, u32 seq_rtt)
1979 {
1980         /* The key players are v_beg_snd_una and v_beg_snd_nxt.
1981          *
1982          * These are so named because they represent the approximate values
1983          * of snd_una and snd_nxt at the beginning of the current RTT. More
1984          * precisely, they represent the amount of data sent during the RTT.
1985          * At the end of the RTT, when we receive an ACK for v_beg_snd_nxt,
1986          * we will calculate that (v_beg_snd_nxt - v_beg_snd_una) outstanding
1987          * bytes of data have been ACKed during the course of the RTT, giving
1988          * an "actual" rate of:
1989          *
1990          *     (v_beg_snd_nxt - v_beg_snd_una) / (rtt duration)
1991          *
1992          * Unfortunately, v_beg_snd_una is not exactly equal to snd_una,
1993          * because delayed ACKs can cover more than one segment, so they
1994          * don't line up nicely with the boundaries of RTTs.
1995          *
1996          * Another unfortunate fact of life is that delayed ACKs delay the
1997          * advance of the left edge of our send window, so that the number
1998          * of bytes we send in an RTT is often less than our cwnd will allow.
1999          * So we keep track of our cwnd separately, in v_beg_snd_cwnd.
2000          */
2001
2002         if (after(ack, tp->vegas.beg_snd_nxt)) {
2003                 /* Do the Vegas once-per-RTT cwnd adjustment. */
2004                 u32 old_wnd, old_snd_cwnd;
2005
2006                 
2007                 /* Here old_wnd is essentially the window of data that was
2008                  * sent during the previous RTT, and has all
2009                  * been acknowledged in the course of the RTT that ended
2010                  * with the ACK we just received. Likewise, old_snd_cwnd
2011                  * is the cwnd during the previous RTT.
2012                  */
2013                 old_wnd = (tp->vegas.beg_snd_nxt - tp->vegas.beg_snd_una) /
2014                         tp->mss_cache;
2015                 old_snd_cwnd = tp->vegas.beg_snd_cwnd;
2016
2017                 /* Save the extent of the current window so we can use this
2018                  * at the end of the next RTT.
2019                  */
2020                 tp->vegas.beg_snd_una  = tp->vegas.beg_snd_nxt;
2021                 tp->vegas.beg_snd_nxt  = tp->snd_nxt;
2022                 tp->vegas.beg_snd_cwnd = tp->snd_cwnd;
2023
2024                 /* Take into account the current RTT sample too, to
2025                  * decrease the impact of delayed acks. This double counts
2026                  * this sample since we count it for the next window as well,
2027                  * but that's not too awful, since we're taking the min,
2028                  * rather than averaging.
2029                  */
2030                 vegas_rtt_calc(tp, seq_rtt);
2031
2032                 /* We do the Vegas calculations only if we got enough RTT
2033                  * samples that we can be reasonably sure that we got
2034                  * at least one RTT sample that wasn't from a delayed ACK.
2035                  * If we only had 2 samples total,
2036                  * then that means we're getting only 1 ACK per RTT, which
2037                  * means they're almost certainly delayed ACKs.
2038                  * If  we have 3 samples, we should be OK.
2039                  */
2040
2041                 if (tp->vegas.cntRTT <= 2) {
2042                         /* We don't have enough RTT samples to do the Vegas
2043                          * calculation, so we'll behave like Reno.
2044                          */
2045                         if (tp->snd_cwnd > tp->snd_ssthresh)
2046                                 tp->snd_cwnd++;
2047                 } else {
2048                         u32 rtt, target_cwnd, diff;
2049
2050                         /* We have enough RTT samples, so, using the Vegas
2051                          * algorithm, we determine if we should increase or
2052                          * decrease cwnd, and by how much.
2053                          */
2054
2055                         /* Pluck out the RTT we are using for the Vegas
2056                          * calculations. This is the min RTT seen during the
2057                          * last RTT. Taking the min filters out the effects
2058                          * of delayed ACKs, at the cost of noticing congestion
2059                          * a bit later.
2060                          */
2061                         rtt = tp->vegas.minRTT;
2062
2063                         /* Calculate the cwnd we should have, if we weren't
2064                          * going too fast.
2065                          *
2066                          * This is:
2067                          *     (actual rate in segments) * baseRTT
2068                          * We keep it as a fixed point number with
2069                          * V_PARAM_SHIFT bits to the right of the binary point.
2070                          */
2071                         target_cwnd = ((old_wnd * tp->vegas.baseRTT)
2072                                        << V_PARAM_SHIFT) / rtt;
2073
2074                         /* Calculate the difference between the window we had,
2075                          * and the window we would like to have. This quantity
2076                          * is the "Diff" from the Arizona Vegas papers.
2077                          *
2078                          * Again, this is a fixed point number with
2079                          * V_PARAM_SHIFT bits to the right of the binary
2080                          * point.
2081                          */
2082                         diff = (old_wnd << V_PARAM_SHIFT) - target_cwnd;
2083
2084                         if (tp->snd_cwnd < tp->snd_ssthresh) {
2085                                 /* Slow start.  */
2086                                 if (diff > sysctl_tcp_vegas_gamma) {
2087                                         /* Going too fast. Time to slow down
2088                                          * and switch to congestion avoidance.
2089                                          */
2090                                         tp->snd_ssthresh = 2;
2091
2092                                         /* Set cwnd to match the actual rate
2093                                          * exactly:
2094                                          *   cwnd = (actual rate) * baseRTT
2095                                          * Then we add 1 because the integer
2096                                          * truncation robs us of full link
2097                                          * utilization.
2098                                          */
2099                                         tp->snd_cwnd = min(tp->snd_cwnd,
2100                                                            (target_cwnd >>
2101                                                             V_PARAM_SHIFT)+1);
2102
2103                                 }
2104                         } else {
2105                                 /* Congestion avoidance. */
2106                                 u32 next_snd_cwnd;
2107
2108                                 /* Figure out where we would like cwnd
2109                                  * to be.
2110                                  */
2111                                 if (diff > sysctl_tcp_vegas_beta) {
2112                                         /* The old window was too fast, so
2113                                          * we slow down.
2114                                          */
2115                                         next_snd_cwnd = old_snd_cwnd - 1;
2116                                 } else if (diff < sysctl_tcp_vegas_alpha) {
2117                                         /* We don't have enough extra packets
2118                                          * in the network, so speed up.
2119                                          */
2120                                         next_snd_cwnd = old_snd_cwnd + 1;
2121                                 } else {
2122                                         /* Sending just as fast as we
2123                                          * should be.
2124                                          */
2125                                         next_snd_cwnd = old_snd_cwnd;
2126                                 }
2127
2128                                 /* Adjust cwnd upward or downward, toward the
2129                                  * desired value.
2130                                  */
2131                                 if (next_snd_cwnd > tp->snd_cwnd)
2132                                         tp->snd_cwnd++;
2133                                 else if (next_snd_cwnd < tp->snd_cwnd)
2134                                         tp->snd_cwnd--;
2135                         }
2136                 }
2137
2138                 /* Wipe the slate clean for the next RTT. */
2139                 tp->vegas.cntRTT = 0;
2140                 tp->vegas.minRTT = 0x7fffffff;
2141         }
2142
2143         /* The following code is executed for every ack we receive,
2144          * except for conditions checked in should_advance_cwnd()
2145          * before the call to tcp_cong_avoid(). Mainly this means that
2146          * we only execute this code if the ack actually acked some
2147          * data.
2148          */
2149
2150         /* If we are in slow start, increase our cwnd in response to this ACK.
2151          * (If we are not in slow start then we are in congestion avoidance,
2152          * and adjust our congestion window only once per RTT. See the code
2153          * above.)
2154          */
2155         if (tp->snd_cwnd <= tp->snd_ssthresh) 
2156                 tp->snd_cwnd++;
2157
2158         /* to keep cwnd from growing without bound */
2159         tp->snd_cwnd = min_t(u32, tp->snd_cwnd, tp->snd_cwnd_clamp);
2160
2161         /* Make sure that we are never so timid as to reduce our cwnd below
2162          * 2 MSS.
2163          *
2164          * Going below 2 MSS would risk huge delayed ACKs from our receiver.
2165          */
2166         tp->snd_cwnd = max(tp->snd_cwnd, 2U);
2167
2168         tp->snd_cwnd_stamp = tcp_time_stamp;
2169 }
2170
2171 static inline void tcp_cong_avoid(struct tcp_opt *tp, u32 ack, u32 seq_rtt)
2172 {
2173         if (tcp_vegas_enabled(tp))
2174                 vegas_cong_avoid(tp, ack, seq_rtt);
2175         else
2176                 reno_cong_avoid(tp);
2177 }
2178
2179 /* Restart timer after forward progress on connection.
2180  * RFC2988 recommends to restart timer to now+rto.
2181  */
2182
2183 static __inline__ void tcp_ack_packets_out(struct sock *sk, struct tcp_opt *tp)
2184 {
2185         if (tp->packets_out==0) {
2186                 tcp_clear_xmit_timer(sk, TCP_TIME_RETRANS);
2187         } else {
2188                 tcp_reset_xmit_timer(sk, TCP_TIME_RETRANS, tp->rto);
2189         }
2190 }
2191
2192 /* Remove acknowledged frames from the retransmission queue. */
2193 static int tcp_clean_rtx_queue(struct sock *sk, __s32 *seq_rtt_p)
2194 {
2195         struct tcp_opt *tp = tcp_sk(sk);
2196         struct sk_buff *skb;
2197         __u32 now = tcp_time_stamp;
2198         int acked = 0;
2199         __s32 seq_rtt = -1;
2200
2201         while ((skb = skb_peek(&sk->sk_write_queue)) && skb != tp->send_head) {
2202                 struct tcp_skb_cb *scb = TCP_SKB_CB(skb); 
2203                 __u8 sacked = scb->sacked;
2204
2205                 /* If our packet is before the ack sequence we can
2206                  * discard it as it's confirmed to have arrived at
2207                  * the other end.
2208                  */
2209                 if (after(scb->end_seq, tp->snd_una))
2210                         break;
2211
2212                 /* Initial outgoing SYN's get put onto the write_queue
2213                  * just like anything else we transmit.  It is not
2214                  * true data, and if we misinform our callers that
2215                  * this ACK acks real data, we will erroneously exit
2216                  * connection startup slow start one packet too
2217                  * quickly.  This is severely frowned upon behavior.
2218                  */
2219                 if(!(scb->flags & TCPCB_FLAG_SYN)) {
2220                         acked |= FLAG_DATA_ACKED;
2221                 } else {
2222                         acked |= FLAG_SYN_ACKED;
2223                         tp->retrans_stamp = 0;
2224                 }
2225
2226                 if (sacked) {
2227                         if(sacked & TCPCB_RETRANS) {
2228                                 if(sacked & TCPCB_SACKED_RETRANS)
2229                                         tp->retrans_out--;
2230                                 acked |= FLAG_RETRANS_DATA_ACKED;
2231                                 seq_rtt = -1;
2232                         } else if (seq_rtt < 0)
2233                                 seq_rtt = now - scb->when;
2234                         if(sacked & TCPCB_SACKED_ACKED)
2235                                 tp->sacked_out--;
2236                         if(sacked & TCPCB_LOST)
2237                                 tp->lost_out--;
2238                         if(sacked & TCPCB_URG) {
2239                                 if (tp->urg_mode &&
2240                                     !before(scb->end_seq, tp->snd_up))
2241                                         tp->urg_mode = 0;
2242                         }
2243                 } else if (seq_rtt < 0)
2244                         seq_rtt = now - scb->when;
2245                 if (tp->fackets_out)
2246                         tp->fackets_out--;
2247                 tp->packets_out--;
2248                 __skb_unlink(skb, skb->list);
2249                 tcp_free_skb(sk, skb);
2250         }
2251
2252         if (acked&FLAG_ACKED) {
2253                 tcp_ack_update_rtt(tp, acked, seq_rtt);
2254                 tcp_ack_packets_out(sk, tp);
2255         }
2256
2257 #if FASTRETRANS_DEBUG > 0
2258         BUG_TRAP((int)tp->sacked_out >= 0);
2259         BUG_TRAP((int)tp->lost_out >= 0);
2260         BUG_TRAP((int)tp->retrans_out >= 0);
2261         if (!tp->packets_out && tp->sack_ok) {
2262                 if (tp->lost_out) {
2263                         printk(KERN_DEBUG "Leak l=%u %d\n", tp->lost_out,
2264                                                             tp->ca_state);
2265                         tp->lost_out = 0;
2266                 }
2267                 if (tp->sacked_out) {
2268                         printk(KERN_DEBUG "Leak s=%u %d\n", tp->sacked_out,
2269                                                             tp->ca_state);
2270                         tp->sacked_out = 0;
2271                 }
2272                 if (tp->retrans_out) {
2273                         printk(KERN_DEBUG "Leak r=%u %d\n", tp->retrans_out,
2274                                                             tp->ca_state);
2275                         tp->retrans_out = 0;
2276                 }
2277         }
2278 #endif
2279         *seq_rtt_p = seq_rtt;
2280         return acked;
2281 }
2282
2283 static void tcp_ack_probe(struct sock *sk)
2284 {
2285         struct tcp_opt *tp = tcp_sk(sk);
2286
2287         /* Was it a usable window open? */
2288
2289         if (!after(TCP_SKB_CB(tp->send_head)->end_seq,
2290                    tp->snd_una + tp->snd_wnd)) {
2291                 tp->backoff = 0;
2292                 tcp_clear_xmit_timer(sk, TCP_TIME_PROBE0);
2293                 /* Socket must be waked up by subsequent tcp_data_snd_check().
2294                  * This function is not for random using!
2295                  */
2296         } else {
2297                 tcp_reset_xmit_timer(sk, TCP_TIME_PROBE0,
2298                                      min(tp->rto << tp->backoff, TCP_RTO_MAX));
2299         }
2300 }
2301
2302 static __inline__ int tcp_ack_is_dubious(struct tcp_opt *tp, int flag)
2303 {
2304         return (!(flag & FLAG_NOT_DUP) || (flag & FLAG_CA_ALERT) ||
2305                 tp->ca_state != TCP_CA_Open);
2306 }
2307
2308 static __inline__ int tcp_may_raise_cwnd(struct tcp_opt *tp, int flag)
2309 {
2310         return (!(flag & FLAG_ECE) || tp->snd_cwnd < tp->snd_ssthresh) &&
2311                 !((1<<tp->ca_state)&(TCPF_CA_Recovery|TCPF_CA_CWR));
2312 }
2313
2314 /* Check that window update is acceptable.
2315  * The function assumes that snd_una<=ack<=snd_next.
2316  */
2317 static __inline__ int
2318 tcp_may_update_window(struct tcp_opt *tp, u32 ack, u32 ack_seq, u32 nwin)
2319 {
2320         return (after(ack, tp->snd_una) ||
2321                 after(ack_seq, tp->snd_wl1) ||
2322                 (ack_seq == tp->snd_wl1 && nwin > tp->snd_wnd));
2323 }
2324
2325 /* Update our send window.
2326  *
2327  * Window update algorithm, described in RFC793/RFC1122 (used in linux-2.2
2328  * and in FreeBSD. NetBSD's one is even worse.) is wrong.
2329  */
2330 static int tcp_ack_update_window(struct sock *sk, struct tcp_opt *tp,
2331                                  struct sk_buff *skb, u32 ack, u32 ack_seq)
2332 {
2333         int flag = 0;
2334         u32 nwin = ntohs(skb->h.th->window);
2335
2336         if (likely(!skb->h.th->syn))
2337                 nwin <<= tp->snd_wscale;
2338
2339         if (tcp_may_update_window(tp, ack, ack_seq, nwin)) {
2340                 flag |= FLAG_WIN_UPDATE;
2341                 tcp_update_wl(tp, ack, ack_seq);
2342
2343                 if (tp->snd_wnd != nwin) {
2344                         tp->snd_wnd = nwin;
2345
2346                         /* Note, it is the only place, where
2347                          * fast path is recovered for sending TCP.
2348                          */
2349                         tcp_fast_path_check(sk, tp);
2350
2351                         if (nwin > tp->max_window) {
2352                                 tp->max_window = nwin;
2353                                 tcp_sync_mss(sk, tp->pmtu_cookie);
2354                         }
2355                 }
2356         }
2357
2358         tp->snd_una = ack;
2359
2360         return flag;
2361 }
2362
2363 static void tcp_process_frto(struct sock *sk, u32 prior_snd_una)
2364 {
2365         struct tcp_opt *tp = tcp_sk(sk);
2366         
2367         tcp_sync_left_out(tp);
2368         
2369         if (tp->snd_una == prior_snd_una ||
2370             !before(tp->snd_una, tp->frto_highmark)) {
2371                 /* RTO was caused by loss, start retransmitting in
2372                  * go-back-N slow start
2373                  */
2374                 tcp_enter_frto_loss(sk);
2375                 return;
2376         }
2377
2378         if (tp->frto_counter == 1) {
2379                 /* First ACK after RTO advances the window: allow two new
2380                  * segments out.
2381                  */
2382                 tp->snd_cwnd = tcp_packets_in_flight(tp) + 2;
2383         } else {
2384                 /* Also the second ACK after RTO advances the window.
2385                  * The RTO was likely spurious. Reduce cwnd and continue
2386                  * in congestion avoidance
2387                  */
2388                 tp->snd_cwnd = min(tp->snd_cwnd, tp->snd_ssthresh);
2389                 tcp_moderate_cwnd(tp);
2390         }
2391
2392         /* F-RTO affects on two new ACKs following RTO.
2393          * At latest on third ACK the TCP behavor is back to normal.
2394          */
2395         tp->frto_counter = (tp->frto_counter + 1) % 3;
2396 }
2397
2398 /*
2399  * TCP Westwood+
2400  */
2401
2402 /*
2403  * @init_westwood
2404  * This function initializes fields used in TCP Westwood+. We can't
2405  * get no information about RTTmin at this time so we simply set it to
2406  * TCP_WESTWOOD_INIT_RTT. This value was chosen to be too conservative
2407  * since in this way we're sure it will be updated in a consistent
2408  * way as soon as possible. It will reasonably happen within the first
2409  * RTT period of the connection lifetime.
2410  */
2411
2412 static void init_westwood(struct sock *sk)
2413 {
2414         struct tcp_opt *tp = tcp_sk(sk);
2415
2416         tp->westwood.bw_ns_est = 0;
2417         tp->westwood.bw_est = 0;
2418         tp->westwood.accounted = 0;
2419         tp->westwood.cumul_ack = 0;
2420         tp->westwood.rtt_win_sx = tcp_time_stamp;
2421         tp->westwood.rtt = TCP_WESTWOOD_INIT_RTT;
2422         tp->westwood.rtt_min = TCP_WESTWOOD_INIT_RTT;
2423         tp->westwood.snd_una = tp->snd_una;
2424 }
2425
2426 /*
2427  * @westwood_do_filter
2428  * Low-pass filter. Implemented using constant coeffients.
2429  */
2430
2431 static inline __u32 westwood_do_filter(__u32 a, __u32 b)
2432 {
2433         return (((7 * a) + b) >> 3);
2434 }
2435
2436 static void westwood_filter(struct sock *sk, __u32 delta)
2437 {
2438         struct tcp_opt *tp = tcp_sk(sk);
2439
2440         tp->westwood.bw_ns_est =
2441                 westwood_do_filter(tp->westwood.bw_ns_est, 
2442                                    tp->westwood.bk / delta);
2443         tp->westwood.bw_est =
2444                 westwood_do_filter(tp->westwood.bw_est,
2445                                    tp->westwood.bw_ns_est);
2446 }
2447
2448 /* 
2449  * @westwood_update_rttmin
2450  * It is used to update RTTmin. In this case we MUST NOT use
2451  * WESTWOOD_RTT_MIN minimum bound since we could be on a LAN!
2452  */
2453
2454 static inline __u32 westwood_update_rttmin(struct sock *sk)
2455 {
2456         struct tcp_opt *tp = tcp_sk(sk);
2457         __u32 rttmin = tp->westwood.rtt_min;
2458
2459         if (tp->westwood.rtt == 0)
2460                 return(rttmin);
2461
2462         if (tp->westwood.rtt < tp->westwood.rtt_min || !rttmin)
2463                 rttmin = tp->westwood.rtt;
2464
2465         return(rttmin);
2466 }
2467
2468 /*
2469  * @westwood_acked
2470  * Evaluate increases for dk. 
2471  */
2472
2473 static inline __u32 westwood_acked(struct sock *sk)
2474 {
2475         struct tcp_opt *tp = tcp_sk(sk);
2476
2477         return ((tp->snd_una) - (tp->westwood.snd_una));
2478 }
2479
2480 /*
2481  * @westwood_new_window
2482  * It evaluates if we are receiving data inside the same RTT window as
2483  * when we started.
2484  * Return value:
2485  * It returns 0 if we are still evaluating samples in the same RTT
2486  * window, 1 if the sample has to be considered in the next window.
2487  */
2488
2489 static int westwood_new_window(struct sock *sk)
2490 {
2491         struct tcp_opt *tp = tcp_sk(sk);
2492         __u32 left_bound;
2493         __u32 rtt;
2494         int ret = 0;
2495
2496         left_bound = tp->westwood.rtt_win_sx;
2497         rtt = max(tp->westwood.rtt, (u32) TCP_WESTWOOD_RTT_MIN);
2498
2499         /*
2500          * A RTT-window has passed. Be careful since if RTT is less than
2501          * 50ms we don't filter but we continue 'building the sample'.
2502          * This minimum limit was choosen since an estimation on small
2503          * time intervals is better to avoid...
2504          * Obvioulsy on a LAN we reasonably will always have
2505          * right_bound = left_bound + WESTWOOD_RTT_MIN
2506          */
2507
2508         if ((left_bound + rtt) < tcp_time_stamp)
2509                 ret = 1;
2510
2511         return ret;
2512 }
2513
2514 /*
2515  * @westwood_update_window
2516  * It updates RTT evaluation window if it is the right moment to do
2517  * it. If so it calls filter for evaluating bandwidth. 
2518  */
2519
2520 static void __westwood_update_window(struct sock *sk, __u32 now)
2521 {
2522         struct tcp_opt *tp = tcp_sk(sk);
2523         __u32 delta = now - tp->westwood.rtt_win_sx;
2524
2525         if (!delta)
2526                 return;
2527
2528         if (tp->westwood.rtt)
2529                 westwood_filter(sk, delta);
2530
2531         tp->westwood.bk = 0;
2532         tp->westwood.rtt_win_sx = tcp_time_stamp;
2533 }
2534
2535
2536 static void westwood_update_window(struct sock *sk, __u32 now)
2537 {
2538         if (westwood_new_window(sk)) 
2539                 __westwood_update_window(sk, now);
2540 }
2541
2542 /*
2543  * @__tcp_westwood_fast_bw
2544  * It is called when we are in fast path. In particular it is called when
2545  * header prediction is successfull. In such case infact update is
2546  * straight forward and doesn't need any particular care.
2547  */
2548
2549 void __tcp_westwood_fast_bw(struct sock *sk, struct sk_buff *skb)
2550 {
2551         struct tcp_opt *tp = tcp_sk(sk);
2552
2553         westwood_update_window(sk, tcp_time_stamp);
2554
2555         tp->westwood.bk += westwood_acked(sk);
2556         tp->westwood.snd_una = tp->snd_una;
2557         tp->westwood.rtt_min = westwood_update_rttmin(sk);
2558 }
2559
2560
2561 /*
2562  * @westwood_dupack_update
2563  * It updates accounted and cumul_ack when receiving a dupack.
2564  */
2565
2566 static void westwood_dupack_update(struct sock *sk)
2567 {
2568         struct tcp_opt *tp = tcp_sk(sk);
2569
2570         tp->westwood.accounted += tp->mss_cache;
2571         tp->westwood.cumul_ack = tp->mss_cache;
2572 }
2573
2574 static inline int westwood_may_change_cumul(struct tcp_opt *tp)
2575 {
2576         return ((tp->westwood.cumul_ack) > tp->mss_cache);
2577 }
2578
2579 static inline void westwood_partial_update(struct tcp_opt *tp)
2580 {
2581         tp->westwood.accounted -= tp->westwood.cumul_ack;
2582         tp->westwood.cumul_ack = tp->mss_cache;
2583 }
2584
2585 static inline void westwood_complete_update(struct tcp_opt *tp)
2586 {
2587         tp->westwood.cumul_ack -= tp->westwood.accounted;
2588         tp->westwood.accounted = 0;
2589 }
2590
2591 /*
2592  * @westwood_acked_count
2593  * This function evaluates cumul_ack for evaluating dk in case of
2594  * delayed or partial acks.
2595  */
2596
2597 static __u32 westwood_acked_count(struct sock *sk)
2598 {
2599         struct tcp_opt *tp = tcp_sk(sk);
2600
2601         tp->westwood.cumul_ack = westwood_acked(sk);
2602
2603         /* If cumul_ack is 0 this is a dupack since it's not moving
2604          * tp->snd_una.
2605          */
2606         if (!(tp->westwood.cumul_ack))
2607                 westwood_dupack_update(sk);
2608
2609         if (westwood_may_change_cumul(tp)) {
2610                 /* Partial or delayed ack */
2611                 if ((tp->westwood.accounted) >= (tp->westwood.cumul_ack))
2612                         westwood_partial_update(tp);
2613                 else
2614                         westwood_complete_update(tp);
2615         }
2616
2617         tp->westwood.snd_una = tp->snd_una;
2618
2619         return tp->westwood.cumul_ack;
2620 }
2621
2622
2623 /*
2624  * @__tcp_westwood_slow_bw
2625  * It is called when something is going wrong..even if there could
2626  * be no problems! Infact a simple delayed packet may trigger a
2627  * dupack. But we need to be careful in such case.
2628  */
2629
2630 void __tcp_westwood_slow_bw(struct sock *sk, struct sk_buff *skb)
2631 {
2632         struct tcp_opt *tp = tcp_sk(sk);
2633
2634         westwood_update_window(sk, tcp_time_stamp);
2635
2636         tp->westwood.bk += westwood_acked_count(sk);
2637         tp->westwood.rtt_min = westwood_update_rttmin(sk);
2638 }
2639
2640 /* This routine deals with incoming acks, but not outgoing ones. */
2641 static int tcp_ack(struct sock *sk, struct sk_buff *skb, int flag)
2642 {
2643         struct tcp_opt *tp = tcp_sk(sk);
2644         u32 prior_snd_una = tp->snd_una;
2645         u32 ack_seq = TCP_SKB_CB(skb)->seq;
2646         u32 ack = TCP_SKB_CB(skb)->ack_seq;
2647         u32 prior_in_flight;
2648         s32 seq_rtt;
2649         int prior_packets;
2650
2651         /* If the ack is newer than sent or older than previous acks
2652          * then we can probably ignore it.
2653          */
2654         if (after(ack, tp->snd_nxt))
2655                 goto uninteresting_ack;
2656
2657         if (before(ack, prior_snd_una))
2658                 goto old_ack;
2659
2660         if (!(flag&FLAG_SLOWPATH) && after(ack, prior_snd_una)) {
2661                 /* Window is constant, pure forward advance.
2662                  * No more checks are required.
2663                  * Note, we use the fact that SND.UNA>=SND.WL2.
2664                  */
2665                 tcp_update_wl(tp, ack, ack_seq);
2666                 tp->snd_una = ack;
2667                 tcp_westwood_fast_bw(sk, skb);
2668                 flag |= FLAG_WIN_UPDATE;
2669
2670                 NET_INC_STATS_BH(TCPHPAcks);
2671         } else {
2672                 if (ack_seq != TCP_SKB_CB(skb)->end_seq)
2673                         flag |= FLAG_DATA;
2674                 else
2675                         NET_INC_STATS_BH(TCPPureAcks);
2676
2677                 flag |= tcp_ack_update_window(sk, tp, skb, ack, ack_seq);
2678
2679                 if (TCP_SKB_CB(skb)->sacked)
2680                         flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una);
2681
2682                 if (TCP_ECN_rcv_ecn_echo(tp, skb->h.th))
2683                         flag |= FLAG_ECE;
2684
2685                 tcp_westwood_slow_bw(sk,skb);
2686         }
2687
2688         /* We passed data and got it acked, remove any soft error
2689          * log. Something worked...
2690          */
2691         sk->sk_err_soft = 0;
2692         tp->rcv_tstamp = tcp_time_stamp;
2693         prior_packets = tp->packets_out;
2694         if (!prior_packets)
2695                 goto no_queue;
2696
2697         prior_in_flight = tcp_packets_in_flight(tp);
2698
2699         /* See if we can take anything off of the retransmit queue. */
2700         flag |= tcp_clean_rtx_queue(sk, &seq_rtt);
2701
2702         if (tp->frto_counter)
2703                 tcp_process_frto(sk, prior_snd_una);
2704
2705         if (tcp_ack_is_dubious(tp, flag)) {
2706                 /* Advanve CWND, if state allows this. */
2707                 if ((flag & FLAG_DATA_ACKED) &&
2708                     (tcp_vegas_enabled(tp) || prior_in_flight >= tp->snd_cwnd) &&
2709                     tcp_may_raise_cwnd(tp, flag))
2710                         tcp_cong_avoid(tp, ack, seq_rtt);
2711                 tcp_fastretrans_alert(sk, prior_snd_una, prior_packets, flag);
2712         } else {
2713                 if ((flag & FLAG_DATA_ACKED) && 
2714                     (tcp_vegas_enabled(tp) || prior_in_flight >= tp->snd_cwnd))
2715                         tcp_cong_avoid(tp, ack, seq_rtt);
2716         }
2717
2718         if ((flag & FLAG_FORWARD_PROGRESS) || !(flag&FLAG_NOT_DUP))
2719                 dst_confirm(sk->sk_dst_cache);
2720
2721         return 1;
2722
2723 no_queue:
2724         tp->probes_out = 0;
2725
2726         /* If this ack opens up a zero window, clear backoff.  It was
2727          * being used to time the probes, and is probably far higher than
2728          * it needs to be for normal retransmission.
2729          */
2730         if (tp->send_head)
2731                 tcp_ack_probe(sk);
2732         return 1;
2733
2734 old_ack:
2735         if (TCP_SKB_CB(skb)->sacked)
2736                 tcp_sacktag_write_queue(sk, skb, prior_snd_una);
2737
2738 uninteresting_ack:
2739         SOCK_DEBUG(sk, "Ack %u out of %u:%u\n", ack, tp->snd_una, tp->snd_nxt);
2740         return 0;
2741 }
2742
2743
2744 /* Look for tcp options. Normally only called on SYN and SYNACK packets.
2745  * But, this can also be called on packets in the established flow when
2746  * the fast version below fails.
2747  */
2748 void tcp_parse_options(struct sk_buff *skb, struct tcp_opt *tp, int estab)
2749 {
2750         unsigned char *ptr;
2751         struct tcphdr *th = skb->h.th;
2752         int length=(th->doff*4)-sizeof(struct tcphdr);
2753
2754         ptr = (unsigned char *)(th + 1);
2755         tp->saw_tstamp = 0;
2756
2757         while(length>0) {
2758                 int opcode=*ptr++;
2759                 int opsize;
2760
2761                 switch (opcode) {
2762                         case TCPOPT_EOL:
2763                                 return;
2764                         case TCPOPT_NOP:        /* Ref: RFC 793 section 3.1 */
2765                                 length--;
2766                                 continue;
2767                         default:
2768                                 opsize=*ptr++;
2769                                 if (opsize < 2) /* "silly options" */
2770                                         return;
2771                                 if (opsize > length)
2772                                         return; /* don't parse partial options */
2773                                 switch(opcode) {
2774                                 case TCPOPT_MSS:
2775                                         if(opsize==TCPOLEN_MSS && th->syn && !estab) {
2776                                                 u16 in_mss = ntohs(*(__u16 *)ptr);
2777                                                 if (in_mss) {
2778                                                         if (tp->user_mss && tp->user_mss < in_mss)
2779                                                                 in_mss = tp->user_mss;
2780                                                         tp->mss_clamp = in_mss;
2781                                                 }
2782                                         }
2783                                         break;
2784                                 case TCPOPT_WINDOW:
2785                                         if(opsize==TCPOLEN_WINDOW && th->syn && !estab)
2786                                                 if (sysctl_tcp_window_scaling) {
2787                                                         tp->wscale_ok = 1;
2788                                                         tp->snd_wscale = *(__u8 *)ptr;
2789                                                         if(tp->snd_wscale > 14) {
2790                                                                 if(net_ratelimit())
2791                                                                         printk("tcp_parse_options: Illegal window "
2792                                                                                "scaling value %d >14 received.",
2793                                                                                tp->snd_wscale);
2794                                                                 tp->snd_wscale = 14;
2795                                                         }
2796                                                 }
2797                                         break;
2798                                 case TCPOPT_TIMESTAMP:
2799                                         if(opsize==TCPOLEN_TIMESTAMP) {
2800                                                 if ((estab && tp->tstamp_ok) ||
2801                                                     (!estab && sysctl_tcp_timestamps)) {
2802                                                         tp->saw_tstamp = 1;
2803                                                         tp->rcv_tsval = ntohl(*(__u32 *)ptr);
2804                                                         tp->rcv_tsecr = ntohl(*(__u32 *)(ptr+4));
2805                                                 }
2806                                         }
2807                                         break;
2808                                 case TCPOPT_SACK_PERM:
2809                                         if(opsize==TCPOLEN_SACK_PERM && th->syn && !estab) {
2810                                                 if (sysctl_tcp_sack) {
2811                                                         tp->sack_ok = 1;
2812                                                         tcp_sack_reset(tp);
2813                                                 }
2814                                         }
2815                                         break;
2816
2817                                 case TCPOPT_SACK:
2818                                         if((opsize >= (TCPOLEN_SACK_BASE + TCPOLEN_SACK_PERBLOCK)) &&
2819                                            !((opsize - TCPOLEN_SACK_BASE) % TCPOLEN_SACK_PERBLOCK) &&
2820                                            tp->sack_ok) {
2821                                                 TCP_SKB_CB(skb)->sacked = (ptr - 2) - (unsigned char *)th;
2822                                         }
2823                                 };
2824                                 ptr+=opsize-2;
2825                                 length-=opsize;
2826                 };
2827         }
2828 }
2829
2830 /* Fast parse options. This hopes to only see timestamps.
2831  * If it is wrong it falls back on tcp_parse_options().
2832  */
2833 static __inline__ int tcp_fast_parse_options(struct sk_buff *skb, struct tcphdr *th, struct tcp_opt *tp)
2834 {
2835         if (th->doff == sizeof(struct tcphdr)>>2) {
2836                 tp->saw_tstamp = 0;
2837                 return 0;
2838         } else if (tp->tstamp_ok &&
2839                    th->doff == (sizeof(struct tcphdr)>>2)+(TCPOLEN_TSTAMP_ALIGNED>>2)) {
2840                 __u32 *ptr = (__u32 *)(th + 1);
2841                 if (*ptr == ntohl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16)
2842                                   | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP)) {
2843                         tp->saw_tstamp = 1;
2844                         ++ptr;
2845                         tp->rcv_tsval = ntohl(*ptr);
2846                         ++ptr;
2847                         tp->rcv_tsecr = ntohl(*ptr);
2848                         return 1;
2849                 }
2850         }
2851         tcp_parse_options(skb, tp, 1);
2852         return 1;
2853 }
2854
2855 static __inline__ void
2856 tcp_store_ts_recent(struct tcp_opt *tp)
2857 {
2858         tp->ts_recent = tp->rcv_tsval;
2859         tp->ts_recent_stamp = xtime.tv_sec;
2860 }
2861
2862 static __inline__ void
2863 tcp_replace_ts_recent(struct tcp_opt *tp, u32 seq)
2864 {
2865         if (tp->saw_tstamp && !after(seq, tp->rcv_wup)) {
2866                 /* PAWS bug workaround wrt. ACK frames, the PAWS discard
2867                  * extra check below makes sure this can only happen
2868                  * for pure ACK frames.  -DaveM
2869                  *
2870                  * Not only, also it occurs for expired timestamps.
2871                  */
2872
2873                 if((s32)(tp->rcv_tsval - tp->ts_recent) >= 0 ||
2874                    xtime.tv_sec >= tp->ts_recent_stamp + TCP_PAWS_24DAYS)
2875                         tcp_store_ts_recent(tp);
2876         }
2877 }
2878
2879 /* Sorry, PAWS as specified is broken wrt. pure-ACKs -DaveM
2880  *
2881  * It is not fatal. If this ACK does _not_ change critical state (seqs, window)
2882  * it can pass through stack. So, the following predicate verifies that
2883  * this segment is not used for anything but congestion avoidance or
2884  * fast retransmit. Moreover, we even are able to eliminate most of such
2885  * second order effects, if we apply some small "replay" window (~RTO)
2886  * to timestamp space.
2887  *
2888  * All these measures still do not guarantee that we reject wrapped ACKs
2889  * on networks with high bandwidth, when sequence space is recycled fastly,
2890  * but it guarantees that such events will be very rare and do not affect
2891  * connection seriously. This doesn't look nice, but alas, PAWS is really
2892  * buggy extension.
2893  *
2894  * [ Later note. Even worse! It is buggy for segments _with_ data. RFC
2895  * states that events when retransmit arrives after original data are rare.
2896  * It is a blatant lie. VJ forgot about fast retransmit! 8)8) It is
2897  * the biggest problem on large power networks even with minor reordering.
2898  * OK, let's give it small replay window. If peer clock is even 1hz, it is safe
2899  * up to bandwidth of 18Gigabit/sec. 8) ]
2900  */
2901
2902 static int tcp_disordered_ack(struct tcp_opt *tp, struct sk_buff *skb)
2903 {
2904         struct tcphdr *th = skb->h.th;
2905         u32 seq = TCP_SKB_CB(skb)->seq;
2906         u32 ack = TCP_SKB_CB(skb)->ack_seq;
2907
2908         return (/* 1. Pure ACK with correct sequence number. */
2909                 (th->ack && seq == TCP_SKB_CB(skb)->end_seq && seq == tp->rcv_nxt) &&
2910
2911                 /* 2. ... and duplicate ACK. */
2912                 ack == tp->snd_una &&
2913
2914                 /* 3. ... and does not update window. */
2915                 !tcp_may_update_window(tp, ack, seq, ntohs(th->window)<<tp->snd_wscale) &&
2916
2917                 /* 4. ... and sits in replay window. */
2918                 (s32)(tp->ts_recent - tp->rcv_tsval) <= (tp->rto*1024)/HZ);
2919 }
2920
2921 static __inline__ int tcp_paws_discard(struct tcp_opt *tp, struct sk_buff *skb)
2922 {
2923         return ((s32)(tp->ts_recent - tp->rcv_tsval) > TCP_PAWS_WINDOW &&
2924                 xtime.tv_sec < tp->ts_recent_stamp + TCP_PAWS_24DAYS &&
2925                 !tcp_disordered_ack(tp, skb));
2926 }
2927
2928 /* Check segment sequence number for validity.
2929  *
2930  * Segment controls are considered valid, if the segment
2931  * fits to the window after truncation to the window. Acceptability
2932  * of data (and SYN, FIN, of course) is checked separately.
2933  * See tcp_data_queue(), for example.
2934  *
2935  * Also, controls (RST is main one) are accepted using RCV.WUP instead
2936  * of RCV.NXT. Peer still did not advance his SND.UNA when we
2937  * delayed ACK, so that hisSND.UNA<=ourRCV.WUP.
2938  * (borrowed from freebsd)
2939  */
2940
2941 static inline int tcp_sequence(struct tcp_opt *tp, u32 seq, u32 end_seq)
2942 {
2943         return  !before(end_seq, tp->rcv_wup) &&
2944                 !after(seq, tp->rcv_nxt + tcp_receive_window(tp));
2945 }
2946
2947 /* When we get a reset we do this. */
2948 static void tcp_reset(struct sock *sk)
2949 {
2950         /* We want the right error as BSD sees it (and indeed as we do). */
2951         switch (sk->sk_state) {
2952                 case TCP_SYN_SENT:
2953                         sk->sk_err = ECONNREFUSED;
2954                         break;
2955                 case TCP_CLOSE_WAIT:
2956                         sk->sk_err = EPIPE;
2957                         break;
2958                 case TCP_CLOSE:
2959                         return;
2960                 default:
2961                         sk->sk_err = ECONNRESET;
2962         }
2963
2964         if (!sock_flag(sk, SOCK_DEAD))
2965                 sk->sk_error_report(sk);
2966
2967         tcp_done(sk);
2968 }
2969
2970 /*
2971  *      Process the FIN bit. This now behaves as it is supposed to work
2972  *      and the FIN takes effect when it is validly part of sequence
2973  *      space. Not before when we get holes.
2974  *
2975  *      If we are ESTABLISHED, a received fin moves us to CLOSE-WAIT
2976  *      (and thence onto LAST-ACK and finally, CLOSE, we never enter
2977  *      TIME-WAIT)
2978  *
2979  *      If we are in FINWAIT-1, a received FIN indicates simultaneous
2980  *      close and we go into CLOSING (and later onto TIME-WAIT)
2981  *
2982  *      If we are in FINWAIT-2, a received FIN moves us to TIME-WAIT.
2983  */
2984 static void tcp_fin(struct sk_buff *skb, struct sock *sk, struct tcphdr *th)
2985 {
2986         struct tcp_opt *tp = tcp_sk(sk);
2987
2988         tcp_schedule_ack(tp);
2989
2990         sk->sk_shutdown |= RCV_SHUTDOWN;
2991         sock_set_flag(sk, SOCK_DONE);
2992
2993         switch (sk->sk_state) {
2994                 case TCP_SYN_RECV:
2995                 case TCP_ESTABLISHED:
2996                         /* Move to CLOSE_WAIT */
2997                         tcp_set_state(sk, TCP_CLOSE_WAIT);
2998                         tp->ack.pingpong = 1;
2999                         break;
3000
3001                 case TCP_CLOSE_WAIT:
3002                 case TCP_CLOSING:
3003                         /* Received a retransmission of the FIN, do
3004                          * nothing.
3005                          */
3006                         break;
3007                 case TCP_LAST_ACK:
3008                         /* RFC793: Remain in the LAST-ACK state. */
3009                         break;
3010
3011                 case TCP_FIN_WAIT1:
3012                         /* This case occurs when a simultaneous close
3013                          * happens, we must ack the received FIN and
3014                          * enter the CLOSING state.
3015                          */
3016                         tcp_send_ack(sk);
3017                         tcp_set_state(sk, TCP_CLOSING);
3018                         break;
3019                 case TCP_FIN_WAIT2:
3020                         /* Received a FIN -- send ACK and enter TIME_WAIT. */
3021                         tcp_send_ack(sk);
3022                         tcp_time_wait(sk, TCP_TIME_WAIT, 0);
3023                         break;
3024                 default:
3025                         /* Only TCP_LISTEN and TCP_CLOSE are left, in these
3026                          * cases we should never reach this piece of code.
3027                          */
3028                         printk(KERN_ERR "%s: Impossible, sk->sk_state=%d\n",
3029                                __FUNCTION__, sk->sk_state);
3030                         break;
3031         };
3032
3033         /* It _is_ possible, that we have something out-of-order _after_ FIN.
3034          * Probably, we should reset in this case. For now drop them.
3035          */
3036         __skb_queue_purge(&tp->out_of_order_queue);
3037         if (tp->sack_ok)
3038                 tcp_sack_reset(tp);
3039         tcp_mem_reclaim(sk);
3040
3041         if (!sock_flag(sk, SOCK_DEAD)) {
3042                 sk->sk_state_change(sk);
3043
3044                 /* Do not send POLL_HUP for half duplex close. */
3045                 if (sk->sk_shutdown == SHUTDOWN_MASK ||
3046                     sk->sk_state == TCP_CLOSE)
3047                         sk_wake_async(sk, 1, POLL_HUP);
3048                 else
3049                         sk_wake_async(sk, 1, POLL_IN);
3050         }
3051 }
3052
3053 static __inline__ int
3054 tcp_sack_extend(struct tcp_sack_block *sp, u32 seq, u32 end_seq)
3055 {
3056         if (!after(seq, sp->end_seq) && !after(sp->start_seq, end_seq)) {
3057                 if (before(seq, sp->start_seq))
3058                         sp->start_seq = seq;
3059                 if (after(end_seq, sp->end_seq))
3060                         sp->end_seq = end_seq;
3061                 return 1;
3062         }
3063         return 0;
3064 }
3065
3066 static __inline__ void tcp_dsack_set(struct tcp_opt *tp, u32 seq, u32 end_seq)
3067 {
3068         if (tp->sack_ok && sysctl_tcp_dsack) {
3069                 if (before(seq, tp->rcv_nxt))
3070                         NET_INC_STATS_BH(TCPDSACKOldSent);
3071                 else
3072                         NET_INC_STATS_BH(TCPDSACKOfoSent);
3073
3074                 tp->dsack = 1;
3075                 tp->duplicate_sack[0].start_seq = seq;
3076                 tp->duplicate_sack[0].end_seq = end_seq;
3077                 tp->eff_sacks = min(tp->num_sacks+1, 4-tp->tstamp_ok);
3078         }
3079 }
3080
3081 static __inline__ void tcp_dsack_extend(struct tcp_opt *tp, u32 seq, u32 end_seq)
3082 {
3083         if (!tp->dsack)
3084                 tcp_dsack_set(tp, seq, end_seq);
3085         else
3086                 tcp_sack_extend(tp->duplicate_sack, seq, end_seq);
3087 }
3088
3089 static void tcp_send_dupack(struct sock *sk, struct sk_buff *skb)
3090 {
3091         struct tcp_opt *tp = tcp_sk(sk);
3092
3093         if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
3094             before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
3095                 NET_INC_STATS_BH(DelayedACKLost);
3096                 tcp_enter_quickack_mode(tp);
3097
3098                 if (tp->sack_ok && sysctl_tcp_dsack) {
3099                         u32 end_seq = TCP_SKB_CB(skb)->end_seq;
3100
3101                         if (after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt))
3102                                 end_seq = tp->rcv_nxt;
3103                         tcp_dsack_set(tp, TCP_SKB_CB(skb)->seq, end_seq);
3104                 }
3105         }
3106
3107         tcp_send_ack(sk);
3108 }
3109
3110 /* These routines update the SACK block as out-of-order packets arrive or
3111  * in-order packets close up the sequence space.
3112  */
3113 static void tcp_sack_maybe_coalesce(struct tcp_opt *tp)
3114 {
3115         int this_sack;
3116         struct tcp_sack_block *sp = &tp->selective_acks[0];
3117         struct tcp_sack_block *swalk = sp+1;
3118
3119         /* See if the recent change to the first SACK eats into
3120          * or hits the sequence space of other SACK blocks, if so coalesce.
3121          */
3122         for (this_sack = 1; this_sack < tp->num_sacks; ) {
3123                 if (tcp_sack_extend(sp, swalk->start_seq, swalk->end_seq)) {
3124                         int i;
3125
3126                         /* Zap SWALK, by moving every further SACK up by one slot.
3127                          * Decrease num_sacks.
3128                          */
3129                         tp->num_sacks--;
3130                         tp->eff_sacks = min(tp->num_sacks+tp->dsack, 4-tp->tstamp_ok);
3131                         for(i=this_sack; i < tp->num_sacks; i++)
3132                                 sp[i] = sp[i+1];
3133                         continue;
3134                 }
3135                 this_sack++, swalk++;
3136         }
3137 }
3138
3139 static __inline__ void tcp_sack_swap(struct tcp_sack_block *sack1, struct tcp_sack_block *sack2)
3140 {
3141         __u32 tmp;
3142
3143         tmp = sack1->start_seq;
3144         sack1->start_seq = sack2->start_seq;
3145         sack2->start_seq = tmp;
3146
3147         tmp = sack1->end_seq;
3148         sack1->end_seq = sack2->end_seq;
3149         sack2->end_seq = tmp;
3150 }
3151
3152 static void tcp_sack_new_ofo_skb(struct sock *sk, u32 seq, u32 end_seq)
3153 {
3154         struct tcp_opt *tp = tcp_sk(sk);
3155         struct tcp_sack_block *sp = &tp->selective_acks[0];
3156         int cur_sacks = tp->num_sacks;
3157         int this_sack;
3158
3159         if (!cur_sacks)
3160                 goto new_sack;
3161
3162         for (this_sack=0; this_sack<cur_sacks; this_sack++, sp++) {
3163                 if (tcp_sack_extend(sp, seq, end_seq)) {
3164                         /* Rotate this_sack to the first one. */
3165                         for (; this_sack>0; this_sack--, sp--)
3166                                 tcp_sack_swap(sp, sp-1);
3167                         if (cur_sacks > 1)
3168                                 tcp_sack_maybe_coalesce(tp);
3169                         return;
3170                 }
3171         }
3172
3173         /* Could not find an adjacent existing SACK, build a new one,
3174          * put it at the front, and shift everyone else down.  We
3175          * always know there is at least one SACK present already here.
3176          *
3177          * If the sack array is full, forget about the last one.
3178          */
3179         if (this_sack >= 4) {
3180                 this_sack--;
3181                 tp->num_sacks--;
3182                 sp--;
3183         }
3184         for(; this_sack > 0; this_sack--, sp--)
3185                 *sp = *(sp-1);
3186
3187 new_sack:
3188         /* Build the new head SACK, and we're done. */
3189         sp->start_seq = seq;
3190         sp->end_seq = end_seq;
3191         tp->num_sacks++;
3192         tp->eff_sacks = min(tp->num_sacks + tp->dsack, 4 - tp->tstamp_ok);
3193 }
3194
3195 /* RCV.NXT advances, some SACKs should be eaten. */
3196
3197 static void tcp_sack_remove(struct tcp_opt *tp)
3198 {
3199         struct tcp_sack_block *sp = &tp->selective_acks[0];
3200         int num_sacks = tp->num_sacks;
3201         int this_sack;
3202
3203         /* Empty ofo queue, hence, all the SACKs are eaten. Clear. */
3204         if (skb_queue_len(&tp->out_of_order_queue) == 0) {
3205                 tp->num_sacks = 0;
3206                 tp->eff_sacks = tp->dsack;
3207                 return;
3208         }
3209
3210         for(this_sack = 0; this_sack < num_sacks; ) {
3211                 /* Check if the start of the sack is covered by RCV.NXT. */
3212                 if (!before(tp->rcv_nxt, sp->start_seq)) {
3213                         int i;
3214
3215                         /* RCV.NXT must cover all the block! */
3216                         BUG_TRAP(!before(tp->rcv_nxt, sp->end_seq));
3217
3218                         /* Zap this SACK, by moving forward any other SACKS. */
3219                         for (i=this_sack+1; i < num_sacks; i++)
3220                                 tp->selective_acks[i-1] = tp->selective_acks[i];
3221                         num_sacks--;
3222                         continue;
3223                 }
3224                 this_sack++;
3225                 sp++;
3226         }
3227         if (num_sacks != tp->num_sacks) {
3228                 tp->num_sacks = num_sacks;
3229                 tp->eff_sacks = min(tp->num_sacks+tp->dsack, 4-tp->tstamp_ok);
3230         }
3231 }
3232
3233 /* This one checks to see if we can put data from the
3234  * out_of_order queue into the receive_queue.
3235  */
3236 static void tcp_ofo_queue(struct sock *sk)
3237 {
3238         struct tcp_opt *tp = tcp_sk(sk);
3239         __u32 dsack_high = tp->rcv_nxt;
3240         struct sk_buff *skb;
3241
3242         while ((skb = skb_peek(&tp->out_of_order_queue)) != NULL) {
3243                 if (after(TCP_SKB_CB(skb)->seq, tp->rcv_nxt))
3244                         break;
3245
3246                 if (before(TCP_SKB_CB(skb)->seq, dsack_high)) {
3247                         __u32 dsack = dsack_high;
3248                         if (before(TCP_SKB_CB(skb)->end_seq, dsack_high))
3249                                 dsack_high = TCP_SKB_CB(skb)->end_seq;
3250                         tcp_dsack_extend(tp, TCP_SKB_CB(skb)->seq, dsack);
3251                 }
3252
3253                 if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) {
3254                         SOCK_DEBUG(sk, "ofo packet was already received \n");
3255                         __skb_unlink(skb, skb->list);
3256                         __kfree_skb(skb);
3257                         continue;
3258                 }
3259                 SOCK_DEBUG(sk, "ofo requeuing : rcv_next %X seq %X - %X\n",
3260                            tp->rcv_nxt, TCP_SKB_CB(skb)->seq,
3261                            TCP_SKB_CB(skb)->end_seq);
3262
3263                 __skb_unlink(skb, skb->list);
3264                 __skb_queue_tail(&sk->sk_receive_queue, skb);
3265                 tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
3266                 if(skb->h.th->fin)
3267                         tcp_fin(skb, sk, skb->h.th);
3268         }
3269 }
3270
3271 static inline int tcp_rmem_schedule(struct sock *sk, struct sk_buff *skb)
3272 {
3273         return (int)skb->truesize <= sk->sk_forward_alloc ||
3274                 tcp_mem_schedule(sk, skb->truesize, 1);
3275 }
3276
3277 static int tcp_prune_queue(struct sock *sk);
3278
3279 static void tcp_data_queue(struct sock *sk, struct sk_buff *skb)
3280 {
3281         struct tcphdr *th = skb->h.th;
3282         struct tcp_opt *tp = tcp_sk(sk);
3283         int eaten = -1;
3284
3285         if (TCP_SKB_CB(skb)->seq == TCP_SKB_CB(skb)->end_seq)
3286                 goto drop;
3287
3288         th = skb->h.th;
3289         __skb_pull(skb, th->doff*4);
3290
3291         TCP_ECN_accept_cwr(tp, skb);
3292
3293         if (tp->dsack) {
3294                 tp->dsack = 0;
3295                 tp->eff_sacks = min_t(unsigned int, tp->num_sacks,
3296                                                     4 - tp->tstamp_ok);
3297         }
3298
3299         /*  Queue data for delivery to the user.
3300          *  Packets in sequence go to the receive queue.
3301          *  Out of sequence packets to the out_of_order_queue.
3302          */
3303         if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt) {
3304                 if (tcp_receive_window(tp) == 0)
3305                         goto out_of_window;
3306
3307                 /* Ok. In sequence. In window. */
3308                 if (tp->ucopy.task == current &&
3309                     tp->copied_seq == tp->rcv_nxt && tp->ucopy.len &&
3310                     sock_owned_by_user(sk) && !tp->urg_data) {
3311                         int chunk = min_t(unsigned int, skb->len,
3312                                                         tp->ucopy.len);
3313
3314                         __set_current_state(TASK_RUNNING);
3315
3316                         local_bh_enable();
3317                         if (!skb_copy_datagram_iovec(skb, 0, tp->ucopy.iov, chunk)) {
3318                                 tp->ucopy.len -= chunk;
3319                                 tp->copied_seq += chunk;
3320                                 eaten = (chunk == skb->len && !th->fin);
3321                         }
3322                         local_bh_disable();
3323                 }
3324
3325                 if (eaten <= 0) {
3326 queue_and_out:
3327                         if (eaten < 0 &&
3328                             (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
3329                              !tcp_rmem_schedule(sk, skb))) {
3330                                 if (tcp_prune_queue(sk) < 0 || !tcp_rmem_schedule(sk, skb))
3331                                         goto drop;
3332                         }
3333                         tcp_set_owner_r(skb, sk);
3334                         __skb_queue_tail(&sk->sk_receive_queue, skb);
3335                 }
3336                 tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
3337                 if(skb->len)
3338                         tcp_event_data_recv(sk, tp, skb);
3339                 if(th->fin)
3340                         tcp_fin(skb, sk, th);
3341
3342                 if (skb_queue_len(&tp->out_of_order_queue)) {
3343                         tcp_ofo_queue(sk);
3344
3345                         /* RFC2581. 4.2. SHOULD send immediate ACK, when
3346                          * gap in queue is filled.
3347                          */
3348                         if (!skb_queue_len(&tp->out_of_order_queue))
3349                                 tp->ack.pingpong = 0;
3350                 }
3351
3352                 if (tp->num_sacks)
3353                         tcp_sack_remove(tp);
3354
3355                 tcp_fast_path_check(sk, tp);
3356
3357                 if (eaten > 0)
3358                         __kfree_skb(skb);
3359                 else if (!sock_flag(sk, SOCK_DEAD))
3360                         sk->sk_data_ready(sk, 0);
3361                 return;
3362         }
3363
3364         if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) {
3365                 /* A retransmit, 2nd most common case.  Force an immediate ack. */
3366                 NET_INC_STATS_BH(DelayedACKLost);
3367                 tcp_dsack_set(tp, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq);
3368
3369 out_of_window:
3370                 tcp_enter_quickack_mode(tp);
3371                 tcp_schedule_ack(tp);
3372 drop:
3373                 __kfree_skb(skb);
3374                 return;
3375         }
3376
3377         /* Out of window. F.e. zero window probe. */
3378         if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt + tcp_receive_window(tp)))
3379                 goto out_of_window;
3380
3381         tcp_enter_quickack_mode(tp);
3382
3383         if (before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
3384                 /* Partial packet, seq < rcv_next < end_seq */
3385                 SOCK_DEBUG(sk, "partial packet: rcv_next %X seq %X - %X\n",
3386                            tp->rcv_nxt, TCP_SKB_CB(skb)->seq,
3387                            TCP_SKB_CB(skb)->end_seq);
3388
3389                 tcp_dsack_set(tp, TCP_SKB_CB(skb)->seq, tp->rcv_nxt);
3390                 
3391                 /* If window is closed, drop tail of packet. But after
3392                  * remembering D-SACK for its head made in previous line.
3393                  */
3394                 if (!tcp_receive_window(tp))
3395                         goto out_of_window;
3396                 goto queue_and_out;
3397         }
3398
3399         TCP_ECN_check_ce(tp, skb);
3400
3401         if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
3402             !tcp_rmem_schedule(sk, skb)) {
3403                 if (tcp_prune_queue(sk) < 0 || !tcp_rmem_schedule(sk, skb))
3404                         goto drop;
3405         }
3406
3407         /* Disable header prediction. */
3408         tp->pred_flags = 0;
3409         tcp_schedule_ack(tp);
3410
3411         SOCK_DEBUG(sk, "out of order segment: rcv_next %X seq %X - %X\n",
3412                    tp->rcv_nxt, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq);
3413
3414         tcp_set_owner_r(skb, sk);
3415
3416         if (!skb_peek(&tp->out_of_order_queue)) {
3417                 /* Initial out of order segment, build 1 SACK. */
3418                 if (tp->sack_ok) {
3419                         tp->num_sacks = 1;
3420                         tp->dsack     = 0;
3421                         tp->eff_sacks = 1;
3422                         tp->selective_acks[0].start_seq = TCP_SKB_CB(skb)->seq;
3423                         tp->selective_acks[0].end_seq =
3424                                                 TCP_SKB_CB(skb)->end_seq;
3425                 }
3426                 __skb_queue_head(&tp->out_of_order_queue,skb);
3427         } else {
3428                 struct sk_buff *skb1 = tp->out_of_order_queue.prev;
3429                 u32 seq = TCP_SKB_CB(skb)->seq;
3430                 u32 end_seq = TCP_SKB_CB(skb)->end_seq;
3431
3432                 if (seq == TCP_SKB_CB(skb1)->end_seq) {
3433                         __skb_append(skb1, skb);
3434
3435                         if (!tp->num_sacks ||
3436                             tp->selective_acks[0].end_seq != seq)
3437                                 goto add_sack;
3438
3439                         /* Common case: data arrive in order after hole. */
3440                         tp->selective_acks[0].end_seq = end_seq;
3441                         return;
3442                 }
3443
3444                 /* Find place to insert this segment. */
3445                 do {
3446                         if (!after(TCP_SKB_CB(skb1)->seq, seq))
3447                                 break;
3448                 } while ((skb1 = skb1->prev) !=
3449                          (struct sk_buff*)&tp->out_of_order_queue);
3450
3451                 /* Do skb overlap to previous one? */
3452                 if (skb1 != (struct sk_buff*)&tp->out_of_order_queue &&
3453                     before(seq, TCP_SKB_CB(skb1)->end_seq)) {
3454                         if (!after(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
3455                                 /* All the bits are present. Drop. */
3456                                 __kfree_skb(skb);
3457                                 tcp_dsack_set(tp, seq, end_seq);
3458                                 goto add_sack;
3459                         }
3460                         if (after(seq, TCP_SKB_CB(skb1)->seq)) {
3461                                 /* Partial overlap. */
3462                                 tcp_dsack_set(tp, seq, TCP_SKB_CB(skb1)->end_seq);
3463                         } else {
3464                                 skb1 = skb1->prev;
3465                         }
3466                 }
3467                 __skb_insert(skb, skb1, skb1->next, &tp->out_of_order_queue);
3468                 
3469                 /* And clean segments covered by new one as whole. */
3470                 while ((skb1 = skb->next) !=
3471                        (struct sk_buff*)&tp->out_of_order_queue &&
3472                        after(end_seq, TCP_SKB_CB(skb1)->seq)) {
3473                        if (before(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
3474                                tcp_dsack_extend(tp, TCP_SKB_CB(skb1)->seq, end_seq);
3475                                break;
3476                        }
3477                        __skb_unlink(skb1, skb1->list);
3478                        tcp_dsack_extend(tp, TCP_SKB_CB(skb1)->seq, TCP_SKB_CB(skb1)->end_seq);
3479                        __kfree_skb(skb1);
3480                 }
3481
3482 add_sack:
3483                 if (tp->sack_ok)
3484                         tcp_sack_new_ofo_skb(sk, seq, end_seq);
3485         }
3486 }
3487
3488 /* Collapse contiguous sequence of skbs head..tail with
3489  * sequence numbers start..end.
3490  * Segments with FIN/SYN are not collapsed (only because this
3491  * simplifies code)
3492  */
3493 static void
3494 tcp_collapse(struct sock *sk, struct sk_buff *head,
3495              struct sk_buff *tail, u32 start, u32 end)
3496 {
3497         struct sk_buff *skb;
3498
3499         /* First, check that queue is collapsable and find
3500          * the point where collapsing can be useful. */
3501         for (skb = head; skb != tail; ) {
3502                 /* No new bits? It is possible on ofo queue. */
3503                 if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
3504                         struct sk_buff *next = skb->next;
3505                         __skb_unlink(skb, skb->list);
3506                         __kfree_skb(skb);
3507                         NET_INC_STATS_BH(TCPRcvCollapsed);
3508                         skb = next;
3509                         continue;
3510                 }
3511
3512                 /* The first skb to collapse is:
3513                  * - not SYN/FIN and
3514                  * - bloated or contains data before "start" or
3515                  *   overlaps to the next one.
3516                  */
3517                 if (!skb->h.th->syn && !skb->h.th->fin &&
3518                     (tcp_win_from_space(skb->truesize) > skb->len ||
3519                      before(TCP_SKB_CB(skb)->seq, start) ||
3520                      (skb->next != tail &&
3521                       TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb->next)->seq)))
3522                         break;
3523
3524                 /* Decided to skip this, advance start seq. */
3525                 start = TCP_SKB_CB(skb)->end_seq;
3526                 skb = skb->next;
3527         }
3528         if (skb == tail || skb->h.th->syn || skb->h.th->fin)
3529                 return;
3530
3531         while (before(start, end)) {
3532                 struct sk_buff *nskb;
3533                 int header = skb_headroom(skb);
3534                 int copy = (PAGE_SIZE - sizeof(struct sk_buff) -
3535                             sizeof(struct skb_shared_info) - header - 31)&~15;
3536
3537                 /* Too big header? This can happen with IPv6. */
3538                 if (copy < 0)
3539                         return;
3540                 if (end-start < copy)
3541                         copy = end-start;
3542                 nskb = alloc_skb(copy+header, GFP_ATOMIC);
3543                 if (!nskb)
3544                         return;
3545                 skb_reserve(nskb, header);
3546                 memcpy(nskb->head, skb->head, header);
3547                 nskb->nh.raw = nskb->head + (skb->nh.raw-skb->head);
3548                 nskb->h.raw = nskb->head + (skb->h.raw-skb->head);
3549                 nskb->mac.raw = nskb->head + (skb->mac.raw-skb->head);
3550                 memcpy(nskb->cb, skb->cb, sizeof(skb->cb));
3551                 TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(nskb)->end_seq = start;
3552                 __skb_insert(nskb, skb->prev, skb, skb->list);
3553                 tcp_set_owner_r(nskb, sk);
3554
3555                 /* Copy data, releasing collapsed skbs. */
3556                 while (copy > 0) {
3557                         int offset = start - TCP_SKB_CB(skb)->seq;
3558                         int size = TCP_SKB_CB(skb)->end_seq - start;
3559
3560                         if (offset < 0) BUG();
3561                         if (size > 0) {
3562                                 size = min(copy, size);
3563                                 if (skb_copy_bits(skb, offset, skb_put(nskb, size), size))
3564                                         BUG();
3565                                 TCP_SKB_CB(nskb)->end_seq += size;
3566                                 copy -= size;
3567                                 start += size;
3568                         }
3569                         if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
3570                                 struct sk_buff *next = skb->next;
3571                                 __skb_unlink(skb, skb->list);
3572                                 __kfree_skb(skb);
3573                                 NET_INC_STATS_BH(TCPRcvCollapsed);
3574                                 skb = next;
3575                                 if (skb == tail || skb->h.th->syn || skb->h.th->fin)
3576                                         return;
3577                         }
3578                 }
3579         }
3580 }
3581
3582 /* Collapse ofo queue. Algorithm: select contiguous sequence of skbs
3583  * and tcp_collapse() them until all the queue is collapsed.
3584  */
3585 static void tcp_collapse_ofo_queue(struct sock *sk)
3586 {
3587         struct tcp_opt *tp = tcp_sk(sk);
3588         struct sk_buff *skb = skb_peek(&tp->out_of_order_queue);
3589         struct sk_buff *head;
3590         u32 start, end;
3591
3592         if (skb == NULL)
3593                 return;
3594
3595         start = TCP_SKB_CB(skb)->seq;
3596         end = TCP_SKB_CB(skb)->end_seq;
3597         head = skb;
3598
3599         for (;;) {
3600                 skb = skb->next;
3601
3602                 /* Segment is terminated when we see gap or when
3603                  * we are at the end of all the queue. */
3604                 if (skb == (struct sk_buff *)&tp->out_of_order_queue ||
3605                     after(TCP_SKB_CB(skb)->seq, end) ||
3606                     before(TCP_SKB_CB(skb)->end_seq, start)) {
3607                         tcp_collapse(sk, head, skb, start, end);
3608                         head = skb;
3609                         if (skb == (struct sk_buff *)&tp->out_of_order_queue)
3610                                 break;
3611                         /* Start new segment */
3612                         start = TCP_SKB_CB(skb)->seq;
3613                         end = TCP_SKB_CB(skb)->end_seq;
3614                 } else {
3615                         if (before(TCP_SKB_CB(skb)->seq, start))
3616                                 start = TCP_SKB_CB(skb)->seq;
3617                         if (after(TCP_SKB_CB(skb)->end_seq, end))
3618                                 end = TCP_SKB_CB(skb)->end_seq;
3619                 }
3620         }
3621 }
3622
3623 /* Reduce allocated memory if we can, trying to get
3624  * the socket within its memory limits again.
3625  *
3626  * Return less than zero if we should start dropping frames
3627  * until the socket owning process reads some of the data
3628  * to stabilize the situation.
3629  */
3630 static int tcp_prune_queue(struct sock *sk)
3631 {
3632         struct tcp_opt *tp = tcp_sk(sk); 
3633
3634         SOCK_DEBUG(sk, "prune_queue: c=%x\n", tp->copied_seq);
3635
3636         NET_INC_STATS_BH(PruneCalled);
3637
3638         if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
3639                 tcp_clamp_window(sk, tp);
3640         else if (tcp_memory_pressure)
3641                 tp->rcv_ssthresh = min(tp->rcv_ssthresh, 4U * tp->advmss);
3642
3643         tcp_collapse_ofo_queue(sk);
3644         tcp_collapse(sk, sk->sk_receive_queue.next,
3645                      (struct sk_buff*)&sk->sk_receive_queue,
3646                      tp->copied_seq, tp->rcv_nxt);
3647         tcp_mem_reclaim(sk);
3648
3649         if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf)
3650                 return 0;
3651
3652         /* Collapsing did not help, destructive actions follow.
3653          * This must not ever occur. */
3654
3655         /* First, purge the out_of_order queue. */
3656         if (skb_queue_len(&tp->out_of_order_queue)) {
3657                 NET_ADD_STATS_BH(OfoPruned,
3658                                  skb_queue_len(&tp->out_of_order_queue));
3659                 __skb_queue_purge(&tp->out_of_order_queue);
3660
3661                 /* Reset SACK state.  A conforming SACK implementation will
3662                  * do the same at a timeout based retransmit.  When a connection
3663                  * is in a sad state like this, we care only about integrity
3664                  * of the connection not performance.
3665                  */
3666                 if (tp->sack_ok)
3667                         tcp_sack_reset(tp);
3668                 tcp_mem_reclaim(sk);
3669         }
3670
3671         if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf)
3672                 return 0;
3673
3674         /* If we are really being abused, tell the caller to silently
3675          * drop receive data on the floor.  It will get retransmitted
3676          * and hopefully then we'll have sufficient space.
3677          */
3678         NET_INC_STATS_BH(RcvPruned);
3679
3680         /* Massive buffer overcommit. */
3681         tp->pred_flags = 0;
3682         return -1;
3683 }
3684
3685
3686 /* RFC2861, slow part. Adjust cwnd, after it was not full during one rto.
3687  * As additional protections, we do not touch cwnd in retransmission phases,
3688  * and if application hit its sndbuf limit recently.
3689  */
3690 void tcp_cwnd_application_limited(struct sock *sk)
3691 {
3692         struct tcp_opt *tp = tcp_sk(sk);
3693
3694         if (tp->ca_state == TCP_CA_Open &&
3695             sk->sk_socket && !test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) {
3696                 /* Limited by application or receiver window. */
3697                 u32 win_used = max(tp->snd_cwnd_used, 2U);
3698                 if (win_used < tp->snd_cwnd) {
3699                         tp->snd_ssthresh = tcp_current_ssthresh(tp);
3700                         tp->snd_cwnd = (tp->snd_cwnd + win_used) >> 1;
3701                 }
3702                 tp->snd_cwnd_used = 0;
3703         }
3704         tp->snd_cwnd_stamp = tcp_time_stamp;
3705 }
3706
3707
3708 /* When incoming ACK allowed to free some skb from write_queue,
3709  * we remember this event in flag tp->queue_shrunk and wake up socket
3710  * on the exit from tcp input handler.
3711  *
3712  * PROBLEM: sndbuf expansion does not work well with largesend.
3713  */
3714 static void tcp_new_space(struct sock *sk)
3715 {
3716         struct tcp_opt *tp = tcp_sk(sk);
3717
3718         if (tp->packets_out < tp->snd_cwnd &&
3719             !(sk->sk_userlocks & SOCK_SNDBUF_LOCK) &&
3720             !tcp_memory_pressure &&
3721             atomic_read(&tcp_memory_allocated) < sysctl_tcp_mem[0]) {
3722                 int sndmem = max_t(u32, tp->mss_clamp, tp->mss_cache) +
3723                         MAX_TCP_HEADER + 16 + sizeof(struct sk_buff),
3724                     demanded = max_t(unsigned int, tp->snd_cwnd,
3725                                                    tp->reordering + 1);
3726                 sndmem *= 2*demanded;
3727                 if (sndmem > sk->sk_sndbuf)
3728                         sk->sk_sndbuf = min(sndmem, sysctl_tcp_wmem[2]);
3729                 tp->snd_cwnd_stamp = tcp_time_stamp;
3730         }
3731
3732         sk->sk_write_space(sk);
3733 }
3734
3735 static inline void tcp_check_space(struct sock *sk)
3736 {
3737         struct tcp_opt *tp = tcp_sk(sk);
3738
3739         if (tp->queue_shrunk) {
3740                 tp->queue_shrunk = 0;
3741                 if (sk->sk_socket &&
3742                     test_bit(SOCK_NOSPACE, &sk->sk_socket->flags))
3743                         tcp_new_space(sk);
3744         }
3745 }
3746
3747 static void __tcp_data_snd_check(struct sock *sk, struct sk_buff *skb)
3748 {
3749         struct tcp_opt *tp = tcp_sk(sk);
3750
3751         if (after(TCP_SKB_CB(skb)->end_seq, tp->snd_una + tp->snd_wnd) ||
3752             tcp_packets_in_flight(tp) >= tp->snd_cwnd ||
3753             tcp_write_xmit(sk, tp->nonagle))
3754                 tcp_check_probe_timer(sk, tp);
3755 }
3756
3757 static __inline__ void tcp_data_snd_check(struct sock *sk)
3758 {
3759         struct tcp_opt *tp = tcp_sk(sk);
3760         struct sk_buff *skb = tp->send_head;
3761
3762         if (skb != NULL)
3763                 __tcp_data_snd_check(sk, skb);
3764         tcp_check_space(sk);
3765 }
3766
3767 /*
3768  * Check if sending an ack is needed.
3769  */
3770 static void __tcp_ack_snd_check(struct sock *sk, int ofo_possible)
3771 {
3772         struct tcp_opt *tp = tcp_sk(sk);
3773
3774             /* More than one full frame received... */
3775         if (((tp->rcv_nxt - tp->rcv_wup) > tp->ack.rcv_mss
3776              /* ... and right edge of window advances far enough.
3777               * (tcp_recvmsg() will send ACK otherwise). Or...
3778               */
3779              && __tcp_select_window(sk) >= tp->rcv_wnd) ||
3780             /* We ACK each frame or... */
3781             tcp_in_quickack_mode(tp) ||
3782             /* We have out of order data. */
3783             (ofo_possible &&
3784              skb_peek(&tp->out_of_order_queue))) {
3785                 /* Then ack it now */
3786                 tcp_send_ack(sk);
3787         } else {
3788                 /* Else, send delayed ack. */
3789                 tcp_send_delayed_ack(sk);
3790         }
3791 }
3792
3793 static __inline__ void tcp_ack_snd_check(struct sock *sk)
3794 {
3795         struct tcp_opt *tp = tcp_sk(sk);
3796         if (!tcp_ack_scheduled(tp)) {
3797                 /* We sent a data segment already. */
3798                 return;
3799         }
3800         __tcp_ack_snd_check(sk, 1);
3801 }
3802
3803 /*
3804  *      This routine is only called when we have urgent data
3805  *      signalled. Its the 'slow' part of tcp_urg. It could be
3806  *      moved inline now as tcp_urg is only called from one
3807  *      place. We handle URGent data wrong. We have to - as
3808  *      BSD still doesn't use the correction from RFC961.
3809  *      For 1003.1g we should support a new option TCP_STDURG to permit
3810  *      either form (or just set the sysctl tcp_stdurg).
3811  */
3812  
3813 static void tcp_check_urg(struct sock * sk, struct tcphdr * th)
3814 {
3815         struct tcp_opt *tp = tcp_sk(sk);
3816         u32 ptr = ntohs(th->urg_ptr);
3817
3818         if (ptr && !sysctl_tcp_stdurg)
3819                 ptr--;
3820         ptr += ntohl(th->seq);
3821
3822         /* Ignore urgent data that we've already seen and read. */
3823         if (after(tp->copied_seq, ptr))
3824                 return;
3825
3826         /* Do not replay urg ptr.
3827          *
3828          * NOTE: interesting situation not covered by specs.
3829          * Misbehaving sender may send urg ptr, pointing to segment,
3830          * which we already have in ofo queue. We are not able to fetch
3831          * such data and will stay in TCP_URG_NOTYET until will be eaten
3832          * by recvmsg(). Seems, we are not obliged to handle such wicked
3833          * situations. But it is worth to think about possibility of some
3834          * DoSes using some hypothetical application level deadlock.
3835          */
3836         if (before(ptr, tp->rcv_nxt))
3837                 return;
3838
3839         /* Do we already have a newer (or duplicate) urgent pointer? */
3840         if (tp->urg_data && !after(ptr, tp->urg_seq))
3841                 return;
3842
3843         /* Tell the world about our new urgent pointer. */
3844         sk_send_sigurg(sk);
3845
3846         /* We may be adding urgent data when the last byte read was
3847          * urgent. To do this requires some care. We cannot just ignore
3848          * tp->copied_seq since we would read the last urgent byte again
3849          * as data, nor can we alter copied_seq until this data arrives
3850          * or we break the sematics of SIOCATMARK (and thus sockatmark())
3851          *
3852          * NOTE. Double Dutch. Rendering to plain English: author of comment
3853          * above did something sort of  send("A", MSG_OOB); send("B", MSG_OOB);
3854          * and expect that both A and B disappear from stream. This is _wrong_.
3855          * Though this happens in BSD with high probability, this is occasional.
3856          * Any application relying on this is buggy. Note also, that fix "works"
3857          * only in this artificial test. Insert some normal data between A and B and we will
3858          * decline of BSD again. Verdict: it is better to remove to trap
3859          * buggy users.
3860          */
3861         if (tp->urg_seq == tp->copied_seq && tp->urg_data &&
3862             !sock_flag(sk, SOCK_URGINLINE) &&
3863             tp->copied_seq != tp->rcv_nxt) {
3864                 struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
3865                 tp->copied_seq++;
3866                 if (skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq)) {
3867                         __skb_unlink(skb, skb->list);
3868                         __kfree_skb(skb);
3869                 }
3870         }
3871
3872         tp->urg_data   = TCP_URG_NOTYET;
3873         tp->urg_seq    = ptr;
3874
3875         /* Disable header prediction. */
3876         tp->pred_flags = 0;
3877 }
3878
3879 /* This is the 'fast' part of urgent handling. */
3880 static void tcp_urg(struct sock *sk, struct sk_buff *skb, struct tcphdr *th)
3881 {
3882         struct tcp_opt *tp = tcp_sk(sk);
3883
3884         /* Check if we get a new urgent pointer - normally not. */
3885         if (th->urg)
3886                 tcp_check_urg(sk,th);
3887
3888         /* Do we wait for any urgent data? - normally not... */
3889         if (tp->urg_data == TCP_URG_NOTYET) {
3890                 u32 ptr = tp->urg_seq - ntohl(th->seq) + (th->doff * 4) -
3891                           th->syn;
3892
3893                 /* Is the urgent pointer pointing into this packet? */   
3894                 if (ptr < skb->len) {
3895                         u8 tmp;
3896                         if (skb_copy_bits(skb, ptr, &tmp, 1))
3897                                 BUG();
3898                         tp->urg_data = TCP_URG_VALID | tmp;
3899                         if (!sock_flag(sk, SOCK_DEAD))
3900                                 sk->sk_data_ready(sk, 0);
3901                 }
3902         }
3903 }
3904
3905 static int tcp_copy_to_iovec(struct sock *sk, struct sk_buff *skb, int hlen)
3906 {
3907         struct tcp_opt *tp = tcp_sk(sk);
3908         int chunk = skb->len - hlen;
3909         int err;
3910
3911         local_bh_enable();
3912         if (skb->ip_summed==CHECKSUM_UNNECESSARY)
3913                 err = skb_copy_datagram_iovec(skb, hlen, tp->ucopy.iov, chunk);
3914         else
3915                 err = skb_copy_and_csum_datagram_iovec(skb, hlen,
3916                                                        tp->ucopy.iov);
3917
3918         if (!err) {
3919                 tp->ucopy.len -= chunk;
3920                 tp->copied_seq += chunk;
3921         }
3922
3923         local_bh_disable();
3924         return err;
3925 }
3926
3927 static int __tcp_checksum_complete_user(struct sock *sk, struct sk_buff *skb)
3928 {
3929         int result;
3930
3931         if (sock_owned_by_user(sk)) {
3932                 local_bh_enable();
3933                 result = __tcp_checksum_complete(skb);
3934                 local_bh_disable();
3935         } else {
3936                 result = __tcp_checksum_complete(skb);
3937         }
3938         return result;
3939 }
3940
3941 static __inline__ int
3942 tcp_checksum_complete_user(struct sock *sk, struct sk_buff *skb)
3943 {
3944         return skb->ip_summed != CHECKSUM_UNNECESSARY &&
3945                 __tcp_checksum_complete_user(sk, skb);
3946 }
3947
3948 /*
3949  *      TCP receive function for the ESTABLISHED state. 
3950  *
3951  *      It is split into a fast path and a slow path. The fast path is 
3952  *      disabled when:
3953  *      - A zero window was announced from us - zero window probing
3954  *        is only handled properly in the slow path. 
3955  *      - Out of order segments arrived.
3956  *      - Urgent data is expected.
3957  *      - There is no buffer space left
3958  *      - Unexpected TCP flags/window values/header lengths are received
3959  *        (detected by checking the TCP header against pred_flags) 
3960  *      - Data is sent in both directions. Fast path only supports pure senders
3961  *        or pure receivers (this means either the sequence number or the ack
3962  *        value must stay constant)
3963  *      - Unexpected TCP option.
3964  *
3965  *      When these conditions are not satisfied it drops into a standard 
3966  *      receive procedure patterned after RFC793 to handle all cases.
3967  *      The first three cases are guaranteed by proper pred_flags setting,
3968  *      the rest is checked inline. Fast processing is turned on in 
3969  *      tcp_data_queue when everything is OK.
3970  */
3971 int tcp_rcv_established(struct sock *sk, struct sk_buff *skb,
3972                         struct tcphdr *th, unsigned len)
3973 {
3974         struct tcp_opt *tp = tcp_sk(sk);
3975
3976         /*
3977          *      Header prediction.
3978          *      The code loosely follows the one in the famous 
3979          *      "30 instruction TCP receive" Van Jacobson mail.
3980          *      
3981          *      Van's trick is to deposit buffers into socket queue 
3982          *      on a device interrupt, to call tcp_recv function
3983          *      on the receive process context and checksum and copy
3984          *      the buffer to user space. smart...
3985          *
3986          *      Our current scheme is not silly either but we take the 
3987          *      extra cost of the net_bh soft interrupt processing...
3988          *      We do checksum and copy also but from device to kernel.
3989          */
3990
3991         tp->saw_tstamp = 0;
3992
3993         /*      pred_flags is 0xS?10 << 16 + snd_wnd
3994          *      if header_predition is to be made
3995          *      'S' will always be tp->tcp_header_len >> 2
3996          *      '?' will be 0 for the fast path, otherwise pred_flags is 0 to
3997          *  turn it off (when there are holes in the receive 
3998          *       space for instance)
3999          *      PSH flag is ignored.
4000          */
4001
4002         if ((tcp_flag_word(th) & TCP_HP_BITS) == tp->pred_flags &&
4003                 TCP_SKB_CB(skb)->seq == tp->rcv_nxt) {
4004                 int tcp_header_len = tp->tcp_header_len;
4005
4006                 /* Timestamp header prediction: tcp_header_len
4007                  * is automatically equal to th->doff*4 due to pred_flags
4008                  * match.
4009                  */
4010
4011                 /* Check timestamp */
4012                 if (tcp_header_len == sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) {
4013                         __u32 *ptr = (__u32 *)(th + 1);
4014
4015                         /* No? Slow path! */
4016                         if (*ptr != ntohl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16)
4017                                           | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP))
4018                                 goto slow_path;
4019
4020                         tp->saw_tstamp = 1;
4021                         ++ptr; 
4022                         tp->rcv_tsval = ntohl(*ptr);
4023                         ++ptr;
4024                         tp->rcv_tsecr = ntohl(*ptr);
4025
4026                         /* If PAWS failed, check it more carefully in slow path */
4027                         if ((s32)(tp->rcv_tsval - tp->ts_recent) < 0)
4028                                 goto slow_path;
4029
4030                         /* DO NOT update ts_recent here, if checksum fails
4031                          * and timestamp was corrupted part, it will result
4032                          * in a hung connection since we will drop all
4033                          * future packets due to the PAWS test.
4034                          */
4035                 }
4036
4037                 if (len <= tcp_header_len) {
4038                         /* Bulk data transfer: sender */
4039                         if (len == tcp_header_len) {
4040                                 /* Predicted packet is in window by definition.
4041                                  * seq == rcv_nxt and rcv_wup <= rcv_nxt.
4042                                  * Hence, check seq<=rcv_wup reduces to:
4043                                  */
4044                                 if (tcp_header_len ==
4045                                     (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) &&
4046                                     tp->rcv_nxt == tp->rcv_wup)
4047                                         tcp_store_ts_recent(tp);
4048                                 /* We know that such packets are checksummed
4049                                  * on entry.
4050                                  */
4051                                 tcp_ack(sk, skb, 0);
4052                                 __kfree_skb(skb); 
4053                                 tcp_data_snd_check(sk);
4054                                 return 0;
4055                         } else { /* Header too small */
4056                                 TCP_INC_STATS_BH(TcpInErrs);
4057                                 goto discard;
4058                         }
4059                 } else {
4060                         int eaten = 0;
4061
4062                         if (tp->ucopy.task == current &&
4063                             tp->copied_seq == tp->rcv_nxt &&
4064                             len - tcp_header_len <= tp->ucopy.len &&
4065                             sock_owned_by_user(sk)) {
4066                                 __set_current_state(TASK_RUNNING);
4067
4068                                 if (!tcp_copy_to_iovec(sk, skb, tcp_header_len)) {
4069                                         /* Predicted packet is in window by definition.
4070                                          * seq == rcv_nxt and rcv_wup <= rcv_nxt.
4071                                          * Hence, check seq<=rcv_wup reduces to:
4072                                          */
4073                                         if (tcp_header_len ==
4074                                             (sizeof(struct tcphdr) +
4075                                              TCPOLEN_TSTAMP_ALIGNED) &&
4076                                             tp->rcv_nxt == tp->rcv_wup)
4077                                                 tcp_store_ts_recent(tp);
4078
4079                                         __skb_pull(skb, tcp_header_len);
4080                                         tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
4081                                         NET_INC_STATS_BH(TCPHPHitsToUser);
4082                                         eaten = 1;
4083                                 }
4084                         }
4085                         if (!eaten) {
4086                                 if (tcp_checksum_complete_user(sk, skb))
4087                                         goto csum_error;
4088
4089                                 /* Predicted packet is in window by definition.
4090                                  * seq == rcv_nxt and rcv_wup <= rcv_nxt.
4091                                  * Hence, check seq<=rcv_wup reduces to:
4092                                  */
4093                                 if (tcp_header_len ==
4094                                     (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) &&
4095                                     tp->rcv_nxt == tp->rcv_wup)
4096                                         tcp_store_ts_recent(tp);
4097
4098                                 if ((int)skb->truesize > sk->sk_forward_alloc)
4099                                         goto step5;
4100
4101                                 NET_INC_STATS_BH(TCPHPHits);
4102
4103                                 /* Bulk data transfer: receiver */
4104                                 __skb_pull(skb,tcp_header_len);
4105                                 __skb_queue_tail(&sk->sk_receive_queue, skb);
4106                                 tcp_set_owner_r(skb, sk);
4107                                 tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
4108                         }
4109
4110                         tcp_event_data_recv(sk, tp, skb);
4111
4112                         if (TCP_SKB_CB(skb)->ack_seq != tp->snd_una) {
4113                                 /* Well, only one small jumplet in fast path... */
4114                                 tcp_ack(sk, skb, FLAG_DATA);
4115                                 tcp_data_snd_check(sk);
4116                                 if (!tcp_ack_scheduled(tp))
4117                                         goto no_ack;
4118                         }
4119
4120                         if (eaten) {
4121                                 if (tcp_in_quickack_mode(tp)) {
4122                                         tcp_send_ack(sk);
4123                                 } else {
4124                                         tcp_send_delayed_ack(sk);
4125                                 }
4126                         } else {
4127                                 __tcp_ack_snd_check(sk, 0);
4128                         }
4129
4130 no_ack:
4131                         if (eaten)
4132                                 __kfree_skb(skb);
4133                         else
4134                                 sk->sk_data_ready(sk, 0);
4135                         return 0;
4136                 }
4137         }
4138
4139 slow_path:
4140         if (len < (th->doff<<2) || tcp_checksum_complete_user(sk, skb))
4141                 goto csum_error;
4142
4143         /*
4144          * RFC1323: H1. Apply PAWS check first.
4145          */
4146         if (tcp_fast_parse_options(skb, th, tp) && tp->saw_tstamp &&
4147             tcp_paws_discard(tp, skb)) {
4148                 if (!th->rst) {
4149                         NET_INC_STATS_BH(PAWSEstabRejected);
4150                         tcp_send_dupack(sk, skb);
4151                         goto discard;
4152                 }
4153                 /* Resets are accepted even if PAWS failed.
4154
4155                    ts_recent update must be made after we are sure
4156                    that the packet is in window.
4157                  */
4158         }
4159
4160         /*
4161          *      Standard slow path.
4162          */
4163
4164         if (!tcp_sequence(tp, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq)) {
4165                 /* RFC793, page 37: "In all states except SYN-SENT, all reset
4166                  * (RST) segments are validated by checking their SEQ-fields."
4167                  * And page 69: "If an incoming segment is not acceptable,
4168                  * an acknowledgment should be sent in reply (unless the RST bit
4169                  * is set, if so drop the segment and return)".
4170                  */
4171                 if (!th->rst)
4172                         tcp_send_dupack(sk, skb);
4173                 goto discard;
4174         }
4175
4176         if(th->rst) {
4177                 tcp_reset(sk);
4178                 goto discard;
4179         }
4180
4181         tcp_replace_ts_recent(tp, TCP_SKB_CB(skb)->seq);
4182
4183         if (th->syn && !before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
4184                 TCP_INC_STATS_BH(TcpInErrs);
4185                 NET_INC_STATS_BH(TCPAbortOnSyn);
4186                 tcp_reset(sk);
4187                 return 1;
4188         }
4189
4190 step5:
4191         if(th->ack)
4192                 tcp_ack(sk, skb, FLAG_SLOWPATH);
4193
4194         /* Process urgent data. */
4195         tcp_urg(sk, skb, th);
4196
4197         /* step 7: process the segment text */
4198         tcp_data_queue(sk, skb);
4199
4200         tcp_data_snd_check(sk);
4201         tcp_ack_snd_check(sk);
4202         return 0;
4203
4204 csum_error:
4205         TCP_INC_STATS_BH(TcpInErrs);
4206
4207 discard:
4208         __kfree_skb(skb);
4209         return 0;
4210 }
4211
4212 static int tcp_rcv_synsent_state_process(struct sock *sk, struct sk_buff *skb,
4213                                          struct tcphdr *th, unsigned len)
4214 {
4215         struct tcp_opt *tp = tcp_sk(sk);
4216         int saved_clamp = tp->mss_clamp;
4217
4218         tcp_parse_options(skb, tp, 0);
4219
4220         if (th->ack) {
4221                 /* rfc793:
4222                  * "If the state is SYN-SENT then
4223                  *    first check the ACK bit
4224                  *      If the ACK bit is set
4225                  *        If SEG.ACK =< ISS, or SEG.ACK > SND.NXT, send
4226                  *        a reset (unless the RST bit is set, if so drop
4227                  *        the segment and return)"
4228                  *
4229                  *  We do not send data with SYN, so that RFC-correct
4230                  *  test reduces to:
4231                  */
4232                 if (TCP_SKB_CB(skb)->ack_seq != tp->snd_nxt)
4233                         goto reset_and_undo;
4234
4235                 if (tp->saw_tstamp && tp->rcv_tsecr &&
4236                     !between(tp->rcv_tsecr, tp->retrans_stamp,
4237                              tcp_time_stamp)) {
4238                         NET_INC_STATS_BH(PAWSActiveRejected);
4239                         goto reset_and_undo;
4240                 }
4241
4242                 /* Now ACK is acceptable.
4243                  *
4244                  * "If the RST bit is set
4245                  *    If the ACK was acceptable then signal the user "error:
4246                  *    connection reset", drop the segment, enter CLOSED state,
4247                  *    delete TCB, and return."
4248                  */
4249
4250                 if (th->rst) {
4251                         tcp_reset(sk);
4252                         goto discard;
4253                 }
4254
4255                 /* rfc793:
4256                  *   "fifth, if neither of the SYN or RST bits is set then
4257                  *    drop the segment and return."
4258                  *
4259                  *    See note below!
4260                  *                                        --ANK(990513)
4261                  */
4262                 if (!th->syn)
4263                         goto discard_and_undo;
4264
4265                 /* rfc793:
4266                  *   "If the SYN bit is on ...
4267                  *    are acceptable then ...
4268                  *    (our SYN has been ACKed), change the connection
4269                  *    state to ESTABLISHED..."
4270                  */
4271
4272                 TCP_ECN_rcv_synack(tp, th);
4273                 if (tp->ecn_flags&TCP_ECN_OK)
4274                         sk->sk_no_largesend = 1;
4275
4276                 tp->snd_wl1 = TCP_SKB_CB(skb)->seq;
4277                 tcp_ack(sk, skb, FLAG_SLOWPATH);
4278
4279                 /* Ok.. it's good. Set up sequence numbers and
4280                  * move to established.
4281                  */
4282                 tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1;
4283                 tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
4284
4285                 /* RFC1323: The window in SYN & SYN/ACK segments is
4286                  * never scaled.
4287                  */
4288                 tp->snd_wnd = ntohs(th->window);
4289                 tcp_init_wl(tp, TCP_SKB_CB(skb)->ack_seq, TCP_SKB_CB(skb)->seq);
4290
4291                 if (!tp->wscale_ok) {
4292                         tp->snd_wscale = tp->rcv_wscale = 0;
4293                         tp->window_clamp = min(tp->window_clamp, 65535U);
4294                 }
4295
4296                 if (tp->saw_tstamp) {
4297                         tp->tstamp_ok      = 1;
4298                         tp->tcp_header_len =
4299                                 sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
4300                         tp->advmss          -= TCPOLEN_TSTAMP_ALIGNED;
4301                         tcp_store_ts_recent(tp);
4302                 } else {
4303                         tp->tcp_header_len = sizeof(struct tcphdr);
4304                 }
4305
4306                 if (tp->sack_ok && sysctl_tcp_fack)
4307                         tp->sack_ok |= 2;
4308
4309                 tcp_sync_mss(sk, tp->pmtu_cookie);
4310                 tcp_initialize_rcv_mss(sk);
4311
4312                 /* Remember, tcp_poll() does not lock socket!
4313                  * Change state from SYN-SENT only after copied_seq
4314                  * is initialized. */
4315                 tp->copied_seq = tp->rcv_nxt;
4316                 mb();
4317                 tcp_set_state(sk, TCP_ESTABLISHED);
4318
4319                 /* Make sure socket is routed, for correct metrics.  */
4320                 tp->af_specific->rebuild_header(sk);
4321
4322                 tcp_init_metrics(sk);
4323
4324                 /* Prevent spurious tcp_cwnd_restart() on first data
4325                  * packet.
4326                  */
4327                 tp->lsndtime = tcp_time_stamp;
4328
4329                 tcp_init_buffer_space(sk);
4330
4331                 if (sock_flag(sk, SOCK_KEEPOPEN))
4332                         tcp_reset_keepalive_timer(sk, keepalive_time_when(tp));
4333
4334                 if (!tp->snd_wscale)
4335                         __tcp_fast_path_on(tp, tp->snd_wnd);
4336                 else
4337                         tp->pred_flags = 0;
4338
4339                 if (!sock_flag(sk, SOCK_DEAD)) {
4340                         sk->sk_state_change(sk);
4341                         sk_wake_async(sk, 0, POLL_OUT);
4342                 }
4343
4344                 if (tp->write_pending || tp->defer_accept || tp->ack.pingpong) {
4345                         /* Save one ACK. Data will be ready after
4346                          * several ticks, if write_pending is set.
4347                          *
4348                          * It may be deleted, but with this feature tcpdumps
4349                          * look so _wonderfully_ clever, that I was not able
4350                          * to stand against the temptation 8)     --ANK
4351                          */
4352                         tcp_schedule_ack(tp);
4353                         tp->ack.lrcvtime = tcp_time_stamp;
4354                         tp->ack.ato      = TCP_ATO_MIN;
4355                         tcp_incr_quickack(tp);
4356                         tcp_enter_quickack_mode(tp);
4357                         tcp_reset_xmit_timer(sk, TCP_TIME_DACK, TCP_DELACK_MAX);
4358
4359 discard:
4360                         __kfree_skb(skb);
4361                         return 0;
4362                 } else {
4363                         tcp_send_ack(sk);
4364                 }
4365                 return -1;
4366         }
4367
4368         /* No ACK in the segment */
4369
4370         if (th->rst) {
4371                 /* rfc793:
4372                  * "If the RST bit is set
4373                  *
4374                  *      Otherwise (no ACK) drop the segment and return."
4375                  */
4376
4377                 goto discard_and_undo;
4378         }
4379
4380         /* PAWS check. */
4381         if (tp->ts_recent_stamp && tp->saw_tstamp && tcp_paws_check(tp, 0))
4382                 goto discard_and_undo;
4383
4384         if (th->syn) {
4385                 /* We see SYN without ACK. It is attempt of
4386                  * simultaneous connect with crossed SYNs.
4387                  * Particularly, it can be connect to self.
4388                  */
4389                 tcp_set_state(sk, TCP_SYN_RECV);
4390
4391                 if (tp->saw_tstamp) {
4392                         tp->tstamp_ok = 1;
4393                         tcp_store_ts_recent(tp);
4394                         tp->tcp_header_len =
4395                                 sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
4396                 } else {
4397                         tp->tcp_header_len = sizeof(struct tcphdr);
4398                 }
4399
4400                 tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1;
4401                 tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
4402
4403                 /* RFC1323: The window in SYN & SYN/ACK segments is
4404                  * never scaled.
4405                  */
4406                 tp->snd_wnd    = ntohs(th->window);
4407                 tp->snd_wl1    = TCP_SKB_CB(skb)->seq;
4408                 tp->max_window = tp->snd_wnd;
4409
4410                 TCP_ECN_rcv_syn(tp, th);
4411                 if (tp->ecn_flags&TCP_ECN_OK)
4412                         sk->sk_no_largesend = 1;
4413
4414                 tcp_sync_mss(sk, tp->pmtu_cookie);
4415                 tcp_initialize_rcv_mss(sk);
4416
4417
4418                 tcp_send_synack(sk);
4419 #if 0
4420                 /* Note, we could accept data and URG from this segment.
4421                  * There are no obstacles to make this.
4422                  *
4423                  * However, if we ignore data in ACKless segments sometimes,
4424                  * we have no reasons to accept it sometimes.
4425                  * Also, seems the code doing it in step6 of tcp_rcv_state_process
4426                  * is not flawless. So, discard packet for sanity.
4427                  * Uncomment this return to process the data.
4428                  */
4429                 return -1;
4430 #else
4431                 goto discard;
4432 #endif
4433         }
4434         /* "fifth, if neither of the SYN or RST bits is set then
4435          * drop the segment and return."
4436          */
4437
4438 discard_and_undo:
4439         tcp_clear_options(tp);
4440         tp->mss_clamp = saved_clamp;
4441         goto discard;
4442
4443 reset_and_undo:
4444         tcp_clear_options(tp);
4445         tp->mss_clamp = saved_clamp;
4446         return 1;
4447 }
4448
4449
4450 /*
4451  *      This function implements the receiving procedure of RFC 793 for
4452  *      all states except ESTABLISHED and TIME_WAIT. 
4453  *      It's called from both tcp_v4_rcv and tcp_v6_rcv and should be
4454  *      address independent.
4455  */
4456         
4457 int tcp_rcv_state_process(struct sock *sk, struct sk_buff *skb,
4458                           struct tcphdr *th, unsigned len)
4459 {
4460         struct tcp_opt *tp = tcp_sk(sk);
4461         int queued = 0;
4462
4463         tp->saw_tstamp = 0;
4464
4465         switch (sk->sk_state) {
4466         case TCP_CLOSE:
4467                 goto discard;
4468
4469         case TCP_LISTEN:
4470                 if(th->ack)
4471                         return 1;
4472
4473                 if(th->rst)
4474                         goto discard;
4475
4476                 if(th->syn) {
4477                         if(tp->af_specific->conn_request(sk, skb) < 0)
4478                                 return 1;
4479
4480                         init_westwood(sk);
4481
4482                         /* Now we have several options: In theory there is 
4483                          * nothing else in the frame. KA9Q has an option to 
4484                          * send data with the syn, BSD accepts data with the
4485                          * syn up to the [to be] advertised window and 
4486                          * Solaris 2.1 gives you a protocol error. For now 
4487                          * we just ignore it, that fits the spec precisely 
4488                          * and avoids incompatibilities. It would be nice in
4489                          * future to drop through and process the data.
4490                          *
4491                          * Now that TTCP is starting to be used we ought to 
4492                          * queue this data.
4493                          * But, this leaves one open to an easy denial of
4494                          * service attack, and SYN cookies can't defend
4495                          * against this problem. So, we drop the data
4496                          * in the interest of security over speed.
4497                          */
4498                         goto discard;
4499                 }
4500                 goto discard;
4501
4502         case TCP_SYN_SENT:
4503                 init_westwood(sk);
4504
4505                 queued = tcp_rcv_synsent_state_process(sk, skb, th, len);
4506                 if (queued >= 0)
4507                         return queued;
4508
4509                 /* Do step6 onward by hand. */
4510                 tcp_urg(sk, skb, th);
4511                 __kfree_skb(skb);
4512                 tcp_data_snd_check(sk);
4513                 return 0;
4514         }
4515
4516         if (tcp_fast_parse_options(skb, th, tp) && tp->saw_tstamp &&
4517             tcp_paws_discard(tp, skb)) {
4518                 if (!th->rst) {
4519                         NET_INC_STATS_BH(PAWSEstabRejected);
4520                         tcp_send_dupack(sk, skb);
4521                         goto discard;
4522                 }
4523                 /* Reset is accepted even if it did not pass PAWS. */
4524         }
4525
4526         /* step 1: check sequence number */
4527         if (!tcp_sequence(tp, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq)) {
4528                 if (!th->rst)
4529                         tcp_send_dupack(sk, skb);
4530                 goto discard;
4531         }
4532
4533         /* step 2: check RST bit */
4534         if(th->rst) {
4535                 tcp_reset(sk);
4536                 goto discard;
4537         }
4538
4539         tcp_replace_ts_recent(tp, TCP_SKB_CB(skb)->seq);
4540
4541         /* step 3: check security and precedence [ignored] */
4542
4543         /*      step 4:
4544          *
4545          *      Check for a SYN in window.
4546          */
4547         if (th->syn && !before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
4548                 NET_INC_STATS_BH(TCPAbortOnSyn);
4549                 tcp_reset(sk);
4550                 return 1;
4551         }
4552
4553         /* step 5: check the ACK field */
4554         if (th->ack) {
4555                 int acceptable = tcp_ack(sk, skb, FLAG_SLOWPATH);
4556
4557                 switch(sk->sk_state) {
4558                 case TCP_SYN_RECV:
4559                         if (acceptable) {
4560                                 tp->copied_seq = tp->rcv_nxt;
4561                                 mb();
4562                                 tcp_set_state(sk, TCP_ESTABLISHED);
4563                                 sk->sk_state_change(sk);
4564
4565                                 /* Note, that this wakeup is only for marginal
4566                                  * crossed SYN case. Passively open sockets
4567                                  * are not waked up, because sk->sk_sleep ==
4568                                  * NULL and sk->sk_socket == NULL.
4569                                  */
4570                                 if (sk->sk_socket) {
4571                                         sk_wake_async(sk,0,POLL_OUT);
4572                                 }
4573
4574                                 tp->snd_una = TCP_SKB_CB(skb)->ack_seq;
4575                                 tp->snd_wnd = ntohs(th->window) <<
4576                                               tp->snd_wscale;
4577                                 tcp_init_wl(tp, TCP_SKB_CB(skb)->ack_seq,
4578                                             TCP_SKB_CB(skb)->seq);
4579
4580                                 /* tcp_ack considers this ACK as duplicate
4581                                  * and does not calculate rtt.
4582                                  * Fix it at least with timestamps.
4583                                  */
4584                                 if (tp->saw_tstamp && tp->rcv_tsecr &&
4585                                     !tp->srtt)
4586                                         tcp_ack_saw_tstamp(tp, 0);
4587
4588                                 if (tp->tstamp_ok)
4589                                         tp->advmss -= TCPOLEN_TSTAMP_ALIGNED;
4590
4591                                 /* Make sure socket is routed, for
4592                                  * correct metrics.
4593                                  */
4594                                 tp->af_specific->rebuild_header(sk);
4595
4596                                 tcp_init_metrics(sk);
4597
4598                                 /* Prevent spurious tcp_cwnd_restart() on
4599                                  * first data packet.
4600                                  */
4601                                 tp->lsndtime = tcp_time_stamp;
4602
4603                                 tcp_initialize_rcv_mss(sk);
4604                                 tcp_init_buffer_space(sk);
4605                                 tcp_fast_path_on(tp);
4606                         } else {
4607                                 return 1;
4608                         }
4609                         break;
4610
4611                 case TCP_FIN_WAIT1:
4612                         if (tp->snd_una == tp->write_seq) {
4613                                 tcp_set_state(sk, TCP_FIN_WAIT2);
4614                                 sk->sk_shutdown |= SEND_SHUTDOWN;
4615                                 dst_confirm(sk->sk_dst_cache);
4616
4617                                 if (!sock_flag(sk, SOCK_DEAD))
4618                                         /* Wake up lingering close() */
4619                                         sk->sk_state_change(sk);
4620                                 else {
4621                                         int tmo;
4622
4623                                         if (tp->linger2 < 0 ||
4624                                             (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
4625                                              after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt))) {
4626                                                 tcp_done(sk);
4627                                                 NET_INC_STATS_BH(TCPAbortOnData);
4628                                                 return 1;
4629                                         }
4630
4631                                         tmo = tcp_fin_time(tp);
4632                                         if (tmo > TCP_TIMEWAIT_LEN) {
4633                                                 tcp_reset_keepalive_timer(sk, tmo - TCP_TIMEWAIT_LEN);
4634                                         } else if (th->fin || sock_owned_by_user(sk)) {
4635                                                 /* Bad case. We could lose such FIN otherwise.
4636                                                  * It is not a big problem, but it looks confusing
4637                                                  * and not so rare event. We still can lose it now,
4638                                                  * if it spins in bh_lock_sock(), but it is really
4639                                                  * marginal case.
4640                                                  */
4641                                                 tcp_reset_keepalive_timer(sk, tmo);
4642                                         } else {
4643                                                 tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
4644                                                 goto discard;
4645                                         }
4646                                 }
4647                         }
4648                         break;
4649
4650                 case TCP_CLOSING:
4651                         if (tp->snd_una == tp->write_seq) {
4652                                 tcp_time_wait(sk, TCP_TIME_WAIT, 0);
4653                                 goto discard;
4654                         }
4655                         break;
4656
4657                 case TCP_LAST_ACK:
4658                         if (tp->snd_una == tp->write_seq) {
4659                                 tcp_update_metrics(sk);
4660                                 tcp_done(sk);
4661                                 goto discard;
4662                         }
4663                         break;
4664                 }
4665         } else
4666                 goto discard;
4667
4668         /* step 6: check the URG bit */
4669         tcp_urg(sk, skb, th);
4670
4671         /* step 7: process the segment text */
4672         switch (sk->sk_state) {
4673         case TCP_CLOSE_WAIT:
4674         case TCP_CLOSING:
4675         case TCP_LAST_ACK:
4676                 if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt))
4677                         break;
4678         case TCP_FIN_WAIT1:
4679         case TCP_FIN_WAIT2:
4680                 /* RFC 793 says to queue data in these states,
4681                  * RFC 1122 says we MUST send a reset. 
4682                  * BSD 4.4 also does reset.
4683                  */
4684                 if (sk->sk_shutdown & RCV_SHUTDOWN) {
4685                         if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
4686                             after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt)) {
4687                                 NET_INC_STATS_BH(TCPAbortOnData);
4688                                 tcp_reset(sk);
4689                                 return 1;
4690                         }
4691                 }
4692                 /* Fall through */
4693         case TCP_ESTABLISHED: 
4694                 tcp_data_queue(sk, skb);
4695                 queued = 1;
4696                 break;
4697         }
4698
4699         /* tcp_data could move socket to TIME-WAIT */
4700         if (sk->sk_state != TCP_CLOSE) {
4701                 tcp_data_snd_check(sk);
4702                 tcp_ack_snd_check(sk);
4703         }
4704
4705         if (!queued) { 
4706 discard:
4707                 __kfree_skb(skb);
4708         }
4709         return 0;
4710 }
4711
4712 EXPORT_SYMBOL(sysctl_tcp_ecn);
4713 EXPORT_SYMBOL(sysctl_tcp_reordering);
4714 EXPORT_SYMBOL(tcp_cwnd_application_limited);
4715 EXPORT_SYMBOL(tcp_parse_options);
4716 EXPORT_SYMBOL(tcp_rcv_established);
4717 EXPORT_SYMBOL(tcp_rcv_state_process);