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/jhash.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(ht
->p
.parent
);
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 u32
rhashtable_hashfn(const struct rhashtable
*ht
, const void *key
, u32 len
)
67 struct bucket_table
*tbl
= rht_dereference_rcu(ht
->tbl
, ht
);
69 return __hashfn(ht
, key
, len
, tbl
->size
);
71 EXPORT_SYMBOL_GPL(rhashtable_hashfn
);
73 static u32
obj_hashfn(const struct rhashtable
*ht
, const void *ptr
, u32 hsize
)
75 if (unlikely(!ht
->p
.key_len
)) {
78 h
= ht
->p
.obj_hashfn(ptr
, ht
->p
.hash_rnd
);
80 return h
& (hsize
- 1);
83 return __hashfn(ht
, ptr
+ ht
->p
.key_offset
, ht
->p
.key_len
, hsize
);
87 * rhashtable_obj_hashfn - compute hash for hashed object
88 * @ht: hash table to compute for
89 * @ptr: pointer to hashed object
91 * Computes the hash value using the hash function `hashfn` respectively
92 * 'obj_hashfn' depending on whether the hash table is set up to work with
93 * a fixed length key. The returned value is guaranteed to be smaller than
94 * the number of buckets in the hash table.
96 u32
rhashtable_obj_hashfn(const struct rhashtable
*ht
, void *ptr
)
98 struct bucket_table
*tbl
= rht_dereference_rcu(ht
->tbl
, ht
);
100 return obj_hashfn(ht
, ptr
, tbl
->size
);
102 EXPORT_SYMBOL_GPL(rhashtable_obj_hashfn
);
104 static u32
head_hashfn(const struct rhashtable
*ht
,
105 const struct rhash_head
*he
, u32 hsize
)
107 return obj_hashfn(ht
, rht_obj(ht
, he
), hsize
);
110 static struct bucket_table
*bucket_table_alloc(size_t nbuckets
)
112 struct bucket_table
*tbl
;
115 size
= sizeof(*tbl
) + nbuckets
* sizeof(tbl
->buckets
[0]);
116 tbl
= kzalloc(size
, GFP_KERNEL
| __GFP_NOWARN
);
123 tbl
->size
= nbuckets
;
128 static void bucket_table_free(const struct bucket_table
*tbl
)
134 * rht_grow_above_75 - returns true if nelems > 0.75 * table-size
136 * @new_size: new table size
138 bool rht_grow_above_75(const struct rhashtable
*ht
, size_t new_size
)
140 /* Expand table when exceeding 75% load */
141 return ht
->nelems
> (new_size
/ 4 * 3);
143 EXPORT_SYMBOL_GPL(rht_grow_above_75
);
146 * rht_shrink_below_30 - returns true if nelems < 0.3 * table-size
148 * @new_size: new table size
150 bool rht_shrink_below_30(const struct rhashtable
*ht
, size_t new_size
)
152 /* Shrink table beneath 30% load */
153 return ht
->nelems
< (new_size
* 3 / 10);
155 EXPORT_SYMBOL_GPL(rht_shrink_below_30
);
157 static void hashtable_chain_unzip(const struct rhashtable
*ht
,
158 const struct bucket_table
*new_tbl
,
159 struct bucket_table
*old_tbl
, size_t n
)
161 struct rhash_head
*he
, *p
, *next
;
164 /* Old bucket empty, no work needed. */
165 p
= rht_dereference(old_tbl
->buckets
[n
], ht
);
169 /* Advance the old bucket pointer one or more times until it
170 * reaches a node that doesn't hash to the same bucket as the
171 * previous node p. Call the previous node p;
173 h
= head_hashfn(ht
, p
, new_tbl
->size
);
174 rht_for_each(he
, p
->next
, ht
) {
175 if (head_hashfn(ht
, he
, new_tbl
->size
) != h
)
179 RCU_INIT_POINTER(old_tbl
->buckets
[n
], p
->next
);
181 /* Find the subsequent node which does hash to the same
182 * bucket as node P, or NULL if no such node exists.
186 rht_for_each(he
, he
->next
, ht
) {
187 if (head_hashfn(ht
, he
, new_tbl
->size
) == h
) {
194 /* Set p's next pointer to that subsequent node pointer,
195 * bypassing the nodes which do not hash to p's bucket
197 RCU_INIT_POINTER(p
->next
, next
);
201 * rhashtable_expand - Expand hash table while allowing concurrent lookups
202 * @ht: the hash table to expand
204 * A secondary bucket array is allocated and the hash entries are migrated
205 * while keeping them on both lists until the end of the RCU grace period.
207 * This function may only be called in a context where it is safe to call
208 * synchronize_rcu(), e.g. not within a rcu_read_lock() section.
210 * The caller must ensure that no concurrent table mutations take place.
211 * It is however valid to have concurrent lookups if they are RCU protected.
213 int rhashtable_expand(struct rhashtable
*ht
)
215 struct bucket_table
*new_tbl
, *old_tbl
= rht_dereference(ht
->tbl
, ht
);
216 struct rhash_head
*he
;
220 ASSERT_RHT_MUTEX(ht
);
222 if (ht
->p
.max_shift
&& ht
->shift
>= ht
->p
.max_shift
)
225 new_tbl
= bucket_table_alloc(old_tbl
->size
* 2);
231 /* For each new bucket, search the corresponding old bucket
232 * for the first entry that hashes to the new bucket, and
233 * link the new bucket to that entry. Since all the entries
234 * which will end up in the new bucket appear in the same
235 * old bucket, this constructs an entirely valid new hash
236 * table, but with multiple buckets "zipped" together into a
237 * single imprecise chain.
239 for (i
= 0; i
< new_tbl
->size
; i
++) {
240 h
= i
& (old_tbl
->size
- 1);
241 rht_for_each(he
, old_tbl
->buckets
[h
], ht
) {
242 if (head_hashfn(ht
, he
, new_tbl
->size
) == i
) {
243 RCU_INIT_POINTER(new_tbl
->buckets
[i
], he
);
249 /* Publish the new table pointer. Lookups may now traverse
250 * the new table, but they will not benefit from any
251 * additional efficiency until later steps unzip the buckets.
253 rcu_assign_pointer(ht
->tbl
, new_tbl
);
255 /* Unzip interleaved hash chains */
257 /* Wait for readers. All new readers will see the new
258 * table, and thus no references to the old table will
263 /* For each bucket in the old table (each of which
264 * contains items from multiple buckets of the new
268 for (i
= 0; i
< old_tbl
->size
; i
++) {
269 hashtable_chain_unzip(ht
, new_tbl
, old_tbl
, i
);
270 if (old_tbl
->buckets
[i
] != NULL
)
275 bucket_table_free(old_tbl
);
278 EXPORT_SYMBOL_GPL(rhashtable_expand
);
281 * rhashtable_shrink - Shrink hash table while allowing concurrent lookups
282 * @ht: the hash table to shrink
284 * This function may only be called in a context where it is safe to call
285 * synchronize_rcu(), e.g. not within a rcu_read_lock() section.
287 * The caller must ensure that no concurrent table mutations take place.
288 * It is however valid to have concurrent lookups if they are RCU protected.
290 int rhashtable_shrink(struct rhashtable
*ht
)
292 struct bucket_table
*ntbl
, *tbl
= rht_dereference(ht
->tbl
, ht
);
293 struct rhash_head __rcu
**pprev
;
296 ASSERT_RHT_MUTEX(ht
);
298 if (ht
->shift
<= ht
->p
.min_shift
)
301 ntbl
= bucket_table_alloc(tbl
->size
/ 2);
307 /* Link each bucket in the new table to the first bucket
308 * in the old table that contains entries which will hash
311 for (i
= 0; i
< ntbl
->size
; i
++) {
312 ntbl
->buckets
[i
] = tbl
->buckets
[i
];
314 /* Link each bucket in the new table to the first bucket
315 * in the old table that contains entries which will hash
318 for (pprev
= &ntbl
->buckets
[i
]; *pprev
!= NULL
;
319 pprev
= &rht_dereference(*pprev
, ht
)->next
)
321 RCU_INIT_POINTER(*pprev
, tbl
->buckets
[i
+ ntbl
->size
]);
324 /* Publish the new, valid hash table */
325 rcu_assign_pointer(ht
->tbl
, ntbl
);
327 /* Wait for readers. No new readers will have references to the
332 bucket_table_free(tbl
);
336 EXPORT_SYMBOL_GPL(rhashtable_shrink
);
339 * rhashtable_insert - insert object into hash hash table
341 * @obj: pointer to hash head inside object
343 * Will automatically grow the table via rhashtable_expand() if the the
344 * grow_decision function specified at rhashtable_init() returns true.
346 * The caller must ensure that no concurrent table mutations occur. It is
347 * however valid to have concurrent lookups if they are RCU protected.
349 void rhashtable_insert(struct rhashtable
*ht
, struct rhash_head
*obj
)
351 struct bucket_table
*tbl
= rht_dereference(ht
->tbl
, ht
);
354 ASSERT_RHT_MUTEX(ht
);
356 hash
= head_hashfn(ht
, obj
, tbl
->size
);
357 RCU_INIT_POINTER(obj
->next
, tbl
->buckets
[hash
]);
358 rcu_assign_pointer(tbl
->buckets
[hash
], obj
);
361 if (ht
->p
.grow_decision
&& ht
->p
.grow_decision(ht
, tbl
->size
))
362 rhashtable_expand(ht
);
364 EXPORT_SYMBOL_GPL(rhashtable_insert
);
367 * rhashtable_remove_pprev - remove object from hash table given previous element
369 * @obj: pointer to hash head inside object
370 * @pprev: pointer to previous element
372 * Identical to rhashtable_remove() but caller is alreayd aware of the element
373 * in front of the element to be deleted. This is in particular useful for
374 * deletion when combined with walking or lookup.
376 void rhashtable_remove_pprev(struct rhashtable
*ht
, struct rhash_head
*obj
,
377 struct rhash_head __rcu
**pprev
)
379 struct bucket_table
*tbl
= rht_dereference(ht
->tbl
, ht
);
381 ASSERT_RHT_MUTEX(ht
);
383 RCU_INIT_POINTER(*pprev
, obj
->next
);
386 if (ht
->p
.shrink_decision
&&
387 ht
->p
.shrink_decision(ht
, tbl
->size
))
388 rhashtable_shrink(ht
);
390 EXPORT_SYMBOL_GPL(rhashtable_remove_pprev
);
393 * rhashtable_remove - remove object from hash table
395 * @obj: pointer to hash head inside object
397 * Since the hash chain is single linked, the removal operation needs to
398 * walk the bucket chain upon removal. The removal operation is thus
399 * considerable slow if the hash table is not correctly sized.
401 * Will automatically shrink the table via rhashtable_expand() if the the
402 * shrink_decision function specified at rhashtable_init() returns true.
404 * The caller must ensure that no concurrent table mutations occur. It is
405 * however valid to have concurrent lookups if they are RCU protected.
407 bool rhashtable_remove(struct rhashtable
*ht
, struct rhash_head
*obj
)
409 struct bucket_table
*tbl
= rht_dereference(ht
->tbl
, ht
);
410 struct rhash_head __rcu
**pprev
;
411 struct rhash_head
*he
;
414 ASSERT_RHT_MUTEX(ht
);
416 h
= head_hashfn(ht
, obj
, tbl
->size
);
418 pprev
= &tbl
->buckets
[h
];
419 rht_for_each(he
, tbl
->buckets
[h
], ht
) {
425 rhashtable_remove_pprev(ht
, he
, pprev
);
431 EXPORT_SYMBOL_GPL(rhashtable_remove
);
434 * rhashtable_lookup - lookup key in hash table
436 * @key: pointer to key
438 * Computes the hash value for the key and traverses the bucket chain looking
439 * for a entry with an identical key. The first matching entry is returned.
441 * This lookup function may only be used for fixed key hash table (key_len
442 * paramter set). It will BUG() if used inappropriately.
444 * Lookups may occur in parallel with hash mutations as long as the lookup is
445 * guarded by rcu_read_lock(). The caller must take care of this.
447 void *rhashtable_lookup(const struct rhashtable
*ht
, const void *key
)
449 const struct bucket_table
*tbl
= rht_dereference_rcu(ht
->tbl
, ht
);
450 struct rhash_head
*he
;
453 BUG_ON(!ht
->p
.key_len
);
455 h
= __hashfn(ht
, key
, ht
->p
.key_len
, tbl
->size
);
456 rht_for_each_rcu(he
, tbl
->buckets
[h
], ht
) {
457 if (memcmp(rht_obj(ht
, he
) + ht
->p
.key_offset
, key
,
460 return (void *) he
- ht
->p
.head_offset
;
465 EXPORT_SYMBOL_GPL(rhashtable_lookup
);
468 * rhashtable_lookup_compare - search hash table with compare function
470 * @hash: hash value of desired entry
471 * @compare: compare function, must return true on match
472 * @arg: argument passed on to compare function
474 * Traverses the bucket chain behind the provided hash value and calls the
475 * specified compare function for each entry.
477 * Lookups may occur in parallel with hash mutations as long as the lookup is
478 * guarded by rcu_read_lock(). The caller must take care of this.
480 * Returns the first entry on which the compare function returned true.
482 void *rhashtable_lookup_compare(const struct rhashtable
*ht
, u32 hash
,
483 bool (*compare
)(void *, void *), void *arg
)
485 const struct bucket_table
*tbl
= rht_dereference_rcu(ht
->tbl
, ht
);
486 struct rhash_head
*he
;
488 if (unlikely(hash
>= tbl
->size
))
491 rht_for_each_rcu(he
, tbl
->buckets
[hash
], ht
) {
492 if (!compare(rht_obj(ht
, he
), arg
))
494 return (void *) he
- ht
->p
.head_offset
;
499 EXPORT_SYMBOL_GPL(rhashtable_lookup_compare
);
501 static size_t rounded_hashtable_size(struct rhashtable_params
*params
)
503 return max(roundup_pow_of_two(params
->nelem_hint
* 4 / 3),
504 1UL << params
->min_shift
);
508 * rhashtable_init - initialize a new hash table
509 * @ht: hash table to be initialized
510 * @params: configuration parameters
512 * Initializes a new hash table based on the provided configuration
513 * parameters. A table can be configured either with a variable or
516 * Configuration Example 1: Fixed length keys
520 * struct rhash_head node;
523 * struct rhashtable_params params = {
524 * .head_offset = offsetof(struct test_obj, node),
525 * .key_offset = offsetof(struct test_obj, key),
526 * .key_len = sizeof(int),
528 * #ifdef CONFIG_PROVE_LOCKING
529 * .mutex_is_held = &my_mutex_is_held,
533 * Configuration Example 2: Variable length keys
536 * struct rhash_head node;
539 * u32 my_hash_fn(const void *data, u32 seed)
541 * struct test_obj *obj = data;
543 * return [... hash ...];
546 * struct rhashtable_params params = {
547 * .head_offset = offsetof(struct test_obj, node),
549 * .obj_hashfn = my_hash_fn,
550 * #ifdef CONFIG_PROVE_LOCKING
551 * .mutex_is_held = &my_mutex_is_held,
555 int rhashtable_init(struct rhashtable
*ht
, struct rhashtable_params
*params
)
557 struct bucket_table
*tbl
;
560 size
= HASH_DEFAULT_SIZE
;
562 if ((params
->key_len
&& !params
->hashfn
) ||
563 (!params
->key_len
&& !params
->obj_hashfn
))
566 params
->min_shift
= max_t(size_t, params
->min_shift
,
567 ilog2(HASH_MIN_SIZE
));
569 if (params
->nelem_hint
)
570 size
= rounded_hashtable_size(params
);
572 tbl
= bucket_table_alloc(size
);
576 memset(ht
, 0, sizeof(*ht
));
577 ht
->shift
= ilog2(tbl
->size
);
578 memcpy(&ht
->p
, params
, sizeof(*params
));
579 RCU_INIT_POINTER(ht
->tbl
, tbl
);
582 get_random_bytes(&ht
->p
.hash_rnd
, sizeof(ht
->p
.hash_rnd
));
586 EXPORT_SYMBOL_GPL(rhashtable_init
);
589 * rhashtable_destroy - destroy hash table
590 * @ht: the hash table to destroy
592 * Frees the bucket array. This function is not rcu safe, therefore the caller
593 * has to make sure that no resizing may happen by unpublishing the hashtable
594 * and waiting for the quiescent cycle before releasing the bucket array.
596 void rhashtable_destroy(const struct rhashtable
*ht
)
598 bucket_table_free(ht
->tbl
);
600 EXPORT_SYMBOL_GPL(rhashtable_destroy
);
602 /**************************************************************************
604 **************************************************************************/
606 #ifdef CONFIG_TEST_RHASHTABLE
608 #define TEST_HT_SIZE 8
609 #define TEST_ENTRIES 2048
610 #define TEST_PTR ((void *) 0xdeadbeef)
611 #define TEST_NEXPANDS 4
613 #ifdef CONFIG_PROVE_LOCKING
614 static int test_mutex_is_held(void *parent
)
623 struct rhash_head node
;
626 static int __init
test_rht_lookup(struct rhashtable
*ht
)
630 for (i
= 0; i
< TEST_ENTRIES
* 2; i
++) {
631 struct test_obj
*obj
;
632 bool expected
= !(i
% 2);
635 obj
= rhashtable_lookup(ht
, &key
);
637 if (expected
&& !obj
) {
638 pr_warn("Test failed: Could not find key %u\n", key
);
640 } else if (!expected
&& obj
) {
641 pr_warn("Test failed: Unexpected entry found for key %u\n",
644 } else if (expected
&& obj
) {
645 if (obj
->ptr
!= TEST_PTR
|| obj
->value
!= i
) {
646 pr_warn("Test failed: Lookup value mismatch %p!=%p, %u!=%u\n",
647 obj
->ptr
, TEST_PTR
, obj
->value
, i
);
656 static void test_bucket_stats(struct rhashtable
*ht
, bool quiet
)
658 unsigned int cnt
, rcu_cnt
, i
, total
= 0;
659 struct test_obj
*obj
;
660 struct bucket_table
*tbl
;
662 tbl
= rht_dereference_rcu(ht
->tbl
, ht
);
663 for (i
= 0; i
< tbl
->size
; i
++) {
667 pr_info(" [%#4x/%zu]", i
, tbl
->size
);
669 rht_for_each_entry_rcu(obj
, tbl
->buckets
[i
], node
) {
673 pr_cont(" [%p],", obj
);
676 rht_for_each_entry_rcu(obj
, tbl
->buckets
[i
], node
)
680 pr_warn("Test failed: Chain count mismach %d != %d",
684 pr_cont("\n [%#x] first element: %p, chain length: %u\n",
685 i
, tbl
->buckets
[i
], cnt
);
688 pr_info(" Traversal complete: counted=%u, nelems=%zu, entries=%d\n",
689 total
, ht
->nelems
, TEST_ENTRIES
);
691 if (total
!= ht
->nelems
|| total
!= TEST_ENTRIES
)
692 pr_warn("Test failed: Total count mismatch ^^^");
695 static int __init
test_rhashtable(struct rhashtable
*ht
)
697 struct bucket_table
*tbl
;
698 struct test_obj
*obj
, *next
;
704 * Insert TEST_ENTRIES into table with all keys even numbers
706 pr_info(" Adding %d keys\n", TEST_ENTRIES
);
707 for (i
= 0; i
< TEST_ENTRIES
; i
++) {
708 struct test_obj
*obj
;
710 obj
= kzalloc(sizeof(*obj
), GFP_KERNEL
);
719 rhashtable_insert(ht
, &obj
->node
);
723 test_bucket_stats(ht
, true);
727 for (i
= 0; i
< TEST_NEXPANDS
; i
++) {
728 pr_info(" Table expansion iteration %u...\n", i
);
729 rhashtable_expand(ht
);
732 pr_info(" Verifying lookups...\n");
737 for (i
= 0; i
< TEST_NEXPANDS
; i
++) {
738 pr_info(" Table shrinkage iteration %u...\n", i
);
739 rhashtable_shrink(ht
);
742 pr_info(" Verifying lookups...\n");
748 test_bucket_stats(ht
, true);
751 pr_info(" Deleting %d keys\n", TEST_ENTRIES
);
752 for (i
= 0; i
< TEST_ENTRIES
; i
++) {
755 obj
= rhashtable_lookup(ht
, &key
);
758 rhashtable_remove(ht
, &obj
->node
);
765 tbl
= rht_dereference_rcu(ht
->tbl
, ht
);
766 for (i
= 0; i
< tbl
->size
; i
++)
767 rht_for_each_entry_safe(obj
, next
, tbl
->buckets
[i
], ht
, node
)
773 static int __init
test_rht_init(void)
775 struct rhashtable ht
;
776 struct rhashtable_params params
= {
777 .nelem_hint
= TEST_HT_SIZE
,
778 .head_offset
= offsetof(struct test_obj
, node
),
779 .key_offset
= offsetof(struct test_obj
, value
),
780 .key_len
= sizeof(int),
782 #ifdef CONFIG_PROVE_LOCKING
783 .mutex_is_held
= &test_mutex_is_held
,
785 .grow_decision
= rht_grow_above_75
,
786 .shrink_decision
= rht_shrink_below_30
,
790 pr_info("Running resizable hashtable tests...\n");
792 err
= rhashtable_init(&ht
, ¶ms
);
794 pr_warn("Test failed: Unable to initialize hashtable: %d\n",
799 err
= test_rhashtable(&ht
);
801 rhashtable_destroy(&ht
);
806 subsys_initcall(test_rht_init
);
808 #endif /* CONFIG_TEST_RHASHTABLE */