• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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  * Authors:	Ross Biro
9  *		Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
10  *		Mark Evans, <evansmp@uhura.aston.ac.uk>
11  *		Corey Minyard <wf-rch!minyard@relay.EU.net>
12  *		Florian La Roche, <flla@stud.uni-sb.de>
13  *		Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
14  *		Linus Torvalds, <torvalds@cs.helsinki.fi>
15  *		Alan Cox, <gw4pts@gw4pts.ampr.org>
16  *		Matthew Dillon, <dillon@apollo.west.oic.com>
17  *		Arnt Gulbrandsen, <agulbra@nvg.unit.no>
18  *		Jorge Cwik, <jorge@laser.satlink.net>
19  */
20 
21 /*
22  * Changes:
23  *		Pedro Roque	:	Fast Retransmit/Recovery.
24  *					Two receive queues.
25  *					Retransmit queue handled by TCP.
26  *					Better retransmit timer handling.
27  *					New congestion avoidance.
28  *					Header prediction.
29  *					Variable renaming.
30  *
31  *		Eric		:	Fast Retransmit.
32  *		Randy Scott	:	MSS option defines.
33  *		Eric Schenk	:	Fixes to slow start algorithm.
34  *		Eric Schenk	:	Yet another double ACK bug.
35  *		Eric Schenk	:	Delayed ACK bug fixes.
36  *		Eric Schenk	:	Floyd style fast retrans war avoidance.
37  *		David S. Miller	:	Don't allow zero congestion window.
38  *		Eric Schenk	:	Fix retransmitter so that it sends
39  *					next packet on ack of previous packet.
40  *		Andi Kleen	:	Moved open_request checking here
41  *					and process RSTs for open_requests.
42  *		Andi Kleen	:	Better prune_queue, and other fixes.
43  *		Andrey Savochkin:	Fix RTT measurements in the presence of
44  *					timestamps.
45  *		Andrey Savochkin:	Check sequence numbers correctly when
46  *					removing SACKs due to in sequence incoming
47  *					data segments.
48  *		Andi Kleen:		Make sure we never ack data there is not
49  *					enough room for. Also make this condition
50  *					a fatal error if it might still happen.
51  *		Andi Kleen:		Add tcp_measure_rcv_mss to make
52  *					connections with MSS<min(MTU,ann. MSS)
53  *					work without delayed acks.
54  *		Andi Kleen:		Process packets with PSH set in the
55  *					fast path.
56  *		J Hadi Salim:		ECN support
57  *	 	Andrei Gurtov,
58  *		Pasi Sarolahti,
59  *		Panu Kuhlberg:		Experimental audit of TCP (re)transmission
60  *					engine. Lots of bugs are found.
61  *		Pasi Sarolahti:		F-RTO for dealing with spurious RTOs
62  */
63 
64 #define pr_fmt(fmt) "TCP: " fmt
65 
66 #include <linux/mm.h>
67 #include <linux/slab.h>
68 #include <linux/module.h>
69 #include <linux/sysctl.h>
70 #include <linux/kernel.h>
71 #include <linux/prefetch.h>
72 #include <net/dst.h>
73 #include <net/tcp.h>
74 #include <net/inet_common.h>
75 #include <linux/ipsec.h>
76 #include <asm/unaligned.h>
77 #include <linux/errqueue.h>
78 
79 int sysctl_tcp_timestamps __read_mostly = 1;
80 int sysctl_tcp_window_scaling __read_mostly = 1;
81 int sysctl_tcp_sack __read_mostly = 1;
82 int sysctl_tcp_fack __read_mostly = 1;
83 int sysctl_tcp_reordering __read_mostly = TCP_FASTRETRANS_THRESH;
84 int sysctl_tcp_max_reordering __read_mostly = 300;
85 EXPORT_SYMBOL(sysctl_tcp_reordering);
86 int sysctl_tcp_dsack __read_mostly = 1;
87 int sysctl_tcp_app_win __read_mostly = 31;
88 int sysctl_tcp_adv_win_scale __read_mostly = 1;
89 EXPORT_SYMBOL(sysctl_tcp_adv_win_scale);
90 
91 /* rfc5961 challenge ack rate limiting */
92 int sysctl_tcp_challenge_ack_limit = 1000;
93 
94 int sysctl_tcp_stdurg __read_mostly;
95 int sysctl_tcp_rfc1337 __read_mostly;
96 int sysctl_tcp_max_orphans __read_mostly = NR_FILE;
97 int sysctl_tcp_frto __read_mostly = 2;
98 int sysctl_tcp_min_rtt_wlen __read_mostly = 300;
99 
100 int sysctl_tcp_thin_dupack __read_mostly;
101 
102 int sysctl_tcp_moderate_rcvbuf __read_mostly = 1;
103 int sysctl_tcp_early_retrans __read_mostly = 3;
104 int sysctl_tcp_invalid_ratelimit __read_mostly = HZ/2;
105 int sysctl_tcp_default_init_rwnd __read_mostly = TCP_INIT_CWND * 2;
106 
107 #define FLAG_DATA		0x01 /* Incoming frame contained data.		*/
108 #define FLAG_WIN_UPDATE		0x02 /* Incoming ACK was a window update.	*/
109 #define FLAG_DATA_ACKED		0x04 /* This ACK acknowledged new data.		*/
110 #define FLAG_RETRANS_DATA_ACKED	0x08 /* "" "" some of which was retransmitted.	*/
111 #define FLAG_SYN_ACKED		0x10 /* This ACK acknowledged SYN.		*/
112 #define FLAG_DATA_SACKED	0x20 /* New SACK.				*/
113 #define FLAG_ECE		0x40 /* ECE in this ACK				*/
114 #define FLAG_LOST_RETRANS	0x80 /* This ACK marks some retransmission lost */
115 #define FLAG_SLOWPATH		0x100 /* Do not skip RFC checks for window update.*/
116 #define FLAG_ORIG_SACK_ACKED	0x200 /* Never retransmitted data are (s)acked	*/
117 #define FLAG_SND_UNA_ADVANCED	0x400 /* Snd_una was changed (!= FLAG_DATA_ACKED) */
118 #define FLAG_DSACKING_ACK	0x800 /* SACK blocks contained D-SACK info */
119 #define FLAG_SACK_RENEGING	0x2000 /* snd_una advanced to a sacked seq */
120 #define FLAG_UPDATE_TS_RECENT	0x4000 /* tcp_replace_ts_recent() */
121 #define FLAG_NO_CHALLENGE_ACK	0x8000 /* do not call tcp_send_challenge_ack()	*/
122 
123 #define FLAG_ACKED		(FLAG_DATA_ACKED|FLAG_SYN_ACKED)
124 #define FLAG_NOT_DUP		(FLAG_DATA|FLAG_WIN_UPDATE|FLAG_ACKED)
125 #define FLAG_CA_ALERT		(FLAG_DATA_SACKED|FLAG_ECE)
126 #define FLAG_FORWARD_PROGRESS	(FLAG_ACKED|FLAG_DATA_SACKED)
127 
128 #define TCP_REMNANT (TCP_FLAG_FIN|TCP_FLAG_URG|TCP_FLAG_SYN|TCP_FLAG_PSH)
129 #define TCP_HP_BITS (~(TCP_RESERVED_BITS|TCP_FLAG_PSH))
130 
131 /* Adapt the MSS value used to make delayed ack decision to the
132  * real world.
133  */
tcp_measure_rcv_mss(struct sock * sk,const struct sk_buff * skb)134 static void tcp_measure_rcv_mss(struct sock *sk, const struct sk_buff *skb)
135 {
136 	struct inet_connection_sock *icsk = inet_csk(sk);
137 	const unsigned int lss = icsk->icsk_ack.last_seg_size;
138 	unsigned int len;
139 
140 	icsk->icsk_ack.last_seg_size = 0;
141 
142 	/* skb->len may jitter because of SACKs, even if peer
143 	 * sends good full-sized frames.
144 	 */
145 	len = skb_shinfo(skb)->gso_size ? : skb->len;
146 	if (len >= icsk->icsk_ack.rcv_mss) {
147 		icsk->icsk_ack.rcv_mss = len;
148 	} else {
149 		/* Otherwise, we make more careful check taking into account,
150 		 * that SACKs block is variable.
151 		 *
152 		 * "len" is invariant segment length, including TCP header.
153 		 */
154 		len += skb->data - skb_transport_header(skb);
155 		if (len >= TCP_MSS_DEFAULT + sizeof(struct tcphdr) ||
156 		    /* If PSH is not set, packet should be
157 		     * full sized, provided peer TCP is not badly broken.
158 		     * This observation (if it is correct 8)) allows
159 		     * to handle super-low mtu links fairly.
160 		     */
161 		    (len >= TCP_MIN_MSS + sizeof(struct tcphdr) &&
162 		     !(tcp_flag_word(tcp_hdr(skb)) & TCP_REMNANT))) {
163 			/* Subtract also invariant (if peer is RFC compliant),
164 			 * tcp header plus fixed timestamp option length.
165 			 * Resulting "len" is MSS free of SACK jitter.
166 			 */
167 			len -= tcp_sk(sk)->tcp_header_len;
168 			icsk->icsk_ack.last_seg_size = len;
169 			if (len == lss) {
170 				icsk->icsk_ack.rcv_mss = len;
171 				return;
172 			}
173 		}
174 		if (icsk->icsk_ack.pending & ICSK_ACK_PUSHED)
175 			icsk->icsk_ack.pending |= ICSK_ACK_PUSHED2;
176 		icsk->icsk_ack.pending |= ICSK_ACK_PUSHED;
177 	}
178 }
179 
tcp_incr_quickack(struct sock * sk,unsigned int max_quickacks)180 static void tcp_incr_quickack(struct sock *sk, unsigned int max_quickacks)
181 {
182 	struct inet_connection_sock *icsk = inet_csk(sk);
183 	unsigned int quickacks = tcp_sk(sk)->rcv_wnd / (2 * icsk->icsk_ack.rcv_mss);
184 
185 	if (quickacks == 0)
186 		quickacks = 2;
187 	quickacks = min(quickacks, max_quickacks);
188 	if (quickacks > icsk->icsk_ack.quick)
189 		icsk->icsk_ack.quick = quickacks;
190 }
191 
tcp_enter_quickack_mode(struct sock * sk,unsigned int max_quickacks)192 void tcp_enter_quickack_mode(struct sock *sk, unsigned int max_quickacks)
193 {
194 	struct inet_connection_sock *icsk = inet_csk(sk);
195 
196 	tcp_incr_quickack(sk, max_quickacks);
197 	icsk->icsk_ack.pingpong = 0;
198 	icsk->icsk_ack.ato = TCP_ATO_MIN;
199 }
200 EXPORT_SYMBOL(tcp_enter_quickack_mode);
201 
202 /* Send ACKs quickly, if "quick" count is not exhausted
203  * and the session is not interactive.
204  */
205 
tcp_in_quickack_mode(struct sock * sk)206 static bool tcp_in_quickack_mode(struct sock *sk)
207 {
208 	const struct inet_connection_sock *icsk = inet_csk(sk);
209 	const struct dst_entry *dst = __sk_dst_get(sk);
210 
211 	return (dst && dst_metric(dst, RTAX_QUICKACK)) ||
212 		(icsk->icsk_ack.quick && !icsk->icsk_ack.pingpong);
213 }
214 
tcp_ecn_queue_cwr(struct tcp_sock * tp)215 static void tcp_ecn_queue_cwr(struct tcp_sock *tp)
216 {
217 	if (tp->ecn_flags & TCP_ECN_OK)
218 		tp->ecn_flags |= TCP_ECN_QUEUE_CWR;
219 }
220 
tcp_ecn_accept_cwr(struct tcp_sock * tp,const struct sk_buff * skb)221 static void tcp_ecn_accept_cwr(struct tcp_sock *tp, const struct sk_buff *skb)
222 {
223 	if (tcp_hdr(skb)->cwr)
224 		tp->ecn_flags &= ~TCP_ECN_DEMAND_CWR;
225 }
226 
tcp_ecn_withdraw_cwr(struct tcp_sock * tp)227 static void tcp_ecn_withdraw_cwr(struct tcp_sock *tp)
228 {
229 	tp->ecn_flags &= ~TCP_ECN_QUEUE_CWR;
230 }
231 
__tcp_ecn_check_ce(struct sock * sk,const struct sk_buff * skb)232 static void __tcp_ecn_check_ce(struct sock *sk, const struct sk_buff *skb)
233 {
234 	struct tcp_sock *tp = tcp_sk(sk);
235 
236 	switch (TCP_SKB_CB(skb)->ip_dsfield & INET_ECN_MASK) {
237 	case INET_ECN_NOT_ECT:
238 		/* Funny extension: if ECT is not set on a segment,
239 		 * and we already seen ECT on a previous segment,
240 		 * it is probably a retransmit.
241 		 */
242 		if (tp->ecn_flags & TCP_ECN_SEEN)
243 			tcp_enter_quickack_mode(sk, 2);
244 		break;
245 	case INET_ECN_CE:
246 		if (tcp_ca_needs_ecn(sk))
247 			tcp_ca_event(sk, CA_EVENT_ECN_IS_CE);
248 
249 		if (!(tp->ecn_flags & TCP_ECN_DEMAND_CWR)) {
250 			/* Better not delay acks, sender can have a very low cwnd */
251 			tcp_enter_quickack_mode(sk, 2);
252 			tp->ecn_flags |= TCP_ECN_DEMAND_CWR;
253 		}
254 		tp->ecn_flags |= TCP_ECN_SEEN;
255 		break;
256 	default:
257 		if (tcp_ca_needs_ecn(sk))
258 			tcp_ca_event(sk, CA_EVENT_ECN_NO_CE);
259 		tp->ecn_flags |= TCP_ECN_SEEN;
260 		break;
261 	}
262 }
263 
tcp_ecn_check_ce(struct sock * sk,const struct sk_buff * skb)264 static void tcp_ecn_check_ce(struct sock *sk, const struct sk_buff *skb)
265 {
266 	if (tcp_sk(sk)->ecn_flags & TCP_ECN_OK)
267 		__tcp_ecn_check_ce(sk, skb);
268 }
269 
tcp_ecn_rcv_synack(struct tcp_sock * tp,const struct tcphdr * th)270 static void tcp_ecn_rcv_synack(struct tcp_sock *tp, const struct tcphdr *th)
271 {
272 	if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || th->cwr))
273 		tp->ecn_flags &= ~TCP_ECN_OK;
274 }
275 
tcp_ecn_rcv_syn(struct tcp_sock * tp,const struct tcphdr * th)276 static void tcp_ecn_rcv_syn(struct tcp_sock *tp, const struct tcphdr *th)
277 {
278 	if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || !th->cwr))
279 		tp->ecn_flags &= ~TCP_ECN_OK;
280 }
281 
tcp_ecn_rcv_ecn_echo(const struct tcp_sock * tp,const struct tcphdr * th)282 static bool tcp_ecn_rcv_ecn_echo(const struct tcp_sock *tp, const struct tcphdr *th)
283 {
284 	if (th->ece && !th->syn && (tp->ecn_flags & TCP_ECN_OK))
285 		return true;
286 	return false;
287 }
288 
289 /* Buffer size and advertised window tuning.
290  *
291  * 1. Tuning sk->sk_sndbuf, when connection enters established state.
292  */
293 
tcp_sndbuf_expand(struct sock * sk)294 static void tcp_sndbuf_expand(struct sock *sk)
295 {
296 	const struct tcp_sock *tp = tcp_sk(sk);
297 	int sndmem, per_mss;
298 	u32 nr_segs;
299 
300 	/* Worst case is non GSO/TSO : each frame consumes one skb
301 	 * and skb->head is kmalloced using power of two area of memory
302 	 */
303 	per_mss = max_t(u32, tp->rx_opt.mss_clamp, tp->mss_cache) +
304 		  MAX_TCP_HEADER +
305 		  SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
306 
307 	per_mss = roundup_pow_of_two(per_mss) +
308 		  SKB_DATA_ALIGN(sizeof(struct sk_buff));
309 
310 	nr_segs = max_t(u32, TCP_INIT_CWND, tp->snd_cwnd);
311 	nr_segs = max_t(u32, nr_segs, tp->reordering + 1);
312 
313 	/* Fast Recovery (RFC 5681 3.2) :
314 	 * Cubic needs 1.7 factor, rounded to 2 to include
315 	 * extra cushion (application might react slowly to POLLOUT)
316 	 */
317 	sndmem = 2 * nr_segs * per_mss;
318 
319 	if (sk->sk_sndbuf < sndmem)
320 		sk->sk_sndbuf = min(sndmem, sysctl_tcp_wmem[2]);
321 }
322 
323 /* 2. Tuning advertised window (window_clamp, rcv_ssthresh)
324  *
325  * All tcp_full_space() is split to two parts: "network" buffer, allocated
326  * forward and advertised in receiver window (tp->rcv_wnd) and
327  * "application buffer", required to isolate scheduling/application
328  * latencies from network.
329  * window_clamp is maximal advertised window. It can be less than
330  * tcp_full_space(), in this case tcp_full_space() - window_clamp
331  * is reserved for "application" buffer. The less window_clamp is
332  * the smoother our behaviour from viewpoint of network, but the lower
333  * throughput and the higher sensitivity of the connection to losses. 8)
334  *
335  * rcv_ssthresh is more strict window_clamp used at "slow start"
336  * phase to predict further behaviour of this connection.
337  * It is used for two goals:
338  * - to enforce header prediction at sender, even when application
339  *   requires some significant "application buffer". It is check #1.
340  * - to prevent pruning of receive queue because of misprediction
341  *   of receiver window. Check #2.
342  *
343  * The scheme does not work when sender sends good segments opening
344  * window and then starts to feed us spaghetti. But it should work
345  * in common situations. Otherwise, we have to rely on queue collapsing.
346  */
347 
348 /* Slow part of check#2. */
__tcp_grow_window(const struct sock * sk,const struct sk_buff * skb)349 static int __tcp_grow_window(const struct sock *sk, const struct sk_buff *skb)
350 {
351 	struct tcp_sock *tp = tcp_sk(sk);
352 	/* Optimize this! */
353 	int truesize = tcp_win_from_space(skb->truesize) >> 1;
354 	int window = tcp_win_from_space(sysctl_tcp_rmem[2]) >> 1;
355 
356 	while (tp->rcv_ssthresh <= window) {
357 		if (truesize <= skb->len)
358 			return 2 * inet_csk(sk)->icsk_ack.rcv_mss;
359 
360 		truesize >>= 1;
361 		window >>= 1;
362 	}
363 	return 0;
364 }
365 
tcp_grow_window(struct sock * sk,const struct sk_buff * skb)366 static void tcp_grow_window(struct sock *sk, const struct sk_buff *skb)
367 {
368 	struct tcp_sock *tp = tcp_sk(sk);
369 	int room;
370 
371 	room = min_t(int, tp->window_clamp, tcp_space(sk)) - tp->rcv_ssthresh;
372 
373 	/* Check #1 */
374 	if (room > 0 && !tcp_under_memory_pressure(sk)) {
375 		int incr;
376 
377 		/* Check #2. Increase window, if skb with such overhead
378 		 * will fit to rcvbuf in future.
379 		 */
380 		if (tcp_win_from_space(skb->truesize) <= skb->len)
381 			incr = 2 * tp->advmss;
382 		else
383 			incr = __tcp_grow_window(sk, skb);
384 
385 		if (incr) {
386 			incr = max_t(int, incr, 2 * skb->len);
387 			tp->rcv_ssthresh += min(room, incr);
388 			inet_csk(sk)->icsk_ack.quick |= 1;
389 		}
390 	}
391 }
392 
393 /* 3. Tuning rcvbuf, when connection enters established state. */
tcp_fixup_rcvbuf(struct sock * sk)394 static void tcp_fixup_rcvbuf(struct sock *sk)
395 {
396 	u32 mss = tcp_sk(sk)->advmss;
397 	int rcvmem;
398 
399 	rcvmem = 2 * SKB_TRUESIZE(mss + MAX_TCP_HEADER) *
400 		 tcp_default_init_rwnd(mss);
401 
402 	/* Dynamic Right Sizing (DRS) has 2 to 3 RTT latency
403 	 * Allow enough cushion so that sender is not limited by our window
404 	 */
405 	if (sysctl_tcp_moderate_rcvbuf)
406 		rcvmem <<= 2;
407 
408 	if (sk->sk_rcvbuf < rcvmem)
409 		sk->sk_rcvbuf = min(rcvmem, sysctl_tcp_rmem[2]);
410 }
411 
412 /* 4. Try to fixup all. It is made immediately after connection enters
413  *    established state.
414  */
tcp_init_buffer_space(struct sock * sk)415 void tcp_init_buffer_space(struct sock *sk)
416 {
417 	struct tcp_sock *tp = tcp_sk(sk);
418 	int maxwin;
419 
420 	if (!(sk->sk_userlocks & SOCK_RCVBUF_LOCK))
421 		tcp_fixup_rcvbuf(sk);
422 	if (!(sk->sk_userlocks & SOCK_SNDBUF_LOCK))
423 		tcp_sndbuf_expand(sk);
424 
425 	tp->rcvq_space.space = tp->rcv_wnd;
426 	tp->rcvq_space.time = tcp_time_stamp;
427 	tp->rcvq_space.seq = tp->copied_seq;
428 
429 	maxwin = tcp_full_space(sk);
430 
431 	if (tp->window_clamp >= maxwin) {
432 		tp->window_clamp = maxwin;
433 
434 		if (sysctl_tcp_app_win && maxwin > 4 * tp->advmss)
435 			tp->window_clamp = max(maxwin -
436 					       (maxwin >> sysctl_tcp_app_win),
437 					       4 * tp->advmss);
438 	}
439 
440 	/* Force reservation of one segment. */
441 	if (sysctl_tcp_app_win &&
442 	    tp->window_clamp > 2 * tp->advmss &&
443 	    tp->window_clamp + tp->advmss > maxwin)
444 		tp->window_clamp = max(2 * tp->advmss, maxwin - tp->advmss);
445 
446 	tp->rcv_ssthresh = min(tp->rcv_ssthresh, tp->window_clamp);
447 	tp->snd_cwnd_stamp = tcp_time_stamp;
448 }
449 
450 /* 5. Recalculate window clamp after socket hit its memory bounds. */
tcp_clamp_window(struct sock * sk)451 static void tcp_clamp_window(struct sock *sk)
452 {
453 	struct tcp_sock *tp = tcp_sk(sk);
454 	struct inet_connection_sock *icsk = inet_csk(sk);
455 
456 	icsk->icsk_ack.quick = 0;
457 
458 	if (sk->sk_rcvbuf < sysctl_tcp_rmem[2] &&
459 	    !(sk->sk_userlocks & SOCK_RCVBUF_LOCK) &&
460 	    !tcp_under_memory_pressure(sk) &&
461 	    sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0)) {
462 		sk->sk_rcvbuf = min(atomic_read(&sk->sk_rmem_alloc),
463 				    sysctl_tcp_rmem[2]);
464 	}
465 	if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf)
466 		tp->rcv_ssthresh = min(tp->window_clamp, 2U * tp->advmss);
467 }
468 
469 /* Initialize RCV_MSS value.
470  * RCV_MSS is an our guess about MSS used by the peer.
471  * We haven't any direct information about the MSS.
472  * It's better to underestimate the RCV_MSS rather than overestimate.
473  * Overestimations make us ACKing less frequently than needed.
474  * Underestimations are more easy to detect and fix by tcp_measure_rcv_mss().
475  */
tcp_initialize_rcv_mss(struct sock * sk)476 void tcp_initialize_rcv_mss(struct sock *sk)
477 {
478 	const struct tcp_sock *tp = tcp_sk(sk);
479 	unsigned int hint = min_t(unsigned int, tp->advmss, tp->mss_cache);
480 
481 	hint = min(hint, tp->rcv_wnd / 2);
482 	hint = min(hint, TCP_MSS_DEFAULT);
483 	hint = max(hint, TCP_MIN_MSS);
484 
485 	inet_csk(sk)->icsk_ack.rcv_mss = hint;
486 }
487 EXPORT_SYMBOL(tcp_initialize_rcv_mss);
488 
489 /* Receiver "autotuning" code.
490  *
491  * The algorithm for RTT estimation w/o timestamps is based on
492  * Dynamic Right-Sizing (DRS) by Wu Feng and Mike Fisk of LANL.
493  * <http://public.lanl.gov/radiant/pubs.html#DRS>
494  *
495  * More detail on this code can be found at
496  * <http://staff.psc.edu/jheffner/>,
497  * though this reference is out of date.  A new paper
498  * is pending.
499  */
tcp_rcv_rtt_update(struct tcp_sock * tp,u32 sample,int win_dep)500 static void tcp_rcv_rtt_update(struct tcp_sock *tp, u32 sample, int win_dep)
501 {
502 	u32 new_sample = tp->rcv_rtt_est.rtt;
503 	long m = sample;
504 
505 	if (m == 0)
506 		m = 1;
507 
508 	if (new_sample != 0) {
509 		/* If we sample in larger samples in the non-timestamp
510 		 * case, we could grossly overestimate the RTT especially
511 		 * with chatty applications or bulk transfer apps which
512 		 * are stalled on filesystem I/O.
513 		 *
514 		 * Also, since we are only going for a minimum in the
515 		 * non-timestamp case, we do not smooth things out
516 		 * else with timestamps disabled convergence takes too
517 		 * long.
518 		 */
519 		if (!win_dep) {
520 			m -= (new_sample >> 3);
521 			new_sample += m;
522 		} else {
523 			m <<= 3;
524 			if (m < new_sample)
525 				new_sample = m;
526 		}
527 	} else {
528 		/* No previous measure. */
529 		new_sample = m << 3;
530 	}
531 
532 	if (tp->rcv_rtt_est.rtt != new_sample)
533 		tp->rcv_rtt_est.rtt = new_sample;
534 }
535 
tcp_rcv_rtt_measure(struct tcp_sock * tp)536 static inline void tcp_rcv_rtt_measure(struct tcp_sock *tp)
537 {
538 	if (tp->rcv_rtt_est.time == 0)
539 		goto new_measure;
540 	if (before(tp->rcv_nxt, tp->rcv_rtt_est.seq))
541 		return;
542 	tcp_rcv_rtt_update(tp, tcp_time_stamp - tp->rcv_rtt_est.time, 1);
543 
544 new_measure:
545 	tp->rcv_rtt_est.seq = tp->rcv_nxt + tp->rcv_wnd;
546 	tp->rcv_rtt_est.time = tcp_time_stamp;
547 }
548 
tcp_rcv_rtt_measure_ts(struct sock * sk,const struct sk_buff * skb)549 static inline void tcp_rcv_rtt_measure_ts(struct sock *sk,
550 					  const struct sk_buff *skb)
551 {
552 	struct tcp_sock *tp = tcp_sk(sk);
553 	if (tp->rx_opt.rcv_tsecr &&
554 	    (TCP_SKB_CB(skb)->end_seq -
555 	     TCP_SKB_CB(skb)->seq >= inet_csk(sk)->icsk_ack.rcv_mss))
556 		tcp_rcv_rtt_update(tp, tcp_time_stamp - tp->rx_opt.rcv_tsecr, 0);
557 }
558 
559 /*
560  * This function should be called every time data is copied to user space.
561  * It calculates the appropriate TCP receive buffer space.
562  */
tcp_rcv_space_adjust(struct sock * sk)563 void tcp_rcv_space_adjust(struct sock *sk)
564 {
565 	struct tcp_sock *tp = tcp_sk(sk);
566 	u32 copied;
567 	int time;
568 
569 	time = tcp_time_stamp - tp->rcvq_space.time;
570 	if (time < (tp->rcv_rtt_est.rtt >> 3) || tp->rcv_rtt_est.rtt == 0)
571 		return;
572 
573 	/* Number of bytes copied to user in last RTT */
574 	copied = tp->copied_seq - tp->rcvq_space.seq;
575 	if (copied <= tp->rcvq_space.space)
576 		goto new_measure;
577 
578 	/* A bit of theory :
579 	 * copied = bytes received in previous RTT, our base window
580 	 * To cope with packet losses, we need a 2x factor
581 	 * To cope with slow start, and sender growing its cwin by 100 %
582 	 * every RTT, we need a 4x factor, because the ACK we are sending
583 	 * now is for the next RTT, not the current one :
584 	 * <prev RTT . ><current RTT .. ><next RTT .... >
585 	 */
586 
587 	if (sysctl_tcp_moderate_rcvbuf &&
588 	    !(sk->sk_userlocks & SOCK_RCVBUF_LOCK)) {
589 		int rcvmem, rcvbuf;
590 		u64 rcvwin;
591 
592 		/* minimal window to cope with packet losses, assuming
593 		 * steady state. Add some cushion because of small variations.
594 		 */
595 		rcvwin = ((u64)copied << 1) + 16 * tp->advmss;
596 
597 		/* If rate increased by 25%,
598 		 *	assume slow start, rcvwin = 3 * copied
599 		 * If rate increased by 50%,
600 		 *	assume sender can use 2x growth, rcvwin = 4 * copied
601 		 */
602 		if (copied >=
603 		    tp->rcvq_space.space + (tp->rcvq_space.space >> 2)) {
604 			if (copied >=
605 			    tp->rcvq_space.space + (tp->rcvq_space.space >> 1))
606 				rcvwin <<= 1;
607 			else
608 				rcvwin += (rcvwin >> 1);
609 		}
610 
611 		rcvmem = SKB_TRUESIZE(tp->advmss + MAX_TCP_HEADER);
612 		while (tcp_win_from_space(rcvmem) < tp->advmss)
613 			rcvmem += 128;
614 
615 		do_div(rcvwin, tp->advmss);
616 		rcvbuf = min_t(u64, rcvwin * rcvmem, sysctl_tcp_rmem[2]);
617 		if (rcvbuf > sk->sk_rcvbuf) {
618 			sk->sk_rcvbuf = rcvbuf;
619 
620 			/* Make the window clamp follow along.  */
621 			tp->window_clamp = tcp_win_from_space(rcvbuf);
622 		}
623 	}
624 	tp->rcvq_space.space = copied;
625 
626 new_measure:
627 	tp->rcvq_space.seq = tp->copied_seq;
628 	tp->rcvq_space.time = tcp_time_stamp;
629 }
630 
631 /* There is something which you must keep in mind when you analyze the
632  * behavior of the tp->ato delayed ack timeout interval.  When a
633  * connection starts up, we want to ack as quickly as possible.  The
634  * problem is that "good" TCP's do slow start at the beginning of data
635  * transmission.  The means that until we send the first few ACK's the
636  * sender will sit on his end and only queue most of his data, because
637  * he can only send snd_cwnd unacked packets at any given time.  For
638  * each ACK we send, he increments snd_cwnd and transmits more of his
639  * queue.  -DaveM
640  */
tcp_event_data_recv(struct sock * sk,struct sk_buff * skb)641 static void tcp_event_data_recv(struct sock *sk, struct sk_buff *skb)
642 {
643 	struct tcp_sock *tp = tcp_sk(sk);
644 	struct inet_connection_sock *icsk = inet_csk(sk);
645 	u32 now;
646 
647 	inet_csk_schedule_ack(sk);
648 
649 	tcp_measure_rcv_mss(sk, skb);
650 
651 	tcp_rcv_rtt_measure(tp);
652 
653 	now = tcp_time_stamp;
654 
655 	if (!icsk->icsk_ack.ato) {
656 		/* The _first_ data packet received, initialize
657 		 * delayed ACK engine.
658 		 */
659 		tcp_incr_quickack(sk, TCP_MAX_QUICKACKS);
660 		icsk->icsk_ack.ato = TCP_ATO_MIN;
661 	} else {
662 		int m = now - icsk->icsk_ack.lrcvtime;
663 
664 		if (m <= TCP_ATO_MIN / 2) {
665 			/* The fastest case is the first. */
666 			icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + TCP_ATO_MIN / 2;
667 		} else if (m < icsk->icsk_ack.ato) {
668 			icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + m;
669 			if (icsk->icsk_ack.ato > icsk->icsk_rto)
670 				icsk->icsk_ack.ato = icsk->icsk_rto;
671 		} else if (m > icsk->icsk_rto) {
672 			/* Too long gap. Apparently sender failed to
673 			 * restart window, so that we send ACKs quickly.
674 			 */
675 			tcp_incr_quickack(sk, TCP_MAX_QUICKACKS);
676 			sk_mem_reclaim(sk);
677 		}
678 	}
679 	icsk->icsk_ack.lrcvtime = now;
680 
681 	tcp_ecn_check_ce(sk, skb);
682 
683 	if (skb->len >= 128)
684 		tcp_grow_window(sk, skb);
685 }
686 
687 /* Called to compute a smoothed rtt estimate. The data fed to this
688  * routine either comes from timestamps, or from segments that were
689  * known _not_ to have been retransmitted [see Karn/Partridge
690  * Proceedings SIGCOMM 87]. The algorithm is from the SIGCOMM 88
691  * piece by Van Jacobson.
692  * NOTE: the next three routines used to be one big routine.
693  * To save cycles in the RFC 1323 implementation it was better to break
694  * it up into three procedures. -- erics
695  */
tcp_rtt_estimator(struct sock * sk,long mrtt_us)696 static void tcp_rtt_estimator(struct sock *sk, long mrtt_us)
697 {
698 	struct tcp_sock *tp = tcp_sk(sk);
699 	long m = mrtt_us; /* RTT */
700 	u32 srtt = tp->srtt_us;
701 
702 	/*	The following amusing code comes from Jacobson's
703 	 *	article in SIGCOMM '88.  Note that rtt and mdev
704 	 *	are scaled versions of rtt and mean deviation.
705 	 *	This is designed to be as fast as possible
706 	 *	m stands for "measurement".
707 	 *
708 	 *	On a 1990 paper the rto value is changed to:
709 	 *	RTO = rtt + 4 * mdev
710 	 *
711 	 * Funny. This algorithm seems to be very broken.
712 	 * These formulae increase RTO, when it should be decreased, increase
713 	 * too slowly, when it should be increased quickly, decrease too quickly
714 	 * etc. I guess in BSD RTO takes ONE value, so that it is absolutely
715 	 * does not matter how to _calculate_ it. Seems, it was trap
716 	 * that VJ failed to avoid. 8)
717 	 */
718 	if (srtt != 0) {
719 		m -= (srtt >> 3);	/* m is now error in rtt est */
720 		srtt += m;		/* rtt = 7/8 rtt + 1/8 new */
721 		if (m < 0) {
722 			m = -m;		/* m is now abs(error) */
723 			m -= (tp->mdev_us >> 2);   /* similar update on mdev */
724 			/* This is similar to one of Eifel findings.
725 			 * Eifel blocks mdev updates when rtt decreases.
726 			 * This solution is a bit different: we use finer gain
727 			 * for mdev in this case (alpha*beta).
728 			 * Like Eifel it also prevents growth of rto,
729 			 * but also it limits too fast rto decreases,
730 			 * happening in pure Eifel.
731 			 */
732 			if (m > 0)
733 				m >>= 3;
734 		} else {
735 			m -= (tp->mdev_us >> 2);   /* similar update on mdev */
736 		}
737 		tp->mdev_us += m;		/* mdev = 3/4 mdev + 1/4 new */
738 		if (tp->mdev_us > tp->mdev_max_us) {
739 			tp->mdev_max_us = tp->mdev_us;
740 			if (tp->mdev_max_us > tp->rttvar_us)
741 				tp->rttvar_us = tp->mdev_max_us;
742 		}
743 		if (after(tp->snd_una, tp->rtt_seq)) {
744 			if (tp->mdev_max_us < tp->rttvar_us)
745 				tp->rttvar_us -= (tp->rttvar_us - tp->mdev_max_us) >> 2;
746 			tp->rtt_seq = tp->snd_nxt;
747 			tp->mdev_max_us = tcp_rto_min_us(sk);
748 		}
749 	} else {
750 		/* no previous measure. */
751 		srtt = m << 3;		/* take the measured time to be rtt */
752 		tp->mdev_us = m << 1;	/* make sure rto = 3*rtt */
753 		tp->rttvar_us = max(tp->mdev_us, tcp_rto_min_us(sk));
754 		tp->mdev_max_us = tp->rttvar_us;
755 		tp->rtt_seq = tp->snd_nxt;
756 	}
757 	tp->srtt_us = max(1U, srtt);
758 }
759 
760 /* Set the sk_pacing_rate to allow proper sizing of TSO packets.
761  * Note: TCP stack does not yet implement pacing.
762  * FQ packet scheduler can be used to implement cheap but effective
763  * TCP pacing, to smooth the burst on large writes when packets
764  * in flight is significantly lower than cwnd (or rwin)
765  */
766 int sysctl_tcp_pacing_ss_ratio __read_mostly = 200;
767 int sysctl_tcp_pacing_ca_ratio __read_mostly = 120;
768 
tcp_update_pacing_rate(struct sock * sk)769 static void tcp_update_pacing_rate(struct sock *sk)
770 {
771 	const struct tcp_sock *tp = tcp_sk(sk);
772 	u64 rate;
773 
774 	/* set sk_pacing_rate to 200 % of current rate (mss * cwnd / srtt) */
775 	rate = (u64)tp->mss_cache * ((USEC_PER_SEC / 100) << 3);
776 
777 	/* current rate is (cwnd * mss) / srtt
778 	 * In Slow Start [1], set sk_pacing_rate to 200 % the current rate.
779 	 * In Congestion Avoidance phase, set it to 120 % the current rate.
780 	 *
781 	 * [1] : Normal Slow Start condition is (tp->snd_cwnd < tp->snd_ssthresh)
782 	 *	 If snd_cwnd >= (tp->snd_ssthresh / 2), we are approaching
783 	 *	 end of slow start and should slow down.
784 	 */
785 	if (tp->snd_cwnd < tp->snd_ssthresh / 2)
786 		rate *= sysctl_tcp_pacing_ss_ratio;
787 	else
788 		rate *= sysctl_tcp_pacing_ca_ratio;
789 
790 	rate *= max(tp->snd_cwnd, tp->packets_out);
791 
792 	if (likely(tp->srtt_us))
793 		do_div(rate, tp->srtt_us);
794 
795 	/* ACCESS_ONCE() is needed because sch_fq fetches sk_pacing_rate
796 	 * without any lock. We want to make sure compiler wont store
797 	 * intermediate values in this location.
798 	 */
799 	ACCESS_ONCE(sk->sk_pacing_rate) = min_t(u64, rate,
800 						sk->sk_max_pacing_rate);
801 }
802 
803 /* Calculate rto without backoff.  This is the second half of Van Jacobson's
804  * routine referred to above.
805  */
tcp_set_rto(struct sock * sk)806 static void tcp_set_rto(struct sock *sk)
807 {
808 	const struct tcp_sock *tp = tcp_sk(sk);
809 	/* Old crap is replaced with new one. 8)
810 	 *
811 	 * More seriously:
812 	 * 1. If rtt variance happened to be less 50msec, it is hallucination.
813 	 *    It cannot be less due to utterly erratic ACK generation made
814 	 *    at least by solaris and freebsd. "Erratic ACKs" has _nothing_
815 	 *    to do with delayed acks, because at cwnd>2 true delack timeout
816 	 *    is invisible. Actually, Linux-2.4 also generates erratic
817 	 *    ACKs in some circumstances.
818 	 */
819 	inet_csk(sk)->icsk_rto = __tcp_set_rto(tp);
820 
821 	/* 2. Fixups made earlier cannot be right.
822 	 *    If we do not estimate RTO correctly without them,
823 	 *    all the algo is pure shit and should be replaced
824 	 *    with correct one. It is exactly, which we pretend to do.
825 	 */
826 
827 	/* NOTE: clamping at TCP_RTO_MIN is not required, current algo
828 	 * guarantees that rto is higher.
829 	 */
830 	tcp_bound_rto(sk);
831 }
832 
tcp_init_cwnd(const struct tcp_sock * tp,const struct dst_entry * dst)833 __u32 tcp_init_cwnd(const struct tcp_sock *tp, const struct dst_entry *dst)
834 {
835 	__u32 cwnd = (dst ? dst_metric(dst, RTAX_INITCWND) : 0);
836 
837 	if (!cwnd)
838 		cwnd = TCP_INIT_CWND;
839 	return min_t(__u32, cwnd, tp->snd_cwnd_clamp);
840 }
841 
842 /*
843  * Packet counting of FACK is based on in-order assumptions, therefore TCP
844  * disables it when reordering is detected
845  */
tcp_disable_fack(struct tcp_sock * tp)846 void tcp_disable_fack(struct tcp_sock *tp)
847 {
848 	/* RFC3517 uses different metric in lost marker => reset on change */
849 	if (tcp_is_fack(tp))
850 		tp->lost_skb_hint = NULL;
851 	tp->rx_opt.sack_ok &= ~TCP_FACK_ENABLED;
852 }
853 
854 /* Take a notice that peer is sending D-SACKs */
tcp_dsack_seen(struct tcp_sock * tp)855 static void tcp_dsack_seen(struct tcp_sock *tp)
856 {
857 	tp->rx_opt.sack_ok |= TCP_DSACK_SEEN;
858 }
859 
tcp_update_reordering(struct sock * sk,const int metric,const int ts)860 static void tcp_update_reordering(struct sock *sk, const int metric,
861 				  const int ts)
862 {
863 	struct tcp_sock *tp = tcp_sk(sk);
864 	if (metric > tp->reordering) {
865 		int mib_idx;
866 
867 		tp->reordering = min(sysctl_tcp_max_reordering, metric);
868 
869 		/* This exciting event is worth to be remembered. 8) */
870 		if (ts)
871 			mib_idx = LINUX_MIB_TCPTSREORDER;
872 		else if (tcp_is_reno(tp))
873 			mib_idx = LINUX_MIB_TCPRENOREORDER;
874 		else if (tcp_is_fack(tp))
875 			mib_idx = LINUX_MIB_TCPFACKREORDER;
876 		else
877 			mib_idx = LINUX_MIB_TCPSACKREORDER;
878 
879 		NET_INC_STATS_BH(sock_net(sk), mib_idx);
880 #if FASTRETRANS_DEBUG > 1
881 		pr_debug("Disorder%d %d %u f%u s%u rr%d\n",
882 			 tp->rx_opt.sack_ok, inet_csk(sk)->icsk_ca_state,
883 			 tp->reordering,
884 			 tp->fackets_out,
885 			 tp->sacked_out,
886 			 tp->undo_marker ? tp->undo_retrans : 0);
887 #endif
888 		tcp_disable_fack(tp);
889 	}
890 
891 	if (metric > 0)
892 		tcp_disable_early_retrans(tp);
893 	tp->rack.reord = 1;
894 }
895 
896 /* This must be called before lost_out is incremented */
tcp_verify_retransmit_hint(struct tcp_sock * tp,struct sk_buff * skb)897 static void tcp_verify_retransmit_hint(struct tcp_sock *tp, struct sk_buff *skb)
898 {
899 	if ((!tp->retransmit_skb_hint && tp->retrans_out >= tp->lost_out) ||
900 	    (tp->retransmit_skb_hint &&
901 	     before(TCP_SKB_CB(skb)->seq,
902 		    TCP_SKB_CB(tp->retransmit_skb_hint)->seq)))
903 		tp->retransmit_skb_hint = skb;
904 
905 	if (!tp->lost_out ||
906 	    after(TCP_SKB_CB(skb)->end_seq, tp->retransmit_high))
907 		tp->retransmit_high = TCP_SKB_CB(skb)->end_seq;
908 }
909 
tcp_skb_mark_lost(struct tcp_sock * tp,struct sk_buff * skb)910 static void tcp_skb_mark_lost(struct tcp_sock *tp, struct sk_buff *skb)
911 {
912 	if (!(TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_ACKED))) {
913 		tcp_verify_retransmit_hint(tp, skb);
914 
915 		tp->lost_out += tcp_skb_pcount(skb);
916 		TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
917 	}
918 }
919 
tcp_skb_mark_lost_uncond_verify(struct tcp_sock * tp,struct sk_buff * skb)920 void tcp_skb_mark_lost_uncond_verify(struct tcp_sock *tp, struct sk_buff *skb)
921 {
922 	tcp_verify_retransmit_hint(tp, skb);
923 
924 	if (!(TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_ACKED))) {
925 		tp->lost_out += tcp_skb_pcount(skb);
926 		TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
927 	}
928 }
929 
930 /* This procedure tags the retransmission queue when SACKs arrive.
931  *
932  * We have three tag bits: SACKED(S), RETRANS(R) and LOST(L).
933  * Packets in queue with these bits set are counted in variables
934  * sacked_out, retrans_out and lost_out, correspondingly.
935  *
936  * Valid combinations are:
937  * Tag  InFlight	Description
938  * 0	1		- orig segment is in flight.
939  * S	0		- nothing flies, orig reached receiver.
940  * L	0		- nothing flies, orig lost by net.
941  * R	2		- both orig and retransmit are in flight.
942  * L|R	1		- orig is lost, retransmit is in flight.
943  * S|R  1		- orig reached receiver, retrans is still in flight.
944  * (L|S|R is logically valid, it could occur when L|R is sacked,
945  *  but it is equivalent to plain S and code short-curcuits it to S.
946  *  L|S is logically invalid, it would mean -1 packet in flight 8))
947  *
948  * These 6 states form finite state machine, controlled by the following events:
949  * 1. New ACK (+SACK) arrives. (tcp_sacktag_write_queue())
950  * 2. Retransmission. (tcp_retransmit_skb(), tcp_xmit_retransmit_queue())
951  * 3. Loss detection event of two flavors:
952  *	A. Scoreboard estimator decided the packet is lost.
953  *	   A'. Reno "three dupacks" marks head of queue lost.
954  *	   A''. Its FACK modification, head until snd.fack is lost.
955  *	B. SACK arrives sacking SND.NXT at the moment, when the
956  *	   segment was retransmitted.
957  * 4. D-SACK added new rule: D-SACK changes any tag to S.
958  *
959  * It is pleasant to note, that state diagram turns out to be commutative,
960  * so that we are allowed not to be bothered by order of our actions,
961  * when multiple events arrive simultaneously. (see the function below).
962  *
963  * Reordering detection.
964  * --------------------
965  * Reordering metric is maximal distance, which a packet can be displaced
966  * in packet stream. With SACKs we can estimate it:
967  *
968  * 1. SACK fills old hole and the corresponding segment was not
969  *    ever retransmitted -> reordering. Alas, we cannot use it
970  *    when segment was retransmitted.
971  * 2. The last flaw is solved with D-SACK. D-SACK arrives
972  *    for retransmitted and already SACKed segment -> reordering..
973  * Both of these heuristics are not used in Loss state, when we cannot
974  * account for retransmits accurately.
975  *
976  * SACK block validation.
977  * ----------------------
978  *
979  * SACK block range validation checks that the received SACK block fits to
980  * the expected sequence limits, i.e., it is between SND.UNA and SND.NXT.
981  * Note that SND.UNA is not included to the range though being valid because
982  * it means that the receiver is rather inconsistent with itself reporting
983  * SACK reneging when it should advance SND.UNA. Such SACK block this is
984  * perfectly valid, however, in light of RFC2018 which explicitly states
985  * that "SACK block MUST reflect the newest segment.  Even if the newest
986  * segment is going to be discarded ...", not that it looks very clever
987  * in case of head skb. Due to potentional receiver driven attacks, we
988  * choose to avoid immediate execution of a walk in write queue due to
989  * reneging and defer head skb's loss recovery to standard loss recovery
990  * procedure that will eventually trigger (nothing forbids us doing this).
991  *
992  * Implements also blockage to start_seq wrap-around. Problem lies in the
993  * fact that though start_seq (s) is before end_seq (i.e., not reversed),
994  * there's no guarantee that it will be before snd_nxt (n). The problem
995  * happens when start_seq resides between end_seq wrap (e_w) and snd_nxt
996  * wrap (s_w):
997  *
998  *         <- outs wnd ->                          <- wrapzone ->
999  *         u     e      n                         u_w   e_w  s n_w
1000  *         |     |      |                          |     |   |  |
1001  * |<------------+------+----- TCP seqno space --------------+---------->|
1002  * ...-- <2^31 ->|                                           |<--------...
1003  * ...---- >2^31 ------>|                                    |<--------...
1004  *
1005  * Current code wouldn't be vulnerable but it's better still to discard such
1006  * crazy SACK blocks. Doing this check for start_seq alone closes somewhat
1007  * similar case (end_seq after snd_nxt wrap) as earlier reversed check in
1008  * snd_nxt wrap -> snd_una region will then become "well defined", i.e.,
1009  * equal to the ideal case (infinite seqno space without wrap caused issues).
1010  *
1011  * With D-SACK the lower bound is extended to cover sequence space below
1012  * SND.UNA down to undo_marker, which is the last point of interest. Yet
1013  * again, D-SACK block must not to go across snd_una (for the same reason as
1014  * for the normal SACK blocks, explained above). But there all simplicity
1015  * ends, TCP might receive valid D-SACKs below that. As long as they reside
1016  * fully below undo_marker they do not affect behavior in anyway and can
1017  * therefore be safely ignored. In rare cases (which are more or less
1018  * theoretical ones), the D-SACK will nicely cross that boundary due to skb
1019  * fragmentation and packet reordering past skb's retransmission. To consider
1020  * them correctly, the acceptable range must be extended even more though
1021  * the exact amount is rather hard to quantify. However, tp->max_window can
1022  * be used as an exaggerated estimate.
1023  */
tcp_is_sackblock_valid(struct tcp_sock * tp,bool is_dsack,u32 start_seq,u32 end_seq)1024 static bool tcp_is_sackblock_valid(struct tcp_sock *tp, bool is_dsack,
1025 				   u32 start_seq, u32 end_seq)
1026 {
1027 	/* Too far in future, or reversed (interpretation is ambiguous) */
1028 	if (after(end_seq, tp->snd_nxt) || !before(start_seq, end_seq))
1029 		return false;
1030 
1031 	/* Nasty start_seq wrap-around check (see comments above) */
1032 	if (!before(start_seq, tp->snd_nxt))
1033 		return false;
1034 
1035 	/* In outstanding window? ...This is valid exit for D-SACKs too.
1036 	 * start_seq == snd_una is non-sensical (see comments above)
1037 	 */
1038 	if (after(start_seq, tp->snd_una))
1039 		return true;
1040 
1041 	if (!is_dsack || !tp->undo_marker)
1042 		return false;
1043 
1044 	/* ...Then it's D-SACK, and must reside below snd_una completely */
1045 	if (after(end_seq, tp->snd_una))
1046 		return false;
1047 
1048 	if (!before(start_seq, tp->undo_marker))
1049 		return true;
1050 
1051 	/* Too old */
1052 	if (!after(end_seq, tp->undo_marker))
1053 		return false;
1054 
1055 	/* Undo_marker boundary crossing (overestimates a lot). Known already:
1056 	 *   start_seq < undo_marker and end_seq >= undo_marker.
1057 	 */
1058 	return !before(start_seq, end_seq - tp->max_window);
1059 }
1060 
tcp_check_dsack(struct sock * sk,const struct sk_buff * ack_skb,struct tcp_sack_block_wire * sp,int num_sacks,u32 prior_snd_una)1061 static bool tcp_check_dsack(struct sock *sk, const struct sk_buff *ack_skb,
1062 			    struct tcp_sack_block_wire *sp, int num_sacks,
1063 			    u32 prior_snd_una)
1064 {
1065 	struct tcp_sock *tp = tcp_sk(sk);
1066 	u32 start_seq_0 = get_unaligned_be32(&sp[0].start_seq);
1067 	u32 end_seq_0 = get_unaligned_be32(&sp[0].end_seq);
1068 	bool dup_sack = false;
1069 
1070 	if (before(start_seq_0, TCP_SKB_CB(ack_skb)->ack_seq)) {
1071 		dup_sack = true;
1072 		tcp_dsack_seen(tp);
1073 		NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPDSACKRECV);
1074 	} else if (num_sacks > 1) {
1075 		u32 end_seq_1 = get_unaligned_be32(&sp[1].end_seq);
1076 		u32 start_seq_1 = get_unaligned_be32(&sp[1].start_seq);
1077 
1078 		if (!after(end_seq_0, end_seq_1) &&
1079 		    !before(start_seq_0, start_seq_1)) {
1080 			dup_sack = true;
1081 			tcp_dsack_seen(tp);
1082 			NET_INC_STATS_BH(sock_net(sk),
1083 					LINUX_MIB_TCPDSACKOFORECV);
1084 		}
1085 	}
1086 
1087 	/* D-SACK for already forgotten data... Do dumb counting. */
1088 	if (dup_sack && tp->undo_marker && tp->undo_retrans > 0 &&
1089 	    !after(end_seq_0, prior_snd_una) &&
1090 	    after(end_seq_0, tp->undo_marker))
1091 		tp->undo_retrans--;
1092 
1093 	return dup_sack;
1094 }
1095 
1096 struct tcp_sacktag_state {
1097 	int	reord;
1098 	int	fack_count;
1099 	/* Timestamps for earliest and latest never-retransmitted segment
1100 	 * that was SACKed. RTO needs the earliest RTT to stay conservative,
1101 	 * but congestion control should still get an accurate delay signal.
1102 	 */
1103 	struct skb_mstamp first_sackt;
1104 	struct skb_mstamp last_sackt;
1105 	int	flag;
1106 };
1107 
1108 /* Check if skb is fully within the SACK block. In presence of GSO skbs,
1109  * the incoming SACK may not exactly match but we can find smaller MSS
1110  * aligned portion of it that matches. Therefore we might need to fragment
1111  * which may fail and creates some hassle (caller must handle error case
1112  * returns).
1113  *
1114  * FIXME: this could be merged to shift decision code
1115  */
tcp_match_skb_to_sack(struct sock * sk,struct sk_buff * skb,u32 start_seq,u32 end_seq)1116 static int tcp_match_skb_to_sack(struct sock *sk, struct sk_buff *skb,
1117 				  u32 start_seq, u32 end_seq)
1118 {
1119 	int err;
1120 	bool in_sack;
1121 	unsigned int pkt_len;
1122 	unsigned int mss;
1123 
1124 	in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
1125 		  !before(end_seq, TCP_SKB_CB(skb)->end_seq);
1126 
1127 	if (tcp_skb_pcount(skb) > 1 && !in_sack &&
1128 	    after(TCP_SKB_CB(skb)->end_seq, start_seq)) {
1129 		mss = tcp_skb_mss(skb);
1130 		in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq);
1131 
1132 		if (!in_sack) {
1133 			pkt_len = start_seq - TCP_SKB_CB(skb)->seq;
1134 			if (pkt_len < mss)
1135 				pkt_len = mss;
1136 		} else {
1137 			pkt_len = end_seq - TCP_SKB_CB(skb)->seq;
1138 			if (pkt_len < mss)
1139 				return -EINVAL;
1140 		}
1141 
1142 		/* Round if necessary so that SACKs cover only full MSSes
1143 		 * and/or the remaining small portion (if present)
1144 		 */
1145 		if (pkt_len > mss) {
1146 			unsigned int new_len = (pkt_len / mss) * mss;
1147 			if (!in_sack && new_len < pkt_len)
1148 				new_len += mss;
1149 			pkt_len = new_len;
1150 		}
1151 
1152 		if (pkt_len >= skb->len && !in_sack)
1153 			return 0;
1154 
1155 		err = tcp_fragment(sk, skb, pkt_len, mss, GFP_ATOMIC);
1156 		if (err < 0)
1157 			return err;
1158 	}
1159 
1160 	return in_sack;
1161 }
1162 
1163 /* Mark the given newly-SACKed range as such, adjusting counters and hints. */
tcp_sacktag_one(struct sock * sk,struct tcp_sacktag_state * state,u8 sacked,u32 start_seq,u32 end_seq,int dup_sack,int pcount,const struct skb_mstamp * xmit_time)1164 static u8 tcp_sacktag_one(struct sock *sk,
1165 			  struct tcp_sacktag_state *state, u8 sacked,
1166 			  u32 start_seq, u32 end_seq,
1167 			  int dup_sack, int pcount,
1168 			  const struct skb_mstamp *xmit_time)
1169 {
1170 	struct tcp_sock *tp = tcp_sk(sk);
1171 	int fack_count = state->fack_count;
1172 
1173 	/* Account D-SACK for retransmitted packet. */
1174 	if (dup_sack && (sacked & TCPCB_RETRANS)) {
1175 		if (tp->undo_marker && tp->undo_retrans > 0 &&
1176 		    after(end_seq, tp->undo_marker))
1177 			tp->undo_retrans--;
1178 		if (sacked & TCPCB_SACKED_ACKED)
1179 			state->reord = min(fack_count, state->reord);
1180 	}
1181 
1182 	/* Nothing to do; acked frame is about to be dropped (was ACKed). */
1183 	if (!after(end_seq, tp->snd_una))
1184 		return sacked;
1185 
1186 	if (!(sacked & TCPCB_SACKED_ACKED)) {
1187 		tcp_rack_advance(tp, xmit_time, sacked);
1188 
1189 		if (sacked & TCPCB_SACKED_RETRANS) {
1190 			/* If the segment is not tagged as lost,
1191 			 * we do not clear RETRANS, believing
1192 			 * that retransmission is still in flight.
1193 			 */
1194 			if (sacked & TCPCB_LOST) {
1195 				sacked &= ~(TCPCB_LOST|TCPCB_SACKED_RETRANS);
1196 				tp->lost_out -= pcount;
1197 				tp->retrans_out -= pcount;
1198 			}
1199 		} else {
1200 			if (!(sacked & TCPCB_RETRANS)) {
1201 				/* New sack for not retransmitted frame,
1202 				 * which was in hole. It is reordering.
1203 				 */
1204 				if (before(start_seq,
1205 					   tcp_highest_sack_seq(tp)))
1206 					state->reord = min(fack_count,
1207 							   state->reord);
1208 				if (!after(end_seq, tp->high_seq))
1209 					state->flag |= FLAG_ORIG_SACK_ACKED;
1210 				if (state->first_sackt.v64 == 0)
1211 					state->first_sackt = *xmit_time;
1212 				state->last_sackt = *xmit_time;
1213 			}
1214 
1215 			if (sacked & TCPCB_LOST) {
1216 				sacked &= ~TCPCB_LOST;
1217 				tp->lost_out -= pcount;
1218 			}
1219 		}
1220 
1221 		sacked |= TCPCB_SACKED_ACKED;
1222 		state->flag |= FLAG_DATA_SACKED;
1223 		tp->sacked_out += pcount;
1224 
1225 		fack_count += pcount;
1226 
1227 		/* Lost marker hint past SACKed? Tweak RFC3517 cnt */
1228 		if (!tcp_is_fack(tp) && tp->lost_skb_hint &&
1229 		    before(start_seq, TCP_SKB_CB(tp->lost_skb_hint)->seq))
1230 			tp->lost_cnt_hint += pcount;
1231 
1232 		if (fack_count > tp->fackets_out)
1233 			tp->fackets_out = fack_count;
1234 	}
1235 
1236 	/* D-SACK. We can detect redundant retransmission in S|R and plain R
1237 	 * frames and clear it. undo_retrans is decreased above, L|R frames
1238 	 * are accounted above as well.
1239 	 */
1240 	if (dup_sack && (sacked & TCPCB_SACKED_RETRANS)) {
1241 		sacked &= ~TCPCB_SACKED_RETRANS;
1242 		tp->retrans_out -= pcount;
1243 	}
1244 
1245 	return sacked;
1246 }
1247 
1248 /* Shift newly-SACKed bytes from this skb to the immediately previous
1249  * already-SACKed sk_buff. Mark the newly-SACKed bytes as such.
1250  */
tcp_shifted_skb(struct sock * sk,struct sk_buff * skb,struct tcp_sacktag_state * state,unsigned int pcount,int shifted,int mss,bool dup_sack)1251 static bool tcp_shifted_skb(struct sock *sk, struct sk_buff *skb,
1252 			    struct tcp_sacktag_state *state,
1253 			    unsigned int pcount, int shifted, int mss,
1254 			    bool dup_sack)
1255 {
1256 	struct tcp_sock *tp = tcp_sk(sk);
1257 	struct sk_buff *prev = tcp_write_queue_prev(sk, skb);
1258 	u32 start_seq = TCP_SKB_CB(skb)->seq;	/* start of newly-SACKed */
1259 	u32 end_seq = start_seq + shifted;	/* end of newly-SACKed */
1260 
1261 	BUG_ON(!pcount);
1262 
1263 	/* Adjust counters and hints for the newly sacked sequence
1264 	 * range but discard the return value since prev is already
1265 	 * marked. We must tag the range first because the seq
1266 	 * advancement below implicitly advances
1267 	 * tcp_highest_sack_seq() when skb is highest_sack.
1268 	 */
1269 	tcp_sacktag_one(sk, state, TCP_SKB_CB(skb)->sacked,
1270 			start_seq, end_seq, dup_sack, pcount,
1271 			&skb->skb_mstamp);
1272 
1273 	if (skb == tp->lost_skb_hint)
1274 		tp->lost_cnt_hint += pcount;
1275 
1276 	TCP_SKB_CB(prev)->end_seq += shifted;
1277 	TCP_SKB_CB(skb)->seq += shifted;
1278 
1279 	tcp_skb_pcount_add(prev, pcount);
1280 	WARN_ON_ONCE(tcp_skb_pcount(skb) < pcount);
1281 	tcp_skb_pcount_add(skb, -pcount);
1282 
1283 	/* When we're adding to gso_segs == 1, gso_size will be zero,
1284 	 * in theory this shouldn't be necessary but as long as DSACK
1285 	 * code can come after this skb later on it's better to keep
1286 	 * setting gso_size to something.
1287 	 */
1288 	if (!TCP_SKB_CB(prev)->tcp_gso_size)
1289 		TCP_SKB_CB(prev)->tcp_gso_size = mss;
1290 
1291 	/* CHECKME: To clear or not to clear? Mimics normal skb currently */
1292 	if (tcp_skb_pcount(skb) <= 1)
1293 		TCP_SKB_CB(skb)->tcp_gso_size = 0;
1294 
1295 	/* Difference in this won't matter, both ACKed by the same cumul. ACK */
1296 	TCP_SKB_CB(prev)->sacked |= (TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS);
1297 
1298 	if (skb->len > 0) {
1299 		BUG_ON(!tcp_skb_pcount(skb));
1300 		NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SACKSHIFTED);
1301 		return false;
1302 	}
1303 
1304 	/* Whole SKB was eaten :-) */
1305 
1306 	if (skb == tp->retransmit_skb_hint)
1307 		tp->retransmit_skb_hint = prev;
1308 	if (skb == tp->lost_skb_hint) {
1309 		tp->lost_skb_hint = prev;
1310 		tp->lost_cnt_hint -= tcp_skb_pcount(prev);
1311 	}
1312 
1313 	TCP_SKB_CB(prev)->tcp_flags |= TCP_SKB_CB(skb)->tcp_flags;
1314 	if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
1315 		TCP_SKB_CB(prev)->end_seq++;
1316 
1317 	if (skb == tcp_highest_sack(sk))
1318 		tcp_advance_highest_sack(sk, skb);
1319 
1320 	tcp_unlink_write_queue(skb, sk);
1321 	sk_wmem_free_skb(sk, skb);
1322 
1323 	NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SACKMERGED);
1324 
1325 	return true;
1326 }
1327 
1328 /* I wish gso_size would have a bit more sane initialization than
1329  * something-or-zero which complicates things
1330  */
tcp_skb_seglen(const struct sk_buff * skb)1331 static int tcp_skb_seglen(const struct sk_buff *skb)
1332 {
1333 	return tcp_skb_pcount(skb) == 1 ? skb->len : tcp_skb_mss(skb);
1334 }
1335 
1336 /* Shifting pages past head area doesn't work */
skb_can_shift(const struct sk_buff * skb)1337 static int skb_can_shift(const struct sk_buff *skb)
1338 {
1339 	return !skb_headlen(skb) && skb_is_nonlinear(skb);
1340 }
1341 
tcp_skb_shift(struct sk_buff * to,struct sk_buff * from,int pcount,int shiftlen)1342 int tcp_skb_shift(struct sk_buff *to, struct sk_buff *from,
1343 		  int pcount, int shiftlen)
1344 {
1345 	/* TCP min gso_size is 8 bytes (TCP_MIN_GSO_SIZE)
1346 	 * Since TCP_SKB_CB(skb)->tcp_gso_segs is 16 bits, we need
1347 	 * to make sure not storing more than 65535 * 8 bytes per skb,
1348 	 * even if current MSS is bigger.
1349 	 */
1350 	if (unlikely(to->len + shiftlen >= 65535 * TCP_MIN_GSO_SIZE))
1351 		return 0;
1352 	if (unlikely(tcp_skb_pcount(to) + pcount > 65535))
1353 		return 0;
1354 	return skb_shift(to, from, shiftlen);
1355 }
1356 
1357 /* Try collapsing SACK blocks spanning across multiple skbs to a single
1358  * skb.
1359  */
tcp_shift_skb_data(struct sock * sk,struct sk_buff * skb,struct tcp_sacktag_state * state,u32 start_seq,u32 end_seq,bool dup_sack)1360 static struct sk_buff *tcp_shift_skb_data(struct sock *sk, struct sk_buff *skb,
1361 					  struct tcp_sacktag_state *state,
1362 					  u32 start_seq, u32 end_seq,
1363 					  bool dup_sack)
1364 {
1365 	struct tcp_sock *tp = tcp_sk(sk);
1366 	struct sk_buff *prev;
1367 	int mss;
1368 	int next_pcount;
1369 	int pcount = 0;
1370 	int len;
1371 	int in_sack;
1372 
1373 	if (!sk_can_gso(sk))
1374 		goto fallback;
1375 
1376 	/* Normally R but no L won't result in plain S */
1377 	if (!dup_sack &&
1378 	    (TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_RETRANS)) == TCPCB_SACKED_RETRANS)
1379 		goto fallback;
1380 	if (!skb_can_shift(skb))
1381 		goto fallback;
1382 	/* This frame is about to be dropped (was ACKed). */
1383 	if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una))
1384 		goto fallback;
1385 
1386 	/* Can only happen with delayed DSACK + discard craziness */
1387 	if (unlikely(skb == tcp_write_queue_head(sk)))
1388 		goto fallback;
1389 	prev = tcp_write_queue_prev(sk, skb);
1390 
1391 	if ((TCP_SKB_CB(prev)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED)
1392 		goto fallback;
1393 
1394 	in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
1395 		  !before(end_seq, TCP_SKB_CB(skb)->end_seq);
1396 
1397 	if (in_sack) {
1398 		len = skb->len;
1399 		pcount = tcp_skb_pcount(skb);
1400 		mss = tcp_skb_seglen(skb);
1401 
1402 		/* TODO: Fix DSACKs to not fragment already SACKed and we can
1403 		 * drop this restriction as unnecessary
1404 		 */
1405 		if (mss != tcp_skb_seglen(prev))
1406 			goto fallback;
1407 	} else {
1408 		if (!after(TCP_SKB_CB(skb)->end_seq, start_seq))
1409 			goto noop;
1410 		/* CHECKME: This is non-MSS split case only?, this will
1411 		 * cause skipped skbs due to advancing loop btw, original
1412 		 * has that feature too
1413 		 */
1414 		if (tcp_skb_pcount(skb) <= 1)
1415 			goto noop;
1416 
1417 		in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq);
1418 		if (!in_sack) {
1419 			/* TODO: head merge to next could be attempted here
1420 			 * if (!after(TCP_SKB_CB(skb)->end_seq, end_seq)),
1421 			 * though it might not be worth of the additional hassle
1422 			 *
1423 			 * ...we can probably just fallback to what was done
1424 			 * previously. We could try merging non-SACKed ones
1425 			 * as well but it probably isn't going to buy off
1426 			 * because later SACKs might again split them, and
1427 			 * it would make skb timestamp tracking considerably
1428 			 * harder problem.
1429 			 */
1430 			goto fallback;
1431 		}
1432 
1433 		len = end_seq - TCP_SKB_CB(skb)->seq;
1434 		BUG_ON(len < 0);
1435 		BUG_ON(len > skb->len);
1436 
1437 		/* MSS boundaries should be honoured or else pcount will
1438 		 * severely break even though it makes things bit trickier.
1439 		 * Optimize common case to avoid most of the divides
1440 		 */
1441 		mss = tcp_skb_mss(skb);
1442 
1443 		/* TODO: Fix DSACKs to not fragment already SACKed and we can
1444 		 * drop this restriction as unnecessary
1445 		 */
1446 		if (mss != tcp_skb_seglen(prev))
1447 			goto fallback;
1448 
1449 		if (len == mss) {
1450 			pcount = 1;
1451 		} else if (len < mss) {
1452 			goto noop;
1453 		} else {
1454 			pcount = len / mss;
1455 			len = pcount * mss;
1456 		}
1457 	}
1458 
1459 	/* tcp_sacktag_one() won't SACK-tag ranges below snd_una */
1460 	if (!after(TCP_SKB_CB(skb)->seq + len, tp->snd_una))
1461 		goto fallback;
1462 
1463 	if (!tcp_skb_shift(prev, skb, pcount, len))
1464 		goto fallback;
1465 	if (!tcp_shifted_skb(sk, skb, state, pcount, len, mss, dup_sack))
1466 		goto out;
1467 
1468 	/* Hole filled allows collapsing with the next as well, this is very
1469 	 * useful when hole on every nth skb pattern happens
1470 	 */
1471 	if (prev == tcp_write_queue_tail(sk))
1472 		goto out;
1473 	skb = tcp_write_queue_next(sk, prev);
1474 
1475 	if (!skb_can_shift(skb) ||
1476 	    (skb == tcp_send_head(sk)) ||
1477 	    ((TCP_SKB_CB(skb)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED) ||
1478 	    (mss != tcp_skb_seglen(skb)))
1479 		goto out;
1480 
1481 	len = skb->len;
1482 	next_pcount = tcp_skb_pcount(skb);
1483 	if (tcp_skb_shift(prev, skb, next_pcount, len)) {
1484 		pcount += next_pcount;
1485 		tcp_shifted_skb(sk, skb, state, next_pcount, len, mss, 0);
1486 	}
1487 out:
1488 	state->fack_count += pcount;
1489 	return prev;
1490 
1491 noop:
1492 	return skb;
1493 
1494 fallback:
1495 	NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SACKSHIFTFALLBACK);
1496 	return NULL;
1497 }
1498 
tcp_sacktag_walk(struct sk_buff * skb,struct sock * sk,struct tcp_sack_block * next_dup,struct tcp_sacktag_state * state,u32 start_seq,u32 end_seq,bool dup_sack_in)1499 static struct sk_buff *tcp_sacktag_walk(struct sk_buff *skb, struct sock *sk,
1500 					struct tcp_sack_block *next_dup,
1501 					struct tcp_sacktag_state *state,
1502 					u32 start_seq, u32 end_seq,
1503 					bool dup_sack_in)
1504 {
1505 	struct tcp_sock *tp = tcp_sk(sk);
1506 	struct sk_buff *tmp;
1507 
1508 	tcp_for_write_queue_from(skb, sk) {
1509 		int in_sack = 0;
1510 		bool dup_sack = dup_sack_in;
1511 
1512 		if (skb == tcp_send_head(sk))
1513 			break;
1514 
1515 		/* queue is in-order => we can short-circuit the walk early */
1516 		if (!before(TCP_SKB_CB(skb)->seq, end_seq))
1517 			break;
1518 
1519 		if (next_dup  &&
1520 		    before(TCP_SKB_CB(skb)->seq, next_dup->end_seq)) {
1521 			in_sack = tcp_match_skb_to_sack(sk, skb,
1522 							next_dup->start_seq,
1523 							next_dup->end_seq);
1524 			if (in_sack > 0)
1525 				dup_sack = true;
1526 		}
1527 
1528 		/* skb reference here is a bit tricky to get right, since
1529 		 * shifting can eat and free both this skb and the next,
1530 		 * so not even _safe variant of the loop is enough.
1531 		 */
1532 		if (in_sack <= 0) {
1533 			tmp = tcp_shift_skb_data(sk, skb, state,
1534 						 start_seq, end_seq, dup_sack);
1535 			if (tmp) {
1536 				if (tmp != skb) {
1537 					skb = tmp;
1538 					continue;
1539 				}
1540 
1541 				in_sack = 0;
1542 			} else {
1543 				in_sack = tcp_match_skb_to_sack(sk, skb,
1544 								start_seq,
1545 								end_seq);
1546 			}
1547 		}
1548 
1549 		if (unlikely(in_sack < 0))
1550 			break;
1551 
1552 		if (in_sack) {
1553 			TCP_SKB_CB(skb)->sacked =
1554 				tcp_sacktag_one(sk,
1555 						state,
1556 						TCP_SKB_CB(skb)->sacked,
1557 						TCP_SKB_CB(skb)->seq,
1558 						TCP_SKB_CB(skb)->end_seq,
1559 						dup_sack,
1560 						tcp_skb_pcount(skb),
1561 						&skb->skb_mstamp);
1562 
1563 			if (!before(TCP_SKB_CB(skb)->seq,
1564 				    tcp_highest_sack_seq(tp)))
1565 				tcp_advance_highest_sack(sk, skb);
1566 		}
1567 
1568 		state->fack_count += tcp_skb_pcount(skb);
1569 	}
1570 	return skb;
1571 }
1572 
1573 /* Avoid all extra work that is being done by sacktag while walking in
1574  * a normal way
1575  */
tcp_sacktag_skip(struct sk_buff * skb,struct sock * sk,struct tcp_sacktag_state * state,u32 skip_to_seq)1576 static struct sk_buff *tcp_sacktag_skip(struct sk_buff *skb, struct sock *sk,
1577 					struct tcp_sacktag_state *state,
1578 					u32 skip_to_seq)
1579 {
1580 	tcp_for_write_queue_from(skb, sk) {
1581 		if (skb == tcp_send_head(sk))
1582 			break;
1583 
1584 		if (after(TCP_SKB_CB(skb)->end_seq, skip_to_seq))
1585 			break;
1586 
1587 		state->fack_count += tcp_skb_pcount(skb);
1588 	}
1589 	return skb;
1590 }
1591 
tcp_maybe_skipping_dsack(struct sk_buff * skb,struct sock * sk,struct tcp_sack_block * next_dup,struct tcp_sacktag_state * state,u32 skip_to_seq)1592 static struct sk_buff *tcp_maybe_skipping_dsack(struct sk_buff *skb,
1593 						struct sock *sk,
1594 						struct tcp_sack_block *next_dup,
1595 						struct tcp_sacktag_state *state,
1596 						u32 skip_to_seq)
1597 {
1598 	if (!next_dup)
1599 		return skb;
1600 
1601 	if (before(next_dup->start_seq, skip_to_seq)) {
1602 		skb = tcp_sacktag_skip(skb, sk, state, next_dup->start_seq);
1603 		skb = tcp_sacktag_walk(skb, sk, NULL, state,
1604 				       next_dup->start_seq, next_dup->end_seq,
1605 				       1);
1606 	}
1607 
1608 	return skb;
1609 }
1610 
tcp_sack_cache_ok(const struct tcp_sock * tp,const struct tcp_sack_block * cache)1611 static int tcp_sack_cache_ok(const struct tcp_sock *tp, const struct tcp_sack_block *cache)
1612 {
1613 	return cache < tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache);
1614 }
1615 
1616 static int
tcp_sacktag_write_queue(struct sock * sk,const struct sk_buff * ack_skb,u32 prior_snd_una,struct tcp_sacktag_state * state)1617 tcp_sacktag_write_queue(struct sock *sk, const struct sk_buff *ack_skb,
1618 			u32 prior_snd_una, struct tcp_sacktag_state *state)
1619 {
1620 	struct tcp_sock *tp = tcp_sk(sk);
1621 	const unsigned char *ptr = (skb_transport_header(ack_skb) +
1622 				    TCP_SKB_CB(ack_skb)->sacked);
1623 	struct tcp_sack_block_wire *sp_wire = (struct tcp_sack_block_wire *)(ptr+2);
1624 	struct tcp_sack_block sp[TCP_NUM_SACKS];
1625 	struct tcp_sack_block *cache;
1626 	struct sk_buff *skb;
1627 	int num_sacks = min(TCP_NUM_SACKS, (ptr[1] - TCPOLEN_SACK_BASE) >> 3);
1628 	int used_sacks;
1629 	bool found_dup_sack = false;
1630 	int i, j;
1631 	int first_sack_index;
1632 
1633 	state->flag = 0;
1634 	state->reord = tp->packets_out;
1635 
1636 	if (!tp->sacked_out) {
1637 		if (WARN_ON(tp->fackets_out))
1638 			tp->fackets_out = 0;
1639 		tcp_highest_sack_reset(sk);
1640 	}
1641 
1642 	found_dup_sack = tcp_check_dsack(sk, ack_skb, sp_wire,
1643 					 num_sacks, prior_snd_una);
1644 	if (found_dup_sack)
1645 		state->flag |= FLAG_DSACKING_ACK;
1646 
1647 	/* Eliminate too old ACKs, but take into
1648 	 * account more or less fresh ones, they can
1649 	 * contain valid SACK info.
1650 	 */
1651 	if (before(TCP_SKB_CB(ack_skb)->ack_seq, prior_snd_una - tp->max_window))
1652 		return 0;
1653 
1654 	if (!tp->packets_out)
1655 		goto out;
1656 
1657 	used_sacks = 0;
1658 	first_sack_index = 0;
1659 	for (i = 0; i < num_sacks; i++) {
1660 		bool dup_sack = !i && found_dup_sack;
1661 
1662 		sp[used_sacks].start_seq = get_unaligned_be32(&sp_wire[i].start_seq);
1663 		sp[used_sacks].end_seq = get_unaligned_be32(&sp_wire[i].end_seq);
1664 
1665 		if (!tcp_is_sackblock_valid(tp, dup_sack,
1666 					    sp[used_sacks].start_seq,
1667 					    sp[used_sacks].end_seq)) {
1668 			int mib_idx;
1669 
1670 			if (dup_sack) {
1671 				if (!tp->undo_marker)
1672 					mib_idx = LINUX_MIB_TCPDSACKIGNOREDNOUNDO;
1673 				else
1674 					mib_idx = LINUX_MIB_TCPDSACKIGNOREDOLD;
1675 			} else {
1676 				/* Don't count olds caused by ACK reordering */
1677 				if ((TCP_SKB_CB(ack_skb)->ack_seq != tp->snd_una) &&
1678 				    !after(sp[used_sacks].end_seq, tp->snd_una))
1679 					continue;
1680 				mib_idx = LINUX_MIB_TCPSACKDISCARD;
1681 			}
1682 
1683 			NET_INC_STATS_BH(sock_net(sk), mib_idx);
1684 			if (i == 0)
1685 				first_sack_index = -1;
1686 			continue;
1687 		}
1688 
1689 		/* Ignore very old stuff early */
1690 		if (!after(sp[used_sacks].end_seq, prior_snd_una)) {
1691 			if (i == 0)
1692 				first_sack_index = -1;
1693 			continue;
1694 		}
1695 
1696 		used_sacks++;
1697 	}
1698 
1699 	/* order SACK blocks to allow in order walk of the retrans queue */
1700 	for (i = used_sacks - 1; i > 0; i--) {
1701 		for (j = 0; j < i; j++) {
1702 			if (after(sp[j].start_seq, sp[j + 1].start_seq)) {
1703 				swap(sp[j], sp[j + 1]);
1704 
1705 				/* Track where the first SACK block goes to */
1706 				if (j == first_sack_index)
1707 					first_sack_index = j + 1;
1708 			}
1709 		}
1710 	}
1711 
1712 	skb = tcp_write_queue_head(sk);
1713 	state->fack_count = 0;
1714 	i = 0;
1715 
1716 	if (!tp->sacked_out) {
1717 		/* It's already past, so skip checking against it */
1718 		cache = tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache);
1719 	} else {
1720 		cache = tp->recv_sack_cache;
1721 		/* Skip empty blocks in at head of the cache */
1722 		while (tcp_sack_cache_ok(tp, cache) && !cache->start_seq &&
1723 		       !cache->end_seq)
1724 			cache++;
1725 	}
1726 
1727 	while (i < used_sacks) {
1728 		u32 start_seq = sp[i].start_seq;
1729 		u32 end_seq = sp[i].end_seq;
1730 		bool dup_sack = (found_dup_sack && (i == first_sack_index));
1731 		struct tcp_sack_block *next_dup = NULL;
1732 
1733 		if (found_dup_sack && ((i + 1) == first_sack_index))
1734 			next_dup = &sp[i + 1];
1735 
1736 		/* Skip too early cached blocks */
1737 		while (tcp_sack_cache_ok(tp, cache) &&
1738 		       !before(start_seq, cache->end_seq))
1739 			cache++;
1740 
1741 		/* Can skip some work by looking recv_sack_cache? */
1742 		if (tcp_sack_cache_ok(tp, cache) && !dup_sack &&
1743 		    after(end_seq, cache->start_seq)) {
1744 
1745 			/* Head todo? */
1746 			if (before(start_seq, cache->start_seq)) {
1747 				skb = tcp_sacktag_skip(skb, sk, state,
1748 						       start_seq);
1749 				skb = tcp_sacktag_walk(skb, sk, next_dup,
1750 						       state,
1751 						       start_seq,
1752 						       cache->start_seq,
1753 						       dup_sack);
1754 			}
1755 
1756 			/* Rest of the block already fully processed? */
1757 			if (!after(end_seq, cache->end_seq))
1758 				goto advance_sp;
1759 
1760 			skb = tcp_maybe_skipping_dsack(skb, sk, next_dup,
1761 						       state,
1762 						       cache->end_seq);
1763 
1764 			/* ...tail remains todo... */
1765 			if (tcp_highest_sack_seq(tp) == cache->end_seq) {
1766 				/* ...but better entrypoint exists! */
1767 				skb = tcp_highest_sack(sk);
1768 				if (!skb)
1769 					break;
1770 				state->fack_count = tp->fackets_out;
1771 				cache++;
1772 				goto walk;
1773 			}
1774 
1775 			skb = tcp_sacktag_skip(skb, sk, state, cache->end_seq);
1776 			/* Check overlap against next cached too (past this one already) */
1777 			cache++;
1778 			continue;
1779 		}
1780 
1781 		if (!before(start_seq, tcp_highest_sack_seq(tp))) {
1782 			skb = tcp_highest_sack(sk);
1783 			if (!skb)
1784 				break;
1785 			state->fack_count = tp->fackets_out;
1786 		}
1787 		skb = tcp_sacktag_skip(skb, sk, state, start_seq);
1788 
1789 walk:
1790 		skb = tcp_sacktag_walk(skb, sk, next_dup, state,
1791 				       start_seq, end_seq, dup_sack);
1792 
1793 advance_sp:
1794 		i++;
1795 	}
1796 
1797 	/* Clear the head of the cache sack blocks so we can skip it next time */
1798 	for (i = 0; i < ARRAY_SIZE(tp->recv_sack_cache) - used_sacks; i++) {
1799 		tp->recv_sack_cache[i].start_seq = 0;
1800 		tp->recv_sack_cache[i].end_seq = 0;
1801 	}
1802 	for (j = 0; j < used_sacks; j++)
1803 		tp->recv_sack_cache[i++] = sp[j];
1804 
1805 	if ((state->reord < tp->fackets_out) &&
1806 	    ((inet_csk(sk)->icsk_ca_state != TCP_CA_Loss) || tp->undo_marker))
1807 		tcp_update_reordering(sk, tp->fackets_out - state->reord, 0);
1808 
1809 	tcp_verify_left_out(tp);
1810 out:
1811 
1812 #if FASTRETRANS_DEBUG > 0
1813 	WARN_ON((int)tp->sacked_out < 0);
1814 	WARN_ON((int)tp->lost_out < 0);
1815 	WARN_ON((int)tp->retrans_out < 0);
1816 	WARN_ON((int)tcp_packets_in_flight(tp) < 0);
1817 #endif
1818 	return state->flag;
1819 }
1820 
1821 /* Limits sacked_out so that sum with lost_out isn't ever larger than
1822  * packets_out. Returns false if sacked_out adjustement wasn't necessary.
1823  */
tcp_limit_reno_sacked(struct tcp_sock * tp)1824 static bool tcp_limit_reno_sacked(struct tcp_sock *tp)
1825 {
1826 	u32 holes;
1827 
1828 	holes = max(tp->lost_out, 1U);
1829 	holes = min(holes, tp->packets_out);
1830 
1831 	if ((tp->sacked_out + holes) > tp->packets_out) {
1832 		tp->sacked_out = tp->packets_out - holes;
1833 		return true;
1834 	}
1835 	return false;
1836 }
1837 
1838 /* If we receive more dupacks than we expected counting segments
1839  * in assumption of absent reordering, interpret this as reordering.
1840  * The only another reason could be bug in receiver TCP.
1841  */
tcp_check_reno_reordering(struct sock * sk,const int addend)1842 static void tcp_check_reno_reordering(struct sock *sk, const int addend)
1843 {
1844 	struct tcp_sock *tp = tcp_sk(sk);
1845 	if (tcp_limit_reno_sacked(tp))
1846 		tcp_update_reordering(sk, tp->packets_out + addend, 0);
1847 }
1848 
1849 /* Emulate SACKs for SACKless connection: account for a new dupack. */
1850 
tcp_add_reno_sack(struct sock * sk)1851 static void tcp_add_reno_sack(struct sock *sk)
1852 {
1853 	struct tcp_sock *tp = tcp_sk(sk);
1854 	tp->sacked_out++;
1855 	tcp_check_reno_reordering(sk, 0);
1856 	tcp_verify_left_out(tp);
1857 }
1858 
1859 /* Account for ACK, ACKing some data in Reno Recovery phase. */
1860 
tcp_remove_reno_sacks(struct sock * sk,int acked)1861 static void tcp_remove_reno_sacks(struct sock *sk, int acked)
1862 {
1863 	struct tcp_sock *tp = tcp_sk(sk);
1864 
1865 	if (acked > 0) {
1866 		/* One ACK acked hole. The rest eat duplicate ACKs. */
1867 		if (acked - 1 >= tp->sacked_out)
1868 			tp->sacked_out = 0;
1869 		else
1870 			tp->sacked_out -= acked - 1;
1871 	}
1872 	tcp_check_reno_reordering(sk, acked);
1873 	tcp_verify_left_out(tp);
1874 }
1875 
tcp_reset_reno_sack(struct tcp_sock * tp)1876 static inline void tcp_reset_reno_sack(struct tcp_sock *tp)
1877 {
1878 	tp->sacked_out = 0;
1879 }
1880 
tcp_clear_retrans(struct tcp_sock * tp)1881 void tcp_clear_retrans(struct tcp_sock *tp)
1882 {
1883 	tp->retrans_out = 0;
1884 	tp->lost_out = 0;
1885 	tp->undo_marker = 0;
1886 	tp->undo_retrans = -1;
1887 	tp->fackets_out = 0;
1888 	tp->sacked_out = 0;
1889 }
1890 
tcp_init_undo(struct tcp_sock * tp)1891 static inline void tcp_init_undo(struct tcp_sock *tp)
1892 {
1893 	tp->undo_marker = tp->snd_una;
1894 	/* Retransmission still in flight may cause DSACKs later. */
1895 	tp->undo_retrans = tp->retrans_out ? : -1;
1896 }
1897 
1898 /* Enter Loss state. If we detect SACK reneging, forget all SACK information
1899  * and reset tags completely, otherwise preserve SACKs. If receiver
1900  * dropped its ofo queue, we will know this due to reneging detection.
1901  */
tcp_enter_loss(struct sock * sk)1902 void tcp_enter_loss(struct sock *sk)
1903 {
1904 	const struct inet_connection_sock *icsk = inet_csk(sk);
1905 	struct tcp_sock *tp = tcp_sk(sk);
1906 	struct sk_buff *skb;
1907 	bool new_recovery = icsk->icsk_ca_state < TCP_CA_Recovery;
1908 	bool is_reneg;			/* is receiver reneging on SACKs? */
1909 
1910 	/* Reduce ssthresh if it has not yet been made inside this window. */
1911 	if (icsk->icsk_ca_state <= TCP_CA_Disorder ||
1912 	    !after(tp->high_seq, tp->snd_una) ||
1913 	    (icsk->icsk_ca_state == TCP_CA_Loss && !icsk->icsk_retransmits)) {
1914 		tp->prior_ssthresh = tcp_current_ssthresh(sk);
1915 		tp->snd_ssthresh = icsk->icsk_ca_ops->ssthresh(sk);
1916 		tcp_ca_event(sk, CA_EVENT_LOSS);
1917 		tcp_init_undo(tp);
1918 	}
1919 	tp->snd_cwnd	   = 1;
1920 	tp->snd_cwnd_cnt   = 0;
1921 	tp->snd_cwnd_stamp = tcp_time_stamp;
1922 
1923 	tp->retrans_out = 0;
1924 	tp->lost_out = 0;
1925 
1926 	if (tcp_is_reno(tp))
1927 		tcp_reset_reno_sack(tp);
1928 
1929 	skb = tcp_write_queue_head(sk);
1930 	is_reneg = skb && (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED);
1931 	if (is_reneg) {
1932 		NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPSACKRENEGING);
1933 		tp->sacked_out = 0;
1934 		tp->fackets_out = 0;
1935 	}
1936 	tcp_clear_all_retrans_hints(tp);
1937 
1938 	tcp_for_write_queue(skb, sk) {
1939 		if (skb == tcp_send_head(sk))
1940 			break;
1941 
1942 		TCP_SKB_CB(skb)->sacked &= (~TCPCB_TAGBITS)|TCPCB_SACKED_ACKED;
1943 		if (!(TCP_SKB_CB(skb)->sacked&TCPCB_SACKED_ACKED) || is_reneg) {
1944 			TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_ACKED;
1945 			TCP_SKB_CB(skb)->sacked |= TCPCB_LOST;
1946 			tp->lost_out += tcp_skb_pcount(skb);
1947 			tp->retransmit_high = TCP_SKB_CB(skb)->end_seq;
1948 		}
1949 	}
1950 	tcp_verify_left_out(tp);
1951 
1952 	/* Timeout in disordered state after receiving substantial DUPACKs
1953 	 * suggests that the degree of reordering is over-estimated.
1954 	 */
1955 	if (icsk->icsk_ca_state <= TCP_CA_Disorder &&
1956 	    tp->sacked_out >= sysctl_tcp_reordering)
1957 		tp->reordering = min_t(unsigned int, tp->reordering,
1958 				       sysctl_tcp_reordering);
1959 	tcp_set_ca_state(sk, TCP_CA_Loss);
1960 	tp->high_seq = tp->snd_nxt;
1961 	tcp_ecn_queue_cwr(tp);
1962 
1963 	/* F-RTO RFC5682 sec 3.1 step 1: retransmit SND.UNA if no previous
1964 	 * loss recovery is underway except recurring timeout(s) on
1965 	 * the same SND.UNA (sec 3.2). Disable F-RTO on path MTU probing
1966 	 */
1967 	tp->frto = sysctl_tcp_frto &&
1968 		   (new_recovery || icsk->icsk_retransmits) &&
1969 		   !inet_csk(sk)->icsk_mtup.probe_size;
1970 }
1971 
1972 /* If ACK arrived pointing to a remembered SACK, it means that our
1973  * remembered SACKs do not reflect real state of receiver i.e.
1974  * receiver _host_ is heavily congested (or buggy).
1975  *
1976  * To avoid big spurious retransmission bursts due to transient SACK
1977  * scoreboard oddities that look like reneging, we give the receiver a
1978  * little time (max(RTT/2, 10ms)) to send us some more ACKs that will
1979  * restore sanity to the SACK scoreboard. If the apparent reneging
1980  * persists until this RTO then we'll clear the SACK scoreboard.
1981  */
tcp_check_sack_reneging(struct sock * sk,int flag)1982 static bool tcp_check_sack_reneging(struct sock *sk, int flag)
1983 {
1984 	if (flag & FLAG_SACK_RENEGING) {
1985 		struct tcp_sock *tp = tcp_sk(sk);
1986 		unsigned long delay = max(usecs_to_jiffies(tp->srtt_us >> 4),
1987 					  msecs_to_jiffies(10));
1988 
1989 		inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
1990 					  delay, TCP_RTO_MAX);
1991 		return true;
1992 	}
1993 	return false;
1994 }
1995 
tcp_fackets_out(const struct tcp_sock * tp)1996 static inline int tcp_fackets_out(const struct tcp_sock *tp)
1997 {
1998 	return tcp_is_reno(tp) ? tp->sacked_out + 1 : tp->fackets_out;
1999 }
2000 
2001 /* Heurestics to calculate number of duplicate ACKs. There's no dupACKs
2002  * counter when SACK is enabled (without SACK, sacked_out is used for
2003  * that purpose).
2004  *
2005  * Instead, with FACK TCP uses fackets_out that includes both SACKed
2006  * segments up to the highest received SACK block so far and holes in
2007  * between them.
2008  *
2009  * With reordering, holes may still be in flight, so RFC3517 recovery
2010  * uses pure sacked_out (total number of SACKed segments) even though
2011  * it violates the RFC that uses duplicate ACKs, often these are equal
2012  * but when e.g. out-of-window ACKs or packet duplication occurs,
2013  * they differ. Since neither occurs due to loss, TCP should really
2014  * ignore them.
2015  */
tcp_dupack_heuristics(const struct tcp_sock * tp)2016 static inline int tcp_dupack_heuristics(const struct tcp_sock *tp)
2017 {
2018 	return tcp_is_fack(tp) ? tp->fackets_out : tp->sacked_out + 1;
2019 }
2020 
tcp_pause_early_retransmit(struct sock * sk,int flag)2021 static bool tcp_pause_early_retransmit(struct sock *sk, int flag)
2022 {
2023 	struct tcp_sock *tp = tcp_sk(sk);
2024 	unsigned long delay;
2025 
2026 	/* Delay early retransmit and entering fast recovery for
2027 	 * max(RTT/4, 2msec) unless ack has ECE mark, no RTT samples
2028 	 * available, or RTO is scheduled to fire first.
2029 	 */
2030 	if (sysctl_tcp_early_retrans < 2 || sysctl_tcp_early_retrans > 3 ||
2031 	    (flag & FLAG_ECE) || !tp->srtt_us)
2032 		return false;
2033 
2034 	delay = max(usecs_to_jiffies(tp->srtt_us >> 5),
2035 		    msecs_to_jiffies(2));
2036 
2037 	if (!time_after(inet_csk(sk)->icsk_timeout, (jiffies + delay)))
2038 		return false;
2039 
2040 	inet_csk_reset_xmit_timer(sk, ICSK_TIME_EARLY_RETRANS, delay,
2041 				  TCP_RTO_MAX);
2042 	return true;
2043 }
2044 
2045 /* Linux NewReno/SACK/FACK/ECN state machine.
2046  * --------------------------------------
2047  *
2048  * "Open"	Normal state, no dubious events, fast path.
2049  * "Disorder"   In all the respects it is "Open",
2050  *		but requires a bit more attention. It is entered when
2051  *		we see some SACKs or dupacks. It is split of "Open"
2052  *		mainly to move some processing from fast path to slow one.
2053  * "CWR"	CWND was reduced due to some Congestion Notification event.
2054  *		It can be ECN, ICMP source quench, local device congestion.
2055  * "Recovery"	CWND was reduced, we are fast-retransmitting.
2056  * "Loss"	CWND was reduced due to RTO timeout or SACK reneging.
2057  *
2058  * tcp_fastretrans_alert() is entered:
2059  * - each incoming ACK, if state is not "Open"
2060  * - when arrived ACK is unusual, namely:
2061  *	* SACK
2062  *	* Duplicate ACK.
2063  *	* ECN ECE.
2064  *
2065  * Counting packets in flight is pretty simple.
2066  *
2067  *	in_flight = packets_out - left_out + retrans_out
2068  *
2069  *	packets_out is SND.NXT-SND.UNA counted in packets.
2070  *
2071  *	retrans_out is number of retransmitted segments.
2072  *
2073  *	left_out is number of segments left network, but not ACKed yet.
2074  *
2075  *		left_out = sacked_out + lost_out
2076  *
2077  *     sacked_out: Packets, which arrived to receiver out of order
2078  *		   and hence not ACKed. With SACKs this number is simply
2079  *		   amount of SACKed data. Even without SACKs
2080  *		   it is easy to give pretty reliable estimate of this number,
2081  *		   counting duplicate ACKs.
2082  *
2083  *       lost_out: Packets lost by network. TCP has no explicit
2084  *		   "loss notification" feedback from network (for now).
2085  *		   It means that this number can be only _guessed_.
2086  *		   Actually, it is the heuristics to predict lossage that
2087  *		   distinguishes different algorithms.
2088  *
2089  *	F.e. after RTO, when all the queue is considered as lost,
2090  *	lost_out = packets_out and in_flight = retrans_out.
2091  *
2092  *		Essentially, we have now two algorithms counting
2093  *		lost packets.
2094  *
2095  *		FACK: It is the simplest heuristics. As soon as we decided
2096  *		that something is lost, we decide that _all_ not SACKed
2097  *		packets until the most forward SACK are lost. I.e.
2098  *		lost_out = fackets_out - sacked_out and left_out = fackets_out.
2099  *		It is absolutely correct estimate, if network does not reorder
2100  *		packets. And it loses any connection to reality when reordering
2101  *		takes place. We use FACK by default until reordering
2102  *		is suspected on the path to this destination.
2103  *
2104  *		NewReno: when Recovery is entered, we assume that one segment
2105  *		is lost (classic Reno). While we are in Recovery and
2106  *		a partial ACK arrives, we assume that one more packet
2107  *		is lost (NewReno). This heuristics are the same in NewReno
2108  *		and SACK.
2109  *
2110  *  Imagine, that's all! Forget about all this shamanism about CWND inflation
2111  *  deflation etc. CWND is real congestion window, never inflated, changes
2112  *  only according to classic VJ rules.
2113  *
2114  * Really tricky (and requiring careful tuning) part of algorithm
2115  * is hidden in functions tcp_time_to_recover() and tcp_xmit_retransmit_queue().
2116  * The first determines the moment _when_ we should reduce CWND and,
2117  * hence, slow down forward transmission. In fact, it determines the moment
2118  * when we decide that hole is caused by loss, rather than by a reorder.
2119  *
2120  * tcp_xmit_retransmit_queue() decides, _what_ we should retransmit to fill
2121  * holes, caused by lost packets.
2122  *
2123  * And the most logically complicated part of algorithm is undo
2124  * heuristics. We detect false retransmits due to both too early
2125  * fast retransmit (reordering) and underestimated RTO, analyzing
2126  * timestamps and D-SACKs. When we detect that some segments were
2127  * retransmitted by mistake and CWND reduction was wrong, we undo
2128  * window reduction and abort recovery phase. This logic is hidden
2129  * inside several functions named tcp_try_undo_<something>.
2130  */
2131 
2132 /* This function decides, when we should leave Disordered state
2133  * and enter Recovery phase, reducing congestion window.
2134  *
2135  * Main question: may we further continue forward transmission
2136  * with the same cwnd?
2137  */
tcp_time_to_recover(struct sock * sk,int flag)2138 static bool tcp_time_to_recover(struct sock *sk, int flag)
2139 {
2140 	struct tcp_sock *tp = tcp_sk(sk);
2141 	__u32 packets_out;
2142 
2143 	/* Trick#1: The loss is proven. */
2144 	if (tp->lost_out)
2145 		return true;
2146 
2147 	/* Not-A-Trick#2 : Classic rule... */
2148 	if (tcp_dupack_heuristics(tp) > tp->reordering)
2149 		return true;
2150 
2151 	/* Trick#4: It is still not OK... But will it be useful to delay
2152 	 * recovery more?
2153 	 */
2154 	packets_out = tp->packets_out;
2155 	if (packets_out <= tp->reordering &&
2156 	    tp->sacked_out >= max_t(__u32, packets_out/2, sysctl_tcp_reordering) &&
2157 	    !tcp_may_send_now(sk)) {
2158 		/* We have nothing to send. This connection is limited
2159 		 * either by receiver window or by application.
2160 		 */
2161 		return true;
2162 	}
2163 
2164 	/* If a thin stream is detected, retransmit after first
2165 	 * received dupack. Employ only if SACK is supported in order
2166 	 * to avoid possible corner-case series of spurious retransmissions
2167 	 * Use only if there are no unsent data.
2168 	 */
2169 	if ((tp->thin_dupack || sysctl_tcp_thin_dupack) &&
2170 	    tcp_stream_is_thin(tp) && tcp_dupack_heuristics(tp) > 1 &&
2171 	    tcp_is_sack(tp) && !tcp_send_head(sk))
2172 		return true;
2173 
2174 	/* Trick#6: TCP early retransmit, per RFC5827.  To avoid spurious
2175 	 * retransmissions due to small network reorderings, we implement
2176 	 * Mitigation A.3 in the RFC and delay the retransmission for a short
2177 	 * interval if appropriate.
2178 	 */
2179 	if (tp->do_early_retrans && !tp->retrans_out && tp->sacked_out &&
2180 	    (tp->packets_out >= (tp->sacked_out + 1) && tp->packets_out < 4) &&
2181 	    !tcp_may_send_now(sk))
2182 		return !tcp_pause_early_retransmit(sk, flag);
2183 
2184 	return false;
2185 }
2186 
2187 /* Detect loss in event "A" above by marking head of queue up as lost.
2188  * For FACK or non-SACK(Reno) senders, the first "packets" number of segments
2189  * are considered lost. For RFC3517 SACK, a segment is considered lost if it
2190  * has at least tp->reordering SACKed seqments above it; "packets" refers to
2191  * the maximum SACKed segments to pass before reaching this limit.
2192  */
tcp_mark_head_lost(struct sock * sk,int packets,int mark_head)2193 static void tcp_mark_head_lost(struct sock *sk, int packets, int mark_head)
2194 {
2195 	struct tcp_sock *tp = tcp_sk(sk);
2196 	struct sk_buff *skb;
2197 	int cnt, oldcnt, lost;
2198 	unsigned int mss;
2199 	/* Use SACK to deduce losses of new sequences sent during recovery */
2200 	const u32 loss_high = tcp_is_sack(tp) ?  tp->snd_nxt : tp->high_seq;
2201 
2202 	WARN_ON(packets > tp->packets_out);
2203 	if (tp->lost_skb_hint) {
2204 		skb = tp->lost_skb_hint;
2205 		cnt = tp->lost_cnt_hint;
2206 		/* Head already handled? */
2207 		if (mark_head && skb != tcp_write_queue_head(sk))
2208 			return;
2209 	} else {
2210 		skb = tcp_write_queue_head(sk);
2211 		cnt = 0;
2212 	}
2213 
2214 	tcp_for_write_queue_from(skb, sk) {
2215 		if (skb == tcp_send_head(sk))
2216 			break;
2217 		/* TODO: do this better */
2218 		/* this is not the most efficient way to do this... */
2219 		tp->lost_skb_hint = skb;
2220 		tp->lost_cnt_hint = cnt;
2221 
2222 		if (after(TCP_SKB_CB(skb)->end_seq, loss_high))
2223 			break;
2224 
2225 		oldcnt = cnt;
2226 		if (tcp_is_fack(tp) || tcp_is_reno(tp) ||
2227 		    (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED))
2228 			cnt += tcp_skb_pcount(skb);
2229 
2230 		if (cnt > packets) {
2231 			if ((tcp_is_sack(tp) && !tcp_is_fack(tp)) ||
2232 			    (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED) ||
2233 			    (oldcnt >= packets))
2234 				break;
2235 
2236 			mss = tcp_skb_mss(skb);
2237 			/* If needed, chop off the prefix to mark as lost. */
2238 			lost = (packets - oldcnt) * mss;
2239 			if (lost < skb->len &&
2240 			    tcp_fragment(sk, skb, lost, mss, GFP_ATOMIC) < 0)
2241 				break;
2242 			cnt = packets;
2243 		}
2244 
2245 		tcp_skb_mark_lost(tp, skb);
2246 
2247 		if (mark_head)
2248 			break;
2249 	}
2250 	tcp_verify_left_out(tp);
2251 }
2252 
2253 /* Account newly detected lost packet(s) */
2254 
tcp_update_scoreboard(struct sock * sk,int fast_rexmit)2255 static void tcp_update_scoreboard(struct sock *sk, int fast_rexmit)
2256 {
2257 	struct tcp_sock *tp = tcp_sk(sk);
2258 
2259 	if (tcp_is_reno(tp)) {
2260 		tcp_mark_head_lost(sk, 1, 1);
2261 	} else if (tcp_is_fack(tp)) {
2262 		int lost = tp->fackets_out - tp->reordering;
2263 		if (lost <= 0)
2264 			lost = 1;
2265 		tcp_mark_head_lost(sk, lost, 0);
2266 	} else {
2267 		int sacked_upto = tp->sacked_out - tp->reordering;
2268 		if (sacked_upto >= 0)
2269 			tcp_mark_head_lost(sk, sacked_upto, 0);
2270 		else if (fast_rexmit)
2271 			tcp_mark_head_lost(sk, 1, 1);
2272 	}
2273 }
2274 
2275 /* CWND moderation, preventing bursts due to too big ACKs
2276  * in dubious situations.
2277  */
tcp_moderate_cwnd(struct tcp_sock * tp)2278 static inline void tcp_moderate_cwnd(struct tcp_sock *tp)
2279 {
2280 	tp->snd_cwnd = min(tp->snd_cwnd,
2281 			   tcp_packets_in_flight(tp) + tcp_max_burst(tp));
2282 	tp->snd_cwnd_stamp = tcp_time_stamp;
2283 }
2284 
tcp_tsopt_ecr_before(const struct tcp_sock * tp,u32 when)2285 static bool tcp_tsopt_ecr_before(const struct tcp_sock *tp, u32 when)
2286 {
2287 	return tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr &&
2288 	       before(tp->rx_opt.rcv_tsecr, when);
2289 }
2290 
2291 /* skb is spurious retransmitted if the returned timestamp echo
2292  * reply is prior to the skb transmission time
2293  */
tcp_skb_spurious_retrans(const struct tcp_sock * tp,const struct sk_buff * skb)2294 static bool tcp_skb_spurious_retrans(const struct tcp_sock *tp,
2295 				     const struct sk_buff *skb)
2296 {
2297 	return (TCP_SKB_CB(skb)->sacked & TCPCB_RETRANS) &&
2298 	       tcp_tsopt_ecr_before(tp, tcp_skb_timestamp(skb));
2299 }
2300 
2301 /* Nothing was retransmitted or returned timestamp is less
2302  * than timestamp of the first retransmission.
2303  */
tcp_packet_delayed(const struct tcp_sock * tp)2304 static inline bool tcp_packet_delayed(const struct tcp_sock *tp)
2305 {
2306 	return !tp->retrans_stamp ||
2307 	       tcp_tsopt_ecr_before(tp, tp->retrans_stamp);
2308 }
2309 
2310 /* Undo procedures. */
2311 
2312 /* We can clear retrans_stamp when there are no retransmissions in the
2313  * window. It would seem that it is trivially available for us in
2314  * tp->retrans_out, however, that kind of assumptions doesn't consider
2315  * what will happen if errors occur when sending retransmission for the
2316  * second time. ...It could the that such segment has only
2317  * TCPCB_EVER_RETRANS set at the present time. It seems that checking
2318  * the head skb is enough except for some reneging corner cases that
2319  * are not worth the effort.
2320  *
2321  * Main reason for all this complexity is the fact that connection dying
2322  * time now depends on the validity of the retrans_stamp, in particular,
2323  * that successive retransmissions of a segment must not advance
2324  * retrans_stamp under any conditions.
2325  */
tcp_any_retrans_done(const struct sock * sk)2326 static bool tcp_any_retrans_done(const struct sock *sk)
2327 {
2328 	const struct tcp_sock *tp = tcp_sk(sk);
2329 	struct sk_buff *skb;
2330 
2331 	if (tp->retrans_out)
2332 		return true;
2333 
2334 	skb = tcp_write_queue_head(sk);
2335 	if (unlikely(skb && TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS))
2336 		return true;
2337 
2338 	return false;
2339 }
2340 
2341 #if FASTRETRANS_DEBUG > 1
DBGUNDO(struct sock * sk,const char * msg)2342 static void DBGUNDO(struct sock *sk, const char *msg)
2343 {
2344 	struct tcp_sock *tp = tcp_sk(sk);
2345 	struct inet_sock *inet = inet_sk(sk);
2346 
2347 	if (sk->sk_family == AF_INET) {
2348 		pr_debug("Undo %s %pI4/%u c%u l%u ss%u/%u p%u\n",
2349 			 msg,
2350 			 &inet->inet_daddr, ntohs(inet->inet_dport),
2351 			 tp->snd_cwnd, tcp_left_out(tp),
2352 			 tp->snd_ssthresh, tp->prior_ssthresh,
2353 			 tp->packets_out);
2354 	}
2355 #if IS_ENABLED(CONFIG_IPV6)
2356 	else if (sk->sk_family == AF_INET6) {
2357 		pr_debug("Undo %s %pI6/%u c%u l%u ss%u/%u p%u\n",
2358 			 msg,
2359 			 &sk->sk_v6_daddr, ntohs(inet->inet_dport),
2360 			 tp->snd_cwnd, tcp_left_out(tp),
2361 			 tp->snd_ssthresh, tp->prior_ssthresh,
2362 			 tp->packets_out);
2363 	}
2364 #endif
2365 }
2366 #else
2367 #define DBGUNDO(x...) do { } while (0)
2368 #endif
2369 
tcp_undo_cwnd_reduction(struct sock * sk,bool unmark_loss)2370 static void tcp_undo_cwnd_reduction(struct sock *sk, bool unmark_loss)
2371 {
2372 	struct tcp_sock *tp = tcp_sk(sk);
2373 
2374 	if (unmark_loss) {
2375 		struct sk_buff *skb;
2376 
2377 		tcp_for_write_queue(skb, sk) {
2378 			if (skb == tcp_send_head(sk))
2379 				break;
2380 			TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST;
2381 		}
2382 		tp->lost_out = 0;
2383 		tcp_clear_all_retrans_hints(tp);
2384 	}
2385 
2386 	if (tp->prior_ssthresh) {
2387 		const struct inet_connection_sock *icsk = inet_csk(sk);
2388 
2389 		if (icsk->icsk_ca_ops->undo_cwnd)
2390 			tp->snd_cwnd = icsk->icsk_ca_ops->undo_cwnd(sk);
2391 		else
2392 			tp->snd_cwnd = max(tp->snd_cwnd, tp->snd_ssthresh << 1);
2393 
2394 		if (tp->prior_ssthresh > tp->snd_ssthresh) {
2395 			tp->snd_ssthresh = tp->prior_ssthresh;
2396 			tcp_ecn_withdraw_cwr(tp);
2397 		}
2398 	} else {
2399 		tp->snd_cwnd = max(tp->snd_cwnd, tp->snd_ssthresh);
2400 	}
2401 	tp->snd_cwnd_stamp = tcp_time_stamp;
2402 	tp->undo_marker = 0;
2403 }
2404 
tcp_may_undo(const struct tcp_sock * tp)2405 static inline bool tcp_may_undo(const struct tcp_sock *tp)
2406 {
2407 	return tp->undo_marker && (!tp->undo_retrans || tcp_packet_delayed(tp));
2408 }
2409 
2410 /* People celebrate: "We love our President!" */
tcp_try_undo_recovery(struct sock * sk)2411 static bool tcp_try_undo_recovery(struct sock *sk)
2412 {
2413 	struct tcp_sock *tp = tcp_sk(sk);
2414 
2415 	if (tcp_may_undo(tp)) {
2416 		int mib_idx;
2417 
2418 		/* Happy end! We did not retransmit anything
2419 		 * or our original transmission succeeded.
2420 		 */
2421 		DBGUNDO(sk, inet_csk(sk)->icsk_ca_state == TCP_CA_Loss ? "loss" : "retrans");
2422 		tcp_undo_cwnd_reduction(sk, false);
2423 		if (inet_csk(sk)->icsk_ca_state == TCP_CA_Loss)
2424 			mib_idx = LINUX_MIB_TCPLOSSUNDO;
2425 		else
2426 			mib_idx = LINUX_MIB_TCPFULLUNDO;
2427 
2428 		NET_INC_STATS_BH(sock_net(sk), mib_idx);
2429 	}
2430 	if (tp->snd_una == tp->high_seq && tcp_is_reno(tp)) {
2431 		/* Hold old state until something *above* high_seq
2432 		 * is ACKed. For Reno it is MUST to prevent false
2433 		 * fast retransmits (RFC2582). SACK TCP is safe. */
2434 		tcp_moderate_cwnd(tp);
2435 		if (!tcp_any_retrans_done(sk))
2436 			tp->retrans_stamp = 0;
2437 		return true;
2438 	}
2439 	tcp_set_ca_state(sk, TCP_CA_Open);
2440 	return false;
2441 }
2442 
2443 /* Try to undo cwnd reduction, because D-SACKs acked all retransmitted data */
tcp_try_undo_dsack(struct sock * sk)2444 static bool tcp_try_undo_dsack(struct sock *sk)
2445 {
2446 	struct tcp_sock *tp = tcp_sk(sk);
2447 
2448 	if (tp->undo_marker && !tp->undo_retrans) {
2449 		DBGUNDO(sk, "D-SACK");
2450 		tcp_undo_cwnd_reduction(sk, false);
2451 		NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPDSACKUNDO);
2452 		return true;
2453 	}
2454 	return false;
2455 }
2456 
2457 /* Undo during loss recovery after partial ACK or using F-RTO. */
tcp_try_undo_loss(struct sock * sk,bool frto_undo)2458 static bool tcp_try_undo_loss(struct sock *sk, bool frto_undo)
2459 {
2460 	struct tcp_sock *tp = tcp_sk(sk);
2461 
2462 	if (frto_undo || tcp_may_undo(tp)) {
2463 		tcp_undo_cwnd_reduction(sk, true);
2464 
2465 		DBGUNDO(sk, "partial loss");
2466 		NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPLOSSUNDO);
2467 		if (frto_undo)
2468 			NET_INC_STATS_BH(sock_net(sk),
2469 					 LINUX_MIB_TCPSPURIOUSRTOS);
2470 		inet_csk(sk)->icsk_retransmits = 0;
2471 		if (frto_undo || tcp_is_sack(tp))
2472 			tcp_set_ca_state(sk, TCP_CA_Open);
2473 		return true;
2474 	}
2475 	return false;
2476 }
2477 
2478 /* The cwnd reduction in CWR and Recovery uses the PRR algorithm in RFC 6937.
2479  * It computes the number of packets to send (sndcnt) based on packets newly
2480  * delivered:
2481  *   1) If the packets in flight is larger than ssthresh, PRR spreads the
2482  *	cwnd reductions across a full RTT.
2483  *   2) Otherwise PRR uses packet conservation to send as much as delivered.
2484  *      But when the retransmits are acked without further losses, PRR
2485  *      slow starts cwnd up to ssthresh to speed up the recovery.
2486  */
tcp_init_cwnd_reduction(struct sock * sk)2487 static void tcp_init_cwnd_reduction(struct sock *sk)
2488 {
2489 	struct tcp_sock *tp = tcp_sk(sk);
2490 
2491 	tp->high_seq = tp->snd_nxt;
2492 	tp->tlp_high_seq = 0;
2493 	tp->snd_cwnd_cnt = 0;
2494 	tp->prior_cwnd = tp->snd_cwnd;
2495 	tp->prr_delivered = 0;
2496 	tp->prr_out = 0;
2497 	tp->snd_ssthresh = inet_csk(sk)->icsk_ca_ops->ssthresh(sk);
2498 	tcp_ecn_queue_cwr(tp);
2499 }
2500 
tcp_cwnd_reduction(struct sock * sk,const int prior_unsacked,int fast_rexmit,int flag)2501 static void tcp_cwnd_reduction(struct sock *sk, const int prior_unsacked,
2502 			       int fast_rexmit, int flag)
2503 {
2504 	struct tcp_sock *tp = tcp_sk(sk);
2505 	int sndcnt = 0;
2506 	int delta = tp->snd_ssthresh - tcp_packets_in_flight(tp);
2507 	int newly_acked_sacked = prior_unsacked -
2508 				 (tp->packets_out - tp->sacked_out);
2509 
2510 	if (newly_acked_sacked <= 0 || WARN_ON_ONCE(!tp->prior_cwnd))
2511 		return;
2512 
2513 	tp->prr_delivered += newly_acked_sacked;
2514 	if (delta < 0) {
2515 		u64 dividend = (u64)tp->snd_ssthresh * tp->prr_delivered +
2516 			       tp->prior_cwnd - 1;
2517 		sndcnt = div_u64(dividend, tp->prior_cwnd) - tp->prr_out;
2518 	} else if ((flag & FLAG_RETRANS_DATA_ACKED) &&
2519 		   !(flag & FLAG_LOST_RETRANS)) {
2520 		sndcnt = min_t(int, delta,
2521 			       max_t(int, tp->prr_delivered - tp->prr_out,
2522 				     newly_acked_sacked) + 1);
2523 	} else {
2524 		sndcnt = min(delta, newly_acked_sacked);
2525 	}
2526 	sndcnt = max(sndcnt, (fast_rexmit ? 1 : 0));
2527 	tp->snd_cwnd = tcp_packets_in_flight(tp) + sndcnt;
2528 }
2529 
tcp_end_cwnd_reduction(struct sock * sk)2530 static inline void tcp_end_cwnd_reduction(struct sock *sk)
2531 {
2532 	struct tcp_sock *tp = tcp_sk(sk);
2533 
2534 	/* Reset cwnd to ssthresh in CWR or Recovery (unless it's undone) */
2535 	if (tp->snd_ssthresh < TCP_INFINITE_SSTHRESH &&
2536 	    (inet_csk(sk)->icsk_ca_state == TCP_CA_CWR || tp->undo_marker)) {
2537 		tp->snd_cwnd = tp->snd_ssthresh;
2538 		tp->snd_cwnd_stamp = tcp_time_stamp;
2539 	}
2540 	tcp_ca_event(sk, CA_EVENT_COMPLETE_CWR);
2541 }
2542 
2543 /* Enter CWR state. Disable cwnd undo since congestion is proven with ECN */
tcp_enter_cwr(struct sock * sk)2544 void tcp_enter_cwr(struct sock *sk)
2545 {
2546 	struct tcp_sock *tp = tcp_sk(sk);
2547 
2548 	tp->prior_ssthresh = 0;
2549 	if (inet_csk(sk)->icsk_ca_state < TCP_CA_CWR) {
2550 		tp->undo_marker = 0;
2551 		tcp_init_cwnd_reduction(sk);
2552 		tcp_set_ca_state(sk, TCP_CA_CWR);
2553 	}
2554 }
2555 EXPORT_SYMBOL(tcp_enter_cwr);
2556 
tcp_try_keep_open(struct sock * sk)2557 static void tcp_try_keep_open(struct sock *sk)
2558 {
2559 	struct tcp_sock *tp = tcp_sk(sk);
2560 	int state = TCP_CA_Open;
2561 
2562 	if (tcp_left_out(tp) || tcp_any_retrans_done(sk))
2563 		state = TCP_CA_Disorder;
2564 
2565 	if (inet_csk(sk)->icsk_ca_state != state) {
2566 		tcp_set_ca_state(sk, state);
2567 		tp->high_seq = tp->snd_nxt;
2568 	}
2569 }
2570 
tcp_try_to_open(struct sock * sk,int flag,const int prior_unsacked)2571 static void tcp_try_to_open(struct sock *sk, int flag, const int prior_unsacked)
2572 {
2573 	struct tcp_sock *tp = tcp_sk(sk);
2574 
2575 	tcp_verify_left_out(tp);
2576 
2577 	if (!tcp_any_retrans_done(sk))
2578 		tp->retrans_stamp = 0;
2579 
2580 	if (flag & FLAG_ECE)
2581 		tcp_enter_cwr(sk);
2582 
2583 	if (inet_csk(sk)->icsk_ca_state != TCP_CA_CWR) {
2584 		tcp_try_keep_open(sk);
2585 	} else {
2586 		tcp_cwnd_reduction(sk, prior_unsacked, 0, flag);
2587 	}
2588 }
2589 
tcp_mtup_probe_failed(struct sock * sk)2590 static void tcp_mtup_probe_failed(struct sock *sk)
2591 {
2592 	struct inet_connection_sock *icsk = inet_csk(sk);
2593 
2594 	icsk->icsk_mtup.search_high = icsk->icsk_mtup.probe_size - 1;
2595 	icsk->icsk_mtup.probe_size = 0;
2596 	NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPMTUPFAIL);
2597 }
2598 
tcp_mtup_probe_success(struct sock * sk)2599 static void tcp_mtup_probe_success(struct sock *sk)
2600 {
2601 	struct tcp_sock *tp = tcp_sk(sk);
2602 	struct inet_connection_sock *icsk = inet_csk(sk);
2603 
2604 	/* FIXME: breaks with very large cwnd */
2605 	tp->prior_ssthresh = tcp_current_ssthresh(sk);
2606 	tp->snd_cwnd = tp->snd_cwnd *
2607 		       tcp_mss_to_mtu(sk, tp->mss_cache) /
2608 		       icsk->icsk_mtup.probe_size;
2609 	tp->snd_cwnd_cnt = 0;
2610 	tp->snd_cwnd_stamp = tcp_time_stamp;
2611 	tp->snd_ssthresh = tcp_current_ssthresh(sk);
2612 
2613 	icsk->icsk_mtup.search_low = icsk->icsk_mtup.probe_size;
2614 	icsk->icsk_mtup.probe_size = 0;
2615 	tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
2616 	NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPMTUPSUCCESS);
2617 }
2618 
2619 /* Do a simple retransmit without using the backoff mechanisms in
2620  * tcp_timer. This is used for path mtu discovery.
2621  * The socket is already locked here.
2622  */
tcp_simple_retransmit(struct sock * sk)2623 void tcp_simple_retransmit(struct sock *sk)
2624 {
2625 	const struct inet_connection_sock *icsk = inet_csk(sk);
2626 	struct tcp_sock *tp = tcp_sk(sk);
2627 	struct sk_buff *skb;
2628 	unsigned int mss = tcp_current_mss(sk);
2629 	u32 prior_lost = tp->lost_out;
2630 
2631 	tcp_for_write_queue(skb, sk) {
2632 		if (skb == tcp_send_head(sk))
2633 			break;
2634 		if (tcp_skb_seglen(skb) > mss &&
2635 		    !(TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)) {
2636 			if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS) {
2637 				TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS;
2638 				tp->retrans_out -= tcp_skb_pcount(skb);
2639 			}
2640 			tcp_skb_mark_lost_uncond_verify(tp, skb);
2641 		}
2642 	}
2643 
2644 	tcp_clear_retrans_hints_partial(tp);
2645 
2646 	if (prior_lost == tp->lost_out)
2647 		return;
2648 
2649 	if (tcp_is_reno(tp))
2650 		tcp_limit_reno_sacked(tp);
2651 
2652 	tcp_verify_left_out(tp);
2653 
2654 	/* Don't muck with the congestion window here.
2655 	 * Reason is that we do not increase amount of _data_
2656 	 * in network, but units changed and effective
2657 	 * cwnd/ssthresh really reduced now.
2658 	 */
2659 	if (icsk->icsk_ca_state != TCP_CA_Loss) {
2660 		tp->high_seq = tp->snd_nxt;
2661 		tp->snd_ssthresh = tcp_current_ssthresh(sk);
2662 		tp->prior_ssthresh = 0;
2663 		tp->undo_marker = 0;
2664 		tcp_set_ca_state(sk, TCP_CA_Loss);
2665 	}
2666 	tcp_xmit_retransmit_queue(sk);
2667 }
2668 EXPORT_SYMBOL(tcp_simple_retransmit);
2669 
tcp_enter_recovery(struct sock * sk,bool ece_ack)2670 static void tcp_enter_recovery(struct sock *sk, bool ece_ack)
2671 {
2672 	struct tcp_sock *tp = tcp_sk(sk);
2673 	int mib_idx;
2674 
2675 	if (tcp_is_reno(tp))
2676 		mib_idx = LINUX_MIB_TCPRENORECOVERY;
2677 	else
2678 		mib_idx = LINUX_MIB_TCPSACKRECOVERY;
2679 
2680 	NET_INC_STATS_BH(sock_net(sk), mib_idx);
2681 
2682 	tp->prior_ssthresh = 0;
2683 	tcp_init_undo(tp);
2684 
2685 	if (!tcp_in_cwnd_reduction(sk)) {
2686 		if (!ece_ack)
2687 			tp->prior_ssthresh = tcp_current_ssthresh(sk);
2688 		tcp_init_cwnd_reduction(sk);
2689 	}
2690 	tcp_set_ca_state(sk, TCP_CA_Recovery);
2691 }
2692 
2693 /* Process an ACK in CA_Loss state. Move to CA_Open if lost data are
2694  * recovered or spurious. Otherwise retransmits more on partial ACKs.
2695  */
tcp_process_loss(struct sock * sk,int flag,bool is_dupack)2696 static void tcp_process_loss(struct sock *sk, int flag, bool is_dupack)
2697 {
2698 	struct tcp_sock *tp = tcp_sk(sk);
2699 	bool recovered = !before(tp->snd_una, tp->high_seq);
2700 
2701 	if ((flag & FLAG_SND_UNA_ADVANCED) &&
2702 	    tcp_try_undo_loss(sk, false))
2703 		return;
2704 
2705 	if (tp->frto) { /* F-RTO RFC5682 sec 3.1 (sack enhanced version). */
2706 		/* Step 3.b. A timeout is spurious if not all data are
2707 		 * lost, i.e., never-retransmitted data are (s)acked.
2708 		 */
2709 		if ((flag & FLAG_ORIG_SACK_ACKED) &&
2710 		    tcp_try_undo_loss(sk, true))
2711 			return;
2712 
2713 		if (after(tp->snd_nxt, tp->high_seq)) {
2714 			if (flag & FLAG_DATA_SACKED || is_dupack)
2715 				tp->frto = 0; /* Step 3.a. loss was real */
2716 		} else if (flag & FLAG_SND_UNA_ADVANCED && !recovered) {
2717 			tp->high_seq = tp->snd_nxt;
2718 			__tcp_push_pending_frames(sk, tcp_current_mss(sk),
2719 						  TCP_NAGLE_OFF);
2720 			if (after(tp->snd_nxt, tp->high_seq))
2721 				return; /* Step 2.b */
2722 			tp->frto = 0;
2723 		}
2724 	}
2725 
2726 	if (recovered) {
2727 		/* F-RTO RFC5682 sec 3.1 step 2.a and 1st part of step 3.a */
2728 		tcp_try_undo_recovery(sk);
2729 		return;
2730 	}
2731 	if (tcp_is_reno(tp)) {
2732 		/* A Reno DUPACK means new data in F-RTO step 2.b above are
2733 		 * delivered. Lower inflight to clock out (re)tranmissions.
2734 		 */
2735 		if (after(tp->snd_nxt, tp->high_seq) && is_dupack)
2736 			tcp_add_reno_sack(sk);
2737 		else if (flag & FLAG_SND_UNA_ADVANCED)
2738 			tcp_reset_reno_sack(tp);
2739 	}
2740 	tcp_xmit_retransmit_queue(sk);
2741 }
2742 
2743 /* Undo during fast recovery after partial ACK. */
tcp_try_undo_partial(struct sock * sk,const int acked,const int prior_unsacked,int flag)2744 static bool tcp_try_undo_partial(struct sock *sk, const int acked,
2745 				 const int prior_unsacked, int flag)
2746 {
2747 	struct tcp_sock *tp = tcp_sk(sk);
2748 
2749 	if (tp->undo_marker && tcp_packet_delayed(tp)) {
2750 		/* Plain luck! Hole if filled with delayed
2751 		 * packet, rather than with a retransmit.
2752 		 */
2753 		tcp_update_reordering(sk, tcp_fackets_out(tp) + acked, 1);
2754 
2755 		/* We are getting evidence that the reordering degree is higher
2756 		 * than we realized. If there are no retransmits out then we
2757 		 * can undo. Otherwise we clock out new packets but do not
2758 		 * mark more packets lost or retransmit more.
2759 		 */
2760 		if (tp->retrans_out) {
2761 			tcp_cwnd_reduction(sk, prior_unsacked, 0, flag);
2762 			return true;
2763 		}
2764 
2765 		if (!tcp_any_retrans_done(sk))
2766 			tp->retrans_stamp = 0;
2767 
2768 		DBGUNDO(sk, "partial recovery");
2769 		tcp_undo_cwnd_reduction(sk, true);
2770 		NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPPARTIALUNDO);
2771 		tcp_try_keep_open(sk);
2772 		return true;
2773 	}
2774 	return false;
2775 }
2776 
2777 /* Process an event, which can update packets-in-flight not trivially.
2778  * Main goal of this function is to calculate new estimate for left_out,
2779  * taking into account both packets sitting in receiver's buffer and
2780  * packets lost by network.
2781  *
2782  * Besides that it does CWND reduction, when packet loss is detected
2783  * and changes state of machine.
2784  *
2785  * It does _not_ decide what to send, it is made in function
2786  * tcp_xmit_retransmit_queue().
2787  */
tcp_fastretrans_alert(struct sock * sk,const int acked,const int prior_unsacked,bool is_dupack,int flag)2788 static void tcp_fastretrans_alert(struct sock *sk, const int acked,
2789 				  const int prior_unsacked,
2790 				  bool is_dupack, int flag)
2791 {
2792 	struct inet_connection_sock *icsk = inet_csk(sk);
2793 	struct tcp_sock *tp = tcp_sk(sk);
2794 	bool do_lost = is_dupack || ((flag & FLAG_DATA_SACKED) &&
2795 				    (tcp_fackets_out(tp) > tp->reordering));
2796 	int fast_rexmit = 0;
2797 
2798 	if (WARN_ON(!tp->packets_out && tp->sacked_out))
2799 		tp->sacked_out = 0;
2800 	if (WARN_ON(!tp->sacked_out && tp->fackets_out))
2801 		tp->fackets_out = 0;
2802 
2803 	/* Now state machine starts.
2804 	 * A. ECE, hence prohibit cwnd undoing, the reduction is required. */
2805 	if (flag & FLAG_ECE)
2806 		tp->prior_ssthresh = 0;
2807 
2808 	/* B. In all the states check for reneging SACKs. */
2809 	if (tcp_check_sack_reneging(sk, flag))
2810 		return;
2811 
2812 	/* C. Check consistency of the current state. */
2813 	tcp_verify_left_out(tp);
2814 
2815 	/* D. Check state exit conditions. State can be terminated
2816 	 *    when high_seq is ACKed. */
2817 	if (icsk->icsk_ca_state == TCP_CA_Open) {
2818 		WARN_ON(tp->retrans_out != 0);
2819 		tp->retrans_stamp = 0;
2820 	} else if (!before(tp->snd_una, tp->high_seq)) {
2821 		switch (icsk->icsk_ca_state) {
2822 		case TCP_CA_CWR:
2823 			/* CWR is to be held something *above* high_seq
2824 			 * is ACKed for CWR bit to reach receiver. */
2825 			if (tp->snd_una != tp->high_seq) {
2826 				tcp_end_cwnd_reduction(sk);
2827 				tcp_set_ca_state(sk, TCP_CA_Open);
2828 			}
2829 			break;
2830 
2831 		case TCP_CA_Recovery:
2832 			if (tcp_is_reno(tp))
2833 				tcp_reset_reno_sack(tp);
2834 			if (tcp_try_undo_recovery(sk))
2835 				return;
2836 			tcp_end_cwnd_reduction(sk);
2837 			break;
2838 		}
2839 	}
2840 
2841 	/* Use RACK to detect loss */
2842 	if (sysctl_tcp_recovery & TCP_RACK_LOST_RETRANS &&
2843 	    tcp_rack_mark_lost(sk))
2844 		flag |= FLAG_LOST_RETRANS;
2845 
2846 	/* E. Process state. */
2847 	switch (icsk->icsk_ca_state) {
2848 	case TCP_CA_Recovery:
2849 		if (!(flag & FLAG_SND_UNA_ADVANCED)) {
2850 			if (tcp_is_reno(tp) && is_dupack)
2851 				tcp_add_reno_sack(sk);
2852 		} else {
2853 			if (tcp_try_undo_partial(sk, acked, prior_unsacked, flag))
2854 				return;
2855 			/* Partial ACK arrived. Force fast retransmit. */
2856 			do_lost = tcp_is_reno(tp) ||
2857 				  tcp_fackets_out(tp) > tp->reordering;
2858 		}
2859 		if (tcp_try_undo_dsack(sk)) {
2860 			tcp_try_keep_open(sk);
2861 			return;
2862 		}
2863 		break;
2864 	case TCP_CA_Loss:
2865 		tcp_process_loss(sk, flag, is_dupack);
2866 		if (icsk->icsk_ca_state != TCP_CA_Open &&
2867 		    !(flag & FLAG_LOST_RETRANS))
2868 			return;
2869 		/* Change state if cwnd is undone or retransmits are lost */
2870 	default:
2871 		if (tcp_is_reno(tp)) {
2872 			if (flag & FLAG_SND_UNA_ADVANCED)
2873 				tcp_reset_reno_sack(tp);
2874 			if (is_dupack)
2875 				tcp_add_reno_sack(sk);
2876 		}
2877 
2878 		if (icsk->icsk_ca_state <= TCP_CA_Disorder)
2879 			tcp_try_undo_dsack(sk);
2880 
2881 		if (!tcp_time_to_recover(sk, flag)) {
2882 			tcp_try_to_open(sk, flag, prior_unsacked);
2883 			return;
2884 		}
2885 
2886 		/* MTU probe failure: don't reduce cwnd */
2887 		if (icsk->icsk_ca_state < TCP_CA_CWR &&
2888 		    icsk->icsk_mtup.probe_size &&
2889 		    tp->snd_una == tp->mtu_probe.probe_seq_start) {
2890 			tcp_mtup_probe_failed(sk);
2891 			/* Restores the reduction we did in tcp_mtup_probe() */
2892 			tp->snd_cwnd++;
2893 			tcp_simple_retransmit(sk);
2894 			return;
2895 		}
2896 
2897 		/* Otherwise enter Recovery state */
2898 		tcp_enter_recovery(sk, (flag & FLAG_ECE));
2899 		fast_rexmit = 1;
2900 	}
2901 
2902 	if (do_lost)
2903 		tcp_update_scoreboard(sk, fast_rexmit);
2904 	tcp_cwnd_reduction(sk, prior_unsacked, fast_rexmit, flag);
2905 	tcp_xmit_retransmit_queue(sk);
2906 }
2907 
2908 /* Kathleen Nichols' algorithm for tracking the minimum value of
2909  * a data stream over some fixed time interval. (E.g., the minimum
2910  * RTT over the past five minutes.) It uses constant space and constant
2911  * time per update yet almost always delivers the same minimum as an
2912  * implementation that has to keep all the data in the window.
2913  *
2914  * The algorithm keeps track of the best, 2nd best & 3rd best min
2915  * values, maintaining an invariant that the measurement time of the
2916  * n'th best >= n-1'th best. It also makes sure that the three values
2917  * are widely separated in the time window since that bounds the worse
2918  * case error when that data is monotonically increasing over the window.
2919  *
2920  * Upon getting a new min, we can forget everything earlier because it
2921  * has no value - the new min is <= everything else in the window by
2922  * definition and it's the most recent. So we restart fresh on every new min
2923  * and overwrites 2nd & 3rd choices. The same property holds for 2nd & 3rd
2924  * best.
2925  */
tcp_update_rtt_min(struct sock * sk,u32 rtt_us)2926 static void tcp_update_rtt_min(struct sock *sk, u32 rtt_us)
2927 {
2928 	const u32 now = tcp_time_stamp, wlen = sysctl_tcp_min_rtt_wlen * HZ;
2929 	struct rtt_meas *m = tcp_sk(sk)->rtt_min;
2930 	struct rtt_meas rttm = {
2931 		.rtt = likely(rtt_us) ? rtt_us : jiffies_to_usecs(1),
2932 		.ts = now,
2933 	};
2934 	u32 elapsed;
2935 
2936 	/* Check if the new measurement updates the 1st, 2nd, or 3rd choices */
2937 	if (unlikely(rttm.rtt <= m[0].rtt))
2938 		m[0] = m[1] = m[2] = rttm;
2939 	else if (rttm.rtt <= m[1].rtt)
2940 		m[1] = m[2] = rttm;
2941 	else if (rttm.rtt <= m[2].rtt)
2942 		m[2] = rttm;
2943 
2944 	elapsed = now - m[0].ts;
2945 	if (unlikely(elapsed > wlen)) {
2946 		/* Passed entire window without a new min so make 2nd choice
2947 		 * the new min & 3rd choice the new 2nd. So forth and so on.
2948 		 */
2949 		m[0] = m[1];
2950 		m[1] = m[2];
2951 		m[2] = rttm;
2952 		if (now - m[0].ts > wlen) {
2953 			m[0] = m[1];
2954 			m[1] = rttm;
2955 			if (now - m[0].ts > wlen)
2956 				m[0] = rttm;
2957 		}
2958 	} else if (m[1].ts == m[0].ts && elapsed > wlen / 4) {
2959 		/* Passed a quarter of the window without a new min so
2960 		 * take 2nd choice from the 2nd quarter of the window.
2961 		 */
2962 		m[2] = m[1] = rttm;
2963 	} else if (m[2].ts == m[1].ts && elapsed > wlen / 2) {
2964 		/* Passed half the window without a new min so take the 3rd
2965 		 * choice from the last half of the window.
2966 		 */
2967 		m[2] = rttm;
2968 	}
2969 }
2970 
tcp_ack_update_rtt(struct sock * sk,const int flag,long seq_rtt_us,long sack_rtt_us,long ca_rtt_us)2971 static inline bool tcp_ack_update_rtt(struct sock *sk, const int flag,
2972 				      long seq_rtt_us, long sack_rtt_us,
2973 				      long ca_rtt_us)
2974 {
2975 	const struct tcp_sock *tp = tcp_sk(sk);
2976 
2977 	/* Prefer RTT measured from ACK's timing to TS-ECR. This is because
2978 	 * broken middle-boxes or peers may corrupt TS-ECR fields. But
2979 	 * Karn's algorithm forbids taking RTT if some retransmitted data
2980 	 * is acked (RFC6298).
2981 	 */
2982 	if (seq_rtt_us < 0)
2983 		seq_rtt_us = sack_rtt_us;
2984 
2985 	/* RTTM Rule: A TSecr value received in a segment is used to
2986 	 * update the averaged RTT measurement only if the segment
2987 	 * acknowledges some new data, i.e., only if it advances the
2988 	 * left edge of the send window.
2989 	 * See draft-ietf-tcplw-high-performance-00, section 3.3.
2990 	 */
2991 	if (seq_rtt_us < 0 && tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr &&
2992 	    flag & FLAG_ACKED)
2993 		seq_rtt_us = ca_rtt_us = jiffies_to_usecs(tcp_time_stamp -
2994 							  tp->rx_opt.rcv_tsecr);
2995 	if (seq_rtt_us < 0)
2996 		return false;
2997 
2998 	/* ca_rtt_us >= 0 is counting on the invariant that ca_rtt_us is
2999 	 * always taken together with ACK, SACK, or TS-opts. Any negative
3000 	 * values will be skipped with the seq_rtt_us < 0 check above.
3001 	 */
3002 	tcp_update_rtt_min(sk, ca_rtt_us);
3003 	tcp_rtt_estimator(sk, seq_rtt_us);
3004 	tcp_set_rto(sk);
3005 
3006 	/* RFC6298: only reset backoff on valid RTT measurement. */
3007 	inet_csk(sk)->icsk_backoff = 0;
3008 	return true;
3009 }
3010 
3011 /* Compute time elapsed between (last) SYNACK and the ACK completing 3WHS. */
tcp_synack_rtt_meas(struct sock * sk,struct request_sock * req)3012 void tcp_synack_rtt_meas(struct sock *sk, struct request_sock *req)
3013 {
3014 	long rtt_us = -1L;
3015 
3016 	if (req && !req->num_retrans && tcp_rsk(req)->snt_synack.v64) {
3017 		struct skb_mstamp now;
3018 
3019 		skb_mstamp_get(&now);
3020 		rtt_us = skb_mstamp_us_delta(&now, &tcp_rsk(req)->snt_synack);
3021 	}
3022 
3023 	tcp_ack_update_rtt(sk, FLAG_SYN_ACKED, rtt_us, -1L, rtt_us);
3024 }
3025 
3026 
tcp_cong_avoid(struct sock * sk,u32 ack,u32 acked)3027 static void tcp_cong_avoid(struct sock *sk, u32 ack, u32 acked)
3028 {
3029 	const struct inet_connection_sock *icsk = inet_csk(sk);
3030 
3031 	icsk->icsk_ca_ops->cong_avoid(sk, ack, acked);
3032 	tcp_sk(sk)->snd_cwnd_stamp = tcp_time_stamp;
3033 }
3034 
3035 /* Restart timer after forward progress on connection.
3036  * RFC2988 recommends to restart timer to now+rto.
3037  */
tcp_rearm_rto(struct sock * sk)3038 void tcp_rearm_rto(struct sock *sk)
3039 {
3040 	const struct inet_connection_sock *icsk = inet_csk(sk);
3041 	struct tcp_sock *tp = tcp_sk(sk);
3042 
3043 	/* If the retrans timer is currently being used by Fast Open
3044 	 * for SYN-ACK retrans purpose, stay put.
3045 	 */
3046 	if (tp->fastopen_rsk)
3047 		return;
3048 
3049 	if (!tp->packets_out) {
3050 		inet_csk_clear_xmit_timer(sk, ICSK_TIME_RETRANS);
3051 	} else {
3052 		u32 rto = inet_csk(sk)->icsk_rto;
3053 		/* Offset the time elapsed after installing regular RTO */
3054 		if (icsk->icsk_pending == ICSK_TIME_EARLY_RETRANS ||
3055 		    icsk->icsk_pending == ICSK_TIME_LOSS_PROBE) {
3056 			struct sk_buff *skb = tcp_write_queue_head(sk);
3057 			const u32 rto_time_stamp =
3058 				tcp_skb_timestamp(skb) + rto;
3059 			s32 delta = (s32)(rto_time_stamp - tcp_time_stamp);
3060 			/* delta may not be positive if the socket is locked
3061 			 * when the retrans timer fires and is rescheduled.
3062 			 */
3063 			rto = max(delta, 1);
3064 		}
3065 		inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS, rto,
3066 					  TCP_RTO_MAX);
3067 	}
3068 }
3069 
3070 /* This function is called when the delayed ER timer fires. TCP enters
3071  * fast recovery and performs fast-retransmit.
3072  */
tcp_resume_early_retransmit(struct sock * sk)3073 void tcp_resume_early_retransmit(struct sock *sk)
3074 {
3075 	struct tcp_sock *tp = tcp_sk(sk);
3076 
3077 	tcp_rearm_rto(sk);
3078 
3079 	/* Stop if ER is disabled after the delayed ER timer is scheduled */
3080 	if (!tp->do_early_retrans)
3081 		return;
3082 
3083 	tcp_enter_recovery(sk, false);
3084 	tcp_update_scoreboard(sk, 1);
3085 	tcp_xmit_retransmit_queue(sk);
3086 }
3087 
3088 /* If we get here, the whole TSO packet has not been acked. */
tcp_tso_acked(struct sock * sk,struct sk_buff * skb)3089 static u32 tcp_tso_acked(struct sock *sk, struct sk_buff *skb)
3090 {
3091 	struct tcp_sock *tp = tcp_sk(sk);
3092 	u32 packets_acked;
3093 
3094 	BUG_ON(!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una));
3095 
3096 	packets_acked = tcp_skb_pcount(skb);
3097 	if (tcp_trim_head(sk, skb, tp->snd_una - TCP_SKB_CB(skb)->seq))
3098 		return 0;
3099 	packets_acked -= tcp_skb_pcount(skb);
3100 
3101 	if (packets_acked) {
3102 		BUG_ON(tcp_skb_pcount(skb) == 0);
3103 		BUG_ON(!before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq));
3104 	}
3105 
3106 	return packets_acked;
3107 }
3108 
tcp_ack_tstamp(struct sock * sk,struct sk_buff * skb,u32 prior_snd_una)3109 static void tcp_ack_tstamp(struct sock *sk, struct sk_buff *skb,
3110 			   u32 prior_snd_una)
3111 {
3112 	const struct skb_shared_info *shinfo;
3113 
3114 	/* Avoid cache line misses to get skb_shinfo() and shinfo->tx_flags */
3115 	if (likely(!(sk->sk_tsflags & SOF_TIMESTAMPING_TX_ACK)))
3116 		return;
3117 
3118 	shinfo = skb_shinfo(skb);
3119 	if ((shinfo->tx_flags & SKBTX_ACK_TSTAMP) &&
3120 	    between(shinfo->tskey, prior_snd_una, tcp_sk(sk)->snd_una - 1))
3121 		__skb_tstamp_tx(skb, NULL, sk, SCM_TSTAMP_ACK);
3122 }
3123 
3124 /* Remove acknowledged frames from the retransmission queue. If our packet
3125  * is before the ack sequence we can discard it as it's confirmed to have
3126  * arrived at the other end.
3127  */
tcp_clean_rtx_queue(struct sock * sk,int prior_fackets,u32 prior_snd_una,struct tcp_sacktag_state * sack)3128 static int tcp_clean_rtx_queue(struct sock *sk, int prior_fackets,
3129 			       u32 prior_snd_una,
3130 			       struct tcp_sacktag_state *sack)
3131 {
3132 	const struct inet_connection_sock *icsk = inet_csk(sk);
3133 	struct skb_mstamp first_ackt, last_ackt, now;
3134 	struct tcp_sock *tp = tcp_sk(sk);
3135 	u32 prior_sacked = tp->sacked_out;
3136 	u32 reord = tp->packets_out;
3137 	bool fully_acked = true;
3138 	long sack_rtt_us = -1L;
3139 	long seq_rtt_us = -1L;
3140 	long ca_rtt_us = -1L;
3141 	struct sk_buff *skb;
3142 	u32 pkts_acked = 0;
3143 	bool rtt_update;
3144 	int flag = 0;
3145 
3146 	first_ackt.v64 = 0;
3147 
3148 	while ((skb = tcp_write_queue_head(sk)) && skb != tcp_send_head(sk)) {
3149 		struct tcp_skb_cb *scb = TCP_SKB_CB(skb);
3150 		u8 sacked = scb->sacked;
3151 		u32 acked_pcount;
3152 
3153 		tcp_ack_tstamp(sk, skb, prior_snd_una);
3154 
3155 		/* Determine how many packets and what bytes were acked, tso and else */
3156 		if (after(scb->end_seq, tp->snd_una)) {
3157 			if (tcp_skb_pcount(skb) == 1 ||
3158 			    !after(tp->snd_una, scb->seq))
3159 				break;
3160 
3161 			acked_pcount = tcp_tso_acked(sk, skb);
3162 			if (!acked_pcount)
3163 				break;
3164 
3165 			fully_acked = false;
3166 		} else {
3167 			/* Speedup tcp_unlink_write_queue() and next loop */
3168 			prefetchw(skb->next);
3169 			acked_pcount = tcp_skb_pcount(skb);
3170 		}
3171 
3172 		if (unlikely(sacked & TCPCB_RETRANS)) {
3173 			if (sacked & TCPCB_SACKED_RETRANS)
3174 				tp->retrans_out -= acked_pcount;
3175 			flag |= FLAG_RETRANS_DATA_ACKED;
3176 		} else if (!(sacked & TCPCB_SACKED_ACKED)) {
3177 			last_ackt = skb->skb_mstamp;
3178 			WARN_ON_ONCE(last_ackt.v64 == 0);
3179 			if (!first_ackt.v64)
3180 				first_ackt = last_ackt;
3181 
3182 			reord = min(pkts_acked, reord);
3183 			if (!after(scb->end_seq, tp->high_seq))
3184 				flag |= FLAG_ORIG_SACK_ACKED;
3185 		}
3186 
3187 		if (sacked & TCPCB_SACKED_ACKED)
3188 			tp->sacked_out -= acked_pcount;
3189 		else if (tcp_is_sack(tp) && !tcp_skb_spurious_retrans(tp, skb))
3190 			tcp_rack_advance(tp, &skb->skb_mstamp, sacked);
3191 		if (sacked & TCPCB_LOST)
3192 			tp->lost_out -= acked_pcount;
3193 
3194 		tp->packets_out -= acked_pcount;
3195 		pkts_acked += acked_pcount;
3196 
3197 		/* Initial outgoing SYN's get put onto the write_queue
3198 		 * just like anything else we transmit.  It is not
3199 		 * true data, and if we misinform our callers that
3200 		 * this ACK acks real data, we will erroneously exit
3201 		 * connection startup slow start one packet too
3202 		 * quickly.  This is severely frowned upon behavior.
3203 		 */
3204 		if (likely(!(scb->tcp_flags & TCPHDR_SYN))) {
3205 			flag |= FLAG_DATA_ACKED;
3206 		} else {
3207 			flag |= FLAG_SYN_ACKED;
3208 			tp->retrans_stamp = 0;
3209 		}
3210 
3211 		if (!fully_acked)
3212 			break;
3213 
3214 		tcp_unlink_write_queue(skb, sk);
3215 		sk_wmem_free_skb(sk, skb);
3216 		if (unlikely(skb == tp->retransmit_skb_hint))
3217 			tp->retransmit_skb_hint = NULL;
3218 		if (unlikely(skb == tp->lost_skb_hint))
3219 			tp->lost_skb_hint = NULL;
3220 	}
3221 
3222 	if (likely(between(tp->snd_up, prior_snd_una, tp->snd_una)))
3223 		tp->snd_up = tp->snd_una;
3224 
3225 	if (skb && (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED))
3226 		flag |= FLAG_SACK_RENEGING;
3227 
3228 	skb_mstamp_get(&now);
3229 	if (likely(first_ackt.v64) && !(flag & FLAG_RETRANS_DATA_ACKED)) {
3230 		seq_rtt_us = skb_mstamp_us_delta(&now, &first_ackt);
3231 		ca_rtt_us = skb_mstamp_us_delta(&now, &last_ackt);
3232 	}
3233 	if (sack->first_sackt.v64) {
3234 		sack_rtt_us = skb_mstamp_us_delta(&now, &sack->first_sackt);
3235 		ca_rtt_us = skb_mstamp_us_delta(&now, &sack->last_sackt);
3236 	}
3237 
3238 	rtt_update = tcp_ack_update_rtt(sk, flag, seq_rtt_us, sack_rtt_us,
3239 					ca_rtt_us);
3240 
3241 	if (flag & FLAG_ACKED) {
3242 		tcp_rearm_rto(sk);
3243 		if (unlikely(icsk->icsk_mtup.probe_size &&
3244 			     !after(tp->mtu_probe.probe_seq_end, tp->snd_una))) {
3245 			tcp_mtup_probe_success(sk);
3246 		}
3247 
3248 		if (tcp_is_reno(tp)) {
3249 			tcp_remove_reno_sacks(sk, pkts_acked);
3250 
3251 			/* If any of the cumulatively ACKed segments was
3252 			 * retransmitted, non-SACK case cannot confirm that
3253 			 * progress was due to original transmission due to
3254 			 * lack of TCPCB_SACKED_ACKED bits even if some of
3255 			 * the packets may have been never retransmitted.
3256 			 */
3257 			if (flag & FLAG_RETRANS_DATA_ACKED)
3258 				flag &= ~FLAG_ORIG_SACK_ACKED;
3259 		} else {
3260 			int delta;
3261 
3262 			/* Non-retransmitted hole got filled? That's reordering */
3263 			if (reord < prior_fackets && reord <= tp->fackets_out)
3264 				tcp_update_reordering(sk, tp->fackets_out - reord, 0);
3265 
3266 			delta = tcp_is_fack(tp) ? pkts_acked :
3267 						  prior_sacked - tp->sacked_out;
3268 			tp->lost_cnt_hint -= min(tp->lost_cnt_hint, delta);
3269 		}
3270 
3271 		tp->fackets_out -= min(pkts_acked, tp->fackets_out);
3272 
3273 	} else if (skb && rtt_update && sack_rtt_us >= 0 &&
3274 		   sack_rtt_us > skb_mstamp_us_delta(&now, &skb->skb_mstamp)) {
3275 		/* Do not re-arm RTO if the sack RTT is measured from data sent
3276 		 * after when the head was last (re)transmitted. Otherwise the
3277 		 * timeout may continue to extend in loss recovery.
3278 		 */
3279 		tcp_rearm_rto(sk);
3280 	}
3281 
3282 	if (icsk->icsk_ca_ops->pkts_acked)
3283 		icsk->icsk_ca_ops->pkts_acked(sk, pkts_acked, ca_rtt_us);
3284 
3285 #if FASTRETRANS_DEBUG > 0
3286 	WARN_ON((int)tp->sacked_out < 0);
3287 	WARN_ON((int)tp->lost_out < 0);
3288 	WARN_ON((int)tp->retrans_out < 0);
3289 	if (!tp->packets_out && tcp_is_sack(tp)) {
3290 		icsk = inet_csk(sk);
3291 		if (tp->lost_out) {
3292 			pr_debug("Leak l=%u %d\n",
3293 				 tp->lost_out, icsk->icsk_ca_state);
3294 			tp->lost_out = 0;
3295 		}
3296 		if (tp->sacked_out) {
3297 			pr_debug("Leak s=%u %d\n",
3298 				 tp->sacked_out, icsk->icsk_ca_state);
3299 			tp->sacked_out = 0;
3300 		}
3301 		if (tp->retrans_out) {
3302 			pr_debug("Leak r=%u %d\n",
3303 				 tp->retrans_out, icsk->icsk_ca_state);
3304 			tp->retrans_out = 0;
3305 		}
3306 	}
3307 #endif
3308 	return flag;
3309 }
3310 
tcp_ack_probe(struct sock * sk)3311 static void tcp_ack_probe(struct sock *sk)
3312 {
3313 	const struct tcp_sock *tp = tcp_sk(sk);
3314 	struct inet_connection_sock *icsk = inet_csk(sk);
3315 
3316 	/* Was it a usable window open? */
3317 
3318 	if (!after(TCP_SKB_CB(tcp_send_head(sk))->end_seq, tcp_wnd_end(tp))) {
3319 		icsk->icsk_backoff = 0;
3320 		inet_csk_clear_xmit_timer(sk, ICSK_TIME_PROBE0);
3321 		/* Socket must be waked up by subsequent tcp_data_snd_check().
3322 		 * This function is not for random using!
3323 		 */
3324 	} else {
3325 		unsigned long when = tcp_probe0_when(sk, TCP_RTO_MAX);
3326 
3327 		inet_csk_reset_xmit_timer(sk, ICSK_TIME_PROBE0,
3328 					  when, TCP_RTO_MAX);
3329 	}
3330 }
3331 
tcp_ack_is_dubious(const struct sock * sk,const int flag)3332 static inline bool tcp_ack_is_dubious(const struct sock *sk, const int flag)
3333 {
3334 	return !(flag & FLAG_NOT_DUP) || (flag & FLAG_CA_ALERT) ||
3335 		inet_csk(sk)->icsk_ca_state != TCP_CA_Open;
3336 }
3337 
3338 /* Decide wheather to run the increase function of congestion control. */
tcp_may_raise_cwnd(const struct sock * sk,const int flag)3339 static inline bool tcp_may_raise_cwnd(const struct sock *sk, const int flag)
3340 {
3341 	if (tcp_in_cwnd_reduction(sk))
3342 		return false;
3343 
3344 	/* If reordering is high then always grow cwnd whenever data is
3345 	 * delivered regardless of its ordering. Otherwise stay conservative
3346 	 * and only grow cwnd on in-order delivery (RFC5681). A stretched ACK w/
3347 	 * new SACK or ECE mark may first advance cwnd here and later reduce
3348 	 * cwnd in tcp_fastretrans_alert() based on more states.
3349 	 */
3350 	if (tcp_sk(sk)->reordering > sysctl_tcp_reordering)
3351 		return flag & FLAG_FORWARD_PROGRESS;
3352 
3353 	return flag & FLAG_DATA_ACKED;
3354 }
3355 
3356 /* Check that window update is acceptable.
3357  * The function assumes that snd_una<=ack<=snd_next.
3358  */
tcp_may_update_window(const struct tcp_sock * tp,const u32 ack,const u32 ack_seq,const u32 nwin)3359 static inline bool tcp_may_update_window(const struct tcp_sock *tp,
3360 					const u32 ack, const u32 ack_seq,
3361 					const u32 nwin)
3362 {
3363 	return	after(ack, tp->snd_una) ||
3364 		after(ack_seq, tp->snd_wl1) ||
3365 		(ack_seq == tp->snd_wl1 && nwin > tp->snd_wnd);
3366 }
3367 
3368 /* If we update tp->snd_una, also update tp->bytes_acked */
tcp_snd_una_update(struct tcp_sock * tp,u32 ack)3369 static void tcp_snd_una_update(struct tcp_sock *tp, u32 ack)
3370 {
3371 	u32 delta = ack - tp->snd_una;
3372 
3373 	u64_stats_update_begin(&tp->syncp);
3374 	tp->bytes_acked += delta;
3375 	u64_stats_update_end(&tp->syncp);
3376 	tp->snd_una = ack;
3377 }
3378 
3379 /* If we update tp->rcv_nxt, also update tp->bytes_received */
tcp_rcv_nxt_update(struct tcp_sock * tp,u32 seq)3380 static void tcp_rcv_nxt_update(struct tcp_sock *tp, u32 seq)
3381 {
3382 	u32 delta = seq - tp->rcv_nxt;
3383 
3384 	u64_stats_update_begin(&tp->syncp);
3385 	tp->bytes_received += delta;
3386 	u64_stats_update_end(&tp->syncp);
3387 	tp->rcv_nxt = seq;
3388 }
3389 
3390 /* Update our send window.
3391  *
3392  * Window update algorithm, described in RFC793/RFC1122 (used in linux-2.2
3393  * and in FreeBSD. NetBSD's one is even worse.) is wrong.
3394  */
tcp_ack_update_window(struct sock * sk,const struct sk_buff * skb,u32 ack,u32 ack_seq)3395 static int tcp_ack_update_window(struct sock *sk, const struct sk_buff *skb, u32 ack,
3396 				 u32 ack_seq)
3397 {
3398 	struct tcp_sock *tp = tcp_sk(sk);
3399 	int flag = 0;
3400 	u32 nwin = ntohs(tcp_hdr(skb)->window);
3401 
3402 	if (likely(!tcp_hdr(skb)->syn))
3403 		nwin <<= tp->rx_opt.snd_wscale;
3404 
3405 	if (tcp_may_update_window(tp, ack, ack_seq, nwin)) {
3406 		flag |= FLAG_WIN_UPDATE;
3407 		tcp_update_wl(tp, ack_seq);
3408 
3409 		if (tp->snd_wnd != nwin) {
3410 			tp->snd_wnd = nwin;
3411 
3412 			/* Note, it is the only place, where
3413 			 * fast path is recovered for sending TCP.
3414 			 */
3415 			tp->pred_flags = 0;
3416 			tcp_fast_path_check(sk);
3417 
3418 			if (tcp_send_head(sk))
3419 				tcp_slow_start_after_idle_check(sk);
3420 
3421 			if (nwin > tp->max_window) {
3422 				tp->max_window = nwin;
3423 				tcp_sync_mss(sk, inet_csk(sk)->icsk_pmtu_cookie);
3424 			}
3425 		}
3426 	}
3427 
3428 	tcp_snd_una_update(tp, ack);
3429 
3430 	return flag;
3431 }
3432 
__tcp_oow_rate_limited(struct net * net,int mib_idx,u32 * last_oow_ack_time)3433 static bool __tcp_oow_rate_limited(struct net *net, int mib_idx,
3434 				   u32 *last_oow_ack_time)
3435 {
3436 	if (*last_oow_ack_time) {
3437 		s32 elapsed = (s32)(tcp_time_stamp - *last_oow_ack_time);
3438 
3439 		if (0 <= elapsed && elapsed < sysctl_tcp_invalid_ratelimit) {
3440 			NET_INC_STATS_BH(net, mib_idx);
3441 			return true;	/* rate-limited: don't send yet! */
3442 		}
3443 	}
3444 
3445 	*last_oow_ack_time = tcp_time_stamp;
3446 
3447 	return false;	/* not rate-limited: go ahead, send dupack now! */
3448 }
3449 
3450 /* Return true if we're currently rate-limiting out-of-window ACKs and
3451  * thus shouldn't send a dupack right now. We rate-limit dupacks in
3452  * response to out-of-window SYNs or ACKs to mitigate ACK loops or DoS
3453  * attacks that send repeated SYNs or ACKs for the same connection. To
3454  * do this, we do not send a duplicate SYNACK or ACK if the remote
3455  * endpoint is sending out-of-window SYNs or pure ACKs at a high rate.
3456  */
tcp_oow_rate_limited(struct net * net,const struct sk_buff * skb,int mib_idx,u32 * last_oow_ack_time)3457 bool tcp_oow_rate_limited(struct net *net, const struct sk_buff *skb,
3458 			  int mib_idx, u32 *last_oow_ack_time)
3459 {
3460 	/* Data packets without SYNs are not likely part of an ACK loop. */
3461 	if ((TCP_SKB_CB(skb)->seq != TCP_SKB_CB(skb)->end_seq) &&
3462 	    !tcp_hdr(skb)->syn)
3463 		return false;
3464 
3465 	return __tcp_oow_rate_limited(net, mib_idx, last_oow_ack_time);
3466 }
3467 
3468 /* RFC 5961 7 [ACK Throttling] */
tcp_send_challenge_ack(struct sock * sk,const struct sk_buff * skb)3469 static void tcp_send_challenge_ack(struct sock *sk, const struct sk_buff *skb)
3470 {
3471 	/* unprotected vars, we dont care of overwrites */
3472 	static u32 challenge_timestamp;
3473 	static unsigned int challenge_count;
3474 	struct tcp_sock *tp = tcp_sk(sk);
3475 	u32 count, now;
3476 
3477 	/* First check our per-socket dupack rate limit. */
3478 	if (__tcp_oow_rate_limited(sock_net(sk),
3479 				   LINUX_MIB_TCPACKSKIPPEDCHALLENGE,
3480 				   &tp->last_oow_ack_time))
3481 		return;
3482 
3483 	/* Then check host-wide RFC 5961 rate limit. */
3484 	now = jiffies / HZ;
3485 	if (now != challenge_timestamp) {
3486 		u32 half = (sysctl_tcp_challenge_ack_limit + 1) >> 1;
3487 
3488 		challenge_timestamp = now;
3489 		WRITE_ONCE(challenge_count, half +
3490 			   prandom_u32_max(sysctl_tcp_challenge_ack_limit));
3491 	}
3492 	count = READ_ONCE(challenge_count);
3493 	if (count > 0) {
3494 		WRITE_ONCE(challenge_count, count - 1);
3495 		NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPCHALLENGEACK);
3496 		tcp_send_ack(sk);
3497 	}
3498 }
3499 
tcp_store_ts_recent(struct tcp_sock * tp)3500 static void tcp_store_ts_recent(struct tcp_sock *tp)
3501 {
3502 	tp->rx_opt.ts_recent = tp->rx_opt.rcv_tsval;
3503 	tp->rx_opt.ts_recent_stamp = get_seconds();
3504 }
3505 
tcp_replace_ts_recent(struct tcp_sock * tp,u32 seq)3506 static void tcp_replace_ts_recent(struct tcp_sock *tp, u32 seq)
3507 {
3508 	if (tp->rx_opt.saw_tstamp && !after(seq, tp->rcv_wup)) {
3509 		/* PAWS bug workaround wrt. ACK frames, the PAWS discard
3510 		 * extra check below makes sure this can only happen
3511 		 * for pure ACK frames.  -DaveM
3512 		 *
3513 		 * Not only, also it occurs for expired timestamps.
3514 		 */
3515 
3516 		if (tcp_paws_check(&tp->rx_opt, 0))
3517 			tcp_store_ts_recent(tp);
3518 	}
3519 }
3520 
3521 /* This routine deals with acks during a TLP episode and ends an episode by
3522  * resetting tlp_high_seq. Ref: TLP algorithm in draft-ietf-tcpm-rack
3523  */
tcp_process_tlp_ack(struct sock * sk,u32 ack,int flag)3524 static void tcp_process_tlp_ack(struct sock *sk, u32 ack, int flag)
3525 {
3526 	struct tcp_sock *tp = tcp_sk(sk);
3527 
3528 	if (before(ack, tp->tlp_high_seq))
3529 		return;
3530 
3531 	if (!tp->tlp_retrans) {
3532 		/* TLP of new data has been acknowledged */
3533 		tp->tlp_high_seq = 0;
3534 	} else if (flag & FLAG_DSACKING_ACK) {
3535 		/* This DSACK means original and TLP probe arrived; no loss */
3536 		tp->tlp_high_seq = 0;
3537 	} else if (after(ack, tp->tlp_high_seq)) {
3538 		/* ACK advances: there was a loss, so reduce cwnd. Reset
3539 		 * tlp_high_seq in tcp_init_cwnd_reduction()
3540 		 */
3541 		tcp_init_cwnd_reduction(sk);
3542 		tcp_set_ca_state(sk, TCP_CA_CWR);
3543 		tcp_end_cwnd_reduction(sk);
3544 		tcp_try_keep_open(sk);
3545 		NET_INC_STATS_BH(sock_net(sk),
3546 				 LINUX_MIB_TCPLOSSPROBERECOVERY);
3547 	} else if (!(flag & (FLAG_SND_UNA_ADVANCED |
3548 			     FLAG_NOT_DUP | FLAG_DATA_SACKED))) {
3549 		/* Pure dupack: original and TLP probe arrived; no loss */
3550 		tp->tlp_high_seq = 0;
3551 	}
3552 }
3553 
tcp_in_ack_event(struct sock * sk,u32 flags)3554 static inline void tcp_in_ack_event(struct sock *sk, u32 flags)
3555 {
3556 	const struct inet_connection_sock *icsk = inet_csk(sk);
3557 
3558 	if (icsk->icsk_ca_ops->in_ack_event)
3559 		icsk->icsk_ca_ops->in_ack_event(sk, flags);
3560 }
3561 
3562 /* This routine deals with incoming acks, but not outgoing ones. */
tcp_ack(struct sock * sk,const struct sk_buff * skb,int flag)3563 static int tcp_ack(struct sock *sk, const struct sk_buff *skb, int flag)
3564 {
3565 	struct inet_connection_sock *icsk = inet_csk(sk);
3566 	struct tcp_sock *tp = tcp_sk(sk);
3567 	struct tcp_sacktag_state sack_state;
3568 	u32 prior_snd_una = tp->snd_una;
3569 	u32 ack_seq = TCP_SKB_CB(skb)->seq;
3570 	u32 ack = TCP_SKB_CB(skb)->ack_seq;
3571 	bool is_dupack = false;
3572 	u32 prior_fackets;
3573 	int prior_packets = tp->packets_out;
3574 	const int prior_unsacked = tp->packets_out - tp->sacked_out;
3575 	int acked = 0; /* Number of packets newly acked */
3576 
3577 	sack_state.first_sackt.v64 = 0;
3578 
3579 	/* We very likely will need to access write queue head. */
3580 	prefetchw(sk->sk_write_queue.next);
3581 
3582 	/* If the ack is older than previous acks
3583 	 * then we can probably ignore it.
3584 	 */
3585 	if (before(ack, prior_snd_una)) {
3586 		/* RFC 5961 5.2 [Blind Data Injection Attack].[Mitigation] */
3587 		if (before(ack, prior_snd_una - tp->max_window)) {
3588 			if (!(flag & FLAG_NO_CHALLENGE_ACK))
3589 				tcp_send_challenge_ack(sk, skb);
3590 			return -1;
3591 		}
3592 		goto old_ack;
3593 	}
3594 
3595 	/* If the ack includes data we haven't sent yet, discard
3596 	 * this segment (RFC793 Section 3.9).
3597 	 */
3598 	if (after(ack, tp->snd_nxt))
3599 		goto invalid_ack;
3600 
3601 	if (icsk->icsk_pending == ICSK_TIME_EARLY_RETRANS ||
3602 	    icsk->icsk_pending == ICSK_TIME_LOSS_PROBE)
3603 		tcp_rearm_rto(sk);
3604 
3605 	if (after(ack, prior_snd_una)) {
3606 		flag |= FLAG_SND_UNA_ADVANCED;
3607 		icsk->icsk_retransmits = 0;
3608 	}
3609 
3610 	prior_fackets = tp->fackets_out;
3611 
3612 	/* ts_recent update must be made after we are sure that the packet
3613 	 * is in window.
3614 	 */
3615 	if (flag & FLAG_UPDATE_TS_RECENT)
3616 		tcp_replace_ts_recent(tp, TCP_SKB_CB(skb)->seq);
3617 
3618 	if (!(flag & FLAG_SLOWPATH) && after(ack, prior_snd_una)) {
3619 		/* Window is constant, pure forward advance.
3620 		 * No more checks are required.
3621 		 * Note, we use the fact that SND.UNA>=SND.WL2.
3622 		 */
3623 		tcp_update_wl(tp, ack_seq);
3624 		tcp_snd_una_update(tp, ack);
3625 		flag |= FLAG_WIN_UPDATE;
3626 
3627 		tcp_in_ack_event(sk, CA_ACK_WIN_UPDATE);
3628 
3629 		NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPHPACKS);
3630 	} else {
3631 		u32 ack_ev_flags = CA_ACK_SLOWPATH;
3632 
3633 		if (ack_seq != TCP_SKB_CB(skb)->end_seq)
3634 			flag |= FLAG_DATA;
3635 		else
3636 			NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPPUREACKS);
3637 
3638 		flag |= tcp_ack_update_window(sk, skb, ack, ack_seq);
3639 
3640 		if (TCP_SKB_CB(skb)->sacked)
3641 			flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una,
3642 							&sack_state);
3643 
3644 		if (tcp_ecn_rcv_ecn_echo(tp, tcp_hdr(skb))) {
3645 			flag |= FLAG_ECE;
3646 			ack_ev_flags |= CA_ACK_ECE;
3647 		}
3648 
3649 		if (flag & FLAG_WIN_UPDATE)
3650 			ack_ev_flags |= CA_ACK_WIN_UPDATE;
3651 
3652 		tcp_in_ack_event(sk, ack_ev_flags);
3653 	}
3654 
3655 	/* We passed data and got it acked, remove any soft error
3656 	 * log. Something worked...
3657 	 */
3658 	sk->sk_err_soft = 0;
3659 	icsk->icsk_probes_out = 0;
3660 	tp->rcv_tstamp = tcp_time_stamp;
3661 	if (!prior_packets)
3662 		goto no_queue;
3663 
3664 	/* See if we can take anything off of the retransmit queue. */
3665 	acked = tp->packets_out;
3666 	flag |= tcp_clean_rtx_queue(sk, prior_fackets, prior_snd_una,
3667 				    &sack_state);
3668 	acked -= tp->packets_out;
3669 
3670 	if (tcp_ack_is_dubious(sk, flag)) {
3671 		is_dupack = !(flag & (FLAG_SND_UNA_ADVANCED | FLAG_NOT_DUP));
3672 		tcp_fastretrans_alert(sk, acked, prior_unsacked,
3673 				      is_dupack, flag);
3674 	}
3675 	if (tp->tlp_high_seq)
3676 		tcp_process_tlp_ack(sk, ack, flag);
3677 
3678 	/* Advance cwnd if state allows */
3679 	if (tcp_may_raise_cwnd(sk, flag))
3680 		tcp_cong_avoid(sk, ack, acked);
3681 
3682 	if ((flag & FLAG_FORWARD_PROGRESS) || !(flag & FLAG_NOT_DUP)) {
3683 		struct dst_entry *dst = __sk_dst_get(sk);
3684 		if (dst)
3685 			dst_confirm(dst);
3686 	}
3687 
3688 	if (icsk->icsk_pending == ICSK_TIME_RETRANS)
3689 		tcp_schedule_loss_probe(sk);
3690 	tcp_update_pacing_rate(sk);
3691 	return 1;
3692 
3693 no_queue:
3694 	/* If data was DSACKed, see if we can undo a cwnd reduction. */
3695 	if (flag & FLAG_DSACKING_ACK)
3696 		tcp_fastretrans_alert(sk, acked, prior_unsacked,
3697 				      is_dupack, flag);
3698 	/* If this ack opens up a zero window, clear backoff.  It was
3699 	 * being used to time the probes, and is probably far higher than
3700 	 * it needs to be for normal retransmission.
3701 	 */
3702 	if (tcp_send_head(sk))
3703 		tcp_ack_probe(sk);
3704 
3705 	if (tp->tlp_high_seq)
3706 		tcp_process_tlp_ack(sk, ack, flag);
3707 	return 1;
3708 
3709 invalid_ack:
3710 	SOCK_DEBUG(sk, "Ack %u after %u:%u\n", ack, tp->snd_una, tp->snd_nxt);
3711 	return -1;
3712 
3713 old_ack:
3714 	/* If data was SACKed, tag it and see if we should send more data.
3715 	 * If data was DSACKed, see if we can undo a cwnd reduction.
3716 	 */
3717 	if (TCP_SKB_CB(skb)->sacked) {
3718 		flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una,
3719 						&sack_state);
3720 		tcp_fastretrans_alert(sk, acked, prior_unsacked,
3721 				      is_dupack, flag);
3722 	}
3723 
3724 	SOCK_DEBUG(sk, "Ack %u before %u:%u\n", ack, tp->snd_una, tp->snd_nxt);
3725 	return 0;
3726 }
3727 
tcp_parse_fastopen_option(int len,const unsigned char * cookie,bool syn,struct tcp_fastopen_cookie * foc,bool exp_opt)3728 static void tcp_parse_fastopen_option(int len, const unsigned char *cookie,
3729 				      bool syn, struct tcp_fastopen_cookie *foc,
3730 				      bool exp_opt)
3731 {
3732 	/* Valid only in SYN or SYN-ACK with an even length.  */
3733 	if (!foc || !syn || len < 0 || (len & 1))
3734 		return;
3735 
3736 	if (len >= TCP_FASTOPEN_COOKIE_MIN &&
3737 	    len <= TCP_FASTOPEN_COOKIE_MAX)
3738 		memcpy(foc->val, cookie, len);
3739 	else if (len != 0)
3740 		len = -1;
3741 	foc->len = len;
3742 	foc->exp = exp_opt;
3743 }
3744 
3745 /* Look for tcp options. Normally only called on SYN and SYNACK packets.
3746  * But, this can also be called on packets in the established flow when
3747  * the fast version below fails.
3748  */
tcp_parse_options(const struct sk_buff * skb,struct tcp_options_received * opt_rx,int estab,struct tcp_fastopen_cookie * foc)3749 void tcp_parse_options(const struct sk_buff *skb,
3750 		       struct tcp_options_received *opt_rx, int estab,
3751 		       struct tcp_fastopen_cookie *foc)
3752 {
3753 	const unsigned char *ptr;
3754 	const struct tcphdr *th = tcp_hdr(skb);
3755 	int length = (th->doff * 4) - sizeof(struct tcphdr);
3756 
3757 	ptr = (const unsigned char *)(th + 1);
3758 	opt_rx->saw_tstamp = 0;
3759 
3760 	while (length > 0) {
3761 		int opcode = *ptr++;
3762 		int opsize;
3763 
3764 		switch (opcode) {
3765 		case TCPOPT_EOL:
3766 			return;
3767 		case TCPOPT_NOP:	/* Ref: RFC 793 section 3.1 */
3768 			length--;
3769 			continue;
3770 		default:
3771 			opsize = *ptr++;
3772 			if (opsize < 2) /* "silly options" */
3773 				return;
3774 			if (opsize > length)
3775 				return;	/* don't parse partial options */
3776 			switch (opcode) {
3777 			case TCPOPT_MSS:
3778 				if (opsize == TCPOLEN_MSS && th->syn && !estab) {
3779 					u16 in_mss = get_unaligned_be16(ptr);
3780 					if (in_mss) {
3781 						if (opt_rx->user_mss &&
3782 						    opt_rx->user_mss < in_mss)
3783 							in_mss = opt_rx->user_mss;
3784 						opt_rx->mss_clamp = in_mss;
3785 					}
3786 				}
3787 				break;
3788 			case TCPOPT_WINDOW:
3789 				if (opsize == TCPOLEN_WINDOW && th->syn &&
3790 				    !estab && sysctl_tcp_window_scaling) {
3791 					__u8 snd_wscale = *(__u8 *)ptr;
3792 					opt_rx->wscale_ok = 1;
3793 					if (snd_wscale > 14) {
3794 						net_info_ratelimited("%s: Illegal window scaling value %d >14 received\n",
3795 								     __func__,
3796 								     snd_wscale);
3797 						snd_wscale = 14;
3798 					}
3799 					opt_rx->snd_wscale = snd_wscale;
3800 				}
3801 				break;
3802 			case TCPOPT_TIMESTAMP:
3803 				if ((opsize == TCPOLEN_TIMESTAMP) &&
3804 				    ((estab && opt_rx->tstamp_ok) ||
3805 				     (!estab && sysctl_tcp_timestamps))) {
3806 					opt_rx->saw_tstamp = 1;
3807 					opt_rx->rcv_tsval = get_unaligned_be32(ptr);
3808 					opt_rx->rcv_tsecr = get_unaligned_be32(ptr + 4);
3809 				}
3810 				break;
3811 			case TCPOPT_SACK_PERM:
3812 				if (opsize == TCPOLEN_SACK_PERM && th->syn &&
3813 				    !estab && sysctl_tcp_sack) {
3814 					opt_rx->sack_ok = TCP_SACK_SEEN;
3815 					tcp_sack_reset(opt_rx);
3816 				}
3817 				break;
3818 
3819 			case TCPOPT_SACK:
3820 				if ((opsize >= (TCPOLEN_SACK_BASE + TCPOLEN_SACK_PERBLOCK)) &&
3821 				   !((opsize - TCPOLEN_SACK_BASE) % TCPOLEN_SACK_PERBLOCK) &&
3822 				   opt_rx->sack_ok) {
3823 					TCP_SKB_CB(skb)->sacked = (ptr - 2) - (unsigned char *)th;
3824 				}
3825 				break;
3826 #ifdef CONFIG_TCP_MD5SIG
3827 			case TCPOPT_MD5SIG:
3828 				/*
3829 				 * The MD5 Hash has already been
3830 				 * checked (see tcp_v{4,6}_do_rcv()).
3831 				 */
3832 				break;
3833 #endif
3834 			case TCPOPT_FASTOPEN:
3835 				tcp_parse_fastopen_option(
3836 					opsize - TCPOLEN_FASTOPEN_BASE,
3837 					ptr, th->syn, foc, false);
3838 				break;
3839 
3840 			case TCPOPT_EXP:
3841 				/* Fast Open option shares code 254 using a
3842 				 * 16 bits magic number.
3843 				 */
3844 				if (opsize >= TCPOLEN_EXP_FASTOPEN_BASE &&
3845 				    get_unaligned_be16(ptr) ==
3846 				    TCPOPT_FASTOPEN_MAGIC)
3847 					tcp_parse_fastopen_option(opsize -
3848 						TCPOLEN_EXP_FASTOPEN_BASE,
3849 						ptr + 2, th->syn, foc, true);
3850 				break;
3851 
3852 			}
3853 			ptr += opsize-2;
3854 			length -= opsize;
3855 		}
3856 	}
3857 }
3858 EXPORT_SYMBOL(tcp_parse_options);
3859 
tcp_parse_aligned_timestamp(struct tcp_sock * tp,const struct tcphdr * th)3860 static bool tcp_parse_aligned_timestamp(struct tcp_sock *tp, const struct tcphdr *th)
3861 {
3862 	const __be32 *ptr = (const __be32 *)(th + 1);
3863 
3864 	if (*ptr == htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16)
3865 			  | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP)) {
3866 		tp->rx_opt.saw_tstamp = 1;
3867 		++ptr;
3868 		tp->rx_opt.rcv_tsval = ntohl(*ptr);
3869 		++ptr;
3870 		if (*ptr)
3871 			tp->rx_opt.rcv_tsecr = ntohl(*ptr) - tp->tsoffset;
3872 		else
3873 			tp->rx_opt.rcv_tsecr = 0;
3874 		return true;
3875 	}
3876 	return false;
3877 }
3878 
3879 /* Fast parse options. This hopes to only see timestamps.
3880  * If it is wrong it falls back on tcp_parse_options().
3881  */
tcp_fast_parse_options(const struct sk_buff * skb,const struct tcphdr * th,struct tcp_sock * tp)3882 static bool tcp_fast_parse_options(const struct sk_buff *skb,
3883 				   const struct tcphdr *th, struct tcp_sock *tp)
3884 {
3885 	/* In the spirit of fast parsing, compare doff directly to constant
3886 	 * values.  Because equality is used, short doff can be ignored here.
3887 	 */
3888 	if (th->doff == (sizeof(*th) / 4)) {
3889 		tp->rx_opt.saw_tstamp = 0;
3890 		return false;
3891 	} else if (tp->rx_opt.tstamp_ok &&
3892 		   th->doff == ((sizeof(*th) + TCPOLEN_TSTAMP_ALIGNED) / 4)) {
3893 		if (tcp_parse_aligned_timestamp(tp, th))
3894 			return true;
3895 	}
3896 
3897 	tcp_parse_options(skb, &tp->rx_opt, 1, NULL);
3898 	if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr)
3899 		tp->rx_opt.rcv_tsecr -= tp->tsoffset;
3900 
3901 	return true;
3902 }
3903 
3904 #ifdef CONFIG_TCP_MD5SIG
3905 /*
3906  * Parse MD5 Signature option
3907  */
tcp_parse_md5sig_option(const struct tcphdr * th)3908 const u8 *tcp_parse_md5sig_option(const struct tcphdr *th)
3909 {
3910 	int length = (th->doff << 2) - sizeof(*th);
3911 	const u8 *ptr = (const u8 *)(th + 1);
3912 
3913 	/* If not enough data remaining, we can short cut */
3914 	while (length >= TCPOLEN_MD5SIG) {
3915 		int opcode = *ptr++;
3916 		int opsize;
3917 
3918 		switch (opcode) {
3919 		case TCPOPT_EOL:
3920 			return NULL;
3921 		case TCPOPT_NOP:
3922 			length--;
3923 			continue;
3924 		default:
3925 			opsize = *ptr++;
3926 			if (opsize < 2 || opsize > length)
3927 				return NULL;
3928 			if (opcode == TCPOPT_MD5SIG)
3929 				return opsize == TCPOLEN_MD5SIG ? ptr : NULL;
3930 		}
3931 		ptr += opsize - 2;
3932 		length -= opsize;
3933 	}
3934 	return NULL;
3935 }
3936 EXPORT_SYMBOL(tcp_parse_md5sig_option);
3937 #endif
3938 
3939 /* Sorry, PAWS as specified is broken wrt. pure-ACKs -DaveM
3940  *
3941  * It is not fatal. If this ACK does _not_ change critical state (seqs, window)
3942  * it can pass through stack. So, the following predicate verifies that
3943  * this segment is not used for anything but congestion avoidance or
3944  * fast retransmit. Moreover, we even are able to eliminate most of such
3945  * second order effects, if we apply some small "replay" window (~RTO)
3946  * to timestamp space.
3947  *
3948  * All these measures still do not guarantee that we reject wrapped ACKs
3949  * on networks with high bandwidth, when sequence space is recycled fastly,
3950  * but it guarantees that such events will be very rare and do not affect
3951  * connection seriously. This doesn't look nice, but alas, PAWS is really
3952  * buggy extension.
3953  *
3954  * [ Later note. Even worse! It is buggy for segments _with_ data. RFC
3955  * states that events when retransmit arrives after original data are rare.
3956  * It is a blatant lie. VJ forgot about fast retransmit! 8)8) It is
3957  * the biggest problem on large power networks even with minor reordering.
3958  * OK, let's give it small replay window. If peer clock is even 1hz, it is safe
3959  * up to bandwidth of 18Gigabit/sec. 8) ]
3960  */
3961 
tcp_disordered_ack(const struct sock * sk,const struct sk_buff * skb)3962 static int tcp_disordered_ack(const struct sock *sk, const struct sk_buff *skb)
3963 {
3964 	const struct tcp_sock *tp = tcp_sk(sk);
3965 	const struct tcphdr *th = tcp_hdr(skb);
3966 	u32 seq = TCP_SKB_CB(skb)->seq;
3967 	u32 ack = TCP_SKB_CB(skb)->ack_seq;
3968 
3969 	return (/* 1. Pure ACK with correct sequence number. */
3970 		(th->ack && seq == TCP_SKB_CB(skb)->end_seq && seq == tp->rcv_nxt) &&
3971 
3972 		/* 2. ... and duplicate ACK. */
3973 		ack == tp->snd_una &&
3974 
3975 		/* 3. ... and does not update window. */
3976 		!tcp_may_update_window(tp, ack, seq, ntohs(th->window) << tp->rx_opt.snd_wscale) &&
3977 
3978 		/* 4. ... and sits in replay window. */
3979 		(s32)(tp->rx_opt.ts_recent - tp->rx_opt.rcv_tsval) <= (inet_csk(sk)->icsk_rto * 1024) / HZ);
3980 }
3981 
tcp_paws_discard(const struct sock * sk,const struct sk_buff * skb)3982 static inline bool tcp_paws_discard(const struct sock *sk,
3983 				   const struct sk_buff *skb)
3984 {
3985 	const struct tcp_sock *tp = tcp_sk(sk);
3986 
3987 	return !tcp_paws_check(&tp->rx_opt, TCP_PAWS_WINDOW) &&
3988 	       !tcp_disordered_ack(sk, skb);
3989 }
3990 
3991 /* Check segment sequence number for validity.
3992  *
3993  * Segment controls are considered valid, if the segment
3994  * fits to the window after truncation to the window. Acceptability
3995  * of data (and SYN, FIN, of course) is checked separately.
3996  * See tcp_data_queue(), for example.
3997  *
3998  * Also, controls (RST is main one) are accepted using RCV.WUP instead
3999  * of RCV.NXT. Peer still did not advance his SND.UNA when we
4000  * delayed ACK, so that hisSND.UNA<=ourRCV.WUP.
4001  * (borrowed from freebsd)
4002  */
4003 
tcp_sequence(const struct tcp_sock * tp,u32 seq,u32 end_seq)4004 static inline bool tcp_sequence(const struct tcp_sock *tp, u32 seq, u32 end_seq)
4005 {
4006 	return	!before(end_seq, tp->rcv_wup) &&
4007 		!after(seq, tp->rcv_nxt + tcp_receive_window(tp));
4008 }
4009 
4010 /* When we get a reset we do this. */
tcp_reset(struct sock * sk)4011 void tcp_reset(struct sock *sk)
4012 {
4013 	/* We want the right error as BSD sees it (and indeed as we do). */
4014 	switch (sk->sk_state) {
4015 	case TCP_SYN_SENT:
4016 		sk->sk_err = ECONNREFUSED;
4017 		break;
4018 	case TCP_CLOSE_WAIT:
4019 		sk->sk_err = EPIPE;
4020 		break;
4021 	case TCP_CLOSE:
4022 		return;
4023 	default:
4024 		sk->sk_err = ECONNRESET;
4025 	}
4026 	/* This barrier is coupled with smp_rmb() in tcp_poll() */
4027 	smp_wmb();
4028 
4029 	if (!sock_flag(sk, SOCK_DEAD))
4030 		sk->sk_error_report(sk);
4031 
4032 	tcp_done(sk);
4033 }
4034 
4035 /*
4036  * 	Process the FIN bit. This now behaves as it is supposed to work
4037  *	and the FIN takes effect when it is validly part of sequence
4038  *	space. Not before when we get holes.
4039  *
4040  *	If we are ESTABLISHED, a received fin moves us to CLOSE-WAIT
4041  *	(and thence onto LAST-ACK and finally, CLOSE, we never enter
4042  *	TIME-WAIT)
4043  *
4044  *	If we are in FINWAIT-1, a received FIN indicates simultaneous
4045  *	close and we go into CLOSING (and later onto TIME-WAIT)
4046  *
4047  *	If we are in FINWAIT-2, a received FIN moves us to TIME-WAIT.
4048  */
tcp_fin(struct sock * sk)4049 static void tcp_fin(struct sock *sk)
4050 {
4051 	struct tcp_sock *tp = tcp_sk(sk);
4052 
4053 	inet_csk_schedule_ack(sk);
4054 
4055 	sk->sk_shutdown |= RCV_SHUTDOWN;
4056 	sock_set_flag(sk, SOCK_DONE);
4057 
4058 	switch (sk->sk_state) {
4059 	case TCP_SYN_RECV:
4060 	case TCP_ESTABLISHED:
4061 		/* Move to CLOSE_WAIT */
4062 		tcp_set_state(sk, TCP_CLOSE_WAIT);
4063 		inet_csk(sk)->icsk_ack.pingpong = 1;
4064 		break;
4065 
4066 	case TCP_CLOSE_WAIT:
4067 	case TCP_CLOSING:
4068 		/* Received a retransmission of the FIN, do
4069 		 * nothing.
4070 		 */
4071 		break;
4072 	case TCP_LAST_ACK:
4073 		/* RFC793: Remain in the LAST-ACK state. */
4074 		break;
4075 
4076 	case TCP_FIN_WAIT1:
4077 		/* This case occurs when a simultaneous close
4078 		 * happens, we must ack the received FIN and
4079 		 * enter the CLOSING state.
4080 		 */
4081 		tcp_send_ack(sk);
4082 		tcp_set_state(sk, TCP_CLOSING);
4083 		break;
4084 	case TCP_FIN_WAIT2:
4085 		/* Received a FIN -- send ACK and enter TIME_WAIT. */
4086 		tcp_send_ack(sk);
4087 		tcp_time_wait(sk, TCP_TIME_WAIT, 0);
4088 		break;
4089 	default:
4090 		/* Only TCP_LISTEN and TCP_CLOSE are left, in these
4091 		 * cases we should never reach this piece of code.
4092 		 */
4093 		pr_err("%s: Impossible, sk->sk_state=%d\n",
4094 		       __func__, sk->sk_state);
4095 		break;
4096 	}
4097 
4098 	/* It _is_ possible, that we have something out-of-order _after_ FIN.
4099 	 * Probably, we should reset in this case. For now drop them.
4100 	 */
4101 	skb_rbtree_purge(&tp->out_of_order_queue);
4102 	if (tcp_is_sack(tp))
4103 		tcp_sack_reset(&tp->rx_opt);
4104 	sk_mem_reclaim(sk);
4105 
4106 	if (!sock_flag(sk, SOCK_DEAD)) {
4107 		sk->sk_state_change(sk);
4108 
4109 		/* Do not send POLL_HUP for half duplex close. */
4110 		if (sk->sk_shutdown == SHUTDOWN_MASK ||
4111 		    sk->sk_state == TCP_CLOSE)
4112 			sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP);
4113 		else
4114 			sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
4115 	}
4116 }
4117 
tcp_sack_extend(struct tcp_sack_block * sp,u32 seq,u32 end_seq)4118 static inline bool tcp_sack_extend(struct tcp_sack_block *sp, u32 seq,
4119 				  u32 end_seq)
4120 {
4121 	if (!after(seq, sp->end_seq) && !after(sp->start_seq, end_seq)) {
4122 		if (before(seq, sp->start_seq))
4123 			sp->start_seq = seq;
4124 		if (after(end_seq, sp->end_seq))
4125 			sp->end_seq = end_seq;
4126 		return true;
4127 	}
4128 	return false;
4129 }
4130 
tcp_dsack_set(struct sock * sk,u32 seq,u32 end_seq)4131 static void tcp_dsack_set(struct sock *sk, u32 seq, u32 end_seq)
4132 {
4133 	struct tcp_sock *tp = tcp_sk(sk);
4134 
4135 	if (tcp_is_sack(tp) && sysctl_tcp_dsack) {
4136 		int mib_idx;
4137 
4138 		if (before(seq, tp->rcv_nxt))
4139 			mib_idx = LINUX_MIB_TCPDSACKOLDSENT;
4140 		else
4141 			mib_idx = LINUX_MIB_TCPDSACKOFOSENT;
4142 
4143 		NET_INC_STATS_BH(sock_net(sk), mib_idx);
4144 
4145 		tp->rx_opt.dsack = 1;
4146 		tp->duplicate_sack[0].start_seq = seq;
4147 		tp->duplicate_sack[0].end_seq = end_seq;
4148 	}
4149 }
4150 
tcp_dsack_extend(struct sock * sk,u32 seq,u32 end_seq)4151 static void tcp_dsack_extend(struct sock *sk, u32 seq, u32 end_seq)
4152 {
4153 	struct tcp_sock *tp = tcp_sk(sk);
4154 
4155 	if (!tp->rx_opt.dsack)
4156 		tcp_dsack_set(sk, seq, end_seq);
4157 	else
4158 		tcp_sack_extend(tp->duplicate_sack, seq, end_seq);
4159 }
4160 
tcp_send_dupack(struct sock * sk,const struct sk_buff * skb)4161 static void tcp_send_dupack(struct sock *sk, const struct sk_buff *skb)
4162 {
4163 	struct tcp_sock *tp = tcp_sk(sk);
4164 
4165 	if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
4166 	    before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
4167 		NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_DELAYEDACKLOST);
4168 		tcp_enter_quickack_mode(sk, TCP_MAX_QUICKACKS);
4169 
4170 		if (tcp_is_sack(tp) && sysctl_tcp_dsack) {
4171 			u32 end_seq = TCP_SKB_CB(skb)->end_seq;
4172 
4173 			if (after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt))
4174 				end_seq = tp->rcv_nxt;
4175 			tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, end_seq);
4176 		}
4177 	}
4178 
4179 	tcp_send_ack(sk);
4180 }
4181 
4182 /* These routines update the SACK block as out-of-order packets arrive or
4183  * in-order packets close up the sequence space.
4184  */
tcp_sack_maybe_coalesce(struct tcp_sock * tp)4185 static void tcp_sack_maybe_coalesce(struct tcp_sock *tp)
4186 {
4187 	int this_sack;
4188 	struct tcp_sack_block *sp = &tp->selective_acks[0];
4189 	struct tcp_sack_block *swalk = sp + 1;
4190 
4191 	/* See if the recent change to the first SACK eats into
4192 	 * or hits the sequence space of other SACK blocks, if so coalesce.
4193 	 */
4194 	for (this_sack = 1; this_sack < tp->rx_opt.num_sacks;) {
4195 		if (tcp_sack_extend(sp, swalk->start_seq, swalk->end_seq)) {
4196 			int i;
4197 
4198 			/* Zap SWALK, by moving every further SACK up by one slot.
4199 			 * Decrease num_sacks.
4200 			 */
4201 			tp->rx_opt.num_sacks--;
4202 			for (i = this_sack; i < tp->rx_opt.num_sacks; i++)
4203 				sp[i] = sp[i + 1];
4204 			continue;
4205 		}
4206 		this_sack++, swalk++;
4207 	}
4208 }
4209 
tcp_sack_new_ofo_skb(struct sock * sk,u32 seq,u32 end_seq)4210 static void tcp_sack_new_ofo_skb(struct sock *sk, u32 seq, u32 end_seq)
4211 {
4212 	struct tcp_sock *tp = tcp_sk(sk);
4213 	struct tcp_sack_block *sp = &tp->selective_acks[0];
4214 	int cur_sacks = tp->rx_opt.num_sacks;
4215 	int this_sack;
4216 
4217 	if (!cur_sacks)
4218 		goto new_sack;
4219 
4220 	for (this_sack = 0; this_sack < cur_sacks; this_sack++, sp++) {
4221 		if (tcp_sack_extend(sp, seq, end_seq)) {
4222 			/* Rotate this_sack to the first one. */
4223 			for (; this_sack > 0; this_sack--, sp--)
4224 				swap(*sp, *(sp - 1));
4225 			if (cur_sacks > 1)
4226 				tcp_sack_maybe_coalesce(tp);
4227 			return;
4228 		}
4229 	}
4230 
4231 	/* Could not find an adjacent existing SACK, build a new one,
4232 	 * put it at the front, and shift everyone else down.  We
4233 	 * always know there is at least one SACK present already here.
4234 	 *
4235 	 * If the sack array is full, forget about the last one.
4236 	 */
4237 	if (this_sack >= TCP_NUM_SACKS) {
4238 		this_sack--;
4239 		tp->rx_opt.num_sacks--;
4240 		sp--;
4241 	}
4242 	for (; this_sack > 0; this_sack--, sp--)
4243 		*sp = *(sp - 1);
4244 
4245 new_sack:
4246 	/* Build the new head SACK, and we're done. */
4247 	sp->start_seq = seq;
4248 	sp->end_seq = end_seq;
4249 	tp->rx_opt.num_sacks++;
4250 }
4251 
4252 /* RCV.NXT advances, some SACKs should be eaten. */
4253 
tcp_sack_remove(struct tcp_sock * tp)4254 static void tcp_sack_remove(struct tcp_sock *tp)
4255 {
4256 	struct tcp_sack_block *sp = &tp->selective_acks[0];
4257 	int num_sacks = tp->rx_opt.num_sacks;
4258 	int this_sack;
4259 
4260 	/* Empty ofo queue, hence, all the SACKs are eaten. Clear. */
4261 	if (RB_EMPTY_ROOT(&tp->out_of_order_queue)) {
4262 		tp->rx_opt.num_sacks = 0;
4263 		return;
4264 	}
4265 
4266 	for (this_sack = 0; this_sack < num_sacks;) {
4267 		/* Check if the start of the sack is covered by RCV.NXT. */
4268 		if (!before(tp->rcv_nxt, sp->start_seq)) {
4269 			int i;
4270 
4271 			/* RCV.NXT must cover all the block! */
4272 			WARN_ON(before(tp->rcv_nxt, sp->end_seq));
4273 
4274 			/* Zap this SACK, by moving forward any other SACKS. */
4275 			for (i = this_sack+1; i < num_sacks; i++)
4276 				tp->selective_acks[i-1] = tp->selective_acks[i];
4277 			num_sacks--;
4278 			continue;
4279 		}
4280 		this_sack++;
4281 		sp++;
4282 	}
4283 	tp->rx_opt.num_sacks = num_sacks;
4284 }
4285 
4286 /**
4287  * tcp_try_coalesce - try to merge skb to prior one
4288  * @sk: socket
4289  * @to: prior buffer
4290  * @from: buffer to add in queue
4291  * @fragstolen: pointer to boolean
4292  *
4293  * Before queueing skb @from after @to, try to merge them
4294  * to reduce overall memory use and queue lengths, if cost is small.
4295  * Packets in ofo or receive queues can stay a long time.
4296  * Better try to coalesce them right now to avoid future collapses.
4297  * Returns true if caller should free @from instead of queueing it
4298  */
tcp_try_coalesce(struct sock * sk,struct sk_buff * to,struct sk_buff * from,bool * fragstolen)4299 static bool tcp_try_coalesce(struct sock *sk,
4300 			     struct sk_buff *to,
4301 			     struct sk_buff *from,
4302 			     bool *fragstolen)
4303 {
4304 	int delta;
4305 
4306 	*fragstolen = false;
4307 
4308 	/* Its possible this segment overlaps with prior segment in queue */
4309 	if (TCP_SKB_CB(from)->seq != TCP_SKB_CB(to)->end_seq)
4310 		return false;
4311 
4312 	if (!skb_try_coalesce(to, from, fragstolen, &delta))
4313 		return false;
4314 
4315 	atomic_add(delta, &sk->sk_rmem_alloc);
4316 	sk_mem_charge(sk, delta);
4317 	NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPRCVCOALESCE);
4318 	TCP_SKB_CB(to)->end_seq = TCP_SKB_CB(from)->end_seq;
4319 	TCP_SKB_CB(to)->ack_seq = TCP_SKB_CB(from)->ack_seq;
4320 	TCP_SKB_CB(to)->tcp_flags |= TCP_SKB_CB(from)->tcp_flags;
4321 	return true;
4322 }
4323 
tcp_ooo_try_coalesce(struct sock * sk,struct sk_buff * to,struct sk_buff * from,bool * fragstolen)4324 static bool tcp_ooo_try_coalesce(struct sock *sk,
4325 			     struct sk_buff *to,
4326 			     struct sk_buff *from,
4327 			     bool *fragstolen)
4328 {
4329 	bool res = tcp_try_coalesce(sk, to, from, fragstolen);
4330 
4331 	/* In case tcp_drop() is called later, update to->gso_segs */
4332 	if (res) {
4333 		u32 gso_segs = max_t(u16, 1, skb_shinfo(to)->gso_segs) +
4334 			       max_t(u16, 1, skb_shinfo(from)->gso_segs);
4335 
4336 		skb_shinfo(to)->gso_segs = min_t(u32, gso_segs, 0xFFFF);
4337 	}
4338 	return res;
4339 }
4340 
tcp_drop(struct sock * sk,struct sk_buff * skb)4341 static void tcp_drop(struct sock *sk, struct sk_buff *skb)
4342 {
4343 	sk_drops_add(sk, skb);
4344 	__kfree_skb(skb);
4345 }
4346 
4347 /* This one checks to see if we can put data from the
4348  * out_of_order queue into the receive_queue.
4349  */
tcp_ofo_queue(struct sock * sk)4350 static void tcp_ofo_queue(struct sock *sk)
4351 {
4352 	struct tcp_sock *tp = tcp_sk(sk);
4353 	__u32 dsack_high = tp->rcv_nxt;
4354 	bool fin, fragstolen, eaten;
4355 	struct sk_buff *skb, *tail;
4356 	struct rb_node *p;
4357 
4358 	p = rb_first(&tp->out_of_order_queue);
4359 	while (p) {
4360 		skb = rb_entry(p, struct sk_buff, rbnode);
4361 		if (after(TCP_SKB_CB(skb)->seq, tp->rcv_nxt))
4362 			break;
4363 
4364 		if (before(TCP_SKB_CB(skb)->seq, dsack_high)) {
4365 			__u32 dsack = dsack_high;
4366 			if (before(TCP_SKB_CB(skb)->end_seq, dsack_high))
4367 				dsack_high = TCP_SKB_CB(skb)->end_seq;
4368 			tcp_dsack_extend(sk, TCP_SKB_CB(skb)->seq, dsack);
4369 		}
4370 		p = rb_next(p);
4371 		rb_erase(&skb->rbnode, &tp->out_of_order_queue);
4372 
4373 		if (unlikely(!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt))) {
4374 			SOCK_DEBUG(sk, "ofo packet was already received\n");
4375 			tcp_drop(sk, skb);
4376 			continue;
4377 		}
4378 		SOCK_DEBUG(sk, "ofo requeuing : rcv_next %X seq %X - %X\n",
4379 			   tp->rcv_nxt, TCP_SKB_CB(skb)->seq,
4380 			   TCP_SKB_CB(skb)->end_seq);
4381 
4382 		tail = skb_peek_tail(&sk->sk_receive_queue);
4383 		eaten = tail && tcp_try_coalesce(sk, tail, skb, &fragstolen);
4384 		tcp_rcv_nxt_update(tp, TCP_SKB_CB(skb)->end_seq);
4385 		fin = TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN;
4386 		if (!eaten)
4387 			__skb_queue_tail(&sk->sk_receive_queue, skb);
4388 		else
4389 			kfree_skb_partial(skb, fragstolen);
4390 
4391 		if (unlikely(fin)) {
4392 			tcp_fin(sk);
4393 			/* tcp_fin() purges tp->out_of_order_queue,
4394 			 * so we must end this loop right now.
4395 			 */
4396 			break;
4397 		}
4398 	}
4399 }
4400 
4401 static bool tcp_prune_ofo_queue(struct sock *sk);
4402 static int tcp_prune_queue(struct sock *sk);
4403 
tcp_try_rmem_schedule(struct sock * sk,struct sk_buff * skb,unsigned int size)4404 static int tcp_try_rmem_schedule(struct sock *sk, struct sk_buff *skb,
4405 				 unsigned int size)
4406 {
4407 	if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
4408 	    !sk_rmem_schedule(sk, skb, size)) {
4409 
4410 		if (tcp_prune_queue(sk) < 0)
4411 			return -1;
4412 
4413 		if (!sk_rmem_schedule(sk, skb, size)) {
4414 			if (!tcp_prune_ofo_queue(sk))
4415 				return -1;
4416 
4417 			if (!sk_rmem_schedule(sk, skb, size))
4418 				return -1;
4419 		}
4420 	}
4421 	return 0;
4422 }
4423 
tcp_data_queue_ofo(struct sock * sk,struct sk_buff * skb)4424 static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb)
4425 {
4426 	struct tcp_sock *tp = tcp_sk(sk);
4427 	struct rb_node **p, *q, *parent;
4428 	struct sk_buff *skb1;
4429 	u32 seq, end_seq;
4430 	bool fragstolen;
4431 
4432 	tcp_ecn_check_ce(sk, skb);
4433 
4434 	if (unlikely(tcp_try_rmem_schedule(sk, skb, skb->truesize))) {
4435 		NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPOFODROP);
4436 		tcp_drop(sk, skb);
4437 		return;
4438 	}
4439 
4440 	/* Disable header prediction. */
4441 	tp->pred_flags = 0;
4442 	inet_csk_schedule_ack(sk);
4443 
4444 	NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPOFOQUEUE);
4445 	seq = TCP_SKB_CB(skb)->seq;
4446 	end_seq = TCP_SKB_CB(skb)->end_seq;
4447 	SOCK_DEBUG(sk, "out of order segment: rcv_next %X seq %X - %X\n",
4448 		   tp->rcv_nxt, seq, end_seq);
4449 
4450 	p = &tp->out_of_order_queue.rb_node;
4451 	if (RB_EMPTY_ROOT(&tp->out_of_order_queue)) {
4452 		/* Initial out of order segment, build 1 SACK. */
4453 		if (tcp_is_sack(tp)) {
4454 			tp->rx_opt.num_sacks = 1;
4455 			tp->selective_acks[0].start_seq = seq;
4456 			tp->selective_acks[0].end_seq = end_seq;
4457 		}
4458 		rb_link_node(&skb->rbnode, NULL, p);
4459 		rb_insert_color(&skb->rbnode, &tp->out_of_order_queue);
4460 		tp->ooo_last_skb = skb;
4461 		goto end;
4462 	}
4463 
4464 	/* In the typical case, we are adding an skb to the end of the list.
4465 	 * Use of ooo_last_skb avoids the O(Log(N)) rbtree lookup.
4466 	 */
4467 	if (tcp_ooo_try_coalesce(sk, tp->ooo_last_skb,
4468 				 skb, &fragstolen)) {
4469 coalesce_done:
4470 		/* For non sack flows, do not grow window to force DUPACK
4471 		 * and trigger fast retransmit.
4472 		 */
4473 		if (tcp_is_sack(tp))
4474 			tcp_grow_window(sk, skb);
4475 		kfree_skb_partial(skb, fragstolen);
4476 		skb = NULL;
4477 		goto add_sack;
4478 	}
4479 
4480 	/* Find place to insert this segment. Handle overlaps on the way. */
4481 	parent = NULL;
4482 	while (*p) {
4483 		parent = *p;
4484 		skb1 = rb_entry(parent, struct sk_buff, rbnode);
4485 		if (before(seq, TCP_SKB_CB(skb1)->seq)) {
4486 			p = &parent->rb_left;
4487 			continue;
4488 		}
4489 
4490 		if (before(seq, TCP_SKB_CB(skb1)->end_seq)) {
4491 			if (!after(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
4492 				/* All the bits are present. Drop. */
4493 				NET_INC_STATS(sock_net(sk),
4494 					      LINUX_MIB_TCPOFOMERGE);
4495 				tcp_drop(sk, skb);
4496 				skb = NULL;
4497 				tcp_dsack_set(sk, seq, end_seq);
4498 				goto add_sack;
4499 			}
4500 			if (after(seq, TCP_SKB_CB(skb1)->seq)) {
4501 				/* Partial overlap. */
4502 				tcp_dsack_set(sk, seq, TCP_SKB_CB(skb1)->end_seq);
4503 			} else {
4504 				/* skb's seq == skb1's seq and skb covers skb1.
4505 				 * Replace skb1 with skb.
4506 				 */
4507 				rb_replace_node(&skb1->rbnode, &skb->rbnode,
4508 						&tp->out_of_order_queue);
4509 				tcp_dsack_extend(sk,
4510 						 TCP_SKB_CB(skb1)->seq,
4511 						 TCP_SKB_CB(skb1)->end_seq);
4512 				NET_INC_STATS(sock_net(sk),
4513 					      LINUX_MIB_TCPOFOMERGE);
4514 				tcp_drop(sk, skb1);
4515 				goto merge_right;
4516 			}
4517 		} else if (tcp_ooo_try_coalesce(sk, skb1,
4518 						skb, &fragstolen)) {
4519 			goto coalesce_done;
4520 		}
4521 		p = &parent->rb_right;
4522 	}
4523 
4524 	/* Insert segment into RB tree. */
4525 	rb_link_node(&skb->rbnode, parent, p);
4526 	rb_insert_color(&skb->rbnode, &tp->out_of_order_queue);
4527 
4528 merge_right:
4529 	/* Remove other segments covered by skb. */
4530 	while ((q = rb_next(&skb->rbnode)) != NULL) {
4531 		skb1 = rb_entry(q, struct sk_buff, rbnode);
4532 		if (!after(end_seq, TCP_SKB_CB(skb1)->seq))
4533 			break;
4534 		if (before(end_seq, TCP_SKB_CB(skb1)->end_seq)) {
4535 			tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq,
4536 					 end_seq);
4537 			break;
4538 		}
4539 		rb_erase(&skb1->rbnode, &tp->out_of_order_queue);
4540 		tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq,
4541 				 TCP_SKB_CB(skb1)->end_seq);
4542 		NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPOFOMERGE);
4543 		tcp_drop(sk, skb1);
4544 	}
4545 	/* If there is no skb after us, we are the last_skb ! */
4546 	if (!q)
4547 		tp->ooo_last_skb = skb;
4548 
4549 add_sack:
4550 	if (tcp_is_sack(tp))
4551 		tcp_sack_new_ofo_skb(sk, seq, end_seq);
4552 end:
4553 	if (skb) {
4554 		/* For non sack flows, do not grow window to force DUPACK
4555 		 * and trigger fast retransmit.
4556 		 */
4557 		if (tcp_is_sack(tp))
4558 			tcp_grow_window(sk, skb);
4559 		skb_set_owner_r(skb, sk);
4560 	}
4561 }
4562 
tcp_queue_rcv(struct sock * sk,struct sk_buff * skb,int hdrlen,bool * fragstolen)4563 static int __must_check tcp_queue_rcv(struct sock *sk, struct sk_buff *skb, int hdrlen,
4564 		  bool *fragstolen)
4565 {
4566 	int eaten;
4567 	struct sk_buff *tail = skb_peek_tail(&sk->sk_receive_queue);
4568 
4569 	__skb_pull(skb, hdrlen);
4570 	eaten = (tail &&
4571 		 tcp_try_coalesce(sk, tail, skb, fragstolen)) ? 1 : 0;
4572 	tcp_rcv_nxt_update(tcp_sk(sk), TCP_SKB_CB(skb)->end_seq);
4573 	if (!eaten) {
4574 		__skb_queue_tail(&sk->sk_receive_queue, skb);
4575 		skb_set_owner_r(skb, sk);
4576 	}
4577 	return eaten;
4578 }
4579 
tcp_send_rcvq(struct sock * sk,struct msghdr * msg,size_t size)4580 int tcp_send_rcvq(struct sock *sk, struct msghdr *msg, size_t size)
4581 {
4582 	struct sk_buff *skb;
4583 	int err = -ENOMEM;
4584 	int data_len = 0;
4585 	bool fragstolen;
4586 
4587 	if (size == 0)
4588 		return 0;
4589 
4590 	if (size > PAGE_SIZE) {
4591 		int npages = min_t(size_t, size >> PAGE_SHIFT, MAX_SKB_FRAGS);
4592 
4593 		data_len = npages << PAGE_SHIFT;
4594 		size = data_len + (size & ~PAGE_MASK);
4595 	}
4596 	skb = alloc_skb_with_frags(size - data_len, data_len,
4597 				   PAGE_ALLOC_COSTLY_ORDER,
4598 				   &err, sk->sk_allocation);
4599 	if (!skb)
4600 		goto err;
4601 
4602 	skb_put(skb, size - data_len);
4603 	skb->data_len = data_len;
4604 	skb->len = size;
4605 
4606 	if (tcp_try_rmem_schedule(sk, skb, skb->truesize))
4607 		goto err_free;
4608 
4609 	err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, size);
4610 	if (err)
4611 		goto err_free;
4612 
4613 	TCP_SKB_CB(skb)->seq = tcp_sk(sk)->rcv_nxt;
4614 	TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(skb)->seq + size;
4615 	TCP_SKB_CB(skb)->ack_seq = tcp_sk(sk)->snd_una - 1;
4616 
4617 	if (tcp_queue_rcv(sk, skb, 0, &fragstolen)) {
4618 		WARN_ON_ONCE(fragstolen); /* should not happen */
4619 		__kfree_skb(skb);
4620 	}
4621 	return size;
4622 
4623 err_free:
4624 	kfree_skb(skb);
4625 err:
4626 	return err;
4627 
4628 }
4629 
tcp_data_queue(struct sock * sk,struct sk_buff * skb)4630 static void tcp_data_queue(struct sock *sk, struct sk_buff *skb)
4631 {
4632 	struct tcp_sock *tp = tcp_sk(sk);
4633 	bool fragstolen = false;
4634 	int eaten = -1;
4635 
4636 	if (TCP_SKB_CB(skb)->seq == TCP_SKB_CB(skb)->end_seq) {
4637 		__kfree_skb(skb);
4638 		return;
4639 	}
4640 	skb_dst_drop(skb);
4641 	__skb_pull(skb, tcp_hdr(skb)->doff * 4);
4642 
4643 	tcp_ecn_accept_cwr(tp, skb);
4644 
4645 	tp->rx_opt.dsack = 0;
4646 
4647 	/*  Queue data for delivery to the user.
4648 	 *  Packets in sequence go to the receive queue.
4649 	 *  Out of sequence packets to the out_of_order_queue.
4650 	 */
4651 	if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt) {
4652 		if (tcp_receive_window(tp) == 0)
4653 			goto out_of_window;
4654 
4655 		/* Ok. In sequence. In window. */
4656 		if (tp->ucopy.task == current &&
4657 		    tp->copied_seq == tp->rcv_nxt && tp->ucopy.len &&
4658 		    sock_owned_by_user(sk) && !tp->urg_data) {
4659 			int chunk = min_t(unsigned int, skb->len,
4660 					  tp->ucopy.len);
4661 
4662 			__set_current_state(TASK_RUNNING);
4663 
4664 			local_bh_enable();
4665 			if (!skb_copy_datagram_msg(skb, 0, tp->ucopy.msg, chunk)) {
4666 				tp->ucopy.len -= chunk;
4667 				tp->copied_seq += chunk;
4668 				eaten = (chunk == skb->len);
4669 				tcp_rcv_space_adjust(sk);
4670 			}
4671 			local_bh_disable();
4672 		}
4673 
4674 		if (eaten <= 0) {
4675 queue_and_out:
4676 			if (eaten < 0) {
4677 				if (skb_queue_len(&sk->sk_receive_queue) == 0)
4678 					sk_forced_mem_schedule(sk, skb->truesize);
4679 				else if (tcp_try_rmem_schedule(sk, skb, skb->truesize))
4680 					goto drop;
4681 			}
4682 			eaten = tcp_queue_rcv(sk, skb, 0, &fragstolen);
4683 		}
4684 		tcp_rcv_nxt_update(tp, TCP_SKB_CB(skb)->end_seq);
4685 		if (skb->len)
4686 			tcp_event_data_recv(sk, skb);
4687 		if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)
4688 			tcp_fin(sk);
4689 
4690 		if (!RB_EMPTY_ROOT(&tp->out_of_order_queue)) {
4691 			tcp_ofo_queue(sk);
4692 
4693 			/* RFC2581. 4.2. SHOULD send immediate ACK, when
4694 			 * gap in queue is filled.
4695 			 */
4696 			if (RB_EMPTY_ROOT(&tp->out_of_order_queue))
4697 				inet_csk(sk)->icsk_ack.pingpong = 0;
4698 		}
4699 
4700 		if (tp->rx_opt.num_sacks)
4701 			tcp_sack_remove(tp);
4702 
4703 		tcp_fast_path_check(sk);
4704 
4705 		if (eaten > 0)
4706 			kfree_skb_partial(skb, fragstolen);
4707 		if (!sock_flag(sk, SOCK_DEAD))
4708 			sk->sk_data_ready(sk);
4709 		return;
4710 	}
4711 
4712 	if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) {
4713 		/* A retransmit, 2nd most common case.  Force an immediate ack. */
4714 		NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_DELAYEDACKLOST);
4715 		tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq);
4716 
4717 out_of_window:
4718 		tcp_enter_quickack_mode(sk, TCP_MAX_QUICKACKS);
4719 		inet_csk_schedule_ack(sk);
4720 drop:
4721 		tcp_drop(sk, skb);
4722 		return;
4723 	}
4724 
4725 	/* Out of window. F.e. zero window probe. */
4726 	if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt + tcp_receive_window(tp)))
4727 		goto out_of_window;
4728 
4729 	if (before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) {
4730 		/* Partial packet, seq < rcv_next < end_seq */
4731 		SOCK_DEBUG(sk, "partial packet: rcv_next %X seq %X - %X\n",
4732 			   tp->rcv_nxt, TCP_SKB_CB(skb)->seq,
4733 			   TCP_SKB_CB(skb)->end_seq);
4734 
4735 		tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, tp->rcv_nxt);
4736 
4737 		/* If window is closed, drop tail of packet. But after
4738 		 * remembering D-SACK for its head made in previous line.
4739 		 */
4740 		if (!tcp_receive_window(tp))
4741 			goto out_of_window;
4742 		goto queue_and_out;
4743 	}
4744 
4745 	tcp_data_queue_ofo(sk, skb);
4746 }
4747 
tcp_skb_next(struct sk_buff * skb,struct sk_buff_head * list)4748 static struct sk_buff *tcp_skb_next(struct sk_buff *skb, struct sk_buff_head *list)
4749 {
4750 	if (list)
4751 		return !skb_queue_is_last(list, skb) ? skb->next : NULL;
4752 
4753 	return rb_entry_safe(rb_next(&skb->rbnode), struct sk_buff, rbnode);
4754 }
4755 
tcp_collapse_one(struct sock * sk,struct sk_buff * skb,struct sk_buff_head * list,struct rb_root * root)4756 static struct sk_buff *tcp_collapse_one(struct sock *sk, struct sk_buff *skb,
4757 					struct sk_buff_head *list,
4758 					struct rb_root *root)
4759 {
4760 	struct sk_buff *next = tcp_skb_next(skb, list);
4761 
4762 	if (list)
4763 		__skb_unlink(skb, list);
4764 	else
4765 		rb_erase(&skb->rbnode, root);
4766 
4767 	__kfree_skb(skb);
4768 	NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPRCVCOLLAPSED);
4769 
4770 	return next;
4771 }
4772 
4773 /* Insert skb into rb tree, ordered by TCP_SKB_CB(skb)->seq */
tcp_rbtree_insert(struct rb_root * root,struct sk_buff * skb)4774 static void tcp_rbtree_insert(struct rb_root *root, struct sk_buff *skb)
4775 {
4776 	struct rb_node **p = &root->rb_node;
4777 	struct rb_node *parent = NULL;
4778 	struct sk_buff *skb1;
4779 
4780 	while (*p) {
4781 		parent = *p;
4782 		skb1 = rb_entry(parent, struct sk_buff, rbnode);
4783 		if (before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb1)->seq))
4784 			p = &parent->rb_left;
4785 		else
4786 			p = &parent->rb_right;
4787 	}
4788 	rb_link_node(&skb->rbnode, parent, p);
4789 	rb_insert_color(&skb->rbnode, root);
4790 }
4791 
4792 /* Collapse contiguous sequence of skbs head..tail with
4793  * sequence numbers start..end.
4794  *
4795  * If tail is NULL, this means until the end of the queue.
4796  *
4797  * Segments with FIN/SYN are not collapsed (only because this
4798  * simplifies code)
4799  */
4800 static void
tcp_collapse(struct sock * sk,struct sk_buff_head * list,struct rb_root * root,struct sk_buff * head,struct sk_buff * tail,u32 start,u32 end)4801 tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root,
4802 	     struct sk_buff *head, struct sk_buff *tail, u32 start, u32 end)
4803 {
4804 	struct sk_buff *skb = head, *n;
4805 	struct sk_buff_head tmp;
4806 	bool end_of_skbs;
4807 
4808 	/* First, check that queue is collapsible and find
4809 	 * the point where collapsing can be useful.
4810 	 */
4811 restart:
4812 	for (end_of_skbs = true; skb != NULL && skb != tail; skb = n) {
4813 		n = tcp_skb_next(skb, list);
4814 
4815 		/* No new bits? It is possible on ofo queue. */
4816 		if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
4817 			skb = tcp_collapse_one(sk, skb, list, root);
4818 			if (!skb)
4819 				break;
4820 			goto restart;
4821 		}
4822 
4823 		/* The first skb to collapse is:
4824 		 * - not SYN/FIN and
4825 		 * - bloated or contains data before "start" or
4826 		 *   overlaps to the next one.
4827 		 */
4828 		if (!(TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN)) &&
4829 		    (tcp_win_from_space(skb->truesize) > skb->len ||
4830 		     before(TCP_SKB_CB(skb)->seq, start))) {
4831 			end_of_skbs = false;
4832 			break;
4833 		}
4834 
4835 		if (n && n != tail &&
4836 		    TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(n)->seq) {
4837 			end_of_skbs = false;
4838 			break;
4839 		}
4840 
4841 		/* Decided to skip this, advance start seq. */
4842 		start = TCP_SKB_CB(skb)->end_seq;
4843 	}
4844 	if (end_of_skbs ||
4845 	    (TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN)))
4846 		return;
4847 
4848 	__skb_queue_head_init(&tmp);
4849 
4850 	while (before(start, end)) {
4851 		int copy = min_t(int, SKB_MAX_ORDER(0, 0), end - start);
4852 		struct sk_buff *nskb;
4853 
4854 		nskb = alloc_skb(copy, GFP_ATOMIC);
4855 		if (!nskb)
4856 			break;
4857 
4858 		memcpy(nskb->cb, skb->cb, sizeof(skb->cb));
4859 		TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(nskb)->end_seq = start;
4860 		if (list)
4861 			__skb_queue_before(list, skb, nskb);
4862 		else
4863 			__skb_queue_tail(&tmp, nskb); /* defer rbtree insertion */
4864 		skb_set_owner_r(nskb, sk);
4865 
4866 		/* Copy data, releasing collapsed skbs. */
4867 		while (copy > 0) {
4868 			int offset = start - TCP_SKB_CB(skb)->seq;
4869 			int size = TCP_SKB_CB(skb)->end_seq - start;
4870 
4871 			BUG_ON(offset < 0);
4872 			if (size > 0) {
4873 				size = min(copy, size);
4874 				if (skb_copy_bits(skb, offset, skb_put(nskb, size), size))
4875 					BUG();
4876 				TCP_SKB_CB(nskb)->end_seq += size;
4877 				copy -= size;
4878 				start += size;
4879 			}
4880 			if (!before(start, TCP_SKB_CB(skb)->end_seq)) {
4881 				skb = tcp_collapse_one(sk, skb, list, root);
4882 				if (!skb ||
4883 				    skb == tail ||
4884 				    (TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN)))
4885 					goto end;
4886 			}
4887 		}
4888 	}
4889 end:
4890 	skb_queue_walk_safe(&tmp, skb, n)
4891 		tcp_rbtree_insert(root, skb);
4892 }
4893 
4894 /* Collapse ofo queue. Algorithm: select contiguous sequence of skbs
4895  * and tcp_collapse() them until all the queue is collapsed.
4896  */
tcp_collapse_ofo_queue(struct sock * sk)4897 static void tcp_collapse_ofo_queue(struct sock *sk)
4898 {
4899 	struct tcp_sock *tp = tcp_sk(sk);
4900 	u32 range_truesize, sum_tiny = 0;
4901 	struct sk_buff *skb, *head;
4902 	struct rb_node *p;
4903 	u32 start, end;
4904 
4905 	p = rb_first(&tp->out_of_order_queue);
4906 	skb = rb_entry_safe(p, struct sk_buff, rbnode);
4907 new_range:
4908 	if (!skb) {
4909 		p = rb_last(&tp->out_of_order_queue);
4910 		/* Note: This is possible p is NULL here. We do not
4911 		 * use rb_entry_safe(), as ooo_last_skb is valid only
4912 		 * if rbtree is not empty.
4913 		 */
4914 		tp->ooo_last_skb = rb_entry(p, struct sk_buff, rbnode);
4915 		return;
4916 	}
4917 	start = TCP_SKB_CB(skb)->seq;
4918 	end = TCP_SKB_CB(skb)->end_seq;
4919 	range_truesize = skb->truesize;
4920 
4921 	for (head = skb;;) {
4922 		skb = tcp_skb_next(skb, NULL);
4923 
4924 		/* Range is terminated when we see a gap or when
4925 		 * we are at the queue end.
4926 		 */
4927 		if (!skb ||
4928 		    after(TCP_SKB_CB(skb)->seq, end) ||
4929 		    before(TCP_SKB_CB(skb)->end_seq, start)) {
4930 			/* Do not attempt collapsing tiny skbs */
4931 			if (range_truesize != head->truesize ||
4932 			    end - start >= SKB_WITH_OVERHEAD(SK_MEM_QUANTUM)) {
4933 				tcp_collapse(sk, NULL, &tp->out_of_order_queue,
4934 					     head, skb, start, end);
4935 			} else {
4936 				sum_tiny += range_truesize;
4937 				if (sum_tiny > sk->sk_rcvbuf >> 3)
4938 					return;
4939 			}
4940 
4941 			goto new_range;
4942 		}
4943 
4944 		range_truesize += skb->truesize;
4945 		if (unlikely(before(TCP_SKB_CB(skb)->seq, start)))
4946 			start = TCP_SKB_CB(skb)->seq;
4947 		if (after(TCP_SKB_CB(skb)->end_seq, end))
4948 			end = TCP_SKB_CB(skb)->end_seq;
4949 	}
4950 }
4951 
4952 /*
4953  * Purge the out-of-order queue.
4954  * Drop at least 12.5 % of sk_rcvbuf to avoid malicious attacks.
4955  * Return true if queue was pruned.
4956  */
tcp_prune_ofo_queue(struct sock * sk)4957 static bool tcp_prune_ofo_queue(struct sock *sk)
4958 {
4959 	struct tcp_sock *tp = tcp_sk(sk);
4960 	struct rb_node *node, *prev;
4961 	int goal;
4962 
4963 	if (RB_EMPTY_ROOT(&tp->out_of_order_queue))
4964 		return false;
4965 
4966 	NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_OFOPRUNED);
4967 	goal = sk->sk_rcvbuf >> 3;
4968 	node = &tp->ooo_last_skb->rbnode;
4969 	do {
4970 		prev = rb_prev(node);
4971 		rb_erase(node, &tp->out_of_order_queue);
4972 		goal -= rb_to_skb(node)->truesize;
4973 		__kfree_skb(rb_to_skb(node));
4974 		if (!prev || goal <= 0) {
4975 			sk_mem_reclaim(sk);
4976 			if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf &&
4977 			    !tcp_under_memory_pressure(sk))
4978 				break;
4979 			goal = sk->sk_rcvbuf >> 3;
4980 		}
4981 
4982 		node = prev;
4983 	} while (node);
4984 	tp->ooo_last_skb = rb_entry(prev, struct sk_buff, rbnode);
4985 
4986 	/* Reset SACK state.  A conforming SACK implementation will
4987 	 * do the same at a timeout based retransmit.  When a connection
4988 	 * is in a sad state like this, we care only about integrity
4989 	 * of the connection not performance.
4990 	 */
4991 	if (tp->rx_opt.sack_ok)
4992 		tcp_sack_reset(&tp->rx_opt);
4993 
4994 	return true;
4995 }
4996 
4997 /* Reduce allocated memory if we can, trying to get
4998  * the socket within its memory limits again.
4999  *
5000  * Return less than zero if we should start dropping frames
5001  * until the socket owning process reads some of the data
5002  * to stabilize the situation.
5003  */
tcp_prune_queue(struct sock * sk)5004 static int tcp_prune_queue(struct sock *sk)
5005 {
5006 	struct tcp_sock *tp = tcp_sk(sk);
5007 
5008 	SOCK_DEBUG(sk, "prune_queue: c=%x\n", tp->copied_seq);
5009 
5010 	NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_PRUNECALLED);
5011 
5012 	if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
5013 		tcp_clamp_window(sk);
5014 	else if (tcp_under_memory_pressure(sk))
5015 		tp->rcv_ssthresh = min(tp->rcv_ssthresh, 4U * tp->advmss);
5016 
5017 	if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf)
5018 		return 0;
5019 
5020 	tcp_collapse_ofo_queue(sk);
5021 	if (!skb_queue_empty(&sk->sk_receive_queue))
5022 		tcp_collapse(sk, &sk->sk_receive_queue, NULL,
5023 			     skb_peek(&sk->sk_receive_queue),
5024 			     NULL,
5025 			     tp->copied_seq, tp->rcv_nxt);
5026 	sk_mem_reclaim(sk);
5027 
5028 	if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf)
5029 		return 0;
5030 
5031 	/* Collapsing did not help, destructive actions follow.
5032 	 * This must not ever occur. */
5033 
5034 	tcp_prune_ofo_queue(sk);
5035 
5036 	if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf)
5037 		return 0;
5038 
5039 	/* If we are really being abused, tell the caller to silently
5040 	 * drop receive data on the floor.  It will get retransmitted
5041 	 * and hopefully then we'll have sufficient space.
5042 	 */
5043 	NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_RCVPRUNED);
5044 
5045 	/* Massive buffer overcommit. */
5046 	tp->pred_flags = 0;
5047 	return -1;
5048 }
5049 
tcp_should_expand_sndbuf(const struct sock * sk)5050 static bool tcp_should_expand_sndbuf(const struct sock *sk)
5051 {
5052 	const struct tcp_sock *tp = tcp_sk(sk);
5053 
5054 	/* If the user specified a specific send buffer setting, do
5055 	 * not modify it.
5056 	 */
5057 	if (sk->sk_userlocks & SOCK_SNDBUF_LOCK)
5058 		return false;
5059 
5060 	/* If we are under global TCP memory pressure, do not expand.  */
5061 	if (tcp_under_memory_pressure(sk))
5062 		return false;
5063 
5064 	/* If we are under soft global TCP memory pressure, do not expand.  */
5065 	if (sk_memory_allocated(sk) >= sk_prot_mem_limits(sk, 0))
5066 		return false;
5067 
5068 	/* If we filled the congestion window, do not expand.  */
5069 	if (tcp_packets_in_flight(tp) >= tp->snd_cwnd)
5070 		return false;
5071 
5072 	return true;
5073 }
5074 
5075 /* When incoming ACK allowed to free some skb from write_queue,
5076  * we remember this event in flag SOCK_QUEUE_SHRUNK and wake up socket
5077  * on the exit from tcp input handler.
5078  *
5079  * PROBLEM: sndbuf expansion does not work well with largesend.
5080  */
tcp_new_space(struct sock * sk)5081 static void tcp_new_space(struct sock *sk)
5082 {
5083 	struct tcp_sock *tp = tcp_sk(sk);
5084 
5085 	if (tcp_should_expand_sndbuf(sk)) {
5086 		tcp_sndbuf_expand(sk);
5087 		tp->snd_cwnd_stamp = tcp_time_stamp;
5088 	}
5089 
5090 	sk->sk_write_space(sk);
5091 }
5092 
tcp_check_space(struct sock * sk)5093 static void tcp_check_space(struct sock *sk)
5094 {
5095 	if (sock_flag(sk, SOCK_QUEUE_SHRUNK)) {
5096 		sock_reset_flag(sk, SOCK_QUEUE_SHRUNK);
5097 		/* pairs with tcp_poll() */
5098 		smp_mb();
5099 		if (sk->sk_socket &&
5100 		    test_bit(SOCK_NOSPACE, &sk->sk_socket->flags))
5101 			tcp_new_space(sk);
5102 	}
5103 }
5104 
tcp_data_snd_check(struct sock * sk)5105 static inline void tcp_data_snd_check(struct sock *sk)
5106 {
5107 	tcp_push_pending_frames(sk);
5108 	tcp_check_space(sk);
5109 }
5110 
5111 /*
5112  * Check if sending an ack is needed.
5113  */
__tcp_ack_snd_check(struct sock * sk,int ofo_possible)5114 static void __tcp_ack_snd_check(struct sock *sk, int ofo_possible)
5115 {
5116 	struct tcp_sock *tp = tcp_sk(sk);
5117 
5118 	    /* More than one full frame received... */
5119 	if (((tp->rcv_nxt - tp->rcv_wup) > inet_csk(sk)->icsk_ack.rcv_mss &&
5120 	     /* ... and right edge of window advances far enough.
5121 	      * (tcp_recvmsg() will send ACK otherwise). Or...
5122 	      */
5123 	     __tcp_select_window(sk) >= tp->rcv_wnd) ||
5124 	    /* We ACK each frame or... */
5125 	    tcp_in_quickack_mode(sk) ||
5126 	    /* We have out of order data. */
5127 	    (ofo_possible && !RB_EMPTY_ROOT(&tp->out_of_order_queue))) {
5128 		/* Then ack it now */
5129 		tcp_send_ack(sk);
5130 	} else {
5131 		/* Else, send delayed ack. */
5132 		tcp_send_delayed_ack(sk);
5133 	}
5134 }
5135 
tcp_ack_snd_check(struct sock * sk)5136 static inline void tcp_ack_snd_check(struct sock *sk)
5137 {
5138 	if (!inet_csk_ack_scheduled(sk)) {
5139 		/* We sent a data segment already. */
5140 		return;
5141 	}
5142 	__tcp_ack_snd_check(sk, 1);
5143 }
5144 
5145 /*
5146  *	This routine is only called when we have urgent data
5147  *	signaled. Its the 'slow' part of tcp_urg. It could be
5148  *	moved inline now as tcp_urg is only called from one
5149  *	place. We handle URGent data wrong. We have to - as
5150  *	BSD still doesn't use the correction from RFC961.
5151  *	For 1003.1g we should support a new option TCP_STDURG to permit
5152  *	either form (or just set the sysctl tcp_stdurg).
5153  */
5154 
tcp_check_urg(struct sock * sk,const struct tcphdr * th)5155 static void tcp_check_urg(struct sock *sk, const struct tcphdr *th)
5156 {
5157 	struct tcp_sock *tp = tcp_sk(sk);
5158 	u32 ptr = ntohs(th->urg_ptr);
5159 
5160 	if (ptr && !sysctl_tcp_stdurg)
5161 		ptr--;
5162 	ptr += ntohl(th->seq);
5163 
5164 	/* Ignore urgent data that we've already seen and read. */
5165 	if (after(tp->copied_seq, ptr))
5166 		return;
5167 
5168 	/* Do not replay urg ptr.
5169 	 *
5170 	 * NOTE: interesting situation not covered by specs.
5171 	 * Misbehaving sender may send urg ptr, pointing to segment,
5172 	 * which we already have in ofo queue. We are not able to fetch
5173 	 * such data and will stay in TCP_URG_NOTYET until will be eaten
5174 	 * by recvmsg(). Seems, we are not obliged to handle such wicked
5175 	 * situations. But it is worth to think about possibility of some
5176 	 * DoSes using some hypothetical application level deadlock.
5177 	 */
5178 	if (before(ptr, tp->rcv_nxt))
5179 		return;
5180 
5181 	/* Do we already have a newer (or duplicate) urgent pointer? */
5182 	if (tp->urg_data && !after(ptr, tp->urg_seq))
5183 		return;
5184 
5185 	/* Tell the world about our new urgent pointer. */
5186 	sk_send_sigurg(sk);
5187 
5188 	/* We may be adding urgent data when the last byte read was
5189 	 * urgent. To do this requires some care. We cannot just ignore
5190 	 * tp->copied_seq since we would read the last urgent byte again
5191 	 * as data, nor can we alter copied_seq until this data arrives
5192 	 * or we break the semantics of SIOCATMARK (and thus sockatmark())
5193 	 *
5194 	 * NOTE. Double Dutch. Rendering to plain English: author of comment
5195 	 * above did something sort of 	send("A", MSG_OOB); send("B", MSG_OOB);
5196 	 * and expect that both A and B disappear from stream. This is _wrong_.
5197 	 * Though this happens in BSD with high probability, this is occasional.
5198 	 * Any application relying on this is buggy. Note also, that fix "works"
5199 	 * only in this artificial test. Insert some normal data between A and B and we will
5200 	 * decline of BSD again. Verdict: it is better to remove to trap
5201 	 * buggy users.
5202 	 */
5203 	if (tp->urg_seq == tp->copied_seq && tp->urg_data &&
5204 	    !sock_flag(sk, SOCK_URGINLINE) && tp->copied_seq != tp->rcv_nxt) {
5205 		struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
5206 		tp->copied_seq++;
5207 		if (skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq)) {
5208 			__skb_unlink(skb, &sk->sk_receive_queue);
5209 			__kfree_skb(skb);
5210 		}
5211 	}
5212 
5213 	tp->urg_data = TCP_URG_NOTYET;
5214 	tp->urg_seq = ptr;
5215 
5216 	/* Disable header prediction. */
5217 	tp->pred_flags = 0;
5218 }
5219 
5220 /* This is the 'fast' part of urgent handling. */
tcp_urg(struct sock * sk,struct sk_buff * skb,const struct tcphdr * th)5221 static void tcp_urg(struct sock *sk, struct sk_buff *skb, const struct tcphdr *th)
5222 {
5223 	struct tcp_sock *tp = tcp_sk(sk);
5224 
5225 	/* Check if we get a new urgent pointer - normally not. */
5226 	if (th->urg)
5227 		tcp_check_urg(sk, th);
5228 
5229 	/* Do we wait for any urgent data? - normally not... */
5230 	if (tp->urg_data == TCP_URG_NOTYET) {
5231 		u32 ptr = tp->urg_seq - ntohl(th->seq) + (th->doff * 4) -
5232 			  th->syn;
5233 
5234 		/* Is the urgent pointer pointing into this packet? */
5235 		if (ptr < skb->len) {
5236 			u8 tmp;
5237 			if (skb_copy_bits(skb, ptr, &tmp, 1))
5238 				BUG();
5239 			tp->urg_data = TCP_URG_VALID | tmp;
5240 			if (!sock_flag(sk, SOCK_DEAD))
5241 				sk->sk_data_ready(sk);
5242 		}
5243 	}
5244 }
5245 
tcp_copy_to_iovec(struct sock * sk,struct sk_buff * skb,int hlen)5246 static int tcp_copy_to_iovec(struct sock *sk, struct sk_buff *skb, int hlen)
5247 {
5248 	struct tcp_sock *tp = tcp_sk(sk);
5249 	int chunk = skb->len - hlen;
5250 	int err;
5251 
5252 	local_bh_enable();
5253 	if (skb_csum_unnecessary(skb))
5254 		err = skb_copy_datagram_msg(skb, hlen, tp->ucopy.msg, chunk);
5255 	else
5256 		err = skb_copy_and_csum_datagram_msg(skb, hlen, tp->ucopy.msg);
5257 
5258 	if (!err) {
5259 		tp->ucopy.len -= chunk;
5260 		tp->copied_seq += chunk;
5261 		tcp_rcv_space_adjust(sk);
5262 	}
5263 
5264 	local_bh_disable();
5265 	return err;
5266 }
5267 
__tcp_checksum_complete_user(struct sock * sk,struct sk_buff * skb)5268 static __sum16 __tcp_checksum_complete_user(struct sock *sk,
5269 					    struct sk_buff *skb)
5270 {
5271 	__sum16 result;
5272 
5273 	if (sock_owned_by_user(sk)) {
5274 		local_bh_enable();
5275 		result = __tcp_checksum_complete(skb);
5276 		local_bh_disable();
5277 	} else {
5278 		result = __tcp_checksum_complete(skb);
5279 	}
5280 	return result;
5281 }
5282 
tcp_checksum_complete_user(struct sock * sk,struct sk_buff * skb)5283 static inline bool tcp_checksum_complete_user(struct sock *sk,
5284 					     struct sk_buff *skb)
5285 {
5286 	return !skb_csum_unnecessary(skb) &&
5287 	       __tcp_checksum_complete_user(sk, skb);
5288 }
5289 
5290 /* Does PAWS and seqno based validation of an incoming segment, flags will
5291  * play significant role here.
5292  */
tcp_validate_incoming(struct sock * sk,struct sk_buff * skb,const struct tcphdr * th,int syn_inerr)5293 static bool tcp_validate_incoming(struct sock *sk, struct sk_buff *skb,
5294 				  const struct tcphdr *th, int syn_inerr)
5295 {
5296 	struct tcp_sock *tp = tcp_sk(sk);
5297 
5298 	/* RFC1323: H1. Apply PAWS check first. */
5299 	if (tcp_fast_parse_options(skb, th, tp) && tp->rx_opt.saw_tstamp &&
5300 	    tcp_paws_discard(sk, skb)) {
5301 		if (!th->rst) {
5302 			NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_PAWSESTABREJECTED);
5303 			if (!tcp_oow_rate_limited(sock_net(sk), skb,
5304 						  LINUX_MIB_TCPACKSKIPPEDPAWS,
5305 						  &tp->last_oow_ack_time))
5306 				tcp_send_dupack(sk, skb);
5307 			goto discard;
5308 		}
5309 		/* Reset is accepted even if it did not pass PAWS. */
5310 	}
5311 
5312 	/* Step 1: check sequence number */
5313 	if (!tcp_sequence(tp, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq)) {
5314 		/* RFC793, page 37: "In all states except SYN-SENT, all reset
5315 		 * (RST) segments are validated by checking their SEQ-fields."
5316 		 * And page 69: "If an incoming segment is not acceptable,
5317 		 * an acknowledgment should be sent in reply (unless the RST
5318 		 * bit is set, if so drop the segment and return)".
5319 		 */
5320 		if (!th->rst) {
5321 			if (th->syn)
5322 				goto syn_challenge;
5323 			if (!tcp_oow_rate_limited(sock_net(sk), skb,
5324 						  LINUX_MIB_TCPACKSKIPPEDSEQ,
5325 						  &tp->last_oow_ack_time))
5326 				tcp_send_dupack(sk, skb);
5327 		}
5328 		goto discard;
5329 	}
5330 
5331 	/* Step 2: check RST bit */
5332 	if (th->rst) {
5333 		/* RFC 5961 3.2 :
5334 		 * If sequence number exactly matches RCV.NXT, then
5335 		 *     RESET the connection
5336 		 * else
5337 		 *     Send a challenge ACK
5338 		 */
5339 		if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt)
5340 			tcp_reset(sk);
5341 		else
5342 			tcp_send_challenge_ack(sk, skb);
5343 		goto discard;
5344 	}
5345 
5346 	/* step 3: check security and precedence [ignored] */
5347 
5348 	/* step 4: Check for a SYN
5349 	 * RFC 5961 4.2 : Send a challenge ack
5350 	 */
5351 	if (th->syn) {
5352 syn_challenge:
5353 		if (syn_inerr)
5354 			TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_INERRS);
5355 		NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPSYNCHALLENGE);
5356 		tcp_send_challenge_ack(sk, skb);
5357 		goto discard;
5358 	}
5359 
5360 	return true;
5361 
5362 discard:
5363 	tcp_drop(sk, skb);
5364 	return false;
5365 }
5366 
5367 /*
5368  *	TCP receive function for the ESTABLISHED state.
5369  *
5370  *	It is split into a fast path and a slow path. The fast path is
5371  * 	disabled when:
5372  *	- A zero window was announced from us - zero window probing
5373  *        is only handled properly in the slow path.
5374  *	- Out of order segments arrived.
5375  *	- Urgent data is expected.
5376  *	- There is no buffer space left
5377  *	- Unexpected TCP flags/window values/header lengths are received
5378  *	  (detected by checking the TCP header against pred_flags)
5379  *	- Data is sent in both directions. Fast path only supports pure senders
5380  *	  or pure receivers (this means either the sequence number or the ack
5381  *	  value must stay constant)
5382  *	- Unexpected TCP option.
5383  *
5384  *	When these conditions are not satisfied it drops into a standard
5385  *	receive procedure patterned after RFC793 to handle all cases.
5386  *	The first three cases are guaranteed by proper pred_flags setting,
5387  *	the rest is checked inline. Fast processing is turned on in
5388  *	tcp_data_queue when everything is OK.
5389  */
tcp_rcv_established(struct sock * sk,struct sk_buff * skb,const struct tcphdr * th,unsigned int len)5390 void tcp_rcv_established(struct sock *sk, struct sk_buff *skb,
5391 			 const struct tcphdr *th, unsigned int len)
5392 {
5393 	struct tcp_sock *tp = tcp_sk(sk);
5394 
5395 	if (unlikely(!sk->sk_rx_dst))
5396 		inet_csk(sk)->icsk_af_ops->sk_rx_dst_set(sk, skb);
5397 	/*
5398 	 *	Header prediction.
5399 	 *	The code loosely follows the one in the famous
5400 	 *	"30 instruction TCP receive" Van Jacobson mail.
5401 	 *
5402 	 *	Van's trick is to deposit buffers into socket queue
5403 	 *	on a device interrupt, to call tcp_recv function
5404 	 *	on the receive process context and checksum and copy
5405 	 *	the buffer to user space. smart...
5406 	 *
5407 	 *	Our current scheme is not silly either but we take the
5408 	 *	extra cost of the net_bh soft interrupt processing...
5409 	 *	We do checksum and copy also but from device to kernel.
5410 	 */
5411 
5412 	tp->rx_opt.saw_tstamp = 0;
5413 
5414 	/*	pred_flags is 0xS?10 << 16 + snd_wnd
5415 	 *	if header_prediction is to be made
5416 	 *	'S' will always be tp->tcp_header_len >> 2
5417 	 *	'?' will be 0 for the fast path, otherwise pred_flags is 0 to
5418 	 *  turn it off	(when there are holes in the receive
5419 	 *	 space for instance)
5420 	 *	PSH flag is ignored.
5421 	 */
5422 
5423 	if ((tcp_flag_word(th) & TCP_HP_BITS) == tp->pred_flags &&
5424 	    TCP_SKB_CB(skb)->seq == tp->rcv_nxt &&
5425 	    !after(TCP_SKB_CB(skb)->ack_seq, tp->snd_nxt)) {
5426 		int tcp_header_len = tp->tcp_header_len;
5427 
5428 		/* Timestamp header prediction: tcp_header_len
5429 		 * is automatically equal to th->doff*4 due to pred_flags
5430 		 * match.
5431 		 */
5432 
5433 		/* Check timestamp */
5434 		if (tcp_header_len == sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) {
5435 			/* No? Slow path! */
5436 			if (!tcp_parse_aligned_timestamp(tp, th))
5437 				goto slow_path;
5438 
5439 			/* If PAWS failed, check it more carefully in slow path */
5440 			if ((s32)(tp->rx_opt.rcv_tsval - tp->rx_opt.ts_recent) < 0)
5441 				goto slow_path;
5442 
5443 			/* DO NOT update ts_recent here, if checksum fails
5444 			 * and timestamp was corrupted part, it will result
5445 			 * in a hung connection since we will drop all
5446 			 * future packets due to the PAWS test.
5447 			 */
5448 		}
5449 
5450 		if (len <= tcp_header_len) {
5451 			/* Bulk data transfer: sender */
5452 			if (len == tcp_header_len) {
5453 				/* Predicted packet is in window by definition.
5454 				 * seq == rcv_nxt and rcv_wup <= rcv_nxt.
5455 				 * Hence, check seq<=rcv_wup reduces to:
5456 				 */
5457 				if (tcp_header_len ==
5458 				    (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) &&
5459 				    tp->rcv_nxt == tp->rcv_wup)
5460 					tcp_store_ts_recent(tp);
5461 
5462 				/* We know that such packets are checksummed
5463 				 * on entry.
5464 				 */
5465 				tcp_ack(sk, skb, 0);
5466 				__kfree_skb(skb);
5467 				tcp_data_snd_check(sk);
5468 				return;
5469 			} else { /* Header too small */
5470 				TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_INERRS);
5471 				goto discard;
5472 			}
5473 		} else {
5474 			int eaten = 0;
5475 			bool fragstolen = false;
5476 
5477 			if (tp->ucopy.task == current &&
5478 			    tp->copied_seq == tp->rcv_nxt &&
5479 			    len - tcp_header_len <= tp->ucopy.len &&
5480 			    sock_owned_by_user(sk)) {
5481 				__set_current_state(TASK_RUNNING);
5482 
5483 				if (!tcp_copy_to_iovec(sk, skb, tcp_header_len)) {
5484 					/* Predicted packet is in window by definition.
5485 					 * seq == rcv_nxt and rcv_wup <= rcv_nxt.
5486 					 * Hence, check seq<=rcv_wup reduces to:
5487 					 */
5488 					if (tcp_header_len ==
5489 					    (sizeof(struct tcphdr) +
5490 					     TCPOLEN_TSTAMP_ALIGNED) &&
5491 					    tp->rcv_nxt == tp->rcv_wup)
5492 						tcp_store_ts_recent(tp);
5493 
5494 					tcp_rcv_rtt_measure_ts(sk, skb);
5495 
5496 					__skb_pull(skb, tcp_header_len);
5497 					tcp_rcv_nxt_update(tp, TCP_SKB_CB(skb)->end_seq);
5498 					NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPHPHITSTOUSER);
5499 					eaten = 1;
5500 				}
5501 			}
5502 			if (!eaten) {
5503 				if (tcp_checksum_complete_user(sk, skb))
5504 					goto csum_error;
5505 
5506 				if ((int)skb->truesize > sk->sk_forward_alloc)
5507 					goto step5;
5508 
5509 				/* Predicted packet is in window by definition.
5510 				 * seq == rcv_nxt and rcv_wup <= rcv_nxt.
5511 				 * Hence, check seq<=rcv_wup reduces to:
5512 				 */
5513 				if (tcp_header_len ==
5514 				    (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) &&
5515 				    tp->rcv_nxt == tp->rcv_wup)
5516 					tcp_store_ts_recent(tp);
5517 
5518 				tcp_rcv_rtt_measure_ts(sk, skb);
5519 
5520 				NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPHPHITS);
5521 
5522 				/* Bulk data transfer: receiver */
5523 				eaten = tcp_queue_rcv(sk, skb, tcp_header_len,
5524 						      &fragstolen);
5525 			}
5526 
5527 			tcp_event_data_recv(sk, skb);
5528 
5529 			if (TCP_SKB_CB(skb)->ack_seq != tp->snd_una) {
5530 				/* Well, only one small jumplet in fast path... */
5531 				tcp_ack(sk, skb, FLAG_DATA);
5532 				tcp_data_snd_check(sk);
5533 				if (!inet_csk_ack_scheduled(sk))
5534 					goto no_ack;
5535 			} else {
5536 				tcp_update_wl(tp, TCP_SKB_CB(skb)->seq);
5537 			}
5538 
5539 			__tcp_ack_snd_check(sk, 0);
5540 no_ack:
5541 			if (eaten)
5542 				kfree_skb_partial(skb, fragstolen);
5543 			sk->sk_data_ready(sk);
5544 			return;
5545 		}
5546 	}
5547 
5548 slow_path:
5549 	if (len < (th->doff << 2) || tcp_checksum_complete_user(sk, skb))
5550 		goto csum_error;
5551 
5552 	if (!th->ack && !th->rst && !th->syn)
5553 		goto discard;
5554 
5555 	/*
5556 	 *	Standard slow path.
5557 	 */
5558 
5559 	if (!tcp_validate_incoming(sk, skb, th, 1))
5560 		return;
5561 
5562 step5:
5563 	if (tcp_ack(sk, skb, FLAG_SLOWPATH | FLAG_UPDATE_TS_RECENT) < 0)
5564 		goto discard;
5565 
5566 	tcp_rcv_rtt_measure_ts(sk, skb);
5567 
5568 	/* Process urgent data. */
5569 	tcp_urg(sk, skb, th);
5570 
5571 	/* step 7: process the segment text */
5572 	tcp_data_queue(sk, skb);
5573 
5574 	tcp_data_snd_check(sk);
5575 	tcp_ack_snd_check(sk);
5576 	return;
5577 
5578 csum_error:
5579 	TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_CSUMERRORS);
5580 	TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_INERRS);
5581 
5582 discard:
5583 	tcp_drop(sk, skb);
5584 }
5585 EXPORT_SYMBOL(tcp_rcv_established);
5586 
tcp_finish_connect(struct sock * sk,struct sk_buff * skb)5587 void tcp_finish_connect(struct sock *sk, struct sk_buff *skb)
5588 {
5589 	struct tcp_sock *tp = tcp_sk(sk);
5590 	struct inet_connection_sock *icsk = inet_csk(sk);
5591 
5592 	tcp_set_state(sk, TCP_ESTABLISHED);
5593 	icsk->icsk_ack.lrcvtime = tcp_time_stamp;
5594 
5595 	if (skb) {
5596 		icsk->icsk_af_ops->sk_rx_dst_set(sk, skb);
5597 		security_inet_conn_established(sk, skb);
5598 	}
5599 
5600 	/* Make sure socket is routed, for correct metrics.  */
5601 	icsk->icsk_af_ops->rebuild_header(sk);
5602 
5603 	tcp_init_metrics(sk);
5604 
5605 	tcp_init_congestion_control(sk);
5606 
5607 	/* Prevent spurious tcp_cwnd_restart() on first data
5608 	 * packet.
5609 	 */
5610 	tp->lsndtime = tcp_time_stamp;
5611 
5612 	tcp_init_buffer_space(sk);
5613 
5614 	if (sock_flag(sk, SOCK_KEEPOPEN))
5615 		inet_csk_reset_keepalive_timer(sk, keepalive_time_when(tp));
5616 
5617 	if (!tp->rx_opt.snd_wscale)
5618 		__tcp_fast_path_on(tp, tp->snd_wnd);
5619 	else
5620 		tp->pred_flags = 0;
5621 
5622 }
5623 
tcp_rcv_fastopen_synack(struct sock * sk,struct sk_buff * synack,struct tcp_fastopen_cookie * cookie)5624 static bool tcp_rcv_fastopen_synack(struct sock *sk, struct sk_buff *synack,
5625 				    struct tcp_fastopen_cookie *cookie)
5626 {
5627 	struct tcp_sock *tp = tcp_sk(sk);
5628 	struct sk_buff *data = tp->syn_data ? tcp_write_queue_head(sk) : NULL;
5629 	u16 mss = tp->rx_opt.mss_clamp, try_exp = 0;
5630 	bool syn_drop = false;
5631 
5632 	if (mss == tp->rx_opt.user_mss) {
5633 		struct tcp_options_received opt;
5634 
5635 		/* Get original SYNACK MSS value if user MSS sets mss_clamp */
5636 		tcp_clear_options(&opt);
5637 		opt.user_mss = opt.mss_clamp = 0;
5638 		tcp_parse_options(synack, &opt, 0, NULL);
5639 		mss = opt.mss_clamp;
5640 	}
5641 
5642 	if (!tp->syn_fastopen) {
5643 		/* Ignore an unsolicited cookie */
5644 		cookie->len = -1;
5645 	} else if (tp->total_retrans) {
5646 		/* SYN timed out and the SYN-ACK neither has a cookie nor
5647 		 * acknowledges data. Presumably the remote received only
5648 		 * the retransmitted (regular) SYNs: either the original
5649 		 * SYN-data or the corresponding SYN-ACK was dropped.
5650 		 */
5651 		syn_drop = (cookie->len < 0 && data);
5652 	} else if (cookie->len < 0 && !tp->syn_data) {
5653 		/* We requested a cookie but didn't get it. If we did not use
5654 		 * the (old) exp opt format then try so next time (try_exp=1).
5655 		 * Otherwise we go back to use the RFC7413 opt (try_exp=2).
5656 		 */
5657 		try_exp = tp->syn_fastopen_exp ? 2 : 1;
5658 	}
5659 
5660 	tcp_fastopen_cache_set(sk, mss, cookie, syn_drop, try_exp);
5661 
5662 	if (data) { /* Retransmit unacked data in SYN */
5663 		tcp_for_write_queue_from(data, sk) {
5664 			if (data == tcp_send_head(sk) ||
5665 			    __tcp_retransmit_skb(sk, data))
5666 				break;
5667 		}
5668 		tcp_rearm_rto(sk);
5669 		NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPFASTOPENACTIVEFAIL);
5670 		return true;
5671 	}
5672 	tp->syn_data_acked = tp->syn_data;
5673 	if (tp->syn_data_acked)
5674 		NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPFASTOPENACTIVE);
5675 	return false;
5676 }
5677 
tcp_rcv_synsent_state_process(struct sock * sk,struct sk_buff * skb,const struct tcphdr * th)5678 static int tcp_rcv_synsent_state_process(struct sock *sk, struct sk_buff *skb,
5679 					 const struct tcphdr *th)
5680 {
5681 	struct inet_connection_sock *icsk = inet_csk(sk);
5682 	struct tcp_sock *tp = tcp_sk(sk);
5683 	struct tcp_fastopen_cookie foc = { .len = -1 };
5684 	int saved_clamp = tp->rx_opt.mss_clamp;
5685 	bool fastopen_fail;
5686 
5687 	tcp_parse_options(skb, &tp->rx_opt, 0, &foc);
5688 	if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr)
5689 		tp->rx_opt.rcv_tsecr -= tp->tsoffset;
5690 
5691 	if (th->ack) {
5692 		/* rfc793:
5693 		 * "If the state is SYN-SENT then
5694 		 *    first check the ACK bit
5695 		 *      If the ACK bit is set
5696 		 *	  If SEG.ACK =< ISS, or SEG.ACK > SND.NXT, send
5697 		 *        a reset (unless the RST bit is set, if so drop
5698 		 *        the segment and return)"
5699 		 */
5700 		if (!after(TCP_SKB_CB(skb)->ack_seq, tp->snd_una) ||
5701 		    after(TCP_SKB_CB(skb)->ack_seq, tp->snd_nxt))
5702 			goto reset_and_undo;
5703 
5704 		if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr &&
5705 		    !between(tp->rx_opt.rcv_tsecr, tp->retrans_stamp,
5706 			     tcp_time_stamp)) {
5707 			NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_PAWSACTIVEREJECTED);
5708 			goto reset_and_undo;
5709 		}
5710 
5711 		/* Now ACK is acceptable.
5712 		 *
5713 		 * "If the RST bit is set
5714 		 *    If the ACK was acceptable then signal the user "error:
5715 		 *    connection reset", drop the segment, enter CLOSED state,
5716 		 *    delete TCB, and return."
5717 		 */
5718 
5719 		if (th->rst) {
5720 			tcp_reset(sk);
5721 			goto discard;
5722 		}
5723 
5724 		/* rfc793:
5725 		 *   "fifth, if neither of the SYN or RST bits is set then
5726 		 *    drop the segment and return."
5727 		 *
5728 		 *    See note below!
5729 		 *                                        --ANK(990513)
5730 		 */
5731 		if (!th->syn)
5732 			goto discard_and_undo;
5733 
5734 		/* rfc793:
5735 		 *   "If the SYN bit is on ...
5736 		 *    are acceptable then ...
5737 		 *    (our SYN has been ACKed), change the connection
5738 		 *    state to ESTABLISHED..."
5739 		 */
5740 
5741 		tcp_ecn_rcv_synack(tp, th);
5742 
5743 		tcp_init_wl(tp, TCP_SKB_CB(skb)->seq);
5744 		tcp_ack(sk, skb, FLAG_SLOWPATH);
5745 
5746 		/* Ok.. it's good. Set up sequence numbers and
5747 		 * move to established.
5748 		 */
5749 		tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1;
5750 		tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
5751 
5752 		/* RFC1323: The window in SYN & SYN/ACK segments is
5753 		 * never scaled.
5754 		 */
5755 		tp->snd_wnd = ntohs(th->window);
5756 
5757 		if (!tp->rx_opt.wscale_ok) {
5758 			tp->rx_opt.snd_wscale = tp->rx_opt.rcv_wscale = 0;
5759 			tp->window_clamp = min(tp->window_clamp, 65535U);
5760 		}
5761 
5762 		if (tp->rx_opt.saw_tstamp) {
5763 			tp->rx_opt.tstamp_ok	   = 1;
5764 			tp->tcp_header_len =
5765 				sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
5766 			tp->advmss	    -= TCPOLEN_TSTAMP_ALIGNED;
5767 			tcp_store_ts_recent(tp);
5768 		} else {
5769 			tp->tcp_header_len = sizeof(struct tcphdr);
5770 		}
5771 
5772 		if (tcp_is_sack(tp) && sysctl_tcp_fack)
5773 			tcp_enable_fack(tp);
5774 
5775 		tcp_mtup_init(sk);
5776 		tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
5777 		tcp_initialize_rcv_mss(sk);
5778 
5779 		/* Remember, tcp_poll() does not lock socket!
5780 		 * Change state from SYN-SENT only after copied_seq
5781 		 * is initialized. */
5782 		tp->copied_seq = tp->rcv_nxt;
5783 
5784 		smp_mb();
5785 
5786 		tcp_finish_connect(sk, skb);
5787 
5788 		fastopen_fail = (tp->syn_fastopen || tp->syn_data) &&
5789 				tcp_rcv_fastopen_synack(sk, skb, &foc);
5790 
5791 		if (!sock_flag(sk, SOCK_DEAD)) {
5792 			sk->sk_state_change(sk);
5793 			sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT);
5794 		}
5795 		if (fastopen_fail)
5796 			return -1;
5797 		if (sk->sk_write_pending ||
5798 		    icsk->icsk_accept_queue.rskq_defer_accept ||
5799 		    icsk->icsk_ack.pingpong) {
5800 			/* Save one ACK. Data will be ready after
5801 			 * several ticks, if write_pending is set.
5802 			 *
5803 			 * It may be deleted, but with this feature tcpdumps
5804 			 * look so _wonderfully_ clever, that I was not able
5805 			 * to stand against the temptation 8)     --ANK
5806 			 */
5807 			inet_csk_schedule_ack(sk);
5808 			tcp_enter_quickack_mode(sk, TCP_MAX_QUICKACKS);
5809 			inet_csk_reset_xmit_timer(sk, ICSK_TIME_DACK,
5810 						  TCP_DELACK_MAX, TCP_RTO_MAX);
5811 
5812 discard:
5813 			tcp_drop(sk, skb);
5814 			return 0;
5815 		} else {
5816 			tcp_send_ack(sk);
5817 		}
5818 		return -1;
5819 	}
5820 
5821 	/* No ACK in the segment */
5822 
5823 	if (th->rst) {
5824 		/* rfc793:
5825 		 * "If the RST bit is set
5826 		 *
5827 		 *      Otherwise (no ACK) drop the segment and return."
5828 		 */
5829 
5830 		goto discard_and_undo;
5831 	}
5832 
5833 	/* PAWS check. */
5834 	if (tp->rx_opt.ts_recent_stamp && tp->rx_opt.saw_tstamp &&
5835 	    tcp_paws_reject(&tp->rx_opt, 0))
5836 		goto discard_and_undo;
5837 
5838 	if (th->syn) {
5839 		/* We see SYN without ACK. It is attempt of
5840 		 * simultaneous connect with crossed SYNs.
5841 		 * Particularly, it can be connect to self.
5842 		 */
5843 		tcp_set_state(sk, TCP_SYN_RECV);
5844 
5845 		if (tp->rx_opt.saw_tstamp) {
5846 			tp->rx_opt.tstamp_ok = 1;
5847 			tcp_store_ts_recent(tp);
5848 			tp->tcp_header_len =
5849 				sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
5850 		} else {
5851 			tp->tcp_header_len = sizeof(struct tcphdr);
5852 		}
5853 
5854 		tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1;
5855 		tp->copied_seq = tp->rcv_nxt;
5856 		tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1;
5857 
5858 		/* RFC1323: The window in SYN & SYN/ACK segments is
5859 		 * never scaled.
5860 		 */
5861 		tp->snd_wnd    = ntohs(th->window);
5862 		tp->snd_wl1    = TCP_SKB_CB(skb)->seq;
5863 		tp->max_window = tp->snd_wnd;
5864 
5865 		tcp_ecn_rcv_syn(tp, th);
5866 
5867 		tcp_mtup_init(sk);
5868 		tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
5869 		tcp_initialize_rcv_mss(sk);
5870 
5871 		tcp_send_synack(sk);
5872 #if 0
5873 		/* Note, we could accept data and URG from this segment.
5874 		 * There are no obstacles to make this (except that we must
5875 		 * either change tcp_recvmsg() to prevent it from returning data
5876 		 * before 3WHS completes per RFC793, or employ TCP Fast Open).
5877 		 *
5878 		 * However, if we ignore data in ACKless segments sometimes,
5879 		 * we have no reasons to accept it sometimes.
5880 		 * Also, seems the code doing it in step6 of tcp_rcv_state_process
5881 		 * is not flawless. So, discard packet for sanity.
5882 		 * Uncomment this return to process the data.
5883 		 */
5884 		return -1;
5885 #else
5886 		goto discard;
5887 #endif
5888 	}
5889 	/* "fifth, if neither of the SYN or RST bits is set then
5890 	 * drop the segment and return."
5891 	 */
5892 
5893 discard_and_undo:
5894 	tcp_clear_options(&tp->rx_opt);
5895 	tp->rx_opt.mss_clamp = saved_clamp;
5896 	goto discard;
5897 
5898 reset_and_undo:
5899 	tcp_clear_options(&tp->rx_opt);
5900 	tp->rx_opt.mss_clamp = saved_clamp;
5901 	return 1;
5902 }
5903 
5904 /*
5905  *	This function implements the receiving procedure of RFC 793 for
5906  *	all states except ESTABLISHED and TIME_WAIT.
5907  *	It's called from both tcp_v4_rcv and tcp_v6_rcv and should be
5908  *	address independent.
5909  */
5910 
tcp_rcv_state_process(struct sock * sk,struct sk_buff * skb)5911 int tcp_rcv_state_process(struct sock *sk, struct sk_buff *skb)
5912 {
5913 	struct tcp_sock *tp = tcp_sk(sk);
5914 	struct inet_connection_sock *icsk = inet_csk(sk);
5915 	const struct tcphdr *th = tcp_hdr(skb);
5916 	struct request_sock *req;
5917 	int queued = 0;
5918 	bool acceptable;
5919 
5920 	tp->rx_opt.saw_tstamp = 0;
5921 
5922 	switch (sk->sk_state) {
5923 	case TCP_CLOSE:
5924 		goto discard;
5925 
5926 	case TCP_LISTEN:
5927 		if (th->ack)
5928 			return 1;
5929 
5930 		if (th->rst)
5931 			goto discard;
5932 
5933 		if (th->syn) {
5934 			if (th->fin)
5935 				goto discard;
5936 			if (icsk->icsk_af_ops->conn_request(sk, skb) < 0)
5937 				return 1;
5938 
5939 			/* Now we have several options: In theory there is
5940 			 * nothing else in the frame. KA9Q has an option to
5941 			 * send data with the syn, BSD accepts data with the
5942 			 * syn up to the [to be] advertised window and
5943 			 * Solaris 2.1 gives you a protocol error. For now
5944 			 * we just ignore it, that fits the spec precisely
5945 			 * and avoids incompatibilities. It would be nice in
5946 			 * future to drop through and process the data.
5947 			 *
5948 			 * Now that TTCP is starting to be used we ought to
5949 			 * queue this data.
5950 			 * But, this leaves one open to an easy denial of
5951 			 * service attack, and SYN cookies can't defend
5952 			 * against this problem. So, we drop the data
5953 			 * in the interest of security over speed unless
5954 			 * it's still in use.
5955 			 */
5956 			kfree_skb(skb);
5957 			return 0;
5958 		}
5959 		goto discard;
5960 
5961 	case TCP_SYN_SENT:
5962 		queued = tcp_rcv_synsent_state_process(sk, skb, th);
5963 		if (queued >= 0)
5964 			return queued;
5965 
5966 		/* Do step6 onward by hand. */
5967 		tcp_urg(sk, skb, th);
5968 		__kfree_skb(skb);
5969 		tcp_data_snd_check(sk);
5970 		return 0;
5971 	}
5972 
5973 	req = tp->fastopen_rsk;
5974 	if (req) {
5975 		WARN_ON_ONCE(sk->sk_state != TCP_SYN_RECV &&
5976 		    sk->sk_state != TCP_FIN_WAIT1);
5977 
5978 		if (!tcp_check_req(sk, skb, req, true))
5979 			goto discard;
5980 	}
5981 
5982 	if (!th->ack && !th->rst && !th->syn)
5983 		goto discard;
5984 
5985 	if (!tcp_validate_incoming(sk, skb, th, 0))
5986 		return 0;
5987 
5988 	/* step 5: check the ACK field */
5989 	acceptable = tcp_ack(sk, skb, FLAG_SLOWPATH |
5990 				      FLAG_UPDATE_TS_RECENT |
5991 				      FLAG_NO_CHALLENGE_ACK) > 0;
5992 
5993 	if (!acceptable) {
5994 		if (sk->sk_state == TCP_SYN_RECV)
5995 			return 1;	/* send one RST */
5996 		tcp_send_challenge_ack(sk, skb);
5997 		goto discard;
5998 	}
5999 	switch (sk->sk_state) {
6000 	case TCP_SYN_RECV:
6001 		if (!tp->srtt_us)
6002 			tcp_synack_rtt_meas(sk, req);
6003 
6004 		/* Once we leave TCP_SYN_RECV, we no longer need req
6005 		 * so release it.
6006 		 */
6007 		if (req) {
6008 			tp->total_retrans = req->num_retrans;
6009 			reqsk_fastopen_remove(sk, req, false);
6010 		} else {
6011 			/* Make sure socket is routed, for correct metrics. */
6012 			icsk->icsk_af_ops->rebuild_header(sk);
6013 			tcp_init_congestion_control(sk);
6014 
6015 			tcp_mtup_init(sk);
6016 			tp->copied_seq = tp->rcv_nxt;
6017 			tcp_init_buffer_space(sk);
6018 		}
6019 		smp_mb();
6020 		tcp_set_state(sk, TCP_ESTABLISHED);
6021 		sk->sk_state_change(sk);
6022 
6023 		/* Note, that this wakeup is only for marginal crossed SYN case.
6024 		 * Passively open sockets are not waked up, because
6025 		 * sk->sk_sleep == NULL and sk->sk_socket == NULL.
6026 		 */
6027 		if (sk->sk_socket)
6028 			sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT);
6029 
6030 		tp->snd_una = TCP_SKB_CB(skb)->ack_seq;
6031 		tp->snd_wnd = ntohs(th->window) << tp->rx_opt.snd_wscale;
6032 		tcp_init_wl(tp, TCP_SKB_CB(skb)->seq);
6033 
6034 		if (tp->rx_opt.tstamp_ok)
6035 			tp->advmss -= TCPOLEN_TSTAMP_ALIGNED;
6036 
6037 		if (req) {
6038 			/* Re-arm the timer because data may have been sent out.
6039 			 * This is similar to the regular data transmission case
6040 			 * when new data has just been ack'ed.
6041 			 *
6042 			 * (TFO) - we could try to be more aggressive and
6043 			 * retransmitting any data sooner based on when they
6044 			 * are sent out.
6045 			 */
6046 			tcp_rearm_rto(sk);
6047 		} else
6048 			tcp_init_metrics(sk);
6049 
6050 		tcp_update_pacing_rate(sk);
6051 
6052 		/* Prevent spurious tcp_cwnd_restart() on first data packet */
6053 		tp->lsndtime = tcp_time_stamp;
6054 
6055 		tcp_initialize_rcv_mss(sk);
6056 		tcp_fast_path_on(tp);
6057 		break;
6058 
6059 	case TCP_FIN_WAIT1: {
6060 		struct dst_entry *dst;
6061 		int tmo;
6062 
6063 		/* If we enter the TCP_FIN_WAIT1 state and we are a
6064 		 * Fast Open socket and this is the first acceptable
6065 		 * ACK we have received, this would have acknowledged
6066 		 * our SYNACK so stop the SYNACK timer.
6067 		 */
6068 		if (req) {
6069 			/* We no longer need the request sock. */
6070 			reqsk_fastopen_remove(sk, req, false);
6071 			tcp_rearm_rto(sk);
6072 		}
6073 		if (tp->snd_una != tp->write_seq)
6074 			break;
6075 
6076 		tcp_set_state(sk, TCP_FIN_WAIT2);
6077 		sk->sk_shutdown |= SEND_SHUTDOWN;
6078 
6079 		dst = __sk_dst_get(sk);
6080 		if (dst)
6081 			dst_confirm(dst);
6082 
6083 		if (!sock_flag(sk, SOCK_DEAD)) {
6084 			/* Wake up lingering close() */
6085 			sk->sk_state_change(sk);
6086 			break;
6087 		}
6088 
6089 		if (tp->linger2 < 0 ||
6090 		    (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
6091 		     after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt))) {
6092 			tcp_done(sk);
6093 			NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
6094 			return 1;
6095 		}
6096 
6097 		tmo = tcp_fin_time(sk);
6098 		if (tmo > TCP_TIMEWAIT_LEN) {
6099 			inet_csk_reset_keepalive_timer(sk, tmo - TCP_TIMEWAIT_LEN);
6100 		} else if (th->fin || sock_owned_by_user(sk)) {
6101 			/* Bad case. We could lose such FIN otherwise.
6102 			 * It is not a big problem, but it looks confusing
6103 			 * and not so rare event. We still can lose it now,
6104 			 * if it spins in bh_lock_sock(), but it is really
6105 			 * marginal case.
6106 			 */
6107 			inet_csk_reset_keepalive_timer(sk, tmo);
6108 		} else {
6109 			tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
6110 			goto discard;
6111 		}
6112 		break;
6113 	}
6114 
6115 	case TCP_CLOSING:
6116 		if (tp->snd_una == tp->write_seq) {
6117 			tcp_time_wait(sk, TCP_TIME_WAIT, 0);
6118 			goto discard;
6119 		}
6120 		break;
6121 
6122 	case TCP_LAST_ACK:
6123 		if (tp->snd_una == tp->write_seq) {
6124 			tcp_update_metrics(sk);
6125 			tcp_done(sk);
6126 			goto discard;
6127 		}
6128 		break;
6129 	}
6130 
6131 	/* step 6: check the URG bit */
6132 	tcp_urg(sk, skb, th);
6133 
6134 	/* step 7: process the segment text */
6135 	switch (sk->sk_state) {
6136 	case TCP_CLOSE_WAIT:
6137 	case TCP_CLOSING:
6138 	case TCP_LAST_ACK:
6139 		if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt))
6140 			break;
6141 	case TCP_FIN_WAIT1:
6142 	case TCP_FIN_WAIT2:
6143 		/* RFC 793 says to queue data in these states,
6144 		 * RFC 1122 says we MUST send a reset.
6145 		 * BSD 4.4 also does reset.
6146 		 */
6147 		if (sk->sk_shutdown & RCV_SHUTDOWN) {
6148 			if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq &&
6149 			    after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt)) {
6150 				NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPABORTONDATA);
6151 				tcp_reset(sk);
6152 				return 1;
6153 			}
6154 		}
6155 		/* Fall through */
6156 	case TCP_ESTABLISHED:
6157 		tcp_data_queue(sk, skb);
6158 		queued = 1;
6159 		break;
6160 	}
6161 
6162 	/* tcp_data could move socket to TIME-WAIT */
6163 	if (sk->sk_state != TCP_CLOSE) {
6164 		tcp_data_snd_check(sk);
6165 		tcp_ack_snd_check(sk);
6166 	}
6167 
6168 	if (!queued) {
6169 discard:
6170 		tcp_drop(sk, skb);
6171 	}
6172 	return 0;
6173 }
6174 EXPORT_SYMBOL(tcp_rcv_state_process);
6175 
pr_drop_req(struct request_sock * req,__u16 port,int family)6176 static inline void pr_drop_req(struct request_sock *req, __u16 port, int family)
6177 {
6178 	struct inet_request_sock *ireq = inet_rsk(req);
6179 
6180 	if (family == AF_INET)
6181 		net_dbg_ratelimited("drop open request from %pI4/%u\n",
6182 				    &ireq->ir_rmt_addr, port);
6183 #if IS_ENABLED(CONFIG_IPV6)
6184 	else if (family == AF_INET6)
6185 		net_dbg_ratelimited("drop open request from %pI6/%u\n",
6186 				    &ireq->ir_v6_rmt_addr, port);
6187 #endif
6188 }
6189 
6190 /* RFC3168 : 6.1.1 SYN packets must not have ECT/ECN bits set
6191  *
6192  * If we receive a SYN packet with these bits set, it means a
6193  * network is playing bad games with TOS bits. In order to
6194  * avoid possible false congestion notifications, we disable
6195  * TCP ECN negotiation.
6196  *
6197  * Exception: tcp_ca wants ECN. This is required for DCTCP
6198  * congestion control: Linux DCTCP asserts ECT on all packets,
6199  * including SYN, which is most optimal solution; however,
6200  * others, such as FreeBSD do not.
6201  */
tcp_ecn_create_request(struct request_sock * req,const struct sk_buff * skb,const struct sock * listen_sk,const struct dst_entry * dst)6202 static void tcp_ecn_create_request(struct request_sock *req,
6203 				   const struct sk_buff *skb,
6204 				   const struct sock *listen_sk,
6205 				   const struct dst_entry *dst)
6206 {
6207 	const struct tcphdr *th = tcp_hdr(skb);
6208 	const struct net *net = sock_net(listen_sk);
6209 	bool th_ecn = th->ece && th->cwr;
6210 	bool ect, ecn_ok;
6211 	u32 ecn_ok_dst;
6212 
6213 	if (!th_ecn)
6214 		return;
6215 
6216 	ect = !INET_ECN_is_not_ect(TCP_SKB_CB(skb)->ip_dsfield);
6217 	ecn_ok_dst = dst_feature(dst, DST_FEATURE_ECN_MASK);
6218 	ecn_ok = net->ipv4.sysctl_tcp_ecn || ecn_ok_dst;
6219 
6220 	if ((!ect && ecn_ok) || tcp_ca_needs_ecn(listen_sk) ||
6221 	    (ecn_ok_dst & DST_FEATURE_ECN_CA))
6222 		inet_rsk(req)->ecn_ok = 1;
6223 }
6224 
tcp_openreq_init(struct request_sock * req,const struct tcp_options_received * rx_opt,struct sk_buff * skb,const struct sock * sk)6225 static void tcp_openreq_init(struct request_sock *req,
6226 			     const struct tcp_options_received *rx_opt,
6227 			     struct sk_buff *skb, const struct sock *sk)
6228 {
6229 	struct inet_request_sock *ireq = inet_rsk(req);
6230 
6231 	req->rsk_rcv_wnd = 0;		/* So that tcp_send_synack() knows! */
6232 	req->cookie_ts = 0;
6233 	tcp_rsk(req)->rcv_isn = TCP_SKB_CB(skb)->seq;
6234 	tcp_rsk(req)->rcv_nxt = TCP_SKB_CB(skb)->seq + 1;
6235 	skb_mstamp_get(&tcp_rsk(req)->snt_synack);
6236 	tcp_rsk(req)->last_oow_ack_time = 0;
6237 	req->mss = rx_opt->mss_clamp;
6238 	req->ts_recent = rx_opt->saw_tstamp ? rx_opt->rcv_tsval : 0;
6239 	ireq->tstamp_ok = rx_opt->tstamp_ok;
6240 	ireq->sack_ok = rx_opt->sack_ok;
6241 	ireq->snd_wscale = rx_opt->snd_wscale;
6242 	ireq->wscale_ok = rx_opt->wscale_ok;
6243 	ireq->acked = 0;
6244 	ireq->ecn_ok = 0;
6245 	ireq->ir_rmt_port = tcp_hdr(skb)->source;
6246 	ireq->ir_num = ntohs(tcp_hdr(skb)->dest);
6247 	ireq->ir_mark = inet_request_mark(sk, skb);
6248 }
6249 
inet_reqsk_alloc(const struct request_sock_ops * ops,struct sock * sk_listener,bool attach_listener)6250 struct request_sock *inet_reqsk_alloc(const struct request_sock_ops *ops,
6251 				      struct sock *sk_listener,
6252 				      bool attach_listener)
6253 {
6254 	struct request_sock *req = reqsk_alloc(ops, sk_listener,
6255 					       attach_listener);
6256 
6257 	if (req) {
6258 		struct inet_request_sock *ireq = inet_rsk(req);
6259 
6260 		kmemcheck_annotate_bitfield(ireq, flags);
6261 		ireq->ireq_opt = NULL;
6262 		atomic64_set(&ireq->ir_cookie, 0);
6263 		ireq->ireq_state = TCP_NEW_SYN_RECV;
6264 		write_pnet(&ireq->ireq_net, sock_net(sk_listener));
6265 		ireq->ireq_family = sk_listener->sk_family;
6266 	}
6267 
6268 	return req;
6269 }
6270 EXPORT_SYMBOL(inet_reqsk_alloc);
6271 
6272 /*
6273  * Return true if a syncookie should be sent
6274  */
tcp_syn_flood_action(const struct sock * sk,const struct sk_buff * skb,const char * proto)6275 static bool tcp_syn_flood_action(const struct sock *sk,
6276 				 const struct sk_buff *skb,
6277 				 const char *proto)
6278 {
6279 	struct request_sock_queue *queue = &inet_csk(sk)->icsk_accept_queue;
6280 	const char *msg = "Dropping request";
6281 	bool want_cookie = false;
6282 
6283 #ifdef CONFIG_SYN_COOKIES
6284 	if (sysctl_tcp_syncookies) {
6285 		msg = "Sending cookies";
6286 		want_cookie = true;
6287 		NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPREQQFULLDOCOOKIES);
6288 	} else
6289 #endif
6290 		NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPREQQFULLDROP);
6291 
6292 	if (!queue->synflood_warned &&
6293 	    sysctl_tcp_syncookies != 2 &&
6294 	    xchg(&queue->synflood_warned, 1) == 0)
6295 		pr_info("%s: Possible SYN flooding on port %d. %s.  Check SNMP counters.\n",
6296 			proto, ntohs(tcp_hdr(skb)->dest), msg);
6297 
6298 	return want_cookie;
6299 }
6300 
tcp_reqsk_record_syn(const struct sock * sk,struct request_sock * req,const struct sk_buff * skb)6301 static void tcp_reqsk_record_syn(const struct sock *sk,
6302 				 struct request_sock *req,
6303 				 const struct sk_buff *skb)
6304 {
6305 	if (tcp_sk(sk)->save_syn) {
6306 		u32 len = skb_network_header_len(skb) + tcp_hdrlen(skb);
6307 		u32 *copy;
6308 
6309 		copy = kmalloc(len + sizeof(u32), GFP_ATOMIC);
6310 		if (copy) {
6311 			copy[0] = len;
6312 			memcpy(&copy[1], skb_network_header(skb), len);
6313 			req->saved_syn = copy;
6314 		}
6315 	}
6316 }
6317 
tcp_conn_request(struct request_sock_ops * rsk_ops,const struct tcp_request_sock_ops * af_ops,struct sock * sk,struct sk_buff * skb)6318 int tcp_conn_request(struct request_sock_ops *rsk_ops,
6319 		     const struct tcp_request_sock_ops *af_ops,
6320 		     struct sock *sk, struct sk_buff *skb)
6321 {
6322 	struct tcp_fastopen_cookie foc = { .len = -1 };
6323 	__u32 isn = TCP_SKB_CB(skb)->tcp_tw_isn;
6324 	struct tcp_options_received tmp_opt;
6325 	struct tcp_sock *tp = tcp_sk(sk);
6326 	struct sock *fastopen_sk = NULL;
6327 	struct dst_entry *dst = NULL;
6328 	struct request_sock *req;
6329 	bool want_cookie = false;
6330 	struct flowi fl;
6331 
6332 	/* TW buckets are converted to open requests without
6333 	 * limitations, they conserve resources and peer is
6334 	 * evidently real one.
6335 	 */
6336 	if ((sysctl_tcp_syncookies == 2 ||
6337 	     inet_csk_reqsk_queue_is_full(sk)) && !isn) {
6338 		want_cookie = tcp_syn_flood_action(sk, skb, rsk_ops->slab_name);
6339 		if (!want_cookie)
6340 			goto drop;
6341 	}
6342 
6343 	if (sk_acceptq_is_full(sk)) {
6344 		NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
6345 		goto drop;
6346 	}
6347 
6348 	req = inet_reqsk_alloc(rsk_ops, sk, !want_cookie);
6349 	if (!req)
6350 		goto drop;
6351 
6352 	tcp_rsk(req)->af_specific = af_ops;
6353 
6354 	tcp_clear_options(&tmp_opt);
6355 	tmp_opt.mss_clamp = af_ops->mss_clamp;
6356 	tmp_opt.user_mss  = tp->rx_opt.user_mss;
6357 	tcp_parse_options(skb, &tmp_opt, 0, want_cookie ? NULL : &foc);
6358 
6359 	if (want_cookie && !tmp_opt.saw_tstamp)
6360 		tcp_clear_options(&tmp_opt);
6361 
6362 	tmp_opt.tstamp_ok = tmp_opt.saw_tstamp;
6363 	tcp_openreq_init(req, &tmp_opt, skb, sk);
6364 
6365 	/* Note: tcp_v6_init_req() might override ir_iif for link locals */
6366 	inet_rsk(req)->ir_iif = sk->sk_bound_dev_if;
6367 
6368 	af_ops->init_req(req, sk, skb);
6369 
6370 	if (security_inet_conn_request(sk, skb, req))
6371 		goto drop_and_free;
6372 
6373 	if (!want_cookie && !isn) {
6374 		/* VJ's idea. We save last timestamp seen
6375 		 * from the destination in peer table, when entering
6376 		 * state TIME-WAIT, and check against it before
6377 		 * accepting new connection request.
6378 		 *
6379 		 * If "isn" is not zero, this request hit alive
6380 		 * timewait bucket, so that all the necessary checks
6381 		 * are made in the function processing timewait state.
6382 		 */
6383 		if (tcp_death_row.sysctl_tw_recycle) {
6384 			bool strict;
6385 
6386 			dst = af_ops->route_req(sk, &fl, req, &strict);
6387 
6388 			if (dst && strict &&
6389 			    !tcp_peer_is_proven(req, dst, true,
6390 						tmp_opt.saw_tstamp)) {
6391 				NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_PAWSPASSIVEREJECTED);
6392 				goto drop_and_release;
6393 			}
6394 		}
6395 		/* Kill the following clause, if you dislike this way. */
6396 		else if (!sysctl_tcp_syncookies &&
6397 			 (sysctl_max_syn_backlog - inet_csk_reqsk_queue_len(sk) <
6398 			  (sysctl_max_syn_backlog >> 2)) &&
6399 			 !tcp_peer_is_proven(req, dst, false,
6400 					     tmp_opt.saw_tstamp)) {
6401 			/* Without syncookies last quarter of
6402 			 * backlog is filled with destinations,
6403 			 * proven to be alive.
6404 			 * It means that we continue to communicate
6405 			 * to destinations, already remembered
6406 			 * to the moment of synflood.
6407 			 */
6408 			pr_drop_req(req, ntohs(tcp_hdr(skb)->source),
6409 				    rsk_ops->family);
6410 			goto drop_and_release;
6411 		}
6412 
6413 		isn = af_ops->init_seq(skb);
6414 	}
6415 	if (!dst) {
6416 		dst = af_ops->route_req(sk, &fl, req, NULL);
6417 		if (!dst)
6418 			goto drop_and_free;
6419 	}
6420 
6421 	tcp_ecn_create_request(req, skb, sk, dst);
6422 
6423 	if (want_cookie) {
6424 		isn = cookie_init_sequence(af_ops, sk, skb, &req->mss);
6425 		req->cookie_ts = tmp_opt.tstamp_ok;
6426 		if (!tmp_opt.tstamp_ok)
6427 			inet_rsk(req)->ecn_ok = 0;
6428 	}
6429 
6430 	tcp_rsk(req)->snt_isn = isn;
6431 	tcp_rsk(req)->txhash = net_tx_rndhash();
6432 	tcp_openreq_init_rwin(req, sk, dst);
6433 	if (!want_cookie) {
6434 		tcp_reqsk_record_syn(sk, req, skb);
6435 		fastopen_sk = tcp_try_fastopen(sk, skb, req, &foc, dst);
6436 	}
6437 	if (fastopen_sk) {
6438 		af_ops->send_synack(fastopen_sk, dst, &fl, req,
6439 				    &foc, false);
6440 		/* Add the child socket directly into the accept queue */
6441 		if (!inet_csk_reqsk_queue_add(sk, req, fastopen_sk)) {
6442 			reqsk_fastopen_remove(fastopen_sk, req, false);
6443 			bh_unlock_sock(fastopen_sk);
6444 			sock_put(fastopen_sk);
6445 			reqsk_put(req);
6446 			goto drop;
6447 		}
6448 		sk->sk_data_ready(sk);
6449 		bh_unlock_sock(fastopen_sk);
6450 		sock_put(fastopen_sk);
6451 	} else {
6452 		tcp_rsk(req)->tfo_listener = false;
6453 		if (!want_cookie)
6454 			inet_csk_reqsk_queue_hash_add(sk, req, TCP_TIMEOUT_INIT);
6455 		af_ops->send_synack(sk, dst, &fl, req,
6456 				    &foc, !want_cookie);
6457 		if (want_cookie)
6458 			goto drop_and_free;
6459 	}
6460 	reqsk_put(req);
6461 	return 0;
6462 
6463 drop_and_release:
6464 	dst_release(dst);
6465 drop_and_free:
6466 	reqsk_free(req);
6467 drop:
6468 	NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS);
6469 	return 0;
6470 }
6471 EXPORT_SYMBOL(tcp_conn_request);
6472