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