File: /usr/src/linux/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.236 2001/09/18 22:29:09 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      */
64     
65     #include <linux/config.h>
66     #include <linux/mm.h>
67     #include <linux/sysctl.h>
68     #include <net/tcp.h>
69     #include <net/inet_common.h>
70     #include <linux/ipsec.h>
71     
72     
73     /* These are on by default so the code paths get tested.
74      * For the final 2.2 this may be undone at our discretion. -DaveM
75      */
76     int sysctl_tcp_timestamps = 1;
77     int sysctl_tcp_window_scaling = 1;
78     int sysctl_tcp_sack = 1;
79     int sysctl_tcp_fack = 1;
80     int sysctl_tcp_reordering = TCP_FASTRETRANS_THRESH;
81     #ifdef CONFIG_INET_ECN
82     int sysctl_tcp_ecn = 1;
83     #else
84     int sysctl_tcp_ecn = 0;
85     #endif
86     int sysctl_tcp_dsack = 1;
87     int sysctl_tcp_app_win = 31;
88     int sysctl_tcp_adv_win_scale = 2;
89     
90     int sysctl_tcp_stdurg = 0;
91     int sysctl_tcp_rfc1337 = 0;
92     int sysctl_tcp_max_orphans = NR_FILE;
93     
94     #define FLAG_DATA		0x01 /* Incoming frame contained data.		*/
95     #define FLAG_WIN_UPDATE		0x02 /* Incoming ACK was a window update.	*/
96     #define FLAG_DATA_ACKED		0x04 /* This ACK acknowledged new data.		*/
97     #define FLAG_RETRANS_DATA_ACKED	0x08 /* "" "" some of which was retransmitted.	*/
98     #define FLAG_SYN_ACKED		0x10 /* This ACK acknowledged SYN.		*/
99     #define FLAG_DATA_SACKED	0x20 /* New SACK.				*/
100     #define FLAG_ECE		0x40 /* ECE in this ACK				*/
101     #define FLAG_DATA_LOST		0x80 /* SACK detected data lossage.		*/
102     #define FLAG_SLOWPATH		0x100 /* Do not skip RFC checks for window update.*/
103     
104     #define FLAG_ACKED		(FLAG_DATA_ACKED|FLAG_SYN_ACKED)
105     #define FLAG_NOT_DUP		(FLAG_DATA|FLAG_WIN_UPDATE|FLAG_ACKED)
106     #define FLAG_CA_ALERT		(FLAG_DATA_SACKED|FLAG_ECE)
107     #define FLAG_FORWARD_PROGRESS	(FLAG_ACKED|FLAG_DATA_SACKED)
108     
109     #define IsReno(tp) ((tp)->sack_ok == 0)
110     #define IsFack(tp) ((tp)->sack_ok & 2)
111     #define IsDSack(tp) ((tp)->sack_ok & 4)
112     
113     #define TCP_REMNANT (TCP_FLAG_FIN|TCP_FLAG_URG|TCP_FLAG_SYN|TCP_FLAG_PSH)
114     
115     /* Adapt the MSS value used to make delayed ack decision to the 
116      * real world.
117      */ 
118     static __inline__ void tcp_measure_rcv_mss(struct tcp_opt *tp, struct sk_buff *skb)
119     {
120     	unsigned int len, lss;
121     
122     	lss = tp->ack.last_seg_size; 
123     	tp->ack.last_seg_size = 0; 
124     
125     	/* skb->len may jitter because of SACKs, even if peer
126     	 * sends good full-sized frames.
127     	 */
128     	len = skb->len;
129     	if (len >= tp->ack.rcv_mss) {
130     		tp->ack.rcv_mss = len;
131     		/* Dubious? Rather, it is final cut. 8) */
132     		if (tcp_flag_word(skb->h.th)&TCP_REMNANT)
133     			tp->ack.pending |= TCP_ACK_PUSHED;
134     	} else {
135     		/* Otherwise, we make more careful check taking into account,
136     		 * that SACKs block is variable.
137     		 *
138     		 * "len" is invariant segment length, including TCP header.
139     		 */
140     		len += skb->data - skb->h.raw;
141     		if (len >= TCP_MIN_RCVMSS + sizeof(struct tcphdr) ||
142     		    /* If PSH is not set, packet should be
143     		     * full sized, provided peer TCP is not badly broken.
144     		     * This observation (if it is correct 8)) allows
145     		     * to handle super-low mtu links fairly.
146     		     */
147     		    (len >= TCP_MIN_MSS + sizeof(struct tcphdr) &&
148     		     !(tcp_flag_word(skb->h.th)&TCP_REMNANT))) {
149     			/* Subtract also invariant (if peer is RFC compliant),
150     			 * tcp header plus fixed timestamp option length.
151     			 * Resulting "len" is MSS free of SACK jitter.
152     			 */
153     			len -= tp->tcp_header_len;
154     			tp->ack.last_seg_size = len;
155     			if (len == lss) {
156     				tp->ack.rcv_mss = len;
157     				return;
158     			}
159     		}
160     		tp->ack.pending |= TCP_ACK_PUSHED;
161     	}
162     }
163     
164     static void tcp_incr_quickack(struct tcp_opt *tp)
165     {
166     	unsigned quickacks = tp->rcv_wnd/(2*tp->ack.rcv_mss);
167     
168     	if (quickacks==0)
169     		quickacks=2;
170     	if (quickacks > tp->ack.quick)
171     		tp->ack.quick = min_t(unsigned int, quickacks, TCP_MAX_QUICKACKS);
172     }
173     
174     void tcp_enter_quickack_mode(struct tcp_opt *tp)
175     {
176     	tcp_incr_quickack(tp);
177     	tp->ack.pingpong = 0;
178     	tp->ack.ato = TCP_ATO_MIN;
179     }
180     
181     /* Send ACKs quickly, if "quick" count is not exhausted
182      * and the session is not interactive.
183      */
184     
185     static __inline__ int tcp_in_quickack_mode(struct tcp_opt *tp)
186     {
187     	return (tp->ack.quick && !tp->ack.pingpong);
188     }
189     
190     /* Buffer size and advertised window tuning.
191      *
192      * 1. Tuning sk->sndbuf, when connection enters established state.
193      */
194     
195     static void tcp_fixup_sndbuf(struct sock *sk)
196     {
197     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
198     	int sndmem = tp->mss_clamp+MAX_TCP_HEADER+16+sizeof(struct sk_buff);
199     
200     	if (sk->sndbuf < 3*sndmem)
201     		sk->sndbuf = min_t(int, 3*sndmem, sysctl_tcp_wmem[2]);
202     }
203     
204     /* 2. Tuning advertised window (window_clamp, rcv_ssthresh)
205      *
206      * All tcp_full_space() is split to two parts: "network" buffer, allocated
207      * forward and advertised in receiver window (tp->rcv_wnd) and
208      * "application buffer", required to isolate scheduling/application
209      * latencies from network.
210      * window_clamp is maximal advertised window. It can be less than
211      * tcp_full_space(), in this case tcp_full_space() - window_clamp
212      * is reserved for "application" buffer. The less window_clamp is
213      * the smoother our behaviour from viewpoint of network, but the lower
214      * throughput and the higher sensitivity of the connection to losses. 8)
215      *
216      * rcv_ssthresh is more strict window_clamp used at "slow start"
217      * phase to predict further behaviour of this connection.
218      * It is used for two goals:
219      * - to enforce header prediction at sender, even when application
220      *   requires some significant "application buffer". It is check #1.
221      * - to prevent pruning of receive queue because of misprediction
222      *   of receiver window. Check #2.
223      *
224      * The scheme does not work when sender sends good segments opening
225      * window and then starts to feed us spagetti. But it should work
226      * in common situations. Otherwise, we have to rely on queue collapsing.
227      */
228     
229     /* Slow part of check#2. */
230     static int
231     __tcp_grow_window(struct sock *sk, struct tcp_opt *tp, struct sk_buff *skb)
232     {
233     	/* Optimize this! */
234     	int truesize = tcp_win_from_space(skb->truesize)/2;
235     	int window = tcp_full_space(sk)/2;
236     
237     	while (tp->rcv_ssthresh <= window) {
238     		if (truesize <= skb->len)
239     			return 2*tp->ack.rcv_mss;
240     
241     		truesize >>= 1;
242     		window >>= 1;
243     	}
244     	return 0;
245     }
246     
247     static __inline__ void
248     tcp_grow_window(struct sock *sk, struct tcp_opt *tp, struct sk_buff *skb)
249     {
250     	/* Check #1 */
251     	if (tp->rcv_ssthresh < tp->window_clamp &&
252     	    (int)tp->rcv_ssthresh < tcp_space(sk) &&
253     	    !tcp_memory_pressure) {
254     		int incr;
255     
256     		/* Check #2. Increase window, if skb with such overhead
257     		 * will fit to rcvbuf in future.
258     		 */
259     		if (tcp_win_from_space(skb->truesize) <= skb->len)
260     			incr = 2*tp->advmss;
261     		else
262     			incr = __tcp_grow_window(sk, tp, skb);
263     
264     		if (incr) {
265     			tp->rcv_ssthresh = min_t(u32, tp->rcv_ssthresh + incr, tp->window_clamp);
266     			tp->ack.quick |= 1;
267     		}
268     	}
269     }
270     
271     /* 3. Tuning rcvbuf, when connection enters established state. */
272     
273     static void tcp_fixup_rcvbuf(struct sock *sk)
274     {
275     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
276     	int rcvmem = tp->advmss+MAX_TCP_HEADER+16+sizeof(struct sk_buff);
277     
278     	/* Try to select rcvbuf so that 4 mss-sized segments
279     	 * will fit to window and correspoding skbs will fit to our rcvbuf.
280     	 * (was 3; 4 is minimum to allow fast retransmit to work.)
281     	 */
282     	while (tcp_win_from_space(rcvmem) < tp->advmss)
283     		rcvmem += 128;
284     	if (sk->rcvbuf < 4*rcvmem)
285     		sk->rcvbuf = min_t(int, 4*rcvmem, sysctl_tcp_rmem[2]);
286     }
287     
288     /* 4. Try to fixup all. It is made iimediately after connection enters
289      *    established state.
290      */
291     static void tcp_init_buffer_space(struct sock *sk)
292     {
293     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
294     	int maxwin;
295     
296     	if (!(sk->userlocks&SOCK_RCVBUF_LOCK))
297     		tcp_fixup_rcvbuf(sk);
298     	if (!(sk->userlocks&SOCK_SNDBUF_LOCK))
299     		tcp_fixup_sndbuf(sk);
300     
301     	maxwin = tcp_full_space(sk);
302     
303     	if (tp->window_clamp >= maxwin) {
304     		tp->window_clamp = maxwin;
305     
306     		if (sysctl_tcp_app_win && maxwin>4*tp->advmss)
307     			tp->window_clamp = max_t(u32, maxwin-(maxwin>>sysctl_tcp_app_win), 4*tp->advmss);
308     	}
309     
310     	/* Force reservation of one segment. */
311     	if (sysctl_tcp_app_win &&
312     	    tp->window_clamp > 2*tp->advmss &&
313     	    tp->window_clamp + tp->advmss > maxwin)
314     		tp->window_clamp = max_t(u32, 2*tp->advmss, maxwin-tp->advmss);
315     
316     	tp->rcv_ssthresh = min_t(u32, tp->rcv_ssthresh, tp->window_clamp);
317     	tp->snd_cwnd_stamp = tcp_time_stamp;
318     }
319     
320     /* 5. Recalculate window clamp after socket hit its memory bounds. */
321     static void tcp_clamp_window(struct sock *sk, struct tcp_opt *tp)
322     {
323     	struct sk_buff *skb;
324     	int app_win = tp->rcv_nxt - tp->copied_seq;
325     	int ofo_win = 0;
326     
327     	tp->ack.quick = 0;
328     
329     	skb_queue_walk(&tp->out_of_order_queue, skb) {
330     		ofo_win += skb->len;
331     	}
332     
333     	/* If overcommit is due to out of order segments,
334     	 * do not clamp window. Try to expand rcvbuf instead.
335     	 */
336     	if (ofo_win) {
337     		if (sk->rcvbuf < sysctl_tcp_rmem[2] &&
338     		    !(sk->userlocks&SOCK_RCVBUF_LOCK) &&
339     		    !tcp_memory_pressure &&
340     		    atomic_read(&tcp_memory_allocated) < sysctl_tcp_mem[0])
341     			sk->rcvbuf = min_t(int, atomic_read(&sk->rmem_alloc), sysctl_tcp_rmem[2]);
342     	}
343     	if (atomic_read(&sk->rmem_alloc) > sk->rcvbuf) {
344     		app_win += ofo_win;
345     		if (atomic_read(&sk->rmem_alloc) >= 2*sk->rcvbuf)
346     			app_win >>= 1;
347     		if (app_win > tp->ack.rcv_mss)
348     			app_win -= tp->ack.rcv_mss;
349     		app_win = max_t(unsigned int, app_win, 2*tp->advmss);
350     
351     		if (!ofo_win)
352     			tp->window_clamp = min_t(u32, tp->window_clamp, app_win);
353     		tp->rcv_ssthresh = min_t(u32, tp->window_clamp, 2*tp->advmss);
354     	}
355     }
356     
357     /* There is something which you must keep in mind when you analyze the
358      * behavior of the tp->ato delayed ack timeout interval.  When a
359      * connection starts up, we want to ack as quickly as possible.  The
360      * problem is that "good" TCP's do slow start at the beginning of data
361      * transmission.  The means that until we send the first few ACK's the
362      * sender will sit on his end and only queue most of his data, because
363      * he can only send snd_cwnd unacked packets at any given time.  For
364      * each ACK we send, he increments snd_cwnd and transmits more of his
365      * queue.  -DaveM
366      */
367     static void tcp_event_data_recv(struct sock *sk, struct tcp_opt *tp, struct sk_buff *skb)
368     {
369     	u32 now;
370     
371     	tcp_schedule_ack(tp);
372     
373     	tcp_measure_rcv_mss(tp, skb);
374     
375     	now = tcp_time_stamp;
376     
377     	if (!tp->ack.ato) {
378     		/* The _first_ data packet received, initialize
379     		 * delayed ACK engine.
380     		 */
381     		tcp_incr_quickack(tp);
382     		tp->ack.ato = TCP_ATO_MIN;
383     	} else {
384     		int m = now - tp->ack.lrcvtime;
385     
386     		if (m <= TCP_ATO_MIN/2) {
387     			/* The fastest case is the first. */
388     			tp->ack.ato = (tp->ack.ato>>1) + TCP_ATO_MIN/2;
389     		} else if (m < tp->ack.ato) {
390     			tp->ack.ato = (tp->ack.ato>>1) + m;
391     			if (tp->ack.ato > tp->rto)
392     				tp->ack.ato = tp->rto;
393     		} else if (m > tp->rto) {
394     			/* Too long gap. Apparently sender falled to
395     			 * restart window, so that we send ACKs quickly.
396     			 */
397     			tcp_incr_quickack(tp);
398     			tcp_mem_reclaim(sk);
399     		}
400     	}
401     	tp->ack.lrcvtime = now;
402     
403     	TCP_ECN_check_ce(tp, skb);
404     
405     	if (skb->len >= 128)
406     		tcp_grow_window(sk, tp, skb);
407     }
408     
409     /* Called to compute a smoothed rtt estimate. The data fed to this
410      * routine either comes from timestamps, or from segments that were
411      * known _not_ to have been retransmitted [see Karn/Partridge
412      * Proceedings SIGCOMM 87]. The algorithm is from the SIGCOMM 88
413      * piece by Van Jacobson.
414      * NOTE: the next three routines used to be one big routine.
415      * To save cycles in the RFC 1323 implementation it was better to break
416      * it up into three procedures. -- erics
417      */
418     static __inline__ void tcp_rtt_estimator(struct tcp_opt *tp, __u32 mrtt)
419     {
420     	long m = mrtt; /* RTT */
421     
422     	/*	The following amusing code comes from Jacobson's
423     	 *	article in SIGCOMM '88.  Note that rtt and mdev
424     	 *	are scaled versions of rtt and mean deviation.
425     	 *	This is designed to be as fast as possible 
426     	 *	m stands for "measurement".
427     	 *
428     	 *	On a 1990 paper the rto value is changed to:
429     	 *	RTO = rtt + 4 * mdev
430     	 *
431     	 * Funny. This algorithm seems to be very broken.
432     	 * These formulae increase RTO, when it should be decreased, increase
433     	 * too slowly, when it should be incresed fastly, decrease too fastly
434     	 * etc. I guess in BSD RTO takes ONE value, so that it is absolutely
435     	 * does not matter how to _calculate_ it. Seems, it was trap
436     	 * that VJ failed to avoid. 8)
437     	 */
438     	if(m == 0)
439     		m = 1;
440     	if (tp->srtt != 0) {
441     		m -= (tp->srtt >> 3);	/* m is now error in rtt est */
442     		tp->srtt += m;		/* rtt = 7/8 rtt + 1/8 new */
443     		if (m < 0) {
444     			m = -m;		/* m is now abs(error) */
445     			m -= (tp->mdev >> 2);   /* similar update on mdev */
446     			/* This is similar to one of Eifel findings.
447     			 * Eifel blocks mdev updates when rtt decreases.
448     			 * This solution is a bit different: we use finer gain
449     			 * for mdev in this case (alpha*beta).
450     			 * Like Eifel it also prevents growth of rto,
451     			 * but also it limits too fast rto decreases,
452     			 * happening in pure Eifel.
453     			 */
454     			if (m > 0)
455     				m >>= 3;
456     		} else {
457     			m -= (tp->mdev >> 2);   /* similar update on mdev */
458     		}
459     		tp->mdev += m;	    	/* mdev = 3/4 mdev + 1/4 new */
460     		if (tp->mdev > tp->mdev_max) {
461     			tp->mdev_max = tp->mdev;
462     			if (tp->mdev_max > tp->rttvar)
463     				tp->rttvar = tp->mdev_max;
464     		}
465     		if (after(tp->snd_una, tp->rtt_seq)) {
466     			if (tp->mdev_max < tp->rttvar)
467     				tp->rttvar -= (tp->rttvar-tp->mdev_max)>>2;
468     			tp->rtt_seq = tp->snd_una;
469     			tp->mdev_max = TCP_RTO_MIN;
470     		}
471     	} else {
472     		/* no previous measure. */
473     		tp->srtt = m<<3;	/* take the measured time to be rtt */
474     		tp->mdev = m<<2;	/* make sure rto = 3*rtt */
475     		tp->mdev_max = tp->rttvar = max_t(u32, tp->mdev, TCP_RTO_MIN);
476     		tp->rtt_seq = tp->snd_nxt;
477     	}
478     }
479     
480     /* Calculate rto without backoff.  This is the second half of Van Jacobson's
481      * routine referred to above.
482      */
483     static __inline__ void tcp_set_rto(struct tcp_opt *tp)
484     {
485     	/* Old crap is replaced with new one. 8)
486     	 *
487     	 * More seriously:
488     	 * 1. If rtt variance happened to be less 50msec, it is hallucination.
489     	 *    It cannot be less due to utterly erratic ACK generation made
490     	 *    at least by solaris and freebsd. "Erratic ACKs" has _nothing_
491     	 *    to do with delayed acks, because at cwnd>2 true delack timeout
492     	 *    is invisible. Actually, Linux-2.4 also generates erratic
493     	 *    ACKs in some curcumstances.
494     	 */
495     	tp->rto = (tp->srtt >> 3) + tp->rttvar;
496     
497     	/* 2. Fixups made earlier cannot be right.
498     	 *    If we do not estimate RTO correctly without them,
499     	 *    all the algo is pure shit and should be replaced
500     	 *    with correct one. It is exaclty, which we pretend to do.
501     	 */
502     }
503     
504     /* NOTE: clamping at TCP_RTO_MIN is not required, current algo
505      * guarantees that rto is higher.
506      */
507     static __inline__ void tcp_bound_rto(struct tcp_opt *tp)
508     {
509     	if (tp->rto > TCP_RTO_MAX)
510     		tp->rto = TCP_RTO_MAX;
511     }
512     
513     /* Save metrics learned by this TCP session.
514        This function is called only, when TCP finishes successfully
515        i.e. when it enters TIME-WAIT or goes from LAST-ACK to CLOSE.
516      */
517     void tcp_update_metrics(struct sock *sk)
518     {
519     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
520     	struct dst_entry *dst = __sk_dst_get(sk);
521     
522     	dst_confirm(dst);
523     
524     	if (dst && (dst->flags&DST_HOST)) {
525     		int m;
526     
527     		if (tp->backoff || !tp->srtt) {
528     			/* This session failed to estimate rtt. Why?
529     			 * Probably, no packets returned in time.
530     			 * Reset our results.
531     			 */
532     			if (!(dst->mxlock&(1<<RTAX_RTT)))
533     				dst->rtt = 0;
534     			return;
535     		}
536     
537     		m = dst->rtt - tp->srtt;
538     
539     		/* If newly calculated rtt larger than stored one,
540     		 * store new one. Otherwise, use EWMA. Remember,
541     		 * rtt overestimation is always better than underestimation.
542     		 */
543     		if (!(dst->mxlock&(1<<RTAX_RTT))) {
544     			if (m <= 0)
545     				dst->rtt = tp->srtt;
546     			else
547     				dst->rtt -= (m>>3);
548     		}
549     
550     		if (!(dst->mxlock&(1<<RTAX_RTTVAR))) {
551     			if (m < 0)
552     				m = -m;
553     
554     			/* Scale deviation to rttvar fixed point */
555     			m >>= 1;
556     			if (m < tp->mdev)
557     				m = tp->mdev;
558     
559     			if (m >= dst->rttvar)
560     				dst->rttvar = m;
561     			else
562     				dst->rttvar -= (dst->rttvar - m)>>2;
563     		}
564     
565     		if (tp->snd_ssthresh >= 0xFFFF) {
566     			/* Slow start still did not finish. */
567     			if (dst->ssthresh &&
568     			    !(dst->mxlock&(1<<RTAX_SSTHRESH)) &&
569     			    (tp->snd_cwnd>>1) > dst->ssthresh)
570     				dst->ssthresh = (tp->snd_cwnd>>1);
571     			if (!(dst->mxlock&(1<<RTAX_CWND)) &&
572     			    tp->snd_cwnd > dst->cwnd)
573     				dst->cwnd = tp->snd_cwnd;
574     		} else if (tp->snd_cwnd > tp->snd_ssthresh &&
575     			   tp->ca_state == TCP_CA_Open) {
576     			/* Cong. avoidance phase, cwnd is reliable. */
577     			if (!(dst->mxlock&(1<<RTAX_SSTHRESH)))
578     				dst->ssthresh = max_t(u32, tp->snd_cwnd>>1, tp->snd_ssthresh);
579     			if (!(dst->mxlock&(1<<RTAX_CWND)))
580     				dst->cwnd = (dst->cwnd + tp->snd_cwnd)>>1;
581     		} else {
582     			/* Else slow start did not finish, cwnd is non-sense,
583     			   ssthresh may be also invalid.
584     			 */
585     			if (!(dst->mxlock&(1<<RTAX_CWND)))
586     				dst->cwnd = (dst->cwnd + tp->snd_ssthresh)>>1;
587     			if (dst->ssthresh &&
588     			    !(dst->mxlock&(1<<RTAX_SSTHRESH)) &&
589     			    tp->snd_ssthresh > dst->ssthresh)
590     				dst->ssthresh = tp->snd_ssthresh;
591     		}
592     
593     		if (!(dst->mxlock&(1<<RTAX_REORDERING))) {
594     			if (dst->reordering < tp->reordering &&
595     			    tp->reordering != sysctl_tcp_reordering)
596     				dst->reordering = tp->reordering;
597     		}
598     	}
599     }
600     
601     /* Increase initial CWND conservatively: if estimated
602      * RTT is low enough (<20msec) or if we have some preset ssthresh.
603      *
604      * Numbers are taken from RFC2414.
605      */
606     __u32 tcp_init_cwnd(struct tcp_opt *tp)
607     {
608     	__u32 cwnd;
609     
610     	if (tp->mss_cache > 1460)
611     		return 2;
612     
613     	cwnd = (tp->mss_cache > 1095) ? 3 : 4;
614     
615     	if (!tp->srtt || (tp->snd_ssthresh >= 0xFFFF && tp->srtt > ((HZ/50)<<3)))
616     		cwnd = 2;
617     	else if (cwnd > tp->snd_ssthresh)
618     		cwnd = tp->snd_ssthresh;
619     
620     	return min_t(u32, cwnd, tp->snd_cwnd_clamp);
621     }
622     
623     /* Initialize metrics on socket. */
624     
625     static void tcp_init_metrics(struct sock *sk)
626     {
627     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
628     	struct dst_entry *dst = __sk_dst_get(sk);
629     
630     	if (dst == NULL)
631     		goto reset;
632     
633     	dst_confirm(dst);
634     
635     	if (dst->mxlock&(1<<RTAX_CWND))
636     		tp->snd_cwnd_clamp = dst->cwnd;
637     	if (dst->ssthresh) {
638     		tp->snd_ssthresh = dst->ssthresh;
639     		if (tp->snd_ssthresh > tp->snd_cwnd_clamp)
640     			tp->snd_ssthresh = tp->snd_cwnd_clamp;
641     	}
642     	if (dst->reordering && tp->reordering != dst->reordering) {
643     		tp->sack_ok &= ~2;
644     		tp->reordering = dst->reordering;
645     	}
646     
647     	if (dst->rtt == 0)
648     		goto reset;
649     
650     	if (!tp->srtt && dst->rtt < (TCP_TIMEOUT_INIT<<3))
651     		goto reset;
652     
653     	/* Initial rtt is determined from SYN,SYN-ACK.
654     	 * The segment is small and rtt may appear much
655     	 * less than real one. Use per-dst memory
656     	 * to make it more realistic.
657     	 *
658     	 * A bit of theory. RTT is time passed after "normal" sized packet
659     	 * is sent until it is ACKed. In normal curcumstances sending small
660     	 * packets force peer to delay ACKs and calculation is correct too.
661     	 * The algorithm is adaptive and, provided we follow specs, it
662     	 * NEVER underestimate RTT. BUT! If peer tries to make some clever
663     	 * tricks sort of "quick acks" for time long enough to decrease RTT
664     	 * to low value, and then abruptly stops to do it and starts to delay
665     	 * ACKs, wait for troubles.
666     	 */
667     	if (dst->rtt > tp->srtt)
668     		tp->srtt = dst->rtt;
669     	if (dst->rttvar > tp->mdev) {
670     		tp->mdev = dst->rttvar;
671     		tp->mdev_max = tp->rttvar = max_t(u32, tp->mdev, TCP_RTO_MIN);
672     	}
673     	tcp_set_rto(tp);
674     	tcp_bound_rto(tp);
675     	if (tp->rto < TCP_TIMEOUT_INIT && !tp->saw_tstamp)
676     		goto reset;
677     	tp->snd_cwnd = tcp_init_cwnd(tp);
678     	tp->snd_cwnd_stamp = tcp_time_stamp;
679     	return;
680     
681     reset:
682     	/* Play conservative. If timestamps are not
683     	 * supported, TCP will fail to recalculate correct
684     	 * rtt, if initial rto is too small. FORGET ALL AND RESET!
685     	 */
686     	if (!tp->saw_tstamp && tp->srtt) {
687     		tp->srtt = 0;
688     		tp->mdev = tp->mdev_max = tp->rttvar = TCP_TIMEOUT_INIT;
689     		tp->rto = TCP_TIMEOUT_INIT;
690     	}
691     }
692     
693     static void tcp_update_reordering(struct tcp_opt *tp, int metric, int ts)
694     {
695     	if (metric > tp->reordering) {
696     		tp->reordering = min_t(unsigned int, TCP_MAX_REORDERING, metric);
697     
698     		/* This exciting event is worth to be remembered. 8) */
699     		if (ts)
700     			NET_INC_STATS_BH(TCPTSReorder);
701     		else if (IsReno(tp))
702     			NET_INC_STATS_BH(TCPRenoReorder);
703     		else if (IsFack(tp))
704     			NET_INC_STATS_BH(TCPFACKReorder);
705     		else
706     			NET_INC_STATS_BH(TCPSACKReorder);
707     #if FASTRETRANS_DEBUG > 1
708     		printk(KERN_DEBUG "Disorder%d %d %u f%u s%u rr%d\n",
709     		       tp->sack_ok, tp->ca_state,
710     		       tp->reordering, tp->fackets_out, tp->sacked_out,
711     		       tp->undo_marker ? tp->undo_retrans : 0);
712     #endif
713     		/* Disable FACK yet. */
714     		tp->sack_ok &= ~2;
715     	}
716     }
717     
718     /* This procedure tags the retransmission queue when SACKs arrive.
719      *
720      * We have three tag bits: SACKED(S), RETRANS(R) and LOST(L).
721      * Packets in queue with these bits set are counted in variables
722      * sacked_out, retrans_out and lost_out, correspondingly.
723      *
724      * Valid combinations are:
725      * Tag  InFlight	Description
726      * 0	1		- orig segment is in flight.
727      * S	0		- nothing flies, orig reached receiver.
728      * L	0		- nothing flies, orig lost by net.
729      * R	2		- both orig and retransmit are in flight.
730      * L|R	1		- orig is lost, retransmit is in flight.
731      * S|R  1		- orig reached receiver, retrans is still in flight.
732      * (L|S|R is logically valid, it could occur when L|R is sacked,
733      *  but it is equivalent to plain S and code short-curcuits it to S.
734      *  L|S is logically invalid, it would mean -1 packet in flight 8))
735      *
736      * These 6 states form finite state machine, controlled by the following events:
737      * 1. New ACK (+SACK) arrives. (tcp_sacktag_write_queue())
738      * 2. Retransmission. (tcp_retransmit_skb(), tcp_xmit_retransmit_queue())
739      * 3. Loss detection event of one of three flavors:
740      *	A. Scoreboard estimator decided the packet is lost.
741      *	   A'. Reno "three dupacks" marks head of queue lost.
742      *	   A''. Its FACK modfication, head until snd.fack is lost.
743      *	B. SACK arrives sacking data transmitted after never retransmitted
744      *	   hole was sent out.
745      *	C. SACK arrives sacking SND.NXT at the moment, when the
746      *	   segment was retransmitted.
747      * 4. D-SACK added new rule: D-SACK changes any tag to S.
748      *
749      * It is pleasant to note, that state diagram turns out to be commutative,
750      * so that we are allowed not to be bothered by order of our actions,
751      * when multiple events arrive simultaneously. (see the function below).
752      *
753      * Reordering detection.
754      * --------------------
755      * Reordering metric is maximal distance, which a packet can be displaced
756      * in packet stream. With SACKs we can estimate it:
757      *
758      * 1. SACK fills old hole and the corresponding segment was not
759      *    ever retransmitted -> reordering. Alas, we cannot use it
760      *    when segment was retransmitted.
761      * 2. The last flaw is solved with D-SACK. D-SACK arrives
762      *    for retransmitted and already SACKed segment -> reordering..
763      * Both of these heuristics are not used in Loss state, when we cannot
764      * account for retransmits accurately.
765      */
766     static int
767     tcp_sacktag_write_queue(struct sock *sk, struct sk_buff *ack_skb, u32 prior_snd_una)
768     {
769     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
770     	unsigned char *ptr = ack_skb->h.raw + TCP_SKB_CB(ack_skb)->sacked;
771     	struct tcp_sack_block *sp = (struct tcp_sack_block *)(ptr+2);
772     	int num_sacks = (ptr[1] - TCPOLEN_SACK_BASE)>>3;
773     	int reord = tp->packets_out;
774     	int prior_fackets;
775     	u32 lost_retrans = 0;
776     	int flag = 0;
777     	int i;
778     
779     	if (!tp->sacked_out)
780     		tp->fackets_out = 0;
781     	prior_fackets = tp->fackets_out;
782     
783     	for (i=0; i<num_sacks; i++, sp++) {
784     		struct sk_buff *skb;
785     		__u32 start_seq = ntohl(sp->start_seq);
786     		__u32 end_seq = ntohl(sp->end_seq);
787     		int fack_count = 0;
788     		int dup_sack = 0;
789     
790     		/* Check for D-SACK. */
791     		if (i == 0) {
792     			u32 ack = TCP_SKB_CB(ack_skb)->ack_seq;
793     
794     			if (before(start_seq, ack)) {
795     				dup_sack = 1;
796     				tp->sack_ok |= 4;
797     				NET_INC_STATS_BH(TCPDSACKRecv);
798     			} else if (num_sacks > 1 &&
799     				   !after(end_seq, ntohl(sp[1].end_seq)) &&
800     				   !before(start_seq, ntohl(sp[1].start_seq))) {
801     				dup_sack = 1;
802     				tp->sack_ok |= 4;
803     				NET_INC_STATS_BH(TCPDSACKOfoRecv);
804     			}
805     
806     			/* D-SACK for already forgotten data...
807     			 * Do dumb counting. */
808     			if (dup_sack &&
809     			    !after(end_seq, prior_snd_una) &&
810     			    after(end_seq, tp->undo_marker))
811     				tp->undo_retrans--;
812     
813     			/* Eliminate too old ACKs, but take into
814     			 * account more or less fresh ones, they can
815     			 * contain valid SACK info.
816     			 */
817     			if (before(ack, prior_snd_una-tp->max_window))
818     				return 0;
819     		}
820     
821     		/* Event "B" in the comment above. */
822     		if (after(end_seq, tp->high_seq))
823     			flag |= FLAG_DATA_LOST;
824     
825     		for_retrans_queue(skb, sk, tp) {
826     			u8 sacked = TCP_SKB_CB(skb)->sacked;
827     			int in_sack;
828     
829     			/* The retransmission queue is always in order, so
830     			 * we can short-circuit the walk early.
831     			 */
832     			if(!before(TCP_SKB_CB(skb)->seq, end_seq))
833     				break;
834     
835     			fack_count++;
836     
837     			in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
838     				!before(end_seq, TCP_SKB_CB(skb)->end_seq);
839     
840     			/* Account D-SACK for retransmitted packet. */
841     			if ((dup_sack && in_sack) &&
842     			    (sacked & TCPCB_RETRANS) &&
843     			    after(TCP_SKB_CB(skb)->end_seq, tp->undo_marker))
844     				tp->undo_retrans--;
845     
846     			/* The frame is ACKed. */
847     			if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una)) {
848     				if (sacked&TCPCB_RETRANS) {
849     					if ((dup_sack && in_sack) &&
850     					    (sacked&TCPCB_SACKED_ACKED))
851     						reord = min_t(int, fack_count, reord);
852     				} else {
853     					/* If it was in a hole, we detected reordering. */
854     					if (fack_count < prior_fackets &&
855     					    !(sacked&TCPCB_SACKED_ACKED))
856     						reord = min_t(int, fack_count, reord);
857     				}
858     
859     				/* Nothing to do; acked frame is about to be dropped. */
860     				continue;
861     			}
862     
863     			if ((sacked&TCPCB_SACKED_RETRANS) &&
864     			    after(end_seq, TCP_SKB_CB(skb)->ack_seq) &&
865     			    (!lost_retrans || after(end_seq, lost_retrans)))
866     				lost_retrans = end_seq;
867     
868     			if (!in_sack)
869     				continue;
870     
871     			if (!(sacked&TCPCB_SACKED_ACKED)) {
872     				if (sacked & TCPCB_SACKED_RETRANS) {
873     					/* If the segment is not tagged as lost,
874     					 * we do not clear RETRANS, believing
875     					 * that retransmission is still in flight.
876     					 */
877     					if (sacked & TCPCB_LOST) {
878     						TCP_SKB_CB(skb)->sacked &= ~(TCPCB_LOST|TCPCB_SACKED_RETRANS);
879     						tp->lost_out--;
880     						tp->retrans_out--;
881     					}
882     				} else {
883     					/* New sack for not retransmitted frame,
884     					 * which was in hole. It is reordering.
885     					 */
886     					if (!(sacked & TCPCB_RETRANS) &&
887     					    fack_count < prior_fackets)
888     						reord = min_t(int, fack_count, reord);
889     
890     					if (sacked & TCPCB_LOST) {
891     						TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
892     						tp->lost_out--;
893     					}
894     				}
895     
896     				TCP_SKB_CB(skb)->sacked |= TCPCB_SACKED_ACKED;
897     				flag |= FLAG_DATA_SACKED;
898     				tp->sacked_out++;
899     
900     				if (fack_count > tp->fackets_out)
901     					tp->fackets_out = fack_count;
902     			} else {
903     				if (dup_sack && (sacked&TCPCB_RETRANS))
904     					reord = min_t(int, fack_count, reord);
905     			}
906     
907     			/* D-SACK. We can detect redundant retransmission
908     			 * in S|R and plain R frames and clear it.
909     			 * undo_retrans is decreased above, L|R frames
910     			 * are accounted above as well.
911     			 */
912     			if (dup_sack &&
913     			    (TCP_SKB_CB(skb)->sacked&TCPCB_SACKED_RETRANS)) {
914     				TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
915     				tp->retrans_out--;
916     			}
917     		}
918     	}
919     
920     	/* Check for lost retransmit. This superb idea is
921     	 * borrowed from "ratehalving". Event "C".
922     	 * Later note: FACK people cheated me again 8),
923     	 * we have to account for reordering! Ugly,
924     	 * but should help.
925     	 */
926     	if (lost_retrans && tp->ca_state == TCP_CA_Recovery) {
927     		struct sk_buff *skb;
928     
929     		for_retrans_queue(skb, sk, tp) {
930     			if (after(TCP_SKB_CB(skb)->seq, lost_retrans))
931     				break;
932     			if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una))
933     				continue;
934     			if ((TCP_SKB_CB(skb)->sacked&TCPCB_SACKED_RETRANS) &&
935     			    after(lost_retrans, TCP_SKB_CB(skb)->ack_seq) &&
936     			    (IsFack(tp) ||
937     			     !before(lost_retrans, TCP_SKB_CB(skb)->ack_seq+tp->reordering*tp->mss_cache))) {
938     				TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
939     				tp->retrans_out--;
940     
941     				if (!(TCP_SKB_CB(skb)->sacked&(TCPCB_LOST|TCPCB_SACKED_ACKED))) {
942     					tp->lost_out++;
943     					TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
944     					flag |= FLAG_DATA_SACKED;
945     					NET_INC_STATS_BH(TCPLostRetransmit);
946     				}
947     			}
948     		}
949     	}
950     
951     	tp->left_out = tp->sacked_out + tp->lost_out;
952     
953     	if (reord < tp->fackets_out && tp->ca_state != TCP_CA_Loss)
954     		tcp_update_reordering(tp, (tp->fackets_out+1)-reord, 0);
955     
956     #if FASTRETRANS_DEBUG > 0
957     	BUG_TRAP((int)tp->sacked_out >= 0);
958     	BUG_TRAP((int)tp->lost_out >= 0);
959     	BUG_TRAP((int)tp->retrans_out >= 0);
960     	BUG_TRAP((int)tcp_packets_in_flight(tp) >= 0);
961     #endif
962     	return flag;
963     }
964     
965     void tcp_clear_retrans(struct tcp_opt *tp)
966     {
967     	tp->left_out = 0;
968     	tp->retrans_out = 0;
969     
970     	tp->fackets_out = 0;
971     	tp->sacked_out = 0;
972     	tp->lost_out = 0;
973     
974     	tp->undo_marker = 0;
975     	tp->undo_retrans = 0;
976     }
977     
978     /* Enter Loss state. If "how" is not zero, forget all SACK information
979      * and reset tags completely, otherwise preserve SACKs. If receiver
980      * dropped its ofo queue, we will know this due to reneging detection.
981      */
982     void tcp_enter_loss(struct sock *sk, int how)
983     {
984     	struct tcp_opt *tp = &sk->tp_pinfo.af_tcp;
985     	struct sk_buff *skb;
986     	int cnt = 0;
987     
988     	/* Reduce ssthresh if it has not yet been made inside this window. */
989     	if (tp->ca_state <= TCP_CA_Disorder ||
990     	    tp->snd_una == tp->high_seq ||
991     	    (tp->ca_state == TCP_CA_Loss && !tp->retransmits)) {
992     		tp->prior_ssthresh = tcp_current_ssthresh(tp);
993     		tp->snd_ssthresh = tcp_recalc_ssthresh(tp);
994     	}
995     	tp->snd_cwnd = 1;
996     	tp->snd_cwnd_cnt = 0;
997     	tp->snd_cwnd_stamp = tcp_time_stamp;
998     
999     	tcp_clear_retrans(tp);
1000     
1001     	/* Push undo marker, if it was plain RTO and nothing
1002     	 * was retransmitted. */
1003     	if (!how)
1004     		tp->undo_marker = tp->snd_una;
1005     
1006     	for_retrans_queue(skb, sk, tp) {
1007     		cnt++;
1008     		if (TCP_SKB_CB(skb)->sacked&TCPCB_RETRANS)
1009     			tp->undo_marker = 0;
1010     		TCP_SKB_CB(skb)->sacked &= (~TCPCB_TAGBITS)|TCPCB_SACKED_ACKED;
1011     		if (!(TCP_SKB_CB(skb)->sacked&TCPCB_SACKED_ACKED) || how) {
1012     			TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_ACKED;
1013     			TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1014     			tp->lost_out++;
1015     		} else {
1016     			tp->sacked_out++;
1017     			tp->fackets_out = cnt;
1018     		}
1019     	}
1020     	tcp_sync_left_out(tp);
1021     
1022     	tp->reordering = min_t(unsigned int, tp->reordering, sysctl_tcp_reordering);
1023     	tp->ca_state = TCP_CA_Loss;
1024     	tp->high_seq = tp->snd_nxt;
1025     	TCP_ECN_queue_cwr(tp);
1026     }
1027     
1028     static int tcp_check_sack_reneging(struct sock *sk, struct tcp_opt *tp)
1029     {
1030     	struct sk_buff *skb;
1031     
1032     	/* If ACK arrived pointing to a remembered SACK,
1033     	 * it means that our remembered SACKs do not reflect
1034     	 * real state of receiver i.e.
1035     	 * receiver _host_ is heavily congested (or buggy).
1036     	 * Do processing similar to RTO timeout.
1037     	 */
1038     	if ((skb = skb_peek(&sk->write_queue)) != NULL &&
1039     	    (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)) {
1040     		NET_INC_STATS_BH(TCPSACKReneging);
1041     
1042     		tcp_enter_loss(sk, 1);
1043     		tp->retransmits++;
1044     		tcp_retransmit_skb(sk, skb_peek(&sk->write_queue));
1045     		tcp_reset_xmit_timer(sk, TCP_TIME_RETRANS, tp->rto);
1046     		return 1;
1047     	}
1048     	return 0;
1049     }
1050     
1051     static inline int tcp_fackets_out(struct tcp_opt *tp)
1052     {
1053     	return IsReno(tp) ? tp->sacked_out+1 : tp->fackets_out;
1054     }
1055     
1056     static inline int tcp_skb_timedout(struct tcp_opt *tp, struct sk_buff *skb)
1057     {
1058     	return (tcp_time_stamp - TCP_SKB_CB(skb)->when > tp->rto);
1059     }
1060     
1061     static inline int tcp_head_timedout(struct sock *sk, struct tcp_opt *tp)
1062     {
1063     	return tp->packets_out && tcp_skb_timedout(tp, skb_peek(&sk->write_queue));
1064     }
1065     
1066     /* Linux NewReno/SACK/FACK/ECN state machine.
1067      * --------------------------------------
1068      *
1069      * "Open"	Normal state, no dubious events, fast path.
1070      * "Disorder"   In all the respects it is "Open",
1071      *		but requires a bit more attention. It is entered when
1072      *		we see some SACKs or dupacks. It is split of "Open"
1073      *		mainly to move some processing from fast path to slow one.
1074      * "CWR"	CWND was reduced due to some Congestion Notification event.
1075      *		It can be ECN, ICMP source quench, local device congestion.
1076      * "Recovery"	CWND was reduced, we are fast-retransmitting.
1077      * "Loss"	CWND was reduced due to RTO timeout or SACK reneging.
1078      *
1079      * tcp_fastretrans_alert() is entered:
1080      * - each incoming ACK, if state is not "Open"
1081      * - when arrived ACK is unusual, namely:
1082      *	* SACK
1083      *	* Duplicate ACK.
1084      *	* ECN ECE.
1085      *
1086      * Counting packets in flight is pretty simple.
1087      *
1088      *	in_flight = packets_out - left_out + retrans_out
1089      *
1090      *	packets_out is SND.NXT-SND.UNA counted in packets.
1091      *
1092      *	retrans_out is number of retransmitted segments.
1093      *
1094      *	left_out is number of segments left network, but not ACKed yet.
1095      *
1096      *		left_out = sacked_out + lost_out
1097      *
1098      *     sacked_out: Packets, which arrived to receiver out of order
1099      *		   and hence not ACKed. With SACKs this number is simply
1100      *		   amount of SACKed data. Even without SACKs
1101      *		   it is easy to give pretty reliable estimate of this number,
1102      *		   counting duplicate ACKs.
1103      *
1104      *       lost_out: Packets lost by network. TCP has no explicit
1105      *		   "loss notification" feedback from network (for now).
1106      *		   It means that this number can be only _guessed_.
1107      *		   Actually, it is the heuristics to predict lossage that
1108      *		   distinguishes different algorithms.
1109      *
1110      *	F.e. after RTO, when all the queue is considered as lost,
1111      *	lost_out = packets_out and in_flight = retrans_out.
1112      *
1113      *		Essentially, we have now two algorithms counting
1114      *		lost packets.
1115      *
1116      *		FACK: It is the simplest heuristics. As soon as we decided
1117      *		that something is lost, we decide that _all_ not SACKed
1118      *		packets until the most forward SACK are lost. I.e.
1119      *		lost_out = fackets_out - sacked_out and left_out = fackets_out.
1120      *		It is absolutely correct estimate, if network does not reorder
1121      *		packets. And it loses any connection to reality when reordering
1122      *		takes place. We use FACK by default until reordering
1123      *		is suspected on the path to this destination.
1124      *
1125      *		NewReno: when Recovery is entered, we assume that one segment
1126      *		is lost (classic Reno). While we are in Recovery and
1127      *		a partial ACK arrives, we assume that one more packet
1128      *		is lost (NewReno). This heuristics are the same in NewReno
1129      *		and SACK.
1130      *
1131      *  Imagine, that's all! Forget about all this shamanism about CWND inflation
1132      *  deflation etc. CWND is real congestion window, never inflated, changes
1133      *  only according to classic VJ rules.
1134      *
1135      * Really tricky (and requiring careful tuning) part of algorithm
1136      * is hidden in functions tcp_time_to_recover() and tcp_xmit_retransmit_queue().
1137      * The first determines the moment _when_ we should reduce CWND and,
1138      * hence, slow down forward transmission. In fact, it determines the moment
1139      * when we decide that hole is caused by loss, rather than by a reorder.
1140      *
1141      * tcp_xmit_retransmit_queue() decides, _what_ we should retransmit to fill
1142      * holes, caused by lost packets.
1143      *
1144      * And the most logically complicated part of algorithm is undo
1145      * heuristics. We detect false retransmits due to both too early
1146      * fast retransmit (reordering) and underestimated RTO, analyzing
1147      * timestamps and D-SACKs. When we detect that some segments were
1148      * retransmitted by mistake and CWND reduction was wrong, we undo
1149      * window reduction and abort recovery phase. This logic is hidden
1150      * inside several functions named tcp_try_undo_<something>.
1151      */
1152     
1153     /* This function decides, when we should leave Disordered state
1154      * and enter Recovery phase, reducing congestion window.
1155      *
1156      * Main question: may we further continue forward transmission
1157      * with the same cwnd?
1158      */
1159     static int
1160     tcp_time_to_recover(struct sock *sk, struct tcp_opt *tp)
1161     {
1162     	/* Trick#1: The loss is proven. */
1163     	if (tp->lost_out)
1164     		return 1;
1165     
1166     	/* Not-A-Trick#2 : Classic rule... */
1167     	if (tcp_fackets_out(tp) > tp->reordering)
1168     		return 1;
1169     
1170     	/* Trick#3 : when we use RFC2988 timer restart, fast
1171     	 * retransmit can be triggered by timeout of queue head.
1172     	 */
1173     	if (tcp_head_timedout(sk, tp))
1174     		return 1;
1175     
1176     	/* Trick#4: It is still not OK... But will it be useful to delay
1177     	 * recovery more?
1178     	 */
1179     	if (tp->packets_out <= tp->reordering &&
1180     	    tp->sacked_out >= max_t(u32, tp->packets_out/2, sysctl_tcp_reordering) &&
1181     	    !tcp_may_send_now(sk, tp)) {
1182     		/* We have nothing to send. This connection is limited
1183     		 * either by receiver window or by application.
1184     		 */
1185     		return 1;
1186     	}
1187     
1188     	return 0;
1189     }
1190     
1191     /* If we receive more dupacks than we expected counting segments
1192      * in assumption of absent reordering, interpret this as reordering.
1193      * The only another reason could be bug in receiver TCP.
1194      */
1195     static void tcp_check_reno_reordering(struct tcp_opt *tp, int addend)
1196     {
1197     	u32 holes = min_t(unsigned int,
1198     			max_t(unsigned int, tp->lost_out, 1),
1199     			tp->packets_out);
1200     
1201     	if (tp->sacked_out + holes > tp->packets_out) {
1202     		tp->sacked_out = tp->packets_out - holes;
1203     		tcp_update_reordering(tp, tp->packets_out+addend, 0);
1204     	}
1205     }
1206     
1207     /* Emulate SACKs for SACKless connection: account for a new dupack. */
1208     
1209     static void tcp_add_reno_sack(struct tcp_opt *tp)
1210     {
1211     	++tp->sacked_out;
1212     	tcp_check_reno_reordering(tp, 0);
1213     	tcp_sync_left_out(tp);
1214     }
1215     
1216     /* Account for ACK, ACKing some data in Reno Recovery phase. */
1217     
1218     static void tcp_remove_reno_sacks(struct sock *sk, struct tcp_opt *tp, int acked)
1219     {
1220     	if (acked > 0) {
1221     		/* One ACK acked hole. The rest eat duplicate ACKs. */
1222     		if (acked-1 >= tp->sacked_out)
1223     			tp->sacked_out = 0;
1224     		else
1225     			tp->sacked_out -= acked-1;
1226     	}
1227     	tcp_check_reno_reordering(tp, acked);
1228     	tcp_sync_left_out(tp);
1229     }
1230     
1231     static inline void tcp_reset_reno_sack(struct tcp_opt *tp)
1232     {
1233     	tp->sacked_out = 0;
1234     	tp->left_out = tp->lost_out;
1235     }
1236     
1237     /* Mark head of queue up as lost. */
1238     static void
1239     tcp_mark_head_lost(struct sock *sk, struct tcp_opt *tp, int packets, u32 high_seq)
1240     {
1241     	struct sk_buff *skb;
1242     	int cnt = packets;
1243     
1244     	BUG_TRAP(cnt <= tp->packets_out);
1245     
1246     	for_retrans_queue(skb, sk, tp) {
1247     		if (--cnt < 0 || after(TCP_SKB_CB(skb)->end_seq, high_seq))
1248     			break;
1249     		if (!(TCP_SKB_CB(skb)->sacked&TCPCB_TAGBITS)) {
1250     			TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1251     			tp->lost_out++;
1252     		}
1253     	}
1254     	tcp_sync_left_out(tp);
1255     }
1256     
1257     /* Account newly detected lost packet(s) */
1258     
1259     static void tcp_update_scoreboard(struct sock *sk, struct tcp_opt *tp)
1260     {
1261     	if (IsFack(tp)) {
1262     		int lost = tp->fackets_out - tp->reordering;
1263     		if (lost <= 0)
1264     			lost = 1;
1265     		tcp_mark_head_lost(sk, tp, lost, tp->high_seq);
1266     	} else {
1267     		tcp_mark_head_lost(sk, tp, 1, tp->high_seq);
1268     	}
1269     
1270     	/* New heuristics: it is possible only after we switched
1271     	 * to restart timer each time when something is ACKed.
1272     	 * Hence, we can detect timed out packets during fast
1273     	 * retransmit without falling to slow start.
1274     	 */
1275     	if (tcp_head_timedout(sk, tp)) {
1276     		struct sk_buff *skb;
1277     
1278     		for_retrans_queue(skb, sk, tp) {
1279     			if (tcp_skb_timedout(tp, skb) &&
1280     			    !(TCP_SKB_CB(skb)->sacked&TCPCB_TAGBITS)) {
1281     				TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1282     				tp->lost_out++;
1283     			}
1284     		}
1285     		tcp_sync_left_out(tp);
1286     	}
1287     }
1288     
1289     /* CWND moderation, preventing bursts due to too big ACKs
1290      * in dubious situations.
1291      */
1292     static __inline__ void tcp_moderate_cwnd(struct tcp_opt *tp)
1293     {
1294     	tp->snd_cwnd = min_t(u32, tp->snd_cwnd,
1295     			   tcp_packets_in_flight(tp)+tcp_max_burst(tp));
1296     	tp->snd_cwnd_stamp = tcp_time_stamp;
1297     }
1298     
1299     /* Decrease cwnd each second ack. */
1300     
1301     static void tcp_cwnd_down(struct tcp_opt *tp)
1302     {
1303     	int decr = tp->snd_cwnd_cnt + 1;
1304     
1305     	tp->snd_cwnd_cnt = decr&1;
1306     	decr >>= 1;
1307     
1308     	if (decr && tp->snd_cwnd > tp->snd_ssthresh/2)
1309     		tp->snd_cwnd -= decr;
1310     
1311     	tp->snd_cwnd = min_t(u32, tp->snd_cwnd, tcp_packets_in_flight(tp)+1);
1312     	tp->snd_cwnd_stamp = tcp_time_stamp;
1313     }
1314     
1315     /* Nothing was retransmitted or returned timestamp is less
1316      * than timestamp of the first retransmission.
1317      */
1318     static __inline__ int tcp_packet_delayed(struct tcp_opt *tp)
1319     {
1320     	return !tp->retrans_stamp ||
1321     		(tp->saw_tstamp && tp->rcv_tsecr &&
1322     		 (__s32)(tp->rcv_tsecr - tp->retrans_stamp) < 0);
1323     }
1324     
1325     /* Undo procedures. */
1326     
1327     #if FASTRETRANS_DEBUG > 1
1328     static void DBGUNDO(struct sock *sk, struct tcp_opt *tp, const char *msg)
1329     {
1330     	printk(KERN_DEBUG "Undo %s %u.%u.%u.%u/%u c%u l%u ss%u/%u p%u\n",
1331     	       msg,
1332     	       NIPQUAD(sk->daddr), ntohs(sk->dport),
1333     	       tp->snd_cwnd, tp->left_out,
1334     	       tp->snd_ssthresh, tp->prior_ssthresh, tp->packets_out);
1335     }
1336     #else
1337     #define DBGUNDO(x...) do { } while (0)
1338     #endif
1339     
1340     static void tcp_undo_cwr(struct tcp_opt *tp, int undo)
1341     {
1342     	if (tp->prior_ssthresh) {
1343     		tp->snd_cwnd = max_t(unsigned int,
1344     				   tp->snd_cwnd, tp->snd_ssthresh<<1);
1345     
1346     		if (undo && tp->prior_ssthresh > tp->snd_ssthresh) {
1347     			tp->snd_ssthresh = tp->prior_ssthresh;
1348     			TCP_ECN_withdraw_cwr(tp);
1349     		}
1350     	} else {
1351     		tp->snd_cwnd = max_t(unsigned int, tp->snd_cwnd, tp->snd_ssthresh);
1352     	}
1353     	tcp_moderate_cwnd(tp);
1354     	tp->snd_cwnd_stamp = tcp_time_stamp;
1355     }
1356     
1357     static inline int tcp_may_undo(struct tcp_opt *tp)
1358     {
1359     	return tp->undo_marker &&
1360     		(!tp->undo_retrans || tcp_packet_delayed(tp));
1361     }
1362     
1363     /* People celebrate: "We love our President!" */
1364     static int tcp_try_undo_recovery(struct sock *sk, struct tcp_opt *tp)
1365     {
1366     	if (tcp_may_undo(tp)) {
1367     		/* Happy end! We did not retransmit anything
1368     		 * or our original transmission succeeded.
1369     		 */
1370     		DBGUNDO(sk, tp, tp->ca_state == TCP_CA_Loss ? "loss" : "retrans");
1371     		tcp_undo_cwr(tp, 1);
1372     		if (tp->ca_state == TCP_CA_Loss)
1373     			NET_INC_STATS_BH(TCPLossUndo);
1374     		else
1375     			NET_INC_STATS_BH(TCPFullUndo);
1376     		tp->undo_marker = 0;
1377     	}
1378     	if (tp->snd_una == tp->high_seq && IsReno(tp)) {
1379     		/* Hold old state until something *above* high_seq
1380     		 * is ACKed. For Reno it is MUST to prevent false
1381     		 * fast retransmits (RFC2582). SACK TCP is safe. */
1382     		tcp_moderate_cwnd(tp);
1383     		return 1;
1384     	}
1385     	tp->ca_state = TCP_CA_Open;
1386     	return 0;
1387     }
1388     
1389     /* Try to undo cwnd reduction, because D-SACKs acked all retransmitted data */
1390     static void tcp_try_undo_dsack(struct sock *sk, struct tcp_opt *tp)
1391     {
1392     	if (tp->undo_marker && !tp->undo_retrans) {
1393     		DBGUNDO(sk, tp, "D-SACK");
1394     		tcp_undo_cwr(tp, 1);
1395     		tp->undo_marker = 0;
1396     		NET_INC_STATS_BH(TCPDSACKUndo);
1397     	}
1398     }
1399     
1400     /* Undo during fast recovery after partial ACK. */
1401     
1402     static int tcp_try_undo_partial(struct sock *sk, struct tcp_opt *tp, int acked)
1403     {
1404     	/* Partial ACK arrived. Force Hoe's retransmit. */
1405     	int failed = IsReno(tp) || tp->fackets_out>tp->reordering;
1406     
1407     	if (tcp_may_undo(tp)) {
1408     		/* Plain luck! Hole if filled with delayed
1409     		 * packet, rather than with a retransmit.
1410     		 */
1411     		if (tp->retrans_out == 0)
1412     			tp->retrans_stamp = 0;
1413     
1414     		tcp_update_reordering(tp, tcp_fackets_out(tp)+acked, 1);
1415     
1416     		DBGUNDO(sk, tp, "Hoe");
1417     		tcp_undo_cwr(tp, 0);
1418     		NET_INC_STATS_BH(TCPPartialUndo);
1419     
1420     		/* So... Do not make Hoe's retransmit yet.
1421     		 * If the first packet was delayed, the rest
1422     		 * ones are most probably delayed as well.
1423     		 */
1424     		failed = 0;
1425     	}
1426     	return failed;
1427     }
1428     
1429     /* Undo during loss recovery after partial ACK. */
1430     static int tcp_try_undo_loss(struct sock *sk, struct tcp_opt *tp)
1431     {
1432     	if (tcp_may_undo(tp)) {
1433     		struct sk_buff *skb;
1434     		for_retrans_queue(skb, sk, tp) {
1435     			TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
1436     		}
1437     		DBGUNDO(sk, tp, "partial loss");
1438     		tp->lost_out = 0;
1439     		tp->left_out = tp->sacked_out;
1440     		tcp_undo_cwr(tp, 1);
1441     		NET_INC_STATS_BH(TCPLossUndo);
1442     		tp->retransmits = 0;
1443     		tp->undo_marker = 0;
1444     		if (!IsReno(tp))
1445     			tp->ca_state = TCP_CA_Open;
1446     		return 1;
1447     	}
1448     	return 0;
1449     }
1450     
1451     static __inline__ void tcp_complete_cwr(struct tcp_opt *tp)
1452     {
1453     	tp->snd_cwnd = min_t(u32, tp->snd_cwnd, tp->snd_ssthresh);
1454     	tp->snd_cwnd_stamp = tcp_time_stamp;
1455     }
1456     
1457     static void tcp_try_to_open(struct sock *sk, struct tcp_opt *tp, int flag)
1458     {
1459     	tp->left_out = tp->sacked_out;
1460     
1461     	if (tp->retrans_out == 0)
1462     		tp->retrans_stamp = 0;
1463     
1464     	if (flag&FLAG_ECE)
1465     		tcp_enter_cwr(tp);
1466     
1467     	if (tp->ca_state != TCP_CA_CWR) {
1468     		int state = TCP_CA_Open;
1469     
1470     		if (tp->left_out ||
1471     		    tp->retrans_out ||
1472     		    tp->undo_marker)
1473     			state = TCP_CA_Disorder;
1474     
1475     		if (tp->ca_state != state) {
1476     			tp->ca_state = state;
1477     			tp->high_seq = tp->snd_nxt;
1478     		}
1479     		tcp_moderate_cwnd(tp);
1480     	} else {
1481     		tcp_cwnd_down(tp);
1482     	}
1483     }
1484     
1485     /* Process an event, which can update packets-in-flight not trivially.
1486      * Main goal of this function is to calculate new estimate for left_out,
1487      * taking into account both packets sitting in receiver's buffer and
1488      * packets lost by network.
1489      *
1490      * Besides that it does CWND reduction, when packet loss is detected
1491      * and changes state of machine.
1492      *
1493      * It does _not_ decide what to send, it is made in function
1494      * tcp_xmit_retransmit_queue().
1495      */
1496     static void
1497     tcp_fastretrans_alert(struct sock *sk, u32 prior_snd_una,
1498     		      int prior_packets, int flag)
1499     {
1500     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
1501     	int is_dupack = (tp->snd_una == prior_snd_una && !(flag&FLAG_NOT_DUP));
1502     
1503     	/* Some technical things:
1504     	 * 1. Reno does not count dupacks (sacked_out) automatically. */
1505     	if (!tp->packets_out)
1506     		tp->sacked_out = 0;
1507             /* 2. SACK counts snd_fack in packets inaccurately. */
1508     	if (tp->sacked_out == 0)
1509     		tp->fackets_out = 0;
1510     
1511             /* Now state machine starts.
1512     	 * A. ECE, hence prohibit cwnd undoing, the reduction is required. */
1513     	if (flag&FLAG_ECE)
1514     		tp->prior_ssthresh = 0;
1515     
1516     	/* B. In all the states check for reneging SACKs. */
1517     	if (tp->sacked_out && tcp_check_sack_reneging(sk, tp))
1518     		return;
1519     
1520     	/* C. Process data loss notification, provided it is valid. */
1521     	if ((flag&FLAG_DATA_LOST) &&
1522     	    before(tp->snd_una, tp->high_seq) &&
1523     	    tp->ca_state != TCP_CA_Open &&
1524     	    tp->fackets_out > tp->reordering) {
1525     		tcp_mark_head_lost(sk, tp, tp->fackets_out-tp->reordering, tp->high_seq);
1526     		NET_INC_STATS_BH(TCPLoss);
1527     	}
1528     
1529     	/* D. Synchronize left_out to current state. */
1530     	tcp_sync_left_out(tp);
1531     
1532     	/* E. Check state exit conditions. State can be terminated
1533     	 *    when high_seq is ACKed. */
1534     	if (tp->ca_state == TCP_CA_Open) {
1535     		BUG_TRAP(tp->retrans_out == 0);
1536     		tp->retrans_stamp = 0;
1537     	} else if (!before(tp->snd_una, tp->high_seq)) {
1538     		switch (tp->ca_state) {
1539     		case TCP_CA_Loss:
1540     			tp->retransmits = 0;
1541     			if (tcp_try_undo_recovery(sk, tp))
1542     				return;
1543     			break;
1544     
1545     		case TCP_CA_CWR:
1546     			/* CWR is to be held something *above* high_seq
1547     			 * is ACKed for CWR bit to reach receiver. */
1548     			if (tp->snd_una != tp->high_seq) {
1549     				tcp_complete_cwr(tp);
1550     				tp->ca_state = TCP_CA_Open;
1551     			}
1552     			break;
1553     
1554     		case TCP_CA_Disorder:
1555     			tcp_try_undo_dsack(sk, tp);
1556     			if (!tp->undo_marker ||
1557     			    /* For SACK case do not Open to allow to undo
1558     			     * catching for all duplicate ACKs. */
1559     			    IsReno(tp) || tp->snd_una != tp->high_seq) {
1560     				tp->undo_marker = 0;
1561     				tp->ca_state = TCP_CA_Open;
1562     			}
1563     			break;
1564     
1565     		case TCP_CA_Recovery:
1566     			if (IsReno(tp))
1567     				tcp_reset_reno_sack(tp);
1568     			if (tcp_try_undo_recovery(sk, tp))
1569     				return;
1570     			tcp_complete_cwr(tp);
1571     			break;
1572     		}
1573     	}
1574     
1575     	/* F. Process state. */
1576     	switch (tp->ca_state) {
1577     	case TCP_CA_Recovery:
1578     		if (prior_snd_una == tp->snd_una) {
1579     			if (IsReno(tp) && is_dupack)
1580     				tcp_add_reno_sack(tp);
1581     		} else {
1582     			int acked = prior_packets - tp->packets_out;
1583     			if (IsReno(tp))
1584     				tcp_remove_reno_sacks(sk, tp, acked);
1585     			is_dupack = tcp_try_undo_partial(sk, tp, acked);
1586     		}
1587     		break;
1588     	case TCP_CA_Loss:
1589     		if (flag&FLAG_DATA_ACKED)
1590     			tp->retransmits = 0;
1591     		if (!tcp_try_undo_loss(sk, tp)) {
1592     			tcp_moderate_cwnd(tp);
1593     			tcp_xmit_retransmit_queue(sk);
1594     			return;
1595     		}
1596     		if (tp->ca_state != TCP_CA_Open)
1597     			return;
1598     		/* Loss is undone; fall through to processing in Open state. */
1599     	default:
1600     		if (IsReno(tp)) {
1601     			if (tp->snd_una != prior_snd_una)
1602     				tcp_reset_reno_sack(tp);
1603     			if (is_dupack)
1604     				tcp_add_reno_sack(tp);
1605     		}
1606     
1607     		if (tp->ca_state == TCP_CA_Disorder)
1608     			tcp_try_undo_dsack(sk, tp);
1609     
1610     		if (!tcp_time_to_recover(sk, tp)) {
1611     			tcp_try_to_open(sk, tp, flag);
1612     			return;
1613     		}
1614     
1615     		/* Otherwise enter Recovery state */
1616     
1617     		if (IsReno(tp))
1618     			NET_INC_STATS_BH(TCPRenoRecovery);
1619     		else
1620     			NET_INC_STATS_BH(TCPSackRecovery);
1621     
1622     		tp->high_seq = tp->snd_nxt;
1623     		tp->prior_ssthresh = 0;
1624     		tp->undo_marker = tp->snd_una;
1625     		tp->undo_retrans = tp->retrans_out;
1626     
1627     		if (tp->ca_state < TCP_CA_CWR) {
1628     			if (!(flag&FLAG_ECE))
1629     				tp->prior_ssthresh = tcp_current_ssthresh(tp);
1630     			tp->snd_ssthresh = tcp_recalc_ssthresh(tp);
1631     			TCP_ECN_queue_cwr(tp);
1632     		}
1633     
1634     		tp->snd_cwnd_cnt = 0;
1635     		tp->ca_state = TCP_CA_Recovery;
1636     	}
1637     
1638     	if (is_dupack || tcp_head_timedout(sk, tp))
1639     		tcp_update_scoreboard(sk, tp);
1640     	tcp_cwnd_down(tp);
1641     	tcp_xmit_retransmit_queue(sk);
1642     }
1643     
1644     /* Read draft-ietf-tcplw-high-performance before mucking
1645      * with this code. (Superceeds RFC1323)
1646      */
1647     static void tcp_ack_saw_tstamp(struct tcp_opt *tp, int flag)
1648     {
1649     	__u32 seq_rtt;
1650     
1651     	/* RTTM Rule: A TSecr value received in a segment is used to
1652     	 * update the averaged RTT measurement only if the segment
1653     	 * acknowledges some new data, i.e., only if it advances the
1654     	 * left edge of the send window.
1655     	 *
1656     	 * See draft-ietf-tcplw-high-performance-00, section 3.3.
1657     	 * 1998/04/10 Andrey V. Savochkin <saw@msu.ru>
1658     	 *
1659     	 * Changed: reset backoff as soon as we see the first valid sample.
1660     	 * If we do not, we get strongly overstimated rto. With timestamps
1661     	 * samples are accepted even from very old segments: f.e., when rtt=1
1662     	 * increases to 8, we retransmit 5 times and after 8 seconds delayed
1663     	 * answer arrives rto becomes 120 seconds! If at least one of segments
1664     	 * in window is lost... Voila.	 			--ANK (010210)
1665     	 */
1666     	seq_rtt = tcp_time_stamp - tp->rcv_tsecr;
1667     	tcp_rtt_estimator(tp, seq_rtt);
1668     	tcp_set_rto(tp);
1669     	tp->backoff = 0;
1670     	tcp_bound_rto(tp);
1671     }
1672     
1673     static void tcp_ack_no_tstamp(struct tcp_opt *tp, u32 seq_rtt, int flag)
1674     {
1675     	/* We don't have a timestamp. Can only use
1676     	 * packets that are not retransmitted to determine
1677     	 * rtt estimates. Also, we must not reset the
1678     	 * backoff for rto until we get a non-retransmitted
1679     	 * packet. This allows us to deal with a situation
1680     	 * where the network delay has increased suddenly.
1681     	 * I.e. Karn's algorithm. (SIGCOMM '87, p5.)
1682     	 */
1683     
1684     	if (flag & FLAG_RETRANS_DATA_ACKED)
1685     		return;
1686     
1687     	tcp_rtt_estimator(tp, seq_rtt);
1688     	tcp_set_rto(tp);
1689     	tp->backoff = 0;
1690     	tcp_bound_rto(tp);
1691     }
1692     
1693     static __inline__ void
1694     tcp_ack_update_rtt(struct tcp_opt *tp, int flag, s32 seq_rtt)
1695     {
1696     	/* Note that peer MAY send zero echo. In this case it is ignored. (rfc1323) */
1697     	if (tp->saw_tstamp && tp->rcv_tsecr)
1698     		tcp_ack_saw_tstamp(tp, flag);
1699     	else if (seq_rtt >= 0)
1700     		tcp_ack_no_tstamp(tp, seq_rtt, flag);
1701     }
1702     
1703     /* This is Jacobson's slow start and congestion avoidance. 
1704      * SIGCOMM '88, p. 328.
1705      */
1706     static __inline__ void tcp_cong_avoid(struct tcp_opt *tp)
1707     {
1708             if (tp->snd_cwnd <= tp->snd_ssthresh) {
1709                     /* In "safe" area, increase. */
1710     		if (tp->snd_cwnd < tp->snd_cwnd_clamp)
1711     			tp->snd_cwnd++;
1712     	} else {
1713                     /* In dangerous area, increase slowly.
1714     		 * In theory this is tp->snd_cwnd += 1 / tp->snd_cwnd
1715     		 */
1716     		if (tp->snd_cwnd_cnt >= tp->snd_cwnd) {
1717     			if (tp->snd_cwnd < tp->snd_cwnd_clamp)
1718     				tp->snd_cwnd++;
1719     			tp->snd_cwnd_cnt=0;
1720     		} else
1721     			tp->snd_cwnd_cnt++;
1722             }
1723     	tp->snd_cwnd_stamp = tcp_time_stamp;
1724     }
1725     
1726     /* Restart timer after forward progress on connection.
1727      * RFC2988 recommends to restart timer to now+rto.
1728      */
1729     
1730     static __inline__ void tcp_ack_packets_out(struct sock *sk, struct tcp_opt *tp)
1731     {
1732     	if (tp->packets_out==0) {
1733     		tcp_clear_xmit_timer(sk, TCP_TIME_RETRANS);
1734     	} else {
1735     		tcp_reset_xmit_timer(sk, TCP_TIME_RETRANS, tp->rto);
1736     	}
1737     }
1738     
1739     /* Remove acknowledged frames from the retransmission queue. */
1740     static int tcp_clean_rtx_queue(struct sock *sk)
1741     {
1742     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
1743     	struct sk_buff *skb;
1744     	__u32 now = tcp_time_stamp;
1745     	int acked = 0;
1746     	__s32 seq_rtt = -1;
1747     
1748     	while((skb=skb_peek(&sk->write_queue)) && (skb != tp->send_head)) {
1749     		struct tcp_skb_cb *scb = TCP_SKB_CB(skb); 
1750     		__u8 sacked = scb->sacked;
1751     
1752     		/* If our packet is before the ack sequence we can
1753     		 * discard it as it's confirmed to have arrived at
1754     		 * the other end.
1755     		 */
1756     		if (after(scb->end_seq, tp->snd_una))
1757     			break;
1758     
1759     		/* Initial outgoing SYN's get put onto the write_queue
1760     		 * just like anything else we transmit.  It is not
1761     		 * true data, and if we misinform our callers that
1762     		 * this ACK acks real data, we will erroneously exit
1763     		 * connection startup slow start one packet too
1764     		 * quickly.  This is severely frowned upon behavior.
1765     		 */
1766     		if(!(scb->flags & TCPCB_FLAG_SYN)) {
1767     			acked |= FLAG_DATA_ACKED;
1768     		} else {
1769     			acked |= FLAG_SYN_ACKED;
1770     		}
1771     
1772     		if (sacked) {
1773     			if(sacked & TCPCB_RETRANS) {
1774     				if(sacked & TCPCB_SACKED_RETRANS)
1775     					tp->retrans_out--;
1776     				acked |= FLAG_RETRANS_DATA_ACKED;
1777     				seq_rtt = -1;
1778     			} else if (seq_rtt < 0)
1779     				seq_rtt = now - scb->when;
1780     			if(sacked & TCPCB_SACKED_ACKED)
1781     				tp->sacked_out--;
1782     			if(sacked & TCPCB_LOST)
1783     				tp->lost_out--;
1784     			if(sacked & TCPCB_URG) {
1785     				if (tp->urg_mode &&
1786     				    !before(scb->end_seq, tp->snd_up))
1787     					tp->urg_mode = 0;
1788     			}
1789     		} else if (seq_rtt < 0)
1790     			seq_rtt = now - scb->when;
1791     		if(tp->fackets_out)
1792     			tp->fackets_out--;
1793     		tp->packets_out--;
1794     		__skb_unlink(skb, skb->list);
1795     		tcp_free_skb(sk, skb);
1796     	}
1797     
1798     	if (acked&FLAG_ACKED) {
1799     		tcp_ack_update_rtt(tp, acked, seq_rtt);
1800     		tcp_ack_packets_out(sk, tp);
1801     	}
1802     
1803     #if FASTRETRANS_DEBUG > 0
1804     	BUG_TRAP((int)tp->sacked_out >= 0);
1805     	BUG_TRAP((int)tp->lost_out >= 0);
1806     	BUG_TRAP((int)tp->retrans_out >= 0);
1807     	if (tp->packets_out==0 && tp->sack_ok) {
1808     		if (tp->lost_out) {
1809     			printk(KERN_DEBUG "Leak l=%u %d\n", tp->lost_out, tp->ca_state);
1810     			tp->lost_out = 0;
1811     		}
1812     		if (tp->sacked_out) {
1813     			printk(KERN_DEBUG "Leak s=%u %d\n", tp->sacked_out, tp->ca_state);
1814     			tp->sacked_out = 0;
1815     		}
1816     		if (tp->retrans_out) {
1817     			printk(KERN_DEBUG "Leak r=%u %d\n", tp->retrans_out, tp->ca_state);
1818     			tp->retrans_out = 0;
1819     		}
1820     	}
1821     #endif
1822     	return acked;
1823     }
1824     
1825     static void tcp_ack_probe(struct sock *sk)
1826     {
1827     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
1828     
1829     	/* Was it a usable window open? */
1830     
1831     	if (!after(TCP_SKB_CB(tp->send_head)->end_seq, tp->snd_una + tp->snd_wnd)) {
1832     		tp->backoff = 0;
1833     		tcp_clear_xmit_timer(sk, TCP_TIME_PROBE0);
1834     		/* Socket must be waked up by subsequent tcp_data_snd_check().
1835     		 * This function is not for random using!
1836     		 */
1837     	} else {
1838     		tcp_reset_xmit_timer(sk, TCP_TIME_PROBE0,
1839     				     min_t(u32, tp->rto << tp->backoff, TCP_RTO_MAX));
1840     	}
1841     }
1842     
1843     static __inline__ int tcp_ack_is_dubious(struct tcp_opt *tp, int flag)
1844     {
1845     	return (!(flag & FLAG_NOT_DUP) || (flag & FLAG_CA_ALERT) ||
1846     		tp->ca_state != TCP_CA_Open);
1847     }
1848     
1849     static __inline__ int tcp_may_raise_cwnd(struct tcp_opt *tp, int flag)
1850     {
1851     	return (!(flag & FLAG_ECE) || tp->snd_cwnd < tp->snd_ssthresh) &&
1852     		!((1<<tp->ca_state)&(TCPF_CA_Recovery|TCPF_CA_CWR));
1853     }
1854     
1855     /* Check that window update is acceptable.
1856      * The function assumes that snd_una<=ack<=snd_next.
1857      */
1858     static __inline__ int
1859     tcp_may_update_window(struct tcp_opt *tp, u32 ack, u32 ack_seq, u32 nwin)
1860     {
1861     	return (after(ack, tp->snd_una) ||
1862     		after(ack_seq, tp->snd_wl1) ||
1863     		(ack_seq == tp->snd_wl1 && nwin > tp->snd_wnd));
1864     }
1865     
1866     /* Update our send window.
1867      *
1868      * Window update algorithm, described in RFC793/RFC1122 (used in linux-2.2
1869      * and in FreeBSD. NetBSD's one is even worse.) is wrong.
1870      */
1871     static int tcp_ack_update_window(struct sock *sk, struct tcp_opt *tp,
1872     				 struct sk_buff *skb, u32 ack, u32 ack_seq)
1873     {
1874     	int flag = 0;
1875     	u32 nwin = ntohs(skb->h.th->window) << tp->snd_wscale;
1876     
1877     	if (tcp_may_update_window(tp, ack, ack_seq, nwin)) {
1878     		flag |= FLAG_WIN_UPDATE;
1879     		tcp_update_wl(tp, ack, ack_seq);
1880     
1881     		if (tp->snd_wnd != nwin) {
1882     			tp->snd_wnd = nwin;
1883     
1884     			/* Note, it is the only place, where
1885     			 * fast path is recovered for sending TCP.
1886     			 */
1887     			tcp_fast_path_check(sk, tp);
1888     
1889     			if (nwin > tp->max_window) {
1890     				tp->max_window = nwin;
1891     				tcp_sync_mss(sk, tp->pmtu_cookie);
1892     			}
1893     		}
1894     	}
1895     
1896     	tp->snd_una = ack;
1897     
1898     	return flag;
1899     }
1900     
1901     /* This routine deals with incoming acks, but not outgoing ones. */
1902     static int tcp_ack(struct sock *sk, struct sk_buff *skb, int flag)
1903     {
1904     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
1905     	u32 prior_snd_una = tp->snd_una;
1906     	u32 ack_seq = TCP_SKB_CB(skb)->seq;
1907     	u32 ack = TCP_SKB_CB(skb)->ack_seq;
1908     	u32 prior_in_flight;
1909     	int prior_packets;
1910     
1911     	/* If the ack is newer than sent or older than previous acks
1912     	 * then we can probably ignore it.
1913     	 */
1914     	if (after(ack, tp->snd_nxt))
1915     		goto uninteresting_ack;
1916     
1917     	if (before(ack, prior_snd_una))
1918     		goto old_ack;
1919     
1920     	if (!(flag&FLAG_SLOWPATH) && after(ack, prior_snd_una)) {
1921     		/* Window is constant, pure forward advance.
1922     		 * No more checks are required.
1923     		 * Note, we use the fact that SND.UNA>=SND.WL2.
1924     		 */
1925     		tcp_update_wl(tp, ack, ack_seq);
1926     		tp->snd_una = ack;
1927     		flag |= FLAG_WIN_UPDATE;
1928     
1929     		NET_INC_STATS_BH(TCPHPAcks);
1930     	} else {
1931     		if (ack_seq != TCP_SKB_CB(skb)->end_seq)
1932     			flag |= FLAG_DATA;
1933     		else
1934     			NET_INC_STATS_BH(TCPPureAcks);
1935     
1936     		flag |= tcp_ack_update_window(sk, tp, skb, ack, ack_seq);
1937     
1938     		if (TCP_SKB_CB(skb)->sacked)
1939     			flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una);
1940     
1941     		if (TCP_ECN_rcv_ecn_echo(tp, skb->h.th))
1942     			flag |= FLAG_ECE;
1943     	}
1944     
1945     	/* We passed data and got it acked, remove any soft error
1946     	 * log. Something worked...
1947     	 */
1948     	sk->err_soft = 0;
1949     	tp->rcv_tstamp = tcp_time_stamp;
1950     	if ((prior_packets = tp->packets_out) == 0)
1951     		goto no_queue;
1952     
1953     	prior_in_flight = tcp_packets_in_flight(tp);
1954     
1955     	/* See if we can take anything off of the retransmit queue. */
1956     	flag |= tcp_clean_rtx_queue(sk);
1957     
1958     	if (tcp_ack_is_dubious(tp, flag)) {
1959     		/* Advanve CWND, if state allows this. */
1960     		if ((flag&FLAG_DATA_ACKED) && prior_in_flight >= tp->snd_cwnd &&
1961     		    tcp_may_raise_cwnd(tp, flag))
1962     			tcp_cong_avoid(tp);
1963     		tcp_fastretrans_alert(sk, prior_snd_una, prior_packets, flag);
1964     	} else {
1965     		if ((flag&FLAG_DATA_ACKED) && prior_in_flight >= tp->snd_cwnd)
1966     			tcp_cong_avoid(tp);
1967     	}
1968     
1969     	if ((flag & FLAG_FORWARD_PROGRESS) || !(flag&FLAG_NOT_DUP))
1970     		dst_confirm(sk->dst_cache);
1971     
1972     	return 1;
1973     
1974     no_queue:
1975     	tp->probes_out = 0;
1976     
1977     	/* If this ack opens up a zero window, clear backoff.  It was
1978     	 * being used to time the probes, and is probably far higher than
1979     	 * it needs to be for normal retransmission.
1980     	 */
1981     	if (tp->send_head)
1982     		tcp_ack_probe(sk);
1983     	return 1;
1984     
1985     old_ack:
1986     	if (TCP_SKB_CB(skb)->sacked)
1987     		tcp_sacktag_write_queue(sk, skb, prior_snd_una);
1988     
1989     uninteresting_ack:
1990     	SOCK_DEBUG(sk, "Ack %u out of %u:%u\n", ack, tp->snd_una, tp->snd_nxt);
1991     	return 0;
1992     }
1993     
1994     
1995     /* Look for tcp options. Normally only called on SYN and SYNACK packets.
1996      * But, this can also be called on packets in the established flow when
1997      * the fast version below fails.
1998      */
1999     void tcp_parse_options(struct sk_buff *skb, struct tcp_opt *tp, int estab)
2000     {
2001     	unsigned char *ptr;
2002     	struct tcphdr *th = skb->h.th;
2003     	int length=(th->doff*4)-sizeof(struct tcphdr);
2004     
2005     	ptr = (unsigned char *)(th + 1);
2006     	tp->saw_tstamp = 0;
2007     
2008     	while(length>0) {
2009     	  	int opcode=*ptr++;
2010     		int opsize;
2011     
2012     		switch (opcode) {
2013     			case TCPOPT_EOL:
2014     				return;
2015     			case TCPOPT_NOP:	/* Ref: RFC 793 section 3.1 */
2016     				length--;
2017     				continue;
2018     			default:
2019     				opsize=*ptr++;
2020     				if (opsize < 2) /* "silly options" */
2021     					return;
2022     				if (opsize > length)
2023     					return;	/* don't parse partial options */
2024     	  			switch(opcode) {
2025     				case TCPOPT_MSS:
2026     					if(opsize==TCPOLEN_MSS && th->syn && !estab) {
2027     						u16 in_mss = ntohs(*(__u16 *)ptr);
2028     						if (in_mss) {
2029     							if (tp->user_mss && tp->user_mss < in_mss)
2030     								in_mss = tp->user_mss;
2031     							tp->mss_clamp = in_mss;
2032     						}
2033     					}
2034     					break;
2035     				case TCPOPT_WINDOW:
2036     					if(opsize==TCPOLEN_WINDOW && th->syn && !estab)
2037     						if (sysctl_tcp_window_scaling) {
2038     							tp->wscale_ok = 1;
2039     							tp->snd_wscale = *(__u8 *)ptr;
2040     							if(tp->snd_wscale > 14) {
2041     								if(net_ratelimit())
2042     									printk("tcp_parse_options: Illegal window "
2043     									       "scaling value %d >14 received.",
2044     									       tp->snd_wscale);
2045     								tp->snd_wscale = 14;
2046     							}
2047     						}
2048     					break;
2049     				case TCPOPT_TIMESTAMP:
2050     					if(opsize==TCPOLEN_TIMESTAMP) {
2051     						if ((estab && tp->tstamp_ok) ||
2052     						    (!estab && sysctl_tcp_timestamps)) {
2053     							tp->saw_tstamp = 1;
2054     							tp->rcv_tsval = ntohl(*(__u32 *)ptr);
2055     							tp->rcv_tsecr = ntohl(*(__u32 *)(ptr+4));
2056     						}
2057     					}
2058     					break;
2059     				case TCPOPT_SACK_PERM:
2060     					if(opsize==TCPOLEN_SACK_PERM && th->syn && !estab) {
2061     						if (sysctl_tcp_sack) {
2062     							tp->sack_ok = 1;
2063     							tcp_sack_reset(tp);
2064     						}
2065     					}
2066     					break;
2067     
2068     				case TCPOPT_SACK:
2069     					if((opsize >= (TCPOLEN_SACK_BASE + TCPOLEN_SACK_PERBLOCK)) &&
2070     					   !((opsize - TCPOLEN_SACK_BASE) % TCPOLEN_SACK_PERBLOCK) &&
2071     					   tp->sack_ok) {
2072     						TCP_SKB_CB(skb)->sacked = (ptr - 2) - (unsigned char *)th;
2073     					}
2074     	  			};
2075     	  			ptr+=opsize-2;
2076     	  			length-=opsize;
2077     	  	};
2078     	}
2079     }
2080     
2081     /* Fast parse options. This hopes to only see timestamps.
2082      * If it is wrong it falls back on tcp_parse_options().
2083      */
2084     static __inline__ int tcp_fast_parse_options(struct sk_buff *skb, struct tcphdr *th, struct tcp_opt *tp)
2085     {
2086     	if (th->doff == sizeof(struct tcphdr)>>2) {
2087     		tp->saw_tstamp = 0;
2088     		return 0;
2089     	} else if (tp->tstamp_ok &&
2090     		   th->doff == (sizeof(struct tcphdr)>>2)+(TCPOLEN_TSTAMP_ALIGNED>>2)) {
2091     		__u32 *ptr = (__u32 *)(th + 1);
2092     		if (*ptr == __constant_ntohl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16)
2093     					     | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP)) {
2094     			tp->saw_tstamp = 1;
2095     			++ptr;
2096     			tp->rcv_tsval = ntohl(*ptr);
2097     			++ptr;
2098     			tp->rcv_tsecr = ntohl(*ptr);
2099     			return 1;
2100     		}
2101     	}
2102     	tcp_parse_options(skb, tp, 1);
2103     	return 1;
2104     }
2105     
2106     extern __inline__ void
2107     tcp_store_ts_recent(struct tcp_opt *tp)
2108     {
2109     	tp->ts_recent = tp->rcv_tsval;
2110     	tp->ts_recent_stamp = xtime.tv_sec;
2111     }
2112     
2113     extern __inline__ void
2114     tcp_replace_ts_recent(struct tcp_opt *tp, u32 seq)
2115     {
2116     	if (tp->saw_tstamp && !after(seq, tp->rcv_wup)) {
2117     		/* PAWS bug workaround wrt. ACK frames, the PAWS discard
2118     		 * extra check below makes sure this can only happen
2119     		 * for pure ACK frames.  -DaveM
2120     		 *
2121     		 * Not only, also it occurs for expired timestamps.
2122     		 */
2123     
2124     		if((s32)(tp->rcv_tsval - tp->ts_recent) >= 0 ||
2125     		   xtime.tv_sec >= tp->ts_recent_stamp + TCP_PAWS_24DAYS)
2126     			tcp_store_ts_recent(tp);
2127     	}
2128     }
2129     
2130     /* Sorry, PAWS as specified is broken wrt. pure-ACKs -DaveM
2131      *
2132      * It is not fatal. If this ACK does _not_ change critical state (seqs, window)
2133      * it can pass through stack. So, the following predicate verifies that
2134      * this segment is not used for anything but congestion avoidance or
2135      * fast retransmit. Moreover, we even are able to eliminate most of such
2136      * second order effects, if we apply some small "replay" window (~RTO)
2137      * to timestamp space.
2138      *
2139      * All these measures still do not guarantee that we reject wrapped ACKs
2140      * on networks with high bandwidth, when sequence space is recycled fastly,
2141      * but it guarantees that such events will be very rare and do not affect
2142      * connection seriously. This doesn't look nice, but alas, PAWS is really
2143      * buggy extension.
2144      *
2145      * [ Later note. Even worse! It is buggy for segments _with_ data. RFC
2146      * states that events when retransmit arrives after original data are rare.
2147      * It is a blatant lie. VJ forgot about fast retransmit! 8)8) It is
2148      * the biggest problem on large power networks even with minor reordering.
2149      * OK, let's give it small replay window. If peer clock is even 1hz, it is safe
2150      * up to bandwidth of 18Gigabit/sec. 8) ]
2151      */
2152     
2153     static int tcp_disordered_ack(struct tcp_opt *tp, struct sk_buff *skb)
2154     {
2155     	struct tcphdr *th = skb->h.th;
2156     	u32 seq = TCP_SKB_CB(skb)->seq;
2157     	u32 ack = TCP_SKB_CB(skb)->ack_seq;
2158     
2159     	return (/* 1. Pure ACK with correct sequence number. */
2160     		(th->ack && seq == TCP_SKB_CB(skb)->end_seq && seq == tp->rcv_nxt) &&
2161     
2162     		/* 2. ... and duplicate ACK. */
2163     		ack == tp->snd_una &&
2164     
2165     		/* 3. ... and does not update window. */
2166     		!tcp_may_update_window(tp, ack, seq, ntohs(th->window)<<tp->snd_wscale) &&
2167     
2168     		/* 4. ... and sits in replay window. */
2169     		(s32)(tp->ts_recent - tp->rcv_tsval) <= (tp->rto*1024)/HZ);
2170     }
2171     
2172     extern __inline__ int tcp_paws_discard(struct tcp_opt *tp, struct sk_buff *skb)
2173     {
2174     	return ((s32)(tp->ts_recent - tp->rcv_tsval) > TCP_PAWS_WINDOW &&
2175     		xtime.tv_sec < tp->ts_recent_stamp + TCP_PAWS_24DAYS &&
2176     		!tcp_disordered_ack(tp, skb));
2177     }
2178     
2179     /* Check segment sequence number for validity.
2180      *
2181      * Segment controls are considered valid, if the segment
2182      * fits to the window after truncation to the window. Acceptability
2183      * of data (and SYN, FIN, of course) is checked separately.
2184      * See tcp_data_queue(), for example.
2185      *
2186      * Also, controls (RST is main one) are accepted using RCV.WUP instead
2187      * of RCV.NXT. Peer still did not advance his SND.UNA when we
2188      * delayed ACK, so that hisSND.UNA<=ourRCV.WUP.
2189      * (borrowed from freebsd)
2190      */
2191     
2192     static inline int tcp_sequence(struct tcp_opt *tp, u32 seq, u32 end_seq)
2193     {
2194     	return	!before(end_seq, tp->rcv_wup) &&
2195     		!after(seq, tp->rcv_nxt + tcp_receive_window(tp));
2196     }
2197     
2198     /* When we get a reset we do this. */
2199     static void tcp_reset(struct sock *sk)
2200     {
2201     	/* We want the right error as BSD sees it (and indeed as we do). */
2202     	switch (sk->state) {
2203     		case TCP_SYN_SENT:
2204     			sk->err = ECONNREFUSED;
2205     			break;
2206     		case TCP_CLOSE_WAIT:
2207     			sk->err = EPIPE;
2208     			break;
2209     		case TCP_CLOSE:
2210     			return;
2211     		default:
2212     			sk->err = ECONNRESET;
2213     	}
2214     
2215     	if (!sk->dead)
2216     		sk->error_report(sk);
2217     
2218     	tcp_done(sk);
2219     }
2220     
2221     /*
2222      * 	Process the FIN bit. This now behaves as it is supposed to work
2223      *	and the FIN takes effect when it is validly part of sequence
2224      *	space. Not before when we get holes.
2225      *
2226      *	If we are ESTABLISHED, a received fin moves us to CLOSE-WAIT
2227      *	(and thence onto LAST-ACK and finally, CLOSE, we never enter
2228      *	TIME-WAIT)
2229      *
2230      *	If we are in FINWAIT-1, a received FIN indicates simultaneous
2231      *	close and we go into CLOSING (and later onto TIME-WAIT)
2232      *
2233      *	If we are in FINWAIT-2, a received FIN moves us to TIME-WAIT.
2234      */
2235     static void tcp_fin(struct sk_buff *skb, struct sock *sk, struct tcphdr *th)
2236     {
2237     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
2238     
2239     	tcp_schedule_ack(tp);
2240     
2241     	sk->shutdown |= RCV_SHUTDOWN;
2242     	sk->done = 1;
2243     
2244     	switch(sk->state) {
2245     		case TCP_SYN_RECV:
2246     		case TCP_ESTABLISHED:
2247     			/* Move to CLOSE_WAIT */
2248     			tcp_set_state(sk, TCP_CLOSE_WAIT);
2249     			tp->ack.pingpong = 1;
2250     			break;
2251     
2252     		case TCP_CLOSE_WAIT:
2253     		case TCP_CLOSING:
2254     			/* Received a retransmission of the FIN, do
2255     			 * nothing.
2256     			 */
2257     			break;
2258     		case TCP_LAST_ACK:
2259     			/* RFC793: Remain in the LAST-ACK state. */
2260     			break;
2261     
2262     		case TCP_FIN_WAIT1:
2263     			/* This case occurs when a simultaneous close
2264     			 * happens, we must ack the received FIN and
2265     			 * enter the CLOSING state.
2266     			 */
2267     			tcp_send_ack(sk);
2268     			tcp_set_state(sk, TCP_CLOSING);
2269     			break;
2270     		case TCP_FIN_WAIT2:
2271     			/* Received a FIN -- send ACK and enter TIME_WAIT. */
2272     			tcp_send_ack(sk);
2273     			tcp_time_wait(sk, TCP_TIME_WAIT, 0);
2274     			break;
2275     		default:
2276     			/* Only TCP_LISTEN and TCP_CLOSE are left, in these
2277     			 * cases we should never reach this piece of code.
2278     			 */
2279     			printk("tcp_fin: Impossible, sk->state=%d\n", sk->state);
2280     			break;
2281     	};
2282     
2283     	/* It _is_ possible, that we have something out-of-order _after_ FIN.
2284     	 * Probably, we should reset in this case. For now drop them.
2285     	 */
2286     	__skb_queue_purge(&tp->out_of_order_queue);
2287     	if (tp->sack_ok)
2288     		tcp_sack_reset(tp);
2289     	tcp_mem_reclaim(sk);
2290     
2291     	if (!sk->dead) {
2292     		sk->state_change(sk);
2293     
2294     		/* Do not send POLL_HUP for half duplex close. */
2295     		if (sk->shutdown == SHUTDOWN_MASK || sk->state == TCP_CLOSE)
2296     			sk_wake_async(sk, 1, POLL_HUP);
2297     		else
2298     			sk_wake_async(sk, 1, POLL_IN);
2299     	}
2300     }
2301     
2302     static __inline__ int
2303     tcp_sack_extend(struct tcp_sack_block *sp, u32 seq, u32 end_seq)
2304     {
2305     	if (!after(seq, sp->end_seq) && !after(sp->start_seq, end_seq)) {
2306     		if (before(seq, sp->start_seq))
2307     			sp->start_seq = seq;
2308     		if (after(end_seq, sp->end_seq))
2309     			sp->end_seq = end_seq;
2310     		return 1;
2311     	}
2312     	return 0;
2313     }
2314     
2315     static __inline__ void tcp_dsack_set(struct tcp_opt *tp, u32 seq, u32 end_seq)
2316     {
2317     	if (tp->sack_ok && sysctl_tcp_dsack) {
2318     		if (before(seq, tp->rcv_nxt))
2319     			NET_INC_STATS_BH(TCPDSACKOldSent);
2320     		else
2321     			NET_INC_STATS_BH(TCPDSACKOfoSent);
2322     
2323     		tp->dsack = 1;
2324     		tp->duplicate_sack[0].start_seq = seq;
2325     		tp->duplicate_sack[0].end_seq = end_seq;
2326     		tp->eff_sacks = min_t(unsigned int, tp->num_sacks+1, 4-tp->tstamp_ok);
2327     	}
2328     }
2329     
2330     static __inline__ void tcp_dsack_extend(struct tcp_opt *tp, u32 seq, u32 end_seq)
2331     {
2332     	if (!tp->dsack)
2333     		tcp_dsack_set(tp, seq, end_seq);
2334     	else
2335     		tcp_sack_extend(tp->duplicate_sack, seq, end_seq);
2336     }
2337     
2338     static void tcp_send_dupack(struct sock *sk, struct sk_buff *skb)
2339     {
2340     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
2341     
2342     	if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
2343     	    before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
2344     		NET_INC_STATS_BH(DelayedACKLost);
2345     		tcp_enter_quickack_mode(tp);
2346     
2347     		if (tp->sack_ok && sysctl_tcp_dsack) {
2348     			u32 end_seq = TCP_SKB_CB(skb)->end_seq;
2349     
2350     			if (after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt))
2351     				end_seq = tp->rcv_nxt;
2352     			tcp_dsack_set(tp, TCP_SKB_CB(skb)->seq, end_seq);
2353     		}
2354     	}
2355     
2356     	tcp_send_ack(sk);
2357     }
2358     
2359     /* These routines update the SACK block as out-of-order packets arrive or
2360      * in-order packets close up the sequence space.
2361      */
2362     static void tcp_sack_maybe_coalesce(struct tcp_opt *tp)
2363     {
2364     	int this_sack;
2365     	struct tcp_sack_block *sp = &tp->selective_acks[0];
2366     	struct tcp_sack_block *swalk = sp+1;
2367     
2368     	/* See if the recent change to the first SACK eats into
2369     	 * or hits the sequence space of other SACK blocks, if so coalesce.
2370     	 */
2371     	for (this_sack = 1; this_sack < tp->num_sacks; ) {
2372     		if (tcp_sack_extend(sp, swalk->start_seq, swalk->end_seq)) {
2373     			int i;
2374     
2375     			/* Zap SWALK, by moving every further SACK up by one slot.
2376     			 * Decrease num_sacks.
2377     			 */
2378     			tp->num_sacks--;
2379     			tp->eff_sacks = min_t(unsigned int, tp->num_sacks+tp->dsack, 4-tp->tstamp_ok);
2380     			for(i=this_sack; i < tp->num_sacks; i++)
2381     				sp[i] = sp[i+1];
2382     			continue;
2383     		}
2384     		this_sack++, swalk++;
2385     	}
2386     }
2387     
2388     static __inline__ void tcp_sack_swap(struct tcp_sack_block *sack1, struct tcp_sack_block *sack2)
2389     {
2390     	__u32 tmp;
2391     
2392     	tmp = sack1->start_seq;
2393     	sack1->start_seq = sack2->start_seq;
2394     	sack2->start_seq = tmp;
2395     
2396     	tmp = sack1->end_seq;
2397     	sack1->end_seq = sack2->end_seq;
2398     	sack2->end_seq = tmp;
2399     }
2400     
2401     static void tcp_sack_new_ofo_skb(struct sock *sk, u32 seq, u32 end_seq)
2402     {
2403     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
2404     	struct tcp_sack_block *sp = &tp->selective_acks[0];
2405     	int cur_sacks = tp->num_sacks;
2406     	int this_sack;
2407     
2408     	if (!cur_sacks)
2409     		goto new_sack;
2410     
2411     	for (this_sack=0; this_sack<cur_sacks; this_sack++, sp++) {
2412     		if (tcp_sack_extend(sp, seq, end_seq)) {
2413     			/* Rotate this_sack to the first one. */
2414     			for (; this_sack>0; this_sack--, sp--)
2415     				tcp_sack_swap(sp, sp-1);
2416     			if (cur_sacks > 1)
2417     				tcp_sack_maybe_coalesce(tp);
2418     			return;
2419     		}
2420     	}
2421     
2422     	/* Could not find an adjacent existing SACK, build a new one,
2423     	 * put it at the front, and shift everyone else down.  We
2424     	 * always know there is at least one SACK present already here.
2425     	 *
2426     	 * If the sack array is full, forget about the last one.
2427     	 */
2428     	if (this_sack >= 4) {
2429     		this_sack--;
2430     		tp->num_sacks--;
2431     		sp--;
2432     	}
2433     	for(; this_sack > 0; this_sack--, sp--)
2434     		*sp = *(sp-1);
2435     
2436     new_sack:
2437     	/* Build the new head SACK, and we're done. */
2438     	sp->start_seq = seq;
2439     	sp->end_seq = end_seq;
2440     	tp->num_sacks++;
2441     	tp->eff_sacks = min_t(unsigned int, tp->num_sacks+tp->dsack, 4-tp->tstamp_ok);
2442     }
2443     
2444     /* RCV.NXT advances, some SACKs should be eaten. */
2445     
2446     static void tcp_sack_remove(struct tcp_opt *tp)
2447     {
2448     	struct tcp_sack_block *sp = &tp->selective_acks[0];
2449     	int num_sacks = tp->num_sacks;
2450     	int this_sack;
2451     
2452     	/* Empty ofo queue, hence, all the SACKs are eaten. Clear. */
2453     	if (skb_queue_len(&tp->out_of_order_queue) == 0) {
2454     		tp->num_sacks = 0;
2455     		tp->eff_sacks = tp->dsack;
2456     		return;
2457     	}
2458     
2459     	for(this_sack = 0; this_sack < num_sacks; ) {
2460     		/* Check if the start of the sack is covered by RCV.NXT. */
2461     		if (!before(tp->rcv_nxt, sp->start_seq)) {
2462     			int i;
2463     
2464     			/* RCV.NXT must cover all the block! */
2465     			BUG_TRAP(!before(tp->rcv_nxt, sp->end_seq));
2466     
2467     			/* Zap this SACK, by moving forward any other SACKS. */
2468     			for (i=this_sack+1; i < num_sacks; i++)
2469     				sp[i-1] = sp[i];
2470     			num_sacks--;
2471     			continue;
2472     		}
2473     		this_sack++;
2474     		sp++;
2475     	}
2476     	if (num_sacks != tp->num_sacks) {
2477     		tp->num_sacks = num_sacks;
2478     		tp->eff_sacks = min_t(unsigned int, tp->num_sacks+tp->dsack, 4-tp->tstamp_ok);
2479     	}
2480     }
2481     
2482     /* This one checks to see if we can put data from the
2483      * out_of_order queue into the receive_queue.
2484      */
2485     static void tcp_ofo_queue(struct sock *sk)
2486     {
2487     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
2488     	__u32 dsack_high = tp->rcv_nxt;
2489     	struct sk_buff *skb;
2490     
2491     	while ((skb = skb_peek(&tp->out_of_order_queue)) != NULL) {
2492     		if (after(TCP_SKB_CB(skb)->seq, tp->rcv_nxt))
2493     			break;
2494     
2495     		if (before(TCP_SKB_CB(skb)->seq, dsack_high)) {
2496     			__u32 dsack = dsack_high;
2497     			if (before(TCP_SKB_CB(skb)->end_seq, dsack_high))
2498     				dsack_high = TCP_SKB_CB(skb)->end_seq;
2499     			tcp_dsack_extend(tp, TCP_SKB_CB(skb)->seq, dsack);
2500     		}
2501     
2502     		if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) {
2503     			SOCK_DEBUG(sk, "ofo packet was already received \n");
2504     			__skb_unlink(skb, skb->list);
2505     			__kfree_skb(skb);
2506     			continue;
2507     		}
2508     		SOCK_DEBUG(sk, "ofo requeuing : rcv_next %X seq %X - %X\n",
2509     			   tp->rcv_nxt, TCP_SKB_CB(skb)->seq,
2510     			   TCP_SKB_CB(skb)->end_seq);
2511     
2512     		__skb_unlink(skb, skb->list);
2513     		__skb_queue_tail(&sk->receive_queue, skb);
2514     		tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
2515     		if(skb->h.th->fin)
2516     			tcp_fin(skb, sk, skb->h.th);
2517     	}
2518     }
2519     
2520     static inline int tcp_rmem_schedule(struct sock *sk, struct sk_buff *skb)
2521     {
2522     	return (int)skb->truesize <= sk->forward_alloc ||
2523     		tcp_mem_schedule(sk, skb->truesize, 1);
2524     }
2525     
2526     static int tcp_prune_queue(struct sock *sk);
2527     
2528     static void tcp_data_queue(struct sock *sk, struct sk_buff *skb)
2529     {
2530     	struct tcphdr *th = skb->h.th;
2531     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
2532     	int eaten = -1;
2533     
2534     	if (TCP_SKB_CB(skb)->seq == TCP_SKB_CB(skb)->end_seq)
2535     		goto drop;
2536     
2537     	th = skb->h.th;
2538     	__skb_pull(skb, th->doff*4);
2539     
2540     	TCP_ECN_accept_cwr(tp, skb);
2541     
2542     	if (tp->dsack) {
2543     		tp->dsack = 0;
2544     		tp->eff_sacks = min_t(unsigned int, tp->num_sacks, 4-tp->tstamp_ok);
2545     	}
2546     
2547     	/*  Queue data for delivery to the user.
2548     	 *  Packets in sequence go to the receive queue.
2549     	 *  Out of sequence packets to the out_of_order_queue.
2550     	 */
2551     	if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt) {
2552     		if (tcp_receive_window(tp) == 0)
2553     			goto out_of_window;
2554     
2555     		/* Ok. In sequence. In window. */
2556     		if (tp->ucopy.task == current &&
2557     		    tp->copied_seq == tp->rcv_nxt &&
2558     		    tp->ucopy.len &&
2559     		    sk->lock.users &&
2560     		    !tp->urg_data) {
2561     			int chunk = min_t(unsigned int, skb->len, tp->ucopy.len);
2562     
2563     			__set_current_state(TASK_RUNNING);
2564     
2565     			local_bh_enable();
2566     			if (skb_copy_datagram_iovec(skb, 0, tp->ucopy.iov, chunk)) {
2567     				sk->err = EFAULT;
2568     				sk->error_report(sk);
2569     			}
2570     			local_bh_disable();
2571     			tp->ucopy.len -= chunk;
2572     			tp->copied_seq += chunk;
2573     			eaten = (chunk == skb->len && !th->fin);
2574     		}
2575     
2576     		if (eaten <= 0) {
2577     queue_and_out:
2578     			if (eaten < 0 &&
2579     			    (atomic_read(&sk->rmem_alloc) > sk->rcvbuf ||
2580     			     !tcp_rmem_schedule(sk, skb))) {
2581     				if (tcp_prune_queue(sk) < 0 || !tcp_rmem_schedule(sk, skb))
2582     					goto drop;
2583     			}
2584     			tcp_set_owner_r(skb, sk);
2585     			__skb_queue_tail(&sk->receive_queue, skb);
2586     		}
2587     		tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
2588     		if(skb->len)
2589     			tcp_event_data_recv(sk, tp, skb);
2590     		if(th->fin)
2591     			tcp_fin(skb, sk, th);
2592     
2593     		if (skb_queue_len(&tp->out_of_order_queue)) {
2594     			tcp_ofo_queue(sk);
2595     
2596     			/* RFC2581. 4.2. SHOULD send immediate ACK, when
2597     			 * gap in queue is filled.
2598     			 */
2599     			if (skb_queue_len(&tp->out_of_order_queue) == 0)
2600     				tp->ack.pingpong = 0;
2601     		}
2602     
2603     		if(tp->num_sacks)
2604     			tcp_sack_remove(tp);
2605     
2606     		tcp_fast_path_check(sk, tp);
2607     
2608     		if (eaten > 0) {
2609     			__kfree_skb(skb);
2610     		} else if (!sk->dead)
2611     			sk->data_ready(sk, 0);
2612     		return;
2613     	}
2614     
2615     	if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) {
2616     		/* A retransmit, 2nd most common case.  Force an immediate ack. */
2617     		NET_INC_STATS_BH(DelayedACKLost);
2618     		tcp_dsack_set(tp, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq);
2619     
2620     out_of_window:
2621     		tcp_enter_quickack_mode(tp);
2622     		tcp_schedule_ack(tp);
2623     drop:
2624     		__kfree_skb(skb);
2625     		return;
2626     	}
2627     
2628     	/* Out of window. F.e. zero window probe. */
2629     	if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt+tcp_receive_window(tp)))
2630     		goto out_of_window;
2631     
2632     	tcp_enter_quickack_mode(tp);
2633     
2634     	if (before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
2635     		/* Partial packet, seq < rcv_next < end_seq */
2636     		SOCK_DEBUG(sk, "partial packet: rcv_next %X seq %X - %X\n",
2637     			   tp->rcv_nxt, TCP_SKB_CB(skb)->seq,
2638     			   TCP_SKB_CB(skb)->end_seq);
2639     
2640     		tcp_dsack_set(tp, TCP_SKB_CB(skb)->seq, tp->rcv_nxt);
2641     		
2642     		/* If window is closed, drop tail of packet. But after
2643     		 * remembering D-SACK for its head made in previous line.
2644     		 */
2645     		if (!tcp_receive_window(tp))
2646     			goto out_of_window;
2647     		goto queue_and_out;
2648     	}
2649     
2650     	TCP_ECN_check_ce(tp, skb);
2651     
2652     	if (atomic_read(&sk->rmem_alloc) > sk->rcvbuf ||
2653     	    !tcp_rmem_schedule(sk, skb)) {
2654     		if (tcp_prune_queue(sk) < 0 || !tcp_rmem_schedule(sk, skb))
2655     			goto drop;
2656     	}
2657     
2658     	/* Disable header prediction. */
2659     	tp->pred_flags = 0;
2660     	tcp_schedule_ack(tp);
2661     
2662     	SOCK_DEBUG(sk, "out of order segment: rcv_next %X seq %X - %X\n",
2663     		   tp->rcv_nxt, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq);
2664     
2665     	tcp_set_owner_r(skb, sk);
2666     
2667     	if (skb_peek(&tp->out_of_order_queue) == NULL) {
2668     		/* Initial out of order segment, build 1 SACK. */
2669     		if(tp->sack_ok) {
2670     			tp->num_sacks = 1;
2671     			tp->dsack = 0;
2672     			tp->eff_sacks = 1;
2673     			tp->selective_acks[0].start_seq = TCP_SKB_CB(skb)->seq;
2674     			tp->selective_acks[0].end_seq = TCP_SKB_CB(skb)->end_seq;
2675     		}
2676     		__skb_queue_head(&tp->out_of_order_queue,skb);
2677     	} else {
2678     		struct sk_buff *skb1=tp->out_of_order_queue.prev;
2679     		u32 seq = TCP_SKB_CB(skb)->seq;
2680     		u32 end_seq = TCP_SKB_CB(skb)->end_seq;
2681     
2682     		if (seq == TCP_SKB_CB(skb1)->end_seq) {
2683     			__skb_append(skb1, skb);
2684     
2685     			if (tp->num_sacks == 0 ||
2686     			    tp->selective_acks[0].end_seq != seq)
2687     				goto add_sack;
2688     
2689     			/* Common case: data arrive in order after hole. */
2690     			tp->selective_acks[0].end_seq = end_seq;
2691     			return;
2692     		}
2693     
2694     		/* Find place to insert this segment. */
2695     		do {
2696     			if (!after(TCP_SKB_CB(skb1)->seq, seq))
2697     				break;
2698     		} while ((skb1=skb1->prev) != (struct sk_buff*)&tp->out_of_order_queue);
2699     
2700     		/* Do skb overlap to previous one? */
2701     		if (skb1 != (struct sk_buff*)&tp->out_of_order_queue &&
2702     		    before(seq, TCP_SKB_CB(skb1)->end_seq)) {
2703     			if (!after(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
2704     				/* All the bits are present. Drop. */
2705     				__kfree_skb(skb);
2706     				tcp_dsack_set(tp, seq, end_seq);
2707     				goto add_sack;
2708     			}
2709     			if (after(seq, TCP_SKB_CB(skb1)->seq)) {
2710     				/* Partial overlap. */
2711     				tcp_dsack_set(tp, seq, TCP_SKB_CB(skb1)->end_seq);
2712     			} else {
2713     				skb1 = skb1->prev;
2714     			}
2715     		}
2716     		__skb_insert(skb, skb1, skb1->next, &tp->out_of_order_queue);
2717     		
2718     		/* And clean segments covered by new one as whole. */
2719     		while ((skb1 = skb->next) != (struct sk_buff*)&tp->out_of_order_queue &&
2720     		       after(end_seq, TCP_SKB_CB(skb1)->seq)) {
2721     		       if (before(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
2722     			       tcp_dsack_extend(tp, TCP_SKB_CB(skb1)->seq, end_seq);
2723     			       break;
2724     		       }
2725     		       __skb_unlink(skb1, skb1->list);
2726     		       tcp_dsack_extend(tp, TCP_SKB_CB(skb1)->seq, TCP_SKB_CB(skb1)->end_seq);
2727     		       __kfree_skb(skb1);
2728     		}
2729     
2730     add_sack:
2731     		if (tp->sack_ok)
2732     			tcp_sack_new_ofo_skb(sk, seq, end_seq);
2733     	}
2734     }
2735     
2736     /* Collapse contiguous sequence of skbs head..tail with
2737      * sequence numbers start..end.
2738      * Segments with FIN/SYN are not collapsed (only because this
2739      * simplifies code)
2740      */
2741     static void
2742     tcp_collapse(struct sock *sk, struct sk_buff *head,
2743     	     struct sk_buff *tail, u32 start, u32 end)
2744     {
2745     	struct sk_buff *skb;
2746     
2747     	/* First, check that queue is collapsable and find
2748     	 * the point where collapsing can be useful. */
2749     	for (skb = head; skb != tail; ) {
2750     		/* No new bits? It is possible on ofo queue. */
2751     		if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
2752     			struct sk_buff *next = skb->next;
2753     			__skb_unlink(skb, skb->list);
2754     			__kfree_skb(skb);
2755     			NET_INC_STATS_BH(TCPRcvCollapsed);
2756     			skb = next;
2757     			continue;
2758     		}
2759     
2760     		/* The first skb to collapse is:
2761     		 * - not SYN/FIN and
2762     		 * - bloated or contains data before "start" or
2763     		 *   overlaps to the next one.
2764     		 */
2765     		if (!skb->h.th->syn && !skb->h.th->fin &&
2766     		    (tcp_win_from_space(skb->truesize) > skb->len ||
2767     		     before(TCP_SKB_CB(skb)->seq, start) ||
2768     		     (skb->next != tail &&
2769     		      TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb->next)->seq)))
2770     			break;
2771     
2772     		/* Decided to skip this, advance start seq. */
2773     		start = TCP_SKB_CB(skb)->end_seq;
2774     		skb = skb->next;
2775     	}
2776     	if (skb == tail || skb->h.th->syn || skb->h.th->fin)
2777     		return;
2778     
2779     	while (before(start, end)) {
2780     		struct sk_buff *nskb;
2781     		int header = skb_headroom(skb);
2782     		int copy = (PAGE_SIZE - sizeof(struct sk_buff) -
2783     			    sizeof(struct skb_shared_info) - header - 31)&~15;
2784     
2785     		/* Too big header? This can happen with IPv6. */
2786     		if (copy < 0)
2787     			return;
2788     		if (end-start < copy)
2789     			copy = end-start;
2790     		nskb = alloc_skb(copy+header, GFP_ATOMIC);
2791     		if (!nskb)
2792     			return;
2793     		skb_reserve(nskb, header);
2794     		memcpy(nskb->head, skb->head, header);
2795     		nskb->nh.raw = nskb->head + (skb->nh.raw-skb->head);
2796     		nskb->h.raw = nskb->head + (skb->h.raw-skb->head);
2797     		nskb->mac.raw = nskb->head + (skb->mac.raw-skb->head);
2798     		memcpy(nskb->cb, skb->cb, sizeof(skb->cb));
2799     		TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(nskb)->end_seq = start;
2800     		__skb_insert(nskb, skb->prev, skb, skb->list);
2801     		tcp_set_owner_r(nskb, sk);
2802     
2803     		/* Copy data, releasing collapsed skbs. */
2804     		while (copy > 0) {
2805     			int offset = start - TCP_SKB_CB(skb)->seq;
2806     			int size = TCP_SKB_CB(skb)->end_seq - start;
2807     
2808     			if (offset < 0) BUG();
2809     			if (size > 0) {
2810     				size = min_t(int, copy, size);
2811     				if (skb_copy_bits(skb, offset, skb_put(nskb, size), size))
2812     					BUG();
2813     				TCP_SKB_CB(nskb)->end_seq += size;
2814     				copy -= size;
2815     				start += size;
2816     			}
2817     			if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
2818     				struct sk_buff *next = skb->next;
2819     				__skb_unlink(skb, skb->list);
2820     				__kfree_skb(skb);
2821     				NET_INC_STATS_BH(TCPRcvCollapsed);
2822     				skb = next;
2823     				if (skb == tail || skb->h.th->syn || skb->h.th->fin)
2824     					return;
2825     			}
2826     		}
2827     	}
2828     }
2829     
2830     /* Collapse ofo queue. Algorithm: select contiguous sequence of skbs
2831      * and tcp_collapse() them until all the queue is collapsed.
2832      */
2833     static void tcp_collapse_ofo_queue(struct sock *sk)
2834     {
2835     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
2836     	struct sk_buff *skb = skb_peek(&tp->out_of_order_queue);
2837     	struct sk_buff *head;
2838     	u32 start, end;
2839     
2840     	if (skb == NULL)
2841     		return;
2842     
2843     	start = TCP_SKB_CB(skb)->seq;
2844     	end = TCP_SKB_CB(skb)->end_seq;
2845     	head = skb;
2846     
2847     	for (;;) {
2848     		skb = skb->next;
2849     
2850     		/* Segment is terminated when we see gap or when
2851     		 * we are at the end of all the queue. */
2852     		if (skb == (struct sk_buff *)&tp->out_of_order_queue ||
2853     		    after(TCP_SKB_CB(skb)->seq, end) ||
2854     		    before(TCP_SKB_CB(skb)->end_seq, start)) {
2855     			tcp_collapse(sk, head, skb, start, end);
2856     			head = skb;
2857     			if (skb == (struct sk_buff *)&tp->out_of_order_queue)
2858     				break;
2859     			/* Start new segment */
2860     			start = TCP_SKB_CB(skb)->seq;
2861     			end = TCP_SKB_CB(skb)->end_seq;
2862     		} else {
2863     			if (before(TCP_SKB_CB(skb)->seq, start))
2864     				start = TCP_SKB_CB(skb)->seq;
2865     			if (after(TCP_SKB_CB(skb)->end_seq, end))
2866     				end = TCP_SKB_CB(skb)->end_seq;
2867     		}
2868     	}
2869     }
2870     
2871     /* Reduce allocated memory if we can, trying to get
2872      * the socket within its memory limits again.
2873      *
2874      * Return less than zero if we should start dropping frames
2875      * until the socket owning process reads some of the data
2876      * to stabilize the situation.
2877      */
2878     static int tcp_prune_queue(struct sock *sk)
2879     {
2880     	struct tcp_opt *tp = &sk->tp_pinfo.af_tcp; 
2881     
2882     	SOCK_DEBUG(sk, "prune_queue: c=%x\n", tp->copied_seq);
2883     
2884     	NET_INC_STATS_BH(PruneCalled);
2885     
2886     	if (atomic_read(&sk->rmem_alloc) >= sk->rcvbuf)
2887     		tcp_clamp_window(sk, tp);
2888     	else if (tcp_memory_pressure)
2889     		tp->rcv_ssthresh = min_t(u32, tp->rcv_ssthresh, 4*tp->advmss);
2890     
2891     	tcp_collapse_ofo_queue(sk);
2892     	tcp_collapse(sk, sk->receive_queue.next,
2893     		     (struct sk_buff*)&sk->receive_queue,
2894     		     tp->copied_seq, tp->rcv_nxt);
2895     	tcp_mem_reclaim(sk);
2896     
2897     	if (atomic_read(&sk->rmem_alloc) <= sk->rcvbuf)
2898     		return 0;
2899     
2900     	/* Collapsing did not help, destructive actions follow.
2901     	 * This must not ever occur. */
2902     
2903     	/* First, purge the out_of_order queue. */
2904     	if (skb_queue_len(&tp->out_of_order_queue)) {
2905     		net_statistics[smp_processor_id()*2].OfoPruned += skb_queue_len(&tp->out_of_order_queue);
2906     		__skb_queue_purge(&tp->out_of_order_queue);
2907     
2908     		/* Reset SACK state.  A conforming SACK implementation will
2909     		 * do the same at a timeout based retransmit.  When a connection
2910     		 * is in a sad state like this, we care only about integrity
2911     		 * of the connection not performance.
2912     		 */
2913     		if(tp->sack_ok)
2914     			tcp_sack_reset(tp);
2915     		tcp_mem_reclaim(sk);
2916     	}
2917     
2918     	if(atomic_read(&sk->rmem_alloc) <= sk->rcvbuf)
2919     		return 0;
2920     
2921     	/* If we are really being abused, tell the caller to silently
2922     	 * drop receive data on the floor.  It will get retransmitted
2923     	 * and hopefully then we'll have sufficient space.
2924     	 */
2925     	NET_INC_STATS_BH(RcvPruned);
2926     
2927     	/* Massive buffer overcommit. */
2928     	tp->pred_flags = 0;
2929     	return -1;
2930     }
2931     
2932     
2933     /* RFC2861, slow part. Adjust cwnd, after it was not full during one rto.
2934      * As additional protections, we do not touch cwnd in retransmission phases,
2935      * and if application hit its sndbuf limit recently.
2936      */
2937     void tcp_cwnd_application_limited(struct sock *sk)
2938     {
2939     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
2940     
2941     	if (tp->ca_state == TCP_CA_Open &&
2942     	    sk->socket && !test_bit(SOCK_NOSPACE, &sk->socket->flags)) {
2943     		/* Limited by application or receiver window. */
2944     		u32 win_used = max_t(u32, tp->snd_cwnd_used, 2);
2945     		if (win_used < tp->snd_cwnd) {
2946     			tp->snd_ssthresh = tcp_current_ssthresh(tp);
2947     			tp->snd_cwnd = (tp->snd_cwnd+win_used)>>1;
2948     		}
2949     		tp->snd_cwnd_used = 0;
2950     	}
2951     	tp->snd_cwnd_stamp = tcp_time_stamp;
2952     }
2953     
2954     
2955     /* When incoming ACK allowed to free some skb from write_queue,
2956      * we remember this event in flag tp->queue_shrunk and wake up socket
2957      * on the exit from tcp input handler.
2958      */
2959     static void tcp_new_space(struct sock *sk)
2960     {
2961     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
2962     
2963     	if (tp->packets_out < tp->snd_cwnd &&
2964     	    !(sk->userlocks&SOCK_SNDBUF_LOCK) &&
2965     	    !tcp_memory_pressure &&
2966     	    atomic_read(&tcp_memory_allocated) < sysctl_tcp_mem[0]) {
2967     		int sndmem, demanded;
2968     
2969     		sndmem = tp->mss_clamp+MAX_TCP_HEADER+16+sizeof(struct sk_buff);
2970     		demanded = max_t(unsigned int, tp->snd_cwnd, tp->reordering+1);
2971     		sndmem *= 2*demanded;
2972     		if (sndmem > sk->sndbuf)
2973     			sk->sndbuf = min_t(int, sndmem, sysctl_tcp_wmem[2]);
2974     		tp->snd_cwnd_stamp = tcp_time_stamp;
2975     	}
2976     
2977     	sk->write_space(sk);
2978     }
2979     
2980     static inline void tcp_check_space(struct sock *sk)
2981     {
2982     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
2983     
2984     	if (tp->queue_shrunk) {
2985     		tp->queue_shrunk = 0;
2986     		if (sk->socket && test_bit(SOCK_NOSPACE, &sk->socket->flags))
2987     			tcp_new_space(sk);
2988     	}
2989     }
2990     
2991     static void __tcp_data_snd_check(struct sock *sk, struct sk_buff *skb)
2992     {
2993     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
2994     
2995     	if (after(TCP_SKB_CB(skb)->end_seq, tp->snd_una + tp->snd_wnd) ||
2996     	    tcp_packets_in_flight(tp) >= tp->snd_cwnd ||
2997     	    tcp_write_xmit(sk, tp->nonagle))
2998     		tcp_check_probe_timer(sk, tp);
2999     }
3000     
3001     static __inline__ void tcp_data_snd_check(struct sock *sk)
3002     {
3003     	struct sk_buff *skb = sk->tp_pinfo.af_tcp.send_head;
3004     
3005     	if (skb != NULL)
3006     		__tcp_data_snd_check(sk, skb);
3007     	tcp_check_space(sk);
3008     }
3009     
3010     /*
3011      * Check if sending an ack is needed.
3012      */
3013     static __inline__ void __tcp_ack_snd_check(struct sock *sk, int ofo_possible)
3014     {
3015     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
3016     
3017     	    /* More than one full frame received... */
3018     	if (((tp->rcv_nxt - tp->rcv_wup) > tp->ack.rcv_mss
3019     	     /* ... and right edge of window advances far enough.
3020     	      * (tcp_recvmsg() will send ACK otherwise). Or...
3021     	      */
3022     	     && __tcp_select_window(sk) >= tp->rcv_wnd) ||
3023     	    /* We ACK each frame or... */
3024     	    tcp_in_quickack_mode(tp) ||
3025     	    /* We have out of order data. */
3026     	    (ofo_possible &&
3027     	     skb_peek(&tp->out_of_order_queue) != NULL)) {
3028     		/* Then ack it now */
3029     		tcp_send_ack(sk);
3030     	} else {
3031     		/* Else, send delayed ack. */
3032     		tcp_send_delayed_ack(sk);
3033     	}
3034     }
3035     
3036     static __inline__ void tcp_ack_snd_check(struct sock *sk)
3037     {
3038     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
3039     	if (!tcp_ack_scheduled(tp)) {
3040     		/* We sent a data segment already. */
3041     		return;
3042     	}
3043     	__tcp_ack_snd_check(sk, 1);
3044     }
3045     
3046     /*
3047      *	This routine is only called when we have urgent data
3048      *	signalled. Its the 'slow' part of tcp_urg. It could be
3049      *	moved inline now as tcp_urg is only called from one
3050      *	place. We handle URGent data wrong. We have to - as
3051      *	BSD still doesn't use the correction from RFC961.
3052      *	For 1003.1g we should support a new option TCP_STDURG to permit
3053      *	either form (or just set the sysctl tcp_stdurg).
3054      */
3055      
3056     static void tcp_check_urg(struct sock * sk, struct tcphdr * th)
3057     {
3058     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
3059     	u32 ptr = ntohs(th->urg_ptr);
3060     
3061     	if (ptr && !sysctl_tcp_stdurg)
3062     		ptr--;
3063     	ptr += ntohl(th->seq);
3064     
3065     	/* Ignore urgent data that we've already seen and read. */
3066     	if (after(tp->copied_seq, ptr))
3067     		return;
3068     
3069     	/* Do not replay urg ptr.
3070     	 *
3071     	 * NOTE: interesting situation not covered by specs.
3072     	 * Misbehaving sender may send urg ptr, pointing to segment,
3073     	 * which we already have in ofo queue. We are not able to fetch
3074     	 * such data and will stay in TCP_URG_NOTYET until will be eaten
3075     	 * by recvmsg(). Seems, we are not obliged to handle such wicked
3076     	 * situations. But it is worth to think about possibility of some
3077     	 * DoSes using some hypothetical application level deadlock.
3078     	 */
3079     	if (before(ptr, tp->rcv_nxt))
3080     		return;
3081     
3082     	/* Do we already have a newer (or duplicate) urgent pointer? */
3083     	if (tp->urg_data && !after(ptr, tp->urg_seq))
3084     		return;
3085     
3086     	/* Tell the world about our new urgent pointer. */
3087     	if (sk->proc != 0) {
3088     		if (sk->proc > 0)
3089     			kill_proc(sk->proc, SIGURG, 1);
3090     		else
3091     			kill_pg(-sk->proc, SIGURG, 1);
3092     		sk_wake_async(sk, 3, POLL_PRI);
3093     	}
3094     
3095     	/* We may be adding urgent data when the last byte read was
3096     	 * urgent. To do this requires some care. We cannot just ignore
3097     	 * tp->copied_seq since we would read the last urgent byte again
3098     	 * as data, nor can we alter copied_seq until this data arrives
3099     	 * or we break the sematics of SIOCATMARK (and thus sockatmark())
3100     	 *
3101     	 * NOTE. Double Dutch. Rendering to plain English: author of comment
3102     	 * above did something sort of 	send("A", MSG_OOB); send("B", MSG_OOB);
3103     	 * and expect that both A and B disappear from stream. This is _wrong_.
3104     	 * Though this happens in BSD with high probability, this is occasional.
3105     	 * Any application relying on this is buggy. Note also, that fix "works"
3106     	 * only in this artificial test. Insert some normal data between A and B and we will
3107     	 * decline of BSD again. Verdict: it is better to remove to trap
3108     	 * buggy users.
3109     	 */
3110     	if (tp->urg_seq == tp->copied_seq && tp->urg_data &&
3111     	    !sk->urginline &&
3112     	    tp->copied_seq != tp->rcv_nxt) {
3113     		struct sk_buff *skb = skb_peek(&sk->receive_queue);
3114     		tp->copied_seq++;
3115     		if (skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq)) {
3116     			__skb_unlink(skb, skb->list);
3117     			__kfree_skb(skb);
3118     		}
3119     	}
3120     
3121     	tp->urg_data = TCP_URG_NOTYET;
3122     	tp->urg_seq = ptr;
3123     
3124     	/* Disable header prediction. */
3125     	tp->pred_flags = 0;
3126     }
3127     
3128     /* This is the 'fast' part of urgent handling. */
3129     static inline void tcp_urg(struct sock *sk, struct sk_buff *skb, struct tcphdr *th)
3130     {
3131     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
3132     
3133     	/* Check if we get a new urgent pointer - normally not. */
3134     	if (th->urg)
3135     		tcp_check_urg(sk,th);
3136     
3137     	/* Do we wait for any urgent data? - normally not... */
3138     	if (tp->urg_data == TCP_URG_NOTYET) {
3139     		u32 ptr = tp->urg_seq - ntohl(th->seq) + (th->doff*4) - th->syn;
3140     
3141     		/* Is the urgent pointer pointing into this packet? */	 
3142     		if (ptr < skb->len) {
3143     			u8 tmp;
3144     			if (skb_copy_bits(skb, ptr, &tmp, 1))
3145     				BUG();
3146     			tp->urg_data = TCP_URG_VALID | tmp;
3147     			if (!sk->dead)
3148     				sk->data_ready(sk,0);
3149     		}
3150     	}
3151     }
3152     
3153     static int tcp_copy_to_iovec(struct sock *sk, struct sk_buff *skb, int hlen)
3154     {
3155     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
3156     	int chunk = skb->len - hlen;
3157     	int err;
3158     
3159     	local_bh_enable();
3160     	if (skb->ip_summed==CHECKSUM_UNNECESSARY)
3161     		err = skb_copy_datagram_iovec(skb, hlen, tp->ucopy.iov, chunk);
3162     	else
3163     		err = skb_copy_and_csum_datagram_iovec(skb, hlen, tp->ucopy.iov);
3164     
3165     	if (!err) {
3166     update:
3167     		tp->ucopy.len -= chunk;
3168     		tp->copied_seq += chunk;
3169     		local_bh_disable();
3170     		return 0;
3171     	}
3172     
3173     	if (err == -EFAULT) {
3174     		sk->err = EFAULT;
3175     		sk->error_report(sk);
3176     		goto update;
3177     	}
3178     
3179     	local_bh_disable();
3180     	return err;
3181     }
3182     
3183     static int __tcp_checksum_complete_user(struct sock *sk, struct sk_buff *skb)
3184     {
3185     	int result;
3186     
3187     	if (sk->lock.users) {
3188     		local_bh_enable();
3189     		result = __tcp_checksum_complete(skb);
3190     		local_bh_disable();
3191     	} else {
3192     		result = __tcp_checksum_complete(skb);
3193     	}
3194     	return result;
3195     }
3196     
3197     static __inline__ int
3198     tcp_checksum_complete_user(struct sock *sk, struct sk_buff *skb)
3199     {
3200     	return skb->ip_summed != CHECKSUM_UNNECESSARY &&
3201     		__tcp_checksum_complete_user(sk, skb);
3202     }
3203     
3204     /*
3205      *	TCP receive function for the ESTABLISHED state. 
3206      *
3207      *	It is split into a fast path and a slow path. The fast path is 
3208      * 	disabled when:
3209      *	- A zero window was announced from us - zero window probing
3210      *        is only handled properly in the slow path. 
3211      *	- Out of order segments arrived.
3212      *	- Urgent data is expected.
3213      *	- There is no buffer space left
3214      *	- Unexpected TCP flags/window values/header lengths are received
3215      *	  (detected by checking the TCP header against pred_flags) 
3216      *	- Data is sent in both directions. Fast path only supports pure senders
3217      *	  or pure receivers (this means either the sequence number or the ack
3218      *	  value must stay constant)
3219      *	- Unexpected TCP option.
3220      *
3221      *	When these conditions are not satisfied it drops into a standard 
3222      *	receive procedure patterned after RFC793 to handle all cases.
3223      *	The first three cases are guaranteed by proper pred_flags setting,
3224      *	the rest is checked inline. Fast processing is turned on in 
3225      *	tcp_data_queue when everything is OK.
3226      */
3227     int tcp_rcv_established(struct sock *sk, struct sk_buff *skb,
3228     			struct tcphdr *th, unsigned len)
3229     {
3230     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
3231     
3232     	/*
3233     	 *	Header prediction.
3234     	 *	The code losely follows the one in the famous 
3235     	 *	"30 instruction TCP receive" Van Jacobson mail.
3236     	 *	
3237     	 *	Van's trick is to deposit buffers into socket queue 
3238     	 *	on a device interrupt, to call tcp_recv function
3239     	 *	on the receive process context and checksum and copy
3240     	 *	the buffer to user space. smart...
3241     	 *
3242     	 *	Our current scheme is not silly either but we take the 
3243     	 *	extra cost of the net_bh soft interrupt processing...
3244     	 *	We do checksum and copy also but from device to kernel.
3245     	 */
3246     
3247     	tp->saw_tstamp = 0;
3248     
3249     	/*	pred_flags is 0xS?10 << 16 + snd_wnd
3250     	 *	if header_predition is to be made
3251     	 *	'S' will always be tp->tcp_header_len >> 2
3252     	 *	'?' will be 0 for the fast path, otherwise pred_flags is 0 to
3253     	 *  turn it off	(when there are holes in the receive 
3254     	 *	 space for instance)
3255     	 *	PSH flag is ignored.
3256     	 */
3257     
3258     	if ((tcp_flag_word(th) & TCP_HP_BITS) == tp->pred_flags &&
3259     		TCP_SKB_CB(skb)->seq == tp->rcv_nxt) {
3260     		int tcp_header_len = tp->tcp_header_len;
3261     
3262     		/* Timestamp header prediction: tcp_header_len
3263     		 * is automatically equal to th->doff*4 due to pred_flags
3264     		 * match.
3265     		 */
3266     
3267     		/* Check timestamp */
3268     		if (tcp_header_len == sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) {
3269     			__u32 *ptr = (__u32 *)(th + 1);
3270     
3271     			/* No? Slow path! */
3272     			if (*ptr != __constant_ntohl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16)
3273     						     | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP))
3274     				goto slow_path;
3275     
3276     			tp->saw_tstamp = 1;
3277     			++ptr; 
3278     			tp->rcv_tsval = ntohl(*ptr);
3279     			++ptr;
3280     			tp->rcv_tsecr = ntohl(*ptr);
3281     
3282     			/* If PAWS failed, check it more carefully in slow path */
3283     			if ((s32)(tp->rcv_tsval - tp->ts_recent) < 0)
3284     				goto slow_path;
3285     
3286     			/* Predicted packet is in window by definition.
3287     			 * seq == rcv_nxt and rcv_wup <= rcv_nxt.
3288     			 * Hence, check seq<=rcv_wup reduces to:
3289     			 */
3290     			if (tp->rcv_nxt == tp->rcv_wup)
3291     				tcp_store_ts_recent(tp);
3292     		}
3293     
3294     		if (len <= tcp_header_len) {
3295     			/* Bulk data transfer: sender */
3296     			if (len == tcp_header_len) {
3297     				/* We know that such packets are checksummed
3298     				 * on entry.
3299     				 */
3300     				tcp_ack(sk, skb, 0);
3301     				__kfree_skb(skb); 
3302     				tcp_data_snd_check(sk);
3303     				return 0;
3304     			} else { /* Header too small */
3305     				TCP_INC_STATS_BH(TcpInErrs);
3306     				goto discard;
3307     			}
3308     		} else {
3309     			int eaten = 0;
3310     
3311     			if (tp->ucopy.task == current &&
3312     			    tp->copied_seq == tp->rcv_nxt &&
3313     			    len - tcp_header_len <= tp->ucopy.len &&
3314     			    sk->lock.users) {
3315     				eaten = 1;
3316     
3317     				NET_INC_STATS_BH(TCPHPHitsToUser);
3318     
3319     				__set_current_state(TASK_RUNNING);
3320     
3321     				if (tcp_copy_to_iovec(sk, skb, tcp_header_len))
3322     					goto csum_error;
3323     
3324     				__skb_pull(skb,tcp_header_len);
3325     
3326     				tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
3327     			} else {
3328     				if (tcp_checksum_complete_user(sk, skb))
3329     					goto csum_error;
3330     
3331     				if ((int)skb->truesize > sk->forward_alloc)
3332     					goto step5;
3333     
3334     				NET_INC_STATS_BH(TCPHPHits);
3335     
3336     				/* Bulk data transfer: receiver */
3337     				__skb_pull(skb,tcp_header_len);
3338     				__skb_queue_tail(&sk->receive_queue, skb);
3339     				tcp_set_owner_r(skb, sk);
3340     				tp->rcv_nxt = TCP_SKB_CB(skb)->end_seq;
3341     			}
3342     
3343     			tcp_event_data_recv(sk, tp, skb);
3344     
3345     			if (TCP_SKB_CB(skb)->ack_seq != tp->snd_una) {
3346     				/* Well, only one small jumplet in fast path... */
3347     				tcp_ack(sk, skb, FLAG_DATA);
3348     				tcp_data_snd_check(sk);
3349     				if (!tcp_ack_scheduled(tp))
3350     					goto no_ack;
3351     			}
3352     
3353     			if (eaten) {
3354     				if (tcp_in_quickack_mode(tp)) {
3355     					tcp_send_ack(sk);
3356     				} else {
3357     					tcp_send_delayed_ack(sk);
3358     				}
3359     			} else {
3360     				__tcp_ack_snd_check(sk, 0);
3361     			}
3362     
3363     no_ack:
3364     			if (eaten)
3365     				__kfree_skb(skb);
3366     			else
3367     				sk->data_ready(sk, 0);
3368     			return 0;
3369     		}
3370     	}
3371     
3372     slow_path:
3373     	if (len < (th->doff<<2) || tcp_checksum_complete_user(sk, skb))
3374     		goto csum_error;
3375     
3376     	/*
3377     	 * RFC1323: H1. Apply PAWS check first.
3378     	 */
3379     	if (tcp_fast_parse_options(skb, th, tp) && tp->saw_tstamp &&
3380     	    tcp_paws_discard(tp, skb)) {
3381     		if (!th->rst) {
3382     			NET_INC_STATS_BH(PAWSEstabRejected);
3383     			tcp_send_dupack(sk, skb);
3384     			goto discard;
3385     		}
3386     		/* Resets are accepted even if PAWS failed.
3387     
3388     		   ts_recent update must be made after we are sure
3389     		   that the packet is in window.
3390     		 */
3391     	}
3392     
3393     	/*
3394     	 *	Standard slow path.
3395     	 */
3396     
3397     	if (!tcp_sequence(tp, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq)) {
3398     		/* RFC793, page 37: "In all states except SYN-SENT, all reset
3399     		 * (RST) segments are validated by checking their SEQ-fields."
3400     		 * And page 69: "If an incoming segment is not acceptable,
3401     		 * an acknowledgment should be sent in reply (unless the RST bit
3402     		 * is set, if so drop the segment and return)".
3403     		 */
3404     		if (!th->rst)
3405     			tcp_send_dupack(sk, skb);
3406     		goto discard;
3407     	}
3408     
3409     	if(th->rst) {
3410     		tcp_reset(sk);
3411     		goto discard;
3412     	}
3413     
3414     	tcp_replace_ts_recent(tp, TCP_SKB_CB(skb)->seq);
3415     
3416     	if (th->syn && !before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
3417     		TCP_INC_STATS_BH(TcpInErrs);
3418     		NET_INC_STATS_BH(TCPAbortOnSyn);
3419     		tcp_reset(sk);
3420     		return 1;
3421     	}
3422     
3423     step5:
3424     	if(th->ack)
3425     		tcp_ack(sk, skb, FLAG_SLOWPATH);
3426     
3427     	/* Process urgent data. */
3428     	tcp_urg(sk, skb, th);
3429     
3430     	/* step 7: process the segment text */
3431     	tcp_data_queue(sk, skb);
3432     
3433     	tcp_data_snd_check(sk);
3434     	tcp_ack_snd_check(sk);
3435     	return 0;
3436     
3437     csum_error:
3438     	TCP_INC_STATS_BH(TcpInErrs);
3439     
3440     discard:
3441     	__kfree_skb(skb);
3442     	return 0;
3443     }
3444     
3445     static int tcp_rcv_synsent_state_process(struct sock *sk, struct sk_buff *skb,
3446     					 struct tcphdr *th, unsigned len)
3447     {
3448     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
3449     	int saved_clamp = tp->mss_clamp;
3450     
3451     	tcp_parse_options(skb, tp, 0);
3452     
3453     	if (th->ack) {
3454     		/* rfc793:
3455     		 * "If the state is SYN-SENT then
3456     		 *    first check the ACK bit
3457     		 *      If the ACK bit is set
3458     		 *	  If SEG.ACK =< ISS, or SEG.ACK > SND.NXT, send
3459     		 *        a reset (unless the RST bit is set, if so drop
3460     		 *        the segment and return)"
3461     		 *
3462     		 *  We do not send data with SYN, so that RFC-correct
3463     		 *  test reduces to:
3464     		 */
3465     		if (TCP_SKB_CB(skb)->ack_seq != tp->snd_nxt)
3466     			goto reset_and_undo;
3467     
3468     		if (tp->saw_tstamp && tp->rcv_tsecr &&
3469     		    !between(tp->rcv_tsecr, tp->retrans_stamp, tcp_time_stamp)) {
3470     			NET_INC_STATS_BH(PAWSActiveRejected);
3471     			goto reset_and_undo;
3472     		}
3473     
3474     		/* Now ACK is acceptable.
3475     		 *
3476     		 * "If the RST bit is set
3477     		 *    If the ACK was acceptable then signal the user "error:
3478     		 *    connection reset", drop the segment, enter CLOSED state,
3479     		 *    delete TCB, and return."
3480     		 */
3481     
3482     		if (th->rst) {
3483     			tcp_reset(sk);
3484     			goto discard;
3485     		}
3486     
3487     		/* rfc793:
3488     		 *   "fifth, if neither of the SYN or RST bits is set then
3489     		 *    drop the segment and return."
3490     		 *
3491     		 *    See note below!
3492     		 *                                        --ANK(990513)
3493     		 */
3494     		if (!th->syn)
3495     			goto discard_and_undo;
3496     
3497     		/* rfc793:
3498     		 *   "If the SYN bit is on ...
3499     		 *    are acceptable then ...
3500     		 *    (our SYN has been ACKed), change the connection
3501     		 *    state to ESTABLISHED..."
3502     		 */
3503     
3504     		TCP_ECN_rcv_synack(tp, th);
3505     
3506     		tp->snd_wl1 = TCP_SKB_CB(skb)->seq;
3507     		tcp_ack(sk, skb, FLAG_SLOWPATH);
3508     
3509     		/* Ok.. it's good. Set up sequence numbers and
3510     		 * move to established.
3511     		 */
3512     		tp->rcv_nxt = TCP_SKB_CB(skb)->seq+1;
3513     		tp->rcv_wup = TCP_SKB_CB(skb)->seq+1;
3514     
3515     		/* RFC1323: The window in SYN & SYN/ACK segments is
3516     		 * never scaled.
3517     		 */
3518     		tp->snd_wnd = ntohs(th->window);
3519     		tcp_init_wl(tp, TCP_SKB_CB(skb)->ack_seq, TCP_SKB_CB(skb)->seq);
3520     
3521     		if (tp->wscale_ok == 0) {
3522     			tp->snd_wscale = tp->rcv_wscale = 0;
3523     			tp->window_clamp = min_t(u32, tp->window_clamp, 65535);
3524     		}
3525     
3526     		if (tp->saw_tstamp) {
3527     			tp->tstamp_ok = 1;
3528     			tp->tcp_header_len =
3529     				sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
3530     			tp->advmss -= TCPOLEN_TSTAMP_ALIGNED;
3531     			tcp_store_ts_recent(tp);
3532     		} else {
3533     			tp->tcp_header_len = sizeof(struct tcphdr);
3534     		}
3535     
3536     		if (tp->sack_ok && sysctl_tcp_fack)
3537     			tp->sack_ok |= 2;
3538     
3539     		tcp_sync_mss(sk, tp->pmtu_cookie);
3540     		tcp_initialize_rcv_mss(sk);
3541     		tcp_init_metrics(sk);
3542     		tcp_init_buffer_space(sk);
3543     
3544     		if (sk->keepopen)
3545     			tcp_reset_keepalive_timer(sk, keepalive_time_when(tp));
3546     
3547     		if (tp->snd_wscale == 0)
3548     			__tcp_fast_path_on(tp, tp->snd_wnd);
3549     		else
3550     			tp->pred_flags = 0;
3551     
3552     		/* Remember, tcp_poll() does not lock socket!
3553     		 * Change state from SYN-SENT only after copied_seq
3554     		 * is initialized. */
3555     		tp->copied_seq = tp->rcv_nxt;
3556     		mb();
3557     		tcp_set_state(sk, TCP_ESTABLISHED);
3558     
3559     		if(!sk->dead) {
3560     			sk->state_change(sk);
3561     			sk_wake_async(sk, 0, POLL_OUT);
3562     		}
3563     
3564     		if (tp->write_pending || tp->defer_accept || tp->ack.pingpong) {
3565     			/* Save one ACK. Data will be ready after
3566     			 * several ticks, if write_pending is set.
3567     			 *
3568     			 * It may be deleted, but with this feature tcpdumps
3569     			 * look so _wonderfully_ clever, that I was not able
3570     			 * to stand against the temptation 8)     --ANK
3571     			 */
3572     			tcp_schedule_ack(tp);
3573     			tp->ack.lrcvtime = tcp_time_stamp;
3574     			tp->ack.ato = TCP_ATO_MIN;
3575     			tcp_incr_quickack(tp);
3576     			tcp_enter_quickack_mode(tp);
3577     			tcp_reset_xmit_timer(sk, TCP_TIME_DACK, TCP_DELACK_MAX);
3578     
3579     discard:
3580     			__kfree_skb(skb);
3581     			return 0;
3582     		} else {
3583     			tcp_send_ack(sk);
3584     		}
3585     		return -1;
3586     	}
3587     
3588     	/* No ACK in the segment */
3589     
3590     	if (th->rst) {
3591     		/* rfc793:
3592     		 * "If the RST bit is set
3593     		 *
3594     		 *      Otherwise (no ACK) drop the segment and return."
3595     		 */
3596     
3597     		goto discard_and_undo;
3598     	}
3599     
3600     	/* PAWS check. */
3601     	if (tp->ts_recent_stamp && tp->saw_tstamp && tcp_paws_check(tp, 0))
3602     		goto discard_and_undo;
3603     
3604     	if (th->syn) {
3605     		/* We see SYN without ACK. It is attempt of
3606     		 * simultaneous connect with crossed SYNs.
3607     		 * Particularly, it can be connect to self.
3608     		 */
3609     		tcp_set_state(sk, TCP_SYN_RECV);
3610     
3611     		if (tp->saw_tstamp) {
3612     			tp->tstamp_ok = 1;
3613     			tcp_store_ts_recent(tp);
3614     			tp->tcp_header_len =
3615     				sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
3616     		} else {
3617     			tp->tcp_header_len = sizeof(struct tcphdr);
3618     		}
3619     
3620     		tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1;
3621     		tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
3622     
3623     		/* RFC1323: The window in SYN & SYN/ACK segments is
3624     		 * never scaled.
3625     		 */
3626     		tp->snd_wnd = ntohs(th->window);
3627     		tp->snd_wl1 = TCP_SKB_CB(skb)->seq;
3628     		tp->max_window = tp->snd_wnd;
3629     
3630     		tcp_sync_mss(sk, tp->pmtu_cookie);
3631     		tcp_initialize_rcv_mss(sk);
3632     
3633     		TCP_ECN_rcv_syn(tp, th);
3634     
3635     		tcp_send_synack(sk);
3636     #if 0
3637     		/* Note, we could accept data and URG from this segment.
3638     		 * There are no obstacles to make this.
3639     		 *
3640     		 * However, if we ignore data in ACKless segments sometimes,
3641     		 * we have no reasons to accept it sometimes.
3642     		 * Also, seems the code doing it in step6 of tcp_rcv_state_process
3643     		 * is not flawless. So, discard packet for sanity.
3644     		 * Uncomment this return to process the data.
3645     		 */
3646     		return -1;
3647     #else
3648     		goto discard;
3649     #endif
3650     	}
3651     	/* "fifth, if neither of the SYN or RST bits is set then
3652     	 * drop the segment and return."
3653     	 */
3654     
3655     discard_and_undo:
3656     	tcp_clear_options(tp);
3657     	tp->mss_clamp = saved_clamp;
3658     	goto discard;
3659     
3660     reset_and_undo:
3661     	tcp_clear_options(tp);
3662     	tp->mss_clamp = saved_clamp;
3663     	return 1;
3664     }
3665     
3666     
3667     /*
3668      *	This function implements the receiving procedure of RFC 793 for
3669      *	all states except ESTABLISHED and TIME_WAIT. 
3670      *	It's called from both tcp_v4_rcv and tcp_v6_rcv and should be
3671      *	address independent.
3672      */
3673     	
3674     int tcp_rcv_state_process(struct sock *sk, struct sk_buff *skb,
3675     			  struct tcphdr *th, unsigned len)
3676     {
3677     	struct tcp_opt *tp = &(sk->tp_pinfo.af_tcp);
3678     	int queued = 0;
3679     
3680     	tp->saw_tstamp = 0;
3681     
3682     	switch (sk->state) {
3683     	case TCP_CLOSE:
3684     		goto discard;
3685     
3686     	case TCP_LISTEN:
3687     		if(th->ack)
3688     			return 1;
3689     
3690     		if(th->syn) {
3691     			if(tp->af_specific->conn_request(sk, skb) < 0)
3692     				return 1;
3693     
3694     			/* Now we have several options: In theory there is 
3695     			 * nothing else in the frame. KA9Q has an option to 
3696     			 * send data with the syn, BSD accepts data with the
3697     			 * syn up to the [to be] advertised window and 
3698     			 * Solaris 2.1 gives you a protocol error. For now 
3699     			 * we just ignore it, that fits the spec precisely 
3700     			 * and avoids incompatibilities. It would be nice in
3701     			 * future to drop through and process the data.
3702     			 *
3703     			 * Now that TTCP is starting to be used we ought to 
3704     			 * queue this data.
3705     			 * But, this leaves one open to an easy denial of
3706     		 	 * service attack, and SYN cookies can't defend
3707     			 * against this problem. So, we drop the data
3708     			 * in the interest of security over speed.
3709     			 */
3710     			goto discard;
3711     		}
3712     		goto discard;
3713     
3714     	case TCP_SYN_SENT:
3715     		queued = tcp_rcv_synsent_state_process(sk, skb, th, len);
3716     		if (queued >= 0)
3717     			return queued;
3718     
3719     		/* Do step6 onward by hand. */
3720     		tcp_urg(sk, skb, th);
3721     		__kfree_skb(skb);
3722     		tcp_data_snd_check(sk);
3723     		return 0;
3724     	}
3725     
3726     	if (tcp_fast_parse_options(skb, th, tp) && tp->saw_tstamp &&
3727     	    tcp_paws_discard(tp, skb)) {
3728     		if (!th->rst) {
3729     			NET_INC_STATS_BH(PAWSEstabRejected);
3730     			tcp_send_dupack(sk, skb);
3731     			goto discard;
3732     		}
3733     		/* Reset is accepted even if it did not pass PAWS. */
3734     	}
3735     
3736     	/* step 1: check sequence number */
3737     	if (!tcp_sequence(tp, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq)) {
3738     		if (!th->rst)
3739     			tcp_send_dupack(sk, skb);
3740     		goto discard;
3741     	}
3742     
3743     	/* step 2: check RST bit */
3744     	if(th->rst) {
3745     		tcp_reset(sk);
3746     		goto discard;
3747     	}
3748     
3749     	tcp_replace_ts_recent(tp, TCP_SKB_CB(skb)->seq);
3750     
3751     	/* step 3: check security and precedence [ignored] */
3752     
3753     	/*	step 4:
3754     	 *
3755     	 *	Check for a SYN in window.
3756     	 */
3757     	if (th->syn && !before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
3758     		NET_INC_STATS_BH(TCPAbortOnSyn);
3759     		tcp_reset(sk);
3760     		return 1;
3761     	}
3762     
3763     	/* step 5: check the ACK field */
3764     	if (th->ack) {
3765     		int acceptable = tcp_ack(sk, skb, FLAG_SLOWPATH);
3766     
3767     		switch(sk->state) {
3768     		case TCP_SYN_RECV:
3769     			if (acceptable) {
3770     				tp->copied_seq = tp->rcv_nxt;
3771     				mb();
3772     				tcp_set_state(sk, TCP_ESTABLISHED);
3773     				sk->state_change(sk);
3774     
3775     				/* Note, that this wakeup is only for marginal
3776     				 * crossed SYN case. Passively open sockets
3777     				 * are not waked up, because sk->sleep == NULL
3778     				 * and sk->socket == NULL.
3779     				 */
3780     				if (sk->socket) {
3781     					sk_wake_async(sk,0,POLL_OUT);
3782     				}
3783     
3784     				tp->snd_una = TCP_SKB_CB(skb)->ack_seq;
3785     				tp->snd_wnd = ntohs(th->window) << tp->snd_wscale;
3786     				tcp_init_wl(tp, TCP_SKB_CB(skb)->ack_seq, TCP_SKB_CB(skb)->seq);
3787     
3788     				/* tcp_ack considers this ACK as duplicate
3789     				 * and does not calculate rtt.
3790     				 * Fix it at least with timestamps.
3791     				 */
3792     				if (tp->saw_tstamp && tp->rcv_tsecr && !tp->srtt)
3793     					tcp_ack_saw_tstamp(tp, 0);
3794     
3795     				if (tp->tstamp_ok)
3796     					tp->advmss -= TCPOLEN_TSTAMP_ALIGNED;
3797     
3798     				tcp_init_metrics(sk);
3799     				tcp_initialize_rcv_mss(sk);
3800     				tcp_init_buffer_space(sk);
3801     				tcp_fast_path_on(tp);
3802     			} else {
3803     				return 1;
3804     			}
3805     			break;
3806     
3807     		case TCP_FIN_WAIT1:
3808     			if (tp->snd_una == tp->write_seq) {
3809     				tcp_set_state(sk, TCP_FIN_WAIT2);
3810     				sk->shutdown |= SEND_SHUTDOWN;
3811     				dst_confirm(sk->dst_cache);
3812     
3813     				if (!sk->dead) {
3814     					/* Wake up lingering close() */
3815     					sk->state_change(sk);
3816     				} else {
3817     					int tmo;
3818     
3819     					if (tp->linger2 < 0 ||
3820     					    (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
3821     					     after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt))) {
3822     						tcp_done(sk);
3823     						NET_INC_STATS_BH(TCPAbortOnData);
3824     						return 1;
3825     					}
3826     
3827     					tmo = tcp_fin_time(tp);
3828     					if (tmo > TCP_TIMEWAIT_LEN) {
3829     						tcp_reset_keepalive_timer(sk, tmo - TCP_TIMEWAIT_LEN);
3830     					} else if (th->fin || sk->lock.users) {
3831     						/* Bad case. We could lose such FIN otherwise.
3832     						 * It is not a big problem, but it looks confusing
3833     						 * and not so rare event. We still can lose it now,
3834     						 * if it spins in bh_lock_sock(), but it is really
3835     						 * marginal case.
3836     						 */
3837     						tcp_reset_keepalive_timer(sk, tmo);
3838     					} else {
3839     						tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
3840     						goto discard;
3841     					}
3842     				}
3843     			}
3844     			break;
3845     
3846     		case TCP_CLOSING:
3847     			if (tp->snd_una == tp->write_seq) {
3848     				tcp_time_wait(sk, TCP_TIME_WAIT, 0);
3849     				goto discard;
3850     			}
3851     			break;
3852     
3853     		case TCP_LAST_ACK:
3854     			if (tp->snd_una == tp->write_seq) {
3855     				tcp_update_metrics(sk);
3856     				tcp_done(sk);
3857     				goto discard;
3858     			}
3859     			break;
3860     		}
3861     	} else
3862     		goto discard;
3863     
3864     	/* step 6: check the URG bit */
3865     	tcp_urg(sk, skb, th);
3866     
3867     	/* step 7: process the segment text */
3868     	switch (sk->state) {
3869     	case TCP_CLOSE_WAIT:
3870     	case TCP_CLOSING:
3871     		if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt))
3872     			break;
3873     	case TCP_FIN_WAIT1:
3874     	case TCP_FIN_WAIT2:
3875     		/* RFC 793 says to queue data in these states,
3876     		 * RFC 1122 says we MUST send a reset. 
3877     		 * BSD 4.4 also does reset.
3878     		 */
3879     		if (sk->shutdown & RCV_SHUTDOWN) {
3880     			if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
3881     			    after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt)) {
3882     				NET_INC_STATS_BH(TCPAbortOnData);
3883     				tcp_reset(sk);
3884     				return 1;
3885     			}
3886     		}
3887     		/* Fall through */
3888     	case TCP_ESTABLISHED: 
3889     		tcp_data_queue(sk, skb);
3890     		queued = 1;
3891     		break;
3892     	}
3893     
3894     	/* tcp_data could move socket to TIME-WAIT */
3895     	if (sk->state != TCP_CLOSE) {
3896     		tcp_data_snd_check(sk);
3897     		tcp_ack_snd_check(sk);
3898     	}
3899     
3900     	if (!queued) { 
3901     discard:
3902     		__kfree_skb(skb);
3903     	}
3904     	return 0;
3905     }
3906