xref: /linux/net/ipv4/tcp_minisocks.c (revision 00c94ca2b99e6610e483f92e531b319eeaed94aa)
1 // SPDX-License-Identifier: GPL-2.0-only
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 #include <net/tcp.h>
23 #include <net/tcp_ecn.h>
24 #include <net/xfrm.h>
25 #include <net/busy_poll.h>
26 #include <net/rstreason.h>
27 
28 static bool tcp_in_window(u32 seq, u32 end_seq, u32 s_win, u32 e_win)
29 {
30 	if (seq == s_win)
31 		return true;
32 	if (after(end_seq, s_win) && before(seq, e_win))
33 		return true;
34 	return seq == e_win && seq == end_seq;
35 }
36 
37 static enum tcp_tw_status
38 tcp_timewait_check_oow_rate_limit(struct inet_timewait_sock *tw,
39 				  const struct sk_buff *skb, int mib_idx)
40 {
41 	struct tcp_timewait_sock *tcptw = tcp_twsk((struct sock *)tw);
42 
43 	if (!tcp_oow_rate_limited(twsk_net(tw), skb, mib_idx,
44 				  &tcptw->tw_last_oow_ack_time)) {
45 		/* Send ACK. Note, we do not put the bucket,
46 		 * it will be released by caller.
47 		 */
48 		return TCP_TW_ACK_OOW;
49 	}
50 
51 	/* We are rate-limiting, so just release the tw sock and drop skb. */
52 	inet_twsk_put(tw);
53 	return TCP_TW_SUCCESS;
54 }
55 
56 static void twsk_rcv_nxt_update(struct tcp_timewait_sock *tcptw, u32 seq,
57 				u32 rcv_nxt)
58 {
59 #ifdef CONFIG_TCP_AO
60 	struct tcp_ao_info *ao;
61 
62 	ao = rcu_dereference(tcptw->ao_info);
63 	if (unlikely(ao && seq < rcv_nxt))
64 		WRITE_ONCE(ao->rcv_sne, ao->rcv_sne + 1);
65 #endif
66 	WRITE_ONCE(tcptw->tw_rcv_nxt, seq);
67 }
68 
69 /*
70  * * Main purpose of TIME-WAIT state is to close connection gracefully,
71  *   when one of ends sits in LAST-ACK or CLOSING retransmitting FIN
72  *   (and, probably, tail of data) and one or more our ACKs are lost.
73  * * What is TIME-WAIT timeout? It is associated with maximal packet
74  *   lifetime in the internet, which results in wrong conclusion, that
75  *   it is set to catch "old duplicate segments" wandering out of their path.
76  *   It is not quite correct. This timeout is calculated so that it exceeds
77  *   maximal retransmission timeout enough to allow to lose one (or more)
78  *   segments sent by peer and our ACKs. This time may be calculated from RTO.
79  * * When TIME-WAIT socket receives RST, it means that another end
80  *   finally closed and we are allowed to kill TIME-WAIT too.
81  * * Second purpose of TIME-WAIT is catching old duplicate segments.
82  *   Well, certainly it is pure paranoia, but if we load TIME-WAIT
83  *   with this semantics, we MUST NOT kill TIME-WAIT state with RSTs.
84  * * If we invented some more clever way to catch duplicates
85  *   (f.e. based on PAWS), we could truncate TIME-WAIT to several RTOs.
86  *
87  * The algorithm below is based on FORMAL INTERPRETATION of RFCs.
88  * When you compare it to RFCs, please, read section SEGMENT ARRIVES
89  * from the very beginning.
90  *
91  * NOTE. With recycling (and later with fin-wait-2) TW bucket
92  * is _not_ stateless. It means, that strictly speaking we must
93  * spinlock it. I do not want! Well, probability of misbehaviour
94  * is ridiculously low and, seems, we could use some mb() tricks
95  * to avoid misread sequence numbers, states etc.  --ANK
96  *
97  * We don't need to initialize tmp_out.sack_ok as we don't use the results
98  */
99 enum tcp_tw_status
100 tcp_timewait_state_process(struct inet_timewait_sock *tw, struct sk_buff *skb,
101 			   const struct tcphdr *th, u32 *tw_isn,
102 			   enum skb_drop_reason *drop_reason)
103 {
104 	struct tcp_timewait_sock *tcptw = tcp_twsk((struct sock *)tw);
105 	u32 rcv_nxt = READ_ONCE(tcptw->tw_rcv_nxt);
106 	struct tcp_options_received tmp_opt;
107 	bool paws_reject = false;
108 	int ts_recent_stamp;
109 
110 	tmp_opt.saw_tstamp = 0;
111 	ts_recent_stamp = READ_ONCE(tcptw->tw_ts_recent_stamp);
112 	if (th->doff > (sizeof(*th) >> 2) && ts_recent_stamp) {
113 		tcp_parse_options(twsk_net(tw), skb, &tmp_opt, 0, NULL);
114 
115 		if (tmp_opt.saw_tstamp) {
116 			if (tmp_opt.rcv_tsecr)
117 				tmp_opt.rcv_tsecr -= tcptw->tw_ts_offset;
118 			tmp_opt.ts_recent	= READ_ONCE(tcptw->tw_ts_recent);
119 			tmp_opt.ts_recent_stamp	= ts_recent_stamp;
120 			paws_reject = tcp_paws_reject(&tmp_opt, th->rst);
121 		}
122 	}
123 
124 	if (READ_ONCE(tw->tw_substate) == TCP_FIN_WAIT2) {
125 		/* Just repeat all the checks of tcp_rcv_state_process() */
126 
127 		/* Out of window, send ACK */
128 		if (paws_reject ||
129 		    !tcp_in_window(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq,
130 				   rcv_nxt,
131 				   rcv_nxt + tcptw->tw_rcv_wnd))
132 			return tcp_timewait_check_oow_rate_limit(
133 				tw, skb, LINUX_MIB_TCPACKSKIPPEDFINWAIT2);
134 
135 		if (th->rst)
136 			goto kill;
137 
138 		if (th->syn && !before(TCP_SKB_CB(skb)->seq, rcv_nxt))
139 			return TCP_TW_RST;
140 
141 		/* Dup ACK? */
142 		if (!th->ack ||
143 		    !after(TCP_SKB_CB(skb)->end_seq, rcv_nxt) ||
144 		    TCP_SKB_CB(skb)->end_seq == TCP_SKB_CB(skb)->seq) {
145 			inet_twsk_put(tw);
146 			return TCP_TW_SUCCESS;
147 		}
148 
149 		/* New data or FIN. If new data arrive after half-duplex close,
150 		 * reset.
151 		 */
152 		if (!th->fin ||
153 		    TCP_SKB_CB(skb)->end_seq != rcv_nxt + 1)
154 			return TCP_TW_RST;
155 
156 		/* FIN arrived, enter true time-wait state. */
157 		WRITE_ONCE(tw->tw_substate, TCP_TIME_WAIT);
158 		twsk_rcv_nxt_update(tcptw, TCP_SKB_CB(skb)->end_seq,
159 				    rcv_nxt);
160 
161 		if (tmp_opt.saw_tstamp) {
162 			u64 ts = tcp_clock_ms();
163 
164 			WRITE_ONCE(tw->tw_entry_stamp, ts);
165 			WRITE_ONCE(tcptw->tw_ts_recent_stamp,
166 				   div_u64(ts, MSEC_PER_SEC));
167 			WRITE_ONCE(tcptw->tw_ts_recent,
168 				   tmp_opt.rcv_tsval);
169 		}
170 
171 		inet_twsk_reschedule(tw, TCP_TIMEWAIT_LEN);
172 		return TCP_TW_ACK;
173 	}
174 
175 	/*
176 	 *	Now real TIME-WAIT state.
177 	 *
178 	 *	RFC 1122:
179 	 *	"When a connection is [...] on TIME-WAIT state [...]
180 	 *	[a TCP] MAY accept a new SYN from the remote TCP to
181 	 *	reopen the connection directly, if it:
182 	 *
183 	 *	(1)  assigns its initial sequence number for the new
184 	 *	connection to be larger than the largest sequence
185 	 *	number it used on the previous connection incarnation,
186 	 *	and
187 	 *
188 	 *	(2)  returns to TIME-WAIT state if the SYN turns out
189 	 *	to be an old duplicate".
190 	 */
191 
192 	if (!paws_reject &&
193 	    (TCP_SKB_CB(skb)->seq == rcv_nxt &&
194 	     (TCP_SKB_CB(skb)->seq == TCP_SKB_CB(skb)->end_seq || th->rst))) {
195 		/* In window segment, it may be only reset or bare ack. */
196 
197 		if (th->rst) {
198 			/* This is TIME_WAIT assassination, in two flavors.
199 			 * Oh well... nobody has a sufficient solution to this
200 			 * protocol bug yet.
201 			 */
202 			if (!READ_ONCE(twsk_net(tw)->ipv4.sysctl_tcp_rfc1337)) {
203 kill:
204 				inet_twsk_deschedule_put(tw);
205 				return TCP_TW_SUCCESS;
206 			}
207 		} else {
208 			inet_twsk_reschedule(tw, TCP_TIMEWAIT_LEN);
209 		}
210 
211 		if (tmp_opt.saw_tstamp) {
212 			WRITE_ONCE(tcptw->tw_ts_recent,
213 				   tmp_opt.rcv_tsval);
214 			WRITE_ONCE(tcptw->tw_ts_recent_stamp,
215 				   ktime_get_seconds());
216 		}
217 
218 		inet_twsk_put(tw);
219 		return TCP_TW_SUCCESS;
220 	}
221 
222 	/* Out of window segment.
223 
224 	   All the segments are ACKed immediately.
225 
226 	   The only exception is new SYN. We accept it, if it is
227 	   not old duplicate and we are not in danger to be killed
228 	   by delayed old duplicates. RFC check is that it has
229 	   newer sequence number works at rates <40Mbit/sec.
230 	   However, if paws works, it is reliable AND even more,
231 	   we even may relax silly seq space cutoff.
232 
233 	   RED-PEN: we violate main RFC requirement, if this SYN will appear
234 	   old duplicate (i.e. we receive RST in reply to SYN-ACK),
235 	   we must return socket to time-wait state. It is not good,
236 	   but not fatal yet.
237 	 */
238 
239 	if (th->syn && !th->rst && !th->ack && !paws_reject &&
240 	    (after(TCP_SKB_CB(skb)->seq, rcv_nxt) ||
241 	     (tmp_opt.saw_tstamp &&
242 	      (s32)(READ_ONCE(tcptw->tw_ts_recent) - tmp_opt.rcv_tsval) < 0))) {
243 		u32 isn = tcptw->tw_snd_nxt + 65535 + 2;
244 		if (isn == 0)
245 			isn++;
246 		*tw_isn = isn;
247 		return TCP_TW_SYN;
248 	}
249 
250 	if (paws_reject) {
251 		*drop_reason = SKB_DROP_REASON_TCP_RFC7323_TW_PAWS;
252 		__NET_INC_STATS(twsk_net(tw), LINUX_MIB_PAWS_TW_REJECTED);
253 	}
254 
255 	if (!th->rst) {
256 		/* In this case we must reset the TIMEWAIT timer.
257 		 *
258 		 * If it is ACKless SYN it may be both old duplicate
259 		 * and new good SYN with random sequence number <rcv_nxt.
260 		 * Do not reschedule in the last case.
261 		 */
262 		if (paws_reject || th->ack)
263 			inet_twsk_reschedule(tw, TCP_TIMEWAIT_LEN);
264 
265 		return tcp_timewait_check_oow_rate_limit(
266 			tw, skb, LINUX_MIB_TCPACKSKIPPEDTIMEWAIT);
267 	}
268 	inet_twsk_put(tw);
269 	return TCP_TW_SUCCESS;
270 }
271 EXPORT_IPV6_MOD(tcp_timewait_state_process);
272 
273 static void tcp_time_wait_init(struct sock *sk, struct tcp_timewait_sock *tcptw)
274 {
275 #ifdef CONFIG_TCP_MD5SIG
276 	const struct tcp_sock *tp = tcp_sk(sk);
277 	struct tcp_md5sig_key *key;
278 
279 	/*
280 	 * The timewait bucket does not have the key DB from the
281 	 * sock structure. We just make a quick copy of the
282 	 * md5 key being used (if indeed we are using one)
283 	 * so the timewait ack generating code has the key.
284 	 */
285 	tcptw->tw_md5_key = NULL;
286 	if (!static_branch_unlikely(&tcp_md5_needed.key))
287 		return;
288 
289 	key = tp->af_specific->md5_lookup(sk, sk);
290 	if (key) {
291 		tcptw->tw_md5_key = kmemdup(key, sizeof(*key), GFP_ATOMIC);
292 		if (!tcptw->tw_md5_key)
293 			return;
294 		if (!static_key_fast_inc_not_disabled(&tcp_md5_needed.key.key))
295 			goto out_free;
296 		tcp_md5_add_sigpool();
297 	}
298 	return;
299 out_free:
300 	WARN_ON_ONCE(1);
301 	kfree(tcptw->tw_md5_key);
302 	tcptw->tw_md5_key = NULL;
303 #endif
304 }
305 
306 /*
307  * Move a socket to time-wait or dead fin-wait-2 state.
308  */
309 void tcp_time_wait(struct sock *sk, int state, int timeo)
310 {
311 	const struct inet_connection_sock *icsk = inet_csk(sk);
312 	struct tcp_sock *tp = tcp_sk(sk);
313 	struct net *net = sock_net(sk);
314 	struct inet_timewait_sock *tw;
315 
316 	tw = inet_twsk_alloc(sk, &net->ipv4.tcp_death_row, state);
317 
318 	if (tw) {
319 		struct tcp_timewait_sock *tcptw = tcp_twsk((struct sock *)tw);
320 		const int rto = (icsk->icsk_rto << 2) - (icsk->icsk_rto >> 1);
321 
322 		tw->tw_transparent	= inet_test_bit(TRANSPARENT, sk);
323 		tw->tw_mark		= sk->sk_mark;
324 		tw->tw_priority		= READ_ONCE(sk->sk_priority);
325 		tw->tw_rcv_wscale	= tp->rx_opt.rcv_wscale;
326 		/* refreshed when we enter true TIME-WAIT state */
327 		tw->tw_entry_stamp	= tcp_time_stamp_ms(tp);
328 		tcptw->tw_rcv_nxt	= tp->rcv_nxt;
329 		tcptw->tw_snd_nxt	= tp->snd_nxt;
330 		tcptw->tw_rcv_wnd	= tcp_receive_window(tp);
331 		tcptw->tw_ts_recent	= tp->rx_opt.ts_recent;
332 		tcptw->tw_ts_recent_stamp = tp->rx_opt.ts_recent_stamp;
333 		tcptw->tw_ts_offset	= tp->tsoffset;
334 		tw->tw_usec_ts		= tp->tcp_usec_ts;
335 		tcptw->tw_last_oow_ack_time = 0;
336 		tcptw->tw_tx_delay	= tp->tcp_tx_delay;
337 		tw->tw_txhash		= sk->sk_txhash;
338 		tw->tw_tx_queue_mapping = sk->sk_tx_queue_mapping;
339 #ifdef CONFIG_SOCK_RX_QUEUE_MAPPING
340 		tw->tw_rx_queue_mapping = sk->sk_rx_queue_mapping;
341 #endif
342 #if IS_ENABLED(CONFIG_IPV6)
343 		if (tw->tw_family == PF_INET6) {
344 			struct ipv6_pinfo *np = inet6_sk(sk);
345 
346 			tw->tw_v6_daddr = sk->sk_v6_daddr;
347 			tw->tw_v6_rcv_saddr = sk->sk_v6_rcv_saddr;
348 			tw->tw_tclass = np->tclass;
349 			tw->tw_flowlabel = be32_to_cpu(np->flow_label & IPV6_FLOWLABEL_MASK);
350 			tw->tw_ipv6only = sk->sk_ipv6only;
351 		}
352 #endif
353 
354 		tcp_time_wait_init(sk, tcptw);
355 		tcp_ao_time_wait(tcptw, tp);
356 
357 		/* Get the TIME_WAIT timeout firing. */
358 		if (timeo < rto)
359 			timeo = rto;
360 
361 		if (state == TCP_TIME_WAIT)
362 			timeo = TCP_TIMEWAIT_LEN;
363 
364 		/* Linkage updates.
365 		 * Note that access to tw after this point is illegal.
366 		 */
367 		inet_twsk_hashdance_schedule(tw, sk, net->ipv4.tcp_death_row.hashinfo, timeo);
368 	} else {
369 		/* Sorry, if we're out of memory, just CLOSE this
370 		 * socket up.  We've got bigger problems than
371 		 * non-graceful socket closings.
372 		 */
373 		NET_INC_STATS(net, LINUX_MIB_TCPTIMEWAITOVERFLOW);
374 	}
375 
376 	tcp_update_metrics(sk);
377 	tcp_done(sk);
378 }
379 EXPORT_SYMBOL(tcp_time_wait);
380 
381 void tcp_twsk_destructor(struct sock *sk)
382 {
383 #ifdef CONFIG_TCP_MD5SIG
384 	if (static_branch_unlikely(&tcp_md5_needed.key)) {
385 		struct tcp_timewait_sock *twsk = tcp_twsk(sk);
386 
387 		if (twsk->tw_md5_key) {
388 			kfree(twsk->tw_md5_key);
389 			static_branch_slow_dec_deferred(&tcp_md5_needed);
390 			tcp_md5_release_sigpool();
391 		}
392 	}
393 #endif
394 	tcp_ao_destroy_sock(sk, true);
395 }
396 
397 void tcp_twsk_purge(struct list_head *net_exit_list)
398 {
399 	bool purged_once = false;
400 	struct net *net;
401 
402 	list_for_each_entry(net, net_exit_list, exit_list) {
403 		if (net->ipv4.tcp_death_row.hashinfo->pernet) {
404 			/* Even if tw_refcount == 1, we must clean up kernel reqsk */
405 			inet_twsk_purge(net->ipv4.tcp_death_row.hashinfo);
406 		} else if (!purged_once) {
407 			inet_twsk_purge(&tcp_hashinfo);
408 			purged_once = true;
409 		}
410 	}
411 }
412 
413 /* Warning : This function is called without sk_listener being locked.
414  * Be sure to read socket fields once, as their value could change under us.
415  */
416 void tcp_openreq_init_rwin(struct request_sock *req,
417 			   const struct sock *sk_listener,
418 			   const struct dst_entry *dst)
419 {
420 	struct inet_request_sock *ireq = inet_rsk(req);
421 	const struct tcp_sock *tp = tcp_sk(sk_listener);
422 	int full_space = tcp_full_space(sk_listener);
423 	u32 window_clamp;
424 	__u8 rcv_wscale;
425 	u32 rcv_wnd;
426 	int mss;
427 
428 	mss = tcp_mss_clamp(tp, dst_metric_advmss(dst));
429 	window_clamp = READ_ONCE(tp->window_clamp);
430 	/* Set this up on the first call only */
431 	req->rsk_window_clamp = window_clamp ? : dst_metric(dst, RTAX_WINDOW);
432 
433 	/* limit the window selection if the user enforce a smaller rx buffer */
434 	if (sk_listener->sk_userlocks & SOCK_RCVBUF_LOCK &&
435 	    (req->rsk_window_clamp > full_space || req->rsk_window_clamp == 0))
436 		req->rsk_window_clamp = full_space;
437 
438 	rcv_wnd = tcp_rwnd_init_bpf((struct sock *)req);
439 	if (rcv_wnd == 0)
440 		rcv_wnd = dst_metric(dst, RTAX_INITRWND);
441 	else if (full_space < rcv_wnd * mss)
442 		full_space = rcv_wnd * mss;
443 
444 	/* tcp_full_space because it is guaranteed to be the first packet */
445 	tcp_select_initial_window(sk_listener, full_space,
446 		mss - (ireq->tstamp_ok ? TCPOLEN_TSTAMP_ALIGNED : 0),
447 		&req->rsk_rcv_wnd,
448 		&req->rsk_window_clamp,
449 		ireq->wscale_ok,
450 		&rcv_wscale,
451 		rcv_wnd);
452 	ireq->rcv_wscale = rcv_wscale;
453 }
454 
455 static void tcp_ecn_openreq_child(struct sock *sk,
456 				  const struct request_sock *req,
457 				  const struct sk_buff *skb)
458 {
459 	const struct tcp_request_sock *treq = tcp_rsk(req);
460 	struct tcp_sock *tp = tcp_sk(sk);
461 
462 	if (treq->accecn_ok) {
463 		tcp_ecn_mode_set(tp, TCP_ECN_MODE_ACCECN);
464 		tp->syn_ect_snt = treq->syn_ect_snt;
465 		tcp_accecn_third_ack(sk, skb, treq->syn_ect_snt);
466 		tp->saw_accecn_opt = treq->saw_accecn_opt;
467 		tp->prev_ecnfield = treq->syn_ect_rcv;
468 		tp->accecn_opt_demand = 1;
469 		tcp_ecn_received_counters_payload(sk, skb);
470 	} else {
471 		tcp_ecn_mode_set(tp, inet_rsk(req)->ecn_ok ?
472 				     TCP_ECN_MODE_RFC3168 :
473 				     TCP_ECN_DISABLED);
474 	}
475 }
476 
477 void tcp_ca_openreq_child(struct sock *sk, const struct dst_entry *dst)
478 {
479 	struct inet_connection_sock *icsk = inet_csk(sk);
480 	u32 ca_key = dst_metric(dst, RTAX_CC_ALGO);
481 	bool ca_got_dst = false;
482 
483 	if (ca_key != TCP_CA_UNSPEC) {
484 		const struct tcp_congestion_ops *ca;
485 
486 		rcu_read_lock();
487 		ca = tcp_ca_find_key(ca_key);
488 		if (likely(ca && bpf_try_module_get(ca, ca->owner))) {
489 			icsk->icsk_ca_dst_locked = tcp_ca_dst_locked(dst);
490 			icsk->icsk_ca_ops = ca;
491 			ca_got_dst = true;
492 		}
493 		rcu_read_unlock();
494 	}
495 
496 	/* If no valid choice made yet, assign current system default ca. */
497 	if (!ca_got_dst &&
498 	    (!icsk->icsk_ca_setsockopt ||
499 	     !bpf_try_module_get(icsk->icsk_ca_ops, icsk->icsk_ca_ops->owner)))
500 		tcp_assign_congestion_control(sk);
501 
502 	tcp_set_ca_state(sk, TCP_CA_Open);
503 }
504 EXPORT_IPV6_MOD_GPL(tcp_ca_openreq_child);
505 
506 static void smc_check_reset_syn_req(const struct tcp_sock *oldtp,
507 				    struct request_sock *req,
508 				    struct tcp_sock *newtp)
509 {
510 #if IS_ENABLED(CONFIG_SMC)
511 	struct inet_request_sock *ireq;
512 
513 	if (static_branch_unlikely(&tcp_have_smc)) {
514 		ireq = inet_rsk(req);
515 		if (oldtp->syn_smc && !ireq->smc_ok)
516 			newtp->syn_smc = 0;
517 	}
518 #endif
519 }
520 
521 /* This is not only more efficient than what we used to do, it eliminates
522  * a lot of code duplication between IPv4/IPv6 SYN recv processing. -DaveM
523  *
524  * Actually, we could lots of memory writes here. tp of listening
525  * socket contains all necessary default parameters.
526  */
527 struct sock *tcp_create_openreq_child(const struct sock *sk,
528 				      struct request_sock *req,
529 				      struct sk_buff *skb)
530 {
531 	struct sock *newsk = inet_csk_clone_lock(sk, req, GFP_ATOMIC);
532 	const struct inet_request_sock *ireq = inet_rsk(req);
533 	struct tcp_request_sock *treq = tcp_rsk(req);
534 	struct inet_connection_sock *newicsk;
535 	const struct tcp_sock *oldtp;
536 	struct tcp_sock *newtp;
537 	u32 seq;
538 
539 	if (!newsk)
540 		return NULL;
541 
542 	newicsk = inet_csk(newsk);
543 	newtp = tcp_sk(newsk);
544 	oldtp = tcp_sk(sk);
545 
546 	smc_check_reset_syn_req(oldtp, req, newtp);
547 
548 	/* Now setup tcp_sock */
549 	newtp->pred_flags = 0;
550 
551 	seq = treq->rcv_isn + 1;
552 	newtp->rcv_wup = seq;
553 	WRITE_ONCE(newtp->copied_seq, seq);
554 	WRITE_ONCE(newtp->rcv_nxt, seq);
555 	newtp->segs_in = 1;
556 
557 	seq = treq->snt_isn + 1;
558 	newtp->snd_sml = newtp->snd_una = seq;
559 	WRITE_ONCE(newtp->snd_nxt, seq);
560 	newtp->snd_up = seq;
561 
562 	INIT_LIST_HEAD(&newtp->tsq_node);
563 	INIT_LIST_HEAD(&newtp->tsorted_sent_queue);
564 
565 	tcp_init_wl(newtp, treq->rcv_isn);
566 
567 	minmax_reset(&newtp->rtt_min, tcp_jiffies32, ~0U);
568 	newicsk->icsk_ack.lrcvtime = tcp_jiffies32;
569 
570 	newtp->lsndtime = tcp_jiffies32;
571 	newsk->sk_txhash = READ_ONCE(treq->txhash);
572 	newtp->total_retrans = req->num_retrans;
573 
574 	tcp_init_xmit_timers(newsk);
575 	WRITE_ONCE(newtp->write_seq, newtp->pushed_seq = treq->snt_isn + 1);
576 
577 	if (sock_flag(newsk, SOCK_KEEPOPEN))
578 		tcp_reset_keepalive_timer(newsk, keepalive_time_when(newtp));
579 
580 	newtp->rx_opt.tstamp_ok = ireq->tstamp_ok;
581 	newtp->rx_opt.sack_ok = ireq->sack_ok;
582 	newtp->window_clamp = req->rsk_window_clamp;
583 	newtp->rcv_ssthresh = req->rsk_rcv_wnd;
584 	newtp->rcv_wnd = req->rsk_rcv_wnd;
585 	newtp->rx_opt.wscale_ok = ireq->wscale_ok;
586 	if (newtp->rx_opt.wscale_ok) {
587 		newtp->rx_opt.snd_wscale = ireq->snd_wscale;
588 		newtp->rx_opt.rcv_wscale = ireq->rcv_wscale;
589 	} else {
590 		newtp->rx_opt.snd_wscale = newtp->rx_opt.rcv_wscale = 0;
591 		newtp->window_clamp = min(newtp->window_clamp, 65535U);
592 	}
593 	newtp->snd_wnd = ntohs(tcp_hdr(skb)->window) << newtp->rx_opt.snd_wscale;
594 	newtp->max_window = newtp->snd_wnd;
595 
596 	if (newtp->rx_opt.tstamp_ok) {
597 		newtp->tcp_usec_ts = treq->req_usec_ts;
598 		newtp->rx_opt.ts_recent = req->ts_recent;
599 		newtp->rx_opt.ts_recent_stamp = ktime_get_seconds();
600 		newtp->tcp_header_len = sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED;
601 	} else {
602 		newtp->tcp_usec_ts = 0;
603 		newtp->rx_opt.ts_recent_stamp = 0;
604 		newtp->tcp_header_len = sizeof(struct tcphdr);
605 	}
606 	if (req->num_timeout) {
607 		newtp->total_rto = req->num_timeout;
608 		newtp->undo_marker = treq->snt_isn;
609 		if (newtp->tcp_usec_ts) {
610 			newtp->retrans_stamp = treq->snt_synack;
611 			newtp->total_rto_time = (u32)(tcp_clock_us() -
612 						      newtp->retrans_stamp) / USEC_PER_MSEC;
613 		} else {
614 			newtp->retrans_stamp = div_u64(treq->snt_synack,
615 						       USEC_PER_SEC / TCP_TS_HZ);
616 			newtp->total_rto_time = tcp_clock_ms() -
617 						newtp->retrans_stamp;
618 		}
619 		newtp->total_rto_recoveries = 1;
620 	}
621 	newtp->tsoffset = treq->ts_off;
622 #ifdef CONFIG_TCP_MD5SIG
623 	newtp->md5sig_info = NULL;	/*XXX*/
624 #endif
625 #ifdef CONFIG_TCP_AO
626 	newtp->ao_info = NULL;
627 
628 	if (tcp_rsk_used_ao(req)) {
629 		struct tcp_ao_key *ao_key;
630 
631 		ao_key = treq->af_specific->ao_lookup(sk, req, tcp_rsk(req)->ao_keyid, -1);
632 		if (ao_key)
633 			newtp->tcp_header_len += tcp_ao_len_aligned(ao_key);
634 	}
635  #endif
636 	if (skb->len >= TCP_MSS_DEFAULT + newtp->tcp_header_len)
637 		newicsk->icsk_ack.last_seg_size = skb->len - newtp->tcp_header_len;
638 	newtp->rx_opt.mss_clamp = req->mss;
639 	tcp_ecn_openreq_child(newsk, req, skb);
640 	newtp->fastopen_req = NULL;
641 	RCU_INIT_POINTER(newtp->fastopen_rsk, NULL);
642 
643 	newtp->bpf_chg_cc_inprogress = 0;
644 	tcp_bpf_clone(sk, newsk);
645 
646 	__TCP_INC_STATS(sock_net(sk), TCP_MIB_PASSIVEOPENS);
647 
648 	xa_init_flags(&newsk->sk_user_frags, XA_FLAGS_ALLOC1);
649 
650 	return newsk;
651 }
652 EXPORT_SYMBOL(tcp_create_openreq_child);
653 
654 /*
655  * Process an incoming packet for SYN_RECV sockets represented as a
656  * request_sock. Normally sk is the listener socket but for TFO it
657  * points to the child socket.
658  *
659  * XXX (TFO) - The current impl contains a special check for ack
660  * validation and inside tcp_v4_reqsk_send_ack(). Can we do better?
661  *
662  * We don't need to initialize tmp_opt.sack_ok as we don't use the results
663  *
664  * Note: If @fastopen is true, this can be called from process context.
665  *       Otherwise, this is from BH context.
666  */
667 
668 struct sock *tcp_check_req(struct sock *sk, struct sk_buff *skb,
669 			   struct request_sock *req,
670 			   bool fastopen, bool *req_stolen,
671 			   enum skb_drop_reason *drop_reason)
672 {
673 	struct tcp_options_received tmp_opt;
674 	struct sock *child;
675 	const struct tcphdr *th = tcp_hdr(skb);
676 	__be32 flg = tcp_flag_word(th) & (TCP_FLAG_RST|TCP_FLAG_SYN|TCP_FLAG_ACK);
677 	bool tsecr_reject = false;
678 	bool paws_reject = false;
679 	bool own_req;
680 
681 	tmp_opt.saw_tstamp = 0;
682 	tmp_opt.accecn = 0;
683 	if (th->doff > (sizeof(struct tcphdr)>>2)) {
684 		tcp_parse_options(sock_net(sk), skb, &tmp_opt, 0, NULL);
685 
686 		if (tmp_opt.saw_tstamp) {
687 			tmp_opt.ts_recent = req->ts_recent;
688 			if (tmp_opt.rcv_tsecr) {
689 				if (inet_rsk(req)->tstamp_ok && !fastopen)
690 					tsecr_reject = !between(tmp_opt.rcv_tsecr,
691 							tcp_rsk(req)->snt_tsval_first,
692 							READ_ONCE(tcp_rsk(req)->snt_tsval_last));
693 				tmp_opt.rcv_tsecr -= tcp_rsk(req)->ts_off;
694 			}
695 			/* We do not store true stamp, but it is not required,
696 			 * it can be estimated (approximately)
697 			 * from another data.
698 			 */
699 			tmp_opt.ts_recent_stamp = ktime_get_seconds() - reqsk_timeout(req, TCP_RTO_MAX) / HZ;
700 			paws_reject = tcp_paws_reject(&tmp_opt, th->rst);
701 		}
702 	}
703 
704 	/* Check for pure retransmitted SYN. */
705 	if (TCP_SKB_CB(skb)->seq == tcp_rsk(req)->rcv_isn &&
706 	    flg == TCP_FLAG_SYN &&
707 	    !paws_reject) {
708 		/*
709 		 * RFC793 draws (Incorrectly! It was fixed in RFC1122)
710 		 * this case on figure 6 and figure 8, but formal
711 		 * protocol description says NOTHING.
712 		 * To be more exact, it says that we should send ACK,
713 		 * because this segment (at least, if it has no data)
714 		 * is out of window.
715 		 *
716 		 *  CONCLUSION: RFC793 (even with RFC1122) DOES NOT
717 		 *  describe SYN-RECV state. All the description
718 		 *  is wrong, we cannot believe to it and should
719 		 *  rely only on common sense and implementation
720 		 *  experience.
721 		 *
722 		 * Enforce "SYN-ACK" according to figure 8, figure 6
723 		 * of RFC793, fixed by RFC1122.
724 		 *
725 		 * Note that even if there is new data in the SYN packet
726 		 * they will be thrown away too.
727 		 *
728 		 * Reset timer after retransmitting SYNACK, similar to
729 		 * the idea of fast retransmit in recovery.
730 		 */
731 		if (!tcp_oow_rate_limited(sock_net(sk), skb,
732 					  LINUX_MIB_TCPACKSKIPPEDSYNRECV,
733 					  &tcp_rsk(req)->last_oow_ack_time) &&
734 
735 		    !tcp_rtx_synack(sk, req)) {
736 			unsigned long expires = jiffies;
737 
738 			expires += reqsk_timeout(req, TCP_RTO_MAX);
739 			if (!fastopen)
740 				mod_timer_pending(&req->rsk_timer, expires);
741 			else
742 				req->rsk_timer.expires = expires;
743 		}
744 		return NULL;
745 	}
746 
747 	/* Further reproduces section "SEGMENT ARRIVES"
748 	   for state SYN-RECEIVED of RFC793.
749 	   It is broken, however, it does not work only
750 	   when SYNs are crossed.
751 
752 	   You would think that SYN crossing is impossible here, since
753 	   we should have a SYN_SENT socket (from connect()) on our end,
754 	   but this is not true if the crossed SYNs were sent to both
755 	   ends by a malicious third party.  We must defend against this,
756 	   and to do that we first verify the ACK (as per RFC793, page
757 	   36) and reset if it is invalid.  Is this a true full defense?
758 	   To convince ourselves, let us consider a way in which the ACK
759 	   test can still pass in this 'malicious crossed SYNs' case.
760 	   Malicious sender sends identical SYNs (and thus identical sequence
761 	   numbers) to both A and B:
762 
763 		A: gets SYN, seq=7
764 		B: gets SYN, seq=7
765 
766 	   By our good fortune, both A and B select the same initial
767 	   send sequence number of seven :-)
768 
769 		A: sends SYN|ACK, seq=7, ack_seq=8
770 		B: sends SYN|ACK, seq=7, ack_seq=8
771 
772 	   So we are now A eating this SYN|ACK, ACK test passes.  So
773 	   does sequence test, SYN is truncated, and thus we consider
774 	   it a bare ACK.
775 
776 	   If icsk->icsk_accept_queue.rskq_defer_accept, we silently drop this
777 	   bare ACK.  Otherwise, we create an established connection.  Both
778 	   ends (listening sockets) accept the new incoming connection and try
779 	   to talk to each other. 8-)
780 
781 	   Note: This case is both harmless, and rare.  Possibility is about the
782 	   same as us discovering intelligent life on another plant tomorrow.
783 
784 	   But generally, we should (RFC lies!) to accept ACK
785 	   from SYNACK both here and in tcp_rcv_state_process().
786 	   tcp_rcv_state_process() does not, hence, we do not too.
787 
788 	   Note that the case is absolutely generic:
789 	   we cannot optimize anything here without
790 	   violating protocol. All the checks must be made
791 	   before attempt to create socket.
792 	 */
793 
794 	/* RFC793 page 36: "If the connection is in any non-synchronized state ...
795 	 *                  and the incoming segment acknowledges something not yet
796 	 *                  sent (the segment carries an unacceptable ACK) ...
797 	 *                  a reset is sent."
798 	 *
799 	 * Invalid ACK: reset will be sent by listening socket.
800 	 * Note that the ACK validity check for a Fast Open socket is done
801 	 * elsewhere and is checked directly against the child socket rather
802 	 * than req because user data may have been sent out.
803 	 */
804 	if ((flg & TCP_FLAG_ACK) && !fastopen &&
805 	    (TCP_SKB_CB(skb)->ack_seq !=
806 	     tcp_rsk(req)->snt_isn + 1))
807 		return sk;
808 
809 	/* RFC793: "first check sequence number". */
810 
811 	if (paws_reject || tsecr_reject ||
812 	    !tcp_in_window(TCP_SKB_CB(skb)->seq,
813 			   TCP_SKB_CB(skb)->end_seq,
814 			   tcp_rsk(req)->rcv_nxt,
815 			   tcp_rsk(req)->rcv_nxt +
816 			   tcp_synack_window(req))) {
817 		/* Out of window: send ACK and drop. */
818 		if (!(flg & TCP_FLAG_RST) &&
819 		    !tcp_oow_rate_limited(sock_net(sk), skb,
820 					  LINUX_MIB_TCPACKSKIPPEDSYNRECV,
821 					  &tcp_rsk(req)->last_oow_ack_time))
822 			req->rsk_ops->send_ack(sk, skb, req);
823 		if (paws_reject) {
824 			SKB_DR_SET(*drop_reason, TCP_RFC7323_PAWS);
825 			NET_INC_STATS(sock_net(sk), LINUX_MIB_PAWSESTABREJECTED);
826 		} else if (tsecr_reject) {
827 			SKB_DR_SET(*drop_reason, TCP_RFC7323_TSECR);
828 			NET_INC_STATS(sock_net(sk), LINUX_MIB_TSECRREJECTED);
829 		} else {
830 			SKB_DR_SET(*drop_reason, TCP_OVERWINDOW);
831 		}
832 		return NULL;
833 	}
834 
835 	/* In sequence, PAWS is OK. */
836 
837 	if (TCP_SKB_CB(skb)->seq == tcp_rsk(req)->rcv_isn) {
838 		/* Truncate SYN, it is out of window starting
839 		   at tcp_rsk(req)->rcv_isn + 1. */
840 		flg &= ~TCP_FLAG_SYN;
841 	}
842 
843 	/* RFC793: "second check the RST bit" and
844 	 *	   "fourth, check the SYN bit"
845 	 */
846 	if (flg & (TCP_FLAG_RST|TCP_FLAG_SYN)) {
847 		TCP_INC_STATS(sock_net(sk), TCP_MIB_ATTEMPTFAILS);
848 		goto embryonic_reset;
849 	}
850 
851 	/* ACK sequence verified above, just make sure ACK is
852 	 * set.  If ACK not set, just silently drop the packet.
853 	 *
854 	 * XXX (TFO) - if we ever allow "data after SYN", the
855 	 * following check needs to be removed.
856 	 */
857 	if (!(flg & TCP_FLAG_ACK))
858 		return NULL;
859 
860 	if (tcp_rsk(req)->accecn_ok && tmp_opt.accecn &&
861 	    tcp_rsk(req)->saw_accecn_opt < TCP_ACCECN_OPT_COUNTER_SEEN) {
862 		u8 saw_opt = tcp_accecn_option_init(skb, tmp_opt.accecn);
863 
864 		tcp_rsk(req)->saw_accecn_opt = saw_opt;
865 		if (tcp_rsk(req)->saw_accecn_opt == TCP_ACCECN_OPT_FAIL_SEEN) {
866 			u8 fail_mode = TCP_ACCECN_OPT_FAIL_RECV;
867 
868 			tcp_rsk(req)->accecn_fail_mode |= fail_mode;
869 		}
870 	}
871 
872 	/* For Fast Open no more processing is needed (sk is the
873 	 * child socket).
874 	 */
875 	if (fastopen)
876 		return sk;
877 
878 	/* While TCP_DEFER_ACCEPT is active, drop bare ACK. */
879 	if (req->num_timeout < READ_ONCE(inet_csk(sk)->icsk_accept_queue.rskq_defer_accept) &&
880 	    TCP_SKB_CB(skb)->end_seq == tcp_rsk(req)->rcv_isn + 1) {
881 		inet_rsk(req)->acked = 1;
882 		__NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDEFERACCEPTDROP);
883 		return NULL;
884 	}
885 
886 	/* OK, ACK is valid, create big socket and
887 	 * feed this segment to it. It will repeat all
888 	 * the tests. THIS SEGMENT MUST MOVE SOCKET TO
889 	 * ESTABLISHED STATE. If it will be dropped after
890 	 * socket is created, wait for troubles.
891 	 */
892 	child = inet_csk(sk)->icsk_af_ops->syn_recv_sock(sk, skb, req, NULL,
893 							 req, &own_req);
894 	if (!child)
895 		goto listen_overflow;
896 
897 	if (own_req && tmp_opt.saw_tstamp &&
898 	    !after(TCP_SKB_CB(skb)->seq, tcp_rsk(req)->rcv_nxt))
899 		tcp_sk(child)->rx_opt.ts_recent = tmp_opt.rcv_tsval;
900 
901 	if (own_req && rsk_drop_req(req)) {
902 		reqsk_queue_removed(&inet_csk(req->rsk_listener)->icsk_accept_queue, req);
903 		inet_csk_reqsk_queue_drop_and_put(req->rsk_listener, req);
904 		return child;
905 	}
906 
907 	sock_rps_save_rxhash(child, skb);
908 	tcp_synack_rtt_meas(child, req);
909 	*req_stolen = !own_req;
910 	return inet_csk_complete_hashdance(sk, child, req, own_req);
911 
912 listen_overflow:
913 	SKB_DR_SET(*drop_reason, TCP_LISTEN_OVERFLOW);
914 	if (sk != req->rsk_listener)
915 		__NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMIGRATEREQFAILURE);
916 
917 	if (!READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_abort_on_overflow)) {
918 		inet_rsk(req)->acked = 1;
919 		return NULL;
920 	}
921 
922 embryonic_reset:
923 	if (!(flg & TCP_FLAG_RST)) {
924 		/* Received a bad SYN pkt - for TFO We try not to reset
925 		 * the local connection unless it's really necessary to
926 		 * avoid becoming vulnerable to outside attack aiming at
927 		 * resetting legit local connections.
928 		 */
929 		req->rsk_ops->send_reset(sk, skb, SK_RST_REASON_INVALID_SYN);
930 	} else if (fastopen) { /* received a valid RST pkt */
931 		reqsk_fastopen_remove(sk, req, true);
932 		tcp_reset(sk, skb);
933 	}
934 	if (!fastopen) {
935 		bool unlinked = inet_csk_reqsk_queue_drop(sk, req);
936 
937 		if (unlinked)
938 			__NET_INC_STATS(sock_net(sk), LINUX_MIB_EMBRYONICRSTS);
939 		*req_stolen = !unlinked;
940 	}
941 	return NULL;
942 }
943 EXPORT_IPV6_MOD(tcp_check_req);
944 
945 /*
946  * Queue segment on the new socket if the new socket is active,
947  * otherwise we just shortcircuit this and continue with
948  * the new socket.
949  *
950  * For the vast majority of cases child->sk_state will be TCP_SYN_RECV
951  * when entering. But other states are possible due to a race condition
952  * where after __inet_lookup_established() fails but before the listener
953  * locked is obtained, other packets cause the same connection to
954  * be created.
955  */
956 
957 enum skb_drop_reason tcp_child_process(struct sock *parent, struct sock *child,
958 				       struct sk_buff *skb)
959 	__releases(&((child)->sk_lock.slock))
960 {
961 	enum skb_drop_reason reason = SKB_NOT_DROPPED_YET;
962 	int state = child->sk_state;
963 
964 	/* record sk_napi_id and sk_rx_queue_mapping of child. */
965 	sk_mark_napi_id_set(child, skb);
966 
967 	tcp_segs_in(tcp_sk(child), skb);
968 	if (!sock_owned_by_user(child)) {
969 		reason = tcp_rcv_state_process(child, skb);
970 		/* Wakeup parent, send SIGIO */
971 		if (state == TCP_SYN_RECV && child->sk_state != state)
972 			parent->sk_data_ready(parent);
973 	} else {
974 		/* Alas, it is possible again, because we do lookup
975 		 * in main socket hash table and lock on listening
976 		 * socket does not protect us more.
977 		 */
978 		__sk_add_backlog(child, skb);
979 	}
980 
981 	bh_unlock_sock(child);
982 	sock_put(child);
983 	return reason;
984 }
985 EXPORT_IPV6_MOD(tcp_child_process);
986