Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-or-later
0002 /*
0003  * INET     An implementation of the TCP/IP protocol suite for the LINUX
0004  *      operating system.  INET is implemented using the BSD Socket
0005  *      interface as the means of communication with the user level.
0006  *
0007  *      Generic INET transport hashtables
0008  *
0009  * Authors: Lotsa people, from code originally in tcp
0010  */
0011 
0012 #include <linux/module.h>
0013 #include <linux/random.h>
0014 #include <linux/sched.h>
0015 #include <linux/slab.h>
0016 #include <linux/wait.h>
0017 #include <linux/vmalloc.h>
0018 #include <linux/memblock.h>
0019 
0020 #include <net/addrconf.h>
0021 #include <net/inet_connection_sock.h>
0022 #include <net/inet_hashtables.h>
0023 #if IS_ENABLED(CONFIG_IPV6)
0024 #include <net/inet6_hashtables.h>
0025 #endif
0026 #include <net/secure_seq.h>
0027 #include <net/ip.h>
0028 #include <net/tcp.h>
0029 #include <net/sock_reuseport.h>
0030 
0031 static u32 inet_ehashfn(const struct net *net, const __be32 laddr,
0032             const __u16 lport, const __be32 faddr,
0033             const __be16 fport)
0034 {
0035     static u32 inet_ehash_secret __read_mostly;
0036 
0037     net_get_random_once(&inet_ehash_secret, sizeof(inet_ehash_secret));
0038 
0039     return __inet_ehashfn(laddr, lport, faddr, fport,
0040                   inet_ehash_secret + net_hash_mix(net));
0041 }
0042 
0043 /* This function handles inet_sock, but also timewait and request sockets
0044  * for IPv4/IPv6.
0045  */
0046 static u32 sk_ehashfn(const struct sock *sk)
0047 {
0048 #if IS_ENABLED(CONFIG_IPV6)
0049     if (sk->sk_family == AF_INET6 &&
0050         !ipv6_addr_v4mapped(&sk->sk_v6_daddr))
0051         return inet6_ehashfn(sock_net(sk),
0052                      &sk->sk_v6_rcv_saddr, sk->sk_num,
0053                      &sk->sk_v6_daddr, sk->sk_dport);
0054 #endif
0055     return inet_ehashfn(sock_net(sk),
0056                 sk->sk_rcv_saddr, sk->sk_num,
0057                 sk->sk_daddr, sk->sk_dport);
0058 }
0059 
0060 /*
0061  * Allocate and initialize a new local port bind bucket.
0062  * The bindhash mutex for snum's hash chain must be held here.
0063  */
0064 struct inet_bind_bucket *inet_bind_bucket_create(struct kmem_cache *cachep,
0065                          struct net *net,
0066                          struct inet_bind_hashbucket *head,
0067                          const unsigned short snum,
0068                          int l3mdev)
0069 {
0070     struct inet_bind_bucket *tb = kmem_cache_alloc(cachep, GFP_ATOMIC);
0071 
0072     if (tb) {
0073         write_pnet(&tb->ib_net, net);
0074         tb->l3mdev    = l3mdev;
0075         tb->port      = snum;
0076         tb->fastreuse = 0;
0077         tb->fastreuseport = 0;
0078         INIT_HLIST_HEAD(&tb->owners);
0079         hlist_add_head(&tb->node, &head->chain);
0080     }
0081     return tb;
0082 }
0083 
0084 /*
0085  * Caller must hold hashbucket lock for this tb with local BH disabled
0086  */
0087 void inet_bind_bucket_destroy(struct kmem_cache *cachep, struct inet_bind_bucket *tb)
0088 {
0089     if (hlist_empty(&tb->owners)) {
0090         __hlist_del(&tb->node);
0091         kmem_cache_free(cachep, tb);
0092     }
0093 }
0094 
0095 void inet_bind_hash(struct sock *sk, struct inet_bind_bucket *tb,
0096             const unsigned short snum)
0097 {
0098     inet_sk(sk)->inet_num = snum;
0099     sk_add_bind_node(sk, &tb->owners);
0100     inet_csk(sk)->icsk_bind_hash = tb;
0101 }
0102 
0103 /*
0104  * Get rid of any references to a local port held by the given sock.
0105  */
0106 static void __inet_put_port(struct sock *sk)
0107 {
0108     struct inet_hashinfo *hashinfo = sk->sk_prot->h.hashinfo;
0109     const int bhash = inet_bhashfn(sock_net(sk), inet_sk(sk)->inet_num,
0110             hashinfo->bhash_size);
0111     struct inet_bind_hashbucket *head = &hashinfo->bhash[bhash];
0112     struct inet_bind_bucket *tb;
0113 
0114     spin_lock(&head->lock);
0115     tb = inet_csk(sk)->icsk_bind_hash;
0116     __sk_del_bind_node(sk);
0117     inet_csk(sk)->icsk_bind_hash = NULL;
0118     inet_sk(sk)->inet_num = 0;
0119     inet_bind_bucket_destroy(hashinfo->bind_bucket_cachep, tb);
0120     spin_unlock(&head->lock);
0121 }
0122 
0123 void inet_put_port(struct sock *sk)
0124 {
0125     local_bh_disable();
0126     __inet_put_port(sk);
0127     local_bh_enable();
0128 }
0129 EXPORT_SYMBOL(inet_put_port);
0130 
0131 int __inet_inherit_port(const struct sock *sk, struct sock *child)
0132 {
0133     struct inet_hashinfo *table = sk->sk_prot->h.hashinfo;
0134     unsigned short port = inet_sk(child)->inet_num;
0135     const int bhash = inet_bhashfn(sock_net(sk), port,
0136             table->bhash_size);
0137     struct inet_bind_hashbucket *head = &table->bhash[bhash];
0138     struct inet_bind_bucket *tb;
0139     int l3mdev;
0140 
0141     spin_lock(&head->lock);
0142     tb = inet_csk(sk)->icsk_bind_hash;
0143     if (unlikely(!tb)) {
0144         spin_unlock(&head->lock);
0145         return -ENOENT;
0146     }
0147     if (tb->port != port) {
0148         l3mdev = inet_sk_bound_l3mdev(sk);
0149 
0150         /* NOTE: using tproxy and redirecting skbs to a proxy
0151          * on a different listener port breaks the assumption
0152          * that the listener socket's icsk_bind_hash is the same
0153          * as that of the child socket. We have to look up or
0154          * create a new bind bucket for the child here. */
0155         inet_bind_bucket_for_each(tb, &head->chain) {
0156             if (net_eq(ib_net(tb), sock_net(sk)) &&
0157                 tb->l3mdev == l3mdev && tb->port == port)
0158                 break;
0159         }
0160         if (!tb) {
0161             tb = inet_bind_bucket_create(table->bind_bucket_cachep,
0162                              sock_net(sk), head, port,
0163                              l3mdev);
0164             if (!tb) {
0165                 spin_unlock(&head->lock);
0166                 return -ENOMEM;
0167             }
0168         }
0169         inet_csk_update_fastreuse(tb, child);
0170     }
0171     inet_bind_hash(child, tb, port);
0172     spin_unlock(&head->lock);
0173 
0174     return 0;
0175 }
0176 EXPORT_SYMBOL_GPL(__inet_inherit_port);
0177 
0178 static struct inet_listen_hashbucket *
0179 inet_lhash2_bucket_sk(struct inet_hashinfo *h, struct sock *sk)
0180 {
0181     u32 hash;
0182 
0183 #if IS_ENABLED(CONFIG_IPV6)
0184     if (sk->sk_family == AF_INET6)
0185         hash = ipv6_portaddr_hash(sock_net(sk),
0186                       &sk->sk_v6_rcv_saddr,
0187                       inet_sk(sk)->inet_num);
0188     else
0189 #endif
0190         hash = ipv4_portaddr_hash(sock_net(sk),
0191                       inet_sk(sk)->inet_rcv_saddr,
0192                       inet_sk(sk)->inet_num);
0193     return inet_lhash2_bucket(h, hash);
0194 }
0195 
0196 static inline int compute_score(struct sock *sk, struct net *net,
0197                 const unsigned short hnum, const __be32 daddr,
0198                 const int dif, const int sdif)
0199 {
0200     int score = -1;
0201 
0202     if (net_eq(sock_net(sk), net) && sk->sk_num == hnum &&
0203             !ipv6_only_sock(sk)) {
0204         if (sk->sk_rcv_saddr != daddr)
0205             return -1;
0206 
0207         if (!inet_sk_bound_dev_eq(net, sk->sk_bound_dev_if, dif, sdif))
0208             return -1;
0209         score =  sk->sk_bound_dev_if ? 2 : 1;
0210 
0211         if (sk->sk_family == PF_INET)
0212             score++;
0213         if (READ_ONCE(sk->sk_incoming_cpu) == raw_smp_processor_id())
0214             score++;
0215     }
0216     return score;
0217 }
0218 
0219 static inline struct sock *lookup_reuseport(struct net *net, struct sock *sk,
0220                         struct sk_buff *skb, int doff,
0221                         __be32 saddr, __be16 sport,
0222                         __be32 daddr, unsigned short hnum)
0223 {
0224     struct sock *reuse_sk = NULL;
0225     u32 phash;
0226 
0227     if (sk->sk_reuseport) {
0228         phash = inet_ehashfn(net, daddr, hnum, saddr, sport);
0229         reuse_sk = reuseport_select_sock(sk, phash, skb, doff);
0230     }
0231     return reuse_sk;
0232 }
0233 
0234 /*
0235  * Here are some nice properties to exploit here. The BSD API
0236  * does not allow a listening sock to specify the remote port nor the
0237  * remote address for the connection. So always assume those are both
0238  * wildcarded during the search since they can never be otherwise.
0239  */
0240 
0241 /* called with rcu_read_lock() : No refcount taken on the socket */
0242 static struct sock *inet_lhash2_lookup(struct net *net,
0243                 struct inet_listen_hashbucket *ilb2,
0244                 struct sk_buff *skb, int doff,
0245                 const __be32 saddr, __be16 sport,
0246                 const __be32 daddr, const unsigned short hnum,
0247                 const int dif, const int sdif)
0248 {
0249     struct sock *sk, *result = NULL;
0250     struct hlist_nulls_node *node;
0251     int score, hiscore = 0;
0252 
0253     sk_nulls_for_each_rcu(sk, node, &ilb2->nulls_head) {
0254         score = compute_score(sk, net, hnum, daddr, dif, sdif);
0255         if (score > hiscore) {
0256             result = lookup_reuseport(net, sk, skb, doff,
0257                           saddr, sport, daddr, hnum);
0258             if (result)
0259                 return result;
0260 
0261             result = sk;
0262             hiscore = score;
0263         }
0264     }
0265 
0266     return result;
0267 }
0268 
0269 static inline struct sock *inet_lookup_run_bpf(struct net *net,
0270                            struct inet_hashinfo *hashinfo,
0271                            struct sk_buff *skb, int doff,
0272                            __be32 saddr, __be16 sport,
0273                            __be32 daddr, u16 hnum, const int dif)
0274 {
0275     struct sock *sk, *reuse_sk;
0276     bool no_reuseport;
0277 
0278     if (hashinfo != &tcp_hashinfo)
0279         return NULL; /* only TCP is supported */
0280 
0281     no_reuseport = bpf_sk_lookup_run_v4(net, IPPROTO_TCP, saddr, sport,
0282                         daddr, hnum, dif, &sk);
0283     if (no_reuseport || IS_ERR_OR_NULL(sk))
0284         return sk;
0285 
0286     reuse_sk = lookup_reuseport(net, sk, skb, doff, saddr, sport, daddr, hnum);
0287     if (reuse_sk)
0288         sk = reuse_sk;
0289     return sk;
0290 }
0291 
0292 struct sock *__inet_lookup_listener(struct net *net,
0293                     struct inet_hashinfo *hashinfo,
0294                     struct sk_buff *skb, int doff,
0295                     const __be32 saddr, __be16 sport,
0296                     const __be32 daddr, const unsigned short hnum,
0297                     const int dif, const int sdif)
0298 {
0299     struct inet_listen_hashbucket *ilb2;
0300     struct sock *result = NULL;
0301     unsigned int hash2;
0302 
0303     /* Lookup redirect from BPF */
0304     if (static_branch_unlikely(&bpf_sk_lookup_enabled)) {
0305         result = inet_lookup_run_bpf(net, hashinfo, skb, doff,
0306                          saddr, sport, daddr, hnum, dif);
0307         if (result)
0308             goto done;
0309     }
0310 
0311     hash2 = ipv4_portaddr_hash(net, daddr, hnum);
0312     ilb2 = inet_lhash2_bucket(hashinfo, hash2);
0313 
0314     result = inet_lhash2_lookup(net, ilb2, skb, doff,
0315                     saddr, sport, daddr, hnum,
0316                     dif, sdif);
0317     if (result)
0318         goto done;
0319 
0320     /* Lookup lhash2 with INADDR_ANY */
0321     hash2 = ipv4_portaddr_hash(net, htonl(INADDR_ANY), hnum);
0322     ilb2 = inet_lhash2_bucket(hashinfo, hash2);
0323 
0324     result = inet_lhash2_lookup(net, ilb2, skb, doff,
0325                     saddr, sport, htonl(INADDR_ANY), hnum,
0326                     dif, sdif);
0327 done:
0328     if (IS_ERR(result))
0329         return NULL;
0330     return result;
0331 }
0332 EXPORT_SYMBOL_GPL(__inet_lookup_listener);
0333 
0334 /* All sockets share common refcount, but have different destructors */
0335 void sock_gen_put(struct sock *sk)
0336 {
0337     if (!refcount_dec_and_test(&sk->sk_refcnt))
0338         return;
0339 
0340     if (sk->sk_state == TCP_TIME_WAIT)
0341         inet_twsk_free(inet_twsk(sk));
0342     else if (sk->sk_state == TCP_NEW_SYN_RECV)
0343         reqsk_free(inet_reqsk(sk));
0344     else
0345         sk_free(sk);
0346 }
0347 EXPORT_SYMBOL_GPL(sock_gen_put);
0348 
0349 void sock_edemux(struct sk_buff *skb)
0350 {
0351     sock_gen_put(skb->sk);
0352 }
0353 EXPORT_SYMBOL(sock_edemux);
0354 
0355 struct sock *__inet_lookup_established(struct net *net,
0356                   struct inet_hashinfo *hashinfo,
0357                   const __be32 saddr, const __be16 sport,
0358                   const __be32 daddr, const u16 hnum,
0359                   const int dif, const int sdif)
0360 {
0361     INET_ADDR_COOKIE(acookie, saddr, daddr);
0362     const __portpair ports = INET_COMBINED_PORTS(sport, hnum);
0363     struct sock *sk;
0364     const struct hlist_nulls_node *node;
0365     /* Optimize here for direct hit, only listening connections can
0366      * have wildcards anyways.
0367      */
0368     unsigned int hash = inet_ehashfn(net, daddr, hnum, saddr, sport);
0369     unsigned int slot = hash & hashinfo->ehash_mask;
0370     struct inet_ehash_bucket *head = &hashinfo->ehash[slot];
0371 
0372 begin:
0373     sk_nulls_for_each_rcu(sk, node, &head->chain) {
0374         if (sk->sk_hash != hash)
0375             continue;
0376         if (likely(inet_match(net, sk, acookie, ports, dif, sdif))) {
0377             if (unlikely(!refcount_inc_not_zero(&sk->sk_refcnt)))
0378                 goto out;
0379             if (unlikely(!inet_match(net, sk, acookie,
0380                          ports, dif, sdif))) {
0381                 sock_gen_put(sk);
0382                 goto begin;
0383             }
0384             goto found;
0385         }
0386     }
0387     /*
0388      * if the nulls value we got at the end of this lookup is
0389      * not the expected one, we must restart lookup.
0390      * We probably met an item that was moved to another chain.
0391      */
0392     if (get_nulls_value(node) != slot)
0393         goto begin;
0394 out:
0395     sk = NULL;
0396 found:
0397     return sk;
0398 }
0399 EXPORT_SYMBOL_GPL(__inet_lookup_established);
0400 
0401 /* called with local bh disabled */
0402 static int __inet_check_established(struct inet_timewait_death_row *death_row,
0403                     struct sock *sk, __u16 lport,
0404                     struct inet_timewait_sock **twp)
0405 {
0406     struct inet_hashinfo *hinfo = death_row->hashinfo;
0407     struct inet_sock *inet = inet_sk(sk);
0408     __be32 daddr = inet->inet_rcv_saddr;
0409     __be32 saddr = inet->inet_daddr;
0410     int dif = sk->sk_bound_dev_if;
0411     struct net *net = sock_net(sk);
0412     int sdif = l3mdev_master_ifindex_by_index(net, dif);
0413     INET_ADDR_COOKIE(acookie, saddr, daddr);
0414     const __portpair ports = INET_COMBINED_PORTS(inet->inet_dport, lport);
0415     unsigned int hash = inet_ehashfn(net, daddr, lport,
0416                      saddr, inet->inet_dport);
0417     struct inet_ehash_bucket *head = inet_ehash_bucket(hinfo, hash);
0418     spinlock_t *lock = inet_ehash_lockp(hinfo, hash);
0419     struct sock *sk2;
0420     const struct hlist_nulls_node *node;
0421     struct inet_timewait_sock *tw = NULL;
0422 
0423     spin_lock(lock);
0424 
0425     sk_nulls_for_each(sk2, node, &head->chain) {
0426         if (sk2->sk_hash != hash)
0427             continue;
0428 
0429         if (likely(inet_match(net, sk2, acookie, ports, dif, sdif))) {
0430             if (sk2->sk_state == TCP_TIME_WAIT) {
0431                 tw = inet_twsk(sk2);
0432                 if (twsk_unique(sk, sk2, twp))
0433                     break;
0434             }
0435             goto not_unique;
0436         }
0437     }
0438 
0439     /* Must record num and sport now. Otherwise we will see
0440      * in hash table socket with a funny identity.
0441      */
0442     inet->inet_num = lport;
0443     inet->inet_sport = htons(lport);
0444     sk->sk_hash = hash;
0445     WARN_ON(!sk_unhashed(sk));
0446     __sk_nulls_add_node_rcu(sk, &head->chain);
0447     if (tw) {
0448         sk_nulls_del_node_init_rcu((struct sock *)tw);
0449         __NET_INC_STATS(net, LINUX_MIB_TIMEWAITRECYCLED);
0450     }
0451     spin_unlock(lock);
0452     sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
0453 
0454     if (twp) {
0455         *twp = tw;
0456     } else if (tw) {
0457         /* Silly. Should hash-dance instead... */
0458         inet_twsk_deschedule_put(tw);
0459     }
0460     return 0;
0461 
0462 not_unique:
0463     spin_unlock(lock);
0464     return -EADDRNOTAVAIL;
0465 }
0466 
0467 static u64 inet_sk_port_offset(const struct sock *sk)
0468 {
0469     const struct inet_sock *inet = inet_sk(sk);
0470 
0471     return secure_ipv4_port_ephemeral(inet->inet_rcv_saddr,
0472                       inet->inet_daddr,
0473                       inet->inet_dport);
0474 }
0475 
0476 /* Searches for an exsiting socket in the ehash bucket list.
0477  * Returns true if found, false otherwise.
0478  */
0479 static bool inet_ehash_lookup_by_sk(struct sock *sk,
0480                     struct hlist_nulls_head *list)
0481 {
0482     const __portpair ports = INET_COMBINED_PORTS(sk->sk_dport, sk->sk_num);
0483     const int sdif = sk->sk_bound_dev_if;
0484     const int dif = sk->sk_bound_dev_if;
0485     const struct hlist_nulls_node *node;
0486     struct net *net = sock_net(sk);
0487     struct sock *esk;
0488 
0489     INET_ADDR_COOKIE(acookie, sk->sk_daddr, sk->sk_rcv_saddr);
0490 
0491     sk_nulls_for_each_rcu(esk, node, list) {
0492         if (esk->sk_hash != sk->sk_hash)
0493             continue;
0494         if (sk->sk_family == AF_INET) {
0495             if (unlikely(inet_match(net, esk, acookie,
0496                         ports, dif, sdif))) {
0497                 return true;
0498             }
0499         }
0500 #if IS_ENABLED(CONFIG_IPV6)
0501         else if (sk->sk_family == AF_INET6) {
0502             if (unlikely(inet6_match(net, esk,
0503                          &sk->sk_v6_daddr,
0504                          &sk->sk_v6_rcv_saddr,
0505                          ports, dif, sdif))) {
0506                 return true;
0507             }
0508         }
0509 #endif
0510     }
0511     return false;
0512 }
0513 
0514 /* Insert a socket into ehash, and eventually remove another one
0515  * (The another one can be a SYN_RECV or TIMEWAIT)
0516  * If an existing socket already exists, socket sk is not inserted,
0517  * and sets found_dup_sk parameter to true.
0518  */
0519 bool inet_ehash_insert(struct sock *sk, struct sock *osk, bool *found_dup_sk)
0520 {
0521     struct inet_hashinfo *hashinfo = sk->sk_prot->h.hashinfo;
0522     struct hlist_nulls_head *list;
0523     struct inet_ehash_bucket *head;
0524     spinlock_t *lock;
0525     bool ret = true;
0526 
0527     WARN_ON_ONCE(!sk_unhashed(sk));
0528 
0529     sk->sk_hash = sk_ehashfn(sk);
0530     head = inet_ehash_bucket(hashinfo, sk->sk_hash);
0531     list = &head->chain;
0532     lock = inet_ehash_lockp(hashinfo, sk->sk_hash);
0533 
0534     spin_lock(lock);
0535     if (osk) {
0536         WARN_ON_ONCE(sk->sk_hash != osk->sk_hash);
0537         ret = sk_nulls_del_node_init_rcu(osk);
0538     } else if (found_dup_sk) {
0539         *found_dup_sk = inet_ehash_lookup_by_sk(sk, list);
0540         if (*found_dup_sk)
0541             ret = false;
0542     }
0543 
0544     if (ret)
0545         __sk_nulls_add_node_rcu(sk, list);
0546 
0547     spin_unlock(lock);
0548 
0549     return ret;
0550 }
0551 
0552 bool inet_ehash_nolisten(struct sock *sk, struct sock *osk, bool *found_dup_sk)
0553 {
0554     bool ok = inet_ehash_insert(sk, osk, found_dup_sk);
0555 
0556     if (ok) {
0557         sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
0558     } else {
0559         this_cpu_inc(*sk->sk_prot->orphan_count);
0560         inet_sk_set_state(sk, TCP_CLOSE);
0561         sock_set_flag(sk, SOCK_DEAD);
0562         inet_csk_destroy_sock(sk);
0563     }
0564     return ok;
0565 }
0566 EXPORT_SYMBOL_GPL(inet_ehash_nolisten);
0567 
0568 static int inet_reuseport_add_sock(struct sock *sk,
0569                    struct inet_listen_hashbucket *ilb)
0570 {
0571     struct inet_bind_bucket *tb = inet_csk(sk)->icsk_bind_hash;
0572     const struct hlist_nulls_node *node;
0573     struct sock *sk2;
0574     kuid_t uid = sock_i_uid(sk);
0575 
0576     sk_nulls_for_each_rcu(sk2, node, &ilb->nulls_head) {
0577         if (sk2 != sk &&
0578             sk2->sk_family == sk->sk_family &&
0579             ipv6_only_sock(sk2) == ipv6_only_sock(sk) &&
0580             sk2->sk_bound_dev_if == sk->sk_bound_dev_if &&
0581             inet_csk(sk2)->icsk_bind_hash == tb &&
0582             sk2->sk_reuseport && uid_eq(uid, sock_i_uid(sk2)) &&
0583             inet_rcv_saddr_equal(sk, sk2, false))
0584             return reuseport_add_sock(sk, sk2,
0585                           inet_rcv_saddr_any(sk));
0586     }
0587 
0588     return reuseport_alloc(sk, inet_rcv_saddr_any(sk));
0589 }
0590 
0591 int __inet_hash(struct sock *sk, struct sock *osk)
0592 {
0593     struct inet_hashinfo *hashinfo = sk->sk_prot->h.hashinfo;
0594     struct inet_listen_hashbucket *ilb2;
0595     int err = 0;
0596 
0597     if (sk->sk_state != TCP_LISTEN) {
0598         local_bh_disable();
0599         inet_ehash_nolisten(sk, osk, NULL);
0600         local_bh_enable();
0601         return 0;
0602     }
0603     WARN_ON(!sk_unhashed(sk));
0604     ilb2 = inet_lhash2_bucket_sk(hashinfo, sk);
0605 
0606     spin_lock(&ilb2->lock);
0607     if (sk->sk_reuseport) {
0608         err = inet_reuseport_add_sock(sk, ilb2);
0609         if (err)
0610             goto unlock;
0611     }
0612     if (IS_ENABLED(CONFIG_IPV6) && sk->sk_reuseport &&
0613         sk->sk_family == AF_INET6)
0614         __sk_nulls_add_node_tail_rcu(sk, &ilb2->nulls_head);
0615     else
0616         __sk_nulls_add_node_rcu(sk, &ilb2->nulls_head);
0617     sock_set_flag(sk, SOCK_RCU_FREE);
0618     sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
0619 unlock:
0620     spin_unlock(&ilb2->lock);
0621 
0622     return err;
0623 }
0624 EXPORT_SYMBOL(__inet_hash);
0625 
0626 int inet_hash(struct sock *sk)
0627 {
0628     int err = 0;
0629 
0630     if (sk->sk_state != TCP_CLOSE)
0631         err = __inet_hash(sk, NULL);
0632 
0633     return err;
0634 }
0635 EXPORT_SYMBOL_GPL(inet_hash);
0636 
0637 void inet_unhash(struct sock *sk)
0638 {
0639     struct inet_hashinfo *hashinfo = sk->sk_prot->h.hashinfo;
0640 
0641     if (sk_unhashed(sk))
0642         return;
0643 
0644     if (sk->sk_state == TCP_LISTEN) {
0645         struct inet_listen_hashbucket *ilb2;
0646 
0647         ilb2 = inet_lhash2_bucket_sk(hashinfo, sk);
0648         /* Don't disable bottom halves while acquiring the lock to
0649          * avoid circular locking dependency on PREEMPT_RT.
0650          */
0651         spin_lock(&ilb2->lock);
0652         if (sk_unhashed(sk)) {
0653             spin_unlock(&ilb2->lock);
0654             return;
0655         }
0656 
0657         if (rcu_access_pointer(sk->sk_reuseport_cb))
0658             reuseport_stop_listen_sock(sk);
0659 
0660         __sk_nulls_del_node_init_rcu(sk);
0661         sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
0662         spin_unlock(&ilb2->lock);
0663     } else {
0664         spinlock_t *lock = inet_ehash_lockp(hashinfo, sk->sk_hash);
0665 
0666         spin_lock_bh(lock);
0667         if (sk_unhashed(sk)) {
0668             spin_unlock_bh(lock);
0669             return;
0670         }
0671         __sk_nulls_del_node_init_rcu(sk);
0672         sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
0673         spin_unlock_bh(lock);
0674     }
0675 }
0676 EXPORT_SYMBOL_GPL(inet_unhash);
0677 
0678 /* RFC 6056 3.3.4.  Algorithm 4: Double-Hash Port Selection Algorithm
0679  * Note that we use 32bit integers (vs RFC 'short integers')
0680  * because 2^16 is not a multiple of num_ephemeral and this
0681  * property might be used by clever attacker.
0682  * RFC claims using TABLE_LENGTH=10 buckets gives an improvement, though
0683  * attacks were since demonstrated, thus we use 65536 instead to really
0684  * give more isolation and privacy, at the expense of 256kB of kernel
0685  * memory.
0686  */
0687 #define INET_TABLE_PERTURB_SHIFT 16
0688 #define INET_TABLE_PERTURB_SIZE (1 << INET_TABLE_PERTURB_SHIFT)
0689 static u32 *table_perturb;
0690 
0691 int __inet_hash_connect(struct inet_timewait_death_row *death_row,
0692         struct sock *sk, u64 port_offset,
0693         int (*check_established)(struct inet_timewait_death_row *,
0694             struct sock *, __u16, struct inet_timewait_sock **))
0695 {
0696     struct inet_hashinfo *hinfo = death_row->hashinfo;
0697     struct inet_timewait_sock *tw = NULL;
0698     struct inet_bind_hashbucket *head;
0699     int port = inet_sk(sk)->inet_num;
0700     struct net *net = sock_net(sk);
0701     struct inet_bind_bucket *tb;
0702     u32 remaining, offset;
0703     int ret, i, low, high;
0704     int l3mdev;
0705     u32 index;
0706 
0707     if (port) {
0708         head = &hinfo->bhash[inet_bhashfn(net, port,
0709                           hinfo->bhash_size)];
0710         tb = inet_csk(sk)->icsk_bind_hash;
0711         spin_lock_bh(&head->lock);
0712         if (sk_head(&tb->owners) == sk && !sk->sk_bind_node.next) {
0713             inet_ehash_nolisten(sk, NULL, NULL);
0714             spin_unlock_bh(&head->lock);
0715             return 0;
0716         }
0717         spin_unlock(&head->lock);
0718         /* No definite answer... Walk to established hash table */
0719         ret = check_established(death_row, sk, port, NULL);
0720         local_bh_enable();
0721         return ret;
0722     }
0723 
0724     l3mdev = inet_sk_bound_l3mdev(sk);
0725 
0726     inet_get_local_port_range(net, &low, &high);
0727     high++; /* [32768, 60999] -> [32768, 61000[ */
0728     remaining = high - low;
0729     if (likely(remaining > 1))
0730         remaining &= ~1U;
0731 
0732     net_get_random_once(table_perturb,
0733                 INET_TABLE_PERTURB_SIZE * sizeof(*table_perturb));
0734     index = port_offset & (INET_TABLE_PERTURB_SIZE - 1);
0735 
0736     offset = READ_ONCE(table_perturb[index]) + (port_offset >> 32);
0737     offset %= remaining;
0738 
0739     /* In first pass we try ports of @low parity.
0740      * inet_csk_get_port() does the opposite choice.
0741      */
0742     offset &= ~1U;
0743 other_parity_scan:
0744     port = low + offset;
0745     for (i = 0; i < remaining; i += 2, port += 2) {
0746         if (unlikely(port >= high))
0747             port -= remaining;
0748         if (inet_is_local_reserved_port(net, port))
0749             continue;
0750         head = &hinfo->bhash[inet_bhashfn(net, port,
0751                           hinfo->bhash_size)];
0752         spin_lock_bh(&head->lock);
0753 
0754         /* Does not bother with rcv_saddr checks, because
0755          * the established check is already unique enough.
0756          */
0757         inet_bind_bucket_for_each(tb, &head->chain) {
0758             if (net_eq(ib_net(tb), net) && tb->l3mdev == l3mdev &&
0759                 tb->port == port) {
0760                 if (tb->fastreuse >= 0 ||
0761                     tb->fastreuseport >= 0)
0762                     goto next_port;
0763                 WARN_ON(hlist_empty(&tb->owners));
0764                 if (!check_established(death_row, sk,
0765                                port, &tw))
0766                     goto ok;
0767                 goto next_port;
0768             }
0769         }
0770 
0771         tb = inet_bind_bucket_create(hinfo->bind_bucket_cachep,
0772                          net, head, port, l3mdev);
0773         if (!tb) {
0774             spin_unlock_bh(&head->lock);
0775             return -ENOMEM;
0776         }
0777         tb->fastreuse = -1;
0778         tb->fastreuseport = -1;
0779         goto ok;
0780 next_port:
0781         spin_unlock_bh(&head->lock);
0782         cond_resched();
0783     }
0784 
0785     offset++;
0786     if ((offset & 1) && remaining > 1)
0787         goto other_parity_scan;
0788 
0789     return -EADDRNOTAVAIL;
0790 
0791 ok:
0792     /* Here we want to add a little bit of randomness to the next source
0793      * port that will be chosen. We use a max() with a random here so that
0794      * on low contention the randomness is maximal and on high contention
0795      * it may be inexistent.
0796      */
0797     i = max_t(int, i, (prandom_u32() & 7) * 2);
0798     WRITE_ONCE(table_perturb[index], READ_ONCE(table_perturb[index]) + i + 2);
0799 
0800     /* Head lock still held and bh's disabled */
0801     inet_bind_hash(sk, tb, port);
0802     if (sk_unhashed(sk)) {
0803         inet_sk(sk)->inet_sport = htons(port);
0804         inet_ehash_nolisten(sk, (struct sock *)tw, NULL);
0805     }
0806     if (tw)
0807         inet_twsk_bind_unhash(tw, hinfo);
0808     spin_unlock(&head->lock);
0809     if (tw)
0810         inet_twsk_deschedule_put(tw);
0811     local_bh_enable();
0812     return 0;
0813 }
0814 
0815 /*
0816  * Bind a port for a connect operation and hash it.
0817  */
0818 int inet_hash_connect(struct inet_timewait_death_row *death_row,
0819               struct sock *sk)
0820 {
0821     u64 port_offset = 0;
0822 
0823     if (!inet_sk(sk)->inet_num)
0824         port_offset = inet_sk_port_offset(sk);
0825     return __inet_hash_connect(death_row, sk, port_offset,
0826                    __inet_check_established);
0827 }
0828 EXPORT_SYMBOL_GPL(inet_hash_connect);
0829 
0830 static void init_hashinfo_lhash2(struct inet_hashinfo *h)
0831 {
0832     int i;
0833 
0834     for (i = 0; i <= h->lhash2_mask; i++) {
0835         spin_lock_init(&h->lhash2[i].lock);
0836         INIT_HLIST_NULLS_HEAD(&h->lhash2[i].nulls_head,
0837                       i + LISTENING_NULLS_BASE);
0838     }
0839 }
0840 
0841 void __init inet_hashinfo2_init(struct inet_hashinfo *h, const char *name,
0842                 unsigned long numentries, int scale,
0843                 unsigned long low_limit,
0844                 unsigned long high_limit)
0845 {
0846     h->lhash2 = alloc_large_system_hash(name,
0847                         sizeof(*h->lhash2),
0848                         numentries,
0849                         scale,
0850                         0,
0851                         NULL,
0852                         &h->lhash2_mask,
0853                         low_limit,
0854                         high_limit);
0855     init_hashinfo_lhash2(h);
0856 
0857     /* this one is used for source ports of outgoing connections */
0858     table_perturb = alloc_large_system_hash("Table-perturb",
0859                         sizeof(*table_perturb),
0860                         INET_TABLE_PERTURB_SIZE,
0861                         0, 0, NULL, NULL,
0862                         INET_TABLE_PERTURB_SIZE,
0863                         INET_TABLE_PERTURB_SIZE);
0864 }
0865 
0866 int inet_hashinfo2_init_mod(struct inet_hashinfo *h)
0867 {
0868     h->lhash2 = kmalloc_array(INET_LHTABLE_SIZE, sizeof(*h->lhash2), GFP_KERNEL);
0869     if (!h->lhash2)
0870         return -ENOMEM;
0871 
0872     h->lhash2_mask = INET_LHTABLE_SIZE - 1;
0873     /* INET_LHTABLE_SIZE must be a power of 2 */
0874     BUG_ON(INET_LHTABLE_SIZE & h->lhash2_mask);
0875 
0876     init_hashinfo_lhash2(h);
0877     return 0;
0878 }
0879 EXPORT_SYMBOL_GPL(inet_hashinfo2_init_mod);
0880 
0881 int inet_ehash_locks_alloc(struct inet_hashinfo *hashinfo)
0882 {
0883     unsigned int locksz = sizeof(spinlock_t);
0884     unsigned int i, nblocks = 1;
0885 
0886     if (locksz != 0) {
0887         /* allocate 2 cache lines or at least one spinlock per cpu */
0888         nblocks = max(2U * L1_CACHE_BYTES / locksz, 1U);
0889         nblocks = roundup_pow_of_two(nblocks * num_possible_cpus());
0890 
0891         /* no more locks than number of hash buckets */
0892         nblocks = min(nblocks, hashinfo->ehash_mask + 1);
0893 
0894         hashinfo->ehash_locks = kvmalloc_array(nblocks, locksz, GFP_KERNEL);
0895         if (!hashinfo->ehash_locks)
0896             return -ENOMEM;
0897 
0898         for (i = 0; i < nblocks; i++)
0899             spin_lock_init(&hashinfo->ehash_locks[i]);
0900     }
0901     hashinfo->ehash_locks_mask = nblocks - 1;
0902     return 0;
0903 }
0904 EXPORT_SYMBOL_GPL(inet_ehash_locks_alloc);