2 * Resizable, Scalable, Concurrent Hash Table
4 * Copyright (c) 2014 Thomas Graf <tgraf@suug.ch>
5 * Copyright (c) 2008-2014 Patrick McHardy <kaber@trash.net>
7 * Based on the following paper:
8 * https://www.usenix.org/legacy/event/atc11/tech/final_files/Triplett.pdf
10 * Code partially derived from nft_hash
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License version 2 as
14 * published by the Free Software Foundation.
17 #include <linux/kernel.h>
18 #include <linux/init.h>
19 #include <linux/log2.h>
20 #include <linux/slab.h>
21 #include <linux/vmalloc.h>
23 #include <linux/hash.h>
24 #include <linux/random.h>
25 #include <linux/rhashtable.h>
27 #define HASH_DEFAULT_SIZE 64UL
28 #define HASH_MIN_SIZE 4UL
30 #define ASSERT_RHT_MUTEX(HT) BUG_ON(!lockdep_rht_mutex_is_held(HT))
32 #ifdef CONFIG_PROVE_LOCKING
33 int lockdep_rht_mutex_is_held(const struct rhashtable
*ht
)
35 return ht
->p
.mutex_is_held();
37 EXPORT_SYMBOL_GPL(lockdep_rht_mutex_is_held
);
40 static void *rht_obj(const struct rhashtable
*ht
, const struct rhash_head
*he
)
42 return (void *) he
- ht
->p
.head_offset
;
45 static u32
__hashfn(const struct rhashtable
*ht
, const void *key
,
50 h
= ht
->p
.hashfn(key
, len
, ht
->p
.hash_rnd
);
52 return h
& (hsize
- 1);
56 * rhashtable_hashfn - compute hash for key of given length
57 * @ht: hash table to compute for
58 * @key: pointer to key
61 * Computes the hash value using the hash function provided in the 'hashfn'
62 * of struct rhashtable_params. The returned value is guaranteed to be
63 * smaller than the number of buckets in the hash table.
65 * The caller must ensure that no concurrent table mutations occur.
67 u32
rhashtable_hashfn(const struct rhashtable
*ht
, const void *key
, u32 len
)
69 struct bucket_table
*tbl
= rht_dereference_rcu(ht
->tbl
, ht
);
71 return __hashfn(ht
, key
, len
, tbl
->size
);
73 EXPORT_SYMBOL_GPL(rhashtable_hashfn
);
75 static u32
obj_hashfn(const struct rhashtable
*ht
, const void *ptr
, u32 hsize
)
77 if (unlikely(!ht
->p
.key_len
)) {
80 h
= ht
->p
.obj_hashfn(ptr
, ht
->p
.hash_rnd
);
82 return h
& (hsize
- 1);
85 return __hashfn(ht
, ptr
+ ht
->p
.key_offset
, ht
->p
.key_len
, hsize
);
89 * rhashtable_obj_hashfn - compute hash for hashed object
90 * @ht: hash table to compute for
91 * @ptr: pointer to hashed object
93 * Computes the hash value using the hash function `hashfn` respectively
94 * 'obj_hashfn' depending on whether the hash table is set up to work with
95 * a fixed length key. The returned value is guaranteed to be smaller than
96 * the number of buckets in the hash table.
98 * The caller must ensure that no concurrent table mutations occur.
100 u32
rhashtable_obj_hashfn(const struct rhashtable
*ht
, void *ptr
)
102 struct bucket_table
*tbl
= rht_dereference_rcu(ht
->tbl
, ht
);
104 return obj_hashfn(ht
, ptr
, tbl
->size
);
106 EXPORT_SYMBOL_GPL(rhashtable_obj_hashfn
);
108 static u32
head_hashfn(const struct rhashtable
*ht
,
109 const struct rhash_head
*he
, u32 hsize
)
111 return obj_hashfn(ht
, rht_obj(ht
, he
), hsize
);
114 static struct bucket_table
*bucket_table_alloc(size_t nbuckets
, gfp_t flags
)
116 struct bucket_table
*tbl
;
119 size
= sizeof(*tbl
) + nbuckets
* sizeof(tbl
->buckets
[0]);
120 tbl
= kzalloc(size
, flags
);
127 tbl
->size
= nbuckets
;
132 static void bucket_table_free(const struct bucket_table
*tbl
)
138 * rht_grow_above_75 - returns true if nelems > 0.75 * table-size
140 * @new_size: new table size
142 bool rht_grow_above_75(const struct rhashtable
*ht
, size_t new_size
)
144 /* Expand table when exceeding 75% load */
145 return ht
->nelems
> (new_size
/ 4 * 3);
147 EXPORT_SYMBOL_GPL(rht_grow_above_75
);
150 * rht_shrink_below_30 - returns true if nelems < 0.3 * table-size
152 * @new_size: new table size
154 bool rht_shrink_below_30(const struct rhashtable
*ht
, size_t new_size
)
156 /* Shrink table beneath 30% load */
157 return ht
->nelems
< (new_size
* 3 / 10);
159 EXPORT_SYMBOL_GPL(rht_shrink_below_30
);
161 static void hashtable_chain_unzip(const struct rhashtable
*ht
,
162 const struct bucket_table
*new_tbl
,
163 struct bucket_table
*old_tbl
, size_t n
)
165 struct rhash_head
*he
, *p
, *next
;
168 /* Old bucket empty, no work needed. */
169 p
= rht_dereference(old_tbl
->buckets
[n
], ht
);
173 /* Advance the old bucket pointer one or more times until it
174 * reaches a node that doesn't hash to the same bucket as the
175 * previous node p. Call the previous node p;
177 h
= head_hashfn(ht
, p
, new_tbl
->size
);
178 rht_for_each(he
, p
->next
, ht
) {
179 if (head_hashfn(ht
, he
, new_tbl
->size
) != h
)
183 RCU_INIT_POINTER(old_tbl
->buckets
[n
], p
->next
);
185 /* Find the subsequent node which does hash to the same
186 * bucket as node P, or NULL if no such node exists.
190 rht_for_each(he
, he
->next
, ht
) {
191 if (head_hashfn(ht
, he
, new_tbl
->size
) == h
) {
198 /* Set p's next pointer to that subsequent node pointer,
199 * bypassing the nodes which do not hash to p's bucket
201 RCU_INIT_POINTER(p
->next
, next
);
205 * rhashtable_expand - Expand hash table while allowing concurrent lookups
206 * @ht: the hash table to expand
207 * @flags: allocation flags
209 * A secondary bucket array is allocated and the hash entries are migrated
210 * while keeping them on both lists until the end of the RCU grace period.
212 * This function may only be called in a context where it is safe to call
213 * synchronize_rcu(), e.g. not within a rcu_read_lock() section.
215 * The caller must ensure that no concurrent table mutations take place.
216 * It is however valid to have concurrent lookups if they are RCU protected.
218 int rhashtable_expand(struct rhashtable
*ht
, gfp_t flags
)
220 struct bucket_table
*new_tbl
, *old_tbl
= rht_dereference(ht
->tbl
, ht
);
221 struct rhash_head
*he
;
225 ASSERT_RHT_MUTEX(ht
);
227 if (ht
->p
.max_shift
&& ht
->shift
>= ht
->p
.max_shift
)
230 new_tbl
= bucket_table_alloc(old_tbl
->size
* 2, flags
);
236 /* For each new bucket, search the corresponding old bucket
237 * for the first entry that hashes to the new bucket, and
238 * link the new bucket to that entry. Since all the entries
239 * which will end up in the new bucket appear in the same
240 * old bucket, this constructs an entirely valid new hash
241 * table, but with multiple buckets "zipped" together into a
242 * single imprecise chain.
244 for (i
= 0; i
< new_tbl
->size
; i
++) {
245 h
= i
& (old_tbl
->size
- 1);
246 rht_for_each(he
, old_tbl
->buckets
[h
], ht
) {
247 if (head_hashfn(ht
, he
, new_tbl
->size
) == i
) {
248 RCU_INIT_POINTER(new_tbl
->buckets
[i
], he
);
254 /* Publish the new table pointer. Lookups may now traverse
255 * the new table, but they will not benefit from any
256 * additional efficiency until later steps unzip the buckets.
258 rcu_assign_pointer(ht
->tbl
, new_tbl
);
260 /* Unzip interleaved hash chains */
262 /* Wait for readers. All new readers will see the new
263 * table, and thus no references to the old table will
268 /* For each bucket in the old table (each of which
269 * contains items from multiple buckets of the new
273 for (i
= 0; i
< old_tbl
->size
; i
++) {
274 hashtable_chain_unzip(ht
, new_tbl
, old_tbl
, i
);
275 if (old_tbl
->buckets
[i
] != NULL
)
280 bucket_table_free(old_tbl
);
283 EXPORT_SYMBOL_GPL(rhashtable_expand
);
286 * rhashtable_shrink - Shrink hash table while allowing concurrent lookups
287 * @ht: the hash table to shrink
288 * @flags: allocation flags
290 * This function may only be called in a context where it is safe to call
291 * synchronize_rcu(), e.g. not within a rcu_read_lock() section.
293 * The caller must ensure that no concurrent table mutations take place.
294 * It is however valid to have concurrent lookups if they are RCU protected.
296 int rhashtable_shrink(struct rhashtable
*ht
, gfp_t flags
)
298 struct bucket_table
*ntbl
, *tbl
= rht_dereference(ht
->tbl
, ht
);
299 struct rhash_head __rcu
**pprev
;
302 ASSERT_RHT_MUTEX(ht
);
304 if (ht
->shift
<= ht
->p
.min_shift
)
307 ntbl
= bucket_table_alloc(tbl
->size
/ 2, flags
);
313 /* Link each bucket in the new table to the first bucket
314 * in the old table that contains entries which will hash
317 for (i
= 0; i
< ntbl
->size
; i
++) {
318 ntbl
->buckets
[i
] = tbl
->buckets
[i
];
320 /* Link each bucket in the new table to the first bucket
321 * in the old table that contains entries which will hash
324 for (pprev
= &ntbl
->buckets
[i
]; *pprev
!= NULL
;
325 pprev
= &rht_dereference(*pprev
, ht
)->next
)
327 RCU_INIT_POINTER(*pprev
, tbl
->buckets
[i
+ ntbl
->size
]);
330 /* Publish the new, valid hash table */
331 rcu_assign_pointer(ht
->tbl
, ntbl
);
333 /* Wait for readers. No new readers will have references to the
338 bucket_table_free(tbl
);
342 EXPORT_SYMBOL_GPL(rhashtable_shrink
);
345 * rhashtable_insert - insert object into hash hash table
347 * @obj: pointer to hash head inside object
348 * @flags: allocation flags (table expansion)
350 * Will automatically grow the table via rhashtable_expand() if the the
351 * grow_decision function specified at rhashtable_init() returns true.
353 * The caller must ensure that no concurrent table mutations occur. It is
354 * however valid to have concurrent lookups if they are RCU protected.
356 void rhashtable_insert(struct rhashtable
*ht
, struct rhash_head
*obj
,
359 struct bucket_table
*tbl
= rht_dereference(ht
->tbl
, ht
);
362 ASSERT_RHT_MUTEX(ht
);
364 hash
= head_hashfn(ht
, obj
, tbl
->size
);
365 RCU_INIT_POINTER(obj
->next
, tbl
->buckets
[hash
]);
366 rcu_assign_pointer(tbl
->buckets
[hash
], obj
);
369 if (ht
->p
.grow_decision
&& ht
->p
.grow_decision(ht
, tbl
->size
))
370 rhashtable_expand(ht
, flags
);
372 EXPORT_SYMBOL_GPL(rhashtable_insert
);
375 * rhashtable_remove_pprev - remove object from hash table given previous element
377 * @obj: pointer to hash head inside object
378 * @pprev: pointer to previous element
379 * @flags: allocation flags (table expansion)
381 * Identical to rhashtable_remove() but caller is alreayd aware of the element
382 * in front of the element to be deleted. This is in particular useful for
383 * deletion when combined with walking or lookup.
385 void rhashtable_remove_pprev(struct rhashtable
*ht
, struct rhash_head
*obj
,
386 struct rhash_head __rcu
**pprev
, gfp_t flags
)
388 struct bucket_table
*tbl
= rht_dereference(ht
->tbl
, ht
);
390 ASSERT_RHT_MUTEX(ht
);
392 RCU_INIT_POINTER(*pprev
, obj
->next
);
395 if (ht
->p
.shrink_decision
&&
396 ht
->p
.shrink_decision(ht
, tbl
->size
))
397 rhashtable_shrink(ht
, flags
);
399 EXPORT_SYMBOL_GPL(rhashtable_remove_pprev
);
402 * rhashtable_remove - remove object from hash table
404 * @obj: pointer to hash head inside object
405 * @flags: allocation flags (table expansion)
407 * Since the hash chain is single linked, the removal operation needs to
408 * walk the bucket chain upon removal. The removal operation is thus
409 * considerable slow if the hash table is not correctly sized.
411 * Will automatically shrink the table via rhashtable_expand() if the the
412 * shrink_decision function specified at rhashtable_init() returns true.
414 * The caller must ensure that no concurrent table mutations occur. It is
415 * however valid to have concurrent lookups if they are RCU protected.
417 bool rhashtable_remove(struct rhashtable
*ht
, struct rhash_head
*obj
,
420 struct bucket_table
*tbl
= rht_dereference(ht
->tbl
, ht
);
421 struct rhash_head __rcu
**pprev
;
422 struct rhash_head
*he
;
425 ASSERT_RHT_MUTEX(ht
);
427 h
= head_hashfn(ht
, obj
, tbl
->size
);
429 pprev
= &tbl
->buckets
[h
];
430 rht_for_each(he
, tbl
->buckets
[h
], ht
) {
436 rhashtable_remove_pprev(ht
, he
, pprev
, flags
);
442 EXPORT_SYMBOL_GPL(rhashtable_remove
);
445 * rhashtable_lookup - lookup key in hash table
447 * @key: pointer to key
449 * Computes the hash value for the key and traverses the bucket chain looking
450 * for a entry with an identical key. The first matching entry is returned.
452 * This lookup function may only be used for fixed key hash table (key_len
453 * paramter set). It will BUG() if used inappropriately.
455 * Lookups may occur in parallel with hash mutations as long as the lookup is
456 * guarded by rcu_read_lock(). The caller must take care of this.
458 void *rhashtable_lookup(const struct rhashtable
*ht
, const void *key
)
460 const struct bucket_table
*tbl
= rht_dereference_rcu(ht
->tbl
, ht
);
461 struct rhash_head
*he
;
464 BUG_ON(!ht
->p
.key_len
);
466 h
= __hashfn(ht
, key
, ht
->p
.key_len
, tbl
->size
);
467 rht_for_each_rcu(he
, tbl
->buckets
[h
], ht
) {
468 if (memcmp(rht_obj(ht
, he
) + ht
->p
.key_offset
, key
,
471 return (void *) he
- ht
->p
.head_offset
;
476 EXPORT_SYMBOL_GPL(rhashtable_lookup
);
479 * rhashtable_lookup_compare - search hash table with compare function
481 * @key: pointer to key
482 * @compare: compare function, must return true on match
483 * @arg: argument passed on to compare function
485 * Traverses the bucket chain behind the provided hash value and calls the
486 * specified compare function for each entry.
488 * Lookups may occur in parallel with hash mutations as long as the lookup is
489 * guarded by rcu_read_lock(). The caller must take care of this.
491 * Returns the first entry on which the compare function returned true.
493 void *rhashtable_lookup_compare(const struct rhashtable
*ht
, void *key
,
494 bool (*compare
)(void *, void *), void *arg
)
496 const struct bucket_table
*tbl
= rht_dereference_rcu(ht
->tbl
, ht
);
497 struct rhash_head
*he
;
500 hash
= __hashfn(ht
, key
, ht
->p
.key_len
, tbl
->size
);
502 rht_for_each_rcu(he
, tbl
->buckets
[hash
], ht
) {
503 if (!compare(rht_obj(ht
, he
), arg
))
505 return (void *) he
- ht
->p
.head_offset
;
510 EXPORT_SYMBOL_GPL(rhashtable_lookup_compare
);
512 static size_t rounded_hashtable_size(struct rhashtable_params
*params
)
514 return max(roundup_pow_of_two(params
->nelem_hint
* 4 / 3),
515 1UL << params
->min_shift
);
519 * rhashtable_init - initialize a new hash table
520 * @ht: hash table to be initialized
521 * @params: configuration parameters
523 * Initializes a new hash table based on the provided configuration
524 * parameters. A table can be configured either with a variable or
527 * Configuration Example 1: Fixed length keys
531 * struct rhash_head node;
534 * struct rhashtable_params params = {
535 * .head_offset = offsetof(struct test_obj, node),
536 * .key_offset = offsetof(struct test_obj, key),
537 * .key_len = sizeof(int),
538 * .hashfn = arch_fast_hash,
539 * .mutex_is_held = &my_mutex_is_held,
542 * Configuration Example 2: Variable length keys
545 * struct rhash_head node;
548 * u32 my_hash_fn(const void *data, u32 seed)
550 * struct test_obj *obj = data;
552 * return [... hash ...];
555 * struct rhashtable_params params = {
556 * .head_offset = offsetof(struct test_obj, node),
557 * .hashfn = arch_fast_hash,
558 * .obj_hashfn = my_hash_fn,
559 * .mutex_is_held = &my_mutex_is_held,
562 int rhashtable_init(struct rhashtable
*ht
, struct rhashtable_params
*params
)
564 struct bucket_table
*tbl
;
567 size
= HASH_DEFAULT_SIZE
;
569 if ((params
->key_len
&& !params
->hashfn
) ||
570 (!params
->key_len
&& !params
->obj_hashfn
))
573 params
->min_shift
= max_t(size_t, params
->min_shift
,
574 ilog2(HASH_MIN_SIZE
));
576 if (params
->nelem_hint
)
577 size
= rounded_hashtable_size(params
);
579 tbl
= bucket_table_alloc(size
, GFP_KERNEL
);
583 memset(ht
, 0, sizeof(*ht
));
584 ht
->shift
= ilog2(tbl
->size
);
585 memcpy(&ht
->p
, params
, sizeof(*params
));
586 RCU_INIT_POINTER(ht
->tbl
, tbl
);
589 get_random_bytes(&ht
->p
.hash_rnd
, sizeof(ht
->p
.hash_rnd
));
593 EXPORT_SYMBOL_GPL(rhashtable_init
);
596 * rhashtable_destroy - destroy hash table
597 * @ht: the hash table to destroy
599 * Frees the bucket array. This function is not rcu safe, therefore the caller
600 * has to make sure that no resizing may happen by unpublishing the hashtable
601 * and waiting for the quiescent cycle before releasing the bucket array.
603 void rhashtable_destroy(const struct rhashtable
*ht
)
605 bucket_table_free(ht
->tbl
);
607 EXPORT_SYMBOL_GPL(rhashtable_destroy
);
609 /**************************************************************************
611 **************************************************************************/
613 #ifdef CONFIG_TEST_RHASHTABLE
615 #define TEST_HT_SIZE 8
616 #define TEST_ENTRIES 2048
617 #define TEST_PTR ((void *) 0xdeadbeef)
618 #define TEST_NEXPANDS 4
620 static int test_mutex_is_held(void)
628 struct rhash_head node
;
631 static int __init
test_rht_lookup(struct rhashtable
*ht
)
635 for (i
= 0; i
< TEST_ENTRIES
* 2; i
++) {
636 struct test_obj
*obj
;
637 bool expected
= !(i
% 2);
640 obj
= rhashtable_lookup(ht
, &key
);
642 if (expected
&& !obj
) {
643 pr_warn("Test failed: Could not find key %u\n", key
);
645 } else if (!expected
&& obj
) {
646 pr_warn("Test failed: Unexpected entry found for key %u\n",
649 } else if (expected
&& obj
) {
650 if (obj
->ptr
!= TEST_PTR
|| obj
->value
!= i
) {
651 pr_warn("Test failed: Lookup value mismatch %p!=%p, %u!=%u\n",
652 obj
->ptr
, TEST_PTR
, obj
->value
, i
);
661 static void test_bucket_stats(struct rhashtable
*ht
,
662 struct bucket_table
*tbl
,
665 unsigned int cnt
, i
, total
= 0;
666 struct test_obj
*obj
;
668 for (i
= 0; i
< tbl
->size
; i
++) {
672 pr_info(" [%#4x/%zu]", i
, tbl
->size
);
674 rht_for_each_entry_rcu(obj
, tbl
->buckets
[i
], node
) {
678 pr_cont(" [%p],", obj
);
682 pr_cont("\n [%#x] first element: %p, chain length: %u\n",
683 i
, tbl
->buckets
[i
], cnt
);
686 pr_info(" Traversal complete: counted=%u, nelems=%zu, entries=%d\n",
687 total
, ht
->nelems
, TEST_ENTRIES
);
690 static int __init
test_rhashtable(struct rhashtable
*ht
)
692 struct bucket_table
*tbl
;
693 struct test_obj
*obj
, *next
;
699 * Insert TEST_ENTRIES into table with all keys even numbers
701 pr_info(" Adding %d keys\n", TEST_ENTRIES
);
702 for (i
= 0; i
< TEST_ENTRIES
; i
++) {
703 struct test_obj
*obj
;
705 obj
= kzalloc(sizeof(*obj
), GFP_KERNEL
);
714 rhashtable_insert(ht
, &obj
->node
, GFP_KERNEL
);
718 tbl
= rht_dereference_rcu(ht
->tbl
, ht
);
719 test_bucket_stats(ht
, tbl
, true);
723 for (i
= 0; i
< TEST_NEXPANDS
; i
++) {
724 pr_info(" Table expansion iteration %u...\n", i
);
725 rhashtable_expand(ht
, GFP_KERNEL
);
728 pr_info(" Verifying lookups...\n");
733 for (i
= 0; i
< TEST_NEXPANDS
; i
++) {
734 pr_info(" Table shrinkage iteration %u...\n", i
);
735 rhashtable_shrink(ht
, GFP_KERNEL
);
738 pr_info(" Verifying lookups...\n");
743 pr_info(" Deleting %d keys\n", TEST_ENTRIES
);
744 for (i
= 0; i
< TEST_ENTRIES
; i
++) {
747 obj
= rhashtable_lookup(ht
, &key
);
750 rhashtable_remove(ht
, &obj
->node
, GFP_KERNEL
);
757 tbl
= rht_dereference_rcu(ht
->tbl
, ht
);
758 for (i
= 0; i
< tbl
->size
; i
++)
759 rht_for_each_entry_safe(obj
, next
, tbl
->buckets
[i
], ht
, node
)
765 static int __init
test_rht_init(void)
767 struct rhashtable ht
;
768 struct rhashtable_params params
= {
769 .nelem_hint
= TEST_HT_SIZE
,
770 .head_offset
= offsetof(struct test_obj
, node
),
771 .key_offset
= offsetof(struct test_obj
, value
),
772 .key_len
= sizeof(int),
773 .hashfn
= arch_fast_hash
,
774 .mutex_is_held
= &test_mutex_is_held
,
775 .grow_decision
= rht_grow_above_75
,
776 .shrink_decision
= rht_shrink_below_30
,
780 pr_info("Running resizable hashtable tests...\n");
782 err
= rhashtable_init(&ht
, ¶ms
);
784 pr_warn("Test failed: Unable to initialize hashtable: %d\n",
789 err
= test_rhashtable(&ht
);
791 rhashtable_destroy(&ht
);
796 subsys_initcall(test_rht_init
);
798 #endif /* CONFIG_TEST_RHASHTABLE */