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