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