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