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