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