File Index
Files and directories
Sign in
FILE

inet_connection_sock.c

File preview with syntax highlighting.

linux-6.19.14/net/ipv4/inet_connection_sock.c C
   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 *		Support for INET connection oriented protocols.
   8 *
   9 * Authors:	See the TCP sources
  10 */
  11
  12#include <linux/module.h>
  13#include <linux/jhash.h>
  14
  15#include <net/inet_connection_sock.h>
  16#include <net/inet_hashtables.h>
  17#include <net/inet_timewait_sock.h>
  18#include <net/ip.h>
  19#include <net/route.h>
  20#include <net/tcp_states.h>
  21#include <net/xfrm.h>
  22#include <net/tcp.h>
  23#include <net/sock_reuseport.h>
  24#include <net/addrconf.h>
  25
  26#if IS_ENABLED(CONFIG_IPV6)
  27/* match_sk*_wildcard == true:  IPV6_ADDR_ANY equals to any IPv6 addresses
  28 *				if IPv6 only, and any IPv4 addresses
  29 *				if not IPv6 only
  30 * match_sk*_wildcard == false: addresses must be exactly the same, i.e.
  31 *				IPV6_ADDR_ANY only equals to IPV6_ADDR_ANY,
  32 *				and 0.0.0.0 equals to 0.0.0.0 only
  33 */
  34static bool ipv6_rcv_saddr_equal(const struct in6_addr *sk1_rcv_saddr6,
  35				 const struct in6_addr *sk2_rcv_saddr6,
  36				 __be32 sk1_rcv_saddr, __be32 sk2_rcv_saddr,
  37				 bool sk1_ipv6only, bool sk2_ipv6only,
  38				 bool match_sk1_wildcard,
  39				 bool match_sk2_wildcard)
  40{
  41	int addr_type = ipv6_addr_type(sk1_rcv_saddr6);
  42	int addr_type2 = sk2_rcv_saddr6 ? ipv6_addr_type(sk2_rcv_saddr6) : IPV6_ADDR_MAPPED;
  43
  44	/* if both are mapped, treat as IPv4 */
  45	if (addr_type == IPV6_ADDR_MAPPED && addr_type2 == IPV6_ADDR_MAPPED) {
  46		if (!sk2_ipv6only) {
  47			if (sk1_rcv_saddr == sk2_rcv_saddr)
  48				return true;
  49			return (match_sk1_wildcard && !sk1_rcv_saddr) ||
  50				(match_sk2_wildcard && !sk2_rcv_saddr);
  51		}
  52		return false;
  53	}
  54
  55	if (addr_type == IPV6_ADDR_ANY && addr_type2 == IPV6_ADDR_ANY)
  56		return true;
  57
  58	if (addr_type2 == IPV6_ADDR_ANY && match_sk2_wildcard &&
  59	    !(sk2_ipv6only && addr_type == IPV6_ADDR_MAPPED))
  60		return true;
  61
  62	if (addr_type == IPV6_ADDR_ANY && match_sk1_wildcard &&
  63	    !(sk1_ipv6only && addr_type2 == IPV6_ADDR_MAPPED))
  64		return true;
  65
  66	if (sk2_rcv_saddr6 &&
  67	    ipv6_addr_equal(sk1_rcv_saddr6, sk2_rcv_saddr6))
  68		return true;
  69
  70	return false;
  71}
  72#endif
  73
  74/* match_sk*_wildcard == true:  0.0.0.0 equals to any IPv4 addresses
  75 * match_sk*_wildcard == false: addresses must be exactly the same, i.e.
  76 *				0.0.0.0 only equals to 0.0.0.0
  77 */
  78static bool ipv4_rcv_saddr_equal(__be32 sk1_rcv_saddr, __be32 sk2_rcv_saddr,
  79				 bool sk2_ipv6only, bool match_sk1_wildcard,
  80				 bool match_sk2_wildcard)
  81{
  82	if (!sk2_ipv6only) {
  83		if (sk1_rcv_saddr == sk2_rcv_saddr)
  84			return true;
  85		return (match_sk1_wildcard && !sk1_rcv_saddr) ||
  86			(match_sk2_wildcard && !sk2_rcv_saddr);
  87	}
  88	return false;
  89}
  90
  91bool inet_rcv_saddr_equal(const struct sock *sk, const struct sock *sk2,
  92			  bool match_wildcard)
  93{
  94#if IS_ENABLED(CONFIG_IPV6)
  95	if (sk->sk_family == AF_INET6)
  96		return ipv6_rcv_saddr_equal(&sk->sk_v6_rcv_saddr,
  97					    inet6_rcv_saddr(sk2),
  98					    sk->sk_rcv_saddr,
  99					    sk2->sk_rcv_saddr,
 100					    ipv6_only_sock(sk),
 101					    ipv6_only_sock(sk2),
 102					    match_wildcard,
 103					    match_wildcard);
 104#endif
 105	return ipv4_rcv_saddr_equal(sk->sk_rcv_saddr, sk2->sk_rcv_saddr,
 106				    ipv6_only_sock(sk2), match_wildcard,
 107				    match_wildcard);
 108}
 109EXPORT_SYMBOL(inet_rcv_saddr_equal);
 110
 111bool inet_rcv_saddr_any(const struct sock *sk)
 112{
 113#if IS_ENABLED(CONFIG_IPV6)
 114	if (sk->sk_family == AF_INET6)
 115		return ipv6_addr_any(&sk->sk_v6_rcv_saddr);
 116#endif
 117	return !sk->sk_rcv_saddr;
 118}
 119
 120/**
 121 *	inet_sk_get_local_port_range - fetch ephemeral ports range
 122 *	@sk: socket
 123 *	@low: pointer to low port
 124 *	@high: pointer to high port
 125 *
 126 *	Fetch netns port range (/proc/sys/net/ipv4/ip_local_port_range)
 127 *	Range can be overridden if socket got IP_LOCAL_PORT_RANGE option.
 128 *	Returns true if IP_LOCAL_PORT_RANGE was set on this socket.
 129 */
 130bool inet_sk_get_local_port_range(const struct sock *sk, int *low, int *high)
 131{
 132	int lo, hi, sk_lo, sk_hi;
 133	bool local_range = false;
 134	u32 sk_range;
 135
 136	inet_get_local_port_range(sock_net(sk), &lo, &hi);
 137
 138	sk_range = READ_ONCE(inet_sk(sk)->local_port_range);
 139	if (unlikely(sk_range)) {
 140		sk_lo = sk_range & 0xffff;
 141		sk_hi = sk_range >> 16;
 142
 143		if (lo <= sk_lo && sk_lo <= hi)
 144			lo = sk_lo;
 145		if (lo <= sk_hi && sk_hi <= hi)
 146			hi = sk_hi;
 147		local_range = true;
 148	}
 149
 150	*low = lo;
 151	*high = hi;
 152	return local_range;
 153}
 154EXPORT_SYMBOL(inet_sk_get_local_port_range);
 155
 156static bool inet_bind_conflict(const struct sock *sk, struct sock *sk2,
 157			       kuid_t uid, bool relax,
 158			       bool reuseport_cb_ok, bool reuseport_ok)
 159{
 160	int bound_dev_if2;
 161
 162	if (sk == sk2)
 163		return false;
 164
 165	bound_dev_if2 = READ_ONCE(sk2->sk_bound_dev_if);
 166
 167	if (!sk->sk_bound_dev_if || !bound_dev_if2 ||
 168	    sk->sk_bound_dev_if == bound_dev_if2) {
 169		if (sk->sk_reuse && sk2->sk_reuse &&
 170		    sk2->sk_state != TCP_LISTEN) {
 171			if (!relax || (!reuseport_ok && sk->sk_reuseport &&
 172				       sk2->sk_reuseport && reuseport_cb_ok &&
 173				       (sk2->sk_state == TCP_TIME_WAIT ||
 174					uid_eq(uid, sk_uid(sk2)))))
 175				return true;
 176		} else if (!reuseport_ok || !sk->sk_reuseport ||
 177			   !sk2->sk_reuseport || !reuseport_cb_ok ||
 178			   (sk2->sk_state != TCP_TIME_WAIT &&
 179			    !uid_eq(uid, sk_uid(sk2)))) {
 180			return true;
 181		}
 182	}
 183	return false;
 184}
 185
 186static bool __inet_bhash2_conflict(const struct sock *sk, struct sock *sk2,
 187				   kuid_t uid, bool relax,
 188				   bool reuseport_cb_ok, bool reuseport_ok)
 189{
 190	if (ipv6_only_sock(sk2)) {
 191		if (sk->sk_family == AF_INET)
 192			return false;
 193
 194#if IS_ENABLED(CONFIG_IPV6)
 195		if (ipv6_addr_v4mapped(&sk->sk_v6_rcv_saddr))
 196			return false;
 197#endif
 198	}
 199
 200	return inet_bind_conflict(sk, sk2, uid, relax,
 201				  reuseport_cb_ok, reuseport_ok);
 202}
 203
 204static bool inet_bhash2_conflict(const struct sock *sk,
 205				 const struct inet_bind2_bucket *tb2,
 206				 kuid_t uid,
 207				 bool relax, bool reuseport_cb_ok,
 208				 bool reuseport_ok)
 209{
 210	struct sock *sk2;
 211
 212	sk_for_each_bound(sk2, &tb2->owners) {
 213		if (__inet_bhash2_conflict(sk, sk2, uid, relax,
 214					   reuseport_cb_ok, reuseport_ok))
 215			return true;
 216	}
 217
 218	return false;
 219}
 220
 221#define sk_for_each_bound_bhash(__sk, __tb2, __tb)			\
 222	hlist_for_each_entry(__tb2, &(__tb)->bhash2, bhash_node)	\
 223		sk_for_each_bound((__sk), &(__tb2)->owners)
 224
 225/* This should be called only when the tb and tb2 hashbuckets' locks are held */
 226static int inet_csk_bind_conflict(const struct sock *sk,
 227				  const struct inet_bind_bucket *tb,
 228				  const struct inet_bind2_bucket *tb2, /* may be null */
 229				  bool relax, bool reuseport_ok)
 230{
 231	struct sock_reuseport *reuseport_cb;
 232	kuid_t uid = sk_uid(sk);
 233	bool reuseport_cb_ok;
 234	struct sock *sk2;
 235
 236	rcu_read_lock();
 237	reuseport_cb = rcu_dereference(sk->sk_reuseport_cb);
 238	/* paired with WRITE_ONCE() in __reuseport_(add|detach)_closed_sock */
 239	reuseport_cb_ok = !reuseport_cb || READ_ONCE(reuseport_cb->num_closed_socks);
 240	rcu_read_unlock();
 241
 242	/* Conflicts with an existing IPV6_ADDR_ANY (if ipv6) or INADDR_ANY (if
 243	 * ipv4) should have been checked already. We need to do these two
 244	 * checks separately because their spinlocks have to be acquired/released
 245	 * independently of each other, to prevent possible deadlocks
 246	 */
 247	if (inet_use_hash2_on_bind(sk))
 248		return tb2 && inet_bhash2_conflict(sk, tb2, uid, relax,
 249						   reuseport_cb_ok, reuseport_ok);
 250
 251	/* Unlike other sk lookup places we do not check
 252	 * for sk_net here, since _all_ the socks listed
 253	 * in tb->owners and tb2->owners list belong
 254	 * to the same net - the one this bucket belongs to.
 255	 */
 256	sk_for_each_bound_bhash(sk2, tb2, tb) {
 257		if (!inet_bind_conflict(sk, sk2, uid, relax, reuseport_cb_ok, reuseport_ok))
 258			continue;
 259
 260		if (inet_rcv_saddr_equal(sk, sk2, true))
 261			return true;
 262	}
 263
 264	return false;
 265}
 266
 267/* Determine if there is a bind conflict with an existing IPV6_ADDR_ANY (if ipv6) or
 268 * INADDR_ANY (if ipv4) socket.
 269 *
 270 * Caller must hold bhash hashbucket lock with local bh disabled, to protect
 271 * against concurrent binds on the port for addr any
 272 */
 273static bool inet_bhash2_addr_any_conflict(const struct sock *sk, int port, int l3mdev,
 274					  bool relax, bool reuseport_ok)
 275{
 276	const struct net *net = sock_net(sk);
 277	struct sock_reuseport *reuseport_cb;
 278	struct inet_bind_hashbucket *head2;
 279	struct inet_bind2_bucket *tb2;
 280	kuid_t uid = sk_uid(sk);
 281	bool conflict = false;
 282	bool reuseport_cb_ok;
 283
 284	rcu_read_lock();
 285	reuseport_cb = rcu_dereference(sk->sk_reuseport_cb);
 286	/* paired with WRITE_ONCE() in __reuseport_(add|detach)_closed_sock */
 287	reuseport_cb_ok = !reuseport_cb || READ_ONCE(reuseport_cb->num_closed_socks);
 288	rcu_read_unlock();
 289
 290	head2 = inet_bhash2_addr_any_hashbucket(sk, net, port);
 291
 292	spin_lock(&head2->lock);
 293
 294	inet_bind_bucket_for_each(tb2, &head2->chain) {
 295		if (!inet_bind2_bucket_match_addr_any(tb2, net, port, l3mdev, sk))
 296			continue;
 297
 298		if (!inet_bhash2_conflict(sk, tb2, uid, relax, reuseport_cb_ok,	reuseport_ok))
 299			continue;
 300
 301		conflict = true;
 302		break;
 303	}
 304
 305	spin_unlock(&head2->lock);
 306
 307	return conflict;
 308}
 309
 310/*
 311 * Find an open port number for the socket.  Returns with the
 312 * inet_bind_hashbucket locks held if successful.
 313 */
 314static struct inet_bind_hashbucket *
 315inet_csk_find_open_port(const struct sock *sk, struct inet_bind_bucket **tb_ret,
 316			struct inet_bind2_bucket **tb2_ret,
 317			struct inet_bind_hashbucket **head2_ret, int *port_ret)
 318{
 319	struct inet_hashinfo *hinfo = tcp_get_hashinfo(sk);
 320	int i, low, high, attempt_half, port, l3mdev;
 321	struct inet_bind_hashbucket *head, *head2;
 322	struct net *net = sock_net(sk);
 323	struct inet_bind2_bucket *tb2;
 324	struct inet_bind_bucket *tb;
 325	u32 remaining, offset;
 326	bool relax = false;
 327
 328	l3mdev = inet_sk_bound_l3mdev(sk);
 329ports_exhausted:
 330	attempt_half = (sk->sk_reuse == SK_CAN_REUSE) ? 1 : 0;
 331other_half_scan:
 332	inet_sk_get_local_port_range(sk, &low, &high);
 333	high++; /* [32768, 60999] -> [32768, 61000[ */
 334	if (high - low < 4)
 335		attempt_half = 0;
 336	if (attempt_half) {
 337		int half = low + (((high - low) >> 2) << 1);
 338
 339		if (attempt_half == 1)
 340			high = half;
 341		else
 342			low = half;
 343	}
 344	remaining = high - low;
 345	if (likely(remaining > 1))
 346		remaining &= ~1U;
 347
 348	offset = get_random_u32_below(remaining);
 349	/* __inet_hash_connect() favors ports having @low parity
 350	 * We do the opposite to not pollute connect() users.
 351	 */
 352	offset |= 1U;
 353
 354other_parity_scan:
 355	port = low + offset;
 356	for (i = 0; i < remaining; i += 2, port += 2) {
 357		if (unlikely(port >= high))
 358			port -= remaining;
 359		if (inet_is_local_reserved_port(net, port))
 360			continue;
 361		head = &hinfo->bhash[inet_bhashfn(net, port,
 362						  hinfo->bhash_size)];
 363		spin_lock_bh(&head->lock);
 364		if (inet_use_hash2_on_bind(sk)) {
 365			if (inet_bhash2_addr_any_conflict(sk, port, l3mdev, relax, false))
 366				goto next_port;
 367		}
 368
 369		head2 = inet_bhashfn_portaddr(hinfo, sk, net, port);
 370		spin_lock(&head2->lock);
 371		tb2 = inet_bind2_bucket_find(head2, net, port, l3mdev, sk);
 372		inet_bind_bucket_for_each(tb, &head->chain)
 373			if (inet_bind_bucket_match(tb, net, port, l3mdev)) {
 374				if (!inet_csk_bind_conflict(sk, tb, tb2,
 375							    relax, false))
 376					goto success;
 377				spin_unlock(&head2->lock);
 378				goto next_port;
 379			}
 380		tb = NULL;
 381		goto success;
 382next_port:
 383		spin_unlock_bh(&head->lock);
 384		cond_resched();
 385	}
 386
 387	offset--;
 388	if (!(offset & 1))
 389		goto other_parity_scan;
 390
 391	if (attempt_half == 1) {
 392		/* OK we now try the upper half of the range */
 393		attempt_half = 2;
 394		goto other_half_scan;
 395	}
 396
 397	if (READ_ONCE(net->ipv4.sysctl_ip_autobind_reuse) && !relax) {
 398		/* We still have a chance to connect to different destinations */
 399		relax = true;
 400		goto ports_exhausted;
 401	}
 402	return NULL;
 403success:
 404	*port_ret = port;
 405	*tb_ret = tb;
 406	*tb2_ret = tb2;
 407	*head2_ret = head2;
 408	return head;
 409}
 410
 411static inline int sk_reuseport_match(struct inet_bind_bucket *tb,
 412				     const struct sock *sk)
 413{
 414	if (tb->fastreuseport <= 0)
 415		return 0;
 416	if (!sk->sk_reuseport)
 417		return 0;
 418	if (rcu_access_pointer(sk->sk_reuseport_cb))
 419		return 0;
 420	if (!uid_eq(tb->fastuid, sk_uid(sk)))
 421		return 0;
 422	/* We only need to check the rcv_saddr if this tb was once marked
 423	 * without fastreuseport and then was reset, as we can only know that
 424	 * the fast_*rcv_saddr doesn't have any conflicts with the socks on the
 425	 * owners list.
 426	 */
 427	if (tb->fastreuseport == FASTREUSEPORT_ANY)
 428		return 1;
 429#if IS_ENABLED(CONFIG_IPV6)
 430	if (tb->fast_sk_family == AF_INET6)
 431		return ipv6_rcv_saddr_equal(&tb->fast_v6_rcv_saddr,
 432					    inet6_rcv_saddr(sk),
 433					    tb->fast_rcv_saddr,
 434					    sk->sk_rcv_saddr,
 435					    tb->fast_ipv6_only,
 436					    ipv6_only_sock(sk), true, false);
 437#endif
 438	return ipv4_rcv_saddr_equal(tb->fast_rcv_saddr, sk->sk_rcv_saddr,
 439				    ipv6_only_sock(sk), true, false);
 440}
 441
 442void inet_csk_update_fastreuse(const struct sock *sk,
 443			       struct inet_bind_bucket *tb,
 444			       struct inet_bind2_bucket *tb2)
 445{
 446	bool reuse = sk->sk_reuse && sk->sk_state != TCP_LISTEN;
 447
 448	if (hlist_empty(&tb->bhash2)) {
 449		tb->fastreuse = reuse;
 450		if (sk->sk_reuseport) {
 451			tb->fastreuseport = FASTREUSEPORT_ANY;
 452			tb->fastuid = sk_uid(sk);
 453			tb->fast_rcv_saddr = sk->sk_rcv_saddr;
 454			tb->fast_ipv6_only = ipv6_only_sock(sk);
 455			tb->fast_sk_family = sk->sk_family;
 456#if IS_ENABLED(CONFIG_IPV6)
 457			tb->fast_v6_rcv_saddr = sk->sk_v6_rcv_saddr;
 458#endif
 459		} else {
 460			tb->fastreuseport = 0;
 461		}
 462	} else {
 463		if (!reuse)
 464			tb->fastreuse = 0;
 465		if (sk->sk_reuseport) {
 466			/* We didn't match or we don't have fastreuseport set on
 467			 * the tb, but we have sk_reuseport set on this socket
 468			 * and we know that there are no bind conflicts with
 469			 * this socket in this tb, so reset our tb's reuseport
 470			 * settings so that any subsequent sockets that match
 471			 * our current socket will be put on the fast path.
 472			 *
 473			 * If we reset we need to set FASTREUSEPORT_STRICT so we
 474			 * do extra checking for all subsequent sk_reuseport
 475			 * socks.
 476			 */
 477			if (!sk_reuseport_match(tb, sk)) {
 478				tb->fastreuseport = FASTREUSEPORT_STRICT;
 479				tb->fastuid = sk_uid(sk);
 480				tb->fast_rcv_saddr = sk->sk_rcv_saddr;
 481				tb->fast_ipv6_only = ipv6_only_sock(sk);
 482				tb->fast_sk_family = sk->sk_family;
 483#if IS_ENABLED(CONFIG_IPV6)
 484				tb->fast_v6_rcv_saddr = sk->sk_v6_rcv_saddr;
 485#endif
 486			}
 487		} else {
 488			tb->fastreuseport = 0;
 489		}
 490	}
 491
 492	tb2->fastreuse = tb->fastreuse;
 493	tb2->fastreuseport = tb->fastreuseport;
 494}
 495
 496/* Obtain a reference to a local port for the given sock,
 497 * if snum is zero it means select any available local port.
 498 * We try to allocate an odd port (and leave even ports for connect())
 499 */
 500int inet_csk_get_port(struct sock *sk, unsigned short snum)
 501{
 502	bool reuse = sk->sk_reuse && sk->sk_state != TCP_LISTEN;
 503	bool found_port = false, check_bind_conflict = true;
 504	bool bhash_created = false, bhash2_created = false;
 505	struct inet_hashinfo *hinfo = tcp_get_hashinfo(sk);
 506	int ret = -EADDRINUSE, port = snum, l3mdev;
 507	struct inet_bind_hashbucket *head, *head2;
 508	struct inet_bind2_bucket *tb2 = NULL;
 509	struct inet_bind_bucket *tb = NULL;
 510	bool head2_lock_acquired = false;
 511	struct net *net = sock_net(sk);
 512
 513	l3mdev = inet_sk_bound_l3mdev(sk);
 514
 515	if (!port) {
 516		head = inet_csk_find_open_port(sk, &tb, &tb2, &head2, &port);
 517		if (!head)
 518			return ret;
 519
 520		head2_lock_acquired = true;
 521
 522		if (tb && tb2)
 523			goto success;
 524		found_port = true;
 525	} else {
 526		head = &hinfo->bhash[inet_bhashfn(net, port,
 527						  hinfo->bhash_size)];
 528		spin_lock_bh(&head->lock);
 529		inet_bind_bucket_for_each(tb, &head->chain)
 530			if (inet_bind_bucket_match(tb, net, port, l3mdev))
 531				break;
 532	}
 533
 534	if (!tb) {
 535		tb = inet_bind_bucket_create(hinfo->bind_bucket_cachep, net,
 536					     head, port, l3mdev);
 537		if (!tb)
 538			goto fail_unlock;
 539		bhash_created = true;
 540	}
 541
 542	if (!found_port) {
 543		if (!hlist_empty(&tb->bhash2)) {
 544			if (sk->sk_reuse == SK_FORCE_REUSE ||
 545			    (tb->fastreuse > 0 && reuse) ||
 546			    sk_reuseport_match(tb, sk))
 547				check_bind_conflict = false;
 548		}
 549
 550		if (check_bind_conflict && inet_use_hash2_on_bind(sk)) {
 551			if (inet_bhash2_addr_any_conflict(sk, port, l3mdev, true, true))
 552				goto fail_unlock;
 553		}
 554
 555		head2 = inet_bhashfn_portaddr(hinfo, sk, net, port);
 556		spin_lock(&head2->lock);
 557		head2_lock_acquired = true;
 558		tb2 = inet_bind2_bucket_find(head2, net, port, l3mdev, sk);
 559	}
 560
 561	if (!tb2) {
 562		tb2 = inet_bind2_bucket_create(hinfo->bind2_bucket_cachep,
 563					       net, head2, tb, sk);
 564		if (!tb2)
 565			goto fail_unlock;
 566		bhash2_created = true;
 567	}
 568
 569	if (!found_port && check_bind_conflict) {
 570		if (inet_csk_bind_conflict(sk, tb, tb2, true, true))
 571			goto fail_unlock;
 572	}
 573
 574success:
 575	inet_csk_update_fastreuse(sk, tb, tb2);
 576
 577	if (!inet_csk(sk)->icsk_bind_hash)
 578		inet_bind_hash(sk, tb, tb2, port);
 579	WARN_ON(inet_csk(sk)->icsk_bind_hash != tb);
 580	WARN_ON(inet_csk(sk)->icsk_bind2_hash != tb2);
 581	ret = 0;
 582
 583fail_unlock:
 584	if (ret) {
 585		if (bhash2_created)
 586			inet_bind2_bucket_destroy(hinfo->bind2_bucket_cachep, tb2);
 587		if (bhash_created)
 588			inet_bind_bucket_destroy(tb);
 589	}
 590	if (head2_lock_acquired)
 591		spin_unlock(&head2->lock);
 592	spin_unlock_bh(&head->lock);
 593	return ret;
 594}
 595EXPORT_SYMBOL_GPL(inet_csk_get_port);
 596
 597/*
 598 * Wait for an incoming connection, avoid race conditions. This must be called
 599 * with the socket locked.
 600 */
 601static int inet_csk_wait_for_connect(struct sock *sk, long timeo)
 602{
 603	struct inet_connection_sock *icsk = inet_csk(sk);
 604	DEFINE_WAIT(wait);
 605	int err;
 606
 607	/*
 608	 * True wake-one mechanism for incoming connections: only
 609	 * one process gets woken up, not the 'whole herd'.
 610	 * Since we do not 'race & poll' for established sockets
 611	 * anymore, the common case will execute the loop only once.
 612	 *
 613	 * Subtle issue: "add_wait_queue_exclusive()" will be added
 614	 * after any current non-exclusive waiters, and we know that
 615	 * it will always _stay_ after any new non-exclusive waiters
 616	 * because all non-exclusive waiters are added at the
 617	 * beginning of the wait-queue. As such, it's ok to "drop"
 618	 * our exclusiveness temporarily when we get woken up without
 619	 * having to remove and re-insert us on the wait queue.
 620	 */
 621	for (;;) {
 622		prepare_to_wait_exclusive(sk_sleep(sk), &wait,
 623					  TASK_INTERRUPTIBLE);
 624		release_sock(sk);
 625		if (reqsk_queue_empty(&icsk->icsk_accept_queue))
 626			timeo = schedule_timeout(timeo);
 627		sched_annotate_sleep();
 628		lock_sock(sk);
 629		err = 0;
 630		if (!reqsk_queue_empty(&icsk->icsk_accept_queue))
 631			break;
 632		err = -EINVAL;
 633		if (sk->sk_state != TCP_LISTEN)
 634			break;
 635		err = sock_intr_errno(timeo);
 636		if (signal_pending(current))
 637			break;
 638		err = -EAGAIN;
 639		if (!timeo)
 640			break;
 641	}
 642	finish_wait(sk_sleep(sk), &wait);
 643	return err;
 644}
 645
 646/*
 647 * This will accept the next outstanding connection.
 648 */
 649struct sock *inet_csk_accept(struct sock *sk, struct proto_accept_arg *arg)
 650{
 651	struct inet_connection_sock *icsk = inet_csk(sk);
 652	struct request_sock_queue *queue = &icsk->icsk_accept_queue;
 653	struct request_sock *req;
 654	struct sock *newsk;
 655	int error;
 656
 657	lock_sock(sk);
 658
 659	/* We need to make sure that this socket is listening,
 660	 * and that it has something pending.
 661	 */
 662	error = -EINVAL;
 663	if (sk->sk_state != TCP_LISTEN)
 664		goto out_err;
 665
 666	/* Find already established connection */
 667	if (reqsk_queue_empty(queue)) {
 668		long timeo = sock_rcvtimeo(sk, arg->flags & O_NONBLOCK);
 669
 670		/* If this is a non blocking socket don't sleep */
 671		error = -EAGAIN;
 672		if (!timeo)
 673			goto out_err;
 674
 675		error = inet_csk_wait_for_connect(sk, timeo);
 676		if (error)
 677			goto out_err;
 678	}
 679	req = reqsk_queue_remove(queue, sk);
 680	arg->is_empty = reqsk_queue_empty(queue);
 681	newsk = req->sk;
 682
 683	if (sk->sk_protocol == IPPROTO_TCP &&
 684	    tcp_rsk(req)->tfo_listener) {
 685		spin_lock_bh(&queue->fastopenq.lock);
 686		if (tcp_rsk(req)->tfo_listener) {
 687			/* We are still waiting for the final ACK from 3WHS
 688			 * so can't free req now. Instead, we set req->sk to
 689			 * NULL to signify that the child socket is taken
 690			 * so reqsk_fastopen_remove() will free the req
 691			 * when 3WHS finishes (or is aborted).
 692			 */
 693			req->sk = NULL;
 694			req = NULL;
 695		}
 696		spin_unlock_bh(&queue->fastopenq.lock);
 697	}
 698
 699	release_sock(sk);
 700
 701	if (req)
 702		reqsk_put(req);
 703
 704	inet_init_csk_locks(newsk);
 705	return newsk;
 706
 707out_err:
 708	release_sock(sk);
 709	arg->err = error;
 710	return NULL;
 711}
 712EXPORT_SYMBOL(inet_csk_accept);
 713
 714/*
 715 * Using different timers for retransmit, delayed acks and probes
 716 * We may wish use just one timer maintaining a list of expire jiffies
 717 * to optimize.
 718 */
 719void inet_csk_init_xmit_timers(struct sock *sk,
 720			       void (*retransmit_handler)(struct timer_list *t),
 721			       void (*delack_handler)(struct timer_list *t),
 722			       void (*keepalive_handler)(struct timer_list *t))
 723{
 724	struct inet_connection_sock *icsk = inet_csk(sk);
 725
 726	timer_setup(&sk->tcp_retransmit_timer, retransmit_handler, 0);
 727	timer_setup(&icsk->icsk_delack_timer, delack_handler, 0);
 728	timer_setup(&icsk->icsk_keepalive_timer, keepalive_handler, 0);
 729	icsk->icsk_pending = icsk->icsk_ack.pending = 0;
 730}
 731
 732void inet_csk_clear_xmit_timers(struct sock *sk)
 733{
 734	struct inet_connection_sock *icsk = inet_csk(sk);
 735
 736	smp_store_release(&icsk->icsk_pending, 0);
 737	smp_store_release(&icsk->icsk_ack.pending, 0);
 738
 739	sk_stop_timer(sk, &sk->tcp_retransmit_timer);
 740	sk_stop_timer(sk, &icsk->icsk_delack_timer);
 741	sk_stop_timer(sk, &icsk->icsk_keepalive_timer);
 742}
 743
 744void inet_csk_clear_xmit_timers_sync(struct sock *sk)
 745{
 746	struct inet_connection_sock *icsk = inet_csk(sk);
 747
 748	/* ongoing timer handlers need to acquire socket lock. */
 749	sock_not_owned_by_me(sk);
 750
 751	smp_store_release(&icsk->icsk_pending, 0);
 752	smp_store_release(&icsk->icsk_ack.pending, 0);
 753
 754	sk_stop_timer_sync(sk, &sk->tcp_retransmit_timer);
 755	sk_stop_timer_sync(sk, &icsk->icsk_delack_timer);
 756	sk_stop_timer_sync(sk, &icsk->icsk_keepalive_timer);
 757}
 758
 759struct dst_entry *inet_csk_route_req(const struct sock *sk,
 760				     struct flowi4 *fl4,
 761				     const struct request_sock *req)
 762{
 763	const struct inet_request_sock *ireq = inet_rsk(req);
 764	struct net *net = read_pnet(&ireq->ireq_net);
 765	struct ip_options_rcu *opt;
 766	struct rtable *rt;
 767
 768	rcu_read_lock();
 769	opt = rcu_dereference(ireq->ireq_opt);
 770
 771	flowi4_init_output(fl4, ireq->ir_iif, ireq->ir_mark,
 772			   ip_sock_rt_tos(sk), ip_sock_rt_scope(sk),
 773			   sk->sk_protocol, inet_sk_flowi_flags(sk),
 774			   (opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr,
 775			   ireq->ir_loc_addr, ireq->ir_rmt_port,
 776			   htons(ireq->ir_num), sk_uid(sk));
 777	security_req_classify_flow(req, flowi4_to_flowi_common(fl4));
 778	rt = ip_route_output_flow(net, fl4, sk);
 779	if (IS_ERR(rt))
 780		goto no_route;
 781	if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway)
 782		goto route_err;
 783	rcu_read_unlock();
 784	return &rt->dst;
 785
 786route_err:
 787	ip_rt_put(rt);
 788no_route:
 789	rcu_read_unlock();
 790	__IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
 791	return NULL;
 792}
 793
 794struct dst_entry *inet_csk_route_child_sock(const struct sock *sk,
 795					    struct sock *newsk,
 796					    const struct request_sock *req)
 797{
 798	const struct inet_request_sock *ireq = inet_rsk(req);
 799	struct net *net = read_pnet(&ireq->ireq_net);
 800	struct inet_sock *newinet = inet_sk(newsk);
 801	struct ip_options_rcu *opt;
 802	struct flowi4 *fl4;
 803	struct rtable *rt;
 804
 805	opt = rcu_dereference(ireq->ireq_opt);
 806	fl4 = &newinet->cork.fl.u.ip4;
 807
 808	flowi4_init_output(fl4, ireq->ir_iif, ireq->ir_mark,
 809			   ip_sock_rt_tos(sk), ip_sock_rt_scope(sk),
 810			   sk->sk_protocol, inet_sk_flowi_flags(sk),
 811			   (opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr,
 812			   ireq->ir_loc_addr, ireq->ir_rmt_port,
 813			   htons(ireq->ir_num), sk_uid(sk));
 814	security_req_classify_flow(req, flowi4_to_flowi_common(fl4));
 815	rt = ip_route_output_flow(net, fl4, sk);
 816	if (IS_ERR(rt))
 817		goto no_route;
 818	if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway)
 819		goto route_err;
 820	return &rt->dst;
 821
 822route_err:
 823	ip_rt_put(rt);
 824no_route:
 825	__IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
 826	return NULL;
 827}
 828EXPORT_SYMBOL_GPL(inet_csk_route_child_sock);
 829
 830/* Decide when to expire the request and when to resend SYN-ACK */
 831static void syn_ack_recalc(struct request_sock *req,
 832			   const int max_syn_ack_retries,
 833			   const u8 rskq_defer_accept,
 834			   int *expire, int *resend)
 835{
 836	if (!rskq_defer_accept) {
 837		*expire = req->num_timeout >= max_syn_ack_retries;
 838		*resend = 1;
 839		return;
 840	}
 841	*expire = req->num_timeout >= max_syn_ack_retries &&
 842		  (!inet_rsk(req)->acked || req->num_timeout >= rskq_defer_accept);
 843	/* Do not resend while waiting for data after ACK,
 844	 * start to resend on end of deferring period to give
 845	 * last chance for data or ACK to create established socket.
 846	 */
 847	*resend = !inet_rsk(req)->acked ||
 848		  req->num_timeout >= rskq_defer_accept - 1;
 849}
 850
 851static struct request_sock *
 852reqsk_alloc_noprof(const struct request_sock_ops *ops, struct sock *sk_listener,
 853		   bool attach_listener)
 854{
 855	struct request_sock *req;
 856
 857	req = kmem_cache_alloc_noprof(ops->slab, GFP_ATOMIC | __GFP_NOWARN);
 858	if (!req)
 859		return NULL;
 860	req->rsk_listener = NULL;
 861	if (attach_listener) {
 862		if (unlikely(!refcount_inc_not_zero(&sk_listener->sk_refcnt))) {
 863			kmem_cache_free(ops->slab, req);
 864			return NULL;
 865		}
 866		req->rsk_listener = sk_listener;
 867	}
 868	req->rsk_ops = ops;
 869	req_to_sk(req)->sk_prot = sk_listener->sk_prot;
 870	sk_node_init(&req_to_sk(req)->sk_node);
 871	sk_tx_queue_clear(req_to_sk(req));
 872	req->saved_syn = NULL;
 873	req->syncookie = 0;
 874	req->num_timeout = 0;
 875	req->num_retrans = 0;
 876	req->sk = NULL;
 877	refcount_set(&req->rsk_refcnt, 0);
 878
 879	return req;
 880}
 881#define reqsk_alloc(...)	alloc_hooks(reqsk_alloc_noprof(__VA_ARGS__))
 882
 883struct request_sock *inet_reqsk_alloc(const struct request_sock_ops *ops,
 884				      struct sock *sk_listener,
 885				      bool attach_listener)
 886{
 887	struct request_sock *req = reqsk_alloc(ops, sk_listener,
 888					       attach_listener);
 889
 890	if (req) {
 891		struct inet_request_sock *ireq = inet_rsk(req);
 892
 893		ireq->ireq_opt = NULL;
 894#if IS_ENABLED(CONFIG_IPV6)
 895		ireq->pktopts = NULL;
 896#endif
 897		atomic64_set(&ireq->ir_cookie, 0);
 898		ireq->ireq_state = TCP_NEW_SYN_RECV;
 899		write_pnet(&ireq->ireq_net, sock_net(sk_listener));
 900		ireq->ireq_family = sk_listener->sk_family;
 901	}
 902
 903	return req;
 904}
 905EXPORT_SYMBOL(inet_reqsk_alloc);
 906
 907static struct request_sock *inet_reqsk_clone(struct request_sock *req,
 908					     struct sock *sk)
 909{
 910	struct sock *req_sk, *nreq_sk;
 911	struct request_sock *nreq;
 912
 913	nreq = kmem_cache_alloc(req->rsk_ops->slab, GFP_ATOMIC | __GFP_NOWARN);
 914	if (!nreq) {
 915		__NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMIGRATEREQFAILURE);
 916
 917		/* paired with refcount_inc_not_zero() in reuseport_migrate_sock() */
 918		sock_put(sk);
 919		return NULL;
 920	}
 921
 922	req_sk = req_to_sk(req);
 923	nreq_sk = req_to_sk(nreq);
 924
 925	memcpy(nreq_sk, req_sk,
 926	       offsetof(struct sock, sk_dontcopy_begin));
 927	unsafe_memcpy(&nreq_sk->sk_dontcopy_end, &req_sk->sk_dontcopy_end,
 928		      req->rsk_ops->obj_size - offsetof(struct sock, sk_dontcopy_end),
 929		      /* alloc is larger than struct, see above */);
 930
 931	sk_node_init(&nreq_sk->sk_node);
 932	nreq_sk->sk_tx_queue_mapping = req_sk->sk_tx_queue_mapping;
 933#ifdef CONFIG_SOCK_RX_QUEUE_MAPPING
 934	nreq_sk->sk_rx_queue_mapping = req_sk->sk_rx_queue_mapping;
 935#endif
 936	nreq_sk->sk_incoming_cpu = req_sk->sk_incoming_cpu;
 937
 938	nreq->rsk_listener = sk;
 939
 940	/* We need not acquire fastopenq->lock
 941	 * because the child socket is locked in inet_csk_listen_stop().
 942	 */
 943	if (sk->sk_protocol == IPPROTO_TCP && tcp_rsk(nreq)->tfo_listener)
 944		rcu_assign_pointer(tcp_sk(nreq->sk)->fastopen_rsk, nreq);
 945
 946	return nreq;
 947}
 948
 949static void reqsk_queue_migrated(struct request_sock_queue *queue,
 950				 const struct request_sock *req)
 951{
 952	if (req->num_timeout == 0)
 953		atomic_inc(&queue->young);
 954	atomic_inc(&queue->qlen);
 955}
 956
 957static void reqsk_migrate_reset(struct request_sock *req)
 958{
 959	req->saved_syn = NULL;
 960#if IS_ENABLED(CONFIG_IPV6)
 961	inet_rsk(req)->ipv6_opt = NULL;
 962	inet_rsk(req)->pktopts = NULL;
 963#else
 964	inet_rsk(req)->ireq_opt = NULL;
 965#endif
 966}
 967
 968/* return true if req was found in the ehash table */
 969static bool reqsk_queue_unlink(struct request_sock *req)
 970{
 971	struct sock *sk = req_to_sk(req);
 972	bool found = false;
 973
 974	if (sk_hashed(sk)) {
 975		struct inet_hashinfo *hashinfo = tcp_get_hashinfo(sk);
 976		spinlock_t *lock;
 977
 978		lock = inet_ehash_lockp(hashinfo, req->rsk_hash);
 979		spin_lock(lock);
 980		found = __sk_nulls_del_node_init_rcu(sk);
 981		spin_unlock(lock);
 982	}
 983
 984	return found;
 985}
 986
 987static bool __inet_csk_reqsk_queue_drop(struct sock *sk,
 988					struct request_sock *req,
 989					bool from_timer)
 990{
 991	bool unlinked = reqsk_queue_unlink(req);
 992
 993	if (!from_timer && timer_delete_sync(&req->rsk_timer))
 994		reqsk_put(req);
 995
 996	if (unlinked) {
 997		reqsk_queue_removed(&inet_csk(sk)->icsk_accept_queue, req);
 998		reqsk_put(req);
 999	}
1000
1001	return unlinked;
1002}
1003
1004bool inet_csk_reqsk_queue_drop(struct sock *sk, struct request_sock *req)
1005{
1006	return __inet_csk_reqsk_queue_drop(sk, req, false);
1007}
1008
1009void inet_csk_reqsk_queue_drop_and_put(struct sock *sk, struct request_sock *req)
1010{
1011	inet_csk_reqsk_queue_drop(sk, req);
1012	reqsk_put(req);
1013}
1014EXPORT_IPV6_MOD(inet_csk_reqsk_queue_drop_and_put);
1015
1016static void reqsk_timer_handler(struct timer_list *t)
1017{
1018	struct request_sock *req = timer_container_of(req, t, rsk_timer);
1019	struct request_sock *nreq = NULL, *oreq = req;
1020	struct sock *sk_listener = req->rsk_listener;
1021	struct inet_connection_sock *icsk;
1022	struct request_sock_queue *queue;
1023	struct net *net;
1024	int max_syn_ack_retries, qlen, expire = 0, resend = 0;
1025
1026	if (inet_sk_state_load(sk_listener) != TCP_LISTEN) {
1027		struct sock *nsk;
1028
1029		nsk = reuseport_migrate_sock(sk_listener, req_to_sk(req), NULL);
1030		if (!nsk)
1031			goto drop;
1032
1033		nreq = inet_reqsk_clone(req, nsk);
1034		if (!nreq)
1035			goto drop;
1036
1037		/* The new timer for the cloned req can decrease the 2
1038		 * by calling inet_csk_reqsk_queue_drop_and_put(), so
1039		 * hold another count to prevent use-after-free and
1040		 * call reqsk_put() just before return.
1041		 */
1042		refcount_set(&nreq->rsk_refcnt, 2 + 1);
1043		timer_setup(&nreq->rsk_timer, reqsk_timer_handler, TIMER_PINNED);
1044		reqsk_queue_migrated(&inet_csk(nsk)->icsk_accept_queue, req);
1045
1046		req = nreq;
1047		sk_listener = nsk;
1048	}
1049
1050	icsk = inet_csk(sk_listener);
1051	net = sock_net(sk_listener);
1052	max_syn_ack_retries = READ_ONCE(icsk->icsk_syn_retries) ? :
1053		READ_ONCE(net->ipv4.sysctl_tcp_synack_retries);
1054	/* Normally all the openreqs are young and become mature
1055	 * (i.e. converted to established socket) for first timeout.
1056	 * If synack was not acknowledged for 1 second, it means
1057	 * one of the following things: synack was lost, ack was lost,
1058	 * rtt is high or nobody planned to ack (i.e. synflood).
1059	 * When server is a bit loaded, queue is populated with old
1060	 * open requests, reducing effective size of queue.
1061	 * When server is well loaded, queue size reduces to zero
1062	 * after several minutes of work. It is not synflood,
1063	 * it is normal operation. The solution is pruning
1064	 * too old entries overriding normal timeout, when
1065	 * situation becomes dangerous.
1066	 *
1067	 * Essentially, we reserve half of room for young
1068	 * embrions; and abort old ones without pity, if old
1069	 * ones are about to clog our table.
1070	 */
1071	queue = &icsk->icsk_accept_queue;
1072	qlen = reqsk_queue_len(queue);
1073	if ((qlen << 1) > max(8U, READ_ONCE(sk_listener->sk_max_ack_backlog))) {
1074		int young = reqsk_queue_len_young(queue) << 1;
1075
1076		while (max_syn_ack_retries > 2) {
1077			if (qlen < young)
1078				break;
1079			max_syn_ack_retries--;
1080			young <<= 1;
1081		}
1082	}
1083
1084	syn_ack_recalc(req, max_syn_ack_retries, READ_ONCE(queue->rskq_defer_accept),
1085		       &expire, &resend);
1086	tcp_syn_ack_timeout(req);
1087
1088	if (!expire &&
1089	    (!resend ||
1090	     !tcp_rtx_synack(sk_listener, req) ||
1091	     inet_rsk(req)->acked)) {
1092		if (req->num_timeout++ == 0)
1093			atomic_dec(&queue->young);
1094		mod_timer(&req->rsk_timer, jiffies + tcp_reqsk_timeout(req));
1095
1096		if (!nreq)
1097			return;
1098
1099		if (!inet_ehash_insert(req_to_sk(nreq), req_to_sk(oreq), NULL)) {
1100			/* delete timer */
1101			__inet_csk_reqsk_queue_drop(sk_listener, nreq, true);
1102			goto no_ownership;
1103		}
1104
1105		__NET_INC_STATS(net, LINUX_MIB_TCPMIGRATEREQSUCCESS);
1106		reqsk_migrate_reset(oreq);
1107		reqsk_queue_removed(&inet_csk(oreq->rsk_listener)->icsk_accept_queue, oreq);
1108		reqsk_put(oreq);
1109
1110		reqsk_put(nreq);
1111		return;
1112	}
1113
1114	/* Even if we can clone the req, we may need not retransmit any more
1115	 * SYN+ACKs (nreq->num_timeout > max_syn_ack_retries, etc), or another
1116	 * CPU may win the "own_req" race so that inet_ehash_insert() fails.
1117	 */
1118	if (nreq) {
1119		__NET_INC_STATS(net, LINUX_MIB_TCPMIGRATEREQFAILURE);
1120no_ownership:
1121		reqsk_migrate_reset(nreq);
1122		reqsk_queue_removed(queue, nreq);
1123		__reqsk_free(nreq);
1124	}
1125
1126drop:
1127	__inet_csk_reqsk_queue_drop(sk_listener, oreq, true);
1128	reqsk_put(oreq);
1129}
1130
1131static bool reqsk_queue_hash_req(struct request_sock *req)
1132{
1133	bool found_dup_sk = false;
1134
1135	if (!inet_ehash_insert(req_to_sk(req), NULL, &found_dup_sk))
1136		return false;
1137
1138	/* The timer needs to be setup after a successful insertion. */
1139	req->timeout = tcp_timeout_init((struct sock *)req);
1140	timer_setup(&req->rsk_timer, reqsk_timer_handler, TIMER_PINNED);
1141	mod_timer(&req->rsk_timer, jiffies + req->timeout);
1142
1143	/* before letting lookups find us, make sure all req fields
1144	 * are committed to memory and refcnt initialized.
1145	 */
1146	smp_wmb();
1147	refcount_set(&req->rsk_refcnt, 2 + 1);
1148	return true;
1149}
1150
1151bool inet_csk_reqsk_queue_hash_add(struct sock *sk, struct request_sock *req)
1152{
1153	if (!reqsk_queue_hash_req(req))
1154		return false;
1155
1156	inet_csk_reqsk_queue_added(sk);
1157	return true;
1158}
1159
1160static void inet_clone_ulp(const struct request_sock *req, struct sock *newsk,
1161			   const gfp_t priority)
1162{
1163	struct inet_connection_sock *icsk = inet_csk(newsk);
1164
1165	if (!icsk->icsk_ulp_ops)
1166		return;
1167
1168	icsk->icsk_ulp_ops->clone(req, newsk, priority);
1169}
1170
1171/**
1172 *	inet_csk_clone_lock - clone an inet socket, and lock its clone
1173 *	@sk: the socket to clone
1174 *	@req: request_sock
1175 *	@priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
1176 *
1177 *	Caller must unlock socket even in error path (bh_unlock_sock(newsk))
1178 */
1179struct sock *inet_csk_clone_lock(const struct sock *sk,
1180				 const struct request_sock *req,
1181				 const gfp_t priority)
1182{
1183	struct sock *newsk = sk_clone_lock(sk, priority);
1184	struct inet_connection_sock *newicsk;
1185	struct inet_request_sock *ireq;
1186	struct inet_sock *newinet;
1187
1188	if (!newsk)
1189		return NULL;
1190
1191	newicsk = inet_csk(newsk);
1192	newinet = inet_sk(newsk);
1193	ireq = inet_rsk(req);
1194
1195	newicsk->icsk_bind_hash = NULL;
1196	newicsk->icsk_bind2_hash = NULL;
1197
1198	newinet->inet_dport = ireq->ir_rmt_port;
1199	newinet->inet_num = ireq->ir_num;
1200	newinet->inet_sport = htons(ireq->ir_num);
1201
1202	newsk->sk_bound_dev_if = ireq->ir_iif;
1203
1204	newsk->sk_daddr = ireq->ir_rmt_addr;
1205	newsk->sk_rcv_saddr = ireq->ir_loc_addr;
1206	newinet->inet_saddr = ireq->ir_loc_addr;
1207
1208#if IS_ENABLED(CONFIG_IPV6)
1209	newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr;
1210	newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr;
1211#endif
1212
1213	/* listeners have SOCK_RCU_FREE, not the children */
1214	sock_reset_flag(newsk, SOCK_RCU_FREE);
1215
1216	inet_sk(newsk)->mc_list = NULL;
1217
1218	newsk->sk_mark = inet_rsk(req)->ir_mark;
1219	atomic64_set(&newsk->sk_cookie,
1220		     atomic64_read(&inet_rsk(req)->ir_cookie));
1221
1222	newicsk->icsk_retransmits = 0;
1223	newicsk->icsk_backoff	  = 0;
1224	newicsk->icsk_probes_out  = 0;
1225	newicsk->icsk_probes_tstamp = 0;
1226
1227	/* Deinitialize accept_queue to trap illegal accesses. */
1228	memset(&newicsk->icsk_accept_queue, 0,
1229	       sizeof(newicsk->icsk_accept_queue));
1230
1231	inet_sk_set_state(newsk, TCP_SYN_RECV);
1232
1233	inet_clone_ulp(req, newsk, priority);
1234
1235	security_inet_csk_clone(newsk, req);
1236
1237	return newsk;
1238}
1239
1240/*
1241 * At this point, there should be no process reference to this
1242 * socket, and thus no user references at all.  Therefore we
1243 * can assume the socket waitqueue is inactive and nobody will
1244 * try to jump onto it.
1245 */
1246void inet_csk_destroy_sock(struct sock *sk)
1247{
1248	WARN_ON(sk->sk_state != TCP_CLOSE);
1249	WARN_ON(!sock_flag(sk, SOCK_DEAD));
1250
1251	/* It cannot be in hash table! */
1252	WARN_ON(!sk_unhashed(sk));
1253
1254	/* If it has not 0 inet_sk(sk)->inet_num, it must be bound */
1255	WARN_ON(inet_sk(sk)->inet_num && !inet_csk(sk)->icsk_bind_hash);
1256
1257	sk->sk_prot->destroy(sk);
1258
1259	sk_stream_kill_queues(sk);
1260
1261	xfrm_sk_free_policy(sk);
1262
1263	tcp_orphan_count_dec();
1264
1265	sock_put(sk);
1266}
1267EXPORT_SYMBOL(inet_csk_destroy_sock);
1268
1269void inet_csk_prepare_for_destroy_sock(struct sock *sk)
1270{
1271	/* The below has to be done to allow calling inet_csk_destroy_sock */
1272	sock_set_flag(sk, SOCK_DEAD);
1273	tcp_orphan_count_inc();
1274}
1275
1276/* This function allows to force a closure of a socket after the call to
1277 * tcp_create_openreq_child().
1278 */
1279void inet_csk_prepare_forced_close(struct sock *sk)
1280	__releases(&sk->sk_lock.slock)
1281{
1282	/* sk_clone_lock locked the socket and set refcnt to 2 */
1283	bh_unlock_sock(sk);
1284	sock_put(sk);
1285	inet_csk_prepare_for_destroy_sock(sk);
1286	inet_sk(sk)->inet_num = 0;
1287}
1288EXPORT_SYMBOL(inet_csk_prepare_forced_close);
1289
1290static int inet_ulp_can_listen(const struct sock *sk)
1291{
1292	const struct inet_connection_sock *icsk = inet_csk(sk);
1293
1294	if (icsk->icsk_ulp_ops && !icsk->icsk_ulp_ops->clone)
1295		return -EINVAL;
1296
1297	return 0;
1298}
1299
1300int inet_csk_listen_start(struct sock *sk)
1301{
1302	struct inet_connection_sock *icsk = inet_csk(sk);
1303	struct inet_sock *inet = inet_sk(sk);
1304	int err;
1305
1306	err = inet_ulp_can_listen(sk);
1307	if (unlikely(err))
1308		return err;
1309
1310	reqsk_queue_alloc(&icsk->icsk_accept_queue);
1311
1312	sk->sk_ack_backlog = 0;
1313	inet_csk_delack_init(sk);
1314
1315	/* There is race window here: we announce ourselves listening,
1316	 * but this transition is still not validated by get_port().
1317	 * It is OK, because this socket enters to hash table only
1318	 * after validation is complete.
1319	 */
1320	inet_sk_state_store(sk, TCP_LISTEN);
1321	err = sk->sk_prot->get_port(sk, inet->inet_num);
1322	if (!err) {
1323		inet->inet_sport = htons(inet->inet_num);
1324
1325		sk_dst_reset(sk);
1326		err = sk->sk_prot->hash(sk);
1327
1328		if (likely(!err))
1329			return 0;
1330	}
1331
1332	inet_sk_set_state(sk, TCP_CLOSE);
1333	return err;
1334}
1335
1336static void inet_child_forget(struct sock *sk, struct request_sock *req,
1337			      struct sock *child)
1338{
1339	sk->sk_prot->disconnect(child, O_NONBLOCK);
1340
1341	sock_orphan(child);
1342
1343	tcp_orphan_count_inc();
1344
1345	if (sk->sk_protocol == IPPROTO_TCP && tcp_rsk(req)->tfo_listener) {
1346		BUG_ON(rcu_access_pointer(tcp_sk(child)->fastopen_rsk) != req);
1347		BUG_ON(sk != req->rsk_listener);
1348
1349		/* Paranoid, to prevent race condition if
1350		 * an inbound pkt destined for child is
1351		 * blocked by sock lock in tcp_v4_rcv().
1352		 * Also to satisfy an assertion in
1353		 * tcp_v4_destroy_sock().
1354		 */
1355		RCU_INIT_POINTER(tcp_sk(child)->fastopen_rsk, NULL);
1356	}
1357	inet_csk_destroy_sock(child);
1358}
1359
1360struct sock *inet_csk_reqsk_queue_add(struct sock *sk,
1361				      struct request_sock *req,
1362				      struct sock *child)
1363{
1364	struct request_sock_queue *queue = &inet_csk(sk)->icsk_accept_queue;
1365
1366	spin_lock(&queue->rskq_lock);
1367	if (unlikely(sk->sk_state != TCP_LISTEN)) {
1368		inet_child_forget(sk, req, child);
1369		child = NULL;
1370	} else {
1371		req->sk = child;
1372		req->dl_next = NULL;
1373		if (queue->rskq_accept_head == NULL)
1374			WRITE_ONCE(queue->rskq_accept_head, req);
1375		else
1376			queue->rskq_accept_tail->dl_next = req;
1377		queue->rskq_accept_tail = req;
1378		sk_acceptq_added(sk);
1379	}
1380	spin_unlock(&queue->rskq_lock);
1381	return child;
1382}
1383EXPORT_SYMBOL(inet_csk_reqsk_queue_add);
1384
1385struct sock *inet_csk_complete_hashdance(struct sock *sk, struct sock *child,
1386					 struct request_sock *req, bool own_req)
1387{
1388	if (own_req) {
1389		inet_csk_reqsk_queue_drop(req->rsk_listener, req);
1390		reqsk_queue_removed(&inet_csk(req->rsk_listener)->icsk_accept_queue, req);
1391
1392		if (sk != req->rsk_listener) {
1393			/* another listening sk has been selected,
1394			 * migrate the req to it.
1395			 */
1396			struct request_sock *nreq;
1397
1398			/* hold a refcnt for the nreq->rsk_listener
1399			 * which is assigned in inet_reqsk_clone()
1400			 */
1401			sock_hold(sk);
1402			nreq = inet_reqsk_clone(req, sk);
1403			if (!nreq) {
1404				inet_child_forget(sk, req, child);
1405				goto child_put;
1406			}
1407
1408			refcount_set(&nreq->rsk_refcnt, 1);
1409			if (inet_csk_reqsk_queue_add(sk, nreq, child)) {
1410				__NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMIGRATEREQSUCCESS);
1411				reqsk_migrate_reset(req);
1412				reqsk_put(req);
1413				return child;
1414			}
1415
1416			__NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMIGRATEREQFAILURE);
1417			reqsk_migrate_reset(nreq);
1418			__reqsk_free(nreq);
1419		} else if (inet_csk_reqsk_queue_add(sk, req, child)) {
1420			return child;
1421		}
1422	}
1423	/* Too bad, another child took ownership of the request, undo. */
1424child_put:
1425	bh_unlock_sock(child);
1426	sock_put(child);
1427	return NULL;
1428}
1429
1430/*
1431 *	This routine closes sockets which have been at least partially
1432 *	opened, but not yet accepted.
1433 */
1434void inet_csk_listen_stop(struct sock *sk)
1435{
1436	struct inet_connection_sock *icsk = inet_csk(sk);
1437	struct request_sock_queue *queue = &icsk->icsk_accept_queue;
1438	struct request_sock *next, *req;
1439
1440	/* Following specs, it would be better either to send FIN
1441	 * (and enter FIN-WAIT-1, it is normal close)
1442	 * or to send active reset (abort).
1443	 * Certainly, it is pretty dangerous while synflood, but it is
1444	 * bad justification for our negligence 8)
1445	 * To be honest, we are not able to make either
1446	 * of the variants now.			--ANK
1447	 */
1448	while ((req = reqsk_queue_remove(queue, sk)) != NULL) {
1449		struct sock *child = req->sk, *nsk;
1450		struct request_sock *nreq;
1451
1452		local_bh_disable();
1453		bh_lock_sock(child);
1454		WARN_ON(sock_owned_by_user(child));
1455		sock_hold(child);
1456
1457		nsk = reuseport_migrate_sock(sk, child, NULL);
1458		if (nsk) {
1459			nreq = inet_reqsk_clone(req, nsk);
1460			if (nreq) {
1461				refcount_set(&nreq->rsk_refcnt, 1);
1462
1463				if (inet_csk_reqsk_queue_add(nsk, nreq, child)) {
1464					__NET_INC_STATS(sock_net(nsk),
1465							LINUX_MIB_TCPMIGRATEREQSUCCESS);
1466					reqsk_migrate_reset(req);
1467				} else {
1468					__NET_INC_STATS(sock_net(nsk),
1469							LINUX_MIB_TCPMIGRATEREQFAILURE);
1470					reqsk_migrate_reset(nreq);
1471					__reqsk_free(nreq);
1472				}
1473
1474				/* inet_csk_reqsk_queue_add() has already
1475				 * called inet_child_forget() on failure case.
1476				 */
1477				goto skip_child_forget;
1478			}
1479		}
1480
1481		inet_child_forget(sk, req, child);
1482skip_child_forget:
1483		reqsk_put(req);
1484		bh_unlock_sock(child);
1485		local_bh_enable();
1486		sock_put(child);
1487
1488		cond_resched();
1489	}
1490	if (queue->fastopenq.rskq_rst_head) {
1491		/* Free all the reqs queued in rskq_rst_head. */
1492		spin_lock_bh(&queue->fastopenq.lock);
1493		req = queue->fastopenq.rskq_rst_head;
1494		queue->fastopenq.rskq_rst_head = NULL;
1495		spin_unlock_bh(&queue->fastopenq.lock);
1496		while (req != NULL) {
1497			next = req->dl_next;
1498			reqsk_put(req);
1499			req = next;
1500		}
1501	}
1502	WARN_ON_ONCE(sk->sk_ack_backlog);
1503}
1504EXPORT_SYMBOL_GPL(inet_csk_listen_stop);
1505
1506static struct dst_entry *inet_csk_rebuild_route(struct sock *sk, struct flowi *fl)
1507{
1508	const struct inet_sock *inet = inet_sk(sk);
1509	struct flowi4 *fl4;
1510	struct rtable *rt;
1511
1512	rcu_read_lock();
1513	fl4 = &fl->u.ip4;
1514	inet_sk_init_flowi4(inet, fl4);
1515	rt = ip_route_output_flow(sock_net(sk), fl4, sk);
1516	if (IS_ERR(rt))
1517		rt = NULL;
1518	if (rt)
1519		sk_setup_caps(sk, &rt->dst);
1520	rcu_read_unlock();
1521
1522	return &rt->dst;
1523}
1524
1525struct dst_entry *inet_csk_update_pmtu(struct sock *sk, u32 mtu)
1526{
1527	struct dst_entry *dst = __sk_dst_check(sk, 0);
1528	struct inet_sock *inet = inet_sk(sk);
1529
1530	if (!dst) {
1531		dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
1532		if (!dst)
1533			goto out;
1534	}
1535	dst->ops->update_pmtu(dst, sk, NULL, mtu, true);
1536
1537	dst = __sk_dst_check(sk, 0);
1538	if (!dst)
1539		dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
1540out:
1541	return dst;
1542}
~/ Read-only file preview.