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