xref: /linux/net/ipv4/inet_hashtables.c (revision cad4977344b35ea116ec5fefe91a76b1dfa113f5)
1 /*
2  * INET		An implementation of the TCP/IP protocol suite for the LINUX
3  *		operating system.  INET is implemented using the BSD Socket
4  *		interface as the means of communication with the user level.
5  *
6  *		Generic INET transport hashtables
7  *
8  * Authors:	Lotsa people, from code originally in tcp
9  *
10  *	This program is free software; you can redistribute it and/or
11  *      modify it under the terms of the GNU General Public License
12  *      as published by the Free Software Foundation; either version
13  *      2 of the License, or (at your option) any later version.
14  */
15 
16 #include <linux/module.h>
17 #include <linux/random.h>
18 #include <linux/sched.h>
19 #include <linux/slab.h>
20 #include <linux/wait.h>
21 #include <linux/vmalloc.h>
22 #include <linux/memblock.h>
23 
24 #include <net/addrconf.h>
25 #include <net/inet_connection_sock.h>
26 #include <net/inet_hashtables.h>
27 #include <net/secure_seq.h>
28 #include <net/ip.h>
29 #include <net/tcp.h>
30 #include <net/sock_reuseport.h>
31 
32 static u32 inet_ehashfn(const struct net *net, const __be32 laddr,
33 			const __u16 lport, const __be32 faddr,
34 			const __be16 fport)
35 {
36 	static u32 inet_ehash_secret __read_mostly;
37 
38 	net_get_random_once(&inet_ehash_secret, sizeof(inet_ehash_secret));
39 
40 	return __inet_ehashfn(laddr, lport, faddr, fport,
41 			      inet_ehash_secret + net_hash_mix(net));
42 }
43 
44 /* This function handles inet_sock, but also timewait and request sockets
45  * for IPv4/IPv6.
46  */
47 static u32 sk_ehashfn(const struct sock *sk)
48 {
49 #if IS_ENABLED(CONFIG_IPV6)
50 	if (sk->sk_family == AF_INET6 &&
51 	    !ipv6_addr_v4mapped(&sk->sk_v6_daddr))
52 		return inet6_ehashfn(sock_net(sk),
53 				     &sk->sk_v6_rcv_saddr, sk->sk_num,
54 				     &sk->sk_v6_daddr, sk->sk_dport);
55 #endif
56 	return inet_ehashfn(sock_net(sk),
57 			    sk->sk_rcv_saddr, sk->sk_num,
58 			    sk->sk_daddr, sk->sk_dport);
59 }
60 
61 /*
62  * Allocate and initialize a new local port bind bucket.
63  * The bindhash mutex for snum's hash chain must be held here.
64  */
65 struct inet_bind_bucket *inet_bind_bucket_create(struct kmem_cache *cachep,
66 						 struct net *net,
67 						 struct inet_bind_hashbucket *head,
68 						 const unsigned short snum,
69 						 int l3mdev)
70 {
71 	struct inet_bind_bucket *tb = kmem_cache_alloc(cachep, GFP_ATOMIC);
72 
73 	if (tb) {
74 		write_pnet(&tb->ib_net, net);
75 		tb->l3mdev    = l3mdev;
76 		tb->port      = snum;
77 		tb->fastreuse = 0;
78 		tb->fastreuseport = 0;
79 		INIT_HLIST_HEAD(&tb->owners);
80 		hlist_add_head(&tb->node, &head->chain);
81 	}
82 	return tb;
83 }
84 
85 /*
86  * Caller must hold hashbucket lock for this tb with local BH disabled
87  */
88 void inet_bind_bucket_destroy(struct kmem_cache *cachep, struct inet_bind_bucket *tb)
89 {
90 	if (hlist_empty(&tb->owners)) {
91 		__hlist_del(&tb->node);
92 		kmem_cache_free(cachep, tb);
93 	}
94 }
95 
96 void inet_bind_hash(struct sock *sk, struct inet_bind_bucket *tb,
97 		    const unsigned short snum)
98 {
99 	inet_sk(sk)->inet_num = snum;
100 	sk_add_bind_node(sk, &tb->owners);
101 	inet_csk(sk)->icsk_bind_hash = tb;
102 }
103 
104 /*
105  * Get rid of any references to a local port held by the given sock.
106  */
107 static void __inet_put_port(struct sock *sk)
108 {
109 	struct inet_hashinfo *hashinfo = sk->sk_prot->h.hashinfo;
110 	const int bhash = inet_bhashfn(sock_net(sk), inet_sk(sk)->inet_num,
111 			hashinfo->bhash_size);
112 	struct inet_bind_hashbucket *head = &hashinfo->bhash[bhash];
113 	struct inet_bind_bucket *tb;
114 
115 	spin_lock(&head->lock);
116 	tb = inet_csk(sk)->icsk_bind_hash;
117 	__sk_del_bind_node(sk);
118 	inet_csk(sk)->icsk_bind_hash = NULL;
119 	inet_sk(sk)->inet_num = 0;
120 	inet_bind_bucket_destroy(hashinfo->bind_bucket_cachep, tb);
121 	spin_unlock(&head->lock);
122 }
123 
124 void inet_put_port(struct sock *sk)
125 {
126 	local_bh_disable();
127 	__inet_put_port(sk);
128 	local_bh_enable();
129 }
130 EXPORT_SYMBOL(inet_put_port);
131 
132 int __inet_inherit_port(const struct sock *sk, struct sock *child)
133 {
134 	struct inet_hashinfo *table = sk->sk_prot->h.hashinfo;
135 	unsigned short port = inet_sk(child)->inet_num;
136 	const int bhash = inet_bhashfn(sock_net(sk), port,
137 			table->bhash_size);
138 	struct inet_bind_hashbucket *head = &table->bhash[bhash];
139 	struct inet_bind_bucket *tb;
140 	int l3mdev;
141 
142 	spin_lock(&head->lock);
143 	tb = inet_csk(sk)->icsk_bind_hash;
144 	if (unlikely(!tb)) {
145 		spin_unlock(&head->lock);
146 		return -ENOENT;
147 	}
148 	if (tb->port != port) {
149 		l3mdev = inet_sk_bound_l3mdev(sk);
150 
151 		/* NOTE: using tproxy and redirecting skbs to a proxy
152 		 * on a different listener port breaks the assumption
153 		 * that the listener socket's icsk_bind_hash is the same
154 		 * as that of the child socket. We have to look up or
155 		 * create a new bind bucket for the child here. */
156 		inet_bind_bucket_for_each(tb, &head->chain) {
157 			if (net_eq(ib_net(tb), sock_net(sk)) &&
158 			    tb->l3mdev == l3mdev && tb->port == port)
159 				break;
160 		}
161 		if (!tb) {
162 			tb = inet_bind_bucket_create(table->bind_bucket_cachep,
163 						     sock_net(sk), head, port,
164 						     l3mdev);
165 			if (!tb) {
166 				spin_unlock(&head->lock);
167 				return -ENOMEM;
168 			}
169 		}
170 	}
171 	inet_bind_hash(child, tb, port);
172 	spin_unlock(&head->lock);
173 
174 	return 0;
175 }
176 EXPORT_SYMBOL_GPL(__inet_inherit_port);
177 
178 static struct inet_listen_hashbucket *
179 inet_lhash2_bucket_sk(struct inet_hashinfo *h, struct sock *sk)
180 {
181 	u32 hash;
182 
183 #if IS_ENABLED(CONFIG_IPV6)
184 	if (sk->sk_family == AF_INET6)
185 		hash = ipv6_portaddr_hash(sock_net(sk),
186 					  &sk->sk_v6_rcv_saddr,
187 					  inet_sk(sk)->inet_num);
188 	else
189 #endif
190 		hash = ipv4_portaddr_hash(sock_net(sk),
191 					  inet_sk(sk)->inet_rcv_saddr,
192 					  inet_sk(sk)->inet_num);
193 	return inet_lhash2_bucket(h, hash);
194 }
195 
196 static void inet_hash2(struct inet_hashinfo *h, struct sock *sk)
197 {
198 	struct inet_listen_hashbucket *ilb2;
199 
200 	if (!h->lhash2)
201 		return;
202 
203 	ilb2 = inet_lhash2_bucket_sk(h, sk);
204 
205 	spin_lock(&ilb2->lock);
206 	if (sk->sk_reuseport && sk->sk_family == AF_INET6)
207 		hlist_add_tail_rcu(&inet_csk(sk)->icsk_listen_portaddr_node,
208 				   &ilb2->head);
209 	else
210 		hlist_add_head_rcu(&inet_csk(sk)->icsk_listen_portaddr_node,
211 				   &ilb2->head);
212 	ilb2->count++;
213 	spin_unlock(&ilb2->lock);
214 }
215 
216 static void inet_unhash2(struct inet_hashinfo *h, struct sock *sk)
217 {
218 	struct inet_listen_hashbucket *ilb2;
219 
220 	if (!h->lhash2 ||
221 	    WARN_ON_ONCE(hlist_unhashed(&inet_csk(sk)->icsk_listen_portaddr_node)))
222 		return;
223 
224 	ilb2 = inet_lhash2_bucket_sk(h, sk);
225 
226 	spin_lock(&ilb2->lock);
227 	hlist_del_init_rcu(&inet_csk(sk)->icsk_listen_portaddr_node);
228 	ilb2->count--;
229 	spin_unlock(&ilb2->lock);
230 }
231 
232 static inline int compute_score(struct sock *sk, struct net *net,
233 				const unsigned short hnum, const __be32 daddr,
234 				const int dif, const int sdif, bool exact_dif)
235 {
236 	int score = -1;
237 	struct inet_sock *inet = inet_sk(sk);
238 	bool dev_match;
239 
240 	if (net_eq(sock_net(sk), net) && inet->inet_num == hnum &&
241 			!ipv6_only_sock(sk)) {
242 		__be32 rcv_saddr = inet->inet_rcv_saddr;
243 		score = sk->sk_family == PF_INET ? 2 : 1;
244 		if (rcv_saddr) {
245 			if (rcv_saddr != daddr)
246 				return -1;
247 			score += 4;
248 		}
249 		dev_match = inet_sk_bound_dev_eq(net, sk->sk_bound_dev_if,
250 						 dif, sdif);
251 		if (!dev_match)
252 			return -1;
253 		score += 4;
254 
255 		if (sk->sk_incoming_cpu == raw_smp_processor_id())
256 			score++;
257 	}
258 	return score;
259 }
260 
261 /*
262  * Here are some nice properties to exploit here. The BSD API
263  * does not allow a listening sock to specify the remote port nor the
264  * remote address for the connection. So always assume those are both
265  * wildcarded during the search since they can never be otherwise.
266  */
267 
268 /* called with rcu_read_lock() : No refcount taken on the socket */
269 static struct sock *inet_lhash2_lookup(struct net *net,
270 				struct inet_listen_hashbucket *ilb2,
271 				struct sk_buff *skb, int doff,
272 				const __be32 saddr, __be16 sport,
273 				const __be32 daddr, const unsigned short hnum,
274 				const int dif, const int sdif)
275 {
276 	bool exact_dif = inet_exact_dif_match(net, skb);
277 	struct inet_connection_sock *icsk;
278 	struct sock *sk, *result = NULL;
279 	int score, hiscore = 0;
280 	u32 phash = 0;
281 
282 	inet_lhash2_for_each_icsk_rcu(icsk, &ilb2->head) {
283 		sk = (struct sock *)icsk;
284 		score = compute_score(sk, net, hnum, daddr,
285 				      dif, sdif, exact_dif);
286 		if (score > hiscore) {
287 			if (sk->sk_reuseport) {
288 				phash = inet_ehashfn(net, daddr, hnum,
289 						     saddr, sport);
290 				result = reuseport_select_sock(sk, phash,
291 							       skb, doff);
292 				if (result)
293 					return result;
294 			}
295 			result = sk;
296 			hiscore = score;
297 		}
298 	}
299 
300 	return result;
301 }
302 
303 struct sock *__inet_lookup_listener(struct net *net,
304 				    struct inet_hashinfo *hashinfo,
305 				    struct sk_buff *skb, int doff,
306 				    const __be32 saddr, __be16 sport,
307 				    const __be32 daddr, const unsigned short hnum,
308 				    const int dif, const int sdif)
309 {
310 	unsigned int hash = inet_lhashfn(net, hnum);
311 	struct inet_listen_hashbucket *ilb = &hashinfo->listening_hash[hash];
312 	bool exact_dif = inet_exact_dif_match(net, skb);
313 	struct inet_listen_hashbucket *ilb2;
314 	struct sock *sk, *result = NULL;
315 	int score, hiscore = 0;
316 	unsigned int hash2;
317 	u32 phash = 0;
318 
319 	if (ilb->count <= 10 || !hashinfo->lhash2)
320 		goto port_lookup;
321 
322 	/* Too many sk in the ilb bucket (which is hashed by port alone).
323 	 * Try lhash2 (which is hashed by port and addr) instead.
324 	 */
325 
326 	hash2 = ipv4_portaddr_hash(net, daddr, hnum);
327 	ilb2 = inet_lhash2_bucket(hashinfo, hash2);
328 	if (ilb2->count > ilb->count)
329 		goto port_lookup;
330 
331 	result = inet_lhash2_lookup(net, ilb2, skb, doff,
332 				    saddr, sport, daddr, hnum,
333 				    dif, sdif);
334 	if (result)
335 		goto done;
336 
337 	/* Lookup lhash2 with INADDR_ANY */
338 
339 	hash2 = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum);
340 	ilb2 = inet_lhash2_bucket(hashinfo, hash2);
341 	if (ilb2->count > ilb->count)
342 		goto port_lookup;
343 
344 	result = inet_lhash2_lookup(net, ilb2, skb, doff,
345 				    saddr, sport, daddr, hnum,
346 				    dif, sdif);
347 	goto done;
348 
349 port_lookup:
350 	sk_for_each_rcu(sk, &ilb->head) {
351 		score = compute_score(sk, net, hnum, daddr,
352 				      dif, sdif, exact_dif);
353 		if (score > hiscore) {
354 			if (sk->sk_reuseport) {
355 				phash = inet_ehashfn(net, daddr, hnum,
356 						     saddr, sport);
357 				result = reuseport_select_sock(sk, phash,
358 							       skb, doff);
359 				if (result)
360 					goto done;
361 			}
362 			result = sk;
363 			hiscore = score;
364 		}
365 	}
366 done:
367 	if (unlikely(IS_ERR(result)))
368 		return NULL;
369 	return result;
370 }
371 EXPORT_SYMBOL_GPL(__inet_lookup_listener);
372 
373 /* All sockets share common refcount, but have different destructors */
374 void sock_gen_put(struct sock *sk)
375 {
376 	if (!refcount_dec_and_test(&sk->sk_refcnt))
377 		return;
378 
379 	if (sk->sk_state == TCP_TIME_WAIT)
380 		inet_twsk_free(inet_twsk(sk));
381 	else if (sk->sk_state == TCP_NEW_SYN_RECV)
382 		reqsk_free(inet_reqsk(sk));
383 	else
384 		sk_free(sk);
385 }
386 EXPORT_SYMBOL_GPL(sock_gen_put);
387 
388 void sock_edemux(struct sk_buff *skb)
389 {
390 	sock_gen_put(skb->sk);
391 }
392 EXPORT_SYMBOL(sock_edemux);
393 
394 struct sock *__inet_lookup_established(struct net *net,
395 				  struct inet_hashinfo *hashinfo,
396 				  const __be32 saddr, const __be16 sport,
397 				  const __be32 daddr, const u16 hnum,
398 				  const int dif, const int sdif)
399 {
400 	INET_ADDR_COOKIE(acookie, saddr, daddr);
401 	const __portpair ports = INET_COMBINED_PORTS(sport, hnum);
402 	struct sock *sk;
403 	const struct hlist_nulls_node *node;
404 	/* Optimize here for direct hit, only listening connections can
405 	 * have wildcards anyways.
406 	 */
407 	unsigned int hash = inet_ehashfn(net, daddr, hnum, saddr, sport);
408 	unsigned int slot = hash & hashinfo->ehash_mask;
409 	struct inet_ehash_bucket *head = &hashinfo->ehash[slot];
410 
411 begin:
412 	sk_nulls_for_each_rcu(sk, node, &head->chain) {
413 		if (sk->sk_hash != hash)
414 			continue;
415 		if (likely(INET_MATCH(sk, net, acookie,
416 				      saddr, daddr, ports, dif, sdif))) {
417 			if (unlikely(!refcount_inc_not_zero(&sk->sk_refcnt)))
418 				goto out;
419 			if (unlikely(!INET_MATCH(sk, net, acookie,
420 						 saddr, daddr, ports,
421 						 dif, sdif))) {
422 				sock_gen_put(sk);
423 				goto begin;
424 			}
425 			goto found;
426 		}
427 	}
428 	/*
429 	 * if the nulls value we got at the end of this lookup is
430 	 * not the expected one, we must restart lookup.
431 	 * We probably met an item that was moved to another chain.
432 	 */
433 	if (get_nulls_value(node) != slot)
434 		goto begin;
435 out:
436 	sk = NULL;
437 found:
438 	return sk;
439 }
440 EXPORT_SYMBOL_GPL(__inet_lookup_established);
441 
442 /* called with local bh disabled */
443 static int __inet_check_established(struct inet_timewait_death_row *death_row,
444 				    struct sock *sk, __u16 lport,
445 				    struct inet_timewait_sock **twp)
446 {
447 	struct inet_hashinfo *hinfo = death_row->hashinfo;
448 	struct inet_sock *inet = inet_sk(sk);
449 	__be32 daddr = inet->inet_rcv_saddr;
450 	__be32 saddr = inet->inet_daddr;
451 	int dif = sk->sk_bound_dev_if;
452 	struct net *net = sock_net(sk);
453 	int sdif = l3mdev_master_ifindex_by_index(net, dif);
454 	INET_ADDR_COOKIE(acookie, saddr, daddr);
455 	const __portpair ports = INET_COMBINED_PORTS(inet->inet_dport, lport);
456 	unsigned int hash = inet_ehashfn(net, daddr, lport,
457 					 saddr, inet->inet_dport);
458 	struct inet_ehash_bucket *head = inet_ehash_bucket(hinfo, hash);
459 	spinlock_t *lock = inet_ehash_lockp(hinfo, hash);
460 	struct sock *sk2;
461 	const struct hlist_nulls_node *node;
462 	struct inet_timewait_sock *tw = NULL;
463 
464 	spin_lock(lock);
465 
466 	sk_nulls_for_each(sk2, node, &head->chain) {
467 		if (sk2->sk_hash != hash)
468 			continue;
469 
470 		if (likely(INET_MATCH(sk2, net, acookie,
471 					 saddr, daddr, ports, dif, sdif))) {
472 			if (sk2->sk_state == TCP_TIME_WAIT) {
473 				tw = inet_twsk(sk2);
474 				if (twsk_unique(sk, sk2, twp))
475 					break;
476 			}
477 			goto not_unique;
478 		}
479 	}
480 
481 	/* Must record num and sport now. Otherwise we will see
482 	 * in hash table socket with a funny identity.
483 	 */
484 	inet->inet_num = lport;
485 	inet->inet_sport = htons(lport);
486 	sk->sk_hash = hash;
487 	WARN_ON(!sk_unhashed(sk));
488 	__sk_nulls_add_node_rcu(sk, &head->chain);
489 	if (tw) {
490 		sk_nulls_del_node_init_rcu((struct sock *)tw);
491 		__NET_INC_STATS(net, LINUX_MIB_TIMEWAITRECYCLED);
492 	}
493 	spin_unlock(lock);
494 	sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
495 
496 	if (twp) {
497 		*twp = tw;
498 	} else if (tw) {
499 		/* Silly. Should hash-dance instead... */
500 		inet_twsk_deschedule_put(tw);
501 	}
502 	return 0;
503 
504 not_unique:
505 	spin_unlock(lock);
506 	return -EADDRNOTAVAIL;
507 }
508 
509 static u32 inet_sk_port_offset(const struct sock *sk)
510 {
511 	const struct inet_sock *inet = inet_sk(sk);
512 
513 	return secure_ipv4_port_ephemeral(inet->inet_rcv_saddr,
514 					  inet->inet_daddr,
515 					  inet->inet_dport);
516 }
517 
518 /* insert a socket into ehash, and eventually remove another one
519  * (The another one can be a SYN_RECV or TIMEWAIT
520  */
521 bool inet_ehash_insert(struct sock *sk, struct sock *osk)
522 {
523 	struct inet_hashinfo *hashinfo = sk->sk_prot->h.hashinfo;
524 	struct hlist_nulls_head *list;
525 	struct inet_ehash_bucket *head;
526 	spinlock_t *lock;
527 	bool ret = true;
528 
529 	WARN_ON_ONCE(!sk_unhashed(sk));
530 
531 	sk->sk_hash = sk_ehashfn(sk);
532 	head = inet_ehash_bucket(hashinfo, sk->sk_hash);
533 	list = &head->chain;
534 	lock = inet_ehash_lockp(hashinfo, sk->sk_hash);
535 
536 	spin_lock(lock);
537 	if (osk) {
538 		WARN_ON_ONCE(sk->sk_hash != osk->sk_hash);
539 		ret = sk_nulls_del_node_init_rcu(osk);
540 	}
541 	if (ret)
542 		__sk_nulls_add_node_rcu(sk, list);
543 	spin_unlock(lock);
544 	return ret;
545 }
546 
547 bool inet_ehash_nolisten(struct sock *sk, struct sock *osk)
548 {
549 	bool ok = inet_ehash_insert(sk, osk);
550 
551 	if (ok) {
552 		sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
553 	} else {
554 		percpu_counter_inc(sk->sk_prot->orphan_count);
555 		inet_sk_set_state(sk, TCP_CLOSE);
556 		sock_set_flag(sk, SOCK_DEAD);
557 		inet_csk_destroy_sock(sk);
558 	}
559 	return ok;
560 }
561 EXPORT_SYMBOL_GPL(inet_ehash_nolisten);
562 
563 static int inet_reuseport_add_sock(struct sock *sk,
564 				   struct inet_listen_hashbucket *ilb)
565 {
566 	struct inet_bind_bucket *tb = inet_csk(sk)->icsk_bind_hash;
567 	struct sock *sk2;
568 	kuid_t uid = sock_i_uid(sk);
569 
570 	sk_for_each_rcu(sk2, &ilb->head) {
571 		if (sk2 != sk &&
572 		    sk2->sk_family == sk->sk_family &&
573 		    ipv6_only_sock(sk2) == ipv6_only_sock(sk) &&
574 		    sk2->sk_bound_dev_if == sk->sk_bound_dev_if &&
575 		    inet_csk(sk2)->icsk_bind_hash == tb &&
576 		    sk2->sk_reuseport && uid_eq(uid, sock_i_uid(sk2)) &&
577 		    inet_rcv_saddr_equal(sk, sk2, false))
578 			return reuseport_add_sock(sk, sk2,
579 						  inet_rcv_saddr_any(sk));
580 	}
581 
582 	return reuseport_alloc(sk, inet_rcv_saddr_any(sk));
583 }
584 
585 int __inet_hash(struct sock *sk, struct sock *osk)
586 {
587 	struct inet_hashinfo *hashinfo = sk->sk_prot->h.hashinfo;
588 	struct inet_listen_hashbucket *ilb;
589 	int err = 0;
590 
591 	if (sk->sk_state != TCP_LISTEN) {
592 		inet_ehash_nolisten(sk, osk);
593 		return 0;
594 	}
595 	WARN_ON(!sk_unhashed(sk));
596 	ilb = &hashinfo->listening_hash[inet_sk_listen_hashfn(sk)];
597 
598 	spin_lock(&ilb->lock);
599 	if (sk->sk_reuseport) {
600 		err = inet_reuseport_add_sock(sk, ilb);
601 		if (err)
602 			goto unlock;
603 	}
604 	if (IS_ENABLED(CONFIG_IPV6) && sk->sk_reuseport &&
605 		sk->sk_family == AF_INET6)
606 		hlist_add_tail_rcu(&sk->sk_node, &ilb->head);
607 	else
608 		hlist_add_head_rcu(&sk->sk_node, &ilb->head);
609 	inet_hash2(hashinfo, sk);
610 	ilb->count++;
611 	sock_set_flag(sk, SOCK_RCU_FREE);
612 	sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
613 unlock:
614 	spin_unlock(&ilb->lock);
615 
616 	return err;
617 }
618 EXPORT_SYMBOL(__inet_hash);
619 
620 int inet_hash(struct sock *sk)
621 {
622 	int err = 0;
623 
624 	if (sk->sk_state != TCP_CLOSE) {
625 		local_bh_disable();
626 		err = __inet_hash(sk, NULL);
627 		local_bh_enable();
628 	}
629 
630 	return err;
631 }
632 EXPORT_SYMBOL_GPL(inet_hash);
633 
634 void inet_unhash(struct sock *sk)
635 {
636 	struct inet_hashinfo *hashinfo = sk->sk_prot->h.hashinfo;
637 	struct inet_listen_hashbucket *ilb = NULL;
638 	spinlock_t *lock;
639 
640 	if (sk_unhashed(sk))
641 		return;
642 
643 	if (sk->sk_state == TCP_LISTEN) {
644 		ilb = &hashinfo->listening_hash[inet_sk_listen_hashfn(sk)];
645 		lock = &ilb->lock;
646 	} else {
647 		lock = inet_ehash_lockp(hashinfo, sk->sk_hash);
648 	}
649 	spin_lock_bh(lock);
650 	if (sk_unhashed(sk))
651 		goto unlock;
652 
653 	if (rcu_access_pointer(sk->sk_reuseport_cb))
654 		reuseport_detach_sock(sk);
655 	if (ilb) {
656 		inet_unhash2(hashinfo, sk);
657 		 __sk_del_node_init(sk);
658 		 ilb->count--;
659 	} else {
660 		__sk_nulls_del_node_init_rcu(sk);
661 	}
662 	sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
663 unlock:
664 	spin_unlock_bh(lock);
665 }
666 EXPORT_SYMBOL_GPL(inet_unhash);
667 
668 int __inet_hash_connect(struct inet_timewait_death_row *death_row,
669 		struct sock *sk, u32 port_offset,
670 		int (*check_established)(struct inet_timewait_death_row *,
671 			struct sock *, __u16, struct inet_timewait_sock **))
672 {
673 	struct inet_hashinfo *hinfo = death_row->hashinfo;
674 	struct inet_timewait_sock *tw = NULL;
675 	struct inet_bind_hashbucket *head;
676 	int port = inet_sk(sk)->inet_num;
677 	struct net *net = sock_net(sk);
678 	struct inet_bind_bucket *tb;
679 	u32 remaining, offset;
680 	int ret, i, low, high;
681 	static u32 hint;
682 	int l3mdev;
683 
684 	if (port) {
685 		head = &hinfo->bhash[inet_bhashfn(net, port,
686 						  hinfo->bhash_size)];
687 		tb = inet_csk(sk)->icsk_bind_hash;
688 		spin_lock_bh(&head->lock);
689 		if (sk_head(&tb->owners) == sk && !sk->sk_bind_node.next) {
690 			inet_ehash_nolisten(sk, NULL);
691 			spin_unlock_bh(&head->lock);
692 			return 0;
693 		}
694 		spin_unlock(&head->lock);
695 		/* No definite answer... Walk to established hash table */
696 		ret = check_established(death_row, sk, port, NULL);
697 		local_bh_enable();
698 		return ret;
699 	}
700 
701 	l3mdev = inet_sk_bound_l3mdev(sk);
702 
703 	inet_get_local_port_range(net, &low, &high);
704 	high++; /* [32768, 60999] -> [32768, 61000[ */
705 	remaining = high - low;
706 	if (likely(remaining > 1))
707 		remaining &= ~1U;
708 
709 	offset = (hint + port_offset) % remaining;
710 	/* In first pass we try ports of @low parity.
711 	 * inet_csk_get_port() does the opposite choice.
712 	 */
713 	offset &= ~1U;
714 other_parity_scan:
715 	port = low + offset;
716 	for (i = 0; i < remaining; i += 2, port += 2) {
717 		if (unlikely(port >= high))
718 			port -= remaining;
719 		if (inet_is_local_reserved_port(net, port))
720 			continue;
721 		head = &hinfo->bhash[inet_bhashfn(net, port,
722 						  hinfo->bhash_size)];
723 		spin_lock_bh(&head->lock);
724 
725 		/* Does not bother with rcv_saddr checks, because
726 		 * the established check is already unique enough.
727 		 */
728 		inet_bind_bucket_for_each(tb, &head->chain) {
729 			if (net_eq(ib_net(tb), net) && tb->l3mdev == l3mdev &&
730 			    tb->port == port) {
731 				if (tb->fastreuse >= 0 ||
732 				    tb->fastreuseport >= 0)
733 					goto next_port;
734 				WARN_ON(hlist_empty(&tb->owners));
735 				if (!check_established(death_row, sk,
736 						       port, &tw))
737 					goto ok;
738 				goto next_port;
739 			}
740 		}
741 
742 		tb = inet_bind_bucket_create(hinfo->bind_bucket_cachep,
743 					     net, head, port, l3mdev);
744 		if (!tb) {
745 			spin_unlock_bh(&head->lock);
746 			return -ENOMEM;
747 		}
748 		tb->fastreuse = -1;
749 		tb->fastreuseport = -1;
750 		goto ok;
751 next_port:
752 		spin_unlock_bh(&head->lock);
753 		cond_resched();
754 	}
755 
756 	offset++;
757 	if ((offset & 1) && remaining > 1)
758 		goto other_parity_scan;
759 
760 	return -EADDRNOTAVAIL;
761 
762 ok:
763 	hint += i + 2;
764 
765 	/* Head lock still held and bh's disabled */
766 	inet_bind_hash(sk, tb, port);
767 	if (sk_unhashed(sk)) {
768 		inet_sk(sk)->inet_sport = htons(port);
769 		inet_ehash_nolisten(sk, (struct sock *)tw);
770 	}
771 	if (tw)
772 		inet_twsk_bind_unhash(tw, hinfo);
773 	spin_unlock(&head->lock);
774 	if (tw)
775 		inet_twsk_deschedule_put(tw);
776 	local_bh_enable();
777 	return 0;
778 }
779 
780 /*
781  * Bind a port for a connect operation and hash it.
782  */
783 int inet_hash_connect(struct inet_timewait_death_row *death_row,
784 		      struct sock *sk)
785 {
786 	u32 port_offset = 0;
787 
788 	if (!inet_sk(sk)->inet_num)
789 		port_offset = inet_sk_port_offset(sk);
790 	return __inet_hash_connect(death_row, sk, port_offset,
791 				   __inet_check_established);
792 }
793 EXPORT_SYMBOL_GPL(inet_hash_connect);
794 
795 void inet_hashinfo_init(struct inet_hashinfo *h)
796 {
797 	int i;
798 
799 	for (i = 0; i < INET_LHTABLE_SIZE; i++) {
800 		spin_lock_init(&h->listening_hash[i].lock);
801 		INIT_HLIST_HEAD(&h->listening_hash[i].head);
802 		h->listening_hash[i].count = 0;
803 	}
804 
805 	h->lhash2 = NULL;
806 }
807 EXPORT_SYMBOL_GPL(inet_hashinfo_init);
808 
809 void __init inet_hashinfo2_init(struct inet_hashinfo *h, const char *name,
810 				unsigned long numentries, int scale,
811 				unsigned long low_limit,
812 				unsigned long high_limit)
813 {
814 	unsigned int i;
815 
816 	h->lhash2 = alloc_large_system_hash(name,
817 					    sizeof(*h->lhash2),
818 					    numentries,
819 					    scale,
820 					    0,
821 					    NULL,
822 					    &h->lhash2_mask,
823 					    low_limit,
824 					    high_limit);
825 
826 	for (i = 0; i <= h->lhash2_mask; i++) {
827 		spin_lock_init(&h->lhash2[i].lock);
828 		INIT_HLIST_HEAD(&h->lhash2[i].head);
829 		h->lhash2[i].count = 0;
830 	}
831 }
832 
833 int inet_ehash_locks_alloc(struct inet_hashinfo *hashinfo)
834 {
835 	unsigned int locksz = sizeof(spinlock_t);
836 	unsigned int i, nblocks = 1;
837 
838 	if (locksz != 0) {
839 		/* allocate 2 cache lines or at least one spinlock per cpu */
840 		nblocks = max(2U * L1_CACHE_BYTES / locksz, 1U);
841 		nblocks = roundup_pow_of_two(nblocks * num_possible_cpus());
842 
843 		/* no more locks than number of hash buckets */
844 		nblocks = min(nblocks, hashinfo->ehash_mask + 1);
845 
846 		hashinfo->ehash_locks = kvmalloc_array(nblocks, locksz, GFP_KERNEL);
847 		if (!hashinfo->ehash_locks)
848 			return -ENOMEM;
849 
850 		for (i = 0; i < nblocks; i++)
851 			spin_lock_init(&hashinfo->ehash_locks[i]);
852 	}
853 	hashinfo->ehash_locks_mask = nblocks - 1;
854 	return 0;
855 }
856 EXPORT_SYMBOL_GPL(inet_ehash_locks_alloc);
857