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