xref: /linux/net/ipv4/tcp_ipv4.c (revision d8674294aefef02266c4d47ad10131f1bffbe534)
1 // SPDX-License-Identifier: GPL-2.0-or-later
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  *		IPv4 specific functions
10  *
11  *		code split from:
12  *		linux/ipv4/tcp.c
13  *		linux/ipv4/tcp_input.c
14  *		linux/ipv4/tcp_output.c
15  *
16  *		See tcp.c for author information
17  */
18 
19 /*
20  * Changes:
21  *		David S. Miller	:	New socket lookup architecture.
22  *					This code is dedicated to John Dyson.
23  *		David S. Miller :	Change semantics of established hash,
24  *					half is devoted to TIME_WAIT sockets
25  *					and the rest go in the other half.
26  *		Andi Kleen :		Add support for syncookies and fixed
27  *					some bugs: ip options weren't passed to
28  *					the TCP layer, missed a check for an
29  *					ACK bit.
30  *		Andi Kleen :		Implemented fast path mtu discovery.
31  *	     				Fixed many serious bugs in the
32  *					request_sock handling and moved
33  *					most of it into the af independent code.
34  *					Added tail drop and some other bugfixes.
35  *					Added new listen semantics.
36  *		Mike McLagan	:	Routing by source
37  *	Juan Jose Ciarlante:		ip_dynaddr bits
38  *		Andi Kleen:		various fixes.
39  *	Vitaly E. Lavrov	:	Transparent proxy revived after year
40  *					coma.
41  *	Andi Kleen		:	Fix new listen.
42  *	Andi Kleen		:	Fix accept error reporting.
43  *	YOSHIFUJI Hideaki @USAGI and:	Support IPV6_V6ONLY socket option, which
44  *	Alexey Kuznetsov		allow both IPv4 and IPv6 sockets to bind
45  *					a single port at the same time.
46  */
47 
48 #define pr_fmt(fmt) "TCP: " fmt
49 
50 #include <linux/bottom_half.h>
51 #include <linux/types.h>
52 #include <linux/fcntl.h>
53 #include <linux/module.h>
54 #include <linux/random.h>
55 #include <linux/cache.h>
56 #include <linux/fips.h>
57 #include <linux/jhash.h>
58 #include <linux/init.h>
59 #include <linux/times.h>
60 #include <linux/slab.h>
61 #include <linux/sched.h>
62 #include <linux/sock_diag.h>
63 
64 #include <net/aligned_data.h>
65 #include <net/net_namespace.h>
66 #include <net/icmp.h>
67 #include <net/inet_hashtables.h>
68 #include <net/tcp.h>
69 #include <net/tcp_ecn.h>
70 #include <net/transp_v6.h>
71 #include <net/ipv6.h>
72 #include <net/inet_common.h>
73 #include <net/inet_ecn.h>
74 #include <net/timewait_sock.h>
75 #include <net/xfrm.h>
76 #include <net/secure_seq.h>
77 #include <net/busy_poll.h>
78 #include <net/rstreason.h>
79 #include <net/psp.h>
80 
81 #include <linux/inet.h>
82 #include <linux/ipv6.h>
83 #include <linux/stddef.h>
84 #include <linux/proc_fs.h>
85 #include <linux/seq_file.h>
86 #include <linux/inetdevice.h>
87 #include <linux/btf_ids.h>
88 #include <linux/skbuff_ref.h>
89 
90 #include <crypto/md5.h>
91 #include <crypto/utils.h>
92 
93 #include <trace/events/tcp.h>
94 
95 #ifdef CONFIG_TCP_MD5SIG
96 static void tcp_v4_md5_hash_hdr(char *md5_hash, const struct tcp_md5sig_key *key,
97 				__be32 daddr, __be32 saddr, const struct tcphdr *th);
98 #endif
99 
100 struct inet_hashinfo tcp_hashinfo;
101 
102 static DEFINE_PER_CPU(struct sock_bh_locked, ipv4_tcp_sk) = {
103 	.bh_lock = INIT_LOCAL_LOCK(bh_lock),
104 };
105 
106 static DEFINE_MUTEX(tcp_exit_batch_mutex);
107 
108 INDIRECT_CALLABLE_SCOPE union tcp_seq_and_ts_off
109 tcp_v4_init_seq_and_ts_off(const struct net *net, const struct sk_buff *skb)
110 {
111 	return secure_tcp_seq_and_ts_off(net,
112 					 ip_hdr(skb)->daddr,
113 					 ip_hdr(skb)->saddr,
114 					 tcp_hdr(skb)->dest,
115 					 tcp_hdr(skb)->source);
116 }
117 
118 int tcp_twsk_unique(struct sock *sk, struct sock *sktw, void *twp)
119 {
120 	int reuse = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_tw_reuse);
121 	const struct inet_timewait_sock *tw = inet_twsk(sktw);
122 	const struct tcp_timewait_sock *tcptw = tcp_twsk(sktw);
123 	struct tcp_sock *tp = tcp_sk(sk);
124 	int ts_recent_stamp;
125 	u32 reuse_thresh;
126 
127 	if (READ_ONCE(tw->tw_substate) == TCP_FIN_WAIT2)
128 		reuse = 0;
129 
130 	if (reuse == 2) {
131 		/* Still does not detect *everything* that goes through
132 		 * lo, since we require a loopback src or dst address
133 		 * or direct binding to 'lo' interface.
134 		 */
135 		bool loopback = false;
136 		if (tw->tw_bound_dev_if == LOOPBACK_IFINDEX)
137 			loopback = true;
138 #if IS_ENABLED(CONFIG_IPV6)
139 		if (tw->tw_family == AF_INET6) {
140 			if (ipv6_addr_loopback(&tw->tw_v6_daddr) ||
141 			    ipv6_addr_v4mapped_loopback(&tw->tw_v6_daddr) ||
142 			    ipv6_addr_loopback(&tw->tw_v6_rcv_saddr) ||
143 			    ipv6_addr_v4mapped_loopback(&tw->tw_v6_rcv_saddr))
144 				loopback = true;
145 		} else
146 #endif
147 		{
148 			if (ipv4_is_loopback(tw->tw_daddr) ||
149 			    ipv4_is_loopback(tw->tw_rcv_saddr))
150 				loopback = true;
151 		}
152 		if (!loopback)
153 			reuse = 0;
154 	}
155 
156 	/* With PAWS, it is safe from the viewpoint
157 	   of data integrity. Even without PAWS it is safe provided sequence
158 	   spaces do not overlap i.e. at data rates <= 80Mbit/sec.
159 
160 	   Actually, the idea is close to VJ's one, only timestamp cache is
161 	   held not per host, but per port pair and TW bucket is used as state
162 	   holder.
163 
164 	   If TW bucket has been already destroyed we fall back to VJ's scheme
165 	   and use initial timestamp retrieved from peer table.
166 	 */
167 	ts_recent_stamp = READ_ONCE(tcptw->tw_ts_recent_stamp);
168 	reuse_thresh = READ_ONCE(tw->tw_entry_stamp) +
169 		       READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_tw_reuse_delay);
170 	if (ts_recent_stamp &&
171 	    (!twp || (reuse && time_after32(tcp_clock_ms(), reuse_thresh)))) {
172 		/* inet_twsk_hashdance_schedule() sets sk_refcnt after putting twsk
173 		 * and releasing the bucket lock.
174 		 */
175 		if (unlikely(!refcount_inc_not_zero(&sktw->sk_refcnt)))
176 			return 0;
177 
178 		/* In case of repair and re-using TIME-WAIT sockets we still
179 		 * want to be sure that it is safe as above but honor the
180 		 * sequence numbers and time stamps set as part of the repair
181 		 * process.
182 		 *
183 		 * Without this check re-using a TIME-WAIT socket with TCP
184 		 * repair would accumulate a -1 on the repair assigned
185 		 * sequence number. The first time it is reused the sequence
186 		 * is -1, the second time -2, etc. This fixes that issue
187 		 * without appearing to create any others.
188 		 */
189 		if (likely(!tp->repair)) {
190 			u32 seq = tcptw->tw_snd_nxt + 65535 + 2;
191 
192 			if (!seq)
193 				seq = 1;
194 			WRITE_ONCE(tp->write_seq, seq);
195 			tp->rx_opt.ts_recent	   = READ_ONCE(tcptw->tw_ts_recent);
196 			tp->rx_opt.ts_recent_stamp = ts_recent_stamp;
197 		}
198 
199 		return 1;
200 	}
201 
202 	return 0;
203 }
204 
205 static int tcp_v4_pre_connect(struct sock *sk, struct sockaddr_unsized *uaddr,
206 			      int addr_len)
207 {
208 	/* This check is replicated from tcp_v4_connect() and intended to
209 	 * prevent BPF program called below from accessing bytes that are out
210 	 * of the bound specified by user in addr_len.
211 	 */
212 	if (addr_len < sizeof(struct sockaddr_in))
213 		return -EINVAL;
214 
215 	sock_owned_by_me(sk);
216 
217 	return BPF_CGROUP_RUN_PROG_INET4_CONNECT(sk, uaddr, &addr_len);
218 }
219 
220 /* This will initiate an outgoing connection. */
221 int tcp_v4_connect(struct sock *sk, struct sockaddr_unsized *uaddr, int addr_len)
222 {
223 	struct sockaddr_in *usin = (struct sockaddr_in *)uaddr;
224 	struct inet_timewait_death_row *tcp_death_row;
225 	struct inet_sock *inet = inet_sk(sk);
226 	struct tcp_sock *tp = tcp_sk(sk);
227 	struct ip_options_rcu *inet_opt;
228 	struct net *net = sock_net(sk);
229 	__be16 orig_sport, orig_dport;
230 	__be32 daddr, nexthop;
231 	struct flowi4 *fl4;
232 	struct rtable *rt;
233 	int err;
234 
235 	if (addr_len < sizeof(struct sockaddr_in))
236 		return -EINVAL;
237 
238 	if (usin->sin_family != AF_INET)
239 		return -EAFNOSUPPORT;
240 
241 	if (psp_sk_assoc(sk))
242 		return -EINVAL;
243 
244 	nexthop = daddr = usin->sin_addr.s_addr;
245 	inet_opt = rcu_dereference_protected(inet->inet_opt,
246 					     lockdep_sock_is_held(sk));
247 	if (inet_opt && inet_opt->opt.srr) {
248 		if (!daddr)
249 			return -EINVAL;
250 		nexthop = inet_opt->opt.faddr;
251 	}
252 
253 	orig_sport = inet->inet_sport;
254 	orig_dport = usin->sin_port;
255 	fl4 = &inet->cork.fl.u.ip4;
256 	rt = ip_route_connect(fl4, nexthop, inet->inet_saddr,
257 			      sk->sk_bound_dev_if, IPPROTO_TCP, orig_sport,
258 			      orig_dport, sk);
259 	if (IS_ERR(rt)) {
260 		err = PTR_ERR(rt);
261 		if (err == -ENETUNREACH)
262 			IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
263 		return err;
264 	}
265 
266 	if (rt->rt_flags & (RTCF_MULTICAST | RTCF_BROADCAST)) {
267 		ip_rt_put(rt);
268 		return -ENETUNREACH;
269 	}
270 
271 	if (!inet_opt || !inet_opt->opt.srr)
272 		daddr = fl4->daddr;
273 
274 	tcp_death_row = &sock_net(sk)->ipv4.tcp_death_row;
275 
276 	if (!inet->inet_saddr) {
277 		err = inet_bhash2_update_saddr(sk,  &fl4->saddr, AF_INET);
278 		if (err) {
279 			ip_rt_put(rt);
280 			return err;
281 		}
282 	} else {
283 		sk_rcv_saddr_set(sk, inet->inet_saddr);
284 	}
285 
286 	if (tp->rx_opt.ts_recent_stamp && inet->inet_daddr != daddr) {
287 		/* Reset inherited state */
288 		tp->rx_opt.ts_recent	   = 0;
289 		tp->rx_opt.ts_recent_stamp = 0;
290 		if (likely(!tp->repair))
291 			WRITE_ONCE(tp->write_seq, 0);
292 	}
293 
294 	inet->inet_dport = usin->sin_port;
295 	sk_daddr_set(sk, daddr);
296 
297 	inet_csk(sk)->icsk_ext_hdr_len = 0;
298 	if (inet_opt)
299 		inet_csk(sk)->icsk_ext_hdr_len = inet_opt->opt.optlen;
300 
301 	tp->rx_opt.mss_clamp = TCP_MSS_DEFAULT;
302 
303 	/* Socket identity is still unknown (sport may be zero).
304 	 * However we set state to SYN-SENT and not releasing socket
305 	 * lock select source port, enter ourselves into the hash tables and
306 	 * complete initialization after this.
307 	 */
308 	tcp_set_state(sk, TCP_SYN_SENT);
309 	err = inet_hash_connect(tcp_death_row, sk);
310 	if (err)
311 		goto failure;
312 
313 	sk_set_txhash(sk);
314 
315 	rt = ip_route_newports(fl4, rt, orig_sport, orig_dport,
316 			       inet->inet_sport, inet->inet_dport, sk);
317 	if (IS_ERR(rt)) {
318 		err = PTR_ERR(rt);
319 		rt = NULL;
320 		goto failure;
321 	}
322 	tp->tcp_usec_ts = dst_tcp_usec_ts(&rt->dst);
323 	/* OK, now commit destination to socket.  */
324 	sk->sk_gso_type = SKB_GSO_TCPV4;
325 	sk_setup_caps(sk, &rt->dst);
326 	rt = NULL;
327 
328 	if (likely(!tp->repair)) {
329 		union tcp_seq_and_ts_off st;
330 
331 		st = secure_tcp_seq_and_ts_off(net,
332 					       inet->inet_saddr,
333 					       inet->inet_daddr,
334 					       inet->inet_sport,
335 					       usin->sin_port);
336 		if (!tp->write_seq)
337 			WRITE_ONCE(tp->write_seq, st.seq);
338 		WRITE_ONCE(tp->tsoffset, st.ts_off);
339 	}
340 
341 	atomic_set(&inet->inet_id, get_random_u16());
342 
343 	if (tcp_fastopen_defer_connect(sk, &err))
344 		return err;
345 	if (err)
346 		goto failure;
347 
348 	err = tcp_connect(sk);
349 
350 	if (err)
351 		goto failure;
352 
353 	return 0;
354 
355 failure:
356 	/*
357 	 * This unhashes the socket and releases the local port,
358 	 * if necessary.
359 	 */
360 	tcp_set_state(sk, TCP_CLOSE);
361 	inet_bhash2_reset_saddr(sk);
362 	ip_rt_put(rt);
363 	sk->sk_route_caps = 0;
364 	inet->inet_dport = 0;
365 	return err;
366 }
367 
368 /*
369  * This routine reacts to ICMP_FRAG_NEEDED mtu indications as defined in RFC1191.
370  * It can be called through tcp_release_cb() if socket was owned by user
371  * at the time tcp_v4_err() was called to handle ICMP message.
372  */
373 void tcp_v4_mtu_reduced(struct sock *sk)
374 {
375 	struct inet_sock *inet = inet_sk(sk);
376 	struct dst_entry *dst;
377 	u32 mtu, dmtu;
378 
379 	if ((1 << sk->sk_state) & (TCPF_LISTEN | TCPF_CLOSE))
380 		return;
381 	mtu = READ_ONCE(tcp_sk(sk)->mtu_info);
382 	dst = inet_csk_update_pmtu(sk, mtu);
383 	if (!dst)
384 		return;
385 
386 	/* Something is about to be wrong... Remember soft error
387 	 * for the case, if this connection will not able to recover.
388 	 */
389 	dmtu = dst4_mtu(dst);
390 	if (mtu < dmtu && ip_dont_fragment(sk, dst))
391 		WRITE_ONCE(sk->sk_err_soft, EMSGSIZE);
392 
393 	if (inet->pmtudisc != IP_PMTUDISC_DONT &&
394 	    ip_sk_accept_pmtu(sk) &&
395 	    inet_csk(sk)->icsk_pmtu_cookie > dmtu) {
396 		tcp_sync_mss(sk, dmtu);
397 
398 		/* Resend the TCP packet because it's
399 		 * clear that the old packet has been
400 		 * dropped. This is the new "fast" path mtu
401 		 * discovery.
402 		 */
403 		tcp_simple_retransmit(sk);
404 	} /* else let the usual retransmit timer handle it */
405 }
406 
407 static void do_redirect(struct sk_buff *skb, struct sock *sk)
408 {
409 	struct dst_entry *dst = __sk_dst_check(sk, 0);
410 
411 	if (dst)
412 		dst->ops->redirect(dst, sk, skb);
413 }
414 
415 
416 /* handle ICMP messages on TCP_NEW_SYN_RECV request sockets */
417 void tcp_req_err(struct sock *sk, u32 seq, bool abort)
418 {
419 	struct request_sock *req = inet_reqsk(sk);
420 	struct net *net = sock_net(sk);
421 
422 	/* ICMPs are not backlogged, hence we cannot get
423 	 * an established socket here.
424 	 */
425 	if (seq != tcp_rsk(req)->snt_isn) {
426 		__NET_INC_STATS(net, LINUX_MIB_OUTOFWINDOWICMPS);
427 	} else if (abort) {
428 		/*
429 		 * Still in SYN_RECV, just remove it silently.
430 		 * There is no good way to pass the error to the newly
431 		 * created socket, and POSIX does not want network
432 		 * errors returned from accept().
433 		 */
434 		inet_csk_reqsk_queue_drop(req->rsk_listener, req);
435 		tcp_listendrop(req->rsk_listener);
436 	}
437 	reqsk_put(req);
438 }
439 
440 /* TCP-LD (RFC 6069) logic */
441 void tcp_ld_RTO_revert(struct sock *sk, u32 seq)
442 {
443 	struct inet_connection_sock *icsk = inet_csk(sk);
444 	struct tcp_sock *tp = tcp_sk(sk);
445 	struct sk_buff *skb;
446 	s32 remaining;
447 	u32 delta_us;
448 
449 	if (sock_owned_by_user(sk))
450 		return;
451 
452 	if (seq != tp->snd_una  || !icsk->icsk_retransmits ||
453 	    !icsk->icsk_backoff)
454 		return;
455 
456 	skb = tcp_rtx_queue_head(sk);
457 	if (WARN_ON_ONCE(!skb))
458 		return;
459 
460 	icsk->icsk_backoff--;
461 	icsk->icsk_rto = tp->srtt_us ? __tcp_set_rto(tp) : TCP_TIMEOUT_INIT;
462 	icsk->icsk_rto = inet_csk_rto_backoff(icsk, tcp_rto_max(sk));
463 
464 	tcp_mstamp_refresh(tp);
465 	delta_us = (u32)(tp->tcp_mstamp - tcp_skb_timestamp_us(skb));
466 	remaining = icsk->icsk_rto - usecs_to_jiffies(delta_us);
467 
468 	if (remaining > 0) {
469 		tcp_reset_xmit_timer(sk, ICSK_TIME_RETRANS, remaining, false);
470 	} else {
471 		/* RTO revert clocked out retransmission.
472 		 * Will retransmit now.
473 		 */
474 		tcp_retransmit_timer(sk);
475 	}
476 }
477 
478 /*
479  * This routine is called by the ICMP module when it gets some
480  * sort of error condition.  If err < 0 then the socket should
481  * be closed and the error returned to the user.  If err > 0
482  * it's just the icmp type << 8 | icmp code.  After adjustment
483  * header points to the first 8 bytes of the tcp header.  We need
484  * to find the appropriate port.
485  *
486  * The locking strategy used here is very "optimistic". When
487  * someone else accesses the socket the ICMP is just dropped
488  * and for some paths there is no check at all.
489  * A more general error queue to queue errors for later handling
490  * is probably better.
491  *
492  */
493 
494 int tcp_v4_err(struct sk_buff *skb, u32 info)
495 {
496 	const struct iphdr *iph = (const struct iphdr *)skb->data;
497 	struct tcphdr *th = (struct tcphdr *)(skb->data + (iph->ihl << 2));
498 	struct net *net = dev_net_rcu(skb->dev);
499 	const int type = icmp_hdr(skb)->type;
500 	const int code = icmp_hdr(skb)->code;
501 	struct request_sock *fastopen;
502 	struct tcp_sock *tp;
503 	u32 seq, snd_una;
504 	struct sock *sk;
505 	int err;
506 
507 	sk = __inet_lookup_established(net, iph->daddr, th->dest, iph->saddr,
508 				       ntohs(th->source), inet_iif(skb), 0);
509 	if (!sk) {
510 		__ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
511 		return -ENOENT;
512 	}
513 	if (sk->sk_state == TCP_TIME_WAIT) {
514 		/* To increase the counter of ignored icmps for TCP-AO */
515 		tcp_ao_ignore_icmp(sk, AF_INET, type, code);
516 		inet_twsk_put(inet_twsk(sk));
517 		return 0;
518 	}
519 	seq = ntohl(th->seq);
520 	if (sk->sk_state == TCP_NEW_SYN_RECV) {
521 		tcp_req_err(sk, seq, type == ICMP_PARAMETERPROB ||
522 				     type == ICMP_TIME_EXCEEDED ||
523 				     (type == ICMP_DEST_UNREACH &&
524 				      (code == ICMP_NET_UNREACH ||
525 				       code == ICMP_HOST_UNREACH)));
526 		return 0;
527 	}
528 
529 	if (tcp_ao_ignore_icmp(sk, AF_INET, type, code)) {
530 		sock_put(sk);
531 		return 0;
532 	}
533 
534 	bh_lock_sock(sk);
535 	/* If too many ICMPs get dropped on busy
536 	 * servers this needs to be solved differently.
537 	 * We do take care of PMTU discovery (RFC1191) special case :
538 	 * we can receive locally generated ICMP messages while socket is held.
539 	 */
540 	if (sock_owned_by_user(sk)) {
541 		if (!(type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED))
542 			__NET_INC_STATS(net, LINUX_MIB_LOCKDROPPEDICMPS);
543 	}
544 	if (sk->sk_state == TCP_CLOSE)
545 		goto out;
546 
547 	if (static_branch_unlikely(&ip4_min_ttl)) {
548 		/* min_ttl can be changed concurrently from do_ip_setsockopt() */
549 		if (unlikely(iph->ttl < READ_ONCE(inet_sk(sk)->min_ttl))) {
550 			__NET_INC_STATS(net, LINUX_MIB_TCPMINTTLDROP);
551 			goto out;
552 		}
553 	}
554 
555 	tp = tcp_sk(sk);
556 	/* XXX (TFO) - tp->snd_una should be ISN (tcp_create_openreq_child() */
557 	fastopen = rcu_dereference(tp->fastopen_rsk);
558 	snd_una = fastopen ? tcp_rsk(fastopen)->snt_isn : tp->snd_una;
559 	if (sk->sk_state != TCP_LISTEN &&
560 	    !between(seq, snd_una, tp->snd_nxt)) {
561 		__NET_INC_STATS(net, LINUX_MIB_OUTOFWINDOWICMPS);
562 		goto out;
563 	}
564 
565 	switch (type) {
566 	case ICMP_REDIRECT:
567 		if (!sock_owned_by_user(sk))
568 			do_redirect(skb, sk);
569 		goto out;
570 	case ICMP_SOURCE_QUENCH:
571 		/* Just silently ignore these. */
572 		goto out;
573 	case ICMP_PARAMETERPROB:
574 		err = EPROTO;
575 		break;
576 	case ICMP_DEST_UNREACH:
577 		if (code > NR_ICMP_UNREACH)
578 			goto out;
579 
580 		if (code == ICMP_FRAG_NEEDED) { /* PMTU discovery (RFC1191) */
581 			/* We are not interested in TCP_LISTEN and open_requests
582 			 * (SYN-ACKs send out by Linux are always <576bytes so
583 			 * they should go through unfragmented).
584 			 */
585 			if (sk->sk_state == TCP_LISTEN)
586 				goto out;
587 
588 			WRITE_ONCE(tp->mtu_info, info);
589 			if (!sock_owned_by_user(sk)) {
590 				tcp_v4_mtu_reduced(sk);
591 			} else {
592 				if (!test_and_set_bit(TCP_MTU_REDUCED_DEFERRED, &sk->sk_tsq_flags))
593 					sock_hold(sk);
594 			}
595 			goto out;
596 		}
597 
598 		err = icmp_err_convert[code].errno;
599 		/* check if this ICMP message allows revert of backoff.
600 		 * (see RFC 6069)
601 		 */
602 		if (!fastopen &&
603 		    (code == ICMP_NET_UNREACH || code == ICMP_HOST_UNREACH))
604 			tcp_ld_RTO_revert(sk, seq);
605 		break;
606 	case ICMP_TIME_EXCEEDED:
607 		err = EHOSTUNREACH;
608 		break;
609 	default:
610 		goto out;
611 	}
612 
613 	switch (sk->sk_state) {
614 	case TCP_SYN_SENT:
615 	case TCP_SYN_RECV:
616 		/* Only in fast or simultaneous open. If a fast open socket is
617 		 * already accepted it is treated as a connected one below.
618 		 */
619 		if (fastopen && !fastopen->sk)
620 			break;
621 
622 		ip_icmp_error(sk, skb, err, th->dest, info, (u8 *)th);
623 
624 		if (!sock_owned_by_user(sk))
625 			tcp_done_with_error(sk, err);
626 		else
627 			WRITE_ONCE(sk->sk_err_soft, err);
628 		goto out;
629 	}
630 
631 	/* If we've already connected we will keep trying
632 	 * until we time out, or the user gives up.
633 	 *
634 	 * rfc1122 4.2.3.9 allows to consider as hard errors
635 	 * only PROTO_UNREACH and PORT_UNREACH (well, FRAG_FAILED too,
636 	 * but it is obsoleted by pmtu discovery).
637 	 *
638 	 * Note, that in modern internet, where routing is unreliable
639 	 * and in each dark corner broken firewalls sit, sending random
640 	 * errors ordered by their masters even this two messages finally lose
641 	 * their original sense (even Linux sends invalid PORT_UNREACHs)
642 	 *
643 	 * Now we are in compliance with RFCs.
644 	 *							--ANK (980905)
645 	 */
646 
647 	if (!sock_owned_by_user(sk) &&
648 	    inet_test_bit(RECVERR, sk)) {
649 		WRITE_ONCE(sk->sk_err, err);
650 		sk_error_report(sk);
651 	} else	{ /* Only an error on timeout */
652 		WRITE_ONCE(sk->sk_err_soft, err);
653 	}
654 
655 out:
656 	bh_unlock_sock(sk);
657 	sock_put(sk);
658 	return 0;
659 }
660 
661 #define REPLY_OPTIONS_LEN      (MAX_TCP_OPTION_SPACE / sizeof(__be32))
662 
663 static bool tcp_v4_ao_sign_reset(const struct sock *sk, struct sk_buff *skb,
664 				 const struct tcp_ao_hdr *aoh,
665 				 struct ip_reply_arg *arg, struct tcphdr *reply,
666 				 __be32 reply_options[REPLY_OPTIONS_LEN])
667 {
668 #ifdef CONFIG_TCP_AO
669 	int sdif = tcp_v4_sdif(skb);
670 	int dif = inet_iif(skb);
671 	int l3index = sdif ? dif : 0;
672 	bool allocated_traffic_key;
673 	struct tcp_ao_key *key;
674 	char *traffic_key;
675 	bool drop = true;
676 	u32 ao_sne = 0;
677 	u8 keyid;
678 
679 	rcu_read_lock();
680 	if (tcp_ao_prepare_reset(sk, skb, aoh, l3index, ntohl(reply->seq),
681 				 &key, &traffic_key, &allocated_traffic_key,
682 				 &keyid, &ao_sne))
683 		goto out;
684 
685 	reply_options[0] = htonl((TCPOPT_AO << 24) | (tcp_ao_len(key) << 16) |
686 				 (aoh->rnext_keyid << 8) | keyid);
687 	arg->iov[0].iov_len += tcp_ao_len_aligned(key);
688 	reply->doff = arg->iov[0].iov_len / 4;
689 
690 	if (tcp_ao_hash_hdr(AF_INET, (char *)&reply_options[1],
691 			    key, traffic_key,
692 			    (union tcp_ao_addr *)&ip_hdr(skb)->saddr,
693 			    (union tcp_ao_addr *)&ip_hdr(skb)->daddr,
694 			    reply, ao_sne))
695 		goto out;
696 	drop = false;
697 out:
698 	rcu_read_unlock();
699 	if (allocated_traffic_key)
700 		kfree(traffic_key);
701 	return drop;
702 #else
703 	return true;
704 #endif
705 }
706 
707 /*
708  *	This routine will send an RST to the other tcp.
709  *
710  *	Someone asks: why I NEVER use socket parameters (TOS, TTL etc.)
711  *		      for reset.
712  *	Answer: if a packet caused RST, it is not for a socket
713  *		existing in our system, if it is matched to a socket,
714  *		it is just duplicate segment or bug in other side's TCP.
715  *		So that we build reply only basing on parameters
716  *		arrived with segment.
717  *	Exception: precedence violation. We do not implement it in any case.
718  */
719 
720 static void tcp_v4_send_reset(const struct sock *sk, struct sk_buff *skb,
721 			      enum sk_rst_reason reason)
722 {
723 	const struct tcphdr *th = tcp_hdr(skb);
724 	struct {
725 		struct tcphdr th;
726 		__be32 opt[REPLY_OPTIONS_LEN];
727 	} rep;
728 	const __u8 *md5_hash_location = NULL;
729 	const struct tcp_ao_hdr *aoh;
730 	struct ip_reply_arg arg;
731 #ifdef CONFIG_TCP_MD5SIG
732 	struct tcp_md5sig_key *key = NULL;
733 	unsigned char newhash[16];
734 	struct sock *sk1 = NULL;
735 #endif
736 	u64 transmit_time = 0;
737 	struct sock *ctl_sk;
738 	struct net *net;
739 	u32 txhash = 0;
740 
741 	/* Never send a reset in response to a reset. */
742 	if (th->rst)
743 		return;
744 
745 	/* If sk not NULL, it means we did a successful lookup and incoming
746 	 * route had to be correct. prequeue might have dropped our dst.
747 	 */
748 	if (!sk && skb_rtable(skb)->rt_type != RTN_LOCAL)
749 		return;
750 
751 	/* Swap the send and the receive. */
752 	memset(&rep, 0, sizeof(rep));
753 	rep.th.dest   = th->source;
754 	rep.th.source = th->dest;
755 	rep.th.doff   = sizeof(struct tcphdr) / 4;
756 	rep.th.rst    = 1;
757 
758 	if (th->ack) {
759 		rep.th.seq = th->ack_seq;
760 	} else {
761 		rep.th.ack = 1;
762 		rep.th.ack_seq = htonl(ntohl(th->seq) + th->syn + th->fin +
763 				       skb->len - (th->doff << 2));
764 	}
765 
766 	memset(&arg, 0, sizeof(arg));
767 	arg.iov[0].iov_base = (unsigned char *)&rep;
768 	arg.iov[0].iov_len  = sizeof(rep.th);
769 
770 	net = sk ? sock_net(sk) : skb_dst_dev_net_rcu(skb);
771 
772 	/* Invalid TCP option size or twice included auth */
773 	if (tcp_parse_auth_options(tcp_hdr(skb), &md5_hash_location, &aoh))
774 		return;
775 
776 	if (aoh && tcp_v4_ao_sign_reset(sk, skb, aoh, &arg, &rep.th, rep.opt))
777 		return;
778 
779 #ifdef CONFIG_TCP_MD5SIG
780 	rcu_read_lock();
781 	if (sk && sk_fullsock(sk)) {
782 		const union tcp_md5_addr *addr;
783 		int l3index;
784 
785 		/* sdif set, means packet ingressed via a device
786 		 * in an L3 domain and inet_iif is set to it.
787 		 */
788 		l3index = tcp_v4_sdif(skb) ? inet_iif(skb) : 0;
789 		addr = (union tcp_md5_addr *)&ip_hdr(skb)->saddr;
790 		key = tcp_md5_do_lookup(sk, l3index, addr, AF_INET);
791 	} else if (md5_hash_location) {
792 		const union tcp_md5_addr *addr;
793 		int sdif = tcp_v4_sdif(skb);
794 		int dif = inet_iif(skb);
795 		int l3index;
796 
797 		/*
798 		 * active side is lost. Try to find listening socket through
799 		 * source port, and then find md5 key through listening socket.
800 		 * we are not loose security here:
801 		 * Incoming packet is checked with md5 hash with finding key,
802 		 * no RST generated if md5 hash doesn't match.
803 		 */
804 		sk1 = __inet_lookup_listener(net, NULL, 0, ip_hdr(skb)->saddr,
805 					     th->source, ip_hdr(skb)->daddr,
806 					     ntohs(th->source), dif, sdif);
807 		/* don't send rst if it can't find key */
808 		if (!sk1)
809 			goto out;
810 
811 		/* sdif set, means packet ingressed via a device
812 		 * in an L3 domain and dif is set to it.
813 		 */
814 		l3index = sdif ? dif : 0;
815 		addr = (union tcp_md5_addr *)&ip_hdr(skb)->saddr;
816 		key = tcp_md5_do_lookup(sk1, l3index, addr, AF_INET);
817 		if (!key)
818 			goto out;
819 
820 		tcp_v4_md5_hash_skb(newhash, key, NULL, skb);
821 		if (crypto_memneq(md5_hash_location, newhash, 16))
822 			goto out;
823 	}
824 
825 	if (key) {
826 		rep.opt[0] = htonl((TCPOPT_NOP << 24) |
827 				   (TCPOPT_NOP << 16) |
828 				   (TCPOPT_MD5SIG << 8) |
829 				   TCPOLEN_MD5SIG);
830 		/* Update length and the length the header thinks exists */
831 		arg.iov[0].iov_len += TCPOLEN_MD5SIG_ALIGNED;
832 		rep.th.doff = arg.iov[0].iov_len / 4;
833 
834 		tcp_v4_md5_hash_hdr((__u8 *) &rep.opt[1],
835 				     key, ip_hdr(skb)->saddr,
836 				     ip_hdr(skb)->daddr, &rep.th);
837 	}
838 #endif
839 	/* Can't co-exist with TCPMD5, hence check rep.opt[0] */
840 	if (rep.opt[0] == 0) {
841 		__be32 mrst = mptcp_reset_option(skb);
842 
843 		if (mrst) {
844 			rep.opt[0] = mrst;
845 			arg.iov[0].iov_len += sizeof(mrst);
846 			rep.th.doff = arg.iov[0].iov_len / 4;
847 		}
848 	}
849 
850 	arg.csum = csum_tcpudp_nofold(ip_hdr(skb)->daddr,
851 				      ip_hdr(skb)->saddr, /* XXX */
852 				      arg.iov[0].iov_len, IPPROTO_TCP, 0);
853 	arg.csumoffset = offsetof(struct tcphdr, check) / 2;
854 	arg.flags = (sk && inet_sk_transparent(sk)) ? IP_REPLY_ARG_NOSRCCHECK : 0;
855 
856 	/* When socket is gone, all binding information is lost.
857 	 * routing might fail in this case. No choice here, if we choose to force
858 	 * input interface, we will misroute in case of asymmetric route.
859 	 */
860 	if (sk)
861 		arg.bound_dev_if = sk->sk_bound_dev_if;
862 
863 	trace_tcp_send_reset(sk, skb, reason);
864 
865 	BUILD_BUG_ON(offsetof(struct sock, sk_bound_dev_if) !=
866 		     offsetof(struct inet_timewait_sock, tw_bound_dev_if));
867 
868 	/* ECN bits of TW reset are cleared */
869 	arg.tos = ip_hdr(skb)->tos & ~INET_ECN_MASK;
870 	arg.uid = sock_net_uid(net, sk && sk_fullsock(sk) ? sk : NULL);
871 	local_bh_disable();
872 	local_lock_nested_bh(&ipv4_tcp_sk.bh_lock);
873 	ctl_sk = this_cpu_read(ipv4_tcp_sk.sock);
874 
875 	sock_net_set(ctl_sk, net);
876 	if (sk) {
877 		ctl_sk->sk_mark = (sk->sk_state == TCP_TIME_WAIT) ?
878 				   inet_twsk(sk)->tw_mark : READ_ONCE(sk->sk_mark);
879 		ctl_sk->sk_priority = (sk->sk_state == TCP_TIME_WAIT) ?
880 				   inet_twsk(sk)->tw_priority : READ_ONCE(sk->sk_priority);
881 		transmit_time = tcp_transmit_time(sk);
882 		xfrm_sk_clone_policy(ctl_sk, sk);
883 		txhash = (sk->sk_state == TCP_TIME_WAIT) ?
884 			 inet_twsk(sk)->tw_txhash : sk->sk_txhash;
885 	} else {
886 		ctl_sk->sk_mark = 0;
887 		ctl_sk->sk_priority = 0;
888 	}
889 	ip_send_unicast_reply(ctl_sk, sk,
890 			      skb, &TCP_SKB_CB(skb)->header.h4.opt,
891 			      ip_hdr(skb)->saddr, ip_hdr(skb)->daddr,
892 			      &arg, arg.iov[0].iov_len,
893 			      transmit_time, txhash);
894 
895 	xfrm_sk_free_policy(ctl_sk);
896 	sock_net_set(ctl_sk, &init_net);
897 	__TCP_INC_STATS(net, TCP_MIB_OUTSEGS);
898 	__TCP_INC_STATS(net, TCP_MIB_OUTRSTS);
899 	local_unlock_nested_bh(&ipv4_tcp_sk.bh_lock);
900 	local_bh_enable();
901 
902 #ifdef CONFIG_TCP_MD5SIG
903 out:
904 	rcu_read_unlock();
905 #endif
906 }
907 
908 /* The code following below sending ACKs in SYN-RECV and TIME-WAIT states
909    outside socket context is ugly, certainly. What can I do?
910  */
911 
912 static void tcp_v4_send_ack(const struct sock *sk,
913 			    struct sk_buff *skb, u32 seq, u32 ack,
914 			    u32 win, u32 tsval, u32 tsecr, int oif,
915 			    struct tcp_key *key,
916 			    int reply_flags, u8 tos, u32 txhash)
917 {
918 	const struct tcphdr *th = tcp_hdr(skb);
919 	struct {
920 		struct tcphdr th;
921 		__be32 opt[(MAX_TCP_OPTION_SPACE  >> 2)];
922 	} rep;
923 	struct net *net = sock_net(sk);
924 	struct ip_reply_arg arg;
925 	struct sock *ctl_sk;
926 	u64 transmit_time;
927 
928 	memset(&rep.th, 0, sizeof(struct tcphdr));
929 	memset(&arg, 0, sizeof(arg));
930 
931 	arg.iov[0].iov_base = (unsigned char *)&rep;
932 	arg.iov[0].iov_len  = sizeof(rep.th);
933 	if (tsecr) {
934 		rep.opt[0] = htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) |
935 				   (TCPOPT_TIMESTAMP << 8) |
936 				   TCPOLEN_TIMESTAMP);
937 		rep.opt[1] = htonl(tsval);
938 		rep.opt[2] = htonl(tsecr);
939 		arg.iov[0].iov_len += TCPOLEN_TSTAMP_ALIGNED;
940 	}
941 
942 	/* Swap the send and the receive. */
943 	rep.th.dest    = th->source;
944 	rep.th.source  = th->dest;
945 	rep.th.doff    = arg.iov[0].iov_len / 4;
946 	rep.th.seq     = htonl(seq);
947 	rep.th.ack_seq = htonl(ack);
948 	rep.th.ack     = 1;
949 	rep.th.window  = htons(win);
950 
951 #ifdef CONFIG_TCP_MD5SIG
952 	if (tcp_key_is_md5(key)) {
953 		int offset = (tsecr) ? 3 : 0;
954 
955 		rep.opt[offset++] = htonl((TCPOPT_NOP << 24) |
956 					  (TCPOPT_NOP << 16) |
957 					  (TCPOPT_MD5SIG << 8) |
958 					  TCPOLEN_MD5SIG);
959 		arg.iov[0].iov_len += TCPOLEN_MD5SIG_ALIGNED;
960 		rep.th.doff = arg.iov[0].iov_len/4;
961 
962 		tcp_v4_md5_hash_hdr((__u8 *) &rep.opt[offset],
963 				    key->md5_key, ip_hdr(skb)->saddr,
964 				    ip_hdr(skb)->daddr, &rep.th);
965 	}
966 #endif
967 #ifdef CONFIG_TCP_AO
968 	if (tcp_key_is_ao(key)) {
969 		int offset = (tsecr) ? 3 : 0;
970 
971 		rep.opt[offset++] = htonl((TCPOPT_AO << 24) |
972 					  (tcp_ao_len(key->ao_key) << 16) |
973 					  (key->ao_key->sndid << 8) |
974 					  key->rcv_next);
975 		arg.iov[0].iov_len += tcp_ao_len_aligned(key->ao_key);
976 		rep.th.doff = arg.iov[0].iov_len / 4;
977 		memset((u8 *)&rep.opt[offset] + tcp_ao_maclen(key->ao_key),
978 		       TCPOPT_NOP, tcp_ao_len_aligned(key->ao_key) -
979 				    tcp_ao_len(key->ao_key));
980 
981 		tcp_ao_hash_hdr(AF_INET, (char *)&rep.opt[offset],
982 				key->ao_key, key->traffic_key,
983 				(union tcp_ao_addr *)&ip_hdr(skb)->saddr,
984 				(union tcp_ao_addr *)&ip_hdr(skb)->daddr,
985 				&rep.th, key->sne);
986 	}
987 #endif
988 	arg.flags = reply_flags;
989 	arg.csum = csum_tcpudp_nofold(ip_hdr(skb)->daddr,
990 				      ip_hdr(skb)->saddr, /* XXX */
991 				      arg.iov[0].iov_len, IPPROTO_TCP, 0);
992 	arg.csumoffset = offsetof(struct tcphdr, check) / 2;
993 	if (oif)
994 		arg.bound_dev_if = oif;
995 	arg.tos = tos;
996 	arg.uid = sock_net_uid(net, sk_fullsock(sk) ? sk : NULL);
997 	local_bh_disable();
998 	local_lock_nested_bh(&ipv4_tcp_sk.bh_lock);
999 	ctl_sk = this_cpu_read(ipv4_tcp_sk.sock);
1000 	sock_net_set(ctl_sk, net);
1001 	ctl_sk->sk_mark = (sk->sk_state == TCP_TIME_WAIT) ?
1002 			   inet_twsk(sk)->tw_mark : READ_ONCE(sk->sk_mark);
1003 	ctl_sk->sk_priority = (sk->sk_state == TCP_TIME_WAIT) ?
1004 			   inet_twsk(sk)->tw_priority : READ_ONCE(sk->sk_priority);
1005 	transmit_time = tcp_transmit_time(sk);
1006 	ip_send_unicast_reply(ctl_sk, sk,
1007 			      skb, &TCP_SKB_CB(skb)->header.h4.opt,
1008 			      ip_hdr(skb)->saddr, ip_hdr(skb)->daddr,
1009 			      &arg, arg.iov[0].iov_len,
1010 			      transmit_time, txhash);
1011 
1012 	sock_net_set(ctl_sk, &init_net);
1013 	__TCP_INC_STATS(net, TCP_MIB_OUTSEGS);
1014 	local_unlock_nested_bh(&ipv4_tcp_sk.bh_lock);
1015 	local_bh_enable();
1016 }
1017 
1018 static void tcp_v4_timewait_ack(struct sock *sk, struct sk_buff *skb,
1019 				enum tcp_tw_status tw_status)
1020 {
1021 	struct inet_timewait_sock *tw = inet_twsk(sk);
1022 	struct tcp_timewait_sock *tcptw = tcp_twsk(sk);
1023 	struct tcp_key key = {};
1024 	u8 tos = tw->tw_tos;
1025 
1026 	/* Cleaning only ECN bits of TW ACKs of oow data or is paws_reject,
1027 	 * while not cleaning ECN bits of other TW ACKs to avoid these ACKs
1028 	 * being placed in a different service queues (Classic rather than L4S)
1029 	 */
1030 	if (tw_status == TCP_TW_ACK_OOW)
1031 		tos &= ~INET_ECN_MASK;
1032 
1033 #ifdef CONFIG_TCP_AO
1034 	struct tcp_ao_info *ao_info;
1035 
1036 	if (static_branch_unlikely(&tcp_ao_needed.key)) {
1037 		/* FIXME: the segment to-be-acked is not verified yet */
1038 		ao_info = rcu_dereference(tcptw->ao_info);
1039 		if (ao_info) {
1040 			const struct tcp_ao_hdr *aoh;
1041 
1042 			if (tcp_parse_auth_options(tcp_hdr(skb), NULL, &aoh)) {
1043 				inet_twsk_put(tw);
1044 				return;
1045 			}
1046 
1047 			if (aoh)
1048 				key.ao_key = tcp_ao_established_key(sk, ao_info,
1049 								    aoh->rnext_keyid, -1);
1050 		}
1051 	}
1052 	if (key.ao_key) {
1053 		struct tcp_ao_key *rnext_key;
1054 
1055 		key.traffic_key = snd_other_key(key.ao_key);
1056 		key.sne = READ_ONCE(ao_info->snd_sne);
1057 		rnext_key = READ_ONCE(ao_info->rnext_key);
1058 		key.rcv_next = rnext_key->rcvid;
1059 		key.type = TCP_KEY_AO;
1060 #else
1061 	if (0) {
1062 #endif
1063 	} else if (static_branch_tcp_md5()) {
1064 		key.md5_key = tcp_twsk_md5_key(tcptw);
1065 		if (key.md5_key)
1066 			key.type = TCP_KEY_MD5;
1067 	}
1068 
1069 	tcp_v4_send_ack(sk, skb,
1070 			tcptw->tw_snd_nxt, READ_ONCE(tcptw->tw_rcv_nxt),
1071 			tcptw->tw_rcv_wnd >> tw->tw_rcv_wscale,
1072 			tcp_tw_tsval(tcptw),
1073 			READ_ONCE(tcptw->tw_ts_recent),
1074 			tw->tw_bound_dev_if, &key,
1075 			tw->tw_transparent ? IP_REPLY_ARG_NOSRCCHECK : 0,
1076 			tos,
1077 			tw->tw_txhash);
1078 
1079 	inet_twsk_put(tw);
1080 }
1081 
1082 static void tcp_v4_reqsk_send_ack(const struct sock *sk, struct sk_buff *skb,
1083 				  struct request_sock *req)
1084 {
1085 	struct tcp_key key = {};
1086 
1087 	/* sk->sk_state == TCP_LISTEN -> for regular TCP_SYN_RECV
1088 	 * sk->sk_state == TCP_SYN_RECV -> for Fast Open.
1089 	 */
1090 	u32 seq = (sk->sk_state == TCP_LISTEN) ? tcp_rsk(req)->snt_isn + 1 :
1091 					     tcp_sk(sk)->snd_nxt;
1092 
1093 #ifdef CONFIG_TCP_AO
1094 	if (static_branch_unlikely(&tcp_ao_needed.key) &&
1095 	    tcp_rsk_used_ao(req)) {
1096 		const union tcp_md5_addr *addr;
1097 		const struct tcp_ao_hdr *aoh;
1098 		int l3index;
1099 
1100 		/* Invalid TCP option size or twice included auth */
1101 		if (tcp_parse_auth_options(tcp_hdr(skb), NULL, &aoh))
1102 			return;
1103 		if (!aoh)
1104 			return;
1105 
1106 		addr = (union tcp_md5_addr *)&ip_hdr(skb)->saddr;
1107 		l3index = tcp_v4_sdif(skb) ? inet_iif(skb) : 0;
1108 		key.ao_key = tcp_ao_do_lookup(sk, l3index, addr, AF_INET,
1109 					      aoh->rnext_keyid, -1);
1110 		if (unlikely(!key.ao_key)) {
1111 			/* Send ACK with any matching MKT for the peer */
1112 			key.ao_key = tcp_ao_do_lookup(sk, l3index, addr, AF_INET, -1, -1);
1113 			/* Matching key disappeared (user removed the key?)
1114 			 * let the handshake timeout.
1115 			 */
1116 			if (!key.ao_key) {
1117 				net_info_ratelimited("TCP-AO key for (%pI4, %d)->(%pI4, %d) suddenly disappeared, won't ACK new connection\n",
1118 						     addr,
1119 						     ntohs(tcp_hdr(skb)->source),
1120 						     &ip_hdr(skb)->daddr,
1121 						     ntohs(tcp_hdr(skb)->dest));
1122 				return;
1123 			}
1124 		}
1125 		key.traffic_key = kmalloc(tcp_ao_digest_size(key.ao_key), GFP_ATOMIC);
1126 		if (!key.traffic_key)
1127 			return;
1128 
1129 		key.type = TCP_KEY_AO;
1130 		key.rcv_next = aoh->keyid;
1131 		tcp_v4_ao_calc_key_rsk(key.ao_key, key.traffic_key, req);
1132 #else
1133 	if (0) {
1134 #endif
1135 	} else if (static_branch_tcp_md5()) {
1136 		const union tcp_md5_addr *addr;
1137 		int l3index;
1138 
1139 		addr = (union tcp_md5_addr *)&ip_hdr(skb)->saddr;
1140 		l3index = tcp_v4_sdif(skb) ? inet_iif(skb) : 0;
1141 		key.md5_key = tcp_md5_do_lookup(sk, l3index, addr, AF_INET);
1142 		if (key.md5_key)
1143 			key.type = TCP_KEY_MD5;
1144 	}
1145 
1146 	/* Cleaning ECN bits of TW ACKs of oow data or is paws_reject */
1147 	tcp_v4_send_ack(sk, skb, seq,
1148 			tcp_rsk(req)->rcv_nxt,
1149 			tcp_synack_window(req) >> inet_rsk(req)->rcv_wscale,
1150 			tcp_rsk_tsval(tcp_rsk(req)),
1151 			req->ts_recent,
1152 			0, &key,
1153 			inet_rsk(req)->no_srccheck ? IP_REPLY_ARG_NOSRCCHECK : 0,
1154 			ip_hdr(skb)->tos & ~INET_ECN_MASK,
1155 			READ_ONCE(tcp_rsk(req)->txhash));
1156 	if (tcp_key_is_ao(&key))
1157 		kfree(key.traffic_key);
1158 }
1159 
1160 /*
1161  *	Send a SYN-ACK after having received a SYN.
1162  *	This still operates on a request_sock only, not on a big
1163  *	socket.
1164  */
1165 static int tcp_v4_send_synack(const struct sock *sk, struct dst_entry *dst,
1166 			      struct flowi *fl,
1167 			      struct request_sock *req,
1168 			      struct tcp_fastopen_cookie *foc,
1169 			      enum tcp_synack_type synack_type,
1170 			      struct sk_buff *syn_skb)
1171 {
1172 	struct inet_request_sock *ireq = inet_rsk(req);
1173 	struct flowi4 fl4;
1174 	int err = -1;
1175 	struct sk_buff *skb;
1176 	u8 tos;
1177 
1178 	/* First, grab a route. */
1179 	if (!dst && (dst = inet_csk_route_req(sk, &fl4, req)) == NULL)
1180 		return -1;
1181 
1182 	skb = tcp_make_synack(sk, dst, req, foc, synack_type, syn_skb);
1183 
1184 	if (skb) {
1185 		tcp_rsk(req)->syn_ect_snt = inet_sk(sk)->tos & INET_ECN_MASK;
1186 		__tcp_v4_send_check(skb, ireq->ir_loc_addr, ireq->ir_rmt_addr);
1187 
1188 		tos = READ_ONCE(inet_sk(sk)->tos);
1189 
1190 		if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_reflect_tos))
1191 			tos = (tcp_rsk(req)->syn_tos & ~INET_ECN_MASK) |
1192 			      (tos & INET_ECN_MASK);
1193 
1194 		if (!INET_ECN_is_capable(tos) &&
1195 		    tcp_bpf_ca_needs_ecn((struct sock *)req))
1196 			tos |= INET_ECN_ECT_0;
1197 
1198 		rcu_read_lock();
1199 		err = ip_build_and_send_pkt(skb, sk, ireq->ir_loc_addr,
1200 					    ireq->ir_rmt_addr,
1201 					    rcu_dereference(ireq->ireq_opt),
1202 					    tos);
1203 		rcu_read_unlock();
1204 		err = net_xmit_eval(err);
1205 	}
1206 
1207 	return err;
1208 }
1209 
1210 /*
1211  *	IPv4 request_sock destructor.
1212  */
1213 static void tcp_v4_reqsk_destructor(struct request_sock *req)
1214 {
1215 	kfree_rcu(rcu_dereference_protected(inet_rsk(req)->ireq_opt, 1), rcu);
1216 }
1217 
1218 #ifdef CONFIG_TCP_MD5SIG
1219 /*
1220  * RFC2385 MD5 checksumming requires a mapping of
1221  * IP address->MD5 Key.
1222  * We need to maintain these in the sk structure.
1223  */
1224 
1225 DEFINE_STATIC_KEY_DEFERRED_FALSE(tcp_md5_needed, HZ);
1226 
1227 static bool better_md5_match(struct tcp_md5sig_key *old, struct tcp_md5sig_key *new)
1228 {
1229 	if (!old)
1230 		return true;
1231 
1232 	/* l3index always overrides non-l3index */
1233 	if (old->l3index && new->l3index == 0)
1234 		return false;
1235 	if (old->l3index == 0 && new->l3index)
1236 		return true;
1237 
1238 	return old->prefixlen < new->prefixlen;
1239 }
1240 
1241 /* Find the Key structure for an address.  */
1242 struct tcp_md5sig_key *__tcp_md5_do_lookup(const struct sock *sk, int l3index,
1243 					   const union tcp_md5_addr *addr,
1244 					   int family, bool any_l3index)
1245 {
1246 	const struct tcp_sock *tp = tcp_sk(sk);
1247 	struct tcp_md5sig_key *key;
1248 	const struct tcp_md5sig_info *md5sig;
1249 	__be32 mask;
1250 	struct tcp_md5sig_key *best_match = NULL;
1251 	bool match;
1252 
1253 	/* caller either holds rcu_read_lock() or socket lock */
1254 	md5sig = rcu_dereference_check(tp->md5sig_info,
1255 				       lockdep_sock_is_held(sk));
1256 	if (!md5sig)
1257 		return NULL;
1258 
1259 	hlist_for_each_entry_rcu(key, &md5sig->head, node,
1260 				 lockdep_sock_is_held(sk)) {
1261 		if (key->family != family)
1262 			continue;
1263 		if (!any_l3index && key->flags & TCP_MD5SIG_FLAG_IFINDEX &&
1264 		    key->l3index != l3index)
1265 			continue;
1266 		if (family == AF_INET) {
1267 			mask = inet_make_mask(key->prefixlen);
1268 			match = (key->addr.a4.s_addr & mask) ==
1269 				(addr->a4.s_addr & mask);
1270 #if IS_ENABLED(CONFIG_IPV6)
1271 		} else if (family == AF_INET6) {
1272 			match = ipv6_prefix_equal(&key->addr.a6, &addr->a6,
1273 						  key->prefixlen);
1274 #endif
1275 		} else {
1276 			match = false;
1277 		}
1278 
1279 		if (match && better_md5_match(best_match, key))
1280 			best_match = key;
1281 	}
1282 	return best_match;
1283 }
1284 
1285 static struct tcp_md5sig_key *tcp_md5_do_lookup_exact(const struct sock *sk,
1286 						      const union tcp_md5_addr *addr,
1287 						      int family, u8 prefixlen,
1288 						      int l3index, u8 flags)
1289 {
1290 	const struct tcp_sock *tp = tcp_sk(sk);
1291 	struct tcp_md5sig_key *key;
1292 	unsigned int size = sizeof(struct in_addr);
1293 	const struct tcp_md5sig_info *md5sig;
1294 
1295 	/* caller either holds rcu_read_lock() or socket lock */
1296 	md5sig = rcu_dereference_check(tp->md5sig_info,
1297 				       lockdep_sock_is_held(sk));
1298 	if (!md5sig)
1299 		return NULL;
1300 #if IS_ENABLED(CONFIG_IPV6)
1301 	if (family == AF_INET6)
1302 		size = sizeof(struct in6_addr);
1303 #endif
1304 	hlist_for_each_entry_rcu(key, &md5sig->head, node,
1305 				 lockdep_sock_is_held(sk)) {
1306 		if (key->family != family)
1307 			continue;
1308 		if ((key->flags & TCP_MD5SIG_FLAG_IFINDEX) != (flags & TCP_MD5SIG_FLAG_IFINDEX))
1309 			continue;
1310 		if (key->l3index != l3index)
1311 			continue;
1312 		if (!memcmp(&key->addr, addr, size) &&
1313 		    key->prefixlen == prefixlen)
1314 			return key;
1315 	}
1316 	return NULL;
1317 }
1318 
1319 struct tcp_md5sig_key *tcp_v4_md5_lookup(const struct sock *sk,
1320 					 const struct sock *addr_sk)
1321 {
1322 	const union tcp_md5_addr *addr;
1323 	int l3index;
1324 
1325 	l3index = l3mdev_master_ifindex_by_index(sock_net(sk),
1326 						 addr_sk->sk_bound_dev_if);
1327 	addr = (const union tcp_md5_addr *)&addr_sk->sk_daddr;
1328 	return tcp_md5_do_lookup(sk, l3index, addr, AF_INET);
1329 }
1330 
1331 static int tcp_md5sig_info_add(struct sock *sk, gfp_t gfp)
1332 {
1333 	struct tcp_sock *tp = tcp_sk(sk);
1334 	struct tcp_md5sig_info *md5sig;
1335 
1336 	md5sig = kmalloc_obj(*md5sig, gfp);
1337 	if (!md5sig)
1338 		return -ENOMEM;
1339 
1340 	sk_gso_disable(sk);
1341 	INIT_HLIST_HEAD(&md5sig->head);
1342 	rcu_assign_pointer(tp->md5sig_info, md5sig);
1343 	return 0;
1344 }
1345 
1346 /* This can be called on a newly created socket, from other files */
1347 static int __tcp_md5_do_add(struct sock *sk, const union tcp_md5_addr *addr,
1348 			    int family, u8 prefixlen, int l3index, u8 flags,
1349 			    const u8 *newkey, u8 newkeylen, gfp_t gfp)
1350 {
1351 	/* Add Key to the list */
1352 	struct tcp_md5sig_key *key;
1353 	struct tcp_sock *tp = tcp_sk(sk);
1354 	struct tcp_md5sig_info *md5sig;
1355 
1356 	key = tcp_md5_do_lookup_exact(sk, addr, family, prefixlen, l3index, flags);
1357 	if (key) {
1358 		/* Pre-existing entry - just update that one.
1359 		 * Note that the key might be used concurrently.
1360 		 * data_race() is telling kcsan that we do not care of
1361 		 * key mismatches, since changing MD5 key on live flows
1362 		 * can lead to packet drops.
1363 		 */
1364 		data_race(memcpy(key->key, newkey, newkeylen));
1365 
1366 		/* Pairs with READ_ONCE() in tcp_md5_hash_key().
1367 		 * Also note that a reader could catch new key->keylen value
1368 		 * but old key->key[], this is the reason we use __GFP_ZERO
1369 		 * at sock_kmalloc() time below these lines.
1370 		 */
1371 		WRITE_ONCE(key->keylen, newkeylen);
1372 
1373 		return 0;
1374 	}
1375 
1376 	md5sig = rcu_dereference_protected(tp->md5sig_info,
1377 					   lockdep_sock_is_held(sk));
1378 
1379 	key = sock_kmalloc(sk, sizeof(*key), gfp | __GFP_ZERO);
1380 	if (!key)
1381 		return -ENOMEM;
1382 
1383 	memcpy(key->key, newkey, newkeylen);
1384 	key->keylen = newkeylen;
1385 	key->family = family;
1386 	key->prefixlen = prefixlen;
1387 	key->l3index = l3index;
1388 	key->flags = flags;
1389 	memcpy(&key->addr, addr,
1390 	       (IS_ENABLED(CONFIG_IPV6) && family == AF_INET6) ? sizeof(struct in6_addr) :
1391 								 sizeof(struct in_addr));
1392 	hlist_add_head_rcu(&key->node, &md5sig->head);
1393 	return 0;
1394 }
1395 
1396 int tcp_md5_do_add(struct sock *sk, const union tcp_md5_addr *addr,
1397 		   int family, u8 prefixlen, int l3index, u8 flags,
1398 		   const u8 *newkey, u8 newkeylen)
1399 {
1400 	struct tcp_sock *tp = tcp_sk(sk);
1401 
1402 	if (!rcu_dereference_protected(tp->md5sig_info, lockdep_sock_is_held(sk))) {
1403 		if (fips_enabled) {
1404 			pr_warn_once("TCP-MD5 support is disabled due to FIPS\n");
1405 			return -EOPNOTSUPP;
1406 		}
1407 
1408 		if (tcp_md5sig_info_add(sk, GFP_KERNEL))
1409 			return -ENOMEM;
1410 
1411 		if (!static_branch_inc(&tcp_md5_needed.key)) {
1412 			struct tcp_md5sig_info *md5sig;
1413 
1414 			md5sig = rcu_dereference_protected(tp->md5sig_info, lockdep_sock_is_held(sk));
1415 			rcu_assign_pointer(tp->md5sig_info, NULL);
1416 			kfree_rcu(md5sig, rcu);
1417 			return -EUSERS;
1418 		}
1419 	}
1420 
1421 	return __tcp_md5_do_add(sk, addr, family, prefixlen, l3index, flags,
1422 				newkey, newkeylen, GFP_KERNEL);
1423 }
1424 
1425 int tcp_md5_key_copy(struct sock *sk, const union tcp_md5_addr *addr,
1426 		     int family, u8 prefixlen, int l3index,
1427 		     struct tcp_md5sig_key *key)
1428 {
1429 	struct tcp_sock *tp = tcp_sk(sk);
1430 
1431 	if (!rcu_dereference_protected(tp->md5sig_info, lockdep_sock_is_held(sk))) {
1432 
1433 		if (tcp_md5sig_info_add(sk, sk_gfp_mask(sk, GFP_ATOMIC)))
1434 			return -ENOMEM;
1435 
1436 		if (!static_key_fast_inc_not_disabled(&tcp_md5_needed.key.key)) {
1437 			struct tcp_md5sig_info *md5sig;
1438 
1439 			md5sig = rcu_dereference_protected(tp->md5sig_info, lockdep_sock_is_held(sk));
1440 			net_warn_ratelimited("Too many TCP-MD5 keys in the system\n");
1441 			rcu_assign_pointer(tp->md5sig_info, NULL);
1442 			kfree_rcu(md5sig, rcu);
1443 			return -EUSERS;
1444 		}
1445 	}
1446 
1447 	return __tcp_md5_do_add(sk, addr, family, prefixlen, l3index,
1448 				key->flags, key->key, key->keylen,
1449 				sk_gfp_mask(sk, GFP_ATOMIC));
1450 }
1451 
1452 int tcp_md5_do_del(struct sock *sk, const union tcp_md5_addr *addr, int family,
1453 		   u8 prefixlen, int l3index, u8 flags)
1454 {
1455 	struct tcp_md5sig_key *key;
1456 
1457 	key = tcp_md5_do_lookup_exact(sk, addr, family, prefixlen, l3index, flags);
1458 	if (!key)
1459 		return -ENOENT;
1460 	hlist_del_rcu(&key->node);
1461 	atomic_sub(sizeof(*key), &sk->sk_omem_alloc);
1462 	kfree_rcu(key, rcu);
1463 	return 0;
1464 }
1465 
1466 void tcp_clear_md5_list(struct sock *sk)
1467 {
1468 	struct tcp_sock *tp = tcp_sk(sk);
1469 	struct tcp_md5sig_key *key;
1470 	struct hlist_node *n;
1471 	struct tcp_md5sig_info *md5sig;
1472 
1473 	md5sig = rcu_dereference_protected(tp->md5sig_info, 1);
1474 
1475 	hlist_for_each_entry_safe(key, n, &md5sig->head, node) {
1476 		hlist_del_rcu(&key->node);
1477 		atomic_sub(sizeof(*key), &sk->sk_omem_alloc);
1478 		kfree_rcu(key, rcu);
1479 	}
1480 }
1481 
1482 static int tcp_v4_parse_md5_keys(struct sock *sk, int optname,
1483 				 sockptr_t optval, int optlen)
1484 {
1485 	struct tcp_md5sig cmd;
1486 	struct sockaddr_in *sin = (struct sockaddr_in *)&cmd.tcpm_addr;
1487 	const union tcp_md5_addr *addr;
1488 	u8 prefixlen = 32;
1489 	int l3index = 0;
1490 	bool l3flag;
1491 	u8 flags;
1492 
1493 	if (optlen < sizeof(cmd))
1494 		return -EINVAL;
1495 
1496 	if (copy_from_sockptr(&cmd, optval, sizeof(cmd)))
1497 		return -EFAULT;
1498 
1499 	if (sin->sin_family != AF_INET)
1500 		return -EINVAL;
1501 
1502 	flags = cmd.tcpm_flags & TCP_MD5SIG_FLAG_IFINDEX;
1503 	l3flag = cmd.tcpm_flags & TCP_MD5SIG_FLAG_IFINDEX;
1504 
1505 	if (optname == TCP_MD5SIG_EXT &&
1506 	    cmd.tcpm_flags & TCP_MD5SIG_FLAG_PREFIX) {
1507 		prefixlen = cmd.tcpm_prefixlen;
1508 		if (prefixlen > 32)
1509 			return -EINVAL;
1510 	}
1511 
1512 	if (optname == TCP_MD5SIG_EXT && cmd.tcpm_ifindex &&
1513 	    cmd.tcpm_flags & TCP_MD5SIG_FLAG_IFINDEX) {
1514 		struct net_device *dev;
1515 
1516 		rcu_read_lock();
1517 		dev = dev_get_by_index_rcu(sock_net(sk), cmd.tcpm_ifindex);
1518 		if (dev && netif_is_l3_master(dev))
1519 			l3index = dev->ifindex;
1520 
1521 		rcu_read_unlock();
1522 
1523 		/* ok to reference set/not set outside of rcu;
1524 		 * right now device MUST be an L3 master
1525 		 */
1526 		if (!dev || !l3index)
1527 			return -EINVAL;
1528 	}
1529 
1530 	addr = (union tcp_md5_addr *)&sin->sin_addr.s_addr;
1531 
1532 	if (!cmd.tcpm_keylen)
1533 		return tcp_md5_do_del(sk, addr, AF_INET, prefixlen, l3index, flags);
1534 
1535 	if (cmd.tcpm_keylen > TCP_MD5SIG_MAXKEYLEN)
1536 		return -EINVAL;
1537 
1538 	/* Don't allow keys for peers that have a matching TCP-AO key.
1539 	 * See the comment in tcp_ao_add_cmd()
1540 	 */
1541 	if (tcp_ao_required(sk, addr, AF_INET, l3flag ? l3index : -1, false))
1542 		return -EKEYREJECTED;
1543 
1544 	return tcp_md5_do_add(sk, addr, AF_INET, prefixlen, l3index, flags,
1545 			      cmd.tcpm_key, cmd.tcpm_keylen);
1546 }
1547 
1548 static void tcp_v4_md5_hash_headers(struct md5_ctx *ctx,
1549 				    __be32 daddr, __be32 saddr,
1550 				    const struct tcphdr *th, int nbytes)
1551 {
1552 	struct {
1553 		struct tcp4_pseudohdr ip;
1554 		struct tcphdr tcp;
1555 	} h;
1556 
1557 	h.ip.saddr = saddr;
1558 	h.ip.daddr = daddr;
1559 	h.ip.pad = 0;
1560 	h.ip.protocol = IPPROTO_TCP;
1561 	h.ip.len = cpu_to_be16(nbytes);
1562 	h.tcp = *th;
1563 	h.tcp.check = 0;
1564 	md5_update(ctx, (const u8 *)&h, sizeof(h.ip) + sizeof(h.tcp));
1565 }
1566 
1567 static noinline_for_stack void
1568 tcp_v4_md5_hash_hdr(char *md5_hash, const struct tcp_md5sig_key *key,
1569 		    __be32 daddr, __be32 saddr, const struct tcphdr *th)
1570 {
1571 	struct md5_ctx ctx;
1572 
1573 	md5_init(&ctx);
1574 	tcp_v4_md5_hash_headers(&ctx, daddr, saddr, th, th->doff << 2);
1575 	tcp_md5_hash_key(&ctx, key);
1576 	md5_final(&ctx, md5_hash);
1577 }
1578 
1579 noinline_for_stack void
1580 tcp_v4_md5_hash_skb(char *md5_hash, const struct tcp_md5sig_key *key,
1581 		    const struct sock *sk, const struct sk_buff *skb)
1582 {
1583 	const struct tcphdr *th = tcp_hdr(skb);
1584 	__be32 saddr, daddr;
1585 	struct md5_ctx ctx;
1586 
1587 	if (sk) { /* valid for establish/request sockets */
1588 		saddr = sk->sk_rcv_saddr;
1589 		daddr = sk->sk_daddr;
1590 	} else {
1591 		const struct iphdr *iph = ip_hdr(skb);
1592 		saddr = iph->saddr;
1593 		daddr = iph->daddr;
1594 	}
1595 
1596 	md5_init(&ctx);
1597 	tcp_v4_md5_hash_headers(&ctx, daddr, saddr, th, skb->len);
1598 	tcp_md5_hash_skb_data(&ctx, skb, th->doff << 2);
1599 	tcp_md5_hash_key(&ctx, key);
1600 	md5_final(&ctx, md5_hash);
1601 }
1602 
1603 #endif
1604 
1605 static void tcp_v4_init_req(struct request_sock *req,
1606 			    const struct sock *sk_listener,
1607 			    struct sk_buff *skb)
1608 {
1609 	struct inet_request_sock *ireq = inet_rsk(req);
1610 	struct net *net = sock_net(sk_listener);
1611 
1612 	sk_rcv_saddr_set(req_to_sk(req), ip_hdr(skb)->daddr);
1613 	sk_daddr_set(req_to_sk(req), ip_hdr(skb)->saddr);
1614 	RCU_INIT_POINTER(ireq->ireq_opt, tcp_v4_save_options(net, skb));
1615 }
1616 
1617 static struct dst_entry *tcp_v4_route_req(const struct sock *sk,
1618 					  struct sk_buff *skb,
1619 					  struct flowi *fl,
1620 					  struct request_sock *req,
1621 					  u32 tw_isn)
1622 {
1623 	tcp_v4_init_req(req, sk, skb);
1624 
1625 	if (security_inet_conn_request(sk, skb, req))
1626 		return NULL;
1627 
1628 	return inet_csk_route_req(sk, &fl->u.ip4, req);
1629 }
1630 
1631 struct request_sock_ops tcp_request_sock_ops __read_mostly = {
1632 	.family		=	PF_INET,
1633 	.obj_size	=	sizeof(struct tcp_request_sock),
1634 	.send_ack	=	tcp_v4_reqsk_send_ack,
1635 	.destructor	=	tcp_v4_reqsk_destructor,
1636 	.send_reset	=	tcp_v4_send_reset,
1637 };
1638 
1639 const struct tcp_request_sock_ops tcp_request_sock_ipv4_ops = {
1640 	.mss_clamp	=	TCP_MSS_DEFAULT,
1641 #ifdef CONFIG_TCP_MD5SIG
1642 	.req_md5_lookup	=	tcp_v4_md5_lookup,
1643 	.calc_md5_hash	=	tcp_v4_md5_hash_skb,
1644 #endif
1645 #ifdef CONFIG_TCP_AO
1646 	.ao_lookup	=	tcp_v4_ao_lookup_rsk,
1647 	.ao_calc_key	=	tcp_v4_ao_calc_key_rsk,
1648 	.ao_synack_hash	=	tcp_v4_ao_synack_hash,
1649 #endif
1650 #ifdef CONFIG_SYN_COOKIES
1651 	.cookie_init_seq =	cookie_v4_init_sequence,
1652 #endif
1653 	.route_req	=	tcp_v4_route_req,
1654 	.init_seq_and_ts_off	=	tcp_v4_init_seq_and_ts_off,
1655 	.send_synack	=	tcp_v4_send_synack,
1656 };
1657 
1658 int tcp_v4_conn_request(struct sock *sk, struct sk_buff *skb)
1659 {
1660 	/* Never answer to SYNs send to broadcast or multicast */
1661 	if (skb_rtable(skb)->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST))
1662 		goto drop;
1663 
1664 	return tcp_conn_request(&tcp_request_sock_ops,
1665 				&tcp_request_sock_ipv4_ops, sk, skb);
1666 
1667 drop:
1668 	tcp_listendrop(sk);
1669 	return 0;
1670 }
1671 
1672 
1673 /*
1674  * The three way handshake has completed - we got a valid synack -
1675  * now create the new socket.
1676  */
1677 struct sock *tcp_v4_syn_recv_sock(const struct sock *sk, struct sk_buff *skb,
1678 				  struct request_sock *req,
1679 				  struct dst_entry *dst,
1680 				  struct request_sock *req_unhash,
1681 				  bool *own_req,
1682 				  void (*opt_child_init)(struct sock *newsk,
1683 							 const struct sock *sk))
1684 {
1685 	struct inet_request_sock *ireq;
1686 	bool found_dup_sk = false;
1687 	struct inet_sock *newinet;
1688 	struct tcp_sock *newtp;
1689 	struct sock *newsk;
1690 #ifdef CONFIG_TCP_MD5SIG
1691 	const union tcp_md5_addr *addr;
1692 	struct tcp_md5sig_key *key;
1693 	int l3index;
1694 #endif
1695 	struct ip_options_rcu *inet_opt;
1696 
1697 	if (sk_acceptq_is_full(sk))
1698 		goto exit_overflow;
1699 
1700 	newsk = tcp_create_openreq_child(sk, req, skb);
1701 	if (!newsk)
1702 		goto exit_nonewsk;
1703 
1704 	newsk->sk_gso_type = SKB_GSO_TCPV4;
1705 	inet_sk_rx_dst_set(newsk, skb);
1706 
1707 	newtp		      = tcp_sk(newsk);
1708 	newinet		      = inet_sk(newsk);
1709 	ireq		      = inet_rsk(req);
1710 	inet_opt	      = rcu_dereference(ireq->ireq_opt);
1711 	RCU_INIT_POINTER(newinet->inet_opt, inet_opt);
1712 	newinet->mc_index     = inet_iif(skb);
1713 	newinet->mc_ttl	      = ip_hdr(skb)->ttl;
1714 	newinet->rcv_tos      = ip_hdr(skb)->tos;
1715 	inet_csk(newsk)->icsk_ext_hdr_len = 0;
1716 	if (inet_opt)
1717 		inet_csk(newsk)->icsk_ext_hdr_len = inet_opt->opt.optlen;
1718 	atomic_set(&newinet->inet_id, get_random_u16());
1719 
1720 	/* Set ToS of the new socket based upon the value of incoming SYN.
1721 	 * ECT bits are set later in tcp_init_transfer().
1722 	 */
1723 	if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_reflect_tos))
1724 		newinet->tos = tcp_rsk(req)->syn_tos & ~INET_ECN_MASK;
1725 
1726 	if (!dst) {
1727 		dst = inet_csk_route_child_sock(sk, newsk, req);
1728 		if (!dst)
1729 			goto put_and_exit;
1730 	} else {
1731 		/* syncookie case : see end of cookie_v4_check() */
1732 	}
1733 	sk_setup_caps(newsk, dst);
1734 
1735 #if IS_ENABLED(CONFIG_IPV6)
1736 	if (opt_child_init)
1737 		opt_child_init(newsk, sk);
1738 #endif
1739 	tcp_ca_openreq_child(newsk, dst);
1740 
1741 	tcp_sync_mss(newsk, dst4_mtu(dst));
1742 	newtp->advmss = tcp_mss_clamp(tcp_sk(sk), tcp_dst_advmss(dst));
1743 
1744 	tcp_initialize_rcv_mss(newsk);
1745 
1746 #ifdef CONFIG_TCP_MD5SIG
1747 	l3index = l3mdev_master_ifindex_by_index(sock_net(sk), ireq->ir_iif);
1748 	/* Copy over the MD5 key from the original socket */
1749 	addr = (union tcp_md5_addr *)&newinet->inet_daddr;
1750 	key = tcp_md5_do_lookup(sk, l3index, addr, AF_INET);
1751 	if (key && !tcp_rsk_used_ao(req)) {
1752 		if (tcp_md5_key_copy(newsk, addr, AF_INET, 32, l3index, key))
1753 			goto put_and_exit;
1754 		sk_gso_disable(newsk);
1755 	}
1756 #endif
1757 #ifdef CONFIG_TCP_AO
1758 	if (tcp_ao_copy_all_matching(sk, newsk, req, skb, AF_INET))
1759 		goto put_and_exit; /* OOM, release back memory */
1760 #endif
1761 
1762 	if (__inet_inherit_port(sk, newsk) < 0)
1763 		goto put_and_exit;
1764 	*own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash),
1765 				       &found_dup_sk);
1766 	if (likely(*own_req)) {
1767 		tcp_move_syn(newtp, req);
1768 		ireq->ireq_opt = NULL;
1769 	} else {
1770 		newinet->inet_opt = NULL;
1771 
1772 		if (!req_unhash && found_dup_sk) {
1773 			/* This code path should only be executed in the
1774 			 * syncookie case only
1775 			 */
1776 			bh_unlock_sock(newsk);
1777 			sock_put(newsk);
1778 			newsk = NULL;
1779 		}
1780 	}
1781 	return newsk;
1782 
1783 exit_overflow:
1784 	NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
1785 exit_nonewsk:
1786 	dst_release(dst);
1787 exit:
1788 	tcp_listendrop(sk);
1789 	return NULL;
1790 put_and_exit:
1791 	newinet->inet_opt = NULL;
1792 	inet_csk_prepare_forced_close(newsk);
1793 	tcp_done(newsk);
1794 	goto exit;
1795 }
1796 
1797 static struct sock *tcp_v4_cookie_check(struct sock *sk, struct sk_buff *skb)
1798 {
1799 #ifdef CONFIG_SYN_COOKIES
1800 	const struct tcphdr *th = tcp_hdr(skb);
1801 
1802 	if (!th->syn)
1803 		sk = cookie_v4_check(sk, skb);
1804 #endif
1805 	return sk;
1806 }
1807 
1808 u16 tcp_v4_get_syncookie(struct sock *sk, struct iphdr *iph,
1809 			 struct tcphdr *th, u32 *cookie)
1810 {
1811 	u16 mss = 0;
1812 #ifdef CONFIG_SYN_COOKIES
1813 	mss = tcp_get_syncookie_mss(&tcp_request_sock_ops,
1814 				    &tcp_request_sock_ipv4_ops, sk, th);
1815 	if (mss) {
1816 		*cookie = __cookie_v4_init_sequence(iph, th, &mss);
1817 		tcp_synq_overflow(sk);
1818 	}
1819 #endif
1820 	return mss;
1821 }
1822 
1823 INDIRECT_CALLABLE_DECLARE(struct dst_entry *ipv4_dst_check(struct dst_entry *,
1824 							   u32));
1825 /* The socket must have it's spinlock held when we get
1826  * here, unless it is a TCP_LISTEN socket.
1827  *
1828  * We have a potential double-lock case here, so even when
1829  * doing backlog processing we use the BH locking scheme.
1830  * This is because we cannot sleep with the original spinlock
1831  * held.
1832  */
1833 int tcp_v4_do_rcv(struct sock *sk, struct sk_buff *skb)
1834 {
1835 	enum skb_drop_reason reason;
1836 
1837 	reason = psp_sk_rx_policy_check(sk, skb);
1838 	if (reason)
1839 		goto err_discard;
1840 
1841 	if (sk->sk_state == TCP_ESTABLISHED) { /* Fast path */
1842 		struct dst_entry *dst;
1843 
1844 		dst = rcu_dereference_protected(sk->sk_rx_dst,
1845 						lockdep_sock_is_held(sk));
1846 
1847 		sock_rps_save_rxhash(sk, skb);
1848 		sk_mark_napi_id(sk, skb);
1849 		if (dst && unlikely(dst != skb_dst(skb))) {
1850 			if (sk->sk_rx_dst_ifindex != skb->skb_iif ||
1851 			    !INDIRECT_CALL_1(dst->ops->check, ipv4_dst_check,
1852 					     dst, 0)) {
1853 				RCU_INIT_POINTER(sk->sk_rx_dst, NULL);
1854 				dst_release(dst);
1855 			}
1856 		}
1857 		tcp_rcv_established(sk, skb);
1858 		return 0;
1859 	}
1860 
1861 	if (tcp_checksum_complete(skb))
1862 		goto csum_err;
1863 
1864 	if (sk->sk_state == TCP_LISTEN) {
1865 		struct sock *nsk = tcp_v4_cookie_check(sk, skb);
1866 
1867 		if (!nsk)
1868 			return 0;
1869 		if (nsk != sk) {
1870 			reason = tcp_child_process(sk, nsk, skb);
1871 			sock_put(nsk);
1872 			if (reason)
1873 				goto reset;
1874 			return 0;
1875 		}
1876 	} else
1877 		sock_rps_save_rxhash(sk, skb);
1878 
1879 	reason = tcp_rcv_state_process(sk, skb);
1880 	if (reason)
1881 		goto reset;
1882 	return 0;
1883 
1884 reset:
1885 	tcp_v4_send_reset(sk, skb, sk_rst_convert_drop_reason(reason));
1886 discard:
1887 	sk_skb_reason_drop(sk, skb, reason);
1888 	/* Be careful here. If this function gets more complicated and
1889 	 * gcc suffers from register pressure on the x86, sk (in %ebx)
1890 	 * might be destroyed here. This current version compiles correctly,
1891 	 * but you have been warned.
1892 	 */
1893 	return 0;
1894 
1895 csum_err:
1896 	reason = SKB_DROP_REASON_TCP_CSUM;
1897 	trace_tcp_bad_csum(skb);
1898 	TCP_INC_STATS(sock_net(sk), TCP_MIB_CSUMERRORS);
1899 err_discard:
1900 	TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS);
1901 	goto discard;
1902 }
1903 
1904 enum skb_drop_reason tcp_add_backlog(struct sock *sk, struct sk_buff *skb)
1905 {
1906 	u32 tail_gso_size, tail_gso_segs;
1907 	struct skb_shared_info *shinfo;
1908 	const struct tcphdr *th;
1909 	struct tcphdr *thtail;
1910 	struct sk_buff *tail;
1911 	unsigned int hdrlen;
1912 	bool fragstolen;
1913 	u32 gso_segs;
1914 	u32 gso_size;
1915 	u64 limit;
1916 	int delta;
1917 	int err;
1918 
1919 	/* In case all data was pulled from skb frags (in __pskb_pull_tail()),
1920 	 * we can fix skb->truesize to its real value to avoid future drops.
1921 	 * This is valid because skb is not yet charged to the socket.
1922 	 * It has been noticed pure SACK packets were sometimes dropped
1923 	 * (if cooked by drivers without copybreak feature).
1924 	 */
1925 	skb_condense(skb);
1926 
1927 	tcp_cleanup_skb(skb);
1928 
1929 	if (unlikely(tcp_checksum_complete(skb))) {
1930 		bh_unlock_sock(sk);
1931 		trace_tcp_bad_csum(skb);
1932 		__TCP_INC_STATS(sock_net(sk), TCP_MIB_CSUMERRORS);
1933 		__TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS);
1934 		return SKB_DROP_REASON_TCP_CSUM;
1935 	}
1936 
1937 	/* Attempt coalescing to last skb in backlog, even if we are
1938 	 * above the limits.
1939 	 * This is okay because skb capacity is limited to MAX_SKB_FRAGS.
1940 	 */
1941 	th = (const struct tcphdr *)skb->data;
1942 	hdrlen = th->doff * 4;
1943 
1944 	tail = sk->sk_backlog.tail;
1945 	if (!tail)
1946 		goto no_coalesce;
1947 	thtail = (struct tcphdr *)tail->data;
1948 
1949 	if (TCP_SKB_CB(tail)->end_seq != TCP_SKB_CB(skb)->seq ||
1950 	    TCP_SKB_CB(tail)->ip_dsfield != TCP_SKB_CB(skb)->ip_dsfield ||
1951 	    ((TCP_SKB_CB(tail)->tcp_flags |
1952 	      TCP_SKB_CB(skb)->tcp_flags) & (TCPHDR_SYN | TCPHDR_RST | TCPHDR_URG)) ||
1953 	    !((TCP_SKB_CB(tail)->tcp_flags &
1954 	      TCP_SKB_CB(skb)->tcp_flags) & TCPHDR_ACK) ||
1955 	    ((TCP_SKB_CB(tail)->tcp_flags ^
1956 	      TCP_SKB_CB(skb)->tcp_flags) &
1957 	     (TCPHDR_ECE | TCPHDR_CWR | TCPHDR_AE)) ||
1958 	    !tcp_skb_can_collapse_rx(tail, skb) ||
1959 	    thtail->doff != th->doff ||
1960 	    memcmp(thtail + 1, th + 1, hdrlen - sizeof(*th)) ||
1961 	    /* prior to PSP Rx policy check, retain exact PSP metadata */
1962 	    psp_skb_coalesce_diff(tail, skb))
1963 		goto no_coalesce;
1964 
1965 	__skb_pull(skb, hdrlen);
1966 
1967 	shinfo = skb_shinfo(skb);
1968 	gso_size = shinfo->gso_size ?: skb->len;
1969 	gso_segs = shinfo->gso_segs ?: 1;
1970 
1971 	shinfo = skb_shinfo(tail);
1972 	tail_gso_size = shinfo->gso_size ?: (tail->len - hdrlen);
1973 	tail_gso_segs = shinfo->gso_segs ?: 1;
1974 
1975 	if (skb_try_coalesce(tail, skb, &fragstolen, &delta)) {
1976 		TCP_SKB_CB(tail)->end_seq = TCP_SKB_CB(skb)->end_seq;
1977 
1978 		if (likely(!before(TCP_SKB_CB(skb)->ack_seq, TCP_SKB_CB(tail)->ack_seq))) {
1979 			TCP_SKB_CB(tail)->ack_seq = TCP_SKB_CB(skb)->ack_seq;
1980 			thtail->window = th->window;
1981 		}
1982 
1983 		/* We have to update both TCP_SKB_CB(tail)->tcp_flags and
1984 		 * thtail->fin, so that the fast path in tcp_rcv_established()
1985 		 * is not entered if we append a packet with a FIN.
1986 		 * SYN, RST, URG are not present.
1987 		 * ACK is set on both packets.
1988 		 * PSH : we do not really care in TCP stack,
1989 		 *       at least for 'GRO' packets.
1990 		 */
1991 		thtail->fin |= th->fin;
1992 		TCP_SKB_CB(tail)->tcp_flags |= TCP_SKB_CB(skb)->tcp_flags;
1993 
1994 		if (TCP_SKB_CB(skb)->has_rxtstamp) {
1995 			TCP_SKB_CB(tail)->has_rxtstamp = true;
1996 			tail->tstamp = skb->tstamp;
1997 			skb_hwtstamps(tail)->hwtstamp = skb_hwtstamps(skb)->hwtstamp;
1998 		}
1999 
2000 		/* Not as strict as GRO. We only need to carry mss max value */
2001 		shinfo->gso_size = max(gso_size, tail_gso_size);
2002 		shinfo->gso_segs = min_t(u32, gso_segs + tail_gso_segs, 0xFFFF);
2003 
2004 		sk->sk_backlog.len += delta;
2005 		__NET_INC_STATS(sock_net(sk),
2006 				LINUX_MIB_TCPBACKLOGCOALESCE);
2007 		kfree_skb_partial(skb, fragstolen);
2008 		return SKB_NOT_DROPPED_YET;
2009 	}
2010 	__skb_push(skb, hdrlen);
2011 
2012 no_coalesce:
2013 	/* sk->sk_backlog.len is reset only at the end of __release_sock().
2014 	 * Both sk->sk_backlog.len and sk->sk_rmem_alloc could reach
2015 	 * sk_rcvbuf in normal conditions.
2016 	 */
2017 	limit = ((u64)READ_ONCE(sk->sk_rcvbuf)) << 1;
2018 
2019 	limit += ((u32)READ_ONCE(sk->sk_sndbuf)) >> 1;
2020 
2021 	/* Only socket owner can try to collapse/prune rx queues
2022 	 * to reduce memory overhead, so add a little headroom here.
2023 	 * Few sockets backlog are possibly concurrently non empty.
2024 	 */
2025 	limit += 64 * 1024;
2026 
2027 	limit = min_t(u64, limit, UINT_MAX);
2028 
2029 	err = sk_add_backlog(sk, skb, limit);
2030 	if (unlikely(err)) {
2031 		bh_unlock_sock(sk);
2032 		if (err == -ENOMEM) {
2033 			__NET_INC_STATS(sock_net(sk), LINUX_MIB_PFMEMALLOCDROP);
2034 			return SKB_DROP_REASON_PFMEMALLOC;
2035 		}
2036 		__NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPBACKLOGDROP);
2037 		return SKB_DROP_REASON_SOCKET_BACKLOG;
2038 	}
2039 	return SKB_NOT_DROPPED_YET;
2040 }
2041 
2042 static void tcp_v4_restore_cb(struct sk_buff *skb)
2043 {
2044 	memmove(IPCB(skb), &TCP_SKB_CB(skb)->header.h4,
2045 		sizeof(struct inet_skb_parm));
2046 }
2047 
2048 static void tcp_v4_fill_cb(struct sk_buff *skb, const struct iphdr *iph,
2049 			   const struct tcphdr *th)
2050 {
2051 	/* This is tricky : We move IPCB at its correct location into TCP_SKB_CB()
2052 	 * barrier() makes sure compiler wont play fool^Waliasing games.
2053 	 */
2054 	memmove(&TCP_SKB_CB(skb)->header.h4, IPCB(skb),
2055 		sizeof(struct inet_skb_parm));
2056 	barrier();
2057 
2058 	TCP_SKB_CB(skb)->seq = ntohl(th->seq);
2059 	TCP_SKB_CB(skb)->end_seq = (TCP_SKB_CB(skb)->seq + th->syn + th->fin +
2060 				    skb->len - th->doff * 4);
2061 	TCP_SKB_CB(skb)->ack_seq = ntohl(th->ack_seq);
2062 	TCP_SKB_CB(skb)->tcp_flags = tcp_flags_ntohs(th);
2063 	TCP_SKB_CB(skb)->ip_dsfield = ipv4_get_dsfield(iph);
2064 	TCP_SKB_CB(skb)->sacked	 = 0;
2065 	TCP_SKB_CB(skb)->has_rxtstamp =
2066 			skb->tstamp || skb_hwtstamps(skb)->hwtstamp;
2067 }
2068 
2069 /*
2070  *	From tcp_input.c
2071  */
2072 
2073 int tcp_v4_rcv(struct sk_buff *skb)
2074 {
2075 	struct net *net = dev_net_rcu(skb->dev);
2076 	enum skb_drop_reason drop_reason;
2077 	enum tcp_tw_status tw_status;
2078 	int sdif = inet_sdif(skb);
2079 	int dif = inet_iif(skb);
2080 	const struct iphdr *iph;
2081 	const struct tcphdr *th;
2082 	struct sock *sk = NULL;
2083 	bool refcounted;
2084 	int ret;
2085 	u32 isn;
2086 
2087 	drop_reason = SKB_DROP_REASON_NOT_SPECIFIED;
2088 	if (skb->pkt_type != PACKET_HOST)
2089 		goto discard_it;
2090 
2091 	/* Count it even if it's bad */
2092 	__TCP_INC_STATS(net, TCP_MIB_INSEGS);
2093 
2094 	if (!pskb_may_pull(skb, sizeof(struct tcphdr)))
2095 		goto discard_it;
2096 
2097 	th = (const struct tcphdr *)skb->data;
2098 
2099 	if (unlikely(th->doff < sizeof(struct tcphdr) / 4)) {
2100 		drop_reason = SKB_DROP_REASON_PKT_TOO_SMALL;
2101 		goto bad_packet;
2102 	}
2103 	if (!pskb_may_pull(skb, th->doff * 4))
2104 		goto discard_it;
2105 
2106 	/* An explanation is required here, I think.
2107 	 * Packet length and doff are validated by header prediction,
2108 	 * provided case of th->doff==0 is eliminated.
2109 	 * So, we defer the checks. */
2110 
2111 	if (skb_checksum_init(skb, IPPROTO_TCP, inet_compute_pseudo))
2112 		goto csum_error;
2113 
2114 	th = (const struct tcphdr *)skb->data;
2115 	iph = ip_hdr(skb);
2116 lookup:
2117 	sk = __inet_lookup_skb(skb, __tcp_hdrlen(th), th->source,
2118 			       th->dest, sdif, &refcounted);
2119 	if (!sk)
2120 		goto no_tcp_socket;
2121 
2122 	if (sk->sk_state == TCP_TIME_WAIT)
2123 		goto do_time_wait;
2124 
2125 	if (sk->sk_state == TCP_NEW_SYN_RECV) {
2126 		struct request_sock *req = inet_reqsk(sk);
2127 		bool req_stolen = false;
2128 		struct sock *nsk;
2129 
2130 		sk = req->rsk_listener;
2131 		if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb))
2132 			drop_reason = SKB_DROP_REASON_XFRM_POLICY;
2133 		else
2134 			drop_reason = tcp_inbound_hash(sk, req, skb,
2135 						       &iph->saddr, &iph->daddr,
2136 						       AF_INET, dif, sdif);
2137 		if (unlikely(drop_reason)) {
2138 			sk_drops_skbadd(sk, skb);
2139 			reqsk_put(req);
2140 			goto discard_it;
2141 		}
2142 		if (tcp_checksum_complete(skb)) {
2143 			reqsk_put(req);
2144 			goto csum_error;
2145 		}
2146 		if (unlikely(sk->sk_state != TCP_LISTEN)) {
2147 			nsk = reuseport_migrate_sock(sk, req_to_sk(req), skb);
2148 			if (!nsk) {
2149 				inet_csk_reqsk_queue_drop_and_put(sk, req);
2150 				goto lookup;
2151 			}
2152 			sk = nsk;
2153 			/* reuseport_migrate_sock() has already held one sk_refcnt
2154 			 * before returning.
2155 			 */
2156 		} else {
2157 			/* We own a reference on the listener, increase it again
2158 			 * as we might lose it too soon.
2159 			 */
2160 			sock_hold(sk);
2161 		}
2162 		refcounted = true;
2163 		nsk = NULL;
2164 		drop_reason = tcp_filter(sk, skb);
2165 		if (!drop_reason) {
2166 			th = (const struct tcphdr *)skb->data;
2167 			iph = ip_hdr(skb);
2168 			tcp_v4_fill_cb(skb, iph, th);
2169 			nsk = tcp_check_req(sk, skb, req, false, &req_stolen,
2170 					    &drop_reason);
2171 		}
2172 		if (!nsk) {
2173 			reqsk_put(req);
2174 			if (req_stolen) {
2175 				/* Another cpu got exclusive access to req
2176 				 * and created a full blown socket.
2177 				 * Try to feed this packet to this socket
2178 				 * instead of discarding it.
2179 				 */
2180 				tcp_v4_restore_cb(skb);
2181 				sock_put(sk);
2182 				goto lookup;
2183 			}
2184 			goto discard_and_relse;
2185 		}
2186 		nf_reset_ct(skb);
2187 		if (nsk == sk) {
2188 			reqsk_put(req);
2189 			tcp_v4_restore_cb(skb);
2190 		} else {
2191 			drop_reason = tcp_child_process(sk, nsk, skb);
2192 			if (drop_reason) {
2193 				enum sk_rst_reason rst_reason;
2194 
2195 				rst_reason = sk_rst_convert_drop_reason(drop_reason);
2196 				tcp_v4_send_reset(nsk, skb, rst_reason);
2197 				sock_put(nsk);
2198 				goto discard_and_relse;
2199 			}
2200 			sock_put(nsk);
2201 			sock_put(sk);
2202 			return 0;
2203 		}
2204 	}
2205 
2206 	isn = 0;
2207 process:
2208 	if (static_branch_unlikely(&ip4_min_ttl)) {
2209 		/* min_ttl can be changed concurrently from do_ip_setsockopt() */
2210 		if (unlikely(iph->ttl < READ_ONCE(inet_sk(sk)->min_ttl))) {
2211 			__NET_INC_STATS(net, LINUX_MIB_TCPMINTTLDROP);
2212 			drop_reason = SKB_DROP_REASON_TCP_MINTTL;
2213 			goto discard_and_relse;
2214 		}
2215 	}
2216 
2217 	if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) {
2218 		drop_reason = SKB_DROP_REASON_XFRM_POLICY;
2219 		goto discard_and_relse;
2220 	}
2221 
2222 	drop_reason = tcp_inbound_hash(sk, NULL, skb, &iph->saddr, &iph->daddr,
2223 				       AF_INET, dif, sdif);
2224 	if (drop_reason)
2225 		goto discard_and_relse;
2226 
2227 	nf_reset_ct(skb);
2228 
2229 	drop_reason = tcp_filter(sk, skb);
2230 	if (drop_reason)
2231 		goto discard_and_relse;
2232 
2233 	th = (const struct tcphdr *)skb->data;
2234 	iph = ip_hdr(skb);
2235 	tcp_v4_fill_cb(skb, iph, th);
2236 	TCP_SKB_CB(skb)->tcp_tw_isn = isn;
2237 
2238 	skb->dev = NULL;
2239 
2240 	if (sk->sk_state == TCP_LISTEN) {
2241 		ret = tcp_v4_do_rcv(sk, skb);
2242 		goto put_and_return;
2243 	}
2244 
2245 	sk_incoming_cpu_update(sk);
2246 
2247 	bh_lock_sock_nested(sk);
2248 	tcp_segs_in(tcp_sk(sk), skb);
2249 	ret = 0;
2250 	if (!sock_owned_by_user(sk)) {
2251 		ret = tcp_v4_do_rcv(sk, skb);
2252 	} else {
2253 		drop_reason = tcp_add_backlog(sk, skb);
2254 		if (drop_reason)
2255 			goto discard_and_relse;
2256 	}
2257 	bh_unlock_sock(sk);
2258 
2259 put_and_return:
2260 	if (refcounted)
2261 		sock_put(sk);
2262 
2263 	return ret;
2264 
2265 no_tcp_socket:
2266 	drop_reason = SKB_DROP_REASON_NO_SOCKET;
2267 	if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
2268 		goto discard_it;
2269 
2270 	tcp_v4_fill_cb(skb, iph, th);
2271 
2272 	if (tcp_checksum_complete(skb)) {
2273 csum_error:
2274 		drop_reason = SKB_DROP_REASON_TCP_CSUM;
2275 		trace_tcp_bad_csum(skb);
2276 		__TCP_INC_STATS(net, TCP_MIB_CSUMERRORS);
2277 bad_packet:
2278 		__TCP_INC_STATS(net, TCP_MIB_INERRS);
2279 	} else {
2280 		tcp_v4_send_reset(NULL, skb, sk_rst_convert_drop_reason(drop_reason));
2281 	}
2282 
2283 discard_it:
2284 	SKB_DR_OR(drop_reason, NOT_SPECIFIED);
2285 	/* Discard frame. */
2286 	sk_skb_reason_drop(sk, skb, drop_reason);
2287 	return 0;
2288 
2289 discard_and_relse:
2290 	sk_drops_skbadd(sk, skb);
2291 	if (refcounted)
2292 		sock_put(sk);
2293 	goto discard_it;
2294 
2295 do_time_wait:
2296 	if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) {
2297 		drop_reason = SKB_DROP_REASON_XFRM_POLICY;
2298 		inet_twsk_put(inet_twsk(sk));
2299 		goto discard_it;
2300 	}
2301 
2302 	tcp_v4_fill_cb(skb, iph, th);
2303 
2304 	if (tcp_checksum_complete(skb)) {
2305 		inet_twsk_put(inet_twsk(sk));
2306 		goto csum_error;
2307 	}
2308 
2309 	tw_status = tcp_timewait_state_process(inet_twsk(sk), skb, th, &isn,
2310 					       &drop_reason);
2311 	switch (tw_status) {
2312 	case TCP_TW_SYN: {
2313 		struct sock *sk2 = inet_lookup_listener(net, skb, __tcp_hdrlen(th),
2314 							iph->saddr, th->source,
2315 							iph->daddr, th->dest,
2316 							inet_iif(skb),
2317 							sdif);
2318 		if (sk2) {
2319 			inet_twsk_deschedule_put(inet_twsk(sk));
2320 			sk = sk2;
2321 			tcp_v4_restore_cb(skb);
2322 			refcounted = false;
2323 			goto process;
2324 		}
2325 
2326 		drop_reason = psp_twsk_rx_policy_check(inet_twsk(sk), skb);
2327 		if (drop_reason) {
2328 			inet_twsk_put(inet_twsk(sk));
2329 			goto discard_it;
2330 		}
2331 	}
2332 		/* to ACK */
2333 		fallthrough;
2334 	case TCP_TW_ACK:
2335 	case TCP_TW_ACK_OOW:
2336 		tcp_v4_timewait_ack(sk, skb, tw_status);
2337 		break;
2338 	case TCP_TW_RST:
2339 		tcp_v4_send_reset(sk, skb, SK_RST_REASON_TCP_TIMEWAIT_SOCKET);
2340 		inet_twsk_deschedule_put(inet_twsk(sk));
2341 		goto discard_it;
2342 	case TCP_TW_SUCCESS:;
2343 	}
2344 	goto discard_it;
2345 }
2346 
2347 static struct timewait_sock_ops tcp_timewait_sock_ops = {
2348 	.twsk_obj_size	= sizeof(struct tcp_timewait_sock),
2349 };
2350 
2351 void inet_sk_rx_dst_set(struct sock *sk, const struct sk_buff *skb)
2352 {
2353 	struct dst_entry *dst = skb_dst(skb);
2354 
2355 	if (dst && dst_hold_safe(dst)) {
2356 		rcu_assign_pointer(sk->sk_rx_dst, dst);
2357 		sk->sk_rx_dst_ifindex = skb->skb_iif;
2358 	}
2359 }
2360 
2361 const struct inet_connection_sock_af_ops ipv4_specific = {
2362 	.queue_xmit	   = ip_queue_xmit,
2363 	.rebuild_header	   = inet_sk_rebuild_header,
2364 	.sk_rx_dst_set	   = inet_sk_rx_dst_set,
2365 	.conn_request	   = tcp_v4_conn_request,
2366 	.syn_recv_sock	   = tcp_v4_syn_recv_sock,
2367 	.net_header_len	   = sizeof(struct iphdr),
2368 	.setsockopt	   = ip_setsockopt,
2369 	.getsockopt	   = ip_getsockopt,
2370 	.mtu_reduced	   = tcp_v4_mtu_reduced,
2371 };
2372 
2373 #if defined(CONFIG_TCP_MD5SIG) || defined(CONFIG_TCP_AO)
2374 static const struct tcp_sock_af_ops tcp_sock_ipv4_specific = {
2375 #ifdef CONFIG_TCP_MD5SIG
2376 	.md5_lookup		= tcp_v4_md5_lookup,
2377 	.calc_md5_hash		= tcp_v4_md5_hash_skb,
2378 	.md5_parse		= tcp_v4_parse_md5_keys,
2379 #endif
2380 #ifdef CONFIG_TCP_AO
2381 	.ao_lookup		= tcp_v4_ao_lookup,
2382 	.calc_ao_hash		= tcp_v4_ao_hash_skb,
2383 	.ao_parse		= tcp_v4_parse_ao,
2384 	.ao_calc_key_sk		= tcp_v4_ao_calc_key_sk,
2385 #endif
2386 };
2387 
2388 static void tcp4_destruct_sock(struct sock *sk)
2389 {
2390 	tcp_md5_destruct_sock(sk);
2391 	tcp_ao_destroy_sock(sk, false);
2392 	inet_sock_destruct(sk);
2393 }
2394 #endif
2395 
2396 /* NOTE: A lot of things set to zero explicitly by call to
2397  *       sk_alloc() so need not be done here.
2398  */
2399 static int tcp_v4_init_sock(struct sock *sk)
2400 {
2401 	struct inet_connection_sock *icsk = inet_csk(sk);
2402 
2403 	tcp_init_sock(sk);
2404 
2405 	icsk->icsk_af_ops = &ipv4_specific;
2406 
2407 #if defined(CONFIG_TCP_MD5SIG) || defined(CONFIG_TCP_AO)
2408 	tcp_sk(sk)->af_specific = &tcp_sock_ipv4_specific;
2409 	sk->sk_destruct = tcp4_destruct_sock;
2410 #endif
2411 
2412 	return 0;
2413 }
2414 
2415 static void tcp_release_user_frags(struct sock *sk)
2416 {
2417 #ifdef CONFIG_PAGE_POOL
2418 	unsigned long index;
2419 	void *netmem;
2420 
2421 	xa_for_each(&sk->sk_user_frags, index, netmem)
2422 		WARN_ON_ONCE(!napi_pp_put_page((__force netmem_ref)netmem));
2423 #endif
2424 }
2425 
2426 void tcp_v4_destroy_sock(struct sock *sk)
2427 {
2428 	struct tcp_sock *tp = tcp_sk(sk);
2429 
2430 	tcp_release_user_frags(sk);
2431 
2432 	xa_destroy(&sk->sk_user_frags);
2433 
2434 	trace_tcp_destroy_sock(sk);
2435 
2436 	tcp_clear_xmit_timers(sk);
2437 
2438 	tcp_cleanup_congestion_control(sk);
2439 
2440 	tcp_cleanup_ulp(sk);
2441 
2442 	/* Cleanup up the write buffer. */
2443 	tcp_write_queue_purge(sk);
2444 
2445 	/* Check if we want to disable active TFO */
2446 	tcp_fastopen_active_disable_ofo_check(sk);
2447 
2448 	/* Cleans up our, hopefully empty, out_of_order_queue. */
2449 	skb_rbtree_purge(&tp->out_of_order_queue);
2450 
2451 	/* Clean up a referenced TCP bind bucket. */
2452 	if (inet_csk(sk)->icsk_bind_hash)
2453 		inet_put_port(sk);
2454 
2455 	BUG_ON(rcu_access_pointer(tp->fastopen_rsk));
2456 
2457 	/* If socket is aborted during connect operation */
2458 	tcp_free_fastopen_req(tp);
2459 	tcp_fastopen_destroy_cipher(sk);
2460 	tcp_saved_syn_free(tp);
2461 
2462 	sk_sockets_allocated_dec(sk);
2463 }
2464 
2465 #ifdef CONFIG_PROC_FS
2466 /* Proc filesystem TCP sock list dumping. */
2467 
2468 static unsigned short seq_file_family(const struct seq_file *seq);
2469 
2470 static bool seq_sk_match(struct seq_file *seq, const struct sock *sk)
2471 {
2472 	unsigned short family = seq_file_family(seq);
2473 
2474 	/* AF_UNSPEC is used as a match all */
2475 	return ((family == AF_UNSPEC || family == sk->sk_family) &&
2476 		net_eq(sock_net(sk), seq_file_net(seq)));
2477 }
2478 
2479 /* Find a non empty bucket (starting from st->bucket)
2480  * and return the first sk from it.
2481  */
2482 static void *listening_get_first(struct seq_file *seq)
2483 {
2484 	struct inet_hashinfo *hinfo = seq_file_net(seq)->ipv4.tcp_death_row.hashinfo;
2485 	struct tcp_iter_state *st = seq->private;
2486 
2487 	st->offset = 0;
2488 	for (; st->bucket <= hinfo->lhash2_mask; st->bucket++) {
2489 		struct inet_listen_hashbucket *ilb2;
2490 		struct hlist_nulls_node *node;
2491 		struct sock *sk;
2492 
2493 		ilb2 = &hinfo->lhash2[st->bucket];
2494 		if (hlist_nulls_empty(&ilb2->nulls_head))
2495 			continue;
2496 
2497 		spin_lock(&ilb2->lock);
2498 		sk_nulls_for_each(sk, node, &ilb2->nulls_head) {
2499 			if (seq_sk_match(seq, sk))
2500 				return sk;
2501 		}
2502 		spin_unlock(&ilb2->lock);
2503 	}
2504 
2505 	return NULL;
2506 }
2507 
2508 /* Find the next sk of "cur" within the same bucket (i.e. st->bucket).
2509  * If "cur" is the last one in the st->bucket,
2510  * call listening_get_first() to return the first sk of the next
2511  * non empty bucket.
2512  */
2513 static void *listening_get_next(struct seq_file *seq, void *cur)
2514 {
2515 	struct tcp_iter_state *st = seq->private;
2516 	struct inet_listen_hashbucket *ilb2;
2517 	struct hlist_nulls_node *node;
2518 	struct inet_hashinfo *hinfo;
2519 	struct sock *sk = cur;
2520 
2521 	++st->num;
2522 	++st->offset;
2523 
2524 	sk = sk_nulls_next(sk);
2525 	sk_nulls_for_each_from(sk, node) {
2526 		if (seq_sk_match(seq, sk))
2527 			return sk;
2528 	}
2529 
2530 	hinfo = seq_file_net(seq)->ipv4.tcp_death_row.hashinfo;
2531 	ilb2 = &hinfo->lhash2[st->bucket];
2532 	spin_unlock(&ilb2->lock);
2533 	++st->bucket;
2534 	return listening_get_first(seq);
2535 }
2536 
2537 static void *listening_get_idx(struct seq_file *seq, loff_t *pos)
2538 {
2539 	struct tcp_iter_state *st = seq->private;
2540 	void *rc;
2541 
2542 	st->bucket = 0;
2543 	st->offset = 0;
2544 	rc = listening_get_first(seq);
2545 
2546 	while (rc && *pos) {
2547 		rc = listening_get_next(seq, rc);
2548 		--*pos;
2549 	}
2550 	return rc;
2551 }
2552 
2553 static inline bool empty_bucket(struct inet_hashinfo *hinfo,
2554 				const struct tcp_iter_state *st)
2555 {
2556 	return hlist_nulls_empty(&hinfo->ehash[st->bucket].chain);
2557 }
2558 
2559 /*
2560  * Get first established socket starting from bucket given in st->bucket.
2561  * If st->bucket is zero, the very first socket in the hash is returned.
2562  */
2563 static void *established_get_first(struct seq_file *seq)
2564 {
2565 	struct inet_hashinfo *hinfo = seq_file_net(seq)->ipv4.tcp_death_row.hashinfo;
2566 	struct tcp_iter_state *st = seq->private;
2567 
2568 	st->offset = 0;
2569 	for (; st->bucket <= hinfo->ehash_mask; ++st->bucket) {
2570 		struct sock *sk;
2571 		struct hlist_nulls_node *node;
2572 		spinlock_t *lock = inet_ehash_lockp(hinfo, st->bucket);
2573 
2574 		cond_resched();
2575 
2576 		/* Lockless fast path for the common case of empty buckets */
2577 		if (empty_bucket(hinfo, st))
2578 			continue;
2579 
2580 		spin_lock_bh(lock);
2581 		sk_nulls_for_each(sk, node, &hinfo->ehash[st->bucket].chain) {
2582 			if (seq_sk_match(seq, sk))
2583 				return sk;
2584 		}
2585 		spin_unlock_bh(lock);
2586 	}
2587 
2588 	return NULL;
2589 }
2590 
2591 static void *established_get_next(struct seq_file *seq, void *cur)
2592 {
2593 	struct inet_hashinfo *hinfo = seq_file_net(seq)->ipv4.tcp_death_row.hashinfo;
2594 	struct tcp_iter_state *st = seq->private;
2595 	struct hlist_nulls_node *node;
2596 	struct sock *sk = cur;
2597 
2598 	++st->num;
2599 	++st->offset;
2600 
2601 	sk = sk_nulls_next(sk);
2602 
2603 	sk_nulls_for_each_from(sk, node) {
2604 		if (seq_sk_match(seq, sk))
2605 			return sk;
2606 	}
2607 
2608 	spin_unlock_bh(inet_ehash_lockp(hinfo, st->bucket));
2609 	++st->bucket;
2610 	return established_get_first(seq);
2611 }
2612 
2613 static void *established_get_idx(struct seq_file *seq, loff_t pos)
2614 {
2615 	struct tcp_iter_state *st = seq->private;
2616 	void *rc;
2617 
2618 	st->bucket = 0;
2619 	rc = established_get_first(seq);
2620 
2621 	while (rc && pos) {
2622 		rc = established_get_next(seq, rc);
2623 		--pos;
2624 	}
2625 	return rc;
2626 }
2627 
2628 static void *tcp_get_idx(struct seq_file *seq, loff_t pos)
2629 {
2630 	void *rc;
2631 	struct tcp_iter_state *st = seq->private;
2632 
2633 	st->state = TCP_SEQ_STATE_LISTENING;
2634 	rc	  = listening_get_idx(seq, &pos);
2635 
2636 	if (!rc) {
2637 		st->state = TCP_SEQ_STATE_ESTABLISHED;
2638 		rc	  = established_get_idx(seq, pos);
2639 	}
2640 
2641 	return rc;
2642 }
2643 
2644 static void *tcp_seek_last_pos(struct seq_file *seq)
2645 {
2646 	struct inet_hashinfo *hinfo = seq_file_net(seq)->ipv4.tcp_death_row.hashinfo;
2647 	struct tcp_iter_state *st = seq->private;
2648 	int bucket = st->bucket;
2649 	int offset = st->offset;
2650 	int orig_num = st->num;
2651 	void *rc = NULL;
2652 
2653 	switch (st->state) {
2654 	case TCP_SEQ_STATE_LISTENING:
2655 		if (st->bucket > hinfo->lhash2_mask)
2656 			break;
2657 		rc = listening_get_first(seq);
2658 		while (offset-- && rc && bucket == st->bucket)
2659 			rc = listening_get_next(seq, rc);
2660 		if (rc)
2661 			break;
2662 		st->bucket = 0;
2663 		st->state = TCP_SEQ_STATE_ESTABLISHED;
2664 		fallthrough;
2665 	case TCP_SEQ_STATE_ESTABLISHED:
2666 		if (st->bucket > hinfo->ehash_mask)
2667 			break;
2668 		rc = established_get_first(seq);
2669 		while (offset-- && rc && bucket == st->bucket)
2670 			rc = established_get_next(seq, rc);
2671 	}
2672 
2673 	st->num = orig_num;
2674 
2675 	return rc;
2676 }
2677 
2678 void *tcp_seq_start(struct seq_file *seq, loff_t *pos)
2679 {
2680 	struct tcp_iter_state *st = seq->private;
2681 	void *rc;
2682 
2683 	if (*pos && *pos == st->last_pos) {
2684 		rc = tcp_seek_last_pos(seq);
2685 		if (rc)
2686 			goto out;
2687 	}
2688 
2689 	st->state = TCP_SEQ_STATE_LISTENING;
2690 	st->num = 0;
2691 	st->bucket = 0;
2692 	st->offset = 0;
2693 	rc = *pos ? tcp_get_idx(seq, *pos - 1) : SEQ_START_TOKEN;
2694 
2695 out:
2696 	st->last_pos = *pos;
2697 	return rc;
2698 }
2699 
2700 void *tcp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2701 {
2702 	struct tcp_iter_state *st = seq->private;
2703 	void *rc = NULL;
2704 
2705 	if (v == SEQ_START_TOKEN) {
2706 		rc = tcp_get_idx(seq, 0);
2707 		goto out;
2708 	}
2709 
2710 	switch (st->state) {
2711 	case TCP_SEQ_STATE_LISTENING:
2712 		rc = listening_get_next(seq, v);
2713 		if (!rc) {
2714 			st->state = TCP_SEQ_STATE_ESTABLISHED;
2715 			st->bucket = 0;
2716 			st->offset = 0;
2717 			rc	  = established_get_first(seq);
2718 		}
2719 		break;
2720 	case TCP_SEQ_STATE_ESTABLISHED:
2721 		rc = established_get_next(seq, v);
2722 		break;
2723 	}
2724 out:
2725 	++*pos;
2726 	st->last_pos = *pos;
2727 	return rc;
2728 }
2729 
2730 void tcp_seq_stop(struct seq_file *seq, void *v)
2731 {
2732 	struct inet_hashinfo *hinfo = seq_file_net(seq)->ipv4.tcp_death_row.hashinfo;
2733 	struct tcp_iter_state *st = seq->private;
2734 
2735 	switch (st->state) {
2736 	case TCP_SEQ_STATE_LISTENING:
2737 		if (v != SEQ_START_TOKEN)
2738 			spin_unlock(&hinfo->lhash2[st->bucket].lock);
2739 		break;
2740 	case TCP_SEQ_STATE_ESTABLISHED:
2741 		if (v)
2742 			spin_unlock_bh(inet_ehash_lockp(hinfo, st->bucket));
2743 		break;
2744 	}
2745 }
2746 
2747 static void get_openreq4(const struct request_sock *req,
2748 			 struct seq_file *f, int i)
2749 {
2750 	const struct inet_request_sock *ireq = inet_rsk(req);
2751 	long delta = req->rsk_timer.expires - jiffies;
2752 
2753 	seq_printf(f, "%4d: %08X:%04X %08X:%04X"
2754 		" %02X %08X:%08X %02X:%08lX %08X %5u %8d %u %d 0",
2755 		i,
2756 		ireq->ir_loc_addr,
2757 		ireq->ir_num,
2758 		ireq->ir_rmt_addr,
2759 		ntohs(ireq->ir_rmt_port),
2760 		TCP_SYN_RECV,
2761 		0, 0, /* could print option size, but that is af dependent. */
2762 		1,    /* timers active (only the expire timer) */
2763 		jiffies_delta_to_clock_t(delta),
2764 		req->num_timeout,
2765 		from_kuid_munged(seq_user_ns(f),
2766 				 sk_uid(req->rsk_listener)),
2767 		0,  /* non standard timer */
2768 		0, /* open_requests have no inode */
2769 		0);
2770 }
2771 
2772 static void get_tcp4_sock(struct sock *sk, struct seq_file *f, int i)
2773 {
2774 	int timer_active;
2775 	unsigned long timer_expires;
2776 	const struct tcp_sock *tp = tcp_sk(sk);
2777 	const struct inet_connection_sock *icsk = inet_csk(sk);
2778 	const struct inet_sock *inet = inet_sk(sk);
2779 	const struct fastopen_queue *fastopenq = &icsk->icsk_accept_queue.fastopenq;
2780 	__be32 dest = inet->inet_daddr;
2781 	__be32 src = inet->inet_rcv_saddr;
2782 	__u16 destp = ntohs(inet->inet_dport);
2783 	__u16 srcp = ntohs(inet->inet_sport);
2784 	u8 icsk_pending;
2785 	int rx_queue;
2786 	int state;
2787 
2788 	icsk_pending = smp_load_acquire(&icsk->icsk_pending);
2789 	if (icsk_pending == ICSK_TIME_RETRANS ||
2790 	    icsk_pending == ICSK_TIME_REO_TIMEOUT ||
2791 	    icsk_pending == ICSK_TIME_LOSS_PROBE) {
2792 		timer_active	= 1;
2793 		timer_expires	= tcp_timeout_expires(sk);
2794 	} else if (icsk_pending == ICSK_TIME_PROBE0) {
2795 		timer_active	= 4;
2796 		timer_expires	= tcp_timeout_expires(sk);
2797 	} else if (timer_pending(&icsk->icsk_keepalive_timer)) {
2798 		timer_active	= 2;
2799 		timer_expires	= icsk->icsk_keepalive_timer.expires;
2800 	} else {
2801 		timer_active	= 0;
2802 		timer_expires = jiffies;
2803 	}
2804 
2805 	state = inet_sk_state_load(sk);
2806 	if (state == TCP_LISTEN)
2807 		rx_queue = READ_ONCE(sk->sk_ack_backlog);
2808 	else
2809 		/* Because we don't lock the socket,
2810 		 * we might find a transient negative value.
2811 		 */
2812 		rx_queue = max_t(int, READ_ONCE(tp->rcv_nxt) -
2813 				      READ_ONCE(tp->copied_seq), 0);
2814 
2815 	seq_printf(f, "%4d: %08X:%04X %08X:%04X %02X %08X:%08X %02X:%08lX "
2816 			"%08X %5u %8d %llu %d 0 %lu %lu %u %u %d",
2817 		i, src, srcp, dest, destp, state,
2818 		READ_ONCE(tp->write_seq) - tp->snd_una,
2819 		rx_queue,
2820 		timer_active,
2821 		jiffies_delta_to_clock_t(timer_expires - jiffies),
2822 		READ_ONCE(icsk->icsk_retransmits),
2823 		from_kuid_munged(seq_user_ns(f), sk_uid(sk)),
2824 		READ_ONCE(icsk->icsk_probes_out),
2825 		sock_i_ino(sk),
2826 		refcount_read(&sk->sk_refcnt),
2827 		jiffies_to_clock_t(icsk->icsk_rto),
2828 		jiffies_to_clock_t(icsk->icsk_ack.ato),
2829 		(icsk->icsk_ack.quick << 1) | inet_csk_in_pingpong_mode(sk),
2830 		tcp_snd_cwnd(tp),
2831 		state == TCP_LISTEN ?
2832 		    fastopenq->max_qlen :
2833 		    (tcp_in_initial_slowstart(tp) ? -1 : tp->snd_ssthresh));
2834 }
2835 
2836 static void get_timewait4_sock(const struct inet_timewait_sock *tw,
2837 			       struct seq_file *f, int i)
2838 {
2839 	long delta = tw->tw_timer.expires - jiffies;
2840 	__be32 dest, src;
2841 	__u16 destp, srcp;
2842 
2843 	dest  = tw->tw_daddr;
2844 	src   = tw->tw_rcv_saddr;
2845 	destp = ntohs(tw->tw_dport);
2846 	srcp  = ntohs(tw->tw_sport);
2847 
2848 	seq_printf(f, "%4d: %08X:%04X %08X:%04X"
2849 		" %02X %08X:%08X %02X:%08lX %08X %5d %8d %d %d 0",
2850 		i, src, srcp, dest, destp, READ_ONCE(tw->tw_substate), 0, 0,
2851 		3, jiffies_delta_to_clock_t(delta), 0, 0, 0, 0,
2852 		refcount_read(&tw->tw_refcnt));
2853 }
2854 
2855 #define TMPSZ 150
2856 
2857 static int tcp4_seq_show(struct seq_file *seq, void *v)
2858 {
2859 	struct tcp_iter_state *st;
2860 	struct sock *sk = v;
2861 
2862 	seq_setwidth(seq, TMPSZ - 1);
2863 	if (v == SEQ_START_TOKEN) {
2864 		seq_puts(seq, "  sl  local_address rem_address   st tx_queue "
2865 			   "rx_queue tr tm->when retrnsmt   uid  timeout "
2866 			   "inode");
2867 		goto out;
2868 	}
2869 	st = seq->private;
2870 
2871 	if (sk->sk_state == TCP_TIME_WAIT)
2872 		get_timewait4_sock(v, seq, st->num);
2873 	else if (sk->sk_state == TCP_NEW_SYN_RECV)
2874 		get_openreq4(v, seq, st->num);
2875 	else
2876 		get_tcp4_sock(v, seq, st->num);
2877 out:
2878 	seq_pad(seq, '\n');
2879 	return 0;
2880 }
2881 
2882 #ifdef CONFIG_BPF_SYSCALL
2883 union bpf_tcp_iter_batch_item {
2884 	struct sock *sk;
2885 	__u64 cookie;
2886 };
2887 
2888 struct bpf_tcp_iter_state {
2889 	struct tcp_iter_state state;
2890 	unsigned int cur_sk;
2891 	unsigned int end_sk;
2892 	unsigned int max_sk;
2893 	union bpf_tcp_iter_batch_item *batch;
2894 };
2895 
2896 struct bpf_iter__tcp {
2897 	__bpf_md_ptr(struct bpf_iter_meta *, meta);
2898 	__bpf_md_ptr(struct sock_common *, sk_common);
2899 	uid_t uid __aligned(8);
2900 };
2901 
2902 static int tcp_prog_seq_show(struct bpf_prog *prog, struct bpf_iter_meta *meta,
2903 			     struct sock_common *sk_common, uid_t uid)
2904 {
2905 	struct bpf_iter__tcp ctx;
2906 
2907 	meta->seq_num--;  /* skip SEQ_START_TOKEN */
2908 	ctx.meta = meta;
2909 	ctx.sk_common = sk_common;
2910 	ctx.uid = uid;
2911 	return bpf_iter_run_prog(prog, &ctx);
2912 }
2913 
2914 static void bpf_iter_tcp_put_batch(struct bpf_tcp_iter_state *iter)
2915 {
2916 	union bpf_tcp_iter_batch_item *item;
2917 	unsigned int cur_sk = iter->cur_sk;
2918 	__u64 cookie;
2919 
2920 	/* Remember the cookies of the sockets we haven't seen yet, so we can
2921 	 * pick up where we left off next time around.
2922 	 */
2923 	while (cur_sk < iter->end_sk) {
2924 		item = &iter->batch[cur_sk++];
2925 		cookie = sock_gen_cookie(item->sk);
2926 		sock_gen_put(item->sk);
2927 		item->cookie = cookie;
2928 	}
2929 }
2930 
2931 static int bpf_iter_tcp_realloc_batch(struct bpf_tcp_iter_state *iter,
2932 				      unsigned int new_batch_sz, gfp_t flags)
2933 {
2934 	union bpf_tcp_iter_batch_item *new_batch;
2935 
2936 	new_batch = kvmalloc_objs(*new_batch, new_batch_sz,
2937 				  flags | __GFP_NOWARN);
2938 	if (!new_batch)
2939 		return -ENOMEM;
2940 
2941 	memcpy(new_batch, iter->batch, sizeof(*iter->batch) * iter->end_sk);
2942 	kvfree(iter->batch);
2943 	iter->batch = new_batch;
2944 	iter->max_sk = new_batch_sz;
2945 
2946 	return 0;
2947 }
2948 
2949 static struct sock *bpf_iter_tcp_resume_bucket(struct sock *first_sk,
2950 					       union bpf_tcp_iter_batch_item *cookies,
2951 					       int n_cookies)
2952 {
2953 	struct hlist_nulls_node *node;
2954 	struct sock *sk;
2955 	int i;
2956 
2957 	for (i = 0; i < n_cookies; i++) {
2958 		sk = first_sk;
2959 		sk_nulls_for_each_from(sk, node)
2960 			if (cookies[i].cookie == atomic64_read(&sk->sk_cookie))
2961 				return sk;
2962 	}
2963 
2964 	return NULL;
2965 }
2966 
2967 static struct sock *bpf_iter_tcp_resume_listening(struct seq_file *seq)
2968 {
2969 	struct inet_hashinfo *hinfo = seq_file_net(seq)->ipv4.tcp_death_row.hashinfo;
2970 	struct bpf_tcp_iter_state *iter = seq->private;
2971 	struct tcp_iter_state *st = &iter->state;
2972 	unsigned int find_cookie = iter->cur_sk;
2973 	unsigned int end_cookie = iter->end_sk;
2974 	int resume_bucket = st->bucket;
2975 	struct sock *sk;
2976 
2977 	if (end_cookie && find_cookie == end_cookie)
2978 		++st->bucket;
2979 
2980 	sk = listening_get_first(seq);
2981 	iter->cur_sk = 0;
2982 	iter->end_sk = 0;
2983 
2984 	if (sk && st->bucket == resume_bucket && end_cookie) {
2985 		sk = bpf_iter_tcp_resume_bucket(sk, &iter->batch[find_cookie],
2986 						end_cookie - find_cookie);
2987 		if (!sk) {
2988 			spin_unlock(&hinfo->lhash2[st->bucket].lock);
2989 			++st->bucket;
2990 			sk = listening_get_first(seq);
2991 		}
2992 	}
2993 
2994 	return sk;
2995 }
2996 
2997 static struct sock *bpf_iter_tcp_resume_established(struct seq_file *seq)
2998 {
2999 	struct inet_hashinfo *hinfo = seq_file_net(seq)->ipv4.tcp_death_row.hashinfo;
3000 	struct bpf_tcp_iter_state *iter = seq->private;
3001 	struct tcp_iter_state *st = &iter->state;
3002 	unsigned int find_cookie = iter->cur_sk;
3003 	unsigned int end_cookie = iter->end_sk;
3004 	int resume_bucket = st->bucket;
3005 	struct sock *sk;
3006 
3007 	if (end_cookie && find_cookie == end_cookie)
3008 		++st->bucket;
3009 
3010 	sk = established_get_first(seq);
3011 	iter->cur_sk = 0;
3012 	iter->end_sk = 0;
3013 
3014 	if (sk && st->bucket == resume_bucket && end_cookie) {
3015 		sk = bpf_iter_tcp_resume_bucket(sk, &iter->batch[find_cookie],
3016 						end_cookie - find_cookie);
3017 		if (!sk) {
3018 			spin_unlock_bh(inet_ehash_lockp(hinfo, st->bucket));
3019 			++st->bucket;
3020 			sk = established_get_first(seq);
3021 		}
3022 	}
3023 
3024 	return sk;
3025 }
3026 
3027 static struct sock *bpf_iter_tcp_resume(struct seq_file *seq)
3028 {
3029 	struct bpf_tcp_iter_state *iter = seq->private;
3030 	struct tcp_iter_state *st = &iter->state;
3031 	struct sock *sk = NULL;
3032 
3033 	switch (st->state) {
3034 	case TCP_SEQ_STATE_LISTENING:
3035 		sk = bpf_iter_tcp_resume_listening(seq);
3036 		if (sk)
3037 			break;
3038 		st->bucket = 0;
3039 		st->state = TCP_SEQ_STATE_ESTABLISHED;
3040 		fallthrough;
3041 	case TCP_SEQ_STATE_ESTABLISHED:
3042 		sk = bpf_iter_tcp_resume_established(seq);
3043 		break;
3044 	}
3045 
3046 	return sk;
3047 }
3048 
3049 static unsigned int bpf_iter_tcp_listening_batch(struct seq_file *seq,
3050 						 struct sock **start_sk)
3051 {
3052 	struct bpf_tcp_iter_state *iter = seq->private;
3053 	struct hlist_nulls_node *node;
3054 	unsigned int expected = 1;
3055 	struct sock *sk;
3056 
3057 	sock_hold(*start_sk);
3058 	iter->batch[iter->end_sk++].sk = *start_sk;
3059 
3060 	sk = sk_nulls_next(*start_sk);
3061 	*start_sk = NULL;
3062 	sk_nulls_for_each_from(sk, node) {
3063 		if (seq_sk_match(seq, sk)) {
3064 			if (iter->end_sk < iter->max_sk) {
3065 				sock_hold(sk);
3066 				iter->batch[iter->end_sk++].sk = sk;
3067 			} else if (!*start_sk) {
3068 				/* Remember where we left off. */
3069 				*start_sk = sk;
3070 			}
3071 			expected++;
3072 		}
3073 	}
3074 
3075 	return expected;
3076 }
3077 
3078 static unsigned int bpf_iter_tcp_established_batch(struct seq_file *seq,
3079 						   struct sock **start_sk)
3080 {
3081 	struct bpf_tcp_iter_state *iter = seq->private;
3082 	struct hlist_nulls_node *node;
3083 	struct sock *sk = *start_sk;
3084 	unsigned int expected = 0;
3085 
3086 	*start_sk = NULL;
3087 	sk_nulls_for_each_from(sk, node) {
3088 		if (!seq_sk_match(seq, sk))
3089 			continue;
3090 		expected++;
3091 		if (iter->end_sk < iter->max_sk) {
3092 			/* reqsk_queue_hash_req() inserts with sk_refcnt == 0
3093 			 * and refcount_set()s it after the bucket lock drops.
3094 			 */
3095 			if (unlikely(!refcount_inc_not_zero(&sk->sk_refcnt)))
3096 				continue;
3097 			iter->batch[iter->end_sk++].sk = sk;
3098 		} else if (!*start_sk) {
3099 			/* Remember where we left off. */
3100 			*start_sk = sk;
3101 		}
3102 	}
3103 
3104 	return expected;
3105 }
3106 
3107 static unsigned int bpf_iter_fill_batch(struct seq_file *seq,
3108 					struct sock **start_sk)
3109 {
3110 	struct bpf_tcp_iter_state *iter = seq->private;
3111 	struct tcp_iter_state *st = &iter->state;
3112 
3113 	if (st->state == TCP_SEQ_STATE_LISTENING)
3114 		return bpf_iter_tcp_listening_batch(seq, start_sk);
3115 	else
3116 		return bpf_iter_tcp_established_batch(seq, start_sk);
3117 }
3118 
3119 static void bpf_iter_tcp_unlock_bucket(struct seq_file *seq)
3120 {
3121 	struct inet_hashinfo *hinfo = seq_file_net(seq)->ipv4.tcp_death_row.hashinfo;
3122 	struct bpf_tcp_iter_state *iter = seq->private;
3123 	struct tcp_iter_state *st = &iter->state;
3124 
3125 	if (st->state == TCP_SEQ_STATE_LISTENING)
3126 		spin_unlock(&hinfo->lhash2[st->bucket].lock);
3127 	else
3128 		spin_unlock_bh(inet_ehash_lockp(hinfo, st->bucket));
3129 }
3130 
3131 static struct sock *bpf_iter_tcp_batch(struct seq_file *seq)
3132 {
3133 	struct bpf_tcp_iter_state *iter = seq->private;
3134 	unsigned int expected;
3135 	struct sock *sk;
3136 	int err;
3137 
3138 again:
3139 	sk = bpf_iter_tcp_resume(seq);
3140 	if (!sk)
3141 		return NULL; /* Done */
3142 
3143 	expected = bpf_iter_fill_batch(seq, &sk);
3144 	if (likely(!sk))
3145 		goto done;
3146 
3147 	/* Batch size was too small. */
3148 	bpf_iter_tcp_unlock_bucket(seq);
3149 	bpf_iter_tcp_put_batch(iter);
3150 	err = bpf_iter_tcp_realloc_batch(iter, expected * 3 / 2,
3151 					 GFP_USER);
3152 	if (err) {
3153 		iter->cur_sk = 0;
3154 		iter->end_sk = 0;
3155 		return ERR_PTR(err);
3156 	}
3157 
3158 	sk = bpf_iter_tcp_resume(seq);
3159 	if (!sk)
3160 		return NULL; /* Done */
3161 
3162 	expected = bpf_iter_fill_batch(seq, &sk);
3163 	if (likely(!sk))
3164 		goto done;
3165 
3166 	/* Batch size was still too small. Hold onto the lock while we try
3167 	 * again with a larger batch to make sure the current bucket's size
3168 	 * does not change in the meantime.
3169 	 */
3170 	err = bpf_iter_tcp_realloc_batch(iter, expected, GFP_NOWAIT);
3171 	if (err) {
3172 		bpf_iter_tcp_unlock_bucket(seq);
3173 		return ERR_PTR(err);
3174 	}
3175 
3176 	bpf_iter_fill_batch(seq, &sk);
3177 	WARN_ON_ONCE(sk);
3178 done:
3179 	bpf_iter_tcp_unlock_bucket(seq);
3180 	if (unlikely(!iter->end_sk)) {
3181 		++iter->state.bucket;
3182 		goto again;
3183 	}
3184 	return iter->batch[0].sk;
3185 }
3186 
3187 static void *bpf_iter_tcp_seq_start(struct seq_file *seq, loff_t *pos)
3188 {
3189 	/* bpf iter does not support lseek, so it always
3190 	 * continue from where it was stop()-ped.
3191 	 */
3192 	if (*pos)
3193 		return bpf_iter_tcp_batch(seq);
3194 
3195 	return SEQ_START_TOKEN;
3196 }
3197 
3198 static void *bpf_iter_tcp_seq_next(struct seq_file *seq, void *v, loff_t *pos)
3199 {
3200 	struct bpf_tcp_iter_state *iter = seq->private;
3201 	struct tcp_iter_state *st = &iter->state;
3202 	struct sock *sk;
3203 
3204 	/* Whenever seq_next() is called, the iter->cur_sk is
3205 	 * done with seq_show(), so advance to the next sk in
3206 	 * the batch.
3207 	 */
3208 	if (iter->cur_sk < iter->end_sk) {
3209 		/* Keeping st->num consistent in tcp_iter_state.
3210 		 * bpf_iter_tcp does not use st->num.
3211 		 * meta.seq_num is used instead.
3212 		 */
3213 		st->num++;
3214 		sock_gen_put(iter->batch[iter->cur_sk++].sk);
3215 	}
3216 
3217 	if (iter->cur_sk < iter->end_sk)
3218 		sk = iter->batch[iter->cur_sk].sk;
3219 	else
3220 		sk = bpf_iter_tcp_batch(seq);
3221 
3222 	++*pos;
3223 	/* Keeping st->last_pos consistent in tcp_iter_state.
3224 	 * bpf iter does not do lseek, so st->last_pos always equals to *pos.
3225 	 */
3226 	st->last_pos = *pos;
3227 	return sk;
3228 }
3229 
3230 static int bpf_iter_tcp_seq_show(struct seq_file *seq, void *v)
3231 {
3232 	struct bpf_iter_meta meta;
3233 	struct bpf_prog *prog;
3234 	struct sock *sk = v;
3235 	uid_t uid;
3236 	int ret;
3237 
3238 	if (v == SEQ_START_TOKEN)
3239 		return 0;
3240 
3241 	if (sk_fullsock(sk))
3242 		lock_sock(sk);
3243 
3244 	if (unlikely(sk_unhashed(sk))) {
3245 		ret = SEQ_SKIP;
3246 		goto unlock;
3247 	}
3248 
3249 	if (sk->sk_state == TCP_TIME_WAIT) {
3250 		uid = 0;
3251 	} else if (sk->sk_state == TCP_NEW_SYN_RECV) {
3252 		const struct request_sock *req = v;
3253 
3254 		uid = from_kuid_munged(seq_user_ns(seq),
3255 				       sk_uid(req->rsk_listener));
3256 	} else {
3257 		uid = from_kuid_munged(seq_user_ns(seq), sk_uid(sk));
3258 	}
3259 
3260 	meta.seq = seq;
3261 	prog = bpf_iter_get_info(&meta, false);
3262 	ret = tcp_prog_seq_show(prog, &meta, v, uid);
3263 
3264 unlock:
3265 	if (sk_fullsock(sk))
3266 		release_sock(sk);
3267 	return ret;
3268 
3269 }
3270 
3271 static void bpf_iter_tcp_seq_stop(struct seq_file *seq, void *v)
3272 {
3273 	struct bpf_tcp_iter_state *iter = seq->private;
3274 	struct bpf_iter_meta meta;
3275 	struct bpf_prog *prog;
3276 
3277 	if (!v) {
3278 		meta.seq = seq;
3279 		prog = bpf_iter_get_info(&meta, true);
3280 		if (prog)
3281 			(void)tcp_prog_seq_show(prog, &meta, v, 0);
3282 	}
3283 
3284 	if (iter->cur_sk < iter->end_sk)
3285 		bpf_iter_tcp_put_batch(iter);
3286 }
3287 
3288 static const struct seq_operations bpf_iter_tcp_seq_ops = {
3289 	.show		= bpf_iter_tcp_seq_show,
3290 	.start		= bpf_iter_tcp_seq_start,
3291 	.next		= bpf_iter_tcp_seq_next,
3292 	.stop		= bpf_iter_tcp_seq_stop,
3293 };
3294 #endif
3295 static unsigned short seq_file_family(const struct seq_file *seq)
3296 {
3297 	const struct tcp_seq_afinfo *afinfo;
3298 
3299 #ifdef CONFIG_BPF_SYSCALL
3300 	/* Iterated from bpf_iter.  Let the bpf prog to filter instead. */
3301 	if (seq->op == &bpf_iter_tcp_seq_ops)
3302 		return AF_UNSPEC;
3303 #endif
3304 
3305 	/* Iterated from proc fs */
3306 	afinfo = pde_data(file_inode(seq->file));
3307 	return afinfo->family;
3308 }
3309 
3310 static const struct seq_operations tcp4_seq_ops = {
3311 	.show		= tcp4_seq_show,
3312 	.start		= tcp_seq_start,
3313 	.next		= tcp_seq_next,
3314 	.stop		= tcp_seq_stop,
3315 };
3316 
3317 static struct tcp_seq_afinfo tcp4_seq_afinfo = {
3318 	.family		= AF_INET,
3319 };
3320 
3321 static int __net_init tcp4_proc_init_net(struct net *net)
3322 {
3323 	if (!proc_create_net_data("tcp", 0444, net->proc_net, &tcp4_seq_ops,
3324 			sizeof(struct tcp_iter_state), &tcp4_seq_afinfo))
3325 		return -ENOMEM;
3326 	return 0;
3327 }
3328 
3329 static void __net_exit tcp4_proc_exit_net(struct net *net)
3330 {
3331 	remove_proc_entry("tcp", net->proc_net);
3332 }
3333 
3334 static struct pernet_operations tcp4_net_ops = {
3335 	.init = tcp4_proc_init_net,
3336 	.exit = tcp4_proc_exit_net,
3337 };
3338 
3339 int __init tcp4_proc_init(void)
3340 {
3341 	return register_pernet_subsys(&tcp4_net_ops);
3342 }
3343 
3344 void tcp4_proc_exit(void)
3345 {
3346 	unregister_pernet_subsys(&tcp4_net_ops);
3347 }
3348 #endif /* CONFIG_PROC_FS */
3349 
3350 struct proto tcp_prot = {
3351 	.name			= "TCP",
3352 	.owner			= THIS_MODULE,
3353 	.close			= tcp_close,
3354 	.pre_connect		= tcp_v4_pre_connect,
3355 	.connect		= tcp_v4_connect,
3356 	.disconnect		= tcp_disconnect,
3357 	.accept			= inet_csk_accept,
3358 	.ioctl			= tcp_ioctl,
3359 	.init			= tcp_v4_init_sock,
3360 	.destroy		= tcp_v4_destroy_sock,
3361 	.shutdown		= tcp_shutdown,
3362 	.setsockopt		= tcp_setsockopt,
3363 	.getsockopt		= tcp_getsockopt,
3364 	.bpf_bypass_getsockopt	= tcp_bpf_bypass_getsockopt,
3365 	.keepalive		= tcp_set_keepalive,
3366 	.recvmsg		= tcp_recvmsg,
3367 	.sendmsg		= tcp_sendmsg,
3368 	.splice_eof		= tcp_splice_eof,
3369 	.backlog_rcv		= tcp_v4_do_rcv,
3370 	.release_cb		= tcp_release_cb,
3371 	.hash			= inet_hash,
3372 	.unhash			= inet_unhash,
3373 	.get_port		= inet_csk_get_port,
3374 	.put_port		= inet_put_port,
3375 #ifdef CONFIG_BPF_SYSCALL
3376 	.psock_update_sk_prot	= tcp_bpf_update_proto,
3377 #endif
3378 	.enter_memory_pressure	= tcp_enter_memory_pressure,
3379 	.leave_memory_pressure	= tcp_leave_memory_pressure,
3380 	.stream_memory_free	= tcp_stream_memory_free,
3381 	.sockets_allocated	= &tcp_sockets_allocated,
3382 
3383 	.memory_allocated	= &net_aligned_data.tcp_memory_allocated,
3384 	.per_cpu_fw_alloc	= &tcp_memory_per_cpu_fw_alloc,
3385 
3386 	.memory_pressure	= &tcp_memory_pressure,
3387 	.sysctl_mem		= sysctl_tcp_mem,
3388 	.sysctl_wmem_offset	= offsetof(struct net, ipv4.sysctl_tcp_wmem),
3389 	.sysctl_rmem_offset	= offsetof(struct net, ipv4.sysctl_tcp_rmem),
3390 	.max_header		= MAX_TCP_HEADER,
3391 	.obj_size		= sizeof(struct tcp_sock),
3392 	.freeptr_offset		= offsetof(struct tcp_sock,
3393 					   inet_conn.icsk_inet.sk.sk_freeptr),
3394 	.slab_flags		= SLAB_TYPESAFE_BY_RCU,
3395 	.twsk_prot		= &tcp_timewait_sock_ops,
3396 	.rsk_prot		= &tcp_request_sock_ops,
3397 	.h.hashinfo		= NULL,
3398 	.no_autobind		= true,
3399 	.diag_destroy		= tcp_abort,
3400 };
3401 EXPORT_SYMBOL(tcp_prot);
3402 
3403 static void __net_exit tcp_sk_exit(struct net *net)
3404 {
3405 	if (net->ipv4.tcp_congestion_control)
3406 		bpf_module_put(net->ipv4.tcp_congestion_control,
3407 			       net->ipv4.tcp_congestion_control->owner);
3408 }
3409 
3410 static void __net_init tcp_set_hashinfo(struct net *net)
3411 {
3412 	struct inet_hashinfo *hinfo;
3413 	unsigned int ehash_entries;
3414 	struct net *old_net;
3415 
3416 	if (net_eq(net, &init_net))
3417 		goto fallback;
3418 
3419 	old_net = current->nsproxy->net_ns;
3420 	ehash_entries = READ_ONCE(old_net->ipv4.sysctl_tcp_child_ehash_entries);
3421 	if (!ehash_entries)
3422 		goto fallback;
3423 
3424 	ehash_entries = roundup_pow_of_two(ehash_entries);
3425 	hinfo = inet_pernet_hashinfo_alloc(&tcp_hashinfo, ehash_entries);
3426 	if (!hinfo) {
3427 		pr_warn("Failed to allocate TCP ehash (entries: %u) "
3428 			"for a netns, fallback to the global one\n",
3429 			ehash_entries);
3430 fallback:
3431 		hinfo = &tcp_hashinfo;
3432 		ehash_entries = tcp_hashinfo.ehash_mask + 1;
3433 	}
3434 
3435 	net->ipv4.tcp_death_row.hashinfo = hinfo;
3436 	net->ipv4.tcp_death_row.sysctl_max_tw_buckets = ehash_entries / 2;
3437 	net->ipv4.sysctl_max_syn_backlog = max(128U, ehash_entries / 128);
3438 }
3439 
3440 static int __net_init tcp_sk_init(struct net *net)
3441 {
3442 	net->ipv4.sysctl_tcp_ecn = TCP_ECN_IN_ECN_OUT_NOECN;
3443 	net->ipv4.sysctl_tcp_ecn_option = TCP_ACCECN_OPTION_FULL;
3444 	net->ipv4.sysctl_tcp_ecn_option_beacon = TCP_ACCECN_OPTION_BEACON;
3445 	net->ipv4.sysctl_tcp_ecn_fallback = 1;
3446 
3447 	net->ipv4.sysctl_tcp_base_mss = TCP_BASE_MSS;
3448 	net->ipv4.sysctl_tcp_min_snd_mss = TCP_MIN_SND_MSS;
3449 	net->ipv4.sysctl_tcp_probe_threshold = TCP_PROBE_THRESHOLD;
3450 	net->ipv4.sysctl_tcp_probe_interval = TCP_PROBE_INTERVAL;
3451 	net->ipv4.sysctl_tcp_mtu_probe_floor = TCP_MIN_SND_MSS;
3452 
3453 	net->ipv4.sysctl_tcp_keepalive_time = TCP_KEEPALIVE_TIME;
3454 	net->ipv4.sysctl_tcp_keepalive_probes = TCP_KEEPALIVE_PROBES;
3455 	net->ipv4.sysctl_tcp_keepalive_intvl = TCP_KEEPALIVE_INTVL;
3456 
3457 	net->ipv4.sysctl_tcp_syn_retries = TCP_SYN_RETRIES;
3458 	net->ipv4.sysctl_tcp_synack_retries = TCP_SYNACK_RETRIES;
3459 	net->ipv4.sysctl_tcp_syncookies = 1;
3460 	net->ipv4.sysctl_tcp_reordering = TCP_FASTRETRANS_THRESH;
3461 	net->ipv4.sysctl_tcp_retries1 = TCP_RETR1;
3462 	net->ipv4.sysctl_tcp_retries2 = TCP_RETR2;
3463 	net->ipv4.sysctl_tcp_orphan_retries = 0;
3464 	net->ipv4.sysctl_tcp_fin_timeout = TCP_FIN_TIMEOUT;
3465 	net->ipv4.sysctl_tcp_notsent_lowat = UINT_MAX;
3466 	net->ipv4.sysctl_tcp_tw_reuse = 2;
3467 	net->ipv4.sysctl_tcp_tw_reuse_delay = 1 * MSEC_PER_SEC;
3468 	net->ipv4.sysctl_tcp_no_ssthresh_metrics_save = 1;
3469 
3470 	refcount_set(&net->ipv4.tcp_death_row.tw_refcount, 1);
3471 	tcp_set_hashinfo(net);
3472 
3473 	net->ipv4.sysctl_tcp_sack = 1;
3474 	net->ipv4.sysctl_tcp_window_scaling = 1;
3475 	net->ipv4.sysctl_tcp_timestamps = 1;
3476 	net->ipv4.sysctl_tcp_early_retrans = 3;
3477 	net->ipv4.sysctl_tcp_recovery = TCP_RACK_LOSS_DETECTION;
3478 	net->ipv4.sysctl_tcp_slow_start_after_idle = 1; /* By default, RFC2861 behavior.  */
3479 	net->ipv4.sysctl_tcp_retrans_collapse = 1;
3480 	net->ipv4.sysctl_tcp_max_reordering = 300;
3481 	net->ipv4.sysctl_tcp_dsack = 1;
3482 	net->ipv4.sysctl_tcp_app_win = 31;
3483 	net->ipv4.sysctl_tcp_adv_win_scale = 1;
3484 	net->ipv4.sysctl_tcp_frto = 2;
3485 	net->ipv4.sysctl_tcp_moderate_rcvbuf = 1;
3486 	net->ipv4.sysctl_tcp_rcvbuf_low_rtt = USEC_PER_MSEC;
3487 	/* This limits the percentage of the congestion window which we
3488 	 * will allow a single TSO frame to consume.  Building TSO frames
3489 	 * which are too large can cause TCP streams to be bursty.
3490 	 */
3491 	net->ipv4.sysctl_tcp_tso_win_divisor = 3;
3492 	/* Default TSQ limit of 4 MB */
3493 	net->ipv4.sysctl_tcp_limit_output_bytes = 4 << 20;
3494 
3495 	/* rfc5961 challenge ack rate limiting, per net-ns, disabled by default. */
3496 	net->ipv4.sysctl_tcp_challenge_ack_limit = INT_MAX;
3497 
3498 	net->ipv4.sysctl_tcp_min_tso_segs = 2;
3499 	net->ipv4.sysctl_tcp_tso_rtt_log = 9;  /* 2^9 = 512 usec */
3500 	net->ipv4.sysctl_tcp_min_rtt_wlen = 300;
3501 	net->ipv4.sysctl_tcp_autocorking = 1;
3502 	net->ipv4.sysctl_tcp_invalid_ratelimit = HZ/2;
3503 	net->ipv4.sysctl_tcp_pacing_ss_ratio = 200;
3504 	net->ipv4.sysctl_tcp_pacing_ca_ratio = 120;
3505 	if (net != &init_net) {
3506 		memcpy(net->ipv4.sysctl_tcp_rmem,
3507 		       init_net.ipv4.sysctl_tcp_rmem,
3508 		       sizeof(init_net.ipv4.sysctl_tcp_rmem));
3509 		memcpy(net->ipv4.sysctl_tcp_wmem,
3510 		       init_net.ipv4.sysctl_tcp_wmem,
3511 		       sizeof(init_net.ipv4.sysctl_tcp_wmem));
3512 	}
3513 	net->ipv4.sysctl_tcp_comp_sack_delay_ns = NSEC_PER_MSEC;
3514 	net->ipv4.sysctl_tcp_comp_sack_slack_ns = 10 * NSEC_PER_USEC;
3515 	net->ipv4.sysctl_tcp_comp_sack_nr = 44;
3516 	net->ipv4.sysctl_tcp_comp_sack_rtt_percent = 33;
3517 	net->ipv4.sysctl_tcp_backlog_ack_defer = 1;
3518 	net->ipv4.sysctl_tcp_fastopen = TFO_CLIENT_ENABLE;
3519 	net->ipv4.sysctl_tcp_fastopen_blackhole_timeout = 0;
3520 	atomic_set(&net->ipv4.tfo_active_disable_times, 0);
3521 
3522 	/* Set default values for PLB */
3523 	net->ipv4.sysctl_tcp_plb_enabled = 0; /* Disabled by default */
3524 	net->ipv4.sysctl_tcp_plb_idle_rehash_rounds = 3;
3525 	net->ipv4.sysctl_tcp_plb_rehash_rounds = 12;
3526 	net->ipv4.sysctl_tcp_plb_suspend_rto_sec = 60;
3527 	/* Default congestion threshold for PLB to mark a round is 50% */
3528 	net->ipv4.sysctl_tcp_plb_cong_thresh = (1 << TCP_PLB_SCALE) / 2;
3529 
3530 	/* Reno is always built in */
3531 	if (!net_eq(net, &init_net) &&
3532 	    bpf_try_module_get(init_net.ipv4.tcp_congestion_control,
3533 			       init_net.ipv4.tcp_congestion_control->owner))
3534 		net->ipv4.tcp_congestion_control = init_net.ipv4.tcp_congestion_control;
3535 	else
3536 		net->ipv4.tcp_congestion_control = &tcp_reno;
3537 
3538 	net->ipv4.sysctl_tcp_syn_linear_timeouts = 4;
3539 	net->ipv4.sysctl_tcp_shrink_window = 0;
3540 
3541 	net->ipv4.sysctl_tcp_pingpong_thresh = 1;
3542 	net->ipv4.sysctl_tcp_rto_min_us = jiffies_to_usecs(TCP_RTO_MIN);
3543 	net->ipv4.sysctl_tcp_rto_max_ms = TCP_RTO_MAX_SEC * MSEC_PER_SEC;
3544 
3545 	return 0;
3546 }
3547 
3548 static void __net_exit tcp_sk_exit_batch(struct list_head *net_exit_list)
3549 {
3550 	struct net *net;
3551 
3552 	/* make sure concurrent calls to tcp_sk_exit_batch from net_cleanup_work
3553 	 * and failed setup_net error unwinding path are serialized.
3554 	 *
3555 	 * tcp_twsk_purge() handles twsk in any dead netns, not just those in
3556 	 * net_exit_list, the thread that dismantles a particular twsk must
3557 	 * do so without other thread progressing to refcount_dec_and_test() of
3558 	 * tcp_death_row.tw_refcount.
3559 	 */
3560 	mutex_lock(&tcp_exit_batch_mutex);
3561 
3562 	tcp_twsk_purge(net_exit_list);
3563 
3564 	list_for_each_entry(net, net_exit_list, exit_list) {
3565 		inet_pernet_hashinfo_free(net->ipv4.tcp_death_row.hashinfo);
3566 		WARN_ON_ONCE(!refcount_dec_and_test(&net->ipv4.tcp_death_row.tw_refcount));
3567 		tcp_fastopen_ctx_destroy(net);
3568 	}
3569 
3570 	mutex_unlock(&tcp_exit_batch_mutex);
3571 }
3572 
3573 static struct pernet_operations __net_initdata tcp_sk_ops = {
3574        .init	   = tcp_sk_init,
3575        .exit	   = tcp_sk_exit,
3576        .exit_batch = tcp_sk_exit_batch,
3577 };
3578 
3579 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
3580 DEFINE_BPF_ITER_FUNC(tcp, struct bpf_iter_meta *meta,
3581 		     struct sock_common *sk_common, uid_t uid)
3582 
3583 #define INIT_BATCH_SZ 16
3584 
3585 static int bpf_iter_init_tcp(void *priv_data, struct bpf_iter_aux_info *aux)
3586 {
3587 	struct bpf_tcp_iter_state *iter = priv_data;
3588 	int err;
3589 
3590 	err = bpf_iter_init_seq_net(priv_data, aux);
3591 	if (err)
3592 		return err;
3593 
3594 	err = bpf_iter_tcp_realloc_batch(iter, INIT_BATCH_SZ, GFP_USER);
3595 	if (err) {
3596 		bpf_iter_fini_seq_net(priv_data);
3597 		return err;
3598 	}
3599 
3600 	return 0;
3601 }
3602 
3603 static void bpf_iter_fini_tcp(void *priv_data)
3604 {
3605 	struct bpf_tcp_iter_state *iter = priv_data;
3606 
3607 	bpf_iter_fini_seq_net(priv_data);
3608 	kvfree(iter->batch);
3609 }
3610 
3611 static const struct bpf_iter_seq_info tcp_seq_info = {
3612 	.seq_ops		= &bpf_iter_tcp_seq_ops,
3613 	.init_seq_private	= bpf_iter_init_tcp,
3614 	.fini_seq_private	= bpf_iter_fini_tcp,
3615 	.seq_priv_size		= sizeof(struct bpf_tcp_iter_state),
3616 };
3617 
3618 static const struct bpf_func_proto *
3619 bpf_iter_tcp_get_func_proto(enum bpf_func_id func_id,
3620 			    const struct bpf_prog *prog)
3621 {
3622 	switch (func_id) {
3623 	case BPF_FUNC_setsockopt:
3624 		return &bpf_sk_setsockopt_proto;
3625 	case BPF_FUNC_getsockopt:
3626 		return &bpf_sk_getsockopt_proto;
3627 	default:
3628 		return NULL;
3629 	}
3630 }
3631 
3632 static struct bpf_iter_reg tcp_reg_info = {
3633 	.target			= "tcp",
3634 	.ctx_arg_info_size	= 1,
3635 	.ctx_arg_info		= {
3636 		{ offsetof(struct bpf_iter__tcp, sk_common),
3637 		  PTR_TO_BTF_ID_OR_NULL | PTR_TRUSTED },
3638 	},
3639 	.get_func_proto		= bpf_iter_tcp_get_func_proto,
3640 	.seq_info		= &tcp_seq_info,
3641 };
3642 
3643 static void __init bpf_iter_register(void)
3644 {
3645 	tcp_reg_info.ctx_arg_info[0].btf_id = btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON];
3646 	if (bpf_iter_reg_target(&tcp_reg_info))
3647 		pr_warn("Warning: could not register bpf iterator tcp\n");
3648 }
3649 
3650 #endif
3651 
3652 void __init tcp_v4_init(void)
3653 {
3654 	int cpu, res;
3655 
3656 	for_each_possible_cpu(cpu) {
3657 		struct sock *sk;
3658 
3659 		res = inet_ctl_sock_create(&sk, PF_INET, SOCK_RAW,
3660 					   IPPROTO_TCP, &init_net);
3661 		if (res)
3662 			panic("Failed to create the TCP control socket.\n");
3663 		sock_set_flag(sk, SOCK_USE_WRITE_QUEUE);
3664 
3665 		/* Please enforce IP_DF and IPID==0 for RST and
3666 		 * ACK sent in SYN-RECV and TIME-WAIT state.
3667 		 */
3668 		inet_sk(sk)->pmtudisc = IP_PMTUDISC_DO;
3669 
3670 		sk->sk_clockid = CLOCK_MONOTONIC;
3671 
3672 		per_cpu(ipv4_tcp_sk.sock, cpu) = sk;
3673 	}
3674 	if (register_pernet_subsys(&tcp_sk_ops))
3675 		panic("Failed to create the TCP control socket.\n");
3676 
3677 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
3678 	bpf_iter_register();
3679 #endif
3680 }
3681