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.
6 * Generic INET transport hashtables
8 * Authors: Lotsa people, from code originally in tcp
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.
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>
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>
29 #include <net/secure_seq.h>
32 #include <net/sock_reuseport.h>
34 static u32 inet_ehashfn(const struct net *net, const __be32 laddr,
35 const __u16 lport, const __be32 faddr,
38 static u32 inet_ehash_secret __read_mostly;
40 net_get_random_once(&inet_ehash_secret, sizeof(inet_ehash_secret));
42 return __inet_ehashfn(laddr, lport, faddr, fport,
43 inet_ehash_secret + net_hash_mix(net));
46 /* This function handles inet_sock, but also timewait and request sockets
49 static u32 sk_ehashfn(const struct sock *sk)
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);
58 return inet_ehashfn(sock_net(sk),
59 sk->sk_rcv_saddr, sk->sk_num,
60 sk->sk_daddr, sk->sk_dport);
64 * Allocate and initialize a new local port bind bucket.
65 * The bindhash mutex for snum's hash chain must be held here.
67 struct inet_bind_bucket *inet_bind_bucket_create(struct kmem_cache *cachep,
69 struct inet_bind_hashbucket *head,
70 const unsigned short snum)
72 struct inet_bind_bucket *tb = kmem_cache_alloc(cachep, GFP_ATOMIC);
75 write_pnet(&tb->ib_net, net);
78 tb->fastreuseport = 0;
79 INIT_HLIST_HEAD(&tb->owners);
80 hlist_add_head(&tb->node, &head->chain);
86 * Caller must hold hashbucket lock for this tb with local BH disabled
88 void inet_bind_bucket_destroy(struct kmem_cache *cachep, struct inet_bind_bucket *tb)
90 if (hlist_empty(&tb->owners)) {
91 __hlist_del(&tb->node);
92 kmem_cache_free(cachep, tb);
96 void inet_bind_hash(struct sock *sk, struct inet_bind_bucket *tb,
97 const unsigned short snum)
99 inet_sk(sk)->inet_num = snum;
100 sk_add_bind_node(sk, &tb->owners);
101 inet_csk(sk)->icsk_bind_hash = tb;
105 * Get rid of any references to a local port held by the given sock.
107 static void __inet_put_port(struct sock *sk)
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;
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);
124 void inet_put_port(struct sock *sk)
130 EXPORT_SYMBOL(inet_put_port);
132 int __inet_inherit_port(const struct sock *sk, struct sock *child)
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,
138 struct inet_bind_hashbucket *head = &table->bhash[bhash];
139 struct inet_bind_bucket *tb;
141 spin_lock(&head->lock);
142 tb = inet_csk(sk)->icsk_bind_hash;
144 spin_unlock(&head->lock);
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)) &&
159 tb = inet_bind_bucket_create(table->bind_bucket_cachep,
160 sock_net(sk), head, port);
162 spin_unlock(&head->lock);
166 inet_csk_update_fastreuse(tb, child);
168 inet_bind_hash(child, tb, port);
169 spin_unlock(&head->lock);
173 EXPORT_SYMBOL_GPL(__inet_inherit_port);
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)
180 struct inet_sock *inet = inet_sk(sk);
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;
187 if (rcv_saddr != daddr)
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);
197 if (sk->sk_bound_dev_if)
200 if (READ_ONCE(sk->sk_incoming_cpu) == raw_smp_processor_id())
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.
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)
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;
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;
235 phash = inet_ehashfn(net, daddr, hnum,
237 result = reuseport_select_sock(sk, phash,
245 } else if (score == hiscore && reuseport) {
247 if (reciprocal_scale(phash, matches) == 0)
249 phash = next_pseudo_random32(phash);
254 EXPORT_SYMBOL_GPL(__inet_lookup_listener);
256 /* All sockets share common refcount, but have different destructors */
257 void sock_gen_put(struct sock *sk)
259 if (!refcount_dec_and_test(&sk->sk_refcnt))
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));
269 EXPORT_SYMBOL_GPL(sock_gen_put);
271 void sock_edemux(struct sk_buff *skb)
273 sock_gen_put(skb->sk);
275 EXPORT_SYMBOL(sock_edemux);
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)
283 INET_ADDR_COOKIE(acookie, saddr, daddr);
284 const __portpair ports = INET_COMBINED_PORTS(sport, hnum);
286 const struct hlist_nulls_node *node;
287 /* Optimize here for direct hit, only listening connections can
288 * have wildcards anyways.
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];
295 sk_nulls_for_each_rcu(sk, node, &head->chain) {
296 if (sk->sk_hash != hash)
298 if (likely(INET_MATCH(sk, net, acookie,
299 saddr, daddr, ports, dif, sdif))) {
300 if (unlikely(!refcount_inc_not_zero(&sk->sk_refcnt)))
302 if (unlikely(!INET_MATCH(sk, net, acookie,
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.
316 if (get_nulls_value(node) != slot)
323 EXPORT_SYMBOL_GPL(__inet_lookup_established);
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)
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);
344 const struct hlist_nulls_node *node;
345 struct inet_timewait_sock *tw = NULL;
349 sk_nulls_for_each(sk2, node, &head->chain) {
350 if (sk2->sk_hash != hash)
353 if (likely(INET_MATCH(sk2, net, acookie,
354 saddr, daddr, ports, dif, sdif))) {
355 if (sk2->sk_state == TCP_TIME_WAIT) {
357 if (twsk_unique(sk, sk2, twp))
364 /* Must record num and sport now. Otherwise we will see
365 * in hash table socket with a funny identity.
367 inet->inet_num = lport;
368 inet->inet_sport = htons(lport);
370 WARN_ON(!sk_unhashed(sk));
371 __sk_nulls_add_node_rcu(sk, &head->chain);
373 sk_nulls_del_node_init_rcu((struct sock *)tw);
374 __NET_INC_STATS(net, LINUX_MIB_TIMEWAITRECYCLED);
377 sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
382 /* Silly. Should hash-dance instead... */
383 inet_twsk_deschedule_put(tw);
389 return -EADDRNOTAVAIL;
392 static u64 inet_sk_port_offset(const struct sock *sk)
394 const struct inet_sock *inet = inet_sk(sk);
396 return secure_ipv4_port_ephemeral(inet->inet_rcv_saddr,
401 /* Searches for an exsiting socket in the ehash bucket list.
402 * Returns true if found, false otherwise.
404 static bool inet_ehash_lookup_by_sk(struct sock *sk,
405 struct hlist_nulls_head *list)
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);
414 INET_ADDR_COOKIE(acookie, sk->sk_daddr, sk->sk_rcv_saddr);
416 sk_nulls_for_each_rcu(esk, node, list) {
417 if (esk->sk_hash != sk->sk_hash)
419 if (sk->sk_family == AF_INET) {
420 if (unlikely(INET_MATCH(esk, net, acookie,
423 ports, dif, sdif))) {
427 #if IS_ENABLED(CONFIG_IPV6)
428 else if (sk->sk_family == AF_INET6) {
429 if (unlikely(INET6_MATCH(esk, net,
431 &sk->sk_v6_rcv_saddr,
432 ports, dif, sdif))) {
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.
446 bool inet_ehash_insert(struct sock *sk, struct sock *osk, bool *found_dup_sk)
448 struct inet_hashinfo *hashinfo = sk->sk_prot->h.hashinfo;
449 struct hlist_nulls_head *list;
450 struct inet_ehash_bucket *head;
454 WARN_ON_ONCE(!sk_unhashed(sk));
456 sk->sk_hash = sk_ehashfn(sk);
457 head = inet_ehash_bucket(hashinfo, sk->sk_hash);
459 lock = inet_ehash_lockp(hashinfo, sk->sk_hash);
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);
472 __sk_nulls_add_node_rcu(sk, list);
479 bool inet_ehash_nolisten(struct sock *sk, struct sock *osk, bool *found_dup_sk)
481 bool ok = inet_ehash_insert(sk, osk, found_dup_sk);
484 sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
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);
493 EXPORT_SYMBOL_GPL(inet_ehash_nolisten);
495 static int inet_reuseport_add_sock(struct sock *sk,
496 struct inet_listen_hashbucket *ilb)
498 struct inet_bind_bucket *tb = inet_csk(sk)->icsk_bind_hash;
499 const struct hlist_nulls_node *node;
501 kuid_t uid = sock_i_uid(sk);
503 sk_nulls_for_each_rcu(sk2, node, &ilb->nulls_head) {
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);
514 return reuseport_alloc(sk);
517 int __inet_hash(struct sock *sk, struct sock *osk)
519 struct inet_hashinfo *hashinfo = sk->sk_prot->h.hashinfo;
520 struct inet_listen_hashbucket *ilb;
523 if (sk->sk_state != TCP_LISTEN) {
524 inet_ehash_nolisten(sk, osk, NULL);
527 WARN_ON(!sk_unhashed(sk));
528 ilb = &hashinfo->listening_hash[inet_sk_listen_hashfn(sk)];
530 spin_lock(&ilb->lock);
531 if (sk->sk_reuseport) {
532 err = inet_reuseport_add_sock(sk, ilb);
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);
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);
544 spin_unlock(&ilb->lock);
548 EXPORT_SYMBOL(__inet_hash);
550 int inet_hash(struct sock *sk)
554 if (sk->sk_state != TCP_CLOSE) {
556 err = __inet_hash(sk, NULL);
562 EXPORT_SYMBOL_GPL(inet_hash);
564 void inet_unhash(struct sock *sk)
566 struct inet_hashinfo *hashinfo = sk->sk_prot->h.hashinfo;
568 bool listener = false;
574 if (sk->sk_state == TCP_LISTEN) {
575 lock = &hashinfo->listening_hash[inet_sk_listen_hashfn(sk)].lock;
578 lock = inet_ehash_lockp(hashinfo, sk->sk_hash);
581 if (rcu_access_pointer(sk->sk_reuseport_cb))
582 reuseport_detach_sock(sk);
583 done = __sk_nulls_del_node_init_rcu(sk);
585 sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
586 spin_unlock_bh(lock);
588 EXPORT_SYMBOL_GPL(inet_unhash);
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.
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
600 #define INET_TABLE_PERTURB_SIZE (1 << CONFIG_INET_TABLE_PERTURB_ORDER)
601 static u32 *table_perturb;
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 **))
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;
620 ret = check_established(death_row, sk, port, NULL);
625 inet_get_local_port_range(net, &low, &high);
626 high++; /* [32768, 60999] -> [32768, 61000[ */
627 remaining = high - low;
628 if (likely(remaining > 1))
631 get_random_slow_once(table_perturb,
632 INET_TABLE_PERTURB_SIZE * sizeof(*table_perturb));
633 index = port_offset & (INET_TABLE_PERTURB_SIZE - 1);
635 offset = READ_ONCE(table_perturb[index]) + (port_offset >> 32);
638 /* In first pass we try ports of @low parity.
639 * inet_csk_get_port() does the opposite choice.
644 for (i = 0; i < remaining; i += 2, port += 2) {
645 if (unlikely(port >= high))
647 if (inet_is_local_reserved_port(net, port))
649 head = &hinfo->bhash[inet_bhashfn(net, port,
651 spin_lock_bh(&head->lock);
653 /* Does not bother with rcv_saddr checks, because
654 * the established check is already unique enough.
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)
661 WARN_ON(hlist_empty(&tb->owners));
662 if (!check_established(death_row, sk,
669 tb = inet_bind_bucket_create(hinfo->bind_bucket_cachep,
672 spin_unlock_bh(&head->lock);
676 tb->fastreuseport = -1;
679 spin_unlock_bh(&head->lock);
684 if ((offset & 1) && remaining > 1)
685 goto other_parity_scan;
687 return -EADDRNOTAVAIL;
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.
695 i = max_t(int, i, (prandom_u32() & 7) * 2);
696 WRITE_ONCE(table_perturb[index], READ_ONCE(table_perturb[index]) + i + 2);
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);
705 inet_twsk_bind_unhash(tw, hinfo);
706 spin_unlock(&head->lock);
708 inet_twsk_deschedule_put(tw);
714 * Bind a port for a connect operation and hash it.
716 int inet_hash_connect(struct inet_timewait_death_row *death_row,
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);
726 EXPORT_SYMBOL_GPL(inet_hash_connect);
728 void inet_hashinfo_init(struct inet_hashinfo *h)
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);
738 if (h != &tcp_hashinfo)
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);
745 panic("TCP: failed to alloc table_perturb");
747 EXPORT_SYMBOL_GPL(inet_hashinfo_init);
749 int inet_ehash_locks_alloc(struct inet_hashinfo *hashinfo)
751 unsigned int locksz = sizeof(spinlock_t);
752 unsigned int i, nblocks = 1;
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());
759 /* no more locks than number of hash buckets */
760 nblocks = min(nblocks, hashinfo->ehash_mask + 1);
762 hashinfo->ehash_locks = kvmalloc_array(nblocks, locksz, GFP_KERNEL);
763 if (!hashinfo->ehash_locks)
766 for (i = 0; i < nblocks; i++)
767 spin_lock_init(&hashinfo->ehash_locks[i]);
769 hashinfo->ehash_locks_mask = nblocks - 1;
772 EXPORT_SYMBOL_GPL(inet_ehash_locks_alloc);