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