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