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