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