xref: /linux/net/ipv4/inet_hashtables.c (revision 889dd44491b37c890b1b4ef40876cf19032ca897)
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  *		Generic INET transport hashtables
8  *
9  * Authors:	Lotsa people, from code originally in tcp
10  */
11 
12 #include <linux/module.h>
13 #include <linux/random.h>
14 #include <linux/sched.h>
15 #include <linux/slab.h>
16 #include <linux/wait.h>
17 #include <linux/vmalloc.h>
18 #include <linux/memblock.h>
19 #include <linux/gcd.h>
20 
21 #include <net/addrconf.h>
22 #include <net/inet_connection_sock.h>
23 #include <net/inet_hashtables.h>
24 #if IS_ENABLED(CONFIG_IPV6)
25 #include <net/inet6_hashtables.h>
26 #endif
27 #include <net/hotdata.h>
28 #include <net/ip.h>
29 #include <net/rps.h>
30 #include <net/secure_seq.h>
31 #include <net/sock_reuseport.h>
32 #include <net/tcp.h>
33 
34 static void inet_init_ehash_secret(void)
35 {
36 	net_get_random_sleepable_once(&inet_ehash_secret,
37 				      sizeof(inet_ehash_secret));
38 }
39 
40 u32 inet_ehashfn(const struct net *net, const __be32 laddr,
41 		 const __u16 lport, const __be32 faddr,
42 		 const __be16 fport)
43 {
44 	return lport + __inet_ehashfn(laddr, 0, faddr, fport,
45 				      inet_ehash_secret + net_hash_mix(net));
46 }
47 EXPORT_SYMBOL_GPL(inet_ehashfn);
48 
49 /* This function handles inet_sock, but also timewait and request sockets
50  * for IPv4/IPv6.
51  */
52 static u32 sk_ehashfn(const struct sock *sk)
53 {
54 #if IS_ENABLED(CONFIG_IPV6)
55 	if (sk->sk_family == AF_INET6 &&
56 	    !ipv6_addr_v4mapped(&sk->sk_v6_daddr))
57 		return inet6_ehashfn(sock_net(sk),
58 				     &sk->sk_v6_rcv_saddr, sk->sk_num,
59 				     &sk->sk_v6_daddr, sk->sk_dport);
60 #endif
61 	return inet_ehashfn(sock_net(sk),
62 			    sk->sk_rcv_saddr, sk->sk_num,
63 			    sk->sk_daddr, sk->sk_dport);
64 }
65 
66 static bool sk_is_connect_bind(const struct sock *sk)
67 {
68 	if (sk->sk_state == TCP_TIME_WAIT)
69 		return inet_twsk(sk)->tw_connect_bind;
70 	else
71 		return sk->sk_userlocks & SOCK_CONNECT_BIND;
72 }
73 
74 /*
75  * Allocate and initialize a new local port bind bucket.
76  * The bindhash mutex for snum's hash chain must be held here.
77  */
78 struct inet_bind_bucket *inet_bind_bucket_create(struct kmem_cache *cachep,
79 						 struct net *net,
80 						 struct inet_bind_hashbucket *head,
81 						 const unsigned short snum,
82 						 int l3mdev)
83 {
84 	struct inet_bind_bucket *tb = kmem_cache_alloc(cachep, GFP_ATOMIC);
85 
86 	if (tb) {
87 		write_pnet(&tb->ib_net, net);
88 		tb->l3mdev    = l3mdev;
89 		tb->port      = snum;
90 		tb->fastreuse = 0;
91 		tb->fastreuseport = 0;
92 		INIT_HLIST_HEAD(&tb->bhash2);
93 		hlist_add_head_rcu(&tb->node, &head->chain);
94 	}
95 	return tb;
96 }
97 
98 /*
99  * Caller must hold hashbucket lock for this tb with local BH disabled
100  */
101 void inet_bind_bucket_destroy(struct inet_bind_bucket *tb)
102 {
103 	const struct inet_bind2_bucket *tb2;
104 
105 	if (hlist_empty(&tb->bhash2)) {
106 		hlist_del_rcu(&tb->node);
107 		kfree_rcu(tb, rcu);
108 		return;
109 	}
110 
111 	if (tb->fastreuse == -1 && tb->fastreuseport == -1)
112 		return;
113 	hlist_for_each_entry(tb2, &tb->bhash2, bhash_node) {
114 		if (tb2->fastreuse != -1 || tb2->fastreuseport != -1)
115 			return;
116 	}
117 	tb->fastreuse = -1;
118 	tb->fastreuseport = -1;
119 }
120 
121 bool inet_bind_bucket_match(const struct inet_bind_bucket *tb, const struct net *net,
122 			    unsigned short port, int l3mdev)
123 {
124 	return net_eq(ib_net(tb), net) && tb->port == port &&
125 		tb->l3mdev == l3mdev;
126 }
127 
128 static void inet_bind2_bucket_init(struct inet_bind2_bucket *tb2,
129 				   struct net *net,
130 				   struct inet_bind_hashbucket *head,
131 				   struct inet_bind_bucket *tb,
132 				   const struct sock *sk)
133 {
134 	write_pnet(&tb2->ib_net, net);
135 	tb2->l3mdev = tb->l3mdev;
136 	tb2->port = tb->port;
137 #if IS_ENABLED(CONFIG_IPV6)
138 	BUILD_BUG_ON(USHRT_MAX < (IPV6_ADDR_ANY | IPV6_ADDR_MAPPED));
139 	if (sk->sk_family == AF_INET6) {
140 		tb2->addr_type = ipv6_addr_type(&sk->sk_v6_rcv_saddr);
141 		tb2->v6_rcv_saddr = sk->sk_v6_rcv_saddr;
142 	} else {
143 		tb2->addr_type = IPV6_ADDR_MAPPED;
144 		ipv6_addr_set_v4mapped(sk->sk_rcv_saddr, &tb2->v6_rcv_saddr);
145 	}
146 #else
147 	tb2->rcv_saddr = sk->sk_rcv_saddr;
148 #endif
149 	tb2->fastreuse = 0;
150 	tb2->fastreuseport = 0;
151 	INIT_HLIST_HEAD(&tb2->owners);
152 	hlist_add_head(&tb2->node, &head->chain);
153 	hlist_add_head(&tb2->bhash_node, &tb->bhash2);
154 }
155 
156 struct inet_bind2_bucket *inet_bind2_bucket_create(struct kmem_cache *cachep,
157 						   struct net *net,
158 						   struct inet_bind_hashbucket *head,
159 						   struct inet_bind_bucket *tb,
160 						   const struct sock *sk)
161 {
162 	struct inet_bind2_bucket *tb2 = kmem_cache_alloc(cachep, GFP_ATOMIC);
163 
164 	if (tb2)
165 		inet_bind2_bucket_init(tb2, net, head, tb, sk);
166 
167 	return tb2;
168 }
169 
170 /* Caller must hold hashbucket lock for this tb with local BH disabled */
171 void inet_bind2_bucket_destroy(struct kmem_cache *cachep, struct inet_bind2_bucket *tb)
172 {
173 	const struct sock *sk;
174 
175 	if (hlist_empty(&tb->owners)) {
176 		__hlist_del(&tb->node);
177 		__hlist_del(&tb->bhash_node);
178 		kmem_cache_free(cachep, tb);
179 		return;
180 	}
181 
182 	if (tb->fastreuse == -1 && tb->fastreuseport == -1)
183 		return;
184 	sk_for_each_bound(sk, &tb->owners) {
185 		if (!sk_is_connect_bind(sk))
186 			return;
187 	}
188 	tb->fastreuse = -1;
189 	tb->fastreuseport = -1;
190 }
191 
192 static bool inet_bind2_bucket_addr_match(const struct inet_bind2_bucket *tb2,
193 					 const struct sock *sk)
194 {
195 #if IS_ENABLED(CONFIG_IPV6)
196 	if (sk->sk_family == AF_INET6)
197 		return ipv6_addr_equal(&tb2->v6_rcv_saddr, &sk->sk_v6_rcv_saddr);
198 
199 	if (tb2->addr_type != IPV6_ADDR_MAPPED)
200 		return false;
201 #endif
202 	return tb2->rcv_saddr == sk->sk_rcv_saddr;
203 }
204 
205 void inet_bind_hash(struct sock *sk, struct inet_bind_bucket *tb,
206 		    struct inet_bind2_bucket *tb2, unsigned short port)
207 {
208 	WRITE_ONCE(inet_sk(sk)->inet_num, port);
209 	inet_csk(sk)->icsk_bind_hash = tb;
210 	inet_csk(sk)->icsk_bind2_hash = tb2;
211 	sk_add_bind_node(sk, &tb2->owners);
212 }
213 
214 /*
215  * Get rid of any references to a local port held by the given sock.
216  */
217 static void __inet_put_port(struct sock *sk)
218 {
219 	struct inet_hashinfo *hashinfo = tcp_get_hashinfo(sk);
220 	struct inet_bind_hashbucket *head, *head2;
221 	struct net *net = sock_net(sk);
222 	struct inet_bind_bucket *tb;
223 	int bhash;
224 
225 	bhash = inet_bhashfn(net, inet_sk(sk)->inet_num, hashinfo->bhash_size);
226 	head = &hashinfo->bhash[bhash];
227 	head2 = inet_bhashfn_portaddr(hashinfo, sk, net, inet_sk(sk)->inet_num);
228 
229 	spin_lock(&head->lock);
230 	tb = inet_csk(sk)->icsk_bind_hash;
231 	inet_csk(sk)->icsk_bind_hash = NULL;
232 	WRITE_ONCE(inet_sk(sk)->inet_num, 0);
233 	sk->sk_userlocks &= ~SOCK_CONNECT_BIND;
234 
235 	spin_lock(&head2->lock);
236 	if (inet_csk(sk)->icsk_bind2_hash) {
237 		struct inet_bind2_bucket *tb2 = inet_csk(sk)->icsk_bind2_hash;
238 
239 		__sk_del_bind_node(sk);
240 		inet_csk(sk)->icsk_bind2_hash = NULL;
241 		inet_bind2_bucket_destroy(hashinfo->bind2_bucket_cachep, tb2);
242 	}
243 	spin_unlock(&head2->lock);
244 
245 	inet_bind_bucket_destroy(tb);
246 	spin_unlock(&head->lock);
247 }
248 
249 void inet_put_port(struct sock *sk)
250 {
251 	local_bh_disable();
252 	__inet_put_port(sk);
253 	local_bh_enable();
254 }
255 
256 int __inet_inherit_port(const struct sock *sk, struct sock *child)
257 {
258 	struct inet_hashinfo *table = tcp_get_hashinfo(sk);
259 	unsigned short port = inet_sk(child)->inet_num;
260 	struct inet_bind_hashbucket *head, *head2;
261 	bool created_inet_bind_bucket = false;
262 	struct net *net = sock_net(sk);
263 	bool update_fastreuse = false;
264 	struct inet_bind2_bucket *tb2;
265 	struct inet_bind_bucket *tb;
266 	int bhash, l3mdev;
267 
268 	bhash = inet_bhashfn(net, port, table->bhash_size);
269 	head = &table->bhash[bhash];
270 	head2 = inet_bhashfn_portaddr(table, child, net, port);
271 
272 	spin_lock(&head->lock);
273 	spin_lock(&head2->lock);
274 	tb = inet_csk(sk)->icsk_bind_hash;
275 	tb2 = inet_csk(sk)->icsk_bind2_hash;
276 	if (unlikely(!tb || !tb2)) {
277 		spin_unlock(&head2->lock);
278 		spin_unlock(&head->lock);
279 		return -ENOENT;
280 	}
281 	if (tb->port != port) {
282 		l3mdev = inet_sk_bound_l3mdev(sk);
283 
284 		/* NOTE: using tproxy and redirecting skbs to a proxy
285 		 * on a different listener port breaks the assumption
286 		 * that the listener socket's icsk_bind_hash is the same
287 		 * as that of the child socket. We have to look up or
288 		 * create a new bind bucket for the child here. */
289 		inet_bind_bucket_for_each(tb, &head->chain) {
290 			if (inet_bind_bucket_match(tb, net, port, l3mdev))
291 				break;
292 		}
293 		if (!tb) {
294 			tb = inet_bind_bucket_create(table->bind_bucket_cachep,
295 						     net, head, port, l3mdev);
296 			if (!tb) {
297 				spin_unlock(&head2->lock);
298 				spin_unlock(&head->lock);
299 				return -ENOMEM;
300 			}
301 			created_inet_bind_bucket = true;
302 		}
303 		update_fastreuse = true;
304 
305 		goto bhash2_find;
306 	} else if (!inet_bind2_bucket_addr_match(tb2, child)) {
307 		l3mdev = inet_sk_bound_l3mdev(sk);
308 
309 bhash2_find:
310 		tb2 = inet_bind2_bucket_find(head2, net, port, l3mdev, child);
311 		if (!tb2) {
312 			tb2 = inet_bind2_bucket_create(table->bind2_bucket_cachep,
313 						       net, head2, tb, child);
314 			if (!tb2)
315 				goto error;
316 		}
317 	}
318 	if (update_fastreuse)
319 		inet_csk_update_fastreuse(child, tb, tb2);
320 	inet_bind_hash(child, tb, tb2, port);
321 	spin_unlock(&head2->lock);
322 	spin_unlock(&head->lock);
323 
324 	return 0;
325 
326 error:
327 	if (created_inet_bind_bucket)
328 		inet_bind_bucket_destroy(tb);
329 	spin_unlock(&head2->lock);
330 	spin_unlock(&head->lock);
331 	return -ENOMEM;
332 }
333 
334 static struct inet_listen_hashbucket *
335 inet_lhash2_bucket_sk(struct inet_hashinfo *h, struct sock *sk)
336 {
337 	u32 hash;
338 
339 #if IS_ENABLED(CONFIG_IPV6)
340 	if (sk->sk_family == AF_INET6)
341 		hash = ipv6_portaddr_hash(sock_net(sk),
342 					  &sk->sk_v6_rcv_saddr,
343 					  inet_sk(sk)->inet_num);
344 	else
345 #endif
346 		hash = ipv4_portaddr_hash(sock_net(sk),
347 					  inet_sk(sk)->inet_rcv_saddr,
348 					  inet_sk(sk)->inet_num);
349 	return inet_lhash2_bucket(h, hash);
350 }
351 
352 static inline int compute_score(struct sock *sk, const struct net *net,
353 				const unsigned short hnum, const __be32 daddr,
354 				const int dif, const int sdif)
355 {
356 	int score = -1;
357 
358 	if (net_eq(sock_net(sk), net) && READ_ONCE(sk->sk_num) == hnum &&
359 			!ipv6_only_sock(sk)) {
360 		if (sk->sk_rcv_saddr != daddr)
361 			return -1;
362 
363 		if (!inet_sk_bound_dev_eq(net, sk->sk_bound_dev_if, dif, sdif))
364 			return -1;
365 		score =  sk->sk_bound_dev_if ? 2 : 1;
366 
367 		if (sk->sk_family == PF_INET)
368 			score++;
369 		if (READ_ONCE(sk->sk_incoming_cpu) == raw_smp_processor_id())
370 			score++;
371 	}
372 	return score;
373 }
374 
375 /**
376  * inet_lookup_reuseport() - execute reuseport logic on AF_INET socket if necessary.
377  * @net: network namespace.
378  * @sk: AF_INET socket, must be in TCP_LISTEN state for TCP or TCP_CLOSE for UDP.
379  * @skb: context for a potential SK_REUSEPORT program.
380  * @doff: header offset.
381  * @saddr: source address.
382  * @sport: source port.
383  * @daddr: destination address.
384  * @hnum: destination port in host byte order.
385  * @ehashfn: hash function used to generate the fallback hash.
386  *
387  * Return: NULL if sk doesn't have SO_REUSEPORT set, otherwise a pointer to
388  *         the selected sock or an error.
389  */
390 struct sock *inet_lookup_reuseport(const struct net *net, struct sock *sk,
391 				   struct sk_buff *skb, int doff,
392 				   __be32 saddr, __be16 sport,
393 				   __be32 daddr, unsigned short hnum,
394 				   inet_ehashfn_t *ehashfn)
395 {
396 	struct sock *reuse_sk = NULL;
397 	u32 phash;
398 
399 	if (sk->sk_reuseport) {
400 		phash = INDIRECT_CALL_2(ehashfn, udp_ehashfn, inet_ehashfn,
401 					net, daddr, hnum, saddr, sport);
402 		reuse_sk = reuseport_select_sock(sk, phash, skb, doff);
403 	}
404 	return reuse_sk;
405 }
406 EXPORT_SYMBOL_GPL(inet_lookup_reuseport);
407 
408 /*
409  * Here are some nice properties to exploit here. The BSD API
410  * does not allow a listening sock to specify the remote port nor the
411  * remote address for the connection. So always assume those are both
412  * wildcarded during the search since they can never be otherwise.
413  */
414 
415 /* called with rcu_read_lock() : No refcount taken on the socket */
416 static struct sock *inet_lhash2_lookup(const struct net *net,
417 				struct inet_listen_hashbucket *ilb2,
418 				struct sk_buff *skb, int doff,
419 				const __be32 saddr, __be16 sport,
420 				const __be32 daddr, const unsigned short hnum,
421 				const int dif, const int sdif)
422 {
423 	struct sock *sk, *result = NULL;
424 	struct hlist_nulls_node *node;
425 	int score, hiscore = 0;
426 
427 	sk_nulls_for_each_rcu(sk, node, &ilb2->nulls_head) {
428 		score = compute_score(sk, net, hnum, daddr, dif, sdif);
429 		if (score > hiscore) {
430 			result = inet_lookup_reuseport(net, sk, skb, doff,
431 						       saddr, sport, daddr, hnum, inet_ehashfn);
432 			if (result)
433 				return result;
434 
435 			result = sk;
436 			hiscore = score;
437 		}
438 	}
439 
440 	return result;
441 }
442 
443 struct sock *inet_lookup_run_sk_lookup(const struct net *net,
444 				       int protocol,
445 				       struct sk_buff *skb, int doff,
446 				       __be32 saddr, __be16 sport,
447 				       __be32 daddr, u16 hnum, const int dif,
448 				       inet_ehashfn_t *ehashfn)
449 {
450 	struct sock *sk, *reuse_sk;
451 	bool no_reuseport;
452 
453 	no_reuseport = bpf_sk_lookup_run_v4(net, protocol, saddr, sport,
454 					    daddr, hnum, dif, &sk);
455 	if (no_reuseport || IS_ERR_OR_NULL(sk))
456 		return sk;
457 
458 	reuse_sk = inet_lookup_reuseport(net, sk, skb, doff, saddr, sport, daddr, hnum,
459 					 ehashfn);
460 	if (reuse_sk)
461 		sk = reuse_sk;
462 	return sk;
463 }
464 
465 struct sock *__inet_lookup_listener(const struct net *net,
466 				    struct sk_buff *skb, int doff,
467 				    const __be32 saddr, __be16 sport,
468 				    const __be32 daddr, const unsigned short hnum,
469 				    const int dif, const int sdif)
470 {
471 	struct inet_listen_hashbucket *ilb2;
472 	struct inet_hashinfo *hashinfo;
473 	struct sock *result = NULL;
474 	unsigned int hash2;
475 
476 	/* Lookup redirect from BPF */
477 	if (static_branch_unlikely(&bpf_sk_lookup_enabled)) {
478 		result = inet_lookup_run_sk_lookup(net, IPPROTO_TCP, skb, doff,
479 						   saddr, sport, daddr, hnum, dif,
480 						   inet_ehashfn);
481 		if (result)
482 			goto done;
483 	}
484 
485 	hashinfo = net->ipv4.tcp_death_row.hashinfo;
486 	hash2 = ipv4_portaddr_hash(net, daddr, hnum);
487 	ilb2 = inet_lhash2_bucket(hashinfo, hash2);
488 
489 	result = inet_lhash2_lookup(net, ilb2, skb, doff,
490 				    saddr, sport, daddr, hnum,
491 				    dif, sdif);
492 	if (result)
493 		goto done;
494 
495 	/* Lookup lhash2 with INADDR_ANY */
496 	hash2 = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum);
497 	ilb2 = inet_lhash2_bucket(hashinfo, hash2);
498 
499 	result = inet_lhash2_lookup(net, ilb2, skb, doff,
500 				    saddr, sport, htonl(INADDR_ANY), hnum,
501 				    dif, sdif);
502 done:
503 	if (IS_ERR(result))
504 		return NULL;
505 	return result;
506 }
507 EXPORT_SYMBOL_GPL(__inet_lookup_listener);
508 
509 /* All sockets share common refcount, but have different destructors */
510 void sock_gen_put(struct sock *sk)
511 {
512 	if (!refcount_dec_and_test(&sk->sk_refcnt))
513 		return;
514 
515 	if (sk->sk_state == TCP_TIME_WAIT)
516 		inet_twsk_free(inet_twsk(sk));
517 	else if (sk->sk_state == TCP_NEW_SYN_RECV)
518 		reqsk_free(inet_reqsk(sk));
519 	else
520 		sk_free(sk);
521 }
522 EXPORT_SYMBOL_GPL(sock_gen_put);
523 
524 void sock_edemux(struct sk_buff *skb)
525 {
526 	sock_gen_put(skb->sk);
527 }
528 EXPORT_SYMBOL(sock_edemux);
529 
530 struct sock *__inet_lookup_established(const struct net *net,
531 				       const __be32 saddr, const __be16 sport,
532 				       const __be32 daddr, const u16 hnum,
533 				       const int dif, const int sdif)
534 {
535 	const __portpair ports = INET_COMBINED_PORTS(sport, hnum);
536 	INET_ADDR_COOKIE(acookie, saddr, daddr);
537 	const struct hlist_nulls_node *node;
538 	struct inet_ehash_bucket *head;
539 	struct inet_hashinfo *hashinfo;
540 	unsigned int hash, slot;
541 	struct sock *sk;
542 
543 	hashinfo = net->ipv4.tcp_death_row.hashinfo;
544 	hash = inet_ehashfn(net, daddr, hnum, saddr, sport);
545 	slot = hash & hashinfo->ehash_mask;
546 	head = &hashinfo->ehash[slot];
547 
548 begin:
549 	sk_nulls_for_each_rcu(sk, node, &head->chain) {
550 		if (sk->sk_hash != hash)
551 			continue;
552 		if (likely(inet_match(net, sk, acookie, ports, dif, sdif))) {
553 			if (unlikely(!refcount_inc_not_zero_acquire(&sk->sk_refcnt)))
554 				goto out;
555 			if (unlikely(hlist_nulls_unhashed_lockless(&sk->sk_nulls_node) ||
556 				     !inet_match(net, sk, acookie, ports, dif,
557 						 sdif))) {
558 				sock_gen_put(sk);
559 				goto begin;
560 			}
561 			goto found;
562 		}
563 	}
564 	/*
565 	 * if the nulls value we got at the end of this lookup is
566 	 * not the expected one, we must restart lookup.
567 	 * We probably met an item that was moved to another chain.
568 	 */
569 	if (get_nulls_value(node) != slot)
570 		goto begin;
571 out:
572 	sk = NULL;
573 found:
574 	return sk;
575 }
576 EXPORT_SYMBOL_GPL(__inet_lookup_established);
577 
578 /* called with local bh disabled */
579 static int __inet_check_established(struct inet_timewait_death_row *death_row,
580 				    struct sock *sk, __u16 lport,
581 				    struct inet_timewait_sock **twp,
582 				    bool rcu_lookup,
583 				    u32 hash)
584 {
585 	struct inet_hashinfo *hinfo = death_row->hashinfo;
586 	struct inet_sock *inet = inet_sk(sk);
587 	__be32 daddr = inet->inet_rcv_saddr;
588 	__be32 saddr = inet->inet_daddr;
589 	int dif = sk->sk_bound_dev_if;
590 	struct net *net = sock_net(sk);
591 	int sdif = l3mdev_master_ifindex_by_index(net, dif);
592 	INET_ADDR_COOKIE(acookie, saddr, daddr);
593 	const __portpair ports = INET_COMBINED_PORTS(inet->inet_dport, lport);
594 	struct inet_ehash_bucket *head = inet_ehash_bucket(hinfo, hash);
595 	struct inet_timewait_sock *tw = NULL;
596 	const struct hlist_nulls_node *node;
597 	struct sock *sk2;
598 	spinlock_t *lock;
599 
600 	if (rcu_lookup) {
601 		sk_nulls_for_each(sk2, node, &head->chain) {
602 			if (sk2->sk_hash != hash ||
603 			    !inet_match(net, sk2, acookie, ports, dif, sdif))
604 				continue;
605 			if (sk2->sk_state == TCP_TIME_WAIT)
606 				break;
607 			return -EADDRNOTAVAIL;
608 		}
609 		return 0;
610 	}
611 
612 	lock = inet_ehash_lockp(hinfo, hash);
613 	spin_lock(lock);
614 
615 	sk_nulls_for_each(sk2, node, &head->chain) {
616 		if (sk2->sk_hash != hash)
617 			continue;
618 
619 		if (likely(inet_match(net, sk2, acookie, ports, dif, sdif))) {
620 			if (sk2->sk_state == TCP_TIME_WAIT) {
621 				tw = inet_twsk(sk2);
622 				if (tcp_twsk_unique(sk, sk2, twp))
623 					break;
624 			}
625 			goto not_unique;
626 		}
627 	}
628 
629 	/* Must record num and sport now. Otherwise we will see
630 	 * in hash table socket with a funny identity.
631 	 */
632 	inet->inet_num = lport;
633 	inet->inet_sport = htons(lport);
634 	sk->sk_hash = hash;
635 	WARN_ON(!sk_unhashed(sk));
636 	__sk_nulls_add_node_rcu(sk, &head->chain);
637 	if (tw) {
638 		sk_nulls_del_node_init_rcu((struct sock *)tw);
639 		__NET_INC_STATS(net, LINUX_MIB_TIMEWAITRECYCLED);
640 	}
641 	spin_unlock(lock);
642 	sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
643 
644 	if (twp) {
645 		*twp = tw;
646 	} else if (tw) {
647 		/* Silly. Should hash-dance instead... */
648 		inet_twsk_deschedule_put(tw);
649 	}
650 	return 0;
651 
652 not_unique:
653 	spin_unlock(lock);
654 	return -EADDRNOTAVAIL;
655 }
656 
657 static u64 inet_sk_port_offset(const struct sock *sk)
658 {
659 	const struct inet_sock *inet = inet_sk(sk);
660 
661 	return secure_ipv4_port_ephemeral(inet->inet_rcv_saddr,
662 					  inet->inet_daddr,
663 					  inet->inet_dport);
664 }
665 
666 /* Searches for an exsiting socket in the ehash bucket list.
667  * Returns true if found, false otherwise.
668  */
669 static bool inet_ehash_lookup_by_sk(struct sock *sk,
670 				    struct hlist_nulls_head *list)
671 {
672 	const __portpair ports = INET_COMBINED_PORTS(sk->sk_dport, sk->sk_num);
673 	const int sdif = sk->sk_bound_dev_if;
674 	const int dif = sk->sk_bound_dev_if;
675 	const struct hlist_nulls_node *node;
676 	struct net *net = sock_net(sk);
677 	struct sock *esk;
678 
679 	INET_ADDR_COOKIE(acookie, sk->sk_daddr, sk->sk_rcv_saddr);
680 
681 	sk_nulls_for_each_rcu(esk, node, list) {
682 		if (esk->sk_hash != sk->sk_hash)
683 			continue;
684 		if (sk->sk_family == AF_INET) {
685 			if (unlikely(inet_match(net, esk, acookie,
686 						ports, dif, sdif))) {
687 				return true;
688 			}
689 		}
690 #if IS_ENABLED(CONFIG_IPV6)
691 		else if (sk->sk_family == AF_INET6) {
692 			if (unlikely(inet6_match(net, esk,
693 						 &sk->sk_v6_daddr,
694 						 &sk->sk_v6_rcv_saddr,
695 						 ports, dif, sdif))) {
696 				return true;
697 			}
698 		}
699 #endif
700 	}
701 	return false;
702 }
703 
704 /* Insert a socket into ehash, and eventually remove another one
705  * (The another one can be a SYN_RECV or TIMEWAIT)
706  * If an existing socket already exists, socket sk is not inserted,
707  * and sets found_dup_sk parameter to true.
708  */
709 bool inet_ehash_insert(struct sock *sk, struct sock *osk, bool *found_dup_sk)
710 {
711 	struct inet_hashinfo *hashinfo = tcp_get_hashinfo(sk);
712 	struct inet_ehash_bucket *head;
713 	struct hlist_nulls_head *list;
714 	spinlock_t *lock;
715 	bool ret = true;
716 
717 	WARN_ON_ONCE(!sk_unhashed(sk));
718 
719 	sk->sk_hash = sk_ehashfn(sk);
720 	head = inet_ehash_bucket(hashinfo, sk->sk_hash);
721 	list = &head->chain;
722 	lock = inet_ehash_lockp(hashinfo, sk->sk_hash);
723 
724 	spin_lock(lock);
725 	if (osk) {
726 		WARN_ON_ONCE(sk->sk_hash != osk->sk_hash);
727 		ret = sk_nulls_replace_node_init_rcu(osk, sk);
728 		goto unlock;
729 	}
730 
731 	if (found_dup_sk) {
732 		*found_dup_sk = inet_ehash_lookup_by_sk(sk, list);
733 		if (*found_dup_sk)
734 			ret = false;
735 	}
736 
737 	if (ret)
738 		__sk_nulls_add_node_rcu(sk, list);
739 
740 unlock:
741 	spin_unlock(lock);
742 
743 	return ret;
744 }
745 
746 bool inet_ehash_nolisten(struct sock *sk, struct sock *osk, bool *found_dup_sk)
747 {
748 	bool ok = inet_ehash_insert(sk, osk, found_dup_sk);
749 
750 	if (ok) {
751 		sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
752 	} else {
753 		tcp_orphan_count_inc();
754 		inet_sk_set_state(sk, TCP_CLOSE);
755 		sock_set_flag(sk, SOCK_DEAD);
756 		inet_csk_destroy_sock(sk);
757 	}
758 	return ok;
759 }
760 
761 static int inet_reuseport_add_sock(struct sock *sk,
762 				   struct inet_listen_hashbucket *ilb)
763 {
764 	struct inet_bind_bucket *tb = inet_csk(sk)->icsk_bind_hash;
765 	const struct hlist_nulls_node *node;
766 	kuid_t uid = sk_uid(sk);
767 	struct sock *sk2;
768 
769 	sk_nulls_for_each_rcu(sk2, node, &ilb->nulls_head) {
770 		if (sk2 != sk &&
771 		    sk2->sk_family == sk->sk_family &&
772 		    ipv6_only_sock(sk2) == ipv6_only_sock(sk) &&
773 		    sk2->sk_bound_dev_if == sk->sk_bound_dev_if &&
774 		    inet_csk(sk2)->icsk_bind_hash == tb &&
775 		    sk2->sk_reuseport && uid_eq(uid, sk_uid(sk2)) &&
776 		    inet_rcv_saddr_equal(sk, sk2, false))
777 			return reuseport_add_sock(sk, sk2,
778 						  inet_rcv_saddr_any(sk));
779 	}
780 
781 	return reuseport_alloc(sk, inet_rcv_saddr_any(sk));
782 }
783 
784 int inet_hash(struct sock *sk)
785 {
786 	struct inet_hashinfo *hashinfo = tcp_get_hashinfo(sk);
787 	struct inet_listen_hashbucket *ilb2;
788 	int err = 0;
789 
790 	if (sk->sk_state == TCP_CLOSE)
791 		return 0;
792 
793 	if (sk->sk_state != TCP_LISTEN) {
794 		local_bh_disable();
795 		inet_ehash_nolisten(sk, NULL, NULL);
796 		local_bh_enable();
797 		return 0;
798 	}
799 
800 #if IS_ENABLED(CONFIG_IPV6)
801 	if (sk->sk_family == AF_INET6)
802 		inet6_init_ehash_secret();
803 #endif
804 	inet_init_ehash_secret();
805 
806 	WARN_ON(!sk_unhashed(sk));
807 
808 	if (unlikely(inet_csk(sk)->unhashed_state &&
809 		     inet_csk(sk)->unhashed_state != TCP_LISTEN))
810 		return -EINVAL;
811 
812 	ilb2 = inet_lhash2_bucket_sk(hashinfo, sk);
813 
814 	spin_lock(&ilb2->lock);
815 	if (sk->sk_reuseport) {
816 		err = inet_reuseport_add_sock(sk, ilb2);
817 		if (err)
818 			goto unlock;
819 	}
820 	sock_set_flag(sk, SOCK_RCU_FREE);
821 	if (IS_ENABLED(CONFIG_IPV6) && sk->sk_reuseport &&
822 		sk->sk_family == AF_INET6)
823 		__sk_nulls_add_node_tail_rcu(sk, &ilb2->nulls_head);
824 	else
825 		__sk_nulls_add_node_rcu(sk, &ilb2->nulls_head);
826 	sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
827 unlock:
828 	spin_unlock(&ilb2->lock);
829 
830 	return err;
831 }
832 
833 void inet_unhash(struct sock *sk)
834 {
835 	struct inet_hashinfo *hashinfo = tcp_get_hashinfo(sk);
836 
837 	if (sk_unhashed(sk))
838 		return;
839 
840 	sock_rps_delete_flow(sk);
841 
842 	inet_csk(sk)->unhashed_state = sk->sk_state;
843 
844 	if (sk->sk_state == TCP_LISTEN) {
845 		struct inet_listen_hashbucket *ilb2;
846 
847 		ilb2 = inet_lhash2_bucket_sk(hashinfo, sk);
848 		/* Don't disable bottom halves while acquiring the lock to
849 		 * avoid circular locking dependency on PREEMPT_RT.
850 		 */
851 		spin_lock(&ilb2->lock);
852 		if (rcu_access_pointer(sk->sk_reuseport_cb))
853 			reuseport_stop_listen_sock(sk);
854 
855 		__sk_nulls_del_node_init_rcu(sk);
856 		sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
857 		spin_unlock(&ilb2->lock);
858 	} else {
859 		spinlock_t *lock = inet_ehash_lockp(hashinfo, sk->sk_hash);
860 
861 		spin_lock_bh(lock);
862 		__sk_nulls_del_node_init_rcu(sk);
863 		sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
864 		spin_unlock_bh(lock);
865 	}
866 }
867 
868 static bool inet_bind2_bucket_match(const struct inet_bind2_bucket *tb,
869 				    const struct net *net, unsigned short port,
870 				    int l3mdev, const struct sock *sk)
871 {
872 	if (!net_eq(ib2_net(tb), net) || tb->port != port ||
873 	    tb->l3mdev != l3mdev)
874 		return false;
875 
876 	return inet_bind2_bucket_addr_match(tb, sk);
877 }
878 
879 bool inet_bind2_bucket_match_addr_any(const struct inet_bind2_bucket *tb, const struct net *net,
880 				      unsigned short port, int l3mdev, const struct sock *sk)
881 {
882 	if (!net_eq(ib2_net(tb), net) || tb->port != port ||
883 	    tb->l3mdev != l3mdev)
884 		return false;
885 
886 #if IS_ENABLED(CONFIG_IPV6)
887 	if (tb->addr_type == IPV6_ADDR_ANY)
888 		return true;
889 
890 	if (tb->addr_type != IPV6_ADDR_MAPPED)
891 		return false;
892 
893 	if (sk->sk_family == AF_INET6 &&
894 	    !ipv6_addr_v4mapped(&sk->sk_v6_rcv_saddr))
895 		return false;
896 #endif
897 	return tb->rcv_saddr == 0;
898 }
899 
900 /* The socket's bhash2 hashbucket spinlock must be held when this is called */
901 struct inet_bind2_bucket *
902 inet_bind2_bucket_find(const struct inet_bind_hashbucket *head, const struct net *net,
903 		       unsigned short port, int l3mdev, const struct sock *sk)
904 {
905 	struct inet_bind2_bucket *bhash2 = NULL;
906 
907 	inet_bind_bucket_for_each(bhash2, &head->chain)
908 		if (inet_bind2_bucket_match(bhash2, net, port, l3mdev, sk))
909 			break;
910 
911 	return bhash2;
912 }
913 
914 struct inet_bind_hashbucket *
915 inet_bhash2_addr_any_hashbucket(const struct sock *sk, const struct net *net, int port)
916 {
917 	struct inet_hashinfo *hinfo = tcp_get_hashinfo(sk);
918 	u32 hash;
919 
920 #if IS_ENABLED(CONFIG_IPV6)
921 	if (sk->sk_family == AF_INET6)
922 		hash = ipv6_portaddr_hash(net, &in6addr_any, port);
923 	else
924 #endif
925 		hash = ipv4_portaddr_hash(net, 0, port);
926 
927 	return &hinfo->bhash2[hash & (hinfo->bhash_size - 1)];
928 }
929 
930 static void inet_update_saddr(struct sock *sk, void *saddr, int family)
931 {
932 	if (family == AF_INET) {
933 		inet_sk(sk)->inet_saddr = *(__be32 *)saddr;
934 		sk_rcv_saddr_set(sk, inet_sk(sk)->inet_saddr);
935 	}
936 #if IS_ENABLED(CONFIG_IPV6)
937 	else {
938 		sk->sk_v6_rcv_saddr = *(struct in6_addr *)saddr;
939 	}
940 #endif
941 }
942 
943 static int __inet_bhash2_update_saddr(struct sock *sk, void *saddr, int family, bool reset)
944 {
945 	struct inet_hashinfo *hinfo = tcp_get_hashinfo(sk);
946 	struct inet_bind_hashbucket *head, *head2;
947 	struct inet_bind2_bucket *tb2, *new_tb2;
948 	int l3mdev = inet_sk_bound_l3mdev(sk);
949 	int port = inet_sk(sk)->inet_num;
950 	struct net *net = sock_net(sk);
951 	int bhash;
952 
953 	if (!inet_csk(sk)->icsk_bind2_hash) {
954 		/* Not bind()ed before. */
955 		if (reset)
956 			inet_reset_saddr(sk);
957 		else
958 			inet_update_saddr(sk, saddr, family);
959 
960 		return 0;
961 	}
962 
963 	/* Allocate a bind2 bucket ahead of time to avoid permanently putting
964 	 * the bhash2 table in an inconsistent state if a new tb2 bucket
965 	 * allocation fails.
966 	 */
967 	new_tb2 = kmem_cache_alloc(hinfo->bind2_bucket_cachep, GFP_ATOMIC);
968 	if (!new_tb2) {
969 		if (reset) {
970 			/* The (INADDR_ANY, port) bucket might have already
971 			 * been freed, then we cannot fixup icsk_bind2_hash,
972 			 * so we give up and unlink sk from bhash/bhash2 not
973 			 * to leave inconsistency in bhash2.
974 			 */
975 			inet_put_port(sk);
976 			inet_reset_saddr(sk);
977 		}
978 
979 		return -ENOMEM;
980 	}
981 
982 	bhash = inet_bhashfn(net, port, hinfo->bhash_size);
983 	head = &hinfo->bhash[bhash];
984 	head2 = inet_bhashfn_portaddr(hinfo, sk, net, port);
985 
986 	/* If we change saddr locklessly, another thread
987 	 * iterating over bhash might see corrupted address.
988 	 */
989 	spin_lock_bh(&head->lock);
990 
991 	spin_lock(&head2->lock);
992 	__sk_del_bind_node(sk);
993 	inet_bind2_bucket_destroy(hinfo->bind2_bucket_cachep, inet_csk(sk)->icsk_bind2_hash);
994 	spin_unlock(&head2->lock);
995 
996 	if (reset)
997 		inet_reset_saddr(sk);
998 	else
999 		inet_update_saddr(sk, saddr, family);
1000 
1001 	head2 = inet_bhashfn_portaddr(hinfo, sk, net, port);
1002 
1003 	spin_lock(&head2->lock);
1004 	tb2 = inet_bind2_bucket_find(head2, net, port, l3mdev, sk);
1005 	if (!tb2) {
1006 		tb2 = new_tb2;
1007 		inet_bind2_bucket_init(tb2, net, head2, inet_csk(sk)->icsk_bind_hash, sk);
1008 		if (sk_is_connect_bind(sk)) {
1009 			tb2->fastreuse = -1;
1010 			tb2->fastreuseport = -1;
1011 		}
1012 	}
1013 	inet_csk(sk)->icsk_bind2_hash = tb2;
1014 	sk_add_bind_node(sk, &tb2->owners);
1015 	spin_unlock(&head2->lock);
1016 
1017 	spin_unlock_bh(&head->lock);
1018 
1019 	if (tb2 != new_tb2)
1020 		kmem_cache_free(hinfo->bind2_bucket_cachep, new_tb2);
1021 
1022 	return 0;
1023 }
1024 
1025 int inet_bhash2_update_saddr(struct sock *sk, void *saddr, int family)
1026 {
1027 	return __inet_bhash2_update_saddr(sk, saddr, family, false);
1028 }
1029 
1030 void inet_bhash2_reset_saddr(struct sock *sk)
1031 {
1032 	if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
1033 		__inet_bhash2_update_saddr(sk, NULL, 0, true);
1034 }
1035 
1036 /* RFC 6056 3.3.4.  Algorithm 4: Double-Hash Port Selection Algorithm
1037  * Note that we use 32bit integers (vs RFC 'short integers')
1038  * because 2^16 is not a multiple of num_ephemeral and this
1039  * property might be used by clever attacker.
1040  *
1041  * RFC claims using TABLE_LENGTH=10 buckets gives an improvement, though
1042  * attacks were since demonstrated, thus we use 65536 by default instead
1043  * to really give more isolation and privacy, at the expense of 256kB
1044  * of kernel memory.
1045  */
1046 #define INET_TABLE_PERTURB_SIZE (1 << CONFIG_INET_TABLE_PERTURB_ORDER)
1047 static u32 *table_perturb;
1048 
1049 int __inet_hash_connect(struct inet_timewait_death_row *death_row,
1050 		struct sock *sk, u64 port_offset,
1051 		u32 hash_port0,
1052 		int (*check_established)(struct inet_timewait_death_row *,
1053 			struct sock *, __u16, struct inet_timewait_sock **,
1054 			bool rcu_lookup, u32 hash))
1055 {
1056 	struct inet_hashinfo *hinfo = death_row->hashinfo;
1057 	struct inet_bind_hashbucket *head, *head2;
1058 	struct inet_timewait_sock *tw = NULL;
1059 	int port = inet_sk(sk)->inet_num;
1060 	struct net *net = sock_net(sk);
1061 	struct inet_bind2_bucket *tb2;
1062 	struct inet_bind_bucket *tb;
1063 	int step, scan_step, l3mdev;
1064 	u32 index, max_rand_step;
1065 	bool tb_created = false;
1066 	u32 remaining, offset;
1067 	int ret, i, low, high;
1068 	bool local_ports;
1069 
1070 	if (unlikely(inet_csk(sk)->unhashed_state == TCP_LISTEN))
1071 		return -EINVAL;
1072 
1073 	if (port) {
1074 		local_bh_disable();
1075 		ret = check_established(death_row, sk, port, NULL, false,
1076 					hash_port0 + port);
1077 		local_bh_enable();
1078 		return ret;
1079 	}
1080 
1081 	l3mdev = inet_sk_bound_l3mdev(sk);
1082 
1083 	local_ports = inet_sk_get_local_port_range(sk, &low, &high);
1084 	step = local_ports ? 1 : 2;
1085 	scan_step = step;
1086 	max_rand_step = READ_ONCE(net->ipv4.sysctl_ip_local_port_step_width);
1087 
1088 	high++; /* [32768, 60999] -> [32768, 61000[ */
1089 	remaining = high - low;
1090 	if (!local_ports && remaining > 1)
1091 		remaining &= ~1U;
1092 
1093 	get_random_sleepable_once(table_perturb,
1094 				  INET_TABLE_PERTURB_SIZE * sizeof(*table_perturb));
1095 	index = port_offset & (INET_TABLE_PERTURB_SIZE - 1);
1096 
1097 	offset = READ_ONCE(table_perturb[index]) + (port_offset >> 32);
1098 	offset %= remaining;
1099 
1100 	/* In first pass we try ports of @low parity.
1101 	 * inet_csk_get_port() does the opposite choice.
1102 	 */
1103 	if (!local_ports)
1104 		offset &= ~1U;
1105 
1106 	if (max_rand_step && remaining > 1) {
1107 		u32 range = remaining / step;
1108 		u32 upper_bound;
1109 
1110 		upper_bound = min(range, max_rand_step);
1111 		scan_step = get_random_u32_inclusive(1, upper_bound);
1112 		while (gcd(scan_step, range) != 1) {
1113 			scan_step++;
1114 			/* if both scan_step and range are even gcd won't be 1 */
1115 			if (!(scan_step & 1) && !(range & 1))
1116 				scan_step++;
1117 			if (unlikely(scan_step > upper_bound)) {
1118 				scan_step = 1;
1119 				break;
1120 			}
1121 		}
1122 		scan_step *= step;
1123 	}
1124 other_parity_scan:
1125 	port = low + offset;
1126 	for (i = 0; i < remaining; i += step, port += scan_step) {
1127 		if (unlikely(port >= high))
1128 			port -= remaining;
1129 		if (inet_is_local_reserved_port(net, port))
1130 			continue;
1131 		head = &hinfo->bhash[inet_bhashfn(net, port,
1132 						  hinfo->bhash_size)];
1133 		rcu_read_lock();
1134 		hlist_for_each_entry_rcu(tb, &head->chain, node) {
1135 			if (!inet_bind_bucket_match(tb, net, port, l3mdev))
1136 				continue;
1137 			if (tb->fastreuse >= 0 || tb->fastreuseport >= 0) {
1138 				rcu_read_unlock();
1139 				goto next_port;
1140 			}
1141 			if (!check_established(death_row, sk, port, &tw, true,
1142 					       hash_port0 + port))
1143 				break;
1144 			rcu_read_unlock();
1145 			goto next_port;
1146 		}
1147 		rcu_read_unlock();
1148 
1149 		spin_lock_bh(&head->lock);
1150 
1151 		/* Does not bother with rcv_saddr checks, because
1152 		 * the established check is already unique enough.
1153 		 */
1154 		inet_bind_bucket_for_each(tb, &head->chain) {
1155 			if (inet_bind_bucket_match(tb, net, port, l3mdev)) {
1156 				if (tb->fastreuse >= 0 ||
1157 				    tb->fastreuseport >= 0)
1158 					goto next_port_unlock;
1159 				WARN_ON(hlist_empty(&tb->bhash2));
1160 				if (!check_established(death_row, sk,
1161 						       port, &tw, false,
1162 						       hash_port0 + port))
1163 					goto ok;
1164 				goto next_port_unlock;
1165 			}
1166 		}
1167 
1168 		tb = inet_bind_bucket_create(hinfo->bind_bucket_cachep,
1169 					     net, head, port, l3mdev);
1170 		if (!tb) {
1171 			spin_unlock_bh(&head->lock);
1172 			return -ENOMEM;
1173 		}
1174 		tb_created = true;
1175 		tb->fastreuse = -1;
1176 		tb->fastreuseport = -1;
1177 		goto ok;
1178 next_port_unlock:
1179 		spin_unlock_bh(&head->lock);
1180 next_port:
1181 		cond_resched();
1182 	}
1183 
1184 	if (!local_ports) {
1185 		offset++;
1186 		if ((offset & 1) && remaining > 1)
1187 			goto other_parity_scan;
1188 	}
1189 	return -EADDRNOTAVAIL;
1190 
1191 ok:
1192 	/* Find the corresponding tb2 bucket since we need to
1193 	 * add the socket to the bhash2 table as well
1194 	 */
1195 	head2 = inet_bhashfn_portaddr(hinfo, sk, net, port);
1196 	spin_lock(&head2->lock);
1197 
1198 	tb2 = inet_bind2_bucket_find(head2, net, port, l3mdev, sk);
1199 	if (!tb2) {
1200 		tb2 = inet_bind2_bucket_create(hinfo->bind2_bucket_cachep, net,
1201 					       head2, tb, sk);
1202 		if (!tb2)
1203 			goto error;
1204 		tb2->fastreuse = -1;
1205 		tb2->fastreuseport = -1;
1206 	}
1207 
1208 	/* Here we want to add a little bit of randomness to the next source
1209 	 * port that will be chosen. We use a max() with a random here so that
1210 	 * on low contention the randomness is maximal and on high contention
1211 	 * it may be inexistent.
1212 	 */
1213 	i = max_t(int, i, get_random_u32_below(8) * step);
1214 	WRITE_ONCE(table_perturb[index], READ_ONCE(table_perturb[index]) + i + step);
1215 
1216 	/* Head lock still held and bh's disabled */
1217 	inet_bind_hash(sk, tb, tb2, port);
1218 	sk->sk_userlocks |= SOCK_CONNECT_BIND;
1219 
1220 	if (sk_unhashed(sk)) {
1221 		inet_sk(sk)->inet_sport = htons(port);
1222 		inet_ehash_nolisten(sk, (struct sock *)tw, NULL);
1223 	}
1224 	if (tw)
1225 		inet_twsk_bind_unhash(tw, hinfo);
1226 
1227 	spin_unlock(&head2->lock);
1228 	spin_unlock(&head->lock);
1229 
1230 	if (tw)
1231 		inet_twsk_deschedule_put(tw);
1232 	local_bh_enable();
1233 	return 0;
1234 
1235 error:
1236 	if (sk_hashed(sk)) {
1237 		spinlock_t *lock = inet_ehash_lockp(hinfo, sk->sk_hash);
1238 
1239 		sock_prot_inuse_add(net, sk->sk_prot, -1);
1240 
1241 		spin_lock(lock);
1242 		__sk_nulls_del_node_init_rcu(sk);
1243 		spin_unlock(lock);
1244 
1245 		sk->sk_hash = 0;
1246 		inet_sk(sk)->inet_sport = 0;
1247 		WRITE_ONCE(inet_sk(sk)->inet_num, 0);
1248 
1249 		if (tw)
1250 			inet_twsk_bind_unhash(tw, hinfo);
1251 	}
1252 
1253 	spin_unlock(&head2->lock);
1254 	if (tb_created)
1255 		inet_bind_bucket_destroy(tb);
1256 	spin_unlock(&head->lock);
1257 
1258 	if (tw)
1259 		inet_twsk_deschedule_put(tw);
1260 
1261 	local_bh_enable();
1262 
1263 	return -ENOMEM;
1264 }
1265 
1266 /*
1267  * Bind a port for a connect operation and hash it.
1268  */
1269 int inet_hash_connect(struct inet_timewait_death_row *death_row,
1270 		      struct sock *sk)
1271 {
1272 	const struct inet_sock *inet = inet_sk(sk);
1273 	const struct net *net = sock_net(sk);
1274 	u64 port_offset = 0;
1275 	u32 hash_port0;
1276 
1277 	if (!inet_sk(sk)->inet_num)
1278 		port_offset = inet_sk_port_offset(sk);
1279 
1280 	inet_init_ehash_secret();
1281 
1282 	hash_port0 = inet_ehashfn(net, inet->inet_rcv_saddr, 0,
1283 				  inet->inet_daddr, inet->inet_dport);
1284 
1285 	return __inet_hash_connect(death_row, sk, port_offset, hash_port0,
1286 				   __inet_check_established);
1287 }
1288 
1289 void __init inet_hashinfo2_init(struct inet_hashinfo *h, const char *name,
1290 				unsigned long numentries, int scale,
1291 				unsigned long low_limit,
1292 				unsigned long high_limit)
1293 {
1294 	unsigned int i;
1295 
1296 	h->lhash2 = alloc_large_system_hash(name,
1297 					    sizeof(*h->lhash2),
1298 					    numentries,
1299 					    scale,
1300 					    0,
1301 					    NULL,
1302 					    &h->lhash2_mask,
1303 					    low_limit,
1304 					    high_limit);
1305 
1306 	for (i = 0; i <= h->lhash2_mask; i++) {
1307 		spin_lock_init(&h->lhash2[i].lock);
1308 		INIT_HLIST_NULLS_HEAD(&h->lhash2[i].nulls_head,
1309 				      i + LISTENING_NULLS_BASE);
1310 	}
1311 
1312 	/* this one is used for source ports of outgoing connections */
1313 	table_perturb = alloc_large_system_hash("Table-perturb",
1314 						sizeof(*table_perturb),
1315 						INET_TABLE_PERTURB_SIZE,
1316 						0, 0, NULL, NULL,
1317 						INET_TABLE_PERTURB_SIZE,
1318 						INET_TABLE_PERTURB_SIZE);
1319 }
1320 
1321 int inet_ehash_locks_alloc(struct inet_hashinfo *hashinfo)
1322 {
1323 	unsigned int locksz = sizeof(spinlock_t);
1324 	unsigned int i, nblocks = 1;
1325 	spinlock_t *ptr = NULL;
1326 
1327 	if (locksz == 0)
1328 		goto set_mask;
1329 
1330 	/* Allocate 2 cache lines or at least one spinlock per cpu. */
1331 	nblocks = max(2U * L1_CACHE_BYTES / locksz, 1U) * num_possible_cpus();
1332 
1333 	/* At least one page per NUMA node. */
1334 	nblocks = max(nblocks, num_online_nodes() * PAGE_SIZE / locksz);
1335 
1336 	nblocks = roundup_pow_of_two(nblocks);
1337 
1338 	/* No more locks than number of hash buckets. */
1339 	nblocks = min(nblocks, hashinfo->ehash_mask + 1);
1340 
1341 	if (num_online_nodes() > 1) {
1342 		/* Use vmalloc() to allow NUMA policy to spread pages
1343 		 * on all available nodes if desired.
1344 		 */
1345 		ptr = vmalloc_array(nblocks, locksz);
1346 	}
1347 	if (!ptr) {
1348 		ptr = kvmalloc_array(nblocks, locksz, GFP_KERNEL);
1349 		if (!ptr)
1350 			return -ENOMEM;
1351 	}
1352 	for (i = 0; i < nblocks; i++)
1353 		spin_lock_init(&ptr[i]);
1354 	hashinfo->ehash_locks = ptr;
1355 set_mask:
1356 	hashinfo->ehash_locks_mask = nblocks - 1;
1357 	return 0;
1358 }
1359 
1360 struct inet_hashinfo *inet_pernet_hashinfo_alloc(struct inet_hashinfo *hashinfo,
1361 						 unsigned int ehash_entries)
1362 {
1363 	struct inet_hashinfo *new_hashinfo;
1364 	int i;
1365 
1366 	new_hashinfo = kmemdup(hashinfo, sizeof(*hashinfo), GFP_KERNEL);
1367 	if (!new_hashinfo)
1368 		goto err;
1369 
1370 	new_hashinfo->ehash = vmalloc_huge(ehash_entries * sizeof(struct inet_ehash_bucket),
1371 					   GFP_KERNEL_ACCOUNT);
1372 	if (!new_hashinfo->ehash)
1373 		goto free_hashinfo;
1374 
1375 	new_hashinfo->ehash_mask = ehash_entries - 1;
1376 
1377 	if (inet_ehash_locks_alloc(new_hashinfo))
1378 		goto free_ehash;
1379 
1380 	for (i = 0; i < ehash_entries; i++)
1381 		INIT_HLIST_NULLS_HEAD(&new_hashinfo->ehash[i].chain, i);
1382 
1383 	new_hashinfo->pernet = true;
1384 
1385 	return new_hashinfo;
1386 
1387 free_ehash:
1388 	vfree(new_hashinfo->ehash);
1389 free_hashinfo:
1390 	kfree(new_hashinfo);
1391 err:
1392 	return NULL;
1393 }
1394 
1395 void inet_pernet_hashinfo_free(struct inet_hashinfo *hashinfo)
1396 {
1397 	if (!hashinfo->pernet)
1398 		return;
1399 
1400 	inet_ehash_locks_free(hashinfo);
1401 	vfree(hashinfo->ehash);
1402 	kfree(hashinfo);
1403 }
1404